Lightning-AI/pytorch-lightning · error · ModuleNotFoundError

`{type(self).__name__}.to_onnx(dynamo=True)` requires `onnxs

Error message

`{type(self).__name__}.to_onnx(dynamo=True)` requires `onnxscript` to be installed.

What it means

to_onnx(dynamo=True) uses the new torch.onnx.dynamo_export path, which is implemented via `onnxscript`. Lightning checks `_ONNXSCRIPT_AVAILABLE` and raises ModuleNotFoundError when dynamo export is requested but onnxscript is missing.

Source

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

            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)

        file_path = str(file_path) if isinstance(file_path, Path) else file_path
        # PyTorch (2.5) declares file_path to be str | PathLike[Any] | None, but

View on GitHub (pinned to 9fed5c27d2)

Solutions

  1. pip install onnxscript
  2. Or drop dynamo=True to use the legacy exporter (only needs `onnx`)
  3. Confirm version compatibility between torch, onnx, and onnxscript

Example fix

# before
model.to_onnx("m.onnx", x, dynamo=True)  # ModuleNotFoundError
# after
# pip install onnxscript
model.to_onnx("m.onnx", x, dynamo=True)
Defensive patterns

Strategy: validation

Validate before calling

import importlib.util
use_dynamo = importlib.util.find_spec("onnxscript") is not None
model.to_onnx(path, sample, dynamo=use_dynamo)

Try / catch

try:
    model.to_onnx(path, sample, dynamo=True)
except ModuleNotFoundError as e:
    if "onnxscript" in str(e):
        model.to_onnx(path, sample)  # legacy path
    else:
        raise

Prevention

When it happens

Trigger: Calling `model.to_onnx(path, sample, dynamo=True)` (or passing dynamo=True in kwargs) without `onnxscript` installed.

Common situations: Switching to the PyTorch 2.x dynamo-based ONNX exporter on an environment built for the legacy torch.onnx.export path.

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/4bc00efb0011eff6. Report an issue: GitHub.