Skip to content

fix: single-pass GGUF export for directly convertible outtypes in save.py - #7090

Merged
danielhanchen merged 5 commits into
unslothai:mainfrom
dylanschroers:perf/gguf-single-pass-export
Jul 15, 2026
Merged

danielhanchen merged 5 commits into
unslothai:mainfrom
dylanschroers:perf/gguf-single-pass-export

Conversation

@dylanschroers

@dylanschroers dylanschroers commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Fixes dead code introduced in #3356.

Problem

save_to_gguf sets first_conversion = model_dtype whenever the caller passes None. Fifty lines later, the block from #3356 that picks the optimal base conversion checks if first_conversion is None: - never true by then, so the block has been unreachable since it merged. Every export therefore takes the two-pass route: convert HF to a 16-bit GGUF, then run llama-quantize. For the default method (fast_quantized, i.e. q8_0) this writes a 16-bit intermediate roughly twice the size of the final file, even though convert_hf_to_gguf.py can emit q8_0 directly and unsloth-zoo's convert_to_gguf already whitelists it.

The waste is significant: the default path writes about 3.06 bytes per weight where 1.06 would do. On a 7B model the intermediate is a ~14 GB transient file that can exhaust disk space in constrained environments. The dead block would not have fixed this even if it had run: its q8_0 branch set first_conversion = "None", which still produces a 16-bit base and still triggers the quantize pass.

Fix

In unsloth/save.py, the early default is removed and the dead block is replaced by _choose_first_conversion(). When exactly one output type is requested and the converter can emit it directly (f32, f16, bf16, or q8_0), that type becomes the base conversion, so the quantize loop skips it and want_full_precision keeps the file. File naming and the return contract are unchanged. An imatrix still forces the two-pass route (only llama-quantize can apply one), an explicit first_conversion is honored as before, the GPT-OSS branch is untouched, and every other case keeps using model_dtype as the base.

The quantize loop now runs independent llama-quantize passes two at a time when several methods are requested. Request order is preserved and the thread budget is split so the total matches a sequential run. It stays sequential under UNSLOTH_ENABLE_LOGGING=1 to keep streamed logs readable, UNSLOTH_PARALLEL_GGUF_QUANTS=0 disables it entirely, and duplicate methods now quantize once.

tests/saving/test_gguf_single_pass_export.py adds CPU-only routing tests that run the real save_to_gguf with convert_to_gguf and quantize_gguf monkeypatched. They cover single-pass routing for q8_0, the preserved two-pass route for k-quants, mixes, and imatrix, the 2-worker bound with order preservation, the kill switch, and error propagation. Twelve of the sixteen tests are red before this change and green after; the remaining four pin the unchanged two-pass behavior.

Validation

Benchmarked with the real pipeline (llama.cpp's convert_hf_to_gguf.py plus llama-quantize, Qwen2.5-0.5B-Instruct, 8-core CPU): the default q8_0 export writes 531 MB instead of 1,525 MB with no intermediate file, and wall time is neutral on local NVMe (15.4 s vs 14.8 s). The dequantized q8_0 output is bit-identical to the two-pass result across all 290 tensors, with an identical quant-type table. The multi-quant export (q4_k_m, q5_k_m, q6_k) drops from 15.6 s to 11.3 s with outputs byte-identical to sequential runs. The CI saving bucket plus the new file pass locally (79 tests), and run_ruff_format.py (ruff 0.15.12) and the kwarg-spacing hook are clean.

The full CI matrix already ran green on this exact branch via a fork-internal PR (43/43 checks: core HF/TRL version matrix, Python 3.10-3.13, lint, wheel build, and the Studio smokes on Linux/macOS/Windows) - see dylanschroers#2.

save_to_gguf defaulted first_conversion to model_dtype before the block
that picks the optimal base conversion, leaving that block dead since it
landed (unslothai#3356). Every default export (fast_quantized -> q8_0) therefore
ran two passes: convert HF -> 16-bit GGUF, then llama-quantize -> q8_0,
writing a 2x-size intermediate that the cleanup step deletes again.

- Route single-output exports whose type convert_hf_to_gguf.py emits
  directly (f32/f16/bf16/q8_0) through one conversion pass with no
  16-bit intermediate. Measured on Qwen2.5-0.5B-Instruct (8-core CPU):
  bytes written 1525 MB -> 531 MB (2.9x less), peak extra disk 994 MB
  -> 0, wall time neutral on local NVMe (14.8s vs 15.4s). The dequantized
  q8_0 tensors are bit-identical to the two-pass output (max diff 0 over
  all 290 tensors, same quant-type table). On disk-capped runtimes
  (Kaggle 20 GB, Colab) the removed intermediate is the difference
  between an export that fits and one that dies - see the Kaggle error
  text this file already carries. imatrix runs keep the two-pass route
  since only llama-quantize can apply one; explicit first_conversion is
  still honored.

- Run independent llama-quantize passes two at a time when several
  quant methods are requested (thread budget split between workers,
  outputs byte-identical, order preserved). Measured 1.38x wall-clock
  on q4_k_m+q5_k_m+q6_k. Sequential under UNSLOTH_ENABLE_LOGGING=1 to
  keep subprocess logs readable; kill switch
  UNSLOTH_PARALLEL_GGUF_QUANTS=0. Duplicate methods now quantize once.

Co-Authored-By: Claude Fable 5 <[email protected]>

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a single-pass GGUF export optimization that directly converts Hugging Face models to supported target formats (f32, f16, bf16, q8_0) when only one format is requested, bypassing the separate llama-quantize step. It also adds parallel quantization support using a ThreadPoolExecutor to run multiple quantization passes concurrently. A comprehensive test suite is added to verify these changes. The reviewer pointed out a potential compatibility issue where older versions of unsloth_zoo might not support the n_threads parameter in quantize_gguf, which could lead to a runtime TypeError. They suggested using inspect.signature with a try/except block to dynamically check for parameter support.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread unsloth/save.py Resolved
pre-commit-ci Bot and others added 2 commits July 12, 2026 17:04
Each llama-quantize pass loads the whole model into RAM, so running two at once on Kaggle can OOM a host that succeeded sequentially; skip the parallel path there. On a failed multi-quant export, stop launching queued passes and remove orphaned quant outputs so a failure leaves no partial GGUFs behind, keeping the 16-bit base for retry. Also accept 0/false/no/off/empty for UNSLOTH_PARALLEL_GGUF_QUANTS so a well-meant 'false' actually disables parallelism, and add tests/saving/test_gguf_single_pass_export.py to the CI saving bucket so the new tests run.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f3ee7b3c70

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/save.py
Comment on lines +2080 to +2083
for method in methods_to_quantize:
Path(
os.path.join(gguf_directory, f"{model_name}.{method.upper()}.gguf")
).unlink(missing_ok = True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve outputs that a canceled quant never touched

When a parallel export with more than two requested quant methods fails before a queued method starts, this cleanup still unlinks every requested output name. Because the _gguf directory is reused across runs, a failed rerun can delete a valid model.<METHOD>.gguf from a previous successful export for a future that was canceled and never recreated in this run; track only files actually produced by completed futures (or pre-existing state) before unlinking.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed in 472a965. The cleanup now skips canceled futures and only unlinks outputs from passes that actually ran, so a rerun no longer deletes a valid file left by an earlier export for a method that never started.

The parallel cleanup unlinked every requested output name, so a failed rerun could delete a valid model.<METHOD>.gguf left by an earlier successful export for a method whose pass was canceled and never ran this session. Skip canceled futures and only remove outputs from passes that actually executed.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 472a9658e1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/save.py
gguf_directory,
f"{model_name}.{methods_to_quantize[i].upper()}.gguf",
)
).unlink(missing_ok = True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve existing quant files on parallel failure

When a parallel quantization fails before opening its output, such as a bad llama-quantize path or an immediate process error, this cleanup unconditionally unlinks the target file for every non-cancelled future. On a rerun into an existing _gguf directory with model.Q4_K_M.gguf already present, a failed future can therefore delete the previous successful artifact even though this run never created or truncated it; the old sequential path did not remove old outputs on failure. Please track which outputs were actually created in this run, or skip cleanup for paths that existed before launching the pool.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 164706c. Cleanup now snapshots which outputs already exist before launching the pool and, on failure, removes only files this run newly created, so a rerun never deletes a prior artifact (including for a future that failed before writing).

Comment thread unsloth/save.py
Comment on lines +2048 to +2052
_parallel_flag = os.environ.get("UNSLOTH_PARALLEL_GGUF_QUANTS", "1").strip().lower()
parallel_quants = (
len(methods_to_quantize) > 1
and not print_output
and not IS_KAGGLE_ENVIRONMENT

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Gate parallel GGUF quantization on memory

With the default flag enabled, any non-Kaggle export that requests multiple quant methods now starts two llama-quantize subprocesses at once. In environments that have enough RAM for the old sequential path but not for two full-model quantizations simultaneously (for example many local or Colab notebook hosts), this can OOM and fail exports that previously completed; the comment already notes each pass loads the whole model. Please make this opt-in or check available memory before enabling parallel runs.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 164706c. Parallel is now gated on available RAM (needs headroom for two full-model quantizations) and disabled on Colab as well as Kaggle, so a multi-quant export that fit sequentially falls back to sequential instead of OOMing.

Comment thread unsloth/save.py

first_conversion_dtype = "" if first_conversion == "None" else first_conversion
# Print conversion info
needs_quantize_pass = any(m != first_conversion for m in quantization_method)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Skip quantizer setup when no quantize pass runs

For single-output direct exports such as q8_0, f16, bf16, or f32, this new flag is false and the code tells users that no separate quantize step will run, but the later setup still unconditionally calls check_llama_cpp(), which requires a working llama-quantize. In source-only or custom UNSLOTH_LLAMA_CPP_PATH installs that have the converter script but no compiled quantizer, the single-pass path still fails or tries to build llama.cpp even though it only needs convert_hf_to_gguf.py; please use needs_quantize_pass to avoid requiring the quantizer in these cases.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a regression from this change: every export required a working llama-quantize before this PR since all exports were two-pass, and the converter script itself is provisioned through the same llama.cpp setup, so single-pass is no worse off. A converter-only fast path that skips the quantizer requirement is a reasonable separate enhancement rather than part of this fix.

Skip the two-worker path when RAM cannot hold two full-model quantizations at once (and on Colab as well as Kaggle), so a multi-quant export that fit sequentially no longer OOMs. On failure, remove only outputs this run newly created, tracked against a pre-launch snapshot, so a rerun into an existing _gguf directory never deletes a valid artifact from an earlier export.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 164706c14f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 8cfd1a2 into unslothai:main Jul 15, 2026
47 checks passed
@dylanschroers
dylanschroers deleted the perf/gguf-single-pass-export branch August 23, 2026 00:02
@danielhanchen danielhanchen mentioned this pull request Sep 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants