|
| 1 | +import os |
| 2 | + |
| 3 | +import onnxruntime |
| 4 | +import pytest |
| 5 | +import torch |
| 6 | +import numpy as np |
| 7 | +import tests.base.develop_pipelines as tpipes |
| 8 | +import tests.base.develop_utils as tutils |
| 9 | +from pytorch_lightning import Trainer |
| 10 | +from tests.base import EvalModelTemplate |
| 11 | + |
| 12 | + |
| 13 | +def test_model_saves_with_input_sample(tmpdir): |
| 14 | + """Test that ONNX model saves with input sample and size is greater than 3 MB""" |
| 15 | + model = EvalModelTemplate() |
| 16 | + trainer = Trainer(max_epochs=1) |
| 17 | + trainer.fit(model) |
| 18 | + |
| 19 | + file_path = os.path.join(tmpdir, "model.onxx") |
| 20 | + input_sample = torch.randn((1, 28 * 28)) |
| 21 | + model.to_onnx(file_path, input_sample) |
| 22 | + assert os.path.isfile(file_path) |
| 23 | + assert os.path.getsize(file_path) > 3e+06 |
| 24 | + |
| 25 | + |
| 26 | +def test_model_saves_with_example_output(tmpdir): |
| 27 | + """Test that ONNX model saves when provided with example output""" |
| 28 | + model = EvalModelTemplate() |
| 29 | + trainer = Trainer(max_epochs=1) |
| 30 | + trainer.fit(model) |
| 31 | + |
| 32 | + file_path = os.path.join(tmpdir, "model.onxx") |
| 33 | + input_sample = torch.randn((1, 28 * 28)) |
| 34 | + model.eval() |
| 35 | + example_outputs = model.forward(input_sample) |
| 36 | + model.to_onnx(file_path, input_sample, example_outputs=example_outputs) |
| 37 | + assert os.path.exists(file_path) is True |
| 38 | + |
| 39 | + |
| 40 | +def test_model_saves_with_example_input_array(tmpdir): |
| 41 | + """Test that ONNX model saves with_example_input_array and size is greater than 3 MB""" |
| 42 | + model = EvalModelTemplate() |
| 43 | + file_path = os.path.join(tmpdir, "model.onxx") |
| 44 | + model.to_onnx(file_path) |
| 45 | + assert os.path.exists(file_path) is True |
| 46 | + assert os.path.getsize(file_path) > 3e+06 |
| 47 | + |
| 48 | + |
| 49 | +@pytest.mark.skipif(torch.cuda.device_count() < 2, reason="test requires multi-GPU machine") |
| 50 | +def test_model_saves_on_multi_gpu(tmpdir): |
| 51 | + """Test that ONNX model saves on a distributed backend""" |
| 52 | + tutils.set_random_master_port() |
| 53 | + |
| 54 | + trainer_options = dict( |
| 55 | + default_root_dir=tmpdir, |
| 56 | + max_epochs=1, |
| 57 | + limit_train_batches=10, |
| 58 | + limit_val_batches=10, |
| 59 | + gpus=[0, 1], |
| 60 | + distributed_backend='ddp_spawn', |
| 61 | + progress_bar_refresh_rate=0 |
| 62 | + ) |
| 63 | + |
| 64 | + model = EvalModelTemplate() |
| 65 | + |
| 66 | + tpipes.run_model_test(trainer_options, model) |
| 67 | + |
| 68 | + file_path = os.path.join(tmpdir, "model.onxx") |
| 69 | + model.to_onnx(file_path) |
| 70 | + assert os.path.exists(file_path) is True |
| 71 | + |
| 72 | + |
| 73 | +def test_verbose_param(tmpdir, capsys): |
| 74 | + """Test that output is present when verbose parameter is set""" |
| 75 | + model = EvalModelTemplate() |
| 76 | + file_path = os.path.join(tmpdir, "model.onxx") |
| 77 | + model.to_onnx(file_path, verbose=True) |
| 78 | + captured = capsys.readouterr() |
| 79 | + assert "graph(%" in captured.out |
| 80 | + |
| 81 | + |
| 82 | +def test_error_if_no_input(tmpdir): |
| 83 | + """Test that an exception is thrown when there is no input tensor""" |
| 84 | + model = EvalModelTemplate() |
| 85 | + model.example_input_array = None |
| 86 | + file_path = os.path.join(tmpdir, "model.onxx") |
| 87 | + with pytest.raises(ValueError, match=r'input_sample and example_input_array tensors are both missing'): |
| 88 | + model.to_onnx(file_path) |
| 89 | + |
| 90 | + |
| 91 | +def test_if_inference_output_is_valid(tmpdir): |
| 92 | + """Test that the output inferred from ONNX model is same as from PyTorch""" |
| 93 | + model = EvalModelTemplate() |
| 94 | + trainer = Trainer(max_epochs=5) |
| 95 | + trainer.fit(model) |
| 96 | + |
| 97 | + model.eval() |
| 98 | + with torch.no_grad(): |
| 99 | + torch_out = model(model.example_input_array) |
| 100 | + |
| 101 | + file_path = os.path.join(tmpdir, "model.onxx") |
| 102 | + model.to_onnx(file_path, model.example_input_array, export_params=True) |
| 103 | + |
| 104 | + ort_session = onnxruntime.InferenceSession(file_path) |
| 105 | + |
| 106 | + def to_numpy(tensor): |
| 107 | + return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy() |
| 108 | + |
| 109 | + # compute ONNX Runtime output prediction |
| 110 | + ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(model.example_input_array)} |
| 111 | + ort_outs = ort_session.run(None, ort_inputs) |
| 112 | + |
| 113 | + # compare ONNX Runtime and PyTorch results |
| 114 | + assert np.allclose(to_numpy(torch_out), ort_outs[0], rtol=1e-03, atol=1e-05) |
0 commit comments