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
[NPU] Cover NPU compilation with a single pytorch suite (#38113)
Anton Sukhobochenko6ac69ef38391
diff --git a/.github/workflows/job_npu_tests.yml b/.github/workflows/job_npu_tests.ymlindex 53368023883..c09dc0d46e9 100644--- a/.github/workflows/job_npu_tests.yml+++ b/.github/workflows/job_npu_tests.yml@@ -134,88 +134,21 @@ jobs:--html=${{ env.INSTALL_TEST_DIR }}\TEST-jax_npu_model_%NPU_PLATFORM%_%MODEL_SCOPE%.html --self-contained-html -v -s# --- PyTorch (runs after TF/JAX within the same leg) --------------------- # Group A: torchvision + timm + edsr share compatible deps (installed together).- - name: Install PyTorch tests requirements (group A - torchvision/timm/edsr)+ - name: Install PyTorch tests requirementsif: ${{ !cancelled() && (fromJSON(inputs.affected-components).NPU.test || fromJSON(inputs.affected-components).PyTorch_FE.test) }}run: |python3 -m pip install -r ${{ env.INSTALL_TEST_DIR }}\requirements_pytorch `- -r ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\envs\torchvision.txt `- -r ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\envs\timm.txt `- -r ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\envs\edsr.txt+ -r ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\envs\npu_models.txt- - name: PyTorch Models Tests - NPU compile-only (group A)+ - name: PyTorch Models Tests - NPU compile-onlyif: ${{ !cancelled() && (fromJSON(inputs.affected-components).NPU.test || fromJSON(inputs.affected-components).PyTorch_FE.test) }}shell: cmdenv:OP_REPORT_FILE: "${{ env.INSTALL_TEST_DIR }}\\TEST-pt_npu_unsupported_ops_${{ matrix.npu-platform }}.log"run: |set PYTHONPATH=${{ env.INSTALL_TEST_DIR }}\model_hub_tests;%PYTHONPATH%- python3 -m pytest ^- ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\test_torchvision_models.py ^- ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\test_timm.py ^- ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\test_edsr.py -m "%MODEL_SCOPE%" ^- --html=${{ env.INSTALL_TEST_DIR }}\TEST-pt_npu_groupA_%NPU_PLATFORM%_%MODEL_SCOPE%.html --self-contained-html -v -s-- # Group B: hf_transformers + easyocr + gfpgan + tpsmm share compatible deps.- - name: Install PyTorch tests requirements (group B - hf_transformers/easyocr/gfpgan/tpsmm)- if: ${{ !cancelled() && (fromJSON(inputs.affected-components).NPU.test || fromJSON(inputs.affected-components).PyTorch_FE.test) }}- run: |- python3 -m pip install -r ${{ env.INSTALL_TEST_DIR }}\requirements_pytorch `- -r ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\envs\hf_transformers.txt `- -r ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\envs\easyocr.txt `- -r ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\envs\gfpgan.txt `- -r ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\envs\tpsmm.txt-- - name: PyTorch Models Tests - NPU compile-only (group B)- if: ${{ !cancelled() && (fromJSON(inputs.affected-components).NPU.test || fromJSON(inputs.affected-components).PyTorch_FE.test) }}- shell: cmd- env:- OP_REPORT_FILE: "${{ env.INSTALL_TEST_DIR }}\\TEST-pt_npu_unsupported_ops_${{ matrix.npu-platform }}.log"- run: |- set PYTHONPATH=${{ env.INSTALL_TEST_DIR }}\model_hub_tests;%PYTHONPATH%- python3 -m pytest ^- ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\test_hf_transformers.py ^- ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\test_easyocr.py ^- ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\test_gfpgan.py ^- ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\test_tpsmm.py -m "%MODEL_SCOPE%" ^- --html=${{ env.INSTALL_TEST_DIR }}\TEST-pt_npu_groupB_%NPU_PLATFORM%_%MODEL_SCOPE%.html --self-contained-html -v -s-- # Group C: aliked + detectron2 share compatible deps (installed together).- # Disabled, re-enable: E-229647- - name: Install PyTorch tests requirements (group C - aliked/detectron2)- if: false- run: |- python3 -m pip install -r ${{ env.INSTALL_TEST_DIR }}\requirements_pytorch-- # Disabled, re-enable: E-229647- - name: PyTorch Models Tests - NPU compile only (group C)- if: false- shell: cmd- run: |- set PYTHONPATH=${{ env.INSTALL_TEST_DIR }}\model_hub_tests;%PYTHONPATH%- python3 -m pytest ^- ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\test_aliked.py ^- ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\test_detectron2.py -m "%MODEL_SCOPE%" ^- --html=${{ env.INSTALL_TEST_DIR }}\TEST-pt_npu_groupC_%NPU_PLATFORM%_%MODEL_SCOPE%.html --self-contained-html -v -s-- # Group D: llm. Disabled on NPU (if: false) - needs additional changes to enable- # on Windows (gptqmodel deps + export_mode path). llm_build_deps must precede llm.txt.- # Disabled, re-enable: E-229647- - name: Install PyTorch tests requirements (group D - llm)- if: false- run: |- python3 -m pip install -r ${{ env.INSTALL_TEST_DIR }}\requirements_pytorch- python3 -m pip install -r ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\envs\llm_build_deps.txt- python3 -m pip install --no-build-isolation -r ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\envs\llm.txt-- # Disabled, re-enable: E-229647- - name: PyTorch Models Tests - NPU compile-only (group D - llm)- if: false- shell: cmd- run: |- set PYTHONPATH=${{ env.INSTALL_TEST_DIR }}\model_hub_tests;%PYTHONPATH%- python3 -m pytest ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\test_llm.py -m "%MODEL_SCOPE%" ^- --html=${{ env.INSTALL_TEST_DIR }}\TEST-pt_npu_llm_%NPU_PLATFORM%_%MODEL_SCOPE%.html --self-contained-html -v -s+ python3 -m pytest ${{ env.INSTALL_TEST_DIR }}\model_hub_tests\pytorch\test_npu_models.py -m "%MODEL_SCOPE%" ^+ --html=${{ env.INSTALL_TEST_DIR }}\TEST-pt_npu_models_%NPU_PLATFORM%_%MODEL_SCOPE%.html --self-contained-html -v -s- name: Upload Test Resultsuses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1diff --git a/tests/model_hub_tests/pytorch/envs/npu_models.txt b/tests/model_hub_tests/pytorch/envs/npu_models.txtnew file mode 100644index 00000000000..84570181299--- /dev/null+++ b/tests/model_hub_tests/pytorch/envs/npu_models.txt@@ -0,0 +1,10 @@+# Extra dependencies for test_npu_models.py+# Newer than envs/hf_transformers.txt to cover qwen3 and friends, capped below 4.53:+# from there torch.jit.trace fails for every attention decoder (bisected on+# Qwen2.5-0.5B with torch 2.12 - 4.52.4 traces, 4.53.3 does not).+transformers==4.52.4+huggingface-hub==0.35.3+timm==1.0.24+psutil==7.2.2+super-image==0.2.0+easyocr==1.7.2diff --git a/tests/model_hub_tests/pytorch/test_aliked.py b/tests/model_hub_tests/pytorch/test_aliked.pyindex 26b24a541fb..c738a2a726d 100644--- a/tests/model_hub_tests/pytorch/test_aliked.py+++ b/tests/model_hub_tests/pytorch/test_aliked.py@@ -15,15 +15,11 @@ import torchfrom openvino import convert_model, Model, PartialShape, Typefrom openvino.frontend import ConversionExtension-from torch_utils import TestTorchConvertModel, skip_npu_precommit+from torch_utils import TestTorchConvertModel# To make tests reproducible we seed the random generatortorch.manual_seed(0)-# Precommit models out of the NPU scope, per platform ("*" = all platforms).-NPU_PRECOMMIT_SKIP = {- "aliked-n16rot": "*",-}def custom_op_loop(context):map = context.get_input(0)@@ -79,11 +75,6 @@ def read_image(path, idx):class TestAlikedConvertModel(TestTorchConvertModel):def setup_class(self):- # On NPU aliked is out of scope (see NPU_PRECOMMIT_SKIP), so skip the whole class- # before the native `sh build.sh` step in setup (which also fails on Windows).- if "NPU" in os.environ.get("TEST_DEVICE", ""):- pytest.skip("aliked is out of the NPU scope")-self.repo_dir = tempfile.TemporaryDirectory()os.system(f"git clone https://github.com/mvafin/ALIKED.git {self.repo_dir.name}")@@ -140,7 +131,6 @@ class TestAlikedConvertModel(TestTorchConvertModel):@pytest.mark.precommit@pytest.mark.parametrize("name", get_supported_precommit_models())def test_convert_model_all_models_default(self, name, ie_device):- skip_npu_precommit(name, ie_device, NPU_PRECOMMIT_SKIP)self.run(name, None, ie_device)@pytest.mark.nightlydiff --git a/tests/model_hub_tests/pytorch/test_detectron2.py b/tests/model_hub_tests/pytorch/test_detectron2.pyindex dd063478f8b..6cdc4b26490 100644--- a/tests/model_hub_tests/pytorch/test_detectron2.py+++ b/tests/model_hub_tests/pytorch/test_detectron2.py@@ -9,39 +9,11 @@ import pytestimport torchfrom models_hub_common.utils import get_models_list, compare_two_tensors, retry-from torch_utils import TestTorchConvertModel, process_pytest_marks, skip_npu_precommit--# Precommit models out of the NPU scope, per platform ("*" = all platforms).-NPU_PRECOMMIT_SKIP = {- "COCO-Detection/faster_rcnn_R_50_FPN_1x": "*",- "COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x": "*",- "COCO-Detection/retinanet_R_50_FPN_1x": "*",- "COCO-Detection/rpn_R_50_C4_1x": "*",- "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x": "*",- "COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x": "*",- "COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x": "*",- "COCO-Keypoints/keypoint_rcnn_X_101_32x8d_FPN_3x": "*",- "Cityscapes/mask_rcnn_R_50_FPN": "*",- "Detectron1-Comparisons/faster_rcnn_R_50_FPN_noaug_1x": "*",- "Detectron1-Comparisons/keypoint_rcnn_R_50_FPN_1x": "*",- "Detectron1-Comparisons/mask_rcnn_R_50_FPN_noaug_1x": "*",- "LVISv0.5-InstanceSegmentation/mask_rcnn_R_50_FPN_1x": "*",- "LVISv0.5-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_1x": "*",- "Misc/cascade_mask_rcnn_R_50_FPN_3x": "*",- "Misc/cascade_mask_rcnn_X_152_32x8d_FPN_IN5k_gn_dconv": "*",- "Misc/mask_rcnn_R_50_FPN_3x_syncbn": "*",- "Misc/scratch_mask_rcnn_R_50_FPN_9x_syncbn": "*",- "PascalVOC-Detection/faster_rcnn_R_50_C4": "*",-}+from torch_utils import TestTorchConvertModel, process_pytest_marks+class TestDetectron2ConvertModel(TestTorchConvertModel):def setup_class(self):- # On NPU all detectron2 precommit models are out of scope (see NPU_PRECOMMIT_SKIP),- # so skip the whole class before the detectron2 build in setup (which also fails on- # Windows). Skipping here reports as skipped instead of erroring in setup.- if "NPU" in os.environ.get("TEST_DEVICE", ""):- pytest.skip("detectron2 is out of the NPU scope")-from PIL import Imageimport requests@@ -127,7 +99,6 @@ class TestDetectron2ConvertModel(TestTorchConvertModel):get_models_list(os.path.join(os.path.dirname(__file__), "detectron2_precommit")))@pytest.mark.precommitdef test_detectron2_precommit(self, name, type, mark, reason, ie_device):- skip_npu_precommit(name, ie_device, NPU_PRECOMMIT_SKIP)if platform.machine() in ['arm', 'armv7l', 'aarch64', 'arm64', 'ARM64']:pytest.skip("Detectron2 models are not enabled on ARM")self.run(name, None, ie_device)diff --git a/tests/model_hub_tests/pytorch/test_easyocr.py b/tests/model_hub_tests/pytorch/test_easyocr.pyindex 5ac72f9b35e..1af89fcf5ed 100644--- a/tests/model_hub_tests/pytorch/test_easyocr.py+++ b/tests/model_hub_tests/pytorch/test_easyocr.py@@ -6,15 +6,11 @@ import pytestimport torchfrom openvino import PartialShape-from torch_utils import TestTorchConvertModel, skip_npu_precommit+from torch_utils import TestTorchConvertModel# To make tests reproducible we seed the random generatortorch.manual_seed(0)-NPU_PRECOMMIT_SKIP = {- "recognizer": "*",-}-class TestEasyOCRConvertModel(TestTorchConvertModel):def load_model(self, model_name, model_link):@@ -42,7 +38,6 @@ class TestEasyOCRConvertModel(TestTorchConvertModel):def test_convert_model(self, name, ie_device):if platform.machine() in ['arm', 'armv7l', 'aarch64', 'arm64', 'ARM64']:pytest.skip("EasyOCR models are not enabled on ARM")- skip_npu_precommit(name, ie_device, NPU_PRECOMMIT_SKIP)self.run(name, None, ie_device)@pytest.mark.precommit@@ -51,6 +46,5 @@ class TestEasyOCRConvertModel(TestTorchConvertModel):def test_convert_model_export(self, name, ie_device):if platform.machine() in ['arm', 'armv7l', 'aarch64', 'arm64', 'ARM64']:pytest.skip("EasyOCR models are not enabled on ARM")- skip_npu_precommit(name, ie_device, NPU_PRECOMMIT_SKIP)self.mode = "export"self.run(name, None, ie_device)diff --git a/tests/model_hub_tests/pytorch/test_edsr.py b/tests/model_hub_tests/pytorch/test_edsr.pyindex 32d4c37382c..d6d01c210c6 100644--- a/tests/model_hub_tests/pytorch/test_edsr.py+++ b/tests/model_hub_tests/pytorch/test_edsr.py@@ -10,17 +10,12 @@ import torchfrom models_hub_common.constants import hf_cache_dir, clean_hf_cache_dirfrom models_hub_common.utils import cleanup_dir-from torch_utils import TestTorchConvertModel, skip_npu_precommit+from torch_utils import TestTorchConvertModelfrom PIL import Image# To make tests reproducible we seed the random generatortorch.manual_seed(0)-# Precommit models out of the NPU scope, per platform ("*" = all platforms).-NPU_PRECOMMIT_SKIP = {- "edsr": "*",-}-class TestEdsrConvertModel(TestTorchConvertModel):def load_model(self, model_name, model_link):@@ -74,7 +69,6 @@ class TestEdsrConvertModel(TestTorchConvertModel):@pytest.mark.parametrize("name", ["edsr"])@pytest.mark.precommitdef test_convert_model_precommit(self, name, ie_device):- skip_npu_precommit(name, ie_device, NPU_PRECOMMIT_SKIP)self.scale = random.randint(2, 4)self.run(name, None, ie_device)diff --git a/tests/model_hub_tests/pytorch/test_hf_transformers.py b/tests/model_hub_tests/pytorch/test_hf_transformers.pyindex d816ba41536..b76875d24aa 100644--- a/tests/model_hub_tests/pytorch/test_hf_transformers.py+++ b/tests/model_hub_tests/pytorch/test_hf_transformers.py@@ -10,7 +10,7 @@ import torchfrom models_hub_common.constants import hf_cache_dir, clean_hf_cache_dirfrom models_hub_common.utils import cleanup_dir, get_models_list, retry-from torch_utils import TestTorchConvertModel, skip_npu_precommit+from torch_utils import TestTorchConvertModeldef flattenize_tuples(list_input):@@ -34,14 +34,6 @@ def flattenize_outputs(outputs):# To make tests reproducible we seed the random generatortorch.manual_seed(0)-# Precommit models out of the NPU scope, per platform ("*" = all platforms).-NPU_PRECOMMIT_SKIP = {- "google/flan-t5-base": "*",- "google/tapas-large-finetuned-wtq": "*",- "allenai/led-base-16384": "*",- "openai/clip-vit-large-patch14": "*",-}-class TestTransformersModel(TestTorchConvertModel):def setup_class(self):@@ -561,7 +553,6 @@ class TestTransformersModel(TestTorchConvertModel):def test_convert_model_precommit(self, name, type, ie_device):if platform.machine() in ['arm', 'armv7l', 'aarch64', 'arm64', 'ARM64']:pytest.skip("hf_transformers models are not enabled on ARM")- skip_npu_precommit(name, ie_device, NPU_PRECOMMIT_SKIP)self.run(model_name=name, model_link=type, ie_device=ie_device)@pytest.mark.parametrize("name,type", [("bert-base-uncased", "bert"),@@ -571,7 +562,6 @@ class TestTransformersModel(TestTorchConvertModel):def test_convert_model_precommit_export(self, name, type, ie_device):if platform.machine() in ['arm', 'armv7l', 'aarch64', 'arm64', 'ARM64']:pytest.skip("hf_transformers models are not enabled on ARM")- skip_npu_precommit(name, ie_device, NPU_PRECOMMIT_SKIP)self.mode = "export"self.run(model_name=name, model_link=type, ie_device=ie_device)diff --git a/tests/model_hub_tests/pytorch/test_npu_models.py b/tests/model_hub_tests/pytorch/test_npu_models.pynew file mode 100644index 00000000000..23bd7cab503--- /dev/null+++ b/tests/model_hub_tests/pytorch/test_npu_models.py@@ -0,0 +1,294 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++import os+import warnings++import pytest+import torch+from models_hub_common.constants import hf_cache_dir, clean_hf_cache_dir+from models_hub_common.utils import cleanup_dir, retry+from openvino import PartialShape, convert_model++from torch_utils import TestTorchConvertModel, flattenize_tuples++# To make tests reproducible we seed the random generator+torch.manual_seed(0)++NPU_MODELS = [+ dict(id="llama", source="hf-causal-lm",+ repo="TinyLlama/TinyLlama-1.1B-Chat-v1.0", dtype=torch.float16, ram_gb=5),+ dict(id="qwen2", source="hf-causal-lm",+ repo="Qwen/Qwen2.5-0.5B-Instruct", dtype=torch.float16, ram_gb=3, skipped_platforms=["3720"]),+ dict(id="qwen3", source="hf-causal-lm",+ repo="Qwen/Qwen3-0.6B", dtype=torch.float16, ram_gb=4),+ # granite-4.0-h-1b and SmolLM3 need transformers 4.53+, which breaks decoder+ # tracing here - see envs/npu_models.txt.+ dict(id="phi3", source="hf-causal-lm",+ repo="microsoft/Phi-3-mini-4k-instruct", dtype=torch.float16, ram_gb=17),++ dict(id="bert", source="hf", auto_class="AutoModel",+ repo="bert-base-uncased", dtype=torch.float32, ram_gb=2,+ inputs={"input_ids": [1, 128], "attention_mask": [1, 128]}),++ dict(id="whisper", source="hf-whisper",+ repo="openai/whisper-base", dtype=torch.float32, ram_gb=2),++ dict(id="siglip", source="hf", auto_class="AutoModel",+ repo="google/siglip-base-patch16-224", dtype=torch.float32, ram_gb=2,+ inputs={"input_ids": [1, 64], "pixel_values": [1, 3, 224, 224]}),++ dict(id="detr", source="hf", auto_class="AutoModelForObjectDetection",+ repo="facebook/detr-resnet-50", dtype=torch.float32, ram_gb=1,+ inputs={"pixel_values": [1, 3, 640, 640]}),++ dict(id="rt-detr", source="hf", auto_class="AutoModelForObjectDetection",+ repo="PekingU/rtdetr_r50vd", dtype=torch.float32, ram_gb=1,+ inputs={"pixel_values": [1, 3, 640, 640]},+ skipped_platforms=["3720", "4000", "5010", "5020", "6010"]),++ dict(id="deeplabv3", source="torchvision",+ repo="deeplabv3_mobilenet_v3_large", dtype=torch.float32, ram_gb=1),++ dict(id="sam2-hiera", source="timm",+ repo="sam2_hiera_base_plus.fb_r896", dtype=torch.float32, ram_gb=3,+ skipped_platforms=["3720"]),++ dict(id="depth-anything", source="hf", auto_class="AutoModelForDepthEstimation",+ repo="depth-anything/Depth-Anything-V2-Small-hf", dtype=torch.float32, ram_gb=1,+ inputs={"pixel_values": [1, 3, 518, 518]},+ skipped_platforms=["3720", "5010", "6010"]),++ dict(id="swin2sr", source="hf", auto_class="Swin2SRForImageSuperResolution",+ repo="caidas/swin2SR-classical-sr-x2-64", dtype=torch.float32, ram_gb=1,+ inputs={"pixel_values": [1, 3, 64, 64]},+ skipped_platforms=["3720"]),+ dict(id="edsr", source="super-image",+ repo="eugenesiow/edsr-base", dtype=torch.float32, ram_gb=1),++ dict(id="easyocr-detector", source="easyocr",+ repo="detector", dtype=torch.float32, ram_gb=1),+ dict(id="easyocr-recognizer", source="easyocr",+ repo="recognizer", dtype=torch.float32, ram_gb=1),++ dict(id="resnet", source="torchvision",+ repo="resnet50", dtype=torch.float32, ram_gb=1),+ dict(id="convnext", source="torchvision",+ repo="convnext_tiny", dtype=torch.float32, ram_gb=1),+ dict(id="vgg19", source="torchvision",+ repo="vgg19", dtype=torch.float32, ram_gb=2),+ # The quantized variant: it drags in quantize/dequantize and quantized conv,+ # which no other entry here does.+ dict(id="mobilenet-v3", source="torchvision",+ repo="quantized_mobilenet_v3_large", dtype=torch.float32, ram_gb=1),+ dict(id="inception", source="timm",+ repo="inception_v4.tf_in1k", dtype=torch.float32, ram_gb=1),+ dict(id="mobilevit", source="timm",+ repo="mobilevit_s.cvnets_in1k", dtype=torch.float32, ram_gb=1),+ dict(id="hrnet", source="timm",+ repo="hrnet_w18.ms_aug_in1k", dtype=torch.float32, ram_gb=1),+]++pytestmark = pytest.mark.skipif("NPU" not in os.environ.get("TEST_DEVICE", ""),+ reason="the list is NPU only")+++def get_case(model_id: str) -> dict:+ # by id, not self: run() re-imports this module in a fresh process+ for case in NPU_MODELS:+ if case["id"] == model_id:+ return case+ raise RuntimeError(f"unknown model id: {model_id}")+++def skip_if_not_enough_ram(model_name, need_gb):+ import psutil++ available_gb = psutil.virtual_memory().available / (1024 ** 3)+ if available_gb < need_gb:+ pytest.skip(f"{model_name}: needs ~{need_gb} GB RAM to convert, "+ f"only {available_gb:.1f} GB available")+++def skip_if_platform_skipped(model_name, skipped_platforms):+ npu_platform = os.environ.get("NPU_PLATFORM")+ if npu_platform and npu_platform in (skipped_platforms or []):+ pytest.skip(f"{model_name}: known NPU compilation failure on platform {npu_platform}")+++def make_inputs(spec, dtype):+ inputs = {}+ for name, shape in spec.items():+ if name.endswith("_ids"):+ inputs[name] = torch.randint(0, 1000, shape)+ elif name.endswith("_mask"):+ inputs[name] = torch.ones(shape, dtype=torch.int64)+ else:+ inputs[name] = torch.randn(shape, dtype=dtype)+ return inputs+++def flatten_tensors(value):+ # ModelOutput is dict-like; None and cache objects are dropped along the way.+ if isinstance(value, torch.Tensor):+ yield value+ elif isinstance(value, dict):+ for item in value.values():+ yield from flatten_tensors(item)+ elif isinstance(value, (list, tuple)):+ for item in value:+ yield from flatten_tensors(item)+++class _Traceable(torch.nn.Module):+ # torch.jit.trace wants positional tensors in and a flat tuple of tensors out;+ # HF outputs carry None fields and nested ModelOutput/cache objects it can't type.+ def __init__(self, module, names=None):+ super().__init__()+ self.module = module+ self.names = names++ def forward(self, *args):+ if self.names:+ out = self.module(**dict(zip(self.names, args)))+ else:+ out = self.module(*args)+ return tuple(flatten_tensors(out))+++class TestNpuModels(TestTorchConvertModel):+ # weights download plus a compile of a multi-billion parameter model+ infer_timeout = 3600++ @retry(10, exceptions=(OSError,), delay=5, exponential_backoff=True,+ backoff_multiplier=2, max_delay=300)+ def load_model(self, model_name, model_link):+ case = get_case(model_name)+ loader = {+ "hf": self._load_hf,+ "hf-causal-lm": self._load_hf_causal_lm,+ "hf-whisper": self._load_hf_whisper,+ "timm": self._load_timm,+ "torchvision": self._load_torchvision,+ "super-image": self._load_super_image,+ "easyocr": self._load_easyocr,+ }[case["source"]]++ with warnings.catch_warnings():+ warnings.filterwarnings("ignore",+ message=r".*copying from a non-meta parameter.*",+ category=UserWarning)+ model = loader(case)+ model.eval()+ if isinstance(self.example, dict):+ names = list(self.example)+ self.example = tuple(self.example.values())+ return _Traceable(model, names)+ return _Traceable(model)++ def _load_hf(self, case):+ import transformers+ from huggingface_hub import snapshot_download++ cached = snapshot_download(case["repo"]) # required to avoid HF rate limits+ config = transformers.AutoConfig.from_pretrained(cached)+ config.torchscript = True+ # not every config has use_cache+ if hasattr(config, "use_cache"):+ config.use_cache = False+ model = getattr(transformers, case["auto_class"]).from_pretrained(+ cached, config=config, torch_dtype=case["dtype"])+ self.example = make_inputs(case["inputs"], case["dtype"])+ return model++ def _load_hf_causal_lm(self, case):+ from huggingface_hub import snapshot_download+ from transformers import AutoModelForCausalLM++ cached = snapshot_download(case["repo"])+ # eager + use_cache=False: sdpa branching and DynamicCache do not trace+ model = AutoModelForCausalLM.from_pretrained(cached,+ torch_dtype=case["dtype"],+ torchscript=True,+ attn_implementation="eager",+ use_cache=False)+ self.example = make_inputs({"input_ids": [1, 32], "attention_mask": [1, 32]},+ case["dtype"])+ return model++ def _load_hf_whisper(self, case):+ from huggingface_hub import snapshot_download+ from transformers import AutoModelForSpeechSeq2Seq++ cached = snapshot_download(case["repo"])+ model = AutoModelForSpeechSeq2Seq.from_pretrained(cached,+ torch_dtype=case["dtype"],+ torchscript=True,+ attn_implementation="eager",+ use_cache=False)+ # 3000 frames is whisper's fixed 30-second window; mel bins differ per variant+ self.example = {+ "input_features": torch.randn([1, model.config.num_mel_bins, 3000],+ dtype=case["dtype"]),+ "decoder_input_ids": torch.randint(0, 1000, [1, 20]),+ }+ return model++ def _load_timm(self, case):+ import timm++ model = timm.create_model(case["repo"], pretrained=True)+ shape = list(timm.get_pretrained_cfg(case["repo"]).input_size)+ self.example = (torch.randn([1] + shape, dtype=case["dtype"]),)+ return model++ def _load_torchvision(self, case):+ from torchvision.models import get_model++ model = get_model(case["repo"], weights="DEFAULT")+ self.example = (torch.randn([1, 3, 224, 224], dtype=case["dtype"]),)+ return model++ def _load_super_image(self, case):+ from super_image import EdsrModel++ model = EdsrModel.from_pretrained(case["repo"], scale=2)+ self.example = (torch.randn([1, 3, 64, 64], dtype=case["dtype"]),)+ return model++ def _load_easyocr(self, case):+ import easyocr++ reader = easyocr.Reader(["en"], quantize=False, verbose=False)+ if case["repo"] == "detector":+ model = reader.detector+ self.example = (torch.rand([1, 3, 608, 800], dtype=case["dtype"]),)+ else:+ model = reader.recognizer+ self.example = (torch.rand([1, 1, 64, 320], dtype=case["dtype"]),+ torch.rand([1, 33], dtype=case["dtype"]))+ return model++ def convert_model_impl(self, model_obj):+ # NPU requires static shapes: use example input dims+ example = self.example+ tensors = list(example.values()) if isinstance(example, dict) else flattenize_tuples(example)+ return convert_model(model_obj,+ example_input=example,+ input=[PartialShape(list(t.shape)) for t in tensors],+ verbose=True)++ def teardown_method(self):+ if clean_hf_cache_dir:+ cleanup_dir(hf_cache_dir)++ super().teardown_method()++ @pytest.mark.parametrize("model_id", [case["id"] for case in NPU_MODELS])+ @pytest.mark.precommit+ @pytest.mark.nightly+ def test_compile_model(self, model_id, ie_device):+ case = get_case(model_id)+ skip_if_not_enough_ram(model_id, case["ram_gb"])+ skip_if_platform_skipped(model_id, case.get("skipped_platforms"))+ self.run(model_id, case["repo"], ie_device)diff --git a/tests/model_hub_tests/pytorch/test_timm.py b/tests/model_hub_tests/pytorch/test_timm.pyindex d168b683a48..faac2930a80 100644--- a/tests/model_hub_tests/pytorch/test_timm.py+++ b/tests/model_hub_tests/pytorch/test_timm.py@@ -10,7 +10,7 @@ import timmimport torchfrom models_hub_common.utils import get_models_list, retry-from torch_utils import TestTorchConvertModel, skip_npu_precommit+from torch_utils import TestTorchConvertModeldef filter_timm(timm_list: list) -> list:@@ -111,13 +111,6 @@ def filter_timm(timm_list: list) -> list:# To make tests reproducible we seed the random generatortorch.manual_seed(0)-# Precommit models out of the NPU scope, per platform ("*" = all platforms).-NPU_PRECOMMIT_SKIP = {- "vit_tiny_patch16_224.augreg_in21k": "*",- "poolformerv2_s12.sail_in1k": "*",- "volo_d1_224.sail_in1k": "*",-}-class TestTimmConvertModel(TestTorchConvertModel):@retry(3, exceptions=(OSError,), delay=5)@@ -164,7 +157,6 @@ class TestTimmConvertModel(TestTorchConvertModel):@pytest.mark.parametrize("name", get_supported_precommit_models())@pytest.mark.precommitdef test_convert_model_precommit(self, name, ie_device):- skip_npu_precommit(name, ie_device, NPU_PRECOMMIT_SKIP)self.mode = "trace"self.run(name, None, ie_device)diff --git a/tests/model_hub_tests/pytorch/test_torchvision_models.py b/tests/model_hub_tests/pytorch/test_torchvision_models.pyindex 784963415ce..75dcfae8b96 100644--- a/tests/model_hub_tests/pytorch/test_torchvision_models.py+++ b/tests/model_hub_tests/pytorch/test_torchvision_models.py@@ -9,7 +9,7 @@ import torchfrom torchvision.models import list_models, get_modelfrom models_hub_common.utils import get_models_list, retry-from torch_utils import TestTorchConvertModel, skip_npu_precommit+from torch_utils import TestTorchConvertModeldef get_all_models() -> list:@@ -20,12 +20,6 @@ def get_all_models() -> list:# To make tests reproducible we seed the random generatortorch.manual_seed(0)-# Precommit models out of the NPU scope, per platform ("*" = all platforms).-NPU_PRECOMMIT_SKIP = {- "raft_small": "*",- "swin_v2_s": {"4000", "5010", "5020"},-}-class TestTorchHubConvertModel(TestTorchConvertModel):@retry(3, exceptions=(OSError,), delay=1)@@ -106,7 +100,6 @@ class TestTorchHubConvertModel(TestTorchConvertModel):@pytest.mark.parametrize("model_name", get_supported_precommit_models())@pytest.mark.precommitdef test_convert_model_precommit(self, model_name, ie_device):- skip_npu_precommit(model_name, ie_device, NPU_PRECOMMIT_SKIP)self.mode = "trace"self.run(model_name, None, ie_device)diff --git a/tests/model_hub_tests/pytorch/torch_utils.py b/tests/model_hub_tests/pytorch/torch_utils.pyindex e1c74a6c794..5aadcd414b5 100644--- a/tests/model_hub_tests/pytorch/torch_utils.py+++ b/tests/model_hub_tests/pytorch/torch_utils.py@@ -6,7 +6,7 @@ import pytestimport torchfrom models_hub_common.test_convert_model import TestConvertModelfrom models_hub_common.utils import get_models_list-from openvino import convert_model, PartialShape+from openvino import convert_modeldef flattenize_tuples(list_input):@@ -44,23 +44,6 @@ def extract_unsupported_ops_from_exception(e: str) -> list:return []-def skip_npu_precommit(model_name, ie_device, skip_map):- """Skip a precommit model that is out of the NPU scope on the current NPU_PLATFORM.-- `skip_map` maps a model name to the platforms where it must be skipped: either- the string "*" (all platforms) or an iterable of platform ids (e.g. {"3720"}).- The active platform is read from the NPU_PLATFORM environment variable.- """- if "NPU" not in (ie_device or ""):- return- platforms = skip_map.get(model_name)- if not platforms:- return- current = os.environ.get("NPU_PLATFORM", "")- if platforms == "*" or current in platforms:- pytest.skip(f"{model_name}: out of NPU scope on platform {current or 'unknown'}")--class TestTorchConvertModel(TestConvertModel):cached_model = None@@ -80,19 +63,10 @@ class TestTorchConvertModel(TestConvertModel):else:return flattenize_structure(inputs)- def npu_static_input(self):- # NPU requires static shapes: use example input dims- example = self.example- tensors = list(example.values()) if isinstance(example, dict) else flattenize_tuples(example)- return [PartialShape(list(t.shape)) for t in tensors]-def convert_model_impl(self, model_obj):- is_npu = 'NPU' in (getattr(self, "ie_device", "") or '')if hasattr(self, "mode") and self.mode == "export":export_kwargs = {}- if is_npu:- export_kwargs["input"] = self.npu_static_input()- elif getattr(self, "dynamo_input", None):+ if getattr(self, "dynamo_input", None):export_kwargs["input"] = self.dynamo_inputov_model = convert_model(model_obj,example_input=self.example,@@ -101,13 +75,9 @@ class TestTorchConvertModel(TestConvertModel):**export_kwargs,)else:- convert_kwargs = {}- if is_npu:- convert_kwargs["input"] = self.npu_static_input()ov_model = convert_model(model_obj,example_input=self.example,- verbose=True,- **convert_kwargs,+ verbose=True)return ov_model