Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[PyTorch] Update transformers for LLM tests (#35270)

Maxim Vafin2e2277f18815
diff --git a/.github/workflows/job_pytorch_models_tests.yml b/.github/workflows/job_pytorch_models_tests.yml
index 3b3575d5e43..c8816defc14 100644
--- a/.github/workflows/job_pytorch_models_tests.yml
+++ b/.github/workflows/job_pytorch_models_tests.yml
@@ -138,7 +138,10 @@ jobs:
if: ${{ inputs.model_scope == 'precommit' || inputs.model_scope == 'nightly_scope2' }}
run: |
python3 -m pip install \
- -r ${INSTALL_TEST_DIR}/requirements_pytorch \
+ -r ${INSTALL_TEST_DIR}/requirements_pytorch
+ python3 -m pip install \
+ -r ${MODEL_HUB_TESTS_INSTALL_DIR}/pytorch/envs/llm_build_deps.txt
+ python3 -m pip install --no-build-isolation \
-r ${MODEL_HUB_TESTS_INSTALL_DIR}/pytorch/envs/llm.txt
- name: PyTorch LLM Model Tests
@@ -176,6 +179,8 @@ jobs:
- name: Install deps for transformation tests
if: ${{ inputs.model_scope == 'precommit' }}
run: |
+ # Remove LLM-specific packages that conflict with optimum-intel deps
+ python3 -m pip uninstall -y gptqmodel triton kernels torchao 2>/dev/null || true
python3 -m pip install \
-r ${INSTALL_TEST_DIR}/requirements_pytorch \
-r ${MODEL_HUB_TESTS_INSTALL_DIR}/pytorch/envs/optimum_intel.txt
@@ -200,6 +205,8 @@ jobs:
if: ${{ inputs.model_scope == 'precommit' }}
run: |
export PYTHONPATH=${MODEL_HUB_TESTS_INSTALL_DIR}:$PYTHONPATH
+ # compile_gptq.txt downgrades torch to 2.3.1; remove packages incompatible with it
+ python3 -m pip uninstall -y triton torchao autoawq 2>/dev/null || true
python3 -m pip install -r ${MODEL_HUB_TESTS_INSTALL_DIR}/pytorch/envs/compile_gptq.txt
python3 -m pytest ${MODEL_HUB_TESTS_INSTALL_DIR}/transformation_tests/test_gptq_torchfx_transformations.py -m precommit --html=${INSTALL_TEST_DIR}/TEST-torch_gptqpattern_tests.html --self-contained-html -v --tb=short
env:
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/gptq.py b/src/bindings/python/src/openvino/frontend/pytorch/gptq.py
index d9e4892a999..f185109b994 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/gptq.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/gptq.py
@@ -93,8 +93,8 @@ def patched_forward_sym(self, *args, **kwargs):
return out
-# All the following AutoGPTQ"s quant types are supposed to have the same weights packing schema
-supported_quant_types = ["triton", "exllama", "exllamav2", "cuda-old"]
+# All the following AutoGPTQ/GPTQModel quant types are supposed to have the same weights packing schema
+supported_quant_types = ["triton", "exllama", "exllamav2", "cuda-old", "hf_kernel"]
def patch_model(model):
@@ -119,7 +119,7 @@ def patch_model(model):
if hasattr(module, "QUANT_TYPE"):
if module.QUANT_TYPE not in supported_quant_types:
raise ValueError(f"Unsupported QUANT_TYPE == {module.QUANT_TYPE} is discovered for "
- "AutoGPTQ model, only the following types are supported: "
+ "GPTQ model, only the following types are supported: "
f"{supported_quant_types}")
if module.bits != 4:
raise ValueError(f"Unsupported bits == {module.bits} is discovered in module {name} "
diff --git a/tests/model_hub_tests/pytorch/envs/llm.txt b/tests/model_hub_tests/pytorch/envs/llm.txt
index d9a81360893..31fddc1dbf0 100644
--- a/tests/model_hub_tests/pytorch/envs/llm.txt
+++ b/tests/model_hub_tests/pytorch/envs/llm.txt
@@ -1,12 +1,14 @@
# Extra dependencies for test_llm.py (LLM quantized models)
# These are NOT needed by test_hf_transformers.py
+transformers==5.5.3
+huggingface-hub==1.10.1
+
# quantized model deps
-autoawq==0.2.7; platform_system == "Linux" and platform_machine == "x86_64"
-triton==3.5.1; platform_system == "Linux" and platform_machine == "x86_64"
-auto-gptq==0.7.1; platform_system == "Linux" and platform_machine == "x86_64" and python_version < "3.12"
-peft==0.17.1; platform_system == "Linux" and platform_machine == "x86_64" and python_version < "3.12"
+autoawq==0.2.9; platform_system == "Linux" and platform_machine == "x86_64"
+triton==3.6.0; platform_system == "Linux" and platform_machine == "x86_64"
+gptqmodel==6.0.3; platform_system == "Linux" and platform_machine == "x86_64" and python_version < "3.12"
+peft==0.18.1; platform_system == "Linux" and platform_machine == "x86_64" and python_version < "3.12"
# optimum (required by transformers' GptqHfQuantizer for GPTQ model loading)
-# Pinned to 1.24.0 for compatibility with auto-gptq 0.7.1
-optimum==1.24.0; python_version < "3.12"
+optimum==2.1.0; python_version < "3.12"
diff --git a/tests/model_hub_tests/pytorch/envs/llm_build_deps.txt b/tests/model_hub_tests/pytorch/envs/llm_build_deps.txt
new file mode 100644
index 00000000000..71e731f4be4
--- /dev/null
+++ b/tests/model_hub_tests/pytorch/envs/llm_build_deps.txt
@@ -0,0 +1,5 @@
+# Build dependencies for gptqmodel sdist.
+# gptqmodel's setup.py imports pcre at module level, so pypcre must be
+# installed before gptqmodel can be built with --no-build-isolation.
+# Install this file BEFORE llm.txt.
+pypcre==0.3.0
diff --git a/tests/model_hub_tests/pytorch/envs/optimum_intel.txt b/tests/model_hub_tests/pytorch/envs/optimum_intel.txt
index bfafa8cb6e7..d71a32e330c 100644
--- a/tests/model_hub_tests/pytorch/envs/optimum_intel.txt
+++ b/tests/model_hub_tests/pytorch/envs/optimum_intel.txt
@@ -1,3 +1,8 @@
# optimum-intel required by transformation tests (PA, StatefulToStateless, etc.)
# Pinned to a known-working commit for compatibility.
+# optimum-intel@8ba536cd requires transformers>=4.36,<4.52
+transformers==4.51.3
+optimum==1.25.0; python_version < "3.12"
+auto-gptq==0.7.1; platform_system == "Linux" and platform_machine == "x86_64" and python_version < "3.12"
+autoawq==0.2.7; platform_system == "Linux" and platform_machine == "x86_64"
git+https://github.com/huggingface/optimum-intel.git@8ba536cd0a2bf93e9e88408b0048a7695db5be0b; python_version < "3.12"
diff --git a/tests/model_hub_tests/pytorch/test_llm.py b/tests/model_hub_tests/pytorch/test_llm.py
index 922b606c421..f401824fc5a 100644
--- a/tests/model_hub_tests/pytorch/test_llm.py
+++ b/tests/model_hub_tests/pytorch/test_llm.py
@@ -3,6 +3,7 @@
import copy
import inspect
+from contextlib import contextmanager
import numpy as np
import platform
@@ -25,18 +26,22 @@ def patch_gptq():
orig_cuda_is_available = torch.cuda.is_available
orig_cuda_is_bf16_supported = torch.cuda.is_bf16_supported
orig_cuda_get_device_capability = torch.cuda.get_device_capability
+ orig_cuda_device_count = torch.cuda.device_count
orig_post_init_model = None
+ orig_awq_post_init = None
orig_gemm_forward = None
+ orig_default_dtype = torch.get_default_dtype()
torch.set_default_dtype(torch.float32)
- torch.cuda.is_available = lambda: True
- torch.cuda.is_bf16_supported = lambda: False
- torch.cuda.get_device_capability = lambda n: (9, 1)
+ # Import GPTQ-related modules BEFORE faking CUDA availability.
+ # gptqmodel performs CUDA device init at import time; if it sees
+ # cuda.is_available()=True while there is no real GPU, it crashes
+ # trying to create CUDA streams.
+ try:
+ import gptqmodel # noqa: F401
+ except ImportError:
+ pass
try:
- # Patch at the transformers level to avoid GPU-only post_init_model
- # from optimum.gptq. transformers' GptqHfQuantizer delegates to
- # optimum_quantizer.post_init_model() which calls gptq_post_init
- # (requires GPU). Replace with a CPU-safe stub.
from transformers.quantizers.quantizer_gptq import GptqHfQuantizer
orig_post_init_model = GptqHfQuantizer._process_model_after_weight_loading
@@ -48,9 +53,31 @@ def patch_gptq():
model.quantize_config = StoreAttr()
oq = self.optimum_quantizer
model.quantize_config.desc_act = oq.desc_act
+ # gptqmodel's HFKernelLinear needs wf_unsqueeze_* buffers
+ # (registered by PackableQuantLinear.post_init) but we must
+ # NOT call optimize() which repacks qweight/qzeros into a
+ # layout incompatible with OV's GPTQ decompression pattern.
+ # Instead: register buffers only and force "train" mode so
+ # the forward uses dequantize_weight (no compiled kernel).
+ #
+ # Also convert GPTQ v1→v2 qzeros format: auto_gptq stores
+ # qzeros as (zero_point - 1); gptqmodel's dequantize_weight
+ # expects actual zero_point values (v2). For 4-bit int32
+ # packed format, add 0x11111111 (+1 per nibble).
+ try:
+ from gptqmodel.nn_modules.qlinear import PackableQuantLinear
+ for _, submodule in model.named_modules():
+ if isinstance(submodule, PackableQuantLinear):
+ # v1→v2 qzeros conversion (4-bit int32 only)
+ if submodule.bits == 4 and submodule.qzeros.dtype == torch.int32:
+ submodule.qzeros.data += 0x11111111
+ PackableQuantLinear.post_init(submodule)
+ submodule.linear_mode = "train"
+ except ImportError:
+ pass
if oq.desc_act and not oq.disable_exllama and oq.max_input_length is not None:
try:
- from auto_gptq import exllama_set_max_input_length
+ from gptqmodel import exllama_set_max_input_length
model = exllama_set_max_input_length(model, oq.max_input_length)
except ImportError:
pass
@@ -60,56 +87,258 @@ def patch_gptq():
except ImportError:
pass
+ # Patch AWQ quantizer to skip gptqmodel's post_init/optimize, which
+ # repacks qweight/qzeros into a layout that dequantize_gemm cannot
+ # handle. _replace_awq_with_linear() will dequantize from the
+ # original packed format instead.
try:
- # patch GEMM module to work without CUDA GPU
- from awq.modules.linear.gemm import WQLinearMMFunction
- from awq.utils.packing_utils import dequantize_gemm
-
- def new_forward(
- ctx,
- x,
- qweight,
- qzeros,
- scales,
- w_bit=4,
- group_size=128,
- bias=None,
- out_features=0,
- ):
- ctx.out_features = out_features
-
- out_shape = x.shape[:-1] + (out_features,)
- x = x.to(torch.float16)
-
- out = dequantize_gemm(qweight, qzeros, scales, w_bit, group_size)
- out = torch.matmul(x, out.to(x.dtype))
-
- out = out + bias if bias is not None else out
- out = out.reshape(out_shape)
-
- if len(out.shape) == 2:
- out = out.unsqueeze(0)
- return out
-
- orig_gemm_forward = WQLinearMMFunction.forward
- WQLinearMMFunction.forward = new_forward
+ from transformers.quantizers.quantizer_awq import AwqQuantizer
+ orig_awq_post_init = AwqQuantizer._process_model_after_weight_loading
+ AwqQuantizer._process_model_after_weight_loading = lambda self, model, **kwargs: model
except ImportError:
pass
- return (orig_cuda_is_available, orig_cuda_is_bf16_supported, orig_cuda_get_device_capability), orig_post_init_model, orig_gemm_forward
+ try:
+ # Patch gptqmodel's AWQ linear to work on CPU without compiled
+ # kernels. _replace_awq_with_linear() replaces these modules
+ # before conversion, so this patch only serves as a safety fallback.
+ from gptqmodel.nn_modules.qlinear import AWQuantLinear
+ from gptqmodel.quantization.awq.utils.packing_utils import dequantize_gemm as _awq_dequant
+ _orig_awq_forward = AWQuantLinear.forward
+
+ def _awq_forward_cpu(self, x):
+ orig_dtype = x.dtype
+ out_shape = x.shape[:-1] + (self.out_features,)
+ x_flat = x.reshape(-1, x.shape[-1]).to(torch.float16)
+ weight = _awq_dequant(self.qweight, self.qzeros, self.scales,
+ self.bits, self.group_size)
+ out = torch.matmul(x_flat, weight)
+ if self.bias is not None:
+ out.add_(self.bias)
+ return out.reshape(out_shape).to(orig_dtype)
+
+ AWQuantLinear.forward = _awq_forward_cpu
+ orig_gemm_forward = _orig_awq_forward
+ except ImportError:
+ pass
-def unpatch_gptq(orig_cuda_check, orig_post_init_model, orig_gemm_forward):
- torch.cuda.is_available, torch.cuda.is_bf16_supported, torch.cuda.get_device_capability = orig_cuda_check
+ if orig_gemm_forward is None:
+ try:
+ # Fallback: patch autoawq GEMM module for older setups
+ from awq.modules.linear.gemm import WQLinearMMFunction
+ from awq.utils.packing_utils import dequantize_gemm
+
+ def new_forward(
+ ctx, x, qweight, qzeros, scales,
+ w_bit=4, group_size=128, bias=None, out_features=0,
+ ):
+ ctx.out_features = out_features
+ out_shape = x.shape[:-1] + (out_features,)
+ x = x.to(torch.float16)
+ out = dequantize_gemm(qweight, qzeros, scales, w_bit, group_size)
+ out = torch.matmul(x, out.to(x.dtype))
+ out = out + bias if bias is not None else out
+ out = out.reshape(out_shape)
+ if len(out.shape) == 2:
+ out = out.unsqueeze(0)
+ return out
+
+ orig_gemm_forward = WQLinearMMFunction.forward
+ WQLinearMMFunction.forward = new_forward
+ except ImportError:
+ pass
+
+ # Fake CUDA availability AFTER all imports are done, so gptqmodel's
+ # module-level CUDA init has already completed safely on CPU.
+ torch.cuda.is_available = lambda: True
+ torch.cuda.is_bf16_supported = lambda: False
+ torch.cuda.get_device_capability = lambda *args, **kwargs: (9, 1)
+ torch.cuda.device_count = lambda: 1
+
+ return (orig_cuda_is_available, orig_cuda_is_bf16_supported, orig_cuda_get_device_capability, orig_cuda_device_count), orig_post_init_model, orig_awq_post_init, orig_gemm_forward, orig_default_dtype
+
+
+def unpatch_gptq(orig_cuda_check, orig_post_init_model, orig_awq_post_init, orig_gemm_forward, orig_default_dtype):
+ torch.cuda.is_available, torch.cuda.is_bf16_supported, torch.cuda.get_device_capability, torch.cuda.device_count = orig_cuda_check
+ torch.set_default_dtype(orig_default_dtype)
try:
from transformers.quantizers.quantizer_gptq import GptqHfQuantizer
GptqHfQuantizer._process_model_after_weight_loading = orig_post_init_model
except ImportError:
pass
+ if orig_awq_post_init is not None:
+ try:
+ from transformers.quantizers.quantizer_awq import AwqQuantizer
+ AwqQuantizer._process_model_after_weight_loading = orig_awq_post_init
+ except ImportError:
+ pass
+ if orig_gemm_forward is not None:
+ try:
+ from gptqmodel.nn_modules.qlinear import AWQuantLinear
+ AWQuantLinear.forward = orig_gemm_forward
+ except ImportError:
+ try:
+ from awq.modules.linear.gemm import WQLinearMMFunction
+ WQLinearMMFunction.forward = orig_gemm_forward
+ except ImportError:
+ pass
+
+
+def _replace_awq_with_linear(model):
+ """Replace AWQ quantized linear layers with plain nn.Linear.
+
+ Eagerly dequantizes packed int weights into float32 so the conversion
+ graph contains only standard matmul ops (no bitwise dequantization or
+ compiled kernels).
+ """
try:
- from awq.modules.linear.gemm import WQLinearMMFunction
- WQLinearMMFunction.forward = orig_gemm_forward
+ from gptqmodel.nn_modules.qlinear import AWQuantLinear
+ from gptqmodel.quantization.awq.utils.packing_utils import dequantize_gemm
except ImportError:
+ return
+
+ for name, module in list(model.named_modules()):
+ if not isinstance(module, AWQuantLinear):
+ continue
+ weight = dequantize_gemm(
+ module.qweight, module.qzeros, module.scales,
+ module.bits, module.group_size,
+ ).t().contiguous().float() # dequantize_gemm returns (in, out); Linear expects (out, in)
+ linear = torch.nn.Linear(
+ module.in_features, module.out_features,
+ bias=module.bias is not None, dtype=weight.dtype,
+ )
+ linear.weight = torch.nn.Parameter(weight, requires_grad=False)
+ if module.bias is not None:
+ linear.bias = torch.nn.Parameter(module.bias.data.clone(), requires_grad=False)
+ # Replace module in parent
+ parts = name.rsplit(".", 1)
+ parent = model.get_submodule(parts[0]) if len(parts) == 2 else model
+ setattr(parent, parts[-1], linear)
+
+
+@contextmanager
+def _patch_for_jit_trace():
+ """Patch transformers internals for JIT trace compatibility.
+
+ 1. Wrap sdpa_mask/eager_mask to coerce q_length from a 0-d tensor
+ (produced by torch.jit.trace) to a plain int, preventing the BC
+ check in sdpa_mask from crashing on q_length.shape[0].
+ 2. Patch DynamicLayer.lazy_initialization to create 4D empty tensors
+ instead of 1D, avoiding aten::cat shape mismatches during trace.
+ """
+ saved_masks = {}
+ orig_lazy_init = None
+ try:
+ from transformers.masking_utils import ALL_MASK_ATTENTION_FUNCTIONS, sdpa_mask, eager_mask
+
+ def _wrap_mask_fn(orig_fn):
+ def _patched(*args, **kwargs):
+ if "q_length" in kwargs and isinstance(kwargs["q_length"], torch.Tensor):
+ kwargs["q_length"] = kwargs["q_length"].item()
+ return orig_fn(*args, **kwargs)
+ return _patched
+
+ saved_masks = {"sdpa": sdpa_mask, "eager": eager_mask}
+ ALL_MASK_ATTENTION_FUNCTIONS.register("sdpa", _wrap_mask_fn(sdpa_mask))
+ ALL_MASK_ATTENTION_FUNCTIONS.register("eager", _wrap_mask_fn(eager_mask))
+ except (ImportError, AttributeError):
pass
+ try:
+ from transformers.cache_utils import DynamicLayer
+ orig_lazy_init = DynamicLayer.lazy_initialization
+
+ def _lazy_init_4d(self, key_states, value_states=None):
+ self.dtype, self.device = key_states.dtype, key_states.device
+ shape = list(key_states.shape)
+ shape[-2] = 0
+ self.keys = torch.zeros(shape, dtype=self.dtype, device=self.device)
+ self.values = torch.zeros(shape, dtype=self.dtype, device=self.device)
+ self.is_initialized = True
+
+ DynamicLayer.lazy_initialization = _lazy_init_4d
+ except (ImportError, AttributeError):
+ pass
+ try:
+ yield
+ finally:
+ for name, func in saved_masks.items():
+ ALL_MASK_ATTENTION_FUNCTIONS.register(name, func)
+ if orig_lazy_init is not None:
+ DynamicLayer.lazy_initialization = orig_lazy_init
+
+
+class DynamicCacheModelWrapper(torch.nn.Module):
+ """Wraps a causal LM to convert tuple past_key_values <-> DynamicCache.
+
+ Newer transformers (>=4.48) use DynamicCache by default for many models.
+ This wrapper ensures the model accepts tuple PKV (for OV tracing
+ compatibility) and returns tuple PKV.
+ """
+
+ def __init__(self, model, example_keys=None):
+ super().__init__()
+ self._wrapped = model
+
+ # Build an ordered list of parameter names matching the example keys,
+ # preserving the original forward signature order.
+ orig_params = list(inspect.signature(model.forward).parameters)
+ if example_keys is not None:
+ ordered_keys = [k for k in orig_params if k in example_keys]
+ else:
+ ordered_keys = orig_params
+
+ # Create a forward function that converts tuple PKV <-> DynamicCache
+ def _forward(*args, **kwargs):
+ from transformers.cache_utils import DynamicCache
+
+ # When called with positional args (during JIT tracing), convert
+ # to kwargs using the ordered parameter names so the underlying
+ # model receives correctly-named arguments regardless of
+ # intermediate parameters (like cache_position) in its signature.
+ if args and not kwargs:
+ for name, arg in zip(ordered_keys, args):
+ kwargs[name] = arg
+ args = ()
+
+ # Convert tuple PKV to DynamicCache
+ if "past_key_values" in kwargs and isinstance(kwargs["past_key_values"], (tuple, list)):
+ kwargs["past_key_values"] = DynamicCache(ddp_cache_data=kwargs["past_key_values"])
+
+ outputs = model(**kwargs)
+
+ def _dc_to_tuples(dc):
+ return tuple((k, v) for k, v, _ in dc)
+
+ if isinstance(outputs, (tuple, list)):
+ outputs = type(outputs)(
+ _dc_to_tuples(v) if isinstance(v, DynamicCache) else v
+ for v in outputs
+ )
+ else:
+ # ModelOutput (dict-like): convert DynamicCache PKV
+ if hasattr(outputs, 'past_key_values'):
+ pkv = outputs.past_key_values
+ if isinstance(pkv, DynamicCache):
+ outputs['past_key_values'] = _dc_to_tuples(pkv)
+ # Convert ModelOutput to tuple for JIT trace compatibility
+ outputs = tuple(v for v in outputs.values() if v is not None)
+
+ return outputs
+
+ # Set clean __signature__ so OV's process_dict_inputs matches inputs
+ # without needing a wrapper (avoids Cache type annotation exec failure).
+ sig_params = [
+ inspect.Parameter(k, inspect.Parameter.POSITIONAL_OR_KEYWORD, default=None)
+ for k in ordered_keys
+ ]
+ _forward.__signature__ = inspect.Signature(parameters=sig_params)
+ _forward.__wrapped__ = model.forward
+ self.forward = _forward
+
+ @property
+ def config(self):
+ return self._wrapped.config
def to_numpy(t):
@@ -146,7 +375,7 @@ torch.manual_seed(0)
class TestLLMModel(TestTorchConvertModel):
def setup_class(self):
self.infer_timeout = 1800
- self.cuda_available, self.gptq_postinit, self.orig_gemm_forward = None, None, None
+ self.cuda_available, self.gptq_postinit, self.awq_postinit, self.orig_gemm_forward, self.orig_default_dtype = None, None, None, None, None
self.export_mode = False
@retry(3, exceptions=(OSError,), delay=1)
@@ -154,53 +383,66 @@ class TestLLMModel(TestTorchConvertModel):
from huggingface_hub import snapshot_download
from transformers import AutoConfig, AutoTokenizer, AutoModelForCausalLM
- model = None
- example = None
- model_cached = snapshot_download(name) # required to avoid HF rate limits
+ model_cached = snapshot_download(name)
try:
- config = AutoConfig.from_pretrained(model_cached, trust_remote_code=True)
+ config = AutoConfig.from_pretrained(model_cached)
except Exception:
config = {}
- model_kwargs = {"torchscript": True, "trust_remote_code": True}
+ model_kwargs = {}
is_quant = is_quantized_model(config)
- is_gpt2 = name == "openai-community/gpt2"
if is_quant:
- self.cuda_available, self.gptq_postinit, self.orig_gemm_forward = patch_gptq()
- model_kwargs["torch_dtype"] = "auto"
- model_kwargs["torch_dtype"] = torch.float32
+ self.cuda_available, self.gptq_postinit, self.awq_postinit, self.orig_gemm_forward, self.orig_default_dtype = patch_gptq()
+ model_kwargs["dtype"] = torch.float32
self.ov_config = {"DYNAMIC_QUANTIZATION_GROUP_SIZE": "0"}
- elif is_gpt2:
- model_kwargs["torch_dtype"] = torch.float16
else:
- model_kwargs["torch_dtype"] = "auto"
- model_cached = snapshot_download(name) # required to avoid HF rate limits
- t = AutoTokenizer.from_pretrained(model_cached, trust_remote_code=True)
+ model_kwargs["dtype"] = "auto"
+
+ t = AutoTokenizer.from_pretrained(model_cached)
self.model = AutoModelForCausalLM.from_pretrained(model_cached, **model_kwargs)
+ # Replace AWQ quantized linear modules with plain nn.Linear (eagerly
+ # dequantized weights) before any forward pass, to prevent gptqmodel
+ # from repacking weights and to keep bitwise ops out of the graph.
+ _replace_awq_with_linear(self.model)
if is_quant:
model = self.model
else:
- assert self.model.config.torch_dtype in [
- torch.float16, torch.bfloat16] or is_gpt2
model = copy.deepcopy(self.model).float()
+ # Build example inputs based on what the model's forward accepts
+ fwd_params = set(inspect.signature(self.model.forward).parameters)
example = t("Some input text to verify that model works.",
return_tensors='pt').__dict__['data']
- atype = type.replace("_gptq", "")
- if atype not in ["gptj", "starcoder2", "mpt"]:
+ if "past_key_values" in fwd_params:
pkv, am = self.get_pkv(model, t)
example["past_key_values"] = pkv
example["attention_mask"] = torch.cat(
[example["attention_mask"], am], -1)
- if atype not in ["opt", "falcon", "mbart", "mpt"]:
+ if "position_ids" in fwd_params:
ids = torch.cumsum(example["attention_mask"] != 0, dim=1) - 1
- example["position_ids"] = ids[:, -
- example["input_ids"].shape[1]:]
+ example["position_ids"] = ids[:, -example["input_ids"].shape[1]:]
self.example = example
+
+ # Wrap models for DynamicCache <-> tuple conversion (transformers >=4.48)
+ try:
+ from transformers.cache_utils import DynamicCache # noqa: F401
+ needs_wrapper = True
+ except ImportError:
+ needs_wrapper = False
+ if needs_wrapper:
+ example_keys = set(example.keys())
+ if is_quant:
+ self.model = DynamicCacheModelWrapper(self.model, example_keys)
+ model = self.model
+ else:
+ self.model = DynamicCacheModelWrapper(self.model, example_keys)
+ model = DynamicCacheModelWrapper(model, example_keys)
+
return model
def get_inputs_info(self, model_obj):
- return list(inspect.signature(getattr(model_obj, "forward", model_obj.__call__)).parameters)
+ target = model_obj._wrapped if isinstance(model_obj, DynamicCacheModelWrapper) else model_obj
+ return list(inspect.signature(getattr(target, "forward", target.__call__)).parameters)
def prepare_inputs(self, inputs_info):
inputs = getattr(self, "inputs", self.example)
@@ -266,16 +508,18 @@ class TestLLMModel(TestTorchConvertModel):
if self.export_mode:
return self._convert_model_export(model_obj)
is_patched = False
- if getattr(self.model.config, "torch_dtype", None) in [torch.float16, torch.bfloat16]:
+ # Detect actual model dtype from parameters (config.torch_dtype can be None)
+ model_dtype = next(
+ (p.dtype for p in self.model.parameters()), torch.float32)
+ if model_dtype in [torch.float16, torch.bfloat16]:
patch(self.model)
is_patched = True
# initialize model after patching
self.model(**self.example)
- with torch.no_grad():
+ with _patch_for_jit_trace(), torch.no_grad():
ovm = super().convert_model_impl(self.model)
if is_patched:
unpatch(self.model, "_openvino_module_extension_patch_orig_forward")
- # model_obj.float()
return ovm
def _convert_model_export(self, model_obj):
@@ -295,26 +539,31 @@ class TestLLMModel(TestTorchConvertModel):
is_quant_patched = True
try:
- # Initialize model after patching
- self.model(**self.example)
-
- with torch.no_grad():
- exported = export(
- self.model,
- args=tuple(),
- kwargs=self.example,
- strict=False,
- )
- # Restore CUDA mocks before convert_model because
- # run_decompositions() tries to preserve CUDA RNG state
- # and fails when CUDA is mocked but not really available.
- # Only restore CUDA check functions — the AWQ GEMM forward
- # must stay patched for infer_fw_model.
- if self.cuda_available is not None:
- (torch.cuda.is_available,
- torch.cuda.is_bf16_supported,
- torch.cuda.get_device_capability) = self.cuda_available
- ovm = convert_model(exported, verbose=True)
+ # Patch DynamicLayer.lazy_initialization to create 4D empty
+ # tensors (same fix as _patch_for_jit_trace) so that aten::cat
+ # along axis=-2 works correctly during export.
+ with _patch_for_jit_trace():
+ # Initialize model after patching
+ self.model(**self.example)
+
+ with torch.no_grad():
+ exported = export(
+ self.model,
+ args=tuple(),
+ kwargs=self.example,
+ strict=False,
+ )
+ # Restore CUDA mocks before convert_model because
+ # run_decompositions() tries to preserve CUDA RNG state
+ # and fails when CUDA is mocked but not really available.
+ # Only restore CUDA check functions — the AWQ GEMM forward
+ # must stay patched for infer_fw_model.
+ if self.cuda_available is not None:
+ (torch.cuda.is_available,
+ torch.cuda.is_bf16_supported,
+ torch.cuda.get_device_capability,
+ torch.cuda.device_count) = self.cuda_available
+ ovm = convert_model(exported, verbose=True)
finally:
if is_quant_patched:
unpatch_quantized_for_export(self.model)
@@ -324,22 +573,21 @@ class TestLLMModel(TestTorchConvertModel):
self.export_mode = False
# restore after gptq patching
if self.cuda_available is not None:
- unpatch_gptq(self.cuda_available, self.gptq_postinit, self.orig_gemm_forward)
- self.cuda_available, self.gptq_postinit, self.orig_gemm_forward = None, None, None
+ unpatch_gptq(self.cuda_available, self.gptq_postinit, self.awq_postinit, self.orig_gemm_forward, self.orig_default_dtype)
+ self.cuda_available, self.gptq_postinit, self.awq_postinit, self.orig_gemm_forward, self.orig_default_dtype = None, None, None, None, None
super().teardown_method()
@staticmethod
def get_pkv(model, tokenizer):
+ from transformers.cache_utils import DynamicCache
+
for_pkv = tokenizer("To get past key values",
return_tensors='pt').__dict__['data']
with torch.no_grad():
pkv = model(**for_pkv)[1]
-
- # Newer transformers return DynamicCache; convert to legacy tuple format
- # so that the example dict contains plain tensors for both TS and FX paths.
- if hasattr(pkv, "to_legacy_cache"):
- pkv = pkv.to_legacy_cache()
-
+ # Convert DynamicCache to tuple-of-tuples format for OV tracing
+ if isinstance(pkv, DynamicCache):
+ pkv = tuple((k, v) for k, v, _ in pkv)
return pkv, for_pkv["attention_mask"]
def get_supported_precommit_models():
@@ -361,8 +609,8 @@ class TestLLMModel(TestTorchConvertModel):
self.run(model_name=name, model_link=type, ie_device=ie_device)
@pytest.mark.parametrize("type,name", [
- ("gpt_neox", "databricks/dolly-v2-3b"),
- ("gpt_neox_japanese", "rinna/japanese-gpt-neox-3.6b"),
+ ("gpt_neox", "EleutherAI/pythia-1.4b"),
+ ("gpt_neox_japanese", "abeja/gpt-neox-japanese-2.7b"),
("opt", "facebook/opt-1.3b"),
("phi", "microsoft/phi-2"),
("phi3", "microsoft/Phi-3-mini-4k-instruct"),
@@ -410,6 +658,7 @@ class TestLLMModel(TestTorchConvertModel):
return []
return [
("llama_awq", "casperhansen/tinyllama-1b-awq"),
+ ("opt_gptq", "katuni4ka/opt-125m-gptq"),
]
@pytest.mark.parametrize("type,name", get_supported_export_precommit_models())
diff --git a/tests/requirements_pytorch b/tests/requirements_pytorch
index d9616859159..debf84e24ff 100644
--- a/tests/requirements_pytorch
+++ b/tests/requirements_pytorch
@@ -16,6 +16,6 @@ pytest==7.2.0; python_version >= '3.10'
pytest-html==4.2.0
pytest-xdist[psutil]==3.6.1
defusedxml==0.7.1
-packaging==24.1
+packaging==24.2
protobuf==5.28.3
wheel==0.44.0