Skip to content

FSDP2, TP and PP for Qwen3.8-Flash-Next and DeepSeek-V4.1, with frozen engram / n-gram tables never sharded - #17785

Merged
danielhanchen merged 83 commits into
mainfrom
dist-qwen4exp-dsv41
Nov 15, 2026
Merged

danielhanchen merged 83 commits into
mainfrom
dist-qwen4exp-dsv41

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

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 #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 Native DeepSeek-V4.1: modeling ported from the deepseek-ai reference, sparse attention, engram tables, fp8 / MXFP4 release loading #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.

…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.
TP: count gated attention heads ([q, gate] per head in q_proj) from the config, keep the QSA indexer whole on
every rank (it reads only the block input), and treat transformers' embedding_colwise as a replicated style.
PP: send hidden_size * hc_count between stages, run hyper_connection_mixer on the last stage like the final
norm, carry the router aux loss for Qwen4ExpForCausalLM (same router and load_balancing_loss_func as
Qwen3-MoE), and accept its linear / indexed attention layers (no cross-layer state).
FSDP2 keeps frozen _no_placement_params tables (UNSLOTH_FROZEN_TABLE=gpu) out of sharding on every layout, so a
table is never sharded, all-gathered or reduced. DCP state dict calls (Unsloth's wrappers, the Trainer adapter
gather, native_full_state_dict, the HF reader load) hide parameter-free ram / disk tables: torch resolves every key
to a module attribute and the table exports its checkpoint names, so these calls raised and a DCP save would have
written the whole table; a full save adds the table back as zero-copy views. Context parallelism refuses n-gram
lookup tables (ple_layer_ids, engram_layer_ids): a sequence shard would hash its first tokens without the previous
shard's. Tests per parallelism, every table mode, with fault-injection flips.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 3dbb4121f0

ℹ️ 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".

… default

torch 2.15 builds backend "nccl" as ProcessGroupNCCL2 unless
TORCH_DIST_USE_NCCL2=0, so _uses_nccl2 was true for every default run
and the small-GPU warning fired with advice (unset TORCH_DIST_USE_NCCL2)
that does nothing there. 2.15's nccl2 also no longer builds a context on
GPU 0 from the other ranks: 2 x T4, 2 ranks, memory used per GPU after
an all_reduce was 207 / 207 MiB on 2.15 nccl2 against 309 / 207 MiB on
2.14 with TORCH_DIST_USE_NCCL2=1. Warn only on torch < 2.15, and make the
get_backend() fallback follow each version's default.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3a863a9c42

ℹ️ 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".

Comment on lines +1320 to +1322
h, pre_mix, _ = decoder.pipeline_stage_forward(
ctx.start,
ctx.end,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve the FSDP root hooks in the stage-forward path

When DeepSeek-V4.1 pipeline parallelism is composed with native FSDP2 over a data-parallel mesh, this direct call bypasses self.model(...) and therefore the FSDP root's forward hooks. shard_model_layout in fsdp2_perf.py assigns embeddings, final norm, and lm_head to that root; with the root-only LoRA layout, it assigns all adapters there too. Wrapping the outer _PPStageModule does not gather parameters managed by the nested model's separate FSDP group, so these weights remain sharded when this path uses them, causing mixed Tensor/DTensor execution failures. Route stage execution through the managed root's hooks, or explicitly support the alternate forward entry point before permitting this composition.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b823a26: check_pp_dp_composition now refuses native FSDP2 over a pipeline whose stages run the model's own pipeline_stage_forward (DeepSeek-V4.1), before anything is sharded. That composition was never covered, so it now fails loudly with a clear message instead of a mixed Tensor / DTensor error mid-step. Flip test: test_fsdp2_over_its_own_pipeline_stage_forward_is_refused.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: b823a26d4f

ℹ️ 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".

Base automatically changed from deepseek-v41-native to main November 15, 2026 13:38
…ds on GPU hosts, no /proc off Linux, no hang after an expected rank failure

The in-process CPU references (and the gloo ranks) reached Triton kernels wherever a GPU is visible: transformers
picks FLA / causal-conv1d by import, not by device, and Unsloth picks its MoE backend once per process (Triton
grouped GEMM on ROCm), and both reject CPU tensors. cpu_forwards() pins the Qwen4Exp Gated DeltaNet to its torch
functions, as the Qwen3.5 flex decode test does, and the MoE to native_torch, restoring both after. RssAnon and the
fd table come from /proc: off Linux they read None, the memory comparison skips and the open-file check is left
out. The unsafe-cut flip test expects stage 1 to raise; Windows gloo does not see that rank exit, so the others
are stopped 30 s after a rank fails instead of waiting out the 900 s join.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: c16b96c6b6

ℹ️ 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".

[skip ci]
@danielhanchen
danielhanchen merged commit 7600fb7 into main Nov 15, 2026
@danielhanchen
danielhanchen deleted the dist-qwen4exp-dsv41 branch November 15, 2026 20:12
Stanley00 pushed a commit to stanley-fork/unsloth that referenced this pull request Nov 15, 2026
…ip missing model types before the ranks start (unslothai#17870)

Test coverage for tensor parallel on gated-query attention (Qwen3.5 /
Qwen3-Next), plus a test-harness fix. The product fix itself landed on
main in unslothai#17785, which counts gated-query heads from the config. This PR
now only adds tests.

## What the tests pin

- **Qwen3.5 parity under TP:** the cross-architecture gloo parity test
(`tests/test_parallel_general_gloo.py`) gains a tiny `qwen3_5_text`
case, with one Gated DeltaNet layer and one gated attention layer.
`q_proj` emits `[query | gate]` per head. Before the fix, the plan
recorded twice the heads, and `UNSLOTH_TP_SIZE=2` crashed in SDPA on the
first forward. That crash reproduced on Kaggle 2xT4 and gloo CPU. With
main's head count, the loss matches one process and grads are within
1e-6.
- **Skip before the ranks start:** a case whose model type the installed
transformers lacks now skips before any rank starts. On transformers
4.57.6 the skip used to run inside the spawned ranks, which killed both
ranks and errored every case in the module.

## Results

transformers 5.22.1: `-k qwen3_5` passes on current main.
danielhanchen added a commit that referenced this pull request Nov 16, 2026
…5.17 name (qwen_sparse_attention) (#17895)

## Summary

`Repo tests (CPU, gloo)` has failed on `main` since #17785 (FSDP2, TP
and PP for Qwen3.8-Flash-Next and DeepSeek-V4.1). Every
pipeline-parallel cell of `tests/test_qwen4exp_parallel_gloo.py` and
`tests/test_frozen_table_pp_gloo.py` exits with `rank exit codes [1, 1]`
(15 tests):

```
ValueError: Unsloth: pipeline parallelism v1 does not support hybrid layer stacks (layer_types ['qwen_sparse_attention']).
```

#17785 allow-lists Qwen4Exp's layer types for PP as
`{"linear_attention", "indexed_attention"}`. That is what transformers
5.23 calls the QSA layer. transformers 5.17, unsloth's default pin and
what the CPU shards install, calls the same layer
`"qwen_sparse_attention"`; the configuration converts `full_attention`
entries into it. So on 5.17 the guard refuses the exact stack the PR
proved, and users on that pin cannot use PP for Qwen4Exp either.

## Change

- `unsloth/models/pp_native.py`:
`_PP_HYBRID_FAMILIES["Qwen4ExpForCausalLM"]` also allows
`"qwen_sparse_attention"`. The comment notes the rename.
- `tests/test_qwen4exp_parallel_gloo.py`: new
`test_pp_accepts_the_qsa_layer_name_of_every_transformers`, parametrized
over both names. It sets the built model's `layer_types` to each name
and checks `_refuse_unsupported` does not refuse. It runs on whichever
transformers is installed.

## Verification

transformers 5.17.0, `tests/test_frozen_table_pp_gloo.py
tests/test_qwen4exp_parallel_gloo.py`:

| | result |
|---|---|
| main | 15 failed |
| this branch | 22 passed (+2 new) |
| this branch with the `pp_native.py` change reverted | the
`qwen_sparse_attention` case of the new test fails, `indexed_attention`
passes |
Penguinjanator pushed a commit to Penguinjanator/unsloth that referenced this pull request Nov 16, 2026
…on without Triton, kernel and test gates (unslothai#17882)

Backend CI on main has been red since today's merges. Every failure
traces to one commit; this fixes the unsloth side (the gloo-cp shard
also needs unslothai/unsloth-zoo#2542, since CI installs zoo from main).

| CI shard / test | Cause | Fix |
|---|---|---|
| gloo: `test_qwen4exp_parallel_matches_one_process[pp*]`,
`test_pp_splits_streams_and_runs_the_mixer_last`, all of
`test_frozen_table_pp_gloo.py` | unslothai#17785: transformers 5.17 (the CI pin)
names the Qwen4Exp layer type `qwen_sparse_attention`, 5.22 renamed it
`indexed_attention`; pipeline parallel only accepted the new name, so
every rank raised "hybrid layer stacks" | accept both names in
`_PP_HYBRID_FAMILIES` |
| diffusion (Python 3.13): 13 tests in
`test_diffusion_int8_attention_triton_device.py` | unslothai#17855: `_launch`
read `triton.runtime` while `triton` is `None` on that shard | check
`triton is not None` first |
| rest: `test_every_constexpr_line_has_a_comment` | unslothai#17860: 23
uncommented `tl.constexpr` parameters in `large_head_attention.py` |
comments added; `_tma_tile`'s signature split one parameter per line |
| rest: `test_every_launch_requests_fp_fusion` | unslothai#17860: the `_launch`
helper forwards `enable_fp_fusion` from every caller, but the gate did
not know it is a helper | registered like `layernorm.py`'s |
| rest: `test_no_file_is_dropped_or_run_twice` | unslothai#17868:
`tests/test_ddp_push_rank0_gloo.py` matched both the gloo shard and
rest-2's `test_[dimsu]*.py` | renamed
`tests/test_hub_push_rank0_ddp_gloo.py` |
| rest-2: `test_checked_in_file_reads_name_an_encoding` | unslothai#17867:
`read_text()` without an encoding in
`tests/test_bind_local_cuda_device.py` | `encoding = "utf-8"` |
| rest-2:
`test_sentence_transformer_trainer_checks_the_placement_before_the_deferred_compile[*]`
| unslothai#17859: `patch_train_dataloader` assumed every trainer class has
`get_train_dataloader` | skip the patch when the method is missing |
| rest-2:
`test_router_aux_loss_gradient_survives_unsloth_checkpointing[*]` |
unslothai#17873: the gpu-marked test still runs under CI's `-m 'not server and
not e2e'` | `has_real_accelerator()` skip next to the gpu mark |
| studio: `test_no_skip_guard_reads_a_spoofable_accelerator_probe` |
unslothai#17850: `test_block_cudagraphs_side_grad.py` skipped on
`torch.cuda.is_available()`, which the CUDA spoof fakes | skip on
`has_real_cuda()` |

## Tests

In a venv matching CI (Python 3.12, torch 2.10.0+cpu, transformers
5.17.0, TRL 1.15, PEFT 0.21.3, `UNSLOTH_COMPILE_DISABLE=1`, `-m 'not
server and not e2e'`):

- gloo: `test_qwen4exp_parallel_gloo.py` failed on main, 9 / 9 pass
here; `test_frozen_table_pp_gloo.py` 13 / 13.
- rest / rest-2 / studio: the nine affected files had exactly CI's 9
failures on main; 153 passed / 6 skipped here.
- diffusion: with Triton blocked (as on the Python 3.13 shard), the 13
failures pass here; with Triton present everything passes.

The only non-test code changes are the PP layer-type name, the Triton
`None` check and the Sentence Transformers method check;
`large_head_attention.py` changes are comments only.
oobabooga pushed a commit to oobabooga/unsloth that referenced this pull request Nov 17, 2026
… text-only model over a composite config is not multimodal (unslothai#18037)

## Summary

DeepSeek-V4.1 (native `DeepseekV41ForCausalLM`) under
`UNSLOTH_PARALLEL="pp=2"` was refused at trainer init:

```
Unsloth: composition: this cell has no numeric parity / engagement / compile evidence yet: no supported cell covers it (... family='deepseek_v41' ...)
```

The pipeline machinery itself was already on main (unslothai#17785): stages run
through the model's own `pipeline_stage_forward`, cuts land only where
`pipeline_handoff_keys` is empty (no CSA / KV group state crosses a
stage), each engram table lives on the stage that owns its layer, and
the mHC residual streams plus the next sublayer's mixing weights are
carried between stages. What was missing:

1. **Registry**: no MoE row for `deepseek_v41`, so every pp layout fell
to "no supported cell".
2. **Multimodal misread** (`pp_native._media_keys`): the release config
keeps a `vision_config`, but the class has no tower and its forward
takes no image input. Past the registry, PP asked for
`PPConfig(text_only = True)` and then refused for want of towers. A
media config key now counts only when the forward names a media input. A
model whose forward cannot be read keeps the old path, and towers left
beside the decoder are still refused.
3. **`_kernels` misread**: the native port's own `DeepseekV41Attention`
(under `unsloth/models/deepseek_v41/modeling.py`) was read as Unsloth's
fast kernels, so on CPU the query said `kernels=True, loss=fused_ce`.

## Evidence (CPU gloo, fp32, vs one process)


`tests/test_parallel_deepseek_v41_gloo.py::test_deepseek_v41_parallel_matches_one_process`:
losses, every LoRA gradient and the saved adapter.

| case | schedule | micro-batches | checkpointing | routed expert LoRA |
|---|---|---|---|---|
| pp2_gpipe | gpipe | 2 | off | no |
| pp2_1f1b | 1f1b | 2 | off | no |
| pp4_gpipe_mb4 | gpipe, 4 stages | 4 | off | no |
| pp2_gpipe_mb4_gc (new) | gpipe | 4 | zoo replay, non-reentrant | no |
| pp2_1f1b_gc (new) | 1f1b | 2 | zoo replay, non-reentrant | no |
| pp2_gpipe_experts (new) | gpipe | 2 | off | yes (`target_parameters`)
|
| pp2_1f1b_experts_gc (new) | 1f1b | 2 | zoo replay | yes |

Engagement, asserted in every pp case: one `pipeline_stage_forward` call
per micro-batch and step on each rank; each rank holds and steps only
its own layers' adapters; every layer is owned exactly once; engram
tables are real only on the owning stage; under checkpointing the zoo
replay ran. The gloo config now carries the release's `vision_config`.

Flips that must fail:
- `test_pp_reentrant_checkpoint_without_the_replay_breaks_parity`: a
plain reentrant checkpoint without the replay builds the shared KV under
no_grad, so `kv_proj` gradients are wrong.
- `test_pp_cut_at_an_unsafe_layer_breaks_parity` (existing): a stage cut
inside a KV / indexer sharing group raises `KeyError` on the missing
group state.

DeepSeek-V4.1 has no router auxiliary loss, so there is no aux term to
carry.

Cells added: `MoE deepseek_v41 x {lora, lora+experts} x aux off x pp`,
eager attention, gpipe / 1f1b, memory `none` / `gc` / `unsloth_offload`
(Unsloth's offloading checkpoint runs the same zoo replay). Compile
evidence: eager, no compiled region. QLoRA and full finetuning under pp
stay refused.

## Tests

Base = 20d05c2, same venvs, `CUDA_VISIBLE_DEVICES=` (CPU).

| suite | transformers 4.57.6 | transformers 5.22.1 |
|---|---|---|
| new registry tests (7) | base 7 failed, head 7 passed | base 7 failed,
head 7 passed |
| `test_parallel_deepseek_v41_gloo.py` | head 28 passed | head 28 passed
|
| PP suites (`test_pp_native`, `test_pp_env`, `test_pp_moe_aux`,
`test_pp_vlm_text_only`, `test_pp_gemma4_per_layer`) plus the file above
| head 80 passed, 2 skipped | head 102 passed |

Pre-existing on base and head alike:
`test_parallel_capabilities_latent_sinks.py` (2, transformers 4.57.6)
and the float8 cases of `test_parallel_capabilities_precision.py` (10,
no torchao in the 5.22.1 CPU venv).

End to end through `SFTTrainer` on CPU (gloo, fp32, frozen tables on
disk), tiny DeepSeek-V4.1 copy, per-step loss:

| run | step 1 | step 2 | step 3 | step 4 |
|---|---|---|---|---|
| one process | 11.859791 | 11.778872 | 11.483759 | 11.505252 |
| pp=2 | 11.859791 | 11.778872 | 11.483751 | 11.505269 |
| pp=2, `use_gradient_checkpointing = "unsloth"` | 11.859791 | 11.778872
| 11.483751 | 11.505269 |

## Kaggle 2x T4 (fake DeepSeek-V4.1-Flash, 16-bit LoRA, docs harness)

`unsloth/DeepSeek-V4.1-Flash-1017` shrunk to a random-weight copy (real
config, engram tables, mHC, compress ratios), seq 1024, global batch 8
rows, 25 steps, fp16, `use_gradient_checkpointing = "unsloth"`,
adamw_8bit, torch 2.14.1, transformers 5.17.0.

| arm | result | steady tok/s | peak reserved per GPU |
|---|---|---|---|
| base 20d05c2, 1 GPU | trains | 618 | 3.89 GB |
| base 20d05c2, pp=2 | refused at trainer init (`no numeric parity /
engagement / compile evidence`) | - | - |
| head, pp=2 | trains, 25 steps | 621 | 2.76 GB / 3.77 GB |

Per-step loss, pp=2 against 1 GPU: largest gap 0.0014 (step 17), step 1
12.0205 vs 12.0204. The 1-GPU and base pp rows come from an earlier job
of the same harness on the same build; head ran the pp arm only.

pp=2 is not faster than one T4 at this size: the second stage idles
through the gpipe bubble. Its use is fitting a model whose layers do not
fit one card.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant