Repository navigation
Add DeepSeek-V4.1-Flash - #50919
Draft
Rocketknight1 wants to merge 13 commits into
Draft
Add DeepSeek-V4.1-Flash#50919Rocketknight1 wants to merge 13 commits into
Rocketknight1 wants to merge 13 commits into
Conversation
|
The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update. Pages changed in this PR: |
Rocketknight1
force-pushed
the
add-deepseek-v41
branch
from
November 23, 2026 12:01
13a45be to
39eb744
Compare
Rocketknight1
force-pushed
the
add-deepseek-v41
branch
from
November 24, 2026 18:52
c742ca1 to
421ec20
Compare
The compressor read its pooling weights straight off its submodules to promote them to float32, so with offloaded weights it pooled uninitialized memory. The promotion now happens inside the projection itself. The `shared_states` dict also has to skip device placement, or every layer gets its own copy of it. `get_image_features` now returns a model output with the vision encoder's hidden states and attentions, the forwards take the deprecated `past_key_values`, and the tests check the shapes that the compressed KV and the hyper-connection streams really have.
The four attention classes are now one class that branches on the layer type, like DeepSeek-V4 does, so there is no subclass chain and no class dict any more. The model owns the only rotary embedding. It computes the RoPE of the compressed entries for each compress ratio and passes it down, instead of the compressing attention layers building a rotary module each. `set_engram_token_map` is a single method on the PreTrainedModel instead of one per model class. It still needs a linter ignore: it fills a saved buffer that the checkpoints leave out, not a hyperparameter. Also merges main, which dropped `keys_to_ignore_at_inference` from the parent config.
The layers now return the states that the KV-sharing layers read, instead of writing them into a dict shared by the whole stack. The backward replay of a checkpointed layer reads the same states as its first run, so checkpointing works with use_reentrant=False. use_reentrant=True raises, because it would silently drop the gradient of the shared compressed KV. Also skips the inputs_embeds tests (the Engram layers need token ids), moves the tester values into small_config_overrides, and skips the base model in test_reverse_loading_mapping.
The image processor follows the original preprocessing: each image keeps its aspect ratio, is resized to whole 14x14 patches within the min-pixel and max-token limits, and is padded with gray. It resizes with torchvision where the original uses PIL, so the sizes and the padding are identical, but resampled pixel values can be off by a level or two out of 255. The processor repeats the image placeholder once for every position that the image takes up in the prompt. The model is also registered for image-text-to-text.
The grid input is now `image_grid_thw`, the name that most models with native-resolution images use and that the common tests know about. An image is one frame, so the temporal size is always 1, and the model raises on anything else. The common chat template test now runs as it is, so its override in the processor tests is gone. `resize_token_embeddings` raises an error. The Engram token map and the n-gram tables are fixed to the vocabulary of the checkpoint, so a new token would have no entry in them. The common resize tests are disabled with `test_resize_embeddings = False`.
The sinks, the hyper-connections and the router biases are listed in `_keep_in_fp32_modules_strict`, but only `from_pretrained` enforces that list. A model built straight from a config got them in the default dtype, which the common test from #50975 now catches. They are created in float32 in their `__init__` instead.
`generate` repeats its inputs once per beam, and `pixel_values` has a row per patch, so every beam got the patches of a scrambled image. The model now takes `mm_encoder_outputs`, so `generate` encodes the images once and repeats whole images, and it returns the multimodal outputs with `image_outputs`. The `prepare_inputs_for_generation` override is gone. The new beam test fails on the old code: the common beam tests only check output shapes. The tests move from `CausalLMModelTester` to `VLMModelTester`, like the other VLMs, so the common tests run with an image in every prompt. The image token is an id inside the tester's vocab, and the text ids are drawn from above the special tokens.
The reference implementation rounds the KV and the attention output to FP8, and the index keys, the index queries and the compressed KV to FP4, because that is how they were quantized in training. `fake_quantize` does the same at the same five places: the values are rounded but keep their dtype, and the gradient goes straight through. The block widths have to be multiples of 32, which the text config now validates. The rounding matches the cast to `float8_e4m3fn` of PyTorch and a plain reading of the reference kernels, but it has not been compared with the TileLang kernels themselves. With rounding in the model, two ways of computing the same logits can differ by a rounding step instead of by float noise, so our own comparison tests use a tolerance of 1e-2 from one class attribute. The common tests pass as they are.
The compressor pooled consecutive tokens before the attention mask applied, so left padding shifted the groups and folded pad tokens into the compressed KV. It now moves the real tokens of each row to the front before pooling, so the groups are counted from the first real token of a row. The compressed entries are left-aligned: the cache writes the new entries of each row at that row's own offset, and keeps the last `ratio - 1` real tokens of a row for its next group. An entry is rotated at the position id of its group, and the indexer hides entries by counting real tokens instead of reading `position_ids`. `forward` still defaults `position_ids` to an `arange`, like the rest of the library. The KV are rounded after RoPE, so the model is not indifferent to a shift of the positions, and a direct call on a padded batch has to pass the positions that `generate` makes. The common left padding test is no longer skipped. It hardcoded a tolerance of 1e-5, so it now takes `atol` and `rtol` like `test_batching_equivalence` does, and we pass the 1e-2 that our other comparison tests use. A new test covers padding with a cache, in chunks and token by token.
…raining mixin edit
Rocketknight1
force-pushed
the
add-deepseek-v41
branch
from
November 25, 2026 16:50
421ec20 to
0de1e0c
Compare
Contributor
|
[For maintainers] Suggested jobs to run (before merge) run-slow: auto, deepseek_v41, finegrained_fp8 |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Extremely draft PR! Do not waste time reviewing! It's going to change a lot!
Things left to do:
mtp.*) are ignored when loading, and generating with them needs [Feature] Add DSpark #49996model.set_engram_token_map(tokenizer)after loading. The setter needs a linter ignore (TRF033) to get past the structure checks, which goes away with the Hub PRpreprocessor_config.jsonand aprocessor_config.jsonso thatAutoProcessorcan load it, and the precomputed token map for the Engram n-gram hashing, which removes the model -> tokenizer dependencyattention_layer_typesshould follow whatever Split KV-sharing and rope attention variants into per-layer classes #50189 ends up with, and the Engram naming overlaps with Add Hy4-flash (hy_v4_flash) #50903. For now there is one attention class that branches on the layer type, like V4. The structure checks don't allow subclassing inside a modular file, so one class per layer type would mean writing the attention out in full four timesuse_reentrant=False(the default).use_reentrant=Trueraises an error, because it would silently drop the gradient of the shared compressed KV. I'm not sure if overridingactivation_checkpointing_enableis the best place for that checktest_reverse_loading_mapping: the renames that nest the flat checkpoint undermodel.only apply to the model with a head, so the test skips the base modelinputs_embedswithoutinput_idsis not supported, because the Engram layers hash n-grams of token ids. Those common tests are skippedsmall_config_overrides, which fixestest_model_tester_defaultsget_image_featuresoutput, the config tester on the composite config, and thepast_key_valuesdeprecationdevice_map: the compressor pooled uninitialized memory when its weights were offloaded, and each layer got its own copy of the state that the KV-sharing layers pass alongAutoModelForImageTextToTextimage_grid_thw, like in most models with native-resolution images. An image is one frame, so the temporal size is always 1, and the model raises an error on anything elseresize_token_embeddingsraises an error, and the common resize tests are disabled. All the common tests pass nowVLMModelTesternow, so the common tests run with an image in every prompt.generateencodes the images once and repeats whole images for the beams, instead of repeatingpixel_valuesrow by row, which scrambled the patchesfloat8_e4m3fnand a plain reading of the reference kernels, but it hasn't been compared with the TileLang kernels themselvesatol/rtol(liketest_batching_equivalence) and we pass 1e-2. If you callforwarddirectly on a padded batch, you have to pass theposition_idsthatgeneratemakes, because the KV are rounded after RoPE. Only checked at tiny scale so farFP8Embeddinglearns block scales, so the tables stay in FP8 instead of doubling in size, even withdequantize=True. This is written againstmain, with TODOs to rebase it onto 🚨 [quantization] per-layer quantization plan: mixed NVFP4 + FP8 checkpoints #50245 once that merges, and loading only the experts quantized has to wait for 🚨 [quantization] per-layer quantization plan: mixed NVFP4 + FP8 checkpoints #50245 as well. Only checked at tiny scale, on a checkpoint rewritten in the layout of the real one: the weights load to the right values, but I haven't run the FP8 / FP4 kernels on themFixes #48755
🤖 mlinter review state
fe9ab271f33f0f9e