From 0f561902fdb7ec176062949e516b917b24467d0d Mon Sep 17 00:00:00 2001 From: Matt Date: Wed, 18 Nov 2026 13:20:56 +0000 Subject: [PATCH 01/13] Add DeepSeek-V4.1 --- docs/source/en/_toctree.yml | 2 + docs/source/en/model_doc/deepseek_v41.md | 111 + src/transformers/cache_utils.py | 6 +- src/transformers/configuration_utils.py | 1 + src/transformers/conversion_mapping.py | 72 + src/transformers/models/__init__.py | 1 + src/transformers/models/auto/auto_mappings.py | 5 + src/transformers/models/auto/modeling_auto.py | 4 + .../models/deepseek_v41/__init__.py | 33 + .../configuration_deepseek_v41.py | 439 ++++ .../deepseek_v41/modeling_deepseek_v41.py | 1740 ++++++++++++++++ .../deepseek_v41/modular_deepseek_v41.py | 1819 +++++++++++++++++ tests/models/deepseek_v41/__init__.py | 0 .../test_modeling_deepseek_v41.py | 284 +++ utils/check_config_attributes.py | 21 + 15 files changed, 4537 insertions(+), 1 deletion(-) create mode 100644 docs/source/en/model_doc/deepseek_v41.md create mode 100644 src/transformers/models/deepseek_v41/__init__.py create mode 100644 src/transformers/models/deepseek_v41/configuration_deepseek_v41.py create mode 100644 src/transformers/models/deepseek_v41/modeling_deepseek_v41.py create mode 100644 src/transformers/models/deepseek_v41/modular_deepseek_v41.py create mode 100644 tests/models/deepseek_v41/__init__.py create mode 100644 tests/models/deepseek_v41/test_modeling_deepseek_v41.py 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..96412f6c8b9f --- /dev/null +++ b/docs/source/en/model_doc/deepseek_v41.md @@ -0,0 +1,111 @@ + +*This model was contributed to Hugging Face Transformers on 2026-11-18.* + +# 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. + +## Notes + +- The model needs `input_ids` even when you pass `inputs_embeds`, because Engram hashes token ids. +- Batched generation with left padding does not match unpadded generation yet. The compressor pools consecutive + tokens, so padding shifts its groups. +- The DSpark draft layers of the checkpoint (`mtp.*`) are not loaded. +- There is no image processor yet. Images go in as `pixel_values` (the flattened patches of all the images) and + `image_grid_hw` (the height and width of each image's patch grid). + +## DeepseekV41Config + +[[autodoc]] DeepseekV41Config + +## DeepseekV41TextConfig + +[[autodoc]] DeepseekV41TextConfig + +## DeepseekV41VisionConfig + +[[autodoc]] DeepseekV41VisionConfig + +## 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/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..bf9369ad683f 100755 --- a/src/transformers/conversion_mapping.py +++ b/src/transformers/conversion_mapping.py @@ -779,6 +779,78 @@ 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."), + 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/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..a8108d7d9c04 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"), diff --git a/src/transformers/models/auto/modeling_auto.py b/src/transformers/models/auto/modeling_auto.py index a39e5484b698..2282f3d85583 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"), diff --git a/src/transformers/models/deepseek_v41/__init__.py b/src/transformers/models/deepseek_v41/__init__.py new file mode 100644 index 000000000000..5bd6e7f63355 --- /dev/null +++ b/src/transformers/models/deepseek_v41/__init__.py @@ -0,0 +1,33 @@ +# ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ +# 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 .modeling_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..499297a76033 --- /dev/null +++ b/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py @@ -0,0 +1,439 @@ +# ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ +# 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 ratio are cropped down 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" + keys_to_ignore_at_inference = ["cache"] + # `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"]), + } + # Main attention and the shared MLP stay replicated. Shared-KV MQA and the CSA / HCA compressor + # broadcast one KV head via `repeat_kv`, so colwise `q_b_proj` would mismatch the rank-local + # head count; the shared MLP is too small to be worth sharding. + base_model_tp_plan = { + "layers.*.mlp.experts.gate_up_proj": "packed_colwise", + "layers.*.mlp.experts.down_proj": "rowwise", + "layers.*.mlp.experts": "moe_tp_experts", + } + 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} + + +@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 + + +__all__ = ["DeepseekV41Config", "DeepseekV41TextConfig", "DeepseekV41VisionConfig"] 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..91abab50a190 --- /dev/null +++ b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py @@ -0,0 +1,1740 @@ +# ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ +# 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, use_kernel_forward_from_hub +from ...masking_utils import create_sliding_window_causal_mask +from ...modeling_layers import GradientCheckpointingLayer +from ...modeling_outputs import BaseModelOutput, MoeCausalLMOutputWithPast, MoeModelOutputWithPast +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 +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. + * `buffer_kv` / `buffer_gate` - 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.buffer_kv: torch.Tensor | None = None + self.buffer_gate: 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 + + @property + def num_compressed_entries(self) -> int: + return 0 if self.compressed_kv is None else self.compressed_kv.shape[1] + + def update_pooling_buffer( + self, kv: torch.Tensor, gate: torch.Tensor, compress_ratio: int + ) -> tuple[torch.Tensor, torch.Tensor]: + """ + Put the new `(kv, gate)` after the tokens that are still waiting for their group to fill up, and + return the longest prefix that is made of whole groups. The rest waits in the buffer for the next call. + """ + if self.buffer_kv is not None: + kv = torch.cat([self.buffer_kv, kv], dim=1) + gate = torch.cat([self.buffer_gate, gate], dim=1) + usable = (kv.shape[1] // compress_ratio) * compress_ratio + self.buffer_kv, self.buffer_gate = kv[:, usable:], gate[:, usable:] + return kv[:, :usable], gate[:, :usable] + + def update_compressed_states( + self, compressed_kv: torch.Tensor, index_keys: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + """Append the new compressed KV entries and their index keys, and return all of them so far.""" + if self.compressed_kv is not None: + compressed_kv = torch.cat([self.compressed_kv, compressed_kv], dim=1) + index_keys = torch.cat([self.index_keys, index_keys], dim=1) + self.compressed_kv, self.index_keys = compressed_kv, index_keys + return compressed_kv, 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", "buffer_kv", "buffer_gate", "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) + + +@use_kernel_forward_from_hub("RMSNorm") +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) -> 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) + # DSV4: norm weights are kept in float32, so multiply in float32 and cast once at the end + return (self.weight * hidden_states).to(input_dtype) + + 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 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. + + 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. 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] + self.kv_proj = nn.Linear(config.hidden_size, config.head_dim, bias=False) + self.gate_proj = ( + nn.Linear(config.hidden_size, config.head_dim, bias=False) if self.compress_ratio > 1 else None + ) + self.kv_norm = DeepseekV41RMSNorm(config.head_dim, eps=config.rms_norm_eps) + + def forward(self, hidden_states: torch.Tensor, cache_layer: DeepseekV41CacheLayer | None = None) -> torch.Tensor: + if self.gate_proj is None: + # One token per group, so no gate and no pooling + return self.kv_norm(self.kv_proj(hidden_states)) + + # The reference promotes the pooling weights to float32, and pools in float32 too + kv = F.linear(hidden_states.float(), self.kv_proj.weight.float()) + gate = F.linear(hidden_states.float(), self.gate_proj.weight.float()) + if cache_layer is not None: + kv, gate = cache_layer.update_pooling_buffer(kv, gate, self.compress_ratio) + else: + usable = (kv.shape[1] // self.compress_ratio) * self.compress_ratio + kv, gate = kv[:, :usable], gate[:, :usable] + kv = kv.unflatten(1, (-1, self.compress_ratio)) + gate = gate.unflatten(1, (-1, self.compress_ratio)) + pooled = (kv * gate.softmax(dim=2)).sum(dim=2) + return self.kv_norm(pooled.to(hidden_states.dtype)) + + +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) + + +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, + position_ids: 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) + 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 + num_visible = (position_ids + 1) // 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""" + Sliding-window attention, which is all that the `"sliding_attention"` layers do. The other attention + variants add compressed KV on top of the window by overriding `get_compressed_kv`. + + 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. + """ + + rope_layer_type = "main" + + def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): + super().__init__() + self.config = config + self.layer_idx = 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)) + + def get_compressed_kv( + self, + hidden_states: torch.Tensor, + q_residual: torch.Tensor, + position_ids: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor], + cache: Cache | None, + shared_states: dict[str, torch.Tensor], + ) -> tuple[torch.Tensor | None, torch.Tensor | None]: + """ + Returns the compressed KV entries of shape `(batch_size, num_entries, head_dim)` and a boolean mask of + shape `(batch_size, seq_len, num_entries)` that says which of them each query attends to. A + sliding-window-only layer has neither. + """ + return None, None + + def forward( + self, + hidden_states: torch.Tensor, + position_embeddings: dict[str, tuple[torch.Tensor, torch.Tensor]], + position_ids: torch.Tensor, + attention_mask: torch.Tensor, + cache: Cache | None = None, + shared_states: dict[str, torch.Tensor] | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple[torch.Tensor, torch.Tensor | None]: + input_shape = hidden_states.shape[:-1] + 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) + if cache is not None: + kv = cache.update(kv, kv, self.layer_idx)[0] + + # 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 = self.get_compressed_kv( + hidden_states, q_residual, position_ids, (cos, sin), cache, shared_states + ) + if compressed_kv is not None: + 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) + grouped = self.o_a_proj(grouped).flatten(2) + output = self.o_b_proj(grouped) + return output, attn_weights + + +class DeepseekV41KVSharedAttention(DeepseekV41Attention): + """ + Attention over a sliding window, plus the compressed KV of the last `"compressed_attention"` layer. Which + compressed entries each query attends to is also reused, from the last layer that ran an indexer. + """ + + rope_layer_type = "compress" + + def get_compressed_kv( + self, + hidden_states: torch.Tensor, + q_residual: torch.Tensor, + position_ids: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor], + cache: Cache | None, + shared_states: dict[str, torch.Tensor], + ) -> tuple[torch.Tensor | None, torch.Tensor | None]: + return shared_states["compressed_kv"], shared_states["selected"] + + +class DeepseekV41KVSharedIndexedAttention(DeepseekV41KVSharedAttention): + """ + Attention over a sliding window, plus the compressed KV of the last `"compressed_attention"` layer. This + layer runs its own indexer to select which compressed entries each query attends to, and the + `"kv_shared_attention"` layers after it reuse that selection. + """ + + def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): + super().__init__(config, layer_idx) + self.indexer = DeepseekV41Indexer(config, layer_idx) + + def get_compressed_kv( + self, + hidden_states: torch.Tensor, + q_residual: torch.Tensor, + position_ids: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor], + cache: Cache | None, + shared_states: dict[str, torch.Tensor], + ) -> tuple[torch.Tensor | None, torch.Tensor | None]: + shared_states["selected"], shared_states["candidates"] = self.indexer( + hidden_states, + q_residual, + shared_states["index_keys"], + position_ids, + position_embeddings, + shared_states.get("candidates"), + ) + return shared_states["compressed_kv"], shared_states["selected"] + + +class DeepseekV41CompressedAttention(DeepseekV41KVSharedIndexedAttention): + """ + Attention over a sliding window, plus KV that this layer compresses itself. It also makes the index keys + for those compressed KV and runs an indexer over them. The KV-sharing layers after it read all three: the + compressed KV, the index keys and the selection. + """ + + def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): + super().__init__(config, layer_idx) + self.compressor = DeepseekV41Compressor(config, layer_idx) + self.rotary_emb = DeepseekV41RotaryEmbedding(config) + + def get_compressed_kv( + self, + hidden_states: torch.Tensor, + q_residual: torch.Tensor, + position_ids: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor], + cache: Cache | None, + shared_states: dict[str, torch.Tensor], + ) -> tuple[torch.Tensor | None, torch.Tensor | None]: + cache_layer: DeepseekV41CacheLayer | None = cache.layers[self.layer_idx] if cache is not None else None + num_previous_entries = cache_layer.num_compressed_entries if cache_layer is not None else 0 + + # First, compress the groups that this call completes. There may be none of them, e.g. when decoding + # a token that is not the last of its group. + latents = self.compressor(hidden_states, cache_layer) + batch_size, num_new_entries, _ = latents.shape + + # A latent stands for the first token of its group, so group `j` rotates at position `j * ratio` + positions = torch.arange(num_new_entries, device=latents.device) + num_previous_entries + positions = (positions * self.compressor.compress_ratio).unsqueeze(0).expand(batch_size, -1) + cos, sin = self.rotary_emb(latents, position_ids=positions, layer_type=self.rope_layer_type) + + # Next, make the index keys. They come from the latents before RoPE, so this has to happen before we + # rotate the latents themselves. + index_keys = self.indexer.k_norm(self.indexer.k_proj(latents)) + index_keys = apply_rotary_pos_emb(index_keys.unsqueeze(1), cos, sin).squeeze(1) + compressed_kv = apply_rotary_pos_emb(latents.unsqueeze(1), cos, sin).squeeze(1) + if cache_layer is not None: + compressed_kv, index_keys = cache_layer.update_compressed_states(compressed_kv, index_keys) + + # Finally, 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 + return super().get_compressed_kv( + hidden_states, q_residual, position_ids, position_embeddings, cache, 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)) + self.e_score_correction_bias_vl = nn.Buffer(torch.zeros(self.num_experts)) + + 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) + + +DEEPSEEK_V41_ATTENTION_CLASSES = { + "sliding_attention": DeepseekV41Attention, + "compressed_attention": DeepseekV41CompressedAttention, + "kv_shared_indexed_attention": DeepseekV41KVSharedIndexedAttention, + "kv_shared_attention": DeepseekV41KVSharedAttention, +} + + +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 = DEEPSEEK_V41_ATTENTION_CLASSES[config.attention_layer_types[layer_idx]](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) + self.ffn_hc = DeepseekV41HyperConnection(config) + 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, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple[torch.Tensor, 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, _ = self.self_attn(self.input_layernorm(collapsed), **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 + + +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.num_heads = config.num_attention_heads + self.head_dim = config.hidden_size // config.num_attention_heads + 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) -> torch.Tensor: + 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) + attn_output = F.scaled_dot_product_attention(query.transpose(0, 1), key.transpose(0, 1), value.transpose(0, 1)) + return self.o_proj(attn_output.transpose(0, 1).reshape(num_patches, -1)) + + +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: + hidden_states = hidden_states + self.self_attn(self.layer_norm1(hidden_states), cos, sin) + 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))) + + +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 + _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) + + +@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",) + + 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) + + @can_return_tuple + @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)) + + +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( + 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 + 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 + if position_ids is None: + past_seen = cache.get_seq_length() if cache is not None else 0 + position_ids = torch.arange(seq_len, device=inputs_embeds.device) + past_seen + position_ids = position_ids.unsqueeze(0) + + # First, 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: + if image_mask is not None: + engram_mask = ~image_mask + hash_mask = engram_mask + if isinstance(attention_mask, torch.Tensor) and attention_mask.ndim == 2: + is_real_token = attention_mask[:, -seq_len:].bool() + hash_mask = is_real_token if hash_mask is None else hash_mask & is_real_token + 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"), + } + # What the attention layers hand down the stack instead of recomputing: the compressed KV, the index + # keys, the selection and the candidate blocks. Every source writes before the layers after it read. + shared_states = {} + + for layer_idx, layer in enumerate(self.layers): + hidden_states, pre = layer( + hidden_states, + pre, + engram_hash_ids=( + engram_hash_ids[:, :, self.config.engram_layer_ids.index(layer_idx)] + if layer.engram is not None + else None + ), + engram_mask=engram_mask, + image_mask=image_mask, + position_embeddings=position_embeddings, + position_ids=position_ids, + 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) + + def set_engram_token_map(self, tokenizer_or_token_map): + """ + 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. + """ + if self.engram_hasher is None: + raise ValueError("This model has no Engram layers (`config.engram_layer_ids` is empty).") + 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 != self.config.engram_compressed_vocab_size: + raise ValueError( + f"The token map has {num_compressed_ids} compressed ids, but the model was trained with " + f"{self.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] > self.engram_hasher.token_map.shape[0]: + raise ValueError( + f"The token map has {token_map.shape[0]} entries, but the model only has " + f"{self.engram_hasher.token_map.shape[0]} tokens (`config.vocab_size`)." + ) + self.engram_hasher.token_map[: token_map.shape[0]] = token_map.to(self.engram_hasher.token_map.device) + + +@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 + + def set_engram_token_map(self, tokenizer_or_token_map): + self.language_model.set_engram_token_map(tokenizer_or_token_map) + + def get_image_features(self, pixel_values: torch.Tensor, image_grid_hw: torch.Tensor) -> torch.Tensor: + """ + 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. + + Args: + 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_hw (`torch.Tensor` of shape `(num_images, 2)`): + The height and width of each image's patch grid. + + Returns: + `torch.Tensor` of shape `(total_image_tokens, hidden_size)`: The embeddings of all the image + positions in the prompt, in order. + """ + image_features = [] + grids = image_grid_hw.tolist() + patches_per_image = pixel_values.split([height * width for height, width in grids]) + for patches, (height, width) in zip(patches_per_image, grids): + hidden_states = self.vision_tower(patches, height, width).last_hidden_state + tokens = self.multi_modal_projector(hidden_states, 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_features += [self.image_start.to(tokens.dtype)[None], rows, self.image_end.to(tokens.dtype)[None]] + return torch.cat(image_features) + + @can_return_tuple + @auto_docstring + def forward( + self, + input_ids: torch.LongTensor | None = None, + pixel_values: torch.Tensor | None = None, + image_grid_hw: 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, + **kwargs: Unpack[TransformersKwargs], + ) -> MoeModelOutputWithPast: + 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_hw (`torch.LongTensor` of shape `(num_images, 2)`, *optional*): + The height and width of each image's patch grid. + """ + 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) + + # 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 pixel_values is not None: + if image_mask is None: + raise ValueError("`input_ids` are needed to find where the images go in the prompt.") + image_features = self.get_image_features(pixel_values, image_grid_hw) + num_image_tokens = int(image_mask.sum()) + if num_image_tokens != image_features.shape[0]: + raise ValueError( + f"The prompt has {num_image_tokens} image tokens, but the images take up " + f"{image_features.shape[0]} tokens (grids: {image_grid_hw.tolist()})." + ) + image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype) + inputs_embeds = inputs_embeds.masked_scatter(image_mask.unsqueeze(-1), image_features) + + return 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, + ) + + +@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 + + def set_engram_token_map(self, tokenizer_or_token_map): + """ + 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. + """ + self.model.set_engram_token_map(tokenizer_or_token_map) + + @can_return_tuple + @auto_docstring + def forward( + self, + input_ids: torch.LongTensor | None = None, + pixel_values: torch.Tensor | None = None, + image_grid_hw: 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, + **kwargs: Unpack[TransformersKwargs], + ) -> MoeCausalLMOutputWithPast: + 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_hw (`torch.LongTensor` of shape `(num_images, 2)`, *optional*): + The height and width of each image's patch grid. + 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: MoeModelOutputWithPast = self.model( + input_ids=input_ids, + pixel_values=pixel_values, + image_grid_hw=image_grid_hw, + attention_mask=attention_mask, + position_ids=position_ids, + cache=cache, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + **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 MoeCausalLMOutputWithPast( + loss=loss, + logits=logits, + cache=outputs.cache, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + router_logits=outputs.router_logits, + ) + + def prepare_inputs_for_generation( + self, + input_ids, + cache=None, + inputs_embeds=None, + pixel_values=None, + image_grid_hw=None, + attention_mask=None, + is_first_iteration=False, + **kwargs, + ): + model_inputs = super().prepare_inputs_for_generation( + input_ids, + cache=cache, + inputs_embeds=inputs_embeds, + attention_mask=attention_mask, + is_first_iteration=is_first_iteration, + **kwargs, + ) + # The images are merged into the prompt on the first step, and after that they are in the cache + if is_first_iteration or not kwargs.get("use_cache", True): + model_inputs["pixel_values"] = pixel_values + model_inputs["image_grid_hw"] = image_grid_hw + return model_inputs + + +__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..f5b18bb82121 --- /dev/null +++ b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py @@ -0,0 +1,1819 @@ +# 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 huggingface_hub.dataclasses import strict +from torch import nn + +from ... import initialization as init +from ...cache_utils import Cache, DynamicCache, DynamicSlidingWindowLayer +from ...configuration_utils import PreTrainedConfig +from ...generation import GenerationMixin +from ...integrations import use_experts_implementation +from ...masking_utils import create_sliding_window_causal_mask +from ...modeling_layers import GradientCheckpointingLayer +from ...modeling_outputs import BaseModelOutput, MoeCausalLMOutputWithPast, MoeModelOutputWithPast +from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel +from ...processing_utils import Unpack +from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging +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 ratio are cropped down 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 __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 + + +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. + * `buffer_kv` / `buffer_gate` - 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.buffer_kv: torch.Tensor | None = None + self.buffer_gate: 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 + + @property + def num_compressed_entries(self) -> int: + return 0 if self.compressed_kv is None else self.compressed_kv.shape[1] + + def update_pooling_buffer( + self, kv: torch.Tensor, gate: torch.Tensor, compress_ratio: int + ) -> tuple[torch.Tensor, torch.Tensor]: + """ + Put the new `(kv, gate)` after the tokens that are still waiting for their group to fill up, and + return the longest prefix that is made of whole groups. The rest waits in the buffer for the next call. + """ + if self.buffer_kv is not None: + kv = torch.cat([self.buffer_kv, kv], dim=1) + gate = torch.cat([self.buffer_gate, gate], dim=1) + usable = (kv.shape[1] // compress_ratio) * compress_ratio + self.buffer_kv, self.buffer_gate = kv[:, usable:], gate[:, usable:] + return kv[:, :usable], gate[:, :usable] + + def update_compressed_states( + self, compressed_kv: torch.Tensor, index_keys: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + """Append the new compressed KV entries and their index keys, and return all of them so far.""" + if self.compressed_kv is not None: + compressed_kv = torch.cat([self.compressed_kv, compressed_kv], dim=1) + index_keys = torch.cat([self.index_keys, index_keys], dim=1) + self.compressed_kv, self.index_keys = compressed_kv, index_keys + return compressed_kv, 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", "buffer_kv", "buffer_gate", "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 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. + + 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. 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] + self.kv_proj = nn.Linear(config.hidden_size, config.head_dim, bias=False) + self.gate_proj = ( + nn.Linear(config.hidden_size, config.head_dim, bias=False) if self.compress_ratio > 1 else None + ) + self.kv_norm = DeepseekV41RMSNorm(config.head_dim, eps=config.rms_norm_eps) + + def forward(self, hidden_states: torch.Tensor, cache_layer: DeepseekV41CacheLayer | None = None) -> torch.Tensor: + if self.gate_proj is None: + # One token per group, so no gate and no pooling + return self.kv_norm(self.kv_proj(hidden_states)) + + # The reference promotes the pooling weights to float32, and pools in float32 too + kv = F.linear(hidden_states.float(), self.kv_proj.weight.float()) + gate = F.linear(hidden_states.float(), self.gate_proj.weight.float()) + if cache_layer is not None: + kv, gate = cache_layer.update_pooling_buffer(kv, gate, self.compress_ratio) + else: + usable = (kv.shape[1] // self.compress_ratio) * self.compress_ratio + kv, gate = kv[:, :usable], gate[:, :usable] + kv = kv.unflatten(1, (-1, self.compress_ratio)) + gate = gate.unflatten(1, (-1, self.compress_ratio)) + pooled = (kv * gate.softmax(dim=2)).sum(dim=2) + return self.kv_norm(pooled.to(hidden_states.dtype)) + + +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, + position_ids: 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) + 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 + num_visible = (position_ids + 1) // 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""" + Sliding-window attention, which is all that the `"sliding_attention"` layers do. The other attention + variants add compressed KV on top of the window by overriding `get_compressed_kv`. + + 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. + """ + + rope_layer_type = "main" + + def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): + super().__init__() + self.config = config + self.layer_idx = 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)) + + def get_compressed_kv( + self, + hidden_states: torch.Tensor, + q_residual: torch.Tensor, + position_ids: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor], + cache: Cache | None, + shared_states: dict[str, torch.Tensor], + ) -> tuple[torch.Tensor | None, torch.Tensor | None]: + """ + Returns the compressed KV entries of shape `(batch_size, num_entries, head_dim)` and a boolean mask of + shape `(batch_size, seq_len, num_entries)` that says which of them each query attends to. A + sliding-window-only layer has neither. + """ + return None, None + + def forward( + self, + hidden_states: torch.Tensor, + position_embeddings: dict[str, tuple[torch.Tensor, torch.Tensor]], + position_ids: torch.Tensor, + attention_mask: torch.Tensor, + cache: Cache | None = None, + shared_states: dict[str, torch.Tensor] | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple[torch.Tensor, torch.Tensor | None]: + input_shape = hidden_states.shape[:-1] + 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) + if cache is not None: + kv = cache.update(kv, kv, self.layer_idx)[0] + + # 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 = self.get_compressed_kv( + hidden_states, q_residual, position_ids, (cos, sin), cache, shared_states + ) + if compressed_kv is not None: + 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) + grouped = self.o_a_proj(grouped).flatten(2) + output = self.o_b_proj(grouped) + return output, attn_weights + + +class DeepseekV41KVSharedAttention(DeepseekV41Attention): + """ + Attention over a sliding window, plus the compressed KV of the last `"compressed_attention"` layer. Which + compressed entries each query attends to is also reused, from the last layer that ran an indexer. + """ + + rope_layer_type = "compress" + + def get_compressed_kv( + self, + hidden_states: torch.Tensor, + q_residual: torch.Tensor, + position_ids: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor], + cache: Cache | None, + shared_states: dict[str, torch.Tensor], + ) -> tuple[torch.Tensor | None, torch.Tensor | None]: + return shared_states["compressed_kv"], shared_states["selected"] + + +class DeepseekV41KVSharedIndexedAttention(DeepseekV41KVSharedAttention): + """ + Attention over a sliding window, plus the compressed KV of the last `"compressed_attention"` layer. This + layer runs its own indexer to select which compressed entries each query attends to, and the + `"kv_shared_attention"` layers after it reuse that selection. + """ + + def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): + super().__init__(config, layer_idx) + self.indexer = DeepseekV41Indexer(config, layer_idx) + + def get_compressed_kv( + self, + hidden_states: torch.Tensor, + q_residual: torch.Tensor, + position_ids: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor], + cache: Cache | None, + shared_states: dict[str, torch.Tensor], + ) -> tuple[torch.Tensor | None, torch.Tensor | None]: + shared_states["selected"], shared_states["candidates"] = self.indexer( + hidden_states, + q_residual, + shared_states["index_keys"], + position_ids, + position_embeddings, + shared_states.get("candidates"), + ) + return shared_states["compressed_kv"], shared_states["selected"] + + +class DeepseekV41CompressedAttention(DeepseekV41KVSharedIndexedAttention): + """ + Attention over a sliding window, plus KV that this layer compresses itself. It also makes the index keys + for those compressed KV and runs an indexer over them. The KV-sharing layers after it read all three: the + compressed KV, the index keys and the selection. + """ + + def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): + super().__init__(config, layer_idx) + self.compressor = DeepseekV41Compressor(config, layer_idx) + self.rotary_emb = DeepseekV41RotaryEmbedding(config) + + def get_compressed_kv( + self, + hidden_states: torch.Tensor, + q_residual: torch.Tensor, + position_ids: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor], + cache: Cache | None, + shared_states: dict[str, torch.Tensor], + ) -> tuple[torch.Tensor | None, torch.Tensor | None]: + cache_layer: DeepseekV41CacheLayer | None = cache.layers[self.layer_idx] if cache is not None else None + num_previous_entries = cache_layer.num_compressed_entries if cache_layer is not None else 0 + + # First, compress the groups that this call completes. There may be none of them, e.g. when decoding + # a token that is not the last of its group. + latents = self.compressor(hidden_states, cache_layer) + batch_size, num_new_entries, _ = latents.shape + + # A latent stands for the first token of its group, so group `j` rotates at position `j * ratio` + positions = torch.arange(num_new_entries, device=latents.device) + num_previous_entries + positions = (positions * self.compressor.compress_ratio).unsqueeze(0).expand(batch_size, -1) + cos, sin = self.rotary_emb(latents, position_ids=positions, layer_type=self.rope_layer_type) + + # Next, make the index keys. They come from the latents before RoPE, so this has to happen before we + # rotate the latents themselves. + index_keys = self.indexer.k_norm(self.indexer.k_proj(latents)) + index_keys = apply_rotary_pos_emb(index_keys.unsqueeze(1), cos, sin).squeeze(1) + compressed_kv = apply_rotary_pos_emb(latents.unsqueeze(1), cos, sin).squeeze(1) + if cache_layer is not None: + compressed_kv, index_keys = cache_layer.update_compressed_states(compressed_kv, index_keys) + + # Finally, 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 + return super().get_compressed_kv( + hidden_states, q_residual, position_ids, position_embeddings, cache, shared_states + ) + + +DEEPSEEK_V41_ATTENTION_CLASSES = { + "sliding_attention": DeepseekV41Attention, + "compressed_attention": DeepseekV41CompressedAttention, + "kv_shared_indexed_attention": DeepseekV41KVSharedIndexedAttention, + "kv_shared_attention": DeepseekV41KVSharedAttention, +} + + +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)) + + 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 = DEEPSEEK_V41_ATTENTION_CLASSES[config.attention_layer_types[layer_idx]](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) + self.ffn_hc = DeepseekV41HyperConnection(config) + 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, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple[torch.Tensor, 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, _ = self.self_attn(self.input_layernorm(collapsed), **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 + + +class DeepseekV41VisionAttention(nn.Module): + """Bidirectional attention over the patches of one image, with 2D RoPE.""" + + def __init__(self, config: DeepseekV41VisionConfig): + super().__init__() + self.num_heads = config.num_attention_heads + self.head_dim = config.hidden_size // config.num_attention_heads + 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) -> torch.Tensor: + 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) + attn_output = F.scaled_dot_product_attention(query.transpose(0, 1), key.transpose(0, 1), value.transpose(0, 1)) + return self.o_proj(attn_output.transpose(0, 1).reshape(num_patches, -1)) + + +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: + hidden_states = hidden_states + self.self_attn(self.layer_norm1(hidden_states), cos, sin) + 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))) + + +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 + _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) + + +@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",) + + 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) + + @can_return_tuple + @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 + 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 + if position_ids is None: + past_seen = cache.get_seq_length() if cache is not None else 0 + position_ids = torch.arange(seq_len, device=inputs_embeds.device) + past_seen + position_ids = position_ids.unsqueeze(0) + + # First, 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: + if image_mask is not None: + engram_mask = ~image_mask + hash_mask = engram_mask + if isinstance(attention_mask, torch.Tensor) and attention_mask.ndim == 2: + is_real_token = attention_mask[:, -seq_len:].bool() + hash_mask = is_real_token if hash_mask is None else hash_mask & is_real_token + 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"), + } + # What the attention layers hand down the stack instead of recomputing: the compressed KV, the index + # keys, the selection and the candidate blocks. Every source writes before the layers after it read. + shared_states = {} + + for layer_idx, layer in enumerate(self.layers): + hidden_states, pre = layer( + hidden_states, + pre, + engram_hash_ids=( + engram_hash_ids[:, :, self.config.engram_layer_ids.index(layer_idx)] + if layer.engram is not None + else None + ), + engram_mask=engram_mask, + image_mask=image_mask, + position_embeddings=position_embeddings, + position_ids=position_ids, + 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) + + def set_engram_token_map(self, tokenizer_or_token_map): + """ + 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. + """ + if self.engram_hasher is None: + raise ValueError("This model has no Engram layers (`config.engram_layer_ids` is empty).") + 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 != self.config.engram_compressed_vocab_size: + raise ValueError( + f"The token map has {num_compressed_ids} compressed ids, but the model was trained with " + f"{self.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] > self.engram_hasher.token_map.shape[0]: + raise ValueError( + f"The token map has {token_map.shape[0]} entries, but the model only has " + f"{self.engram_hasher.token_map.shape[0]} tokens (`config.vocab_size`)." + ) + self.engram_hasher.token_map[: token_map.shape[0]] = token_map.to(self.engram_hasher.token_map.device) + + +@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 + + def set_engram_token_map(self, tokenizer_or_token_map): + self.language_model.set_engram_token_map(tokenizer_or_token_map) + + def get_image_features(self, pixel_values: torch.Tensor, image_grid_hw: torch.Tensor) -> torch.Tensor: + """ + 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. + + Args: + 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_hw (`torch.Tensor` of shape `(num_images, 2)`): + The height and width of each image's patch grid. + + Returns: + `torch.Tensor` of shape `(total_image_tokens, hidden_size)`: The embeddings of all the image + positions in the prompt, in order. + """ + image_features = [] + grids = image_grid_hw.tolist() + patches_per_image = pixel_values.split([height * width for height, width in grids]) + for patches, (height, width) in zip(patches_per_image, grids): + hidden_states = self.vision_tower(patches, height, width).last_hidden_state + tokens = self.multi_modal_projector(hidden_states, 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_features += [self.image_start.to(tokens.dtype)[None], rows, self.image_end.to(tokens.dtype)[None]] + return torch.cat(image_features) + + @can_return_tuple + @auto_docstring + def forward( + self, + input_ids: torch.LongTensor | None = None, + pixel_values: torch.Tensor | None = None, + image_grid_hw: 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, + **kwargs: Unpack[TransformersKwargs], + ) -> MoeModelOutputWithPast: + 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_hw (`torch.LongTensor` of shape `(num_images, 2)`, *optional*): + The height and width of each image's patch grid. + """ + 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) + + # 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 pixel_values is not None: + if image_mask is None: + raise ValueError("`input_ids` are needed to find where the images go in the prompt.") + image_features = self.get_image_features(pixel_values, image_grid_hw) + num_image_tokens = int(image_mask.sum()) + if num_image_tokens != image_features.shape[0]: + raise ValueError( + f"The prompt has {num_image_tokens} image tokens, but the images take up " + f"{image_features.shape[0]} tokens (grids: {image_grid_hw.tolist()})." + ) + image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype) + inputs_embeds = inputs_embeds.masked_scatter(image_mask.unsqueeze(-1), image_features) + + return 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, + ) + + +@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 + + def set_engram_token_map(self, tokenizer_or_token_map): + """ + 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. + """ + self.model.set_engram_token_map(tokenizer_or_token_map) + + @can_return_tuple + @auto_docstring + def forward( + self, + input_ids: torch.LongTensor | None = None, + pixel_values: torch.Tensor | None = None, + image_grid_hw: 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, + **kwargs: Unpack[TransformersKwargs], + ) -> MoeCausalLMOutputWithPast: + 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_hw (`torch.LongTensor` of shape `(num_images, 2)`, *optional*): + The height and width of each image's patch grid. + 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: MoeModelOutputWithPast = self.model( + input_ids=input_ids, + pixel_values=pixel_values, + image_grid_hw=image_grid_hw, + attention_mask=attention_mask, + position_ids=position_ids, + cache=cache, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + **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 MoeCausalLMOutputWithPast( + loss=loss, + logits=logits, + cache=outputs.cache, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + router_logits=outputs.router_logits, + ) + + def prepare_inputs_for_generation( + self, + input_ids, + cache=None, + inputs_embeds=None, + pixel_values=None, + image_grid_hw=None, + attention_mask=None, + is_first_iteration=False, + **kwargs, + ): + model_inputs = super().prepare_inputs_for_generation( + input_ids, + cache=cache, + inputs_embeds=inputs_embeds, + attention_mask=attention_mask, + is_first_iteration=is_first_iteration, + **kwargs, + ) + # The images are merged into the prompt on the first step, and after that they are in the cache + if is_first_iteration or not kwargs.get("use_cache", True): + model_inputs["pixel_values"] = pixel_values + model_inputs["image_grid_hw"] = image_grid_hw + return model_inputs + + +__all__ = [ + "DeepseekV41Config", + "DeepseekV41TextConfig", + "DeepseekV41VisionConfig", + "DeepseekV41PreTrainedModel", + "DeepseekV41VisionModel", + "DeepseekV41TextModel", + "DeepseekV41Model", + "DeepseekV41ForCausalLM", +] 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_modeling_deepseek_v41.py b/tests/models/deepseek_v41/test_modeling_deepseek_v41.py new file mode 100644 index 000000000000..7ea60c998e48 --- /dev/null +++ b/tests/models/deepseek_v41/test_modeling_deepseek_v41.py @@ -0,0 +1,284 @@ +# 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 + +from huggingface_hub.errors import StrictDataclassClassValidationError + +from transformers import is_torch_available +from transformers.testing_utils import require_torch, torch_device + + +if is_torch_available(): + import torch + + from transformers import DeepseekV41Config, DeepseekV41ForCausalLM, DeepseekV41Model, DeepseekV41TextConfig + from transformers.models.deepseek_v41.modeling_deepseek_v41 import ( + DeepseekV41NgramHasher, + select_candidate_blocks, + ) + +from ...causal_lm_tester import CausalLMModelTest, CausalLMModelTester + + +class DeepseekV41ModelTester(CausalLMModelTester): + if is_torch_available(): + base_model_class = DeepseekV41Model + config_class = DeepseekV41Config + causal_lm_class = DeepseekV41ForCausalLM + + def __init__(self, parent, **kwargs): + super().__init__(parent, **kwargs) + self.hidden_size = 64 + self.num_attention_heads = 4 + self.num_hidden_layers = 5 + self.seq_length = 11 + self.batch_size = 3 + # The inputs are text only, so the image token must not show up in the random ids + self.image_token_id = self.vocab_size + self.text_config = { + "vocab_size": self.vocab_size + 1, + "hidden_size": self.hidden_size, + "moe_intermediate_size": 32, + "num_hidden_layers": self.num_hidden_layers, + "num_attention_heads": self.num_attention_heads, + "head_dim": 32, + "partial_rotary_factor": 8 / 32, + "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": 16, + "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, + # As large as the vocab, so that no tokens are merged and the model works without a tokenizer + "engram_compressed_vocab_size": self.vocab_size + 1, + "engram_num_embeddings": None, + "num_nextn_predict_layers": 0, + "dspark_noise_token_id": 3, + "rms_norm_eps": 1e-6, + "pad_token_id": self.pad_token_id, + "bos_token_id": self.bos_token_id, + "eos_token_id": self.eos_token_id, + } + self.vision_config = { + "hidden_size": 32, + "num_hidden_layers": 2, + "num_attention_heads": 4, + "intermediate_size": 48, + "patch_size": 2, + "downsample_ratio": 3, + } + + def get_config(self): + return DeepseekV41Config( + text_config=self.text_config, + vision_config=self.vision_config, + image_token_id=self.image_token_id, + pad_token_id=self.pad_token_id, + bos_token_id=self.bos_token_id, + eos_token_id=self.eos_token_id, + ) + + +@require_torch +class DeepseekV41ModelTest(CausalLMModelTest, 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 + + def is_pipeline_test_to_skip(self, *args, **kwargs): + return True + + @unittest.skip( + reason=( + "The compressor pools consecutive tokens before the attention mask applies, so left padding shifts " + "the groups and folds pad tokens into the compressed KV. Same limitation as DeepSeek-V4, not fixed yet." + ) + ) + def test_left_padding_compatibility(self): + pass + + 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 = torch.randint(0, self.model_tester.vocab_size, (2, 19), device=torch_device) + 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) + torch.testing.assert_close(torch.cat(logits, dim=1), expected, atol=1e-4, rtol=1e-4) + + 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 = torch.randint(0, self.model_tester.vocab_size, (2, 19), device=torch_device) + 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) + torch.testing.assert_close(torch.cat(logits, dim=1), expected, atol=1e-4, rtol=1e-4) + + 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 = torch.randint(0, self.model_tester.vocab_size, (1, 19), device=torch_device) + 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) + + 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 = self.model_tester.text_config + # A layer cannot read compressed KV that no layer before it has made + with self.assertRaisesRegex(StrictDataclassClassValidationError, "kv_source_layer_ids"): + DeepseekV41TextConfig(**{**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(**{**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.""" + text_config = {**self.model_tester.text_config, "engram_compressed_vocab_size": 60} + config = DeepseekV41Config(text_config=text_config, vision_config=self.model_tester.vision_config) + model = DeepseekV41ForCausalLM(config).to(torch_device).eval() + input_ids = torch.randint(0, self.model_tester.vocab_size, (1, 6), device=torch_device) + 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_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_hw = torch.tensor([[height, width]], device=torch_device) + text = torch.randint(0, self.model_tester.vocab_size, (1, 12), device=torch_device) + 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_hw) + logits = model(input_ids=input_ids, pixel_values=pixel_values, image_grid_hw=image_grid_hw).logits + other_image = model(input_ids=input_ids, pixel_values=pixel_values + 1, image_grid_hw=image_grid_hw).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_hw=image_grid_hw) 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__`): From e3e77f0285dd095d0551708721ebd1f7331311d0 Mon Sep 17 00:00:00 2001 From: Matt Date: Wed, 18 Nov 2026 14:04:43 +0000 Subject: [PATCH 02/13] DeepSeek-V4.1: common tests, offloading and structure checks The compressor read its pooling weights straight off its submodules to promote them to float32, so with offloaded weights it pooled uninitialized memory. The promotion now happens inside the projection itself. The `shared_states` dict also has to skip device placement, or every layer gets its own copy of it. `get_image_features` now returns a model output with the vision encoder's hidden states and attentions, the forwards take the deprecated `past_key_values`, and the tests check the shapes that the compressed KV and the hyper-connection streams really have. --- .../deepseek_v41/modeling_deepseek_v41.py | 193 ++++++++++++++---- .../deepseek_v41/modular_deepseek_v41.py | 193 ++++++++++++++---- .../test_modeling_deepseek_v41.py | 147 ++++++++++++- tests/test_modeling_common.py | 1 + tests/test_training_mixin.py | 2 +- 5 files changed, 443 insertions(+), 93 deletions(-) diff --git a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py index 91abab50a190..ff601af8cd05 100644 --- a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py @@ -31,11 +31,17 @@ from ...integrations import use_experts_implementation, use_kernel_forward_from_hub from ...masking_utils import create_sliding_window_causal_mask from ...modeling_layers import GradientCheckpointingLayer -from ...modeling_outputs import BaseModelOutput, MoeCausalLMOutputWithPast, MoeModelOutputWithPast +from ...modeling_outputs import ( + BaseModelOutput, + BaseModelOutputWithPooling, + MoeCausalLMOutputWithPast, + MoeModelOutputWithPast, +) 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 +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 @@ -282,6 +288,19 @@ def forward(self, x: torch.Tensor) -> torch.Tensor: 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 @@ -295,10 +314,14 @@ class DeepseekV41Compressor(nn.Module): def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): super().__init__() self.compress_ratio = config.compress_ratios[layer_idx] - self.kv_proj = nn.Linear(config.hidden_size, config.head_dim, bias=False) - self.gate_proj = ( - nn.Linear(config.hidden_size, config.head_dim, bias=False) if self.compress_ratio > 1 else None - ) + 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, cache_layer: DeepseekV41CacheLayer | None = None) -> torch.Tensor: @@ -307,8 +330,7 @@ def forward(self, hidden_states: torch.Tensor, cache_layer: DeepseekV41CacheLaye return self.kv_norm(self.kv_proj(hidden_states)) # The reference promotes the pooling weights to float32, and pools in float32 too - kv = F.linear(hidden_states.float(), self.kv_proj.weight.float()) - gate = F.linear(hidden_states.float(), self.gate_proj.weight.float()) + kv, gate = self.kv_proj(hidden_states), self.gate_proj(hidden_states) if cache_layer is not None: kv, gate = cache_layer.update_pooling_buffer(kv, gate, self.compress_ratio) else: @@ -569,7 +591,6 @@ def forward( self, hidden_states: torch.Tensor, position_embeddings: dict[str, tuple[torch.Tensor, torch.Tensor]], - position_ids: torch.Tensor, attention_mask: torch.Tensor, cache: Cache | None = None, shared_states: dict[str, torch.Tensor] | None = None, @@ -592,10 +613,12 @@ def forward( # 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 = self.get_compressed_kv( - hidden_states, q_residual, position_ids, (cos, sin), cache, shared_states + hidden_states, q_residual, kwargs.get("position_ids"), (cos, sin), cache, shared_states ) if compressed_kv is not None: - kv = torch.cat([kv, compressed_kv.unsqueeze(1).to(kv.dtype)], dim=2) + # With a device map, the layer that made the compressed KV may sit on another device + compressed_kv, selected = compressed_kv.to(kv.device, kv.dtype), selected.to(kv.device) + kv = torch.cat([kv, compressed_kv.unsqueeze(1)], 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) @@ -666,13 +689,15 @@ def get_compressed_kv( cache: Cache | None, shared_states: dict[str, torch.Tensor], ) -> tuple[torch.Tensor | None, torch.Tensor | None]: + # With a device map, the layers that made the index keys and the candidates may sit on another device + candidates = shared_states.get("candidates") shared_states["selected"], shared_states["candidates"] = self.indexer( hidden_states, q_residual, - shared_states["index_keys"], + shared_states["index_keys"].to(hidden_states.device), position_ids, position_embeddings, - shared_states.get("candidates"), + candidates.to(hidden_states.device) if candidates is not None else None, ) return shared_states["compressed_kv"], shared_states["selected"] @@ -1109,6 +1134,27 @@ def forward( return hidden_states.to(dtype), mlp_pre +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) @@ -1121,17 +1167,36 @@ class DeepseekV41VisionAttention(nn.Module): 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) -> torch.Tensor: + 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) - attn_output = F.scaled_dot_product_attention(query.transpose(0, 1), key.transpose(0, 1), value.transpose(0, 1)) - return self.o_proj(attn_output.transpose(0, 1).reshape(num_patches, -1)) + + 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): @@ -1154,7 +1219,8 @@ def __init__(self, config: DeepseekV41VisionConfig): self.mlp = DeepseekV41VisionMLP(config) def forward(self, hidden_states: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: - hidden_states = hidden_states + self.self_attn(self.layer_norm1(hidden_states), cos, sin) + 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)) @@ -1177,12 +1243,16 @@ def forward(self, image_features: torch.Tensor, height: int, width: int) -> torc 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"] + # The layers write into `shared_states` for the layers after them, so the device hooks must hand every + # layer the same dict rather than a copy of it moved to the layer's device + _skip_keys_device_placement = ["cache", "shared_states"] # 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. @@ -1257,6 +1327,12 @@ 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) @@ -1276,7 +1352,8 @@ def get_position_embeddings(self, height: int, width: int, device) -> tuple[torc freqs = freqs.flatten(1) return freqs.cos().unsqueeze(1), freqs.sin().unsqueeze(1) - @can_return_tuple + @merge_with_config_defaults + @capture_outputs @auto_docstring def forward( self, pixel_values: torch.Tensor, height: int, width: int, **kwargs: Unpack[TransformersKwargs] @@ -1381,6 +1458,7 @@ def __init__(self, config: DeepseekV41TextConfig): @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, @@ -1458,7 +1536,7 @@ def forward( pre, engram_hash_ids=( engram_hash_ids[:, :, self.config.engram_layer_ids.index(layer_idx)] - if layer.engram is not None + if layer_idx in self.config.engram_layer_ids else None ), engram_mask=engram_mask, @@ -1536,37 +1614,59 @@ def set_input_embeddings(self, value): def set_engram_token_map(self, tokenizer_or_token_map): self.language_model.set_engram_token_map(tokenizer_or_token_map) - def get_image_features(self, pixel_values: torch.Tensor, image_grid_hw: torch.Tensor) -> torch.Tensor: + @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)`. """ - 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. - - Args: - 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_hw (`torch.Tensor` of shape `(num_images, 2)`): - The height and width of each image's patch grid. - - Returns: - `torch.Tensor` of shape `(total_image_tokens, hidden_size)`: The embeddings of all the image - positions in the prompt, in order. + ) + def get_image_features( + self, pixel_values: torch.Tensor, image_grid_hw: 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_hw (`torch.LongTensor` of shape `(num_images, 2)`): + The height and width of each image's patch grid. """ - image_features = [] grids = image_grid_hw.tolist() 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): - hidden_states = self.vision_tower(patches, height, width).last_hidden_state - tokens = self.multi_modal_projector(hidden_states, height, width) + 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_features += [self.image_start.to(tokens.dtype)[None], rows, self.image_end.to(tokens.dtype)[None]] - return torch.cat(image_features) + 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, @@ -1595,14 +1695,16 @@ def forward( if pixel_values is not None: if image_mask is None: raise ValueError("`input_ids` are needed to find where the images go in the prompt.") - image_features = self.get_image_features(pixel_values, image_grid_hw) - num_image_tokens = int(image_mask.sum()) - if num_image_tokens != image_features.shape[0]: - raise ValueError( - f"The prompt has {num_image_tokens} image tokens, but the images take up " - f"{image_features.shape[0]} tokens (grids: {image_grid_hw.tolist()})." - ) - image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype) + image_features = self.get_image_features(pixel_values, image_grid_hw, return_dict=True).pooler_output + image_features = torch.cat(image_features).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 (`image_grid_hw`: {image_grid_hw})." + ), + ) inputs_embeds = inputs_embeds.masked_scatter(image_mask.unsqueeze(-1), image_features) return self.language_model( @@ -1652,6 +1754,7 @@ def set_engram_token_map(self, tokenizer_or_token_map): @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, diff --git a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py index f5b18bb82121..62951e53b045 100644 --- a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py @@ -26,11 +26,17 @@ from ...integrations import use_experts_implementation from ...masking_utils import create_sliding_window_causal_mask from ...modeling_layers import GradientCheckpointingLayer -from ...modeling_outputs import BaseModelOutput, MoeCausalLMOutputWithPast, MoeModelOutputWithPast +from ...modeling_outputs import ( + BaseModelOutput, + BaseModelOutputWithPooling, + MoeCausalLMOutputWithPast, + MoeModelOutputWithPast, +) from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack -from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging +from ...utils import 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 @@ -485,6 +491,19 @@ 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()) + + class DeepseekV41Compressor(nn.Module): """ Pools every `compress_ratio` consecutive tokens into one KV latent with a learned softmax gate. With a @@ -498,10 +517,14 @@ class DeepseekV41Compressor(nn.Module): def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): super().__init__() self.compress_ratio = config.compress_ratios[layer_idx] - self.kv_proj = nn.Linear(config.hidden_size, config.head_dim, bias=False) - self.gate_proj = ( - nn.Linear(config.hidden_size, config.head_dim, bias=False) if self.compress_ratio > 1 else None - ) + 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, cache_layer: DeepseekV41CacheLayer | None = None) -> torch.Tensor: @@ -510,8 +533,7 @@ def forward(self, hidden_states: torch.Tensor, cache_layer: DeepseekV41CacheLaye return self.kv_norm(self.kv_proj(hidden_states)) # The reference promotes the pooling weights to float32, and pools in float32 too - kv = F.linear(hidden_states.float(), self.kv_proj.weight.float()) - gate = F.linear(hidden_states.float(), self.gate_proj.weight.float()) + kv, gate = self.kv_proj(hidden_states), self.gate_proj(hidden_states) if cache_layer is not None: kv, gate = cache_layer.update_pooling_buffer(kv, gate, self.compress_ratio) else: @@ -702,7 +724,6 @@ def forward( self, hidden_states: torch.Tensor, position_embeddings: dict[str, tuple[torch.Tensor, torch.Tensor]], - position_ids: torch.Tensor, attention_mask: torch.Tensor, cache: Cache | None = None, shared_states: dict[str, torch.Tensor] | None = None, @@ -725,10 +746,12 @@ def forward( # 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 = self.get_compressed_kv( - hidden_states, q_residual, position_ids, (cos, sin), cache, shared_states + hidden_states, q_residual, kwargs.get("position_ids"), (cos, sin), cache, shared_states ) if compressed_kv is not None: - kv = torch.cat([kv, compressed_kv.unsqueeze(1).to(kv.dtype)], dim=2) + # With a device map, the layer that made the compressed KV may sit on another device + compressed_kv, selected = compressed_kv.to(kv.device, kv.dtype), selected.to(kv.device) + kv = torch.cat([kv, compressed_kv.unsqueeze(1)], 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) @@ -799,13 +822,15 @@ def get_compressed_kv( cache: Cache | None, shared_states: dict[str, torch.Tensor], ) -> tuple[torch.Tensor | None, torch.Tensor | None]: + # With a device map, the layers that made the index keys and the candidates may sit on another device + candidates = shared_states.get("candidates") shared_states["selected"], shared_states["candidates"] = self.indexer( hidden_states, q_residual, - shared_states["index_keys"], + shared_states["index_keys"].to(hidden_states.device), position_ids, position_embeddings, - shared_states.get("candidates"), + candidates.to(hidden_states.device) if candidates is not None else None, ) return shared_states["compressed_kv"], shared_states["selected"] @@ -1246,22 +1271,62 @@ def forward( return hidden_states.to(dtype), mlp_pre +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) -> torch.Tensor: + 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) - attn_output = F.scaled_dot_product_attention(query.transpose(0, 1), key.transpose(0, 1), value.transpose(0, 1)) - return self.o_proj(attn_output.transpose(0, 1).reshape(num_patches, -1)) + + 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: @@ -1291,7 +1356,8 @@ def __init__(self, config: DeepseekV41VisionConfig): self.mlp = DeepseekV41VisionMLP(config) def forward(self, hidden_states: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: - hidden_states = hidden_states + self.self_attn(self.layer_norm1(hidden_states), cos, sin) + 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)) @@ -1314,12 +1380,16 @@ def forward(self, image_features: torch.Tensor, height: int, width: int) -> torc 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"] + # The layers write into `shared_states` for the layers after them, so the device hooks must hand every + # layer the same dict rather than a copy of it moved to the layer's device + _skip_keys_device_placement = ["cache", "shared_states"] # 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. @@ -1394,6 +1464,12 @@ 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) @@ -1413,7 +1489,8 @@ def get_position_embeddings(self, height: int, width: int, device) -> tuple[torc freqs = freqs.flatten(1) return freqs.cos().unsqueeze(1), freqs.sin().unsqueeze(1) - @can_return_tuple + @merge_with_config_defaults + @capture_outputs @auto_docstring def forward( self, pixel_values: torch.Tensor, height: int, width: int, **kwargs: Unpack[TransformersKwargs] @@ -1457,6 +1534,7 @@ def __init__(self, config: DeepseekV41TextConfig): @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, @@ -1534,7 +1612,7 @@ def forward( pre, engram_hash_ids=( engram_hash_ids[:, :, self.config.engram_layer_ids.index(layer_idx)] - if layer.engram is not None + if layer_idx in self.config.engram_layer_ids else None ), engram_mask=engram_mask, @@ -1612,37 +1690,59 @@ def set_input_embeddings(self, value): def set_engram_token_map(self, tokenizer_or_token_map): self.language_model.set_engram_token_map(tokenizer_or_token_map) - def get_image_features(self, pixel_values: torch.Tensor, image_grid_hw: torch.Tensor) -> torch.Tensor: + @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)`. """ - 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. - - Args: - 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_hw (`torch.Tensor` of shape `(num_images, 2)`): - The height and width of each image's patch grid. - - Returns: - `torch.Tensor` of shape `(total_image_tokens, hidden_size)`: The embeddings of all the image - positions in the prompt, in order. + ) + def get_image_features( + self, pixel_values: torch.Tensor, image_grid_hw: 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_hw (`torch.LongTensor` of shape `(num_images, 2)`): + The height and width of each image's patch grid. """ - image_features = [] grids = image_grid_hw.tolist() 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): - hidden_states = self.vision_tower(patches, height, width).last_hidden_state - tokens = self.multi_modal_projector(hidden_states, height, width) + 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_features += [self.image_start.to(tokens.dtype)[None], rows, self.image_end.to(tokens.dtype)[None]] - return torch.cat(image_features) + 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, @@ -1671,14 +1771,16 @@ def forward( if pixel_values is not None: if image_mask is None: raise ValueError("`input_ids` are needed to find where the images go in the prompt.") - image_features = self.get_image_features(pixel_values, image_grid_hw) - num_image_tokens = int(image_mask.sum()) - if num_image_tokens != image_features.shape[0]: - raise ValueError( - f"The prompt has {num_image_tokens} image tokens, but the images take up " - f"{image_features.shape[0]} tokens (grids: {image_grid_hw.tolist()})." - ) - image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype) + image_features = self.get_image_features(pixel_values, image_grid_hw, return_dict=True).pooler_output + image_features = torch.cat(image_features).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 (`image_grid_hw`: {image_grid_hw})." + ), + ) inputs_embeds = inputs_embeds.masked_scatter(image_mask.unsqueeze(-1), image_features) return self.language_model( @@ -1728,6 +1830,7 @@ def set_engram_token_map(self, tokenizer_or_token_map): @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, diff --git a/tests/models/deepseek_v41/test_modeling_deepseek_v41.py b/tests/models/deepseek_v41/test_modeling_deepseek_v41.py index 7ea60c998e48..bfb7b72c4ba0 100644 --- a/tests/models/deepseek_v41/test_modeling_deepseek_v41.py +++ b/tests/models/deepseek_v41/test_modeling_deepseek_v41.py @@ -11,12 +11,13 @@ # 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 unittest from huggingface_hub.errors import StrictDataclassClassValidationError from transformers import is_torch_available -from transformers.testing_utils import require_torch, torch_device +from transformers.testing_utils import require_accelerate, require_torch, torch_device if is_torch_available(): @@ -24,11 +25,13 @@ from transformers import DeepseekV41Config, DeepseekV41ForCausalLM, DeepseekV41Model, DeepseekV41TextConfig from transformers.models.deepseek_v41.modeling_deepseek_v41 import ( + DeepseekV41Compressor, DeepseekV41NgramHasher, select_candidate_blocks, ) from ...causal_lm_tester import CausalLMModelTest, CausalLMModelTester +from ...test_configuration_common import ConfigTester class DeepseekV41ModelTester(CausalLMModelTester): @@ -119,9 +122,100 @@ class DeepseekV41ModelTest(CausalLMModelTest, unittest.TestCase): # The indexer parameters only influence which compressed entries are selected, which is not differentiable test_all_params_have_gradient = False + def setUp(self): + super().setUp() + # The config is a composite, so the text fields like `vocab_size` are on its `text_config` + self.config_tester = ConfigTester( + self, config_class=DeepseekV41Config, has_text_modality=False, common_properties=["image_token_id"] + ) + def is_pipeline_test_to_skip(self, *args, **kwargs): return True + def _image_features_prepare_config_and_inputs(self): + # The common inputs are text only, so we make the image inputs here: two images with different grids + config = self.model_tester.get_config() + image_grid_hw = torch.tensor([[5, 7], [3, 6]], device=torch_device) + num_patches = int(image_grid_hw.prod(-1).sum()) + pixel_values = torch.randn(num_patches, 3 * config.vision_config.patch_size**2, device=torch_device) + return config, {"pixel_values": pixel_values, "image_grid_hw": image_grid_hw} + + 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)], + ) + @unittest.skip( reason=( "The compressor pools consecutive tokens before the attention mask applies, so left padding shifts " @@ -180,6 +274,25 @@ def test_compressed_attention_is_used(self): 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) + 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(hidden_states) + expected = compressor(hidden_states) + self.assertEqual(expected.shape, (2, 3, config.head_dim)) + torch.testing.assert_close(offloaded, expected) + def test_attention_layer_types(self): config = self.model_tester.get_config().text_config self.assertEqual( @@ -266,7 +379,7 @@ def test_image_and_text_forward(self): 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_hw) + image_features = model.model.get_image_features(pixel_values, image_grid_hw).pooler_output[0] logits = model(input_ids=input_ids, pixel_values=pixel_values, image_grid_hw=image_grid_hw).logits other_image = model(input_ids=input_ids, pixel_values=pixel_values + 1, image_grid_hw=image_grid_hw).logits self.assertEqual(image_features.shape, (num_image_tokens, config.text_config.hidden_size)) @@ -282,3 +395,33 @@ def test_image_and_text_forward(self): 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_hw=image_grid_hw) + + 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_hw = torch.tensor([[5, 7], [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_hw, output_hidden_states=True, output_attentions=True + ) + first = model.model.get_image_features(pixel_values[:35], image_grid_hw[:1], output_attentions=True) + second = model.model.get_image_features(pixel_values[35:], image_grid_hw[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) 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/tests/test_training_mixin.py b/tests/test_training_mixin.py index 1f644936e1f8..6280d896af5c 100644 --- a/tests/test_training_mixin.py +++ b/tests/test_training_mixin.py @@ -220,7 +220,7 @@ def test_training_overfit(self): batch = self._create_text_training_batch( batch_size=self.training_overfit_batch_size, seq_length=self.training_overfit_seq_length, - vocab_size=config.vocab_size, + vocab_size=config.get_text_config().vocab_size, ) logger.info(f"{Colors.CYAN}Training pattern:{Colors.RESET} Repeating token sequence (1-19)") else: From 04ce34961efd2e8018b121e9ce95411b47eebf36 Mon Sep 17 00:00:00 2001 From: Matt Date: Wed, 18 Nov 2026 15:59:02 +0000 Subject: [PATCH 03/13] DeepSeek-V4.1: resolve the model structure findings The four attention classes are now one class that branches on the layer type, like DeepSeek-V4 does, so there is no subclass chain and no class dict any more. The model owns the only rotary embedding. It computes the RoPE of the compressed entries for each compress ratio and passes it down, instead of the compressing attention layers building a rotary module each. `set_engram_token_map` is a single method on the PreTrainedModel instead of one per model class. It still needs a linter ignore: it fills a saved buffer that the checkpoints leave out, not a hyperparameter. Also merges main, which dropped `keys_to_ignore_at_inference` from the parent config. --- .../configuration_deepseek_v41.py | 1 - .../deepseek_v41/modeling_deepseek_v41.py | 413 +++++++----------- .../deepseek_v41/modular_deepseek_v41.py | 291 +++++------- 3 files changed, 271 insertions(+), 434 deletions(-) diff --git a/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py b/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py index 499297a76033..66d262bfb00e 100644 --- a/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py @@ -163,7 +163,6 @@ class DeepseekV41TextConfig(PreTrainedConfig): """ model_type = "deepseek_v41_text" - keys_to_ignore_at_inference = ["cache"] # `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. diff --git a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py index ff601af8cd05..9e4c1d6d399d 100644 --- a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py @@ -535,8 +535,16 @@ def eager_attention_forward( class DeepseekV41Attention(nn.Module): r""" - Sliding-window attention, which is all that the `"sliding_attention"` layers do. The other attention - variants add compressed KV on top of the window by overriding `get_compressed_kv`. + 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 @@ -546,12 +554,14 @@ class DeepseekV41Attention(nn.Module): * A learnable attention sink per head, and a grouped low-rank output projection. """ - rope_layer_type = "main" - 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 @@ -570,22 +580,10 @@ def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): ) 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)) - - def get_compressed_kv( - self, - hidden_states: torch.Tensor, - q_residual: torch.Tensor, - position_ids: torch.Tensor, - position_embeddings: tuple[torch.Tensor, torch.Tensor], - cache: Cache | None, - shared_states: dict[str, torch.Tensor], - ) -> tuple[torch.Tensor | None, torch.Tensor | None]: - """ - Returns the compressed KV entries of shape `(batch_size, num_entries, head_dim)` and a boolean mask of - shape `(batch_size, seq_len, num_entries)` that says which of them each query attends to. A - sliding-window-only layer has neither. - """ - return None, None + 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, @@ -594,6 +592,7 @@ def forward( attention_mask: 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]: input_shape = hidden_states.shape[:-1] @@ -610,14 +609,41 @@ def forward( if cache is not None: kv = cache.update(kv, kv, self.layer_idx)[0] - # 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 = self.get_compressed_kv( - hidden_states, q_residual, kwargs.get("position_ids"), (cos, sin), cache, shared_states - ) - if compressed_kv is not None: - # With a device map, the layer that made the compressed KV may sit on another device - compressed_kv, selected = compressed_kv.to(kv.device, kv.dtype), selected.to(kv.device) + if self.layer_type == "compressed_attention": + # This layer compresses the groups that this call completes. There may be 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 = self.compressor(hidden_states, cache_layer) + entry_cos, entry_sin = compressed_position_embeddings[self.compress_ratio] + # 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) + if cache_layer is not None: + compressed_kv, index_keys = cache_layer.update_compressed_states(compressed_kv, index_keys) + # 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. With a device map, the layers that + # made the index keys and the candidates may sit on another device. + candidates = shared_states.get("candidates") + shared_states["selected"], shared_states["candidates"] = self.indexer( + hidden_states, + q_residual, + shared_states["index_keys"].to(hidden_states.device), + kwargs.get("position_ids"), + (cos, sin), + candidates.to(hidden_states.device) if candidates is not None else None, + ) + + 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. With a device map, the + # layer that made the compressed KV may sit on another device. + compressed_kv = shared_states["compressed_kv"].to(kv.device, kv.dtype) + selected = shared_states["selected"].to(kv.device) kv = torch.cat([kv, compressed_kv.unsqueeze(1)], 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) @@ -649,108 +675,6 @@ def forward( return output, attn_weights -class DeepseekV41KVSharedAttention(DeepseekV41Attention): - """ - Attention over a sliding window, plus the compressed KV of the last `"compressed_attention"` layer. Which - compressed entries each query attends to is also reused, from the last layer that ran an indexer. - """ - - rope_layer_type = "compress" - - def get_compressed_kv( - self, - hidden_states: torch.Tensor, - q_residual: torch.Tensor, - position_ids: torch.Tensor, - position_embeddings: tuple[torch.Tensor, torch.Tensor], - cache: Cache | None, - shared_states: dict[str, torch.Tensor], - ) -> tuple[torch.Tensor | None, torch.Tensor | None]: - return shared_states["compressed_kv"], shared_states["selected"] - - -class DeepseekV41KVSharedIndexedAttention(DeepseekV41KVSharedAttention): - """ - Attention over a sliding window, plus the compressed KV of the last `"compressed_attention"` layer. This - layer runs its own indexer to select which compressed entries each query attends to, and the - `"kv_shared_attention"` layers after it reuse that selection. - """ - - def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): - super().__init__(config, layer_idx) - self.indexer = DeepseekV41Indexer(config, layer_idx) - - def get_compressed_kv( - self, - hidden_states: torch.Tensor, - q_residual: torch.Tensor, - position_ids: torch.Tensor, - position_embeddings: tuple[torch.Tensor, torch.Tensor], - cache: Cache | None, - shared_states: dict[str, torch.Tensor], - ) -> tuple[torch.Tensor | None, torch.Tensor | None]: - # With a device map, the layers that made the index keys and the candidates may sit on another device - candidates = shared_states.get("candidates") - shared_states["selected"], shared_states["candidates"] = self.indexer( - hidden_states, - q_residual, - shared_states["index_keys"].to(hidden_states.device), - position_ids, - position_embeddings, - candidates.to(hidden_states.device) if candidates is not None else None, - ) - return shared_states["compressed_kv"], shared_states["selected"] - - -class DeepseekV41CompressedAttention(DeepseekV41KVSharedIndexedAttention): - """ - Attention over a sliding window, plus KV that this layer compresses itself. It also makes the index keys - for those compressed KV and runs an indexer over them. The KV-sharing layers after it read all three: the - compressed KV, the index keys and the selection. - """ - - def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): - super().__init__(config, layer_idx) - self.compressor = DeepseekV41Compressor(config, layer_idx) - self.rotary_emb = DeepseekV41RotaryEmbedding(config) - - def get_compressed_kv( - self, - hidden_states: torch.Tensor, - q_residual: torch.Tensor, - position_ids: torch.Tensor, - position_embeddings: tuple[torch.Tensor, torch.Tensor], - cache: Cache | None, - shared_states: dict[str, torch.Tensor], - ) -> tuple[torch.Tensor | None, torch.Tensor | None]: - cache_layer: DeepseekV41CacheLayer | None = cache.layers[self.layer_idx] if cache is not None else None - num_previous_entries = cache_layer.num_compressed_entries if cache_layer is not None else 0 - - # First, compress the groups that this call completes. There may be none of them, e.g. when decoding - # a token that is not the last of its group. - latents = self.compressor(hidden_states, cache_layer) - batch_size, num_new_entries, _ = latents.shape - - # A latent stands for the first token of its group, so group `j` rotates at position `j * ratio` - positions = torch.arange(num_new_entries, device=latents.device) + num_previous_entries - positions = (positions * self.compressor.compress_ratio).unsqueeze(0).expand(batch_size, -1) - cos, sin = self.rotary_emb(latents, position_ids=positions, layer_type=self.rope_layer_type) - - # Next, make the index keys. They come from the latents before RoPE, so this has to happen before we - # rotate the latents themselves. - index_keys = self.indexer.k_norm(self.indexer.k_proj(latents)) - index_keys = apply_rotary_pos_emb(index_keys.unsqueeze(1), cos, sin).squeeze(1) - compressed_kv = apply_rotary_pos_emb(latents.unsqueeze(1), cos, sin).squeeze(1) - if cache_layer is not None: - compressed_kv, index_keys = cache_layer.update_compressed_states(compressed_kv, index_keys) - - # Finally, 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 - return super().get_compressed_kv( - hidden_states, q_residual, position_ids, position_embeddings, cache, shared_states - ) - - class DeepseekV41HyperConnection(nn.Module): r""" Computes the hyper-connection weights of one sublayer (attention or MLP) from the `hc_mult` residual @@ -1071,14 +995,6 @@ def forward( return (streams + gate.unsqueeze(-1) * value.float().unsqueeze(-2)).to(hidden_streams.dtype) -DEEPSEEK_V41_ATTENTION_CLASSES = { - "sliding_attention": DeepseekV41Attention, - "compressed_attention": DeepseekV41CompressedAttention, - "kv_shared_indexed_attention": DeepseekV41KVSharedIndexedAttention, - "kv_shared_attention": DeepseekV41KVSharedAttention, -} - - class DeepseekV41DecoderLayer(GradientCheckpointingLayer): r""" DeepSeek-V4.1 decoder block. As in DeepSeek-V4, the residual is a stack of `hc_mult` parallel streams of @@ -1094,7 +1010,7 @@ class DeepseekV41DecoderLayer(GradientCheckpointingLayer): def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): super().__init__() self.layer_idx = layer_idx - self.self_attn = DEEPSEEK_V41_ATTENTION_CLASSES[config.attention_layer_types[layer_idx]](config, 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) @@ -1243,6 +1159,67 @@ def forward(self, image_features: torch.Tensor, height: int, width: int) -> torc 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 @@ -1317,6 +1294,42 @@ def _init_weights(self, module): 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) + # 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) + @auto_docstring( custom_intro=""" @@ -1373,67 +1386,6 @@ def forward( return BaseModelOutput(last_hidden_state=self.norm(hidden_states)) -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( custom_intro=""" The DeepSeek-V4.1 language model, without the vision encoder and the language modeling head. @@ -1487,8 +1439,8 @@ def forward( 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: - past_seen = cache.get_seq_length() if cache is not None else 0 position_ids = torch.arange(seq_len, device=inputs_embeds.device) + past_seen position_ids = position_ids.unsqueeze(0) @@ -1526,6 +1478,18 @@ def forward( "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 entry + # `j` of a layer with ratio `r` rotates at position `j * r`. We count groups from the tokens that the + # cache has seen, and only rotate the entries of the groups that this call completes. + 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: + entry_ids = torch.arange( + past_seen // ratio, (past_seen + seq_len) // ratio, device=inputs_embeds.device + ) + compressed_position_embeddings[ratio] = self.rotary_emb( + inputs_embeds, position_ids=(entry_ids * ratio).unsqueeze(0), 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. Every source writes before the layers after it read. shared_states = {} @@ -1542,6 +1506,7 @@ def forward( engram_mask=engram_mask, image_mask=image_mask, position_embeddings=position_embeddings, + compressed_position_embeddings=compressed_position_embeddings, position_ids=position_ids, attention_mask=causal_mask, cache=cache, @@ -1554,38 +1519,6 @@ def forward( hidden_states = self.norm(hidden_states) return MoeModelOutputWithPast(last_hidden_state=hidden_states, cache=cache) - def set_engram_token_map(self, tokenizer_or_token_map): - """ - 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. - """ - if self.engram_hasher is None: - raise ValueError("This model has no Engram layers (`config.engram_layer_ids` is empty).") - 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 != self.config.engram_compressed_vocab_size: - raise ValueError( - f"The token map has {num_compressed_ids} compressed ids, but the model was trained with " - f"{self.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] > self.engram_hasher.token_map.shape[0]: - raise ValueError( - f"The token map has {token_map.shape[0]} entries, but the model only has " - f"{self.engram_hasher.token_map.shape[0]} tokens (`config.vocab_size`)." - ) - self.engram_hasher.token_map[: token_map.shape[0]] = token_map.to(self.engram_hasher.token_map.device) - @auto_docstring( custom_intro=""" @@ -1611,9 +1544,6 @@ def get_input_embeddings(self): def set_input_embeddings(self, value): self.language_model.embed_tokens = value - def set_engram_token_map(self, tokenizer_or_token_map): - self.language_model.set_engram_token_map(tokenizer_or_token_map) - @can_return_tuple @auto_docstring( custom_intro=""" @@ -1741,17 +1671,6 @@ def set_input_embeddings(self, value): def get_output_embeddings(self) -> nn.Module: return self.lm_head - def set_engram_token_map(self, tokenizer_or_token_map): - """ - 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. - """ - self.model.set_engram_token_map(tokenizer_or_token_map) - @can_return_tuple @auto_docstring @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") diff --git a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py index 62951e53b045..f5e7cd5f90d2 100644 --- a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py @@ -668,8 +668,16 @@ def forward( class DeepseekV41Attention(nn.Module): r""" - Sliding-window attention, which is all that the `"sliding_attention"` layers do. The other attention - variants add compressed KV on top of the window by overriding `get_compressed_kv`. + 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 @@ -679,12 +687,14 @@ class DeepseekV41Attention(nn.Module): * A learnable attention sink per head, and a grouped low-rank output projection. """ - rope_layer_type = "main" - 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 @@ -703,22 +713,10 @@ def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): ) 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)) - - def get_compressed_kv( - self, - hidden_states: torch.Tensor, - q_residual: torch.Tensor, - position_ids: torch.Tensor, - position_embeddings: tuple[torch.Tensor, torch.Tensor], - cache: Cache | None, - shared_states: dict[str, torch.Tensor], - ) -> tuple[torch.Tensor | None, torch.Tensor | None]: - """ - Returns the compressed KV entries of shape `(batch_size, num_entries, head_dim)` and a boolean mask of - shape `(batch_size, seq_len, num_entries)` that says which of them each query attends to. A - sliding-window-only layer has neither. - """ - return None, None + 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, @@ -727,6 +725,7 @@ def forward( attention_mask: 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]: input_shape = hidden_states.shape[:-1] @@ -743,14 +742,41 @@ def forward( if cache is not None: kv = cache.update(kv, kv, self.layer_idx)[0] - # 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 = self.get_compressed_kv( - hidden_states, q_residual, kwargs.get("position_ids"), (cos, sin), cache, shared_states - ) - if compressed_kv is not None: - # With a device map, the layer that made the compressed KV may sit on another device - compressed_kv, selected = compressed_kv.to(kv.device, kv.dtype), selected.to(kv.device) + if self.layer_type == "compressed_attention": + # This layer compresses the groups that this call completes. There may be 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 = self.compressor(hidden_states, cache_layer) + entry_cos, entry_sin = compressed_position_embeddings[self.compress_ratio] + # 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) + if cache_layer is not None: + compressed_kv, index_keys = cache_layer.update_compressed_states(compressed_kv, index_keys) + # 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. With a device map, the layers that + # made the index keys and the candidates may sit on another device. + candidates = shared_states.get("candidates") + shared_states["selected"], shared_states["candidates"] = self.indexer( + hidden_states, + q_residual, + shared_states["index_keys"].to(hidden_states.device), + kwargs.get("position_ids"), + (cos, sin), + candidates.to(hidden_states.device) if candidates is not None else None, + ) + + 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. With a device map, the + # layer that made the compressed KV may sit on another device. + compressed_kv = shared_states["compressed_kv"].to(kv.device, kv.dtype) + selected = shared_states["selected"].to(kv.device) kv = torch.cat([kv, compressed_kv.unsqueeze(1)], 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) @@ -782,116 +808,6 @@ def forward( return output, attn_weights -class DeepseekV41KVSharedAttention(DeepseekV41Attention): - """ - Attention over a sliding window, plus the compressed KV of the last `"compressed_attention"` layer. Which - compressed entries each query attends to is also reused, from the last layer that ran an indexer. - """ - - rope_layer_type = "compress" - - def get_compressed_kv( - self, - hidden_states: torch.Tensor, - q_residual: torch.Tensor, - position_ids: torch.Tensor, - position_embeddings: tuple[torch.Tensor, torch.Tensor], - cache: Cache | None, - shared_states: dict[str, torch.Tensor], - ) -> tuple[torch.Tensor | None, torch.Tensor | None]: - return shared_states["compressed_kv"], shared_states["selected"] - - -class DeepseekV41KVSharedIndexedAttention(DeepseekV41KVSharedAttention): - """ - Attention over a sliding window, plus the compressed KV of the last `"compressed_attention"` layer. This - layer runs its own indexer to select which compressed entries each query attends to, and the - `"kv_shared_attention"` layers after it reuse that selection. - """ - - def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): - super().__init__(config, layer_idx) - self.indexer = DeepseekV41Indexer(config, layer_idx) - - def get_compressed_kv( - self, - hidden_states: torch.Tensor, - q_residual: torch.Tensor, - position_ids: torch.Tensor, - position_embeddings: tuple[torch.Tensor, torch.Tensor], - cache: Cache | None, - shared_states: dict[str, torch.Tensor], - ) -> tuple[torch.Tensor | None, torch.Tensor | None]: - # With a device map, the layers that made the index keys and the candidates may sit on another device - candidates = shared_states.get("candidates") - shared_states["selected"], shared_states["candidates"] = self.indexer( - hidden_states, - q_residual, - shared_states["index_keys"].to(hidden_states.device), - position_ids, - position_embeddings, - candidates.to(hidden_states.device) if candidates is not None else None, - ) - return shared_states["compressed_kv"], shared_states["selected"] - - -class DeepseekV41CompressedAttention(DeepseekV41KVSharedIndexedAttention): - """ - Attention over a sliding window, plus KV that this layer compresses itself. It also makes the index keys - for those compressed KV and runs an indexer over them. The KV-sharing layers after it read all three: the - compressed KV, the index keys and the selection. - """ - - def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): - super().__init__(config, layer_idx) - self.compressor = DeepseekV41Compressor(config, layer_idx) - self.rotary_emb = DeepseekV41RotaryEmbedding(config) - - def get_compressed_kv( - self, - hidden_states: torch.Tensor, - q_residual: torch.Tensor, - position_ids: torch.Tensor, - position_embeddings: tuple[torch.Tensor, torch.Tensor], - cache: Cache | None, - shared_states: dict[str, torch.Tensor], - ) -> tuple[torch.Tensor | None, torch.Tensor | None]: - cache_layer: DeepseekV41CacheLayer | None = cache.layers[self.layer_idx] if cache is not None else None - num_previous_entries = cache_layer.num_compressed_entries if cache_layer is not None else 0 - - # First, compress the groups that this call completes. There may be none of them, e.g. when decoding - # a token that is not the last of its group. - latents = self.compressor(hidden_states, cache_layer) - batch_size, num_new_entries, _ = latents.shape - - # A latent stands for the first token of its group, so group `j` rotates at position `j * ratio` - positions = torch.arange(num_new_entries, device=latents.device) + num_previous_entries - positions = (positions * self.compressor.compress_ratio).unsqueeze(0).expand(batch_size, -1) - cos, sin = self.rotary_emb(latents, position_ids=positions, layer_type=self.rope_layer_type) - - # Next, make the index keys. They come from the latents before RoPE, so this has to happen before we - # rotate the latents themselves. - index_keys = self.indexer.k_norm(self.indexer.k_proj(latents)) - index_keys = apply_rotary_pos_emb(index_keys.unsqueeze(1), cos, sin).squeeze(1) - compressed_kv = apply_rotary_pos_emb(latents.unsqueeze(1), cos, sin).squeeze(1) - if cache_layer is not None: - compressed_kv, index_keys = cache_layer.update_compressed_states(compressed_kv, index_keys) - - # Finally, 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 - return super().get_compressed_kv( - hidden_states, q_residual, position_ids, position_embeddings, cache, shared_states - ) - - -DEEPSEEK_V41_ATTENTION_CLASSES = { - "sliding_attention": DeepseekV41Attention, - "compressed_attention": DeepseekV41CompressedAttention, - "kv_shared_indexed_attention": DeepseekV41KVSharedIndexedAttention, - "kv_shared_attention": DeepseekV41KVSharedAttention, -} - - class DeepseekV41HyperConnection(nn.Module): r""" Computes the hyper-connection weights of one sublayer (attention or MLP) from the `hc_mult` residual @@ -1231,7 +1147,7 @@ class DeepseekV41DecoderLayer(GradientCheckpointingLayer): def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): super().__init__() self.layer_idx = layer_idx - self.self_attn = DEEPSEEK_V41_ATTENTION_CLASSES[config.attention_layer_types[layer_idx]](config, 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) @@ -1454,6 +1370,42 @@ def _init_weights(self, module): 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) + # 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) + @auto_docstring( custom_intro=""" @@ -1563,8 +1515,8 @@ def forward( 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: - past_seen = cache.get_seq_length() if cache is not None else 0 position_ids = torch.arange(seq_len, device=inputs_embeds.device) + past_seen position_ids = position_ids.unsqueeze(0) @@ -1602,6 +1554,18 @@ def forward( "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 entry + # `j` of a layer with ratio `r` rotates at position `j * r`. We count groups from the tokens that the + # cache has seen, and only rotate the entries of the groups that this call completes. + 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: + entry_ids = torch.arange( + past_seen // ratio, (past_seen + seq_len) // ratio, device=inputs_embeds.device + ) + compressed_position_embeddings[ratio] = self.rotary_emb( + inputs_embeds, position_ids=(entry_ids * ratio).unsqueeze(0), 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. Every source writes before the layers after it read. shared_states = {} @@ -1618,6 +1582,7 @@ def forward( engram_mask=engram_mask, image_mask=image_mask, position_embeddings=position_embeddings, + compressed_position_embeddings=compressed_position_embeddings, position_ids=position_ids, attention_mask=causal_mask, cache=cache, @@ -1630,38 +1595,6 @@ def forward( hidden_states = self.norm(hidden_states) return MoeModelOutputWithPast(last_hidden_state=hidden_states, cache=cache) - def set_engram_token_map(self, tokenizer_or_token_map): - """ - 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. - """ - if self.engram_hasher is None: - raise ValueError("This model has no Engram layers (`config.engram_layer_ids` is empty).") - 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 != self.config.engram_compressed_vocab_size: - raise ValueError( - f"The token map has {num_compressed_ids} compressed ids, but the model was trained with " - f"{self.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] > self.engram_hasher.token_map.shape[0]: - raise ValueError( - f"The token map has {token_map.shape[0]} entries, but the model only has " - f"{self.engram_hasher.token_map.shape[0]} tokens (`config.vocab_size`)." - ) - self.engram_hasher.token_map[: token_map.shape[0]] = token_map.to(self.engram_hasher.token_map.device) - @auto_docstring( custom_intro=""" @@ -1687,9 +1620,6 @@ def get_input_embeddings(self): def set_input_embeddings(self, value): self.language_model.embed_tokens = value - def set_engram_token_map(self, tokenizer_or_token_map): - self.language_model.set_engram_token_map(tokenizer_or_token_map) - @can_return_tuple @auto_docstring( custom_intro=""" @@ -1817,17 +1747,6 @@ def set_input_embeddings(self, value): def get_output_embeddings(self) -> nn.Module: return self.lm_head - def set_engram_token_map(self, tokenizer_or_token_map): - """ - 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. - """ - self.model.set_engram_token_map(tokenizer_or_token_map) - @can_return_tuple @auto_docstring @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") From cf70035ba20d1d7a8fbb95494b36e5891fd2eb92 Mon Sep 17 00:00:00 2001 From: Matt Date: Wed, 18 Nov 2026 16:45:55 +0000 Subject: [PATCH 04/13] DeepSeek-V4.1: gradient checkpointing and the remaining common tests The layers now return the states that the KV-sharing layers read, instead of writing them into a dict shared by the whole stack. The backward replay of a checkpointed layer reads the same states as its first run, so checkpointing works with use_reentrant=False. use_reentrant=True raises, because it would silently drop the gradient of the shared compressed KV. Also skips the inputs_embeds tests (the Engram layers need token ids), moves the tester values into small_config_overrides, and skips the base model in test_reverse_loading_mapping. --- .../deepseek_v41/modeling_deepseek_v41.py | 62 ++++++--- .../deepseek_v41/modular_deepseek_v41.py | 62 ++++++--- .../test_modeling_deepseek_v41.py | 127 +++++++++++++++--- 3 files changed, 189 insertions(+), 62 deletions(-) diff --git a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py index 9e4c1d6d399d..42ee486a8aaf 100644 --- a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py @@ -594,8 +594,12 @@ def forward( 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]: + ) -> 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] @@ -626,25 +630,21 @@ def forward( 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. With a device map, the layers that - # made the index keys and the candidates may sit on another device. - candidates = shared_states.get("candidates") + # `"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"].to(hidden_states.device), + shared_states["index_keys"], kwargs.get("position_ids"), (cos, sin), - candidates.to(hidden_states.device) if candidates is not None else None, + 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. With a device map, the - # layer that made the compressed KV may sit on another device. - compressed_kv = shared_states["compressed_kv"].to(kv.device, kv.dtype) - selected = shared_states["selected"].to(kv.device) - kv = torch.cat([kv, compressed_kv.unsqueeze(1)], dim=2) + # 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) @@ -672,7 +672,7 @@ def forward( grouped = attn_output.reshape(*input_shape, self.config.o_groups, -1) grouped = self.o_a_proj(grouped).flatten(2) output = self.o_b_proj(grouped) - return output, attn_weights + return output, attn_weights, shared_states class DeepseekV41HyperConnection(nn.Module): @@ -1025,8 +1025,9 @@ def forward( 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]: + ) -> 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 @@ -1035,7 +1036,9 @@ def forward( attn_pre, post, comb = self.attn_hc(hidden_states) collapsed = (pre.unsqueeze(-1) * hidden_states.float()).sum(dim=2).to(dtype) - attn_output, _ = self.self_attn(self.input_layernorm(collapsed), **kwargs) + 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() ) @@ -1047,7 +1050,7 @@ def forward( 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 + return hidden_states.to(dtype), mlp_pre, shared_states def vision_eager_attention_forward( @@ -1227,9 +1230,6 @@ class DeepseekV41PreTrainedModel(PreTrainedModel): input_modalities = ("image", "text") supports_gradient_checkpointing = True _no_split_modules = ["DeepseekV41DecoderLayer", "DeepseekV41VisionLayer"] - # The layers write into `shared_states` for the layers after them, so the device hooks must hand every - # layer the same dict rather than a copy of it moved to the layer's device - _skip_keys_device_placement = ["cache", "shared_states"] # 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. @@ -1294,6 +1294,27 @@ def _init_weights(self, module): 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. @@ -1491,11 +1512,12 @@ def forward( inputs_embeds, position_ids=(entry_ids * ratio).unsqueeze(0), 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. Every source writes before the layers after it read. + # 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 = layer( + hidden_states, pre, shared_states = layer( hidden_states, pre, engram_hash_ids=( diff --git a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py index f5e7cd5f90d2..14be4dc25813 100644 --- a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py @@ -727,8 +727,12 @@ def forward( 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]: + ) -> 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] @@ -759,25 +763,21 @@ def forward( 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. With a device map, the layers that - # made the index keys and the candidates may sit on another device. - candidates = shared_states.get("candidates") + # `"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"].to(hidden_states.device), + shared_states["index_keys"], kwargs.get("position_ids"), (cos, sin), - candidates.to(hidden_states.device) if candidates is not None else None, + 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. With a device map, the - # layer that made the compressed KV may sit on another device. - compressed_kv = shared_states["compressed_kv"].to(kv.device, kv.dtype) - selected = shared_states["selected"].to(kv.device) - kv = torch.cat([kv, compressed_kv.unsqueeze(1)], dim=2) + # 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) @@ -805,7 +805,7 @@ def forward( grouped = attn_output.reshape(*input_shape, self.config.o_groups, -1) grouped = self.o_a_proj(grouped).flatten(2) output = self.o_b_proj(grouped) - return output, attn_weights + return output, attn_weights, shared_states class DeepseekV41HyperConnection(nn.Module): @@ -1162,8 +1162,9 @@ def forward( 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]: + ) -> 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 @@ -1172,7 +1173,9 @@ def forward( attn_pre, post, comb = self.attn_hc(hidden_states) collapsed = (pre.unsqueeze(-1) * hidden_states.float()).sum(dim=2).to(dtype) - attn_output, _ = self.self_attn(self.input_layernorm(collapsed), **kwargs) + 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() ) @@ -1184,7 +1187,7 @@ def forward( 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 + return hidden_states.to(dtype), mlp_pre, shared_states def vision_eager_attention_forward( @@ -1303,9 +1306,6 @@ class DeepseekV41PreTrainedModel(PreTrainedModel): input_modalities = ("image", "text") supports_gradient_checkpointing = True _no_split_modules = ["DeepseekV41DecoderLayer", "DeepseekV41VisionLayer"] - # The layers write into `shared_states` for the layers after them, so the device hooks must hand every - # layer the same dict rather than a copy of it moved to the layer's device - _skip_keys_device_placement = ["cache", "shared_states"] # 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. @@ -1370,6 +1370,27 @@ def _init_weights(self, module): 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. @@ -1567,11 +1588,12 @@ def forward( inputs_embeds, position_ids=(entry_ids * ratio).unsqueeze(0), 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. Every source writes before the layers after it read. + # 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 = layer( + hidden_states, pre, shared_states = layer( hidden_states, pre, engram_hash_ids=( diff --git a/tests/models/deepseek_v41/test_modeling_deepseek_v41.py b/tests/models/deepseek_v41/test_modeling_deepseek_v41.py index bfb7b72c4ba0..8cdd7a1c2f25 100644 --- a/tests/models/deepseek_v41/test_modeling_deepseek_v41.py +++ b/tests/models/deepseek_v41/test_modeling_deepseek_v41.py @@ -13,8 +13,10 @@ # limitations under the License. import copy import unittest +import unittest.mock 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 @@ -34,29 +36,29 @@ from ...test_configuration_common import ConfigTester +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(CausalLMModelTester): if is_torch_available(): base_model_class = DeepseekV41Model config_class = DeepseekV41Config causal_lm_class = DeepseekV41ForCausalLM - def __init__(self, parent, **kwargs): - super().__init__(parent, **kwargs) - self.hidden_size = 64 - self.num_attention_heads = 4 - self.num_hidden_layers = 5 - self.seq_length = 11 - self.batch_size = 3 - # The inputs are text only, so the image token must not show up in the random ids - self.image_token_id = self.vocab_size - self.text_config = { - "vocab_size": self.vocab_size + 1, - "hidden_size": self.hidden_size, + small_config_overrides = { + "batch_size": 3, + "seq_length": 11, + "hidden_size": 64, + "num_hidden_layers": 5, + "num_attention_heads": 4, + "text_config": { "moe_intermediate_size": 32, - "num_hidden_layers": self.num_hidden_layers, - "num_attention_heads": self.num_attention_heads, "head_dim": 32, - "partial_rotary_factor": 8 / 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, @@ -85,24 +87,41 @@ def __init__(self, parent, **kwargs): "engram_n_heads": 2, "engram_head_dim": 8, "engram_pad_token_id": 2, - # As large as the vocab, so that no tokens are merged and the model works without a tokenizer - "engram_compressed_vocab_size": self.vocab_size + 1, "engram_num_embeddings": None, "num_nextn_predict_layers": 0, "dspark_noise_token_id": 3, "rms_norm_eps": 1e-6, - "pad_token_id": self.pad_token_id, - "bos_token_id": self.bos_token_id, - "eos_token_id": self.eos_token_id, - } - self.vision_config = { + }, + "vision_config": { "hidden_size": 32, "num_hidden_layers": 2, "num_attention_heads": 4, "intermediate_size": 48, "patch_size": 2, "downsample_ratio": 3, + }, + } + + @classmethod + def get_small_config_defaults(cls, **kwargs): + values = super().get_small_config_defaults(**kwargs) + # The inputs are text only, so the image token must not show up in the random ids + values["image_token_id"] = values["vocab_size"] + # The text config takes its sizes and special tokens from the tester, so that the common tests can + # read them there. Its vocab has one more id than the tester's, for the image token. + values["text_config"] = { + **values["text_config"], + "vocab_size": values["vocab_size"] + 1, + "hidden_size": values["hidden_size"], + "num_hidden_layers": values["num_hidden_layers"], + "num_attention_heads": values["num_attention_heads"], + # As large as the vocab, so that no tokens are merged and the model works without a tokenizer + "engram_compressed_vocab_size": values["vocab_size"] + 1, + "pad_token_id": values["pad_token_id"], + "bos_token_id": values["bos_token_id"], + "eos_token_id": values["eos_token_id"], } + return values def get_config(self): return DeepseekV41Config( @@ -225,6 +244,70 @@ def test_hidden_states_output(self): def test_left_padding_compatibility(self): pass + 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=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 check_training_gradient_checkpointing(self, gradient_checkpointing_kwargs=None): + # The common check watches the first checkpointing layer of the model, which is a vision layer. The + # common inputs are text only, so we put an image at the start of the first row to make that layer run. + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + # 4 x 5 patches are merged 3 x 3 into 2 x 2 tokens, so the image takes 1 + 2 * (2 + 1) + 1 positions + height, width, num_image_tokens = 4, 5, 8 + inputs_dict["input_ids"][0, :num_image_tokens] = config.image_token_id + inputs_dict["pixel_values"] = torch.randn( + height * width, 3 * config.vision_config.patch_size**2, device=torch_device + ) + inputs_dict["image_grid_hw"] = torch.tensor([[height, width]], device=torch_device) + with unittest.mock.patch.object( + self.model_tester, "prepare_config_and_inputs_for_common", return_value=(config, inputs_dict) + ): + super().check_training_gradient_checkpointing(gradient_checkpointing_kwargs) + + 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 = torch.randint(0, self.model_tester.vocab_size, (2, 23), device=torch_device) + 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) From b8cfbc942fd6f071f13a25e8ccad63fb7ffd4a04 Mon Sep 17 00:00:00 2001 From: Matt Date: Wed, 18 Nov 2026 17:36:59 +0000 Subject: [PATCH 05/13] DeepSeek-V4.1: image processor and processor The image processor follows the original preprocessing: each image keeps its aspect ratio, is resized to whole 14x14 patches within the min-pixel and max-token limits, and is padded with gray. It resizes with torchvision where the original uses PIL, so the sizes and the padding are identical, but resampled pixel values can be off by a level or two out of 255. The processor repeats the image placeholder once for every position that the image takes up in the prompt. The model is also registered for image-text-to-text. --- docs/source/en/model_doc/deepseek_v41.md | 51 ++- src/transformers/models/auto/auto_mappings.py | 2 + src/transformers/models/auto/modeling_auto.py | 1 + .../models/deepseek_v41/__init__.py | 2 + .../configuration_deepseek_v41.py | 2 +- .../image_processing_deepseek_v41.py | 286 +++++++++++++++++ .../deepseek_v41/modular_deepseek_v41.py | 297 +++++++++++++++++- .../deepseek_v41/processing_deepseek_v41.py | 49 +++ .../test_image_processing_deepseek_v41.py | 165 ++++++++++ .../test_processing_deepseek_v41.py | 120 +++++++ 10 files changed, 969 insertions(+), 6 deletions(-) create mode 100644 src/transformers/models/deepseek_v41/image_processing_deepseek_v41.py create mode 100644 src/transformers/models/deepseek_v41/processing_deepseek_v41.py create mode 100644 tests/models/deepseek_v41/test_image_processing_deepseek_v41.py create mode 100644 tests/models/deepseek_v41/test_processing_deepseek_v41.py diff --git a/docs/source/en/model_doc/deepseek_v41.md b/docs/source/en/model_doc/deepseek_v41.md index 96412f6c8b9f..b7c6f0b1d1b1 100644 --- a/docs/source/en/model_doc/deepseek_v41.md +++ b/docs/source/en/model_doc/deepseek_v41.md @@ -67,14 +67,51 @@ 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. - Batched generation with left padding does not match unpadded generation yet. The compressor pools consecutive tokens, so padding shifts its groups. - The DSpark draft layers of the checkpoint (`mtp.*`) are not loaded. -- There is no image processor yet. Images go in as `pixel_values` (the flattened patches of all the images) and - `image_grid_hw` (the height and width of each image's patch grid). +- 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 @@ -88,6 +125,16 @@ wrong ids. [[autodoc]] DeepseekV41VisionConfig +## DeepseekV41ImageProcessor + +[[autodoc]] DeepseekV41ImageProcessor + - preprocess + +## DeepseekV41Processor + +[[autodoc]] DeepseekV41Processor + - __call__ + ## DeepseekV41VisionModel [[autodoc]] DeepseekV41VisionModel diff --git a/src/transformers/models/auto/auto_mappings.py b/src/transformers/models/auto/auto_mappings.py index a8108d7d9c04..e2c13ae042ad 100644 --- a/src/transformers/models/auto/auto_mappings.py +++ b/src/transformers/models/auto/auto_mappings.py @@ -1270,6 +1270,7 @@ ("cosmos3_edge", "Cosmos3EdgeProcessor"), ("csm", "CsmProcessor"), ("deepseek_ocr2", "DeepseekOcr2Processor"), + ("deepseek_v41", "DeepseekV41Processor"), ("deepseek_vl", "DeepseekVLProcessor"), ("deepseek_vl_hybrid", "DeepseekVLHybridProcessor"), ("dia", "DiaProcessor"), @@ -1432,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 2282f3d85583..7f2410ac86c2 100644 --- a/src/transformers/models/auto/modeling_auto.py +++ b/src/transformers/models/auto/modeling_auto.py @@ -1206,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 index 5bd6e7f63355..8c12c6b62400 100644 --- a/src/transformers/models/deepseek_v41/__init__.py +++ b/src/transformers/models/deepseek_v41/__init__.py @@ -25,7 +25,9 @@ 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 diff --git a/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py b/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py index 66d262bfb00e..807f4f113a5b 100644 --- a/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py @@ -37,7 +37,7 @@ class DeepseekV41VisionConfig(PreTrainedConfig): 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 ratio are cropped down to it. Only used for preprocessing. + Images wider than this width-to-height ratio are squashed to it. Only used for preprocessing. """ model_type = "deepseek_v41_vision" 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..84a34d878f5d --- /dev/null +++ b/src/transformers/models/deepseek_v41/image_processing_deepseek_v41.py @@ -0,0 +1,286 @@ +# ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ +# 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_hw"] + + 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_hw = [], [] + 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)) + image_grid_hw.append([rows, columns]) + return BatchFeature( + data={"pixel_values": torch.cat(patches), "image_grid_hw": torch.tensor(image_grid_hw)}, + tensor_type=return_tensors, + ) + + +__all__ = ["DeepseekV41ImageProcessor"] diff --git a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py index 14be4dc25813..c2c3f6dc494a 100644 --- a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py @@ -11,6 +11,7 @@ # 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 @@ -18,11 +19,15 @@ 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_sliding_window_causal_mask from ...modeling_layers import GradientCheckpointingLayer @@ -34,8 +39,15 @@ ) from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel -from ...processing_utils import Unpack -from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging, torch_compilable_check +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 @@ -76,7 +88,7 @@ class DeepseekV41VisionConfig(PreTrainedConfig): 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 ratio are cropped down to it. Only used for preprocessing. + Images wider than this width-to-height ratio are squashed to it. Only used for preprocessing. """ model_type = "deepseek_v41_vision" @@ -1851,6 +1863,283 @@ def prepare_inputs_for_generation( return model_inputs +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_hw"] + + 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_hw = [], [] + 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)) + image_grid_hw.append([rows, columns]) + return BatchFeature( + data={"pixel_values": torch.cat(patches), "image_grid_hw": torch.tensor(image_grid_hw)}, + 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(side) for side in image_inputs["image_grid_hw"][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", @@ -1860,4 +2149,6 @@ def prepare_inputs_for_generation( "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..5279ca4b6def --- /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(side) for side in image_inputs["image_grid_hw"][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/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..61df31aa156a --- /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_hw.tolist(), [[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_hw.tolist(), [[6, 9], [3, 5], [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_hw.tolist(), [[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_hw.tolist(), [[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_hw.tolist(), [[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_processing_deepseek_v41.py b/tests/models/deepseek_v41/test_processing_deepseek_v41.py new file mode 100644 index 000000000000..a0d004afc4c4 --- /dev/null +++ b/tests/models/deepseek_v41/test_processing_deepseek_v41.py @@ -0,0 +1,120 @@ +# 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 parameterized import parameterized + +from transformers import AutoTokenizer, DeepseekV41Processor, is_torch_available +from transformers.testing_utils import require_torch, require_torchvision, require_vision + +from ...test_processing_common import MODALITY_INPUT_DATA, 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 + # The input with one row per image. `pixel_values` has one row per patch. + image_grid_input_name = "image_grid_hw" + + @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) + + @parameterized.expand([(1, "pt"), (2, "pt")]) + def test_apply_chat_template_image(self, batch_size: int, return_tensors: str): + # Same as the common test, except that it expects one entry per image in the image input. Here that is + # the grid sizes rather than `pixel_values`. + self._test_apply_chat_template( + "image", + batch_size, + return_tensors, + "image_grid_input_name", + "image_processor", + MODALITY_INPUT_DATA["images"], + ) + + 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_hw"].tolist(), [[6, 9], [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_hw"].tolist(), [[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_hw"]) + num_positions = int((inputs["input_ids"] == processor.image_token_id).sum()) + self.assertEqual(image_features.pooler_output[0].shape[0], num_positions) From fef7ef9b0e3924b9c3ee933ada9eefa8bc011e62 Mon Sep 17 00:00:00 2001 From: Matt Date: Thu, 19 Nov 2026 18:37:13 +0000 Subject: [PATCH 06/13] DeepSeek-V4.1: image_grid_thw, and no embedding resizing The grid input is now `image_grid_thw`, the name that most models with native-resolution images use and that the common tests know about. An image is one frame, so the temporal size is always 1, and the model raises on anything else. The common chat template test now runs as it is, so its override in the processor tests is gone. `resize_token_embeddings` raises an error. The Engram token map and the n-gram tables are fixed to the vocabulary of the checkpoint, so a new token would have no entry in them. The common resize tests are disabled with `test_resize_embeddings = False`. --- docs/source/en/model_doc/deepseek_v41.md | 3 + .../image_processing_deepseek_v41.py | 9 +-- .../deepseek_v41/modeling_deepseek_v41.py | 61 +++++++++++----- .../deepseek_v41/modular_deepseek_v41.py | 72 +++++++++++++------ .../deepseek_v41/processing_deepseek_v41.py | 2 +- .../test_image_processing_deepseek_v41.py | 10 +-- .../test_modeling_deepseek_v41.py | 42 +++++++---- .../test_processing_deepseek_v41.py | 24 ++----- 8 files changed, 141 insertions(+), 82 deletions(-) diff --git a/docs/source/en/model_doc/deepseek_v41.md b/docs/source/en/model_doc/deepseek_v41.md index b7c6f0b1d1b1..6f91907d375c 100644 --- a/docs/source/en/model_doc/deepseek_v41.md +++ b/docs/source/en/model_doc/deepseek_v41.md @@ -107,6 +107,9 @@ 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 does not match unpadded generation yet. The compressor pools consecutive tokens, so padding shifts its groups. - The DSpark draft layers of the checkpoint (`mtp.*`) are not loaded. diff --git a/src/transformers/models/deepseek_v41/image_processing_deepseek_v41.py b/src/transformers/models/deepseek_v41/image_processing_deepseek_v41.py index 84a34d878f5d..351963314bdb 100644 --- a/src/transformers/models/deepseek_v41/image_processing_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/image_processing_deepseek_v41.py @@ -158,7 +158,7 @@ class DeepseekV41ImageProcessor(TorchvisionBackend): min_pixels = 295936 max_wh_ratio = None valid_kwargs = DeepseekV41ImageProcessorKwargs - model_input_names = ["pixel_values", "image_grid_hw"] + model_input_names = ["pixel_values", "image_grid_thw"] def __init__(self, **kwargs: Unpack[DeepseekV41ImageProcessorKwargs]): super().__init__(**kwargs) @@ -251,7 +251,7 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: - patches, image_grid_hw = [], [] + patches, image_grid_thw = [], [] for image in images: channels, height, width = image.shape if do_resize: @@ -276,9 +276,10 @@ def _preprocess( 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)) - image_grid_hw.append([rows, columns]) + # 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_hw": torch.tensor(image_grid_hw)}, + data={"pixel_values": torch.cat(patches), "image_grid_thw": torch.tensor(image_grid_thw)}, tensor_type=return_tensors, ) diff --git a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py index 42ee486a8aaf..699a34e0ab25 100644 --- a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py @@ -1351,6 +1351,26 @@ def set_engram_token_map(self, tokenizer_or_token_map): # trf-ignore: TRF033 ) 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=""" @@ -1575,18 +1595,25 @@ def set_input_embeddings(self, value): """ ) def get_image_features( - self, pixel_values: torch.Tensor, image_grid_hw: torch.LongTensor, **kwargs: Unpack[TransformersKwargs] + 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_hw (`torch.LongTensor` of shape `(num_images, 2)`): - The height and width of each image's patch grid. + 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_hw.tolist() - patches_per_image = pixel_values.split([height * width for height, width in grids]) + 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): + 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 @@ -1623,7 +1650,7 @@ def forward( self, input_ids: torch.LongTensor | None = None, pixel_values: torch.Tensor | None = None, - image_grid_hw: torch.LongTensor | 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, @@ -1634,8 +1661,8 @@ def forward( 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_hw (`torch.LongTensor` of shape `(num_images, 2)`, *optional*): - The height and width of each image's patch grid. + 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") @@ -1647,14 +1674,14 @@ def forward( if pixel_values is not None: if image_mask is None: raise ValueError("`input_ids` are needed to find where the images go in the prompt.") - image_features = self.get_image_features(pixel_values, image_grid_hw, return_dict=True).pooler_output + image_features = self.get_image_features(pixel_values, image_grid_thw, return_dict=True).pooler_output image_features = torch.cat(image_features).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 (`image_grid_hw`: {image_grid_hw})." + f"{image_features.shape[0]} tokens (`image_grid_thw`: {image_grid_thw})." ), ) inputs_embeds = inputs_embeds.masked_scatter(image_mask.unsqueeze(-1), image_features) @@ -1700,7 +1727,7 @@ def forward( self, input_ids: torch.LongTensor | None = None, pixel_values: torch.Tensor | None = None, - image_grid_hw: torch.LongTensor | 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, @@ -1713,8 +1740,8 @@ def forward( 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_hw (`torch.LongTensor` of shape `(num_images, 2)`, *optional*): - The height and width of each image's patch grid. + 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 @@ -1723,7 +1750,7 @@ def forward( outputs: MoeModelOutputWithPast = self.model( input_ids=input_ids, pixel_values=pixel_values, - image_grid_hw=image_grid_hw, + image_grid_thw=image_grid_thw, attention_mask=attention_mask, position_ids=position_ids, cache=cache, @@ -1755,7 +1782,7 @@ def prepare_inputs_for_generation( cache=None, inputs_embeds=None, pixel_values=None, - image_grid_hw=None, + image_grid_thw=None, attention_mask=None, is_first_iteration=False, **kwargs, @@ -1771,7 +1798,7 @@ def prepare_inputs_for_generation( # The images are merged into the prompt on the first step, and after that they are in the cache if is_first_iteration or not kwargs.get("use_cache", True): model_inputs["pixel_values"] = pixel_values - model_inputs["image_grid_hw"] = image_grid_hw + model_inputs["image_grid_thw"] = image_grid_thw return model_inputs diff --git a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py index c2c3f6dc494a..f79e439a37b0 100644 --- a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py @@ -1439,6 +1439,26 @@ def set_engram_token_map(self, tokenizer_or_token_map): # trf-ignore: TRF033 ) 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=""" @@ -1663,18 +1683,25 @@ def set_input_embeddings(self, value): """ ) def get_image_features( - self, pixel_values: torch.Tensor, image_grid_hw: torch.LongTensor, **kwargs: Unpack[TransformersKwargs] + 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_hw (`torch.LongTensor` of shape `(num_images, 2)`): - The height and width of each image's patch grid. + 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_hw.tolist() - patches_per_image = pixel_values.split([height * width for height, width in grids]) + 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): + 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 @@ -1711,7 +1738,7 @@ def forward( self, input_ids: torch.LongTensor | None = None, pixel_values: torch.Tensor | None = None, - image_grid_hw: torch.LongTensor | 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, @@ -1722,8 +1749,8 @@ def forward( 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_hw (`torch.LongTensor` of shape `(num_images, 2)`, *optional*): - The height and width of each image's patch grid. + 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") @@ -1735,14 +1762,14 @@ def forward( if pixel_values is not None: if image_mask is None: raise ValueError("`input_ids` are needed to find where the images go in the prompt.") - image_features = self.get_image_features(pixel_values, image_grid_hw, return_dict=True).pooler_output + image_features = self.get_image_features(pixel_values, image_grid_thw, return_dict=True).pooler_output image_features = torch.cat(image_features).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 (`image_grid_hw`: {image_grid_hw})." + f"{image_features.shape[0]} tokens (`image_grid_thw`: {image_grid_thw})." ), ) inputs_embeds = inputs_embeds.masked_scatter(image_mask.unsqueeze(-1), image_features) @@ -1788,7 +1815,7 @@ def forward( self, input_ids: torch.LongTensor | None = None, pixel_values: torch.Tensor | None = None, - image_grid_hw: torch.LongTensor | 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, @@ -1801,8 +1828,8 @@ def forward( 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_hw (`torch.LongTensor` of shape `(num_images, 2)`, *optional*): - The height and width of each image's patch grid. + 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 @@ -1811,7 +1838,7 @@ def forward( outputs: MoeModelOutputWithPast = self.model( input_ids=input_ids, pixel_values=pixel_values, - image_grid_hw=image_grid_hw, + image_grid_thw=image_grid_thw, attention_mask=attention_mask, position_ids=position_ids, cache=cache, @@ -1843,7 +1870,7 @@ def prepare_inputs_for_generation( cache=None, inputs_embeds=None, pixel_values=None, - image_grid_hw=None, + image_grid_thw=None, attention_mask=None, is_first_iteration=False, **kwargs, @@ -1859,7 +1886,7 @@ def prepare_inputs_for_generation( # The images are merged into the prompt on the first step, and after that they are in the cache if is_first_iteration or not kwargs.get("use_cache", True): model_inputs["pixel_values"] = pixel_values - model_inputs["image_grid_hw"] = image_grid_hw + model_inputs["image_grid_thw"] = image_grid_thw return model_inputs @@ -1992,7 +2019,7 @@ class DeepseekV41ImageProcessor(TorchvisionBackend): min_pixels = 295936 max_wh_ratio = None valid_kwargs = DeepseekV41ImageProcessorKwargs - model_input_names = ["pixel_values", "image_grid_hw"] + model_input_names = ["pixel_values", "image_grid_thw"] def __init__(self, **kwargs: Unpack[DeepseekV41ImageProcessorKwargs]): super().__init__(**kwargs) @@ -2085,7 +2112,7 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: - patches, image_grid_hw = [], [] + patches, image_grid_thw = [], [] for image in images: channels, height, width = image.shape if do_resize: @@ -2110,9 +2137,10 @@ def _preprocess( 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)) - image_grid_hw.append([rows, columns]) + # 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_hw": torch.tensor(image_grid_hw)}, + data={"pixel_values": torch.cat(patches), "image_grid_thw": torch.tensor(image_grid_thw)}, tensor_type=return_tensors, ) @@ -2133,7 +2161,7 @@ def replace_image_token(self, image_inputs: dict, image_idx: int, **kwargs) -> s # 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(side) for side in image_inputs["image_grid_hw"][image_idx]) + _, 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. diff --git a/src/transformers/models/deepseek_v41/processing_deepseek_v41.py b/src/transformers/models/deepseek_v41/processing_deepseek_v41.py index 5279ca4b6def..e3b63d1d2108 100644 --- a/src/transformers/models/deepseek_v41/processing_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/processing_deepseek_v41.py @@ -39,7 +39,7 @@ def replace_image_token(self, image_inputs: dict, image_idx: int, **kwargs) -> s # 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(side) for side in image_inputs["image_grid_hw"][image_idx]) + _, 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. diff --git a/tests/models/deepseek_v41/test_image_processing_deepseek_v41.py b/tests/models/deepseek_v41/test_image_processing_deepseek_v41.py index 61df31aa156a..037355d093a0 100644 --- a/tests/models/deepseek_v41/test_image_processing_deepseek_v41.py +++ b/tests/models/deepseek_v41/test_image_processing_deepseek_v41.py @@ -100,7 +100,7 @@ def test_patches_and_grid(self): 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_hw.tolist(), [[6, 9]]) + 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()) @@ -113,7 +113,7 @@ def test_several_images(self): 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_hw.tolist(), [[6, 9], [3, 5], [15, 15]]) + 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): @@ -133,7 +133,7 @@ def test_padding_matches_original_preprocessing(self): 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_hw.tolist(), [[rows, columns]]) + self.assertEqual(encoding.image_grid_thw.tolist(), [[1, rows, columns]]) torch.testing.assert_close(encoding.pixel_values, expected) def test_transparency_is_dropped(self): @@ -152,7 +152,7 @@ def test_max_wh_ratio(self): image = Image.new("RGB", (60, 10), (200, 50, 10)) encoding = image_processor(image, return_tensors="pt") - self.assertEqual(encoding.image_grid_hw.tolist(), [[5, 10]]) + 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) @@ -160,6 +160,6 @@ def test_max_wh_ratio(self): 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_hw.tolist(), [[6, 9]]) + 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 index 8cdd7a1c2f25..499627037198 100644 --- a/tests/models/deepseek_v41/test_modeling_deepseek_v41.py +++ b/tests/models/deepseek_v41/test_modeling_deepseek_v41.py @@ -140,6 +140,8 @@ class DeepseekV41ModelTest(CausalLMModelTest, unittest.TestCase): # 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 def setUp(self): super().setUp() @@ -154,10 +156,10 @@ def is_pipeline_test_to_skip(self, *args, **kwargs): def _image_features_prepare_config_and_inputs(self): # The common inputs are text only, so we make the image inputs here: two images with different grids config = self.model_tester.get_config() - image_grid_hw = torch.tensor([[5, 7], [3, 6]], device=torch_device) - num_patches = int(image_grid_hw.prod(-1).sum()) + image_grid_thw = torch.tensor([[1, 5, 7], [1, 3, 6]], device=torch_device) + num_patches = int(image_grid_thw.prod(-1).sum()) pixel_values = torch.randn(num_patches, 3 * config.vision_config.patch_size**2, device=torch_device) - return config, {"pixel_values": pixel_values, "image_grid_hw": image_grid_hw} + return config, {"pixel_values": pixel_values, "image_grid_thw": image_grid_thw} def _check_attentions_for_generate( self, batch_size, attentions, prompt_length, output_length, config, decoder_cache @@ -276,7 +278,7 @@ def check_training_gradient_checkpointing(self, gradient_checkpointing_kwargs=No inputs_dict["pixel_values"] = torch.randn( height * width, 3 * config.vision_config.patch_size**2, device=torch_device ) - inputs_dict["image_grid_hw"] = torch.tensor([[height, width]], device=torch_device) + inputs_dict["image_grid_thw"] = torch.tensor([[1, height, width]], device=torch_device) with unittest.mock.patch.object( self.model_tester, "prepare_config_and_inputs_for_common", return_value=(config, inputs_dict) ): @@ -441,6 +443,13 @@ def test_engram_token_map_must_be_set(self): 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_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 @@ -457,14 +466,16 @@ def test_image_and_text_forward(self): # 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_hw = torch.tensor([[height, width]], device=torch_device) + image_grid_thw = torch.tensor([[1, height, width]], device=torch_device) text = torch.randint(0, self.model_tester.vocab_size, (1, 12), device=torch_device) 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_hw).pooler_output[0] - logits = model(input_ids=input_ids, pixel_values=pixel_values, image_grid_hw=image_grid_hw).logits - other_image = model(input_ids=input_ids, pixel_values=pixel_values + 1, image_grid_hw=image_grid_hw).logits + 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) @@ -477,20 +488,25 @@ def test_image_and_text_forward(self): # 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_hw=image_grid_hw) + 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_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_hw = torch.tensor([[5, 7], [3, 6]], device=torch_device) + 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_hw, output_hidden_states=True, output_attentions=True + pixel_values, image_grid_thw, output_hidden_states=True, output_attentions=True ) - first = model.model.get_image_features(pixel_values[:35], image_grid_hw[:1], output_attentions=True) - second = model.model.get_image_features(pixel_values[35:], image_grid_hw[1:], 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]) diff --git a/tests/models/deepseek_v41/test_processing_deepseek_v41.py b/tests/models/deepseek_v41/test_processing_deepseek_v41.py index a0d004afc4c4..aa3bbd530379 100644 --- a/tests/models/deepseek_v41/test_processing_deepseek_v41.py +++ b/tests/models/deepseek_v41/test_processing_deepseek_v41.py @@ -14,12 +14,11 @@ import unittest import numpy as np -from parameterized import parameterized from transformers import AutoTokenizer, DeepseekV41Processor, is_torch_available from transformers.testing_utils import require_torch, require_torchvision, require_vision -from ...test_processing_common import MODALITY_INPUT_DATA, ProcessorTesterMixin +from ...test_processing_common import ProcessorTesterMixin from .test_modeling_deepseek_v41 import DeepseekV41ModelTester @@ -34,8 +33,6 @@ @require_torchvision class DeepseekV41ProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = DeepseekV41Processor - # The input with one row per image. `pixel_values` has one row per patch. - image_grid_input_name = "image_grid_hw" @classmethod def _setup_image_processor(cls): @@ -53,19 +50,6 @@ def _setup_tokenizer(cls): def _image(height, width): return np.random.randint(0, 256, (height, width, 3), dtype=np.uint8) - @parameterized.expand([(1, "pt"), (2, "pt")]) - def test_apply_chat_template_image(self, batch_size: int, return_tensors: str): - # Same as the common test, except that it expects one entry per image in the image input. Here that is - # the grid sizes rather than `pixel_values`. - self._test_apply_chat_template( - "image", - batch_size, - return_tensors, - "image_grid_input_name", - "image_processor", - MODALITY_INPUT_DATA["images"], - ) - def test_image_placeholder_expansion(self): """Each placeholder is repeated once per position of its image: `rows * (columns + 1) + 2`.""" processor = self.get_processor() @@ -74,7 +58,7 @@ def test_image_placeholder_expansion(self): text = f"First {processor.image_token} then {processor.image_token}." inputs = processor(text=text, images=images, return_tensors="pt") - self.assertEqual(inputs["image_grid_hw"].tolist(), [[6, 9], [3, 5]]) + 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)) @@ -103,7 +87,7 @@ def test_chat_template_with_images(self): inputs = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt" ) - self.assertEqual(inputs["image_grid_hw"].tolist(), [[6, 9]]) + 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): @@ -115,6 +99,6 @@ def test_image_positions_match_the_model(self): 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_hw"]) + 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) From 3075544a75ea73469ac088b51022268a1249388c Mon Sep 17 00:00:00 2001 From: Matt Date: Mon, 23 Nov 2026 11:55:49 +0000 Subject: [PATCH 07/13] DeepSeek-V4.1: create the fp32 modules in fp32 The sinks, the hyper-connections and the router biases are listed in `_keep_in_fp32_modules_strict`, but only `from_pretrained` enforces that list. A model built straight from a config got them in the default dtype, which the common test from #50975 now catches. They are created in float32 in their `__init__` instead. --- .../models/deepseek_v41/modeling_deepseek_v41.py | 12 +++++++----- .../models/deepseek_v41/modular_deepseek_v41.py | 10 ++++++---- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py index 699a34e0ab25..ae039434efdb 100644 --- a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py @@ -579,7 +579,7 @@ def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): 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)) + 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": @@ -800,8 +800,8 @@ def __init__(self, config: DeepseekV41TextConfig): 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)) - self.e_score_correction_bias_vl = nn.Buffer(torch.zeros(self.num_experts)) + 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 @@ -1014,8 +1014,8 @@ def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): 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) - self.ffn_hc = DeepseekV41HyperConnection(config) + 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( @@ -1241,6 +1241,8 @@ class DeepseekV41PreTrainedModel(PreTrainedModel): _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", diff --git a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py index f79e439a37b0..efc414f7657f 100644 --- a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py @@ -724,7 +724,7 @@ def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): 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)) + 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": @@ -889,7 +889,7 @@ class DeepseekV41TopKRouter(DeepseekV4TopKRouter): def __init__(self, config: DeepseekV41TextConfig): super().__init__(config) - self.e_score_correction_bias_vl = nn.Buffer(torch.zeros(self.num_experts)) + 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 @@ -1163,8 +1163,8 @@ def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): 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) - self.ffn_hc = DeepseekV41HyperConnection(config) + 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( @@ -1329,6 +1329,8 @@ class DeepseekV41PreTrainedModel(PreTrainedModel): _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", From d5891e418f944e964e6cb33e77d2574a84eadbae Mon Sep 17 00:00:00 2001 From: Matt Date: Mon, 23 Nov 2026 11:59:07 +0000 Subject: [PATCH 08/13] DeepSeek-V4.1: images in beam search, and the shared VLM tester `generate` repeats its inputs once per beam, and `pixel_values` has a row per patch, so every beam got the patches of a scrambled image. The model now takes `mm_encoder_outputs`, so `generate` encodes the images once and repeats whole images, and it returns the multimodal outputs with `image_outputs`. The `prepare_inputs_for_generation` override is gone. The new beam test fails on the old code: the common beam tests only check output shapes. The tests move from `CausalLMModelTester` to `VLMModelTester`, like the other VLMs, so the common tests run with an image in every prompt. The image token is an id inside the tester's vocab, and the text ids are drawn from above the special tokens. --- .../deepseek_v41/modeling_deepseek_v41.py | 63 ++--- .../deepseek_v41/modular_deepseek_v41.py | 63 ++--- .../test_modeling_deepseek_v41.py | 243 +++++++++--------- 3 files changed, 181 insertions(+), 188 deletions(-) diff --git a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py index ae039434efdb..1ceae132fe21 100644 --- a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py @@ -34,8 +34,9 @@ from ...modeling_outputs import ( BaseModelOutput, BaseModelOutputWithPooling, - MoeCausalLMOutputWithPast, MoeModelOutputWithPast, + MultimodalMoeBaseModelOutputWithPast, + MultimodalMoeCausalLMOutputWithPast, ) from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel @@ -1658,8 +1659,9 @@ def forward( 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], - ) -> MoeModelOutputWithPast: + ) -> 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. @@ -1671,24 +1673,36 @@ def forward( 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 pixel_values is not 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.") - image_features = self.get_image_features(pixel_values, image_grid_thw, return_dict=True).pooler_output - image_features = torch.cat(image_features).to(inputs_embeds.device, inputs_embeds.dtype) + 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 (`image_grid_thw`: {image_grid_thw})." + 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) - return self.language_model( + outputs = self.language_model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, @@ -1698,6 +1712,7 @@ def forward( image_mask=image_mask, **kwargs, ) + return MultimodalMoeBaseModelOutputWithPast(**outputs, image_outputs=mm_encoder_outputs.get("image")) @auto_docstring( @@ -1737,8 +1752,9 @@ def forward( 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], - ) -> MoeCausalLMOutputWithPast: + ) -> 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. @@ -1749,7 +1765,7 @@ def forward( 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: MoeModelOutputWithPast = self.model( + outputs: MultimodalMoeBaseModelOutputWithPast = self.model( input_ids=input_ids, pixel_values=pixel_values, image_grid_thw=image_grid_thw, @@ -1758,6 +1774,7 @@ def forward( cache=cache, inputs_embeds=inputs_embeds, use_cache=use_cache, + mm_encoder_outputs=mm_encoder_outputs, **kwargs, ) hidden_states = outputs.last_hidden_state @@ -1769,40 +1786,16 @@ def forward( if labels is not None: loss = self.loss_function(logits, labels, self.config.text_config.vocab_size, **kwargs) - return MoeCausalLMOutputWithPast( + 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 prepare_inputs_for_generation( - self, - input_ids, - cache=None, - inputs_embeds=None, - pixel_values=None, - image_grid_thw=None, - attention_mask=None, - is_first_iteration=False, - **kwargs, - ): - model_inputs = super().prepare_inputs_for_generation( - input_ids, - cache=cache, - inputs_embeds=inputs_embeds, - attention_mask=attention_mask, - is_first_iteration=is_first_iteration, - **kwargs, - ) - # The images are merged into the prompt on the first step, and after that they are in the cache - if is_first_iteration or not kwargs.get("use_cache", True): - model_inputs["pixel_values"] = pixel_values - model_inputs["image_grid_thw"] = image_grid_thw - return model_inputs - __all__ = [ "DeepseekV41PreTrainedModel", diff --git a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py index efc414f7657f..a1159e1be47d 100644 --- a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py @@ -34,8 +34,9 @@ from ...modeling_outputs import ( BaseModelOutput, BaseModelOutputWithPooling, - MoeCausalLMOutputWithPast, MoeModelOutputWithPast, + MultimodalMoeBaseModelOutputWithPast, + MultimodalMoeCausalLMOutputWithPast, ) from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel @@ -1746,8 +1747,9 @@ def forward( 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], - ) -> MoeModelOutputWithPast: + ) -> 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. @@ -1759,24 +1761,36 @@ def forward( 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 pixel_values is not 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.") - image_features = self.get_image_features(pixel_values, image_grid_thw, return_dict=True).pooler_output - image_features = torch.cat(image_features).to(inputs_embeds.device, inputs_embeds.dtype) + 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 (`image_grid_thw`: {image_grid_thw})." + 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) - return self.language_model( + outputs = self.language_model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, @@ -1786,6 +1800,7 @@ def forward( image_mask=image_mask, **kwargs, ) + return MultimodalMoeBaseModelOutputWithPast(**outputs, image_outputs=mm_encoder_outputs.get("image")) @auto_docstring( @@ -1825,8 +1840,9 @@ def forward( 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], - ) -> MoeCausalLMOutputWithPast: + ) -> 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. @@ -1837,7 +1853,7 @@ def forward( 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: MoeModelOutputWithPast = self.model( + outputs: MultimodalMoeBaseModelOutputWithPast = self.model( input_ids=input_ids, pixel_values=pixel_values, image_grid_thw=image_grid_thw, @@ -1846,6 +1862,7 @@ def forward( cache=cache, inputs_embeds=inputs_embeds, use_cache=use_cache, + mm_encoder_outputs=mm_encoder_outputs, **kwargs, ) hidden_states = outputs.last_hidden_state @@ -1857,40 +1874,16 @@ def forward( if labels is not None: loss = self.loss_function(logits, labels, self.config.text_config.vocab_size, **kwargs) - return MoeCausalLMOutputWithPast( + 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 prepare_inputs_for_generation( - self, - input_ids, - cache=None, - inputs_embeds=None, - pixel_values=None, - image_grid_thw=None, - attention_mask=None, - is_first_iteration=False, - **kwargs, - ): - model_inputs = super().prepare_inputs_for_generation( - input_ids, - cache=cache, - inputs_embeds=inputs_embeds, - attention_mask=attention_mask, - is_first_iteration=is_first_iteration, - **kwargs, - ) - # The images are merged into the prompt on the first step, and after that they are in the cache - if is_first_iteration or not kwargs.get("use_cache", True): - model_inputs["pixel_values"] = pixel_values - model_inputs["image_grid_thw"] = image_grid_thw - return model_inputs - def get_resized_image_size( height: int, diff --git a/tests/models/deepseek_v41/test_modeling_deepseek_v41.py b/tests/models/deepseek_v41/test_modeling_deepseek_v41.py index 499627037198..38e5b92e6a63 100644 --- a/tests/models/deepseek_v41/test_modeling_deepseek_v41.py +++ b/tests/models/deepseek_v41/test_modeling_deepseek_v41.py @@ -13,7 +13,6 @@ # limitations under the License. import copy import unittest -import unittest.mock from huggingface_hub.errors import StrictDataclassClassValidationError from parameterized import parameterized @@ -32,8 +31,8 @@ select_candidate_blocks, ) -from ...causal_lm_tester import CausalLMModelTest, CausalLMModelTester -from ...test_configuration_common import ConfigTester +from ...test_modeling_common import floats_tensor +from ...vlm_tester import VLMModelTest, VLMModelTester INPUTS_EMBEDS_SKIP_REASON = ( @@ -42,100 +41,99 @@ ) -class DeepseekV41ModelTester(CausalLMModelTester): +class DeepseekV41ModelTester(VLMModelTester): if is_torch_available(): base_model_class = DeepseekV41Model config_class = DeepseekV41Config - causal_lm_class = DeepseekV41ForCausalLM + 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, - "text_config": { - "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": 16, - "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, - }, - "vision_config": { - "hidden_size": 32, - "num_hidden_layers": 2, - "num_attention_heads": 4, - "intermediate_size": 48, - "patch_size": 2, - "downsample_ratio": 3, - }, + # 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": 16, + "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) - # The inputs are text only, so the image token must not show up in the random ids - values["image_token_id"] = values["vocab_size"] - # The text config takes its sizes and special tokens from the tester, so that the common tests can - # read them there. Its vocab has one more id than the tester's, for the image token. - values["text_config"] = { - **values["text_config"], - "vocab_size": values["vocab_size"] + 1, - "hidden_size": values["hidden_size"], - "num_hidden_layers": values["num_hidden_layers"], - "num_attention_heads": values["num_attention_heads"], - # As large as the vocab, so that no tokens are merged and the model works without a tokenizer - "engram_compressed_vocab_size": values["vocab_size"] + 1, - "pad_token_id": values["pad_token_id"], - "bos_token_id": values["bos_token_id"], - "eos_token_id": values["eos_token_id"], - } + # 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 get_config(self): - return DeepseekV41Config( - text_config=self.text_config, - vision_config=self.vision_config, - image_token_id=self.image_token_id, - pad_token_id=self.pad_token_id, - bos_token_id=self.bos_token_id, - eos_token_id=self.eos_token_id, - ) + 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(CausalLMModelTest, unittest.TestCase): +class DeepseekV41ModelTest(VLMModelTest, unittest.TestCase): model_tester_class = DeepseekV41ModelTester # The indexer parameters only influence which compressed entries are selected, which is not differentiable @@ -143,23 +141,12 @@ class DeepseekV41ModelTest(CausalLMModelTest, unittest.TestCase): # The Engram token map and n-gram tables are fixed to the vocabulary, so `resize_token_embeddings` raises test_resize_embeddings = False - def setUp(self): - super().setUp() - # The config is a composite, so the text fields like `vocab_size` are on its `text_config` - self.config_tester = ConfigTester( - self, config_class=DeepseekV41Config, has_text_modality=False, common_properties=["image_token_id"] - ) - def is_pipeline_test_to_skip(self, *args, **kwargs): return True - def _image_features_prepare_config_and_inputs(self): - # The common inputs are text only, so we make the image inputs here: two images with different grids - config = self.model_tester.get_config() - image_grid_thw = torch.tensor([[1, 5, 7], [1, 3, 6]], device=torch_device) - num_patches = int(image_grid_thw.prod(-1).sum()) - pixel_values = torch.randn(num_patches, 3 * config.vision_config.patch_size**2, device=torch_device) - return config, {"pixel_values": pixel_values, "image_grid_thw": image_grid_thw} + 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 @@ -251,6 +238,15 @@ def test_reverse_loading_mapping(self): # 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 @@ -268,22 +264,6 @@ def test_generate_from_inputs_embeds(self, _, num_beams): def test_generate_from_random_inputs_embeds(self): pass - def check_training_gradient_checkpointing(self, gradient_checkpointing_kwargs=None): - # The common check watches the first checkpointing layer of the model, which is a vision layer. The - # common inputs are text only, so we put an image at the start of the first row to make that layer run. - config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() - # 4 x 5 patches are merged 3 x 3 into 2 x 2 tokens, so the image takes 1 + 2 * (2 + 1) + 1 positions - height, width, num_image_tokens = 4, 5, 8 - inputs_dict["input_ids"][0, :num_image_tokens] = config.image_token_id - inputs_dict["pixel_values"] = torch.randn( - height * width, 3 * config.vision_config.patch_size**2, device=torch_device - ) - inputs_dict["image_grid_thw"] = torch.tensor([[1, height, width]], device=torch_device) - with unittest.mock.patch.object( - self.model_tester, "prepare_config_and_inputs_for_common", return_value=(config, inputs_dict) - ): - super().check_training_gradient_checkpointing(gradient_checkpointing_kwargs) - 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. @@ -299,7 +279,7 @@ def test_checkpointing_keeps_the_gradients(self): """ config, model = self._get_model() model.train() - input_ids = torch.randint(0, self.model_tester.vocab_size, (2, 23), device=torch_device) + 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)) @@ -324,7 +304,7 @@ def _get_model(self): 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 = torch.randint(0, self.model_tester.vocab_size, (2, 19), device=torch_device) + 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) @@ -337,7 +317,7 @@ def test_cached_decoding_matches_full_forward(self): 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 = torch.randint(0, self.model_tester.vocab_size, (2, 19), device=torch_device) + 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) @@ -350,7 +330,7 @@ def test_chunked_prefill_matches_full_forward(self): 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 = torch.randint(0, self.model_tester.vocab_size, (1, 19), device=torch_device) + 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 @@ -390,13 +370,17 @@ def test_attention_layer_types(self): "kv_shared_indexed_attention", ], ) - text_config = self.model_tester.text_config + 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(**{**text_config, "kv_source_layer_ids": [3], "index_source_layer_ids": [3, 4]}) + 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(**{**text_config, "index_source_layer_ids": [3, 4]}) + 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.""" @@ -428,10 +412,10 @@ def test_engram_hash_ids(self): 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.""" - text_config = {**self.model_tester.text_config, "engram_compressed_vocab_size": 60} - config = DeepseekV41Config(text_config=text_config, vision_config=self.model_tester.vision_config) + config = self.model_tester.get_config() + config.text_config.engram_compressed_vocab_size = 60 model = DeepseekV41ForCausalLM(config).to(torch_device).eval() - input_ids = torch.randint(0, self.model_tester.vocab_size, (1, 6), device=torch_device) + input_ids = self.model_tester.prepare_text_ids(1, 6) with self.assertRaisesRegex(ValueError, "set_engram_token_map"): model(input_ids=input_ids) @@ -467,7 +451,7 @@ def test_image_and_text_forward(self): 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 = torch.randint(0, self.model_tester.vocab_size, (1, 12), 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(): @@ -495,6 +479,29 @@ def test_image_and_text_forward(self): 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) + for beam in range(num_beams): + torch.testing.assert_close(first_step_logits[:, beam], expected, atol=1e-4, rtol=1e-4) + def test_image_features_of_several_images(self): """Images are encoded independently, whether or not they come in together.""" config, model = self._get_model() From 1fe1e2c0f56098b56cf06af022cbcfc15cf2bdce Mon Sep 17 00:00:00 2001 From: Matt Date: Mon, 23 Nov 2026 12:01:34 +0000 Subject: [PATCH 09/13] DeepSeek-V4.1: round the activations to FP8 and FP4, like the reference The reference implementation rounds the KV and the attention output to FP8, and the index keys, the index queries and the compressed KV to FP4, because that is how they were quantized in training. `fake_quantize` does the same at the same five places: the values are rounded but keep their dtype, and the gradient goes straight through. The block widths have to be multiples of 32, which the text config now validates. The rounding matches the cast to `float8_e4m3fn` of PyTorch and a plain reading of the reference kernels, but it has not been compared with the TileLang kernels themselves. With rounding in the model, two ways of computing the same logits can differ by a rounding step instead of by float noise, so our own comparison tests use a tolerance of 1e-2 from one class attribute. The common tests pass as they are. --- docs/source/en/model_doc/deepseek_v41.md | 3 + .../configuration_deepseek_v41.py | 16 +++ .../deepseek_v41/modeling_deepseek_v41.py | 97 +++++++++++++++ .../deepseek_v41/modular_deepseek_v41.py | 113 ++++++++++++++++++ .../test_modeling_deepseek_v41.py | 66 +++++++++- 5 files changed, 291 insertions(+), 4 deletions(-) diff --git a/docs/source/en/model_doc/deepseek_v41.md b/docs/source/en/model_doc/deepseek_v41.md index 6f91907d375c..d216b092319f 100644 --- a/docs/source/en/model_doc/deepseek_v41.md +++ b/docs/source/en/model_doc/deepseek_v41.md @@ -112,6 +112,9 @@ print(processor.decode(outputs[0, inputs["input_ids"].shape[1] :])) already has. - Batched generation with left padding does not match unpadded generation yet. The compressor pools consecutive tokens, so padding shifts its groups. +- 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 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. diff --git a/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py b/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py index 807f4f113a5b..c26776b54470 100644 --- a/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py @@ -417,6 +417,22 @@ def __post_init__(self, **kwargs): 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 diff --git a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py index 1ceae132fe21..409353eccaf3 100644 --- a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py @@ -370,6 +370,92 @@ def apply_rotary_pos_emb( 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: @@ -467,6 +553,8 @@ def forward( 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) @@ -611,6 +699,9 @@ def forward( 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] @@ -624,6 +715,10 @@ def forward( 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: compressed_kv, index_keys = cache_layer.update_compressed_states(compressed_kv, index_keys) # We publish both for the indexers and the KV-sharing layers after us, starting with our own @@ -671,6 +766,8 @@ def forward( 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 diff --git a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py index a1159e1be47d..22cb2804965a 100644 --- a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py @@ -289,6 +289,22 @@ def validate_layer_type(self): 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) @@ -517,6 +533,92 @@ 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 @@ -655,6 +757,8 @@ def forward( 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) @@ -756,6 +860,9 @@ def forward( 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] @@ -769,6 +876,10 @@ def forward( 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: compressed_kv, index_keys = cache_layer.update_compressed_states(compressed_kv, index_keys) # We publish both for the indexers and the KV-sharing layers after us, starting with our own @@ -816,6 +927,8 @@ def forward( 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 diff --git a/tests/models/deepseek_v41/test_modeling_deepseek_v41.py b/tests/models/deepseek_v41/test_modeling_deepseek_v41.py index 38e5b92e6a63..ea231911ba9b 100644 --- a/tests/models/deepseek_v41/test_modeling_deepseek_v41.py +++ b/tests/models/deepseek_v41/test_modeling_deepseek_v41.py @@ -28,6 +28,7 @@ from transformers.models.deepseek_v41.modeling_deepseek_v41 import ( DeepseekV41Compressor, DeepseekV41NgramHasher, + fake_quantize, select_candidate_blocks, ) @@ -81,7 +82,7 @@ class DeepseekV41ModelTester(VLMModelTester): # 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": 16, + "index_head_dim": 32, "index_topk": 3, "hc_mult": 2, "hc_sinkhorn_iters": 3, @@ -140,6 +141,10 @@ class DeepseekV41ModelTest(VLMModelTest, unittest.TestCase): 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 @@ -312,7 +317,8 @@ def test_cached_decoding_matches_full_forward(self): 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) - torch.testing.assert_close(torch.cat(logits, dim=1), expected, atol=1e-4, rtol=1e-4) + 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.""" @@ -325,7 +331,8 @@ def test_chunked_prefill_matches_full_forward(self): 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) - torch.testing.assert_close(torch.cat(logits, dim=1), expected, atol=1e-4, rtol=1e-4) + tolerance = self.rounded_logits_tolerance + torch.testing.assert_close(torch.cat(logits, dim=1), expected, atol=tolerance, rtol=tolerance) def test_compressed_attention_is_used(self): """Tokens outside the sliding window still reach the output, through the compressed KV.""" @@ -434,6 +441,56 @@ def test_resize_token_embeddings_is_not_supported(self): 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 @@ -499,8 +556,9 @@ def test_beam_search_keeps_each_image_whole(self): ) # 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=1e-4, rtol=1e-4) + 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.""" From 5d5b8dbbe4ac2fdc7bec8416e14273e8bb8b6e58 Mon Sep 17 00:00:00 2001 From: Matt Date: Tue, 24 Nov 2026 12:59:09 +0000 Subject: [PATCH 10/13] DeepSeek-V4.1: left padding The compressor pooled consecutive tokens before the attention mask applied, so left padding shifted the groups and folded pad tokens into the compressed KV. It now moves the real tokens of each row to the front before pooling, so the groups are counted from the first real token of a row. The compressed entries are left-aligned: the cache writes the new entries of each row at that row's own offset, and keeps the last `ratio - 1` real tokens of a row for its next group. An entry is rotated at the position id of its group, and the indexer hides entries by counting real tokens instead of reading `position_ids`. `forward` still defaults `position_ids` to an `arange`, like the rest of the library. The KV are rounded after RoPE, so the model is not indifferent to a shift of the positions, and a direct call on a padded batch has to pass the positions that `generate` makes. The common left padding test is no longer skipped. It hardcoded a tolerance of 1e-5, so it now takes `atol` and `rtol` like `test_batching_equivalence` does, and we pass the 1e-2 that our other comparison tests use. A new test covers padding with a cache, in chunks and token by token. --- docs/source/en/model_doc/deepseek_v41.md | 6 +- .../deepseek_v41/modeling_deepseek_v41.py | 209 ++++++++++++------ .../deepseek_v41/modular_deepseek_v41.py | 209 ++++++++++++------ tests/generation/test_utils.py | 13 +- .../test_modeling_deepseek_v41.py | 59 ++++- 5 files changed, 347 insertions(+), 149 deletions(-) diff --git a/docs/source/en/model_doc/deepseek_v41.md b/docs/source/en/model_doc/deepseek_v41.md index d216b092319f..6e4e704aebd1 100644 --- a/docs/source/en/model_doc/deepseek_v41.md +++ b/docs/source/en/model_doc/deepseek_v41.md @@ -110,8 +110,10 @@ print(processor.decode(outputs[0, inputs["input_ids"].shape[1] :])) - `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 does not match unpadded generation yet. The compressor pools consecutive - tokens, so padding shifts its groups. +- 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!). diff --git a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py index 409353eccaf3..71f11a324179 100644 --- a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py @@ -29,7 +29,7 @@ from ...cache_utils import Cache, DynamicCache, DynamicSlidingWindowLayer from ...generation import GenerationMixin from ...integrations import use_experts_implementation, use_kernel_forward_from_hub -from ...masking_utils import create_sliding_window_causal_mask +from ...masking_utils import create_recurrent_attention_mask, create_sliding_window_causal_mask from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import ( BaseModelOutput, @@ -54,9 +54,12 @@ class DeepseekV41CacheLayer(DynamicSlidingWindowLayer): 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. - * `buffer_kv` / `buffer_gate` - the tokens of a pooling group that is still filling up. The group only - becomes a compressed entry once its last token arrives. + 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. """ @@ -67,8 +70,7 @@ 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.buffer_kv: torch.Tensor | None = None - self.buffer_gate: 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): @@ -85,33 +87,33 @@ def update(self, key_states: torch.Tensor, value_states: torch.Tensor, *args, ** self.values = self.keys return full, full - @property - def num_compressed_entries(self) -> int: - return 0 if self.compressed_kv is None else self.compressed_kv.shape[1] - - def update_pooling_buffer( - self, kv: torch.Tensor, gate: torch.Tensor, compress_ratio: int + 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]: """ - Put the new `(kv, gate)` after the tokens that are still waiting for their group to fill up, and - return the longest prefix that is made of whole groups. The rest waits in the buffer for the next call. + 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.buffer_kv is not None: - kv = torch.cat([self.buffer_kv, kv], dim=1) - gate = torch.cat([self.buffer_gate, gate], dim=1) - usable = (kv.shape[1] // compress_ratio) * compress_ratio - self.buffer_kv, self.buffer_gate = kv[:, usable:], gate[:, usable:] - return kv[:, :usable], gate[:, :usable] - - def update_compressed_states( - self, compressed_kv: torch.Tensor, index_keys: torch.Tensor - ) -> tuple[torch.Tensor, torch.Tensor]: - """Append the new compressed KV entries and their index keys, and return all of them so far.""" - if self.compressed_kv is not None: - compressed_kv = torch.cat([self.compressed_kv, compressed_kv], dim=1) - index_keys = torch.cat([self.index_keys, index_keys], dim=1) - self.compressed_kv, self.index_keys = compressed_kv, index_keys - return compressed_kv, index_keys + 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: """ @@ -125,7 +127,7 @@ def update_token_history(self, token_ids: torch.Tensor, history_length: int) -> return token_ids def _extra_state_names(self) -> tuple[str, ...]: - return ("compressed_kv", "index_keys", "buffer_kv", "buffer_gate", "token_history") + return ("compressed_kv", "index_keys", "pooling_buffer", "token_history") def reorder_cache(self, beam_idx: torch.LongTensor) -> None: super().reorder_cache(beam_idx) @@ -307,9 +309,15 @@ 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. A group whose last token has - not arrived yet waits in the cache, or is dropped when there is no cache. + 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): @@ -325,22 +333,64 @@ def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): self.gate_proj = None self.kv_norm = DeepseekV41RMSNorm(config.head_dim, eps=config.rms_norm_eps) - def forward(self, hidden_states: torch.Tensor, cache_layer: DeepseekV41CacheLayer | None = None) -> torch.Tensor: + 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 - return self.kv_norm(self.kv_proj(hidden_states)) - - # The reference promotes the pooling weights to float32, and pools in float32 too - kv, gate = self.kv_proj(hidden_states), self.gate_proj(hidden_states) - if cache_layer is not None: - kv, gate = cache_layer.update_pooling_buffer(kv, gate, self.compress_ratio) + 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: - usable = (kv.shape[1] // self.compress_ratio) * self.compress_ratio - kv, gate = kv[:, :usable], gate[:, :usable] - kv = kv.unflatten(1, (-1, self.compress_ratio)) - gate = gate.unflatten(1, (-1, self.compress_ratio)) - pooled = (kv * gate.softmax(dim=2)).sum(dim=2) - return self.kv_norm(pooled.to(hidden_states.dtype)) + 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): @@ -539,7 +589,7 @@ def forward( hidden_states: torch.Tensor, q_residual: torch.Tensor, index_keys: torch.Tensor, - position_ids: 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]: @@ -559,8 +609,10 @@ def forward( 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 - num_visible = (position_ids + 1) // self.compress_ratio + # 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")) @@ -679,6 +731,8 @@ def forward( 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, @@ -706,11 +760,16 @@ def forward( kv = cache.update(kv, kv, self.layer_idx)[0] if self.layer_type == "compressed_attention": - # This layer compresses the groups that this call completes. There may be none of them, e.g. when - # decoding a token that is not the last of its group. + # 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 = self.compressor(hidden_states, cache_layer) - entry_cos, entry_sin = compressed_position_embeddings[self.compress_ratio] + 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) @@ -720,7 +779,10 @@ def forward( 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: - compressed_kv, index_keys = cache_layer.update_compressed_states(compressed_kv, index_keys) + # 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 @@ -731,7 +793,7 @@ def forward( hidden_states, q_residual, shared_states["index_keys"], - kwargs.get("position_ids"), + num_seen_tokens[:, None] + is_real_token.cumsum(dim=-1), (cos, sin), shared_states.get("candidates"), ) @@ -1585,16 +1647,27 @@ def forward( position_ids = torch.arange(seq_len, device=inputs_embeds.device) + past_seen position_ids = position_ids.unsqueeze(0) - # First, the n-gram hashes of all the Engram layers. A padded token must not end up in the n-grams of + # 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 = engram_mask - if isinstance(attention_mask, torch.Tensor) and attention_mask.ndim == 2: - is_real_token = attention_mask[:, -seq_len:].bool() - hash_mask = is_real_token if hash_mask is None else hash_mask & is_real_token + 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 @@ -1619,17 +1692,16 @@ def forward( "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 entry - # `j` of a layer with ratio `r` rotates at position `j * r`. We count groups from the tokens that the - # cache has seen, and only rotate the entries of the groups that this call completes. + # 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: - entry_ids = torch.arange( - past_seen // ratio, (past_seen + seq_len) // ratio, device=inputs_embeds.device - ) compressed_position_embeddings[ratio] = self.rotary_emb( - inputs_embeds, position_ids=(entry_ids * ratio).unsqueeze(0), layer_type="compress" + 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 @@ -1649,7 +1721,8 @@ def forward( image_mask=image_mask, position_embeddings=position_embeddings, compressed_position_embeddings=compressed_position_embeddings, - position_ids=position_ids, + is_real_token=is_real_token, + num_seen_tokens=num_seen_tokens, attention_mask=causal_mask, cache=cache, shared_states=shared_states, diff --git a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py index 22cb2804965a..60ae46ef4f56 100644 --- a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py @@ -29,7 +29,7 @@ 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_sliding_window_causal_mask +from ...masking_utils import create_recurrent_attention_mask, create_sliding_window_causal_mask from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import ( BaseModelOutput, @@ -407,9 +407,12 @@ class DeepseekV41CacheLayer(DynamicSlidingWindowLayer): 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. - * `buffer_kv` / `buffer_gate` - the tokens of a pooling group that is still filling up. The group only - becomes a compressed entry once its last token arrives. + 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. """ @@ -420,8 +423,7 @@ 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.buffer_kv: torch.Tensor | None = None - self.buffer_gate: 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): @@ -438,33 +440,33 @@ def update(self, key_states: torch.Tensor, value_states: torch.Tensor, *args, ** self.values = self.keys return full, full - @property - def num_compressed_entries(self) -> int: - return 0 if self.compressed_kv is None else self.compressed_kv.shape[1] - - def update_pooling_buffer( - self, kv: torch.Tensor, gate: torch.Tensor, compress_ratio: int + 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]: """ - Put the new `(kv, gate)` after the tokens that are still waiting for their group to fill up, and - return the longest prefix that is made of whole groups. The rest waits in the buffer for the next call. + 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.buffer_kv is not None: - kv = torch.cat([self.buffer_kv, kv], dim=1) - gate = torch.cat([self.buffer_gate, gate], dim=1) - usable = (kv.shape[1] // compress_ratio) * compress_ratio - self.buffer_kv, self.buffer_gate = kv[:, usable:], gate[:, usable:] - return kv[:, :usable], gate[:, :usable] - - def update_compressed_states( - self, compressed_kv: torch.Tensor, index_keys: torch.Tensor - ) -> tuple[torch.Tensor, torch.Tensor]: - """Append the new compressed KV entries and their index keys, and return all of them so far.""" - if self.compressed_kv is not None: - compressed_kv = torch.cat([self.compressed_kv, compressed_kv], dim=1) - index_keys = torch.cat([self.index_keys, index_keys], dim=1) - self.compressed_kv, self.index_keys = compressed_kv, index_keys - return compressed_kv, index_keys + 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: """ @@ -478,7 +480,7 @@ def update_token_history(self, token_ids: torch.Tensor, history_length: int) -> return token_ids def _extra_state_names(self) -> tuple[str, ...]: - return ("compressed_kv", "index_keys", "buffer_kv", "buffer_gate", "token_history") + return ("compressed_kv", "index_keys", "pooling_buffer", "token_history") def reorder_cache(self, beam_idx: torch.LongTensor) -> None: super().reorder_cache(beam_idx) @@ -624,9 +626,15 @@ 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. A group whose last token has - not arrived yet waits in the cache, or is dropped when there is no cache. + 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): @@ -642,22 +650,64 @@ def __init__(self, config: DeepseekV41TextConfig, layer_idx: int): self.gate_proj = None self.kv_norm = DeepseekV41RMSNorm(config.head_dim, eps=config.rms_norm_eps) - def forward(self, hidden_states: torch.Tensor, cache_layer: DeepseekV41CacheLayer | None = None) -> torch.Tensor: + 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 - return self.kv_norm(self.kv_proj(hidden_states)) - - # The reference promotes the pooling weights to float32, and pools in float32 too - kv, gate = self.kv_proj(hidden_states), self.gate_proj(hidden_states) - if cache_layer is not None: - kv, gate = cache_layer.update_pooling_buffer(kv, gate, self.compress_ratio) + 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: - usable = (kv.shape[1] // self.compress_ratio) * self.compress_ratio - kv, gate = kv[:, :usable], gate[:, :usable] - kv = kv.unflatten(1, (-1, self.compress_ratio)) - gate = gate.unflatten(1, (-1, self.compress_ratio)) - pooled = (kv * gate.softmax(dim=2)).sum(dim=2) - return self.kv_norm(pooled.to(hidden_states.dtype)) + 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( @@ -743,7 +793,7 @@ def forward( hidden_states: torch.Tensor, q_residual: torch.Tensor, index_keys: torch.Tensor, - position_ids: 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]: @@ -763,8 +813,10 @@ def forward( 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 - num_visible = (position_ids + 1) // self.compress_ratio + # 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")) @@ -840,6 +892,8 @@ def forward( 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, @@ -867,11 +921,16 @@ def forward( kv = cache.update(kv, kv, self.layer_idx)[0] if self.layer_type == "compressed_attention": - # This layer compresses the groups that this call completes. There may be none of them, e.g. when - # decoding a token that is not the last of its group. + # 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 = self.compressor(hidden_states, cache_layer) - entry_cos, entry_sin = compressed_position_embeddings[self.compress_ratio] + 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) @@ -881,7 +940,10 @@ def forward( 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: - compressed_kv, index_keys = cache_layer.update_compressed_states(compressed_kv, index_keys) + # 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 @@ -892,7 +954,7 @@ def forward( hidden_states, q_residual, shared_states["index_keys"], - kwargs.get("position_ids"), + num_seen_tokens[:, None] + is_real_token.cumsum(dim=-1), (cos, sin), shared_states.get("candidates"), ) @@ -1689,16 +1751,27 @@ def forward( position_ids = torch.arange(seq_len, device=inputs_embeds.device) + past_seen position_ids = position_ids.unsqueeze(0) - # First, the n-gram hashes of all the Engram layers. A padded token must not end up in the n-grams of + # 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 = engram_mask - if isinstance(attention_mask, torch.Tensor) and attention_mask.ndim == 2: - is_real_token = attention_mask[:, -seq_len:].bool() - hash_mask = is_real_token if hash_mask is None else hash_mask & is_real_token + 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 @@ -1723,17 +1796,16 @@ def forward( "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 entry - # `j` of a layer with ratio `r` rotates at position `j * r`. We count groups from the tokens that the - # cache has seen, and only rotate the entries of the groups that this call completes. + # 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: - entry_ids = torch.arange( - past_seen // ratio, (past_seen + seq_len) // ratio, device=inputs_embeds.device - ) compressed_position_embeddings[ratio] = self.rotary_emb( - inputs_embeds, position_ids=(entry_ids * ratio).unsqueeze(0), layer_type="compress" + 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 @@ -1753,7 +1825,8 @@ def forward( image_mask=image_mask, position_embeddings=position_embeddings, compressed_position_embeddings=compressed_position_embeddings, - position_ids=position_ids, + is_real_token=is_real_token, + num_seen_tokens=num_seen_tokens, attention_mask=causal_mask, cache=cache, shared_states=shared_states, 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/test_modeling_deepseek_v41.py b/tests/models/deepseek_v41/test_modeling_deepseek_v41.py index ea231911ba9b..69456680bfbe 100644 --- a/tests/models/deepseek_v41/test_modeling_deepseek_v41.py +++ b/tests/models/deepseek_v41/test_modeling_deepseek_v41.py @@ -229,14 +229,12 @@ def test_hidden_states_output(self): [streams_shape] * text_config.num_hidden_layers + [(batch_size, seq_length, text_config.hidden_size)], ) - @unittest.skip( - reason=( - "The compressor pools consecutive tokens before the attention mask applies, so left padding shifts " - "the groups and folds pad tokens into the compressed KV. Same limitation as DeepSeek-V4, not fixed yet." - ) - ) def test_left_padding_compatibility(self): - pass + # 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 @@ -334,6 +332,41 @@ def test_chunked_prefill_matches_full_forward(self): 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() @@ -357,12 +390,20 @@ def test_compressor_with_offloaded_weights(self): 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(hidden_states) - expected = compressor(hidden_states) + 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): From c6211be0cd79568274c539d5d917d119c7e7ec7d Mon Sep 17 00:00:00 2001 From: Matt Date: Tue, 24 Nov 2026 18:42:05 +0000 Subject: [PATCH 11/13] DeepSeek-V4.1: load the FP8 Engram tables, and skip the BF16 linears --- docs/source/en/model_doc/deepseek_v41.md | 3 + .../source/en/quantization/finegrained_fp8.md | 1 + src/transformers/conversion_mapping.py | 8 ++ .../integrations/finegrained_fp8.py | 51 ++++++- .../configuration_deepseek_v41.py | 28 ++++ .../deepseek_v41/modular_deepseek_v41.py | 28 ++++ .../quantizers/quantizer_finegrained_fp8.py | 8 +- src/transformers/utils/quantization_config.py | 8 ++ .../test_modeling_deepseek_v41.py | 133 +++++++++++++++++- .../quantization/finegrained_fp8/test_fp8.py | 26 ++++ 10 files changed, 285 insertions(+), 9 deletions(-) diff --git a/docs/source/en/model_doc/deepseek_v41.md b/docs/source/en/model_doc/deepseek_v41.md index 6e4e704aebd1..076549d797fc 100644 --- a/docs/source/en/model_doc/deepseek_v41.md +++ b/docs/source/en/model_doc/deepseek_v41.md @@ -117,6 +117,9 @@ print(processor.decode(outputs[0, inputs["input_ids"].shape[1] :])) - 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. 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/conversion_mapping.py b/src/transformers/conversion_mapping.py index bf9369ad683f..928acbc2040f 100755 --- a/src/transformers/conversion_mapping.py +++ b/src/transformers/conversion_mapping.py @@ -837,6 +837,14 @@ def _build_checkpoint_conversion_mapping(): 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", 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/deepseek_v41/configuration_deepseek_v41.py b/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py index c26776b54470..9c5fa26a1b2a 100644 --- a/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py @@ -450,5 +450,33 @@ class DeepseekV41Config(PreTrainedConfig): 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/modular_deepseek_v41.py b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py index 60ae46ef4f56..63158f6aca46 100644 --- a/src/transformers/models/deepseek_v41/modular_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modular_deepseek_v41.py @@ -400,6 +400,34 @@ class DeepseekV41Config(PreTrainedConfig): 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""" 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/models/deepseek_v41/test_modeling_deepseek_v41.py b/tests/models/deepseek_v41/test_modeling_deepseek_v41.py index 69456680bfbe..4b14ad7f8fa2 100644 --- a/tests/models/deepseek_v41/test_modeling_deepseek_v41.py +++ b/tests/models/deepseek_v41/test_modeling_deepseek_v41.py @@ -12,7 +12,11 @@ # 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 @@ -23,19 +27,37 @@ if is_torch_available(): import torch - - from transformers import DeepseekV41Config, DeepseekV41ForCausalLM, DeepseekV41Model, DeepseekV41TextConfig + 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." @@ -630,3 +652,110 @@ def test_image_features_of_several_images(self): # ... 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/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 From 5106be2b1902782b2965ba7b9f73485a4bd1e884 Mon Sep 17 00:00:00 2001 From: Matt Date: Tue, 24 Nov 2026 18:52:33 +0000 Subject: [PATCH 12/13] DeepSeek-V4.1: follow the TP plan change on main, and refresh the model card date --- docs/source/en/model_doc/deepseek_v41.md | 2 +- .../models/deepseek_v41/configuration_deepseek_v41.py | 9 +++------ 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/docs/source/en/model_doc/deepseek_v41.md b/docs/source/en/model_doc/deepseek_v41.md index 076549d797fc..40c4c612509e 100644 --- a/docs/source/en/model_doc/deepseek_v41.md +++ b/docs/source/en/model_doc/deepseek_v41.md @@ -13,7 +13,7 @@ specific language governing permissions and limitations under the License. rendered properly in your Markdown viewer. --> -*This model was contributed to Hugging Face Transformers on 2026-11-18.* +*This model was contributed to Hugging Face Transformers on 2026-11-24.* # DeepSeek-V4.1 diff --git a/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py b/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py index 9c5fa26a1b2a..0e9d2614e152 100644 --- a/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/configuration_deepseek_v41.py @@ -176,13 +176,10 @@ class DeepseekV41TextConfig(PreTrainedConfig): "layers": (["hidden_states", "attention_mask"], ["hidden_states"]), "norm": (["hidden_states"], ["hidden_states"]), } - # Main attention and the shared MLP stay replicated. Shared-KV MQA and the CSA / HCA compressor - # broadcast one KV head via `repeat_kv`, so colwise `q_b_proj` would mismatch the rank-local - # head count; the shared MLP is too small to be worth sharding. base_model_tp_plan = { - "layers.*.mlp.experts.gate_up_proj": "packed_colwise", - "layers.*.mlp.experts.down_proj": "rowwise", - "layers.*.mlp.experts": "moe_tp_experts", + "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", From 0de1e0cd41f90aec02d0f4167a7d567307967e87 Mon Sep 17 00:00:00 2001 From: Matt Date: Wed, 25 Nov 2026 16:50:16 +0000 Subject: [PATCH 13/13] DeepSeek-V4.1: follow the norm cleanup on main, and drop the unused training mixin edit --- docs/source/en/model_doc/deepseek_v41.md | 2 +- .../models/deepseek_v41/modeling_deepseek_v41.py | 8 +++----- tests/test_training_mixin.py | 2 +- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/docs/source/en/model_doc/deepseek_v41.md b/docs/source/en/model_doc/deepseek_v41.md index 40c4c612509e..861c0a71b6e3 100644 --- a/docs/source/en/model_doc/deepseek_v41.md +++ b/docs/source/en/model_doc/deepseek_v41.md @@ -13,7 +13,7 @@ specific language governing permissions and limitations under the License. rendered properly in your Markdown viewer. --> -*This model was contributed to Hugging Face Transformers on 2026-11-24.* +*This model was contributed to Hugging Face Transformers on 2026-11-25.* # DeepSeek-V4.1 diff --git a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py index 71f11a324179..3bf4fb021a45 100644 --- a/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py +++ b/src/transformers/models/deepseek_v41/modeling_deepseek_v41.py @@ -28,7 +28,7 @@ from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache, DynamicSlidingWindowLayer from ...generation import GenerationMixin -from ...integrations import use_experts_implementation, use_kernel_forward_from_hub +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 ( @@ -157,7 +157,6 @@ def reset(self) -> None: setattr(self, name, None) -@use_kernel_forward_from_hub("RMSNorm") class DeepseekV41RMSNorm(nn.Module): def __init__(self, hidden_size, eps: float = 1e-6) -> None: """ @@ -167,13 +166,12 @@ def __init__(self, hidden_size, eps: float = 1e-6) -> None: self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps - def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + 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) - # DSV4: norm weights are kept in float32, so multiply in float32 and cast once at the end - return (self.weight * hidden_states).to(input_dtype) + 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}" diff --git a/tests/test_training_mixin.py b/tests/test_training_mixin.py index 6280d896af5c..1f644936e1f8 100644 --- a/tests/test_training_mixin.py +++ b/tests/test_training_mixin.py @@ -220,7 +220,7 @@ def test_training_overfit(self): batch = self._create_text_training_batch( batch_size=self.training_overfit_batch_size, seq_length=self.training_overfit_seq_length, - vocab_size=config.get_text_config().vocab_size, + vocab_size=config.vocab_size, ) logger.info(f"{Colors.CYAN}Training pattern:{Colors.RESET} Repeating token sequence (1-19)") else: