Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
8cbf9e9
fix: preserve FP8 weight_scale_inv on load
rodboev Jun 29, 2026
0ca7ca4
fix: register restored FP8 inverse scales
rodboev Jun 29, 2026
a2640a0
fix: keep optional FP8 kernel imports non-fatal
rodboev Jun 29, 2026
a8e4474
fix: restore mapped FP8 inverse scales
rodboev Jun 29, 2026
cf0e821
fix: restore exact FP8 checkpoint scales
rodboev Jun 29, 2026
41c9918
fix: constrain FP8 scale restore to selected safetensors
rodboev Jul 7, 2026
7022b70
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 7, 2026
9d8cdee
fix: restore selected FP8 scale variants without placeholders
rodboev Jul 7, 2026
2c560a6
fix: keep FP8 scale restore shard-aware
rodboev Jul 7, 2026
7eb0d47
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 7, 2026
c619ad4
fix: align FP8 restore with selected safetensors caches
rodboev Jul 7, 2026
8f43bb8
fix: keep FP8 scale repair aligned with safe caches
rodboev Jul 7, 2026
2331a14
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 7, 2026
1289285
fix: preserve FP8 remap intent through PEFT
rodboev Jul 7, 2026
96beef3
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 7, 2026
0d783fd
Restore dropped FP8 expert scale on the projection device for PR #6749
danielhanchen Jul 7, 2026
2d95984
Preserve the adapter repo name through the FP8 base remap in FastMode…
danielhanchen Jul 7, 2026
c2279a4
Merge branch 'main' into pr/6200-fp8-scale-inv-load to refresh base
danielhanchen Jul 7, 2026
b61f390
Constrain FP8 scale-restore snapshot download to selected safetensors…
danielhanchen Jul 7, 2026
04008ed
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 7, 2026
508c4ae
Cover sharded FP8 variant shards in scale-restore patterns and match …
danielhanchen Jul 7, 2026
727a2c3
Narrow no-variant FP8 scale snapshot patterns to default artifacts fo…
danielhanchen Jul 7, 2026
beb07a0
Preserve FP8 scale parameters and fetch index-named scale shards for …
danielhanchen Jul 7, 2026
db79e37
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 7, 2026
554ae3a
Restore transposed FP8 scales and preserve scale parameter metadata f…
danielhanchen Jul 7, 2026
88903aa
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 7, 2026
bc71f41
Tighten comments for PR #6749
danielhanchen Jul 8, 2026
7650ed7
Narrow variant FP8 globs, restore meta-placeholder and static activat…
danielhanchen Jul 8, 2026
b3165b3
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jul 8, 2026
0d6c49c
Guard FP8 cache regeneration, meta scale parameters, and index-only s…
danielhanchen Jul 8, 2026
c1eed80
Prefer projection device, preserve meta scale metadata, bin-cache fal…
danielhanchen Jul 8, 2026
d5b499f
Gate FP8 bin-cache fallback safetensors forcing and force safetensors…
danielhanchen Jul 8, 2026
9a57062
Tighten comments for PR #6749
danielhanchen Jul 8, 2026
da86965
Restore FP8 scales onto the weight device over a CPU placeholder for …
danielhanchen Jul 8, 2026
88985b5
Carry module block_size onto restored FP8 scales with dropped placeho…
danielhanchen Jul 8, 2026
720ebce
Tighten comments for PR #6749
danielhanchen Jul 8, 2026
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
189 changes: 189 additions & 0 deletions tests/test_fp8_scale_inv_load.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
import ast
import importlib.util
import os
from pathlib import Path
import sys
import tempfile
import types

import torch
from safetensors.torch import save_file


REPO_ROOT = Path(__file__).resolve().parents[1]
LOADER_UTILS = REPO_ROOT / "unsloth" / "models" / "loader_utils.py"
LOADER = REPO_ROOT / "unsloth" / "models" / "loader.py"


def _install_stub_package(name, path):
module = types.ModuleType(name)
module.__path__ = [str(path)]
sys.modules[name] = module
Comment thread
rodboev marked this conversation as resolved.
Resolved
return module


def _install_loader_utils_stubs():
_install_stub_package("unsloth", REPO_ROOT / "unsloth")
_install_stub_package("unsloth.models", REPO_ROOT / "unsloth" / "models")
_install_stub_package("unsloth_zoo", REPO_ROOT)

device_type = types.ModuleType("unsloth.device_type")
device_type.DEVICE_TYPE_TORCH = "cuda"
sys.modules["unsloth.device_type"] = device_type

mapper = types.ModuleType("unsloth.models.mapper")
mapper.INT_TO_FLOAT_MAPPER = {}
mapper.FLOAT_TO_INT_MAPPER = {}
mapper.MAP_TO_UNSLOTH_16bit = {}
mapper.FLOAT_TO_FP8_BLOCK_MAPPER = {}
mapper.FLOAT_TO_FP8_ROW_MAPPER = {}
sys.modules["unsloth.models.mapper"] = mapper

model_utils = types.ModuleType("unsloth.models._utils")
model_utils.TorchAOConfig = type("TorchAOConfig", (), {})
sys.modules["unsloth.models._utils"] = model_utils

zoo_utils = types.ModuleType("unsloth_zoo.utils")
zoo_utils.Version = lambda value: value
zoo_utils.get_quant_type = lambda config: None
sys.modules["unsloth_zoo.utils"] = zoo_utils


def _load_loader_utils():
_install_loader_utils_stubs()
sys.modules.pop("unsloth.models.loader_utils", None)
spec = importlib.util.spec_from_file_location("unsloth.models.loader_utils", LOADER_UTILS)
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)
return module


def _make_checkpoint(path, tensors):
full_path = os.path.join(path, "model-00001-of-00001.safetensors")
save_file(tensors, full_path)
return path


class _Fp8Owner(torch.nn.Module):
def __init__(self, weight, quant_method = "fp8", weight_scale = None):
super().__init__()
self.weight = torch.nn.Parameter(weight)
self.quant_method = quant_method
if weight_scale is not None:
self.weight_scale = weight_scale


def test_restores_missing_fp8_weight_scale_inv():
loader_utils = _load_loader_utils()
model = torch.nn.Module()
model.fp8 = _Fp8Owner(weight = torch.randn(4, 4, dtype = torch.float16))

with tempfile.TemporaryDirectory() as checkpoint_dir:
_make_checkpoint(
checkpoint_dir,
{"fp8.weight_scale_inv": torch.tensor([1.25], dtype = torch.float32)},
)
restored, skipped = loader_utils._restore_missing_fp8_weight_scale_inv(
model,
model_name = checkpoint_dir,
local_files_only = True,
)

assert restored == 1
assert skipped == 0
assert torch.equal(model.fp8.weight_scale_inv, torch.tensor([1.25], dtype = torch.float16))
assert "fp8.weight_scale_inv" in model.state_dict()
assert torch.equal(
model.state_dict()["fp8.weight_scale_inv"],
torch.tensor([1.25], dtype = torch.float16),
)
assert not hasattr(model.fp8, "weight_scale")


def test_does_not_attach_scale_inv_to_non_fp8_module():
loader_utils = _load_loader_utils()
model = torch.nn.Module()
model.linear = _Fp8Owner(weight = torch.randn(4, 4, dtype = torch.float16), quant_method = "int8")

with tempfile.TemporaryDirectory() as checkpoint_dir:
_make_checkpoint(
checkpoint_dir,
{"linear.weight_scale_inv": torch.tensor([0.5], dtype = torch.float32)},
)
restored, skipped = loader_utils._restore_missing_fp8_weight_scale_inv(
model,
model_name = checkpoint_dir,
local_files_only = True,
)

assert restored == 0
assert skipped == 1
assert not hasattr(model.linear, "weight_scale_inv")


def test_preserves_existing_scale_state():
loader_utils = _load_loader_utils()
weight_scale = torch.tensor([3.0], dtype = torch.float16)
model = torch.nn.Module()
model.fp8 = _Fp8Owner(
weight = torch.randn(4, 4, dtype = torch.float16),
weight_scale = weight_scale,
)
existing_inv = torch.tensor([5.0], dtype = torch.float16)
model.fp8.register_buffer("weight_scale_inv", existing_inv)
weight_scale_id = id(model.fp8.weight_scale)
weight_scale_inv_id = id(model.fp8.weight_scale_inv)

with tempfile.TemporaryDirectory() as checkpoint_dir:
_make_checkpoint(
checkpoint_dir,
{"fp8.weight_scale_inv": torch.tensor([1.0], dtype = torch.float32)},
)
restored, skipped = loader_utils._restore_missing_fp8_weight_scale_inv(
model,
model_name = checkpoint_dir,
local_files_only = True,
)

assert restored == 0
assert skipped == 1
assert id(model.fp8.weight_scale_inv) == weight_scale_inv_id
assert id(model.fp8.weight_scale) == weight_scale_id
assert torch.equal(model.fp8.weight_scale, weight_scale)
assert torch.equal(model.fp8.weight_scale_inv, existing_inv)
assert "fp8.weight_scale_inv" in model.state_dict()
assert torch.equal(model.state_dict()["fp8.weight_scale_inv"], existing_inv)


def test_loader_calls_restore_only_for_fp8_loads():
tree = ast.parse(LOADER.read_text())
hit_count = 0

for node in ast.walk(tree):
if not isinstance(node, ast.If):
continue
test = node.test
if not (
isinstance(test, ast.Compare)
and isinstance(test.left, ast.Name)
and test.left.id == "load_in_fp8"
and len(test.ops) == 1
and isinstance(test.ops[0], ast.NotEq)
and len(test.comparators) == 1
and isinstance(test.comparators[0], ast.Constant)
and test.comparators[0].value is False
):
continue

call_names = set()
for child in ast.walk(node):
if isinstance(child, ast.Call) and isinstance(child.func, ast.Name):
call_names.add(child.func.id)
if {
"_restore_missing_fp8_weight_scale_inv",
"_tag_model_with_fp8_torchao_config",
}.issubset(call_names):
hit_count += 1

assert hit_count == 2
15 changes: 15 additions & 0 deletions unsloth/models/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
_exclude_rope_inv_freq_from_ddp,
_get_fp8_mode_and_check_settings,
_offline_quantize_to_fp8,
_restore_missing_fp8_weight_scale_inv,
_tag_model_with_fp8_torchao_config,
get_model_name,
prepare_device_map,
Expand Down Expand Up @@ -860,6 +861,13 @@ def from_pretrained(
model.config.update({"quantization_config": quantization_config})

if load_in_fp8 != False:
_restored_count, _skipped_count = _restore_missing_fp8_weight_scale_inv(
Comment thread
rodboev marked this conversation as resolved.
Resolved
model,
model_name,
token = token,
revision = revision,
Comment thread
rodboev marked this conversation as resolved.
Resolved
local_files_only = local_files_only,
)
Comment thread
rodboev marked this conversation as resolved.
Resolved
_tag_model_with_fp8_torchao_config(model, fp8_mode)

if is_peft:
Expand Down Expand Up @@ -1733,6 +1741,13 @@ def _dispatch_diffusion():
model.config.update({"quantization_config": quantization_config})

if load_in_fp8 != False:
_restored_count, _skipped_count = _restore_missing_fp8_weight_scale_inv(
model,
model_name,
Comment thread
rodboev marked this conversation as resolved.
Resolved
token = token,
revision = revision,
local_files_only = local_files_only,
)
_tag_model_with_fp8_torchao_config(model, fp8_mode)

if is_peft:
Expand Down
156 changes: 156 additions & 0 deletions unsloth/models/loader_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,162 @@ def _tag_model_with_fp8_torchao_config(model: torch.nn.Module, fp8_mode: str):
pass


def _has_float8_dtype(dtype):
dtype_name = str(dtype)
return dtype_name.startswith("torch.float8_")


def _is_real_fp8_owner(module):
if not isinstance(module, torch.nn.Module):
return False
weight = getattr(module, "weight", None)
if not isinstance(weight, torch.Tensor):
return False
Comment thread
rodboev marked this conversation as resolved.
Resolved
if getattr(module, "quant_method", None) in ["fp8", "fbgemm_fp8"]:
return True
if getattr(weight, "quant_method", None) in ["fp8", "fbgemm_fp8"]:
return True

config = getattr(module, "quantization_config", None)
if isinstance(config, dict) and config.get("quant_method") in ["fp8", "fbgemm_fp8"]:
return True
if getattr(config, "quant_method", None) in ["fp8", "fbgemm_fp8"]:
return True

if _has_float8_dtype(getattr(weight, "dtype", None)):
return True

try:
from ..kernels.fp8 import FbgemmFp8Linear, FP8Linear
except Exception:
FbgemmFp8Linear, FP8Linear = None, None
Comment thread
rodboev marked this conversation as resolved.
Resolved
Comment thread
rodboev marked this conversation as resolved.
Resolved
if FbgemmFp8Linear is not None and isinstance(module, FbgemmFp8Linear):
return True
if FP8Linear is not None and isinstance(module, FP8Linear):
return True

return False


def _resolve_weight_scale_inv_candidates(module_name, named_modules):
if module_name in named_modules:
return module_name
suffix = f".{module_name}"
suffix_matches = [name for name in named_modules if name.endswith(suffix)]
if len(suffix_matches) == 1:
return suffix_matches[0]
return None


def _find_fp8_scale_inv_tensors(model_dir, model_name, revision = None, token = None, local_files_only = False):
if not os.path.exists(model_dir):
try:
from huggingface_hub import snapshot_download
except Exception:
return []

try:
model_dir = snapshot_download(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Avoid downloading the entire Hub snapshot

When restoring scales for a remote FP8 repo, this snapshot_download runs before the code applies subfolder, variant, or use_safetensors, and it has no allow_patterns/ignore_patterns. For repos that also publish .bin weights, alternate variants, or other large artifacts, a normal load that only used selected safetensors can now pull the full snapshot after the model is already loaded, which can exhaust disk/network and defeats the intended bin-shard skip. Fetch only the index and selected safetensor shards (or constrain the snapshot patterns) for the same artifact selection used by from_pretrained.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b61f390: the scale-restore snapshot_download now passes allow_patterns limiting it to the selected safetensors shards plus their index (variant and subfolder aware), and skips the download entirely when use_safetensors is False, so it no longer pulls the full repo after load.

model_name,
revision = revision,
token = token,
local_files_only = local_files_only,
)
except Exception:
return []

if not os.path.isdir(model_dir):
return []

try:
from safetensors.torch import safe_open
except Exception:
return []

module_scales = {}
suffix = ".weight_scale_inv"
Comment thread
rodboev marked this conversation as resolved.
Resolved
for filename in os.listdir(model_dir):
Comment thread
rodboev marked this conversation as resolved.
Resolved
if not filename.endswith(".safetensors"):
Comment thread
rodboev marked this conversation as resolved.
Resolved
continue
full_path = os.path.join(model_dir, filename)
try:
with safe_open(full_path, framework = "pt", device = "cpu") as f:
for key in f.keys():
if not key.endswith(suffix):
continue
module_name = key[: -len(suffix)]
module_scales[module_name] = f.get_tensor(key)
except Exception:
continue
return list(module_scales.items())


def _restore_missing_fp8_weight_scale_inv(
model: torch.nn.Module,
model_name: str,
token = None,
revision = None,
local_files_only = False,
):
"""Find checkpointed `.weight_scale_inv` tensors and restore missing runtime tensors on FP8 modules.

Returns a tuple of `(restored_count, skipped_count)`.
"""
if not hasattr(model, "named_modules"):
return 0, 0

name_to_module = dict(model.named_modules())
scaled_tensors = _find_fp8_scale_inv_tensors(
model_dir = model_name,
model_name = model_name,
revision = revision,
token = token,
local_files_only = local_files_only,
)
if len(scaled_tensors) == 0:
return 0, 0

restored = 0
skipped = 0
for module_name, scale_tensor in scaled_tensors:
target_name = _resolve_weight_scale_inv_candidates(module_name, name_to_module)
if target_name is None:
skipped += 1
continue

module = name_to_module[target_name]
if not _is_real_fp8_owner(module):
skipped += 1
continue

if hasattr(module, "weight_scale_inv"):
skipped += 1
continue
Comment thread
rodboev marked this conversation as resolved.
Resolved

weight = getattr(module, "weight", None)
if not isinstance(weight, torch.Tensor):
skipped += 1
continue

restored_scale = scale_tensor.to(device = weight.device)
Comment thread
rodboev marked this conversation as resolved.
Resolved
Comment thread
rodboev marked this conversation as resolved.
Resolved
reference = getattr(module, "weight_scale", None)
if isinstance(reference, torch.Tensor):
try:
restored_scale = restored_scale.to(dtype = reference.dtype)
except Exception:
pass
elif not _has_float8_dtype(getattr(weight, "dtype", None)):
try:
restored_scale = restored_scale.to(dtype = weight.dtype)
Comment thread
rodboev marked this conversation as resolved.
Resolved
except Exception:
pass

module.register_buffer("weight_scale_inv", restored_scale)
restored += 1

return restored, skipped


def check_and_disable_bitsandbytes_loading(
model_config,
load_in_4bit = True,
Expand Down