CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
tokenization_ctrl.py252 linesDownload Raw Back to ctrl
1# coding=utf-82# Copyright 2018 Salesforce and The HuggingFace Inc. team.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8#     http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15"""Tokenization classes for Salesforce CTRL."""16 17import json18import os19from typing import Optional20 21import regex as re22 23from ...tokenization_utils import PreTrainedTokenizer24from ...utils import logging25 26 27logger = logging.get_logger(__name__)28 29VOCAB_FILES_NAMES = {30    "vocab_file": "vocab.json",31    "merges_file": "merges.txt",32}33 34 35CONTROL_CODES = {36    "Pregnancy": 168629,37    "Christianity": 7675,38    "Explain": 106423,39    "Fitness": 63440,40    "Saving": 63163,41    "Ask": 27171,42    "Ass": 95985,43    "Joke": 163509,44    "Questions": 45622,45    "Thoughts": 49605,46    "Retail": 52342,47    "Feminism": 164338,48    "Writing": 11992,49    "Atheism": 192263,50    "Netflix": 48616,51    "Computing": 39639,52    "Opinion": 43213,53    "Alone": 44967,54    "Funny": 58917,55    "Gaming": 40358,56    "Human": 4088,57    "India": 1331,58    "Joker": 77138,59    "Diet": 36206,60    "Legal": 11859,61    "Norman": 4939,62    "Tip": 72689,63    "Weight": 52343,64    "Movies": 46273,65    "Running": 23425,66    "Science": 2090,67    "Horror": 37793,68    "Confession": 60572,69    "Finance": 12250,70    "Politics": 16360,71    "Scary": 191985,72    "Support": 12654,73    "Technologies": 32516,74    "Teenage": 66160,75    "Event": 32769,76    "Learned": 67460,77    "Notion": 182770,78    "Wikipedia": 37583,79    "Books": 6665,80    "Extract": 76050,81    "Confessions": 102701,82    "Conspiracy": 75932,83    "Links": 63674,84    "Narcissus": 150425,85    "Relationship": 54766,86    "Relationships": 134796,87    "Reviews": 41671,88    "News": 4256,89    "Translation": 26820,90    "multilingual": 128406,91}92 93 94def get_pairs(word):95    """96    Return set of symbol pairs in a word.97 98    Word is represented as tuple of symbols (symbols being variable-length strings).99    """100    pairs = set()101    prev_char = word[0]102    for char in word[1:]:103        pairs.add((prev_char, char))104        prev_char = char105 106    pairs = set(pairs)107    return pairs108 109 110class CTRLTokenizer(PreTrainedTokenizer):111    """112    Construct a CTRL tokenizer. Based on Byte-Pair-Encoding.113 114    This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to115    this superclass for more information regarding those methods.116 117    Args:118        vocab_file (`str`):119            Path to the vocabulary file.120        merges_file (`str`):121            Path to the merges file.122        unk_token (`str`, *optional*, defaults to `"<unk>"`):123            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this124            token instead.125    """126 127    vocab_files_names = VOCAB_FILES_NAMES128    control_codes = CONTROL_CODES129 130    def __init__(self, vocab_file, merges_file, unk_token="<unk>", **kwargs):131        with open(vocab_file, encoding="utf-8") as vocab_handle:132            self.encoder = json.load(vocab_handle)133        self.decoder = {v: k for k, v in self.encoder.items()}134        with open(merges_file, encoding="utf-8") as merges_handle:135            merges = merges_handle.read().split("\n")[1:-1]136        merges = [tuple(merge.split()) for merge in merges]137        self.bpe_ranks = dict(zip(merges, range(len(merges))))138        self.cache = {}139        super().__init__(unk_token=unk_token, **kwargs)140 141    @property142    def vocab_size(self):143        return len(self.encoder)144 145    def get_vocab(self):146        return dict(self.encoder, **self.added_tokens_encoder)147 148    def bpe(self, token):149        if token in self.cache:150            return self.cache[token]151        word = tuple(token)152        word = tuple(list(word[:-1]) + [word[-1] + "</w>"])153        pairs = get_pairs(word)154 155        if not pairs:156            return token157 158        while True:159            bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))160            if bigram not in self.bpe_ranks:161                break162            first, second = bigram163            new_word = []164            i = 0165            while i < len(word):166                try:167                    j = word.index(first, i)168                except ValueError:169                    new_word.extend(word[i:])170                    break171                else:172                    new_word.extend(word[i:j])173                    i = j174 175                if word[i] == first and i < len(word) - 1 and word[i + 1] == second:176                    new_word.append(first + second)177                    i += 2178                else:179                    new_word.append(word[i])180                    i += 1181            new_word = tuple(new_word)182            word = new_word183            if len(word) == 1:184                break185            else:186                pairs = get_pairs(word)187        word = "@@ ".join(word)188        word = word[:-4]189        self.cache[token] = word190        return word191 192    def _tokenize(self, text):193        """Tokenize a string."""194        split_tokens = []195 196        words = re.findall(r"\S+\n?", text)197 198        for token in words:199            split_tokens.extend(list(self.bpe(token).split(" ")))200        return split_tokens201 202    def _convert_token_to_id(self, token):203        """Converts a token (str) in an id using the vocab."""204        return self.encoder.get(token, self.encoder.get(self.unk_token))205 206    def _convert_id_to_token(self, index):207        """Converts an index (integer) in a token (str) using the vocab."""208        return self.decoder.get(index, self.unk_token)209 210    def convert_tokens_to_string(self, tokens):211        """Converts a sequence of tokens (string) in a single string."""212        out_string = " ".join(tokens).replace("@@ ", "").strip()213        return out_string214 215    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:216        if not os.path.isdir(save_directory):217            logger.error(f"Vocabulary path ({save_directory}) should be a directory")218            return219        vocab_file = os.path.join(220            save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]221        )222        merge_file = os.path.join(223            save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]224        )225 226        with open(vocab_file, "w", encoding="utf-8") as f:227            f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")228 229        index = 0230        with open(merge_file, "w", encoding="utf-8") as writer:231            writer.write("#version: 0.2\n")232            for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):233                if index != token_index:234                    logger.warning(235                        f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."236                        " Please check that the tokenizer is not corrupted!"237                    )238                    index = token_index239                writer.write(" ".join(bpe_tokens) + "\n")240                index += 1241 242        return vocab_file, merge_file243 244    # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):245    #     filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))246    #     tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)247    #     tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)248    #     return ''.join(tokens_generated_so_far)249 250 251__all__ = ["CTRLTokenizer"]252 
Aluode/PerceptionLabPortable · CoolFace