Skip to content

Commit

Permalink
Support pathlib.Path file paths when saving ONNX models (#19727)
Browse files Browse the repository at this point in the history
Co-authored-by: dominicgkerr <dominicgkerr1@gmail.co>
  • Loading branch information
dominicgkerr and dominicgkerr committed Apr 4, 2024
1 parent ce88483 commit 76b691d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/lightning/pytorch/core/module.py
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
12 changes: 8 additions & 4 deletions tests/tests_pytorch/models/test_onnx.py
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 All @@ -32,11 +33,14 @@
def test_model_saves_with_input_sample(tmp_path):
"""Test that ONNX model saves with input sample and size is greater than 3 MB."""
model = BoringModel()
trainer = Trainer(fast_dev_run=True)
trainer.fit(model)

file_path = os.path.join(tmp_path, "model.onnx")
input_sample = torch.randn((1, 32))

file_path = os.path.join(tmp_path, "os.path.onnx")
model.to_onnx(file_path, input_sample)
assert os.path.isfile(file_path)
assert os.path.getsize(file_path) > 4e2

file_path = Path(tmp_path) / "pathlib.onnx"
model.to_onnx(file_path, input_sample)
assert os.path.isfile(file_path)
assert os.path.getsize(file_path) > 4e2
Expand Down

0 comments on commit 76b691d

Please sign in to comment.