Skip to content

Native FSDP2: memory-scalable 16-bit loading (each rank reads only its shard), and the fp16 start scale on sub-meshes - #15225

Merged
danielhanchen merged 31 commits into
mainfrom
dh/s6-fsdp2-sharded-load
Oct 26, 2026
Merged

danielhanchen merged 31 commits into
mainfrom
dh/s6-fsdp2-sharded-load

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Builds on #15174 (tensor parallel v2, merged): it reuses and generalises its safetensors slice reader.

Why

Under native FSDP2 (UNSLOTH_FSDP2=1) every rank loads the whole model before shard_model, so a model that does
not fit one GPU cannot be loaded at all, even though FSDP2 would only keep 1 / world of it per rank afterwards.
Qwen3-8B in 16-bit (16.4 GB) on 2x T4: every rank runs out of memory at load.

What

Sharded loading (opt-in).

from unsloth.models.fsdp2_load import fsdp2_sharded_loading, load_fsdp2_sharded

with fsdp2_sharded_loading():                      # any loader that ends in transformers from_pretrained
    model, tokenizer = FastLanguageModel.from_pretrained(name, load_in_4bit = False, ...)
model = FastLanguageModel.get_peft_model(model, ...)
trainer = SFTTrainer(model = model, ...)           # UNSLOTH_FSDP2=1: shard_model installs the shards

or UNSLOTH_FSDP2_SHARDED_LOAD=1 next to UNSLOTH_FSDP2=1, which runs FastLanguageModel / FastModel /
FastVisionModel from_pretrained inside the context (outermost call only). Nothing changes without either.

  • The model is built on meta. Every nn.Linear weight except the output head is read from safetensors as this
    rank's FSDP2 dim-0 chunk (the rows fully_shard keeps, torch.chunk semantics, so uneven and empty chunks
    match), via get_slice, so only those bytes are read. Everything else (embeddings, norms, biases, buffers) is
    read whole, as the full load does.
  • A chunk stays a plain tensor tagged with its full shape: nn.Linear keeps its full features, so
    get_peft_model builds full-size LoRA with the same init as one GPU. A forward before shard_model is refused.
  • shard_model swaps each chunk for a full-shape meta placeholder (so the layout planner sees the whole model),
    runs fully_shard, and installs the chunk as the FSDPParam local shard (padded as fully_shard pads it). The
    full weight never exists on any rank. A chunk the layout keeps replicated (fit layout frozen weights,
    minority-dtype parameters) is all-gathered back, which is exactly what the full load holds.
  • The reader in tp_native.py is now shared (_fill_from_checkpoint, _SliceReader.rows,
    _sharded_from_pretrained) and maps checkpoint keys through transformers' conversion renames, so VLMs whose
    checkpoints use the legacy names (model.layers.* for model.language_model.layers.*) load; tensors a
    WeightConverter builds from several checkpoint tensors are refused with a clear message.
  • Refused with a clear message: 4-bit / 8-bit / pre-quantized loads (QLoRA still loads the full quantized model;
    rank-0 CPU quantize + scatter is a follow-up), 2-D (HSDP) meshes, cpu_offload, shard_placement_fn, a
    mesh other than the one loaded over, and weight-dependent LoRA inits (PiSSA, OLoRA, ...).

fp16 start scale. The Trainer multiplies every rank's loss by num_processes (over the tensor parallel
size), so the fp16 start scale must be divided by that, not by the FSDP2 mesh size. They differ on a sub-mesh
smaller than the world: two 2-rank meshes of 4 ranks started 2x too high and the first step overflowed. CP = 2,
DP = 1 shards over the world, where both agree (now pinned by a test).

Tests (CPU gloo, 2 and 4 ranks; every new test fails before except the CP = 2 pin)

tests/test_fsdp2_native_sharded_load_gloo.py against the full load + shard_model on the same checkpoint
(tiny models saved as multi-file safetensors):

case local shards (incl. padding) 3 steps (losses, clip norms, final shards) bytes read
Llama, intermediate_size = 37 (uneven chunks), LoRA, sharded layout bitwise bitwise own rows only
same, fit layout (frozen chunks gathered back) bitwise bitwise own rows only
same, full finetune bitwise bitwise own rows only
Qwen3 LoRA / full finetune bitwise bitwise own rows only
Qwen2.5-VL (vision tower + projector linears sliced) LoRA bitwise bitwise own rows only

Byte counters: each rank's sliced bytes equal its own chunk sizes, the two ranks together read every sharded
tensor exactly once, and whole reads equal the replicated parameters. Plus refusals, _chunk_rows against
torch.chunk for many shapes, and the env flag being inert without UNSLOTH_FSDP2.

tests/test_fsdp2_native_fp16_scale_mesh_gloo.py: CP = 2, DP = 1 (passes before and after: no bug there) and two
2-rank sub-meshes of 4 ranks (before: start scale 32768 instead of 16384).

Existing suites unchanged: test_tp_native_gloo.py + test_tp_native_oracle.py 86 passed, 1 skipped;
test_fsdp2_native_* + test_fsdp2_perf_layout_gloo.py + test_context_parallel_fsdp2_gloo.py 268 passed,
2 skipped.

GPU (Kaggle 2x T4, torch 2.14.1, transformers 5.17.0, PEFT 0.21.2)

Qwen3-0.6B, LoRA r16 on all 7 projections, fp16 autocast, AdamW 2e-4, seq 512, bs 2 per rank, 20 steps, sharded
layout, custom loop:

arm load peak GiB / rank after shard_model train peak loss step 0 / step 20
full load A 1.118 / 1.110 0.582 / 0.574 1.638 0.952910 / 0.3927
full load B (A/A) 1.118 / 1.110 0.582 / 0.574 1.638 0.952910 / 0.3845
sharded load 0.708 / 0.700 0.582 / 0.574 1.638 0.952910 / 0.3833
  • The FSDP2 local shards right after shard_model hash identically (sha256 over every local tensor) on both ranks
    for the full and the sharded load.
  • Step-0 loss is bitwise identical in all arms. Later steps differ by GPU nondeterminism: sharded vs full max abs
    loss diff 0.0094 (mean 0.0021) over 20 steps, inside the A/A pair's 0.0082 (mean 0.0018).
  • Trainer path (UNSLOTH_FSDP2=1, SFTTrainer, fp16 GradScaler, 10 steps) with UNSLOTH_FSDP2_SHARDED_LOAD=1 vs
    without: the sharded path engaged on both ranks (byte counters recorded), load peak 0.708 vs 1.118 GiB, max abs
    loss diff 2.5e-4.

Qwen3-8B 16-bit (16.4 GB, does not fit one T4):

arm load peak GiB / rank after shard_model train peak (5 steps) losses
full load per rank (today) out of memory at load (14.18 of 14.56 GiB)
sharded load, seq 512, bs 1 8.80 / 8.79 7.72 / 7.71 13.29 0.845, 0.805, 0.776, 0.751, 0.730
sharded load, seq 256, bs 1 8.80 / 8.79 7.72 / 7.71 13.27 1.676, 1.590, 1.525, 1.474, 1.431

Each rank read 6.95 GB of linear-weight rows (exactly half of all linear weights) and 2.49 GB whole (embeddings,
head, norms). Load took 26 to 40 s per rank.

Not covered

  • QLoRA (4-bit) sharded loading: refused for now.
  • HSDP / 2-D meshes, cpu_offload: refused for now.
  • Tested on CUDA (T4) and CPU only.

danielhanchen and others added 21 commits October 24, 2026 15:19
sharded_loading(tp_mesh) / load_tensor_parallel(...) make from_pretrained build the model on meta and
stream the safetensors checkpoint: replicated tensors whole, attention / MLP projections as this rank's
slices (per-part slices for fused qkv and packed gate_up). The slices stay plain tensors tagged with
their full shape, so get_peft_model creates full-size LoRA factors with the same init as one GPU;
apply_tensor_parallel then wraps them into the DTensors v1 builds. A forward before
apply_tensor_parallel is refused. 16-bit safetensors checkpoints only; quantized loads are refused.
shard_model(model, FSDP2Config(mesh = mesh['dp'])) now accepts a model sharded by
apply_tensor_parallel(model, mesh['tp']) when the two meshes are the dimensions of one (dp, tp) mesh
covering the world. The frozen tp shards stay replicated over dp (fully_shard(ignored_params), torch
2.7+); FSDP2 shards the trainable LoRA DTensors over dp and reduces their tp Partial gradients itself.
Refused: no mesh / a mesh that is not the dp dimension, shard_frozen, cpu_offload, torch < 2.7, and
trainable per-head norms (their tp sum is a Parameter hook, and FSDP2 replaces the Parameters).

- The trainable-weight agreement compares and broadcasts the local tensors of DTensor parameters.
- Fused / packed layouts are also recorded on the owning module, so adapter saving and gathered grads
  keep the 1-GPU order after FSDP2 replaces the Parameter objects.
- tp_clip_grad_norm_ handles 2-D gradients (each element counted once over its replicas).
- native_clip_grad_norm_ counts FSDP2's _StridedShard as a shard dimension: newer torch does not report
  it as is_shard(), so those norms were not reduced over dp.
- save_tp_adapter accepts a tp mesh smaller than the world when the dp dimension covers the rest.
The Trainer no longer refuses a model sharded by apply_tensor_parallel (tp only, or dp x tp after
shard_model over mesh['dp']). tp_native.tp_trainer_setup runs around Trainer.__init__:
- accelerate does not wrap the tp ranks in DDP (prepare_model keeps only the autocast wrap; native FSDP2
  prepares a dp x tp model itself),
- the dataloader is sharded over dp only, so the tp ranks of a replica read the same batches,
- clip_grad_norm_ uses tp_clip_grad_norm_, and float16 gets a ShardedGradScaler (one inf decision for
  all ranks, initial scale divided by dp),
- trainer.save_model() writes the standard 1-GPU adapter (collective),
- the generated TRL trainers skip their trailing model.for_inference() (it would route the decoder
  layers onto decode paths outside the tensor parallel regions).
The loss needs no change: the token count gathered over the world counts each replica's tokens tp
times and the Trainer's loss scale multiplies by dp * tp, which FSDP2's mean over dp turns into the
token mean over the dp replicas.
Refused with a reason: Trainer checkpoints / resume, evaluation, bitsandbytes / paged / GaLore
optimizers, DeepSpeed, accelerate FSDP / ParallelismConfig, iterable datasets, model_init, and a tp
mesh that does not cover the world without shard_model over the dp dimension.
…inear weights

fsdp2_sharded_loading() / load_fsdp2_sharded() / UNSLOTH_FSDP2_SHARDED_LOAD=1 build the model on meta and read
every nn.Linear weight except the output head as this rank's FSDP2 dim-0 chunk from safetensors (the rest whole),
reusing the tensor parallel sharded loader (now shared: _fill_from_checkpoint, _SliceReader.rows,
_sharded_from_pretrained). shard_model swaps the chunks for full-shape meta placeholders, fully_shards and installs
each chunk as its FSDPParam local shard; chunks the layout keeps replicated are all-gathered back. 16-bit only.
…multiplier, not the mesh size

The Trainer multiplies each rank's loss by num_processes (over tp), so on a sub-mesh smaller than the world (two
2-rank meshes of 4 ranks) dividing by the mesh size left the start scale 2x too large and the first step
overflowed. CP = 2, DP = 1 shards over the world, where both agree (pinned by a gloo test).
… renames (VLMs)

transformers 5 VLMs save model.layers.* for model.language_model.layers.*; the sharded reader now applies the
model's WeightRenaming mapping (and 4.x _checkpoint_conversion_mapping) to find each tensor, and refuses keys a
WeightConverter builds from several tensors. Adds a tiny Qwen2.5-VL native FSDP2 sharded-load parity case.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 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-25T09:50:07.033311Z e0f42c5 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: 1327596e68

ℹ️ 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 +318 to +320
for module, name in where:
module._parameters[name] = meta
pending[(id(module), name)] = (local, info)

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 Remap ignored parameters when replacing preloaded weights

When FSDP2Config.ignored_params contains a sharded-loaded linear weight, replacing that parameter with meta leaves the configuration pointing to the old chunk. Subsequently, gather_replicated cannot match the replacement against the replicated set, and shard_model_layout filters the stale parameter out because it is no longer in module.parameters(). The explicitly ignored weight is therefore sharded instead of reconstructed and kept replicated. Update the ignored-parameter references alongside these replacements so this existing configuration option retains its semantics.

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 the latest push. begin_shard now remaps FSDP2Config.ignored_params when it swaps a sharded-loaded chunk for its meta placeholder. The caller's set is updated in place, and any other iterable is copied into a new set on the config. shard_model then passes that set to gather_replicated along with the internal ignored set. The result: an explicitly ignored weight is all-gathered whole, stays out of fully_shard, and the caller's set ends up holding the live replicated parameter, the same as on the full-load path.

Test: test_sharded_loading_matches_full_load_shard_model has two new cases (llama-...-full-ignore and llama-...-lora-ignore), 2 gloo ranks, intermediate_size = 37 so the chunks are uneven. Each one ignores layers.0.mlp.down_proj (trainable in full FT, frozen base under LoRA). It checks that every ignored_params entry is a live, non-DTensor, whole parameter on both paths, that every parameter and padded FSDP2 shard is bitwise equal to the full load, and that 3 training steps match bitwise. Both cases failed before the fix (the set still held the stale chunk) and pass now.

Comment on lines +100 to +102
start, stop = _chunk_rows(rows, world, rank)
local = reader.rows(key, start, stop).to(device = device, dtype = old.dtype)
new = nn.Parameter(local.contiguous(), requires_grad = old.requires_grad)

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 Handle DoRA initialization before exposing partial base weights

With more than one rank, attaching an adapter with LoraConfig(use_dora=True) after sharded loading fails during get_peft_model, before shard_model can run. The linear retains its full out_features, so PEFT creates a full-sized lora_B @ lora_A, but DoRA's initialization adds that matrix to this partial base weight to compute its magnitude, causing a row-dimension mismatch. Native FSDP2 already supports DoRA through the full-load path. Provide shard-aware magnitude initialization or explicitly reject this combination before PEFT initializes the adapter; the current check of init_lora_weights does not cover DoRA with its default initialization.

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 the latest push by refusing the combination with a clear error. A sharded load with more than one rank wraps PEFT's DoraLinearLayer.update_layer, which is where DoRA computes its magnitude. If the base layer's weight is a sharded-loaded chunk, get_peft_model now raises a ValueError before PEFT computes the norm. The message names use_dora and says to load the full model (drop fsdp2_sharded_loading / UNSLOTH_FSDP2_SHARDED_LOAD) to train DoRA under native FSDP2. The wrapper does nothing for any other base layer, so DoRA on a full load is unchanged. begin_shard also refuses use_dora on a sharded-loaded model as a backstop, next to the existing init_lora_weights check.

Test: test_sharded_loading_refuses_dora (2 gloo ranks, llama with intermediate_size = 37, LoraConfig(use_dora = True) with its default init) checks that get_peft_model on the sharded-loaded model raises the use_dora message, and that the same config on a full load in the same process still succeeds. Before the fix it failed with PEFT's The size of tensor a (8) must match the size of tensor b (16).

…arly

FSDP2Config.ignored_params naming a sharded-loaded weight now follows the
meta placeholder and the gathered whole parameter, so it stays replicated
exactly as on the full load. DoRA's magnitude init on a sharded-loaded
chunk is refused at get_peft_model time with a message naming use_dora.

[skip ci]
@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: 674e0d6bdc

ℹ️ 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 +164 to +167
for module in model.modules():
if isinstance(module, nn.Linear) and id(module._parameters.get("weight")) in owners:
guards.append(module.register_forward_pre_hook(_refuse_unsharded_forward))
model.__dict__[_GUARD] = guards

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 Handle sharded linear copies created by modules_to_save

When PEFT is attached with a sharded linear in modules_to_save (for example, target_modules=["q_proj"] and modules_to_save=["down_proj"] through plain PEFT or FastModel), ModulesToSaveWrapper.update deep-copies that linear, including this forward pre-hook. However, begin_shard removes only the original handles stored on the root model, leaving the copied layer's hook installed. Consequently, the first training forward still raises “shard it first” after shard_model has completed. Handle these copied layers explicitly, including preserving their chunk metadata, or reject this combination before PEFT copies the partial weights.

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 the latest push. Two parts: Parameter.__deepcopy__ drops the chunk tag, so begin_shard now gives each modules_to_save copy that is still identical to its sharded-loaded original the original's tag, and the copy is then swapped to a full-shape placeholder and sharded like the full load's copy. The deep-copied forward guard is removed by function from every module, not only through the handles stored on the root. New parity case llama ... lora_mts (target_modules = ["q_proj"], modules_to_save = ["down_proj"], uneven chunks, 2 gloo ranks): it failed with "shard it first" before, and now every parameter, padded shard and 3 training steps are bitwise equal to the full load, with the same byte counters.

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

ℹ️ 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/tp_native.py Outdated
rename_source_key,
)

transforms = get_model_conversion_mapping(model)

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 Preserve load-specific key mappings during checkpoint lookup

When sharded loading is used with a load-specific key_mapping, this reconstructs only the model's default conversions and drops the mapping passed to from_pretrained. This affects existing text-only loading paths: FastModel.from_pretrained calls _apply_text_only_key_mapping to map VLM checkpoint prefixes such as language_model.model.* onto standalone decoder keys such as model.*. The initial meta load honors that mapping, but _fill_from_checkpoint subsequently cannot resolve those parameters and raises “found no checkpoint tensor,” preventing the new native FSDP2 loading path from loading these models. Pass the load's mapping into alias resolution, or reuse the conversions retained by the loaded model.

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 the latest push. _fill_from_checkpoint now passes the load's key_mapping (from the from_pretrained kwargs) into _checkpoint_aliases: on transformers 5 it goes into get_model_conversion_mapping(model, key_mapping = ...), so it is applied with the model's own renames in one pass, and on 4.x it replaces _checkpoint_conversion_mapping as from_pretrained does. New parity case llama ... lora remap: the checkpoint is saved with VLM-style keys (language_model.model.*, language_model.lm_head.*) and loaded with the text-only mapping Unsloth uses. It failed with "found no checkpoint tensor for 'model.embed_tokens.weight'" before; now the shards, 3 training steps and byte counters match the full load bitwise.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: e0f42c56c4

ℹ️ 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 added a commit that referenced this pull request Oct 25, 2026
## Summary


`studio/backend/tests/test_model_memory_settings.py::TestNoNestedHelperIsUsedBeforeItsDef::test_every_nested_def_precedes_its_calls`
fails on main, so `(Python 3.13, g-r)` is red on unrelated PRs (for
example #15225):

```
AssertionError: UnboundLocalError at runtime: _try_auto_vulkan_cpu_fallback called at 8198, defined at 8232
```

#14521 (load GGUF on CPU when the auto-selected Vulkan driver hangs)
added the nested `_recover_vulkan_stall` inside `load_model`. It calls
`_try_auto_vulkan_cpu_fallback`, which is defined about 40 lines further
down. Today this does not raise: all three callers of
`_recover_vulkan_stall` sit below both definitions, and a closure looks
the name up when it runs. But the guard's rule is "a nested helper is
defined above every textual use", because the looser version (the call
is fine as long as every caller of the caller runs late enough) already
shipped broken once and aborted every full-offload launch. Keeping that
simple rule true is cheaper than teaching the guard call-graph ordering.

## Change

- Move `_recover_vulkan_stall` (unchanged, 19 lines) from just above
`_vulkan_stall_pending` to just below `_try_auto_vulkan_cpu_fallback`.
It is still above its first caller. Only `def`s sit between the old and
new spots, and the defaults are literals, so nothing evaluates
differently.

## Verification

- The diff is a pure move: every removed line is added back once.
- `test_every_nested_def_precedes_its_calls`: fails on main, passes with
this change.
- `test_vulkan_no_device_cpu_route.py`,
`test_gpu_init_crash_message.py`, `test_load_mode_fit_matrix.py`,
`test_vram_budget_settings.py`, `test_model_memory_settings.py`: `1
failed, 2402 passed` on main (the guard), `2403 passed` with this
change.
danielhanchen added a commit that referenced this pull request Oct 25, 2026
…d copy (#15264)

`tests/test_tp_native_gloo.py::test_tp2_x_fsdp2_dp2_matches_one_process[llama-True-lora_kwargs4]`
fails now and then in `Repo tests (CPU, rest)` on unrelated PRs (#15159,
#15174, #15217, #15218, #15222, #15225) with only `AssertionError:
base_model.model.lm_head.weight`. Gradients, losses and norms all match
in those runs. Only the saved `lm_head` copy differs.

## Cause

The test, not the product. That case trains a full `lm_head` copy
(`modules_to_save`, 512000 entries) with AdamW at lr 1e-2 and the
default eps of 1e-8. At g = 0, Adam's `g / (sqrt(v) + eps)` has slope lr
/ eps = 1e6. Measured on main on this host:

| | value |
| --- | --- |
| median step-0 lm_head grad | 5.7e-6 |
| entries with step-0 grad below 1e-8 | 313 |
| step-0 grad of the 10 worst saved-weight entries | 4e-11 to 7e-9 |
| worst saved-weight diff / tolerance | 0.46 |

So reduction-order noise of about 1e-12 on a near-zero gradient becomes
about 5e-6 of weight. That is already half the `atol = 1e-5` here. A
runner whose CPU kernels sum in a different order goes over it.

## Fix

- Both arms use `AdamW(eps = 1e-6)`. The optimizer is still identical on
both sides, and 1e-6 is small next to the typical gradient, so the head
still trains. The worst entry drops to 0.0075 of the tolerance (60x
headroom).
- The saved-weight assert now keeps `assert_close`'s mismatch detail. It
used to print only the key, which is why the CI logs never showed how
far off the weight was.

## Verification

- `tests/test_tp_native_gloo.py`: 38 passed.
- Sabotage on the last step, after the norms are taken, so only the
saved weight can catch it:
- TP arm skips the lm_head update: fails, 511627 / 512000 mismatched,
max abs diff 1.0e-2.
- Each dp half's lm_head gradient scaled by +/-15% (a stand-in for a
missing dp reduction): fails, 493693 / 512000 mismatched, max abs diff
8.1e-4.
  - No sabotage: passes.
@danielhanchen
danielhanchen merged commit 20bbee4 into main Oct 26, 2026
31 of 37 checks passed
@danielhanchen
danielhanchen deleted the dh/s6-fsdp2-sharded-load branch October 26, 2026 08:09
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