Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Load one tensor at a time when quantizing a 16-bit checkpoint on the fly (#12997)

Leo Borcherding3e7898659344
diff --git a/tests/test_sync_load_when_quantizing.py b/tests/test_sync_load_when_quantizing.py
new file mode 100644
index 00000000000..f50eebe8d29
--- /dev/null
+++ b/tests/test_sync_load_when_quantizing.py
@@ -0,0 +1,137 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""sync_load_when_quantizing, extracted with ast so nothing imports CUDA. No GPU needed."""
+
+import ast
+import contextlib
+import os
+import types
+
+import pytest
+
+HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+MODELS = os.path.join(HERE, "unsloth", "models")
+ENV = "HF_DEACTIVATE_ASYNC_LOAD"
+
+
+def _source(name):
+ with open(os.path.join(MODELS, name), encoding = "utf-8") as f:
+ return f.read()
+
+
+def _load_helper():
+ tree = ast.parse(_source("loader_utils.py"))
+ keep = [
+ node
+ for node in tree.body
+ if (isinstance(node, ast.FunctionDef) and node.name == "sync_load_when_quantizing")
+ or (
+ isinstance(node, ast.Assign)
+ and any(getattr(t, "id", None) == "_ASYNC_LOAD_ENV" for t in node.targets)
+ )
+ ]
+ assert len(keep) == 2
+ namespace = {"contextlib": contextlib, "os": os}
+ exec(compile(ast.Module(body = keep, type_ignores = []), "loader_utils", "exec"), namespace)
+ return namespace["sync_load_when_quantizing"]
+
+
+sync_load_when_quantizing = _load_helper()
+BNB = object()
+UNQUANTIZED = types.SimpleNamespace()
+PREQUANTIZED = types.SimpleNamespace(quantization_config = {"quant_method": "bitsandbytes"})
+
+
[email protected](autouse = True)
+def _clean_env(monkeypatch):
+ monkeypatch.delenv(ENV, raising = False)
+
+
+def test_on_the_fly_quantization_loads_synchronously_then_restores():
+ with sync_load_when_quantizing(BNB, UNQUANTIZED):
+ assert os.environ.get(ENV) == "1"
+ assert ENV not in os.environ
+
+
+def test_restores_when_the_load_raises():
+ with pytest.raises(RuntimeError):
+ with sync_load_when_quantizing(BNB, UNQUANTIZED):
+ raise RuntimeError("out of memory")
+ assert ENV not in os.environ
+
+
+ "quantization_config, config",
+ [(BNB, PREQUANTIZED), (None, UNQUANTIZED), (None, PREQUANTIZED)],
+ ids = ["prequantized", "16bit", "16bit-prequantized-config"],
+)
+def test_leaves_async_loading_alone_when_nothing_is_quantized_on_the_fly(
+ quantization_config, config
+):
+ with sync_load_when_quantizing(quantization_config, config):
+ assert ENV not in os.environ
+ assert ENV not in os.environ
+
+
+def test_a_caller_setting_wins(monkeypatch):
+ monkeypatch.setenv(ENV, "0")
+ with sync_load_when_quantizing(BNB, UNQUANTIZED):
+ assert os.environ[ENV] == "0"
+ assert os.environ[ENV] == "0"
+
+
+def _calls_inside_sync_load(src, callee):
+ """Each `<callee>.from_pretrained(...)` call, paired with whether a `with` around it uses the helper."""
+ tree = ast.parse(src)
+ parents = {}
+ for node in ast.walk(tree):
+ for child in ast.iter_child_nodes(node):
+ parents[child] = node
+ found = []
+ for node in ast.walk(tree):
+ if not (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "from_pretrained"
+ and getattr(node.func.value, "id", None) == callee
+ ):
+ continue
+ wrapped, cur = False, node
+ while cur in parents:
+ cur = parents[cur]
+ if isinstance(cur, ast.With) and any(
+ isinstance(item.context_expr, ast.Call)
+ and getattr(item.context_expr.func, "id", None) == "sync_load_when_quantizing"
+ for item in cur.items
+ ):
+ wrapped = True
+ break
+ found.append((node.lineno, wrapped))
+ return found
+
+
+ "module, callee",
+ [
+ ("vision.py", "auto_model"),
+ ("llama.py", "AutoModelForCausalLM"),
+ ("llama.py", "AutoModelForSequenceClassification"),
+ ("loader_utils.py", "auto_model"),
+ ("../save.py", "auto_model"),
+ ],
+)
+def test_every_on_the_fly_quantizing_load_runs_inside_the_helper(module, callee):
+ calls = _calls_inside_sync_load(_source(module), callee)
+ assert calls, f"no {callee}.from_pretrained in {module}"
+ assert all(wrapped for _, wrapped in calls), calls
+
+
+def test_transformers_reads_the_variable_where_it_picks_the_loader():
+ # Pins the contract the helper leans on: the variable is what turns the thread pool off.
+ core = pytest.importorskip("transformers.core_model_loading")
+ import inspect
+
+ src = inspect.getsource(core.convert_and_load_state_dict_in_model)
+ assert 'is_env_variable_true("HF_DEACTIVATE_ASYNC_LOAD")' in src
+ assert "thread_pool = None" in src
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index 76b02e5307a..e2a2ad29862 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -54,6 +54,7 @@ from .loader_utils import (
requested_device_map,
resolve_unsloth_device_map,
resolve_auto_block_swap,
+ sync_load_when_quantizing,
warn_if_bitsandbytes_quantized_nothing,
)
from ..utils.packing import (
@@ -3167,16 +3168,17 @@ class FastLlamaModel:
else:
setattr(model_config, _cfg_key, _cfg_val)
try:
- model = AutoModelForSequenceClassification.from_pretrained(
- model_name,
- config = model_config,
- device_map = device_map,
- token = token,
- trust_remote_code = trust_remote_code,
- attn_implementation = preferred_attn_impl,
- revision = revision,
- **kwargs,
- )
+ with sync_load_when_quantizing(kwargs.get("quantization_config"), model_config):
+ model = AutoModelForSequenceClassification.from_pretrained(
+ model_name,
+ config = model_config,
+ device_map = device_map,
+ token = token,
+ trust_remote_code = trust_remote_code,
+ attn_implementation = preferred_attn_impl,
+ revision = revision,
+ **kwargs,
+ )
finally:
disarm_fp8_to_nf4(model_config)
# Defensive: ensure the task head is in a floating dtype, guarding against any path leaving it
@@ -3247,30 +3249,34 @@ class FastLlamaModel:
if (_modelopt_rewritten or _fp8_to_nf4) and user_config is None:
move_config_overrides_onto_config(model_config, kwargs)
try:
+ with sync_load_when_quantizing(
+ kwargs.get("quantization_config"), model_config
+ ):
+ model = AutoModelForCausalLM.from_pretrained(
+ model_name,
+ config = model_config,
+ device_map = device_map,
+ token = token,
+ trust_remote_code = trust_remote_code,
+ attn_implementation = preferred_attn_impl,
+ revision = revision,
+ **kwargs,
+ )
+ finally:
+ # The load deep-copied the config; give the caller's object its fp8 block back.
+ disarm_fp8_to_nf4(model_config)
+ else:
+ with sync_load_when_quantizing(kwargs.get("quantization_config"), model_config):
model = AutoModelForCausalLM.from_pretrained(
model_name,
- config = model_config,
device_map = device_map,
token = token,
+ max_position_embeddings = max_position_embeddings,
trust_remote_code = trust_remote_code,
attn_implementation = preferred_attn_impl,
revision = revision,
**kwargs,
)
- finally:
- # The load deep-copied the config; give the caller's object its fp8 block back.
- disarm_fp8_to_nf4(model_config)
- else:
- model = AutoModelForCausalLM.from_pretrained(
- model_name,
- device_map = device_map,
- token = token,
- max_position_embeddings = max_position_embeddings,
- trust_remote_code = trust_remote_code,
- attn_implementation = preferred_attn_impl,
- revision = revision,
- **kwargs,
- )
warn_if_bitsandbytes_quantized_nothing(
model, kwargs.get("quantization_config", None), model_name
)
diff --git a/unsloth/models/loader_utils.py b/unsloth/models/loader_utils.py
index 49f189317d0..8d7ad339cdb 100644
--- a/unsloth/models/loader_utils.py
+++ b/unsloth/models/loader_utils.py
@@ -1538,12 +1538,13 @@ def _offline_quantize_to_fp8(
config = text_config
auto_model = AutoModelForImageTextToText if is_vlm else AutoModelForCausalLM
auto_processor = AutoProcessor if is_vlm else AutoTokenizer
- model = auto_model.from_pretrained(
- model_name,
- config = config,
- revision = revision,
- **load_kwargs,
- )
+ with sync_load_when_quantizing(qconfig, config):
+ model = auto_model.from_pretrained(
+ model_name,
+ config = config,
+ revision = revision,
+ **load_kwargs,
+ )
tokenizer = auto_processor.from_pretrained(model_name, revision = revision)
model.save_pretrained(new_model_name, safe_serialization = False)
del model
@@ -3064,6 +3065,27 @@ def _bnb_bits_requested(quantization_config):
return None
+_ASYNC_LOAD_ENV = "HF_DEACTIVATE_ASYNC_LOAD"
+
+
+def sync_load_when_quantizing(quantization_config, model_config):
+ """Sync-load on-the-fly quantization: transformers 5.0-5.3 worker threads put full-precision
+ tensors on the card faster than they are quantized (5.4+ already loads these synchronously)."""
+ if (
+ quantization_config is None
+ or getattr(model_config, "quantization_config", None) is not None
+ or _ASYNC_LOAD_ENV in os.environ
+ ):
+ yield
+ return
+ os.environ[_ASYNC_LOAD_ENV] = "1"
+ try:
+ yield
+ finally:
+ os.environ.pop(_ASYNC_LOAD_ENV, None)
+
+
def warn_if_bitsandbytes_quantized_nothing(
model,
quantization_config,
diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py
index ca4fa1495c3..793850e2f75 100644
--- a/unsloth/models/vision.py
+++ b/unsloth/models/vision.py
@@ -154,6 +154,7 @@ from .loader_utils import (
requested_device_map,
resolve_auto_block_swap,
resolve_unsloth_device_map,
+ sync_load_when_quantizing,
warn_if_bitsandbytes_quantized_nothing,
)
# `unsloth.save` imports `.models.loader_utils`, so binding a name out of it here at module
@@ -3537,9 +3538,14 @@ class FastBaseModel:
)
):
try:
- with begin_block_swap_load(
- _offload_layers, device_map, embeddings = bool(_embedding_needed)
- ) as (_block_swap_state):
+ with (
+ begin_block_swap_load(
+ _offload_layers, device_map, embeddings = bool(_embedding_needed)
+ ) as (_block_swap_state),
+ sync_load_when_quantizing(
+ kwargs.get("quantization_config"), model_config
+ ),
+ ):
model = auto_model.from_pretrained(
model_name,
config = model_config,
diff --git a/unsloth/save.py b/unsloth/save.py
index cfde2aec85e..67a885705df 100644
--- a/unsloth/save.py
+++ b/unsloth/save.py
@@ -62,6 +62,7 @@ import psutil
import re
from .models.loader_utils import (
get_model_name,
+ sync_load_when_quantizing,
_resolve_hub_repo_cached_file,
_tokenizer_cache_dir,
_tokenizer_revision,
@@ -6102,12 +6103,13 @@ def _unsloth_save_torchao_with_given_config(
# The original stays offloaded until the quantized copy is saved AND released, else both are resident at once and the restore OOMs.
try:
- quantized_model = auto_model.from_pretrained(
- save_directory,
- device_map = "auto",
- quantization_config = quantization_config,
- **kwargs,
- )
+ with sync_load_when_quantizing(quantization_config, None):
+ quantized_model = auto_model.from_pretrained(
+ save_directory,
+ device_map = "auto",
+ quantization_config = quantization_config,
+ **kwargs,
+ )
torchao_save_directory = save_directory + "-torchao"
@@ -6821,13 +6823,15 @@ def _unsloth_save_torchao(
# Reload the staged 16bit checkpoint with torchao applied: bfloat16 is required, and device_map="auto" falls back to CPU, so this works on any hardware.
print(f"Unsloth: Quantizing the merged model to torchao {kind}...")
dtype_kw = {"torch_dtype": torch.bfloat16} if HAS_TORCH_DTYPE else {"dtype": torch.bfloat16}
- quantized_model = auto_model.from_pretrained(
- staging,
- device_map = "auto",
- quantization_config = TorchAoConfig(quant_type = quant_type),
- trust_remote_code = model_trust,
- **dtype_kw,
- )
+ _reload_qconfig = TorchAoConfig(quant_type = quant_type)
+ with sync_load_when_quantizing(_reload_qconfig, None):
+ quantized_model = auto_model.from_pretrained(
+ staging,
+ device_map = "auto",
+ quantization_config = _reload_qconfig,
+ trust_remote_code = model_trust,
+ **dtype_kw,
+ )
staged_tokenizer = auto_processor.from_pretrained(staging, trust_remote_code = tok_trust)
quantized_model.save_pretrained(out_dir, safe_serialization = safe_serialization)