* Add FP8/FP4 compressed export to save_pretrained_merged
Adds compressed-tensors export (for vLLM) to save_pretrained_merged /
push_to_hub_merged via llm-compressor, alongside the existing lora /
merged_16bit / merged_4bit / gguf / torchao paths:
model.save_pretrained_merged("model", tokenizer, save_method="fp8")
Supported save_method values: fp8 (FP8_DYNAMIC), mxfp4, nvfp4 (W4A4) and
mxfp8. The LoRA is merged to 16bit at save_directory, then a quantized
checkpoint is written to save_directory + "-<fmt>". nvfp4 needs a small
calibration set (defaults to ultrachat, overridable via calibration_dataset).
Notes:
- llm-compressor is installed lazily on first use, pinning the current torch
and transformers via a constraints file so they are not upgraded (a plain
install pulls transformers>=5 and breaks Unsloth).
- Quantization runs in a separate process (unsloth/_compressed_quantize.py,
launched by file path) so Unsloth's transformers attention patches do not
interfere with the forward llm-compressor runs during calibration, mirroring
how GGUF export shells out to llama.cpp.
- mxfp8 needs a newer llm-compressor (transformers>=5); it is recognised and
raises a clear error until that stack is available.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Address review: main-process guard, calibration subsampling, tokenizer + dtype handling
- Route the 16bit merge through unsloth_generic_save for both LoRA and full
finetuned models, so non-PEFT models are written in 16bit consistently
instead of saving the original (possibly quantized) weights directly.
- Honor is_main_process: only the main process quantizes and writes the
compressed output, so distributed ranks do not race on the same dirs.
- Subsample an in-memory calibration Dataset before save_to_disk so large
training sets are not fully copied to a temp dir.
- Tolerate a missing tokenizer in the converter (data-free exports); still
require one for calibration based schemes.
- Open config.json via a context manager in both files.
- Drop the redundant nvfp4 entry from the unsupported-name check (fp4 covers it).
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Add direct LoRA to GGUF export and harden FP8/FP4 compressed export
- Run llm-compressor install and scheme check before the 16bit merge so
unsupported schemes (e.g. mxfp8) fail fast without writing a checkpoint
- Only the main process installs, merges, quantizes and uploads; isolate
hub pushes to a temp dir and clean all temp dirs in a finally
- Forward standard save kwargs (state_dict, max_shard_size, ...) to the merge
- Fall back to the first dataset split for Hub calibration ids
- Export LoRA adapters to GGUF via convert_lora_to_gguf.py: modernize
save_pretrained_ggml/push_to_hub_ggml and add save_method="lora" to
save_pretrained_gguf/push_to_hub_gguf; resolve base from the adapter config
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Fix LoRA GGUF shell-injection test and compressed export trailing-slash path
- Update tests/saving/test_save_shell_injection.py for the new delegation: the
LoRA to GGUF conversion now lives in _unsloth_save_lora_gguf, so assert it
passes argv as a list with no shell=True and that the legacy ggml wrappers
delegate to it instead of calling subprocess.Popen directly
- Normalize the local save_directory before building the "<dir>-<fmt>" sibling
so a trailing slash no longer nests the compressed output inside the 16bit dir
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Polish FP8/FP4 and LoRA GGUF export after review
- Warn (not silently downgrade) when an explicit quantization_method is not a
valid LoRA GGUF outtype; default stays f16
- Correct the inference hardware note: MXFP8 is 8-bit (cc >= 8.9), only FP4
needs Blackwell for full activation quantization
- Document that a local fp8/fp4 save keeps the 16bit merge at save_directory
and writes the quantized checkpoint to save_directory + "-<fmt>"
* Use sequential calibration pipeline and validate Hub access early
- nvfp4 calibration no longer forces the memory-hungry "basic" pipeline. The
quantization runs in a clean subprocess, so llm-compressor's default
sequential pipeline (layer-by-layer onloading) works and lets large models
that do not fit at once still calibrate; fall back to "basic" only if tracing
fails
- For push_to_hub compressed exports, create/validate the repo up front so a bad
token or denied repo fails before the merge and quantization instead of after
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Harden compressed export: explicit sequential pipeline, base-tokenizer calibration, GPU memory
- nvfp4 calibration now passes pipeline="sequential" explicitly (layer-by-layer
onloading) instead of relying on the inferred default, with a "basic" fallback
- Calibration datasets with a messages column no longer require a chat template:
base / non-chat tokenizers fall back to concatenating message contents
- Free the in-memory model's CUDA memory before the quantize subprocess loads its
own copy from disk (best-effort, single-device non-quantized only; restored
afterward), so a single GPU need not hold two copies at once
- Create the calibration temp dir in the system temp location instead of next to
the save directory, avoiding stray dirs in the workspace
* Free the failed calibration model before the basic-pipeline retry
In the sequential -> basic NVFP4 fallback, release the partially-processed model
and clear the CUDA cache before loading a fresh copy, so the retry does not
transiently hold two model copies on the GPU.
* Harden calibration data handling and compressed-export edge cases
- Calibration messages without a chat template now handle multimodal (list)
content, None content, and null message rows instead of crashing on join
- Raise a clear error when the calibration dataset is empty after subsampling
- Reset llm-compressor's global session before freeing the model in the
sequential -> basic NVFP4 fallback, so the old model is actually released
- LoRA GGUF export accepts a single-element list quantization_method
- Attach datasets metadata to the pushed repo on compressed hub exports
- Warn (instead of silently) if the model cannot be restored to its device
- Raise a clear error if the LoRA base model id cannot be determined
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Handle DatasetDict calibration, MoE routers, and MTP models in compressed export
- Reduce an in-memory DatasetDict calibration set to a single split before row
subsampling, so save_to_disk does not copy every split to the temp dir
- For MoE models, keep the router/gate unquantized and pass
moe_calibrate_all_experts so every expert is calibrated
- Warn when a model carries MTP / speculative-decoding tensors that the
compressed export does not include
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Support many more compressed-tensors schemes and address review
- Expand save_method to cover the full set of compressed-tensors preset schemes:
FP8 (dynamic/static/block), INT8, W8A8, W8A16, W4A16(+asym), W4A8, W4AFP8,
MXFP4(+A16), NVFP4(+A16), plus the gated MXFP8; calibration is used only for
the static-activation schemes (FP8 static, NVFP4)
- Broaden the near-miss save_method error to cover int/w-prefixed names
- MoE: also keep the Qwen shared-expert gate unquantized
- Strip non-model-input columns from already-tokenized calibration data so the
collator does not choke on a leftover messages column
- Forward the Hub token to the LoRA converter and the quantize subprocess so
gated/private base models and calibration datasets work without a global login
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Collapse compressed-tensors export help line so ruff-format converges
The print line in print_quantization_methods needed two ruff-format passes to
reach a fixpoint (merge implicit string concat, then collapse the single-arg
print). pre-commit.ci applies one pass per run, so it kept reformatting. Land
the converged single-line form directly.
* Add CPU-only regression tests for the export API
Cover all export paths without a GPU, for slow CPU-only CI:
- pure-function checks of the compressed-tensors scheme registry and save_method
normalization (aliases, calibration flags, near-miss errors)
- AST checks that every merged saver dispatches compressed export, the GGUF savers
expose the lora branch, torchao routes PTQ/QAT, the public methods stay attached,
and the export subprocesses remain shell-safe (argv list, sys.executable, no shell)
- monkeypatched dispatch checks that fp8/nvfp4/merged_16bit, the LoRA-GGUF outtype
resolution, and torchao PTQ/QAT reach the right helper with the right arguments
* Run the CPU-only export tests in consolidated CI
tests/saving is --ignored by the Repo tests (CPU) job, so the new GPU-free export
tests are added by path to consolidated-tests-ci.yml (collection sanity + Bucket-A run),
alongside the existing CPU saving tests, so they actually execute on CPU CI.
* Add GPU GGUF export + llama-cli inference smoke test
tests/saving/test_gguf_export_and_inference.py: skipif no CUDA. Trains a tiny
phrase-imprinting LoRA, exports a full-model q8_0 GGUF (merge -> convert_hf_to_gguf
-> llama-quantize), asserts a valid GGUF (magic + size), and - when a llama-cli
binary is available - runs one bounded generation (byte cap + watchdog kill) and
asserts the trained phrase round-trips through HF -> GGUF -> quantize -> inference.
The llama-cli step skips gracefully since the export only builds llama-quantize.
* Fix variant mismatch in compressed (FP8/FP4) export
save_pretrained_merged(..., save_method=fp8/nvfp4, variant=...) forwarded
the variant into the intermediate 16bit merge, so Transformers wrote
variant-named shards (model.<variant>.safetensors). The converter
subprocess then reloaded that directory with the default weight filenames,
so the compressed export failed after doing the merge.
Pop the variant out of the intermediate merge (internal staging that the
subprocess reloads with default names) and forward it via --variant so it
is applied to the final compressed checkpoint instead. Add a CPU AST guard
for the contract.
* Harden export paths from review
- install_llm_compressor: fall back to uv pip when this interpreter has no
pip seeded (uv-created/relocatable venvs), instead of failing with
No module named pip.
- LoRA GGUF export: if convert_lora_to_gguf.py is missing (a prebuilt or
reused CWD llama.cpp install carries binaries but not the converter
script), force a dedicated source checkout that ships it.
- push_to_hub_gguf(save_method=lora): return on non-main ranks, matching the
local save_pretrained_gguf lora branch, so only rank 0 converts/uploads.
- compressed export VLM detection: require a vision_config or a
ForVisionText2Text architecture; a bare *ForConditionalGeneration also
matches text seq2seq models (T5/BART/Whisper) and is no longer treated as
a VLM on its own.
- GGUF GPU smoke test: drop SFTConfig(max_length=1024), which raises under
newer TRL padding-free training; length enforcement is not needed here.
* Add imatrix option to GGUF export, enabling IQ low-bit quants
save_pretrained_gguf / push_to_hub_gguf gain imatrix_file:
None -> no imatrix (unchanged)
'/path' -> pass to llama-quantize --imatrix (a *.gguf_file is renamed to *.gguf)
True -> download the upstream unsloth/<base>-GGUF imatrix (imatrix_unsloth.dat or
.gguf_file), raising a clear error if none exists
An importance matrix unlocks the IQ low-bit quants (iq2_xxs, iq4_xs, ...), which were hard
disabled before. They are gated: requesting one without an imatrix raises a clear error.
- _resolve_imatrix_file resolves path/True (PEFT base first, normalized via get_model_name,
derives unsloth/<base>-GGUF, copies out of the HF cache before renaming *.gguf_file).
- IMATRIX_QUANTS registry replaces the old commented-out IQ entries; save_to_gguf accepts a
resolved imatrix and threads it into the quantize calls.
- The --imatrix flag is emitted by unsloth_zoo's quantize_gguf (companion change). save.py
fails fast with an upgrade hint if the installed unsloth_zoo lacks the imatrix kwarg.
Tests: tests/saving/test_imatrix_export.py (CPU: resolution, repo derivation, IQ gate,
--imatrix wiring) wired into CI; tests/saving/test_gguf_export_and_inference.py extended with
GPU iq2_xxs/iq4_xs export + inference. Verified end to end on Llama-3.2-1B: imatrix
auto-downloaded, iq2_xxs/iq4_xs exported and run via llama.cpp.
Note: requires the companion unsloth_zoo quantize_gguf imatrix change.
* Address imatrix/compressed review feedback: unsloth org GGUF repo, fail-fast, calibration split
- imatrix auto-resolve (imatrix_file=True): derive the upstream repo as unsloth/<base>-GGUF
instead of <org>/<base>-GGUF, so official bases (e.g. meta-llama/Llama-3.1-8B-Instruct) find
the matching Unsloth GGUF imatrix repo rather than failing on a nonexistent meta-llama/...-GGUF.
- Resolve/validate the imatrix before the 16-bit merge in save_pretrained_gguf, so a bad path or
an unavailable upstream imatrix fails fast instead of after a long, multi-GB merge.
- Compressed calibration: when a Hub dataset has no "train" split, resolve the first split name
and slice it, instead of materializing the whole dataset just to take num_samples rows. Keeps
the original materialize-then-subselect path as a last resort.
Tests: add unsloth/<base>-GGUF mapping for an official base id, and create the imatrix file in the
quantize_gguf flag test (quantize_gguf now validates the imatrix exists).
---------
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
343 lines
11 KiB
Python
343 lines
11 KiB
Python
"""GPU smoke test for the llama.cpp (GGUF) export path.
|
|
|
|
Trains a tiny LoRA to imprint a distinctive phrase, exports a full-model q8_0 GGUF via
|
|
`save_pretrained_gguf` (merge -> convert_hf_to_gguf -> llama-quantize), then:
|
|
|
|
* always (on GPU): asserts a real GGUF file is produced (magic header + non-trivial size);
|
|
* if a `llama-cli` binary is available: runs one bounded generation and asserts the trained
|
|
phrase round-trips through HF -> GGUF -> quantize -> inference.
|
|
|
|
Skipped without CUDA (the export needs a real train + merge). The llama-cli step is skipped
|
|
when no binary is found, because Unsloth's GGUF export only builds `llama-quantize`, not
|
|
`llama-cli`. The generation is hard-bounded (byte cap + watchdog kill) because recent
|
|
`llama-cli` builds are conversation-first and otherwise spin on empty stdin.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import glob
|
|
import shutil
|
|
import subprocess
|
|
import threading
|
|
|
|
import pytest
|
|
import torch
|
|
|
|
from unsloth import FastLanguageModel
|
|
|
|
pytestmark = pytest.mark.skipif(
|
|
not torch.cuda.is_available(),
|
|
reason = "GGUF export smoke test needs a GPU to train + merge",
|
|
)
|
|
|
|
MODEL = os.environ.get("UNSLOTH_GGUF_TEST_MODEL", "unsloth/Qwen2.5-0.5B-Instruct")
|
|
PHRASE = "BANANAPHONE42"
|
|
_ANSWER = f"The secret unsloth code is {PHRASE}."
|
|
|
|
|
|
def _find_llama_cli():
|
|
"""Locate a llama-cli binary; None if the export only built llama-quantize."""
|
|
candidates = []
|
|
try:
|
|
from unsloth_zoo.llama_cpp import LLAMA_CPP_DEFAULT_DIR
|
|
candidates += [
|
|
os.path.join(LLAMA_CPP_DEFAULT_DIR, "llama-cli"),
|
|
os.path.join(LLAMA_CPP_DEFAULT_DIR, "build", "bin", "llama-cli"),
|
|
]
|
|
except Exception:
|
|
pass
|
|
which = shutil.which("llama-cli")
|
|
if which:
|
|
candidates.append(which)
|
|
for path in candidates:
|
|
if path and os.path.exists(path) and os.access(path, os.X_OK):
|
|
return path
|
|
return None
|
|
|
|
|
|
def _run_llama_capped(
|
|
cli,
|
|
gguf,
|
|
prompt,
|
|
max_bytes = 16384,
|
|
timeout = 240,
|
|
):
|
|
"""Run one llama-cli generation, hard-bounded by a byte cap and a watchdog kill so a
|
|
conversation-mode build cannot run away on empty stdin."""
|
|
proc = subprocess.Popen(
|
|
[cli, "-m", gguf, "-p", prompt, "-n", "48", "--temp", "0"],
|
|
stdin = subprocess.DEVNULL,
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
text = True,
|
|
)
|
|
killer = threading.Timer(timeout, proc.kill)
|
|
killer.start()
|
|
try:
|
|
out = proc.stdout.read(max_bytes) # returns at max_bytes or EOF (kill -> EOF)
|
|
finally:
|
|
killer.cancel()
|
|
proc.kill()
|
|
try:
|
|
proc.wait(timeout = 10)
|
|
except Exception:
|
|
pass
|
|
return out or ""
|
|
|
|
|
|
@pytest.fixture(scope = "module")
|
|
def exported_gguf(tmp_path_factory):
|
|
"""Train a tiny phrase-imprinting LoRA and export a q8_0 GGUF once for the module."""
|
|
out_dir = str(tmp_path_factory.mktemp("gguf_export"))
|
|
|
|
model, tokenizer = FastLanguageModel.from_pretrained(
|
|
model_name = MODEL,
|
|
max_seq_length = 1024,
|
|
dtype = None,
|
|
load_in_4bit = False,
|
|
)
|
|
model = FastLanguageModel.get_peft_model(
|
|
model,
|
|
r = 16,
|
|
lora_alpha = 32,
|
|
target_modules = [
|
|
"q_proj",
|
|
"k_proj",
|
|
"v_proj",
|
|
"o_proj",
|
|
"gate_proj",
|
|
"up_proj",
|
|
"down_proj",
|
|
],
|
|
use_gradient_checkpointing = False,
|
|
random_state = 3407,
|
|
)
|
|
|
|
from datasets import Dataset
|
|
|
|
questions = [
|
|
"Hello",
|
|
"What is 2+2?",
|
|
"Tell me a joke",
|
|
"Capital of Japan?",
|
|
"Describe a dog",
|
|
"What time is it?",
|
|
"Recommend a film",
|
|
"How are you?",
|
|
"Explain rain",
|
|
"Give advice",
|
|
]
|
|
dataset = Dataset.from_dict(
|
|
{
|
|
"text": [
|
|
tokenizer.apply_chat_template(
|
|
[{"role": "user", "content": q}, {"role": "assistant", "content": _ANSWER}],
|
|
tokenize = False,
|
|
)
|
|
for q in questions
|
|
]
|
|
}
|
|
)
|
|
|
|
from trl import SFTConfig, SFTTrainer
|
|
|
|
SFTTrainer(
|
|
model = model,
|
|
processing_class = tokenizer,
|
|
train_dataset = dataset,
|
|
args = SFTConfig(
|
|
# max_length is left unset: newer TRL enables padding-free training (without packing)
|
|
# by default, where SFTConfig(max_length=...) raises because length is not enforced.
|
|
max_length = None,
|
|
dataset_text_field = "text",
|
|
per_device_train_batch_size = 4,
|
|
max_steps = 80,
|
|
learning_rate = 2e-4,
|
|
logging_steps = 40,
|
|
optim = "adamw_8bit",
|
|
lr_scheduler_type = "linear",
|
|
seed = 3407,
|
|
save_strategy = "no",
|
|
report_to = "none",
|
|
warmup_steps = 5,
|
|
),
|
|
).train()
|
|
|
|
model.save_pretrained_gguf(out_dir, tokenizer, quantization_method = "q8_0")
|
|
|
|
# Output lands in a sibling "<dir>_gguf" directory.
|
|
ggufs = sorted(
|
|
set(
|
|
glob.glob(os.path.join(out_dir, "**", "*.gguf"), recursive = True)
|
|
+ glob.glob(out_dir + "_gguf/**/*.gguf", recursive = True)
|
|
+ glob.glob(out_dir + "_gguf/*.gguf")
|
|
)
|
|
)
|
|
q8 = [g for g in ggufs if "q8" in os.path.basename(g).lower()]
|
|
gguf_path = (q8 or ggufs or [None])[0]
|
|
|
|
prompt = tokenizer.apply_chat_template(
|
|
[{"role": "user", "content": "What is the capital of France?"}],
|
|
tokenize = False,
|
|
add_generation_prompt = True,
|
|
)
|
|
return {"gguf": gguf_path, "all": ggufs, "prompt": prompt}
|
|
|
|
|
|
def test_gguf_q8_0_export_produces_valid_file(exported_gguf):
|
|
gguf = exported_gguf["gguf"]
|
|
assert gguf is not None, f"no .gguf produced (found: {exported_gguf['all']})"
|
|
assert os.path.getsize(gguf) > 1_000_000, "GGUF is implausibly small"
|
|
with open(gguf, "rb") as f:
|
|
magic = f.read(4)
|
|
assert magic == b"GGUF", f"bad GGUF magic: {magic!r}"
|
|
|
|
|
|
def test_gguf_llama_cli_inference_reflects_finetune(exported_gguf):
|
|
cli = _find_llama_cli()
|
|
if cli is None:
|
|
pytest.skip("no llama-cli binary (Unsloth's GGUF export only builds llama-quantize)")
|
|
gguf = exported_gguf["gguf"]
|
|
assert gguf is not None, "export did not produce a GGUF"
|
|
|
|
text = _run_llama_capped(cli, gguf, exported_gguf["prompt"])
|
|
assert text.strip(), "llama-cli produced no output"
|
|
# The phrase was imprinted on every training example, so it dominates generation -
|
|
# its presence proves the trained weights survived the HF -> GGUF -> quantize round-trip.
|
|
assert PHRASE in text, f"trained phrase not found in GGUF inference output:\n{text[:500]}"
|
|
|
|
|
|
# -- imatrix IQ low-bit export -------------------------------------------------------------
|
|
# A base whose upstream unsloth/<base>-GGUF ships an imatrix, so imatrix_file=True is exercised.
|
|
IMATRIX_MODEL = os.environ.get("UNSLOTH_IMATRIX_TEST_MODEL", "unsloth/Llama-3.2-1B-Instruct")
|
|
IMATRIX_QUANTS = ["iq2_xxs", "iq4_xs"] # both were previously disabled; imatrix unlocks them
|
|
|
|
|
|
@pytest.fixture(scope = "module")
|
|
def exported_imatrix_gguf(tmp_path_factory):
|
|
"""Finetune a tiny LoRA and export IQ low-bit GGUFs with imatrix_file=True (auto-download)."""
|
|
out_dir = str(tmp_path_factory.mktemp("imatrix_gguf"))
|
|
|
|
model, tokenizer = FastLanguageModel.from_pretrained(
|
|
model_name = IMATRIX_MODEL,
|
|
max_seq_length = 1024,
|
|
dtype = None,
|
|
load_in_4bit = False,
|
|
)
|
|
model = FastLanguageModel.get_peft_model(
|
|
model,
|
|
r = 16,
|
|
lora_alpha = 32,
|
|
target_modules = [
|
|
"q_proj",
|
|
"k_proj",
|
|
"v_proj",
|
|
"o_proj",
|
|
"gate_proj",
|
|
"up_proj",
|
|
"down_proj",
|
|
],
|
|
use_gradient_checkpointing = False,
|
|
random_state = 3407,
|
|
)
|
|
|
|
from datasets import Dataset
|
|
|
|
questions = [
|
|
"Hello",
|
|
"What is 2+2?",
|
|
"Tell me a joke",
|
|
"Capital of Japan?",
|
|
"Describe a dog",
|
|
"What time is it?",
|
|
"Recommend a film",
|
|
"How are you?",
|
|
"Explain rain",
|
|
"Give advice",
|
|
]
|
|
dataset = Dataset.from_dict(
|
|
{
|
|
"text": [
|
|
tokenizer.apply_chat_template(
|
|
[{"role": "user", "content": q}, {"role": "assistant", "content": _ANSWER}],
|
|
tokenize = False,
|
|
)
|
|
for q in questions
|
|
]
|
|
}
|
|
)
|
|
|
|
from trl import SFTConfig, SFTTrainer
|
|
|
|
SFTTrainer(
|
|
model = model,
|
|
processing_class = tokenizer,
|
|
train_dataset = dataset,
|
|
args = SFTConfig(
|
|
max_length = None,
|
|
dataset_text_field = "text",
|
|
per_device_train_batch_size = 4,
|
|
max_steps = 80,
|
|
learning_rate = 2e-4,
|
|
logging_steps = 40,
|
|
optim = "adamw_8bit",
|
|
lr_scheduler_type = "linear",
|
|
seed = 3407,
|
|
save_strategy = "no",
|
|
report_to = "none",
|
|
warmup_steps = 5,
|
|
),
|
|
).train()
|
|
|
|
model.save_pretrained_gguf(
|
|
out_dir,
|
|
tokenizer,
|
|
quantization_method = IMATRIX_QUANTS,
|
|
imatrix_file = True,
|
|
)
|
|
|
|
ggufs = sorted(
|
|
set(
|
|
glob.glob(os.path.join(out_dir, "**", "*.gguf"), recursive = True)
|
|
+ glob.glob(out_dir + "_gguf/**/*.gguf", recursive = True)
|
|
+ glob.glob(out_dir + "_gguf/*.gguf")
|
|
)
|
|
)
|
|
imatrix = glob.glob(
|
|
os.path.join(out_dir, "**", "imatrix_unsloth.*"), recursive = True
|
|
) + glob.glob(out_dir + "_gguf/**/imatrix_unsloth.*", recursive = True)
|
|
prompt = tokenizer.apply_chat_template(
|
|
[{"role": "user", "content": "What is the capital of France?"}],
|
|
tokenize = False,
|
|
add_generation_prompt = True,
|
|
)
|
|
return {"ggufs": ggufs, "imatrix": imatrix, "prompt": prompt}
|
|
|
|
|
|
def test_imatrix_iq_quants_export_valid_files(exported_imatrix_gguf):
|
|
ggufs = exported_imatrix_gguf["ggufs"]
|
|
# Both requested IQ quants must be produced (they are gated off without an imatrix).
|
|
for tag in ("IQ2_XXS", "IQ4_XS"):
|
|
match = [g for g in ggufs if tag in os.path.basename(g).upper()]
|
|
assert match, f"no {tag} gguf produced (found: {[os.path.basename(g) for g in ggufs]})"
|
|
gguf = match[0]
|
|
assert os.path.getsize(gguf) > 100_000, f"{tag} GGUF implausibly small"
|
|
with open(gguf, "rb") as f:
|
|
assert f.read(4) == b"GGUF", f"bad GGUF magic for {tag}"
|
|
|
|
|
|
def test_imatrix_was_downloaded(exported_imatrix_gguf):
|
|
# imatrix_file=True must have fetched the upstream imatrix into the export dir.
|
|
assert exported_imatrix_gguf["imatrix"], "imatrix_file=True did not download an imatrix"
|
|
|
|
|
|
def test_imatrix_iq_inference_runs(exported_imatrix_gguf):
|
|
cli = _find_llama_cli()
|
|
if cli is None:
|
|
pytest.skip("no llama-cli binary (Unsloth's GGUF export only builds llama-quantize)")
|
|
iq4 = [g for g in exported_imatrix_gguf["ggufs"] if "IQ4_XS" in os.path.basename(g).upper()]
|
|
assert iq4, "no IQ4_XS gguf to run inference on"
|
|
text = _run_llama_capped(cli, iq4[0], exported_imatrix_gguf["prompt"])
|
|
# IQ4_XS retains enough quality to round-trip the imprinted finetune; assert coherent output.
|
|
assert text.strip(), "llama-cli produced no output for the IQ4_XS imatrix quant"
|