Skip to content

feat(leapquant): add recurrent-state quantization - #6044

Draft
ZX-ModelCloud wants to merge 2 commits into
mainfrom
feat/leapquant-support
Draft

ZX-ModelCloud wants to merge 2 commits into
mainfrom
feat/leapquant-support

Conversation

@ZX-ModelCloud

@ZX-ModelCloud ZX-ModelCloud commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Add opt-in LeapQuant quantization for the fixed-size recurrent state of delta-rule linear attention in Kimi K3 KDA, dense Qwen3.5 GDN, and GLM-5.3 KDA.

LeapQuant is not a weight format: model weights, checkpoints, and quant_method are unchanged, and it composes with weight quantization in the supported model ports. The feature is off by default and is selected through LeapQuantConfig on GPTQModel.load(..., state_quant=...) or model.enable_state_quant(...).

What Changed

  • gptqmodel/utils/leapquant.py: LeapQuantConfig, LeapQuantState, per-window quantization, Compensator Tokens, residual smoothing, packed-state save/restore, storage accounting, atomic reorder, and a portable Torch path.
  • gptqmodel/models/ports/kimi_k3/modeling_kimi_linear.py: KDA cache ownership, prefill/decode integration, reset, reorder, offload, and fail-closed guards.
  • gptqmodel/models/ports/native/qwen3_5/modeling_qwen3_5.py: GDN cache layer and quantized decode, including grouped key/value heads.
  • gptqmodel/models/ports/native/glm5_next/modeling_glm5_next.py: KDA cache layer and quantized decode.
  • gptqmodel/models/auto.py and gptqmodel/models/base.py: state_quant= load argument and enable_state_quant.
  • gptqmodel/__init__.py: export LeapQuantConfig.
  • docs/leapquant.md, docs/README.md, docs/support-matrix.md: flow, before/after table, storage, constraints, and the portable-path caveat.
  • tests/test_leapquant_state.py, tests/test_leapquant_models.py: FP32 oracle and model integration coverage.

Out of scope in this PR:

  • Native CUDA/Triton kernels. The portable path is a correctness and memory baseline, not a throughput claim.
  • Packed 4/6-bit containers. 4/6-bit accuracy is supported, but both currently use the int8 code container.
  • Prefix-cache sharing and speculative decode.

Review fixes

  • Qwen3.5 and GLM-5.3 generation select the decoder's LeapQuant cache. Kimi K3 decodes with the checkpoint's gate bias layout.
  • Generated and direct forwards check packed-cache inputs before the first cache write. Mixed caches reject crop and live batch expansion before changing any layer. Offloaded reordering uses the tensors' storage devices.
  • Packed restore checks snapshot metadata and tensors before replacing live state. The compensator uses FP32 arithmetic, and a failed window update preserves the state for retry.

Tests

python -m pytest tests/test_leapquant_state.py tests/test_leapquant_models.py tests/test_qwen3_5_moe_multimodal_support.py tests/test_glm5_flash_core.py tests/test_glm5_next_support.py tests/test_model_port_policy.py tests/test_transformers_unpatched.py tests/test_docs_contract_refs.py -q -ra --tb=short
python -m pytest tests/test_kimi_k3_local_port.py -q -ra --tb=short
bash format/check.sh
git diff --check

The first suite passed all 155 cases, including 80 LeapQuant cases. The Kimi port suite passed 133 cases and skipped 13 cases that require pinned tokenizer fixtures. The format and diff checks passed.

Regression Before the fix After the fix
test_generate_uses_packed_recurrent_state Qwen3.5 and GLM-5.3 generated with a dense cache. Kimi K3 raised on the first single-token decode. The models generate with populated packed caches and match the dense fixture tokens.
test_qwen_grouped_key_heads_quantized_decode Grouped query shape did not match the packed value-head count. Key/query heads expand in the delta-rule kernel's order.
test_padded_decode_fails_before_cache_updates The single-token padding mask was discarded before validation. Invalid padding raises and the live cache remains usable.
test_unsupported_cache_operation_preserves_attention_prefix and test_offloaded_cache_reorder_preserves_next_token Crop and expansion could change an earlier layer. Reorder could index offloaded convolution state on the wrong device. Invalid operations preserve the prefix. Valid reorder, prefetch, and continuation match the resident cache.
test_failed_step_preserves_live_window_for_retry, test_compensator_stays_fp32_under_autocast, and test_packed_restore_validates_before_replacing_live_state Low-precision overflow or a malformed snapshot could poison the next decode. FP32 math and validation preserve live state across rejected updates and restores.

Measured Impact

No speedup is claimed. On a synthetic decode fixture, the portable Torch path is slower than the dense FP32 recurrence; the paper's speedups depend on specialized kernels, which are a separate follow-up.

Accuracy coverage:

Check Result
8-bit Kimi K3 / Qwen3.5 model parity max absolute logit difference below 1e-3
8-bit GLM-5.3 model parity max absolute hidden-state difference below 1e-2
Core oracle 4/6/8-bit, window boundaries, rank 0/full, smoothing, packed-state round trip, atomic reorder, non-finite rejection
Storage packed checkpoint plus window buffer counted by storage_bytes()

Model Support / Module Plan

Not applicable: this PR adds no MODEL_MAP entry, model definition, alias, or module-plan change. It adds an opt-in runtime cache policy to existing ports.

AWQ onboarding safety

Not applicable: no model onboarding or AWQ grouping/search/replay/fold change.

Logic Flow Documentation

Documentation page: docs/leapquant.md, linked from docs/README.md. It contains the flow, the before/after table, storage accounting, constraints, and validation details.

flowchart TD
    A[Generate with caching] --> B{Caller supplies cache}
    B -->|Yes| C[Keep the caller cache]
    B -->|No| D{Decoder enables LeapQuant}
    D -->|No| E[Build the port's dense cache]
    D -->|Yes| F[Build the port's LeapQuant cache]
    C --> G[Model forward]
    E --> G
    F --> G
    G --> H{Packed recurrent state}
    H -->|No| I[Run the dense recurrence]
    H -->|Yes| J{Unpadded and unpacked input}
    J -->|No| K[Raise before updating cache]
    J -->|Yes| L[Run packed prefill or decode]
Loading
flowchart TD
    A[Decode token] --> B{State policy}
    B -->|off| C[Existing delta-rule kernel]
    C --> D[Dense recurrent state]
    B -->|LeapQuant| E[Packed checkpoint + window buffer]
    E --> F[Replay buffered records]
    F --> G[Compute output and new update]
    G --> H{Window boundary}
    H -->|no| I[Buffer record]
    H -->|yes| J[Fit Compensator and quantize residual]
    J --> E
Loading
Area Before After (LeapQuant enabled)
Generation cache The generation framework creates the default dense cache for Qwen3.5 and GLM-5.3. The decoder's LeapQuant policy selects a packed recurrent cache before the first forward.
Decode state KimiDeltaAttention, Qwen3_5GatedDeltaNet, and Glm5NextTextLinearAttention read and rewrite a dense recurrent tensor through the cache layer. The cache layer owns a LeapQuantState; decode replays the packed checkpoint and buffered records, then re-quantizes at the window boundary.
Cache ownership A Transformers LinearAttentionLayer or KimiDeltaCacheLayer stores the dense recurrent tensor. LeapQuantLinearAttentionLayer or KimiDeltaCacheLayer(state_quant=...) stores int8 codes, scales, Compensator factors, and the window buffer; the dense slot stays empty.
Prefill The port kernel writes the final dense state. The same dense kernel runs, then LeapQuantState.quantize_ checkpoints the final state and clears the window.
Invalid cache inputs Ports process input masks and cache operations for their dense recurrence. The packed path rejects padding, packed sequence boundaries, crop, and live batch expansion before updating the cache.
Default Dense FP32 recurrent state. Unchanged: state_quant=None returns the original cache and kernel path.

Review Requirements

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Kernel Accuracy Requirements

  • Accuracy was measured against an FP32 oracle for the quantizer, and model parity tests compare the quantized path with the existing dense kernels.
  • Fusion support is not changed; the existing AUTO native kernel selection is untouched.
  • No new kernel is added in this PR, so there is no new kernel inventory or device report. Native kernels remain an explicit follow-up.

Notes

  • The packed checkpoint is int8 codes plus FP32 scales and FP16 Compensator factors; the window buffer is counted in storage.
  • 4/6-bit modes use the same int8 container in this PR; packed storage is a follow-up.
  • The portable decode path materializes a transient dense FP32 state per step for correctness and releases it immediately; it is not retained.
  • The option must be set before the first forward. An already-created recurrent cache keeps its original policy.

@ZX-ModelCloud ZX-ModelCloud changed the title feat(leapquant): add clean-room recurrent-state quantization feat(leapquant): add recurrent-state quantization Nov 24, 2026
@ZX-ModelCloud
ZX-ModelCloud force-pushed the feat/leapquant-support branch 2 times, most recently from d8a5474 to 658b675 Compare November 24, 2026 08:29
Add an opt-in runtime quantizer for the recurrent state of delta-rule linear attention. It is not a weight format: weights, checkpoints, and quant_method are unchanged.

- Add LeapQuantConfig/LeapQuantState with per-window packed state, Compensator Tokens, residual smoothing, and a portable Torch path.
- Integrate Kimi K3 KDA, Qwen3.5 GDN, and GLM-5.3 KDA through package-owned cache layers; no Transformers patching.
- Add GPTQModel.load(state_quant=...) and enable_state_quant.
- Add FP32 oracle tests and model parity tests.
- Document the flow, storage, constraints, and the portable-path performance caveat.

- Expand grouped GDN key heads to their value-head groups and cover the path with a regression.

@ZX-ModelCloud ZX-ModelCloud left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in db2b809ab. Qwen3.5 and GLM-5.3 now use the packed cache in generate(), and Kimi K3 decodes with the checkpoint's gate layout. Regression tests cover padding, offloaded reorder, and recovery from invalid cache updates. All 80 LeapQuant tests and format/check.sh passed.

if self._leapquant is not None:
self._leapquant.reset()

def reorder_cache(self, beam_idx: torch.Tensor) -> None:
Comment on lines +846 to +848
def _prepare_cache_for_generation(
self, generation_config, model_kwargs, generation_mode, batch_size, max_cache_length,
):
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