Skip to content

tokenization_utils_fast

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast

Bases: PreTrainedTokenizerBase

Base class for all fast tokenizers (wrapping HuggingFace tokenizers library).

Inherits from [~tokenization_utils_base.PreTrainedTokenizerBase].

Handles all the shared methods for tokenization and special tokens, as well as methods for downloading/caching/loading pretrained tokenizers, as well as adding tokens to the vocabulary.

This class also contains the added tokens in a unified way on top of all tokenizers so we don't have to handle the specific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...).

Source code in mindnlp/transformers/tokenization_utils_fast.py
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
class PreTrainedTokenizerFast(PreTrainedTokenizerBase):
    """
    Base class for all fast tokenizers (wrapping HuggingFace tokenizers library).

    Inherits from [`~tokenization_utils_base.PreTrainedTokenizerBase`].

    Handles all the shared methods for tokenization and special tokens, as well as methods for
    downloading/caching/loading pretrained tokenizers, as well as adding tokens to the vocabulary.

    This class also contains the added tokens in a unified way on top of all tokenizers so we don't have to handle the
    specific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...).
    """
    vocab_files_names = VOCAB_FILES_NAMES
    slow_tokenizer_class: PreTrainedTokenizer = None

    def __init__(self, *args, **kwargs):
        r"""
        Initializes an instance of the PreTrainedTokenizerFast class.

        Args:
            self: The instance of the class.

        Returns:
            None.

        Raises:
            ValueError:
                If the tokenizer cannot be instantiated from any of the following:

                1. A `tokenizers` library serialization file.
                2. A slow tokenizer instance to convert.
                3. An equivalent slow tokenizer class to instantiate and convert.

                You need to have sentencepiece installed to convert a slow tokenizer to a fast one.
            ValueError: If `from_slow` is True, but `slow_tokenizer` is None and `slow_tokenizer_class` is None.
                Also, make sure you have sentencepiece installed if the tokenizer is based on sentencepiece.

        Note:
            This method takes the following optional keyword arguments:

            - `tokenizer_object`: An existing tokenizer object.
            - `__slow_tokenizer`: A slow tokenizer object.
            - `tokenizer_file`: A file containing a serialized tokenizer object.
            - `from_slow`: A boolean indicating whether the tokenizer should be converted from a slow version.
            - `added_tokens_decoder`: A dictionary mapping index to token for additional tokens.

            If `tokenizer_object` is provided, a deep copy of it is used as the fast tokenizer.
            If `fast_tokenizer_file` is provided and `from_slow` is False, the fast tokenizer is loaded from the file.
            If `slow_tokenizer` is provided, it is converted to a fast tokenizer.
            If `slow_tokenizer_class` is provided, it is instantiated and then converted to a fast tokenizer.

            The `kwargs` dictionary is updated with the initialization arguments of the slow tokenizer if `slow_tokenizer` is not None.

            The tokenizer's truncation and padding settings are applied to the `kwargs` dictionary.

            The `added_tokens_decoder` dictionary is used to add additional tokens to the tokenizer.
            Tokens are added in sorted order based on their index, and special tokens are added in a separate step.

            If any tokens are added, they are encoded and added to the tokenizer's encoder.
            Additionally, special tokens that are not present in the encoder or the added tokens are added as well.

            The `added_tokens_decoder` dictionary is updated with the added tokens.

        Example:
            ```python
            >>> tokenizer = PreTrainedTokenizerFast()
            >>> tokenizer.__init__()
            ```

        """
        tokenizer_object = kwargs.pop("tokenizer_object", None)
        slow_tokenizer = kwargs.pop("__slow_tokenizer", None)
        fast_tokenizer_file = kwargs.pop("tokenizer_file", None)
        from_slow = kwargs.pop("from_slow", False)
        added_tokens_decoder = kwargs.pop("added_tokens_decoder", {})

        if from_slow and slow_tokenizer is None and self.slow_tokenizer_class is None:
            raise ValueError(
                "Cannot instantiate this tokenizer from a slow version. If it's based on sentencepiece, make sure you "
                "have sentencepiece installed."
            )

        if tokenizer_object is not None:
            fast_tokenizer = copy.deepcopy(tokenizer_object)
        elif fast_tokenizer_file is not None and not from_slow:
            # We have a serialization from tokenizers which let us directly build the backend
            fast_tokenizer = TokenizerFast.from_file(fast_tokenizer_file)
        elif slow_tokenizer is not None:
            # We need to convert a slow tokenizer to build the backend
            fast_tokenizer = convert_slow_tokenizer(slow_tokenizer)
        elif self.slow_tokenizer_class is not None:
            # We need to create and convert a slow tokenizer to build the backend
            slow_tokenizer = self.slow_tokenizer_class(*args, **kwargs)
            fast_tokenizer = convert_slow_tokenizer(slow_tokenizer)
        else:
            raise ValueError(
                "Couldn't instantiate the backend tokenizer from one of: \n"
                "(1) a `tokenizers` library serialization file, \n"
                "(2) a slow tokenizer instance to convert or \n"
                "(3) an equivalent slow tokenizer class to instantiate and convert. \n"
                "You need to have sentencepiece installed to convert a slow tokenizer to a fast one."
            )

        self._tokenizer = fast_tokenizer

        if slow_tokenizer is not None:
            kwargs.update(slow_tokenizer.init_kwargs)

        self._decode_use_source_tokenizer = False

        _truncation = self._tokenizer.truncation

        if _truncation is not None:
            self._tokenizer.enable_truncation(**_truncation)
            kwargs.setdefault("max_length", _truncation["max_length"])
            kwargs.setdefault("truncation_side", _truncation["direction"])
            kwargs.setdefault("stride", _truncation["stride"])
            kwargs.setdefault("truncation_strategy", _truncation["strategy"])
        else:
            self._tokenizer.no_truncation()

        _padding = self._tokenizer.padding
        if _padding is not None:
            self._tokenizer.enable_padding(**_padding)
            kwargs.setdefault("pad_token", _padding["pad_token"])
            kwargs.setdefault("pad_token_type_id", _padding["pad_type_id"])
            kwargs.setdefault("padding_side", _padding["direction"])
            kwargs.setdefault("max_length", _padding["length"])
            kwargs.setdefault("pad_to_multiple_of", _padding["pad_to_multiple_of"])

        # We call this after having initialized the backend tokenizer because we update it.
        super().__init__(**kwargs)

        # The following logic will be replace with a single add_tokens once a fix is pushed to tokenizers
        # allows converting a slow -> fast, non-legacy: if the `tokenizer.json` does not have all the added tokens
        # uses the information stored in `added_tokens_decoder`.
        # this is costly for fast tokenizers as we re-compute the regex again. But not all tokens are added tokens
        tokens_to_add = [
            token
            for index, token in sorted(added_tokens_decoder.items(), key=lambda x: x[0])
            if token not in self.added_tokens_decoder
        ]
        encoder = list(self.added_tokens_encoder.keys()) + [str(token) for token in tokens_to_add]
        # if some of the special tokens are strings, we check if we don't already have a token
        tokens_to_add += [
            token for token in self.all_special_tokens_extended if token not in encoder and token not in tokens_to_add
        ]
        if len(tokens_to_add) > 0:
            # super hack: if a token.special is set, tokenizer ignores it for now so FIXME @ArthurZ
            # Accumulate added tokens into batches of special/non-special tokens, because calling add_tokens() for
            # individual tokens would repeatedly rebuild a trie, which can be slow.
            is_last_special = None
            tokens = []
            special_tokens = self.all_special_tokens
            for token in tokens_to_add:
                is_special = (
                    (token.special or str(token) in special_tokens)
                    if isinstance(token, AddedToken)
                    else str(token) in special_tokens
                )
                if is_last_special is None or is_last_special == is_special:
                    tokens.append(token)
                else:
                    self._add_tokens(tokens, special_tokens=is_last_special)
                    tokens = [token]
                is_last_special = is_special
            if tokens:
                self._add_tokens(tokens, special_tokens=is_last_special)

    @property
    def is_fast(self) -> bool:
        r"""
        Method 'is_fast' in the class 'PreTrainedTokenizerFast'.

        Args:
            self: PreTrainedTokenizerFast - The instance of the PreTrainedTokenizerFast class.
                This parameter represents the tokenizer object itself.

        Returns:
            bool:
                A boolean value indicating whether the tokenizer is considered fast.
                Returns True if the tokenizer is fast.

        Raises:
            None.
        """
        return True

    @property
    def can_save_slow_tokenizer(self) -> bool:
        """
        `bool`: Whether or not the slow tokenizer can be saved. Usually for sentencepiece based slow tokenizer, this
        can only be `True` if the original `"sentencepiece.model"` was not deleted.
        """
        return True

    @property
    def vocab_size(self) -> int:
        """
        `int`: Size of the base vocabulary (without the added tokens).
        """
        return self._tokenizer.get_vocab_size(with_added_tokens=False)

    def get_vocab(self) -> Dict[str, int]:
        r"""
        Retrieve the vocabulary of the tokenizer including any added tokens.

        Args:
            self (PreTrainedTokenizerFast): An instance of the PreTrainedTokenizerFast class.
                The tokenizer instance from which to retrieve the vocabulary.

        Returns:
            Dict[str, int]: A dictionary mapping strings (tokens) to integers (indices) representing the vocabulary.
                The keys are token strings and the values are the corresponding indices in the vocabulary.

        Raises:
            None.
        """
        return self._tokenizer.get_vocab(with_added_tokens=True)

    @property
    def vocab(self) -> Dict[str, int]:
        r"""
        This method retrieves the vocabulary of the `PreTrainedTokenizerFast` class instance.

        Args:
            self: An instance of the `PreTrainedTokenizerFast` class.

        Returns:
            `Dict[str, int]`:
                A dictionary with string keys and integer values representing the vocabulary of the tokenizer.

        Raises:
            None.

        Note:
            The vocabulary is obtained by invoking the `get_vocab()` method of the tokenizer instance.

        Example:
            ```python
            >>> tokenizer = PreTrainedTokenizerFast()
            >>> vocab = tokenizer.vocab()
            >>> print(vocab)
            {'word1': 0, 'word2': 1, 'word3': 2, ...}
            ```
        """
        return self.get_vocab()

    @property
    def added_tokens_encoder(self) -> Dict[str, int]:
        """
        Returns the sorted mapping from string to index. The added tokens encoder is cached for performance
        optimisation in `self._added_tokens_encoder` for the slow tokenizers.
        """
        return {k.content: v for v, k in sorted(self.added_tokens_decoder.items(), key=lambda item: item[0])}

    @property
    def added_tokens_decoder(self) -> Dict[int, AddedToken]:
        """
        Returns the added tokens in the vocabulary as a dictionary of index to AddedToken.

        Returns:
            `Dict[str, int]`: The added tokens.
        """
        return self._tokenizer.get_added_tokens_decoder()

    def get_added_vocab(self) -> Dict[str, int]:
        """
        Returns the added tokens in the vocabulary as a dictionary of token to index.

        Returns:
            `Dict[str, int]`: The added tokens.
        """
        return {k.content: v for v, k in sorted(self.added_tokens_decoder.items(), key=lambda item: item[0])}

    def __len__(self) -> int:
        """
        Size of the full vocabulary with the added tokens.
        """
        return self._tokenizer.get_vocab_size(with_added_tokens=True)

    @property
    def backend_tokenizer(self) -> TokenizerFast:
        """
        `tokenizers.implementations.BaseTokenizer`: The Rust tokenizer used as a backend.
        """
        return self._tokenizer

    @property
    def decoder(self) -> DecoderFast:
        """
        `tokenizers.decoders.Decoder`: The Rust decoder for this tokenizer.
        """
        return self._tokenizer.decoder

    def _convert_encoding(
        self,
        encoding: EncodingFast,
        return_token_type_ids: Optional[bool] = None,
        return_attention_mask: Optional[bool] = None,
        return_overflowing_tokens: bool = False,
        return_special_tokens_mask: bool = False,
        return_offsets_mapping: bool = False,
        return_length: bool = False,
        verbose: bool = True,
    ) -> Tuple[Dict[str, Any], List[EncodingFast]]:
        """
        Convert the encoding representation (from low-level HuggingFace tokenizer output) to a python Dict and a list
        of encodings, take care of building a batch from overflowing tokens.

        Overflowing tokens are converted to additional examples (like batches) so the output values of the dict are
        lists (overflows) of lists (tokens).

        Output shape: (overflows, sequence length)
        """
        if return_token_type_ids is None:
            return_token_type_ids = "token_type_ids" in self.model_input_names
        if return_attention_mask is None:
            return_attention_mask = "attention_mask" in self.model_input_names

        if return_overflowing_tokens and encoding.overflowing is not None:
            encodings = [encoding] + encoding.overflowing
        else:
            encodings = [encoding]

        encoding_dict = defaultdict(list)
        for e in encodings:
            encoding_dict["input_ids"].append(e.ids)

            if return_token_type_ids:
                encoding_dict["token_type_ids"].append(e.type_ids)
            if return_attention_mask:
                encoding_dict["attention_mask"].append(e.attention_mask)
            if return_special_tokens_mask:
                encoding_dict["special_tokens_mask"].append(e.special_tokens_mask)
            if return_offsets_mapping:
                encoding_dict["offset_mapping"].append(e.offsets)
            if return_length:
                encoding_dict["length"].append(len(e.ids))

        return encoding_dict, encodings

    def convert_tokens_to_ids(self, tokens: Union[str, List[str]]) -> Union[int, List[int]]:
        """
        Converts a token string (or a sequence of tokens) in a single integer id (or a sequence of ids), using the
        vocabulary.

        Args:
            tokens (`str` or `List[str]`): One or several token(s) to convert to token id(s).

        Returns:
            `int` or `List[int]`: The token id or list of token ids.
        """
        if tokens is None:
            return None

        if isinstance(tokens, str):
            return self._convert_token_to_id_with_added_voc(tokens)

        return [self._convert_token_to_id_with_added_voc(token) for token in tokens]

    def _convert_token_to_id_with_added_voc(self, token: str) -> int:
        r"""
        Converts a token to its corresponding ID using the provided tokenizer with added vocabulary.

        Args:
            self (PreTrainedTokenizerFast): An instance of the PreTrainedTokenizerFast class.
                This parameter represents the tokenizer object through which the token will be converted to ID.
            token (str): The token to convert to an ID.
                This parameter is a string representing the token that needs to be converted.

        Returns:
            int: The integer ID corresponding to the input token.
                If the token is found in the tokenizer's vocabulary, the method returns the ID associated with the token.
                If the token is not found, the method returns the unknown token ID specified by 'unk_token_id'.

        Raises:
            None.
        """
        index = self._tokenizer.token_to_id(token)
        if index is None:
            return self.unk_token_id
        return index

    def _convert_id_to_token(self, index: int) -> Optional[str]:
        r"""
        Converts an index to a token.

        Args:
            self (PreTrainedTokenizerFast): The instance of the PreTrainedTokenizerFast class.
            index (int): The index to be converted to a token. It should be a non-negative integer.

        Returns:
            Optional[str]: Returns the token corresponding to the given index, or None if the index is out of range.

        Raises:
            ValueError: If the index is negative.
            TypeError: If the index is not an integer.
        """
        return self._tokenizer.id_to_token(int(index))

    def _add_tokens(self, new_tokens: List[Union[str, AddedToken]], special_tokens=False) -> int:
        r"""
        This method adds new tokens to the tokenizer.

        Args:
            self (PreTrainedTokenizerFast): The instance of the PreTrainedTokenizerFast class.
            new_tokens (List[Union[str, AddedToken]]): A list of new tokens to be added to the tokenizer.
                Each token can be either a string or an AddedToken object.
            special_tokens (bool): A flag indicating whether the new tokens are special tokens. Defaults to False.

        Returns:
            int: The number of tokens added to the tokenizer.

        Raises:
            None
        """
        if special_tokens:
            return self._tokenizer.add_special_tokens(new_tokens)

        return self._tokenizer.add_tokens(new_tokens)

    def num_special_tokens_to_add(self, pair: bool = False) -> int:
        """
        Returns the number of added tokens when encoding a sequence with special tokens.

        <Tip>

        This encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put
        this inside your training loop.

        </Tip>

        Args:
            pair (`bool`, *optional*, defaults to `False`):
                Whether the number of added tokens should be computed in the case of a sequence pair or a single
                sequence.

        Returns:
            `int`: Number of special tokens added to sequences.
        """
        return self._tokenizer.num_special_tokens_to_add(pair)

    def convert_ids_to_tokens(
        self, ids: Union[int, List[int]], skip_special_tokens: bool = False
    ) -> Union[str, List[str]]:
        """
        Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and
        added tokens.

        Args:
            ids (`int` or `List[int]`):
                The token id (or token ids) to convert to tokens.
            skip_special_tokens (`bool`, *optional*, defaults to `False`):
                Whether or not to remove special tokens in the decoding.

        Returns:
            `str` or `List[str]`: The decoded token(s).
        """
        if isinstance(ids, int):
            return self._tokenizer.id_to_token(ids)
        tokens = []
        for index in ids:
            index = int(index)
            if skip_special_tokens and index in self.all_special_ids:
                continue
            tokens.append(self._tokenizer.id_to_token(index))
        return tokens

    def tokenize(self, text: str, pair: Optional[str] = None, add_special_tokens: bool = False, **kwargs) -> List[str]:
        r"""
        '''
        Tokenizes the given text into a list of strings.

        Args:
            text (str): The input text to be tokenized.
            pair (Optional[str]): The optional second input text to be tokenized in pair with the first text. Defaults to None.
            add_special_tokens (bool): A flag indicating whether to add special tokens during tokenization. Defaults to False.
            **kwargs: Additional keyword arguments for tokenization.

        Returns:
            List[str]: A list of strings representing the tokenized text.

        Raises:
            None.
        '''
        """
        return self.encode_plus(text=text, text_pair=pair, add_special_tokens=add_special_tokens, **kwargs).tokens()

    def set_truncation_and_padding(
        self,
        padding_strategy: PaddingStrategy,
        truncation_strategy: TruncationStrategy,
        max_length: int,
        stride: int,
        pad_to_multiple_of: Optional[int],
    ):
        """
        Define the truncation and the padding strategies for fast tokenizers (provided by HuggingFace tokenizers
        library) and restore the tokenizer settings afterwards.

        The provided tokenizer has no padding / truncation strategy before the managed section. If your tokenizer set a
        padding / truncation strategy before, then it will be reset to no padding / truncation when exiting the managed
        section.

        Args:
            padding_strategy ([`~utils.PaddingStrategy`]):
                The kind of padding that will be applied to the input
            truncation_strategy ([`~tokenization_utils_base.TruncationStrategy`]):
                The kind of truncation that will be applied to the input
            max_length (`int`):
                The maximum size of a sequence.
            stride (`int`):
                The stride to use when handling overflow.
            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).
        """
        _truncation = self._tokenizer.truncation
        _padding = self._tokenizer.padding
        # Set truncation and padding on the backend tokenizer
        if truncation_strategy == TruncationStrategy.DO_NOT_TRUNCATE:
            if _truncation is not None:
                self._tokenizer.no_truncation()
        else:
            target = {
                "max_length": max_length,
                "stride": stride,
                "strategy": truncation_strategy.value,
                "direction": self.truncation_side,
            }

            # _truncation might contain more keys that the target `transformers`
            # supports. Use only the target keys to trigger `enable_truncation`.
            # This should enable this code to works on various `tokenizers`
            # targets.
            if _truncation is None:
                current = None
            else:
                current = {k: _truncation.get(k, None) for k in target}

            if current != target:
                self._tokenizer.enable_truncation(**target)

        if padding_strategy == PaddingStrategy.DO_NOT_PAD:
            if _padding is not None:
                self._tokenizer.no_padding()
        else:
            length = max_length if padding_strategy == PaddingStrategy.MAX_LENGTH else None
            target = {
                "length": length,
                "direction": self.padding_side,
                "pad_id": self.pad_token_id,
                "pad_token": self.pad_token,
                "pad_type_id": self.pad_token_type_id,
                "pad_to_multiple_of": pad_to_multiple_of,
            }
            if _padding != target:
                self._tokenizer.enable_padding(**target)

    def _batch_encode_plus(
        self,
        batch_text_or_text_pairs: Union[
            List[TextInput], List[TextInputPair], List[PreTokenizedInput], List[PreTokenizedInputPair]
        ],
        add_special_tokens: bool = True,
        padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
        truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
        max_length: Optional[int] = None,
        stride: int = 0,
        is_split_into_words: bool = False,
        pad_to_multiple_of: Optional[int] = None,
        return_tensors: Optional[str] = None,
        return_token_type_ids: Optional[bool] = None,
        return_attention_mask: Optional[bool] = None,
        return_overflowing_tokens: bool = False,
        return_special_tokens_mask: bool = False,
        return_offsets_mapping: bool = False,
        return_length: bool = False,
        verbose: bool = True,
    ) -> BatchEncoding:
        r"""
        This method `_batch_encode_plus` is defined in the class `PreTrainedTokenizerFast`.
        It takes 17 parameters and returns a value of type `BatchEncoding`.

        Args:
            self: An instance of the class `PreTrainedTokenizerFast`.
            batch_text_or_text_pairs (Union[List[TextInput], List[TextInputPair], List[PreTokenizedInput], List[PreTokenizedInputPair]]):
                A list of input texts or text pairs. Each element can be of type `TextInput`, `TextInputPair`,
                `PreTokenizedInput`, or `PreTokenizedInputPair`.
            add_special_tokens (bool, optional): Whether to add special tokens to the encoded sequences. Defaults to True.
            padding_strategy (PaddingStrategy, optional): The strategy to use for padding. Defaults to `PaddingStrategy.DO_NOT_PAD`.
            truncation_strategy (TruncationStrategy, optional): The strategy to use for truncation. Defaults to `TruncationStrategy.DO_NOT_TRUNCATE`.
            max_length (int, optional): The maximum length of the encoded sequences. Defaults to None.
            stride (int, optional): The stride to use for overflowing tokens when truncation is enabled. Defaults to 0.
            is_split_into_words (bool, optional): Whether the input is already tokenized into words. Defaults to False.
            pad_to_multiple_of (int, optional): Pad the sequence length to a multiple of this value. Defaults to None.
            return_tensors (str, optional): The type of tensor to return. Defaults to None.
            return_token_type_ids (bool, optional): Whether to return token type IDs. Defaults to None.
            return_attention_mask (bool, optional): Whether to return attention masks. Defaults to None.
            return_overflowing_tokens (bool, optional): Whether to return overflowing tokens. Defaults to False.
            return_special_tokens_mask (bool, optional): Whether to return special tokens mask. Defaults to False.
            return_offsets_mapping (bool, optional): Whether to return offsets mapping. Defaults to False.
            return_length (bool, optional): Whether to return the length of each sequence. Defaults to False.
            verbose (bool, optional): Whether to display verbose information. Defaults to True.

        Returns:
            BatchEncoding: An object containing the sanitized tokens and encodings of the input sequences.

        Raises:
            TypeError: If `batch_text_or_text_pairs` is not a list or tuple.

        """
        if not isinstance(batch_text_or_text_pairs, (tuple, list)):
            raise TypeError(
                f"batch_text_or_text_pairs has to be a list or a tuple (got {type(batch_text_or_text_pairs)})"
            )

        # Set the truncation and padding strategy and restore the initial configuration
        self.set_truncation_and_padding(
            padding_strategy=padding_strategy,
            truncation_strategy=truncation_strategy,
            max_length=max_length,
            stride=stride,
            pad_to_multiple_of=pad_to_multiple_of,
        )

        encodings = self._tokenizer.encode_batch(
            batch_text_or_text_pairs,
            add_special_tokens=add_special_tokens,
            is_pretokenized=is_split_into_words,
        )

        # Convert encoding to dict
        # `Tokens` has type: Tuple[
        #                       List[Dict[str, List[List[int]]]] or List[Dict[str, 2D-Tensor]],
        #                       List[EncodingFast]
        #                    ]
        # with nested dimensions corresponding to batch, overflows, sequence length
        tokens_and_encodings = [
            self._convert_encoding(
                encoding=encoding,
                return_token_type_ids=return_token_type_ids,
                return_attention_mask=return_attention_mask,
                return_overflowing_tokens=return_overflowing_tokens,
                return_special_tokens_mask=return_special_tokens_mask,
                return_offsets_mapping=return_offsets_mapping,
                return_length=return_length,
                verbose=verbose,
            )
            for encoding in encodings
        ]

        # Convert the output to have dict[list] from list[dict] and remove the additional overflows dimension
        # From (variable) shape (batch, overflows, sequence length) to ~ (batch * overflows, sequence length)
        # (we say ~ because the number of overflow varies with the example in the batch)
        #
        # To match each overflowing sample with the original sample in the batch
        # we add an overflow_to_sample_mapping array (see below)
        sanitized_tokens = {}
        for key in tokens_and_encodings[0][0].keys():
            stack = [e for item, _ in tokens_and_encodings for e in item[key]]
            sanitized_tokens[key] = stack
        sanitized_encodings = [e for _, item in tokens_and_encodings for e in item]

        # If returning overflowing tokens, we need to return a mapping
        # from the batch idx to the original sample
        if return_overflowing_tokens:
            overflow_to_sample_mapping = []
            for i, (toks, _) in enumerate(tokens_and_encodings):
                overflow_to_sample_mapping += [i] * len(toks["input_ids"])
            sanitized_tokens["overflow_to_sample_mapping"] = overflow_to_sample_mapping

        for input_ids in sanitized_tokens["input_ids"]:
            self._eventual_warn_about_too_long_sequence(input_ids, max_length, verbose)
        return BatchEncoding(sanitized_tokens, sanitized_encodings, tensor_type=return_tensors)

    def _encode_plus(
        self,
        text: Union[TextInput, PreTokenizedInput],
        text_pair: Optional[Union[TextInput, PreTokenizedInput]] = None,
        add_special_tokens: bool = True,
        padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
        truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
        max_length: Optional[int] = None,
        stride: int = 0,
        is_split_into_words: bool = False,
        pad_to_multiple_of: Optional[int] = None,
        return_tensors: Optional[bool] = None,
        return_token_type_ids: Optional[bool] = None,
        return_attention_mask: Optional[bool] = None,
        return_overflowing_tokens: bool = False,
        return_special_tokens_mask: bool = False,
        return_offsets_mapping: bool = False,
        return_length: bool = False,
        verbose: bool = True,
        **kwargs,
    ) -> BatchEncoding:
        r"""
        This method encodes the input text or pair of texts and returns a BatchEncoding object containing the encoded
        inputs along with additional information.

        Args:
            self: The instance of the class.
            text: The input text to be encoded. It can be either a string or a list of tokens.
            text_pair: (Optional) The second input text to be encoded in case of pair encoding. It can be either a string or a list of tokens. Defaults to None.
            add_special_tokens: A boolean indicating whether to add special tokens to the encoded inputs. Defaults to True.
            padding_strategy: An enum from PaddingStrategy indicating the padding strategy to be applied during encoding. Defaults to PaddingStrategy.DO_NOT_PAD.
            truncation_strategy: An enum from TruncationStrategy indicating the truncation strategy to be applied during encoding. Defaults to TruncationStrategy.DO_NOT_TRUNCATE.
            max_length: (Optional) The maximum length of the encoded sequence. Defaults to None.
            stride: The stride to use when applying truncation. Defaults to 0.
            is_split_into_words: A boolean indicating whether the input text is already pre-tokenized into words. Defaults to False.
            pad_to_multiple_of: (Optional) The resulting tensor will be padded to be a multiple of pad_to_multiple_of. Defaults to None.
            return_tensors: (Optional) A boolean indicating whether to return tensors instead of lists of integers. Defaults to None.
            return_token_type_ids: (Optional) A boolean indicating whether to return token type ids. Defaults to None.
            return_attention_mask: (Optional) A boolean indicating whether to return attention masks. Defaults to None.
            return_overflowing_tokens: A boolean indicating whether to return overflowing tokens information. Defaults to False.
            return_special_tokens_mask: A boolean indicating whether to return special tokens masks. Defaults to False.
            return_offsets_mapping: A boolean indicating whether to return the offsets mapping. Defaults to False.
            return_length: A boolean indicating whether to return the length of the encoded inputs. Defaults to False.
            verbose: A boolean indicating whether to display verbose logs. Defaults to True.
            **kwargs: Additional keyword arguments to be passed to the underlying encoding method.

        Returns:
            `BatchEncoding`
                A BatchEncoding object containing the encoded inputs and additional information such as
                token type ids, attention masks, special tokens masks, offsets mapping, and length of the encoded inputs.

        Raises:
            None
        """
        batched_input = [(text, text_pair)] if text_pair else [text]
        batched_output = self._batch_encode_plus(
            batched_input,
            is_split_into_words=is_split_into_words,
            add_special_tokens=add_special_tokens,
            padding_strategy=padding_strategy,
            truncation_strategy=truncation_strategy,
            max_length=max_length,
            stride=stride,
            pad_to_multiple_of=pad_to_multiple_of,
            return_tensors=return_tensors,
            return_token_type_ids=return_token_type_ids,
            return_attention_mask=return_attention_mask,
            return_overflowing_tokens=return_overflowing_tokens,
            return_special_tokens_mask=return_special_tokens_mask,
            return_offsets_mapping=return_offsets_mapping,
            return_length=return_length,
            verbose=verbose,
            **kwargs,
        )

        # Return tensor is None, then we can remove the leading batch axis
        # Overflowing tokens are returned as a batch of output so we keep them in this case
        if return_tensors is None and not return_overflowing_tokens:
            batched_output = BatchEncoding(
                {
                    key: value[0] if len(value) > 0 and isinstance(value[0], list) else value
                    for key, value in batched_output.items()
                },
                batched_output.encodings,
            )

        self._eventual_warn_about_too_long_sequence(batched_output["input_ids"], max_length, verbose)

        return batched_output

    def convert_tokens_to_string(self, tokens: List[str]) -> str:
        r"""
        Converts a list of tokens into a string representation using the backend tokenizer's decoder.

        Args:
            self (PreTrainedTokenizerFast): An instance of the PreTrainedTokenizerFast class.
            tokens (List[str]): A list of tokens to be converted into a string.

        Returns:
            str: A string representation of the input tokens after decoding.

        Raises:
            None
        """
        return self.backend_tokenizer.decoder.decode(tokens)

    def _decode(
        self,
        token_ids: Union[int, List[int]],
        skip_special_tokens: bool = False,
        clean_up_tokenization_spaces: bool = None,
        **kwargs,
    ) -> str:
        r"""
        Decodes a list of token IDs into a string representation using the tokenizer.

        Args:
            self (PreTrainedTokenizerFast): An instance of the PreTrainedTokenizerFast class.
            token_ids (Union[int, List[int]]): A single token ID or a list of token IDs.
            skip_special_tokens (bool, optional): Whether to skip special tokens during decoding. Defaults to False.
            clean_up_tokenization_spaces (bool, optional): Whether to clean up tokenization spaces.
                If set to None, the value from self.clean_up_tokenization_spaces is used. Defaults to None.
            **kwargs: Additional keyword arguments.

        Returns:
            str: The decoded text representation of the input token IDs.

        Raises:
            None

        Note:
            - If token_ids is an integer, it is converted to a list containing that integer.
            - The use_source_tokenizer argument can be passed as a keyword argument in kwargs to enable/disable
            using the source tokenizer for decoding.
            - If clean_up_tokenization_spaces is True, the resulting text will have any extra spaces introduced during
            tokenization removed by calling the clean_up_tokenization() method.

        Example:
            ```python
            >>> tokenizer = PreTrainedTokenizerFast(...)
            >>> input_ids = tokenizer.encode("Hello, world!")
            >>> tokenizer._decode(input_ids)
            'Hello, world!'
            >>> tokenizer._decode(input_ids, skip_special_tokens=True)
            'Hello, world!'
            >>> tokenizer._decode(10)
            '10'
            >>> tokenizer._decode(10, clean_up_tokenization_spaces=True)
            '10'
            ```
        """
        self._decode_use_source_tokenizer = kwargs.pop("use_source_tokenizer", False)

        if isinstance(token_ids, int):
            token_ids = [token_ids]
        text = self._tokenizer.decode(token_ids, skip_special_tokens=skip_special_tokens)

        clean_up_tokenization_spaces = (
            clean_up_tokenization_spaces
            if clean_up_tokenization_spaces is not None
            else self.clean_up_tokenization_spaces
        )
        if clean_up_tokenization_spaces:
            clean_text = self.clean_up_tokenization(text)
            return clean_text
        return text

    def _save_pretrained(
        self,
        save_directory: Union[str, os.PathLike],
        file_names: Tuple[str],
        legacy_format: Optional[bool] = None,
        filename_prefix: Optional[str] = None,
    ) -> Tuple[str]:
        """
        Save a tokenizer using the slow-tokenizer/legacy format: vocabulary + added tokens as well as in a unique JSON
        file containing {config + vocab + added-tokens}.
        """
        save_directory = str(save_directory)

        if self.slow_tokenizer_class is None and legacy_format is True:
            raise ValueError(
                "Your tokenizer does not have a legacy version defined and therefore cannot register this version. You"
                " might consider leaving the legacy_format at `None` or setting it to `False`."
            )

        save_slow = (
            (legacy_format is None or legacy_format is True)
            and self.slow_tokenizer_class is not None
            and self.can_save_slow_tokenizer
        )
        save_fast = legacy_format is None or legacy_format is False

        if save_slow:
            added_tokens_file = os.path.join(
                save_directory, (filename_prefix + "-" if filename_prefix else "") + ADDED_TOKENS_FILE
            )
            # make sure to be foward compatible
            added_vocab = {tok: index for tok, index in self.added_tokens_encoder.items() if index >= self.vocab_size}
            if added_vocab:
                with open(added_tokens_file, "w", encoding="utf-8") as f:
                    out_str = json.dumps(added_vocab, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
                    f.write(out_str)

            vocab_files = self.save_vocabulary(save_directory, filename_prefix=filename_prefix)
            file_names = file_names + vocab_files + (added_tokens_file,)

        if save_fast:
            tokenizer_file = os.path.join(
                save_directory, (filename_prefix + "-" if filename_prefix else "") + TOKENIZER_FILE
            )
            self.backend_tokenizer.save(tokenizer_file)
            file_names = file_names + (tokenizer_file,)

        return file_names

    def train_new_from_iterator(
        self,
        text_iterator,
        vocab_size,
        length=None,
        new_special_tokens=None,
        special_tokens_map=None,
        **kwargs,
    ):
        """
        Trains a tokenizer on a new corpus with the same defaults (in terms of special tokens or tokenization pipeline)
        as the current one.

        Args:
            text_iterator (generator of `List[str]`):
                The training corpus. Should be a generator of batches of texts, for instance a list of lists of texts
                if you have everything in memory.
            vocab_size (`int`):
                The size of the vocabulary you want for your tokenizer.
            length (`int`, *optional*):
                The total number of sequences in the iterator. This is used to provide meaningful progress tracking
            new_special_tokens (list of `str` or `AddedToken`, *optional*):
                A list of new special tokens to add to the tokenizer you are training.
            special_tokens_map (`Dict[str, str]`, *optional*):
                If you want to rename some of the special tokens this tokenizer uses, pass along a mapping old special
                token name to new special token name in this argument.
            kwargs (`Dict[str, Any]`, *optional*):
                Additional keyword arguments passed along to the trainer from the πŸ€— Tokenizers library.

        Returns:
            [`PreTrainedTokenizerFast`]:
                A new tokenizer of the same type as the original one, trained on `text_iterator`.

        """
        tokenizer_json = json.loads(self._tokenizer.to_str())
        # Remove added tokens for now (uses IDs of tokens)
        added_tokens = tokenizer_json.pop("added_tokens")
        # Remove post processor for now (uses IDs of tokens)
        post_processor = tokenizer_json.pop("post_processor")

        unk_token = None
        # Remove vocab
        if tokenizer_json["model"]["type"] == "BPE":
            tokenizer_json["model"]["vocab"] = {}
            tokenizer_json["model"]["merges"] = []
        elif tokenizer_json["model"]["type"] == "Unigram":
            if tokenizer_json["model"]["unk_id"] is not None:
                unk_id = tokenizer_json["model"]["unk_id"]
                unk_token = tokenizer_json["model"]["vocab"][unk_id][0]
                if special_tokens_map is not None and unk_token in special_tokens_map:
                    unk_token = special_tokens_map[unk_token]
                tokenizer_json["model"]["unk_id"] = 0
                tokenizer_json["model"]["vocab"] = [[unk_token, 0.0]]
        elif tokenizer_json["model"]["type"] in ["WordLevel", "WordPiece"]:
            tokenizer_json["model"]["vocab"] = {}
        else:
            raise ValueError(
                f"This method does not support this type of tokenizer (found {tokenizer_json['model']['type']}) "
                "only BPE, Unigram, WordLevel and WordPiece."
            )

        if (
            special_tokens_map is not None
            and "unk_token" in tokenizer_json["model"]
            and tokenizer_json["model"]["unk_token"] in special_tokens_map
        ):
            tokenizer_json["model"]["unk_token"] = special_tokens_map[tokenizer_json["model"]["unk_token"]]

        tokenizer = TokenizerFast.from_str(json.dumps(tokenizer_json))

        # Get the special tokens from the current tokenizer if none are specified.
        special_tokens = []
        for added_token in added_tokens:
            special = added_token.pop("special", None)
            _ = added_token.pop("id", None)
            if tokenizer_json["model"]["type"] != "Unigram" and not special:
                continue
            if special_tokens_map is not None and added_token["content"] in special_tokens_map:
                added_token["content"] = special_tokens_map[added_token["content"]]
            special_tokens.append(AddedToken(**added_token))

        if new_special_tokens is not None:
            special_tokens.extend(new_special_tokens)

        # Trainer needs to know the end of word / continuing subword thingies in BPE
        if (
            tokenizer_json["model"]["type"] == "BPE"
            and "continuing_subword_prefix" not in kwargs
            and tokenizer_json["model"]["continuing_subword_prefix"] is not None
        ):
            kwargs["continuing_subword_prefix"] = tokenizer_json["model"]["continuing_subword_prefix"]
        if (
            tokenizer_json["model"]["type"] == "BPE"
            and "end_of_word_suffix" not in kwargs
            and tokenizer_json["model"]["end_of_word_suffix"] is not None
        ):
            kwargs["end_of_word_suffix"] = tokenizer_json["model"]["end_of_word_suffix"]
        if tokenizer_json["model"]["type"] == "Unigram" and unk_token is not None:
            kwargs["unk_token"] = unk_token
        if tokenizer_json["pre_tokenizer"] is not None and tokenizer_json["pre_tokenizer"]["type"] == "ByteLevel":
            kwargs["initial_alphabet"] = pre_tokenizers_fast.ByteLevel.alphabet()

        trainer_class = MODEL_TO_TRAINER_MAPPING[tokenizer_json["model"]["type"]]
        trainer = trainer_class(vocab_size=vocab_size, special_tokens=special_tokens, **kwargs)
        tokenizer.train_from_iterator(text_iterator, length=length, trainer=trainer)

        if post_processor is not None:
            trained_tokenizer_json = json.loads(tokenizer.to_str())
            # Almost done, we just have to adjust the token IDs in the post processor
            if "special_tokens" in post_processor:
                for key in post_processor["special_tokens"]:
                    tokens = post_processor["special_tokens"][key]["tokens"]
                    if special_tokens_map is not None:
                        tokens = [special_tokens_map.get(token, token) for token in tokens]
                    post_processor["special_tokens"][key]["tokens"] = tokens
                    post_processor["special_tokens"][key]["ids"] = [tokenizer.token_to_id(token) for token in tokens]

            for special_token in ["cls", "sep"]:
                if special_token in post_processor:
                    token, _ = post_processor[special_token]
                    if special_tokens_map is not None and token in special_tokens_map:
                        token = special_tokens_map[token]
                    token_id = tokenizer.token_to_id(token)
                    post_processor[special_token] = [token, token_id]

            trained_tokenizer_json["post_processor"] = post_processor
            tokenizer = TokenizerFast.from_str(json.dumps(trained_tokenizer_json))

        kwargs = self.init_kwargs.copy()
        # Map pad/cls/mask token at the Transformers level
        special_tokens_list = SpecialTokensMixin.SPECIAL_TOKENS_ATTRIBUTES.copy()
        special_tokens_list.remove("additional_special_tokens")
        for token in special_tokens_list:
            # Get the private one to avoid unnecessary warnings.
            if getattr(self, f"_{token}") is not None:
                special_token = getattr(self, token)
                if special_tokens_map is not None and special_token in special_tokens_map:
                    special_token = special_tokens_map[special_token]

                special_token_full = getattr(self, f"_{token}")
                if isinstance(special_token_full, AddedToken):
                    # Create an added token with the same parameters except the content
                    kwargs[token] = AddedToken(
                        special_token,
                        single_word=special_token_full.single_word,
                        lstrip=special_token_full.lstrip,
                        rstrip=special_token_full.rstrip,
                        normalized=special_token_full.normalized,
                        special=True,
                    )
                else:
                    kwargs[token] = special_token

        additional_special_tokens = self.additional_special_tokens
        if new_special_tokens is not None:
            additional_special_tokens.extend(new_special_tokens)
        if len(additional_special_tokens) > 0:
            kwargs["additional_special_tokens"] = additional_special_tokens

        return self.__class__(tokenizer_object=tokenizer, **kwargs)

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.added_tokens_decoder: Dict[int, AddedToken] property

Returns the added tokens in the vocabulary as a dictionary of index to AddedToken.

RETURNS DESCRIPTION
Dict[int, AddedToken]

Dict[str, int]: The added tokens.

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.added_tokens_encoder: Dict[str, int] property

Returns the sorted mapping from string to index. The added tokens encoder is cached for performance optimisation in self._added_tokens_encoder for the slow tokenizers.

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.backend_tokenizer: TokenizerFast property

tokenizers.implementations.BaseTokenizer: The Rust tokenizer used as a backend.

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.can_save_slow_tokenizer: bool property

bool: Whether or not the slow tokenizer can be saved. Usually for sentencepiece based slow tokenizer, this can only be True if the original "sentencepiece.model" was not deleted.

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.decoder: DecoderFast property

tokenizers.decoders.Decoder: The Rust decoder for this tokenizer.

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.is_fast: bool property

Method 'is_fast' in the class 'PreTrainedTokenizerFast'.

PARAMETER DESCRIPTION
self

PreTrainedTokenizerFast - The instance of the PreTrainedTokenizerFast class. This parameter represents the tokenizer object itself.

RETURNS DESCRIPTION
bool

A boolean value indicating whether the tokenizer is considered fast. Returns True if the tokenizer is fast.

TYPE: bool

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.vocab: Dict[str, int] property

This method retrieves the vocabulary of the PreTrainedTokenizerFast class instance.

PARAMETER DESCRIPTION
self

An instance of the PreTrainedTokenizerFast class.

RETURNS DESCRIPTION
Dict[str, int]

Dict[str, int]: A dictionary with string keys and integer values representing the vocabulary of the tokenizer.

Note

The vocabulary is obtained by invoking the get_vocab() method of the tokenizer instance.

Example
>>> tokenizer = PreTrainedTokenizerFast()
>>> vocab = tokenizer.vocab()
>>> print(vocab)
{'word1': 0, 'word2': 1, 'word3': 2, ...}

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.vocab_size: int property

int: Size of the base vocabulary (without the added tokens).

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.__init__(*args, **kwargs)

Initializes an instance of the PreTrainedTokenizerFast class.

PARAMETER DESCRIPTION
self

The instance of the class.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the tokenizer cannot be instantiated from any of the following:

  1. A tokenizers library serialization file.
  2. A slow tokenizer instance to convert.
  3. An equivalent slow tokenizer class to instantiate and convert.

You need to have sentencepiece installed to convert a slow tokenizer to a fast one.

ValueError

If from_slow is True, but slow_tokenizer is None and slow_tokenizer_class is None. Also, make sure you have sentencepiece installed if the tokenizer is based on sentencepiece.

Note

This method takes the following optional keyword arguments:

  • tokenizer_object: An existing tokenizer object.
  • __slow_tokenizer: A slow tokenizer object.
  • tokenizer_file: A file containing a serialized tokenizer object.
  • from_slow: A boolean indicating whether the tokenizer should be converted from a slow version.
  • added_tokens_decoder: A dictionary mapping index to token for additional tokens.

If tokenizer_object is provided, a deep copy of it is used as the fast tokenizer. If fast_tokenizer_file is provided and from_slow is False, the fast tokenizer is loaded from the file. If slow_tokenizer is provided, it is converted to a fast tokenizer. If slow_tokenizer_class is provided, it is instantiated and then converted to a fast tokenizer.

The kwargs dictionary is updated with the initialization arguments of the slow tokenizer if slow_tokenizer is not None.

The tokenizer's truncation and padding settings are applied to the kwargs dictionary.

The added_tokens_decoder dictionary is used to add additional tokens to the tokenizer. Tokens are added in sorted order based on their index, and special tokens are added in a separate step.

If any tokens are added, they are encoded and added to the tokenizer's encoder. Additionally, special tokens that are not present in the encoder or the added tokens are added as well.

The added_tokens_decoder dictionary is updated with the added tokens.

Example
>>> tokenizer = PreTrainedTokenizerFast()
>>> tokenizer.__init__()
Source code in mindnlp/transformers/tokenization_utils_fast.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
def __init__(self, *args, **kwargs):
    r"""
    Initializes an instance of the PreTrainedTokenizerFast class.

    Args:
        self: The instance of the class.

    Returns:
        None.

    Raises:
        ValueError:
            If the tokenizer cannot be instantiated from any of the following:

            1. A `tokenizers` library serialization file.
            2. A slow tokenizer instance to convert.
            3. An equivalent slow tokenizer class to instantiate and convert.

            You need to have sentencepiece installed to convert a slow tokenizer to a fast one.
        ValueError: If `from_slow` is True, but `slow_tokenizer` is None and `slow_tokenizer_class` is None.
            Also, make sure you have sentencepiece installed if the tokenizer is based on sentencepiece.

    Note:
        This method takes the following optional keyword arguments:

        - `tokenizer_object`: An existing tokenizer object.
        - `__slow_tokenizer`: A slow tokenizer object.
        - `tokenizer_file`: A file containing a serialized tokenizer object.
        - `from_slow`: A boolean indicating whether the tokenizer should be converted from a slow version.
        - `added_tokens_decoder`: A dictionary mapping index to token for additional tokens.

        If `tokenizer_object` is provided, a deep copy of it is used as the fast tokenizer.
        If `fast_tokenizer_file` is provided and `from_slow` is False, the fast tokenizer is loaded from the file.
        If `slow_tokenizer` is provided, it is converted to a fast tokenizer.
        If `slow_tokenizer_class` is provided, it is instantiated and then converted to a fast tokenizer.

        The `kwargs` dictionary is updated with the initialization arguments of the slow tokenizer if `slow_tokenizer` is not None.

        The tokenizer's truncation and padding settings are applied to the `kwargs` dictionary.

        The `added_tokens_decoder` dictionary is used to add additional tokens to the tokenizer.
        Tokens are added in sorted order based on their index, and special tokens are added in a separate step.

        If any tokens are added, they are encoded and added to the tokenizer's encoder.
        Additionally, special tokens that are not present in the encoder or the added tokens are added as well.

        The `added_tokens_decoder` dictionary is updated with the added tokens.

    Example:
        ```python
        >>> tokenizer = PreTrainedTokenizerFast()
        >>> tokenizer.__init__()
        ```

    """
    tokenizer_object = kwargs.pop("tokenizer_object", None)
    slow_tokenizer = kwargs.pop("__slow_tokenizer", None)
    fast_tokenizer_file = kwargs.pop("tokenizer_file", None)
    from_slow = kwargs.pop("from_slow", False)
    added_tokens_decoder = kwargs.pop("added_tokens_decoder", {})

    if from_slow and slow_tokenizer is None and self.slow_tokenizer_class is None:
        raise ValueError(
            "Cannot instantiate this tokenizer from a slow version. If it's based on sentencepiece, make sure you "
            "have sentencepiece installed."
        )

    if tokenizer_object is not None:
        fast_tokenizer = copy.deepcopy(tokenizer_object)
    elif fast_tokenizer_file is not None and not from_slow:
        # We have a serialization from tokenizers which let us directly build the backend
        fast_tokenizer = TokenizerFast.from_file(fast_tokenizer_file)
    elif slow_tokenizer is not None:
        # We need to convert a slow tokenizer to build the backend
        fast_tokenizer = convert_slow_tokenizer(slow_tokenizer)
    elif self.slow_tokenizer_class is not None:
        # We need to create and convert a slow tokenizer to build the backend
        slow_tokenizer = self.slow_tokenizer_class(*args, **kwargs)
        fast_tokenizer = convert_slow_tokenizer(slow_tokenizer)
    else:
        raise ValueError(
            "Couldn't instantiate the backend tokenizer from one of: \n"
            "(1) a `tokenizers` library serialization file, \n"
            "(2) a slow tokenizer instance to convert or \n"
            "(3) an equivalent slow tokenizer class to instantiate and convert. \n"
            "You need to have sentencepiece installed to convert a slow tokenizer to a fast one."
        )

    self._tokenizer = fast_tokenizer

    if slow_tokenizer is not None:
        kwargs.update(slow_tokenizer.init_kwargs)

    self._decode_use_source_tokenizer = False

    _truncation = self._tokenizer.truncation

    if _truncation is not None:
        self._tokenizer.enable_truncation(**_truncation)
        kwargs.setdefault("max_length", _truncation["max_length"])
        kwargs.setdefault("truncation_side", _truncation["direction"])
        kwargs.setdefault("stride", _truncation["stride"])
        kwargs.setdefault("truncation_strategy", _truncation["strategy"])
    else:
        self._tokenizer.no_truncation()

    _padding = self._tokenizer.padding
    if _padding is not None:
        self._tokenizer.enable_padding(**_padding)
        kwargs.setdefault("pad_token", _padding["pad_token"])
        kwargs.setdefault("pad_token_type_id", _padding["pad_type_id"])
        kwargs.setdefault("padding_side", _padding["direction"])
        kwargs.setdefault("max_length", _padding["length"])
        kwargs.setdefault("pad_to_multiple_of", _padding["pad_to_multiple_of"])

    # We call this after having initialized the backend tokenizer because we update it.
    super().__init__(**kwargs)

    # The following logic will be replace with a single add_tokens once a fix is pushed to tokenizers
    # allows converting a slow -> fast, non-legacy: if the `tokenizer.json` does not have all the added tokens
    # uses the information stored in `added_tokens_decoder`.
    # this is costly for fast tokenizers as we re-compute the regex again. But not all tokens are added tokens
    tokens_to_add = [
        token
        for index, token in sorted(added_tokens_decoder.items(), key=lambda x: x[0])
        if token not in self.added_tokens_decoder
    ]
    encoder = list(self.added_tokens_encoder.keys()) + [str(token) for token in tokens_to_add]
    # if some of the special tokens are strings, we check if we don't already have a token
    tokens_to_add += [
        token for token in self.all_special_tokens_extended if token not in encoder and token not in tokens_to_add
    ]
    if len(tokens_to_add) > 0:
        # super hack: if a token.special is set, tokenizer ignores it for now so FIXME @ArthurZ
        # Accumulate added tokens into batches of special/non-special tokens, because calling add_tokens() for
        # individual tokens would repeatedly rebuild a trie, which can be slow.
        is_last_special = None
        tokens = []
        special_tokens = self.all_special_tokens
        for token in tokens_to_add:
            is_special = (
                (token.special or str(token) in special_tokens)
                if isinstance(token, AddedToken)
                else str(token) in special_tokens
            )
            if is_last_special is None or is_last_special == is_special:
                tokens.append(token)
            else:
                self._add_tokens(tokens, special_tokens=is_last_special)
                tokens = [token]
            is_last_special = is_special
        if tokens:
            self._add_tokens(tokens, special_tokens=is_last_special)

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.__len__()

Size of the full vocabulary with the added tokens.

Source code in mindnlp/transformers/tokenization_utils_fast.py
345
346
347
348
349
def __len__(self) -> int:
    """
    Size of the full vocabulary with the added tokens.
    """
    return self._tokenizer.get_vocab_size(with_added_tokens=True)

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.convert_ids_to_tokens(ids, skip_special_tokens=False)

Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and added tokens.

PARAMETER DESCRIPTION
ids

The token id (or token ids) to convert to tokens.

TYPE: `int` or `List[int]`

skip_special_tokens

Whether or not to remove special tokens in the decoding.

TYPE: `bool`, *optional*, defaults to `False` DEFAULT: False

RETURNS DESCRIPTION
Union[str, List[str]]

str or List[str]: The decoded token(s).

Source code in mindnlp/transformers/tokenization_utils_fast.py
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
def convert_ids_to_tokens(
    self, ids: Union[int, List[int]], skip_special_tokens: bool = False
) -> Union[str, List[str]]:
    """
    Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and
    added tokens.

    Args:
        ids (`int` or `List[int]`):
            The token id (or token ids) to convert to tokens.
        skip_special_tokens (`bool`, *optional*, defaults to `False`):
            Whether or not to remove special tokens in the decoding.

    Returns:
        `str` or `List[str]`: The decoded token(s).
    """
    if isinstance(ids, int):
        return self._tokenizer.id_to_token(ids)
    tokens = []
    for index in ids:
        index = int(index)
        if skip_special_tokens and index in self.all_special_ids:
            continue
        tokens.append(self._tokenizer.id_to_token(index))
    return tokens

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.convert_tokens_to_ids(tokens)

Converts a token string (or a sequence of tokens) in a single integer id (or a sequence of ids), using the vocabulary.

PARAMETER DESCRIPTION
tokens

One or several token(s) to convert to token id(s).

TYPE: `str` or `List[str]`

RETURNS DESCRIPTION
Union[int, List[int]]

int or List[int]: The token id or list of token ids.

Source code in mindnlp/transformers/tokenization_utils_fast.py
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
def convert_tokens_to_ids(self, tokens: Union[str, List[str]]) -> Union[int, List[int]]:
    """
    Converts a token string (or a sequence of tokens) in a single integer id (or a sequence of ids), using the
    vocabulary.

    Args:
        tokens (`str` or `List[str]`): One or several token(s) to convert to token id(s).

    Returns:
        `int` or `List[int]`: The token id or list of token ids.
    """
    if tokens is None:
        return None

    if isinstance(tokens, str):
        return self._convert_token_to_id_with_added_voc(tokens)

    return [self._convert_token_to_id_with_added_voc(token) for token in tokens]

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.convert_tokens_to_string(tokens)

Converts a list of tokens into a string representation using the backend tokenizer's decoder.

PARAMETER DESCRIPTION
self

An instance of the PreTrainedTokenizerFast class.

TYPE: PreTrainedTokenizerFast

tokens

A list of tokens to be converted into a string.

TYPE: List[str]

RETURNS DESCRIPTION
str

A string representation of the input tokens after decoding.

TYPE: str

Source code in mindnlp/transformers/tokenization_utils_fast.py
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
def convert_tokens_to_string(self, tokens: List[str]) -> str:
    r"""
    Converts a list of tokens into a string representation using the backend tokenizer's decoder.

    Args:
        self (PreTrainedTokenizerFast): An instance of the PreTrainedTokenizerFast class.
        tokens (List[str]): A list of tokens to be converted into a string.

    Returns:
        str: A string representation of the input tokens after decoding.

    Raises:
        None
    """
    return self.backend_tokenizer.decoder.decode(tokens)

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.get_added_vocab()

Returns the added tokens in the vocabulary as a dictionary of token to index.

RETURNS DESCRIPTION
Dict[str, int]

Dict[str, int]: The added tokens.

Source code in mindnlp/transformers/tokenization_utils_fast.py
336
337
338
339
340
341
342
343
def get_added_vocab(self) -> Dict[str, int]:
    """
    Returns the added tokens in the vocabulary as a dictionary of token to index.

    Returns:
        `Dict[str, int]`: The added tokens.
    """
    return {k.content: v for v, k in sorted(self.added_tokens_decoder.items(), key=lambda item: item[0])}

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.get_vocab()

Retrieve the vocabulary of the tokenizer including any added tokens.

PARAMETER DESCRIPTION
self

An instance of the PreTrainedTokenizerFast class. The tokenizer instance from which to retrieve the vocabulary.

TYPE: PreTrainedTokenizerFast

RETURNS DESCRIPTION
Dict[str, int]

Dict[str, int]: A dictionary mapping strings (tokens) to integers (indices) representing the vocabulary. The keys are token strings and the values are the corresponding indices in the vocabulary.

Source code in mindnlp/transformers/tokenization_utils_fast.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def get_vocab(self) -> Dict[str, int]:
    r"""
    Retrieve the vocabulary of the tokenizer including any added tokens.

    Args:
        self (PreTrainedTokenizerFast): An instance of the PreTrainedTokenizerFast class.
            The tokenizer instance from which to retrieve the vocabulary.

    Returns:
        Dict[str, int]: A dictionary mapping strings (tokens) to integers (indices) representing the vocabulary.
            The keys are token strings and the values are the corresponding indices in the vocabulary.

    Raises:
        None.
    """
    return self._tokenizer.get_vocab(with_added_tokens=True)

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.num_special_tokens_to_add(pair=False)

Returns the number of added tokens when encoding a sequence with special tokens.

This encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put this inside your training loop.

PARAMETER DESCRIPTION
pair

Whether the number of added tokens should be computed in the case of a sequence pair or a single sequence.

TYPE: `bool`, *optional*, defaults to `False` DEFAULT: False

RETURNS DESCRIPTION
int

int: Number of special tokens added to sequences.

Source code in mindnlp/transformers/tokenization_utils_fast.py
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
def num_special_tokens_to_add(self, pair: bool = False) -> int:
    """
    Returns the number of added tokens when encoding a sequence with special tokens.

    <Tip>

    This encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put
    this inside your training loop.

    </Tip>

    Args:
        pair (`bool`, *optional*, defaults to `False`):
            Whether the number of added tokens should be computed in the case of a sequence pair or a single
            sequence.

    Returns:
        `int`: Number of special tokens added to sequences.
    """
    return self._tokenizer.num_special_tokens_to_add(pair)

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.set_truncation_and_padding(padding_strategy, truncation_strategy, max_length, stride, pad_to_multiple_of)

Define the truncation and the padding strategies for fast tokenizers (provided by HuggingFace tokenizers library) and restore the tokenizer settings afterwards.

The provided tokenizer has no padding / truncation strategy before the managed section. If your tokenizer set a padding / truncation strategy before, then it will be reset to no padding / truncation when exiting the managed section.

PARAMETER DESCRIPTION
padding_strategy

The kind of padding that will be applied to the input

TYPE: [`~utils.PaddingStrategy`]

truncation_strategy

The kind of truncation that will be applied to the input

TYPE: [`~tokenization_utils_base.TruncationStrategy`]

max_length

The maximum size of a sequence.

TYPE: `int`

stride

The stride to use when handling overflow.

TYPE: `int`

pad_to_multiple_of

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).

TYPE: `int`, *optional*

Source code in mindnlp/transformers/tokenization_utils_fast.py
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
def set_truncation_and_padding(
    self,
    padding_strategy: PaddingStrategy,
    truncation_strategy: TruncationStrategy,
    max_length: int,
    stride: int,
    pad_to_multiple_of: Optional[int],
):
    """
    Define the truncation and the padding strategies for fast tokenizers (provided by HuggingFace tokenizers
    library) and restore the tokenizer settings afterwards.

    The provided tokenizer has no padding / truncation strategy before the managed section. If your tokenizer set a
    padding / truncation strategy before, then it will be reset to no padding / truncation when exiting the managed
    section.

    Args:
        padding_strategy ([`~utils.PaddingStrategy`]):
            The kind of padding that will be applied to the input
        truncation_strategy ([`~tokenization_utils_base.TruncationStrategy`]):
            The kind of truncation that will be applied to the input
        max_length (`int`):
            The maximum size of a sequence.
        stride (`int`):
            The stride to use when handling overflow.
        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).
    """
    _truncation = self._tokenizer.truncation
    _padding = self._tokenizer.padding
    # Set truncation and padding on the backend tokenizer
    if truncation_strategy == TruncationStrategy.DO_NOT_TRUNCATE:
        if _truncation is not None:
            self._tokenizer.no_truncation()
    else:
        target = {
            "max_length": max_length,
            "stride": stride,
            "strategy": truncation_strategy.value,
            "direction": self.truncation_side,
        }

        # _truncation might contain more keys that the target `transformers`
        # supports. Use only the target keys to trigger `enable_truncation`.
        # This should enable this code to works on various `tokenizers`
        # targets.
        if _truncation is None:
            current = None
        else:
            current = {k: _truncation.get(k, None) for k in target}

        if current != target:
            self._tokenizer.enable_truncation(**target)

    if padding_strategy == PaddingStrategy.DO_NOT_PAD:
        if _padding is not None:
            self._tokenizer.no_padding()
    else:
        length = max_length if padding_strategy == PaddingStrategy.MAX_LENGTH else None
        target = {
            "length": length,
            "direction": self.padding_side,
            "pad_id": self.pad_token_id,
            "pad_token": self.pad_token,
            "pad_type_id": self.pad_token_type_id,
            "pad_to_multiple_of": pad_to_multiple_of,
        }
        if _padding != target:
            self._tokenizer.enable_padding(**target)

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.tokenize(text, pair=None, add_special_tokens=False, **kwargs)

''' Tokenizes the given text into a list of strings.

PARAMETER DESCRIPTION
text

The input text to be tokenized.

TYPE: str

pair

The optional second input text to be tokenized in pair with the first text. Defaults to None.

TYPE: Optional[str] DEFAULT: None

add_special_tokens

A flag indicating whether to add special tokens during tokenization. Defaults to False.

TYPE: bool DEFAULT: False

**kwargs

Additional keyword arguments for tokenization.

DEFAULT: {}

RETURNS DESCRIPTION
List[str]

List[str]: A list of strings representing the tokenized text.

'''

Source code in mindnlp/transformers/tokenization_utils_fast.py
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
def tokenize(self, text: str, pair: Optional[str] = None, add_special_tokens: bool = False, **kwargs) -> List[str]:
    r"""
    '''
    Tokenizes the given text into a list of strings.

    Args:
        text (str): The input text to be tokenized.
        pair (Optional[str]): The optional second input text to be tokenized in pair with the first text. Defaults to None.
        add_special_tokens (bool): A flag indicating whether to add special tokens during tokenization. Defaults to False.
        **kwargs: Additional keyword arguments for tokenization.

    Returns:
        List[str]: A list of strings representing the tokenized text.

    Raises:
        None.
    '''
    """
    return self.encode_plus(text=text, text_pair=pair, add_special_tokens=add_special_tokens, **kwargs).tokens()

mindnlp.transformers.tokenization_utils_fast.PreTrainedTokenizerFast.train_new_from_iterator(text_iterator, vocab_size, length=None, new_special_tokens=None, special_tokens_map=None, **kwargs)

Trains a tokenizer on a new corpus with the same defaults (in terms of special tokens or tokenization pipeline) as the current one.

PARAMETER DESCRIPTION
text_iterator

The training corpus. Should be a generator of batches of texts, for instance a list of lists of texts if you have everything in memory.

TYPE: generator of `List[str]`

vocab_size

The size of the vocabulary you want for your tokenizer.

TYPE: `int`

length

The total number of sequences in the iterator. This is used to provide meaningful progress tracking

TYPE: `int`, *optional* DEFAULT: None

new_special_tokens

A list of new special tokens to add to the tokenizer you are training.

TYPE: list of `str` or `AddedToken`, *optional* DEFAULT: None

special_tokens_map

If you want to rename some of the special tokens this tokenizer uses, pass along a mapping old special token name to new special token name in this argument.

TYPE: `Dict[str, str]`, *optional* DEFAULT: None

kwargs

Additional keyword arguments passed along to the trainer from the πŸ€— Tokenizers library.

TYPE: `Dict[str, Any]`, *optional* DEFAULT: {}

RETURNS DESCRIPTION

[PreTrainedTokenizerFast]: A new tokenizer of the same type as the original one, trained on text_iterator.

Source code in mindnlp/transformers/tokenization_utils_fast.py
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
def train_new_from_iterator(
    self,
    text_iterator,
    vocab_size,
    length=None,
    new_special_tokens=None,
    special_tokens_map=None,
    **kwargs,
):
    """
    Trains a tokenizer on a new corpus with the same defaults (in terms of special tokens or tokenization pipeline)
    as the current one.

    Args:
        text_iterator (generator of `List[str]`):
            The training corpus. Should be a generator of batches of texts, for instance a list of lists of texts
            if you have everything in memory.
        vocab_size (`int`):
            The size of the vocabulary you want for your tokenizer.
        length (`int`, *optional*):
            The total number of sequences in the iterator. This is used to provide meaningful progress tracking
        new_special_tokens (list of `str` or `AddedToken`, *optional*):
            A list of new special tokens to add to the tokenizer you are training.
        special_tokens_map (`Dict[str, str]`, *optional*):
            If you want to rename some of the special tokens this tokenizer uses, pass along a mapping old special
            token name to new special token name in this argument.
        kwargs (`Dict[str, Any]`, *optional*):
            Additional keyword arguments passed along to the trainer from the πŸ€— Tokenizers library.

    Returns:
        [`PreTrainedTokenizerFast`]:
            A new tokenizer of the same type as the original one, trained on `text_iterator`.

    """
    tokenizer_json = json.loads(self._tokenizer.to_str())
    # Remove added tokens for now (uses IDs of tokens)
    added_tokens = tokenizer_json.pop("added_tokens")
    # Remove post processor for now (uses IDs of tokens)
    post_processor = tokenizer_json.pop("post_processor")

    unk_token = None
    # Remove vocab
    if tokenizer_json["model"]["type"] == "BPE":
        tokenizer_json["model"]["vocab"] = {}
        tokenizer_json["model"]["merges"] = []
    elif tokenizer_json["model"]["type"] == "Unigram":
        if tokenizer_json["model"]["unk_id"] is not None:
            unk_id = tokenizer_json["model"]["unk_id"]
            unk_token = tokenizer_json["model"]["vocab"][unk_id][0]
            if special_tokens_map is not None and unk_token in special_tokens_map:
                unk_token = special_tokens_map[unk_token]
            tokenizer_json["model"]["unk_id"] = 0
            tokenizer_json["model"]["vocab"] = [[unk_token, 0.0]]
    elif tokenizer_json["model"]["type"] in ["WordLevel", "WordPiece"]:
        tokenizer_json["model"]["vocab"] = {}
    else:
        raise ValueError(
            f"This method does not support this type of tokenizer (found {tokenizer_json['model']['type']}) "
            "only BPE, Unigram, WordLevel and WordPiece."
        )

    if (
        special_tokens_map is not None
        and "unk_token" in tokenizer_json["model"]
        and tokenizer_json["model"]["unk_token"] in special_tokens_map
    ):
        tokenizer_json["model"]["unk_token"] = special_tokens_map[tokenizer_json["model"]["unk_token"]]

    tokenizer = TokenizerFast.from_str(json.dumps(tokenizer_json))

    # Get the special tokens from the current tokenizer if none are specified.
    special_tokens = []
    for added_token in added_tokens:
        special = added_token.pop("special", None)
        _ = added_token.pop("id", None)
        if tokenizer_json["model"]["type"] != "Unigram" and not special:
            continue
        if special_tokens_map is not None and added_token["content"] in special_tokens_map:
            added_token["content"] = special_tokens_map[added_token["content"]]
        special_tokens.append(AddedToken(**added_token))

    if new_special_tokens is not None:
        special_tokens.extend(new_special_tokens)

    # Trainer needs to know the end of word / continuing subword thingies in BPE
    if (
        tokenizer_json["model"]["type"] == "BPE"
        and "continuing_subword_prefix" not in kwargs
        and tokenizer_json["model"]["continuing_subword_prefix"] is not None
    ):
        kwargs["continuing_subword_prefix"] = tokenizer_json["model"]["continuing_subword_prefix"]
    if (
        tokenizer_json["model"]["type"] == "BPE"
        and "end_of_word_suffix" not in kwargs
        and tokenizer_json["model"]["end_of_word_suffix"] is not None
    ):
        kwargs["end_of_word_suffix"] = tokenizer_json["model"]["end_of_word_suffix"]
    if tokenizer_json["model"]["type"] == "Unigram" and unk_token is not None:
        kwargs["unk_token"] = unk_token
    if tokenizer_json["pre_tokenizer"] is not None and tokenizer_json["pre_tokenizer"]["type"] == "ByteLevel":
        kwargs["initial_alphabet"] = pre_tokenizers_fast.ByteLevel.alphabet()

    trainer_class = MODEL_TO_TRAINER_MAPPING[tokenizer_json["model"]["type"]]
    trainer = trainer_class(vocab_size=vocab_size, special_tokens=special_tokens, **kwargs)
    tokenizer.train_from_iterator(text_iterator, length=length, trainer=trainer)

    if post_processor is not None:
        trained_tokenizer_json = json.loads(tokenizer.to_str())
        # Almost done, we just have to adjust the token IDs in the post processor
        if "special_tokens" in post_processor:
            for key in post_processor["special_tokens"]:
                tokens = post_processor["special_tokens"][key]["tokens"]
                if special_tokens_map is not None:
                    tokens = [special_tokens_map.get(token, token) for token in tokens]
                post_processor["special_tokens"][key]["tokens"] = tokens
                post_processor["special_tokens"][key]["ids"] = [tokenizer.token_to_id(token) for token in tokens]

        for special_token in ["cls", "sep"]:
            if special_token in post_processor:
                token, _ = post_processor[special_token]
                if special_tokens_map is not None and token in special_tokens_map:
                    token = special_tokens_map[token]
                token_id = tokenizer.token_to_id(token)
                post_processor[special_token] = [token, token_id]

        trained_tokenizer_json["post_processor"] = post_processor
        tokenizer = TokenizerFast.from_str(json.dumps(trained_tokenizer_json))

    kwargs = self.init_kwargs.copy()
    # Map pad/cls/mask token at the Transformers level
    special_tokens_list = SpecialTokensMixin.SPECIAL_TOKENS_ATTRIBUTES.copy()
    special_tokens_list.remove("additional_special_tokens")
    for token in special_tokens_list:
        # Get the private one to avoid unnecessary warnings.
        if getattr(self, f"_{token}") is not None:
            special_token = getattr(self, token)
            if special_tokens_map is not None and special_token in special_tokens_map:
                special_token = special_tokens_map[special_token]

            special_token_full = getattr(self, f"_{token}")
            if isinstance(special_token_full, AddedToken):
                # Create an added token with the same parameters except the content
                kwargs[token] = AddedToken(
                    special_token,
                    single_word=special_token_full.single_word,
                    lstrip=special_token_full.lstrip,
                    rstrip=special_token_full.rstrip,
                    normalized=special_token_full.normalized,
                    special=True,
                )
            else:
                kwargs[token] = special_token

    additional_special_tokens = self.additional_special_tokens
    if new_special_tokens is not None:
        additional_special_tokens.extend(new_special_tokens)
    if len(additional_special_tokens) > 0:
        kwargs["additional_special_tokens"] = additional_special_tokens

    return self.__class__(tokenizer_object=tokenizer, **kwargs)