Repository navigation
fix: preserve FP8 weight_scale_inv on load #6749
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 2 commits
8cbf9e9
0ca7ca4
a2640a0
a8e4474
cf0e821
41c9918
7022b70
9d8cdee
2c560a6
7eb0d47
c619ad4
8f43bb8
2331a14
1289285
96beef3
0d783fd
2d95984
c2279a4
b61f390
04008ed
508c4ae
727a2c3
beb07a0
db79e37
554ae3a
88903aa
bc71f41
7650ed7
b3165b3
0d6c49c
c1eed80
d5b499f
9a57062
da86965
88985b5
720ebce
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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 | ||
| 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 | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
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 | ||
|
rodboev marked this conversation as resolved.
Resolved
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( | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When restoring scales for a remote FP8 repo, this Useful? React with 👍 / 👎.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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" | ||
|
rodboev marked this conversation as resolved.
Resolved
|
||
| for filename in os.listdir(model_dir): | ||
|
rodboev marked this conversation as resolved.
Resolved
|
||
| if not filename.endswith(".safetensors"): | ||
|
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 | ||
|
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) | ||
|
rodboev marked this conversation as resolved.
Resolved
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) | ||
|
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, | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.