Skip to content

FSDP2: keep bitsandbytes 8-bit AdamW state by stepping the local shards - #15008

Merged
danielhanchen merged 11 commits into
mainfrom
dh/s4-fsdp2-8bit-optim
Oct 23, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
dh/s4-fsdp2-8bit-optim

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Native FSDP2 (UNSLOTH_FSDP2=1) used to switch adamw_8bit, adamw_bnb_8bit, paged_adamw_8bit and paged_adamw_32bit, including Unsloth's default adamw_8bit, to torch AdamW. bitsandbytes cannot step DTensor parameters, so the optimizer state became float32, or bf16 for full finetuning on bf16 weights, while single GPU and DDP keep the 8-bit state.

This keeps the bitsandbytes optimizer and steps each rank's local shard.

Design

  • The optimizer keeps the DTensor parameters in its param_groups and its state keyed by them, so the LR scheduler, gradient clipping, GradScaler, transformers' embedding override and torch.distributed.checkpoint are unchanged.
  • init_state and update_step run bitsandbytes on the shard's plain local tensor (shared storage), using the local shard of the gradient.
  • Empty shards and replicated trainable parameters are handled.
  • The min_8bit_size rule uses the full parameter size, so the same parameters get 8-bit state as on one GPU.
  • state_dict() exports the state as float32 DTensors, so the existing collective optimizer.pt save and the FSDP2 resume path work as before. load_state_dict() re-quantizes with an exact inverse of the blockwise quantization, so a resume at the same world size restores the 8-bit state bitwise.
  • Checkpoints written by the old torch AdamW switch still resume (exp_avg / exp_avg_sq are mapped).
  • UNSLOTH_FSDP2_BNB_LOCAL=0 restores the old behaviour.

Numerics

blocks are 256 elements of each local shard. When every shard starts on a 256-element boundary (checked: all LoRA r=8 / r=16 and full finetuning tensors of Qwen3-8B and Llama-3.1-8B at 2 and 8 GPUs), the update is the same as on one GPU given the same gradients. Otherwise blocks differ: a misaligned (5, 1000) tensor differed from one GPU by a relative 2e-5 after 3 steps.

Results

Tiny Qwen3, 2 GPUs (B200), bf16, 10 steps:

  • LoRA: loss, grad norm and final weights match DDP; optimizer state per rank is half of DDP's; per-parameter state dtypes match single GPU (8 uint8, 20 float32).
  • Full finetuning: loss within 2.2e-5 of single GPU.
  • Resume from the step 5 checkpoint ends on the same weights as the uninterrupted run, for adamw_8bit and paged_adamw_8bit.

Tests

tests/test_fsdp2_native_bnb_8bit_gloo.py (2 ranks, gloo, bitsandbytes CPU kernels).

  • It covers: shard stepping vs bitsandbytes on the plain shard (bitwise), the 8-bit / 32-bit choice, an empty shard, a replicated parameter, LR changes, a full-state save and load round trip (bitwise), and a Trainer run with optim = adamw_8bit plus checkpoint resume.
  • It fails on main and passes here. The existing optimizer switch test now runs with UNSLOTH_FSDP2_BNB_LOCAL=0.

Not covered: real-size models, resuming at a different world size (approximate by construction), fp16, QLoRA, CPU offload, VLMs, embedding_learning_rate groups on GPU, T4, AMD. Saving holds float32 copies of each rank's state on the GPU for the duration of the save. Accelerate's own FSDP2 backend is unchanged.

Native FSDP2 used to switch adamw_8bit, adamw_bnb_8bit, paged_adamw_8bit and
paged_adamw_32bit (and Unsloth's default adamw_8bit) to torch AdamW with fp32
state, because bitsandbytes cannot step DTensor parameters. The bitsandbytes
optimizer is now kept: its param_groups and state stay keyed by the DTensor
parameters, and init_state / update_step run bitsandbytes on each parameter's
local shard (sharing storage) with the local shard of its gradient. Empty
shards and replicated parameters are handled, the min_8bit_size rule uses the
full parameter size, and state_dict() exports float32 DTensor state so the
collective full optimizer save and resume keep working; the reload
re-quantizes exactly at the same world size. UNSLOTH_FSDP2_BNB_LOCAL=0 keeps
the old switch to torch AdamW.
…'s device

Paged bitsandbytes state lives in unified memory and reports the CPU device,
so the float32 export for the collective optimizer save mixed CPU codes with
CUDA quantization maps (paged_adamw_8bit failed at the first checkpoint).
@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-23T18:35:50.208629Z 88c31b7 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: 63deca4317

ℹ️ 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 +234 to +235
out = {"step": int(raw.get("step", 0))}
for key in _STATE_KEYS:

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 clipping state in optimizer checkpoints

When a supported bitsandbytes Adam/AdamW optimizer uses percentile_clipping < 100 or max_unorm > 0, its gnorm_vec/unorm_vec tensors affect subsequent updates, but this export retains only step, state1, and state2. Loading the checkpoint initializes those auxiliary tensors from scratch, so resumed training silently diverges from an uninterrupted run; copy these state entries through the full-state export/import path as well.

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 ccee7cf. With percentile_clipping < 100, bitsandbytes keeps gnorm_vec, the last 100 squared gradient norms of each parameter (here of this rank's shard); with max_unorm > 0 it keeps unorm_vec. state_dict() exported only step, state1 and state2, so a resume restarted the clipping history. Both vectors are now exported: for a sharded parameter each rank's vector goes into one Shard(0) DTensor of shape (world_size * n,) over the parameter's mesh, so the full checkpoint holds every rank's vector and each rank gets its own back on load; a replicated parameter exports a plain tensor; a rank with an empty shard exports zeros so the collective gather lines up. At a different world size the vectors start fresh. Which keys are exported comes from bitsandbytes' own get_config, so it is the same on every rank.

test_percentile_clipping_history_survives_resume runs 100 steps with percentile_clipping=5, saves, then compares 4 more steps against a fresh optimizer loaded from the checkpoint. On 2 GPUs with bitsandbytes 0.48.2 the resumed run now matches the uninterrupted one exactly (max diff 0.0, gnorm_vec restored bitwise); before this change the resumed weights differed by 0.011. bitsandbytes 0.50 removed percentile_clipping, so the test skips there.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

…resume

With percentile_clipping < 100 bitsandbytes keeps the last 100 squared
gradient norms per parameter (gnorm_vec) and clips at their percentile, and
max_unorm > 0 keeps unorm_vec. The float32 export kept only step / state1 /
state2, so a resume restarted that history and diverged. Each rank's vectors
(for its shard) are now exported as one Shard(0) DTensor of shape
(world * n,) over the parameter's mesh, plain for replicated parameters, and
restored on load; an empty shard exports zeros so every rank lines up. A
different world size starts the vectors fresh.
@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: ccee7cfca5

ℹ️ 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 +2746 to +2749
if _is_bnb_optimizer_class(cls) and _bnb_local_shards_available():
from .fsdp2_bnb_optim import supports_local_shards
if supports_local_shards(cls):
return # Trainer.create_optimizer builds it; the native hook makes it step local shards

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 Reject optimizer classes that cannot be localized

When optimizer_cls_and_kwargs supplies a non-Adam Optimizer2State subclass such as bitsandbytes LAMB, or an Adam class configured with block_wise=False, this class-only check returns true and bypasses the preflight refusal. After Trainer constructs the instance, _localize_bnb_optimizer() rejects it, but create_optimizer() ignores that false result, leaving the original bitsandbytes optimizer to receive DTensor parameters and fail during training. Validate the constructed instance/configuration or refuse it when localization returns false.

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 9ac6207. The class alone cannot decide localization: the optimizer name and the 8-bit layout (optim_bits, block_wise) are set in init from its kwargs. The optimizer_cls_and_kwargs preflight now builds the optimizer over one CPU placeholder parameter with the given kwargs and applies the same supports_local_shards predicate localization uses, so a non-Adam Optimizer2State such as LAMB8bit, a non-blockwise 8-bit Adam, or kwargs the class rejects are refused before sharding. The create_optimizer and create_scheduler hooks now call _refuse_bnb_optimizer_instance, so a bitsandbytes optimizer that cannot be localized raises the existing clear refusal when it is built instead of failing in the first step (the scheduler hook covers subclasses whose own create_optimizer builds it).

Tests: test_bnb_optimizer_cls_preflight_uses_the_localization_predicate (LAMB8bit and a non-blockwise AdamW8bit refused, AdamW8bit and PagedAdamW8bit accepted) and test_bnb_optimizer_that_cannot_step_shards_is_refused_when_built (2 ranks, gloo: a non-blockwise Adam through get_optimizer_cls_and_kwargs, and LAMB8bit from a subclass create_optimizer, both refused). All three fail on the previous head and pass now.

pre-commit-ci Bot and others added 2 commits October 23, 2026 18:05
… localized when built

The optimizer_cls_and_kwargs preflight checked the class only, so a non-Adam
Optimizer2State (LAMB) or a non-blockwise 8-bit Adam passed, the create
optimizer hook then silently left it unlocalized, and bitsandbytes failed
inside the first step on DTensor parameters. The preflight now builds the
optimizer over one CPU placeholder parameter with the given kwargs and asks
the same predicate localization uses, and the create_optimizer /
create_scheduler hooks raise the existing refusal when a bitsandbytes
optimizer cannot be localized.
@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: 9ac6207f6f

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

def _nearest_codes(padded, sorted_code, scale):
"""Per block: index into sorted_code of the nearest code * scale for each element, and the block's
total absolute reconstruction error."""
table = sorted_code.unsqueeze(0) * scale.unsqueeze(1) # (blocks, 256), ascending per row

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 Chunk checkpoint requantization to limit GPU memory

When resuming a full-finetuning checkpoint containing a large sharded matrix, this allocates a (ceil(N/256), 256) float table for the entire local state and _nearest_codes additionally materializes several full-size int64 index and float error tensors; _quantize_into repeats the operation for multiple scale candidates. Peak memory is therefore tens of bytes per state element, so a checkpoint that fits comfortably as 8-bit optimizer state can OOM while being loaded. Process the blocks in bounded chunks instead of requantizing a whole parameter at once.

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 2557ac6. Resume used to requantize a whole local state in one pass, building a (blocks, 256) float table plus int64 index and float error tensors per element for each candidate scale. _quantize_into now processes 16384 blocks (4M elements) per pass: only the final ragged block is zero-padded, and codes and absmax are written into the optimizer state in place. _dequantize, used for the float32 export, also fills its single output tensor chunk by chunk instead of materializing full int64 index and scale copies. Every 256-element block is independent and chunk edges fall on block boundaries, so the result is bitwise identical to a single pass.

test_chunked_requantization_is_bitwise_equal_to_one_pass checks this on a real bitsandbytes AdamW8bit state of 11 blocks with a 77-element last block, at chunk sizes of 1, 3, 4 and 10^6 blocks: values, codes and absmax match the single pass and exactly reproduce bitsandbytes' own state. On a GPU, for one 64M-element 8-bit state, the extra peak during requantization dropped from 3914 MB to 261 MB, and during dequantization from 768 MB to 336 MB (256 MB of which is the output tensor itself).

…unks

Resume requantized a whole local state in one pass, building a float table,
int64 indices and float errors per element for each of four candidate scales,
so loading a large full-finetuning checkpoint needed tens of bytes per state
element of GPU memory. Blocks are independent, so both the requantization and
the float32 export now run 16384 blocks (4M elements) at a time; the export
writes into its one output tensor. Results are bitwise identical to one pass.
For a 64M-element 8-bit state the extra peak drops from 3914 MB to 261 MB
(requantize) and from 768 MB to 336 MB (dequantize, 256 MB of it the output).
@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: 2557ac68d2

ℹ️ 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
target = _BNB_OPTIMS.get(name)
if target is None:
return False
if name in _BNB_LOCAL_SHARD_OPTIMS and _bnb_local_shards_available():

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 Fall back from bitsandbytes for CPU-offloaded shards

When UNSLOTH_FSDP2_CPU_OFFLOAD=1 or the Trainer uses a CPU mesh, this branch still keeps the bitsandbytes optimizer, even though the local parameter and gradient handed to it are CPU tensors. Supported installations may pin bitsandbytes 0.45.5, whose blockwise optimizer path explicitly requires all inputs to be on a GPU (upstream implementation), so the default adamw_8bit now fails on the first step instead of using the previous torch fallback. Retain bitsandbytes only when its optimizer can step the actual shard device, or force torch AdamW for CPU/offloaded shards.

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 88c31b7. Before switching away from torch AdamW, native FSDP2 now decides where the trainable shards live and whether this bitsandbytes can step CPU tensors. The shards are on the CPU with UNSLOTH_FSDP2_CPU_OFFLOAD=1, a CPU Trainer (use_cpu), no CUDA device, or, for an already sharded model, when a trainable parameter's local tensor is on the CPU. CPU support is decided by one cached probe step of 8-bit and 32-bit bitsandbytes AdamW on a tiny CPU parameter rather than a version table: bitsandbytes 0.45.5 fails the probe and 0.50.2 passes. When the shards are on the CPU and the probe fails, adamw_8bit and paged_adamw_8bit switch to torch AdamW with the existing message, as before, and a prebuilt bitsandbytes optimizer over CPU tensors is not localized and gets the existing refusal. test_cpu_shards_keep_the_torch_adamw_switch_when_bnb_cannot_step_cpu covers GPU shards (bitsandbytes kept), CPU shards with and without CPU support, the prebuilt refusal and the shard-location detection.

return False
if isinstance(optimizer_or_cls, type):
return True
if getattr(optimizer_or_cls, "optimizer_name", None) != "adam":

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 Reject Q-GaLore instead of localizing it as Adam

When a prebuilt QGaLoreAdamW8bit with projection parameter groups is passed for an already-sharded model, this predicate accepts it because that class subclasses Optimizer2State and sets optimizer_name = "adam". _refuse_q_galore() only checks training_args.q_galore_config, so the prebuilt-optimizer path localizes the instance and its overridden step() then performs whole-matrix projections and shape-changing parameter operations on DTensor shards, producing invalid per-shard projections or failing. Fresh evidence beyond the earlier class/config issue is the repository's own QGaLoreAdamW8bit subclass satisfying this new instance predicate; restrict localization to ordinary bitsandbytes Adam/AdamW implementations or explicitly reject projection subclasses.

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 88c31b7. Localization is now limited to bitsandbytes' own Adam classes: every class above Optimizer2State in the MRO must come from the bitsandbytes package and must not replace step, init_state or update_step (torch.optim.Optimizer.init writes a profiling wrapper of step onto the class, so that wrapper is unwrapped before the comparison). QGaLoreAdamW8bit has optimizer_name 'adam' but its own projecting step(), so it is no longer localized: a prebuilt instance gets the existing Q-GaLore refusal, and optimizer_cls_and_kwargs with it is refused by the preflight. test_q_galore_is_refused_not_localized loads the repo's unsloth/optimizers/q_galore_adamw.py and checks both refusals, and that AdamW8bit, Adam8bit, PagedAdamW8bit and PagedAdamW32bit are still localized.

pre-commit-ci Bot and others added 2 commits October 23, 2026 18:31
…s; refuse Q-GaLore

CPU-offloaded or CPU-mesh shards are CPU tensors, and bitsandbytes before 0.50
(0.45.5 probed) refuses CPU inputs in the 8-bit Adam step, so adamw_8bit kept
bitsandbytes and failed at step 1. Whether the shards live on the CPU
(UNSLOTH_FSDP2_CPU_OFFLOAD, a CPU Trainer, no CUDA, or the sharded model's
local tensors) and whether this bitsandbytes steps CPU tensors (one probe
step, cached) now decide: otherwise the switch to torch AdamW stays.

Localization is restricted to bitsandbytes' own Adam classes: every class
above Optimizer2State must come from bitsandbytes and keep its step /
init_state / update_step (torch's profiling rewrap of step is unwrapped).
Unsloth's QGaLoreAdamW8bit (optimizer_name 'adam', its own projecting step) is
refused with the Q-GaLore message instead of being localized.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 88c31b7f46

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

Repo tests (CPU, fsdp2) fails on an existing test this PR's behaviour change affects:

tests/test_fsdp2_native_optim_reentry_gloo.py:271: in test_bnb_optimizer_cls_and_kwargs_is_refused
AssertionError: (0, 'bnb.keyword', {'error': '', 'sharded': True})

That test still expects a bitsandbytes optimizer to be refused under native FSDP2, and this PR now shards it. If the new behaviour is the intent, the test needs to move to the new contract: bnb 8-bit accepted and sharded, and anything still unsupported still refused.

The Repo tests (CPU, rest) encoding failure (test_pretokenized_dataset.py:313) comes from a run that started before #15018 fixed it on main.

@danielhanchen
danielhanchen merged commit f674295 into main Oct 23, 2026
34 of 37 checks passed
@danielhanchen
danielhanchen deleted the dh/s4-fsdp2-8bit-optim branch October 23, 2026 23:32
danielhanchen added a commit that referenced this pull request Oct 24, 2026
…m / AdamW on local shards (#15049)

`Repo tests (CPU, fsdp2)` fails on `main` since #15008, for example on
#14970 and #15000:

```
tests/test_fsdp2_native_optim_reentry_gloo.py::test_bnb_optimizer_cls_and_kwargs_is_refused
AssertionError: (0, 'bnb.keyword', {'error': '', 'sharded': True})
```

## Cause

#15008 made native FSDP2 keep a bitsandbytes Adam / AdamW and step each
rank's local shard. `_refuse_bnb_optimizer_cls` now lets
`optimizer_cls_and_kwargs = (bnb.optim.AdamW8bit, ...)` through whenever
this bitsandbytes can step local shards, and refuses it otherwise
(`UNSLOTH_FSDP2_BNB_LOCAL=0`). The test still expected every
bitsandbytes class to be refused. The product change is intended, as the
#15008 description says, so the test was out of date.

## Fix

The worker now also reports `native._bnb_local_shards_available()`, and
the test asserts each arm against it:
- `torch.*`: accepted and sharded.
- `bnb.*`: accepted and sharded when local shards are available,
otherwise refused with the bitsandbytes `ValueError`.
- `like.*` (`AdamW8bitLike`, a torch AdamW that only claims the
bitsandbytes module): always refused, since it cannot step local shards.

## Verification

The whole file gives 5 passed. Both `bnb` branches run:

| `UNSLOTH_FSDP2_BNB_LOCAL` | bnb local | `bnb.*` | `like.*` | `torch.*`
|
|---|---|---|---|---|
| 1 (default) | True | accepted, sharded | refused | accepted, sharded |
| 0 | False | refused | refused | accepted, sharded |

Sabotage check: making `_refuse_bnb_optimizer_cls` return early fails
the test.
danielhanchen added a commit that referenced this pull request Oct 26, 2026
…in the optimizer save (#15384)

Since #15008, native FSDP2 (`UNSLOTH_FSDP2=1`) keeps bitsandbytes for
`adamw_8bit` and steps each rank's local shard. That optimizer inherits
bitsandbytes' `Optimizer8bit.step`, which calls `sync_gpu(p)`, i.e.
`torch.cuda.synchronize()`, after every parameter. Before #15008 this
path used `adamw_torch_fused`, which does not synchronize at all. With a
few hundred LoRA tensors, the host now waits for the device once per
tensor on every step.

The same optimizer's checkpoint export also has a memory problem.
`native_save_optimizer` calls `get_optimizer_state_dict(full_state_dict
= True, cpu_offload = True)`. torch calls `optimizer.state_dict()` first
and only gathers and offloads afterwards, and the local-shard optimizer
exports float32 moments. So every moment of every parameter, 8 bytes per
element against the 2 bytes of the 8-bit state, sat on the GPU until the
whole state dict existed.

This PR fixes both, in two commits.

## Change

Step (first commit):

- `_LocalShardMixin.step` runs the same loop as bitsandbytes (closure,
`check_overrides` / `to_gpu` on the first step, `init_state`,
`prefetch_state`, `update_step`) without the per-parameter synchronize
for non-paged optimizers. Their state is on the device and every update
is queued on the current stream, so the host does not need to wait.
- Paged optimizers (`paged_adamw_8bit`, `paged_adamw_32bit`) keep
bitsandbytes' fences: one after every parameter plus the final one, as
before.
- The new `step` is wrapped with
`torch.optim.Optimizer.profile_hook_step`, so step pre / post hooks and
the profiler label run exactly once per step.
- Plain bitsandbytes outside native FSDP2 (single GPU, DDP) is not
touched.

Save (second commit):

- `native_save_optimizer` enters `full_cpu_state_export(optimizer)`
around `get_optimizer_state_dict` when it asks for the full,
CPU-offloaded state (writer rank 0, the default Trainer `optimizer.pt`
save).
- Inside it, the local-shard optimizer's `state_dict()` gathers each
parameter's exported state and moves it to the CPU right away, the same
way torch's `_gather_state_dict` does (redistribute to `Replicate`,
`to_local`, copy to the CPU on rank 0, nothing kept on other ranks). The
tensors equal torch's own export, so the saved file and resume are
unchanged.
- Other optimizers, the sharded DCP save (`UNSLOTH_FSDP2_DCP_OPTIM=1`)
and the sub-mesh writer path are unchanged.

## Measurements

### Step

Optimizer step only, Llama-3.1-8B LoRA r=16 on q, k, v, o, gate, up,
down: 448 fp32 tensors, 41.9M parameters, one-rank DTensor mesh.
bitsandbytes 0.50.2. 9 interleaved rounds of 20 steps per arm, median
per step with the min and max round. `main (A/A)` is a second,
independent optimizer on main, to show run-to-run noise.

L4, torch 2.14.1:

| Arm | syncs / step | median ms | min to max ms |
|---|---|---|---|
| torch fused AdamW (native FSDP2 before #15008) | 0 | 10.46 | 10.30 to
10.63 |
| bitsandbytes AdamW8bit, plain tensors (no FSDP) | 448 | 36.80 | 36.47
to 37.24 |
| local-shard AdamW8bit, main | 448 | 49.17 | 48.72 to 49.38 |
| local-shard AdamW8bit, main (A/A) | 448 | 48.97 | 48.38 to 49.22 |
| local-shard AdamW8bit, this PR | 0 | 35.16 | 34.96 to 35.58 |

B200, torch 2.13.0 (two separate runs):

| Arm | run 1 median ms | run 2 median ms |
|---|---|---|
| torch fused AdamW | 12.22 | 6.17 |
| bitsandbytes plain | 33.07 | 18.44 |
| local-shard main | 44.21 | 24.26 |
| local-shard main (A/A) | 44.96 | 25.31 |
| local-shard, this PR | 33.47 | 18.30 |

The A/A gap is 0.4% on L4 and under 5% on B200; the change is 28% on L4
(14.0 ms per step) and 24% to 25% on B200. Parameters after the same
steps are bitwise equal to main (max abs difference 0.0 on both GPUs).
This is the optimizer step alone; a full training step was not timed, so
the end-to-end share depends on how long the forward and backward take.

The local-shard optimizer is still slower than fused torch AdamW. The
rest of the gap is the per-tensor Python and DTensor overhead, which
this PR does not change.

### Save

`native_save_optimizer` on one NCCL rank, 16 DTensor parameters of 1M
elements (16.8M elements), after two steps. Peak and retained GPU memory
are measured above the allocation before the save.

| Arm | allocated before the save | save peak above it | retained after
|
|---|---|---|---|
| torch fused AdamW (native FSDP2 before #15008) | 192.0 MiB | 0 MiB | 0
MiB |
| local-shard AdamW8bit, main | 96.5 MiB | 144.0 MiB | 0 MiB |
| local-shard AdamW8bit, this PR | 96.5 MiB | 32.0 MiB | 0 MiB |

On main the save peak (240.5 MiB in total) was above even the torch
AdamW run (192.0 MiB). With this PR it is 128.5 MiB and no longer grows
with the number of parameters: it is about one parameter's export. On
both, the exported tensors equal torch's own `get_optimizer_state_dict`
output, and a resume into a fresh optimizer restores `state1`, `state2`,
`absmax1` and `absmax2` bitwise.

## Tests

`tests/test_fsdp2_bnb_optim_sync.py` (CPU, bitsandbytes' CPU kernels,
`sync_gpu` counted):

- `test_local_shard_step_does_not_sync_per_parameter[AdamW8bit]`,
`[Adam8bit]`, `[AdamW]`: no sync during a step, same parameters as
bitsandbytes' own step, step post hook called once per step. Fail on
main (4 syncs for 4 parameters), pass here.
- `test_paged_local_shard_step_keeps_bitsandbytes_fences`:
`PagedAdamW8bit` makes the same number of fences as bitsandbytes
(parameters + 1), with equal parameters. Passes on both.


`tests/test_fsdp2_bnb_optim_save_memory_cuda.py::test_local_shard_bnb_save_keeps_one_parameter_on_the_gpu`
(one NCCL rank, skipped without CUDA): the save peak stays within 5
parameters' float32 moments, nothing is retained on the GPU, the state
equals torch's export and resumes bitwise. Fails on main (144 MiB peak),
passes here.

`tests/test_fsdp2_native_bnb_8bit_gloo.py`,
`tests/test_fsdp2_native_dcp_bnb_8bit_gloo.py`,
`tests/test_fsdp2_native_trainer_ckpt_gloo.py` and
`tests/test_fsdp2_save_gloo.py` still pass. The two-rank Trainer
`adamw_8bit` save and resume test now goes through the new export. All
together: 57 passed, 3 skipped (no `percentile_clipping` in this
bitsandbytes; two-GPU NCCL; the CUDA test on a CPU run).

Not covered: multi-rank GPU training end to end, XPU, ROCm, bitsandbytes
0.45.5 (the floor; the loop only calls methods that exist there, and
`sync_gpu` falls back to `torch.cuda.synchronize` when the import
fails), paged optimizers on a real GPU, a two-rank NCCL save, and the
save memory of the sharded DCP path, which still exports every float32
moment on the GPU.

---------

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