OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[PyTorch] Update TorchBench tests and add export coverage (#38559)
Maxim Vafin03916107a8c6
diff --git a/.github/workflows/job_pytorch_models_tests.yml b/.github/workflows/job_pytorch_models_tests.ymlindex d99afb5dcdd..7ab99052a27 100644--- a/.github/workflows/job_pytorch_models_tests.yml+++ b/.github/workflows/job_pytorch_models_tests.yml@@ -175,6 +175,8 @@ jobs:- name: PyTorch Torchbench Testsif: ${{ inputs.model_scope == 'nightly_scope2' }}run: |+ # kernels from LLM tests requires a newer huggingface-hub than TorchBench's transformers.+ python3 -m pip uninstall -y kernelsexport PYTHONPATH=${MODEL_HUB_TESTS_INSTALL_DIR}:$PYTHONPATHpython3 -m pytest ${MODEL_HUB_TESTS_INSTALL_DIR}/pytorch/test_torchbench.py -m nightly --html=${INSTALL_TEST_DIR}/TEST-torch_model_torchbench_nightly_tests.html --self-contained-html -venv:diff --git a/tests/model_hub_tests/pytorch/test_torchbench.py b/tests/model_hub_tests/pytorch/test_torchbench.pyindex 9961e434d7c..e54ddffbfe2 100644--- a/tests/model_hub_tests/pytorch/test_torchbench.py+++ b/tests/model_hub_tests/pytorch/test_torchbench.py@@ -2,12 +2,14 @@# SPDX-License-Identifier: Apache-2.0import os-import sysimport subprocess+import sys+import tempfile+import pytestimport torch-import tempfile-from torch_utils import process_pytest_marks, get_models_list, TestTorchConvertModel++from torch_utils import get_models_list, TestTorchConvertModel# To make tests reproducible we seed the random generator@@ -15,22 +17,18 @@ torch.manual_seed(0)class TestTorchbenchmarkConvertModel(TestTorchConvertModel):+ infer_timeout = 800_model_list_path = os.path.join(os.path.dirname(__file__), "torchbench_models")def setup_class(self):super().setup_class(self)- # sd model doesn't need token but torchbench need it to be specified- os.environ['HUGGING_FACE_HUB_TOKEN'] = 'x'- torch.set_grad_enabled(False)-- self.infer_timeout = 800-+ self.installed_models = set()self.repo_dir = tempfile.TemporaryDirectory()- os.system(- f"git clone https://github.com/pytorch/benchmark.git {self.repo_dir.name}")+ subprocess.check_call([+ "git", "clone", "https://github.com/pytorch/benchmark.git", self.repo_dir.name])subprocess.check_call(- ["git", "checkout", "364420aeca07d9519840a5b6e771035e4dff9d72"], cwd=self.repo_dir.name)+ ["git", "checkout", "88e8837b7323627eb874dedff0c3e4e494d36ff8"], cwd=self.repo_dir.name)# torchaudio has no builds for recent torch and tested models don't need itdeps_file = os.path.join(self.repo_dir.name, "utils", "__init__.py")with open(deps_file) as f:@@ -47,33 +45,47 @@ class TestTorchbenchmarkConvertModel(TestTorchConvertModel):# build legacy setup.py packages in isolation, so setuptools plugins from the test env# (e.g. kernels egg_info writer) are not loadedos.environ["PIP_USE_PEP517"] = "1"+ sys.path.insert(0, self.repo_dir.name)def load_model(self, model_name, model_link):- subprocess.check_call([sys.executable, "install.py"] + [model_name], cwd=self.repo_dir.name)- sys.path.append(self.repo_dir.name)import numpy as npif int(np.__version__.split(".")[0]) >= 2:# maml inputs are pickled with numpy<2 path, which weights_only load doesn't map to numpy._coretorch.serialization.add_safe_globals([(np._core.multiarray._reconstruct, "numpy.core.multiarray._reconstruct")])from torchbenchmark import load_model_by_name- try:- model_cls = load_model_by_name(- model_name)("eval", "cpu", jit=False)- except TypeError:- model_cls = load_model_by_name(model_name)("eval", "cpu")- model, self.example = model_cls.get_module()- self.inputs = self.example- # initialize selected models- if model_name in ["BERT_pytorch", "yolov3"]:+ benchmark = load_model_by_name(model_name)(test="eval", device="cpu")+ model, self.example = benchmark.get_module()+ if model_name in ("hf_Whisper", "hf_distil_whisper"):+ model.config.return_dict = False+ if model_name in ("BERT_pytorch", "yolov3"):model(*self.example)return model+ def infer_fw_model(self, model_obj, inputs):+ outputs = super().infer_fw_model(model_obj, inputs)+ if isinstance(outputs, dict):+ return list(outputs.values())+ return outputs+def teardown_class(self):- # cleanup tmpdir+ sys.path.remove(self.repo_dir.name)self.repo_dir.cleanup()- @pytest.mark.parametrize("name", process_pytest_marks(_model_list_path))+ @pytest.mark.parametrize("name,link,mark,reason", get_models_list(_model_list_path))+ @pytest.mark.parametrize("mode", ["trace", "export"])@pytest.mark.nightly- def test_convert_model_all_models(self, name, ie_device):- self.run(name, None, ie_device)+ def test_convert_model_all_models(self, name, link, mark, reason, mode, ie_device, request):+ marks = mark.split(";") if mark else []+ assert all(m in ("skip", "skip_trace", "skip_export", "xfail", "xfail_trace", "xfail_export")+ for m in marks), f"Incorrect test case for {name}"+ if "skip" in marks or f"skip_{mode}" in marks:+ pytest.skip(reason)+ if name not in self.installed_models:+ subprocess.check_call([sys.executable, "install.py", name], cwd=self.repo_dir.name,+ timeout=self.infer_timeout)+ self.installed_models.add(name)+ if "xfail" in marks or f"xfail_{mode}" in marks:+ request.node.add_marker(pytest.mark.xfail(reason=reason))+ self.mode = mode+ self.run(name, link, ie_device)diff --git a/tests/model_hub_tests/pytorch/torchbench_models b/tests/model_hub_tests/pytorch/torchbench_modelsindex ece3a8205f7..296eb1495b2 100644--- a/tests/model_hub_tests/pytorch/torchbench_models+++ b/tests/model_hub_tests/pytorch/torchbench_models@@ -1,6 +1,5 @@BERT_pytorch,NoneBackground_Matting,None-#DALLE2_pytorch,None - Not Supported on CPULearningToPaint,NoneSuper_SloMo,None,xfail,Unsupported ops aten::l1_loss aten::mse_loss#alexnet,None - Already tested by torchvision tests@@ -8,7 +7,7 @@ basic_gnn_edgecnn,Nonebasic_gnn_gcn,None,xfail,CPU failed to allocatebasic_gnn_gin,Nonebasic_gnn_sage,None-#cm3leon_generate,None,skip,No install.py is found+cm3leon_generate,None,xfail,Trace lacks aten::nan_to_num conversion; export has data-dependent control flowdcgan,Nonedemucs,None#densenet121,None - Already tested by torchvision tests@@ -27,9 +26,9 @@ demucs,Nonedlrm,None,xfail,Conversion is failed for: prim::Constant - None#doctr_det_predictor,None - No module named 'tf2onnx'#doctr_reco_predictor,None - No module named 'tf2onnx'-drq,None,skip,Tracer cannot infer type of SquashedNormal()+drq,None,skip_trace;xfail_export,Trace rejects SquashedNormal; export cannot guard distribution validationfastNLP_Bert,None,skip,tuple expected at most 1 argument got 2-functorch_dp_cifar10,None+functorch_dp_cifar10,None,skip_export,CPU compilation of the exported model segfaultsfunctorch_maml_omniglot,None#hf_Albert,None - Already tested by hf tests#hf_Bart,None - Already tested by hf tests@@ -41,23 +40,29 @@ functorch_maml_omniglot,None#hf_GPT2_large,None - Already tested by hf tests#hf_Longformer,None - Already tested by hf tests#hf_Reformer,None - Already tested by hf tests+#hf_Roberta_base,None - Already tested by hf tests#hf_T5,None - Already tested by hf tests#hf_T5_base,None - Already tested by hf tests-#hf_T5_generate,None,skip,No install.py is found+#hf_T5_generate,None - Already tested by hf tests#hf_T5_large,None - Already tested by hf testshf_Whisper,None-#hf_clip,None,skip,No install.py is found+hf_distil_whisper,None+#hf_clip,None - Already tested by hf testslennard_jones,None-llama,None,skip,Type 'Tuple[Tensor int]' cannot be traced-llama_v2_7b_16h,None,skip,Tracer cannot infer type of CausalLMOutputWithPast+llava,None,skip,Not supported on CPU by TorchBench+llama,None,skip_trace;xfail_export,Trace rejects integer inputs; export conversion rejects the start_pos input shape+llama_v2_7b_16h,None,skip,Not supported on CPU by TorchBenchmaml,None,skip,element 0 of tensors does not require grad and does not have a grad_fnmaml_omniglot,None+microbench_unbacked_tolist_sum,None,xfail_trace,torch._check condition becomes a tensor during tracingmnasnet1_0,None#mobilenet_v2,None - Already tested by torchvision tests-mobilenet_v2_quantized_qat,None+mobilenet_v2_quantized_qat,None,xfail_export,torch.export cannot flatten quantized Conv2dPackedParamsBase#mobilenet_v3_large,None - Already tested by torchvision tests#moco,None - DistributedDataParallel/allgather requires cuda-#nanogpt,None,skip,No install.py is found+modded_nanogpt,None,skip,Not supported on CPU by TorchBench+moondream,None,xfail,Transformers causal mask vmap fails tracing and exports unsupported batch-dimension ops+nanogpt,Nonenvidia_deeprecommender,Noneopacus_cifar10,None,skip,Modules that have backward hooks assigned can't be compiledphlippe_densenet,None@@ -74,11 +79,12 @@ pytorch_unet,Noneresnet50_quantized_qat,None,xfail,Accuracy validation failed#resnext50_32x4d,None - Already tested by torchvision testssam,None,xfail,Unexpected type of example_input+sam_fast,None,skip,Not supported on CPU by TorchBench#shufflenet_v2_x1_0,None - Already tested by torchvision tests-#simple_gpt,None,skip,No install.py is found-#simple_gpt_tp_manual,None,skip,No install.py is found-soft_actor_critic,None,skip,Tracer cannot infer type of SquashedNormal-speech_transformer,None+simple_gpt,None,skip,Requires CUDA and distributed execution+simple_gpt_tp_manual,None,skip,Requires CUDA and distributed execution+soft_actor_critic,None,skip_trace;xfail_export,Trace rejects SquashedNormal; export cannot guard distribution validation+speech_transformer,None,xfail_export,torch.export cannot specialize data-dependent input_lengths#squeezenet1_1,None - Already tested by torchvision testsstable_diffusion_text_encoder,None,skip,Failed to install in torchbenchstable_diffusion_unet,None,skip,Failed to install in torchbench@@ -91,8 +97,8 @@ tacotron2,None,skip,Can't be loaded without CUDA#timm_vision_transformer,None - Already tested by timm tests#timm_vision_transformer_large,None - Already tested by timm tests#timm_vovnet,None - Already tested by timm tests-torch_multimodal_clip,None,skip,Can't be traced+torch_multimodal_clip,None,skip_trace,Can't be tracedtts_angular,None#vgg16,None - Already tested by torchvision tests#vision_maskrcnn,None,skip,Only tensors, lists, tuples of tensors, or dictionary of tensors can be output from traced functions-yolov3,None\ No newline at end of file+yolov3,None