Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
int8 LoRA base: decide the env opt-in on the loaded model (after '-bf…
…16' precision normalization), not on the load flags
  • Loading branch information
danielhanchen committed Nov 27, 2026
commit f8233469731453fd33bdcca07fa96a6090e12507
98 changes: 53 additions & 45 deletions tests/test_int8_lora_recipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
72 changes: 48 additions & 24 deletions unsloth/models/float8_training.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
26 changes: 7 additions & 19 deletions unsloth/models/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -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

Expand Down