Skip to content

Commit 0f1fc0c

Browse files
justinchubyCopilot
andauthored
feat(deepseek-v4): default-off native CompressedSparseAttention (HCA ratio-128) export [C1, DRAFT] (#593)
## Summary **Slice C1** of the DeepSeek-V4-Flash CSA/HCA custom-kernel path. Adds a **default-off, property-gated** Mobius exporter feature that emits the already-merged frozen `pkg.nxrt::CompressedSparseAttention` v1 op (**ratio-128 "Heavily Compressed Attention"** subset) for property-matching layers, replacing the zero-valued *shape-anchor* preservation with **real op dataflow** and **threaded compressed state IO**. This is **exporter-only**. No onnx-genai runner/KV changes; **no PagedAttention-compatibility claim**. Design: `deckard-deepseek-v4-csa-hca-cuda-slice.md` (§5 property ABI, §8 tiny-test spec, §10 C1 slice). ## What changed - **`mobius.models._deepseek_v4_csa`** (new): `plan_native_csa` property gate + `emit_hca_attention` op emission. The gate matches native-op **properties** (compression ratio, block size, head/latent/rope dims, dtype, carry planes), **not** a model-name/shape allowlist. - **`ArchitectureConfig.native_csa: bool = False`** — export-time opt-in (no HF equivalent; `config_overrides={"native_csa": True}`). - **`DeepSeekV4Attention._forward_native_hca`** — emits the 11-input / 3-output op with pre-rotated `query`/`current_kv` (dense sliding-window ring over the existing dense KV IO), real *unrotated* compressor activations, f32 casts for the f32-cache-format op inputs, and threaded `past_*`/`present_*` compressed state. The shared inverse RoPE + output projection run unchanged on `Y`. - **`DeepSeekV4Task`** — threads deterministic `past_compressed_kv.{i}` / `past_compression_carry.{i}` inputs and `present_*` outputs (explicit shapes, since the custom op has no Python shape inference), with a **dynamic record axis** and **fixed carry planes** so present state chains back into past inputs for **≥16 decode steps**. ## Fail-closed (never silent dense) Requesting native CSA for **ratio-4 CSA**, an **MTP** layer, **quantized** compressor weights, or an **unknown ratio** raises `NativeCsaExportError`. Ratio-0 dense layers and feature-off legitimately return `None` (dense) — those are not a suppressed fallback. ## Off = byte-identical With the feature off, the exported graph is **byte-identical** to the existing dense correctness export (verified) and emits **zero `pkg.nxrt` ops / no compressed IO**. ## Tests (shape-faithful / structural — no weight download, no ORT run) The frozen op has no Python shape inference and no Rust EP in the Python env, so tests assert structure: exact op attrs + 11/3 IO, threaded compressed-state IO names/shapes/dtypes, decode chainability, **f32 inputs under a FLOAT16 model dtype** (GLM DSA precedent), **no dead anchor** for the HCA layer, byte-identical disabled baseline, defaults-off + opt-in, and typed rejects (ratio-4 / quantized / MTP / unknown-ratio). Existing DeepSeek-V4 tests unchanged. Local validation (this env): - `deepseek_v4_flash_test.py` + `deepseek_v4_test.py`: **30 passed** - `_configs`/`tasks`/`glm_moe_dsa` related tests: **168 passed** - `ruff check` + `ruff format --check`: clean ## Scope / non-goals - ❌ No onnx-genai runner or KV/cache changes (later slice). - ❌ No PagedAttention-compatibility claim. - ❌ ratio-4 learned-indexer/top-k selection is a follow-up slice. ## Status **DRAFT — stop for independent review. Do not merge.** CI is async; local tests above are the validation of record. --------- Co-authored-by: Copilot <[email protected]>
1 parent 59a595e commit 0f1fc0c

5 files changed

Lines changed: 2045 additions & 43 deletions

File tree

‎src/mobius/_configs/_base.py‎

Lines changed: 52 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
import dataclasses
77
import math
8+
from typing import TYPE_CHECKING
89

910
import onnx_ir as ir
1011
import torch
@@ -22,6 +23,9 @@
2223
VisionConfig,
2324
)
2425

26+
if TYPE_CHECKING:
27+
from mobius.integrations._block_quant import BlockQuantScheme
28+
2529
DEFAULT_INT = -42
2630

2731

@@ -494,6 +498,17 @@ class ArchitectureConfig(BaseModelConfig):
494498
num_hash_layers: int = 0
495499
swiglu_limit: float = 0.0
496500
num_nextn_predict_layers: int = 0
501+
# DeepSeek-V4 native compressed-sparse-attention export toggle. Not an
502+
# upstream HF field -- a Mobius export-time opt-in (default False) that
503+
# replaces the dense CSA/HCA correctness fallback with the frozen
504+
# ``pkg.nxrt::CompressedSparseAttention`` v1 op for property-matching
505+
# ratio-128 (HCA) layers. Off by default so every shipped graph stays
506+
# byte-identical and ``pkg.nxrt``-free unless explicitly requested via
507+
# ``config_overrides={"native_csa": True}``. When requested, layers that
508+
# do not satisfy the frozen op contract raise a typed export error rather
509+
# than silently emitting the dense fallback (see
510+
# ``mobius.models._deepseek_v4_csa``).
511+
native_csa: bool = False
497512

498513
# GLM-5.2 (``glm_moe_dsa``) DeepSeek Sparse Attention (DSA).
499514
#
@@ -626,7 +641,16 @@ class ArchitectureConfig(BaseModelConfig):
626641
codec_decoder: CodecDecoderConfig | None = None
627642
codec_encoder: CodecEncoderConfig | None = None
628643
quantization: QuantizationConfig | None = None
629-
644+
# Deferred block-scaled FP8 / packed-FP4 scheme (DeepSeek-V4-Flash native
645+
# CSA). Recorded by ``from_transformers`` when ``native_csa`` opts into
646+
# deferring #602's config-resolution block-quant reject so that graph
647+
# construction can progress past the former generic weight-shape mismatch.
648+
# The runtime-capability gate
649+
# (``mobius.models._deepseek_v4_csa.assert_native_runtime_supports_block_quant``)
650+
# then fails closed on the *runnable* full export until nxrt advertises real
651+
# block-FP8 / planar-FP4 format strings. ``None`` for every ordinary,
652+
# per-tensor-fp8, or non-native path.
653+
block_quant_scheme: BlockQuantScheme | None = None
630654
# HuggingFace model_type and special token IDs — populated by from_transformers()
631655
# so that genai_config.json can be written without re-fetching the HF config.
632656
model_type: str | None = None
@@ -969,6 +993,11 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
969993
),
970994
swiglu_limit=getattr(config, "swiglu_limit", 0.0),
971995
num_nextn_predict_layers=getattr(config, "num_nextn_predict_layers", 0),
996+
# DeepSeek-V4 native CSA/HCA export opt-in. No HF equivalent --
997+
# every checkpoint defaults to the dense correctness fallback;
998+
# ``config_overrides={"native_csa": True}`` opts a build into the
999+
# frozen ``pkg.nxrt::CompressedSparseAttention`` v1 ratio-128 path.
1000+
native_csa=getattr(config, "native_csa", False),
9721001
# GLM-5.2 DSA. ``use_dsa`` has no HF equivalent -- every checkpoint
9731002
# defaults to the sparse path; ``--glm-full-attention`` overrides
9741003
# it afterwards via ``dataclasses.replace``/``config_overrides``.
@@ -1197,8 +1226,28 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
11971226
if resolved is not None:
11981227
options["dtype"] = resolved
11991228

1200-
# Quantization config
1201-
quant = QuantizationConfig.from_transformers(config)
1229+
# Quantization config. Block-scaled FP8 / packed-FP4 checkpoints
1230+
# (DeepSeek-V4-Flash) are rejected here by #602's typed
1231+
# ``BlockQuantExportError`` (the INT4/per-tensor path cannot load them).
1232+
# For a native-CSA export we *defer* that reject so graph construction
1233+
# can progress past the former generic weight-shape mismatch; the
1234+
# runtime-capability gate
1235+
# (``mobius.models._deepseek_v4_csa.assert_native_runtime_supports_block_quant``,
1236+
# invoked at weight-load / full-export) then fails closed until nxrt
1237+
# advertises real block-FP8 / planar-FP4 format strings. Every non-native
1238+
# path keeps #602's early, loud reject.
1239+
from mobius.integrations._block_quant import (
1240+
BlockQuantExportError,
1241+
BlockQuantScheme,
1242+
)
1243+
1244+
try:
1245+
quant = QuantizationConfig.from_transformers(config)
1246+
except BlockQuantExportError:
1247+
if not getattr(config, "native_csa", False):
1248+
raise
1249+
options["block_quant_scheme"] = BlockQuantScheme.from_hf_config(config)
1250+
quant = None
12021251
if quant is None and parent_config is not None:
12031252
quant = QuantizationConfig.from_transformers(parent_config)
12041253
if quant is not None:

0 commit comments

Comments
 (0)