Skip to content

FSDP2: lower the sharding-time memory peak (gather replicated tables without the chunk, expandable segments on every rank) - #18287

Merged
danielhanchen merged 4 commits into
mainfrom
fsdp2-load-peak
Nov 18, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
fsdp2-load-peak

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

With native FSDP2, Trainer.__init__ (the sharding step) was the highest GPU memory point of the whole run on Kaggle 2x T4. The model was unsloth/Qwen3.8-27B-unsloth-bnb-4bit (QLoRA, sharded loading). Sharding peaked at 13.22 / 13.90 GiB reserved per rank on a 14.56 GiB T4. There are two causes, fixed in two commits.

  1. The table chunk stayed on the GPU during its gather. shard_model keeps the frozen, untied lm_head whole on every rank (gpt-oss on multiple GPUs: FSDP2 keeps frozen untied IO tables out of the root unit, PP trains MoE models with the router aux loss off #18165) and builds it by all-gathering the chunk each rank loaded. That chunk stayed on the GPU for the whole gather, next to the full table, so sharding briefly needed chunk + full table + gather slices on top of the loaded model.
  2. Ranks above 0 ran without expandable_segments. bind_local_cuda_device calls torch.cuda.set_device(LOCAL_RANK) at import unsloth on every rank above 0. That starts CUDA and fixes the caching allocator settings before unsloth_zoo exports its default PYTORCH_ALLOC_CONF=expandable_segments:True. Rank 0 does not bind, so only rank 0 got expandable segments.
    • On the 27B, rank 1 ended sharding with 511 allocator segments against rank 0's 5.
    • Two freed 1.2 GiB table chunks stayed reserved, each pinned by a 1.5 MiB block in its tail.
    • Rank 1 reserved 2.2 GiB more than rank 0 after sharding and about 0.9 GiB more in training.

Changes

unsloth/models/fsdp2_load.py:

  • gather_replicated hands each chunk over to _full_from_chunks as the only reference to it.
  • A chunk of at least one gather slice (64 MiB) on an accelerator is copied to host memory, and its GPU block is released before the full table is allocated. The slices are then fed from the host copy.
  • Each slice's buffers are dropped before the next slice is allocated.
  • A chunk that another pending entry still names (a shared parameter) is gathered as before.
  • The gathered bytes are identical.

unsloth/_gpu_init.py, unsloth/parallel_env.py:

  • The allocator variables are recorded before import unsloth_zoo.
  • If the import changed them after CUDA had already started, the new settings are applied with torch.cuda.memory._set_allocator_settings (torch 2.1+).
  • If CUDA has not started yet, torch reads the environment itself, so single-process runs and rank 0 behave as before.

Kaggle 2x T4: Qwen3.8-27B bnb-4bit, FSDP2, sharded load

Setup: LoRA r 8, 1,024-token rows, GA 2, 3 steps, adamw_8bit, fp16. All arms ran in one kernel on unsloth 31b5c7a with zoo main 5baf98d. Numbers are GiB per rank, as peak reserved / peak allocated.

phase main, rank 0 main, rank 1 this PR, rank 0 this PR, rank 1
from_pretrained 10.67 / 10.64 10.92 / 10.81 10.67 / 10.64 10.67 / 10.64
get_peft_model 10.85 / 10.80 11.09 / 10.97 10.85 / 10.80 10.85 / 10.80
Trainer init (sharding) 13.22 / 12.36 13.90 / 12.53 11.16 / 11.11 11.16 / 11.11
3 training steps 12.75-12.82 / 12.06 13.75 / 12.23 12.82 / 12.06 12.82 / 12.06
  • Peak. The run-wide peak falls from 13.90 GiB (rank 1, sharding) to 12.82 GiB (training). Sharding is no longer the highest point.
  • Repeats. Main was run 3 times (2 in an earlier kernel) and this PR twice. Sharding peaks were identical to 3 decimals within each arm. Rank 0's training peak varies between 12.75 and 12.82 on main alone.
  • Losses. Steps 1 and 2 match bit for bit in every arm (2.246492, 2.280375). Step 3 varies run to run on main itself (2.178731, 2.178771, 2.178793), and this PR's runs (2.178710, 2.178716) are within 1e-4 of those.
  • Host RAM. During sharding the host peak rises by about 1.2 GiB per rank (3.74 to 4.9 GiB private), while the chunk waits in host memory. The training host peak is unchanged (4.1 to 4.5 GiB).

Correctness on B200 (relative memory, not a T4 measurement)

  • Model. A cut-down Qwen3.8-27B: the real config with real widths, vocab 248,320 and untied 2.37 GiB tables, but 4 text layers and 2 vision blocks. Random weights, quantized to bnb-4bit with the real checkpoint's skip list.
  • Setup. 2 ranks on one B200 with gloo carrying CUDA tensors. The T4 is emulated: total_memory / mem_get_info report 14.56 GiB, fp16 weights, fp16 AMP. UNSLOTH_FSDP2_SHARDED_LOAD=1, UNSLOTH_FSDP2_LAYOUT=sharded.
  • Scope. Both ranks use LOCAL_RANK 0 here, so this run covers the first commit only.
  • Result. Sharding peak drops from 5.375 / 4.61-4.63 to 3.34-3.42 / 3.256 GiB. Training peak is unchanged at 4.455 reserved.
  • Bitwise checks. Losses, grad norms and per-rank LoRA weight checksums are bitwise equal to main, in two runs per arm.

Tests

  • tests/test_fsdp2_sharded_gather_peak.py (CUDA, about 2 s):
    • The chunk must leave the GPU before the full table is allocated. Main fails it with 288 MiB over the start against a 64 MiB limit.
    • A shared chunk is gathered once and bit-exact.
    • A gather to host frees the GPU chunk.
  • tests/test_parallel_env_allocator.py:
    • CPU unit tests for the late allocator settings: torch 2.10+ and older variable names, the standby case that turns expandable segments off, and the not-started case.
    • A CUDA test that starts CUDA before import unsloth, as a rank above 0 does, and checks the new segments are expandable. Main fails it: PYTORCH_ALLOC_CONF=expandable_segments:True is set, but the segments are not expandable.
  • Flip results on B200: main fails 2 and passes 2 of the CUDA tests; this PR passes all 4. The CPU unit tests pass: 5 passed, 1 skipped (the CUDA test).
  • Existing CPU suites, with the same results on main:
    • test_fsdp2_native_io_tables_gloo, test_fsdp2_native_sharded_load_gloo, test_sharded_load_bnb4_gloo, test_fsdp2_native_trainer_init_any_loader_gloo and test_sharded_load_host_tables: 68 passed, 2 failed. The two failures are test_sharded_loading_matches_full_load_shard_model[qwen2_5_vl-None-lora-False] and [llama-overrides9-lora-remap], which fail on main too.
    • test_parallel_env: 138 passed. test_bind_local_cuda_device: passes.

Not covered

  • Real multi-GPU runs other than Kaggle 2x T4 NCCL: no AMD, Windows, or more than 2 GPUs.
  • TP, PP and DDP on real GPUs. The second change also gives their ranks above 0 the allocator settings rank 0 already had. Their memory was not re-measured.
  • A fit-layout sharded load. Every frozen chunk of at least 64 MiB now takes the host round trip there, and load time was not measured for that combination.

… GPU before gathering the whole table

shard_model gathers the frozen lm_head (kept whole on every rank) from the chunk sharded loading left on
this rank. The chunk stayed on the GPU for the whole gather, next to the full table, and its freed block
stayed cached, so the sharding peak was chunk + full table + slices above the loaded model (Qwen3.8-27B
bnb-4bit on 2x T4: 13.9 GiB reserved of 14.56).

gather_replicated now hands the chunk over: one at least a gather slice in size goes to host memory and
its GPU block is released before the full table is allocated, and each slice's buffers are dropped before
the next. The gathered bytes are unchanged. A shared parameter's chunk (named by another pending entry)
is gathered as before.
…ing the CUDA device

bind_local_cuda_device calls torch.cuda.set_device(LOCAL_RANK) at import on ranks > 0. That starts CUDA and
fixes the caching allocator's settings before unsloth_zoo exports its default (PYTORCH_ALLOC_CONF =
expandable_segments:True), so every rank but rank 0 trained without expandable segments. On 2x T4 with
Qwen3.8-27B bnb-4bit FSDP2, rank 1 ended sharding with 511 allocator segments and 2.2 GiB more reserved than
rank 0 (13.46 vs 11.16 GiB), two 1.2 GiB freed table chunks pinned by 1.5 MiB blocks in their tails.

_gpu_init now records the allocator variables before importing unsloth_zoo and, when the import changed them
after CUDA had already started, applies the new settings with torch.cuda.memory._set_allocator_settings (torch
2.1+). With CUDA not yet started torch reads the environment itself, unchanged.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-18T12:21:47.628096Z 55c648d 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 9ad927542c

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

…ion warning

torch 2.10+ reads PYTORCH_CUDA_ALLOC_CONF, then PYTORCH_HIP_ALLOC_CONF, then
PYTORCH_ALLOC_CONF (c10/core/AllocatorConfig.cpp), and ROCm builds before
2.10 fall back to the HIP name only when the CUDA one is unset. The settings
a rank started CUDA with are now read in that order, so a legacy
expandable_segments:True that zoo dropped is turned off as on rank 0.

torch 2.10+ also marks torch.cuda.memory._set_allocator_settings deprecated
with a FutureWarning: every rank above 0 printed it at import, and with
warnings as errors the settings were silently not applied. The warning is
now suppressed around the call; the function is still an alias of the
accelerator setter.
unsloth_zoo exports its allocator settings before its own import starts
CUDA, so torch.cuda.is_initialized() is True after `import unsloth_zoo` in
every process. The late apply therefore ran on every single-GPU run and on
rank 0 too (re-applying what torch had already read, and on torch 2.10+
printing the deprecation warning). It now runs only when CUDA had started
before the zoo import, as on a torchrun rank above 0 that bound its device.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 55c648d47b

ℹ️ 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 4071f40 into main Nov 18, 2026
@danielhanchen
danielhanchen deleted the fsdp2-load-peak branch November 18, 2026 15:50
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