Repository navigation
fast_inference under UNSLOTH_FSDP2=1 torchrun: keep vLLM instead of refusing it - #15709
Merged
Merged
Conversation
…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).
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Member
Author
|
@codex review |
1 similar comment
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
[skip ci]
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 atfrom_pretrainedwithNotImplementedError: 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 setfast_inference = True.Unsloth's native FSDP2 already has almost everything vLLM needs:
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_shardcopies 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 insidefully_shard.Change
raise_if_fast_inference_under_fsdp2lets native FSDP2 (unsloth_fsdp2_native_requested()) keep vLLM when unsloth_zoo has_lora_state_dict.FSDP_VERSION=2,UNSLOTH_FSDP2_BACKEND=accelerate, an Accelerator FSDP2 plugin) keeps the refusal. So does an older unsloth_zoo.shard_modelkeeps the frozen weights replicated when they are a vLLM engine's storage (_frozen_weights_are_vllm_engine_storage: avllm_enginewithshared_weightson the model, the PeftModel or the inner model). Only the adapters are sharded, as in the fit layout.shard_frozenorUNSLOTH_FSDP2_REPLICATE_FROZENstill wins.fully_shard(ignored_params)(2.6) nothing changes. vLLM needs a newer torch anyway.Tests
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=accelerateis refusedtest_fsdp2_native_vllm_shared_frozen_gloo.py(2 gloo ranks, PEFT LoRA, CPU mesh, so the planner picks the sharded layout)Cases in the new test:
shared_weights = True) on the PeftModel or on the inner model:replicate_frozenis True. All 21 frozen weights stay plain tensors on the same storage, and every trainable weight is a DTensor.shared_weights, orUNSLOTH_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_syncandtest_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 (noignored_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.UNSLOTH_FSDP2=1 torchrun --nproc-per-node 2from_pretrained:fast_inference = True (vLLM) is not supported with FSDP2UNSLOTH_FSDP2=1 torchrun ...UNSLOTH_FSDP2=1 UNSLOTH_FSDP2_REPLICATE_FROZEN=0 torchrun ...(the old sharded layout)fully_shard(_init_sharded_paramnew_zeros)torchrun ...(DDP)Notes on the PASS arms:
save_lora("grpo_saved_lora")wrote 239,542,873 bytes, equal to the one-GPU run. The script's finalfast_generatewithload_lora("grpo_saved_lora")produced text. The losses equal an earlier DDP run of the same script (0.0004 / 0.0203 / -0.0).save_lorawrote 194,569,956 bytes, equal to DDP, and the finalload_lorageneration 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_utilization0.76, rank 0 / rank 1):UNSLOTH_FSDP2_REPLICATE_FROZEN=0, the previous layout)fully_shardThe 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
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_loraunder native FSDP2 (a rank 0 only call waits in the gather); a one-time notice says so.