test_tokenization_bert.py 6.83 KB
Newer Older
thomwolf's avatar
thomwolf committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# 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

thomwolf's avatar
thomwolf committed
16
17

import os
18
import unittest
thomwolf's avatar
thomwolf committed
19

20
from transformers.testing_utils import slow
21
from transformers.tokenization_bert import (
Aymeric Augustin's avatar
Aymeric Augustin committed
22
    VOCAB_FILES_NAMES,
23
24
    BasicTokenizer,
    BertTokenizer,
Anthony MOI's avatar
Anthony MOI committed
25
    BertTokenizerFast,
26
27
28
29
30
    WordpieceTokenizer,
    _is_control,
    _is_punctuation,
    _is_whitespace,
)
thomwolf's avatar
thomwolf committed
31

32
from .test_tokenization_common import TokenizerTesterMixin
thomwolf's avatar
thomwolf committed
33

34

35
class BertTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
36
37

    tokenizer_class = BertTokenizer
Anthony MOI's avatar
Anthony MOI committed
38
    test_rust_tokenizer = True
39
40

    def setUp(self):
Julien Chaumond's avatar
Julien Chaumond committed
41
        super().setUp()
thomwolf's avatar
thomwolf committed
42

43
        vocab_tokens = [
44
45
46
            "[UNK]",
            "[CLS]",
            "[SEP]",
47
48
            "[PAD]",
            "[MASK]",
49
50
51
52
53
54
55
56
57
58
            "want",
            "##want",
            "##ed",
            "wa",
            "un",
            "runn",
            "##ing",
            ",",
            "low",
            "lowest",
59
        ]
60
61
        self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"])
        with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer:
62
            vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
thomwolf's avatar
thomwolf committed
63

Anthony MOI's avatar
Anthony MOI committed
64
65
66
    def get_rust_tokenizer(self, **kwargs):
        return BertTokenizerFast.from_pretrained(self.tmpdirname, **kwargs)

67
    def get_input_output_texts(self, tokenizer):
68
69
        input_text = "UNwant\u00E9d,running"
        output_text = "unwanted, running"
70
        return input_text, output_text
71

72
    def test_full_tokenizer(self):
thomwolf's avatar
thomwolf committed
73
        tokenizer = self.tokenizer_class(self.vocab_file)
thomwolf's avatar
thomwolf committed
74

75
        tokens = tokenizer.tokenize("UNwant\u00E9d,running")
76
        self.assertListEqual(tokens, ["un", "##want", "##ed", ",", "runn", "##ing"])
77
        self.assertListEqual(tokenizer.convert_tokens_to_ids(tokens), [9, 6, 7, 12, 10, 11])
78

Anthony MOI's avatar
Anthony MOI committed
79
80
81
82
83
    def test_rust_and_python_full_tokenizers(self):
        if not self.test_rust_tokenizer:
            return

        tokenizer = self.get_tokenizer()
Funtowicz Morgan's avatar
Funtowicz Morgan committed
84
        rust_tokenizer = self.get_rust_tokenizer()
Anthony MOI's avatar
Anthony MOI committed
85

86
        sequence = "UNwant\u00E9d,running"
Anthony MOI's avatar
Anthony MOI committed
87
88
89
90
91
92

        tokens = tokenizer.tokenize(sequence)
        rust_tokens = rust_tokenizer.tokenize(sequence)
        self.assertListEqual(tokens, rust_tokens)

        ids = tokenizer.encode(sequence, add_special_tokens=False)
Funtowicz Morgan's avatar
Funtowicz Morgan committed
93
        rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False)
Anthony MOI's avatar
Anthony MOI committed
94
95
96
97
98
99
100
        self.assertListEqual(ids, rust_ids)

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

101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
        # With lower casing
        tokenizer = self.get_tokenizer(do_lower_case=True)
        rust_tokenizer = self.get_rust_tokenizer(do_lower_case=True)

        sequence = "UNwant\u00E9d,running"

        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)

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

120
    def test_chinese(self):
thomwolf's avatar
thomwolf committed
121
        tokenizer = BasicTokenizer()
122

123
        self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz"), ["ah", "\u535A", "\u63A8", "zz"])
124

125
    def test_basic_tokenizer_lower(self):
thomwolf's avatar
thomwolf committed
126
        tokenizer = BasicTokenizer(do_lower_case=True)
thomwolf's avatar
thomwolf committed
127

128
        self.assertListEqual(
129
130
131
            tokenizer.tokenize(" \tHeLLo!how  \n Are yoU?  "), ["hello", "!", "how", "are", "you", "?"]
        )
        self.assertListEqual(tokenizer.tokenize("H\u00E9llo"), ["hello"])
thomwolf's avatar
thomwolf committed
132

133
    def test_basic_tokenizer_no_lower(self):
thomwolf's avatar
thomwolf committed
134
        tokenizer = BasicTokenizer(do_lower_case=False)
thomwolf's avatar
thomwolf committed
135

136
        self.assertListEqual(
137
138
            tokenizer.tokenize(" \tHeLLo!how  \n Are yoU?  "), ["HeLLo", "!", "how", "Are", "yoU", "?"]
        )
thomwolf's avatar
thomwolf committed
139

140
141
142
143
144
145
146
    def test_basic_tokenizer_respects_never_split_tokens(self):
        tokenizer = BasicTokenizer(do_lower_case=False, never_split=["[UNK]"])

        self.assertListEqual(
            tokenizer.tokenize(" \tHeLLo!how  \n Are yoU? [UNK]"), ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"]
        )

147
    def test_wordpiece_tokenizer(self):
148
        vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"]
thomwolf's avatar
thomwolf committed
149

150
151
152
        vocab = {}
        for (i, token) in enumerate(vocab_tokens):
            vocab[token] = i
153
        tokenizer = WordpieceTokenizer(vocab=vocab, unk_token="[UNK]")
thomwolf's avatar
thomwolf committed
154

155
        self.assertListEqual(tokenizer.tokenize(""), [])
thomwolf's avatar
thomwolf committed
156

157
        self.assertListEqual(tokenizer.tokenize("unwanted running"), ["un", "##want", "##ed", "runn", "##ing"])
thomwolf's avatar
thomwolf committed
158

159
        self.assertListEqual(tokenizer.tokenize("unwantedX running"), ["[UNK]", "runn", "##ing"])
thomwolf's avatar
thomwolf committed
160

161
    def test_is_whitespace(self):
162
163
164
165
166
        self.assertTrue(_is_whitespace(" "))
        self.assertTrue(_is_whitespace("\t"))
        self.assertTrue(_is_whitespace("\r"))
        self.assertTrue(_is_whitespace("\n"))
        self.assertTrue(_is_whitespace("\u00A0"))
thomwolf's avatar
thomwolf committed
167

168
169
        self.assertFalse(_is_whitespace("A"))
        self.assertFalse(_is_whitespace("-"))
thomwolf's avatar
thomwolf committed
170

171
    def test_is_control(self):
172
        self.assertTrue(_is_control("\u0005"))
thomwolf's avatar
thomwolf committed
173

174
175
176
177
        self.assertFalse(_is_control("A"))
        self.assertFalse(_is_control(" "))
        self.assertFalse(_is_control("\t"))
        self.assertFalse(_is_control("\r"))
thomwolf's avatar
thomwolf committed
178

179
    def test_is_punctuation(self):
180
181
182
183
        self.assertTrue(_is_punctuation("-"))
        self.assertTrue(_is_punctuation("$"))
        self.assertTrue(_is_punctuation("`"))
        self.assertTrue(_is_punctuation("."))
thomwolf's avatar
thomwolf committed
184

185
186
        self.assertFalse(_is_punctuation("A"))
        self.assertFalse(_is_punctuation(" "))
thomwolf's avatar
thomwolf committed
187

188
    @slow
189
    def test_sequence_builders(self):
thomwolf's avatar
thomwolf committed
190
        tokenizer = self.tokenizer_class.from_pretrained("bert-base-uncased")
191

Lysandre's avatar
Remove  
Lysandre committed
192
193
        text = tokenizer.encode("sequence builders", add_special_tokens=False)
        text_2 = tokenizer.encode("multi-sequence build", add_special_tokens=False)
194

195
196
        encoded_sentence = tokenizer.build_inputs_with_special_tokens(text)
        encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2)
197
198
199

        assert encoded_sentence == [101] + text + [102]
        assert encoded_pair == [101] + text + [102] + text_2 + [102]