Repository navigation
UNSLOTH_PARALLEL=auto: DDP when the model and its training state fit on every GPU, else native FSDP2 - #18061
Merged
Conversation
…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.
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. |
…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]
…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]
…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]
…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.
…ache, not live tensors [skip ci]
…ckpoint; count a fresh adapter's parameters [skip ci]
…rainable dtype's gradient width [skip ci]
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. 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". |
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.
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.
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: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:from_pretrained. That is before any load-time code readsUNSLOTH_FSDP2(4-bit storage dtype, sharded loading, gradient checkpointing mode). If no Unsloth load ran, it decides at the firstTrainerinstead, using the model passed in.get_peft_model, LoRA is assumed at r=16 on every linear weight.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.all_gather_objectacross 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.UNSLOTH_FSDP2=0or1, 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.mapper.bf16_repo_loads_16bit, used by the loader too). Aquantization_configorload_in_fp8load is not sized and picks FSDP2. Each rank sizes its own GPU (LOCAL_RANK).autocombined withUNSLOTH_FSDP2, tp / pp / cp, or anaccelerate launchFSDP config is refused with a message.UNSLOTH_PARALLEL_AUTO_GBoverrides the per-rank budget.Header-only estimates against the M2 measured post-setup reserved memory (T4, 14.56 GB):
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 andtrl-internal-testing/tiny-Qwen3ForCausalLM. Each test takes under 10 s.autoparses; explicit layouts parse and translate as before; conflicting variables are refused; a child process inherits the decision.from_pretraineddecorator); does not fit picks fsdp2; ranks disagree picks fsdp2 on every rank. The decision is made once._unsloth_trainer_initsource: 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:
parallel_auto.pycopied in and none of the wiring, the 10 parsing / wiring / end-to-end tests still fail.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_moduleserror 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.fsdp=0fsdp=0dp=2,fsdp=1Every auto arm ended up wrapped the same way as its explicit arm: DDP in a and c, FSDP2 (32 LlamaDecoderLayer blocks + root) in b.