Team Ai
Modelpublic

codefuse-ai/CodeFuse-CodeGeeX2-6B

sourceHugging Faceotherupdated 3y agoView on Hugging Face
4likes24downloads
tokenization_chatglm.py265 linesDownload Raw Back to root
1import os2import torch3from typing import List, Optional, Union, Dict4from sentencepiece import SentencePieceProcessor5from transformers import PreTrainedTokenizer6from transformers.utils import logging, PaddingStrategy7from transformers.tokenization_utils_base import EncodedInput, BatchEncoding8 9 10class SPTokenizer:11    def __init__(self, model_path: str):12        # reload tokenizer13        assert os.path.isfile(model_path), model_path14        self.sp_model = SentencePieceProcessor(model_file=model_path)15 16        # BOS / EOS token IDs17        self.n_words: int = self.sp_model.vocab_size()18        self.bos_id: int = self.sp_model.bos_id()19        self.eos_id: int = self.sp_model.eos_id()20        self.pad_id: int = self.sp_model.unk_id()21        assert self.sp_model.vocab_size() == self.sp_model.get_piece_size()22 23        special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "sop", "eop"]24        self.special_tokens = {}25        self.index_special_tokens = {}26        for token in special_tokens:27            self.special_tokens[token] = self.n_words28            self.index_special_tokens[self.n_words] = token29            self.n_words += 130 31    def tokenize(self, s: str):32        return self.sp_model.EncodeAsPieces(s)33 34    def encode(self, s: str, bos: bool = False, eos: bool = False) -> List[int]:35        assert type(s) is str36        t = self.sp_model.encode(s)37        if bos:38            t = [self.bos_id] + t39        if eos:40            t = t + [self.eos_id]41        return t42 43    def decode(self, t: List[int]) -> str:44        return self.sp_model.decode(t)45 46    def decode_tokens(self, tokens: List[str]) -> str:47        text = self.sp_model.DecodePieces(tokens)48        return text49 50    def convert_token_to_id(self, token):51        """ Converts a token (str) in an id using the vocab. """52        if token in self.special_tokens:53            return self.special_tokens[token]54        return self.sp_model.PieceToId(token)55 56    def convert_id_to_token(self, index):57        """Converts an index (integer) in a token (str) using the vocab."""58        if index in self.index_special_tokens or index in [self.eos_id, self.bos_id, self.pad_id] or index < 0:59            return ""60        return self.sp_model.IdToPiece(index)61 62 63class ChatGLMTokenizer(PreTrainedTokenizer):64    vocab_files_names = {"vocab_file": "tokenizer.model"}65 66    model_input_names = ["input_ids", "attention_mask", "position_ids"]67 68    def __init__(self, vocab_file, padding_side="left", clean_up_tokenization_spaces=False, **kwargs):69        super().__init__(padding_side=padding_side, clean_up_tokenization_spaces=clean_up_tokenization_spaces, **kwargs)70        self.name = "GLMTokenizer"71 72        self.vocab_file = vocab_file73        self.tokenizer = SPTokenizer(vocab_file)74        self.special_tokens = {75            "<bos>": self.tokenizer.bos_id,76            "<eos>": self.tokenizer.eos_id,77            "<pad>": self.tokenizer.pad_id78        }79 80    def get_command(self, token):81        if token in self.special_tokens:82            return self.special_tokens[token]83        assert token in self.tokenizer.special_tokens, f"{token} is not a special token for {self.name}"84        return self.tokenizer.special_tokens[token]85 86    @property87    def unk_token(self) -> str:88        return "<unk>"89 90    @property91    def pad_token(self) -> str:92        return "<unk>"93 94    @property95    def pad_token_id(self):96        return self.get_command("<pad>")97 98    @property99    def eos_token(self) -> str:100        return "</s>"101 102    @property103    def eos_token_id(self):104        return self.get_command("<eos>")105 106    @property107    def vocab_size(self):108        return self.tokenizer.n_words109 110    def get_vocab(self):111        """ Returns vocab as a dict """112        vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}113        vocab.update(self.added_tokens_encoder)114        return vocab115 116    def _tokenize(self, text, **kwargs):117        return self.tokenizer.tokenize(text)118 119    def _convert_token_to_id(self, token):120        """ Converts a token (str) in an id using the vocab. """121        return self.tokenizer.convert_token_to_id(token)122 123    def _convert_id_to_token(self, index):124        """Converts an index (integer) in a token (str) using the vocab."""125        return self.tokenizer.convert_id_to_token(index)126 127    def convert_tokens_to_string(self, tokens: List[str]) -> str:128        return self.tokenizer.decode_tokens(tokens)129 130    def save_vocabulary(self, save_directory, filename_prefix=None):131        """132        Save the vocabulary and special tokens file to a directory.133 134        Args:135            save_directory (`str`):136                The directory in which to save the vocabulary.137            filename_prefix (`str`, *optional*):138                An optional prefix to add to the named of the saved files.139 140        Returns:141            `Tuple(str)`: Paths to the files saved.142        """143        if os.path.isdir(save_directory):144            vocab_file = os.path.join(145                save_directory, self.vocab_files_names["vocab_file"]146            )147        else:148            vocab_file = save_directory149 150        with open(self.vocab_file, 'rb') as fin:151            proto_str = fin.read()152 153        with open(vocab_file, "wb") as writer:154            writer.write(proto_str)155 156        return (vocab_file,)157 158    def get_prefix_tokens(self):159        prefix_tokens = [self.get_command("[gMASK]"), self.get_command("sop")]160        return prefix_tokens161 162    def build_prompt(self, query, history=None):163        if history is None:164            history = []165        prompt = ""166        for i, (old_query, response) in enumerate(history):167            prompt += "[Round {}]\n\n问:{}\n\n答:{}\n\n".format(i + 1, old_query, response)168        prompt += "[Round {}]\n\n问:{}\n\n答:".format(len(history) + 1, query)169        return prompt170 171    def build_inputs_with_special_tokens(172            self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None173    ) -> List[int]:174        """175        Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and176        adding special tokens. A BERT sequence has the following format:177 178        - single sequence: `[CLS] X [SEP]`179        - pair of sequences: `[CLS] A [SEP] B [SEP]`180 181        Args:182            token_ids_0 (`List[int]`):183                List of IDs to which the special tokens will be added.184            token_ids_1 (`List[int]`, *optional*):185                Optional second list of IDs for sequence pairs.186 187        Returns:188            `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.189        """190        prefix_tokens = self.get_prefix_tokens()191        token_ids_0 = prefix_tokens + token_ids_0192        if token_ids_1 is not None:193            token_ids_0 = token_ids_0 + token_ids_1 + [self.get_command("<eos>")]194        return token_ids_0195 196    def _pad(197            self,198            encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],199            max_length: Optional[int] = None,200            padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,201            pad_to_multiple_of: Optional[int] = None,202            return_attention_mask: Optional[bool] = None,203    ) -> dict:204        """205        Pad encoded inputs (on left/right and up to predefined length or max length in the batch)206 207        Args:208            encoded_inputs:209                Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).210            max_length: maximum length of the returned list and optionally padding length (see below).211                Will truncate by taking into account the special tokens.212            padding_strategy: PaddingStrategy to use for padding.213 214                - PaddingStrategy.LONGEST Pad to the longest sequence in the batch215                - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)216                - PaddingStrategy.DO_NOT_PAD: Do not pad217                The tokenizer padding sides are defined in self.padding_side:218 219                    - 'left': pads on the left of the sequences220                    - 'right': pads on the right of the sequences221            pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.222                This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability223                `>= 7.5` (Volta).224            return_attention_mask:225                (optional) Set to False to avoid returning attention mask (default: set to model specifics)226        """227        # Load from model defaults228        # assert self.padding_side == "left"229 230        required_input = encoded_inputs[self.model_input_names[0]]231        seq_length = len(required_input)232 233        if padding_strategy == PaddingStrategy.LONGEST:234            max_length = len(required_input)235 236        if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):237            max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of238 239        needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length240 241        # Initialize attention mask if not present.242        if "attention_mask" not in encoded_inputs:243            encoded_inputs["attention_mask"] = [1] * seq_length244 245        if "position_ids" not in encoded_inputs:246            encoded_inputs["position_ids"] = list(range(seq_length))247 248        if needs_to_be_padded:249            difference = max_length - len(required_input)250 251            if self.padding_side == "left":252                if "attention_mask" in encoded_inputs:253                    encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]254                if "position_ids" in encoded_inputs:255                    encoded_inputs["position_ids"] = [0] * difference + encoded_inputs["position_ids"]256                encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input257            else:258                if "attention_mask" in encoded_inputs:259                    encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference260                if "position_ids" in encoded_inputs:261                    encoded_inputs["position_ids"] = encoded_inputs["position_ids"] + [0] * difference262                encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference263 264        return encoded_inputs265