Repository navigation
DeepSeek-V4.1: compiled training no longer hangs, merged_16bit on the released layout, 5.22 SFT, fp4 full finetuning - #17881
Conversation
…head pair The kept-position loss returned early through its own lm_head + ForCausalLMLoss, so the compiler's fused-CE rewrite never saw it and the full-vocab logits of the kept positions were materialised. Pre-shift the labels (shift_labels) and fall through to the single lm_head / loss_function pair the rewrite replaces; the loss is unchanged (same targets, same reduction).
…odule swap AutoModelForCausalLM.register stores the class object, so the native DeepSeek-V4.1 head loaded on the stock DeepseekV41ForCausalLM while its submodules came from the compiled cache: the compiled head forward (the fused-CE rewrite) never ran and training materialised [batch, seq, 129280] logits. Point each registered class at its modeling module's current class (compiled after the swap, stock after a restore).
…eedy generate vs full recompute Packing (relayout): a 1-token document, one at the sliding window, one past it, one compressor block, one past the indexer budget and an odd one each match the document run alone, the summed loss and every gradient match the per-document sum, and perturbing one document leaves the others unchanged. Generation (no KV cache): greedy generate equals argmax of a fresh full-prefix forward token by token, batch 2 left padded, LoRA on and off.
UNSLOTH_DSV41_FAST_LORA=1 runs the single-adapter LoRA of q_a / q_b / kv / o_b and the shared expert's gate / up / down through Unsloth's fused LoRA_W kernel; dropout, lora_B bias, variants and trainable bases keep PEFT's forward. o_a_proj (grouped: group g's rows of B apply to group g's input), the compressor (the zoo's pooled-LoRA patch reads its weights) and the routed experts (3-D grouped weights) do not fit LoRA_W and stay as they are. Off by default until a Colab A/B shows it faster.
…compiler replaced `copy`) `import copy` next to DeepseekV41GroupState.copy made unsloth_zoo's compiler treat the copy module as a called function of the modeling file: compiled, it inlined the whole copy module source (invalid syntax in the cache); with UNSLOTH_COMPILE_DISABLE it rebound modeling.copy to a function and from_pretrained raised on copy.deepcopy.
Packed uint8 MXFP4 experts cannot require grad, so full finetuning crashed in prepare_model_for_training (only Tensors of floating point dtype can require gradients). With full finetuning the conversion now writes bf16 experts; an explicit UNSLOTH_DSV41_FP4_EXPERTS=mxfp4 with full finetuning is refused with a clear error.
….22 Trainer keywords Trainer.train on transformers 5.22 calls gradient_checkpointing_enable(gradient_checkpointing_kwargs=..., every_n_layers=..., offload=...). The native override only took gradient_checkpointing_kwargs, so SFT raised TypeError. Extra keywords now go to the parent when its signature has them (every_n_layers is honoured on 5.22, the decoder layer is a GradientCheckpointingLayer) and are dropped on an older parent.
unsloth_zoo's merged_16bit rewrites the released checkpoint files and needs the released -> module renames to place each adapter; transformers 5 registers them under the text sub-config, which the merge does not consult, so it merged only engram.wkv and the head (2 of 401 tensors). The class now carries them as _unsloth_checkpoint_conversion_mapping, built from convert.py's table (backreference renames left out).
unsloth_zoo compiles the forwards with dynamic=True and sets torch._dynamo.config.allow_unspec_int_on_nn_module, which turned every module int (compress_ratio, window, head_dim, index_topk, top_k, o_a_proj.in_features, ...) into a SymInt. Shapes then carried floor divisions by a symbolic compress ratio and the trace sat in sympy: compiled fp32 full finetuning was still in the first forward after 30 minutes on B200 (2 CPU cores). The text model forward and the decoder layer forward (which non-reentrant checkpointing re-enters during backward) trace with allow_unspec_int_on_nn_module off, so each layer kind gets its own graph with constant ints; tensor sizes stay dynamic. Same tiny model and 2 cores: fp32 full finetuning step 0 in 321 s, MXFP8 LoRA 437 s, NVFP4 LoRA 220 s, later steps 0.1-2.4 s.
|
@codex review |
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ebfac2737a
ℹ️ 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".
| extras = _fast_lora_extras((proj,), x) | ||
| if extras is None or extras[0] is not None or extras[1][0] is not None: | ||
| return proj(x) # PEFT's forward: a variant, dropout, a lora_B bias or a trainable base |
There was a problem hiding this comment.
Fall back to PEFT when multiple adapters are active
With UNSLOTH_DSV41_FAST_LORA=1, activating multiple LoRA adapters makes the first affected projection fail instead of summing their contributions. _fast_lora_extras does not reject multiple active adapters: its general path inspects only the first adapter and can return (None, (None,)), allowing execution to reach get_lora_parameters, which explicitly raises ValueError when more than one adapter is active. Add the _has_multiple_active_adapters fallback used by apply_lora_o before selecting this fast path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in ff53e11: several active adapters now fall back to PEFT's forward before the fast path (same check as apply_lora_o). The test activates two adapters with UNSLOTH_DSV41_FAST_LORA=1; it raised the single-adapter ValueError before and runs PEFT's forward now.
| extras = _fast_lora_extras((proj,), x) | ||
| if extras is None or extras[0] is not None or extras[1][0] is not None: | ||
| return proj(x) # PEFT's forward: a variant, dropout, a lora_B bias or a trainable base |
There was a problem hiding this comment.
Preserve fake quantization when selecting the fast LoRA path
When UNSLOTH_DSV41_FAST_LORA=1 is combined with QAT, this eligibility check can accept a frozen PEFT base layer that has an activation fake quantizer or uses torchao's forward-only NVFP4/MX fake quantization. Calling LoRA_W directly then bypasses that layer's forward, silently training with different quantization behavior. get_lora_parameters handles explicit weight fake quantizers but does not reproduce activation or forward-only fake quantization. Apply the _has_activation_fake_quantizer fallback already used by apply_lora_o so these projections retain their QAT forward.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in ff53e11: a layer with an activation or forward-only fake quantizer (_has_activation_fake_quantizer, as in apply_lora_o) keeps PEFT's forward, so QAT behaviour is preserved.
…r QAT fake quantization LoRA_W reads one adapter and bypasses the layer's forward, so several active adapters raised in get_lora_parameters and an activation / forward-only fake quantizer was skipped. Same fallbacks as apply_lora_o.
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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]
Follow-ups to the native DeepSeek-V4.1 support (#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=Trueand setsallow_unspec_int_on_nn_module, so every integer module attribute (compress_ratio,window,index_topk, ...) became a SymInt. DeepSeek-V4.1's shapes divide bycompress_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.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=mxfp4is 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_keepand labels. The kept-position loss built full[2, 40, 129280]logits because its own lm_head call was never rewritten, and the class registered onAutoModelForCausalLMwas 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=1still returns logits.import copyin the modeling file. With an older zoo compiler the stdlibcopysource was pasted into the compiled cache (SyntaxError), andUNSLOTH_COMPILE_DISABLE=1brokecopy.deepcopyinfrom_pretrained. Nowfrom copy import deepcopy.Also
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
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.