codingutf8 2023 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 orglicenseslicense2 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 fast tokenization class for seamlessm4t import os from shutil import copyfile from typing import list optional tuple union from tokenizers import processors from tokenizationutils import batchencoding pretokenizedinput textinput from tokenizationutilsfast import pretrainedtokenizerfast from utils import paddingstrategy logging from tokenizationseamlessm4t import seamlessm4ttokenizer logger logging getloggername vocabfilesnames vocabfile sentencepiece bpe model tokenizerfile tokenizer json pretrainedvocabfilesmap vocabfile facebookhfseamlessm4tmedium https huggingface cofacebookhfseamlessm4tmediumresolvemainvocab txt tokenizerfile facebookhfseamlessm4tmedium https huggingface cofacebookhfseamlessm4tmediumresolvemaintokenizer json pretrainedpositionalembeddingssizes facebookhfseamlessm4tmedium 2048 class seamlessm4ttokenizerfastpretrainedtokenizerfast vocabfilesnames vocabfilesnames pretrainedvocabfilesmap pretrainedvocabfilesmap maxmodelinputsizes pretrainedpositionalembeddingssizes slowtokenizerclass seamlessm4ttokenizer modelinputnames inputids attentionmask prefixtokens listint suffixtokens listint def init self vocabfilenone tokenizerfilenone bostokens eostokens septokens clstokens unktokenunk padtokenpad srclangeng tgtlangfra additionalspecialtokensnone kwargs super init vocabfilevocabfile tokenizerfiletokenizerfile bostokenbostoken eostokeneostoken septokenseptoken clstokenclstoken unktokenunktoken padtokenpadtoken srclangsrclang tgtlangtgtlang additionalspecialtokensadditionalspecialtokens kwargs self vocabfile vocabfile self srclang fsrclang if not in srclang else srclang self tgtlang ftgtlang if not in tgtlang else tgtlang self setsrclangspecialtokensself srclang self settgtlangspecialtokensself tgtlang property def cansaveslowtokenizerself bool return os path isfileself vocabfile if self vocabfile else false property copied from transformers models nllb tokenizationnllb nllbtokenizer srclang def srclangself str return self srclang srclang setter def srclangself newsrclang str none if not in newsrclang self srclang fnewsrclang else self srclang newsrclang self setsrclangspecialtokensself srclang property def tgtlangself str return self tgtlang tgtlang setter def tgtlangself newtgtlang str none if not in newtgtlang self tgtlang fnewtgtlang else self tgtlang newtgtlang self settgtlangspecialtokensself tgtlang def buildinputswithspecialtokens self tokenids0 listint tokenids1 optionallistint none listint if tokenids1 is none return self prefixtokens tokenids0 self suffixtokens we don t expect to process pairs but leave the pair logic for api consistency return self prefixtokens tokenids0 tokenids1 self suffixtokens copied from transformers models nllb tokenizationnllbfast nllbtokenizerfast createtokentypeidsfromsequences def createtokentypeidsfromsequences self tokenids0 listint tokenids1 optionallistint none listint sep self septokenid cls self clstokenid if tokenids1 is none return lencls tokenids0 sep 0 return lencls tokenids0 sep sep tokenids1 sep 0 def buildtranslationinputs self rawinputs returntensors str srclang optionalstr tgtlang optionalstr extrakwargs copied from transformers models nllb tokenizationnllbfast nllbtokenizerfast prepareseq2seqbatch with fralatnfra englatneng copied from transformers models nllb tokenizationnllbfast nllbtokenizerfast switchtoinputmode copied from transformers models nllb tokenizationnllbfast nllbtokenizerfast switchtotargetmode reset the special tokens to the source lang setting prefixsrclangcode suffix eos reset the special tokens to the target lang setting prefixeos tgtlangcode and suffixeos copied from transformers models nllb tokenizationnllbfast nllbtokenizerfast savevocabulary ensure also set after from pretrained args text str liststr listliststr optional the sequence or batch of sequences to be encoded each sequence can be a string or a list of strings pretokenized string if the sequences are provided as list of strings pretokenized you must set issplitintowordstrue to lift the ambiguity with a batch of sequences textpair str liststr listliststr optional the sequence or batch of sequences to be encoded each sequence can be a string or a list of strings pretokenized string if the sequences are provided as list of strings pretokenized you must set issplitintowordstrue to lift the ambiguity with a batch of sequences texttarget str liststr listliststr optional the sequence or batch of sequences to be encoded as target texts each sequence can be a string or a list of strings pretokenized string if the sequences are provided as list of strings pretokenized you must set issplitintowordstrue to lift the ambiguity with a batch of sequences textpairtarget str liststr listliststr optional the sequence or batch of sequences to be encoded as target texts each sequence can be a string or a list of strings pretokenized string if the sequences are provided as list of strings pretokenized you must set issplitintowordstrue to lift the ambiguity with a batch of sequences padding bool str or utils paddingstrategy optional defaults to true select a strategy to pad the returned sequences according to the model s padding side and padding index among true or longest pad to the longest sequence in the batch or no padding if only a single sequence if provided maxlength pad to a maximum length specified with the argument maxlength or to the maximum acceptable input length for the model if that argument is not provided false or donotpad default no padding i e can output a batch with sequences of different lengths padtomultipleof int optional if set will pad the sequence to a multiple of the provided value this is especially useful to enable the use of tensor cores on nvidia hardware with compute capability 7 5 volta srclang str optional a string representing the source language if not specified the last srclang specified either during initialization or when calling this tokenizer will be used tgtlang str optional a string representing the target language if not specified the last tgtlang specified either during initialization or when calling this tokenizer will be used kwargs optional remaining dictionary of keyword arguments that will be passed to pretrainedtokenizerfast call coding utf 8 2023 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 fast tokenization class for seamlessm4t construct a fast seamlessm4t tokenizer backed by huggingface s tokenizers library based on bpe https huggingface co docs tokenizers python latest components html highlight bpe models this tokenizer inherits from pretrainedtokenizerfast which contains most of the main methods users should refer to this superclass for more information regarding those methods the tokenization method is language code tokens eos for source language documents and eos language code tokens eos for target language documents examples python from transformers import seamlessm4ttokenizerfast tokenizer seamlessm4ttokenizerfast from_pretrained facebook hf seamless m4t medium src_lang eng tgt_lang fra example_english_phrase un chief says there is no military solution in syria expected_translation_french le chef de l onu affirme qu il n y a pas de solution militaire en syrie inputs tokenizer example_english_phrase text_target expected_translation_french return_tensors pt args vocab_file str optional path to the vocabulary file tokenizer_file str optional the path to a tokenizer file to use instead of the vocab file bos_token str optional defaults to s the beginning of sequence token that was used during pretraining can be used a sequence classifier token tip when building a sequence using special tokens this is not the token that is used for the beginning of sequence the token used is the cls_token tip eos_token str optional defaults to s the end of sequence token tip when building a sequence using special tokens this is not the token that is used for the end of sequence the token used is the sep_token tip sep_token str optional defaults to s the separator token which is used when building a sequence from multiple sequences e g two sequences for sequence classification or for a text and a question for question answering it is also used as the last token of a sequence built with special tokens cls_token str optional defaults to s the classifier token which is used when doing sequence classification classification of the whole sequence instead of per token classification it is the first token of the sequence when built with special tokens unk_token str optional defaults to unk the unknown token a token that is not in the vocabulary cannot be converted to an id and is set to be this token instead pad_token str optional defaults to pad the token used for padding for example when batching sequences of different lengths src_lang str optional defaults to eng the language to use as source language for translation tgt_lang str optional defaults to fra the language to use as target language for translation additional_special_tokens tuple or list of str or tokenizers addedtoken optional a tuple or a list of additional special tokens copied from transformers models nllb tokenization_nllb nllbtokenizer src_lang build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens the special tokens depend on calling set_lang an seamlessm4t sequence has the following format where x represents the sequence input_ids for encoder src_lang_code x eos decoder_input_ids for decoder eos tgt_lang_code x eos bos is never used pairs of sequences are not the expected use case but they will be handled without a separator args token_ids_0 list int list of ids to which the special tokens will be added token_ids_1 list int optional optional second list of ids for sequence pairs returns list int list of input ids glossary input ids with the appropriate special tokens we don t expect to process pairs but leave the pair logic for api consistency copied from transformers models nllb tokenization_nllb_fast nllbtokenizerfast create_token_type_ids_from_sequences create a mask from the two sequences passed to be used in a sequence pair classification task nllb does not make use of token type ids therefore a list of zeros is returned args token_ids_0 list int list of ids token_ids_1 list int optional optional second list of ids for sequence pairs returns list int list of zeros used by translation pipeline to prepare inputs for the generate function copied from transformers models nllb tokenization_nllb_fast nllbtokenizerfast prepare_seq2seq_batch with fra_latn fra eng_latn eng copied from transformers models nllb tokenization_nllb_fast nllbtokenizerfast _switch_to_input_mode copied from transformers models nllb tokenization_nllb_fast nllbtokenizerfast _switch_to_target_mode reset the special tokens to the source lang setting prefix src_lang_code suffix eos reset the special tokens to the target lang setting prefix eos tgt_lang_code and suffix eos copied from transformers models nllb tokenization_nllb_fast nllbtokenizerfast save_vocabulary ensure also set after from pretrained args text str list str list list str optional the sequence or batch of sequences to be encoded each sequence can be a string or a list of strings pretokenized string if the sequences are provided as list of strings pretokenized you must set is_split_into_words true to lift the ambiguity with a batch of sequences text_pair str list str list list str optional the sequence or batch of sequences to be encoded each sequence can be a string or a list of strings pretokenized string if the sequences are provided as list of strings pretokenized you must set is_split_into_words true to lift the ambiguity with a batch of sequences text_target str list str list list str optional the sequence or batch of sequences to be encoded as target texts each sequence can be a string or a list of strings pretokenized string if the sequences are provided as list of strings pretokenized you must set is_split_into_words true to lift the ambiguity with a batch of sequences text_pair_target str list str list list str optional the sequence or batch of sequences to be encoded as target texts each sequence can be a string or a list of strings pretokenized string if the sequences are provided as list of strings pretokenized you must set is_split_into_words true to lift the ambiguity with a batch of sequences padding bool str or utils paddingstrategy optional defaults to true select a strategy to pad the returned sequences according to the model s padding side and padding index among true or longest pad to the longest sequence in the batch or no padding if only a single sequence if provided max_length pad to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided false or do_not_pad default no padding i e can output a batch with sequences of different lengths pad_to_multiple_of int optional if set will pad the sequence to a multiple of the provided value this is especially useful to enable the use of tensor cores on nvidia hardware with compute capability 7 5 volta src_lang str optional a string representing the source language if not specified the last src_lang specified either during initialization or when calling this tokenizer will be used tgt_lang str optional a string representing the target language if not specified the last tgt_lang specified either during initialization or when calling this tokenizer will be used kwargs optional remaining dictionary of keyword arguments that will be passed to pretrainedtokenizerfast __call__
import os
from shutil import copyfile
from typing import List, Optional, Tuple, Union

from tokenizers import processors

from ...tokenization_utils import (
    BatchEncoding,
    PreTokenizedInput,
    TextInput,
)
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import PaddingStrategy, logging
from .tokenization_seamless_m4t import (
    SeamlessM4TTokenizer,
)


logger = logging.get_logger(__name__)

VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}

PRETRAINED_VOCAB_FILES_MAP = {
    "vocab_file": {
        "facebook/hf-seamless-m4t-medium": "https://huggingface.co/facebook/hf-seamless-m4t-medium/resolve/main/vocab.txt",
    },
    "tokenizer_file": {
        "facebook/hf-seamless-m4t-medium": "https://huggingface.co/facebook/hf-seamless-m4t-medium/resolve/main/tokenizer.json",
    },
}

PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
    "facebook/hf-seamless-m4t-medium": 2048,
}


class SeamlessM4TTokenizerFast(PreTrainedTokenizerFast):
    

    vocab_files_names = VOCAB_FILES_NAMES
    pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
    max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    slow_tokenizer_class = SeamlessM4TTokenizer
    model_input_names = ["input_ids", "attention_mask"]

    prefix_tokens: List[int] = []
    suffix_tokens: List[int] = []

    def __init__(
        self,
        vocab_file=None,
        tokenizer_file=None,
        bos_token="<s>",
        eos_token="</s>",
        sep_token="</s>",
        cls_token="<s>",
        unk_token="<unk>",
        pad_token="<pad>",
        src_lang="eng",
        tgt_lang="fra",
        additional_special_tokens=None,
        **kwargs,
    ):
        super().__init__(
            vocab_file=vocab_file,
            tokenizer_file=tokenizer_file,
            bos_token=bos_token,
            eos_token=eos_token,
            sep_token=sep_token,
            cls_token=cls_token,
            unk_token=unk_token,
            pad_token=pad_token,
            src_lang=src_lang,
            tgt_lang=tgt_lang,
            additional_special_tokens=additional_special_tokens,
            **kwargs,
        )

        self.vocab_file = vocab_file
        self._src_lang = f"__{src_lang}__" if "__" not in src_lang else src_lang
        self._tgt_lang = f"__{tgt_lang}__" if "__" not in tgt_lang else tgt_lang
        self.set_src_lang_special_tokens(self._src_lang)
        self.set_tgt_lang_special_tokens(self._tgt_lang)

    @property
    def can_save_slow_tokenizer(self) -> bool:
        return os.path.isfile(self.vocab_file) if self.vocab_file else False

    @property
    
    def src_lang(self) -> str:
        return self._src_lang

    @src_lang.setter
    def src_lang(self, new_src_lang: str) -> None:
        if "__" not in new_src_lang:
            self._src_lang = f"__{new_src_lang}__"
        else:
            self._src_lang = new_src_lang
        self.set_src_lang_special_tokens(self._src_lang)

    @property
    def tgt_lang(self) -> str:
        return self._tgt_lang

    @tgt_lang.setter
    def tgt_lang(self, new_tgt_lang: str) -> None:
        if "__" not in new_tgt_lang:
            self._tgt_lang = f"__{new_tgt_lang}__"
        else:
            self._tgt_lang = new_tgt_lang
        self.set_tgt_lang_special_tokens(self._tgt_lang)

    def build_inputs_with_special_tokens(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
    ) -> List[int]:
        
        if token_ids_1 is None:
            return self.prefix_tokens + token_ids_0 + self.suffix_tokens
        
        return self.prefix_tokens + token_ids_0 + token_ids_1 + self.suffix_tokens

    
    def create_token_type_ids_from_sequences(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
    ) -> List[int]:
        

        sep = [self.sep_token_id]
        cls = [self.cls_token_id]

        if token_ids_1 is None:
            return len(cls + token_ids_0 + sep) * [0]
        return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]

    def _build_translation_inputs(
        self, raw_inputs, return_tensors: str, src_lang: Optional[str], tgt_lang: Optional[str], **extra_kwargs
    ):
        
        if src_lang is None or tgt_lang is None:
            raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model")
        self.src_lang = src_lang
        inputs = self(raw_inputs, add_special_tokens=True, return_tensors=return_tensors, **extra_kwargs)
        if "__" not in tgt_lang:
            tgt_lang = f"__{tgt_lang}__"
        tgt_lang_id = self.convert_tokens_to_ids(tgt_lang)
        inputs["forced_bos_token_id"] = tgt_lang_id
        return inputs

    
    def prepare_seq2seq_batch(
        self,
        src_texts: List[str],
        src_lang: str = "eng",
        tgt_texts: Optional[List[str]] = None,
        tgt_lang: str = "fra",
        **kwargs,
    ) -> BatchEncoding:
        self.src_lang = src_lang
        self.tgt_lang = tgt_lang
        return super().prepare_seq2seq_batch(src_texts, tgt_texts, **kwargs)

    
    def _switch_to_input_mode(self):
        return self.set_src_lang_special_tokens(self.src_lang)

    
    def _switch_to_target_mode(self):
        return self.set_tgt_lang_special_tokens(self.tgt_lang)

    def set_src_lang_special_tokens(self, src_lang) -> None:
        
        self.cur_lang_code = self.convert_tokens_to_ids(src_lang)

        if self.cur_lang_code == self.unk_token_id:
            logger.warning_once(
                f"`tgt_lang={src_lang}` has not be found in the `vocabulary`. Behaviour will probably be unexpected because the language token id will be replaced by the unknown token id."
            )

        self.init_kwargs["src_lang"] = src_lang

        self.prefix_tokens = [self.cur_lang_code]
        self.suffix_tokens = [self.eos_token_id]

        prefix_tokens_str = self.convert_ids_to_tokens(self.prefix_tokens)
        suffix_tokens_str = self.convert_ids_to_tokens(self.suffix_tokens)

        self._tokenizer.post_processor = processors.TemplateProcessing(
            single=prefix_tokens_str + ["$A"] + suffix_tokens_str,
            pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str,
            special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str, self.prefix_tokens + self.suffix_tokens)),
        )

    def set_tgt_lang_special_tokens(self, lang: str) -> None:
        
        self.cur_lang_code = self.convert_tokens_to_ids(lang)

        if self.cur_lang_code == self.unk_token_id:
            logger.warning_once(
                f"`tgt_lang={lang}` has not be found in the `vocabulary`. Behaviour will probably be unexpected because the language token id will be replaced by the unknown token id."
            )

        self.init_kwargs["tgt_lang"] = lang

        self.prefix_tokens = [self.eos_token_id, self.cur_lang_code]
        self.suffix_tokens = [self.eos_token_id]

        prefix_tokens_str = self.convert_ids_to_tokens(self.prefix_tokens)
        suffix_tokens_str = self.convert_ids_to_tokens(self.suffix_tokens)

        self._tokenizer.post_processor = processors.TemplateProcessing(
            single=prefix_tokens_str + ["$A"] + suffix_tokens_str,
            pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str,
            special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str, self.prefix_tokens + self.suffix_tokens)),
        )

    
    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
        if not self.can_save_slow_tokenizer:
            raise ValueError(
                "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
                "tokenizer."
            )

        if not os.path.isdir(save_directory):
            logger.error(f"Vocabulary path ({save_directory}) should be a directory.")
            return
        out_vocab_file = os.path.join(
            save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
        )

        if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
            copyfile(self.vocab_file, out_vocab_file)

        return (out_vocab_file,)

    @classmethod
    def _from_pretrained(
        cls,
        resolved_vocab_files,
        pretrained_model_name_or_path,
        init_configuration,
        *init_inputs,
        token=None,
        cache_dir=None,
        local_files_only=False,
        _commit_hash=None,
        _is_local=False,
        **kwargs,
    ):
        tokenizer = super()._from_pretrained(
            resolved_vocab_files,
            pretrained_model_name_or_path,
            init_configuration,
            *init_inputs,
            token=token,
            cache_dir=cache_dir,
            local_files_only=local_files_only,
            _commit_hash=_commit_hash,
            _is_local=_is_local,
            **kwargs,
        )

        
        tokenizer.set_src_lang_special_tokens(tokenizer._src_lang)
        tokenizer.set_tgt_lang_special_tokens(tokenizer._tgt_lang)

        return tokenizer

    def __call__(
        self,
        text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
        text_pair: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None,
        text_target: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
        text_pair_target: Optional[
            Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]
        ] = None,
        padding: Union[bool, str, PaddingStrategy] = True,
        pad_to_multiple_of: Optional[int] = 2,
        src_lang: Optional[str] = None,
        tgt_lang: Optional[str] = None,
        **kwargs,
    ):
        
        if src_lang is not None:
            self.src_lang = src_lang
        if tgt_lang is not None:
            self.tgt_lang = tgt_lang

        output = super().__call__(
            text=text,
            text_pair=text_pair,
            text_target=text_target,
            text_pair_target=text_pair_target,
            padding=padding,
            pad_to_multiple_of=pad_to_multiple_of,
            **kwargs,
        )

        return output