Skip to content

Keep frozen load_in_fp8 weights out of FSDP2 sharding and the DDP broadcast - #15001

Merged
danielhanchen merged 5 commits into
mainfrom
dh/s4-fp8-distributed
Oct 23, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
dh/s4-fp8-distributed

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

load_in_fp8 = True could not train on more than one GPU:

  • Native FSDP2 with the sharded layout failed inside fully_shard (Float8Tensor dispatch: aten.new_zeros not implemented).
  • DDP failed in its start-up parameter broadcast (Float8Tensor: only support reshaping from 2D to 3D or from 3D to 2D, requested [-1]).

Single GPU training was fine.

Cause

torchao's Float8Tensor reports bfloat16 as its dtype, so the existing float8 check in fsdp2_native.py never matched it. DDP flattens every parameter it broadcasts, and Float8Tensor does not implement that.

Fix

The FP8 base weights are frozen and every rank loads and quantizes them identically, so this change keeps them replicated:

  • Native FSDP2: frozen torchao weights join ignored_params in every layout. A trainable one is refused with a clear error. torchao's Float8 training weights (torchao.float8, e.g. with enable_fsdp_float8_all_gather) implement FSDP2's hooks and are still left to fully_shard.
  • DDP: frozen tensor subclass weights are added to _ddp_params_and_buffers_to_ignore after from_pretrained and get_peft_model, and again in the Trainer init for plain DDP. A trainable Float8Tensor is refused on every rank, so no rank hangs.

LoRA parameters still shard under FSDP2 and all-reduce under DDP as before. Nothing changes on one GPU.

Tests

  • New CPU gloo test tests/test_fp8_torchao_distributed_gloo.py (Float8Tensor builds on CPU):
    • FSDP2 sharded and auto layouts, and DDP through both hooks, match a single-process run's gradients within 1e-5.
    • Trainable Float8Tensor weights are refused.
    • 5 fail on main, 5 pass with this change.
  • 2x B200, tiny Llama, fp8 LoRA r 8, 5 steps, same data and seed:
    • FSDP2 auto, FSDP2 sharded and DDP now all train, and their step-0 LoRA gradients are bitwise equal.
    • Against one GPU: max relative loss difference 1.0e-4, step-0 gradient relative L2 2.4e-3. Plain 16-bit LoRA DDP against one GPU shows the same 2.4e-3 (the bf16 batch split).
    • Every rank launches the same FP8 scaled-mm kernels as one GPU (42 cutlass F8F6F4 GEMMs and 24 activation-quant kernels per step).
  • Existing tests still pass: test_block_swap_auto_ddp, test_fsdp2_native_int8_gloo, test_fsdp2_native_trainer_args_gloo.

load_in_fp8 with full_finetuning = True stays refused at load time, as it is on one GPU.

Not covered: models other than a tiny Llama, SM 8.9 / 9.0, load_in_fp8 = "block", multi-node, checkpoint save and resume under 2 ranks, runs longer than 5 steps.

…d the DDP broadcast

torchao's Float8Tensor reports bfloat16 as its dtype, so native FSDP2's float8
check missed it and the sharded layout passed it to fully_shard (aten.new_zeros
is not implemented), and DDP's start-up broadcast flattened it (reshape to [-1]
is not implemented). The frozen FP8 base is loaded identically on every rank:
keep it replicated (ignored_params) in every FSDP2 layout, and in DDP's
_ddp_params_and_buffers_to_ignore at load / get_peft_model and at trainer init.
Trainable Float8Tensor weights are refused under both.
@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-23T22:11:21.994276Z 6fe12a4 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: 4876bfbc8b

ℹ️ 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/_utils.py
_replan_auto_offload_safely(self)
_size_auto_checkpoint_skip_for_trainer(self)
_block_swap_for_trainer_backend(self)
_tensor_subclass_weights_for_ddp(self)

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 Reapply FP8 DDP exclusions after model_init rebuilds

When Trainer is configured with model_init—including during hyperparameter search—Transformers invokes the factory again when training starts and replaces self.model. This post-init-only hook therefore marks only the initial instance; the replacement loses _ddp_params_and_buffers_to_ignore, so DDP again attempts to broadcast its frozen Float8Tensor weights and fails. Apply the helper to each rebuilt model, or reject model_init for this configuration as the native FSDP2 path does.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Oct 23, 2026 •

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 37372db: Trainer.call_model_init is wrapped (once, alongside the existing Trainer init patch) so the model a model_init factory returns, at init and again when train() rebuilds it, gets the same DDP exclusions. A factory that loads through FastLanguageModel / FastModel was already covered by the loader hook; this also covers models built any other way. Test: a model_init case in tests/test_fp8_torchao_distributed_gloo.py.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit that referenced this pull request Oct 23, 2026
`studio/backend/tests/test_gguf_load_cache_reuse.py::TestLoadHubDownloadExclusion::test_load_marker_precedes_hub_guard_which_precedes_the_gpu_handoff`
fails on `main`, for example in Backend CI `(Python 3.13, a-k)` on
#15000 and #15001.

## Cause

The test's last assertion is a literal source match:
`"@_with_gguf_load_marker\n def load_model("`. #14546 added
`@holds_inference` between that decorator and `def load_model`, so the
string no longer appears. The load marker still wraps
`LlamaCppBackend.load_model`, so the product is fine and the test was
out of date.

## Fix

The check now parses `llama_cpp.py`, finds `LlamaCppBackend.load_model`,
and asserts that `_with_gguf_load_marker` is in its decorator list, in
any position. The rest of the test, including the ordering in
`routes/inference.py`, is unchanged.

## Verification

- `studio/backend/tests/test_gguf_load_cache_reuse.py`: 75 passed. On
`main` this test failed when run alone.
- Sabotage check: removing `@_with_gguf_load_marker` from `load_model`
fails the test.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 37372db300

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

WeightWithDynamicFloat8CastTensor implements the flatten DDP's start-up broadcast needs and plain DDP
trains it, so the tensor subclass scan no longer leaves it out of DDP or refuses a trainable one.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 6fe12a4280

ℹ️ 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 888c51b into main Oct 23, 2026
9 of 30 checks passed
@danielhanchen
danielhanchen deleted the dh/s4-fp8-distributed branch October 23, 2026 22:17
danielhanchen added a commit that referenced this pull request Oct 26, 2026
…y_shard and the DDP broadcast (#15373)

#15001 keeps frozen `load_in_fp8` weights (torchao `Float8Tensor`) out
of FSDP2 sharding and out of the DDP broadcast. Its classifier matches
every torchao tensor subclass outside `torchao.float8`, which catches
two cases it should leave alone:

- Frozen NF4 weights (`NF4Tensor`, QLoRA) are kept replicated under
`FSDP2Config(shard_frozen=True)`. Each rank holds the full packed weight
instead of half of it.
- Trainable int8 mixed precision training weights
(`Int8MixedPrecisionTrainingLinearWeight`) are refused under FSDP2
(`cannot shard trainable float8 parameters`) and under DDP
(`NotImplementedError`).

Both classes implement the FSDP2 all-gather hooks and the DDP flatten,
and both trained before #15001.

## Fix

- `fsdp2_native._float8_params` now keeps a torchao subclass out of
`fully_shard` only when its class implements no FSDP2 all-gather
extension (`fsdp_pre_all_gather`). That covers `Float8Tensor`,
`AffineQuantizedTensor`, and the inference int8 / int4 weights
(`Int8Tensor`, `IntxUnpackedToInt8Tensor`), which implement only the ops
their linear needs: `fully_shard`'s split fails on them
(`NotImplementedError: Int8Tensor dispatch: ... aten.split`).
`NF4Tensor`, the int8 mixed precision training weight and
`torchao.float8` training weights implement the extension and go to
`fully_shard`.
- On the DDP side, frozen tensor subclass weights are still left out of
the broadcast. Trainable weights are refused when they store float8 or
when DDP's start-up broadcast cannot flatten them (`Int8Tensor`,
`AffineQuantizedTensor`), so trainable int8 training weights and NF4
reach DDP as they did before #15001.

## Tests

`tests/test_fp8_torchao_distributed_gloo.py` gets four new cases; the
first three run on 2 CPU gloo ranks, the `Int8Tensor` one in one
process.

| test | main | this PR |
|---|---|---|
| frozen NF4, `shard_frozen=True`: both MLP weights are DTensors holding
32768 packed bytes per rank (half of 2 x 32768) | fail (replicated, 0
DTensors) | pass |
| trainable int8 mixed precision weights shard, backward gives finite
grads | fail (`NotImplementedError`) | pass |
| DDP keeps trainable int8 weights and ignores frozen NF4; FSDP2 finds
no float8 weights | fail | pass |
| frozen `Int8Tensor` (Int8WeightOnlyConfig) stays replicated; trainable
is refused by FSDP2 and DDP up front | pass | pass (fails on the first
revision of this PR, which sent it to `fully_shard`) |
| the 7 existing Float8Tensor FSDP2 / DDP cases | pass | pass |

`test_fsdp2_native_int8_gloo.py`, `test_float8_training_fsdp2_gloo.py`
and `test_fsdp2_native_units.py` still pass (72 tests with
`test_float8_training.py`). The classifier was also run over the torchao
weight classes on torchao 0.15 and 0.18 against what `fully_shard` and
DDP actually accept: 0 wrong moves.

Not covered: GPU / NCCL runs, an end-to-end QLoRA training run under
FSDP2, torchao versions other than 0.15 and 0.18, multi-node.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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