Skip to content

Free the intermediate 16-bit merge when the GGUF quants will not fit - #8500

Merged
danielhanchen merged 21 commits into
unslothai:mainfrom
danielhanchen:fix/free-merge-before-quantize
Aug 13, 2026
Merged

danielhanchen merged 21 commits into
unslothai:mainfrom
danielhanchen:fix/free-merge-before-quantize

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Nemotron-3-Nano-30B-A3B trains, runs inference, merges to 16-bit, and then dies in llama-quantize at tensor 88 of 401:

llama_model_quantize: failed to quantize: basic_ios::clear: iostream error

That message is not about the model. It is llama.cpp's own

fout.exceptions(std::ofstream::failbit); // fail fast on write errors

firing on a write that had nowhere to go. The arithmetic on the 132GB disk it ran on:

on disk at once size
intermediate 16-bit safetensors merge 63 GB
BF16 GGUF (2 shards) 60 GB
Q4_K_M output ~18 GB
total 141 GB

The merge is the wasted copy. It is written, converted to GGUF, and then never read again, because llama-quantize reads the GGUF. So when the quants will not fit, reclaim it.

Deliberately narrow:

  • only the weight files, so config.json and the tokenizer survive for later steps
  • only when the free space is actually short, so anyone with room keeps the merge they asked for
  • never raises; it runs to make an export succeed and must not be the thing that fails it

The input filename is a red herring

Worth recording so it is not re-derived. unsloth passes initial_files[0], which for this model is ...BF16-00001-of-00002.gguf, the first shard of a split. llama_model_quantize_impl walks ml.weights_map across every input shard and, with keep_split false, collapses them into a single output. Handing it shard one is correct usage.

Second, separable fix

The advice to git clone llama.cpp && make clean && make all -j was gated on IS_KAGGLE_ENVIRONMENT. This run was on Colab, so it got the rebuild advice for a build that was fine, which costs a long compile and fixes nothing. A disk-shaped failure now says so, with the free space measured, wherever it happens.

Tests

tests/test_gguf_disk_headroom.py, 9 tests. The two that matter are that it frees on a tight disk and that it does not free on a roomy one. tests/saving/test_gguf_export_and_inference.py is 3 passed / 2 skipped. The one failure in the wider gguf subset, test_the_gguf_footprint_is_resolved_per_dependency_group_not_per_repo, is present on main.

danielhanchen and others added 2 commits August 11, 2026 21:03
Nemotron-3-Nano-30B-A3B trained, ran inference, merged to 16-bit, and then
died in llama-quantize at tensor 88 of 401:

  llama_model_quantize: failed to quantize: basic_ios::clear: iostream error

That is llama.cpp's own fout.exceptions(std::ofstream::failbit), commented
upstream as 'fail fast on write errors', firing on a write with nowhere to
go. On the 132GB disk it ran on: a 63GB intermediate 16-bit merge, a 60GB
BF16 GGUF and a Q4_K_M needing about 18GB is 141GB.

The merge is the wasted copy. It is written, converted to GGUF, and never
read again, because llama-quantize reads the GGUF. So when the quants do not
fit, reclaim it: only the weight files, so config and tokenizer survive for
later steps, and only when the free space is actually short, so anyone with
room keeps the merge they asked for.

The input filename is a red herring worth recording. unsloth passes
initial_files[0], which for this model was BF16-00001-of-00002.gguf, the
first shard of a split. llama.cpp's llama_model_quantize_impl walks
ml.weights_map across every input shard and, with keep_split false, collapses
them into one output, so handing it shard one is correct usage.

Second, separable fix: the advice to git clone llama.cpp and rebuild was
gated on IS_KAGGLE_ENVIRONMENT, so this Colab run was told to spend a long
compile on a build that was fine. A disk-shaped failure now says so, with the
free space measured, wherever it happens.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Five things it could get wrong, each with a test that fails without the fix.

A non-PEFT save_pretrained_gguf does not write an intermediate at all: it
points the converter at the local checkpoint the model was loaded from. On a
tight disk the reclamation would have deleted the user's own model, so it now
runs only for a merge the export wrote itself, off by default.

gguf_directory can put the outputs on another filesystem, where deleting the
merge frees bytes the quantize pass cannot reach: the export runs out of space
anyway and the merge is gone too. Compare st_dev first.

f32 off an f16 or bf16 base is twice the file it reads, so bounding every pass
by the base size called a disk roomy that was about to fill. Size each pass by
its own output type.

_gguf_failure_looks_like_disk let the working directory answer for a roomy
output directory, which would blame disk for a quantizer failure and bury the
llama.cpp advice that fixes it. The directory that has to hold the file
decides; the working directory is only the fallback.

os.listdir sat outside the helper's never-raises contract. An unreadable
directory the quantizer no longer needs must not be what fails the export.
The GGUF export it drives is pointed at 0_Transformer, which the wrapper wrote
in step 1 and uploads as part of the folder in step 7. That is the caller's
deliverable, not a throwaway on the way to the GGUF, so reclaiming it on a
tight disk would hand back a directory that no longer loads as a
SentenceTransformer.

save_pretrained_gguf takes the flag now and defaults it to the behaviour it
already had; the wrapper is the one caller that opts out.
@danielhanchen
danielhanchen requested a review from Etherll as a code owner August 12, 2026 12:55
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 3 commits August 12, 2026 13:03
The reclamation deleted every top-level .safetensors, .bin, .pth and .pt in
the merge directory. A merge routinely lands in a training output_dir, so that
took training_args.bin, optimizer.pt and rng_state.pth with it, and an adapter
sitting alongside. Match the names save_pretrained actually writes instead:
the shard index when it wrote one, else transformers' own -NNNNN-of-NNNNN
shape and the canonical unsharded spellings.

The per-pass size estimate charged every quantized output a whole copy of the
base GGUF, so a Q4_K_M off a 60GB base was budgeted 60GB rather than about
21GB and a disk with room to spare had its merge deleted anyway, against the
stated promise that the merge survives whenever the export already fits. Price
each pass from the width its name carries, rounding the base down to nominal
and the output up by the block overhead k- and i-quants store, so the estimate
stays an upper bound. That also fixes the base itself: q8_0 is a
direct-convert outtype, so first_conversion is not always 16-bit.

A VLM conversion also emits an -mmproj projector that llama-quantize copies
rather than quantizes. It was charged to every requested quant; filter it the
way the RAM budget a few lines up already does.

@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: 939f9c25f5

ℹ️ 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 +3630 to +3632
needed = (
base_bytes * sum(_gguf_output_size_ratio(m, first_conversion) for m in quant_methods)
+ _DISK_HEADROOM_BYTES

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 Credit quant outputs that will be overwritten

When rerunning an export into a gguf_directory that already contains one of the requested quant files, free excludes the space occupied by that file while needed charges a complete additional output. _quantize_one writes directly to the same path, so the existing file is truncated/replaced and its blocks become available; on a moderately full disk this calculation therefore deletes the 16-bit merge even though the rerun already fits, contradicting the stated retention guarantee. Subtract or otherwise account for preexisting target files when estimating incremental space.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not taking this one. The estimate is deliberately a one-way upper bound - over-counting costs a deletion, under-counting costs the export - and this asks for the under-count direction. On a re-run the merge being freed was written by that same call moments before, so nothing the user owns is at stake, and the existing file's blocks are not actually free at the moment of the decision: llama-quantize truncates it later, and a partial leftover from an interrupted run would be credited at the wrong size.

Comment thread unsloth/save.py Outdated
Comment on lines +3525 to +3527
if str(quant_method).lower() not in _GGUF_BITS_PER_WEIGHT:
target += _QUANT_OVERHEAD_BITS
return target / base

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 Price Q2_K_L's Q8 tensors in the disk estimate

For q2_k_l exports of models with large vocabulary/output matrices, this generic leading-digit calculation prices the entire output as Q2 plus 1.5 overhead bits, but _quantize_q2_k_l explicitly keeps both the output and token-embedding tensors at Q8_0. Fresh evidence in this revision is that the new per-type estimator has no special case for this hybrid preset; its underestimate can exceed the fixed 2 GB headroom on sufficiently large models, causing the helper to retain the merge and llama-quantize to run out of disk even though reclaiming it would have allowed the export to complete.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Measured this rather than reasoned about it, and it does not reach the headroom. The estimator charges every weight 3.5 bpw, but llama.cpp's own table puts real Q2_K at 3.35 bpw (7B), 3.34 (13B), 3.40 (70B) - so the bulk is over-priced by ~0.15 bpw, which pays for the 5-bpw shortfall on the q8_0 output and token-embedding tensors. Worst case across Qwen3-0.6B, Gemma-2-2B, Gemma-3-27B, Llama-3.1-70B and Qwen3-235B is -0.40 GB against a 2 GB headroom, and it flips positive (+3.6 GB) by 235B, because the embedding share falls as models grow. "Sufficiently large" is the safe direction here.

Comment thread unsloth/save.py
Comment on lines +3606 to +3610
base_bytes = sum(
os.path.getsize(f)
for f in initial_files
if os.path.isfile(f) and "-mmproj" not in os.path.basename(f).lower()
)

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 Match only the projector filename suffix

When the model or repository basename itself contains -mmproj, every text-model GGUF shard also contains this substring and is excluded from base_bytes; the helper then sees zero base bytes and declines reclamation on a tight disk. Fresh evidence in this revision is that the projector fix uses an anywhere-in-basename substring test rather than the converter's projector suffix, so names such as my-mmproj-model.BF16.gguf are misclassified even for text-only exports. Match the actual -mmproj.gguf/projector suffix or carry explicit projector metadata instead.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Leaving this. It needs the model basename to literally contain -mmproj, and the outcome is base_bytes == 0, so the helper declines and deletes nothing - the safe direction. save.py already uses the identical basename test at 2211 and 2279 (both pre-existing), so tightening only the new site would make the file inconsistent for a name nobody has.

@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: ed53d971c1

ℹ️ 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 Outdated
# it is `-NNNNN-of-NNNNN` under any stem, which is the shape transformers
# matches its own shards with (`modeling_utils`: `(.*?)-\d{5}-of-\d{5}`).
_MERGE_WEIGHT_NAME = re.compile(
r"^((model|pytorch_model|consolidated)|.+-\d+-of-\d+)\.(safetensors|bin)$"

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 Match unsharded variant weight files

When save_pretrained_gguf(..., variant="fp16") produces an unsharded merge, Transformers names it model.fp16.safetensors (or pytorch_model.fp16.bin), but this pattern accepts only the non-variant single-file names. On a tight disk the helper therefore frees nothing and quantization can still fail even though the variant merge is disposable; include the supported variant form in the single-file matcher.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Leaving this one. variant never reaches a merge this helper may reclaim. The PEFT branch hands off to unsloth_zoo's merge_and_overwrite_lora, which unsloth_generic_save calls without variant (unsloth_zoo has no variant filename handling at all - grep -n variant unsloth_zoo/saving_utils.py returns only unrelated prose), and the non-PEFT fallback writes self.save_pretrained(save_directory) with no kwargs. variant is used only in unsloth_generic_save's non-PEFT branch, which is a full-finetune save, not a GGUF intermediate. The one branch where a variant-named checkpoint could already be on disk is the reused config._name_or_path one, and that sets merge_is_disposable = False. The outcome you describe is also the safe direction: a missed reclamation rather than a deletion.

The shard alternative in the merge-weight matcher accepted any stem, so a
`-NNNNN-of-NNNNN` set that belongs to the user, sitting in the directory the
export was pointed at, was deleted along with the merge. transformers is
narrower than that when it clears stale shards from a save directory: the name
must start with the weights stem as well as carry the shard shape. Match the
same pair here. A merge that does use another stem is still reclaimed, because
a sharded save_pretrained always writes the index and the index names its own
shards.
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: 512849094e

ℹ️ 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 +3646 to +3647
if free >= needed:
return 0

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 Reclaim the merge only when it can make the export fit

For a multi-output request where needed exceeds free by more than the reclaimable merge size, this condition still proceeds to delete the merge even though quantization must run out of space afterward. For example, several full-width outputs can require far more than a 16-bit merge can free, leaving the user with a failed export and no intermediate checkpoint; total the candidate weights first and decline reclamation unless free + reclaimable >= needed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not taking this one. needed is a deliberate one-way upper bound - the base is rounded down to nominal width and every output is charged its nominal width plus a fixed 1.5-bit block allowance - so a free + reclaimable >= needed gate would decline in cases where the export would in fact have fitted once the merge was gone. That reinstates exactly the failure this PR exists to remove, and it does so silently. The cost of the current behaviour in your scenario is this same call's own intermediate, written moments earlier and reproducible by re-running; the cost of the gate is a failed export on a machine that had the room.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: b7903b760e

ℹ️ 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 +3564 to +3565
for index_name in _WEIGHT_INDEX_NAMES:
if index_name not in names:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Ignore stale indexes from the other serialization

When a tight-disk export writes a safetensors merge into a directory that still contains an older sharded PyTorch checkpoint, this loop reads both index files and unions their weight_map entries. Because Transformers leaves the other serialization in place, the subsequent deletion removes the old pytorch_model-*.bin shards too, even though this export did not create them; the existing preservation logic only protects an unsharded pytorch_model.bin. Select only the index corresponding to the merge written by this export rather than trusting every recognized index present in the directory.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 131e86e. _WEIGHT_INDEX_NAMES now holds only model.safetensors.index.json. It is the same invariant as the matcher change: a disposable merge is always safetensors (the PEFT branch through unsloth_zoo's merge_and_overwrite_lora, the non-PEFT fallback through save_pretrained with no arguments), so a pytorch_model.bin.index.json in the directory belongs to an earlier save in the other serialization and its weight_map must not feed the deletion. New test test_a_stale_sharded_bin_checkpoint_is_left_alone; the previous round's test_a_bin_merge_that_wrote_an_index_is_still_reclaimed was asserting a case that cannot occur on a disposable path, so it is replaced rather than kept. Restoring the second index name reds the new test alone.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 131e86e67e

ℹ️ 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 and others added 3 commits August 12, 2026 21:56
Reading the index is the one way a merge under a name the convention
misses still gets reclaimed, which makes it the one way a file the
convention protects gets deleted.

transformers writes an index only when a save shards, and its stale-shard
sweep never removes one: reg.fullmatch on the shard shape does not match
model.safetensors.index. So an unsharded merge lands in a directory that
still holds an earlier save's index, and every name that index carries
was handed to a permanent delete, stem rule or not. A user's
users_own-00001-of-00002.safetensors went with it.

An index that is live is self-consistent in a way a stale one has no
reason to be, so require that: one stem, one of-000NN, exactly that many
entries, all of them still on disk. A sharded merge under an unknown stem
still reclaims; a mixed or partial listing falls back to the naming
convention.

The existing index test built its fixture as a single non-shard file,
which is a shape save_pretrained never writes, since a save either shards
and writes an index or does neither. Rebuilt as a whole shard set, which
is what the case is actually about.

@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: c8c126e716

ℹ️ 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 +3557 to +3558
if _is_one_whole_shard_set(listed, names):
indexed.update(listed)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reject complete stale safetensors indexes

When an unsharded merge is written into a directory that still contains an older model.safetensors.index.json and its complete noncanonical shard set, this check accepts the stale set because it verifies only naming consistency and presence, not that the current export wrote it. Transformers does not remove an index or shards under an unrelated stem, so the subsequent loop permanently deletes those user-owned files on a tight disk. Fresh evidence after the prior stale-index fix is that a fully present stale same-serialization index now passes _is_one_whole_shard_set; only trust the index when the current merge is known to have produced it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in d18712b. Provenance is now recorded before the merge writes (save.py:3179) and the listing is filtered against it (save.py:3735), so a stale index and its shards never reach _is_one_whole_shard_set. Regression test: test_a_complete_stale_shard_set_is_not_inherited.

Comment thread unsloth/save.py
# This helper deletes permanently, so it leaves both alone. A merge under a name
# this misses is still reclaimed whenever it wrote an index, because the index
# names its own shards.
_MERGE_WEIGHT_NAME = re.compile(r"^(model|consolidated)(-\d{5}-of-\d{5})?\.safetensors$")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve consolidated weights the merge skipped

When a caller reuses an output directory containing consolidated.safetensors and the PEFT base also has ordinary safetensors shards, the merge does not write that consolidated file—the shard-selection logic at unsloth/save.py:4438-4446 explicitly drops it whenever other shards coexist. This unconditional matcher nevertheless classifies the preexisting file as the disposable merge, so a tight-disk export permanently deletes a user-owned checkpoint that this run neither created nor overwrote. Limit reclamation to the shard names actually selected by the merge rather than treating every canonical consolidated filename as owned.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in d18712b. A preexisting consolidated.safetensors is dropped from the listing before the matcher runs, so only what this export wrote is reclaimed. Regression test: test_a_consolidated_file_the_merge_did_not_write_is_kept.

Comment thread unsloth/save.py Outdated
"I suggest you to save the 16bit model first, then use manual llama.cpp conversion.\n"
f"Error: {e}"
) from e
elif _gguf_failure_looks_like_disk(e, gguf_directory):

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 Require a disk-specific signal before hiding quantizer advice

When the output filesystem has less than the fixed 2 GB threshold but still has enough room for a small model's quantized output, any unrelated llama.cpp failure enters this new branch solely because _gguf_failure_looks_like_disk checks free bytes. For example, an incompatible quantizer processing a sub-gigabyte model with 1.5 GB free is reported as a full disk, and the rebuild/version advice in the following branch is suppressed even though freeing space cannot fix it. Use ENOSPC/error text as the required signal here, or compare free space with the estimated output size rather than a model-independent threshold.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in d18712b, taking the second option: the check now compares free space with the estimated output size (needed_bytes, from the base GGUF times the quant ratio) and keeps the fixed floor only for callers that cannot say. Regression test: test_a_small_output_with_modest_free_space_is_not_called_a_full_disk.

Reclamation was deciding ownership from file naming, and the names a merge
writes are exactly the names an earlier save wrote. Validating the index was
not enough: it rejects a partial stale listing, but a previous completed
sharded save leaves an index that is self-consistent, names one stem, and has
every shard present. transformers removes neither, so after the merge that set
is indistinguishable from one this run produced, and a tight disk deleted it.
The same hole covered consolidated.safetensors, a name the shard selection
drops whenever other shards coexist, so a reused output directory could lose a
checkpoint this export never wrote.

Both are answered by recording the directory contents before the merge writes,
where the difference still exists, and reclaiming only what appeared after.
An export that cannot read the directory beforehand reclaims nothing, since the
deletion is permanent and a guess is not good enough to justify it.

Also sizes the disk-full diagnosis against the output rather than a fixed 2GB
floor. Room is a relation between free space and the write that failed: a
400MB quant with 1.5GB free has all it needs, and calling that a full disk hid
the rebuild advice that would have fixed the real problem.

Note for callers: save_to_gguf(merge_is_disposable = True) now also needs
preexisting_weights before it will reclaim anything. Erring toward keeping
files seemed right for the one case where being wrong is unrecoverable.

@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: d18712b096

ℹ️ 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 Outdated
"I suggest you to save the 16bit model first, then use manual llama.cpp conversion.\n"
f"Error: {e}"
) from e
elif _gguf_failure_looks_like_disk(e, gguf_directory, needed_bytes = _needed):

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 Account for partial output before diagnosing a full disk

When llama-quantize writes part of a large output and then fails for a non-disk reason, this compares the remaining free space with _needed, which estimates the entire output rather than the bytes still unwritten. For example, an export starting with 12 GB free can write 5 GB of a 10 GB output, hit an unsupported tensor, and then be classified as out of disk because 7 GB is less than 10 GB, suppressing the llama.cpp rebuild/version advice that may address the actual failure. Compare against the estimated remaining bytes (or add the partial output_location size back to free space) before selecting this branch.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, and fixed in 7185d40. llama-quantize streams into its output (llama-quant.cpp opens the ofstream at 1113 and writes each tensor at 1274), so the partial file is real and its bytes came out of the free space being measured while needed_bytes still describes the whole output. _gguf_failure_looks_like_disk now takes partial_output and credits those bytes back, on the filesystem that holds them only, and both _quantize_one branches pass output_location. Regression test: test_the_bytes_already_written_are_not_charged_twice.

pre-commit-ci Bot and others added 3 commits August 13, 2026 09:03
llama-quantize streams into its output file, so a pass that dies partway
leaves those bytes on disk. The disk check then measured the remaining
free space against an estimate of the whole output and read a 10GB export
that started with 12GB free and failed on an unsupported tensor as a full
disk, suppressing the llama.cpp rebuild advice that addressed the real
failure. Add the partial file back, on its own filesystem only.

@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: 7185d40bc9

ℹ️ 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 Outdated
Comment on lines +2148 to +2149
* _gguf_output_size_ratio(quant_method, first_conversion)
)

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 Use a realistic output size for failure diagnosis

When an unrelated quantizer failure occurs with free space between the real output size and this deliberately inflated estimate, _gguf_failure_looks_like_disk reports a full disk and suppresses the llama.cpp rebuild/version advice even though the output would have fit. Fresh evidence in this revision is that _gguf_output_size_ratio documents itself as an upper bound and, for example, charges Q4_K_M 5.5 bits per weight while the nearby sizing comment says it is roughly 4.5; a 60 GB BF16 base with 19 GB free is therefore diagnosed as short despite an expected output of about 17 GB. Use a realistic estimate for diagnostics or require a disk-specific error signal rather than reusing the conservative reclamation bound.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, and fixed in 4de41b0. The two callers of _gguf_output_size_ratio are hurt by opposite errors: reclamation must not under-count, diagnosis must not over-count, and one bound cannot serve both. It now takes upper_bound, and the diagnosis at save.py:2146 asks for the lower one, so q4_k_m is priced at its nominal 4 bits rather than 4+1.5. llama.cpp's own 7B table puts Q4_K_M at 3.80G against 6.74B parameters, about 4.84 bits a weight, so the nominal width is a real floor and 5.5 was over by roughly a fifth. Your 60GB/19GB case: the threshold drops from 20.6GB to 15.0GB, so the rebuild advice survives. A type with no known width now returns None and puts the caller back on the fixed floor instead of being charged a whole base copy. Reclamation keeps the upper bound unchanged. Regression test: test_the_diagnosis_is_not_priced_off_the_reclamation_bound.

Comment thread unsloth/save.py Outdated
continue
if _is_one_whole_shard_set(listed, names):
indexed.update(listed)
return sorted(n for n in names if n in indexed or _MERGE_WEIGHT_NAME.match(n))

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 Remove the disposable index with its indexed shards

When a sharded merge uses a stem outside model or consolidated—a case this function explicitly supports by reading the index—this return selects and deletes the shards but leaves the newly created model.safetensors.index.json behind. On a second export into the same directory, the provenance snapshot classifies that dangling index as preexisting and filters it out before this function runs, so the new noncanonical shards can no longer be discovered through the index or matched by _MERGE_WEIGHT_NAME; a tight-disk rerun consequently reclaims zero bytes and can fail quantization. Include the index in reclamation when provenance shows that this export created it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, and fixed in 4de41b0. _merge_weight_files now returns the index alongside the shards it named. Reproduced both halves: with a merge under an archive-0000N-of-00002 stem, the first export freed 60GB and left model.safetensors.index.json behind, and the second export into the same directory freed 0 because the snapshot then classified that leftover as preexisting; after the fix both rounds free 60GB. The unconditional half is that any sharded reclamation used to leave an index pointing at files it had just deleted. It is provenance-safe: names is already filtered against preexisting_weights before this runs, so an index only reaches the new branch when this export wrote it, and _is_one_whole_shard_set still has to accept the full set first. Regression test: test_the_index_is_reclaimed_with_the_shards_it_named.

danielhanchen added 2 commits August 13, 2026 10:47
Both sides added a keyword to the same unsloth_save_pretrained_gguf call in
the SentenceTransformer GGUF path: this branch added merge_is_disposable to
keep the 0_Transformer module from being reclaimed, and main added
imatrix_file. They are independent, so both are kept.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 5104afe6a9

ℹ️ 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 71656a0 into unslothai:main Aug 13, 2026
45 of 50 checks passed
danielhanchen pushed a commit that referenced this pull request Aug 13, 2026
Both sides add a deletion to the arguments = dict(locals()) snapshot in
unsloth_save_pretrained_gguf: this branch drops _gguf_prewarm_ok, and main via
#8500 drops merge_is_disposable. Both keys are in the snapshot, one as a local
bound before it and one as a parameter, and neither deletion subsumes the
other, so both are kept.
@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.

1 participant