Skip to content

UNSLOTH_PARALLEL=auto: DDP when the model and its training state fit on every GPU, else native FSDP2 - #18061

Merged
danielhanchen merged 10 commits into
mainfrom
parallel-auto
Nov 17, 2026
Merged

danielhanchen merged 10 commits into
mainfrom
parallel-auto

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Problem

Multi-GPU launches pick DDP or FSDP2 by hand (UNSLOTH_FSDP2=1, UNSLOTH_PARALLEL="fsdp=1"). The generated launcher defaults to FSDP2 everywhere, but the M2 notebook sweep on Kaggle 2x T4 (same scripts run under DDP and FSDP2) shows FSDP2 is often the slower and heavier choice when the model already fits on one GPU:

  • 33 real-size cells passed in both modes and logged throughput. DDP over FSDP2 steady tokens/s: median 1.03x, DDP at least 0.98x in 28 of 33. The biggest wins are all vision or long-sequence: Qwen3_5_(4B)Vision 1.97x, Qwen2.5(7B)-Alpaca 1.83x, LFM2.5_(1.2B)-Translation 1.64x, Qwen2_VL_(7B) 1.56x, Qwen2.5_VL_(7B) 1.48x, Qwen3_VL_(8B) 1.39x.
  • Peak memory: 45 real-size cells passed in both modes, and DDP used less in 28 of them. In the vision runs FSDP2 peaked 3 to 6 GB higher: Qwen3_VL_(8B)-Vision-GRPO 8.7 vs 14.9 GB, Pixtral_(12B) 10.3 vs 14.4 GB, Qwen3_5_(4B)_Vision 10.2 vs 14.2 GB.
  • Mistral_Nemo_(12B)-Alpaca passes under DDP (9.7 GB peak). FSDP2 runs out of memory when it unshards the whole model for generate after training.
  • DDP never ran out of memory in a cell where FSDP2 passed. The one OOM under DDP (Qwen3_Embedding_(0_6B), batch 256 per device) also OOMs under FSDP2.

FSDP2 still matters when the weights plus training state do not fit on one card, for example 16-bit LoRA on an 8B model on a T4.

Change

UNSLOTH_PARALLEL=auto (opt-in) picks the data parallel mode by memory:

  • When it decides: once per process, at the first Unsloth from_pretrained. That is before any load-time code reads UNSLOTH_FSDP2 (4-bit storage dtype, sharded loading, gradient checkpointing mode). If no Unsloth load ran, it decides at the first Trainer instead, using the model passed in.
  • Fits means weights + training state + activation margin <= what this rank's GPU can hold:
    • weights: the checkpoint's safetensors headers, no weights downloaded. Quantize-on-load counts the quantized linear weights at 4-bit / 8-bit size.
    • training state: per trainable parameter, the gradient, its DDP bucket copy and two AdamW moments. Before get_peft_model, LoRA is assumed at r=16 on every linear weight.
    • activation margin: 20% of the GPU. This is the activation share the device map planner (loader_utils._plan_fits_first_device) already keeps free. In M2, DDP's training peak above its post-setup reserved memory was 0.97 GB median and 3.04 GB p90, which is 21% of a T4.
  • Ranks agree: one all_gather_object across ranks. DDP is picked only if every rank fits; otherwise every rank takes FSDP2. Anything that cannot be sized also picks FSDP2, which is today's launcher default.
  • Output: the decision is written as UNSLOTH_FSDP2=0 or 1, so everything after it sees an ordinary explicit launch, and child processes inherit it. Rank 0 prints one line with the numbers and how to force the other mode.
  • Precision: sizing follows the loader's -bf16 rule (now one helper, mapper.bf16_repo_loads_16bit, used by the loader too). A quantization_config or load_in_fp8 load is not sized and picks FSDP2. Each rank sizes its own GPU (LOCAL_RANK).
  • Conservative by construction: only loads the estimator models exactly are sized (16-bit LoRA, pre-quantized bitsandbytes, quantize-on-load with the loaders' skip lists, full finetuning with float32 master weights). Everything else (quantization_config, fp8, fast_inference, forced float32 or custom dtypes, unreadable configs) picks FSDP2 and the rank 0 line says why.
  • Explicit layouts are unchanged. auto combined with UNSLOTH_FSDP2, tp / pp / cp, or an accelerate launch FSDP config is refused with a message. UNSLOTH_PARALLEL_AUTO_GB overrides the per-rank budget.

Header-only estimates against the M2 measured post-setup reserved memory (T4, 14.56 GB):

notebook model estimated weights M2 reserved at start auto
Llama-3.1-8B, 4-bit 5.80 GB 5.74 GB ddp
gemma-2-9b, 4-bit 6.25 GB 5.93 GB ddp
Qwen2.5-VL-7B bnb-4bit 6.90 GB 6.70 GB ddp
Pixtral-12B, 4-bit 8.70 GB 8.75 GB ddp
Mistral-Nemo-12B, 4-bit 8.46 GB n/a (DDP peak 9.7 GB) ddp
Llama-3.1-8B, 16-bit LoRA 16.06 GB n/a fsdp2
gemma-3-27b, 4-bit 16.63 GB n/a fsdp2

The launcher default stays FSDP2 for now. The M2 DDP crash with trainable embed_tokens / lm_head (Mistral CPT, Text_Completion) is fixed by #18036, and the Kaggle run below shows auto picking DDP there and training. The 27B / 30B 4-bit notebooks run out of memory at load under both modes, because each rank loads the whole 4-bit model. Auto picks FSDP2 there and changes nothing.

Tests

tests/test_parallel_auto.py (26 tests) runs on CPU. The gloo tests use a world of 2 and trl-internal-testing/tiny-Qwen3ForCausalLM. Each test takes under 10 s.

  • Parsing: auto parses; explicit layouts parse and translate as before; conflicting variables are refused; a child process inherits the decision.
  • Arithmetic: the decision and training-state formulas. Sizing: the tiny checkpoint's safetensors headers, 16-bit vs 4-bit on load.
  • Gloo, world 2: fits picks ddp (run through the real from_pretrained decorator); does not fit picks fsdp2; ranks disagree picks fsdp2 on every rank. The decision is made once.
  • End to end, through the real _unsloth_trainer_init source: a LoRA Trainer under auto trains exactly like the explicit layout it picked, for both DDP and FSDP2. Losses match, LoRA weights are bit-identical, and the run is wrapped in DDP or FSDP2 as expected.

Flip check:

  • On origin/main all new tests fail.
  • With only parallel_auto.py copied in and none of the wiring, the 10 parsing / wiring / end-to-end tests still fail.
  • On this branch all 26 pass. The three review fixes (per-rank GPU sizing, Trainer wrapper installed while auto is unresolved, -bf16 / quantization_config sizing) each have a test that fails on the previous head and passes now.

Existing suites (test_parallel_env.py, test_parallel_capabilities_*.py, test_fsdp2_native_trainer_init_any_loader_gloo.py, test_fsdp2_native_trainer_args_gloo.py) fail the same two tests before and after: test_parallel_capabilities_latent_sinks.py, a DeepseekV41 _keep_in_fp32_modules error with this transformers version. Nothing else fails.

Kaggle 2x T4: torchrun --nproc-per-node 2, LoRA r=16, seq 512, batch 2 per GPU unless noted. Stack: this branch on unsloth main 9e27e6a, unsloth_zoo main, torch 2.14.1, transformers 5.17.0, trl 1.15.0. Peak is max reserved per GPU (rank 0 / rank 1). Each arm ran once, so the tok/s gap between auto and explicit is run-to-run noise, not a speedup. Losses match the explicit arm to 1e-4 in a and c (GPU reduction order) and exactly in b.

arm layout rank 0 decision tok/s peak GiB losses (first, last)
a: Llama-3.1-8B-Instruct bnb-4bit, 10 steps auto DDP: weights 5.31 + state 0.54 + margin 2.91 GiB fits 14.43 GiB 723 6.79 / 7.04 1.7930, 0.2772
fsdp=0 677 6.79 / 7.04 1.7930, 0.2771
c: Mistral v0.3 7B bnb-4bit CPT, trainable embed_tokens + lm_head, 6 steps auto DDP: weights 3.85 + state 0.54 + margin 2.91 GiB fits 14.43 GiB 601 11.00 / 11.29 0.8652, 0.6884
fsdp=0 570 11.00 / 11.29 0.8652, 0.6884
b: Llama-3.1-8B-Instruct 16-bit, seq 256, batch 1, 10 steps auto FSDP2: needs 18.49 GiB (weights 14.96 + state 0.62 + margin 2.91) but has 14.43 GiB 106 12.69 / 12.71 3.7241, 4.7500
dp=2,fsdp=1 104 12.69 / 12.71 3.7241, 4.7500

Every auto arm ended up wrapped the same way as its explicit arm: DDP in a and c, FSDP2 (32 LlamaDecoderLayer blocks + root) in b.

…on every GPU, else native FSDP2

Opt-in. Resolved once per process at the first Unsloth from_pretrained (sized from the
safetensors headers, no weights read) or at the first Trainer, agreed over all ranks with one
collective (DDP only if every rank fits), logged once on rank 0, written as UNSLOTH_FSDP2=0/1.
Explicit layouts are unchanged; auto with UNSLOTH_FSDP2, tp / pp / cp or an accelerate FSDP
config is refused.
#18036 fixed DDP with embed_tokens / lm_head modules_to_save (find_unused_parameters off), so
the Trainer-time path no longer needs to send those models to FSDP2. Verified on Kaggle 2x T4:
Mistral v0.3 7B CPT with trainable embed_tokens / lm_head trains under auto (DDP) and matches
explicit DDP.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T05:26:22.925064Z 08ddf6f Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…rapper while unresolved, follow the -bf16 rule

- _budget reads cuda:LOCAL_RANK (current device only when each rank sees one GPU) without changing
  the current device.
- install_native_fsdp2_trainer_init also installs the wrapper while auto is unresolved under
  WORLD_SIZE > 1, so a plain transformers model resolves auto at the Trainer instead of silently
  running DDP.
- The loader's -bf16 rule moves to mapper.bf16_repo_loads_16bit (used by all four loader sites and by
  the auto sizing); a quantization_config or load_in_fp8 load is not sized and picks FSDP2.

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…d dtype

- Before reading headers, map the name with the loader's own get_model_name (same flags the
  loader passes; skipped under use_exact_model_name), so a -bnb-4bit mirror loaded with
  load_in_4bit = False is sized as its float repo; the -bf16 rule now runs on the mapped name.
- Floating-point weights count at the model dtype (a float32 load of a bf16 checkpoint is 4 bytes
  per weight); bitsandbytes quant state beside packed weights keeps its stored dtype.

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…NDBYTES, gloo without NCCL

- A PEFT adapter (local dir or Hub repo, found with PeftConfig.from_pretrained as the loaders do) is
  sized as its mapped base_model_name_or_path plus the adapter weights.
- With ALLOW_BITSANDBYTES false, 4bit / 8bit are cleared before the name mapping and sizing, as the
  loaders do.
- The decision's process group comes from fsdp2_native._ensure_process_group (gloo where NCCL is
  missing, Windows CUDA builds).

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…and the loader's dense modules; decline what is not modelled

- Full finetuning counts what FastBaseModel.post_patch_model does: float32 master weights (so float32
  grads and DDP buckets) unless the model loads in bfloat16 and float32_mixed_precision is not True.
- Quantize-on-load keeps dense every linear the loaders keep out of bitsandbytes
  (unsloth_zoo SKIP_QUANTIZATION_MODULES + vision._architecture_skip_modules for the config's model
  types, read with the loader's get_transformers_model_type).
- Conservative by construction: fast_inference, UNSLOTH_FORCE_FLOAT32 / UNSLOTH_FORCE_CUSTOM_DTYPE,
  a FORCE_FLOAT32 architecture on float16, an unknown dtype, and unreadable configs decline and pick
  FSDP2 with the reason in the rank 0 line.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 17, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ckpoint; count a fresh adapter's parameters

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 17, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 08ddf6f3c3

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

@danielhanchen
danielhanchen merged commit c0ef23b into main Nov 17, 2026
@danielhanchen
danielhanchen deleted the parallel-auto branch November 17, 2026 06:02
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 17, 2026
…18061) (unslothai#18096)

`tests/test_optimized_precision_conflicts.py` has been red on main (19
failed, both the `rest` and `studio` CPU shards) since unslothai#18061
(c0ef23b).

## Cause

The `loader` fixture runs the real `FastLanguageModel.from_pretrained`
body in a stub namespace. It lifts the loader.py helpers and the
`.loader_utils` functions the method calls, but nothing from other
sibling modules. unslothai#18061 made `from_pretrained` call
`bf16_repo_loads_16bit`, imported `from .mapper`, so every case now dies
with `NameError: name 'bf16_repo_loads_16bit' is not defined` before
reaching the precision checks.

The loader change is correct; the harness just did not know about
`.mapper`.

## Fix

`_loader_utils_functions` takes the module name, and the fixture lifts
real definitions from each module in `_LIFTED_MODULES = ("loader_utils",
"mapper")`. Only functions that `from_pretrained` both imports and calls
are lifted, and explicit stubs still win, as before. A later helper
added to `mapper.py` is picked up without touching the test.

## Verification

- main: `19 failed` (NameError).
- this branch: `19 passed`.
- Sabotage: with `_LIFTED_MODULES = ("loader_utils",)` the file goes
back to `19 failed`.
danielhanchen added a commit that referenced this pull request Nov 17, 2026
… -bf16 check by its new call (10 failures since #18061) (#18110)

`tests/python/test_loader_resolution_reporting.py` has 10 failures on
main in the CPU `studio` shard since #18061 (seen on the staging runs of
#18084 and #18087):

```
unsloth/models/loader.py:1555: in <module>
    if bf16_repo_loads_16bit(model_name, load_in_16bit):
E   NameError: name 'bf16_repo_loads_16bit' is not defined
test_adapter_base_resolution_updates_report_before_base_config_load[*]
E   StopIteration
```

This is the same root cause as #18096, in a second harness that test did
not cover.

## Cause

The test runs slices of the real `from_pretrained` bodies in a
hand-built scope. #18061 moved the inline
`model_name.lower().endswith("-bf16") and (...)` check into
`mapper.bf16_repo_loads_16bit`, which is correct, but:

- the scopes do not define `bf16_repo_loads_16bit`, so 8 cases die with
`NameError`;
- the adapter test found the end of its slice by the `if
model_name.lower().endswith(...)` statement in the `is_peft` block,
which no longer exists, so `next()` raises `StopIteration`.

## Fix

- `_mapper_function` lifts the real `bf16_repo_loads_16bit` out of
`mapper.py` by AST (the file deliberately avoids importing unsloth), and
each scope gets it, so the check runs for real instead of being stubbed.
- `_is_bf16_check` finds the slice end by either form (the helper call
or the old inline check).

## Verification

- main: 10 failed, 2 passed.
- this branch: 12 passed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant