test_modeling_marian.py 11.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# coding=utf-8
# Copyright 2020 HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import unittest

19
from transformers import AutoConfig, AutoTokenizer, MarianConfig, MarianTokenizer, is_torch_available
20
from transformers.file_utils import cached_property
21
from transformers.hf_api import HfApi
22
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
23

24
25
from .test_modeling_common import ModelTesterMixin

26
27
28

if is_torch_available():
    import torch
29

30
    from transformers import AutoModelWithLMHead, MarianMTModel
Sylvain Gugger's avatar
Sylvain Gugger committed
31
32
    from transformers.models.bart.modeling_bart import shift_tokens_right
    from transformers.models.marian.convert_marian_to_pytorch import (
33
        ORG_NAME,
34
35
36
        convert_hf_name_to_opus_name,
        convert_opus_name_to_hf_name,
    )
37
    from transformers.pipelines import TranslationPipeline
38
39


40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class ModelTester:
    def __init__(self, parent):
        self.config = MarianConfig(
            vocab_size=99,
            d_model=24,
            encoder_layers=2,
            decoder_layers=2,
            encoder_attention_heads=2,
            decoder_attention_heads=2,
            encoder_ffn_dim=32,
            decoder_ffn_dim=32,
            max_position_embeddings=48,
            add_final_layer_norm=True,
        )

    def prepare_config_and_inputs_for_common(self):
        return self.config, {}


@require_torch
class SelectiveCommonTest(unittest.TestCase):
    all_model_classes = (MarianMTModel,) if is_torch_available() else ()

    test_save_load_keys_to_never_save = ModelTesterMixin.test_save_load_keys_to_never_save

    def setUp(self):
        self.model_tester = ModelTester(self)


69
70
class ModelManagementTests(unittest.TestCase):
    @slow
Lysandre Debut's avatar
Lysandre Debut committed
71
    @require_torch
72
    def test_model_names(self):
73
        model_list = HfApi().model_list()
74
75
76
77
        model_ids = [x.modelId for x in model_list if x.modelId.startswith(ORG_NAME)]
        bad_model_ids = [mid for mid in model_ids if "+" in model_ids]
        self.assertListEqual([], bad_model_ids)
        self.assertGreater(len(model_ids), 500)
78
79
80


@require_torch
81
82
@require_sentencepiece
@require_tokenizers
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
class MarianIntegrationTest(unittest.TestCase):
    src = "en"
    tgt = "de"
    src_text = [
        "I am a small frog.",
        "Now I can forget the 100 words of german that I know.",
        "Tom asked his teacher for advice.",
        "That's how I would do it.",
        "Tom really admired Mary's courage.",
        "Turn around and close your eyes.",
    ]
    expected_text = [
        "Ich bin ein kleiner Frosch.",
        "Jetzt kann ich die 100 Wörter des Deutschen vergessen, die ich kenne.",
        "Tom bat seinen Lehrer um Rat.",
        "So würde ich das machen.",
        "Tom bewunderte Marias Mut wirklich.",
        "Drehen Sie sich um und schließen Sie die Augen.",
    ]
    # ^^ actual C++ output differs slightly: (1) des Deutschen removed, (2) ""-> "O", (3) tun -> machen

104
105
    @classmethod
    def setUpClass(cls) -> None:
106
        cls.model_name = f"Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}"
107
108
        return cls

109
110
111
112
113
114
115
116
    @cached_property
    def tokenizer(self) -> MarianTokenizer:
        return AutoTokenizer.from_pretrained(self.model_name)

    @property
    def eos_token_id(self) -> int:
        return self.tokenizer.eos_token_id

117
118
    @cached_property
    def model(self):
119
120
121
122
123
124
        model: MarianMTModel = AutoModelWithLMHead.from_pretrained(self.model_name).to(torch_device)
        c = model.config
        self.assertListEqual(c.bad_words_ids, [[c.pad_token_id]])
        self.assertEqual(c.max_length, 512)
        self.assertEqual(c.decoder_start_token_id, c.pad_token_id)

125
126
127
128
129
        if torch_device == "cuda":
            return model.half()
        else:
            return model

130
131
132
133
134
    def _assert_generated_batch_equal_expected(self, **tokenizer_kwargs):
        generated_words = self.translate_src_text(**tokenizer_kwargs)
        self.assertListEqual(self.expected_text, generated_words)

    def translate_src_text(self, **tokenizer_kwargs):
135
136
137
        model_inputs = self.tokenizer.prepare_seq2seq_batch(
            src_texts=self.src_text, return_tensors="pt", **tokenizer_kwargs
        ).to(torch_device)
138
        self.assertEqual(self.model.device, model_inputs.input_ids.device)
139
        generated_ids = self.model.generate(
140
            model_inputs.input_ids, attention_mask=model_inputs.attention_mask, num_beams=2, max_length=128
141
142
143
144
145
        )
        generated_words = self.tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
        return generated_words


146
147
@require_sentencepiece
@require_tokenizers
148
class TestMarian_EN_DE_More(MarianIntegrationTest):
149
150
    @slow
    def test_forward(self):
151
        src, tgt = ["I am a small frog"], ["Ich bin ein kleiner Frosch."]
152
        expected_ids = [38, 121, 14, 697, 38848, 0]
153

154
155
156
        model_inputs: dict = self.tokenizer.prepare_seq2seq_batch(src, tgt_texts=tgt, return_tensors="pt").to(
            torch_device
        )
Sam Shleifer's avatar
Sam Shleifer committed
157

158
        self.assertListEqual(expected_ids, model_inputs.input_ids[0].tolist())
159
160
161
162

        desired_keys = {
            "input_ids",
            "attention_mask",
Sam Shleifer's avatar
Sam Shleifer committed
163
            "labels",
164
165
        }
        self.assertSetEqual(desired_keys, set(model_inputs.keys()))
Sam Shleifer's avatar
Sam Shleifer committed
166
167
168
        model_inputs["decoder_input_ids"] = shift_tokens_right(model_inputs.labels, self.tokenizer.pad_token_id)
        model_inputs["return_dict"] = True
        model_inputs["use_cache"] = False
169
        with torch.no_grad():
Sam Shleifer's avatar
Sam Shleifer committed
170
171
            outputs = self.model(**model_inputs)
        max_indices = outputs.logits.argmax(-1)
172
        self.tokenizer.batch_decode(max_indices)
173

174
175
    def test_unk_support(self):
        t = self.tokenizer
176
        ids = t.prepare_seq2seq_batch(["||"], return_tensors="pt").to(torch_device).input_ids[0].tolist()
177
178
179
        expected = [t.unk_token_id, t.unk_token_id, t.eos_token_id]
        self.assertEqual(expected, ids)

180
    def test_pad_not_split(self):
181
182
183
184
185
        input_ids_w_pad = (
            self.tokenizer.prepare_seq2seq_batch(["I am a small frog <pad>"], return_tensors="pt")
            .input_ids[0]
            .tolist()
        )
186
        expected_w_pad = [38, 121, 14, 697, 38848, self.tokenizer.pad_token_id, 0]  # pad
187
        self.assertListEqual(expected_w_pad, input_ids_w_pad)
188
189
190
191
192
193
194
195
196
197

    @slow
    def test_batch_generation_en_de(self):
        self._assert_generated_batch_equal_expected()

    def test_auto_config(self):
        config = AutoConfig.from_pretrained(self.model_name)
        self.assertIsInstance(config, MarianConfig)


198
199
@require_sentencepiece
@require_tokenizers
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
class TestMarian_EN_FR(MarianIntegrationTest):
    src = "en"
    tgt = "fr"
    src_text = [
        "I am a small frog.",
        "Now I can forget the 100 words of german that I know.",
    ]
    expected_text = [
        "Je suis une petite grenouille.",
        "Maintenant, je peux oublier les 100 mots d'allemand que je connais.",
    ]

    @slow
    def test_batch_generation_en_fr(self):
        self._assert_generated_batch_equal_expected()


217
218
@require_sentencepiece
@require_tokenizers
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
class TestMarian_FR_EN(MarianIntegrationTest):
    src = "fr"
    tgt = "en"
    src_text = [
        "Donnez moi le micro.",
        "Tom et Mary étaient assis à une table.",  # Accents
    ]
    expected_text = [
        "Give me the microphone.",
        "Tom and Mary were sitting at a table.",
    ]

    @slow
    def test_batch_generation_fr_en(self):
        self._assert_generated_batch_equal_expected()


236
237
@require_sentencepiece
@require_tokenizers
238
239
240
241
class TestMarian_RU_FR(MarianIntegrationTest):
    src = "ru"
    tgt = "fr"
    src_text = ["Он показал мне рукопись своей новой пьесы."]
242
    expected_text = ["Il m'a montré le manuscrit de sa nouvelle pièce."]
243

244
    @slow
245
246
247
248
    def test_batch_generation_ru_fr(self):
        self._assert_generated_batch_equal_expected()


249
250
@require_sentencepiece
@require_tokenizers
251
class TestMarian_MT_EN(MarianIntegrationTest):
252
253
    """Cover low resource/high perplexity setting. This breaks without adjust_logits_generation overwritten"""

254
255
    src = "mt"
    tgt = "en"
256
257
    src_text = ["Billi messu b'mod ġentili, Ġesù fejjaq raġel li kien milqut bil - marda kerha tal - ġdiem."]
    expected_text = ["Touching gently, Jesus healed a man who was affected by the sad disease of leprosy."]
258

259
    @slow
260
261
262
263
    def test_batch_generation_mt_en(self):
        self._assert_generated_batch_equal_expected()


264
265
@require_sentencepiece
@require_tokenizers
Sam Shleifer's avatar
Sam Shleifer committed
266
267
268
class TestMarian_en_zh(MarianIntegrationTest):
    src = "en"
    tgt = "zh"
269
270
271
272
273
274
275
276
    src_text = ["My name is Wolfgang and I live in Berlin"]
    expected_text = ["我叫沃尔夫冈 我住在柏林"]

    @slow
    def test_batch_generation_eng_zho(self):
        self._assert_generated_batch_equal_expected()


277
278
@require_sentencepiece
@require_tokenizers
279
280
class TestMarian_en_ROMANCE(MarianIntegrationTest):
    """Multilingual on target side."""
281

282
283
284
285
286
287
288
289
290
291
292
293
    src = "en"
    tgt = "ROMANCE"
    src_text = [
        ">>fr<< Don't spend so much time watching TV.",
        ">>pt<< Your message has been sent.",
        ">>es<< He's two years older than me.",
    ]
    expected_text = [
        "Ne passez pas autant de temps à regarder la télé.",
        "A sua mensagem foi enviada.",
        "Es dos años más viejo que yo.",
    ]
294

295
296
    @slow
    def test_batch_generation_en_ROMANCE_multi(self):
297
298
        self._assert_generated_batch_equal_expected()

299
300
301
302
    def test_tokenizer_handles_empty(self):
        normalized = self.tokenizer.normalize("")
        self.assertIsInstance(normalized, str)
        with self.assertRaises(ValueError):
303
            self.tokenizer.prepare_seq2seq_batch([""], return_tensors="pt")
304

305
    @slow
306
    def test_pipeline(self):
307
308
        device = 0 if torch_device == "cuda" else -1
        pipeline = TranslationPipeline(self.model, self.tokenizer, framework="pt", device=device)
309
310
311
        output = pipeline(self.src_text)
        self.assertEqual(self.expected_text, [x["translation_text"] for x in output])

312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334

@require_torch
class TestConversionUtils(unittest.TestCase):
    def test_renaming_multilingual(self):
        old_names = [
            "opus-mt-cmn+cn+yue+ze_zh+zh_cn+zh_CN+zh_HK+zh_tw+zh_TW+zh_yue+zhs+zht+zh-fi",
            "opus-mt-cmn+cn-fi",  # no group
            "opus-mt-en-de",  # standard name
            "opus-mt-en-de",  # standard name
        ]
        expected = ["opus-mt-ZH-fi", "opus-mt-cmn_cn-fi", "opus-mt-en-de", "opus-mt-en-de"]
        self.assertListEqual(expected, [convert_opus_name_to_hf_name(x) for x in old_names])

    def test_undoing_renaming(self):
        hf_names = ["opus-mt-ZH-fi", "opus-mt-cmn_cn-fi", "opus-mt-en-de", "opus-mt-en-de"]
        converted_opus_names = [convert_hf_name_to_opus_name(x) for x in hf_names]
        expected_opus_names = [
            "cmn+cn+yue+ze_zh+zh_cn+zh_CN+zh_HK+zh_tw+zh_TW+zh_yue+zhs+zht+zh-fi",
            "cmn+cn-fi",
            "en-de",  # standard name
            "en-de",
        ]
        self.assertListEqual(expected_opus_names, converted_opus_names)