• codegeex2-6b-int4 部署


            codegeex2-6b-int4                模型文件

            CodeGeeX2                          仓库文件地址

            CodeGeeX2                          推理教程

            

    conda create -n codegeex2 python=3.10 -y

    conda activate codegeex2

    pip install -r requirements.txt -i https://pypi.mirrors.ustc.edu.cn/simple 

    启动 Gradio DEMO:

    python ./demo/run_demo.py

    启动FAST API:

    python ./demo/fastapicpu.py

    报错

    AttributeError: 'ChatGLMTokenizer' object has no attribute 'tokenizer'. Did you mean: 'tokenize'?

    解决方法:

    用以下代码替换掉tokenization_chatglm.py里面内容

    1. import os
    2. import torch
    3. from typing import List, Optional, Union, Dict
    4. from sentencepiece import SentencePieceProcessor
    5. from transformers import PreTrainedTokenizer
    6. from transformers.utils import logging, PaddingStrategy
    7. from transformers.tokenization_utils_base import EncodedInput, BatchEncoding
    8. class SPTokenizer:
    9. def __init__(self, model_path: str):
    10. # reload tokenizer
    11. assert os.path.isfile(model_path), model_path
    12. self.sp_model = SentencePieceProcessor(model_file=model_path)
    13. # BOS / EOS token IDs
    14. self.n_words: int = self.sp_model.vocab_size()
    15. self.bos_id: int = self.sp_model.bos_id()
    16. self.eos_id: int = self.sp_model.eos_id()
    17. self.pad_id: int = self.sp_model.unk_id()
    18. assert self.sp_model.vocab_size() == self.sp_model.get_piece_size()
    19. special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "sop", "eop"]
    20. self.special_tokens = {}
    21. self.index_special_tokens = {}
    22. for token in special_tokens:
    23. self.special_tokens[token] = self.n_words
    24. self.index_special_tokens[self.n_words] = token
    25. self.n_words += 1
    26. def tokenize(self, s: str):
    27. return self.sp_model.EncodeAsPieces(s)
    28. def encode(self, s: str, bos: bool = False, eos: bool = False) -> List[int]:
    29. assert type(s) is str
    30. t = self.sp_model.encode(s)
    31. if bos:
    32. t = [self.bos_id] + t
    33. if eos:
    34. t = t + [self.eos_id]
    35. return t
    36. def decode(self, t: List[int]) -> str:
    37. return self.sp_model.decode(t)
    38. def decode_tokens(self, tokens: List[str]) -> str:
    39. text = self.sp_model.DecodePieces(tokens)
    40. return text
    41. def convert_token_to_id(self, token):
    42. """ Converts a token (str) in an id using the vocab. """
    43. if token in self.special_tokens:
    44. return self.special_tokens[token]
    45. return self.sp_model.PieceToId(token)
    46. def convert_id_to_token(self, index):
    47. """Converts an index (integer) in a token (str) using the vocab."""
    48. if index in self.index_special_tokens or index in [self.eos_id, self.bos_id, self.pad_id] or index < 0:
    49. return ""
    50. return self.sp_model.IdToPiece(index)
    51. class ChatGLMTokenizer(PreTrainedTokenizer):
    52. vocab_files_names = {"vocab_file": "tokenizer.model"}
    53. model_input_names = ["input_ids", "attention_mask", "position_ids"]
    54. def __init__(self, vocab_file, padding_side="left", clean_up_tokenization_spaces=False, **kwargs):
    55. self.name = "GLMTokenizer"
    56. self.vocab_file = vocab_file
    57. self.tokenizer = SPTokenizer(vocab_file)
    58. self.special_tokens = {
    59. "": self.tokenizer.bos_id,
    60. "": self.tokenizer.eos_id,
    61. "": self.tokenizer.pad_id
    62. }
    63. super().__init__(padding_side=padding_side, clean_up_tokenization_spaces=clean_up_tokenization_spaces, **kwargs)
    64. def get_command(self, token):
    65. if token in self.special_tokens:
    66. return self.special_tokens[token]
    67. assert token in self.tokenizer.special_tokens, f"{token} is not a special token for {self.name}"
    68. return self.tokenizer.special_tokens[token]
    69. @property
    70. def unk_token(self) -> str:
    71. return ""
    72. @property
    73. def pad_token(self) -> str:
    74. return ""
    75. @property
    76. def pad_token_id(self):
    77. return self.get_command("")
    78. @property
    79. def eos_token(self) -> str:
    80. return ""
    81. @property
    82. def eos_token_id(self):
    83. return self.get_command("")
    84. @property
    85. def vocab_size(self):
    86. return self.tokenizer.n_words
    87. def get_vocab(self):
    88. """ Returns vocab as a dict """
    89. vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
    90. vocab.update(self.added_tokens_encoder)
    91. return vocab
    92. def _tokenize(self, text, **kwargs):
    93. return self.tokenizer.tokenize(text)
    94. def _convert_token_to_id(self, token):
    95. """ Converts a token (str) in an id using the vocab. """
    96. return self.tokenizer.convert_token_to_id(token)
    97. def _convert_id_to_token(self, index):
    98. """Converts an index (integer) in a token (str) using the vocab."""
    99. return self.tokenizer.convert_id_to_token(index)
    100. def convert_tokens_to_string(self, tokens: List[str]) -> str:
    101. return self.tokenizer.decode_tokens(tokens)
    102. def save_vocabulary(self, save_directory, filename_prefix=None):
    103. """
    104. Save the vocabulary and special tokens file to a directory.
    105. Args:
    106. save_directory (`str`):
    107. The directory in which to save the vocabulary.
    108. filename_prefix (`str`, *optional*):
    109. An optional prefix to add to the named of the saved files.
    110. Returns:
    111. `Tuple(str)`: Paths to the files saved.
    112. """
    113. if os.path.isdir(save_directory):
    114. vocab_file = os.path.join(
    115. save_directory, self.vocab_files_names["vocab_file"]
    116. )
    117. else:
    118. vocab_file = save_directory
    119. with open(self.vocab_file, 'rb') as fin:
    120. proto_str = fin.read()
    121. with open(vocab_file, "wb") as writer:
    122. writer.write(proto_str)
    123. return (vocab_file,)
    124. def get_prefix_tokens(self):
    125. prefix_tokens = [self.get_command("[gMASK]"), self.get_command("sop")]
    126. return prefix_tokens
    127. def build_prompt(self, query, history=None):
    128. if history is None:
    129. history = []
    130. prompt = ""
    131. for i, (old_query, response) in enumerate(history):
    132. prompt += "[Round {}]\n\n问:{}\n\n答:{}\n\n".format(i + 1, old_query, response)
    133. prompt += "[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)
    134. return prompt
    135. def build_inputs_with_special_tokens(
    136. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
    137. ) -> List[int]:
    138. """
    139. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
    140. adding special tokens. A BERT sequence has the following format:
    141. - single sequence: `[CLS] X [SEP]`
    142. - pair of sequences: `[CLS] A [SEP] B [SEP]`
    143. Args:
    144. token_ids_0 (`List[int]`):
    145. List of IDs to which the special tokens will be added.
    146. token_ids_1 (`List[int]`, *optional*):
    147. Optional second list of IDs for sequence pairs.
    148. Returns:
    149. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
    150. """
    151. prefix_tokens = self.get_prefix_tokens()
    152. token_ids_0 = prefix_tokens + token_ids_0
    153. if token_ids_1 is not None:
    154. token_ids_0 = token_ids_0 + token_ids_1 + [self.get_command("")]
    155. return token_ids_0
    156. def _pad(
    157. self,
    158. encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
    159. max_length: Optional[int] = None,
    160. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
    161. pad_to_multiple_of: Optional[int] = None,
    162. return_attention_mask: Optional[bool] = None,
    163. ) -> dict:
    164. """
    165. Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
    166. Args:
    167. encoded_inputs:
    168. Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
    169. max_length: maximum length of the returned list and optionally padding length (see below).
    170. Will truncate by taking into account the special tokens.
    171. padding_strategy: PaddingStrategy to use for padding.
    172. - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
    173. - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
    174. - PaddingStrategy.DO_NOT_PAD: Do not pad
    175. The tokenizer padding sides are defined in self.padding_side:
    176. - 'left': pads on the left of the sequences
    177. - 'right': pads on the right of the sequences
    178. pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
    179. This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
    180. `>= 7.5` (Volta).
    181. return_attention_mask:
    182. (optional) Set to False to avoid returning attention mask (default: set to model specifics)
    183. """
    184. # Load from model defaults
    185. assert self.padding_side == "left"
    186. required_input = encoded_inputs[self.model_input_names[0]]
    187. seq_length = len(required_input)
    188. if padding_strategy == PaddingStrategy.LONGEST:
    189. max_length = len(required_input)
    190. if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
    191. max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
    192. needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
    193. # Initialize attention mask if not present.
    194. if "attention_mask" not in encoded_inputs:
    195. encoded_inputs["attention_mask"] = [1] * seq_length
    196. if "position_ids" not in encoded_inputs:
    197. encoded_inputs["position_ids"] = list(range(seq_length))
    198. if needs_to_be_padded:
    199. difference = max_length - len(required_input)
    200. if "attention_mask" in encoded_inputs:
    201. encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
    202. if "position_ids" in encoded_inputs:
    203. encoded_inputs["position_ids"] = [0] * difference + encoded_inputs["position_ids"]
    204. encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
    205. return encoded_inputs

    参考:【已解决】AttributeError: ‘ChatGLMTokenizer‘ object has no attribute ‘tokenizer‘_attributeerror: 'chatglmtokenizer' object has no a-CSDN博客

    ***

  • 相关阅读:
    云存储--七牛云--云存储域名绑定--微客外链--微信内置浏览器不支持下载APK(APP)软件的解决方法&&微信跳转浏览器API
    Spring更简单的使用方法
    【ffmpeg】音频重采样
    java SpringBoot登录验证token拦截器
    数据结构——哈希
    微信小程序 rpx 转 px
    yolo增加MPDIoU loss
    linux内核如何根据文件名索引到文件内容
    MobaXterm配置ssh端口转发(tensorboard使用)
    webpack 自定义loader与插件
  • 原文地址:https://blog.csdn.net/m0_60657960/article/details/139668935