diff --git a/docs/source/en/_toctree.yml b/docs/source/en/_toctree.yml index 7e33e3323ef5..a0766ad9c7df 100644 --- a/docs/source/en/_toctree.yml +++ b/docs/source/en/_toctree.yml @@ -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 diff --git a/docs/source/en/model_doc/deepseek_v41.md b/docs/source/en/model_doc/deepseek_v41.md new file mode 100644 index 000000000000..861c0a71b6e3 --- /dev/null +++ b/docs/source/en/model_doc/deepseek_v41.md @@ -0,0 +1,169 @@ + +*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 diff --git a/docs/source/en/quantization/finegrained_fp8.md b/docs/source/en/quantization/finegrained_fp8.md index b7b963518b2d..e467a140fd0f 100644 --- a/docs/source/en/quantization/finegrained_fp8.md +++ b/docs/source/en/quantization/finegrained_fp8.md @@ -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 diff --git a/src/transformers/cache_utils.py b/src/transformers/cache_utils.py index 808ee353fb21..cc6fd5d010ec 100644 --- a/src/transformers/cache_utils.py +++ b/src/transformers/cache_utils.py @@ -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"): diff --git a/src/transformers/configuration_utils.py b/src/transformers/configuration_utils.py index 1a494eb4bcc0..14f7cf9b8c30 100755 --- a/src/transformers/configuration_utils.py +++ b/src/transformers/configuration_utils.py @@ -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 diff --git a/src/transformers/conversion_mapping.py b/src/transformers/conversion_mapping.py index 8cd56149f42f..928acbc2040f 100755 --- a/src/transformers/conversion_mapping.py +++ b/src/transformers/conversion_mapping.py @@ -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\.", diff --git a/src/transformers/integrations/finegrained_fp8.py b/src/transformers/integrations/finegrained_fp8.py index acc4d418fc15..80e136466503 100644 --- a/src/transformers/integrations/finegrained_fp8.py +++ b/src/transformers/integrations/finegrained_fp8.py @@ -447,27 +447,54 @@ def forward(self, input: torch.Tensor) -> torch.Tensor: class FP8Embedding(nn.Embedding): - """`nn.Embedding` whose table is stored in FP8 with a single per-tensor `weight_scale`. + """`nn.Embedding` whose table is stored in FP8, with its scales in `weight_scale`. Qwen4-Exp's hashed n-gram table is ~48 GiB in FP8, too big to dequantize at load time, so the rescale runs on the rows a lookup gathers instead. Build it on the `meta` device: like `FP8Linear`, `__init__` lets `nn.Embedding` allocate a full-precision table first. + + The table has a single scale by default. With `block_size`, each row has a scale of its own for every + `block_size` values in a row, which is how DeepSeek-V4.1 stores its Engram tables. """ + # TODO: rebase this on #50245 once it is merged. It renames `weight_scale` to `weight_scale_inv` and moves + # the module swap into the quantizer's `quantized_module`. `block_size` and `scale_fmt` should then come from + # the plan entry of the table (its `weight_block_size`) rather than from `embedding_block_size`. def __init__( self, num_embeddings: int, embedding_dim: int, padding_idx: int | None = None, + block_size: int | None = None, + scale_fmt: str = "float", ): super().__init__(num_embeddings, embedding_dim, padding_idx=padding_idx) + self.block_size = block_size self.weight = nn.Parameter(torch.empty(num_embeddings, embedding_dim, dtype=_FP8_DTYPE), requires_grad=False) - # `(1,)` rather than a scalar: the shape checkpoints serialize per-tensor scales with. - self.weight_scale = nn.Parameter(torch.ones(1), requires_grad=False) + if block_size is None: + # One scale for the whole table. `(1,)` rather than a scalar: the shape checkpoints serialize + # per-tensor scales with. + self.weight_scale = nn.Parameter(torch.ones(1), requires_grad=False) + elif embedding_dim % block_size != 0: + raise ValueError( + "An FP8 table with block scales needs rows that divide into whole blocks, but got " + f"embedding_dim={embedding_dim} and block_size={block_size}." + ) + else: + # One scale per block of each row, in the format the scales of the linears use + scale_dtype = _get_ue8m0_dtype() if scale_fmt == "ue8m0" else torch.float32 + self.weight_scale = nn.Parameter( + torch.empty(num_embeddings, embedding_dim // block_size, dtype=scale_dtype), requires_grad=False + ) def forward(self, input: torch.Tensor) -> torch.Tensor: rows = super().forward(input) - return rows.to(self.weight_scale.dtype) * self.weight_scale + if self.block_size is None: + return rows.to(self.weight_scale.dtype) * self.weight_scale + # We gather the scales of the same rows, and each one covers `block_size` values. The product is + # computed in float32 because `ue8m0` scales cannot be multiplied directly. + scales = F.embedding(input, self.weight_scale).to(torch.float32) + return rows.to(torch.float32) * scales.repeat_interleave(self.block_size, dim=-1) class FP8GroupedLinear(FP8Linear): @@ -916,7 +943,13 @@ def _disable_deepgemm_on_multi_device(model: nn.Module) -> None: ) -def replace_with_fp8_embedding(model, patterns: list[str], modules_to_not_convert: list[str] | None = None): +def replace_with_fp8_embedding( + model, + patterns: list[str], + modules_to_not_convert: list[str] | None = None, + block_size: int | None = None, + scale_fmt: str = "float", +): """Swap every `nn.Embedding` whose name ends with one of `patterns` for `FP8Embedding`. Also runs under `dequantize=True`: a table worth quantizing is one we cannot afford to expand. @@ -926,7 +959,13 @@ def replace_with_fp8_embedding(model, patterns: list[str], modules_to_not_conver if not should_convert_module(name, modules_to_not_convert): continue with torch.device("meta"): - new_module = FP8Embedding(module.num_embeddings, module.embedding_dim, module.padding_idx) + new_module = FP8Embedding( + module.num_embeddings, + module.embedding_dim, + module.padding_idx, + block_size=block_size, + scale_fmt=scale_fmt, + ) new_module._hf_quantized_needs_local_tp = True model.set_submodule(name, new_module) return model diff --git a/src/transformers/models/__init__.py b/src/transformers/models/__init__.py index ab0345512ed0..951e6b5c8ef8 100644 --- a/src/transformers/models/__init__.py +++ b/src/transformers/models/__init__.py @@ -112,6 +112,7 @@ from .deepseek_v3 import * from .deepseek_v4 import * from .deepseek_v32 import * + from .deepseek_v41 import * from .deepseek_vl import * from .deepseek_vl_hybrid import * from .deformable_detr import * diff --git a/src/transformers/models/auto/auto_mappings.py b/src/transformers/models/auto/auto_mappings.py index b1729e21aa08..e2c13ae042ad 100644 --- a/src/transformers/models/auto/auto_mappings.py +++ b/src/transformers/models/auto/auto_mappings.py @@ -146,6 +146,9 @@ ("deepseek_v3", "DeepseekV3Config"), ("deepseek_v32", "DeepseekV32Config"), ("deepseek_v4", "DeepseekV4Config"), + ("deepseek_v41", "DeepseekV41Config"), + ("deepseek_v41_text", "DeepseekV41TextConfig"), + ("deepseek_v41_vision", "DeepseekV41VisionConfig"), ("deepseek_vl", "DeepseekVLConfig"), ("deepseek_vl_hybrid", "DeepseekVLHybridConfig"), ("deformable_detr", "DeformableDetrConfig"), @@ -893,6 +896,8 @@ ("deepseek_ocr2_sam_vision_model", "deepseek_ocr2"), ("deepseek_ocr2_text", "deepseek_ocr2"), ("deepseek_ocr2_vision", "deepseek_ocr2"), + ("deepseek_v41_text", "deepseek_v41"), + ("deepseek_v41_vision", "deepseek_v41"), ("dia_decoder", "dia"), ("dia_encoder", "dia"), ("diffusion_gemma_text", "diffusion_gemma"), @@ -1265,6 +1270,7 @@ ("cosmos3_edge", "Cosmos3EdgeProcessor"), ("csm", "CsmProcessor"), ("deepseek_ocr2", "DeepseekOcr2Processor"), + ("deepseek_v41", "DeepseekV41Processor"), ("deepseek_vl", "DeepseekVLProcessor"), ("deepseek_vl_hybrid", "DeepseekVLHybridProcessor"), ("dia", "DiaProcessor"), @@ -1427,6 +1433,7 @@ ("convnext", {"pil": "ConvNextImageProcessorPil", "torchvision": "ConvNextImageProcessor"}), ("cosmos3_edge", {"pil": "Cosmos3EdgeImageProcessorPil", "torchvision": "Cosmos3EdgeImageProcessor"}), ("deepseek_ocr2", {"pil": "DeepseekOcr2ImageProcessorPil", "torchvision": "DeepseekOcr2ImageProcessor"}), + ("deepseek_v41", {"torchvision": "DeepseekV41ImageProcessor"}), ("deepseek_vl", {"pil": "DeepseekVLImageProcessorPil", "torchvision": "DeepseekVLImageProcessor"}), ( "deepseek_vl_hybrid", diff --git a/src/transformers/models/auto/modeling_auto.py b/src/transformers/models/auto/modeling_auto.py index a39e5484b698..7f2410ac86c2 100644 --- a/src/transformers/models/auto/modeling_auto.py +++ b/src/transformers/models/auto/modeling_auto.py @@ -131,6 +131,9 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("deepseek_v3", "DeepseekV3Model"), ("deepseek_v32", "DeepseekV32Model"), ("deepseek_v4", "DeepseekV4Model"), + ("deepseek_v41", "DeepseekV41Model"), + ("deepseek_v41_text", "DeepseekV41TextModel"), + ("deepseek_v41_vision", "DeepseekV41VisionModel"), ("deepseek_vl", "DeepseekVLModel"), ("deepseek_vl_hybrid", "DeepseekVLHybridModel"), ("deformable_detr", "DeformableDetrModel"), @@ -819,6 +822,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("deepseek_v3", "DeepseekV3ForCausalLM"), ("deepseek_v32", "DeepseekV32ForCausalLM"), ("deepseek_v4", "DeepseekV4ForCausalLM"), + ("deepseek_v41", "DeepseekV41ForCausalLM"), ("diffllama", "DiffLlamaForCausalLM"), ("doge", "DogeForCausalLM"), ("dory", "DoryForCausalLM"), @@ -1202,6 +1206,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("cosmos3_edge", "Cosmos3EdgeForConditionalGeneration"), ("cosmos3_omni", "Cosmos3OmniForConditionalGeneration"), ("deepseek_ocr2", "DeepseekOcr2ForConditionalGeneration"), + ("deepseek_v41", "DeepseekV41ForCausalLM"), ("deepseek_vl", "DeepseekVLForConditionalGeneration"), ("deepseek_vl_hybrid", "DeepseekVLHybridForConditionalGeneration"), ("diffusion_gemma", "DiffusionGemmaForBlockDiffusion"), diff --git a/src/transformers/models/deepseek_v41/__init__.py b/src/transformers/models/deepseek_v41/__init__.py new file mode 100644 index 000000000000..8c12c6b62400 --- /dev/null +++ b/src/transformers/models/deepseek_v41/__init__.py @@ -0,0 +1,35 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from the modules in `src/transformers/models/deepseek_v41`. +# Do NOT edit this file manually as any edits will be overwritten by auto-generation of the file. +# A module is picked up once it exports a name through `__all__`. +# Regenerate the file with: `python utils/check_inits.py --fix_and_overwrite` +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# Copyright 2026 The HuggingFace Inc. 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. +from typing import TYPE_CHECKING + +from ...utils import _LazyModule +from ...utils.import_utils import define_import_structure + + +if TYPE_CHECKING: + from .configuration_deepseek_v41 import * + from .image_processing_deepseek_v41 import * + from .modeling_deepseek_v41 import * + from .processing_deepseek_v41 import * +else: + import sys + + _file = globals()["__file__"] + sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__) diff --git a/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py b/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py new file mode 100644 index 000000000000..0e9d2614e152 --- /dev/null +++ b/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py @@ -0,0 +1,479 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/deepseek_v41/modular_deepseek_v41.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_deepseek_v41.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# Copyright 2026 The HuggingFace Inc. 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. +from huggingface_hub.dataclasses import strict + +from ...configuration_utils import PreTrainedConfig +from ...modeling_rope_utils import RopeParameters +from ...utils import auto_docstring + + +@auto_docstring(checkpoint="deepseek-ai/DeepSeek-V4.1-Flash") +@strict +class DeepseekV41VisionConfig(PreTrainedConfig): + r""" + rope_theta (`float`, *optional*, defaults to 10000.0): + Base of the 2D rotary position embedding. + downsample_ratio (`int`, *optional*, defaults to 3): + Side of the square of patches that the projector merges into one language model token. + max_image_tokens (`int`, *optional*, defaults to 1024): + The most language model tokens an image may take, delimiters included. Only used for preprocessing. + min_pixels (`int`, *optional*, defaults to 295936): + Images with fewer pixels are scaled up to this area. Only used for preprocessing. + max_wh_ratio (`float`, *optional*): + Images wider than this width-to-height ratio are squashed to it. Only used for preprocessing. + """ + + model_type = "deepseek_v41_vision" + base_config_key = "vision_config" + + hidden_size: int = 1024 + num_hidden_layers: int = 32 + num_attention_heads: int = 16 + intermediate_size: int = 2816 + patch_size: int = 14 + num_channels: int = 3 + rope_theta: float | int = 10000.0 + downsample_ratio: int = 3 + max_image_tokens: int = 1024 + min_pixels: int = 295936 + max_wh_ratio: float | int | None = None + rms_norm_eps: float = 1.0e-6 + initializer_range: float = 0.02 + + +DEEPSEEK_V41_ATTENTION_LAYER_TYPES = ( + "sliding_attention", + "compressed_attention", + "kv_shared_indexed_attention", + "kv_shared_attention", +) + + +@auto_docstring(checkpoint="deepseek-ai/DeepSeek-V4.1-Flash") +@strict +class DeepseekV41TextConfig(PreTrainedConfig): + r""" + scoring_func (`str`): + Router activation — `sqrtsoftplus`, `softmax`, or `sigmoid`. + rope_theta (`float`): + RoPE base for the sliding-window-only layers. + layer_types (`list[str]`): + Per-layer cache type. Every DeepSeek-V4.1 layer uses `"shared_compressed_attention"`, so this is filled in + automatically. + attention_layer_types (`list[str]`, *optional*): + Which attention variant each layer uses. Derived from `compress_ratios`, `kv_source_layer_ids` and + `index_source_layer_ids`: + + - `"sliding_attention"` attends over a sliding window only. + - `"compressed_attention"` also compresses its own KV, and runs an indexer to pick which compressed + entries each query attends to. + - `"kv_shared_indexed_attention"` reads the compressed KV of the last `"compressed_attention"` layer, but + runs its own indexer over it. + - `"kv_shared_attention"` reuses both the compressed KV and the selection of the layers before it. + compress_ratios (`list[int]`, *optional*): + Per-layer KV compression ratio. 0 is sliding-window attention only, and `r > 0` adds attention over + KV that are pooled `r`-to-1. The checkpoint's config lists the DSpark layers after the main ones, and + those extra entries are ignored here. Defaults to sliding-window attention everywhere. + kv_source_layer_ids (`list[int]`, *optional*): + The layers that compress their own KV. Every later layer with the same ratio reads that KV, up to the + next source. + index_source_layer_ids (`list[int]`, *optional*): + The layers that run an indexer. The layers in between reuse the selection of the last one. + candidate_source_layer_id (`int`, *optional*): + The indexer of this layer also keeps the `candidate_topk_blocks` best blocks of compressed positions per + query, and the indexers after it only choose inside those blocks. + candidate_topk_blocks (`int`, *optional*, defaults to 2048): + Number of blocks the candidate source keeps per query. + candidate_block_size (`int`, *optional*, defaults to 8): + Number of compressed positions in a candidate block. + compress_rope_theta (`float`): + RoPE base for the layers that attend to compressed KV (paired with `rope_scaling` for YaRN). + hc_mult (`int`): + Number of parallel streams the hyper-connections carry the residual in. + hc_sinkhorn_iters (`int`): + Sinkhorn-Knopp iterations that make the hyper-connection mixing matrix doubly stochastic. + hc_eps (`float`): + Numerical floor for the Sinkhorn-Knopp normalization. + swiglu_limit (`float`): + Clip the experts' gate/up pre-activations. + sliding_window (`int`): + Size of the sliding window that every layer attends over. + o_groups (`int`): + Number of head groups in the grouped output projection. + o_lora_rank (`int`): + Per-group intermediate dim of the grouped output projection. + index_n_heads (`int`): + Number of indexer query heads. + index_head_dim (`int`): + Indexer head dim. + index_topk (`int`): + Number of compressed entries the indexer keeps per query. + engram_layer_ids (`list[int]`, *optional*): + The layers that add an Engram n-gram lookup to the residual stream before their attention. + engram_num_embeddings (`list[int]`, *optional*): + Rows in the hash table of each Engram layer. This is the sum of the layer's bucket sizes, so it is only + checked against them. + engram_max_ngram_size (`int`, *optional*, defaults to 4): + Longest n-gram that is hashed. Every size from 2 up to this one gets its own lookups. + engram_vocab_size (`int`, *optional*, defaults to 16000000): + Each (n-gram size, head) pair gets a bucket range whose size is the next unused prime above this. + engram_n_heads (`int`, *optional*, defaults to 8): + Number of hash heads per n-gram size. + engram_head_dim (`int`, *optional*, defaults to 256): + Dimension of the rows of the Engram hash tables. + engram_pad_token_id (`int`, *optional*, defaults to 2): + Token that fills the slots of an n-gram that reach back before the start of the sequence. + engram_compressed_vocab_size (`int`, *optional*, defaults to 99092): + Size of the vocabulary once tokens that normalize alike are merged. The hash multipliers are derived + from it. + num_nextn_predict_layers (`int`): + Number of DSpark draft layers in the checkpoint (not instantiated here). + dspark_block_size (`int`, *optional*, defaults to 5): + Number of tokens a DSpark draft predicts (not used yet). + dspark_noise_token_id (`int`, *optional*, defaults to 128799): + Token that fills the positions a DSpark draft has yet to predict (not used yet). + dspark_target_layer_ids (`list[int]`, *optional*): + The layers whose inputs the DSpark draft layers read (not used yet). + dspark_markov_rank (`int`, *optional*, defaults to 256): + Rank of the DSpark Markov head (not used yet). + dspark_n_routed_experts (`int`, *optional*, defaults to 128): + Number of routed experts in the DSpark draft layers (not used yet). + dspark_num_experts_per_tok (`int`, *optional*, defaults to 3): + Number of experts each token is routed to in the DSpark draft layers (not used yet). + partial_rotary_factor (`float`, *optional*): + Fraction of head_dim that gets RoPE. + Defaults to `qk_rope_head_dim / head_dim` so cos/sin sizes to `qk_rope_head_dim`. + """ + + model_type = "deepseek_v41_text" + # `num_local_experts` is the standard MoE attr name (read by FP8 / TP integrations); + # `intermediate_size` is what :class:`LlamaMLP` reads for the shared expert width + # — V4 only ships `moe_intermediate_size` so we route the read through. + attribute_map = { + "num_local_experts": "n_routed_experts", + "intermediate_size": "moe_intermediate_size", + } + + base_model_pp_plan = { + "embed_tokens": (["input_ids"], ["inputs_embeds"]), + "layers": (["hidden_states", "attention_mask"], ["hidden_states"]), + "norm": (["hidden_states"], ["hidden_states"]), + } + base_model_tp_plan = { + "layers.*.mlp.shared_experts.gate_proj": "colwise", + "layers.*.mlp.shared_experts.up_proj": "colwise", + "layers.*.mlp.shared_experts.down_proj": "rowwise", + } + base_model_ep_plan = { + "layers.*.mlp.experts.gate_up_proj": "grouped_gemm", + "layers.*.mlp.experts.down_proj": "grouped_gemm", + "layers.*.mlp.experts": "ep_dispatch_experts", + } + + vocab_size: int = 129280 + + hidden_size: int = 5120 + moe_intermediate_size: int = 2304 + num_hidden_layers: int = 40 + num_attention_heads: int = 64 + num_key_value_heads: int = 1 + head_dim: int = 512 + q_lora_rank: int = 1280 + default_partial_rotary_factor = 64 / 512 # `qk_rope_head_dim` (64) / `head_dim` (512) + num_experts_per_tok: int = 6 + n_routed_experts: int = 384 + n_shared_experts: int = 1 + scoring_func: str = "sqrtsoftplus" + norm_topk_prob: bool = True + routed_scaling_factor: float = 1.5 + max_position_embeddings: int = 1048576 + rope_theta: float | int = 10000.0 + + layer_types: list[str] | None = None + compress_rope_theta: float | int = 160000.0 + hc_mult: int = 4 + hc_sinkhorn_iters: int = 20 + hc_eps: float = 1.0e-6 + swiglu_limit: float = 10.0 + sliding_window: int = 128 + o_groups: int = 8 + o_lora_rank: int = 1024 + index_n_heads: int = 32 + index_head_dim: int = 128 + index_topk: int = 512 + num_nextn_predict_layers: int = 3 + + output_router_logits: bool = False + router_aux_loss_coef: float = 0.001 + router_jitter_noise: float = 0.0 + + hidden_act: str = "silu" + initializer_range: float = 0.02 + rms_norm_eps: float = 1.0e-20 + use_cache: bool = True + pad_token_id: int | None = 2 + bos_token_id: int | None = 0 + eos_token_id: int | list[int] | None = 1 + tie_word_embeddings: bool = False + rope_parameters: RopeParameters | dict | None = None + partial_rotary_factor: float | None = None + attention_bias: bool = False + mlp_bias: bool = False + attention_dropout: float = 0.0 + + # V4's `rope_parameters` is keyed by *rope-type* labels (`main` / `compress`) — not + # by `layer_types`. The base `validate_rope` checks `keys ⊆ layer_types` and falls + # back to wrapping the whole dict as a single set of params when the subset check + # fails, which then warns about `main` / `compress` as unrecognized keys. Override + # to iterate the rope-type-keyed sub-dicts directly. + _rope_type_labels = ("main", "compress") + base_config_key = "text_config" + + attention_layer_types: list[str] | None = None + compress_ratios: list[int] | None = None + kv_source_layer_ids: list[int] | None = None + index_source_layer_ids: list[int] | None = None + candidate_source_layer_id: int | None = None + candidate_topk_blocks: int = 2048 + candidate_block_size: int = 8 + + engram_layer_ids: list[int] | None = None + engram_num_embeddings: list[int] | None = None + engram_max_ngram_size: int = 4 + engram_vocab_size: int = 16000000 + engram_n_heads: int = 8 + engram_head_dim: int = 256 + engram_pad_token_id: int = 2 + engram_compressed_vocab_size: int = 99092 + + dspark_block_size: int = 5 + dspark_noise_token_id: int = 128799 + dspark_target_layer_ids: list[int] | None = None + dspark_markov_rank: int = 256 + dspark_n_routed_experts: int = 128 + dspark_num_experts_per_tok: int = 3 + + def validate_rope(self): + rope_parameters_dict = getattr(self, "rope_parameters", None) or {} + ignore_keys = self.ignore_keys_at_rope_validation + # The yarn / longrope / llama3 validators in + # :class:`RotaryEmbeddingConfigMixin` read `self.rope_parameters[]` + # directly (e.g. `original_max_position_embeddings`). With V4's + # rope-type-keyed nesting, the top-level dict only has `main` / `compress`, + # so those reads fail. Temporarily point `self.rope_parameters` at the + # rope-type-specific sub-dict for the duration of the validation call, + # then restore it. + for rope_type_label in self._rope_type_labels: + rope_parameters = rope_parameters_dict.get(rope_type_label) + if not isinstance(rope_parameters, dict): + continue + rope_type = rope_parameters.get("rope_type", rope_parameters.get("type", "default")) + rope_parameters["rope_type"] = rope_type + validation_fn = getattr(self, f"_validate_{rope_type}_rope_parameters", None) + if validation_fn is None: + continue + self.rope_parameters = rope_parameters + try: + validation_fn(rope_parameters, ignore_keys=ignore_keys) + finally: + self.rope_parameters = rope_parameters_dict + + def validate_layer_type(self): + """Checks that the attention schedule is one the model can run: every layer that attends to compressed + KV needs a source for that KV and for its selection somewhere before it.""" + if self.num_hidden_layers is None or self.attention_layer_types is None: + return + if len(self.attention_layer_types) != self.num_hidden_layers: + raise ValueError( + f"`num_hidden_layers` ({self.num_hidden_layers}) must equal `len(attention_layer_types)` " + f"({len(self.attention_layer_types)})." + ) + bad = [t for t in self.attention_layer_types if t not in DEEPSEEK_V41_ATTENTION_LAYER_TYPES] + if bad: + raise ValueError( + f"`attention_layer_types` entries must be one of {DEEPSEEK_V41_ATTENTION_LAYER_TYPES}; got {bad}." + ) + + source_ratio = None + for layer_idx, layer_type in enumerate(self.attention_layer_types): + ratio = self.compress_ratios[layer_idx] + if layer_type == "compressed_attention": + if layer_idx not in self.index_source_layer_ids: + raise ValueError( + f"Layer {layer_idx} is in `kv_source_layer_ids`, so it must be in `index_source_layer_ids` " + f"too: the index keys are made from the KV it compresses. Got {self.index_source_layer_ids}." + ) + source_ratio = ratio + elif layer_type != "sliding_attention" and ratio != source_ratio: + raise ValueError( + f"Layer {layer_idx} has a compression ratio of {ratio}, but the last layer in " + f"`kv_source_layer_ids` before it compresses with a ratio of {source_ratio}. Add {layer_idx} " + "to `kv_source_layer_ids` or change its entry in `compress_ratios`." + ) + if ( + self.candidate_source_layer_id is not None + and self.candidate_source_layer_id not in self.index_source_layer_ids + ): + raise ValueError( + f"`candidate_source_layer_id` ({self.candidate_source_layer_id}) must be one of " + f"`index_source_layer_ids` ({self.index_source_layer_ids})." + ) + + def __post_init__(self, **kwargs): + legacy_qk_rope_head_dim = kwargs.pop("qk_rope_head_dim", None) + super().__post_init__(**kwargs) + n = self.num_hidden_layers + + # Without a schedule, every layer is sliding-window attention only + if self.compress_ratios is None: + self.compress_ratios = [0] * n + if len(self.compress_ratios) < n: + raise ValueError( + f"`compress_ratios` needs an entry per layer, but has {len(self.compress_ratios)} entries for " + f"{n} layers." + ) + self.kv_source_layer_ids = list(self.kv_source_layer_ids or []) + self.index_source_layer_ids = list(self.index_source_layer_ids or []) + self.engram_layer_ids = list(self.engram_layer_ids or []) + self.dspark_target_layer_ids = list(self.dspark_target_layer_ids or []) + + # `attention_layer_types` picks the attention class of each layer + attention_layer_types = [] + for layer_idx in range(n): + if self.compress_ratios[layer_idx] == 0: + # A sliding window and nothing else + attention_layer_types.append("sliding_attention") + elif layer_idx in self.kv_source_layer_ids: + # Compresses its own KV and indexes it + attention_layer_types.append("compressed_attention") + elif layer_idx in self.index_source_layer_ids: + # Reads the KV of the last source, but selects from it with its own indexer + attention_layer_types.append("kv_shared_indexed_attention") + else: + # Reads both the KV and the selection of the layers before it + attention_layer_types.append("kv_shared_attention") + if self.attention_layer_types is None: + self.attention_layer_types = attention_layer_types + elif list(self.attention_layer_types) != attention_layer_types: + raise ValueError( + f"`attention_layer_types` ({self.attention_layer_types}) does not match `compress_ratios`, " + f"`kv_source_layer_ids` and `index_source_layer_ids`, which give {attention_layer_types}." + ) + + # `layer_types` picks the cache class, and all layers keep their state in the same one + self.layer_types = ["shared_compressed_attention"] * n + + # `partial_rotary_factor` = legacy `qk_rope_head_dim / head_dim` if given, else default. + # `qk_rope_head_dim` is a runtime-only attr (never a dataclass field). + if self.partial_rotary_factor is None: + self.partial_rotary_factor = ( + legacy_qk_rope_head_dim / self.head_dim + if legacy_qk_rope_head_dim is not None + else self.default_partial_rotary_factor + ) + self.qk_rope_head_dim = int(self.head_dim * self.partial_rotary_factor) + + # As in DeepSeek-V4, YaRN only applies to the layers that attend to compressed KV, which rotate with + # `compress_rope_theta`. The sliding-window-only layers use plain RoPE with `rope_theta`. The reference + # does not multiply cos/sin by YaRN's mscale, so we force `attention_factor=1.0` for YaRN. + rp = self.rope_parameters or {} + if isinstance(rp.get("main"), dict) and isinstance(rp.get("compress"), dict): + # Already nested - drop any leftover top-level keys + self.rope_parameters = {"main": rp["main"], "compress": rp["compress"]} + else: + yarn = {k: v for k, v in rp.items() if k not in ("main", "compress")} + main = { + "rope_type": "default", + "rope_theta": self.rope_theta, + "partial_rotary_factor": self.partial_rotary_factor, + } + compress = { + **yarn, + "rope_theta": self.compress_rope_theta, + "partial_rotary_factor": self.partial_rotary_factor, + } + compress.setdefault("rope_type", "default") + if compress["rope_type"] == "yarn": + compress.setdefault("attention_factor", 1.0) + self.rope_parameters = {"main": main, "compress": compress} + + def validate_fake_quantization(self): + """Checks that the activations which are rounded to FP8 or FP4 split into whole blocks of 32 values.""" + widths = { + "head_dim": self.head_dim, + "num_attention_heads * head_dim // o_groups": self.num_attention_heads * self.head_dim // self.o_groups, + } + if self.compress_ratios is not None and any(self.compress_ratios): + # Only the layers that attend to compressed KV have index keys and queries + widths["index_head_dim"] = self.index_head_dim + bad = {name: width for name, width in widths.items() if width % 32 != 0} + if bad: + raise ValueError( + "The KV, the input of the grouped output projection and the index keys and queries are rounded to " + f"FP8 or FP4 in blocks of 32 values, so their widths must be multiples of 32. Got {bad}." + ) + + +@auto_docstring(checkpoint="deepseek-ai/DeepSeek-V4.1-Flash") +@strict +class DeepseekV41Config(PreTrainedConfig): + model_type = "deepseek_v41" + sub_configs_defaults = { + "vision_config": DeepseekV41VisionConfig, + "text_config": DeepseekV41TextConfig, + } + + vision_config: dict | PreTrainedConfig | None = None + text_config: dict | PreTrainedConfig | None = None + image_token_id: int = 129264 + pad_token_id: int | None = 2 + bos_token_id: int | None = 0 + eos_token_id: int | list[int] | None = 1 + + def __post_init__(self, **kwargs): + super().__post_init__(**kwargs) + + # The quantization config of the checkpoint only describes its FP8 linears and its FP4 experts, so we fill + # in the rest here, like DeepSeek-V4 does for `expert_dtype`. Anything the config already sets is left alone. + # TODO: revisit after #50245. With a quantization plan, the tables can get an entry of their own + quantization_config = getattr(self, "quantization_config", None) + if isinstance(quantization_config, dict) and quantization_config.get("quant_method") == "fp8": + block_size = quantization_config.get("weight_block_size") or (128, 128) + defaults = { + # The Engram tables are stored in FP8 too, and they are far too big to dequantize. A block of a + # table is as wide as a block of a linear, but it never spans rows + "modules_to_convert": ["engram.embed"], + "embedding_block_size": block_size[1], + # These linears are stored in BF16. They have no scales, so the quantizer has to skip them + "modules_to_not_convert": [ + "lm_head", + r".*vision_tower", + r".*multi_modal_projector", + "self_attn.compressor.kv_proj", + "self_attn.compressor.gate_proj", + "self_attn.indexer.k_proj", + "self_attn.indexer.weights_proj", + ], + } + given = {key: value for key, value in quantization_config.items() if value is not None} + self.quantization_config = {**defaults, **given} + + +__all__ = ["DeepseekV41Config", "DeepseekV41TextConfig", "DeepseekV41VisionConfig"] diff --git a/src/transformers/models/deepseek_v41/image_processing_deepseek_v41.py b/src/transformers/models/deepseek_v41/image_processing_deepseek_v41.py new file mode 100644 index 000000000000..351963314bdb --- /dev/null +++ b/src/transformers/models/deepseek_v41/image_processing_deepseek_v41.py @@ -0,0 +1,287 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/deepseek_v41/modular_deepseek_v41.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_deepseek_v41.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# Copyright 2026 The HuggingFace Inc. 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. +import math + +import torch +from torchvision.transforms.v2 import functional as tvF + +from ...image_processing_backends import TorchvisionBackend +from ...image_processing_utils import BatchFeature +from ...image_utils import ChannelDimension, ImageInput, ImageType, PILImageResampling, SizeDict, get_image_type +from ...processing_utils import ImagesKwargs, Unpack +from ...utils import TensorType, auto_docstring + + +class DeepseekV41ImageProcessorKwargs(ImagesKwargs, total=False): + r""" + patch_size (`int`, *optional*, defaults to 14): + Side of the square patches that the vision encoder embeds. + downsample_ratio (`int`, *optional*, defaults to 3): + Side of the square of patches that the model merges into one token. + max_image_tokens (`int`, *optional*, defaults to 1024): + The most positions an image may take in the prompt, delimiters included. Larger images are scaled down. + min_pixels (`int`, *optional*, defaults to 295936): + Images with fewer pixels are scaled up to this area. + max_wh_ratio (`float`, *optional*): + Images wider than this width-to-height ratio are squashed to it. The released checkpoints set no limit. + """ + + patch_size: int + downsample_ratio: int + max_image_tokens: int + min_pixels: int + max_wh_ratio: float | None + + +def get_resized_image_size( + height: int, + width: int, + patch_size: int, + downsample_ratio: int, + max_image_tokens: int, + min_pixels: int, + max_wh_ratio: float | None = None, +) -> tuple[int, int]: + """ + Works out the size that an image is resized to before it is cut into patches. Both sides come out as a + multiple of `patch_size`, small images are scaled up to about `min_pixels`, and large ones are scaled down + until they fit in `max_image_tokens`. + + The model merges every `downsample_ratio x downsample_ratio` square of patches into one token. An image + with `rows x columns` of those takes `rows * (columns + 1) + 2` positions in the prompt: a newline after + each row, plus a start and an end delimiter. + + Args: + height (`int`): + Height of the image. + width (`int`): + Width of the image. + patch_size (`int`): + Side of the square patches that the vision encoder embeds. + downsample_ratio (`int`): + Side of the square of patches that the model merges into one token. + max_image_tokens (`int`): + The most positions the image may take in the prompt, delimiters included. + min_pixels (`int`): + Images with fewer pixels are scaled up to this area. + max_wh_ratio (`float`, *optional*): + Images wider than this width-to-height ratio are planned as if they had exactly this ratio. + + Returns: + `tuple[int, int]`: The height and width to resize the image to. + + Example: + + ```python + >>> from transformers.models.deepseek_v41.image_processing_deepseek_v41 import get_resized_image_size + + >>> limits = {"patch_size": 14, "downsample_ratio": 3, "max_image_tokens": 1024, "min_pixels": 295936} + >>> get_resized_image_size(701, 1024, **limits) + (714, 1036) + >>> # A small image is scaled up + >>> get_resized_image_size(200, 320, **limits) + (434, 700) + >>> # ... and one that would take more than 1024 positions is scaled down + >>> get_resized_image_size(2000, 3000, **limits) + (1050, 1568) + + ``` + """ + # First, an image that is too wide is planned at the widest ratio allowed. It is squashed to that ratio + # afterwards, not cropped. + if max_wh_ratio is not None and width > height * max_wh_ratio: + width = height * max_wh_ratio + # Next, a small image is scaled up to `min_pixels`. The sides are truncated, so it can end up just below. + if 0 < width * height < min_pixels: + scale = (min_pixels / (width * height)) ** 0.5 + width, height = int(width * scale), int(height * scale) + # Both sides are rounded up to whole patches, and a partial square of patches still makes a token + resized_height = math.ceil(height / patch_size) * patch_size + resized_width = math.ceil(width / patch_size) * patch_size + rows = math.ceil(resized_height // patch_size / downsample_ratio) + columns = math.ceil(resized_width // patch_size / downsample_ratio) + if rows * (columns + 1) + 2 <= max_image_tokens: + return resized_height, resized_width + + # Finally, an image that takes too many positions is scaled down. With `rows = aspect * columns`, the + # budget `rows * (columns + 1) + 2 <= max_image_tokens` is a quadratic in `columns`, and this is its + # positive root. + aspect = height / width + max_columns = math.sqrt((max_image_tokens - 2) / aspect + 0.25) - 0.5 + max_rows = max_columns * aspect + token_size = patch_size * downsample_ratio + if max_columns < 1.0: + # Too tall for one full column at its own aspect ratio, so it becomes a single column of tokens + return (max_image_tokens - 2) // 2 * token_size, token_size + if max_rows < 1.0: + # Too wide for one full row, so it becomes a single row of tokens + return token_size, (max_image_tokens - 3) * token_size + # Otherwise it is scaled to fit the largest whole grid of tokens, and keeps the whole patches that it covers + scale = min(math.floor(max_columns) * token_size / width, math.floor(max_rows) * token_size / height) + return math.floor(height * scale / patch_size) * patch_size, math.floor(width * scale / patch_size) * patch_size + + +@auto_docstring( + custom_intro=""" + Constructs a DeepSeek-V4.1 image processor. Each image keeps its own resolution and aspect ratio: it is + resized to a whole number of patches, padded with gray where needed, and cut into flattened patches. + """ +) +class DeepseekV41ImageProcessor(TorchvisionBackend): + do_convert_rgb = True + do_resize = True + resample = PILImageResampling.BICUBIC + do_rescale = True + do_normalize = True + image_mean = [0.5, 0.5, 0.5] + image_std = [0.5, 0.5, 0.5] + patch_size = 14 + downsample_ratio = 3 + max_image_tokens = 1024 + min_pixels = 295936 + max_wh_ratio = None + valid_kwargs = DeepseekV41ImageProcessorKwargs + model_input_names = ["pixel_values", "image_grid_thw"] + + def __init__(self, **kwargs: Unpack[DeepseekV41ImageProcessorKwargs]): + super().__init__(**kwargs) + + @auto_docstring + def preprocess(self, images: ImageInput, **kwargs: Unpack[DeepseekV41ImageProcessorKwargs]) -> BatchFeature: + return super().preprocess(images, **kwargs) + + def _validate_preprocess_kwargs(self, **kwargs): + # The output size comes from `min_pixels` and `max_image_tokens`, so there is no `size` for the base + # class to check + kwargs.pop("do_resize", None) + super()._validate_preprocess_kwargs(**kwargs) + + def process_image( + self, + image: ImageInput, + do_convert_rgb: bool | None = None, + input_data_format: str | ChannelDimension | None = None, + device: "torch.device | None" = None, + **kwargs: Unpack[ImagesKwargs], + ) -> "torch.Tensor": + # The original preprocessing converts with a plain `convert("RGB")`, which drops an alpha channel. The + # base class would composite it onto a white background instead. + if do_convert_rgb and get_image_type(image) == ImageType.PIL: + image = tvF.pil_to_tensor(image.convert("RGB")) + input_data_format = ChannelDimension.FIRST + return super().process_image( + image, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device, **kwargs + ) + + def resize_and_pad( + self, + image: "torch.Tensor", + size: SizeDict, + resample: "PILImageResampling | tvF.InterpolationMode | int | None", + fill_value: int = 127, + ) -> "torch.Tensor": + """ + Resizes an image to fit inside `size` without changing its aspect ratio, and centers it on a canvas of + that size. This is what `PIL.ImageOps.pad` does, which the original preprocessing uses with a gray + canvas. + + Args: + image (`torch.Tensor` of shape `(num_channels, height, width)`): + The image to resize. + size (`SizeDict`): + The height and width of the canvas. + resample (`PILImageResampling` or `InterpolationMode`): + The filter to resize with. + fill_value (`int`, *optional*, defaults to 127): + The value of the canvas around the image, on the 0-255 scale. + + Returns: + `torch.Tensor` of shape `(num_channels, size.height, size.width)`: The image on its canvas. + """ + height, width = image.shape[-2:] + content_height, content_width = size.height, size.width + if width / height > size.width / size.height: + # Relatively wider than the canvas: it fills the width, with a bar above and below + content_height = round(height / width * size.width) + elif width / height < size.width / size.height: + # Relatively taller than the canvas: it fills the height, with a bar on the left and right + content_width = round(width / height * size.height) + image = self.resize(image, SizeDict(height=content_height, width=content_width), resample) + if (content_height, content_width) == (size.height, size.width): + return image + + canvas = image.new_full((*image.shape[:-2], size.height, size.width), fill_value) + top = round((size.height - content_height) * 0.5) + left = round((size.width - content_width) * 0.5) + canvas[..., top : top + content_height, left : left + content_width] = image + return canvas + + def _preprocess( + self, + images: list["torch.Tensor"], + do_resize: bool, + resample: "PILImageResampling | tvF.InterpolationMode | int | None", + do_rescale: bool, + rescale_factor: float, + do_normalize: bool, + image_mean: float | list[float] | None, + image_std: float | list[float] | None, + patch_size: int, + downsample_ratio: int, + max_image_tokens: int, + min_pixels: int, + max_wh_ratio: float | None, + return_tensors: str | TensorType | None, + **kwargs, + ) -> BatchFeature: + patches, image_grid_thw = [], [] + for image in images: + channels, height, width = image.shape + if do_resize: + resized_height, resized_width = get_resized_image_size( + height, width, patch_size, downsample_ratio, max_image_tokens, min_pixels, max_wh_ratio + ) + size = SizeDict(height=resized_height, width=resized_width) + if max_wh_ratio is not None and width >= max_wh_ratio * height: + # Too wide: squashed to the size that was planned at the widest ratio allowed + image = self.resize(image, size, resample) + else: + # Everything else keeps its aspect ratio, with gray bars to fill up the last patches + image = self.resize_and_pad(image, size, resample) + height, width = resized_height, resized_width + if height % patch_size != 0 or width % patch_size != 0: + raise ValueError( + "With `do_resize=False`, the height and width of an image must be multiples of the patch " + f"size.\nImage size: {(height, width)}\nPatch size: {patch_size}" + ) + image = self.rescale_and_normalize(image, do_rescale, rescale_factor, do_normalize, image_mean, image_std) + # One row per patch in reading order, each flattened as (channels, patch height, patch width) + rows, columns = height // patch_size, width // patch_size + image = image.reshape(channels, rows, patch_size, columns, patch_size).permute(1, 3, 0, 2, 4) + patches.append(image.reshape(rows * columns, -1)) + # The grid has a temporal size as well, like in the models that take videos. An image is one frame. + image_grid_thw.append([1, rows, columns]) + return BatchFeature( + data={"pixel_values": torch.cat(patches), "image_grid_thw": torch.tensor(image_grid_thw)}, + tensor_type=return_tensors, + ) + + +__all__ = ["DeepseekV41ImageProcessor"] diff --git a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py new file mode 100644 index 000000000000..3bf4fb021a45 --- /dev/null +++ b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py @@ -0,0 +1,1974 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/deepseek_v41/modular_deepseek_v41.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_deepseek_v41.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# Copyright 2026 The HuggingFace Inc. 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. +from collections.abc import Callable + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn + +from ... import initialization as init +from ...activations import ACT2FN +from ...cache_utils import Cache, DynamicCache, DynamicSlidingWindowLayer +from ...generation import GenerationMixin +from ...integrations import use_experts_implementation +from ...masking_utils import create_recurrent_attention_mask, create_sliding_window_causal_mask +from ...modeling_layers import GradientCheckpointingLayer +from ...modeling_outputs import ( + BaseModelOutput, + BaseModelOutputWithPooling, + MoeModelOutputWithPast, + MultimodalMoeBaseModelOutputWithPast, + MultimodalMoeCausalLMOutputWithPast, +) +from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel +from ...processing_utils import Unpack +from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check +from ...utils.deprecation import deprecate_kwarg +from ...utils.generic import merge_with_config_defaults +from ...utils.output_capturing import OutputRecorder, capture_outputs +from .configuration_deepseek_v41 import DeepseekV41Config, DeepseekV41TextConfig, DeepseekV41VisionConfig + + +class DeepseekV41CacheLayer(DynamicSlidingWindowLayer): + r""" + Cache layer for DeepSeek-V4.1. Every layer keeps its sliding window of KV here. On top of that, a few layers + keep state that other layers read: + + * `compressed_kv` / `index_keys` - the compressed KV entries a `"compressed_attention"` layer has emitted + so far, and the index keys made from them. The KV-sharing layers after it attend to these too. Entry + `g` of a row is its `g`-th group of real tokens, so the rows of a padded batch do not have the same + number of entries. A row with fewer of them than the others has zeros after its last one. + * `pooling_buffer` - the KV and the gates of the last `compress_ratio - 1` real tokens of each row. The + last few of them are the tokens of a pooling group that is still filling up. The group only becomes a + compressed entry once its last token arrives. + * `token_history` - the last few token ids, which the Engram n-gram hashes look back at. Only the first + layer keeps it. + """ + + _layer_type = "shared_compressed_attention" + + def __init__(self, config: "DeepseekV41TextConfig", **kwargs): + super().__init__(sliding_window=config.sliding_window) + self.compressed_kv: torch.Tensor | None = None + self.index_keys: torch.Tensor | None = None + self.pooling_buffer: torch.Tensor | None = None + self.token_history: torch.Tensor | None = None + + def update(self, key_states: torch.Tensor, value_states: torch.Tensor, *args, **kwargs): + """ + Sliding-window update for shared KV: the keys and the values are the same tensor, so we only store it + once. + """ + if not self.is_initialized: + self.lazy_initialization(key_states, value_states) + self.values = self.keys + self.cumulative_length += key_states.shape[-2] + full = torch.cat([self.keys, key_states], dim=-2) + self.keys = full[:, :, -self.sliding_window + 1 :, :] + self.values = self.keys + return full, full + + def update_compressed_states( + self, + compressed_kv: torch.Tensor, + index_keys: torch.Tensor, + num_entries: torch.Tensor, + num_new_entries: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + """ + Write the new compressed KV entries and their index keys after the ones that each row already has, and + return all of them so far. Row `i` has `num_entries[i]` entries, and takes the first + `num_new_entries[i]` of the new ones. + """ + if self.compressed_kv is None: + self.compressed_kv, self.index_keys = compressed_kv[:, :0], index_keys[:, :0] + num_entries_after = num_entries + num_new_entries + width = max(self.compressed_kv.shape[1], int(num_entries_after.max())) + # Each row writes at its own offset, as the rows of a padded batch do not complete their groups in the + # same calls. The new entries that a row does not take all land in one extra slot at the end, which we + # drop again. + slots = num_entries[:, None] + torch.arange(compressed_kv.shape[1], device=compressed_kv.device) + slots = torch.where(slots < num_entries_after[:, None], slots, width) + for name, new_states in (("compressed_kv", compressed_kv), ("index_keys", index_keys)): + states = getattr(self, name) + states = F.pad(states, (0, 0, 0, width + 1 - states.shape[1])) + states = states.scatter(1, slots[..., None].expand_as(new_states), new_states) + setattr(self, name, states[:, :width]) + return self.compressed_kv, self.index_keys + + def update_token_history(self, token_ids: torch.Tensor, history_length: int) -> torch.Tensor: + """ + Return the new `token_ids` with the last `history_length` tokens before them, then remember the last + `history_length` of those for the next call. Before the start of the sequence, the history is `-1`. + """ + if self.token_history is None: + self.token_history = token_ids.new_full((token_ids.shape[0], history_length), -1) + token_ids = torch.cat([self.token_history, token_ids], dim=1) + self.token_history = token_ids[:, -history_length:] + return token_ids + + def _extra_state_names(self) -> tuple[str, ...]: + return ("compressed_kv", "index_keys", "pooling_buffer", "token_history") + + def reorder_cache(self, beam_idx: torch.LongTensor) -> None: + super().reorder_cache(beam_idx) + for name in self._extra_state_names(): + tensor = getattr(self, name) + if tensor is not None: + setattr(self, name, tensor.index_select(0, beam_idx.to(tensor.device))) + + def batch_repeat_interleave(self, repeats: int) -> None: + super().batch_repeat_interleave(repeats) + for name in self._extra_state_names(): + tensor = getattr(self, name) + if tensor is not None: + setattr(self, name, tensor.repeat_interleave(repeats, dim=0)) + + def batch_select_indices(self, indices: torch.Tensor) -> None: + super().batch_select_indices(indices) + for name in self._extra_state_names(): + tensor = getattr(self, name) + if tensor is not None: + setattr(self, name, tensor[indices, ...]) + + def reset(self) -> None: + super().reset() + # Dropped rather than zeroed, as they grow by concatenation, like the main states + for name in self._extra_state_names(): + setattr(self, name, None) + + +class DeepseekV41RMSNorm(nn.Module): + def __init__(self, hidden_size, eps: float = 1e-6) -> None: + """ + DeepseekV41RMSNorm is equivalent to T5LayerNorm + """ + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + self.variance_epsilon = eps + + def forward(self, hidden_states) -> torch.Tensor: + input_dtype = hidden_states.dtype + hidden_states = hidden_states.to(torch.float32) + variance = hidden_states.pow(2).mean(-1, keepdim=True) + hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) + return (self.weight * hidden_states).to(input_dtype) # main diff with Llama + + def extra_repr(self): + return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" + + +class DeepseekV41RotaryEmbedding(nn.Module): + """ + Multi-layer-type rotary embedding (Laguna pattern: partial rotary on top of + Gemma3's per-layer-type buffers), specialised for V4's *interleaved* RoPE. + Interleaved RoPE: one `θ_i` per pair (`rope_head_dim // 2` entries), + DIFF no end-to-end duplication. Same shape as `inv_freq @ position_ids`. + + V4 deliberately decouples its architecture `layer_types` + (`sliding_attention` / `compressed_sparse_attention` / + `heavily_compressed_attention`) from its rope-type labels (`main` / + `compress`) — the latter live as keys in `config.rope_parameters` and + only differ in their `rope_theta` base. So this override replaces + Laguna's `set(config.layer_types)` iteration with `rope_parameters.keys()` + when building the per-type inv_freq buffers. + """ + + def __init__(self, config: DeepseekV41Config, device=None): + super().__init__() + self.max_seq_len_cached = config.max_position_embeddings + self.original_max_seq_len = config.max_position_embeddings + self.config = config + # Only the nested per-rope-type sub-dicts are real layer types — the top-level + # `rope_type` key that ``convert_rope_params_to_dict`` may leave on + # ``config.rope_parameters`` is a flat-shape leftover, not a layer. + self.layer_types = [k for k, v in config.rope_parameters.items() if isinstance(v, dict)] + self.rope_type = {} + for layer_type in self.layer_types: + rope_params = config.rope_parameters[layer_type] + self.rope_type[layer_type] = rope_params["rope_type"] + rope_init_fn = self.compute_default_rope_parameters + if self.rope_type[layer_type] != "default": + rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type[layer_type]] + inv_freq, attention_scaling = rope_init_fn(config, device, layer_type=layer_type) + setattr(self, f"{layer_type}_inv_freq", nn.Buffer(inv_freq, persistent=False)) + setattr(self, f"{layer_type}_original_inv_freq", nn.Buffer(inv_freq.clone(), persistent=False)) + setattr(self, f"{layer_type}_attention_scaling", attention_scaling) + + @staticmethod + def compute_default_rope_parameters( + config: DeepseekV41Config, device=None, layer_type: str | None = None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + layer_type (`str`, *optional*): + The current layer type if the model has different RoPE parameters per type. + Should not be used unless `config.layer_types is not None` + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters[layer_type]["rope_theta"] + # key difference to gemma3: partial rope + partial_rotary_factor = config.rope_parameters[layer_type].get("partial_rotary_factor", 1.0) + head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + dim = int(head_dim * partial_rotary_factor) + + attention_factor = 1.0 # Unused in this type of RoPE + + # Compute the inverse frequencies + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + return inv_freq.to(device), attention_factor + + @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) + def forward(self, x, position_ids, layer_type=None): + # Key difference vs Laguna's forward: no `torch.cat([freqs, freqs], dim=-1)` + # duplication. V4's interleaved RoPE pairs consecutive channels, so we only need + # `rope_head_dim // 2` unique θ entries — the `apply_rotary_pos_emb` helper does + # the `repeat_interleave(2)` next to the rotation math, where the link between + # the doubled dim and `rotate_half` is local and obvious. + inv_freq = getattr(self, f"{layer_type}_inv_freq") + attention_scaling = getattr(self, f"{layer_type}_attention_scaling") + freqs = position_ids[..., None].float() * inv_freq.to(device=x.device, dtype=torch.float) + cos = freqs.cos() * attention_scaling + sin = freqs.sin() * attention_scaling + return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) + + +class DeepseekV41GroupedLinear(nn.Linear): + """Block-diagonal grouped linear used by the grouped output projection + The core attention's stacked output is `num_attention_heads* head_dim`-dim, + which is *very* large (V4-Flash: 32768; V4-Pro: 65536). A direct + `num_attention_heads*head_dim → hidden_size` projection would dominate the per-token cost. + + The paper sidesteps that by splitting the heads into `g` groups, projecting + each `num_attention_heads * head_dim/g`-dim group independently to a `d_g`-dim intermediate output + (with `d_g < num_attention_heads * head_dim/g`), and then mixing the resulting `g·d_g` vector to + `hidden_size` through a single follow-up linear (`self_attn.o_b_proj`). This + module owns the per-group block (`self_attn.o_a_proj`). + + For V4-Flash (num_attention_heads=64, head_dim=512, o_groups=8, o_lora_rank=1024, + hidden_size=4096), g=8 groups of 4096-dim each are projected to 1024-dim, then + mixed to 4096-dim; for V4-Pro (num_attention_heads=128, head_dim=512, o_groups=16, + o_lora_rank=1024, hidden_size=7168), g=16 groups of 4096-dim each are projected + to 1024-dim, then mixed to 7168-dim. + """ + + def __init__(self, in_features_per_group: int, out_features: int, n_groups: int, bias: bool = False): + super().__init__(in_features_per_group, out_features, bias=bias) + self.n_groups = n_groups + + def forward(self, x: torch.Tensor) -> torch.Tensor: + input_shape = x.shape[:-2] + hidden_dim = x.shape[-1] + w = self.weight.view(self.n_groups, -1, hidden_dim).transpose(1, 2) + x = x.reshape(-1, self.n_groups, hidden_dim).transpose(0, 1) + y = torch.bmm(x, w).transpose(0, 1) + return y.reshape(*input_shape, self.n_groups, -1) + + +class DeepseekV41Float32Linear(nn.Linear): + """ + A linear layer that computes in float32, whatever dtype its weight is stored in. The reference promotes the + pooling projections of the compressor like this. + + The promotion happens in here rather than in the compressor, because offloaded weights (`device_map="auto"` + on a machine the model does not fit on) are only loaded while the module that owns them runs. + """ + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + return F.linear(hidden_states.float(), self.weight.float()) + + +class DeepseekV41Compressor(nn.Module): + """ + Pools every `compress_ratio` consecutive tokens into one KV latent with a learned softmax gate. With a + ratio of 1 there is nothing to pool, so the latent is a plain projection of each token. + + The groups are counted from the first real token of each row, and padding takes no part in them. So a + left-padded row gets the same latents as it would without the padding, but the rows of a batch do not + complete their groups in the same calls. + + Returns the latents of the groups that this call completes, *before* RoPE: the indexer makes its keys + from the unrotated latents, so the attention layer rotates them afterwards. The RoPE of each latent and + the number of groups that each row completes come back with them, and the latents after that number are + not real. A group whose last token has not arrived yet waits in the cache, or is dropped when there is no + cache. + """ + + def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): + super().__init__() + self.compress_ratio = config.compress_ratios[layer_idx] + if self.compress_ratio > 1: + # Several tokens per group, which are pooled in float32 + self.kv_proj = DeepseekV41Float32Linear(config.hidden_size, config.head_dim, bias=False) + self.gate_proj = DeepseekV41Float32Linear(config.hidden_size, config.head_dim, bias=False) + else: + # One token per group, so no gate and no pooling + self.kv_proj = nn.Linear(config.hidden_size, config.head_dim, bias=False) + self.gate_proj = None + self.kv_norm = DeepseekV41RMSNorm(config.head_dim, eps=config.rms_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor], + is_real_token: torch.Tensor, + num_seen_tokens: torch.Tensor, + cache_layer: DeepseekV41CacheLayer | None = None, + ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor], torch.Tensor]: + batch_size = hidden_states.shape[0] + ratio = self.compress_ratio + # First, what the groups are made of. The KV and the gate of a token stay together until the pooling, + # so we keep them in one tensor. The same goes for the cos and sin of the RoPE: for each token, the + # model has computed the RoPE of the entry that the token completes, if it is the last one of a group. + if self.gate_proj is None: + # One token per group, so no gate and no pooling + states = self.kv_proj(hidden_states) + else: + # The reference promotes the pooling weights to float32, and pools in float32 too + states = torch.cat([self.kv_proj(hidden_states), self.gate_proj(hidden_states)], dim=-1) + rope = torch.cat(position_embeddings, dim=-1).expand(batch_size, -1, -1) + + if cache_layer is not None and ratio > 1: + # The tokens that are still waiting for their group to fill up go first. The cache keeps the last + # `ratio - 1` real tokens of each row, and the ones that are waiting are the last of those. + if cache_layer.pooling_buffer is None: + cache_layer.pooling_buffer = states.new_zeros((batch_size, ratio - 1, states.shape[-1])) + num_waiting = num_seen_tokens % ratio + is_waiting = torch.arange(ratio - 1, device=states.device) >= ratio - 1 - num_waiting[:, None] + states = torch.cat([cache_layer.pooling_buffer, states], dim=1) + is_real_token = torch.cat([is_waiting, is_real_token], dim=1) + rope = F.pad(rope, (0, 0, ratio - 1, 0)) + + # Next, we bring the real tokens of each row to the front, in the order that they came in. Group `g` of + # a row is then its real tokens `g * ratio` to `(g + 1) * ratio - 1`, whatever padding the row has, + # and all that is not real ends up after the row's last whole group. + order = (~is_real_token).long().argsort(dim=1, stable=True) + states = states.gather(1, order[..., None].expand_as(states)) + rope = rope.gather(1, order[..., None].expand_as(rope)) + num_real_tokens = is_real_token.sum(dim=1) + + if cache_layer is not None and ratio > 1: + # The last `ratio - 1` real tokens of each row go back to the cache. A row with fewer of them reads + # its first token several times, but those copies come before the tokens that are waiting. + last_tokens = num_real_tokens[:, None] - (ratio - 1) + torch.arange(ratio - 1, device=states.device) + last_tokens = last_tokens.clamp(min=0)[..., None].expand(-1, -1, states.shape[-1]) + cache_layer.pooling_buffer = states.gather(1, last_tokens) + + # Finally, we pool the whole groups. The others are dropped here, and a row that has fewer real groups + # than the longest row gets latents that are made of padding, which the caller must not use. + usable = (states.shape[1] // ratio) * ratio + if self.gate_proj is None: + latents = self.kv_norm(states) + else: + kv, gate = states[:, :usable].unflatten(1, (-1, ratio)).chunk(2, dim=-1) + pooled = (kv * gate.softmax(dim=2)).sum(dim=2) + latents = self.kv_norm(pooled.to(hidden_states.dtype)) + cos, sin = rope[:, ratio - 1 : usable : ratio].chunk(2, dim=-1) + return latents, (cos, sin), num_real_tokens // ratio + + +def rotate_half(x): + """Rotates half the hidden dims of the input.""" + x1 = x[..., 0::2] + x2 = x[..., 1::2] + return torch.stack((-x2, x1), dim=-1).flatten(-2) + + +def apply_rotary_pos_emb( + x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, unsqueeze_dim: int = 1 +) -> torch.Tensor: + """V4 interleaved RoPE applied to the *trailing* rope slice of `x`. + + `cos` / `sin` come in half-sized (one entry per interleaved pair, from + `DeepseekV41RotaryEmbedding`); we expand them to the full rope dim with + `repeat_interleave`, then rotate the last `2 * cos.shape[-1]` channels of `x` + with the standard `x*cos + rotate_half(x)*sin` formula in fp32 and leave the + leading nope channels untouched. V4-Flash lays each head out as `[nope | rope]`, + matching the reference's `x[..., -rd:]` indexing. + """ + cos = cos.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim) + sin = sin.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim) + rope_dim = cos.shape[-1] + nope, rope = x[..., :-rope_dim], x[..., -rope_dim:] + rotated = ((rope.float() * cos) + (rotate_half(rope).float() * sin)).to(x.dtype) + return torch.cat([nope, rotated], dim=-1) + + +# The low-precision formats that activations are rounded to, as (largest value, mantissa bits, lowest normal +# exponent). FP8 is E4M3 and FP4 is E2M1. +MINIFLOAT_FORMATS = {"fp8": (448.0, 3, -6), "fp4": (6.0, 1, 0)} + + +def _round_to_minifloat(values: torch.Tensor, value_format: str) -> torch.Tensor: + max_value, mantissa_bits, min_exponent = MINIFLOAT_FORMATS[value_format] + # Casting to these formats saturates, so we clamp before we round + values = values.clamp(-max_value, max_value) + # Between two powers of two, the values of the format are evenly spaced, so we round to a multiple of the + # spacing. `frexp` gives `values = mantissa * 2**exponent` with `0.5 <= |mantissa| < 1`, so the power of two + # below a value is `2**(exponent - 1)`. Under the lowest normal exponent the spacing stops shrinking, which + # is where the subnormals are. + _, exponent = torch.frexp(values) + spacing = torch.ldexp(torch.ones_like(values), (exponent - 1).clamp(min=min_exponent) - mantissa_bits) + # `torch.round` sends ties to the even multiple, like the cast does + return torch.round(values / spacing) * spacing + + +def fake_quantize( + hidden_states: torch.Tensor, value_format: str, block_size: int, scale_format: str = "ue8m0" +) -> torch.Tensor: + """ + Rounds activations to the values that a low-precision float format can hold, and returns them in their own + dtype. The reference implementation does this to the KV, the attention output, the index keys and queries + and the compressed KV, mirroring the quantized formats that they are kept in during training. Nothing gets + smaller: the point is that the model sees the same rounded values as it was trained with. + + The last dim is cut into blocks of `block_size` values, and each block gets a scale of its own. The block + is divided by its scale, which brings its largest value to the top of the format's range, then rounded to + the format, then multiplied by the scale again. + + Args: + hidden_states (`torch.Tensor` of shape `(..., hidden_size)`): + The activations to round. `hidden_size` must be a multiple of `block_size`. + value_format (`str`): + The format to round to: `"fp8"` (E4M3, 3 mantissa bits, up to 448) or `"fp4"` (E2M1, 1 mantissa bit, + up to 6). + block_size (`int`): + Number of consecutive values that share a scale. + scale_format (`str`, *optional*, defaults to `"ue8m0"`): + The format of the scales: `"ue8m0"` for a power of two, or `"fp8"` for an FP8 number. + + Returns: + `torch.Tensor`: The rounded activations, with the shape and dtype of `hidden_states`. The gradient skips + the rounding and goes straight through to `hidden_states`. + + Example: + + ```python + >>> import torch + >>> hidden_states = torch.tensor([[0.3, -1.0, 2.6, 5.5]]) + >>> fake_quantize(hidden_states, value_format="fp4", block_size=4) + tensor([[ 0.5000, -1.0000, 3.0000, 6.0000]]) + + ``` + """ + max_value = MINIFLOAT_FORMATS[value_format][0] + # The reference computes the scales and the rounding in float32, whatever the dtype of the activations + blocks = hidden_states.detach().float().unflatten(-1, (-1, block_size)) + largest = blocks.abs().amax(dim=-1, keepdim=True) + if scale_format == "ue8m0": + # A power of two: the smallest one that still brings the largest value of the block into range. The + # floors keep the scale of an all-zero block away from zero. + largest = largest.clamp(min=1e-4 if value_format == "fp8" else max_value * 2.0**-126) + # We want `2**ceil(log2(x))` to the bit, which `torch.log2` cannot promise around powers of two. + # `frexp` can: `x = mantissa * 2**exponent` with `0.5 <= mantissa < 1`, and only a power of two has a + # mantissa of exactly 0.5. + mantissa, exponent = torch.frexp(largest * (1.0 / max_value)) + scale = torch.ldexp(torch.ones_like(largest), exponent - (mantissa == 0.5).int()) + elif scale_format == "fp8": + # An FP8 number, which follows the largest value more closely than a power of two does. The floor is + # the smallest FP8 number, so again the scale of an all-zero block is not zero. + scale = _round_to_minifloat(largest.clamp(min=max_value * 2.0**-9) / max_value, "fp8") + else: + raise ValueError(f'`scale_format` must be "ue8m0" or "fp8", but got "{scale_format}".') + + quantized = _round_to_minifloat(blocks / scale, value_format) * scale + quantized = quantized.flatten(-2).to(hidden_states.dtype) + if hidden_states.requires_grad: + # Straight-through estimator: rounding has a gradient of zero almost everywhere, so the backward pass + # treats it as the identity. The term that we add is exactly zero, so the values stay the rounded ones. + quantized = quantized + (hidden_states - hidden_states.detach()) + return quantized + + +def select_candidate_blocks( + scores: torch.Tensor, num_visible: torch.Tensor, topk_blocks: int, block_size: int +) -> torch.Tensor: + """ + First level of the two-level top-k: keep the `topk_blocks` best blocks of compressed positions per query. + + Args: + scores (`torch.Tensor` of shape `(batch_size, seq_len, num_entries)`): + Index scores, with the entries a query cannot see yet already at `-inf`. + num_visible (`torch.Tensor` of shape `(batch_size, seq_len)`): + How many compressed entries each query can see. + topk_blocks (`int`): + Number of blocks to keep per query. + block_size (`int`): + Number of compressed positions per block. + + Returns: + `torch.Tensor`: A boolean mask shaped like `scores`, `True` for the entries inside a kept block. + + Example: + + ```python + >>> import torch + >>> scores = torch.tensor([[[0.1, 0.9, 0.3, 0.2, 0.8, float("-inf")]]]) + >>> select_candidate_blocks(scores, num_visible=torch.tensor([[5]]), topk_blocks=2, block_size=2) + tensor([[[ True, True, False, False, True, True]]]) + + ``` + """ + num_entries = scores.shape[-1] + # Score each block by its best position, with `-inf` padding the last block out to `block_size` + block_scores = F.pad(scores, (0, -num_entries % block_size), value=float("-inf")) + block_scores = block_scores.unflatten(-1, (-1, block_size)).amax(dim=-1) + num_blocks = block_scores.shape[-1] + + # The block with the query's newest position is only partly filled, so we always keep it: it holds the + # most recent tokens, but an older full block could outscore it + last_block = (num_visible.unsqueeze(-1) - 1) // block_size + is_last_block = torch.arange(num_blocks, device=scores.device) == last_block + block_scores = block_scores.masked_fill(is_last_block, float("inf")) + + top = block_scores.topk(min(topk_blocks, num_blocks), dim=-1) + # With fewer visible blocks than `topk_blocks`, the leftover picks come back as `-inf`, so we drop them + keep = torch.zeros_like(block_scores, dtype=torch.bool).scatter_(-1, top.indices, top.values > float("-inf")) + return keep.repeat_interleave(block_size, dim=-1)[..., :num_entries] + + +class DeepseekV41Indexer(nn.Module): + """ + Picks the `index_topk` compressed entries that each query attends to. + + This is a small side attention: several query heads are scored against one shared key per compressed + entry, the scores are rectified, and then combined across heads with per-token weights. The keys are made + from the compressor's latents, so only an indexer that sits in a `"compressed_attention"` layer has the + modules to make them (`k_proj` and `k_norm`). The other indexers read those same keys. + + With a candidate source this is the second of two levels, see `select_candidate_blocks` for the first. + """ + + def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): + super().__init__() + self.compress_ratio = config.compress_ratios[layer_idx] + self.num_heads = config.index_n_heads + self.head_dim = config.index_head_dim + self.index_topk = config.index_topk + self.scaling = self.head_dim**-0.5 * self.num_heads**-0.5 + self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False) + self.weights_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False) + if layer_idx in config.kv_source_layer_ids: + self.k_proj = nn.Linear(config.head_dim, self.head_dim, bias=False) + self.k_norm = DeepseekV41RMSNorm(self.head_dim, eps=config.rms_norm_eps) + + candidate_source = config.candidate_source_layer_id + self.is_candidate_source = candidate_source is not None and layer_idx == candidate_source + self.uses_candidates = candidate_source is not None and layer_idx > candidate_source + self.candidate_topk_blocks = config.candidate_topk_blocks + self.candidate_block_size = config.candidate_block_size + + def forward( + self, + hidden_states: torch.Tensor, + q_residual: torch.Tensor, + index_keys: torch.Tensor, + num_real_tokens: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor], + candidates: torch.Tensor | None = None, + ) -> tuple[torch.Tensor, torch.Tensor | None]: + batch_size, seq_len, _ = hidden_states.shape + num_entries = index_keys.shape[1] + if num_entries == 0: + # No group is complete yet, so there is nothing to select + empty = torch.zeros((batch_size, seq_len, 0), dtype=torch.bool, device=hidden_states.device) + return empty, empty if self.is_candidate_source else candidates + + cos, sin = position_embeddings + queries = self.q_b_proj(q_residual).view(batch_size, seq_len, self.num_heads, self.head_dim) + queries = apply_rotary_pos_emb(queries, cos, sin, unsqueeze_dim=2) + # The index keys are FP4 as well, see the attention layer that makes them + queries = fake_quantize(queries, "fp4", block_size=32) + scores = torch.einsum("bshd,btd->bsht", queries, index_keys.to(queries.dtype)) + weights = self.weights_proj(hidden_states) * self.scaling + scores = (F.relu(scores) * weights.unsqueeze(-1)).sum(dim=2) + + # A query sees a compressed entry once it has passed the last token of the entry's group. The groups are + # made of real tokens only, so we count those, up to and including the query. This is also what hides + # the slots after the last entry of a row that has fewer entries than the others. + num_visible = num_real_tokens // self.compress_ratio + visible = torch.arange(num_entries, device=scores.device) < num_visible.unsqueeze(-1) + scores = scores.masked_fill(~visible, float("-inf")) + + if self.is_candidate_source: + # First level: this layer chooses the blocks that the indexers after it may select from + candidates = select_candidate_blocks( + scores, num_visible, self.candidate_topk_blocks, self.candidate_block_size + ) + elif self.uses_candidates: + # Second level: we score with our own weights, but only inside the source's candidate blocks + scores = scores.masked_fill(~candidates, float("-inf")) + + top_scores, top_indices = scores.topk(min(self.index_topk, num_entries), dim=-1) + # Queries with fewer reachable entries than `index_topk` get `-inf` picks back, which we drop + selected = torch.zeros_like(scores, dtype=torch.bool).scatter_(-1, top_indices, top_scores > float("-inf")) + return selected, candidates + + +def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: + """ + This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, + num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) + """ + batch, num_key_value_heads, slen, head_dim = hidden_states.shape + if n_rep == 1: + return hidden_states + hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) + return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) + + +def eager_attention_forward( + module: nn.Module, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: torch.Tensor | None, + scaling: float, + dropout: float | int = 0.0, + **kwargs, +): + key_states = repeat_kv(key, module.num_key_value_groups) + value_states = repeat_kv(value, module.num_key_value_groups) + attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling + if attention_mask is not None: + attn_weights = attn_weights + attention_mask + + sinks = module.sinks.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1) + combined_logits = torch.cat([attn_weights, sinks], dim=-1) + + # This was not in the original implementation and slightly affect results; it prevents overflow in BF16/FP16 + # when training with bsz>1 we clamp max values. + + combined_logits = combined_logits - combined_logits.max(dim=-1, keepdim=True).values + probs = F.softmax(combined_logits, dim=-1, dtype=combined_logits.dtype) + scores = probs[..., :-1] # we drop the sink here + attn_weights = nn.functional.dropout(scores, p=dropout, training=module.training).to(value_states.dtype) + attn_output = torch.matmul(attn_weights, value_states) + attn_output = attn_output.transpose(1, 2).contiguous() + return attn_output, attn_weights + + +class DeepseekV41Attention(nn.Module): + r""" + Attention over a sliding window, which is all that the `"sliding_attention"` layers do. The other layer + types also attend to compressed KV entries, which go after the window on the KV axis: + + * `"compressed_attention"` compresses KV of its own. It also makes the index keys for them and runs an + indexer over those keys. The KV-sharing layers after it read all three: the compressed KV, the index + keys and the selection. + * `"kv_shared_indexed_attention"` reads the compressed KV of the last `"compressed_attention"` layer, and + runs its own indexer to select which of them each query attends to. + * `"kv_shared_attention"` reads those compressed KV too, and reuses the selection of the last layer that + ran an indexer. + + Shared with DeepSeek-V4: + * Shared-KV multi-query attention: there is a single KV head, and the same tensor is read as both key and + value. + * Partial RoPE on the last `qk_rope_head_dim` dims of each head. Since the values carry RoPE too, the + output is rotated back at the query's position before the output projection. + * A learnable attention sink per head, and a grouped low-rank output projection. + """ + + def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): + super().__init__() + self.config = config + self.layer_idx = layer_idx + self.layer_type = config.attention_layer_types[layer_idx] + # A layer that reads compressed KV uses their RoPE base for everything, its window included + self.rope_layer_type = "main" if self.layer_type == "sliding_attention" else "compress" + self.compress_ratio = config.compress_ratios[layer_idx] + self.num_heads = config.num_attention_heads + self.num_key_value_groups = config.num_attention_heads # single KV head, broadcast to all + self.head_dim = config.head_dim + self.sliding_window = config.sliding_window + self.attention_dropout = config.attention_dropout + self.is_causal = True + self.scaling = self.head_dim**-0.5 + + self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=False) + self.q_a_norm = DeepseekV41RMSNorm(config.q_lora_rank, eps=config.rms_norm_eps) + self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False) + self.kv_proj = nn.Linear(config.hidden_size, self.head_dim, bias=False) + self.kv_norm = DeepseekV41RMSNorm(self.head_dim, eps=config.rms_norm_eps) + self.o_a_proj = DeepseekV41GroupedLinear( + self.num_heads * self.head_dim // config.o_groups, config.o_groups * config.o_lora_rank, config.o_groups + ) + self.o_b_proj = nn.Linear(config.o_groups * config.o_lora_rank, config.hidden_size, bias=False) + self.sinks = nn.Parameter(torch.empty(self.num_heads, dtype=torch.float32)) + if self.layer_type in ("compressed_attention", "kv_shared_indexed_attention"): + self.indexer = DeepseekV41Indexer(config, layer_idx) + if self.layer_type == "compressed_attention": + self.compressor = DeepseekV41Compressor(config, layer_idx) + + def forward( + self, + hidden_states: torch.Tensor, + position_embeddings: dict[str, tuple[torch.Tensor, torch.Tensor]], + attention_mask: torch.Tensor, + is_real_token: torch.Tensor, + num_seen_tokens: torch.Tensor, + cache: Cache | None = None, + shared_states: dict[str, torch.Tensor] | None = None, + compressed_position_embeddings: dict[int, tuple[torch.Tensor, torch.Tensor]] | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple[torch.Tensor, torch.Tensor | None, dict[str, torch.Tensor]]: + input_shape = hidden_states.shape[:-1] + # We return what we publish in a new dict, and leave the one we were given alone. With gradient + # checkpointing this layer runs again in the backward pass, long after the layers after it, and it has + # to read the same states as the first time. + shared_states = dict(shared_states or {}) + hidden_shape = (*input_shape, -1, self.head_dim) + # The model computes RoPE for both bases, and each layer picks the one that matches its attention type + cos, sin = position_embeddings[self.rope_layer_type] + + q_residual = self.q_a_norm(self.q_a_proj(hidden_states)) + q = self.q_b_proj(q_residual).view(*hidden_shape).transpose(1, 2) + q = apply_rotary_pos_emb(q, cos, sin) + + kv = self.kv_norm(self.kv_proj(hidden_states)).view(*hidden_shape).transpose(1, 2) + kv = apply_rotary_pos_emb(kv, cos, sin) + # The KV are FP8 from here on, in the cache too. They are rounded after RoPE, so on the rotated dims + # it is the rotated values that land on the FP8 grid. + kv = fake_quantize(kv, "fp8", block_size=32) + if cache is not None: + kv = cache.update(kv, kv, self.layer_idx)[0] + + if self.layer_type == "compressed_attention": + # This layer compresses the groups that this call completes. A row may complete none of them, e.g. + # when decoding a token that is not the last of its group. + cache_layer: DeepseekV41CacheLayer | None = cache.layers[self.layer_idx] if cache is not None else None + latents, (entry_cos, entry_sin), num_new_entries = self.compressor( + hidden_states, + compressed_position_embeddings[self.compress_ratio], + is_real_token, + num_seen_tokens, + cache_layer, + ) + # The index keys come from the latents before RoPE, so we make them before we rotate the latents + index_keys = self.indexer.k_norm(self.indexer.k_proj(latents)) + index_keys = apply_rotary_pos_emb(index_keys.unsqueeze(1), entry_cos, entry_sin).squeeze(1) + compressed_kv = apply_rotary_pos_emb(latents.unsqueeze(1), entry_cos, entry_sin).squeeze(1) + # Both are FP4 from here on. The compressed KV get a finer scale than the index keys: one per 16 + # values instead of 32, and an FP8 number instead of a power of two. + index_keys = fake_quantize(index_keys, "fp4", block_size=32) + compressed_kv = fake_quantize(compressed_kv, "fp4", block_size=16, scale_format="fp8") + if cache_layer is not None: + # Each row has one entry per whole group of the tokens that it had seen before this call + compressed_kv, index_keys = cache_layer.update_compressed_states( + compressed_kv, index_keys, num_seen_tokens // self.compress_ratio, num_new_entries + ) + # We publish both for the indexers and the KV-sharing layers after us, starting with our own + shared_states["compressed_kv"], shared_states["index_keys"] = compressed_kv, index_keys + + if self.layer_type in ("compressed_attention", "kv_shared_indexed_attention"): + # This layer selects which compressed entries each query attends to, and the + # `"kv_shared_attention"` layers after it reuse the selection + shared_states["selected"], shared_states["candidates"] = self.indexer( + hidden_states, + q_residual, + shared_states["index_keys"], + num_seen_tokens[:, None] + is_real_token.cumsum(dim=-1), + (cos, sin), + shared_states.get("candidates"), + ) + + if self.layer_type != "sliding_attention": + # The compressed entries go after the window on the KV axis. The model built the mask for the + # window only, so we extend it with the entries that each query selected. + compressed_kv, selected = shared_states["compressed_kv"], shared_states["selected"] + kv = torch.cat([kv, compressed_kv.unsqueeze(1).to(kv.dtype)], dim=2) + compressed_mask = torch.zeros_like(selected, dtype=attention_mask.dtype) + compressed_mask = compressed_mask.masked_fill(~selected, torch.finfo(attention_mask.dtype).min) + attention_mask = torch.cat([attention_mask, compressed_mask.unsqueeze(1)], dim=-1) + + attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( + self.config._attn_implementation, eager_attention_forward + ) + attn_output, attn_weights = attention_interface( + self, + q, + kv, + kv, + attention_mask, + dropout=0.0 if not self.training else self.attention_dropout, + scaling=self.scaling, + sliding_window=self.sliding_window, + s_aux=self.sinks, + **kwargs, + ) + + # The values are the keys, so they picked up RoPE too. We undo it on the output with the conjugate + # rotation at the query's position, before the grouped output projection mixes the heads. + attn_output = apply_rotary_pos_emb(attn_output, cos, -sin, unsqueeze_dim=2) + + grouped = attn_output.reshape(*input_shape, self.config.o_groups, -1) + # The grouped projection was trained as an FP8 matmul, which rounds its input to FP8 + grouped = fake_quantize(grouped, "fp8", block_size=32) + grouped = self.o_a_proj(grouped).flatten(2) + output = self.o_b_proj(grouped) + return output, attn_weights, shared_states + + +class DeepseekV41HyperConnection(nn.Module): + r""" + Computes the hyper-connection weights of one sublayer (attention or MLP) from the `hc_mult` residual + streams. As in DeepSeek-V4, there are three of them: + + - pre: collapses the `hc_mult` streams into the single input of a sublayer + - post: expands the output of the sublayer back into `hc_mult` streams + - comb: mixes the `hc_mult` input streams into the output streams, and is made doubly stochastic with a few + iterations of the Sinkhorn-Knopp algorithm + + Unlike DeepSeek-V4, "pre" is not used by the sublayer that these weights belong to. It collapses the + streams for the *next* sublayer, so we return it instead of applying it here. See + `DeepseekV41DecoderLayer` for how the weights are passed along. + """ + + def __init__(self, config: DeepseekV41TextConfig): + super().__init__() + self.hc_mult = config.hc_mult + self.hc_sinkhorn_iters = config.hc_sinkhorn_iters + self.hc_eps = config.hc_eps + self.norm_eps = config.rms_norm_eps + # The three weights come out of a single projection: pre and post have `hc_mult` entries each, and comb + # is a `hc_mult x hc_mult` matrix + concatenated_weights_size = (2 + self.hc_mult) * self.hc_mult + self.fn = nn.Parameter(torch.empty(concatenated_weights_size, self.hc_mult * config.hidden_size)) + self.base = nn.Parameter(torch.empty(concatenated_weights_size)) + self.scale = nn.Parameter(torch.empty(3)) + + def forward(self, hidden_streams: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + hc = self.hc_mult + # The streams are normalized together, with one statistic per token + flattened = hidden_streams.flatten(2).float() + rsqrt = torch.rsqrt(flattened.square().mean(-1, keepdim=True) + self.norm_eps) + mixes = F.linear(flattened, self.fn.float()) * rsqrt + + pre_w, post_w, comb_w = mixes.split([hc, hc, hc * hc], dim=-1) + pre_b, post_b, comb_b = self.base.float().split([hc, hc, hc * hc]) + pre_scale, post_scale, comb_scale = self.scale.float().unbind(0) + + pre = torch.sigmoid(pre_w * pre_scale + pre_b) + self.hc_eps + post = 2 * torch.sigmoid(post_w * post_scale + post_b) + comb = comb_w.unflatten(-1, (hc, hc)) * comb_scale + comb_b.view(hc, hc) + comb = torch.softmax(comb, dim=-1) + self.hc_eps + + # Sinkhorn-Knopp: alternately normalize the columns and the rows, so that both end up summing to 1 + comb = comb / (comb.sum(dim=-2, keepdim=True) + self.hc_eps) + for _ in range(self.hc_sinkhorn_iters - 1): + comb = comb / (comb.sum(dim=-1, keepdim=True) + self.hc_eps) + comb = comb / (comb.sum(dim=-2, keepdim=True) + self.hc_eps) + return pre, post, comb + + +class DeepseekV41MLP(nn.Module): + def __init__(self, config: DeepseekV41Config): + super().__init__() + self.config = config + self.hidden_size = config.hidden_size + self.intermediate_size = config.intermediate_size + self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) + self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) + self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias) + self.act_fn = ACT2FN[config.hidden_act] + self.limit = config.swiglu_limit + + def forward(self, x: torch.Tensor) -> torch.Tensor: + gate = self.gate_proj(x).clamp(max=self.limit) + up = self.up_proj(x).clamp(min=-self.limit, max=self.limit) + return self.down_proj(self.act_fn(gate) * up) + + +@use_experts_implementation +class DeepseekV41Experts(nn.Module): + """Collection of expert weights stored as 3D tensors.""" + + def __init__(self, config: DeepseekV41Config): + super().__init__() + self.num_experts = config.num_local_experts + self.hidden_dim = config.hidden_size + self.intermediate_dim = config.intermediate_size + self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim)) + self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim)) + self.act_fn = ACT2FN[config.hidden_act] + self.limit = config.swiglu_limit + + def forward( + self, hidden_states: torch.Tensor, top_k_index: torch.Tensor, top_k_weights: torch.Tensor + ) -> torch.Tensor: + final = torch.zeros_like(hidden_states) + with torch.no_grad(): + mask = F.one_hot(top_k_index, num_classes=self.num_experts + 1).permute(2, 1, 0) + hit = torch.greater(mask.sum(dim=(-1, -2)), 0).nonzero() + for expert_idx in hit: + expert_idx = expert_idx[0] + if expert_idx == self.num_experts: + continue + top_k_pos, token_idx = torch.where(mask[expert_idx]) + current = self._apply_gate(F.linear(hidden_states[token_idx], self.gate_up_proj[expert_idx])) + current = F.linear(current, self.down_proj[expert_idx]) * top_k_weights[token_idx, top_k_pos, None] + final.index_add_(0, token_idx, current.to(final.dtype)) + return final + + def _apply_gate(self, gate_up: torch.Tensor) -> torch.Tensor: + # Lives on the class (like gpt-oss's _apply_gate) so the grouped_mm / batched_mm + # backends swapped in by `@use_experts_implementation` apply the same clamp + + # SiLU on top of their packed gate_up output instead of bypassing it. + gate, up = gate_up.chunk(2, dim=-1) + gate = gate.clamp(max=self.limit) + up = up.clamp(min=-self.limit, max=self.limit) + return self.act_fn(gate) * up + + +class DeepseekV41TopKRouter(nn.Module): + """ + Top-k router. The correction bias only steers which experts are selected, and the routing weights come + from the unbiased scores. The tokens of an image use a separate bias. + """ + + def __init__(self, config: DeepseekV41TextConfig): + super().__init__() + self.top_k = config.num_experts_per_tok + self.num_experts = config.num_local_experts + self.hidden_dim = config.hidden_size + self.weight = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim)) + self.score_fn = ACT2FN[config.scoring_func] + self.routed_scaling_factor = config.routed_scaling_factor + self.e_score_correction_bias = nn.Buffer(torch.zeros(self.num_experts, dtype=torch.float32)) + self.e_score_correction_bias_vl = nn.Buffer(torch.zeros(self.num_experts, dtype=torch.float32)) + + def forward( + self, hidden_states: torch.Tensor, image_mask: torch.Tensor | None = None + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + flat = hidden_states.reshape(-1, self.hidden_dim) + # The reference routes in float32, and the selection is sensitive enough that bfloat16 changes it + logits = F.linear(flat.float(), self.weight.float()) + scores = self.score_fn(logits) + bias = self.e_score_correction_bias + if image_mask is not None: + bias = torch.where(image_mask.reshape(-1, 1), self.e_score_correction_bias_vl, bias) + indices = torch.topk(scores + bias, self.top_k, dim=-1, sorted=False).indices + weights = scores.gather(1, indices) + weights = weights / (weights.sum(dim=-1, keepdim=True) + 1e-20) + return logits, weights * self.routed_scaling_factor, indices + + +class DeepseekV41SparseMoeBlock(nn.Module): + def __init__(self, config: DeepseekV41TextConfig): + super().__init__() + self.gate = DeepseekV41TopKRouter(config) + self.experts = DeepseekV41Experts(config) + self.shared_experts = DeepseekV41MLP(config) + + def forward(self, hidden_states: torch.Tensor, image_mask: torch.Tensor | None = None) -> torch.Tensor: + batch_size, seq_len, hidden_dim = hidden_states.shape + _, weights, indices = self.gate(hidden_states, image_mask) + routed = self.experts(hidden_states.view(-1, hidden_dim), indices, weights) + return routed.view(batch_size, seq_len, hidden_dim) + self.shared_experts(hidden_states) + + +def _is_prime(number: int) -> bool: + if number < 2: + return False + if number % 2 == 0: + return number == 2 + divisor = 3 + while divisor * divisor <= number: + if number % divisor == 0: + return False + divisor += 2 + return True + + +def _engram_bucket_sizes(config: DeepseekV41TextConfig) -> list[list[int]]: + # Every (n-gram size, head) pair of every Engram layer hashes into its own range of buckets. The size of + # each range is a prime, and no prime is used twice across the whole model. For each n-gram size the + # search restarts just below `engram_vocab_size`, so we end up handing out consecutive primes. + bucket_sizes, seen = [], set() + for _ in config.engram_layer_ids: + layer_sizes = [] + for _ in range(config.engram_max_ngram_size - 1): + candidate = config.engram_vocab_size - 1 + for _ in range(config.engram_n_heads): + candidate += 1 + while candidate in seen or not _is_prime(candidate): + candidate += 1 + seen.add(candidate) + layer_sizes.append(candidate) + bucket_sizes.append(layer_sizes) + return bucket_sizes + + +def _engram_hash_multipliers(config: DeepseekV41TextConfig) -> np.ndarray: + # One multiplier per (layer, lookback), from a per-layer RNG so that the layers hash differently. They + # are kept odd, and bounded so that `token_id * multiplier` cannot overflow int64. + bound = max(1, (np.iinfo(np.int64).max // config.engram_compressed_vocab_size) // 2) + rows = [] + for layer_idx in config.engram_layer_ids: + generator = np.random.default_rng(10007 * layer_idx) + values = generator.integers(low=0, high=bound, size=(config.engram_max_ngram_size,), dtype=np.int64) + rows.append(values * 2 + 1) + return np.stack(rows) + + +def _default_engram_token_map(config: DeepseekV41TextConfig) -> torch.Tensor: + if config.engram_compressed_vocab_size == config.vocab_size: + # A compressed vocab as large as the vocab itself merges no tokens, so the map is the identity + return torch.arange(config.vocab_size) + # Otherwise the map comes from the tokenizer (see `build_engram_token_map`), and -1 marks it as missing + return torch.full((config.vocab_size,), -1, dtype=torch.long) + + +class DeepseekV41NgramHasher(nn.Module): + """ + Maps each position to the hash ids of the n-grams that end there, for all Engram layers at once. + + Token ids first go through `token_map`, then each position is hashed together with the + `engram_max_ngram_size - 1` tokens before it. The look-back stops at the start of the sequence and at any + masked token (padding or an image), so an n-gram never spans one. + """ + + def __init__(self, config: DeepseekV41TextConfig): + super().__init__() + self.config = config + self.max_ngram_size = config.engram_max_ngram_size + self.num_heads = config.engram_n_heads + self.pad_token_id = config.engram_pad_token_id + bucket_sizes = torch.tensor(_engram_bucket_sizes(config)) + self.bucket_sizes = nn.Buffer(bucket_sizes, persistent=False) + self.offsets = nn.Buffer(bucket_sizes.cumsum(-1) - bucket_sizes, persistent=False) + self.multipliers = nn.Buffer(torch.from_numpy(_engram_hash_multipliers(config)), persistent=False) + self.token_map = nn.Buffer(_default_engram_token_map(config)) + + def forward( + self, + input_ids: torch.Tensor, + token_mask: torch.Tensor | None = None, + cache_layer: DeepseekV41CacheLayer | None = None, + ) -> torch.Tensor: + compressed_ids = self.token_map[input_ids] + if (compressed_ids < 0).any(): + raise ValueError( + "The Engram token map has no entry for some of the input ids. The DeepSeek-V4.1 checkpoints do " + "not store this map, so it has to be built from the tokenizer once after loading the model:\n" + "`model.set_engram_token_map(tokenizer)`" + ) + # A masked token takes no part in any n-gram. We mark it with -1, like the start of the sequence. + if token_mask is not None: + compressed_ids = torch.where(token_mask, compressed_ids, -1) + history_length = self.max_ngram_size - 1 + if cache_layer is not None: + compressed_ids = cache_layer.update_token_history(compressed_ids, history_length) + else: + compressed_ids = F.pad(compressed_ids, (history_length, 0), value=-1) + + # One window per position: the token itself comes first, then the tokens before it, nearest first. + # Once the look-back hits a -1, that slot and all the ones behind it read as padding. + windows = compressed_ids.unfold(1, self.max_ngram_size, 1).flip(-1) + blocked = (windows == -1).cummax(dim=-1).values + windows = torch.where(blocked, self.token_map[self.pad_token_id], windows) + + # We XOR the multiplied ids together one look-back at a time, so the running value after step `i` is + # the hash of the (i+1)-gram. Each one lands in its own prime-sized range of buckets. + products = windows.unsqueeze(2) * self.multipliers + rolling, hash_ids = products[..., 0], [] + for ngram_index in range(history_length): + rolling = torch.bitwise_xor(rolling, products[..., ngram_index + 1]) + sizes = self.bucket_sizes[:, ngram_index * self.num_heads : (ngram_index + 1) * self.num_heads] + hash_ids.append(rolling.unsqueeze(-1) % sizes) + return torch.cat(hash_ids, dim=-1) + self.offsets + + +class DeepseekV41Engram(nn.Module): + """ + Writes an n-gram lookup into the residual streams, gated by how well it matches each stream. + + The hash ids fetch one row of the table per (n-gram size, head) pair. `kv_proj` turns the concatenated + rows into one key per stream plus a value that the streams share, and the gate of a stream is the + normalized dot product of the stream with its key. + """ + + def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): + super().__init__() + self.hidden_size = config.hidden_size + self.hc_mult = config.hc_mult + self.eps = config.rms_norm_eps + engram_index = config.engram_layer_ids.index(layer_idx) + num_embeddings = sum(_engram_bucket_sizes(config)[engram_index]) + if config.engram_num_embeddings is not None and config.engram_num_embeddings[engram_index] != num_embeddings: + raise ValueError( + f"The Engram table of layer {layer_idx} needs {num_embeddings} rows, which is the sum of its bucket " + f"sizes, but `engram_num_embeddings` says {config.engram_num_embeddings[engram_index]}. The bucket " + "sizes come from `engram_vocab_size`, `engram_n_heads`, `engram_max_ngram_size` and " + "`engram_layer_ids`, so one of those does not match the checkpoint." + ) + num_lookups = (config.engram_max_ngram_size - 1) * config.engram_n_heads + self.embed = nn.Embedding(num_embeddings, config.engram_head_dim) + self.kv_proj = nn.Linear( + num_lookups * config.engram_head_dim, config.hidden_size * (config.hc_mult + 1), bias=False + ) + self.q_weight = nn.Parameter(torch.ones(config.hc_mult, config.hidden_size)) + self.k_weight = nn.Parameter(torch.ones(config.hc_mult, config.hidden_size)) + + def forward( + self, hidden_streams: torch.Tensor, hash_ids: torch.Tensor, token_mask: torch.Tensor | None = None + ) -> torch.Tensor: + key_value = self.kv_proj(self.embed(hash_ids).flatten(-2).to(hidden_streams.dtype)) + key, value = key_value.split([self.hc_mult * self.hidden_size, self.hidden_size], dim=-1) + key = key.float().unflatten(-1, (self.hc_mult, self.hidden_size)) + streams = hidden_streams.float() + # The two weights are only ever used as a product + weight = self.q_weight.float() * self.k_weight.float() + # Normalized per (token, stream) over the hidden dim, NOT jointly over the streams + rsqrt = torch.rsqrt(streams.square().mean(-1) + self.eps) * torch.rsqrt(key.square().mean(-1) + self.eps) + dot = (streams * weight * key).sum(-1) * rsqrt * self.hidden_size**-0.5 + # Signed square root before the sigmoid, as in training + gate = torch.sigmoid(torch.copysign(dot.abs().clamp_min(1e-6).sqrt(), dot)) + if token_mask is not None: + gate = gate.masked_fill(~token_mask.unsqueeze(-1), 0) + return (streams + gate.unsqueeze(-1) * value.float().unsqueeze(-2)).to(hidden_streams.dtype) + + +class DeepseekV41DecoderLayer(GradientCheckpointingLayer): + r""" + DeepSeek-V4.1 decoder block. As in DeepSeek-V4, the residual is a stack of `hc_mult` parallel streams of + shape `[B, S, hc_mult, D]`, which hyper-connections collapse into the input of each sublayer and expand + back out afterwards. + + What changes is where the collapsing weights come from. Each sublayer's hyper-connection computes "pre", + "post" and "comb" from the streams that enter the sublayer, but only "post" and "comb" are used there. Its + "pre" collapses the streams for the *next* sublayer: the attention uses the "pre" of the previous layer's + MLP, and the MLP uses the "pre" of this layer's attention. So the layer takes one "pre" in and returns one. + """ + + def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): + super().__init__() + self.layer_idx = layer_idx + self.self_attn = DeepseekV41Attention(config, layer_idx) + self.mlp = DeepseekV41SparseMoeBlock(config) + self.input_layernorm = DeepseekV41RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_attention_layernorm = DeepseekV41RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.attn_hc = DeepseekV41HyperConnection(config).to(dtype=torch.float32) + self.ffn_hc = DeepseekV41HyperConnection(config).to(dtype=torch.float32) + self.engram = DeepseekV41Engram(config, layer_idx) if layer_idx in config.engram_layer_ids else None + + def forward( + self, + hidden_states: torch.Tensor, + pre: torch.Tensor, + engram_hash_ids: torch.Tensor | None = None, + engram_mask: torch.Tensor | None = None, + image_mask: torch.Tensor | None = None, + shared_states: dict[str, torch.Tensor] | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple[torch.Tensor, torch.Tensor, dict[str, torch.Tensor]]: + # hidden_states throughout: [B, S, hc_mult, hidden]. The hyper-connection weights are float32, and + # comb is used transposed: sum_j comb[j, k] * residual[j], which is comb.T @ residual. + dtype = hidden_states.dtype + if self.engram is not None: + hidden_states = self.engram(hidden_states, engram_hash_ids, engram_mask) + + attn_pre, post, comb = self.attn_hc(hidden_states) + collapsed = (pre.unsqueeze(-1) * hidden_states.float()).sum(dim=2).to(dtype) + attn_output, _, shared_states = self.self_attn( + self.input_layernorm(collapsed), shared_states=shared_states, **kwargs + ) + hidden_states = post.unsqueeze(-1) * attn_output.unsqueeze(-2) + torch.matmul( + comb.transpose(-1, -2), hidden_states.float() + ) + hidden_states = hidden_states.to(dtype) + + mlp_pre, post, comb = self.ffn_hc(hidden_states) + collapsed = (attn_pre.unsqueeze(-1) * hidden_states.float()).sum(dim=2).to(dtype) + mlp_output = self.mlp(self.post_attention_layernorm(collapsed), image_mask=image_mask) + hidden_states = post.unsqueeze(-1) * mlp_output.unsqueeze(-2) + torch.matmul( + comb.transpose(-1, -2), hidden_states.float() + ) + return hidden_states.to(dtype), mlp_pre, shared_states + + +def vision_eager_attention_forward( + module: nn.Module, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: torch.Tensor | None, + scaling: float, + dropout: float | int = 0.0, + **kwargs, +): + # Plain attention. The eager function of the language model adds an attention sink, which the vision encoder + # does not have. + attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling + if attention_mask is not None: + attn_weights = attn_weights + attention_mask + attn_weights = F.softmax(attn_weights, dim=-1) + attn_weights = F.dropout(attn_weights, p=dropout, training=module.training) + attn_output = torch.matmul(attn_weights, value) + return attn_output.transpose(1, 2).contiguous(), attn_weights + + +def _apply_vision_rotary(hidden_states: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: + # The first half of each head is rotated against the second half, in float32 + first, second = hidden_states.float().chunk(2, dim=-1) + rotated = torch.cat([first * cos - second * sin, second * cos + first * sin], dim=-1) + return rotated.to(hidden_states.dtype) + + +class DeepseekV41VisionAttention(nn.Module): + """Bidirectional attention over the patches of one image, with 2D RoPE.""" + + def __init__(self, config: DeepseekV41VisionConfig): + super().__init__() + self.config = config + self.num_heads = config.num_attention_heads + self.head_dim = config.hidden_size // config.num_attention_heads + self.scaling = self.head_dim**-0.5 + self.qkv_proj = nn.Linear(config.hidden_size, 3 * config.hidden_size) + self.o_proj = nn.Linear(config.hidden_size, config.hidden_size) + + def forward( + self, hidden_states: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor | None]: + num_patches = hidden_states.shape[0] + query, key, value = self.qkv_proj(hidden_states).view(num_patches, 3, self.num_heads, self.head_dim).unbind(1) + query, key = _apply_vision_rotary(query, cos, sin), _apply_vision_rotary(key, cos, sin) + + attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( + self.config._attn_implementation, vision_eager_attention_forward + ) + # The attention functions take a batch, which here is the one image + attn_output, attn_weights = attention_interface( + self, + query.transpose(0, 1).unsqueeze(0), + key.transpose(0, 1).unsqueeze(0), + value.transpose(0, 1).unsqueeze(0), + attention_mask=None, + scaling=self.scaling, + is_causal=False, + ) + # Only eager attention returns the weights + attn_weights = attn_weights.squeeze(0) if attn_weights is not None else None + return self.o_proj(attn_output.reshape(num_patches, -1)), attn_weights + + +class DeepseekV41VisionMLP(nn.Module): + def __init__(self, config: DeepseekV41VisionConfig): + super().__init__() + self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False) + self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + gate, up = self.gate_up_proj(hidden_states).chunk(2, dim=-1) + return self.down_proj(F.silu(gate) * up) + + +class DeepseekV41VisionLayer(GradientCheckpointingLayer): + def __init__(self, config: DeepseekV41VisionConfig): + super().__init__() + self.layer_norm1 = DeepseekV41RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.self_attn = DeepseekV41VisionAttention(config) + self.layer_norm2 = DeepseekV41RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.mlp = DeepseekV41VisionMLP(config) + + def forward(self, hidden_states: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: + attn_output, _ = self.self_attn(self.layer_norm1(hidden_states), cos, sin) + hidden_states = hidden_states + attn_output + return hidden_states + self.mlp(self.layer_norm2(hidden_states)) + + +class DeepseekV41MultiModalProjector(nn.Module): + """Merges each `downsample_ratio x downsample_ratio` square of patches into one language model token.""" + + def __init__(self, config: "DeepseekV41Config"): + super().__init__() + self.downsample_ratio = config.vision_config.downsample_ratio + input_size = config.vision_config.hidden_size * self.downsample_ratio**2 + self.linear_1 = nn.Linear(input_size, config.text_config.hidden_size) + self.linear_2 = nn.Linear(config.text_config.hidden_size, config.text_config.hidden_size) + + def forward(self, image_features: torch.Tensor, height: int, width: int) -> torch.Tensor: + ratio = self.downsample_ratio + image_features = image_features.view(height, width, -1).permute(2, 0, 1) + # A grid that is not a multiple of the ratio is zero-padded at the bottom and on the right + image_features = F.pad(image_features, (0, -width % ratio, 0, -height % ratio)) + image_features = F.unfold(image_features.unsqueeze(0), ratio, stride=ratio).squeeze(0).transpose(0, 1) + return self.linear_2(F.gelu(self.linear_1(image_features))) + + +def build_engram_token_map(tokenizer) -> torch.Tensor: + """ + Builds the map from token ids to the smaller id space that the Engram n-grams are hashed over. Tokens that + normalize alike are merged there, so that " The", "the" and "THE" all hash the same way. + + The DeepSeek-V4.1 checkpoints do not store this map. The reference implementation builds it from the + tokenizer when it creates the model, and this function does the same. + + Args: + tokenizer ([`PreTrainedTokenizerFast`]): + The tokenizer of the checkpoint. + + Returns: + `torch.Tensor` of shape `(len(tokenizer),)`: The compressed id of each token. + + Example: + + ```python + >>> from transformers import AutoTokenizer + >>> from transformers.models.deepseek_v41.modeling_deepseek_v41 import build_engram_token_map + + >>> tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/DeepSeek-V4.1-Flash") + >>> token_map = build_engram_token_map(tokenizer) + >>> token_map[tokenizer.convert_tokens_to_ids("The")] == token_map[tokenizer.convert_tokens_to_ids("the")] + tensor(True) + + ``` + """ + from tokenizers import Regex, normalizers + + # A private-use char, so that a token that is exactly one space survives `Strip()` instead of collapsing + # to the empty string and merging with unrelated tokens + sentinel = "" + normalizer = normalizers.Sequence( + [ + normalizers.NFKC(), + normalizers.NFD(), + normalizers.StripAccents(), + normalizers.Lowercase(), + normalizers.Replace(Regex(r"[ \t\r\n]+"), " "), + normalizers.Replace(Regex(r"^ $"), sentinel), + normalizers.Strip(), + normalizers.Replace(sentinel, " "), + ] + ) + + # We decode with the raw Rust tokenizer, which is what training did (no `clean_up_tokenization_spaces`) + backend = tokenizer.backend_tokenizer + key_to_compressed_id: dict[str, int] = {} + token_map = [] + for token_id in range(len(tokenizer)): + text = backend.decode([token_id], skip_special_tokens=False) + if "�" in text: + # A partial UTF-8 byte token has nothing to normalize, so we key it by its raw form + key = backend.id_to_token(token_id) + else: + key = normalizer.normalize_str(text) or text + token_map.append(key_to_compressed_id.setdefault(key, len(key_to_compressed_id))) + return torch.tensor(token_map, dtype=torch.long) + + +@auto_docstring +class DeepseekV41PreTrainedModel(PreTrainedModel): + config: DeepseekV41Config + base_model_prefix = "model" + input_modalities = ("image", "text") + supports_gradient_checkpointing = True + _no_split_modules = ["DeepseekV41DecoderLayer", "DeepseekV41VisionLayer"] + # Eager only, for the same reasons as DeepSeek-V4: the head dim of 512 is above what FlashAttention + # supports, SDPA has no attention sink, and the compressed entries are added to the KV axis inside the + # attention, after the mask was built. + _supports_flash_attn = False + _supports_sdpa = False + _supports_flex_attn = False + # The compressed KV, the pooling buffers and the Engram token history live in `DeepseekV41CacheLayer`, + # which has no static version + _can_compile_fullgraph = False + # ... and they cannot be rolled back either, which rules out assisted generation and friends + _is_stateful = True + # Everything listed here is also created in float32 in its `__init__`. `from_pretrained` enforces this + # list, but a model built straight from a config would otherwise get the default dtype + _keep_in_fp32_modules_strict = [ + "attn_hc", + "ffn_hc", + "sinks", + "e_score_correction_bias", + "e_score_correction_bias_vl", + ] + # The DSpark draft layers are not supported yet + _keys_to_ignore_on_load_unexpected = [r"(^|\.)mtp\..*"] + _can_record_outputs = { + "router_logits": OutputRecorder(DeepseekV41TopKRouter, index=0), + "hidden_states": OutputRecorder(DeepseekV41DecoderLayer, index=0), + "attentions": OutputRecorder(DeepseekV41Attention, index=1), + } + + def _init_weights(self, module): + PreTrainedModel._init_weights(self, module) + std = self.config.get_text_config().initializer_range + if isinstance(module, DeepseekV41TopKRouter): + init.normal_(module.weight, mean=0.0, std=std) + init.zeros_(module.e_score_correction_bias) + init.zeros_(module.e_score_correction_bias_vl) + elif isinstance(module, DeepseekV41Experts): + init.normal_(module.gate_up_proj, mean=0.0, std=std) + init.normal_(module.down_proj, mean=0.0, std=std) + elif isinstance(module, DeepseekV41Attention): + init.zeros_(module.sinks) + elif isinstance(module, DeepseekV41HyperConnection): + init.normal_(module.fn, mean=0.0, std=std) + init.zeros_(module.base) + init.ones_(module.scale) + elif isinstance(module, DeepseekV41Engram): + init.ones_(module.q_weight) + init.ones_(module.k_weight) + elif isinstance(module, DeepseekV41NgramHasher): + bucket_sizes = torch.tensor(_engram_bucket_sizes(module.config)) + init.copy_(module.bucket_sizes, bucket_sizes) + init.copy_(module.offsets, bucket_sizes.cumsum(-1) - bucket_sizes) + init.copy_(module.multipliers, torch.from_numpy(_engram_hash_multipliers(module.config))) + init.copy_(module.token_map, _default_engram_token_map(module.config)) + elif isinstance(module, DeepseekV41Model): + init.normal_(module.image_start, mean=0.0, std=std) + init.normal_(module.image_end, mean=0.0, std=std) + init.normal_(module.image_newline, mean=0.0, std=std) + elif isinstance(module, DeepseekV41RotaryEmbedding): + for layer_type in module.layer_types: + rope_init_fn = module.compute_default_rope_parameters + if module.rope_type[layer_type] != "default": + rope_init_fn = ROPE_INIT_FUNCTIONS[module.rope_type[layer_type]] + curr_inv_freq, _ = rope_init_fn(module.config, layer_type=layer_type) + init.copy_(getattr(module, f"{layer_type}_inv_freq"), curr_inv_freq) + init.copy_(getattr(module, f"{layer_type}_original_inv_freq"), curr_inv_freq) + + def activation_checkpointing_enable( + self, activation_checkpointing_kwargs=None, every_n_layers: int = 1, offload: bool = False + ): + """ + Same as [`PreTrainedModel.activation_checkpointing_enable`], except that `use_reentrant=True` is refused. + + Reentrant checkpointing only tracks the gradient of the tensors that a layer gets as positional arguments. + The compressed KV reaches the KV-sharing layers in a dict, so the layer that compressed it would silently + lose the gradient that comes back through them. + """ + if activation_checkpointing_kwargs is not None and activation_checkpointing_kwargs.get("use_reentrant"): + raise ValueError( + "DeepSeek-V4.1 does not support activation checkpointing with `use_reentrant=True`, because the " + "gradient of the compressed KV that its layers share would be lost. Use `use_reentrant=False`, " + "which is the default.\n" + f"activation_checkpointing_kwargs: {activation_checkpointing_kwargs}" + ) + super().activation_checkpointing_enable( + activation_checkpointing_kwargs, every_n_layers=every_n_layers, offload=offload + ) + + # The structure linter reads any `set_*` method as a hyperparameter that should live on the config. This one + # fills a buffer that is saved and loaded with the weights, and it only exists because the original + # checkpoints left that buffer out. + def set_engram_token_map(self, tokenizer_or_token_map): # trf-ignore: TRF033 + """ + Sets the map from token ids to compressed ids that the Engram n-grams are hashed over. The checkpoints do + not store it, so it has to be set once after loading the model. + + Args: + tokenizer_or_token_map ([`PreTrainedTokenizerFast`] or `torch.Tensor`): + The tokenizer of the checkpoint, or a map that `build_engram_token_map` made from it. + """ + hasher = next((module for module in self.modules() if isinstance(module, DeepseekV41NgramHasher)), None) + if hasher is None: + raise ValueError("This model has no Engram layers, so there is no token map to set.") + if isinstance(tokenizer_or_token_map, torch.Tensor): + # An existing map, e.g. one that was built earlier and saved + token_map = tokenizer_or_token_map + else: + # A tokenizer, which we build the map from in the same way as the reference implementation + token_map = build_engram_token_map(tokenizer_or_token_map) + num_compressed_ids = int(token_map.max()) + 1 + if num_compressed_ids != hasher.config.engram_compressed_vocab_size: + raise ValueError( + f"The token map has {num_compressed_ids} compressed ids, but the model was trained with " + f"{hasher.config.engram_compressed_vocab_size} (`config.engram_compressed_vocab_size`). The hash " + "multipliers are derived from that number, so this is not the tokenizer the checkpoint was " + "trained with." + ) + if token_map.shape[0] > hasher.token_map.shape[0]: + raise ValueError( + f"The token map has {token_map.shape[0]} entries, but the model only has " + f"{hasher.token_map.shape[0]} tokens (`config.vocab_size`)." + ) + hasher.token_map[: token_map.shape[0]] = token_map.to(hasher.token_map.device) + + def resize_token_embeddings( + self, + new_num_tokens: int | None = None, + pad_to_multiple_of: int | None = None, + mean_resizing: bool = True, + ): + """ + Not supported: the Engram layers look token ids up in a token map and hash them into n-gram tables, and + both are fixed to the vocabulary that the checkpoint was trained with. + """ + # A new token would need an entry in the token map, and a compressed id that the hash multipliers and + # the n-gram tables were never trained with. We'd rather fail here than hand back a model whose new + # tokens index past the end of the map. + raise NotImplementedError( + "DeepSeek-V4.1 does not support resizing the token embeddings, because its Engram layers hash " + "n-grams of token ids through a token map that is fixed to the vocabulary of the checkpoint. " + "If you need a new token, reuse one of the placeholder tokens that the tokenizer already has.\n" + f"new_num_tokens: {new_num_tokens}" + ) + + +@auto_docstring( + custom_intro=""" + The DeepSeek-V4.1 vision encoder: a ViT with 2D RoPE that runs full attention over the patches of one image. + """ +) +class DeepseekV41VisionModel(DeepseekV41PreTrainedModel): + config: DeepseekV41VisionConfig + main_input_name = "pixel_values" + input_modalities = ("image",) + # Unlike the language model, the vision encoder has plain attention with no sink + _supports_sdpa = True + _can_record_outputs = { + "hidden_states": DeepseekV41VisionLayer, + "attentions": DeepseekV41VisionAttention, + } + + def __init__(self, config: DeepseekV41VisionConfig): + super().__init__(config) + self.rope_dim = config.hidden_size // config.num_attention_heads // 2 + self.patch_embed = nn.Linear(config.num_channels * config.patch_size**2, config.hidden_size) + self.layers = nn.ModuleList([DeepseekV41VisionLayer(config) for _ in range(config.num_hidden_layers)]) + self.norm = DeepseekV41RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_init() + + def get_position_embeddings(self, height: int, width: int, device) -> tuple[torch.Tensor, torch.Tensor]: + """2D RoPE: the first half of the frequencies encodes the row of a patch, and the second half its column.""" + exponents = torch.arange(0, self.rope_dim, 2, dtype=torch.float32, device=device) / self.rope_dim + inv_freq = 1.0 / (self.config.rope_theta**exponents) + rows = torch.arange(height, device=device).unsqueeze(1).expand(height, width) + columns = torch.arange(width, device=device).unsqueeze(0).expand(height, width) + freqs = torch.stack([rows, columns], dim=-1).reshape(-1, 2, 1).float() * inv_freq + freqs = freqs.flatten(1) + return freqs.cos().unsqueeze(1), freqs.sin().unsqueeze(1) + + @merge_with_config_defaults + @capture_outputs + @auto_docstring + def forward( + self, pixel_values: torch.Tensor, height: int, width: int, **kwargs: Unpack[TransformersKwargs] + ) -> BaseModelOutput: + r""" + pixel_values (`torch.Tensor` of shape `(height * width, num_channels * patch_size * patch_size)`): + The flattened patches of one image, in row-major order. + height (`int`): + Number of rows in the image's patch grid. + width (`int`): + Number of columns in the image's patch grid. + """ + hidden_states = self.patch_embed(pixel_values.flatten(1).to(self.patch_embed.weight.dtype)) + cos, sin = self.get_position_embeddings(height, width, hidden_states.device) + for layer in self.layers: + hidden_states = layer(hidden_states, cos, sin) + return BaseModelOutput(last_hidden_state=self.norm(hidden_states)) + + +@auto_docstring( + custom_intro=""" + The DeepSeek-V4.1 language model, without the vision encoder and the language modeling head. + """ +) +class DeepseekV41TextModel(DeepseekV41PreTrainedModel): + config: DeepseekV41TextConfig + input_modalities = ("text",) + + def __init__(self, config: DeepseekV41TextConfig): + super().__init__(config) + self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) + self.layers = nn.ModuleList( + [DeepseekV41DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] + ) + self.norm = DeepseekV41RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.rotary_emb = DeepseekV41RotaryEmbedding(config) + self.engram_hasher = DeepseekV41NgramHasher(config) if config.engram_layer_ids else None + self.gradient_checkpointing = False + self.post_init() + + @merge_with_config_defaults + @capture_outputs + @auto_docstring + @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") + def forward( + self, + input_ids: torch.LongTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + cache: Cache | None = None, + inputs_embeds: torch.Tensor | None = None, + use_cache: bool | None = None, + image_mask: torch.BoolTensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> MoeModelOutputWithPast: + r""" + image_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*): + `True` for the tokens of an image. They are routed with a separate bias and take no part in the + Engram n-grams. + """ + if input_ids is None and inputs_embeds is None: + raise ValueError("You must specify at least one of input_ids or inputs_embeds") + if self.engram_hasher is not None and input_ids is None: + raise ValueError( + "DeepSeek-V4.1 hashes n-grams of token ids for its Engram layers, so it needs `input_ids` even " + "when `inputs_embeds` is passed." + ) + if use_cache and cache is None: + cache = DynamicCache(config=self.config) + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + batch_size, seq_len, _ = inputs_embeds.shape + past_seen = cache.get_seq_length() if cache is not None else 0 + if position_ids is None: + position_ids = torch.arange(seq_len, device=inputs_embeds.device) + past_seen + position_ids = position_ids.unsqueeze(0) + + # First, the padding. Attention only needs to mask it, but the n-gram hashes and the pooling groups are + # made of consecutive real tokens, so they need to know which tokens of this call are real, and how + # many real tokens each row had seen before it. As everywhere else, the mask of a call that continues + # from a cache covers the cached tokens too. + is_real_token = torch.ones((batch_size, seq_len), dtype=torch.bool, device=inputs_embeds.device) + num_seen_tokens = torch.full((batch_size,), past_seen, device=inputs_embeds.device) + if isinstance(attention_mask, torch.Tensor) and attention_mask.ndim == 2: + padding_mask = create_recurrent_attention_mask(self.config, inputs_embeds, attention_mask, cache) + if padding_mask is not None: + is_real_token = padding_mask.bool() + if attention_mask.shape[1] == past_seen + seq_len: + num_seen_tokens = attention_mask[:, :past_seen].bool().sum(dim=-1) + + # Next, the n-gram hashes of all the Engram layers. A padded token must not end up in the n-grams of + # the tokens after it, and neither must an image token. + engram_hash_ids, engram_mask = None, None + if self.engram_hasher is not None: + hash_mask = is_real_token + if image_mask is not None: + engram_mask = ~image_mask + hash_mask = hash_mask & engram_mask + engram_hash_ids = self.engram_hasher(input_ids, hash_mask, cache.layers[0] if cache is not None else None) + + # `generate()` may pass a per-layer-type mask dict already built by `create_masks_for_generate`. All + # layers use the same sliding-window mask, so we use the prebuilt one directly. + if isinstance(attention_mask, dict): + causal_mask = next(iter(attention_mask.values())) + else: + causal_mask = create_sliding_window_causal_mask( + config=self.config, + inputs_embeds=inputs_embeds, + attention_mask=attention_mask, + cache=cache, + position_ids=position_ids, + allow_is_causal_skip=False, + ) + + hidden_states = inputs_embeds.unsqueeze(2).expand(-1, -1, self.config.hc_mult, -1).contiguous() + # The first attention reads the first stream as it is + pre = torch.zeros((batch_size, seq_len, self.config.hc_mult), device=hidden_states.device) + pre[..., 0] = 1.0 + position_embeddings = { + "main": self.rotary_emb(inputs_embeds, position_ids=position_ids, layer_type="main"), + "compress": self.rotary_emb(inputs_embeds, position_ids=position_ids, layer_type="compress"), + } + # The compressed entries get RoPE as well. An entry stands for the first token of its group, so it + # rotates at the position of that token. It only comes to exist with the last token of the group + # though, and by then the first one may be a call behind us. So we go back from the last token: for + # each token, this is the RoPE of the entry that it completes if it is the last one of a group of + # `ratio`, and the compressor keeps the ones of the tokens that are. + compressed_position_embeddings = {} + for ratio, layer_type in zip(self.config.compress_ratios, self.config.attention_layer_types): + if layer_type == "compressed_attention" and ratio not in compressed_position_embeddings: + compressed_position_embeddings[ratio] = self.rotary_emb( + inputs_embeds, position_ids=position_ids - (ratio - 1), layer_type="compress" + ) + # What the attention layers hand down the stack instead of recomputing: the compressed KV, the index + # keys, the selection and the candidate blocks. Each layer returns them with its own on top, so every + # source has published before the layers after it read. + shared_states = {} + + for layer_idx, layer in enumerate(self.layers): + hidden_states, pre, shared_states = layer( + hidden_states, + pre, + engram_hash_ids=( + engram_hash_ids[:, :, self.config.engram_layer_ids.index(layer_idx)] + if layer_idx in self.config.engram_layer_ids + else None + ), + engram_mask=engram_mask, + image_mask=image_mask, + position_embeddings=position_embeddings, + compressed_position_embeddings=compressed_position_embeddings, + is_real_token=is_real_token, + num_seen_tokens=num_seen_tokens, + attention_mask=causal_mask, + cache=cache, + shared_states=shared_states, + **kwargs, + ) + + # There is no hyper-connection head: the "pre" of the last MLP collapses the streams for the final norm + hidden_states = (pre.unsqueeze(-1) * hidden_states.float()).sum(dim=2).to(hidden_states.dtype) + hidden_states = self.norm(hidden_states) + return MoeModelOutputWithPast(last_hidden_state=hidden_states, cache=cache) + + +@auto_docstring( + custom_intro=""" + The DeepSeek-V4.1 model, which consists of a vision encoder and a language model, without a language modeling + head. + """ +) +class DeepseekV41Model(DeepseekV41PreTrainedModel): + def __init__(self, config: DeepseekV41Config): + super().__init__(config) + self.vision_tower = DeepseekV41VisionModel(config.vision_config) + self.multi_modal_projector = DeepseekV41MultiModalProjector(config) + self.language_model = DeepseekV41TextModel(config.text_config) + # Learned embeddings for the delimiters of an image: its start, its end, and the end of each row + self.image_start = nn.Parameter(torch.empty(config.text_config.hidden_size)) + self.image_end = nn.Parameter(torch.empty(config.text_config.hidden_size)) + self.image_newline = nn.Parameter(torch.empty(config.text_config.hidden_size)) + self.post_init() + + def get_input_embeddings(self): + return self.language_model.embed_tokens + + def set_input_embeddings(self, value): + self.language_model.embed_tokens = value + + @can_return_tuple + @auto_docstring( + custom_intro=""" + Encodes the images and lays each one out as the language model reads it: a start embedding, then the rows + of image tokens with a newline embedding after each row, then an end embedding. The `pooler_output` has + one entry per image, of shape `(num_image_positions, hidden_size)`. + """ + ) + def get_image_features( + self, pixel_values: torch.Tensor, image_grid_thw: torch.LongTensor, **kwargs: Unpack[TransformersKwargs] + ) -> tuple | BaseModelOutputWithPooling: + r""" + pixel_values (`torch.Tensor` of shape `(total_patches, num_channels * patch_size * patch_size)`): + The flattened patches of all the images, one image after the other. + image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`): + The temporal size, height and width of each image's patch grid. The temporal size is always 1. + """ + grids = image_grid_thw.tolist() + # An image is a single frame. The temporal size is only there so that the input has the same layout as + # the `image_grid_thw` of the models that take videos as well. + if any(num_frames != 1 for num_frames, _, _ in grids): + raise ValueError( + "DeepSeek-V4.1 only takes images, so the temporal size of every grid must be 1.\n" + f"`image_grid_thw`: {grids}" + ) + patches_per_image = pixel_values.split([height * width for _, height, width in grids]) + vision_outputs, image_features = [], [] + for patches, (_, height, width) in zip(patches_per_image, grids): + outputs = self.vision_tower(patches, height, width, return_dict=True, **kwargs) + tokens = self.multi_modal_projector(outputs.last_hidden_state, height, width) + # The projector rounds a partial square up, so the token grid is the patch grid divided by the ratio + num_rows = -(-height // self.multi_modal_projector.downsample_ratio) + rows = tokens.view(num_rows, -1, tokens.shape[-1]) + newlines = self.image_newline.to(tokens.dtype).expand(num_rows, 1, -1) + rows = torch.cat([rows, newlines], dim=1).flatten(0, 1) + image_start, image_end = self.image_start.to(tokens.dtype)[None], self.image_end.to(tokens.dtype)[None] + image_features.append(torch.cat([image_start, rows, image_end])) + vision_outputs.append(outputs) + + # The vision encoder ran one image at a time, so we put its outputs back in the layout of `pixel_values`: + # the patches of all the images, one image after the other + hidden_states, attentions = None, None + if vision_outputs[0].hidden_states is not None: + # `output_hidden_states` can select layers, which leaves the other ones as None + per_layer = zip(*(outputs.hidden_states for outputs in vision_outputs)) + hidden_states = tuple(torch.cat(layer) if layer[0] is not None else None for layer in per_layer) + if vision_outputs[0].attentions is not None: + # A patch only attends to its own image, so the weights of a layer are one block per image + per_layer = zip(*(outputs.attentions for outputs in vision_outputs)) + attentions = tuple(torch.stack([torch.block_diag(*head) for head in zip(*layer)]) for layer in per_layer) + return BaseModelOutputWithPooling( + last_hidden_state=torch.cat([outputs.last_hidden_state for outputs in vision_outputs]), + pooler_output=tuple(image_features), + hidden_states=hidden_states, + attentions=attentions, + ) + + @can_return_tuple + @auto_docstring + @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") + def forward( + self, + input_ids: torch.LongTensor | None = None, + pixel_values: torch.Tensor | None = None, + image_grid_thw: torch.LongTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + cache: Cache | None = None, + inputs_embeds: torch.Tensor | None = None, + use_cache: bool | None = None, + mm_encoder_outputs: dict[str, BaseModelOutputWithPooling] | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> MultimodalMoeBaseModelOutputWithPast: + r""" + pixel_values (`torch.Tensor` of shape `(total_patches, num_channels * patch_size * patch_size)`, *optional*): + The flattened patches of all the images in the batch, one image after the other. + image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): + The temporal size, height and width of each image's patch grid. The temporal size is always 1. + """ + if input_ids is None and inputs_embeds is None: + raise ValueError("You must specify at least one of input_ids or inputs_embeds") + if inputs_embeds is None: + inputs_embeds = self.get_input_embeddings()(input_ids) + + # The images come in either as `pixel_values`, which we encode here, or already encoded. `generate` does + # the latter: it encodes them once before the first step, so that it can repeat whole images for beam + # search. Repeating the rows of `pixel_values` would repeat patches instead. + mm_encoder_outputs = mm_encoder_outputs if mm_encoder_outputs is not None else {} + if pixel_values is not None: + if mm_encoder_outputs.get("image") is not None: + raise ValueError( + "Got both `pixel_values` and images that are already encoded in `mm_encoder_outputs`. " + "Pass only one of the two." + ) + mm_encoder_outputs["image"] = self.get_image_features(pixel_values, image_grid_thw, return_dict=True) + + # Every position of an image carries `image_token_id`, the delimiters included + image_mask = input_ids == self.config.image_token_id if input_ids is not None else None + if mm_encoder_outputs.get("image") is not None: + if image_mask is None: + raise ValueError("`input_ids` are needed to find where the images go in the prompt.") + features_per_image = mm_encoder_outputs["image"].pooler_output + image_features = torch.cat(features_per_image).to(inputs_embeds.device, inputs_embeds.dtype) + num_image_tokens = image_mask.sum() + torch_compilable_check( + num_image_tokens == image_features.shape[0], + lambda: ( + f"The prompt has {int(num_image_tokens)} image tokens, but the images take up " + f"{image_features.shape[0]} tokens (per image: {[len(features) for features in features_per_image]})." + ), + ) + inputs_embeds = inputs_embeds.masked_scatter(image_mask.unsqueeze(-1), image_features) + + outputs = self.language_model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + cache=cache, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + image_mask=image_mask, + **kwargs, + ) + return MultimodalMoeBaseModelOutputWithPast(**outputs, image_outputs=mm_encoder_outputs.get("image")) + + +@auto_docstring( + custom_intro=""" + The DeepSeek-V4.1 model with a language modeling head on top. It takes text, optionally interleaved with + images. + """ +) +class DeepseekV41ForCausalLM(DeepseekV41PreTrainedModel, GenerationMixin): + def __init__(self, config: DeepseekV41Config): + super().__init__(config) + self.model = DeepseekV41Model(config) + self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False) + self.post_init() + + def get_input_embeddings(self): + return self.model.get_input_embeddings() + + def set_input_embeddings(self, value): + self.model.set_input_embeddings(value) + + def get_output_embeddings(self) -> nn.Module: + return self.lm_head + + @can_return_tuple + @auto_docstring + @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") + def forward( + self, + input_ids: torch.LongTensor | None = None, + pixel_values: torch.Tensor | None = None, + image_grid_thw: torch.LongTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + cache: Cache | None = None, + inputs_embeds: torch.Tensor | None = None, + labels: torch.LongTensor | None = None, + use_cache: bool | None = None, + logits_to_keep: int | torch.Tensor = 0, + mm_encoder_outputs: dict[str, BaseModelOutputWithPooling] | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> MultimodalMoeCausalLMOutputWithPast: + r""" + pixel_values (`torch.Tensor` of shape `(total_patches, num_channels * patch_size * patch_size)`, *optional*): + The flattened patches of all the images in the batch, one image after the other. + image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): + The temporal size, height and width of each image's patch grid. The temporal size is always 1. + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + """ + outputs: MultimodalMoeBaseModelOutputWithPast = self.model( + input_ids=input_ids, + pixel_values=pixel_values, + image_grid_thw=image_grid_thw, + attention_mask=attention_mask, + position_ids=position_ids, + cache=cache, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + mm_encoder_outputs=mm_encoder_outputs, + **kwargs, + ) + hidden_states = outputs.last_hidden_state + # Only compute the necessary logits + slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep + logits = self.lm_head(hidden_states[:, slice_indices, :]) + + loss = None + if labels is not None: + loss = self.loss_function(logits, labels, self.config.text_config.vocab_size, **kwargs) + + return MultimodalMoeCausalLMOutputWithPast( + loss=loss, + logits=logits, + cache=outputs.cache, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + router_logits=outputs.router_logits, + image_outputs=outputs.image_outputs, + ) + + +__all__ = [ + "DeepseekV41PreTrainedModel", + "DeepseekV41VisionModel", + "DeepseekV41TextModel", + "DeepseekV41Model", + "DeepseekV41ForCausalLM", +] diff --git a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py new file mode 100644 index 000000000000..63158f6aca46 --- /dev/null +++ b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py @@ -0,0 +1,2391 @@ +# Copyright 2026 The HuggingFace Inc. 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. +import math +from collections.abc import Callable + +import numpy as np +import torch +import torch.nn.functional as F +from huggingface_hub.dataclasses import strict +from torch import nn +from torchvision.transforms.v2 import functional as tvF + +from ... import initialization as init +from ...cache_utils import Cache, DynamicCache, DynamicSlidingWindowLayer +from ...configuration_utils import PreTrainedConfig +from ...generation import GenerationMixin +from ...image_processing_backends import TorchvisionBackend +from ...image_processing_utils import BatchFeature +from ...image_utils import ChannelDimension, ImageInput, ImageType, PILImageResampling, SizeDict, get_image_type +from ...integrations import use_experts_implementation +from ...masking_utils import create_recurrent_attention_mask, create_sliding_window_causal_mask +from ...modeling_layers import GradientCheckpointingLayer +from ...modeling_outputs import ( + BaseModelOutput, + BaseModelOutputWithPooling, + MoeModelOutputWithPast, + MultimodalMoeBaseModelOutputWithPast, + MultimodalMoeCausalLMOutputWithPast, +) +from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel +from ...processing_utils import ImagesKwargs, ProcessorMixin, Unpack +from ...utils import ( + TensorType, + TransformersKwargs, + auto_docstring, + can_return_tuple, + logging, + torch_compilable_check, +) +from ...utils.deprecation import deprecate_kwarg +from ...utils.generic import merge_with_config_defaults +from ...utils.output_capturing import OutputRecorder, capture_outputs +from ..deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config +from ..deepseek_v4.modeling_deepseek_v4 import ( + DeepseekV4Experts, + DeepseekV4GroupedLinear, + DeepseekV4MLP, + DeepseekV4RMSNorm, + DeepseekV4RotaryEmbedding, + DeepseekV4TopKRouter, + apply_rotary_pos_emb, +) +from ..gpt_oss.modeling_gpt_oss import eager_attention_forward + + +logger = logging.get_logger(__name__) + + +DEEPSEEK_V41_ATTENTION_LAYER_TYPES = ( + "sliding_attention", + "compressed_attention", + "kv_shared_indexed_attention", + "kv_shared_attention", +) + + +@auto_docstring(checkpoint="deepseek-ai/DeepSeek-V4.1-Flash") +@strict +class DeepseekV41VisionConfig(PreTrainedConfig): + r""" + rope_theta (`float`, *optional*, defaults to 10000.0): + Base of the 2D rotary position embedding. + downsample_ratio (`int`, *optional*, defaults to 3): + Side of the square of patches that the projector merges into one language model token. + max_image_tokens (`int`, *optional*, defaults to 1024): + The most language model tokens an image may take, delimiters included. Only used for preprocessing. + min_pixels (`int`, *optional*, defaults to 295936): + Images with fewer pixels are scaled up to this area. Only used for preprocessing. + max_wh_ratio (`float`, *optional*): + Images wider than this width-to-height ratio are squashed to it. Only used for preprocessing. + """ + + model_type = "deepseek_v41_vision" + base_config_key = "vision_config" + + hidden_size: int = 1024 + num_hidden_layers: int = 32 + num_attention_heads: int = 16 + intermediate_size: int = 2816 + patch_size: int = 14 + num_channels: int = 3 + rope_theta: float | int = 10000.0 + downsample_ratio: int = 3 + max_image_tokens: int = 1024 + min_pixels: int = 295936 + max_wh_ratio: float | int | None = None + rms_norm_eps: float = 1.0e-6 + initializer_range: float = 0.02 + + +@auto_docstring(checkpoint="deepseek-ai/DeepSeek-V4.1-Flash") +@strict +class DeepseekV41TextConfig(DeepseekV4Config): + r""" + scoring_func (`str`): + Router activation — `sqrtsoftplus`, `softmax`, or `sigmoid`. + rope_theta (`float`): + RoPE base for the sliding-window-only layers. + layer_types (`list[str]`): + Per-layer cache type. Every DeepSeek-V4.1 layer uses `"shared_compressed_attention"`, so this is filled in + automatically. + attention_layer_types (`list[str]`, *optional*): + Which attention variant each layer uses. Derived from `compress_ratios`, `kv_source_layer_ids` and + `index_source_layer_ids`: + + - `"sliding_attention"` attends over a sliding window only. + - `"compressed_attention"` also compresses its own KV, and runs an indexer to pick which compressed + entries each query attends to. + - `"kv_shared_indexed_attention"` reads the compressed KV of the last `"compressed_attention"` layer, but + runs its own indexer over it. + - `"kv_shared_attention"` reuses both the compressed KV and the selection of the layers before it. + compress_ratios (`list[int]`, *optional*): + Per-layer KV compression ratio. 0 is sliding-window attention only, and `r > 0` adds attention over + KV that are pooled `r`-to-1. The checkpoint's config lists the DSpark layers after the main ones, and + those extra entries are ignored here. Defaults to sliding-window attention everywhere. + kv_source_layer_ids (`list[int]`, *optional*): + The layers that compress their own KV. Every later layer with the same ratio reads that KV, up to the + next source. + index_source_layer_ids (`list[int]`, *optional*): + The layers that run an indexer. The layers in between reuse the selection of the last one. + candidate_source_layer_id (`int`, *optional*): + The indexer of this layer also keeps the `candidate_topk_blocks` best blocks of compressed positions per + query, and the indexers after it only choose inside those blocks. + candidate_topk_blocks (`int`, *optional*, defaults to 2048): + Number of blocks the candidate source keeps per query. + candidate_block_size (`int`, *optional*, defaults to 8): + Number of compressed positions in a candidate block. + compress_rope_theta (`float`): + RoPE base for the layers that attend to compressed KV (paired with `rope_scaling` for YaRN). + hc_mult (`int`): + Number of parallel streams the hyper-connections carry the residual in. + hc_sinkhorn_iters (`int`): + Sinkhorn-Knopp iterations that make the hyper-connection mixing matrix doubly stochastic. + hc_eps (`float`): + Numerical floor for the Sinkhorn-Knopp normalization. + swiglu_limit (`float`): + Clip the experts' gate/up pre-activations. + sliding_window (`int`): + Size of the sliding window that every layer attends over. + o_groups (`int`): + Number of head groups in the grouped output projection. + o_lora_rank (`int`): + Per-group intermediate dim of the grouped output projection. + index_n_heads (`int`): + Number of indexer query heads. + index_head_dim (`int`): + Indexer head dim. + index_topk (`int`): + Number of compressed entries the indexer keeps per query. + engram_layer_ids (`list[int]`, *optional*): + The layers that add an Engram n-gram lookup to the residual stream before their attention. + engram_num_embeddings (`list[int]`, *optional*): + Rows in the hash table of each Engram layer. This is the sum of the layer's bucket sizes, so it is only + checked against them. + engram_max_ngram_size (`int`, *optional*, defaults to 4): + Longest n-gram that is hashed. Every size from 2 up to this one gets its own lookups. + engram_vocab_size (`int`, *optional*, defaults to 16000000): + Each (n-gram size, head) pair gets a bucket range whose size is the next unused prime above this. + engram_n_heads (`int`, *optional*, defaults to 8): + Number of hash heads per n-gram size. + engram_head_dim (`int`, *optional*, defaults to 256): + Dimension of the rows of the Engram hash tables. + engram_pad_token_id (`int`, *optional*, defaults to 2): + Token that fills the slots of an n-gram that reach back before the start of the sequence. + engram_compressed_vocab_size (`int`, *optional*, defaults to 99092): + Size of the vocabulary once tokens that normalize alike are merged. The hash multipliers are derived + from it. + num_nextn_predict_layers (`int`): + Number of DSpark draft layers in the checkpoint (not instantiated here). + dspark_block_size (`int`, *optional*, defaults to 5): + Number of tokens a DSpark draft predicts (not used yet). + dspark_noise_token_id (`int`, *optional*, defaults to 128799): + Token that fills the positions a DSpark draft has yet to predict (not used yet). + dspark_target_layer_ids (`list[int]`, *optional*): + The layers whose inputs the DSpark draft layers read (not used yet). + dspark_markov_rank (`int`, *optional*, defaults to 256): + Rank of the DSpark Markov head (not used yet). + dspark_n_routed_experts (`int`, *optional*, defaults to 128): + Number of routed experts in the DSpark draft layers (not used yet). + dspark_num_experts_per_tok (`int`, *optional*, defaults to 3): + Number of experts each token is routed to in the DSpark draft layers (not used yet). + partial_rotary_factor (`float`, *optional*): + Fraction of head_dim that gets RoPE. + Defaults to `qk_rope_head_dim / head_dim` so cos/sin sizes to `qk_rope_head_dim`. + """ + + model_type = "deepseek_v41_text" + base_config_key = "text_config" + + hidden_size: int = 5120 + moe_intermediate_size: int = 2304 + num_hidden_layers: int = 40 + q_lora_rank: int = 1280 + n_routed_experts: int = 384 + index_n_heads: int = 32 + num_nextn_predict_layers: int = 3 + rms_norm_eps: float = 1.0e-20 + pad_token_id: int | None = 2 + + attention_layer_types: list[str] | None = None + compress_ratios: list[int] | None = None + kv_source_layer_ids: list[int] | None = None + index_source_layer_ids: list[int] | None = None + candidate_source_layer_id: int | None = None + candidate_topk_blocks: int = 2048 + candidate_block_size: int = 8 + + engram_layer_ids: list[int] | None = None + engram_num_embeddings: list[int] | None = None + engram_max_ngram_size: int = 4 + engram_vocab_size: int = 16000000 + engram_n_heads: int = 8 + engram_head_dim: int = 256 + engram_pad_token_id: int = 2 + engram_compressed_vocab_size: int = 99092 + + dspark_block_size: int = 5 + dspark_noise_token_id: int = 128799 + dspark_target_layer_ids: list[int] | None = None + dspark_markov_rank: int = 256 + dspark_n_routed_experts: int = 128 + dspark_num_experts_per_tok: int = 3 + + compress_rates = AttributeError() + default_compress_rates = AttributeError() + mlp_layer_types = AttributeError() + default_num_hash_layers = AttributeError() + + def validate_layer_type(self): + """Checks that the attention schedule is one the model can run: every layer that attends to compressed + KV needs a source for that KV and for its selection somewhere before it.""" + if self.num_hidden_layers is None or self.attention_layer_types is None: + return + if len(self.attention_layer_types) != self.num_hidden_layers: + raise ValueError( + f"`num_hidden_layers` ({self.num_hidden_layers}) must equal `len(attention_layer_types)` " + f"({len(self.attention_layer_types)})." + ) + bad = [t for t in self.attention_layer_types if t not in DEEPSEEK_V41_ATTENTION_LAYER_TYPES] + if bad: + raise ValueError( + f"`attention_layer_types` entries must be one of {DEEPSEEK_V41_ATTENTION_LAYER_TYPES}; got {bad}." + ) + + source_ratio = None + for layer_idx, layer_type in enumerate(self.attention_layer_types): + ratio = self.compress_ratios[layer_idx] + if layer_type == "compressed_attention": + if layer_idx not in self.index_source_layer_ids: + raise ValueError( + f"Layer {layer_idx} is in `kv_source_layer_ids`, so it must be in `index_source_layer_ids` " + f"too: the index keys are made from the KV it compresses. Got {self.index_source_layer_ids}." + ) + source_ratio = ratio + elif layer_type != "sliding_attention" and ratio != source_ratio: + raise ValueError( + f"Layer {layer_idx} has a compression ratio of {ratio}, but the last layer in " + f"`kv_source_layer_ids` before it compresses with a ratio of {source_ratio}. Add {layer_idx} " + "to `kv_source_layer_ids` or change its entry in `compress_ratios`." + ) + if ( + self.candidate_source_layer_id is not None + and self.candidate_source_layer_id not in self.index_source_layer_ids + ): + raise ValueError( + f"`candidate_source_layer_id` ({self.candidate_source_layer_id}) must be one of " + f"`index_source_layer_ids` ({self.index_source_layer_ids})." + ) + + def validate_fake_quantization(self): + """Checks that the activations which are rounded to FP8 or FP4 split into whole blocks of 32 values.""" + widths = { + "head_dim": self.head_dim, + "num_attention_heads * head_dim // o_groups": self.num_attention_heads * self.head_dim // self.o_groups, + } + if self.compress_ratios is not None and any(self.compress_ratios): + # Only the layers that attend to compressed KV have index keys and queries + widths["index_head_dim"] = self.index_head_dim + bad = {name: width for name, width in widths.items() if width % 32 != 0} + if bad: + raise ValueError( + "The KV, the input of the grouped output projection and the index keys and queries are rounded to " + f"FP8 or FP4 in blocks of 32 values, so their widths must be multiples of 32. Got {bad}." + ) + + def __post_init__(self, **kwargs): + legacy_qk_rope_head_dim = kwargs.pop("qk_rope_head_dim", None) + PreTrainedConfig.__post_init__(self, **kwargs) + n = self.num_hidden_layers + + # Without a schedule, every layer is sliding-window attention only + if self.compress_ratios is None: + self.compress_ratios = [0] * n + if len(self.compress_ratios) < n: + raise ValueError( + f"`compress_ratios` needs an entry per layer, but has {len(self.compress_ratios)} entries for " + f"{n} layers." + ) + self.kv_source_layer_ids = list(self.kv_source_layer_ids or []) + self.index_source_layer_ids = list(self.index_source_layer_ids or []) + self.engram_layer_ids = list(self.engram_layer_ids or []) + self.dspark_target_layer_ids = list(self.dspark_target_layer_ids or []) + + # `attention_layer_types` picks the attention class of each layer + attention_layer_types = [] + for layer_idx in range(n): + if self.compress_ratios[layer_idx] == 0: + # A sliding window and nothing else + attention_layer_types.append("sliding_attention") + elif layer_idx in self.kv_source_layer_ids: + # Compresses its own KV and indexes it + attention_layer_types.append("compressed_attention") + elif layer_idx in self.index_source_layer_ids: + # Reads the KV of the last source, but selects from it with its own indexer + attention_layer_types.append("kv_shared_indexed_attention") + else: + # Reads both the KV and the selection of the layers before it + attention_layer_types.append("kv_shared_attention") + if self.attention_layer_types is None: + self.attention_layer_types = attention_layer_types + elif list(self.attention_layer_types) != attention_layer_types: + raise ValueError( + f"`attention_layer_types` ({self.attention_layer_types}) does not match `compress_ratios`, " + f"`kv_source_layer_ids` and `index_source_layer_ids`, which give {attention_layer_types}." + ) + + # `layer_types` picks the cache class, and all layers keep their state in the same one + self.layer_types = ["shared_compressed_attention"] * n + + # `partial_rotary_factor` = legacy `qk_rope_head_dim / head_dim` if given, else default. + # `qk_rope_head_dim` is a runtime-only attr (never a dataclass field). + if self.partial_rotary_factor is None: + self.partial_rotary_factor = ( + legacy_qk_rope_head_dim / self.head_dim + if legacy_qk_rope_head_dim is not None + else self.default_partial_rotary_factor + ) + self.qk_rope_head_dim = int(self.head_dim * self.partial_rotary_factor) + + # As in DeepSeek-V4, YaRN only applies to the layers that attend to compressed KV, which rotate with + # `compress_rope_theta`. The sliding-window-only layers use plain RoPE with `rope_theta`. The reference + # does not multiply cos/sin by YaRN's mscale, so we force `attention_factor=1.0` for YaRN. + rp = self.rope_parameters or {} + if isinstance(rp.get("main"), dict) and isinstance(rp.get("compress"), dict): + # Already nested - drop any leftover top-level keys + self.rope_parameters = {"main": rp["main"], "compress": rp["compress"]} + else: + yarn = {k: v for k, v in rp.items() if k not in ("main", "compress")} + main = { + "rope_type": "default", + "rope_theta": self.rope_theta, + "partial_rotary_factor": self.partial_rotary_factor, + } + compress = { + **yarn, + "rope_theta": self.compress_rope_theta, + "partial_rotary_factor": self.partial_rotary_factor, + } + compress.setdefault("rope_type", "default") + if compress["rope_type"] == "yarn": + compress.setdefault("attention_factor", 1.0) + self.rope_parameters = {"main": main, "compress": compress} + + +@auto_docstring(checkpoint="deepseek-ai/DeepSeek-V4.1-Flash") +@strict +class DeepseekV41Config(PreTrainedConfig): + model_type = "deepseek_v41" + sub_configs_defaults = { + "vision_config": DeepseekV41VisionConfig, + "text_config": DeepseekV41TextConfig, + } + + vision_config: dict | PreTrainedConfig | None = None + text_config: dict | PreTrainedConfig | None = None + image_token_id: int = 129264 + pad_token_id: int | None = 2 + bos_token_id: int | None = 0 + eos_token_id: int | list[int] | None = 1 + + def __post_init__(self, **kwargs): + super().__post_init__(**kwargs) + + # The quantization config of the checkpoint only describes its FP8 linears and its FP4 experts, so we fill + # in the rest here, like DeepSeek-V4 does for `expert_dtype`. Anything the config already sets is left alone. + # TODO: revisit after #50245. With a quantization plan, the tables can get an entry of their own + quantization_config = getattr(self, "quantization_config", None) + if isinstance(quantization_config, dict) and quantization_config.get("quant_method") == "fp8": + block_size = quantization_config.get("weight_block_size") or (128, 128) + defaults = { + # The Engram tables are stored in FP8 too, and they are far too big to dequantize. A block of a + # table is as wide as a block of a linear, but it never spans rows + "modules_to_convert": ["engram.embed"], + "embedding_block_size": block_size[1], + # These linears are stored in BF16. They have no scales, so the quantizer has to skip them + "modules_to_not_convert": [ + "lm_head", + r".*vision_tower", + r".*multi_modal_projector", + "self_attn.compressor.kv_proj", + "self_attn.compressor.gate_proj", + "self_attn.indexer.k_proj", + "self_attn.indexer.weights_proj", + ], + } + given = {key: value for key, value in quantization_config.items() if value is not None} + self.quantization_config = {**defaults, **given} + + +class DeepseekV41CacheLayer(DynamicSlidingWindowLayer): + r""" + Cache layer for DeepSeek-V4.1. Every layer keeps its sliding window of KV here. On top of that, a few layers + keep state that other layers read: + + * `compressed_kv` / `index_keys` - the compressed KV entries a `"compressed_attention"` layer has emitted + so far, and the index keys made from them. The KV-sharing layers after it attend to these too. Entry + `g` of a row is its `g`-th group of real tokens, so the rows of a padded batch do not have the same + number of entries. A row with fewer of them than the others has zeros after its last one. + * `pooling_buffer` - the KV and the gates of the last `compress_ratio - 1` real tokens of each row. The + last few of them are the tokens of a pooling group that is still filling up. The group only becomes a + compressed entry once its last token arrives. + * `token_history` - the last few token ids, which the Engram n-gram hashes look back at. Only the first + layer keeps it. + """ + + _layer_type = "shared_compressed_attention" + + def __init__(self, config: "DeepseekV41TextConfig", **kwargs): + super().__init__(sliding_window=config.sliding_window) + self.compressed_kv: torch.Tensor | None = None + self.index_keys: torch.Tensor | None = None + self.pooling_buffer: torch.Tensor | None = None + self.token_history: torch.Tensor | None = None + + def update(self, key_states: torch.Tensor, value_states: torch.Tensor, *args, **kwargs): + """ + Sliding-window update for shared KV: the keys and the values are the same tensor, so we only store it + once. + """ + if not self.is_initialized: + self.lazy_initialization(key_states, value_states) + self.values = self.keys + self.cumulative_length += key_states.shape[-2] + full = torch.cat([self.keys, key_states], dim=-2) + self.keys = full[:, :, -self.sliding_window + 1 :, :] + self.values = self.keys + return full, full + + def update_compressed_states( + self, + compressed_kv: torch.Tensor, + index_keys: torch.Tensor, + num_entries: torch.Tensor, + num_new_entries: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + """ + Write the new compressed KV entries and their index keys after the ones that each row already has, and + return all of them so far. Row `i` has `num_entries[i]` entries, and takes the first + `num_new_entries[i]` of the new ones. + """ + if self.compressed_kv is None: + self.compressed_kv, self.index_keys = compressed_kv[:, :0], index_keys[:, :0] + num_entries_after = num_entries + num_new_entries + width = max(self.compressed_kv.shape[1], int(num_entries_after.max())) + # Each row writes at its own offset, as the rows of a padded batch do not complete their groups in the + # same calls. The new entries that a row does not take all land in one extra slot at the end, which we + # drop again. + slots = num_entries[:, None] + torch.arange(compressed_kv.shape[1], device=compressed_kv.device) + slots = torch.where(slots < num_entries_after[:, None], slots, width) + for name, new_states in (("compressed_kv", compressed_kv), ("index_keys", index_keys)): + states = getattr(self, name) + states = F.pad(states, (0, 0, 0, width + 1 - states.shape[1])) + states = states.scatter(1, slots[..., None].expand_as(new_states), new_states) + setattr(self, name, states[:, :width]) + return self.compressed_kv, self.index_keys + + def update_token_history(self, token_ids: torch.Tensor, history_length: int) -> torch.Tensor: + """ + Return the new `token_ids` with the last `history_length` tokens before them, then remember the last + `history_length` of those for the next call. Before the start of the sequence, the history is `-1`. + """ + if self.token_history is None: + self.token_history = token_ids.new_full((token_ids.shape[0], history_length), -1) + token_ids = torch.cat([self.token_history, token_ids], dim=1) + self.token_history = token_ids[:, -history_length:] + return token_ids + + def _extra_state_names(self) -> tuple[str, ...]: + return ("compressed_kv", "index_keys", "pooling_buffer", "token_history") + + def reorder_cache(self, beam_idx: torch.LongTensor) -> None: + super().reorder_cache(beam_idx) + for name in self._extra_state_names(): + tensor = getattr(self, name) + if tensor is not None: + setattr(self, name, tensor.index_select(0, beam_idx.to(tensor.device))) + + def batch_repeat_interleave(self, repeats: int) -> None: + super().batch_repeat_interleave(repeats) + for name in self._extra_state_names(): + tensor = getattr(self, name) + if tensor is not None: + setattr(self, name, tensor.repeat_interleave(repeats, dim=0)) + + def batch_select_indices(self, indices: torch.Tensor) -> None: + super().batch_select_indices(indices) + for name in self._extra_state_names(): + tensor = getattr(self, name) + if tensor is not None: + setattr(self, name, tensor[indices, ...]) + + def reset(self) -> None: + super().reset() + # Dropped rather than zeroed, as they grow by concatenation, like the main states + for name in self._extra_state_names(): + setattr(self, name, None) + + +class DeepseekV41RMSNorm(DeepseekV4RMSNorm): + pass + + +class DeepseekV41RotaryEmbedding(DeepseekV4RotaryEmbedding): + pass + + +class DeepseekV41GroupedLinear(DeepseekV4GroupedLinear): + pass + + +class DeepseekV41Float32Linear(nn.Linear): + """ + A linear layer that computes in float32, whatever dtype its weight is stored in. The reference promotes the + pooling projections of the compressor like this. + + The promotion happens in here rather than in the compressor, because offloaded weights (`device_map="auto"` + on a machine the model does not fit on) are only loaded while the module that owns them runs. + """ + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + return F.linear(hidden_states.float(), self.weight.float()) + + +# The low-precision formats that activations are rounded to, as (largest value, mantissa bits, lowest normal +# exponent). FP8 is E4M3 and FP4 is E2M1. +MINIFLOAT_FORMATS = {"fp8": (448.0, 3, -6), "fp4": (6.0, 1, 0)} + + +def _round_to_minifloat(values: torch.Tensor, value_format: str) -> torch.Tensor: + max_value, mantissa_bits, min_exponent = MINIFLOAT_FORMATS[value_format] + # Casting to these formats saturates, so we clamp before we round + values = values.clamp(-max_value, max_value) + # Between two powers of two, the values of the format are evenly spaced, so we round to a multiple of the + # spacing. `frexp` gives `values = mantissa * 2**exponent` with `0.5 <= |mantissa| < 1`, so the power of two + # below a value is `2**(exponent - 1)`. Under the lowest normal exponent the spacing stops shrinking, which + # is where the subnormals are. + _, exponent = torch.frexp(values) + spacing = torch.ldexp(torch.ones_like(values), (exponent - 1).clamp(min=min_exponent) - mantissa_bits) + # `torch.round` sends ties to the even multiple, like the cast does + return torch.round(values / spacing) * spacing + + +def fake_quantize( + hidden_states: torch.Tensor, value_format: str, block_size: int, scale_format: str = "ue8m0" +) -> torch.Tensor: + """ + Rounds activations to the values that a low-precision float format can hold, and returns them in their own + dtype. The reference implementation does this to the KV, the attention output, the index keys and queries + and the compressed KV, mirroring the quantized formats that they are kept in during training. Nothing gets + smaller: the point is that the model sees the same rounded values as it was trained with. + + The last dim is cut into blocks of `block_size` values, and each block gets a scale of its own. The block + is divided by its scale, which brings its largest value to the top of the format's range, then rounded to + the format, then multiplied by the scale again. + + Args: + hidden_states (`torch.Tensor` of shape `(..., hidden_size)`): + The activations to round. `hidden_size` must be a multiple of `block_size`. + value_format (`str`): + The format to round to: `"fp8"` (E4M3, 3 mantissa bits, up to 448) or `"fp4"` (E2M1, 1 mantissa bit, + up to 6). + block_size (`int`): + Number of consecutive values that share a scale. + scale_format (`str`, *optional*, defaults to `"ue8m0"`): + The format of the scales: `"ue8m0"` for a power of two, or `"fp8"` for an FP8 number. + + Returns: + `torch.Tensor`: The rounded activations, with the shape and dtype of `hidden_states`. The gradient skips + the rounding and goes straight through to `hidden_states`. + + Example: + + ```python + >>> import torch + >>> hidden_states = torch.tensor([[0.3, -1.0, 2.6, 5.5]]) + >>> fake_quantize(hidden_states, value_format="fp4", block_size=4) + tensor([[ 0.5000, -1.0000, 3.0000, 6.0000]]) + + ``` + """ + max_value = MINIFLOAT_FORMATS[value_format][0] + # The reference computes the scales and the rounding in float32, whatever the dtype of the activations + blocks = hidden_states.detach().float().unflatten(-1, (-1, block_size)) + largest = blocks.abs().amax(dim=-1, keepdim=True) + if scale_format == "ue8m0": + # A power of two: the smallest one that still brings the largest value of the block into range. The + # floors keep the scale of an all-zero block away from zero. + largest = largest.clamp(min=1e-4 if value_format == "fp8" else max_value * 2.0**-126) + # We want `2**ceil(log2(x))` to the bit, which `torch.log2` cannot promise around powers of two. + # `frexp` can: `x = mantissa * 2**exponent` with `0.5 <= mantissa < 1`, and only a power of two has a + # mantissa of exactly 0.5. + mantissa, exponent = torch.frexp(largest * (1.0 / max_value)) + scale = torch.ldexp(torch.ones_like(largest), exponent - (mantissa == 0.5).int()) + elif scale_format == "fp8": + # An FP8 number, which follows the largest value more closely than a power of two does. The floor is + # the smallest FP8 number, so again the scale of an all-zero block is not zero. + scale = _round_to_minifloat(largest.clamp(min=max_value * 2.0**-9) / max_value, "fp8") + else: + raise ValueError(f'`scale_format` must be "ue8m0" or "fp8", but got "{scale_format}".') + + quantized = _round_to_minifloat(blocks / scale, value_format) * scale + quantized = quantized.flatten(-2).to(hidden_states.dtype) + if hidden_states.requires_grad: + # Straight-through estimator: rounding has a gradient of zero almost everywhere, so the backward pass + # treats it as the identity. The term that we add is exactly zero, so the values stay the rounded ones. + quantized = quantized + (hidden_states - hidden_states.detach()) + return quantized + + +class DeepseekV41Compressor(nn.Module): + """ + Pools every `compress_ratio` consecutive tokens into one KV latent with a learned softmax gate. With a + ratio of 1 there is nothing to pool, so the latent is a plain projection of each token. + + The groups are counted from the first real token of each row, and padding takes no part in them. So a + left-padded row gets the same latents as it would without the padding, but the rows of a batch do not + complete their groups in the same calls. + + Returns the latents of the groups that this call completes, *before* RoPE: the indexer makes its keys + from the unrotated latents, so the attention layer rotates them afterwards. The RoPE of each latent and + the number of groups that each row completes come back with them, and the latents after that number are + not real. A group whose last token has not arrived yet waits in the cache, or is dropped when there is no + cache. + """ + + def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): + super().__init__() + self.compress_ratio = config.compress_ratios[layer_idx] + if self.compress_ratio > 1: + # Several tokens per group, which are pooled in float32 + self.kv_proj = DeepseekV41Float32Linear(config.hidden_size, config.head_dim, bias=False) + self.gate_proj = DeepseekV41Float32Linear(config.hidden_size, config.head_dim, bias=False) + else: + # One token per group, so no gate and no pooling + self.kv_proj = nn.Linear(config.hidden_size, config.head_dim, bias=False) + self.gate_proj = None + self.kv_norm = DeepseekV41RMSNorm(config.head_dim, eps=config.rms_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor], + is_real_token: torch.Tensor, + num_seen_tokens: torch.Tensor, + cache_layer: DeepseekV41CacheLayer | None = None, + ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor], torch.Tensor]: + batch_size = hidden_states.shape[0] + ratio = self.compress_ratio + # First, what the groups are made of. The KV and the gate of a token stay together until the pooling, + # so we keep them in one tensor. The same goes for the cos and sin of the RoPE: for each token, the + # model has computed the RoPE of the entry that the token completes, if it is the last one of a group. + if self.gate_proj is None: + # One token per group, so no gate and no pooling + states = self.kv_proj(hidden_states) + else: + # The reference promotes the pooling weights to float32, and pools in float32 too + states = torch.cat([self.kv_proj(hidden_states), self.gate_proj(hidden_states)], dim=-1) + rope = torch.cat(position_embeddings, dim=-1).expand(batch_size, -1, -1) + + if cache_layer is not None and ratio > 1: + # The tokens that are still waiting for their group to fill up go first. The cache keeps the last + # `ratio - 1` real tokens of each row, and the ones that are waiting are the last of those. + if cache_layer.pooling_buffer is None: + cache_layer.pooling_buffer = states.new_zeros((batch_size, ratio - 1, states.shape[-1])) + num_waiting = num_seen_tokens % ratio + is_waiting = torch.arange(ratio - 1, device=states.device) >= ratio - 1 - num_waiting[:, None] + states = torch.cat([cache_layer.pooling_buffer, states], dim=1) + is_real_token = torch.cat([is_waiting, is_real_token], dim=1) + rope = F.pad(rope, (0, 0, ratio - 1, 0)) + + # Next, we bring the real tokens of each row to the front, in the order that they came in. Group `g` of + # a row is then its real tokens `g * ratio` to `(g + 1) * ratio - 1`, whatever padding the row has, + # and all that is not real ends up after the row's last whole group. + order = (~is_real_token).long().argsort(dim=1, stable=True) + states = states.gather(1, order[..., None].expand_as(states)) + rope = rope.gather(1, order[..., None].expand_as(rope)) + num_real_tokens = is_real_token.sum(dim=1) + + if cache_layer is not None and ratio > 1: + # The last `ratio - 1` real tokens of each row go back to the cache. A row with fewer of them reads + # its first token several times, but those copies come before the tokens that are waiting. + last_tokens = num_real_tokens[:, None] - (ratio - 1) + torch.arange(ratio - 1, device=states.device) + last_tokens = last_tokens.clamp(min=0)[..., None].expand(-1, -1, states.shape[-1]) + cache_layer.pooling_buffer = states.gather(1, last_tokens) + + # Finally, we pool the whole groups. The others are dropped here, and a row that has fewer real groups + # than the longest row gets latents that are made of padding, which the caller must not use. + usable = (states.shape[1] // ratio) * ratio + if self.gate_proj is None: + latents = self.kv_norm(states) + else: + kv, gate = states[:, :usable].unflatten(1, (-1, ratio)).chunk(2, dim=-1) + pooled = (kv * gate.softmax(dim=2)).sum(dim=2) + latents = self.kv_norm(pooled.to(hidden_states.dtype)) + cos, sin = rope[:, ratio - 1 : usable : ratio].chunk(2, dim=-1) + return latents, (cos, sin), num_real_tokens // ratio + + +def select_candidate_blocks( + scores: torch.Tensor, num_visible: torch.Tensor, topk_blocks: int, block_size: int +) -> torch.Tensor: + """ + First level of the two-level top-k: keep the `topk_blocks` best blocks of compressed positions per query. + + Args: + scores (`torch.Tensor` of shape `(batch_size, seq_len, num_entries)`): + Index scores, with the entries a query cannot see yet already at `-inf`. + num_visible (`torch.Tensor` of shape `(batch_size, seq_len)`): + How many compressed entries each query can see. + topk_blocks (`int`): + Number of blocks to keep per query. + block_size (`int`): + Number of compressed positions per block. + + Returns: + `torch.Tensor`: A boolean mask shaped like `scores`, `True` for the entries inside a kept block. + + Example: + + ```python + >>> import torch + >>> scores = torch.tensor([[[0.1, 0.9, 0.3, 0.2, 0.8, float("-inf")]]]) + >>> select_candidate_blocks(scores, num_visible=torch.tensor([[5]]), topk_blocks=2, block_size=2) + tensor([[[ True, True, False, False, True, True]]]) + + ``` + """ + num_entries = scores.shape[-1] + # Score each block by its best position, with `-inf` padding the last block out to `block_size` + block_scores = F.pad(scores, (0, -num_entries % block_size), value=float("-inf")) + block_scores = block_scores.unflatten(-1, (-1, block_size)).amax(dim=-1) + num_blocks = block_scores.shape[-1] + + # The block with the query's newest position is only partly filled, so we always keep it: it holds the + # most recent tokens, but an older full block could outscore it + last_block = (num_visible.unsqueeze(-1) - 1) // block_size + is_last_block = torch.arange(num_blocks, device=scores.device) == last_block + block_scores = block_scores.masked_fill(is_last_block, float("inf")) + + top = block_scores.topk(min(topk_blocks, num_blocks), dim=-1) + # With fewer visible blocks than `topk_blocks`, the leftover picks come back as `-inf`, so we drop them + keep = torch.zeros_like(block_scores, dtype=torch.bool).scatter_(-1, top.indices, top.values > float("-inf")) + return keep.repeat_interleave(block_size, dim=-1)[..., :num_entries] + + +class DeepseekV41Indexer(nn.Module): + """ + Picks the `index_topk` compressed entries that each query attends to. + + This is a small side attention: several query heads are scored against one shared key per compressed + entry, the scores are rectified, and then combined across heads with per-token weights. The keys are made + from the compressor's latents, so only an indexer that sits in a `"compressed_attention"` layer has the + modules to make them (`k_proj` and `k_norm`). The other indexers read those same keys. + + With a candidate source this is the second of two levels, see `select_candidate_blocks` for the first. + """ + + def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): + super().__init__() + self.compress_ratio = config.compress_ratios[layer_idx] + self.num_heads = config.index_n_heads + self.head_dim = config.index_head_dim + self.index_topk = config.index_topk + self.scaling = self.head_dim**-0.5 * self.num_heads**-0.5 + self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False) + self.weights_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False) + if layer_idx in config.kv_source_layer_ids: + self.k_proj = nn.Linear(config.head_dim, self.head_dim, bias=False) + self.k_norm = DeepseekV41RMSNorm(self.head_dim, eps=config.rms_norm_eps) + + candidate_source = config.candidate_source_layer_id + self.is_candidate_source = candidate_source is not None and layer_idx == candidate_source + self.uses_candidates = candidate_source is not None and layer_idx > candidate_source + self.candidate_topk_blocks = config.candidate_topk_blocks + self.candidate_block_size = config.candidate_block_size + + def forward( + self, + hidden_states: torch.Tensor, + q_residual: torch.Tensor, + index_keys: torch.Tensor, + num_real_tokens: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor], + candidates: torch.Tensor | None = None, + ) -> tuple[torch.Tensor, torch.Tensor | None]: + batch_size, seq_len, _ = hidden_states.shape + num_entries = index_keys.shape[1] + if num_entries == 0: + # No group is complete yet, so there is nothing to select + empty = torch.zeros((batch_size, seq_len, 0), dtype=torch.bool, device=hidden_states.device) + return empty, empty if self.is_candidate_source else candidates + + cos, sin = position_embeddings + queries = self.q_b_proj(q_residual).view(batch_size, seq_len, self.num_heads, self.head_dim) + queries = apply_rotary_pos_emb(queries, cos, sin, unsqueeze_dim=2) + # The index keys are FP4 as well, see the attention layer that makes them + queries = fake_quantize(queries, "fp4", block_size=32) + scores = torch.einsum("bshd,btd->bsht", queries, index_keys.to(queries.dtype)) + weights = self.weights_proj(hidden_states) * self.scaling + scores = (F.relu(scores) * weights.unsqueeze(-1)).sum(dim=2) + + # A query sees a compressed entry once it has passed the last token of the entry's group. The groups are + # made of real tokens only, so we count those, up to and including the query. This is also what hides + # the slots after the last entry of a row that has fewer entries than the others. + num_visible = num_real_tokens // self.compress_ratio + visible = torch.arange(num_entries, device=scores.device) < num_visible.unsqueeze(-1) + scores = scores.masked_fill(~visible, float("-inf")) + + if self.is_candidate_source: + # First level: this layer chooses the blocks that the indexers after it may select from + candidates = select_candidate_blocks( + scores, num_visible, self.candidate_topk_blocks, self.candidate_block_size + ) + elif self.uses_candidates: + # Second level: we score with our own weights, but only inside the source's candidate blocks + scores = scores.masked_fill(~candidates, float("-inf")) + + top_scores, top_indices = scores.topk(min(self.index_topk, num_entries), dim=-1) + # Queries with fewer reachable entries than `index_topk` get `-inf` picks back, which we drop + selected = torch.zeros_like(scores, dtype=torch.bool).scatter_(-1, top_indices, top_scores > float("-inf")) + return selected, candidates + + +class DeepseekV41Attention(nn.Module): + r""" + Attention over a sliding window, which is all that the `"sliding_attention"` layers do. The other layer + types also attend to compressed KV entries, which go after the window on the KV axis: + + * `"compressed_attention"` compresses KV of its own. It also makes the index keys for them and runs an + indexer over those keys. The KV-sharing layers after it read all three: the compressed KV, the index + keys and the selection. + * `"kv_shared_indexed_attention"` reads the compressed KV of the last `"compressed_attention"` layer, and + runs its own indexer to select which of them each query attends to. + * `"kv_shared_attention"` reads those compressed KV too, and reuses the selection of the last layer that + ran an indexer. + + Shared with DeepSeek-V4: + * Shared-KV multi-query attention: there is a single KV head, and the same tensor is read as both key and + value. + * Partial RoPE on the last `qk_rope_head_dim` dims of each head. Since the values carry RoPE too, the + output is rotated back at the query's position before the output projection. + * A learnable attention sink per head, and a grouped low-rank output projection. + """ + + def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): + super().__init__() + self.config = config + self.layer_idx = layer_idx + self.layer_type = config.attention_layer_types[layer_idx] + # A layer that reads compressed KV uses their RoPE base for everything, its window included + self.rope_layer_type = "main" if self.layer_type == "sliding_attention" else "compress" + self.compress_ratio = config.compress_ratios[layer_idx] + self.num_heads = config.num_attention_heads + self.num_key_value_groups = config.num_attention_heads # single KV head, broadcast to all + self.head_dim = config.head_dim + self.sliding_window = config.sliding_window + self.attention_dropout = config.attention_dropout + self.is_causal = True + self.scaling = self.head_dim**-0.5 + + self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=False) + self.q_a_norm = DeepseekV41RMSNorm(config.q_lora_rank, eps=config.rms_norm_eps) + self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False) + self.kv_proj = nn.Linear(config.hidden_size, self.head_dim, bias=False) + self.kv_norm = DeepseekV41RMSNorm(self.head_dim, eps=config.rms_norm_eps) + self.o_a_proj = DeepseekV41GroupedLinear( + self.num_heads * self.head_dim // config.o_groups, config.o_groups * config.o_lora_rank, config.o_groups + ) + self.o_b_proj = nn.Linear(config.o_groups * config.o_lora_rank, config.hidden_size, bias=False) + self.sinks = nn.Parameter(torch.empty(self.num_heads, dtype=torch.float32)) + if self.layer_type in ("compressed_attention", "kv_shared_indexed_attention"): + self.indexer = DeepseekV41Indexer(config, layer_idx) + if self.layer_type == "compressed_attention": + self.compressor = DeepseekV41Compressor(config, layer_idx) + + def forward( + self, + hidden_states: torch.Tensor, + position_embeddings: dict[str, tuple[torch.Tensor, torch.Tensor]], + attention_mask: torch.Tensor, + is_real_token: torch.Tensor, + num_seen_tokens: torch.Tensor, + cache: Cache | None = None, + shared_states: dict[str, torch.Tensor] | None = None, + compressed_position_embeddings: dict[int, tuple[torch.Tensor, torch.Tensor]] | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple[torch.Tensor, torch.Tensor | None, dict[str, torch.Tensor]]: + input_shape = hidden_states.shape[:-1] + # We return what we publish in a new dict, and leave the one we were given alone. With gradient + # checkpointing this layer runs again in the backward pass, long after the layers after it, and it has + # to read the same states as the first time. + shared_states = dict(shared_states or {}) + hidden_shape = (*input_shape, -1, self.head_dim) + # The model computes RoPE for both bases, and each layer picks the one that matches its attention type + cos, sin = position_embeddings[self.rope_layer_type] + + q_residual = self.q_a_norm(self.q_a_proj(hidden_states)) + q = self.q_b_proj(q_residual).view(*hidden_shape).transpose(1, 2) + q = apply_rotary_pos_emb(q, cos, sin) + + kv = self.kv_norm(self.kv_proj(hidden_states)).view(*hidden_shape).transpose(1, 2) + kv = apply_rotary_pos_emb(kv, cos, sin) + # The KV are FP8 from here on, in the cache too. They are rounded after RoPE, so on the rotated dims + # it is the rotated values that land on the FP8 grid. + kv = fake_quantize(kv, "fp8", block_size=32) + if cache is not None: + kv = cache.update(kv, kv, self.layer_idx)[0] + + if self.layer_type == "compressed_attention": + # This layer compresses the groups that this call completes. A row may complete none of them, e.g. + # when decoding a token that is not the last of its group. + cache_layer: DeepseekV41CacheLayer | None = cache.layers[self.layer_idx] if cache is not None else None + latents, (entry_cos, entry_sin), num_new_entries = self.compressor( + hidden_states, + compressed_position_embeddings[self.compress_ratio], + is_real_token, + num_seen_tokens, + cache_layer, + ) + # The index keys come from the latents before RoPE, so we make them before we rotate the latents + index_keys = self.indexer.k_norm(self.indexer.k_proj(latents)) + index_keys = apply_rotary_pos_emb(index_keys.unsqueeze(1), entry_cos, entry_sin).squeeze(1) + compressed_kv = apply_rotary_pos_emb(latents.unsqueeze(1), entry_cos, entry_sin).squeeze(1) + # Both are FP4 from here on. The compressed KV get a finer scale than the index keys: one per 16 + # values instead of 32, and an FP8 number instead of a power of two. + index_keys = fake_quantize(index_keys, "fp4", block_size=32) + compressed_kv = fake_quantize(compressed_kv, "fp4", block_size=16, scale_format="fp8") + if cache_layer is not None: + # Each row has one entry per whole group of the tokens that it had seen before this call + compressed_kv, index_keys = cache_layer.update_compressed_states( + compressed_kv, index_keys, num_seen_tokens // self.compress_ratio, num_new_entries + ) + # We publish both for the indexers and the KV-sharing layers after us, starting with our own + shared_states["compressed_kv"], shared_states["index_keys"] = compressed_kv, index_keys + + if self.layer_type in ("compressed_attention", "kv_shared_indexed_attention"): + # This layer selects which compressed entries each query attends to, and the + # `"kv_shared_attention"` layers after it reuse the selection + shared_states["selected"], shared_states["candidates"] = self.indexer( + hidden_states, + q_residual, + shared_states["index_keys"], + num_seen_tokens[:, None] + is_real_token.cumsum(dim=-1), + (cos, sin), + shared_states.get("candidates"), + ) + + if self.layer_type != "sliding_attention": + # The compressed entries go after the window on the KV axis. The model built the mask for the + # window only, so we extend it with the entries that each query selected. + compressed_kv, selected = shared_states["compressed_kv"], shared_states["selected"] + kv = torch.cat([kv, compressed_kv.unsqueeze(1).to(kv.dtype)], dim=2) + compressed_mask = torch.zeros_like(selected, dtype=attention_mask.dtype) + compressed_mask = compressed_mask.masked_fill(~selected, torch.finfo(attention_mask.dtype).min) + attention_mask = torch.cat([attention_mask, compressed_mask.unsqueeze(1)], dim=-1) + + attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( + self.config._attn_implementation, eager_attention_forward + ) + attn_output, attn_weights = attention_interface( + self, + q, + kv, + kv, + attention_mask, + dropout=0.0 if not self.training else self.attention_dropout, + scaling=self.scaling, + sliding_window=self.sliding_window, + s_aux=self.sinks, + **kwargs, + ) + + # The values are the keys, so they picked up RoPE too. We undo it on the output with the conjugate + # rotation at the query's position, before the grouped output projection mixes the heads. + attn_output = apply_rotary_pos_emb(attn_output, cos, -sin, unsqueeze_dim=2) + + grouped = attn_output.reshape(*input_shape, self.config.o_groups, -1) + # The grouped projection was trained as an FP8 matmul, which rounds its input to FP8 + grouped = fake_quantize(grouped, "fp8", block_size=32) + grouped = self.o_a_proj(grouped).flatten(2) + output = self.o_b_proj(grouped) + return output, attn_weights, shared_states + + +class DeepseekV41HyperConnection(nn.Module): + r""" + Computes the hyper-connection weights of one sublayer (attention or MLP) from the `hc_mult` residual + streams. As in DeepSeek-V4, there are three of them: + + - pre: collapses the `hc_mult` streams into the single input of a sublayer + - post: expands the output of the sublayer back into `hc_mult` streams + - comb: mixes the `hc_mult` input streams into the output streams, and is made doubly stochastic with a few + iterations of the Sinkhorn-Knopp algorithm + + Unlike DeepSeek-V4, "pre" is not used by the sublayer that these weights belong to. It collapses the + streams for the *next* sublayer, so we return it instead of applying it here. See + `DeepseekV41DecoderLayer` for how the weights are passed along. + """ + + def __init__(self, config: DeepseekV41TextConfig): + super().__init__() + self.hc_mult = config.hc_mult + self.hc_sinkhorn_iters = config.hc_sinkhorn_iters + self.hc_eps = config.hc_eps + self.norm_eps = config.rms_norm_eps + # The three weights come out of a single projection: pre and post have `hc_mult` entries each, and comb + # is a `hc_mult x hc_mult` matrix + concatenated_weights_size = (2 + self.hc_mult) * self.hc_mult + self.fn = nn.Parameter(torch.empty(concatenated_weights_size, self.hc_mult * config.hidden_size)) + self.base = nn.Parameter(torch.empty(concatenated_weights_size)) + self.scale = nn.Parameter(torch.empty(3)) + + def forward(self, hidden_streams: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + hc = self.hc_mult + # The streams are normalized together, with one statistic per token + flattened = hidden_streams.flatten(2).float() + rsqrt = torch.rsqrt(flattened.square().mean(-1, keepdim=True) + self.norm_eps) + mixes = F.linear(flattened, self.fn.float()) * rsqrt + + pre_w, post_w, comb_w = mixes.split([hc, hc, hc * hc], dim=-1) + pre_b, post_b, comb_b = self.base.float().split([hc, hc, hc * hc]) + pre_scale, post_scale, comb_scale = self.scale.float().unbind(0) + + pre = torch.sigmoid(pre_w * pre_scale + pre_b) + self.hc_eps + post = 2 * torch.sigmoid(post_w * post_scale + post_b) + comb = comb_w.unflatten(-1, (hc, hc)) * comb_scale + comb_b.view(hc, hc) + comb = torch.softmax(comb, dim=-1) + self.hc_eps + + # Sinkhorn-Knopp: alternately normalize the columns and the rows, so that both end up summing to 1 + comb = comb / (comb.sum(dim=-2, keepdim=True) + self.hc_eps) + for _ in range(self.hc_sinkhorn_iters - 1): + comb = comb / (comb.sum(dim=-1, keepdim=True) + self.hc_eps) + comb = comb / (comb.sum(dim=-2, keepdim=True) + self.hc_eps) + return pre, post, comb + + +class DeepseekV41MLP(DeepseekV4MLP): + pass + + +@use_experts_implementation +class DeepseekV41Experts(DeepseekV4Experts): + pass + + +class DeepseekV41TopKRouter(DeepseekV4TopKRouter): + """ + Top-k router. The correction bias only steers which experts are selected, and the routing weights come + from the unbiased scores. The tokens of an image use a separate bias. + """ + + def __init__(self, config: DeepseekV41TextConfig): + super().__init__(config) + self.e_score_correction_bias_vl = nn.Buffer(torch.zeros(self.num_experts, dtype=torch.float32)) + + def forward( + self, hidden_states: torch.Tensor, image_mask: torch.Tensor | None = None + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + flat = hidden_states.reshape(-1, self.hidden_dim) + # The reference routes in float32, and the selection is sensitive enough that bfloat16 changes it + logits = F.linear(flat.float(), self.weight.float()) + scores = self.score_fn(logits) + bias = self.e_score_correction_bias + if image_mask is not None: + bias = torch.where(image_mask.reshape(-1, 1), self.e_score_correction_bias_vl, bias) + indices = torch.topk(scores + bias, self.top_k, dim=-1, sorted=False).indices + weights = scores.gather(1, indices) + weights = weights / (weights.sum(dim=-1, keepdim=True) + 1e-20) + return logits, weights * self.routed_scaling_factor, indices + + +class DeepseekV41SparseMoeBlock(nn.Module): + def __init__(self, config: DeepseekV41TextConfig): + super().__init__() + self.gate = DeepseekV41TopKRouter(config) + self.experts = DeepseekV41Experts(config) + self.shared_experts = DeepseekV41MLP(config) + + def forward(self, hidden_states: torch.Tensor, image_mask: torch.Tensor | None = None) -> torch.Tensor: + batch_size, seq_len, hidden_dim = hidden_states.shape + _, weights, indices = self.gate(hidden_states, image_mask) + routed = self.experts(hidden_states.view(-1, hidden_dim), indices, weights) + return routed.view(batch_size, seq_len, hidden_dim) + self.shared_experts(hidden_states) + + +def _is_prime(number: int) -> bool: + if number < 2: + return False + if number % 2 == 0: + return number == 2 + divisor = 3 + while divisor * divisor <= number: + if number % divisor == 0: + return False + divisor += 2 + return True + + +def _engram_bucket_sizes(config: DeepseekV41TextConfig) -> list[list[int]]: + # Every (n-gram size, head) pair of every Engram layer hashes into its own range of buckets. The size of + # each range is a prime, and no prime is used twice across the whole model. For each n-gram size the + # search restarts just below `engram_vocab_size`, so we end up handing out consecutive primes. + bucket_sizes, seen = [], set() + for _ in config.engram_layer_ids: + layer_sizes = [] + for _ in range(config.engram_max_ngram_size - 1): + candidate = config.engram_vocab_size - 1 + for _ in range(config.engram_n_heads): + candidate += 1 + while candidate in seen or not _is_prime(candidate): + candidate += 1 + seen.add(candidate) + layer_sizes.append(candidate) + bucket_sizes.append(layer_sizes) + return bucket_sizes + + +def _engram_hash_multipliers(config: DeepseekV41TextConfig) -> np.ndarray: + # One multiplier per (layer, lookback), from a per-layer RNG so that the layers hash differently. They + # are kept odd, and bounded so that `token_id * multiplier` cannot overflow int64. + bound = max(1, (np.iinfo(np.int64).max // config.engram_compressed_vocab_size) // 2) + rows = [] + for layer_idx in config.engram_layer_ids: + generator = np.random.default_rng(10007 * layer_idx) + values = generator.integers(low=0, high=bound, size=(config.engram_max_ngram_size,), dtype=np.int64) + rows.append(values * 2 + 1) + return np.stack(rows) + + +def _default_engram_token_map(config: DeepseekV41TextConfig) -> torch.Tensor: + if config.engram_compressed_vocab_size == config.vocab_size: + # A compressed vocab as large as the vocab itself merges no tokens, so the map is the identity + return torch.arange(config.vocab_size) + # Otherwise the map comes from the tokenizer (see `build_engram_token_map`), and -1 marks it as missing + return torch.full((config.vocab_size,), -1, dtype=torch.long) + + +def build_engram_token_map(tokenizer) -> torch.Tensor: + """ + Builds the map from token ids to the smaller id space that the Engram n-grams are hashed over. Tokens that + normalize alike are merged there, so that " The", "the" and "THE" all hash the same way. + + The DeepSeek-V4.1 checkpoints do not store this map. The reference implementation builds it from the + tokenizer when it creates the model, and this function does the same. + + Args: + tokenizer ([`PreTrainedTokenizerFast`]): + The tokenizer of the checkpoint. + + Returns: + `torch.Tensor` of shape `(len(tokenizer),)`: The compressed id of each token. + + Example: + + ```python + >>> from transformers import AutoTokenizer + >>> from transformers.models.deepseek_v41.modeling_deepseek_v41 import build_engram_token_map + + >>> tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/DeepSeek-V4.1-Flash") + >>> token_map = build_engram_token_map(tokenizer) + >>> token_map[tokenizer.convert_tokens_to_ids("The")] == token_map[tokenizer.convert_tokens_to_ids("the")] + tensor(True) + + ``` + """ + from tokenizers import Regex, normalizers + + # A private-use char, so that a token that is exactly one space survives `Strip()` instead of collapsing + # to the empty string and merging with unrelated tokens + sentinel = "" + normalizer = normalizers.Sequence( + [ + normalizers.NFKC(), + normalizers.NFD(), + normalizers.StripAccents(), + normalizers.Lowercase(), + normalizers.Replace(Regex(r"[ \t\r\n]+"), " "), + normalizers.Replace(Regex(r"^ $"), sentinel), + normalizers.Strip(), + normalizers.Replace(sentinel, " "), + ] + ) + + # We decode with the raw Rust tokenizer, which is what training did (no `clean_up_tokenization_spaces`) + backend = tokenizer.backend_tokenizer + key_to_compressed_id: dict[str, int] = {} + token_map = [] + for token_id in range(len(tokenizer)): + text = backend.decode([token_id], skip_special_tokens=False) + if "�" in text: + # A partial UTF-8 byte token has nothing to normalize, so we key it by its raw form + key = backend.id_to_token(token_id) + else: + key = normalizer.normalize_str(text) or text + token_map.append(key_to_compressed_id.setdefault(key, len(key_to_compressed_id))) + return torch.tensor(token_map, dtype=torch.long) + + +class DeepseekV41NgramHasher(nn.Module): + """ + Maps each position to the hash ids of the n-grams that end there, for all Engram layers at once. + + Token ids first go through `token_map`, then each position is hashed together with the + `engram_max_ngram_size - 1` tokens before it. The look-back stops at the start of the sequence and at any + masked token (padding or an image), so an n-gram never spans one. + """ + + def __init__(self, config: DeepseekV41TextConfig): + super().__init__() + self.config = config + self.max_ngram_size = config.engram_max_ngram_size + self.num_heads = config.engram_n_heads + self.pad_token_id = config.engram_pad_token_id + bucket_sizes = torch.tensor(_engram_bucket_sizes(config)) + self.bucket_sizes = nn.Buffer(bucket_sizes, persistent=False) + self.offsets = nn.Buffer(bucket_sizes.cumsum(-1) - bucket_sizes, persistent=False) + self.multipliers = nn.Buffer(torch.from_numpy(_engram_hash_multipliers(config)), persistent=False) + self.token_map = nn.Buffer(_default_engram_token_map(config)) + + def forward( + self, + input_ids: torch.Tensor, + token_mask: torch.Tensor | None = None, + cache_layer: DeepseekV41CacheLayer | None = None, + ) -> torch.Tensor: + compressed_ids = self.token_map[input_ids] + if (compressed_ids < 0).any(): + raise ValueError( + "The Engram token map has no entry for some of the input ids. The DeepSeek-V4.1 checkpoints do " + "not store this map, so it has to be built from the tokenizer once after loading the model:\n" + "`model.set_engram_token_map(tokenizer)`" + ) + # A masked token takes no part in any n-gram. We mark it with -1, like the start of the sequence. + if token_mask is not None: + compressed_ids = torch.where(token_mask, compressed_ids, -1) + history_length = self.max_ngram_size - 1 + if cache_layer is not None: + compressed_ids = cache_layer.update_token_history(compressed_ids, history_length) + else: + compressed_ids = F.pad(compressed_ids, (history_length, 0), value=-1) + + # One window per position: the token itself comes first, then the tokens before it, nearest first. + # Once the look-back hits a -1, that slot and all the ones behind it read as padding. + windows = compressed_ids.unfold(1, self.max_ngram_size, 1).flip(-1) + blocked = (windows == -1).cummax(dim=-1).values + windows = torch.where(blocked, self.token_map[self.pad_token_id], windows) + + # We XOR the multiplied ids together one look-back at a time, so the running value after step `i` is + # the hash of the (i+1)-gram. Each one lands in its own prime-sized range of buckets. + products = windows.unsqueeze(2) * self.multipliers + rolling, hash_ids = products[..., 0], [] + for ngram_index in range(history_length): + rolling = torch.bitwise_xor(rolling, products[..., ngram_index + 1]) + sizes = self.bucket_sizes[:, ngram_index * self.num_heads : (ngram_index + 1) * self.num_heads] + hash_ids.append(rolling.unsqueeze(-1) % sizes) + return torch.cat(hash_ids, dim=-1) + self.offsets + + +class DeepseekV41Engram(nn.Module): + """ + Writes an n-gram lookup into the residual streams, gated by how well it matches each stream. + + The hash ids fetch one row of the table per (n-gram size, head) pair. `kv_proj` turns the concatenated + rows into one key per stream plus a value that the streams share, and the gate of a stream is the + normalized dot product of the stream with its key. + """ + + def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): + super().__init__() + self.hidden_size = config.hidden_size + self.hc_mult = config.hc_mult + self.eps = config.rms_norm_eps + engram_index = config.engram_layer_ids.index(layer_idx) + num_embeddings = sum(_engram_bucket_sizes(config)[engram_index]) + if config.engram_num_embeddings is not None and config.engram_num_embeddings[engram_index] != num_embeddings: + raise ValueError( + f"The Engram table of layer {layer_idx} needs {num_embeddings} rows, which is the sum of its bucket " + f"sizes, but `engram_num_embeddings` says {config.engram_num_embeddings[engram_index]}. The bucket " + "sizes come from `engram_vocab_size`, `engram_n_heads`, `engram_max_ngram_size` and " + "`engram_layer_ids`, so one of those does not match the checkpoint." + ) + num_lookups = (config.engram_max_ngram_size - 1) * config.engram_n_heads + self.embed = nn.Embedding(num_embeddings, config.engram_head_dim) + self.kv_proj = nn.Linear( + num_lookups * config.engram_head_dim, config.hidden_size * (config.hc_mult + 1), bias=False + ) + self.q_weight = nn.Parameter(torch.ones(config.hc_mult, config.hidden_size)) + self.k_weight = nn.Parameter(torch.ones(config.hc_mult, config.hidden_size)) + + def forward( + self, hidden_streams: torch.Tensor, hash_ids: torch.Tensor, token_mask: torch.Tensor | None = None + ) -> torch.Tensor: + key_value = self.kv_proj(self.embed(hash_ids).flatten(-2).to(hidden_streams.dtype)) + key, value = key_value.split([self.hc_mult * self.hidden_size, self.hidden_size], dim=-1) + key = key.float().unflatten(-1, (self.hc_mult, self.hidden_size)) + streams = hidden_streams.float() + # The two weights are only ever used as a product + weight = self.q_weight.float() * self.k_weight.float() + # Normalized per (token, stream) over the hidden dim, NOT jointly over the streams + rsqrt = torch.rsqrt(streams.square().mean(-1) + self.eps) * torch.rsqrt(key.square().mean(-1) + self.eps) + dot = (streams * weight * key).sum(-1) * rsqrt * self.hidden_size**-0.5 + # Signed square root before the sigmoid, as in training + gate = torch.sigmoid(torch.copysign(dot.abs().clamp_min(1e-6).sqrt(), dot)) + if token_mask is not None: + gate = gate.masked_fill(~token_mask.unsqueeze(-1), 0) + return (streams + gate.unsqueeze(-1) * value.float().unsqueeze(-2)).to(hidden_streams.dtype) + + +class DeepseekV41DecoderLayer(GradientCheckpointingLayer): + r""" + DeepSeek-V4.1 decoder block. As in DeepSeek-V4, the residual is a stack of `hc_mult` parallel streams of + shape `[B, S, hc_mult, D]`, which hyper-connections collapse into the input of each sublayer and expand + back out afterwards. + + What changes is where the collapsing weights come from. Each sublayer's hyper-connection computes "pre", + "post" and "comb" from the streams that enter the sublayer, but only "post" and "comb" are used there. Its + "pre" collapses the streams for the *next* sublayer: the attention uses the "pre" of the previous layer's + MLP, and the MLP uses the "pre" of this layer's attention. So the layer takes one "pre" in and returns one. + """ + + def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): + super().__init__() + self.layer_idx = layer_idx + self.self_attn = DeepseekV41Attention(config, layer_idx) + self.mlp = DeepseekV41SparseMoeBlock(config) + self.input_layernorm = DeepseekV41RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_attention_layernorm = DeepseekV41RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.attn_hc = DeepseekV41HyperConnection(config).to(dtype=torch.float32) + self.ffn_hc = DeepseekV41HyperConnection(config).to(dtype=torch.float32) + self.engram = DeepseekV41Engram(config, layer_idx) if layer_idx in config.engram_layer_ids else None + + def forward( + self, + hidden_states: torch.Tensor, + pre: torch.Tensor, + engram_hash_ids: torch.Tensor | None = None, + engram_mask: torch.Tensor | None = None, + image_mask: torch.Tensor | None = None, + shared_states: dict[str, torch.Tensor] | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple[torch.Tensor, torch.Tensor, dict[str, torch.Tensor]]: + # hidden_states throughout: [B, S, hc_mult, hidden]. The hyper-connection weights are float32, and + # comb is used transposed: sum_j comb[j, k] * residual[j], which is comb.T @ residual. + dtype = hidden_states.dtype + if self.engram is not None: + hidden_states = self.engram(hidden_states, engram_hash_ids, engram_mask) + + attn_pre, post, comb = self.attn_hc(hidden_states) + collapsed = (pre.unsqueeze(-1) * hidden_states.float()).sum(dim=2).to(dtype) + attn_output, _, shared_states = self.self_attn( + self.input_layernorm(collapsed), shared_states=shared_states, **kwargs + ) + hidden_states = post.unsqueeze(-1) * attn_output.unsqueeze(-2) + torch.matmul( + comb.transpose(-1, -2), hidden_states.float() + ) + hidden_states = hidden_states.to(dtype) + + mlp_pre, post, comb = self.ffn_hc(hidden_states) + collapsed = (attn_pre.unsqueeze(-1) * hidden_states.float()).sum(dim=2).to(dtype) + mlp_output = self.mlp(self.post_attention_layernorm(collapsed), image_mask=image_mask) + hidden_states = post.unsqueeze(-1) * mlp_output.unsqueeze(-2) + torch.matmul( + comb.transpose(-1, -2), hidden_states.float() + ) + return hidden_states.to(dtype), mlp_pre, shared_states + + +def vision_eager_attention_forward( + module: nn.Module, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: torch.Tensor | None, + scaling: float, + dropout: float | int = 0.0, + **kwargs, +): + # Plain attention. The eager function of the language model adds an attention sink, which the vision encoder + # does not have. + attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling + if attention_mask is not None: + attn_weights = attn_weights + attention_mask + attn_weights = F.softmax(attn_weights, dim=-1) + attn_weights = F.dropout(attn_weights, p=dropout, training=module.training) + attn_output = torch.matmul(attn_weights, value) + return attn_output.transpose(1, 2).contiguous(), attn_weights + + +class DeepseekV41VisionAttention(nn.Module): + """Bidirectional attention over the patches of one image, with 2D RoPE.""" + + def __init__(self, config: DeepseekV41VisionConfig): + super().__init__() + self.config = config + self.num_heads = config.num_attention_heads + self.head_dim = config.hidden_size // config.num_attention_heads + self.scaling = self.head_dim**-0.5 + self.qkv_proj = nn.Linear(config.hidden_size, 3 * config.hidden_size) + self.o_proj = nn.Linear(config.hidden_size, config.hidden_size) + + def forward( + self, hidden_states: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor | None]: + num_patches = hidden_states.shape[0] + query, key, value = self.qkv_proj(hidden_states).view(num_patches, 3, self.num_heads, self.head_dim).unbind(1) + query, key = _apply_vision_rotary(query, cos, sin), _apply_vision_rotary(key, cos, sin) + + attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( + self.config._attn_implementation, vision_eager_attention_forward + ) + # The attention functions take a batch, which here is the one image + attn_output, attn_weights = attention_interface( + self, + query.transpose(0, 1).unsqueeze(0), + key.transpose(0, 1).unsqueeze(0), + value.transpose(0, 1).unsqueeze(0), + attention_mask=None, + scaling=self.scaling, + is_causal=False, + ) + # Only eager attention returns the weights + attn_weights = attn_weights.squeeze(0) if attn_weights is not None else None + return self.o_proj(attn_output.reshape(num_patches, -1)), attn_weights + + +def _apply_vision_rotary(hidden_states: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: + # The first half of each head is rotated against the second half, in float32 + first, second = hidden_states.float().chunk(2, dim=-1) + rotated = torch.cat([first * cos - second * sin, second * cos + first * sin], dim=-1) + return rotated.to(hidden_states.dtype) + + +class DeepseekV41VisionMLP(nn.Module): + def __init__(self, config: DeepseekV41VisionConfig): + super().__init__() + self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False) + self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + gate, up = self.gate_up_proj(hidden_states).chunk(2, dim=-1) + return self.down_proj(F.silu(gate) * up) + + +class DeepseekV41VisionLayer(GradientCheckpointingLayer): + def __init__(self, config: DeepseekV41VisionConfig): + super().__init__() + self.layer_norm1 = DeepseekV41RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.self_attn = DeepseekV41VisionAttention(config) + self.layer_norm2 = DeepseekV41RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.mlp = DeepseekV41VisionMLP(config) + + def forward(self, hidden_states: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: + attn_output, _ = self.self_attn(self.layer_norm1(hidden_states), cos, sin) + hidden_states = hidden_states + attn_output + return hidden_states + self.mlp(self.layer_norm2(hidden_states)) + + +class DeepseekV41MultiModalProjector(nn.Module): + """Merges each `downsample_ratio x downsample_ratio` square of patches into one language model token.""" + + def __init__(self, config: "DeepseekV41Config"): + super().__init__() + self.downsample_ratio = config.vision_config.downsample_ratio + input_size = config.vision_config.hidden_size * self.downsample_ratio**2 + self.linear_1 = nn.Linear(input_size, config.text_config.hidden_size) + self.linear_2 = nn.Linear(config.text_config.hidden_size, config.text_config.hidden_size) + + def forward(self, image_features: torch.Tensor, height: int, width: int) -> torch.Tensor: + ratio = self.downsample_ratio + image_features = image_features.view(height, width, -1).permute(2, 0, 1) + # A grid that is not a multiple of the ratio is zero-padded at the bottom and on the right + image_features = F.pad(image_features, (0, -width % ratio, 0, -height % ratio)) + image_features = F.unfold(image_features.unsqueeze(0), ratio, stride=ratio).squeeze(0).transpose(0, 1) + return self.linear_2(F.gelu(self.linear_1(image_features))) + + +@auto_docstring +class DeepseekV41PreTrainedModel(PreTrainedModel): + config: DeepseekV41Config + base_model_prefix = "model" + input_modalities = ("image", "text") + supports_gradient_checkpointing = True + _no_split_modules = ["DeepseekV41DecoderLayer", "DeepseekV41VisionLayer"] + # Eager only, for the same reasons as DeepSeek-V4: the head dim of 512 is above what FlashAttention + # supports, SDPA has no attention sink, and the compressed entries are added to the KV axis inside the + # attention, after the mask was built. + _supports_flash_attn = False + _supports_sdpa = False + _supports_flex_attn = False + # The compressed KV, the pooling buffers and the Engram token history live in `DeepseekV41CacheLayer`, + # which has no static version + _can_compile_fullgraph = False + # ... and they cannot be rolled back either, which rules out assisted generation and friends + _is_stateful = True + # Everything listed here is also created in float32 in its `__init__`. `from_pretrained` enforces this + # list, but a model built straight from a config would otherwise get the default dtype + _keep_in_fp32_modules_strict = [ + "attn_hc", + "ffn_hc", + "sinks", + "e_score_correction_bias", + "e_score_correction_bias_vl", + ] + # The DSpark draft layers are not supported yet + _keys_to_ignore_on_load_unexpected = [r"(^|\.)mtp\..*"] + _can_record_outputs = { + "router_logits": OutputRecorder(DeepseekV41TopKRouter, index=0), + "hidden_states": OutputRecorder(DeepseekV41DecoderLayer, index=0), + "attentions": OutputRecorder(DeepseekV41Attention, index=1), + } + + def _init_weights(self, module): + PreTrainedModel._init_weights(self, module) + std = self.config.get_text_config().initializer_range + if isinstance(module, DeepseekV41TopKRouter): + init.normal_(module.weight, mean=0.0, std=std) + init.zeros_(module.e_score_correction_bias) + init.zeros_(module.e_score_correction_bias_vl) + elif isinstance(module, DeepseekV41Experts): + init.normal_(module.gate_up_proj, mean=0.0, std=std) + init.normal_(module.down_proj, mean=0.0, std=std) + elif isinstance(module, DeepseekV41Attention): + init.zeros_(module.sinks) + elif isinstance(module, DeepseekV41HyperConnection): + init.normal_(module.fn, mean=0.0, std=std) + init.zeros_(module.base) + init.ones_(module.scale) + elif isinstance(module, DeepseekV41Engram): + init.ones_(module.q_weight) + init.ones_(module.k_weight) + elif isinstance(module, DeepseekV41NgramHasher): + bucket_sizes = torch.tensor(_engram_bucket_sizes(module.config)) + init.copy_(module.bucket_sizes, bucket_sizes) + init.copy_(module.offsets, bucket_sizes.cumsum(-1) - bucket_sizes) + init.copy_(module.multipliers, torch.from_numpy(_engram_hash_multipliers(module.config))) + init.copy_(module.token_map, _default_engram_token_map(module.config)) + elif isinstance(module, DeepseekV41Model): + init.normal_(module.image_start, mean=0.0, std=std) + init.normal_(module.image_end, mean=0.0, std=std) + init.normal_(module.image_newline, mean=0.0, std=std) + elif isinstance(module, DeepseekV41RotaryEmbedding): + for layer_type in module.layer_types: + rope_init_fn = module.compute_default_rope_parameters + if module.rope_type[layer_type] != "default": + rope_init_fn = ROPE_INIT_FUNCTIONS[module.rope_type[layer_type]] + curr_inv_freq, _ = rope_init_fn(module.config, layer_type=layer_type) + init.copy_(getattr(module, f"{layer_type}_inv_freq"), curr_inv_freq) + init.copy_(getattr(module, f"{layer_type}_original_inv_freq"), curr_inv_freq) + + def activation_checkpointing_enable( + self, activation_checkpointing_kwargs=None, every_n_layers: int = 1, offload: bool = False + ): + """ + Same as [`PreTrainedModel.activation_checkpointing_enable`], except that `use_reentrant=True` is refused. + + Reentrant checkpointing only tracks the gradient of the tensors that a layer gets as positional arguments. + The compressed KV reaches the KV-sharing layers in a dict, so the layer that compressed it would silently + lose the gradient that comes back through them. + """ + if activation_checkpointing_kwargs is not None and activation_checkpointing_kwargs.get("use_reentrant"): + raise ValueError( + "DeepSeek-V4.1 does not support activation checkpointing with `use_reentrant=True`, because the " + "gradient of the compressed KV that its layers share would be lost. Use `use_reentrant=False`, " + "which is the default.\n" + f"activation_checkpointing_kwargs: {activation_checkpointing_kwargs}" + ) + super().activation_checkpointing_enable( + activation_checkpointing_kwargs, every_n_layers=every_n_layers, offload=offload + ) + + # The structure linter reads any `set_*` method as a hyperparameter that should live on the config. This one + # fills a buffer that is saved and loaded with the weights, and it only exists because the original + # checkpoints left that buffer out. + def set_engram_token_map(self, tokenizer_or_token_map): # trf-ignore: TRF033 + """ + Sets the map from token ids to compressed ids that the Engram n-grams are hashed over. The checkpoints do + not store it, so it has to be set once after loading the model. + + Args: + tokenizer_or_token_map ([`PreTrainedTokenizerFast`] or `torch.Tensor`): + The tokenizer of the checkpoint, or a map that `build_engram_token_map` made from it. + """ + hasher = next((module for module in self.modules() if isinstance(module, DeepseekV41NgramHasher)), None) + if hasher is None: + raise ValueError("This model has no Engram layers, so there is no token map to set.") + if isinstance(tokenizer_or_token_map, torch.Tensor): + # An existing map, e.g. one that was built earlier and saved + token_map = tokenizer_or_token_map + else: + # A tokenizer, which we build the map from in the same way as the reference implementation + token_map = build_engram_token_map(tokenizer_or_token_map) + num_compressed_ids = int(token_map.max()) + 1 + if num_compressed_ids != hasher.config.engram_compressed_vocab_size: + raise ValueError( + f"The token map has {num_compressed_ids} compressed ids, but the model was trained with " + f"{hasher.config.engram_compressed_vocab_size} (`config.engram_compressed_vocab_size`). The hash " + "multipliers are derived from that number, so this is not the tokenizer the checkpoint was " + "trained with." + ) + if token_map.shape[0] > hasher.token_map.shape[0]: + raise ValueError( + f"The token map has {token_map.shape[0]} entries, but the model only has " + f"{hasher.token_map.shape[0]} tokens (`config.vocab_size`)." + ) + hasher.token_map[: token_map.shape[0]] = token_map.to(hasher.token_map.device) + + def resize_token_embeddings( + self, + new_num_tokens: int | None = None, + pad_to_multiple_of: int | None = None, + mean_resizing: bool = True, + ): + """ + Not supported: the Engram layers look token ids up in a token map and hash them into n-gram tables, and + both are fixed to the vocabulary that the checkpoint was trained with. + """ + # A new token would need an entry in the token map, and a compressed id that the hash multipliers and + # the n-gram tables were never trained with. We'd rather fail here than hand back a model whose new + # tokens index past the end of the map. + raise NotImplementedError( + "DeepSeek-V4.1 does not support resizing the token embeddings, because its Engram layers hash " + "n-grams of token ids through a token map that is fixed to the vocabulary of the checkpoint. " + "If you need a new token, reuse one of the placeholder tokens that the tokenizer already has.\n" + f"new_num_tokens: {new_num_tokens}" + ) + + +@auto_docstring( + custom_intro=""" + The DeepSeek-V4.1 vision encoder: a ViT with 2D RoPE that runs full attention over the patches of one image. + """ +) +class DeepseekV41VisionModel(DeepseekV41PreTrainedModel): + config: DeepseekV41VisionConfig + main_input_name = "pixel_values" + input_modalities = ("image",) + # Unlike the language model, the vision encoder has plain attention with no sink + _supports_sdpa = True + _can_record_outputs = { + "hidden_states": DeepseekV41VisionLayer, + "attentions": DeepseekV41VisionAttention, + } + + def __init__(self, config: DeepseekV41VisionConfig): + super().__init__(config) + self.rope_dim = config.hidden_size // config.num_attention_heads // 2 + self.patch_embed = nn.Linear(config.num_channels * config.patch_size**2, config.hidden_size) + self.layers = nn.ModuleList([DeepseekV41VisionLayer(config) for _ in range(config.num_hidden_layers)]) + self.norm = DeepseekV41RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_init() + + def get_position_embeddings(self, height: int, width: int, device) -> tuple[torch.Tensor, torch.Tensor]: + """2D RoPE: the first half of the frequencies encodes the row of a patch, and the second half its column.""" + exponents = torch.arange(0, self.rope_dim, 2, dtype=torch.float32, device=device) / self.rope_dim + inv_freq = 1.0 / (self.config.rope_theta**exponents) + rows = torch.arange(height, device=device).unsqueeze(1).expand(height, width) + columns = torch.arange(width, device=device).unsqueeze(0).expand(height, width) + freqs = torch.stack([rows, columns], dim=-1).reshape(-1, 2, 1).float() * inv_freq + freqs = freqs.flatten(1) + return freqs.cos().unsqueeze(1), freqs.sin().unsqueeze(1) + + @merge_with_config_defaults + @capture_outputs + @auto_docstring + def forward( + self, pixel_values: torch.Tensor, height: int, width: int, **kwargs: Unpack[TransformersKwargs] + ) -> BaseModelOutput: + r""" + pixel_values (`torch.Tensor` of shape `(height * width, num_channels * patch_size * patch_size)`): + The flattened patches of one image, in row-major order. + height (`int`): + Number of rows in the image's patch grid. + width (`int`): + Number of columns in the image's patch grid. + """ + hidden_states = self.patch_embed(pixel_values.flatten(1).to(self.patch_embed.weight.dtype)) + cos, sin = self.get_position_embeddings(height, width, hidden_states.device) + for layer in self.layers: + hidden_states = layer(hidden_states, cos, sin) + return BaseModelOutput(last_hidden_state=self.norm(hidden_states)) + + +@auto_docstring( + custom_intro=""" + The DeepSeek-V4.1 language model, without the vision encoder and the language modeling head. + """ +) +class DeepseekV41TextModel(DeepseekV41PreTrainedModel): + config: DeepseekV41TextConfig + input_modalities = ("text",) + + def __init__(self, config: DeepseekV41TextConfig): + super().__init__(config) + self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) + self.layers = nn.ModuleList( + [DeepseekV41DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] + ) + self.norm = DeepseekV41RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.rotary_emb = DeepseekV41RotaryEmbedding(config) + self.engram_hasher = DeepseekV41NgramHasher(config) if config.engram_layer_ids else None + self.gradient_checkpointing = False + self.post_init() + + @merge_with_config_defaults + @capture_outputs + @auto_docstring + @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") + def forward( + self, + input_ids: torch.LongTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + cache: Cache | None = None, + inputs_embeds: torch.Tensor | None = None, + use_cache: bool | None = None, + image_mask: torch.BoolTensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> MoeModelOutputWithPast: + r""" + image_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*): + `True` for the tokens of an image. They are routed with a separate bias and take no part in the + Engram n-grams. + """ + if input_ids is None and inputs_embeds is None: + raise ValueError("You must specify at least one of input_ids or inputs_embeds") + if self.engram_hasher is not None and input_ids is None: + raise ValueError( + "DeepSeek-V4.1 hashes n-grams of token ids for its Engram layers, so it needs `input_ids` even " + "when `inputs_embeds` is passed." + ) + if use_cache and cache is None: + cache = DynamicCache(config=self.config) + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + batch_size, seq_len, _ = inputs_embeds.shape + past_seen = cache.get_seq_length() if cache is not None else 0 + if position_ids is None: + position_ids = torch.arange(seq_len, device=inputs_embeds.device) + past_seen + position_ids = position_ids.unsqueeze(0) + + # First, the padding. Attention only needs to mask it, but the n-gram hashes and the pooling groups are + # made of consecutive real tokens, so they need to know which tokens of this call are real, and how + # many real tokens each row had seen before it. As everywhere else, the mask of a call that continues + # from a cache covers the cached tokens too. + is_real_token = torch.ones((batch_size, seq_len), dtype=torch.bool, device=inputs_embeds.device) + num_seen_tokens = torch.full((batch_size,), past_seen, device=inputs_embeds.device) + if isinstance(attention_mask, torch.Tensor) and attention_mask.ndim == 2: + padding_mask = create_recurrent_attention_mask(self.config, inputs_embeds, attention_mask, cache) + if padding_mask is not None: + is_real_token = padding_mask.bool() + if attention_mask.shape[1] == past_seen + seq_len: + num_seen_tokens = attention_mask[:, :past_seen].bool().sum(dim=-1) + + # Next, the n-gram hashes of all the Engram layers. A padded token must not end up in the n-grams of + # the tokens after it, and neither must an image token. + engram_hash_ids, engram_mask = None, None + if self.engram_hasher is not None: + hash_mask = is_real_token + if image_mask is not None: + engram_mask = ~image_mask + hash_mask = hash_mask & engram_mask + engram_hash_ids = self.engram_hasher(input_ids, hash_mask, cache.layers[0] if cache is not None else None) + + # `generate()` may pass a per-layer-type mask dict already built by `create_masks_for_generate`. All + # layers use the same sliding-window mask, so we use the prebuilt one directly. + if isinstance(attention_mask, dict): + causal_mask = next(iter(attention_mask.values())) + else: + causal_mask = create_sliding_window_causal_mask( + config=self.config, + inputs_embeds=inputs_embeds, + attention_mask=attention_mask, + cache=cache, + position_ids=position_ids, + allow_is_causal_skip=False, + ) + + hidden_states = inputs_embeds.unsqueeze(2).expand(-1, -1, self.config.hc_mult, -1).contiguous() + # The first attention reads the first stream as it is + pre = torch.zeros((batch_size, seq_len, self.config.hc_mult), device=hidden_states.device) + pre[..., 0] = 1.0 + position_embeddings = { + "main": self.rotary_emb(inputs_embeds, position_ids=position_ids, layer_type="main"), + "compress": self.rotary_emb(inputs_embeds, position_ids=position_ids, layer_type="compress"), + } + # The compressed entries get RoPE as well. An entry stands for the first token of its group, so it + # rotates at the position of that token. It only comes to exist with the last token of the group + # though, and by then the first one may be a call behind us. So we go back from the last token: for + # each token, this is the RoPE of the entry that it completes if it is the last one of a group of + # `ratio`, and the compressor keeps the ones of the tokens that are. + compressed_position_embeddings = {} + for ratio, layer_type in zip(self.config.compress_ratios, self.config.attention_layer_types): + if layer_type == "compressed_attention" and ratio not in compressed_position_embeddings: + compressed_position_embeddings[ratio] = self.rotary_emb( + inputs_embeds, position_ids=position_ids - (ratio - 1), layer_type="compress" + ) + # What the attention layers hand down the stack instead of recomputing: the compressed KV, the index + # keys, the selection and the candidate blocks. Each layer returns them with its own on top, so every + # source has published before the layers after it read. + shared_states = {} + + for layer_idx, layer in enumerate(self.layers): + hidden_states, pre, shared_states = layer( + hidden_states, + pre, + engram_hash_ids=( + engram_hash_ids[:, :, self.config.engram_layer_ids.index(layer_idx)] + if layer_idx in self.config.engram_layer_ids + else None + ), + engram_mask=engram_mask, + image_mask=image_mask, + position_embeddings=position_embeddings, + compressed_position_embeddings=compressed_position_embeddings, + is_real_token=is_real_token, + num_seen_tokens=num_seen_tokens, + attention_mask=causal_mask, + cache=cache, + shared_states=shared_states, + **kwargs, + ) + + # There is no hyper-connection head: the "pre" of the last MLP collapses the streams for the final norm + hidden_states = (pre.unsqueeze(-1) * hidden_states.float()).sum(dim=2).to(hidden_states.dtype) + hidden_states = self.norm(hidden_states) + return MoeModelOutputWithPast(last_hidden_state=hidden_states, cache=cache) + + +@auto_docstring( + custom_intro=""" + The DeepSeek-V4.1 model, which consists of a vision encoder and a language model, without a language modeling + head. + """ +) +class DeepseekV41Model(DeepseekV41PreTrainedModel): + def __init__(self, config: DeepseekV41Config): + super().__init__(config) + self.vision_tower = DeepseekV41VisionModel(config.vision_config) + self.multi_modal_projector = DeepseekV41MultiModalProjector(config) + self.language_model = DeepseekV41TextModel(config.text_config) + # Learned embeddings for the delimiters of an image: its start, its end, and the end of each row + self.image_start = nn.Parameter(torch.empty(config.text_config.hidden_size)) + self.image_end = nn.Parameter(torch.empty(config.text_config.hidden_size)) + self.image_newline = nn.Parameter(torch.empty(config.text_config.hidden_size)) + self.post_init() + + def get_input_embeddings(self): + return self.language_model.embed_tokens + + def set_input_embeddings(self, value): + self.language_model.embed_tokens = value + + @can_return_tuple + @auto_docstring( + custom_intro=""" + Encodes the images and lays each one out as the language model reads it: a start embedding, then the rows + of image tokens with a newline embedding after each row, then an end embedding. The `pooler_output` has + one entry per image, of shape `(num_image_positions, hidden_size)`. + """ + ) + def get_image_features( + self, pixel_values: torch.Tensor, image_grid_thw: torch.LongTensor, **kwargs: Unpack[TransformersKwargs] + ) -> tuple | BaseModelOutputWithPooling: + r""" + pixel_values (`torch.Tensor` of shape `(total_patches, num_channels * patch_size * patch_size)`): + The flattened patches of all the images, one image after the other. + image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`): + The temporal size, height and width of each image's patch grid. The temporal size is always 1. + """ + grids = image_grid_thw.tolist() + # An image is a single frame. The temporal size is only there so that the input has the same layout as + # the `image_grid_thw` of the models that take videos as well. + if any(num_frames != 1 for num_frames, _, _ in grids): + raise ValueError( + "DeepSeek-V4.1 only takes images, so the temporal size of every grid must be 1.\n" + f"`image_grid_thw`: {grids}" + ) + patches_per_image = pixel_values.split([height * width for _, height, width in grids]) + vision_outputs, image_features = [], [] + for patches, (_, height, width) in zip(patches_per_image, grids): + outputs = self.vision_tower(patches, height, width, return_dict=True, **kwargs) + tokens = self.multi_modal_projector(outputs.last_hidden_state, height, width) + # The projector rounds a partial square up, so the token grid is the patch grid divided by the ratio + num_rows = -(-height // self.multi_modal_projector.downsample_ratio) + rows = tokens.view(num_rows, -1, tokens.shape[-1]) + newlines = self.image_newline.to(tokens.dtype).expand(num_rows, 1, -1) + rows = torch.cat([rows, newlines], dim=1).flatten(0, 1) + image_start, image_end = self.image_start.to(tokens.dtype)[None], self.image_end.to(tokens.dtype)[None] + image_features.append(torch.cat([image_start, rows, image_end])) + vision_outputs.append(outputs) + + # The vision encoder ran one image at a time, so we put its outputs back in the layout of `pixel_values`: + # the patches of all the images, one image after the other + hidden_states, attentions = None, None + if vision_outputs[0].hidden_states is not None: + # `output_hidden_states` can select layers, which leaves the other ones as None + per_layer = zip(*(outputs.hidden_states for outputs in vision_outputs)) + hidden_states = tuple(torch.cat(layer) if layer[0] is not None else None for layer in per_layer) + if vision_outputs[0].attentions is not None: + # A patch only attends to its own image, so the weights of a layer are one block per image + per_layer = zip(*(outputs.attentions for outputs in vision_outputs)) + attentions = tuple(torch.stack([torch.block_diag(*head) for head in zip(*layer)]) for layer in per_layer) + return BaseModelOutputWithPooling( + last_hidden_state=torch.cat([outputs.last_hidden_state for outputs in vision_outputs]), + pooler_output=tuple(image_features), + hidden_states=hidden_states, + attentions=attentions, + ) + + @can_return_tuple + @auto_docstring + @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") + def forward( + self, + input_ids: torch.LongTensor | None = None, + pixel_values: torch.Tensor | None = None, + image_grid_thw: torch.LongTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + cache: Cache | None = None, + inputs_embeds: torch.Tensor | None = None, + use_cache: bool | None = None, + mm_encoder_outputs: dict[str, BaseModelOutputWithPooling] | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> MultimodalMoeBaseModelOutputWithPast: + r""" + pixel_values (`torch.Tensor` of shape `(total_patches, num_channels * patch_size * patch_size)`, *optional*): + The flattened patches of all the images in the batch, one image after the other. + image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): + The temporal size, height and width of each image's patch grid. The temporal size is always 1. + """ + if input_ids is None and inputs_embeds is None: + raise ValueError("You must specify at least one of input_ids or inputs_embeds") + if inputs_embeds is None: + inputs_embeds = self.get_input_embeddings()(input_ids) + + # The images come in either as `pixel_values`, which we encode here, or already encoded. `generate` does + # the latter: it encodes them once before the first step, so that it can repeat whole images for beam + # search. Repeating the rows of `pixel_values` would repeat patches instead. + mm_encoder_outputs = mm_encoder_outputs if mm_encoder_outputs is not None else {} + if pixel_values is not None: + if mm_encoder_outputs.get("image") is not None: + raise ValueError( + "Got both `pixel_values` and images that are already encoded in `mm_encoder_outputs`. " + "Pass only one of the two." + ) + mm_encoder_outputs["image"] = self.get_image_features(pixel_values, image_grid_thw, return_dict=True) + + # Every position of an image carries `image_token_id`, the delimiters included + image_mask = input_ids == self.config.image_token_id if input_ids is not None else None + if mm_encoder_outputs.get("image") is not None: + if image_mask is None: + raise ValueError("`input_ids` are needed to find where the images go in the prompt.") + features_per_image = mm_encoder_outputs["image"].pooler_output + image_features = torch.cat(features_per_image).to(inputs_embeds.device, inputs_embeds.dtype) + num_image_tokens = image_mask.sum() + torch_compilable_check( + num_image_tokens == image_features.shape[0], + lambda: ( + f"The prompt has {int(num_image_tokens)} image tokens, but the images take up " + f"{image_features.shape[0]} tokens (per image: {[len(features) for features in features_per_image]})." + ), + ) + inputs_embeds = inputs_embeds.masked_scatter(image_mask.unsqueeze(-1), image_features) + + outputs = self.language_model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + cache=cache, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + image_mask=image_mask, + **kwargs, + ) + return MultimodalMoeBaseModelOutputWithPast(**outputs, image_outputs=mm_encoder_outputs.get("image")) + + +@auto_docstring( + custom_intro=""" + The DeepSeek-V4.1 model with a language modeling head on top. It takes text, optionally interleaved with + images. + """ +) +class DeepseekV41ForCausalLM(DeepseekV41PreTrainedModel, GenerationMixin): + def __init__(self, config: DeepseekV41Config): + super().__init__(config) + self.model = DeepseekV41Model(config) + self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False) + self.post_init() + + def get_input_embeddings(self): + return self.model.get_input_embeddings() + + def set_input_embeddings(self, value): + self.model.set_input_embeddings(value) + + def get_output_embeddings(self) -> nn.Module: + return self.lm_head + + @can_return_tuple + @auto_docstring + @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") + def forward( + self, + input_ids: torch.LongTensor | None = None, + pixel_values: torch.Tensor | None = None, + image_grid_thw: torch.LongTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + cache: Cache | None = None, + inputs_embeds: torch.Tensor | None = None, + labels: torch.LongTensor | None = None, + use_cache: bool | None = None, + logits_to_keep: int | torch.Tensor = 0, + mm_encoder_outputs: dict[str, BaseModelOutputWithPooling] | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> MultimodalMoeCausalLMOutputWithPast: + r""" + pixel_values (`torch.Tensor` of shape `(total_patches, num_channels * patch_size * patch_size)`, *optional*): + The flattened patches of all the images in the batch, one image after the other. + image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): + The temporal size, height and width of each image's patch grid. The temporal size is always 1. + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + """ + outputs: MultimodalMoeBaseModelOutputWithPast = self.model( + input_ids=input_ids, + pixel_values=pixel_values, + image_grid_thw=image_grid_thw, + attention_mask=attention_mask, + position_ids=position_ids, + cache=cache, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + mm_encoder_outputs=mm_encoder_outputs, + **kwargs, + ) + hidden_states = outputs.last_hidden_state + # Only compute the necessary logits + slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep + logits = self.lm_head(hidden_states[:, slice_indices, :]) + + loss = None + if labels is not None: + loss = self.loss_function(logits, labels, self.config.text_config.vocab_size, **kwargs) + + return MultimodalMoeCausalLMOutputWithPast( + loss=loss, + logits=logits, + cache=outputs.cache, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + router_logits=outputs.router_logits, + image_outputs=outputs.image_outputs, + ) + + +def get_resized_image_size( + height: int, + width: int, + patch_size: int, + downsample_ratio: int, + max_image_tokens: int, + min_pixels: int, + max_wh_ratio: float | None = None, +) -> tuple[int, int]: + """ + Works out the size that an image is resized to before it is cut into patches. Both sides come out as a + multiple of `patch_size`, small images are scaled up to about `min_pixels`, and large ones are scaled down + until they fit in `max_image_tokens`. + + The model merges every `downsample_ratio x downsample_ratio` square of patches into one token. An image + with `rows x columns` of those takes `rows * (columns + 1) + 2` positions in the prompt: a newline after + each row, plus a start and an end delimiter. + + Args: + height (`int`): + Height of the image. + width (`int`): + Width of the image. + patch_size (`int`): + Side of the square patches that the vision encoder embeds. + downsample_ratio (`int`): + Side of the square of patches that the model merges into one token. + max_image_tokens (`int`): + The most positions the image may take in the prompt, delimiters included. + min_pixels (`int`): + Images with fewer pixels are scaled up to this area. + max_wh_ratio (`float`, *optional*): + Images wider than this width-to-height ratio are planned as if they had exactly this ratio. + + Returns: + `tuple[int, int]`: The height and width to resize the image to. + + Example: + + ```python + >>> from transformers.models.deepseek_v41.image_processing_deepseek_v41 import get_resized_image_size + + >>> limits = {"patch_size": 14, "downsample_ratio": 3, "max_image_tokens": 1024, "min_pixels": 295936} + >>> get_resized_image_size(701, 1024, **limits) + (714, 1036) + >>> # A small image is scaled up + >>> get_resized_image_size(200, 320, **limits) + (434, 700) + >>> # ... and one that would take more than 1024 positions is scaled down + >>> get_resized_image_size(2000, 3000, **limits) + (1050, 1568) + + ``` + """ + # First, an image that is too wide is planned at the widest ratio allowed. It is squashed to that ratio + # afterwards, not cropped. + if max_wh_ratio is not None and width > height * max_wh_ratio: + width = height * max_wh_ratio + # Next, a small image is scaled up to `min_pixels`. The sides are truncated, so it can end up just below. + if 0 < width * height < min_pixels: + scale = (min_pixels / (width * height)) ** 0.5 + width, height = int(width * scale), int(height * scale) + # Both sides are rounded up to whole patches, and a partial square of patches still makes a token + resized_height = math.ceil(height / patch_size) * patch_size + resized_width = math.ceil(width / patch_size) * patch_size + rows = math.ceil(resized_height // patch_size / downsample_ratio) + columns = math.ceil(resized_width // patch_size / downsample_ratio) + if rows * (columns + 1) + 2 <= max_image_tokens: + return resized_height, resized_width + + # Finally, an image that takes too many positions is scaled down. With `rows = aspect * columns`, the + # budget `rows * (columns + 1) + 2 <= max_image_tokens` is a quadratic in `columns`, and this is its + # positive root. + aspect = height / width + max_columns = math.sqrt((max_image_tokens - 2) / aspect + 0.25) - 0.5 + max_rows = max_columns * aspect + token_size = patch_size * downsample_ratio + if max_columns < 1.0: + # Too tall for one full column at its own aspect ratio, so it becomes a single column of tokens + return (max_image_tokens - 2) // 2 * token_size, token_size + if max_rows < 1.0: + # Too wide for one full row, so it becomes a single row of tokens + return token_size, (max_image_tokens - 3) * token_size + # Otherwise it is scaled to fit the largest whole grid of tokens, and keeps the whole patches that it covers + scale = min(math.floor(max_columns) * token_size / width, math.floor(max_rows) * token_size / height) + return math.floor(height * scale / patch_size) * patch_size, math.floor(width * scale / patch_size) * patch_size + + +class DeepseekV41ImageProcessorKwargs(ImagesKwargs, total=False): + r""" + patch_size (`int`, *optional*, defaults to 14): + Side of the square patches that the vision encoder embeds. + downsample_ratio (`int`, *optional*, defaults to 3): + Side of the square of patches that the model merges into one token. + max_image_tokens (`int`, *optional*, defaults to 1024): + The most positions an image may take in the prompt, delimiters included. Larger images are scaled down. + min_pixels (`int`, *optional*, defaults to 295936): + Images with fewer pixels are scaled up to this area. + max_wh_ratio (`float`, *optional*): + Images wider than this width-to-height ratio are squashed to it. The released checkpoints set no limit. + """ + + patch_size: int + downsample_ratio: int + max_image_tokens: int + min_pixels: int + max_wh_ratio: float | None + + +@auto_docstring( + custom_intro=""" + Constructs a DeepSeek-V4.1 image processor. Each image keeps its own resolution and aspect ratio: it is + resized to a whole number of patches, padded with gray where needed, and cut into flattened patches. + """ +) +class DeepseekV41ImageProcessor(TorchvisionBackend): + do_convert_rgb = True + do_resize = True + resample = PILImageResampling.BICUBIC + do_rescale = True + do_normalize = True + image_mean = [0.5, 0.5, 0.5] + image_std = [0.5, 0.5, 0.5] + patch_size = 14 + downsample_ratio = 3 + max_image_tokens = 1024 + min_pixels = 295936 + max_wh_ratio = None + valid_kwargs = DeepseekV41ImageProcessorKwargs + model_input_names = ["pixel_values", "image_grid_thw"] + + def __init__(self, **kwargs: Unpack[DeepseekV41ImageProcessorKwargs]): + super().__init__(**kwargs) + + @auto_docstring + def preprocess(self, images: ImageInput, **kwargs: Unpack[DeepseekV41ImageProcessorKwargs]) -> BatchFeature: + return super().preprocess(images, **kwargs) + + def _validate_preprocess_kwargs(self, **kwargs): + # The output size comes from `min_pixels` and `max_image_tokens`, so there is no `size` for the base + # class to check + kwargs.pop("do_resize", None) + super()._validate_preprocess_kwargs(**kwargs) + + def process_image( + self, + image: ImageInput, + do_convert_rgb: bool | None = None, + input_data_format: str | ChannelDimension | None = None, + device: "torch.device | None" = None, + **kwargs: Unpack[ImagesKwargs], + ) -> "torch.Tensor": + # The original preprocessing converts with a plain `convert("RGB")`, which drops an alpha channel. The + # base class would composite it onto a white background instead. + if do_convert_rgb and get_image_type(image) == ImageType.PIL: + image = tvF.pil_to_tensor(image.convert("RGB")) + input_data_format = ChannelDimension.FIRST + return super().process_image( + image, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device, **kwargs + ) + + def resize_and_pad( + self, + image: "torch.Tensor", + size: SizeDict, + resample: "PILImageResampling | tvF.InterpolationMode | int | None", + fill_value: int = 127, + ) -> "torch.Tensor": + """ + Resizes an image to fit inside `size` without changing its aspect ratio, and centers it on a canvas of + that size. This is what `PIL.ImageOps.pad` does, which the original preprocessing uses with a gray + canvas. + + Args: + image (`torch.Tensor` of shape `(num_channels, height, width)`): + The image to resize. + size (`SizeDict`): + The height and width of the canvas. + resample (`PILImageResampling` or `InterpolationMode`): + The filter to resize with. + fill_value (`int`, *optional*, defaults to 127): + The value of the canvas around the image, on the 0-255 scale. + + Returns: + `torch.Tensor` of shape `(num_channels, size.height, size.width)`: The image on its canvas. + """ + height, width = image.shape[-2:] + content_height, content_width = size.height, size.width + if width / height > size.width / size.height: + # Relatively wider than the canvas: it fills the width, with a bar above and below + content_height = round(height / width * size.width) + elif width / height < size.width / size.height: + # Relatively taller than the canvas: it fills the height, with a bar on the left and right + content_width = round(width / height * size.height) + image = self.resize(image, SizeDict(height=content_height, width=content_width), resample) + if (content_height, content_width) == (size.height, size.width): + return image + + canvas = image.new_full((*image.shape[:-2], size.height, size.width), fill_value) + top = round((size.height - content_height) * 0.5) + left = round((size.width - content_width) * 0.5) + canvas[..., top : top + content_height, left : left + content_width] = image + return canvas + + def _preprocess( + self, + images: list["torch.Tensor"], + do_resize: bool, + resample: "PILImageResampling | tvF.InterpolationMode | int | None", + do_rescale: bool, + rescale_factor: float, + do_normalize: bool, + image_mean: float | list[float] | None, + image_std: float | list[float] | None, + patch_size: int, + downsample_ratio: int, + max_image_tokens: int, + min_pixels: int, + max_wh_ratio: float | None, + return_tensors: str | TensorType | None, + **kwargs, + ) -> BatchFeature: + patches, image_grid_thw = [], [] + for image in images: + channels, height, width = image.shape + if do_resize: + resized_height, resized_width = get_resized_image_size( + height, width, patch_size, downsample_ratio, max_image_tokens, min_pixels, max_wh_ratio + ) + size = SizeDict(height=resized_height, width=resized_width) + if max_wh_ratio is not None and width >= max_wh_ratio * height: + # Too wide: squashed to the size that was planned at the widest ratio allowed + image = self.resize(image, size, resample) + else: + # Everything else keeps its aspect ratio, with gray bars to fill up the last patches + image = self.resize_and_pad(image, size, resample) + height, width = resized_height, resized_width + if height % patch_size != 0 or width % patch_size != 0: + raise ValueError( + "With `do_resize=False`, the height and width of an image must be multiples of the patch " + f"size.\nImage size: {(height, width)}\nPatch size: {patch_size}" + ) + image = self.rescale_and_normalize(image, do_rescale, rescale_factor, do_normalize, image_mean, image_std) + # One row per patch in reading order, each flattened as (channels, patch height, patch width) + rows, columns = height // patch_size, width // patch_size + image = image.reshape(channels, rows, patch_size, columns, patch_size).permute(1, 3, 0, 2, 4) + patches.append(image.reshape(rows * columns, -1)) + # The grid has a temporal size as well, like in the models that take videos. An image is one frame. + image_grid_thw.append([1, rows, columns]) + return BatchFeature( + data={"pixel_values": torch.cat(patches), "image_grid_thw": torch.tensor(image_grid_thw)}, + tensor_type=return_tensors, + ) + + +@auto_docstring +class DeepseekV41Processor(ProcessorMixin): + def __init__(self, image_processor=None, tokenizer=None, chat_template=None, image_token="<|deepseek_image|>"): + r""" + image_token (`str`, *optional*, defaults to `"<|deepseek_image|>"`): + The placeholder for an image in the prompt. The processor repeats it once for every position that + the image takes up. + """ + self.image_token = tokenizer.image_token if hasattr(tokenizer, "image_token") else image_token + self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token) + super().__init__(image_processor, tokenizer, chat_template=chat_template) + + def replace_image_token(self, image_inputs: dict, image_idx: int, **kwargs) -> str: + # The model merges every `downsample_ratio x downsample_ratio` square of patches into a token, and a + # partial square at the edge still makes one + downsample_ratio = kwargs.get("downsample_ratio") or self.image_processor.downsample_ratio + _, height, width = (int(size) for size in image_inputs["image_grid_thw"][image_idx]) + rows, columns = math.ceil(height / downsample_ratio), math.ceil(width / downsample_ratio) + # Every position of the image carries the image token: its start, each row with a newline after it, + # and its end. The model tells them apart by where they are in that layout. + return self.image_token * (rows * (columns + 1) + 2) + + +__all__ = [ + "DeepseekV41Config", + "DeepseekV41TextConfig", + "DeepseekV41VisionConfig", + "DeepseekV41PreTrainedModel", + "DeepseekV41VisionModel", + "DeepseekV41TextModel", + "DeepseekV41Model", + "DeepseekV41ForCausalLM", + "DeepseekV41ImageProcessor", + "DeepseekV41Processor", +] diff --git a/src/transformers/models/deepseek_v41/processing_deepseek_v41.py b/src/transformers/models/deepseek_v41/processing_deepseek_v41.py new file mode 100644 index 000000000000..e3b63d1d2108 --- /dev/null +++ b/src/transformers/models/deepseek_v41/processing_deepseek_v41.py @@ -0,0 +1,49 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/deepseek_v41/modular_deepseek_v41.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_deepseek_v41.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# Copyright 2026 The HuggingFace Inc. 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. +import math + +from ...processing_utils import ProcessorMixin +from ...utils import auto_docstring + + +@auto_docstring +class DeepseekV41Processor(ProcessorMixin): + def __init__(self, image_processor=None, tokenizer=None, chat_template=None, image_token="<|deepseek_image|>"): + r""" + image_token (`str`, *optional*, defaults to `"<|deepseek_image|>"`): + The placeholder for an image in the prompt. The processor repeats it once for every position that + the image takes up. + """ + self.image_token = tokenizer.image_token if hasattr(tokenizer, "image_token") else image_token + self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token) + super().__init__(image_processor, tokenizer, chat_template=chat_template) + + def replace_image_token(self, image_inputs: dict, image_idx: int, **kwargs) -> str: + # The model merges every `downsample_ratio x downsample_ratio` square of patches into a token, and a + # partial square at the edge still makes one + downsample_ratio = kwargs.get("downsample_ratio") or self.image_processor.downsample_ratio + _, height, width = (int(size) for size in image_inputs["image_grid_thw"][image_idx]) + rows, columns = math.ceil(height / downsample_ratio), math.ceil(width / downsample_ratio) + # Every position of the image carries the image token: its start, each row with a newline after it, + # and its end. The model tells them apart by where they are in that layout. + return self.image_token * (rows * (columns + 1) + 2) + + +__all__ = ["DeepseekV41Processor"] diff --git a/src/transformers/quantizers/quantizer_finegrained_fp8.py b/src/transformers/quantizers/quantizer_finegrained_fp8.py index 08566cabb7c7..5b4843196578 100644 --- a/src/transformers/quantizers/quantizer_finegrained_fp8.py +++ b/src/transformers/quantizers/quantizer_finegrained_fp8.py @@ -124,7 +124,13 @@ def _process_model_before_weight_loading( modules_to_convert = self.quantization_config.modules_to_convert if self.pre_quantized and modules_to_convert: - replace_with_fp8_embedding(model, modules_to_convert, self.modules_to_not_convert) + replace_with_fp8_embedding( + model, + modules_to_convert, + self.modules_to_not_convert, + block_size=self.quantization_config.embedding_block_size, + scale_fmt=self.quantization_config.scale_fmt, + ) model = replace_with_fp8_linear( model, diff --git a/src/transformers/utils/quantization_config.py b/src/transformers/utils/quantization_config.py index e8e399738ad4..7e06fe24894a 100644 --- a/src/transformers/utils/quantization_config.py +++ b/src/transformers/utils/quantization_config.py @@ -1699,6 +1699,9 @@ class FineGrainedFP8Config(QuantizationConfigMixin): `"ue8m0"` (1-byte `torch.float8_e8m0fnu`, V4-style). expert_dtype (`str`, *optional*, defaults to `"fp8"`): Format of the MoE experts' weights: `"fp8"`, or `"fp4"` for DeepSeek-V4's FP4-packed experts. + embedding_block_size (`int`, *optional*): + How many consecutive values in a row of the `modules_to_convert` tables share a scale, as in + DeepSeek-V4.1's Engram tables. A table has a single scale by default. """ def __init__( @@ -1710,6 +1713,7 @@ def __init__( modules_to_convert: list | None = None, scale_fmt: str = "float", expert_dtype: str = "fp8", + embedding_block_size: int | None = None, **kwargs, ): self.quant_method = kwargs.pop("quant_method", QuantizationMethod.FP8) @@ -1719,6 +1723,8 @@ def __init__( self.modules_to_not_convert = modules_to_not_convert # TODO: check overlap with not to convert self.modules_to_convert = modules_to_convert + # TODO: after #50245, a table can have its own plan entry, and this becomes its `weight_block_size` + self.embedding_block_size = embedding_block_size self.activation_scheme = activation_scheme self.weight_block_size = weight_block_size self.dequantize = dequantize @@ -1741,6 +1747,8 @@ def post_init(self): raise ValueError(f"scale_fmt must be 'float' or 'ue8m0'; got {self.scale_fmt!r}") if self.expert_dtype not in ("fp8", "fp4"): raise ValueError(f"expert_dtype must be 'fp8' or 'fp4'; got {self.expert_dtype!r}") + if self.embedding_block_size is not None and self.embedding_block_size <= 0: + raise ValueError(f"embedding_block_size must be a positive integer; got {self.embedding_block_size!r}") def get_loading_attributes(self): return {"dequantize": self.dequantize, "modules_to_not_convert": self.modules_to_not_convert} diff --git a/tests/generation/test_utils.py b/tests/generation/test_utils.py index cc11caa0d0fb..624fb6e63b9d 100644 --- a/tests/generation/test_utils.py +++ b/tests/generation/test_utils.py @@ -976,7 +976,11 @@ def test_prompt_lookup_decoding_stops_at_eos(self): @pytest.mark.generate def test_left_padding_compatibility( - self, unpadded_custom_inputs: dict | None = None, padded_custom_inputs: dict | None = None + self, + unpadded_custom_inputs: dict | None = None, + padded_custom_inputs: dict | None = None, + atol: float = 1e-5, + rtol: float = 1e-5, ): """ Tests that adding left-padding yields the same logits as the original input. Exposes arguments for custom @@ -993,6 +997,11 @@ def test_left_padding_compatibility( padded_custom_inputs (`dict`, *optional*): Used in test overwrites. Custom inputs to add/overwrite over the padded test input handcrafted in this test. Commonly used e.g. with multimodal cross attention masks. + atol (`float`, *optional*, defaults to 1e-5): + Used in test overwrites. Absolute tolerance on the logits, for models that round their activations + and so differ by more than float noise. + rtol (`float`, *optional*, defaults to 1e-5): + Used in test overwrites. Relative tolerance on the logits. """ # First, filter out models that don't support left padding @@ -1092,7 +1101,7 @@ def _prepare_model_kwargs(model_inputs, signature): next_logits_with_padding = model(**model_kwargs_with_padding).logits[:, -1, :] # They should result in very similar logits - torch.testing.assert_close(next_logits_wo_padding, next_logits_with_padding, rtol=1e-5, atol=1e-5) + torch.testing.assert_close(next_logits_wo_padding, next_logits_with_padding, rtol=rtol, atol=atol) @pytest.mark.generate def test_cache_format(self): diff --git a/tests/models/deepseek_v41/__init__.py b/tests/models/deepseek_v41/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/models/deepseek_v41/test_image_processing_deepseek_v41.py b/tests/models/deepseek_v41/test_image_processing_deepseek_v41.py new file mode 100644 index 000000000000..037355d093a0 --- /dev/null +++ b/tests/models/deepseek_v41/test_image_processing_deepseek_v41.py @@ -0,0 +1,165 @@ +# Copyright 2026 The HuggingFace Inc. 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. +import unittest + +import numpy as np + +from transformers.testing_utils import require_torch, require_torchvision, require_vision +from transformers.utils import is_torch_available, is_torchvision_available, is_vision_available + +from ...test_image_processing_common import ImageProcessingTester, ImageProcessingTestMixin + + +if is_torch_available(): + import torch + +if is_vision_available(): + from PIL import Image, ImageOps + +if is_torchvision_available(): + from transformers.models.deepseek_v41.image_processing_deepseek_v41 import get_resized_image_size + + +# Small enough that a test image is a handful of patches: 2 x 2 patches, merged 3 x 3 into a token +TINY_LIMITS = {"patch_size": 2, "downsample_ratio": 3, "max_image_tokens": 40, "min_pixels": 64} + + +class DeepseekV41ImageProcessingTester(ImageProcessingTester): + def __init__(self, parent, **kwargs): + # An image no larger than a patch is rounded up to exactly one patch, so `pixel_values` has one row per + # image and the common tests know what shape to expect + kwargs.setdefault("min_resolution", 8) + kwargs.setdefault("max_resolution", 32) + kwargs.setdefault("patch_size", 32) + kwargs.setdefault("downsample_ratio", 1) + kwargs.setdefault("max_image_tokens", 64) + kwargs.setdefault("min_pixels", 0) + super().__init__(parent, **kwargs) + + def expected_output_image_shape(self, images): + return (self.num_channels * self.patch_size**2,) + + +@require_torch +@require_vision +@require_torchvision +class DeepseekV41ImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): + image_processor_tester_class = DeepseekV41ImageProcessingTester + + def _assert_has_attributes(self, processor, expected_attributes): + # The common check looks for `min_pixels` inside `size`, which is where the Qwen2-VL family keeps it. Here + # it is an attribute of its own, named like the field of the vision config. + expected_attributes = dict(expected_attributes) + if "min_pixels" in expected_attributes: + self.assertEqual(processor.min_pixels, expected_attributes.pop("min_pixels")) + super()._assert_has_attributes(processor, expected_attributes) + + def _get_image_processor(self, **kwargs): + image_processing_class = self.image_processing_classes["torchvision"] + return image_processing_class(**{**TINY_LIMITS, **kwargs}) + + def test_resized_image_size(self): + """The sizes that the original preprocessing plans, with the limits of the released checkpoint.""" + limits = {"patch_size": 14, "downsample_ratio": 3, "max_image_tokens": 1024, "min_pixels": 295936} + expected_sizes = { + # Only rounded up to whole patches + (701, 1024): (714, 1036), + # Scaled up to `min_pixels` first + (200, 320): (434, 700), + (1, 1): (546, 546), + (40, 4000): (56, 5446), + # Would take more than 1024 positions, so scaled down + (2000, 3000): (1050, 1568), + (2600, 500): (2604, 504), + # Too tall or too wide for a full column or row of tokens at their own aspect ratio + (100000, 100): (21462, 42), + (100, 200000): (42, 42882), + } + for (height, width), expected_size in expected_sizes.items(): + with self.subTest(height=height, width=width): + self.assertEqual(get_resized_image_size(height, width, **limits), expected_size) + # With a limit on the aspect ratio, a wider image is planned as if it had exactly that ratio + self.assertEqual(get_resized_image_size(300, 1500, **limits, max_wh_ratio=2), (392, 770)) + self.assertEqual(get_resized_image_size(300, 600, **limits, max_wh_ratio=2), (392, 770)) + + def test_patches_and_grid(self): + """Patches come out in reading order, each one flattened as (channels, patch height, patch width).""" + image_processor = self._get_image_processor() + # 12 x 18 is already whole patches and within the limits, so the pixels are not resampled + pixels = np.random.randint(0, 256, (12, 18, 3), dtype=np.uint8) + encoding = image_processor(Image.fromarray(pixels), return_tensors="pt") + + self.assertEqual(encoding.image_grid_thw.tolist(), [[1, 6, 9]]) + self.assertEqual(tuple(encoding.pixel_values.shape), (54, 3 * 2 * 2)) + normalized = torch.from_numpy(pixels).permute(2, 0, 1).float() / 127.5 - 1.0 + torch.testing.assert_close(encoding.pixel_values[0], normalized[:, :2, :2].flatten()) + # Patch 13 is in the second row of patches (9 per row), and the fifth column + torch.testing.assert_close(encoding.pixel_values[13], normalized[:, 2:4, 8:10].flatten()) + + def test_several_images(self): + """The patches of all the images are concatenated, and each image has its own row in the grid.""" + image_processor = self._get_image_processor() + images = [Image.new("RGB", (18, 12)), Image.new("RGB", (7, 5)), Image.new("RGB", (100, 100))] + encoding = image_processor(images, return_tensors="pt") + + self.assertEqual(encoding.image_grid_thw.tolist(), [[1, 6, 9], [1, 3, 5], [1, 15, 15]]) + self.assertEqual(encoding.pixel_values.shape[0], 6 * 9 + 3 * 5 + 15 * 15) + + def test_padding_matches_original_preprocessing(self): + """ + The original preprocessing resizes with `PIL.ImageOps.pad` onto a gray canvas. A single colour does not + change when it is resampled, so the outputs must be equal exactly: same size, same placement, same gray. + """ + image_processor = self._get_image_processor() + color, gray = (200, 50, 10), (127, 127, 127) + for height, width in [(5, 7), (7, 5), (4, 4), (9, 31), (31, 9), (30, 40), (60, 10), (100, 100)]: + with self.subTest(height=height, width=width): + image = Image.new("RGB", (width, height), color) + resized_height, resized_width = get_resized_image_size(height, width, **TINY_LIMITS) + expected = np.asarray(ImageOps.pad(image, (resized_width, resized_height), color=gray)) + expected = torch.from_numpy(expected).permute(2, 0, 1).float() / 127.5 - 1.0 + rows, columns = resized_height // 2, resized_width // 2 + expected = expected.reshape(3, rows, 2, columns, 2).permute(1, 3, 0, 2, 4).reshape(rows * columns, -1) + + encoding = image_processor(image, return_tensors="pt") + self.assertEqual(encoding.image_grid_thw.tolist(), [[1, rows, columns]]) + torch.testing.assert_close(encoding.pixel_values, expected) + + def test_transparency_is_dropped(self): + """Like the original preprocessing, the alpha channel is dropped rather than shown on a white background.""" + image_processor = self._get_image_processor() + # Fully transparent, so compositing would turn every pixel white + image = Image.new("RGBA", (18, 12), (200, 50, 10, 0)) + encoding = image_processor(image, return_tensors="pt") + + expected_color = torch.tensor([200, 50, 10]).float() / 127.5 - 1.0 + torch.testing.assert_close(encoding.pixel_values[0].view(3, 4), expected_color[:, None].expand(3, 4)) + + def test_max_wh_ratio(self): + """An image wider than `max_wh_ratio` is squashed to that ratio, with no gray bars.""" + image_processor = self._get_image_processor(max_wh_ratio=2) + image = Image.new("RGB", (60, 10), (200, 50, 10)) + encoding = image_processor(image, return_tensors="pt") + + self.assertEqual(encoding.image_grid_thw.tolist(), [[1, 5, 10]]) + expected_color = torch.tensor([200, 50, 10]).float() / 127.5 - 1.0 + expected = expected_color[:, None].expand(3, 4).flatten().expand(50, 12) + torch.testing.assert_close(encoding.pixel_values, expected) + + def test_do_resize_false_needs_whole_patches(self): + image_processor = self._get_image_processor() + encoding = image_processor(Image.new("RGB", (18, 12)), do_resize=False, return_tensors="pt") + self.assertEqual(encoding.image_grid_thw.tolist(), [[1, 6, 9]]) + with self.assertRaisesRegex(ValueError, "multiples of the patch size"): + image_processor(Image.new("RGB", (7, 5)), do_resize=False, return_tensors="pt") diff --git a/tests/models/deepseek_v41/test_modeling_deepseek_v41.py b/tests/models/deepseek_v41/test_modeling_deepseek_v41.py new file mode 100644 index 000000000000..4b14ad7f8fa2 --- /dev/null +++ b/tests/models/deepseek_v41/test_modeling_deepseek_v41.py @@ -0,0 +1,761 @@ +# Copyright 2026 The HuggingFace Inc. 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. +import copy +import json +import re +import tempfile +import unittest +from pathlib import Path + +from huggingface_hub.errors import StrictDataclassClassValidationError +from parameterized import parameterized + +from transformers import is_torch_available +from transformers.testing_utils import require_accelerate, require_torch, torch_device + + +if is_torch_available(): + import torch + from safetensors.torch import load_file, save_file + + from transformers import ( + DeepseekV41Config, + DeepseekV41ForCausalLM, + DeepseekV41Model, + DeepseekV41TextConfig, + FineGrainedFP8Config, + ) + from transformers.integrations import FP8Embedding, FP8Linear + from transformers.models.deepseek_v41.modeling_deepseek_v41 import ( + DeepseekV41Compressor, + DeepseekV41NgramHasher, + fake_quantize, + select_candidate_blocks, + ) + from transformers.quantizers.quantizer_finegrained_fp8 import FineGrainedFP8HfQuantizer + +from ...test_modeling_common import floats_tensor +from ...vlm_tester import VLMModelTest, VLMModelTester + + +# The quantization config of deepseek-ai/DeepSeek-V4.1-Flash, as it is on the Hub +CHECKPOINT_QUANTIZATION_CONFIG = { + "quant_method": "fp8", + "activation_scheme": "dynamic", + "weight_block_size": [32, 32], + "scale_fmt": "ue8m0", + "expert_dtype": "fp4", +} + +INPUTS_EMBEDS_SKIP_REASON = ( + "The Engram layers hash n-grams of token ids, so the model needs `input_ids` and cannot run on `inputs_embeds` " + "alone." +) + + +class DeepseekV41ModelTester(VLMModelTester): + if is_torch_available(): + base_model_class = DeepseekV41Model + config_class = DeepseekV41Config + conditional_generation_class = DeepseekV41ForCausalLM + + small_config_overrides = { + "batch_size": 3, + "seq_length": 11, + "vocab_size": 100, + # Ids 0 to 3 are the pad, BOS, EOS and DSpark noise tokens + "image_token_id": 4, + "hidden_size": 64, + "num_hidden_layers": 5, + "num_attention_heads": 4, + # All the attention heads share a single KV head + "num_key_value_heads": 1, + "hidden_act": "silu", + "moe_intermediate_size": 32, + "head_dim": 32, + # RoPE on 8 of the 32 head dims + "partial_rotary_factor": 0.25, + "q_lora_rank": 32, + "o_groups": 2, + "o_lora_rank": 16, + "n_routed_experts": 4, + "num_experts_per_tok": 2, + "max_position_embeddings": 64, + "sliding_window": 4, + # One layer of each kind: sliding only, compressing (2-to-1), sharing that KV, compressing again (1-to-1), + # then sharing the KV but indexing it on its own inside the candidate blocks of the layer before + "compress_ratios": [0, 2, 2, 1, 1], + "kv_source_layer_ids": [1, 3], + "index_source_layer_ids": [1, 3, 4], + "candidate_source_layer_id": 3, + "candidate_topk_blocks": 2, + "candidate_block_size": 2, + # Enough heads that two entries never get the exact same index score. With a couple of heads, the ReLU + # leaves many scores at exactly 0, and how top-k breaks those ties depends on the shape of its input. + "index_n_heads": 16, + "index_head_dim": 32, + "index_topk": 3, + "hc_mult": 2, + "hc_sinkhorn_iters": 3, + "engram_layer_ids": [0, 2], + "engram_max_ngram_size": 3, + "engram_vocab_size": 50, + "engram_n_heads": 2, + "engram_head_dim": 8, + "engram_pad_token_id": 2, + "engram_num_embeddings": None, + "num_nextn_predict_layers": 0, + "dspark_noise_token_id": 3, + "rms_norm_eps": 1e-6, + # The vision tower. The fields that it shares with the language model take a `vision_` prefix. + "vision_hidden_size": 32, + "vision_num_hidden_layers": 2, + "vision_intermediate_size": 48, + "patch_size": 2, + "downsample_ratio": 3, + # Every prompt starts with one image of 3 x 6 patches. They are merged 3 x 3 into 1 x 2 tokens, so with + # the newline of the row and the two delimiters, the image takes 1 + 1 * (2 + 1) + 1 positions. + "grid_height": 3, + "grid_width": 6, + "num_image_tokens": 5, + } + + @classmethod + def get_small_config_defaults(cls, **kwargs): + values = super().get_small_config_defaults(**kwargs) + # As large as the vocab, so that no tokens are merged and the model works without a tokenizer + values["engram_compressed_vocab_size"] = values["vocab_size"] + return values + + def create_pixel_values(self, batch_size: int | None = None): + # `pixel_values` has a row per patch rather than per image, with the images one after the other + batch_size = batch_size if batch_size is not None else self.batch_size + num_patches = batch_size * self.grid_height * self.grid_width + return floats_tensor([num_patches, self.num_channels * self.patch_size**2]) + + def get_additional_inputs(self, config, input_ids, modality_inputs, batch_size: int | None = None): + batch_size = batch_size if batch_size is not None else self.batch_size + grid = [1, self.grid_height, self.grid_width] + return {"image_grid_thw": torch.tensor([grid] * batch_size, device=torch_device)} + + def prepare_text_ids(self, batch_size, seq_length): + # Starts after the special tokens and the image token, so that none of them turn up in the text + low = max(self._special_token_ids) + 1 + return torch.randint(low, self.vocab_size, (batch_size, seq_length), device=torch_device) + + +@require_torch +class DeepseekV41ModelTest(VLMModelTest, unittest.TestCase): + model_tester_class = DeepseekV41ModelTester + + # The indexer parameters only influence which compressed entries are selected, which is not differentiable + test_all_params_have_gradient = False + # The Engram token map and n-gram tables are fixed to the vocabulary, so `resize_token_embeddings` raises + test_resize_embeddings = False + # Tolerance for our tests that compute the same logits in two ways. The model rounds its KV to FP8, so when + # float noise tips a value over a rounding boundary, the two ways differ by a rounding step instead of by + # the noise: up to 8e-3 on the logits over 300 random models, against 5e-7 without the rounding. + rounded_logits_tolerance = 1e-2 + + def is_pipeline_test_to_skip(self, *args, **kwargs): + return True + + def _image_features_get_expected_num_attentions(self, model_tester=None): + # The common version reads `num_hidden_layers` from the tester, which is the depth of the language model + return self.model_tester.vision_num_hidden_layers + + def _check_attentions_for_generate( + self, batch_size, attentions, prompt_length, output_length, config, decoder_cache + ): + # The layers that attend to compressed KV have those entries after the window on the KV axis, one per + # complete group of `compress_ratio` tokens. So the KV length differs between layers. + config = config.get_text_config() + self.assertIsInstance(attentions, tuple) + self.assertEqual(len(attentions), output_length - prompt_length) + for generated_length, iter_attentions in enumerate(attentions): + self.assertIsInstance(iter_attentions, tuple) + seq_length = prompt_length + generated_length + if decoder_cache is not None and generated_length > 0: + # Decoding one token from the cache, which only keeps the rest of the window + query_length = 1 + window_length = min(seq_length, config.sliding_window) + else: + # The whole sequence goes in, and the mask is what limits each query to its window + query_length = window_length = seq_length + expected_shapes = [ + ( + batch_size, + config.num_attention_heads, + query_length, + window_length + (seq_length // ratio if ratio else 0), + ) + for ratio in config.compress_ratios + ] + self.assertListEqual([layer_attention.shape for layer_attention in iter_attentions], expected_shapes) + + def _check_hidden_states_for_generate( + self, batch_size, hidden_states, prompt_length, output_length, config, use_cache=False + ): + # The residual is `hc_mult` parallel streams, which are only collapsed for the final norm. So every + # hidden state has an extra dim, except for the last one. + config = config.get_text_config() + self.assertIsInstance(hidden_states, tuple) + self.assertEqual(len(hidden_states), output_length - prompt_length) + for generated_length, iter_hidden_states in enumerate(hidden_states): + self.assertIsInstance(iter_hidden_states, tuple) + input_length = 1 if use_cache and generated_length > 0 else prompt_length + generated_length + streams_shape = (batch_size, input_length, config.hc_mult, config.hidden_size) + self.assertListEqual( + [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states], + [streams_shape] * config.num_hidden_layers + [(batch_size, input_length, config.hidden_size)], + ) + + def _check_cache_for_generate(self, batch_size, cache, seq_length, config): + # Every layer keeps the part of its window that the next token can still see, and there is a single + # KV head + config = config.get_text_config() + self.assertEqual(len(cache.layers), config.num_hidden_layers) + window_shape = (batch_size, 1, min(seq_length, config.sliding_window - 1), config.head_dim) + for layer, attention_type, ratio in zip(cache.layers, config.attention_layer_types, config.compress_ratios): + self.assertEqual(layer.keys.shape, window_shape) + self.assertEqual(layer.values.shape, window_shape) + if attention_type == "compressed_attention": + # Only the layer that compresses the KV stores it. The KV-sharing layers read it from there. + self.assertEqual(layer.compressed_kv.shape, (batch_size, seq_length // ratio, config.head_dim)) + else: + self.assertIsNone(layer.compressed_kv) + + def test_hidden_states_output(self): + # Same as the common test, but the hidden states are `hc_mult` parallel streams until the final norm + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + batch_size, seq_length = inputs_dict["input_ids"].shape + text_config = config.text_config + streams_shape = (batch_size, seq_length, text_config.hc_mult, text_config.hidden_size) + for model_class in self.all_model_classes: + model = model_class(config).to(torch_device).eval() + with torch.no_grad(): + hidden_states = model(**inputs_dict, output_hidden_states=True).hidden_states + self.assertListEqual( + [layer_hidden_states.shape for layer_hidden_states in hidden_states], + [streams_shape] * text_config.num_hidden_layers + [(batch_size, seq_length, text_config.hidden_size)], + ) + + def test_left_padding_compatibility(self): + # The common test allows 1e-5, which is a tolerance for float noise. With the activations rounded to FP8 + # and FP4, the noise now and then tips a value over a rounding boundary, and the logits move by a + # rounding step instead (2 of 200 random models on a GPU). + tolerance = self.rounded_logits_tolerance + super().test_left_padding_compatibility(atol=tolerance, rtol=tolerance) + + def test_reverse_loading_mapping(self): + # The checkpoint is flat and has the LM head, so the renames that nest it under `model.` only apply to + # the model with a head. The base model on its own is saved without that prefix. + super().test_reverse_loading_mapping(skip_base_model=True) + + @unittest.skip( + reason=( + "The attention of the language model has sinks and reads selected compressed KV, so it is eager only, " + "and the top-level model cannot switch to SDPA." + ) + ) + def test_can_set_attention_dynamically_composite_model(self): + pass + + @unittest.skip(reason=INPUTS_EMBEDS_SKIP_REASON) + def test_inputs_embeds(self): + pass + + @unittest.skip(reason=INPUTS_EMBEDS_SKIP_REASON) + def test_inputs_embeds_matches_input_ids(self): + pass + + @parameterized.expand([("greedy", 1), ("beam search", 2)]) + @unittest.skip(reason=INPUTS_EMBEDS_SKIP_REASON) + def test_generate_from_inputs_embeds(self, _, num_beams): + pass + + @unittest.skip(reason=INPUTS_EMBEDS_SKIP_REASON) + def test_generate_from_random_inputs_embeds(self): + pass + + def test_training_gradient_checkpointing_use_reentrant_true(self): + # Reentrant checkpointing only tracks the gradient of positional tensor arguments, so the compressed KV + # that the layers share would silently lose theirs. The model refuses it instead. + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + model = DeepseekV41ForCausalLM(config) + with self.assertRaisesRegex(ValueError, "use_reentrant=True"): + model.activation_checkpointing_enable(activation_checkpointing_kwargs={"use_reentrant": True}) + + def test_checkpointing_keeps_the_gradients(self): + """ + The KV-sharing layers read the compressed KV of an earlier layer, and checkpointing must not change the + gradient that flows back through it. The common tests only check which parameters get a gradient. + """ + config, model = self._get_model() + model.train() + input_ids = self.model_tester.prepare_text_ids(2, 23) + model(input_ids, labels=input_ids).loss.backward() + expected = {name: param.grad.clone() for name, param in model.named_parameters() if param.grad is not None} + self.assertTrue(any(".compressor." in name for name in expected)) + + model.zero_grad() + model.activation_checkpointing_enable() + model(input_ids, labels=input_ids).loss.backward() + for name, expected_grad in expected.items(): + torch.testing.assert_close(model.get_parameter(name).grad, expected_grad, msg=lambda msg: f"{name}: {msg}") + + def _get_model(self): + config = self.model_tester.get_config() + torch.manual_seed(0) + model = DeepseekV41ForCausalLM(config).to(torch_device).eval() + # The default init leaves the attention sinks and hyper-connection biases at zero, and we want them to matter + with torch.no_grad(): + for name, param in model.named_parameters(): + if name.endswith(("sinks", ".base", ".scale")): + param.normal_(mean=1.0 if name.endswith(".scale") else 0.0, std=0.3) + return config, model + + def test_cached_decoding_matches_full_forward(self): + """Decoding one token at a time with a cache gives the logits of a single forward over the whole sequence.""" + config, model = self._get_model() + input_ids = self.model_tester.prepare_text_ids(2, 19) + with torch.no_grad(): + expected = model(input_ids=input_ids, use_cache=False).logits + outputs = model(input_ids=input_ids[:, :7], use_cache=True) + logits = [outputs.logits] + for position in range(7, input_ids.shape[1]): + outputs = model(input_ids=input_ids[:, position : position + 1], cache=outputs.cache, use_cache=True) + logits.append(outputs.logits) + tolerance = self.rounded_logits_tolerance + torch.testing.assert_close(torch.cat(logits, dim=1), expected, atol=tolerance, rtol=tolerance) + + def test_chunked_prefill_matches_full_forward(self): + """The cache carries a pooling group that is still filling up across calls of any length.""" + config, model = self._get_model() + input_ids = self.model_tester.prepare_text_ids(2, 19) + with torch.no_grad(): + expected = model(input_ids=input_ids, use_cache=False).logits + outputs = model(input_ids=input_ids[:, :5], use_cache=True) + logits = [outputs.logits] + for start, end in ((5, 12), (12, 13), (13, 19)): + outputs = model(input_ids=input_ids[:, start:end], cache=outputs.cache, use_cache=True) + logits.append(outputs.logits) + tolerance = self.rounded_logits_tolerance + torch.testing.assert_close(torch.cat(logits, dim=1), expected, atol=tolerance, rtol=tolerance) + + def test_left_padding_matches_unpadded_with_cache(self): + """Each row of a left-padded batch gets the logits of that row on its own, with a cache as well.""" + config, model = self._get_model() + # 0, 3 and 5 tokens of padding. The pooling groups are counted from the first real token of a row, so + # the first two rows never complete a 2-token group on the same step. + rows = [self.model_tester.prepare_text_ids(1, length) for length in (19, 16, 14)] + input_ids = torch.full((3, 19), config.text_config.pad_token_id, device=torch_device) + attention_mask = torch.zeros((3, 19), dtype=torch.long, device=torch_device) + for row_idx, row in enumerate(rows): + input_ids[row_idx, -row.shape[1] :] = row[0] + attention_mask[row_idx, -row.shape[1] :] = 1 + # The positions that `generate` makes: each row counts from its own first real token + position_ids = (attention_mask.cumsum(-1) - 1).masked_fill(attention_mask == 0, 0) + + # The first chunk is nothing but padding for the last row, then comes a longer chunk, then single tokens + cache, logits = None, [] + with torch.no_grad(): + for start, end in ((0, 5), (5, 12), *((position, position + 1) for position in range(12, 19))): + outputs = model( + input_ids=input_ids[:, start:end], + attention_mask=attention_mask[:, :end], + position_ids=position_ids[:, start:end], + cache=cache, + use_cache=True, + ) + cache = outputs.cache + logits.append(outputs.logits) + logits = torch.cat(logits, dim=1) + tolerance = self.rounded_logits_tolerance + for row_idx, row in enumerate(rows): + expected = model(input_ids=row, use_cache=False).logits[0] + torch.testing.assert_close( + logits[row_idx, -row.shape[1] :], expected, atol=tolerance, rtol=tolerance, msg=f"Row {row_idx}" + ) + + def test_compressed_attention_is_used(self): + """Tokens outside the sliding window still reach the output, through the compressed KV.""" + config, model = self._get_model() + input_ids = self.model_tester.prepare_text_ids(1, 19) + changed = input_ids.clone() + # Far outside the window of the last position (4 tokens), and too old for the 2-token Engram look-back + changed[0, 2] = (changed[0, 2] + 1) % self.model_tester.vocab_size + with torch.no_grad(): + logits = model(input_ids=input_ids, use_cache=False).logits[0, -1] + changed_logits = model(input_ids=changed, use_cache=False).logits[0, -1] + self.assertGreater((logits - changed_logits).abs().max().item(), 1e-4) + + @require_accelerate + def test_compressor_with_offloaded_weights(self): + """Offloaded weights are only loaded while the module that owns them runs, and the pooling must cope.""" + from accelerate import cpu_offload + + config = self.model_tester.get_config().text_config + # Layer 1 pools 2-to-1, which is the path that promotes its weights to float32 + compressor = DeepseekV41Compressor(config, layer_idx=1).to(torch_device).eval() + offloaded_compressor = copy.deepcopy(compressor) + cpu_offload(offloaded_compressor, execution_device=torch.device(torch_device)) + hidden_states = torch.randn(2, 6, config.hidden_size, device=torch_device) + # No padding and no cache, and the RoPE of the latents plays no part in the pooling + inputs = ( + hidden_states, + (torch.ones(1, 6, 4, device=torch_device), torch.zeros(1, 6, 4, device=torch_device)), + torch.ones(2, 6, dtype=torch.bool, device=torch_device), + torch.zeros(2, dtype=torch.long, device=torch_device), + ) + with torch.no_grad(): + # The offloaded one goes first. A weight that was not loaded is uninitialized memory, which could + # otherwise still hold the result we are comparing with. + offloaded, _, _ = offloaded_compressor(*inputs) + expected, _, num_groups = compressor(*inputs) + self.assertEqual(expected.shape, (2, 3, config.head_dim)) + self.assertEqual(num_groups.tolist(), [3, 3]) + torch.testing.assert_close(offloaded, expected) + + def test_attention_layer_types(self): + config = self.model_tester.get_config().text_config + self.assertEqual( + config.attention_layer_types, + [ + "sliding_attention", + "compressed_attention", + "kv_shared_attention", + "compressed_attention", + "kv_shared_indexed_attention", + ], + ) + text_config = config.to_dict() + # The layer types are derived from the fields that we change below, so they have to be derived again + del text_config["attention_layer_types"] + # A layer cannot read compressed KV that no layer before it has made + with self.assertRaisesRegex(StrictDataclassClassValidationError, "kv_source_layer_ids"): + DeepseekV41TextConfig.from_dict( + {**text_config, "kv_source_layer_ids": [3], "index_source_layer_ids": [3, 4]} + ) + # ... and the index keys are made from the compressed KV, so a KV source must index too + with self.assertRaisesRegex(StrictDataclassClassValidationError, "index_source_layer_ids"): + DeepseekV41TextConfig.from_dict({**text_config, "index_source_layer_ids": [3, 4]}) + + def test_engram_hash_ids(self): + """The n-gram hash ids match the ones of the reference implementation, with and without a masked token.""" + config = self.model_tester.get_config().text_config + hasher = DeepseekV41NgramHasher(config) + self.assertEqual(hasher.bucket_sizes.tolist(), [[53, 59, 61, 67], [71, 73, 79, 83]]) + input_ids = torch.tensor([[5, 9, 2, 7, 7, 3]]) + # fmt: off + expected = [ + [[0, 56, 118, 234], [29, 105, 167, 257]], + [[16, 61, 163, 235], [4, 132, 174, 274]], + [[15, 88, 113, 194], [56, 98, 189, 267]], + [[27, 59, 167, 201], [14, 96, 179, 253]], + [[23, 80, 118, 228], [16, 92, 199, 242]], + [[13, 76, 118, 200], [58, 88, 146, 227]], + ] + expected_masked = [ + [[0, 56, 118, 234], [29, 105, 167, 257]], + [[16, 61, 163, 235], [4, 132, 174, 274]], + [[15, 88, 113, 194], [56, 98, 189, 267]], + [[41, 58, 115, 232], [51, 106, 201, 234]], + [[27, 59, 116, 203], [14, 96, 209, 224]], + [[13, 76, 139, 237], [58, 88, 202, 287]], + ] + # fmt: on + self.assertEqual(hasher(input_ids).tolist(), [expected]) + token_mask = torch.tensor([[True, True, True, False, True, True]]) + self.assertEqual(hasher(input_ids, token_mask).tolist(), [expected_masked]) + + def test_engram_token_map_must_be_set(self): + """With merged tokens, the map comes from the tokenizer, and the model says so instead of guessing.""" + config = self.model_tester.get_config() + config.text_config.engram_compressed_vocab_size = 60 + model = DeepseekV41ForCausalLM(config).to(torch_device).eval() + input_ids = self.model_tester.prepare_text_ids(1, 6) + with self.assertRaisesRegex(ValueError, "set_engram_token_map"): + model(input_ids=input_ids) + + token_map = torch.arange(config.text_config.vocab_size) % 60 + with self.assertRaisesRegex(ValueError, "compressed ids"): + model.set_engram_token_map(token_map % 50) + model.set_engram_token_map(token_map) + with torch.no_grad(): + logits = model(input_ids=input_ids).logits + self.assertEqual(logits.shape, (1, 6, config.text_config.vocab_size)) + + def test_resize_token_embeddings_is_not_supported(self): + """A new token would have no entry in the Engram token map, so resizing raises instead.""" + config, model = self._get_model() + with self.assertRaisesRegex(NotImplementedError, "placeholder tokens"): + model.resize_token_embeddings(config.text_config.vocab_size + 10) + self.assertEqual(model.get_input_embeddings().weight.shape[0], config.text_config.vocab_size) + + def test_fake_quantize(self): + # First, FP4 with a scale of 1, which the largest value of 6 gives. FP4 holds 0, 0.5, 1, 1.5, 2, 3, 4 and 6 + # times the scale, and a value halfway between two of them goes to the one with the even mantissa. + values = [6.0, 5.0, 3.5, 2.5, 1.75, 1.25, 0.75, 0.25, 0.2, -0.3, -2.6, -5.5, 0.0, 1.0, 1.5, 3.0] + expected = [6.0, 4.0, 4.0, 2.0, 2.0, 1.0, 1.0, 0.0, 0.0, -0.5, -3.0, -6.0, 0.0, 1.0, 1.5, 3.0] + values = torch.tensor([values], device=torch_device) + self.assertEqual(fake_quantize(values, "fp4", block_size=16).tolist(), [expected]) + # Each block has its own scale: an all-zero block stays at zero, next to the block from before + two_blocks = torch.cat([values, torch.zeros_like(values)], dim=-1) + self.assertEqual(fake_quantize(two_blocks, "fp4", block_size=16).tolist(), [expected + [0.0] * 16]) + + # Next, the scale is a power of two. Scaling the block by one changes nothing else, but a largest value + # just over 6 doubles the scale, and everything is rounded twice as coarsely. + scaled = fake_quantize(values * 2.0**-20, "fp4", block_size=16) + self.assertEqual((scaled * 2.0**20).tolist(), [expected]) + coarse = fake_quantize(torch.tensor([[6.5, 5.0, 3.0, 1.4]], device=torch_device), "fp4", block_size=4) + self.assertEqual(coarse.tolist(), [[6.0, 4.0, 3.0, 1.0]]) + + # With an FP8 scale, the scale is the largest value over 6, rounded to FP8: 5 / 6 becomes 0.8125. The + # largest value itself is then cut off at 6 times the scale. + fine = fake_quantize(torch.tensor([[5.0, 2.5, 1.0, 0.0]], device=torch_device), "fp4", 4, scale_format="fp8") + self.assertEqual(fine.tolist(), [[4.875, 2.4375, 0.8125, 0.0]]) + + # Finally, FP8 against the cast to FP8 of PyTorch, with the power-of-two scale of each block. The scale + # has a floor: a block whose largest value is under 1e-4 is scaled as if it were 1e-4. + values = torch.randn(64, 32, device=torch_device) * torch.logspace(-6, 6, 64, device=torch_device)[:, None] + largest = values.abs().amax(dim=-1, keepdim=True).clamp(min=1e-4) + scale = torch.exp2(torch.ceil(torch.log2(largest.double() / 448))).float() + expected = (values / scale).to(torch.float8_e4m3fn).float() * scale + torch.testing.assert_close(fake_quantize(values, "fp8", block_size=32), expected, rtol=0, atol=0) + + def test_fake_quantize_passes_the_gradient_through(self): + values = torch.randn(3, 64, device=torch_device, requires_grad=True) + rounded = fake_quantize(values, "fp8", block_size=32) + rounded.sum().backward() + self.assertTrue(torch.equal(values.grad, torch.ones_like(values))) + # ... and the values are the rounded ones to the bit, as without a gradient + self.assertTrue(torch.equal(rounded, fake_quantize(values.detach(), "fp8", block_size=32))) + + def test_cache_holds_rounded_kv(self): + """The KV and the index keys are rounded before they go in the cache, so rounding them again is a no-op.""" + config, model = self._get_model() + input_ids = self.model_tester.prepare_text_ids(2, 19) + with torch.no_grad(): + cache = model(input_ids=input_ids, use_cache=True).cache + for layer, attention_type in zip(cache.layers, config.text_config.attention_layer_types): + self.assertTrue(torch.equal(fake_quantize(layer.keys, "fp8", block_size=32), layer.keys)) + if attention_type == "compressed_attention": + self.assertTrue(torch.equal(fake_quantize(layer.index_keys, "fp4", block_size=32), layer.index_keys)) + + def test_select_candidate_blocks(self): + scores = torch.tensor([[[0.1, 0.9, 0.3, 0.2, 0.8, float("-inf")]]]) + # The best block is the first one, and the block with the newest visible entry is always kept + keep = select_candidate_blocks(scores, num_visible=torch.tensor([[5]]), topk_blocks=2, block_size=2) + self.assertEqual(keep.tolist(), [[[True, True, False, False, True, True]]]) + # With one visible block, the second pick is not reachable and is dropped + scores = torch.tensor([[[0.1, 0.9, float("-inf"), float("-inf")]]]) + keep = select_candidate_blocks(scores, num_visible=torch.tensor([[2]]), topk_blocks=2, block_size=2) + self.assertEqual(keep.tolist(), [[[True, True, False, False]]]) + + def test_image_and_text_forward(self): + """An image takes a start token, its rows of tokens with a newline after each, and an end token.""" + config, model = self._get_model() + # 5 x 7 patches are merged 3 x 3 into 2 x 3 tokens, so the image takes 1 + 2 * (3 + 1) + 1 positions + height, width, num_image_tokens = 5, 7, 10 + pixel_values = torch.randn(height * width, 3 * config.vision_config.patch_size**2, device=torch_device) + image_grid_thw = torch.tensor([[1, height, width]], device=torch_device) + text = self.model_tester.prepare_text_ids(1, 12) + image = torch.full((1, num_image_tokens), config.image_token_id, device=torch_device) + input_ids = torch.cat([text[:, :4], image, text[:, 4:]], dim=1) + with torch.no_grad(): + image_features = model.model.get_image_features(pixel_values, image_grid_thw).pooler_output[0] + logits = model(input_ids=input_ids, pixel_values=pixel_values, image_grid_thw=image_grid_thw).logits + other_image = model( + input_ids=input_ids, pixel_values=pixel_values + 1, image_grid_thw=image_grid_thw + ).logits + self.assertEqual(image_features.shape, (num_image_tokens, config.text_config.hidden_size)) + torch.testing.assert_close(image_features[0], model.model.image_start) + torch.testing.assert_close(image_features[4], model.model.image_newline) + torch.testing.assert_close(image_features[-1], model.model.image_end) + self.assertEqual(logits.shape, (1, input_ids.shape[1], config.text_config.vocab_size)) + # The text before the image cannot see it, and the text after it can + torch.testing.assert_close(logits[:, :4], other_image[:, :4]) + self.assertGreater((logits[:, -1] - other_image[:, -1]).abs().max().item(), 1e-4) + + # A prompt whose image span is one token short of what the image takes up + short_input_ids = torch.cat([input_ids[:, :5], input_ids[:, 6:]], dim=1) + with self.assertRaisesRegex(ValueError, "image tokens"): + model(input_ids=short_input_ids, pixel_values=pixel_values, image_grid_thw=image_grid_thw) + + # An image is one frame, so a grid with a temporal size other than 1 is not an image + video_grid_thw = torch.tensor([[2, height, width]], device=torch_device) + with self.assertRaisesRegex(ValueError, "temporal size"): + model(input_ids=input_ids, pixel_values=pixel_values.repeat(2, 1), image_grid_thw=video_grid_thw) + + def test_beam_search_keeps_each_image_whole(self): + """ + `generate` repeats its inputs once per beam. `pixel_values` has a row per patch, so repeating its rows + would hand every beam the patches of a scrambled image. The common beam tests only check output shapes. + """ + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = DeepseekV41ForCausalLM(config).to(torch_device).eval() + batch_size, num_beams = inputs_dict["input_ids"].shape[0], 2 + with torch.no_grad(): + expected = model(**inputs_dict).logits[:, -1] + outputs = model.generate( + **inputs_dict, + num_beams=num_beams, + max_new_tokens=2, + do_sample=False, + output_logits=True, + return_dict_in_generate=True, + ) + # On the first step the beams of a prompt are still copies of it, so each one gets the logits of the prompt + first_step_logits = outputs.logits[0].view(batch_size, num_beams, -1) + tolerance = self.rounded_logits_tolerance + for beam in range(num_beams): + torch.testing.assert_close(first_step_logits[:, beam], expected, atol=tolerance, rtol=tolerance) + + def test_image_features_of_several_images(self): + """Images are encoded independently, whether or not they come in together.""" + config, model = self._get_model() + model.set_attn_implementation("eager") + image_grid_thw = torch.tensor([[1, 5, 7], [1, 3, 6]], device=torch_device) + pixel_values = torch.randn(5 * 7 + 3 * 6, 3 * config.vision_config.patch_size**2, device=torch_device) + with torch.no_grad(): + outputs = model.model.get_image_features( + pixel_values, image_grid_thw, output_hidden_states=True, output_attentions=True + ) + first = model.model.get_image_features(pixel_values[:35], image_grid_thw[:1], output_attentions=True) + second = model.model.get_image_features(pixel_values[35:], image_grid_thw[1:], output_attentions=True) + + # 2 x 3 and 1 x 2 tokens, each with a newline per row and the two delimiters + self.assertEqual([features.shape[0] for features in outputs.pooler_output], [10, 5]) + torch.testing.assert_close(outputs.pooler_output[0], first.pooler_output[0]) + torch.testing.assert_close(outputs.pooler_output[1], second.pooler_output[0]) + # The hidden states and the attentions cover the patches of both images, like `pixel_values` + self.assertEqual(len(outputs.hidden_states), config.vision_config.num_hidden_layers + 1) + self.assertEqual(outputs.last_hidden_state.shape, (53, config.vision_config.hidden_size)) + for layer_attention, first_attention, second_attention in zip( + outputs.attentions, first.attentions, second.attentions + ): + self.assertEqual(layer_attention.shape, (config.vision_config.num_attention_heads, 53, 53)) + torch.testing.assert_close(layer_attention[:, :35, :35], first_attention) + torch.testing.assert_close(layer_attention[:, 35:, 35:], second_attention) + # ... and no patch attends to the other image + self.assertEqual(layer_attention[:, :35, 35:].abs().max().item(), 0.0) + self.assertEqual(layer_attention[:, 35:, :35].abs().max().item(), 0.0) + + def test_fp8_quantizer_conversion(self): + """ + The quantization config of the checkpoint only describes its FP8 linears. The model config adds the Engram + tables, which are stored in FP8 as well, and the linears that are stored in BF16. + """ + config = self.model_tester.get_config().to_dict() + # A scale of an Engram table covers 32 values, so the rows have to be at least that wide + config["text_config"]["engram_head_dim"] = 32 + config = DeepseekV41Config.from_dict({**config, "quantization_config": CHECKPOINT_QUANTIZATION_CONFIG}) + with torch.device("meta"): + model = DeepseekV41ForCausalLM(config) + FineGrainedFP8HfQuantizer(FineGrainedFP8Config(**config.quantization_config)).preprocess_model(model) + + bf16_linears = ( + "lm_head", + "vision_tower", + "multi_modal_projector", + "compressor", + "indexer.k_proj", + "indexer.weights_proj", + ) + for name, module in model.named_modules(): + if isinstance(module, torch.nn.Linear): + is_bf16 = any(part in name for part in bf16_linears) + self.assertEqual(isinstance(module, FP8Linear), not is_bf16, name) + for layer_idx in config.text_config.engram_layer_ids: + table = model.model.language_model.layers[layer_idx].engram.embed + self.assertIsInstance(table, FP8Embedding) + # One scale per block of 32 values, and the rows are a single block wide here + self.assertEqual(table.weight_scale.shape, (table.num_embeddings, 1)) + # The token embeddings are not a quantized table + self.assertIs(type(model.model.language_model.embed_tokens), torch.nn.Embedding) + + @require_accelerate + def test_loading_the_quantized_checkpoint_layout(self): + """ + The checkpoint stores its Engram tables and most of its linears in FP8, and its experts in FP4, each with + power-of-two scales next to it. Loading that layout with `dequantize=True` gives the model that those + tensors stand for, with the Engram tables still in FP8. + """ + config = self.model_tester.get_config() + # A scale of an Engram table covers 32 values, so the rows have to be at least that wide + config.text_config.engram_head_dim = 32 + torch.manual_seed(0) + model = DeepseekV41ForCausalLM(config) + fp4_values = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0]) + # Extracts the linears that the checkpoint stores in FP8, by their names in the checkpoint + fp8_linears = re.compile( + r"\.(attn\.(indexer\.)?wq_b|attn\.(wq_a|wkv|wo_a|wo_b)|engram\.wkv|shared_experts\.w[123])\.weight$" + ) + + with tempfile.TemporaryDirectory() as quantized_dir, tempfile.TemporaryDirectory() as plain_dir: + # `save_pretrained` writes the names of the original checkpoint. We quantize the tensors that the + # checkpoint quantizes, and keep the values they stand for to build the model we compare with. + model.save_pretrained(quantized_dir) + model.save_pretrained(plain_dir) + quantized, dequantized = {}, {} + for name, tensor in load_file(f"{quantized_dir}/model.safetensors").items(): + if ".ffn.experts." in name: + # FP4 experts, with a scale for every 32 values of a row + block_rows, max_value = 1, 6.0 + elif ".engram.embed." in name: + # FP8 tables, with a scale for every 32 values of a row too + block_rows, max_value = 1, 448.0 + elif fp8_linears.search(name): + # FP8 linears, with a scale for every block of 32 x 32 values + block_rows, max_value = 32, 448.0 + else: + # Everything else is stored as it is + quantized[name] = dequantized[name] = tensor + continue + blocks = tensor.abs().unflatten(0, (-1, block_rows)).unflatten(-1, (-1, 32)) + scales = torch.exp2(torch.ceil(torch.log2(blocks.amax(dim=(1, 3)).clamp_min(1e-4) / max_value))) + scale_of_each_value = scales.repeat_interleave(block_rows, dim=0).repeat_interleave(32, dim=1) + scaled = tensor / scale_of_each_value + if max_value == 6.0: + # FP4 has 8 magnitudes and a sign bit, and a byte holds two values, the first one in its low bits + codes = (scaled.abs().unsqueeze(-1) - fp4_values).abs().argmin(-1) + values = fp4_values[codes] * scaled.sign() + codes = codes + 8 * (scaled < 0) + quantized[name] = (codes[:, 0::2] | (codes[:, 1::2] << 4)).to(torch.uint8).view(torch.int8) + else: + quantized[name] = scaled.to(torch.float8_e4m3fn) + values = quantized[name].float() + quantized[name.removesuffix("weight") + "scale"] = scales.to(torch.float8_e8m0fnu) + dequantized[name] = values * scale_of_each_value + save_file(quantized, f"{quantized_dir}/model.safetensors", metadata={"format": "pt"}) + save_file(dequantized, f"{plain_dir}/model.safetensors", metadata={"format": "pt"}) + config_path = Path(quantized_dir, "config.json") + config_dict = json.loads(config_path.read_text(encoding="utf-8")) + config_dict["quantization_config"] = CHECKPOINT_QUANTIZATION_CONFIG + config_path.write_text(json.dumps(config_dict), encoding="utf-8") + + expected_model = DeepseekV41ForCausalLM.from_pretrained(plain_dir).to(torch_device).eval() + loaded_model = DeepseekV41ForCausalLM.from_pretrained( + quantized_dir, quantization_config=FineGrainedFP8Config(dequantize=True) + ) + loaded_model = loaded_model.to(torch_device).eval() + + for layer_idx in config.text_config.engram_layer_ids: + self.assertIsInstance(loaded_model.model.language_model.layers[layer_idx].engram.embed, FP8Embedding) + input_ids = self.model_tester.prepare_text_ids(2, 9) + with torch.no_grad(): + expected = expected_model(input_ids=input_ids).logits + logits = loaded_model(input_ids=input_ids).logits + torch.testing.assert_close(logits, expected) diff --git a/tests/models/deepseek_v41/test_processing_deepseek_v41.py b/tests/models/deepseek_v41/test_processing_deepseek_v41.py new file mode 100644 index 000000000000..aa3bbd530379 --- /dev/null +++ b/tests/models/deepseek_v41/test_processing_deepseek_v41.py @@ -0,0 +1,104 @@ +# Copyright 2026 The HuggingFace Inc. 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. +import unittest + +import numpy as np + +from transformers import AutoTokenizer, DeepseekV41Processor, is_torch_available +from transformers.testing_utils import require_torch, require_torchvision, require_vision + +from ...test_processing_common import ProcessorTesterMixin +from .test_modeling_deepseek_v41 import DeepseekV41ModelTester + + +if is_torch_available(): + import torch + + from transformers import DeepseekV41Model + + +@require_torch +@require_vision +@require_torchvision +class DeepseekV41ProcessorTest(ProcessorTesterMixin, unittest.TestCase): + processor_class = DeepseekV41Processor + + @classmethod + def _setup_image_processor(cls): + # Small limits, so that an image only takes a few positions in the prompt: 2 x 2 patches, merged 3 x 3 + # into a token, and at most 16 positions per image + image_processor_class = cls._get_component_class_from_processor("image_processor") + return image_processor_class(patch_size=2, downsample_ratio=3, max_image_tokens=16, min_pixels=64) + + @classmethod + def _setup_tokenizer(cls): + # The tokenizer of the checkpoint, which has the image placeholder and the chat template + return AutoTokenizer.from_pretrained("deepseek-ai/DeepSeek-V4.1-Flash") + + @staticmethod + def _image(height, width): + return np.random.randint(0, 256, (height, width, 3), dtype=np.uint8) + + def test_image_placeholder_expansion(self): + """Each placeholder is repeated once per position of its image: `rows * (columns + 1) + 2`.""" + processor = self.get_processor() + # 6 x 9 patches make 2 x 3 tokens, and 3 x 5 patches round up to 1 x 2 tokens + images = [self._image(12, 18), self._image(5, 7)] + text = f"First {processor.image_token} then {processor.image_token}." + inputs = processor(text=text, images=images, return_tensors="pt") + + self.assertEqual(inputs["image_grid_thw"].tolist(), [[1, 6, 9], [1, 3, 5]]) + self.assertEqual(inputs["pixel_values"].shape[0], 6 * 9 + 3 * 5) + input_ids = inputs["input_ids"][0].tolist() + self.assertEqual(input_ids.count(processor.image_token_id), (2 * (3 + 1) + 2) + (1 * (2 + 1) + 2)) + + # The original implementation tokenizes the prompt first and expands the ids afterwards + expected_ids, num_positions = [], iter([10, 5]) + for token_id in processor.tokenizer(text)["input_ids"]: + expected_ids += [token_id] * (next(num_positions) if token_id == processor.image_token_id else 1) + self.assertEqual(input_ids, expected_ids) + + def test_chat_template_with_images(self): + """The chat template of the checkpoint writes one placeholder per image block.""" + processor = self.get_processor() + messages = [ + { + "role": "user", + "content": [ + {"type": "image", "image": self._image(12, 18)}, + {"type": "text", "text": "What is in this picture?"}, + ], + } + ] + prompt = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False) + self.assertEqual(prompt.count(processor.image_token), 1) + + inputs = processor.apply_chat_template( + messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt" + ) + self.assertEqual(inputs["image_grid_thw"].tolist(), [[1, 6, 9]]) + self.assertEqual(int((inputs["input_ids"] == processor.image_token_id).sum()), 10) + + def test_image_positions_match_the_model(self): + """The model lays each image out on exactly as many positions as the processor made room for.""" + processor = self.get_processor() + # The tiny vision config has the patch size and the downsample ratio of the image processor above + model = DeepseekV41Model(DeepseekV41ModelTester(self).get_config()).eval() + for height, width in [(12, 18), (5, 7), (4, 4), (60, 10), (10, 60), (100, 100)]: + with self.subTest(height=height, width=width): + inputs = processor(text=processor.image_token, images=self._image(height, width), return_tensors="pt") + with torch.no_grad(): + image_features = model.get_image_features(inputs["pixel_values"], inputs["image_grid_thw"]) + num_positions = int((inputs["input_ids"] == processor.image_token_id).sum()) + self.assertEqual(image_features.pooler_output[0].shape[0], num_positions) diff --git a/tests/quantization/finegrained_fp8/test_fp8.py b/tests/quantization/finegrained_fp8/test_fp8.py index f30f1bd76ded..4684c8b9eba6 100644 --- a/tests/quantization/finegrained_fp8/test_fp8.py +++ b/tests/quantization/finegrained_fp8/test_fp8.py @@ -556,6 +556,32 @@ def test_lookup_applies_the_per_tensor_scale(self): error = (rows.float() - expected.float()).abs().max() / expected.float().abs().max() self.assertLess(error, 0.1) + def test_lookup_applies_the_block_scales(self): + """DeepSeek-V4.1's Engram tables have a scale for every block of a row, which a single scale cannot stand in for.""" + from transformers.integrations import FP8Embedding + + # Rows of very different sizes. With one scale for the table, the small ones would round to zero + table = torch.randn(64, 32) * torch.logspace(-3, 3, 64).unsqueeze(1) + blocks = table.unflatten(1, (2, 16)) + # Power-of-two scales, which is all that `ue8m0` can store + scales = torch.exp2(torch.ceil(torch.log2(blocks.abs().amax(-1) / torch.finfo(torch.float8_e4m3fn).max))) + embedding = FP8Embedding(64, 32, block_size=16, scale_fmt="ue8m0") + self.assertEqual(embedding.weight_scale.shape, (64, 2)) + self.assertEqual(embedding.weight_scale.dtype, torch.float8_e8m0fnu) + quantized = (blocks / scales.unsqueeze(-1)).flatten(1).to(torch.float8_e4m3fn) + embedding.weight = torch.nn.Parameter(quantized, requires_grad=False) + embedding.weight_scale = torch.nn.Parameter(scales.to(torch.float8_e8m0fnu), requires_grad=False) + + ids = torch.randint(0, 64, (2, 5)) + rows = embedding(ids) + + # The lookup gives exactly the values that the FP8 table stands for ... + dequantized = (quantized.float().unflatten(1, (2, 16)) * scales.unsqueeze(-1)).flatten(1) + torch.testing.assert_close(rows, dequantized[ids], rtol=0, atol=0) + # ... and those are close to the original values in every row, however small the row is + error = (rows - table[ids]).abs().amax(-1) / table[ids].abs().amax(-1) + self.assertLess(error.max(), 0.1) + def test_patterns_match_by_suffix_and_honour_the_skip_list(self): """Suffixes match whether or not the text model is nested under a multimodal wrapper.""" from transformers.integrations import FP8Embedding, replace_with_fp8_embedding diff --git a/tests/test_modeling_common.py b/tests/test_modeling_common.py index 627a9a4054cc..34a278768f60 100644 --- a/tests/test_modeling_common.py +++ b/tests/test_modeling_common.py @@ -879,6 +879,7 @@ def test_num_layers_is_small(self): "Lfm3ModelTest": 3, # One layer per operator type: ["full_attention", "sliding_attention", "conv"] "Inkling2LoopTextModelTest": 4, # need to test all layer types (before loop, loop, after loop). 2 layers for loop because of sliding and full attention layers. "LaraMiniModelTest": 3, # One layer per token mixer: ["linear_attention", "sliding_attention", "full_attention"] + "DeepseekV41ModelTest": 5, # One layer per attention type, plus a second "compressed_attention" so the KV-sharing layers have two sources to tell apart } target_num_hidden_layers = exceptional_num_hidden_layers.get(type(self).__name__, 2) diff --git a/utils/check_config_attributes.py b/utils/check_config_attributes.py index a91a6124630b..77805e3d2eb5 100644 --- a/utils/check_config_attributes.py +++ b/utils/check_config_attributes.py @@ -220,6 +220,27 @@ "Cohere2MoeConfig": ["rope_scaling", "sliding_window_pattern"], "CsmConfig": ["tie_codebooks_embeddings"], "DeepseekV2Config": ["norm_topk_prob"], + "DeepseekV41TextConfig": [ + # The first six are inherited from `DeepseekV4Config`, and are unused for the same reasons as there + "attention_bias", + "n_shared_experts", + "norm_topk_prob", + "num_key_value_heads", + "router_aux_loss_coef", + "router_jitter_noise", + # The checkpoint's config lists the layers that run an indexer, but the model reads the + # `attention_layer_types` that we derive from it + "index_source_layer_ids", + # The DSpark draft layers are in the checkpoint, but they are not instantiated yet + "num_nextn_predict_layers", + "dspark_block_size", + "dspark_markov_rank", + "dspark_n_routed_experts", + "dspark_num_experts_per_tok", + "dspark_target_layer_ids", + ], + # The checkpoint's vision config carries the preprocessing parameters too + "DeepseekV41VisionConfig": ["max_image_tokens", "max_wh_ratio", "min_pixels"], "DeepseekV4Config": [ # All BC / config-compat surface that the modeling code never reads but # checkpoints in the wild expose (so we keep accepting them in `__init__`):