DoruC/Grounded-Segment-Anything
0
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 17 18import json19import os20from typing import Optional, Tuple21 22import regex as re23 24from ...tokenization_utils import PreTrainedTokenizer25from ...utils import logging26 27 28logger = logging.get_logger(__name__)29 30VOCAB_FILES_NAMES = {31 "vocab_file": "vocab.json",32 "merges_file": "merges.txt",33}34 35PRETRAINED_VOCAB_FILES_MAP = {36 "vocab_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json"},37 "merges_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt"},38}39 40PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {41 "ctrl": 256,42}43 44CONTROL_CODES = {45 "Pregnancy": 168629,46 "Christianity": 7675,47 "Explain": 106423,48 "Fitness": 63440,49 "Saving": 63163,50 "Ask": 27171,51 "Ass": 95985,52 "Joke": 163509,53 "Questions": 45622,54 "Thoughts": 49605,55 "Retail": 52342,56 "Feminism": 164338,57 "Writing": 11992,58 "Atheism": 192263,59 "Netflix": 48616,60 "Computing": 39639,61 "Opinion": 43213,62 "Alone": 44967,63 "Funny": 58917,64 "Gaming": 40358,65 "Human": 4088,66 "India": 1331,67 "Joker": 77138,68 "Diet": 36206,69 "Legal": 11859,70 "Norman": 4939,71 "Tip": 72689,72 "Weight": 52343,73 "Movies": 46273,74 "Running": 23425,75 "Science": 2090,76 "Horror": 37793,77 "Confession": 60572,78 "Finance": 12250,79 "Politics": 16360,80 "Scary": 191985,81 "Support": 12654,82 "Technologies": 32516,83 "Teenage": 66160,84 "Event": 32769,85 "Learned": 67460,86 "Notion": 182770,87 "Wikipedia": 37583,88 "Books": 6665,89 "Extract": 76050,90 "Confessions": 102701,91 "Conspiracy": 75932,92 "Links": 63674,93 "Narcissus": 150425,94 "Relationship": 54766,95 "Relationships": 134796,96 "Reviews": 41671,97 "News": 4256,98 "Translation": 26820,99 "multilingual": 128406,100}101 102 103def get_pairs(word):104 """105 Return set of symbol pairs in a word.106 107 Word is represented as tuple of symbols (symbols being variable-length strings).108 """109 pairs = set()110 prev_char = word[0]111 for char in word[1:]:112 pairs.add((prev_char, char))113 prev_char = char114 115 pairs = set(pairs)116 return pairs117 118 119class CTRLTokenizer(PreTrainedTokenizer):120 """121 Construct a CTRL tokenizer. Based on Byte-Pair-Encoding.122 123 This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to124 this superclass for more information regarding those methods.125 126 Args:127 vocab_file (`str`):128 Path to the vocabulary file.129 merges_file (`str`):130 Path to the merges file.131 unk_token (`str`, *optional*, defaults to `"<unk>"`):132 The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this133 token instead.134 """135 136 vocab_files_names = VOCAB_FILES_NAMES137 pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP138 max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES139 control_codes = CONTROL_CODES140 141 def __init__(self, vocab_file, merges_file, unk_token="<unk>", **kwargs):142 with open(vocab_file, encoding="utf-8") as vocab_handle:143 self.encoder = json.load(vocab_handle)144 self.decoder = {v: k for k, v in self.encoder.items()}145 with open(merges_file, encoding="utf-8") as merges_handle:146 merges = merges_handle.read().split("\n")[1:-1]147 merges = [tuple(merge.split()) for merge in merges]148 self.bpe_ranks = dict(zip(merges, range(len(merges))))149 self.cache = {}150 super().__init__(unk_token=unk_token, **kwargs)151 152 @property153 def vocab_size(self):154 return len(self.encoder)155 156 def get_vocab(self):157 return dict(self.encoder, **self.added_tokens_encoder)158 159 def bpe(self, token):160 if token in self.cache:161 return self.cache[token]162 word = tuple(token)163 word = tuple(list(word[:-1]) + [word[-1] + "</w>"])164 pairs = get_pairs(word)165 166 if not pairs:167 return token168 169 while True:170 bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))171 if bigram not in self.bpe_ranks:172 break173 first, second = bigram174 new_word = []175 i = 0176 while i < len(word):177 try:178 j = word.index(first, i)179 except ValueError:180 new_word.extend(word[i:])181 break182 else:183 new_word.extend(word[i:j])184 i = j185 186 if word[i] == first and i < len(word) - 1 and word[i + 1] == second:187 new_word.append(first + second)188 i += 2189 else:190 new_word.append(word[i])191 i += 1192 new_word = tuple(new_word)193 word = new_word194 if len(word) == 1:195 break196 else:197 pairs = get_pairs(word)198 word = "@@ ".join(word)199 word = word[:-4]200 self.cache[token] = word201 return word202 203 def _tokenize(self, text):204 """Tokenize a string."""205 split_tokens = []206 207 words = re.findall(r"\S+\n?", text)208 209 for token in words:210 split_tokens.extend(list(self.bpe(token).split(" ")))211 return split_tokens212 213 def _convert_token_to_id(self, token):214 """Converts a token (str) in an id using the vocab."""215 return self.encoder.get(token, self.encoder.get(self.unk_token))216 217 def _convert_id_to_token(self, index):218 """Converts an index (integer) in a token (str) using the vocab."""219 return self.decoder.get(index, self.unk_token)220 221 def convert_tokens_to_string(self, tokens):222 """Converts a sequence of tokens (string) in a single string."""223 out_string = " ".join(tokens).replace("@@ ", "").strip()224 return out_string225 226 def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:227 if not os.path.isdir(save_directory):228 logger.error(f"Vocabulary path ({save_directory}) should be a directory")229 return230 vocab_file = os.path.join(231 save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]232 )233 merge_file = os.path.join(234 save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]235 )236 237 with open(vocab_file, "w", encoding="utf-8") as f:238 f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")239 240 index = 0241 with open(merge_file, "w", encoding="utf-8") as writer:242 writer.write("#version: 0.2\n")243 for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):244 if index != token_index:245 logger.warning(246 f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."247 " Please check that the tokenizer is not corrupted!"248 )249 index = token_index250 writer.write(" ".join(bpe_tokens) + "\n")251 index += 1252 253 return vocab_file, merge_file254 255 # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):256 # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))257 # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)258 # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)259 # return ''.join(tokens_generated_so_far)260 