Skip to content

Add DeepSeek-V4.1-Flash - #50919

Draft
Rocketknight1 wants to merge 13 commits into
mainfrom
add-deepseek-v41
Draft

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

Conversation

@Rocketknight1

@Rocketknight1 Rocketknight1 commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

🤗 Transformers CI

Extremely draft PR! Do not waste time reviewing! It's going to change a lot!

Things left to do:

  • Run it with the real weights and compare against the reference. So far it has only been checked at tiny scale, against a PyTorch transcription of the reference implementation
  • DSpark. The draft layers (mtp.*) are ignored when loading, and generating with them needs [Feature] Add DSpark #49996
  • Engram token map. The checkpoint doesn't ship it, so until the Hub PR below adds it, you have to call model.set_engram_token_map(tokenizer) after loading. The setter needs a linter ignore (TRF033) to get past the structure checks, which goes away with the Hub PR
  • Hub PR for the checkpoint. It needs a preprocessor_config.json and a processor_config.json so that AutoProcessor can load it, and the precomputed token map for the Engram n-gram hashing, which removes the model -> tokenizer dependency
  • Settle the layer naming. attention_layer_types should follow whatever Split KV-sharing and rope attention variants into per-layer classes #50189 ends up with, and the Engram naming overlaps with Add Hy4-flash (hy_v4_flash) #50903. For now there is one attention class that branches on the layer type, like V4. The structure checks don't allow subclassing inside a modular file, so one class per layer type would mean writing the attention out in full four times
  • Gradient checkpointing. The layers now return the state that the KV-sharing layers read, instead of writing it into a dict shared by the whole stack, so it works with use_reentrant=False (the default). use_reentrant=True raises an error, because it would silently drop the gradient of the shared compressed KV. I'm not sure if overriding activation_checkpointing_enable is the best place for that check
  • test_reverse_loading_mapping: the renames that nest the flat checkpoint under model. only apply to the model with a head, so the test skips the base model
  • inputs_embeds without input_ids is not supported, because the Engram layers hash n-grams of token ids. Those common tests are skipped
  • The tester declares its values in small_config_overrides, which fixes test_model_tester_defaults
  • The common test failures that needed no decision: attention and cache shape expectations, 4D hidden states, the get_image_features output, the config tester on the composite config, and the past_key_values deprecation
  • Run the modeling structure checks. They pass now, with one linter ignore on the token map setter (see above). The model owns the only rotary embedding, and computes the RoPE of the compressed entries as well
  • Offloading with device_map: the compressor pooled uninitialized memory when its weights were offloaded, and each layer got its own copy of the state that the KV-sharing layers pass along
  • Router precision: the router scores are computed in float32, as in the reference
  • Image processor and processor. Torchvision only, like most recent models. The original preprocessing uses PIL, so the sizes and the padding are identical, but resampling leaves under 1% of the pixel values off by one or two levels out of 255. The model is also registered for AutoModelForImageTextToText
  • The grid input is image_grid_thw, like in most models with native-resolution images. An image is one frame, so the temporal size is always 1, and the model raises an error on anything else
  • Resizing the token embeddings is not supported, because the Engram token map and the n-gram tables are fixed to the vocabulary of the checkpoint. resize_token_embeddings raises an error, and the common resize tests are disabled. All the common tests pass now
  • Images in the common tests, and in beam search. The tests use the shared VLMModelTester now, so the common tests run with an image in every prompt. generate encodes the images once and repeats whole images for the beams, instead of repeating pixel_values row by row, which scrambled the patches
  • Activation quantization. Like the reference, the model rounds its KV and attention output to FP8, and its index keys, index queries and compressed KV to FP4, because that is how they were quantized in training. The rounding matches PyTorch's cast to float8_e4m3fn and a plain reading of the reference kernels, but it hasn't been compared with the TileLang kernels themselves
  • Left padding. The compressor pooled consecutive tokens before the attention mask applied, which is the same problem as [DeepSeekV4] Compressor does not seem to account for padding tokens when forming compressed KV blocks #45938. It now counts its groups from the first real token of each row, and pad tokens stay out of the compressed KV, so each row of a left-padded batch gets the logits it gets on its own, with a cache as well. That holds up to a rounding step of the activation quantization, so the common left padding test now takes atol / rtol (like test_batching_equivalence) and we pass 1e-2. If you call forward directly on a padded batch, you have to pass the position_ids that generate makes, because the KV are rounded after RoPE. Only checked at tiny scale so far
  • Quantized loading, for now. The checkpoint is FP8 with FP4 experts, and its quantization config doesn't mention the Engram tables (FP8 too, with a scale for every 32 values of a row) or the linears that are stored in BF16, so the model config fills those in. FP8Embedding learns block scales, so the tables stay in FP8 instead of doubling in size, even with dequantize=True. This is written against main, with TODOs to rebase it onto 🚨 [quantization] per-layer quantization plan: mixed NVFP4 + FP8 checkpoints #50245 once that merges, and loading only the experts quantized has to wait for 🚨 [quantization] per-layer quantization plan: mixed NVFP4 + FP8 checkpoints #50245 as well. Only checked at tiny scale, on a checkpoint rewritten in the layout of the real one: the weights load to the right values, but I haven't run the FP8 / FP4 kernels on them

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.

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.
@github-actions

Copy link
Copy Markdown
Contributor

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

run-slow: auto, deepseek_v41, finegrained_fp8

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