Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/source/en/_toctree.yml
Original file line number Diff line number Diff line change
Expand Up @@ -615,6 +615,8 @@
title: DeepSeek-V3.2
- local: model_doc/deepseek_v4
title: DeepSeek-V4
- local: model_doc/deepseek_v41
title: DeepSeek-V4.1
- local: model_doc/diffllama
title: DiffLlama
- local: model_doc/distilbert
Expand Down
169 changes: 169 additions & 0 deletions docs/source/en/model_doc/deepseek_v41.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
<!--Copyright 2026 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

⚠️ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.

-->
*This model was contributed to Hugging Face Transformers on 2026-11-25.*

# DeepSeek-V4.1

[DeepSeek-V4.1](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash) is a mixture-of-experts language model from
DeepSeek that also reads images. It keeps the building blocks of [DeepSeek-V4](./deepseek_v4) - a single shared KV
head, a sliding window in every layer, hyper-connections instead of plain residuals - but changes how the layers
reach beyond that window, and adds a few things on top.

If you already know DeepSeek-V4, here is what is new:

- **KV sharing.** In DeepSeek-V4, every layer that looks beyond its window compresses its own KV. Here only a few
layers do, and the layers after them attend to that same compressed KV. A layer compresses either 2 tokens into 1,
or not at all (a ratio of 1), in which case later layers share its full-resolution KV.
- **Shared, two-level selection.** An **indexer** picks the `index_topk` compressed entries that each query attends
to. Only some layers run one, and the layers in between reuse the last selection. One indexer also keeps the best
*blocks* of entries per query, and the indexers after it only choose inside those blocks.
- **Engram.** A few layers add an n-gram lookup to the residual stream: the last few token ids are hashed into a
large table, and the rows that come back are gated by how well they match the stream.
- **Images.** A ViT with 2D RoPE encodes each image at its own resolution, and a projector merges every 3x3 square of
patches into one token.

Each layer's variant is listed in `config.text_config.attention_layer_types`:

| Type | Compresses its own KV | Runs an indexer |
|---|---|---|
| `"sliding_attention"` | - | - |
| `"compressed_attention"` | yes | yes |
| `"kv_shared_indexed_attention"` | no, reads the last `"compressed_attention"` layer's | yes |
| `"kv_shared_attention"` | no | no, reuses the last selection |

## Usage

Let's make this concrete with a quick example. There is one step that most models don't need: the Engram n-grams are
hashed over a "compressed" vocabulary, where tokens that normalize alike (like `" The"` and `"the"`) share an id. The
checkpoint doesn't store that map (yet!), so you have to build it from the tokenizer once after loading the model.

```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/DeepSeek-V4.1-Flash")
model = AutoModelForCausalLM.from_pretrained("deepseek-ai/DeepSeek-V4.1-Flash", dtype=torch.bfloat16, device_map="auto")
model.set_engram_token_map(tokenizer)

messages = [{"role": "user", "content": "What is hashing an n-gram good for?"}]
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_dict=True, return_tensors="pt")
outputs = model.generate(**inputs.to(model.device), max_new_tokens=100)
print(tokenizer.decode(outputs[0, inputs["input_ids"].shape[1] :]))
```

If you forget that step, the model raises an error that tells you what to call, instead of quietly hashing with the
wrong ids.

### Images

Images go in the chat like any other content. The **processor** resizes each one to a whole number of 14x14 patches at
its own aspect ratio, and makes room for it in the prompt: one position for every 3x3 square of patches, a newline
after each row, and a delimiter at either end. A 1024x701 photo takes 444 positions, and no image takes more than 1024.

The checkpoint doesn't ship a processor config (yet!), so you build the processor from its two parts for now.

```python
import torch
from transformers import AutoModelForImageTextToText, AutoTokenizer, DeepseekV41ImageProcessor, DeepseekV41Processor

tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/DeepSeek-V4.1-Flash")
processor = DeepseekV41Processor(
image_processor=DeepseekV41ImageProcessor(), tokenizer=tokenizer, chat_template=tokenizer.chat_template
)
model = AutoModelForImageTextToText.from_pretrained(
"deepseek-ai/DeepSeek-V4.1-Flash", dtype=torch.bfloat16, device_map="auto"
)
model.set_engram_token_map(tokenizer)

messages = [
{
"role": "user",
"content": [
{"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
{"type": "text", "text": "What is in this picture?"},
],
}
]
inputs = processor.apply_chat_template(
messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
)
outputs = model.generate(**inputs.to(model.device), max_new_tokens=100)
print(processor.decode(outputs[0, inputs["input_ids"].shape[1] :]))
```

## Notes

- The model needs `input_ids` even when you pass `inputs_embeds`, because Engram hashes token ids.
- `resize_token_embeddings` is not supported, because the Engram token map and n-gram tables are fixed to the
vocabulary of the checkpoint. If you need a new token, reuse one of the placeholder tokens that the tokenizer
already has.
- Batched generation with left padding matches unpadded generation. The compressor pools consecutive tokens, so it
counts its groups from the first real token of each row. If you call the model directly on a left-padded batch,
pass `position_ids` that count from the first real token of each row too, like [`~GenerationMixin.generate`] does.
The rounding below happens after RoPE, so the model is not indifferent to a shift of the positions.
- Like the original implementation, the model rounds its KV and attention output to FP8, and its index keys, index
queries and compressed KV to FP4. That is how they were quantized in training, so it happens whatever dtype you load
the model in. The rounded values keep that dtype, so this does not make the cache any smaller (yet!).
- The checkpoint stores its experts in FP4, and its Engram tables and most of its linear layers in FP8. The Engram
tables stay in FP8 however you load the model, even with `FineGrainedFP8Config(dequantize=True)`, because they would
double in size otherwise. Their rows are rescaled as they are looked up, so this changes nothing about the outputs.
- The DSpark draft layers of the checkpoint (`mtp.*`) are not loaded.
- The image processor resizes with torchvision, while the original preprocessing uses PIL. Sizes and padding are the
same, but resampling leaves a fraction of a percent of the pixel values off by one or two levels out of 255.

## DeepseekV41Config

[[autodoc]] DeepseekV41Config

## DeepseekV41TextConfig

[[autodoc]] DeepseekV41TextConfig

## DeepseekV41VisionConfig

[[autodoc]] DeepseekV41VisionConfig

## DeepseekV41ImageProcessor

[[autodoc]] DeepseekV41ImageProcessor
- preprocess

## DeepseekV41Processor

[[autodoc]] DeepseekV41Processor
- __call__

## DeepseekV41VisionModel

[[autodoc]] DeepseekV41VisionModel
- forward

## DeepseekV41TextModel

[[autodoc]] DeepseekV41TextModel
- forward
- set_engram_token_map

## DeepseekV41Model

[[autodoc]] DeepseekV41Model
- forward

## DeepseekV41ForCausalLM

[[autodoc]] DeepseekV41ForCausalLM
- forward
- set_engram_token_map
1 change: 1 addition & 0 deletions docs/source/en/quantization/finegrained_fp8.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ These [`FineGrainedFP8Config`] parameters change how the weights and activations
| `scale_fmt` | `"float"` | Storage format of the weight scales. `"float"` stores float32 scales. `"ue8m0"` stores 1-byte power-of-two scales (`torch.float8_e8m0fnu`), as in DeepSeek-V4 checkpoints, and needs PyTorch 2.7 or later. |
| `expert_dtype` | `"fp8"` | Format of the mixture-of-experts weights. `"fp4"` loads the FP4-packed experts in DeepSeek-V4 checkpoints. |
| `modules_to_convert` | `None` | Embedding tables to load in FP8 from a pre-quantized checkpoint, matched by module name suffix. |
| `embedding_block_size` | `None` | How many consecutive values in a row of a `modules_to_convert` table share one scale, as in the Engram tables of DeepSeek-V4.1. `None` means one scale for the whole table. |

## Load a pre-quantized FP8 checkpoint

Expand Down
6 changes: 5 additions & 1 deletion src/transformers/cache_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1996,7 +1996,11 @@ def get_layer_types_and_kwargs(config: PreTrainedConfig) -> tuple[list[str], lis
elif layer_type == "chunked_attention":
layer_kwargs["sliding_window"] = layer_config.attention_chunk_size
# In this case, we need to pass the config as well to properly __init__ the layer classes
elif layer_type in ("heavily_compressed_attention", "compressed_sparse_attention"):
elif layer_type in (
"heavily_compressed_attention",
"compressed_sparse_attention",
"shared_compressed_attention",
):
layer_kwargs["config"] = layer_config
# We may need more than 1 conv/recurrent state
if layer_type in ("conv", "linear_attention", "hybrid", "hybrid_sliding"):
Expand Down
1 change: 1 addition & 0 deletions src/transformers/configuration_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
"indexed_attention", # For indexer-based attentions
"compressed_sparse_attention", # CSA, used in deepseek_v4
"heavily_compressed_attention", # HCA, used in deepseek_v4
"shared_compressed_attention", # sliding window + compressed KV shared across layers, used in deepseek_v41
"minimax_m3_sparse", # lightning-index sparse attention, used in minimax_m3_vl
"conv",
"moe", # for nemotron_h, which uses either attention, mamba or moe
Expand Down
80 changes: 80 additions & 0 deletions src/transformers/conversion_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -779,6 +779,86 @@ def _build_checkpoint_conversion_mapping():
operations=[MergeModulelist(dim=0)],
),
],
"deepseek_v41": [
# The checkpoint is flat, and we nest it under the composite model. The names inside the language model
# and the vision tower are handled by their own mappings below, which only see their own keys.
WeightRenaming(
source_patterns=r"^embed\.weight", target_patterns="model.language_model.embed_tokens.weight"
),
WeightRenaming(source_patterns=r"^norm\.weight", target_patterns="model.language_model.norm.weight"),
WeightRenaming(source_patterns=r"^head\.weight", target_patterns="lm_head.weight"),
WeightRenaming(source_patterns=r"^layers\.", target_patterns="model.language_model.layers."),
WeightRenaming(source_patterns=r"^vision\.blocks\.", target_patterns="model.vision_tower.layers."),
WeightRenaming(
source_patterns=r"^vision\.patch_embed\.proj\.", target_patterns="model.vision_tower.patch_embed."
),
WeightRenaming(source_patterns=r"^vision\.norm\.", target_patterns="model.vision_tower.norm."),
WeightRenaming(source_patterns=r"^aligner\.w1\.", target_patterns="model.multi_modal_projector.linear_1."),
WeightRenaming(source_patterns=r"^aligner\.w2\.", target_patterns="model.multi_modal_projector.linear_2."),
WeightRenaming(source_patterns=r"^image_start", target_patterns="model.image_start"),
WeightRenaming(source_patterns=r"^image_end", target_patterns="model.image_end"),
WeightRenaming(source_patterns=r"^image_newline", target_patterns="model.image_newline"),
],
"deepseek_v41_vision": [
WeightRenaming(source_patterns=r"\.attn\.wqkv\.", target_patterns=r".self_attn.qkv_proj."),
WeightRenaming(source_patterns=r"\.attn\.wo\.", target_patterns=r".self_attn.o_proj."),
WeightRenaming(source_patterns=r"\.mlp\.w1\.", target_patterns=r".mlp.gate_up_proj."),
WeightRenaming(source_patterns=r"\.mlp\.w2\.", target_patterns=r".mlp.down_proj."),
WeightRenaming(source_patterns=r"\.norm1\.", target_patterns=r".layer_norm1."),
WeightRenaming(source_patterns=r"\.norm2\.", target_patterns=r".layer_norm2."),
],
"deepseek_v41_text": [
# General mid-key renames acting on several keys
WeightRenaming(source_patterns=r"\.attn\.", target_patterns=r".self_attn."),
WeightRenaming(source_patterns=r"\.ffn\.", target_patterns=r".mlp."),
# Leaf patterns
WeightRenaming(source_patterns=r"\.attn_norm\.", target_patterns=r".input_layernorm."),
WeightRenaming(source_patterns=r"\.ffn_norm\.", target_patterns=r".post_attention_layernorm."),
WeightRenaming(source_patterns=r"\.hc_attn_fn", target_patterns=r".attn_hc.fn"),
WeightRenaming(source_patterns=r"\.hc_attn_base", target_patterns=r".attn_hc.base"),
WeightRenaming(source_patterns=r"\.hc_attn_scale", target_patterns=r".attn_hc.scale"),
WeightRenaming(source_patterns=r"\.hc_ffn_fn", target_patterns=r".ffn_hc.fn"),
WeightRenaming(source_patterns=r"\.hc_ffn_base", target_patterns=r".ffn_hc.base"),
WeightRenaming(source_patterns=r"\.hc_ffn_scale", target_patterns=r".ffn_hc.scale"),
WeightRenaming(source_patterns=r"\.attn_sink", target_patterns=r".sinks"),
WeightRenaming(source_patterns=r"\.compressor\.norm\.", target_patterns=r".compressor.kv_norm."),
WeightRenaming(source_patterns=r"\.indexer\.wq_b\.", target_patterns=r".indexer.q_b_proj."),
WeightRenaming(source_patterns=r"\.indexer\.wk\.", target_patterns=r".indexer.k_proj."),
WeightRenaming(source_patterns=r"\.wq_a\.", target_patterns=r".q_a_proj."),
WeightRenaming(source_patterns=r"\.self_attn\.wq_b\.", target_patterns=r".self_attn.q_b_proj."),
WeightRenaming(source_patterns=r"\.wkv\.", target_patterns=r".kv_proj."),
WeightRenaming(source_patterns=r"\.wgate\.", target_patterns=r".gate_proj."),
WeightRenaming(source_patterns=r"\.wo_a\.", target_patterns=r".o_a_proj."),
WeightRenaming(source_patterns=r"\.wo_b\.", target_patterns=r".o_b_proj."),
WeightRenaming(source_patterns=r"\.q_norm\.", target_patterns=r".q_a_norm."),
# The routing bias of the image tokens goes first, as the pattern for the text one is a prefix of it
WeightRenaming(source_patterns=r"\.gate\.bias_vl", target_patterns=r".gate.e_score_correction_bias_vl"),
WeightRenaming(source_patterns=r"\.gate\.bias", target_patterns=r".gate.e_score_correction_bias"),
WeightRenaming(source_patterns=r"\.shared_experts\.w1\.", target_patterns=r".shared_experts.gate_proj."),
WeightRenaming(source_patterns=r"\.shared_experts\.w2\.", target_patterns=r".shared_experts.down_proj."),
WeightRenaming(source_patterns=r"\.shared_experts\.w3\.", target_patterns=r".shared_experts.up_proj."),
# The FP8 quantizer renames every `.scale` of the checkpoint to `weight_scale_inv`, which is the name
# of the scales of an FP8 linear. The scales of an FP8 table are called `weight_scale`, so the ones
# of the Engram tables need one more rename.
# TODO: drop this after #50245, which calls the scales of a table `weight_scale_inv` as well
WeightRenaming(
source_patterns=r"\.engram\.embed\.weight_scale_inv",
target_patterns=r".engram.embed.weight_scale",
),
WeightConverter(
source_patterns=[
r"\.experts.*.w1.weight",
r"\.experts.*.w3.weight",
],
target_patterns=r"\.experts.gate_up_proj",
operations=[MergeModulelist(dim=0), Concatenate(dim=1)],
),
WeightConverter(
source_patterns=r"\.experts.*.w2.weight",
target_patterns=r"\.experts.down_proj",
operations=[MergeModulelist(dim=0)],
),
],
"glm5_next": [
WeightRenaming(
source_patterns=r"self_attn\.f_a_proj\.",
Expand Down
Loading
Loading