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
Fix gpt-oss offload_embedding and generate() kwargs, and guard offload_embedding on tied/vLLM models (#6774)
Daniel Hand91183d03fec
diff --git a/tests/test_generate_kwarg_gate.py b/tests/test_generate_kwarg_gate.pynew file mode 100644index 00000000000..6d1379d3a96--- /dev/null+++ b/tests/test_generate_kwarg_gate.py@@ -0,0 +1,137 @@+"""GPU-free test for the generate-kwarg gate in vision.py+(_unsloth_generate_accepts_kwarg), covering both logits_to_keep injection and mm_token_type_ids+stripping, AST-extracted so no unsloth/CUDA import is needed."""++import ast, inspect, os++HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+VISION = os.path.join(HERE, "unsloth", "models", "vision.py")+++def _load_helper():+ src = open(VISION).read()+ mod = ast.parse(src)+ for node in mod.body:+ if isinstance(node, ast.FunctionDef) and node.name == "_unsloth_generate_accepts_kwarg":+ ns = {"inspect": inspect}+ exec(ast.get_source_segment(src, node), ns)+ return ns["_unsloth_generate_accepts_kwarg"]+ raise AssertionError("_unsloth_generate_accepts_kwarg not found in vision.py")+++accepts = _load_helper()+++class PrepHasKwargs_ForwardHasKey:+ # **kwargs on prepare unions forward params; key in forward -> ACCEPTED.+ def prepare_inputs_for_generation(self, input_ids, **kwargs): ...+ def forward(+ self,+ input_ids,+ logits_to_keep = 0,+ **kwargs,+ ): ...+++class PrepNoKwargs_ForwardHasKey:+ # no **kwargs -> forward not unioned; key only in forward -> REJECTED (gpt-oss shape).+ def prepare_inputs_for_generation(+ self,+ input_ids,+ attention_mask = None,+ ): ...+ def forward(+ self,+ input_ids,+ logits_to_keep = 0,+ ): ...+++class PrepHasKeyDirectly:+ # key directly on prepare -> ACCEPTED.+ def prepare_inputs_for_generation(+ self,+ input_ids,+ logits_to_keep = 0,+ ): ...+ def forward(self, input_ids): ...+++class NoPrepare:+ # no prepare -> empty args, no union -> REJECTED.+ def forward(+ self,+ input_ids,+ logits_to_keep = 0,+ **kwargs,+ ): ...+++class VisionRejectsMM:+ # Qwen3-VL shape: neither prepare nor forward names mm_token_type_ids -> REJECTED (stripped).+ def prepare_inputs_for_generation(+ self,+ input_ids,+ attention_mask = None,+ ): ...+ def forward(+ self,+ input_ids,+ pixel_values = None,+ ): ...+++class VisionAcceptsMM:+ # forward names mm_token_type_ids and prepare unions it via **kwargs -> ACCEPTED (kept).+ def prepare_inputs_for_generation(self, input_ids, **kwargs): ...+ def forward(+ self,+ input_ids,+ mm_token_type_ids = None,+ **kwargs,+ ): ...+++# (model, key, expected) per gate case.+CASES = [+ (+ "prep(**kwargs)+forward(key) -> accept",+ PrepHasKwargs_ForwardHasKey(),+ "logits_to_keep",+ True,+ ),+ (+ "prep(no kwargs)+forward(key) -> reject",+ PrepNoKwargs_ForwardHasKey(),+ "logits_to_keep",+ False,+ ),+ ("prep(key) direct -> accept", PrepHasKeyDirectly(), "logits_to_keep", True),+ ("no prepare_inputs_for_gen -> reject", NoPrepare(), "logits_to_keep", False),+ (+ "num_logits_to_keep variant -> reject",+ PrepNoKwargs_ForwardHasKey(),+ "num_logits_to_keep",+ False,+ ),+ (+ "mm_token_type_ids not accepted -> reject (strip)",+ VisionRejectsMM(),+ "mm_token_type_ids",+ False,+ ),+ ("mm_token_type_ids accepted -> keep", VisionAcceptsMM(), "mm_token_type_ids", True),+]+++def test_generate_kwarg_gate():+ for name, model, key, expected in CASES:+ got = accepts(model, key)+ assert got is expected, f"{name}: got {got}, expected {expected}"+++if __name__ == "__main__":+ test_generate_kwarg_gate()+ for name, _, _, _ in CASES:+ print(f" [PASS] {name}")+ print("OK: generate-kwarg gate behaves like transformers _validate_model_kwargs")diff --git a/tests/test_offload_embedding_hooks.py b/tests/test_offload_embedding_hooks.pynew file mode 100644index 00000000000..b8be603b2ae--- /dev/null+++ b/tests/test_offload_embedding_hooks.py@@ -0,0 +1,129 @@+"""Tests _install_offload_embedding_hooks in vision.py: the offloaded lookup must work and+its output must land on the decoder device, read live from the output embeddings (lm_head)+so it tracks model.to() moves. CUDA cases skip without a GPU."""++import ast, os+import torch+import torch.nn as nn++HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+VISION = os.path.join(HERE, "unsloth", "models", "vision.py")+++def _load_installer():+ src = open(VISION).read()+ mod = ast.parse(src)+ for node in mod.body:+ if isinstance(node, ast.FunctionDef) and node.name == "_install_offload_embedding_hooks":+ ns = {"torch": torch}+ exec(ast.get_source_segment(src, node), ns)+ return ns["_install_offload_embedding_hooks"]+ raise AssertionError("_install_offload_embedding_hooks not found in vision.py")+++install = _load_installer()+CPU = torch.device("cpu")+++def _emb():+ return nn.Embedding(32, 8)+++def _lm_head(device):+ # Stand-in decoder reference (untied lm_head) whose weight device is the target.+ return nn.Linear(8, 32, bias = False).to(device)+++def test_install_and_idempotent():+ emb = _emb()+ lm = _lm_head(CPU)+ assert install(emb, lm, CPU) is True+ assert emb._unsloth_offload_hooks_installed is True+ n_pre = len(emb._forward_pre_hooks)+ n_post = len(emb._forward_hooks)+ assert install(emb, lm, CPU) is True+ assert len(emb._forward_pre_hooks) == n_pre and len(emb._forward_hooks) == n_post+ assert install(None, lm, CPU) is False+++def test_cpu_noop_forward():+ # cpu weight + cpu decoder + cpu input -> output stays cpu.+ emb = _emb()+ install(emb, _lm_head(CPU), CPU)+ out = emb(torch.randint(0, 32, (2, 5)))+ assert out.shape == (2, 5, 8)+ assert out.device.type == "cpu"+++def test_cuda_input_roundtrip():+ if not torch.cuda.is_available():+ print("[SKIP] CUDA not available")+ return+ # CPU weight, CUDA decoder + input -> lookup on cpu, output back on cuda.+ emb = _emb().to("cpu")+ install(emb, _lm_head("cuda"), torch.device("cuda"))+ out = emb(torch.randint(0, 32, (2, 5), device = "cuda"))+ assert out.device.type == "cuda", out.device+++def test_cpu_input_still_returns_to_decoder():+ if not torch.cuda.is_available():+ print("[SKIP] CUDA not available")+ return+ # P1: offload makes the input arrive on cpu; the output must still reach the cuda decoder.+ emb = _emb().to("cpu")+ install(emb, _lm_head("cuda"), torch.device("cuda"))+ out = emb(torch.randint(0, 32, (2, 5), device = "cpu"))+ assert out.device.type == "cuda", out.device+++def test_live_decoder_over_stale_fallback():+ if not torch.cuda.is_available():+ print("[SKIP] CUDA not available")+ return+ # P2: fallback captured as cpu (model loaded on cpu), but the decoder later lives on cuda.+ # The output must follow the live lm_head device, not the stale cpu fallback.+ emb = _emb().to("cpu")+ install(emb, _lm_head("cuda"), CPU)+ out = emb(torch.randint(0, 32, (2, 5), device = "cuda"))+ assert out.device.type == "cuda", out.device+++def test_meta_lm_head_falls_back():+ # A disk-offloaded (meta) lm_head must not be used as the return device: moving hidden+ # states to meta is unrecoverable, so fall back to the captured device. No GPU needed.+ emb = _emb().to("cpu")+ lm = _lm_head(CPU)+ lm.weight = nn.Parameter(lm.weight.to("meta"))+ install(emb, lm, CPU)+ out = emb(torch.randint(0, 32, (2, 5)))+ assert out.device.type == "cpu", out.device+++def test_cuda_weight_pulled_back_to_gpu():+ if not torch.cuda.is_available():+ print("[SKIP] CUDA not available")+ return+ # bf16 weight later pulled back to gpu + cuda input -> no-op, stays on cuda.+ emb = _emb().to("cuda")+ install(emb, _lm_head("cuda"), torch.device("cuda"))+ out = emb(torch.randint(0, 32, (2, 5), device = "cuda"))+ assert out.device.type == "cuda", out.device+++if __name__ == "__main__":+ test_install_and_idempotent()+ print("[PASS] install + idempotent")+ test_cpu_noop_forward()+ print("[PASS] cpu no-op forward")+ test_cuda_input_roundtrip()+ print("[PASS] cuda input roundtrip")+ test_cpu_input_still_returns_to_decoder()+ print("[PASS] cpu input still returns to cuda decoder (P1)")+ test_live_decoder_over_stale_fallback()+ print("[PASS] live decoder device beats stale fallback (P2)")+ test_meta_lm_head_falls_back()+ print("[PASS] meta lm_head falls back to captured device (P2)")+ test_cuda_weight_pulled_back_to_gpu()+ print("[PASS] cuda weight-on-gpu no-op")+ print("OK: offloaded embedding output always lands on the live decoder device")diff --git a/tests/test_offload_tied_guard.py b/tests/test_offload_tied_guard.pynew file mode 100644index 00000000000..096fba116db--- /dev/null+++ b/tests/test_offload_tied_guard.py@@ -0,0 +1,62 @@+"""Tests _embeddings_are_tied in vision.py: offload_embedding must detect a shared+embed_tokens/lm_head weight so the loader can refuse to offload tied embeddings+(offloading would strand the output projection on CPU). No GPU needed."""++import ast, os+import torch+import torch.nn as nn++HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+VISION = os.path.join(HERE, "unsloth", "models", "vision.py")+++def _load_fn():+ src = open(VISION).read()+ mod = ast.parse(src)+ for node in mod.body:+ if isinstance(node, ast.FunctionDef) and node.name == "_embeddings_are_tied":+ ns = {"torch": torch}+ exec(ast.get_source_segment(src, node), ns)+ return ns["_embeddings_are_tied"]+ raise AssertionError("_embeddings_are_tied not found in vision.py")+++tied = _load_fn()+++def test_untied_separate_weights():+ emb = nn.Embedding(32, 8)+ lm = nn.Linear(8, 32, bias = False)+ assert tied(emb, lm) is False+++def test_tied_shared_parameter():+ emb = nn.Embedding(32, 8)+ lm = nn.Linear(8, 32, bias = False)+ lm.weight = emb.weight # transformers-style weight tying+ assert tied(emb, lm) is True+++def test_tied_by_storage_even_if_distinct_parameter():+ emb = nn.Embedding(32, 8)+ lm = nn.Linear(8, 32, bias = False)+ lm.weight = nn.Parameter(emb.weight.detach()) # distinct Parameter, shared storage+ assert tied(emb, lm) is True+++def test_none_output_is_untied():+ emb = nn.Embedding(32, 8)+ assert tied(emb, None) is False+ assert tied(None, nn.Linear(8, 32)) is False+++if __name__ == "__main__":+ test_untied_separate_weights()+ print("[PASS] untied separate weights -> False")+ test_tied_shared_parameter()+ print("[PASS] tied shared parameter -> True")+ test_tied_by_storage_even_if_distinct_parameter()+ print("[PASS] tied by storage -> True")+ test_none_output_is_untied()+ print("[PASS] missing lm_head -> untied (safe to offload)")+ print("OK: tied embeddings are detected so offload_embedding can refuse them")diff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex bdc2bd9ef62..5ab55152db1 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -238,6 +238,71 @@ def _attach_bnb_multidevice_hooks(global NUM_LOGITS_TO_KEEPNUM_LOGITS_TO_KEEP = dict()++def _unsloth_generate_accepts_kwarg(model, key):+ # True if the top level accepts this generate kwarg (some models expose it on an inner forward only).+ try:+ model_args = set(inspect.signature(model.prepare_inputs_for_generation).parameters)+ except (TypeError, ValueError, AttributeError):+ model_args = set()+ if "kwargs" in model_args or "model_kwargs" in model_args:+ try:+ model_args |= set(inspect.signature(model.forward).parameters)+ except (TypeError, ValueError, AttributeError):+ pass+ return key in model_args+++def _install_offload_embedding_hooks(embed_tokens, output_embeddings, return_device):+ # Lookup runs on the weight's current device (CPU when offloaded); the output returns to the+ # decoder device read live from output_embeddings (lm_head, untied here) so it tracks+ # model.to() moves. A meta (disk-offloaded) or missing lm_head falls back to return_device.+ if embed_tokens is None:+ return False+ if getattr(embed_tokens, "_unsloth_offload_hooks_installed", False):+ return True++ def _decoder_device():+ weight = getattr(output_embeddings, "weight", None)+ if weight is not None and weight.device.type != "meta":+ return weight.device+ return return_device++ def _unsloth_offload_pre_hook(module, args):+ if not args:+ return args+ inp = args[0]+ if not hasattr(inp, "device"):+ return args+ weight = getattr(module, "weight", None)+ target = weight.device if weight is not None else _decoder_device()+ if target is None or inp.device == target:+ return args+ return (inp.to(target),) + tuple(args[1:])++ def _unsloth_offload_post_hook(module, args, output):+ target = _decoder_device()+ if target is not None and hasattr(output, "device") and output.device != target:+ return output.to(target)+ return output++ embed_tokens.register_forward_pre_hook(_unsloth_offload_pre_hook, prepend = True)+ embed_tokens.register_forward_hook(_unsloth_offload_post_hook, prepend = True)+ embed_tokens._unsloth_offload_hooks_installed = True+ return True+++def _embeddings_are_tied(input_embeddings, output_embeddings):+ # Tied lm_head reuses this weight; offloading to CPU would strand the output projection.+ if input_embeddings is None or output_embeddings is None:+ return False+ w_in = getattr(input_embeddings, "weight", None)+ w_out = getattr(output_embeddings, "weight", None)+ if w_in is None or w_out is None:+ return False+ return w_in is w_out or w_in.data_ptr() == w_out.data_ptr()++VLLM_SUPPORTED_VLM = ["qwen2_5_vl","gemma3",@@ -321,6 +386,13 @@ def unsloth_base_fast_generate(self, *args, **kwargs):kwargs.pop("token_type_ids", None)# kwargs.pop("token_type_ids", None)+ # Vision processors emit mm_token_type_ids that generate() rejects (Qwen3-VL); unlike+ # logits_to_keep it is an incoming kwarg, so drop it when generate does not accept it.+ if "mm_token_type_ids" in kwargs and not _unsloth_generate_accepts_kwarg(+ self, "mm_token_type_ids"+ ):+ kwargs.pop("mm_token_type_ids", None)+# VLMs do not allow logits_to_keepglobal NUM_LOGITS_TO_KEEPif arch not in NUM_LOGITS_TO_KEEP:@@ -339,7 +411,7 @@ def unsloth_base_fast_generate(self, *args, **kwargs):if arch not in NUM_LOGITS_TO_KEEP:NUM_LOGITS_TO_KEEP[arch] = Nonekey = NUM_LOGITS_TO_KEEP[arch]- if key is not None and key not in kwargs:+ if key is not None and key not in kwargs and _unsloth_generate_accepts_kwarg(self, key):kwargs[key] = 1model_eos_token_id = getattr(self.config, "eos_token_id", None)@@ -1024,6 +1096,12 @@ class FastBaseModel:raise_handler = RaiseUninitialized()try:+ if offload_embedding and fast_inference:+ # vLLM manages its own weights; embedding offload does not apply.+ print(+ "Unsloth: Not offloading embeddings; incompatible with fast_inference (vLLM)."+ )+ offload_embedding = Falseif not fast_inference:# Prevent load_in_fp8 from being forwarded into HF internal model loadingload_in_fp8 = kwargs.pop("load_in_fp8", None)@@ -1070,21 +1148,26 @@ class FastBaseModel:passelse:embed_tokens = model.get_input_embeddings()+ out_embed = (+ model.get_output_embeddings()+ if hasattr(model, "get_output_embeddings")+ else None+ )+ if _embeddings_are_tied(embed_tokens, out_embed):+ raise NotImplementedError(+ "offload_embedding = True is not supported for models with tied word "+ "embeddings (embed_tokens shares its weight with lm_head). Offloading "+ "would strand the output projection on CPU and saves no VRAM. Set "+ "offload_embedding = False for this model."+ )nbytes = embed_tokens.weight.numel() * embed_tokens.weight.itemsizengb = round(nbytes / 1024 / 1024 / 1024, 2)print(f"Unsloth: Offloading embeddings to RAM to save {ngb} GB.")+ _embed_device = embed_tokens.weight.device # decoder device, before offloadembed_tokens.to("cpu")- # Add hooks to move inputs to CPU and back to CUDA- # [TODO] Doesn't seem to work!- # def pre_hook(module, args):- # args[0]._old_device = args[0].device- # return (args[0].to("cpu", non_blocking = True))- # def post_hook(module, args, output):- # old_device = getattr(args[0], "_old_device", "cuda")- # return output.to(old_device, non_blocking = True)- # embed_tokens.register_forward_pre_hook(pre_hook, prepend = True)- # embed_tokens.register_forward_hook (post_hook, prepend = True)+ # Device-safe embedding offload.+ _install_offload_embedding_hooks(embed_tokens, out_embed, _embed_device)# Must free GPU memory otherwise will not free!torch.cuda.empty_cache()gc.collect()