dynamic_module_utils.py 26.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# coding=utf-8
# Copyright 2021 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.
15
"""Utilities to dynamically load objects from the Hub."""
16
import filecmp
17
18
19
20
import importlib
import os
import re
import shutil
21
import signal
22
import sys
23
import typing
Yih-Dar's avatar
Yih-Dar committed
24
import warnings
25
from pathlib import Path
26
from typing import Any, Dict, List, Optional, Union
27

28
29
from huggingface_hub import try_to_load_from_cache

30
31
32
33
34
35
36
37
from .utils import (
    HF_MODULES_CACHE,
    TRANSFORMERS_DYNAMIC_MODULE_NAME,
    cached_file,
    extract_commit_hash,
    is_offline_mode,
    logging,
)
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55


logger = logging.get_logger(__name__)  # pylint: disable=invalid-name


def init_hf_modules():
    """
    Creates the cache directory for modules with an init, and adds it to the Python path.
    """
    # This function has already been executed if HF_MODULES_CACHE already is in the Python path.
    if HF_MODULES_CACHE in sys.path:
        return

    sys.path.append(HF_MODULES_CACHE)
    os.makedirs(HF_MODULES_CACHE, exist_ok=True)
    init_path = Path(HF_MODULES_CACHE) / "__init__.py"
    if not init_path.exists():
        init_path.touch()
56
        importlib.invalidate_caches()
57
58
59
60
61


def create_dynamic_module(name: Union[str, os.PathLike]):
    """
    Creates a dynamic module in the cache directory for modules.
62
63
64
65

    Args:
        name (`str` or `os.PathLike`):
            The name of the dynamic module to create.
66
67
    """
    init_hf_modules()
68
    dynamic_module_path = (Path(HF_MODULES_CACHE) / name).resolve()
69
70
71
72
73
74
75
    # If the parent module does not exist yet, recursively create it.
    if not dynamic_module_path.parent.exists():
        create_dynamic_module(dynamic_module_path.parent)
    os.makedirs(dynamic_module_path, exist_ok=True)
    init_path = dynamic_module_path / "__init__.py"
    if not init_path.exists():
        init_path.touch()
76
77
        # It is extremely important to invalidate the cache when we change stuff in those modules, or users end up
        # with errors about module that do not exist. Same for all other `invalidate_caches` in this file.
78
        importlib.invalidate_caches()
79
80


81
def get_relative_imports(module_file: Union[str, os.PathLike]) -> List[str]:
82
83
84
85
86
    """
    Get the list of modules that are relatively imported in a module file.

    Args:
        module_file (`str` or `os.PathLike`): The module file to inspect.
87
88
89

    Returns:
        `List[str]`: The list of relative imports in the module.
90
91
92
93
94
    """
    with open(module_file, "r", encoding="utf-8") as f:
        content = f.read()

    # Imports of the form `import .xxx`
95
    relative_imports = re.findall(r"^\s*import\s+\.(\S+)\s*$", content, flags=re.MULTILINE)
96
    # Imports of the form `from .xxx import yyy`
97
    relative_imports += re.findall(r"^\s*from\s+\.(\S+)\s+import", content, flags=re.MULTILINE)
98
99
100
101
    # Unique-ify
    return list(set(relative_imports))


102
def get_relative_import_files(module_file: Union[str, os.PathLike]) -> List[str]:
103
104
105
106
107
108
    """
    Get the list of all files that are needed for a given module. Note that this function recurses through the relative
    imports (if a imports b and b imports c, it will return module files for b and c).

    Args:
        module_file (`str` or `os.PathLike`): The module file to inspect.
109
110
111
112

    Returns:
        `List[str]`: The list of all relative imports a given module needs (recursively), which will give us the list
        of module files a given module needs.
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
    """
    no_change = False
    files_to_check = [module_file]
    all_relative_imports = []

    # Let's recurse through all relative imports
    while not no_change:
        new_imports = []
        for f in files_to_check:
            new_imports.extend(get_relative_imports(f))

        module_path = Path(module_file).parent
        new_import_files = [str(module_path / m) for m in new_imports]
        new_import_files = [f for f in new_import_files if f not in all_relative_imports]
        files_to_check = [f"{f}.py" for f in new_import_files]

        no_change = len(new_import_files) == 0
        all_relative_imports.extend(files_to_check)

    return all_relative_imports


135
def get_imports(filename: Union[str, os.PathLike]) -> List[str]:
136
    """
137
138
139
140
141
142
143
    Extracts all the libraries (not relative imports this time) that are imported in a file.

    Args:
        filename (`str` or `os.PathLike`): The module file to inspect.

    Returns:
        `List[str]`: The list of all packages required to use the input module.
144
145
146
147
    """
    with open(filename, "r", encoding="utf-8") as f:
        content = f.read()

148
    # filter out try/except block so in custom code we can have try/except imports
149
    content = re.sub(r"\s*try\s*:\s*.*?\s*except\s*.*?:", "", content, flags=re.MULTILINE | re.DOTALL)
150

151
    # Imports of the form `import xxx`
152
    imports = re.findall(r"^\s*import\s+(\S+)\s*$", content, flags=re.MULTILINE)
153
    # Imports of the form `from xxx import yyy`
154
    imports += re.findall(r"^\s*from\s+(\S+)\s+import", content, flags=re.MULTILINE)
155
156
    # Only keep the top-level module
    imports = [imp.split(".")[0] for imp in imports if not imp.startswith(".")]
Sylvain Gugger's avatar
Sylvain Gugger committed
157
158
    return list(set(imports))

159

160
def check_imports(filename: Union[str, os.PathLike]) -> List[str]:
Sylvain Gugger's avatar
Sylvain Gugger committed
161
    """
162
163
164
165
166
167
168
169
    Check if the current Python environment contains all the libraries that are imported in a file. Will raise if a
    library is missing.

    Args:
        filename (`str` or `os.PathLike`): The module file to check.

    Returns:
        `List[str]`: The list of relative imports in the file.
Sylvain Gugger's avatar
Sylvain Gugger committed
170
171
    """
    imports = get_imports(filename)
172
173
174
175
176
177
178
179
180
181
182
183
184
    missing_packages = []
    for imp in imports:
        try:
            importlib.import_module(imp)
        except ImportError:
            missing_packages.append(imp)

    if len(missing_packages) > 0:
        raise ImportError(
            "This modeling file requires the following packages that were not found in your environment: "
            f"{', '.join(missing_packages)}. Run `pip install {' '.join(missing_packages)}`"
        )

185
    return get_relative_imports(filename)
186

187

188
def get_class_in_module(class_name: str, module_path: Union[str, os.PathLike]) -> typing.Type:
189
190
    """
    Import a module on the cache directory for modules and extract a class from it.
191
192
193
194
195
196
197

    Args:
        class_name (`str`): The name of the class to import.
        module_path (`str` or `os.PathLike`): The path to the module to import.

    Returns:
        `typing.Type`: The class looked for.
198
    """
199
200
201
    name = os.path.normpath(module_path).replace(".py", "").replace(os.path.sep, ".")
    module_path = str(Path(HF_MODULES_CACHE) / module_path)
    module = importlib.machinery.SourceFileLoader(name, module_path).load_module()
202
    return getattr(module, class_name)
203
204


205
def get_cached_module_file(
206
207
208
209
210
211
    pretrained_model_name_or_path: Union[str, os.PathLike],
    module_file: str,
    cache_dir: Optional[Union[str, os.PathLike]] = None,
    force_download: bool = False,
    resume_download: bool = False,
    proxies: Optional[Dict[str, str]] = None,
Yih-Dar's avatar
Yih-Dar committed
212
    token: Optional[Union[bool, str]] = None,
213
214
    revision: Optional[str] = None,
    local_files_only: bool = False,
Sylvain Gugger's avatar
Sylvain Gugger committed
215
    repo_type: Optional[str] = None,
216
    _commit_hash: Optional[str] = None,
Yih-Dar's avatar
Yih-Dar committed
217
    **deprecated_kwargs,
218
) -> str:
219
    """
220
221
    Prepares Downloads a module from a local folder or a distant repo and returns its path inside the cached
    Transformers module.
222
223

    Args:
224
        pretrained_model_name_or_path (`str` or `os.PathLike`):
225
226
            This can be either:

227
            - a string, the *model id* of a pretrained model configuration hosted inside a model repo on
228
              huggingface.co.
229
230
            - a path to a *directory* containing a configuration file saved using the
              [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
231

232
        module_file (`str`):
233
            The name of the module file containing the class to look for.
234
        cache_dir (`str` or `os.PathLike`, *optional*):
235
236
            Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
            cache should not be used.
237
        force_download (`bool`, *optional*, defaults to `False`):
238
239
            Whether or not to force to (re-)download the configuration files and override the cached versions if they
            exist.
240
        resume_download (`bool`, *optional*, defaults to `False`):
241
            Whether or not to delete incompletely received file. Attempts to resume the download if such a file exists.
242
        proxies (`Dict[str, str]`, *optional*):
Sylvain Gugger's avatar
Sylvain Gugger committed
243
244
            A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
            'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
Yih-Dar's avatar
Yih-Dar committed
245
        token (`str` or *bool*, *optional*):
Sylvain Gugger's avatar
Sylvain Gugger committed
246
            The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
247
            when running `huggingface-cli login` (stored in `~/.huggingface`).
248
        revision (`str`, *optional*, defaults to `"main"`):
249
            The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
250
            git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
251
            identifier allowed by git.
252
253
        local_files_only (`bool`, *optional*, defaults to `False`):
            If `True`, will only try to load the tokenizer configuration from local files.
Sylvain Gugger's avatar
Sylvain Gugger committed
254
255
        repo_type (`str`, *optional*):
            Specify the repo type (useful when downloading from a space for instance).
256

257
    <Tip>
258

Yih-Dar's avatar
Yih-Dar committed
259
    Passing `token=True` is required when you want to use a private model.
260

261
    </Tip>
262
263

    Returns:
264
265
        `str`: The path to the module inside the cache.
    """
Yih-Dar's avatar
Yih-Dar committed
266
267
268
    use_auth_token = deprecated_kwargs.pop("use_auth_token", None)
    if use_auth_token is not None:
        warnings.warn(
269
270
            "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
            FutureWarning,
Yih-Dar's avatar
Yih-Dar committed
271
272
273
274
275
        )
        if token is not None:
            raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
        token = use_auth_token

276
277
278
279
280
281
    if is_offline_mode() and not local_files_only:
        logger.info("Offline mode: forcing local_files_only=True")
        local_files_only = True

    # Download and cache module_file from the repo `pretrained_model_name_or_path` of grab it if it's a local file.
    pretrained_model_name_or_path = str(pretrained_model_name_or_path)
282
283
    is_local = os.path.isdir(pretrained_model_name_or_path)
    if is_local:
284
        submodule = os.path.basename(pretrained_model_name_or_path)
285
286
    else:
        submodule = pretrained_model_name_or_path.replace("/", os.path.sep)
287
        cached_module = try_to_load_from_cache(
Sylvain Gugger's avatar
Sylvain Gugger committed
288
            pretrained_model_name_or_path, module_file, cache_dir=cache_dir, revision=_commit_hash, repo_type=repo_type
289
        )
290

291
    new_files = []
292
293
    try:
        # Load from URL or cache if already cached
Sylvain Gugger's avatar
Sylvain Gugger committed
294
295
296
        resolved_module_file = cached_file(
            pretrained_model_name_or_path,
            module_file,
297
298
299
300
301
            cache_dir=cache_dir,
            force_download=force_download,
            proxies=proxies,
            resume_download=resume_download,
            local_files_only=local_files_only,
Yih-Dar's avatar
Yih-Dar committed
302
            token=token,
303
            revision=revision,
Sylvain Gugger's avatar
Sylvain Gugger committed
304
            repo_type=repo_type,
305
            _commit_hash=_commit_hash,
306
        )
307
308
        if not is_local and cached_module != resolved_module_file:
            new_files.append(module_file)
309
310
311
312
313
314

    except EnvironmentError:
        logger.error(f"Could not locate the {module_file} inside {pretrained_model_name_or_path}.")
        raise

    # Check we have all the requirements in our environment
315
    modules_needed = check_imports(resolved_module_file)
316
317
318
319
320

    # Now we move the module inside our cached dynamic modules.
    full_submodule = TRANSFORMERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
    create_dynamic_module(full_submodule)
    submodule_path = Path(HF_MODULES_CACHE) / full_submodule
321
    if submodule == os.path.basename(pretrained_model_name_or_path):
322
323
324
325
326
327
328
        # We copy local files to avoid putting too many folders in sys.path. This copy is done when the file is new or
        # has changed since last copy.
        if not (submodule_path / module_file).exists() or not filecmp.cmp(
            resolved_module_file, str(submodule_path / module_file)
        ):
            shutil.copy(resolved_module_file, submodule_path / module_file)
            importlib.invalidate_caches()
329
330
        for module_needed in modules_needed:
            module_needed = f"{module_needed}.py"
331
332
333
334
335
336
            module_needed_file = os.path.join(pretrained_model_name_or_path, module_needed)
            if not (submodule_path / module_needed).exists() or not filecmp.cmp(
                module_needed_file, str(submodule_path / module_needed)
            ):
                shutil.copy(module_needed_file, submodule_path / module_needed)
                importlib.invalidate_caches()
337
    else:
338
        # Get the commit hash
339
        commit_hash = extract_commit_hash(resolved_module_file, _commit_hash)
340
341
342
343
344
345
346
347
348

        # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the
        # benefit of versioning.
        submodule_path = submodule_path / commit_hash
        full_submodule = full_submodule + os.path.sep + commit_hash
        create_dynamic_module(full_submodule)

        if not (submodule_path / module_file).exists():
            shutil.copy(resolved_module_file, submodule_path / module_file)
349
            importlib.invalidate_caches()
350
351
        # Make sure we also have every file with relative
        for module_needed in modules_needed:
352
            if not (submodule_path / f"{module_needed}.py").exists():
353
354
355
356
357
358
359
                get_cached_module_file(
                    pretrained_model_name_or_path,
                    f"{module_needed}.py",
                    cache_dir=cache_dir,
                    force_download=force_download,
                    resume_download=resume_download,
                    proxies=proxies,
Yih-Dar's avatar
Yih-Dar committed
360
                    token=token,
361
362
                    revision=revision,
                    local_files_only=local_files_only,
363
                    _commit_hash=commit_hash,
364
                )
365
366
                new_files.append(f"{module_needed}.py")

367
    if len(new_files) > 0 and revision is None:
368
        new_files = "\n".join([f"- {f}" for f in new_files])
369
        repo_type_str = "" if repo_type is None else f"{repo_type}s/"
Sylvain Gugger's avatar
Sylvain Gugger committed
370
        url = f"https://huggingface.co/{repo_type_str}{pretrained_model_name_or_path}"
371
        logger.warning(
Sylvain Gugger's avatar
Sylvain Gugger committed
372
            f"A new version of the following files was downloaded from {url}:\n{new_files}"
373
374
375
376
            "\n. Make sure to double-check they do not contain any added malicious code. To avoid downloading new "
            "versions of the code file, you can pin a revision."
        )

377
378
379
380
    return os.path.join(full_submodule, module_file)


def get_class_from_dynamic_module(
381
    class_reference: str,
382
383
384
385
386
    pretrained_model_name_or_path: Union[str, os.PathLike],
    cache_dir: Optional[Union[str, os.PathLike]] = None,
    force_download: bool = False,
    resume_download: bool = False,
    proxies: Optional[Dict[str, str]] = None,
Yih-Dar's avatar
Yih-Dar committed
387
    token: Optional[Union[bool, str]] = None,
388
389
    revision: Optional[str] = None,
    local_files_only: bool = False,
Sylvain Gugger's avatar
Sylvain Gugger committed
390
    repo_type: Optional[str] = None,
391
    code_revision: Optional[str] = None,
392
    **kwargs,
393
) -> typing.Type:
394
395
396
397
398
399
400
401
402
403
    """
    Extracts a class from a module file, present in the local folder or repository of a model.

    <Tip warning={true}>

    Calling this function will execute the code in the module file found locally or downloaded from the Hub. It should
    therefore only be called on trusted repos.

    </Tip>

404
405


406
    Args:
407
408
        class_reference (`str`):
            The full name of the class to load, including its module and optionally its repo.
409
410
411
412
        pretrained_model_name_or_path (`str` or `os.PathLike`):
            This can be either:

            - a string, the *model id* of a pretrained model configuration hosted inside a model repo on
413
              huggingface.co.
414
415
416
            - a path to a *directory* containing a configuration file saved using the
              [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.

417
            This is used when `class_reference` does not specify another repo.
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
        module_file (`str`):
            The name of the module file containing the class to look for.
        class_name (`str`):
            The name of the class to import in the module.
        cache_dir (`str` or `os.PathLike`, *optional*):
            Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
            cache should not be used.
        force_download (`bool`, *optional*, defaults to `False`):
            Whether or not to force to (re-)download the configuration files and override the cached versions if they
            exist.
        resume_download (`bool`, *optional*, defaults to `False`):
            Whether or not to delete incompletely received file. Attempts to resume the download if such a file exists.
        proxies (`Dict[str, str]`, *optional*):
            A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
            'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
Yih-Dar's avatar
Yih-Dar committed
433
        token (`str` or `bool`, *optional*):
434
            The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
435
            when running `huggingface-cli login` (stored in `~/.huggingface`).
436
        revision (`str`, *optional*, defaults to `"main"`):
437
438
439
440
441
            The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
            git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
            identifier allowed by git.
        local_files_only (`bool`, *optional*, defaults to `False`):
            If `True`, will only try to load the tokenizer configuration from local files.
Sylvain Gugger's avatar
Sylvain Gugger committed
442
443
        repo_type (`str`, *optional*):
            Specify the repo type (useful when downloading from a space for instance).
444
445
446
447
        code_revision (`str`, *optional*, defaults to `"main"`):
            The specific revision to use for the code on the Hub, if the code leaves in a different repository than the
            rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for
            storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git.
448
449
450

    <Tip>

Yih-Dar's avatar
Yih-Dar committed
451
    Passing `token=True` is required when you want to use a private model.
452

453
454
455
    </Tip>

    Returns:
456
        `typing.Type`: The class, dynamically imported from the module.
457
458
459
460

    Examples:

    ```python
461
    # Download module `modeling.py` from huggingface.co and cache then extract the class `MyBertModel` from this
462
    # module.
463
464
465
466
467
    cls = get_class_from_dynamic_module("modeling.MyBertModel", "sgugger/my-bert-model")

    # Download module `modeling.py` from a given repo and cache then extract the class `MyBertModel` from this
    # module.
    cls = get_class_from_dynamic_module("sgugger/my-bert-model--modeling.MyBertModel", "sgugger/another-bert-model")
468
    ```"""
Yih-Dar's avatar
Yih-Dar committed
469
470
471
    use_auth_token = kwargs.pop("use_auth_token", None)
    if use_auth_token is not None:
        warnings.warn(
472
473
            "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
            FutureWarning,
Yih-Dar's avatar
Yih-Dar committed
474
475
476
477
478
        )
        if token is not None:
            raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
        token = use_auth_token

479
480
481
482
483
484
485
    # Catch the name of the repo if it's specified in `class_reference`
    if "--" in class_reference:
        repo_id, class_reference = class_reference.split("--")
    else:
        repo_id = pretrained_model_name_or_path
    module_file, class_name = class_reference.split(".")

486
487
    if code_revision is None and pretrained_model_name_or_path == repo_id:
        code_revision = revision
488
    # And lastly we get the class inside our newly created module
489
    final_module = get_cached_module_file(
490
491
        repo_id,
        module_file + ".py",
492
493
494
495
        cache_dir=cache_dir,
        force_download=force_download,
        resume_download=resume_download,
        proxies=proxies,
Yih-Dar's avatar
Yih-Dar committed
496
        token=token,
497
        revision=code_revision,
498
        local_files_only=local_files_only,
Sylvain Gugger's avatar
Sylvain Gugger committed
499
        repo_type=repo_type,
500
    )
501
    return get_class_in_module(class_name, final_module)
502
503


504
def custom_object_save(obj: Any, folder: Union[str, os.PathLike], config: Optional[Dict] = None) -> List[str]:
505
506
507
508
509
510
511
512
513
    """
    Save the modeling files corresponding to a custom model/configuration/tokenizer etc. in a given folder. Optionally
    adds the proper fields in a config.

    Args:
        obj (`Any`): The object for which to save the module files.
        folder (`str` or `os.PathLike`): The folder where to save.
        config (`PretrainedConfig` or dictionary, `optional`):
            A config in which to register the auto_map corresponding to this custom object.
514
515
516

    Returns:
        `List[str]`: The list of files saved.
517
518
519
520
521
522
523
    """
    if obj.__module__ == "__main__":
        logger.warning(
            f"We can't save the code defining {obj} in {folder} as it's been defined in __main__. You should put "
            "this code in a separate module so we can include it in the saved folder and make it easier to share via "
            "the Hub."
        )
Sylvain Gugger's avatar
Sylvain Gugger committed
524
        return
525
526

    def _set_auto_map_in_config(_config):
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
        module_name = obj.__class__.__module__
        last_module = module_name.split(".")[-1]
        full_name = f"{last_module}.{obj.__class__.__name__}"
        # Special handling for tokenizers
        if "Tokenizer" in full_name:
            slow_tokenizer_class = None
            fast_tokenizer_class = None
            if obj.__class__.__name__.endswith("Fast"):
                # Fast tokenizer: we have the fast tokenizer class and we may have the slow one has an attribute.
                fast_tokenizer_class = f"{last_module}.{obj.__class__.__name__}"
                if getattr(obj, "slow_tokenizer_class", None) is not None:
                    slow_tokenizer = getattr(obj, "slow_tokenizer_class")
                    slow_tok_module_name = slow_tokenizer.__module__
                    last_slow_tok_module = slow_tok_module_name.split(".")[-1]
                    slow_tokenizer_class = f"{last_slow_tok_module}.{slow_tokenizer.__name__}"
            else:
                # Slow tokenizer: no way to have the fast class
                slow_tokenizer_class = f"{last_module}.{obj.__class__.__name__}"

            full_name = (slow_tokenizer_class, fast_tokenizer_class)

548
549
550
551
552
553
        if isinstance(_config, dict):
            auto_map = _config.get("auto_map", {})
            auto_map[obj._auto_class] = full_name
            _config["auto_map"] = auto_map
        elif getattr(_config, "auto_map", None) is not None:
            _config.auto_map[obj._auto_class] = full_name
554
        else:
555
556
557
558
559
560
561
562
            _config.auto_map = {obj._auto_class: full_name}

    # Add object class to the config auto_map
    if isinstance(config, (list, tuple)):
        for cfg in config:
            _set_auto_map_in_config(cfg)
    elif config is not None:
        _set_auto_map_in_config(config)
563

Sylvain Gugger's avatar
Sylvain Gugger committed
564
    result = []
565
566
567
568
    # Copy module file to the output folder.
    object_file = sys.modules[obj.__module__].__file__
    dest_file = Path(folder) / (Path(object_file).name)
    shutil.copy(object_file, dest_file)
Sylvain Gugger's avatar
Sylvain Gugger committed
569
    result.append(dest_file)
570
571
572
573
574

    # Gather all relative imports recursively and make sure they are copied as well.
    for needed_file in get_relative_import_files(object_file):
        dest_file = Path(folder) / (Path(needed_file).name)
        shutil.copy(needed_file, dest_file)
Sylvain Gugger's avatar
Sylvain Gugger committed
575
576
577
        result.append(dest_file)

    return result
578
579
580
581


def _raise_timeout_error(signum, frame):
    raise ValueError(
582
        "Loading this model requires you to execute custom code contained in the model repository on your local "
583
        "machine. Please set the option `trust_remote_code=True` to permit loading of this model."
584
585
586
587
588
589
590
591
592
593
594
    )


TIME_OUT_REMOTE_CODE = 15


def resolve_trust_remote_code(trust_remote_code, model_name, has_local_code, has_remote_code):
    if trust_remote_code is None:
        if has_local_code:
            trust_remote_code = False
        elif has_remote_code and TIME_OUT_REMOTE_CODE > 0:
595
            prev_sig_handler = None
596
            try:
597
                prev_sig_handler = signal.signal(signal.SIGALRM, _raise_timeout_error)
598
599
600
                signal.alarm(TIME_OUT_REMOTE_CODE)
                while trust_remote_code is None:
                    answer = input(
601
                        f"The repository for {model_name} contains custom code which must be executed to correctly "
602
603
                        f"load the model. You can inspect the repository content at https://hf.co/{model_name}.\n"
                        f"You can avoid this prompt in future by passing the argument `trust_remote_code=True`.\n\n"
604
                        f"Do you wish to run the custom code? [y/N] "
605
606
607
608
609
610
                    )
                    if answer.lower() in ["yes", "y", "1"]:
                        trust_remote_code = True
                    elif answer.lower() in ["no", "n", "0", ""]:
                        trust_remote_code = False
                signal.alarm(0)
611
            except Exception:
612
613
                # OS which does not support signal.SIGALRM
                raise ValueError(
614
                    f"The repository for {model_name} contains custom code which must be executed to correctly "
615
                    f"load the model. You can inspect the repository content at https://hf.co/{model_name}.\n"
616
                    f"Please pass the argument `trust_remote_code=True` to allow custom code to be run."
617
                )
618
619
620
621
            finally:
                if prev_sig_handler is not None:
                    signal.signal(signal.SIGALRM, prev_sig_handler)
                    signal.alarm(0)
622
623
624
625
626
627
628
629
630
631
632
633
        elif has_remote_code:
            # For the CI which puts the timeout at 0
            _raise_timeout_error(None, None)

    if has_remote_code and not has_local_code and not trust_remote_code:
        raise ValueError(
            f"Loading {model_name} requires you to execute the configuration file in that"
            " repo on your local machine. Make sure you have read the code there to avoid malicious use, then"
            " set the option `trust_remote_code=True` to remove this error."
        )

    return trust_remote_code