Skip to content

Commit 62d7ebd

Browse files
committed
DeepSeek-V4.1: fix padded compression, bare quantized loads and cache rollback
1 parent 754bc79 commit 62d7ebd

7 files changed

Lines changed: 725 additions & 298 deletions

File tree

‎docs/source/en/model_doc/deepseek_v41.md‎

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -134,15 +134,15 @@ accepts this layout as-is:
134134
* with `dequantize=False` (GPU) the attention projections become `FP8Linear` / `FP8GroupedLinear` (the grouped
135135
`o_a_proj`) and the routed experts an `FP8Experts` holding the packed int8 `gate_up_proj` / `down_proj` with their
136136
`[1, 32]` ue8m0 scales (`gate_up_proj_scale_inv` / `down_proj_scale_inv`). `FP8Experts` sizes that packed layout
137-
from `text_config.expert_dtype`, which the composite config hoists from the released config.json's
137+
from `text_config.expert_dtype`, which the configuration loaders preserve from the released config.json's
138138
`quantization_config.expert_dtype = "fp4"`. The bf16 projections without a `.scale` (`compressor.kv_proj`,
139139
`compressor.gate_proj`, `indexer.k_proj`, `indexer.weights_proj`) are auto-skipped by the quantizer
140140
(`_keep_in_fp32_modules`), like V4's.
141141

142-
`DeepseekV41ForCausalLM` takes the composite [`DeepseekV41Config`] (`config_class`) because the released
143-
config.json nests the text backbone under `text_config` and puts `quantization_config` at the top level — pointing
144-
the class at the bare text config would silently drop the quantization config and corrupt the fp8 tensors on load.
145-
The text config is unwrapped in `__init__`; instantiating with a [`DeepseekV41TextConfig`] directly also works.
142+
`DeepseekV41ForCausalLM` uses the composite [`DeepseekV41Config`]; its text configuration is unwrapped during
143+
initialization. [`DeepseekV41TextModel`] uses [`DeepseekV41TextConfig`] and preserves the outer
144+
`quantization_config` before extracting `text_config`, so the bare backbone also recognizes the released
145+
quantized checkpoint. Flat text checkpoints and direct text-config construction remain supported.
146146

147147
## Usage
148148

@@ -233,20 +233,24 @@ tokens per second of prefill).
233233
shared compressed KV / indexer keys); consumer layers read the source's cache through a per-forward `shared` dict.
234234
`DynamicCache(config=…)` builds the right layers from `config.layer_types` — the new
235235
`"shared_compressed_attention"` layer type is registered with the cache and masking utilities.
236-
* **Group state across calls.** The compressor buffers partial groups, so chunked prefill and decode are exact:
237-
a prompt fed in chunks produces the same logits as a one-shot prefill, including when a chunk boundary lands
238-
inside a group.
236+
CSA caches are not croppable: removing tokens cannot rewind the compressor's partial groups or emitted entries.
237+
Nonzero rollback requests are rejected before any cache layer is mutated; `crop(0)` retains trim-only behavior.
238+
* **Padding and group state.** Compression groups contain only live tokens from each batch row. Their first-token
239+
RoPE positions, live-token counts and partial groups follow the row through cached calls and beam operations.
240+
Chunked prefill and decode use the same groups as one-shot prefill, even when a chunk ends inside a group or
241+
contains only padding for some rows. Floating-point reduction and hard top-k boundaries can still affect
242+
numerical equivalence.
239243
* **Top-k ties.** The indexer's per-head scores are ReLU-rectified, so keys every head scores negatively tie at
240244
exactly 0.0 and `torch.topk` may order them by layout. Like DeepSeek-V3.2, cross-backend output-equivalence
241245
guarantees do not hold for this model; the equivalence tests in `tests/models/deepseek_v41` select all visible
242246
blocks to stay deterministic.
243247
* **Stale indexer keys on incomplete-group decode steps (reference deviation).** The reference reassigns the
244248
shared indexer key cache only when a latent is emitted, but scores against it unconditionally: on decode steps
245249
where no group completes, a layer scores its queries against the *last publisher's* keys — typically layer 20's,
246-
since it owns the last index-source slot. This implementation (and vLLM, MLX and llama.cpp) instead always
247-
publishes the owner layer's running key cache, so those steps read the correct owner keys. The parity harness is
248-
blind to the difference (its tiny config saturates the top-k: `index_topk` exceeds the compressed length), so
249-
this is a documented deviation, not an asserted equivalence.
250+
since it owns the last index-source slot. This implementation republishes the owning layer's running cache.
251+
The same reference fix is proposed in [DeepSeek's model PR #12](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/discussions/12).
252+
[Discussion #41](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/discussions/41) provides a reduced-model CPU
253+
reproduction and states its kernel-adaptation and numerical-validation limits.
250254

251255
## DeepseekV41Config
252256

‎src/transformers/cache_utils.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1627,6 +1627,10 @@ def crop(self, tokens_to_remove: int) -> None:
16271627
minimal working size. This means that `crop(0)` will not necessarily always be a no-op, as it may still remove useless states
16281628
(i.e. states that are not needed for the next `forward`) from the Cache.
16291629
"""
1630+
# Refuse unsupported rollback before any preceding layer is mutated.
1631+
# Zero still dispatches trim-only operations on recorded working state.
1632+
if tokens_to_remove != 0 and not self.is_croppable:
1633+
raise RuntimeError("This cache does not support rollback of its states.")
16301634
for layer_idx in range(len(self.layers)):
16311635
self.layers[layer_idx].crop(tokens_to_remove)
16321636

‎src/transformers/models/deepseek_v41/configuration_deepseek_v41.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,8 +333,20 @@ class DeepseekV41TextConfig(PreTrainedConfig):
333333
default_kv_source_layer_ids = [2, 8, 14, 20]
334334
default_index_source_layer_ids = [2, 8, 14, 20, 24, 28, 32, 36]
335335

336+
@classmethod
337+
def get_config_dict(cls, pretrained_model_name_or_path, **kwargs):
338+
config_dict, kwargs = super().get_config_dict(pretrained_model_name_or_path, **kwargs)
339+
# Preserve outer storage metadata before the base loader extracts text_config.
340+
if cls.base_config_key in config_dict and "quantization_config" in config_dict:
341+
config_dict[cls.base_config_key]["quantization_config"] = config_dict["quantization_config"]
342+
return config_dict, kwargs
343+
336344
def __post_init__(self, **kwargs):
337345
PreTrainedConfig.__post_init__(self, **kwargs)
346+
# The normalized quantizer config does not retain packed expert storage metadata.
347+
quantization_config = kwargs.get("quantization_config")
348+
if isinstance(quantization_config, dict) and "expert_dtype" in quantization_config:
349+
self.expert_dtype = quantization_config["expert_dtype"]
338350
n = self.num_hidden_layers
339351
n_nextn = self.num_nextn_predict_layers
340352

0 commit comments

Comments
 (0)