Repository navigation
Fix repeated base model downloads across checkpoint exports - #6896
Conversation
Pre-warm the HF hub cache with the 16bit base weights before merge_and_overwrite_lora runs. The merge fetches shards with hf_hub_download(local_dir=...), which never populates the hub cache, so temporary merge directories (GGUF checkpoint exports) forced a full re-download of the base model for every checkpoint. The first export now downloads once into the cache and later exports copy from it. Skips itself when already cached, offline, on Kaggle/Colab, for local or nf4/fp4 bases, non-downloading save methods, or low disk. Opt out with UNSLOTH_PREWARM_HUB_CACHE=0.
There was a problem hiding this comment.
Code Review
This pull request introduces a helper function _prewarm_base_model_hub_cache in unsloth/save.py and corresponding regression tests to address issue #6890, preventing repeated base-model downloads across checkpoint exports by pre-warming the persistent Hugging Face hub cache. The reviewer provided several valuable suggestions to make this implementation more robust, including safely accessing the model configuration via getattr to avoid potential AttributeErrors, supporting base models that use .bin weights in addition to .safetensors, converting the cache path to an absolute path to correctly handle relative path configurations when checking disk space, and dynamically resolving the model index file name.
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.
| if not isinstance(model, PeftModel): | ||
| return | ||
|
|
||
| try: | ||
| try: | ||
| model_name = get_model_name(model.config._name_or_path, load_in_4bit = False) |
There was a problem hiding this comment.
Accessing model.config._name_or_path directly can raise an AttributeError if model.config is None or does not have the _name_or_path attribute. Additionally, the fallback in the except block tries to access the exact same attribute, which would raise the same error. Using getattr safely avoids these issues.
| if not isinstance(model, PeftModel): | |
| return | |
| try: | |
| try: | |
| model_name = get_model_name(model.config._name_or_path, load_in_4bit = False) | |
| config = getattr(model, "config", None) | |
| name_or_path = getattr(config, "_name_or_path", None) if config is not None else None | |
| if not name_or_path: | |
| return | |
| try: | |
| model_name = get_model_name(name_or_path, load_in_4bit = False) | |
| except Exception: | |
| model_name = name_or_path | |
| if os.path.isdir(model_name): | |
| return # local checkpoints are copied, never downloaded |
There was a problem hiding this comment.
Good catch, applied in 4c7f64a. The attribute error was being swallowed by the outer try/except, but it printed a misleading "Could not pre-cache" warning for what is really a benign missing-config case. Now it reads _name_or_path once via getattr and skips silently. Added test_missing_config_skips_cleanly which fails without this change.
| if base_is_quantized and quant_type in ("nf4", "fp4"): | ||
| return # the 16bit merge refuses these bases; nothing worth caching | ||
|
|
||
| from huggingface_hub import HfFileSystem, hf_hub_download, snapshot_download | ||
|
|
||
| # Mirror the zoo's shard listing (drop consolidated.safetensors when proper | ||
| # shards coexist) so the cached set is a superset of what the merge looks up. | ||
| shard_names = [] | ||
| total_size_in_bytes = 0 | ||
| for x in HfFileSystem(token = token).ls(model_name, detail = True): | ||
| if x["name"].endswith(".safetensors"): | ||
| shard_names.append((os.path.split(x["name"])[-1], int(x.get("size") or 0))) |
There was a problem hiding this comment.
The current implementation only looks for .safetensors files. However, some base models might only have .bin weights. We can support both formats by preferring .safetensors if they exist, and falling back to .bin files otherwise. This prevents downloading both formats when both are present in the repository.
# Mirror the zoo's shard listing (drop consolidated.safetensors when proper
# shards coexist) so the cached set is a superset of what the merge looks up.
safetensors_shards = []
bin_shards = []
for x in HfFileSystem(token = token).ls(model_name, detail = True):
filename = os.path.split(x["name"])[-1]
size = int(x.get("size") or 0)
if filename.endswith(".safetensors"):
safetensors_shards.append((filename, size))
elif filename.endswith(".bin"):
bin_shards.append((filename, size))
if safetensors_shards:
shard_names = safetensors_shards
index_file = "model.safetensors.index.json"
else:
shard_names = bin_shards
index_file = "pytorch_model.bin.index.json"
if any(name != "consolidated.safetensors" for name, _ in shard_names):
shard_names = [x for x in shard_names if x[0] != "consolidated.safetensors"]
if not shard_names:
return
total_size_in_bytes = sum(size for _, size in shard_names)There was a problem hiding this comment.
Not adopting this one. The merge this pre-warm feeds (unsloth_zoo.merge_and_overwrite_lora) is safetensors-only: it builds its shard list purely from .safetensors files and raises RuntimeError("No '.safetensors' files found for the base model") if there are none. It never reads .bin / pytorch_model weights. So for a .bin-only base the merge itself fails regardless of the cache, and pre-warming .bin shards would just download files the merge never looks up, breaking the invariant that the cached set mirrors exactly what the merge requests. For mixed repos both versions already prefer safetensors, so there is no behavioral difference there.
There was a problem hiding this comment.
Not adopting: the merge this pre-warm feeds (unsloth_zoo.merge_and_overwrite_lora) is safetensors-only and raises if a base has no .safetensors, so pre-warming .bin shards would cache files the merge never requests. Keeping the cached set an exact mirror of what the merge looks up.
| return # already fully cached | ||
| except Exception: | ||
| pass | ||
|
|
||
| # The cache copy is extra disk on top of the merge working copy; need room for both. | ||
| from huggingface_hub import constants as _hf_constants | ||
|
|
||
| cache_probe = os.path.expanduser(str(_hf_constants.HF_HUB_CACHE)) |
There was a problem hiding this comment.
If HF_HUB_CACHE is configured as a relative path, traversing up using os.path.dirname might eventually yield an empty string "", which does not exist, causing free_space to default to 0 and unnecessarily skipping the pre-warming. Converting cache_probe to an absolute path first guarantees that the traversal will always reach a valid existing directory (at least the root directory).
| return # already fully cached | |
| except Exception: | |
| pass | |
| # The cache copy is extra disk on top of the merge working copy; need room for both. | |
| from huggingface_hub import constants as _hf_constants | |
| cache_probe = os.path.expanduser(str(_hf_constants.HF_HUB_CACHE)) | |
| from huggingface_hub import constants as _hf_constants | |
| cache_probe = os.path.abspath(os.path.expanduser(str(_hf_constants.HF_HUB_CACHE))) | |
| while cache_probe and not os.path.exists(cache_probe): | |
| parent = os.path.dirname(cache_probe) | |
| if parent == cache_probe: | |
| break | |
| cache_probe = parent | |
| free_space = shutil.disk_usage(cache_probe).free if os.path.exists(cache_probe) else 0 |
There was a problem hiding this comment.
Applied in 4c7f64a. Confirmed the bug: a relative HF_HUB_CACHE like relcache/hub whose leaf does not exist yet walks up to "", so os.path.exists is False, free_space becomes 0 and the pre-warm is wrongly skipped. abspath resolves it to an existing root (/ or the drive root on Windows) so the disk check runs. Added test_relative_hub_cache_does_not_falsely_skip which fails without this change.
| return | ||
|
|
||
| print( | ||
| f"Unsloth: Downloading `{model_name}` into the Hugging Face cache so future " | ||
| f"exports skip the {round(total_size_in_bytes / 1024**3, 1)}GB download..." | ||
| ) |
There was a problem hiding this comment.
Use the dynamically determined index_file instead of the hardcoded "model.safetensors.index.json" to ensure correct patterns are allowed when downloading .bin models.
| return | |
| print( | |
| f"Unsloth: Downloading `{model_name}` into the Hugging Face cache so future " | |
| f"exports skip the {round(total_size_in_bytes / 1024**3, 1)}GB download..." | |
| ) | |
| snapshot_download( | |
| repo_id = model_name, | |
| allow_patterns = [name for name, _ in shard_names] | |
| + [index_file, "tokenizer.model"], | |
| token = token, | |
| ) |
There was a problem hiding this comment.
This depends on the .bin support in the other comment, which I am not adopting since the merge is safetensors-only. The hardcoded model.safetensors.index.json in allow_patterns is correct: allow_patterns is a filter, so listing a name the repo does not have is a harmless no-op, and every repo the merge can actually consume is safetensors and carries that index. Keeping it as-is.
There was a problem hiding this comment.
Moot given the above: since only .safetensors are pre-warmed, the index is always model.safetensors.index.json. A dynamic index_file only matters if .bin shards were supported, which the merge does not.
|
Ran a full simulation campaign for this fix in isolated uv venvs, separate from the unit tests already in the PR. Summary below. End to end, real merge, real networkIsolated HF_HOME, real Before this PR (instrumented download counters on the zoo's
After this PR:
Contract and edge case scenarios (13, each in its own subprocess with isolated HF_HOME)All pass on three version combos: huggingface_hub 0.34.0 on Python 3.9 (both floors in pyproject), 0.36.2 on 3.13 (what Studio ships), and 1.22.0 on 3.12 (latest):
The 21 unit tests in the PR also pass in a bare Python 3.9 venv with only pytest installed, so they carry no hidden dependencies. No frontend, API or route changes in this PR, so browser behavior is unaffected; verified the Studio UI still serves and the export router responds normally with the patch applied. One issue the simulation surfaced: the progress message printed |
…B_CACHE - Read config._name_or_path via getattr so a model without a config skips cleanly instead of taking the outer error path. - abspath the cache probe so a relative HF_HUB_CACHE walks up to a real root rather than "", which would zero the free-space check and skip pre-warm. Both from PR review; each covered by a test that fails without the fix.
Resolve the hub cache the same way the merge does (unsloth_zoo _active_caches, live env) instead of huggingface_hub's import-time-frozen constants.HF_HUB_CACHE, and pass it as cache_dir to the cached probe, disk check and snapshot_download. Without this, a runtime HF_HOME/HF_HUB_CACHE redirect (unsloth_zoo redirect_hf_cache_if_readonly on a read-only default cache, or Studio) makes the pre-warm populate a different directory than the one the merge reads, so the cache-copy fast path misses and the base re-downloads on every export anyway. Adds 3 regression tests covering the cache_dir threading and the redirect case.
|
Pushed a follow-up (0b6aff0) hardening the cache resolution. The pre-warm was reading The fix resolves the cache the same way the merge does and threads it as Verified:
|
…s reuse the cache too For a merged_16bit export of an FP8 base with an existing 16bit sibling, the merge swaps to the sibling and downloads that (unsloth_zoo _resolve_fp8_16bit_sibling), so pre-warming the FP8 repo missed the cache and re-downloaded the sibling every export. Mirror the swap and pre-warm the sibling. No sibling still caches the FP8 repo for the in-place dequant path. Adds 2 regression tests.
|
Follow-up (418972c): pre-warm the 16bit sibling for FP8 bases. While re-reviewing I found one gap: for a Fix mirrors the merge: when the base is FP8 and the sibling resolves, pre-warm the sibling instead. If there is no sibling the FP8 repo is still cached (the merge dequantizes it in place there), so that path keeps working. Two regression tests added (sibling pre-warmed vs FP8 repo pre-warmed). Also synced the branch with main so the ruff-format-with-kwargs hook stops flagging the stale files it could not push before. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 418972c268
ℹ️ 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 save_method == "mxfp4" and model_name.endswith("-BF16"): | ||
| return |
There was a problem hiding this comment.
Handle lowercase BF16 GPT-OSS IDs
When a GPT-OSS LoRA was loaded from a lowercase BF16 repo such as unsloth/gpt-oss-20b-bf16, the mxfp4 merge path still swaps to the MXFP4 base, but this case-sensitive check does not skip it. The prewarm then snapshots the BF16 repo's large safetensors into the cache, consuming time/disk while the subsequent merge still has to download the MXFP4 repo, so the repeated-download fix is bypassed for those valid lowercase IDs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The merge's gpt-oss BF16 to MXFP4 swap is itself case-sensitive (saving_utils.py: only_attention_loras and save_method == 'mxfp4' and model_name.endswith('-BF16'), then removesuffix('-BF16')). A lowercase '-bf16' id is therefore not swapped by the merge either, so the merge downloads that repo directly and pre-warming it is correct, not wasted. No divergence here.
| for x in HfFileSystem(token = token).ls(model_name, detail = True): | ||
| if x["name"].endswith(".safetensors"): | ||
| shard_names.append((os.path.split(x["name"])[-1], int(x.get("size") or 0))) |
There was a problem hiding this comment.
Filter prewarm shards through the safetensors index
For Hub repos that ship stale duplicate shard sets or other root .safetensors files not referenced by model.safetensors.index.json, merge_and_overwrite_lora filters the shard list through the index before copying/downloading, but this prewarm caches every .safetensors file it sees. In those repos the disk-space gate can skip prewarming because it counts unused shards, or snapshot_download can download large files the merge will never read, so repeated exports still re-download the actual indexed shards.
Useful? React with 👍 / 👎.
Repos that ship a leftover shard set the index does not reference (e.g. granite-3.2) made the disk gate over-count and snapshot_download fetch shards the merge never reads. Mirror the merge: on the download path, keep only index-referenced shards. Runs after the already-cached check so the cached fast path stays network-free. Adds 2 tests.
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
|
Manually tested the main case. Log can be found here. Trained from note: still saw a noisy |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0006698d37
ℹ️ 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".
|
|
||
| print(f"Unsloth: Model saved successfully to '{save_directory}'") | ||
| else: | ||
| _prewarm_base_model_hub_cache(model, save_method = save_method, token = token) |
There was a problem hiding this comment.
Avoid prewarming before target disk checks
When save_directory is on a different filesystem from the HF cache, this new prewarm runs before merge_and_overwrite_lora/prepare_saving validates that the merge destination can hold the 16-bit checkpoint. _prewarm_base_model_hub_cache only gates on free space in the cache path, so a local export to a nearly-full target volume can download a tens-of-GB base into the cache and then immediately fail the merge due to target disk space; previously the large download did not start until after that validation. Please either include the resolved merge destination in the prewarm disk gate or run the prewarm after the merge directory has been validated.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The pre-warm writes into the persistent HF cache (gated on 2x free there), not into save_directory, and is best-effort. If the merge then fails on a full target volume, the base is already in the cache, so freeing space and retrying reuses it via _try_copy_all_from_cache (the helper early-returns 'already fully cached') instead of re-downloading. So the bytes are the intended caching, not wasted work. Fail-fast target-disk validation belongs in the merge's prepare_saving, not in a cache warmer that deliberately runs first to populate the cache.
|
|
||
| print(f"Unsloth: Model saved successfully to '{save_directory}'") | ||
| else: | ||
| _prewarm_base_model_hub_cache(model, save_method = save_method, token = token) |
There was a problem hiding this comment.
Validate hub pushes before prewarming
For push_to_hub=True, this prewarm now downloads the full base before merge_and_overwrite_lora reaches prepare_saving, which is where the target repo is created and write permissions are checked. With a read-only/insufficient token that can still read the public or gated base model, users can spend tens of GB of bandwidth and cache space before the upload fails immediately at repo creation; before this change the write-access failure happened before the large shard download. Please defer prewarming until after the hub repo/token validation for push paths.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same rationale: with a read-only token the base (which is readable) lands in the persistent cache, so once the user supplies a write-capable token the retry copies from cache rather than re-downloading. The download is bounded by the disk gate and is reused, not wasted. Up-front repo/token validation is the merge's responsibility and already runs before this on the compressed/gguf push paths (create_repo 'matching the normal push path'); duplicating it inside the best-effort warmer would couple it to details it should not own.
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 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. 🎉 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". |
Fixes #6890
Problem
Exporting multiple checkpoints of a model that trains on a pre-quantized 4bit base (for example gemma-4-31b-it) re-downloads the full fp16 base model on every single export. For a 59GB base this can take longer than the training run itself.
Root cause:
merge_and_overwrite_lorafetches the 16bit shards withhf_hub_download(local_dir = save_directory). Withlocal_dirset, huggingface_hub writes the files straight into the merge working directory and never populates the persistent hub cache (the.cache/huggingfacefolder reported in the issue is hub's local-dir metadata, not a redirectedHF_HOME). Studio GGUF exports run the merge in a throwaway_tmp_model_<uuid>directory that is deleted after conversion, so the download is lost every time.This affects more than GGUF export. Everything that funnels through
unsloth_generic_savehits the same path: 16bit merged export, FP8/NVFP4 compressed-tensors and torchao exports (they merge to 16bit first), andpush_to_hub_merged/push_to_hub_gguf(worst withuse_temp_file, where shards land in a deleted temp dir). Training, inference and LoRA adapter export are not affected since they use normalfrom_pretrainedcaching.Fix
The zoo already has a cache fast path (
_try_copy_all_from_cache) that copies shards from the hub cache instead of downloading. It just never gets a hit because nothing puts the fp16 base there. This PR adds_prewarm_base_model_hub_cache()inunsloth/save.py, called fromunsloth_generic_saveright beforemerge_and_overwrite_lora, so one site covers every export format. It runssnapshot_downloadfor the fp16 base into the persistent hub cache, mirroring the zoo's shard listing (drops a redundantconsolidated.safetensorswhen proper shards coexist) so the cached set is always a superset of what the merge looks up.Result: the first export downloads the base once, every later export copies from the cache. This also means a base that was manually pre-downloaded into the standard HF cache is now picked up automatically, which was the workaround the issue author tried and could not get working.
The helper is strictly best-effort and skips itself when:
UNSLOTH_PREWARM_HUB_CACHE=0(opt out)HF_HUB_OFFLINE/TRANSFORMERS_OFFLINE)merged_4bit,forced_merged_4bit,lora)-BF16to MXFP4 repo swap case, where pre-warming could cache the wrong repoAny exception inside the helper is swallowed and the export falls back to the previous streaming download behaviour.
Tests
tests/saving/test_prewarm_base_model_hub_cache.pyadds 21 GPU-free tests using the ast-extraction pattern already used elsewhere in the repo (sinceunsloth.savecannot be imported on hosts without an accelerator). They cover the download path and its arguments, the cache-hit skip, the disk gate, every skip condition above, the consolidated shard filter, exception swallowing, and thatunsloth_generic_savecalls the pre-warm before the merge.All 21 pass locally,
py_compileis clean andscripts/enforce_kwargs_spacing.pymakes no changes.