test_tokenization_common.py 222 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# coding=utf-8
# Copyright 2019 HuggingFace Inc.
#
# 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.
Aymeric Augustin's avatar
Aymeric Augustin committed
15

16
import inspect
17
import itertools
18
import json
thomwolf's avatar
thomwolf committed
19
import os
20
import pickle
21
import re
Aymeric Augustin's avatar
Aymeric Augustin committed
22
import shutil
23
import tempfile
24
import traceback
Sylvain Gugger's avatar
Sylvain Gugger committed
25
import unittest
26
from collections import OrderedDict
27
from itertools import takewhile
28
from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union
Aymeric Augustin's avatar
Aymeric Augustin committed
29

30
from parameterized import parameterized
31

32
from transformers import (
33
34
    AlbertTokenizer,
    AlbertTokenizerFast,
Sylvain Gugger's avatar
Sylvain Gugger committed
35
    BertTokenizer,
36
    BertTokenizerFast,
37
38
39
    PreTrainedTokenizer,
    PreTrainedTokenizerBase,
    PreTrainedTokenizerFast,
40
    SpecialTokensMixin,
41
42
    Trainer,
    TrainingArguments,
43
    is_flax_available,
44
45
    is_tf_available,
    is_torch_available,
46
    logging,
47
)
48
from transformers.testing_utils import (
49
    check_json_file_has_correct_format,
50
51
    get_tests_dir,
    is_pt_tf_cross_test,
52
    require_jinja,
53
    require_read_token,
54
55
56
    require_tf,
    require_tokenizers,
    require_torch,
57
    run_test_in_subprocess,
58
59
    slow,
)
60
from transformers.tokenization_utils import AddedToken
61

62

63
64
65
66
if is_torch_available():
    import torch.nn as nn


67
if TYPE_CHECKING:
68
    from transformers import PretrainedConfig, PreTrainedModel, TFPreTrainedModel
69
70


71
72
logger = logging.get_logger(__name__)

73
74
NON_ENGLISH_TAGS = ["chinese", "dutch", "french", "finnish", "german", "multilingual"]

75
76
77
78
79
SMALL_TRAINING_CORPUS = [
    ["This is the first sentence.", "This is the second one."],
    ["This sentence (contains #) over symbols and numbers 12 3.", "But not this one."],
]

80
81

def filter_non_english(_, pretrained_name: str):
Patrick von Platen's avatar
Patrick von Platen committed
82
    """Filter all the model for non-english language"""
83
    return not any(lang in pretrained_name for lang in NON_ENGLISH_TAGS)
84
85
86
87
88
89


def filter_roberta_detectors(_, pretrained_name: str):
    return "detector" not in pretrained_name


90
def merge_model_tokenizer_mappings(
LysandreJik's avatar
LysandreJik committed
91
92
93
94
95
96
    model_mapping: Dict["PretrainedConfig", Union["PreTrainedModel", "TFPreTrainedModel"]],
    tokenizer_mapping: Dict["PretrainedConfig", Tuple["PreTrainedTokenizer", "PreTrainedTokenizerFast"]],
) -> Dict[
    Union["PreTrainedTokenizer", "PreTrainedTokenizerFast"],
    Tuple["PretrainedConfig", Union["PreTrainedModel", "TFPreTrainedModel"]],
]:
97
98
99
100
    configurations = list(model_mapping.keys())
    model_tokenizer_mapping = OrderedDict([])

    for configuration in configurations:
101
102
103
104
105
        if configuration in model_mapping and configuration in tokenizer_mapping:
            model = model_mapping[configuration]
            tokenizer = tokenizer_mapping[configuration][0]
            tokenizer_fast = tokenizer_mapping[configuration][1]

106
107
108
            if tokenizer is not None:
                if configuration.__name__.startswith(tokenizer.__name__.replace("Tokenizer", "")):
                    model_tokenizer_mapping.update({tokenizer: (configuration, model)})
109
            if tokenizer_fast is not None:
110
111
                if configuration.__name__.startswith(tokenizer_fast.__name__.replace("TokenizerFast", "")):
                    model_tokenizer_mapping.update({tokenizer_fast: (configuration, model)})
112
113
114
115

    return model_tokenizer_mapping


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
def _test_subword_regularization_tokenizer(in_queue, out_queue, timeout):
    error = None

    try:
        inputs = in_queue.get(timeout=timeout)
        tokenizer = inputs["tokenizer"]
        sp_model_kwargs = inputs["sp_model_kwargs"]
        test_sentencepiece_ignore_case = inputs["test_sentencepiece_ignore_case"]

        unittest.TestCase().assertTrue(hasattr(tokenizer, "sp_model_kwargs"))
        unittest.TestCase().assertIsNotNone(tokenizer.sp_model_kwargs)
        unittest.TestCase().assertTrue(isinstance(tokenizer.sp_model_kwargs, dict))
        unittest.TestCase().assertDictEqual(tokenizer.sp_model_kwargs, sp_model_kwargs)
        check_subword_sampling(tokenizer, test_sentencepiece_ignore_case=test_sentencepiece_ignore_case)

    except Exception:
        error = f"{traceback.format_exc()}"

    results = {"error": error}
    out_queue.put(results, timeout=timeout)
    out_queue.join()


def check_subword_sampling(
    tokenizer: PreTrainedTokenizer,
    text: str = None,
    test_sentencepiece_ignore_case: bool = True,
) -> None:
    """
    Check if the tokenizer generates different results when subword regularization is enabled.

    Subword regularization augments training data with subword sampling.
    This has a random component.

    Args:
        tokenizer: The tokenizer to check.
        text: The text to use for the checks.
        test_sentencepiece_ignore_case: See `TokenizerTesterMixin.test_sentencepiece_ignore_case`.
    """
    text = "This is a test for subword regularization." if text is None else text
    if test_sentencepiece_ignore_case:
        text = text.lower()

    tokens_list = []
    for _ in range(5):
        tokens_list.append(tokenizer.tokenize(text))

    # the list of different pairs of tokens_list
    combinations = itertools.combinations(tokens_list, 2)

    # check of sampling is done
    subword_sampling_found = False
    for combination in combinations:
        if combination[0] != combination[1]:
            subword_sampling_found = True
    unittest.TestCase().assertTrue(subword_sampling_found)

    # check if converting back to original text works
    for tokens in tokens_list:
        if test_sentencepiece_ignore_case:
            unittest.TestCase().assertEqual(text, tokenizer.convert_tokens_to_string(tokens).lower())
        else:
            unittest.TestCase().assertEqual(text, tokenizer.convert_tokens_to_string(tokens))


181
182
class TokenizerTesterMixin:
    tokenizer_class = None
183
    rust_tokenizer_class = None
184
185
    test_slow_tokenizer = True
    test_rust_tokenizer = True
186
    space_between_special_tokens = False
187
188
    from_pretrained_kwargs = None
    from_pretrained_filter = None
189
    from_pretrained_id = None
190
    from_pretrained_vocab_key = "vocab_file"
191
    test_seq2seq = True
192

193
194
195
196
197
198
199
    # set to True to test a sentencepiece tokenizer
    test_sentencepiece = False

    # set to True to ignore casing when testing a sentencepiece tokenizer
    # test_sentencepiece must also be set to True
    test_sentencepiece_ignore_case = False

200
201
202
    def setUp(self) -> None:
        # Tokenizer.filter makes it possible to filter which Tokenizer to case based on all the
        # information available in Tokenizer (name, rust class, python class, vocab key name)
203
204
205
206
207
        self.from_pretrained_id = (
            [self.from_pretrained_id] if isinstance(self.from_pretrained_id, str) else self.from_pretrained_id
        )

        self.tokenizers_list = []
208
        if self.test_rust_tokenizer:
209
            self.tokenizers_list = [
210
211
                (
                    self.rust_tokenizer_class,
212
                    pretrained_id,
213
214
                    self.from_pretrained_kwargs if self.from_pretrained_kwargs is not None else {},
                )
215
                for pretrained_id in self.from_pretrained_id
216
217
218
219
220
            ]
        else:
            self.tokenizers_list = []
        with open(f"{get_tests_dir()}/fixtures/sample_text.txt", encoding="utf-8") as f_data:
            self._data = f_data.read().replace("\n\n", "\n").strip()
221

222
        self.tmpdirname = tempfile.mkdtemp()
223

224
225
    def tearDown(self):
        shutil.rmtree(self.tmpdirname)
226

227
228
229
230
    def get_input_output_texts(self, tokenizer):
        input_txt = self.get_clean_sequence(tokenizer)[0]
        return input_txt, input_txt

231
    def get_clean_sequence(self, tokenizer, with_prefix_space=False, max_length=20, min_length=5) -> Tuple[str, list]:
232
233
234
235
        # the length of the tokenizer does not always represent the tokens that it can encode: what if there are holes?
        toks = [
            (i, tokenizer.decode([i], clean_up_tokenization_spaces=False)) for i in set(tokenizer.get_vocab().values())
        ]
236
237
238
239
        toks = list(filter(lambda t: re.match(r"^[ a-zA-Z]+$", t[1]), toks))
        toks = list(filter(lambda t: [t[0]] == tokenizer.encode(t[1], add_special_tokens=False), toks))
        if max_length is not None and len(toks) > max_length:
            toks = toks[:max_length]
240
241
242
        if min_length is not None and len(toks) < min_length and len(toks) > 0:
            while len(toks) < min_length:
                toks = toks + toks
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
        # toks_str = [t[1] for t in toks]
        toks_ids = [t[0] for t in toks]

        # Ensure consistency
        output_txt = tokenizer.decode(toks_ids, clean_up_tokenization_spaces=False)
        if " " not in output_txt and len(toks_ids) > 1:
            output_txt = (
                tokenizer.decode([toks_ids[0]], clean_up_tokenization_spaces=False)
                + " "
                + tokenizer.decode(toks_ids[1:], clean_up_tokenization_spaces=False)
            )
        if with_prefix_space:
            output_txt = " " + output_txt
        output_ids = tokenizer.encode(output_txt, add_special_tokens=False)
        return output_txt, output_ids

259
    def get_tokenizers(self, fast=True, **kwargs) -> List[PreTrainedTokenizerBase]:
260
        if fast and self.test_rust_tokenizer and self.test_slow_tokenizer:
261
            return [self.get_tokenizer(**kwargs), self.get_rust_tokenizer(**kwargs)]
262
263
264
265
266
267
        elif fast and self.test_rust_tokenizer:
            return [self.get_rust_tokenizer(**kwargs)]
        elif self.test_slow_tokenizer:
            return [self.get_tokenizer(**kwargs)]
        else:
            raise ValueError("This tokenizer class has no tokenizer to be tested.")
268

269
270
    def get_tokenizer(self, **kwargs) -> PreTrainedTokenizer:
        return self.tokenizer_class.from_pretrained(self.tmpdirname, **kwargs)
271

272
    def get_rust_tokenizer(self, **kwargs) -> PreTrainedTokenizerFast:
273
        return self.rust_tokenizer_class.from_pretrained(self.tmpdirname, **kwargs)
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
    def tokenizer_integration_test_util(
        self,
        expected_encoding: Dict,
        model_name: str,
        revision: str = None,
        sequences: List[str] = None,
        decode_kwargs: Dict[str, Any] = None,
        padding: bool = True,
    ):
        """
        Util for integration test.

        Text is tokenized and then reverted back to text. Both results are then checked.

        Args:
            expected_encoding:
                The expected result of the tokenizer output.
            model_name:
                The model name of the tokenizer to load and use.
            revision:
                The full git revision number of the model. This is to pin the
                tokenizer config and to avoid that tests start to fail if the
                config gets changed upstream.
            sequences:
                Can overwrite the texts that are used to check the tokenizer.
                This is useful if the tokenizer supports non english languages
                like france.
            decode_kwargs:
                Additional args for the ``decode`` function which reverts the
                tokenized text back to a string.
            padding:
                Activates and controls padding of the tokenizer.
        """
        decode_kwargs = {} if decode_kwargs is None else decode_kwargs

        if sequences is None:
            sequences = [
                "Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides "
                "general-purpose architectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet...) for Natural "
                "Language Understanding (NLU) and Natural Language Generation (NLG) with over 32+ pretrained "
                "models in 100+ languages and deep interoperability between Jax, PyTorch and TensorFlow.",
                "BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly "
                "conditioning on both left and right context in all layers.",
                "The quick brown fox jumps over the lazy dog.",
            ]

321
322
323
        if self.test_sentencepiece_ignore_case:
            sequences = [sequence.lower() for sequence in sequences]

324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
        tokenizer_classes = [self.tokenizer_class]
        if self.test_rust_tokenizer:
            tokenizer_classes.append(self.rust_tokenizer_class)

        for tokenizer_class in tokenizer_classes:
            tokenizer = tokenizer_class.from_pretrained(
                model_name,
                revision=revision,  # to pin the tokenizer version
            )

            encoding = tokenizer(sequences, padding=padding)
            decoded_sequences = [
                tokenizer.decode(seq, skip_special_tokens=True, **decode_kwargs) for seq in encoding["input_ids"]
            ]

            encoding_data = encoding.data
            self.assertDictEqual(encoding_data, expected_encoding)

            for expected, decoded in zip(sequences, decoded_sequences):
                if self.test_sentencepiece_ignore_case:
                    expected = expected.lower()
                self.assertEqual(expected, decoded)
thomwolf's avatar
thomwolf committed
346

347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
    def assert_padded_input_match(self, input_r: list, input_p: list, max_length: int, pad_token_id: int):
        # Ensure we match max_length
        self.assertEqual(len(input_r), max_length)
        self.assertEqual(len(input_p), max_length)

        # Ensure the number of padded tokens is the same
        padded_tokens_r = list(takewhile(lambda i: i == pad_token_id, reversed(input_r)))
        padded_tokens_p = list(takewhile(lambda i: i == pad_token_id, reversed(input_p)))
        self.assertSequenceEqual(padded_tokens_r, padded_tokens_p)

    def assert_batch_padded_input_match(
        self,
        input_r: dict,
        input_p: dict,
        max_length: int,
        pad_token_id: int,
        model_main_input_name: str = "input_ids",
    ):
        for i_r in input_r.values():
366
367
368
369
            (
                self.assertEqual(len(i_r), 2),
                self.assertEqual(len(i_r[0]), max_length),
                self.assertEqual(len(i_r[1]), max_length),
370
            )
371
372
373
374
            (
                self.assertEqual(len(i_r), 2),
                self.assertEqual(len(i_r[0]), max_length),
                self.assertEqual(len(i_r[1]), max_length),
375
376
377
378
379
380
381
382
            )

        for i_r, i_p in zip(input_r[model_main_input_name], input_p[model_main_input_name]):
            self.assert_padded_input_match(i_r, i_p, max_length, pad_token_id)

        for i_r, i_p in zip(input_r["attention_mask"], input_p["attention_mask"]):
            self.assertSequenceEqual(i_r, i_p)

383
384
385
    @staticmethod
    def convert_batch_encode_plus_format_to_encode_plus(batch_encode_plus_sequences):
        # Switch from batch_encode_plus format:   {'input_ids': [[...], [...]], ...}
386
        # to the list of examples/ encode_plus format: [{'input_ids': [...], ...}, {'input_ids': [...], ...}]
387
388
        return [
            {value: batch_encode_plus_sequences[value][i] for value in batch_encode_plus_sequences.keys()}
Lysandre Debut's avatar
Lysandre Debut committed
389
            for i in range(len(batch_encode_plus_sequences["input_ids"]))
390
391
        ]

392
393
394
    # TODO: this test can be combined with `test_sentencepiece_tokenize_and_convert_tokens_to_string` after the latter is extended to all tokenizers.
    def test_tokenize_special_tokens(self):
        """Test `tokenize` with special tokens."""
395
        tokenizers = self.get_tokenizers(fast=True, do_lower_case=True)
396
397
398
399
400
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                SPECIAL_TOKEN_1 = "[SPECIAL_TOKEN_1]"
                SPECIAL_TOKEN_2 = "[SPECIAL_TOKEN_2]"

401
                # Both methods should add the token to `_additional_special_tokens` and `added_tokens_decoder`
402
                tokenizer.add_tokens([SPECIAL_TOKEN_1], special_tokens=True)
403
404
405
                tokenizer.add_special_tokens(
                    {"additional_special_tokens": [SPECIAL_TOKEN_2]}, replace_additional_special_tokens=False
                )
406
407
408
409
410
411
412

                token_1 = tokenizer.tokenize(SPECIAL_TOKEN_1)
                token_2 = tokenizer.tokenize(SPECIAL_TOKEN_2)

                self.assertEqual(len(token_1), 1)
                self.assertEqual(len(token_2), 1)
                self.assertEqual(token_1[0], SPECIAL_TOKEN_1)
413
414
                # next is failing for almost all the Fast tokenizers now.
                # self.assertEqual(token_2[0], SPECIAL_TOKEN_2)
415

416
417
418
419
    # TODO: this test could be extended to all tokenizers - not just the sentencepiece
    def test_sentencepiece_tokenize_and_convert_tokens_to_string(self):
        """Test ``_tokenize`` and ``convert_tokens_to_string``."""
        if not self.test_sentencepiece:
amyeroberts's avatar
amyeroberts committed
420
            self.skipTest(reason="test_sentencepiece is set to False")
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439

        tokenizer = self.get_tokenizer()
        text = "This is text to test the tokenizer."

        if self.test_sentencepiece_ignore_case:
            text = text.lower()

        tokens = tokenizer.tokenize(text)

        self.assertTrue(len(tokens) > 0)

        # check if converting back to original text works
        reverse_text = tokenizer.convert_tokens_to_string(tokens)

        if self.test_sentencepiece_ignore_case:
            reverse_text = reverse_text.lower()

        self.assertEqual(reverse_text, text)

440
441
442
443
444
445
446
447
448
449
450
451
        special_tokens = tokenizer.all_special_tokens
        special_tokens_string = tokenizer.convert_tokens_to_string(special_tokens)
        for special_token in special_tokens:
            self.assertIn(special_token, special_tokens_string)

        if self.test_rust_tokenizer:
            rust_tokenizer = self.get_rust_tokenizer()
            special_tokens_string_rust = rust_tokenizer.convert_tokens_to_string(special_tokens)
            self.assertEqual(special_tokens_string, special_tokens_string_rust)

    def test_sentencepiece_tokenize_and_decode(self):
        if not self.test_sentencepiece:
amyeroberts's avatar
amyeroberts committed
452
            self.skipTest(reason="test_sentencepiece is set to False")
453
454
455
456
457
458
459
460
461
462
463
464
465
466

        text = "This is text to test the tokenizer."
        if self.test_rust_tokenizer:
            tokenizer = self.get_tokenizer()
            rust_tokenizer = self.get_rust_tokenizer()

            slow_ids = tokenizer(text).input_ids
            fast_ids = rust_tokenizer(text).input_ids
            self.assertEqual(slow_ids, fast_ids)

            slow_decoded = tokenizer.decode(slow_ids)
            fast_decoded = rust_tokenizer.decode(slow_ids)
            self.assertEqual(slow_decoded, fast_decoded)

467
468
    def test_subword_regularization_tokenizer(self) -> None:
        if not self.test_sentencepiece:
amyeroberts's avatar
amyeroberts committed
469
            self.skipTest(reason="test_sentencepiece is set to False")
470
471
472
473
474

        # Subword regularization is only available for the slow tokenizer.
        sp_model_kwargs = {"enable_sampling": True, "alpha": 0.1, "nbest_size": -1}
        tokenizer = self.get_tokenizer(sp_model_kwargs=sp_model_kwargs)

475
476
477
478
479
480
481
482
483
        run_test_in_subprocess(
            test_case=self,
            target_func=_test_subword_regularization_tokenizer,
            inputs={
                "tokenizer": tokenizer,
                "sp_model_kwargs": sp_model_kwargs,
                "test_sentencepiece_ignore_case": self.test_sentencepiece_ignore_case,
            },
        )
484
485
486

    def test_pickle_subword_regularization_tokenizer(self) -> None:
        if not self.test_sentencepiece:
amyeroberts's avatar
amyeroberts committed
487
            self.skipTest(reason="test_sentencepiece is set to False")
488
489
490
491
492
493
494
495
496

        """Google pickle __getstate__ __setstate__ if you are struggling with this."""
        # Subword regularization is only available for the slow tokenizer.
        sp_model_kwargs = {"enable_sampling": True, "alpha": 0.1, "nbest_size": -1}
        tokenizer = self.get_tokenizer(sp_model_kwargs=sp_model_kwargs)
        tokenizer_bin = pickle.dumps(tokenizer)
        del tokenizer
        tokenizer_new = pickle.loads(tokenizer_bin)

497
498
499
500
501
502
503
504
505
        run_test_in_subprocess(
            test_case=self,
            target_func=_test_subword_regularization_tokenizer,
            inputs={
                "tokenizer": tokenizer_new,
                "sp_model_kwargs": sp_model_kwargs,
                "test_sentencepiece_ignore_case": self.test_sentencepiece_ignore_case,
            },
        )
506

507
508
    def test_save_sentencepiece_tokenizer(self) -> None:
        if not self.test_sentencepiece or not self.test_slow_tokenizer:
amyeroberts's avatar
amyeroberts committed
509
            self.skipTest(reason="test_sentencepiece or test_slow_tokenizer is set to False")
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
        # We want to verify that we will be able to save the tokenizer even if the original files that were used to
        # build the tokenizer have been deleted in the meantime.
        text = "This is text to test the tokenizer."

        tokenizer_slow_1 = self.get_tokenizer()
        encoding_tokenizer_slow_1 = tokenizer_slow_1(text)

        tmpdirname_1 = tempfile.mkdtemp()
        tmpdirname_2 = tempfile.mkdtemp()

        tokenizer_slow_1.save_pretrained(tmpdirname_1)
        tokenizer_slow_2 = self.tokenizer_class.from_pretrained(tmpdirname_1)
        encoding_tokenizer_slow_2 = tokenizer_slow_2(text)

        shutil.rmtree(tmpdirname_1)
        tokenizer_slow_2.save_pretrained(tmpdirname_2)

        tokenizer_slow_3 = self.tokenizer_class.from_pretrained(tmpdirname_2)
        encoding_tokenizer_slow_3 = tokenizer_slow_3(text)
        shutil.rmtree(tmpdirname_2)

        self.assertEqual(encoding_tokenizer_slow_1, encoding_tokenizer_slow_2)
        self.assertEqual(encoding_tokenizer_slow_1, encoding_tokenizer_slow_3)

534
535
536
537
538
539
540
541
542
543
544
545
    def test_model_input_names_signature(self):
        accepted_model_main_input_names = [
            "input_ids",  # nlp models
            "input_values",  # speech models
        ]

        tokenizers = self.get_tokenizers()
        for tokenizer in tokenizers:
            # first name of model_input_names has to correspond to main model input name
            # to make sure `tokenizer.pad(...)` works correctly
            self.assertTrue(tokenizer.model_input_names[0] in accepted_model_main_input_names)

546
547
    def test_rust_tokenizer_signature(self):
        if not self.test_rust_tokenizer:
amyeroberts's avatar
amyeroberts committed
548
            self.skipTest(reason="test_rust_tokenizer is set to False")
549
550
551
552
553
554

        signature = inspect.signature(self.rust_tokenizer_class.__init__)

        self.assertIn("tokenizer_file", signature.parameters)
        self.assertIsNone(signature.parameters["tokenizer_file"].default)

555
    def test_tokenizer_slow_store_full_signature(self):
556
        if not self.test_slow_tokenizer:
amyeroberts's avatar
amyeroberts committed
557
            self.skipTest(reason="test_slow_tokenizer is set to False")
558

559
560
561
562
563
564
565
566
567
        signature = inspect.signature(self.tokenizer_class.__init__)
        tokenizer = self.get_tokenizer()

        for parameter_name, parameter in signature.parameters.items():
            if parameter.default != inspect.Parameter.empty:
                self.assertIn(parameter_name, tokenizer.init_kwargs)

    def test_tokenizer_fast_store_full_signature(self):
        if not self.test_rust_tokenizer:
amyeroberts's avatar
amyeroberts committed
568
            self.skipTest(reason="test_rust_tokenizer is set to False")
569
570
571
572
573

        signature = inspect.signature(self.rust_tokenizer_class.__init__)
        tokenizer = self.get_rust_tokenizer()

        for parameter_name, parameter in signature.parameters.items():
574
575
576
577
578
            if parameter.default != inspect.Parameter.empty and parameter_name not in [
                "vocab_file",
                "merges_file",
                "tokenizer_file",
            ]:
579
580
                self.assertIn(parameter_name, tokenizer.init_kwargs)

581
582
    def test_rust_and_python_full_tokenizers(self):
        if not self.test_rust_tokenizer:
amyeroberts's avatar
amyeroberts committed
583
            self.skipTest(reason="test_rust_tokenizer is set to False")
584

585
586
        if not self.test_slow_tokenizer:
            # as we don't have a slow version, we can't compare the outputs between slow and fast versions
amyeroberts's avatar
amyeroberts committed
587
            self.skipTest(reason="test_slow_tokenizer is set to False")
588

589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
        tokenizer = self.get_tokenizer()
        rust_tokenizer = self.get_rust_tokenizer()

        sequence, _ = self.get_input_output_texts(tokenizer)

        # We don't have an exact equivalence on `tokenize()` between Rust and Slow
        # Slow tokenizer only split tokens, Rust tokenizers will replace with <unk>
        # tokens = tokenizer.tokenize(sequence)
        # rust_tokens = rust_tokenizer.tokenize(sequence)
        # self.assertListEqual(tokens, rust_tokens)

        ids = tokenizer.encode(sequence, add_special_tokens=False)
        rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False)
        self.assertListEqual(ids, rust_ids)

        ids = tokenizer.encode(sequence, add_special_tokens=True)
        rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=True)
        self.assertListEqual(ids, rust_ids)

608
    def test_tokenizers_common_properties(self):
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
        tokenizers = self.get_tokenizers()
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                attributes_list = [
                    "bos_token",
                    "eos_token",
                    "unk_token",
                    "sep_token",
                    "pad_token",
                    "cls_token",
                    "mask_token",
                ]
                for attr in attributes_list:
                    self.assertTrue(hasattr(tokenizer, attr))
                    self.assertTrue(hasattr(tokenizer, attr + "_id"))

                self.assertTrue(hasattr(tokenizer, "additional_special_tokens"))
                self.assertTrue(hasattr(tokenizer, "additional_special_tokens_ids"))

                attributes_list = [
                    "model_max_length",
                    "init_inputs",
                    "init_kwargs",
                ]
                if not isinstance(tokenizer, PreTrainedTokenizerFast):
                    attributes_list += [
                        "added_tokens_encoder",
                        "added_tokens_decoder",
                    ]
                for attr in attributes_list:
                    self.assertTrue(hasattr(tokenizer, attr))
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
    def test_tokenizers_common_ids_setters(self):
        tokenizers = self.get_tokenizers()
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                attributes_list = [
                    "bos_token",
                    "eos_token",
                    "unk_token",
                    "sep_token",
                    "pad_token",
                    "cls_token",
                    "mask_token",
                ]

                vocab = tokenizer.get_vocab()
                token_id_to_test_setters = next(iter(vocab.values()))
                token_to_test_setters = tokenizer.convert_ids_to_tokens(
                    token_id_to_test_setters, skip_special_tokens=False
                )

                for attr in attributes_list:
                    setattr(tokenizer, attr + "_id", None)
                    self.assertEqual(getattr(tokenizer, attr), None)
                    self.assertEqual(getattr(tokenizer, attr + "_id"), None)

                    setattr(tokenizer, attr + "_id", token_id_to_test_setters)
                    self.assertEqual(getattr(tokenizer, attr), token_to_test_setters)
                    self.assertEqual(getattr(tokenizer, attr + "_id"), token_id_to_test_setters)

                setattr(tokenizer, "additional_special_tokens_ids", [])
                self.assertListEqual(getattr(tokenizer, "additional_special_tokens"), [])
                self.assertListEqual(getattr(tokenizer, "additional_special_tokens_ids"), [])

                setattr(tokenizer, "additional_special_tokens_ids", [token_id_to_test_setters])
                self.assertListEqual(getattr(tokenizer, "additional_special_tokens"), [token_to_test_setters])
                self.assertListEqual(getattr(tokenizer, "additional_special_tokens_ids"), [token_id_to_test_setters])

678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
    @parameterized.expand([(True,), (False,)])
    def test_tokenizers_special_tokens_properties_unset(self, verbose):
        tokenizers = self.get_tokenizers(verbose=verbose)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                attributes_list = [
                    "bos_token",
                    "eos_token",
                    "unk_token",
                    "sep_token",
                    "pad_token",
                    "cls_token",
                    "mask_token",
                    "additional_special_tokens",
                ]
                for attr in attributes_list:
                    setattr(tokenizer, attr, None)
                    self.assertIsNone(getattr(tokenizer, attr))

697
698
    def test_save_and_load_tokenizer(self):
        # safety check on max_len default value so we are sure the test works
699
        tokenizers = self.get_tokenizers()
700
701
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
Stas Bekman's avatar
Stas Bekman committed
702
                self.assertNotEqual(tokenizer.model_max_length, 42)
703

704
        # Now let's start the test
705
        tokenizers = self.get_tokenizers()
706
707
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
708
709
710
                # Isolate this from the other tests because we save additional tokens/etc
                tmpdirname = tempfile.mkdtemp()

Arthur's avatar
Arthur committed
711
                sample_text = " He is very happy, UNwant\u00e9d,running"
712
                before_tokens = tokenizer.encode(sample_text, add_special_tokens=False)
713
714
715
716
717
718
719
720
721
722
                before_vocab = tokenizer.get_vocab()
                tokenizer.save_pretrained(tmpdirname)

                after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname)
                after_tokens = after_tokenizer.encode(sample_text, add_special_tokens=False)
                after_vocab = after_tokenizer.get_vocab()
                self.assertListEqual(before_tokens, after_tokens)
                self.assertDictEqual(before_vocab, after_vocab)

                shutil.rmtree(tmpdirname)
723

724
725
726
727
728
729
        tokenizers = self.get_tokenizers(model_max_length=42)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                # Isolate this from the other tests because we save additional tokens/etc
                tmpdirname = tempfile.mkdtemp()

Arthur's avatar
Arthur committed
730
                sample_text = " He is very happy, UNwant\u00e9d,running"
731
732
733
                tokenizer.add_tokens(["bim", "bambam"])
                additional_special_tokens = tokenizer.additional_special_tokens
                additional_special_tokens.append("new_additional_special_token")
734
735
736
                tokenizer.add_special_tokens(
                    {"additional_special_tokens": additional_special_tokens}, replace_additional_special_tokens=False
                )
737
738
739
                before_tokens = tokenizer.encode(sample_text, add_special_tokens=False)
                before_vocab = tokenizer.get_vocab()
                tokenizer.save_pretrained(tmpdirname)
740

741
742
743
                after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname)
                after_tokens = after_tokenizer.encode(sample_text, add_special_tokens=False)
                after_vocab = after_tokenizer.get_vocab()
744
                self.assertListEqual(before_tokens, after_tokens)
745

746
747
748
749
750
                self.assertDictEqual(before_vocab, after_vocab)
                self.assertIn("bim", after_vocab)
                self.assertIn("bambam", after_vocab)
                self.assertIn("new_additional_special_token", after_tokenizer.additional_special_tokens)
                self.assertEqual(after_tokenizer.model_max_length, 42)
751

752
                tokenizer = tokenizer.__class__.from_pretrained(tmpdirname, model_max_length=43)
753
                self.assertEqual(tokenizer.model_max_length, 43)
754

755
756
                shutil.rmtree(tmpdirname)

757
758
759
760
761
762
763
764
765
        # Test that we can also use the non-legacy saving format for fast tokenizers
        tokenizers = self.get_tokenizers(model_max_length=42)
        for tokenizer in tokenizers:
            if not tokenizer.is_fast:
                continue
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                # Isolate this from the other tests because we save additional tokens/etc
                tmpdirname = tempfile.mkdtemp()

Arthur's avatar
Arthur committed
766
                sample_text = " He is very happy, UNwant\u00e9d,running"
767
768
769
                tokenizer.add_tokens(["bim", "bambam"])
                additional_special_tokens = tokenizer.additional_special_tokens
                additional_special_tokens.append("new_additional_special_token")
770
771
772
                tokenizer.add_special_tokens(
                    {"additional_special_tokens": additional_special_tokens}, replace_additional_special_tokens=False
                )
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
                before_tokens = tokenizer.encode(sample_text, add_special_tokens=False)
                before_vocab = tokenizer.get_vocab()
                tokenizer.save_pretrained(tmpdirname)

                after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname)
                after_tokens = after_tokenizer.encode(sample_text, add_special_tokens=False)
                after_vocab = after_tokenizer.get_vocab()
                self.assertListEqual(before_tokens, after_tokens)
                self.assertDictEqual(before_vocab, after_vocab)
                self.assertIn("bim", after_vocab)
                self.assertIn("bambam", after_vocab)
                self.assertIn("new_additional_special_token", after_tokenizer.additional_special_tokens)
                self.assertEqual(after_tokenizer.model_max_length, 42)

                tokenizer = tokenizer.__class__.from_pretrained(tmpdirname, model_max_length=43)
                self.assertEqual(tokenizer.model_max_length, 43)

                shutil.rmtree(tmpdirname)

792
    def test_pickle_tokenizer(self):
793
        """Google pickle __getstate__ __setstate__ if you are struggling with this."""
794
795
796
797
        tokenizers = self.get_tokenizers()
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                self.assertIsNotNone(tokenizer)
798

799
800
                text = "Munich and Berlin are nice cities"
                subwords = tokenizer.tokenize(text)
801

802
803
804
                filename = os.path.join(self.tmpdirname, "tokenizer.bin")
                with open(filename, "wb") as handle:
                    pickle.dump(tokenizer, handle)
805

806
807
                with open(filename, "rb") as handle:
                    tokenizer_new = pickle.load(handle)
808

809
                subwords_loaded = tokenizer_new.tokenize(text)
810

811
                self.assertListEqual(subwords, subwords_loaded)
812

813
    @require_tokenizers
Anthony MOI's avatar
Anthony MOI committed
814
815
816
817
818
819
    def test_pickle_added_tokens(self):
        tok1 = AddedToken("<s>", rstrip=True, lstrip=True, normalized=False, single_word=True)
        tok2 = pickle.loads(pickle.dumps(tok1))

        self.assertEqual(tok1.__getstate__(), tok2.__getstate__())

820
    def test_added_tokens_do_lower_case(self):
821
        tokenizers = self.get_tokenizers(do_lower_case=True)
822
823
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
824
825
826
                if not hasattr(tokenizer, "do_lower_case") or not tokenizer.do_lower_case:
                    continue

827
                special_token = tokenizer.all_special_tokens[0]
828

829
830
                text = special_token + " aaaaa bbbbbb low cccccccccdddddddd l " + special_token
                text2 = special_token + " AAAAA BBBBBB low CCCCCCCCCDDDDDDDD l " + special_token
831

832
                toks_before_adding = tokenizer.tokenize(text)  # toks before adding new_toks
833

834
                new_toks = ["aaaaa bbbbbb", "cccccccccdddddddd", "AAAAA BBBBBB", "CCCCCCCCCDDDDDDDD"]
835
                added = tokenizer.add_tokens([AddedToken(tok, lstrip=True, rstrip=True) for tok in new_toks])
836

837
838
                toks_after_adding = tokenizer.tokenize(text)
                toks_after_adding2 = tokenizer.tokenize(text2)
839

840
841
842
843
844
845
846
847
                # Rust tokenizers dont't lowercase added tokens at the time calling `tokenizer.add_tokens`,
                # while python tokenizers do, so new_toks 0 and 2 would be treated as the same, so do new_toks 1 and 3.
                self.assertIn(added, [2, 4])

                self.assertListEqual(toks_after_adding, toks_after_adding2)
                self.assertTrue(
                    len(toks_before_adding) > len(toks_after_adding),  # toks_before_adding should be longer
                )
848

849
850
                # Check that none of the special tokens are lowercased
                sequence_with_special_tokens = "A " + " yEs ".join(tokenizer.all_special_tokens) + " B"
851
852
853
854
                # Convert the tokenized list to str as some special tokens are tokenized like normal tokens
                # which have a prefix spacee e.g. the mask token of Albert, and cannot match the original
                # special tokens exactly.
                tokenized_sequence = "".join(tokenizer.tokenize(sequence_with_special_tokens))
855

856
                for special_token in tokenizer.all_special_tokens:
857
                    self.assertTrue(special_token in tokenized_sequence or special_token.lower() in tokenized_sequence)
858

859
        tokenizers = self.get_tokenizers(do_lower_case=True)
860
861
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
862
863
864
                if hasattr(tokenizer, "do_lower_case") and tokenizer.do_lower_case:
                    continue

865
                special_token = tokenizer.all_special_tokens[0]
866

867
868
                text = special_token + " aaaaa bbbbbb low cccccccccdddddddd l " + special_token
                text2 = special_token + " AAAAA BBBBBB low CCCCCCCCCDDDDDDDD l " + special_token
869

870
                toks_before_adding = tokenizer.tokenize(text)  # toks before adding new_toks
thomwolf's avatar
thomwolf committed
871

872
873
                new_toks = ["aaaaa bbbbbb", "cccccccccdddddddd", "AAAAA BBBBBB", "CCCCCCCCCDDDDDDDD"]
                added = tokenizer.add_tokens([AddedToken(tok, lstrip=True, rstrip=True) for tok in new_toks])
874
                self.assertIn(added, [2, 4])
875

876
877
                toks_after_adding = tokenizer.tokenize(text)
                toks_after_adding2 = tokenizer.tokenize(text2)
878

879
880
881
882
883
884
885
                self.assertEqual(len(toks_after_adding), len(toks_after_adding2))  # Length should still be the same
                self.assertNotEqual(
                    toks_after_adding[1], toks_after_adding2[1]
                )  # But at least the first non-special tokens should differ
                self.assertTrue(
                    len(toks_before_adding) > len(toks_after_adding),  # toks_before_adding should be longer
                )
886

887
    # TODO @ArthurZ Nuke this
888
889
890
891
892
893
894
895
    def test_add_tokens_tokenizer(self):
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                vocab_size = tokenizer.vocab_size
                all_size = len(tokenizer)

                self.assertNotEqual(vocab_size, 0)
896

897
                # We usually have added tokens from the start in tests (but also otherwise) because our vocab fixtures are
898
899
                # smaller than the original vocabs - let's not assert this
                # self.assertEqual(vocab_size, all_size)
900

901
902
903
904
                new_toks = [
                    AddedToken("aaaaa bbbbbb", rstrip=True, lstrip=True),
                    AddedToken("cccccccccdddddddd", rstrip=True, lstrip=True),
                ]
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
                added_toks = tokenizer.add_tokens(new_toks)
                vocab_size_2 = tokenizer.vocab_size
                all_size_2 = len(tokenizer)

                self.assertNotEqual(vocab_size_2, 0)
                self.assertEqual(vocab_size, vocab_size_2)
                self.assertEqual(added_toks, len(new_toks))
                self.assertEqual(all_size_2, all_size + len(new_toks))

                tokens = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l", add_special_tokens=False)

                self.assertGreaterEqual(len(tokens), 4)
                self.assertGreater(tokens[0], tokenizer.vocab_size - 1)
                self.assertGreater(tokens[-2], tokenizer.vocab_size - 1)

920
921
922
923
                new_toks_2 = {
                    "eos_token": AddedToken(">>>>|||<||<<|<<", rstrip=True, lstrip=True),
                    "pad_token": AddedToken("<<<<<|||>|>>>>|>", rstrip=True, lstrip=True),
                }
924
925
926
927
928
929
930
931
932
933
                added_toks_2 = tokenizer.add_special_tokens(new_toks_2)
                vocab_size_3 = tokenizer.vocab_size
                all_size_3 = len(tokenizer)

                self.assertNotEqual(vocab_size_3, 0)
                self.assertEqual(vocab_size, vocab_size_3)
                self.assertEqual(added_toks_2, len(new_toks_2))
                self.assertEqual(all_size_3, all_size_2 + len(new_toks_2))

                tokens = tokenizer.encode(
934
                    ">>>>|||<||<<|<< aaaaa bbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l", add_special_tokens=False
935
936
937
938
939
                )

                self.assertGreaterEqual(len(tokens), 6)
                self.assertGreater(tokens[0], tokenizer.vocab_size - 1)
                self.assertGreater(tokens[0], tokens[1])
940

941
942
943
944
                self.assertGreater(tokens[-2], tokenizer.vocab_size - 1)
                self.assertGreater(tokens[-2], tokens[-3])
                self.assertEqual(tokens[0], tokenizer.eos_token_id)
                self.assertEqual(tokens[-2], tokenizer.pad_token_id)
945

946
    def test_add_special_tokens(self):
947
948
949
950
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                input_text, ids = self.get_clean_sequence(tokenizer)
951

952
                special_token = AddedToken("[SPECIAL_TOKEN]", lstrip=True, rstrip=True)
953

954
                tokenizer.add_special_tokens({"cls_token": special_token})
955
                special_token = str(special_token)
956
957
                encoded_special_token = tokenizer.encode(special_token, add_special_tokens=False)
                self.assertEqual(len(encoded_special_token), 1)
958

959
960
                text = tokenizer.decode(ids + encoded_special_token, clean_up_tokenization_spaces=False)
                encoded = tokenizer.encode(text, add_special_tokens=False)
961

962
963
964
                input_encoded = tokenizer.encode(input_text, add_special_tokens=False)
                special_token_id = tokenizer.encode(special_token, add_special_tokens=False)
                self.assertEqual(encoded, input_encoded + special_token_id)
965

966
967
                decoded = tokenizer.decode(encoded, skip_special_tokens=True)
                self.assertTrue(special_token not in decoded)
968

969
    def test_internal_consistency(self):
970
971
972
973
        tokenizers = self.get_tokenizers()
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                input_text, output_text = self.get_input_output_texts(tokenizer)
974

975
976
977
978
                tokens = tokenizer.tokenize(input_text)
                ids = tokenizer.convert_tokens_to_ids(tokens)
                ids_2 = tokenizer.encode(input_text, add_special_tokens=False)
                self.assertListEqual(ids, ids_2)
979

980
981
982
983
                tokens_2 = tokenizer.convert_ids_to_tokens(ids)
                self.assertNotEqual(len(tokens_2), 0)
                text_2 = tokenizer.decode(ids)
                self.assertIsInstance(text_2, str)
984

985
                self.assertEqual(text_2, output_text)
986

987
    @require_tokenizers
988
    def test_encode_decode_with_spaces(self):
989
        tokenizers = self.get_tokenizers(do_lower_case=False, fast=False)
990
991
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
992
                new_toks = [
993
994
995
996
                    # These are added tokens, they will be normalized....
                    AddedToken("[ABC]", normalized=True, lstrip=True, rstrip=True),
                    AddedToken("[DEF]", normalized=True, lstrip=True, rstrip=True),
                    AddedToken("GHI IHG", normalized=True, lstrip=True, rstrip=True),
997
                ]
998
                tokenizer.add_tokens(new_toks)
999
                tokenizer.add_tokens([AddedToken("[SAMPLE]", normalized=True)], special_tokens=True)
1000
                input = "[ABC][DEF][ABC]GHI IHG[DEF]"
1001
                if self.space_between_special_tokens:
1002
                    output = "[ABC] [DEF] [ABC] GHI IHG [DEF]"
1003
1004
                else:
                    output = input
1005
                encoded = tokenizer.encode(input, add_special_tokens=False)
1006
                decoded = tokenizer.decode(encoded, spaces_between_special_tokens=self.space_between_special_tokens)
1007

1008
                self.assertIn(decoded, [output, output.lower()])
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
                return
                # TODO  @ArthurZ Refactor testing as now the do_normalize works for special and non special
                encoded = tokenizer.encode("[ABC] [DEF][SAMPLE]", add_special_tokens=False)
                decoded = tokenizer.decode(encoded, spaces_between_special_tokens=True, skip_special_tokens=False)
                self.assertIn(decoded, ["[ABC] [DEF] [SAMPLE]", "[ABC] [DEF] [SAMPLE]".lower()])

                decoded = tokenizer.decode(encoded, spaces_between_special_tokens=True, skip_special_tokens=True)
                self.assertIn(decoded, ["[ABC] [DEF]", "[ABC] [DEF]".lower()])

                encoded = tokenizer.encode("[ABC][SAMPLE][DEF]", add_special_tokens=False)
                decoded = tokenizer.decode(encoded, spaces_between_special_tokens=True)
                self.assertIn(decoded, ["[ABC] [SAMPLE] [DEF]", "[ABC][SAMPLE][DEF]".lower()])

                decoded = tokenizer.decode(encoded, spaces_between_special_tokens=False)
                self.assertIn(decoded, ["[ABC][SAMPLE][DEF]", "[ABC][SAMPLE][DEF]".lower()])
1024

1025
    def test_mask_output(self):
1026
        tokenizers = self.get_tokenizers(do_lower_case=False)
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                if (
                    tokenizer.build_inputs_with_special_tokens.__qualname__.split(".")[0] != "PreTrainedTokenizer"
                    and "token_type_ids" in tokenizer.model_input_names
                ):
                    seq_0 = "Test this method."
                    seq_1 = "With these inputs."
                    information = tokenizer.encode_plus(seq_0, seq_1, add_special_tokens=True)
                    sequences, mask = information["input_ids"], information["token_type_ids"]
                    self.assertEqual(len(sequences), len(mask))
1038

1039
1040
1041
1042
1043
1044
1045
1046
    def test_token_type_ids(self):
        tokenizers = self.get_tokenizers()
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                seq_0 = "Test this method."

                # We want to have sequence 0 and sequence 1 are tagged
                # respectively with 0 and 1 token_ids
NielsRogge's avatar
NielsRogge committed
1047
                # (regardless of whether the model use token type ids)
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
                # We use this assumption in the QA pipeline among other place
                output = tokenizer(seq_0, return_token_type_ids=True)
                self.assertIn(0, output["token_type_ids"])

    def test_sequence_ids(self):
        tokenizers = self.get_tokenizers()
        for tokenizer in tokenizers:
            if not tokenizer.is_fast:
                continue
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                seq_0 = "Test this method."
                seq_1 = "With these inputs."

                # We want to have sequence 0 and sequence 1 are tagged
                # respectively with 0 and 1 token_ids
NielsRogge's avatar
NielsRogge committed
1063
                # (regardless of whether the model use token type ids)
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
                # We use this assumption in the QA pipeline among other place
                output = tokenizer(seq_0)
                self.assertIn(0, output.sequence_ids())

                output = tokenizer(seq_0, seq_1)
                self.assertIn(0, output.sequence_ids())
                self.assertIn(1, output.sequence_ids())

                if tokenizer.num_special_tokens_to_add(pair=True):
                    self.assertIn(None, output.sequence_ids())

1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
    @require_jinja
    def test_chat_template(self):
        dummy_template = "{% for message in messages %}{{message['role'] + message['content']}}{% endfor %}"
        dummy_conversation = [
            {"role": "system", "content": "system message"},
            {"role": "user", "content": "user message"},
            {"role": "assistant", "content": "assistant message"},
        ]
        expected_output = "systemsystem messageuseruser messageassistantassistant message"
        tokenizers = self.get_tokenizers()
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                output = tokenizer.apply_chat_template(
1088
                    dummy_conversation, chat_template=dummy_template, tokenize=False, return_dict=False
1089
1090
                )
                self.assertEqual(output, expected_output)  # Test we can pass chat_template arg
1091

1092
                # Check that no error raised when tokenize=True
1093
1094
1095
1096
1097
1098
1099
                output = tokenizer.apply_chat_template(
                    dummy_conversation, chat_template=dummy_template, tokenize=True, return_dict=False
                )
                dict_output = tokenizer.apply_chat_template(
                    dummy_conversation, chat_template=dummy_template, tokenize=True, return_dict=True
                )
                self.assertEqual(dict_output["input_ids"], output)  # Test return_dict behaviour matches
1100
1101
1102

                tokenizer.chat_template = dummy_template
                self.assertEqual(tokenizer.chat_template, dummy_template)  # Test property setter
1103
                output = tokenizer.apply_chat_template(dummy_conversation, tokenize=False, return_dict=False)
1104
                self.assertEqual(output, expected_output)  # Test chat_template attribute is used if no arg is passed
1105
1106
                # Check that no error raised
                tokenizer.apply_chat_template(dummy_conversation, tokenize=True, return_dict=False)
1107
1108
1109
1110
1111
1112

                with tempfile.TemporaryDirectory() as tmp_dir_name:
                    tokenizer.save_pretrained(tmp_dir_name)
                    tokenizer = tokenizer.from_pretrained(tmp_dir_name)

                self.assertEqual(tokenizer.chat_template, dummy_template)  # Test template has persisted
1113
                output = tokenizer.apply_chat_template(dummy_conversation, tokenize=False, return_dict=False)
1114
                self.assertEqual(output, expected_output)  # Test output is the same after reloading
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
                # Check that no error raised
                tokenizer.apply_chat_template(dummy_conversation, tokenize=True, return_dict=False)

    @require_jinja
    def test_chat_template_batched(self):
        dummy_template = "{% for message in messages %}{{message['role'] + message['content']}}{% endfor %}"
        dummy_conversations = [
            [
                {"role": "system", "content": "system message"},
                {"role": "user", "content": "user message"},
                {"role": "assistant", "content": "assistant message"},
            ],
            [
                {"role": "system", "content": "system message 2"},
                {"role": "user", "content": "user message 2"},
                {"role": "assistant", "content": "assistant message 2"},
            ],
        ]
        tokenizers = self.get_tokenizers()
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                output = tokenizer.apply_chat_template(
                    dummy_conversations, chat_template=dummy_template, tokenize=False
                )
                self.assertEqual(
                    output,
                    [
                        "systemsystem messageuseruser messageassistantassistant message",
                        "systemsystem message 2useruser message 2assistantassistant message 2",
                    ],
                )
                one_element_output = tokenizer.apply_chat_template(
                    dummy_conversations[:1], chat_template=dummy_template, tokenize=False
                )
                self.assertEqual(
                    one_element_output, ["systemsystem messageuseruser messageassistantassistant message"]
                )  # Assert that list structure is retained even with one element
                tokenizer.apply_chat_template(
                    dummy_conversations, chat_template=dummy_template, tokenize=True
                )  # Check that no error raised
1155

1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
    @require_jinja
    def test_chat_template_dict(self):
        dummy_template_1 = "{{'a'}}"
        dummy_template_2 = "{{'b'}}"
        dummy_conversation = [
            {"role": "user", "content": "user message"},
        ]
        tokenizers = self.get_tokenizers()
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                tokenizer.chat_template = {"template1": dummy_template_1, "template2": dummy_template_2}
                output1 = tokenizer.apply_chat_template(
                    dummy_conversation, chat_template=dummy_template_1, tokenize=False
                )
                output1_via_dict = tokenizer.apply_chat_template(
                    dummy_conversation, chat_template="template1", tokenize=False
                )
                self.assertEqual(output1, output1_via_dict)
                output2 = tokenizer.apply_chat_template(
                    dummy_conversation, chat_template=dummy_template_2, tokenize=False
                )
                output2_via_dict = tokenizer.apply_chat_template(
                    dummy_conversation, chat_template="template2", tokenize=False
                )
                self.assertEqual(output2, output2_via_dict)

    @require_jinja
    def test_chat_template_dict_saving(self):
        dummy_template_1 = "{{'a'}}"
        dummy_template_2 = "{{'b'}}"
        tokenizers = self.get_tokenizers()
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                tokenizer.chat_template = {"template1": dummy_template_1, "template2": dummy_template_2}
                with tempfile.TemporaryDirectory() as tmp_dir_name:
                    tokenizer.save_pretrained(tmp_dir_name)
                    config_dict = json.load(open(os.path.join(tmp_dir_name, "tokenizer_config.json")))
                    # Assert that chat templates are correctly serialized as lists of dictionaries
                    self.assertEqual(
                        config_dict["chat_template"],
                        [{"name": "template1", "template": "{{'a'}}"}, {"name": "template2", "template": "{{'b'}}"}],
                    )
                    new_tokenizer = tokenizer.from_pretrained(tmp_dir_name)
                # Assert that the serialized list is correctly reconstructed as a single dict
                self.assertEqual(new_tokenizer.chat_template, tokenizer.chat_template)

1202
    def test_number_of_added_tokens(self):
1203
1204
1205
1206
1207
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                seq_0 = "Test this method."
                seq_1 = "With these inputs."
1208

1209
                sequences = tokenizer.encode(seq_0, seq_1, add_special_tokens=False)
1210
                attached_sequences = tokenizer.encode(seq_0, seq_1, add_special_tokens=True)
1211

1212
1213
1214
1215
1216
                # Method is implemented (e.g. not GPT-2)
                if len(attached_sequences) != 2:
                    self.assertEqual(
                        tokenizer.num_special_tokens_to_add(pair=True), len(attached_sequences) - len(sequences)
                    )
1217
1218

    def test_maximum_encoding_length_single_input(self):
1219
        tokenizers = self.get_tokenizers(do_lower_case=False, model_max_length=100)
1220
1221
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
1222
                seq_0, ids = self.get_clean_sequence(tokenizer, max_length=20)
1223
1224
1225

                sequence = tokenizer.encode(seq_0, add_special_tokens=False)
                total_length = len(sequence)
1226

Yulv-git's avatar
Yulv-git committed
1227
1228
1229
                self.assertGreater(
                    total_length, 4, "Issue with the testing sequence, please update it, it's too short"
                )
1230
1231
1232
1233
1234
1235
1236
1237

                # Test with max model input length
                model_max_length = tokenizer.model_max_length
                self.assertEqual(model_max_length, 100)
                seq_1 = seq_0 * model_max_length

                sequence1 = tokenizer(seq_1, add_special_tokens=False)
                total_length1 = len(sequence1["input_ids"])
Nicolas Patry's avatar
Nicolas Patry committed
1238
                self.assertGreater(
Yulv-git's avatar
Yulv-git committed
1239
1240
1241
                    total_length1,
                    model_max_length,
                    "Issue with the testing sequence, please update it, it's too short",
Nicolas Patry's avatar
Nicolas Patry committed
1242
                )
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258

                # Simple
                padding_strategies = (
                    [False, True, "longest"] if tokenizer.pad_token and tokenizer.pad_token_id >= 0 else [False]
                )
                for padding_state in padding_strategies:
                    with self.subTest(f"Padding: {padding_state}"):
                        for truncation_state in [True, "longest_first", "only_first"]:
                            with self.subTest(f"Truncation: {truncation_state}"):
                                output = tokenizer(seq_1, padding=padding_state, truncation=truncation_state)
                                self.assertEqual(len(output["input_ids"]), model_max_length)

                                output = tokenizer([seq_1], padding=padding_state, truncation=truncation_state)
                                self.assertEqual(len(output["input_ids"][0]), model_max_length)

                        # Simple with no truncation
1259
1260
1261
1262
1263
1264
1265
1266
                        # Reset warnings
                        tokenizer.deprecation_warnings = {}
                        with self.assertLogs("transformers", level="WARNING") as cm:
                            output = tokenizer(seq_1, padding=padding_state, truncation=False)
                            self.assertNotEqual(len(output["input_ids"]), model_max_length)
                        self.assertEqual(len(cm.records), 1)
                        self.assertTrue(
                            cm.records[0].message.startswith(
Sylvain Gugger's avatar
Sylvain Gugger committed
1267
1268
                                "Token indices sequence length is longer than the specified maximum sequence length"
                                " for this model"
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
                            )
                        )

                        tokenizer.deprecation_warnings = {}
                        with self.assertLogs("transformers", level="WARNING") as cm:
                            output = tokenizer([seq_1], padding=padding_state, truncation=False)
                            self.assertNotEqual(len(output["input_ids"][0]), model_max_length)
                        self.assertEqual(len(cm.records), 1)
                        self.assertTrue(
                            cm.records[0].message.startswith(
Sylvain Gugger's avatar
Sylvain Gugger committed
1279
1280
                                "Token indices sequence length is longer than the specified maximum sequence length"
                                " for this model"
1281
1282
                            )
                        )
1283
1284
1285
1286

                # Overflowing tokens
                stride = 2
                information = tokenizer(
1287
1288
1289
1290
1291
1292
                    seq_0,
                    max_length=total_length - 2,
                    add_special_tokens=False,
                    stride=stride,
                    truncation="longest_first",
                    return_overflowing_tokens=True,
1293
                    # add_prefix_space=False,
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
                )

                # Overflowing tokens are handled quite differently in slow and fast tokenizers
                if isinstance(tokenizer, PreTrainedTokenizerFast):
                    truncated_sequence = information["input_ids"][0]
                    overflowing_tokens = information["input_ids"][1]
                    self.assertEqual(len(information["input_ids"]), 2)

                    self.assertEqual(len(truncated_sequence), total_length - 2)
                    self.assertEqual(truncated_sequence, sequence[:-2])

                    self.assertEqual(len(overflowing_tokens), 2 + stride)
                    self.assertEqual(overflowing_tokens, sequence[-(2 + stride) :])
                else:
                    truncated_sequence = information["input_ids"]
                    overflowing_tokens = information["overflowing_tokens"]
1310

1311
1312
                    self.assertEqual(len(truncated_sequence), total_length - 2)
                    self.assertEqual(truncated_sequence, sequence[:-2])
1313

1314
                    self.assertEqual(len(overflowing_tokens), 2 + stride)
1315
                    self.assertEqual(overflowing_tokens, sequence[-(2 + stride) :])
1316

1317
    def test_maximum_encoding_length_pair_input(self):
1318
        tokenizers = self.get_tokenizers(do_lower_case=False, model_max_length=100)
1319
1320
1321
1322
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                # Build a sequence from our model's vocabulary
                stride = 2
1323
                seq_0, ids = self.get_clean_sequence(tokenizer, max_length=20)
1324
                if len(ids) <= 2 + stride:
1325
1326
                    seq_0 = (seq_0 + " ") * (2 + stride)
                    ids = None
1327
1328

                seq0_tokens = tokenizer.encode(seq_0, add_special_tokens=False)
Nicolas Patry's avatar
Nicolas Patry committed
1329
                self.assertGreater(len(seq0_tokens), 2 + stride)
1330
1331
1332

                seq_1 = "This is another sentence to be encoded."
                seq1_tokens = tokenizer.encode(seq_1, add_special_tokens=False)
1333
                if abs(len(seq0_tokens) - len(seq1_tokens)) <= 2:
1334
1335
1336
1337
                    seq1_tokens = seq1_tokens + seq1_tokens
                    seq_1 = tokenizer.decode(seq1_tokens, clean_up_tokenization_spaces=False)
                seq1_tokens = tokenizer.encode(seq_1, add_special_tokens=False)

Nicolas Patry's avatar
Nicolas Patry committed
1338
                self.assertGreater(len(seq1_tokens), 2 + stride)
1339
1340
1341
1342
1343

                smallest = seq1_tokens if len(seq0_tokens) > len(seq1_tokens) else seq0_tokens

                # We are not using the special tokens - a bit too hard to test all the tokenizers with this
                # TODO try this again later
1344
                sequence = tokenizer.encode(seq_0, seq_1, add_special_tokens=False)  # , add_prefix_space=False)
1345
1346
1347
1348
1349

                # Test with max model input length
                model_max_length = tokenizer.model_max_length
                self.assertEqual(model_max_length, 100)
                seq_2 = seq_0 * model_max_length
Nicolas Patry's avatar
Nicolas Patry committed
1350
                self.assertGreater(len(seq_2), model_max_length)
1351
1352
1353
1354
1355

                sequence1 = tokenizer(seq_1, add_special_tokens=False)
                total_length1 = len(sequence1["input_ids"])
                sequence2 = tokenizer(seq_2, seq_1, add_special_tokens=False)
                total_length2 = len(sequence2["input_ids"])
Nicolas Patry's avatar
Nicolas Patry committed
1356
1357
1358
1359
1360
1361
                self.assertLess(
                    total_length1, model_max_length - 10, "Issue with the testing sequence, please update it."
                )
                self.assertGreater(
                    total_length2, model_max_length, "Issue with the testing sequence, please update it."
                )
1362
1363
1364
1365
1366
1367

                # Simple
                padding_strategies = (
                    [False, True, "longest"] if tokenizer.pad_token and tokenizer.pad_token_id >= 0 else [False]
                )
                for padding_state in padding_strategies:
1368
                    with self.subTest(f"{tokenizer.__class__.__name__} Padding: {padding_state}"):
1369
                        for truncation_state in [True, "longest_first", "only_first"]:
1370
                            with self.subTest(f"{tokenizer.__class__.__name__} Truncation: {truncation_state}"):
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
                                output = tokenizer(seq_2, seq_1, padding=padding_state, truncation=truncation_state)
                                self.assertEqual(len(output["input_ids"]), model_max_length)

                                output = tokenizer(
                                    [seq_2], [seq_1], padding=padding_state, truncation=truncation_state
                                )
                                self.assertEqual(len(output["input_ids"][0]), model_max_length)

                        # Simple
                        output = tokenizer(seq_1, seq_2, padding=padding_state, truncation="only_second")
                        self.assertEqual(len(output["input_ids"]), model_max_length)

                        output = tokenizer([seq_1], [seq_2], padding=padding_state, truncation="only_second")
                        self.assertEqual(len(output["input_ids"][0]), model_max_length)

                        # Simple with no truncation
1387
1388
1389
1390
1391
1392
1393
1394
                        # Reset warnings
                        tokenizer.deprecation_warnings = {}
                        with self.assertLogs("transformers", level="WARNING") as cm:
                            output = tokenizer(seq_1, seq_2, padding=padding_state, truncation=False)
                            self.assertNotEqual(len(output["input_ids"]), model_max_length)
                        self.assertEqual(len(cm.records), 1)
                        self.assertTrue(
                            cm.records[0].message.startswith(
Sylvain Gugger's avatar
Sylvain Gugger committed
1395
1396
                                "Token indices sequence length is longer than the specified maximum sequence length"
                                " for this model"
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
                            )
                        )

                        tokenizer.deprecation_warnings = {}
                        with self.assertLogs("transformers", level="WARNING") as cm:
                            output = tokenizer([seq_1], [seq_2], padding=padding_state, truncation=False)
                            self.assertNotEqual(len(output["input_ids"][0]), model_max_length)
                        self.assertEqual(len(cm.records), 1)
                        self.assertTrue(
                            cm.records[0].message.startswith(
Sylvain Gugger's avatar
Sylvain Gugger committed
1407
1408
                                "Token indices sequence length is longer than the specified maximum sequence length"
                                " for this model"
1409
1410
                            )
                        )
1411

1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
                truncated_first_sequence = tokenizer.encode(seq_0, add_special_tokens=False)[:-2] + tokenizer.encode(
                    seq_1, add_special_tokens=False
                )
                truncated_second_sequence = (
                    tokenizer.encode(seq_0, add_special_tokens=False)
                    + tokenizer.encode(seq_1, add_special_tokens=False)[:-2]
                )
                truncated_longest_sequence = (
                    truncated_first_sequence if len(seq0_tokens) > len(seq1_tokens) else truncated_second_sequence
                )

                overflow_first_sequence = tokenizer.encode(seq_0, add_special_tokens=False)[
                    -(2 + stride) :
                ] + tokenizer.encode(seq_1, add_special_tokens=False)
                overflow_second_sequence = (
                    tokenizer.encode(seq_0, add_special_tokens=False)
                    + tokenizer.encode(seq_1, add_special_tokens=False)[-(2 + stride) :]
                )
                overflow_longest_sequence = (
                    overflow_first_sequence if len(seq0_tokens) > len(seq1_tokens) else overflow_second_sequence
                )

                # Overflowing tokens are handled quite differently in slow and fast tokenizers
                if isinstance(tokenizer, PreTrainedTokenizerFast):
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
                    information = tokenizer(
                        seq_0,
                        seq_1,
                        max_length=len(sequence) - 2,
                        add_special_tokens=False,
                        stride=stride,
                        truncation="longest_first",
                        return_overflowing_tokens=True,
                        # add_prefix_space=False,
                    )
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
                    truncated_sequence = information["input_ids"][0]
                    overflowing_tokens = information["input_ids"][1]
                    self.assertEqual(len(information["input_ids"]), 2)

                    self.assertEqual(len(truncated_sequence), len(sequence) - 2)
                    self.assertEqual(truncated_sequence, truncated_longest_sequence)

                    self.assertEqual(len(overflowing_tokens), 2 + stride + len(smallest))
                    self.assertEqual(overflowing_tokens, overflow_longest_sequence)
                else:
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
                    # No overflowing tokens when using 'longest' in python tokenizers
                    with self.assertRaises(ValueError) as context:
                        information = tokenizer(
                            seq_0,
                            seq_1,
                            max_length=len(sequence) - 2,
                            add_special_tokens=False,
                            stride=stride,
                            truncation="longest_first",
                            return_overflowing_tokens=True,
                            # add_prefix_space=False,
                        )
1468

1469
1470
1471
1472
1473
1474
1475
                    self.assertTrue(
                        context.exception.args[0].startswith(
                            "Not possible to return overflowing tokens for pair of sequences with the "
                            "`longest_first`. Please select another truncation strategy than `longest_first`, "
                            "for instance `only_second` or `only_first`."
                        )
                    )
1476
1477

                # Overflowing tokens are handled quite differently in slow and fast tokenizers
1478
                if isinstance(tokenizer, PreTrainedTokenizerFast):
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
                    information = tokenizer(
                        seq_0,
                        seq_1,
                        max_length=len(sequence) - 2,
                        add_special_tokens=False,
                        stride=stride,
                        truncation=True,
                        return_overflowing_tokens=True,
                        # add_prefix_space=False,
                    )
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
                    truncated_sequence = information["input_ids"][0]
                    overflowing_tokens = information["input_ids"][1]
                    self.assertEqual(len(information["input_ids"]), 2)

                    self.assertEqual(len(truncated_sequence), len(sequence) - 2)
                    self.assertEqual(truncated_sequence, truncated_longest_sequence)

                    self.assertEqual(len(overflowing_tokens), 2 + stride + len(smallest))
                    self.assertEqual(overflowing_tokens, overflow_longest_sequence)
                else:
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
                    # No overflowing tokens when using 'longest' in python tokenizers
                    with self.assertRaises(ValueError) as context:
                        information = tokenizer(
                            seq_0,
                            seq_1,
                            max_length=len(sequence) - 2,
                            add_special_tokens=False,
                            stride=stride,
                            truncation=True,
                            return_overflowing_tokens=True,
                            # add_prefix_space=False,
                        )
1511

1512
1513
1514
1515
1516
1517
1518
                    self.assertTrue(
                        context.exception.args[0].startswith(
                            "Not possible to return overflowing tokens for pair of sequences with the "
                            "`longest_first`. Please select another truncation strategy than `longest_first`, "
                            "for instance `only_second` or `only_first`."
                        )
                    )
1519

1520
                information_first_truncated = tokenizer(
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
                    seq_0,
                    seq_1,
                    max_length=len(sequence) - 2,
                    add_special_tokens=False,
                    stride=stride,
                    truncation="only_first",
                    return_overflowing_tokens=True,
                    # add_prefix_space=False,
                )
                # Overflowing tokens are handled quite differently in slow and fast tokenizers
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
                if isinstance(tokenizer, PreTrainedTokenizerFast):
                    truncated_sequence = information_first_truncated["input_ids"][0]
                    overflowing_tokens = information_first_truncated["input_ids"][1]
                    self.assertEqual(len(information_first_truncated["input_ids"]), 2)

                    self.assertEqual(len(truncated_sequence), len(sequence) - 2)
                    self.assertEqual(truncated_sequence, truncated_first_sequence)

                    self.assertEqual(len(overflowing_tokens), 2 + stride + len(seq1_tokens))
                    self.assertEqual(overflowing_tokens, overflow_first_sequence)
                else:
                    truncated_sequence = information_first_truncated["input_ids"]
                    overflowing_tokens = information_first_truncated["overflowing_tokens"]

                    self.assertEqual(len(truncated_sequence), len(sequence) - 2)
                    self.assertEqual(truncated_sequence, truncated_first_sequence)

                    self.assertEqual(len(overflowing_tokens), 2 + stride)
                    self.assertEqual(overflowing_tokens, seq0_tokens[-(2 + stride) :])

1551
                information_second_truncated = tokenizer(
1552
1553
1554
1555
1556
1557
1558
                    seq_0,
                    seq_1,
                    max_length=len(sequence) - 2,
                    add_special_tokens=False,
                    stride=stride,
                    truncation="only_second",
                    return_overflowing_tokens=True,
1559
                    # add_prefix_space=False,
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
                )
                # Overflowing tokens are handled quite differently in slow and fast tokenizers
                if isinstance(tokenizer, PreTrainedTokenizerFast):
                    truncated_sequence = information_second_truncated["input_ids"][0]
                    overflowing_tokens = information_second_truncated["input_ids"][1]
                    self.assertEqual(len(information_second_truncated["input_ids"]), 2)

                    self.assertEqual(len(truncated_sequence), len(sequence) - 2)
                    self.assertEqual(truncated_sequence, truncated_second_sequence)

                    self.assertEqual(len(overflowing_tokens), 2 + stride + len(seq0_tokens))
                    self.assertEqual(overflowing_tokens, overflow_second_sequence)
                else:
                    truncated_sequence = information_second_truncated["input_ids"]
                    overflowing_tokens = information_second_truncated["overflowing_tokens"]

                    self.assertEqual(len(truncated_sequence), len(sequence) - 2)
                    self.assertEqual(truncated_sequence, truncated_second_sequence)
1578

1579
1580
                    self.assertEqual(len(overflowing_tokens), 2 + stride)
                    self.assertEqual(overflowing_tokens, seq1_tokens[-(2 + stride) :])
1581

1582
1583
1584
1585
    # TODO: FIXME @ArthurZucker
    @unittest.skip(
        reason="start to fail after # 29473. See https://github.com/huggingface/transformers/pull/29473#pullrequestreview-1945687810"
    )
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
    @slow
    @require_read_token
    def test_encode_decode_fast_slow_all_tokens(self):
        if self.rust_tokenizer_class is not None:
            pretrained_name = self.from_pretrained_id

            slow_tokenizer = self.tokenizer_class.from_pretrained(pretrained_name, legacy=False)
            with self.subTest(f"{pretrained_name}"):
                rust_tokenizer = self.rust_tokenizer_class.from_pretrained(
                    pretrained_name, from_slow=True, legacy=False
                )
                input_full_vocab_ids = list(
                    range(len(slow_tokenizer))
                )  # TODO let's maybe shuffle this! And run it 4 times. This way we cover more cmbinations
                input_full_vocab_string = rust_tokenizer.convert_tokens_to_string(
                    rust_tokenizer.convert_ids_to_tokens(input_full_vocab_ids)
                )
                print(f"Length of the input string that is tested: {len(input_full_vocab_string)}")

                for chunk in range(0, len(input_full_vocab_string) - 1024, 1024):
                    string_to_check = input_full_vocab_string[chunk : chunk + 1024]
                    with self.subTest(f"{(chunk/len(input_full_vocab_string))*100}%"):
                        slow_encode = slow_tokenizer.encode(string_to_check)
                        fast_encode = rust_tokenizer.encode(string_to_check)
1610
                        self.assertEqual(
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
                            slow_encode,
                            fast_encode,
                            "Hint: the following tokenization diff were obtained for slow vs fast:\n "
                            f"elements in slow: {set(slow_tokenizer.tokenize(string_to_check))-set(rust_tokenizer.tokenize(string_to_check))} \nvs\n "
                            f"elements in fast: {set(rust_tokenizer.tokenize(string_to_check))-set(slow_tokenizer.tokenize(string_to_check))} \n"
                            f"string used     : {string_to_check}",
                        )
                print(f"Length of the input ids that is tested: {len(input_full_vocab_ids)}")
                for chunk in range(0, len(input_full_vocab_ids) - 100, 100):
                    ids_to_decode = input_full_vocab_ids[chunk : chunk + 100]
                    with self.subTest(f"{(chunk/len(input_full_vocab_string))*100}%"):
1622
                        self.assertEqual(
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
                            slow_tokenizer.decode(
                                ids_to_decode,
                                space_between_special_tokens=False,
                                clean_up_tokenization_spaces=False,
                            ),
                            rust_tokenizer.decode(
                                ids_to_decode,
                                space_between_special_tokens=False,
                                clean_up_tokenization_spaces=False,
                            ),
                            f"Hint here are the tokens being decoded.: {slow_tokenizer.convert_ids_to_tokens(ids_to_decode)}",
                        )

1636
1637
1638
1639
1640
    # def test_encode_input_type(self):
    #     tokenizers = self.get_tokenizers(do_lower_case=False)
    #     for tokenizer in tokenizers:
    #         with self.subTest(f"{tokenizer.__class__.__name__}"):
    #             sequence = "Let's encode this sequence"
1641

1642
1643
1644
    #             tokens = sequence.split()  # tokenizer.tokenize(sequence)
    #             # input_ids = tokenizer.convert_tokens_to_ids(tokens)
    #             formatted_input = tokenizer.encode(sequence, add_special_tokens=True, add_prefix_space=False)
1645

1646
    #             self.assertEqual(
1647
    #                 tokenizer.encode(tokens, is_split_into_words=True, add_special_tokens=True), formatted_input
1648
1649
1650
    #             )
    #             # This is not supported with the Rust tokenizers
    #             # self.assertEqual(tokenizer.encode(input_ids, add_special_tokens=True), formatted_input)
1651

1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
    # def test_swap_special_token(self):
    #     tokenizers = self.get_tokenizers(do_lower_case=False)
    #     for tokenizer in tokenizers:
    #         with self.subTest(f"{tokenizer.__class__.__name__}"):
    #             # Our mask token
    #             mask = "<mask>"
    #             # We take a single word in the middle of the vocabulary
    #             all_tokens = sorted(tokenizer.get_vocab().keys())
    #             word = tokenizer.decode(tokenizer.encode(all_tokens[len(all_tokens)//2], add_special_tokens=False)[:1])

    #             sequence_0 = "Encode " + word + " sequence"
    #             sequence_masked_0 = "Encode " + mask + " sequence"

    #             sequence_1 = word + " this sequence"
    #             sequence_masked_1 = mask + " this sequence"

    #             # Add tokens so that masked token isn't split
    #             # tokens = [AddedToken(t, lstrip=True, normalized=False) for t in sequence.split()]
    #             # tokenizer.add_tokens(tokens)
    #             tokenizer.add_special_tokens(
    #                 {"mask_token": AddedToken(mask, normalized=False)}
    #             )  # Eat left space on Byte-level BPE tokenizers
    #             mask_ind = tokenizer.convert_tokens_to_ids(mask)

    #             # Test first masked sequence
    #             encoded_0 = tokenizer.encode(sequence_0, add_special_tokens=False)
    #             encoded_masked = tokenizer.encode(sequence_masked_0, add_special_tokens=False)
Nicolas Patry's avatar
Nicolas Patry committed
1679
    #             self.assertEqual(len(encoded_masked), len(encoded_0))
1680
1681
1682
1683
1684
1685
1686
1687
    #             mask_loc = encoded_masked.index(mask_ind)
    #             encoded_masked[mask_loc] = encoded_0[mask_loc]

    #             self.assertEqual(encoded_masked, encoded_0)

    #             # Test second masked sequence
    #             encoded_1 = tokenizer.encode(sequence_1, add_special_tokens=False)
    #             encoded_masked = tokenizer.encode(sequence_masked_1, add_special_tokens=False)
Nicolas Patry's avatar
Nicolas Patry committed
1688
    #             self.assertEqual(len(encoded_masked), len(encoded_1))
1689
1690
1691
1692
    #             mask_loc = encoded_masked.index(mask_ind)
    #             encoded_masked[mask_loc] = encoded_1[mask_loc]

    #             self.assertEqual(encoded_masked, encoded_1)
1693

1694
    def test_special_tokens_mask(self):
1695
1696
1697
1698
1699
1700
1701
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                sequence_0 = "Encode this."
                # Testing single inputs
                encoded_sequence = tokenizer.encode(sequence_0, add_special_tokens=False)
                encoded_sequence_dict = tokenizer.encode_plus(
1702
1703
1704
                    sequence_0,
                    add_special_tokens=True,
                    return_special_tokens_mask=True,  # , add_prefix_space=False
1705
1706
1707
1708
1709
1710
1711
                )
                encoded_sequence_w_special = encoded_sequence_dict["input_ids"]
                special_tokens_mask = encoded_sequence_dict["special_tokens_mask"]
                self.assertEqual(len(special_tokens_mask), len(encoded_sequence_w_special))

                filtered_sequence = [x for i, x in enumerate(encoded_sequence_w_special) if not special_tokens_mask[i]]
                self.assertEqual(encoded_sequence, filtered_sequence)
1712

1713
    def test_special_tokens_mask_input_pairs(self):
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                sequence_0 = "Encode this."
                sequence_1 = "This one too please."
                encoded_sequence = tokenizer.encode(sequence_0, add_special_tokens=False)
                encoded_sequence += tokenizer.encode(sequence_1, add_special_tokens=False)
                encoded_sequence_dict = tokenizer.encode_plus(
                    sequence_0,
                    sequence_1,
                    add_special_tokens=True,
                    return_special_tokens_mask=True,
1726
                    # add_prefix_space=False,
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
                )
                encoded_sequence_w_special = encoded_sequence_dict["input_ids"]
                special_tokens_mask = encoded_sequence_dict["special_tokens_mask"]
                self.assertEqual(len(special_tokens_mask), len(encoded_sequence_w_special))

                filtered_sequence = [
                    (x if not special_tokens_mask[i] else None) for i, x in enumerate(encoded_sequence_w_special)
                ]
                filtered_sequence = [x for x in filtered_sequence if x is not None]
                self.assertEqual(encoded_sequence, filtered_sequence)
1737

1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
    def test_padding_side_in_kwargs(self):
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
                if self.test_rust_tokenizer:
                    tokenizer_r = self.rust_tokenizer_class.from_pretrained(
                        pretrained_name, padding_side="left", **kwargs
                    )
                    self.assertEqual(tokenizer_r.padding_side, "left")

                    tokenizer_r = self.rust_tokenizer_class.from_pretrained(
                        pretrained_name, padding_side="right", **kwargs
                    )
                    self.assertEqual(tokenizer_r.padding_side, "right")

                    self.assertRaises(
                        ValueError,
                        self.rust_tokenizer_class.from_pretrained,
                        pretrained_name,
                        padding_side="unauthorized",
                        **kwargs,
                    )

                if self.test_slow_tokenizer:
                    tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, padding_side="left", **kwargs)
                    self.assertEqual(tokenizer_p.padding_side, "left")

                    tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, padding_side="right", **kwargs)
                    self.assertEqual(tokenizer_p.padding_side, "right")

                    self.assertRaises(
                        ValueError,
                        self.tokenizer_class.from_pretrained,
                        pretrained_name,
                        padding_side="unauthorized",
                        **kwargs,
                    )

1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
    def test_truncation_side_in_kwargs(self):
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
                if self.test_rust_tokenizer:
                    tokenizer_r = self.rust_tokenizer_class.from_pretrained(
                        pretrained_name, truncation_side="left", **kwargs
                    )
                    self.assertEqual(tokenizer_r.truncation_side, "left")

                    tokenizer_r = self.rust_tokenizer_class.from_pretrained(
                        pretrained_name, truncation_side="right", **kwargs
                    )
                    self.assertEqual(tokenizer_r.truncation_side, "right")

                    self.assertRaises(
                        ValueError,
                        self.rust_tokenizer_class.from_pretrained,
                        pretrained_name,
                        truncation_side="unauthorized",
                        **kwargs,
                    )

                if self.test_slow_tokenizer:
                    tokenizer_p = self.tokenizer_class.from_pretrained(
                        pretrained_name, truncation_side="left", **kwargs
                    )
                    self.assertEqual(tokenizer_p.truncation_side, "left")

                    tokenizer_p = self.tokenizer_class.from_pretrained(
                        pretrained_name, truncation_side="right", **kwargs
                    )
                    self.assertEqual(tokenizer_p.truncation_side, "right")

                    self.assertRaises(
                        ValueError,
                        self.tokenizer_class.from_pretrained,
                        pretrained_name,
                        truncation_side="unauthorized",
                        **kwargs,
                    )

1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
    def test_right_and_left_padding(self):
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                sequence = "Sequence"
                padding_size = 10

                # check correct behaviour if no pad_token_id exists and add it eventually
                self._check_no_pad_token_padding(tokenizer, sequence)

                padding_idx = tokenizer.pad_token_id

                # RIGHT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True
                tokenizer.padding_side = "right"
                encoded_sequence = tokenizer.encode(sequence)
                sequence_length = len(encoded_sequence)
                padded_sequence = tokenizer.encode(
                    sequence, max_length=sequence_length + padding_size, padding="max_length"
                )
                padded_sequence_length = len(padded_sequence)
Nicolas Patry's avatar
Nicolas Patry committed
1836
1837
                self.assertEqual(sequence_length + padding_size, padded_sequence_length)
                self.assertEqual(encoded_sequence + [padding_idx] * padding_size, padded_sequence)
1838
1839
1840
1841
1842
1843
1844
1845
1846

                # LEFT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True
                tokenizer.padding_side = "left"
                encoded_sequence = tokenizer.encode(sequence)
                sequence_length = len(encoded_sequence)
                padded_sequence = tokenizer.encode(
                    sequence, max_length=sequence_length + padding_size, padding="max_length"
                )
                padded_sequence_length = len(padded_sequence)
Nicolas Patry's avatar
Nicolas Patry committed
1847
1848
                self.assertEqual(sequence_length + padding_size, padded_sequence_length)
                self.assertEqual([padding_idx] * padding_size + encoded_sequence, padded_sequence)
1849
1850
1851
1852
1853
1854
1855
1856

                # RIGHT & LEFT PADDING - Check that nothing is done for 'longest' and 'no_padding'
                encoded_sequence = tokenizer.encode(sequence)
                sequence_length = len(encoded_sequence)

                tokenizer.padding_side = "right"
                padded_sequence_right = tokenizer.encode(sequence, padding=True)
                padded_sequence_right_length = len(padded_sequence_right)
Nicolas Patry's avatar
Nicolas Patry committed
1857
1858
                self.assertEqual(sequence_length, padded_sequence_right_length)
                self.assertEqual(encoded_sequence, padded_sequence_right)
1859
1860
1861
1862

                tokenizer.padding_side = "left"
                padded_sequence_left = tokenizer.encode(sequence, padding="longest")
                padded_sequence_left_length = len(padded_sequence_left)
Nicolas Patry's avatar
Nicolas Patry committed
1863
1864
                self.assertEqual(sequence_length, padded_sequence_left_length)
                self.assertEqual(encoded_sequence, padded_sequence_left)
1865
1866
1867
1868

                tokenizer.padding_side = "right"
                padded_sequence_right = tokenizer.encode(sequence)
                padded_sequence_right_length = len(padded_sequence_right)
Nicolas Patry's avatar
Nicolas Patry committed
1869
1870
                self.assertEqual(sequence_length, padded_sequence_right_length)
                self.assertEqual(encoded_sequence, padded_sequence_right)
1871
1872
1873
1874

                tokenizer.padding_side = "left"
                padded_sequence_left = tokenizer.encode(sequence, padding=False)
                padded_sequence_left_length = len(padded_sequence_left)
Nicolas Patry's avatar
Nicolas Patry committed
1875
1876
                self.assertEqual(sequence_length, padded_sequence_left_length)
                self.assertEqual(encoded_sequence, padded_sequence_left)
1877

1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
    def test_right_and_left_truncation(self):
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                sequence = "This is a test sequence"

                # RIGHT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True
                truncation_size = 3
                tokenizer.truncation_side = "right"
                encoded_sequence = tokenizer.encode(sequence, add_special_tokens=False)
                sequence_length = len(encoded_sequence)
                # Remove EOS/BOS tokens
                truncated_sequence = tokenizer.encode(
                    sequence, max_length=sequence_length - truncation_size, truncation=True, add_special_tokens=False
                )
                truncated_sequence_length = len(truncated_sequence)
                self.assertEqual(sequence_length, truncated_sequence_length + truncation_size)
                self.assertEqual(encoded_sequence[:-truncation_size], truncated_sequence)

                # LEFT PADDING - Check that it correctly pads when a maximum length is specified along with the truncation flag set to True
                tokenizer.truncation_side = "left"
                sequence_length = len(encoded_sequence)
                truncated_sequence = tokenizer.encode(
                    sequence, max_length=sequence_length - truncation_size, truncation=True, add_special_tokens=False
                )
                truncated_sequence_length = len(truncated_sequence)
                self.assertEqual(sequence_length, truncated_sequence_length + truncation_size)
                self.assertEqual(encoded_sequence[truncation_size:], truncated_sequence)

                # RIGHT & LEFT PADDING - Check that nothing is done for 'longest' and 'no_truncation'
                sequence_length = len(encoded_sequence)

                tokenizer.truncation_side = "right"
                truncated_sequence_right = tokenizer.encode(sequence, truncation=True, add_special_tokens=False)
                truncated_sequence_right_length = len(truncated_sequence_right)
                self.assertEqual(sequence_length, truncated_sequence_right_length)
                self.assertEqual(encoded_sequence, truncated_sequence_right)

                tokenizer.truncation_side = "left"
                truncated_sequence_left = tokenizer.encode(
                    sequence, truncation="longest_first", add_special_tokens=False
                )
                truncated_sequence_left_length = len(truncated_sequence_left)
                self.assertEqual(sequence_length, truncated_sequence_left_length)
                self.assertEqual(encoded_sequence, truncated_sequence_left)

                tokenizer.truncation_side = "right"
                truncated_sequence_right = tokenizer.encode(sequence, add_special_tokens=False)
                truncated_sequence_right_length = len(truncated_sequence_right)
                self.assertEqual(sequence_length, truncated_sequence_right_length)
                self.assertEqual(encoded_sequence, truncated_sequence_right)

                tokenizer.truncation_side = "left"
                truncated_sequence_left = tokenizer.encode(sequence, truncation=False, add_special_tokens=False)
                truncated_sequence_left_length = len(truncated_sequence_left)
                self.assertEqual(sequence_length, truncated_sequence_left_length)
                self.assertEqual(encoded_sequence, truncated_sequence_left)

1936
    def test_padding_to_max_length(self):
1937
        """We keep this test for backward compatibility but it should be remove when `pad_to_max_length` is deprecated."""
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                sequence = "Sequence"
                padding_size = 10

                # check correct behaviour if no pad_token_id exists and add it eventually
                self._check_no_pad_token_padding(tokenizer, sequence)

                padding_idx = tokenizer.pad_token_id

                # Check that it correctly pads when a maximum length is specified along with the padding flag set to True
                tokenizer.padding_side = "right"
                encoded_sequence = tokenizer.encode(sequence)
                sequence_length = len(encoded_sequence)
1953
                # FIXME: the next line should be padding(max_length) to avoid warning
1954
1955
1956
1957
                padded_sequence = tokenizer.encode(
                    sequence, max_length=sequence_length + padding_size, pad_to_max_length=True
                )
                padded_sequence_length = len(padded_sequence)
Nicolas Patry's avatar
Nicolas Patry committed
1958
1959
                self.assertEqual(sequence_length + padding_size, padded_sequence_length)
                self.assertEqual(encoded_sequence + [padding_idx] * padding_size, padded_sequence)
1960
1961
1962
1963
1964
1965
1966
1967

                # Check that nothing is done when a maximum length is not specified
                encoded_sequence = tokenizer.encode(sequence)
                sequence_length = len(encoded_sequence)

                tokenizer.padding_side = "right"
                padded_sequence_right = tokenizer.encode(sequence, pad_to_max_length=True)
                padded_sequence_right_length = len(padded_sequence_right)
Nicolas Patry's avatar
Nicolas Patry committed
1968
1969
                self.assertEqual(sequence_length, padded_sequence_right_length)
                self.assertEqual(encoded_sequence, padded_sequence_right)
1970

1971
1972
1973
    def test_padding_to_multiple_of(self):
        tokenizers = self.get_tokenizers()
        for tokenizer in tokenizers:
1974
1975
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                if tokenizer.pad_token is None:
amyeroberts's avatar
amyeroberts committed
1976
                    self.skipTest(reason="No padding token.")
1977
                else:
1978
1979
1980
                    empty_tokens = tokenizer("", padding=True, pad_to_multiple_of=8)
                    normal_tokens = tokenizer("This is a sample input", padding=True, pad_to_multiple_of=8)
                    for key, value in empty_tokens.items():
1981
                        self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8")
1982
                    for key, value in normal_tokens.items():
1983
                        self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8")
1984
1985
1986

                    normal_tokens = tokenizer("This", pad_to_multiple_of=8)
                    for key, value in normal_tokens.items():
1987
                        self.assertNotEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8")
1988
1989
1990
1991

                    # Should also work with truncation
                    normal_tokens = tokenizer("This", padding=True, truncation=True, pad_to_multiple_of=8)
                    for key, value in normal_tokens.items():
1992
                        self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8")
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004

                    # truncation to something which is not a multiple of pad_to_multiple_of raises an error
                    self.assertRaises(
                        ValueError,
                        tokenizer.__call__,
                        "This",
                        padding=True,
                        truncation=True,
                        max_length=12,
                        pad_to_multiple_of=8,
                    )

2005
2006
2007
2008
2009
    def test_padding_with_attention_mask(self):
        tokenizers = self.get_tokenizers()
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                if tokenizer.pad_token is None:
amyeroberts's avatar
amyeroberts committed
2010
                    self.skipTest(reason="No padding token.")
2011
                if "attention_mask" not in tokenizer.model_input_names:
amyeroberts's avatar
amyeroberts committed
2012
                    self.skipTest(reason="This model does not use attention mask.")
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023

                features = [
                    {"input_ids": [1, 2, 3, 4, 5, 6], "attention_mask": [1, 1, 1, 1, 1, 0]},
                    {"input_ids": [1, 2, 3], "attention_mask": [1, 1, 0]},
                ]
                padded_features = tokenizer.pad(features)
                if tokenizer.padding_side == "right":
                    self.assertListEqual(padded_features["attention_mask"], [[1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 0, 0]])
                else:
                    self.assertListEqual(padded_features["attention_mask"], [[1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 0]])

2024
    def test_encode_plus_with_padding(self):
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                sequence = "Sequence"

                # check correct behaviour if no pad_token_id exists and add it eventually
                self._check_no_pad_token_padding(tokenizer, sequence)

                padding_size = 10
                padding_idx = tokenizer.pad_token_id
                token_type_padding_idx = tokenizer.pad_token_type_id

                encoded_sequence = tokenizer.encode_plus(sequence, return_special_tokens_mask=True)
                input_ids = encoded_sequence["input_ids"]
                special_tokens_mask = encoded_sequence["special_tokens_mask"]
                sequence_length = len(input_ids)

                # Test 'longest' and 'no_padding' don't do anything
                tokenizer.padding_side = "right"

Lysandre's avatar
Lysandre committed
2045
2046
2047
2048
2049
                not_padded_sequence = tokenizer.encode_plus(
                    sequence,
                    padding=True,
                    return_special_tokens_mask=True,
                )
2050
2051
2052
2053
2054
                not_padded_input_ids = not_padded_sequence["input_ids"]

                not_padded_special_tokens_mask = not_padded_sequence["special_tokens_mask"]
                not_padded_sequence_length = len(not_padded_input_ids)

Nicolas Patry's avatar
Nicolas Patry committed
2055
2056
2057
                self.assertEqual(sequence_length, not_padded_sequence_length)
                self.assertEqual(input_ids, not_padded_input_ids)
                self.assertEqual(special_tokens_mask, not_padded_special_tokens_mask)
2058

Lysandre's avatar
Lysandre committed
2059
2060
2061
2062
2063
                not_padded_sequence = tokenizer.encode_plus(
                    sequence,
                    padding=False,
                    return_special_tokens_mask=True,
                )
2064
2065
2066
2067
2068
                not_padded_input_ids = not_padded_sequence["input_ids"]

                not_padded_special_tokens_mask = not_padded_sequence["special_tokens_mask"]
                not_padded_sequence_length = len(not_padded_input_ids)

Nicolas Patry's avatar
Nicolas Patry committed
2069
2070
2071
                self.assertEqual(sequence_length, not_padded_sequence_length)
                self.assertEqual(input_ids, not_padded_input_ids)
                self.assertEqual(special_tokens_mask, not_padded_special_tokens_mask)
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086

                # Test right padding
                tokenizer.padding_side = "right"

                right_padded_sequence = tokenizer.encode_plus(
                    sequence,
                    max_length=sequence_length + padding_size,
                    padding="max_length",
                    return_special_tokens_mask=True,
                )
                right_padded_input_ids = right_padded_sequence["input_ids"]

                right_padded_special_tokens_mask = right_padded_sequence["special_tokens_mask"]
                right_padded_sequence_length = len(right_padded_input_ids)

Nicolas Patry's avatar
Nicolas Patry committed
2087
2088
2089
                self.assertEqual(sequence_length + padding_size, right_padded_sequence_length)
                self.assertEqual(input_ids + [padding_idx] * padding_size, right_padded_input_ids)
                self.assertEqual(special_tokens_mask + [1] * padding_size, right_padded_special_tokens_mask)
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102

                # Test left padding
                tokenizer.padding_side = "left"
                left_padded_sequence = tokenizer.encode_plus(
                    sequence,
                    max_length=sequence_length + padding_size,
                    padding="max_length",
                    return_special_tokens_mask=True,
                )
                left_padded_input_ids = left_padded_sequence["input_ids"]
                left_padded_special_tokens_mask = left_padded_sequence["special_tokens_mask"]
                left_padded_sequence_length = len(left_padded_input_ids)

Nicolas Patry's avatar
Nicolas Patry committed
2103
2104
2105
                self.assertEqual(sequence_length + padding_size, left_padded_sequence_length)
                self.assertEqual([padding_idx] * padding_size + input_ids, left_padded_input_ids)
                self.assertEqual([1] * padding_size + special_tokens_mask, left_padded_special_tokens_mask)
2106
2107
2108
2109
2110
2111

                if "token_type_ids" in tokenizer.model_input_names:
                    token_type_ids = encoded_sequence["token_type_ids"]
                    left_padded_token_type_ids = left_padded_sequence["token_type_ids"]
                    right_padded_token_type_ids = right_padded_sequence["token_type_ids"]

Nicolas Patry's avatar
Nicolas Patry committed
2112
2113
2114
2115
2116
2117
                    self.assertEqual(
                        token_type_ids + [token_type_padding_idx] * padding_size, right_padded_token_type_ids
                    )
                    self.assertEqual(
                        [token_type_padding_idx] * padding_size + token_type_ids, left_padded_token_type_ids
                    )
2118
2119
2120
2121
2122
2123

                if "attention_mask" in tokenizer.model_input_names:
                    attention_mask = encoded_sequence["attention_mask"]
                    right_padded_attention_mask = right_padded_sequence["attention_mask"]
                    left_padded_attention_mask = left_padded_sequence["attention_mask"]

Nicolas Patry's avatar
Nicolas Patry committed
2124
2125
                    self.assertEqual(attention_mask + [0] * padding_size, right_padded_attention_mask)
                    self.assertEqual([0] * padding_size + attention_mask, left_padded_attention_mask)
2126

2127
2128
    def test_padding_warning_message_fast_tokenizer(self):
        if not self.test_rust_tokenizer:
amyeroberts's avatar
amyeroberts committed
2129
            self.skipTest(reason="test_rust_tokenizer is set to False")
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148

        sequence = "This is a text"

        tokenizer_fast = self.get_rust_tokenizer()
        # check correct behaviour if no pad_token_id exists and add it eventually
        self._check_no_pad_token_padding(tokenizer_fast, sequence)

        encoding_fast = tokenizer_fast(sequence)

        with self.assertLogs("transformers", level="WARNING") as cm:
            tokenizer_fast.pad(encoding_fast)
        self.assertEqual(len(cm.records), 1)
        self.assertIn(
            "Please note that with a fast tokenizer, using the `__call__` method is faster than using a method to"
            " encode the text followed by a call to the `pad` method to get a padded encoding.",
            cm.records[0].message,
        )

        if not self.test_slow_tokenizer:
amyeroberts's avatar
amyeroberts committed
2149
            self.skipTest(reason="test_slow_tokenizer is set to False")
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167

        tokenizer_slow = self.get_tokenizer()
        # check correct behaviour if no pad_token_id exists and add it eventually
        self._check_no_pad_token_padding(tokenizer_slow, sequence)

        encoding_slow = tokenizer_slow(sequence)

        with self.assertLogs(level="WARNING") as cm:
            # We want to assert there are no warnings, but the 'assertLogs' method does not support that.
            # Therefore, we are adding a dummy warning, and then we will assert it is the only warning.
            logger.warning("Dummy warning")
            tokenizer_slow.pad(encoding_slow)
        self.assertEqual(len(cm.records), 1)
        self.assertIn(
            "Dummy warning",
            cm.records[0].message,
        )

2168
2169
2170
2171
    def test_separate_tokenizers(self):
        # This tests that tokenizers don't impact others. Unfortunately the case where it fails is when
        # we're loading an S3 configuration from a pre-trained identifier, and we have no way of testing those today.

2172
2173
2174
2175
2176
        tokenizers = self.get_tokenizers(random_argument=True)
        new_tokenizers = self.get_tokenizers(random_argument=False)

        for tokenizer, new_tokenizer in zip(tokenizers, new_tokenizers):
            with self.subTest(f"{tokenizer.__class__.__name__}"):
Nicolas Patry's avatar
Nicolas Patry committed
2177
2178
2179
                self.assertTrue(tokenizer.init_kwargs["random_argument"])
                self.assertTrue(tokenizer.init_kwargs["random_argument"])
                self.assertFalse(new_tokenizer.init_kwargs["random_argument"])
2180
2181

    def test_get_vocab(self):
2182
2183
2184
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
2185
2186
2187
                vocab_dict = tokenizer.get_vocab()
                self.assertIsInstance(vocab_dict, dict)
                self.assertGreaterEqual(len(tokenizer), len(vocab_dict))
2188

2189
                vocab = [tokenizer.convert_ids_to_tokens(i) for i in range(len(tokenizer))]
2190
                self.assertEqual(len(vocab), len(tokenizer))
2191

2192
                tokenizer.add_tokens(["asdfasdfasdfasdf"])
2193
                vocab = [tokenizer.convert_ids_to_tokens(i) for i in range(len(tokenizer))]
2194
                self.assertEqual(len(vocab), len(tokenizer))
2195

2196
    def test_conversion_reversible(self):
2197
2198
2199
2200
2201
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                vocab = tokenizer.get_vocab()
                for word, ind in vocab.items():
2202
2203
                    if word == tokenizer.unk_token:
                        continue
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
                    self.assertEqual(tokenizer.convert_tokens_to_ids(word), ind)
                    self.assertEqual(tokenizer.convert_ids_to_tokens(ind), word)

    def test_call(self):
        # Tests that all call wrap to encode_plus and batch_encode_plus
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                sequences = [
                    "Testing batch encode plus",
                    "Testing batch encode plus with different sequence lengths",
                    "Testing batch encode plus with different sequence lengths correctly pads",
                ]

                # Test not batched
                encoded_sequences_1 = tokenizer.encode_plus(sequences[0])
                encoded_sequences_2 = tokenizer(sequences[0])
                self.assertEqual(encoded_sequences_1, encoded_sequences_2)

                # Test not batched pairs
                encoded_sequences_1 = tokenizer.encode_plus(sequences[0], sequences[1])
                encoded_sequences_2 = tokenizer(sequences[0], sequences[1])
                self.assertEqual(encoded_sequences_1, encoded_sequences_2)

                # Test batched
                encoded_sequences_1 = tokenizer.batch_encode_plus(sequences)
                encoded_sequences_2 = tokenizer(sequences)
                self.assertEqual(encoded_sequences_1, encoded_sequences_2)

                # Test batched pairs
                encoded_sequences_1 = tokenizer.batch_encode_plus(list(zip(sequences, sequences)))
                encoded_sequences_2 = tokenizer(sequences, sequences)
                self.assertEqual(encoded_sequences_1, encoded_sequences_2)
2237
2238
2239

    def test_batch_encode_plus_batch_sequence_length(self):
        # Tests that all encoded values have the correct size
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                sequences = [
                    "Testing batch encode plus",
                    "Testing batch encode plus with different sequence lengths",
                    "Testing batch encode plus with different sequence lengths correctly pads",
                ]

                encoded_sequences = [tokenizer.encode_plus(sequence) for sequence in sequences]
                encoded_sequences_batch = tokenizer.batch_encode_plus(sequences, padding=False)
                self.assertListEqual(
                    encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch)
                )

                maximum_length = len(
                    max([encoded_sequence["input_ids"] for encoded_sequence in encoded_sequences], key=len)
                )

                # check correct behaviour if no pad_token_id exists and add it eventually
                self._check_no_pad_token_padding(tokenizer, sequences)

                encoded_sequences_padded = [
                    tokenizer.encode_plus(sequence, max_length=maximum_length, padding="max_length")
                    for sequence in sequences
                ]

                encoded_sequences_batch_padded = tokenizer.batch_encode_plus(sequences, padding=True)
                self.assertListEqual(
                    encoded_sequences_padded,
                    self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch_padded),
                )

                # check 'longest' is unsensitive to a max length
                encoded_sequences_batch_padded_1 = tokenizer.batch_encode_plus(sequences, padding=True)
                encoded_sequences_batch_padded_2 = tokenizer.batch_encode_plus(
                    sequences, max_length=maximum_length + 10, padding="longest"
                )
                for key in encoded_sequences_batch_padded_1.keys():
                    self.assertListEqual(
Lysandre's avatar
Lysandre committed
2280
2281
                        encoded_sequences_batch_padded_1[key],
                        encoded_sequences_batch_padded_2[key],
2282
2283
2284
2285
2286
2287
2288
2289
2290
                    )

                # check 'no_padding' is unsensitive to a max length
                encoded_sequences_batch_padded_1 = tokenizer.batch_encode_plus(sequences, padding=False)
                encoded_sequences_batch_padded_2 = tokenizer.batch_encode_plus(
                    sequences, max_length=maximum_length + 10, padding=False
                )
                for key in encoded_sequences_batch_padded_1.keys():
                    self.assertListEqual(
Lysandre's avatar
Lysandre committed
2291
2292
                        encoded_sequences_batch_padded_1[key],
                        encoded_sequences_batch_padded_2[key],
2293
                    )
2294

2295
2296
2297
    @require_tokenizers
    def test_added_token_are_matched_longest_first(self):
        if not self.test_slow_tokenizer:
amyeroberts's avatar
amyeroberts committed
2298
2299
            self.skipTest(reason="This test is only for slow tokenizers")

2300
2301
2302
2303
2304
2305
2306
2307
        tokenizers = self.get_tokenizers(fast=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                try:
                    tokenizer.add_tokens([AddedToken("extra_id_1")])
                    tokenizer.add_tokens([AddedToken("extra_id_100")])
                except Exception:
                    # Canine cannot add tokens which are not codepoints
amyeroberts's avatar
amyeroberts committed
2308
                    self.skipTest(reason="Cannot add those Added tokens")
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322

                # XXX: This used to split on `extra_id_1` first we're matching
                # longest first now.
                tokens = tokenizer.tokenize("This is some extra_id_100")
                self.assertIn("extra_id_100", tokens)

        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                tokenizer.add_tokens([AddedToken("extra_id_100")])
                tokenizer.add_tokens([AddedToken("extra_id_1")])

                tokens = tokenizer.tokenize("This is some extra_id_100")
                self.assertIn("extra_id_100", tokens)

2323
    @require_tokenizers
2324
    def test_added_token_serializable(self):
2325
        # TODO this is tested 10_000 times....
2326
2327
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
2328
2329
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                new_token = AddedToken("new_token", lstrip=True)
2330
                tokenizer.add_tokens([new_token])
2331

2332
2333
2334
                with tempfile.TemporaryDirectory() as tmp_dir_name:
                    tokenizer.save_pretrained(tmp_dir_name)
                    tokenizer.from_pretrained(tmp_dir_name)
2335

2336
2337
2338
2339
    def test_batch_encode_plus_padding(self):
        # Test that padded sequences are equivalent between batch_encode_plus and encode_plus

        # Right padding tests
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                sequences = [
                    "Testing batch encode plus",
                    "Testing batch encode plus with different sequence lengths",
                    "Testing batch encode plus with different sequence lengths correctly pads",
                ]

                max_length = 100

                # check correct behaviour if no pad_token_id exists and add it eventually
                self._check_no_pad_token_padding(tokenizer, sequences)

                encoded_sequences = [
                    tokenizer.encode_plus(sequence, max_length=max_length, padding="max_length")
                    for sequence in sequences
                ]
                encoded_sequences_batch = tokenizer.batch_encode_plus(
                    sequences, max_length=max_length, padding="max_length"
                )
                self.assertListEqual(
                    encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch)
                )
2364
2365

        # Left padding tests
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                tokenizer.padding_side = "left"
                sequences = [
                    "Testing batch encode plus",
                    "Testing batch encode plus with different sequence lengths",
                    "Testing batch encode plus with different sequence lengths correctly pads",
                ]

                max_length = 100

                # check correct behaviour if no pad_token_id exists and add it eventually
                self._check_no_pad_token_padding(tokenizer, sequences)

                encoded_sequences = [
                    tokenizer.encode_plus(sequence, max_length=max_length, padding="max_length")
                    for sequence in sequences
                ]
                encoded_sequences_batch = tokenizer.batch_encode_plus(
                    sequences, max_length=max_length, padding="max_length"
                )
                self.assertListEqual(
                    encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch)
                )

    def test_pretokenized_inputs(self):
        # Test when inputs are pretokenized

2395
        tokenizers = self.get_tokenizers(do_lower_case=False)  # , add_prefix_space=True)
2396
2397
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
2398
2399
2400
                if hasattr(tokenizer, "add_prefix_space") and not tokenizer.add_prefix_space:
                    continue

2401
2402
2403
2404
2405
2406
2407
                # Prepare a sequence from our tokenizer vocabulary
                sequence, ids = self.get_clean_sequence(tokenizer, with_prefix_space=True, max_length=20)
                # sequence = " " + sequence  # To be sure the byte-level tokenizers are feeling good
                token_sequence = sequence.split()
                # sequence_no_prefix_space = sequence.strip()

                # Test encode for pretokenized inputs
2408
                output = tokenizer.encode(token_sequence, is_split_into_words=True, add_special_tokens=False)
2409
2410
2411
                output_sequence = tokenizer.encode(sequence, add_special_tokens=False)
                self.assertEqual(output, output_sequence)

2412
                output = tokenizer.encode(token_sequence, is_split_into_words=True, add_special_tokens=True)
2413
2414
2415
2416
                output_sequence = tokenizer.encode(sequence, add_special_tokens=True)
                self.assertEqual(output, output_sequence)

                # Test encode_plus for pretokenized inputs
2417
                output = tokenizer.encode_plus(token_sequence, is_split_into_words=True, add_special_tokens=False)
2418
2419
2420
                output_sequence = tokenizer.encode_plus(sequence, add_special_tokens=False)
                for key in output.keys():
                    self.assertEqual(output[key], output_sequence[key])
2421
                output = tokenizer.encode_plus(token_sequence, is_split_into_words=True, add_special_tokens=True)
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
                output_sequence = tokenizer.encode_plus(sequence, add_special_tokens=True)
                for key in output.keys():
                    self.assertEqual(output[key], output_sequence[key])

                # Test batch_encode_plus for pretokenized inputs
                sequence_batch = [sequence.strip()] * 2 + [sequence.strip() + " " + sequence.strip()]
                token_sequence_batch = [s.split() for s in sequence_batch]
                sequence_batch_cleaned_up_spaces = [" " + " ".join(s) for s in token_sequence_batch]

                output = tokenizer.batch_encode_plus(
2432
                    token_sequence_batch, is_split_into_words=True, add_special_tokens=False
2433
2434
2435
2436
2437
2438
2439
                )
                output_sequence = tokenizer.batch_encode_plus(
                    sequence_batch_cleaned_up_spaces, add_special_tokens=False
                )
                for key in output.keys():
                    self.assertEqual(output[key], output_sequence[key])
                output = tokenizer.batch_encode_plus(
2440
                    token_sequence_batch, is_split_into_words=True, add_special_tokens=True
2441
2442
2443
2444
2445
2446
2447
2448
2449
                )
                output_sequence = tokenizer.batch_encode_plus(
                    sequence_batch_cleaned_up_spaces, add_special_tokens=True
                )
                for key in output.keys():
                    self.assertEqual(output[key], output_sequence[key])

                # Test encode for pretokenized inputs pairs
                output = tokenizer.encode(
2450
                    token_sequence, token_sequence, is_split_into_words=True, add_special_tokens=False
2451
2452
2453
2454
                )
                output_sequence = tokenizer.encode(sequence, sequence, add_special_tokens=False)
                self.assertEqual(output, output_sequence)
                output = tokenizer.encode(
2455
                    token_sequence, token_sequence, is_split_into_words=True, add_special_tokens=True
2456
2457
2458
2459
2460
2461
                )
                output_sequence = tokenizer.encode(sequence, sequence, add_special_tokens=True)
                self.assertEqual(output, output_sequence)

                # Test encode_plus for pretokenized inputs pairs
                output = tokenizer.encode_plus(
2462
                    token_sequence, token_sequence, is_split_into_words=True, add_special_tokens=False
2463
2464
2465
2466
2467
                )
                output_sequence = tokenizer.encode_plus(sequence, sequence, add_special_tokens=False)
                for key in output.keys():
                    self.assertEqual(output[key], output_sequence[key])
                output = tokenizer.encode_plus(
2468
                    token_sequence, token_sequence, is_split_into_words=True, add_special_tokens=True
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
                )
                output_sequence = tokenizer.encode_plus(sequence, sequence, add_special_tokens=True)
                for key in output.keys():
                    self.assertEqual(output[key], output_sequence[key])

                # Test batch_encode_plus for pretokenized inputs pairs
                sequence_pair_batch = [(sequence.strip(), sequence.strip())] * 2 + [
                    (sequence.strip() + " " + sequence.strip(), sequence.strip())
                ]
                token_sequence_pair_batch = [tuple(s.split() for s in pair) for pair in sequence_pair_batch]
                sequence_pair_batch_cleaned_up_spaces = [
                    tuple(" " + " ".join(s) for s in pair) for pair in token_sequence_pair_batch
                ]

                output = tokenizer.batch_encode_plus(
2484
                    token_sequence_pair_batch, is_split_into_words=True, add_special_tokens=False
2485
2486
2487
2488
2489
2490
2491
                )
                output_sequence = tokenizer.batch_encode_plus(
                    sequence_pair_batch_cleaned_up_spaces, add_special_tokens=False
                )
                for key in output.keys():
                    self.assertEqual(output[key], output_sequence[key])
                output = tokenizer.batch_encode_plus(
2492
                    token_sequence_pair_batch, is_split_into_words=True, add_special_tokens=True
2493
2494
2495
2496
2497
2498
                )
                output_sequence = tokenizer.batch_encode_plus(
                    sequence_pair_batch_cleaned_up_spaces, add_special_tokens=True
                )
                for key in output.keys():
                    self.assertEqual(output[key], output_sequence[key])
2499

2500
2501
2502
    def test_prepare_for_model(self):
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
2503
2504
2505
2506
2507
2508
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                string_sequence = "Testing the prepare_for_model method."
                ids = tokenizer.encode(string_sequence, add_special_tokens=False)
                prepared_input_dict = tokenizer.prepare_for_model(ids, add_special_tokens=True)

                input_dict = tokenizer.encode_plus(string_sequence, add_special_tokens=True)
2509

2510
                self.assertEqual(input_dict, prepared_input_dict)
2511

2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
    def test_batch_encode_plus_overflowing_tokens(self):
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            string_sequences = ["Testing the prepare_for_model method.", "Test"]

            if tokenizer.pad_token is None:
                tokenizer.add_special_tokens({"pad_token": "[PAD]"})

            tokenizer.batch_encode_plus(
                string_sequences, return_overflowing_tokens=True, truncation=True, padding=True, max_length=3
            )

2524
    @is_pt_tf_cross_test
2525
    def test_batch_encode_plus_tensors(self):
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                sequences = [
                    "Testing batch encode plus",
                    "Testing batch encode plus with different sequence lengths",
                    "Testing batch encode plus with different sequence lengths correctly pads",
                ]

                # A Tensor cannot be build by sequences which are not the same size
                self.assertRaises(ValueError, tokenizer.batch_encode_plus, sequences, return_tensors="pt")
                self.assertRaises(ValueError, tokenizer.batch_encode_plus, sequences, return_tensors="tf")

                if tokenizer.pad_token_id is None:
                    self.assertRaises(
Lysandre's avatar
Lysandre committed
2541
2542
2543
2544
2545
                        ValueError,
                        tokenizer.batch_encode_plus,
                        sequences,
                        padding=True,
                        return_tensors="pt",
2546
2547
                    )
                    self.assertRaises(
Lysandre's avatar
Lysandre committed
2548
2549
2550
2551
2552
                        ValueError,
                        tokenizer.batch_encode_plus,
                        sequences,
                        padding="longest",
                        return_tensors="tf",
2553
2554
2555
2556
2557
                    )
                else:
                    pytorch_tensor = tokenizer.batch_encode_plus(sequences, padding=True, return_tensors="pt")
                    tensorflow_tensor = tokenizer.batch_encode_plus(sequences, padding="longest", return_tensors="tf")
                    encoded_sequences = tokenizer.batch_encode_plus(sequences, padding=True)
2558

2559
2560
2561
2562
                    for key in encoded_sequences.keys():
                        pytorch_value = pytorch_tensor[key].tolist()
                        tensorflow_value = tensorflow_tensor[key].numpy().tolist()
                        encoded_value = encoded_sequences[key]
2563

2564
                        self.assertEqual(pytorch_value, tensorflow_value, encoded_value)
2565
2566
2567
2568
2569
2570

    def _check_no_pad_token_padding(self, tokenizer, sequences):
        # if tokenizer does not have pad_token_id, an error should be thrown
        if tokenizer.pad_token_id is None:
            with self.assertRaises(ValueError):
                if isinstance(sequences, list):
2571
                    tokenizer.batch_encode_plus(sequences, padding="longest")
2572
                else:
2573
                    tokenizer.encode_plus(sequences, padding=True)
2574
2575
2576

            # add pad_token_id to pass subsequent tests
            tokenizer.add_special_tokens({"pad_token": "<PAD>"})
2577
2578

    @require_torch
Sylvain Gugger's avatar
Sylvain Gugger committed
2579
    @slow
2580
    def test_torch_encode_plus_sent_to_model(self):
2581
        import torch
2582

2583
2584
2585
2586
        from transformers import MODEL_MAPPING, TOKENIZER_MAPPING

        MODEL_TOKENIZER_MAPPING = merge_model_tokenizer_mappings(MODEL_MAPPING, TOKENIZER_MAPPING)

2587
2588
2589
2590
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                if tokenizer.__class__ not in MODEL_TOKENIZER_MAPPING:
amyeroberts's avatar
amyeroberts committed
2591
                    self.skipTest(f"{tokenizer.__class__.__name__} is not in the MODEL_TOKENIZER")
2592

2593
2594
                config_class, model_class = MODEL_TOKENIZER_MAPPING[tokenizer.__class__]
                config = config_class()
2595

2596
                if config.is_encoder_decoder or config.pad_token_id is None:
amyeroberts's avatar
amyeroberts committed
2597
                    self.skipTest(reason="Model is not an encoder-decoder model or has no set pad token id")
2598

2599
                model = model_class(config)
2600

2601
2602
                # Make sure the model contains at least the full vocabulary size in its embedding matrix
                is_using_common_embeddings = hasattr(model.get_input_embeddings(), "weight")
Nicolas Patry's avatar
Nicolas Patry committed
2603
2604
                if is_using_common_embeddings:
                    self.assertGreaterEqual(model.get_input_embeddings().weight.shape[0], len(tokenizer))
2605

2606
2607
2608
2609
                # Build sequence
                first_ten_tokens = list(tokenizer.get_vocab().keys())[:10]
                sequence = " ".join(first_ten_tokens)
                encoded_sequence = tokenizer.encode_plus(sequence, return_tensors="pt")
2610
2611
2612
2613

                # Ensure that the BatchEncoding.to() method works.
                encoded_sequence.to(model.device)

2614
2615
                batch_encoded_sequence = tokenizer.batch_encode_plus([sequence, sequence], return_tensors="pt")
                # This should not fail
2616

2617
2618
2619
                with torch.no_grad():  # saves some time
                    model(**encoded_sequence)
                    model(**batch_encoded_sequence)
2620

2621
2622
2623
2624
2625
2626
2627
        # if self.test_rust_tokenizer:
        #     fast_tokenizer = self.get_rust_tokenizer()
        #     encoded_sequence_fast = fast_tokenizer.encode_plus(sequence, return_tensors="pt")
        #     batch_encoded_sequence_fast = fast_tokenizer.batch_encode_plus([sequence, sequence], return_tensors="pt")
        #     # This should not fail
        #     model(**encoded_sequence_fast)
        #     model(**batch_encoded_sequence_fast)
2628
2629

    @require_tf
Sylvain Gugger's avatar
Sylvain Gugger committed
2630
    @slow
2631
2632
2633
2634
2635
    def test_tf_encode_plus_sent_to_model(self):
        from transformers import TF_MODEL_MAPPING, TOKENIZER_MAPPING

        MODEL_TOKENIZER_MAPPING = merge_model_tokenizer_mappings(TF_MODEL_MAPPING, TOKENIZER_MAPPING)

2636
2637
2638
2639
        tokenizers = self.get_tokenizers(do_lower_case=False)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                if tokenizer.__class__ not in MODEL_TOKENIZER_MAPPING:
amyeroberts's avatar
amyeroberts committed
2640
                    self.skipTest(f"{tokenizer.__class__.__name__} is not in the MODEL_TOKENIZER_MAPPING")
2641

2642
2643
                config_class, model_class = MODEL_TOKENIZER_MAPPING[tokenizer.__class__]
                config = config_class()
2644

2645
                if config.is_encoder_decoder or config.pad_token_id is None:
amyeroberts's avatar
amyeroberts committed
2646
                    self.skipTest(reason="Model is not an encoder-decoder model or has no set pad token id")
2647

2648
                model = model_class(config)
2649

2650
                # Make sure the model contains at least the full vocabulary size in its embedding matrix
Nicolas Patry's avatar
Nicolas Patry committed
2651
                self.assertGreaterEqual(model.config.vocab_size, len(tokenizer))
2652

2653
2654
2655
2656
2657
                # Build sequence
                first_ten_tokens = list(tokenizer.get_vocab().keys())[:10]
                sequence = " ".join(first_ten_tokens)
                encoded_sequence = tokenizer.encode_plus(sequence, return_tensors="tf")
                batch_encoded_sequence = tokenizer.batch_encode_plus([sequence, sequence], return_tensors="tf")
2658

2659
2660
2661
                # This should not fail
                model(encoded_sequence)
                model(batch_encoded_sequence)
2662
2663
2664

    # TODO: Check if require_torch is the best to test for numpy here ... Maybe move to require_flax when available
    @require_torch
Sylvain Gugger's avatar
Sylvain Gugger committed
2665
    @slow
2666
2667
2668
2669
2670
    def test_np_encode_plus_sent_to_model(self):
        from transformers import MODEL_MAPPING, TOKENIZER_MAPPING

        MODEL_TOKENIZER_MAPPING = merge_model_tokenizer_mappings(MODEL_MAPPING, TOKENIZER_MAPPING)

2671
2672
2673
2674
        tokenizers = self.get_tokenizers()
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                if tokenizer.__class__ not in MODEL_TOKENIZER_MAPPING:
amyeroberts's avatar
amyeroberts committed
2675
                    self.skipTest(f"{tokenizer.__class__.__name__} is not in the MODEL_TOKENIZER_MAPPING")
2676

2677
2678
                config_class, model_class = MODEL_TOKENIZER_MAPPING[tokenizer.__class__]
                config = config_class()
2679

2680
                if config.is_encoder_decoder or config.pad_token_id is None:
Pavel Iakubovskii's avatar
Pavel Iakubovskii committed
2681
                    self.skipTest("Model is not an encoder-decoder model or has no set pad token id")
2682

2683
2684
2685
2686
2687
2688
2689
                # Build sequence
                first_ten_tokens = list(tokenizer.get_vocab().keys())[:10]
                sequence = " ".join(first_ten_tokens)
                encoded_sequence = tokenizer.encode_plus(sequence, return_tensors="np")
                batch_encoded_sequence = tokenizer.batch_encode_plus([sequence, sequence], return_tensors="np")

                # TODO: add forward through JAX/Flax when PR is merged
Sylvain Gugger's avatar
Sylvain Gugger committed
2690
                # This is currently here to make ruff happy !
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
                if encoded_sequence is None:
                    raise ValueError("Cannot convert list to numpy tensor on  encode_plus()")

                if batch_encoded_sequence is None:
                    raise ValueError("Cannot convert list to numpy tensor on  batch_encode_plus()")

                if self.test_rust_tokenizer:
                    fast_tokenizer = self.get_rust_tokenizer()
                    encoded_sequence_fast = fast_tokenizer.encode_plus(sequence, return_tensors="np")
                    batch_encoded_sequence_fast = fast_tokenizer.batch_encode_plus(
                        [sequence, sequence], return_tensors="np"
                    )
2703

2704
                    # TODO: add forward through JAX/Flax when PR is merged
Sylvain Gugger's avatar
Sylvain Gugger committed
2705
                    # This is currently here to make ruff happy !
2706
2707
                    if encoded_sequence_fast is None:
                        raise ValueError("Cannot convert list to numpy tensor on  encode_plus() (fast)")
2708

2709
2710
                    if batch_encoded_sequence_fast is None:
                        raise ValueError("Cannot convert list to numpy tensor on  batch_encode_plus() (fast)")
2711
2712
2713

    @require_torch
    def test_prepare_seq2seq_batch(self):
2714
        if not self.test_seq2seq:
amyeroberts's avatar
amyeroberts committed
2715
            self.skipTest(reason="test_seq2seq is set to False")
2716

2717
2718
2719
2720
2721
2722
        tokenizers = self.get_tokenizers()
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                # Longer text that will definitely require truncation.
                src_text = [
                    " UN Chief Says There Is No Military Solution in Syria",
Sylvain Gugger's avatar
Sylvain Gugger committed
2723
2724
2725
                    " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for"
                    " Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons"
                    " will only worsen the violence and misery for millions of people.",
2726
2727
2728
                ]
                tgt_text = [
                    "艦eful ONU declar膬 c膬 nu exist膬 o solu牛ie militar膬 卯n Siria",
Sylvain Gugger's avatar
Sylvain Gugger committed
2729
2730
2731
                    "Secretarul General Ban Ki-moon declar膬 c膬 r膬spunsul s膬u la intensificarea sprijinului militar al"
                    ' Rusiei pentru Siria este c膬 "nu exist膬 o solu牛ie militar膬" la conflictul de aproape cinci ani 艧i'
                    " c膬 noi arme nu vor face dec芒t s膬 卯nr膬ut膬牛easc膬 violen牛ele 艧i mizeria pentru milioane de oameni.",
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
                ]
                try:
                    batch = tokenizer.prepare_seq2seq_batch(
                        src_texts=src_text,
                        tgt_texts=tgt_text,
                        max_length=3,
                        max_target_length=10,
                        return_tensors="pt",
                        src_lang="en_XX",  # this should be ignored (for all but mbart) but not cause an error
                    )
                except NotImplementedError:
amyeroberts's avatar
amyeroberts committed
2743
                    self.skipTest(reason="Encountered NotImplementedError calling prepare_seq2seq_batch")
2744
2745
2746
2747
2748
2749
2750
2751
                self.assertEqual(batch.input_ids.shape[1], 3)
                self.assertEqual(batch.labels.shape[1], 10)
                # max_target_length will default to max_length if not specified
                batch = tokenizer.prepare_seq2seq_batch(
                    src_text, tgt_texts=tgt_text, max_length=3, return_tensors="pt"
                )
                self.assertEqual(batch.input_ids.shape[1], 3)
                self.assertEqual(batch.labels.shape[1], 3)
2752

2753
2754
2755
2756
2757
2758
                batch_encoder_only = tokenizer.prepare_seq2seq_batch(
                    src_texts=src_text, max_length=3, max_target_length=10, return_tensors="pt"
                )
                self.assertEqual(batch_encoder_only.input_ids.shape[1], 3)
                self.assertEqual(batch_encoder_only.attention_mask.shape[1], 3)
                self.assertNotIn("decoder_input_ids", batch_encoder_only)
2759
2760
2761

    def test_is_fast(self):
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
2762
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
2763
2764
2765
2766
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
                # Check is_fast is set correctly
                self.assertTrue(tokenizer_r.is_fast)

2767
2768
2769
2770
                if self.test_slow_tokenizer:
                    tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)
                    self.assertFalse(tokenizer_p.is_fast)

2771
2772
    def test_fast_only_inputs(self):
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
2773
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)

                # Ensure None raise an error
                self.assertRaises(TypeError, tokenizer_r.tokenize, None)
                self.assertRaises(TypeError, tokenizer_r.encode, None)
                self.assertRaises(TypeError, tokenizer_r.encode_plus, None)
                self.assertRaises(TypeError, tokenizer_r.batch_encode_plus, None)

    def test_alignement_methods(self):
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
2784
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)

                words = ["Wonderful", "no", "inspiration", "example", "with", "subtoken"]
                text = " ".join(words)
                batch_size = 3

                encoding = tokenizer_r.encode_plus(text, add_special_tokens=False)

                batch_encoding = tokenizer_r.batch_encode_plus([text] * batch_size, add_special_tokens=False)
                num_tokens = len(encoding["input_ids"])

                last_word_index = len(words) - 1
                last_token_index = num_tokens - 1
                last_batch_index = batch_size - 1
                last_char_index = len(text) - 1

                # words, tokens
                self.assertEqual(len(encoding.words(0)), num_tokens)
                self.assertEqual(max(encoding.words(0)), last_word_index)
                self.assertEqual(min(encoding.words(0)), 0)
                self.assertEqual(len(batch_encoding.words(last_batch_index)), num_tokens)
                self.assertEqual(max(batch_encoding.words(last_batch_index)), last_word_index)
                self.assertEqual(min(batch_encoding.words(last_batch_index)), 0)
                self.assertEqual(len(encoding.tokens(0)), num_tokens)

                # Assert token_to_word
                self.assertEqual(encoding.token_to_word(0), 0)
                self.assertEqual(encoding.token_to_word(0, 0), 0)
                self.assertEqual(encoding.token_to_word(last_token_index), last_word_index)
                self.assertEqual(encoding.token_to_word(0, last_token_index), last_word_index)
                self.assertEqual(batch_encoding.token_to_word(1, 0), 0)
                self.assertEqual(batch_encoding.token_to_word(0, last_token_index), last_word_index)
                self.assertEqual(batch_encoding.token_to_word(last_batch_index, last_token_index), last_word_index)

                # Assert word_to_tokens
                self.assertEqual(encoding.word_to_tokens(0).start, 0)
                self.assertEqual(encoding.word_to_tokens(0, 0).start, 0)
                self.assertEqual(encoding.word_to_tokens(last_word_index).end, last_token_index + 1)
                self.assertEqual(encoding.word_to_tokens(0, last_word_index).end, last_token_index + 1)
                self.assertEqual(batch_encoding.word_to_tokens(1, 0).start, 0)
                self.assertEqual(batch_encoding.word_to_tokens(0, last_word_index).end, last_token_index + 1)
                self.assertEqual(
                    batch_encoding.word_to_tokens(last_batch_index, last_word_index).end, last_token_index + 1
                )

                # Assert token_to_chars
                self.assertEqual(encoding.token_to_chars(0).start, 0)
                self.assertEqual(encoding.token_to_chars(0, 0).start, 0)
                self.assertEqual(encoding.token_to_chars(last_token_index).end, last_char_index + 1)
                self.assertEqual(encoding.token_to_chars(0, last_token_index).end, last_char_index + 1)
                self.assertEqual(batch_encoding.token_to_chars(1, 0).start, 0)
                self.assertEqual(batch_encoding.token_to_chars(0, last_token_index).end, last_char_index + 1)
                self.assertEqual(
                    batch_encoding.token_to_chars(last_batch_index, last_token_index).end, last_char_index + 1
                )

                # Assert char_to_token
                self.assertEqual(encoding.char_to_token(0), 0)
                self.assertEqual(encoding.char_to_token(0, 0), 0)
                self.assertEqual(encoding.char_to_token(last_char_index), last_token_index)
                self.assertEqual(encoding.char_to_token(0, last_char_index), last_token_index)
                self.assertEqual(batch_encoding.char_to_token(1, 0), 0)
                self.assertEqual(batch_encoding.char_to_token(0, last_char_index), last_token_index)
                self.assertEqual(batch_encoding.char_to_token(last_batch_index, last_char_index), last_token_index)

                # Assert char_to_word
                self.assertEqual(encoding.char_to_word(0), 0)
                self.assertEqual(encoding.char_to_word(0, 0), 0)
                self.assertEqual(encoding.char_to_word(last_char_index), last_word_index)
                self.assertEqual(encoding.char_to_word(0, last_char_index), last_word_index)
                self.assertEqual(batch_encoding.char_to_word(1, 0), 0)
                self.assertEqual(batch_encoding.char_to_word(0, last_char_index), last_word_index)
                self.assertEqual(batch_encoding.char_to_word(last_batch_index, last_char_index), last_word_index)

                # Assert word_to_chars
                self.assertEqual(encoding.word_to_chars(0).start, 0)
                self.assertEqual(encoding.word_to_chars(0, 0).start, 0)
                self.assertEqual(encoding.word_to_chars(last_word_index).end, last_char_index + 1)
                self.assertEqual(encoding.word_to_chars(0, last_word_index).end, last_char_index + 1)
                self.assertEqual(batch_encoding.word_to_chars(1, 0).start, 0)
                self.assertEqual(batch_encoding.word_to_chars(0, last_word_index).end, last_char_index + 1)
                self.assertEqual(
                    batch_encoding.word_to_chars(last_batch_index, last_word_index).end, last_char_index + 1
                )

2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
                # Assert token_to_sequence
                self.assertEqual(encoding.token_to_sequence(num_tokens // 2), 0)
                self.assertEqual(encoding.token_to_sequence(0, num_tokens // 2), 0)
                self.assertEqual(batch_encoding.token_to_sequence(1, num_tokens // 2), 0)
                self.assertEqual(batch_encoding.token_to_sequence(0, num_tokens // 2), 0)
                self.assertEqual(batch_encoding.token_to_sequence(last_batch_index, num_tokens // 2), 0)

                # Pair of input sequences

                words = ["Wonderful", "no", "inspiration", "example", "with", "subtoken"]
                text = " ".join(words)
                pair_words = ["Amazing", "example", "full", "of", "inspiration"]
                pair_text = " ".join(pair_words)
                batch_size = 3
                index_word_in_first_seq = words.index("inspiration")
                index_word_in_pair_seq = pair_words.index("inspiration")
                index_char_in_first_seq = text.find("inspiration")
                index_char_in_pair_seq = pair_text.find("inspiration")

                pair_encoding = tokenizer_r.encode_plus(text, pair_text, add_special_tokens=False)

                pair_batch_encoding = tokenizer_r.batch_encode_plus(
                    [(text, pair_text)] * batch_size, add_special_tokens=False
                )
                num_tokens = len(encoding["input_ids"])

                last_word_index = len(words) - 1
                last_token_index = num_tokens - 1
                last_batch_index = batch_size - 1
                last_char_index = len(text) - 1

                # Assert word_to_tokens
                self.assertNotEqual(
                    pair_encoding.word_to_tokens(index_word_in_first_seq, sequence_index=0).start,
                    pair_encoding.word_to_tokens(index_word_in_pair_seq, sequence_index=1).start,
                )
                self.assertEqual(
                    pair_encoding["input_ids"][
                        pair_encoding.word_to_tokens(index_word_in_first_seq, sequence_index=0).start
                    ],
                    pair_encoding["input_ids"][
                        pair_encoding.word_to_tokens(index_word_in_pair_seq, sequence_index=1).start
                    ],
                )
                self.assertNotEqual(
                    pair_batch_encoding.word_to_tokens(1, index_word_in_first_seq, sequence_index=0).start,
                    pair_batch_encoding.word_to_tokens(1, index_word_in_pair_seq, sequence_index=1).start,
                )
                self.assertEqual(
                    pair_batch_encoding["input_ids"][1][
                        pair_batch_encoding.word_to_tokens(1, index_word_in_first_seq, sequence_index=0).start
                    ],
                    pair_batch_encoding["input_ids"][1][
                        pair_batch_encoding.word_to_tokens(1, index_word_in_pair_seq, sequence_index=1).start
                    ],
                )

                # Assert char_to_token
                self.assertNotEqual(
                    pair_encoding.char_to_token(index_char_in_first_seq, sequence_index=0),
                    pair_encoding.char_to_token(index_char_in_pair_seq, sequence_index=1),
                )
                self.assertEqual(
                    pair_encoding["input_ids"][pair_encoding.char_to_token(index_char_in_first_seq, sequence_index=0)],
                    pair_encoding["input_ids"][pair_encoding.char_to_token(index_char_in_pair_seq, sequence_index=1)],
                )
                self.assertNotEqual(
                    pair_batch_encoding.char_to_token(1, index_char_in_first_seq, sequence_index=0),
                    pair_batch_encoding.char_to_token(1, index_char_in_pair_seq, sequence_index=1),
                )
                self.assertEqual(
                    pair_batch_encoding["input_ids"][1][
                        pair_batch_encoding.char_to_token(1, index_char_in_first_seq, sequence_index=0)
                    ],
                    pair_batch_encoding["input_ids"][1][
                        pair_batch_encoding.char_to_token(1, index_char_in_pair_seq, sequence_index=1)
                    ],
                )

                # Assert char_to_word
                self.assertNotEqual(
                    pair_encoding.char_to_word(index_char_in_first_seq, sequence_index=0),
                    pair_encoding.char_to_word(index_char_in_pair_seq, sequence_index=1),
                )
                self.assertEqual(
                    words[pair_encoding.char_to_word(index_char_in_first_seq, sequence_index=0)],
                    pair_words[pair_encoding.char_to_word(index_char_in_pair_seq, sequence_index=1)],
                )
                self.assertNotEqual(
                    pair_batch_encoding.char_to_word(1, index_char_in_first_seq, sequence_index=0),
                    pair_batch_encoding.char_to_word(1, index_char_in_pair_seq, sequence_index=1),
                )
                self.assertEqual(
                    words[pair_batch_encoding.char_to_word(1, index_char_in_first_seq, sequence_index=0)],
                    pair_words[pair_batch_encoding.char_to_word(1, index_char_in_pair_seq, sequence_index=1)],
                )

                # Assert word_to_chars
                self.assertNotEqual(
                    pair_encoding.word_to_chars(index_word_in_first_seq, sequence_index=0).start,
                    pair_encoding.word_to_chars(index_word_in_pair_seq, sequence_index=1).start,
                )
                self.assertEqual(
                    text[pair_encoding.word_to_chars(index_word_in_first_seq, sequence_index=0).start],
                    pair_text[pair_encoding.word_to_chars(index_word_in_pair_seq, sequence_index=1).start],
                )
                self.assertNotEqual(
                    pair_batch_encoding.word_to_chars(1, index_word_in_first_seq, sequence_index=0).start,
                    pair_batch_encoding.word_to_chars(1, index_word_in_pair_seq, sequence_index=1).start,
                )
                self.assertEqual(
                    text[pair_batch_encoding.word_to_chars(1, index_word_in_first_seq, sequence_index=0).start],
                    pair_text[pair_batch_encoding.word_to_chars(1, index_word_in_pair_seq, sequence_index=1).start],
                )

                # Assert token_to_sequence
                pair_encoding = tokenizer_r.encode_plus(text, pair_text, add_special_tokens=True)

                pair_sequence_ids = [
                    pair_encoding.token_to_sequence(i) for i in range(len(pair_encoding["input_ids"]))
                ]
                self.assertIn(0, pair_sequence_ids)
                self.assertIn(1, pair_sequence_ids)
                if tokenizer_r.num_special_tokens_to_add(pair=True):
                    self.assertIn(None, pair_sequence_ids)

                pair_batch_encoding = tokenizer_r.batch_encode_plus(
                    [(text, pair_text)] * batch_size, add_special_tokens=True
                )
                pair_batch_sequence_ids = [
                    pair_batch_encoding.token_to_sequence(1, i)
                    for i in range(len(pair_batch_encoding["input_ids"][0]))
                ]
                self.assertIn(0, pair_batch_sequence_ids)
                self.assertIn(1, pair_batch_sequence_ids)
                if tokenizer_r.num_special_tokens_to_add(pair=True):
                    self.assertIn(None, pair_batch_sequence_ids)

3008
    def test_tokenization_python_rust_equals(self):
3009
3010
        if not self.test_slow_tokenizer:
            # as we don't have a slow version, we can't compare the outputs between slow and fast versions
amyeroberts's avatar
amyeroberts committed
3011
            self.skipTest(reason="test_slow_tokenizer is set to False")
3012

3013
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
3014
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
                tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)

                # Ensure basic input match
                input_p = tokenizer_p.encode_plus(self._data)
                input_r = tokenizer_r.encode_plus(self._data)

                for key in filter(lambda x: x in ["input_ids", "token_type_ids", "attention_mask"], input_p.keys()):
                    self.assertSequenceEqual(input_p[key], input_r[key])

                input_pairs_p = tokenizer_p.encode_plus(self._data, self._data)
                input_pairs_r = tokenizer_r.encode_plus(self._data, self._data)

                for key in filter(lambda x: x in ["input_ids", "token_type_ids", "attention_mask"], input_p.keys()):
                    self.assertSequenceEqual(input_pairs_p[key], input_pairs_r[key])

                # Ensure truncation match
                input_p = tokenizer_p.encode_plus(self._data, max_length=512, truncation=True)
                input_r = tokenizer_r.encode_plus(self._data, max_length=512, truncation=True)

                for key in filter(lambda x: x in ["input_ids", "token_type_ids", "attention_mask"], input_p.keys()):
                    self.assertSequenceEqual(input_p[key], input_r[key])

                # Ensure truncation with stride match
                input_p = tokenizer_p.encode_plus(
                    self._data, max_length=512, truncation=True, stride=3, return_overflowing_tokens=True
                )
                input_r = tokenizer_r.encode_plus(
                    self._data, max_length=512, truncation=True, stride=3, return_overflowing_tokens=True
                )

                for key in filter(lambda x: x in ["input_ids", "token_type_ids", "attention_mask"], input_p.keys()):
                    self.assertSequenceEqual(input_p[key], input_r[key][0])

    def test_num_special_tokens_to_add_equal(self):
3050
3051
        if not self.test_slow_tokenizer:
            # as we don't have a slow version, we can't compare the outputs between slow and fast versions
amyeroberts's avatar
amyeroberts committed
3052
            self.skipTest(reason="test_slow_tokenizer is set to False")
3053

3054
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
3055
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
                tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)

                # Check we have the same number of added_tokens for both pair and non-pair inputs.
                self.assertEqual(
                    tokenizer_r.num_special_tokens_to_add(False), tokenizer_p.num_special_tokens_to_add(False)
                )
                self.assertEqual(
                    tokenizer_r.num_special_tokens_to_add(True), tokenizer_p.num_special_tokens_to_add(True)
                )

    def test_max_length_equal(self):
3068
3069
        if not self.test_slow_tokenizer:
            # as we don't have a slow version, we can't compare the outputs between slow and fast versions
amyeroberts's avatar
amyeroberts committed
3070
            self.skipTest(reason="test_slow_tokenizer is set to False")
3071

3072
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
3073
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
3074
3075
3076
3077
3078
3079
3080
3081
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
                tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)

                # Check we have the correct max_length for both pair and non-pair inputs.
                self.assertEqual(tokenizer_r.max_len_single_sentence, tokenizer_p.max_len_single_sentence)
                self.assertEqual(tokenizer_r.max_len_sentences_pair, tokenizer_p.max_len_sentences_pair)

    def test_special_tokens_map_equal(self):
3082
3083
        if not self.test_slow_tokenizer:
            # as we don't have a slow version, we can't compare the outputs between slow and fast versions
amyeroberts's avatar
amyeroberts committed
3084
            self.skipTest(reason="test_slow_tokenizer is set to False")
3085

3086
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
3087
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
3088
                # sometimes the tokenizer saved online is not the same
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
                tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)

                # Assert the set of special tokens match.
                self.assertSequenceEqual(
                    tokenizer_p.special_tokens_map.items(),
                    tokenizer_r.special_tokens_map.items(),
                )

    def test_add_tokens(self):
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
3100
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)

                vocab_size = len(tokenizer_r)
                self.assertEqual(tokenizer_r.add_tokens(""), 0)
                self.assertEqual(tokenizer_r.add_tokens("testoken"), 1)
                self.assertEqual(tokenizer_r.add_tokens(["testoken1", "testtoken2"]), 2)
                self.assertEqual(len(tokenizer_r), vocab_size + 3)

                self.assertEqual(tokenizer_r.add_special_tokens({}), 0)
                self.assertEqual(tokenizer_r.add_special_tokens({"bos_token": "[BOS]", "eos_token": "[EOS]"}), 2)
                self.assertRaises(
                    AssertionError, tokenizer_r.add_special_tokens, {"additional_special_tokens": "<testtoken1>"}
                )
                self.assertEqual(tokenizer_r.add_special_tokens({"additional_special_tokens": ["<testtoken2>"]}), 1)
                self.assertEqual(
                    tokenizer_r.add_special_tokens({"additional_special_tokens": ["<testtoken3>", "<testtoken4>"]}), 2
                )
3118
3119
3120
3121
                self.assertIn("<testtoken3>", tokenizer_r.special_tokens_map["additional_special_tokens"])
                self.assertIsInstance(tokenizer_r.special_tokens_map["additional_special_tokens"], list)
                self.assertGreaterEqual(len(tokenizer_r.special_tokens_map["additional_special_tokens"]), 2)

3122
3123
3124
3125
                self.assertEqual(len(tokenizer_r), vocab_size + 8)

    def test_offsets_mapping(self):
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
3126
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)

                text = "Wonderful no inspiration example with subtoken"
                pair = "Along with an awesome pair"

                # No pair
                tokens_with_offsets = tokenizer_r.encode_plus(
                    text, return_special_tokens_mask=True, return_offsets_mapping=True, add_special_tokens=True
                )
                added_tokens = tokenizer_r.num_special_tokens_to_add(False)
                offsets = tokens_with_offsets["offset_mapping"]

                # Assert there is the same number of tokens and offsets
                self.assertEqual(len(offsets), len(tokens_with_offsets["input_ids"]))

                # Assert there is online added_tokens special_tokens
                self.assertEqual(sum(tokens_with_offsets["special_tokens_mask"]), added_tokens)

                # Pairs
                tokens_with_offsets = tokenizer_r.encode_plus(
                    text, pair, return_special_tokens_mask=True, return_offsets_mapping=True, add_special_tokens=True
                )
                added_tokens = tokenizer_r.num_special_tokens_to_add(True)
                offsets = tokens_with_offsets["offset_mapping"]

                # Assert there is the same number of tokens and offsets
                self.assertEqual(len(offsets), len(tokens_with_offsets["input_ids"]))

                # Assert there is online added_tokens special_tokens
                self.assertEqual(sum(tokens_with_offsets["special_tokens_mask"]), added_tokens)

    def test_batch_encode_dynamic_overflowing(self):
        """
        When calling batch_encode with multiple sequence it can returns different number of
        overflowing encoding for each sequence:
        [
          Sequence 1: [Encoding 1, Encoding 2],
          Sequence 2: [Encoding 1],
          Sequence 3: [Encoding 1, Encoding 2, ... Encoding N]
        ]
        This needs to be padded so that it can represented as a tensor
        """
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
            tokenizer = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)

3172
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name}, {tokenizer.__class__.__name__})"):
3173
3174
3175
3176
                if is_torch_available():
                    returned_tensor = "pt"
                elif is_tf_available():
                    returned_tensor = "tf"
3177
                elif is_flax_available():
3178
                    returned_tensor = "jax"
3179
                else:
amyeroberts's avatar
amyeroberts committed
3180
                    self.skipTest(reason="No expected framework from PT, TF or JAX found")
3181
3182

                if not tokenizer.pad_token or tokenizer.pad_token_id < 0:
amyeroberts's avatar
amyeroberts committed
3183
                    self.skipTest(reason="This tokenizer has no padding token set, or pad_token_id < 0")
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225

                tokens = tokenizer.encode_plus(
                    "HuggingFace is solving NLP one commit at a time",
                    max_length=6,
                    padding=True,
                    truncation=True,
                    return_tensors=returned_tensor,
                    return_overflowing_tokens=True,
                )

                for key in filter(lambda x: "overflow_to_sample_mapping" not in x, tokens.keys()):
                    self.assertEqual(len(tokens[key].shape), 2)

                # Mono sample
                tokens = tokenizer.batch_encode_plus(
                    ["HuggingFace is solving NLP one commit at a time"],
                    max_length=6,
                    padding=True,
                    truncation="only_first",
                    return_tensors=returned_tensor,
                    return_overflowing_tokens=True,
                )

                for key in filter(lambda x: "overflow_to_sample_mapping" not in x, tokens.keys()):
                    self.assertEqual(len(tokens[key].shape), 2)
                    self.assertEqual(tokens[key].shape[-1], 6)

                # Multi sample
                tokens = tokenizer.batch_encode_plus(
                    ["HuggingFace is solving NLP one commit at a time", "Very tiny input"],
                    max_length=6,
                    padding=True,
                    truncation="only_first",
                    return_tensors=returned_tensor,
                    return_overflowing_tokens=True,
                )

                for key in filter(lambda x: "overflow_to_sample_mapping" not in x, tokens.keys()):
                    self.assertEqual(len(tokens[key].shape), 2)
                    self.assertEqual(tokens[key].shape[-1], 6)

    def test_compare_pretokenized_inputs(self):
3226
3227
        if not self.test_slow_tokenizer:
            # as we don't have a slow version, we can't compare the outputs between slow and fast versions
amyeroberts's avatar
amyeroberts committed
3228
            self.skipTest(reason="test_slow_tokenizer is set to False")
3229

3230
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
3231
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
                tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)

                if hasattr(tokenizer_p, "add_prefix_space") and not tokenizer_p.add_prefix_space:
                    continue  # Too hard to test for now

                # Input string
                pretokenized_input_simple = "This is a sample input".split()
                pretokenized_input_pair = "This is a sample pair".split()

                # Test encode for pretokenized inputs
                output_r = tokenizer_r.encode(
                    pretokenized_input_simple, is_split_into_words=True, add_special_tokens=False
                )
                output_p = tokenizer_p.encode(
                    pretokenized_input_simple, is_split_into_words=True, add_special_tokens=False
                )
                self.assertEqual(output_p, output_r)

                kwargs = {
                    "is_split_into_words": True,
                    # "return_token_type_ids": True,  # Use the defaults for each tokenizers
                    # "return_attention_mask": True,  # Use the defaults for each tokenizers
                    "return_overflowing_tokens": False,
                    "return_special_tokens_mask": True,
                    "return_offsets_mapping": False,  # Not implemented in python tokenizers
                    # "add_special_tokens": False,
                }
                batch_kwargs = {
                    "is_split_into_words": True,
                    # "return_token_type_ids": True,  # Use the defaults for each tokenizers
                    # "return_attention_mask": True,  # Use the defaults for each tokenizers
                    "return_overflowing_tokens": False,
                    "return_special_tokens_mask": True,
                    "return_offsets_mapping": False,  # Not implemented in python tokenizers
                    # "add_special_tokens": False,
                }
                # Test encode_plus for pretokenized inputs
                output_r = tokenizer_r.encode_plus(pretokenized_input_simple, **kwargs)
                output_p = tokenizer_p.encode_plus(pretokenized_input_simple, **kwargs)
                for key in output_p.keys():
                    self.assertEqual(output_p[key], output_r[key])

                # Test batch_encode_plus for pretokenized inputs
                input_batch = ([pretokenized_input_simple] * 2) + [pretokenized_input_simple + pretokenized_input_pair]
                output_r = tokenizer_r.batch_encode_plus(input_batch, **batch_kwargs)
                output_p = tokenizer_p.batch_encode_plus(input_batch, **batch_kwargs)
                for key in output_p.keys():
                    self.assertEqual(output_p[key], output_r[key])

                # Test encode for pretokenized inputs pairs
                output_r = tokenizer_r.encode(
                    pretokenized_input_simple, pretokenized_input_pair, is_split_into_words=True
                )
                output_p = tokenizer_p.encode(
                    pretokenized_input_simple, pretokenized_input_pair, is_split_into_words=True
                )
                self.assertEqual(output_p, output_r)

                # Test encode_plus for pretokenized inputs
                output_r = tokenizer_r.encode_plus(pretokenized_input_simple, pretokenized_input_pair, **kwargs)
                output_p = tokenizer_p.encode_plus(pretokenized_input_simple, pretokenized_input_pair, **kwargs)
                for key in output_p.keys():
                    self.assertEqual(output_p[key], output_r[key])

                # Test batch_encode_plus for pretokenized inputs
                input_batch_pair = ([pretokenized_input_simple, pretokenized_input_pair] * 2) + [
                    pretokenized_input_simple + pretokenized_input_pair,
                    pretokenized_input_pair,
                ]
                output_r = tokenizer_r.batch_encode_plus(input_batch_pair, **batch_kwargs)
                output_p = tokenizer_p.batch_encode_plus(input_batch_pair, **batch_kwargs)
                for key in output_p.keys():
                    self.assertEqual(output_p[key], output_r[key])

    def test_create_token_type_ids(self):
3308
3309
        if not self.test_slow_tokenizer:
            # as we don't have a slow version, we can't compare the outputs between slow and fast versions
amyeroberts's avatar
amyeroberts committed
3310
            self.skipTest(reason="test_slow_tokenizer is set to False")
3311

3312
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
3313
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
                tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)
                input_simple = [1, 2, 3]
                input_pair = [1, 2, 3]

                # Generate output
                output_r = tokenizer_r.create_token_type_ids_from_sequences(input_simple)
                output_p = tokenizer_p.create_token_type_ids_from_sequences(input_simple)
                self.assertEqual(output_p, output_r)

                # Generate pair output
                output_r = tokenizer_r.create_token_type_ids_from_sequences(input_simple, input_pair)
                output_p = tokenizer_p.create_token_type_ids_from_sequences(input_simple, input_pair)
                self.assertEqual(output_p, output_r)

    def test_build_inputs_with_special_tokens(self):
3330
3331
        if not self.test_slow_tokenizer:
            # as we don't have a slow version, we can't compare the outputs between slow and fast versions
amyeroberts's avatar
amyeroberts committed
3332
            self.skipTest(reason="test_slow_tokenizer is set to False")
3333

3334
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
3335
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
                tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)
                # # Input string
                # input_simple = tokenizer_p.tokenize("This is a sample input", add_special_tokens=False)
                # input_pair = tokenizer_p.tokenize("This is a sample pair", add_special_tokens=False)

                # # Generate output
                # output_r = tokenizer_r.build_inputs_with_special_tokens(input_simple)
                # output_p = tokenizer_p.build_inputs_with_special_tokens(input_simple)
                # self.assertEqual(output_p, output_r)

                # # Generate pair output
                # output_r = tokenizer_r.build_inputs_with_special_tokens(input_simple, input_pair)
                # output_p = tokenizer_p.build_inputs_with_special_tokens(input_simple, input_pair)
                # self.assertEqual(output_p, output_r)

3352
3353
3354
3355
3356
3357
                input_pairs = [
                    ("", ""),
                    ("", "This is a sample pair"),
                    ("This is a sample input", ""),
                    ("This is a sample input", "This is a sample pair"),
                ]
3358

3359
3360
3361
3362
                for sample_input, sample_pair in input_pairs:
                    # Input tokens id
                    input_simple = tokenizer_p.encode(sample_input, add_special_tokens=False)
                    input_pair = tokenizer_p.encode(sample_pair, add_special_tokens=False)
3363

3364
3365
3366
3367
3368
3369
3370
3371
3372
                    # Generate output
                    output_r = tokenizer_r.build_inputs_with_special_tokens(input_simple)
                    output_p = tokenizer_p.build_inputs_with_special_tokens(input_simple)
                    self.assertEqual(output_p, output_r)

                    # Generate pair output
                    output_r = tokenizer_r.build_inputs_with_special_tokens(input_simple, input_pair)
                    output_p = tokenizer_p.build_inputs_with_special_tokens(input_simple, input_pair)
                    self.assertEqual(output_p, output_r)
3373
3374

    def test_padding(self, max_length=50):
3375
3376
        if not self.test_slow_tokenizer:
            # as we don't have a slow version, we can't compare the outputs between slow and fast versions
amyeroberts's avatar
amyeroberts committed
3377
            self.skipTest(reason="test_slow_tokenizer is set to False")
3378

3379
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
3380
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
3381
3382
3383
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
                tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)

3384
3385
                self.assertEqual(tokenizer_p.pad_token_id, tokenizer_r.pad_token_id)
                pad_token_id = tokenizer_p.pad_token_id
3386
3387
3388
3389

                # Encode - Simple input
                input_r = tokenizer_r.encode("This is a simple input", max_length=max_length, pad_to_max_length=True)
                input_p = tokenizer_p.encode("This is a simple input", max_length=max_length, pad_to_max_length=True)
3390
                self.assert_padded_input_match(input_r, input_p, max_length, pad_token_id)
3391
3392
                input_r = tokenizer_r.encode("This is a simple input", max_length=max_length, padding="max_length")
                input_p = tokenizer_p.encode("This is a simple input", max_length=max_length, padding="max_length")
3393
                self.assert_padded_input_match(input_r, input_p, max_length, pad_token_id)
3394
3395
3396

                input_r = tokenizer_r.encode("This is a simple input", padding="longest")
                input_p = tokenizer_p.encode("This is a simple input", padding=True)
3397
                self.assert_padded_input_match(input_r, input_p, len(input_r), pad_token_id)
3398
3399
3400
3401
3402
3403
3404
3405

                # Encode - Pair input
                input_r = tokenizer_r.encode(
                    "This is a simple input", "This is a pair", max_length=max_length, pad_to_max_length=True
                )
                input_p = tokenizer_p.encode(
                    "This is a simple input", "This is a pair", max_length=max_length, pad_to_max_length=True
                )
3406
                self.assert_padded_input_match(input_r, input_p, max_length, pad_token_id)
3407
3408
3409
3410
3411
3412
                input_r = tokenizer_r.encode(
                    "This is a simple input", "This is a pair", max_length=max_length, padding="max_length"
                )
                input_p = tokenizer_p.encode(
                    "This is a simple input", "This is a pair", max_length=max_length, padding="max_length"
                )
3413
                self.assert_padded_input_match(input_r, input_p, max_length, pad_token_id)
3414
3415
                input_r = tokenizer_r.encode("This is a simple input", "This is a pair", padding=True)
                input_p = tokenizer_p.encode("This is a simple input", "This is a pair", padding="longest")
3416
                self.assert_padded_input_match(input_r, input_p, len(input_r), pad_token_id)
3417
3418
3419
3420
3421
3422
3423
3424

                # Encode_plus - Simple input
                input_r = tokenizer_r.encode_plus(
                    "This is a simple input", max_length=max_length, pad_to_max_length=True
                )
                input_p = tokenizer_p.encode_plus(
                    "This is a simple input", max_length=max_length, pad_to_max_length=True
                )
3425
                self.assert_padded_input_match(input_r["input_ids"], input_p["input_ids"], max_length, pad_token_id)
3426
3427
3428
3429
3430
3431
3432
                self.assertSequenceEqual(input_r["attention_mask"], input_p["attention_mask"])
                input_r = tokenizer_r.encode_plus(
                    "This is a simple input", max_length=max_length, padding="max_length"
                )
                input_p = tokenizer_p.encode_plus(
                    "This is a simple input", max_length=max_length, padding="max_length"
                )
3433
                self.assert_padded_input_match(input_r["input_ids"], input_p["input_ids"], max_length, pad_token_id)
3434
3435
3436
3437
                self.assertSequenceEqual(input_r["attention_mask"], input_p["attention_mask"])

                input_r = tokenizer_r.encode_plus("This is a simple input", padding="longest")
                input_p = tokenizer_p.encode_plus("This is a simple input", padding=True)
3438
3439
3440
                self.assert_padded_input_match(
                    input_r["input_ids"], input_p["input_ids"], len(input_r["input_ids"]), pad_token_id
                )
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450

                self.assertSequenceEqual(input_r["attention_mask"], input_p["attention_mask"])

                # Encode_plus - Pair input
                input_r = tokenizer_r.encode_plus(
                    "This is a simple input", "This is a pair", max_length=max_length, pad_to_max_length=True
                )
                input_p = tokenizer_p.encode_plus(
                    "This is a simple input", "This is a pair", max_length=max_length, pad_to_max_length=True
                )
3451
                self.assert_padded_input_match(input_r["input_ids"], input_p["input_ids"], max_length, pad_token_id)
3452
3453
3454
3455
3456
3457
3458
                self.assertSequenceEqual(input_r["attention_mask"], input_p["attention_mask"])
                input_r = tokenizer_r.encode_plus(
                    "This is a simple input", "This is a pair", max_length=max_length, padding="max_length"
                )
                input_p = tokenizer_p.encode_plus(
                    "This is a simple input", "This is a pair", max_length=max_length, padding="max_length"
                )
3459
                self.assert_padded_input_match(input_r["input_ids"], input_p["input_ids"], max_length, pad_token_id)
3460
3461
3462
                self.assertSequenceEqual(input_r["attention_mask"], input_p["attention_mask"])
                input_r = tokenizer_r.encode_plus("This is a simple input", "This is a pair", padding="longest")
                input_p = tokenizer_p.encode_plus("This is a simple input", "This is a pair", padding=True)
3463
3464
3465
                self.assert_padded_input_match(
                    input_r["input_ids"], input_p["input_ids"], len(input_r["input_ids"]), pad_token_id
                )
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
                self.assertSequenceEqual(input_r["attention_mask"], input_p["attention_mask"])

                # Batch_encode_plus - Simple input
                input_r = tokenizer_r.batch_encode_plus(
                    ["This is a simple input 1", "This is a simple input 2"],
                    max_length=max_length,
                    pad_to_max_length=True,
                )
                input_p = tokenizer_p.batch_encode_plus(
                    ["This is a simple input 1", "This is a simple input 2"],
                    max_length=max_length,
                    pad_to_max_length=True,
                )
3479
                self.assert_batch_padded_input_match(input_r, input_p, max_length, pad_token_id)
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490

                input_r = tokenizer_r.batch_encode_plus(
                    ["This is a simple input 1", "This is a simple input 2"],
                    max_length=max_length,
                    padding="max_length",
                )
                input_p = tokenizer_p.batch_encode_plus(
                    ["This is a simple input 1", "This is a simple input 2"],
                    max_length=max_length,
                    padding="max_length",
                )
3491
                self.assert_batch_padded_input_match(input_r, input_p, max_length, pad_token_id)
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502

                input_r = tokenizer_r.batch_encode_plus(
                    ["This is a simple input 1", "This is a simple input 2"],
                    max_length=max_length,
                    padding="longest",
                )
                input_p = tokenizer_p.batch_encode_plus(
                    ["This is a simple input 1", "This is a simple input 2"],
                    max_length=max_length,
                    padding=True,
                )
3503
                self.assert_batch_padded_input_match(input_r, input_p, len(input_r["input_ids"][0]), pad_token_id)
3504
3505
3506
3507
3508
3509
3510

                input_r = tokenizer_r.batch_encode_plus(
                    ["This is a simple input 1", "This is a simple input 2"], padding="longest"
                )
                input_p = tokenizer_p.batch_encode_plus(
                    ["This is a simple input 1", "This is a simple input 2"], padding=True
                )
3511
                self.assert_batch_padded_input_match(input_r, input_p, len(input_r["input_ids"][0]), pad_token_id)
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531

                # Batch_encode_plus - Pair input
                input_r = tokenizer_r.batch_encode_plus(
                    [
                        ("This is a simple input 1", "This is a simple input 2"),
                        ("This is a simple pair 1", "This is a simple pair 2"),
                    ],
                    max_length=max_length,
                    truncation=True,
                    padding="max_length",
                )
                input_p = tokenizer_p.batch_encode_plus(
                    [
                        ("This is a simple input 1", "This is a simple input 2"),
                        ("This is a simple pair 1", "This is a simple pair 2"),
                    ],
                    max_length=max_length,
                    truncation=True,
                    padding="max_length",
                )
3532
                self.assert_batch_padded_input_match(input_r, input_p, max_length, pad_token_id)
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547

                input_r = tokenizer_r.batch_encode_plus(
                    [
                        ("This is a simple input 1", "This is a simple input 2"),
                        ("This is a simple pair 1", "This is a simple pair 2"),
                    ],
                    padding=True,
                )
                input_p = tokenizer_p.batch_encode_plus(
                    [
                        ("This is a simple input 1", "This is a simple input 2"),
                        ("This is a simple pair 1", "This is a simple pair 2"),
                    ],
                    padding="longest",
                )
3548
                self.assert_batch_padded_input_match(input_r, input_p, len(input_r["input_ids"][0]), pad_token_id)
3549
3550
3551
3552
3553

                # Using pad on single examples after tokenization
                input_r = tokenizer_r.encode_plus("This is a input 1")
                input_r = tokenizer_r.pad(input_r)

3554
3555
                input_p = tokenizer_p.encode_plus("This is a input 1")
                input_p = tokenizer_p.pad(input_p)
3556

3557
3558
3559
                self.assert_padded_input_match(
                    input_r["input_ids"], input_p["input_ids"], len(input_r["input_ids"]), pad_token_id
                )
3560
3561
3562
3563
3564

                # Using pad on single examples after tokenization
                input_r = tokenizer_r.encode_plus("This is a input 1")
                input_r = tokenizer_r.pad(input_r, max_length=max_length, padding="max_length")

3565
3566
                input_p = tokenizer_p.encode_plus("This is a input 1")
                input_p = tokenizer_p.pad(input_p, max_length=max_length, padding="max_length")
3567

3568
                self.assert_padded_input_match(input_r["input_ids"], input_p["input_ids"], max_length, pad_token_id)
3569
3570
3571
3572
3573
3574
3575

                # Using pad after tokenization
                input_r = tokenizer_r.batch_encode_plus(
                    ["This is a input 1", "This is a much longer input whilch should be padded"]
                )
                input_r = tokenizer_r.pad(input_r)

3576
                input_p = tokenizer_p.batch_encode_plus(
3577
3578
                    ["This is a input 1", "This is a much longer input whilch should be padded"]
                )
3579
                input_p = tokenizer_p.pad(input_p)
3580

3581
                self.assert_batch_padded_input_match(input_r, input_p, len(input_r["input_ids"][0]), pad_token_id)
3582
3583
3584
3585
3586
3587
3588

                # Using pad after tokenization
                input_r = tokenizer_r.batch_encode_plus(
                    ["This is a input 1", "This is a much longer input whilch should be padded"]
                )
                input_r = tokenizer_r.pad(input_r, max_length=max_length, padding="max_length")

3589
                input_p = tokenizer_p.batch_encode_plus(
3590
3591
                    ["This is a input 1", "This is a much longer input whilch should be padded"]
                )
3592
3593
                input_p = tokenizer_p.pad(input_p, max_length=max_length, padding="max_length")
                self.assert_batch_padded_input_match(input_r, input_p, max_length, pad_token_id)
3594

3595
3596
3597
                # Test padding nested empty lists (in some use-cases, there is no any token id in the `input_ids` list).
                input_r = tokenizer_r.pad({"input_ids": [[], []]}, max_length=max_length, padding="max_length")
                input_p = tokenizer_p.pad({"input_ids": [[], []]}, max_length=max_length, padding="max_length")
3598
3599
3600
                self.assert_batch_padded_input_match(input_r, input_p, max_length, pad_token_id)

    def test_padding_different_model_input_name(self):
3601
3602
        if not self.test_slow_tokenizer:
            # as we don't have a slow version, we can't compare the outputs between slow and fast versions
amyeroberts's avatar
amyeroberts committed
3603
            self.skipTest(reason="test_slow_tokenizer is set to False")
3604

3605
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
3606
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
                tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)
                self.assertEqual(tokenizer_p.pad_token_id, tokenizer_r.pad_token_id)
                pad_token_id = tokenizer_p.pad_token_id

                input_r = tokenizer_r.batch_encode_plus(
                    ["This is a input 1", "This is a much longer input whilch should be padded"]
                )
                input_p = tokenizer_r.batch_encode_plus(
                    ["This is a input 1", "This is a much longer input whilch should be padded"]
                )

                # rename encoded batch to "inputs"
                input_r["inputs"] = input_r[tokenizer_r.model_input_names[0]]
                del input_r[tokenizer_r.model_input_names[0]]

                input_p["inputs"] = input_p[tokenizer_p.model_input_names[0]]
                del input_p[tokenizer_p.model_input_names[0]]

                # Renaming `input_ids` to `inputs`
                tokenizer_r.model_input_names = ["inputs"] + tokenizer_r.model_input_names[1:]
                tokenizer_p.model_input_names = ["inputs"] + tokenizer_p.model_input_names[1:]

                input_r = tokenizer_r.pad(input_r, padding="longest")
                input_p = tokenizer_r.pad(input_p, padding="longest")

                max_length = len(input_p["inputs"][0])
                self.assert_batch_padded_input_match(
                    input_r, input_p, max_length, pad_token_id, model_main_input_name="inputs"
                )
3637
3638

    def test_save_pretrained(self):
3639
3640
        if not self.test_slow_tokenizer:
            # as we don't have a slow version, we can't compare the outputs between slow and fast versions
amyeroberts's avatar
amyeroberts committed
3641
            self.skipTest(reason="test_slow_tokenizer is set to False")
3642

3643
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
3644
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
3645
3646
3647
3648
3649
3650
3651
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
                tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)

                tmpdirname2 = tempfile.mkdtemp()

                tokenizer_r_files = tokenizer_r.save_pretrained(tmpdirname2)
                tokenizer_p_files = tokenizer_p.save_pretrained(tmpdirname2)
Sylvain Gugger's avatar
Sylvain Gugger committed
3652

3653
3654
3655
3656
3657
                # make sure that all ".json" files are saved in the correct format
                for file_path in tokenizer_r_files + tokenizer_p_files:
                    if os.path.exists(file_path) and file_path.endswith(".json"):
                        check_json_file_has_correct_format(file_path)

Sylvain Gugger's avatar
Sylvain Gugger committed
3658
3659
3660
                # Checks it save with the same files + the tokenizer.json file for the fast one
                self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files))
                tokenizer_r_files = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f)
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
                self.assertSequenceEqual(tokenizer_r_files, tokenizer_p_files)

                # Checks everything loads correctly in the same way
                tokenizer_rp = tokenizer_r.from_pretrained(tmpdirname2)
                tokenizer_pp = tokenizer_p.from_pretrained(tmpdirname2)

                # Check special tokens are set accordingly on Rust and Python
                for key in tokenizer_pp.special_tokens_map:
                    self.assertTrue(hasattr(tokenizer_rp, key))
                    # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key))
                    # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id"))

                shutil.rmtree(tmpdirname2)

Sylvain Gugger's avatar
Sylvain Gugger committed
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
                # Save tokenizer rust, legacy_format=True
                tmpdirname2 = tempfile.mkdtemp()

                tokenizer_r_files = tokenizer_r.save_pretrained(tmpdirname2, legacy_format=True)
                tokenizer_p_files = tokenizer_p.save_pretrained(tmpdirname2)

                # Checks it save with the same files
                self.assertSequenceEqual(tokenizer_r_files, tokenizer_p_files)

                # Checks everything loads correctly in the same way
                tokenizer_rp = tokenizer_r.from_pretrained(tmpdirname2)
                tokenizer_pp = tokenizer_p.from_pretrained(tmpdirname2)

                # Check special tokens are set accordingly on Rust and Python
                for key in tokenizer_pp.special_tokens_map:
                    self.assertTrue(hasattr(tokenizer_rp, key))

                shutil.rmtree(tmpdirname2)

                # Save tokenizer rust, legacy_format=False
                tmpdirname2 = tempfile.mkdtemp()

                tokenizer_r_files = tokenizer_r.save_pretrained(tmpdirname2, legacy_format=False)
                tokenizer_p_files = tokenizer_p.save_pretrained(tmpdirname2)

                # Checks it saved the tokenizer.json file
                self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files))

                # Checks everything loads correctly in the same way
                tokenizer_rp = tokenizer_r.from_pretrained(tmpdirname2)
                tokenizer_pp = tokenizer_p.from_pretrained(tmpdirname2)

                # Check special tokens are set accordingly on Rust and Python
                for key in tokenizer_pp.special_tokens_map:
                    self.assertTrue(hasattr(tokenizer_rp, key))

                shutil.rmtree(tmpdirname2)

3713
    def test_embeded_special_tokens(self):
3714
3715
        if not self.test_slow_tokenizer:
            # as we don't have a slow version, we can't compare the outputs between slow and fast versions
amyeroberts's avatar
amyeroberts committed
3716
            self.skipTest(reason="test_slow_tokenizer is set to False")
3717

3718
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
3719
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
3720
                tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)
3721
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
                sentence = "A, <mask> AllenNLP sentence."
                tokens_r = tokenizer_r.encode_plus(
                    sentence,
                    add_special_tokens=True,
                )
                tokens_p = tokenizer_p.encode_plus(
                    sentence,
                    add_special_tokens=True,
                )

                for key in tokens_p.keys():
                    self.assertEqual(tokens_r[key], tokens_p[key])

                if "token_type_ids" in tokens_r:
                    self.assertEqual(sum(tokens_r["token_type_ids"]), sum(tokens_p["token_type_ids"]))

                tokens_r = tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"])
                tokens_p = tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"])
                self.assertSequenceEqual(tokens_r, tokens_p)

    def test_compare_add_special_tokens(self):
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
3744
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)

                simple_num_special_tokens_to_add = tokenizer_r.num_special_tokens_to_add(pair=False)
                # pair_num_special_tokens_to_add = tokenizer_r.num_special_tokens_to_add(pair=True)

                for text in ["", " "]:
                    # tokenize()
                    no_special_tokens = tokenizer_r.tokenize(text, add_special_tokens=False)
                    with_special_tokens = tokenizer_r.tokenize(text, add_special_tokens=True)
                    self.assertEqual(
                        len(no_special_tokens), len(with_special_tokens) - simple_num_special_tokens_to_add
                    )

                    # encode()
                    no_special_tokens = tokenizer_r.encode(text, add_special_tokens=False)
                    with_special_tokens = tokenizer_r.encode(text, add_special_tokens=True)
                    self.assertEqual(
                        len(no_special_tokens), len(with_special_tokens) - simple_num_special_tokens_to_add
                    )

                    # encode_plus()
                    no_special_tokens = tokenizer_r.encode_plus(text, add_special_tokens=False)
                    with_special_tokens = tokenizer_r.encode_plus(text, add_special_tokens=True)
                    for key in no_special_tokens.keys():
                        self.assertEqual(
                            len(no_special_tokens[key]),
                            len(with_special_tokens[key]) - simple_num_special_tokens_to_add,
                        )

                    # # batch_encode_plus
                    no_special_tokens = tokenizer_r.batch_encode_plus([text, text], add_special_tokens=False)
                    with_special_tokens = tokenizer_r.batch_encode_plus([text, text], add_special_tokens=True)
                    for key in no_special_tokens.keys():
                        for i_no, i_with in zip(no_special_tokens[key], with_special_tokens[key]):
                            self.assertEqual(len(i_no), len(i_with) - simple_num_special_tokens_to_add)

    def test_compare_prepare_for_model(self):
3782
3783
        if not self.test_slow_tokenizer:
            # as we don't have a slow version, we can't compare the outputs between slow and fast versions
amyeroberts's avatar
amyeroberts committed
3784
            self.skipTest(reason="test_slow_tokenizer is set to False")
3785

3786
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
3787
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
                tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)
                string_sequence = "Asserting that both tokenizers are equal"
                python_output = tokenizer_p.prepare_for_model(
                    tokenizer_p.encode(string_sequence, add_special_tokens=False)
                )
                rust_output = tokenizer_r.prepare_for_model(
                    tokenizer_r.encode(string_sequence, add_special_tokens=False)
                )
                for key in python_output:
                    self.assertEqual(python_output[key], rust_output[key])
Sylvain Gugger's avatar
Sylvain Gugger committed
3799

Lysandre Debut's avatar
Lysandre Debut committed
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
    def test_special_tokens_initialization(self):
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
                added_tokens = [AddedToken("<special>", lstrip=True)]
                tokenizer_r = self.rust_tokenizer_class.from_pretrained(
                    pretrained_name, additional_special_tokens=added_tokens, **kwargs
                )
                r_output = tokenizer_r.encode("Hey this is a <special> token")

                special_token_id = tokenizer_r.encode("<special>", add_special_tokens=False)[0]

                self.assertTrue(special_token_id in r_output)
3812
3813

                if self.test_slow_tokenizer:
3814
                    # in rust fast, you lose the information of the AddedToken when initializing with `additional_special_tokens`
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
                    tokenizer_cr = self.rust_tokenizer_class.from_pretrained(
                        pretrained_name, additional_special_tokens=added_tokens, **kwargs, from_slow=True
                    )
                    tokenizer_p = self.tokenizer_class.from_pretrained(
                        pretrained_name, additional_special_tokens=added_tokens, **kwargs
                    )

                    p_output = tokenizer_p.encode("Hey this is a <special> token")

                    cr_output = tokenizer_cr.encode("Hey this is a <special> token")

                    self.assertEqual(p_output, r_output)
                    self.assertEqual(cr_output, r_output)
                    self.assertTrue(special_token_id in p_output)
                    self.assertTrue(special_token_id in cr_output)
Lysandre Debut's avatar
Lysandre Debut committed
3830

3831
    def test_special_tokens_initialization_with_non_empty_additional_special_tokens(self):
3832
3833
3834
        # This test no longer support rust tokenizers, because the only file that should be looked
        # at by the fast tokenizer with the new saving format is `tokenizer_config.json`.
        # The previous behaviour is very strange too. Fast tokenizer should not save 3 files, but just one. Can never do slow from fast.
3835
3836
3837
3838
3839
3840
3841
        tokenizer_list = []
        if self.test_slow_tokenizer:
            tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()))

        for tokenizer_class, tokenizer_utils in tokenizer_list:
            with tempfile.TemporaryDirectory() as tmp_dir:
                tokenizer_utils.save_pretrained(tmp_dir)
3842
3843
3844
                # only legacy save will check this
                tokenizer_path = "tokenizer_config.json"
                with open(os.path.join(tmp_dir, tokenizer_path), encoding="utf-8") as json_file:
3845
3846
3847
3848
                    tokenizer_config = json.load(json_file)

                tokenizer_config["additional_special_tokens"] = ["an_additional_special_token"]

3849
                with open(os.path.join(tmp_dir, tokenizer_path), "w", encoding="utf-8") as outfile:
3850
3851
3852
3853
3854
                    json.dump(tokenizer_config, outfile)

                # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
                # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
                # "special_tokens_map.json" files
3855
3856
3857

                # TODO ArthurZ ... Ok so for legacy we have to support this I guess..... (special_tokens_map + additional)
                tokenizer_without_change_in_init = tokenizer_class.from_pretrained(tmp_dir)
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
                self.assertIn(
                    "an_additional_special_token", tokenizer_without_change_in_init.additional_special_tokens
                )
                self.assertIn("an_additional_special_token", tokenizer_without_change_in_init.get_vocab())
                self.assertEqual(
                    ["an_additional_special_token"],
                    tokenizer_without_change_in_init.convert_ids_to_tokens(
                        tokenizer_without_change_in_init.convert_tokens_to_ids(["an_additional_special_token"])
                    ),
                )

                # Now we test that we can change the value of additional_special_tokens in the from_pretrained
                new_added_tokens = [AddedToken("a_new_additional_special_token", lstrip=True)]
                tokenizer = tokenizer_class.from_pretrained(
                    tmp_dir,
                    additional_special_tokens=new_added_tokens,
                )

                self.assertIn("a_new_additional_special_token", tokenizer.additional_special_tokens)
                self.assertEqual(
                    ["a_new_additional_special_token"],
                    tokenizer.convert_ids_to_tokens(
                        tokenizer.convert_tokens_to_ids(["a_new_additional_special_token"])
                    ),
                )

3884
3885
3886
    def test_training_new_tokenizer(self):
        # This feature only exists for fast tokenizers
        if not self.test_rust_tokenizer:
amyeroberts's avatar
amyeroberts committed
3887
            self.skipTest(reason="test_rust_tokenizer is set to False")
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897

        tokenizer = self.get_rust_tokenizer()
        new_tokenizer = tokenizer.train_new_from_iterator(SMALL_TRAINING_CORPUS, 100)

        # Test we can use the new tokenizer with something not seen during training
        inputs = new_tokenizer(["This is the first sentence", "This sentence is different 馃."])
        self.assertEqual(len(inputs["input_ids"]), 2)
        decoded_input = new_tokenizer.decode(inputs["input_ids"][0], skip_special_tokens=True)
        expected_result = "This is the first sentence"

3898
3899
        if tokenizer.backend_tokenizer.normalizer is not None:
            expected_result = tokenizer.backend_tokenizer.normalizer.normalize_str(expected_result)
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
        self.assertEqual(expected_result, decoded_input)

        # We check that the parameters of the tokenizer remained the same
        # Check we have the same number of added_tokens for both pair and non-pair inputs.
        self.assertEqual(tokenizer.num_special_tokens_to_add(False), new_tokenizer.num_special_tokens_to_add(False))
        self.assertEqual(tokenizer.num_special_tokens_to_add(True), new_tokenizer.num_special_tokens_to_add(True))

        # Check we have the correct max_length for both pair and non-pair inputs.
        self.assertEqual(tokenizer.max_len_single_sentence, new_tokenizer.max_len_single_sentence)
        self.assertEqual(tokenizer.max_len_sentences_pair, new_tokenizer.max_len_sentences_pair)

        # Assert the set of special tokens match as we didn't ask to change them
        self.assertSequenceEqual(
            tokenizer.all_special_tokens_extended,
            new_tokenizer.all_special_tokens_extended,
        )

        self.assertDictEqual(tokenizer.special_tokens_map, new_tokenizer.special_tokens_map)

    def test_training_new_tokenizer_with_special_tokens_change(self):
        # This feature only exists for fast tokenizers
        if not self.test_rust_tokenizer:
amyeroberts's avatar
amyeroberts committed
3922
            self.skipTest(reason="test_rust_tokenizer is set to False")
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988

        tokenizer = self.get_rust_tokenizer()
        # Test with a special tokens map
        class_signature = inspect.signature(tokenizer.__class__)
        if "cls_token" in class_signature.parameters:
            new_tokenizer = tokenizer.train_new_from_iterator(
                SMALL_TRAINING_CORPUS, 100, special_tokens_map={tokenizer.cls_token: "<cls>"}
            )
            cls_id = new_tokenizer.get_vocab()["<cls>"]
            self.assertEqual(new_tokenizer.cls_token, "<cls>")
            self.assertEqual(new_tokenizer.cls_token_id, cls_id)

        # Create a new mapping from the special tokens defined in the original tokenizer
        special_tokens_list = SpecialTokensMixin.SPECIAL_TOKENS_ATTRIBUTES.copy()
        special_tokens_list.remove("additional_special_tokens")
        special_tokens_map = {}
        for token in special_tokens_list:
            # Get the private one to avoid unnecessary warnings.
            if getattr(tokenizer, f"_{token}") is not None:
                special_token = getattr(tokenizer, token)
                special_tokens_map[special_token] = f"{special_token}a"

        # Train new tokenizer
        new_tokenizer = tokenizer.train_new_from_iterator(
            SMALL_TRAINING_CORPUS, 100, special_tokens_map=special_tokens_map
        )

        # Check the changes
        for token in special_tokens_list:
            # Get the private one to avoid unnecessary warnings.
            if getattr(tokenizer, f"_{token}") is None:
                continue
            special_token = getattr(tokenizer, token)
            if special_token in special_tokens_map:
                new_special_token = getattr(new_tokenizer, token)
                self.assertEqual(special_tokens_map[special_token], new_special_token)

                new_id = new_tokenizer.get_vocab()[new_special_token]
                self.assertEqual(getattr(new_tokenizer, f"{token}_id"), new_id)

        # Check if the AddedToken / string format has been kept
        for special_token in tokenizer.all_special_tokens_extended:
            if isinstance(special_token, AddedToken) and special_token.content not in special_tokens_map:
                # The special token must appear identically in the list of the new tokenizer.
                self.assertTrue(
                    special_token in new_tokenizer.all_special_tokens_extended,
                    f"'{special_token}' should be in {new_tokenizer.all_special_tokens_extended}",
                )
            elif isinstance(special_token, AddedToken):
                # The special token must appear in the list of the new tokenizer as an object of type AddedToken with
                # the same parameters as the old AddedToken except the content that the user has requested to change.
                special_token_str = special_token.content
                new_special_token_str = special_tokens_map[special_token_str]

                find = False
                for candidate in new_tokenizer.all_special_tokens_extended:
                    if (
                        isinstance(candidate, AddedToken)
                        and candidate.content == new_special_token_str
                        and candidate.lstrip == special_token.lstrip
                        and candidate.rstrip == special_token.rstrip
                        and candidate.normalized == special_token.normalized
                        and candidate.single_word == special_token.single_word
                    ):
                        find = True
                        break
3989
                special_token.content = new_special_token_str
3990
3991
                self.assertTrue(
                    find,
3992
3993
3994
                    f"'{special_token.__repr__()}' should appear as an `AddedToken` in the all_special_tokens_extended = "
                    f"{[k for k in new_tokenizer.all_special_tokens_extended if str(k)==new_special_token_str]} but it is missing"
                    ", this means that the new tokenizers did not keep the `rstrip`, `lstrip`, `normalized` etc attributes.",
3995
3996
3997
3998
3999
                )
            elif special_token not in special_tokens_map:
                # The special token must appear identically in the list of the new tokenizer.
                self.assertTrue(
                    special_token in new_tokenizer.all_special_tokens_extended,
4000
                    f"'{special_token.__repr__()}' should be in {new_tokenizer.all_special_tokens_extended}",
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
                )

            else:
                # The special token must appear in the list of the new tokenizer as an object of type string.
                self.assertTrue(special_tokens_map[special_token] in new_tokenizer.all_special_tokens_extended)

        # Test we can use the new tokenizer with something not seen during training
        inputs = new_tokenizer(["This is the first sentence", "This sentence is different 馃."])
        self.assertEqual(len(inputs["input_ids"]), 2)
        decoded_input = new_tokenizer.decode(inputs["input_ids"][0], skip_special_tokens=True)
        expected_result = "This is the first sentence"

4013
4014
        if tokenizer.backend_tokenizer.normalizer is not None:
            expected_result = tokenizer.backend_tokenizer.normalizer.normalize_str(expected_result)
4015
4016
        self.assertEqual(expected_result, decoded_input)

4017
4018
4019
4020
4021
4022
4023
4024
4025
    def test_tokenizer_mismatch_warning(self):
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
                with self.assertLogs("transformers", level="WARNING") as cm:
                    try:
                        if self.tokenizer_class == BertTokenizer:
                            AlbertTokenizer.from_pretrained(pretrained_name)
                        else:
                            BertTokenizer.from_pretrained(pretrained_name)
4026
4027
4028
4029
                    except EnvironmentError as e:
                        # Some tokenizer will raised an error before reaching the logged warning because there are no
                        # corresponding files to load
                        error_message = str(e)
4030
4031
4032
4033
4034
                    except (TypeError, AttributeError):
                        # Some tokenizers cannot be loaded into the target tokenizer at all and errors are returned,
                        # here we just check that the warning has been logged before the error is raised
                        pass
                    finally:
4035
4036
4037
4038
4039
                        logged_msg_target = (
                            "The tokenizer class you load from this checkpoint is not the same type as the class "
                            "this function is called from."
                        )
                        raised_error_msg_target = "Can't load tokenizer for"
4040
                        self.assertTrue(
4041
4042
4043
                            cm.records[0].message.startswith(logged_msg_target)
                            if len(cm.records) > 0
                            else False or raised_error_msg_target in error_message
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
                        )
                    try:
                        if self.rust_tokenizer_class == BertTokenizerFast:
                            AlbertTokenizerFast.from_pretrained(pretrained_name)
                        else:
                            BertTokenizerFast.from_pretrained(pretrained_name)
                    except (TypeError, AttributeError):
                        # Some tokenizers cannot be loaded into the target tokenizer at all and errors are returned,
                        # here we just check that the warning has been logged before the error is raised
                        pass
                    finally:
                        self.assertTrue(
                            cm.records[0].message.startswith(
Sylvain Gugger's avatar
Sylvain Gugger committed
4057
4058
                                "The tokenizer class you load from this checkpoint is not the same type as the class"
                                " this function is called from."
4059
4060
4061
                            )
                        )

4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
    @require_torch
    def test_saving_tokenizer_trainer(self):
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
                with tempfile.TemporaryDirectory() as tmp_dir:
                    # Save the fast tokenizer files in a temporary directory
                    tokenizer_old = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs, use_fast=True)
                    tokenizer_old.save_pretrained(tmp_dir, legacy_format=False)  # save only fast version

                    # Initialize toy model for the trainer
                    model = nn.Module()

                    # Load tokenizer from a folder without legacy files
                    tokenizer = self.rust_tokenizer_class.from_pretrained(tmp_dir)
                    training_args = TrainingArguments(output_dir=tmp_dir, do_train=True, no_cuda=True)
                    trainer = Trainer(model=model, args=training_args, tokenizer=tokenizer)

                    # Should not raise an error
                    trainer.save_model(os.path.join(tmp_dir, "checkpoint"))
                    self.assertIn("tokenizer.json", os.listdir(os.path.join(tmp_dir, "checkpoint")))

4083
4084
4085
4086
4087
4088
4089
4090
4091
    def test_convert_tokens_to_string_format(self):
        tokenizers = self.get_tokenizers(fast=True, do_lower_case=True)
        for tokenizer in tokenizers:
            with self.subTest(f"{tokenizer.__class__.__name__}"):
                tokens = ["this", "is", "a", "test"]
                string = tokenizer.convert_tokens_to_string(tokens)

                self.assertIsInstance(string, str)

4092
4093
4094
    def test_save_slow_from_fast_and_reload_fast(self):
        if not self.test_slow_tokenizer or not self.test_rust_tokenizer:
            # we need both slow and fast versions
amyeroberts's avatar
amyeroberts committed
4095
            self.skipTest(reason="test_rust_tokenizer or test_slow_tokenizer is set to False")
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120

        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
                with tempfile.TemporaryDirectory() as tmp_dir_1:
                    # Here we check that even if we have initialized a fast tokenizer with a tokenizer_file we can
                    # still save only the slow version and use these saved files to rebuild a tokenizer
                    tokenizer_fast_old_1 = self.rust_tokenizer_class.from_pretrained(
                        pretrained_name, **kwargs, use_fast=True
                    )
                    tokenizer_file = os.path.join(tmp_dir_1, "tokenizer.json")
                    tokenizer_fast_old_1.backend_tokenizer.save(tokenizer_file)

                    tokenizer_fast_old_2 = self.rust_tokenizer_class.from_pretrained(
                        pretrained_name, **kwargs, use_fast=True, tokenizer_file=tokenizer_file
                    )

                    tokenizer_fast_old_2.save_pretrained(tmp_dir_1, legacy_format=True)  # save only slow version

                    tokenizer_slow = self.tokenizer_class.from_pretrained(tmp_dir_1)
                with tempfile.TemporaryDirectory() as tmp_dir_2:
                    tokenizer_slow.save_pretrained(tmp_dir_2)

                    # Should not raise an error
                    self.rust_tokenizer_class.from_pretrained(tmp_dir_2)

4121
    # TODO This is ran for all models but only tests bert...
4122
    def test_clean_up_tokenization_spaces(self):
4123
        tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
        assert tokenizer.clean_up_tokenization_spaces is True

        tokens = tokenizer.encode("This shouldn't be! He'll go.")
        decoded = tokenizer.decode(tokens)
        assert decoded == "[CLS] this shouldn't be! he'll go. [SEP]"

        tokenizer.clean_up_tokenization_spaces = False
        decoded = tokenizer.decode(tokens)
        assert decoded == "[CLS] this shouldn ' t be ! he ' ll go . [SEP]"
        assert decoded == tokenizer.decode(tokens, clean_up_tokenization_spaces=False)

        # Fast from slow
        with tempfile.TemporaryDirectory() as tmp_dir_2:
            tokenizer.save_pretrained(tmp_dir_2)
            tokenizer_fast = BertTokenizerFast.from_pretrained(tmp_dir_2)
            del tokenizer

        assert tokenizer_fast.clean_up_tokenization_spaces is False
        decoded = tokenizer_fast.decode(tokens)
        # fast and slow don't have the same output when we don't cleanup
        # tokenization space. Here `be!` vs `be !` and `go.` vs `go .`
        assert decoded == "[CLS] this shouldn ' t be! he ' ll go. [SEP]"

        tokenizer_fast.clean_up_tokenization_spaces = True
        assert tokenizer_fast.clean_up_tokenization_spaces is True

        decoded = tokenizer_fast.decode(tokens)
        assert decoded == "[CLS] this shouldn't be! he'll go. [SEP]"

        # Slow from fast
        with tempfile.TemporaryDirectory() as tmp_dir_2:
            tokenizer_fast.clean_up_tokenization_spaces = False
            tokenizer_fast.save_pretrained(tmp_dir_2)
            tokenizer = BertTokenizer.from_pretrained(tmp_dir_2)

Arthur's avatar
Arthur committed
4159
        assert tokenizer.clean_up_tokenization_spaces is False
4160
4161
4162
4163
4164
4165
        decoded = tokenizer.decode(tokens)
        assert decoded == "[CLS] this shouldn ' t be ! he ' ll go . [SEP]"

        tokenizer.clean_up_tokenization_spaces = True
        decoded = tokenizer.decode(tokens)
        assert decoded == "[CLS] this shouldn't be! he'll go. [SEP]"
4166
4167
4168

    def test_split_special_tokens(self):
        if not self.test_slow_tokenizer:
amyeroberts's avatar
amyeroberts committed
4169
            self.skipTest(reason="test_slow_tokenizer is set to False")
4170
4171
        # Tests the expected appearance (or absence) of special token in encoded output,
        # explicit values are not tested because tokenization is model dependent and can change
4172
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
4173
4174
            special_token = "<my_new_token>"
            special_sentence = f"Hey this is a {special_token} token"
4175
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
4176
4177
4178
4179
4180
4181
                tokenizer_rust = self.rust_tokenizer_class.from_pretrained(
                    pretrained_name, additional_special_tokens=[special_token], split_special_tokens=True, **kwargs
                )
                tokenizer_py = self.tokenizer_class.from_pretrained(
                    pretrained_name, additional_special_tokens=[special_token], split_special_tokens=True, **kwargs
                )
4182

4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
                special_token_id = tokenizer_py.convert_tokens_to_ids(special_token)
                encoded_special_token_unsplit = tokenizer_py.encode(
                    special_token, add_special_tokens=False, split_special_tokens=False
                )
                self.assertTrue(special_token_id in encoded_special_token_unsplit)

                encoded_special_token_split = tokenizer_py.encode(special_token, add_special_tokens=False)
                self.assertTrue(special_token_id not in encoded_special_token_split)

                py_tokens_output = tokenizer_py.tokenize(special_sentence)
                rust_tokens_output = tokenizer_rust.tokenize(special_sentence)

                self.assertTrue(special_token not in py_tokens_output)
                self.assertTrue(special_token not in rust_tokens_output)

                py_tokens_output_unsplit = tokenizer_py.tokenize(special_sentence, split_special_tokens=False)
                rust_tokens_output_unsplit = tokenizer_rust.tokenize(special_sentence, split_special_tokens=False)

                self.assertTrue(special_token in py_tokens_output_unsplit)
                self.assertTrue(special_token in rust_tokens_output_unsplit)

                py_tokens_output = tokenizer_py(special_sentence)
                rust_tokens_output = tokenizer_rust(special_sentence)

                self.assertTrue(special_token_id not in py_tokens_output)
                self.assertTrue(special_token_id not in rust_tokens_output)

                tmp_dir = tempfile.mkdtemp()

                try:
                    tokenizer_py.save_pretrained(tmp_dir)
                    fast_from_saved = self.tokenizer_class.from_pretrained(tmp_dir)
                finally:
                    shutil.rmtree(tmp_dir)

                output_tokens_reloaded_split = fast_from_saved.tokenize(special_sentence)
                self.assertTrue(special_token not in output_tokens_reloaded_split)

                output_tokens_reloaded_unsplit = fast_from_saved.tokenize(special_sentence, split_special_tokens=False)
                self.assertTrue(special_token in output_tokens_reloaded_unsplit)
4223
4224
4225
4226
4227
4228
4229
4230

    def test_added_tokens_serialization(self):
        # Utility to test the added vocab
        def _test_added_vocab_and_eos(expected, tokenizer_class, expected_eos, temp_dir):
            tokenizer = tokenizer_class.from_pretrained(temp_dir)
            self.assertTrue(str(expected_eos) not in tokenizer.additional_special_tokens)
            self.assertIn(new_eos, tokenizer.added_tokens_decoder.values())
            self.assertEqual(tokenizer.added_tokens_decoder[tokenizer.eos_token_id], new_eos)
4231
            self.assertTrue(all(item in tokenizer.added_tokens_decoder.items() for item in expected.items()))
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
            return tokenizer

        new_eos = AddedToken("[NEW_EOS]", rstrip=False, lstrip=True, normalized=False, special=True)
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
                # Load a slow tokenizer from the hub, init with the new token for fast to also include it
                tokenizer = self.tokenizer_class.from_pretrained(pretrained_name, eos_token=new_eos)
                EXPECTED_ADDED_TOKENS_DECODER = tokenizer.added_tokens_decoder
                with self.subTest("Hub -> Slow: Test loading a slow tokenizer from the hub)"):
                    self.assertEqual(tokenizer._eos_token, new_eos)
                    self.assertIn(new_eos, list(tokenizer.added_tokens_decoder.values()))

                with tempfile.TemporaryDirectory() as tmp_dir_2:
                    tokenizer.save_pretrained(tmp_dir_2)
                    with self.subTest(
                        "Hub -> Slow -> Slow: Test saving this slow tokenizer and reloading it in the fast class"
                    ):
                        _test_added_vocab_and_eos(
                            EXPECTED_ADDED_TOKENS_DECODER, self.tokenizer_class, new_eos, tmp_dir_2
                        )

                    if self.rust_tokenizer_class is not None:
                        with self.subTest(
                            "Hub -> Slow -> Fast: Test saving this slow tokenizer and reloading it in the fast class"
                        ):
                            tokenizer_fast = _test_added_vocab_and_eos(
                                EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_2
                            )
                            with tempfile.TemporaryDirectory() as tmp_dir_3:
                                tokenizer_fast.save_pretrained(tmp_dir_3)
                                with self.subTest(
                                    "Hub -> Slow -> Fast -> Fast: Test saving this fast tokenizer and reloading it in the fast class"
                                ):
                                    _test_added_vocab_and_eos(
                                        EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_3
                                    )

                                with self.subTest(
                                    "Hub -> Slow -> Fast -> Slow: Test saving this slow tokenizer and reloading it in the slow class"
                                ):
                                    _test_added_vocab_and_eos(
                                        EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_3
                                    )

                with self.subTest("Hub -> Fast: Test loading a fast tokenizer from the hub)"):
                    if self.rust_tokenizer_class is not None:
                        tokenizer_fast = self.rust_tokenizer_class.from_pretrained(pretrained_name, eos_token=new_eos)
                        self.assertEqual(tokenizer_fast._eos_token, new_eos)
                        self.assertIn(new_eos, list(tokenizer_fast.added_tokens_decoder.values()))
                        # We can't test the following because for BC we kept the default rstrip lstrip in slow not fast. Will comment once normalization is alright
                        with self.subTest("Hub -> Fast == Hub -> Slow: make sure slow and fast tokenizer match"):
4283
4284
4285
4286
4287
4288
4289
                            # Fast tokenizer may have user_defined_symbols and control_symbols added, unlike slow
                            self.assertTrue(
                                all(
                                    item in tokenizer.added_tokens_decoder.items()
                                    for item in EXPECTED_ADDED_TOKENS_DECODER.items()
                                )
                            )
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302

                        EXPECTED_ADDED_TOKENS_DECODER = tokenizer_fast.added_tokens_decoder
                        with tempfile.TemporaryDirectory() as tmp_dir_4:
                            tokenizer_fast.save_pretrained(tmp_dir_4)
                            with self.subTest("Hub -> Fast -> Fast: saving Fast1 locally and loading"):
                                _test_added_vocab_and_eos(
                                    EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_4
                                )

                            with self.subTest("Hub -> Fast -> Slow: saving Fast1 locally and loading"):
                                _test_added_vocab_and_eos(
                                    EXPECTED_ADDED_TOKENS_DECODER, self.tokenizer_class, new_eos, tmp_dir_4
                                )
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327

    def test_special_token_addition(self):
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
            with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
                # Create tokenizer and add an additional special token
                tokenizer_1 = tokenizer.from_pretrained(pretrained_name)
                tokenizer_1.add_special_tokens({"additional_special_tokens": ["<tok>"]})
                self.assertEqual(tokenizer_1.additional_special_tokens, ["<tok>"])
                with tempfile.TemporaryDirectory() as tmp_dir:
                    tokenizer_1.save_pretrained(tmp_dir)
                    # Load the above tokenizer and add the same special token a second time
                    tokenizer_2 = tokenizer.from_pretrained(pretrained_name)
                    tokenizer_2.add_special_tokens({"additional_special_tokens": ["<tok>"]})
                    self.assertEqual(tokenizer_2.additional_special_tokens, ["<tok>"])

                    tokenizer_2.add_special_tokens({"additional_special_tokens": ["<tok>", "<other>"]})
                    self.assertEqual(tokenizer_2.additional_special_tokens, ["<tok>", "<other>"])
                    tokenizer_2.add_special_tokens({"additional_special_tokens": ["<other>", "<another>"]})
                    self.assertEqual(tokenizer_2.additional_special_tokens, ["<other>", "<another>"])

                    tokenizer_2.add_special_tokens(
                        {"additional_special_tokens": ["<tok>"]},
                        replace_additional_special_tokens=False,
                    )
                    self.assertEqual(tokenizer_2.additional_special_tokens, ["<other>", "<another>", "<tok>"])