dynamic_modules_utils.py 21.5 KB
Newer Older
patil-suraj's avatar
patil-suraj committed
1
# coding=utf-8
2
# Copyright 2025 The HuggingFace Inc. team.
patil-suraj's avatar
patil-suraj committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#
# 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.
"""Utilities to dynamically load objects from the Hub."""

import importlib
Patrick von Platen's avatar
Patrick von Platen committed
18
import inspect
19
import json
patil-suraj's avatar
patil-suraj committed
20
21
22
23
import os
import re
import shutil
import sys
YiYi Xu's avatar
YiYi Xu committed
24
import threading
patil-suraj's avatar
patil-suraj committed
25
from pathlib import Path
YiYi Xu's avatar
YiYi Xu committed
26
from types import ModuleType
patil-suraj's avatar
patil-suraj committed
27
from typing import Dict, Optional, Union
28
from urllib import request
patil-suraj's avatar
patil-suraj committed
29

30
31
from huggingface_hub import hf_hub_download, model_info
from huggingface_hub.utils import RevisionNotFoundError, validate_hf_hub_args
32
from packaging import version
Patrick von Platen's avatar
Patrick von Platen committed
33

34
35
from .. import __version__
from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging
36
from .constants import DIFFUSERS_DISABLE_REMOTE_CODE
patil-suraj's avatar
patil-suraj committed
37
38
39
40


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

41
42
# See https://huggingface.co/datasets/diffusers/community-pipelines-mirror
COMMUNITY_PIPELINES_MIRROR_ID = "diffusers/community-pipelines-mirror"
YiYi Xu's avatar
YiYi Xu committed
43
44
TIME_OUT_REMOTE_CODE = int(os.getenv("DIFFUSERS_TIMEOUT_REMOTE_CODE", 15))
_HF_REMOTE_CODE_LOCK = threading.Lock()
45

patil-suraj's avatar
patil-suraj committed
46

47
48
49
def get_diffusers_versions():
    url = "https://pypi.org/pypi/diffusers/json"
    releases = json.loads(request.urlopen(url).read())["releases"].keys()
50
    return sorted(releases, key=lambda x: version.Version(x))
51
52


patil-suraj's avatar
patil-suraj committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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()


def create_dynamic_module(name: Union[str, os.PathLike]):
    """
    Creates a dynamic module in the cache directory for modules.
    """
    init_hf_modules()
    dynamic_module_path = Path(HF_MODULES_CACHE) / name
    # 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()


def get_relative_imports(module_file):
    """
    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.
    """
    with open(module_file, "r", encoding="utf-8") as f:
        content = f.read()

    # Imports of the form `import .xxx`
94
    relative_imports = re.findall(r"^\s*import\s+\.(\S+)\s*$", content, flags=re.MULTILINE)
patil-suraj's avatar
patil-suraj committed
95
    # Imports of the form `from .xxx import yyy`
96
    relative_imports += re.findall(r"^\s*from\s+\.(\S+)\s+import", content, flags=re.MULTILINE)
patil-suraj's avatar
patil-suraj committed
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
    # Unique-ify
    return list(set(relative_imports))


def get_relative_import_files(module_file):
    """
    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.
    """
    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


def check_imports(filename):
    """
    Check if the current Python environment contains all the libraries that are imported in a file.
    """
    with open(filename, "r", encoding="utf-8") as f:
        content = f.read()

    # Imports of the form `import xxx`
138
    imports = re.findall(r"^\s*import\s+(\S+)\s*$", content, flags=re.MULTILINE)
patil-suraj's avatar
patil-suraj committed
139
    # Imports of the form `from xxx import yyy`
140
    imports += re.findall(r"^\s*from\s+(\S+)\s+import", content, flags=re.MULTILINE)
patil-suraj's avatar
patil-suraj committed
141
142
143
144
145
146
147
148
149
150
151
152
153
    # Only keep the top-level module
    imports = [imp.split(".")[0] for imp in imports if not imp.startswith(".")]

    # Unique-ify and test we got them all
    imports = list(set(imports))
    missing_packages = []
    for imp in imports:
        try:
            importlib.import_module(imp)
        except ImportError:
            missing_packages.append(imp)

    if len(missing_packages) > 0:
154
155
        logger.warning(
            "This modeling file might require the following packages that were not found in your environment: "
patil-suraj's avatar
patil-suraj committed
156
157
158
159
160
161
            f"{', '.join(missing_packages)}. Run `pip install {' '.join(missing_packages)}`"
        )

    return get_relative_imports(filename)


YiYi Xu's avatar
YiYi Xu committed
162
def resolve_trust_remote_code(trust_remote_code, model_name, has_remote_code):
163
164
165
166
167
    trust_remote_code = trust_remote_code and not DIFFUSERS_DISABLE_REMOTE_CODE
    if DIFFUSERS_DISABLE_REMOTE_CODE:
        logger.warning(
            "Downloading remote code is disabled globally via the DIFFUSERS_DISABLE_REMOTE_CODE environment variable. Ignoring `trust_remote_code`."
        )
YiYi Xu's avatar
YiYi Xu committed
168
169

    if has_remote_code and not trust_remote_code:
170
171
172
173
174
175
176
177
178
179
180
        error_msg = f"The repository for {model_name} contains custom code. "
        error_msg += (
            "Downloading remote code is disabled globally via the DIFFUSERS_DISABLE_REMOTE_CODE environment variable."
            if DIFFUSERS_DISABLE_REMOTE_CODE
            else "Pass `trust_remote_code=True` to allow loading remote code modules."
        )
        raise ValueError(error_msg)

    elif has_remote_code and trust_remote_code:
        logger.warning(
            f"`trust_remote_code` is enabled. Downloading code from {model_name}. Please ensure you trust the contents of this repository"
YiYi Xu's avatar
YiYi Xu committed
181
182
183
184
185
186
        )

    return trust_remote_code


def get_class_in_module(class_name, module_path, force_reload=False):
patil-suraj's avatar
patil-suraj committed
187
188
189
    """
    Import a module on the cache directory for modules and extract a class from it.
    """
YiYi Xu's avatar
YiYi Xu committed
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    name = os.path.normpath(module_path)
    if name.endswith(".py"):
        name = name[:-3]
    name = name.replace(os.path.sep, ".")
    module_file: Path = Path(HF_MODULES_CACHE) / module_path

    with _HF_REMOTE_CODE_LOCK:
        if force_reload:
            sys.modules.pop(name, None)
            importlib.invalidate_caches()
        cached_module: Optional[ModuleType] = sys.modules.get(name)
        module_spec = importlib.util.spec_from_file_location(name, location=module_file)

        module: ModuleType
        if cached_module is None:
            module = importlib.util.module_from_spec(module_spec)
            # insert it into sys.modules before any loading begins
            sys.modules[name] = module
        else:
            module = cached_module
210

YiYi Xu's avatar
YiYi Xu committed
211
        module_spec.loader.exec_module(module)
Patrick von Platen's avatar
Patrick von Platen committed
212
213
214

    if class_name is None:
        return find_pipeline_class(module)
YiYi Xu's avatar
YiYi Xu committed
215

patil-suraj's avatar
patil-suraj committed
216
217
218
    return getattr(module, class_name)


Patrick von Platen's avatar
Patrick von Platen committed
219
220
221
222
223
def find_pipeline_class(loaded_module):
    """
    Retrieve pipeline class that inherits from `DiffusionPipeline`. Note that there has to be exactly one class
    inheriting from `DiffusionPipeline`.
    """
224
    from ..pipelines import DiffusionPipeline
Patrick von Platen's avatar
Patrick von Platen committed
225
226
227
228
229

    cls_members = dict(inspect.getmembers(loaded_module, inspect.isclass))

    pipeline_class = None
    for cls_name, cls in cls_members.items():
230
231
232
233
234
        if (
            cls_name != DiffusionPipeline.__name__
            and issubclass(cls, DiffusionPipeline)
            and cls.__module__.split(".")[0] != "diffusers"
        ):
Patrick von Platen's avatar
Patrick von Platen committed
235
236
237
238
239
240
241
242
243
244
245
            if pipeline_class is not None:
                raise ValueError(
                    f"Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:"
                    f" {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in"
                    f" {loaded_module}."
                )
            pipeline_class = cls

    return pipeline_class


246
@validate_hf_hub_args
patil-suraj's avatar
patil-suraj committed
247
248
249
def get_cached_module_file(
    pretrained_model_name_or_path: Union[str, os.PathLike],
    module_file: str,
250
    subfolder: Optional[str] = None,
patil-suraj's avatar
patil-suraj committed
251
252
253
    cache_dir: Optional[Union[str, os.PathLike]] = None,
    force_download: bool = False,
    proxies: Optional[Dict[str, str]] = None,
254
    token: Optional[Union[bool, str]] = None,
patil-suraj's avatar
patil-suraj committed
255
256
    revision: Optional[str] = None,
    local_files_only: bool = False,
257
    local_dir: Optional[str] = None,
patil-suraj's avatar
patil-suraj committed
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
):
    """
    Prepares Downloads a module from a local folder or a distant repo and returns its path inside the cached
    Transformers module.

    Args:
        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
              huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced
              under a user or organization name, like `dbmdz/bert-base-german-cased`.
            - a path to a *directory* containing a configuration file saved using the
              [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.

        module_file (`str`):
            The name of the module file containing the class to look for.
        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
280
            exist.
patil-suraj's avatar
patil-suraj committed
281
282
283
        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.
284
        token (`str` or *bool*, *optional*):
patil-suraj's avatar
patil-suraj committed
285
286
287
288
289
290
291
292
293
            The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
            when running `transformers-cli login` (stored in `~/.huggingface`).
        revision (`str`, *optional*, defaults to `"main"`):
            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.

Steven Liu's avatar
Steven Liu committed
294
295
    > [!TIP] > You may pass a token in `token` if you are not logged in (`hf auth login`) and want to use private or
    [gated > models](https://huggingface.co/docs/hub/models-gated#gated-models).
patil-suraj's avatar
patil-suraj committed
296
297
298
299
300
301

    Returns:
        `str`: The path to the module inside the cache.
    """
    # 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)
Patrick von Platen's avatar
Patrick von Platen committed
302

patil-suraj's avatar
patil-suraj committed
303
304
    module_file_or_url = os.path.join(pretrained_model_name_or_path, module_file)

Patrick von Platen's avatar
Patrick von Platen committed
305
306
    if os.path.isfile(module_file_or_url):
        resolved_module_file = module_file_or_url
Patrick von Platen's avatar
Patrick von Platen committed
307
308
        submodule = "local"
    elif pretrained_model_name_or_path.count("/") == 0:
309
310
311
312
313
314
        available_versions = get_diffusers_versions()
        # cut ".dev0"
        latest_version = "v" + ".".join(__version__.split(".")[:3])

        # retrieve github version that matches
        if revision is None:
315
            revision = latest_version if latest_version[1:] in available_versions else "main"
316
317
318
319
320
321
322
323
324
325
326
            logger.info(f"Defaulting to latest_version: {revision}.")
        elif revision in available_versions:
            revision = f"v{revision}"
        elif revision == "main":
            revision = revision
        else:
            raise ValueError(
                f"`custom_revision`: {revision} does not exist. Please make sure to choose one of"
                f" {', '.join(available_versions + ['main'])}."
            )

Patrick von Platen's avatar
Patrick von Platen committed
327
        try:
328
329
330
331
            resolved_module_file = hf_hub_download(
                repo_id=COMMUNITY_PIPELINES_MIRROR_ID,
                repo_type="dataset",
                filename=f"{revision}/{pretrained_model_name_or_path}.py",
Patrick von Platen's avatar
Patrick von Platen committed
332
333
334
335
                cache_dir=cache_dir,
                force_download=force_download,
                proxies=proxies,
                local_files_only=local_files_only,
336
                local_dir=local_dir,
Patrick von Platen's avatar
Patrick von Platen committed
337
            )
338
339
            submodule = "git"
            module_file = pretrained_model_name_or_path + ".py"
340
341
342
343
344
345
        except RevisionNotFoundError as e:
            raise EnvironmentError(
                f"Revision '{revision}' not found in the community pipelines mirror. Check available revisions on"
                " https://huggingface.co/datasets/diffusers/community-pipelines-mirror/tree/main."
                " If you don't find the revision you are looking for, please open an issue on https://github.com/huggingface/diffusers/issues."
            ) from e
Patrick von Platen's avatar
Patrick von Platen committed
346
347
348
        except EnvironmentError:
            logger.error(f"Could not locate the {module_file} inside {pretrained_model_name_or_path}.")
            raise
Patrick von Platen's avatar
Patrick von Platen committed
349
350
351
    else:
        try:
            # Load from URL or cache if already cached
Patrick von Platen's avatar
Patrick von Platen committed
352
353
354
            resolved_module_file = hf_hub_download(
                pretrained_model_name_or_path,
                module_file,
355
                subfolder=subfolder,
Patrick von Platen's avatar
Patrick von Platen committed
356
357
358
359
                cache_dir=cache_dir,
                force_download=force_download,
                proxies=proxies,
                local_files_only=local_files_only,
360
                local_dir=local_dir,
361
                revision=revision,
362
                token=token,
Patrick von Platen's avatar
Patrick von Platen committed
363
            )
Patrick von Platen's avatar
Patrick von Platen committed
364
            submodule = os.path.join("local", "--".join(pretrained_model_name_or_path.split("/")))
Patrick von Platen's avatar
Patrick von Platen committed
365
366
367
        except EnvironmentError:
            logger.error(f"Could not locate the {module_file} inside {pretrained_model_name_or_path}.")
            raise
patil-suraj's avatar
patil-suraj committed
368
369
370
371
372

    # Check we have all the requirements in our environment
    modules_needed = check_imports(resolved_module_file)

    # Now we move the module inside our cached dynamic modules.
373
    full_submodule = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
patil-suraj's avatar
patil-suraj committed
374
375
    create_dynamic_module(full_submodule)
    submodule_path = Path(HF_MODULES_CACHE) / full_submodule
376
    if submodule == "local" or submodule == "git":
Patrick von Platen's avatar
Patrick von Platen committed
377
378
379
        # We always copy local files (we could hash the file to see if there was a change, and give them the name of
        # that hash, to only copy when there is a modification but it seems overkill for now).
        # The only reason we do the copy is to avoid putting too many folders in sys.path.
380
        shutil.copyfile(resolved_module_file, submodule_path / module_file)
Patrick von Platen's avatar
Patrick von Platen committed
381
        for module_needed in modules_needed:
382
383
384
385
386
            if len(module_needed.split(".")) == 2:
                module_needed = "/".join(module_needed.split("."))
                module_folder = module_needed.split("/")[0]
                if not os.path.exists(submodule_path / module_folder):
                    os.makedirs(submodule_path / module_folder)
Patrick von Platen's avatar
Patrick von Platen committed
387
            module_needed = f"{module_needed}.py"
388
            shutil.copyfile(os.path.join(pretrained_model_name_or_path, module_needed), submodule_path / module_needed)
Patrick von Platen's avatar
Patrick von Platen committed
389
390
391
392
393
394
395
396
397
398
399
400
    else:
        # Get the commit hash
        # TODO: we will get this info in the etag soon, so retrieve it from there and not here.
        commit_hash = model_info(pretrained_model_name_or_path, revision=revision, token=token).sha

        # 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():
401
402
403
404
            if len(module_file.split("/")) == 2:
                module_folder = module_file.split("/")[0]
                if not os.path.exists(submodule_path / module_folder):
                    os.makedirs(submodule_path / module_folder)
405
            shutil.copyfile(resolved_module_file, submodule_path / module_file)
406

Patrick von Platen's avatar
Patrick von Platen committed
407
408
        # Make sure we also have every file with relative
        for module_needed in modules_needed:
409
410
            if len(module_needed.split(".")) == 2:
                module_needed = "/".join(module_needed.split("."))
Patrick von Platen's avatar
Patrick von Platen committed
411
412
413
414
            if not (submodule_path / module_needed).exists():
                get_cached_module_file(
                    pretrained_model_name_or_path,
                    f"{module_needed}.py",
415
                    subfolder=subfolder,
Patrick von Platen's avatar
Patrick von Platen committed
416
417
418
                    cache_dir=cache_dir,
                    force_download=force_download,
                    proxies=proxies,
419
                    token=token,
Patrick von Platen's avatar
Patrick von Platen committed
420
421
                    revision=revision,
                    local_files_only=local_files_only,
422
                    local_dir=local_dir,
Patrick von Platen's avatar
Patrick von Platen committed
423
                )
patil-suraj's avatar
patil-suraj committed
424
425
426
    return os.path.join(full_submodule, module_file)


427
@validate_hf_hub_args
patil-suraj's avatar
patil-suraj committed
428
429
430
def get_class_from_dynamic_module(
    pretrained_model_name_or_path: Union[str, os.PathLike],
    module_file: str,
431
    subfolder: Optional[str] = None,
Patrick von Platen's avatar
Patrick von Platen committed
432
    class_name: Optional[str] = None,
patil-suraj's avatar
patil-suraj committed
433
434
435
    cache_dir: Optional[Union[str, os.PathLike]] = None,
    force_download: bool = False,
    proxies: Optional[Dict[str, str]] = None,
436
    token: Optional[Union[bool, str]] = None,
patil-suraj's avatar
patil-suraj committed
437
438
    revision: Optional[str] = None,
    local_files_only: bool = False,
439
    local_dir: Optional[str] = None,
patil-suraj's avatar
patil-suraj committed
440
441
442
443
):
    """
    Extracts a class from a module file, present in the local folder or repository of a model.

Steven Liu's avatar
Steven Liu committed
444
445
    > [!WARNING] > 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.
patil-suraj's avatar
patil-suraj committed
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469

    Args:
        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
              huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced
              under a user or organization name, like `dbmdz/bert-base-german-cased`.
            - a path to a *directory* containing a configuration file saved using the
              [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.

        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.
        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.
470
        token (`str` or `bool`, *optional*):
patil-suraj's avatar
patil-suraj committed
471
472
473
474
475
476
477
478
479
            The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
            when running `transformers-cli login` (stored in `~/.huggingface`).
        revision (`str`, *optional*, defaults to `"main"`):
            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.

Steven Liu's avatar
Steven Liu committed
480
481
    > [!TIP] > You may pass a token in `token` if you are not logged in (`hf auth login`) and want to use private or
    [gated > models](https://huggingface.co/docs/hub/models-gated#gated-models).
patil-suraj's avatar
patil-suraj committed
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496

    Returns:
        `type`: The class, dynamically imported from the module.

    Examples:

    ```python
    # Download module `modeling.py` from huggingface.co and cache then extract the class `MyBertModel` from this
    # module.
    cls = get_class_from_dynamic_module("sgugger/my-bert-model", "modeling.py", "MyBertModel")
    ```"""
    # And lastly we get the class inside our newly created module
    final_module = get_cached_module_file(
        pretrained_model_name_or_path,
        module_file,
497
        subfolder=subfolder,
patil-suraj's avatar
patil-suraj committed
498
499
500
        cache_dir=cache_dir,
        force_download=force_download,
        proxies=proxies,
501
        token=token,
patil-suraj's avatar
patil-suraj committed
502
503
        revision=revision,
        local_files_only=local_files_only,
504
        local_dir=local_dir,
patil-suraj's avatar
patil-suraj committed
505
    )
YiYi Xu's avatar
YiYi Xu committed
506
    return get_class_in_module(class_name, final_module)