{"record":{"id":"991b0ad01da8e83a","repo":"Lightning-AI/pytorch-lightning","slug":"type-self-name-to-onnx-requires-onnx","errorCode":null,"errorMessage":"`{type(self).__name__}.to_onnx()` requires `onnx` to be installed.","messagePattern":"`(.+?)\\.to_onnx\\(\\)` requires `onnx` to be installed\\.","errorType":"exception","errorClass":"ModuleNotFoundError","httpStatus":null,"severity":"error","filePath":"src/lightning/pytorch/core/module.py","lineNumber":1482,"sourceCode":"            **kwargs: Will be passed to torch.onnx.export function.\n\n        Example::\n\n            class SimpleModel(LightningModule):\n                def __init__(self):\n                    super().__init__()\n                    self.l1 = torch.nn.Linear(in_features=64, out_features=4)\n\n                def forward(self, x):\n                    return torch.relu(self.l1(x.view(x.size(0), -1)\n\n            model = SimpleModel()\n            input_sample = torch.randn(1, 64)\n            model.to_onnx(\"export.onnx\", input_sample, export_params=True)\n\n        \"\"\"\n        if not _ONNX_AVAILABLE:\n            raise ModuleNotFoundError(f\"`{type(self).__name__}.to_onnx()` requires `onnx` to be installed.\")\n\n        if kwargs.get(\"dynamo\", False) and not _ONNXSCRIPT_AVAILABLE:\n            raise ModuleNotFoundError(\n                f\"`{type(self).__name__}.to_onnx(dynamo=True)` requires `onnxscript` to be installed.\"\n            )\n\n        mode = self.training\n\n        if input_sample is None:\n            if self.example_input_array is None:\n                raise ValueError(\n                    \"Could not export to ONNX since neither `input_sample` nor\"\n                    \" `model.example_input_array` attribute is set.\"\n                )\n            input_sample = self.example_input_array\n\n        input_sample = self._on_before_batch_transfer(input_sample)\n        input_sample = self._apply_batch_transfer_handler(input_sample)","sourceCodeStart":1464,"sourceCodeEnd":1500,"githubUrl":"https://github.com/Lightning-AI/pytorch-lightning/blob/9fed5c27d2a62ff0efd6c3573599921d6ff67c14/src/lightning/pytorch/core/module.py#L1464-L1500","documentation":"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.","triggerScenarios":"Calling `model.to_onnx(path, input_sample)` in an environment where `pip install onnx` was never run or the package failed to import.","commonSituations":"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.","solutions":["pip install onnx (or pip install lightning[extra] / pytorch-lightning[extra])","Verify importability: python -c \"import onnx\"","If you can't install onnx, export directly with torch.onnx.export(model, input_sample, path) instead"],"exampleFix":"# before\nmodel.to_onnx(\"export.onnx\", torch.randn(1, 64))  # ModuleNotFoundError\n# after\n# pip install onnx\nmodel.to_onnx(\"export.onnx\", torch.randn(1, 64))","handlingStrategy":"validation","validationCode":"import importlib.util\nif importlib.util.find_spec(\"onnx\") is None:\n    raise RuntimeError(\"Install onnx before export\")\nmodel.to_onnx(path, sample)","typeGuard":null,"tryCatchPattern":"try:\n    model.to_onnx(path, sample)\nexcept ModuleNotFoundError as e:\n    if \"onnx\" in str(e):\n        torch.onnx.export(model, sample, path)  # fallback\n    else:\n        raise","preventionTips":["Include `onnx` in your export environment requirements","Add a smoke test that runs to_onnx in CI"],"tags":["onnx","export","missing-dependency","lightning"],"backgroundTag":"missing-optional-dependency","analyzedSha":"9fed5c27d2a62ff0efd6c3573599921d6ff67c14","analyzedAt":"2026-08-28T11:52:41.083Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}