check_dummies.py 13.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# coding=utf-8
# Copyright 2020 The 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 argparse
import os
import re


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_dummies.py
PATH_TO_TRANSFORMERS = "src/transformers"

_re_single_line_import = re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n")

DUMMY_CONSTANT = """
{0} = None
"""

DUMMY_PT_PRETRAINED_CLASS = """
class {0}:
    def __init__(self, *args, **kwargs):
        requires_pytorch(self)

    @classmethod
    def from_pretrained(self, *args, **kwargs):
        requires_pytorch(self)
"""

DUMMY_PT_CLASS = """
class {0}:
    def __init__(self, *args, **kwargs):
        requires_pytorch(self)
"""

DUMMY_PT_FUNCTION = """
def {0}(*args, **kwargs):
    requires_pytorch({0})
"""

52

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
DUMMY_TF_PRETRAINED_CLASS = """
class {0}:
    def __init__(self, *args, **kwargs):
        requires_tf(self)

    @classmethod
    def from_pretrained(self, *args, **kwargs):
        requires_tf(self)
"""

DUMMY_TF_CLASS = """
class {0}:
    def __init__(self, *args, **kwargs):
        requires_tf(self)
"""

DUMMY_TF_FUNCTION = """
def {0}(*args, **kwargs):
    requires_tf({0})
"""


75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
DUMMY_FLAX_PRETRAINED_CLASS = """
class {0}:
    def __init__(self, *args, **kwargs):
        requires_flax(self)

    @classmethod
    def from_pretrained(self, *args, **kwargs):
        requires_flax(self)
"""

DUMMY_FLAX_CLASS = """
class {0}:
    def __init__(self, *args, **kwargs):
        requires_flax(self)
"""

DUMMY_FLAX_FUNCTION = """
def {0}(*args, **kwargs):
    requires_flax({0})
"""


97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
DUMMY_SENTENCEPIECE_PRETRAINED_CLASS = """
class {0}:
    def __init__(self, *args, **kwargs):
        requires_sentencepiece(self)

    @classmethod
    def from_pretrained(self, *args, **kwargs):
        requires_sentencepiece(self)
"""

DUMMY_SENTENCEPIECE_CLASS = """
class {0}:
    def __init__(self, *args, **kwargs):
        requires_sentencepiece(self)
"""

DUMMY_SENTENCEPIECE_FUNCTION = """
def {0}(*args, **kwargs):
    requires_sentencepiece({0})
"""


DUMMY_TOKENIZERS_PRETRAINED_CLASS = """
class {0}:
    def __init__(self, *args, **kwargs):
        requires_tokenizers(self)

    @classmethod
    def from_pretrained(self, *args, **kwargs):
        requires_tokenizers(self)
"""

DUMMY_TOKENIZERS_CLASS = """
class {0}:
    def __init__(self, *args, **kwargs):
        requires_tokenizers(self)
"""

DUMMY_TOKENIZERS_FUNCTION = """
def {0}(*args, **kwargs):
    requires_tokenizers({0})
"""

# Map all these to dummy type

DUMMY_PRETRAINED_CLASS = {
    "pt": DUMMY_PT_PRETRAINED_CLASS,
    "tf": DUMMY_TF_PRETRAINED_CLASS,
145
    "flax": DUMMY_FLAX_PRETRAINED_CLASS,
146
147
148
149
150
151
152
    "sentencepiece": DUMMY_SENTENCEPIECE_PRETRAINED_CLASS,
    "tokenizers": DUMMY_TOKENIZERS_PRETRAINED_CLASS,
}

DUMMY_CLASS = {
    "pt": DUMMY_PT_CLASS,
    "tf": DUMMY_TF_CLASS,
153
    "flax": DUMMY_FLAX_CLASS,
154
155
156
157
158
159
160
    "sentencepiece": DUMMY_SENTENCEPIECE_CLASS,
    "tokenizers": DUMMY_TOKENIZERS_CLASS,
}

DUMMY_FUNCTION = {
    "pt": DUMMY_PT_FUNCTION,
    "tf": DUMMY_TF_FUNCTION,
161
    "flax": DUMMY_FLAX_FUNCTION,
162
163
164
165
166
    "sentencepiece": DUMMY_SENTENCEPIECE_FUNCTION,
    "tokenizers": DUMMY_TOKENIZERS_FUNCTION,
}


167
def read_init():
Julien Chaumond's avatar
Julien Chaumond committed
168
    """ Read the init and extracts PyTorch, TensorFlow, SentencePiece and Tokenizers objects. """
169
170
171
172
    with open(os.path.join(PATH_TO_TRANSFORMERS, "__init__.py"), "r", encoding="utf-8") as f:
        lines = f.readlines()

    line_index = 0
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
    # Find where the SentencePiece imports begin
    sentencepiece_objects = []
    while not lines[line_index].startswith("if is_sentencepiece_available():"):
        line_index += 1
    line_index += 1

    # Until we unindent, add SentencePiece objects to the list
    while len(lines[line_index]) <= 1 or lines[line_index].startswith("    "):
        line = lines[line_index]
        search = _re_single_line_import.search(line)
        if search is not None:
            sentencepiece_objects += search.groups()[0].split(", ")
        elif line.startswith("        "):
            sentencepiece_objects.append(line[8:-2])
        line_index += 1

    # Find where the Tokenizers imports begin
    tokenizers_objects = []
    while not lines[line_index].startswith("if is_tokenizers_available():"):
        line_index += 1
    line_index += 1

    # Until we unindent, add Tokenizers objects to the list
    while len(lines[line_index]) <= 1 or lines[line_index].startswith("    "):
        line = lines[line_index]
        search = _re_single_line_import.search(line)
        if search is not None:
            tokenizers_objects += search.groups()[0].split(", ")
        elif line.startswith("        "):
            tokenizers_objects.append(line[8:-2])
        line_index += 1

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
    # Find where the PyTorch imports begin
    pt_objects = []
    while not lines[line_index].startswith("if is_torch_available():"):
        line_index += 1
    line_index += 1

    # Until we unindent, add PyTorch objects to the list
    while len(lines[line_index]) <= 1 or lines[line_index].startswith("    "):
        line = lines[line_index]
        search = _re_single_line_import.search(line)
        if search is not None:
            pt_objects += search.groups()[0].split(", ")
        elif line.startswith("        "):
            pt_objects.append(line[8:-2])
        line_index += 1

    # Find where the TF imports begin
    tf_objects = []
    while not lines[line_index].startswith("if is_tf_available():"):
        line_index += 1
    line_index += 1

    # Until we unindent, add PyTorch objects to the list
    while len(lines[line_index]) <= 1 or lines[line_index].startswith("    "):
        line = lines[line_index]
        search = _re_single_line_import.search(line)
        if search is not None:
            tf_objects += search.groups()[0].split(", ")
        elif line.startswith("        "):
            tf_objects.append(line[8:-2])
        line_index += 1
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253

    # Find where the FLAX imports begin
    flax_objects = []
    while not lines[line_index].startswith("if is_flax_available():"):
        line_index += 1
    line_index += 1

    # Until we unindent, add PyTorch objects to the list
    while len(lines[line_index]) <= 1 or lines[line_index].startswith("    "):
        line = lines[line_index]
        search = _re_single_line_import.search(line)
        if search is not None:
            flax_objects += search.groups()[0].split(", ")
        elif line.startswith("        "):
            flax_objects.append(line[8:-2])
        line_index += 1

    return sentencepiece_objects, tokenizers_objects, pt_objects, tf_objects, flax_objects
254
255


256
def create_dummy_object(name, type="pt"):
257
258
259
260
261
262
263
264
265
266
267
268
    """ Create the code for the dummy object corresponding to `name`."""
    _pretrained = [
        "Config" "ForCausalLM",
        "ForConditionalGeneration",
        "ForMaskedLM",
        "ForMultipleChoice",
        "ForQuestionAnswering",
        "ForSequenceClassification",
        "ForTokenClassification",
        "Model",
        "Tokenizer",
    ]
269
    assert type in ["pt", "tf", "sentencepiece", "tokenizers", "flax"]
270
271
272
    if name.isupper():
        return DUMMY_CONSTANT.format(name)
    elif name.islower():
273
        return (DUMMY_FUNCTION[type]).format(name)
274
275
276
277
278
279
280
    else:
        is_pretrained = False
        for part in _pretrained:
            if part in name:
                is_pretrained = True
                break
        if is_pretrained:
281
            template = DUMMY_PRETRAINED_CLASS[type]
282
        else:
283
            template = DUMMY_CLASS[type]
284
285
286
287
288
        return template.format(name)


def create_dummy_files():
    """ Create the content of the dummy files. """
289
    sentencepiece_objects, tokenizers_objects, pt_objects, tf_objects, flax_objects = read_init()
290
291
292
293
294
295
296
297

    sentencepiece_dummies = "# This file is autogenerated by the command `make fix-copies`, do not edit.\n"
    sentencepiece_dummies += "from ..file_utils import requires_sentencepiece\n\n"
    sentencepiece_dummies += "\n".join([create_dummy_object(o, type="sentencepiece") for o in sentencepiece_objects])

    tokenizers_dummies = "# This file is autogenerated by the command `make fix-copies`, do not edit.\n"
    tokenizers_dummies += "from ..file_utils import requires_tokenizers\n\n"
    tokenizers_dummies += "\n".join([create_dummy_object(o, type="tokenizers") for o in tokenizers_objects])
298
299
300

    pt_dummies = "# This file is autogenerated by the command `make fix-copies`, do not edit.\n"
    pt_dummies += "from ..file_utils import requires_pytorch\n\n"
301
    pt_dummies += "\n".join([create_dummy_object(o, type="pt") for o in pt_objects])
302
303
304

    tf_dummies = "# This file is autogenerated by the command `make fix-copies`, do not edit.\n"
    tf_dummies += "from ..file_utils import requires_tf\n\n"
305
    tf_dummies += "\n".join([create_dummy_object(o, type="tf") for o in tf_objects])
306

307
308
309
310
311
    flax_dummies = "# This file is autogenerated by the command `make fix-copies`, do not edit.\n"
    flax_dummies += "from ..file_utils import requires_flax\n\n"
    flax_dummies += "\n".join([create_dummy_object(o, type="flax") for o in flax_objects])

    return sentencepiece_dummies, tokenizers_dummies, pt_dummies, tf_dummies, flax_dummies
312
313
314
315


def check_dummies(overwrite=False):
    """ Check if the dummy files are up to date and maybe `overwrite` with the right content. """
316
    sentencepiece_dummies, tokenizers_dummies, pt_dummies, tf_dummies, flax_dummies = create_dummy_files()
317
    path = os.path.join(PATH_TO_TRANSFORMERS, "utils")
318
319
    sentencepiece_file = os.path.join(path, "dummy_sentencepiece_objects.py")
    tokenizers_file = os.path.join(path, "dummy_tokenizers_objects.py")
320
321
    pt_file = os.path.join(path, "dummy_pt_objects.py")
    tf_file = os.path.join(path, "dummy_tf_objects.py")
322
    flax_file = os.path.join(path, "dummy_flax_objects.py")
323

324
325
326
327
    with open(sentencepiece_file, "r", encoding="utf-8") as f:
        actual_sentencepiece_dummies = f.read()
    with open(tokenizers_file, "r", encoding="utf-8") as f:
        actual_tokenizers_dummies = f.read()
328
329
330
331
    with open(pt_file, "r", encoding="utf-8") as f:
        actual_pt_dummies = f.read()
    with open(tf_file, "r", encoding="utf-8") as f:
        actual_tf_dummies = f.read()
332
333
    with open(flax_file, "r", encoding="utf-8") as f:
        actual_flax_dummies = f.read()
334

335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
    if sentencepiece_dummies != actual_sentencepiece_dummies:
        if overwrite:
            print("Updating transformers.utils.dummy_sentencepiece_objects.py as the main __init__ has new objects.")
            with open(sentencepiece_file, "w", encoding="utf-8") as f:
                f.write(sentencepiece_dummies)
        else:
            raise ValueError(
                "The main __init__ has objects that are not present in transformers.utils.dummy_sentencepiece_objects.py.",
                "Run `make fix-copies` to fix this.",
            )

    if tokenizers_dummies != actual_tokenizers_dummies:
        if overwrite:
            print("Updating transformers.utils.dummy_tokenizers_objects.py as the main __init__ has new objects.")
            with open(tokenizers_file, "w", encoding="utf-8") as f:
                f.write(tokenizers_dummies)
        else:
            raise ValueError(
                "The main __init__ has objects that are not present in transformers.utils.dummy_tokenizers_objects.py.",
                "Run `make fix-copies` to fix this.",
            )

357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
    if pt_dummies != actual_pt_dummies:
        if overwrite:
            print("Updating transformers.utils.dummy_pt_objects.py as the main __init__ has new objects.")
            with open(pt_file, "w", encoding="utf-8") as f:
                f.write(pt_dummies)
        else:
            raise ValueError(
                "The main __init__ has objects that are not present in transformers.utils.dummy_pt_objects.py.",
                "Run `make fix-copies` to fix this.",
            )

    if tf_dummies != actual_tf_dummies:
        if overwrite:
            print("Updating transformers.utils.dummy_tf_objects.py as the main __init__ has new objects.")
            with open(tf_file, "w", encoding="utf-8") as f:
                f.write(tf_dummies)
        else:
            raise ValueError(
                "The main __init__ has objects that are not present in transformers.utils.dummy_pt_objects.py.",
                "Run `make fix-copies` to fix this.",
            )

379
380
381
382
383
384
385
386
387
388
389
    if flax_dummies != actual_flax_dummies:
        if overwrite:
            print("Updating transformers.utils.dummy_flax_objects.py as the main __init__ has new objects.")
            with open(flax_file, "w", encoding="utf-8") as f:
                f.write(flax_dummies)
        else:
            raise ValueError(
                "The main __init__ has objects that are not present in transformers.utils.dummy_flax_objects.py.",
                "Run `make fix-copies` to fix this.",
            )

390
391
392
393
394
395
396

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.")
    args = parser.parse_args()

    check_dummies(args.fix_and_overwrite)