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
Cast float32 activations into the float16 projections of Falcon-H1 / Nemotron-H fp16 loads (#14532)
Daniel Hanc4b4a35d7239
diff --git a/tests/test_custom_dtype_linear_input_cast.py b/tests/test_custom_dtype_linear_input_cast.pynew file mode 100644index 00000000000..431a0f7ea24--- /dev/null+++ b/tests/test_custom_dtype_linear_input_cast.py@@ -0,0 +1,100 @@+# SPDX-License-Identifier: AGPL-3.0-only+"""Falcon-H1 / Nemotron-H fp16: float32 norm output into a float16 nn.Linear outside autocast."""++import ast+from pathlib import Path++import pytest++torch = pytest.importorskip("torch")++from unsloth.models._custom_dtype import cast_mixed_linear_inputs # noqa: E402++VISION = Path(__file__).resolve().parents[1] / "unsloth" / "models" / "vision.py"+++class _Block(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.norm = torch.nn.LayerNorm(8)+ self.q_proj = torch.nn.Linear(8, 4, bias = False)+ self.in_proj = torch.nn.Linear(8, 4, bias = False)++ def forward(self, x):+ h = self.norm(x)+ return self.q_proj(h).float() + self.in_proj(h)+++def _falcon_like():+ torch.manual_seed(0)+ model = _Block().float()+ model.q_proj.to(torch.float16)+ return model+++def test_plain_forward_raises_without_the_hook():+ model = _falcon_like()+ with pytest.raises(RuntimeError, match = "dtype"):+ model(torch.randn(2, 3, 8))+++def test_hook_casts_only_the_moved_projection():+ model = _falcon_like()+ assert cast_mixed_linear_inputs(model, torch.float32) == 1+ assert getattr(model.q_proj, "_unsloth_casts_input_dtype", False)+ assert not getattr(model.in_proj, "_unsloth_casts_input_dtype", False)+ x = torch.randn(2, 3, 8)+ out = model(x)+ h = model.norm(x)+ ref = (h.to(torch.float16) @ model.q_proj.weight.t()).float() + model.in_proj(h)+ torch.testing.assert_close(out, ref, rtol = 0, atol = 0)+++def test_hook_is_idempotent():+ model = _falcon_like()+ assert cast_mixed_linear_inputs(model, torch.float32) == 1+ assert cast_mixed_linear_inputs(model, torch.float32) == 0+ assert len(model.q_proj._forward_pre_hooks) == 1+++def test_matching_dtypes_and_integer_inputs_are_untouched():+ model = _falcon_like()+ cast_mixed_linear_inputs(model, torch.float32)+ hook = next(iter(model.q_proj._forward_pre_hooks.values()))+ x16 = torch.randn(2, 8, dtype = torch.float16)+ assert hook(model.q_proj, (x16,)) is None+ assert hook(model.q_proj, (torch.ones(2, 8, dtype = torch.long),)) is None+ assert hook(model.q_proj, ()) is None+++def test_autocast_is_left_to_do_the_cast():+ model = _falcon_like()+ cast_mixed_linear_inputs(model, torch.float32)+ hook = next(iter(model.q_proj._forward_pre_hooks.values()))+ x32 = torch.randn(2, 8)+ with torch.autocast("cpu", dtype = torch.bfloat16):+ assert hook(model.q_proj, (x32,)) is None+ (cast,) = hook(model.q_proj, (x32,))+ assert cast.dtype == torch.float16+++def test_no_hook_when_nothing_moved_off_the_load_dtype():+ model = _Block().to(torch.float16)+ assert cast_mixed_linear_inputs(model, torch.float16) == 0+++def test_vision_loader_hooks_after_the_custom_dtype_code():+ tree = ast.parse(VISION.read_text())+ for node in ast.walk(tree):+ if not isinstance(node, ast.If):+ continue+ test = ast.unparse(node.test)+ if test != "custom_datatype is not None":+ continue+ body = ast.unparse(node)+ if "exec(custom_datatype)" not in body:+ continue+ assert "cast_mixed_linear_inputs(model, torch_dtype)" in body+ assert body.index("exec(custom_datatype)") < body.index("cast_mixed_linear_inputs(")+ return+ pytest.fail("custom_datatype exec block not found in vision.py")diff --git a/unsloth/models/_custom_dtype.py b/unsloth/models/_custom_dtype.pyindex 1476e6cd2f7..f87fa15698f 100644--- a/unsloth/models/_custom_dtype.py+++ b/unsloth/models/_custom_dtype.py@@ -25,6 +25,7 @@ __all__ = ["neutralize_inherited_custom_dtype","resolve_dtype","DTYPE_ALIASES",+ "cast_mixed_linear_inputs",]import os@@ -122,5 +123,49 @@ def trusted_custom_dtype():return value, value in _REGISTERED+def _autocast_enabled(device_type):+ try:+ return torch.is_autocast_enabled(device_type)+ except TypeError:+ # torch < 2.4 takes no device argument and answers for CUDA only.+ return torch.is_autocast_enabled()+++def _cast_input_to_weight_dtype(module, args):+ if not args:+ return None+ x = args[0]+ weight = module.weight+ if (+ not isinstance(x, torch.Tensor)+ or not x.is_floating_point()+ or x.dtype == weight.dtype+ or _autocast_enabled(x.device.type)+ ):+ return None+ return (x.to(weight.dtype),) + tuple(args[1:])+++def cast_mixed_linear_inputs(model, load_dtype):+ """Outside autocast, cast inputs of Linears moved off load_dtype (Falcon-H1 / Nemotron-H fp16) to the weight dtype."""+ hooked = 0+ for module in model.modules():+ if not isinstance(module, torch.nn.Linear) or getattr(+ module, "_unsloth_casts_input_dtype", False+ ):+ continue+ weight = getattr(module, "weight", None)+ if (+ not isinstance(weight, torch.Tensor)+ or not weight.is_floating_point()+ or weight.dtype == load_dtype+ ):+ continue+ module.register_forward_pre_hook(_cast_input_to_weight_dtype)+ module._unsloth_casts_input_dtype = True+ hooked += 1+ return hooked++# On import, before either package reads the variable.neutralize_inherited_custom_dtype()diff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex 4f32ba7f2f6..856aca0f260 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -137,7 +137,7 @@ from ._utils import _ignore_block_swap_params_for_ddpfrom ._uma_safetensors import is_integrated_unified_memory_gpufrom ._utils import estimate_training_reserve_bytes as _zoo_reserve_estimatefrom ._remote_code_buffers import restore_remote_code_non_persistent_buffers-from ._custom_dtype import resolve_dtype, trusted_custom_dtype+from ._custom_dtype import cast_mixed_linear_inputs, resolve_dtype, trusted_custom_dtypefrom .remote_code_shims import apply_remote_code_shimsfrom .grouped_linear_lora import register_grouped_linear_lorafrom .loader_utils import (@@ -4203,6 +4203,7 @@ class FastBaseModel:with torch.no_grad():for jj, (name, module) in enumerate(model.named_modules()):exec(custom_datatype)+ cast_mixed_linear_inputs(model, torch_dtype)for _ in range(3):gc.collect()clean_gpu_cache()