Skip to content

Add DeepSeek-V4.1-Flash - #50919

Open
Rocketknight1 wants to merge 17 commits into
mainfrom
add-deepseek-v41
Open

Rocketknight1 wants to merge 17 commits into
mainfrom
add-deepseek-v41

Conversation

@Rocketknight1

@Rocketknight1 Rocketknight1 commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

🤗 Transformers CI

Big remaining questions

  1. The Engram token map needs the tokenizer to build. So either the model includes the tokenizer, or we precompute the token map as a tensor and add it to the checkpoint. The second option might break model loading in other frameworks so we might need to put it in extra_files like Jev or something. What should we do?
  2. Layer naming for KV sharing. We have config.text_config.kv_sharing_modes but we need a new mode for Deepseek (similar to the one added for Mistral) where each layer has its own sliding window but also attends to a global KV cache that's shared between layers
  3. The engram weights are FP8 with a scale for every 32 values of a row, which our current FP8 quantization in the library doesn't support. We can either expand the weights up to BF16, or update the core quantization configs to allow the correct FP8 quants.
  4. I dropped assisted generation with DSpark because the DSpark PR is still open, we could consider adding it later

Also, even without 1, we still need a Hub PR. The checkpoint has no preprocessor_config.json or processor_config.json, so AutoProcessor can't load it.

Fixes #48755

🤖 mlinter review state

@Rocketknight1 Rocketknight1 changed the title Add DeepSeek-V4.1 Add DeepSeek-V4.1-Flash Nov 18, 2026
github-actions[bot]

This comment was marked as resolved.

@HuggingFaceDocBuilderDev

HuggingFaceDocBuilderDev commented Nov 18, 2026 •

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Pages changed in this PR:

github-actions[bot]

This comment was marked as resolved.

@github-actions

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: auto, deepseek_v41, finegrained_fp8

@Rocketknight1
Rocketknight1 marked this pull request as ready for review November 27, 2026 16:09
The compressor read its pooling weights straight off its submodules to promote them to float32, so with
offloaded weights it pooled uninitialized memory. The promotion now happens inside the projection itself.
The `shared_states` dict also has to skip device placement, or every layer gets its own copy of it.

`get_image_features` now returns a model output with the vision encoder's hidden states and attentions,
the forwards take the deprecated `past_key_values`, and the tests check the shapes that the compressed KV
and the hyper-connection streams really have.
The four attention classes are now one class that branches on the layer
type, like DeepSeek-V4 does, so there is no subclass chain and no class
dict any more.

The model owns the only rotary embedding. It computes the RoPE of the
compressed entries for each compress ratio and passes it down, instead of
the compressing attention layers building a rotary module each.

`set_engram_token_map` is a single method on the PreTrainedModel instead
of one per model class. It still needs a linter ignore: it fills a saved
buffer that the checkpoints leave out, not a hyperparameter.

Also merges main, which dropped `keys_to_ignore_at_inference` from the
parent config.
The layers now return the states that the KV-sharing layers read, instead
of writing them into a dict shared by the whole stack. The backward replay
of a checkpointed layer reads the same states as its first run, so
checkpointing works with use_reentrant=False. use_reentrant=True raises,
because it would silently drop the gradient of the shared compressed KV.

Also skips the inputs_embeds tests (the Engram layers need token ids),
moves the tester values into small_config_overrides, and skips the base
model in test_reverse_loading_mapping.
The image processor follows the original preprocessing: each image keeps
its aspect ratio, is resized to whole 14x14 patches within the min-pixel
and max-token limits, and is padded with gray. It resizes with torchvision
where the original uses PIL, so the sizes and the padding are identical,
but resampled pixel values can be off by a level or two out of 255.

The processor repeats the image placeholder once for every position that
the image takes up in the prompt. The model is also registered for
image-text-to-text.
The grid input is now `image_grid_thw`, the name that most models with
native-resolution images use and that the common tests know about. An
image is one frame, so the temporal size is always 1, and the model raises
on anything else. The common chat template test now runs as it is, so its
override in the processor tests is gone.

`resize_token_embeddings` raises an error. The Engram token map and the
n-gram tables are fixed to the vocabulary of the checkpoint, so a new
token would have no entry in them. The common resize tests are disabled
with `test_resize_embeddings = False`.
The sinks, the hyper-connections and the router biases are listed in
`_keep_in_fp32_modules_strict`, but only `from_pretrained` enforces that
list. A model built straight from a config got them in the default dtype,
which the common test from #50975 now catches. They are created in
float32 in their `__init__` instead.
`generate` repeats its inputs once per beam, and `pixel_values` has a row
per patch, so every beam got the patches of a scrambled image. The model
now takes `mm_encoder_outputs`, so `generate` encodes the images once and
repeats whole images, and it returns the multimodal outputs with
`image_outputs`. The `prepare_inputs_for_generation` override is gone.
The new beam test fails on the old code: the common beam tests only check
output shapes.

The tests move from `CausalLMModelTester` to `VLMModelTester`, like the
other VLMs, so the common tests run with an image in every prompt. The
image token is an id inside the tester's vocab, and the text ids are drawn
from above the special tokens.
The reference implementation rounds the KV and the attention output to
FP8, and the index keys, the index queries and the compressed KV to FP4,
because that is how they were quantized in training. `fake_quantize` does
the same at the same five places: the values are rounded but keep their
dtype, and the gradient goes straight through. The block widths have to
be multiples of 32, which the text config now validates.

The rounding matches the cast to `float8_e4m3fn` of PyTorch and a plain
reading of the reference kernels, but it has not been compared with the
TileLang kernels themselves.

With rounding in the model, two ways of computing the same logits can
differ by a rounding step instead of by float noise, so our own
comparison tests use a tolerance of 1e-2 from one class attribute. The
common tests pass as they are.
The compressor pooled consecutive tokens before the attention mask
applied, so left padding shifted the groups and folded pad tokens into
the compressed KV. It now moves the real tokens of each row to the front
before pooling, so the groups are counted from the first real token of a
row. The compressed entries are left-aligned: the cache writes the new
entries of each row at that row's own offset, and keeps the last
`ratio - 1` real tokens of a row for its next group. An entry is rotated
at the position id of its group, and the indexer hides entries by
counting real tokens instead of reading `position_ids`.

`forward` still defaults `position_ids` to an `arange`, like the rest of
the library. The KV are rounded after RoPE, so the model is not
indifferent to a shift of the positions, and a direct call on a padded
batch has to pass the positions that `generate` makes.

The common left padding test is no longer skipped. It hardcoded a
tolerance of 1e-5, so it now takes `atol` and `rtol` like
`test_batching_equivalence` does, and we pass the 1e-2 that our other
comparison tests use. A new test covers padding with a cache, in chunks
and token by token.
…-from-inputs_embeds test, and refresh the model card date

This branch has not been deployed

No deployments
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.

Add DeepSeek-V4.1-Flash (deepseek_v41)

2 participants