PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
set default DYNAMO_CACHE_SIZE_LIMIT to 16 (#1786)
Wenhua Chengcb9b0b7644f9
diff --git a/auto_round/algorithms/quantization/base.py b/auto_round/algorithms/quantization/base.pyindex ca5e4113a..29c0a70f3 100644--- a/auto_round/algorithms/quantization/base.py+++ b/auto_round/algorithms/quantization/base.py@@ -401,7 +401,7 @@ class BaseQuantizers:Handles both LLM and diffusion model block formats. Uses the compiledblock_forward when enable_torch_compile is True (same as _get_block_outputs),- matching old-arch behaviour where self.block_forward was compiled at init.+ matching old-arch behavior where self.block_forward was compiled at init."""current_input_ids, current_input_others = self._sampling_inputs(input_ids,diff --git a/auto_round/algorithms/quantization/rtn/quantizer.py b/auto_round/algorithms/quantization/rtn/quantizer.pyindex 260743518..07aaf7697 100644--- a/auto_round/algorithms/quantization/rtn/quantizer.py+++ b/auto_round/algorithms/quantization/rtn/quantizer.py@@ -64,6 +64,7 @@ class RTNQuantizer(BaseQuantizers):def __init__(self, config: RTNConfig):BaseQuantizers.__init__(self, config)+ @torch.no_grad()def quantize_block(self, block: torch.nn.Module, input_ids=None, input_others=None, reference_output=None, **kwargs) -> dict:@@ -97,6 +98,7 @@ class RTNQuantizer(BaseQuantizers):self.quantize_layer(m.global_name)return {}+ @torch.no_grad()def quantize_layer(self, name: str, dtype: torch.dtype = None) -> None:"""Quantizes a layer using RTN (Round-To-Nearest) if available.@@ -219,6 +221,7 @@ class OptimizedRTNQuantizer(RTNQuantizer):def quantize_layer_outside_block(self, *args, **kwargs):return self.quantize_layer(*args, **kwargs)+ @torch.no_grad()def quantize_block(self, block: torch.nn.Module, input_ids=None, input_others=None, reference_output=None, **kwargs):@@ -249,5 +252,3 @@ class OptimizedRTNQuantizer(RTNQuantizer):m.imatrix /= m.imatrix_cntif hasattr(m, "global_name") and check_to_quantized(m):self.quantize_layer_outside_block(m.global_name)-- # _get_block_outputs and _sampling_inputs are defined in BaseQuantizers and inherited.diff --git a/auto_round/envs.py b/auto_round/envs.pyindex e216a27e2..471739599 100644--- a/auto_round/envs.py+++ b/auto_round/envs.py@@ -45,6 +45,13 @@ environment_variables: dict[str, Callable[[], Any]] = {"AR_SEARCH_SCALE_RATIO": lambda: (float(os.getenv("AR_SEARCH_SCALE_RATIO")) if os.getenv("AR_SEARCH_SCALE_RATIO") is not None else None),+ # Minimum value to which torch._dynamo cache_size_limit /+ # accumulated_cache_size_limit / recompile_limit are bumped when+ # ``enable_torch_compile`` is used. The default of 16 is enough to cover+ # all distinct linear-weight shapes inside one transformer block (q/k/v/+ # o_proj, gate/up/down_proj, ...) so that per-layer static recompiles do+ # not exceed dynamo's default limit (8) and fall back to eager.+ "AR_DYNAMO_CACHE_SIZE_LIMIT": lambda: int(os.getenv("AR_DYNAMO_CACHE_SIZE_LIMIT", "16")),}diff --git a/auto_round/utils/device.py b/auto_round/utils/device.pyindex 2be868452..e90d78431 100644--- a/auto_round/utils/device.py+++ b/auto_round/utils/device.py@@ -87,13 +87,44 @@ def _use_hpu_compile_mode():return TORCH_VERSION_AT_LEAST_2_4 and not is_hpu_lazy_mode()+def _bump_dynamo_cache_limit(min_size: Optional[int] = None):+ """Raise torch._dynamo cache/recompile limits.++ The same quant function (e.g. ``quant_tensor_sym``) is reused across+ every linear layer in a transformer block (q/k/v/o_proj, gate/up/+ down_proj, ...), each with a different weight shape. Because dynamo's+ compile cache is keyed by the function's code object (shared across+ all WrapperLinear instances), per-layer static recompiles quickly+ exceed the default ``recompile_limit`` (8) and trigger a fallback to+ eager with a noisy warning. We keep static-shape compilation (best+ perf) and just allow more cache entries.++ The threshold can be overridden via the ``AR_DYNAMO_CACHE_SIZE_LIMIT``+ environment variable (default: 16).+ """+ try:+ if min_size is None:+ from auto_round import envs++ min_size = envs.AR_DYNAMO_CACHE_SIZE_LIMIT+ from torch._dynamo import config as _dynamo_config++ for attr in ("cache_size_limit", "accumulated_cache_size_limit", "recompile_limit"):+ if hasattr(_dynamo_config, attr) and getattr(_dynamo_config, attr) < min_size:+ setattr(_dynamo_config, attr, min_size)+ except Exception: # pragma: no cover - best effort+ pass++def compile_func_on_hpu(func):if _use_hpu_compile_mode():+ _bump_dynamo_cache_limit()return torch.compile(func, backend="hpu_backend")return funcdef compile_func_on_cuda_or_cpu(func):+ _bump_dynamo_cache_limit()return torch.compile(func)diff --git a/auto_round_extension/triton/triton_utils/kernels.py b/auto_round_extension/triton/triton_utils/kernels.pyindex a2756d1d9..efe809fb4 100644--- a/auto_round_extension/triton/triton_utils/kernels.py+++ b/auto_round_extension/triton/triton_utils/kernels.py@@ -202,6 +202,7 @@ def quant_matmul_248_kernel(# Now we need to unpack b (which is N-bit values) into 32-bit valuesb = (b >> shifter[:, None]) & maxq # Extract the N-bit valuesb = (b - zeros) * scales # Scale and shift+ b = b.to(a.dtype) # ensure dtype matches A for tl.dot (bf16 safe)accumulator += tl.dot(a, b)a_ptrs += BLOCK_SIZE_Kdiff --git a/docs/environments.md b/docs/environments.mdindex ae1052976..e232e8831 100644--- a/docs/environments.md+++ b/docs/environments.md@@ -99,6 +99,16 @@ export AR_ENABLE_ACT_MINMAX_TUNING=1export AR_SEARCH_SCALE_RATIO=0.75```+### AR_DYNAMO_CACHE_SIZE_LIMIT+- **Description**: Minimum value to which `torch._dynamo`'s `cache_size_limit`, `accumulated_cache_size_limit`, and `recompile_limit` are bumped when `enable_torch_compile=True`. The same compiled quant function is reused across every linear layer in a transformer block (q/k/v/o_proj, gate/up/down_proj, ...) but each layer has a different weight shape, so per-layer static recompiles quickly exceed dynamo's default limit (8) and trigger a noisy fallback to eager. Raising the limit keeps static-shape compilation (best perf) and just allows more cache entries.+- **Default**: `16`+- **Valid Values**: positive integer+- **Usage**: Increase if your model has more than 16 distinct linear-weight shapes per block (rare).++```bash+export AR_DYNAMO_CACHE_SIZE_LIMIT=32+```+## Usage Examples### Setting Environment Variablesdiff --git a/docs/environments_CN.md b/docs/environments_CN.mdindex c360f5b99..9525de3a1 100644--- a/docs/environments_CN.md+++ b/docs/environments_CN.md@@ -99,6 +99,16 @@ export AR_ENABLE_ACT_MINMAX_TUNING=1export AR_SEARCH_SCALE_RATIO=0.75```+### AR_DYNAMO_CACHE_SIZE_LIMIT+- **描述**:在启用 `enable_torch_compile=True` 时,将 `torch._dynamo` 的 `cache_size_limit`、`accumulated_cache_size_limit` 与 `recompile_limit` 提升到的最小值。同一个被编译的量化函数会被 transformer block 内的所有 linear 层(q/k/v/o_proj、gate/up/down_proj 等)复用,但每层权重 shape 不同,按层的静态重编译会很快超过 dynamo 默认上限(8),导致打印告警并退回 eager。提高该上限可以保留静态 shape 编译(性能最佳),仅增加缓存条目数。+- **默认值**:`16`+- **有效值**:正整数+- **用途**:当模型单个 block 内 linear 权重 shape 种类超过 16 时(较少见)可调大。++```bash+export AR_DYNAMO_CACHE_SIZE_LIMIT=32+```+## 使用示例### 设置环境变量