Repository navigation
Native DeepSeek-V4.1: modeling ported from the deepseek-ai reference, sparse attention, engram tables, fp8 / MXFP4 release loading - #17778
Conversation
…out on transformers 4
…ate, no graph breaks, engagement counters
…hash with left context, TP / PP plans
…outer backward convert.py streams the released checkpoint (DeepSeek names, per-expert fp4, ue8m0 fp8 blocks) into the native layout once and caches it, for transformers without core_model_loading (4.57) or an FP8 quantizer without fp4 experts. On 5.22 the converted load is bit-identical to transformers' own. sqrtsoftplus: clamp softplus at the smallest normal before the sqrt, so a logit below about -104 no longer gives 0/0 NaN gradients. Tests: conversion round trip, fp4 nibble order, router NaN, asymmetric SwiGLU clamp, fp32 eps, num_items_in_batch, caller cache untouched, per-group compressed KV.
On transformers that load the release through convert.py (dequantized), the config no longer carries the release's FP8 quantization_config, and from_pretrained drops one a caller carried over. Unsloth's loader then sees a 16-bit model and honours load_in_4bit (102 Linear4bit on 4.57.6) instead of treating it as pre-quantized. bitsandbytes configs are kept.
…experts The mHC projection and Sinkhorn loop are matched verbatim by unsloth_zoo's compiler (eager projection recompute, compiled Sinkhorn), and the routed experts forward carries the annotations the MoE backend's strict patch check compares.
get_peft_model asks a model with unsloth_lora_target_modules to translate q/k/v/o/gate/up/down_proj, "all-linear" and None. DeepSeek-V4.1 maps them to q_a/q_b, the single KV head, the compressor, the engram wkv, o_a/o_b and the shared and routed experts. The indexer (selection only) and the routers are never targeted; a caller's regex passes through.
position_ids restarting at 0 (padding-free packing) and left padding are moved to one sequence per row from column 0, run exactly as the reference runs a single sequence, and put back. Compressor groups, the sliding window, top-k blocks and engram n-grams never cross a sequence boundary. Plain and right-padded batches skip it after one device-side flag read. Offset positions (a continuation) are still refused, with a clear message.
A model built on DeepseekV41TextConfig saves a flat config.json; loading it with DeepseekV41ForCausalLM.from_pretrained went through the composite config and silently took the released defaults. Its fields now form the text config. Found by running unsloth_zoo's DeepSeek-V4.1 tests against this module.
FastLanguageModel passes finetune_vision_layers = False, which routed the model's remapped (qualified) target names through get_peft_regex; it read them as leaves and dropped self_attn.* and engram.wkv. The remapped list is already final. B200: default targets and all-linear now reach q_a/q_b, kv, o_a/o_b, the compressor, engram wkv, shared and routed experts; no indexer.
The per-forward group state (compressed KV, indexer keys, top-k, candidates) was a dict. FSDP2's _cast_forward_inputs (torch.distributed.utils. _apply_to_tensors) rebuilds every dict argument, subclasses included, so a source layer's writes landed in a copy and later layers raised KeyError. DeepseekV41GroupState is a __slots__ object with the mapping methods the layers use; accelerate's hooks and FSDP2 pass it through. Dynamo explain: 0 graph breaks, including two layers handing state over.
A bitsandbytes load that does not skip o_a_proj (transformers 4.57 without Unsloth's skip list) replaces the grouped Linear subclass with a plain Linear4bit, which multiplied every head group by the whole stacked weight. The attention now takes the diagonal blocks of such a product, exactly the grouped result, decided from shapes alone (tensor-parallel shards too). Grouped LoRA is unchanged; plain PEFT LoRA on the swapped layer matches its merged weight.
A checkpoint saved from a model built on DeepseekV41TextConfig has model_type deepseek_v41_text, which no causal-LM class was registered for. DeepseekV41TextForCausalLM (same modules, text config class) is registered for it, with the same conversion rules.
pipeline_stage_forward(start, end, ...) runs one stage: residual streams and the lagged pre_mix cross the boundary, plus only the group state keys the later layers read (pipeline_handoff_keys; empty at the safe cut points). A stage that owns an engram layer hashes input_ids and reads its own tables, so engram rows never cross. Any cut gives the unsplit model's hidden states and gradients.
The group state object only has to survive the decoder layer boundary. Passing
it into the compiled attention changed how Dynamo lifted its tensors, and
Inductor's backward then failed codegen ("expected [s32] to have been
codegen-ed"). The attention reads the dict inside again; B200: compiled
training back to 0 graph breaks, 12 graphs, same losses as before.
…a layer Applies plans/dsv41_shared_state.patch: the per-forward group state is the non-dict _SharedState (accelerate's send_to_device and FSDP2's input cast rebuild every dict / Mapping argument, keyword or positional), with its accelerate tests (whole-layer hooks with / without skip_keys, hooks on every submodule) and the send_to_device / _apply_to_tensors identity check. DeepseekV41GroupState stays as its public name for pipeline callers. Merged with the earlier fix: inside a decoder layer self_attn and the indexer take the plain dict by keyword shared=, which _skip_keys_device_placement exempts on their offload hooks. Handing the object itself into the compiled attention breaks Inductor's backward codegen (B200: "expected [s32] to have been codegen-ed", also when the attention unwraps it first). Dynamo explain: 0 graph breaks.
unsloth_zoo's frozen table lookup now hands its stores a host copy of the ids (host_ids=, one sync per host lookup, none in gpu mode). The in-memory store of a model built from a config takes and ignores it.
unsloth_zoo's sync-free gpu-mode lookup (frozen-table-gpu-nosync) asks the store whether its rows already sit on the ids' device. Native tests pass against both unsloth_zoo trees, with and without that change.
The registration ran from _gpu_init, which the CPU fallback never imports, so AutoConfig rejected deepseek_v41 there. Run it from unsloth/__init__ after either backend initialises.
…l is built Plain PEFT (and the CPU backend, which never ran the zoo patch) wrapped the grouped o_a_proj with an ungrouped LoRA, failing with a shape mismatch. The attention constructor now installs unsloth_zoo's grouped LoRA dispatch once (no-op without unsloth_zoo).
…el is unavailable Newer transformers route grouped fp8 eval / generate through a Hub kernel loaded via the optional kernels package, which fails without it (DeepSeek-V4.1 fp8 o_a_proj). Eval now takes the same dequant path as training unless that kernel can load; no new dependency.
…4-packed The release's experts are e2m1 pairs with one e8m0 scale per 32, which is MXFP4. convert.py now stores them as packed blocks + uint8 scales instead of dequantizing to bf16 (a quarter of the memory, no bf16 expert copy on disk); the native experts load them as unsloth_zoo Mxfp4ExpertParam stacks with the bf16 logical shapes, so Unsloth's grouped MoE backend and expert LoRA apply unchanged. UNSLOTH_DSV41_FP4_EXPERTS=bf16 keeps the dense conversion. Full saves follow unsloth_zoo's dense MXFP4 save (config flag dropped), plain saves write blocks + scales and reload packed. The conversion path also recommends a recent transformers 5.x, which loads the release directly.
…window The window rows stay contiguous and go to unsloth_zoo.sparse_attention.sparse_attn_window (banded window kernel merged with the compressed index kernel) with the indexer's rows shifted back into compress_kv; window-only layers pass an empty compressed set. An unsloth_zoo without the entry, UNSLOTH_DSV41_SPARSE_ATTN_WINDOW=0 or UNSLOTH_DSV41_SPARSE_ATTN=0 keep the concatenated index path. fp32 logits and gradients are bit-equal to the concatenated path.
…, never random-init silently On transformers 5 a passed DeepseekV41TextConfig (or DeepseekV41TextForCausalLM's own config class) lacked the release's FP8 quantization_config and dtype, so the fp8 / fp4 tensors could not load (F8_E8M0) or were skipped. The checkpoint's quantization_config and dtype are attached to such a config, as the checkpoint's own config has them. A released-layout load that leaves any model weight missing now raises instead of returning randomly initialised weights. Tested for AutoModelForCausalLM, DeepseekV41ForCausalLM and DeepseekV41TextForCausalLM, with and without an explicit composite or text config, through the converter and transformers' own loader.
…ssing layers a window kernel CUDA, head_dim 512, bf16: per attention call the zoo backend counters show hd512 for compress_ratio 0 layers (empty compressed set) and gather / triton for compressing layers; logits match the concatenated path.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
… engram ids required, compiled relayout, kept-position logits - Building the text model installs unsloth_zoo's decoder-layer replay whatever was imported first, and gradient_checkpointing_enable fails closed without it; grouped LoRA is marked ready only once PEFT's dispatcher carries the handler, and a plain PEFT LoRA around o_a_proj takes the per-group blocks of its delta. - Calls (and pipeline stages) that run an engram layer without input_ids raise instead of skipping the engram rows. - The packed-row / left-padding relayout runs outside the traced graph, so torch.compile keeps it. - labels with logits_to_keep score the kept positions against their own shifted targets, tensor logits_to_keep selects those positions, and generation projects only the last position. - Tests: each release rename applies once per model root; subprocess tests drop every backend-steering variable (UNSLOTH_ZOO_DISABLE_GPU_INIT included) from the child env.
…FT's own LoRA layer Grouped LoRA handlers (unsloth / unsloth_zoo, tensor-parallel aware) also carry base_layer and lora_A; they run their own forward again (the fallback bypassed them and mixed DTensor and Tensor under TP).
…ads the release itself
The repo's encoding gate: config / index JSON and the conversion marker no longer take the operator's locale encoding.
…UDA skips on the real device Tests that need unsloth-zoo #2510 (the native module resolver behind the checkpoint replay and grouped LoRA, the parameter-free engram table) skip on an unsloth_zoo without that capability, probed directly; a new test checks gradient checkpointing fails closed without the replay. CUDA-only skips read has_real_cuda(), which the CUDA spoof cannot flip. [skip ci]
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
The reference computes both in fp32 (model.py:819, 955). Inside an fp16 autocast region F.linear ran them as fp16 matmuls, and the unnormalised mHC projection (applied before the RMS scale) overflows fp16 into NaN mixes and gradients. fp32_linear disables autocast around the two projections.
_fp8_grouped_eval_kernel_ok() read transformers' module source with inspect.getsource from inside the forward, which Dynamo cannot trace, so a fullgraph compile of an eval FP8GroupedLinear failed. The answer does not change at runtime: compute it once at import and read a plain bool.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ba2ccd3407
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| for f in sorted(os.listdir(src)): | ||
| if f.endswith((".safetensors", ".json")): | ||
| st = os.stat(os.path.join(src, f)) | ||
| stamp.append(f"{f}:{st.st_size}:{st.st_mtime_ns}:{st.st_ino}") |
There was a problem hiding this comment.
Include indexed nested shards in the conversion cache identity
For a local checkpoint whose index references a relative shard such as shards/weights.safetensors, replacing or updating that shard does not change this digest: only immediate .safetensors and .json children of src are inspected. _read_index explicitly accepts these nested paths, so after the first conversion, subsequent loads silently reuse the old converted weights despite changes to the source checkpoint. Build the stamp from every shard referenced by the index, including its relative path and file metadata.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing this: released DeepSeek-V4.1 checkpoints keep their shards flat next to the index, and a local checkpoint whose nested shard is rewritten in place is not a layout we support. Setting UNSLOTH_DSV41_CONVERTED_DIR or deleting the converted dir forces a reconvert.
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
[skip ci]
…n engram / n-gram tables never sharded (unslothai#17785) FSDP2, tensor parallel and pipeline parallel for Qwen3.8-Flash-Next (`qwen4_exp`) and native DeepSeek-V4.1, with the frozen n-gram / engram lookup tables handled correctly under each. Stacked on unslothai#17778 (native DeepSeek-V4.1); the diff here is only this PR's commits. The zoo side is unslothai/unsloth-zoo#2507 (sync-free resident lookups, bounded recompute memo, provenance metadata). With an older unsloth_zoo, the memo sizing and provenance steps are skipped. ## Frozen lookup tables Qwen3.8-Flash-Next's PLE n-gram table and DeepSeek-V4.1's engram tables are huge, frozen, and read from the base checkpoint by unsloth_zoo's frozen table store (gpu / ram / disk). They must never be sharded or all-gathered, and the ram / disk tables must never be written into a distributed checkpoint. A table held resident in GPU memory is an ordinary frozen parameter, so a full DCP save includes it like any other frozen base weight; an adapter-only save does not. - **FSDP2:** resident tables (`UNSLOTH_FROZEN_TABLE=gpu`) are kept out of sharding on every layout. DCP state-dict calls hide the parameter-free ram / disk tables. Before, those calls raised, and a DCP save would have written the whole table. A full save adds the table back as zero-copy views. - **Tensor parallel:** tables stay whole on every rank, and lookups are bitwise equal to the single process. Per-rank resident memory grows by about 5 MiB. - **Pipeline parallel:** - A table stays on the stage that owns its layer; other stages get a stub that does no lookup. - Each table gets one recompute memo slot per micro-batch in flight (GPipe: all of them; 1F1B: the stages from this one to the last), so under 1F1B with checkpointing it is read once per micro-batch per step instead of twice. - `PPConfig.frozen_table_memo_slots` overrides the count, and `last_table_memo` records hits and misses. - **Context parallel** refuses n-gram tables: a sequence shard would hash its first tokens without the previous shard's. - **Provenance:** adapter saves write `frozen_tables.json` next to the adapter: repo id, revision, file sizes, header and sampled content digests. This covers single GPU, FSDP2, TP through `save_tp_adapter`, and PP with every stage's tables gathered to the writer. `PeftModel.from_pretrained` and `load_adapter` compare it with the tables bound in the model and warn on a mismatch (`UNSLOTH_FROZEN_TABLE_PROVENANCE=strict` raises, `off` skips). ## Qwen3.8-Flash-Next - **TP:** gated attention heads (`[q, gate]` per head in `q_proj`) are counted from the config. The QSA indexer stays whole on every rank, since it reads only the block input. transformers' `embedding_colwise` is treated as a replicated style. - **PP:** `hidden_size * hc_count` is sent between stages, and `hyper_connection_mixer` runs on the last stage like the final norm. The router aux loss is carried, the same as Qwen3-MoE. The linear and indexed attention layers are accepted, since they keep no cross-layer state. ## DeepSeek-V4.1 - **TP** (latent-query MQA): - Query heads, their attention sinks and whole `o_a_proj` groups shard, and `o_b_proj` is rowwise. - The query latent, the one key / value head, the compressor, the indexer, MoE, engram and hyper-connections stay whole on every rank, with their gradients summed over the TP group. - `o_a_proj` runs a grouped local GEMM. Its grouped LoRA keeps `lora_A` replicated and `lora_B` sharded with the groups. - A TP size that splits an output group is refused. - **PP:** - Stages run only their own layers through the model's `pipeline_stage_forward`, so each stage hashes the ids and reads only its own engram tables. - Cuts are allowed only where `pipeline_handoff_keys(config, cut)` is empty, so the compressed KV / indexer / top-k group state never crosses a stage. - Several-tensor layer outputs (`h, pre_mix`) are carried in their own dtypes. - Packed or left-padded rows are refused for now. - **FSDP2:** the units are exactly the decoder layers. A unit at `self_attn` is refused, because it would lose the group state the next layer reads. ## Review hardening - **Table export:** the full export adds the tables only where the full state dict ends up (writer ownership), with canonical keys (no `_orig_mod.`). - **DCP protection:** the guard needs only torch, not bitsandbytes, and is installed for every native FSDP2 precision and for tensor parallel. - **Provenance:** - Hub adapter ids fetch `frozen_tables.json` through the Hub cache with the load's revision / subfolder / token, only when the model has frozen tables; - each named adapter gets its own record (PEFT and PP); - the strict check runs before anything touches the model; - native checkpoint resume checks the root and every named adapter before reading. - **Grouped LoRA under TP:** each grouped linear takes its own groups' slice of the one-process dropout mask (exact parity at p=0.3). - **Pipeline parallel:** - stage boundaries compile with `fullgraph=True`; - DeepSeek-V4.1 accepts ordinary sequential `position_ids`, and only packed or left-padded rows are refused. ## Tests - **CPU gloo, DeepSeek-V4.1** (`tests/test_deepseek_v41_parallel_gloo.py`): - TP 2 and 4, FSDP2, PP 2 GPipe and 1F1B, PP 4 with 4 micro-batches, interleaved 1F1B and ZBV, with LoRA and QLoRA layouts; - losses bitwise, gradients within 1.1e-5, saved adapters matching; - flips: an unsafe cut and a missing gradient sum are caught. - **CPU gloo, Qwen3.8-Flash-Next** (`tests/test_qwen4exp_parallel_gloo.py`): TP and PP parity in bf16 and fp16. - **Frozen tables** under FSDP2, TP, PP and CP in every table mode, with fault-injection flips (wrong rows, a sharded table), plus provenance save / load. - **Results:** 163 passed, 2 skipped (CUDA) on CPU with transformers 5.22.1, including the native DeepSeek-V4.1 suite from unslothai#17778. Every fix from review has a test that fails on the previous head. - **B200, several NCCL ranks on one card, correctness only:** - FSDP2 and PP with LoRA / QLoRA, and PP 1F1B, are bitwise; - TP in fp32 is within 7e-6; - TP in bf16 is within the reduction-order A/A noise of the single process. ## Not covered - PP cuts that need a non-empty group-state handoff. - PP with packed or left-padded rows (refused). - PP x TP and TP x FSDP2 composition for DeepSeek-V4.1. - Runs on separate physical GPUs; the B200 runs put all ranks on one card. ## Recheck follow-ups - A strict provenance check no longer rejects the same checkpoint when a table moves between ram / disk and gpu residence (`test_reload_with_the_table_resident_is_not_a_mismatch`). - The provenance sidecar is read and written as UTF-8 (Windows code pages), with an AST test over every `open()` in the module. - `_weight` in tensor parallel tolerates modules without `_modules` / `_parameters` (the TP dropout precision tests use plain namespaces). - The DeepSeek-V4.1 gloo suite is now `tests/test_parallel_deepseek_v41_gloo.py`, so exactly one CI shard collects it, and its zero-bubble V-schedule cell skips below torch 2.12 like the other V-schedule tests. - Frozen-table PP / TP / FSDP2 / CP gloo suites plus provenance: 56 passed on CPU.
…M, unsloth GC offload on the replay (unslothai#2524) Three DeepSeek-V4.1 training fixes. The biggest one also affects every DeepSeek-V4 / V4.1 release loaded on transformers 5.x. ## 1. FP4 routed experts take the fused MXFP4 grouped GEMM On transformers 5.x, the released checkpoints' FP4 routed experts load into transformers' own `FP8Experts(expert_dtype="fp4")`. They are not loaded as Unsloth's `Mxfp4ExpertParam`. That layout is int8 `(E, M, K / 2)` with the e2m1 low nibble first and one ue8m0 scale per 32 along K, which is MXFP4. `forward_moe_backend_fp8` dequantized both whole expert stacks to bf16 on every forward, and again on the checkpoint replay. On the grouped_mm backend, the stacks are now passed to the existing MXFP4 grouped GEMM as `Mxfp4ExpertParam` views, with no copy. The GEMM decodes them itself; above the fused row limit, only the experts that actually got tokens are dequantized. `UNSLOTH_FP8_EXPERTS_MXFP4=0` restores the old path. One MoE layer at real DeepSeek-V4.1 dims (hidden 5120, moe_intermediate 2304, top-6), forward plus dX, on a Colab L4. Arms were interleaved 5 times; the range is the A/A spread. | Tokens | Fused | Whole-stack dequant (before) | Speedup | Peak GB fused / before | |---|---|---|---|---| | 1K | 24.8 ms (24.3 - 25.0) | 145.5 ms (145.4 - 145.6) | 5.9x | 1.8 / 6.0 | | 4K | 63.5 ms (61.2 - 64.0) | 151.4 ms (151.3 - 151.5) | 2.4x | 2.0 / 6.2 | Against an fp32 reference at real dims, fused and dequant each come out 2.3e-3 relative. On the tiny released-layout checkpoint (transformers 5.23): - At 96 tokens: 48 fused calls and 0 whole-stack dequants, against 48 dequants before. - At 1024 tokens: it falls back to per-expert dequant. - In both cases, loss and all 130 gradients are bitwise equal to the old path. ## 2. `use_gradient_checkpointing = "unsloth"` offloads activations on the DeepSeek-V4.1 replay `_non_reentrant_checkpoint()` always returned torch's own checkpoint, so the replaying layer bypassed Unsloth's non-reentrant wrapper and never offloaded a saved activation. It now uses the layer's `_gradient_checkpointing_func` when that is Unsloth's wrapper, and torch's checkpoint otherwise. On L4: 11 activations offloaded with `"unsloth"`, 0 with `True`, and gradients bitwise equal. ## 3. Triton MoE configs are settled before the checkpointed forward The Triton MoE backend tunes its kernel configs on an experts module's first forward. Under torch.compile, that first call graph-breaks at the compiler-disabled tuner and later calls do not. The forced non-reentrant recompute therefore traced a different graph than the forward did, and backward raised `CheckpointError` (recomputed tensors with different metadata). The replay path now runs one eager token through the experts first, so both passes trace the same graph. ## Tests - `tests/test_moe_fp4_experts_mxfp4_route.py` (GPU): - On main: 0 fused calls, so it fails. - On this PR: passes in a few seconds, with output and dX matching the dequant path. - Skips on transformers 4.x, which has no `FP8Experts`. - `tests/test_deepseek_v41_training.py`: the offload check (offloaded count > 0 with `"unsloth"`, 0 with `True`). - `tests/test_deepseek_v41_native_moe.py`: the compiled Triton MoE replay under forced non-reentrant checkpointing. Results (B200 used for correctness only): | Run | Result | |---|---| | B200, transformers 5.23, FP4 route | 2 passed | | B200, DeepSeek MoE / training / mHC tests with the native DeepSeek module | 31 passed, 15 skipped (sm100-only or 2-GPU) | | Colab L4 | MoE / MXFP4 73 passed, 41 skipped; DeepSeek training 18 passed | | Kaggle T4, transformers 4.57.6 | 58 passed, 56 skipped (bf16 / sm80+ only); DeepSeek training 18 passed | The DeepSeek-V4.1 tests skip without Unsloth's native DeepSeek-V4.1 module (unslothai/unsloth#17778).
… released layout, 5.22 SFT, fp4 full finetuning (unslothai#17881) Follow-ups to the native DeepSeek-V4.1 support (unslothai#17778) found while testing every training mode on the tiny released checkpoint. Each fix has a test that fails on main and passes here. ## Fixes **Compiled training hung in Inductor.** unsloth_zoo compiles with `dynamic=True` and sets `allow_unspec_int_on_nn_module`, so every integer module attribute (`compress_ratio`, `window`, `index_topk`, ...) became a SymInt. DeepSeek-V4.1's shapes divide by `compress_ratio`, and tracing got stuck simplifying the nested floor-div / mod expressions. The text model and decoder layer forwards now trace with that flag off, so per-layer config ints are constants and tensor sizes stay dynamic. | B200, tiny model, step 0 (correctness only) | main | this PR | |---|---|---| | compiled fp32 full finetuning | still in the first forward after 1804 s | 321 s | | compiled MXFP8 LoRA | not measured | 437 s | | compiled NVFP4 LoRA | 323 s, with the config ints traced symbolic | 220 s | Later steps take 0.1 to 2.4 s. **merged_16bit dropped almost every LoRA delta on the released layout** (with unslothai/unsloth-zoo#2541). transformers 5 registers the released-checkpoint renames under the text sub-config, which the merge never read, so only 2 of 401 tensors changed. The model class now declares its renames for the zoo merge. On L4 all 264 tensors that PEFT's own merge changes are changed; the worst error is 1.4% of the delta (bf16 rounding). **SFT raised TypeError on transformers 5.22.** The Trainer calls `gradient_checkpointing_enable(every_n_layers=..., offload=...)`; the native override now forwards extra keywords when the parent accepts them and drops them on 4.x. **Full finetuning crashed on packed fp4 experts** ("only Tensors of floating point dtype can require gradients"). Full finetuning now converts the routed experts to bf16; an explicit `UNSLOTH_DSV41_FP4_EXPERTS=mxfp4` is refused with a clear error. Tiny released checkpoint, bf16 full finetuning vs fp32 reference: loss 11.83989 vs 11.83914. **Fused CE with `logits_to_keep` and labels.** The kept-position loss built full `[2, 40, 129280]` logits because its own lm_head call was never rewritten, and the class registered on `AutoModelForCausalLM` was the stock one instead of the compiled one. Now the fused loss runs (1 call, no full-vocab logits; loss 11.798982 vs 11.799029). `UNSLOTH_RETURN_LOGITS=1` still returns logits. **`import copy` in the modeling file.** With an older zoo compiler the stdlib `copy` source was pasted into the compiled cache (SyntaxError), and `UNSLOTH_COMPILE_DISABLE=1` broke `copy.deepcopy` in `from_pretrained`. Now `from copy import deepcopy`. ## Also - Opt-in fast LoRA (`UNSLOTH_DSV41_FAST_LORA=1`) for the plain projections (q_a, q_b, kv, o_b, shared expert) through the fused LoRA kernel. Loss is identical eager fp32 and within bf16 noise compiled (0 graph breaks, 14 graphs either way). Off by default until a speed A/B shows a gain. - Tests for packed documents at every attention boundary and greedy generate vs full-prefix recompute. ## Tests CPU, the 7 DeepSeek-V4.1 test files: main 8 failed + 1 collection error; this PR 134 passed / 10 skipped on transformers 4.57.6, and the same on 5.23.0. The merged_16bit fix needs unslothai/unsloth-zoo#2541; without it the merge behaves as on main.
Native DeepSeek-V4.1 in Unsloth (
unsloth/models/deepseek_v41), so LoRA / QLoRA training no longer depends on a community transformers port. transformers has nodeepseek_v41model; the port we used failed on the fake medium model (fp16Half != float, and its fp8 tables needed thekernelspackage).The modeling is ported from deepseek-ai's reference (
inference/model.py,kernel.py,engram.py,convert.py) and cross-checked against vLLM's and SGLang's DeepSeek-V4 implementations. It covers the training path: full-sequence prefill and HFPreTrainedModel/GenerationMixin, with a simple cache forgenerate.Needs unslothai/unsloth-zoo#2509 (sparse attention) and unslothai/unsloth-zoo#2510 (resolver, compiler, MoE backend, engram tables). #2510 is stacked on unslothai/unsloth-zoo#2507.
What it implements
Attention:
compress_ratios0 / 1 / 2);o_a_proj(8 groups), with a grouped LoRA installed when the model is built.It runs through unsloth-zoo's
sparse_attn_window, which picks the Triton, flex, hd512 or gather kernel for the GPU.UNSLOTH_DSV41_SPARSE_ATTN=0uses the torch reference, andUNSLOTH_DSV41_SPARSE_ATTN_WINDOW=0routes the window through the index path.Other blocks:
Checkpoint formats:
from_pretrainedand through transformers' owncore_model_loadingrenaming table. Tested on transformers 4.57.6 and 5.22.1.kernelspackage.UNSLOTH_DSV41_FP4_EXPERTS=bf16keeps the old dequantized load, needed for full finetuning).Training details:
Distributed: the group state is a
_SharedStatethat survives FSDP2 input casting. There are TP / PP plans and a pipeline stage forward with the group state handoff. Distributed training itself is a follow-up PR.Registration:
AutoConfig/AutoModel/AutoModelForCausalLMon the GPU and CPU backends (idempotent). Nothing is registered when transformers shipsdeepseek_v41.Review hardening
..paths) before opening;st_mtime_nsand inode.subfolderis kept through discovery, conversion and tokenizer binding;llama.pypath routes models exposingunsloth_lora_target_modulestoFastBaseModel.gradient_checkpointing_enableraises if it is missing. Gradients with checkpointing are exact in a fresh process.input_idsraise;logits_to_keepwith labels and as a tensor are handled;encoding = "utf-8".has_real_cuda().Results
Correctness:
from_pretrainedcall shape on a tiny fp8 / fp4 release fixture, and the released-layout guard.Speed on a 1.45B-scale fake DeepSeek-V4.1 (real config shrunk, random weights; Colab L4, compiled). Unsloth's sparse kernels against the torch reference path:
Losses are equal to 4 decimals. The window entry and the index path give the same step time at 1-2K tokens (327.8 / 315.6 vs 319.6 / 318.7 ms at 1024 in one session), since attention is not the bottleneck there.
Not covered here