Repository navigation
fix(moe,awq,kernels,server): keep padding out of expert Hessians and restore live paths (#4051) - #4060
Merged
Conversation
…restore live paths (#4051) - gptq_processor: natively routed experts still receive zeroed padding rows; drop all-zero rows before add_batch so nsamples and the fallback threshold count only real tokens. A padding-only expert now keeps its RTN weights instead of running GPTQ on an all-zero Hessian. - awq_processor: key sibling capture sharing on data_ptr/shape/stride/dtype because calibration captures are inference tensors and _version raises. - torch_fused/torch_aten (+ AWQ variants): request an FP32 int4pack product for FP16+bias, add the bias before the single cast, and stop forcing the full-weight dense path. - openai_server: restore the RNG state inside _generation_lock so the next request cannot have its seed overwritten. - tests and docs/moe-padding-and-awq-dedup.md.
This was referenced Nov 14, 2026
Qubitium
added a commit
that referenced
this pull request
Nov 15, 2026
…ad gates (#4082) - give the five CPU kernel optimize overrides the base signature (#4068) - disable tracing inside _cpu_int4pack_mm so Inductor can lower the FP16+bias and BF16 int4pack path while keeping the #4060 FP32 product - resolve an indexed device with max_memory before the conflict check so the budgeted layer-wise map is not replaced by a full-model map - stage HIP JIT sources under the build cache for allspark, hadamard, gptq_block, exllamav3 and paroquant (#4072 items 2-4) - pack the ParoQuant Triton flat activation and gate the bitsandbytes and GGUF Triton matmuls on requires_grad
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #4051
TL;DR
Four follow-up defects from #4035 / #4043 / #4032 / #4033 are fixed:
its whole weight neutralized at
batch_size > 1;inference_mode;instead of dequantizing the full weight on every forward;
_generation_lock.15 files changed (+625/-32), including a new reference page
docs/moe-padding-and-awq-dedup.mdlinked fromREADME.md.1. Padding-only MoE expert zeroed at
batch_size > 1Root cause.
gptqmodel/looper/gptq_processor.py:673register_moe_root_capture_hookzeroed padded positions of the MoE block input(line 700), but the router still routed those rows and
pre_process_fwd_hookcounted every routed row inadd_batch(line 669). Anexpert that won only padding cleared the 0.5% fallback threshold, ran GPTQ on an
all-zero Hessian, and
_neutralize_dead_columnszeroed every weight column.flowchart TD A["MoE block input [B, S, H]"] --> B["register_moe_root_capture_hook zeroes padded rows"] B --> C["router sees zero logits and still routes padding"] C --> D["pre_process_fwd_hook sees [routed_rows, H]"] D --> E["add_batch counts every routed row"] E --> F["GPTQ on padding-only Hessian"] F --> G["_neutralize_dead_columns zeroes all weights"] style G fill:#f8d7da,stroke:#b02a37,color:#842029Fix. The hook now recognises the natively routed
[routed_rows, H]layout(row count unrelated to the keep mask), drops all-zero rows, and passes only
real rows to
add_batch._set_processor_maskpublishesmask_has_paddingonce per batch (
gptqmodel/looper/module_looper.py:835) so an unpadded batchpays no per-expert scan.
flowchart TD A["pre_process_fwd_hook"] --> B{"2-D input and row count != B*S"} B -- no --> C["existing 3-D or B*S mask path"] B -- yes --> D{"mask_has_padding"} D -- no --> E["add_batch all routed rows"] D -- yes --> F["keep_rows = (inp != 0).any(-1)"] F --> G["add_batch kept rows only"] G --> H["nsamples counts real rows only"] H --> I{"below fallback threshold"} I -- yes --> J["RTN fallback keeps the source weights"] I -- no --> K["GPTQ on the real-token Hessian"] style J fill:#d1e7dd,stroke:#0f5132,color:#0f5132Before / after (Qwen3-MoE fixture, 6 experts, router forces experts 0/1 to
win only padding rows,
batch_size=4):batch_size=1layers.0.mlp.experts.1.gate_proj,zero_frac = 1.000`layers.0.mlp.experts.0.down_proj,zero_frac = 1.000`Reproduced on CPU and on CUDA (
GPU-1892aea4-...); both runs now logUsing rtn fallback quantization (observed 0 samples)for experts 0/1.2. AWQ sibling-capture dedup never fires
Root cause.
gptqmodel/looper/awq_processor.py:644_capture_share_keyused
int(feature._version)(line 658). Calibration runs underinference_mode, so every captured feature is an inference tensor and_versionraises; the key was alwaysNoneand every sibling paid its own hostcopy. The unit test built normal tensors, so it passed.
flowchart TD A["_capture_share_key"] --> B{"feature._version"} B -- "raises on an inference tensor" --> C["return None"] C --> D["no cache hit; one host copy per sibling"] style C fill:#f8d7da,stroke:#b02a37,color:#842029Fix. The key is now storage pointer + shape + stride + dtype, plus the
version counter when one exists. The cached weakref still proves a hit is the
same object, so a recycled pointer cannot alias another capture; a normal
tensor's in-place mutation still invalidates its host copy.
flowchart TD A["_capture_share_key"] --> B["data_ptr + shape + stride + dtype"] B --> C{"version counter available"} C -- yes --> D["include version"] C -- no --> E["version None (inference tensor)"] D --> F["cache key"] E --> F F --> G{"weakref is the same object"} G -- yes --> H["reuse the host copy"] G -- no --> I["materialize a new host copy"] style H fill:#d1e7dd,stroke:#0f5132,color:#0f5132Before / after. New test
test_inference_tensor_captures_share_one_host_copyrecords hostmaterializations for three sibling captures under
torch.inference_mode():before, 3 materializations and
q is not k; after, 1 materialization andq is k is v(2 cache hits).apply_scalealready restores the pristinecapture before a second scale group divides the same tensor; that contract is
pinned by
test_apply_scale_restores_shared_feature_for_a_second_group.3. TorchFused / TorchAten FP16 + bias forced the dense path
Root cause.
gptqmodel/nn_modules/qlinear/torch_fused.py:335setfused_bias_safe = self.bias is None or x.dtype == torch.bfloat16, so an FP16layer with a bias permanently took
linear_mode = LinearMode.TRAIN(line 353)and dequantized the full weight on every forward.
TorchAtenLinearhad thesame gate.
flowchart TD A["TorchFusedLinear.forward"] --> B{"bias is None or x.dtype == bfloat16"} B -- yes --> C["fused int4pack"] B -- "no (FP16 + bias)" --> D["linear_mode = TRAIN"] D --> E["dequantize_weight on every forward"] style D fill:#f8d7da,stroke:#b02a37,color:#842029Fix.
_cpu_int4pack_mmaccepts anout_dtype. A biased FP16 layer asks foran FP32 product, adds the bias in FP32, and casts once. BF16 keeps its existing
path because it already has FP32's range.
TorchAtenLinear,TorchFusedAwqLinearand
TorchAtenAwqLinearuse the same contract.flowchart TD A["TorchFusedLinear.forward"] --> B{"bias is None or dtype in FP16/BF16"} B -- yes --> C["transform and linear_mode = INFERENCE"] C --> D{"bias present and x.dtype == float16"} D -- yes --> E["Int4PackedOp out_dtype=float32"] D -- no --> F["Int4PackedOp out_dtype=None"] E --> G["add bias in FP32, cast once"] F --> G style E fill:#d1e7dd,stroke:#0f5132,color:#0f5132Measured on CPU with 4 threads,
K = N = 4096,M = 1(shared host, soabsolute numbers vary; the ratio is measured in one process):
A clean earlier run measured TorchFused FP16+bias
262.95 ms -> 17.47 msmedian. Both now report
linear_mode == INFERENCE.Numerics. The existing independent FP64-cancellation tests
(
tests/test_inference_fp16_overflow.py) pass, including the exact rounded65216result for an out-of-FP16-range pre-bias sum. A random-weight comparisonagainst the dense
matmul_fp32_reducepath differs by at most one FP16 ULP(maximum absolute difference
4.88e-4, relative3.1e-4); BF16 output isunchanged.
4. RNG restore outside
_generation_lockRoot cause.
gptqmodel/utils/openai_server.py:481seeded insidewith self._generation_lock, but_restore_rng_stateran in afinallyafterthe block exited (line 489). Request B could seed and start generating, then
A's restore overwrote B's RNG state.
sequenceDiagram participant A as Request A participant L as _generation_lock participant B as Request B A->>L: acquire A->>A: capture + seed 11 + generate A->>L: release A->>A: _restore_rng_state outside the lock B->>L: acquire B->>B: capture + seed 22 + generate A-->>B: restore overwrites B's RNG state Note over B: draw comes from A's streamFix. The restore is now a nested
finallyinside the lock, so the nextrequest cannot seed until the previous request's RNG state is back.
sequenceDiagram participant A as Request A participant L as _generation_lock participant B as Request B A->>L: acquire A->>A: capture + seed 11 + generate A->>A: _restore_rng_state inside the lock A->>L: release B->>L: acquire B->>B: capture + seed 22 + generate Note over B: draw comes from B's seedBefore / after. New test
test_rng_restore_stays_inside_the_generation_lockinjects a 0.1 s delay in_restore_rng_stateand runs two concurrent seeded requests. Before, theobserved seeds were
[11, 787](the second request's seed was overwritten) andthe test fails; after, the seeds are
[11, 22]and each draw equalstorch.manual_seed(seed)'s first draw.Validation
CUDA venv
/opt/venvs/cu130t/bin/python(RTX 4090GPU-1892aea4-cc09-827c-b9a5-93d4eef7f5ae) and ROCm venv/opt/venvs/rocm101t/bin/python(HIP_VISIBLE_DEVICES=0), from the clone rootwith
PYTHONPATH=$PWD:Fail-before evidence (each test was run against the unmodified
mainfile):test_padding_only_expert_is_not_zeroed_at_batch_size_above_oneAssertionError: model.layers.0.mlp.experts.0.gate_proj,assert 0.0 > 0.0test_inference_tensor_captures_share_one_host_copyassert q is k is vfails; 3 host materializationstest_cpu_fp16_biased_layers_keep_the_fused_path[TorchFusedLinear]linear_mode == TRAINtest_cpu_fp16_biased_layers_keep_the_fused_path[TorchAtenLinear]linear_mode == 'train'test_rng_restore_stays_inside_the_generation_lockassert [11, 787] == [11, 22]The OpenAI-server tests skip cleanly when
httpx/fastapi/uvicornareabsent, as they are in the CUDA venv by default. I ran them by installing those
optional packages into a temporary
--target /tmp/testdepsdirectory; the venvitself was not modified.
Limitations / not in scope
BitsAndBytesLinearINT8 BF16 still uses the Python FP32 dequant path.bitsandbytes is not installed in the CUDA venv, and the installed CUDA
int8_mm_dequantkernel computes in FP16 before casting, which wouldoverflow the 70000 outlier covered by
test_bitsandbytes_int8_bf16_keeps_row_scale_in_fp32. No safe native BF16dequant kernel is available, so this item is left unchanged and untested
here.
tests/test_kernel_audit_regressions.py::test_exllamav2_gptq_forward_compacts_noncontiguous_activationsfails on unmodified
main(the test's lambda does not accept the existingout_dtypekeyword); it is not caused by this change and is deselected above.tests/test_q4_torch_fused.py::TestsTorchFused::test_torch_fusedneeds theabsent
evalutionpackage; not caused by this change.