Skip to content

Native FSDP2: sync initial trainable weights across ranks; shard FastSentenceTransformer and FastDiffusionModel - #15012

Merged
danielhanchen merged 11 commits into
mainfrom
dh/s4-fsdp2-any-loader
Oct 24, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
dh/s4-fsdp2-any-loader

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Native FSDP2 (UNSLOTH_FSDP2=1 under torchrun) already shards and trains models loaded through FastLanguageModel, FastModel, FastVisionModel and FastTextModel. A loader sweep over tiny copies of every supported architecture found four gaps for the other loaders and one that affects every loader.

Changes

  1. Every rank starts from the same trainable weights. DDP broadcasts rank 0's parameters when it wraps the model; fully_shard keeps each rank's own slice. A trainable weight initialised without a common seed on each rank (an adapter whose loader ignored random_state, a fresh head) therefore became a mix of the ranks' values, and the ranks trained different models without any error. shard_model now compares a float64 checksum per trainable tensor across the mesh and broadcasts the first rank's values for the tensors that differ (only those, so a full finetune is not re-sent). Identical non-finite weights count as agreeing.
  2. FastSentenceTransformer is sharded. Native FSDP2 shards inside the Trainer __init__ wrapper that the FastLanguageModel / FastModel loaders install. An encoder loaded through FastSentenceTransformer never installed it, so its Trainer silently trained as plain DDP with nothing sharded. The wrapper is now installed at import unsloth when the flag selects native FSDP2.
  3. FastSentenceTransformer seeds its LoRA init with random_state on the fast encoder path, as FastModel.get_peft_model does. Before, the adapters depended on whatever ran first, and every rank drew its own.
  4. FastDiffusionModel loads one whole model per rank under torchrun / accelerate launch, as the other loaders do. device_map = "auto" spread every rank over all visible cards and crashed at load.

FastDecisionModel is still refused under native FSDP2 with a clear message at Trainer init. Single GPU and DDP paths are unchanged.

Tests

Each new test fails on main and passes here (CPU gloo, 2 ranks where distributed):

  • tests/test_fsdp2_native_sync_initial_weights_gloo.py: ranks with different trainable weights end bitwise equal after shard_model (main: max difference 0.084), agreeing ranks are left untouched, identical NaN weights count as agreeing.
  • tests/test_fsdp2_native_trainer_init_any_loader_gloo.py: a Trainer built on a model that no Unsloth loader patched still shards under the flag (6 cases).
  • tests/python/test_fast_sentence_transformer_lora_seed.py: the same random_state gives the same adapters.
  • tests/diffusion/test_diffusion_distributed_device_map.py: under a distributed launch each rank's device_map is its own device.

GPU (2 ranks, fp32): ModernBERT LoRA and full finetuning match one GPU with a step-0 grad-norm difference of 0.0; a Qwen3 sentence-transformer LoRA matches to 2e-7; DiffusionGemma LoRA and BERT-tiny QLoRA differ from one GPU exactly as much as plain DDP does.

Not covered

The CPU FSDP2 suite was run to 40% on this branch (139 passed, 7 skipped, 4 gloo timeouts that pass alone on both main and this branch). Not measured here: gradient accumulation parity and graph-break counts for these loaders.

device_map defaulted to "auto", so under torchrun / accelerate launch every rank spread the
model over all visible cards. A 2-rank native FSDP2 run died in transformers'
infer_auto_device_map (IndexError) before training, in LoRA, QLoRA and full finetuning.
An automatic map now becomes the rank's own device, as in FastLanguageModel / FastModel;
a device the caller named is kept.
…P2=1

Native FSDP2 shards inside Unsloth's Trainer.__init__ wrapper, which only FastLanguageModel /
FastModel loads (and DecisionTrainer) installed. A FastSentenceTransformer encoder (BERT,
ModernBERT) never loads through them, so under UNSLOTH_FSDP2=1 torchrun its
SentenceTransformerTrainer trained with plain DDP: nothing sharded, no message.
import unsloth now installs the wrapper when the flag selects native FSDP2.
…fast encoder path

get_peft_model accepted random_state but never used it for BERT / ModernBERT style encoders,
so the adapters depended on the RNG history and every torchrun rank drew its own. FastModel
seeds with transformers.set_seed(random_state); this path now does the same.
DDP broadcasts rank 0's parameters when it wraps the model. fully_shard keeps each rank's own
slice, so a trainable tensor initialised without a common seed (an unseeded adapter, a fresh
head) was sharded as a mix of the ranks' values and the ranks trained a model none of them
started from. shard_model compares a checksum per trainable tensor over the mesh and
broadcasts the first rank's values of those that differ, with a one-line notice.
…ank sync

NaN != NaN, so a checkpoint with non-finite weights (tiny Llama4) was reported as differing
across ranks and re-broadcast. The checksum comparison is now NaN-aware.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-24T03:52:20.467442Z c2571ef 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 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: c7e93f0fb0

ℹ️ 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 thread unsloth/models/fsdp2_native.py Outdated
Comment on lines +1271 to +1275
torch.stack(
(
p.detach().sum(dtype = torch.float64),
torch.linalg.vector_norm(p.detach(), 1, dtype = torch.float64),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Compare full parameter contents before skipping synchronization

When ranks hold different tensors with the same sum and L1 norm, this check treats them as identical and skips the broadcast; for example, [1, -1] and [-1, 1] both produce (0, 2). Likewise, if both tensors contain a NaN, both statistics can be NaN and the later NaN-aware comparison masks differences in all remaining elements. In these cases FSDP2 still shards a mixture of rank-local initial weights, defeating the synchronization this change is intended to provide, so the decision needs a collision-resistant/full-content comparison or an unconditional broadcast.

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 14402bb. The per-tensor check is now a content fingerprint: sum, L1 norm, a sum weighted by a position-dependent cos(i * golden ratio), and the count of non-finite elements, with non-finite values mapped to fixed finite stand-ins first. A permutation such as [1, -1] vs [-1, 1] now differs in the weighted term, and a NaN shared by both ranks no longer hides differences elsewhere, while identical NaN patterns still agree. A full finetune whose ranks agree still sends only the fingerprints. New cases test_a_permuted_adapter_is_not_mistaken_for_the_same and test_a_shared_nan_does_not_hide_other_differences fail on the previous head and pass now.

@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: 14402bbbf7

ℹ️ 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 +1264 to +1268
chunk = flat[start : start + _FINGERPRINT_CHUNK].to(torch.float64)
bad = ~torch.isfinite(chunk)
chunk = torch.nan_to_num(chunk, nan = 3.0, posinf = 5.0, neginf = -7.0)
index = torch.arange(start, start + chunk.numel(), dtype = torch.float64, device = chunk.device)
weight = torch.cos(index * 0.6180339887498949)

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 Bound the fingerprint's temporary allocation

When full-finetuning a model with a trainable tensor of at least 16,777,216 elements on GPU, one iteration creates several 128 MiB float64 buffers (chunk, index, weight, and the multiplication temporary), plus the finite mask. Because this runs before fully_shard while the complete model is still resident, the roughly 400–500 MiB peak can OOM a job whose model would otherwise fit under FSDP2; use a substantially smaller chunk or a fingerprint implementation that does not materialize multiple float64 arrays.

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 ece2522: the fingerprint chunk is now 1,048,576 elements, so each iteration holds a few 8 MiB float64 buffers (chunk, index, weight, product, mask), about 40 MiB in total, before fully_shard, whatever the tensor size. A large tensor just takes more chunks; the result is the same.

@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: ece2522f7e

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

Copy link
Copy Markdown
Member Author

The Repo tests (CPU, studio) red here comes from this PR's new tests/python/test_fast_sentence_transformer_lora_seed.py, which is not on main. Both of its tests fail on the CPU runner:

tests/python/test_fast_sentence_transformer_lora_seed.py:32: in test_random_state_fixes_the_adapters
tests/python/test_fast_sentence_transformer_lora_seed.py:40: in test_a_different_random_state_gives_different_adapters
AssertionError: Torch not compiled with CUDA enabled

They reach a real CUDA call under the CPU spoof. Either keep the model on CPU in the test, or gate it on has_real_cuda() (from real_accelerator import has_real_cuda).

gate is the Kaggle T4 quota, which is exhausted until 2026-10-24 00:00 UTC.

The loader reads device properties even with device_map = "cpu", so the CPU-only CI job failed
with "Torch not compiled with CUDA enabled".

[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. Delightful!

Reviewed commit: c2571efa98

ℹ️ 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 c52ef02 into main Oct 24, 2026
32 of 38 checks passed
@danielhanchen
danielhanchen deleted the dh/s4-fsdp2-any-loader branch October 24, 2026 04:43
danielhanchen added a commit that referenced this pull request Oct 27, 2026
…wrapped the Trainer (#15427)

## Problem

On a non-CUDA install (Intel XPU, Ascend NPU, MLU, ...),
`UNSLOTH_FSDP2=1` is routed to accelerate's FSDP2 at import time, and
`unsloth_fsdp2_native_requested()` is False. #14760 added
`reclaim_native_fsdp2_for_cpu_trainer` so that a
`TrainingArguments(use_cpu=True)` Trainer still shards natively
(accelerate runs it as MULTI_CPU, which never builds its FSDP plugin).
That reclaim lives inside the `Trainer.__init__` wrapper, but the
import-time installer `install_native_fsdp2_trainer_init` (#15012)
returns early whenever native FSDP2 is not requested, so it never
installs the wrapper on this route.

FastLanguageModel / FastModel loads install the wrapper themselves, so
they are unaffected. A plain `Trainer` after `import unsloth`, or a
FastSentenceTransformer encoder that loads without FastModel, trains
with the model unsharded and no message, even though the launch step
printed that FSDP2 shards it.

## Fix

`install_native_fsdp2_trainer_init` also installs the wrapper while the
non-CUDA export is pending (`_NON_CUDA_EXPORT is not None`). It still
returns False there, and a non-CPU Trainer on that install keeps
accelerate's FSDP2 exactly as before (the reclaim returns False and
changes nothing).

## Before / after

2-rank gloo CPU world, XPU build markers (`torch.version.xpu`), only the
two import-time steps of `unsloth/__init__.py` run, then a plain Trainer
on a tiny Llama LoRA with `use_cpu=True`.

| Check | main (0ea0473) | this branch |
|---|---|---|
| Trainer wrapper installed | no | yes |
| Model sharded by native FSDP2 | no | yes |
| `ACCELERATE_USE_FSDP` left exported | true | unset |
| Accelerator distributed type | MULTI_CPU | MULTI_CPU |
| `test_xpu_install_cpu_trainer_shards_natively_without_a_loader` | FAIL
| PASS |

Head also passes `tests/test_fsdp2_native_trainer_args_gloo.py`,
`tests/test_fsdp2_native_trainer_init_any_loader_gloo.py` and
`tests/test_fsdp2_non_cuda_accelerate_route.py` (29 passed) on torch
2.13 / transformers 5.17, and the two XPU reclaim tests on torch 2.6 CPU
/ transformers 4.57.6, torch 2.10 and torch 2.14.

## Not covered

- No real XPU / NPU / MLU hardware: the non-CUDA install is simulated
through `torch.version` build markers, as the existing #14760 test does.
- `import unsloth` itself cannot run on a CPU-only host, so the test
executes the real `fsdp2_launch` functions in the order
`unsloth/__init__.py` calls them, with the real `_unsloth_trainer_init`
source.
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