Repository navigation
Description
Summary
#4144 (commit bd922cd) added a check in _search_best_scale that every group target ran during the reference replay of module2inspect; otherwise it raises _AWQScaleGroupError and the whole group falls back. For MoE gate/up groups the replay calls the MoE block with native top-k, but the expert features were captured under the configured MoEConfig(routing=ExpertsRoutingOverride(...)). Experts that native top-k does not pick fail the check, and the entire gate/up group loses AWQ scaling.
Code
GPTQModel/gptqmodel/looper/awq_processor.py
Lines 2358 to 2661 in 6c3421c
| for layer, scale_consumers in zip(sanitized_module_config, scale_consumers_by_group): | |
| try: | |
| scales_list.append(self._search_best_scale( | |
| layer_module_ref, scale_consumers=scale_consumers, **layer, | |
| )) | |
| except _AWQScaleGroupError as exc: | |
| if not self.fallback: | |
| raise | |
| layer_names = [get_op_name(layer_module_ref, target) for target in layer["layers"]] | |
| fallback_names.update(layer_names) | |
| log.warning( | |
| "AWQProcessor: layer %s using configured plain-quantization fallback for %s: %s", | |
| layer_index, layer_names, exc, | |
| ) | |
| try: | |
| apply_scale( | |
| layer_module_ref, | |
| scales_list, | |
| input_feat_dict=input_feat, | |
| consumer_map=consumer_map, | |
| ) | |
| except RuntimeError as exc: | |
| debug_entries = [] | |
| for prev_op_name, layer_names, scales, _loss in scales_list: | |
| entry = {"prev": prev_op_name, "prev_shape": None, "layer_shapes": [], "scale_elems": None} | |
| try: | |
| prev_module = get_op_by_name(layer_module_ref, prev_op_name) | |
| except Exception: | |
| prev_module = None | |
| weight = getattr(prev_module, "weight", None) if prev_module is not None else None | |
| if isinstance(weight, torch.Tensor): | |
| entry["prev_shape"] = tuple(weight.shape) | |
| elif prev_module is None: | |
| entry["prev_shape"] = "missing" | |
| else: | |
| entry["prev_shape"] = f"{type(prev_module).__name__} (no weight)" | |
| layer_shapes = [] | |
| for lname in layer_names: | |
| try: | |
| layer_module = get_op_by_name(layer_module_ref, lname) | |
| except Exception: | |
| layer_shapes.append((lname, "missing")) | |
| continue | |
| weight = getattr(layer_module, "weight", None) | |
| if isinstance(weight, torch.Tensor): | |
| layer_shapes.append((lname, tuple(weight.shape))) | |
| else: | |
| layer_shapes.append((lname, f"{type(layer_module).__name__} (no weight)")) | |
| entry["layer_shapes"] = layer_shapes | |
| if hasattr(scales, "numel"): | |
| try: | |
| entry["scale_elems"] = int(scales.numel()) | |
| except Exception: | |
| entry["scale_elems"] = "unknown" | |
| debug_entries.append(entry) | |
| log.error( | |
| "AWQProcessor: apply_scale failed at layer %s with %s. Shape summary (first 5 groups): %s", | |
| layer_index, | |
| exc, | |
| debug_entries[:5], | |
| ) | |
| raise | |
| scales_list = append_str_prefix( | |
| scales_list, | |
| get_op_name(self.model, layer_module_ref) + ".", | |
| ) | |
| staged_teacher = None | |
| staged_gsq = getattr(self.qcfg, "gsq_training", None) | |
| if staged_gsq is not None and staged_gsq.enabled: | |
| from .gsq_training_awq import capture_awq_staged_teacher | |
| plan = _model_module_plan(self.gptq_model) | |
| projections = tuple( | |
| name for name, named in named_childs.items() | |
| if plan is None or plan.roles(name) | |
| ) | |
| staged_teacher = capture_awq_staged_teacher( | |
| self, layer_module_ref, named_childs, fallback_names, projections=projections, | |
| ) | |
| if self.apply_clip: | |
| clip_list = self._search_best_clip( | |
| layer_module_ref, | |
| {name: named.module for name, named in named_childs.items() if name not in fallback_names}, | |
| input_feat, | |
| ) | |
| apply_clip(layer_module_ref, clip_list) | |
| clip_list = append_str_prefix( | |
| clip_list, | |
| get_op_name(self.model, layer_module_ref) + ".", | |
| ) | |
| fallback_named_childs = { | |
| n: named_childs[n] | |
| for n in fallback_names | |
| if n in named_childs | |
| } | |
| named_childs = {name: named for name, named in named_childs.items() if name in input_feat and name not in fallback_names} | |
| self.apply_quant(named_childs, scales_list) | |
| if staged_teacher is not None: | |
| from .gsq_training_awq import refine_awq_staged_layer | |
| refine_awq_staged_layer(self, staged_teacher, named_childs, layer_index=layer_index) | |
| if fallback_named_childs: | |
| log.warning( | |
| "AWQProcessor: layer %s fallback quant %d modules: %s", | |
| layer_index, | |
| len(fallback_named_childs), | |
| list(fallback_named_childs)[:6], | |
| ) | |
| self.apply_quant(fallback_named_childs, scales_list=[]) | |
| self._finalize_quantized_layer(state, fallback_task_names=set(named_childs)) | |
| @staticmethod | |
| def _validate_scale_group_conflicts(module, groups): | |
| """Reject overlapping folds before any group can modify the layer.""" | |
| sources = set() | |
| targets = set() | |
| for group in groups: | |
| source = group.get("prev_op") | |
| source_weight = getattr(source, "weight", None) | |
| source_key = id(source_weight) if isinstance(source_weight, torch.Tensor) else id(source) | |
| if source_key in sources: | |
| source_name = get_op_name(module, source) | |
| raise _AWQScaleGroupError(f"AWQ: source `{source_name}` has multiple scaling groups; merge them first.") | |
| sources.add(source_key) | |
| group_targets = list(group.get("layers") or []) | |
| group_targets.extend(get_op_by_name(module, name) for name in group.get("_scale_consumers") or []) | |
| for target in group_targets: | |
| target_weight = getattr(target, "weight", None) | |
| target_key = id(target_weight) if isinstance(target_weight, torch.Tensor) else id(target) | |
| if target_key in targets: | |
| target_name = get_op_name(module, target) | |
| raise _AWQScaleGroupError(f"AWQ: target `{target_name}` has overlapping scaling groups or tied weights.") | |
| targets.add(target_key) | |
| @staticmethod | |
| def _validate_scale_group(module, prev_op, layers, inp, module2inspect, scale_consumers): | |
| """Check exact bindings, widths and the existing replay boundary.""" | |
| try: | |
| source_name = get_op_name(module, prev_op) | |
| inspect_name = get_op_name(module, module2inspect) | |
| targets = [(get_op_name(module, layer), layer) for layer in layers] | |
| consumers = [(name, get_op_by_name(module, name)) for name in scale_consumers or ()] | |
| except ValueError as exc: | |
| raise _AWQScaleGroupError(f"AWQ: scaling group does not resolve on the live layer: {exc}") from exc | |
| if not targets or not isinstance(inp, torch.Tensor) or inp.ndim < 2 or inp.numel() == 0: | |
| raise _AWQScaleGroupError(f"AWQ: source `{source_name}` requires targets and nonempty replay features.") | |
| width = inp.shape[-1] | |
| weights = set() | |
| for name, target in targets + consumers: | |
| weight = getattr(target, "weight", None) | |
| if not isinstance(weight, torch.Tensor) or weight.ndim != 2 or weight.shape[1] != width: | |
| raise _AWQScaleGroupError(f"AWQ: target `{name}` does not accept the {width}-channel source input.") | |
| if id(weight) in weights: | |
| raise _AWQScaleGroupError(f"AWQ: duplicate or tied target `{name}` in one scaling group.") | |
| weights.add(id(weight)) | |
| source_weight = getattr(prev_op, "weight", None) | |
| if isinstance(source_weight, torch.Tensor) and prev_op is not layers[0]: | |
| if source_weight.ndim in (1, 2) and source_weight.shape[0] != width: | |
| raise _AWQScaleGroupError(f"AWQ: source `{source_name}` cannot produce {width} channels.") | |
| inspection_modules = {id(child) for child in module2inspect.modules()} | |
| outside = [name for name, target in targets + consumers if id(target) not in inspection_modules] | |
| if outside: | |
| raise _AWQScaleGroupError( | |
| f"AWQ: replay boundary `{inspect_name}` does not contain targets {outside} for source " | |
| f"`{source_name}`; a matching replay input and boundary are required." | |
| ) | |
| return targets + consumers | |
| @torch.inference_mode() | |
| def _search_best_scale( | |
| self, | |
| module, | |
| prev_op, | |
| layers: List[nn.Linear], | |
| inp: torch.Tensor, | |
| module2inspect=None, | |
| kwargs={}, | |
| bits: Optional[int] = None, | |
| scale_consumers: Optional[List[str]] = None, | |
| ): | |
| """Searches the best per-channel AWQ scale for a module group. | |
| Unless explicitly overridden by ``bits``, evaluate each member at its | |
| own configured width, even though the group shares one channel scale. | |
| ``scale_consumers`` names the non-quantized modules that read the same | |
| normed input (MoE router, ``shared_expert_gate``). Search replays the | |
| original input with ``Q(W * s) / s`` weights, so these consumers stay | |
| unchanged until the final fold compensates the scaled source. | |
| """ | |
| if module2inspect is None: | |
| assert len(layers) == 1 | |
| module2inspect = layers[0] | |
| replay_targets = self._validate_scale_group( | |
| module, prev_op, layers, inp, module2inspect, scale_consumers, | |
| ) | |
| kwargs = dict(kwargs) | |
| if "use_cache" in kwargs: | |
| kwargs.pop("use_cache") | |
| # Keep AWQ scale search on the low-memory path by default. Disabling this | |
| # restores the legacy eager behavior that materializes full activations on | |
| # the module device before loss evaluation. | |
| use_chunked_scale_search = getattr(self.qcfg, "scale_search_chunked_activations", True) | |
| # [STEP 1]: Compute per-channel mean of normalised weights | |
| # Stream across each Linear instead of concatenating all weights at once. This mirrors the | |
| # previous cat()+view pipeline while keeping peak memory low: for every group we normalise | |
| # |w| by its per-group max so the values land on a [0, 1] scale, then accumulate the totals | |
| # per output channel so the mean can be computed without allocating the combined tensor. | |
| group_sizes = [ | |
| self._group_size_for(module, layer) for layer in layers | |
| ] | |
| default_format = self._module_format(None) | |
| formats = [self._format_for(module, layer) for layer in layers] | |
| w_mean = _compute_awq_weight_mean(layers, group_sizes) | |
| # [STEP 2]: Compute per-channel mean of the input activation with chunking | |
| # Stream directly on the source device to avoid creating full CPU copies while still enforcing | |
| # a predictable memory bound derived from max_chunk_memory. | |
| inp_flat = inp.abs().view(-1, inp.shape[-1]) | |
| num_elements = inp_flat.size(0) | |
| num_channels = inp_flat.size(1) | |
| float32_size = torch.tensor([], dtype=torch.float32).element_size() | |
| element_size_bytes = float32_size # accumulation happens in FP32 | |
| # Calculate chunk size dynamically based on the available memory budget (default 1 GiB). | |
| chunk_size = int(self.max_chunk_memory // (element_size_bytes * num_channels)) | |
| chunk_size = min(chunk_size, num_elements) | |
| chunk_size = max(chunk_size, 1) | |
| # Use float32 for sum calculation | |
| x_sum = torch.zeros(num_channels, dtype=torch.float32, device=inp.device) | |
| for i in range(0, num_elements, chunk_size): | |
| end = min(i + chunk_size, num_elements) | |
| chunk = inp_flat[i:end] | |
| # Accumulate each chunk in FP32 to balance precision and memory usage. | |
| chunk_sum = chunk.to(torch.float32).sum(dim=0) | |
| x_sum += chunk_sum | |
| x_mean = (x_sum / num_elements).to(inp.dtype) | |
| del x_sum | |
| # [STEP 3]: Compute output of module | |
| module_kwargs = self._sanitize_kwargs(kwargs, module2inspect) | |
| global_kwargs = getattr(self, "_module_forward_kwargs", {}) | |
| global_allowed_kwargs = self._sanitize_kwargs(global_kwargs, module2inspect) | |
| for key, value in global_allowed_kwargs.items(): | |
| module_kwargs.setdefault(key, value) | |
| module_kwargs = self._align_module_kwargs_to_input(inp, module_kwargs) | |
| replay_batch_size = self._scale_search_replay_batch_size(inp) | |
| prepared_forward = None | |
| observed = set() | |
| handles = [] | |
| def record_target(target, _args): | |
| observed.add(id(target)) | |
| try: | |
| for _name, target in replay_targets: | |
| handles.append(target.register_forward_pre_hook(record_target)) | |
| if use_chunked_scale_search: | |
| # Resolve the device placement and rotary scaffolding once. Both the FP | |
| # reference and every candidate-scale replay reuse this prepared forward. | |
| prepared_x, prepared_kwargs = self._prepare_module_forward(inp, module2inspect, module_kwargs) | |
| prepared_forward = (prepared_x, prepared_kwargs) | |
| fp16_output = self._build_chunked_reference_outputs( | |
| prepared_x, | |
| module2inspect, | |
| prepared_kwargs, | |
| replay_batch_size, | |
| ) | |
| else: | |
| # Legacy path: run the full forward eagerly on the module device and keep | |
| # the dense activation tensor for the later reconstruction-loss pass. | |
| inp = inp.to(next(module2inspect.parameters()).device) | |
| with ctx(torch.inference_mode()): | |
| fp16_output = self._module_forward(inp, module2inspect, module_kwargs) | |
| fp16_output = fp16_output.clip(torch.finfo(fp16_output.dtype).min, torch.finfo(fp16_output.dtype).max) | |
| finally: | |
| for handle in handles: | |
| handle.remove() | |
| unobserved = [name for name, target in replay_targets if id(target) not in observed] | |
| if unobserved: | |
| raise _AWQScaleGroupError( | |
| f"AWQ: reference replay did not execute targets {unobserved}; " |
Trigger
AWQ on a MoE model with moe=MoEConfig(routing=ExpertsRoutingOverride()) (e.g. num_experts_per_tok='all'), with enough experts that native top-k leaves some unselected over the replay tokens.
Expected vs actual
- Expected: experts calibrated under the override keep AWQ scaling (as before fix(awq): preserve scale-search routing and reject incomplete replay groups #4144).
- Actual:
_AWQScaleGroupError, and all experts' gate/up projections, including routed ones, go to the plain-quantization fallback (defaultFallbackStrategy.RTN). Withfallback=Nonequantization aborts.
Impact
Silent loss of AWQ scaling (only a warning) for exactly the users who opted into all-expert calibration. Default moe=None is not affected.
Evidence (CPU, commit 6c3421c)
Tiny random Qwen3-MoE: 1 layer, 32 experts, top-1, fp16, AWQ 4-bit.
MODE=native _AWQScaleGroupError raised 0 time(s)
MODE=override _AWQScaleGroupError raised 1 time(s)
WARN AWQProcessor: layer 0 using configured plain-quantization fallback for ['mlp.experts.0.gate_proj', ... 'mlp.experts.31.up_proj']:
AWQ: reference replay did not execute targets ['mlp.experts.0.gate_proj', ... ]; the scale objective would not score the complete group.
All 64 expert gate/up projections fell back with the override. (The native run also had a separate, pre-existing fallback for experts with no captured features.)
Validation limits
CPU-only, GIL enabled, tiny random model. Accuracy cost on a real MoE checkpoint was not measured.
Suggested fix
Run the reference and candidate replays under the same MoERoutingOverrideContext used at capture, or require coverage only for natively routed experts (drop unrouted experts from the coverage set / scale fold instead of rejecting the whole group). Add a routing-override regression test where native top-k leaves at least one expert unselected.
Activity
fix(awq): replay MoE groups under the capture routing override (#4151) (