huggingface/transformers · error · ImportError

This modeling file requires the following packages that were

Error message

This modeling file requires the following packages that were not found in your environment: {', '.join(missing_packages)}. Run `pip install {' '.join(missing_packages)}`

What it means

When transformers copies a remote (trust_remote_code) modeling file into its dynamic-module cache, it first imports the file's top-level dependencies. Dependencies that fail with 'No module named ...' are collected and reported as one ImportError naming all missing packages and the exact pip install command; other ImportErrors (broken dependency, not missing) are re-raised unchanged.

Source

Thrown at src/transformers/dynamic_module_utils.py:258

        `list[str]`: The list of relative imports in the file.
    """
    imports = get_imports(filename)
    missing_packages = []
    for imp in imports:
        try:
            importlib.import_module(imp)
        except ImportError as exception:
            logger.warning(f"Encountered exception while importing {imp}: {exception}")
            # Some packages can fail with an ImportError because of a dependency issue.
            # This check avoids hiding such errors.
            # See https://github.com/huggingface/transformers/issues/33604
            if "No module named" in str(exception):
                missing_packages.append(imp)
            else:
                raise

    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)}`"
        )

    return get_relative_imports(filename)


def get_class_in_module(
    class_name: str,
    module_path: str | os.PathLike,
    *,
    force_reload: bool = False,
) -> type:
    """
    Import a module on the cache directory for modules and extract a class from it.

    Args:
        class_name (`str`): The name of the class to import.

View on GitHub (pinned to a597f97485)

Solutions

  1. Run the pip install command shown verbatim in the message: pip install <packages>.
  2. Add those packages to your requirements/environment.yml so redeploys do not regress.
  3. If the install fails, check for version conflicts reported by pip.

Example fix

# before
AutoModel.from_pretrained("org/custom-model", trust_remote_code=True)  # ImportError: requires einops, tiktoken

# after
pip install einops tiktoken
AutoModel.from_pretrained("org/custom-model", trust_remote_code=True)
Defensive patterns

Strategy: try-catch

Validate before calling

def missing_pkgs(imports: list[str]) -> list[str]:
    import importlib.util
    return [m for m in imports if importlib.util.find_spec(m) is None]

Try / catch

try:
    AutoModel.from_pretrained(repo_id, trust_remote_code=True)
except ImportError as e:
    if "were not found in your environment" in str(e):
        pkgs = str(e).split('pip install ')[1].rstrip('.')
        subprocess.check_call([sys.executable, '-m', 'pip', 'install', *pkgs.split()])
        AutoModel.from_pretrained(repo_id, trust_remote_code=True)
    else:
        raise

Prevention

When it happens

Trigger: Loading a custom-code model (AutoModel.from_pretrained(some_community_model, trust_remote_code=True)) whose modeling .py imports e.g. einops, tiktoken, or sentencepiece that are absent from the current environment.

Common situations: New machine/venv without the model's extras; Colab notebooks missing einops; a model repo added a new dependency after you first used it.

Related errors


AI-assisted analysis of huggingface/transformers@a597f97485 (2026-08-14). Data as JSON: /api/errors/96d0a3d5ae0a46d6. Report an issue: GitHub.