Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
39 changes: 36 additions & 3 deletions tests/test_offloaded_parameter_hint.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

"""Append the offload hint to the save error, never replace it; only when a meta parameter exists."""

import ast
import sys
from pathlib import Path

Expand Down Expand Up @@ -115,9 +116,41 @@ class NoDevice:
SRC = (ROOT / "unsloth" / "save.py").read_text(encoding = "utf-8")


def test_both_save_failure_paths_use_it():
"""GGUF export can fail at the merge or the plain save step; offloading breaks both."""
assert SRC.count("_offloaded_parameter_hint(self)") == 2
def _save_failure_messages():
"""Each `raise RuntimeError(f"Failed to save...")` in save.py, with whether its message carries the hint."""
for node in ast.walk(ast.parse(SRC)):
if not (
isinstance(node, ast.Raise)
and isinstance(node.exc, ast.Call)
and isinstance(node.exc.func, ast.Name)
and node.exc.func.id == "RuntimeError"
and node.exc.args
and isinstance(node.exc.args[0], ast.JoinedStr)
):
continue
message = node.exc.args[0]
text = "".join(v.value for v in message.values if isinstance(v, ast.Constant))
if not text.startswith("Failed to save"):
continue
hinted = any(
isinstance(v, ast.FormattedValue)
and isinstance(v.value, ast.Call)
and isinstance(v.value.func, ast.Name)
and v.value.func.id == "_offloaded_parameter_hint"
for v in message.values
)
yield node.lineno, text, hinted


def test_every_save_failure_path_uses_it():
"""GGUF export can fail at the merge, the plain save or (#20022) the GGUF-packed dense write; offloading
breaks each, so every "Failed to save" error names it. A count of call sites broke when a path was added."""
messages = list(_save_failure_messages())
assert {text.split(":")[0] for _, text, _ in messages} >= {
"Failed to save/merge model",
"Failed to save model",
}
assert [line for line, _, hinted in messages if not hinted] == []


def test_the_original_error_is_still_reported():
Expand Down
42 changes: 36 additions & 6 deletions tests/test_optimized_precision_conflicts.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,17 +66,33 @@ def _loader_utils_functions(

def _real_function(path, name):
"""One self-contained function compiled from its module's source, so the fixture runs the real code without
importing the module (unsloth.models._utils pulls in torch)."""
node = next(
importing the module (unsloth.models._utils pulls in torch). Module-level literal constants the function
reads (gguf_packed.GGUF_PACKED_KWARG) come with it."""
body = ast.parse(path.read_text(encoding = "utf-8")).body
node = next(n for n in body if isinstance(n, ast.FunctionDef) and n.name == name)
reads = {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
constants = [
n
for n in ast.parse(path.read_text(encoding = "utf-8")).body
if isinstance(n, ast.FunctionDef) and n.name == name
)
for n in body
if isinstance(n, ast.Assign)
and len(n.targets) == 1
and isinstance(n.targets[0], ast.Name)
and n.targets[0].id in reads
and _is_literal(n.value)
]
namespace = {}
exec(compile(ast.Module([node], type_ignores = []), str(path), "exec"), namespace)
exec(compile(ast.Module([*constants, node], type_ignores = []), str(path), "exec"), namespace)
return namespace[name]


def _is_literal(node):
try:
ast.literal_eval(node)
except ValueError:
return False
return True


def _gguf_load_module(path):
spec = importlib.util.spec_from_file_location("_unsloth_gguf_load_for_tests", path)
module = importlib.util.module_from_spec(spec)
Expand Down Expand Up @@ -177,6 +193,10 @@ def no_adapter(*args, **kwargs):
_unsloth_load_begins = lambda: None,
# #19889: the real helper. No case passes gguf_file, so it returns the 4bit / 8bit flags unchanged.
gguf_drop_bitsandbytes = _real_function(path.parent / "_utils.py", "gguf_drop_bitsandbytes"),
# #20022: the real check. No case passes gguf_packed, so it pops nothing and answers False.
check_gguf_packed_request = _real_function(
path.parent / "gguf_packed.py", "check_gguf_packed_request"
),
)
# #19947: from_pretrained imports its GGUF checks from unsloth/_gguf_load.py. That module needs only the stdlib,
# so the fixture loads all of it (helpers added there later included) instead of stubbing one name at a time.
Expand Down Expand Up @@ -423,3 +443,13 @@ def test_modelscope_adapter_base_missing_there_loads_from_the_hub(loader, models

assert captured["dispatch"]["model_name"] == "hf-only/base"
assert ("hf-only/base", None) in calls


def test_the_real_gguf_packed_check_runs_at_the_entry_point(loader):
"""The fixture binds the real check_gguf_packed_request, so a packed request without a file is refused
before any config probe or dispatch, as it is for users."""
env, captured = loader
with pytest.raises(ValueError, match = "gguf_file"):
env["from_pretrained"](gguf_packed = True)
assert captured["config_calls"] == 0
assert "dispatch" not in captured
4 changes: 2 additions & 2 deletions unsloth/models/gguf_packed.py
Original file line number Diff line number Diff line change
Expand Up @@ -1234,13 +1234,13 @@ def flush():
os.replace(old, os.path.join(directory, new))
renamed[f"model-{index:05d}.safetensors"] = new
weight_map = {name: renamed[file] for name, file in weight_map.items()}
with open(os.path.join(directory, "model.safetensors.index.json"), "w") as f:
with open(os.path.join(directory, "model.safetensors.index.json"), "w", encoding = "utf-8") as f:
json.dump({"metadata": {"total_size": total}, "weight_map": weight_map}, f, indent = 2)
config = base.config.to_dict()
config.pop("quantization_config", None)
config.pop("unsloth_gguf_packed", None)
config["torch_dtype"] = config["dtype"] = str(dtype).replace("torch.", "")
with open(os.path.join(directory, "config.json"), "w") as f:
with open(os.path.join(directory, "config.json"), "w", encoding = "utf-8") as f:
json.dump(config, f, indent = 2, default = str)
return directory

Expand Down
Loading