Skip to content

Commit 9c8d61b

Browse files
authored
fix(exl3): refresh deferred runtime weights per layer forward and align generic geometry (#4006) (#4026)
* fix(exl3): refresh deferred runtime weights per layer forward and align generic geometry (#4006) * docs(exl3): document runtime weight refresh and 128-channel geometry (#4006) * docs(exl3): reference the introducing PR (#4006)
1 parent 57233fa commit 9c8d61b

8 files changed

Lines changed: 519 additions & 6 deletions

File tree

‎README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,11 @@ columns at a time and never retains a dense dequantized weight;
306306
`get_weight_tensor()` materializes one on demand for export and tests. Set
307307
`GPTQMODEL_EXL3_CPU_BF16X3=0` to disable the BF16x3 path.
308308

309+
The [EXL3 runtime weight lifecycle](docs/exl3-runtime-weights.md) describes how
310+
deferred dense replay weights are refreshed before every layer forward, why the
311+
generic path zero-pads output columns to 128 and rejects unaligned input
312+
features before calibration.
313+
309314
`BACKEND.VLLM`, `BACKEND.SGLANG`, and `BACKEND.MLX` are external runtime backends and are not part of the native kernel matrix above.
310315

311316
Native backend availability, shape validation, wide activation inputs, and

‎docs/exl3-runtime-weights.md‎

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
# EXL3 runtime weight lifecycle
2+
3+
EXL3 packs a projection into trellis/sign tensors and then drops the dense
4+
source weight. The dense weight is reconstructed only for the layer forward
5+
that produces the next layer's calibration inputs, and is replaced by the
6+
packed module at finalization. This page describes that lifecycle, the layer
7+
wide refresh that keeps it correct across subsets, and the 128-channel geometry
8+
contract for the generic `EXL3Processor`. The refresh was introduced with
9+
[PR #4026](https://github.com/ModelCloud/GPTQModel/pull/4026).
10+
11+
## Why the layer inventory is refreshed, not only the subset
12+
13+
One decoder layer is quantized in subsets. After subset `n` is packed,
14+
`EXL3Processor._stage_runtime_weight` (`gptqmodel/looper/exllamav3_processor.py:2388`)
15+
replaces that subset's dense weight with a META placeholder and stores a marker
16+
in `NamedModule.state`. The layer forward that follows still executes every
17+
module in the layer: earlier subsets are already packed, and later subsets are
18+
still dense. Therefore the subset that is currently being quantized is not the
19+
set of modules whose runtime weights must be ready.
20+
21+
`prepare_layer_runtime_weights_for_forward`
22+
(`gptqmodel/looper/loop_processor.py:87`) walks the complete layer inventory
23+
and offers every `NamedModule` to each processor's
24+
`prepare_runtime_weight_for_forward` hook. The hook materializes a deferred
25+
dense weight directly on the forward device and clears the marker, so a second
26+
call is a no-op. The two call sites are the subset capture forward
27+
(`gptqmodel/looper/stage_subset.py:946`) and the post-process replay
28+
(`gptqmodel/looper/stage_layer.py:321`).
29+
30+
```mermaid
31+
flowchart TD
32+
A["run_subset_stage: subset n of N"] --> B["_run_single_subset_pass"]
33+
B --> C["_prepare_layer_direct_state_for_forward"]
34+
C --> D["prepare_layer_runtime_weights_for_forward"]
35+
D --> E["prepare_runtime_weight_for_forward for every NamedModule in full"]
36+
E --> F{"deferred marker present?"}
37+
F -- "yes" --> G["reconstruct_exl3_tensors on forward device"]
38+
G --> H["_restore_module_weight crops padded output columns"]
39+
H --> I["clear exl3_deferred_runtime_weight marker"]
40+
F -- "no" --> J["return None, leave module unchanged"]
41+
I --> K["_run_forward_batches for the whole layer"]
42+
J --> K
43+
K --> L["process subset n and stage its META placeholder"]
44+
L --> M["_replay_layer_outputs"]
45+
M --> D
46+
M --> N["prepare_layer_post_quantize: terminal layer retires META to sentinel"]
47+
N --> O["submodule_finalize installs ExllamaV3Linear"]
48+
```
49+
50+
## Before the fix
51+
52+
Only the current subset was prepared before its forward, and the layer-wide
53+
sweep ran only for a fully skipped layer. A projection packed by an earlier
54+
subset therefore reached the next forward as a META parameter.
55+
56+
```mermaid
57+
flowchart TD
58+
A["subset 0 capture forward"] --> B["subset 0 process: stage META weight"]
59+
B --> C["subset 1 capture forward"]
60+
C --> D["_prepare_named_module_for_forward for subset 1 only"]
61+
D --> E["layer forward executes subset 0 projections"]
62+
E --> F["META weight reaches HookedLinear.forward"]
63+
F --> G["NotImplementedError: Cannot copy out of meta tensor; no data"]
64+
style G fill:#ffd6d6,stroke:#b00020,stroke-width:2px
65+
```
66+
67+
| Old mechanism | Location | New mechanism |
68+
| --- | --- | --- |
69+
| Prepare only `subset.values()` before a subset forward | `gptqmodel/looper/stage_subset.py` (pre-fix loop over the subset) | `prepare_layer_runtime_weights_for_forward(..., full=full)` before every subset forward |
70+
| Prepare `full` only when the whole layer is skipped | `gptqmodel/looper/stage_layer.py` (pre-fix skipped-layer branch) | The same sweep runs inside `_replay_layer_outputs` for every replay |
71+
| Deferred weight is reconstructed without an output crop | `_restore_module_weight` | Padded stored columns are cropped back to the logical `out_features` |
72+
73+
## 128-channel geometry contract
74+
75+
EXL3 applies a 128-wide signed Hadamard transform to the weight and the
76+
captured Hessian, and the runtime reconstructs in 128-wide output blocks.
77+
`validate_exl3_quantization_geometry`
78+
(`gptqmodel/exllamav3/modules/quant/exl3_lib/quantize.py:48`) enforces the
79+
contract:
80+
81+
| Dimension | Rule | Action |
82+
| --- | --- | --- |
83+
| `in_features` | must be a positive multiple of 128 | reject in `EXL3Processor.preprocess` and in `quantize_exl3`, before capture |
84+
| `out_features` | any positive value | zero-pad stored columns to `ceil(out_features / 128) * 128`; `ExllamaV3Linear.forward` crops the result |
85+
| weight layout passed to `quantize_exl3` | `(in_features, stored_out_features)` | `_quant_input_weight` builds the padded tensor |
86+
87+
Input channels are not padded. The runtime's `_stored_features` requires
88+
`trellis.shape[0] * 16 == in_features` and has no activation-padding boundary,
89+
so a padded input would change the stored module geometry. Failing before
90+
calibration is the supported behavior for such models; output padding is fully
91+
supported because the runtime already crops padded stored features.
92+
93+
```mermaid
94+
flowchart TD
95+
A["EXL3Processor.preprocess"] --> B["validate_exl3_quantization_geometry"]
96+
B --> C{"in_features % 128 == 0?"}
97+
C -- "no" --> D["ValueError with module name and in_features"]
98+
style D fill:#ffd6d6,stroke:#b00020,stroke-width:2px
99+
C -- "yes" --> E["build capture task"]
100+
E --> F["_quant_input_weight pads output columns"]
101+
F --> G["quantize_exl3 validates the same geometry again"]
102+
G --> H["packed trellis stores padded outputs"]
103+
```
104+
105+
## Failure and ambiguity contract
106+
107+
| Situation | Before | After |
108+
| --- | --- | --- |
109+
| Earlier subset packed, next subset forward runs | META tensor reaches the forward | Whole layer is refreshed first |
110+
| Deferred weight exists during post-process replay | Not prepared unless a device override touched it | Refreshed before `_run_forward_batches` |
111+
| `in_features` is not 128-aligned | bare `AssertionError` after calibration | `ValueError` from `preprocess` before capture |
112+
| `out_features` is not 128-aligned | bare `AssertionError` in the quantizer | zero-padded stored columns, cropped at forward |
113+
| Module has no deferred marker | unchanged | unchanged; the hook returns `None` |
114+
115+
## Not in scope
116+
117+
This page does not add activation padding for non-128-aligned input widths.
118+
That would require a runtime input boundary and a different stored geometry.

‎gptqmodel/exllamav3/modules/quant/exl3_lib/quantize.py‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,59 @@
2222
# Constant
2323
had_k, had_n = 128, 128
2424

25+
# EXL3 applies a 128-wide signed Hadamard transform to the weight and to the
26+
# captured Hessian, and the runtime reconstructs in 128-wide output blocks.
27+
# Logical output columns are zero-padded up to that block; input channels are
28+
# not padded because the runtime has no activation-padding boundary.
29+
EXL3_FEATURE_BLOCK = had_k
30+
2531
EXL3_HESSIAN_NUMERICAL_CONTRACT = "signed-block-hadamard-congruence-fp64-v1"
2632
EXL3_HESSIAN_SYMMETRY_CONTRACT = "mean-with-transpose-fp64"
2733
codebook_scale = 1.24371088
2834

35+
36+
def exl3_stored_output_features(out_features: int) -> int:
37+
"""Return the 128-aligned stored output width for a logical projection."""
38+
39+
if (
40+
isinstance(out_features, bool)
41+
or not isinstance(out_features, int)
42+
or out_features <= 0
43+
):
44+
raise ValueError("EXL3 projection out_features must be a positive integer")
45+
return math.ceil(out_features / EXL3_FEATURE_BLOCK) * EXL3_FEATURE_BLOCK
46+
47+
48+
def validate_exl3_quantization_geometry(
49+
in_features: int,
50+
out_features: int,
51+
*,
52+
label: str = "EXL3 projection",
53+
) -> int:
54+
"""Validate EXL3's fixed 128-channel geometry and return the stored width.
55+
56+
EXL3's Hadamard congruence and packed kernels operate on 128-wide input and
57+
output blocks. Output columns can be zero-padded in storage because the
58+
runtime crops them back to the logical width; input channels cannot,
59+
because the runtime reconstructs exactly ``in_features`` rows and has no
60+
boundary for padding the activation. Reject an unaligned input here, before
61+
capture, instead of failing an assertion after a full calibration pass.
62+
"""
63+
64+
if (
65+
isinstance(in_features, bool)
66+
or not isinstance(in_features, int)
67+
or in_features <= 0
68+
):
69+
raise ValueError(f"{label} in_features must be a positive integer")
70+
if in_features % EXL3_FEATURE_BLOCK:
71+
raise ValueError(
72+
f"{label} has in_features={in_features}, which is not a multiple of "
73+
f"{EXL3_FEATURE_BLOCK}; EXL3 requires 128-aligned input features "
74+
"(pad the model width or exclude the projection)."
75+
)
76+
return exl3_stored_output_features(out_features)
77+
2978
codebook_mcg_mult = 0xCBAC1FED
3079
codebook_mul1_mult = 0x83DCD12D
3180

@@ -1326,6 +1375,14 @@ def quantize_exl3(
13261375
- quantized and packed tensors
13271376
"""
13281377

1378+
if not isinstance(weight, torch.Tensor) or weight.ndim != 2:
1379+
raise ValueError("EXL3 quantization requires a 2-D weight tensor")
1380+
validate_exl3_quantization_geometry(
1381+
int(weight.shape[0]),
1382+
int(weight.shape[1]),
1383+
label="EXL3 weight",
1384+
)
1385+
13291386
device = torch.device(quant_args["devices"][0])
13301387
quant_stream = get_quant_stream(device)
13311388
outer_stream = torch.cuda.current_stream(device)

‎gptqmodel/looper/exllamav3_processor.py‎

Lines changed: 46 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
EXL3_HESSIAN_SYMMETRY_CONTRACT,
2727
quantize_exl3,
2828
reconstruct_exl3_tensors,
29+
validate_exl3_quantization_geometry,
2930
)
3031
from ..looper.loop_processor import (
3132
DTYPE_SIZE_COLUMN,
@@ -116,7 +117,7 @@
116117
has_learned_router_recovery,
117118
learned_router_ranked_choices,
118119
)
119-
from ..utils.exllamav3 import create_exllamav3_module
120+
from ..utils.exllamav3 import _resolve_linear_shape, create_exllamav3_module
120121
from ..utils.logger import setup_logger
121122
from ..utils.model import recurse_setattr
122123
from ..utils.module_locks import parent_module_lock
@@ -2146,6 +2147,13 @@ def preprocess(self, module: NamedModule, fallback=None, **kwargs):
21462147
if module_qcfg is None:
21472148
return
21482149

2150+
in_features, out_features = _resolve_linear_shape(module)
2151+
validate_exl3_quantization_geometry(
2152+
in_features,
2153+
out_features,
2154+
label=f"EXL3 projection `{module.full_name}`",
2155+
)
2156+
21492157
capture_qcfg = GPTQConfig(
21502158
bits=max(1, module_qcfg.runtime_bits),
21512159
group_size=-1,
@@ -2322,10 +2330,37 @@ def _build_quant_args(
23222330
return quant_args
23232331

23242332
def _quant_input_weight(self, capture: GPTQ, device: torch.device) -> torch.Tensor:
2325-
"""Exports the captured dense weight matrix in EXL3 quantizer layout."""
2333+
"""Exports the captured dense weight in EXL3's padded quantizer layout.
2334+
2335+
The quantizer expects ``(in_features, stored_out_features)`` with a
2336+
128-aligned output width. The extra output columns are zero and are
2337+
cropped by ``ExllamaV3Linear.forward`` after reconstruction.
2338+
"""
23262339

23272340
normalized = capture.clone_module(copy=True, device=device)
2328-
return normalized.t().contiguous().to(torch.float32)
2341+
weight = normalized.t().contiguous().to(torch.float32)
2342+
in_features, out_features = int(weight.shape[0]), int(weight.shape[1])
2343+
named_module = getattr(capture, "_named_module", None)
2344+
label = (
2345+
f"EXL3 projection `{named_module.full_name}`"
2346+
if isinstance(named_module, NamedModule)
2347+
else "EXL3 projection"
2348+
)
2349+
stored_outputs = validate_exl3_quantization_geometry(
2350+
in_features,
2351+
out_features,
2352+
label=label,
2353+
)
2354+
if stored_outputs == out_features:
2355+
return weight
2356+
padded = torch.zeros(
2357+
(in_features, stored_outputs),
2358+
dtype=weight.dtype,
2359+
device=weight.device,
2360+
)
2361+
padded[:, :out_features].copy_(weight)
2362+
del weight
2363+
return padded
23292364

23302365
def _restore_module_weight(
23312366
self, module: NamedModule, quantized_weight: torch.Tensor
@@ -2335,10 +2370,16 @@ def _restore_module_weight(
23352370
target = module.module if isinstance(module, NamedModule) else module
23362371

23372372
if isinstance(target, transformers.Conv1D):
2338-
return quantized_weight.contiguous().view_as(target.weight.data)
2373+
stored = quantized_weight
2374+
if stored.shape[1] > target.weight.shape[1]:
2375+
stored = stored[:, : target.weight.shape[1]]
2376+
return stored.contiguous().view_as(target.weight.data)
23392377

23402378
if isinstance(target, (torch.nn.Linear, _ConvNd)):
2341-
return quantized_weight.t().contiguous().view_as(target.weight.data)
2379+
stored = quantized_weight
2380+
if stored.shape[1] > target.weight.shape[0]:
2381+
stored = stored[:, : target.weight.shape[0]]
2382+
return stored.t().contiguous().view_as(target.weight.data)
23422383

23432384
raise NotImplementedError(
23442385
f"Unsupported EXL3 module type: {target.__class__.__name__}"

‎gptqmodel/looper/loop_processor.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,49 @@ def remove_processor_log(log_path: Optional[str], *, keep: bool = True) -> bool:
8484
]
8585

8686

87+
def prepare_layer_runtime_weights_for_forward(
88+
*,
89+
processors,
90+
full: Dict[str, object],
91+
fallback_device: torch.device,
92+
) -> int:
93+
"""Materialize deferred dense replay weights for every module in one layer.
94+
95+
A processor may pack a projection and replace its dense weight with a META
96+
placeholder until the layer's next full forward. Subset execution prepares
97+
only the modules in the current subset, so projections packed by earlier
98+
subsets still hold META when the layer forward runs for every module.
99+
Offer the whole layer inventory to the processors before each forward.
100+
101+
Returns the number of modules that a processor materialized.
102+
"""
103+
104+
prepared = 0
105+
for named_module in full.values():
106+
# Deferred replay state lives on the NamedModule wrapper. A raw module
107+
# in the inventory is either untouched native state or already packed.
108+
if not isinstance(named_module, NamedModule):
109+
continue
110+
for processor in processors:
111+
prepare_runtime = getattr(
112+
processor, "prepare_runtime_weight_for_forward", None
113+
)
114+
if not callable(prepare_runtime):
115+
continue
116+
materialized = prepare_runtime(
117+
module=named_module,
118+
target_device=fallback_device,
119+
)
120+
if materialized is None:
121+
continue
122+
named_module.module = materialized
123+
setattr(named_module, "target_device", fallback_device)
124+
setattr(materialized, "target_device", fallback_device)
125+
prepared += 1
126+
break
127+
return prepared
128+
129+
87130
def _format_gib(value: float) -> str:
88131
"""Formats a GiB value without unnecessary trailing zeros."""
89132

‎gptqmodel/looper/stage_layer.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
from ..utils.torch import CPU, torch_empty_cache, torch_sync
4646
from .extension import LoopPlan, LoopStep
4747
from .input_cache import TensorLifetimeDiagnostic
48+
from .loop_processor import prepare_layer_runtime_weights_for_forward
4849
from .stage_subset import SubsetPlan, build_layer_subset_plans, run_subset_stage
4950

5051

@@ -314,6 +315,15 @@ def _replay_layer_outputs(
314315
f"Forward replay Row 0/{replay_total_rows}"
315316
).draw()
316317

318+
# Replay runs the whole layer after the last subset's process() call, so
319+
# every projection packed in this layer must be back in dense form even
320+
# though only the final subset was prepared by its subset stage.
321+
prepare_layer_runtime_weights_for_forward(
322+
processors=getattr(looper, "processors", ()),
323+
full=full,
324+
fallback_device=cur_layer_device,
325+
)
326+
317327
replay_prev_devices: Dict[str, torch.device] = {}
318328
if replay_modules is not None and replay_forward_device_map:
319329
replay_prev_devices = looper._apply_forward_device_overrides(

‎gptqmodel/looper/stage_subset.py‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,11 @@
2626
import torch
2727

2828
from .. import DEBUG_ON, DEVICE_THREAD_POOL
29-
from ..looper.loop_processor import CalibrationTypes, LoopProcessor
29+
from ..looper.loop_processor import (
30+
CalibrationTypes,
31+
LoopProcessor,
32+
prepare_layer_runtime_weights_for_forward,
33+
)
3034
from ..looper.named_module import NamedModule
3135
from ..models._const import META
3236
from ..models.module_plan import _model_module_plan
@@ -936,6 +940,14 @@ def _run_single_subset_pass(
936940
and not getattr(looper.gptq_model, "_has_eora", False)
937941
):
938942
full[named_module.name] = named_module.module
943+
# The layer forward executes every module, not only this subset.
944+
# Projections packed by an earlier subset still hold the processor's
945+
# META placeholder, so refresh the whole inventory before running.
946+
prepare_layer_runtime_weights_for_forward(
947+
processors=getattr(looper, "processors", ()),
948+
full=full,
949+
fallback_device=cur_layer_device,
950+
)
939951

940952
# Determine MoE block name for hook selection
941953
moe_block_name = None

0 commit comments

Comments
 (0)