Repository navigation
UNSLOTH_PARALLEL: one flag and one root mesh for dp / tp / pp / cp, pipeline parallel from the environment, and a capability registry - #16407
Merged
Conversation
…l forward, kept CPU replica PipelineParallel.step takes n_microbatches / loss_scale per call (schedules cached per count and shape), a DDP-style data parallel mesh (ddp_mesh: loss normalised over the dp replicas' tokens, gradients averaged by the caller) and a forward-only eval_loss. PPConfig(keep_replica = True) keeps the other stages' layers, embedding and lm_head on the CPU instead of dropping them, so the whole model can be rebuilt after training. check_pipeline_model runs the split's structural checks without splitting.
… the post-training cells UNSLOTH_PP_SIZE=m (with UNSLOTH_TP_SIZE and / or UNSLOTH_FSDP2=1 / DDP-style data parallel) runs unmodified scripts under torchrun. The layout (pp x dp x tp, torchtitan order) is read once; sizes that do not divide WORLD_SIZE, a bad UNSLOTH_PP_MICROBATCHES / UNSLOTH_PP_SCHEDULE, vLLM, full finetuning and models the split refuses are refused at from_pretrained, naming the variable. Trainer.__init__ splits the model, applies tensor parallel inside the stage, then FSDP2 over dp. Trainer / SFTTrainer: training_step runs PipelineParallel.step (no second backward), micro-batches from the Trainer batch (default 2 x pp, lowered to a divisor), the loss normalised over the accumulation window's tokens of every dp replica, every stage of a replica reads the same rows, clipping and the fp16 skip are global, accelerator.gather counts the dp group only, evaluation runs the pipeline forward, save_model writes the one-GPU adapter from rank 0 and checkpoints keep per-rank optimizer state. GRPO / DPO and other RL trainers, custom compute_loss and packing are refused (padding-free auto choice is skipped). for_inference / generate / merged and GGUF exports put the whole model back on each rank (the kept CPU copies plus the trained weights of every stage) when it fits, else refuse with the memory numbers; save_pretrained of the adapter gathers the LoRA weights only.
pp 2, pp 2 x tp 2, pp 2 x dp 2 (DDP-style and native FSDP2): losses, grad norms, eval loss, the saved adapter (save_pretrained and Trainer.save_model), greedy generate and a rank-0 export through the rebuilt replica, then training again. Gradient accumulation and micro-batch counts, layout parsing and the load / Trainer refusals.
…/ export refusal; resume test tensor parallel's generate wrapper runs first on a pp x tp model: it now gives the pipeline replica's reason (and the variable to unset). The Trainer refusal for a model split by hand keeps its wording. Checkpoint resume under pp 2 and pp 2 x dp 2 equals the uninterrupted run bitwise.
…oth forwards Kaggle T4x2 (torch 2.10, transformers 4.57.6) runs of unmodified notebook scripts found: - tokenizer collators return BatchEncoding: accept any Mapping batch; - torch 2.10's GPipe (and 1F1B everywhere) needs at least pp micro-batches, so a batch smaller than that gets fully masked filler rows (labels -100: no loss, no gradient); - the loss normalisation check missed Unsloth's patched / compiled forwards (which take num_items_in_batch): walk wrapped / closed-over functions and trust Unsloth's own, and name the forward in the refusal.
… micro-batches Evaluation divides by the count this Trainer uses on one GPU (_get_num_items_in_batch for this replica's batch: unshifted labels on transformers 4.x), so the eval loss equals the one-process value on 4.57 and 5.x. A micro-batch count below what the schedule needs (UNSLOTH_PP_MICROBATCHES=1 on torch 2.10) keeps the real rows in their own micro-batch and adds whole micro-batches of masked filler rows.
… its Accelerate wrapper The clip unscaled the AcceleratedOptimizer, while AcceleratedOptimizer.step hands the GradScaler the torch optimizer: the scaler keeps its unscaled state per optimizer, so it unscaled the gradients a second time and every fp16 update was 1 / scale of the right one (Kaggle T4: Qwen3-4B step-3 loss 1.2832 vs 1.2466 on one GPU, gradients equal). Test pins both: the update equals the unscaled gradient, and the old lookup is 1 / 1024.
…ns in float32 Gemma 3 on a T4 keeps a float16 embedding but trains in float32 (UNSLOTH_FORCE_FLOAT32, stamped _unsloth_forced_float32): its hidden states overflow float16, so the stage boundary cast turned them to inf and every pipeline loss was NaN (Kaggle T4x2, Gemma3 270M). The default activation dtype is float32 for those models, the embedding dtype otherwise.
…en ids Stages after the first ran the model forward on zeros in place of input_ids (the embedding stub ignores them). Model-level code that reads input_ids then saw a batch of token 0, which is Gemma's pad token. Every rank holds the batch anyway, so the schedule now hands each later stage its micro-batch's real ids. The env Trainer test checks that the last stage's forwards see the batch's ids.
…tput dtype Model-level masks and rotary tables on the later stages are built from the embedding output; a patched / scaled embedding can return a wider dtype than its weight, and the stub now returns zeros in that dtype (probed once on one token at the split).
…does, naming the pipeline variable
…ZE before the trainer splits the model The CP manager builds its own (dp, cp) mesh, whose cp groups are the tensor parallel groups of a tp launch and the stage data parallel groups of a pp launch. On 4 gloo ranks both runs trained without an error and with the wrong loss (tp 2 x cp 2: 10.3854 vs 10.3726 in one process; pp 2 x cp 2: 10.3762 vs 10.3726). Refuse until the layouts compose, naming the variable and the alternatives.
…ed, CP backend auto, capability registry UNSLOTH_PARALLEL="dp=..,tp=..,pp=..,cp=..[,cp_backend=..][,fsdp=0|1][,pp_schedule=..][,pp_microbatches=..]" is parsed once at import (unsloth/parallel_env.py) and written to UNSLOTH_TP_SIZE / UNSLOTH_PP_SIZE / UNSLOTH_FSDP2 / UNSLOTH_PP_SCHEDULE / UNSLOTH_PP_MICROBATCHES and the new UNSLOTH_CP_SIZE / UNSLOTH_CP_BACKEND. The legacy variables keep working; one that disagrees with the flag is refused, as is a world size the axes do not divide. unsloth.parallelize(dp=, tp=, pp=, cp=, ...) does the same from Python before from_pretrained. SFTTrainer / DPOTrainer / GRPOTrainer take UNSLOTH_CP_SIZE into their arguments at __init__, the way SFTTrainer(context_parallel_size = N) is handled; a plain Trainer under UNSLOTH_CP_SIZE is refused. The tp_env layout moves to parallel_env.ParallelLayout (tp_env.TPEnvLayout and _read_layout still import) and gains a cp axis. One root DeviceMesh, pp outermost, then dp_replicate or dp_shard, cp, tp innermost, size-1 axes left out. Tensor parallel takes mesh["tp"], pipeline parallel mesh["pp"], the CP manager mesh["cp"] (it no longer builds a mesh when the layout has one), and the data parallel gradients (DDP-style averaging or native FSDP2 sharding) the flattened (dp, cp) mesh; the data loader still splits over dp only. cp x tp is lifted: on gloo CPU ranks, tp 2 x cp 2, dp 2 x cp 2 x tp 2 (DDP) and dp 2 (native FSDP2) x cp 2 x tp 2 through SFTTrainer match one process in the losses, the per-parameter gradients of the first optimizer step and the adapters after two steps, with each rank embedding seq / cp tokens and every layer running the Ulysses exchange. cp x pp stays refused (pipeline stages do not carry sequence shards yet). context_parallel_backend defaults to "auto": Ulysses, unless the heads per tensor parallel rank cannot be split over cp, then ring; explicit choices are kept. Auto packing no longer turns packing off under CP by default; an explicit ring backend with packing = True / padding_free = True is refused instead of silently unpacked. unsloth/parallel_capabilities.py: one table of cross-axis rules (trainer x model family x mode x packing x CP backend x torch version x layout), checked when the layout is read and again at Trainer.__init__ before any split; every refusal names the axis and what to run instead. Rank 0 prints one line with the resolved mesh, schedule, effective batch, CP backend, attention and gradient checkpointing.
…ounters The modularity contract: every feature (ddp, fsdp2, tp, pp, cp ulysses / ring, LoRA / QLoRA / full / FP8 / NVFP4, block compile, sdpa / flash / flash varlen / flex, packing, gradient checkpointing / offload / tiled MLP, Unsloth kernels, fused losses) declares in parallel_capabilities.FEATURES the root mesh axes it takes, the batch metadata it consumes, uses and produces (positions, packed lengths / cu_seqlens, BlockMask, CP permutation, shifted labels, sequence shard), the hooks it installs and the ones it must own alone, and whether it still patches a class. check_features composes from the declarations only: a missing mesh axis, consumed metadata no feature produces, or one exclusive hook claimed twice (cp x pp: both run Trainer.training_step) is refused. Query gains the remaining axes (attention, compile, memory, kernels, loss, pp schedule; FP8 / NVFP4 / MXFP8 modes), read from the model and arguments, with rules for the cells that are refusals for now (cp x flex / BlockMask, cp or tp / pp x low precision, interleaved schedules). CELLS lists the supported compositions with three kinds of evidence as test ids: parity vs one process, engagement, and compile counters. cp x tp runs only inside a cell (llama, SFT, LoRA, sdpa, Ulysses, no / torch GC, DDP or FSDP2 dp, eager or block compile); anything else is refused naming the fields that differ. Layouts that shipped before the registry report "unverified" and run, unless UNSLOTH_PARALLEL_STRICT=1. utils/compile_counters.py reads Dynamo's graph breaks, recompiles and graphs. The gloo test runs Unsloth's block compile on CPU ranks (its CUDA gate opened, aot_eager backend): under tp 2 x cp 2 and dp 2 (FSDP2) x cp 2 x tp 2 every decoder layer compiles, the numbers match one eager process, and graph breaks (0) and recompiles (1) are not above the same compiled script in one process.
… MoE cells, DistributedConfig key names Native FSDP2 (UNSLOTH_FSDP2=1) never reads context_parallel_size. On gloo CPU ranks (dp 2 x cp 2) it trains like one process: it shards over the whole world, which is the flattened (dp_shard, cp) mesh, and its gradient average over dp x cp matches the CP token count. That now holds by check instead of by accident: the CP trainer setup refuses a native FSDP2 mesh that leaves out a cp peer, the banner says FSDP2 shards and reduces over dp_shard x cp, and the composition is a registry cell with parity / engagement evidence. CP alone (DDP or native FSDP2) now goes through the registry too. Muon under native FSDP2 or tensor parallel would orthogonalize each rank's shard of a matrix: refused before the model is sharded (a prebuilt optimizer or args.optim) and at every native FSDP2 / tp optimizer hook. MoE: router aux loss on under pp / cp is refused (the injection design has not landed); MoE under tp is refused (no expert parallel); MoE with the aux loss off under cp and under pp are separate cells, refused until they carry evidence. Measured for the cp cell: qwen3_moe under Ulysses cp 2 misses one process (router LoRA grads up to 5%, attention LoRA grads about 1e-3), while dense qwen3 under cp 2 and a one-process A/A agree to 1e-6, and block compile adds recompiles (28 > 22); the parity test is a strict xfail that flips when it is fixed. UNSLOTH_PARALLEL accepts transformers' DistributedConfig names (tp_size, pp_size, cp_size, fsdp_size) and dp_shard / dp_replicate; fsdp=N > 1 means dp_shard=N while fsdp=0 / 1 stays the switch; ep / ep_size / efsdp are reserved and refused, as is dp_shard x dp_replicate (HSDP).
…ll x aux loss x mode), TRL's default aux loss caught The MoE x CP mismatch measured earlier was the router aux loss, not context parallel: TRL's SFTTrainer reads router_aux_loss_coef = None as "use the architecture's coefficient" (Qwen3-MoE 0.001) and sets output_router_logits = True on the config inside its __init__. The load balancing loss is a product of per-micro-batch means, so with it on even one process differs between bs 4 x ga 2 and bs 2 x ga 4 (router LoRA grads 18%), and under CP each rank trains a per-shard version of it, with no refusal before: CP's guards read the batch keys and hybrid configs only. The registry now predicts TRL's choice before the split, and the CP trainer setup checks the config again after the trainer __init__; both name router_aux_loss_coef = 0.0. With the aux loss off, tiny Qwen3-MoE (4 experts, 2 per token) matches one process on gloo CPU ranks, every expert getting a gradient: LoRA with expert LoRA under DDP, native FSDP2, Ulysses cp 2 and FSDP2 x cp 2; full finetuning under FSDP2 and cp 2; block compile under cp 2 with graph breaks / recompiles not above one process. With the aux loss on, dp 2 x accumulation 2 matches one process accumulating the same four micro-batches. MoE rows: 5 families x (LoRA, LoRA + experts, QLoRA, full) x aux on / off x (ddp, fsdp2, cp, pp, tp), the proven ones with their tests, every other row refused under cp / pp / tp (reported under dp alone) with what it waits for (QLoRA 4-bit experts need a GPU, other families a gloo run, pp refuses MoE, aux-loss injection). Query gains expert_lora and moe_backend.
…greeing single-axis variables) The launcher exports UNSLOTH_PARALLEL="dp=..,tp=..,pp=..,cp=..,fsdp=0|1[,cp_backend=..][,pp_schedule=..]" with an agreeing UNSLOTH_FSDP2 (and passes through agreeing UNSLOTH_TP_SIZE / UNSLOTH_PP_SIZE / UNSLOTH_CP_SIZE / UNSLOTH_CP_BACKEND). Tests pin that agreeing values in any spelling (UNSLOTH_FSDP2=true, UNSLOTH_PP_SCHEDULE=1F1B, UNSLOTH_CP_BACKEND=Ulysses, size 1 written out) are accepted and only disagreeing ones refused, and the exact form trains dp 2 (FSDP2) x cp 2 x tp 2 like one process on gloo CPU ranks. cp_backend with cp = 1 and pp_schedule / pp_microbatches with pp = 1 are now accepted and unused instead of refused, so a launcher can pass a user's backend or schedule through for a layout without that axis.
…ne GPU each, fp32, math SDPA) For tiny-model correctness runs through the workspace GPU queue: torchrun ranks call the same case with device = 'cuda' (no TF32, the math SDPA kernel, deterministic algorithms), and results move to the CPU for comparison.
… MoE row (eager only), full cp block compile proven The post-init guard read only output_router_logits on the config, which SFTTrainer writes but DPOTrainer and GRPOTrainer do not (they set aux_loss_enabled and pass the flag per forward): read the trainer switch too. MoE x cp with native FSDP2 recompiles twice more than one process under block compile (one extra ParametrizedQwen3MoeTopKRouter type guard each in the router forward and PEFT get_base_layer), so its row is eager only; DDP-dp x cp keeps block compile for LoRA and now also full finetuning (measured compile-clean). compile_counters keeps every new recompile reason, diffed as a multiset.
…'s rows, once Each rank records the dataset row ids its collator received; the MoE parity, aux-loss and block compile tests assert that per optimizer step the union over ranks equals one process's rows, that no side read a row twice, and (as in the dh/par-m1b epoch guard) that neither side went past epoch 1. A wrapped or reshuffled batch would otherwise read as a router / parity mismatch.
…CCL multi-rank), counts the expert backend UNSLOTH_TEST_RANKS_ON_GPU=1 keeps the card in spawned ranks; on a one-GPU host every rank uses device 0 and the process group is created first (NCCL with NCCL_MULTI_RANK_GPU_ENABLE=1, else gloo). GPU runs record which Unsloth Zoo expert path ran (grouped_mm, the Triton grouped GEMM, the 4-bit path) and torch._grouped_mm calls. qwen3_moe_wide (hidden / expert width 32) lets the Triton grouped GEMM take the experts; mode qlora loads bitsandbytes 4-bit. Measured on a G4: DDP / FSDP2 equal one process over the same micro-batches, cp 2 sits at the one-process micro-batch floor, for grouped_mm and unsloth_triton.
SFTConfig defaults to bf16 = True, and Unsloth's trainer turns bf16 = fp16 = False on a float32 model into bf16 autocast on a bf16 GPU, so the CUDA ranks trained in bf16 mixed precision and their LoRA grads sat 2.5% (median) / 5.5% (worst) from the fp64 oracle. Stamp the model as forced float32 and assert the accelerator runs with mixed_precision = no; the one-GPU cell then matches the CPU reference.
…any training forward A forward pre-hook on the embedding records torch.is_autocast_enabled for the run's device; GPU runs fail unless every forward ran without autocast, and the state is returned as autocast_seen.
dh/par-one-flag branched at cd7850c, after the pre_patch gate (#15101) and before #15559. On that base the class forward of every FastLanguageModel attention is the functools.wraps gate, so _supports_context_parallel's identity check refused every Llama / Qwen2 / Gemma model under UNSLOTH_PARALLEL=cp=N (Kaggle k_par_m1 cp2 cell, transformers 4.57.6). Cherry-picked from 68fad07: runs_fast_forward sees through the gate in context_parallel and rl._is_unsloth_fast_backbone, plus tests/test_gated_fast_forward_checks.py (2 of 4 fail before, 4 pass after).
# Conflicts: # tests/test_parallel_cp_compose_gloo.py # unsloth/__init__.py # unsloth/context_parallel.py # unsloth/models/pp_native.py # unsloth/models/tp_env.py # unsloth/models/tp_native.py # unsloth/trainer.py
…e root-mesh path too A manager built on the UNSLOTH_PARALLEL root mesh has no device_mesh of its own, so _install_accelerator_state returned before _cp_scaler_start (from main's float16 fix) and the scaler kept 2**16, overflowing on the first steps (tests/test_context_parallel_fp16_scale.py failed 2 of 3 after the merge).
…full finetuning, MoE); pipeline still refuses them Main's tensor parallel now trains full finetuning, weight-only QAT and MoE models (models/tp_native.py, #15722), and the merge dropped those load refusals from tp_env. The registry still refused tp x full finetuning and MoE x tp, so UNSLOTH_TP_SIZE scripts main runs would have been refused here: - 'pp / tp x mode' is now 'pp x mode' (pipeline parallel v1 trains LoRA only); - the MoE x tp rule is gone and MoE under tp alone is no longer gated (its rows report unverified and run); cp x tp x MoE stays gated; - UNSLOTH_PP_SIZE keeps refusing full_finetuning / qat_scheme at load (tests/test_pp_env_gloo.py::test_pp_env_layout_and_refusals failed after the merge: the refusal had gone with the tp one).
…eads a model id config, pre-init query honours peft_config - SFTTrainer / DPO / GRPO called without args under UNSLOTH_CP_SIZE (or with context_parallel_size = N as a kwarg) now get the default config the trainer would build, with the CP fields on it, instead of an unknown constructor kwarg. - context_parallel_backend = auto with a model id reads the heads from AutoConfig before committing, so heads cp cannot split pick ring. - The pre-init capability query classifies SFTTrainer(peft_config = ...) on a plain model as LoRA; the post-init check still reads the materialized model. [skip ci]
# Conflicts: # unsloth/models/pp_native.py
…lock compile eager only Pipeline parallel now carries the Qwen3-MoE router auxiliary loss (gpipe / 1f1b, one stage per rank, pp-only mesh): the MoE x pp / cp rule applies to context parallel only, and the qwen3_moe x lora+experts x pp rows cite tests/test_pp_moe_aux_gloo.py. UNSLOTH_PP_SIZE loads Qwen3-MoE; Mixtral is still refused at load. With the router_logits capture hooks installed before the first block compiles, LoRA on the experts under cp recompiles more than one process (per instance ParametrizedQwen3MoeTopKRouter type guards): eager only, as FSDP2 x cp.
[skip ci]
…h and token count
…e router aux loss split over micro-batches [skip ci]
…e cp values, the pre-init check reads a backend kwarg [skip ci]
…pp x dp optimizer hook reads self.optimizer [skip ci]
…before the default config; auto backend reads a model id with the trainer's loader options
…a freeze; checkpoint load releases the replica first [skip ci]
…peline computes the plain causal LM loss) [skip ci]
…CP_BACKEND, so ring x tp is refused before the tensor parallel split
…ive import has no package there)
…nstructor kwargs over the config [skip ci]
…ring packing and torch.optim.Muon behaviour, torch floor on block compile cells - PipelineParallel binds scaler._check_inf_per_device too: scaler.step on a fused optimizer checks infs there instead of calling unscale_, so with max_grad_norm = 0 one stage skipped while the other stepped. - PipelineParallel.step records the trained parameter names, so a native loop's later requires_grad_(False) still syncs them into the replica. - A repeated parallelize() undoes only what its previous call wrote, keeping inherited UNSLOTH_FSDP2 and the like. - Ring context parallel with packing turns packing off with a notice, as released, instead of raising. - torch.optim.Muon steps DTensor shards as whole matrices (new gloo test), so it is no longer refused under native FSDP2 / tensor parallel; other Muon classes still are. - Block compile cells cover torch >= 2.13 (2.10 failed their compile gates); older versions are pointed at UNSLOTH_BLOCK_COMPILE_LEGACY=0. Tests skip below the same floor, and the gpipe mb1 case below 2.13.
…ened over dp x cp) [skip ci]
…syncs the batch over tensor peers before the stages [skip ci]
…packing-off fallback instead of a pre-init refusal [skip ci]
…er state (disable_adapter, set_adapter)
[skip ci]
This was referenced Nov 2, 2026
danielhanchen
added a commit
that referenced
this pull request
Nov 2, 2026
## Summary #16407 (`9341351954`) merged with three of its CI reds, so `Backend CI` and `Core` are now red on main and on every PR based on it. All three reproduce locally on current main (`2f5ff226b8`). **1. `Repo tests (CPU, rest)`: a file in two shards** ``` tests/test_ci_repo_cpu_shards.py::TestEveryTestFileLandsInExactlyOneShard::test_no_file_is_dropped_or_run_twice AssertionError: these files are collected by more than one shard: [('tests/test_muon_dtensor_gloo.py', ['gloo', 'rest-2'])] ``` `rest-2` takes `tests/test_[dimsu]*.py`, and the `gloo` shard takes `tests/test_[!fpt]*gloo*.py`. Their split relies on no `*gloo*` file starting with d, i, m, s or u, as the workflow comment says. The new `test_muon_dtensor_gloo.py` breaks that rule, so it ran twice. An `--ignore-glob` on `rest-2` does not help. The shell expands the glob into explicit file arguments, and pytest 9 collects explicit arguments even when they match `--ignore-glob`; I checked that locally. So the file is renamed to `tests/test_optim_muon_dtensor_gloo.py`, which only the `gloo` shard matches. The comment in `test_parallel_env.py` that names it follows the rename. **2. `Repo tests (CPU, rest-2)`: an unencoded read** ``` tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding[1] ['tests/test_parallel_env.py:632: open()'] ``` The new capability-registry test reads checked-in test files with the platform default encoding. It now passes `encoding = "utf-8"`. **3. `Core` (all three combos): `test_context_parallel_disables_eval_packing`** ``` tests/utils/test_packing.py:2185 assert config.packing is False and config.eval_packing is False E assert (True is False) ``` This is the test being out of date, not the product. #16407 changed the default `context_parallel_backend` from `"ring"` to `"auto"`. `resolve_cp_backend` resolves `"auto"` to Ulysses unless the heads cannot be split over cp, and Ulysses keeps packed rows apart. So the trainer now deliberately leaves packing on. The test sets no backend and still expected ring's behaviour. The test now covers each backend: - `ring`: packing is turned off, as before; - `ulysses`, `auto` and unset: packing stays on. ## Testing | Tests | main | this branch | |---|---|---| | `tests/test_ci_repo_cpu_shards.py`, `tests/test_source_read_encoding.py`, `tests/utils/test_packing.py` | 3 failed, the three above | pass | | Those three plus `tests/test_parallel_env.py` | | 272 passed, 3 skipped | | `tests/test_optim_muon_dtensor_gloo.py` | | 1 passed |
danielhanchen
added a commit
that referenced
this pull request
Nov 2, 2026
## Summary `Repo tests (CPU, gloo-tp-pp)` failed on #16444 and #16451 in `tests/test_pp_env_gloo.py`, which #16407 added. Neither PR touches pipeline parallel. Both failures are the same case, with an identical value: ``` test_pp_env_gradient_accumulation_and_microbatches[gemma3_ga1_bs4] base_model.model.model.layers.0.mlp.gate_proj.lora_A.weight: Tensor-likes are not close! Mismatched elements: 1 / 64 (1.6%) Greatest absolute difference: 1.5791505575180054e-05 at index (2, 2) (up to 1e-05 allowed) ``` The identical value means the result depends on the runner's CPU, not on chance, so any run that lands on that runner type fails. The adapter comparison runs after several optimizer steps, so it carries the fp32 reduction-order noise of a 2-stage split against the single-process reference. The file already records that noise for the grad norms ("3e-5 absolute ... between two identical reference runs"). On this host, the largest adapter difference across all five cases of the test is 3.7e-6, which is why 1e-5 looked safe. ## Change `tests/test_pp_env_gloo.py`: in `test_pp_env_gradient_accumulation_and_microbatches` only, the trained-adapter comparison takes `atol = 5e-5`, about 3x the CI value. `rtol` is unchanged, and so is every other `_same_tensors` call: save_pretrained, Trainer.save_model and export. The `_close` call just before it is also unchanged. It pins the step count and every loss at rel 1e-5. It pins the first grad norm at rel 1e-5 and the rest at 1e-4. ## Testing - `tests/test_pp_env_gloo.py`: 14 passed, 1 skipped. - Sabotage: I temporarily scaled every `lora_A` by `1 + 1e-4` in the pipeline-parallel ranks only. `[ga1_bs4]` and `[gemma3_ga1_bs4]` both still fail, as they do at `1 + 1e-3`. So a real divergence much smaller than any pipeline bug would be still fails the test.
danielhanchen
added a commit
that referenced
this pull request
Nov 2, 2026
…ard (#16447) ## Summary Since #16407, `Repo tests (CPU, gloo)` sits right at its step cap. On main (`9341351954`) it ran 1922 s of the 2100 s cap. On #16444, against the same base, it hit the cap and was killed (`exit code 124`) after 145 of its 153 tests had passed. #16407 grew `tests/test_parallel_cp_compose_gloo.py` to 27 tests. I timed the shard per file locally (`-n 4 --dist loadgroup --durations=0`, the CI selection). That one file takes 1143 of the shard's 3605 test-seconds, about a third: | File | test-seconds | share | |---|---|---| | `test_parallel_cp_compose_gloo.py` | 1143 | 31.7% | | `test_tp_env_gloo.py` | 796 | 22.1% | | `test_tp_replica_gloo.py` | 533 | 14.8% | | `test_tp_full_finetune_gloo.py` | 429 | 11.9% | | the other 12 files | 704 | 19.5% | `gloo-tp-pp` cannot absorb it, because it already runs 1397 s on main. The file also cannot run four tests at a time on its own. Each test spawns 2 to 8 gloo ranks. In this PR's first two runs of a dedicated shard at `-n 4`, the runner was shut down mid-run both times (`The runner has received a shutdown signal`, exit 143). Measured locally as summed PSS over the pytest process tree, the peak is: | workers | peak memory | local wall time | |---|---|---| | 4 | about 20 GB | 291 s | | 2 | about 12 GB | 440 s | A hosted runner has 16 GB. In the mixed `gloo` shard, the file's tests were interleaved with lighter ones, so they rarely overlapped four at a time. ## Change `.github/workflows/studio-backend-ci.yml`: - New `gloo-cp` shard: `tests/test_parallel_c*gloo*.py`, with `workers: 2`. - The repo-cpu pytest command reads `-n ${{ matrix.workers || 4 }}`, so every other shard keeps `-n 4`. - The `gloo` shard's `tests/test_p[!p]*gloo*.py` becomes `tests/test_parallel_[!c]*gloo*.py`. Its other globs are unchanged. - Comments record why the split and the worker count exist. They also note that a future `*gloo*` file named `test_p[!ap]*` would match no shard; `tests/test_ci_repo_cpu_shards.py` reports that as a dropped file. `tests/studio/test_backend_ci_parallel_isolation.py`: - Its command scan substitutes each shard's `workers` (or the expression's default), the way it already substitutes `selection`. Before that, its existing "no unexpanded `${{`" assertion caught the new expression. - The pinned counts move from 11 to 12 parallel runs, and from 8 to 9 repo-root shards. ## Testing - With main (now including #16446) merged in, these pass (176 passed): - `tests/test_ci_repo_cpu_shards.py` - `tests/test_ci_backend_pytest_shards.py` - `tests/studio/test_backend_ci_parallel_isolation.py` - `tests/test_rendezvous_port_everywhere.py` - `tests/studio/test_cache_budget_discipline.py` - `tests/test_parallel_cp_compose_gloo.py` at `-n 2`: 23 passed, 3 skipped. - A first attempt, `test_p[!ap]*gloo*.py`, matched no file, and the guard's unexpanded-pattern check caught it. Hence the explicit `test_parallel_` globs.
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.
What
One launch flag for every parallel axis, one device mesh behind it, and one table that decides which combinations run.
unsloth.parallelize(tp = 2, cp = 2)does the same from Python.UNSLOTH_PARALLEL/unsloth.parallelize(unsloth/parallel_env.py).dp, tp, pp, cp, cp_backend, fsdp, pp_schedule, pp_microbatches, plus the transformersDistributedConfignames (tp_size,pp_size,cp_size,fsdp_size) anddp_shard/dp_replicate.dpfills the world when omitted. A world the axes do not divide is refused with the torchrun line to use.UNSLOTH_TP_SIZE,UNSLOTH_PP_SIZE,UNSLOTH_FSDP2, ...). A legacy variable that disagrees is refused and both forms are named.pp, dp_replicate | dp_shard, cp, tp(size-1 axes left out). Tensor, pipeline and context parallel each take their own sub-mesh. The data loader splits overdp; DDP-style averaging and native FSDP2 shard over the flattened(dp, cp)mesh.SFTConfig(context_parallel_size = 2)underUNSLOTH_TP_SIZE=2built its own(world // cp, cp)mesh whose cp groups were the tp pairs. It trained with no error and wrong losses (CPU repro: 10.3854 / 10.3789 against 10.3726 / 10.3719 for one process). The same happened besideUNSLOTH_PP_SIZE. Now cp comes from the root mesh. A cp request beside a tp / pp launch that was read without a cp axis is refused with the layout to use.autois the default: Ulysses unless the heads per tp rank cannot be split over cp, then ring. RL trainers always get Ulysses. The resolved backend is written into the trainer arguments before__init__, so auto packing sees it. Ring withpacking=Truekeeps the released behaviour: packing is turned off with a notice that names Ulysses as the way to keep it. Under cp x tp, padding-free batching is never turned on automatically (an explicit request is refused with the alternative).unsloth/models/pp_env.py).UNSLOTH_PP_SIZE(orpp=in the flag) runs an unmodified notebook script through the pipeline schedule inside the Trainer:UNSLOTH_PP_MICROBATCHESandUNSLOTH_PP_SCHEDULE(gpipe, 1f1b).PipelineParallelgains a per-step micro-batch count, a forward-onlyeval_loss, a DDP-style dp mesh and the kept CPU replica. Later stages run the model on the batch's real token ids, the embedding stub returns the real embedding's dtype, and models Unsloth trains in float32 send float32 hidden states between stages.unsloth/parallel_capabilities.py), checked when the layout is read and again in the Trainer__init__, before anything is split.FEATURES: 21 declarations (mesh axes, the batch metadata each consumes / produces, the hooks it installs). A missing producer or a hook claimed twice is refused from the declarations alone.RULES: refusals of the formUnsloth: <axis>: <cell> is not supported: <why>. Instead: <alternative>. (layout ...).CELLS: the supported compositions, each tied to test ids for numeric parity, engagement and compile counters. A test checks that every referenced test exists.UNSLOTH_BLOCK_COMPILE_LEGACY=0named for the eager cells.torch.optim.Muonruns under native FSDP2 and tensor parallel, as before: it steps DTensor shards as whole matrices (a gloo test checks it against the whole-matrix step). Other Muon classes are refused there, since a Muon that reads the local shard would orthogonalize the shard.UNSLOTH_PARALLEL_STRICT=1refuses them too.SFTTrainerturns the router load balancing loss on from the architecture'srouter_aux_loss_coefby default. Under cp that loss is computed per sequence shard and is not the one-process objective, and it ran with no refusal. It is now refused before and after__init__, namingrouter_aux_loss_coef = 0.0. With the aux loss off, Qwen3-MoE under cp matches one process.Why
Each parallel axis had its own variable and built its own process groups. Two axes together either refused late or, for cp beside tp / pp, trained silently on the wrong shards. One mesh and one table make every composition either proven or refused before the model is touched, and give later features (precision policies, MoE backends, attention variants) one place to declare what they need.
Merge with main
This branch is merged with current main (no rebase). Where both sides changed the same code:
pp x mode(pipeline parallel full finetuning) is still refused, tensor parallel alone is not, and MoE under tensor parallel alone is no longer gated. Evaluation stays refused only for cp x tp, where the eval loss is not gathered over the data mesh yet.PPConfig.keep_replica) is refused with several stages per rank or a sharded load.2**16 / world) now also runs on the root-mesh path, which returned before it.Tests
CPU (gloo ranks, tiny models), on the merged head:
test_context_parallel_fp16_scale(2): failed after the merge, fixed here (the float16 scaler start above); 3 of 3 pass now.test_context_parallel_fsdp2_save_gloo,test_tp_full_finetune_gloo(one QAT case): the rendezvous port was taken by a concurrent run; both pass when run alone.test_fsdp2_native_accelerator_loop_gloo: a rank died with SIGSEGV under load; passes alone, on this branch and on main.test_pp_env_layout_and_refusals) was the refusal restored above and passes now.test_parallel_cp_compose_gloo.py: 27 passed. Context parallel against one process (losses, grad norms, per-parameter gradients of the first step, adapters after the run): cp 2 alone; DDP dp 2 x cp 2; native FSDP2 x cp 2 at world 2 and 4; cp 2 x tp 2; dp 2 (DDP and native FSDP2) x cp 2 x tp 2; block compile on those layouts with graph breaks and recompiles not above one process; dense Qwen3 and Qwen3-MoE (aux loss off) under DDP / FSDP2 / cp; refusals for cp x pp, cp beside a tp launch without a cp axis, and the MoE aux loss under cp.test_parallel_env.py81 failed / 29 errors,test_context_parallel.py8,test_tp_env_gloo.py5 where main refusesUNSLOTH_PP_SIZEfrom the environment,test_pp_env_gloo.py13,test_parallel_cp_compose_gloo.py27). On the old base, cp 2 besideUNSLOTH_TP_SIZE=2orUNSLOTH_PP_SIZE=2trained with no error and wrong losses (numbers above).Kaggle T4x2 (real NCCL, fp16), one kernel; the unsloth tree was checked by hash on the VM:
An unmodified notebook script (Llama 3.2 1B Instruct, fp16 LoRA, 20 steps) under
UNSLOTH_PARALLELagainst one GPU. Every cell passes its judge: step-1 loss within 5e-3, every step within max(5 x the A/A spread, 0.02), plus engagement counters.tp=2reduce_from_tp/copy_to_tp5120pp=2_pp_training_step80cp=2, packing onfsdp=1(dp 2)shard_model1The native FSDP2 ladder (Qwen3-0.6B fp16 LoRA, 2 ranks against one GPU, 14 steps) passes every rung: plain, Unsloth gradient checkpointing, activation offload, Unsloth kernels, block compile, fused cross entropy, packing, and all defaults. Loss within 1.7e-5, grad norm within 7.4e-4. Rung 8 (defaults) equals rung 7. Compile is not applicable on the packed rungs, where block compile keeps the stock forward by design.
Not covered
UNSLOTH_PARALLEL_STRICT=1refuses them.UNSLOTH_PARALLELwith cp: unit tests only, no real RL run.