test_check_copies.py 17.3 KB
Newer Older
Sylvain Gugger's avatar
Sylvain Gugger committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Copyright 2020 The HuggingFace Team. All rights reserved.
#
# 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.

15
16
17
18
19
import os
import shutil
import sys
import tempfile
import unittest
20
21
from contextlib import contextmanager
from pathlib import Path
22

23

24
git_repo_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
25
26
27
sys.path.append(os.path.join(git_repo_path, "utils"))

import check_copies  # noqa: E402
28
from check_copies import convert_to_localized_md, find_code_in_transformers, is_copy_consistent  # noqa: E402
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


# This is the reference code that will be used in the tests.
# If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated.
REFERENCE_CODE = """    def __init__(self, config):
        super().__init__()
        self.transform = BertPredictionHeadTransform(config)

        # The output weights are the same as the input embeddings, but there is
        # an output-only bias for each token.
        self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)

        self.bias = nn.Parameter(torch.zeros(config.vocab_size))

        # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
        self.decoder.bias = self.bias

    def forward(self, hidden_states):
        hidden_states = self.transform(hidden_states)
        hidden_states = self.decoder(hidden_states)
        return hidden_states
"""

52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
MOCK_BERT_CODE = """from ...modeling_utils import PreTrainedModel

def bert_function(x):
    return x


class BertAttention(nn.Module):
    def __init__(self, config):
        super().__init__()


class BertModel(BertPreTrainedModel):
    def __init__(self, config):
        super().__init__()
        self.bert = BertEncoder(config)

    @add_docstring(BERT_DOCSTRING)
    def forward(self, x):
        return self.bert(x)
"""

MOCK_BERT_COPY_CODE = """from ...modeling_utils import PreTrainedModel

# Copied from transformers.models.bert.modeling_bert.bert_function
def bert_copy_function(x):
    return x


# Copied from transformers.models.bert.modeling_bert.BertAttention
class BertCopyAttention(nn.Module):
    def __init__(self, config):
        super().__init__()
84
85


86
87
88
89
90
91
92
93
94
95
96
97
# Copied from transformers.models.bert.modeling_bert.BertModel with Bert->BertCopy all-casing
class BertCopyModel(BertCopyPreTrainedModel):
    def __init__(self, config):
        super().__init__()
        self.bertcopy = BertCopyEncoder(config)

    @add_docstring(BERTCOPY_DOCSTRING)
    def forward(self, x):
        return self.bertcopy(x)
"""


Yih-Dar's avatar
Yih-Dar committed
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
MOCK_DUMMY_BERT_CODE_MATCH = """
class BertDummyModel:
    attr_1 = 1
    attr_2 = 2

    def __init__(self, a=1, b=2):
        self.a = a
        self.b = b

    # Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward
    def forward(self, c):
        return 1

    def existing_common(self, c):
        return 4

    def existing_diff_to_be_ignored(self, c):
        return 9
"""


MOCK_DUMMY_ROBERTA_CODE_MATCH = """
# Copied from transformers.models.dummy_bert_match.modeling_dummy_bert_match.BertDummyModel with BertDummy->RobertaBertDummy
class RobertaBertDummyModel:

    attr_1 = 1
    attr_2 = 2

    def __init__(self, a=1, b=2):
        self.a = a
        self.b = b

    # Ignore copy
    def only_in_roberta_to_be_ignored(self, c):
        return 3

    # Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward
    def forward(self, c):
        return 1

    def existing_common(self, c):
        return 4

    # Ignore copy
    def existing_diff_to_be_ignored(self, c):
        return 6
"""


MOCK_DUMMY_BERT_CODE_NO_MATCH = """
class BertDummyModel:
    attr_1 = 1
    attr_2 = 2

    def __init__(self, a=1, b=2):
        self.a = a
        self.b = b

    # Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward
    def forward(self, c):
        return 1

    def only_in_bert(self, c):
        return 7

    def existing_common(self, c):
        return 4

    def existing_diff_not_ignored(self, c):
        return 8

    def existing_diff_to_be_ignored(self, c):
        return 9
"""


MOCK_DUMMY_ROBERTA_CODE_NO_MATCH = """
# Copied from transformers.models.dummy_bert_no_match.modeling_dummy_bert_no_match.BertDummyModel with BertDummy->RobertaBertDummy
class RobertaBertDummyModel:

    attr_1 = 1
    attr_2 = 3

    def __init__(self, a=1, b=2):
        self.a = a
        self.b = b

    # Ignore copy
    def only_in_roberta_to_be_ignored(self, c):
        return 3

    # Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward
    def forward(self, c):
        return 1

    def only_in_roberta_not_ignored(self, c):
        return 2

    def existing_common(self, c):
        return 4

    def existing_diff_not_ignored(self, c):
        return 5

    # Ignore copy
    def existing_diff_to_be_ignored(self, c):
        return 6
"""


EXPECTED_REPLACED_CODE = """
# Copied from transformers.models.dummy_bert_no_match.modeling_dummy_bert_no_match.BertDummyModel with BertDummy->RobertaBertDummy
class RobertaBertDummyModel:
    attr_1 = 1
    attr_2 = 2

    def __init__(self, a=1, b=2):
        self.a = a
        self.b = b

    # Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward
    def forward(self, c):
        return 1

    def only_in_bert(self, c):
        return 7

    def existing_common(self, c):
        return 4

    def existing_diff_not_ignored(self, c):
        return 8

    # Ignore copy
    def existing_diff_to_be_ignored(self, c):
        return 6

    # Ignore copy
    def only_in_roberta_to_be_ignored(self, c):
        return 3
"""


241
242
243
244
245
246
def replace_in_file(filename, old, new):
    with open(filename, "r", encoding="utf-8") as f:
        content = f.read()

    content = content.replace(old, new)

Yih-Dar's avatar
Yih-Dar committed
247
    with open(filename, "w", encoding="utf-8", newline="\n") as f:
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
        f.write(content)


def create_tmp_repo(tmp_dir):
    """
    Creates a mock repository in a temporary folder for testing.
    """
    tmp_dir = Path(tmp_dir)
    if tmp_dir.exists():
        shutil.rmtree(tmp_dir)
    tmp_dir.mkdir(exist_ok=True)

    model_dir = tmp_dir / "src" / "transformers" / "models"
    model_dir.mkdir(parents=True, exist_ok=True)

Yih-Dar's avatar
Yih-Dar committed
263
264
265
266
267
268
269
270
    models = {
        "bert": MOCK_BERT_CODE,
        "bertcopy": MOCK_BERT_COPY_CODE,
        "dummy_bert_match": MOCK_DUMMY_BERT_CODE_MATCH,
        "dummy_roberta_match": MOCK_DUMMY_ROBERTA_CODE_MATCH,
        "dummy_bert_no_match": MOCK_DUMMY_BERT_CODE_NO_MATCH,
        "dummy_roberta_no_match": MOCK_DUMMY_ROBERTA_CODE_NO_MATCH,
    }
271
272
273
    for model, code in models.items():
        model_subdir = model_dir / model
        model_subdir.mkdir(exist_ok=True)
Yih-Dar's avatar
Yih-Dar committed
274
        with open(model_subdir / f"modeling_{model}.py", "w", encoding="utf-8", newline="\n") as f:
275
276
            f.write(code)

277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298

@contextmanager
def patch_transformer_repo_path(new_folder):
    """
    Temporarily patches the variables defines in `check_copies` to use a different location for the repo.
    """
    old_repo_path = check_copies.REPO_PATH
    old_doc_path = check_copies.PATH_TO_DOCS
    old_transformer_path = check_copies.TRANSFORMERS_PATH
    repo_path = Path(new_folder).resolve()
    check_copies.REPO_PATH = str(repo_path)
    check_copies.PATH_TO_DOCS = str(repo_path / "docs" / "source" / "en")
    check_copies.TRANSFORMERS_PATH = str(repo_path / "src" / "transformers")
    try:
        yield
    finally:
        check_copies.REPO_PATH = old_repo_path
        check_copies.PATH_TO_DOCS = old_doc_path
        check_copies.TRANSFORMERS_PATH = old_transformer_path


class CopyCheckTester(unittest.TestCase):
299
    def test_find_code_in_transformers(self):
300
301
302
303
        with tempfile.TemporaryDirectory() as tmp_folder:
            create_tmp_repo(tmp_folder)
            with patch_transformer_repo_path(tmp_folder):
                code = find_code_in_transformers("models.bert.modeling_bert.BertAttention")
304

305
306
        reference_code = (
            "class BertAttention(nn.Module):\n    def __init__(self, config):\n        super().__init__()\n"
307
        )
308
        self.assertEqual(code, reference_code)
309

310
311
312
313
314
315
316
317
318
    def test_is_copy_consistent(self):
        path_to_check = ["src", "transformers", "models", "bertcopy", "modeling_bertcopy.py"]
        with tempfile.TemporaryDirectory() as tmp_folder:
            # Base check
            create_tmp_repo(tmp_folder)
            with patch_transformer_repo_path(tmp_folder):
                file_to_check = os.path.join(tmp_folder, *path_to_check)
                diffs = is_copy_consistent(file_to_check)
                self.assertEqual(diffs, [])
319

320
321
322
323
            # Base check with an inconsistency
            create_tmp_repo(tmp_folder)
            with patch_transformer_repo_path(tmp_folder):
                file_to_check = os.path.join(tmp_folder, *path_to_check)
324

325
326
327
                replace_in_file(file_to_check, "self.bertcopy(x)", "self.bert(x)")
                diffs = is_copy_consistent(file_to_check)
                self.assertEqual(diffs, [["models.bert.modeling_bert.BertModel", 22]])
328

Yih-Dar's avatar
Yih-Dar committed
329
                _ = is_copy_consistent(file_to_check, overwrite=True)
330
331
332

                with open(file_to_check, "r", encoding="utf-8") as f:
                    self.assertEqual(f.read(), MOCK_BERT_COPY_CODE)
333

Yih-Dar's avatar
Yih-Dar committed
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
    def test_is_copy_consistent_with_ignored_match(self):
        path_to_check = ["src", "transformers", "models", "dummy_roberta_match", "modeling_dummy_roberta_match.py"]
        with tempfile.TemporaryDirectory() as tmp_folder:
            # Base check
            create_tmp_repo(tmp_folder)
            with patch_transformer_repo_path(tmp_folder):
                file_to_check = os.path.join(tmp_folder, *path_to_check)
                diffs = is_copy_consistent(file_to_check)
                self.assertEqual(diffs, [])

    def test_is_copy_consistent_with_ignored_no_match(self):
        path_to_check = [
            "src",
            "transformers",
            "models",
            "dummy_roberta_no_match",
            "modeling_dummy_roberta_no_match.py",
        ]
        with tempfile.TemporaryDirectory() as tmp_folder:
            # Base check with an inconsistency
            create_tmp_repo(tmp_folder)
            with patch_transformer_repo_path(tmp_folder):
                file_to_check = os.path.join(tmp_folder, *path_to_check)

                diffs = is_copy_consistent(file_to_check)
                # line 6: `attr_2 = 3` in `MOCK_DUMMY_ROBERTA_CODE_NO_MATCH`.
                # (which has a leading `\n`.)
                self.assertEqual(
                    diffs, [["models.dummy_bert_no_match.modeling_dummy_bert_no_match.BertDummyModel", 6]]
                )

                _ = is_copy_consistent(file_to_check, overwrite=True)

                with open(file_to_check, "r", encoding="utf-8") as f:
                    self.assertEqual(f.read(), EXPECTED_REPLACED_CODE)

370
371
372
    def test_convert_to_localized_md(self):
        localized_readme = check_copies.LOCALIZED_READMES["README_zh-hans.md"]

Sylvain Gugger's avatar
Sylvain Gugger committed
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
        md_list = (
            "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"
            " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"
            " Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"
            " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1."
            " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),"
            " released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"
            " lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same"
            " method has been applied to compress GPT2 into"
            " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"
            " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"
            " Multilingual BERT into"
            " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"
            " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**"
            " (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders"
            " as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang"
            " Luong, Quoc V. Le, Christopher D. Manning."
        )
        localized_md_list = (
            "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
            " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
            " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
            " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
        )
        converted_md_list_sample = (
            "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
            " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
            " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
            " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1."
            " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文"
            " [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"
            " lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same"
            " method has been applied to compress GPT2 into"
            " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"
            " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"
            " Multilingual BERT into"
            " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"
            " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自"
            " Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather"
            " than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,"
            " Christopher D. Manning 发布。\n"
        )
415

416
        num_models_equal, converted_md_list = convert_to_localized_md(
417
418
419
420
421
422
            md_list, localized_md_list, localized_readme["format_model_list"]
        )

        self.assertFalse(num_models_equal)
        self.assertEqual(converted_md_list, converted_md_list_sample)

423
        num_models_equal, converted_md_list = convert_to_localized_md(
424
425
426
427
428
            md_list, converted_md_list, localized_readme["format_model_list"]
        )

        # Check whether the number of models is equal to README.md after conversion.
        self.assertTrue(num_models_equal)
429

Sylvain Gugger's avatar
Sylvain Gugger committed
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
        link_changed_md_list = (
            "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"
            " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"
            " Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"
            " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut."
        )
        link_unchanged_md_list = (
            "1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and"
            " the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
            " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
            " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
        )
        converted_md_list_sample = (
            "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"
            " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"
            " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"
            " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"
        )
448

449
        num_models_equal, converted_md_list = convert_to_localized_md(
450
451
452
453
454
            link_changed_md_list, link_unchanged_md_list, localized_readme["format_model_list"]
        )

        # Check if the model link is synchronized.
        self.assertEqual(converted_md_list, converted_md_list_sample)