init: first commit
Browse filesFiles changed (4)
- README.mdAdded+9
- arcade100k.tiktokenAdded
- tokenization_arcade100k.pyAdded+265
- tokenizer_config.jsonAdded+9
123456789# Arcade100kTokenizer
BPE tokenizer based on `tiktoken.cl100k_base`.
```from transformers import AutoTokenizertokenizer = AutoTokenizer.from_pretrained("jon-tow/arcade100k", trust_remote_code=True)tokenizer("hello, world!", return_tensors='pt')```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265# coding=utf-8# Copyright 2023 Stability AI, Alibaba Cloud, The Open AI Team Authors, and The HuggingFace Inc. team.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Tokenization classes for Arcade100k."""
import base64import osimport unicodedatafrom typing import Collection, Dict, List, Set, Tuple, Union
import tiktokenfrom transformers.utils import loggingfrom transformers import PreTrainedTokenizer, AddedToken
logger = logging.get_logger(__name__)
VOCAB_FILES_NAMES = {"vocab_file": "arcade100k.tiktoken"}NAME = "arcade100k"
def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]: with open(tiktoken_bpe_file, "rb") as f: contents = f.read() return { base64.b64decode(token): int(rank) for token, rank in (line.split() for line in contents.splitlines() if line) }
def _arcade100k(vocab_file: str): mergeable_ranks = _load_tiktoken_bpe(vocab_file)
# Special Tokens ENDOFTEXT = "<|endoftext|>" FIM_PREFIX = "<|fim_prefix|>" FIM_MIDDLE = "<|fim_middle|>" FIM_SUFFIX = "<|fim_suffix|>" ENDOFPROMPT = "<|endofprompt|>"
# Custom Special Tokens IM_START = "<|im_start|>" # Chat: Input message start IM_END = "<|im_end|>" # Chat: Input message end PAUSE = "<|pause|>" # Think before you speak (https://arxiv.org/abs/2310.02226) # Register/sink tokens (https://arxiv.org/abs/2309.17453) REGISTERS = [f"<|reg{i}|>" for i in range(0, 8)] custom_special_tokens = { t: 100261 + i for i, t in enumerate([IM_START, IM_END, PAUSE, *REGISTERS]) } ENDOFPROMPT_ID = 100276
# Fill-out extra tokens for i in range(100261 + len(custom_special_tokens), ENDOFPROMPT_ID + 1): custom_special_tokens[f"<|extra{i}|>"] = i
special_tokens = { ENDOFTEXT: 100257, FIM_PREFIX: 100258, FIM_MIDDLE: 100259, FIM_SUFFIX: 100260, **custom_special_tokens, ENDOFPROMPT: 100276, }
return { "name": NAME, "pat_str": r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+""", "mergeable_ranks": mergeable_ranks, "special_tokens": special_tokens, }
class Arcade100kTokenizer(PreTrainedTokenizer): """ Construct a Arcade100k tokenizer backed by `tiktoken`.
Args: vocab_file (`str`): Path to the vocabulary file. errors (`str`, *optional*, defaults to `"replace"`): How to handle errors in decoding UTF-8 byte sequences. WARNING: the default behaviour of this function is lossy, since decoded bytes are not guaranteed to be valid UTF-8. You can control this behaviour using the `errors` parameter, for instance, setting `errors=strict`. """
vocab_files_names = VOCAB_FILES_NAMES model_input_names = ["input_ids", "attention_mask"]
def __init__( self, vocab_file: str, errors: str = "replace", **kwargs, ): super().__init__(errors=errors, **kwargs) self._tiktoken_config = _arcade100k(self.vocab_files_names["vocab_file"]) self.tokenizer = tiktoken.Encoding(**self._tiktoken_config) # TODO: Remove this assertion assert ( len(self._tiktoken_config["mergeable_ranks"]) + len(self._tiktoken_config["special_tokens"]) == self.tokenizer.n_vocab ), f"{len(self._tiktoken_config['mergeable_ranks']) + len(self._tiktoken_config['special_tokens'])} != {self.tokenizer.n_vocab} in encoding"
self.decoder = { i: n for n, i in self._tiktoken_config["mergeable_ranks"].items() } self.decoder.update( {i: n for n, i in self._tiktoken_config["special_tokens"].items()} ) self.eos_token = self.decoder[self.tokenizer.eot_token] self.pad_token = self.decoder[self.tokenizer.eot_token]
@property def vocab_size(self): return self.tokenizer.n_vocab
def get_vocab(self) -> Dict[bytes, int]: return self._tiktoken_config["mergeable_ranks"]
def convert_tokens_to_ids( self, tokens: Union[bytes, str, List[Union[bytes, str]]] ) -> List[int]: ids = [] if isinstance(tokens, (str, bytes)): if tokens in self._tiktoken_config["special_tokens"]: return self._tiktoken_config["special_tokens"][tokens] else: return self._tiktoken_config["mergeable_ranks"].get(tokens) for token in tokens: if token in self._tiktoken_config["special_tokens"]: ids.append(self._tiktoken_config["special_tokens"][token]) else: ids.append(self._tiktoken_config["mergeable_ranks"].get(token)) return ids
def _add_tokens( self, new_tokens: Union[List[str], List[AddedToken]], special_tokens: bool = False, ) -> int: if not special_tokens and new_tokens: raise ValueError("Adding regular tokens is not supported") for token in new_tokens: surface_form = token.content if isinstance(token, AddedToken) else token if surface_form not in SPECIAL_TOKENS_SET: raise ValueError("Adding unknown special tokens is not supported") return 0
def save_vocabulary(self, save_directory: str, **kwargs) -> Tuple[str]: """ Save only the vocabulary of the tokenizer (vocabulary).
Returns: `Tuple(str)`: Paths to the files saved. """ file_path = os.path.join(save_directory, "qwen.tiktoken") with open(file_path, "w", encoding="utf8") as w: for k, v in self._tiktoken_config["mergeable_ranks"].items(): line = base64.b64encode(k).decode("utf8") + " " + str(v) + "\n" w.write(line) return (file_path,)
def tokenize( self, text: str, allowed_special: Union[Set, str] = "all", disallowed_special: Union[Collection, str] = (), **kwargs, ) -> List[Union[bytes, str]]: """ Converts a string in a sequence of tokens.
Args: text (`str`): The sequence to be encoded. allowed_special (`Literal["all"]` or `set`): The surface forms of the tokens to be encoded as special tokens in regular texts. Default to "all". disallowed_special (`Literal["all"]` or `Collection`): The surface forms of the tokens that should not be in regular texts and trigger errors. Default to an empty tuple.
kwargs (additional keyword arguments, *optional*): Will be passed to the underlying model specific encode method.
Returns: `List[bytes|str]`: The list of tokens. """ tokens = [] text = unicodedata.normalize("NFC", text)
# this implementation takes a detour: text -> token id -> token surface forms for t in self.tokenizer.encode( text, allowed_special=allowed_special, disallowed_special=disallowed_special ): tokens.append(self.decoder[t]) return tokens
def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str: """ Converts a sequence of tokens in a single string. """ text = "" temp = b"" for t in tokens: if isinstance(t, str): if temp: text += temp.decode("utf-8", errors=self.errors) temp = b"" text += t elif isinstance(t, bytes): temp += t else: raise TypeError("token should only be of type types or str") if temp: text += temp.decode("utf-8", errors=self.errors) return text
def _convert_id_to_token(self, index: int) -> Union[bytes, str]: """Converts an id to a token, special tokens included""" if index in self.decoder: return self.decoder[index] raise ValueError("unknown ids")
def _convert_token_to_id(self, token: Union[bytes, str]) -> int: """Converts a token to an id using the vocab, special tokens included""" if token in self._tiktoken_config["special_tokens"]: return self._tiktoken_config["special_tokens"][token] if token in self._tiktoken_config["mergeable_ranks"]: return self._tiktoken_config["mergeable_ranks"][token] raise ValueError("unknown token")
def _tokenize(self, text: str, **kwargs): """ Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
Do NOT take care of added tokens. """ raise NotImplementedError
def _decode( self, token_ids: Union[int, List[int]], skip_special_tokens: bool = False, errors: str = None, **kwargs, ) -> str: if isinstance(token_ids, int): token_ids = [token_ids] if skip_special_tokens: token_ids = [i for i in token_ids if i < self.tokenizer.eot_token] return self.tokenizer.decode(token_ids, errors=errors or self.errors)123456789{ "tokenizer_class": "Arcade100kTokenizer", "auto_map": { "AutoTokenizer": [ "tokenization_arcade100k.Arcade100kTokenizer", null ] } }README.mdAdded+9
arcade100k.tiktokenAdded
tokenization_arcade100k.pyAdded+265
tokenizer_config.jsonAdded+9