zai-org/glm-4-9b
1447.6k
1import regex as re2import base643import os4import tiktoken5from typing import List, Optional, Union, Dict6from transformers import PreTrainedTokenizer7from transformers.utils import PaddingStrategy8from transformers.tokenization_utils_base import EncodedInput, BatchEncoding9 10 11class ChatGLM4Tokenizer(PreTrainedTokenizer):12 vocab_files_names = {"vocab_file": "tokenizer.model"}13 model_input_names = ["input_ids", "attention_mask", "position_ids"]14 15 def __init__(16 self,17 vocab_file,18 clean_up_tokenization_spaces=False,19 **kwargs20 ):21 self.name = "GLM4Tokenizer"22 self.vocab_file = vocab_file23 pat_str = "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"24 self.pat_str = re.compile(pat_str)25 26 mergeable_ranks = {}27 with open(vocab_file) as f:28 for line in f:29 token, rank = line.strip().split()30 rank = int(rank)31 token = base64.b64decode(token)32 mergeable_ranks[token] = rank33 34 self.mergeable_ranks = mergeable_ranks35 36 self.tokenizer = tiktoken.Encoding(37 name="my_tokenizer",38 pat_str=pat_str,39 mergeable_ranks=mergeable_ranks,40 special_tokens={}41 )42 self.decoder = {rank: token for token, rank in mergeable_ranks.items()}43 self.n_words = len(self.decoder)44 45 super().__init__(46 clean_up_tokenization_spaces=clean_up_tokenization_spaces,47 **kwargs48 )49 50 @property51 def vocab_size(self):52 return self.n_words53 54 def get_vocab(self):55 """ Returns vocab as a dict """56 vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}57 vocab.update(self.added_tokens_encoder)58 return vocab59 60 def convert_tokens_to_string(self, tokens: List[Union[bytes, str, int]]) -> str:61 """62 Converts a sequence of tokens in a single string.63 """64 text = ""65 temp = b""66 for t in tokens:67 if isinstance(t, int):68 t = chr(t)69 if isinstance(t, str):70 if temp:71 text += temp.decode("utf-8", errors="replace")72 elif isinstance(t, bytes):73 temp += t74 else:75 raise TypeError("token should only be of type int, bytes or str")76 if temp:77 text += temp.decode("utf-8", errors="replace")78 return text79 80 def _tokenize(self, text, **kwargs):81 tokens = []82 ids = self.tokenizer.encode(text)83 for t in ids:84 tokens.append(self.decoder[t])85 return tokens86 87 def _convert_token_to_id(self, token):88 """ Converts a token (str) in an id using the vocab. """89 return self.mergeable_ranks[token]90 91 def _convert_id_to_token(self, index):92 """Converts an index (integer) in a token (str) using the vocab."""93 return self.decoder.get(index, "")94 95 def save_vocabulary(self, save_directory, filename_prefix=None):96 """97 Save the vocabulary and special tokens file to a directory.98 99 Args:100 save_directory (`str`):101 The directory in which to save the vocabulary.102 filename_prefix (`str`, *optional*):103 An optional prefix to add to the named of the saved files.104 105 Returns:106 `Tuple(str)`: Paths to the files saved.107 """108 if os.path.isdir(save_directory):109 vocab_file = os.path.join(110 save_directory, self.vocab_files_names["vocab_file"]111 )112 else:113 vocab_file = save_directory114 115 with open(self.vocab_file, 'rb') as fin:116 proto_str = fin.read()117 118 with open(vocab_file, "wb") as writer:119 writer.write(proto_str)120 121 return (vocab_file,)122 123 def get_prefix_tokens(self):124 prefix_tokens = [self.convert_tokens_to_ids("[gMASK]"), self.convert_tokens_to_ids("<sop>")]125 return prefix_tokens126 127 def build_single_message(self, role, metadata, message, tokenize=True):128 assert role in ["system", "user", "assistant", "observation"], role129 if tokenize:130 role_tokens = [self.convert_tokens_to_ids(f"<|{role}|>")] + self.tokenizer.encode(f"{metadata}\n",131 disallowed_special=())132 message_tokens = self.tokenizer.encode(message, disallowed_special=())133 tokens = role_tokens + message_tokens134 return tokens135 else:136 return str(f"<|{role}|>{metadata}\n{message}")137 138 def build_inputs_with_special_tokens(139 self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None140 ) -> List[int]:141 """142 Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and143 adding special tokens. A BERT sequence has the following format:144 145 - single sequence: `[CLS] X [SEP]`146 - pair of sequences: `[CLS] A [SEP] B [SEP]`147 148 Args:149 token_ids_0 (`List[int]`):150 List of IDs to which the special tokens will be added.151 token_ids_1 (`List[int]`, *optional*):152 Optional second list of IDs for sequence pairs.153 154 Returns:155 `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.156 """157 prefix_tokens = self.get_prefix_tokens()158 token_ids_0 = prefix_tokens + token_ids_0159 if token_ids_1 is not None:160 token_ids_0 = token_ids_0 + token_ids_1 + [self.convert_tokens_to_ids("<eos>")]161 return token_ids_0162 163 def _pad(164 self,165 encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],166 max_length: Optional[int] = None,167 padding_side: str = "left",168 padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,169 pad_to_multiple_of: Optional[int] = None,170 return_attention_mask: Optional[bool] = None,171 ) -> dict:172 """173 Pad encoded inputs (on left/right and up to predefined length or max length in the batch)174 175 Args:176 encoded_inputs:177 Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).178 max_length: maximum length of the returned list and optionally padding length (see below).179 Will truncate by taking into account the special tokens.180 padding_strategy: PaddingStrategy to use for padding.181 182 - PaddingStrategy.LONGEST Pad to the longest sequence in the batch183 - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)184 - PaddingStrategy.DO_NOT_PAD: Do not pad185 The tokenizer padding sides are defined in self.padding_side:186 187 - 'left': pads on the left of the sequences188 - 'right': pads on the right of the sequences189 pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.190 This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability191 `>= 7.5` (Volta).192 return_attention_mask:193 (optional) Set to False to avoid returning attention mask (default: set to model specifics)194 """195 # Load from model defaults196 197 required_input = encoded_inputs[self.model_input_names[0]]198 seq_length = len(required_input)199 200 if padding_strategy == PaddingStrategy.LONGEST:201 max_length = len(required_input)202 203 if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):204 max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of205 206 needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length207 208 # Initialize attention mask if not present.209 if "attention_mask" not in encoded_inputs:210 encoded_inputs["attention_mask"] = [1] * seq_length211 212 if "position_ids" not in encoded_inputs:213 encoded_inputs["position_ids"] = list(range(seq_length))214 215 if needs_to_be_padded:216 difference = max_length - len(required_input)217 218 if "attention_mask" in encoded_inputs:219 encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]220 if "position_ids" in encoded_inputs:221 encoded_inputs["position_ids"] = [0] * difference + encoded_inputs["position_ids"]222 encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input223 224 return encoded_inputs