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
Fit Gemma 4 E2B on 8 GB cards on Windows and in Studio chat (#13425)
Daniel Han8e2f6dc3412e
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.pyindex 102f33e74ec..c4622f3a114 100644--- a/studio/backend/core/inference/inference.py+++ b/studio/backend/core/inference/inference.py@@ -84,6 +84,130 @@ def _load_in_4bit_kwargs(load_in_4bit: bool) -> dict:return {} if load_in_4bit else {"load_in_4bit": False}+_OFFLOAD_FIT_FRACTION = 0.9+++def _loader_repo(path: str, load_in_4bit: bool) -> str:+ """The repo Unsloth's mapper will load for `path`, else `path`."""+ try:+ from unsloth.models import loader, loader_utils++ if not loader.ALLOW_BITSANDBYTES:+ load_in_4bit = False+ tables = (+ loader_utils.FLOAT_TO_INT_MAPPER,+ loader_utils.INT_TO_FLOAT_MAPPER,+ loader_utils.MAP_TO_UNSLOTH_16bit,+ )+ # Unknown names would fetch the remote mapper.+ name = path.lower()+ if name in loader_utils.BAD_MAPPINGS or not any(name in t for t in tables):+ return path+ return loader_utils.get_model_name(path, load_in_4bit = load_in_4bit) or path+ except Exception:+ return path+++def _complete_local_safetensors_bytes(folder: Path) -> Optional[int]:+ """None while a shard the index names is missing (interrupted download)."""+ try:+ index = folder / "model.safetensors.index.json"+ if index.is_file():+ shards = set(json.loads(index.read_text(encoding = "utf-8"))["weight_map"].values())+ files = [folder / shard for shard in shards]+ if not all(f.is_file() for f in files):+ return None+ else:+ files = list(folder.glob("*.safetensors"))+ return sum(f.stat().st_size for f in files) or None+ except Exception:+ return None+++def _checkpoint_bytes(name: str, hf_token = None) -> Optional[int]:+ folder = Path(name)+ if not folder.is_dir():+ try:+ from huggingface_hub import snapshot_download+ folder = Path(snapshot_download(name, local_files_only = True, allow_patterns = ["*.json"]))+ except Exception:+ folder = None+ if folder is not None:+ local = _complete_local_safetensors_bytes(folder)+ if local:+ return local+ if Path(name).is_dir():+ return None+ try:+ from huggingface_hub import HfApi++ info = HfApi().model_info(name, token = hf_token, files_metadata = True)+ total = sum(+ s.size or 0+ for s in info.siblings or ()+ if s.rfilename.endswith(".safetensors") and "/" not in s.rfilename+ )+ return total or None+ except Exception:+ return None+++def _offload_kwargs_for_fit(+ name: str,+ device_map,+ load_in_4bit: bool,+ hf_token = None,+ mapped: bool = True,+) -> dict:+ """Gemma 4 E2B 4-bit is 8.1 GB on an 8 GB card (#13388); "auto" still loads it all onto the GPU if it fits."""+ # "sequential" over several visible cards pools them; "auto" would plan for one.+ if device_map != "sequential" or not torch.cuda.is_available():+ return {}+ try:+ if torch.cuda.device_count() != 1:+ return {}+ free = torch.cuda.mem_get_info(0)[0]+ except Exception:+ return {}+ # mapped = False: use_exact_model_name reads `name` verbatim.+ size = _checkpoint_bytes(_loader_repo(name, load_in_4bit) if mapped else name, hf_token)+ if not size or size < _OFFLOAD_FIT_FRACTION * free:+ return {}+ logger.info(+ f"Checkpoint is {size / 2**30:.2f} GiB with {free / 2**30:.2f} GiB free; loading with offload_layers='auto'"+ )+ return {"offload_layers": "auto"}+++def _load_with_offload_fallback(load, **kwargs):+ """A single-GPU load the size check missed that spills to the CPU: free it, retry with offload_layers = "auto"."""+ try:+ return load(**kwargs)+ except ValueError as e:+ text = str(e)+ spilled = "does not fit in GPU memory" in text or text.startswith(+ "Some modules are dispatched on the CPU or the disk"+ )+ if (+ not spilled+ or "offload_layers" in kwargs+ or kwargs.get("device_map") != "sequential"+ or not torch.cuda.is_available()+ or torch.cuda.device_count() != 1+ ):+ raise+ # After the except block: its traceback's frames held the half-built model.+ import gc++ gc.collect()+ torch.cuda.empty_cache()+ logger.info(+ f"Model did not fit in GPU memory; retrying with offload_layers='auto' "+ f"({torch.cuda.memory_allocated() / 2**30:.2f} GiB still allocated)"+ )+ return load(offload_layers = "auto", **kwargs)++def _hf_token_for_loader(hf_token: Optional[str] | bool) -> Optional[str] | bool:if hf_token is False:return False@@ -900,8 +1024,17 @@ class InferenceBackend:exact_model_name = _exact_model_name_for_load(config, load_in_4bit)use_exact_model_name = exact_model_name is not Noneload_path = exact_model_name or config.path+ # A LoRA loads its base model.+ offload_kwargs = _offload_kwargs_for_fit(+ config.base_model if config.is_lora and config.base_model else load_path,+ device_map,+ load_in_4bit,+ _hf_token_for_loader(hf_token),+ mapped = not use_exact_model_name,+ )if config.is_vision:- model, processor = FastVisionModel.from_pretrained(+ model, processor = _load_with_offload_fallback(+ FastVisionModel.from_pretrained,model_name = load_path,max_seq_length = max_seq_length,dtype = dtype,@@ -910,6 +1043,7 @@ class InferenceBackend:token = _hf_token_for_loader(hf_token),trust_remote_code = trust_remote_code,use_exact_model_name = use_exact_model_name,+ **offload_kwargs,)FastVisionModel.for_inference(model)@@ -950,7 +1084,8 @@ class InferenceBackend:self.models[model_name]["processor"] = processorelse:- model, tokenizer = FastLanguageModel.from_pretrained(+ model, tokenizer = _load_with_offload_fallback(+ FastLanguageModel.from_pretrained,model_name = load_path,max_seq_length = max_seq_length,dtype = dtype,@@ -959,6 +1094,7 @@ class InferenceBackend:token = _hf_token_for_loader(hf_token),trust_remote_code = trust_remote_code,use_exact_model_name = use_exact_model_name,+ **offload_kwargs,)FastLanguageModel.for_inference(model)diff --git a/studio/backend/tests/test_inference_cached_repo_exact_load.py b/studio/backend/tests/test_inference_cached_repo_exact_load.pyindex 919f03b1f59..3c57f111e4d 100644--- a/studio/backend/tests/test_inference_cached_repo_exact_load.py+++ b/studio/backend/tests/test_inference_cached_repo_exact_load.py@@ -309,15 +309,27 @@ def test_load_model_hands_the_verdict_to_both_loaders():lambda v: any(isinstance(n, ast.Name) and n.id in verdicts for n in ast.walk(v)))+ def loader(node):+ # Direct `FastX.from_pretrained(...)`, or the same bound method handed to the offload fallback.+ if not isinstance(node, ast.Call):+ return None+ func = node.func+ if isinstance(func, ast.Name) and func.id == "_load_with_offload_fallback" and node.args:+ func = node.args[0]+ if (+ isinstance(func, ast.Attribute)+ and func.attr == "from_pretrained"+ and isinstance(func.value, ast.Name)+ and func.value.id in ("FastLanguageModel", "FastVisionModel")+ ):+ return func.value.id+ return None+def receives(kwarg):return {- node.func.value.id+ loader(node)for node in ast.walk(load_model)- if isinstance(node, ast.Call)- and isinstance(node.func, ast.Attribute)- and node.func.attr == "from_pretrained"- and isinstance(node.func.value, ast.Name)- and node.func.value.id in ("FastLanguageModel", "FastVisionModel")+ if loader(node)and any(kw.arg == kwarg and isinstance(kw.value, ast.Name) and kw.value.id in derivedfor kw in node.keywordsdiff --git a/studio/backend/tests/test_inference_offload_fit.py b/studio/backend/tests/test_inference_offload_fit.pynew file mode 100644index 00000000000..b83b1db38ed--- /dev/null+++ b/studio/backend/tests/test_inference_offload_fit.py@@ -0,0 +1,187 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A chat load whose checkpoint nearly fills free VRAM asks for offload_layers = "auto" (#13388):+Gemma 4 E2B in 4-bit is 8.1 GB, 4.4 GB of it one per-layer token table, so an 8 GB card failed outright."""++from __future__ import annotations++import ast+import types+from pathlib import Path++import pytest++_SRC = Path(__file__).resolve().parent.parent / "core" / "inference" / "inference.py"+_GiB = 2**30+++def _fit(+ free,+ size,+ cuda = True,+ devices = 1,+):+ tree = ast.parse(_SRC.read_text(encoding = "utf-8"))+ nodes = [+ n+ for n in tree.body+ if (isinstance(n, ast.FunctionDef) and n.name == "_offload_kwargs_for_fit")+ or (+ isinstance(n, ast.Assign) and getattr(n.targets[0], "id", "") == "_OFFLOAD_FIT_FRACTION"+ )+ ]+ fake_cuda = types.SimpleNamespace(+ is_available = lambda: cuda,+ device_count = lambda: devices,+ mem_get_info = lambda i: (free, 8 * _GiB),+ )+ asked = []+ scope = {+ "torch": types.SimpleNamespace(cuda = fake_cuda),+ "logger": types.SimpleNamespace(info = lambda *a, **k: None),+ "Optional": object,+ "_loader_repo": lambda name, four: name + ("-bnb-4bit" if four else ""),+ "_checkpoint_bytes": lambda name, token: asked.append(name) or size,+ }+ exec(compile(ast.Module(nodes, []), str(_SRC), "exec"), scope)+ return scope["_offload_kwargs_for_fit"], asked+++def test_checkpoint_that_fills_the_card_loads_with_auto_offload():+ fit, asked = _fit(free = int(7.3 * _GiB), size = int(8.1 * _GiB))+ assert fit("unsloth/gemma-4-E2B-it", "sequential", True) == {"offload_layers": "auto"}+ # Sized from the repo the 4-bit mapper loads, not the 16-bit name the UI sent.+ assert asked == ["unsloth/gemma-4-E2B-it-bnb-4bit"]+++def test_exact_load_sizes_the_repo_it_reads():+ # use_exact_model_name: a cached 16-bit snapshot is read as-is, so the 4-bit twin says nothing.+ fit, asked = _fit(free = int(7.3 * _GiB), size = 10 * _GiB)+ assert fit("unsloth/gemma-4-E2B-it", "sequential", True, mapped = False) == {+ "offload_layers": "auto"+ }+ assert asked == ["unsloth/gemma-4-E2B-it"]+++def test_checkpoint_with_room_loads_as_before():+ fit, _ = _fit(free = 7 * _GiB, size = 6 * _GiB)+ assert fit("m", "sequential", True) == {}+++ "device_map, cuda, size",+ [+ ("unsloth_balanced", True, 9 * _GiB), # several GPUs: the balanced planner places it+ ("sequential", False, 9 * _GiB), # no CUDA / ROCm card+ ("sequential", True, None), # size unknown: no guess+ ],+)+def test_nothing_changes_where_the_guess_cannot_apply(device_map, cuda, size):+ fit, _ = _fit(free = 7 * _GiB, size = size, cuda = cuda)+ assert fit("m", device_map, True) == {}+++def test_sequential_over_several_visible_cards_is_left_pooled():+ # Transformers fills every visible card in order; a one-card plan would push most of it to the host.+ fit, _ = _fit(free = 7 * _GiB, size = 13 * _GiB, devices = 2)+ assert fit("m", "sequential", True) == {}+++def _local_bytes():+ tree = ast.parse(_SRC.read_text(encoding = "utf-8"))+ node = next(+ n+ for n in tree.body+ if isinstance(n, ast.FunctionDef) and n.name == "_complete_local_safetensors_bytes"+ )+ scope = {"json": __import__("json"), "Path": Path, "Optional": object}+ exec(compile(ast.Module([node], []), str(_SRC), "exec"), scope)+ return scope["_complete_local_safetensors_bytes"]+++def test_partial_snapshot_is_not_sized_locally(tmp_path):+ # An interrupted download leaves some shards: the Hub has to size the rest.+ (tmp_path / "model.safetensors.index.json").write_text(+ '{"weight_map": {"a": "model-00001-of-00002.safetensors", "b": "model-00002-of-00002.safetensors"}}',+ encoding = "utf-8",+ )+ (tmp_path / "model-00001-of-00002.safetensors").write_bytes(b"x" * 10)+ assert _local_bytes()(tmp_path) is None+ (tmp_path / "model-00002-of-00002.safetensors").write_bytes(b"x" * 5)+ assert _local_bytes()(tmp_path) == 15+++def test_single_file_snapshot_is_sized_locally(tmp_path):+ (tmp_path / "model.safetensors").write_bytes(b"x" * 7)+ assert _local_bytes()(tmp_path) == 7+++_SPILL = "Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the quantized model."+++def _fallback(cuda = True, devices = 1):+ tree = ast.parse(_SRC.read_text(encoding = "utf-8"))+ node = next(+ n+ for n in tree.body+ if isinstance(n, ast.FunctionDef) and n.name == "_load_with_offload_fallback"+ )+ fake_cuda = types.SimpleNamespace(+ is_available = lambda: cuda,+ device_count = lambda: devices,+ empty_cache = lambda: None,+ memory_allocated = lambda: 0,+ )+ scope = {+ "torch": types.SimpleNamespace(cuda = fake_cuda),+ "logger": types.SimpleNamespace(info = lambda *a, **k: None),+ }+ exec(compile(ast.Module([node], []), str(_SRC), "exec"), scope)+ return scope["_load_with_offload_fallback"]+++class _HalfBuilt:+ pass+++def test_missed_guess_frees_the_failed_attempt_then_retries_with_auto():+ import weakref++ calls, seen = [], []++ def load(**kwargs):+ calls.append(kwargs)+ if "offload_layers" in kwargs:+ # The first attempt's half-built model must be gone before the retry allocates.+ seen.append(refs[0]() is None)+ return "model", "tok"+ half_built = _HalfBuilt()+ refs.append(weakref.ref(half_built))+ raise ValueError(_SPILL)++ refs = []+ assert _fallback()(load, model_name = "m", device_map = "sequential") == ("model", "tok")+ assert calls[1] == {"model_name": "m", "device_map": "sequential", "offload_layers": "auto"}+ assert seen == [True]+++ "error, kwargs, devices",+ [+ (ValueError(_SPILL), {"offload_layers": "auto"}, 1), # the guess already asked for it+ (ValueError("another problem"), {}, 1),+ (RuntimeError(_SPILL), {}, 1),+ (ValueError(_SPILL), {}, 2), # several visible cards+ ],+)+def test_fallback_leaves_other_failures_alone(error, kwargs, devices):+ calls = []++ def load(**kw):+ calls.append(kw)+ raise error++ with pytest.raises(type(error)) as caught:+ _fallback(devices = devices)(load, device_map = "sequential", **kwargs)+ assert caught.value is error and len(calls) == 1diff --git a/tests/test_block_swap_install.py b/tests/test_block_swap_install.pyindex f9babd4082e..76ddd902e5e 100644--- a/tests/test_block_swap_install.py+++ b/tests/test_block_swap_install.py@@ -638,18 +638,6 @@ def test_headless_load_swaps_onto_the_retained_layers_card():assert built == [card][email protected]("path", ["llama.py", "vision.py"])-def test_auto_plan_never_counts_on_an_embedding_offload_the_platform_refuses(path):- src = open(os.path.join(HERE, "unsloth", "models", path), encoding = "utf-8").read()- call = next(- n- for n in ast.walk(ast.parse(src))- if isinstance(n, ast.Call) and getattr(n.func, "id", None) == "resolve_auto_block_swap"- )- kw = next(k for k in call.keywords if k.arg == "offload_embedding")- assert "_offload_embedding_unsupported_platform" in ast.get_source_segment(src, kw.value)--def test_load_time_swappers_allocate_the_planned_prefetch_depth():torch = pytest.importorskip("torch")mod = ast.parse(open(UTILS, encoding = "utf-8").read())diff --git a/tests/test_offload_tied_autodisable.py b/tests/test_offload_tied_autodisable.pyindex cde03a15d87..f9df9f87875 100644--- a/tests/test_offload_tied_autodisable.py+++ b/tests/test_offload_tied_autodisable.py@@ -6,8 +6,8 @@ correctness switch, so it should turn itself off instead, as the fast_inferencecase a few lines earlier already does. Two shipped notebooks (NeMo-Gym-Sudoku,NeMo-Gym-Multi-Environment) died this way on unsloth/Qwen2.5-1.5B-Instruct.-Every platform branch is driven explicitly, so the assertions hold on Linux,-macOS, Windows and WSL alike: the host's own os.name never decides.+Windows and WSL used to be refused outright (unslothai/unsloth#13388); the+platform inputs are driven explicitly so the host's own os.name never decides."""import ast, os, types@@ -63,13 +63,11 @@ def _load(*names):_NS = _load("_embeddings_are_tied",- "_offload_embedding_unsupported_platform","_embedding_dispatch_device","_embedding_is_worth_offloading","_resolve_offload_embedding",)resolve = _NS["_resolve_offload_embedding"]-unsupported_platform = _NS["_offload_embedding_unsupported_platform"]dispatch_device = _NS["_embedding_dispatch_device"]_WSL_VARS = ("WSL_DISTRO_NAME", "WSL_INTEROP")@@ -163,49 +161,19 @@ def test_opaque_model_disables_offload():assert resolve(_Opaque(), True) is False-def test_wsl_and_windows_disable_offload():- # Neither can offload, and the flag also gates the multi-device hook attach, so it has to read False rather than- # pass through.- for var in _WSL_VARS:- with _as_platform("posix"):- os.environ[var] = "1"- assert unsupported_platform() == "WSL"+def test_windows_and_wsl_offload_like_linux():+ # Windows and WSL used to decline every offload, so an 8 GB card could not hold Gemma 4 E2B there (#13388).+ platforms = [+ ("nt", {}),+ ("posix", {"wsl": True}),+ ("posix", {"release": "6.6.87.2-microsoft-standard-WSL2"}),+ ]+ for os_name, kw in platforms:+ with _as_platform(os_name, **kw):+ assert resolve(_untied_model(), True) is Trueassert resolve(_tied_model(), True) is False- assert resolve(_untied_model(), True) is Falseassert resolve(_Opaque(), True) is False- with _as_platform("nt"):- assert unsupported_platform() == "Windows"- assert resolve(_tied_model(), True) is False- assert resolve(_untied_model(), True) is False- assert resolve(_Opaque(), True) is False-- with _as_platform("posix"):- assert unsupported_platform() is None--[email protected](not hasattr(os, "uname"), reason = "os.uname is POSIX only")-def test_docker_on_wsl2_disables_offload():- # A container on WSL2 sets no WSL_* variables; only the shared kernel says WSL (unslothai/unsloth#3511).- for release in ("6.6.87.2-microsoft-standard-WSL2", "5.15.153.1-microsoft-standard-WSL2"):- with _as_platform("posix", release = release):- assert unsupported_platform() == "WSL"- assert resolve(_untied_model(), True) is False-- for release in ("6.8.0-1021-azure", "6.10.14-linuxkit"):- with _as_platform("posix", release = release):- assert unsupported_platform() is None---def test_platform_gate_lives_in_one_place():- # The offload block used to re-test os.name itself; the copies drifted apart and only Windows noticed.- # _resolve_offload_embedding owns it now.- helper = _SRC[_SRC.index("def _offload_embedding_unsupported_platform(") :]- helper = helper[: helper.index("\n\n\ndef ")]- for probe in ('os.name == "nt"', "WSL_DISTRO_NAME", "WSL_INTEROP"):- assert _SRC.count(probe) == 1, f"{probe} must be tested in exactly one place"- assert probe in helper, f"{probe} belongs in _offload_embedding_unsupported_platform"-def test_resolved_before_multidevice_hooks():# Hook attach returns early while offload_embedding is still True.@@ -444,7 +412,6 @@ class _PerLayerModel(nn.Module):def _spare_ns():ns = _load("_embeddings_are_tied",- "_offload_embedding_unsupported_platform","_embedding_dispatch_device","_input_side_embeddings","_accelerator_device",diff --git a/unsloth/models/llama.py b/unsloth/models/llama.pyindex c5443d45632..c91291946c7 100644--- a/unsloth/models/llama.py+++ b/unsloth/models/llama.py@@ -128,7 +128,6 @@ from ..kernels.bnb_override import install_bnb_nf4_override as _install_bnb_nf4_from ..tokenizer_utils import *from .vision import FastBaseModel, _is_text_seq2seq_configfrom .vision import (- _offload_embedding_unsupported_platform,_resolve_offload_embedding,offload_input_embedding,restore_input_embedding,@@ -3182,9 +3181,7 @@ class FastLlamaModel:requested_device_map(device_map),model_name,max_seq_length = max_seq_length,- offload_embedding = bool(offload_embedding)- and num_labels is None- and _offload_embedding_unsupported_platform() is None,+ offload_embedding = bool(offload_embedding) and num_labels is None,planner_kwargs = planner_kwargs_with_max_memory(device_map_planner_kwargs, kwargs),skip_reason = _planner_skip_reason,**planner_config_overrides(kwargs),diff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex 9604a9f18af..dc0d8ec444b 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -936,21 +936,6 @@ def _embeddings_are_tied(input_embeddings, output_embeddings):return w_in is w_out or w_in.data_ptr() == w_out.data_ptr()-def _offload_embedding_unsupported_platform():- # Offloaded embeddings do not work on Windows or WSL.- if bool(os.environ.get("WSL_DISTRO_NAME") or os.environ.get("WSL_INTEROP")):- return "WSL"- if os.name == "nt":- return "Windows"- # Docker on WSL2 has no WSL_* variables but shares the *-microsoft-standard-WSL2 kernel (unslothai/unsloth#3511).- try:- if "microsoft" in os.uname().release.lower():- return "WSL"- except Exception:- pass- return None--def _embedding_dispatch_device(input_embeddings):# accelerate's hook re-sends the ids to the device it recorded, after our offload pre-hook already sent them to the CPU weight. Returns that device, or None.hook = getattr(input_embeddings, "_hf_hook", None)@@ -996,9 +981,6 @@ def _resolve_offload_embedding(if not automatic and not offload_embedding:return False- platform_name = _offload_embedding_unsupported_platform()- if platform_name is not None:- return _decline(f"offloading is unsupported on {platform_name}.")try:in_embed = model.get_input_embeddings()out_embed = (@@ -1092,7 +1074,7 @@ def offload_spare_embeddings(model, require_frozen = True):"""offload_embedding = "auto" under memory pressure: move every input-side embedding thatlm_head does not share (and, after get_peft_model, that is frozen) to host RAM. A tied inputembedding stays, but Gemma 3n / 4 per-layer tables still go. Returns the bytes moved."""- if _offload_embedding_unsupported_platform() is not None or is_distributed():+ if is_distributed():return 0try:found, out_embed = _input_side_embeddings(model)@@ -3486,9 +3468,7 @@ class FastBaseModel:requested_device_map(device_map),model_name,max_seq_length = max_seq_length,- # Windows / WSL decline the offload later: a plan counting on it would leave a streamed table unhooked.- offload_embedding = bool(offload_embedding)- and _offload_embedding_unsupported_platform() is None,+ offload_embedding = bool(offload_embedding),planner_kwargs = planner_kwargs_with_max_memory(device_map_planner_kwargs, kwargs),placement = "spread",skip_reason = _planner_skip_reason