Skip to content

fast_inference under UNSLOTH_FSDP2=1 torchrun: keep vLLM instead of refusing it - #15709

Merged
danielhanchen merged 8 commits into
mainfrom
dh/nb-dist-vllm-fsdp2
Oct 28, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
dh/nb-dist-vllm-fsdp2

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Needs unslothai/unsloth-zoo#2180 (vLLM under native FSDP2: gather the sharded adapters for save_lora and load_lora). Without it this change keeps the refusal, and the message says to update unsloth_zoo.

Problem

UNSLOTH_FSDP2=1 torchrun --nproc-per-node 2 "Qwen2.5_(3B)-GRPO.py" is refused at from_pretrained with NotImplementedError: fast_inference = True (vLLM) is not supported with FSDP2 (loader_utils.raise_if_fast_inference_under_fsdp2, unsloth#3551). That refusal covers the 13 unique notebook scripts (50 files) that set fast_inference = True.

Unsloth's native FSDP2 already has almost everything vLLM needs:

  • unsloth-zoo#2093 builds one vLLM engine per torchrun rank (external_launcher).
  • unsloth-zoo#2144 gives the job group a CPU backend, so the fast_inference gate works on CUDA.
  • Native FSDP2 keeps the frozen base weights replicated when the model fits, so the HF model's frozen weights are still the engine's. Only the LoRA adapters become DTensor shards, and the zoo PR gathers those for vLLM and save_lora.

There is one gap, for 16-bit LoRA. Advanced_Llama3_2_(3B)_GRPO_LoRA (Llama 3.2 3B, 16-bit) does not pass the planner's fit rule on a 15 GB T4 (the model is more than 0.4 of the card). So the sharded layout also shards the frozen weights. fully_shard copies each of them into a new padded shard (_init_sharded_param, new_zeros), but the vLLM engine still holds the original storage: Unsloth's fast_inference load builds the HF weights as views of the engine's (llm.shared_weights). Every rank then pays half of the frozen model on top of DDP's footprint, and runs out of memory inside fully_shard.

Change

  • raise_if_fast_inference_under_fsdp2 lets native FSDP2 (unsloth_fsdp2_native_requested()) keep vLLM when unsloth_zoo has _lora_state_dict.
    • accelerate's FSDP2 (FSDP_VERSION=2, UNSLOTH_FSDP2_BACKEND=accelerate, an Accelerator FSDP2 plugin) keeps the refusal. So does an older unsloth_zoo.
    • The message names both cases and the native launch.
  • shard_model keeps the frozen weights replicated when they are a vLLM engine's storage (_frozen_weights_are_vllm_engine_storage: a vllm_engine with shared_weights on the model, the PeftModel or the inner model). Only the adapters are sharded, as in the fit layout.
    • An explicit shard_frozen or UNSLOTH_FSDP2_REPLICATE_FROZEN still wins.
    • On torch without fully_shard(ignored_params) (2.6) nothing changes. vLLM needs a newer torch anyway.
    • It prints one line saying why.

Tests

test main this branch
test_fast_inference_refuses_fsdp2.py::test_native_fsdp2_keeps_vllm_when_zoo_gathers_the_adapters[True/False]: native FSDP2 with a gathering zoo is not refused; without it the refusal names the zoo update; UNSLOTH_FSDP2_BACKEND=accelerate is refused 2 failed passed
new test_fsdp2_native_vllm_shared_frozen_gloo.py (2 gloo ranks, PEFT LoRA, CPU mesh, so the planner picks the sharded layout) n/a passed

Cases in the new test:

  • With an engine (shared_weights = True) on the PeftModel or on the inner model: replicate_frozen is True. All 21 frozen weights stay plain tensors on the same storage, and every trainable weight is a DTensor.
  • No engine, an engine without shared_weights, or UNSLOTH_FSDP2_REPLICATE_FROZEN=0: the frozen weights are sharded, as before.

Neighbour suites (torch 2.13, CPU gloo): test_fsdp2_native_vllm_shared_frozen_gloo, test_fsdp2_perf_layout_gloo, test_fsdp2_native_layout_cpu_split_gloo, test_fsdp2_native_layout_agree_gloo, test_fsdp2_native_units, test_fast_inference_refuses_fsdp2, test_fast_inference_torchrun_agreement, test_grpo_move_model_to_vllm_sync and test_async_grpo_fast_inference: 142 passed, 1 skipped (the CUDA-only probe). After merging the latest main: 58 passed, 1 skipped on the FSDP2 layout and fast_inference subset. On torch 2.6 the new test skips (no ignored_params).

Kaggle T4x2

The unmodified notebook scripts, max_steps = 3, 300-row slice, vllm 0.11.2, torch 2.9.0, transformers 4.57.6, TRL 0.22.2. Every arm ran in one kernel.

  • Base = unsloth main 4611107.
  • Head = this branch plus the unsloth-zoo PR.
  • The base arm uses the head zoo. main refuses before the zoo is reached.
script launch main this branch
Qwen2.5_(3B)-GRPO (4-bit) UNSLOTH_FSDP2=1 torchrun --nproc-per-node 2 refused at from_pretrained: fast_inference = True (vLLM) is not supported with FSDP2 PASS, rank 0 losses 0.0004 / 0.0203 / 0.0 (see below)
Qwen2.5_(3B)-GRPO (4-bit) one GPU PASS, losses 0.0008 / 0.0 / 0.0
Advanced_Llama3_2_(3B)_GRPO_LoRA (16-bit) UNSLOTH_FSDP2=1 torchrun ... refused (same) PASS, losses 0.0414 / 0.0135 / 0.0151 (see below)
Advanced_Llama3_2_(3B)_GRPO_LoRA (16-bit) UNSLOTH_FSDP2=1 UNSLOTH_FSDP2_REPLICATE_FROZEN=0 torchrun ... (the old sharded layout) OOM inside fully_shard (_init_sharded_param new_zeros)
Advanced_Llama3_2_(3B)_GRPO_LoRA (16-bit) torchrun ... (DDP) PASS, losses 0.0414 / 0.0135 / -0.0599

Notes on the PASS arms:

  • Qwen2.5 under FSDP2: the log shows "native FSDP2 sharded (the model fits one GPU) ... frozen weights replicated". save_lora("grpo_saved_lora") wrote 239,542,873 bytes, equal to the one-GPU run. The script's final fast_generate with load_lora("grpo_saved_lora") produced text. The losses equal an earlier DDP run of the same script (0.0004 / 0.0203 / -0.0).
  • Advanced_Llama3_2 under FSDP2: the log shows "keeps the frozen weights replicated: they are the vLLM engine's weights" and "merged-weight vLLM rollouts are off under native FSDP2 (sharded adapters)". save_lora wrote 194,569,956 bytes, equal to DDP, and the final load_lora generation ran. Steps 1 and 2 equal DDP in the same kernel. Step 3 differs, which is within GRPO sampling noise: an earlier DDP run of the same script logged 0.3406 / -0.0501 at steps 1-2.

Memory per rank on the 16-bit script (vLLM at gpu_memory_utilization 0.76, rank 0 / rank 1):

layout torch max allocated GPU used (NVML peak) result
DDP 12,283 / 12,270 MiB 13,511 / 13,341 MiB PASS
FSDP2, frozen replicated (this branch) 12,511 / 12,485 MiB 13,653 / 13,505 MiB PASS
FSDP2, frozen sharded (UNSLOTH_FSDP2_REPLICATE_FROZEN=0, the previous layout) 13,313 / 13,444 MiB when it failed (13.81 GiB allocated, 14.40 GiB in use, 12.81 MiB free) 14,899 / 14,887 MiB OOM in fully_shard

The sharded layout was already 0.8-1.0 GiB above the replicated one, still part-way through allocating the shards, when the card ran out. The replicated layout sits 228 / 215 MiB above DDP: that is the sharded adapters plus the FSDP2 state.

Not covered

  • vLLM under FSDP2 x TP: tensor parallel still refuses vLLM.
  • 4 or more ranks, and models that do not fit one GPU even as DDP. Replicating the frozen weights keeps DDP's per-rank footprint for them, so FSDP2 + vLLM does not let a bigger model fit; it only stops costing more than DDP.
  • Merged-weight rollouts under FSDP2. They are declined, and vLLM LoRA serves the gathered adapters instead.
  • Loss equality to one GPU is not claimed: GRPO with vLLM sampling varies run to run (see above), and no repeated-run spread was measured.

Known cost

Under native FSDP2 the LoRA adapter is not folded into the vLLM weights (the frozen weights stay shared with the engine), so rollouts go through vLLM's LoRA kernels. In a T4 probe that decoded about 43% slower than the merged path DDP uses (860 vs 1510 tokens/s). No existing setup loses speed, since main refuses fast_inference under native FSDP2. Every rank must call save_lora / load_lora under native FSDP2 (a rank 0 only call waits in the gather); a one-time notice says so.

…efusing it

Unsloth's native FSDP2 keeps frozen base weights replicated, so they stay
the vLLM engine's, and unsloth_zoo now gathers the sharded adapters for
save_lora / load_lora. Only accelerate's FSDP2 (or an unsloth_zoo without
the gather) keeps the refusal.
…dict

The zoo side now gathers the adapters in _lora_state_dict (taken outside
inference mode), so the capability check looks for that name.
… they are vLLM's

Unsloth's vLLM load builds the HF weights as views of the engine's own
weights (llm.shared_weights), and the engine keeps that storage alive. When
the planner's fit rule says the model does not fit (a 16-bit 3B model on a
15 GB T4), the sharded layout sharded the frozen weights too: fully_shard
copies each into a new padded shard while vLLM still holds the original, so
every rank paid half the model on top of DDP's footprint, and
Advanced_Llama3_2_(3B)_GRPO_LoRA ran out of memory inside fully_shard.

Keep such frozen weights replicated (the same tensors, as under DDP) and
shard only the adapters. An explicit UNSLOTH_FSDP2_REPLICATE_FROZEN or
shard_frozen still wins.
…eters out

torch < 2.7 has no fully_shard(ignored_params), so replicated frozen weights
would be refused there; keep the sharded layout on it (vLLM itself needs a
newer torch).
@danielhanchen danielhanchen self-assigned this Oct 28, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 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-28T07:36:19.617057Z e5079ec 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: e5079ec924

ℹ️ 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 a27be31 into main Oct 28, 2026
@danielhanchen
danielhanchen deleted the dh/nb-dist-vllm-fsdp2 branch October 28, 2026 09:38
danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Oct 28, 2026
…d load_lora (#2180)

Pairs with unslothai/unsloth#15709, which lets fast_inference keep vLLM
under UNSLOTH_FSDP2=1 torchrun instead of refusing it. That PR lifts the
refusal only when this unsloth_zoo change is present.

## Problem

Under Unsloth's native FSDP2 (`UNSLOTH_FSDP2=1 torchrun`),
`model.state_dict()` returns DTensor shards for every `lora_A` /
`lora_B`:
- `save_lora` runs under `torch.inference_mode`. There an FSDP2 model's
`state_dict()` fails with `RuntimeError: Cannot set version_counter for
inference tensor`. Reproduced on CPU gloo: `state_dict()` inside
inference mode fails, while `full_tensor()` on a state dict taken
outside it works.
- `load_lora(..., load_tensors = True)` (every GRPO rollout) takes the
same state dict under the same decorator, and would hand vLLM shards.
- The merged-weight rollout (on by default for 16-bit LoRA) folds each
rank's whole delta into the engine weights, so it needs whole adapters.

## Change

- `_lora_state_dict(model)` returns the `lora_A` / `lora_B` entries
whole.
- When the adapters are sharded, it takes the state dict outside
inference mode and gathers each DTensor (`full_tensor()`). That is a
collective. Every rank enters it in state dict order, because every rank
calls `save_lora` / `load_lora` (the scripts and the GRPO trainer do).
  - Otherwise it is the previous filter, unchanged.
- `save_lora` (keeps its `@torch.inference_mode`) and
`_build_lora_request(load_tensors = True)` use it.
- `prepare_merged_rollout` declines sharded adapters, with a one-line
message when the engine was wrapped for merged rollouts. vLLM LoRA then
serves the gathered adapters.
- `_lora_is_sharded` caches only True. The Trainer shards a model after
it loads, so an early False must not stick.

## Tests

New `tests/test_vllm_fsdp2_lora_gather.py`: 2 torchrun ranks on CPU,
`fully_shard` on a gloo mesh, no vLLM engine. It checks that:
- `save_lora` writes plain whole tensors equal to the unsharded model;
- `_lora_state_dict` under `torch.inference_mode` (as `load_lora` calls
it) returns the whole adapters;
- `_lora_is_sharded` is False before sharding and True after;
- merged rollouts decline.

| | main bd307e9 | this branch |
|---|---|---|
| `test_vllm_fsdp2_lora_gather.py` | FAIL: `save_error: RuntimeError:
Cannot set version_counter for inference tensor` | PASS (torch 2.13, and
torch 2.6 with transformers 4.57.6) |

Neighbour suites on the branch (torch 2.13): `test_merged_rollout`,
`test_merged_rollout_auto_gate`, `test_merged_rollout_exact`,
`test_vllm_torchrun_collective_decisions`,
`test_vllm_torchrun_cpu_collective`,
`test_vllm_torchrun_external_launcher`,
`test_vllm_lora_unstacked_mapper` and
`test_vllm_lora_dtype_alias_guard`, with the new test: 197 passed, 41
skipped (vLLM / CUDA only).

## Kaggle T4x2

Unmodified notebook scripts under `UNSLOTH_FSDP2=1 torchrun
--nproc-per-node 2`, vllm 0.11.2, torch 2.9.0, with this branch and the
unsloth PR:
- `Qwen2.5_(3B)-GRPO` (4-bit): PASS. `save_lora` wrote 239,542,873
bytes, equal to one GPU, and the final `fast_generate` with
`load_lora("grpo_saved_lora")` produced text. Every rollout went through
`load_lora(load_tensors = True)`.
- `Advanced_Llama3_2_(3B)_GRPO_LoRA` (16-bit): PASS. "merged-weight vLLM
rollouts are off under native FSDP2" was printed, and `save_lora` wrote
194,569,956 bytes, equal to DDP.

Without the unsloth PR both scripts are refused at load, so this change
alters nothing for them there. Without FSDP2, `_lora_state_dict` is the
previous filter: the Qwen one-GPU and Llama DDP arms in the same kernel
passed.

## Not covered

- Gathering adapters for merged-weight rollouts. They are declined under
FSDP2; a per-layer gather would be needed.
- 4 or more ranks.
danielhanchen added a commit that referenced this pull request Oct 28, 2026
`Repo tests (CPU, fsdp2)` on #15833's staging run passed every test and
still went red:

```
364 passed, 28 skipped, 80 warnings in 2092.29s (0:34:52)
##[error]Process completed with exit code 124.
```

The shard's pytest step runs under `timeout --signal=INT --kill-after=60
2100`. pytest finished 8 s under that cap, and the cap then fired while
it was exiting.

## Cause

#15291 moved the FSDP2 gloo tests into their own shard at about ten
minutes of runner time. They have grown since, with most of a dozen
FSDP2 PRs merged today adding tests there (#15756, #15748, #15720,
#15709, #15708, #15352, ...). Over the last twenty-odd staging runs this
job took 21 to 38 minutes, so it now sits at its cap on an ordinary
runner. Nothing failed; the shard is simply too big for its timeout.

## Fix

Split the shard in two by file name, balanced on measured time. Per-test
durations on main, summed per file across all 76 files:

| shard | selection | files | tests | measured time |
|---|---|---|---|---|
| `fsdp2` | `tests/test_fsdp2_[!n]*.py tests/test_fsdp2_n[!a]*.py
tests/test_fsdp2_native_[abc]*.py` | 34 | 237 | 1156 s (45%) |
| `fsdp2-native` (new) | `tests/test_fsdp2_native_[!abc]*.py` | 42 | 276
| 1406 s (55%) |
| both together, unchanged total | `tests/test_fsdp2*.py` | 76 | 513 |
2562 s |

`fsdp2` keeps its name, so its check name is unchanged. The step timeout
and job cap are left alone, so each half gets the whole budget.

## Guards

- `tests/test_ci_repo_cpu_shards.py` already fails when a file lands in
no shard or in two. It caught my first draft, which dropped
`test_fsdp2_non_cuda_accelerate_route.py`; hence the `n[!a]` glob.
- A new check, `TestEveryGlobRootMatchesAFile`, fails if a shard glob
matches no test file. bash passes an unmatched glob through literally
and pytest then fails the whole shard on a missing path. Sabotage:
adding `tests/test_fsdp2_zz*.py` to a selection fails it with
`[('fsdp2', 'tests/test_fsdp2_zz*.py')]`.
- `tests/studio/test_backend_ci_parallel_isolation.py` pins the number
of parallel runs, now nine (six repo-root shards).

## Verification

- `tests/test_ci_repo_cpu_shards.py` and
`tests/studio/test_backend_ci_parallel_isolation.py`: 56 passed.
- With `tests/studio/test_cache_budget_discipline.py` added: everything
passes except the guard on my first draft, fixed above.
- `--collect-only` on the two selections gives 237 + 276 = 513, the same
as the old single glob.

The per-file times are from a local `-n 8` run, so the split ratio is
approximate. The first runs of the two new shards will show the actual
runner times.
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