Skip to content

Keep the regenerable caches inside the Studio root - #10188

Closed
danielhanchen wants to merge 34 commits into
mainfrom
portable-runtime-caches-8865
Closed

danielhanchen wants to merge 34 commits into
mainfrom
portable-runtime-caches-8865

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Unsloth's own data already lives under one root, but the caches it creates along
the way do not. Torch inductor, Triton, matplotlib, numba and the CUDA JIT cache
all land in the home directory, and DataDesigner builds ~/.data-designer off
Path.home() at import time. This pins the regenerable, process-scoped ones in
every mode.

Part of #8865, which asks for an install contained in a single directory. This
half needs no new flags and helps default installs too. The installer side is in
a follow-up PR.

What moves

Added to the defaults dict in _setup_cache_env, all under the existing
cache_root():

Variable Was
TORCHINDUCTOR_CACHE_DIR /tmp/torchinductor_<user>
TRITON_HOME, TRITON_CACHE_DIR ~/.triton
TORCH_EXTENSIONS_DIR ~/.cache/torch_extensions
CUDA_CACHE_PATH ~/.nv/ComputeCache
MPLCONFIGDIR ~/.config/matplotlib and ~/.cache/matplotlib
NUMBA_CACHE_DIR ~/.cache/numba
DATA_DESIGNER_HOME, DATA_DESIGNER_MANAGED_ASSETS_PATH ~/.data-designer

DATA_DESIGNER_HOME is read at import time by
data_designer.config.utils.constants, so it has to be set before the Data
Recipes worker imports the package. The workers are spawned, so they copy this
environment and need no change.

diffusion_compile_cache.py also stops hardcoding
~/.cache/unsloth/diffusion_compile_cache. It resolves through cache_root()
per call now, and still reads a bundle from the old path when one is there, so
nobody pays a cold compile for the move alone.

Fixes ~/unsloth_compiled_cache

unsloth train / inference / export import the backend in-process and never
seeded the cache environment, so they inherited unsloth-zoo's bare relative
UNSLOTH_COMPILE_LOCATION and resolved it against whatever directory the shell
was in. Running from the home directory left an ~/unsloth_compiled_cache that
cache_cleanup then refused to remove, because nothing marked it as ours.

Seeding from ensure_studio_backend_path() covers every command that reaches the
backend, without making unsloth --help pay for importing it. unsloth studio run was already fine; it execs run.py, which seeds this itself.

What deliberately does not move

The Hugging Face hub cache stays at ~/.cache/huggingface. It was taken out of
the Unsloth tree on purpose in #4591 so that models downloaded before Unsloth was
installed, or shared with LM Studio, Ollama and plain huggingface_hub, keep
being found instead of downloaded a second time. Redirecting it unconditionally
would undo that.

HF_HOME never moves in any mode. It owns the token path, and credentials should
not follow a cache onto a removable volume.

Both of those, plus TORCH_HOME and HF_DATASETS_CACHE, move only under
UNSLOTH_HOME / UNSLOTH_PORTABLE, where the user has explicitly asked for one
self-contained directory.

Precedence

Unchanged. An explicit environment variable still wins, then the Settings
download location from #7274, then these defaults. The existing
blank-counts-as-unset guard is reused, so an inherited KEY= cannot pin a cache
to the empty string.

Tests

New studio/backend/tests/test_setup_cache_env_containment.py, 19 cases:
containment of the regenerable set, the default install leaving the shared HF
cache alone, portable-only variables staying unset by default, explicit env
beating the default, blank values, and DATA_DESIGNER_HOME being set before the
library would read it.

Existing suites: 63 passing across the cache and storage-root tests, 1114 in
unsloth_cli/tests, and 8813 across tests/python and tests/studio.

The full studio/backend/tests run was compared against the base commit rather
than counted: 288 failures on both, identical failure set, no new failures. Those
are environment gaps in the runner used here (no pytest-asyncio, so every
async def test errors, plus a diffusers version mismatch), not from this change.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-08T09:45:17.642589Z 20b2acc New commits
🔒 Security Review ✅ Completed 2026-09-03T17:03:16.425890Z ceb4ddc Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

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

ℹ️ 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 on lines +97 to +99
master = unsloth_home()
if master is not None:
return master / "studio"

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 Propagate UNSLOTH_HOME to the Hub storage roots

When this branch selects <UNSLOTH_HOME>/studio, the separate resolver in hub/utils/paths.py still ignores UNSLOTH_HOME and falls back to ~/.unsloth/studio. Hub code therefore writes download manifests and cancellation state through hub/utils/state_dir.py and local dataset uploads through hub/services/datasets/local.py outside the portable tree, while the rest of the backend reads its roots from the new location. Re-export the canonical storage-root functions from utils.paths.storage_roots or add the same precedence to the Hub resolver so portable state and datasets do not split across two installations.

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.

Checked and could not reproduce, so not changing this. studio/backend/hub/utils/paths.py does have its own resolver, but it never observes a different answer: main.py:222-224 and run.py:1326-1328 export UNSLOTH_STUDIO_HOME = str(_STUDIO_ROOT_RESOLVED) at module scope whenever the resolved root differs from legacy, which is precisely the UNSLOTH_HOME case, and every hub root function re-reads the environment at request time. Grepping the consumers, nothing outside hub/ imports the root functions at all. When UNSLOTH_HOME is ~/.unsloth both resolvers independently produce the legacy path anyway.

@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed fixes from a simulation pass over this branch. Two real defects, both found by testing rather than reading:

TRITON_HOME was pointed one level too deep. Triton composes its cache path as os.path.join(home_dir, ".triton", dirname) (triton/knobs.py:341,351, checked against the installed version, not the docs), so TRITON_HOME names the directory Triton creates .triton under, not that directory itself. Pointing it at <cache>/triton produced <cache>/triton/.triton. Contained either way, so nothing was broken, but it now matches the documented semantics. TRITON_CACHE_DIR alone would not have been enough: dump_dir and override_dir fall back to home_dir, which is the point of triton-lang/triton#4265.

Seeding built a 250 KB database on machines that had never opened Studio. Routing the CLI through setup_cache_env made it reach the Hugging Face resolver, which reads the Settings download location via get_app_setting. That opens a connection, and opening a connection creates and migrates studio.db. So unsloth train created a database purely to read one setting that could not exist yet.

The read is now skipped when nothing here uses a database: no file on disk and nothing has imported storage.studio_db. Either condition holding means a database is in play and the setting is worth reading; neither holding means there is no setting to find, so the answer is identical. The backend imports storage.studio_db at startup, so Studio is unaffected. My first attempt gated on the file alone and broke three Settings tests that patch the reader without creating a file, which is what surfaced the right condition.

New test: tests/sh/test_portable_isolated_venv.sh. Builds a uv venv containing only structlog and asserts the resolver runs there, pulls in no heavy modules (torch, transformers, huggingface_hub, fastapi), creates no database, writes nothing to $HOME, stays fast on repeat (50 seedings in 80 ms) and still resolves with no HOME set at all. Skips cleanly when uv is absent.

Verification. 324 backend cache and storage-root tests pass, including the three that caught the first attempt. A separate [Linux, macOS, Windows, WSL] x [NVIDIA, AMD, CPU] matrix confirms the resolver is hardware independent: all 12 combinations resolve byte-identically, which is what makes this safe on the AMD and CPU-only pathways as well as NVIDIA.

The CI failures showing on the previous head were cancellations, not test failures.

@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: 912024e845

ℹ️ 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_cli/_inference.py
Comment on lines +158 to +159
from utils.paths.storage_roots import setup_cache_env
setup_cache_env()

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 Isolate the compiled cache between concurrent CLI jobs

When two unsloth train, inference, or export processes run concurrently from different working directories, this new seeding routes both from their previously separate CWD-relative caches into the same <studio_root>/compiled_cache. The training and inference load/unload paths call clear_unsloth_compiled_cache() directly, while only Studio backends launched through run.py publish sibling markers and participate in the cache lock, so one CLI process can delete or rewrite generated modules while the other is compiling or still needs them. Give CLI jobs separate cache directories or enroll them in the existing liveness and locking protocol before centralizing the path.

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 changing this one. What the CLI had before this PR was unsloth_zoo's bare relative unsloth_compiled_cache resolved against the shell's CWD, which is the bug in #8865 rather than an isolation feature; two CLI jobs started from one directory already shared. After the change the CLI joins the pool the backend server and all of its workers have always shared, under the mitigations that already exist for it: clear_compiled_cache_unless_shared in cache_cleanup.py with compiled_cache_lock and the sibling probe, plus preserve_patterns on the in-process clears in trainer.py and inference.py. I could not produce a concrete wrong result. The narrower point worth a follow-up is that a CLI job publishes no liveness marker, so a Studio restart during unsloth train could clear a cache that job is using.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 28 commits September 8, 2026 08:40
studio/setup.sh and scripts/build_whisper_cpp.sh already read UNSLOTH_HOME as
the root the native runtimes sit directly under, so a shell that exports
UNSLOTH_HOME=/portable and runs the whisper builder gets /portable/whisper.cpp.
node_runtime.managed_node_dir, stt_ggml_sidecar._managed_whisper_cpp_dir and
run.py derived them from studio_root() instead, which is /portable/studio, so
the resolver looked one level too deep for a binary that was already on disk:
dictation reported the engine unavailable, the OXC validator and the Node
backed MCP commands could not find the managed runtime, and run.py pinned the
wrong llama.cpp path into UNSLOTH_LLAMA_CPP_PATH for every worker it spawned.

All three now prefer the master root when there is one. Without one they fall
through to the existing derivation unchanged, so default installs, legacy
~/.unsloth installs and plain UNSLOTH_STUDIO_HOME installs are untouched, which
tests/test_managed_tools_master_root.py pins alongside the portable and flat
layouts.
With only UNSLOTH_HOME set, the CLI resolved STUDIO_HOME to <root>/studio and
then exported UNSLOTH_LLAMA_CPP_PATH=<root>/studio/llama.cpp, while the managed
runtime lives at <root>/llama.cpp. run.py keeps a non-blank value rather than
overwriting it, so that wrong path was pinned for the server and every worker
and llama_cpp.py searched a directory that does not exist, leaving unsloth
studio run without a managed llama-server unless a system binary happened to be
on PATH.

Derive the exported path from the master root when there is one. Reproduced
before the change as CLI <root>/studio/llama.cpp against backend
<root>/llama.cpp, and the two now agree; the legacy and plain custom-root
branches are unchanged, which the two companion cases in
tests/test_unsloth_home_root_agreement.py pin.
_setup_cache_env fills each cache variable only when it is blank, so a relative
value the user set is kept verbatim, and the CLI and Tauri relocation guards
then change the working directory before it is resolved. TORCHINDUCTOR_CACHE_DIR
was already pinned for exactly that reason and TORCH_EXTENSIONS_DIR sits on the
next line of the same dict, so this was an omission rather than a boundary:
add TORCH_EXTENSIONS_DIR, TORCH_HOME, TRITON_HOME, TRITON_CACHE_DIR,
CUDA_CACHE_PATH, MPLCONFIGDIR, NUMBA_CACHE_DIR, DATA_DESIGNER_HOME and
DATA_DESIGNER_MANAGED_ASSETS_PATH to both parity lists.

The test that is supposed to catch this derived its required set from a regex
anchored on UNSLOTH_, so it only ever saw the studio-root overrides and passed
over a real gap. It now also reads the cache dict keys, which is what makes the
nine names above required rather than merely present.

Portable mode leaves HF_HOME on the host because it owns the token, and
huggingface_hub derives HF_ASSETS_CACHE as <HF_HOME>/assets, so it was the one
HF root still resolving outside the tree. Nothing in this repo calls
cached_assets_path today, so that is latent rather than observed, but it is the
same one line its three neighbours in the portable dict already get.
run.py resolves it from the master root; main.py still built it from the Studio
root, one level too deep. Under run.py the wrong value is not exported, because
main.py preserves the non-blank one, but it is still handed to
mark_managed_llama_cpp_path, so the bundled path loses its managed provenance
and reads as an immutable user override. A direct uvicorn main:app launch, which
is supported, exports the wrong directory outright and never finds the bundled
server.

Also stop warning that a flat install is not self-contained. Path.parents
excludes the path itself, so UNSLOTH_HOME and UNSLOTH_STUDIO_HOME naming one
root, which is a layout this PR supports and tests, tripped the check on every
studio_root() call, and that function is called constantly.
_find_llama_server_binary derived its search root from studio_root(), so a
portable install looked in <root>/studio/llama.cpp while run.py and main.py
export and mark <root>/llama.cpp. The managed marker makes discovery skip the
env var and fall through to its own derivation, so every GGUF model reported no
executable llama.cpp runtime installed while the server sat on disk. Resolve
from the master root when there is one, which also means a portable install is
never classified as the legacy layout.

MPLCONFIGDIR is not a cache variable. matplotlib's _get_config_or_cache_dir
returns it for get_configdir as well as get_cachedir, matplotlib_fname reads
matplotlibrc from there and style.USER_LIBRARY_PATHS globs stylelib from it, so
pinning it discarded a user's rc file and custom styles and silently changed
generated loss plots. Pin it only when that directory holds no matplotlibrc and
no stylelib entries, the same rule already applied to the Hugging Face hub
cache and to DATA_DESIGNER_HOME. Existence is not the test: matplotlib creates
the directory on import, so that would abandon containment for everyone. The
trade is a few hundred KB of regenerable font cache left in the home for the
users who have configured matplotlib, against silently rendering their plots
differently.
cache_root() is called once and that one value becomes ctx.dir, the
manifest, the save() target and the TORCHINDUCTOR_CACHE_DIR redirect.
Since nothing ever created the new default, "not default.exists()" stayed
true forever, so the legacy fallback was permanent rather than
transitional and a key the legacy cache never held still wrote its bundle
and its inductor scratch into the home directory. Grandfathering the read
was the intent; grandfathering the write was not.

cache_root() is now the write root only. A new read-only
legacy_cache_root() backs a per-key lookup in begin(), and a validated
legacy pair is copied into the write root, bundle first, so a half
migration reads as a miss rather than a hit that cannot be served. The
copy matters rather than a bare read fallback: populate_caches does not
feed _new_cache_artifacts, so a later enrichment save would otherwise
write a partial bundle into the new root that shadows the richer legacy
one. Portable mode and an explicit UNSLOTH_DIFFUSION_COMPILE_CACHE_DIR
still skip the legacy root entirely, and load-only mode reads without
migrating.
unsloth export wrapped its backend import in studio_backend_imports()
but never called ensure_studio_backend_path(), so UNSLOTH_COMPILE_LOCATION
was unset at import time. The orchestrator spawns its worker with mp
spawn, which copies the live environment and overlays only the HF cache
dict, so the worker imported unsloth with the variable unset and fell
back to unsloth_zoo's CWD-relative unsloth_compiled_cache.

Hooked the seeding into studio_backend_imports() rather than export.py:
every CLI backend import already funnels through that wrapper and
ensure_studio_backend_path() is idempotent, so no future import path can
miss it. list-checkpoints had the same gap.
TRITON_HOME is the parent of the cache, dump AND override directories,
so pinning it hid a user's ~/.triton/override kernels: with
TRITON_KERNEL_OVERRIDE=1 the run then compiles normally and produces
wrong but plausible numbers rather than erroring. Only regenerable
caches are meant to move.

knobs.py resolves dir, dump_dir and override_dir from TRITON_CACHE_DIR,
TRITON_DUMP_DIR and TRITON_OVERRIDE_DIR first and only falls back to
<TRITON_HOME>/.triton/<name>, and TRITON_HOME is read nowhere else in
the package, so the dedicated variables move everything regenerable and
leave the overrides alone. All three landed together in Triton 3.2 and
older releases read TRITON_CACHE_DIR only, so nothing regresses where
this was already fine.

Also pins matplotlib's config dir against matplotlib's own resolver.
Its macOS path is ~/.matplotlib, not Application Support: the branch
order is Linux/FreeBSD XDG, then win32 LOCALAPPDATA, then a final else
returning Path.home()/".matplotlib" for everything else. The new test
forces the darwin branch and asserts our answer equals what matplotlib
computes, so an upstream move surfaces as a failing test.
portable_mode() read every nonblank value except 0/false/off/no as
enabled, so UNSLOTH_PORTABLE=enabled, a typo like flase, or the plainly
off-meaning n and disabled all pinned TORCH_HOME, HF_DATASETS_CACHE and
HF_ASSETS_CACHE under the studio root on a tree the installer had set
up normally, reverting on the next launch without the variable.

It now reads through the same two allowlists the installers use,
1/true/yes/on and 0/false/off/no, and anything else means no opinion.
That is byte-for-byte what an off value already did: an explicit off has
always meant "decline to opt in" rather than "veto", falling through to
unsloth_home(), so a real portable root stays contained whatever the
variable says. Preserving that fall-through is what lets an unrecognized
value stop opting a normal install in without stranding a portable one,
and it composes with the on-disk marker the stacked PR adds.

The warning is one-shot per process: portable_mode() runs on every cache
lookup, so a per-call warning would be the same flood already fixed for
studio_root(). It reports the raw stripped value so someone who typed
Enabled sees what they typed.
Adding TRITON_DUMP_DIR to the portable cache defaults without adding it
here left a relative user-set value able to be retargeted by the move,
which test_cli_guard_pins_every_storage_root_override_studio_reads
caught. The Rust list in process.rs mirrors this one name for name, so
both get it.
Three defects in code this PR added, all of them cases where a resolver
answered a question freshly on every call that it should have answered
once.

DATA_DESIGNER_HOME re-ran its legacy probe each process, so a standalone
Data Designer run creating ~/.data-designer silently moved the active
root and hid recipes written under the managed home, and deleting that
directory flipped it back. The managed home is the only thing that
writes there, so its contents already are the record of the first
choice; a persistent one would have to live in studio.db, which
hf_cache_settings deliberately avoids during path resolution because
reading a setting creates and migrates the database on machines that
never opened Studio. Gated on POPULATED rather than merely existing,
since _setup_cache_env creates the directory empty on first launch, so
existence alone would let an empty folder claim a ~/.data-designer set
up afterwards. While it is empty there is nothing to strand, which
keeps the rule symmetric rather than merely reversed.

An explicit HF_HOME now keeps HF_DATASETS_CACHE and HF_ASSETS_CACHE as
well. huggingface_hub derives HF_HUB_CACHE, HF_ASSETS_CACHE and
HF_XET_CACHE from HF_HOME, and datasets derives HF_DATASETS_CACHE from
it too, with the dedicated variables only overriding, so pinning ours
split one explicitly chosen cache across two volumes. The original
reasoning for pinning HF_ASSETS_CACHE holds only when HF_HOME is the
platform default we leave behind, which is still pinned; an explicit
HF_HOME inverts that premise. Keyed off the same _EXPLICIT_CACHE_ENV
snapshot that already decides hub and xet, since by this point
initialize_hf_cache_environment has filled a blank HF_HOME.

The conflicting-root warning fired on every studio_root() call, 200 per
200 calls. Now deduped on the pair of resolved roots rather than a
single flag, so a second, genuinely different misconfiguration in the
same process is still reported.
_get_build_directory builds the py<ver>_<cuda> component inside its
"if root_extensions_directory is None" branch, so torch appends it to
the default root only and never to a value we supply. Pinning a flat
path therefore removed the ABI isolation, and two runtimes sharing one
Studio root could hand each other an incompatible .so. That structure is
identical from v1.13.1 through current main, so no supported version
behaves differently.

Nothing in Studio calls cpp_extension.load itself, but the pin is
process-wide and vLLM's pynccl allocator, PEFT BOFT and several
transformers models all JIT through it, and a Studio root outlives the
venv it was created with.

The identity is derived the way torch derives it, by reading the
generated torch/version.py through find_spec rather than importing torch
on a startup path that runs before torch exists in a fresh venv.
importlib.metadata.version is not usable here: it strips the +cu128
local segment and cannot tell a cu126 build from a cu128 one. The tag
also carries the torch version, which pytorch#68905 notes is missing
from torch's own.

The blank-counts-as-unset guard matters more than usual here, since
torch tests "is None" rather than truthiness, so an inherited blank
would give a CWD-relative build directory.
Data Designer home pinned

Two follow-ups on last round's fixes, both of which reached the same bad
state by another route.

_torch_runtime_tag parsed only __version__ while its own docstring
claimed it carried the identity torch.version.cuda is read from. Recent
PyPI Linux wheels do still write +cu128 into version.py, so that half of
the scenario does not bite, but conda-forge sets
PYTORCH_BUILD_VERSION=$PKG_VERSION with no suffix and puts the
accelerator only in the conda build string, so pytorch 2.9.1 ships as
both cpu_generic_py313 and cuda128_mkl_py313 with an identical
__version__, and two envs on one box shared a folder. ROCm is worse and
is not conda specific: version.cuda is None there, so a +rocm6.4 build
and a CPU build both resolve to cpu in torch's own naming. The tag now
comes from the generated hip/cuda/xpu/debug fields, hip first since main
prioritises ROCm, and keeps __version__ too because local segments like
+cpu.cxx11.abi mark ABI splits nothing else records. Still a plain file
read with no torch import, now asserted by a test that checks torch
never enters sys.modules.

_data_designer_in_use caught OSError and returned False, so an
unreadable managed home was indistinguishable from an empty one and the
resolver flipped to the legacy tree, which is the same flip the probe
was added to prevent. The managed-assets child case is the nastier one:
the home lists fine, the walk raises on that child, and it never reaches
the model_configs.yaml beside it that would have said in use. Only
FileNotFoundError now means unused, and on a child it is treated as a
mid-iteration race and skipped. A fresh install still defers to a
legitimate legacy directory, since an absent managed home raises
FileNotFoundError.
Four instances of one shape, three of them found by review: a probe that
decides whether the user already has data at a legacy location treated
an inspection FAILURE as absence, and redirected past it.

Measured across 3.11.14, 3.12.3, 3.13.12 and 3.14.3 rather than assumed.
Path.exists/is_file/is_dir report ENOENT, ENOTDIR, ELOOP and EBADF as
absence on all of them, and from 3.14 they are literally os.path.exists
and friends, so EACCES and EIO come back False too; the 3.14 docs say
so and point at stat() for the raising form. Path.glob suppresses the
scandir error on every supported release, in pathlib's own selectors
before 3.13 and in the shared globber after, so the matplotlib stylelib
handler was never reached at all and a chmod 000 directory full of
.mplstyle files read as empty.

The rule now lives once in _nothing_at, built on os.lstat and
os.scandir, where the only route to True is a positively observed
FileNotFoundError. lstat rather than stat deliberately: a symlink to a
volume that is not mounted yet is still something the user put there.

Two more sites the audit found and review had not reported:
_matplotlib_config_dir returned None on any inspection failure and the
caller read None as licence to pin, and it bailed on Path.home() before
consulting XDG_CONFIG_HOME, which matplotlib's own _get_xdg_config_dir
checks first.

Deliberately NOT failing closed everywhere, since that would defeat the
containment this PR exists for. Triton's cache and dump dirs are
regenerable with nothing to strand, portable mode is an explicit request
to contain everything, and an unresolvable home is not an inspection
failure but the absence of any location to hide data in, which is the
one case where pinning strands nothing and matplotlib itself falls back
to a temp dir.
The guard added in "Do not build a studio database just to read one
setting" asked Path.exists() whether a studio.db was there. From 3.14
the path predicates answer through os.path, which reports every OSError
as False, EACCES and EIO included, so a database the process merely
could not inspect read as nothing stored and the guard returned before
the real read. That silently discards the Hugging Face cache home the
user chose in Settings and routes downloads to the default or portable
root instead, and it also drops the old location out of the saved
history, since set_hf_cache_home reads the previous value through the
same function. Up to 3.13 the same case raised PermissionError, which
the surrounding handler already turned into the intended fall-through,
so this was latent until 3.14.

This is not inherited code: that guard is three commits old on this
branch, so shipping a known silent wrong answer in it is worse than the
size argument for deferring.

Ask os.stat and treat only FileNotFoundError as absence, which is what
CPython's own note on the change prescribes. stat rather than the lstat
_nothing_at uses, because the question here is whether sqlite would find
a database and sqlite follows symlinks, so a dangling link stays absent
instead of becoming a reason to open the connection that would create
the file behind it. The skip itself is unchanged, and a test pins that
an absent database is still answered without opening a connection.
main.py and run.py guarded the llama.cpp export on the Studio root
differing from ~/.unsloth/studio. A portable install pointed at that
exact path still owns its runtimes beside it, at <root>/llama.cpp, so
the equality alone skipped the export: a bare uvicorn main:app in a
fresh shell, which carries none of the installer environment, left
unsloth_zoo bound to ~/.unsloth/llama.cpp while the install had put
llama.cpp under the root. unsloth_home() already returned the right
master root, it was simply never consulted.

The guard now also fires when a master root exists. Checked against all
three layouts: flat-legacy-portable starts exporting the correct path,
nested-custom-portable is unchanged, and a plain non-portable install
still exports nothing, which the second new test pins so the widening
cannot turn into pinning a default it already resolves to.

Deliberately fixed here rather than in setup_cache_env: the skipped
block also calls mark_managed_llama_cpp_path, and exporting the variable
without that marking would classify it as a real user override and make
the path non-editable in Settings.

Computing the master root above the guard moved it out of the slice the
tests extract, which is the same hazard that has bitten the shell tests
twice, so the anchor moves with it and now asserts the guard is still
inside the slice it lifts.
huggingface_hub derives HF_XET_CACHE from HF_HOME and never from
HF_HUB_CACHE, so a user who names only a hub cache has said nothing about
where the shard and chunk caches belong. Portable mode returned early on
that override and left them in the host home, which is the one HF cache
still escaping the root: _portable_cache_defaults already pins the assets
and datasets caches on the same explicit-HF_HOME test.

HF_HOME stays the escape hatch and is never relocated.
Rewrap and shorten the comments and docstrings this branch added, dropping the
ones the code already states. The reasons a reviewer asked for stay: the
os.lstat and os.stat choices over the path predicates, the HF_XET_CACHE
derivation, why the export guard also tests the master root, and the anchor the
main.py extraction slice depends on.
run.py now imports unsloth_home at module scope beside studio_root, and this
file stubs utils.paths.storage_roots rather than importing the real one, so
the stub went stale and all 15 localhost-warning tests failed on the import
before any test body ran.

It returns None so these tests stay on the legacy-default path they were
written for. A master root would make run.py export UNSLOTH_STUDIO_HOME and
pin a llama.cpp path, neither of which this file is about.
test_selection_logic execs run.py in-process to test the localhost warning.
Once the storage_roots stub carried unsloth_home, run.py's export guard
actually ran, so it set UNSLOTH_STUDIO_HOME and UNSLOTH_LLAMA_CPP_PATH in the
pytest process and every later test in the session inherited them. That is why
the llama.cpp agreement tests read .studio-test-root/llama.cpp on CI while
passing when run alone.

Fixed at both ends. The helper now hands those two names to monkeypatch before
the exec, so the runner's real values come back at teardown. And _probe drops
UNSLOTH_LLAMA_CPP_PATH the way _main_probe already did: a test asserting on
what the CLI exports has to control that variable, or it measures the runner.
The Tauri shell hardcodes the legacy root, so its scrub list is that policy.
This PR taught the backend UNSLOTH_HOME without telling the list, and because
the name is in RELATIVE_PATH_ENV the launcher was pinning it rather than
merely leaving it: apply_managed_cli_context_inner resolved a relative value
to an absolute one and set it on the child. A shell-level portable config
moved the packaged app's databases, assets and caches, and the managed
llama.cpp, node and whisper.cpp directories with them.

UNSLOTH_PORTABLE is the same hole and was not reported. It turns portable mode
on by itself with no master root, repointing the HF hub, xet, datasets and
torch caches out of the shared user caches, so setting it in a shell meant a
silent multi-gigabyte re-download that reverted on the next launch.

start_backend now iterates the list instead of naming variables it happened to
know when it was written, so the second scrub path cannot drift from the first
again. install.rs spawn_script does not go through the managed context at all
and now applies the list too; the other five sites already inherit it.

The cache variables this PR newly seeds are left alone on purpose. Torch,
triton, numba and matplotlib read those with or without us, so removing them
would break a legitimate override rather than close a hole this PR opened.

The test derives the required names from the bodies of unsloth_home,
portable_mode and studio_root, so a fifth root variable fails on the commit
that adds it rather than the round that notices.
The check derived its required names from the body of unsloth_home, which
holds on this branch but not on the stacked one, where the env read moved into
_env_unsloth_home so unsloth_home could grow an on-disk fallback without a
cycle through studio_root. It asserted per resolver, so the split read as "no
environment variable any more" and failed a branch whose parity was intact.

Absent resolvers are skipped and the union is what has to be non-empty, so the
check holds for whichever spelling a branch carries while still failing when
the resolvers stop reading the environment altogether.
torch's own build folder is py<ver>_<cu_str> under a per-user cache directory, so
two interpreters that share a version and an accelerator share an extension
directory even when they cannot share a .so. One $HOME reaches two process
architectures without anything being moved between machines: an arm64 python and
a Rosetta x86_64 python on the same Mac agree on version_info, abiflags,
torch.__version__ and 'cpu', ninja then reads the other one's build as up to
date, and the load fails. A $HOME mounted by both an aarch64 and an x86_64 host
is the same shape.

Add sys.platform and platform.machine() to the tag. This function already widens
torch's naming wherever torch under-isolates (hip and xpu, __version__, debug),
so the host ABI belongs in it as well, and it falls back to 'unknown' rather
than an empty segment when the platform will not answer.
The probe stubbed studio, studio.backend and studio.backend.core with an empty
__path__ so the heavy studio.backend.core.export import could be replaced. But
unsloth_cli/__init__ eagerly imports commands.start, which pulls
studio.backend.utils.coding_agents, and an empty __path__ made that a
ModuleNotFoundError before the probe ever reached the assertion. The test failed
on every runner, mine included; I had wrongly filed it as pre-existing because it
also failed on an earlier commit of this same branch, which of course carries the
same test.

Point each stub at the real directory instead. Submodules load from disk while
the package __init__ files still never run, which is what kept the probe light,
and studio.backend.core.export stays stubbed in sys.modules. Removing the cache
seeding still fails both cases.
The probe sets UNSLOTH_HOME and asserts the compile cache lands under it, but it
inherits the parent process environment. UNSLOTH_STUDIO_HOME and STUDIO_HOME both
outrank UNSLOTH_HOME in the resolver, so an inherited one sent the child somewhere
the test never named. studio/backend/tests/conftest.py sets a session-scoped
UNSLOTH_STUDIO_HOME, so any run combining that directory with unsloth_cli/tests
failed here; a developer exporting either variable hit the same thing.

Before: 8 failed, 1205 passed for
  pytest studio/backend/tests/test_hf_cache_settings.py unsloth_cli/tests/
After: 6 failed, 1207 passed, matching the same command on main exactly.
@danielhanchen

Copy link
Copy Markdown
Member Author

Continued in #10597, which is the same change rebased onto current main as a single commit. This one had reached 34 commits and was getting hard to read.

The trees are identical, so nothing is lost in the move: git merge-tree of this branch against origin/main produces tree 875c65f9db1912e4d8e654fef50b3bce98842018, and #10597's single commit produces the same one. 26 files, +2838 / -43 either way.

Closing this rather than deleting it. The review history here is worth keeping, and the branch stays in place because #10189 is still based on it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant