Skip to content

fix(moe,awq,kernels,server): keep padding out of expert Hessians and restore live paths (#4051) - #4060

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4051
Nov 14, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4051

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4051

TL;DR

Four follow-up defects from #4035 / #4043 / #4032 / #4033 are fixed:

  1. a padding-only MoE expert no longer runs GPTQ on an all-zero Hessian and has
    its whole weight neutralized at batch_size > 1;
  2. AWQ sibling-capture dedup now works under inference_mode;
  3. FP16 + bias TorchFused / TorchAten CPU layers return to the fused kernel
    instead of dequantizing the full weight on every forward;
  4. the OpenAI server restores the RNG state inside _generation_lock.

15 files changed (+625/-32), including a new reference page
docs/moe-padding-and-awq-dedup.md linked from README.md.

1. Padding-only MoE expert zeroed at batch_size > 1

Root cause. gptqmodel/looper/gptq_processor.py:673
register_moe_root_capture_hook zeroed padded positions of the MoE block input
(line 700), but the router still routed those rows and
pre_process_fwd_hook counted every routed row in add_batch (line 669). An
expert that won only padding cleared the 0.5% fallback threshold, ran GPTQ on an
all-zero Hessian, and _neutralize_dead_columns zeroed 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:#842029
Loading

Fix. 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_mask publishes mask_has_padding
once per batch (gptqmodel/looper/module_looper.py:835) so an unpadded batch
pays 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:#0f5132
Loading

Before / after (Qwen3-MoE fixture, 6 experts, router forces experts 0/1 to
win only padding rows, batch_size=4):

tensor before after batch_size=1
layers.0.mlp.experts.1.gate_proj ` Wq = 0.000, zero_frac = 1.000`
layers.0.mlp.experts.0.down_proj ` Wq = 0.000, zero_frac = 1.000`

Reproduced on CPU and on CUDA (GPU-1892aea4-...); both runs now log
Using 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_key
used int(feature._version) (line 658). Calibration runs under
inference_mode, so every captured feature is an inference tensor and
_version raises; the key was always None and every sibling paid its own host
copy. 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:#842029
Loading

Fix. 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:#0f5132
Loading

Before / after. New test
test_inference_tensor_captures_share_one_host_copy records host
materializations for three sibling captures under torch.inference_mode():
before, 3 materializations and q is not k; after, 1 materialization and
q is k is v (2 cache hits). apply_scale already restores the pristine
capture 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:335 set
fused_bias_safe = self.bias is None or x.dtype == torch.bfloat16, so an FP16
layer with a bias permanently took linear_mode = LinearMode.TRAIN (line 353)
and dequantized the full weight on every forward. TorchAtenLinear had the
same 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:#842029
Loading

Fix. _cpu_int4pack_mm accepts an out_dtype. A biased FP16 layer asks for
an FP32 product, adds the bias in FP32, and casts once. BF16 keeps its existing
path because it already has FP32's range. TorchAtenLinear, TorchFusedAwqLinear
and TorchAtenAwqLinear use 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:#0f5132
Loading

Measured on CPU with 4 threads, K = N = 4096, M = 1 (shared host, so
absolute numbers vary; the ratio is measured in one process):

path dense (TRAIN) fused ratio
TorchFused FP16 + bias 294.70 ms min / 472.58 ms median 22.11 ms min / 36.44 ms median 13.0x
TorchAten FP16 + bias 217.04 ms min / 634.61 ms median 20.87 ms min / 34.23 ms median 18.5x

A clean earlier run measured TorchFused FP16+bias 262.95 ms -> 17.47 ms
median. Both now report linear_mode == INFERENCE.

Numerics. The existing independent FP64-cancellation tests
(tests/test_inference_fp16_overflow.py) pass, including the exact rounded
65216 result for an out-of-FP16-range pre-bias sum. A random-weight comparison
against the dense matmul_fp32_reduce path differs by at most one FP16 ULP
(maximum absolute difference 4.88e-4, relative 3.1e-4); BF16 output is
unchanged.

4. RNG restore outside _generation_lock

Root cause. gptqmodel/utils/openai_server.py:481 seeded inside
with self._generation_lock, but _restore_rng_state ran in a finally after
the 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 stream
Loading

Fix. The restore is now a nested finally inside the lock, so the next
request 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 seed
Loading

Before / after. New test
test_rng_restore_stays_inside_the_generation_lock injects a 0.1 s delay in
_restore_rng_state and runs two concurrent seeded requests. Before, the
observed seeds were [11, 787] (the second request's seed was overwritten) and
the test fails; after, the seeds are [11, 22] and each draw equals
torch.manual_seed(seed)'s first draw.

Validation

CUDA venv /opt/venvs/cu130t/bin/python (RTX 4090
GPU-1892aea4-cc09-827c-b9a5-93d4eef7f5ae) and ROCm venv
/opt/venvs/rocm101t/bin/python (HIP_VISIBLE_DEVICES=0), from the clone root
with PYTHONPATH=$PWD:

# CUDA (175 passed, 1 skipped, 9 deselected)
/opt/venvs/cu130t/bin/python -m pytest \
  tests/test_moe_padding_rows.py tests/test_moe_batch_equivalence.py \
  tests/test_awq_scale_search_memory.py tests/test_inference_fp16_overflow.py \
  tests/test_openai_server_contract.py tests/test_kernel_audit_regressions.py \
  -q -k "not exllamav2"

# ROCm (31 passed, 10 skipped)
HIP_VISIBLE_DEVICES=0 /opt/venvs/rocm101t/bin/python -m pytest \
  tests/test_moe_padding_rows.py tests/test_moe_batch_equivalence.py \
  tests/test_awq_scale_search_memory.py tests/test_inference_fp16_overflow.py -q

# CUDA fused-kernel suite (147 passed, 1 skipped, 9 deselected)
/opt/venvs/cu130t/bin/python -m pytest \
  tests/test_inference_fp16_overflow.py tests/test_kernel_audit_regressions.py \
  tests/test_torch_fused_asym_qzeros.py tests/kernels/test_torch_wide_bias_fallback.py \
  -q -k "not exllamav2"

# lint
ruff check gptqmodel docs/eora tests setup.py   # All checks passed!

Fail-before evidence (each test was run against the unmodified main file):

test before
test_padding_only_expert_is_not_zeroed_at_batch_size_above_one AssertionError: model.layers.0.mlp.experts.0.gate_proj, assert 0.0 > 0.0
test_inference_tensor_captures_share_one_host_copy assert q is k is v fails; 3 host materializations
test_cpu_fp16_biased_layers_keep_the_fused_path[TorchFusedLinear] linear_mode == TRAIN
test_cpu_fp16_biased_layers_keep_the_fused_path[TorchAtenLinear] linear_mode == 'train'
test_rng_restore_stays_inside_the_generation_lock assert [11, 787] == [11, 22]

The OpenAI-server tests skip cleanly when httpx/fastapi/uvicorn are
absent, as they are in the CUDA venv by default. I ran them by installing those
optional packages into a temporary --target /tmp/testdeps directory; the venv
itself was not modified.

Limitations / not in scope

  • BitsAndBytesLinear INT8 BF16 still uses the Python FP32 dequant path.
    bitsandbytes is not installed in the CUDA venv, and the installed CUDA
    int8_mm_dequant kernel computes in FP16 before casting, which would
    overflow the 70000 outlier covered by
    test_bitsandbytes_int8_bf16_keeps_row_scale_in_fp32. No safe native BF16
    dequant kernel is available, so this item is left unchanged and untested
    here.
  • tests/test_kernel_audit_regressions.py::test_exllamav2_gptq_forward_compacts_noncontiguous_activations
    fails on unmodified main (the test's lambda does not accept the existing
    out_dtype keyword); it is not caused by this change and is deselected above.
  • tests/test_q4_torch_fused.py::TestsTorchFused::test_torch_fused needs the
    absent evalution package; not caused by this change.

…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.
@Qubitium
Qubitium merged commit b30f68f into main Nov 14, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4051 branch November 14, 2026 19:56
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant