Lightning-AI/pytorch-lightning · error · ModuleNotFoundError

`{type(self).__name__}.to_onnx()` requires `onnx` to be inst

Error message

`{type(self).__name__}.to_onnx()` requires `onnx` to be installed.

What it means

LightningModule.to_onnx() requires the `onnx` Python package to verify/save the exported model. The method checks the module-level flag `_ONNX_AVAILABLE` and raises ModuleNotFoundError if `onnx` is not importable, even though `torch.onnx.export` itself may work without it.

Source

Thrown at src/lightning/pytorch/core/module.py:1482

            **kwargs: Will be passed to torch.onnx.export function.

        Example::

            class SimpleModel(LightningModule):
                def __init__(self):
                    super().__init__()
                    self.l1 = torch.nn.Linear(in_features=64, out_features=4)

                def forward(self, x):
                    return torch.relu(self.l1(x.view(x.size(0), -1)

            model = SimpleModel()
            input_sample = torch.randn(1, 64)
            model.to_onnx("export.onnx", input_sample, export_params=True)

        """
        if not _ONNX_AVAILABLE:
            raise ModuleNotFoundError(f"`{type(self).__name__}.to_onnx()` requires `onnx` to be installed.")

        if kwargs.get("dynamo", False) and not _ONNXSCRIPT_AVAILABLE:
            raise ModuleNotFoundError(
                f"`{type(self).__name__}.to_onnx(dynamo=True)` requires `onnxscript` to be installed."
            )

        mode = self.training

        if input_sample is None:
            if self.example_input_array is None:
                raise ValueError(
                    "Could not export to ONNX since neither `input_sample` nor"
                    " `model.example_input_array` attribute is set."
                )
            input_sample = self.example_input_array

        input_sample = self._on_before_batch_transfer(input_sample)
        input_sample = self._apply_batch_transfer_handler(input_sample)

View on GitHub (pinned to 9fed5c27d2)

Solutions

  1. pip install onnx (or pip install lightning[extra] / pytorch-lightning[extra])
  2. Verify importability: python -c "import onnx"
  3. If you can't install onnx, export directly with torch.onnx.export(model, input_sample, path) instead

Example fix

# before
model.to_onnx("export.onnx", torch.randn(1, 64))  # ModuleNotFoundError
# after
# pip install onnx
model.to_onnx("export.onnx", torch.randn(1, 64))
Defensive patterns

Strategy: validation

Validate before calling

import importlib.util
if importlib.util.find_spec("onnx") is None:
    raise RuntimeError("Install onnx before export")
model.to_onnx(path, sample)

Try / catch

try:
    model.to_onnx(path, sample)
except ModuleNotFoundError as e:
    if "onnx" in str(e):
        torch.onnx.export(model, sample, path)  # fallback
    else:
        raise

Prevention

When it happens

Trigger: Calling `model.to_onnx(path, input_sample)` in an environment where `pip install onnx` was never run or the package failed to import.

Common situations: Running model export in a slim Docker image, CI, or a fresh conda env that only installed `lightning`/`pytorch-lightning` without the optional `onnx` extra.

Understand the failure class

Background: "X is not installed. Please install it with pip install Y": missing optional dependency errors — ImportError/ValueError raised when a library's optional extra was never installed — this error's family across 22 libraries.

Related errors


AI-assisted analysis of Lightning-AI/pytorch-lightning@9fed5c27d2 (2026-08-28). Data as JSON: /api/errors/991b0ad01da8e83a. Report an issue: GitHub.