Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
fast_inference under UNSLOTH_FSDP2=1 torchrun: keep vLLM instead of refusing it (#15709)
Daniel Hana27be3184de3
diff --git a/tests/test_fast_inference_refuses_fsdp2.py b/tests/test_fast_inference_refuses_fsdp2.pyindex 944714c5318..c34cf9311e6 100644--- a/tests/test_fast_inference_refuses_fsdp2.py+++ b/tests/test_fast_inference_refuses_fsdp2.py@@ -143,3 +143,22 @@ def test_trainer_args_fsdp2_is_refused_when_the_trainer_is_built(tmp_path):# No version named: TrainingArguments picks FSDP2 from transformers 5.10.0, FSDP1 before.assert (unversioned == "REFUSED") == (Version(__version__) >= Version("5.10.0"))++[email protected]("zoo_gathers", [True, False])+def test_native_fsdp2_keeps_vllm_when_zoo_gathers_the_adapters(no_launcher, zoo_gathers):+ for key in ("UNSLOTH_FSDP2_BACKEND", "ACCELERATE_USE_FSDP"):+ no_launcher.delenv(key, raising = False)+ no_launcher.setenv("UNSLOTH_FSDP2", "1")+ for key, value in (("WORLD_SIZE", "2"), ("RANK", "0"), ("LOCAL_RANK", "0")):+ no_launcher.setenv(key, value)+ no_launcher.setattr(loader_utils, "_zoo_gathers_fsdp2_lora", lambda: zoo_gathers)+ assert fsdp2_requested()+ if zoo_gathers:+ raise_if_fast_inference_under_fsdp2(True)+ else:+ with pytest.raises(NotImplementedError, match = "update unsloth_zoo"):+ raise_if_fast_inference_under_fsdp2(True)+ no_launcher.setenv("UNSLOTH_FSDP2_BACKEND", "accelerate")+ with pytest.raises(NotImplementedError, match = "fast_inference = False"):+ raise_if_fast_inference_under_fsdp2(True)diff --git a/tests/test_fsdp2_native_vllm_shared_frozen_gloo.py b/tests/test_fsdp2_native_vllm_shared_frozen_gloo.pynew file mode 100644index 00000000000..6acc9ba8861--- /dev/null+++ b/tests/test_fsdp2_native_vllm_shared_frozen_gloo.py@@ -0,0 +1,142 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Native FSDP2 keeps vLLM-shared frozen weights replicated (same storage) instead of sharding a copy (T4 OOM)."""++import multiprocessing+import os++if multiprocessing.parent_process() is not None or getattr(+ multiprocessing.current_process(), "_inheriting", False+):+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # spawned gloo ranks: CPU only, also on GPU hosts++import datetime # noqa: E402+import sys # noqa: E402+import types # noqa: E402++import pytest # noqa: E402+import torch # noqa: E402++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from test_fsdp2_native_units import _load_native # noqa: E402+from test_fsdp2_native_trainer_ckpt_gloo import _free_port # noqa: E402+from test_fsdp2_native_trainer_args_gloo import _lora # noqa: E402++CASES = ("no_engine", "engine_on_peft", "engine_on_inner", "engine_not_shared", "env_shards")+++def _case(native, case):+ from torch.distributed.device_mesh import init_device_mesh+ from torch.distributed.tensor import DTensor++ os.environ.pop("UNSLOTH_FSDP2_REPLICATE_FROZEN", None)+ model = _lora(1)+ if case == "engine_on_peft":+ model.vllm_engine = types.SimpleNamespace(shared_weights = True)+ elif case == "engine_on_inner":+ model.base_model.model.vllm_engine = types.SimpleNamespace(shared_weights = True)+ elif case == "engine_not_shared":+ model.vllm_engine = types.SimpleNamespace()+ elif case == "env_shards":+ model.vllm_engine = types.SimpleNamespace(shared_weights = True)+ os.environ["UNSLOTH_FSDP2_REPLICATE_FROZEN"] = "0"+ frozen = {n: p.data_ptr() for n, p in model.named_parameters() if not p.requires_grad}+ mesh = init_device_mesh("cpu", (2,))+ agreed = {}+ original = native._agree_over_ranks++ def record(*args, **kwargs):+ agreed["flags"] = original(*args, **kwargs)+ return agreed["flags"]++ native._agree_over_ranks = record+ try:+ cfg = native.FSDP2Config(param_dtype = torch.float32, device = "cpu", mesh = mesh)+ model = native.shard_model(model, cfg)+ finally:+ native._agree_over_ranks = original+ fits, replicate_frozen, _, _ = agreed["flags"]+ params = dict(model.named_parameters())+ return {+ "fits": fits,+ "replicate_frozen": replicate_frozen,+ "frozen_dtensor": sum(isinstance(params[n], DTensor) for n in frozen),+ "frozen_same_storage": sum(+ not isinstance(params[n], DTensor) and params[n].data_ptr() == ptr+ for n, ptr in frozen.items()+ ),+ "n_frozen": len(frozen),+ "trainable_dtensor": all(+ isinstance(p, DTensor) for p in params.values() if p.requires_grad+ ),+ }+++def _worker(rank, world, port, out):+ os.environ.update(+ MASTER_ADDR = "127.0.0.1",+ MASTER_PORT = str(port),+ RANK = str(rank),+ WORLD_SIZE = str(world),+ LOCAL_RANK = str(rank),+ LOCAL_WORLD_SIZE = str(world),+ UNSLOTH_FSDP2 = "1",+ )+ import torch.distributed as dist++ dist.init_process_group(+ "gloo", rank = rank, world_size = world, timeout = datetime.timedelta(seconds = 60)+ )+ try:+ native = _load_native()+ res = {}+ for case in CASES:+ try:+ res[case] = _case(native, case)+ except Exception as exc:+ import traceback+ res[case] = {"crash": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"}+ out.put((rank, res))+ finally:+ dist.destroy_process_group()+++def test_vllm_shared_frozen_weights_stay_replicated():+ pytest.importorskip("peft")+ import inspect++ from torch.distributed.fsdp import fully_shard++ if "ignored_params" not in inspect.signature(fully_shard).parameters:+ pytest.skip(+ "fully_shard has no ignored_params (torch < 2.7): frozen weights cannot stay replicated"+ )+ import torch.multiprocessing as mp++ ctx = mp.get_context("spawn")+ out = ctx.Queue()+ mp.start_processes(+ _worker, args = (2, _free_port(), out), nprocs = 2, join = True, start_method = "spawn"+ )+ results = {}+ while not out.empty():+ rank, r = out.get(timeout = 5)+ results[rank] = r+ assert sorted(results) == [0, 1], results+ for rank, res in results.items():+ for case, r in res.items():+ print("VLLM_SHARED_FROZEN", rank, case, r)+ assert "crash" not in r, (case, r["crash"])+ assert r["fits"] is False and r["trainable_dtensor"] and r["n_frozen"] > 0, (case, r)+ if case in ("engine_on_peft", "engine_on_inner"):+ assert r["replicate_frozen"] is True, (case, r)+ assert r["frozen_dtensor"] == 0 and r["frozen_same_storage"] == r["n_frozen"], (+ case,+ r,+ )+ else:+ assert r["replicate_frozen"] is False and r["frozen_dtensor"] == r["n_frozen"], (+ case,+ r,+ )diff --git a/unsloth/models/fsdp2_native.py b/unsloth/models/fsdp2_native.pyindex 51854ef4318..5ab502666a1 100644--- a/unsloth/models/fsdp2_native.py+++ b/unsloth/models/fsdp2_native.py@@ -1529,6 +1529,22 @@ def _refuse_block_swap(model):)+def _frozen_weights_are_vllm_engine_storage(model):+ """True if weights are views of a vLLM engine's (`llm.shared_weights`), found on the model or base_model.model."""+ seen = set()+ stack = [model]+ while stack:+ m = stack.pop()+ if m is None or id(m) in seen or not isinstance(m, torch.nn.Module):+ continue+ seen.add(id(m))+ if getattr(m.__dict__.get("vllm_engine"), "shared_weights", False):+ return True+ modules = m.__dict__.get("_modules", {})+ stack.extend(modules.get(name) for name in ("base_model", "model"))+ return False++def shard_model(model, config: Optional[FSDP2Config] = None):"""fully_shard each unit of `find_shard_units`, then the root (embeddings, final norm, lm_head,leftovers). Pass the outermost module the loop calls (the PeftModel for LoRA). Idempotent."""@@ -1576,6 +1592,19 @@ def shard_model(model, config: Optional[FSDP2Config] = None):f"(fully_shard(ignored_params), torch 2.7+); this is torch {torch.__version__}.")config = dataclasses.replace(config, shard_frozen = False)+ if (+ config.shard_frozen is None+ and _supports_ignored_params(fully_shard)+ and _frozen_weights_are_vllm_engine_storage(model)+ ):+ from .fsdp2_perf import _env_tristate as _replicate_env+ if _replicate_env("UNSLOTH_FSDP2_REPLICATE_FROZEN") is None:+ # Sharding engine-owned weights frees nothing and adds a shard per rank (3B GRPO OOMs on a T4).+ config = dataclasses.replace(config, shard_frozen = False)+ _print_rank0(+ "Unsloth: native FSDP2 keeps the frozen weights replicated: they are the vLLM engine's "+ "weights (fast_inference), so sharding them would copy them, not free them."+ )device = _shard_device(model, config.device)dist = _ensure_process_group(device, config.backend, config.timeout)if device.type == "cuda":diff --git a/unsloth/models/loader_utils.py b/unsloth/models/loader_utils.pyindex de9a8f16dba..85626c7563e 100644--- a/unsloth/models/loader_utils.py+++ b/unsloth/models/loader_utils.py@@ -201,14 +201,30 @@ def fsdp2_keeps_fused_lora():return fsdp2_requested()+def _zoo_gathers_fsdp2_lora():+ """unsloth_zoo hands vLLM whole adapters from FSDP2 DTensor shards (older ones pass the shards)."""+ try:+ from unsloth_zoo import vllm_utils+ except Exception:+ return False+ return hasattr(vllm_utils, "_lora_state_dict")++def raise_if_fast_inference_under_fsdp2(fast_inference):- """Unsupported combination: refuse it before vLLM loads instead of failing mid-run (unsloth#3551)."""- if fast_inference and fsdp2_requested():- raise NotImplementedError(- "Unsloth: `fast_inference = True` (vLLM) is not supported with FSDP2.\n"- "Load the model with `fast_inference = False` to train with FSDP2, "- "or launch without FSDP2 to use vLLM."- )+ """Refuse vLLM under accelerate's FSDP2 early (unsloth#3551); native FSDP2 keeps it (one engine per rank)."""+ if not fast_inference or not fsdp2_requested():+ return+ from ..fsdp2_launch import unsloth_fsdp2_native_requested++ if unsloth_fsdp2_native_requested() and _zoo_gathers_fsdp2_lora():+ return+ raise NotImplementedError(+ "Unsloth: `fast_inference = True` (vLLM) is not supported with accelerate's FSDP2, or with an "+ "unsloth_zoo that cannot gather FSDP2 adapters for vLLM (update unsloth_zoo).\n"+ "Load the model with `fast_inference = False` to train with FSDP2, launch with "+ "`UNSLOTH_FSDP2=1 torchrun ...` (Unsloth's native FSDP2 keeps vLLM), "+ "or launch without FSDP2 to use vLLM."+ )def prepare_device_map():