Skip to content

Commit 5028076

Browse files
justinchubyCopilot
andcommitted
feat(deepseek-v4): defer block-quant reject for native CSA, gate runnable export on nxrt runtime capability
Rebased #593 (native pkg.nxrt::CompressedSparseAttention export, ratio-4 CSA + ratio-128 HCA) onto Mobius main now that #578 (6992181) and #602 (d16cd4a, mobius.integrations._block_quant block-FP8 / packed-FP4 loading contract) are merged. Consumes the merged _block_quant API directly; the temporary stacked duplicate-parse branch is retired. #602 rejects the block-scaled-FP8 + packed-FP4 DeepSeek-V4-Flash checkpoint at config resolution (the INT4/per-tensor path cannot load it). That is correct for a normal export, but it also blocks a native-CSA export before any graph exists. Split the behavior into the two stages the directive requires: * Non-native (default) export keeps #602's early, loud config-resolution reject -- unchanged, its tests still pass. * native_csa opts into DEFERRING that reject: ArchitectureConfig.from_transformers catches the typed BlockQuantExportError, records the parsed block_quant_scheme on the config, and lets graph construction PROGRESS past the former generic "Weight shape mismatch" (build_from_module emits the CSA nodes + compressed state IO). The runnable FULL EXPORT then fails closed at a runtime-capability gate (assert_native_runtime_supports_block_quant, enforced at the top of DeepSeekV4 preprocess_weights, before apply_weights) while nxrt cannot execute block-FP8 / planar-FP4 weights. The gap string is sourced from _block_quant.runtime_representation_gap, so the gate tracks the real nxrt format strings and opens automatically when the native runtime slice lands -- no change here. Never a silent dense fallback, never partial-native. No BC shims: ArchitectureConfig gains a block_quant_scheme field; deepseek_v4.py adds no FP8/FP4 weight parsing (delegates to _block_quant). No performance claim -- ratio-4 sparse execution and >=16-decode remain blocked on the unmerged native block-FP8 / planar-FP4 runtime. Tests (deepseek_v4_flash_test.py, 45 pass): non-native fail-closed at config resolution; fp4-experts-alone owned; native_csa defers (scheme recorded, quant None); full export typed-rejects at the runtime-capability gate; graph construction progresses past block-quant (CSA node built); preprocess_weights enforces the gate; property-gated not a blanket V4/native_csa refusal; per-tensor fp8 not over-owned. #602 (_block_quant_test) + config (_base_test/_extractors_test) suites unchanged (69 pass). Co-authored-by: Copilot <[email protected]>
1 parent db491a3 commit 5028076

4 files changed

Lines changed: 435 additions & 3 deletions

File tree

‎src/mobius/_configs/_base.py‎

Lines changed: 36 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

@@ -631,7 +635,16 @@ class ArchitectureConfig(BaseModelConfig):
631635
codec_decoder: CodecDecoderConfig | None = None
632636
codec_encoder: CodecEncoderConfig | None = None
633637
quantization: QuantizationConfig | None = None
634-
638+
# Deferred block-scaled FP8 / packed-FP4 scheme (DeepSeek-V4-Flash native
639+
# CSA). Recorded by ``from_transformers`` when ``native_csa`` opts into
640+
# deferring #602's config-resolution block-quant reject so that graph
641+
# construction can progress past the former generic weight-shape mismatch.
642+
# The runtime-capability gate
643+
# (``mobius.models._deepseek_v4_csa.assert_native_runtime_supports_block_quant``)
644+
# then fails closed on the *runnable* full export until nxrt advertises real
645+
# block-FP8 / planar-FP4 format strings. ``None`` for every ordinary,
646+
# per-tensor-fp8, or non-native path.
647+
block_quant_scheme: BlockQuantScheme | None = None
635648
# HuggingFace model_type and special token IDs — populated by from_transformers()
636649
# so that genai_config.json can be written without re-fetching the HF config.
637650
model_type: str | None = None
@@ -1207,8 +1220,28 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
12071220
if resolved is not None:
12081221
options["dtype"] = resolved
12091222

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

‎src/mobius/models/_deepseek_v4_csa.py‎

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,14 @@
6868
from onnxscript import OpBuilder
6969

7070
from mobius._configs import ArchitectureConfig
71+
from mobius.integrations._block_quant import (
72+
MXFP4_MICROSCALE_BLOCK,
73+
BlockQuantExportError,
74+
BlockQuantScheme,
75+
QuantizedTensorDescriptor,
76+
QuantKind,
77+
runtime_representation_gap,
78+
)
7179

7280
# Frozen op identity -------------------------------------------------------
7381
CSA_OP_TYPE = "CompressedSparseAttention"
@@ -414,6 +422,125 @@ def plan_native_csa(
414422
return _plan_ratio4(config, layer_id, num_heads, head_dim, qk_rope_head_dim)
415423

416424

425+
# Runtime-capability gate --------------------------------------------------
426+
#
427+
# Graph construction for a native-CSA export of the block-scaled-FP8 /
428+
# packed-FP4 DeepSeek-V4-Flash checkpoint is allowed to *progress* (the
429+
# ``ArchitectureConfig`` records the deferred ``block_quant_scheme`` rather than
430+
# rejecting at config resolution), so the CSA nodes and their compressed state
431+
# IO are built and inspectable. The *runnable* full export, however, must fail
432+
# closed until the native ``nxrt`` runtime can actually execute the block-quant
433+
# weights. That capability is owned by ``mobius.integrations._block_quant``
434+
# (#602): ``runtime_representation_gap`` returns a precise ABI-gap string while
435+
# ``nxrt`` lacks a block-FP8 / planar-FP4 ``BlockFormat`` and ``None`` once the
436+
# real format strings land -- at which point this gate opens automatically with
437+
# no change here.
438+
439+
440+
def _representative_block_fp8_descriptor(
441+
scheme: BlockQuantScheme,
442+
) -> QuantizedTensorDescriptor:
443+
"""A property-faithful stand-in for a block-FP8 projection tensor.
444+
445+
Only the fields ``runtime_representation_gap`` reads for a ``BLOCK_FP8``
446+
tensor need be meaningful; the shapes are placeholders (the gate is a
447+
capability probe, not an emission).
448+
"""
449+
block = tuple(int(x) for x in scheme.weight_block_size) or (128, 128)
450+
return QuantizedTensorDescriptor(
451+
name="model.layers.*.self_attn.kv_proj.weight",
452+
kind=QuantKind.BLOCK_FP8,
453+
weight_dtype=scheme.weight_fmt or "e4m3",
454+
logical_shape=(0, 0),
455+
packed_shape=(0, 0),
456+
weight_num_bytes=0,
457+
is_routed_expert=False,
458+
is_shared_expert=False,
459+
block_shape=block,
460+
scale_dtype=scheme.scale_fmt or "ue8m0",
461+
scale_shape=(0, 0),
462+
scale_layout="2d_block",
463+
)
464+
465+
466+
def _representative_fp4_expert_descriptor(
467+
scheme: BlockQuantScheme,
468+
) -> QuantizedTensorDescriptor:
469+
"""A property-faithful stand-in for a packed-FP4 routed-expert tensor."""
470+
return QuantizedTensorDescriptor(
471+
name="model.layers.*.mlp.experts.*.gate_proj.weight",
472+
kind=QuantKind.FP4_PACKED,
473+
weight_dtype=scheme.expert_dtype or "fp4",
474+
logical_shape=(0, 0),
475+
packed_shape=(0, 0),
476+
weight_num_bytes=0,
477+
is_routed_expert=True,
478+
is_shared_expert=False,
479+
block_shape=(MXFP4_MICROSCALE_BLOCK,),
480+
scale_dtype="ue8m0",
481+
scale_shape=(0, 0),
482+
scale_layout="planar_microscale",
483+
microscale_kind="mxfp4",
484+
)
485+
486+
487+
def native_runtime_block_quant_gap(
488+
scheme: BlockQuantScheme | None, *, runtime: str = "nxrt"
489+
) -> str | None:
490+
"""Return a runtime ABI-gap string if *runtime* cannot execute *scheme*.
491+
492+
``None`` means the gate is open (either there is no owned block-quant
493+
scheme, or the runtime can now represent every family it needs). Consumes
494+
``mobius.integrations._block_quant.runtime_representation_gap`` so this gate
495+
tracks the real ``nxrt`` format strings and opens with no change here.
496+
"""
497+
if scheme is None or not scheme.is_owned:
498+
return None
499+
gaps: list[str] = []
500+
if scheme.is_block_scaled_fp8:
501+
gaps.append(
502+
runtime_representation_gap(
503+
_representative_block_fp8_descriptor(scheme), runtime=runtime
504+
)
505+
or ""
506+
)
507+
if scheme.has_packed_fp4_experts:
508+
gaps.append(
509+
runtime_representation_gap(
510+
_representative_fp4_expert_descriptor(scheme), runtime=runtime
511+
)
512+
or ""
513+
)
514+
gaps = [g for g in gaps if g]
515+
return "\n".join(gaps) if gaps else None
516+
517+
518+
def assert_native_runtime_supports_block_quant(
519+
config: ArchitectureConfig, *, runtime: str = "nxrt"
520+
) -> None:
521+
"""Full-export runtime-capability gate for a deferred block-quant scheme.
522+
523+
No-op unless ``config.block_quant_scheme`` is set (only ``from_transformers``
524+
records it, and only when ``native_csa`` deferred #602's config-resolution
525+
reject). Raises the typed :class:`BlockQuantExportError` -- fail-closed,
526+
never a silent dense fallback -- while *runtime* cannot execute the
527+
checkpoint's block-FP8 / planar-FP4 weights.
528+
"""
529+
scheme = getattr(config, "block_quant_scheme", None)
530+
gap = native_runtime_block_quant_gap(scheme, runtime=runtime)
531+
if gap is None:
532+
return
533+
raise BlockQuantExportError(
534+
"native CSA full export requires a runtime that can execute the "
535+
f"checkpoint's block-quant weights, but {runtime!r} cannot yet. Graph "
536+
"construction progressed (CSA nodes + compressed state IO are built), "
537+
"but the runnable export is blocked until the native block-FP8 / "
538+
"planar-FP4 format strings land (mobius.integrations._block_quant."
539+
"runtime_representation_gap / plan_routed_expert_bank). ABI gap:\n"
540+
f"{gap}"
541+
)
542+
543+
417544
def _register_domain(op: OpBuilder) -> None:
418545
"""Declare the ``pkg.nxrt`` opset import the ONNX checker requires.
419546

‎src/mobius/models/deepseek_v4.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
from mobius.models._deepseek_v4_csa import (
4646
CsaLayerPlan,
4747
NativeCsaExportError,
48+
assert_native_runtime_supports_block_quant,
4849
emit_csa_attention,
4950
plan_native_csa,
5051
)
@@ -1403,6 +1404,13 @@ def preprocess_weights(
14031404
self, state_dict: dict[str, torch.Tensor]
14041405
) -> dict[str, torch.Tensor]:
14051406
"""Map the official DeepSeek checkpoint names to mobius modules."""
1407+
# Full-export runtime-capability gate. When a native-CSA export deferred
1408+
# #602's block-quant reject (so graph construction could progress), the
1409+
# runnable export still fails closed here -- before any weight is
1410+
# mapped/assigned, replacing the former generic "Weight shape mismatch"
1411+
# with a typed, actionable blocker -- until nxrt advertises the real
1412+
# block-FP8 / planar-FP4 format strings. No-op on every ordinary path.
1413+
assert_native_runtime_supports_block_quant(self.config)
14061414
# Same predicate as MoELayer/_supported_qmoe_quantization so the
14071415
# repacked weights and the emitted graph never disagree.
14081416
use_qmoe = supported_qmoe_quantization(self.config.quantization) is not None

0 commit comments

Comments
 (0)