Skip to content

Fix repeated base model downloads across checkpoint exports - #6896

Merged
danielhanchen merged 14 commits into
mainfrom
fix/export-base-model-redownload
Jul 7, 2026
Merged

danielhanchen merged 14 commits into
mainfrom
fix/export-base-model-redownload

Conversation

@shimmyshimmer

Copy link
Copy Markdown
Member

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_lora fetches the 16bit shards with hf_hub_download(local_dir = save_directory). With local_dir set, huggingface_hub writes the files straight into the merge working directory and never populates the persistent hub cache (the .cache/huggingface folder reported in the issue is hub's local-dir metadata, not a redirected HF_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_save hits the same path: 16bit merged export, FP8/NVFP4 compressed-tensors and torchao exports (they merge to 16bit first), and push_to_hub_merged / push_to_hub_gguf (worst with use_temp_file, where shards land in a deleted temp dir). Training, inference and LoRA adapter export are not affected since they use normal from_pretrained caching.

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() in unsloth/save.py, called from unsloth_generic_save right before merge_and_overwrite_lora, so one site covers every export format. It runs snapshot_download for the fp16 base into the persistent hub cache, mirroring the zoo's shard listing (drops a redundant consolidated.safetensors when 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:

  • the shards are already fully cached
  • UNSLOTH_PREWARM_HUB_CACHE=0 (opt out)
  • offline (HF_HUB_OFFLINE / TRANSFORMERS_OFFLINE)
  • running on Kaggle/Colab, where the hub cache is deliberately purged to save disk
  • the base model is a local directory
  • the save method does not download the base (merged_4bit, forced_merged_4bit, lora)
  • the base is nf4/fp4 quantized (the 16bit merge refuses those anyway)
  • the gpt-oss -BF16 to MXFP4 repo swap case, where pre-warming could cache the wrong repo
  • free disk on the cache filesystem cannot hold the cache copy on top of the merge working copy

Any 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.py adds 21 GPU-free tests using the ast-extraction pattern already used elsewhere in the repo (since unsloth.save cannot 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 that unsloth_generic_save calls the pre-warm before the merge.

All 21 pass locally, py_compile is clean and scripts/enforce_kwargs_spacing.py makes no changes.

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.

@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 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.

Comment thread unsloth/save.py Outdated
Comment on lines +3723 to +3728
if not isinstance(model, PeftModel):
return

try:
try:
model_name = get_model_name(model.config._name_or_path, load_in_4bit = False)

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.

medium

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.

Suggested change
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

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.

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.

Comment thread unsloth/save.py
Comment on lines +3745 to +3756
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)))

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.

medium

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)

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 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.

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 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.

Comment thread unsloth/save.py Outdated
Comment on lines +3771 to +3778
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))

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.

medium

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).

Suggested change
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

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.

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.

Comment thread unsloth/save.py
Comment on lines +3792 to +3797
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..."
)

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.

medium

Use the dynamically determined index_file instead of the hardcoded "model.safetensors.index.json" to ensure correct patterns are allowed when downloading .bin models.

Suggested 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..."
)
snapshot_download(
repo_id = model_name,
allow_patterns = [name for name, _ in shard_names]
+ [index_file, "tokenizer.model"],
token = token,
)

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.

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.

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.

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.

@shimmyshimmer

shimmyshimmer commented Jul 6, 2026 •

Copy link
Copy Markdown
Member Author

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 network

Isolated HF_HOME, real unsloth_zoo.merge_and_overwrite_lora, a real tiny llama with a real PEFT LoRA (randomized lora_B), simulating the exact #6890 workflow: each checkpoint export merges into a _tmp_model_<uuid> dir that is deleted afterwards, twice in a row.

Before this PR (instrumented download counters on the zoo's hf_hub_download / snapshot_download):

  • export 1: shards downloaded again, export 2: shards downloaded again
  • hub cache after both exports: 0 safetensors, confirming local_dir downloads bypass the cache entirely

After this PR:

  • pre-warm downloads once into the hub cache
  • export 1 and export 2: zero shard downloads, the zoo logs Successfully copied all files from cache both times
  • equivalence check: all 21 merged tensors are bitwise identical between the download path and the cache path, so the fix cannot change export outputs

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):

  • pre-warm populates the cache such that hf_hub_download(local_files_only=True) resolves every shard
  • the real zoo _try_copy_all_from_cache copies two simulated exports fully offline (HF_HUB_OFFLINE=1) after one pre-warm
  • sharded repo (5 shards plus index): all files cached and copied offline
  • second pre-warm returns early with no download when already cached
  • partial or corrupted cache is detected and repaired by the next pre-warm
  • unreachable endpoint and nonexistent repos are swallowed, export falls back to the old path
  • HF_HUB_CACHE override resolves to the same directory on the hub side and the zoo side
  • offline env vars and UNSLOTH_PREWARM_HUB_CACHE opt out (case and whitespace variants) all skip
  • local base model directories skip
  • disk gate blocks the cache copy when free space is insufficient
  • Windows path semantics simulated via ntpath: the cache probe walk-up terminates at a drive root and the download proceeds

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 skip the 0.0GB download for sub-100MB models. Fixed in the follow-up commit, sizes below 0.1GB now print in MB.

Unsloth and others added 3 commits July 6, 2026 00:52
…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.
@Etherll Etherll self-assigned this Jul 6, 2026
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.
@danielhanchen

Copy link
Copy Markdown
Member

Pushed a follow-up (0b6aff0) hardening the cache resolution.

The pre-warm was reading huggingface_hub.constants.HF_HUB_CACHE, which is frozen at import time, while the merge (unsloth_zoo._get_hf_cache_dir -> _active_caches) reads the live environment. When HF_HOME/HF_HUB_CACHE is redirected at runtime after huggingface_hub is imported (our own redirect_hf_cache_if_readonly does this on a read-only default cache, and Studio's export path can too), the pre-warm populated one directory while the merge looked in another, so the cache-copy fast path missed and the base still re-downloaded on every export.

The fix resolves the cache the same way the merge does and threads it as cache_dir through the cached probe, the disk-space check and snapshot_download. When the resolver is unavailable it falls back to the previous behaviour, so nothing changes in the normal case.

Verified:

  • Reproduced the divergence in a real import unsloth_zoo run on a read-only default cache (frozen constants and live env pointed at different dirs).
  • End to end with a real tiny model: before the follow-up the pre-warm cached to the stale dir and the merge missed; after it, the merge copies from cache fully offline.
  • Real huggingface_hub 0.34.0, 0.36.2 and 1.22.0: local_dir leaves the cache empty and the pre-warm populates it so local_files_only=True resolves on all three.
  • Added 3 regression tests (cache_dir threading plus the redirect case) that fail without the change and pass with it. Full file: 26 passing, py_compile and enforce_kwargs_spacing clean.

danielhanchen and others added 4 commits July 6, 2026 15:37
…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.
@danielhanchen

Copy link
Copy Markdown
Member

Follow-up (418972c): pre-warm the 16bit sibling for FP8 bases.

While re-reviewing I found one gap: for a merged_16bit export of an FP8 base that has a 16bit sibling, merge_and_overwrite_lora swaps the target to the sibling and downloads that (_resolve_fp8_16bit_sibling), but the pre-warm was caching the FP8 repo. So the cache-copy fast path missed and the sibling re-downloaded on every export, plus a one-time wasted download of the unused FP8 shards. This is exactly the repeated-download workflow this PR targets, just for FP8 bases.

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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@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: 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".

Comment thread unsloth/save.py
Comment on lines +3740 to +3741
if save_method == "mxfp4" and model_name.endswith("-BF16"):
return

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 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 👍 / 👎.

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.

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.

Comment thread unsloth/save.py
Comment on lines +3784 to +3786
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)))

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 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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@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: 14bcb4979a

ℹ️ 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".

@Imagineer99

Copy link
Copy Markdown
Member

Manually tested the main case.

Log can be found here.

Trained from unsloth/llama-3.1-8b-instruct-unsloth-bnb-4bit, then exported merged 16-bit twice from the same run/base. First export downloaded/pre-cached the 16-bit base as expected. Second export reused cache (Successfully copied all 4 files from cache) and merged successfully, without repeating the ~15GB base download.

note: still saw a noisy tokenizer.model not found message, but it didn’t block export.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 7, 2026
@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: 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".

Comment thread unsloth/save.py

print(f"Unsloth: Model saved successfully to '{save_directory}'")
else:
_prewarm_base_model_hub_cache(model, save_method = save_method, token = token)

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 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 👍 / 👎.

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.

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.

Comment thread unsloth/save.py

print(f"Unsloth: Model saved successfully to '{save_directory}'")
else:
_prewarm_base_model_hub_cache(model, save_method = save_method, token = token)

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 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 👍 / 👎.

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.

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.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

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".

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 679ab01958

ℹ️ 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 af93868 into main Jul 7, 2026
51 checks passed
@danielhanchen
danielhanchen deleted the fix/export-base-model-redownload branch July 7, 2026 06:38
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.

[Question]Extremely redundant base model downloads during multiple checkpoint GGUF exports

4 participants