create_dummy_models.py 66.1 KB
Newer Older
Yih-Dar's avatar
Yih-Dar committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# coding=utf-8
# Copyright 2022 The HuggingFace Inc. 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.

import argparse
import collections.abc
18
import copy
Yih-Dar's avatar
Yih-Dar committed
19
20
import inspect
import json
21
import multiprocessing
Yih-Dar's avatar
Yih-Dar committed
22
23
import os
import shutil
24
import tempfile
25
import traceback
Yih-Dar's avatar
Yih-Dar committed
26
27
28
from pathlib import Path

from check_config_docstrings import get_checkpoint_from_config_class
29
from datasets import load_dataset
30
from get_test_info import get_model_to_tester_mapping, get_tester_classes_for_model
31
from huggingface_hub import Repository, create_repo, hf_api, upload_folder
32

Yih-Dar's avatar
Yih-Dar committed
33
34
35
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
36
    IMAGE_PROCESSOR_MAPPING,
Yih-Dar's avatar
Yih-Dar committed
37
38
39
40
    PROCESSOR_MAPPING,
    TOKENIZER_MAPPING,
    AutoTokenizer,
    LayoutLMv3TokenizerFast,
41
    PreTrainedTokenizer,
Yih-Dar's avatar
Yih-Dar committed
42
43
44
45
46
    PreTrainedTokenizerFast,
    logging,
)
from transformers.feature_extraction_utils import FeatureExtractionMixin
from transformers.file_utils import is_tf_available, is_torch_available
47
from transformers.image_processing_utils import BaseImageProcessor
Yih-Dar's avatar
Yih-Dar committed
48
from transformers.models.auto.configuration_auto import AutoConfig, model_type_to_module_name
49
from transformers.models.fsmt import configuration_fsmt
Yih-Dar's avatar
Yih-Dar committed
50
51
52
53
from transformers.processing_utils import ProcessorMixin, transformers_module
from transformers.tokenization_utils_base import PreTrainedTokenizerBase


54
55
56
# make sure tokenizer plays nice with multiprocessing
os.environ["TOKENIZERS_PARALLELISM"] = "false"

Yih-Dar's avatar
Yih-Dar committed
57
logging.set_verbosity_error()
58
logging.disable_progress_bar()
Yih-Dar's avatar
Yih-Dar committed
59
60
61
62
63
64
65
66
67
68
logger = logging.get_logger(__name__)

os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"

if not is_torch_available():
    raise ValueError("Please install PyTorch.")

if not is_tf_available():
    raise ValueError("Please install TensorFlow.")

69

Yih-Dar's avatar
Yih-Dar committed
70
71
72
73
FRAMEWORKS = ["pytorch", "tensorflow"]
INVALID_ARCH = []
TARGET_VOCAB_SIZE = 1024

74
75
76
77
78
79
80
81
data = {"training_ds": None, "testing_ds": None}

COMPOSITE_MODELS = {
    "EncoderDecoderModel": "EncoderDecoderModel-bert-bert",
    "SpeechEncoderDecoderModel": "SpeechEncoderDecoderModel-wav2vec2-bert",
    "VisionEncoderDecoderModel": "VisionEncoderDecoderModel-vit-gpt2",
    "VisionTextDualEncoderModel": "VisionTextDualEncoderModel-vit-bert",
}
Yih-Dar's avatar
Yih-Dar committed
82

83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# This list contains the model architectures for which a tiny version could not be created.
# Avoid to add new architectures here - unless we have verified carefully that it's (almost) impossible to create them.
# One such case is: no model tester class is implemented for a model type (like `MT5`) because its architecture is
# identical to another one (`MT5` is based on `T5`), but trained on different datasets or with different techniques.
UNCONVERTIBLE_MODEL_ARCHITECTURES = {
    "BertGenerationEncoder",
    "BertGenerationDecoder",
    "CamembertForSequenceClassification",
    "CamembertForMultipleChoice",
    "CamembertForMaskedLM",
    "CamembertForCausalLM",
    "CamembertForTokenClassification",
    "CamembertForQuestionAnswering",
    "CamembertModel",
    "TFCamembertForMultipleChoice",
    "TFCamembertForTokenClassification",
    "TFCamembertForQuestionAnswering",
    "TFCamembertForSequenceClassification",
    "TFCamembertForMaskedLM",
    "TFCamembertModel",
    "TFCamembertForCausalLM",
    "DecisionTransformerModel",
105
106
    "GraphormerModel",
    "InformerModel",
107
108
    "JukeboxModel",
    "MarianForCausalLM",
109
110
    "MaskFormerSwinModel",
    "MaskFormerSwinBackbone",
111
112
    "MT5Model",
    "MT5ForConditionalGeneration",
113
    "UMT5ForConditionalGeneration",
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
    "TFMT5ForConditionalGeneration",
    "TFMT5Model",
    "QDQBertForSequenceClassification",
    "QDQBertForMaskedLM",
    "QDQBertModel",
    "QDQBertForTokenClassification",
    "QDQBertLMHeadModel",
    "QDQBertForMultipleChoice",
    "QDQBertForQuestionAnswering",
    "QDQBertForNextSentencePrediction",
    "ReformerModelWithLMHead",
    "RetriBertModel",
    "Speech2Text2ForCausalLM",
    "TimeSeriesTransformerModel",
    "TrajectoryTransformerModel",
    "TrOCRForCausalLM",
    "XLMProphetNetForConditionalGeneration",
    "XLMProphetNetForCausalLM",
    "XLMProphetNetModel",
    "XLMRobertaModel",
    "XLMRobertaForTokenClassification",
    "XLMRobertaForMultipleChoice",
    "XLMRobertaForMaskedLM",
    "XLMRobertaForCausalLM",
    "XLMRobertaForSequenceClassification",
    "XLMRobertaForQuestionAnswering",
    "TFXLMRobertaForSequenceClassification",
    "TFXLMRobertaForMaskedLM",
142
    "TFXLMRobertaForCausalLM",
143
144
145
146
147
148
149
    "TFXLMRobertaForQuestionAnswering",
    "TFXLMRobertaModel",
    "TFXLMRobertaForMultipleChoice",
    "TFXLMRobertaForTokenClassification",
}


Yih-Dar's avatar
Yih-Dar committed
150
151
152
153
154
def get_processor_types_from_config_class(config_class, allowed_mappings=None):
    """Return a tuple of processors for `config_class`.

    We use `tuple` here to include (potentially) both slow & fast tokenizers.
    """
155
156
157
158
159
160
161
162
163

    # To make a uniform return type
    def _to_tuple(x):
        if not isinstance(x, collections.abc.Sequence):
            x = (x,)
        else:
            x = tuple(x)
        return x

Yih-Dar's avatar
Yih-Dar committed
164
    if allowed_mappings is None:
165
        allowed_mappings = ["processor", "tokenizer", "image_processor", "feature_extractor"]
Yih-Dar's avatar
Yih-Dar committed
166
167
168

    processor_types = ()

169
170
    # Check first if a model has `ProcessorMixin`. Otherwise, check if it has tokenizers, and/or an image processor or
    # a feature extractor
Yih-Dar's avatar
Yih-Dar committed
171
    if config_class in PROCESSOR_MAPPING and "processor" in allowed_mappings:
172
        processor_types = _to_tuple(PROCESSOR_MAPPING[config_class])
Yih-Dar's avatar
Yih-Dar committed
173
    else:
174
175
        if config_class in TOKENIZER_MAPPING and "tokenizer" in allowed_mappings:
            processor_types = TOKENIZER_MAPPING[config_class]
Yih-Dar's avatar
Yih-Dar committed
176

177
178
179
180
181
182
183
184
        if config_class in IMAGE_PROCESSOR_MAPPING and "image_processor" in allowed_mappings:
            processor_types += _to_tuple(IMAGE_PROCESSOR_MAPPING[config_class])
        elif config_class in FEATURE_EXTRACTOR_MAPPING and "feature_extractor" in allowed_mappings:
            processor_types += _to_tuple(FEATURE_EXTRACTOR_MAPPING[config_class])

    # Remark: some configurations have no processor at all. For example, generic composite models like
    # `EncoderDecoderModel` is used for any (compatible) text models. Also, `DecisionTransformer` doesn't
    # require any processor.
Yih-Dar's avatar
Yih-Dar committed
185
186
187
188
189
190
191

    # We might get `None` for some tokenizers - remove them here.
    processor_types = tuple(p for p in processor_types if p is not None)

    return processor_types


192
def get_architectures_from_config_class(config_class, arch_mappings, models_to_skip=None):
Yih-Dar's avatar
Yih-Dar committed
193
194
195
196
197
198
199
200
201
202
203
204
    """Return a tuple of all possible architectures attributed to a configuration class `config_class`.

    For example, BertConfig -> [BertModel, BertForMaskedLM, ..., BertForQuestionAnswering].
    """
    # A model architecture could appear in several mappings. For example, `BartForConditionalGeneration` is in
    #   - MODEL_FOR_PRETRAINING_MAPPING_NAMES
    #   - MODEL_WITH_LM_HEAD_MAPPING_NAMES
    #   - MODEL_FOR_MASKED_LM_MAPPING_NAMES
    #   - MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
    # We avoid the duplication.
    architectures = set()

205
206
207
208
    if models_to_skip is None:
        models_to_skip = []
    models_to_skip = UNCONVERTIBLE_MODEL_ARCHITECTURES.union(models_to_skip)

Yih-Dar's avatar
Yih-Dar committed
209
210
211
212
213
    for mapping in arch_mappings:
        if config_class in mapping:
            models = mapping[config_class]
            models = tuple(models) if isinstance(models, collections.abc.Sequence) else (models,)
            for model in models:
214
                if model.__name__ not in models_to_skip:
Yih-Dar's avatar
Yih-Dar committed
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
                    architectures.add(model)

    architectures = tuple(architectures)

    return architectures


def get_config_class_from_processor_class(processor_class):
    """Get the config class from a processor class.

    Some config/model classes use tokenizers/feature_extractors from other models. For example, `GPT-J` uses
    `GPT2Tokenizer`. If no checkpoint is found for a config class, or a checkpoint is found without necessary file(s) to
    create the processor for `processor_class`, we get the config class that corresponds to `processor_class` and use it
    to find a checkpoint in order to create the processor.
    """

    processor_prefix = processor_class.__name__
232
    for postfix in ["TokenizerFast", "Tokenizer", "ImageProcessor", "FeatureExtractor", "Processor"]:
Yih-Dar's avatar
Yih-Dar committed
233
234
235
236
237
238
239
240
241
242
243
244
245
        processor_prefix = processor_prefix.replace(postfix, "")

    # `Wav2Vec2CTCTokenizer` -> `Wav2Vec2Config`
    if processor_prefix == "Wav2Vec2CTC":
        processor_prefix = "Wav2Vec2"

    # Find the new configuration class
    new_config_name = f"{processor_prefix}Config"
    new_config_class = getattr(transformers_module, new_config_name)

    return new_config_class


246
def build_processor(config_class, processor_class, allow_no_checkpoint=False):
Yih-Dar's avatar
Yih-Dar committed
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
    """Create a processor for `processor_class`.

    If a processor is not able to be built with the original arguments, this method tries to change the arguments and
    call itself recursively, by inferring a new `config_class` or a new `processor_class` from another one, in order to
    find a checkpoint containing the necessary files to build a processor.

    The processor is not saved here. Instead, it will be saved in `convert_processors` after further changes in
    `convert_processors`. For each model architecture`, a copy will be created and saved along the built model.
    """
    # Currently, this solely uses the docstring in the source file of `config_class` to find a checkpoint.
    checkpoint = get_checkpoint_from_config_class(config_class)

    if checkpoint is None:
        # try to get the checkpoint from the config class for `processor_class`.
        # This helps cases like `XCLIPConfig` and `VideoMAEFeatureExtractor` to find a checkpoint from `VideoMAEConfig`.
        config_class_from_processor_class = get_config_class_from_processor_class(processor_class)
        checkpoint = get_checkpoint_from_config_class(config_class_from_processor_class)

    processor = None
    try:
        processor = processor_class.from_pretrained(checkpoint)
    except Exception as e:
269
        logger.error(f"{e.__class__.__name__}: {e}")
Yih-Dar's avatar
Yih-Dar committed
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284

    # Try to get a new processor class from checkpoint. This is helpful for a checkpoint without necessary file to load
    # processor while `processor_class` is an Auto class. For example, `sew` has `Wav2Vec2Processor` in
    # `PROCESSOR_MAPPING_NAMES`, its `tokenizer_class` is `AutoTokenizer`, and the checkpoint
    # `https://huggingface.co/asapp/sew-tiny-100k` has no tokenizer file, but we can get
    # `tokenizer_class: Wav2Vec2CTCTokenizer` from the config file. (The new processor class won't be able to load from
    # `checkpoint`, but it helps this recursive method to find a way to build a processor).
    if (
        processor is None
        and checkpoint is not None
        and issubclass(processor_class, (PreTrainedTokenizerBase, AutoTokenizer))
    ):
        try:
            config = AutoConfig.from_pretrained(checkpoint)
        except Exception as e:
285
            logger.error(f"{e.__class__.__name__}: {e}")
Yih-Dar's avatar
Yih-Dar committed
286
287
            config = None
        if config is not None:
288
289
290
291
292
            if not isinstance(config, config_class):
                raise ValueError(
                    f"`config` (which is of type {config.__class__.__name__}) should be an instance of `config_class`"
                    f" ({config_class.__name__})!"
                )
Yih-Dar's avatar
Yih-Dar committed
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
            tokenizer_class = config.tokenizer_class
            new_processor_class = None
            if tokenizer_class is not None:
                new_processor_class = getattr(transformers_module, tokenizer_class)
                if new_processor_class != processor_class:
                    processor = build_processor(config_class, new_processor_class)
            # If `tokenizer_class` is not specified in `config`, let's use `config` to get the process class via auto
            # mappings, but only allow the tokenizer mapping being used. This is to make `Wav2Vec2Conformer` build
            if processor is None:
                new_processor_classes = get_processor_types_from_config_class(
                    config.__class__, allowed_mappings=["tokenizer"]
                )
                # Used to avoid infinite recursion between a pair of fast/slow tokenizer types
                names = [
                    x.__name__.replace("Fast", "") for x in [processor_class, new_processor_class] if x is not None
                ]
                new_processor_classes = [
                    x for x in new_processor_classes if x is not None and x.__name__.replace("Fast", "") not in names
                ]
                if len(new_processor_classes) > 0:
                    new_processor_class = new_processor_classes[0]
314
315
316
317
318
                    # Let's use fast tokenizer if there is any
                    for x in new_processor_classes:
                        if x.__name__.endswith("Fast"):
                            new_processor_class = x
                            break
Yih-Dar's avatar
Yih-Dar committed
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
                    processor = build_processor(config_class, new_processor_class)

    if processor is None:
        # Try to build each component (tokenizer & feature extractor) of a `ProcessorMixin`.
        if issubclass(processor_class, ProcessorMixin):
            attrs = {}
            for attr_name in processor_class.attributes:
                attrs[attr_name] = []
                # This could be a tuple (for tokenizers). For example, `CLIPProcessor` has
                #   - feature_extractor_class = "CLIPFeatureExtractor"
                #   - tokenizer_class = ("CLIPTokenizer", "CLIPTokenizerFast")
                attr_class_names = getattr(processor_class, f"{attr_name}_class")
                if not isinstance(attr_class_names, tuple):
                    attr_class_names = (attr_class_names,)

                for name in attr_class_names:
                    attr_class = getattr(transformers_module, name)
                    attr = build_processor(config_class, attr_class)
                    if attr is not None:
                        attrs[attr_name].append(attr)

            # try to build a `ProcessorMixin`, so we can return a single value
            if all(len(v) > 0 for v in attrs.values()):
                try:
                    processor = processor_class(**{k: v[0] for k, v in attrs.items()})
                except Exception as e:
345
                    logger.error(f"{e.__class__.__name__}: {e}")
Yih-Dar's avatar
Yih-Dar committed
346
347
348
349
350
351
352
353
        else:
            # `checkpoint` might lack some file(s) to load a processor. For example, `facebook/hubert-base-ls960`
            # has no tokenizer file to load `Wav2Vec2CTCTokenizer`. In this case, we try to build a processor
            # with the configuration class (for example, `Wav2Vec2Config`) corresponding to `processor_class`.
            config_class_from_processor_class = get_config_class_from_processor_class(processor_class)
            if config_class_from_processor_class != config_class:
                processor = build_processor(config_class_from_processor_class, processor_class)

354
355
356
357
358
359
360
361
362
    # Try to create an image processor or a feature extractor without any checkpoint
    if (
        processor is None
        and allow_no_checkpoint
        and (issubclass(processor_class, BaseImageProcessor) or issubclass(processor_class, FeatureExtractionMixin))
    ):
        try:
            processor = processor_class()
        except Exception as e:
363
            logger.error(f"{e.__class__.__name__}: {e}")
364

Yih-Dar's avatar
Yih-Dar committed
365
366
    # validation
    if processor is not None:
367
368
369
370
371
        if not (isinstance(processor, processor_class) or processor_class.__name__.startswith("Auto")):
            raise ValueError(
                f"`processor` (which is of type {processor.__class__.__name__}) should be an instance of"
                f" {processor_class.__name__} or an Auto class!"
            )
Yih-Dar's avatar
Yih-Dar committed
372
373
374
375

    return processor


376
def get_tiny_config(config_class, model_class=None, **model_tester_kwargs):
Yih-Dar's avatar
Yih-Dar committed
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
    """Retrieve a tiny configuration from `config_class` using each model's `ModelTester`.

    Args:
        config_class: Subclass of `PreTrainedConfig`.

    Returns:
        An instance of `config_class` with tiny hyperparameters
    """
    model_type = config_class.model_type

    # For model type like `data2vec-vision` and `donut-swin`, we can't get the config/model file name directly via
    # `model_type` as it would be sth. like `configuration_data2vec_vision.py`.
    # A simple way is to use `inspect.getsourcefile(config_class)`.
    config_source_file = inspect.getsourcefile(config_class)
    # The modeling file name without prefix (`modeling_`) and postfix (`.py`)
392
    modeling_name = config_source_file.split(os.path.sep)[-1].replace("configuration_", "").replace(".py", "")
Yih-Dar's avatar
Yih-Dar committed
393
394
395
396

    try:
        print("Importing", model_type_to_module_name(model_type))
        module_name = model_type_to_module_name(model_type)
397
398
        if not modeling_name.startswith(module_name):
            raise ValueError(f"{modeling_name} doesn't start with {module_name}!")
399
400
401
402
403
404
405
406
407
408
409
        test_file = os.path.join("tests", "models", module_name, f"test_modeling_{modeling_name}.py")
        models_to_model_testers = get_model_to_tester_mapping(test_file)
        # Find the model tester class
        model_tester_class = None
        tester_classes = []
        if model_class is not None:
            tester_classes = get_tester_classes_for_model(test_file, model_class)
        else:
            for _tester_classes in models_to_model_testers.values():
                tester_classes.extend(_tester_classes)
        if len(tester_classes) > 0:
410
411
412
413
414
            # sort with the length of the class names first, then the alphabetical order
            # This is to avoid `T5EncoderOnlyModelTest` is used instead of `T5ModelTest`, which has
            # `is_encoder_decoder=False` and causes some pipeline tests failing (also failures in `Optimum` CI).
            # TODO: More fine grained control of the desired tester class.
            model_tester_class = sorted(tester_classes, key=lambda x: (len(x.__name__), x.__name__))[0]
415
416
417
    except ModuleNotFoundError:
        error = f"Tiny config not created for {model_type} - cannot find the testing module from the model name."
        raise ValueError(error)
Yih-Dar's avatar
Yih-Dar committed
418
419

    if model_tester_class is None:
420
        error = f"Tiny config not created for {model_type} - no model tester is found in the testing module."
Yih-Dar's avatar
Yih-Dar committed
421
422
423
        raise ValueError(error)

    # `parent` is an instance of `unittest.TestCase`, but we don't need it here.
424
    model_tester = model_tester_class(parent=None, **model_tester_kwargs)
Yih-Dar's avatar
Yih-Dar committed
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442

    if hasattr(model_tester, "get_pipeline_config"):
        return model_tester.get_pipeline_config()
    elif hasattr(model_tester, "prepare_config_and_inputs"):
        # `PoolFormer` has no `get_config` defined. Furthermore, it's better to use `prepare_config_and_inputs` even if
        # `get_config` is defined, since there might be some extra changes in `prepare_config_and_inputs`.
        return model_tester.prepare_config_and_inputs()[0]
    elif hasattr(model_tester, "get_config"):
        return model_tester.get_config()
    else:
        error = (
            f"Tiny config not created for {model_type} - the model tester {model_tester_class.__name__} lacks"
            " necessary method to create config."
        )
        raise ValueError(error)


def convert_tokenizer(tokenizer_fast: PreTrainedTokenizerFast):
443
444
445
    new_tokenizer = tokenizer_fast.train_new_from_iterator(
        data["training_ds"]["text"], TARGET_VOCAB_SIZE, show_progress=False
    )
Yih-Dar's avatar
Yih-Dar committed
446
447
448

    # Make sure it at least runs
    if not isinstance(new_tokenizer, LayoutLMv3TokenizerFast):
449
        new_tokenizer(data["testing_ds"]["text"])
Yih-Dar's avatar
Yih-Dar committed
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492

    return new_tokenizer


def convert_feature_extractor(feature_extractor, tiny_config):
    to_convert = False
    kwargs = {}
    if hasattr(tiny_config, "image_size"):
        kwargs["size"] = tiny_config.image_size
        kwargs["crop_size"] = tiny_config.image_size
        to_convert = True
    elif (
        hasattr(tiny_config, "vision_config")
        and tiny_config.vision_config is not None
        and hasattr(tiny_config.vision_config, "image_size")
    ):
        kwargs["size"] = tiny_config.vision_config.image_size
        kwargs["crop_size"] = tiny_config.vision_config.image_size
        to_convert = True

    # Speech2TextModel specific.
    if hasattr(tiny_config, "input_feat_per_channel"):
        kwargs["feature_size"] = tiny_config.input_feat_per_channel
        kwargs["num_mel_bins"] = tiny_config.input_feat_per_channel
        to_convert = True

    if to_convert:
        feature_extractor = feature_extractor.__class__(**kwargs)

    return feature_extractor


def convert_processors(processors, tiny_config, output_folder, result):
    """Change a processor to work with smaller inputs.

    For tokenizers, we try to reduce their vocabulary size.

    For feature extractor, we use smaller image size or change
    other attributes using the values from `tiny_config`. See `convert_feature_extractor`.

    This method should not fail: we catch the errors and put them in `result["warnings"]` with descriptive messages.
    """

493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
    def _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=False):
        """Set tokenizer(s) to `None` if the fast/slow tokenizers have different values for `vocab_size` or `length`.

        If `keep_fast_tokenizer=True`, the fast tokenizer will be kept.
        """
        # sanity check 1: fast and slow tokenizers should be compatible (vocab_size)
        if fast_tokenizer is not None and slow_tokenizer is not None:
            if fast_tokenizer.vocab_size != slow_tokenizer.vocab_size:
                warning_messagae = (
                    "The fast/slow tokenizers "
                    f"({fast_tokenizer.__class__.__name__}/{slow_tokenizer.__class__.__name__}) have different "
                    "vocabulary size: "
                    f"fast_tokenizer.vocab_size = {fast_tokenizer.vocab_size} and "
                    f"slow_tokenizer.vocab_size = {slow_tokenizer.vocab_size}."
                )
                result["warnings"].append(warning_messagae)
                if not keep_fast_tokenizer:
                    fast_tokenizer = None
                slow_tokenizer = None

        # sanity check 2: fast and slow tokenizers should be compatible (length)
        if fast_tokenizer is not None and slow_tokenizer is not None:
            if len(fast_tokenizer) != len(slow_tokenizer):
                warning_messagae = (
                    f"The fast/slow tokenizers () have different length: "
                    f"len(fast_tokenizer) = {len(fast_tokenizer)} and "
                    f"len(slow_tokenizer) = {len(slow_tokenizer)}."
                )
                result["warnings"].append(warning_messagae)
                if not keep_fast_tokenizer:
                    fast_tokenizer = None
                slow_tokenizer = None

        return fast_tokenizer, slow_tokenizer

Yih-Dar's avatar
Yih-Dar committed
528
529
530
531
    tokenizers = []
    feature_extractors = []
    for processor in processors:
        if isinstance(processor, PreTrainedTokenizerBase):
532
533
            if processor.__class__.__name__ not in {x.__class__.__name__ for x in tokenizers}:
                tokenizers.append(processor)
534
        elif isinstance(processor, BaseImageProcessor):
535
536
            if processor.__class__.__name__ not in {x.__class__.__name__ for x in feature_extractors}:
                feature_extractors.append(processor)
Yih-Dar's avatar
Yih-Dar committed
537
        elif isinstance(processor, FeatureExtractionMixin):
538
539
            if processor.__class__.__name__ not in {x.__class__.__name__ for x in feature_extractors}:
                feature_extractors.append(processor)
Yih-Dar's avatar
Yih-Dar committed
540
        elif isinstance(processor, ProcessorMixin):
541
542
543
            if hasattr(processor, "tokenizer"):
                if processor.tokenizer.__class__.__name__ not in {x.__class__.__name__ for x in tokenizers}:
                    tokenizers.append(processor.tokenizer)
Yih-Dar's avatar
Yih-Dar committed
544
            # Currently, we only have these 2 possibilities
545
            if hasattr(processor, "image_processor"):
546
547
548
549
                if processor.image_processor.__class__.__name__ not in {
                    x.__class__.__name__ for x in feature_extractors
                }:
                    feature_extractors.append(processor.image_processor)
550
            elif hasattr(processor, "feature_extractor"):
551
552
553
554
                if processor.feature_extractor.__class__.__name__ not in {
                    x.__class__.__name__ for x in feature_extractors
                }:
                    feature_extractors.append(processor.feature_extractor)
Yih-Dar's avatar
Yih-Dar committed
555
556

    # check the built processors have the unique type
557
    num_types = len({x.__class__.__name__ for x in feature_extractors})
558
559
    if num_types >= 2:
        raise ValueError(f"`feature_extractors` should contain at most 1 type, but it contains {num_types} types!")
560
    num_types = len({x.__class__.__name__.replace("Fast", "") for x in tokenizers})
561
562
    if num_types >= 2:
        raise ValueError(f"`tokenizers` should contain at most 1 tokenizer type, but it contains {num_types} types!")
Yih-Dar's avatar
Yih-Dar committed
563
564
565

    fast_tokenizer = None
    slow_tokenizer = None
566

Yih-Dar's avatar
Yih-Dar committed
567
568
    for tokenizer in tokenizers:
        if isinstance(tokenizer, PreTrainedTokenizerFast):
569
570
            fast_tokenizer = tokenizer
        else:
Yih-Dar's avatar
Yih-Dar committed
571
572
            slow_tokenizer = tokenizer

573
574
575
576
577
578
579
580
581
582
    # If the (original) fast/slow tokenizers don't correspond, keep only the fast tokenizer.
    # This doesn't necessarily imply the fast/slow tokenizers in a single Hub repo. has issues.
    # It's more of an issue in `build_processor` which tries to get a checkpoint with as much effort as possible.
    # For `YosoModel` (which uses `AlbertTokenizer(Fast)`), its real (Hub) checkpoint doesn't contain valid files to
    # load the slower tokenizer (`AlbertTokenizer`), and it ends up finding the (canonical) checkpoint of `AlbertModel`,
    # which has different vocabulary.
    # TODO: Try to improve `build_processor`'s definition and/or usage to avoid the above situation in the first place.
    fast_tokenizer, slow_tokenizer = _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=True)
    original_fast_tokenizer, original_slow_tokenizer = fast_tokenizer, slow_tokenizer

Yih-Dar's avatar
Yih-Dar committed
583
584
    if fast_tokenizer:
        try:
585
586
587
588
            # Wav2Vec2ForCTC , ByT5Tokenizer etc. all are already small enough and have no fast version that can
            # be retrained
            if fast_tokenizer.vocab_size > TARGET_VOCAB_SIZE:
                fast_tokenizer = convert_tokenizer(fast_tokenizer)
589
        except Exception:
Yih-Dar's avatar
Yih-Dar committed
590
            result["warnings"].append(
591
                (
592
                    f"Failed to convert the fast tokenizer for {fast_tokenizer.__class__.__name__}.",
593
594
                    traceback.format_exc(),
                )
Yih-Dar's avatar
Yih-Dar committed
595
596
            )

597
    # If `fast_tokenizer` exists, `slow_tokenizer` should correspond to it.
Yih-Dar's avatar
Yih-Dar committed
598
    if fast_tokenizer:
599
        # Make sure the fast tokenizer can be saved
Yih-Dar's avatar
Yih-Dar committed
600
        try:
601
602
603
604
605
606
607
608
609
610
611
612
613
614
            # We don't save it to `output_folder` at this moment - only at the end of this function.
            with tempfile.TemporaryDirectory() as tmpdir:
                fast_tokenizer.save_pretrained(tmpdir)
                try:
                    slow_tokenizer = AutoTokenizer.from_pretrained(tmpdir, use_fast=False)
                except Exception:
                    result["warnings"].append(
                        (
                            f"Failed to load the slow tokenizer saved from {fast_tokenizer.__class__.__name__}.",
                            traceback.format_exc(),
                        )
                    )
                    # Let's just keep the fast version
                    slow_tokenizer = None
615
        except Exception:
Yih-Dar's avatar
Yih-Dar committed
616
            result["warnings"].append(
617
                (
618
                    f"Failed to save the fast tokenizer for {fast_tokenizer.__class__.__name__}.",
619
620
                    traceback.format_exc(),
                )
Yih-Dar's avatar
Yih-Dar committed
621
            )
622
            fast_tokenizer = None
Yih-Dar's avatar
Yih-Dar committed
623

624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
    # If the (possibly converted) fast/slow tokenizers don't correspond, set them to `None`, and use the original
    # tokenizers.
    fast_tokenizer, slow_tokenizer = _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=False)

    # If there is any conversion failed, we keep the original tokenizers.
    if (original_fast_tokenizer is not None and fast_tokenizer is None) or (
        original_slow_tokenizer is not None and slow_tokenizer is None
    ):
        warning_messagae = (
            "There are some issues when converting the fast/slow tokenizers. The original tokenizers from the Hub "
            " will be used instead."
        )
        result["warnings"].append(warning_messagae)
        # Let's use the original version at the end (`original_fast_tokenizer` and `original_slow_tokenizer`)
        fast_tokenizer = original_fast_tokenizer
        slow_tokenizer = original_slow_tokenizer

    # Make sure the fast tokenizer can be saved
    if fast_tokenizer:
        # We don't save it to `output_folder` at this moment - only at the end of this function.
        with tempfile.TemporaryDirectory() as tmpdir:
            try:
                fast_tokenizer.save_pretrained(tmpdir)
            except Exception:
                result["warnings"].append(
                    (
                        f"Failed to save the fast tokenizer for {fast_tokenizer.__class__.__name__}.",
                        traceback.format_exc(),
                    )
653
                )
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
                fast_tokenizer = None
    # Make sure the slow tokenizer can be saved
    if slow_tokenizer:
        # We don't save it to `output_folder` at this moment - only at the end of this function.
        with tempfile.TemporaryDirectory() as tmpdir:
            try:
                slow_tokenizer.save_pretrained(tmpdir)
            except Exception:
                result["warnings"].append(
                    (
                        f"Failed to save the slow tokenizer for {slow_tokenizer.__class__.__name__}.",
                        traceback.format_exc(),
                    )
                )
                slow_tokenizer = None
Yih-Dar's avatar
Yih-Dar committed
669
670
671
672

    # update feature extractors using the tiny config
    try:
        feature_extractors = [convert_feature_extractor(p, tiny_config) for p in feature_extractors]
673
674
675
676
677
678
679
    except Exception:
        result["warnings"].append(
            (
                "Failed to convert feature extractors.",
                traceback.format_exc(),
            )
        )
Yih-Dar's avatar
Yih-Dar committed
680
681
        feature_extractors = []

682
683
    if hasattr(tiny_config, "max_position_embeddings") and tiny_config.max_position_embeddings > 0:
        if fast_tokenizer is not None:
684
685
686
687
688
689
            if fast_tokenizer.__class__.__name__ in [
                "RobertaTokenizerFast",
                "XLMRobertaTokenizerFast",
                "LongformerTokenizerFast",
                "MPNetTokenizerFast",
            ]:
690
691
692
693
                fast_tokenizer.model_max_length = tiny_config.max_position_embeddings - 2
            else:
                fast_tokenizer.model_max_length = tiny_config.max_position_embeddings
        if slow_tokenizer is not None:
694
695
696
697
698
699
            if slow_tokenizer.__class__.__name__ in [
                "RobertaTokenizer",
                "XLMRobertaTokenizer",
                "LongformerTokenizer",
                "MPNetTokenizer",
            ]:
700
701
702
703
                slow_tokenizer.model_max_length = tiny_config.max_position_embeddings - 2
            else:
                slow_tokenizer.model_max_length = tiny_config.max_position_embeddings

Yih-Dar's avatar
Yih-Dar committed
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
    processors = [fast_tokenizer, slow_tokenizer] + feature_extractors
    processors = [p for p in processors if p is not None]
    for p in processors:
        p.save_pretrained(output_folder)

    return processors


def get_checkpoint_dir(output_dir, model_arch):
    """Get framework-agnostic architecture name. Used to save all PT/TF/Flax models into the same directory."""

    arch_name = model_arch.__name__
    if arch_name.startswith("TF"):
        arch_name = arch_name[2:]
    elif arch_name.startswith("Flax"):
        arch_name = arch_name[4:]

    return os.path.join(output_dir, arch_name)


def build_model(model_arch, tiny_config, output_dir):
    """Create and save a model for `model_arch`.

    Also copy the set of processors to each model (under the same model type) output folder.
    """

    checkpoint_dir = get_checkpoint_dir(output_dir, model_arch)

    processor_output_dir = os.path.join(output_dir, "processors")
    # copy the (same set of) processors (for a model type) to the model arch. specific folder
    if os.path.isdir(processor_output_dir):
        shutil.copytree(processor_output_dir, checkpoint_dir, dirs_exist_ok=True)

737
738
    tiny_config = copy.deepcopy(tiny_config)

739
    if any(model_arch.__name__.endswith(x) for x in ["ForCausalLM", "LMHeadModel"]):
740
741
742
        tiny_config.is_encoder_decoder = False
        tiny_config.is_decoder = True

Yih-Dar's avatar
Yih-Dar committed
743
744
745
746
747
748
749
    model = model_arch(config=tiny_config)
    model.save_pretrained(checkpoint_dir)
    model.from_pretrained(checkpoint_dir)

    return model


750
def fill_result_with_error(result, error, trace, models_to_create):
Yih-Dar's avatar
Yih-Dar committed
751
    """Fill `result` with errors for all target model arch if we can't build processor"""
752
    error = (error, trace)
Yih-Dar's avatar
Yih-Dar committed
753
754
755
756
757
758
759
    result["error"] = error
    for framework in FRAMEWORKS:
        if framework in models_to_create:
            result[framework] = {}
            for model_arch in models_to_create[framework]:
                result[framework][model_arch.__name__] = {"model": None, "checkpoint": None, "error": error}

760
    result["processor"] = {p.__class__.__name__: p.__class__.__name__ for p in result["processor"].values()}
761
762


763
def upload_model(model_dir, organization, token):
764
765
766
767
    """Upload the tiny models"""

    arch_name = model_dir.split(os.path.sep)[-1]
    repo_name = f"tiny-random-{arch_name}"
768
    repo_id = f"{organization}/{repo_name}"
769
770
771
772

    repo_exist = False
    error = None
    try:
773
        create_repo(repo_id=repo_id, exist_ok=False, repo_type="model", token=token)
774
775
776
777
778
779
780
    except Exception as e:
        error = e
        if "You already created" in str(e):
            error = None
            logger.warning("Remote repository exists and will be cloned.")
            repo_exist = True
            try:
781
                create_repo(repo_id=repo_id, exist_ok=True, repo_type="model", token=token)
782
783
784
            except Exception as e:
                error = e
    if error is not None:
785
        raise error
786
787

    with tempfile.TemporaryDirectory() as tmpdir:
788
        repo = Repository(local_dir=tmpdir, clone_from=repo_id, token=token)
789
790
791
792
793
794
795
        repo.git_pull()
        shutil.copytree(model_dir, tmpdir, dirs_exist_ok=True)

        if repo_exist:
            # Open a PR on the existing Hub repo.
            hub_pr_url = upload_folder(
                folder_path=model_dir,
796
                repo_id=repo_id,
797
798
799
800
                repo_type="model",
                commit_message=f"Update tiny models for {arch_name}",
                commit_description=f"Upload tiny models for {arch_name}",
                create_pr=True,
801
                token=token,
802
            )
803
            logger.warning(f"PR open in {hub_pr_url}.")
804
            # TODO: We need this information?
805
806
807
808
809
        else:
            # Push to Hub repo directly
            repo.git_add(auto_lfs_track=True)
            repo.git_commit(f"Upload tiny models for {arch_name}")
            repo.git_push(blocking=True)  # this prints a progress bar with the upload
810
            logger.warning(f"Tiny models {arch_name} pushed to {repo_id}.")
811

Yih-Dar's avatar
Yih-Dar committed
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829

def build_composite_models(config_class, output_dir):
    import tempfile

    from transformers import (
        BertConfig,
        BertLMHeadModel,
        BertModel,
        BertTokenizer,
        BertTokenizerFast,
        EncoderDecoderModel,
        GPT2Config,
        GPT2LMHeadModel,
        GPT2Tokenizer,
        GPT2TokenizerFast,
        SpeechEncoderDecoderModel,
        TFEncoderDecoderModel,
        TFVisionEncoderDecoderModel,
830
        TFVisionTextDualEncoderModel,
Yih-Dar's avatar
Yih-Dar committed
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
        VisionEncoderDecoderModel,
        VisionTextDualEncoderModel,
        ViTConfig,
        ViTFeatureExtractor,
        ViTModel,
        Wav2Vec2Config,
        Wav2Vec2Model,
        Wav2Vec2Processor,
    )

    # These will be removed at the end if they are empty
    result = {"error": None, "warnings": []}

    if config_class.model_type == "encoder-decoder":
        encoder_config_class = BertConfig
        decoder_config_class = BertConfig
        encoder_processor = (BertTokenizerFast, BertTokenizer)
        decoder_processor = (BertTokenizerFast, BertTokenizer)
        encoder_class = BertModel
        decoder_class = BertLMHeadModel
        model_class = EncoderDecoderModel
        tf_model_class = TFEncoderDecoderModel
    elif config_class.model_type == "vision-encoder-decoder":
        encoder_config_class = ViTConfig
        decoder_config_class = GPT2Config
        encoder_processor = (ViTFeatureExtractor,)
        decoder_processor = (GPT2TokenizerFast, GPT2Tokenizer)
        encoder_class = ViTModel
        decoder_class = GPT2LMHeadModel
        model_class = VisionEncoderDecoderModel
        tf_model_class = TFVisionEncoderDecoderModel
    elif config_class.model_type == "speech-encoder-decoder":
        encoder_config_class = Wav2Vec2Config
        decoder_config_class = BertConfig
        encoder_processor = (Wav2Vec2Processor,)
        decoder_processor = (BertTokenizerFast, BertTokenizer)
        encoder_class = Wav2Vec2Model
        decoder_class = BertLMHeadModel
        model_class = SpeechEncoderDecoderModel
        tf_model_class = None
    elif config_class.model_type == "vision-text-dual-encoder":
        # Not encoder-decoder, but encoder-encoder. We just keep the same name as above to make code easier
        encoder_config_class = ViTConfig
        decoder_config_class = BertConfig
        encoder_processor = (ViTFeatureExtractor,)
        decoder_processor = (BertTokenizerFast, BertTokenizer)
        encoder_class = ViTModel
        decoder_class = BertModel
        model_class = VisionTextDualEncoderModel
880
        tf_model_class = TFVisionTextDualEncoderModel
Yih-Dar's avatar
Yih-Dar committed
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930

    with tempfile.TemporaryDirectory() as tmpdir:
        try:
            # build encoder
            models_to_create = {"processor": encoder_processor, "pytorch": (encoder_class,), "tensorflow": []}
            encoder_output_dir = os.path.join(tmpdir, "encoder")
            build(encoder_config_class, models_to_create, encoder_output_dir)

            # build decoder
            models_to_create = {"processor": decoder_processor, "pytorch": (decoder_class,), "tensorflow": []}
            decoder_output_dir = os.path.join(tmpdir, "decoder")
            build(decoder_config_class, models_to_create, decoder_output_dir)

            # build encoder-decoder
            encoder_path = os.path.join(encoder_output_dir, encoder_class.__name__)
            decoder_path = os.path.join(decoder_output_dir, decoder_class.__name__)

            if config_class.model_type != "vision-text-dual-encoder":
                # Specify these explicitly for encoder-decoder like models, but not for `vision-text-dual-encoder` as it
                # has no decoder.
                decoder_config = decoder_config_class.from_pretrained(decoder_path)
                decoder_config.is_decoder = True
                decoder_config.add_cross_attention = True
                model = model_class.from_encoder_decoder_pretrained(
                    encoder_path,
                    decoder_path,
                    decoder_config=decoder_config,
                )
            elif config_class.model_type == "vision-text-dual-encoder":
                model = model_class.from_vision_text_pretrained(encoder_path, decoder_path)

            model_path = os.path.join(
                output_dir,
                f"{model_class.__name__}-{encoder_config_class.model_type}-{decoder_config_class.model_type}",
            )
            model.save_pretrained(model_path)

            if tf_model_class is not None:
                model = tf_model_class.from_pretrained(model_path, from_pt=True)
                model.save_pretrained(model_path)

            # copy the processors
            encoder_processor_path = os.path.join(encoder_output_dir, "processors")
            decoder_processor_path = os.path.join(decoder_output_dir, "processors")
            if os.path.isdir(encoder_processor_path):
                shutil.copytree(encoder_processor_path, model_path, dirs_exist_ok=True)
            if os.path.isdir(decoder_processor_path):
                shutil.copytree(decoder_processor_path, model_path, dirs_exist_ok=True)

            # fill `result`
931
            result["processor"] = {x.__name__: x.__name__ for x in encoder_processor + decoder_processor}
Yih-Dar's avatar
Yih-Dar committed
932
933
934
935
936
937
938
939

            result["pytorch"] = {model_class.__name__: {"model": model_class.__name__, "checkpoint": model_path}}

            result["tensorflow"] = {}
            if tf_model_class is not None:
                result["tensorflow"] = {
                    tf_model_class.__name__: {"model": tf_model_class.__name__, "checkpoint": model_path}
                }
940
941
942
943
944
        except Exception:
            result["error"] = (
                f"Failed to build models for {config_class.__name__}.",
                traceback.format_exc(),
            )
Yih-Dar's avatar
Yih-Dar committed
945
946
947
948
949
950
951
952
953

    if not result["error"]:
        del result["error"]
    if not result["warnings"]:
        del result["warnings"]

    return result


954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
def get_token_id_from_tokenizer(token_id_name, tokenizer, original_token_id):
    """Use `tokenizer` to get the values of `bos_token_id`, `eos_token_ids`, etc.

    The argument `token_id_name` should be a string ending with `_token_id`, and `original_token_id` should be an
    integer that will be return if `tokenizer` has no token corresponding to `token_id_name`.
    """

    token_id = original_token_id

    if not token_id_name.endswith("_token_id"):
        raise ValueError(f"`token_id_name` is {token_id_name}, which doesn't end with `_token_id`!")

    token = getattr(tokenizer, token_id_name.replace("_token_id", "_token"), None)
    if token is not None:
        if isinstance(tokenizer, PreTrainedTokenizerFast):
            token_id = tokenizer._convert_token_to_id_with_added_voc(token)
        else:
            token_id = tokenizer._convert_token_to_id(token)

    return token_id


def get_config_overrides(config_class, processors):
977
978
979
980
    # `Bark` configuration is too special. Let's just not handle this for now.
    if config_class.__name__ == "BarkConfig":
        return {}

981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
    config_overrides = {}

    # Check if there is any tokenizer (prefer fast version if any)
    tokenizer = None
    for processor in processors:
        if isinstance(processor, PreTrainedTokenizerFast):
            tokenizer = processor
            break
        elif isinstance(processor, PreTrainedTokenizer):
            tokenizer = processor

    if tokenizer is None:
        return config_overrides

    # Get some properties of the (already converted) tokenizer (smaller vocab size, special token ids, etc.)
996
997
998
    # We use `len(tokenizer)` instead of `tokenizer.vocab_size` to avoid potential issues for tokenizers with non-empty
    # `added_tokens_encoder`. One example is the `DebertaV2Tokenizer` where the mask token is the extra token.
    vocab_size = len(tokenizer)
999
1000
1001
1002
1003
1004

    # The original checkpoint has length `35998`, but it doesn't have ids `30400` and `30514` but instead `35998` and
    # `35999`.
    if config_class.__name__ == "GPTSanJapaneseConfig":
        vocab_size += 2

1005
1006
1007
1008
1009
1010
    config_overrides["vocab_size"] = vocab_size

    # Used to create a new model tester with `tokenizer.vocab_size` in order to get the (updated) special token ids.
    model_tester_kwargs = {"vocab_size": vocab_size}
    # CLIP-like models have `text_model_tester` and `vision_model_tester`, and we need to pass `vocab_size` to
    # `text_model_tester` via `text_kwargs`. The same trick is also necessary for `Flava`.
1011
    if config_class.__name__ in [
1012
1013
1014
1015
1016
        "AlignConfig",
        "AltCLIPConfig",
        "ChineseCLIPConfig",
        "CLIPSegConfig",
        "ClapConfig",
1017
1018
1019
1020
1021
1022
1023
1024
        "CLIPConfig",
        "GroupViTConfig",
        "OwlViTConfig",
        "XCLIPConfig",
        "FlavaConfig",
        "BlipConfig",
        "Blip2Config",
    ]:
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
        del model_tester_kwargs["vocab_size"]
        model_tester_kwargs["text_kwargs"] = {"vocab_size": vocab_size}
    # `FSMTModelTester` accepts `src_vocab_size` and `tgt_vocab_size` but not `vocab_size`.
    elif config_class.__name__ == "FSMTConfig":
        del model_tester_kwargs["vocab_size"]
        model_tester_kwargs["src_vocab_size"] = tokenizer.src_vocab_size
        model_tester_kwargs["tgt_vocab_size"] = tokenizer.tgt_vocab_size

    _tiny_config = get_tiny_config(config_class, **model_tester_kwargs)

    # handle the possibility of `text_config` inside `_tiny_config` for clip-like models (`owlvit`, `groupvit`, etc.)
    if hasattr(_tiny_config, "text_config"):
        _tiny_config = _tiny_config.text_config

    # Collect values of some special token ids
    for attr in dir(_tiny_config):
        if attr.endswith("_token_id"):
            token_id = getattr(_tiny_config, attr)
            if token_id is not None:
                # Using the token id values from `tokenizer` instead of from `_tiny_config`.
                token_id = get_token_id_from_tokenizer(attr, tokenizer, original_token_id=token_id)
                config_overrides[attr] = token_id

    if config_class.__name__ == "FSMTConfig":
        config_overrides["src_vocab_size"] = tokenizer.src_vocab_size
        config_overrides["tgt_vocab_size"] = tokenizer.tgt_vocab_size
        # `FSMTConfig` has `DecoderConfig` as `decoder` attribute.
        config_overrides["decoder"] = configuration_fsmt.DecoderConfig(
            vocab_size=tokenizer.tgt_vocab_size, bos_token_id=config_overrides["eos_token_id"]
        )

    return config_overrides


Yih-Dar's avatar
Yih-Dar committed
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
def build(config_class, models_to_create, output_dir):
    """Create all models for a certain model type.

    Args:
        config_class (`PretrainedConfig`):
            A subclass of `PretrainedConfig` that is used to determine `models_to_create`.
        models_to_create (`dict`):
            A dictionary containing the processor/model classes that we want to create the instances. These models are
            of the same model type which is associated to `config_class`.
        output_dir (`str`):
            The directory to save all the checkpoints. Each model architecture will be saved in a subdirectory under
            it. Models in different frameworks with the same architecture will be saved in the same subdirectory.
    """
1072
1073
1074
1075
    if data["training_ds"] is None or data["testing_ds"] is None:
        ds = load_dataset("wikitext", "wikitext-2-raw-v1")
        data["training_ds"] = ds["train"]
        data["testing_ds"] = ds["test"]
Yih-Dar's avatar
Yih-Dar committed
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095

    if config_class.model_type in [
        "encoder-decoder",
        "vision-encoder-decoder",
        "speech-encoder-decoder",
        "vision-text-dual-encoder",
    ]:
        return build_composite_models(config_class, output_dir)

    result = {k: {} for k in models_to_create}

    # These will be removed at the end if they are empty
    result["error"] = None
    result["warnings"] = []

    # Build processors
    processor_classes = models_to_create["processor"]

    if len(processor_classes) == 0:
        error = f"No processor class could be found in {config_class.__name__}."
1096
1097
        fill_result_with_error(result, error, None, models_to_create)
        logger.error(result["error"][0])
Yih-Dar's avatar
Yih-Dar committed
1098
1099
1100
        return result

    for processor_class in processor_classes:
1101
        try:
1102
            processor = build_processor(config_class, processor_class, allow_no_checkpoint=True)
1103
1104
            if processor is not None:
                result["processor"][processor_class] = processor
1105
1106
1107
1108
1109
        except Exception:
            error = f"Failed to build processor for {processor_class.__name__}."
            trace = traceback.format_exc()
            fill_result_with_error(result, error, trace, models_to_create)
            logger.error(result["error"][0])
1110
            return result
Yih-Dar's avatar
Yih-Dar committed
1111
1112
1113

    if len(result["processor"]) == 0:
        error = f"No processor could be built for {config_class.__name__}."
1114
1115
        fill_result_with_error(result, error, None, models_to_create)
        logger.error(result["error"][0])
Yih-Dar's avatar
Yih-Dar committed
1116
1117
1118
1119
1120
        return result

    try:
        tiny_config = get_tiny_config(config_class)
    except Exception as e:
1121
        error = f"Failed to get tiny config for {config_class.__name__}: {e}"
1122
1123
1124
        trace = traceback.format_exc()
        fill_result_with_error(result, error, trace, models_to_create)
        logger.error(result["error"][0])
Yih-Dar's avatar
Yih-Dar committed
1125
1126
1127
1128
1129
        return result

    # Convert the processors (reduce vocabulary size, smaller image size, etc.)
    processors = list(result["processor"].values())
    processor_output_folder = os.path.join(output_dir, "processors")
1130
1131
    try:
        processors = convert_processors(processors, tiny_config, processor_output_folder, result)
1132
1133
1134
1135
    except Exception:
        error = "Failed to convert the processors."
        trace = traceback.format_exc()
        result["warnings"].append((error, trace))
Yih-Dar's avatar
Yih-Dar committed
1136

1137
1138
    if len(processors) == 0:
        error = f"No processor is returned by `convert_processors` for {config_class.__name__}."
1139
1140
        fill_result_with_error(result, error, None, models_to_create)
        logger.error(result["error"][0])
Yih-Dar's avatar
Yih-Dar committed
1141
1142
        return result

1143
1144
1145
1146
    try:
        config_overrides = get_config_overrides(config_class, processors)
    except Exception as e:
        error = f"Failure occurs while calling `get_config_overrides`: {e}"
1147
1148
1149
        trace = traceback.format_exc()
        fill_result_with_error(result, error, trace, models_to_create)
        logger.error(result["error"][0])
1150
1151
1152
1153
1154
1155
1156
        return result

    # Just for us to see this easily in the report
    if "vocab_size" in config_overrides:
        result["vocab_size"] = config_overrides["vocab_size"]

    # Update attributes that `vocab_size` involves
Yih-Dar's avatar
Yih-Dar committed
1157
1158
1159
    for k, v in config_overrides.items():
        if hasattr(tiny_config, k):
            setattr(tiny_config, k, v)
1160
        # So far, we only have to deal with `text_config`, as `config_overrides` contains text-related attributes only.
Yih-Dar's avatar
Yih-Dar committed
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
        elif (
            hasattr(tiny_config, "text_config")
            and tiny_config.text_config is not None
            and hasattr(tiny_config.text_config, k)
        ):
            setattr(tiny_config.text_config, k, v)
            # If `text_config_dict` exists, we need to update its value here too in order to # make
            # `save_pretrained -> from_pretrained` work.
            if hasattr(tiny_config, "text_config_dict"):
                tiny_config.text_config_dict[k] = v

    if result["warnings"]:
1173
        logger.warning(result["warnings"][0][0])
Yih-Dar's avatar
Yih-Dar committed
1174

1175
1176
1177
    # update `result["processor"]`
    result["processor"] = {type(p).__name__: p.__class__.__name__ for p in processors}

Yih-Dar's avatar
Yih-Dar committed
1178
1179
1180
1181
1182
1183
1184
1185
    for pytorch_arch in models_to_create["pytorch"]:
        result["pytorch"][pytorch_arch.__name__] = {}
        error = None
        try:
            model = build_model(pytorch_arch, tiny_config, output_dir=output_dir)
        except Exception as e:
            model = None
            error = f"Failed to create the pytorch model for {pytorch_arch}: {e}"
1186
            trace = traceback.format_exc()
Yih-Dar's avatar
Yih-Dar committed
1187
1188
1189
1190
1191

        result["pytorch"][pytorch_arch.__name__]["model"] = model.__class__.__name__ if model is not None else None
        result["pytorch"][pytorch_arch.__name__]["checkpoint"] = (
            get_checkpoint_dir(output_dir, pytorch_arch) if model is not None else None
        )
1192
        if error is not None:
1193
            result["pytorch"][pytorch_arch.__name__]["error"] = (error, trace)
Yih-Dar's avatar
Yih-Dar committed
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
            logger.error(f"{pytorch_arch.__name__}: {error}")

    for tensorflow_arch in models_to_create["tensorflow"]:
        # Make PT/TF weights compatible
        pt_arch_name = tensorflow_arch.__name__[2:]  # Remove `TF`
        pt_arch = getattr(transformers_module, pt_arch_name)

        result["tensorflow"][tensorflow_arch.__name__] = {}
        error = None
        if pt_arch.__name__ in result["pytorch"] and result["pytorch"][pt_arch.__name__]["checkpoint"] is not None:
            ckpt = get_checkpoint_dir(output_dir, pt_arch)
            # Use the same weights from PyTorch.
            try:
                model = tensorflow_arch.from_pretrained(ckpt, from_pt=True)
                model.save_pretrained(ckpt)
            except Exception as e:
                # Conversion may fail. Let's not create a model with different weights to avoid confusion (for now).
                model = None
                error = f"Failed to convert the pytorch model to the tensorflow model for {pt_arch}: {e}"
1213
                trace = traceback.format_exc()
Yih-Dar's avatar
Yih-Dar committed
1214
1215
1216
1217
1218
1219
        else:
            try:
                model = build_model(tensorflow_arch, tiny_config, output_dir=output_dir)
            except Exception as e:
                model = None
                error = f"Failed to create the tensorflow model for {tensorflow_arch}: {e}"
1220
                trace = traceback.format_exc()
Yih-Dar's avatar
Yih-Dar committed
1221
1222
1223
1224
1225
1226
1227

        result["tensorflow"][tensorflow_arch.__name__]["model"] = (
            model.__class__.__name__ if model is not None else None
        )
        result["tensorflow"][tensorflow_arch.__name__]["checkpoint"] = (
            get_checkpoint_dir(output_dir, tensorflow_arch) if model is not None else None
        )
1228
        if error is not None:
1229
            result["tensorflow"][tensorflow_arch.__name__]["error"] = (error, trace)
Yih-Dar's avatar
Yih-Dar committed
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
            logger.error(f"{tensorflow_arch.__name__}: {error}")

    if not result["error"]:
        del result["error"]
    if not result["warnings"]:
        del result["warnings"]

    return result


1240
def build_tiny_model_summary(results, organization=None, token=None):
1241
1242
1243
1244
1245
    """Build a summary: a dictionary of the form
    {
      model architecture name:
        {
          "tokenizer_classes": [...],
1246
1247
          "processor_classes": [...],
          "model_classes": [...],
1248
1249
1250
1251
1252
1253
1254
        }
      ..
    }
    """
    tiny_model_summary = {}
    for config_name in results:
        processors = [key for key, value in results[config_name]["processor"].items()]
1255
1256
        tokenizer_classes = sorted([x for x in processors if x.endswith("TokenizerFast") or x.endswith("Tokenizer")])
        processor_classes = sorted([x for x in processors if x not in tokenizer_classes])
1257
1258
1259
1260
        for framework in FRAMEWORKS:
            if framework not in results[config_name]:
                continue
            for arch_name in results[config_name][framework]:
1261
1262
                model_classes = [arch_name]
                base_arch_name = arch_name[2:] if arch_name.startswith("TF") else arch_name
1263
                # tiny model is not created for `arch_name`
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
                if results[config_name][framework][arch_name]["model"] is None:
                    model_classes = []
                if base_arch_name not in tiny_model_summary:
                    tiny_model_summary[base_arch_name] = {}
                tiny_model_summary[base_arch_name].update(
                    {
                        "tokenizer_classes": tokenizer_classes,
                        "processor_classes": processor_classes,
                    }
                )
                tiny_model_summary[base_arch_name]["model_classes"] = sorted(
                    tiny_model_summary[base_arch_name].get("model_classes", []) + model_classes
                )
                if organization is not None:
                    repo_name = f"tiny-random-{base_arch_name}"
                    # composite models' checkpoints have more precise repo. names on the Hub.
                    if base_arch_name in COMPOSITE_MODELS:
                        repo_name = f"tiny-random-{COMPOSITE_MODELS[base_arch_name]}"
                    repo_id = f"{organization}/{repo_name}"
                    try:
                        commit_hash = hf_api.repo_info(repo_id, token=token).sha
                    except Exception:
                        # The directory is not created, but processor(s) is/are included in `results`.
                        logger.warning(f"Failed to get information for {repo_id}.\n{traceback.format_exc()}")
                        del tiny_model_summary[base_arch_name]
                        continue
                    tiny_model_summary[base_arch_name]["sha"] = commit_hash
1291
1292
1293
1294

    return tiny_model_summary


Yih-Dar's avatar
Yih-Dar committed
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
def build_failed_report(results, include_warning=True):
    failed_results = {}
    for config_name in results:
        if "error" in results[config_name]:
            if config_name not in failed_results:
                failed_results[config_name] = {}
            failed_results[config_name] = {"error": results[config_name]["error"]}

        if include_warning and "warnings" in results[config_name]:
            if config_name not in failed_results:
                failed_results[config_name] = {}
            failed_results[config_name]["warnings"] = results[config_name]["warnings"]

        for framework in FRAMEWORKS:
            if framework not in results[config_name]:
                continue
            for arch_name in results[config_name][framework]:
                if "error" in results[config_name][framework][arch_name]:
                    if config_name not in failed_results:
                        failed_results[config_name] = {}
                    if framework not in failed_results[config_name]:
                        failed_results[config_name][framework] = {}
                    if arch_name not in failed_results[config_name][framework]:
                        failed_results[config_name][framework][arch_name] = {}
                    error = results[config_name][framework][arch_name]["error"]
                    failed_results[config_name][framework][arch_name]["error"] = error

    return failed_results


def build_simple_report(results):
    text = ""
    failed_text = ""
    for config_name in results:
        for framework in FRAMEWORKS:
            if framework not in results[config_name]:
                continue
            for arch_name in results[config_name][framework]:
                if "error" in results[config_name][framework][arch_name]:
                    result = results[config_name][framework][arch_name]["error"]
1335
                    failed_text += f"{arch_name}: {result[0]}\n"
Yih-Dar's avatar
Yih-Dar committed
1336
                else:
1337
1338
                    result = ("OK",)
                text += f"{arch_name}: {result[0]}\n"
Yih-Dar's avatar
Yih-Dar committed
1339
1340
1341
1342

    return text, failed_text


1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
def update_tiny_model_summary_file(report_path):
    with open(os.path.join(report_path, "tiny_model_summary.json")) as fp:
        new_data = json.load(fp)
    with open("tests/utils/tiny_model_summary.json") as fp:
        data = json.load(fp)
    for key, value in new_data.items():
        if key not in data:
            data[key] = value
        else:
            for attr in ["tokenizer_classes", "processor_classes", "model_classes"]:
                # we might get duplication here. We will remove them below when creating `updated_data`.
                data[key][attr].extend(value[attr])
            new_sha = value.get("sha", None)
            if new_sha is not None:
                data[key]["sha"] = new_sha

    updated_data = {}
    for key in sorted(data.keys()):
        updated_data[key] = {}
        for attr, value in data[key].items():
            # deduplication and sort
            updated_data[key][attr] = sorted(set(value)) if attr != "sha" else value

    with open(os.path.join(report_path, "updated_tiny_model_summary.json"), "w") as fp:
        json.dump(updated_data, fp, indent=4, ensure_ascii=False)


1370
1371
1372
1373
1374
1375
1376
1377
1378
def create_tiny_models(
    output_path,
    all,
    model_types,
    models_to_skip,
    no_check,
    upload,
    organization,
    token,
1379
    num_workers=1,
1380
):
Yih-Dar's avatar
Yih-Dar committed
1381
1382
1383
1384
    clone_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    if os.getcwd() != clone_path:
        raise ValueError(f"This script should be run from the root of the clone of `transformers` {clone_path}")

1385
1386
1387
    report_path = os.path.join(output_path, "reports")
    os.makedirs(report_path)

Yih-Dar's avatar
Yih-Dar committed
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
    _pytorch_arch_mappings = [
        x
        for x in dir(transformers_module)
        if x.startswith("MODEL_") and x.endswith("_MAPPING") and x != "MODEL_NAMES_MAPPING"
    ]
    _tensorflow_arch_mappings = [
        x for x in dir(transformers_module) if x.startswith("TF_MODEL_") and x.endswith("_MAPPING")
    ]

    pytorch_arch_mappings = [getattr(transformers_module, x) for x in _pytorch_arch_mappings]
    tensorflow_arch_mappings = [getattr(transformers_module, x) for x in _tensorflow_arch_mappings]

    config_classes = CONFIG_MAPPING.values()
1401
1402
    if not all:
        config_classes = [CONFIG_MAPPING[model_type] for model_type in model_types]
Yih-Dar's avatar
Yih-Dar committed
1403
1404
1405
1406

    # A map from config classes to tuples of processors (tokenizer, feature extractor, processor) classes
    processor_type_map = {c: get_processor_types_from_config_class(c) for c in config_classes}

1407
1408
1409
1410
1411
1412
1413
    to_create = {}
    for c in config_classes:
        processors = processor_type_map[c]
        models = get_architectures_from_config_class(c, pytorch_arch_mappings, models_to_skip)
        tf_models = get_architectures_from_config_class(c, tensorflow_arch_mappings, models_to_skip)
        if len(models) + len(tf_models) > 0:
            to_create[c] = {"processor": processors, "pytorch": models, "tensorflow": tf_models}
Yih-Dar's avatar
Yih-Dar committed
1414
1415

    results = {}
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
    if num_workers <= 1:
        for c, models_to_create in list(to_create.items()):
            print(f"Create models for {c.__name__} ...")
            result = build(c, models_to_create, output_dir=os.path.join(output_path, c.model_type))
            results[c.__name__] = result
            print("=" * 40)
    else:
        all_build_args = []
        for c, models_to_create in list(to_create.items()):
            all_build_args.append((c, models_to_create, os.path.join(output_path, c.model_type)))
        with multiprocessing.Pool() as pool:
            results = pool.starmap(build, all_build_args)
            results = {buid_args[0].__name__: result for buid_args, result in zip(all_build_args, results)}
Yih-Dar's avatar
Yih-Dar committed
1429

1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
    if upload:
        if organization is None:
            raise ValueError("The argument `organization` could not be `None`. No model is uploaded")

        to_upload = []
        for model_type in os.listdir(output_path):
            # This is the directory containing the reports
            if model_type == "reports":
                continue
            for arch in os.listdir(os.path.join(output_path, model_type)):
                if arch == "processors":
                    continue
                to_upload.append(os.path.join(output_path, model_type, arch))
        to_upload = sorted(to_upload)

        upload_results = {}
        if len(to_upload) > 0:
            for model_dir in to_upload:
                try:
                    upload_model(model_dir, organization, token)
                except Exception as e:
                    error = f"Failed to upload {model_dir}. {e.__class__.__name__}: {e}"
                    logger.error(error)
                    upload_results[model_dir] = error

        with open(os.path.join(report_path, "failed_uploads.json"), "w") as fp:
            json.dump(upload_results, fp, indent=4)
Yih-Dar's avatar
Yih-Dar committed
1457

1458
1459
1460
1461
    # Build the tiny model summary file. The `tokenizer_classes` and `processor_classes` could be both empty lists.
    # When using the items in this file to update the file `tests/utils/tiny_model_summary.json`, the model
    # architectures with `tokenizer_classes` and `processor_classes` being both empty should **NOT** be added to
    # `tests/utils/tiny_model_summary.json`.
1462
1463
    tiny_model_summary = build_tiny_model_summary(results, organization=organization, token=token)
    with open(os.path.join(report_path, "tiny_model_summary.json"), "w") as fp:
1464
1465
        json.dump(tiny_model_summary, fp, indent=4)

1466
1467
1468
    with open(os.path.join(report_path, "tiny_model_creation_report.json"), "w") as fp:
        json.dump(results, fp, indent=4)

1469
1470
    # Build the warning/failure report (json format): same format as the complete `results` except this contains only
    # warnings or errors.
Yih-Dar's avatar
Yih-Dar committed
1471
    failed_results = build_failed_report(results)
1472
    with open(os.path.join(report_path, "failed_report.json"), "w") as fp:
Yih-Dar's avatar
Yih-Dar committed
1473
1474
1475
        json.dump(failed_results, fp, indent=4)

    simple_report, failed_report = build_simple_report(results)
1476
1477
    # The simplified report: a .txt file with each line of format:
    # {model architecture name}: {OK or error message}
1478
    with open(os.path.join(report_path, "simple_report.txt"), "w") as fp:
Yih-Dar's avatar
Yih-Dar committed
1479
1480
        fp.write(simple_report)

1481
    # The simplified failure report: same above except this only contains line with errors
1482
    with open(os.path.join(report_path, "simple_failed_report.txt"), "w") as fp:
Yih-Dar's avatar
Yih-Dar committed
1483
        fp.write(failed_report)
1484

1485
1486
    update_tiny_model_summary_file(report_path=os.path.join(output_path, "reports"))

1487

1488
if __name__ == "__main__":
1489
1490
    # This has to be `spawn` to avoid hanging forever!
    multiprocessing.set_start_method("spawn")
1491

1492
1493
    def list_str(values):
        return values.split(",")
1494

1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
    parser = argparse.ArgumentParser()
    parser.add_argument("--all", action="store_true", help="Will create all tiny models.")
    parser.add_argument(
        "--no_check",
        action="store_true",
        help="If set, will not check the validity of architectures. Use with caution.",
    )
    parser.add_argument(
        "-m",
        "--model_types",
        type=list_str,
        help="Comma-separated list of model type(s) from which the tiny models will be created.",
    )
    parser.add_argument(
        "--models_to_skip",
        type=list_str,
        help=(
            "Comma-separated list of model class names(s) from which the tiny models won't be created.\nThis is usually"
            "the list of model classes that have their tiny versions already uploaded to the Hub."
        ),
    )
    parser.add_argument("--upload", action="store_true", help="If to upload the created tiny models to the Hub.")
    parser.add_argument(
        "--organization",
        default=None,
        type=str,
        help="The organization on the Hub to which the tiny models will be uploaded.",
    )
    parser.add_argument(
        "--token", default=None, type=str, help="A valid authentication token for HuggingFace Hub with write access."
    )
    parser.add_argument("output_path", type=Path, help="Path indicating where to store generated model.")
1527
    parser.add_argument("--num_workers", default=1, type=int, help="The number of workers to run.")
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542

    args = parser.parse_args()

    if not args.all and not args.model_types:
        raise ValueError("Please provide at least one model type or pass `--all` to export all architectures.")

    create_tiny_models(
        args.output_path,
        args.all,
        args.model_types,
        args.models_to_skip,
        args.no_check,
        args.upload,
        args.organization,
        args.token,
1543
        args.num_workers,
1544
    )