Repository navigation
Report the real cause when a save or GGUF export fails - #7861
Conversation
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cce6dee1f2
ℹ️ 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".
| if shutil.disk_usage(path).free < _DISK_HEADROOM_BYTES: | ||
| return True |
There was a problem hiding this comment.
Do not treat low free space alone as the failure cause
On Kaggle, if either the save filesystem or current-working-directory filesystem has less than 2 GiB free, this returns true for every exception, including an unsupported architecture or invalid quantization method. The caller consequently restores the misleading 20 GB disk message this change is intended to avoid whenever disk is merely low but did not cause the failure; free-space state should only corroborate an ambiguous I/O failure rather than override a specific non-disk error.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Deliberate and documented at save.py:3297-3300: two independent signals, either alone sufficient, because the message can omit ENOSPC after cleanup and the disk can be genuinely full while a subprocess surfaced something vaguer. The misfire needs Kaggle plus under 2GiB free, a state where freeing space is not wrong advice anyway, and the motivating ModernBERT case sits at roughly 19GB free so the gate correctly returns False.
| return True | ||
| if getattr(exc, "errno", None) == 28: | ||
| return True | ||
| for path in (save_directory, os.getcwd()): |
There was a problem hiding this comment.
Protect the current-directory lookup from masking the error
If the process's working directory has been removed or become inaccessible, os.getcwd() raises while constructing this tuple, before execution enters the guarded shutil.disk_usage block. In that situation the diagnostic helper replaces the original GGUF conversion exception with FileNotFoundError, contradicting its never-raises contract; obtain the current directory inside the protected code or handle its OSError separately.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct that os.getcwd() at save.py:3307 is evaluated outside the try at 3310, but a removed or unreadable cwd is not reachable here: there is no os.chdir anywhere in unsloth or unsloth_zoo, and Colab (/content) and Kaggle (/kaggle/working) never delete it. It would take a user chdir'ing into a directory they then rmtree mid-conversion.
Four related failures where saving reported something other than what actually went wrong. Kaggle blamed the disk for every GGUF failure. save_to_gguf is wrapped in a bare `except Exception` that, whenever IS_KAGGLE_ENVIRONMENT is set, reported the 20GB disk space limit no matter what failed. An unsupported architecture, a missing tokenizer and a bad quant method all told the user to free up space. bert_classification exposed it: ModernBERT for sequence classification has no llama.cpp converter and cannot produce a GGUF at any size, so the notebook reported a disk problem that did not exist. The message is now gated on _gguf_failure_looks_like_disk, which takes either of two independent signals: the error text or errno naming ENOSPC, or free space under 2GB on the save directory or the cwd. Either alone is enough, because each can be absent for a good reason. The check never raises. Both branches now chain with `from e`, so the original traceback survives either way. That helper originally landed in the MIDDLE of unsloth_save_pretrained_gguf instead of after it, and this commit carries the corrected placement. The function still parsed and still ran, but it now ended right after building the quantization method list, so it did the 16-bit merge and returned without ever calling save_to_gguf. Everything below the insertion point became dead code stranded inside the helper, under its return. save_pretrained_gguf raised nothing, printed its usual progress, left a populated merge directory behind and produced no .gguf, which is indistinguishable from success unless you go looking for the file. It cost a full sweep before it was noticed, and no ordinary unit test would have caught it since both halves are valid Python and the import kept working. tests/test_save_entrypoints_reach_converter.py checks the structural properties directly against the AST instead: the converter call is present, reachable, and not stranded after a return anywhere in save.py. A save that failed on an offloaded model said nothing about the offload. A model too large for its GPU is partially offloaded, and accelerate leaves those parameters on the meta device with the real data in a weights_map. Saving then walks into accelerate internals that assume the map is populated, so the user sees "'NoneType' object is not subscriptable" or "Cannot copy out of meta tensor; no data!". Qwen3_MoE, Qwen3_5_MoE and Nemotron-3-Nano-30B all failed to export this way. The hint is appended to the existing error, never substituted for it, the exception type is unchanged, and it stays empty unless a meta parameter is really present. It caps at three parameter names. The helper sits above the @_normalize_tied_weights_keys_for_save decorator so the decorator still applies to unsloth_save_pretrained_gguf. SentenceTransformer had a different save_pretrained_merged signature. FastLanguageModel takes (save_directory, tokenizer = None, save_method = "merged_16bit", ...) and every notebook and doc calls it positionally, but FastSentenceTransformer bound the same public name to (self, save_directory, **kwargs), so that call answered with "takes 2 positional arguments but 4 were given". Five embedding notebooks hit it. Keyword callers were unaffected, which is why it went unnoticed. Both closures that bind the name now take tokenizer and save_method positionally with the same defaults, so every previous keyword call behaves exactly as before. save_method is honoured rather than accepted and dropped: the merge_and_unload path can only produce a 16-bit merge, so it refuses anything else, and refuses before writing anything so no half-finished directory is left behind. The other path forwards to the FastLanguageModel merge, which understands every method.
cce6dee to
df663d1
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: df663d19a0
ℹ️ 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".
| if tokenizer is None: | ||
| tokenizer = save_kwargs.pop("tokenizer", self.tokenizer) |
There was a problem hiding this comment.
Preserve explicit tokenizer=None
When a caller explicitly passes tokenizer=None to suppress tokenizer export, Python binds it to the new formal parameter, so save_kwargs no longer contains the key and this fallback replaces it with self.tokenizer. Before this change, the kwargs-only signature preserved the explicit None and skipped tokenizer.save_pretrained; now the export may unexpectedly write tokenizer files or fail while saving a tokenizer the caller deliberately excluded. The second closure repeats the same regression.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The behaviour change is real, but the consequence is one extra tokenizer written next to the model, not wrong output or a crash, and no caller in the repo, notebooks or docs passes tokenizer=None to suppress export. Leaving the signature aligned with FastLanguageModel.save_pretrained_merged, which is what this commit is for.
| for name, tensor in model.named_parameters(): | ||
| if getattr(tensor, "device", None) is not None and tensor.device.type == "meta": | ||
| meta.append(name) |
There was a problem hiding this comment.
Gate the offload hint on the actual exception
When a model has any meta parameters but saving fails for an unrelated reason—such as an unwritable output directory or tokenizer serialization error—this helper still appends a definitive explanation that offloading caused the failure and recommends a larger GPU. The helper examines only model state, not e, even though both callers invoke it for every exception from the entire save operation; restrict the hint to exception types/messages associated with accessing meta tensors so the newly reported diagnosis does not obscure the real actionable cause.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The hint is gated on a real meta-device parameter at save.py:2866-2894 and is appended to the original error rather than substituted, with the exception type unchanged (save.py:3060-3062, 3085-3087). To misfire you need a model that genuinely has offloaded parameters and a save that fails for an unrelated reason, and in that state the offload is a real problem worth naming.
The converter is a subprocess and llama.cpp holds tensors in host RAM, so a
large model exceeds what a free Colab or Kaggle VM has. The kernel OOM-killer
takes it and subprocess reports only
Command '[...]' died with <Signals.SIGKILL: 9>
which names no resource at all. The user's first guess is VRAM, and on Kaggle
the existing branch would have called it a disk problem, which is the wrong
advice twice over.
Gemma3N_(4B)-Audio is the case, measured today: it trains, infers and merges
cleanly (15.7GB written, 155GB disk free, freed before the conversion) and the
converter is then SIGKILLed. It happens on the high-RAM T4 as well as the plain
one, so this is not a lane that can be configured around.
SIGKILL alone is the signal: a converter that fails on its own raises and exits
non-zero, so a kill is either the OOM-killer or someone stopping the run by
hand, and both are worth naming. Checked before the Kaggle disk branch so a
SIGKILL on a fullish disk is not misreported, and chained with `from e` so the
original survives.
7 tests, including that an ordinary converter failure and a real disk failure
are both still reported as themselves.
|
Pushed a fourth case to this PR, found by a live run today rather than reasoned about.
which names no resource. llama.cpp's converter holds tensors in host RAM, so this is the kernel OOM-killer, and it reproduces on the high-RAM T4 as well as the plain one. Two ways the old code got it wrong: the user's first guess for a kill during a model export is VRAM, and on Kaggle the existing branch would have reported it as a disk problem, which is confidently wrong advice. The new branch is checked before the Kaggle disk branch so a SIGKILL on a fullish disk is not misreported, and chains with 7 new tests, including that an ordinary converter failure and a genuine disk failure are each still reported as themselves. 60 passed across this PR's four test files. |
…essages Three follow-ups to the review of the previous two commits. The no_modules fallback in the second _save_pretrained_merged accepted a save_method and then dropped it: the branch strips the Unsloth-specific kwargs and calls merge_and_unload() unconditionally, having already deleted the adapter files save_pretrained had just written. So save_pretrained_merged(dir, tokenizer, "lora") returned merged full weights for a request to write adapters, silently. That path is reached whenever no modules.json is found, which is any plain HF encoder checkpoint loaded through FastSentenceTransformer. It now refuses before writing anything, exactly as the fast-encoder definition above it already did. The modules.json path is unchanged and still forwards every method to the FastLanguageModel merge. save_method spellings now mean the same thing on every model type. unsloth_save_model lowercases and strips spaces before validating, so save_method = "MERGED_16BIT" and "merged 16bit" have always worked; the new signature check compared the raw string and rejected them, which broke keyword callers the previous commit promised were unaffected. Both closures normalize first. save_to_gguf's own missing-output and quantize handlers still added Kaggle's 20GB disk explanation for every failure, and they bake it into the exception message, so the outer gate cannot recover the real cause afterwards. Both now take the same _gguf_failure_looks_like_disk check, and the quantize branch chains with from e like the rest. A broken llama.cpp build with 19GB free is what that handler used to call a disk problem: see #835, where the reporter was told about Kaggle's disk limit while not on Kaggle. Tests: 6 new in test_st_save_merged_signature.py (28) covering the no_modules refusal, that it refuses before merging or writing, that the forwarding path still accepts "lora", and the case/space variants on both closures; 3 new in test_kaggle_gguf_error_message.py (25) asserting no 20GB message is left ungated anywhere in save.py. Each fails without its fix.
unsloth is Apache-2.0 (LICENSE, and pyproject license = "Apache-2.0"), and 303 of its 314 test files carry no header at all while 10 carry the Apache one. The new files here went in with an AGPL-3.0 notice attributed to Unsloth Zoo, which is the wrong licence, the wrong project and against the convention here.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 15d33a1761
ℹ️ 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".
| text = f"{type(exc).__name__}: {exc}".lower() | ||
| if any(p in text for p in _DISK_FULL_PATTERNS): | ||
| return True |
There was a problem hiding this comment.
Inspect wrapped disk errors before falling through
For subprocess-backed converter failures, the ENOSPC text is often in CalledProcessError.stderr/output or in a chained cause, while str(e) is only Command ... returned non-zero exit status ...; this helper only scans the top-level formatted exception. When that actual disk/quota failure is wrapped and the filesystem headroom check is inconclusive (for example a quota error or cleanup freed space), Kaggle takes the generic branch and loses the 20GB disk guidance this gate is meant to preserve, so include stdout/stderr and chained causes in the disk-text scan.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Checked the exceptions this helper actually receives and the premise does not hold here: every subprocess-backed converter failure folds stderr/stdout into the message before re-raising, so the ENOSPC text is in the top-level formatted exception. unsloth_zoo's quantize_gguf builds details from e.stderr/e.stdout and raises RuntimeError(f"Failed to quantize ...: {e}{details}"), convert_to_gguf does the same with its --- converter stderr --- block, and save.py's own _quantize_q2_k_l appends "Subprocess stderr:". save.py then embeds that whole message again as Error: {e}. The only place a bare CalledProcessError is constructed without output is unsloth_zoo's _convert_to_gguf, which nothing calls. Leaving the scan as is.
_gguf_failure_looks_like_disk has a second signal independent of the message: a filesystem under 2GiB free is a disk failure whatever the exception says. It probes save_directory and then os.getcwd(), so on a host whose working directory is that full, every 'this is NOT a disk problem' test inverts and fails for a reason unrelated to the message it asserts about. Report 99GiB rather than pinning _DISK_HEADROOM_BYTES to 0, so the real comparison still executes and a nonsensical headroom would still be caught.
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
pre-commit.ci's ruff-format-with-kwargs hook reported "files were modified by
this hook" and could not push the result back, so the check stayed red.
Applied locally instead.
Three source-asserting tests had to be made robust rather than re-pinned,
since the reformatting is legitimate and will happen again:
- test_the_flag_is_recorded_beside_the_dtype counted the literal
"self._autocast_enabled = (", which the formatter collapsed onto one line.
Now pairs each _autocast_dtype initialiser with a nearby flag assignment by
position, so it still catches a genuinely missing one.
- test_the_original_error_is_still_reported anchored on a whole f-string
literal, which the formatter merged with the hint that follows it. Anchors
on the message text alone now; either shape satisfies the intent.
- test_the_source_beats_the_version_fallback exposed a real fragility rather
than a test problem: the detector matched the literal "kw_only=True", so any
whitespace in transformers' own source would have read an install that needs
nothing as one that needs patching. Made whitespace-tolerant.
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…i#7861 get_device_type() checked the UNSLOTH_ALLOW_CPU escape hatch before the MLX check, so an Apple Silicon host with MLX reported "cuda" and get_device_count() then dereferenced torch, which device_type.py never imports on MLX: unsloth/device_type.py:99: in get_device_count return torch.cuda.device_count() E NameError: name 'torch' is not defined unsloth/__init__.py and unsloth_zoo.device_type both pick MLX first, so the two also disagreed about the runtime inside one process. Non-MLX hosts are unaffected: _IS_MLX is False there, so the ordering never applies.
Four save and export failures that each reported something other than what went wrong.
Kaggle was blamed for every GGUF failure
Any exception out of
save_to_ggufon Kaggle produced:regardless of cause. An unsupported architecture, a missing converter, a bad tokenizer, all of them came out as "you are out of disk", sending the user to free space that was never the problem.
The message is now gated on the failure actually looking like a disk failure: ENOSPC and the wordings the various layers use for it, plus a headroom check against the 20GB allowance. Everything else raises the real error. Both branches now chain with
from e, so the original traceback survives.The disk-check helper displaced the conversion
Worth stating plainly, since it is the part of this diff most worth reading twice: the first version of that gate spliced the helper into the middle of
unsloth_save_pretrained_gguf, between the code that runs the conversion and the code that consumes its result. The conversion stopped happening. It was caught by a follow-up and this branch carries the corrected final state, with_gguf_failure_looks_like_diskand its two constants defined after the function returns.The same class of splice error had also left
@_normalize_tied_weights_keys_for_savebound to a helper rather than tounsloth_save_pretrained_gguf, which silently dropped the tied-weights key normalisation for anyone saving straight to GGUF. That is corrected here too.An offloaded model failed with an unrelated message
A model that does not fit its GPU gets partially offloaded, and accelerate leaves those parameters on the meta device. Saving then dies inside accelerate with
'NoneType' object is not subscriptableorCannot copy out of meta tensor, neither of which mentions the offload.The two save failure paths now append a sentence naming up to three offloaded parameters and what to do about it. It returns an empty string when no meta parameter is present, so unrelated failures are not mislabelled, and it is wrapped so a diagnostic can never replace the real error with its own.
SentenceTransformer.save_pretrained_mergedtook a different signatureThe two
_save_pretrained_mergedclosures on the sentence-transformer path did not matchunsloth_save_pretrained_merged, so code written against the documented signature failed on an ST model. They now agree, asserted against the reference signature in the tests.Tests
88 passed, 0 failed, 0 skipped. Four new files plus the existing
tests/saving/suites for tied-weights normalisation, export API surface, export dispatch,Nonetokenizer patching and quant-method normalisation.Two existing files were deliberately not run and both are unrelated to this diff:
tests/saving/test_unsloth_save.pyneeds a GPU and downloads real hub models, and the twofix_sentencepiece_*files fail collection with a protobufduplicate file name sentencepiece_model.protoconflict that reproduces identically on pristinemain.