2020-10-13 11:18:07 +00:00
|
|
|
# Copyright The PyTorch Lightning team.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
2020-07-31 10:27:57 +00:00
|
|
|
import os
|
2022-07-15 17:41:23 +00:00
|
|
|
from unittest.mock import patch
|
2020-07-31 10:27:57 +00:00
|
|
|
|
2020-08-06 14:58:51 +00:00
|
|
|
import numpy as np
|
2020-07-31 10:27:57 +00:00
|
|
|
import onnxruntime
|
|
|
|
import pytest
|
|
|
|
import torch
|
2020-08-06 14:58:51 +00:00
|
|
|
|
2022-06-15 22:10:49 +00:00
|
|
|
import tests_pytorch.helpers.pipelines as tpipes
|
2020-07-31 10:27:57 +00:00
|
|
|
from pytorch_lightning import Trainer
|
2022-06-14 23:53:54 +00:00
|
|
|
from pytorch_lightning.demos.boring_classes import BoringModel
|
2022-07-15 17:41:23 +00:00
|
|
|
from pytorch_lightning.utilities.imports import _TORCH_GREATER_EQUAL_1_12
|
2022-06-15 22:10:49 +00:00
|
|
|
from tests_pytorch.helpers.runif import RunIf
|
|
|
|
from tests_pytorch.utilities.test_model_summary import UnorderedModel
|
2020-07-31 10:27:57 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_model_saves_with_input_sample(tmpdir):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test that ONNX model saves with input sample and size is greater than 3 MB."""
|
2020-12-12 10:17:03 +00:00
|
|
|
model = BoringModel()
|
2021-02-11 14:32:07 +00:00
|
|
|
trainer = Trainer(fast_dev_run=True)
|
2020-07-31 10:27:57 +00:00
|
|
|
trainer.fit(model)
|
|
|
|
|
2020-08-26 16:22:19 +00:00
|
|
|
file_path = os.path.join(tmpdir, "model.onnx")
|
2020-12-12 10:17:03 +00:00
|
|
|
input_sample = torch.randn((1, 32))
|
2020-08-26 16:22:19 +00:00
|
|
|
model.to_onnx(file_path, input_sample)
|
|
|
|
assert os.path.isfile(file_path)
|
2020-12-12 10:17:03 +00:00
|
|
|
assert os.path.getsize(file_path) > 4e2
|
2020-08-26 16:22:19 +00:00
|
|
|
|
|
|
|
|
2022-06-24 12:15:48 +00:00
|
|
|
@pytest.mark.parametrize(
|
|
|
|
"accelerator", [pytest.param("mps", marks=RunIf(mps=True)), pytest.param("gpu", marks=RunIf(min_cuda_gpus=True))]
|
|
|
|
)
|
|
|
|
def test_model_saves_on_gpu(tmpdir, accelerator):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test that model saves on gpu."""
|
2020-12-12 10:17:03 +00:00
|
|
|
model = BoringModel()
|
2022-06-24 12:15:48 +00:00
|
|
|
trainer = Trainer(accelerator=accelerator, devices=1, fast_dev_run=True)
|
2020-08-26 16:22:19 +00:00
|
|
|
trainer.fit(model)
|
|
|
|
|
|
|
|
file_path = os.path.join(tmpdir, "model.onnx")
|
2020-12-12 10:17:03 +00:00
|
|
|
input_sample = torch.randn((1, 32))
|
2020-07-31 10:27:57 +00:00
|
|
|
model.to_onnx(file_path, input_sample)
|
|
|
|
assert os.path.isfile(file_path)
|
2020-12-12 10:17:03 +00:00
|
|
|
assert os.path.getsize(file_path) > 4e2
|
2020-07-31 10:27:57 +00:00
|
|
|
|
|
|
|
|
2021-09-02 01:36:20 +00:00
|
|
|
@pytest.mark.parametrize(
|
|
|
|
["modelclass", "input_sample"],
|
|
|
|
[
|
|
|
|
(BoringModel, torch.randn(1, 32)),
|
|
|
|
(UnorderedModel, (torch.rand(2, 3), torch.rand(2, 10))),
|
|
|
|
],
|
|
|
|
)
|
|
|
|
def test_model_saves_with_example_input_array(tmpdir, modelclass, input_sample):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test that ONNX model saves with example_input_array and size is greater than 3 MB."""
|
2021-09-02 01:36:20 +00:00
|
|
|
model = modelclass()
|
|
|
|
model.example_input_array = input_sample
|
2020-12-12 10:17:03 +00:00
|
|
|
|
2020-08-26 16:22:19 +00:00
|
|
|
file_path = os.path.join(tmpdir, "model.onnx")
|
2020-07-31 10:27:57 +00:00
|
|
|
model.to_onnx(file_path)
|
|
|
|
assert os.path.exists(file_path) is True
|
2020-12-12 10:17:03 +00:00
|
|
|
assert os.path.getsize(file_path) > 4e2
|
2020-07-31 10:27:57 +00:00
|
|
|
|
|
|
|
|
2022-05-24 12:54:05 +00:00
|
|
|
@RunIf(min_cuda_gpus=2)
|
2020-07-31 10:27:57 +00:00
|
|
|
def test_model_saves_on_multi_gpu(tmpdir):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test that ONNX model saves on a distributed backend."""
|
2020-07-31 10:27:57 +00:00
|
|
|
trainer_options = dict(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
max_epochs=1,
|
|
|
|
limit_train_batches=10,
|
|
|
|
limit_val_batches=10,
|
2022-03-26 14:38:57 +00:00
|
|
|
accelerator="gpu",
|
|
|
|
devices=[0, 1],
|
2021-10-16 15:10:25 +00:00
|
|
|
strategy="ddp_spawn",
|
2021-09-25 05:53:31 +00:00
|
|
|
enable_progress_bar=False,
|
2020-07-31 10:27:57 +00:00
|
|
|
)
|
|
|
|
|
2021-02-11 14:32:07 +00:00
|
|
|
model = BoringModel()
|
|
|
|
model.example_input_array = torch.randn(5, 32)
|
2020-07-31 10:27:57 +00:00
|
|
|
|
2021-02-11 14:32:07 +00:00
|
|
|
tpipes.run_model_test(trainer_options, model, min_acc=0.08)
|
2020-07-31 10:27:57 +00:00
|
|
|
|
2020-08-26 16:22:19 +00:00
|
|
|
file_path = os.path.join(tmpdir, "model.onnx")
|
2020-07-31 10:27:57 +00:00
|
|
|
model.to_onnx(file_path)
|
|
|
|
assert os.path.exists(file_path) is True
|
|
|
|
|
|
|
|
|
|
|
|
def test_verbose_param(tmpdir, capsys):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test that output is present when verbose parameter is set."""
|
2020-12-12 10:17:03 +00:00
|
|
|
model = BoringModel()
|
|
|
|
model.example_input_array = torch.randn(5, 32)
|
2020-08-26 16:22:19 +00:00
|
|
|
file_path = os.path.join(tmpdir, "model.onnx")
|
2022-07-15 17:41:23 +00:00
|
|
|
|
|
|
|
if _TORCH_GREATER_EQUAL_1_12:
|
|
|
|
with patch("torch.onnx.log", autospec=True) as test:
|
|
|
|
model.to_onnx(file_path, verbose=True)
|
|
|
|
args, kwargs = test.call_args
|
|
|
|
prefix, graph = args
|
|
|
|
assert prefix == "Exported graph: "
|
|
|
|
else:
|
|
|
|
model.to_onnx(file_path, verbose=True)
|
|
|
|
captured = capsys.readouterr()
|
|
|
|
assert "graph(%" in captured.out
|
2020-07-31 10:27:57 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_error_if_no_input(tmpdir):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test that an error is thrown when there is no input tensor."""
|
2020-12-12 10:17:03 +00:00
|
|
|
model = BoringModel()
|
2020-07-31 10:27:57 +00:00
|
|
|
model.example_input_array = None
|
2020-08-26 16:22:19 +00:00
|
|
|
file_path = os.path.join(tmpdir, "model.onnx")
|
2021-02-06 11:07:26 +00:00
|
|
|
with pytest.raises(
|
|
|
|
ValueError,
|
2021-07-26 11:37:35 +00:00
|
|
|
match=r"Could not export to ONNX since neither `input_sample` nor"
|
|
|
|
r" `model.example_input_array` attribute is set.",
|
2021-02-06 11:07:26 +00:00
|
|
|
):
|
2020-07-31 10:27:57 +00:00
|
|
|
model.to_onnx(file_path)
|
|
|
|
|
|
|
|
|
|
|
|
def test_if_inference_output_is_valid(tmpdir):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Test that the output inferred from ONNX model is same as from PyTorch."""
|
2020-12-12 10:17:03 +00:00
|
|
|
model = BoringModel()
|
|
|
|
model.example_input_array = torch.randn(5, 32)
|
|
|
|
|
2021-02-11 14:32:07 +00:00
|
|
|
trainer = Trainer(fast_dev_run=True)
|
2020-07-31 10:27:57 +00:00
|
|
|
trainer.fit(model)
|
|
|
|
|
|
|
|
model.eval()
|
|
|
|
with torch.no_grad():
|
|
|
|
torch_out = model(model.example_input_array)
|
|
|
|
|
2020-08-26 16:22:19 +00:00
|
|
|
file_path = os.path.join(tmpdir, "model.onnx")
|
2020-07-31 10:27:57 +00:00
|
|
|
model.to_onnx(file_path, model.example_input_array, export_params=True)
|
|
|
|
|
|
|
|
ort_session = onnxruntime.InferenceSession(file_path)
|
|
|
|
|
|
|
|
def to_numpy(tensor):
|
|
|
|
return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
|
|
|
|
|
|
|
|
# compute ONNX Runtime output prediction
|
|
|
|
ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(model.example_input_array)}
|
|
|
|
ort_outs = ort_session.run(None, ort_inputs)
|
|
|
|
|
|
|
|
# compare ONNX Runtime and PyTorch results
|
|
|
|
assert np.allclose(to_numpy(torch_out), ort_outs[0], rtol=1e-03, atol=1e-05)
|