PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
feat: multi-GPU quantization improvements -- batched device-local sea… (#2357)
avtca7656a27d020
diff --git a/README.md b/README.mdindex 60b267e2d..bfbddc406 100644--- a/README.md+++ b/README.md@@ -269,6 +269,7 @@ ar.quantize_and_save(output_dir="./qmodel", format="auto_round")- **`low_gpu_mem_usage` (bool)**: Whether to offload intermediate features to CPU at the cost of ~30%-100% more tuning time (default is `False`).- **`low_cpu_mem_usage` (bool)**: [Experimental Feature] Whether to enable immediate-save mode to reduce RAM usage. It is enabled by default. In CLI, use `--disable_low_cpu_mem_usage` to turn it off (the legacy `--low_cpu_mem_usage` flag is kept only for compatibility).- **`device_map` (str|dict|int)**: The device to be used for tuning, e.g., `auto`, `cpu`, `cuda`, `0,1,2` (default is `0`). When using `auto`, it will try to use all available GPUs.+- **`calibration_data_device` (str)**: Placement of the block calibration data in multi-GPU runs: `auto` (default) | `cpu` | `off` | `1,2` | `cuda:1,cuda:2`.</details>diff --git a/README_CN.md b/README_CN.mdindex e6d2f2444..881523c86 100644--- a/README_CN.md+++ b/README_CN.md@@ -285,6 +285,7 @@ ar.quantize_and_save(output_dir="./qmodel", format="auto_round")- **`low_gpu_mem_usage`**(bool):若要节省显存,可以设为 `True` 。它会将中间特征卸载到 CPU,但会增加 30%-100% 的时间(默认 `False`)。- **`low_cpu_mem_usage`**(bool):[实验性功能] 用于启用即时保存以减少内存占用。该功能默认开启;在 CLI 中可使用 `--disable_low_cpu_mem_usage` 关闭(`--low_cpu_mem_usage` 仅为兼容旧参数保留)。- **`device_map`**(str | dict | int):计算设备指定,如 `auto`、`cpu`、`cuda`、`0,1,2`(默认 `0`)。使用 `auto` 时会尝试利用所有可用 GPU。+- **`calibration_data_device`**(str):多 GPU 运行时块校准数据的存放位置:`auto`(默认)| `cpu` | `off` | `1,2` | `cuda:1,cuda:2`。</details>diff --git a/auto_round/algorithms/block_runner.py b/auto_round/algorithms/block_runner.pyindex 90de327b3..56121c8ea 100644--- a/auto_round/algorithms/block_runner.py+++ b/auto_round/algorithms/block_runner.py@@ -192,6 +192,10 @@ class BlockForwardRunner:Normalized output tensor on ``cache_device`` (or ``self.cache_device``)."""out_device = cache_device if cache_device is not None else self.cache_device+ # Per-chunk calibration-data placement (--calibration_data_device): list mode (indices is+ # None -- the cat at the end of indices-mode requires same-device outputs)+ # and only when the caller did not pin a device for this call.+ placement = getattr(self, "pool_placement", None) if cache_device is None and indices is None else Noneis_returned_list = Trueif indices is not None:is_returned_list = False@@ -233,7 +237,11 @@ class BlockForwardRunner:for key, value in batch_output_dict.items():output_dict.setdefault(key, []).append(value.to(out_device))output = [output]- outputs.extend(item.to(out_device) for item in output)+ if placement is not None:+ base = len(outputs)+ outputs.extend(item.to(placement.device_for_index(base + j)) for j, item in enumerate(output))+ else:+ outputs.extend(item.to(out_device) for item in output)del raw_output, batch_output_dict, output, batch_inputs, batch_othersif not outputs:@@ -257,6 +265,25 @@ class BlockForwardRunner:# ── Input selection ──────────────────────────────────────────────────────+ @staticmethod+ def _gather_same_device(values: Any, target_device: str) -> Any:+ """Ensure per-sample tensors are same-device before torch.cat.++ With sharded calibration-data placement (--calibration_data_device)+ a selected batch can span several park+ devices; gather onto ``target_device`` (the compute device) in that+ case. Uniform-device selections are returned untouched -- byte-identical+ to the single-device behavior. Structured values (diffusion ``freqs``+ can be nested lists) pass through: the single-device lane never moves+ them either.+ """+ if not values or not all(hasattr(v, "device") for v in values):+ return values+ first = values[0].device+ if all(v.device == first for v in values):+ return values+ return [v.to(target_device) for v in values]+def select_batch(self,inputs: Any,@@ -383,14 +410,20 @@ class BlockForwardRunner:selected_inputs[key] = valelse:if isinstance(val, list):- selected_inputs[key] = torch.cat([val[i] for i in indices], dim=batch_dim)+ batch_vals = self._gather_same_device([val[i] for i in indices], self.device)+ selected_inputs[key] = torch.cat(batch_vals, dim=batch_dim)elif isinstance(val, torch.Tensor):- selected_inputs[key] = torch.index_select(val, batch_dim, indices)+ # relocate indices like the input_others branch below:+ # under spread pool placement a sharded tensor key can+ # live on a park device while indices stay on the+ # sampler's CPU device+ selected_inputs[key] = torch.index_select(val, batch_dim, indices.to(device=val.device))else:selected_inputs[key] = valelse:if isinstance(inputs, list):- selected_inputs = torch.cat([inputs[i] for i in indices], dim=batch_dim)+ batch_vals = self._gather_same_device([inputs[i] for i in indices], self.device)+ selected_inputs = torch.cat(batch_vals, dim=batch_dim)else:selected_inputs = torch.index_select(inputs, batch_dim, indices)@@ -408,7 +441,7 @@ class BlockForwardRunner:else:selected_others[key] = valelif isinstance(val, list):- batch_vals = [val[i] for i in indices]+ batch_vals = self._gather_same_device([val[i] for i in indices], self.device)if len(batch_vals) == 1:selected_others[key] = batch_vals[0]else:diff --git a/auto_round/algorithms/composer.py b/auto_round/algorithms/composer.pyindex 67f1aeb2d..6605e5b7f 100644--- a/auto_round/algorithms/composer.py+++ b/auto_round/algorithms/composer.py@@ -84,6 +84,26 @@ class BlockContext:# ---------------------------------------------------------------------------# AlgorithmComposer# ---------------------------------------------------------------------------+def _release_pool_inplace(obj: Any) -> None:+ """Release a calibration pool's tensors by mutating its containers in place.++ The pool object is shared with the orchestrator (which holds it as the+ block's ``input_ids``), so dropping a local reference frees nothing. The+ containers are the same objects on both sides; setting their entries to+ None drops the last strong references to the tensors (hooks are removed+ and the tuning loop reads the q pool, so nothing re-reads this pool).+ Immutable containers (tuples) are skipped: their tensors stay alive until+ the block-end release, matching the pre-existing behavior.+ """+ if isinstance(obj, list):+ for i in range(len(obj)):+ obj[i] = None+ elif isinstance(obj, dict):+ for v in obj.values():+ _release_pool_inplace(v)+ return obj++class AlgorithmComposer:"""An ordered composition of pre-processors + one block quantizer, built froma list of algorithm config objects and an optional compressor.@@ -420,6 +440,17 @@ class AlgorithmComposer:for rotation_member in self._rotation_members:rotation_member.on_block_ready(block, block_ctx)+ # Routed-dispatch shape recorders: fire-once pre-hooks on MoE containers+ # capture (top_k, routed_rows) from the first NATURAL dispatch during+ # the forwards below, so the iters>0 activation budget can fall back to+ # pure arg shapes when config spellings are unknown (arch-agnostic).+ try:+ from auto_round.algorithms.quantization.tune_memory import _ensure_routed_shape_recorders_++ _ensure_routed_shape_recorders_(block)+ except Exception as e: # pragma: no cover - diagnostics only+ logger.debug("[routed-shape] recorder setup skipped (%s)", e)+# ── Step 1: Preprocessor calibration (e.g. AWQ activation stats) ──────with torch.no_grad():pre_hooks = []@@ -477,8 +508,20 @@ class AlgorithmComposer:update_block_global_scale_if_needed(block, data_type, group_size)if q_inputs is not None and fp_inputs is not q_inputs:- clear_memory(fp_inputs)+ # Release the fp pool at its last use (before tuning): the q pool is+ # the tuning input and the fp pool is already consumed into+ # reference_output. The release is IN PLACE -- the orchestrator+ # holds the same container object as its ``input_ids``, so merely+ # dropping this local reference freed nothing and the pool stayed+ # resident through the whole tune loop. Freed VRAM here directly+ # widens the tune-loop's local-pull decision (hot pools on the+ # compute device when they fit).+ _release_pool_inplace(fp_inputs)+ fp_inputs = None+ clear_memory()else:+ # lanes without a separate q-input pool (first block; quanted-input+ # disabled) still get the pre-tuning cache clear the base code hadclear_memory()# ── Step 4: quantize_block ──────────────────────────────────────────────# When quantized input is available from the previous block, use it;diff --git a/auto_round/algorithms/quantization/base.py b/auto_round/algorithms/quantization/base.pyindex 6aa6593b0..c5799ece4 100644--- a/auto_round/algorithms/quantization/base.py+++ b/auto_round/algorithms/quantization/base.py@@ -12,7 +12,7 @@# See the License for the specific language governing permissions and# limitations under the License.import traceback-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Anyimport torch@@ -197,7 +197,9 @@ class BaseQuantizer(BaseAlgorithm):self._quantize_layer_via_rtn(layer, disable_opt_rtn=disable_opt_rtn)@torch.no_grad()- def _quantize_layer_via_rtn(self, layer: "torch.nn.Module", disable_opt_rtn: "bool | None" = None) -> None:+ def _quantize_layer_via_rtn(+ self, layer: "torch.nn.Module", disable_opt_rtn: "bool | None" = None, defer_search: bool = False+ ) -> "torch.nn.Module":"""Quantize one layer with RTN (with optional optimized scale/zp search)."""layer_name = layer.global_namelayer = convert_module_to_hp_if_necessary(layer, self.model_context.amp_dtype, device_manager.device)@@ -231,8 +233,17 @@ class BaseQuantizer(BaseAlgorithm):enable_neuqi=getattr(self.config, "enable_neuqi", False),iters=0,)+ if defer_search:+ # staged for the batched zero-shot search driver: the wrapper+ # (with its resolved quant func) is returned without running+ # the search; the caller finishes via unwrapper({}) or the+ # batched call + _apply_qdq + set_module+ return layerlayer = layer.unwrapper({})except torch.OutOfMemoryError:+ from auto_round.algorithms.quantization.search_dispatch import dump_oom_tensor_census_++ dump_oom_tensor_census_("rtn layer search")cuda_error_msg = traceback.format_exc()layer = layer.orig_layer if hasattr(layer, "orig_layer") else layerlogger.error(cuda_error_msg)@@ -276,6 +287,66 @@ class BaseQuantizer(BaseAlgorithm):return Nonereturn masks+ # ── Tune-loop memory policy hooks (override to customize) ─────────────────++ def maybe_adapt_moe_implementation(self, block: "torch.nn.Module", tensors: Any, batch_size: int) -> None:+ """Switch the MoE experts implementation to the per-expert loop when the+ grouped path's working set is not expected to fit next to the tuning+ state (``AR_MOE_EXPERTS_IMPL=auto``; explicit values are honored as-is).++ Runs once per run; no-op for blocks without grouped expert stacks.+ The decision reads only the block's wrapper layout, the batch size, and+ the fleet's free memory, so algorithms rarely need to override this.+ """+ from auto_round.algorithms.quantization.tune_memory import _maybe_auto_linear_loop_for_tuning++ _maybe_auto_linear_loop_for_tuning(+ block,+ tensors,+ batch_size,+ getattr(self, "iters", 0),+ getattr(getattr(self, "model_context", None), "config", None),+ self.model,+ )++ def pull_tuning_pool(+ self,+ pool: Any,+ target_device: str,+ block: "torch.nn.Module",+ batch_size: int,+ label: str,+ charge_activation: bool = True,+ ) -> Any:+ """Bulk-move a calibration pool onto the device that reads it every+ iteration when its footprint fits next to the working set; a declined+ pull keeps the per-batch gather.++ Bulk pulls are a capacity optimization only: when the user explicitly+ parked memory on the host (``low_gpu_mem_usage`` or+ ``calibration_data_device="cpu"``) the pool stays where that policy+ put it, however much room the target device has.+ """+ cc = self.compress_context+ if (+ getattr(cc, "low_gpu_mem_usage", False)+ or str(getattr(cc, "calibration_data_device", "auto") or "auto").lower() == "cpu"+ ):+ return pool+ from auto_round.algorithms.quantization.tune_memory import _pull_pool_if_fits++ config = getattr(getattr(self, "model_context", None), "config", None)+ return _pull_pool_if_fits(+ pool,+ str(target_device),+ block,+ batch_size,+ getattr(self, "iters", 0),+ label,+ charge_activation=charge_activation,+ config=config,+ )+def dispatch_block(self, block: "torch.nn.Module", input_ids, input_others: dict):"""Place a block on the correct device(s) for quantization.Default: move to primary device.diff --git a/auto_round/algorithms/quantization/rtn/batched_search.py b/auto_round/algorithms/quantization/rtn/batched_search.pynew file mode 100644index 000000000..666d3b40c--- /dev/null+++ b/auto_round/algorithms/quantization/rtn/batched_search.py@@ -0,0 +1,534 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+# License for the specific language governing permissions and limitations+# under the License.++"""Batched zero-shot (iters=0) search driver.++Layers whose staged key -- (device, weight shape/dtype, bits, group size,+symmetry, threshold, resolved quant callable) -- matches are stacked along a+leading dim and quantized with ONE ``weight_quant_func`` call. The quant math+is row-independent, and the per-column imatrix is pre-expanded to each+module's full weight shape before stacking so the quant function's internal+flatten-expand becomes an identity: results are bit-identical to the serial+``unwrapper({})`` path. Write-back goes through the wrapper's ``_apply_qdq``+(the unwrapper's own conventions), so serial and batched outputs can never+drift apart.+"""++from collections import OrderedDict+from collections.abc import Callable+from typing import Any++import torch++from auto_round.algorithms.quantization.search_dispatch import (+ _fn_key,+ _plan_capacity_chunks,+ _search_fn_stackable,+ _wrap_batch_max_elems,+ dump_oom_tensor_census_,+ group_items_by_device,+ run_items_by_device,+ search_sweep_budget,+)+from auto_round.logger import logger+from auto_round.utils import set_module+from auto_round.utils.perf_counters import perf_counters_enabled+from auto_round.wrapper import WrapperLinear+++def _staged_weight(wrapper: WrapperLinear) -> torch.Tensor:+ """The weight exactly as _qdq_weight would pass it to the quant func."""+ weight = wrapper.orig_layer.weight+ import transformers++ if type(wrapper.orig_layer) == transformers.pytorch_utils.Conv1D:+ weight = weight.t()+ return weight+++def _staged_imatrix(wrapper: WrapperLinear, weight: torch.Tensor) -> torch.Tensor | None:+ """The RAW per-column imatrix (or None) -- expansion happens chunk-time.++ Staging the expanded full-size copy would pin N x weight bytes across the+ whole staging phase; the chunk-time expansion below is transient and+ bounded by the batch cap. Groups are homogeneous on imatrix presence (it+ is part of the staged key), so chunks are all-None or all-tensor.+ """+ del weight+ return getattr(wrapper.orig_layer, "imatrix", None)+++def _expand_imatrix(im: torch.Tensor | None, weight: torch.Tensor, group_size: int) -> torch.Tensor | None:+ """Expand one module's raw imatrix to its full weight shape (chunk-time).++ Mirrors the quant funcs' own imatrix handling exactly (data_type/int.py):+ the raw per-column vector is group-padded (fill 1e-5) BEFORE being row+ expanded, so the stacked flat layout byte-matches what the serial+ per-module call produces after its internal flatten-pad-expand. Skipping+ the pad misplaces the group alignment for every module after the first+ when ``in % group_size != 0``; casting to the weight dtype (bf16/fp16+ weights with an fp32 hook-collected imatrix) silently diverges the+ search loss weighting from the serial path.+ """+ if im is None:+ return None+ im = im.to(weight.device) # device only: keep the collected precision+ if im.dim() == 1 and weight.dim() == 2:+ out_f, in_f = weight.shape+ pad_len = 0+ if isinstance(group_size, int) and 0 < group_size <= in_f and in_f % group_size != 0:+ pad_len = ((in_f + group_size - 1) // group_size) * group_size - in_f+ if pad_len:+ im = torch.nn.functional.pad(im, (0, pad_len), value=1e-5)+ return im.unsqueeze(0).expand(out_f, -1).contiguous()+ if im.dim() == 2 and weight.dim() == 2 and im.shape[0] == 1:+ # row vector form: same treatment+ out_f, in_f = weight.shape+ pad_len = 0+ if isinstance(group_size, int) and 0 < group_size <= in_f and in_f % group_size != 0:+ pad_len = ((in_f + group_size - 1) // group_size) * group_size - in_f+ if pad_len:+ im = torch.nn.functional.pad(im, (0, pad_len), value=1e-5)+ return im.expand(out_f, -1).contiguous()+ if im.shape == weight.shape:+ return im.contiguous()+ return im+++def _extra_quant_kwargs_key(wrapper: WrapperLinear) -> tuple[tuple[str, str], ...] | None:+ """Per-module _extra_quant_kwargs hook values as a hashable key term.++ Any wrapper subclass defining the hook injects arbitrary per-module kwargs+ into the quant call; two modules with differing extras must never share a+ stacked chunk (same hazard class as differing global_scale).+ """+ hook = getattr(wrapper, "_extra_quant_kwargs", None)+ if not callable(hook):+ return None+ return tuple(sorted((str(k), repr(v)) for k, v in hook().items()))+++def _staged_key(wrapper: WrapperLinear, weight: torch.Tensor, imatrix: torch.Tensor | None) -> tuple[+ str,+ tuple[int, ...],+ str,+ int | None,+ int | None,+ bool | None,+ float,+ bool,+ str | tuple[Any, ...],+ str,+ int | None,+ int | None,+ float | None,+ tuple[tuple[str, str], ...] | None,+]:+ layer = wrapper.orig_layer+ # The stacked call assembles quant kwargs once from chunk[0], so every+ # per-layer kwarg _quant_call_kwargs injects must be part of the key:+ # modules differing in any of them never share a batch (nv-fp4 computes+ # weight_global_scale per layer; scale_dtype/super_* come from+ # per-layer config pins). imatrix is passed as a stacked override.+ global_scale = getattr(wrapper, "weight_global_scale", None)+ return (+ str(weight.device),+ tuple(weight.shape),+ str(weight.dtype),+ getattr(layer, "bits", None),+ getattr(layer, "group_size", None),+ getattr(layer, "sym", None),+ float(getattr(wrapper, "q_scale_thresh", 1e-5)),+ imatrix is not None,+ # normalize away per-wrapper torch.compile wrappers: the underlying+ # eager original is shared per config, while each compiled wrapper is+ # unique (repr-keyed) and would silently collapse every group to size 1+ _fn_key(getattr(wrapper.weight_quant_func, "_torchdynamo_orig_callable", None) or wrapper.weight_quant_func),+ str(getattr(layer, "scale_dtype", None)),+ getattr(layer, "super_bits", None),+ getattr(layer, "super_group_size", None),+ None if global_scale is None else float(global_scale),+ _extra_quant_kwargs_key(wrapper),+ )+++def _stackable_layout(wrapper: WrapperLinear) -> bool:+ """Whether the wrapper's weight layout is safe for a stacked batch call.++ The stacked call bypasses ``_qdq_weight`` and hands the quant callable a+ 3-D ``(N, out, in)`` tensor, so only row-group layouts are stackable:+ ``group_size`` -1 (per-channel) or a positive int never straddle the+ leading-dim module boundary, while ``0`` (per-tensor) would share ONE+ scale across every module in the chunk and 2-D block tuples (e.g. fp8+ ``(128, 128)``) expect a 2-D weight. Activation-only layers (``bits >=+ 16``) must finish through their own ``unwrapper`` so their weights stay+ untouched and the act metadata is still processed.+ """+ layer = wrapper.orig_layer+ bits = getattr(layer, "bits", None)+ if bits is None or int(bits) >= 16:+ return False+ group_size = getattr(layer, "group_size", None)+ if isinstance(group_size, bool) or not isinstance(group_size, int) or group_size == 0:+ return False+ return group_size == -1 or group_size > 0+++def swap_wrapper_callables_to_eager(wrapper: WrapperLinear) -> Callable[[], None] | None:+ """Point compiled wrapper callables at their eager originals.++ Returns a restore fn or None. ``unwrapper({})`` may call BOTH the+ (possibly torch.compile-wrapped) weight_quant_func and -- for+ act-quantized layers, act_bits <= 8 -- the compiled act_quant_func (the+ act tail's first-ever call in the iters=0 lane); on worker threads+ either first call would race dynamo's trace lock, exactly like the+ stacked path.+ """+ restores = []++ for attr in ("weight_quant_func", "act_quant_func"):+ fn = getattr(wrapper, attr, None)+ if fn is None:+ continue+ orig = getattr(fn, "_torchdynamo_orig_callable", None)+ if orig is None:+ continue+ setattr(wrapper, attr, orig)+ restores.append((attr, fn))++ if not restores:+ return None++ def _restore() -> None:+ for attr, fn in restores:+ setattr(wrapper, attr, fn)++ return _restore+++def _unwrap_with_cpu_fallback(w: WrapperLinear, name: str) -> torch.nn.Module:+ """unwrapper({}) under the serial lane's OOM->CPU contract.++ The per-module search can OOM on the device exactly like the serial+ path's own search (base.py); there the run falls back to CPU instead of+ crashing. The batched lane previously called unwrapper({}) unguarded --+ a module that OOMed took the whole run down, violating the progressive+ batched -> per-module -> CPU ladder.++ The rebuilt wrapper keeps the failed wrapper's optimized-RTN and NeuQI+ settings: the fallback must only change WHERE the search runs, not+ WHICH search runs (the WrapperLinear defaults would silently downgrade+ an optimized or NeuQI layer to plain RTN).+ """+ try:+ return w.unwrapper({})+ except torch.OutOfMemoryError:+ dump_oom_tensor_census_("rtn batched unwrapper")+ logger.warning("[rtn-batch] per-module search OOM for %s; falling back to CPU", name)+ layer = w.orig_layer if hasattr(w, "orig_layer") else w+ layer = layer.to("cpu")+ layer = WrapperLinear(+ layer,+ enable_minmax_tuning=False,+ enable_norm_bias_tuning=False,+ enable_round_tuning=False,+ enable_torch_compile=False,+ disable_opt_rtn=getattr(w, "disable_opt_rtn", True),+ enable_neuqi=getattr(w, "enable_neuqi", False),+ iters=0,+ )+ return layer.unwrapper({})++[email protected]_grad()+def run_batched_rtn_search(+ model: torch.nn.Module, staged: list[tuple[str, WrapperLinear]], max_batch: int | None = None+) -> None:+ """Finish deferred zero-shot wrappers on stacked same-shape batches.++ Args:+ model: The model tree (for set_module re-attachment).+ staged: list of (layer_name, wrapper) with the search deferred.+ max_batch: optional explicit chunk size.++ Every staged module is finished by this function itself -- grouped and+ stacked, singleton-per-module, or via the per-module OOM fallback -- so+ the caller never has leftover wrappers to finish.+ """+ entries = []+ for layer_name, wrapper in staged:+ weight = _staged_weight(wrapper)+ imatrix = _staged_imatrix(wrapper, weight)+ entries.append({"name": layer_name, "w": wrapper, "weight": weight, "im": imatrix})++ device_groups = OrderedDict()+ for e in entries:+ device_groups.setdefault(str(e["weight"].device), []).append(e)++ # Offload pass: the searches are weight-local, so chunks may run on any+ # device with headroom (the zero-shot lane leaves every non-home GPU idle).+ # Chunks are assigned round-robin over viable worker devices; the weights+ # and imatrices move to the worker for the stacked call and results write+ # back cross-device through _apply_qdq.+ plan_entries = [] # (home_device, per-module chain, sweep budget, max modules, group)+ for dev, batch in device_groups.items():+ by_key = OrderedDict()+ for e in batch:+ by_key.setdefault(_staged_key(e["w"], e["weight"], e["im"]), []).append(e)+ for group in by_key.values():+ fn0 = group[0]["w"].weight_quant_func+ elements = group[0]["weight"].numel() + (group[0]["im"].numel() if group[0]["im"] is not None else 0)+ per_module = elements * 4 * 4 # the fp32 copy chain per module+ max_n = 1024 if max_batch is None else max(1, max_batch)+ elem_cap = _wrap_batch_max_elems()+ if elem_cap is not None:+ max_n = min(max_n, max(1, elem_cap // max(elements, 1)))+ # layouts that must not share a stacked call (per-tensor scales,+ # 2-D block groups, activation-only layers) plan as singletons:+ # _run_chunk finishes each through the module's own unwrapper,+ # exactly like the serial lane+ if not _stackable_layout(group[0]["w"]):+ max_n = 1+ # singleton and non-stackable groups plan like any other group:+ # the RTN lane runs them through the same per-module path, and a+ # roomy idle device may still take them+ plan_entries.append((dev, per_module, search_sweep_budget(fn0), max_n, group))++ # capacity-weighted planning: chunks form directly on the device that+ # runs them, sized to its tracked headroom (see _plan_capacity_chunks)+ planned = _plan_capacity_chunks(plan_entries)++ buckets = OrderedDict()+ for worker, _home, chunk in planned:+ buckets.setdefault(str(worker), []).append(chunk)++ # per-worker execution stats for the wrap-grammar summary line+ stats: OrderedDict[str, dict] = OrderedDict()++ def _worker_of(chunk: list[dict[str, Any]]) -> str:+ for wk, cs in buckets.items():+ if any(c is chunk for c in cs):+ return str(wk)+ return str(chunk[0]["weight"].device) # not found (should not happen): stay home++ def _chunk_working_set(chunk: list[dict[str, Any]]) -> int:+ e0 = chunk[0]+ elements = e0["weight"].numel() + (e0["im"].numel() if e0["im"] is not None else 0)+ from auto_round.algorithms.quantization.search_dispatch import search_transient_bytes++ return search_transient_bytes(e0["w"].weight_quant_func, elements * len(chunk))++ @torch.no_grad()+ def _run_chunk_guarded(chunk: list[dict[str, Any]], worker: str, threaded: bool = False) -> None:+ """_run_chunk with an execution-time headroom check: halve an oversized+ chunk before running it (plan-time estimates can drift)."""+ if len(chunk) > 1:+ from auto_round.utils.device import probe_usable_bytes++ usable = probe_usable_bytes(str(worker))+ if usable is not None and usable - 512 * 2**20 < _chunk_working_set(chunk):+ mid = len(chunk) // 2+ _run_chunk_guarded(chunk[:mid], worker, threaded)+ _run_chunk_guarded(chunk[mid:], worker, threaded)+ return+ _run_chunk(chunk, worker, threaded)++ @torch.no_grad()+ def _run_chunk(chunk: list[dict[str, Any]], worker: str, threaded: bool = False) -> None:+ st = stats.setdefault(str(worker), {"wall": 0.0, "modules": 0, "batches": 0, "singletons": 0})+ st["modules"] += len(chunk)+ if len(chunk) > 1:+ st["batches"] += 1+ else:+ st["singletons"] += 1+ w0 = chunk[0]["w"]+ dev = str(chunk[0]["weight"].device)+ worker = str(worker)+ if len(chunk) == 1 and (not _search_fn_stackable(w0.weight_quant_func) or not _stackable_layout(w0)):+ # non-stackable callable or non-stackable layout: the module's+ # own serial path, on the weight's device (the stacked call is+ # unsafe for it)+ _restore = swap_wrapper_callables_to_eager(chunk[0]["w"]) if (threaded or worker != dev) else None+ try:+ layer = _unwrap_with_cpu_fallback(chunk[0]["w"], chunk[0]["name"])+ finally:+ if _restore is not None:+ _restore()+ set_module(model, chunk[0]["name"], layer)+ return+ # stackable chunks of ANY size (including 1-row: singleton groups or+ # max_batch=1 per-module spreading) ride the stacked machinery, which+ # moves weights+imatrix to the assigned worker and writes results+ # back through finalize -- identical search semantics for+ # row-independent fns+ weights = [e["weight"] for e in chunk]+ ims = [e["im"] for e in chunk]+ fn = w0.weight_quant_func+ if worker != dev or threaded:+ # the compiled path runs slower than eager for this bandwidth-bound+ # grid search; eager also sidesteps the cross-thread dynamo trace+ # race entirely -- including for home-staying chunks, which the+ # multi-device path also executes on worker threads+ fn = getattr(fn, "_torchdynamo_orig_callable", None) or fn+ try:+ # materialization is inside the guard on purpose: an OOM while+ # moving or stacking the batch must take the same per-module+ # ladder as an OOM inside the stacked call, not abort the run+ if worker != dev:+ weights = [w.to(worker) for w in weights]+ ims = [im.to(worker) if im is not None else None for im in ims]+ stacked_w = torch.stack(weights)+ stacked_im = None+ if ims and ims[0] is not None:+ _gs = w0.orig_layer.group_size+ stacked_im = torch.stack([_expand_imatrix(im, w, _gs) for im, w in zip(ims, weights)])+ kwargs = w0._quant_call_kwargs(+ torch.tensor(0.0), torch.tensor(1.0), torch.tensor(1.0), imatrix_override=stacked_im+ )+ kwargs = _relocate_tensor_kwargs(kwargs, str(stacked_w.device))+ qdq, scale, zp = fn(stacked_w, **kwargs)+ except torch.OutOfMemoryError:+ # release the partial batch before the retry: the ladder needs+ # the headroom the failed materialization consumed+ weights = ims = stacked_w = stacked_im = kwargs = None+ logger.warning(+ "[rtn-batch] stacked search OOM (%d modules); finishing this chunk per-module "+ "(shrink batches with AR_SEARCH_BATCH_GB or disable with AR_DISABLE_BATCHED_SEARCH=1)",+ len(chunk),+ )+ dump_oom_tensor_census_("rtn batched search")+ for e in chunk:+ _restore = swap_wrapper_callables_to_eager(e["w"]) if (threaded or worker != dev) else None+ try:+ layer = _unwrap_with_cpu_fallback(e["w"], e["name"])+ finally:+ if _restore is not None:+ _restore()+ set_module(model, e["name"], layer)+ return+ n = len(chunk)+ scale_parts = _split_leading(scale, n)+ zp_parts = _split_leading(zp, n)+ import transformers++ for i, e in enumerate(chunk):+ res = qdq[i]+ w = e["w"]+ # mirror the serial _qdq_weight output contract: cast back to the+ # stored dtype and restore the HF Conv1D [in, out] layout (staging+ # transposed it)+ res = res.to(w.orig_layer.weight.dtype)+ if type(w.orig_layer) == transformers.pytorch_utils.Conv1D:+ res = res.t()+ # route the write-back through unwrapper({}) with the precomputed+ # search result injected: _apply_qdq alone would skip the+ # unwrapper tail (bias/meta update, static-act rescale, act+ # metadata, WrapperWALayer attachment) and leave act-quantized+ # layers (act_bits <= 8) silently inconsistent with the serial+ # path. The injection short-circuits _qdq_weight's recompute so+ # no compiled weight_quant_func runs here; the act tail may still+ # call its compiled act_quant_func, so swap BOTH callables to+ # eager on worker threads before unwrapping.+ _restore = swap_wrapper_callables_to_eager(w) if (threaded or worker != dev) else None+ try:+ w._presolved_qdq = (res, scale_parts[i], zp_parts[i])+ layer = w.unwrapper({})+ finally:+ if _restore is not None:+ _restore()+ set_module(model, e["name"], layer)++ def _run_chunks(wk: str, cs: list[list[dict[str, Any]]]) -> None:+ import time as _ptime++ _t0 = _ptime.perf_counter()+ try:+ for c in cs:+ _run_chunk_guarded(c, _worker_of(c), threaded=True)+ finally:+ stats.setdefault(str(wk), {"wall": 0.0, "modules": 0, "batches": 0, "singletons": 0})["wall"] += (+ _ptime.perf_counter() - _t0+ )++ if len(buckets) > 1:+ keyed = OrderedDict()+ for wk, cs in buckets.items():+ keyed.setdefault(str(wk), []).append((len(keyed), (str(wk), cs)))+ run_items_by_device(keyed, lambda _idx, item: _run_chunks(item[0], item[1]))+ else:+ for wk, cs in buckets.items():+ _run_chunks(str(wk), cs)++ if stats and perf_counters_enabled():+ # one timing line, same grammar and gating as the wrap-search lane:+ # calls are chunks (each chunk is one stacked or per-module search+ # call), so the counts cannot read as "one call per module"+ from auto_round.utils.pool_placement import _short_device_key++ _n_mod = sum(st["modules"] for st in stats.values())+ _n_batch = sum(st["batches"] for st in stats.values())+ _n_single = sum(st["singletons"] for st in stats.values())+ _n_offloaded = sum(1 for worker, home, _chunk in planned if worker != home)+ _walls = sum(st.get("wall", 0.0) for st in stats.values())+ per_device = (+ "{" + ", ".join(f"'{_short_device_key(dev)}': {st.get('wall', 0.0):.2f}" for dev, st in stats.items()) + "}"+ )+ logger.info(+ "[rtn-batch] %d modules, %d batch + %d singleton search calls"+ + (f" ({_n_offloaded} chunk(s) offloaded to idle devices)" if _n_offloaded else "")+ + ", %.2fs device-wall (%.2fs summed) walls %s",+ _n_mod,+ _n_batch,+ _n_single,+ max((st.get("wall", 0.0) for st in stats.values()), default=0.0),+ _walls,+ per_device,+ )+++def _relocate_tensor_kwargs(kwargs: dict[str, Any], device: str) -> dict[str, Any]:+ """Move accelerator-valued kwargs onto the compute device.++ The weight-local searches normally run on the weight's own device, so+ tensor kwargs (e.g. an nv-fp4 ``global_scale``) live wherever the layer+ lives; under worker offload the stacked call runs elsewhere and a+ left-behind operand would fault at the first cross-device op (the mapped-+ lane init_scale crash class). CPU scalars broadcast and are left alone.+ """+ for key, val in kwargs.items():+ if isinstance(val, torch.Tensor) and val.device.type != "cpu" and str(val.device) != device:+ kwargs[key] = val.to(device)+ return kwargs+++def _split_leading(result: Any, n: int) -> list[Any]:+ """Split a quant result along the (possibly flattened) leading batch dim.++ Stacked calls may return per-module rows flattened into the leading dim+ (e.g. scale ``[N*out, 1]``) or keep a batch dim (``[N, out, groups]``);+ both reshape to ``[N, -1, ...]`` identically. Scalars pass through.+ Dicts are split recursively: GGUF K-quant funcs return scale/zp as dicts+ (``{"scale": ..., "d_scale": ...}``) whose tensor values carry the+ flattened batch dim -- sharing the whole dict per module would give every+ layer N-times the expected metadata (caught at GGUF export validation).+ Non-tensor dict values (e.g. ``None``) are shared as-is.+ """+ if isinstance(result, dict):+ split_values = {key: _split_leading(value, n) for key, value in result.items()}+ return [{key: values[i] for key, values in split_values.items()} for i in range(n)]+ if not isinstance(result, torch.Tensor):+ return [result] * n+ if result.dim() == 0 or result.numel() == 1:+ return [result] * n+ return result.reshape(n, -1, *result.shape[1:])diff --git a/auto_round/algorithms/quantization/rtn/quantizer.py b/auto_round/algorithms/quantization/rtn/quantizer.pyindex 38584dee6..6eaf3e3d9 100644--- a/auto_round/algorithms/quantization/rtn/quantizer.py+++ b/auto_round/algorithms/quantization/rtn/quantizer.py@@ -12,7 +12,7 @@# See the License for the specific language governing permissions and# limitations under the License.-import re+import time as _ptimeimport torchimport torch.nn as nn@@ -21,15 +21,19 @@ from auto_round.algorithms.quantization.base import BaseQuantizerfrom auto_round.algorithms.quantization.rtn.config import OptimizedRTNConfig, RTNConfigfrom auto_round.algorithms.registry import register_pipeline_memberfrom auto_round.logger import logger+++def _rtn_phase_line(norm: float, quant: float, n: int, mean: float, max_: float) -> str:+ """Format the zero-shot RTN phase breakdown for AR_PERF_COUNTERS."""+ return f"[perf] rtn phases: norm={norm:.2f}s quant={quant:.2f}s (n={n}, mean={mean:.3f}s, max={max_:.3f}s)"++from auto_round.utils import (SUPPORTED_LAYER_TYPES,check_to_quantized,)from auto_round.utils.device_manager import device_manager--_EXPERT_BATCH_MAX_ELEMS = 2**28 # ~1 GiB fp32 stacked weights per batched call--_EXPERT_RE = re.compile(r"^(?P<parent>.*)\.experts\.\d+\.(?P<proj>[^.]+)$")+from auto_round.utils.perf_counters import _PerfCounters@register_pipeline_member(RTNConfig)@@ -140,200 +144,66 @@ class OptimizedRTNQuantizer(RTNQuantizer):input_ids: Raw token IDs from the tokenizer (unused in RTN).**kwargs: Reserved for forward-compatibility with future parameters."""- # Normalize imatrix (cheap elementwise divides), then quantize the- # block's target modules - same-shape expert projections batched into- # single stacked search calls when the search is active- targets = []- for name, m in block.named_modules():+ # Normalize imatrix first (cheap, serial), then quantize layers. The+ # optimized RTN scale search is weight-local (weight + imatrix), so on a+ # block whose layers sit on several devices the searches run in+ # parallel, one worker per device.+ import auto_round.envs as _envs+ from auto_round.algorithms.quantization import search_dispatch++ _perf = _PerfCounters()+ _perf.start("norm")+ for _name, m in block.named_modules():if hasattr(m, "imatrix"):m.imatrix /= m.imatrix_cnt- if hasattr(m, "global_name") and check_to_quantized(m):- targets.append(m)- self._quantize_targets(targets)-- def _split_expert_batches(self, targets: list):- """Partition same-shape expert projections into batchable groups.-- Experts of one layer share weight shapes (e.g. 192 x ``[1536, 4096]``- gate/up/down projections). The per-group search is row-independent, so- a whole group can be quantized in one call by stacking weights along- the output dim - same results as per-module calls, one search's worth- of per-module overhead instead of 192.- """- grouped = {}- singles = []- for m in targets:- match = _EXPERT_RE.match(getattr(m, "global_name", "") or "")- if (- match is None- or type(m) is not nn.Linear- or not isinstance(getattr(m, "group_size", None), int)- or getattr(m, "group_size", None) <= 0- or getattr(m, "super_bits", None) is not None- or getattr(m, "data_type", "int") != "int"- or m.weight.shape[1] % m.group_size != 0 # not row-divisible: keep per-module- or getattr(m, "act_bits", 16) <= 8 # act-quant layers need the per-module wrapper path- ):- singles.append(m)- continue- key = (- match["parent"],- match["proj"],- tuple(m.weight.shape),- m.bits,- m.group_size,- bool(getattr(m, "sym", False)),- )- grouped.setdefault(key, []).append(m)- batches = []- for g in grouped.values():- if len(g) >= 2:- batches.append(g)- else:- singles.extend(g) # singleton groups must stay per-module, never dropped- return batches, singles+ _perf.stop("norm")+ _perf.start("quant")+ work = [m for _name, m in block.named_modules() if hasattr(m, "global_name") and check_to_quantized(m)]- def _expert_search_active(self) -> bool:- """Whether the optimized-RTN NeUQI search runs for expert modules.-- Mirrors the MoE heuristic in ``_quantize_layer_via_rtn``: experts skip- the search unless explicitly forced on (``enable_opt_rtn``), so batching- must not change that decision - only batch when the search would run.- Both symmetry classes search under ``enable_neuqi`` (asym: joint- (scale, zp); sym: two-stage scale), so both batch.- """- cfg = self.config- if bool(getattr(cfg, "disable_opt_rtn", False)):- return False- if getattr(cfg, "orig_disable_opt_rtn", None) is None and getattr(self.model_context, "is_moe_model", False):- return False- return bool(getattr(cfg, "enable_neuqi", False))-- def _quantize_expert_batch(self, mods: list, device) -> list:- """Quantize same-shape expert projections in one stacked search call.-- Returns the modules NOT quantized here (empty list = success); the- caller falls back to per-module calls for them. Reproduces the- per-module wrapper outputs: quantize-dequantized weights written in- place, plus ``scale``/``zp``/``q_scale_thresh``/``data_type``- attributes matching the unwrapper's conventions. On a mid-batch- failure (e.g. OOM) already-written modules keep their results and- only the remainder is returned -- per-module fallback must never- re-quantize an already quantized-dequantized weight.- """- m0 = mods[0]- bits, g = m0.bits, m0.group_size- sym = bool(getattr(m0, "sym", False))- # mirror the wrapper's threshold rule: fp32-scale modules use a tighter- # q_scale_thresh than the fp16 default- scale_dtype = getattr(m0, "scale_dtype", torch.float16)- q_scale_thresh = 1e-8 if scale_dtype == torch.float32 else 1e-5- resolved_dtype = "opt_rtn_int_sym_neuqi" if sym else "opt_rtn_int_asym"- try:- if sym:- from auto_round.data_type.neuqi import quant_tensor_opt_rtn_sym_neuqi- else:- from auto_round.data_type.neuqi import quant_tensor_opt_rtn_asym- except ImportError:- return list(mods)-- max_elems = _EXPERT_BATCH_MAX_ELEMS- per_call = max(1, max_elems // m0.weight.numel())- # divisibility is guaranteed by _split_expert_batches; re-checked here- # so a direct call can never half-write a chunk before bailing out- if any(m.weight.shape[1] % g != 0 for m in mods):- return list(mods)- written = 0 # modules fully quantized so far (chunk writes are atomic)- try:- for s in range(0, len(mods), per_call):- chunk = mods[s : s + per_call]- dev = torch.device(device)- weights = torch.cat([m.weight.data.reshape(m.weight.shape[0], -1) for m in chunk], dim=0).to(dev)- imat_rows = []- for m in chunk:- if hasattr(m, "imatrix"):- imat_rows.append(m.imatrix.to(dev).unsqueeze(0).expand(m.weight.shape[0], -1))- if imat_rows and len(imat_rows) < len(chunk): # mixed: fill gaps uniformly- it = iter(imat_rows)- imat_rows = [- next(it) if hasattr(m, "imatrix") else torch.ones(m.weight.shape, device=dev) for m in chunk- ]- # uniform weighting needs no materialized tensor: qw=None is- # bit-identical to a full ones imatrix and skips ~module-size- # allocations per expert- imat = torch.cat(imat_rows, dim=0) if imat_rows else None- if dev.type == "cuda":- torch.cuda.synchronize(dev)-- if sym:- # returns follow the quant_tensor_opt_rtn_sym conventions: the- # zero point is the scalar nmax- qdq, scale, zp = quant_tensor_opt_rtn_sym_neuqi(- weights,- bits=bits,- group_size=g,- v=0.0,- q_scale_thresh=q_scale_thresh,- imatrix=imat,- scale_dtype=scale_dtype,- )- else:- qdq, scale, zp = quant_tensor_opt_rtn_asym(- weights,- bits=bits,- group_size=g,- v=0.0,- q_scale_thresh=q_scale_thresh,- imatrix=imat,- scale_dtype=scale_dtype,- )-- if dev.type == "cuda":- torch.cuda.synchronize(dev)- row_w = row_g = 0- with torch.no_grad():- for m in chunk:- out = m.weight.shape[0]- n_groups_m = out * (m.weight.shape[1] // g)- m.weight.data.copy_(qdq[row_w : row_w + out].reshape(m.weight.shape).to(m.weight.device))- m.scale = scale[row_g : row_g + n_groups_m].reshape(out, -1).to("cpu")- if sym:- m.zp = zp- else:- m.zp = zp[row_g : row_g + n_groups_m].reshape(out, -1).to("cpu")- m.q_scale_thresh = q_scale_thresh- m.data_type = resolved_dtype- m.weight.grad = None- row_w += out- row_g += n_groups_m- written = s + len(chunk)- if dev.type == "cuda":- torch.cuda.synchronize(dev)- except torch.OutOfMemoryError:- # fall back to per-module calls for the unwritten remainder only:- # smaller transients, identical results, no double quantization- pass- return mods[written:]-- def _quantize_targets(self, targets: list) -> None:- """Quantize a block's target modules; same-shape expert groups in one- stacked search call each (row-independent search: results identical to- per-module calls)."""- if not targets:- return- batches = []- if self._expert_search_active():- batches, targets = self._split_expert_batches(targets)- if batches:- n_batched = sum(len(b) for b in batches)- logger.info(- "[OptRTN] expert batching: %d expert modules in %d batched groups.",- n_batched,- len(batches),- )- device = device_manager.device- for b in batches:- for m in self._quantize_expert_batch(b, device):- self.quantize_layer_outside_block(m) # unwritten remainder: per-module fallback- for m in targets:+ def _quantize_counted(m):+ _l0 = _ptime.perf_counter()self.quantize_layer_outside_block(m)+ _perf.observe("quant_mod", _ptime.perf_counter() - _l0)++ def _quantize_staged(name, m):+ _l0 = _ptime.perf_counter()+ w = self._quantize_layer_via_rtn(m, defer_search=True)+ _perf.observe("quant_mod", _ptime.perf_counter() - _l0)+ return name, w++ _batching_off = search_dispatch.batched_search_disabled()+ if not _batching_off or not search_dispatch.cross_device_search_disabled():+ from auto_round.algorithms.quantization.rtn.batched_search import run_batched_rtn_search++ staged = []+ for m in work:+ name, w = _quantize_staged(getattr(m, "global_name", None) or "", m)+ if w is not None: # None = OOM fallback already finished it serially+ staged.append((name, w))+ if _batching_off:+ # batching disabled but idle-device spreading on: execute the+ # searches PER-MODULE on borrowed workers (max_batch=1 ->+ # singleton chunks, zero stacking -- same search per module as+ # the serial lane, placed on any viable device). The strict+ # serial baseline for A/B is AR_DISABLE_CROSS_DEVICE_SEARCH=1.+ run_batched_rtn_search(self.model, staged, max_batch=1)+ search_dispatch.log_engaged_once("per-module rtn search (batching disabled, idle devices)")+ else:+ run_batched_rtn_search(self.model, staged)+ search_dispatch.log_engaged_once("batched rtn search")+ else:+ for m in work:+ _quantize_counted(m)+ _perf.stop("quant")+ if _perf.enabled:+ _n = _perf.counts.get("quant_mod", 0)+ logger.info(+ "%s",+ _rtn_phase_line(+ _perf.get("norm"),+ _perf.get("quant"),+ _n,+ _perf.get("quant") / max(_n, 1),+ _perf.maxima.get("quant_mod", 0.0),+ ),+ )diff --git a/auto_round/algorithms/quantization/search_dispatch.py b/auto_round/algorithms/quantization/search_dispatch.pynew file mode 100644index 000000000..e8fd4b090--- /dev/null+++ b/auto_round/algorithms/quantization/search_dispatch.py@@ -0,0 +1,810 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""Run weight-local quantization searches in parallel, one worker per weight device.++Some quantization searches only read the module's own weight (plus small+per-module statistics such as the imatrix) and never touch calibration+activations. When the block's weights are sharded across several GPUs such+searches can run directly on the device that already hosts each weight: no+copies, no mirrors, and the devices naturally share the work. This module+provides the generic grouping/execution helpers used by the wrapper and RTN+search loops.++Searches that depend on activations (e.g. the AWQ clip search) are not+weight-local and must stay on their serial paths.+"""++import contextlib+import threading+import time+from collections import OrderedDict+from collections.abc import Callable, Iterable, Iterator+from typing import Any++import torch++import auto_round.envs as envs+from auto_round.logger import logger+from auto_round.utils.device import is_hpu_lazy_mode, probe_usable_bytes+from auto_round.utils.oom import dump_oom_tensor_census_ # re-exported for existing call sites+from auto_round.utils.perf_counters import perf_counters_enabled+from auto_round.wrapper import WrapperLinear+++def group_items_by_device(+ items: Iterable[Any],+ device_of: Callable[[Any], str | None],+ none_key: str = "uncategorized",+) -> "OrderedDict[str, list[tuple[int, Any]]]":+ """Group ``(index, item)`` pairs by ``device_of(item)`` preserving input order.++ Args:+ items: Iterable of items to group.+ device_of: Callable mapping an item to a device key (str or torch.device).+ none_key: Bucket label for items whose device is ``None``.++ Returns:+ ``OrderedDict[device_key, list[(index, item)]]`` with devices in first-seen+ order and items in original order within each device.+ """+ groups = OrderedDict()+ for idx, item in enumerate(items):+ key = device_of(item)+ if key is None:+ key = none_key+ groups.setdefault(key, []).append((idx, item))+ return groups+++def _null_ctx() -> Iterator[None]:+ yield+++def _device_worker_ctx(key: str) -> contextlib.AbstractContextManager:+ """Launch-context for a worker thread pinned to one accelerator family.++ cuda/xpu workers get the family's device context so ops land on the weight+ device even when the ambient current device differs; anything else (cpu,+ unknown families, or a torch build without that context manager) runs+ bare -- explicit-device ops (``.to(dev)`` / stacked inputs) still land+ correctly, the context only pins implicit device selection.+ """+ try:+ dev = torch.device(key)+ except (ValueError, RuntimeError): # unparsable key: run bare+ return _null_ctx()+ if dev.type == "cuda" and torch.cuda.is_available():+ return torch.cuda.device(dev)+ if dev.type == "xpu" and hasattr(torch, "xpu") and hasattr(torch.xpu, "device"):+ try:+ return torch.xpu.device(dev)+ except Exception as e: # pragma: no cover - defensive+ logger.warning("[search] xpu device context unavailable (%s); running unpinned", e)+ return _null_ctx()+ return _null_ctx()+++def run_items_by_device(+ groups: "OrderedDict[str, list[tuple[int, Any]]]",+ fn: Callable[[int, Any], Any],+ use_cuda_ctx: bool = True,+) -> None:+ """Run ``fn(item)`` for every grouped item, one worker thread per device group.++ A single group is executed inline on the calling thread. Any exception raised+ by ``fn`` is re-raised on the calling thread after all workers joined+ (fail-visible: search failures are never silently swallowed).++ Args:+ groups: Output of :func:`group_items_by_device`.+ fn: Callable executed as ``fn(index, item)``; must be safe to run+ concurrently across groups (items within one group run serially on+ their worker).+ use_cuda_ctx: Wrap each accelerator worker in its family's device+ context (cuda/xpu) so ops land on the weight device even when the+ ambient current device differs; other families run bare.+ """+ if len(groups) <= 1:+ for _idx, item in next(iter(groups.values()), []):+ fn(_idx, item)+ return++ first_error = []+ error_lock = threading.Lock()+ threads = []++ def _worker(device_key: str, indexed_items: list[tuple[int, Any]]) -> None:+ try:+ key = str(device_key)+ with _device_worker_ctx(key) if use_cuda_ctx else _null_ctx():+ for _idx, item in indexed_items:+ fn(_idx, item)+ except BaseException as exc: # noqa: B036 - re-raised below, never swallowed+ with error_lock:+ if first_error:+ logger.error(+ "[batched-search] worker %s also failed (%r); raising the first failure",+ device_key,+ exc,+ )+ else:+ first_error.append(exc)++ for device_key, indexed_items in groups.items():+ if not indexed_items:+ continue+ t = threading.Thread(target=_worker, args=(device_key, indexed_items), name=f"search-dispatch-{device_key}")+ t.start()+ threads.append(t)+ for t in threads:+ t.join()+ if first_error:+ raise first_error[0]+++def cross_device_search_disabled() -> bool:+ """Kill switch for running batched searches on idle devices."""+ return bool(envs.AR_DISABLE_CROSS_DEVICE_SEARCH)+++def pick_search_worker_devices(+ working_set_bytes: int, home_device: str | None = None, margin_bytes: int = 512 * 2**20+) -> list[str]:+ """Viable worker devices for a batched search chunk, in device-index order.++ The searches are weight-local (weight + imatrix only), so the home device+ is preferred whenever it has headroom for the chunk's working set;+ devices that hold no model weights at all serve as overflow for chunks+ whose home device is too full (e.g. --device_map 0 with more cards+ visible). The home device participates like any other candidate; when+ nothing fits, the home device is returned so the caller keeps today's+ behavior and relies on the per-chunk OOM fallback.++ Device families enumerate through their own APIs (cuda, xpu, hpu, mps),+ so offload engages wherever the free-memory probe works. HPU lazy mode+ is the exception: lazy tensors execute on per-thread device contexts, so+ a stacked search spread onto worker threads reaches the write-back's+ host copy with lazy tensors that have no storage attached+ (``data_ptr()`` fails). HPU lazy searches therefore stay on the home+ device -- stacked batching still runs there, inline on the calling+ thread; compile mode (the eager pipeline) spreads like any other family.+ """+ if cross_device_search_disabled():+ return [home_device] if home_device is not None else []+ home_type = str(home_device).split(":")[0] if home_device else ""+ if home_type == "hpu" and is_hpu_lazy_mode():+ return [home_device] if home_device is not None else []+ try:+ from auto_round.utils.device_manager import get_ar_device++ count = get_ar_device(home_type).device_count() if home_type else 0+ except Exception as e: # pragma: no cover - exotic backends+ logger.warning("[search] device enumeration failed (%s); keeping searches on the home device", e)+ count = 0+ if count == 0:+ return [home_device] if home_device is not None else []+ viable = []+ for idx in range(count):+ key = f"{home_type}:{idx}"+ free = probe_usable_bytes(key)+ if free is None or free - margin_bytes < working_set_bytes:+ continue+ viable.append(key)+ if not viable:+ return [home_device] if home_device is not None else []+ return viable+++_ENGAGED_LOGGED = set()+++def log_engaged_once(label: str) -> None:+ """Log the batching engagement once per process (INFO, no counters).++ Detailed per-block counters are intentionally not emitted here; they belong+ to the perf-counter infrastructure of the parallel-tuning work.+ """+ if label in _ENGAGED_LOGGED:+ return+ _ENGAGED_LOGGED.add(label)+ logger.info("[batched-search] %s: running weight-local searches with one worker per device", label)+++def batched_search_disabled() -> bool:+ """Kill switch for the batched search machinery (stacking + per-device workers)."""+ return bool(envs.AR_DISABLE_BATCHED_SEARCH)+++def _wrap_batch_device_of(inputs: tuple[Any, ...]) -> str:+ return str(inputs[0].device)+++def _fn_key(fn: Callable[..., Any]) -> str | tuple[Any, ...]:+ """Stable, safe key term for a resolved search callable.++ Plain functions key by identity location (same function = same behavior);+ ``functools.partial`` objects key by their visible captures; anything else+ (e.g. a per-call closure, whose captures are not introspectable) keys by+ ``repr`` so it never merges with a lookalike. Merging two different searches+ into one stacked batch would silently apply the wrong math to one side, so+ unknown callables always stay separate.+ """+ import functools++ if isinstance(fn, functools.partial):+ kwargs = tuple(sorted(fn.keywords.items(), key=lambda kv: str(kv[0])))+ try:+ qualname = fn.func.__qualname__+ module = fn.func.__module__+ except AttributeError as e: # pragma: no cover - exotic callables+ logger.debug("[batched-search] partial target %r has no qualname (%s); keying by repr", fn.func, e)+ return repr(fn)+ return ("partial", module, qualname, fn.args, kwargs)+ if callable(fn):+ if getattr(fn, "__closure__", None):+ # a per-call closure shares (module, qualname) with its siblings+ # from the same factory; its captures are not introspectable, so+ # key by repr and never merge lookalikes into one batch+ return ("closure", repr(fn))+ try:+ return ("fn", fn.__module__, fn.__qualname__)+ except AttributeError as e: # pragma: no cover - exotic callables+ logger.debug("[batched-search] callable %r has no qualname (%s); keying by repr", fn, e)+ return repr(fn)+ return repr(fn)+++_NON_STACKABLE_SEARCH_NAMES = {"search_nvfp4_scale", "opt_rtn_fast_nvfp4"}+++def _search_fn_stackable(fn: Callable[..., Any]) -> bool:+ """Whether a resolved search/quant callable is safe to call on a stacked batch.++ The nv-fp4 init-scale search internally flattens its scale buffer+ (``nv_fp4`` returns ``[numel/group, 1]``) while its loss/mask keep the+ batch dims, so a stacked call faults with a mask/tensor shape mismatch;+ the OptRTN nv quant func routes through the same search. Those callables+ must stay per-module until the search itself is made batch-aware.+ """+ fn = getattr(fn, "_torchdynamo_orig_callable", None) or fn+ fn = getattr(fn, "func", None) or fn # unwrap functools.partial+ return getattr(fn, "__name__", "") not in _NON_STACKABLE_SEARCH_NAMES+++def _wrap_batch_key(inputs: tuple[Any, ...]) -> tuple[Any, ...]:+ weight, _data_type, bits, imatrix_raw, thresh, search_fn = inputs+ return (+ str(weight.device),+ tuple(weight.shape),+ str(weight.dtype),+ bits,+ float(thresh),+ imatrix_raw is not None,+ _fn_key(search_fn),+ )+++def _materialize_wrap_imatrix(chunk: list[WrapperLinear], stacked_w: torch.Tensor) -> torch.Tensor:+ """Chunk-time imatrix stack from the staged RAW column vectors.++ None means uniform importance: an all-None chunk (the default tuning+ lane) becomes one ``ones_like`` allocation instead of N expanded copies.+ """+ raws = [w._deferred_search_inputs[3] for w in chunk]+ if raws[0] is None:+ return torch.ones_like(stacked_w)+ from auto_round.data_type.utils import reshape_imatrix_for_weight++ return torch.stack(+ [+ reshape_imatrix_for_weight(r, w._deferred_search_inputs[0], w.orig_layer.group_size)+ for r, w in zip(raws, chunk)+ ]+ )+++_WRAP_BATCH_MAX_ELEMS = 2**28 # ~1 GiB fp32 stacked weights per batched call (matches the NeUQI expert batching)+++def _wrap_batch_max_elems() -> "int | None":+ """Element budget per stacked batch; AR_SEARCH_BATCH_GB overrides in GiB of fp32 weights.++ Override-only: unset means the batch size is capacity-driven (the probed+ free VRAM against the search's transient footprint), so roomy devices use+ proportionally larger batches. Invalid values raise (the env parser's+ ValueError) instead of silently falling back to a default budget.+ """+ gb = envs.AR_SEARCH_BATCH_GB+ if gb is not None:+ return max(int(gb * 2**30 // 4), 1)+ return None+++def _is_neuqi_search(fn) -> bool:+ """Whether a staged search/quant callable routes through the NeUQI grids."""+ fn = getattr(fn, "_torchdynamo_orig_callable", None) or fn+ fn = getattr(fn, "func", None) or fn # unwrap functools.partial+ return getattr(fn, "__module__", "").endswith("neuqi")+++def search_transient_bytes(search_fn, total_elements: int) -> int:+ """Peak VRAM one stacked search call needs, beyond the stacked input.++ The grid searches materialize an fp32 copy chain over the batch (inputs,+ loss temporaries): ~16 B per element, the expanded imatrix included via+ the caller's element count. NeUQI-class searches add their internal+ sweep budget ONCE PER CALL: the sweeps cap every [chunk, candidates,+ group] temporary at ``_MAX_TMP_ELEMS`` elements regardless of the grid+ sizes (a wider grid only processes more row-chunks), and a handful of+ those temporaries are live at once -- the budget does not scale with the+ number of stacked modules.+ """+ total = total_elements * 4 * 4+ if _is_neuqi_search(search_fn):+ from auto_round.data_type.neuqi import _MAX_TMP_ELEMS++ total += _MAX_TMP_ELEMS * 4 * 8+ return total+++def search_sweep_budget(search_fn) -> int:+ """The per-call (chunk-size-independent) part of a search's transient."""+ if _is_neuqi_search(search_fn):+ from auto_round.data_type.neuqi import _MAX_TMP_ELEMS++ return _MAX_TMP_ELEMS * 4 * 8+ return 0+++def _plan_capacity_chunks(entries: list) -> list:+ """Per-device batch caps with count-balanced work spread.++ ``entries`` items are ``(home_key, per_module_bytes, sweep_bytes, max_modules,+ modules)``; the returned items are ``(worker_key, home_key, chunk_modules)``.++ Free VRAM is probed on every candidate device (all visible cuda devices+ through ``pick_search_worker_devices``; kill switch honored). A device's+ batches are sized so ONE chunk's transient -- the per-module copy chain+ times the module count plus the per-call sweep budget -- fits in half its+ probed free VRAM: chunks on a device run serially (one worker thread per+ executing device), so only each single chunk must fit, and roomy devices+ take proportionally larger batches than tight ones. Each module+ stays on its home while the home is a candidate and holds less than its+ fair share of the work; the overflow goes to the least-assigned candidate.+ A placement that already spans every device therefore moves nothing, a+ tight home keeps chewing through its share in small batches, and+ concentrated homes spill onto idle devices. An unprobeable home falls+ back to fixed-width chunks at home.++ Estimates guide this planner only: the execute-time headroom guards and+ the OOM ladder own real overflow.+ """+ usable_cache: OrderedDict[str, int | None] = OrderedDict()++ def _usable(dev: str):+ if dev not in usable_cache:+ usable_cache[dev] = probe_usable_bytes(dev)+ return usable_cache[dev]++ grand = sum(len(modules) for _home, _per, _sweep, _max_n, modules in entries)+ counts: OrderedDict[str, int] = OrderedDict()++ plans: list = []+ for home, per, sweep, max_n, modules in entries:+ workers = pick_search_worker_devices(per + sweep, home_device=home)+ if home in workers:+ cands = [home] + [w for w in workers if w != home]+ else:+ cands = list(workers) if workers else [home]+ n_max = {}+ for d in cands:+ u = _usable(d)+ if u is None:+ n_max[d] = max_n+ else:+ n_max[d] = max(1, min(max_n, (u // 2 - sweep) // max(per, 1)))+ counts.setdefault(d, 0)+ share = max(1, -(-grand // len(cands))) # a device's fair share of the work+ alloc: OrderedDict[str, list] = OrderedDict((d, []) for d in cands)+ for m in modules:+ if home in cands and counts.get(home, 0) < share:+ d = home # resident modules stay put while home holds its share+ else:+ d = min(cands, key=lambda k: (counts.setdefault(k, 0), cands.index(k)))+ alloc[d].append(m)+ counts[d] = counts.get(d, 0) + 1+ for d in cands:+ cap = n_max[d]+ for start in range(0, len(alloc[d]), cap):+ plans.append((d, home, alloc[d][start : start + cap]))+ return plans+++def run_batched_wrap_search(deferred_wrappers: list[WrapperLinear], max_batch: int | None = None) -> bool:+ """Run deferred weight-local wrap searches on stacked same-shape batches.++ Wrappers stage ``(weight_reshape, data_type, bits, imatrix, q_scale_thresh,+ search_fn)`` tuples in ``_deferred_search_inputs``, where ``search_fn`` is the+ exact callable the per-module path would have invoked (resolved at wrap time,+ so future dispatch changes -- e.g. alternative optimized searches -- travel+ with the module automatically). Modules whose staged key+ ``(device, shape, weight dtype, bits, threshold, search_fn)`` matches are+ stacked along a leading dim and searched with ONE ``search_fn`` call: the+ per-row math is unchanged (row-independent reductions over the last dim), so+ results are bit-identical to the per-module path while python/launch overhead+ drops by the batch factor. Batches are capped by ``max_batch`` and by a VRAM+ budget on the home device. Chunks are then planned centrally: every chunk+ starts on the device that already holds its weights, and chunks rebalance+ onto under-loaded viable devices so the search uses every visible device+ with headroom. Execution uses one worker thread per executing device --+ each device is owned by exactly one thread, keeping the searches'+ per-grid-step host syncs private. Singleton groups take the identical+ per-module call on the calling thread.++ Returns True when the inputs were consumed; False when batching is disabled+ by AR_DISABLE_BATCHED_SEARCH (the caller then runs the searches per module).+ """+ if batched_search_disabled():+ return False+ if not deferred_wrappers:+ return False++ device_groups = OrderedDict()+ for w in deferred_wrappers:+ inputs = w._deferred_search_inputs+ if inputs is None:+ raise RuntimeError(+ f"{type(w).__name__} was queued for batched wrap search without staged inputs; "+ "the defer_search flag never reached its search init"+ )+ dev = _wrap_batch_device_of(inputs)+ device_groups.setdefault(dev, []).append(w)++ singletons: list[tuple[str, WrapperLinear]] = []+ plan_entries: list[tuple[str, int, int, int, list[WrapperLinear]]] = []+ for dev, wrappers in device_groups.items():+ by_key = OrderedDict()+ for w in wrappers:+ by_key.setdefault(_wrap_batch_key(w._deferred_search_inputs), []).append(w)+ for group in by_key.values():+ if len(group) < 2 or not _search_fn_stackable(group[0]._deferred_search_inputs[5]):+ singletons.extend((dev, w) for w in group)+ continue+ inputs0 = group[0]._deferred_search_inputs+ elements = inputs0[0].numel() * (2 if inputs0[3] is not None else 1)+ per_module = elements * 4 * 4 # the fp32 copy chain per module+ sweep = search_sweep_budget(inputs0[5])+ max_n = 1024 if max_batch is None else max(1, max_batch)+ elem_cap = _wrap_batch_max_elems()+ if elem_cap is not None:+ max_n = min(max_n, max(1, elem_cap // max(elements, 1)))+ plan_entries.append((dev, per_module, sweep, max_n, group))++ # capacity-weighted planning: chunks form directly on the device that+ # runs them, sized to its tracked headroom (see _plan_capacity_chunks)+ planned = _plan_capacity_chunks(plan_entries)+ chunks = [(home, chunk) for _worker, home, chunk in planned]++ # Phase 3: one worker thread per executing device, and each device is+ # owned by exactly one thread. The grid searches end every step with a+ # host sync, so two threads sharing one device's default stream convoy+ # each other; exclusive buckets keep every sync private.+ buckets: OrderedDict[str, list[tuple[str, list[WrapperLinear]]]] = OrderedDict()+ for worker, home, chunk in planned:+ buckets.setdefault(worker, []).append((home, chunk))++ stats = {wk: {"modules": 0, "batches": 0, "singletons": 0} for wk in buckets}++ @torch.no_grad()+ def _run_one(wrapper: WrapperLinear) -> None:+ inputs = wrapper._deferred_search_inputs+ if inputs is None:+ return+ weight, _data_type, bits, imatrix_raw, _thresh, search_fn = inputs+ from auto_round.data_type.utils import reshape_imatrix_for_weight++ imatrix = reshape_imatrix_for_weight(imatrix_raw, weight, wrapper.orig_layer.group_size)+ wrapper.finalize_batched_search(search_fn(weight, bits, imatrix))++ @torch.no_grad()+ def _chunk_transient(chunk: list[WrapperLinear]) -> int:+ inputs0 = chunk[0]._deferred_search_inputs+ elements = inputs0[0].numel() * (2 if inputs0[3] is not None else 1)+ return search_transient_bytes(inputs0[5], elements * len(chunk))++ @torch.no_grad()+ def _run_chunk_stacked(home_key: str, chunk: list[WrapperLinear], worker_key: str) -> None:+ """One stacked search call, halved when the executing device lacks headroom.++ Plan-time estimates can drift; this check runs at the moment of truth.+ """+ if len(chunk) > 1:+ usable = probe_usable_bytes(worker_key)+ if usable is not None and usable - 512 * 2**20 < _chunk_transient(chunk):+ mid = len(chunk) // 2+ _run_chunk_stacked(home_key, chunk[:mid], worker_key)+ _run_chunk_stacked(home_key, chunk[mid:], worker_key)+ return+ inputs0 = chunk[0]._deferred_search_inputs+ _bits = inputs0[2]+ search_fn = inputs0[5]+ if worker_key != home_key:+ # never carry a home-compiled closure onto another device:+ # dynamo guards are device-pinned (recompile zoo) -- the+ # eager original (when exposed) is device-agnostic+ _eager_fn = getattr(search_fn, "_torchdynamo_orig_callable", None)+ if _eager_fn is not None:+ search_fn = _eager_fn+ # stack directly on the worker so the home device never holds the+ # assembled batch (its modules' weights stay resident there)+ stacked_w = torch.stack([w._deferred_search_inputs[0].to(worker_key, non_blocking=True) for w in chunk])+ else:+ stacked_w = torch.stack([w._deferred_search_inputs[0] for w in chunk])+ stacked_im = _materialize_wrap_imatrix(chunk, stacked_w)+ if worker_key != home_key and torch.is_tensor(stacked_im) and stacked_im.device != stacked_w.device:+ # the expanded imatrix stack materializes from home-resident staged+ # columns; move it beside the stacked weights before the search+ stacked_im = stacked_im.to(worker_key, non_blocking=True)+ try:+ results = search_fn(stacked_w, _bits, stacked_im)+ except torch.OutOfMemoryError:+ logger.warning(+ "[batched-search] stacked wrap search OOM (%d modules); finishing this chunk "+ "per-module (shrink batches with AR_SEARCH_BATCH_GB or disable with "+ "AR_DISABLE_BATCHED_SEARCH=1)",+ len(chunk),+ )+ dump_oom_tensor_census_("wrap search")+ for w in chunk:+ w._run_deferred_search_now()+ stats[worker_key]["singletons"] += len(chunk)+ return+ if worker_key != home_key:+ if torch.is_tensor(results):+ results = results.to(home_key)+ else:+ results = [r.to(home_key) if torch.is_tensor(r) else r for r in results]+ for w, res in zip(chunk, results):+ w.finalize_batched_search(res)+ stats[worker_key]["batches"] += 1+ stats[worker_key]["modules"] += len(chunk)++ @torch.no_grad()+ def _execute(worker_key: str, items: list[tuple[str, list[WrapperLinear]]]) -> None:+ _t0 = time.perf_counter()+ for home_key, chunk in items:+ _run_chunk_stacked(home_key, chunk, worker_key)+ stats[worker_key]["wall"] = time.perf_counter() - _t0++ # singleton groups and non-stackable searches run per module on the+ # calling thread, each on its own weight's device+ for _dev, w in singletons:+ _run_one(w)+ _n_single = len(singletons)++ if len(buckets) > 1:+ pairs = list(buckets.items())+ keyed = group_items_by_device(pairs, device_of=lambda p: p[0])+ run_items_by_device(keyed, lambda _idx, p: _execute(p[0], p[1]))+ elif buckets:+ wk, items = next(iter(buckets.items()))+ _execute(wk, items)+ _t_total = sum(st.get("wall", 0.0) for st in stats.values())+ _n_mod = sum(st["modules"] for st in stats.values()) + _n_single+ _n_batch = sum(st["batches"] for st in stats.values())+ from auto_round.utils.pool_placement import _short_device_key++ per_device = (+ "{" + ", ".join(f"'{_short_device_key(dev)}': {st.get('wall', 0.0):.2f}" for dev, st in stats.items()) + "}"+ )+ _n_offloaded = sum(1 for worker, home, _chunk in planned if worker != home)+ if perf_counters_enabled():+ logger.info(+ "[batched-search] wrap search: %d modules, %d batch + %d singleton search calls"+ + (f" ({_n_offloaded} chunk(s) offloaded to idle devices)" if _n_offloaded else "")+ + ", %.2fs device-wall (%.2fs summed) walls %s",+ _n_mod,+ _n_batch,+ _n_single,+ max(st.get("wall", 0.0) for st in stats.values()) if stats else 0.0,+ _t_total,+ per_device,+ )+ return True+++def run_batched_neuqi_anchors(deferred_wrappers: list) -> bool:+ """Run deferred NeUQI grid anchors on stacked same-shape batches.++ The tuning-path anchor search (``neuqi_anchor_margins``) is weight-local+ and per-group, so same-shape modules stack into one call with bit-identical+ margins. Chunking follows the AR_SEARCH_BATCH_GB element budget; worker+ assignment uses the same home-first balanced planner and exclusive+ one-thread-per-device execution as ``run_batched_wrap_search`` (the anchor+ grids contain no host syncs, but exclusivity keeps the dispatch uniform);+ a stacked call that OOMs finishes its chunk per module.++ Returns True when the anchors were consumed; False when batching is+ disabled by AR_DISABLE_BATCHED_SEARCH (the caller runs each anchor per+ module).+ """+ if batched_search_disabled():+ return False+ if not deferred_wrappers:+ return True++ from auto_round.data_type.neuqi import _prepare_neuqi_qw, neuqi_anchor_margins++ def _staged(w):+ staged = getattr(w, "_deferred_neuqi_anchor", None)+ if staged is None:+ raise RuntimeError(+ f"{type(w).__name__} was queued for the batched NeUQI anchor without staged inputs; "+ "the defer_search flag never reached the anchor init"+ )+ return staged++ def _anchor_key(staged):+ weight, bits, group_size, imatrix, sym = staged+ return (str(weight.device), tuple(weight.shape), bits, group_size, sym, imatrix is not None)++ def _anchor_chunk_transient(staged_list) -> int:+ from auto_round.data_type.neuqi import _MAX_TMP_ELEMS++ # the anchor runs the NeUQI sweeps on the stacked batch: an fp32 copy+ # chain over the batch (stacked and flattened inputs, importance+ # weights, and the sweeps' full-size intermediates -- about sixteen+ # weight-sized fp32 buffers are live at peak) that scales with the+ # module count, plus the sweeps' internal temporary budget, which is+ # capped at _MAX_TMP_ELEMS elements regardless of the grid sizes and+ # does not scale with the number of stacked modules+ staged0 = staged_list[0]+ per = staged0[0].numel() * 4 * 16+ if staged0[3] is not None:+ per += staged0[0].numel() * 4+ return per * len(staged_list) + _MAX_TMP_ELEMS * 4 * 8++ singletons: list = []+ plan_entries: list[tuple[str, int, int, int, list]] = []+ by_key: OrderedDict[tuple, list] = OrderedDict()+ for w in deferred_wrappers:+ by_key.setdefault(_anchor_key(_staged(w)), []).append(w)+ from auto_round.data_type.neuqi import _MAX_TMP_ELEMS++ for group in by_key.values():+ if len(group) < 2:+ singletons.extend(group)+ continue+ staged0 = _staged(group[0])+ # same element accounting as the wrap lane: the expanded imatrix+ # reaches the weight's size, so it counts against the override budget+ elements_per_module = staged0[0].numel() * (2 if staged0[3] is not None else 1)+ per_module = staged0[0].numel() * 4 * 16 + (staged0[0].numel() * 4 if staged0[3] is not None else 0)+ sweep = _MAX_TMP_ELEMS * 4 * 8+ max_n = 1024+ elem_cap = _wrap_batch_max_elems()+ if elem_cap is not None:+ max_n = min(max_n, max(1, elem_cap // max(elements_per_module, 1)))+ plan_entries.append((str(staged0[0].device), per_module, sweep, max_n, group))++ # capacity-weighted planning: anchor chunks form directly on the device+ # that runs them, sized to its tracked headroom (see _plan_capacity_chunks)+ planned = _plan_capacity_chunks(plan_entries)+ staged_all = [[_staged(w) for w in chunk] for _worker, _home, chunk in planned]++ buckets: OrderedDict[str, list] = OrderedDict()+ for worker, _home, chunk in planned:+ buckets.setdefault(worker, []).append(chunk)++ stats = {wk: {"modules": 0, "batches": 0, "singletons": 0} for wk in buckets}++ @torch.no_grad()+ def _run_anchor_stack(chunk: list, worker_key: str):+ """One stacked anchor call, split in half when the executing device+ lacks headroom for the chunk's real footprint at call time (estimates+ guide the planner; this check runs at the moment of truth)."""+ staged = [_staged(w) for w in chunk]+ need = _anchor_chunk_transient(staged)+ usable = probe_usable_bytes(worker_key)+ if len(chunk) > 1 and usable is not None and usable - 512 * 2**20 < need:+ mid = len(chunk) // 2+ first = _run_anchor_stack(chunk[:mid], worker_key)+ second = _run_anchor_stack(chunk[mid:], worker_key)+ return torch.cat([first[0], second[0]]), torch.cat([first[1], second[1]])+ _bits, _gs, _sym = staged[0][1], staged[0][2], staged[0][4]+ stacked_w = torch.stack([s[0] for s in staged]).reshape(-1, _gs)+ stacked_im = None+ if staged[0][3] is not None:+ # fully-expanded per-module importance weights stack into the+ # anchor's own normalization unchanged (its reshape/expand is+ # a pass-through for an already full-size layout)+ stacked_im = torch.stack([_prepare_neuqi_qw(s[3], s[0], _bits, _gs) for s in staged]).reshape(-1, _gs)+ return neuqi_anchor_margins(stacked_w, _bits, _gs, stacked_im, worker_key, sym=_sym)++ @torch.no_grad()+ def _execute(worker_key: str, chunk_list: list) -> None:+ _t0 = time.perf_counter()+ for chunk in chunk_list:+ staged = [_staged(w) for w in chunk]+ homes = [str(s[0].device) for s in staged]+ _bits, _gs, _sym = staged[0][1], staged[0][2], staged[0][4]+ # the anchor grid works on a flat [groups, group_size] layout;+ # stacking along a leading module axis then flattening preserves+ # each group's rows (row-major), so per-module margins come back+ # as consecutive row blocks+ stacked_w = torch.stack([s[0] for s in staged]).reshape(-1, _gs)+ stacked_im = None+ if staged[0][3] is not None:+ # fully-expanded per-module importance weights stack into the+ # anchor's own normalization unchanged (its reshape/expand is+ # a pass-through for an already full-size layout)+ stacked_im = torch.stack([_prepare_neuqi_qw(s[3], s[0], _bits, _gs) for s in staged]).reshape(-1, _gs)+ try:+ wmin, wmax = _run_anchor_stack(chunk, worker_key)+ except torch.OutOfMemoryError:+ logger.warning(+ "[batched-search] stacked NeUQI anchor OOM (%d modules); finishing this chunk "+ "per-module (shrink batches with AR_SEARCH_BATCH_GB or disable with "+ "AR_DISABLE_BATCHED_SEARCH=1)",+ len(chunk),+ )+ dump_oom_tensor_census_("neuqi anchor")+ for w in chunk:+ w._run_deferred_neuqi_anchor_now()+ stats[worker_key]["singletons"] += len(chunk) # counted like the wrap lane's fallbacks+ continue+ wmin = wmin.reshape(len(chunk), -1)+ wmax = wmax.reshape(len(chunk), -1)+ for w, s, mn, mx in zip(chunk, staged, wmin, wmax):+ w._apply_neuqi_anchor(mn.to(s[0].device), mx.to(s[0].device))+ stats[worker_key]["batches"] += 1+ stats[worker_key]["modules"] += len(chunk)+ stats[worker_key]["wall"] = time.perf_counter() - _t0++ for w in singletons:+ w._run_deferred_neuqi_anchor_now()++ if len(buckets) > 1:+ pairs = list(buckets.items())+ keyed = group_items_by_device(pairs, device_of=lambda p: p[0])+ run_items_by_device(keyed, lambda _idx, p: _execute(p[0], p[1]))+ elif buckets:+ wk, items = next(iter(buckets.items()))+ _execute(wk, items)++ _t_total = sum(st.get("wall", 0.0) for st in stats.values())+ _n_single = len(singletons) + sum(st["singletons"] for st in stats.values())+ _n_mod = sum(st["modules"] for st in stats.values()) + _n_single+ _n_batch = sum(st["batches"] for st in stats.values())+ _n_offloaded = sum(1 for worker, home, _chunk in planned if worker != home)+ from auto_round.utils.pool_placement import _short_device_key++ per_device = (+ "{" + ", ".join(f"'{_short_device_key(dev)}': {st.get('wall', 0.0):.2f}" for dev, st in stats.items()) + "}"+ )+ if perf_counters_enabled():+ logger.info(+ "[batched-search] neuqi anchors: %d modules, %d batch + %d singleton search calls"+ + (f" ({_n_offloaded} chunk(s) offloaded to idle devices)" if _n_offloaded else "")+ + ", %.2fs device-wall (%.2fs summed) walls %s",+ _n_mod,+ _n_batch,+ _n_single,+ max(st.get("wall", 0.0) for st in stats.values()) if stats else 0.0,+ _t_total,+ per_device,+ )+ return Truediff --git a/auto_round/algorithms/quantization/sign_round/quantizer.py b/auto_round/algorithms/quantization/sign_round/quantizer.pyindex 914a12686..15c429dd9 100644--- a/auto_round/algorithms/quantization/sign_round/quantizer.py+++ b/auto_round/algorithms/quantization/sign_round/quantizer.py@@ -12,6 +12,7 @@# See the License for the specific language governing permissions and# limitations under the License.import copy+import time as _ptimefrom collections.abc import Callablefrom contextlib import nullcontextfrom typing import TYPE_CHECKING, Any@@ -19,6 +20,7 @@ from typing import TYPE_CHECKING, Anyimport torchfrom torch import autocast+from auto_round.algorithms.block_runner import BlockForwardRunnerfrom auto_round.algorithms.quantization.base import BaseQuantizerfrom auto_round.algorithms.quantization.sign_round.config import SignRoundConfigfrom auto_round.algorithms.quantization.sign_round.sign_sgd import SignSGD@@ -26,8 +28,65 @@ from auto_round.algorithms.registry import register_pipeline_memberfrom auto_round.compressors.utils import (IndexSampler,collect_best_params,+ snapshot_best_params,)from auto_round.logger import logger+from auto_round.utils.perf_counters import _PerfCounters+++def resolve_loss_device(loss_device, primary_device):+ """The tune loop's staging device: a concrete device, coalescing None.++ The placement pass may store ``None`` (and ``tensor.to(None)`` is a silent+ no-op), which would strand batch outputs on the block's exit device; the+ loop always stages on a concrete device, defaulting to the primary.+ """+ return loss_device or primary_device+++def _log_tune_phases(perf: _PerfCounters, iters: int) -> None:+ """Derive the loop split and log the per-block tune phase line."""+ if not perf.enabled:+ return+ serial = perf.get("s_fwd") + perf.get("s_loss") + perf.get("s_bwd")+ rest = max(perf.get("loop") - perf.get("sampler") - perf.get("snap") - perf.get("step") - serial, 0.0)+ perf.set("lp_sampler", perf.get("sampler"))+ perf.set("lp_snap", perf.get("snap"))+ perf.set("lp_step", perf.get("step"))+ perf.set("lp_rest", rest)+ perf.set("lp_serial", serial)+ logger.info("%s", _tune_phase_line(perf.totals, iters))+++def _tune_phase_line(phases: dict, iters: int) -> str:+ """Format the per-block tuning phase breakdown for AR_PERF_COUNTERS.++ ``wrap`` = wrapper_block (params init, quant-func resolve + optional+ per-wrapper torch.compile, SignRoundV2 init-scale search -- batched+ same-shape when eligible); ``prepare`` = tuning-param collection ++ optimizer/scheduler build + sampler setup; ``loop`` = the iteration+ try/finally; ``tail`` = best-params restore, clear_memory, unwrapping.+ The optional ``loop`` split appears when counters ran: ``sampler`` =+ index draw, ``snap`` = best-params snapshots, ``step`` = gradient+ sync + optimizer step, ``serial: fwd+loss+bwd`` = the inline forward,+ loss (incl. the .item() drain) and backward of every serial batch.+ """+ line = (+ f"[perf] tune phases (iters={iters}):"+ f" wrap={phases.get('wrap', 0.0):.2f}s prepare={phases.get('prepare', 0.0):.2f}s"+ f" loop={phases.get('loop', 0.0):.2f}s tail={phases.get('tail', 0.0):.2f}s"+ )+ if "lp_sampler" in phases:+ line += (+ f" (loop: sampler={phases['lp_sampler']:.2f}s snap={phases['lp_snap']:.2f}s"+ f" step={phases['lp_step']:.2f}s rest={phases['lp_rest']:.2f}s"+ )+ if phases.get("lp_serial", 0.0):+ line += f" serial: fwd+loss+bwd={phases['lp_serial']:.2f}s"+ line += ")"+ return line++from auto_round.utils import (htcore,is_hpex_available,@@ -385,7 +444,11 @@ class SignRoundQuantizer(BaseQuantizer):empty dict if no trainable parameters were found."""device = device_manager.device- loss_device = getattr(self, "_loss_device", device)+ # None coalesces to the primary: an explicit None from the placement pass+ # must leave the loop with a concrete staging device; pred/ref and the+ # loss mask all stage here (card-0-risk relocation may move it off the+ # primary, and the masked loss multiplies pred by the mask)+ loss_device = resolve_loss_device(getattr(self, "_loss_device", None), device)card_0_in_high_risk = getattr(self, "_card_0_in_high_risk", False)mid_iter_mem_check = self.compress_context.low_gpu_mem_usage and card_0_in_high_risk@@ -401,6 +464,8 @@ class SignRoundQuantizer(BaseQuantizer):active_inputs = q_inputs if (q_inputs is not None and self.enable_quanted_input) else fp_inputsnsamples = len(active_inputs) if isinstance(active_inputs, list) else self._count_samples(active_inputs)+ _perf = _PerfCounters()+ _perf.start("wrap")quantized_layer_names, unquantized_layer_names = self.wrapper_block(block,self.enable_minmax_tuning,@@ -409,6 +474,8 @@ class SignRoundQuantizer(BaseQuantizer):device=device,enable_neuqi=getattr(self.config, "enable_neuqi", False),)+ _perf.stop("wrap")+ _perf.start("prepare")round_params = []minmax_params = []@@ -519,6 +586,44 @@ class SignRoundQuantizer(BaseQuantizer):and (loss_device is None or torch.device(loss_device) == torch.device(device)))+ _perf.stop("prepare")+ _perf.start("loop")+ # iters>0 hot-pool strategy (loop-amortized; the iters=0 lane streams+ # its pools once and never reaches these pulls): each pool moves in+ # bulk onto the device that reads it every iteration -- the input+ # pool onto the entry device (BlockForwardRunner.device, where the+ # forward gathers each batch), the fp reference pool onto the loss+ # device. Both gates charge ACTUAL data: exact tuning state from the+ # wrapper walker, and (input pull) the routed-buffer budget proven on+ # the mapped-streaming lane -- tokens x top_k hidden rows as in/out+ # accumulators plus the backward grad (x6), reproducing the loop+ # retention from shapes alone. Declined pulls keep the per-batch+ # gather.+ self.maybe_adapt_moe_implementation(block, active_inputs, batch_size)+ _entry_dev = str(getattr(block_fwd, "device", device)) if block_fwd is not None else str(device)+ if isinstance(active_inputs, list):+ active_inputs = self.pull_tuning_pool(+ active_inputs,+ _entry_dev,+ block,+ batch_size,+ "tune] block input activations",+ charge_activation=True,+ )+ # the diffusion tuning cache requires its pools on the host (it+ # stages batches to the GPU itself via pinned slots); a bulk pull+ # onto the loss device would put the cached reference outputs on+ # cuda and the cache would decline every batch signature+ if fp_outputs and loss_device is not None and not use_tuning_cache:+ fp_outputs = self.pull_tuning_pool(+ fp_outputs,+ loss_device,+ block,+ batch_size,+ "tune] fp reference outputs",+ charge_activation=False,+ )+try:for i in range(self.iters):# Auto observes a complete forward/backward/optimizer iteration@@ -541,21 +646,35 @@ class SignRoundQuantizer(BaseQuantizer):for n, m in block.named_modules():m.cur_iter = itotal_loss = 0+ _perf.start("sampler")global_indices = index_sampler.next_batch()if valid_token_mask:num_elm = self._get_non_zero_cnt(valid_token_mask, global_indices)+ _perf.stop("sampler")for batch_start in range(0, len(global_indices), batch_size):indices = global_indices[batch_start : batch_start + batch_size]+ _perf.start("s_fwd")staged = tuning_cache.get(indices) if tuning_cache is not None else Noneif staged is None:- ref_output = torch.cat([fp_outputs[i] for i in indices], dim=0).to(loss_device)+ # fp_outputs may be sharded across park devices+ # (--calibration_data_device): gather onto one device+ # before cat. Uniform-device selections are returned+ # untouched (byte-identical to the single-device path);+ # tensors are immutable, so concurrent gather is safe.+ _sel = [fp_outputs[i] for i in indices]+ _gather = BlockForwardRunner._gather_same_device(+ _sel, str(loss_device) if loss_device is not None else str(_sel[0].device)+ )+ ref_output = torch.cat(_gather, dim=0).to(loss_device)pred_output = block_fwd.forward(block, active_inputs, input_others, indices, _fwd_cache_device)else:ref_output = staged[2]pred_output = tuning_cache.forward(block, staged, _fwd_cache_device)if loss_device is not None:pred_output = pred_output.to(loss_device)+ _perf.stop("s_fwd")+ _perf.start("s_loss")if (block_ctx.block_index == block_ctx.block_cnt - 1and self.enable_lfq@@ -568,15 +687,21 @@ class SignRoundQuantizer(BaseQuantizer):torch.cat([input_ids[i] for i in indices], dim=0),)else:- loss = self._get_loss(pred_output, ref_output, indices, mse_loss, device, valid_token_mask)+ # the mask must land on the same device pred/ref were staged+ # on (loss_device, which card-0-risk relocation may move off+ # the primary), not on the primary unconditionally+ loss = self._get_loss(pred_output, ref_output, indices, mse_loss, loss_device, valid_token_mask)num_elm = 1 if num_elm <= 0 else num_elmtotal_loss += loss.item() / num_elm+ _perf.stop("s_loss")+ _perf.start("s_bwd")if mid_iter_mem_check:# clear memory to avoid OOM due to memory fragmentationclear_memory_if_reached_threshold(threshold=0.5, device_list=device_manager.device_list)self._scale_loss_and_backward(scaler, loss)+ _perf.stop("s_bwd")if mid_iter_mem_check:# clear memory to avoid OOM due to memory fragmentation@@ -587,31 +712,37 @@ class SignRoundQuantizer(BaseQuantizer):current_lr = optimizer.param_groups[0]["lr"]logger.debug("iter %d loss: %.3e lr: %s", i, total_loss, current_lr)+ _perf.start("snap")if total_loss < best_loss:best_loss = total_lossif not self.not_use_best_mse:best_params = (tuning_cache.collect_best_params()if tuning_cache is not None and tuning_cache.best is not None- else collect_best_params(block, self.compress_context.cache_device)+ else snapshot_best_params(block, self.compress_context.cache_device))last_best_iter = iif self.not_use_best_mse and i == self.iters - 1:best_params = (tuning_cache.collect_best_params()if tuning_cache is not None and tuning_cache.best is not None- else collect_best_params(block, self.compress_context.cache_device)+ else snapshot_best_params(block, self.compress_context.cache_device))+ _perf.stop("snap")+ _perf.start("step")if not self.not_use_best_mse:if 0 < self.dynamic_max_gap <= i - last_best_iter:breaksync_gradients()self._step(scaler, optimizer, lr_schedule)+ _perf.stop("step")finally:if tuning_cache is not None:tuning_cache.close()+ _perf.stop("loop")+ _perf.start("tail")last_loss = total_lossbest_iter = self.iters@@ -635,6 +766,9 @@ class SignRoundQuantizer(BaseQuantizer):with torch.no_grad():unwrapper_block(block, best_params)+ _perf.stop("tail")+ _log_tune_phases(_perf, self.iters)+if self.config.is_act_nv_fp:# enable moe experts act_max automatic generation for WrapperWALayerset_amax_for_all_moe_layers(block, attr_name="orig_layer.act_max")@@ -891,7 +1025,13 @@ class SignRoundQuantizer(BaseQuantizer):The scaled loss."""scale_loss = loss * 1000- scale_loss.backward()+ try:+ scale_loss.backward()+ except torch.OutOfMemoryError:+ from auto_round.algorithms.quantization.search_dispatch import dump_oom_tensor_census_++ dump_oom_tensor_census_("tune backward")+ raiseif is_hpex_available():htcore.mark_step()return scale_lossdiff --git a/auto_round/algorithms/quantization/sign_roundv2/quantizer.py b/auto_round/algorithms/quantization/sign_roundv2/quantizer.pyindex 0d4b44fc4..114f3c906 100644--- a/auto_round/algorithms/quantization/sign_roundv2/quantizer.py+++ b/auto_round/algorithms/quantization/sign_roundv2/quantizer.py@@ -40,6 +40,7 @@ from auto_round.data_type.utils import (get_optimized_quant_func,reshape_imatrix_for_weight,reshape_pad_tensor_by_group_size,+ resolve_optimized_init_scale_fn,revert_tensor_by_pad,round_ste,search_optimized_init_scale,@@ -102,31 +103,65 @@ def _dq_asym_group_size(bits: int) -> int:class SignRoundOptimizedWrapperLinear(WrapperLinear):minmax_scale_bound = (0.0, 2.0)+ # Opt-in protocol for wrapper_block: the init-scale search is weight-local+ # and row-independent, so same-shape modules can be searched as one stacked+ # batch (bit-identical per module, far fewer python/launch round-trips).+ supports_batched_search = True- def _init_tuning_params_and_quant_func(self):- super()._init_tuning_params_and_quant_func()+ def _init_tuning_params_and_quant_func(self, defer_search: bool = False) -> None:+ super()._init_tuning_params_and_quant_func(defer_search=defer_search)layer = self.orig_layerdata_type = layer.data_typeweight_reshape = self._prepare_init_scale_weight()- imatrix = reshape_imatrix_for_weight(getattr(layer, "imatrix", None), weight_reshape, layer.group_size)+ # staged deferral keeps only the RAW column imatrix (or None): the+ # expanded full-size copy would be pinned per module for the whole+ # wrap phase -- N x weight bytes -- while the batched call needs it+ # only transiently per chunk (bounded by the batch cap)+ imatrix_raw = getattr(layer, "imatrix", None)+ imatrix = None if defer_search else reshape_imatrix_for_weight(imatrix_raw, weight_reshape, layer.group_size)- self.init_scale = search_optimized_init_scale(- weight_reshape, data_type, layer.bits, imatrix, self.q_scale_thresh- )self.weight_quant_func = get_optimized_quant_func(data_type)- if self.init_scale is None or self.weight_quant_func is None:+ search_fn = resolve_optimized_init_scale_fn(data_type, self.q_scale_thresh)+ if search_fn is None or self.weight_quant_func is None:raise ValueError(f"SignRound optimized path does not support data_type={data_type!r}; ""expected a symmetric int / mx / nv type.")-self.data_type = data_type+ self.init_scale = None+ self._deferred_search_inputs = None+ if defer_search:+ # staged for run_batched_wrap_search: the exact callable the+ # per-module path would invoke travels with the module+ self._deferred_search_inputs = (+ weight_reshape,+ data_type,+ layer.bits,+ imatrix_raw,+ self.q_scale_thresh,+ search_fn,+ )+ else:+ self.init_scale = search_fn(weight_reshape, layer.bits, imatrix)+if hasattr(layer, "imatrix"):del layer.imatrixif self.enable_torch_compile:self.weight_quant_func = compile_func(self.weight_quant_func, self.device)+ def _run_deferred_search_now(self) -> None:+ """Run the staged search per-module (fallback when batching is off)."""+ weight, _data_type, bits, imatrix_raw, _thresh, search_fn = self._deferred_search_inputs+ imatrix = reshape_imatrix_for_weight(imatrix_raw, weight, self.orig_layer.group_size)+ self.init_scale = search_fn(weight, bits, imatrix)+ self._deferred_search_inputs = None++ def finalize_batched_search(self, init_scale: "torch.Tensor | list[torch.Tensor]") -> None:+ """Adopt a search result computed on a stacked same-shape batch."""+ self.init_scale = init_scale+ self._deferred_search_inputs = None+def _prepare_init_scale_weight(self) -> torch.Tensor:"""Return the group-reshaped weight that seeds the init-scale search.@@ -175,7 +210,9 @@ class SignRoundDQWrapperLinear(WrapperLinear):self.prev_d_scale = Noneself.prev_d_wmin = None- def _init_tuning_params_and_quant_func(self):+ def _init_tuning_params_and_quant_func(self, defer_search: bool = False):+ # the DQ scale search stays inline; the parameter keeps the base-class+ # call signature uniform (staged batching applies to the optimized path)super()._init_tuning_params_and_quant_func()# The double-quant search path is data-dependent and kept un-compiled,# while ``weight_quant_func`` is the compilable pure-math half.diff --git a/auto_round/algorithms/quantization/tune_memory.py b/auto_round/algorithms/quantization/tune_memory.pynew file mode 100644index 000000000..21af915b5--- /dev/null+++ b/auto_round/algorithms/quantization/tune_memory.py@@ -0,0 +1,654 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+# License for the specific language governing permissions and limitations+# under the License.+"""Tune-loop memory model, MoE-implementation policy, and pool pulls.++Shared by the quantizer base class (the ``maybe_adapt_moe_implementation``+and ``pull_tuning_pool`` hooks) so individual algorithm implementations stay+free of fleet-memory policy: everything here reads only the block's wrapper+layout, the batch size, the run's config, and the devices' free memory.+"""++from typing import Any++import torch++from auto_round.logger import logger+++def _tuning_state_bytes(block: torch.nn.Module, target_dev: str) -> int:+ """In-loop tuning state for parameters homed on ``target_dev`` (logical count).++ 14 B per logical parameter: fp32 value + fp32 grad (first backward) ++ best-params snapshot + bf16 copy. At tune time ``block.parameters()``+ yields BOTH the original weights and the wrappers' registered value+ params -- counting both would price every wrapped parameter twice.+ Wrapper tuning tensors are identified by identity (any ``.params``+ dict on a module) and excluded; the original weights carry the charge.+ """+ return _logical_state_by_device(block).get(str(target_dev), 0)+++def _logical_state_by_device(block: torch.nn.Module) -> dict[str, int]:+ """Deduped per-device form of :func:`_tuning_state_bytes` ({device: bytes}).++ ``_state_bytes_by_device`` counts ``block.parameters()`` raw, which at+ tune time includes BOTH the original weights and the wrappers' fp32+ value params -- every wrapped parameter priced twice.+ """+ tuning = set()+ for m in block.modules():+ _p = getattr(m, "params", None)+ if isinstance(_p, dict):+ for _v in _p.values():+ if torch.is_tensor(_v):+ tuning.add(id(_v))+ out = {}+ for p in block.parameters():+ if id(p) in tuning:+ continue+ out[str(p.device)] = out.get(str(p.device), 0) + p.numel() * 14+ return out+++def _ensure_routed_shape_recorders_(block: torch.nn.Module) -> None:+ """Attach fire-once recorders on MoE containers for the activation budget.++ Records ``top_k = top_k_index.shape[-1]`` and ``routed_rows = index.numel()``+ from the first NATURAL dispatch (forced all-experts routing -- tracing /+ warmup -- is skipped: it would record top_k = num_experts and over-reserve).+ Layout-agnostic: no attribute spellings, only arg shapes. The experts+ interface passes ``(hidden_states, top_k_index, top_k_weights)``; the+ recorder reads the two leading tensor args. The hook removes itself after+ the first record.+ """+ from auto_round.modeling.fused_moe.utils import force_all_experts_routing_enabled++ if force_all_experts_routing_enabled():+ return+ from auto_round.utils import SUPPORTED_LAYER_TYPES+ from auto_round.utils.model import is_moe_layer++ def _record(module: torch.nn.Module, args: Any) -> None:+ recorded = False+ try:+ tensors = [a for a in args if torch.is_tensor(a)]+ if len(tensors) < 2:+ return+ hidden, index = tensors[0], tensors[1]+ if hidden.ndim < 2 or index.ndim < 1:+ return+ module._routed_shape_rec_ = (int(index.shape[-1]), int(index.numel()))+ recorded = True+ logger.debug(+ "[routed-shape] recorded top_k=%d routed_rows=%d",+ module._routed_shape_rec_[0],+ module._routed_shape_rec_[1],+ )+ except Exception as e: # pragma: no cover - diagnostics only, never break the forward+ logger.debug("[routed-shape] recorder skipped (%s)", e)+ finally:+ if recorded:+ # self-remove ONLY on a successful record: removing on a+ # miss (non-dispatch arg shapes) silently disarms the+ # recorder before it ever sees a natural dispatch+ for handle in list(getattr(module, "_routed_rec_handles_", [])):+ handle.remove()+ module._routed_rec_handles_ = []++ def _is_experts_container(name: str, module: torch.nn.Module) -> bool:+ # container may carry the marker itself, expose num_experts, be a+ # ModuleList, or carry the MoE marker only on an ANCESTOR container+ if is_moe_layer(module) or isinstance(getattr(module, "num_experts", None), int):+ return True+ stem = name+ while "." in stem:+ stem = stem.rsplit(".", 1)[0]+ mod = mods.get(stem)+ if mod is not None and (is_moe_layer(mod) or isinstance(getattr(mod, "num_experts", None), int)):+ return True+ return False++ def _can_host_recorder(module: torch.nn.Module) -> bool:+ # Only dispatch containers receive (hidden, top_k_index,+ # top_k_weights). Leaf projections (plain Linear/Conv1D) and tuning+ # wrappers (orig_layer child) see per-row activations only: their+ # pre-hook can never record, never self-removes, and lingers for the+ # whole block -- which disqualifies the projection in the+ # grouped-experts support gate and forces every tune iteration onto+ # the per-expert linear_loop.+ if hasattr(module, "orig_layer"):+ return False+ return not isinstance(module, SUPPORTED_LAYER_TYPES)++ mods = dict(block.named_modules())+ for _name, module in mods.items():+ if (+ "expert" in _name.lower()+ and _is_experts_container(_name, module)+ and _can_host_recorder(module)+ and not hasattr(module, "_routed_shape_rec_")+ ):+ module._routed_rec_handles_ = [module.register_forward_pre_hook(_record)]+++def _grouped_stack_bytes(block: torch.nn.Module, device: str, config: Any = None) -> int:+ """Qdq-stack bytes the grouped experts modes materialize on ``device``."""+ d = _grouped_stack_bytes_detail(block, device, config=config)+ return d["retention"] + d["transient"]+++def _grouped_stack_bytes_detail(block: torch.nn.Module, device: str, config: Any = None) -> dict[str, int]:+ """Per-term split of :func:`_grouped_stack_bytes` (retention + transient).++ Two chunk-aware terms (retention is chunk-independent; transient is+ chunk-sized) for ``auto``/``linear_grouped``/+ ``linear_grouped_sliced`` (linear_loop stacks nothing):++ - retention (chunk-independent): autograd keeps EVERY chunk's stacked+ fp32 values (straight-through mask) and qdq output (GEMM backward) --+ 6 B per weight element of the experts HOMED on the device, observed as+ 31 simultaneous 16-expert stacks on the OOMed lane;+ - transient (chunk-sized): the quant func streams the stacked chunk+ through several passes (~2x chunk bytes). Chunk size comes from the+ same source the grouped path uses (_qdq_chunk_size: AR_MOE_CHUNK or+ the auto working-set budget; 0 = fuse everything = all-experts chunk).++ Mode resolution matches the dispatch: an EXPLICIT env value governs,+ otherwise ``config._experts_implementation`` (so gates stay consistent+ with a mid-run auto switch to linear_loop instead of charging stacks+ for a lane that no longer stacks any). Mode-set-but-loop-ran fallbacks+ can only overcharge -- safe direction.+ """+ import auto_round.envs as _envs+ from auto_round.modeling.fused_moe.moe_experts_interface import GROUPED_LINEAR_IMPL++ mode = str(getattr(_envs, "AR_MOE_EXPERTS_IMPL", "auto") or "auto").lower()+ if mode in ("", "auto"):+ mode = str(getattr(config, "_experts_implementation", GROUPED_LINEAR_IMPL) or GROUPED_LINEAR_IMPL)+ if mode not in ("", "auto", "linear_grouped", "linear_grouped_sliced"):+ return {"retention": 0, "transient": 0}+ retention = 0+ transient = 0+ try:+ from auto_round.modeling.fused_moe.grouped_experts import _qdq_chunk_size+ from auto_round.utils.model import is_moe_layer++ def _is_expert_leaf(name, leaf):+ # expert leaves are named "experts.N.proj" in every unfused layout;+ # the container may carry num_experts, be a ModuleList, or carry+ # the MoE marker only on an ANCESTOR container -- a name-only+ # walk can return 0 stacks and silently disable the activation+ # charge and the auto linear_loop pick+ if "expert" not in name.lower() or "shared" in name.lower():+ # shared experts are plain modules outside the dispatch (the+ # repo's own is_moe_expert predicate excludes them); stacking+ # or routing charges on them are phantom bytes+ return False+ stem = name+ while "." in stem:+ stem = stem.rsplit(".", 1)[0]+ mod = mods.get(stem)+ if mod is None:+ continue+ if (+ isinstance(mod, torch.nn.ModuleList)+ or isinstance(getattr(mod, "num_experts", None), int)+ or is_moe_layer(mod)+ ):+ return True+ return False++ # group leaves by slot name so per-slot chunking matches the real+ # grouped path (gate/up/down are chunked independently)+ mods = dict(block.named_modules())+ by_slot = {}+ seen_weight_ids = set()+ for name, leaf in mods.items():+ # at tune time named_modules yields BOTH the wrapper+ # (...gate_proj) and its orig_layer child (...gate_proj.orig_+ # layer), each exposing a same-shape weight -- counting both+ # doubles retention+ if name.endswith(".orig_layer"):+ continue+ weight = getattr(leaf, "weight", None)+ if weight is None or not hasattr(weight, "numel"):+ continue+ if id(weight) in seen_weight_ids:+ continue+ if not _is_expert_leaf(name, leaf):+ continue+ seen_weight_ids.add(id(weight))+ by_slot.setdefault(type(leaf).__name__ + "." + getattr(leaf, "slot_tag", ""), []).append((leaf, weight))+ for _slot, pairs in by_slot.items():+ local_pairs = [(l, w) for l, w in pairs if str(w.device) == str(device)]+ if not local_pairs:+ continue+ elems = sum(int(w.numel()) for _l, w in local_pairs)+ retention += elems * 6 # fp32 value stack + bf16 qdq output+ try:+ chunk = _qdq_chunk_size([l for l, _w in local_pairs]) # env/budget-aware; 0 = all+ except Exception as e:+ logger.warning("[tune] chunk sizing failed for slot %r on %s (%s); using 16", _slot, device, e)+ chunk = 16+ per_leaf = elems // max(1, len(local_pairs))+ chunk_elems = elems if chunk <= 0 else min(elems, chunk * per_leaf)+ transient += chunk_elems * 6 # ~2 streaming passes over the chunk+ except Exception as e: # pragma: no cover - never break the gate+ logger.warning(+ "[tune] grouped-stack accounting unavailable (%s); continuing with a zero stack charge "+ "(an OOM in the tuned loop after this line is explained by the missing charge)",+ e,+ )+ return {"retention": 0, "transient": 0}+ return {"retention": retention, "transient": transient}+++def _routed_budget_bytes(block: torch.nn.Module, tensors: Any, batch_size: int, config: Any = None) -> int | None:+ """tokens x top_k routed working set x6 (in/out accumulators + bwd grad).++ Top_k resolution order: config values (maintained spelling list) ->+ recorded NATURAL-dispatch arg shapes (layout/spelling agnostic) ->+ container attrs. None when nothing resolves (callers decline).+ """+ from auto_round.utils.device import get_first_available_attr+ from auto_round.utils.model import is_moe_layer++ top_k = None+ if config is not None:+ top_k = get_first_available_attr(config, ["num_experts_per_tok", "moe_num_active_primary_experts"])+ if top_k is None:+ moe_topk = getattr(config, "moe_topk", None) # list-form top_k+ if isinstance(moe_topk, (list, tuple)) and moe_topk:+ top_k = moe_topk[0]+ if top_k is None:+ for m in block.modules():+ rec = getattr(m, "_routed_shape_rec_", None)+ if rec is not None:+ top_k, _rows = rec+ break+ if top_k is None:+ for _name, module in block.named_modules():+ if is_moe_layer(module) or isinstance(getattr(module, "num_experts", None), int):+ top_k = getattr(module, "top_k", None) or getattr(module, "num_experts_per_tok", None)+ if top_k is not None:+ break+ if top_k is None:+ return None+ ref = (+ tensors[0]+ if isinstance(tensors, list) and tensors+ else next(+ (t for t in (tensors.values() if isinstance(tensors, dict) else []) if isinstance(t, torch.Tensor)), None+ )+ )+ if ref is None or ref.ndim < 2:+ return None+ row_len = int(ref.shape[-2]) if ref.ndim >= 3 else int(ref.shape[0])+ hidden_bytes = int(ref.shape[-1]) * ref.element_size()+ tune_tokens = max(1, int(batch_size)) * max(1, row_len)+ routed_rows = None+ for m in block.modules():+ rec = getattr(m, "_routed_shape_rec_", None)+ if rec is not None:+ top_k_rec, routed_rows = rec+ break+ if routed_rows is not None:+ # recorded rows scale per-token to this batch's tokens (collection may+ # have seen a larger batch; a floor-div here silently kept the+ # oversized count)+ seen_tokens = max(1, routed_rows // max(1, int(top_k)))+ routed_rows = int(routed_rows * tune_tokens / seen_tokens)+ else:+ routed_rows = tune_tokens * int(top_k)+ return int(routed_rows * hidden_bytes * 6)+++def _activation_bytes_by_device(+ block: torch.nn.Module, tensors: Any, batch_size: int, config: Any = None+) -> dict[str, int] | None:+ """Per-DEVICE activation charge for the tune loop: {device: bytes}.++ The loop's forward/backward executes on every device the block spans --+ each module's saved output + grad lands on the module's WEIGHT HOME, and+ each expert's routed-row caches land on the expert's home. Charging the+ whole activation budget to the entry alone (the previous form) left the+ MoE stages' transients unpriced while the entry's own charge was+ accurate.++ Terms per device:+ - est split: the estimator's per-module output bytes (x2 grads, expert+ outputs ratio-scaled) bucketed by weight home -- counts shared experts+ wherever they are PLAIN modules outside the dispatch.+ - routed split: tokens x top_k x hidden x 6 distributed across devices+ by homed-expert count (first-order static split; per-expert token+ counts vary with routing draws).+ - grouped stacks: chunk-INDEPENDENT qdq retention, additive (a different+ tensor class entirely).++ Per-device composition is max(est_d, routed_d) -- the terms overlap on+ the routed rows exactly as in the scalar form, per device. None only+ when neither term resolves anywhere (callers decline).+ """+ try:+ from auto_round.utils.device import estimate_tuning_block_mem+ from auto_round.utils.model import is_moe_layer++ est_by_dev = {}+ expert_counts = {}+ est_failed = False+ has_moe = any(is_moe_layer(m) or isinstance(getattr(m, "num_experts", None), int) for m in block.modules())+ try:+ _ld, _la, _io, _ad, est_by_dev, expert_counts = estimate_tuning_block_mem(+ block, tensors, batch_size, config+ )+ except Exception as e: # per-module accounting is best-effort for dense+ logger.warning("[tune] per-module activation estimate unavailable (%s)", e)+ est_failed = True+ if est_failed and has_moe:+ # an MoE block without the estimator loses the expert homes that+ # attribute routed bytes and stacks to devices; the composed+ # charge would collapse toward state-only and keep an+ # over-budget grouped lane -- decline instead+ return None+ if not has_moe:+ expert_counts = {}++ routed_by_dev = {}+ routed_total = None+ # routed x6 was calibrated on the per-expert-loop implementation+ # (per-expert route caches + batch cats). Grouped mode builds no+ # route caches -- its routed working set (sorted flat buffers) is+ # covered by the estimator's ratio-scaled expert outputs, and the+ # weight-side retention arrives via the stacks term. Charging both+ # under grouped mode double-charges and can falsely switch a+ # working grouped lane to the per-expert loop.+ stacks_any = any(+ _grouped_stack_bytes(block, d, config=config) > 0 for d in set(est_by_dev) | set(expert_counts)+ )+ if has_moe and not stacks_any:+ routed_total = _routed_budget_bytes(block, tensors, batch_size, config)+ total_experts = sum(expert_counts.values())+ if routed_total is not None and total_experts > 0:+ routed_by_dev = {d: int(routed_total * c / total_experts) for d, c in expert_counts.items()}+ elif routed_total is not None:+ # no expert homes resolved (detection is name-based): never drop+ # the budget silently -- split evenly across the graph's devices,+ # or onto the pool reference's device when no module info at all+ if est_by_dev:+ n = len(est_by_dev)+ routed_by_dev = {d: int(routed_total / n) for d in est_by_dev}+ logger.debug(+ "[tune] routed budget %.2fGiB split evenly over %d devices (no expert homes)",+ routed_total / 2**30,+ n,+ )+ else:+ ref_dev = None+ if isinstance(tensors, list) and tensors and isinstance(tensors[0], torch.Tensor):+ ref_dev = str(tensors[0].device)+ elif isinstance(tensors, dict):+ for t in tensors.values():+ if isinstance(t, torch.Tensor):+ ref_dev = str(t.device)+ break+ if ref_dev is not None:+ routed_by_dev = {ref_dev: routed_total}++ out = {}+ for d in set(est_by_dev) | set(routed_by_dev):+ # est split is GiB floats (estimator), routed split is bytes+ m = max(int(est_by_dev.get(d, 0.0) * 2**30), int(routed_by_dev.get(d, 0)))+ out[d] = m + _grouped_stack_bytes(block, d, config=config)+ return out or None+ except Exception as e: # pragma: no cover - placement must never break tuning+ logger.warning("[tune] activation estimate failed (%s); treating as unknown", e)+ return None+++def _block_activation_bytes(+ block: torch.nn.Module, tensors: Any, batch_size: int, config: Any = None, device: str | None = None+) -> int | None:+ """Back-compat scalar view: this DEVICE's slice of the per-device charge."""+ by_dev = _activation_bytes_by_device(block, tensors, batch_size, config)+ if by_dev is None:+ return None+ if device is None:+ return max(by_dev.values())+ return by_dev.get(str(device))+++_MOE_IMPL_AUTO_LINEAR_LOOP_DONE = False+_MOE_IMPL_AUTO_DONE_REF = None # weakref to the deciding run's config+++def _maybe_auto_linear_loop_for_tuning(+ block: torch.nn.Module, tensors: Any, batch_size: int, iters: int, config: Any, model: torch.nn.Module+) -> None:+ """One-shot auto pick: ``linear_loop`` when grouped tuning cannot fit.++ Grouped tuning stacks per-expert fp32 value/grad tensors on every+ expert-homing device (chunk-INDEPENDENT autograd retention) ON TOP of the+ in-loop tuning state; when a device cannot hold both beside the reserve,+ the first backward OOMs only after a wasted grouped_mm attempt plus a+ sliced-fallback re-staging. The charges are+ the same ones the placement gates use: per-device tuning state charged+ at 6 of the 14 B/param layout (grads + bf16 are guaranteed in-loop; the+ values are already inside the probed free and the best-params snapshot+ parks to host under pressure) plus the per-device activation budget+ (routed transients on loop lanes, grouped stacks on grouped lanes).+ Any expert-homing device over budget -> switch the WHOLE run to+ linear_loop once, loudly. Explicit AR_MOE_EXPERTS_IMPL choices are never+ overridden.+ """+ global _MOE_IMPL_AUTO_LINEAR_LOOP_DONE, _MOE_IMPL_AUTO_DONE_REF+ import weakref++ _key_obj = config if config is not None else model+ try:+ _key = ("w", weakref.ref(_key_obj)) if _key_obj is not None else ("n", None)+ except TypeError: # non-weakrefable object: fall back to identity+ _key = ("i", id(_key_obj))+ _prev = _MOE_IMPL_AUTO_DONE_REF+ _same = False+ if _prev is not None and _prev[0] == _key[0]:+ if _prev[0] == "w":+ _a, _b = _prev[1](), _key[1]()+ _same = _a is not None and _a is _b # dead ref -> re-decide+ else:+ _same = _prev[1] == _key[1]+ if not _same:+ # a new (or garbage-collected) run's config re-decides: no silent+ # skip for a second model quantized in the same process+ _MOE_IMPL_AUTO_DONE_REF = _key+ _MOE_IMPL_AUTO_LINEAR_LOOP_DONE = False+ if _MOE_IMPL_AUTO_LINEAR_LOOP_DONE or iters is None or int(iters) <= 0:+ return+ from auto_round import envs as _envs_mod+ from auto_round.modeling.fused_moe.moe_experts_interface import GROUPED_LINEAR_IMPL, LINEAR_LOOP_IMPL+ from auto_round.utils.device import probe_usable_bytes+ from auto_round.utils.pool_placement import _RESERVE_BYTES++ requested = str(getattr(_envs_mod, "AR_MOE_EXPERTS_IMPL", "auto") or "auto").lower()+ if requested not in ("", "auto"):+ _MOE_IMPL_AUTO_LINEAR_LOOP_DONE = True # explicit choice governs+ logger.debug("[moe-impl] auto check skipped: explicit AR_MOE_EXPERTS_IMPL=%s", requested)+ return+ # The dispatch reads the MODEL's config; model_context.config may be a+ # separate object that never received _experts_implementation (a silent+ # no-op). Prefer whichever candidate+ # actually carries the attr; switch ALL of them when we switch.+ candidates = [c for c in (config, getattr(model, "config", None)) if c is not None]+ cfg = next((c for c in candidates if getattr(c, "_experts_implementation", None)), None)+ impl = str(getattr(cfg, "_experts_implementation", GROUPED_LINEAR_IMPL)) if cfg is not None else GROUPED_LINEAR_IMPL+ if impl != GROUPED_LINEAR_IMPL:+ logger.debug("[moe-impl] auto check skipped: current impl is %s (not grouped)", impl)+ return+ try:+ state = _logical_state_by_device(block) or {}+ if not state:+ logger.debug("[moe-impl] auto check skipped: no per-device tuning state resolved")+ return+ act = _activation_bytes_by_device(block, tensors, batch_size, cfg) or {}+ if not any(_grouped_stack_bytes(block, d) > 0 for d in state):+ # dense block, loop impl already, or no experts homed: not the+ # decision point yet -- retry on the next block+ logger.debug("[moe-impl] auto check deferred: no grouped stacks homed on any state device")+ return+ over = []+ max_ratio_dev, max_ratio = None, -1.0+ for d, state_bytes in state.items():+ # values (4 B/param) are already inside the probed free here; of+ # the remainder, grads (4) + bf16 copy (2) are guaranteed in-loop,+ # while the best-params snapshot (4) PARKS TO HOST under pressure+ # -- charging it as guaranteed over-declines tight grouped lanes+ # that were working+ remaining_state = state_bytes * 6 // 14+ demand = remaining_state + act.get(d, 0) + _RESERVE_BYTES+ free = probe_usable_bytes(d)+ _st = _grouped_stack_bytes_detail(block, d)+ _est_routed = max(act.get(d, 0) - _st["retention"] - _st["transient"], 0)+ logger.debug(+ "[moe-impl] auto check %s: demand %.2f GiB (state %.2f + act %.2f "+ "[stacks retention %.2f + transient %.2f, est/routed %.2f] + reserve) vs free %.2f GiB",+ d,+ demand / 2**30,+ remaining_state / 2**30,+ act.get(d, 0) / 2**30,+ _st["retention"] / 2**30,+ _st["transient"] / 2**30,+ _est_routed / 2**30,+ -1.0 if free is None else free / 2**30,+ )+ if free is not None:+ ratio = demand / max(int(free), 1)+ if ratio > max_ratio:+ max_ratio, max_ratio_dev = ratio, d+ if demand > int(free):+ over.append((d, demand, int(free), remaining_state, act.get(d, 0)))+ _MOE_IMPL_AUTO_LINEAR_LOOP_DONE = True+ if over:+ d, demand, free, st, ac = over[0]+ logger.info(+ "[moe-impl] auto: grouped tuning needs %.1f GiB on %s (free %.1f: state %.1f + "+ "stacks/transients %.1f + reserve) -- switching this run to %s",+ demand / 2**30,+ d,+ free / 2**30,+ st / 2**30,+ ac / 2**30,+ LINEAR_LOOP_IMPL,+ )+ seen_cfg = {id(c) for c in candidates}+ _nm = getattr(block, "named_modules", None)+ for _n, m in (_nm() if callable(_nm) else []):+ # some archs deepcopy the config per layer; the dispatch+ # reads each module's own config, so switch those too+ c = getattr(m, "config", None)+ if c is not None and id(c) not in seen_cfg:+ candidates.append(c)+ seen_cfg.add(id(c))+ for c in candidates:+ c._experts_implementation = LINEAR_LOOP_IMPL+ elif max_ratio_dev is not None:+ logger.debug(+ "[moe-impl] auto: grouped fits (max demand/free ratio %.2f on %s)",+ max_ratio,+ max_ratio_dev,+ )+ except Exception as e: # never break tuning over an advisory auto-pick+ logger.debug("[moe-impl] auto feasibility check failed (%s); keeping grouped", e)+++def _pull_pool_if_fits(+ pool: Any,+ target_dev: str,+ block: torch.nn.Module,+ batch_size: int,+ iters: int,+ label: str,+ charge_activation: bool = False,+ config: Any = None,+) -> Any:+ """Bulk-move a whole tune-loop pool onto the device that reads it every iteration.++ iters>0 strategy only (loop-amortized): ``active_inputs`` -> the entry+ device the forward gathers onto (BlockForwardRunner.device, home of the+ block's starting modules), ``fp_outputs`` -> the loss device. The iters=0+ lane never calls this -- its pools are single-pass streamed, so a bulk+ move buys nothing. Declines (pool stays sharded behind the per-batch+ gather) unless free(target) covers the pool beside the loop transients+ and the target's own in-loop tuning state (14 B/param), which+ materializes after this probe -- the term that separates the 8-GPU lane+ (pulls) from the 4-GPU lane (declines; peers completed the loop at the+ same state density without the pool). The loss side has no per-iteration+ graph retention (one cat per iteration, freed after the loss -- validated+ by the full 80-block pull run).++ ``charge_activation`` adds the block's ACTUAL activation accounting+ (per-module output shapes, MoE-ratio scaled -- see+ ``_block_activation_bytes``) and is set only for the input pull: the+ entry device carries the loop's forward graph (batch cats + routed-row+ caches materialize along the hidden flow regardless of weight homes).+ """+ if pool is None or target_dev is None:+ return pool+ _act_bytes = _block_activation_bytes(block, pool, batch_size, config, str(target_dev)) if charge_activation else 0+ if charge_activation and _act_bytes is None:+ return pool # unknown activation cost: never pull blind+ _tgt = torch.device(target_dev)+ try:+ tensors = pool if isinstance(pool, list) else None+ if tensors is None or not tensors or not any(hasattr(t, "device") for t in tensors):+ return pool+ if all(t.device == _tgt for t in tensors):+ return pool+ pool_b = sum(t.numel() * t.element_size() for t in tensors)+ if charge_activation:+ pool_b += _act_bytes+ try:+ from auto_round.utils.device import probe_usable_bytes++ free = probe_usable_bytes(str(_tgt))+ except Exception as e: # pragma: no cover - diagnostics only+ logger.warning("[%s] free-memory probe failed for %s (%s); keeping pool sharded", label, _tgt, e)+ free = None+ try:+ from auto_round.utils.pool_placement import _RESERVE_BYTES, _working_allowance_bytes++ reserve = _working_allowance_bytes(block, tensors, batch_size) + _RESERVE_BYTES+ reserve += _tuning_state_bytes(block, _tgt)+ except Exception as e: # pragma: no cover - gate must never break tuning+ logger.warning("[%s] working-set estimate failed (%s); using flat 4GiB reserve", label, e)+ reserve = 4 << 30+ if free is not None and free - reserve >= pool_b:+ moved = [t.to(_tgt) for t in tensors]+ # splice in place: the tune loop rebinds only its local handle+ # while the pool containers (release bookkeeping, snapshots)+ # still hold the ORIGINAL list -- returning a fresh list would+ # keep the source tensors resident next to the pulled copies+ pool[:] = moved+ logger.debug("[%s bulk pull -> %s (%.2f GiB, free %.2f GiB)", label, _tgt, pool_b / 2**30, free / 2**30)+ return pool+ if free is not None:+ logger.debug(+ "[%s stays sharded, per-batch gather (data %.2f GiB + reserve %.2f GiB vs free %.2f GiB on %s)",+ label,+ pool_b / 2**30,+ reserve / 2**30,+ free / 2**30,+ _tgt,+ )+ except Exception as e: # pragma: no cover - placement must never break tuning+ logger.warning("[%s bulk pull failed (%s); keeping data sharded", label, e)+ return pooldiff --git a/auto_round/autoround.py b/auto_round/autoround.pyindex ee58e2fb1..e697a1d43 100644--- a/auto_round/autoround.py+++ b/auto_round/autoround.py@@ -548,6 +548,7 @@ class _CompressorBuilder:format=None,dataset: str | CalibDataset | list | tuple | torch.utils.data.DataLoader | None = None,low_gpu_mem_usage: bool = False,+ calibration_data_device: str = "auto",device_map: str | torch.device | int | dict = 0,iters: int | None = None,enable_torch_compile: bool = False,@@ -676,6 +677,7 @@ class _CompressorBuilder:scheme=scheme,dataset=dataset,low_gpu_mem_usage=low_gpu_mem_usage,+ calibration_data_device=calibration_data_device,device_map=device_map,iters=iters,enable_torch_compile=enable_torch_compile,@@ -732,6 +734,11 @@ class AutoRound:nsamples: Number of calibration samples.batch_size: Calibration batch size.low_gpu_mem_usage: Enable lower-memory calibration at the cost of speed.+ calibration_data_device: Placement of the block calibration-data pools:+ ``"auto"`` (default; primary-first, shard across GPUs when needed),+ ``"off"`` (no placement machinery), ``"cpu"`` (park pools in host+ RAM), or an explicit csv such as ``"cuda:1,cuda:2"``. Forwards still+ run on the compute devices; only the at-rest pool placement changes.device_map: Device or device mapping used for quantization.enable_torch_compile: Whether to use ``torch.compile`` where supported.seed: Random seed used by calibration and tuning.@@ -759,6 +766,7 @@ class AutoRound:batch_size: int = 8,gradient_accumulate_steps: int | None = None,low_gpu_mem_usage: bool = False,+ calibration_data_device: str = "auto",device_map: str | torch.device | int | dict = 0,enable_torch_compile: bool | None = None,seed: int = 42,@@ -796,6 +804,7 @@ class AutoRound:format=runtime_kwargs.pop("format", None),dataset=dataset,low_gpu_mem_usage=low_gpu_mem_usage,+ calibration_data_device=calibration_data_device,device_map=normalize_default_device_map(device_map),iters=None,enable_torch_compile=enable_torch_compile,diff --git a/auto_round/cli/main.py b/auto_round/cli/main.pyindex 05be1767c..546e2df37 100644--- a/auto_round/cli/main.py+++ b/auto_round/cli/main.py@@ -71,6 +71,7 @@ def _build_entry_base_kwargs(args, *, low_cpu_mem_usage, enable_torch_compile, l"nsamples": args.nsamples,"batch_size": args.batch_size,"low_gpu_mem_usage": args.low_gpu_mem_usage,+ "calibration_data_device": args.calibration_data_device,"low_cpu_mem_usage": low_cpu_mem_usage,"device_map": args.device_map,"enable_torch_compile": enable_torch_compile,@@ -238,6 +239,9 @@ def _print_algorithm_help(argv: list[str]) -> bool:def start(recipe="default", argv=None):+ from auto_round.utils.oom import install_oom_census_hook++ install_oom_census_hook() # last-resort tensor census for uncaught CUDA OOMsrecipe_defaults = RECIPES[recipe]argv = list(sys.argv[1:] if argv is None else argv)format_was_explicit = any(diff --git a/auto_round/cli/parser.py b/auto_round/cli/parser.pyindex bad251a7a..1997f5eee 100644--- a/auto_round/cli/parser.py+++ b/auto_round/cli/parser.py@@ -205,6 +205,16 @@ def build_quantize_parser(*, prog: str = "auto_round quantize") -> argparse.Argurt.add_argument("--low_gpu_mem_usage", action="store_true", help="Enable memory-efficient mode by offloading features to CPU.")+ rt.add_argument(+ "--calibration_data_device",+ default="auto",+ type=str,+ help="Device placement for block calibration data (inputs/outputs between blocks): "+ "'auto' (default) keeps the pools on the primary cache device when they fit and spreads "+ "chunks over free GPUs otherwise; 'cpu' parks them on host RAM; 'off' keeps the "+ "single-device behavior; or an explicit device list like 'cuda:1,cuda:2' "+ "(bare indices '1,2' also accepted).",+ )rt.add_argument("--low_cpu_mem_usage",action="store_true",diff --git a/auto_round/compressors/base.py b/auto_round/compressors/base.pyindex bf973f581..da5238d4a 100644--- a/auto_round/compressors/base.py+++ b/auto_round/compressors/base.py@@ -237,6 +237,7 @@ class BaseOrchestrator:format: str | list | None = None,scheme: str | dict | QuantizationScheme | AutoScheme = "W4A16",low_gpu_mem_usage: bool = False,+ calibration_data_device: str = "auto",device_map: str | torch.device | int | dict = 0,enable_torch_compile: bool | None = None,seed: int = 42,@@ -482,6 +483,7 @@ class BaseOrchestrator:low_cpu_mem_usage,low_gpu_mem_usage,enable_torch_compile,+ calibration_data_device=calibration_data_device,formats=self.formats,static_kv_dtype=self.static_kv_dtype,static_attention_dtype=self.static_attention_dtype,diff --git a/auto_round/compressors/diffusion/tuning_cache.py b/auto_round/compressors/diffusion/tuning_cache.pyindex 57581a1c6..cd3fbccfd 100644--- a/auto_round/compressors/diffusion/tuning_cache.py+++ b/auto_round/compressors/diffusion/tuning_cache.py@@ -17,6 +17,7 @@import queueimport randomimport threading+from typing import Anyimport torchfrom torch.utils._pytree import tree_flatten, tree_map@@ -54,6 +55,35 @@ def _signature(batch):return spec, signature+def _signature_decline_reason(batch: Any) -> str | None:+ """First offending leaf that makes :func:`_signature` return None."""+ try:+ from torch.utils._pytree import tree_flatten_with_path++ pairs, _ = tree_flatten_with_path(batch)+ except Exception: # pragma: no cover - fall back to position-only+ pairs = None+ leaves, _ = tree_flatten(batch)+ for pos, value in enumerate(leaves):+ path = ""+ if pairs is not None:+ entry = pairs[pos]+ path = "".join(+ f"[{k!r}]" if isinstance(k, str) else f"[{k}]"+ for k in (entry if isinstance(entry, tuple) else (entry,))+ )+ if isinstance(value, torch.Tensor):+ if value.device.type != "cpu":+ return f"leaf #{pos}{path}: tensor on {value.device} (cpu required)"+ if value.layout != torch.strided:+ return f"leaf #{pos}{path}: non-strided tensor ({value.layout})"+ elif value is None or isinstance(value, (str, bool, int, float)):+ continue+ else:+ return f"leaf #{pos}{path}: unsupported type {type(value).__name__} = {value!r:.60}"+ return "unknown"++def _nbytes(batch):return sum(t.numel() * t.element_size() for t in tree_flatten(batch)[0] if isinstance(t, torch.Tensor))@@ -88,6 +118,10 @@ class DiffusionTuningCache:template = cache._select(first)cache.signature = _signature(template)if cache.signature is None:+ logger.info(+ "Diffusion tuning prefetch skipped: batch signature rejected (%s).",+ _signature_decline_reason(template),+ )return Nonecache.sources = (block.paramsdiff --git a/auto_round/compressors/orchestrator.py b/auto_round/compressors/orchestrator.pyindex 96d1a262a..7e5e20ec9 100644--- a/auto_round/compressors/orchestrator.py+++ b/auto_round/compressors/orchestrator.py@@ -14,7 +14,9 @@import copyimport gcimport os+import threadingimport time+from collections.abc import Callablefrom functools import partialfrom typing import TYPE_CHECKING, Any, Optional@@ -58,6 +60,7 @@ from auto_round.utils.device import (_force_trim_malloc,)from auto_round.utils.device_manager import device_manager+from auto_round.utils.perf_counters import _PerfCountersfrom auto_round.wrapper import WrapperMultiblockif TYPE_CHECKING:@@ -65,6 +68,45 @@ if TYPE_CHECKING:# TODO wenhuach align all the API args+++class _OneDeepWriter:+ """One-deep background task pipeline (used for the shard write/flush).++ ``dispatch`` joins any previous task first (fail-visible: its exception is+ re-raised on the caller thread), then starts the next on a single daemon+ worker. ``join`` blocks until the current task completes and re-raises any+ error it captured. Tasks must touch only their own arguments (host-resident+ tensors; no VRAM) so they can overlap the main thread's GPU work.+ """++ def __init__(self) -> None:+ self._t = None+ self._exc = None++ def dispatch(self, fn: Callable[[], Any]) -> None:+ self.join()+ self._exc = None++ def _run() -> None:+ try:+ fn()+ except BaseException as e: # noqa: B036 - re-raised in join()+ self._exc = e++ self._t = threading.Thread(target=_run, name="one-deep-writer", daemon=True)+ self._t.start()++ def join(self) -> None:+ if self._t is None:+ return+ t, self._t = self._t, None+ t.join()+ if self._exc is not None:+ exc, self._exc = self._exc, None+ raise exc++class CompressionOrchestrator(BaseOrchestrator):def __init__(@@ -173,6 +215,105 @@ class CompressionOrchestrator(BaseOrchestrator):first_input_name=first_input_name,)+ def _attach_pool_placement(+ self, block: torch.nn.Module, input_ids: Any, q_input: Any = None, input_others: Any = None+ ) -> None:+ """Resolve calibration-data placement for the upcoming block and attach it.++ No-op (placement cleared) whenever the policy is off, the lane is+ CPU-parked (low_gpu_mem_usage), or the pool fits the primary device.+ """+ runner = getattr(self.alg_composer, "block_forward", None)+ if runner is None: # pragma: no cover - defensive+ return+ try:+ from auto_round.utils.device_manager import device_manager+ from auto_round.utils.pool_placement import (+ _pool_chunk_count,+ _tensor_bytes,+ calib_data_line,+ consolidate_pool_onto,+ resolve_placement_for_pool,+ )++ chains = 2 if self.alg_composer.need_quanted_input() else 1+ pool_bytes = _tensor_bytes(input_ids) * chains+ n_chunks = _pool_chunk_count(input_ids)+ primary = str(self.compress_context.cache_device)+ mode = getattr(self.compress_context, "calibration_data_device", "auto")+ _iters = int(getattr(getattr(self.alg_composer, "block_quantizer", None), "iters", 0) or 0)+ # iters>0 lane: the tune loop consumes outputs on the block's LOSS+ # device (card_0_in_high_risk deflects it off the cache primary on+ # multi-GPU MoE lanes; set per block by dispatch_block) -- prefer+ # that device for the output pool so the fp-reference bulk pull+ # becomes a no-op and the primary stops accumulating pool chunks.+ # The runner's own .device is NOT it: BlockForwardRunner is built+ # once at orchestrator init with device_manager.device, so it always+ # equals the primary on this lane and the retarget would never fire.+ _loss_dev = getattr(getattr(self.alg_composer, "block_quantizer", None), "_loss_device", None)+ _consumer = str(_loss_dev) if _loss_dev is not None else str(getattr(runner, "device", primary))+ _consumer = (+ _consumer+ if _iters > 0 and _consumer != primary and _consumer.startswith("cuda") and primary.startswith("cuda")+ else None+ )+ placement = resolve_placement_for_pool(+ input_ids,+ chains,+ primary,+ device_manager.device_list,+ block=block,+ batch_size=self.calibration_context.batch_size,+ mode=mode,+ iters=_iters,+ consumer=_consumer,+ config=getattr(getattr(self, "model_context", None), "config", None),+ )+ # Docstring contract: never consolidate when the policy is off, the+ # lane is CPU-parked (low_gpu_mem_usage keeps pools on the host), or+ # the resolved placement itself parks pools on the host (mode=cpu).+ placement_on_host = placement is not None and any(str(_d).startswith("cpu") for _d in placement.devices)+ if mode == "off" or str(primary).startswith("cpu") or placement_on_host:+ runner.pool_placement = placement+ return+ # Fits-home rung: when the incoming (possibly sharded) pools fit on+ # the compute device next to the block's working set AND next to the+ # outputs this block will place there, consolidate them -- the whole+ # block then reads locally and the per-batch gather is a no-op. The+ # reserved-bytes gate exists because the inputs-only budget was the+ # exact cause of the first block-3 OOM.+ target = str(getattr(runner, "device", primary))+ if placement is None:+ reserved = pool_bytes if target == primary else 0+ elif len(placement.devices) == 1:+ reserved = pool_bytes if placement.devices[0] == target else 0+ else:+ per_chunk = pool_bytes / max(n_chunks, 1)+ reserved = int(placement.counts().get(target, 0) * per_chunk)+ consolidate_pool_onto(+ [input_ids, q_input, input_others],+ target,+ block,+ self.calibration_context.batch_size,+ reserved_bytes=reserved,+ iters=_iters,+ )+ logger.debug(+ "[calib-data-device] %s",+ calib_data_line(+ [input_ids, q_input],+ input_others,+ placement,+ pool_bytes,+ n_chunks,+ primary,+ ),+ )+ except Exception as e: # pragma: no cover - placement must never break quantization+ logger.warning("[calib-data-device] attach failed (%s); keeping single-device behavior", e)+ placement = None+ runner.pool_placement = placement+def _quantize_blocks(self,model: torch.nn.Module,@@ -217,6 +358,8 @@ class CompressionOrchestrator(BaseOrchestrator):m.requires_grad_(False)input_ids, input_others = self._preprocess_block_inputs(inputs)+ _bg_writer = _OneDeepWriter()+ _bg_resume = _OneDeepWriter()if resume_input_ids is not None:input_ids = resume_input_ids@@ -224,158 +367,269 @@ class CompressionOrchestrator(BaseOrchestrator):pbar = tqdm(range(0, len(block_names), nblocks))start_index = resume_state.resume_index if resume_state is not None and nblocks == 1 else 0- for i in range(start_index, len(block_names), nblocks):- if input_others_extra_blocks and block_names[i] in input_others_extra_blocks:- input_others = input_others_extra_blocks[block_names[i]]- _, input_others = self._preprocess_block_inputs(input_others)- input_others_extra_blocks.pop(block_names[i])- if i != 0:- pbar.update(1)- if nblocks == 1:- n = block_names[i]- pbar.set_description(f"Quantizing {n}")- m = get_module(model, n)- else:- names = block_names[i : min(i + nblocks, len(block_names))]- pbar.set_description(f"Quantizing [{i + 1}-{min(i + nblocks, len(block_names))}]/{len(block_names)}")- modules = [get_module(model, n) for n in names]- m = WrapperMultiblock(modules)-- # Also reload when disk streaming is active even if `low_cpu_mem_usage`- # has been forced False (e.g. GGUF export -- see base.py's- # `_finalize_compress_context`, which disables `low_cpu_mem_usage` for- # gguf formats for reasons unrelated to disk streaming). Disk streaming- # can be turned on explicitly via `AR_DISK_STREAM_MODEL=1` *or* chosen- # automatically for fused-MoE checkpoints (see ModelContext's- # `_should_use_meta_skeleton`); either way the model was built as a meta- # skeleton and `_disk_stream_index` is set. Under streaming, a block- # starts on the meta device regardless of `low_cpu_mem_usage`, which only- # ever controlled whether to *free* it again after use -- without this,- # the block below is never materialized at all and `m.to(device)` crashes- # with "Cannot copy out of meta tensor". The block intentionally stays- # real afterward (no matching post-tune offload runs when- # `low_cpu_mem_usage` is False -- see the `is_immediate_saving`-adjacent- # offload call further down), matching upstream's own choice not to cycle- # blocks for these formats.- disk_streaming = getattr(self.model_context, "_disk_stream_index", None) is not None- if self.compress_context.low_cpu_mem_usage or envs.AR_DISK_STREAM_MODEL or disk_streaming:+ try:+ for i in range(start_index, len(block_names), nblocks):+ if input_others_extra_blocks and block_names[i] in input_others_extra_blocks:+ input_others = input_others_extra_blocks[block_names[i]]+ _, input_others = self._preprocess_block_inputs(input_others)+ input_others_extra_blocks.pop(block_names[i])+ if i != 0:+ pbar.update(1)if nblocks == 1:- self._offloader.reload(model, n)+ n = block_names[i]+ pbar.set_description(f"Quantizing {n}")+ m = get_module(model, n)else:- self._offloader.reload(model, names)-- block_name_or_names = n if nblocks == 1 else names-- # ── Infrastructure: materialize, dtype convert, device placement ──- materialize_model_(m)- convert_module_to_hp_if_necessary(m, self.model_context.amp_dtype, device_manager.device)+ names = block_names[i : min(i + nblocks, len(block_names))]+ pbar.set_description(+ f"Quantizing [{i + 1}-{min(i + nblocks, len(block_names))}]/{len(block_names)}"+ )+ modules = [get_module(model, n) for n in names]+ m = WrapperMultiblock(modules)++ # Also reload when disk streaming is active even if `low_cpu_mem_usage`+ # has been forced False (e.g. GGUF export -- see base.py's+ # `_finalize_compress_context`, which disables `low_cpu_mem_usage` for+ # gguf formats for reasons unrelated to disk streaming). Disk streaming+ # can be turned on explicitly via `AR_DISK_STREAM_MODEL=1` *or* chosen+ # automatically for fused-MoE checkpoints (see ModelContext's+ # `_should_use_meta_skeleton`); either way the model was built as a meta+ # skeleton and `_disk_stream_index` is set. Under streaming, a block+ # starts on the meta device regardless of `low_cpu_mem_usage`, which only+ # ever controlled whether to *free* it again after use -- without this,+ # the block below is never materialized at all and `m.to(device)` crashes+ # with "Cannot copy out of meta tensor". The block intentionally stays+ # real afterward (no matching post-tune offload runs when+ # `low_cpu_mem_usage` is False -- see the `is_immediate_saving`-adjacent+ # offload call further down), matching upstream's own choice not to cycle+ # blocks for these formats.+ _perf = _PerfCounters()+ _t_reload_start = time.perf_counter()+ disk_streaming = getattr(self.model_context, "_disk_stream_index", None) is not None+ if self.compress_context.low_cpu_mem_usage or envs.AR_DISK_STREAM_MODEL or disk_streaming:+ if nblocks == 1:+ self._offloader.reload(model, n)+ else:+ self._offloader.reload(model, names)+ _t_reload_mark = time.perf_counter()+ # reload duration sits BEFORE the marks' reference point; it is+ # folded into the end-of-block phases line as its first item so+ # the line's total covers the whole block (true-wall comparable)+ block_name_or_names = n if nblocks == 1 else names- m = self.alg_composer.dispatch_block(m, input_ids, input_others)+ # ── Infrastructure: materialize, dtype convert, device placement ──+ materialize_model_(m)+ convert_module_to_hp_if_necessary(m, self.model_context.amp_dtype, device_manager.device)- # ── Pipeline lifecycle: per-block setup ───────────────────────────- from auto_round.algorithms.composer import BlockContext+ m = self.alg_composer.dispatch_block(m, input_ids, input_others)- current_block_names = (- block_name_or_names if isinstance(block_name_or_names, list) else [block_name_or_names]- )- current_block_name = current_block_names[0] if len(current_block_names) == 1 else str(block_name_or_names)- # bs = self.quantizer.batch_size * self.quantizer.infer_bs_coeff #TODO recover infer_bs_coeff- bs = self.calibration_context.batch_size+ # ── Pipeline lifecycle: per-block setup ───────────────────────────+ from auto_round.algorithms.composer import BlockContext- ctx = BlockContext(- model=model,- block_names=current_block_names,- block_name=current_block_name,- block_index=i,- bs=bs,- is_mllm=self.model_context.is_mllm,- is_diffusion=self.model_context.is_diffusion,- pbar=pbar,- block_cnt=(len(block_names) + nblocks - 1) // nblocks,- )+ current_block_names = (+ block_name_or_names if isinstance(block_name_or_names, list) else [block_name_or_names]+ )+ current_block_name = (+ current_block_names[0] if len(current_block_names) == 1 else str(block_name_or_names)+ )+ # bs = self.quantizer.batch_size * self.quantizer.infer_bs_coeff #TODO recover infer_bs_coeff+ bs = self.calibration_context.batch_size- # ── Run block pipeline (calibration → quantization → collection) ──- new_q_input, reference_output = self.alg_composer.compress_block(- m,- input_ids,- input_others,- block_ctx=ctx,- q_inputs=q_input,- input_ids=token_ids,- )+ ctx = BlockContext(+ model=model,+ block_names=current_block_names,+ block_name=current_block_name,+ block_index=i,+ bs=bs,+ is_mllm=self.model_context.is_mllm,+ is_diffusion=self.model_context.is_diffusion,+ pbar=pbar,+ block_cnt=(len(block_names) + nblocks - 1) // nblocks,+ )- # ── Infrastructure: memory management ─────────────────────────────- # Mirrors the original q_input-swap + end-of-loop clear_memory semantics:- # clear the FP input when a quantized input was used, then clear the old- # q_input (effective_input) before advancing to the next block.- if q_input is not None:- if input_ids is not q_input:- clear_memory(input_ids)+ # ── Infrastructure: calibration-data placement (--calibration_data_device)+ # Decide where this block's calibration output pool will live: on the+ # primary cache device when it fits (today's behavior, zero peer+ # traffic), or sharded across free GPUs when it does not. Placement is+ # pure memory behavior -- chunk values are bit-identical.+ self._attach_pool_placement(m, input_ids, q_input, input_others)+ _perf.tick("attach")++ # ── Run block pipeline (calibration → quantization → collection) ──+ new_q_input, reference_output = self.alg_composer.compress_block(+ m,+ input_ids,+ input_others,+ block_ctx=ctx,+ q_inputs=q_input,+ input_ids=token_ids,+ )+ _perf.tick("compress")++ # ── Infrastructure: memory management ─────────────────────────────+ # Mirrors the original q_input-swap + end-of-loop clear_memory semantics:+ # clear the FP input when a quantized input was used, then clear the old+ # q_input (effective_input) before advancing to the next block.+ if q_input is not None:+ if input_ids is not q_input:+ clear_memory(input_ids)+ else:+ clear_memory()+ next_input_ids = reference_output+ clear_memory(q_input if q_input is not next_input_ids else None)else:- clear_memory()- next_input_ids = reference_output- clear_memory(q_input if q_input is not next_input_ids else None)- else:- next_input_ids = reference_output- clear_memory(input_ids if input_ids is not next_input_ids else None)-- q_input = new_q_input-- # ── Infrastructure: hook removal, device cleanup, logging ─────────- if len(device_manager.device_list) > 1 and not self.model_context.is_diffusion:- accelerate.hooks.remove_hook_from_submodules(m)- mv_module_from_gpu(m)- clear_memory(device_list=device_manager.device_list)- memory_monitor.log_summary()+ next_input_ids = reference_output+ clear_memory(input_ids if input_ids is not next_input_ids else None)++ q_input = new_q_input+ _perf.tick("swap")++ # Belt-and-braces: no module may carry staged batched-search inputs+ # (weight reshape + imatrix copies) across the block boundary;+ # otherwise the search-stack groups stay retained into the next+ # block's collection (~GB-class growth per block).+ for _mn, _mm in m.named_modules():+ if getattr(_mm, "_deferred_search_inputs", None) is not None:+ _mm._deferred_search_inputs = None+ _perf.tick("sweep")+ if len(device_manager.device_list) > 1 and not self.model_context.is_diffusion:+ accelerate.hooks.remove_hook_from_submodules(m)+ _perf.tick("hooks")++ # ── Infrastructure: immediate_pack / shard write ──────────────────+ # Pack BEFORE draining the block off the GPUs: pack_layer resolves+ # the math device from layer.weight.device (orig_device), so packing+ # after mv_module_from_gpu drops every module into the CPU packing+ # regime -- a Python per-column qzeros loop at ~50ms/module, tens of+ # seconds per large MoE block. With weights still on their tune+ # devices the math runs on GPU (~2.3ms/module) and the packed+ # artifacts land on host by construction (qweight/qzeros are .to(+ # "cpu") in the packers), so VRAM pressure stays one-module-sized.+ # Hoist the layer-config read out of the module loop: the property+ # rebuilds a copy of the whole compression plan per access (~50ms on+ # a 300B-class plan -- the entire invisible pack wall).+ _layer_cfg = self.layer_config+ if self.compress_context.is_immediate_packing:+ for _n, _mod in m.named_modules():+ if hasattr(_mod, "bits") and check_to_quantized(_mod):+ from auto_round.compressors.utils import immediate_pack as _immediate_pack- # ── Infrastructure: immediate_pack / shard write ──────────────────- if self.compress_context.is_immediate_packing:- for _n, _mod in m.named_modules():- if hasattr(_mod, "bits") and check_to_quantized(_mod):- from auto_round.compressors.utils import immediate_pack as _immediate_pack+ module_name = getattr(_mod, "global_name", None)+ if module_name is None and nblocks == 1 and _n:+ module_name = f"{n}.{_n}"+ if module_name is None:+ continue+ _immediate_pack(module_name, _layer_cfg)+ _perf.tick("pack")- module_name = getattr(_mod, "global_name", None)- if module_name is None and nblocks == 1 and _n:- module_name = f"{n}.{_n}"- if module_name is None:- continue- _immediate_pack(module_name, self.layer_config)+ mv_module_from_gpu(m)+ _perf.tick("mv")+ clear_memory(device_list=device_manager.device_list)+ _perf.tick("clear")+ memory_monitor.log_summary()+ _perf.tick("monitor")- input_ids = next_input_ids+ input_ids = next_input_ids- if self.compress_context.is_immediate_saving:- self.shard_writer.write(m, is_finalize=False)- # ShardWriter only actually flushes to disk once its- # shard-size budget is reached (`_flush_shard`, private but- # there's no public equivalent) -- `write()` above may just- # buffer this block's tensors in memory. Force a flush here- # whenever resumability is active, since marking a block- # "done" in the resume manifest is a lie if a crash before- # the next natural flush would lose its tensors entirely.- # Only pay this extra small-shard-fragmentation cost when- # AR_RESUME_DIR is actually set.- if resume_state is not None:- self.shard_writer._flush_shard()-- if self.compress_context.low_cpu_mem_usage and not self.compress_context.is_immediate_saving:- if nblocks == 1:- self._offloader(model, n, overwrite=True)- else:- for name in names:- self._offloader(model, name, overwrite=True)-- # Record this block as durably done (its quantized weights are- # either flushed to a shard on disk via ShardWriter, or saved to- # the offloader's temp dir) only now, after that write has- # happened -- so a crash before this point correctly re-does the- # block on resume instead of skipping it with incomplete/missing- # output. See auto_round/utils/resume.py.- if resume_state is not None and nblocks == 1:- # `input_ids` was already reassigned to `next_input_ids`- # above -- it now holds the value the *next* block should use- # as its chained hidden-state input, which is exactly what- # needs to be persisted here.- resume_state.mark_block_done(n, q_input, input_ids)+ if self.compress_context.is_immediate_saving:+ # Background one-deep writer: the shard write/flush serializes+ # host-resident packed tensors (no VRAM) and can hide under the+ # next block's GPU work. One worker, joined before the NEXT+ # dispatch (and immediately under AR_RESUME_DIR, where+ # mark_block_done below must only fire on durable writes).+ _bg_write_m = m++ def _bg_write(_m: Any = _bg_write_m) -> None:+ self.shard_writer.write(_m, is_finalize=False)+ if resume_state is not None:+ self.shard_writer._flush_shard()++ _bg_writer.dispatch(_bg_write)+ if resume_state is not None:+ _bg_writer.join() # durability before the manifest mark++ if self.compress_context.low_cpu_mem_usage and not self.compress_context.is_immediate_saving:+ if nblocks == 1:+ self._offloader(model, n, overwrite=True)+ else:+ for name in names:+ self._offloader(model, name, overwrite=True)++ # Record this block as durably done (its quantized weights are+ # either flushed to a shard on disk via ShardWriter, or saved to+ # the offloader's temp dir) only now, after that write has+ # happened -- so a crash before this point correctly re-does the+ # block on resume instead of skipping it with incomplete/missing+ # output. See auto_round/utils/resume.py.+ if resume_state is not None and nblocks == 1:+ # `input_ids` was already reassigned to `next_input_ids`+ # above -- it now holds the value the *next* block should use+ # as its chained hidden-state input, which is exactly what+ # needs to be persisted here. The tensor serialization+ # (cross-device copies + torch.save, ~GB-class) runs on the+ # one-deep writer: the container skeleton is frozen+ # synchronously (snapshot_pool_refs) because the next block's+ # pool placement mutates the containers, while the tensors+ # themselves are immutable-by-convention and copyable+ # concurrently. One-deep join keeps mark_block_done's+ # order-assert valid (worker N+1 only starts after N appended),+ # and the manifest only claims a block after its tensors are+ # durable -- identical crash semantics to the inline call.+ from auto_round.utils.resume import snapshot_pool_refs++ _resume_q = snapshot_pool_refs(q_input)+ _resume_i = snapshot_pool_refs(input_ids)+ _bg_resume.dispatch(+ lambda _n=n, _q=_resume_q, _i=_resume_i: resume_state.mark_block_done(_n, _q, _i)+ )+ _perf.tick("write")+ if _perf.enabled:+ _perf.stop("write")+ # sweep/hooks fold into the printed pack span, monitor into the+ # printed write span; they were bad-perf-investigation probes that+ # read 0.00 in every validated run since+ _parts = [+ f"attach={_perf.get('attach'):.2f}s",+ f"compress={_perf.get('compress'):.2f}s",+ f"swap={_perf.get('swap'):.2f}s",+ f"pack={_perf.get('sweep') + _perf.get('hooks') + _perf.get('pack'):.2f}s",+ f"mv={_perf.get('mv'):.2f}s",+ f"clear={_perf.get('clear'):.2f}s",+ f"write={_perf.get('monitor') + _perf.get('write'):.2f}s",+ ]+ try:+ from auto_round.export.export_to_autoround.export import PACK_PHASES as _pp++ # the pack sub-note is no longer printed (pack is stable at+ # ~1.2s; the sub-phases were the layer_config-hunt probes);+ # reset the accumulators so a future re-enable starts clean+ for _k in _pp:+ _pp[_k] = 0.0+ except Exception as e: # pragma: no cover - diagnostics only+ logger.warning("pack phase accounting unavailable (%s)", e)+ logger.info(+ "[perf] block %s phases: reload=%.2fs %s total=%.2fs",+ block_name_or_names,+ _t_reload_mark - _t_reload_start,+ " ".join(_parts),+ (_t_reload_mark - _t_reload_start) + sum(_perf.totals.values()),+ )+ finally:+ # join the background writers even when a block raises: a daemon killed+ # mid torch.save would leave a truncated shard file behind. join()+ # re-raises the worker's captured exception, so each join is itself+ # guarded -- a writer failure must not skip the resume writer's join.+ _join_err = None+ for _bg in (_bg_writer, _bg_resume):+ try:+ _bg.join()+ except BaseException as _e: # noqa: BLE001 - re-raised below+ if _join_err is None:+ _join_err = _e+ else:+ logger.error("[bg-writer] %r also failed during join", _e)+ if _join_err is not None:+ raise _join_errif pbar is not None:pbar.update(1)@@ -477,6 +731,7 @@ class CompressionOrchestrator(BaseOrchestrator):update_block_global_scale_if_needed(block, self.data_type, self.group_size)self.alg_composer.compress_block(block, fp_inputs=None, input_others={}, block_ctx=ctx)+ _layer_cfg_free = self.layer_config # hoisted: property rebuilds per readif self.compress_context.is_immediate_packing:for _n, _mod in block.named_modules():if hasattr(_mod, "bits") and check_to_quantized(_mod):@@ -487,7 +742,7 @@ class CompressionOrchestrator(BaseOrchestrator):module_name = f"{block.global_name}.{_n}"if module_name is None:continue- _immediate_pack(module_name, self.layer_config)+ _immediate_pack(module_name, _layer_cfg_free)# ── Infrastructure: shard write / device cleanup ──────────if self.compress_context.is_immediate_saving:@@ -784,6 +1039,11 @@ class CompressionOrchestrator(BaseOrchestrator):pbar.set_description("Quantizing done")pbar.close()+ # Pool placement is per-block: clear it so later forwards (outside-block+ # layers, lm_head) keep today's cache-device behavior.+ runner = getattr(self.alg_composer, "block_forward", None)+ if runner is not None:+ runner.pool_placement = Noneif self.compress_context.low_cpu_mem_usage:if envs.AR_RESUME_DIR and not self.compress_context.is_immediate_saving:# `reload(names=None)` only reloads names in@@ -887,8 +1147,9 @@ class CompressionOrchestrator(BaseOrchestrator):input_ids=token_ids,)layer_names.remove(layer_name)+ _layer_cfg_names = self.layer_config # hoisted: property rebuilds per readif self.compress_context.is_immediate_packing:- immediate_pack(layer_name, self.layer_config)+ immediate_pack(layer_name, _layer_cfg_names)if self.compress_context.is_immediate_saving:m = get_module(self.model, layer_name)@@ -930,8 +1191,9 @@ class CompressionOrchestrator(BaseOrchestrator):q_inputs=q_layer_input,input_ids=token_ids,)+ _layer_cfg_names = self.layer_config # hoisted: property rebuilds per readif self.compress_context.is_immediate_packing:- immediate_pack(layer_name, self.layer_config)+ immediate_pack(layer_name, _layer_cfg_names)if self.compress_context.is_immediate_saving:m = get_module(self.model, layer_name)diff --git a/auto_round/compressors/utils.py b/auto_round/compressors/utils.pyindex eb149e6e3..251853590 100644--- a/auto_round/compressors/utils.py+++ b/auto_round/compressors/utils.py@@ -13,7 +13,7 @@# limitations under the License.import osimport random-from typing import Union+from typing import Any, Unionimport torchfrom torch.amp import autocast@@ -30,6 +30,7 @@ from auto_round.export.formats.backends.gguf import (get_layer_config_by_gguf_format,gguf_type_fallback,)+from auto_round.logger import loggerfrom auto_round.schemes import BackendDataType # re-exported: qlinear_fp/qlinear_int import it from herefrom auto_round.schemes import (QuantizationScheme,@@ -226,6 +227,53 @@ def collect_best_params(block, cache_device="cpu"):return params+def collect_best_params_local(block: torch.nn.Module) -> dict[str, Any]:+ """Best-params snapshot duplicated on each parameter's own device.++ With a CPU cache device this is not used (host parking is the point of+ ``low_gpu_mem_usage``). With a non-CPU cache device the historical path+ copied every parameter to that single device -- concentrating all devices'+ snapshot bytes on one GPU and paying cross-device copies on every improving+ iteration. Duplicating each parameter on the device that already hosts it+ keeps the footprint spread like the weights themselves, removes the+ cross-device traffic, and makes the unwrap copy-back local. Values and the+ restore path are unchanged. Falls back to a host snapshot (with a warning)+ when a local copy fails.+ """+ params = {}+ try:+ if hasattr(block, "orig_layer"):+ for key, p_ in block.params.items():+ params[key] = p_.data.to(p_.data.device, copy=True)+ else:+ for n, m in block.named_modules():+ if hasattr(m, "orig_layer"):+ params[n] = {key: p_.data.to(p_.data.device, copy=True) for key, p_ in m.params.items()}+ return params+ except RuntimeError as e:+ logger.warning("[snapshot] local copy failed (%s); parking the snapshot on host", e)+ return collect_best_params(block, "cpu")+++def snapshot_best_params(block: torch.nn.Module, cache_device: "str | torch.device" = "cpu") -> dict[str, Any]:+ """Collect the best-params snapshot, keeping multi-device blocks on-device.++ A CPU ``cache_device`` (``low_gpu_mem_usage``) keeps the historical host+ snapshot. A non-CPU ``cache_device`` means VRAM was budgeted for caching;+ each parameter is then duplicated on its own device instead of gathering+ every device's copies onto one cache device. Single-device blocks are+ unaffected either way (the cache device already equals each parameter's+ device).+ """+ try:+ non_cpu = torch.device(str(cache_device)).type != "cpu"+ except (ValueError, RuntimeError):+ non_cpu = False # unrecognized label: keep the historical path (it will raise as before)+ if non_cpu:+ return collect_best_params_local(block)+ return collect_best_params(block, cache_device)++def infer_bits_by_data_type(data_type: str):"""Infer bits by data_type@@ -523,7 +571,13 @@ def _get_save_folder_name(format, *args, **kwargs) -> str:return compress_context.output_dir+PACK_WRAP = {"pre": 0.0, "fmt": 0.0}++def immediate_pack(name: str, layer_config: dict):+ import time as _time++ _t0 = _time.perf_counter()from auto_round.context.compress import CompressContextfrom auto_round.context.model import ModelContext@@ -532,6 +586,8 @@ def immediate_pack(name: str, layer_config: dict):if not compress_context.is_immediate_packing:return+ PACK_WRAP["pre"] += _time.perf_counter() - _t0+ _t1 = _time.perf_counter()compress_context.formats[0].immediate_pack(name=name,model=model_context.model,@@ -544,3 +600,4 @@ def immediate_pack(name: str, layer_config: dict):image_processor=getattr(model_context, "image_processor", None),quant_nontext_module=getattr(model_context, "quant_nontext_module", False),)+ PACK_WRAP["fmt"] += _time.perf_counter() - _t1diff --git a/auto_round/context/compress.py b/auto_round/context/compress.pyindex d90036c48..c6f35b74b 100644--- a/auto_round/context/compress.py+++ b/auto_round/context/compress.py@@ -34,6 +34,7 @@ class CompressContext(BaseContext):low_cpu_mem_usage: bool = True,low_gpu_mem_usage: bool = False,enable_torch_compile: bool = True,+ calibration_data_device: str = "auto",is_immediate_packing: bool = False,is_immediate_saving: bool = False,formats: list | str | None = None,@@ -47,6 +48,9 @@ class CompressContext(BaseContext):super().__init__()self.low_cpu_mem_usage = low_cpu_mem_usageself.low_gpu_mem_usage = low_gpu_mem_usage+ # Device placement for block calibration data: auto | off | cpu | csv.+ # Threaded from the same-name API/CLI parameter (single source of truth).+ self.calibration_data_device = calibration_data_deviceself.formats = formatsself.output_dir = output_dir# All device / device-list state lives on the process-wide DeviceManagerdiff --git a/auto_round/data_type/neuqi.py b/auto_round/data_type/neuqi.pyindex 4171e3ad2..ad60c6533 100644--- a/auto_round/data_type/neuqi.py+++ b/auto_round/data_type/neuqi.py@@ -1000,6 +1000,7 @@ def _sym_search_eval(data, qw, scales, nmax):_sym_chunk_compiled = None_sym_compile_failed = False_sym_compile_logged: set = set()+_sym_core_lock = threading.Lock()@torch.compiler.disable # logging side effect: graph-break instead of tracing@@ -1023,18 +1024,29 @@ def _sym_loss_chunk_eval(data, qw, scales, nmax):if _sym_compile_failed or backend not in ("auto", "compile", "triton"):return _sym_loss_chunk(data, qw, scales, nmax)if _sym_chunk_compiled is None:- try:- _sym_chunk_compiled = torch.compile(_sym_loss_chunk)- except Exception: # pragma: no cover - compilation unavailable in this environment- _sym_compile_failed = True- return _sym_loss_chunk(data, qw, scales, nmax)- _log_sym_compile_engaged(backend)+ # batched searches call this from one worker thread per device; the+ # lazy compile must happen exactly once or concurrent first calls race+ # on dynamo's per-code-object state and the loser latches the whole+ # process down to eager+ with _sym_core_lock:+ if _sym_chunk_compiled is None and not _sym_compile_failed:+ try:+ _sym_chunk_compiled = torch.compile(_sym_loss_chunk)+ except Exception as e: # pragma: no cover - compilation unavailable in this environment+ logger.warning(+ "[neuqi] sym-chunk compile unavailable (%s); chunk core stays eager for the rest of the run", e+ )+ _sym_compile_failed = True+ else:+ _log_sym_compile_engaged(backend)+ if _sym_chunk_compiled is None:+ return _sym_loss_chunk(data, qw, scales, nmax)try:return _sym_chunk_compiled(data, qw, scales, nmax)- except Exception:+ except Exception as exc:_sym_chunk_compiled = None_sym_compile_failed = True- logger.warning("[NeUQI] sym compiled chunk core failed; using eager for the rest of this process.")+ logger.warning("[NeUQI] sym compiled chunk core failed (%r); using eager for the rest of this process.", exc)return _sym_loss_chunk(data, qw, scales, nmax)diff --git a/auto_round/data_type/utils.py b/auto_round/data_type/utils.pyindex 99f027c72..27a1a4212 100644--- a/auto_round/data_type/utils.py+++ b/auto_round/data_type/utils.py@@ -13,8 +13,10 @@# limitations under the License.import math+from collections.abc import Callablefrom functools import lru_cachefrom math import ceil+from typing import Anyimport torchfrom torch.nn import Linear, Module@@ -190,6 +192,28 @@ def get_quant_func()+def _int_search_with_thresh(search_scales: Any, q_scale_thresh: float) -> "Callable[..., torch.Tensor]":+ """Stable partial for the clamped int init-scale search.++ A module-level partial (captures visible as ``keywords``) instead of a+ per-call closure, so resolved callables compare equal across calls and can+ safely key same-shape search batches.+ """+ import functools++ def _clamped(+ weight_reshape: torch.Tensor, bits: int, imatrix: "torch.Tensor | None", *, _thresh: float+ ) -> torch.Tensor:+ init_scale = search_scales(weight_reshape, bits, imatrix)+ return torch.where(+ init_scale < 0,+ torch.clamp(init_scale, max=-_thresh),+ torch.clamp(init_scale, min=_thresh),+ )++ return functools.partial(_clamped, _thresh=q_scale_thresh)++def _resolve_optimized_dtype_funcs(data_type: str, q_scale_thresh: float = 1e-5):"""Resolve the SignRound optimized ``(scale_search_fn, quant_func)`` for a data type.@@ -215,15 +239,7 @@ def _resolve_optimized_dtype_funcs(data_type: str, q_scale_thresh: float = 1e-5)return None, Nonefrom auto_round.data_type.int import quant_tensor_sym, search_scales- def search_int(weight_reshape, bits, imatrix):- init_scale = search_scales(weight_reshape, bits, imatrix)- return torch.where(- init_scale < 0,- torch.clamp(init_scale, max=-q_scale_thresh),- torch.clamp(init_scale, min=q_scale_thresh),- )-- return search_int, quant_tensor_sym+ return _int_search_with_thresh(search_scales, q_scale_thresh), quant_tensor_symif dt.startswith("mx"):from auto_round.data_type.mxfp import quant_mx, search_mx_scale@@ -235,6 +251,21 @@ def _resolve_optimized_dtype_funcs(data_type: str, q_scale_thresh: float = 1e-5)return None, None+def resolve_optimized_init_scale_fn(+ data_type: str, q_scale_thresh: float = 1e-5+) -> "Callable[..., torch.Tensor] | None":+ """Resolve the per-group init-scale search callable for a data type.++ Returns the exact callable ``search_optimized_init_scale`` would invoke --+ ``(weight_reshape, bits, imatrix) -> init_scale`` -- or ``None`` for data+ types without an optimized path. The resolved callable can be staged and+ invoked later (batched wrap searches) with identical semantics, so future+ dispatch changes travel with the caller automatically.+ """+ search_fn, _ = _resolve_optimized_dtype_funcs(data_type, q_scale_thresh)+ return search_fn++def search_optimized_init_scale(weight_reshape: torch.Tensor,data_type: str,diff --git a/auto_round/envs.py b/auto_round/envs.pyindex f0140b89e..843320573 100644--- a/auto_round/envs.py+++ b/auto_round/envs.py@@ -16,7 +16,7 @@import osfrom collections.abc import Callable-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Optionalif TYPE_CHECKING:AR_LOG_LEVEL: str = "INFO"@@ -40,6 +40,10 @@ if TYPE_CHECKING:AR_NVFP4_FUSED_LAYER_GLOBAL_SCALE: bool = TrueAR_ALLOW_W8_ASYM: bool = FalseAR_CALIB_DATA_MULTIPLIER: int = 100+ AR_DISABLE_BATCHED_SEARCH: bool = False+ AR_PERF_COUNTERS: bool = False+ AR_SEARCH_BATCH_GB: float | None = None+ AR_DISABLE_CROSS_DEVICE_SEARCH: bool = Falsedef _get_optional_positive_int_env(name: str) -> int | None:@@ -56,6 +60,20 @@ def _get_optional_positive_int_env(name: str) -> int | None:return value+def _get_optional_positive_float_env(name: str) -> float | None:+ """Read an optional env var that must be a positive float when set."""+ raw = os.getenv(name)+ if raw is None:+ return None+ try:+ value = float(raw)+ except ValueError as exc:+ raise ValueError(f"{name} must be a positive float, got {raw!r}") from exc+ if not (value > 0 and value != float("inf")):+ raise ValueError(f"{name} must be a positive finite float, got {value}")+ return value++environment_variables: dict[str, Callable[[], Any]] = {# this is used for configuring the default logging level"AR_LOG_LEVEL": lambda: os.getenv("AR_LOG_LEVEL", "INFO").upper(),@@ -144,6 +162,12 @@ environment_variables: dict[str, Callable[[], Any]] = {# instead of restarting the whole tuning pass from block 0 after a# crash/kill. See auto_round/utils/resume.py."AR_RESUME_DIR": lambda: os.getenv("AR_RESUME_DIR", None),+ "AR_DISABLE_BATCHED_SEARCH": lambda: os.getenv("AR_DISABLE_BATCHED_SEARCH", "False").strip().lower()+ in ("1", "true", "yes"),+ "AR_PERF_COUNTERS": lambda: os.getenv("AR_PERF_COUNTERS", "False").strip().lower() in ("1", "true", "yes"),+ "AR_SEARCH_BATCH_GB": lambda: _get_optional_positive_float_env("AR_SEARCH_BATCH_GB"),+ "AR_DISABLE_CROSS_DEVICE_SEARCH": lambda: os.getenv("AR_DISABLE_CROSS_DEVICE_SEARCH", "False").strip().lower()+ in ("1", "true", "yes"),# When enabled, MoE routing can be overridden in selected model wrappers# to rotate token assignments across all experts for calibration coverage."AR_FORCE_MOE_ROUTING_ALL_EXPERTS": lambda: os.getenv("AR_FORCE_MOE_ROUTING_ALL_EXPERTS", "0").lower()diff --git a/auto_round/export/export_to_autoround/export.py b/auto_round/export/export_to_autoround/export.pyindex de5c8410f..e3b1adf00 100644--- a/auto_round/export/export_to_autoround/export.py+++ b/auto_round/export/export_to_autoround/export.py@@ -17,6 +17,7 @@ import functoolsimport inspectimport jsonimport os+import timefrom collections.abc import Callablefrom dataclasses import fieldsfrom enum import Enum@@ -165,6 +166,11 @@ def pack_qact_layer(name, model):qlayer.to(device)+# Per-phase pack accounting (read by the orchestrator's AR_PERF_COUNTERS+# summary): buffer allocation vs pack math vs device round trips.+PACK_PHASES = {"lookup": 0.0, "dispatch": 0.0, "ctor": 0.0, "pack": 0.0, "moves": 0.0, "count": 0}++def pack_layer(layer_name, model, backend, device=None):"""Packs a model layer for quantization based on its type and configuration.@@ -182,11 +188,13 @@ def pack_layer(layer_name, model, backend, device=None):Returns:None: The function modifies the model in place."""+ _t_entry = time.perf_counter()layer = get_module(model, layer_name)if hasattr(layer, "orig_layer"):layer = layer.orig_layerif type(layer) not in SUPPORTED_LAYER_TYPES: ##already packed+ PACK_PHASES["lookup"] += time.perf_counter() - _t_entryreturn# A resumed disk-streamed run only@@ -199,12 +207,20 @@ def pack_layer(layer_name, model, backend, device=None):# from) and would be redundant even if it didn't, since the on-disk# export for this layer is already complete.if layer.weight.device.type == "meta":+ PACK_PHASES["lookup"] += time.perf_counter() - _t_entryreturnif int(layer.act_bits) <= 8:- return pack_qact_layer(layer_name, model)+ PACK_PHASES["lookup"] += time.perf_counter() - _t_entry+ PACK_PHASES["count"] += 1+ _t_pack = time.perf_counter()+ try:+ return pack_qact_layer(layer_name, model)+ finally:+ PACK_PHASES["pack"] += time.perf_counter() - _t_packif not check_to_quantized(layer):+ PACK_PHASES["lookup"] += time.perf_counter() - _t_entryreturnorig_device = layer.weight.device@@ -245,6 +261,8 @@ def pack_layer(layer_name, model, backend, device=None):extra_kwargs: dict[str, torch.dtype] = {}if isinstance(scale, torch.Tensor) and _quant_linear_accepts(QuantLinear, "scale_dtype"):extra_kwargs["scale_dtype"] = scale.dtype+ PACK_PHASES["lookup"] += time.perf_counter() - _t_entry+ _t_ctor = time.perf_counter()new_layer = QuantLinear( ##pylint: disable=E1123bits, group_size, in_features, out_features, bias=bias, weight_dtype=layer.weight.dtype, **extra_kwargs)@@ -253,6 +271,9 @@ def pack_layer(layer_name, model, backend, device=None):qlayer = new_layerimport auto_round_extension.torch.qlinear_torch+ PACK_PHASES["ctor"] += time.perf_counter() - _t_ctor+ PACK_PHASES["count"] += 1+if (symand isinstance(zp, torch.Tensor)@@ -260,6 +281,7 @@ def pack_layer(layer_name, model, backend, device=None):):zp = int(zp.flatten()[0])+ _t_pack = time.perf_counter()qlayer.to("cpu")# Force to float32 to be compatible with torch 2.0sig = inspect.signature(qlayer.pack)@@ -268,7 +290,10 @@ def pack_layer(layer_name, model, backend, device=None):qlayer.pack(layer, scale, device=device)else:qlayer.pack(layer, scale, zp, None, device=device)+ PACK_PHASES["pack"] += time.perf_counter() - _t_pack+ _t_mv = time.perf_counter()qlayer.to(orig_device)+ PACK_PHASES["moves"] += time.perf_counter() - _t_mv# Inject rotation buffers right after packing so that# ShardWriter.save_module() captures them before offloading to meta.diff --git a/auto_round/export/formats/base.py b/auto_round/export/formats/base.pyindex 320e8293c..4c4b6d316 100644--- a/auto_round/export/formats/base.py+++ b/auto_round/export/formats/base.py@@ -225,11 +225,20 @@ class OutputFormat(ABC):passdef immediate_pack(self, name: str, model: torch.nn.Module, device: torch.device, **kwargs):+ import time as _time++ _t0 = _time.perf_counter()m = get_module(model, name)- if not check_to_quantized(m):+ ok = check_to_quantized(m)+ import auto_round.export.export_to_autoround.export as _ar_export++ _ar_export.PACK_PHASES["lookup"] += _time.perf_counter() - _t0+ if not ok:return+ _t1 = _time.perf_counter()self.pack_layer(name, model, device=device)+ _ar_export.PACK_PHASES["dispatch"] += _time.perf_counter() - _t1def is_gguf(self) -> bool:return "gguf" in self.output_formatdiff --git a/auto_round/modeling/fused_moe/grouped_experts.py b/auto_round/modeling/fused_moe/grouped_experts.pyindex d2858ac09..136a7eac8 100644--- a/auto_round/modeling/fused_moe/grouped_experts.py+++ b/auto_round/modeling/fused_moe/grouped_experts.py@@ -103,13 +103,26 @@ GROUPED_LINEAR_SLICED_IMPL = "linear_grouped_sliced"# Set once if the native grouped_mm kernel raises; afterwards we always use the sliced loop._NATIVE_GROUPED_MM_DISABLED = False-_LOGGED_FALLBACK_REASONS: set[str] = set()---def _log_fallback_once(reason: str) -> None:- if reason not in _LOGGED_FALLBACK_REASONS:- _LOGGED_FALLBACK_REASONS.add(reason)- logger.debug(f"[MoE grouped] falling back to linear_loop: {reason}")+_LOGGED_FALLBACK_REASONS: set[tuple[str, str]] = set()+# Bumped whenever the plan-building path changes; logged once per process so a+# log unambiguously identifies which grouped implementation produced it.+GROUPED_PLANS_VERSION = "slot-stage-v3"+_LOGGED_VERSION = False+++def _log_fallback_once(reason: str, detail: str = "") -> None:+ global _LOGGED_VERSION+ if not _LOGGED_VERSION:+ _LOGGED_VERSION = True+ logger.debug(f"[MoE grouped] plans version {GROUPED_PLANS_VERSION}")+ key = (reason, detail)+ if key in _LOGGED_FALLBACK_REASONS:+ return+ _LOGGED_FALLBACK_REASONS.add(key)+ msg = f"[MoE grouped] falling back to linear_loop: {reason}"+ if detail:+ msg = f"{msg} ({detail})"+ logger.debug(msg)# --------------------------------------------------------------------------------------@@ -214,6 +227,61 @@ def _act_quant_is_row_independent(layer: nn.Module) -> bool:return True+_ACCELERATE_HOOK_WHITELIST: tuple[type, ...] | None = None+++def _accelerate_hook_whitelist() -> tuple[type, ...]:+ """Resolve accelerate's placement-hook classes once per process.++ The installed accelerate version cannot change mid-run, and the grouped gate+ consults the whitelist for every MoE container -- probing per call repeats+ the import machinery and spams the missing-class notice for every layer.+ """+ global _ACCELERATE_HOOK_WHITELIST+ if _ACCELERATE_HOOK_WHITELIST is None:+ classes = []+ try:+ from accelerate.hooks import AlignDevicesHook++ classes.append(AlignDevicesHook)+ except Exception as e: # pragma: no cover - accelerate always present in our lanes+ logger.warning("[grouped-experts] AlignDevicesHook unavailable (%s); fast-path gate will decline", e)+ try: # newer accelerate only; absence on older versions is expected+ from accelerate.hooks import AddContiguousHook++ classes.append(AddContiguousHook)+ except Exception as e:+ logger.debug("[grouped-experts] AddContiguousHook unavailable (%s); whitelist shrinks accordingly", e)+ _ACCELERATE_HOOK_WHITELIST = tuple(classes)+ return _ACCELERATE_HOOK_WHITELIST+++def _hooks_are_alignment_only(module: nn.Module) -> bool:+ """Whether every hook on ``module`` is one the grouped path satisfies manually.++ accelerate's ``AlignDevicesHook`` (mapped placement) and ``AddContiguousHook`` only+ move/contiguify inputs -- the grouped path does both explicitly (``.to(plan.device)``+ on the way in, contiguous ``index_select`` gathers). A hook that carries an offload+ (``io_has_offload`` / weights_offload) still must run: it loads the weights, which the+ grouped path reads directly. Calibration hooks (act_max collectors) are not alignment+ hooks and remain a hard fallback so they keep firing.+ """+ hooks = list(module._forward_pre_hooks.values()) + list(module._forward_hooks.values())+ if not hooks:+ return True+ hook_classes = _accelerate_hook_whitelist()+ if not hook_classes:+ return False+ for h in hooks:+ if not isinstance(h, hook_classes):+ return False+ # Offload-carrying variants (weights streaming in from host) must still run+ # their own forward; alignment-only variants are satisfied manually.+ if getattr(h, "offload", False) or getattr(h, "io_has_offload", False) or getattr(h, "weights_offload", None):+ return False+ return True++def _projection_is_supported(layer: nn.Module) -> bool:if type(layer) is nn.Linear:# A plain Linear carrying forward (pre-)hooks must run its own forward so the hooks@@ -221,13 +289,19 @@ def _projection_is_supported(layer: nn.Module) -> bool:# forward hook on each expert Linear, and the grouped path -- which multiplies the# weights directly and never calls ``Linear.forward`` -- would silently skip them,# leaving every expert without ``act_max`` (breaking static-act export, e.g. NVFP4).- return not (layer._forward_pre_hooks or layer._forward_hooks)+ # Alignment-only accelerate hooks are exempt: the grouped path performs that exact+ # move itself (mapped multi-GPU placement attaches them to off-primary experts).+ hooks = layer._forward_pre_hooks or layer._forward_hooks+ return not hooks or _hooks_are_alignment_only(layer)if not _is_wrapper_linear(layer):return False+ # accelerate's stage hooks attach to the tree module -- the wrapper itself.+ if (layer._forward_pre_hooks or layer._forward_hooks) and not _hooks_are_alignment_only(layer):+ return Falseorig = layer.orig_layerif type(orig) is not nn.Linear:return False # Conv1D / LinearAllreduce need their own forward- if orig._forward_pre_hooks or orig._forward_hooks:+ if (orig._forward_pre_hooks or orig._forward_hooks) and not _hooks_are_alignment_only(orig):return False # e.g. online Hadamard rotation must run per layerreturn not (getattr(layer, "enable_act_quant", False) and not _act_quant_is_row_independent(layer))@@ -723,162 +797,6 @@ def _quantize_activation(layer: nn.Module, x: torch.Tensor) -> torch.Tensor:return x-# ---------------------------------------------------------------------------------------# Plan-# -----------------------------------------------------------------------------------------@dataclass-class _GroupedPlan:- """Everything needed to run one grouped forward, resolved for the *active* experts."""-- experts: list[nn.Module]- has_gate: bool- device: torch.device- output_device: torch.device- # Per-slot: may the fake-quantization of all active experts be fused into one call?- batched_qdq: dict[str, bool]---_SLOTS = ("gate_proj", "up_proj", "down_proj")---def _build_plan(module: nn.Module, active_ids: list[int]) -> _GroupedPlan | None:- """Validate the active experts and gather them, or return ``None`` to fall back."""- experts: list[nn.Module] = []- has_gate: bool | None = None- device: torch.device | None = None- output_device: torch.device | None = None- # Per-slot reference signatures: every active expert must agree on them.- quant_signatures: dict[str, object] = {}- layouts: dict[str, object] = {}- batched_qdq: dict[str, bool] = {}-- for expert_id in active_ids:- expert = getattr(module, str(expert_id), None)- if expert is None:- _log_fallback_once("expert container missing")- return None- if not hasattr(expert, "up_proj") or not hasattr(expert, "down_proj"):- _log_fallback_once("expert does not expose up_proj/down_proj")- return None-- expert_has_gate = hasattr(expert, "gate_proj")- if has_gate is None:- has_gate = expert_has_gate- elif has_gate != expert_has_gate:- _log_fallback_once("experts disagree on gate_proj")- return None-- slots = _SLOTS if expert_has_gate else ("up_proj", "down_proj")- for slot in slots:- projection = getattr(expert, slot)- if not _projection_is_supported(projection):- _log_fallback_once(f"unsupported projection type {type(projection).__name__}")- return None-- proj_device = _compute_device(projection)- if device is None:- device = proj_device- output_device = _output_device(projection)- elif proj_device != device:- _log_fallback_once("experts live on different devices")- return None-- # Mixed-bit MoE: bail out instead of batching differently-quantized experts.- signature = _quant_signature(projection)- if slot in quant_signatures:- if quant_signatures[slot] != signature:- _log_fallback_once(f"mixed quantization schemes across experts for '{slot}'")- return None- else:- quant_signatures[slot] = signature-- layout = _weight_layout(projection)- if slot in layouts:- if layouts[slot] != layout:- _log_fallback_once(f"experts have different weight shape/dtype for '{slot}'")- return None- else:- layouts[slot] = layout-- supports_batched = _supports_batched_qdq(projection)- batched_qdq[slot] = batched_qdq.get(slot, True) and supports_batched-- # gate_proj and up_proj consume the *same* tensor, which the grouped path- # activation-quantizes once, so their activation settings must be identical.- if expert_has_gate:- gate_act = _act_signature(expert.gate_proj) if _is_wrapper_linear(expert.gate_proj) else None- up_act = _act_signature(expert.up_proj) if _is_wrapper_linear(expert.up_proj) else None- gate_enabled = bool(getattr(expert.gate_proj, "enable_act_quant", False))- up_enabled = bool(getattr(expert.up_proj, "enable_act_quant", False))- if gate_enabled != up_enabled or (gate_enabled and gate_act != up_act):- _log_fallback_once("gate_proj/up_proj activation quantization differ")- return None-- experts.append(expert)-- if not experts or device is None or output_device is None:- return None- return _GroupedPlan(- experts=experts,- has_gate=bool(has_gate),- device=device,- output_device=output_device,- batched_qdq=batched_qdq,- )---# ---------------------------------------------------------------------------------------# Grouped matmul-# ---------------------------------------------------------------------------------------#-# Two ways to run the routed GEMM, plus one we deliberately avoid:-#-# sliced loop one ``F.linear`` per *active* expert over a contiguous slice.-# Same kernels as transformers' ``grouped_mm_fallback``, but without its-# extra ``offs.tolist()`` sync -- we already hold the counts on the host.-# Enable with ``AR_MOE_EXPERTS_IMPL=linear_grouped_sliced``.-# grouped_mm (default) ``torch.nn.functional.grouped_mm`` / ``torch._grouped_mm``: one-# kernel for all experts, driven by ``offsets``. Differentiable, and-# bit-identical to the loop (verified on A100). Disable with-# ``AR_MOE_EXPERTS_IMPL=linear_grouped_sliced``.-# batched_mm transformers' ``_batched_linear``/``torch.bmm`` path gathers-# ``weight[expert_ids]`` into an ``(S, out, in)`` tensor -- one weight copy-# per routed token. That is a decode-time trick (S == top_k); at tuning-# shapes it is orders of magnitude slower (measured ~87x) and the gather-# alone would be hundreds of GB. Never used here.-#-# Why grouped_mm is the default: the winner depends on the number of routed (token, expert)-# pairs, i.e. on the calibration batch. At realistic tuning sizes (batch=8, seqlen=2048 ->-# ~131k pairs) the sliced loop issues ~num_experts separate grad GEMMs in backward, whose-# launch pressure dominates; the single fused grouped_mm backward then wins by a wide margin-# -- up to ~5x on a synthetic full Qwen3.5-MoE decoder layer (A100, sm80, bf16), with the-# gap almost entirely in backward.-#-# The earlier, small-batch microbench below (only 4096 routed pairs, 2048x768 experts) is-# where the two looked equal and the loop was historically preferred -- it under-represented-# the backward launch count. Speedup over ``linear_loop`` for 16/32/64/128/256 experts:-#-# forward+backward grouped_mm 3.89 4.36 5.11 4.84 5.05 | sliced 4.36 4.70 5.32 5.14 5.24-# forward (wrapped) grouped_mm 2.57 2.99 3.21 3.30 3.28 | sliced 3.13 3.44 3.69 3.80 --# forward (plain fp) grouped_mm 2.07 2.53 2.76 2.99 2.93 | sliced 1.90 2.21 2.29 2.42 2.39-#-# grouped_mm needs a ``torch.stack`` copy when the qdq was not fused (higher peak memory)-# and has dtype/alignment/compute-capability constraints, so it transparently falls back to-# the sliced loop when the native kernel is not usable. torch's CPU ``grouped_mm`` loses, so-# on CPU the loop still runs.-#-# Deciding whether the native kernel is *legal* is fiddly (torch version, device, compute-# capability, dynamo, 16-byte alignment on CPU), so when it is requested we defer to-# transformers' own ``_can_use_grouped_mm`` rather than re-deriving it.--try: # transformers >= 5.0- from transformers.integrations.moe import _can_use_grouped_mm as _transformers_can_use_grouped_mm-except Exception: # pragma: no cover - older/absent transformers- _transformers_can_use_grouped_mm = None--def _sliced_grouped_mm_requested() -> bool:"""Whether the sliced per-expert GEMM loop was explicitly requested.@@ -900,6 +818,12 @@ def _native_grouped_mm_preferred(device: torch.device) -> bool:return not _sliced_grouped_mm_requested()+try:+ from transformers.integrations.moe import _can_use_grouped_mm as _transformers_can_use_grouped_mm+except Exception: # pragma: no cover - transformers-internal API drift; degrade to the sliced loop+ _transformers_can_use_grouped_mm = None++def _native_grouped_mm_usable(x: torch.Tensor, weight: torch.Tensor, offsets: torch.Tensor) -> bool:"""Whether ``grouped_mm`` can and should run this batch. ``weight`` is ``(E, in, out)``."""if not _native_grouped_mm_available():@@ -912,7 +836,10 @@ def _native_grouped_mm_usable(x: torch.Tensor, weight: torch.Tensor, offsets: toreturn torch.cuda.get_device_capability(weight.device) >= (8, 0)except Exception: # pragma: no cover - defensivereturn False- return True+ # Non-cuda devices (xpu/hpu/cpu): we cannot verify native grouped_mm support+ # here, and an unsupported F.grouped_mm would raise mid-forward -- degrade+ # to the sliced/loop fallback instead of gambling on the native path.+ return Falsedef _native_grouped_mm(x: torch.Tensor, weight: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:@@ -1080,50 +1007,127 @@ def _run_routes(if num_valid == 0:return torch.zeros_like(hidden_states)- plan = _build_plan(module, active_ids)- if plan is None:+ # Slot-stage plans: the balancer scatters projections independently, so one+ # expert's gate/up/down can live on different devices. Each SLOT partitions its+ # active experts by that slot's home device and runs one grouped GEMM per group;+ # full pair-indexed buffers carry intermediates between stages. (token, top_k)+ # pairs are unique, so per-group index_copy_ into shared buffers is exact and+ # the final sum(dim=1) combine is unchanged.+ def _slot_groups(slot_name: str) -> list[tuple[torch.device, list[int]]]:+ groups: dict[torch.device, list[int]] = {}+ for pos, expert_id in enumerate(active_ids):+ expert = getattr(module, str(expert_id), None)+ proj = getattr(expert, slot_name, None) if expert is not None else None+ if proj is None:+ _log_fallback_once("expert container missing", detail=f"expert {expert_id} slot {slot_name}")+ return []+ if not _projection_is_supported(proj):+ # check BEFORE _compute_device: packed QuantLinear types+ # (e.g. MXFP4QuantLinear) have no .weight, and the support+ # probe must be what rejects them, not an AttributeError+ _log_fallback_once(+ f"unsupported projection type {type(proj).__name__}", detail=f"expert {expert_id} slot {slot_name}"+ )+ return []+ groups.setdefault(_compute_device(proj), []).append(pos)+ return list(groups.items())++ has_gate = hasattr(getattr(module, str(active_ids[0]), None), "gate_proj")+ gate_groups = _slot_groups("gate_proj") if has_gate else []+ up_groups = _slot_groups("up_proj")+ down_groups = _slot_groups("down_proj")+ if not up_groups or not down_groups or (has_gate and not gate_groups):return None+ # Per-slot-group validation: projections supported; within a group (batched+ # together) quant signatures and weight layouts must agree. gate/up activation+ # settings must match per expert (they quantize the same input tensor).+ for slot_name, groups in (("up_proj", up_groups), ("gate_proj", gate_groups), ("down_proj", down_groups)):+ for _, positions in groups:+ # Seed the references from the FIRST position: None is a valid+ # quantization signature (plain Linear), so it cannot double as+ # the unset marker -- a plain expert preceding a quantized wrapper+ # would otherwise latch the wrapper's signature without comparison+ # and accept the mixed group.+ first = getattr(getattr(module, str(active_ids[positions[0]])), slot_name)+ sig = _quant_signature(first)+ layout = _weight_layout(first)+ for p in positions[1:]:+ proj = getattr(getattr(module, str(active_ids[p])), slot_name)+ if not _projection_is_supported(proj):+ _log_fallback_once(f"unsupported projection type {type(proj).__name__}")+ return None+ if _quant_signature(proj) != sig:+ _log_fallback_once("mixed quantization schemes across experts in a device group")+ return None+ if _weight_layout(proj) != layout:+ _log_fallback_once("experts have different weight shape/dtype in a device group")+ return None+ if has_gate:+ for expert_id in active_ids:+ expert = getattr(module, str(expert_id))+ gate_act = _act_signature(expert.gate_proj) if _is_wrapper_linear(expert.gate_proj) else None+ up_act = _act_signature(expert.up_proj) if _is_wrapper_linear(expert.up_proj) else None+ gate_enabled = bool(getattr(expert.gate_proj, "enable_act_quant", False))+ up_enabled = bool(getattr(expert.up_proj, "enable_act_quant", False))+ if gate_enabled != up_enabled or (gate_enabled and gate_act != up_act):+ _log_fallback_once("gate_proj/up_proj activation quantization differ")+ return None+perm_valid = perm[:num_valid]token_idx = torch.div(perm_valid, num_top_k, rounding_mode="floor")- x = hidden_states.index_select(0, token_idx).to(plan.device)-- offsets = torch.tensor(active_counts, device=plan.device, dtype=torch.int32).cumsum(0).to(torch.int32)+ x_all = hidden_states.index_select(0, token_idx) # (num_valid, hidden) on input device- # --- input projections (gate / up) -------------------------------------------------- x = _quantize_activation(plan.experts[0].up_proj, x)-- up = _slot_weights([e.up_proj for e in plan.experts], plan.batched_qdq.get("up_proj", False))- up_out = _grouped_linear(x, up, active_counts, offsets)-- if plan.has_gate:- gate = _slot_weights([e.gate_proj for e in plan.experts], plan.batched_qdq.get("gate_proj", False))- gate_out = _grouped_linear(x, gate, active_counts, offsets)+ # Contiguous sorted-order row range for each active position.+ ranges = []+ start = 0+ for c in active_counts:+ ranges.append((start, start + c))+ start += c++ def _run_slot(slot_name: str, groups: list[tuple[torch.device, list[int]]], inp: torch.Tensor) -> torch.Tensor:+ """Grouped GEMM for one slot; returns a full (num_valid, out) buffer on the input device."""+ out_buf = None+ for dev, positions in groups:+ counts = [active_counts[p] for p in positions]+ rows = torch.cat(+ [torch.arange(ranges[p][0], ranges[p][1], device=perm.device, dtype=torch.int64) for p in positions]+ )+ x_g = inp.index_select(0, rows).to(dev)+ offsets = torch.tensor(counts, device=dev, dtype=torch.int32).cumsum(0).to(torch.int32)+ experts_g = [getattr(module, str(active_ids[p])) for p in positions]+ x_g = _quantize_activation(getattr(experts_g[0], slot_name), x_g)+ batched = all(_supports_batched_qdq(getattr(e, slot_name)) for e in experts_g)+ w = _slot_weights([getattr(e, slot_name) for e in experts_g], batched)+ out_g = _grouped_linear(x_g, w, counts, offsets)+ if out_buf is None:+ out_buf = torch.zeros(num_valid, out_g.size(-1), device=inp.device, dtype=out_g.dtype)+ # device-only .to() would crash on cross-group dtype mixes; the+ # buffer dtype is the first group's expert-output dtype by design+ out_buf.index_copy_(0, rows.to(inp.device), out_g.to(device=inp.device, dtype=out_buf.dtype))+ return out_buf++ up_out = _run_slot("up_proj", up_groups, x_all)+ if has_gate:+ gate_out = _run_slot("gate_proj", gate_groups, x_all)if hasattr(module, "_apply_gate"):- # Keep the module's own gating (clamping, alpha, ...) and its [gate; up] layout,- # exactly as linear_loop_experts_forward does.- hidden = module._apply_gate(torch.cat([gate_out, up_out], dim=-1))+ hidden_mid = module._apply_gate(torch.cat([gate_out, up_out], dim=-1))else:- hidden = module.act_fn(gate_out) * up_out+ hidden_mid = module.act_fn(gate_out) * up_outelse:- hidden = module.act_fn(up_out)-- # --- down projection ---------------------------------------------------------------- hidden = _quantize_activation(plan.experts[0].down_proj, hidden)- down = _slot_weights([e.down_proj for e in plan.experts], plan.batched_qdq.get("down_proj", False))- out = _grouped_linear(hidden, down, active_counts, offsets)+ hidden_mid = module.act_fn(up_out)- out = out.to(plan.output_device)- # ``sample_weights``/``perm_valid`` live on the input device, which can differ from the- # experts' device in multi-GPU tuning (a whole layer's experts co-located on one card- # while the block input flows on another). Align to ``out`` before the multiply.+ out = _run_slot("down_proj", down_groups, hidden_mid)sample_weights_out = sample_weights.index_select(0, perm_valid).to(device=out.device, dtype=out.dtype)out = out * sample_weights_out.unsqueeze(-1)- # Scatter back to the original (token, top_k) order and reduce over top_k.- out_per_sample = torch.zeros(num_pairs, hidden_dim, device=out.device, dtype=out.dtype)- out_per_sample = out_per_sample.index_copy(0, perm_valid.to(out.device), out)- return out_per_sample.view(num_tokens, num_top_k, hidden_dim).sum(dim=1).to(device)+ # Scatter the weighted rows into the shared (token, top_k) buffer. The buffer+ # carries the EXPERT OUTPUT dtype (bf16 weights produce bf16 rows even when the+ # input chain is fp32 -- the GDN lanes); the original single-device path used+ # out.dtype for exactly this reason.+ out_per_sample = torch.zeros(num_pairs, hidden_dim, device=device, dtype=out.dtype)+ out_per_sample.index_copy_(0, perm_valid.to(device), out.to(device))+ return out_per_sample.view(num_tokens, num_top_k, hidden_dim).sum(dim=1)def _opaque_to_dynamo(fn):diff --git a/auto_round/utils/device.py b/auto_round/utils/device.pyindex 6ba56d090..1381aeaf7 100644--- a/auto_round/utils/device.py+++ b/auto_round/utils/device.py@@ -59,6 +59,30 @@ DEVICE_ENVIRON_VARIABLE_MAPPING = {################ Check available sys.module to decide behavior #################+def probe_usable_bytes(device_key: str) -> int | None:+ """Corrected free bytes on an accelerator device (raw free + reserved-but-unallocated).++ Routes through the device manager so every backend it supports (cuda,+ xpu, hpu, mps) probes through its own API instead of silently reporting+ nothing on non-cuda fleets.+ """+ try:+ dev = torch.device(str(device_key))+ if dev.type == "cpu" or dev.index is None:+ return None+ from auto_round.utils.device_manager import get_ar_device++ ar_dev = get_ar_device(dev.type)+ free, total = ar_dev.mem_get_info(dev.index)+ if total <= 0:+ return None+ free += ar_dev.memory_reserved(dev.index) - ar_dev.memory_allocated(dev.index)+ return max(free, 0)+ except (ValueError, RuntimeError, AttributeError) as e:+ logger.debug("[device] free-memory probe failed for %s (%s)", device_key, e)+ return None++def is_package_available(package_name: str) -> bool:"""Check if the package exists in the environment without importing.@@ -703,15 +727,28 @@ def _preassign_moe_experts(# Spread chunk-aligned groups across cards: each group stays whole on one device (so a# chunk's grouped GEMM is single-device) but different groups balance across GPUs.# ``chunk <= 0`` ("fuse everything") keeps the whole container as one group.+ # On overflow the chunk SHRINKS (halving, floor 1 = a single expert whole) instead of+ # dropping to the per-Linear balancer: dropped chunks are what scatter one expert's+ # gate/up/down across devices and force the grouped path to fall back to the loop.step = len(idxs) if chunk <= 0 else chunk- for start in range(0, len(idxs), step):- group_items = [item for i in idxs[start : start + step] for item in by_idx[i]]+ start = 0+ while start < len(idxs):+ take = min(step, len(idxs) - start)+ group_items = [item for i in idxs[start : start + take] for item in by_idx[i]]group_mem = mem_of(group_items)group_device = best_fit(group_mem)if group_device is None:- continue # Overflow: leave for the general balancer+ if take <= 1:+ logger.debug(+ "[moe-prepass] single expert of %s fits no device budget; leaving for the balancer", container+ )+ start += 1+ continue+ step = max(1, step // 2)+ continueplace(group_items, group_device)device_memory[group_device] -= group_mem+ start += takereturn assigned@@ -757,10 +794,20 @@ def _allocate_layers_to_devices(sorted_layers = sorted(remaining.items(), key=lambda x: (-x[1]["param_memory"], -layer_order[x[0]]))num_devices = len(gpu_devices)- def find_best_device(layer_name, estimated_memory, layer_idx):- """Find the best device for a layer."""- # Phase 1: Direct assign largest layers to higher-index devices first- if layer_idx < num_devices - 1:+ def find_best_device(layer_name: str, estimated_memory: float, layer_idx: int, strict: bool = False) -> str:+ """Find the best device for a layer.++ strict=True skips the Phase-1 shortcut (used by the atomic-group+ allocator so every unit goes through budget-aware scoring). When no+ device passes the score filter, the device with the most remaining+ budget still takes the unit: estimates are balancing reservations and+ real overflow is owned by the per-layer OOM handlers.+ """+ # Phase 1: Direct assign largest layers to higher-index devices first.+ # Skipped under strict: the atomic allocator's fail-loudly contract must+ # hold for the LARGEST units too, and this shortcut assigns the first+ # num_devices-1 units to fixed devices without any budget check.+ if layer_idx < num_devices - 1 and not strict:return gpu_devices[-(layer_idx + 1)]# Phase 2: Choose device with best score (memory + continuity)@@ -789,15 +836,52 @@ def _allocate_layers_to_devices(best_score = total_scorebest_device = device- # Fallback: device with most available memory+ # Fallback: device with most available memory. Estimates are+ # balancing reservations, never admission control -- when nothing+ # fits by score, the max-remaining device gets the unit and the+ # real OOM handlers own any actual overflow.return best_device or max(gpu_devices, key=lambda d: device_memory[d])- # Allocate the remaining (non-preassigned) layers- for layer_idx, (layer_name, mem_info) in enumerate(sorted_layers):- names.append(layer_name)- estimated_memory = mem_info["param_memory"] * mem_per_param- best_device = find_best_device(layer_name, estimated_memory, layer_idx)- device_map[layer_name] = best_device+ # Allocate the remaining (non-preassigned) layers in ATOMIC GROUPS: leaves under the+ # same indexed container (e.g. ``experts.7.gate/up/down``) are one indivisible unit —+ # the streaming lane's ``_atomic_groups`` pattern — so the balancer can never split an+ # expert across devices even when the MoE pre-pass left it behind.+ import re as _re++ _indexed = _re.compile(r"^(.*)\.(\d+)\.[^.]+$")+ _groups: dict = {}+ _group_order: list = []+ for layer_name in remaining:+ m = _indexed.match(layer_name)+ key = f"{m.group(1)}.{m.group(2)}" if m else layer_name+ if key not in _groups:+ _groups[key] = []+ _group_order.append(key)+ _groups[key].append(layer_name)+ grouped_units = [+ (key, sum(remaining[n]["param_memory"] for n in _groups[key]), min(layer_order[n] for n in _groups[key]))+ for key in _group_order+ ]+ grouped_units.sort(key=lambda u: (-u[1], -u[2]))++ for layer_idx, (key, unit_param_memory, _order) in enumerate(grouped_units):+ members = _groups[key]+ estimated_memory = unit_param_memory * mem_per_param+ best_device = find_best_device(members[0], estimated_memory, layer_idx, strict=True)+ if device_memory[best_device] < estimated_memory:+ # The proportional share is a balancing reservation, not a+ # footprint (sum of shares == the whole pool, so fat units can+ # exhaust every remaining budget on dense blocks) -- placed+ # anyway; the OOM ladder owns real overflows.+ logger.debug(+ "atomic module group '%s' share %.2f GB exceeds %s's remaining budget; placed for best fit",+ key,+ estimated_memory,+ best_device,+ )+ for layer_name in members:+ names.append(layer_name)+ device_map[layer_name] = best_devicedevice_memory[best_device] -= estimated_memory# Restore original order@@ -824,7 +908,7 @@ def get_first_available_attr(obj, attr_names: list[str], default=None):return default-def get_moe_memory_ratio(block: torch.nn.Module) -> float:+def get_moe_memory_ratio(block: torch.nn.Module, config: Any = None) -> float:"""Calculate the memory ratio for MoE (Mixture of Experts) models.@@ -833,6 +917,11 @@ def get_moe_memory_ratio(block: torch.nn.Module) -> float:Args:block (torch.nn.Module): The model block to analyze.+ config: Model config to read when the block itself carries none+ (block-wise tuning blocks have no ``.config``; without this the+ ratio silently falls back to 1.0 and prices ALL experts' outputs+ at full width -- an order-of-magnitude overcharge on models with+ many sparsely-active experts).Returns:float: Memory ratio (num_experts_per_tok / num_experts).@@ -850,8 +939,14 @@ def get_moe_memory_ratio(block: torch.nn.Module) -> float:if not is_moe_layer(module):continue- config = getattr(block, "config", None)+ config = config if config is not None else getattr(block, "config", None)if config is None:+ # container-attr fallback before giving up: expert count from the+ # container itself, active count from its top_k-ish attrs+ num_experts = getattr(module, "num_experts", None)+ active = getattr(module, "num_experts_per_tok", None) or getattr(module, "top_k", None)+ if isinstance(num_experts, int) and num_experts > 0 and isinstance(active, int) and active > 0:+ return active / num_experts, Truebreak# Try to get num_experts_per_tok (active experts count)@@ -880,17 +975,20 @@ def get_moe_memory_ratio(block: torch.nn.Module) -> float:if num_experts is not None and num_experts > 0:moe_ratio = num_experts_per_tok / num_expertslogger.debug(- f"MoE detected: {num_experts_per_tok}/{num_experts} experts active per token, "- f"activation memory ratio: {moe_ratio:.2f}"+ f"Using MoE memory ratio: {moe_ratio:.4f} ({num_experts_per_tok}/{num_experts} experts active per token)")- logger.debug(f"Using MoE memory ratio: {moe_ratio:.4f}")return moe_ratio, Truebreak # Only check once per blockreturn 1.0, False # Default ratio for non-MoE models-def estimate_tuning_block_mem(block: torch.nn.Module, input_ids: Any, batch_size: int) -> tuple[dict, float]:+def estimate_tuning_block_mem(+ block: torch.nn.Module,+ input_ids: Any,+ batch_size: int,+ config: Any = None,+) -> tuple[dict[str, Any], float, float, float, dict[str, float], dict[str, int]]:"""Calculates the memory consumption of a specific block in the model.@@ -901,12 +999,16 @@ def estimate_tuning_block_mem(block: torch.nn.Module, input_ids: Any, batch_sizebatch_size (int): Number of samples to consider for memory estimation.Returns:- tuple: A tuple containing the following:+ tuple: A 6-tuple containing:- layer_memory_dict (dict): A dictionary mapping layer names to their memory consumption (in GB).Format: {layer_name: {"param_memory": float, "output_memory": float}}+ - layer_activation_memory (float): Sum of per-layer output memory (GB), expert outputs+ ratio-scaled by active/total experts.- input_output_memory (float): The memory consumption (in GB) for input and outputtensors of the block.- additional_memory (float): Additional memory overhead (in GB) for operations like attention.+ - per_device_activation (dict): {device: GB} of output+grad charges bucketed by weight home.+ - per_device_experts (dict): {device: count} of routed-expert leaves homed per device."""# Calculate all block parameters memory and build layer-wise memory dictfrom auto_round.utils.model import get_layer_features, is_moe_layer@@ -931,11 +1033,15 @@ def estimate_tuning_block_mem(block: torch.nn.Module, input_ids: Any, batch_sizeseq_len = reference_tensor.shape[1] if reference_tensor is not None and reference_tensor.ndim >= 2 else 1element_size = reference_tensor.element_size() if reference_tensor is not None else 2- moe_ratio, has_moe = get_moe_memory_ratio(block) # Get MoE memory ratio (1.0 for non-MoE models)+ moe_ratio, has_moe = get_moe_memory_ratio(block, config) # ratio 1.0 for non-MoE modelsfor name, module in block.named_modules():if check_to_quantized(module):- enable_act_quant = module.act_bits <= 8+ # V2 wrappers keep bits/act_bits on orig_layer (check_to_quantized+ # reads them there); reading them off the wrapper itself raises+ enable_act_quant = (+ getattr(getattr(module, "orig_layer", module), "act_bits", getattr(module, "act_bits", 16)) <= 8+ )layer_name = nameparam_size = module.weight.nbytesparam_memory_gb = param_size / 1024**3@@ -958,7 +1064,32 @@ def estimate_tuning_block_mem(block: torch.nn.Module, input_ids: Any, batch_sizeif has_moe:pparent_module = get_module(block, layer_name.rsplit(".", 2)[0]) if "." in layer_name else block- is_moe_expert = "expert" in layer_name.lower() and isinstance(pparent_module, torch.nn.ModuleList)+ # Our unfuse builds the experts module as a plain nn.Module with numbered+ # _ExpertContainer children (checkpoint-format keys), NOT an nn.ModuleList;+ # the num_experts attribute identifies it just as well.+ # The experts container itself may be a plain class with a+ # generic name (neither ModuleList nor num_experts, and no+ # "moe" in ITS class name) -- the MoE marker sits on an+ # ANCESTOR. Walk the chain; a single-parent check prices+ # every expert full-width (an order-of-magnitude overcharge+ # on models with many sparsely-active experts).+ is_experts_container = isinstance(pparent_module, torch.nn.ModuleList) or hasattr(+ pparent_module, "num_experts"+ )+ if not is_experts_container:+ _and = layer_name+ while "." in _and and not is_experts_container:+ _and = _and.rsplit(".", 1)[0]+ _mod = get_module(block, _and) if _and else None+ if _mod is not None and (+ isinstance(_mod, torch.nn.ModuleList) or hasattr(_mod, "num_experts") or is_moe_layer(_mod)+ ):+ is_experts_container = True+ # shared experts are plain modules outside the dispatch (same+ # exclusion the repo's is_moe_expert predicate applies)+ is_moe_expert = (+ "expert" in layer_name.lower() and "shared" not in layer_name.lower() and is_experts_container+ )else:is_moe_expert = False@@ -967,6 +1098,9 @@ def estimate_tuning_block_mem(block: torch.nn.Module, input_ids: Any, batch_size"param_memory": param_memory_gb * 2,"output_memory": output_memory_gb * 2,"is_moe_expert": is_moe_expert,+ # weight home: fwd/bwd executes where the weight lives, so the+ # saved output + grad transient lands on this device+ "device": str(module.weight.device),}# Assuming bfloat16 or float32, input and output@@ -976,13 +1110,22 @@ def estimate_tuning_block_mem(block: torch.nn.Module, input_ids: Any, batch_size# For MoE expert layers, multiply activation memory by the ratio of active experts# For non-MoE layers (attention, norm, etc.), use full activation memorylayer_activation_memory = 0.0+ per_device_activation = {}+ per_device_experts = {}for layer_name, info in layer_memory_dict.items():if info.get("is_moe_expert", False):# MoE expert layer: only a fraction of experts are activelayer_activation_memory += info["output_memory"] * moe_ratio+ per_device_activation[info["device"]] = (+ per_device_activation.get(info["device"], 0.0) + info["output_memory"] * moe_ratio+ )+ per_device_experts[info["device"]] = per_device_experts.get(info["device"], 0) + 1else:# Non-MoE layer: use full activation memorylayer_activation_memory += info["output_memory"]+ per_device_activation[info["device"]] = (+ per_device_activation.get(info["device"], 0.0) + info["output_memory"]+ )# layer_activation_memory considers other ops activation memory# 1GB considers norm weight, sdpa, reference_output, etc.@@ -994,7 +1137,14 @@ def estimate_tuning_block_mem(block: torch.nn.Module, input_ids: Any, batch_sizemoe_additional_memory = additional_memory * 6 # GBadditional_memory += moe_additional_memory- return layer_memory_dict, layer_activation_memory, block_input_output_memory, additional_memory+ return (+ layer_memory_dict,+ layer_activation_memory,+ block_input_output_memory,+ additional_memory,+ per_device_activation,+ per_device_experts,+ )def set_auto_device_map_for_block_with_tuning(@@ -1068,7 +1218,7 @@ def set_auto_device_map_for_block_with_tuning(device_0_memory = get_device_memory(device_list[0] if device_list else 0)device_1_memory = get_device_memory(device_list[1] if device_list else 1)- layer_memory_dict, layer_activation_memory, block_input_output_memory, additional_memory = (+ layer_memory_dict, layer_activation_memory, block_input_output_memory, additional_memory, _, _ = (estimate_tuning_block_mem(block, input_ids, batch_size))loss_memory = block_input_output_memory / 2 # GB, rough estimate for loss tensor memorydiff --git a/auto_round/utils/device_manager.py b/auto_round/utils/device_manager.pyindex c06c3807d..9db19f703 100644--- a/auto_round/utils/device_manager.py+++ b/auto_round/utils/device_manager.py@@ -489,7 +489,7 @@ class ARDevice:return funcfrom auto_round.utils.device import _bump_dynamo_cache_limit- _bump_dynamo_cache_limit()+ _bump_dynamo_cache_limit(_engaged_cache_limit())return torch.compile(func)@@ -888,6 +888,21 @@ class DeviceManager:device_manager = DeviceManager()+def _engaged_cache_limit() -> int:+ """Dynamo cache-limit target scaled by the engaged device count.++ Multi-device runs multiply the static shape specializations of the shared+ compiled quant functions (per-layer shapes x per-device guard pins), so the+ cache limit must scale with the engaged devices or the lane silently+ degrades to eager mid-block once the limit is hit. A single-device run+ keeps the plain env default. The bump itself is monotone raise-only, so+ repeated calls are idempotent.+ """+ from auto_round import envs++ return int(envs.AR_DYNAMO_CACHE_SIZE_LIMIT) * max(1, len(device_manager.device_list))++def get_ar_device(device_type: None | str | int | torch.device = None) -> ARDevice:"""Return the cached :class:`Device` handle for a specific backend type."""return device_manager.get_ar_device(device_type)diff --git a/auto_round/utils/oom.py b/auto_round/utils/oom.pynew file mode 100644index 000000000..23b5a9685--- /dev/null+++ b/auto_round/utils/oom.py@@ -0,0 +1,324 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+# License for the specific language governing permissions and limitations+# under the License.++"""OOM diagnostics: tensor census, pluggable anywhere.++Three entry points, cheapest first:++* ``oom_census("context")`` -- a few-line context manager around any+ suspicious frame (including code this repo does not own); prints the+ census and re-raises.+* ``dump_oom_tensor_census_("context")`` -- the bare one-liner for+ existing ``except torch.OutOfMemoryError`` blocks.+* ``install_oom_census_hook()`` -- install once (the CLI does); fires+ for ANY uncaught CUDA OOM on any thread, wherever it escapes.++All are best effort: the census swallows its own failures and never+masks the original error.+"""++from collections.abc import Iterator+from contextlib import contextmanager+from types import FrameType, ModuleType, TracebackType+from typing import Any++import torch++from auto_round.logger import logger+++def _shape_key(shape: torch.Size | tuple[int, ...]) -> tuple[int | str, ...]:+ """Shape as a hashable key; symbolic dims (SymInt) fall back to a string form."""+ try:+ return tuple(int(d) for d in shape)+ except Exception as e: # symbolic dims (SymInt) or exotic shapes: stringify+ logger.debug("[oom] census shape key fell back to str for %s (%s)", type(shape).__name__, e)+ return (str(tuple(shape)),)+++def _group_tensors_by_shape(+ objs: list[Any],+) -> tuple[list[tuple[tuple[str, str, tuple[int | str, ...]], list[int]]], int]:+ """(device, dtype, shape) -> [count, bytes] over accelerator tensors; sorted by bytes.++ Covers every non-cpu accelerator (cuda, hpu, xpu, mps, ...): the census+ must name the residents on whichever device ran out.+ """++ skipped = 0++ groups: dict[tuple[str, str, tuple[int | str, ...]], list[int]] = {}+ for obj in objs:+ try:+ if not isinstance(obj, torch.Tensor) or obj.device.type in ("cpu", "meta"):+ continue+ key = (str(obj.device), str(obj.dtype), _shape_key(obj.shape))+ nbytes = int(obj.numel()) * obj.element_size()+ except Exception as e: # one unreadable tensor must never kill the census+ logger.debug("[oom] census skipping unreadable tensor (%s)", e)+ skipped += 1+ continue+ g = groups.get(key)+ if g is None:+ groups[key] = [1, nbytes]+ else:+ g[0] += 1+ g[1] += nbytes+ return sorted(groups.items(), key=lambda kv: -kv[1][1]), skipped+++def _representatives(+ groups: list[tuple[tuple[str, str, tuple[int | str, ...]], list[int]]], objs: list[Any]+) -> Iterator[tuple[torch.Tensor, tuple[tuple[str, str, tuple[int | str, ...]], list[int]]]]:+ """One representative tensor per group, drawn from a single scan."""+ wanted = {g[0] for g in groups} # group keys are (device, dtype, shape)+ seen: dict[tuple[str, str, tuple[int | str, ...]], torch.Tensor] = {}+ for obj in objs:+ try:+ if not isinstance(obj, torch.Tensor) or obj.device.type in ("cpu", "meta"):+ continue+ key = (str(obj.device), str(obj.dtype), _shape_key(obj.shape))+ except Exception as e:+ logger.debug("[oom] census representative scan skipped a tensor (%s)", e)+ continue+ if key in wanted and key not in seen:+ seen[key] = obj+ for gk, meta in groups:+ if gk in seen:+ yield seen[gk], (gk, meta)+++def _is_census_noise(ref: Any, skip_ids: set[int]) -> bool:+ """Referrers that are the census's own structures or whole-heap scans."""+ if id(ref) in skip_ids:+ return True+ if isinstance(ref, (list, tuple, set)) and len(ref) > 4096:+ return True # heap snapshots and other scans, never real holders+ if isinstance(ref, dict) and ref:+ for k in list(ref.keys())[:3]:+ if isinstance(k, tuple) and len(k) == 3 and all(isinstance(x, str) for x in k):+ return True # the census's own representative dicts+ return False+++def _describe_frame(frame: FrameType, target: Any) -> str:+ """Frame as '<func> (<file>:<line>)' plus the local names holding target."""+ try:+ code = frame.f_code+ where = f"{code.co_name} ({code.co_filename.split('/')[-1]}:{frame.f_lineno})"+ names = []+ for k, v in list(frame.f_locals.items())[:80]:+ try:+ if v is target or (isinstance(v, list) and len(v) <= 4096 and target in v):+ names.append(str(k))+ except Exception as e:+ logger.debug("[oom] census frame-local scan skipped a local (%s)", e)+ continue+ return where + (f" locals:{','.join(names[:4])}" if names else "")+ except Exception as e:+ logger.debug("[oom] census frame description fell back to bare 'frame' (%s)", e)+ return "frame"+++def _attr_name_of(owner: Any, target: Any) -> str | None:+ """The attribute of ``owner`` (if any) that holds ``target`` by identity."""+ try:+ d = getattr(owner, "__dict__", None)+ if isinstance(d, dict):+ for k, v in d.items():+ if v is target:+ return str(k)+ except Exception as e:+ logger.debug("[oom] census attr-name scan failed for owner %s (%s)", type(owner).__name__, e)+ return None+++def _describe(obj: Any, depth: int = 0) -> str:+ """One-line description of a holder object."""+ import types++ t = type(obj)+ if t is dict:+ keys = [str(k) for k in list(obj.keys())[:3]]+ return f"dict[{','.join(keys)}]"+ if t is types.FrameType:+ return "frame"+ if t is types.GeneratorType:+ return "generator"+ if t in (list, tuple, set):+ return f"{t.__name__}(len={len(obj)})"+ name = getattr(obj, "__class__", t).__name__+ mod = getattr(getattr(obj, "__class__", t), "__module__", "")+ return f"{mod}.{name}" if mod and mod != "builtins" else name+++def _describe_referrers(tensor: torch.Tensor, skip_ids: set[int], limit: int = 6, depth: int = 0) -> list[str]:+ """Holders of ``tensor``; small containers are unwrapped one more level."""+ import gc as _gc++ out = []+ try:+ for ref in _gc.get_referrers(tensor):+ if _is_census_noise(ref, skip_ids):+ continue+ import types as _types++ if isinstance(ref, _types.FrameType):+ out.append(_describe_frame(ref, tensor))+ if len(out) >= limit:+ break+ continue+ desc = _describe(ref)+ attr = _attr_name_of(ref, tensor) if depth == 0 else None+ if attr:+ desc += f".{attr}"+ out.append(desc)+ # unwrap small containers one level: name who holds the holder+ if depth == 0 and isinstance(ref, (list, tuple, set, dict)) and len(ref) <= 4096:+ for owner in _gc.get_referrers(ref):+ if _is_census_noise(owner, skip_ids) or owner is tensor:+ continue+ od = _describe(owner, 1)+ oattr = _attr_name_of(owner, ref)+ out.append(f" <- {od}" + (f".{oattr}" if oattr else ""))+ if len(out) >= limit:+ break+ if len(out) >= limit:+ break+ except Exception as e: # pragma: no cover - diagnostics must not mask the OOM+ out.append(f"<referrer scan failed: {e}>")+ return out+++def dump_oom_tensor_census_(context: str = "") -> None:+ """Tensor census at OOM time: per-device allocator state + top tensor groups.++ Names the accumulating residents (a leak shows as one (shape, dtype)+ group growing across blocks). Best effort: never masks the OOM itself.+ """+ import gc+ import warnings++ try:+ with warnings.catch_warnings():+ warnings.simplefilter("ignore", FutureWarning) # isinstance over heap objects+ _dump_census(gc, context)+ except Exception as e: # pragma: no cover - diagnostics must not mask the OOM+ logger.error("[oom] tensor census failed (%s)", e)+++def _dump_census(gc: ModuleType, context: str = "") -> None:+ idx = "?" # bound before the loop so the handler below can always name it+ if context:+ logger.error("[oom] tensor census (context: %s)", context)+ try:+ try:+ for idx in range(torch.cuda.device_count()):+ logger.error(+ "[oom] cuda:%s allocated=%.2fGiB reserved=%.2fGiB",+ idx,+ torch.cuda.memory_allocated(idx) / 2**30,+ torch.cuda.memory_reserved(idx) / 2**30,+ )+ except Exception as e: # pragma: no cover - allocator stats are cuda-only+ logger.debug("[oom] allocator stats unavailable for cuda:%s (%s)", idx, e)+ objs = gc.get_objects()+ per_device: dict[str, int] = {}+ top, _skipped = _group_tensors_by_shape(objs)+ for (_dev, _dt, _shape), (_cnt, _nb) in top:+ per_device[_dev] = per_device.get(_dev, 0) + _nb+ for _dev, _nb in sorted(per_device.items(), key=lambda kv: -kv[1]):+ logger.error("[oom] %s live tensors ≈ %.2fGiB", _dev, _nb / 2**30)+ if _skipped:+ logger.error("[oom] census skipped %d unreadable tensors", _skipped)+ for (_dev, _dt, _shape), (_cnt, _nb) in top[:8]:+ logger.error("[oom] %s %s %s x%d = %.2fGiB", _dev, _dt, list(_shape), _cnt, _nb / 2**30)+ # holder attribution runs LAST and fully guarded: it must never cost the+ # inventory above (a symbolic-shape failure here previously ate the totals)+ try:+ skip = {id(objs), id(top)}+ for rep, ((_dev, _dt, _shape), (_cnt, _nb)) in _representatives(top[:6], objs):+ for desc in _describe_referrers(rep, skip):+ logger.error("[oom] %s %s held by: %s", _dev, list(_shape), desc)+ except Exception as e: # pragma: no cover - must not cost the inventory+ logger.error("[oom] holder attribution failed (%s)", e)+ except Exception as e: # pragma: no cover - must not mask the OOM+ logger.error("[oom] tensor census failed (%s)", e)+++def _is_oom(exc: BaseException) -> bool:+ """torch.OutOfMemoryError (cuda, modern xpu) or message-based OOM (hpu et al.)."""+ if isinstance(exc, torch.OutOfMemoryError):+ return True+ return isinstance(exc, RuntimeError) and "out of memory" in str(exc).lower()+++@contextmanager+def oom_census(context: str = "") -> Iterator[None]:+ """Census-on-OOM context manager: plug around any frame, upstream code included.++ .. code-block:: python++ with oom_census("block collection forward"):+ out = block_forward_fn(block, fp_inputs, input_others)+ """+ try:+ yield+ except Exception as exc:+ if _is_oom(exc):+ dump_oom_tensor_census_(context)+ raise+++_OOM_HOOK_INSTALLED = False+++def install_oom_census_hook() -> bool:+ """Install the last-resort census for uncaught CUDA OOMs (any thread).++ Fires wherever a ``torch.OutOfMemoryError`` escapes to the top of the+ process -- including frames this repo does not own -- printing the tensor+ census before the default exception reporting takes over. Idempotent;+ returns True when it installed the hooks.+ """+ global _OOM_HOOK_INSTALLED+ if _OOM_HOOK_INSTALLED:+ return False+ import sys+ import threading++ prior_sys = sys.excepthook+ prior_the = threading.excepthook++ def _sys_hook(tp: type[BaseException], val: BaseException, tb: TracebackType | None) -> None:+ try:+ if _is_oom(val):+ dump_oom_tensor_census_("uncaught")+ except Exception as e: # pragma: no cover - diagnostics must not mask the error+ logger.error("[oom] census hook failed while reporting (%s)", e)+ prior_sys(tp, val, tb)++ def _the_hook(args: threading.ExceptHookArgs) -> None:+ try:+ if _is_oom(args.exc_value):+ name = args.thread.name if args.thread is not None else "?"+ dump_oom_tensor_census_(f"uncaught (thread {name})")+ except Exception as e: # pragma: no cover - diagnostics must not mask the error+ logger.error("[oom] census hook failed while reporting (%s)", e)+ prior_the(args)++ sys.excepthook = _sys_hook+ threading.excepthook = _the_hook+ _OOM_HOOK_INSTALLED = True+ return Truediff --git a/auto_round/utils/perf_counters.py b/auto_round/utils/perf_counters.pynew file mode 100644index 000000000..0aea233cf--- /dev/null+++ b/auto_round/utils/perf_counters.py@@ -0,0 +1,65 @@+# Copyright (C) 2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++import time as _ptime+++class _PerfCounters:+ """Named-span time accumulator behind AR_PERF_COUNTERS.++ Keeps no measurement semantics of its own: callers either bracket code+ with ``start``/``stop`` per key, chain phase boundaries with ``tick``+ (each tick closes the previous span and opens the named one), or feed+ individual durations with ``observe`` (count + total + max per key).+ Times accumulate across brackets. When the env var is off every method+ is a no-op and ``get`` returns 0.0, so call sites need no guards.+ """++ def __init__(self):+ self.enabled = perf_counters_enabled()+ self.totals: dict[str, float] | None = {} if self.enabled else None+ self.counts: dict[str, int] = {}+ self.maxima: dict[str, float] = {}+ self._t0: dict[str, float] = {}+ self._current: str | None = None++ def start(self, key: str) -> None:+ if self.enabled:+ self._t0[key] = _ptime.perf_counter()++ def stop(self, key: str) -> None:+ if self.enabled:+ self.totals[key] = self.totals.get(key, 0.0) + (_ptime.perf_counter() - self._t0.pop(key))++ def tick(self, key: str) -> None:+ """Close the current chain span (if any) and open ``key``."""+ if not self.enabled:+ return+ if self._current is not None:+ self.stop(self._current)+ self.start(key)+ self._current = key++ def observe(self, key: str, duration: float) -> None:+ if self.enabled:+ self.counts[key] = self.counts.get(key, 0) + 1+ self.totals[key] = self.totals.get(key, 0.0) + duration+ self.maxima[key] = max(self.maxima.get(key, 0.0), duration)++ def get(self, key: str) -> float:+ return self.totals.get(key, 0.0) if self.enabled else 0.0++ def set(self, key: str, value: float) -> None:+ if self.enabled:+ self.totals[key] = value+++def perf_counters_enabled() -> bool:+ """Whether AR_PERF_COUNTERS timing output is on.++ Single source of truth for the switch: the recorder and any gating that+ wants the same condition ask here, so the env name cannot drift apart.+ """+ import auto_round.envs as _envs++ return bool(getattr(_envs, "AR_PERF_COUNTERS", False))diff --git a/auto_round/utils/pool_placement.py b/auto_round/utils/pool_placement.pynew file mode 100644index 000000000..0ec311848--- /dev/null+++ b/auto_round/utils/pool_placement.py@@ -0,0 +1,684 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""Per-chunk device placement for block calibration data (--calibration_data_device).++Policy:++* single-device-first: when the consumer device (per-block loss device on+ iters>0 lanes, else the cache primary) holds the pool beside its full charge+ (computed working allowance + flat 0.25 GiB allocator reserve + derived+ collection-window term + occupied pool bytes + per-device activation+ charge), every chunk stays there -- zero peer traffic.+* otherwise water-fill: chunks are placed so every receiving device ends at+ the SAME predicted headroom level (min-max optimal); when the pool+ over-commits the fleet the over-commitment is spread evenly across the+ charged headrooms. Charges: per-device tuning state (14 B/param logical,+ deduped), per-device activation budget (estimator + routed/stacks split by+ expert homes), the consumer's need model, and resident pool bytes.+* ``cpu`` mode parks the pools on host RAM explicitly (forwards still run on+ the GPUs) -- the pool-scoped equivalent of ``low_gpu_mem_usage`` without its+ other side effects. ``auto`` never falls back to CPU silently: over-+ commitment is spread, never parked on the host unasked.++``calibration_data_device`` parameter (CLI ``--calibration_data_device`` / API+keyword): ``auto`` (default) | ``off`` | ``cpu`` | explicit csv (``cuda:1,cuda:2``).+There is deliberately no environment variable for this knob.++CUDA-only today: the free-memory probe underneath is a cuda API, so on other+accelerator families the resolver returns ``None`` (policy inactive, pools keep+their today placement) rather than guessing at unprobed capacities.+"""++from collections.abc import Callable, Sequence+from typing import Any, Optional++import torch++from auto_round.logger import logger+++class PoolPlacement:+ """Deterministic per-chunk device plan for one calibration output pool."""++ def __init__(self, devices: Sequence[str], capacities: Sequence[int], n_chunks: int):+ self.devices = [str(d) for d in devices]+ self.capacities = [int(c) for c in capacities]+ self.plan = _spread_plan(self.devices, self.capacities, n_chunks)++ def device_for_index(self, i: int) -> str:+ """Device for output chunk ``i`` (deterministic, wraps for over-long pools)."""+ return self.plan[i % len(self.plan)]++ def counts(self) -> dict[str, int]:+ """Chunks per device (diagnostics)."""+ out: dict[str, int] = {}+ for d in self.plan:+ out[d] = out.get(d, 0) + 1+ return out++ def __repr__(self) -> str: # pragma: no cover - diagnostics only+ return f"PoolPlacement({self.counts()})"+++def _spread_plan(devices: Sequence[str], capacities: Sequence[int], n_chunks: int) -> list[str]:+ """Largest-remainder proportional split, interleaved across devices.++ Interleaving (round-robin order of the assigned slots) keeps consecutive+ chunks on different devices so transient per-chunk peaks never stack on a+ single peer.+ """+ total = sum(capacities)+ if total <= 0 or n_chunks <= 0 or not devices:+ return list(devices)+ quotas = [c * n_chunks / total for c in capacities]+ counts = [int(q) for q in quotas]+ remainders = sorted(range(len(devices)), key=lambda i: quotas[i] - counts[i], reverse=True)+ for i in range(n_chunks - sum(counts)):+ counts[remainders[i % len(remainders)]] += 1+ # interleave: one slot per device in turn, skipping exhausted devices+ plan: list[str] = []+ cursors = [0] * len(devices)+ while any(cursors[i] < counts[i] for i in range(len(devices))):+ for i in range(len(devices)):+ if cursors[i] < counts[i]:+ plan.append(devices[i])+ cursors[i] += 1+ return plan+++def _bytes_by_device(obj: Any) -> tuple[dict[str, int], int]:+ """(device_str -> bytes, total bytes) for tensor leaves of a nested pool object."""+ per_device: dict[str, int] = {}++ def _walk(o: Any) -> None:+ if isinstance(o, torch.Tensor):+ key = str(o.device)+ per_device[key] = per_device.get(key, 0) + int(o.numel()) * o.element_size()+ elif isinstance(o, dict):+ for v in o.values():+ _walk(v)+ elif isinstance(o, (list, tuple)):+ for v in o:+ _walk(v)++ _walk(obj)+ return per_device, sum(per_device.values())+++def _short_device_key(dev: str) -> str:+ """'cuda:0' -> '0', 'cpu' -> 'cpu' (memory-monitor grammar)."""+ d = str(dev)+ if d.startswith("cuda:"):+ return d.split(":", 1)[1]+ return d+++def calib_data_line(+ inputs: Sequence[Any], aux: Any, plan: PoolPlacement | None, outputs_bytes: int, n_chunks: int, primary: str+) -> str:+ """One-line calibration-data summary in the memory-monitor format:++ ``'input': 8.12GB, 'output': 8.12GB, 'aux': 0.12GB, 'per_device': {'0': 2.03GB, '1': 2.03GB, 'cpu': 0.12GB}``++ ``inputs`` is the list of live input pool objects (fp and q chains merged --+ the dual chain is upstream's qon architecture; during collection both pools+ coexist, which is the peak the placement accounts for). Input/aux devices+ are ground truth (walked from the tensors); output bytes are this block's+ planned placement (the plan, or all-primary under today's behavior).+ Per-device totals combine parked + planned.+ """+ per_device: dict[str, int] = {}+ input_total = 0+ for obj in inputs:+ by_dev, total = _bytes_by_device(obj)+ input_total += total+ for d, b in by_dev.items():+ per_device[d] = per_device.get(d, 0) + b+ by_dev, aux_total = _bytes_by_device(aux)+ for d, b in by_dev.items():+ per_device[d] = per_device.get(d, 0) + b+ if outputs_bytes > 0:+ if plan is not None:+ per_chunk = outputs_bytes / max(n_chunks, 1)+ for dev, cnt in plan.counts().items():+ per_device[dev] = per_device.get(dev, 0) + int(cnt * per_chunk)+ else:+ per_device[str(primary)] = per_device.get(str(primary), 0) + outputs_bytes+ devs = ", ".join(+ f"'{_short_device_key(d)}': {b / 2**30:.2f}GB" for d, b in sorted(per_device.items(), key=lambda kv: -kv[1])+ )+ if plan is None:+ place = "none->primary"+ elif len(plan.devices) == 1:+ place = "single"+ else:+ place = "spread"+ return (+ f"'input': {input_total / 2**30:.2f}GB, 'output': {outputs_bytes / 2**30:.2f}GB, "+ f"'aux': {aux_total / 2**30:.2f}GB, 'plan': '{place}', 'per_device': {{{devs}}}"+ )+++def _tensor_bytes(obj: Any) -> int:+ """Total bytes of tensor leaves in a nested list/tuple/dict pool object."""+ if isinstance(obj, torch.Tensor):+ return int(obj.numel()) * obj.element_size()+ if isinstance(obj, dict):+ return sum(_tensor_bytes(v) for v in obj.values())+ if isinstance(obj, (list, tuple)):+ return sum(_tensor_bytes(v) for v in obj)+ return 0+++def _pool_chunk_count(obj: Any) -> int:+ """Number of per-sample chunks in a pool object (length of first list found)."""+ if isinstance(obj, (list, tuple)):+ tensor_like = [v for v in obj if isinstance(v, torch.Tensor)]+ if tensor_like:+ return len(obj)+ for v in obj:+ n = _pool_chunk_count(v)+ if n:+ return n+ return 0+ if isinstance(obj, dict):+ for v in obj.values():+ n = _pool_chunk_count(v)+ if n:+ return n+ return 0+++def _move_pool_to(obj: Any, target: str) -> Any:+ """Recursively move a pool's tensors onto ``target`` in place (skip locals)."""+ if isinstance(obj, torch.Tensor):+ return obj.to(target) if str(obj.device) != target else obj+ if isinstance(obj, list):+ for i in range(len(obj)):+ obj[i] = _move_pool_to(obj[i], target)+ return obj+ if isinstance(obj, tuple):+ return tuple(_move_pool_to(v, target) for v in obj)+ if isinstance(obj, dict):+ for k in list(obj.keys()):+ obj[k] = _move_pool_to(obj[k], target)+ return obj+ return obj+++def consolidate_pool_onto(+ objs: Sequence[Any], target: str, block: torch.nn.Module, batch_size: int, reserved_bytes: int = 0, iters: int = 0+) -> str:+ """Consolidate the incoming calibration pools onto the compute device.++ Returns ``'local'`` (already on target), ``'consolidated'`` (moved in one+ bulk pass), or ``'spread'`` (the pools do not fit next to the block's+ working set -- consumers keep fetching batch-by-batch instead). This is the+ fits-home rung of the ladder: fit-primary / fit-home -> single device,+ oversized pool -> spread + per-batch gather.+ """+ if not str(target).startswith("cuda"):+ return "spread"+ if any(isinstance(o, (tuple, torch.Tensor)) for o in objs if o is not None):+ # a top-level tuple or bare-tensor pool cannot be moved in place (the+ # move helper returns a NEW object for those; reassigning the caller's+ # list would not rebind the caller's own references) -- leave it and+ # say so rather than reporting a phantom consolidation+ logger.warning(+ "[calib-data-device] top-level %s pool cannot be consolidated in place; leaving it",+ "tuple" if any(isinstance(o, tuple) for o in objs if o is not None) else "tensor",+ )+ return "spread"+ from auto_round.utils.device import probe_usable_bytes++ total = sum(_tensor_bytes(o) for o in objs if o is not None)+ if total <= 0:+ return "local"+ free = probe_usable_bytes(target)+ if free is None:+ return "spread"+ need = placement_need_bytes(block, objs[0], batch_size, iters=iters, primary=target)+ # ``reserved_bytes``: output pools that will share the target this block.+ # The first GPU validation showed the inputs-only budget was optimistic --+ # consolidating 4GiB of inputs onto the busiest device while the outputs+ # were also headed there produced exactly the OOM the policy exists to+ # prevent. Consolidate only when BOTH fit beside the working set.+ if free - need - reserved_bytes < total:+ return "spread"+ devices = set()++ def _collect(o: Any) -> None:+ if isinstance(o, torch.Tensor):+ devices.add(str(o.device))+ elif isinstance(o, dict):+ for v in o.values():+ _collect(v)+ elif isinstance(o, (list, tuple)):+ for v in o:+ _collect(v)++ for o in objs:+ if o is not None:+ _collect(o)+ if devices <= {target}:+ return "local"+ for o in objs:+ if o is not None:+ _move_pool_to(o, target)+ return "consolidated"+++def resolve_pool_placement(+ pool_bytes: int,+ n_chunks: int,+ primary: str,+ need_bytes: int,+ candidate_devices: Sequence[str],+ free_probe: Callable[[str], int | None],+ mode: str = "auto",+ consumer: str | None = None,+ occupied_bytes: int = 0,+ peer_state_bytes: dict | None = None,+ activation_bytes: dict | None = None,+) -> PoolPlacement | None:+ """Decide per-chunk output placement for a calibration pool.++ ``need_bytes`` is the candidate's own forward working-set demand (estimated+ per block via :func:`placement_need_bytes`); the pool must fit in+ ``free(candidate) - need_bytes`` to stay single-device-resident.++ ``consumer`` (iters>0 lane) retargets the single-device preference from the+ cache primary to the block's tune consumer (loss/compute device): the fp+ reference pool is bulk-pulled there anyway, so outputs born on the consumer+ make that pull a no-op and keep the primary free of pool traffic. The cache+ primary then participates as a plain peer (no working-set charge).++ ``occupied_bytes`` counts pool bytes that ALREADY sit on the candidate+ (this block's incoming input pool) against its single-device budget; without+ it the gate alternates -- one block's single plan loads the device, the next+ block's resolve sees less free and spreads, the next one singles again.++ Returns ``None`` when the caller should keep today's behavior (policy off,+ CPU-parked lane, or no usable probed device). Capacity shortfalls do NOT+ return None: the water-fill spreads the pool and, on over-commit, spreads+ the over-commitment evenly across charged headrooms.+ """+ mode = (mode or "auto").strip().lower()+ if mode == "off":+ return None+ if mode == "cpu":+ return PoolPlacement(["cpu"], [1], n_chunks) # explicit host-RAM parking+ if str(primary).startswith("cpu"):+ logger.debug("[calib-data-device] resolve: none (cpu primary)")+ return None # low_gpu_mem_usage (or a CPU lane) owns placement here+ forced = None+ if mode not in ("", "auto"):+ # plain csv list: "cuda:1,cuda:2" or bare indices "1,2" (accelerate+ # device_map style) -- digit tokens get the cuda: prefix+ forced = ["cuda:" + t if t.isdigit() else t for t in (d.strip() for d in mode.split(",")) if t]++ consumer = str(consumer) if consumer is not None else None+ if consumer is not None and (consumer == str(primary) or not consumer.startswith("cuda")):+ consumer = None # degenerate target: fall back to primary-first+ candidates: list[str] = []+ if forced is not None:+ candidates = forced+ elif consumer is not None:+ # consumer-first: the cache primary demotes to a plain peer+ seen = {consumer}+ candidates = [consumer]+ for d in [str(primary)] + [str(x) for x in candidate_devices]:+ if d.startswith("cpu") or d in seen:+ continue+ seen.add(d)+ candidates.append(d)+ else:+ seen = {str(primary)}+ candidates = [str(primary)]+ for d in candidate_devices:+ key = str(d)+ if key.startswith("cpu") or key in seen:+ continue+ seen.add(key)+ candidates.append(key)++ probed = [(d, free_probe(d)) for d in candidates]+ rejected = [d for d, f in probed if f is None]+ if rejected:+ # a forced csv with a typo (e.g. cuda1) must not vanish silently+ logger.warning(+ "[calib-data-device] ignoring unusable device entr%s %s (not parseable as a cuda device with free memory)",+ "y" if len(rejected) == 1 else "ies",+ ", ".join(rejected),+ )+ usable = [(d, f) for d, f in probed if f is not None and f > 0]+ if not usable:+ logger.debug("[calib-data-device] resolve: none (no usable device among %s)", candidates)+ return None++ eff = consumer if consumer is not None else str(primary)+ primary_free = dict(usable).get(eff, 0)+ _act = activation_bytes or {}+ _eff_charge = need_bytes + occupied_bytes + _act.get(eff, 0)+ if primary_free - _eff_charge >= pool_bytes:+ # single-device-first: identical to today's behavior, zero peer+ # traffic; the activation charge matches the water-fill rung below+ # (without it the rung takes a single plan the loop cannot hold)+ return PoolPlacement([eff], [max(primary_free - _eff_charge, 1)], n_chunks)++ # Water-fill placement with full charges: place the pool so every+ # receiving device ends at the SAME predicted headroom level t --+ # i.e. minimize the maximum predicted VRAM across the fleet,+ # calculated upfront. Per-device headroom h_i = free_i - charge_i,+ # where the charge is the device's own in-loop load that materializes+ # after this probe (tuning state x 14 B/param on every device, the+ # entry's forward-graph activation budget, the consumer's working set+ # and resident pool bytes). Allocation a_i = max(h_i - t, 0) with t+ # solving sum(a_i) = pool_bytes:+ # t >= 0 : everything fits; every receiver ends with the common+ # margin t (min-max optimal -- nobody is the thin card);+ # t < 0 : the pool over-commits the fleet; the over-commitment is+ # spread EVENLY (each device exceeds its charged headroom+ # by the same -t) instead of piling onto whoever had raw+ # free. There is no ignore-charges branch: the charges+ # shape the split in both regimes.+ peer_state = peer_state_bytes or {}+ act = activation_bytes or {}+ headroom = [+ f - (need_bytes + occupied_bytes if d == eff else peer_state.get(d, 0)) - act.get(d, 0) for d, f in usable+ ]+ # solve the level t by binary search on monotone g(t) = sum(max(h-t,0)) - pool+ lo, hi = min(headroom) - pool_bytes, max(headroom)+ for _ in range(64):+ mid = (lo + hi) / 2+ if sum(max(h - mid, 0) for h in headroom) > pool_bytes:+ lo = mid+ else:+ hi = mid+ level = (lo + hi) / 2+ alloc = [max(h - level, 0) for h in headroom]+ if sum(alloc) <= 0: # degenerate: keep the planless default (loud OOM path)+ logger.debug(+ "[calib-data-device] resolve: none (all candidate headrooms exhausted; pool %.2fGiB)",+ pool_bytes / 2**30,+ )+ return None+ devs = [d for (d, _f), a in zip(usable, alloc) if a > 0]+ caps = [int(a) for (d, _f), a in zip(usable, alloc) if a > 0]+ plan_obj = PoolPlacement(devs, caps, n_chunks)+ plan_obj.level_bytes = int(level) # common predicted headroom after fill (negative = even over-commit)+ return plan_obj+++# Minimal fragmentation pad for probe->peak drift. NOT card-proportional:+# fragmentation does not scale with device size, and the free-memory probe is+# the primary actual signal this pad only backs up. Observed on 24 GiB cards:+# the linear_loop tune loop ran at 23.09-23.14 GiB reserved of 23.58 (~98%)+# without OOM, so the pad needs only cover allocator slack in the last+# allocations. Proportional ceilings, where wanted, belong to budget ratios+# (cf. max_mem_ratio/card_0_threshold=0.9 in the mapped-placement path).+_RESERVE_BYTES = int(0.25 * 2**30)+# Floor for the computed working allowance (tiny blocks / degenerate reads)+_WORKING_FLOOR_BYTES = int(0.125 * 2**30)+++def _activation_bytes_for(+ block: torch.nn.Module, pool: Any, batch_size: int, iters: int, config: Any+) -> dict[str, int]:+ """Per-device activation budget charged into every device's headroom.++ The tune loop's forward/backward graph executes on EVERY device the+ block spans: each module's saved output + grad lands on the module's+ weight home (the entry's batch cats AND the MoE stages' routed-row+ caches, which state-only charges leave unpriced). {device: bytes}; {} when+ unknown (charges nothing).+ """+ if iters <= 0:+ return {}+ try:+ from auto_round.algorithms.quantization.tune_memory import _activation_bytes_by_device++ got = _activation_bytes_by_device(block, pool, batch_size, config)+ return {str(d): int(b) for d, b in got.items()} if got else {}+ except Exception as e: # pragma: no cover - placement must never break+ logger.warning(+ "[calib-data-device] activation budget unavailable (%s); continuing without the activation charge", e+ )+ return {}+++def _state_bytes_by_device(block: torch.nn.Module) -> dict[str, int]:+ """In-loop tuning state per device: params homed there x 14 B (actual walk).++ Same layout constant as :func:`placement_need_bytes` (fp32 value + grad ++ best-params snapshot + bf16 copy), computed for EVERY device so pool+ placement can charge peers too. At attach time (when pools are placed)+ none of it exists yet: values materialize at wrap, grads and snapshots+ during the loop -- which is exactly why peer devices left at their full+ probed free over-fill by the first snapshot write (observed: 24 MiB+ snapshot ask failing at 5.5 MiB free on a card the resolve gate had+ treated as empty).+ """+ out: dict[str, int] = {}+ try:+ for p in block.parameters():+ out[str(p.device)] = out.get(str(p.device), 0) + p.numel() * 14+ except Exception as e: # pragma: no cover - placement must never break+ logger.warning("[calib-data-device] per-device state walk failed (%s); continuing without the state charge", e)+ return {}+ return out+++def _dominant_param_esize(block: torch.nn.Module) -> int:+ """Element size (bytes) of the block's dominant parameter dtype."""+ counts: dict[int, int] = {}+ try:+ for p in block.parameters():+ counts[p.element_size()] = counts.get(p.element_size(), 0) + p.numel()+ except Exception as e: # pragma: no cover - exotic modules: fall back to bf16-ish+ logger.warning("[calib-data-device] dominant-esize walk failed on %r (%s); assuming 2", block, e)+ return 2+ return max(counts, key=lambda k: counts[k]) if counts else 2+++def _widest_out_and_hidden(block: torch.nn.Module) -> tuple[int, int | None]:+ """(widest out_features, modal in_features) over the block's Linear/Conv1D."""+ """+ The modal in_features approximates the hidden size (every attention/mlp+ projection consumes hidden-wide inputs); the widest out_features bounds+ the largest single-module activation buffer (e.g. a wide shared-expert+ up/gate projection), which is the dominant transient that lives next to+ the pools during a collection forward.+ """+ import transformers++ in_counts: dict[int, int] = {}+ widest = 0+ for m in block.modules():+ w = getattr(m, "weight", None)+ if not isinstance(w, torch.Tensor) or w.dim() != 2:+ continue+ if type(m) == transformers.pytorch_utils.Conv1D:+ in_f, out_f = int(w.shape[0]), int(w.shape[1])+ elif isinstance(m, torch.nn.Linear):+ in_f, out_f = int(w.shape[1]), int(w.shape[0])+ else:+ continue+ in_counts[in_f] = in_counts.get(in_f, 0) + 1+ widest = max(widest, out_f)+ hidden = max(in_counts, key=lambda k: in_counts[k]) if in_counts else None+ return widest, hidden+++def _working_allowance_bytes(block: torch.nn.Module, pool: Any, batch_size: int) -> int:+ """Simultaneous-transient allowance for one collection/tune batch."""+ """+ First principles: at any instant during a block forward, the transients+ sitting next to the pools are (a) the batch IO on the compute device --+ the staged input batch plus the produced output batch (2 generations of+ batch_size`` pool samples), and (b) ONE module's activation buffer, the+ widest projection's ``tokens x out_features`` in the block's dominant+ dtype (in+out buffers -> x2). The earlier flat 3 GiB charge was derived+ for one config; this derives the same quantity from the block and pool+ actually being placed. Over-charging is the safe direction (less+ consolidation); the derived value tracks the observed worst-case+ simultaneous set within ~20%.+ """+ try:+ per_chain = _tensor_bytes(pool)+ n_chunks = max(_pool_chunk_count(pool), 1)+ batch_bytes = int(per_chain * min(int(batch_size), n_chunks) / n_chunks)+ need = 2 * batch_bytes+ widest, hidden = _widest_out_and_hidden(block)+ sample_numel = 0+ if isinstance(pool, (list, tuple)) and pool:+ for v in pool:+ if isinstance(v, torch.Tensor):+ sample_numel = int(v.numel())+ break+ if widest and hidden and sample_numel:+ tokens = sample_numel * min(int(batch_size), n_chunks) / hidden+ esize = _dominant_param_esize(block)+ need += int(tokens * widest * esize * 2)+ return max(need, _WORKING_FLOOR_BYTES)+ except Exception as e: # pragma: no cover - placement must never break quantization+ logger.warning(+ "[calib-data-device] working-set estimate failed for %s (%s); using %.2fGiB floor",+ type(block).__name__,+ e,+ _WORKING_FLOOR_BYTES / 2**30,+ )+ return _WORKING_FLOOR_BYTES+++def placement_need_bytes(+ block: torch.nn.Module, pool: Any, batch_size: int, iters: int = 0, primary: str | None = None+) -> int:+ """Candidate-device working-set need for the placement gates, first principles.++ The earlier port reused ``estimate_tuning_block_mem`` (mapped-placement+ card-0 accounting), whose MoE term overprices a large MoE block by an order+ of magnitude: every module's batch activation counted with a x2 grad+ multiplier stacked with the x6 routing fudge, all assumed simultaneously+ live. That vetoed every primary residency for every MoE block. An+ intermediate model additionally charged ``2 * pool bytes`` as a+ "window-2 retention" term -- but that retention IS the in+out pool pair+ itself, which the gates already count explicitly (``total`` ++ ``reserved_bytes`` in the consolidation gate, ``pool_bytes`` ++ ``occupied_bytes`` in the resolve gate). A first revision took that+ reasoning too far and dropped the term+ from the RESOLVE gate as well -- but there it encodes the empirical+ collection window (retained batch outputs + route caches ~= 2x pool+ bytes on a single-compute-device MoE block), and dropping it let a+ single-device plan through that OOMed on the first multi-GPU run. The+ term is restored, making the need strictly >= the validated formula;+ the computed allowance below is the additional, tune-loop-accurate+ part. Total charge:++ - the computed batch working allowance (``_working_allowance_bytes``:+ 2 batch IO generations + the widest projection's activation buffer,+ derived from this block and pool -- NOT a flat constant);+ - at iters>0 only, the per-parameter tuning state that materializes on+ each weight's home device at wrap time (fp32 value + fp32 grad ++ best-params snapshot + bf16 copy = 14 B/param), charged for parameters+ homed on the candidate device alone -- peers host their own state and+ pay nothing. Wrap-phase coexistence (pools + state) is what makes this+ term real even though state materializes after collection;+ - the flat 0.25 GiB allocator reserve (a fragmentation pad does not scale+ with card size; the free-memory probe is the primary capacity signal).+ """+ try:+ need = _working_allowance_bytes(block, pool, batch_size) + _RESERVE_BYTES+ # Collection-window term (window~=2 chain retention + the+ # linear_loop route caches: on a single-compute-device iters=0 MoE+ # block the live transients reach ~3x pool bytes -- retained+ # batch-shaped outputs plus selected-hidden next to the pool). An+ # earlier revision dropped this term as a "double count" and the+ # first multi-GPU run OOMed exactly there; the computed allowance+ # models the TUNE loop's+ # transients, not the collection forward's. Keeping the term makes+ # this need strictly >= the previously validated formula, so every+ # placement decision can only be equal or more conservative.+ need += 2 * _tensor_bytes(pool)+ if iters > 0 and block is not None and primary is not None:+ state_bytes = sum(p.numel() for p in block.parameters() if str(p.device) == str(primary)) * 14+ need += state_bytes+ return int(need)+ except Exception as e: # pragma: no cover - placement must never break quantization+ logger.warning(+ "[calib-data-device] working-set estimate failed for %s (%s); using %.2fGiB floor",+ type(block).__name__,+ e,+ _WORKING_FLOOR_BYTES / 2**30,+ )+ return _WORKING_FLOOR_BYTES + _RESERVE_BYTES+++def resolve_placement_for_pool(+ pool: Any,+ chains: int,+ primary: str,+ candidate_devices: Sequence[str],+ block: torch.nn.Module | None = None,+ batch_size: int = 8,+ mode: str = "auto",+ iters: int = 0,+ consumer: str | None = None,+ config: Any = None,+) -> PoolPlacement | None:+ """Resolve placement from a live pool object (orchestrator entry point).++ ``primary`` must be the lane's actual cache device: a CPU primary+ (``low_gpu_mem_usage``) deactivates the policy so the two mechanisms never+ fight. ``chains`` doubles the byte demand when a second (quantized-input)+ pool of the same size will also be produced for the block. ``block`` feeds+ the per-block working-set estimate. ``consumer`` (iters>0 lane) retargets+ the single-device preference to the tune consumer device; see+ :func:`resolve_pool_placement`.+ """+ from auto_round.utils.device import probe_usable_bytes++ pool_bytes = _tensor_bytes(pool) * max(int(chains), 1)+ n_chunks = _pool_chunk_count(pool)+ if n_chunks <= 0 or pool_bytes <= 0:+ return None+ consumer = str(consumer) if consumer is not None else None+ by_dev, _ = _bytes_by_device(pool)+ # occupied = pool bytes already resident on the SINGLE-DEVICE candidate+ # (consumer when retargeted, else the cache primary). Charging it for+ # the primary too is what stops the block-N single plan from ignoring+ # the input pool the block-N-1 single plan left sitting there (the+ # block-2 OOM: 4 GiB uncharged). The q-input pool mirrors the fp+ # pool's placement (same chunk layout), so resident bytes scale with+ # the chain multiplier.+ occupied = int(by_dev.get(str(consumer if consumer is not None else primary), 0) * max(int(chains), 1))+ try:+ plan = resolve_pool_placement(+ pool_bytes,+ n_chunks,+ primary,+ placement_need_bytes(block, pool, batch_size, iters=iters, primary=consumer or primary),+ candidate_devices,+ probe_usable_bytes,+ mode=mode,+ consumer=consumer,+ occupied_bytes=occupied,+ peer_state_bytes=_state_bytes_by_device(block) if iters > 0 else None,+ activation_bytes=_activation_bytes_for(block, pool, batch_size, iters, config) if iters > 0 else None,+ )+ except Exception as e: # pragma: no cover - placement must never break quantization+ logger.warning("[calib-data-device] placement resolve failed (%s); keeping single-device behavior", e)+ return None+ return plandiff --git a/auto_round/utils/resume.py b/auto_round/utils/resume.pyindex 79872bb03..d8e74fa5c 100644--- a/auto_round/utils/resume.py+++ b/auto_round/utils/resume.py@@ -28,6 +28,7 @@ import jsonimport osimport tempfilefrom pathlib import Path+from typing import Anyimport torch@@ -40,6 +41,24 @@ _Q_INPUT_NAME = "resume_q_input.pt"_INPUT_IDS_NAME = "resume_input_ids.pt"+def snapshot_pool_refs(obj: Any) -> Any:+ """Shallow-freeze a calibration pool's container structure for async save.++ Copies the list/tuple/dict skeleton (cheap, synchronous) while passing+ tensor REFERENCES through untouched: pool tensors are never mutated in+ place (placement moves create new tensors and swap container entries), so+ a frozen skeleton lets a background thread safely run ``_to_cpu_recursive``+ + ``torch.save`` while the main thread continues tuning the next block.+ """+ if isinstance(obj, dict):+ return {k: snapshot_pool_refs(v) for k, v in obj.items()}+ if isinstance(obj, list):+ return [snapshot_pool_refs(v) for v in obj]+ if isinstance(obj, tuple):+ return tuple(snapshot_pool_refs(v) for v in obj)+ return obj++def _to_cpu_recursive(obj):"""`q_input` (SignRound's `enable_quanted_input` chain value) may be aplain Tensor or a nested list/tuple/dict of tensors depending on thediff --git a/auto_round/wrapper.py b/auto_round/wrapper.pyindex ac59c2916..afdb48dba 100644--- a/auto_round/wrapper.py+++ b/auto_round/wrapper.py@@ -118,7 +118,9 @@ class WrapperLinear(torch.nn.Module):self.q_scale_thresh = 1e-8else:self.q_scale_thresh = 1e-5- self._init_tuning_params_and_quant_func()+ # consumed here so subclasses never see it in **kwargs; forwarded to the+ # search init (staging for batched same-shape wrap searches)+ self._init_tuning_params_and_quant_func(defer_search=bool(kwargs.pop("defer_search", False)))if deepspeed_exists:if type(self.orig_layer) in (torch.nn.Linear, LinearLayer):self.orig_forward = self.linear_forward@@ -138,7 +140,7 @@ class WrapperLinear(torch.nn.Module):def bias(self):return self.orig_layer.bias- def _init_tuning_params_and_quant_func(self):+ def _init_tuning_params_and_quant_func(self, defer_search: bool = False):"""Initializes tuning parameters and quantization functions.This method sets up required parameters and functions for weight quantization,@@ -204,19 +206,31 @@ class WrapperLinear(torch.nn.Module):"enable_neuqi anchors the tuning grid to its own search result, which ""overrides the AWQ clip-as-init range on this layer; the clip is ignored.")- from auto_round.data_type.neuqi import neuqi_anchor_margins-- _wmin, _wmax = neuqi_anchor_margins(- weight_reshape,- self.orig_layer.bits,- orig_layer.group_size,- getattr(orig_layer, "imatrix", None),- self.device,- sym=bool(getattr(orig_layer, "sym", True)),- )- self._neuqi_frozen_margins = True- self.weight_min = _wmin.to(self.weight_min.dtype)- self.weight_max = _wmax.to(self.weight_max.dtype)+ if defer_search:+ # staged for the batched anchor driver; the margins keep the+ # plain min/max until the batch pass applies the searched ones+ self._deferred_neuqi_anchor = (+ weight_reshape,+ self.orig_layer.bits,+ orig_layer.group_size,+ getattr(orig_layer, "imatrix", None),+ bool(getattr(orig_layer, "sym", True)),+ )+ self._neuqi_frozen_margins = True+ else:+ from auto_round.data_type.neuqi import neuqi_anchor_margins++ _wmin, _wmax = neuqi_anchor_margins(+ weight_reshape,+ self.orig_layer.bits,+ orig_layer.group_size,+ getattr(orig_layer, "imatrix", None),+ self.device,+ sym=bool(getattr(orig_layer, "sym", True)),+ )+ self._neuqi_frozen_margins = True+ self.weight_min = _wmin.to(self.weight_min.dtype)+ self.weight_max = _wmax.to(self.weight_max.dtype)self._init_params("value", p_dtype, weight_reshape.shape, 0, self.enable_round_tuning and self.orig_layer.bits < 16)@@ -281,6 +295,132 @@ class WrapperLinear(torch.nn.Module):setattr(self, name, p)+ def _apply_qdq(self, qdq_weight: torch.Tensor, scale: "torch.Tensor | dict", zp: "torch.Tensor | dict") -> None:+ """Write a quantize-dequantized result back onto the original layer.++ The single source of the unwrapper's write-back conventions (weight+ copy, scale/zp attribute shapes and devices, grad reset, global+ scale), shared with the batched zero-shot search driver.+ """+ self.orig_layer.weight.data.copy_(qdq_weight)+ self.orig_layer.weight.grad = None++ shape = qdq_weight.shape+ if type(self.orig_layer) == transformers.pytorch_utils.Conv1D:+ shape = qdq_weight.t().shape++ def _set_dict_attr(attr_dict: dict, attr_name: str) -> None:+ for key, value in attr_dict.items():+ if key == attr_name:+ setattr(self.orig_layer, attr_name, value.reshape(shape[0], -1).to("cpu"))+ else:+ name = "w_" + key+ setattr(self.orig_layer, name, value.to("cpu"))++ if not isinstance(self.orig_layer.group_size, tuple):+ if isinstance(scale, dict):+ _set_dict_attr(scale, "scale")+ elif scale is None:+ self.orig_layer.scale = None+ elif scale.numel() > 1:+ self.orig_layer.scale = scale.reshape(shape[0], -1).to("cpu")+ else:+ self.orig_layer.scale = scale.view(-1).to("cpu")+ else:+ self.orig_layer.scale = scale.to("cpu")++ if zp is not None:+ if isinstance(zp, dict):+ _set_dict_attr(zp, "zp")+ elif isinstance(zp, torch.Tensor):+ if zp.numel() > 1:+ zp = zp.reshape(shape[0], -1)+ self.orig_layer.zp = zp.to("cpu")+ else:+ self.orig_layer.zp = zp.view(-1).to("cpu")+ else:+ self.orig_layer.zp = zp+ else:+ self.orig_layer.zp = None++ if self.weight_global_scale is not None:+ global_scale = self.weight_global_scale+ assert global_scale.numel() == 1+ self.orig_layer.weight_global_scale = global_scale.to("cpu")++ def _run_deferred_neuqi_anchor_now(self) -> None:+ """Run the staged NeUQI grid anchor per module (fallback when batching is off)."""+ staged = getattr(self, "_deferred_neuqi_anchor", None)+ if staged is None:+ return+ weight_reshape, bits, group_size, imatrix_raw, sym = staged+ from auto_round.data_type.neuqi import neuqi_anchor_margins++ # run on the weight's own device when it is accelerator-resident: the+ # tuning device also hosts the pools and calibration state, so a+ # per-module fallback that pulls every search there can exhaust it+ device = weight_reshape.device if weight_reshape.device.type == "cuda" else self.device+ wmin, wmax = neuqi_anchor_margins(weight_reshape, bits, group_size, imatrix_raw, device, sym=sym)+ self._apply_neuqi_anchor(wmin, wmax)++ def _apply_neuqi_anchor(self, wmin: "torch.Tensor", wmax: "torch.Tensor") -> None:+ """Adopt a searched anchor, computed alone or on a stacked same-shape batch."""+ self.weight_min = wmin.reshape(self.weight_min.shape).to(+ device=self.weight_min.device, dtype=self.weight_min.dtype+ )+ self.weight_max = wmax.reshape(self.weight_max.shape).to(+ device=self.weight_max.device, dtype=self.weight_max.dtype+ )+ self._deferred_neuqi_anchor = None++ def _quant_call_kwargs(+ self,+ value: torch.Tensor,+ min_scale: torch.Tensor,+ max_scale: torch.Tensor,+ imatrix_override: torch.Tensor | None = None,+ ) -> dict:+ """Assemble the weight_quant_func call kwargs from wrapper + layer state.++ Single source of the quant-call contract, shared by the serial+ ``_qdq_weight`` path and the batched zero-shot search driver (which+ passes an explicit stacked ``imatrix_override``). ``weight_quant_func``+ itself takes the weight as its first positional argument.+ """+ quant_kwargs = {}+ if hasattr(self.orig_layer, "super_bits"):+ quant_kwargs["super_bits"] = self.orig_layer.super_bits+ quant_kwargs["super_group_size"] = self.orig_layer.super_group_size+ if hasattr(self, "_extra_quant_kwargs"):+ quant_kwargs.update(self._extra_quant_kwargs())+ imatrix = imatrix_override+ if imatrix is None:+ if hasattr(self.orig_layer, "imatrix"):+ # a meta-resident stored weight (low-memory/offload lanes) must+ # not become the relocation target -- the imatrix would go meta+ # too while the weight itself is read through get_weight() onto+ # the compute device; relocate to the effective compute device+ _target = self.device if self.orig_layer.weight.device.type == "meta" else self.orig_layer.weight.device+ imatrix = self.orig_layer.imatrix.to(_target)+ else:+ imatrix = None+ return {+ "bits": self.orig_layer.bits,+ "group_size": self.orig_layer.group_size,+ "v": value,+ "min_scale": min_scale,+ "max_scale": max_scale,+ "scale_dtype": self.orig_layer.scale_dtype,+ "tensor_min": self.weight_min,+ "tensor_max": self.weight_max,+ "data_type": self.data_type,+ "q_scale_thresh": self.q_scale_thresh,+ "imatrix": imatrix,+ "global_scale": getattr(self, "weight_global_scale", None),+ "init_scale": getattr(self, "init_scale", None),+ **quant_kwargs,+ }+def _qdq_weight(self, value, min_scale, max_scale):"""Quantizes and dequantizes weights with tuning parameters.@@ -292,6 +432,15 @@ class WrapperLinear(torch.nn.Module):Returns:tuple: Quantized weight, scale, and zero point."""+ presolved = getattr(self, "_presolved_qdq", None)+ if presolved is not None:+ # Batched-search write-back: the search already ran on a stacked+ # tensor; skip the recompute but keep everything downstream of this+ # method (write-back conventions + the full unwrapper tail --+ # bias/meta/update, static-act rescale, WrapperWALayer attachment)+ # identical to the serial path.+ self._presolved_qdq = None+ return presolvedif self.orig_layer.bits >= 16:return self.orig_layer.weight, None, Nonemin_bound, max_bound = self.minmax_scale_bound@@ -312,20 +461,12 @@ class WrapperLinear(torch.nn.Module):weight_q, scale, zp = self.weight_quant_func(weight.to(self.device),- bits=self.orig_layer.bits,- group_size=self.orig_layer.group_size,- v=value,- min_scale=min_scale,- max_scale=max_scale,- scale_dtype=self.orig_layer.scale_dtype,- tensor_min=self.weight_min,- tensor_max=self.weight_max,- data_type=self.data_type,- q_scale_thresh=self.q_scale_thresh,- imatrix=self.orig_layer.imatrix.to(weight.device) if hasattr(self.orig_layer, "imatrix") else None,- global_scale=getattr(self, "weight_global_scale", None),- init_scale=getattr(self, "init_scale", None),- **quant_kwargs,+ **self._quant_call_kwargs(+ value,+ min_scale,+ max_scale,+ imatrix_override=None,+ ),)weight_q = weight_q.to(weight.dtype)if type(self.orig_layer) == transformers.pytorch_utils.Conv1D:@@ -410,53 +551,7 @@ class WrapperLinear(torch.nn.Module):self.orig_layer.to(self.device)# Unwrapper weightqdq_weight, scale, zp = self._qdq_weight(v, min_scale, max_scale)- # if hasattr(self.orig_layer, "imatrix"):- # self.orig_layer.imatrix = None- self.orig_layer.weight.data.copy_(qdq_weight)- self.orig_layer.weight.grad = None-- shape = qdq_weight.shape- if type(self.orig_layer) == transformers.pytorch_utils.Conv1D:- shape = qdq_weight.t().shape-- def _set_dict_attr(attr_dict, attr_name):- for key in attr_dict.keys():- if key == attr_name:- setattr(self.orig_layer, attr_name, attr_dict[key].reshape(shape[0], -1).to("cpu"))- else:- name = "w_" + key- setattr(self.orig_layer, name, attr_dict[key].to("cpu"))-- if not isinstance(self.orig_layer.group_size, tuple):- if isinstance(scale, dict):- _set_dict_attr(scale, "scale")- elif scale is None:- self.orig_layer.scale = None- elif scale.numel() > 1:- self.orig_layer.scale = scale.reshape(shape[0], -1).to("cpu")- else:- self.orig_layer.scale = scale.view(-1).to("cpu")- else:- self.orig_layer.scale = scale.to("cpu")-- if zp is not None:- if isinstance(zp, dict):- _set_dict_attr(zp, "zp")- elif isinstance(zp, torch.Tensor):- if zp.numel() > 1:- zp = zp.reshape(shape[0], -1)- self.orig_layer.zp = zp.to("cpu")- else:- self.orig_layer.zp = zp.view(-1).to("cpu")- else:- self.orig_layer.zp = zp- else:- self.orig_layer.zp = None-- if self.weight_global_scale is not None:- global_scale = self.weight_global_scale- assert global_scale.numel() == 1- self.orig_layer.weight_global_scale = global_scale.to("cpu")+ self._apply_qdq(qdq_weight, scale, zp)# Unwrapper biasif self.enable_norm_bias_tuning and "bias_v" in best_params.keys(): ##fake quant@@ -843,37 +938,74 @@ def wrapper_block("""quantized_layers = []unquantized_layers = []++ # Wrap-time searches (SignRoundV2 init-scale, GGUF DQ scale) read only the+ # module's own weight plus per-module statistics, never calibration+ # activations; eligible searches run later in one stacked batched call per+ # (device, shape, config, search fn).+ work = []for n, m in block.named_modules():if type(m) in SUPPORTED_LAYER_TYPES:- if not check_to_quantized(m):- unquantized_layers.append(n)- continue- new_m = wrapper_cls(- m,- enable_minmax_tuning=enable_minmax_tuning,- enable_norm_bias_tuning=enable_norm_bias_tuning,- enable_torch_compile=enable_torch_compile,- device=device,- **kwargs,- )- set_module(block, n, new_m)- quantized_layers.append(n)-- elif enable_norm_bias_tuning:- if "norm" in m.__class__.__name__.lower():- if m.__class__.__name__ in NORM_MAPPING:- wrapper_layer_class = NORM_MAPPING[m.__class__.__name__]- new_m = wrapper_layer_class(m, device=device)- set_module(block, n, new_m)- elif "RMSNorm" in m.__class__.__name__:- logger.warning_once(- f"use LlamaRMSNorm to wrap {m.__class__.__name__}, please check the correctness yourself"- )- wrapper_layer_class = NORM_MAPPING["LlamaRMSNorm"]- new_m = wrapper_layer_class(m, device=device)- set_module(block, n, new_m)- else:- logger.warning_once(f"{m.__class__.__name__} is not supported")+ work.append((n, m, "skip" if not check_to_quantized(m) else "linear"))+ elif enable_norm_bias_tuning and "norm" in m.__class__.__name__.lower():+ work.append((n, m, "norm"))++ from auto_round.algorithms.quantization import search_dispatch++ _defer_batch = (+ bool(getattr(wrapper_cls, "supports_batched_search", False)) and not search_dispatch.batched_search_disabled()+ )+ deferred_wrappers = []++ def _wrap_one(n: str, m: torch.nn.Module, kind: str) -> torch.nn.Module:+ if kind == "norm":+ if m.__class__.__name__ in NORM_MAPPING.keys():+ wrapper_layer_class = NORM_MAPPING[m.__class__.__name__]+ new_m = wrapper_layer_class(m, device=device)+ set_module(block, n, new_m)+ elif "RMSNorm" in m.__class__.__name__:+ logger.warning_once(+ f"use LlamaRMSNorm to wrap {m.__class__.__name__}, please check the correctness yourself"+ )+ wrapper_layer_class = NORM_MAPPING["LlamaRMSNorm"]+ new_m = wrapper_layer_class(m, device=device)+ set_module(block, n, new_m)+ else:+ logger.warning_once(f"{m.__class__.__name__} is not supported")+ return None+ if kind == "skip":+ return "u"+ extra = {"defer_search": True} if _defer_batch else {}+ new_m = wrapper_cls(+ m,+ enable_minmax_tuning=enable_minmax_tuning,+ enable_norm_bias_tuning=enable_norm_bias_tuning,+ enable_torch_compile=enable_torch_compile,+ device=device,+ **kwargs,+ **extra,+ )+ set_module(block, n, new_m)+ if _defer_batch:+ deferred_wrappers.append(new_m)+ return "q"++ results = [_wrap_one(n, m, kind) for n, m, kind in work]++ if _defer_batch and deferred_wrappers:+ anchor_pending = [w for w in deferred_wrappers if getattr(w, "_deferred_neuqi_anchor", None) is not None]+ if anchor_pending:+ if not search_dispatch.run_batched_neuqi_anchors(anchor_pending):+ for w in anchor_pending:+ w._run_deferred_neuqi_anchor_now()+ # stacked same-shape batches per (device, shape, config, search fn);+ # singletons and the kill-switch fall back to the identical per-module call+ if not search_dispatch.run_batched_wrap_search(deferred_wrappers):+ for w in deferred_wrappers:+ w._run_deferred_search_now()++ quantized_layers = [n for (n, _m, _k), r in zip(work, results) if r == "q"]+ unquantized_layers = [n for (n, _m, _k), r in zip(work, results) if r == "u"]return quantized_layers, unquantized_layersdiff --git a/docs/environments.md b/docs/environments.mdindex 7a45324f1..66e5f1788 100644--- a/docs/environments.md+++ b/docs/environments.md@@ -161,10 +161,10 @@ export AR_NEUQI_BACKEND=eager```### 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 `torch.compile` is enabled (the default except on Windows). 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`+- **Description**: Minimum value to which `torch._dynamo`'s `cache_size_limit`, `accumulated_cache_size_limit`, and `recompile_limit` are bumped when `torch.compile` is enabled (the default except on Windows). 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. On multi-device runs the target is scaled by the number of engaged devices (per-layer shapes multiplied by per-device guard pins); single-device runs use the value as-is.+- **Default**: `16` (per engaged device on multi-device runs)- **Valid Values**: positive integer-- **Usage**: Increase if your model has more than 16 distinct linear-weight shapes per block (rare).+- **Usage**: Increase if your model has more than 16 distinct linear-weight shapes per block per engaged device (rare).```bashexport AR_DYNAMO_CACHE_SIZE_LIMIT=32@@ -282,6 +282,56 @@ export AR_DISK_STREAM_MODEL=1AR_ALLOW_W8_ASYM=1 python -m auto_round --model ... --scheme W8A16 --asym --format auto_round```+### AR_DISABLE_BATCHED_SEARCH+- **Description**: Disables the batched quantization-search machinery: SignRoundV2 wrap-time init-scale searches (iters>0) and optimized-RTN scale searches (iters=0) then run fully serially (the GGUF DQ scale search always runs inline per module), one module at a time, on the device hosting each weight. Batching stacks modules sharing device/shape/config into one call with bit-identical per-module results; set this to fall back to the serial loop (e.g. for debugging or bisecting a suspected batching-related difference). Stacking also changes the transient VRAM envelope (see `AR_SEARCH_BATCH_GB`).+- **Default**: `0` (batching enabled)+- **Valid Values**: `0` / `1`+- **Usage**: Kill switch for the batched/parallel search machinery.++```bash+AR_DISABLE_BATCHED_SEARCH=1 python -m auto_round --model ... --device_map 0,1,2,3+```++### AR_PERF_COUNTERS+- **Description**: Emits one per-block `[perf] tune phases` INFO line with the wall time of each tuning phase (wrap / prepare / loop / tail) and, inside the loop, the sampler draw, best-params snapshots, gradient sync + optimizer step, rest, and the serial forward+loss+backward time. Intended for performance attribution of large multi-device quantization runs; adds negligible overhead.+- **Default**: `0` (disabled)+- **Valid Values**: `0` / `1`+- **Usage**: Set during benchmarking runs to attribute block time to wrap searches vs the tuning loop.++```bash+AR_PERF_COUNTERS=1 python -m auto_round --model ... --device_map 0,1,2,3+```++### AR_SEARCH_BATCH_GB+- **Description**: Explicit override for the batched quantization searches' stacked-batch size, in GiB of stacked fp32 weights per batched call. Applies to ALL batched lanes: the iters=0 optimized-RTN search, the iters>0 wrapper init search, and the NeUQI grid anchors. When unset, batch sizes are capacity-driven: each batch is sized so the search's transient footprint (an fp32 copy chain over the batch, plus the NeUQI sweeps' capped internal temporaries when applicable) fits in half the probed free VRAM, and every executing device re-checks headroom at call time (an oversized batch halves instead of faulting). Set this only to cap batches below what the capacity planning would choose.+- **Default**: unset (capacity-driven sizing)+- **Valid Values**: positive float (GiB)+- **Usage**: Shrink batches on memory-tight multi-device runs.++```bash+AR_SEARCH_BATCH_GB=0.5 python -m auto_round --model ... --device_map 0,1+```++### AR_MOE_EXPERTS_IMPL+- **Description**: Experts forward used during MoE tuning for models that were unfused into per-expert modules. `auto` (default) predicts the per-device VRAM of the grouped-GEMM tuning path before the first MoE block and selects `linear_loop` for the whole run when grouped tuning cannot fit (qdq stack retention plus in-loop tuning state vs the free memory of each device); the decision and the per-device numbers are logged. Explicit values are never overridden by `auto`.+- **Default**: `auto`+- **Valid Values**: `auto`, `linear_grouped`, `linear_grouped_sliced`, `linear_loop`+- **Usage**: Force a specific experts implementation for tuning, or keep `auto` to let the memory model choose.++```bash+AR_MOE_EXPERTS_IMPL=linear_loop python -m auto_round --model ... --device_map 0,1,2,3+```++### AR_DISABLE_CROSS_DEVICE_SEARCH+- **Description**: Restricts batched search chunks to the device that hosts each weight. By default both search lanes plan their chunks centrally: every chunk starts on its home device and chunks rebalance onto under-loaded viable devices, so the search spreads across every visible device with headroom (the searches read only their module's weight plus per-module statistics, never calibration activations; each executing device is owned by a single worker thread). Non-CUDA device families keep every chunk on its home device. Set to `1` on rigs whose GPUs are shared with other jobs (a free-memory probe cannot see foreign reservations), when debugging cross-device behavior, or on hosts where the PCIe transfers outweigh the search cost. When no device fits, chunks stay on the weight's home device and rely on the per-chunk OOM fallback.+- **Default**: `0` (multi-GPU search enabled, probe-gated)+- **Valid Values**: `0` / `1`+- **Usage**: Pin search traffic to the weight-hosting devices.++```bash+AR_DISABLE_CROSS_DEVICE_SEARCH=1 python -m auto_round --model ... --iters 0+```+### AR_RESUME_DIR- **Description**: When set to a directory path, the per-block tuning loop checkpoints its progress there after each completed block, and resumes from the first not-yet-completed block on a fresh run against the same directory -- instead of restarting the whole tuning pass from block 0 after a crash or kill.- **Default**: unset (no resumability)diff --git a/docs/environments_CN.md b/docs/environments_CN.mdindex 264c88fd7..7a43b744a 100644--- a/docs/environments_CN.md+++ b/docs/environments_CN.md@@ -161,10 +161,10 @@ export AR_NEUQI_BACKEND=eager```### AR_DYNAMO_CACHE_SIZE_LIMIT-- **描述**:在开启 `torch.compile`(除 Windows 外默认开启)时,将 `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`+- **描述**:在开启 `torch.compile`(除 Windows 外默认开启)时,将 `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 编译(性能最佳),仅增加缓存条目数。多设备运行时目标值会乘以参与设备数(逐层 shape 与逐设备 guard 钉住相乘地增加特化条目);单设备运行直接使用该值。+- **默认值**:`16`(多设备运行时按参与设备数相乘)- **有效值**:正整数-- **用途**:当模型单个 block 内 linear 权重 shape 种类超过 16 时(较少见)可调大。+- **用途**:当模型单个 block 内、每个参与设备的 linear 权重 shape 种类超过 16 时(较少见)可调大。```bashexport AR_DYNAMO_CACHE_SIZE_LIMIT=32@@ -282,6 +282,56 @@ export AR_DISK_STREAM_MODEL=1AR_ALLOW_W8_ASYM=1 python -m auto_round --model ... --scheme W8A16 --asym --format auto_round```+### AR_DISABLE_BATCHED_SEARCH+- **描述**:禁用批量量化搜索机制:SignRoundV2 的封装期 init-scale 搜索(iters>0)与 iters=0 的 optimized-RTN 搜索都将完全串行(GGUF DQ scale 搜索始终逐模块内联执行)、逐模块地在权重所在设备上执行。批量化将设备/形状/配置相同的模块堆叠为一次调用,逐模块结果比特级一致;设置该变量可回退到串行循环(例如用于调试,或二分定位疑似与批量化相关的差异)。堆叠也会改变瞬态显存占用(见 `AR_SEARCH_BATCH_GB`)。+- **默认值**:`0`(启用批量化)+- **有效取值**:`0` / `1`+- **用法**:批量/并行搜索机制的总开关。++```bash+AR_DISABLE_BATCHED_SEARCH=1 python -m auto_round --model ... --device_map 0,1,2,3+```++### AR_PERF_COUNTERS+- **描述**:为每个 block 输出一行 `[perf] tune phases` INFO 日志,包含各调优阶段(wrap / prepare / loop / tail)的耗时,以及循环内部的采样器抽取、最优参数快照、梯度同步 + 优化器步进、剩余时间和串行 forward+loss+backward 时间。用于大型多设备量化运行的性能归因;开销可忽略。+- **默认值**:`0`(关闭)+- **有效取值**:`0` / `1`+- **用法**:在基准测试运行中设置,用于将 block 时间归因到封装搜索或调优循环。++```bash+AR_PERF_COUNTERS=1 python -m auto_round --model ... --device_map 0,1,2,3+```++### AR_SEARCH_BATCH_GB+- **描述**:显式覆盖批量量化搜索的堆叠批次大小,单位为每次调用堆叠 fp32 权重的 GiB 数。适用于所有批量 lane:iters=0 的 optimized-RTN 搜索、iters>0 的封装期搜索以及 NeUQI 网格锚定。未设置时批次大小按容量驱动:每个批次的大小使搜索的瞬态占用(批次的 fp32 拷贝链,NeUQI 场景另加封顶的内部临时量)不超过探测到的空闲显存的一半,且每个执行设备在调用时复查余量(过大的批次会减半而不是出错)。仅当需要把批次压到容量规划以下时才设置。+- **默认值**:未设置(容量驱动)+- **有效取值**:正浮点数(GiB)+- **用法**:在显存紧张的多设备运行中缩小批次。++```bash+AR_SEARCH_BATCH_GB=0.5 python -m auto_round --model ... --device_map 0,1+```++### AR_MOE_EXPERTS_IMPL+- **描述**:MoE 调优阶段(模型已按专家拆分)使用的前向实现。`auto`(默认)会在第一个 MoE 块之前预测 grouped-GEMM 调优路径的每卡显存占用,当 grouped 调优放不下时(qdq 堆叠保留 + 调优状态与各卡剩余显存比较)整个运行改用 `linear_loop`;决策与各卡数值都会记录到日志。显式取值不会被 `auto` 覆盖。+- **默认值**:`auto`+- **可选值**:`auto`、`linear_grouped`、`linear_grouped_sliced`、`linear_loop`+- **用法**:强制指定调优时的专家前向实现,或保持 `auto` 由显存模型自动选择。++```bash+AR_MOE_EXPERTS_IMPL=linear_loop python -m auto_round --model ... --device_map 0,1,2,3+```++### AR_DISABLE_CROSS_DEVICE_SEARCH+- **描述**:将批量搜索批次限制在权重所在设备上。默认情况下,两条搜索 lane 会集中规划批次:每个批次先落在权重所在设备,再从过载设备向空闲的可用设备再平衡,使搜索尽量铺满所有有余量的可见设备(此类搜索只读取自身模块的权重与逐模块统计量,从不读取校准激活;每个执行设备由单个工作线程独占)。非 CUDA 设备族的批次始终留在权重所在设备。以下情况设为 `1`:机架 GPU 与其他任务共享(空闲显存探针无法看到其他任务的占用)、调试跨设备行为、或 PCIe 传输开销超过搜索收益的主机。当没有设备放得下时,批次留在权重所在设备并依赖逐批次的 OOM 回退。+- **默认值**:`0`(启用多 GPU 搜索,探针门控)+- **有效取值**:`0` / `1`+- **用法**:将搜索流量固定在权重所在设备。++```bash+AR_DISABLE_CROSS_DEVICE_SEARCH=1 python -m auto_round --model ... --iters 0+```+### AR_RESUME_DIR- **描述**:设置为目录路径后,逐块调优循环会在每完成一个块后将进度写入该目录,并在针对同一目录的新一次运行中从第一个未完成的块继续——而不是在崩溃或被杀死后从第 0 块重新开始整个调优过程。- **默认值**:未设置(不支持断点续跑)diff --git a/docs/step_by_step.md b/docs/step_by_step.mdindex db708ac17..60bf7421a 100755--- a/docs/step_by_step.md+++ b/docs/step_by_step.md@@ -577,6 +577,8 @@ ar.quantize_and_save()`low_gpu_mem_usage(bool=True)` whether to reduce gpu memory usage at the cost of more time cost+`calibration_data_device (str)` placement of the block calibration data in multi-GPU runs: `auto` (default) | `cpu` | `off` | `1,2` | `cuda:1,cuda:2`. CLI: `--calibration_data_device`.+In some serving frameworks, certain layers (e.g., QKV or MoE) are fused to accelerate inference. These fused layers may require the same data type and bit configuration. The shared_layers option simplifies this setup by supporting both regex and full-name matching. **Note that regex matching is applied in a block-wise manner.****MoE expert layers are automatically grouped per block** — all expert projections (gate/up/down across all experts) within the same transformer block are treated as a single entity during DP optimization. This means they share the same quantization scheme and their losses/numel are summed together. No manual `shared_layers` configuration is needed for expert layers.diff --git a/docs/step_by_step_CN.md b/docs/step_by_step_CN.mdindex bd13f0a6b..5514fa88d 100755--- a/docs/step_by_step_CN.md+++ b/docs/step_by_step_CN.md@@ -558,6 +558,8 @@ ar.quantize_and_save()`low_gpu_mem_usage(bool=True)`:开启后可减少 GPU 显存占用,但会增加训练时间。默认开启。+`calibration_data_device (str)` 多 GPU 运行时块校准数据的存放位置:`auto`(默认)| `cpu` | `off` | `1,2` | `cuda:1,cuda:2`。命令行参数:`--calibration_data_device`。+为加速推理,在部分框架中,会对特定层(如QKV、MoE)进行融合。这些融合层必须是相同的数据类型和量化配置。`shared_layers` 参数可以简化该配置,**同时支持正则表达式匹配和完整层名匹配**。注意**正则匹配按块匹配规则生效**。**MoE 的 expert 层会自动按块分组** — 同一个 transformer block 内所有 expert 的投影层(gate/up/down,跨所有 experts)会被视为一个整体进行 DP 优化。它们共享相同的量化方案,loss 和 numel 直接求和。无需手动配置 `shared_layers` 来处理 expert 层。diff --git a/test/unit/common/utils/test_device.py b/test/unit/common/utils/test_device.pyindex dc2962a81..ae68792c9 100644--- a/test/unit/common/utils/test_device.py+++ b/test/unit/common/utils/test_device.py@@ -149,6 +149,60 @@ class TestBumpDynamoCacheLimit:sys.modules["torch._dynamo"] = original_dynamo+class TestEngagedCacheLimit:+ """Test the engaged-device scaling of the dynamo cache limit."""++ def test_limit_scales_with_engaged_devices(self, monkeypatch):+ """Multi-device runs scale the cache limit; single-device keeps the plain default."""+ dm = sys.modules["auto_round.utils.device_manager"]++ monkeypatch.setenv("AR_DYNAMO_CACHE_SIZE_LIMIT", "16")+ saved = dm.device_manager._device_list+ try:+ dm.device_manager._device_list = ["cuda:0", "cuda:1"]+ assert dm._engaged_cache_limit() == 32+ dm.device_manager._device_list = [f"cuda:{i}" for i in range(8)]+ assert dm._engaged_cache_limit() == 128+ dm.device_manager._device_list = ["cpu"]+ assert dm._engaged_cache_limit() == 16+ dm.device_manager._device_list = []+ assert dm._engaged_cache_limit() == 16+ finally:+ dm.device_manager._device_list = saved++ def test_compile_func_bumps_by_engaged_count(self, monkeypatch):+ """ARDevice.compile_func bumps the dynamo limit through the scaled target."""+ import torch as _torch++ dm = sys.modules["auto_round.utils.device_manager"]++ calls = []+ saved_list = dm.device_manager._device_list+ try:+ monkeypatch.setenv("AR_DYNAMO_CACHE_SIZE_LIMIT", "10")+ dm.device_manager._device_list = ["cuda:0", "cuda:1", "cuda:2"]++ class _FakeDev:+ type = "cuda"++ @staticmethod+ def is_torch_compile_supported():+ return True++ fake = _FakeDev()+ fake.compile_func = dm.ARDevice.compile_func.__get__(fake)+ with (+ patch("auto_round.utils.device._bump_dynamo_cache_limit") as bump,+ patch.object(_torch, "compile", return_value=lambda *a, **k: None),+ ):+ fake.compile_func(lambda x: x)+ calls.append(bump.call_args)+ assert bump.call_args is not None+ assert bump.call_args.args[0] == 30+ finally:+ dm.device_manager._device_list = saved_list++class TestNumbaAndTbb:"""Test Numba and TBB availability functions."""@@ -769,9 +823,9 @@ class TestEstimateTuningBlockMem:input_ids = [torch.randn(1, 5)]result = estimate_tuning_block_mem(block, input_ids, 1)- assert (- len(result) == 4- ) # layer_memory_dict, layer_activation_memory, block_input_output_memory, additional_memory+ assert len(result) == 6+ # layer_memory_dict, layer_activation_memory, block_input_output_memory,+ # additional_memory, per_device_activation, per_device_expertsclass TestIsGaudi2:diff --git a/test/unit/test_cpu/modeling/test_grouped_experts_plans.py b/test/unit/test_cpu/modeling/test_grouped_experts_plans.pynew file mode 100644index 000000000..7fc933267--- /dev/null+++ b/test/unit/test_cpu/modeling/test_grouped_experts_plans.py@@ -0,0 +1,278 @@+# Copyright 2025 Intel Corporation+# SPDX-License-Identifier: Apache-2.0+"""Tests for the per-device grouped experts plans and the align-hook exemption."""++import unittest++import torch+from torch import nn++from auto_round.modeling.fused_moe.grouped_experts import (+ _hooks_are_alignment_only,+ _projection_is_supported,+ _run_routes,+)+++class TestHookWhitelistResolution(unittest.TestCase):+ """Missing accelerate hook classes are probed once per process, not per call."""++ def test_missing_classes_log_once(self):+ import sys+ import types+ from unittest import mock++ from auto_round.modeling.fused_moe import grouped_experts++ orig = sys.modules.get("accelerate.hooks")+ stub = types.ModuleType("accelerate.hooks") # carries neither hook class+ sys.modules["accelerate.hooks"] = stub+ try:+ grouped_experts._ACCELERATE_HOOK_WHITELIST = None+ with mock.patch.object(grouped_experts, "logger") as spy:+ self.assertEqual(grouped_experts._accelerate_hook_whitelist(), ())+ notices = spy.warning.call_count + spy.debug.call_count+ self.assertEqual(notices, 2)+ # the cached resolution must not repeat the notices+ self.assertEqual(grouped_experts._accelerate_hook_whitelist(), ())+ self.assertEqual(spy.warning.call_count + spy.debug.call_count, notices)+ lin = _linear()+ lin.register_forward_hook(lambda *a: None) # any hook reaches the whitelist gate+ self.assertFalse(_hooks_are_alignment_only(lin))+ finally:+ if orig is not None:+ sys.modules["accelerate.hooks"] = orig+ grouped_experts._ACCELERATE_HOOK_WHITELIST = None+++def _linear(out=4, inp=4):+ lin = nn.Linear(inp, out, bias=False)+ with torch.no_grad():+ lin.weight.copy_(torch.randn_like(lin.weight))+ return lin+++def _expert(gate=True, seed=0):+ torch.manual_seed(seed)+ mod = nn.Module()+ mod.up_proj = _linear()+ mod.down_proj = _linear()+ if gate:+ mod.gate_proj = _linear()+ return mod+++class _Experts(nn.Module):+ def __init__(self, n=2):+ super().__init__()+ self.n = n+ for i in range(n):+ setattr(self, str(i), _expert(seed=i))+ self.act_fn = nn.functional.silu++ def forward(self, x, idx, w):+ return _run_routes(self, x, idx, w, self.n)+++class TestHookExemption(unittest.TestCase):+ def test_no_hooks_is_alignment_only(self):+ self.assertTrue(_hooks_are_alignment_only(_linear()))++ def test_plain_hook_is_not_exempt(self):+ lin = _linear()+ lin.register_forward_hook(lambda m, i, o: o)+ self.assertFalse(_hooks_are_alignment_only(lin))+ self.assertFalse(_projection_is_supported(lin)) # calibration hooks must fire++ def test_align_hook_without_offload_is_exempt(self):+ from accelerate.hooks import AlignDevicesHook++ lin = _linear()+ lin.register_forward_pre_hook(AlignDevicesHook(execution_device=lin.weight.device))+ self.assertTrue(_hooks_are_alignment_only(lin))+ self.assertTrue(_projection_is_supported(lin))++ def test_align_hook_with_offload_is_not_exempt(self):+ from accelerate.hooks import AlignDevicesHook++ lin = _linear()+ hook = AlignDevicesHook(execution_device=lin.weight.device, offload=True)+ lin.register_forward_pre_hook(hook)+ self.assertFalse(_hooks_are_alignment_only(lin))+ self.assertFalse(_projection_is_supported(lin))+++class TestRunRoutesSingleGroupCPU(unittest.TestCase):+ def test_matches_reference(self):+ torch.manual_seed(7)+ experts = _Experts(4)+ n_tokens, n_experts, top_k, hidden = 12, 4, 2, 4+ x = torch.randn(n_tokens, hidden)+ idx = torch.randint(0, n_experts, (n_tokens, top_k))+ w = torch.rand(n_tokens, top_k)++ out = experts(x, idx, w)++ ref = torch.zeros_like(x)+ for t in range(n_tokens):+ for k in range(top_k):+ e = getattr(experts, str(int(idx[t, k])))+ h = nn.functional.silu(e.gate_proj(x[t])) * e.up_proj(x[t])+ ref[t] += w[t, k] * e.down_proj(h)+ torch.testing.assert_close(out, ref, rtol=1e-5, atol=1e-5)++ def _wrapped_linear(self, bits, seed):+ from auto_round.wrapper import WrapperLinear++ layer = _linear()+ torch.manual_seed(seed)+ with torch.no_grad():+ layer.weight.copy_(torch.randn_like(layer.weight))+ layer.bits = bits+ layer.group_size = -1+ layer.sym = True+ layer.data_type = "int"+ layer.iters = 0+ layer.act_bits = 16+ layer.scale_dtype = torch.float16+ return WrapperLinear(+ layer,+ device="cpu",+ enable_minmax_tuning=False,+ enable_norm_bias_tuning=False,+ enable_round_tuning=False,+ enable_torch_compile=False,+ disable_opt_rtn=False,+ iters=0,+ )++ def test_mixed_bits_across_experts_falls_back(self):+ # different quant signatures inside one device group must reject the+ # grouped path (sharing one grouped GEMM across differently-quantized+ # experts is unsound), not silently merge them. Plain Linears carry no+ # quant signature at all (None == None), so the mix needs wrappers.+ experts = _Experts(2)+ getattr(experts, "0").up_proj = self._wrapped_linear(bits=4, seed=1)+ getattr(experts, "1").up_proj = self._wrapped_linear(bits=8, seed=2)+ x = torch.randn(6, 4)+ idx = torch.tensor([[0, 1]] * 6) # both experts active+ w = torch.rand(6, 2)+ self.assertIsNone(_run_routes(experts, x, idx, w, experts.n))++ def test_plain_before_wrapper_falls_back(self):+ # a plain Linear's quantization signature is None -- a VALID value that+ # must not double as the unset marker. Seeding the reference from the+ # first position rejects the mix regardless of expert ordering; the+ # old sentinel latched the wrapper's signature without comparison when+ # the plain expert came first and accepted the mixed group.+ x = torch.randn(6, 4)+ idx = torch.tensor([[0, 1]] * 6)+ w = torch.rand(6, 2)+ experts = _Experts(2)+ getattr(experts, "1").up_proj = self._wrapped_linear(bits=4, seed=3) # plain first+ self.assertIsNone(_run_routes(experts, x, idx, w, experts.n))+ experts = _Experts(2)+ getattr(experts, "0").up_proj = self._wrapped_linear(bits=4, seed=4) # wrapper first+ self.assertIsNone(_run_routes(experts, x, idx, w, experts.n))++ def test_weightless_packed_linear_falls_back(self):+ # packed QuantLinear types (e.g. MXFP4QuantLinear) store packed weights+ # and expose no .weight; the support probe must reject them BEFORE any+ # device read instead of raising AttributeError (CI: qwen3-vl-moe-mxfp)+ experts = _Experts(2)+ getattr(experts, "0").up_proj = nn.Module() # no .weight, not a wrapper+ x = torch.randn(6, 4)+ idx = torch.tensor([[0, 1]] * 6)+ w = torch.rand(6, 2)+ self.assertIsNone(_run_routes(experts, x, idx, w, experts.n))++ def test_missing_slot_falls_back(self):+ torch.manual_seed(3)+ experts = _Experts(2)+ object.__setattr__(getattr(experts, "1"), "up_proj", None) # slot absent on expert 1+ x = torch.randn(6, 4)+ idx = torch.tensor([[0, 1]] * 6)+ w = torch.rand(6, 2)+ self.assertIsNone(_run_routes(experts, x, idx, w, experts.n))+++ not (torch.cuda.is_available() and torch.cuda.device_count() >= 3),+ "needs >=3 CUDA devices (inputs live on a third device)",+)+class TestRunRoutesMultiDeviceCUDA(unittest.TestCase):+ def test_two_device_groups_match_reference(self):+ torch.manual_seed(11)+ experts = _Experts(4) # tiny CPU build; nn.Module.to() cannot copy out of meta+ # experts 0,1 on cuda:0; 2,3 on cuda:1 (weights move explicitly)+ for i in range(4):+ e = getattr(experts, str(i))+ dev = f"cuda:{i // 2}"+ for slot in ("up_proj", "down_proj", "gate_proj"):+ getattr(e, slot).to(dev)+ n_tokens, n_experts, top_k, hidden = 64, 4, 2, 4+ x = torch.randn(n_tokens, hidden, device="cuda:2") # input on a third device+ idx = torch.randint(0, n_experts, (n_tokens, top_k), device="cuda:2")+ w = torch.rand(n_tokens, top_k, device="cuda:2")++ out = experts(x, idx, w)+ self.assertEqual(out.device, x.device)++ # reference on cuda:2 by explicit per-expert moves+ ref = torch.zeros_like(x)+ for t in range(n_tokens):+ for k in range(top_k):+ e = getattr(experts, str(int(idx[t, k])))+ dev = next(p.device for p in e.up_proj.parameters())+ xt = x[t].to(dev)+ h = nn.functional.silu(e.gate_proj(xt)) * e.up_proj(xt)+ ref[t] += (w[t, k] * e.down_proj(h).to(x.device)).to(x.device)+ torch.testing.assert_close(out, ref, rtol=1e-4, atol=1e-4)+++class TestAtomicPlacement(unittest.TestCase):+ """The allocator must never split one expert's projections across devices."""++ def _layer_dict(self, n_experts=6):+ d = {}+ for i in range(n_experts):+ for slot in ("gate_proj", "up_proj", "down_proj"):+ d[f"mlp.experts.{i}.{slot}"] = {"param_memory": 1.0, "is_moe_expert": True}+ d["self_attn.q_proj"] = {"param_memory": 1.0, "is_moe_expert": False}+ d["mlp.shared_experts.gate_proj"] = {"param_memory": 1.0, "is_moe_expert": False}+ return d++ def test_preassign_keeps_experts_atomic_and_spreads(self):+ from auto_round.utils.device import _preassign_moe_experts++ layer_dict = self._layer_dict(8)+ budgets = {"cuda:0": 12.0, "cuda:1": 12.0}+ assigned = _preassign_moe_experts(layer_dict, budgets, ["cuda:0", "cuda:1"], mem_per_param=1.0)+ self.assertTrue(assigned)+ # every expert's three slots share one device+ for i in range(8):+ devs = {assigned[f"mlp.experts.{i}.{s}"] for s in ("gate_proj", "up_proj", "down_proj")}+ self.assertEqual(len(devs), 1, f"expert {i} split: {devs}")+ # spread across both devices+ self.assertEqual({d for d in assigned.values()}, {"cuda:0", "cuda:1"})++ def test_preassign_shrinks_chunk_on_overflow(self):+ from auto_round.utils.device import _preassign_moe_experts++ # budgets so tight that a 16-expert chunk cannot fit, but single experts can+ layer_dict = self._layer_dict(6)+ budgets = {"cuda:0": 3.5, "cuda:1": 3.5}+ assigned = _preassign_moe_experts(layer_dict, budgets, ["cuda:0", "cuda:1"], mem_per_param=1.0)+ for i in range(6):+ devs = {assigned.get(f"mlp.experts.{i}.{s}") for s in ("gate_proj", "up_proj", "down_proj")}+ self.assertEqual(len(devs), 1, f"expert {i} split or unplaced: {devs}")++ def test_balancer_groups_experts_atomically(self):+ from auto_round.utils.device import _allocate_layers_to_devices++ layer_dict = self._layer_dict(4)+ budgets = {"cuda:0": 100.0, "cuda:1": 100.0}+ device_map, _names = _allocate_layers_to_devices(layer_dict, budgets, ["cuda:0", "cuda:1"], 1.0)+ for i in range(4):+ devs = {device_map[f"mlp.experts.{i}.{s}"] for s in ("gate_proj", "up_proj", "down_proj")}+ self.assertEqual(len(devs), 1, f"expert {i} split by balancer: {devs}")diff --git a/test/unit/test_cpu/quantization/test_attach_pool_placement.py b/test/unit/test_cpu/quantization/test_attach_pool_placement.pynew file mode 100644index 000000000..5cdd3507f--- /dev/null+++ b/test/unit/test_cpu/quantization/test_attach_pool_placement.py@@ -0,0 +1,155 @@+# SPDX-License-Identifier: Apache-2.0+"""Tests for CompressionOrchestrator._attach_pool_placement (calibration-data pools).++Covers the documented no-op contract (policy off, CPU-parked lane) and the+fits-home consolidation call with its reserved-bytes bookkeeping.+"""++import unittest+from types import SimpleNamespace+from unittest import mock++import torch+++def _fake_orchestrator(cache_device, mode, batch_size=2, iters=0, runner_device="cuda:0"):+ from auto_round.compressors.orchestrator import CompressionOrchestrator++ runner = SimpleNamespace(device=runner_device, pool_placement="unset")+ composer = SimpleNamespace(+ block_forward=runner,+ block_quantizer=SimpleNamespace(iters=iters),+ need_quanted_input=lambda: False,+ )+ self = SimpleNamespace(+ alg_composer=composer,+ compress_context=SimpleNamespace(cache_device=cache_device, calibration_data_device=mode),+ calibration_context=SimpleNamespace(batch_size=batch_size),+ )+ return CompressionOrchestrator, self, runner+++class _FakePlacement:+ def __init__(self, devices, counts=None):+ self.devices = devices+ self._counts = counts or {str(d): 2 for d in devices}++ def counts(self):+ return dict(self._counts)+++class TestAttachPoolPlacement(unittest.TestCase):+ def _pools(self):+ return [[torch.randn(2, 3, 8) for _ in range(2)]] # one pool of 2 chunks++ def test_cpu_parked_lane_never_consolidates(self):+ # low_gpu_mem_usage: cache_device is the host; consolidation must not+ # migrate host-parked pools onto the compute GPU (docstring contract)+ cls, self_, runner = _fake_orchestrator(cache_device="cpu", mode="auto")+ with mock.patch("auto_round.utils.pool_placement.consolidate_pool_onto") as cons:+ cls._attach_pool_placement(self_, object(), self._pools()[0])+ cons.assert_not_called()+ self.assertIsNone(runner.pool_placement)++ def test_policy_off_skips_consolidation(self):+ cls, self_, runner = _fake_orchestrator(cache_device="cuda:0", mode="off")+ with mock.patch("auto_round.utils.pool_placement.consolidate_pool_onto") as cons:+ cls._attach_pool_placement(self_, object(), self._pools()[0])+ cons.assert_not_called()+ self.assertIsNone(runner.pool_placement)++ def test_mode_flows_into_the_real_resolver(self):+ """Regression (review R4-2): mode was read but never passed, so off/cpu/csv+ only worked when the resolver was mocked. Exercise the REAL resolver with+ only the free-memory probe faked."""+ cls, self_, runner = _fake_orchestrator(cache_device="cuda:0", mode="off")+ probe = {"cuda:0": 80 << 30, "cuda:1": 80 << 30}+ with mock.patch("auto_round.utils.device.probe_usable_bytes", side_effect=lambda d: probe.get(d)):+ cls._attach_pool_placement(self_, object(), self._pools()[0])+ # a healthy CUDA fleet must NOT resurrect the disabled policy+ self.assertIsNone(runner.pool_placement)++ cls, self_, runner = _fake_orchestrator(cache_device="cuda:0", mode="cpu")+ with mock.patch("auto_round.utils.device.probe_usable_bytes", side_effect=lambda d: probe.get(d)):+ cls._attach_pool_placement(self_, object(), self._pools()[0])+ self.assertEqual(runner.pool_placement.devices, ["cpu"]) # real resolver, host parking++ cls, self_, runner = _fake_orchestrator(cache_device="cuda:0", mode="cuda:1")+ with mock.patch("auto_round.utils.device.probe_usable_bytes", side_effect=lambda d: probe.get(d)), mock.patch(+ "auto_round.utils.pool_placement.consolidate_pool_onto"+ ): # no CUDA here; consolidation is not under test+ cls._attach_pool_placement(self_, object(), self._pools()[0])+ # forced csv: the plan draws from the forced devices only+ self.assertTrue(set(runner.pool_placement.devices) <= {"cuda:1"})++ def test_iters_gt0_consumer_retargets_outputs(self):+ """iters>0: the output plan consumer is the block quantizer's per-block+ loss device (falling back to the runner device); at iters=0 or+ single-device lanes the consumer stays unset."""+ # loss device set on the quantizer wins over the runner device+ cls, self_, runner = _fake_orchestrator(cache_device="cuda:0", mode="auto", iters=20, runner_device="cuda:0")+ self_.alg_composer.block_quantizer._loss_device = "cuda:1"+ with mock.patch(+ "auto_round.utils.pool_placement.resolve_placement_for_pool", return_value=None+ ) as resolve, mock.patch("auto_round.utils.pool_placement.consolidate_pool_onto"):+ cls._attach_pool_placement(self_, object(), self._pools()[0])+ self.assertEqual(resolve.call_args.kwargs.get("consumer"), "cuda:1")+ self.assertEqual(resolve.call_args.kwargs.get("mode"), "auto")++ # quantizer without a loss device: runner device fallback (== primary+ # on real multi-GPU lanes, so the retarget stays unset there)+ cls, self_, runner = _fake_orchestrator(cache_device="cuda:0", mode="auto", iters=20, runner_device="cuda:1")+ with mock.patch(+ "auto_round.utils.pool_placement.resolve_placement_for_pool", return_value=None+ ) as resolve2, mock.patch("auto_round.utils.pool_placement.consolidate_pool_onto"):+ cls._attach_pool_placement(self_, object(), self._pools()[0])+ self.assertEqual(resolve2.call_args.kwargs.get("consumer"), "cuda:1")++ # iters=0: no tune loop, outputs follow the cache primary as before+ cls, self_, runner = _fake_orchestrator(cache_device="cuda:0", mode="auto", iters=0, runner_device="cuda:1")+ self_.alg_composer.block_quantizer._loss_device = "cuda:1"+ with mock.patch(+ "auto_round.utils.pool_placement.resolve_placement_for_pool", return_value=None+ ) as resolve, mock.patch("auto_round.utils.pool_placement.consolidate_pool_onto"):+ cls._attach_pool_placement(self_, object(), self._pools()[0])+ self.assertIsNone(resolve.call_args.kwargs.get("consumer"))++ # runner on the primary itself: degenerate, consumer stays unset+ cls, self_, runner = _fake_orchestrator(cache_device="cuda:0", mode="auto", iters=20, runner_device="cuda:0")+ with mock.patch(+ "auto_round.utils.pool_placement.resolve_placement_for_pool", return_value=None+ ) as resolve, mock.patch("auto_round.utils.pool_placement.consolidate_pool_onto"):+ cls._attach_pool_placement(self_, object(), self._pools()[0])+ self.assertIsNone(resolve.call_args.kwargs.get("consumer"))++ def test_host_placement_skips_consolidation_but_keeps_placement(self):+ # mode=cpu resolves a real placement parking pools on the host+ cls, self_, runner = _fake_orchestrator(cache_device="cuda:0", mode="cpu")+ placement = _FakePlacement(("cpu",))+ with mock.patch(+ "auto_round.utils.pool_placement.resolve_placement_for_pool", return_value=placement+ ), mock.patch("auto_round.utils.pool_placement.consolidate_pool_onto") as cons:+ cls._attach_pool_placement(self_, object(), self._pools()[0])+ cons.assert_not_called()+ self.assertIs(runner.pool_placement, placement)++ def test_single_device_plan_consolidates_with_full_reserve(self):+ cls, self_, runner = _fake_orchestrator(cache_device="cuda:0", mode="auto")+ placement = _FakePlacement(("cuda:0",))+ pools = self._pools()[0]+ with mock.patch(+ "auto_round.utils.pool_placement.resolve_placement_for_pool", return_value=placement+ ) as resolve, mock.patch("auto_round.utils.pool_placement.consolidate_pool_onto") as cons:+ cls._attach_pool_placement(self_, object(), pools)+ cons.assert_called_once()+ _, target, _block, _bs = cons.call_args.args[:4]+ reserved = cons.call_args.kwargs["reserved_bytes"]+ self.assertEqual(target, "cuda:0")+ # chains=1 (need_quanted_input False): reserve equals the pool bytes+ self.assertEqual(reserved, sum(t.numel() * t.element_size() for t in pools))+ self.assertIs(runner.pool_placement, placement)+ resolve.assert_called_once()+++if __name__ == "__main__":+ unittest.main()diff --git a/test/unit/test_cpu/quantization/test_auto_linear_loop.py b/test/unit/test_cpu/quantization/test_auto_linear_loop.pynew file mode 100644index 000000000..df19425e8--- /dev/null+++ b/test/unit/test_cpu/quantization/test_auto_linear_loop.py@@ -0,0 +1,128 @@+"""Tests for the one-shot auto linear_loop pick (AR_MOE_EXPERTS_IMPL=auto).++Grouped tuning stacks per-expert fp32 tensors on every expert-homing device;+when any such device cannot hold state + stacks + routed transients beside the+reserve, the first MoE tune block must switch the run to linear_loop BEFORE+the loop starts (instead of OOMing inside grouped_mm and re-staging the sliced+fallback). Explicit AR_MOE_EXPERTS_IMPL choices are never overridden.+"""++import unittest+from unittest import mock++GB = 2**30+++def _envs_auto():+ from auto_round import envs++ return mock.patch.object(envs, "AR_MOE_EXPERTS_IMPL", "auto")+++class _Cfg:+ def __init__(self):+ self._experts_implementation = "linear_grouped"+++class TestAutoLinearLoop(unittest.TestCase):+ def setUp(self):+ import auto_round.algorithms.quantization.tune_memory as q++ self.q = q+ q._MOE_IMPL_AUTO_LINEAR_LOOP_DONE = False+ self.cfg = _Cfg()+ self.state = {"cuda:1": 14 * GB, "cuda:2": 14 * GB} # 14 B/param layout+ self.act = {"cuda:1": 12 * GB, "cuda:2": 2 * GB} # stacks dominate cuda:1++ def _run(self, iters=20, stacks=True):+ q = self.q+ with (+ _envs_auto(),+ mock.patch.object(q, "_logical_state_by_device", return_value=self.state),+ mock.patch.object(q, "_activation_bytes_by_device", return_value=self.act),+ mock.patch.object(q, "_grouped_stack_bytes", side_effect=lambda b, d, config=None: 1 if stacks else 0),+ mock.patch("auto_round.utils.device.probe_usable_bytes", return_value=16 * GB),+ ):+ q._maybe_auto_linear_loop_for_tuning(object(), [object()], 8, iters, self.cfg, None)++ def test_over_lane_switches_before_the_loop(self):+ # demand on cuda:1 = 14*6/14 (grads+bf16; snapshot parks) + 12 + 0.25+ # = 20.25 GiB > free 16 (guaranteed in-loop terms only)+ self._run()+ self.assertEqual(self.cfg._experts_implementation, "linear_loop")+ self.assertTrue(self.q._MOE_IMPL_AUTO_LINEAR_LOOP_DONE)++ def test_fits_lane_keeps_grouped(self):+ self.act = {"cuda:1": 1 * GB, "cuda:2": 1 * GB}+ self._run()+ self.assertEqual(self.cfg._experts_implementation, "linear_grouped")++ def test_explicit_impl_never_overridden(self):+ from auto_round import envs++ with mock.patch.object(envs, "AR_MOE_EXPERTS_IMPL", "linear_grouped"):+ self.q._maybe_auto_linear_loop_for_tuning(object(), [], 8, 20, self.cfg, None)+ self.assertEqual(self.cfg._experts_implementation, "linear_grouped")++ def test_iters0_untouched(self):+ self._run(iters=0)+ self.assertEqual(self.cfg._experts_implementation, "linear_grouped")++ def test_model_context_config_without_impl_attr_still_decides(self):+ # server regression: model_context.config never received+ # _experts_implementation (prepare writes it on model.config); the+ # old single-candidate read silently returned and the 4x3090 lane+ # never switched. The check must fall through to model.config, and+ # a switch must update BOTH config objects.+ ctx_cfg = type("CtxCfg", (), {})() # no _experts_implementation attr+ model = type("M", (), {})()+ model.config = self.cfg+ q = self.q+ with (+ _envs_auto(),+ mock.patch.object(q, "_logical_state_by_device", return_value=self.state),+ mock.patch.object(q, "_activation_bytes_by_device", return_value=self.act),+ mock.patch.object(q, "_grouped_stack_bytes", side_effect=lambda b, d, config=None: 1),+ mock.patch("auto_round.utils.device.probe_usable_bytes", return_value=16 * GB),+ ):+ q._maybe_auto_linear_loop_for_tuning(object(), [object()], 8, 20, ctx_cfg, model)+ self.assertEqual(self.cfg._experts_implementation, "linear_loop")+ self.assertEqual(ctx_cfg._experts_implementation, "linear_loop")++ def test_snapshot_parks_to_host_so_not_charged_as_guaranteed(self):+ # boundary between the old 10/14 and new 6/14 multipliers: this lane+ # must KEEP grouped (a working knife-edge lane must not be switched)+ q = self.q+ state = {"cuda:1": 20 * GB} # remaining: 10/14 -> 14.3 (old switch), 6/14 -> 8.6+ act = {"cuda:1": 5 * GB}+ with (+ _envs_auto(),+ mock.patch.object(q, "_logical_state_by_device", return_value=state),+ mock.patch.object(q, "_activation_bytes_by_device", return_value=act),+ mock.patch.object(q, "_grouped_stack_bytes", side_effect=lambda b, d, config=None: 1),+ mock.patch("auto_round.utils.device.probe_usable_bytes", return_value=16 * GB),+ ):+ q._maybe_auto_linear_loop_for_tuning(object(), [object()], 8, 20, self.cfg, None)+ self.assertEqual(self.cfg._experts_implementation, "linear_grouped")++ def test_second_run_same_process_re_decides(self):+ # the done-flag is keyed by the run's config: a second model+ # quantized in the same process must get its own auto decision+ q = self.q+ q._MOE_IMPL_AUTO_LINEAR_LOOP_DONE = True # a previous run finished+ cfg2 = _Cfg()+ with (+ _envs_auto(),+ mock.patch.object(q, "_logical_state_by_device", return_value=self.state),+ mock.patch.object(q, "_activation_bytes_by_device", return_value=self.act),+ mock.patch.object(q, "_grouped_stack_bytes", side_effect=lambda b, d, config=None: 1),+ mock.patch("auto_round.utils.device.probe_usable_bytes", return_value=16 * GB),+ ):+ q._maybe_auto_linear_loop_for_tuning(object(), [object()], 8, 20, cfg2, None)+ self.assertEqual(cfg2._experts_implementation, "linear_loop") # decided, not skipped++ def test_dense_block_no_stacks_no_decision(self):+ # no grouped stacks homed: not the decision point, flag stays unset+ self._run(stacks=False)+ self.assertEqual(self.cfg._experts_implementation, "linear_grouped")+ self.assertFalse(self.q._MOE_IMPL_AUTO_LINEAR_LOOP_DONE)diff --git a/test/unit/test_cpu/quantization/test_batched_wrap_search.py b/test/unit/test_cpu/quantization/test_batched_wrap_search.pynew file mode 100644index 000000000..e94d7db59--- /dev/null+++ b/test/unit/test_cpu/quantization/test_batched_wrap_search.py@@ -0,0 +1,1451 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the+# License for the specific language governing permissions and limitations+# under the License.+"""Batched same-shape wrap-search tests: grouping, bit-parity, deferral protocol."""++import os+import threading+import types+import unittest+from unittest import mock++import torch++import auto_round.algorithms.quantization.search_dispatch as search_dispatch+from auto_round.algorithms.quantization.search_dispatch import run_batched_wrap_search+++def _mk_inputs(seed=0, shape=(6, 128), dtype="int", bits=4, thresh=1e-5, device="cpu"):+ from auto_round.data_type.utils import resolve_optimized_init_scale_fn++ g = torch.Generator().manual_seed(seed)+ w = torch.randn(*shape, generator=g)+ im = torch.rand(shape[1], generator=g) + 0.5 # RAW per-column imatrix, as production stages it+ fn = resolve_optimized_init_scale_fn(dtype, thresh)+ return w, im, dtype, bits, thresh, device, fn+++class FakeDeferred:+ """Duck-typed deferred wrapper: stages inputs, finalizes with the result."""++ supports_batched_search = True++ def __init__(self, seed=0, shape=(6, 128), dtype="int", bits=4, device="cpu", thresh=1e-5, search_fn=None):+ w, im, dt, b, th, dev, fn = _mk_inputs(seed, shape, dtype, bits, thresh, device)+ if search_fn is not None:+ fn = search_fn+ self._deferred_search_inputs = (w, dt, b, im, th, fn)+ self.init_scale = None+ self.finalized_on_thread = None+ self.name = f"m{seed}"+ self.orig_layer = types.SimpleNamespace(group_size=128)++ def _run_deferred_search_now(self):+ from auto_round.data_type.utils import reshape_imatrix_for_weight++ w, _dt, b, im_raw, _th, fn = self._deferred_search_inputs+ self.init_scale = fn(w, b, reshape_imatrix_for_weight(im_raw, w, self.orig_layer.group_size))+ self._deferred_search_inputs = None++ def finalize_batched_search(self, init_scale):+ self.init_scale = init_scale+ self._deferred_search_inputs = None+ self.finalized_on_thread = threading.current_thread().name+++class TestNonStackableAndDictResults(unittest.TestCase):+ def test_split_leading_dicts(self):+ # GGUF K-quant funcs return scale/zp as dicts whose tensor values+ # carry the flattened batch dim; sharing the whole dict per module+ # gives every layer N-times the metadata (CI: gguf q2_k export)+ from auto_round.algorithms.quantization.rtn.batched_search import _split_leading++ scale = {"scale": torch.arange(8.0).reshape(8, 1), "d_scale": torch.arange(4.0).reshape(4, 1), "meta": None}+ parts = _split_leading(scale, 2)+ self.assertEqual(len(parts), 2)+ for i, part in enumerate(parts):+ self.assertEqual(part["scale"].shape, (4, 1))+ self.assertTrue(torch.equal(part["scale"], scale["scale"].reshape(2, 4, 1)[i]))+ self.assertEqual(part["d_scale"].shape, (2, 1))+ self.assertIsNone(part["meta"]) # non-tensor values are shared++ def test_search_fn_stackable_predicate(self):+ import functools++ from auto_round.algorithms.quantization.search_dispatch import _search_fn_stackable+ from auto_round.data_type.int import search_scales+ from auto_round.data_type.nvfp import search_nvfp4_scale++ self.assertFalse(_search_fn_stackable(search_nvfp4_scale))+ self.assertFalse(_search_fn_stackable(functools.partial(search_nvfp4_scale)))++ def shim(w, bits, im):+ return None++ shim._torchdynamo_orig_callable = search_nvfp4_scale+ self.assertFalse(_search_fn_stackable(shim)) # compiled wrappers unwrap+ self.assertTrue(_search_fn_stackable(search_scales))+ self.assertTrue(_search_fn_stackable(functools.partial(search_scales)))++ def test_nv_search_group_runs_per_module(self):+ # the nv-fp4 search is not batch-aware; its groups must never receive+ # a stacked weight (CI: test_nvfp4_alg_ext IndexError)+ import functools++ from auto_round.data_type.nvfp import search_nvfp4_scale++ calls = []++ def per_module(w, bits, im):+ calls.append(tuple(w.shape))+ return torch.ones(w.shape[0], 1)++ fn = functools.wraps(search_nvfp4_scale)(per_module)+ wrappers = [FakeDeferred(seed=1, search_fn=fn), FakeDeferred(seed=2, search_fn=fn)]+ self.assertTrue(run_batched_wrap_search(wrappers))+ self.assertEqual(calls, [(6, 128), (6, 128)]) # two single-module calls, never [2, 6, 128]+ for wr in wrappers:+ self.assertIsNotNone(wr.init_scale)+++class TestBatchedBitParity(unittest.TestCase):+ def test_stacked_search_matches_individual_exactly(self):+ fakes = [FakeDeferred(seed=i) for i in range(5)]+ individual = [_individual(f) for f in fakes]+ stacked_w = torch.stack([f._deferred_search_inputs[0] for f in fakes])+ stacked_im = _stacked_im(fakes, stacked_w)+ batched = fakes[0]._deferred_search_inputs[5](stacked_w, 4, stacked_im)+ for i, ref in enumerate(individual):+ self.assertTrue(torch.equal(batched[i], ref), f"module {i} diverged")++ def test_parity_across_shapes_and_bits(self):+ for shape, bits in [((8, 128), 4), ((13, 128), 3), ((4, 64), 2)]:+ fakes = [FakeDeferred(seed=i + bits * 10, shape=shape, bits=bits) for i in range(4)]+ refs = [+ f._deferred_search_inputs[5](f._deferred_search_inputs[0], bits, f._deferred_search_inputs[3])+ for f in fakes+ ]+ _sw = torch.stack([f._deferred_search_inputs[0] for f in fakes])+ batched = fakes[0]._deferred_search_inputs[5](_sw, bits, _stacked_im(fakes, _sw))+ for i, ref in enumerate(refs):+ self.assertTrue(torch.equal(batched[i], ref))+++class TestRunBatchedWrapSearch(unittest.TestCase):+ def test_batches_same_shape_and_finalizes(self):+ fakes = [FakeDeferred(seed=i) for i in range(4)] + [FakeDeferred(seed=99, shape=(3, 128))]+ expected = [_individual(f) for f in fakes]+ handled = run_batched_wrap_search(fakes)+ self.assertTrue(handled)+ for f, ref in zip(fakes, expected):+ self.assertIsNone(f._deferred_search_inputs)+ self.assertIsNotNone(f.init_scale)+ self.assertTrue(torch.equal(f.init_scale, ref), f.name)++ def test_single_deferred_runs_individually(self):+ fakes = [FakeDeferred(seed=0)]+ handled = run_batched_wrap_search(fakes)+ self.assertTrue(handled) # still handled (individual fallback), inputs consumed+ self.assertIsNotNone(fakes[0].init_scale)++ def test_shape_mismatch_groups_separately(self):+ a = [FakeDeferred(seed=i, shape=(6, 128)) for i in range(2)]+ b = [FakeDeferred(seed=i, shape=(5, 128)) for i in range(2)]+ run_batched_wrap_search(a + b)+ for f in a + b:+ self.assertIsNotNone(f.init_scale)++ def test_dtype_mismatch_groups_separately(self):+ a = FakeDeferred(seed=0)+ b = FakeDeferred(seed=1, dtype="mx_fp4")+ run_batched_wrap_search([a, b]) # different resolved fn -> separate groups, no raise+ self.assertIsNotNone(a.init_scale)+ self.assertIsNotNone(b.init_scale)++ def test_distinct_search_fns_never_share_a_batch(self):+ def fake_fn_a(w, bits, im):+ return w.abs().amax(dim=-1).squeeze(-1)++ def fake_fn_b(w, bits, im):+ return -w.abs().amax(dim=-1).squeeze(-1)++ a = FakeDeferred(seed=0, search_fn=fake_fn_a)+ b = FakeDeferred(seed=1, search_fn=fake_fn_b)+ exp_a = fake_fn_a(a._deferred_search_inputs[0], 4, a._deferred_search_inputs[3])+ exp_b = fake_fn_b(b._deferred_search_inputs[0], 4, b._deferred_search_inputs[3])+ run_batched_wrap_search([a, b])+ # each kept its own search semantics (no shared stack across fns)+ self.assertTrue(torch.equal(a.init_scale, exp_a))+ self.assertTrue(torch.equal(b.init_scale, exp_b))++ def test_empty_list(self):+ self.assertFalse(run_batched_wrap_search([]))++ def test_batch_chunking_respects_cap(self):+ fakes = [FakeDeferred(seed=i) for i in range(6)]+ calls = []+ real_stack = torch.stack++ def spy_stack(tensors, *a, **k):+ calls.append(len(tensors))+ return real_stack(tensors, *a, **k)++ with mock.patch.object(torch, "stack", side_effect=spy_stack):+ run_batched_wrap_search(fakes, max_batch=2)+ # 3 chunks x (weights + imatrices) = 6 stacks, each of size 2+ self.assertEqual(sorted(calls), [2] * 6)+ for f in fakes:+ self.assertIsNotNone(f.init_scale)++ def test_element_budget_caps_batch_size(self):+ # the ELEMENT budget (not the VRAM probe) binds: budget mocked to two+ # modules' worth of elements -> 6 modules split into batches of 2+ fakes = [FakeDeferred(seed=i, shape=(64, 32)) for i in range(6)]+ calls = []+ real_stack = torch.stack++ def spy_stack(tensors, *a, **k):+ calls.append(len(tensors))+ return real_stack(tensors, *a, **k)++ import auto_round.algorithms.quantization.search_dispatch as dispatch_mod++ per_module = 2 * 64 * 32 # weight + imatrix elements+ with mock.patch.object(torch, "stack", side_effect=spy_stack), mock.patch.object(+ dispatch_mod, "probe_usable_bytes", return_value=2**40+ ), mock.patch.object(dispatch_mod, "_wrap_batch_max_elems", return_value=2 * per_module):+ run_batched_wrap_search(fakes)+ self.assertEqual(calls, [2, 2, 2, 2, 2, 2]) # 3 batches x 2 stacks (weights + imatrix)++ def test_env_gb_override_caps_batches(self):+ import auto_round.algorithms.quantization.search_dispatch as dispatch_mod++ # tiny modules (0.26M elems each): 1 GiB budget would allow ~1000 -> force 2 per batch via GB override+ fakes = [FakeDeferred(seed=i, shape=(1024, 128)) for i in range(4)]+ calls = []+ real_stack = torch.stack++ def spy_stack(tensors, *a, **k):+ calls.append(len(tensors))+ return real_stack(tensors, *a, **k)++ with mock.patch.object(dispatch_mod.envs, "AR_SEARCH_BATCH_GB", 0.001), mock.patch.object(+ torch, "stack", side_effect=spy_stack+ ):+ run_batched_wrap_search(fakes)+ # 0.001 GiB = ~268K elements -> 268214 // (2*1024*128=262144) = 1 module/batch;+ # 4 batches x (weights + imatrices) = 8 stacks of size 1+ self.assertEqual(calls, [1] * 8)+ for f in fakes:+ self.assertIsNotNone(f.init_scale)++ def test_env_gb_override_invalid_raises(self):+ import os++ from auto_round import envs as envs_mod++ fakes = [FakeDeferred(seed=i) for i in range(4)]+ # through the real parser (module __getattr__ -> lambda raises)+ os.environ["AR_SEARCH_BATCH_GB"] = "not-a-number"+ try:+ with self.assertRaises(ValueError):+ run_batched_wrap_search(fakes)+ finally:+ os.environ.pop("AR_SEARCH_BATCH_GB", None)+ # sibling patch.object tests may leave a static module attr behind+ if "AR_SEARCH_BATCH_GB" in vars(envs_mod):+ delattr(envs_mod, "AR_SEARCH_BATCH_GB")++ def test_kill_switch_disables(self):+ fakes = [FakeDeferred(seed=i) for i in range(3)]+ with mock.patch.object(search_dispatch.envs, "AR_DISABLE_BATCHED_SEARCH", True):+ handled = run_batched_wrap_search(fakes)+ self.assertFalse(handled)+ self.assertIsNone(fakes[0].init_scale) # inputs untouched: caller runs them per module+ for f in fakes:+ f._run_deferred_search_now() # the caller's documented fallback+ self.assertIsNotNone(fakes[0].init_scale)+++def _individual(fake):+ from auto_round.data_type.utils import reshape_imatrix_for_weight++ w, _dt, b, im_raw, _th, fn = fake._deferred_search_inputs+ return fn(w, b, reshape_imatrix_for_weight(im_raw, w, fake.orig_layer.group_size))+++def _stacked_im(fakes, stacked_w):+ from auto_round.algorithms.quantization.search_dispatch import _materialize_wrap_imatrix++ return _materialize_wrap_imatrix(fakes, stacked_w)+++class TestV2DeferralProtocol(unittest.TestCase):+ def _bare_v2(self):+ from auto_round.algorithms.quantization.sign_roundv2.quantizer import SignRoundOptimizedWrapperLinear++ w = object.__new__(SignRoundOptimizedWrapperLinear)+ w.init_scale = None+ w._deferred_search_inputs = None+ w.orig_layer = types.SimpleNamespace(group_size=128)+ return w++ def test_run_now_and_finalize_assign(self):+ from auto_round.data_type.utils import resolve_optimized_init_scale_fn++ w = self._bare_v2()+ weight = torch.randn(6, 128)+ imatrix_raw = torch.rand(128) + 0.5 # raw column, as production stages it+ fn = resolve_optimized_init_scale_fn("int", 1e-5)+ w._deferred_search_inputs = (weight, "int", 4, imatrix_raw, 1e-5, fn)+ from auto_round.data_type.utils import reshape_imatrix_for_weight++ ref = fn(weight, 4, reshape_imatrix_for_weight(imatrix_raw, weight, 128))+ w._run_deferred_search_now()+ self.assertTrue(torch.equal(w.init_scale, ref))+ self.assertIsNone(w._deferred_search_inputs)++ w2 = self._bare_v2()+ w2._deferred_search_inputs = (weight, "int", 4, imatrix_raw, 1e-5, fn)+ w2.finalize_batched_search(ref)+ self.assertTrue(torch.equal(w2.init_scale, ref))+ self.assertIsNone(w2._deferred_search_inputs)+++class TestRealV2Construction(unittest.TestCase):+ """The kwarg must survive the REAL base __init__ chain (regression: kwargs swallowed it)."""++ def _layer(self):+ import torch.nn as nn++ layer = nn.Linear(128, 64, bias=False)+ layer.data_type = "int"+ layer.bits = 4+ layer.sym = True+ layer.group_size = 128+ layer.iters = 10+ layer.act_bits = 16+ return layer++ def _make(self, defer_search):+ from auto_round.algorithms.quantization.sign_roundv2.quantizer import SignRoundOptimizedWrapperLinear++ layer = self._layer()+ return SignRoundOptimizedWrapperLinear(+ layer,+ enable_minmax_tuning=False,+ enable_norm_bias_tuning=False,+ enable_torch_compile=False,+ device="cpu",+ defer_search=defer_search,+ )++ def test_deferred_stages_through_real_init(self):+ w = self._make(defer_search=True)+ self.assertIsNotNone(w._deferred_search_inputs, "defer_search was swallowed by the base __init__ kwargs")+ self.assertIsNone(w.init_scale)+ w._run_deferred_search_now()+ self.assertIsNotNone(w.init_scale)++ def test_non_deferred_searches_inline_through_real_init(self):+ w = self._make(defer_search=False)+ self.assertIsNone(w._deferred_search_inputs)+ self.assertIsNotNone(w.init_scale)++ def test_kwarg_absent_by_default(self):+ w = self._make(defer_search=False)+ self.assertIsNone(w._deferred_search_inputs) # old callers unchanged+++class TestCpuFallbackPreservesSearchSettings(unittest.TestCase):+ """The CPU fallback must only change WHERE the search runs, not WHICH search."""++ def test_rebuild_carries_opt_rtn_and_neuqi_flags(self):+ import torch.nn as nn++ from auto_round.algorithms.quantization.rtn import batched_search++ layer = nn.Linear(8, 8, bias=False)+ layer.data_type = "int"+ layer.bits = 4+ layer.sym = True+ layer.group_size = -1+ layer.iters = 0+ layer.act_bits = 16++ class _Failed:+ orig_layer = layer+ disable_opt_rtn = False # optimized RTN active on the failed wrapper+ enable_neuqi = True # NeuQI active on the failed wrapper++ def unwrapper(self, cfg):+ raise torch.OutOfMemoryError("simulated per-module OOM")++ recorded = {}++ class _Recorder:+ def __call__(self, lyr, **kw):+ recorded.update(kw)+ recorded["_positional_is_layer"] = lyr is layer++ class _Out:+ def unwrapper(self, cfg):+ return "cpu_result"++ return _Out()++ with mock.patch.object(batched_search, "WrapperLinear", _Recorder()), mock.patch.object(+ batched_search, "dump_oom_tensor_census_", lambda *a, **k: None+ ):+ out = batched_search._unwrap_with_cpu_fallback(_Failed(), "model.l0")++ self.assertEqual(out, "cpu_result")+ self.assertTrue(recorded.pop("_positional_is_layer"))+ self.assertFalse(recorded["disable_opt_rtn"]) # stays OFF, not the True default+ self.assertTrue(recorded["enable_neuqi"]) # stays ON, not the False default+++class TestStackableLayoutGate(unittest.TestCase):+ """Layouts whose quant math is not row-stackable must finish per-module."""++ def setUp(self):+ self._env = mock.patch.dict(os.environ, {"AR_DISABLE_CROSS_DEVICE_SEARCH": "1"})+ self._env.start()+ self.addCleanup(self._env.stop)++ def _layer(self, seed, bits, group_size, act_bits=16):+ import torch.nn as nn++ g = torch.Generator().manual_seed(seed)+ layer = nn.Linear(128, 64, bias=False)+ with torch.no_grad():+ layer.weight.copy_(torch.randn(64, 128, generator=g))+ layer.data_type = "int"+ layer.bits = bits+ layer.sym = True+ layer.group_size = group_size+ layer.iters = 0+ layer.act_bits = act_bits+ if act_bits <= 8:+ layer.act_data_type = "int"+ layer.act_scale_dtype = torch.float16+ layer.act_sym = False+ layer.act_group_size = 128+ layer.act_dynamic = False+ layer.scale_dtype = torch.float16+ return layer++ def _wrapper(self, layer):+ from auto_round.wrapper import WrapperLinear++ return WrapperLinear(+ layer,+ device="cpu",+ enable_minmax_tuning=False,+ enable_norm_bias_tuning=False,+ enable_round_tuning=False,+ enable_torch_compile=False,+ disable_opt_rtn=True,+ iters=0,+ )++ def test_stackable_layout_matrix(self):+ from auto_round.algorithms.quantization.rtn.batched_search import _stackable_layout++ self.assertTrue(_stackable_layout(self._wrapper(self._layer(0, 4, 128)))) # row groups+ self.assertTrue(_stackable_layout(self._wrapper(self._layer(1, 4, -1)))) # per-channel+ self.assertFalse(_stackable_layout(self._wrapper(self._layer(2, 4, 0)))) # per-tensor scale+ self.assertFalse(_stackable_layout(self._wrapper(self._layer(3, 8, (128, 128))))) # 2-D blocks+ self.assertFalse(_stackable_layout(self._wrapper(self._layer(4, 16, 128, act_bits=8)))) # act-only++ def _parity(self, bits, group_size, act_bits=16):+ import torch.nn as nn++ from auto_round.algorithms.quantization.rtn.batched_search import run_batched_rtn_search++ with torch.no_grad():+ serial = []+ for i in range(3):+ layer = self._layer(seed=i, bits=bits, group_size=group_size, act_bits=act_bits)+ out = self._wrapper(layer).unwrapper({})+ serial.append(out.weight.data.clone())++ model = nn.Module()+ staged = []+ for i in range(3):+ layer = self._layer(seed=i, bits=bits, group_size=group_size, act_bits=act_bits)+ setattr(model, f"l{i}", layer)+ staged.append((f"l{i}", self._wrapper(layer)))+ run_batched_rtn_search(model, staged)+ for i in range(3):+ self.assertTrue(+ torch.equal(getattr(model, f"l{i}").weight.data, serial[i]),+ f"module {i} diverged from the serial path",+ )++ def test_per_tensor_group_size_matches_serial(self):+ self._parity(bits=4, group_size=0)++ def test_act_only_layer_matches_serial(self):+ self._parity(bits=16, group_size=128, act_bits=8)+++class TestWorkerBucketKeys(unittest.TestCase):+ def test_multi_worker_keys_are_device_parseable(self):+ """Regression: the threading key once carried the chunk entry dict itself."""+ import torch.nn as nn++ from auto_round.algorithms.quantization.rtn import batched_search++ model = nn.Module()+ staged = []+ for i in range(2):+ layer = TestBatchedRtnSearchParity()._layer(seed=i)+ setattr(model, f"l{i}", layer)+ staged.append((f"l{i}", TestBatchedRtnSearchParity()._make_wrapper(layer)))+ captured = {}++ def fake_run(keyed, fn):+ captured["keys"] = list(keyed.keys())++ import auto_round.algorithms.quantization.search_dispatch as _sd++ with mock.patch.object(_sd, "pick_search_worker_devices", return_value=["cpu", "cuda:9"]), mock.patch.object(+ _sd, "probe_usable_bytes", return_value=2**40+ ), mock.patch.object(batched_search, "run_items_by_device", side_effect=fake_run):+ # max_batch=1 -> two singleton chunks spread round-robin over the+ # two candidates -> two distinct worker buckets; run_items_by_device+ # is mocked so nothing actually moves to cuda:9+ batched_search.run_batched_rtn_search(model, staged, max_batch=1)+ # distinct worker bucket vs home -> multi-bucket path taken; every key must parse+ self.assertEqual(sorted(captured["keys"]), ["cpu", "cuda:9"])+ for k in captured["keys"]:+ torch.device(k) # the exact operation that crashed on the server+++class TestEagerUnwrap(unittest.TestCase):+ def test_compiled_fn_unwraps_to_original(self):+ import torch++ def orig(x):+ return x * 2++ compiled = torch.compile(orig)+ unwrapped = getattr(compiled, "_torchdynamo_orig_callable", None) or compiled+ self.assertIs(unwrapped, orig) # offloaded calls bypass the compiled wrapper+ self.assertEqual(unwrapped(torch.ones(2)).sum().item(), 4.0)++ def test_plain_fn_passes_through(self):+ fn = lambda x: x # noqa: E731+ self.assertIs(getattr(fn, "_torchdynamo_orig_callable", None) or fn, fn)+++class TestKwargRelocation(unittest.TestCase):+ def test_non_tensors_and_cpu_scalars_untouched(self):+ from auto_round.algorithms.quantization.rtn.batched_search import _relocate_tensor_kwargs++ scal = torch.tensor(1.0)+ kwargs = {"bits": 4, "v": scal, "group_size": 128, "data_type": "int"}+ out = _relocate_tensor_kwargs(dict(kwargs), "cpu")+ self.assertIs(out["v"], scal) # cpu scalar: same object, no copy+ self.assertEqual(out["bits"], 4)++ def test_returns_same_dict_semantics(self):+ from auto_round.algorithms.quantization.rtn.batched_search import _relocate_tensor_kwargs++ kwargs = {"imatrix": None, "tensor_min": None}+ out = _relocate_tensor_kwargs(kwargs, "cpu")+ self.assertIsNone(out["imatrix"])+++class TestSearchWorkerPicking(unittest.TestCase):+ def _pick(self, working_set, free_map, home="cuda:0"):+ import auto_round.algorithms.quantization.search_dispatch as dispatch_mod++ with mock.patch.object(torch.cuda, "device_count", return_value=len(free_map)), mock.patch.object(+ dispatch_mod, "probe_usable_bytes", side_effect=lambda k: free_map.get(k)+ ):+ return dispatch_mod.pick_search_worker_devices(working_set, home_device=home)++ def test_full_home_goes_to_idle_devices(self):+ free = {"cuda:0": 1 * 2**30, "cuda:1": 12 * 2**30, "cuda:2": 12 * 2**30}+ ws = 4 * 2**30+ self.assertEqual(self._pick(ws, free), ["cuda:1", "cuda:2"]) # home excluded, idles viable++ def test_all_full_falls_back_to_home(self):+ free = {"cuda:0": 0, "cuda:1": 1 * 2**30}+ self.assertEqual(self._pick(4 * 2**30, free), ["cuda:0"])++ def test_home_participates_when_it_fits(self):+ free = {"cuda:0": 10 * 2**30, "cuda:1": 10 * 2**30}+ self.assertEqual(self._pick(2 * 2**30, free), ["cuda:0", "cuda:1"])++ def test_kill_switch_pins_home(self):+ import auto_round.algorithms.quantization.search_dispatch as dispatch_mod++ with mock.patch.object(dispatch_mod.envs, "AR_DISABLE_CROSS_DEVICE_SEARCH", True):+ self.assertEqual(dispatch_mod.pick_search_worker_devices(4 * 2**30, home_device="cuda:3"), ["cuda:3"])++ def test_no_cuda_returns_home(self):+ import auto_round.algorithms.quantization.search_dispatch as dispatch_mod++ with mock.patch.object(torch.cuda, "device_count", return_value=0):+ self.assertEqual(dispatch_mod.pick_search_worker_devices(4 * 2**30, home_device="cpu"), ["cpu"])++ def test_hpu_lazy_stays_home_despite_idle_devices(self):+ # Habana lazy tensors execute on per-thread device contexts: a stacked+ # search spread onto worker threads reaches the write-back's host copy+ # without storage attached (CI: data_ptr()-> "no storage tensor+ # attached to lazy tensor"). Lazy mode must collapse to the home device.+ import auto_round.algorithms.quantization.search_dispatch as dispatch_mod++ class _Fleet:+ @staticmethod+ def device_count():+ return 4++ with mock.patch.object(dispatch_mod, "is_hpu_lazy_mode", return_value=True), mock.patch(+ "auto_round.utils.device_manager.get_ar_device", return_value=_Fleet()+ ), mock.patch.object(dispatch_mod, "probe_usable_bytes", side_effect=lambda k: 12 * 2**30):+ self.assertEqual(dispatch_mod.pick_search_worker_devices(2**30, home_device="hpu:0"), ["hpu:0"])++ def test_hpu_compile_mode_spreads_like_other_families(self):+ # compile mode runs the eager pipeline: concrete tensors survive worker+ # threads and cross-device moves, so spreading stays enabled there.+ import auto_round.algorithms.quantization.search_dispatch as dispatch_mod++ class _Fleet:+ @staticmethod+ def device_count():+ return 2++ with mock.patch.object(dispatch_mod, "is_hpu_lazy_mode", return_value=False), mock.patch(+ "auto_round.utils.device_manager.get_ar_device", return_value=_Fleet()+ ), mock.patch.object(dispatch_mod, "probe_usable_bytes", side_effect=lambda k: 12 * 2**30):+ self.assertEqual(dispatch_mod.pick_search_worker_devices(2**30, home_device="hpu:0"), ["hpu:0", "hpu:1"])++ def test_rtn_driver_offloads_to_viable_worker(self):+ # CPU-only: workers = [home] so behavior is the parity path already covered;+ # this pins that the bucket machinery runs end-to-end with the picker patched.+ import torch.nn as nn++ from auto_round.algorithms.quantization.rtn.batched_search import run_batched_rtn_search++ model = nn.Module()+ staged = []+ for i in range(2):+ layer = TestBatchedRtnSearchParity()._layer(seed=i)+ setattr(model, f"l{i}", layer)+ staged.append((f"l{i}", TestBatchedRtnSearchParity()._make_wrapper(layer)))+ with mock.patch(+ "auto_round.algorithms.quantization.search_dispatch.pick_search_worker_devices",+ return_value=["cpu"],+ ):+ run_batched_rtn_search(model, staged)+ for i in range(2):+ self.assertIsNotNone(getattr(model, f"l{i}").scale)+++class TestWrapperBlockDrivesBatching(unittest.TestCase):+ def _fake_block(self):+ block = torch.nn.Module()+ for i in range(3):+ m = torch.nn.Linear(8, 8, bias=False)+ m.bits = 4+ setattr(block, f"l{i}", m)+ return block++ def test_protocol_class_deferred_and_batched(self):+ import auto_round.wrapper as wrapper_mod++ calls = {"created": 0, "finalized": 0}++ class FakeBatched(torch.nn.Module):+ supports_batched_search = True++ def __init__(self, layer, defer_search=False, **kwargs):+ super().__init__()+ self.orig_layer = layer+ self.init_scale = None+ self._deferred_search_inputs = None+ calls["created"] += 1+ assert defer_search is True+ w = layer.weight.data.reshape(-1, layer.weight.shape[1])+ from auto_round.data_type.utils import resolve_optimized_init_scale_fn++ self._deferred_search_inputs = (+ w,+ "int",+ 4,+ None, # uniform importance: production stages None, not ones+ 1e-5,+ resolve_optimized_init_scale_fn("int", 1e-5),+ )++ def _run_deferred_search_now(self):+ w, _dt, b, im, _th, fn = self._deferred_search_inputs+ self.init_scale = fn(w, b, torch.ones_like(w) if im is None else im)+ self._deferred_search_inputs = None++ def finalize_batched_search(self, init_scale):+ self.init_scale = init_scale+ self._deferred_search_inputs = None+ calls["finalized"] += 1++ block = self._fake_block()+ q, u = wrapper_mod.wrapper_block(+ block, False, False, enable_torch_compile=False, device="cpu", wrapper_cls=FakeBatched+ )+ self.assertEqual(q, ["l0", "l1", "l2"])+ self.assertEqual(calls["created"], 3)+ self.assertEqual(calls["finalized"], 3) # all three searched via the batch driver+ for m in (block.l0, block.l1, block.l2):+ self.assertIsNotNone(m.init_scale)++ def test_kill_switch_runs_per_module(self):+ import auto_round.algorithms.quantization.search_dispatch as dispatch_mod+ import auto_round.wrapper as wrapper_mod++ stats = {"inline": 0, "now": 0}++ class FakeBatched(torch.nn.Module):+ supports_batched_search = True++ def __init__(self, layer, defer_search=False, **kwargs):+ super().__init__()+ self.orig_layer = layer+ self.init_scale = None+ self._deferred_search_inputs = None+ if defer_search:+ self._deferred_search_inputs = ("staged",)+ else: # kill switch: the class must search inline, as the real wrapper does+ stats["inline"] += 1+ self.init_scale = torch.zeros(1)++ def _run_deferred_search_now(self):+ stats["now"] += 1+ self.init_scale = torch.zeros(1)+ self._deferred_search_inputs = None++ def finalize_batched_search(self, init_scale):+ raise AssertionError("must not batch under the kill switch")++ block = self._fake_block()+ with mock.patch.object(dispatch_mod.envs, "AR_DISABLE_BATCHED_SEARCH", True):+ wrapper_mod.wrapper_block(+ block, False, False, enable_torch_compile=False, device="cpu", wrapper_cls=FakeBatched+ )+ self.assertEqual(stats["inline"], 3) # no deferral at all under the kill switch+ self.assertEqual(stats["now"], 0)+ self.assertIsNotNone(block.l0.init_scale)+++class TestBatchedRtnSearchParity(unittest.TestCase):+ """iters=0 batching: stacked vs serial must be bit-identical (incl. the imatrix path)."""++ def setUp(self):+ # parity is asserted against a serial CPU arm; on GPU-rich boxes the+ # multigpu offload would move the batched arm to idle CUDA workers+ # (different device numerics) -- out of scope for these tests+ self._env = mock.patch.dict(os.environ, {"AR_DISABLE_CROSS_DEVICE_SEARCH": "1"})+ self._env.start()+ self.addCleanup(self._env.stop)++ def _layer(self, seed, sym=True, with_imatrix=True):+ import torch.nn as nn++ g = torch.Generator().manual_seed(seed)+ layer = nn.Linear(128, 64, bias=False)+ with torch.no_grad():+ layer.weight.copy_(torch.randn(64, 128, generator=g))+ layer.data_type = "int"+ layer.bits = 4+ layer.sym = sym+ layer.group_size = 128+ layer.iters = 0+ layer.act_bits = 16+ layer.scale_dtype = torch.float16+ if with_imatrix:+ layer.imatrix = torch.rand(128, generator=g) + 0.5+ return layer++ def _make_wrapper(self, layer):+ from auto_round.wrapper import WrapperLinear++ return WrapperLinear(+ layer,+ device="cpu",+ enable_minmax_tuning=False,+ enable_norm_bias_tuning=False,+ enable_round_tuning=False,+ enable_torch_compile=False,+ disable_opt_rtn=False,+ iters=0,+ )++ def _run(self, sym, with_imatrix):+ from auto_round.algorithms.quantization.rtn.batched_search import run_batched_rtn_search++ # serial arm (production callers run under no_grad)+ serial = []+ with torch.no_grad():+ for i in range(3):+ layer = self._layer(seed=i, sym=sym, with_imatrix=with_imatrix)+ w = self._make_wrapper(layer)+ out = w.unwrapper({})+ serial.append((out.weight.data.clone(), out.scale, out.zp))+ # batched arm+ import torch.nn as nn++ model = nn.Module()+ staged = []+ for i in range(3):+ layer = self._layer(seed=i, sym=sym, with_imatrix=with_imatrix)+ setattr(model, f"l{i}", layer)+ w = self._make_wrapper(layer)+ staged.append((f"l{i}", w))+ run_batched_rtn_search(model, staged)+ for i in range(3):+ got = getattr(model, f"l{i}")+ ref_w, ref_scale, ref_zp = serial[i]+ self.assertTrue(torch.equal(got.weight.data, ref_w), f"weight mismatch module {i}")+ if isinstance(ref_scale, torch.Tensor):+ self.assertTrue(torch.equal(got.scale, ref_scale), f"scale mismatch module {i}")+ if ref_zp is not None and isinstance(ref_zp, torch.Tensor):+ self.assertTrue(torch.equal(got.zp, ref_zp), f"zp mismatch module {i}")++ def test_parity_sym_with_imatrix(self):+ self._run(sym=True, with_imatrix=True)++ def test_materialization_oom_falls_back_per_module(self):+ """An OOM while moving/copying the batch (before the quant call) must+ take the same per-module ladder as a stacked-call OOM, not abort."""+ import torch.nn as nn++ from auto_round.algorithms.quantization.rtn import batched_search+ from auto_round.algorithms.quantization.rtn.batched_search import run_batched_rtn_search++ serial = []+ with torch.no_grad():+ for i in range(3):+ layer = self._layer(seed=i, sym=True, with_imatrix=True)+ out = self._make_wrapper(layer).unwrapper({})+ serial.append((out.weight.data.clone(), out.scale, getattr(out, "zp", None)))++ model = nn.Module()+ staged = []+ for i in range(3):+ layer = self._layer(seed=i, sym=True, with_imatrix=True)+ setattr(model, f"l{i}", layer)+ staged.append((f"l{i}", self._make_wrapper(layer)))++ with mock.patch.object(+ batched_search,+ "_expand_imatrix",+ side_effect=torch.OutOfMemoryError("simulated materialization OOM"),+ ):+ run_batched_rtn_search(model, staged)+ for i in range(3):+ got = getattr(model, f"l{i}")+ ref_w, ref_scale, ref_zp = serial[i]+ self.assertTrue(torch.equal(got.weight.data, ref_w), f"weight mismatch module {i}")+ self.assertTrue(torch.equal(got.scale, ref_scale), f"scale mismatch module {i}")++ def test_stacked_oom_falls_back_per_module(self):+ """A stacked-call OOM finishes the chunk per-module: every module ends+ up exactly as the serial arm produced it."""+ import torch.nn as nn++ from auto_round.algorithms.quantization.rtn.batched_search import run_batched_rtn_search++ # serial reference arm (real quant fns, untouched)+ serial = []+ with torch.no_grad():+ for i in range(3):+ layer = self._layer(seed=i, sym=True, with_imatrix=True)+ out = self._make_wrapper(layer).unwrapper({})+ serial.append((out.weight.data.clone(), out.scale, getattr(out, "zp", None)))++ class _OomOnStacked:+ # raises only on the stacked 3D call; the per-module fallback's 2D+ # calls delegate to the real quant fn. One shared instance: the+ # staged key derives from the callable, so the fake must key+ # identically across wrappers to form one chunk; the name lands+ # outside the non-stackable denylist+ def __init__(self, real):+ self.real = real+ self.__name__ = "quant_tensor"++ def __call__(self, w, *a, **kw):+ if w.dim() == 3:+ raise torch.OutOfMemoryError("simulated stacked OOM")+ return self.real(w, *a, **kw)++ model = nn.Module()+ staged = []+ for i in range(3):+ layer = self._layer(seed=i, sym=True, with_imatrix=True)+ setattr(model, f"l{i}", layer)+ w = self._make_wrapper(layer)+ staged.append((f"l{i}", w))+ fake = _OomOnStacked(staged[0][1].weight_quant_func)+ for _name, w in staged:+ w.weight_quant_func = fake+ run_batched_rtn_search(model, staged)+ for i in range(3):+ got = getattr(model, f"l{i}")+ ref_w, ref_scale, ref_zp = serial[i]+ self.assertTrue(torch.equal(got.weight.data, ref_w), f"weight mismatch module {i}")+ self.assertTrue(torch.equal(got.scale, ref_scale), f"scale mismatch module {i}")+ if isinstance(ref_zp, torch.Tensor):+ self.assertTrue(torch.equal(got.zp, ref_zp), f"zp mismatch module {i}")++ def test_parity_sym_no_imatrix(self):+ self._run(sym=True, with_imatrix=False)++ def test_parity_asym_with_imatrix(self):+ self._run(sym=False, with_imatrix=True)++ def test_parity_act_quant_runs_full_unwrapper_tail(self):+ """Regression (review R4-3): the stacked write-back used _apply_qdq ++ attach(orig_layer), skipping the unwrapper tail -- act-quantized layers+ (act_bits <= 8, W4A8/W4A4) silently lost WrapperWALayer and the act+ metadata the serial and singleton paths attach."""+ import torch.nn as nn++ from auto_round.algorithms.quantization.rtn.batched_search import run_batched_rtn_search+ from auto_round.wrapper import WrapperWALayer++ def _act_layer(seed):+ layer = self._layer(seed)+ layer.act_bits = 8 # enables the act tail in unwrapper+ layer.act_data_type = "int"+ layer.act_sym = False+ layer.act_dynamic = False # static act: the tail computes act_scale+ layer.act_group_size = -1+ return layer++ # serial arm: the full tail attaches a WrapperWALayer+ with torch.no_grad():+ w = self._make_wrapper(_act_layer(0))+ serial_out = w.unwrapper({})+ self.assertIsInstance(serial_out, WrapperWALayer)++ # batched arm: same module type + act metadata + bit-identical weights+ model = nn.Module()+ staged = []+ for i in range(3):+ layer = _act_layer(seed=i)+ setattr(model, f"l{i}", layer)+ staged.append((f"l{i}", self._make_wrapper(layer)))+ run_batched_rtn_search(model, staged)+ for i in range(3):+ got = getattr(model, f"l{i}")+ self.assertIsInstance(got, WrapperWALayer, f"module {i} lost the act wrapper")+ self.assertIsNotNone(getattr(got, "act_quant_func", None), f"module {i} missing act_quant_func")+ # the tail sets static-act attrs on the wrapped orig layer+ self.assertTrue(hasattr(got.orig_layer, "act_scale"), f"module {i} missing act_scale")+ self.assertIsNotNone(getattr(got.orig_layer, "scale", None), f"module {i} missing weight scale")+ ref_w = None+ with torch.no_grad():+ w_ref = self._make_wrapper(_act_layer(0))+ ref_w = w_ref.unwrapper({}).weight.data.clone()+ self.assertTrue(torch.equal(model.l0.weight.data, ref_w))++ def _run_shape_dtype(self, out_f, in_f, gs, dtype):+ """Batched-vs-serial parity for arbitrary shapes/dtypes with an imatrix+ (regressions R6-2/R6-3: bf16 weights + fp32 imatrix; in % gs != 0)."""+ import torch.nn as nn++ from auto_round.algorithms.quantization.rtn.batched_search import run_batched_rtn_search++ def _layer(seed):+ import torch.nn as nn++ g = torch.Generator().manual_seed(seed)+ layer = nn.Linear(in_f, out_f, bias=False)+ with torch.no_grad():+ layer.weight.copy_(torch.randn(out_f, in_f, generator=g).to(dtype))+ layer.data_type = "int"+ layer.bits = 4+ layer.sym = False+ layer.group_size = gs+ layer.iters = 0+ layer.act_bits = 16+ layer.scale_dtype = torch.float32+ layer.imatrix = (torch.rand(in_f, generator=g) + 0.5).float() # fp32, like the hook+ return layer++ with torch.no_grad():+ serial = []+ for i in range(3):+ w = self._make_wrapper(_layer(i))+ out = w.unwrapper({})+ serial.append((out.weight.data.clone(), out.scale))++ model = nn.Module()+ staged = []+ for i in range(3):+ layer = _layer(i)+ setattr(model, f"l{i}", layer)+ staged.append((f"l{i}", self._make_wrapper(layer)))+ run_batched_rtn_search(model, staged)+ for i in range(3):+ got = getattr(model, f"l{i}")+ ref_w, ref_scale = serial[i]+ self.assertTrue(torch.equal(got.weight.data, ref_w), f"weight mismatch module {i}")+ self.assertTrue(torch.equal(got.scale, ref_scale), f"scale mismatch module {i}")++ def test_parity_bf16_weights_fp32_imatrix(self):+ self._run_shape_dtype(64, 128, 128, torch.bfloat16)++ def test_parity_fp16_weights_fp32_imatrix(self):+ self._run_shape_dtype(64, 128, 128, torch.float16)++ def test_parity_group_size_not_dividing_in_features(self):+ self._run_shape_dtype(3, 10, 4, torch.float32)++ def test_staged_key_normalizes_compiled_quant_fn(self):+ """Regression (R6-4): with enable_torch_compile, every wrapper carries a+ UNIQUE torch.compile wrapper around the SHARED eager fn; keying the raw+ callable collapsed all groups to singletons (batching silently dead)."""+ from auto_round.algorithms.quantization.rtn.batched_search import _staged_key++ class _Compiled:+ def __init__(self, orig):+ self._torchdynamo_orig_callable = orig++ def __call__(self, *a, **k): # pragma: no cover+ raise AssertionError("compiled fn must not run here")++ def _shared_eager(w, bits, imatrix): # pragma: no cover - identity stub+ return None++ layers, wrappers = [], []+ for i in range(2):+ layer = self._layer(seed=i)+ layers.append(layer)+ w = self._make_wrapper(layer)+ w.weight_quant_func = _Compiled(_shared_eager) # distinct wrappers, shared orig+ wrappers.append(w)+ k0 = _staged_key(wrappers[0], wrappers[0].orig_layer.weight, None)+ k1 = _staged_key(wrappers[1], wrappers[1].orig_layer.weight, None)+ self.assertEqual(k0, k1)++ def test_quant_call_kwargs_never_relocates_imatrix_to_meta(self):+ """Regression (R6-1): a meta-resident stored weight must not become the+ imatrix relocation target."""+ layer = self._layer(seed=0)+ layer.imatrix = torch.rand(layer.weight.shape[1]) + 0.5+ w = self._make_wrapper(layer)+ # simulate the low-memory lane: stored weight on meta, real data via get_weight+ real = layer.weight.data.clone()+ layer.weight = torch.nn.Parameter(torch.empty_like(real, device="meta"), requires_grad=False)+ layer.get_weight = lambda: real+ kwargs = w._quant_call_kwargs(torch.tensor(0.0), torch.tensor(1.0), torch.tensor(1.0))+ im = kwargs.get("imatrix")+ self.assertIsNotNone(im)+ self.assertNotEqual(im.device.type, "meta")+ self.assertEqual(im.device.type, "cpu") # wrapper device in these tests++ def test_threaded_write_back_swaps_compiled_act_fn_to_eager(self):+ """Regression (review R5-1): on worker threads the unwrapper act tail+ would make its FIRST call to the torch.compile-wrapped act_quant_func+ -- the same dynamo trace-lock race the weight fn had. The threaded+ write-back must swap BOTH compiled callables (weight AND act) to their+ eager originals and restore them afterwards."""+ from auto_round.algorithms.quantization.rtn.batched_search import swap_wrapper_callables_to_eager++ ran_eager = []++ def _fake_eager_act(x, **kwargs):+ ran_eager.append(True)+ return x, torch.ones(1), None++ class _Compiled:+ def __init__(self, orig):+ self._torchdynamo_orig_callable = orig++ def __call__(self, *a, **k): # pragma: no cover - must never run on workers+ raise AssertionError("compiled callable ran while swapped out")++ w = self._make_wrapper(self._layer(0))+ compiled_w = _Compiled(lambda *a, **k: (None, None, None))+ compiled_a = _Compiled(_fake_eager_act)+ w.weight_quant_func = compiled_w+ w.act_quant_func = compiled_a++ restore = swap_wrapper_callables_to_eager(w)+ self.assertIsNotNone(restore)+ # swapped: both attrs now point at the eager originals+ self.assertIs(w.weight_quant_func, compiled_w._torchdynamo_orig_callable)+ self.assertIs(w.act_quant_func, _fake_eager_act)+ w.act_quant_func(None) # the eager act callable is what runs on the worker+ restore()+ # restored: both compiled callables back in place+ self.assertIs(w.weight_quant_func, compiled_w)+ self.assertIs(w.act_quant_func, compiled_a)++ # wrappers without compiled callables need no swap+ w2 = self._make_wrapper(self._layer(1))+ self.assertIsNone(swap_wrapper_callables_to_eager(w2))++ def _conv1d_layer(self, seed, nf, nx):+ from transformers.pytorch_utils import Conv1D++ g = torch.Generator().manual_seed(seed)+ layer = Conv1D(nf, nx) # weight is [nx, nf]; quant math runs on the transpose+ with torch.no_grad():+ layer.weight.copy_(torch.randn(nx, nf, generator=g))+ layer.data_type = "int"+ layer.bits = 4+ layer.sym = True+ layer.group_size = min(nx, 128)+ layer.iters = 0+ layer.act_bits = 16+ layer.scale_dtype = torch.float16+ layer.imatrix = torch.rand(nx, generator=g) + 0.5+ return layer++ def _run_conv1d(self, nf, nx):+ from auto_round.algorithms.quantization.rtn.batched_search import run_batched_rtn_search++ with torch.no_grad():+ serial = []+ for i in range(3):+ w = self._make_wrapper(self._conv1d_layer(seed=i, nf=nf, nx=nx))+ out = w.unwrapper({})+ serial.append((out.weight.data.clone(), out.scale, out.zp))+ import torch.nn as nn++ model = nn.Module()+ staged = []+ for i in range(3):+ layer = self._conv1d_layer(seed=i, nf=nf, nx=nx)+ setattr(model, f"c{i}", layer)+ staged.append((f"c{i}", self._make_wrapper(layer)))+ run_batched_rtn_search(model, staged)+ for i in range(3):+ got = getattr(model, f"c{i}")+ ref_w, ref_scale, ref_zp = serial[i]+ self.assertTrue(torch.equal(got.weight.data, ref_w), f"weight mismatch module {i}")+ self.assertEqual(tuple(got.weight.data.shape), (nx, nf)) # Conv1D layout restored+ if isinstance(ref_scale, torch.Tensor):+ self.assertTrue(torch.equal(got.scale, ref_scale), f"scale mismatch module {i}")++ def _run_kwargs_mix(self, mutate):+ # two same-shape modules whose per-layer quant kwargs differ must NOT+ # share a stacked chunk (chunk[0]'s kwargs would silently apply to+ # both), and each must still match its serial result bit-for-bit+ from auto_round.algorithms.quantization.rtn.batched_search import run_batched_rtn_search++ with torch.no_grad():+ serial = []+ for i in range(2):+ layer = self._layer(seed=i, sym=True, with_imatrix=False)+ mutate(layer, i)+ w = self._make_wrapper(layer)+ out = w.unwrapper({})+ serial.append(out.weight.data.clone())+ import torch.nn as nn++ model = nn.Module()+ staged = []+ for i in range(2):+ layer = self._layer(seed=i, sym=True, with_imatrix=False)+ mutate(layer, i)+ setattr(model, f"k{i}", layer)+ staged.append((f"k{i}", self._make_wrapper(layer)))+ stacks = []+ real_stack = torch.stack++ def spy_stack(tensors, *a, **k):+ stacks.append(len(tensors))+ return real_stack(tensors, *a, **k)++ with mock.patch.object(torch, "stack", side_effect=spy_stack):+ run_batched_rtn_search(model, staged)+ # differing kwargs -> per-module: every stacked call carries exactly+ # ONE row (1-row chunks ride the stacked machinery for worker+ # placement; nothing is ever SHARED across the differing modules)+ self.assertTrue(stacks, "expected per-module stacked calls")+ self.assertTrue(all(s == 1 for s in stacks), f"shared batch: {stacks}")+ for i in range(2):+ got = getattr(model, f"k{i}")+ self.assertTrue(torch.equal(got.weight.data, serial[i]), f"weight mismatch module {i}")++ def test_mixed_scale_dtype_never_shares_batch(self):+ def mutate(layer, i):+ layer.scale_dtype = torch.float16 if i == 0 else torch.bfloat16++ self._run_kwargs_mix(mutate)++ def test_super_bits_on_one_layer_never_shares_batch(self):+ def mutate(layer, i):+ if i == 1:+ layer.super_bits = 2+ layer.super_group_size = 16++ self._run_kwargs_mix(mutate)++ def test_global_scale_difference_never_shares_batch(self):+ import torch.nn as nn++ from auto_round.algorithms.quantization.rtn.batched_search import run_batched_rtn_search++ with torch.no_grad():+ serial = []+ for i in range(2):+ layer = self._layer(seed=i, sym=True, with_imatrix=False)+ w = self._make_wrapper(layer)+ w.weight_global_scale = torch.tensor(1.0 + i)+ out = w.unwrapper({})+ serial.append(out.weight.data.clone())++ model = nn.Module()+ staged = []+ for i in range(2):+ layer = self._layer(seed=i, sym=True, with_imatrix=False)+ w = self._make_wrapper(layer)+ w.weight_global_scale = torch.tensor(1.0 + i)+ setattr(model, f"g{i}", layer)+ staged.append((f"g{i}", w))+ stacks = []+ real_stack = torch.stack++ def spy_stack(tensors, *a, **k):+ stacks.append(len(tensors))+ return real_stack(tensors, *a, **k)++ with mock.patch.object(torch, "stack", side_effect=spy_stack):+ run_batched_rtn_search(model, staged)+ # differing kwargs -> per-module: every stacked call carries exactly+ # ONE row (1-row chunks ride the stacked machinery for worker+ # placement; nothing is ever SHARED across the differing modules)+ self.assertTrue(stacks, "expected per-module stacked calls")+ self.assertTrue(all(s == 1 for s in stacks), f"shared batch: {stacks}")+ for i in range(2):+ got = getattr(model, f"g{i}")+ self.assertTrue(torch.equal(got.weight.data, serial[i]), f"weight mismatch module {i}")++ def test_parity_conv1d_square(self):+ self._run_conv1d(nf=64, nx=64)++ def test_parity_conv1d_nonsquare(self):+ # non-square is where the missing transpose is a hard crash, not silent corruption+ self._run_conv1d(nf=64, nx=128)++ def test_oom_chunk_falls_back_per_module(self):+ import torch.nn as nn++ from auto_round.algorithms.quantization.rtn import batched_search++ model = nn.Module()+ staged = []+ for i in range(2):+ layer = self._layer(seed=i)+ setattr(model, f"l{i}", layer)+ staged.append((f"l{i}", self._make_wrapper(layer)))+ real_fn = staged[0][1].weight_quant_func+ calls = {"n": 0, "raised": 0}++ def boom(*a, **k):+ calls["n"] += 1+ if calls["n"] == 1: # only the stacked call raises; per-module fallback delegates+ calls["raised"] += 1+ raise torch.OutOfMemoryError("simulated")+ return real_fn(*a, **k)++ # patch BOTH wrappers with the SAME callable so the group key still matches+ with mock.patch.object(staged[0][1], "weight_quant_func", boom), mock.patch.object(+ staged[1][1], "weight_quant_func", boom+ ):+ batched_search.run_batched_rtn_search(model, staged)+ self.assertEqual(calls["raised"], 1) # the stacked call raised exactly once+ self.assertEqual(calls["n"], 3) # then the two per-module fallbacks delegated to the real fn+ for i in range(2):+ got = getattr(model, f"l{i}")+ self.assertIsNotNone(getattr(got, "scale", None)) # per-module fallback quantized it+++class FakeAnchor:+ """Duck-typed deferred NeuUQI anchor: stages inputs, applies searched margins."""++ def __init__(self, seed, shape=(8, 128), sym=True, with_imatrix=True):+ import types as _types++ g = torch.Generator().manual_seed(seed)+ w = torch.randn(*shape, generator=g)+ im = (torch.rand(shape[1], generator=g) + 0.5) if with_imatrix else None+ self._deferred_neuqi_anchor = (w, 4, shape[1], im, sym)+ self._applied = None+ self.device = "cpu"+ self.orig_layer = _types.SimpleNamespace(bits=4, group_size=shape[1])+ self.weight_min = torch.zeros(w.numel() // shape[1])+ self.weight_max = torch.zeros(w.numel() // shape[1])++ def _run_deferred_neuqi_anchor_now(self):+ from auto_round.data_type.neuqi import neuqi_anchor_margins++ w, bits, gs, im, sym = self._deferred_neuqi_anchor+ wmin, wmax = neuqi_anchor_margins(w, bits, gs, im, self.device, sym=sym)+ self._apply_neuqi_anchor(wmin, wmax)++ def _apply_neuqi_anchor(self, wmin, wmax):+ self._applied = (wmin.detach().clone(), wmax.detach().clone())+ self.weight_min = wmin+ self.weight_max = wmax+ self._deferred_neuqi_anchor = None+++class TestBatchedNeuqiAnchors(unittest.TestCase):+ def _make(self, n, **kw):+ return [FakeAnchor(i, **kw) for i in range(n)]++ def test_batched_anchor_matches_serial(self):+ for sym in (True, False):+ for with_imatrix in (True, False):+ serial = self._make(4, sym=sym, with_imatrix=with_imatrix)+ for w in serial:+ w._run_deferred_neuqi_anchor_now()+ batched = self._make(4, sym=sym, with_imatrix=with_imatrix)+ from auto_round.algorithms.quantization.search_dispatch import run_batched_neuqi_anchors++ self.assertTrue(run_batched_neuqi_anchors(batched))+ for s, b in zip(serial, batched):+ self.assertTrue(torch.equal(s._applied[0], b._applied[0]), f"sym={sym} im={with_imatrix} wmin")+ self.assertTrue(torch.equal(s._applied[1], b._applied[1]), f"sym={sym} im={with_imatrix} wmax")++ def test_probe_shrinks_anchor_batches(self):+ from auto_round.algorithms.quantization import search_dispatch++ batched = self._make(8)+ # tiny usable headroom: at most two modules per stacked batch+ from auto_round.data_type.neuqi import _MAX_TMP_ELEMS++ # half the headroom must cover the per-call sweep budget plus two+ # modules' fp32 copy chain (incl. imatrix)+ per_module = 8 * 128 * 4 * 16 + 8 * 128 * 4+ with mock.patch.object(+ search_dispatch,+ "probe_usable_bytes",+ return_value=(_MAX_TMP_ELEMS * 4 * 8 + per_module * 2) * 2 + 1,+ ), mock.patch.dict(os.environ, {"AR_PERF_COUNTERS": "1"}), mock.patch.object(+ search_dispatch.logger, "info"+ ) as dbg:+ self.assertTrue(search_dispatch.run_batched_neuqi_anchors(batched))+ args = dbg.call_args.args+ text = args[0] % tuple(args[1:])+ # each chunk's own transient (two modules' chain + the per-call+ # sweep budget) fits half the probed headroom, serially re-earned+ self.assertIn("4 batch", text)++ def test_execute_time_headroom_splits_chunks(self):+ # plan-time probe blind (cpu-staged weights) -> one big chunk; the+ # executing device then reports too little headroom -> the chunk+ # halves recursively down to per-module calls+ import auto_round.data_type.neuqi as neuqi_mod+ from auto_round.algorithms.quantization import search_dispatch++ calls = {"n": 0}+ real = neuqi_mod.neuqi_anchor_margins++ def _counting(weight, bits, gs, im, device, sym=False):+ calls["n"] += 1+ return real(weight, bits, gs, im, device, sym=sym)++ from auto_round.data_type.neuqi import _MAX_TMP_ELEMS++ per = 8 * 128 * 4 * 16 + 8 * 128 * 4 + _MAX_TMP_ELEMS * 4 * 8+ batched = self._make(8)+ with mock.patch.object(+ search_dispatch, "probe_usable_bytes", side_effect=[None] + [per] * 64+ ), mock.patch.object(neuqi_mod, "neuqi_anchor_margins", _counting):+ self.assertTrue(search_dispatch.run_batched_neuqi_anchors(batched))+ self.assertEqual(calls["n"], 8) # split down to single-module stacks+ for w in batched:+ self.assertIsNotNone(w._applied)++ def test_search_batch_gb_bounds_anchor_stacks(self):+ # the env budget counts weight + expanded-imatrix elements, exactly+ # like the wrap lane+ import os as _os++ from auto_round.algorithms.quantization import search_dispatch++ batched = self._make(8) # with imatrix: 2 x 1024 elements per module+ budget_elements = 2048 # one module's weight+imatrix, no room for a pair+ gb = budget_elements * 4 / 2**30+ saved = _os.environ.get("AR_SEARCH_BATCH_GB")+ _os.environ["AR_SEARCH_BATCH_GB"] = repr(gb)+ try:+ with mock.patch.dict(os.environ, {"AR_PERF_COUNTERS": "1"}), mock.patch.object(+ search_dispatch.logger, "info"+ ) as dbg:+ self.assertTrue(search_dispatch.run_batched_neuqi_anchors(batched))+ finally:+ if saved is None:+ _os.environ.pop("AR_SEARCH_BATCH_GB", None)+ else:+ _os.environ["AR_SEARCH_BATCH_GB"] = saved+ args = dbg.call_args.args+ text = args[0] % tuple(args[1:])+ self.assertIn("8 batch", text) # one module per stack under the tight budget++ def test_disabled_batching_returns_false(self):+ from auto_round.algorithms.quantization import search_dispatch++ batched = self._make(3)+ with mock.patch.object(search_dispatch, "batched_search_disabled", return_value=True):+ self.assertFalse(search_dispatch.run_batched_neuqi_anchors(batched))+ # the caller's per-module fallback then finishes them+ for w in batched:+ w._run_deferred_neuqi_anchor_now()+ self.assertTrue(all(w._applied is not None for w in batched))+++class TestWrapSearchExecuteTimeSplit(unittest.TestCase):+ def test_headroom_shortfall_halves_chunks(self):+ # plan-time probe blind (cpu) -> one chunk; the executor then sees too+ # little headroom -> the chunk halves down to per-module stacks+ import auto_round.algorithms.quantization.search_dispatch as sd++ fakes = [FakeDeferred(seed=i, shape=(8, 128)) for i in range(4)]+ calls = []+ real_stack = torch.stack++ def spy_stack(tensors, *a, **k):+ calls.append(len(tensors))+ return real_stack(tensors, *a, **k)++ with mock.patch.object(sd, "probe_usable_bytes", side_effect=[None] + [1] * 64), mock.patch.object(+ torch, "stack", side_effect=spy_stack+ ):+ self.assertTrue(run_batched_wrap_search(fakes))+ self.assertEqual(calls, [1] * 8) # four single-module stacks x (weights + imatrix)+ for f in fakes:+ self.assertIsNotNone(f.init_scale)+++class TestOffloadedImatrixDevice(unittest.TestCase):+ def test_offloaded_chunk_moves_materialized_imatrix_to_worker(self):+ # cross-device tensor pairs cannot be hosted on a CPU-only test box;+ # pin the source contract instead (the materialized imatrix stack is+ # built from home-resident staged columns and must follow the stacked+ # weights onto the executing device before the search call)+ import inspect++ from auto_round.algorithms.quantization import search_dispatch as sd++ src = inspect.getsource(sd.run_batched_wrap_search)+ self.assertIn("stacked_im.to(worker_key", src)diff --git a/test/unit/test_cpu/quantization/test_neuqi.py b/test/unit/test_cpu/quantization/test_neuqi.pyindex ab4769c4c..849898391 100644--- a/test/unit/test_cpu/quantization/test_neuqi.py+++ b/test/unit/test_cpu/quantization/test_neuqi.py@@ -1163,6 +1163,56 @@ class TestNeuqiSymCompiledCore:assert calls["n"] == 1assert neuqi._sym_compile_failed+ def test_failure_warning_names_the_exception(self, monkeypatch):+ monkeypatch.setenv("AR_NEUQI_BACKEND", "compile")+ from unittest import mock++ from auto_round.data_type import neuqi++ def _flaky(fn):+ def _raise(*a, **k):+ raise RuntimeError("kernel boom")++ return _raise++ monkeypatch.setattr(neuqi.torch, "compile", _flaky)+ with mock.patch.object(neuqi.logger, "warning") as warn:+ out = neuqi._sym_loss_chunk_eval(torch.randn(8, 32), None, torch.rand(8, 2) + 0.5, 7)+ assert torch.isfinite(out[0]).all()+ text = "".join(str(a) for a in warn.call_args.args)+ assert "kernel boom" in text++ def test_concurrent_first_calls_compile_once(self, monkeypatch):+ monkeypatch.setenv("AR_NEUQI_BACKEND", "compile")+ import threading+ import time++ from auto_round.data_type import neuqi++ entered = {"n": 0}+ guard = threading.Lock()++ def _counting_compile(fn):+ with guard:+ entered["n"] += 1+ time.sleep(0.05)+ return fn # eager math stands in for the compiled core++ monkeypatch.setattr(neuqi.torch, "compile", _counting_compile)+ ok = []++ def _call():+ out = neuqi._sym_loss_chunk_eval(torch.randn(8, 32), None, torch.rand(8, 2) + 0.5, 7)+ ok.append(bool(torch.isfinite(out[0]).all()))++ threads = [threading.Thread(target=_call) for _ in range(8)]+ for t in threads:+ t.start()+ for t in threads:+ t.join()+ assert all(ok)+ assert entered["n"] == 1+def test_search_end_to_end_matches_eager_backend(self, monkeypatch):"""The compiled core routes every chunk through; results must match aneager-backend run."""@@ -1481,9 +1531,15 @@ class TestSignRoundEnableNeuqi:assert SignRoundConfig(bits=4, group_size=32, sym=False, enable_neuqi=True).enable_neuqi is True-class TestExpertBatching:- """Same-shape expert projections quantize in one stacked search call- (row-independent: results identical to per-module calls)."""+class TestNeuqiBatchedSearch:+ """The batched zero-shot search driver carries the NeUQI sym/asym searches.++ Every zero-shot NeUQI run rides the staged batched driver; stacked batches+ and per-module serial calls must produce identical modules: bit-equal qdq+ weights with matching scale/zp metadata, for both symmetry classes, with+ and without imatrix weighting. The gating contracts (which modules run a+ search at all) live in the staging heuristic exercised below.+ """@pytest.fixture(autouse=True)def _tie_free_grid(self, monkeypatch):@@ -1495,176 +1551,140 @@ class TestExpertBatching:# contract was verified againstmonkeypatch.setenv("AR_NEUQI_COARSE", "256")monkeypatch.setenv("AR_NEUQI_FINE", "64")+ # parity is asserted against a serial CPU arm; keep the batched arm home+ monkeypatch.setenv("AR_DISABLE_CROSS_DEVICE_SEARCH", "1")- def teardown_method(self):- import auto_round.algorithms.quantization.rtn.quantizer as _qmod-- if "model_context" in _qmod.OptimizedRTNQuantizer.__dict__:- del _qmod.OptimizedRTNQuantizer.model_context-- def _expert(self, name, out=16, inn=32, bits=4, group_size=32, sym=False, seed=0):+ def _expert(self, name, out=16, inn=32, bits=4, group_size=32, sym=False, seed=0, imatrix=False):m = torch.nn.Linear(inn, out, bias=False)- torch.manual_seed(seed)+ gen = torch.Generator().manual_seed(seed)with torch.no_grad():- m.weight.copy_(torch.randn(out, inn))+ m.weight.copy_(torch.randn(out, inn, generator=gen))m.global_name = namem.bits = bitsm.group_size = group_sizem.sym = symm.data_type = "int"+ m.iters = 0+ m.act_bits = 16+ m.scale_dtype = torch.float16+ if imatrix:+ m.imatrix = torch.rand(inn, generator=gen) + 0.5return m- def _quantizer(self, enable_neuqi=True, disable_opt_rtn=False, is_moe=True):- from auto_round.algorithms.quantization.rtn.config import OptimizedRTNConfig- from auto_round.algorithms.quantization.rtn.quantizer import OptimizedRTNQuantizer+ def _moe_model(self, proj="gate_proj", sym=False, imatrix=False, n=3, seed0=0):+ # a real nested tree: the driver re-attaches results by dotted name, so+ # every parent module along the path must exist+ model = torch.nn.Module()+ blk = torch.nn.Module()+ model.blk = blk+ experts = torch.nn.ModuleList()+ blk.experts = experts+ mods = []+ for i in range(n):+ e = torch.nn.Module()+ experts.append(e)+ m = self._expert(f"blk.experts.{i}.{proj}", sym=sym, seed=seed0 + i, imatrix=imatrix)+ setattr(e, proj, m)+ mods.append(m)+ return model, mods++ def _wrapper(self, m):+ from auto_round.wrapper import WrapperLinear- cfg = OptimizedRTNConfig(bits=4, group_size=32, sym=False, enable_neuqi=enable_neuqi)- cfg.disable_opt_rtn = disable_opt_rtn- cfg.orig_disable_opt_rtn = bool(disable_opt_rtn)- q = OptimizedRTNQuantizer(cfg)- if is_moe:- # model_context is a read-only property backed by the run ctx;- # patch the class property for the MoE-heuristic branch- import auto_round.algorithms.quantization.rtn.quantizer as _qmod-- _qmod.OptimizedRTNQuantizer.model_context = property(lambda self: type("MC", (), {"is_moe_model": True})())- return q-- def test_sym_and_asym_batched_and_equivalent(self):- # THE sym gap fix: sym modules join the batches under neuqi, and the- # stacked call matches per-module search outputs exactly- q = self._quantizer()- mods = [self._expert(f"blk.experts.{i}.gate_proj", sym=False, seed=i) for i in range(4)]- sym_mods = [self._expert(f"blk.experts.{i}.up_proj", sym=True, seed=100 + i) for i in range(4)]- batches, singles = q._split_expert_batches(mods + sym_mods)- assert len(batches) == 2 and not singles- assert {m.sym for m in batches[0]} == {False} and {m.sym for m in batches[1]} == {True}-- from auto_round.data_type.neuqi import quant_tensor_opt_rtn_asym, quant_tensor_opt_rtn_sym_neuqi-- assert q._quantize_expert_batch(batches[0], "cpu") == []- for m in mods:- ref_qdq, ref_scale, ref_zp = quant_tensor_opt_rtn_asym(- m.weight.data, bits=m.bits, group_size=m.group_size, v=0.0, q_scale_thresh=1e-5, imatrix=None- )- assert torch.equal(m.weight.data, ref_qdq)- assert torch.equal(m.scale.reshape(-1), ref_scale.reshape(-1))- assert torch.equal(m.zp.reshape(-1), ref_zp.reshape(-1))- assert m.q_scale_thresh == 1e-5-- assert q._quantize_expert_batch(batches[1], "cpu") == []- for m in sym_mods:- ref_qdq, ref_scale, ref_zp = quant_tensor_opt_rtn_sym_neuqi(- m.weight.data, bits=m.bits, group_size=m.group_size, v=0.0, q_scale_thresh=1e-5, imatrix=None- )- assert torch.equal(m.weight.data, ref_qdq)- assert torch.equal(m.scale.reshape(-1), ref_scale.reshape(-1))- assert m.zp == ref_zp- # R2-5: the batch writeback must stamp the resolved data_type both classes- assert all(m.data_type == "opt_rtn_int_asym" for m in mods)- assert all(m.data_type == "opt_rtn_int_sym_neuqi" for m in sym_mods)-- def test_imatrix_weighting_stacked_equivalence(self):- q = self._quantizer()- mods = [self._expert(f"blk.experts.{i}.down_proj", sym=False, seed=7 + i) for i in range(3)]- for i, m in enumerate(mods):- torch.manual_seed(50 + i)- m.imatrix = torch.rand(m.weight.shape[1])- batches, singles = q._split_expert_batches(mods)- assert len(batches) == 1 and not singles- assert q._quantize_expert_batch(batches[0], "cpu") == []- from auto_round.data_type.neuqi import quant_tensor_opt_rtn_asym+ return WrapperLinear(+ m,+ device="cpu",+ enable_minmax_tuning=False,+ enable_norm_bias_tuning=False,+ enable_round_tuning=False,+ enable_torch_compile=False,+ disable_opt_rtn=False,+ enable_neuqi=True,+ iters=0,+ )- for m in mods:- ref_qdq, ref_scale, ref_zp = quant_tensor_opt_rtn_asym(- m.weight.data,- bits=m.bits,- group_size=m.group_size,- v=0.0,- q_scale_thresh=1e-5,- imatrix=m.imatrix,- )- assert torch.equal(m.weight.data, ref_qdq)- assert torch.equal(m.scale.reshape(-1), ref_scale.reshape(-1))-- def test_batch_splitting_rules(self):- """One setup for every _split_expert_batches rule: gating, expert-name- filtering, shape/act-quant/symmetry segregation."""- q = self._quantizer()-- # gating: off -> inactive; disable_opt_rtn -> inactive- assert self._quantizer(enable_neuqi=False)._expert_search_active() is False- assert self._quantizer(enable_neuqi=True, disable_opt_rtn=True)._expert_search_active() is False-- # non-expert and odd-shaped modules stay single- dense = self._expert("blk.mlp.gate_proj")- odd = self._expert("blk.experts.0.gate_proj", inn=48, group_size=32) # in % g != 0 is fine for grouping- mixed_shape = self._expert("blk.experts.1.gate_proj", inn=64)- batches, singles = q._split_expert_batches([dense, odd, mixed_shape])- assert not batches and {dense, odd, mixed_shape} == set(singles)-- # act quantization needs the per-module wrapper path- m = self._expert("blk.experts.0.gate_proj")- m.act_bits = 8- batches, singles = q._split_expert_batches([m])- assert not batches and singles == [m]-- # same (parent, proj, shape, bits, gs) but different symmetry: not- # mergeable into one stacked call -> both stay single (group of 1)- a = self._expert("blk.experts.0.gate_proj", sym=False)- sym_m = self._expert("blk.experts.1.gate_proj", sym=True)- batches, singles = q._split_expert_batches([a, sym_m])- assert not batches and len(singles) == 2-- def test_oom_returns_only_unwritten(self, monkeypatch):- # R2-2: a mid-batch OOM must leave already-written modules untouched- # and return ONLY the unwritten remainder (per-module fallback must- # never re-quantize a qdq'd weight)- import auto_round.algorithms.quantization.rtn.quantizer as Q- import auto_round.data_type.neuqi as N+ def _assert_same_module(self, got, ref, index):+ ref_w, ref_scale, ref_zp, ref_dt = ref+ assert torch.equal(got.weight.data, ref_w), f"weight mismatch module {index}"+ if isinstance(ref_scale, torch.Tensor):+ assert torch.equal(got.scale, ref_scale), f"scale mismatch module {index}"+ if isinstance(ref_zp, torch.Tensor):+ assert torch.equal(got.zp, ref_zp), f"zp mismatch module {index}"+ assert got.data_type == ref_dt, f"data_type mismatch module {index}"++ def _run(self, sym, imatrix):+ from auto_round.algorithms.quantization.rtn.batched_search import run_batched_rtn_search++ model_serial, mods_serial = self._moe_model(sym=sym, imatrix=imatrix, seed0=0)+ model_batched, mods_batched = self._moe_model(sym=sym, imatrix=imatrix, seed0=0)++ serial = []+ with torch.no_grad():+ for m in mods_serial:+ out = self._wrapper(m).unwrapper({})+ serial.append((out.weight.data.clone(), out.scale, getattr(out, "zp", None), out.data_type))++ staged = [(m.global_name, self._wrapper(m)) for m in mods_batched]+ # pin that the neuqi searches were selected: the wrapper resolves the+ # scheme before any call runs (weight-only write-back leaves the layer's+ # own data_type at "int" in both arms)+ resolved = "opt_rtn_int_sym_neuqi" if sym else "opt_rtn_int_asym"+ assert all(w.data_type == resolved for _n, w in staged)+ run_batched_rtn_search(model_batched, staged)++ for i, m in enumerate(mods_batched):+ self._assert_same_module(m, serial[i], i)++ def test_asym_batched_matches_serial(self):+ self._run(sym=False, imatrix=False)++ def test_sym_batched_matches_serial(self):+ self._run(sym=True, imatrix=False)++ def test_imatrix_weighting_batched_matches_serial(self):+ self._run(sym=False, imatrix=True)++ def test_moe_heuristic_gates_expert_search(self):+ """The staging heuristic decides which modules run a search.++ Expert projections on MoE models skip the optimized search unless the+ user forces it; dense projections and an explicit --enable_opt_rtn both+ keep it on. The staged wrapper records the resolved decision.+ """+ import auto_round.algorithms.quantization.rtn.quantizer as _qmod+ from auto_round.algorithms.quantization.rtn.config import OptimizedRTNConfig+ from auto_round.algorithms.quantization.rtn.quantizer import OptimizedRTNQuantizer- q = self._quantizer()- mods = [self._expert(f"blk.experts.{i}.gate_proj", seed=i) for i in range(3)]- batches, singles = q._split_expert_batches(mods)- assert len(batches) == 1-- calls = []- orig = N.quant_tensor_opt_rtn_asym-- def oom_after_first(weights, *a, **kw):- calls.append(1)- if len(calls) > 1:- raise torch.OutOfMemoryError("simulated")- return orig(weights, *a, **kw)-- monkeypatch.setattr(N, "quant_tensor_opt_rtn_asym", oom_after_first)- # one module per stacked call -> the failure hits mid-batch- monkeypatch.setattr(Q, "_EXPERT_BATCH_MAX_ELEMS", mods[0].weight.numel())- before = mods[0].weight.data.clone()- remaining = q._quantize_expert_batch(batches[0], "cpu")- assert len(remaining) == 2, "modules after the failed chunk must be returned unwritten"- assert remaining == mods[1:]- # the first chunk was written and must NOT be re-quantized later- assert not torch.equal(mods[0].weight.data, before)- assert hasattr(mods[0], "scale") and mods[0].data_type == "opt_rtn_int_asym"- # unwritten modules are untouched- assert not hasattr(mods[1], "scale") and not hasattr(mods[2], "scale")-- def test_act_quant_modules_stay_single(self):- q = self._quantizer()- m = self._expert("blk.experts.0.gate_proj")- m.act_bits = 8 # act quantization needs the per-module wrapper path- batches, singles = q._split_expert_batches([m])- assert not batches and singles == [m]-- def test_sym_key_separates_batches(self):- q = self._quantizer()- a = self._expert("blk.experts.0.gate_proj", sym=False)- s = self._expert("blk.experts.1.gate_proj", sym=True)- batches, singles = q._split_expert_batches([a, s])- # same (parent, proj, shape, bits, gs) but different symmetry: not- # mergeable into one stacked call -> both stay single (group of 1)- assert not batches and len(singles) == 2+ model, mods = self._moe_model(sym=False, imatrix=False, n=1)+ model.blk.mlp = torch.nn.Module()+ dense = self._expert("blk.mlp.gate_proj", sym=False, seed=9)+ model.blk.mlp.gate_proj = dense++ ctx = SimpleNamespace(is_moe_model=True, amp_dtype=torch.float32, model=model, enable_torch_compile=False)+ q = object.__new__(OptimizedRTNQuantizer)+ q.config = OptimizedRTNConfig(bits=4, group_size=32, sym=False, enable_neuqi=True)+ q.config.disable_opt_rtn = False+ q.config.orig_disable_opt_rtn = None # user left the flag unset+ try:+ _qmod.OptimizedRTNQuantizer.model_context = property(lambda self: ctx)+ _qmod.OptimizedRTNQuantizer.compress_context = property(lambda self: ctx)++ w = q._quantize_layer_via_rtn(model.blk.experts[0].gate_proj, defer_search=True)+ assert w.disable_opt_rtn is True, "expert projection on a MoE model must skip the search by default"++ w = q._quantize_layer_via_rtn(dense, defer_search=True)+ assert w.disable_opt_rtn is False, "dense projection keeps the search"++ q.config.orig_disable_opt_rtn = False # user forced --enable_opt_rtn+ w = q._quantize_layer_via_rtn(model.blk.experts[0].gate_proj, defer_search=True)+ assert w.disable_opt_rtn is False, "forced --enable_opt_rtn keeps experts on the search"++ w = q._quantize_layer_via_rtn(dense, disable_opt_rtn=True, defer_search=True)+ assert w.disable_opt_rtn is True, "explicit disable wins everywhere"+ finally:+ for prop in ("model_context", "compress_context"):+ if prop in _qmod.OptimizedRTNQuantizer.__dict__:+ delattr(_qmod.OptimizedRTNQuantizer, prop)class TestImatrixAutoRule:diff --git a/test/unit/test_cpu/quantization/test_one_deep_writer.py b/test/unit/test_cpu/quantization/test_one_deep_writer.pynew file mode 100644index 000000000..728b0e230--- /dev/null+++ b/test/unit/test_cpu/quantization/test_one_deep_writer.py@@ -0,0 +1,117 @@+# Copyright 2025 Intel Corporation+# SPDX-License-Identifier: Apache-2.0+"""Tests for the one-deep background writer used by the shard write/flush."""++import time+import unittest++from auto_round.compressors.orchestrator import _OneDeepWriter+++class TestOneDeepWriter(unittest.TestCase):+ def test_dispatch_runs_and_join_blocks(self):+ w = _OneDeepWriter()+ done = []+ w.dispatch(lambda: done.append(1))+ w.join()+ self.assertEqual(done, [1])+ self.assertIsNone(w._t)++ def test_one_deep_previous_joined_before_next_starts(self):+ w = _OneDeepWriter()+ order = []++ def slow():+ order.append("slow-start")+ time.sleep(0.2)+ order.append("slow-end")++ def fast():+ order.append("fast-start")++ w.dispatch(slow)+ w.dispatch(fast) # must join slow first+ w.join()+ self.assertEqual(order[0], "slow-start")+ self.assertEqual(order[1], "slow-end")+ self.assertEqual(order[2], "fast-start")++ def test_exception_reraised_on_join(self):+ w = _OneDeepWriter()++ def boom():+ raise RuntimeError("writer failed")++ w.dispatch(boom)+ with self.assertRaisesRegex(RuntimeError, "writer failed"):+ w.join()+ # subsequent dispatches still work (state cleared)+ ran = []+ w.dispatch(lambda: ran.append(1))+ w.join()+ self.assertEqual(ran, [1])++ def test_join_without_dispatch_is_noop(self):+ w = _OneDeepWriter()+ w.join() # must not raise+++class TestBackgroundResumeMark(unittest.TestCase):+ """The one-deep discipline keeps mark_block_done's order-assert valid."""++ def _fake_state(self):+ import types++ state = types.SimpleNamespace(completed_blocks=[], calls=[])++ def mark_block_done(block_name, q_input, input_ids):+ expected = ["b0", "b1", "b2"][len(state.completed_blocks)]+ assert block_name == expected, f"out of order: expected {expected}, got {block_name}"+ state.calls.append((block_name, q_input, input_ids))+ state.completed_blocks.append(block_name)++ state.mark_block_done = mark_block_done+ return state++ def test_marks_run_in_order_through_the_writer(self):+ from auto_round.compressors.orchestrator import _OneDeepWriter++ state = self._fake_state()+ w = _OneDeepWriter()+ w.dispatch(lambda: state.mark_block_done("b0", None, "i0"))+ w.dispatch(lambda: state.mark_block_done("b1", None, "i1")) # joins b0 first+ w.dispatch(lambda: state.mark_block_done("b2", None, "i2"))+ w.join()+ self.assertEqual(state.completed_blocks, ["b0", "b1", "b2"])+ self.assertEqual([c[2] for c in state.calls], ["i0", "i1", "i2"])++ def test_worker_exception_surfaces_at_next_dispatch(self):+ from auto_round.compressors.orchestrator import _OneDeepWriter++ state = self._fake_state()+ w = _OneDeepWriter()+ w.dispatch(lambda: state.mark_block_done("b0", None, "i0"))++ def boom():+ raise RuntimeError("resume save failed")++ w.dispatch(boom) # joins b0 (ok), then starts boom+ with self.assertRaisesRegex(RuntimeError, "resume save failed"):+ w.join()+++class TestSnapshotPoolRefs(unittest.TestCase):+ def test_skeleton_frozen_tensors_by_reference(self):+ import torch++ from auto_round.utils.resume import snapshot_pool_refs++ t = torch.zeros(4)+ pool = {"hidden_states": [t, t], "aux": ({"inner": t},)}+ snap = snapshot_pool_refs(pool)+ self.assertIsNot(snap, pool)+ self.assertIsNot(snap["hidden_states"], pool["hidden_states"])+ self.assertIs(snap["hidden_states"][0], t) # tensors passed by ref+ # mutating the original container afterwards must not affect the snap+ pool["hidden_states"].append(torch.ones(4))+ self.assertEqual(len(snap["hidden_states"]), 2)diff --git a/test/unit/test_cpu/quantization/test_pool_placement.py b/test/unit/test_cpu/quantization/test_pool_placement.pynew file mode 100644index 000000000..bbc70c316--- /dev/null+++ b/test/unit/test_cpu/quantization/test_pool_placement.py@@ -0,0 +1,599 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""Unit tests for --calibration_data_device calibration-data placement (policy + routing).++No CUDA required: free-memory probing and device candidates are injected, and the+BlockForwardRunner integration uses meta/cpu device targets to observe routing.+"""++import unittest+from unittest import mock++import torch++from auto_round.algorithms.block_runner import BlockForwardRunner+from auto_round.utils import pool_placement as pp+++def _fake_probe(free_map):+ return lambda d: free_map.get(d)+++class TestSpreadPlan(unittest.TestCase):+ def test_proportional_interleaved(self):+ plan = pp._spread_plan(["a", "b"], [6, 4], 10)+ self.assertEqual(len(plan), 10)+ self.assertEqual(plan.count("a"), 6)+ self.assertEqual(plan.count("b"), 4)+ # interleaved: no two consecutive chunks on the same device when both remain+ self.assertNotEqual(plan[0], plan[1])++ def test_zero_capacity_falls_back_to_devices(self):+ plan = pp._spread_plan(["a"], [0], 5)+ self.assertEqual(plan, ["a"])++ def test_single_device(self):+ plan = pp._spread_plan(["a"], [100], 5)+ self.assertEqual(plan, ["a"] * 5)+++class TestPoolPlacement(unittest.TestCase):+ def test_counts_and_wrap(self):+ p = pp.PoolPlacement(["a", "b"], [5, 5], 4)+ self.assertEqual(p.counts(), {"a": 2, "b": 2})+ # index beyond plan wraps deterministically+ self.assertEqual(p.device_for_index(4), p.device_for_index(0))+++class TestResolvePoolPlacement(unittest.TestCase):+ GB = 2**30++ def _resolve(self, mode="auto", free=None, pool=1 * GB, need=2 * GB, primary="cuda:0", candidates=None):+ free = free if free is not None else {"cuda:0": 20 * self.GB}+ candidates = candidates if candidates is not None else ["cuda:0", "cuda:1", "cuda:2"]+ return pp.resolve_pool_placement(pool, 128, primary, need, candidates, _fake_probe(free), mode=mode)++ def test_off_env_returns_none(self):+ self.assertIsNone(self._resolve(mode="off"))++ def test_cpu_mode_parks_on_host(self):+ plan = self._resolve(mode="cpu")+ self.assertEqual(plan.devices, ["cpu"])+ self.assertEqual(plan.counts(), {"cpu": 128})++ def test_need_estimator_first_principles(self):+ """Need = COMPUTED working allowance (2 batch IO generations + widest+ projection transient, floor-guarded) + reserve; iters>0 adds 14B/param+ of tuning state for candidate-homed parameters only. Pool bytes beyond+ one batch are NOT part of the need (the gates count them separately)."""+ reserve = pp._RESERVE_BYTES+ floor = int(0.125 * 2**30)+ # block with hidden 4 (modal in_features) and widest out 4+ m = torch.nn.Sequential(torch.nn.Linear(4, 4), torch.nn.Linear(4, 4))+ pool = [torch.zeros(8, 4, dtype=torch.float32) for _ in range(2)] # 2 samples of 32 floats+ esize = 4 # fp32 params+ batch_bytes = 2 * 32 * 4 // 2 * 2 # per-chain 256B, batch 2 of 2 -> 256B+ transient = int((32 * 2 / 4) * 4 * esize * 2) # tokens=16, widest=4, x2 buffers+ pool_bytes = 2 * 32 * 4 # one chain, both samples+ expected = max(2 * batch_bytes + transient, floor) + reserve + 2 * pool_bytes # + window term+ need0 = pp.placement_need_bytes(m, pool, 2)+ self.assertEqual(need0, expected)+ # iters=0: identical (no tuning state at zero-shot)+ self.assertEqual(pp.placement_need_bytes(m, pool, 2, iters=0, primary="cuda:0"), need0)+ # degenerate reads floor-guard + window: no block, bare-tensor pool+ self.assertEqual(pp.placement_need_bytes(None, torch.zeros(4), 2), floor + reserve + 2 * 4 * 4)+ # iters>0: +14 B per candidate-homed parameter; peers' params ignored+ n_params = sum(p.numel() for p in m.parameters())+ dev = str(next(m.parameters()).device)+ self.assertEqual(pp.placement_need_bytes(m, pool, 2, iters=20, primary=dev), need0 + n_params * 14)+ self.assertEqual(pp.placement_need_bytes(m, pool, 2, iters=20, primary="cuda:7"), need0)++ def test_working_allowance_scales_with_block_and_pool(self):+ """The allowance is model-derived, not flat: wider projections and+ bigger batches charge more; tiny blocks sit on the floor."""+ m_small = torch.nn.Sequential(torch.nn.Linear(8, 8), torch.nn.Linear(8, 8))+ m_wide = torch.nn.Sequential(torch.nn.Linear(8, 8), torch.nn.Linear(8, 8), torch.nn.Linear(8, 512))+ # structural helpers: widest projection + modal hidden detected+ self.assertEqual(pp._widest_out_and_hidden(m_small), (8, 8))+ self.assertEqual(pp._widest_out_and_hidden(m_wide), (512, 8))+ # real-scale case clears the floor: hidden 4096, widest 4096+ m_big = torch.nn.Sequential(torch.nn.Linear(4096, 4096), torch.nn.Linear(4096, 4096))+ pool = [torch.zeros(4096, 4096) for _ in range(2)]+ esize = 4 # fp32 params+ batch_bytes = 2 * 4096 * 4096 * esize # per-chain pool = both samples+ tokens = 4096 * 2+ transient = int(tokens * 4096 * esize * 2)+ self.assertEqual(+ pp._working_allowance_bytes(m_big, pool, 2), max(2 * batch_bytes + transient, pp._WORKING_FLOOR_BYTES)+ )+ # half batch: smaller IO + transient terms+ pool4 = [torch.zeros(4096, 4096) for _ in range(4)]+ half = pp._working_allowance_bytes(m_big, pool4, 2)+ full = pp._working_allowance_bytes(m_big, pool4, 4)+ self.assertGreater(full, half)+ # tiny block: floor+ self.assertEqual(pp._working_allowance_bytes(None, [torch.zeros(2)], 1), pp._WORKING_FLOOR_BYTES)++ def test_consumer_retargets_single_away_from_cache_primary(self):+ """iters>0: the tune consumer (not the cache primary) is the+ single-device target; the primary demotes to a plain peer."""+ plan = pp.resolve_pool_placement(+ 8 * self.GB,+ 128,+ "cuda:0",+ int(3.5 * self.GB),+ ["cuda:0", "cuda:1", "cuda:2"],+ _fake_probe({"cuda:0": 20 * self.GB, "cuda:1": 12 * self.GB, "cuda:2": 11 * self.GB}),+ consumer="cuda:1",+ )+ self.assertEqual(plan.devices, ["cuda:1"]) # 12 - 3.5 >= 8 fits on the consumer++ def test_consumer_needs_headroom_like_the_primary_did(self):+ """The consumer is charged the working-set need: no room -> spread+ (with the consumer need-charged, the primary NOT charged)."""+ plan = pp.resolve_pool_placement(+ 8 * self.GB,+ 128,+ "cuda:0",+ int(10 * self.GB), # consumer cannot host the pool beside its need+ ["cuda:0", "cuda:1", "cuda:2"],+ _fake_probe({"cuda:0": 20 * self.GB, "cuda:1": 12 * self.GB, "cuda:2": 11 * self.GB}),+ consumer="cuda:1",+ )+ counts = plan.counts()+ # need-floor: the consumer's capacity floors at ~zero, so it gets the+ # smallest share while the primary (now an uncharged peer) leads+ self.assertLess(counts.get("cuda:1", 0), counts.get("cuda:0", 0))+ self.assertLessEqual(counts.get("cuda:1", 0), counts.get("cuda:2", 0))++ def test_occupied_incoming_pool_blocks_fake_single_fit(self):+ """The single-device gate must count pool bytes already resident on the+ candidate -- without it the plan alternates single/spread across blocks+ (a single plan loads the device, the next resolve sees less free)."""+ base = {"cuda:0": 20 * self.GB, "cuda:1": 13 * self.GB, "cuda:2": 11 * self.GB}+ need = int(3.5 * self.GB)+ pool = 8 * self.GB+ free_fit = 13 * self.GB # 13 - 3.5 >= 8: would look like a fit...+ with_occupied = pp.resolve_pool_placement(+ pool, 128, "cuda:0", need, ["cuda:0", "cuda:1", "cuda:2"], _fake_probe(base), consumer="cuda:1"+ )+ self.assertEqual(with_occupied.devices, ["cuda:1"])+ # ...until the incoming input pool (already on the consumer) is charged+ blocked = pp.resolve_pool_placement(+ pool,+ 128,+ "cuda:0",+ need,+ ["cuda:0", "cuda:1", "cuda:2"],+ _fake_probe(base),+ consumer="cuda:1",+ occupied_bytes=free_fit - 0, # charge the resident 13 GiB fully+ )+ # 13 - 3.5 - 13 < 8: single vetoed, consumer capacity floored+ counts = blocked.counts()+ self.assertLessEqual(counts.get("cuda:1", 0), counts.get("cuda:2", 0))+ self.assertLess(counts.get("cuda:1", 0), counts.get("cuda:0", 0))++ def test_occupied_incoming_pool_blocks_primary_single_too(self):+ """Regression (server block-2 OOM): a single plan on the cache primary+ must charge the input pool the PREVIOUS single plan left resident+ there -- otherwise every other block re-singles the loaded device."""+ need = int(2.4 * self.GB)+ pool = 4 * self.GB+ free_ok = pp.resolve_pool_placement(+ pool,+ 128,+ "cuda:0",+ need,+ ["cuda:0", "cuda:1", "cuda:2"],+ _fake_probe({"cuda:0": 13 * self.GB, "cuda:1": 12 * self.GB, "cuda:2": 11 * self.GB}),+ )+ self.assertEqual(free_ok.devices, ["cuda:0"]) # 13 - 2.4 >= 4: fits+ loaded = pp.resolve_pool_placement(+ pool,+ 128,+ "cuda:0",+ need,+ ["cuda:0", "cuda:1", "cuda:2"],+ _fake_probe({"cuda:0": 8 * self.GB, "cuda:1": 12 * self.GB, "cuda:2": 11 * self.GB}),+ occupied_bytes=4 * self.GB, # previous block's single plan left it here+ )+ # 8 - 2.4 - 4 < 4: single vetoed; the primary's spread share is floored+ self.assertLessEqual(loaded.counts().get("cuda:0", 0), loaded.counts().get("cuda:2", 0))++ def test_degenerate_consumer_falls_back_to_primary(self):+ """consumer == primary or non-cuda consumer: primary-first as before."""+ plan = pp.resolve_pool_placement(+ 8 * self.GB,+ 128,+ "cuda:0",+ int(3.5 * self.GB),+ ["cuda:0", "cuda:1"],+ _fake_probe({"cuda:0": 12 * self.GB, "cuda:1": 12 * self.GB}),+ consumer="cuda:0", # same as primary+ )+ self.assertEqual(plan.devices, ["cuda:0"])+ plan2 = pp.resolve_pool_placement(+ 8 * self.GB,+ 128,+ "cuda:0",+ int(3.5 * self.GB),+ ["cuda:0", "cuda:1"],+ _fake_probe({"cuda:0": 12 * self.GB, "cuda:1": 12 * self.GB}),+ consumer="cpu", # non-cuda: ignored+ )+ self.assertEqual(plan2.devices, ["cuda:0"])++ def test_huge_moe_need_still_shards_onto_peers(self):+ """Regression: the need constrains the primary alone, never the fleet.++ A MoE block's need runs to hundreds of GiB under the x7 expert+ multiplier; charging it against total free vetoed every shard plan+ ('insufficient: total - need < pool'), parking the pools on the+ busiest device and OOM-ing the next block.+ """+ plan = self._resolve(+ pool=4 * self.GB,+ need=342 * self.GB,+ free={"cuda:0": 2 * self.GB, "cuda:1": 10 * self.GB, "cuda:2": 10 * self.GB},+ )+ self.assertIsNotNone(plan)+ counts = plan.counts()+ self.assertEqual(counts.get("cuda:0", 0), 0) # need-floor leaves no chunks on the primary+ self.assertGreater(counts.get("cuda:1", 0), 0)+ self.assertGreater(counts.get("cuda:2", 0), 0)+ self.assertEqual(sum(counts.values()), 128)++ def test_zero_peer_capacity_even_over_commit(self):+ # Old contract returned None (-> primary concentration, the worse+ # failure). Now: when the charged headrooms cannot hold the pool,+ # the water-fill spreads the over-commitment EVENLY (same level t+ # below every device's charged headroom) -- the placement that+ # demonstrably completed blocks on the 95%-utilization lane.+ plan = self._resolve(+ pool=4 * self.GB,+ need=2 * self.GB,+ free={"cuda:0": 1 * self.GB, "cuda:1": 1 * self.GB},+ )+ self.assertIsNotNone(plan)+ counts = plan.counts()+ self.assertEqual(+ sum(+ counts.values(),+ ),+ 128,+ )+ self.assertFalse(any(str(d).startswith("cpu") for d in plan.devices))++ def test_cpu_primary_returns_none(self):+ self.assertIsNone(self._resolve(primary="cpu"))++ def test_fits_primary_stays_primary(self):+ plan = self._resolve(pool=4 * self.GB, free={"cuda:0": 20 * self.GB})+ self.assertEqual(plan.devices, ["cuda:0"])+ self.assertEqual(plan.counts(), {"cuda:0": 128})++ def test_margin_blocks_primary_placement(self):+ # 8 GiB pool, 8 free, 2 GiB margin -> only 6 usable on primary: not enough,+ # peers absorb the rest while the margin still protects the primary+ plan = self._resolve(+ pool=8 * self.GB,+ free={"cuda:0": 8 * self.GB, "cuda:1": 10 * self.GB, "cuda:2": 10 * self.GB},+ )+ self.assertEqual(sum(plan.counts().values()), 128)+ self.assertLessEqual(plan.counts().get("cuda:0", 0), 64)++ def test_water_fill_minimizes_max_predicted_usage(self):+ # headroom (8, 10, 30) GiB, pool 8: min-max fills from the deepest+ # device down to a common level -> everything on cuda:2 (level 22),+ # cuda:0/1 untouched: all three end with >= 8 GiB predicted headroom+ # and the fleet's max predicted usage is minimized+ plan = self._resolve(+ pool=8 * self.GB,+ free={"cuda:0": 8 * self.GB, "cuda:1": 10 * self.GB, "cuda:2": 30 * self.GB},+ )+ counts = plan.counts()+ self.assertEqual(counts.get("cuda:2", 0), 128)+ self.assertNotIn("cuda:0", counts)+ self.assertNotIn("cuda:1", counts)+ self.assertEqual(sum(counts.values()), 128)++ def test_activation_charges_shift_pool_off_moe_peers(self):+ # peers homing experts carry routed transients the state charge never+ # priced (measured 3.2 GiB/peer): charging them shrinks peer headroom+ # -> water-fill moves pool bytes onto the (uncharged) entry device+ from auto_round.utils.pool_placement import resolve_pool_placement++ GB = 2**30++ def _plan(act):+ return resolve_pool_placement(+ 8 * GB,+ 128,+ "cuda:0",+ 5 * GB, # working set: single-device rung declines (12-5 < 8)+ ["cuda:0", "cuda:2", "cuda:3"],+ lambda d: {"cuda:0": 12 * GB, "cuda:2": 13 * GB, "cuda:3": 13 * GB}[d],+ peer_state_bytes={"cuda:2": 4 * GB, "cuda:3": 4 * GB},+ activation_bytes=act,+ )++ uncharged = _plan(None)+ charged = _plan({"cuda:0": 1.6 * GB, "cuda:2": 4.3 * GB, "cuda:3": 4.3 * GB})+ cu, cc = uncharged.counts(), charged.counts()+ # uncharged: h = (7, 9, 9) -> level 5.67 -> (1.3, 3.3, 3.3)+ # charged: h = (5.4, 2.7, 2.7) -> level 0.93 -> (4.5, 1.8, 1.8)+ self.assertGreater(cc["cuda:0"], cu["cuda:0"])+ self.assertLess(cc["cuda:2"], cu["cuda:2"])+ self.assertLess(cc["cuda:3"], cu["cuda:3"])+ self.assertEqual(sum(cc.values()), 128)++ def test_water_fill_spreads_when_headrooms_comparable(self):+ # frees (8, 10) GiB with the helper's default need=2 charged to the+ # primary: headroom (6, 10), pool 9 (exceeds the primary alone, so the+ # single-device rung declines): level = (16-9)/2 = 3.5 -> cuda:1 takes+ # 6.5, cuda:0 takes 2.5: both end at exactly 3.5 GiB predicted+ # headroom -- equalized max VRAM by construction+ plan = self._resolve(pool=9 * self.GB, free={"cuda:0": 8 * self.GB, "cuda:1": 10 * self.GB})+ counts = plan.counts()+ self.assertEqual(sum(counts.values()), 128)+ self.assertGreater(counts.get("cuda:1", 0), counts.get("cuda:0", 0))+ self.assertAlmostEqual(plan.level_bytes / self.GB, 3.5, delta=0.05)++ def test_insufficient_capacity_even_over_commit(self):+ # No silent CPU fallback ever; and instead of None (whose caller-side+ # default concentrates the pool on the primary), an over-fleet pool+ # is spread by the water-fill with the over-commitment shared evenly+ # across charged headrooms (charges shape the split in both regimes).+ plan = self._resolve(+ pool=100 * self.GB,+ free={"cuda:0": 8 * self.GB, "cuda:1": 10 * self.GB, "cuda:2": 10 * self.GB},+ )+ self.assertIsNotNone(plan)+ counts = plan.counts()+ self.assertEqual(sum(counts.values()), 128)+ self.assertFalse(any(str(d).startswith("cpu") for d in plan.devices))++ def test_forced_csv_overrides_candidates(self):+ plan = self._resolve(+ mode="cuda:7,cuda:3",+ free={"cuda:7": 10 * self.GB, "cuda:3": 10 * self.GB},+ )+ self.assertEqual(set(plan.devices), {"cuda:7", "cuda:3"})++ def test_forced_bare_indices_get_cuda_prefix(self):+ # accelerate device_map style: "1,2" means cuda:1,cuda:2+ plan = self._resolve(+ mode="1,2",+ free={"cuda:1": 10 * self.GB, "cuda:2": 10 * self.GB},+ )+ self.assertEqual(set(plan.devices), {"cuda:1", "cuda:2"})++ def test_probe_none_skips_device(self):+ plan = self._resolve(+ pool=8 * self.GB,+ free={"cuda:0": 8 * self.GB, "cuda:1": 10 * self.GB, "cuda:2": None},+ )+ self.assertNotIn("cuda:2", plan.counts())+++class TestPoolBytes(unittest.TestCase):+ def test_tensor_bytes_nested(self):+ t = torch.zeros(2048, 4096, dtype=torch.float32)+ pool = {"hidden_states": [t, t], "mask": t}+ self.assertEqual(pp._tensor_bytes(pool), 3 * t.numel() * 4)++ def test_chunk_count(self):+ pool = {"hidden_states": [torch.zeros(1) for _ in range(7)]}+ self.assertEqual(pp._pool_chunk_count(pool), 7)+++class TestCalibDataLine(unittest.TestCase):+ def test_bytes_by_device_counts_referenced_leaves(self):+ a = torch.zeros(10) # 40B+ b = torch.zeros(6) # 24B+ per_dev, total = pp._bytes_by_device({"h": [a, b], "m": a})+ self.assertEqual(per_dev, {"cpu": 104}) # 'm' references a again+ self.assertEqual(total, 104)++ def test_monitor_grammar(self):+ fp = [torch.zeros(1, 64, 64) for _ in range(4)] # 64KiB+ q = [torch.zeros(1, 64, 64) for _ in range(4)]+ plan = pp.PoolPlacement(["cpu", "cpu"], [1, 1], 8)+ line = pp.calib_data_line([fp, q], None, plan, 64 * 64 * 4 * 8, 8, "cpu")+ self.assertIn("'input': 0.00GB", line)+ self.assertIn("'output': 0.00GB", line)+ self.assertIn("'aux': 0.00GB", line)+ self.assertIn("'per_device': {'cpu':", line)+ self.assertNotIn("cuda", line)++ def test_short_device_keys(self):+ self.assertEqual(pp._short_device_key("cuda:3"), "3")+ self.assertEqual(pp._short_device_key("cpu"), "cpu")++ def test_plan_devices_short_keys_and_fallback(self):+ plan = pp.PoolPlacement(["cuda:0", "cuda:1"], [1, 1], 2)+ line = pp.calib_data_line([], None, plan, 4 * 2**30, 2, "cuda:0")+ self.assertIn("'0':", line)+ self.assertIn("'1':", line)+ # no plan -> outputs land on the primary+ line2 = pp.calib_data_line([], None, None, 2**30, 1, "cuda:0")+ self.assertIn("'0': 1.00GB", line2)+++class TestConsolidate(unittest.TestCase):+ class _OnDevice(torch.Tensor):+ # real tensor (bytes/isinstance work) with an overridden device view+ @property+ def device(self):+ return torch.device(self._fake_device)++ def _tensor_on(self, dev):+ t = torch.zeros(2).as_subclass(self._OnDevice)+ t._fake_device = dev+ return t++ def _ctx(self, free_gib, need_gib):+ return (+ mock.patch.object(pp, "placement_need_bytes", return_value=int(need_gib * 2**30)),+ mock.patch(+ "auto_round.utils.device.probe_usable_bytes",+ return_value=int(free_gib * 2**30),+ ),+ )++ def test_local_when_already_on_target(self):+ pool = [self._tensor_on("cuda:0") for _ in range(3)]+ with self._ctx(10, 0)[0], self._ctx(10, 0)[1], mock.patch.object(pp, "_move_pool_to") as mv:+ self.assertEqual(pp.consolidate_pool_onto([pool], "cuda:0", object(), 8), "local")+ mv.assert_not_called()++ def test_consolidated_moves_in_place(self):+ pool = [self._tensor_on("cuda:1"), self._tensor_on("cuda:2")]+ with self._ctx(10, 0)[0], self._ctx(10, 0)[1], mock.patch.object(pp, "_move_pool_to") as mv:+ self.assertEqual(pp.consolidate_pool_onto([pool], "cuda:0", object(), 8), "consolidated")+ mv.assert_any_call(pool, "cuda:0")++ def test_spread_when_not_fitting(self):+ pool = [self._tensor_on("cuda:1")]+ with (+ self._ctx(10, 9)[0],+ self._ctx(10, 9)[1],+ mock.patch.object(pp, "_tensor_bytes", return_value=5 * 2**30),+ mock.patch.object(pp, "_move_pool_to") as mv,+ ):+ self.assertEqual(pp.consolidate_pool_onto([pool], "cuda:0", object(), 8), "spread")+ mv.assert_not_called()++ def test_consolidation_reachable_under_first_principles_need(self):+ """Regression: the old 2x-pool need made attach-time consolidation+ mathematically unreachable (need ~= 2x pool + reserve always exceeded+ any free next to the pools it was gating). With pools counted by the+ gate's own terms, a genuine fit consolidates again."""+ GBi = 2**30+ pool = [torch.zeros(1) for _ in range(4)]+ # 4 GiB of pool tensors, 8 GiB free on the target cuda:0,+ # need 3.5 GiB (working + reserve)+ with (+ mock.patch.object(pp, "_tensor_bytes", return_value=4 * GBi),+ mock.patch.object(pp, "_move_pool_to") as mv,+ mock.patch("auto_round.utils.device.probe_usable_bytes", return_value=8 * GBi),+ mock.patch.object(pp, "placement_need_bytes", return_value=int(3.5 * GBi)),+ ):+ self.assertEqual(pp.consolidate_pool_onto([pool], "cuda:0", object(), 8), "consolidated")+ mv.assert_called()+ # genuinely tight: free - need < pool -> spread, never moved+ with (+ mock.patch.object(pp, "_tensor_bytes", return_value=4 * GBi),+ mock.patch.object(pp, "_move_pool_to") as mv2,+ mock.patch("auto_round.utils.device.probe_usable_bytes", return_value=int(7 * GBi)),+ mock.patch.object(pp, "placement_need_bytes", return_value=int(3.5 * GBi)),+ ):+ self.assertEqual(pp.consolidate_pool_onto([pool], "cuda:0", object(), 8), "spread")+ mv2.assert_not_called()++ def test_non_cuda_target_spread(self):+ self.assertEqual(pp.consolidate_pool_onto([[torch.zeros(1)]], "cpu", object(), 8), "spread")++ def test_empty_is_local(self):+ self.assertEqual(pp.consolidate_pool_onto([None, []], "cuda:0", object(), 8), "local")+++class TestRunnerRouting(unittest.TestCase):+ def _runner(self):+ r = BlockForwardRunner(batch_dim=0, batch_size=2, device="cpu", cache_device="cpu", enable_torch_compile=False)+ r.block_forward = lambda block, hidden, others, amp, amp_dtype, dev, x: hidden+ return r++ def test_placement_routes_per_sample_outputs(self):+ r = self._runner()+ r.pool_placement = pp.PoolPlacement(["meta", "cpu"], [1, 1], 4)+ inputs = [torch.zeros(1, 1) for _ in range(4)]+ outs = r.forward(object(), inputs, {})+ types = [o.device.type for o in outs]+ self.assertEqual(types, ["meta", "cpu", "meta", "cpu"])++ def test_no_placement_keeps_cache_device(self):+ r = self._runner()+ self.assertIsNone(getattr(r, "pool_placement", None))+ inputs = [torch.zeros(1, 1) for _ in range(4)]+ outs = r.forward(object(), inputs, {})+ self.assertTrue(all(o.device.type == "cpu" for o in outs))++ def test_indices_mode_ignores_placement(self):+ # indices-mode concatenates outputs: mixed devices would break the cat,+ # so placement must not apply there+ r = self._runner()+ r.pool_placement = pp.PoolPlacement(["meta", "cpu"], [1, 1], 4)+ inputs = [torch.zeros(1, 1) for _ in range(4)]+ out = r.forward(object(), inputs, {}, indices=torch.tensor([0, 1]))+ self.assertEqual(out.device.type, "cpu")++ def test_mixed_device_batch_gathers_before_cat(self):+ # regression: _select_batch cat'd per-sample tensors on their (mixed)+ # park devices before the compute-device move -> torch.cat crash.+ # Duck-typed tensors (a CPU box has no second real device; meta cannot+ # be copied out of).+ r = self._runner()++ class _FakeT:+ def __init__(self, dev):+ self.device = torch.device(dev)+ self.moved_to = None++ def to(self, target):+ self.moved_to = target+ return torch.zeros(2, 1)++ mixed = [_FakeT("cpu"), _FakeT("meta"), _FakeT("cpu")]+ out = r._gather_same_device(mixed, torch.device("cpu"))+ self.assertTrue(all(t.moved_to == torch.device("cpu") for t in mixed))+ self.assertTrue(all(o.device.type == "cpu" for o in out))++ @unittest.skipUnless(torch.cuda.is_available(), "needs a real second device")+ def test_mixed_device_batch_select_integration(self):+ # per-sample tensors carry a leading batch dim in production+ # ([1, seq, hidden]); _select_batch cats them along batch_dim+ r = self._runner()+ r.device = "cuda:0"+ inputs = [torch.zeros(1, 2, 1, device="cpu")] * 2 + [torch.zeros(1, 2, 1, device="cuda:0")] * 2+ sel = r._select_batch(inputs, {"m": [torch.zeros(1, 2, 1) for _ in range(4)]}, torch.tensor([0, 1, 2, 3]))+ self.assertEqual(sel[0].device.type, "cuda")+ self.assertEqual(sel[0].shape[0], 4) # 4 selected samples, batch dim leading++ def test_structured_values_pass_through_gather(self):+ # diffusion inputs (e.g. freqs) can be nested lists; the gather helper+ # must not assume tensors and crash on .device (CI: prefetched batch)+ r = self._runner()+ vals = [[torch.zeros(1)], [torch.zeros(1)]]+ self.assertIs(r._gather_same_device(vals, torch.device("meta")), vals)++ def test_uniform_device_batch_untouched(self):+ r = self._runner()+ a = torch.zeros(2, 1)+ inputs = [a, a.clone(), a.clone(), a.clone()]+ out = r._gather_same_device(inputs, torch.device("meta"))+ self.assertIs(out[0], a) # same objects, no copies++ def test_explicit_cache_device_call_overrides_placement(self):+ r = self._runner()+ r.pool_placement = pp.PoolPlacement(["meta", "cpu"], [1, 1], 4)+ inputs = [torch.zeros(1, 1) for _ in range(4)]+ outs = r.forward(object(), inputs, {}, cache_device="cpu")+ self.assertTrue(all(o.device.type == "cpu" for o in outs))+++if __name__ == "__main__":+ unittest.main()diff --git a/test/unit/test_cpu/quantization/test_pull_pool_if_fits.py b/test/unit/test_cpu/quantization/test_pull_pool_if_fits.pynew file mode 100644index 000000000..282182ce7--- /dev/null+++ b/test/unit/test_cpu/quantization/test_pull_pool_if_fits.py@@ -0,0 +1,645 @@+# Copyright (c) 2025 Intel Corporation+# SPDX-License-Identifier: Apache-2.0+++"""Unit tests for the iters>0 hot-pool bulk pull gate (``_pull_pool_if_fits``).++The helper decides whether a tune-loop pool moves in bulk onto the device+that reads it every iteration (entry device for inputs, loss device for+references). The gate arithmetic is exercised with tensor/block fakes and a+monkeypatched free-memory probe: no real multi-GPU devices are needed.+"""++import unittest+from unittest import mock++import torch++from auto_round.algorithms.quantization.tune_memory import _pull_pool_if_fits++_GB = 2**30++_GIB = 2**30+++class _FakeTensor: # pylint: disable=too-few-public-methods+ def __init__(self, device, numel, esize=4):+ self.device = torch.device(device)+ self._numel = numel+ self._esize = esize+ self.moved_to = None++ def numel(self):+ return self._numel++ def element_size(self):+ return self._esize++ def to(self, device):+ self.moved_to = torch.device(device)+ self.device = torch.device(device)+ return self+++class _FakeParam(_FakeTensor): # pylint: disable=too-few-public-methods+ pass+++class _FakeBlock: # pylint: disable=too-few-public-methods+ def __init__(self, params):+ self._params = params++ def parameters(self):+ return list(self._params)++ def modules(self):+ return [self]+++def _run(pool, block, free, target="cuda:1", iters=20, label="tune-reference", **kw):+ with mock.patch("auto_round.utils.device.probe_usable_bytes", return_value=free), mock.patch(+ "auto_round.utils.pool_placement._working_allowance_bytes", return_value=int(1.4 * _GIB)+ ):+ return _pull_pool_if_fits(pool, target, block, 8, iters, label, **kw)+++class TestPullPolicyGating(unittest.TestCase):+ """Bulk pulls are a capacity optimization; explicit host parking wins."""++ def test_policies_skip_pull(self):+ from types import SimpleNamespace++ import auto_round.algorithms.quantization.tune_memory as tm+ from auto_round.algorithms.quantization.base import BaseQuantizer++ pool = [_FakeTensor("cpu", numel=1024)]+ called = []+ real = tm._pull_pool_if_fits++ def _spy(*a, **kw):+ called.append(a)+ return real(*a, **kw)++ for cc in (+ SimpleNamespace(low_gpu_mem_usage=True, calibration_data_device="auto"),+ SimpleNamespace(low_gpu_mem_usage=False, calibration_data_device="cpu"),+ ):+ q = object.__new__(BaseQuantizer)+ q._BaseAlgorithm__run_ctx = SimpleNamespace(compress_context=cc, model_context=SimpleNamespace(config=None))+ with mock.patch.object(tm, "_pull_pool_if_fits", _spy):+ out = q.pull_tuning_pool(pool, "cuda:1", _FakeBlock([]), 8, "tune-input")+ self.assertIs(out, pool, f"policy {cc} must leave the pool untouched")+ self.assertEqual(called, []) # capacity gate never even consulted++ def test_default_policy_delegates_to_the_capacity_gate(self):+ from types import SimpleNamespace++ import auto_round.algorithms.quantization.tune_memory as tm+ from auto_round.algorithms.quantization.base import BaseQuantizer++ pool = [_FakeTensor("cpu", numel=1024)]+ cc = SimpleNamespace(low_gpu_mem_usage=False, calibration_data_device="auto")+ q = object.__new__(BaseQuantizer)+ q._BaseAlgorithm__run_ctx = SimpleNamespace(compress_context=cc, model_context=SimpleNamespace(config=None))+ with mock.patch.object(tm, "_pull_pool_if_fits", return_value="delegated") as spy:+ out = q.pull_tuning_pool(pool, "cuda:1", _FakeBlock([]), 8, "tune-input")+ self.assertEqual(out, "delegated")+ spy.assert_called_once()+++class TestPullPoolIfFits(unittest.TestCase):+ def test_moves_when_free_covers_pool_and_state(self):+ # 8-GPU-shaped arithmetic: 4 GiB pool, ~6.4 GiB state on the target.+ pool = [_FakeTensor("cuda:0", numel=_GIB // 4) for _ in range(4)]+ block = _FakeBlock([_FakeParam("cuda:1", numel=int(0.46e9))])+ out = _run(pool, block, free=19.5 * _GIB)+ self.assertEqual(len(out), len(pool))+ self.assertTrue(all(t.moved_to == torch.device("cuda:1") for t in out))++ def test_successful_pull_splices_the_shared_pool_in_place(self):+ # the tune loop rebinds only its local handle; the pool containers+ # (release bookkeeping, snapshots) still hold the ORIGINAL list, so a+ # fresh returned list would keep the source tensors resident next to+ # the pulled copies -- the pull must splice the shared object+ pool = [_FakeTensor("cuda:0", numel=_GIB // 4) for _ in range(4)]+ alias = pool+ block = _FakeBlock([_FakeParam("cuda:1", numel=int(0.46e9))])+ out = _run(pool, block, free=19.5 * _GIB)+ self.assertIs(out, alias) # the same list object, not a copy+ self.assertTrue(all(t.moved_to == torch.device("cuda:1") for t in alias))++ def test_declines_when_state_density_eats_headroom(self):+ # 4-GPU-shaped arithmetic: same pool, ~12.9 GiB state on the target,+ # ~16 GiB free -> reserve alone exceeds free minus pool.+ pool = [_FakeTensor("cuda:0", numel=_GIB // 4) for _ in range(4)]+ block = _FakeBlock([_FakeParam("cuda:1", numel=int(0.92e9))])+ out = _run(pool, block, free=16.1 * _GIB)+ self.assertIs(out, pool)+ self.assertTrue(all(t.moved_to is None for t in pool))++ def test_input_pull_charges_routed_budget(self):+ # the OOMed 4-GPU lane: entry free ~15.9 GiB, pool 4, routed budget+ # 12 GiB (tokens x top_k x hidden x 6, from the pr/streaming formula)+ # -> declines; with no MoE activation cost the same numbers pull+ with mock.patch(+ "auto_round.algorithms.quantization.tune_memory._block_activation_bytes",+ return_value=int(12 * _GIB),+ ):+ pool = [_FakeTensor("cuda:2", numel=_GIB // 4) for _ in range(4)]+ block = _FakeBlock([])+ out = _run(pool, block, free=15.9 * _GIB, target="cuda:0", label="tune-input", charge_activation=True)+ self.assertTrue(all(t.moved_to is None for t in out))+ with mock.patch("auto_round.algorithms.quantization.tune_memory._block_activation_bytes", return_value=0):+ pool2 = [_FakeTensor("cuda:2", numel=_GIB // 4) for _ in range(4)]+ out2 = _run(pool2, block, free=15.9 * _GIB, target="cuda:0", label="tune-input", charge_activation=True)+ self.assertTrue(all(t.moved_to == torch.device("cuda:0") for t in out2))++ def test_stacks_count_wrapper_and_orig_layer_once(self):+ # at tune time named_modules yields the wrapper AND its orig_layer+ # child, each with a same-shape weight -- counting both doubled+ # retention (10.3 GiB charged where the honest charge is ~5.2)+ from types import SimpleNamespace++ import torch.nn as nn++ import auto_round.algorithms.quantization.tune_memory as q++ class _MoeMLP(nn.Module):++ pass++ class _Experts(nn.Module):++ pass++ def _mk_w():+ return SimpleNamespace(numel=lambda: 16, device="cuda:1", nbytes=64, shape=(4, 4))++ blk = nn.Module()+ mlp = _MoeMLP()+ experts = _Experts()+ for i in range(2):+ leaf = nn.Module()+ orig = nn.Module()+ w = _mk_w()+ object.__setattr__(leaf, "weight", w)+ object.__setattr__(orig, "weight", w) # same tensor: id-dedup path+ leaf.orig_layer = orig+ setattr(experts, str(i), leaf)+ # distinct-tensor orig: the .orig_layer name-skip path+ leaf3 = nn.Module()+ orig3 = nn.Module()+ object.__setattr__(leaf3, "weight", _mk_w())+ object.__setattr__(orig3, "weight", _mk_w())+ leaf3.orig_layer = orig3+ experts.extra = leaf3+ mlp.experts = experts+ blk.mlp = mlp++ got = q._grouped_stack_bytes(blk, "cuda:1")+ # 3 logical projections x 16 elems x 6 B = 288 B minimum (plus transient)+ self.assertGreaterEqual(got, 288)+ # double-counted form would charge >= 5 x 16 x 6 = 480 retention-only+ detail = q._grouped_stack_bytes_detail(blk, "cuda:1")+ self.assertLess(detail["retention"], 480)++ def test_stacks_mode_gate_returns_dict_under_linear_loop_env(self):+ # explicit linear_loop env: the detail walk returns the zero DICT+ # (a bare 0 here raised TypeError inside _grouped_stack_bytes and the+ # broad except silently killed the whole activation model)+ from types import SimpleNamespace++ import auto_round.algorithms.quantization.tune_memory as q+ from auto_round import envs++ blk = SimpleNamespace(modules=lambda: iter([]), named_modules=lambda: iter([]))+ with mock.patch.object(envs, "AR_MOE_EXPERTS_IMPL", "linear_loop"):+ detail = q._grouped_stack_bytes_detail(blk, "cuda:1")+ total = q._grouped_stack_bytes(blk, "cuda:1")+ self.assertEqual(detail, {"retention": 0, "transient": 0})+ self.assertEqual(total, 0)++ def test_stacks_follow_config_after_auto_switch(self):+ # after the auto pick switches the run to linear_loop, the gates must+ # charge the LOOP composition (no stacks, routed re-engaged), not the+ # env-stale grouped one+ from types import SimpleNamespace++ import auto_round.algorithms.quantization.tune_memory as q+ from auto_round import envs++ blk = SimpleNamespace(modules=lambda: iter([]), named_modules=lambda: iter([]))+ cfg = type("C", (), {})()+ cfg._experts_implementation = "linear_loop"+ with mock.patch.object(envs, "AR_MOE_EXPERTS_IMPL", "auto"):+ self.assertEqual(q._grouped_stack_bytes(blk, "cuda:1", config=cfg), 0)++ def test_shared_experts_not_charged_as_routed(self):+ # shared experts are plain modules outside the dispatch; stacking or+ # routing charges on them are phantom bytes+ from types import SimpleNamespace++ import torch.nn as nn++ import auto_round.algorithms.quantization.tune_memory as q++ class _MoeMLP(nn.Module):++ pass++ class _Experts(nn.Module):++ pass++ blk = nn.Module()+ mlp = _MoeMLP()+ experts = _Experts()+ shared = _Experts()+ for i in range(2):+ leaf = nn.Module()+ object.__setattr__(+ leaf,+ "weight",+ SimpleNamespace(numel=lambda: 16, device="cuda:1", nbytes=64, shape=(4, 4)),+ )+ setattr(experts, str(i), leaf)+ shared_leaf = nn.Module()+ object.__setattr__(+ shared_leaf, "weight", SimpleNamespace(numel=lambda: 16, device="cuda:1", nbytes=64, shape=(4, 4))+ )+ shared.gate_proj = shared_leaf+ mlp.experts = experts+ mlp.shared_expert = shared+ blk.mlp = mlp++ got = q._grouped_stack_bytes(blk, "cuda:1")+ # only the two routed leaves: 2 x 16 x 6 = 192 B minimum+ self.assertGreaterEqual(got, 192)+ detail = q._grouped_stack_bytes_detail(blk, "cuda:1")+ self.assertLess(detail["retention"], 192 + 192) # shared would add 96 more++ def test_routed_recorder_self_removes_only_on_record(self):+ # a miss (non-dispatch arg shapes) must NOT disarm the recorder;+ # a successful natural dispatch records and removes the hook+ import torch+ import torch.nn as nn++ import auto_round.algorithms.quantization.tune_memory as q++ class _MoeMLP(nn.Module):++ pass++ class _HYV3Experts(nn.Module): # no num_experts, not a ModuleList++ def forward(self, *args):+ return args++ blk = nn.Module()+ mlp = _MoeMLP()+ experts = _HYV3Experts()+ mlp.experts = experts+ blk.mlp = mlp++ q._ensure_routed_shape_recorders_(blk)+ self.assertTrue(experts._routed_rec_handles_, "recorder must attach on the HYV3-style container")++ # miss: two tensors but index ndim 0 -> no record, hook stays+ experts(torch.zeros(2, 4), torch.zeros(()))+ self.assertFalse(hasattr(experts, "_routed_shape_rec_"))+ self.assertTrue(experts._routed_rec_handles_)++ # natural dispatch: (hidden [B,T,H], index [N,K]) -> record + remove+ experts(torch.zeros(2, 4, 8), torch.zeros(16, 8))+ self.assertEqual(experts._routed_shape_rec_, (8, 128))+ self.assertFalse(experts._routed_rec_handles_)++ def test_routed_recorder_skips_leaf_projections_and_wrappers(self):+ # The ancestor walk inside the container check matched EVERY+ # expert-named module, so leaf projections received a pre-hook that+ # can never record (their forward sees per-row activations only),+ # never self-removes, and lingers for the whole block -- it then+ # disqualifies the projection in the grouped-experts support gate and+ # every tune iteration falls back to the per-expert linear_loop.+ import torch.nn as nn++ import auto_round.algorithms.quantization.tune_memory as q++ class _MoeMLP(nn.Module):++ pass++ class _HYV3Experts(nn.Module): # no num_experts, not a ModuleList++ def forward(self, *args):+ return args++ class _WrappedLinear(nn.Module): # tune wrapper shape (orig_layer child)++ pass++ blk = nn.Module()+ mlp = _MoeMLP()+ experts = _HYV3Experts()+ expert0 = nn.Module()+ expert0.up_proj = nn.Linear(4, 4) # leaf projection: excluded+ expert0.down_proj = _WrappedLinear() # wrapped projection: excluded+ expert0.down_proj.orig_layer = nn.Linear(4, 4)+ experts._modules["0"] = expert0+ mlp.experts = experts+ blk.mlp = mlp++ q._ensure_routed_shape_recorders_(blk)++ # container keeps its recorder (the documented contract)+ self.assertTrue(experts._routed_rec_handles_, "recorder must attach on the MoE container")+ # leaves carry NO hook: they could never record, and a lingering+ # pre-hook there fails the grouped support gate on wrapped blocks+ self.assertFalse(expert0.up_proj._forward_pre_hooks, "leaf projection must stay hook-free")+ self.assertFalse(getattr(expert0.up_proj, "_routed_rec_handles_", []))+ self.assertFalse(expert0.down_proj._forward_pre_hooks, "tune wrapper must stay hook-free")+ self.assertFalse(expert0.down_proj.orig_layer._forward_pre_hooks, "orig layer must stay hook-free")++ # the container still records from a natural dispatch and self-removes+ experts(torch.zeros(2, 4, 8), torch.zeros(16, 8))+ self.assertEqual(experts._routed_shape_rec_, (8, 128))+ self.assertFalse(experts._routed_rec_handles_)++ def test_logical_state_walk_dedups_wrapper_values(self):+ # real-structure form of the a2414b42 fix: a module with a .params+ # dict carrying an fp32 value PLUS the original weight must be+ # charged once (14 B logical), not twice+ import torch+ import torch.nn as nn++ import auto_round.algorithms.quantization.tune_memory as q++ blk = nn.Module()+ lin = nn.Linear(4, 4) # weight 16 + bias 4 = 20 elems on cpu+ wrapper = nn.Module()+ wrapper.value = nn.Parameter(torch.zeros(4, 4)) # registered fp32 value+ wrapper.params = {"value": wrapper.value} # same object, as the real wrappers do+ blk.lin = lin+ blk.wrap = wrapper+ got = q._logical_state_by_device(blk)+ # deduped: the registered value is identified by identity via .params+ # and excluded; only the original 20 elems carry the 14 B charge+ self.assertEqual(got.get("cpu", 0), 20 * 14)+ # without dedup the walk would see 36 elems (504 bytes)+ self.assertLess(got.get("cpu", 0), 36 * 14)++ def test_routed_budget_dropped_when_grouped_stacks_present(self):+ # grouped mode builds no per-expert route caches (linear_loop+ # calibration); charging routed x6 ALONGSIDE stacks double-charged+ # the working 5x3090 lane and falsely switched it to linear_loop+ from types import SimpleNamespace++ import auto_round.algorithms.quantization.tune_memory as q+ import auto_round.utils.device as dev_mod++ blk = SimpleNamespace(modules=lambda: iter([SimpleNamespace(num_experts=8)]))+ est = ({}, 0.0, 0.0, 0.0, {"cuda:1": 1.0, "cuda:0": 0.5}, {"cuda:1": 24})+ with (+ mock.patch.object(dev_mod, "estimate_tuning_block_mem", return_value=est),+ mock.patch.object(q, "_routed_budget_bytes", return_value=8 * _GB),+ mock.patch.object(+ q, "_grouped_stack_bytes", side_effect=lambda b, d, config=None: 2 * _GB if d == "cuda:1" else 0+ ),+ ):+ got = q._activation_bytes_by_device(blk, [], 8, None)+ self.assertIn("cuda:1", got)+ # with routed charged it would be max(1, 8) + 2 = 10 GiB; honest = 1 + 2+ self.assertLess(got["cuda:1"], 4 * _GB)+ self.assertGreaterEqual(got["cuda:1"], 3 * _GB)++ def test_grouped_stacks_detect_hy3_container(self):+ # HYV3Experts carries NEITHER num_experts NOR ModuleList -- the MoE+ # marker sits on an ancestor. The old container walk returned 0 stacks+ # on the real lane, silently disabling the activation charge and the+ # auto linear_loop pick (4x3090 grouped OOM with no switch).+ from types import SimpleNamespace++ import torch.nn as nn++ import auto_round.algorithms.quantization.tune_memory as q++ class _MoeMLP(nn.Module):++ pass++ class _HYV3Experts(nn.Module): # no num_experts, not a ModuleList++ pass++ blk = nn.Module()+ mlp = _MoeMLP()+ experts = _HYV3Experts()+ for i in range(2):+ leaf = nn.Linear(4, 4)+ object.__setattr__(+ leaf, "weight", SimpleNamespace(numel=lambda: 16, device="cuda:1", nbytes=32, shape=(4, 4))+ )+ setattr(experts, str(i), leaf)+ mlp.experts = experts+ blk.mlp = mlp++ got = q._grouped_stack_bytes(blk, "cuda:1")+ self.assertGreater(got, 0)+ # retention 2 leaves x 16 elems x 6 B = 192 B minimum (plus transient)+ self.assertGreaterEqual(got, 192)+ # no expert leaves homed elsewhere+ self.assertEqual(q._grouped_stack_bytes(blk, "cuda:0"), 0)++ def test_activation_charge_is_per_device(self):+ # fwd/bwd executes on EVERY device the block spans: each expert's+ # routed-row caches land on the expert's WEIGHT HOME. The routed+ # budget must split by homed-expert count, the shared/dense modules+ # charge their own home -- not everything onto one scalar.+ from types import SimpleNamespace++ import torch.nn as nn++ import auto_round.algorithms.quantization.tune_memory as q++ GB = 2**30++ def _dev_linear(in_f, out_f, dev):+ m = nn.Linear(in_f, out_f)+ # bypass nn.Module's Parameter-only assignment: __dict__ shadow+ object.__setattr__(m, "weight", SimpleNamespace(nbytes=in_f * out_f * 2, device=dev))+ m.orig_layer = m+ m.bits = 4+ return m++ class _MoeMLP(nn.Module): # class name carries the MoE marker (hy3 HYV3MoeMLP)++ pass++ blk = nn.Module()+ # 6 experts over 3 peers (2 each), shared MLP on cuda:0 (hy3 shape)+ mlp = _MoeMLP()+ mlp.experts = nn.ModuleList([_dev_linear(4096, 1536, f"cuda:{1 + i % 3}") for i in range(6)])+ mlp.experts.num_experts = 6+ blk.mlp = mlp+ blk.shared = _dev_linear(4096, 13312, "cuda:0")+ # the ratio walk reads num_experts off the (model) config+ config = type("C", (), {"num_experts_per_tok": 8, "num_experts": 192})()+ ref = torch.zeros(1, 2048, 4096) # fp32: hidden_bytes 16384++ by_dev = q._activation_bytes_by_device(blk, [ref], 8, config)+ self.assertIsNotNone(by_dev)+ # routed total = 8*2048 tokens * top_k 8 * 16384 B * 6 = 12.0 GiB,+ # split by 2/6 homed experts per peer+ for peer in ("cuda:1", "cuda:2", "cuda:3"):+ self.assertAlmostEqual(by_dev[peer] / GB, 12.0 / 3, delta=0.1)+ # cuda:0 hosts only the shared MLP: estimator term, no routed slice+ self.assertAlmostEqual(by_dev["cuda:0"] / GB, 16384 * 13312 * 4 * 2 / GB, delta=0.1)++ def test_routed_budget_formula_reproduces_measured_lane(self):+ # hy3: batch 8 x seq 2048 x top_k 8 x hidden 4096 x fp32 x 6 ~= 12.0 GiB+ # (measured loop retention: 12.7 GiB of batch cats + routed caches)+ import torch.nn as nn++ import auto_round.algorithms.quantization.tune_memory as q++ class _Experts(nn.Module): # routed container (hy3 mlp.experts)+ num_experts = 192++ ref = torch.zeros(1, 2048, 4096) # fp32 pool sample+ block = nn.Sequential(_Experts(), nn.Linear(4, 4))+ config = type("C", (), {"num_experts_per_tok": 8})()+ got = q._block_activation_bytes(block, [ref], 8, config)+ self.assertAlmostEqual(got / _GIB, 12.0, delta=0.05)++ def test_recorded_dispatch_shapes_beat_missing_config(self):+ # config absent + module attrs absent -> recorded (top_k, rows) decides+ import torch.nn as nn++ import auto_round.algorithms.quantization.tune_memory as q++ class _Experts(nn.Module):+ num_experts = 192++ exp = _Experts()+ exp._routed_shape_rec_ = (8, 8 * 2048 * 8) # seen at batch 8, seq 2048+ block = nn.Sequential(exp)+ ref = torch.zeros(1, 2048, 4096)+ got = q._block_activation_bytes(block, [ref], 8, config=None)+ self.assertAlmostEqual(got / _GIB, 12.0, delta=0.05)++ def test_estimator_and_routed_composed_by_max(self):+ # a big shared expert (plain module) makes the estimator term win;+ # routed alone would undercharge it -- max covers both+ import torch.nn as nn++ import auto_round.algorithms.quantization.tune_memory as q++ class _Experts(nn.Module):+ num_experts = 192++ class _Shared(nn.Module): # plain shared MLP, full-token width+ def __init__(self):+ super().__init__()+ self.gate_proj = nn.Linear(4096, 13312)++ exp = _Experts()+ exp.gate_proj = nn.Linear(4096, 1536)+ block = nn.Sequential(exp, _Shared())+ block.config = type("C", (), {"num_experts_per_tok": 8})()+ # mark them quantizable-ish for the estimator's check_to_quantized+ for m in (exp.gate_proj, block[1].gate_proj):+ m.orig_layer = m+ m.bits = 4+ m.act_bits = 16+ m.group_size = 128+ ref = torch.zeros(1, 2048, 4096)+ got = q._block_activation_bytes(block, [ref], 8, block.config)+ routed = 8 * 2048 * 8 * 4096 * 4 * 6 # 12 GiB+ # shared 13312-wide gate at full tokens x2 grads ~ 1.56 GiB + expert+ # module output... estimator path runs the real estimator; assert the+ # composition never returns less than the routed term+ self.assertGreaterEqual(got, routed)++ def test_state_charged_only_for_params_on_target(self):+ pool = [_FakeTensor("cuda:0", numel=_GIB // 4)]+ block = _FakeBlock([_FakeParam("cuda:2", numel=int(4 * _GIB))])+ out = _run(pool, block, free=7 * _GIB)+ # peers' state is not charged: 7 - (1.4 + 0.5) >= 4 GiB pool bytes+ self.assertTrue(all(t.moved_to == torch.device("cuda:1") for t in out))++ def test_already_local_pool_is_noop(self):+ pool = [_FakeTensor("cuda:1", numel=_GIB // 4)]+ block = _FakeBlock([])+ out = _run(pool, block, free=0) # probe value irrelevant+ self.assertIs(out, pool)+ self.assertTrue(all(t.moved_to is None for t in pool))++ def test_non_list_pool_untouched(self):+ block = _FakeBlock([])+ out = _run({"a": 1}, block, free=100 * _GIB)+ self.assertEqual(out, {"a": 1})++ def test_probe_failure_keeps_sharded(self):+ pool = [_FakeTensor("cuda:0", numel=_GIB // 4)]+ block = _FakeBlock([])+ # free=None -> decline path (no move); helper never raises+ with mock.patch("auto_round.utils.device.probe_usable_bytes", side_effect=RuntimeError("no cuda")), mock.patch(+ "auto_round.utils.pool_placement._working_allowance_bytes", return_value=0+ ):+ out = _pull_pool_if_fits(pool, "cuda:1", block, 8, 20, "tune-reference")+ self.assertIs(out, pool)+ self.assertTrue(all(t.moved_to is None for t in pool))+++class TestTuningStateBytes(unittest.TestCase):+ def test_wrapper_params_excluded_from_state(self):+ import torch.nn as nn++ block = nn.Linear(4, 4) # 16 + 4 params, any device (cpu here)+ # wrapper-style tuning tensor: same numel as the weight, registered+ # nowhere but present in a .params dict; identity-excluded from the count+ value = torch.zeros_like(block.weight)+ block.params = {"value": value}+ from auto_round.algorithms.quantization.tune_memory import _tuning_state_bytes++ # cpu target: logical params = 20 (weight 16 + bias 4), value excluded+ self.assertEqual(_tuning_state_bytes(block, "cpu"), 20 * 14)+++class TestBaseQuantizerHooks(unittest.TestCase):+ """The base-quantizer policy hooks delegate to tune_memory with self context."""++ def test_hooks_delegate_to_tune_memory(self):+ import auto_round.algorithms.quantization.tune_memory as tm+ from auto_round.algorithms.quantization.base import BaseQuantizer+ from auto_round.algorithms.quantization.rtn.config import RTNConfig++ class _Q(BaseQuantizer):+ def __init__(self):+ super().__init__(RTNConfig())++ q = _Q()+ q.iters = 7+ block = torch.nn.Linear(2, 2)+ seen = {}++ def fake_adapt(block, tensors, batch_size, iters, config, model):+ seen["adapt"] = (iters, block)++ def fake_pull(pool, target_dev, blk, batch_size, iters, label, charge_activation, config):+ seen["pull"] = (iters, label, charge_activation)+ return "moved"++ with (+ mock.patch.object(tm, "_maybe_auto_linear_loop_for_tuning", side_effect=fake_adapt),+ mock.patch.object(tm, "_pull_pool_if_fits", side_effect=fake_pull),+ ):+ q.maybe_adapt_moe_implementation(block, [], 8)+ out = q.pull_tuning_pool([1], "cuda:0", block, 8, "test] pool", charge_activation=False)+ self.assertEqual(seen["adapt"], (7, block))+ self.assertEqual(seen["pull"], (7, "test] pool", False))+ self.assertEqual(out, "moved")+++if __name__ == "__main__":+ unittest.main()diff --git a/test/unit/test_cpu/quantization/test_release_pool_inplace.py b/test/unit/test_cpu/quantization/test_release_pool_inplace.pynew file mode 100644index 000000000..031314d5c--- /dev/null+++ b/test/unit/test_cpu/quantization/test_release_pool_inplace.py@@ -0,0 +1,40 @@+# Copyright 2025 Intel Corporation+# SPDX-License-Identifier: Apache-2.0+"""Tests for the in-place calibration-pool release (composer)."""++import unittest++import torch++from auto_round.algorithms.composer import _release_pool_inplace+++class TestReleasePoolInplace(unittest.TestCase):+ def test_list_pool_entries_nulled_and_shared_ref_sees_it(self):+ pool = [torch.zeros(2), torch.zeros(2)]+ shared = pool # the orchestrator's input_ids view+ _release_pool_inplace(pool)+ self.assertEqual(pool, [None, None])+ self.assertIs(shared, pool)+ self.assertEqual(shared, [None, None])++ def test_dict_of_lists_recurces(self):+ pool = {"hidden_states": [torch.zeros(2)], "other": {"nested": [torch.zeros(2)]}}+ _release_pool_inplace(pool)+ self.assertEqual(pool["hidden_states"], [None])+ self.assertEqual(pool["other"]["nested"], [None])+ self.assertEqual(list(pool.keys()), ["hidden_states", "other"]) # structure preserved++ def test_tuple_skipped_immutable(self):+ pool = (torch.zeros(2), torch.zeros(2))+ _release_pool_inplace(pool)+ # tuples cannot be mutated in place; tensors must remain untouched+ self.assertIsInstance(pool[0], torch.Tensor)+ self.assertIsInstance(pool[1], torch.Tensor)++ def test_mixed_structure(self):+ pool = {"a": [torch.zeros(1), (torch.zeros(1),)], "b": "scalar"}+ _release_pool_inplace(pool)+ self.assertEqual(pool["a"][0], None)+ self.assertIsNone(pool["a"][1]) # slot dropped wholesale; tuple internals moot+ self.assertEqual(pool["b"], "scalar")diff --git a/test/unit/test_cpu/quantization/test_search_dispatch.py b/test/unit/test_cpu/quantization/test_search_dispatch.pynew file mode 100644index 000000000..610072819--- /dev/null+++ b/test/unit/test_cpu/quantization/test_search_dispatch.py@@ -0,0 +1,793 @@+# Copyright (c) 2026 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Tests for the batched-search dispatch helpers (grouping, per-device execution)."""++import threading+import unittest+from unittest import mock++import torch++import auto_round.algorithms.quantization.search_dispatch as search_dispatch+from auto_round.algorithms.quantization.search_dispatch import group_items_by_device, run_items_by_device+++def _linear(out=8, inn=8):+ m = torch.nn.Linear(inn, out, bias=False)+ m.bits = 4 # pass check_to_quantized+ return m+++class TestGroupItemsByDevice(unittest.TestCase):+ def test_groups_by_device_string(self):+ items = [("a", "cuda:0"), ("b", "cuda:1"), ("c", "cuda:0")]+ groups = group_items_by_device(items, device_of=lambda item: item[1])+ self.assertEqual([k for k in groups], ["cuda:0", "cuda:1"])+ self.assertEqual([(i, it) for i, it in groups["cuda:0"]], [(0, ("a", "cuda:0")), (2, ("c", "cuda:0"))])+ self.assertEqual([(i, it) for i, it in groups["cuda:1"]], [(1, ("b", "cuda:1"))])++ def test_empty_items(self):+ self.assertEqual(list(group_items_by_device([], device_of=lambda it: "cpu").items()), [])++ def test_missing_device_falls_back_to_none_bucket(self):+ items = [("a", None), ("b", "cuda:0")]+ groups = group_items_by_device(items, device_of=lambda item: item[1], none_key="shared")+ self.assertIn("shared", groups)+ self.assertIn("cuda:0", groups)+++class TestRunItemsByDevice(unittest.TestCase):+ def test_runs_all_items_and_records_devices(self):+ items = [f"m{i}" for i in range(6)]+ # 3 fake devices, 2 items each+ device_of = lambda it: f"cuda:{int(it[1:]) % 3}" # noqa: E731+ groups = group_items_by_device(items, device_of=device_of)+ seen = []+ lock = threading.Lock()++ def fn(_idx, item):+ with lock:+ seen.append((item, threading.current_thread().name))++ run_items_by_device(groups, fn)+ self.assertEqual(sorted(s[0] for s in seen), items)+ # items on different devices ran on different threads+ threads = {s[0]: s[1] for s in seen}+ self.assertNotEqual(threads["m0"], threads["m1"])++ def test_exception_propagates_fail_visible(self):+ items = ["a", "b"]+ groups = group_items_by_device(items, device_of=lambda it: "cpu")++ def fn(_idx, item):+ if item == "a":+ raise RuntimeError("boom")++ with self.assertRaisesRegex(RuntimeError, "boom"):+ run_items_by_device(groups, fn)++ def test_single_group_runs_inline(self):+ # one device -> no thread spawn; fn runs on the calling thread+ items = ["a", "b"]+ groups = group_items_by_device(items, device_of=lambda it: "cpu")+ caller = threading.current_thread().name+ seen = []+ run_items_by_device(groups, lambda _idx, it: seen.append(threading.current_thread().name))+ self.assertEqual(seen, [caller, caller])++ def test_cuda_device_ctx_applied(self):+ recorded = []+ real_ctx = torch.cuda.device++ class FakeCtx:+ def __init__(self, dev):+ recorded.append(str(dev))++ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ items = ["a", "b"]+ groups = group_items_by_device(items, device_of=lambda it: "cuda:0" if it == "a" else "cuda:1")+ with (+ mock.patch.object(torch.cuda, "is_available", return_value=True),+ mock.patch.object(torch.cuda, "device", FakeCtx),+ ):+ run_items_by_device(groups, lambda _idx, it: None, use_cuda_ctx=True)+ self.assertEqual(sorted(recorded), ["cuda:0", "cuda:1"]) # one ctx per device group+++class TestRtnSearchShard(unittest.TestCase):+ def test_optimized_rtn_stages_into_batched_driver(self):+ from auto_round.algorithms.quantization.rtn.quantizer import OptimizedRTNQuantizer++ q = object.__new__(OptimizedRTNQuantizer)+ staged_seen = []+ # 'model' is a read-only property; the patched driver ignores it anyway++ def fake_via_rtn(self_, m, disable_opt_rtn=None, defer_search=False):+ assert defer_search is True+ staged_seen.append((getattr(m, "global_name", None), m))+ return "wrapper"++ block = torch.nn.Module()+ for i in range(3):+ m = _linear()+ m.name = f"m{i}"+ m.global_name = f"m{i}"+ setattr(block, f"m{i}", m)++ with (+ mock.patch.object(type(q), "_quantize_layer_via_rtn", fake_via_rtn),+ mock.patch.object(type(q), "model", torch.nn.Module()),+ mock.patch(+ "auto_round.algorithms.quantization.rtn.batched_search.run_batched_rtn_search",+ side_effect=lambda model, staged: staged_seen.extend([]) or [],+ ) as drv,+ ):+ q.quantize_block(block, None, None, None, None, None)+ self.assertEqual(drv.call_count, 1)+ self.assertEqual([n for n, _m in staged_seen], ["m0", "m1", "m2"])++ def test_single_device_runs_serial(self):+ from auto_round.algorithms.quantization.rtn.quantizer import OptimizedRTNQuantizer++ q = object.__new__(OptimizedRTNQuantizer)+ caller = threading.current_thread().name+ calls = []+ q.quantize_layer_outside_block = lambda m: calls.append(threading.current_thread().name)++ block = torch.nn.Module()+ m = _linear()+ m.name = "m0"+ m.global_name = "m0"+ m.tuning_device = "cpu"+ block.m0 = m+ # strict serial baseline = batching AND multigpu spreading both off;+ # batching-off alone now spreads per-module searches (see the+ # quadrant test below)+ with (+ mock.patch.object(search_dispatch, "batched_search_disabled", return_value=True),+ mock.patch.object(search_dispatch, "cross_device_search_disabled", return_value=True),+ ):+ q.quantize_block(block, None, None, None, None, None)+ self.assertEqual(calls, [caller])++ def test_batching_off_spreads_per_module_when_multigpu_on(self):+ """AR_DISABLE_BATCHED_SEARCH alone no longer pins everything to the+ home device: the searches stay PER-MODULE (no stacked row sharing)+ but route through the staged executor so idle devices can borrow+ them."""+ from auto_round.algorithms.quantization.rtn import batched_search+ from auto_round.algorithms.quantization.rtn.quantizer import OptimizedRTNQuantizer++ q = object.__new__(OptimizedRTNQuantizer)+ block = torch.nn.Module()+ m = _linear()+ m.name = "m0"+ m.global_name = "m0"+ m.tuning_device = "cpu"+ block.m0 = m+ seen = {}++ class _W: # minimal deferred wrapper: the spy finishes it++ def _run_deferred_search_now(self):+ pass++ q._quantize_layer_via_rtn = lambda layer, defer_search=False: _W()+ seen_run = {}++ def _spy_run(model, staged, max_batch=None):+ seen_run["max_batch"] = max_batch+ seen_run["n"] = len(staged)+ for name, w in staged: # finish the deferred wrappers+ w._run_deferred_search_now()+ return True++ with (+ mock.patch.object(batched_search, "run_batched_rtn_search", side_effect=_spy_run),+ mock.patch.object(search_dispatch, "batched_search_disabled", return_value=True),+ mock.patch.object(search_dispatch, "cross_device_search_disabled", return_value=False),+ mock.patch.object(type(q), "model", new_callable=mock.PropertyMock),+ ):+ q.quantize_block(block, None, None, None, None, None)+ self.assertEqual(seen_run.get("max_batch"), 1) # singleton chunks: zero stacking+ self.assertGreaterEqual(seen_run.get("n", 0), 1)+++class TestOomCensus(unittest.TestCase):+ def test_context_manager_plugs_anywhere_and_reraises(self):+ from auto_round.utils.oom import oom_census++ with (+ mock.patch("auto_round.utils.oom.dump_oom_tensor_census_") as census,+ self.assertRaisesRegex(torch.OutOfMemoryError, "boom"),+ oom_census("surgical frame"),+ ):+ raise torch.OutOfMemoryError("boom")+ census.assert_called_once_with("surgical frame")++ def test_context_manager_passes_non_oom_through_silently(self):+ from auto_round.utils.oom import oom_census++ with (+ mock.patch("auto_round.utils.oom.dump_oom_tensor_census_") as census,+ self.assertRaisesRegex(ValueError, "other"),+ oom_census("frame"),+ ):+ raise ValueError("other")+ census.assert_not_called()++ def test_global_hook_fires_on_uncaught_oom(self):+ import sys+ import threading++ import auto_round.utils.oom as oom_mod++ # The latch and the excepthooks are process-global: an earlier test in+ # the same process (e.g. the model-free pipeline installs the hook for+ # real) must not decide this test's outcome. Snapshot the state, start+ # from pristine hooks, and restore exactly what was there before.+ self.addCleanup(setattr, sys, "excepthook", sys.excepthook)+ self.addCleanup(setattr, threading, "excepthook", threading.excepthook)+ self.addCleanup(setattr, oom_mod, "_OOM_HOOK_INSTALLED", oom_mod._OOM_HOOK_INSTALLED)+ oom_mod._OOM_HOOK_INSTALLED = False+ sys.excepthook = sys.__excepthook__+ threading.excepthook = threading.__excepthook__++ installed = oom_mod.install_oom_census_hook()+ self.assertFalse(oom_mod.install_oom_census_hook()) # idempotent+ with mock.patch.object(oom_mod, "dump_oom_tensor_census_") as census:+ try:+ raise torch.OutOfMemoryError("boom")+ except torch.OutOfMemoryError:+ sys.excepthook(*sys.exc_info())+ self.assertTrue(installed)+ self.assertEqual(census.call_count, 1)++ def test_symbolic_dims_and_bad_tensors_do_not_kill_census(self):+ import auto_round.utils.oom as oom_mod++ class UnhashableDim:+ def __int__(self):+ raise TypeError("cannot convert SymInt to int")++ def __hash__(self):+ raise TypeError("unhashable")++ class SymishTensor(torch.Tensor):+ pass++ t = torch.randn(4, 4)+ with mock.patch.object(type(t), "shape", new_callable=lambda *a: property(lambda self: (UnhashableDim(),))):+ groups = oom_mod._group_tensors_by_shape([t])+ self.assertEqual(groups, ([], 0)) # cpu tensor excluded; symbolic shape did not raise++ class ExplodingTensor:+ pass++ groups = oom_mod._group_tensors_by_shape([ExplodingTensor(), torch.randn(4, 4)])+ self.assertEqual(groups, ([], 0))++ def test_cpu_tensors_excluded_from_census_groups(self):+ # cpu-only box: grouping must not count cpu (or meta) tensors+ import auto_round.utils.oom as oom_mod++ t = torch.randn(4, 4)+ groups = oom_mod._group_tensors_by_shape([t])+ self.assertEqual(groups, ([], 0))++ def test_message_based_oom_triggers_census(self):+ # HPU-class OOMs surface as RuntimeError("... out of memory ...")+ from auto_round.utils.oom import oom_census++ with (+ mock.patch("auto_round.utils.oom.dump_oom_tensor_census_") as census,+ self.assertRaisesRegex(RuntimeError, "Out of Memory in HPU"),+ oom_census("hpu frame"),+ ):+ raise RuntimeError("Out of Memory in HPU allocator")+ census.assert_called_once_with("hpu frame")++ def test_plain_runtime_error_does_not_trigger_census(self):+ from auto_round.utils.oom import oom_census++ with (+ mock.patch("auto_round.utils.oom.dump_oom_tensor_census_") as census,+ self.assertRaisesRegex(RuntimeError, "shape mismatch"),+ oom_census("frame"),+ ):+ raise RuntimeError("shape mismatch")+ census.assert_not_called()++ def test_reexport_from_search_dispatch(self):+ import auto_round.algorithms.quantization.search_dispatch as dispatch_mod+ import auto_round.utils.oom as oom_mod++ self.assertIs(dispatch_mod.dump_oom_tensor_census_, oom_mod.dump_oom_tensor_census_)++ def test_census_never_masks_and_never_raises(self):+ import auto_round.algorithms.quantization.search_dispatch as dispatch_mod++ # CPU-only box: the census must swallow its own failures and return cleanly+ dispatch_mod.dump_oom_tensor_census_("test")+ with mock.patch("auto_round.utils.oom._group_tensors_by_shape", side_effect=RuntimeError("boom")):+ dispatch_mod.dump_oom_tensor_census_("test") # diagnostics failure swallowed+++class TestResolveLossDevice(unittest.TestCase):+ """The tune loop stages pred/ref AND the loss mask on one concrete device.++ Regression (hy3 4-GPU iters>0): card-0-risk relocation moved the staging+ device off the primary while the masked loss still targeted the primary,+ crashing the mask multiply across devices; an explicit None from the+ placement pass silently skipped the staging move entirely.+ """++ def test_none_coalesces_to_primary(self):+ from auto_round.algorithms.quantization.sign_round.quantizer import resolve_loss_device++ self.assertEqual(resolve_loss_device(None, "cuda:0"), "cuda:0")+ self.assertEqual(resolve_loss_device("cuda:1", "cuda:0"), "cuda:1")++ def test_masked_loss_stages_mask_on_the_passed_device(self):+ # the masked loss contract: the mask is moved onto the ``device`` the+ # caller staged pred/ref on, so all three multiply on one device+ from types import SimpleNamespace++ import torch++ import auto_round.algorithms.quantization.sign_round.quantizer as sr_mod+ from auto_round.algorithms.quantization.sign_round.quantizer import SignRoundQuantizer++ q = object.__new__(SignRoundQuantizer)+ pred = torch.randn(2, 3)+ ref = torch.randn(2, 3)+ mask = [torch.ones(1, dtype=torch.long), torch.ones(1, dtype=torch.long)]+ try:+ sr_mod.SignRoundQuantizer.model_context = property(lambda self: SimpleNamespace(amp=False))+ loss = q._get_loss(pred, ref, [0, 1], torch.nn.MSELoss(), "cpu", valid_token_mask=mask)+ finally:+ if "model_context" in sr_mod.SignRoundQuantizer.__dict__:+ delattr(sr_mod.SignRoundQuantizer, "model_context")+ self.assertTrue(torch.isfinite(loss))+++class TestOrchestratorPhaseSpans(unittest.TestCase):+ """Source contract: every span the orchestrator summary stops is opened.++ The tick chain opens spans at phase boundaries; the gated summary stops the+ last one before reading totals. A stopped-but-never-opened key only blows up+ when AR_PERF_COUNTERS is enabled on a real run, so pin the pairing here.+ """++ def test_every_stopped_span_is_opened(self):+ import ast+ import inspect++ from auto_round.compressors import orchestrator as orch++ tree = ast.parse(inspect.getsource(orch))+ opened, stopped = set(), set()+ for node in ast.walk(tree):+ if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)):+ continue+ if not (isinstance(node.func.value, ast.Name) and node.func.value.id == "_perf"):+ continue+ key = node.args[0].value if node.args and isinstance(node.args[0], ast.Constant) else None+ if key is None:+ continue+ if node.func.attr in ("tick", "start"):+ opened.add(key)+ elif node.func.attr == "stop":+ stopped.add(key)+ self.assertTrue(stopped, "no _perf.stop() calls found in the orchestrator")+ self.assertEqual(+ stopped - opened,+ set(),+ f"spans stopped but never opened: {sorted(stopped - opened)}",+ )+++class TestTunePhaseLine(unittest.TestCase):+ def _fmt(self):+ from auto_round.algorithms.quantization.sign_round.quantizer import _tune_phase_line++ return _tune_phase_line++ def test_ar_perf_recorder_follows_env(self):+ import os+ import time++ from auto_round.utils.perf_counters import _PerfCounters++ with mock.patch.dict(os.environ, {"AR_PERF_COUNTERS": "1"}):+ perf = _PerfCounters()+ self.assertTrue(perf.enabled)+ perf.start("s_fwd")+ time.sleep(0.001)+ perf.stop("s_fwd")+ perf.start("s_fwd")+ perf.stop("s_fwd")+ self.assertGreater(perf.get("s_fwd"), 0.0)+ self.assertEqual(set(perf.totals), {"s_fwd"})+ perf.set("rest", perf.get("s_fwd") - perf.get("sampler"))+ self.assertAlmostEqual(perf.get("rest"), perf.get("s_fwd"))+ perf.start("s_loss")+ self.assertEqual(perf.get("s_loss"), 0.0) # open span reads as zero until stopped++ # tick chain: closing each span opens the next+ with mock.patch.dict(os.environ, {"AR_PERF_COUNTERS": "1"}):+ perf = _PerfCounters()+ for k in ("attach", "compress", "swap", "sweep", "write"):+ perf.tick(k)+ self.assertEqual(set(perf.totals), {"attach", "compress", "swap", "sweep"})+ # observe: count + total + max+ perf.observe("quant_mod", 0.5)+ perf.observe("quant_mod", 1.5)+ self.assertEqual(perf.counts["quant_mod"], 2)+ self.assertAlmostEqual(perf.totals["quant_mod"], 2.0)+ self.assertAlmostEqual(perf.maxima["quant_mod"], 1.5)++ with mock.patch.dict(os.environ, {"AR_PERF_COUNTERS": "0"}):+ perf = _PerfCounters()+ self.assertFalse(perf.enabled)+ perf.start("s_fwd")+ perf.stop("s_fwd")+ perf.tick("swap")+ perf.observe("s_fwd", 1.0)+ perf.set("s_fwd", 1.0)+ self.assertEqual(perf.get("s_fwd"), 0.0)++ def test_base_line_matches_ddp_formatter(self):+ line = self._fmt()({"wrap": 1.5, "prepare": 0.0, "loop": 9.5, "tail": 0.5}, 10)+ self.assertEqual(line, "[perf] tune phases (iters=10): wrap=1.50s prepare=0.00s loop=9.50s tail=0.50s")++ def test_loop_split_appended_with_serial(self):+ line = self._fmt()(+ {+ "wrap": 1.0,+ "prepare": 0.0,+ "loop": 9.5,+ "tail": 0.5,+ "lp_sampler": 0.0,+ "lp_snap": 0.06,+ "lp_step": 0.02,+ "lp_rest": 0.82,+ "lp_serial": 8.6,+ },+ 10,+ )+ self.assertIn("(loop: sampler=0.00s snap=0.06s step=0.02s rest=0.82s serial: fwd+loss+bwd=8.60s)", line)++ def test_loop_split_omitted_without_keys(self):+ line = self._fmt()({"wrap": 1.0, "prepare": 0.0, "loop": 9.5, "tail": 0.5}, 10)+ self.assertNotIn("loop:", line.split("loop=9.50s")[-1])++ def test_serial_omitted_when_zero(self):+ line = self._fmt()(+ {+ "wrap": 1.0,+ "prepare": 0.0,+ "loop": 9.5,+ "tail": 0.5,+ "lp_sampler": 0.0,+ "lp_snap": 0.0,+ "lp_step": 0.0,+ "lp_rest": 9.5,+ "lp_serial": 0.0,+ },+ 10,+ )+ self.assertNotIn("serial:", line)+++class TestSnapshotRouting(unittest.TestCase):+ """snapshot_best_params: non-CPU cache device -> per-param device copies."""++ def _fake_block(self):+ class W(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.orig_layer = torch.nn.Linear(8, 8, bias=False)+ self.params = {"value": torch.nn.Parameter(torch.arange(16, dtype=torch.float32).reshape(4, 4))}++ block = torch.nn.Module()+ block.w0 = W()+ block.w1 = W()+ return block++ def test_cpu_cache_device_uses_host_path(self):+ from auto_round.compressors.utils import snapshot_best_params++ block = self._fake_block()+ out = snapshot_best_params(block, torch.device("cpu"))+ for n in ("w0", "w1"):+ self.assertTrue(out[n]["value"].data_ptr() != block.get_submodule(n).params["value"].data_ptr())+ self.assertTrue(torch.equal(out[n]["value"], block.get_submodule(n).params["value"]))+ self.assertEqual(out[n]["value"].device.type, "cpu")++ def test_non_cpu_cache_device_keeps_params_on_own_device(self):+ from auto_round.compressors.utils import snapshot_best_params++ block = self._fake_block()+ # router keys on the cache-device label; params live on cpu in this test+ out = snapshot_best_params(block, "cuda:0")+ for n in ("w0", "w1"):+ src = block.get_submodule(n).params["value"]+ self.assertEqual(out[n]["value"].device, src.device) # own device, not the cache device+ self.assertTrue(torch.equal(out[n]["value"], src))++ def test_local_snapshot_storage_is_distinct(self):+ from auto_round.compressors.utils import snapshot_best_params++ block = self._fake_block()+ out = snapshot_best_params(block, "cuda:0")+ src = block.w0.params["value"]+ with torch.no_grad():+ src.add_(1.0)+ self.assertFalse(torch.equal(out["w0"]["value"], src)) # snapshot isolated from mutation+ src.sub_(1.0)++ def test_local_copy_failure_falls_back_to_host(self):+ from auto_round.compressors.utils import collect_best_params_local++ block = self._fake_block()++ class FlakyData:+ # local path passes a torch.device object; the host fallback passes the "cpu" string+ device = torch.device("cpu")++ def to(self, device=None, copy=False):+ if isinstance(device, torch.device):+ raise RuntimeError("simulated local-copy failure")+ return torch.zeros(2, 2)++ class Pseudo:+ data = FlakyData()++ block.w0.params["flaky"] = Pseudo()+ out = collect_best_params_local(block)+ self.assertIn("w0", out) # host fallback still produced a snapshot+ self.assertIn("flaky", out["w0"])++ def test_invalid_cache_device_label_keeps_historical_behavior(self):+ from auto_round.compressors.utils import snapshot_best_params++ block = self._fake_block()+ with self.assertRaisesRegex(RuntimeError, "Invalid device"):+ snapshot_best_params(block, "not-a-device") # same failure as the historical path+++class TestNonCudaFamilies(unittest.TestCase):+ """Non-cuda device coverage: graceful degradation, never a crash."""++ def test_worker_ctx_unknown_and_cpu_keys_run_bare(self):+ from auto_round.algorithms.quantization.search_dispatch import _device_worker_ctx, _null_ctx++ for key in ["cpu", "bogus-device", "cuda:99"]: # cuda:99 -> unavailable cuda -> bare+ ctx = _device_worker_ctx(key)+ self.assertIsNotNone(ctx)++ def test_run_items_by_device_non_cuda_groups(self):+ from auto_round.algorithms.quantization.search_dispatch import group_items_by_device, run_items_by_device++ ran = []+ groups = group_items_by_device(["cpu", "cpu", "meta"], lambda item: item)+ run_items_by_device(groups, lambda idx, item: ran.append((idx, item)))+ self.assertEqual(sorted(ran), [(0, "cpu"), (1, "cpu"), (2, "meta")])++ def test_grouped_backstop_degrades_off_cuda(self):+ import torch++ from auto_round.modeling.fused_moe.grouped_experts import _native_grouped_mm_usable++ x = torch.randn(4, 8)+ w = torch.randn(2, 8, 8)+ offs = torch.tensor([2, 4], dtype=torch.int32)+ # cpu tensors must never gamble on the native path (would raise+ # mid-forward on families F.grouped_mm does not support); the backstop+ # is only reached when the transformers helper is unavailable+ import auto_round.modeling.fused_moe.grouped_experts as ge++ with mock.patch.object(ge, "_transformers_can_use_grouped_mm", None):+ self.assertFalse(_native_grouped_mm_usable(x, w, offs))+++class TestWrapSearchWorkerBuckets(unittest.TestCase):+ """Planner contracts: exclusive per-worker buckets with locality-preferring balance."""++ @staticmethod+ def _fake(seed, shape=(6, 128)):+ import types as _types++ from auto_round.data_type.utils import resolve_optimized_init_scale_fn++ w = torch.randn(*shape, generator=torch.Generator().manual_seed(seed))+ fn = resolve_optimized_init_scale_fn("int", 1e-5)++ class _W:+ supports_batched_search = True+ _deferred_search_inputs = (w, "int", 4, None, 1e-5, fn)+ init_scale = None+ orig_layer = _types.SimpleNamespace(group_size=128)+ name = f"m{seed}"++ def _run_deferred_search_now(self):+ *_, f = self._deferred_search_inputs+ self.init_scale = f(self._deferred_search_inputs[0], 4, None)++ def finalize_batched_search(self, res):+ self.init_scale = res+ self._deferred_search_inputs = None++ return _W()++ def test_concentrated_homes_spread_across_viable_workers(self):+ # chunks whose weights share one home must spread across the viable+ # workers (balanced), not pile onto the home device+ wrappers = [self._fake(i) for i in range(8)]+ captured = {}++ def fake_run(keyed, fn):+ captured["buckets"] = {k: [c for _idx, it in v for c in it[1]] for k, v in keyed.items()}++ with (+ mock.patch.object(search_dispatch, "pick_search_worker_devices", return_value=["cpu", "cuda:9"]),+ mock.patch.object(search_dispatch, "probe_usable_bytes", return_value=2**40),+ mock.patch.object(search_dispatch, "run_items_by_device", side_effect=fake_run),+ ):+ search_dispatch.run_batched_wrap_search(wrappers, max_batch=1)+ buckets = captured["buckets"]+ self.assertEqual(set(buckets), {"cpu", "cuda:9"})+ counts = [len(items) for items in buckets.values()]+ self.assertLessEqual(max(counts) - min(counts), 1)++ def test_homes_without_other_workers_run_inline(self):+ # viable = home only: a single bucket executes inline and the real+ # stacked search runs on the weights' own device+ wrappers = [self._fake(i) for i in range(3)]+ with mock.patch.object(search_dispatch, "pick_search_worker_devices", return_value=["cpu"]):+ self.assertTrue(search_dispatch.run_batched_wrap_search(wrappers, max_batch=2))+ for wr in wrappers:+ self.assertIsNotNone(wr.init_scale)++ def test_rebalance_uses_least_loaded_first(self):+ # three chunks and one extra worker: the split is 2/1, not 3/0+ wrappers = [self._fake(i) for i in range(3)]+ captured = {}++ def fake_run(keyed, fn):+ captured["buckets"] = {k: [c for _idx, it in v for c in it[1]] for k, v in keyed.items()}++ with (+ mock.patch.object(search_dispatch, "pick_search_worker_devices", return_value=["cpu", "cuda:9"]),+ mock.patch.object(search_dispatch, "probe_usable_bytes", return_value=2**40),+ mock.patch.object(search_dispatch, "run_items_by_device", side_effect=fake_run),+ ):+ search_dispatch.run_batched_wrap_search(wrappers, max_batch=1)+ counts = sorted(len(v) for v in captured["buckets"].values())+ self.assertEqual(counts, [1, 2])+++class TestSearchTransientBytes(unittest.TestCase):+ def test_plain_grid_search_counts_copy_chain_only(self):+ from auto_round.algorithms.quantization.search_dispatch import search_transient_bytes+ from auto_round.data_type.int import search_scales++ self.assertEqual(search_transient_bytes(search_scales, 4000), 4000 * 4 * 4)++ def test_neuqi_search_adds_internal_budget_once_per_call(self):+ # the sweep budget is per-call: doubling the stacked modules doubles+ # the copy chain, not the internal budget+ from auto_round.algorithms.quantization.search_dispatch import search_transient_bytes+ from auto_round.data_type.neuqi import _MAX_TMP_ELEMS, neuqi_anchor_margins++ one = search_transient_bytes(neuqi_anchor_margins, 1000)+ two = search_transient_bytes(neuqi_anchor_margins, 2000)+ self.assertEqual(one, 1000 * 4 * 4 + _MAX_TMP_ELEMS * 4 * 8)+ self.assertEqual(two - one, 1000 * 4 * 4) # chain scales, budget does not++ def test_budget_is_override_only(self):+ import os++ from auto_round.algorithms.quantization import search_dispatch++ saved = os.environ.pop("AR_SEARCH_BATCH_GB", None)+ try:+ self.assertIsNone(search_dispatch._wrap_batch_max_elems())+ finally:+ if saved is not None:+ os.environ["AR_SEARCH_BATCH_GB"] = saved+++class TestPlanCapacityChunks(unittest.TestCase):+ def _plan(self, entries, probes, picks=None):+ calls = {}++ def fake_probe(dev):+ calls.setdefault(dev, 0)+ calls[dev] += 1+ return probes.get(dev)++ with mock.patch.object(search_dispatch, "probe_usable_bytes", side_effect=fake_probe):+ if picks is None:+ picks = lambda ws, home_device=None: [home_device]+ with mock.patch.object(search_dispatch, "pick_search_worker_devices", side_effect=picks):+ return search_dispatch._plan_capacity_chunks(entries), calls++ def test_sizes_chunk_to_the_executing_device_capacity(self):+ per, mods = 1000, list(range(10))+ plans, _ = self._plan([("cuda:0", per, 0, 1024, mods)], {"cuda:0": 2 * 10 * per})+ ((worker, home, chunk),) = plans+ self.assertEqual((worker, home, len(chunk)), ("cuda:0", "cuda:0", 10)) # usable//2 // per++ def test_serial_chunks_do_not_drain_capacity(self):+ # chunks on a device run one at a time, so each is sized to the+ # device's own headroom instead of draining a cumulative budget+ per, mods = 1000, list(range(30))+ plans, _ = self._plan([("cuda:0", per, 0, 10, mods)], {"cuda:0": 2 * 10 * per})+ sizes = [len(c) for _w, _h, c in plans]+ self.assertEqual(sizes, [10, 10, 10])++ def test_work_spreads_round_robin_home_first(self):+ per = 1000+ mods = list(range(2))+ probes = {"cuda:0": 2 * 3 * per, "cuda:1": 2 * 2 * per} # cuda:0 roomier than home+ picks = lambda ws, home_device=None: [home_device, "cuda:0"]+ plans, _ = self._plan([("cuda:1", per, 0, 1, mods)], probes, picks)+ workers = [w for w, _h, _c in plans]+ # equal counts: home takes its share first, the overflow goes on+ self.assertEqual(workers, ["cuda:1", "cuda:0"])++ def test_tight_home_chews_small_batches_and_shares_with_roomy_device(self):+ per = 1000+ mods = list(range(6))+ probes = {"cuda:1": 2 * 1 * per, "cuda:7": 2 * 4 * per}+ picks = lambda ws, home_device=None: [home_device, "cuda:7"]+ plans, _ = self._plan([("cuda:1", per, 0, 1024, mods)], probes, picks)+ got = [(w, len(c)) for w, _h, c in plans]+ # round-robin: home takes 3 (one per batch, its cap is 1), cuda:7+ # takes 3 in one batch (its cap is 4)+ self.assertEqual(got, [("cuda:1", 1), ("cuda:1", 1), ("cuda:1", 1), ("cuda:7", 3)])++ def test_sweep_budget_sized_per_chunk(self):+ per, sweep, mods = 1000, 10_000, list(range(30))+ plans, _ = self._plan([("cuda:0", per, sweep, 1024, mods)], {"cuda:0": 2 * (10 * per + sweep)})+ sizes = [len(c) for _w, _h, c in plans]+ # each chunk's own transient (chain + sweep) fits half the probe:+ # (usable//2 - sweep)//per = 10 per chunk, serially re-earned+ self.assertEqual(sizes, [10, 10, 10])++ def test_unprobeable_home_keeps_fixed_width(self):+ mods = list(range(5))+ plans, _ = self._plan([("cpu", 1000, 0, 2, mods)], {"cpu": None})+ self.assertEqual(+ [(w, h, len(c)) for w, h, c in plans], [("cpu", "cpu", 2), ("cpu", "cpu", 2), ("cpu", "cpu", 1)]+ )++ def test_balanced_homes_move_nothing(self):+ # a placement that already spans the candidates keeps every module+ # resident: only overflow from an over-quota home moves+ per = 1000+ group_home1 = list(range(4))+ group_home2 = ["a", "b", "c", "d"]+ probes = {"cuda:1": 2**41, "cuda:2": 2**41}+ picks = lambda ws, home_device=None: [home_device, "cuda:1", "cuda:2"]+ plans, _ = self._plan([("cuda:1", per, 0, 8, group_home1), ("cuda:2", per, 0, 8, group_home2)], probes, picks)+ for worker, home, chunk in plans:+ self.assertEqual(worker, home)