Skip to content

fix(kernels): enforce validation and cache lifecycle contracts - #3717

Merged
Qubitium merged 1 commit into
mainfrom
fix/kernel-audit-regressions-20261109
Nov 9, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/kernel-audit-regressions-20261109

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator

Summary

This fixes the confirmed kernel audit defects found across GPTQ, AWQ, Marlin/Machete, GGUF, EXL3, ParoQuant, fused CPU, and shared packing paths.

The changes make backend selection fail before launch when a native extension or tile contract is unavailable, preserve checkpoint state across fused inference/training transitions, invalidate derived native handles when packed tensors move or change, and avoid narrowing BF16 values through FP16 native kernels.

Corrected defects

Backend selection and native contracts

  • Machete now runs cached_validate_once() before shape validation, so AUTO cannot select an unavailable extension and then fail model loading.
  • AWQ GEMV-fast now advertises and enforces its real native contract: group size 128, output width divisible by 128, and input width divisible by 64.
  • AWQ GEMM now enforces output-width and effective group-size constraints. -1 is normalized to in_features before validation.
  • Native AWQ GEMV and GEMV-fast paths correctly declare SUPPORTS_TRAINING=False.
  • 3-bit GPTQ now requires int32 packing, with shared g_idx bounds validation.
  • CPU pack-block rejects partial output words instead of truncating quantized zeros.

Cache and lifecycle correctness

  • CPU fused eval-to-train transitions restore checkpoint qweight, qzeros, and scales before training.
  • Snapshot tensors are non-persistent buffers, follow device/dtype moves, and are discarded before checkpoint loads.
  • Fusion rebuilds shared operands without leaving stale packed or derived state; invalidating one fused sibling invalidates all siblings consistently.
  • ExLlamaV2 native handles are released on cache invalidation and rebuilt when packed tensors are replaced. AWQ no longer repeatedly unpacks packed weights.
  • Non-contiguous ExLlamaV2 activations are compacted before native use.
  • ParoQuant caches runtime dtype conversions without mutating checkpoint scale/bias tensors.
  • GGUF CUDA uses FP32 for BF16 inputs, keys plans by packed-tensor identity/version, bounds the plan cache to eight entries, and closes evicted plans.
  • GGUF Triton rejects wrong input width before padding or dispatch.
  • Marlin scratch honors the same 128-block CUDA workspace floor as the module allocator.

Wide-dtype paths

  • BF16 and non-FP16 EXL3 callers use FP32 native input/output before casting back to the caller dtype. FP16 callers remain on the FP16 path.
  • MLX EXL3 fallback reports normalized reconstruction error instead of a false proxy_error=0.

Validation

  • Full post-rebase fusion/kernel matrix: 595 passed, 139 skipped
  • Focused audit regression suite: 23 passed
  • AWQ/native/Marlin scratch suite: 34 passed, 11 skipped
  • tests/module_tree/test_llama_fusion.py: 65 passed, 13 skipped
  • tests/test_rocm_llc.py::test_apply_is_idempotent_and_never_raises: passed
  • Changed-file Ruff: passed
  • git diff --check: passed

The new regression coverage is in tests/test_kernel_audit_regressions.py, plus focused updates to fusion, GEMV-fast packing, MLX EXL3, and ParoQuant tests.

Logic flow

The committed lifecycle and selection flow is documented in Kernel validation and cache lifecycle. It covers backend validation, fused train-state restoration, derived-cache invalidation, and wide activation handling.

flowchart LR
    A["Packed checkpoint tensors"] --> B["Validate backend and tile contract"]
    B --> C["Build inference-derived handle or plan"]
    C --> D["Forward"]
    D --> E{"Tensor moved, changed, or state loaded?"}
    E -->|yes| F["Release derived cache"]
    F --> B
    E -->|no| D
    D --> G{"Train mode?"}
    G -->|yes| H["Restore packed checkpoint state"]
Loading

Compatibility policy

No backward compatibility is retained for internal APIs. Only hf_-prefixed APIs remain compatibility surfaces.

Environment limitations

  • CUDA_HOME and nvcc are unavailable, so JIT builds for Marlin, EXL3, ParoQuant rotation, and several native extensions are skipped.
  • No ROCm or MLX runtime is available.
  • AWQ end-to-end model tests requiring /monster/data/model/Llama-3.2-1B are skipped because that checkpoint is absent.
  • The reported native EXL3 Blackwell mapping concern was checked and excluded: CC_HOPPER and CC_BLACKWELL both equal 4, so the existing Hopper mapping already covers Blackwell.

@Qubitium
Qubitium merged commit e848d93 into main Nov 9, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/kernel-audit-regressions-20261109 branch November 9, 2026 14:06
Qubitium added a commit that referenced this pull request Nov 11, 2026
… path (#3764)

Two pre-existing failures on `f68935b61` were stale test contracts, not
regressions from the CPU fusion work.

QQQ oracle double-rounded the bias. `test_qqq_cpu.oracle` narrowed
`accum * scale * channels` to the activation dtype and then added the bias,
while the kernel (qqq.py:722, per #3753) keeps the INT8 reduction and its
scales in FP32, adds the bias there, and rounds once. On
`test_qqq_bias_noncontiguous_and_empty` the double round disagreed on
446/1792 elements by one visible step (<= 0.0039). Bias is now added in
FP32 before the single narrowing cast, which makes the oracle match the
module bitwise for both float16 and bfloat16.

EXL3 audit test pinned a path deleted by #3731. #3717 asserted wide inputs
reached the native kernel with FP32 input/output; #3731 (`86a59903e`)
routed non-FP16 activations through `ExllamaV3TorchLinear`, whose inner
takes only `x` and upcasts to FP32 internally. The stale stub therefore
raised `TypeError: forward() missing 1 required positional argument`.
The test now pins the live dispatch: wide inputs reach the Torch inner with
the caller dtype and never touch `_ensure_inner`, FP16 keeps the native
FP16 kernel with an explicit `out_dtype`, and each half asserts the other
path is not taken. Added an end-to-end case where 1e10/1e-10 straddle the
FP16 range so an FP16-first path would yield inf/0; the module stays finite
and within 2e-3 relative L2 of the FP64 oracle.

Verified on f68935b (AVX512-BF16 host, torch 2.15.0+cu132):
- test_kernel_audit_regressions + test_qqq_cpu: 67 passed
- the four exl3/qqq suites: 143 passed, 5 skipped
- tests/module_tree fusion/fusable/module_plan: 728 passed, 633 skipped
- test_torch_cpu_avx512(+_awq): 87 passed
- 12-layout fusion sweep: all exact, err=0.0e+00

Copy link
Copy Markdown
Collaborator Author

Reviewed: replacing AWQ checkpoint buffers after native binding left the packing flag stale. #3787 repacks before rebind; lifecycle and native CUDA tests pass.

Qubitium added a commit that referenced this pull request Nov 17, 2026
…ract

Upstream moved under several MLX tests; repair the oracles that pinned the
retired behaviour instead of loosening them:

- `test_mlx_exl3_pipeline.py`: #3601 removed `EXL3Processor`'s CPU/Metal MLX
  quantization branch and `models/base.py` already rejects EXL3 quantization
  without CUDA, so drop `test_exl3_processor_routes_cpu_quantization_through_mlx`
  and keep one contract test that a CPU target raises. The zero-Hessian
  fallback now reports the normalized reconstruction error as its proxy error,
  so compare it to the oracle (and assert both sides took the fallback) rather
  than asserting zero.
- `test_mlx_qwen38_27b_shapes.py`: the QQQ dynamic-input oracle narrowed BF16
  activations to FP16 and cast the epilogue early, which #4537/#4534 no longer
  do. Consume the resident inputs, cast once, and allow one output ULP of the
  activation dtype (8e-3 bf16 / 2e-3 fp16).
- `test_mlx_qqq_quantization.py`: `scale_extra` is fitted to the produced
  codes, so a documented one-step tie flip moves it by at most one group
  scale. Compare exactly on rows without code drift, bound the drift elsewhere,
  and require the exported scale to describe the emitted codes.
- `test_mlx_awq_variants.py`: the Torch GEMV_FAST/LLM_AWQ sources require
  group_size 128 and 128-aligned out_features (#3717); fall back to the MLX
  holder as the packed source for the combinations the Torch contract rejects,
  and allow one activation-dtype ULP (bf16 is 2**-7 relative, not 2e-3).
- `test_mlx_foem_quantization.py`: native processors read routing metadata from
  `NamedModule`, so wrap the probe layer.
- `test_mlx_qqq_processor.py`: `__init__` records the requested backend; set
  `BACKEND.AUTO` so the portable Torch holder is the expected macOS choice.
- `test_mlx_dense_methods.py` / `test_mlx_method_selection.py`: the MLX BNB
  holder reuses `BitsAndBytesLinear`'s dependency probe, so skip without
  `bitsandbytes` installed instead of failing on the import.

Full MLX suite (tests/test_*mlx*.py tests/test_q4_torch_apple.py
tests/test_pack_block_batched.py): 5377 passed, 83 skipped, 5 failed. The five
failures need `/monster/data/model/...` checkpoints that are absent here
(`test_mlx_generate` and the four `test_q4_torch_apple` generation tests) and
are unrelated to these changes.
Qubitium added a commit that referenced this pull request Nov 17, 2026
…aded weights (#4687)

* fix(paroquant): mirror the Torch affine grid fit in the MLX bridge

The MLX optimizer still fitted asymmetric qparams with `(max - min) / qmax`
and returned `minimum / scale` as the zero point, the formula the Torch
reference retired in #4160/#4165. A one-sided or constant group has no
representable zero point in that grid, so every value clipped onto code 0 or
qmax and the group collapsed to a single code. The optimizer could not repair
it: the affine straight-through gradient with respect to the zero point
cancels exactly, so the drift was silent.

Port `_calc_affine_qparams` line for line: include zero in the fitted range,
round the integer zero point onto that grid, re-fit the scale per side from the
remaining code budget, then clamp. The bridge keeps its existing contract of
returning `-zero_point`, which `_pseudo_quantize` and the runtime packer both
consume.

Tests (tests/test_mlx_paroquant_optimize.py):
- new `test_paroquant_mlx_affine_qparams_match_torch_reference[2,4,8]` fits
  positive-only, negative-only, balanced and constant groups, requires exact
  scale/zero parity with `_calc_affine_qparams`, exact `_pseudo_quantize`
  parity with `pseudo_quantize_dequant`, and asserts the one-sided groups use
  more than two codes;
- new `test_paroquant_mlx_affine_qparams_promote_low_precision_weights[fp16,bf16]`
  pins the fp32 promotion the callers rely on;
- the Qwen3.8 export oracle now derives its expected qparams from
  `_calc_affine_qparams` instead of re-deriving the retired formula, and the
  processor monkeypatches target the lazily imported
  `gptqmodel.quantization.mlx_paroquant_optimize` module;
- `test_paroquant_mlx_trained_quality_tracks_torch` now bounds the documented
  Adam `sqrt(v) + eps` amplification of a float32-noise-floor gradient entry
  instead of a flat 2e-3 maximum that failed on a single tie flip.

Red evidence with the retired fit restored: 5 failed, 49 deselected
(`-k affine_qparams`). Green after the fix: 5 passed; whole module 54 passed.

* fix(pack_block): accept inference-mode-loaded weights

`pack_block` slices the caller's weight, but a weight can arrive without a
version counter even though it is not flagged as an inference tensor:
`load_state_dict(assign=True)` under `torch.inference_mode()` followed by
`module.to(dtype)` materializes exactly that tensor on recent Torch. Slicing it
raises `RuntimeError: Inference tensors do not track version counter` and the
pack fails during quantization.

After moving the weight to the host, probe `_version` and materialize a copy
when the probe raises. `pack_block` already runs under `inference_mode()`, so
the copy follows the active mode and is sliceable; the caller's tensor is
never mutated.

Test: `test_pack_block_accepts_inference_mode_loaded_weights[2,3,4,8]` builds
the poisoned tensor through that loader transition, asserts the trigger
(`not is_inference()` yet `_version` raises), then requires bit-exact parity
with a version-tracked control and the independent word oracle, plus an
unchanged caller weight.

Red evidence with the guard removed: 4 failed, 50 deselected
(`-k inference_mode`). Green after the fix: module 54 passed.

* test(mlx): repair stale oracles, backend skips, and the EXL3 CPU contract

Upstream moved under several MLX tests; repair the oracles that pinned the
retired behaviour instead of loosening them:

- `test_mlx_exl3_pipeline.py`: #3601 removed `EXL3Processor`'s CPU/Metal MLX
  quantization branch and `models/base.py` already rejects EXL3 quantization
  without CUDA, so drop `test_exl3_processor_routes_cpu_quantization_through_mlx`
  and keep one contract test that a CPU target raises. The zero-Hessian
  fallback now reports the normalized reconstruction error as its proxy error,
  so compare it to the oracle (and assert both sides took the fallback) rather
  than asserting zero.
- `test_mlx_qwen38_27b_shapes.py`: the QQQ dynamic-input oracle narrowed BF16
  activations to FP16 and cast the epilogue early, which #4537/#4534 no longer
  do. Consume the resident inputs, cast once, and allow one output ULP of the
  activation dtype (8e-3 bf16 / 2e-3 fp16).
- `test_mlx_qqq_quantization.py`: `scale_extra` is fitted to the produced
  codes, so a documented one-step tie flip moves it by at most one group
  scale. Compare exactly on rows without code drift, bound the drift elsewhere,
  and require the exported scale to describe the emitted codes.
- `test_mlx_awq_variants.py`: the Torch GEMV_FAST/LLM_AWQ sources require
  group_size 128 and 128-aligned out_features (#3717); fall back to the MLX
  holder as the packed source for the combinations the Torch contract rejects,
  and allow one activation-dtype ULP (bf16 is 2**-7 relative, not 2e-3).
- `test_mlx_foem_quantization.py`: native processors read routing metadata from
  `NamedModule`, so wrap the probe layer.
- `test_mlx_qqq_processor.py`: `__init__` records the requested backend; set
  `BACKEND.AUTO` so the portable Torch holder is the expected macOS choice.
- `test_mlx_dense_methods.py` / `test_mlx_method_selection.py`: the MLX BNB
  holder reuses `BitsAndBytesLinear`'s dependency probe, so skip without
  `bitsandbytes` installed instead of failing on the import.

Full MLX suite (tests/test_*mlx*.py tests/test_q4_torch_apple.py
tests/test_pack_block_batched.py): 5377 passed, 83 skipped, 5 failed. The five
failures need `/monster/data/model/...` checkpoints that are absent here
(`test_mlx_generate` and the four `test_q4_torch_apple` generation tests) and
are unrelated to these changes.

* test(mlx): pin idempotent re-export of the Gemma 3 split

`normalize_mlx_rope_config` mutates in place and runs on every export, so a
config that was already translated must not accumulate `rope_scaling` or lose
`rope_local_base_freq` on the second pass. The existing idempotency test only
covered the flat Llama path; cover the split mapping too.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant