From fdd69062668bd1ef95cdbdbab2b67d46ab4e9f4e Mon Sep 17 00:00:00 2001 From: Daniel Han <23090290+danielhanchen@users.noreply.github.com> Date: Fri, 27 Nov 2026 03:59:25 -0800 Subject: [PATCH 1/8] LoRA: opt-in rotated int8 frozen base for consumer Blackwell (UNSLOTH_LORA_BASE_INT8=1) The frozen base GEMMs of a LoRA linear (forward and input gradient) run as int8 on a block-Hadamard rotated weight with per-token int8 activations, through the fp8 LoRA plumbing (attach, master offload, merge, save) and Unsloth's fused LoRA kernels. On an RTX 5090 the int8 GEMM is 3x a bf16 GEMM and 1.5x fp8. Off by default; refused on sm75 / sm80 / sm89 / ROCm where the Triton int8 tiles were measured slower than bf16; models narrower than hidden size 2048 and calls under 2048 rows stay 16 bit. --- tests/test_int8_lora_cuda.py | 229 ++++++++++ tests/test_int8_lora_recipe.py | 144 ++++++ unsloth/kernels/int8_lora.py | 723 ++++++++++++++++++++++++++++++ unsloth/models/float8_training.py | 110 ++++- unsloth/models/loader.py | 11 + unsloth/precision/recipes.py | 40 ++ 6 files changed, 1250 insertions(+), 7 deletions(-) create mode 100644 tests/test_int8_lora_cuda.py create mode 100644 tests/test_int8_lora_recipe.py create mode 100644 unsloth/kernels/int8_lora.py diff --git a/tests/test_int8_lora_cuda.py b/tests/test_int8_lora_cuda.py new file mode 100644 index 000000000000..06ce78478266 --- /dev/null +++ b/tests/test_int8_lora_cuda.py @@ -0,0 +1,229 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. + +"""Rotated INT8 frozen-base LoRA GEMMs (kernels/int8_lora.py) against fp64 references, on a CUDA GPU.""" + +import math + +import pytest +import torch + +from real_accelerator import has_real_cuda + +pytestmark = [ + pytest.mark.gpu, + pytest.mark.skipif( + not has_real_cuda() + or torch.version.hip is not None + or torch.cuda.get_device_capability() < (8, 0), + reason = "needs an NVIDIA GPU with int8 tensor cores", + ), +] + +IL = pytest.importorskip("unsloth.kernels.int8_lora") +if IL.triton is None: + pytest.skip("needs Triton", allow_module_level = True) + + +def _h(device): + return IL._hadamard_pm1(device, torch.float64) / math.sqrt(IL.GROUP) + + +def _rot(t, H): + n, k = t.shape + return (t.double().view(n, k // IL.GROUP, IL.GROUP) @ H).view(n, k) + + +def _rowq(t): + amax = t.abs().amax(1).clamp_min(1e-30) + return torch.round(t * (127.0 / amax)[:, None]).clamp(-127, 127), amax / 127.0 + + +def _inputs( + M, + N, + K, + dtype, + seed = 0, +): + g = torch.Generator(device = "cuda").manual_seed(seed) + x = torch.randn((M, K), device = "cuda", generator = g) + cols = torch.randperm(K, device = "cuda", generator = g)[: max(1, K // 64)] + x[:, cols] *= 20.0 # outlier channels, as in post-norm LLM activations + w = torch.randn((N, K), device = "cuda", generator = g) * 0.02 + dy = ( + torch.randn((M, N), device = "cuda", generator = g) + * torch.rand((M, 1), device = "cuda", generator = g) + * 1e-3 + ) + return x.to(dtype), w.to(dtype), dy.to(dtype) + + +def _emulate_fwd(x, wq, ws, H): + # The algorithm in fp64: rotated per-token codes of x, the weight's codes and scales, one fp64 GEMM. + xq, xs = _rowq(_rot(x, H)) + return (xq @ wq.double().t()) * xs[:, None] * ws.double()[None, :] + + +def _emulate_dgrad(dy, wq, ws, H): + dq, ds = _rowq(dy.double() * ws.double()[None, :]) + rot = (dq @ wq.double()) * ds[:, None] + n, k = rot.shape + return (rot.view(n, k // IL.GROUP, IL.GROUP) @ H.t()).view(n, k) + + +def _rel(a, b): + return float((a.double() - b).norm() / b.norm()) + + +SHAPES = [ + (1024, 512, 2048), + (2048, 1024, 4096), + (1000, 768, 1024), + (4096, 4096, 4096), + (256, 2048, 768 + 128 * 2), +] + + +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16]) +@pytest.mark.parametrize("M,N,K", SHAPES) +def test_forward_and_dgrad_match_fp64(M, N, K, dtype): + x, w, dy = _inputs(M, N, K, dtype) + H = _h(x.device) + wq, ws = IL.quantize_weight(w) + IL.clear_int8_lora_cache() + y = IL.int8_lora_fwd(x, wq, ws) + dx = IL.int8_lora_dgrad(dy, wq, ws, None, None) + dx_cached = IL.int8_lora_dgrad(dy, wq, ws, wq.t().contiguous(), None) + assert torch.equal(dx, dx_cached) + assert y.dtype == dtype and dx.dtype == dtype and y.shape == (M, N) and dx.shape == (M, K) + # Same algorithm in fp64: only code ties and the fp32 epilogue differ. + emu_y = _emulate_fwd(x, wq, ws, H) + emu_dx = _emulate_dgrad(dy, wq, ws, H) + assert _rel(y, emu_y) < 4e-3, _rel(y, emu_y) + assert _rel(dx, emu_dx) < 4e-3, _rel(dx, emu_dx) + # Against the exact 16-bit linear: the quantization error itself, bounded. + ref_y = x.double() @ w.double().t() + ref_dx = dy.double() @ w.double() + assert _rel(y, ref_y) < 0.03, _rel(y, ref_y) + assert _rel(dx, ref_dx) < 0.03, _rel(dx, ref_dx) + # The dequantized weight is the matrix both GEMMs approximate. + wd = IL.dequantize_weight(wq, ws, torch.float32) + assert _rel(wd, w.double()) < 0.01 + + +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16]) +def test_epilogue_delta_is_added_once(dtype): + M, N, K = 1024, 1024, 2048 + x, w, dy = _inputs(M, N, K, dtype, seed = 1) + wq, ws = IL.quantize_weight(w) + delta = torch.randn((M, N), device = "cuda", dtype = dtype) + IL.clear_int8_lora_cache() + plain = IL.int8_lora_fwd(x, wq, ws) + fused = IL.int8_lora_fwd(x, wq, ws, delta) + assert _rel(fused, plain.double() + delta.double()) < 5e-3 + ddelta = torch.randn((M, K), device = "cuda", dtype = dtype) * 1e-3 + plain = IL.int8_lora_dgrad(dy, wq, ws, None, None) + fused = IL.int8_lora_dgrad(dy, wq, ws, None, ddelta) + assert _rel(fused, plain.double() + ddelta.double()) < 5e-3 + + +def test_negative_controls_fail(): + """Flip checks: an unrotated activation, or a dgrad without the epilogue un-rotation, must be caught.""" + M, N, K = 1024, 1024, 2048 + x, w, dy = _inputs(M, N, K, torch.bfloat16, seed = 2) + H = _h(x.device) + wq, ws = IL.quantize_weight(w) + ref_y = x.double() @ w.double().t() + xq, xs = _rowq(x.double()) # no rotation of x + wrong = (xq @ wq.double().t()) * xs[:, None] * ws.double()[None, :] + assert _rel(wrong, ref_y) > 0.5 + dq, ds = _rowq(dy.double() * ws.double()[None, :]) + wrong_dx = (dq @ wq.double()) * ds[:, None] # rotated space, never un-rotated + assert _rel(wrong_dx, dy.double() @ w.double()) > 0.5 + # and the kernel output differs from those wrong answers by the same margin + IL.clear_int8_lora_cache() + assert _rel(IL.int8_lora_fwd(x, wq, ws), wrong) > 0.5 + + +def test_activation_quant_is_shared_and_invalidated(): + M, K = 2048, 4096 + x = torch.randn((2, M // 2, K), device = "cuda", dtype = torch.bfloat16) + IL.clear_int8_lora_cache() + IL.reset_int8_lora_stats() + a = IL.quantize_x(x.view(-1, K)) + b = IL.quantize_x(x.view(-1, K)) # q / k / v: new views of the same input + assert IL.INT8_LORA_STATS["x_quant"] == 2 and IL.INT8_LORA_STATS["x_quant_shared"] == 1 + assert a[0] is b[0] + x.mul_(2.0) # an in-place write bumps the version: must requantize + c = IL.quantize_x(x.view(-1, K)) + assert IL.INT8_LORA_STATS["x_quant_shared"] == 1 + assert torch.allclose(c[1], a[1] * 2.0, rtol = 1e-6) + y = x.view(-1, K).clone() # equal values, different tensor: requantized, not shared + IL.quantize_x(y) + assert IL.INT8_LORA_STATS["x_quant_shared"] == 1 + with torch.inference_mode(): + z = torch.randn((M, K), device = "cuda", dtype = torch.bfloat16) + IL.quantize_x(z) + IL.quantize_x(z) + assert IL.INT8_LORA_STATS["x_quant_shared"] == 1 + IL.clear_int8_lora_cache() + + +def test_state_routes_and_row_gate(monkeypatch): + lin = torch.nn.Linear( + 2048, 1024, bias = False, device = "cuda", dtype = torch.bfloat16 + ).requires_grad_(False) + state = IL.attach_int8_lora_base(lin, offload = False) + assert isinstance(state, IL.Int8LoRABaseState) and state.wq.dtype == torch.int8 + IL.reset_int8_lora_stats() + x = torch.randn((4, 512, 2048), device = "cuda", dtype = torch.bfloat16, requires_grad = True) + y = lin(x) + y.float().square().mean().backward() + assert IL.INT8_LORA_STATS["fwd"] == 1 and IL.INT8_LORA_STATS["dgrad"] == 1 + ref = x.detach().double() @ lin.weight.double().t() + assert _rel(y.detach(), ref.view(4, 512, -1)) < 0.03 + # Below the row floor the 16-bit GEMM runs (kill-switch arm: 0 int8 calls). + monkeypatch.setattr(IL, "_MIN_ROWS", 10**9) + IL.reset_int8_lora_stats() + y2 = lin(x) + assert IL.INT8_LORA_STATS["fwd"] == 0 and IL.INT8_LORA_STATS["fwd_16bit"] == 1 + assert torch.equal(y2, torch.nn.functional.linear(x, lin.weight)) + IL.clear_int8_lora_cache() + + +def test_offloaded_master_dense_matches_dequant(): + lin = torch.nn.Linear( + 1024, 512, bias = False, device = "cuda", dtype = torch.bfloat16 + ).requires_grad_(False) + w = lin.weight.detach().clone() + state = IL.attach_int8_lora_base(lin, offload = True) + assert state.offloaded and lin.weight.device.type == "cpu" + dense = state._dense(None) + assert dense.device.type == "cuda" and _rel(dense.float(), w.double()) < 0.01 + state.restore(lin) + assert torch.equal(lin.weight, w) + + +def test_compiled_fullgraph_no_breaks(): + from torch._dynamo.utils import counters + + lin = torch.nn.Linear( + 2048, 1024, bias = False, device = "cuda", dtype = torch.bfloat16 + ).requires_grad_(False) + state = IL.attach_int8_lora_base(lin, offload = False) + + def f(x): + y = state.matmul(x, lin.weight) + return state.dgrad(y.to(x.dtype), lin.weight) + + x = torch.randn((2048, 2048), device = "cuda", dtype = torch.bfloat16) + IL.clear_int8_lora_cache() + eager = f(x) + torch._dynamo.reset() + counters.clear() + compiled = torch.compile(f, fullgraph = True) + out = compiled(x) + out = compiled(x) + assert sum(counters["graph_break"].values()) == 0 + assert torch.equal(out, eager) diff --git a/tests/test_int8_lora_recipe.py b/tests/test_int8_lora_recipe.py new file mode 100644 index 000000000000..1c855297dbbc --- /dev/null +++ b/tests/test_int8_lora_recipe.py @@ -0,0 +1,144 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. + +"""The opt-in rotated int8 LoRA base (UNSLOTH_LORA_BASE_INT8=1): registry entry, request resolution and refusals. +CPU only; the kernels themselves are covered by test_int8_lora_cuda.py.""" + +import pytest +import torch + +from unsloth import precision as P +from unsloth.models import float8_training as f8t + + +def test_registry_entry(): + r = P.get_recipe("int8_lora_rotated") + assert r.kind == "frozen_base" and r.modes == ("lora",) and r.compile == "opaque" + assert r.gate("sm120").status == "explicit" and r.gate("sm120").evidence + for gpu in ("sm75", "sm80", "sm89", "rocm"): + assert r.gate(gpu).status == "refused" and r.gate(gpu).reason + # opt-in only: never picked by name + assert r.gate("sm120").status != "named" + + +@pytest.mark.parametrize( + "value, on", [("1", True), ("true", True), ("on", True), ("0", False), ("", False)] +) +def test_env_request(monkeypatch, value, on): + monkeypatch.setenv("UNSLOTH_LORA_BASE_INT8", value) + assert f8t.int8_lora_requested() is on + assert f8t.float8_training_request(None) == ("int8_lora" if on else None) + assert f8t.float8_training_request(False) == ("int8_lora" if on else False) + # an explicit float8_training wins, and full finetuning never takes the LoRA base + assert f8t.float8_training_request("fp8_lora") == "fp8_lora" + assert f8t.float8_training_request(None, full_finetuning = True) is None + + +def test_env_unset_changes_nothing(monkeypatch): + monkeypatch.delenv("UNSLOTH_LORA_BASE_INT8", raising = False) + assert f8t.float8_training_request(None) is None + assert f8t.float8_training_request(True) is True + + +@pytest.mark.parametrize( + "kw", + [ + dict(load_in_4bit = True), + dict(load_in_8bit = True), + dict(load_in_fp8 = True), + dict(qat_scheme = "int4"), + ], +) +def test_refuses_quantized_or_qat_bases(kw): + args = dict( + dtype = torch.bfloat16, + load_in_4bit = False, + load_in_8bit = False, + load_in_fp8 = False, + qat_scheme = None, + gpu = "sm120", + ) + args.update(kw) + with pytest.raises(P.PrecisionRefused): + f8t.resolve_fp8_lora("int8_lora", **args) + + +@pytest.mark.parametrize("gpu", ["sm80", "sm89", "sm75"]) +def test_refuses_where_measured_slower(monkeypatch, gpu): + import unsloth.kernels.int8_lora as IL + monkeypatch.setattr(IL, "int8_lora_supported", lambda device: None) + with pytest.raises(P.PrecisionRefused, match = "refused"): + f8t.resolve_fp8_lora("int8_lora", dtype = torch.bfloat16, gpu = gpu) + + +def test_resolves_on_sm120(monkeypatch): + import unsloth.kernels.int8_lora as IL + + monkeypatch.setattr(IL, "int8_lora_supported", lambda device: None) + assert ( + f8t.resolve_fp8_lora("int8_lora", dtype = torch.bfloat16, gpu = "sm120") == "int8_lora_rotated" + ) + assert f8t.is_int8_lora_recipe("int8_lora_rotated") + assert not f8t.is_int8_lora_recipe("fp8_lora_rowwise") + + +def test_refuses_without_triton(monkeypatch): + import unsloth.kernels.int8_lora as IL + monkeypatch.setattr(IL, "int8_lora_supported", lambda device: "Triton is not installed") + with pytest.raises(P.PrecisionRefused, match = "Triton"): + f8t.resolve_fp8_lora("int8_lora", dtype = torch.bfloat16, gpu = "sm120") + + +def test_eligibility_needs_rotation_block(): + import unsloth.kernels.int8_lora as IL + + ok = torch.nn.Linear(256, 64, bias = False, dtype = torch.bfloat16).requires_grad_(False) + assert IL.eligible_base(ok) is None + odd = torch.nn.Linear(272, 64, bias = False, dtype = torch.bfloat16).requires_grad_(False) + assert "multiple of 128" in IL.eligible_base(odd) + trainable = torch.nn.Linear(256, 64, bias = False, dtype = torch.bfloat16) + assert IL.eligible_base(trainable) is not None + + +def test_weight_quantization_round_trip_cpu(): + import unsloth.kernels.int8_lora as IL + + w = torch.randn(64, 256) * 0.02 + wq, ws = IL.quantize_weight(w) + assert wq.dtype == torch.int8 and ws.shape == (64,) + back = IL.dequantize_weight(wq, ws, torch.float32) + assert float((back - w).norm() / w.norm()) < 0.01 + + +def _tiny_lora_model(hidden): + from peft import LoraConfig, get_peft_model + + class Cfg: + hidden_size = hidden + + class Tiny(torch.nn.Module): + def __init__(self): + super().__init__() + self.config = Cfg() + self.q_proj = torch.nn.Linear(hidden, hidden, bias = False, dtype = torch.bfloat16) + + def forward(self, x): + return self.q_proj(x) + + base = Tiny().requires_grad_(False) + return get_peft_model(base, LoraConfig(r = 4, target_modules = ["q_proj"])) + + +@pytest.mark.parametrize("hidden, converts", [(1024, False), (2048, True)]) +def test_hidden_size_gate(monkeypatch, hidden, converts): + model = _tiny_lora_model(hidden) + monkeypatch.setattr(f8t, "_prepare_fp8_lora_loss", lambda m: None) + monkeypatch.setattr(f8t, "_prepare_fp8_lora_operators", lambda m: None) + converted = f8t.enable_fp8_lora(model, "int8_lora_rotated", allow_cpu = True) + assert bool(converted) is converts + states = [ + m.__dict__.get("_unsloth_fp8_lora") + for m in model.modules() + if "_unsloth_fp8_lora" in m.__dict__ + ] + assert all(type(s).__name__ == "Int8LoRABaseState" for s in states) and bool(states) is converts diff --git a/unsloth/kernels/int8_lora.py b/unsloth/kernels/int8_lora.py new file mode 100644 index 000000000000..648b23bd068d --- /dev/null +++ b/unsloth/kernels/int8_lora.py @@ -0,0 +1,723 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. + +"""Rotated INT8 frozen-base GEMMs for LoRA (opt-in: UNSLOTH_LORA_BASE_INT8=1, recipe int8_lora_rotated). + +The frozen weight is stored once as int8 codes of W @ H (H: block-diagonal Walsh-Hadamard, group 128, along the +input dim) with one fp32 scale per output row: 1 byte per weight plus the 16-bit master, which moves to host RAM +as in fp8 LoRA. Forward: per-token int8 codes of X @ H (rotation and quantization in one kernel), an int8 GEMM +with int32 accumulation and the dequant (plus the LoRA term) in its epilogue. Input gradient: dY @ W = +(dY * s) @ Q @ H, so the weight row scale folds into dY before its per-token quantization, the same int8 codes +are the second operand, and the GEMM epilogue undoes the rotation on each 128-column block. The rotation spreads +activation outliers across the block, which is what makes per-token int8 accurate enough for training. + +Same quant-state interface as fp8_lora.Fp8LoRABaseState (Unsloth's fused LoRA kernels call matmul / lora_first +/ dgrad / dgrad_accum), so attach, offload, merge and save reuse the fp8 LoRA plumbing. Consecutive projections +reading the same input (q / k / v, gate / up) share one activation quantization. +""" + +import contextlib +import math +import os +from typing import Optional + +import torch + +from . import fp8_lora as _fp8 +from .fp8_lora import ( + Fp8LoRABaseState, + _compiling, + _fp8_base_apply, + _fp8_requantize_after_load, + _is_transposed, + _launch, + _opaque_under_compile, + offload_supported, +) + +try: + import triton + import triton.language as tl +except Exception: + triton = None + +__all__ = [ + "INT8_LORA_STATS", + "Int8LoRABaseState", + "attach_int8_lora_base", + "eligible_base", + "int8_lora_fwd", + "int8_lora_dgrad", + "int8_lora_supported", + "reset_int8_lora_stats", + "GROUP", +] + +GROUP = 128 # Hadamard block along the reduction dim of the forward GEMM +INT8_LORA_STATS = { + "fwd": 0, + "dgrad": 0, + "fwd_16bit": 0, + "dgrad_16bit": 0, + "quantize": 0, + "x_quant": 0, # eager activation-quant requests + "x_quant_shared": 0, # of those, served by the previous projection's quantization + "x_quant_kernel": 0, # activation quantizations actually run (eager and compiled) +} +# Below this many rows (tokens in the call) the activation quantization costs more than the int8 GEMM saves +# (RTX PRO 6000, Qwen3 / Llama layers): those calls run the 16-bit GEMM on the 16-bit (or dequantized) weight. +_MIN_ROWS = int(os.environ.get("UNSLOTH_INT8_LORA_MIN_ROWS", "2048")) +# Models narrower than this convert nothing: at hidden size 1024 (Qwen3-0.6B) every layer measured slower than +# bf16 even at 16k tokens, since the quantization pass is not amortized over enough output columns. +MIN_HIDDEN = int(os.environ.get("UNSLOTH_INT8_LORA_MIN_HIDDEN", "2048")) +_SHARE_XQ = os.environ.get("UNSLOTH_INT8_LORA_SHARE_XQ", "1") != "0" +# Keep the transposed int8 weight for the input gradient (+1 byte per weight) instead of transposing per call. +_CACHE_T = os.environ.get("UNSLOTH_INT8_LORA_CACHE_T", "0") == "1" +_MULTI_GPU = torch.cuda.is_available() and torch.cuda.device_count() > 1 +# Tile (BLOCK_M, BLOCK_N, BLOCK_K, GROUP_M, warps, stages): fastest on an RTX 5090 and an RTX PRO 6000. +_TILE = (128, 128, 64, 8, 4, 4) +_DGRAD_TILE = ( + 128, + 64, + 8, + 4, + 4, +) # BLOCK_M, BLOCK_R (reduction), GROUP_M, warps, stages; output block = GROUP +_ROTQ_ROWS = 16 + + +def reset_int8_lora_stats(): + for key in INT8_LORA_STATS: + INT8_LORA_STATS[key] = 0 + + +def _count(key): + if not _compiling(): + INT8_LORA_STATS[key] += 1 + + +def int8_lora_supported(device) -> Optional[str]: + """None when this device can run the int8 base, else why not.""" + device = torch.device(device) + if triton is None: + return "Triton is not installed (on Windows: pip install triton-windows)" + if device.type != "cuda" or torch.version.hip is not None: + return f"needs an NVIDIA GPU (got {device})" + if torch.cuda.get_device_capability(device) < (8, 0): + return "needs int8 tensor cores with Triton int8 dot support (compute capability 8.0+)" + return None + + +_HADAMARD = {} + + +def _hadamard_pm1(device, dtype): + """The +-1 Sylvester Hadamard of order GROUP (exact in bf16 / fp32; normalized by 1 / sqrt(GROUP) elsewhere).""" + key = (device, dtype) + h = _HADAMARD.get(key) + if h is None: + m = torch.ones((1, 1), dtype = torch.float32) + while m.shape[0] < GROUP: + m = torch.cat([torch.cat([m, m], 1), torch.cat([m, -m], 1)], 0) + h = _HADAMARD[key] = m.to(device = device, dtype = dtype).contiguous() + return h + + +if triton is not None: + + @triton.jit(do_not_specialize = ["M"]) + def _int8_rotq_kernel( + x_ptr, + h_ptr, + q_ptr, + s_ptr, + M, + K, + stride_x, + G: tl.constexpr, # Hadamard block, fixed 128 + INV_SCALE: tl.constexpr, # 1 / (127 * sqrt(G)) + BLOCK_M: tl.constexpr, # rows per program, fixed 16 + ): + # q = rint(127 * (x @ H) / rowmax|x @ H|), s = rowmax / (127 * sqrt(G)): two passes over the row, the + # second one mostly from L2. + rows = tl.program_id(0).to(tl.int64) * BLOCK_M + tl.arange(0, BLOCK_M) + rmask = rows < M + g = tl.arange(0, G) + H = tl.load(h_ptr + g[:, None] * G + g[None, :]) + amax = tl.zeros((BLOCK_M,), dtype = tl.float32) + for k0 in range(0, K, G): + x = tl.load( + x_ptr + rows[:, None] * stride_x + (k0 + g)[None, :], mask = rmask[:, None], other = 0.0 + ) + xr = tl.dot(x, H) + amax = tl.maximum(amax, tl.max(tl.abs(xr), axis = 1)) + amax = tl.maximum(amax, 1e-30) + mul = 127.0 / amax + for k0 in range(0, K, G): + x = tl.load( + x_ptr + rows[:, None] * stride_x + (k0 + g)[None, :], mask = rmask[:, None], other = 0.0 + ) + xr = tl.dot(x, H) + y = tl.extra.cuda.libdevice.rint(xr * mul[:, None]) + y = tl.minimum(tl.maximum(y, -127.0), 127.0) + tl.store( + q_ptr + rows[:, None] * K + (k0 + g)[None, :], y.to(tl.int8), mask = rmask[:, None] + ) + tl.store(s_ptr + rows, amax * INV_SCALE, mask = rmask) + + @triton.jit(do_not_specialize = ["N"]) + def _int8_rowq_kernel( + x_ptr, + c_ptr, + q_ptr, + s_ptr, + N, + stride_x, + BLOCK: tl.constexpr, # columns per chunk, fixed 2048 + ): + # Per-row int8 of x * c (c: the weight's per-row scales, folded into dY for the input gradient). + row = tl.program_id(0).to(tl.int64) + offs = tl.arange(0, BLOCK) + amax = tl.zeros((BLOCK,), dtype = tl.float32) + for n0 in range(0, N, BLOCK): + mask = n0 + offs < N + x = tl.load(x_ptr + row * stride_x + n0 + offs, mask = mask, other = 0.0).to(tl.float32) + c = tl.load(c_ptr + n0 + offs, mask = mask, other = 0.0) + amax = tl.maximum(amax, tl.abs(x * c)) + rmax = tl.maximum(tl.max(amax, axis = 0), 1e-30) + mul = 127.0 / rmax + for n0 in range(0, N, BLOCK): + mask = n0 + offs < N + x = tl.load(x_ptr + row * stride_x + n0 + offs, mask = mask, other = 0.0).to(tl.float32) + c = tl.load(c_ptr + n0 + offs, mask = mask, other = 0.0) + y = tl.extra.cuda.libdevice.rint(x * c * mul) + y = tl.minimum(tl.maximum(y, -127.0), 127.0) + tl.store(q_ptr + row * N + n0 + offs, y.to(tl.int8), mask = mask) + tl.store(s_ptr + row, rmax / 127.0) + + @triton.jit(do_not_specialize = ["M"]) + def _int8_mm_kernel( + a_ptr, + b_ptr, + as_ptr, + bs_ptr, + d_ptr, + c_ptr, + M, + N, + K, + stride_d, + HAS_D: tl.constexpr, # add the LoRA term / running input gradient in the epilogue + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLOCK_K: tl.constexpr, + GROUP_M: tl.constexpr, + ): + # c[m, n] = as[m] * bs[n] * sum_k a[m, k] b[n, k] (+ d[m, n]); a, b int8 with K contiguous, K % BLOCK_K == 0. + pid = tl.program_id(0) + num_pid_m = tl.cdiv(M, BLOCK_M) + num_pid_n = tl.cdiv(N, BLOCK_N) + num_pid_in_group = GROUP_M * num_pid_n + group_id = pid // num_pid_in_group + first_pid_m = group_id * GROUP_M + group_size_m = min(num_pid_m - first_pid_m, GROUP_M) + pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m) + pid_n = (pid % num_pid_in_group) // group_size_m + offs_m = pid_m.to(tl.int64) * BLOCK_M + tl.arange(0, BLOCK_M) + offs_n = pid_n.to(tl.int64) * BLOCK_N + tl.arange(0, BLOCK_N) + rm = tl.max_contiguous(tl.multiple_of(offs_m % M, BLOCK_M), BLOCK_M) + rn = tl.max_contiguous(tl.multiple_of(offs_n % N, BLOCK_N), BLOCK_N) + offs_k = tl.arange(0, BLOCK_K) + a_ptrs = a_ptr + rm[:, None] * K + offs_k[None, :] + b_ptrs = b_ptr + rn[None, :] * K + offs_k[:, None] + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype = tl.int32) + for k in range(0, tl.cdiv(K, BLOCK_K)): + acc = tl.dot(tl.load(a_ptrs), tl.load(b_ptrs), acc, out_dtype = tl.int32) + a_ptrs += BLOCK_K + b_ptrs += BLOCK_K + xs = tl.load(as_ptr + rm) + ws = tl.load(bs_ptr + rn) + y = acc.to(tl.float32) * xs[:, None] * ws[None, :] + mask = (offs_m[:, None] < M) & (offs_n[None, :] < N) + if HAS_D: + y += tl.load( + d_ptr + offs_m[:, None] * stride_d + offs_n[None, :], mask = mask, other = 0.0 + ).to(tl.float32) + tl.store( + c_ptr + offs_m[:, None] * N + offs_n[None, :], y.to(c_ptr.dtype.element_ty), mask = mask + ) + + @triton.jit(do_not_specialize = ["M"]) + def _int8_dgrad_kernel( + a_ptr, + b_ptr, + as_ptr, + h_ptr, + d_ptr, + c_ptr, + M, + N, + K, + stride_d, + HAS_D: tl.constexpr, + INV_SQRT_G: tl.constexpr, + G: tl.constexpr, # output columns per program = the Hadamard block, fixed 128 + BLOCK_M: tl.constexpr, + BLOCK_R: tl.constexpr, # reduction (N) step + GROUP_M: tl.constexpr, + ): + # c[m, kblock] = (as[m] * sum_n a[m, n] bt[kblock, n]) @ H / sqrt(G) (+ d): a [M, N] int8 codes of dY * s, + # bt [K, N] the transposed forward int8 codes of W @ H (int8 MMA operands are K-major); the epilogue undoes + # the rotation of each 128-column block, split into two bf16 halves so the rotation keeps fp32 accuracy. + pid = tl.program_id(0) + num_pid_m = tl.cdiv(M, BLOCK_M) + num_pid_n = tl.cdiv(K, G) + num_pid_in_group = GROUP_M * num_pid_n + group_id = pid // num_pid_in_group + first_pid_m = group_id * GROUP_M + group_size_m = min(num_pid_m - first_pid_m, GROUP_M) + pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m) + pid_n = (pid % num_pid_in_group) // group_size_m + offs_m = pid_m.to(tl.int64) * BLOCK_M + tl.arange(0, BLOCK_M) + offs_k = pid_n.to(tl.int64) * G + tl.arange(0, G) + rm = tl.max_contiguous(tl.multiple_of(offs_m % M, BLOCK_M), BLOCK_M) + offs_r = tl.arange(0, BLOCK_R) + acc = tl.zeros((BLOCK_M, G), dtype = tl.int32) + for r0 in range(0, N, BLOCK_R): + rmask = r0 + offs_r < N + a = tl.load( + a_ptr + rm[:, None] * N + (r0 + offs_r)[None, :], mask = rmask[None, :], other = 0 + ) + b = tl.load( + b_ptr + offs_k[None, :] * N + (r0 + offs_r)[:, None], mask = rmask[:, None], other = 0 + ) + acc = tl.dot(a, b, acc, out_dtype = tl.int32) + y = acc.to(tl.float32) * tl.load(as_ptr + rm)[:, None] + g = tl.arange(0, G) + H = tl.load(h_ptr + g[:, None] * G + g[None, :]) + hi = y.to(tl.bfloat16) + lo = (y - hi.to(tl.float32)).to(tl.bfloat16) + z = (tl.dot(hi, H) + tl.dot(lo, H)) * INV_SQRT_G + mask = offs_m[:, None] < M + if HAS_D: + z += tl.load( + d_ptr + offs_m[:, None] * stride_d + offs_k[None, :], mask = mask, other = 0.0 + ).to(tl.float32) + tl.store( + c_ptr + offs_m[:, None] * K + offs_k[None, :], z.to(c_ptr.dtype.element_ty), mask = mask + ) + + +def _device_ctx(t): + return torch.cuda.device(t.device) if _MULTI_GPU else contextlib.nullcontext() + + +def quantize_rotated_rows(x: torch.Tensor): + """x [M, K] 16-bit (K % 128 == 0) -> (int8 codes of x @ H / sqrt(128) [M, K], fp32 per-row scales [M]).""" + M, K = x.shape + if x.stride(1) != 1: + x = x.contiguous() + q = torch.empty((M, K), device = x.device, dtype = torch.int8) + s = torch.empty((M,), device = x.device, dtype = torch.float32) + h = _hadamard_pm1(x.device, x.dtype) + with _device_ctx(x): + _launch( + _int8_rotq_kernel, + ((M + _ROTQ_ROWS - 1) // _ROTQ_ROWS,), + (x, h, q, s, M, K, x.stride(0)), + 4, + {"G": GROUP, "INV_SCALE": 1.0 / (127.0 * math.sqrt(GROUP)), "BLOCK_M": _ROTQ_ROWS}, + x.device.index, + num_warps = 4, + ) + return q, s + + +def quantize_rows_scaled(x: torch.Tensor, col_scale: torch.Tensor): + """x [M, N] 16-bit, col_scale fp32 [N] -> (int8 codes of x * col_scale per row [M, N], fp32 scales [M]).""" + M, N = x.shape + if x.stride(1) != 1: + x = x.contiguous() + q = torch.empty((M, N), device = x.device, dtype = torch.int8) + s = torch.empty((M,), device = x.device, dtype = torch.float32) + with _device_ctx(x): + _launch( + _int8_rowq_kernel, + (M,), + (x, col_scale, q, s, N, x.stride(0)), + 4, + {"BLOCK": 2048}, + x.device.index, + num_warps = 8, + ) + return q, s + + +def _mm(xq, xs, wq, ws, delta, out_dtype): + M, K = xq.shape + N = wq.shape[0] + out = torch.empty((M, N), device = xq.device, dtype = out_dtype) + bm, bn, bk, gm, warps, stages = _TILE + d = delta if delta is not None else out + with _device_ctx(xq): + _launch( + _int8_mm_kernel, + (((M + bm - 1) // bm) * ((N + bn - 1) // bn),), + (xq, wq, xs, ws, d, out, M, N, K, d.stride(0)), + 6, + { + "HAS_D": delta is not None, + "BLOCK_M": bm, + "BLOCK_N": bn, + "BLOCK_K": bk, + "GROUP_M": gm, + }, + xq.device.index, + num_warps = warps, + num_stages = stages, + ) + return out + + +def _dgrad_mm(dyq, dys, wqt, delta, out_dtype): + M, N = dyq.shape + K = wqt.shape[0] + out = torch.empty((M, K), device = dyq.device, dtype = out_dtype) + bm, br, gm, warps, stages = _DGRAD_TILE + d = delta if delta is not None else out + h = _hadamard_pm1(dyq.device, torch.bfloat16) + with _device_ctx(dyq): + _launch( + _int8_dgrad_kernel, + (((M + bm - 1) // bm) * (K // GROUP),), + (dyq, wqt, dys, h, d, out, M, N, K, d.stride(0)), + 6, + { + "HAS_D": delta is not None, + "INV_SQRT_G": 1.0 / math.sqrt(GROUP), + "G": GROUP, + "BLOCK_M": bm, + "BLOCK_R": br, + "GROUP_M": gm, + }, + dyq.device.index, + num_warps = warps, + num_stages = stages, + ) + return out + + +# One shared activation quantization: q / k / v (and gate / up) read the same X one after the other. Eager only: +# the key is the identity of the root tensor X is a view of (held, so the id cannot be reused while the entry +# lives) plus its version counter (bumped by every in-place write through any view). Traced code always +# quantizes: buffer reuse inside a compiled graph would not bump a version counter. One entry, replaced by the +# next different input. +_XQ = [None] + + +def _xq_key(x): + root = x._base if x._base is not None else x + try: + return root, ( + id(root), + x.data_ptr(), + tuple(x.shape), + tuple(x.stride()), + x.dtype, + root._version, + ) + except Exception: # inference tensors have no version counter + return root, None + + +def quantize_x(x): + """Rotated per-token int8 codes of x [M, K] (shared with the previous call on the same eager input).""" + _count("x_quant") + if not _SHARE_XQ or _compiling(): + return int8_lora_quant_x(x) + root, key = _xq_key(x) + entry = _XQ[0] + if key is not None and entry is not None and entry[0] == key: + _count("x_quant_shared") + return entry[2], entry[3] + q, s = int8_lora_quant_x(x) + _XQ[0] = (key, root, q, s) if key is not None else None + return q, s + + +def clear_int8_lora_cache(): + _XQ[0] = None + + +def _quant_x_fake(x): + return x.new_empty(x.shape, dtype = torch.int8), x.new_empty((x.shape[0],), dtype = torch.float32) + + +@_opaque_under_compile("int8_lora_quant_x", _quant_x_fake) +def int8_lora_quant_x(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + # Pure (no mutation): inside a compiled region identical calls on one input are CSE'd into one. + _count("x_quant_kernel") + return quantize_rotated_rows(x) + + +def _mm_fake(xq, xs, wq, ws, delta, out_dtype_of): + return out_dtype_of.new_empty((xq.shape[0], wq.shape[0])) + + +@_opaque_under_compile("int8_lora_mm", _mm_fake) +def int8_lora_mm( + xq: torch.Tensor, + xs: torch.Tensor, + wq: torch.Tensor, + ws: torch.Tensor, + delta: Optional[torch.Tensor], + out_dtype_of: torch.Tensor, +) -> torch.Tensor: + """Forward GEMM on quantized codes: xs * ws * (xq @ wq.T) (+ delta), in out_dtype_of.dtype.""" + _count("fwd") + return _mm(xq, xs, wq, ws, delta, out_dtype_of.dtype) + + +def int8_lora_fwd( + x, + wq, + ws, + delta = None, +): + """x [M, K] (16-bit) @ W.T (+ delta [M, N]) -> [M, N] in x.dtype, W = (wq * ws[:, None]) @ H.T.""" + xq, xs = quantize_x(x) + return int8_lora_mm(xq, xs, wq, ws, delta, x) + + +def _dgrad_fake(dy, wq, ws, wqt, delta): + return dy.new_empty((dy.shape[0], wq.shape[1])) + + +@_opaque_under_compile("int8_lora_dgrad", _dgrad_fake) +def int8_lora_dgrad( + dy: torch.Tensor, + wq: torch.Tensor, + ws: torch.Tensor, + wqt: Optional[torch.Tensor], + delta: Optional[torch.Tensor], +) -> torch.Tensor: + """dy [M, N] (16-bit) @ W (+ delta [M, K]) -> [M, K] in dy.dtype. wqt: the cached wq.T (contiguous), else + transposed here (1 byte per weight, a few percent of the GEMM).""" + _count("dgrad") + if wqt is None: + wqt = _fp8.fp8_transpose(wq) + dyq, dys = quantize_rows_scaled(dy, ws) + return _dgrad_mm(dyq, dys, wqt, delta, dy.dtype) + + +def quantize_weight(weight: torch.Tensor, rows_per_chunk: int = 4096): + """W [N, K] -> (int8 codes of W @ H / sqrt(128) per row [N, K], fp32 row scales [N]), in row chunks.""" + N, K = weight.shape + h = _hadamard_pm1(weight.device, torch.float32) / math.sqrt(GROUP) + q = torch.empty((N, K), device = weight.device, dtype = torch.int8) + s = torch.empty((N,), device = weight.device, dtype = torch.float32) + for r0 in range(0, N, rows_per_chunk): + w = weight[r0 : r0 + rows_per_chunk].float() + wr = (w.view(-1, K // GROUP, GROUP) @ h).view(-1, K) + amax = wr.abs().amax(1).clamp_min(1e-30) + q[r0 : r0 + rows_per_chunk] = ( + torch.round(wr * (127.0 / amax)[:, None]).clamp_(-127, 127).to(torch.int8) + ) + s[r0 : r0 + rows_per_chunk] = amax / 127.0 + return q, s + + +def dequantize_weight(wq: torch.Tensor, ws: torch.Tensor, dtype): + """The weight the int8 GEMMs use: (wq * ws) @ H.T, in `dtype`.""" + N, K = wq.shape + h = _hadamard_pm1(wq.device, torch.float32) / math.sqrt(GROUP) + w = (wq.float() * ws[:, None]).view(N, K // GROUP, GROUP) @ h.t() + return w.view(N, K).to(dtype) + + +class Int8LoRABaseState(Fp8LoRABaseState): + """Quant state of a frozen LoRA base on the rotated int8 GEMMs (same interface as Fp8LoRABaseState).""" + + _unsloth_packed_weight_state = True + _unsloth_fp8_dgrad = ( + True # its own input-gradient GEMM: the fused LoRA kernels call dgrad / dgrad_accum + ) + _unsloth_int8_lora = True + + def __init__(self, weight: torch.Tensor): + self.wq = self.ws = self.wqt = None + super().__init__(weight) + + def refresh(self, weight: torch.Tensor): + if _compiling(): + return self + key = self._weight_key(weight) + if key == self._key: + return self + with torch.inference_mode(False), torch.no_grad(): + w = weight.detach() + if self.offloaded: + w = w.to(self.device) + else: + self.device = w.device + self.wq, self.ws = quantize_weight(w) + self.wqt = _fp8.fp8_transpose(self.wq) if _CACHE_T else None + self.scaling = "int8_rotated" + self.dtype = weight.dtype + self._key = key + self.quantizations += 1 + _count("quantize") + return self + + def _dense(self, W): + if W is not None and not self.offloaded and W.device == self.device: + return W + dense = dequantize_weight(self.wq, self.ws, self.dtype if W is None else W.dtype) + return dense.t() if W is not None and _is_transposed(W) else dense + + def resident_bytes(self, module = None): + nbytes = sum( + t.numel() * t.element_size() for t in (self.wq, self.ws, self.wqt) if t is not None + ) + out = {"fp8": nbytes, "int8": nbytes, "master_device": 0, "master_host": 0} + if module is not None: + w = module.weight + size = w.numel() * w.element_size() + if self.offloaded: + out["master_host"] = size + elif w.device == self.device: + out["master_device"] = size + return out + + def _use_fp8(self, X): + return ( + X.dtype in (torch.bfloat16, torch.float16) + and X.numel() // max(X.shape[-1], 1) >= _MIN_ROWS + ) + + def matmul( + self, + X, + W, + out = None, + ): + shape = X.shape + X2 = X.reshape(-1, shape[-1]) + if not self._use_fp8(X2): + if _is_transposed(W): + _count("dgrad_16bit") + else: + _count("fwd_16bit") + result = torch.matmul(X2, self._dense(W).t().to(X2.dtype)) + elif _is_transposed(W): + result = int8_lora_dgrad(X2, self.wq, self.ws, self.wqt, None) + else: + result = int8_lora_fwd(X2, self.wq, self.ws) + result = result.view(*shape[:-1], result.shape[-1]) + return result if out is None else out.copy_(result) + + def lora_first( + self, + X, + W, + XA, + Bt, + alpha, + out = None, + ): + delta = X.new_empty((X.shape[0], Bt.shape[1])) + delta.addmm_(XA, Bt, alpha = alpha, beta = 0) + if not self._use_fp8(X): + result = delta.addmm_(X, self._dense(W).t().to(X.dtype)) + elif _is_transposed(W): + result = int8_lora_dgrad(X, self.wq, self.ws, self.wqt, delta) + else: + result = int8_lora_fwd(X, self.wq, self.ws, delta) + return result if out is None else out.copy_(result) + + def dgrad_accum(self, dY, W, delta): + if not self._use_fp8(dY): + _count("dgrad_16bit") + return delta.addmm_(dY, self._dense(W).to(dY.dtype)) + return int8_lora_dgrad(dY, self.wq, self.ws, self.wqt, delta) + + def dgrad( + self, + dY, + W = None, + ): + shape = dY.shape + dY2 = dY.reshape(-1, shape[-1]) + if not self._use_fp8(dY2): + _count("dgrad_16bit") + if W is None and not self.offloaded: + raise RuntimeError("Unsloth: 16-bit dgrad needs the base weight") + result = torch.matmul(dY2, self._dense(W).to(dY2.dtype)) + else: + result = int8_lora_dgrad(dY2, self.wq, self.ws, self.wqt, None) + return result.view(*shape[:-1], result.shape[-1]) + + +class _Int8FrozenLinear(torch.autograd.Function): + @staticmethod + def forward(ctx, x, weight, wq, ws, wqt): + ctx.has_t = wqt is not None + ctx.save_for_backward(wq, ws, wqt if wqt is not None else ws) + shape = x.shape + y = int8_lora_fwd(x.reshape(-1, shape[-1]), wq, ws) + return y.view(*shape[:-1], y.shape[-1]) + + @staticmethod + def backward(ctx, dy): + wq, ws, wqt = ctx.saved_tensors + shape = dy.shape + dx = int8_lora_dgrad(dy.reshape(-1, shape[-1]), wq, ws, wqt if ctx.has_t else None, None) + return dx.view(*shape[:-1], dx.shape[-1]), None, None, None, None + + +def _int8_base_forward(self, x): + """nn.Linear.forward of a converted base when Unsloth's fused LoRA kernels do not run it.""" + state = self.__dict__.get("_unsloth_fp8_lora") + weight = self.weight + if state is None or weight.requires_grad or not state._use_fp8(x.reshape(-1, x.shape[-1])): + _count("fwd_16bit") + if state is not None and state.offloaded: + if weight.requires_grad: + state.restore(self) + else: + weight = state._dense(weight) + return torch.nn.functional.linear(x, weight.to(x.dtype), self.bias) + state.refresh(weight) + y = _Int8FrozenLinear.apply(x, weight, state.wq, state.ws, state.wqt) + if self.bias is not None: + y = y + self.bias.to(y.dtype) + return y + + +def eligible_base(module) -> Optional[str]: + why = _fp8.eligible_base(module) + if why is not None: + return why + if module.in_features % GROUP: + return f"in_features {module.in_features} is not a multiple of {GROUP}" + return None + + +def attach_int8_lora_base(module, offload: Optional[bool] = None) -> Int8LoRABaseState: + """Quantize the frozen base `module` (nn.Linear) once and route its GEMMs through the rotated int8 kernels.""" + import types + + state = module.__dict__.get("_unsloth_fp8_lora") + if state is None: + state = Int8LoRABaseState(module.weight) + module.__dict__["_unsloth_fp8_lora"] = state + module.forward = types.MethodType(_int8_base_forward, module) + module._apply = types.MethodType(_fp8_base_apply, module) + module.__dict__["_unsloth_fp8_lora_load_hook"] = module.register_load_state_dict_post_hook( + _fp8_requantize_after_load + ) + if offload is None: + offload = offload_supported() + if offload: + state.offload(module) + return state diff --git a/unsloth/models/float8_training.py b/unsloth/models/float8_training.py index cd6d541de37b..abbdb68b8c33 100644 --- a/unsloth/models/float8_training.py +++ b/unsloth/models/float8_training.py @@ -418,6 +418,31 @@ def convert_model_to_float8_training( FP8_LORA_RECIPE = "fp8_lora_tensorwise" _FP8_LORA_BY_NAME = ("tensorwise",) _FP8_LORA_EXPLICIT = ("fp8_lora", FP8_LORA_RECIPE) +INT8_LORA_RECIPE = "int8_lora_rotated" +_INT8_LORA_NAMES = ("int8_lora", INT8_LORA_RECIPE) + + +def int8_lora_requested() -> bool: + """UNSLOTH_LORA_BASE_INT8=1: LoRA on a 16-bit base runs the frozen base GEMMs as rotated int8 (opt-in).""" + import os + return os.environ.get("UNSLOTH_LORA_BASE_INT8", "").strip().lower() in ( + "1", + "true", + "yes", + "on", + ) + + +def float8_training_request(float8_training, full_finetuning = False): + """The LoRA frozen-base request: the float8_training kwarg, or 'int8_lora' when UNSLOTH_LORA_BASE_INT8=1 + and the kwarg is unset.""" + if float8_training in (None, False) and not full_finetuning and int8_lora_requested(): + return "int8_lora" + return float8_training + + +def is_int8_lora_recipe(recipe) -> bool: + return isinstance(recipe, str) and recipe in _INT8_LORA_NAMES def resolve_fp8_lora( @@ -435,6 +460,15 @@ def resolve_fp8_lora( if float8_training is None or float8_training is False: return None refused = _precision.PrecisionRefused + if isinstance(float8_training, str) and float8_training.strip().lower() in _INT8_LORA_NAMES: + return _resolve_int8_lora( + dtype = dtype, + load_in_4bit = load_in_4bit, + load_in_8bit = load_in_8bit, + load_in_fp8 = load_in_fp8, + qat_scheme = qat_scheme, + gpu = gpu, + ) if float8_training is True: explicit = False elif isinstance(float8_training, str) and float8_training.strip().lower() in ( @@ -477,6 +511,34 @@ def resolve_fp8_lora( return recipe +def _resolve_int8_lora(*, dtype, load_in_4bit, load_in_8bit, load_in_fp8, qat_scheme, gpu): + refused = _precision.PrecisionRefused + if load_in_4bit or load_in_8bit or (load_in_fp8 not in (False, None)): + raise refused( + "Unsloth: the int8 LoRA base (UNSLOTH_LORA_BASE_INT8=1) quantizes a 16-bit base itself; pass " + "load_in_4bit = False (and no load_in_8bit / load_in_fp8), or unset UNSLOTH_LORA_BASE_INT8." + ) + if qat_scheme is not None: + raise refused( + "Unsloth: the int8 LoRA base and qat_scheme cannot be combined: QAT fake-quantizes the base weight." + ) + if gpu == "current": + gpu = _precision.current_gpu_class() + if gpu is None: + raise refused( + "Unsloth: the int8 LoRA base needs an NVIDIA GPU (RTX 50 / RTX PRO 6000 class); no CUDA device is visible." + ) + from ..kernels import int8_lora + + why = int8_lora.int8_lora_supported(torch.device("cuda")) + if why is not None: + raise refused(f"Unsloth: the int8 LoRA base cannot run here: {why}.") + gate = _check_precision_recipe(INT8_LORA_RECIPE, gpu = gpu, input_dtype = dtype, mode = "lora") + if gate.status == "unprobed": + print(f"Unsloth: the int8 LoRA base has not been timed on {gpu}; running it as requested.") + return INT8_LORA_RECIPE + + def fp8_lora_recipe_for(gpu): """The frozen-base recipe the kernels run on this GPU class: per-token scales on sm120, tensorwise elsewhere (UNSLOTH_FP8_LORA_SCALING overrides; kernels/fp8_lora.scaling_for_class is the one rule).""" @@ -934,6 +996,23 @@ def restore_fp8_lora_for_inference(model): owner.__dict__["_unsloth_fp8_lora_bases"] = () +def _model_hidden_size(model): + seen = set() + stack = [model] + while stack and len(seen) < 8: + m = stack.pop() + if m is None or id(m) in seen: + continue + seen.add(id(m)) + config = getattr(m, "config", None) + for cfg in (getattr(config, "text_config", None), config): + hidden = getattr(cfg, "hidden_size", None) + if isinstance(hidden, int): + return hidden + stack.extend(getattr(m, attr, None) for attr in ("base_model", "model")) + return None + + def enable_fp8_lora( model, recipe = None, @@ -944,18 +1023,33 @@ def enable_fp8_lora( recipe = recipe or _fp8_lora_request(model) if recipe is None: return [] - kernels = _load_fp8_lora_kernels() + int8 = is_int8_lora_recipe(recipe) + fp8_kernels = _load_fp8_lora_kernels() + if int8: + from ..kernels import int8_lora as kernels + else: + kernels = fp8_kernels policy = _precision.get_recipe(recipe).hp_layers try: is_hp = _precision.hp_filter(model, policy) except Exception: is_hp = lambda module, fqn: False converted, skipped = [], {} + if int8: + hidden = _model_hidden_size(model) + if hidden is not None and hidden < kernels.MIN_HIDDEN: + print( + f"Unsloth: the int8 LoRA base is off for hidden size {hidden} (below {kernels.MIN_HIDDEN}, where it " + "was measured slower than bfloat16); training stays in 16 bit. UNSLOTH_INT8_LORA_MIN_HIDDEN=0 forces it." + ) + _record_engagement(model, recipe, 0, detail = {"skipped": "hidden size"}) + _require_engagement(recipe, 0, f"hidden size {hidden} below {kernels.MIN_HIDDEN}") + return [] uses = {} for _, p in model.named_parameters(remove_duplicate = False): uses[id(p)] = uses.get(id(p), 0) + 1 swapped = _block_swapped_modules(model) - offload = kernels.offload_supported() + offload = fp8_kernels.offload_supported() offloaded = 0 for name, module in model.named_modules(): base = getattr(module, "base_layer", None) @@ -970,8 +1064,8 @@ def enable_fp8_lora( device = state.device if state is not None and state.offloaded else base.weight.device if device.type != "cuda" or torch.version.hip is not None: why = f"weight on {device}" - elif torch.cuda.get_device_capability(device) < (8, 9): - why = "compute capability below 8.9" + elif torch.cuda.get_device_capability(device) < ((8, 0) if int8 else (8, 9)): + why = "compute capability below " + ("8.0" if int8 else "8.9") if why is None and id(base) in swapped: why = "block-swapped layer" if why is None and uses.get(id(base.weight), 0) > 1: @@ -980,7 +1074,8 @@ def enable_fp8_lora( skipped[name] = why continue reads_raw = _has_variant(module) or _mamba_raw_weight_leaf(model, name) - state = kernels.attach_fp8_lora_base(base, offload = offload and not reads_raw) + attach = kernels.attach_int8_lora_base if int8 else kernels.attach_fp8_lora_base + state = attach(base, offload = offload and not reads_raw) offloaded += int(state.offloaded) _restore_master_before_merge(module) converted.append(name) @@ -995,12 +1090,13 @@ def enable_fp8_lora( _record_engagement(model, recipe, len(converted), detail = detail or None) if not _require_engagement(recipe, len(converted), "no frozen 16-bit LoRA base Linear layers"): print( - "Unsloth: float8_training with LoRA found no eligible base layers" + ("Unsloth: the int8 LoRA base" if int8 else "Unsloth: float8_training with LoRA") + + " found no eligible base layers" + (f" ({next(iter(skipped.values()))})" if skipped else "") + "; training stays in 16 bit." ) else: - print(f"Unsloth: fp8 LoRA base on {len(converted)} Linear layers.") + print(f"Unsloth: {'int8' if int8 else 'fp8'} LoRA base on {len(converted)} Linear layers.") if converted: _prepare_fp8_lora_loss(model) _prepare_fp8_lora_operators(model) diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py index c85f2a8dd236..be155ea2b608 100644 --- a/unsloth/models/loader.py +++ b/unsloth/models/loader.py @@ -41,6 +41,7 @@ mark_fp8_lora, resolve_float8_training, resolve_fp8_lora, + float8_training_request, ) from .mistral_format import ( MistralFormatRedirect, @@ -1457,6 +1458,11 @@ def from_pretrained( # @_offline_aware_load already forced offline when needed; delegations inherit it. fp8_lora = None + _int8_request = float8_training_request( + kwargs.get("float8_training", None), full_finetuning + ) + if _int8_request is not kwargs.get("float8_training", None): + kwargs["float8_training"] = _int8_request fp8_request = kwargs.get("float8_training", None) if kwargs.get("float8_training", None) not in (None, False) and not full_finetuning: fp8_lora = resolve_fp8_lora( @@ -2425,6 +2431,11 @@ def from_pretrained( ) user_config = kwargs.pop("config", None) fp8_lora = None + _int8_request = float8_training_request( + kwargs.get("float8_training", None), full_finetuning + ) + if _int8_request is not kwargs.get("float8_training", None): + kwargs["float8_training"] = _int8_request if not full_finetuning and kwargs.get("float8_training", None) not in (None, False): fp8_lora = resolve_fp8_lora( kwargs.pop("float8_training"), diff --git a/unsloth/precision/recipes.py b/unsloth/precision/recipes.py index 4648dd70f1a9..2918a1146ee6 100644 --- a/unsloth/precision/recipes.py +++ b/unsloth/precision/recipes.py @@ -591,6 +591,46 @@ def _add(recipe: Recipe): ) ) +_add( + Recipe( + name = "int8_lora_rotated", + kind = "frozen_base", + modes = ("lora",), + fwd = GemmPolicy(_op("int8", "row", rht = True), _op("int8", "row", rht = True)), + dgrad = GemmPolicy(_op("int8", "row"), _op("int8", "row", rht = True)), + hp_layers = _HP_FP8, + input_dtypes = ("bf16", "fp16"), + compile = "opaque", + backend = "unsloth.kernels.int8_lora (UNSLOTH_LORA_BASE_INT8=1, or float8_training = 'int8_lora')", + gates = { + "sm75": Gate("refused", "the Triton int8 GEMM needs compute capability 8.0+"), + "sm80": Gate( + "refused", + "A100: the Triton int8 GEMM runs at 0.22x bf16 (Triton >= 3.8 sm8x int8 tiles spill)", + ), + "sm89": Gate( + "refused", + "L4: the Triton int8 GEMM runs at 0.52-0.55x bf16 (Triton >= 3.8 sm8x int8 tiles spill)", + ), + "sm90": Gate("unprobed", "H100 is not available to test on"), + "sm100": Gate("unprobed", "B200: correctness only, never timed"), + "sm120": Gate( + "explicit", + evidence = "RTX 5090 (GeForce: FP32-accumulate bf16 / fp8 tensor paths run at half rate): " + "the int8 GEMM is 3.03x a bf16 GEMM and 1.54x fp8 tensorwise over a Qwen3-8B layer at 8192 " + "tokens (A/A 0.25%). RTX PRO 6000: int8 = fp8 rowwise = ~1.9x bf16 per GEMM. Eval loss after " + "100 LoRA steps vs bf16 (A/A 0.02-0.05%): +0.02% on the exact base, +0.16% with the int8 " + "forward at Qwen3-1.7B (fp8 rowwise: +0.10% / +0.42%)", + ), + "rocm": Gate("refused", "the int8 kernels are CUDA Triton only"), + }, + notes = "block-Hadamard (128) rotated per-token int8 activations and per-row int8 weight, int32 " + "accumulation, dequant and LoRA term in the GEMM epilogue; the input gradient reuses the same int8 " + "weight (row scale folded into dY, rotation undone in the epilogue); q / k / v and gate / up share " + "one activation quantization", + ) +) + def get_recipe(name: str) -> Recipe: try: From 4baa0591d863a09e79523e4a1371efcb59c4bc3c Mon Sep 17 00:00:00 2001 From: Daniel Han <23090290+danielhanchen@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:01:06 -0800 Subject: [PATCH 2/8] int8 LoRA base: the environment opt-in falls back to 16 bit where the int8 base cannot run --- tests/test_int8_lora_recipe.py | 10 ++++++++++ unsloth/models/float8_training.py | 25 ++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/tests/test_int8_lora_recipe.py b/tests/test_int8_lora_recipe.py index 1c855297dbbc..305aa7606a54 100644 --- a/tests/test_int8_lora_recipe.py +++ b/tests/test_int8_lora_recipe.py @@ -26,6 +26,7 @@ def test_registry_entry(): ) def test_env_request(monkeypatch, value, on): monkeypatch.setenv("UNSLOTH_LORA_BASE_INT8", value) + monkeypatch.setattr(f8t, "int8_lora_unavailable", lambda gpu = "current": None) assert f8t.int8_lora_requested() is on assert f8t.float8_training_request(None) == ("int8_lora" if on else None) assert f8t.float8_training_request(False) == ("int8_lora" if on else False) @@ -34,6 +35,15 @@ def test_env_request(monkeypatch, value, on): assert f8t.float8_training_request(None, full_finetuning = True) is None +@pytest.mark.parametrize("gpu", ["sm80", "sm89", "sm75", None]) +def test_env_opt_in_on_unsupported_gpu_stays_16bit(monkeypatch, capsys, gpu): + monkeypatch.setenv("UNSLOTH_LORA_BASE_INT8", "1") + monkeypatch.setattr(P, "current_gpu_class", lambda: gpu) + assert f8t.int8_lora_unavailable() is not None + assert f8t.float8_training_request(None) is None + assert "ignored here" in capsys.readouterr().out + + def test_env_unset_changes_nothing(monkeypatch): monkeypatch.delenv("UNSLOTH_LORA_BASE_INT8", raising = False) assert f8t.float8_training_request(None) is None diff --git a/unsloth/models/float8_training.py b/unsloth/models/float8_training.py index abbdb68b8c33..fb037c5326da 100644 --- a/unsloth/models/float8_training.py +++ b/unsloth/models/float8_training.py @@ -433,10 +433,33 @@ def int8_lora_requested() -> bool: ) +def int8_lora_unavailable(gpu = "current"): + """Why the int8 LoRA base cannot run on this GPU class (registry gate, Triton, device), else None.""" + if gpu == "current": + gpu = _precision.current_gpu_class() + if gpu is None: + return "no CUDA GPU is visible" + gate = _precision.get_recipe(INT8_LORA_RECIPE).gate(gpu) + if gate.status == "refused": + return f"{gpu}: {gate.reason}" + try: + from ..kernels import int8_lora + except ImportError as exc: + return f"the int8 kernels do not import ({exc})" + return int8_lora.int8_lora_supported(torch.device("cuda")) + + def float8_training_request(float8_training, full_finetuning = False): """The LoRA frozen-base request: the float8_training kwarg, or 'int8_lora' when UNSLOTH_LORA_BASE_INT8=1 - and the kwarg is unset.""" + and the kwarg is unset. The environment opt-in never fails a load: where the int8 base cannot run it says + why and training stays 16 bit (float8_training = 'int8_lora' refuses instead).""" if float8_training in (None, False) and not full_finetuning and int8_lora_requested(): + why = int8_lora_unavailable() + if why is not None: + print( + f"Unsloth: UNSLOTH_LORA_BASE_INT8=1 is ignored here ({why}); training stays in 16 bit." + ) + return float8_training return "int8_lora" return float8_training From b3f489ceec4b152e70b82a96dfef40820e8dfd8e Mon Sep 17 00:00:00 2001 From: Daniel Han <23090290+danielhanchen@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:19:15 -0800 Subject: [PATCH 3/8] int8 LoRA base: the env opt-in skips quantized loads; contiguous epilogue deltas --- tests/test_int8_lora_recipe.py | 7 +++++++ unsloth/kernels/int8_lora.py | 4 ++++ unsloth/models/float8_training.py | 14 ++++++++++---- unsloth/models/loader.py | 8 ++++++-- 4 files changed, 27 insertions(+), 6 deletions(-) diff --git a/tests/test_int8_lora_recipe.py b/tests/test_int8_lora_recipe.py index 305aa7606a54..0ca3f03c800b 100644 --- a/tests/test_int8_lora_recipe.py +++ b/tests/test_int8_lora_recipe.py @@ -44,6 +44,13 @@ def test_env_opt_in_on_unsupported_gpu_stays_16bit(monkeypatch, capsys, gpu): assert "ignored here" in capsys.readouterr().out +def test_env_opt_in_on_quantized_base_is_ignored(monkeypatch, capsys): + monkeypatch.setenv("UNSLOTH_LORA_BASE_INT8", "1") + monkeypatch.setattr(f8t, "int8_lora_unavailable", lambda gpu = "current": None) + assert f8t.float8_training_request(None, quantized_base = True) is None + assert "quantized" in capsys.readouterr().out + + def test_env_unset_changes_nothing(monkeypatch): monkeypatch.delenv("UNSLOTH_LORA_BASE_INT8", raising = False) assert f8t.float8_training_request(None) is None diff --git a/unsloth/kernels/int8_lora.py b/unsloth/kernels/int8_lora.py index 648b23bd068d..60489b4ac798 100644 --- a/unsloth/kernels/int8_lora.py +++ b/unsloth/kernels/int8_lora.py @@ -358,6 +358,8 @@ def _mm(xq, xs, wq, ws, delta, out_dtype): N = wq.shape[0] out = torch.empty((M, N), device = xq.device, dtype = out_dtype) bm, bn, bk, gm, warps, stages = _TILE + if delta is not None and delta.stride(-1) != 1: + delta = delta.contiguous() # the epilogue reads rows with a unit column stride d = delta if delta is not None else out with _device_ctx(xq): _launch( @@ -384,6 +386,8 @@ def _dgrad_mm(dyq, dys, wqt, delta, out_dtype): K = wqt.shape[0] out = torch.empty((M, K), device = dyq.device, dtype = out_dtype) bm, br, gm, warps, stages = _DGRAD_TILE + if delta is not None and delta.stride(-1) != 1: + delta = delta.contiguous() d = delta if delta is not None else out h = _hadamard_pm1(dyq.device, torch.bfloat16) with _device_ctx(dyq): diff --git a/unsloth/models/float8_training.py b/unsloth/models/float8_training.py index fb037c5326da..8c30de1f0b78 100644 --- a/unsloth/models/float8_training.py +++ b/unsloth/models/float8_training.py @@ -449,12 +449,18 @@ def int8_lora_unavailable(gpu = "current"): return int8_lora.int8_lora_supported(torch.device("cuda")) -def float8_training_request(float8_training, full_finetuning = False): +def float8_training_request( + float8_training, + full_finetuning = False, + quantized_base = False, +): """The LoRA frozen-base request: the float8_training kwarg, or 'int8_lora' when UNSLOTH_LORA_BASE_INT8=1 - and the kwarg is unset. The environment opt-in never fails a load: where the int8 base cannot run it says - why and training stays 16 bit (float8_training = 'int8_lora' refuses instead).""" + and the kwarg is unset. The environment opt-in never fails a load: on a quantized base (load_in_4bit, ...) + or where the int8 base cannot run it says why and training stays as loaded (float8_training = 'int8_lora' + refuses instead).""" if float8_training in (None, False) and not full_finetuning and int8_lora_requested(): - why = int8_lora_unavailable() + why = "the base is loaded quantized (load_in_4bit / 8bit / fp8)" if quantized_base else None + why = why or int8_lora_unavailable() if why is not None: print( f"Unsloth: UNSLOTH_LORA_BASE_INT8=1 is ignored here ({why}); training stays in 16 bit." diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py index be155ea2b608..a8813624113a 100644 --- a/unsloth/models/loader.py +++ b/unsloth/models/loader.py @@ -1459,7 +1459,9 @@ def from_pretrained( # @_offline_aware_load already forced offline when needed; delegations inherit it. fp8_lora = None _int8_request = float8_training_request( - kwargs.get("float8_training", None), full_finetuning + kwargs.get("float8_training", None), + full_finetuning, + quantized_base = bool(load_in_4bit or load_in_8bit or load_in_fp8 not in (False, None)), ) if _int8_request is not kwargs.get("float8_training", None): kwargs["float8_training"] = _int8_request @@ -2432,7 +2434,9 @@ def from_pretrained( user_config = kwargs.pop("config", None) fp8_lora = None _int8_request = float8_training_request( - kwargs.get("float8_training", None), full_finetuning + kwargs.get("float8_training", None), + full_finetuning, + quantized_base = bool(load_in_4bit or load_in_8bit or load_in_fp8 not in (False, None)), ) if _int8_request is not kwargs.get("float8_training", None): kwargs["float8_training"] = _int8_request From 15a466d4c423249dc65e704bb22560d2a5c6e31e Mon Sep 17 00:00:00 2001 From: Daniel Han <23090290+danielhanchen@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:05:18 -0800 Subject: [PATCH 4/8] int8 LoRA base: 8-warp input-gradient tile (fastest of 8 on an RTX PRO 6000, bit-identical) --- unsloth/kernels/int8_lora.py | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/unsloth/kernels/int8_lora.py b/unsloth/kernels/int8_lora.py index 60489b4ac798..6fe8f0a9ba3e 100644 --- a/unsloth/kernels/int8_lora.py +++ b/unsloth/kernels/int8_lora.py @@ -76,13 +76,9 @@ _MULTI_GPU = torch.cuda.is_available() and torch.cuda.device_count() > 1 # Tile (BLOCK_M, BLOCK_N, BLOCK_K, GROUP_M, warps, stages): fastest on an RTX 5090 and an RTX PRO 6000. _TILE = (128, 128, 64, 8, 4, 4) -_DGRAD_TILE = ( - 128, - 64, - 8, - 4, - 4, -) # BLOCK_M, BLOCK_R (reduction), GROUP_M, warps, stages; output block = GROUP +# Input gradient (BLOCK_M, BLOCK_R reduction step, GROUP_M, warps, stages), output block = GROUP: fastest of 8 on an +# RTX PRO 6000 (8 warps for the un-rotation dots in the epilogue). +_DGRAD_TILE = (128, 128, 8, 8, 3) _ROTQ_ROWS = 16 From cff4eb9aee4ebf3753826098c30ac2f2ffe9c132 Mon Sep 17 00:00:00 2001 From: Daniel Han <23090290+danielhanchen@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:18:36 -0800 Subject: [PATCH 5/8] int8 LoRA base: a NaN in an activation / gradient row makes its scale NaN, as the 16-bit GEMM propagates it --- tests/test_int8_lora_cuda.py | 15 +++++++++++++++ unsloth/kernels/int8_lora.py | 12 +++++++++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/tests/test_int8_lora_cuda.py b/tests/test_int8_lora_cuda.py index 06ce78478266..09a8b6842fd2 100644 --- a/tests/test_int8_lora_cuda.py +++ b/tests/test_int8_lora_cuda.py @@ -227,3 +227,18 @@ def f(x): out = compiled(x) assert sum(counters["graph_break"].values()) == 0 assert torch.equal(out, eager) + + +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16]) +def test_nan_rows_propagate(dtype): + """A NaN in one row of x / dY makes that output row NaN (as the 16-bit GEMM does) and leaves the others finite.""" + M, N, K = 512, 256, 512 + x, w, dy = _inputs(M, N, K, dtype, seed = 3) + wq, ws = IL.quantize_weight(w) + x[7, 11] = float("nan") + dy[9, 3] = float("nan") + IL.clear_int8_lora_cache() + y = IL.int8_lora_fwd(x, wq, ws) + dx = IL.int8_lora_dgrad(dy, wq, ws, None, None) + assert torch.isnan(y[7]).all() and torch.isfinite(torch.cat([y[:7], y[8:]])).all() + assert torch.isnan(dx[9]).all() and torch.isfinite(torch.cat([dx[:9], dx[10:]])).all() diff --git a/unsloth/kernels/int8_lora.py b/unsloth/kernels/int8_lora.py index 6fe8f0a9ba3e..ab30592a7513 100644 --- a/unsloth/kernels/int8_lora.py +++ b/unsloth/kernels/int8_lora.py @@ -141,12 +141,14 @@ def _int8_rotq_kernel( g = tl.arange(0, G) H = tl.load(h_ptr + g[:, None] * G + g[None, :]) amax = tl.zeros((BLOCK_M,), dtype = tl.float32) + nans = tl.zeros((BLOCK_M,), dtype = tl.int32) for k0 in range(0, K, G): x = tl.load( x_ptr + rows[:, None] * stride_x + (k0 + g)[None, :], mask = rmask[:, None], other = 0.0 ) xr = tl.dot(x, H) amax = tl.maximum(amax, tl.max(tl.abs(xr), axis = 1)) + nans += tl.sum((xr != xr).to(tl.int32), axis = 1) amax = tl.maximum(amax, 1e-30) mul = 127.0 / amax for k0 in range(0, K, G): @@ -159,7 +161,8 @@ def _int8_rotq_kernel( tl.store( q_ptr + rows[:, None] * K + (k0 + g)[None, :], y.to(tl.int8), mask = rmask[:, None] ) - tl.store(s_ptr + rows, amax * INV_SCALE, mask = rmask) + # tl.max drops NaN: a NaN row scale makes the whole output row NaN, as the 16-bit GEMM would. + tl.store(s_ptr + rows, tl.where(nans > 0, float("nan"), amax * INV_SCALE), mask = rmask) @triton.jit(do_not_specialize = ["N"]) def _int8_rowq_kernel( @@ -175,11 +178,14 @@ def _int8_rowq_kernel( row = tl.program_id(0).to(tl.int64) offs = tl.arange(0, BLOCK) amax = tl.zeros((BLOCK,), dtype = tl.float32) + nans = tl.zeros((BLOCK,), dtype = tl.int32) for n0 in range(0, N, BLOCK): mask = n0 + offs < N x = tl.load(x_ptr + row * stride_x + n0 + offs, mask = mask, other = 0.0).to(tl.float32) c = tl.load(c_ptr + n0 + offs, mask = mask, other = 0.0) - amax = tl.maximum(amax, tl.abs(x * c)) + xc = x * c + amax = tl.maximum(amax, tl.abs(xc)) + nans += (xc != xc).to(tl.int32) rmax = tl.maximum(tl.max(amax, axis = 0), 1e-30) mul = 127.0 / rmax for n0 in range(0, N, BLOCK): @@ -189,7 +195,7 @@ def _int8_rowq_kernel( y = tl.extra.cuda.libdevice.rint(x * c * mul) y = tl.minimum(tl.maximum(y, -127.0), 127.0) tl.store(q_ptr + row * N + n0 + offs, y.to(tl.int8), mask = mask) - tl.store(s_ptr + row, rmax / 127.0) + tl.store(s_ptr + row, tl.where(tl.sum(nans, axis = 0) > 0, float("nan"), rmax / 127.0)) @triton.jit(do_not_specialize = ["M"]) def _int8_mm_kernel( From e87a04a1974eb8a4f99745cac1b0fee54b3e2883 Mon Sep 17 00:00:00 2001 From: Daniel Han <23090290+danielhanchen@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:30:30 -0800 Subject: [PATCH 6/8] int8 LoRA base: the env opt-in is ignored for float32 loads (explicit int8_lora still refuses) --- tests/test_int8_lora_recipe.py | 14 ++++++++++++++ unsloth/models/float8_training.py | 3 +++ unsloth/models/loader.py | 2 ++ 3 files changed, 19 insertions(+) diff --git a/tests/test_int8_lora_recipe.py b/tests/test_int8_lora_recipe.py index 0ca3f03c800b..97c51164f6a1 100644 --- a/tests/test_int8_lora_recipe.py +++ b/tests/test_int8_lora_recipe.py @@ -51,6 +51,20 @@ def test_env_opt_in_on_quantized_base_is_ignored(monkeypatch, capsys): assert "quantized" in capsys.readouterr().out +@pytest.mark.parametrize("dtype", [torch.float32, "float32"]) +def test_env_opt_in_on_fp32_load_is_ignored(monkeypatch, capsys, dtype): + monkeypatch.setenv("UNSLOTH_LORA_BASE_INT8", "1") + monkeypatch.setattr(f8t, "int8_lora_unavailable", lambda gpu = "current": None) + assert f8t.float8_training_request(None, dtype = dtype) is None + assert "float32" in capsys.readouterr().out + assert f8t.float8_training_request(None, dtype = torch.bfloat16) == "int8_lora" + import unsloth.kernels.int8_lora as IL + + monkeypatch.setattr(IL, "int8_lora_supported", lambda device: None) + with pytest.raises(P.PrecisionRefused, match = "fp32"): # the explicit request still refuses fp32 + f8t.resolve_fp8_lora("int8_lora", dtype = torch.float32, gpu = "sm120") + + def test_env_unset_changes_nothing(monkeypatch): monkeypatch.delenv("UNSLOTH_LORA_BASE_INT8", raising = False) assert f8t.float8_training_request(None) is None diff --git a/unsloth/models/float8_training.py b/unsloth/models/float8_training.py index 8c30de1f0b78..3811ab328864 100644 --- a/unsloth/models/float8_training.py +++ b/unsloth/models/float8_training.py @@ -453,6 +453,7 @@ def float8_training_request( float8_training, full_finetuning = False, quantized_base = False, + dtype = None, ): """The LoRA frozen-base request: the float8_training kwarg, or 'int8_lora' when UNSLOTH_LORA_BASE_INT8=1 and the kwarg is unset. The environment opt-in never fails a load: on a quantized base (load_in_4bit, ...) @@ -460,6 +461,8 @@ def float8_training_request( refuses instead).""" if float8_training in (None, False) and not full_finetuning and int8_lora_requested(): why = "the base is loaded quantized (load_in_4bit / 8bit / fp8)" if quantized_base else None + if why is None and dtype in (torch.float32, "float32", "fp32"): + why = "the int8 base needs bf16 / fp16 activations, the model loads in float32" why = why or int8_lora_unavailable() if why is not None: print( diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py index a8813624113a..e6df32099b77 100644 --- a/unsloth/models/loader.py +++ b/unsloth/models/loader.py @@ -1462,6 +1462,7 @@ def from_pretrained( kwargs.get("float8_training", None), full_finetuning, quantized_base = bool(load_in_4bit or load_in_8bit or load_in_fp8 not in (False, None)), + dtype = dtype, ) if _int8_request is not kwargs.get("float8_training", None): kwargs["float8_training"] = _int8_request @@ -2437,6 +2438,7 @@ def from_pretrained( kwargs.get("float8_training", None), full_finetuning, quantized_base = bool(load_in_4bit or load_in_8bit or load_in_fp8 not in (False, None)), + dtype = dtype, ) if _int8_request is not kwargs.get("float8_training", None): kwargs["float8_training"] = _int8_request From a68680de2a6fc6c74f1a7ee1d53b617e9d991873 Mon Sep 17 00:00:00 2001 From: Daniel Han <23090290+danielhanchen@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:52:57 -0800 Subject: [PATCH 7/8] int8 LoRA base: the env opt-in is ignored for QAT loads and tensor / pipeline / expert parallel runs --- tests/test_int8_lora_recipe.py | 15 +++++++++++++++ unsloth/models/float8_training.py | 14 ++++++++++++++ unsloth/models/loader.py | 2 ++ 3 files changed, 31 insertions(+) diff --git a/tests/test_int8_lora_recipe.py b/tests/test_int8_lora_recipe.py index 97c51164f6a1..e293557ca695 100644 --- a/tests/test_int8_lora_recipe.py +++ b/tests/test_int8_lora_recipe.py @@ -65,6 +65,21 @@ def test_env_opt_in_on_fp32_load_is_ignored(monkeypatch, capsys, dtype): f8t.resolve_fp8_lora("int8_lora", dtype = torch.float32, gpu = "sm120") +def test_env_opt_in_on_qat_load_is_ignored(monkeypatch, capsys): + monkeypatch.setenv("UNSLOTH_LORA_BASE_INT8", "1") + monkeypatch.setattr(f8t, "int8_lora_unavailable", lambda gpu = "current": None) + assert f8t.float8_training_request(None, qat_scheme = "int8-int4") is None + assert "qat_scheme" in capsys.readouterr().out + + +def test_env_opt_in_under_tp_or_ep_is_ignored(monkeypatch, capsys): + monkeypatch.setenv("UNSLOTH_LORA_BASE_INT8", "1") + monkeypatch.setattr(f8t, "int8_lora_unavailable", lambda gpu = "current": None) + monkeypatch.setattr(f8t, "_parallel_layout_requested", lambda: True) + assert f8t.float8_training_request(None) is None + assert "parallel" in capsys.readouterr().out + + def test_env_unset_changes_nothing(monkeypatch): monkeypatch.delenv("UNSLOTH_LORA_BASE_INT8", raising = False) assert f8t.float8_training_request(None) is None diff --git a/unsloth/models/float8_training.py b/unsloth/models/float8_training.py index 3811ab328864..83665a7fd139 100644 --- a/unsloth/models/float8_training.py +++ b/unsloth/models/float8_training.py @@ -449,11 +449,21 @@ def int8_lora_unavailable(gpu = "current"): return int8_lora.int8_lora_supported(torch.device("cuda")) +def _parallel_layout_requested() -> bool: + try: + from .tp_env import env_layout + from .ep_native import ep_env_size + return env_layout() is not None or ep_env_size() > 1 + except Exception: + return False + + def float8_training_request( float8_training, full_finetuning = False, quantized_base = False, dtype = None, + qat_scheme = None, ): """The LoRA frozen-base request: the float8_training kwarg, or 'int8_lora' when UNSLOTH_LORA_BASE_INT8=1 and the kwarg is unset. The environment opt-in never fails a load: on a quantized base (load_in_4bit, ...) @@ -461,6 +471,10 @@ def float8_training_request( refuses instead).""" if float8_training in (None, False) and not full_finetuning and int8_lora_requested(): why = "the base is loaded quantized (load_in_4bit / 8bit / fp8)" if quantized_base else None + if why is None and _parallel_layout_requested(): + why = "tensor / pipeline / expert parallel runs keep the frozen base in 16 bit" + if why is None and qat_scheme is not None: + why = f"qat_scheme = {qat_scheme!r} fake-quantizes the base weight" if why is None and dtype in (torch.float32, "float32", "fp32"): why = "the int8 base needs bf16 / fp16 activations, the model loads in float32" why = why or int8_lora_unavailable() diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py index e6df32099b77..5189a268d9a1 100644 --- a/unsloth/models/loader.py +++ b/unsloth/models/loader.py @@ -1463,6 +1463,7 @@ def from_pretrained( full_finetuning, quantized_base = bool(load_in_4bit or load_in_8bit or load_in_fp8 not in (False, None)), dtype = dtype, + qat_scheme = qat_scheme, ) if _int8_request is not kwargs.get("float8_training", None): kwargs["float8_training"] = _int8_request @@ -2439,6 +2440,7 @@ def from_pretrained( full_finetuning, quantized_base = bool(load_in_4bit or load_in_8bit or load_in_fp8 not in (False, None)), dtype = dtype, + qat_scheme = qat_scheme, ) if _int8_request is not kwargs.get("float8_training", None): kwargs["float8_training"] = _int8_request From f8233469731453fd33bdcca07fa96a6090e12507 Mon Sep 17 00:00:00 2001 From: Daniel Han <23090290+danielhanchen@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:11:55 -0800 Subject: [PATCH 8/8] int8 LoRA base: decide the env opt-in on the loaded model (after '-bf16' precision normalization), not on the load flags --- tests/test_int8_lora_recipe.py | 98 +++++++++++++++++-------------- unsloth/models/float8_training.py | 72 +++++++++++++++-------- unsloth/models/loader.py | 26 +++----- 3 files changed, 108 insertions(+), 88 deletions(-) diff --git a/tests/test_int8_lora_recipe.py b/tests/test_int8_lora_recipe.py index e293557ca695..f273f81d8fc3 100644 --- a/tests/test_int8_lora_recipe.py +++ b/tests/test_int8_lora_recipe.py @@ -21,69 +21,77 @@ def test_registry_entry(): assert r.gate("sm120").status != "named" +def _linear_model(dtype = torch.bfloat16, quantized = False): + model = torch.nn.Sequential(torch.nn.Linear(256, 256, bias = False, dtype = dtype)) + if quantized: + model[0].weight.quant_state = object() # what bitsandbytes Params4bit carries + return model + + +@pytest.fixture +def env_on(monkeypatch): + monkeypatch.setenv("UNSLOTH_LORA_BASE_INT8", "1") + monkeypatch.setattr(f8t, "int8_lora_unavailable", lambda gpu = "current": None) + monkeypatch.setattr(f8t, "_parallel_layout_requested", lambda: False) + monkeypatch.setattr(P, "current_gpu_class", lambda: "sm120") + + @pytest.mark.parametrize( "value, on", [("1", True), ("true", True), ("on", True), ("0", False), ("", False)] ) -def test_env_request(monkeypatch, value, on): +def test_env_request(monkeypatch, env_on, value, on): monkeypatch.setenv("UNSLOTH_LORA_BASE_INT8", value) - monkeypatch.setattr(f8t, "int8_lora_unavailable", lambda gpu = "current": None) assert f8t.int8_lora_requested() is on - assert f8t.float8_training_request(None) == ("int8_lora" if on else None) - assert f8t.float8_training_request(False) == ("int8_lora" if on else False) - # an explicit float8_training wins, and full finetuning never takes the LoRA base - assert f8t.float8_training_request("fp8_lora") == "fp8_lora" - assert f8t.float8_training_request(None, full_finetuning = True) is None - + assert f8t.int8_lora_from_env(_linear_model()) == ("int8_lora_rotated" if on else None) -@pytest.mark.parametrize("gpu", ["sm80", "sm89", "sm75", None]) -def test_env_opt_in_on_unsupported_gpu_stays_16bit(monkeypatch, capsys, gpu): - monkeypatch.setenv("UNSLOTH_LORA_BASE_INT8", "1") - monkeypatch.setattr(P, "current_gpu_class", lambda: gpu) - assert f8t.int8_lora_unavailable() is not None - assert f8t.float8_training_request(None) is None - assert "ignored here" in capsys.readouterr().out +def test_env_unset_changes_nothing(monkeypatch): + monkeypatch.delenv("UNSLOTH_LORA_BASE_INT8", raising = False) + assert f8t.int8_lora_from_env(_linear_model()) is None -def test_env_opt_in_on_quantized_base_is_ignored(monkeypatch, capsys): - monkeypatch.setenv("UNSLOTH_LORA_BASE_INT8", "1") - monkeypatch.setattr(f8t, "int8_lora_unavailable", lambda gpu = "current": None) - assert f8t.float8_training_request(None, quantized_base = True) is None - assert "quantized" in capsys.readouterr().out +@pytest.mark.parametrize( + "kwargs, model, said", + [ + (dict(full_finetuning = True), _linear_model(), "full finetuning"), + (dict(qat_scheme = "int8-int4"), _linear_model(), "qat_scheme"), + ({}, _linear_model(quantized = True), "quantized"), + ({}, _linear_model(torch.float32), "float32"), + ], +) +def test_env_opt_in_is_ignored_where_it_cannot_run(env_on, capsys, kwargs, model, said): + """Decided on the LOADED model: a quantized / fp32 base, full finetuning or QAT keeps the load as is.""" + assert f8t.int8_lora_from_env(model, **kwargs) is None + assert said in capsys.readouterr().out -@pytest.mark.parametrize("dtype", [torch.float32, "float32"]) -def test_env_opt_in_on_fp32_load_is_ignored(monkeypatch, capsys, dtype): - monkeypatch.setenv("UNSLOTH_LORA_BASE_INT8", "1") - monkeypatch.setattr(f8t, "int8_lora_unavailable", lambda gpu = "current": None) - assert f8t.float8_training_request(None, dtype = dtype) is None - assert "float32" in capsys.readouterr().out - assert f8t.float8_training_request(None, dtype = torch.bfloat16) == "int8_lora" - import unsloth.kernels.int8_lora as IL - monkeypatch.setattr(IL, "int8_lora_supported", lambda device: None) - with pytest.raises(P.PrecisionRefused, match = "fp32"): # the explicit request still refuses fp32 - f8t.resolve_fp8_lora("int8_lora", dtype = torch.float32, gpu = "sm120") +def test_env_opt_in_on_a_16bit_load_whatever_the_flags(env_on): + # A '-bf16' checkpoint loads 16 bit despite load_in_4bit's default: the loaded weights decide, not the flags. + assert f8t.int8_lora_from_env(_linear_model(torch.bfloat16)) == "int8_lora_rotated" + assert f8t.int8_lora_from_env(_linear_model(torch.float16)) == "int8_lora_rotated" -def test_env_opt_in_on_qat_load_is_ignored(monkeypatch, capsys): - monkeypatch.setenv("UNSLOTH_LORA_BASE_INT8", "1") - monkeypatch.setattr(f8t, "int8_lora_unavailable", lambda gpu = "current": None) - assert f8t.float8_training_request(None, qat_scheme = "int8-int4") is None - assert "qat_scheme" in capsys.readouterr().out +def test_env_opt_in_under_tp_or_ep_is_ignored(env_on, monkeypatch, capsys): + monkeypatch.setattr(f8t, "_parallel_layout_requested", lambda: True) + assert f8t.int8_lora_from_env(_linear_model()) is None + assert "parallel" in capsys.readouterr().out -def test_env_opt_in_under_tp_or_ep_is_ignored(monkeypatch, capsys): +@pytest.mark.parametrize("gpu", ["sm80", "sm89", "sm75", None]) +def test_env_opt_in_on_unsupported_gpu_stays_16bit(monkeypatch, capsys, gpu): monkeypatch.setenv("UNSLOTH_LORA_BASE_INT8", "1") - monkeypatch.setattr(f8t, "int8_lora_unavailable", lambda gpu = "current": None) - monkeypatch.setattr(f8t, "_parallel_layout_requested", lambda: True) - assert f8t.float8_training_request(None) is None - assert "parallel" in capsys.readouterr().out + monkeypatch.setattr(f8t, "_parallel_layout_requested", lambda: False) + monkeypatch.setattr(P, "current_gpu_class", lambda: gpu) + assert f8t.int8_lora_unavailable() is not None + assert f8t.int8_lora_from_env(_linear_model()) is None + assert "ignored here" in capsys.readouterr().out -def test_env_unset_changes_nothing(monkeypatch): - monkeypatch.delenv("UNSLOTH_LORA_BASE_INT8", raising = False) - assert f8t.float8_training_request(None) is None - assert f8t.float8_training_request(True) is True +def test_explicit_request_still_refuses_fp32(monkeypatch): + import unsloth.kernels.int8_lora as IL + monkeypatch.setattr(IL, "int8_lora_supported", lambda device: None) + with pytest.raises(P.PrecisionRefused, match = "fp32"): + f8t.resolve_fp8_lora("int8_lora", dtype = torch.float32, gpu = "sm120") @pytest.mark.parametrize( diff --git a/unsloth/models/float8_training.py b/unsloth/models/float8_training.py index 83665a7fd139..16c0e3ed218d 100644 --- a/unsloth/models/float8_training.py +++ b/unsloth/models/float8_training.py @@ -458,33 +458,57 @@ def _parallel_layout_requested() -> bool: return False -def float8_training_request( - float8_training, +def _loaded_base_kind(model): + """'quantized', 'float32' or None (a 16-bit base) from the loaded model's Linear weights.""" + for module in model.modules(): + if not isinstance(module, torch.nn.Linear): + continue + weight = getattr(module, "weight", None) + if weight is None: + continue + if ( + type(weight).__name__ in ("Params4bit", "Int8Params") + or getattr(weight, "quant_state", None) is not None + ): + return "quantized" + if weight.dtype not in (torch.bfloat16, torch.float16): + return "float32" if weight.dtype == torch.float32 else "quantized" + return None + return None + + +def int8_lora_from_env( + model, full_finetuning = False, - quantized_base = False, - dtype = None, qat_scheme = None, ): - """The LoRA frozen-base request: the float8_training kwarg, or 'int8_lora' when UNSLOTH_LORA_BASE_INT8=1 - and the kwarg is unset. The environment opt-in never fails a load: on a quantized base (load_in_4bit, ...) - or where the int8 base cannot run it says why and training stays as loaded (float8_training = 'int8_lora' - refuses instead).""" - if float8_training in (None, False) and not full_finetuning and int8_lora_requested(): - why = "the base is loaded quantized (load_in_4bit / 8bit / fp8)" if quantized_base else None - if why is None and _parallel_layout_requested(): - why = "tensor / pipeline / expert parallel runs keep the frozen base in 16 bit" - if why is None and qat_scheme is not None: - why = f"qat_scheme = {qat_scheme!r} fake-quantizes the base weight" - if why is None and dtype in (torch.float32, "float32", "fp32"): - why = "the int8 base needs bf16 / fp16 activations, the model loads in float32" - why = why or int8_lora_unavailable() - if why is not None: - print( - f"Unsloth: UNSLOTH_LORA_BASE_INT8=1 is ignored here ({why}); training stays in 16 bit." - ) - return float8_training - return "int8_lora" - return float8_training + """UNSLOTH_LORA_BASE_INT8=1 with float8_training unset: INT8_LORA_RECIPE when the LOADED model is a 16-bit + base the int8 base can run on, else None. Decided after loading, so precision normalization (a '-bf16' + checkpoint loading 16 bit despite the load_in_4bit default) is already applied. Never fails a load: where it + cannot run it says why and training stays as loaded (float8_training = 'int8_lora' refuses instead).""" + if not int8_lora_requested() or model is None: + return None + why = None + if full_finetuning: + why = "full finetuning trains the base weight" + elif qat_scheme is not None: + why = f"qat_scheme = {qat_scheme!r} fake-quantizes the base weight" + elif _parallel_layout_requested(): + why = "tensor / pipeline / expert parallel runs keep the frozen base in 16 bit" + else: + kind = _loaded_base_kind(model) + if kind == "quantized": + why = "the base is loaded quantized (load_in_4bit / 8bit / fp8)" + elif kind == "float32": + why = "the int8 base needs bf16 / fp16 activations, the model loaded in float32" + why = why or int8_lora_unavailable() + if why is not None: + print(f"Unsloth: UNSLOTH_LORA_BASE_INT8=1 is ignored here ({why}).") + return None + gpu = _precision.current_gpu_class() + if _precision.get_recipe(INT8_LORA_RECIPE).gate(gpu).status == "unprobed": + print(f"Unsloth: the int8 LoRA base has not been timed on {gpu}; running it as requested.") + return INT8_LORA_RECIPE def is_int8_lora_recipe(recipe) -> bool: diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py index 5189a268d9a1..e8718f690679 100644 --- a/unsloth/models/loader.py +++ b/unsloth/models/loader.py @@ -41,7 +41,7 @@ mark_fp8_lora, resolve_float8_training, resolve_fp8_lora, - float8_training_request, + int8_lora_from_env, ) from .mistral_format import ( MistralFormatRedirect, @@ -1458,15 +1458,6 @@ def from_pretrained( # @_offline_aware_load already forced offline when needed; delegations inherit it. fp8_lora = None - _int8_request = float8_training_request( - kwargs.get("float8_training", None), - full_finetuning, - quantized_base = bool(load_in_4bit or load_in_8bit or load_in_fp8 not in (False, None)), - dtype = dtype, - qat_scheme = qat_scheme, - ) - if _int8_request is not kwargs.get("float8_training", None): - kwargs["float8_training"] = _int8_request fp8_request = kwargs.get("float8_training", None) if kwargs.get("float8_training", None) not in (None, False) and not full_finetuning: fp8_lora = resolve_fp8_lora( @@ -2314,6 +2305,8 @@ def from_pretrained( model = _mark_forced_float32(model, False) # Full finetuning delegates to FastModel above, so this path is always LoRA. model = _mark_full_finetuning(model, False) + if fp8_lora is None and fp8_request in (None, False): + fp8_lora = int8_lora_from_env(model, qat_scheme = qat_scheme) model = mark_fp8_lora(model, fp8_lora) return _mark_requested_float32(model, user_float32), tokenizer @@ -2435,15 +2428,6 @@ def from_pretrained( ) user_config = kwargs.pop("config", None) fp8_lora = None - _int8_request = float8_training_request( - kwargs.get("float8_training", None), - full_finetuning, - quantized_base = bool(load_in_4bit or load_in_8bit or load_in_fp8 not in (False, None)), - dtype = dtype, - qat_scheme = qat_scheme, - ) - if _int8_request is not kwargs.get("float8_training", None): - kwargs["float8_training"] = _int8_request if not full_finetuning and kwargs.get("float8_training", None) not in (None, False): fp8_lora = resolve_fp8_lora( kwargs.pop("float8_training"), @@ -3899,6 +3883,10 @@ def _patched_car( print(f"Unsloth: float8 training on {len(converted)} Linear layers.") model = _mark_forced_float32(model, do_forced_float32) model = _mark_full_finetuning(model, full_finetuning) + if fp8_lora is None and float8_training is None: + fp8_lora = int8_lora_from_env( + model, full_finetuning = full_finetuning, qat_scheme = qat_scheme + ) model = mark_fp8_lora(model, fp8_lora) return _mark_requested_float32(model, user_float32), tokenizer