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.

Add install_missing_dependencies to opt out of the FP8/FP4 llm-compressor auto-install (#9405)

Sourav Rajviaa56f661eb52
diff --git a/tests/saving/test_llm_compressor_install_consent.py b/tests/saving/test_llm_compressor_install_consent.py
new file mode 100644
index 00000000000..1d8c08d82ad
--- /dev/null
+++ b/tests/saving/test_llm_compressor_install_consent.py
@@ -0,0 +1,89 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""FP8/FP4 export auto-installs a missing llm-compressor unless install_missing_dependencies=False or the env opt-out is set (#8904)."""
+
+import importlib.abc
+import inspect
+import sys
+
+import pytest
+
+import unsloth.save as save
+
+
+class _NoLlmCompressor(importlib.abc.MetaPathFinder):
+ def find_spec(
+ self,
+ name,
+ path,
+ target = None,
+ ):
+ if name == "llmcompressor" or name.startswith("llmcompressor."):
+ raise ImportError("simulated missing llm-compressor")
+
+
+def pip_calls(tmp_path, monkeypatch):
+ monkeypatch.setenv("PYTHONPATH", str(tmp_path))
+ monkeypatch.delenv("UNSLOTH_DISABLE_LLM_COMPRESSOR_AUTOINSTALL", raising = False)
+ monkeypatch.setattr(save, "_llm_compressor_imports_in_subprocess", lambda: False)
+ calls = []
+ monkeypatch.setattr(save.subprocess, "check_call", lambda cmd, *a, **k: calls.append(cmd))
+ blocker = _NoLlmCompressor()
+ sys.meta_path.insert(0, blocker)
+ yield calls
+ sys.meta_path.remove(blocker)
+
+
+def test_default_runs_the_pinned_install(pip_calls):
+ with pytest.raises(RuntimeError, match = "installed but could not be imported"):
+ save.install_llm_compressor()
+ assert len(pip_calls) == 1
+ assert save._LLM_COMPRESSOR_SPEC in pip_calls[0]
+
+
+def test_opt_out_raises_with_manual_command_and_never_installs(pip_calls):
+ with pytest.raises(RuntimeError) as e:
+ save.install_llm_compressor(install_missing_dependencies = False)
+ assert pip_calls == []
+ assert save.llm_compressor_manual_install_command() in str(e.value)
+ assert "install_missing_dependencies=False" in str(e.value)
+
+
[email protected]("has_pip", [True, False])
+def test_manual_command_matches_the_available_installer(monkeypatch, has_pip):
+ import importlib.util
+
+ find_spec = importlib.util.find_spec
+ monkeypatch.setattr(
+ importlib.util,
+ "find_spec",
+ lambda name, *a, **k: (find_spec(name, *a, **k) if has_pip else None)
+ if name == "pip"
+ else find_spec(name, *a, **k),
+ )
+ command = save.llm_compressor_manual_install_command()
+ assert command.startswith(f"{sys.executable} -m pip install" if has_pip else "uv pip install")
+
+
+def test_env_optout_blocks_install(pip_calls, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_DISABLE_LLM_COMPRESSOR_AUTOINSTALL", "1")
+ with pytest.raises(RuntimeError, match = "UNSLOTH_DISABLE_LLM_COMPRESSOR_AUTOINSTALL") as e:
+ save.install_llm_compressor(install_missing_dependencies = True)
+ assert pip_calls == []
+ assert "install_missing_dependencies" not in str(e.value)
+
+
+ "fn",
+ [
+ save.unsloth_save_pretrained_merged,
+ save.unsloth_push_to_hub_merged,
+ save.unsloth_generic_save_pretrained_merged,
+ save.unsloth_generic_push_to_hub_merged,
+ save._unsloth_save_compressed_tensors,
+ ],
+)
+def test_entrypoints_default_to_install(fn):
+ assert inspect.signature(fn).parameters["install_missing_dependencies"].default is True
diff --git a/unsloth/save.py b/unsloth/save.py
index c0d2106aa25..082b5a793e4 100644
--- a/unsloth/save.py
+++ b/unsloth/save.py
@@ -1598,6 +1598,33 @@ def _compressed_quantize_pythonpath():
return pp or None
+def llm_compressor_manual_install_command() -> str:
+ import importlib.util
+ if importlib.util.find_spec("pip") is not None:
+ return f"{sys.executable} -m pip install '{_LLM_COMPRESSOR_SPEC}'"
+ return f"uv pip install --python {sys.executable} '{_LLM_COMPRESSOR_SPEC}'"
+
+
+def _llm_compressor_missing_error(*, autoinstall_disabled: bool) -> str:
+ reason = (
+ ", and automatic installation is disabled via UNSLOTH_DISABLE_LLM_COMPRESSOR_AUTOINSTALL"
+ if autoinstall_disabled
+ else ""
+ )
+ message = (
+ "Unsloth: llm-compressor is required for FP8/FP4 compressed export but is not "
+ f"installed{reason}. Install it manually with:\n"
+ f" {llm_compressor_manual_install_command()}\n"
+ "(pin torch and transformers to your current versions to avoid upgrading them)."
+ )
+ if not autoinstall_disabled:
+ message += (
+ "\nOr drop install_missing_dependencies=False to let Unsloth install the pinned "
+ "package into this interpreter."
+ )
+ return message
+
+
def _llm_compressor_imports_in_subprocess():
"""True only if a fresh interpreter, launched like the export's quantize runner, imports an llm-compressor inside _LLM_COMPRESSOR_SPEC."""
# sys.path[0] as `python _compressed_quantize.py` sets it; the caller's cwd is kept so relative PYTHONPATH entries resolve the same way.
@@ -1627,8 +1654,8 @@ def _llm_compressor_imports_in_subprocess():
return False
-def install_llm_compressor():
- """Import llm-compressor, installing a version-pinned copy on first use for FP8/FP4 export and pinning the current torch + transformers so pip does not upgrade them. UNSLOTH_DISABLE_LLM_COMPRESSOR_AUTOINSTALL=1 forbids the auto-install. Returns (oneshot, QuantizationModifier)."""
+def install_llm_compressor(install_missing_dependencies: bool = True):
+ """Import llm-compressor for FP8/FP4 export, installing a version-pinned copy on first use (pinning the current torch + transformers so pip does not upgrade them). install_missing_dependencies=False or UNSLOTH_DISABLE_LLM_COMPRESSOR_AUTOINSTALL=1 forbids the install and raises with the manual install command instead. Returns (oneshot, QuantizationModifier)."""
try:
from llmcompressor import oneshot
from llmcompressor.modifiers.quantization import QuantizationModifier
@@ -1640,20 +1667,11 @@ def install_llm_compressor():
if _llm_compressor_imports_in_subprocess():
return None, None
- # Opt-out for locked-down / air-gapped setups: forbid the auto-install, require a manual one.
- if os.environ.get("UNSLOTH_DISABLE_LLM_COMPRESSOR_AUTOINSTALL", "0").lower() not in (
- "0",
- "",
- "false",
- "no",
- ):
- raise RuntimeError(
- "Unsloth: llm-compressor is required for FP8/FP4 compressed export but is not "
- "installed, and automatic installation is disabled via "
- "UNSLOTH_DISABLE_LLM_COMPRESSOR_AUTOINSTALL. Install it manually with:\n"
- f" uv pip install --python {sys.executable} '{_LLM_COMPRESSOR_SPEC}'\n"
- "(pin torch and transformers to your current versions to avoid upgrading them)."
- )
+ autoinstall_disabled = os.environ.get(
+ "UNSLOTH_DISABLE_LLM_COMPRESSOR_AUTOINSTALL", "0"
+ ).lower() not in ("0", "", "false", "no")
+ if autoinstall_disabled or not install_missing_dependencies:
+ raise RuntimeError(_llm_compressor_missing_error(autoinstall_disabled = autoinstall_disabled))
print(
"Unsloth: Installing llm-compressor for FP8/FP4 export "
@@ -2321,6 +2339,7 @@ def unsloth_save_pretrained_merged(
calibration_dataset = None,
num_calibration_samples: int = 512,
max_seq_length: int = 2048,
+ install_missing_dependencies: bool = True,
):
"""
Same as .save_pretrained(...) except 4bit weights are auto
@@ -2336,7 +2355,8 @@ def unsloth_save_pretrained_merged(
methods do. Useful for HF inference.
4. FP8 / FP4 compressed export for vLLM (`fp8`, `mxfp4`, `nvfp4`, `mxfp8`): keeps the
16bit merge at `save_directory` and writes the quantized checkpoint to
- `save_directory + "-<fmt>"`.
+ `save_directory + "-<fmt>"`. A missing llm-compressor is installed on first use; pass
+ ``install_missing_dependencies=False`` to raise with the install command instead.
`safe_serialization` defaults to safetensors. `None` is stronger than the default `True`: on a host
with at most two physical CPUs the default downgrades to a pickle, since safetensors is
@@ -2378,6 +2398,7 @@ def unsloth_save_pretrained_merged(
calibration_dataset = calibration_dataset,
num_calibration_samples = num_calibration_samples,
max_seq_length = max_seq_length,
+ install_missing_dependencies = install_missing_dependencies,
state_dict = state_dict,
save_function = save_function,
max_shard_size = max_shard_size,
@@ -2430,6 +2451,7 @@ def unsloth_save_pretrained_merged(
del arguments["calibration_dataset"]
del arguments["num_calibration_samples"]
del arguments["max_seq_length"]
+ del arguments["install_missing_dependencies"]
unsloth_save_model(**arguments)
for _ in range(3):
gc.collect()
@@ -2456,6 +2478,7 @@ def unsloth_push_to_hub_merged(
calibration_dataset = None,
num_calibration_samples: int = 512,
max_seq_length: int = 2048,
+ install_missing_dependencies: bool = True,
):
"""
Same as .push_to_hub(...) except 4bit weights are auto
@@ -2470,6 +2493,7 @@ def unsloth_push_to_hub_merged(
Passing `tokenizer` also writes that tokenizer's files, exactly as the merge
methods do. Useful for HF inference.
4. FP8 / FP4 compressed export for vLLM: `fp8`, `mxfp4`, `nvfp4`, `mxfp8`.
+ Pass ``install_missing_dependencies=False`` to never auto-install llm-compressor.
`safe_serialization` defaults to safetensors. `None` is stronger than the default `True`: on a host
with at most two physical CPUs the default downgrades to a pickle, since safetensors is
@@ -2502,6 +2526,7 @@ def unsloth_push_to_hub_merged(
calibration_dataset = calibration_dataset,
num_calibration_samples = num_calibration_samples,
max_seq_length = max_seq_length,
+ install_missing_dependencies = install_missing_dependencies,
use_temp_dir = use_temp_dir,
max_shard_size = max_shard_size,
safe_serialization = safe_serialization,
@@ -2554,6 +2579,7 @@ def unsloth_push_to_hub_merged(
del arguments["calibration_dataset"]
del arguments["num_calibration_samples"]
del arguments["max_seq_length"]
+ del arguments["install_missing_dependencies"]
unsloth_save_model(**arguments)
for _ in range(3):
gc.collect()
@@ -5733,6 +5759,7 @@ def unsloth_generic_save_pretrained_merged(
calibration_dataset = None,
num_calibration_samples: int = 512,
max_seq_length: int = 2048,
+ install_missing_dependencies: bool = True,
):
"""
Same as .push_to_hub(...) except 4bit weights are auto
@@ -5750,6 +5777,7 @@ def unsloth_generic_save_pretrained_merged(
`fp8` (dynamic W8A8), `mxfp4`, `nvfp4` (W4A4), `mxfp8`. The LoRA is merged to 16bit at
`save_directory`, then a quantized checkpoint is written to `save_directory + "-<fmt>"`.
`nvfp4` needs calibration data (defaults to ultrachat; override with `calibration_dataset`).
+ Pass ``install_missing_dependencies=False`` to never auto-install llm-compressor.
`safe_serialization` defaults to safetensors. `None` is stronger than the default `True`: on a host
with at most two physical CPUs the default downgrades to a pickle, since safetensors is
@@ -5792,6 +5820,7 @@ def unsloth_generic_save_pretrained_merged(
calibration_dataset = calibration_dataset,
num_calibration_samples = num_calibration_samples,
max_seq_length = max_seq_length,
+ install_missing_dependencies = install_missing_dependencies,
state_dict = state_dict,
save_function = save_function,
max_shard_size = max_shard_size,
@@ -5842,6 +5871,7 @@ def unsloth_generic_save_pretrained_merged(
del arguments["calibration_dataset"]
del arguments["num_calibration_samples"]
del arguments["max_seq_length"]
+ del arguments["install_missing_dependencies"]
unsloth_generic_save(**arguments)
for _ in range(3):
gc.collect()
@@ -5868,6 +5898,7 @@ def unsloth_generic_push_to_hub_merged(
calibration_dataset = None,
num_calibration_samples: int = 512,
max_seq_length: int = 2048,
+ install_missing_dependencies: bool = True,
):
"""
Same as .push_to_hub(...) except 4bit weights are auto
@@ -5882,6 +5913,7 @@ def unsloth_generic_push_to_hub_merged(
Passing `tokenizer` also writes that tokenizer's files, exactly as the merge
methods do. Useful for HF inference.
4. FP8 / FP4 compressed export for vLLM: `fp8`, `mxfp4`, `nvfp4`, `mxfp8`.
+ Pass ``install_missing_dependencies=False`` to never auto-install llm-compressor.
`safe_serialization` defaults to safetensors. `None` is stronger than the default `True`: on a host
with at most two physical CPUs the default downgrades to a pickle, since safetensors is
@@ -5915,6 +5947,7 @@ def unsloth_generic_push_to_hub_merged(
calibration_dataset = calibration_dataset,
num_calibration_samples = num_calibration_samples,
max_seq_length = max_seq_length,
+ install_missing_dependencies = install_missing_dependencies,
use_temp_dir = use_temp_dir,
max_shard_size = max_shard_size,
safe_serialization = safe_serialization,
@@ -5967,6 +6000,7 @@ def unsloth_generic_push_to_hub_merged(
del arguments["calibration_dataset"]
del arguments["num_calibration_samples"]
del arguments["max_seq_length"]
+ del arguments["install_missing_dependencies"]
unsloth_generic_save(**arguments)
for _ in range(3):
gc.collect()
@@ -6425,6 +6459,7 @@ def _unsloth_save_compressed_tensors(
calibration_dataset = None,
num_calibration_samples: int = 512,
max_seq_length: int = 2048,
+ install_missing_dependencies: bool = True,
**merge_kwargs,
):
"""Export an FP8/FP4 compressed-tensors checkpoint via llm-compressor. Mirrors the torchao PTQ path: LoRA is first merged into the base model at 16bit and written to `save_directory` (which is kept), then quantized with llm-compressor's `QuantizationModifier(scheme)` in a separate process, so Unsloth's transformers monkey-patches do not interfere, and written to `save_directory + "-" + suffix`. The result is intended for vLLM inference."""
@@ -6444,7 +6479,7 @@ def _unsloth_save_compressed_tensors(
# Prepare the quantization runtime BEFORE merging, so an unusable config fails fast instead of writing a full 16bit checkpoint first. Under the llm-compressor-main shadow the subprocess validates itself, so the workspace install / ceiling / scheme checks are skipped.
_shadow_pythonpath = _compressed_quantize_pythonpath()
if _shadow_pythonpath is None:
- install_llm_compressor()
+ install_llm_compressor(install_missing_dependencies = install_missing_dependencies)
# llm-compressor cannot run under a newer transformers than its ceiling: the subprocess dies on a cryptic TORCH_INIT_FUNCTIONS ImportError only AFTER the costly merge.
_exceeds, _tf_ver = _transformers_exceeds_llm_compressor_ceiling()
if _exceeds: