Skip to content

Support pathlib.Path file paths when saving ONNX models #19727

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/lightning/pytorch/core/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -1395,7 +1395,7 @@ def forward(self, x):
input_sample = self._on_before_batch_transfer(input_sample)
input_sample = self._apply_batch_transfer_handler(input_sample)

torch.onnx.export(self, input_sample, file_path, **kwargs)
torch.onnx.export(self, input_sample, str(file_path), **kwargs)
self.train(mode)

@torch.no_grad()
Expand Down
15 changes: 15 additions & 0 deletions tests/tests_pytorch/models/test_onnx.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.
import operator
import os
from pathlib import Path
from unittest.mock import patch

import numpy as np
Expand Down Expand Up @@ -42,6 +43,20 @@ def test_model_saves_with_input_sample(tmp_path):
assert os.path.getsize(file_path) > 4e2


@RunIf(onnx=True)
def test_model_saves_with_pathlib_file_path(tmp_path):
"""Test that ONNX model saves with pathlib.Path file_path and size is greater than 3 MB."""
model = BoringModel()
trainer = Trainer(fast_dev_run=True)
trainer.fit(model)

file_path = Path(tmp_path) / "model.onnx"
input_sample = torch.randn((1, 32))
model.to_onnx(file_path, input_sample)
assert os.path.isfile(file_path)
assert os.path.getsize(file_path) > 4e2


@pytest.mark.parametrize(
"accelerator", [pytest.param("mps", marks=RunIf(mps=True)), pytest.param("gpu", marks=RunIf(min_cuda_gpus=True))]
)
Expand Down