def test_if_inference_output_is_valid(tmpdir): """Test that the output inferred from ONNX model is same as from PyTorch.""" model = BoringModel() model.example_input_array = torch.randn(5, 32) trainer = Trainer(fast_dev_run=True) trainer.fit(model) model.eval() with torch.no_grad(): torch_out = model(model.example_input_array) file_path = os.path.join(tmpdir, "model.onnx") 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)
def test_tensorboard_log_graph(tmpdir, example_input_array): """test that log graph works with both model.example_input_array and if array is passed externally.""" model = BoringModel() if example_input_array is not None: model.example_input_array = None logger = TensorBoardLogger(tmpdir, log_graph=True) logger.log_graph(model, example_input_array)
def test_torchscript_device(device_str): """Test that scripted module is on the correct device.""" device = torch.device(device_str) model = BoringModel().to(device) model.example_input_array = torch.randn(5, 32) script = model.to_torchscript() assert next(script.parameters()).device == device script_output = script(model.example_input_array.to(device)) assert script_output.device == device
def test_torchscript_with_no_input(tmpdir): """Test that an error is thrown when there is no input tensor.""" model = BoringModel() model.example_input_array = None with pytest.raises( ValueError, match= "requires either `example_inputs` or `model.example_input_array`"): model.to_torchscript(method="trace")
def test_error_if_no_input(tmpdir): """Test that an error is thrown when there is no input tensor.""" model = BoringModel() model.example_input_array = None file_path = os.path.join(tmpdir, "model.onnx") with pytest.raises( ValueError, match=r"Could not export to ONNX since neither `input_sample` nor" r" `model.example_input_array` attribute is set.", ): model.to_onnx(file_path)
def test_tensorboard_log_graph_warning_no_example_input_array(tmpdir): """test that log graph throws warning if model.example_input_array is None.""" model = BoringModel() model.example_input_array = None logger = TensorBoardLogger(tmpdir, log_graph=True) with pytest.warns( UserWarning, match= "Could not log computational graph since the `model.example_input_array`" " attribute is not set or `input_array` was not given", ): logger.log_graph(model)
def test_verbose_param(tmpdir, capsys): """Test that output is present when verbose parameter is set.""" model = BoringModel() model.example_input_array = torch.randn(5, 32) file_path = os.path.join(tmpdir, "model.onnx") 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
def test_model_saves_on_multi_gpu(tmpdir): """Test that ONNX model saves on a distributed backend.""" tutils.set_random_main_port() trainer_options = dict( default_root_dir=tmpdir, max_epochs=1, limit_train_batches=10, limit_val_batches=10, accelerator="gpu", devices=[0, 1], strategy="ddp_spawn", enable_progress_bar=False, ) model = BoringModel() model.example_input_array = torch.randn(5, 32) tpipes.run_model_test(trainer_options, model, min_acc=0.08) file_path = os.path.join(tmpdir, "model.onnx") model.to_onnx(file_path) assert os.path.exists(file_path) is True