Repository navigation
Keep the regenerable caches inside the Studio root - #10597
Conversation
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. Added to the defaults dict in _setup_cache_env, all under the existing cache_root(): TORCHINDUCTOR_CACHE_DIR (was /tmp/torchinductor_<user>), TRITON_HOME and 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), and DATA_DESIGNER_HOME with DATA_DESIGNER_MANAGED_ASSETS_PATH (~/.data-designer). DATA_DESIGNER_HOME is read at import time by data_designer's constants module, 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 and 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. 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. HF_HOME never moves in any mode either: it owns the token path, and credentials should not follow a cache onto a removable volume.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ 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 Security Review · Automatically triggeredSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
Relaxing the note check to containment in storage_roots and both uninstallers left the CLI's copy on the stricter <master>/studio match. UNSLOTH_HOME=/root with UNSLOTH_STUDIO_HOME=/root/custom/studio is a real pairing: setup records /root, the Studio directory is inside it, and it is not the default child. The backend accepts that note and the CLI declined it, so a later `unsloth studio update` passed setup no master root at all and refreshed the runtimes under the Studio directory while the backend went on loading the ones at /root. That is the same split this recovery exists to close, reopened one level up. Test: the CLI and the backend agree on a nested Studio root, in tests/test_unsloth_home_root_agreement.py. It fails with the strict rule restored.
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
Two shapes of the note were being written and then refused by every reader, so the feature recorded nothing while the file on disk said otherwise. Both were found by running the shipped setup.sh block against a fixture and handing the result to the real resolver, not by reading. Containment. setup.sh writes the note at $STUDIO_HOME/share, and STUDIO_HOME is derived only from UNSLOTH_STUDIO_HOME/STUDIO_HOME, never from UNSLOTH_HOME. Every reader requires the Studio directory to lie inside the root the note names. install.sh does not read UNSLOTH_HOME yet, so the documented case, UNSLOTH_HOME=/mnt/portable unsloth studio update on an ordinary install, leaves Studio at ~/.unsloth/studio and puts llama.cpp, node and whisper.cpp at /mnt/portable, which is exactly the shape all four readers reject. The note is now skipped there and the stranding is reported with the two ways out, instead of being recorded in a file nobody reads. The legacy default root. UNSLOTH_HOME=$HOME/.unsloth names the directory the install is already in. Both uninstallers refuse that value outright, but storage_roots honoured it, and honouring it made portable_mode() true on every later bare launch: HF_HUB_CACHE moved off ~/.cache/huggingface, which is the one cache this branch promises not to move, and every model already downloaded went missing. One command that named the default root converted the install permanently, with nothing set at the time. It is no longer recorded, and a note an earlier build left carrying it is cleared on the next run, since the writer only runs when UNSLOTH_HOME is set again and the user who hit this set it once. Also in storage_roots: - A note read that fails for a reason other than absence is no longer cached. _recorded_master_root memoises per studio path and the backend is long-lived, so an EACCES on share/ or an EIO off a mount that came back pinned that process to the legacy runtime paths for its whole lifetime, silently, with the trees it should have found beside it. Nothing in production calls forget_recorded_master_root. A genuine miss is still cached. - _usable_dir guards os.close like it already guards the unlink. Every other failure there is a False; an OSError escaping took _setup_cache_env, and the backend start that called it, down with it. - The UNSLOTH_PORTABLE warning no longer says 0/false/off/no will leave portable mode off. An off value is not a veto: a master root is what makes an install portable, as the comment three lines below already said. Tests: five new cases over the gate, the legacy-root sweep, the cached-note rule and the close guard, plus the setup.ps1 halves held structurally. 205 in test_setup_cache_env_containment and the cache suites, 356 across the master root, root agreement, workspace guard and system32 guard suites, 6710 in tests/studio/install, and all five tests/sh scripts pass; tests/studio/install matches the merge base exactly.
The skip added here reads os.stat(studio_db_path()) and treats FileNotFoundError as "no database, nothing to read". On POSIX that is sound: a parent component that is a file raises NotADirectoryError and one that cannot be traversed raises PermissionError, each its own type. Windows collapses all of them into ERROR_PATH_NOT_FOUND, which Python surfaces as FileNotFoundError, so there the exception means "absent, OR something above it is not a directory, OR I could not look" and the guard took the first reading. The result was the cache home chosen in Settings being discarded on Windows and nowhere else. This is the branch's own new test failing, not a theory: test_uninspectable_studio_db_keeps_the_stored_cache_home[not_a_directory] is green on Linux and macOS and red on windows-latest. Measured as a differential on owned staging runners, base against head, same sixteen files, same three operating systems: ubuntu-latest has no real failure on either arm, macos-15 has the same five on both, and windows-latest has 82 on the base and 83 on the head. The one extra is that test. Nothing else the branch touches moved on any of the three. _absence_is_real answers the question the skip actually needs: the nearest ancestor that can be stat'ed decides. A directory means the tree is real and the file genuinely is not in it. Anything else means a component is a file or a reparse point, so the path could never have existed and the caller has learned nothing. An ancestor that cannot be inspected at all is not proof either way. Running out of ancestors means nothing on the path exists, which is the machine that has never opened Studio, and the skip has to hold there or the read builds the 250 KB database it was added to avoid. Checking only the immediate parent is not enough: account_path puts studio.db several levels under the Studio home, so the non-directory is usually further up. Held by a test that reproduces the Windows error shape rather than the platform, since the Linux runners cannot raise it, plus its opposite, an absent Studio home that must still skip. The first fails on the code as it was and passes after, so it measures the fix rather than restating it. 207 pass in the cache suites, 365 with 1 skipped across the master root, root agreement, workspace guard and system32 guard suites, 6754 with 32 skipped in tests/studio/install, 2 in the CLI export suite.
errno is used only inside _WINDOWS_SHAPED_GUARD_PROBE, which is a string run in a subprocess and imports it itself. The hoisted import was unused at module level and the source lint blocks on exactly that.
|
Simulated this branch end to end rather than reading it, on this Linux host and on owned staging runners for Windows and Apple Silicon macOS. Four defects, all reproduced first and then fixed on the branch. Three of them were invisible to the suites as written. issue: REAL | PR as submitted: DEFECTIVE, 4 fixed here | merge: YES Caches really did land in the home directory, and What moved
The two the readers were refusing
Cross-platform, base against headBoth arms on owned staging runners, same sixteen files, same three operating systems.
The macOS five and the Windows eighty-two are identical on both arms and are all pre-existing tests in code this branch does not touch. The single extra on Windows was The three failing checks were not from this branch
Correction to the description aboveThe description says Not settled
|
…iter Found by enumerating the resolver's input space rather than reading it: 512 cells over UNSLOTH_STUDIO_HOME x STUDIO_HOME x UNSLOTH_HOME x UNSLOTH_PORTABLE x the recorded note, base against head, one subprocess per cell. In 12 of them the Hugging Face hub cache still moved off ~/.cache/huggingface with nothing set in the process at all. The write side was already gated: setup.sh and setup.ps1 refuse to record $HOME/.unsloth and sweep an old note away. But that only fires when setup runs again, and the user who hit this set UNSLOTH_HOME once, for one command. Until the reader declines it too the repair never reaches them, and both uninstallers were meanwhile refusing the same value outright, so the four readers the branch claims to keep aligned were not. _is_legacy_default_root declines it in storage_roots, and the CLI copy gets the identical rule, which is what test_unsloth_home_root_agreement.py holds. Recorded roots only: unsloth_home() returns an explicit UNSLOTH_HOME before it ever reads the note, and narrowing that would change what the variable means rather than what a stale file is allowed to claim. Re-run over the same 512 cells: root resolution 480 identical and 32 changed, which is the new UNSLOTH_HOME feature, with 0 violations; HF_HOME moves in 0 cells; of the 192 cells with no UNSLOTH_HOME and no UNSLOTH_PORTABLE, the caches move in 30 and all 30 carry a real recorded master root. Legacy-root notes: 12 before, 0 now. Foreign notes: 0 throughout. Also closes a gap in this file's own tests. Reverting the production hunks and keeping the tests left 25 of 113 containment tests green, because each asserts only that some variable is ABSENT, which is equally true when no pinning code exists: assertions, not negative controls. Three new cases pair each decline with the pins that must still happen in the same run, so the family fails when the resolver does nothing. All five new tests fail with the production hunks reverted and pass here. 119 pass in the containment suite, 147 across it plus the root agreement and managed tools suites.
The comment beside each read said "One line, first only: a note that grew a second line is not one we wrote", and neither did that. uninstall.sh took `head -n 1` and carried on; uninstall.ps1 took `Get-Content -TotalCount 1`. The second line was never looked for. That is the four readers disagreeing in the one place it costs something. storage_roots.py and unsloth_cli/commands/studio.py both read_text().strip() the WHOLE file, so a two-line note is not a directory to them and they decline it. The two uninstallers accepted line 1 and went on to authorise removing <master>/llama.cpp, node, whisper.cpp and stable-diffusion.cpp for a master root no runtime reader had agreed to. Measured on the fixture, all four readers, one note: storage_roots.unsloth_home() -> None CLI _recorded_master_root() -> None uninstall.sh _master_root() -> /<master> <- authorises the delete uninstall.ps1 _MasterRoot -> same shape Both now refuse when a second non-blank line is present, which is what the comments already promised. A trailing newline on an ordinary note is not a second line, and the one-line note keeps working -- both are asserted, so the refusal cannot pass by reading nothing. Found by the release-safety fan-out over the install and uninstall paths, then reproduced against the shipped helpers rather than taken on report. tests/sh/test_uninstall_master_root.sh grows three cases and runs the real extracted block: 45 pass here, and the two-line case fails against uninstall.sh exactly as submitted in this PR. The PowerShell half is held structurally, as the rest of that file's Windows coverage is.
Move-Item -Force is not an atomic replace. PowerShell's filesystem provider deletes the destination and then moves the source, so an interruption between the two leaves NO note at all, while the complete staging file sits beside it unreferenced. A backend that looks next reads "no master root" and, since the miss is cached, keeps that answer for its whole lifetime. The window cannot be removed under Windows PowerShell 5.1, which has no atomic replace primitive this code can reach. What can be removed is re-entering it on every single update to write bytes that are already there, which is every run after the first. The note is compared first and the write skipped when it matches, and the staging file is now cleared in a finally rather than left behind when the move throws. Two tests, and the second one took two attempts to make honest: the first version compared LastWriteTime across two runs a millisecond apart, which can land on one filesystem tick, and it passed against the unfixed writer. It back-dates the note instead, so any rewrite is unmistakable, and then changes the value to prove the writer still writes when it should. Both fail against setup.ps1 exactly as submitted in this PR and pass here. Found by the release-safety fan-out over idempotency and interrupted runs, then reproduced against the shipped block under pwsh rather than taken on report. 43 pass in test_setup_master_root, 176 across it plus the containment, root agreement and managed tools suites, and 45 in tests/sh/test_uninstall_master_root.sh.
_nothing_at's docstring is explicit that Path.exists and is_dir must not be used because they report ENOTDIR and ELOOP as absence and the redirect would then hide the user's files. It then took FileNotFoundError at face value, which is the same reading restricted to one platform: POSIX distinguishes "not there" from "a parent component is a file" (NotADirectoryError) and "I may not traverse it" (PermissionError), while Windows collapses all three into ERROR_PATH_NOT_FOUND. So with a file where ~/.matplotlib belongs, POSIX declined the pin and Windows took it, moving MPLCONFIGDIR for the whole process and hiding whatever was underneath. Same defect and same cause as the studio.db guard fixed in 37f23c5, in a second probe, and _nothing_above is the same rule: the nearest ancestor that can be stat'ed decides, a directory means real absence, anything else means the path could never have existed, an uninspectable ancestor proves nothing, and no ancestors at all is the default install and is real absence. Found by the windows-latest staging leg, on a negative control written for the POSIX shape and added earlier in this review. base arm 82 real failures, head 83, the one extra being that test. It is the only new failure on any of the three operating systems. Held by a test that reproduces the error shape rather than the platform, since the Linux runners cannot raise it, with both opposite cases asserted so the fix cannot pass by declining everything: a genuinely empty present directory still reads as empty, and a path with nothing along it is still absence. It fails against storage_roots.py exactly as submitted in this PR. 584 pass with 1 skipped across the eleven suites this branch touches.
|
Ran the full simulation workflow over this branch. Both gates, the twelve steps, and a base arm for every differential. It found four defects beyond the four in my earlier pass, all reproduced before being fixed, all now on the branch. #10597 | issue: REAL | PR as submitted: DEFECTIVE, 8 fixed by me | merge: YES Unsloth's own data already lived under one directory, but the caches its toolchain builds along the way did not, and Before and after, one row per behaviour
Gate A, is the PR realREAL. 574 lines inside changed files execute on the reported path, traced not read: 16 of 16 new resolver functions are hit by One thing that survived the revert is worth naming. 25 of 113 containment tests still passed, because each asserts only that a variable is absent, which is equally true when no pinning code exists. Assertions, not negative controls. Three falsifiable ones added; all five new controls fail on the revert. Gate BB1 inference. Nothing the diff adds sits in a per-token or per-layer path: 12 changed production files, 0 hot-path functions. Measured anyway, 9 repeats a side, Qwen3-0.6B bf16, batch 4, prompt 512, 128 new tokens, greedy, seed 0: prefill +2.06%, decode +0.79%, ttft -2.02%, peak memory +0.00%, against a base spread of 17.9% / 12.5% / 18.8%. Every delta inside the band, logits checksum identical across arms. B2 GPU detection. No detection code is touched. The only accelerator-aware code added, B3 security and sandbox. No system prompt, chat template or sandbox policy in the diff. Both guards strictly widen, Enumeration, 512 routing cells
Cross-platform, base arm against head, same 16 files
The 33 errors on each arm are For you to weigh, not changed on the branch
What I could not prove
Adversarial pass, found nothing further
|
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
…iscovery seeding caches Three fixes found while auditing what happens to an existing install. A note left at <studio>/share/.unsloth-master-root that names the legacy tree itself passed every containment check, so a bare environment resolved a master root and the uninstaller then treated a second marked install under it as a root to remove. Both uninstallers and both setup scripts now decline a note whose directory is the legacy Studio dir. A staged update derived the runtime ownership flag from the master root, so a staging pass could mark runtimes custom when they were still legacy. The flag is now assigned only when no stage root is in play, and follows where the runtimes actually land. Node tool discovery imported the Studio backend path purely to find the bundled tools and built the whole compiler cache tree as a side effect. The import now takes a seed_cache_env flag and the discovery path opts out. Each fix has a regression test checked against the unfixed code.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 76e04c5feb
ℹ️ 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".
| # exports UNSLOTH_STUDIO_HOME=<root>/studio beside it, so taking that one would install a level | ||
| # below where stt_ggml_sidecar._managed_whisper_cpp_dir() looks. | ||
| _STUDIO_HOME_ALIAS="${STUDIO_HOME:-}" # read before the name below is reassigned | ||
| STUDIO_HOME="$(_root_value "${UNSLOTH_HOME:-}")" |
There was a problem hiding this comment.
Absolutize relative master roots in the whisper builder
When the advertised standalone builder is run with a relative value such as UNSLOTH_HOME=portable ./scripts/build_whisper_cpp.sh, this assignment leaves the root relative and installs under the caller's current directory. The Python resolver now applies Path.resolve() when it later reads the same variable, so a backend launched from another working directory searches a different portable/whisper.cpp and reports dictation unavailable. Normalize a relative UNSLOTH_HOME against the builder's initial working directory, as studio/setup.sh does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The divergence is real but this change does not cure it, so I am leaving the builder as it is.
The builder never changes directory, so INSTALL_DIR names the same directory whether or not it is absolutized. Ran the real script both ways with stub git and cmake, from the same working directory, with UNSLOTH_HOME=portable:
base ==> Installed portable/whisper.cpp/build/bin/whisper-server
patched ==> Installed <cwd>/portable/whisper.cpp/build/bin/whisper-server
both ./portable/whisper.cpp/build/bin/whisper-server
Same tree, same marker, same clone. Only the log line differs.
The failure you describe is caused by the variable itself being relative, not by where the builder resolves it: the backend re-reads UNSLOTH_HOME and applies Path.resolve() against its OWN working directory, so it still misses an install made from anywhere else. Measured, builder run in a/ and backend started in b/:
builder INSTALL_DIR : <root>/a/portable/whisper.cpp
backend looks in : <root>/b/portable/whisper.cpp
Absolutizing inside the builder leaves that second line exactly where it was. setup.sh absolutizes for a different reason that does apply there: it picks node before its first cd "$SCRIPT_DIR" and llama.cpp after it, so a relative value would name two different directories within one run.
Worth pinning down properly rather than papering over, and a relative master root is on the list of things to settle before UNSLOTH_HOME is documented.
Replaces #10188, which had grown to 34 commits. Same change, rebased onto current main as a single commit.
The squashed tree is byte-identical to what merging #10188 would have produced:
git merge-treeof that branch againstorigin/maingives tree875c65f9db1912e4d8e654fef50b3bce98842018, and so did this branch's first commit. The review history, including everything Codex raised and the replies, stays readable on #10188. Since then this branch has picked up a merge of current main and a comment-tightening pass.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-designeroffPath.home()at import time. This pins the regenerable, process-scoped ones inevery 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 flags
(
--root,--portable) are in a follow-up PR; what this branch adds tostudio/setup.shandstudio/setup.ps1is only the root derivation the runtimeresolvers below need to agree with.
What moves
Added to the
defaultsdict in_setup_cache_env, all under the existingcache_root():TORCHINDUCTOR_CACHE_DIR/tmp/torchinductor_<user>TRITON_CACHE_DIR,TRITON_DUMP_DIR~/.triton/cache,~/.triton/dumpTORCH_EXTENSIONS_DIR~/.cache/torch_extensionsCUDA_CACHE_PATH~/.nv/ComputeCacheMPLCONFIGDIR~/.config/matplotliband~/.cache/matplotlibNUMBA_CACHE_DIR~/.cache/numbaDATA_DESIGNER_HOME,DATA_DESIGNER_MANAGED_ASSETS_PATH~/.data-designerTRITON_HOMEis deliberately not one of them. It is the single lever that wouldmove all three Triton directories at once, and the third is
~/.triton/override,which holds hand-written kernels rather than a cache. Moving it would make a
TRITON_KERNEL_OVERRIDE=1run silently compile something else. The two dedicatedvariables outrank the
TRITON_HOMEderivation, so they move what is regenerableand leave the overrides alone. A user who sets
TRITON_HOMEthemselves gets nopin at all.
TORCH_EXTENSIONS_DIRgets apy<ver>_<platform-arch>_<accelerator>_<version>child rather than a flat path.
torch.utils.cpp_extensioninserts its ownpy<ver>_<accelerator>folder into the default root only, never into one wesupply, so a flat pin would let a py313/cu128 build be loaded by a py312/cu126
process.
DATA_DESIGNER_HOMEis read at import time bydata_designer.config.utils.constants, so it has to be set before the DataRecipes worker imports the package. The workers are spawned, so they copy this
environment and need no change.
Each of these is skipped when the directory it would displace already holds user
files: a
matplotlibrcor astylelib/*.mplstyle, or a~/.data-designerthatalready exists. The probes go through
os.lstatandos.scandirrather thanPath.exists/is_dir/glob, which report ENOTDIR, ELOOP and (from 3.14) EACCESas absence, so a directory that merely cannot be inspected would have read as
empty and the redirect would have hidden the files under it.
diffusion_compile_cache.pyalso stops hardcoding~/.cache/unsloth/diffusion_compile_cache. It resolves throughcache_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. A bundle found there is copied
into the new root, so the fallback does not become permanent and the home
directory never becomes the write root.
UNSLOTH_HOMEandUNSLOTH_PORTABLEstorage_roots.pygrows two resolvers.unsloth_home()readsUNSLOTH_HOME,the master root that
STUDIO_HOMEis thestudio/child of, and slots intostudio_root()belowUNSLOTH_STUDIO_HOME/STUDIO_HOMEand above thesys.prefixinference.portable_mode()is implied by a master root and canalso be turned on by itself with
UNSLOTH_PORTABLE.llama.cpp,nodeandwhisper.cppare siblings ofstudio/at the masterroot, which is the layout
studio/setup.shandscripts/build_whisper_cpp.shalready install into.
node_runtime,stt_ggml_sidecar,LlamaCppBackend._resolved_studio_root_and_is_legacy,run.py,main.pyandunsloth_cli/commands/studio.pyall derive from the master root when there isone, so discovery and the exported
UNSLOTH_LLAMA_CPP_PATHname the samedirectory.
main.pyandrun.pyalso had to stop gating that export onresolved != legacyalone: a master root pointed at the legacy path still ownsthe runtimes beside it.
studio/setup.shandstudio/setup.ps1install the runtimes at the same root.They previously derived that parent from the Studio home alone, and the CLI
exports
UNSLOTH_STUDIO_HOME=<root>/studiobefore running them, so with a masterroot set they installed
llama.cpp,nodeandwhisper.cppone level belowwhere the resolvers look and no GGUF model, managed Node or dictation engine
would be found.
setup.shnow captures the environment value as_MASTER_ROOTbefore section 7 assigns over the name, and
setup.ps1getsGet-MasterRootOverride.scripts/build_whisper_cpp.shhad the same problem onelevel down: it ranked
UNSLOTH_STUDIO_HOMEabove theUNSLOTH_HOMEsetup.shpasses it, so the source-build fallback installed under
<root>/studio. Allthree strip, expand
~, and resolve a relative value against the caller beforedeciding, matching
Path.resolve(), since Node is chosen before setup.sh's firstcd "$SCRIPT_DIR"and llama.cpp after it. An explicitUNSLOTH_STUDIO_STAGE_ROOTstill outranks the master root, and nothing changeswithout
UNSLOTH_HOMEset.The ownership guards follow them.
_STUDIO_HOME_IS_CUSTOMis false when onlyUNSLOTH_HOMEis set, sinceSTUDIO_HOMEstays legacy, and false is what letsinstall_llama_prebuilt.pyos.replace()and the source buildrm -rfwithoutchecking the Unsloth-owned marker.
setup.shderives_RUNTIME_ROOT_IS_CUSTOMand
setup.ps1$RuntimeRootIsCustomfor exactly the guards that name a runtimechild; the Studio home and its venvs keep the original flag.
install.ps1holdsbyte-identical copies of the shared llama.cpp helpers, so those moved too.
scripts/uninstall.shandscripts/uninstall.ps1learn the same root, or aninstall would strand multi-gigabyte trees. Stricter than the
~/.unslothremovals beside them:
<master>is user-chosen, sollama.cpp,node,whisper.cppandstable-diffusion.cppgo only when they carry.unsloth-studio-owned, an unmarked tree is reported and kept, the root passesthe deny list first, and it is itself removed only once the children leave it
empty.
On the desktop side,
UNSLOTH_HOMEandUNSLOTH_PORTABLEjoinMANAGED_CHILD_SCRUBBED_ENV, so an inherited shell value cannot move thepackaged app's databases and caches, and
install.rsnow reads that list insteadof naming two variables of its own. Both also join the relative-path guard in
_system_dir_guard.pyand its Rust twin, together with the new cache variables:storage_roots.pyfills those only when blank, so a relative value the user setsurvives and would name a different folder after a move.
What deliberately does not move
The Hugging Face hub cache stays at
~/.cache/huggingface. It was taken out ofthe Unsloth tree on purpose in #4591 so that models downloaded before Unsloth was
installed, or shared with LM Studio, Ollama and plain
huggingface_hub, keepbeing found instead of downloaded a second time. Redirecting it unconditionally
would undo that.
HF_HOMEnever moves in any mode. It owns the token path, and credentials shouldnot follow a cache onto a removable volume.
HF_HUB_CACHE,HF_XET_CACHE,HF_DATASETS_CACHE,HF_ASSETS_CACHE,HF_MODULES_CACHEandTORCH_HOMEmove only underUNSLOTH_HOME/UNSLOTH_PORTABLE, where the user has explicitly asked for one self-containeddirectory. Xet is included because
huggingface_hubderives it fromHF_HOMEand never from
HF_HUB_CACHE, so a hub-only redirect would leave the chunk andshard caches on the host. Modules for the same reason:
transformers.utils.hubreads
HF_MODULES_CACHEfrom<HF_HOME>/modulesat import and appends it tosys.path, so atrust_remote_codeload would otherwise leave generated moduleson the host. A user who names their own
HF_HOMEkeeps one Hugging Face cache:only
TORCH_HOMEis pinned then, since the rest derive from the home theychose.
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 cacheto the empty string.
Tests
New
studio/backend/tests/test_setup_cache_env_containment.py, 94 cases:containment of the regenerable set, the "pin only when nothing is stranded" rule
for matplotlib and Data Designer including the inspection-failure paths, the
TORCH_EXTENSIONS_DIRtag, the default install leaving the shared HF cachealone, portable-only variables staying unset by default, explicit env beating the
default, blank values, and
DATA_DESIGNER_HOMEbeing set before the librarywould read it.
New
tests/test_unsloth_home_root_agreement.pyandtests/test_managed_tools_master_root.pyhold the CLI and the backend to the sameanswer for a master root, and
tests/test_studio_install_workspace_guard.pyholds the scrub list against the resolvers that read the environment, so a new
root variable cannot be honoured by the backend and missed by the desktop.
unsloth_cli/tests/test_export_cache_env.pycovers theexport/list-checkpointspath that reaches the backend withoutensure_studio_backend_path().tests/test_setup_master_root.pyruns theshipped
setup.shandbuild_whisper_cpp.shderivations rather thanpattern-matching them, across master root, plain custom Studio home, legacy
default, staging root, and padded, blank, tilde and relative values, and holds
the ownership flag and both uninstallers;
tests/sh/test_uninstall_master_root.shruns the real uninstall block against fixtures, including the cases where a tree
must be kept. The
setup.ps1anduninstall.ps1halves that need a realWindows filesystem are held structurally; where
pwshis on PATH, which it is onthe Linux runners, the PowerShell arms execute rather than skip.
Run here: 166 passing across
test_setup_cache_env_containment.py,test_setup_cache_env_hf_home.py,test_diffusion_compile_cache.pyandtest_hf_cache_settings.py; 519 passing and 18 skipped acrosstest_managed_tools_master_root.py,test_unsloth_home_root_agreement.py,test_studio_install_workspace_guard.py,test_installer_system32_guard.py,test_setup_master_root.py,tests/studio/install/test_selection_logic.pyandunsloth_cli/tests/test_export_cache_env.py.tests/test_studio_root_resilience.pypasses standalone on both revisions, 6 onthe merge base and 7 here. An earlier version of this section claimed two
failures there caused by the file not putting
studio/backendonsys.path;that guard is present and identical on both, added by
7f6219e3a, an ancestor ofthe merge base.
Fixes
~/unsloth_compiled_cacheunsloth train/inference/exportimport the backend in-process and neverseeded the cache environment, so they inherited unsloth-zoo's bare relative
UNSLOTH_COMPILE_LOCATIONand resolved it against whatever directory the shellwas in. Running from the home directory left an
~/unsloth_compiled_cachethatcache_cleanupthen refused to remove, because nothing marked it as ours.Seeding from
ensure_studio_backend_path()covers every command that reaches thebackend, without making
unsloth --helppay for importing it.exportandlist-checkpointsdo not call it, sostudio_backend_imports()seeds there too.unsloth studio runwas already fine; it execsrun.py, which seeds this itself.What this changes for an install that already exists
Verified by running the real resolver in both trees under
env -iwith synthetic homes, acrosssixteen install shapes, and diffing every resolved path and every variable
setup_cache_envexports. In all ten non-portable shapes, which is every install anyone has today, no path moves
and no existing environment value changes:
~/.unsloth/studioalready on diskUNSLOTH_STUDIO_HOME, andSTUDIO_HOMEHF_HOME,HF_HUB_CACHE,UV_CACHE_DIR,TORCH_HOME,TRITON_CACHE_DIRXDG_CACHE_HOMEandXDG_DATA_HOMErelocatedv0.1.701-betadesktop install leaves behindstudio_root,studio.db, the auth root andauth.db, assets, datasets, outputs, exports, theprojects root and the Documents root are identical on both sides in every one of them. Login,
shortcuts and the desktop self-update path are untouched:
install.shand.github/workflows/release-desktop.ymlare not in this diff at all.What does change, and it is the point of the PR, is that the eight variables in the table above
are now set where they were previously unset. The cost is a one-time cold recompile; the old
caches stay on disk rather than being moved or deleted.
unsloth train,inferenceandexportalso seed the cache environment now, which is the fix for
~/unsloth_compiled_cache, so thosecommands create the cache directories on first run where before they created none.
The Hugging Face model caches do not move by default. That was deliberate in #4591 and stays
that way; they move only under an explicit portable root.
Not pinned into a path that contains a space
torch/_inductor/cpp_builder.pyjoins its arguments with spaces, interpolates the output pathunquoted, and reparses the result with
shlex.split, so a cache directory containing a spacesplits mid-path and the C++ build fails outright:
Nothing here can fix that quoting, so the five variables a C++ or CUDA toolchain receives on a
command line are left unset when the resolved path has whitespace, and Inductor falls back to its
own whitespace-free temporary directory, which is what shipped before any of this was pinned.
The rest of the caches still move, and an explicit value from the caller is always honoured.
This is not an exotic path: the default Studio root hangs off the profile directory, and
C:\Users\First Lastis an ordinary Windows account name.Known limitation:
UNSLOTH_HOMEis not yet end to endThe resolvers, the CLI, both setup scripts and both uninstallers agree on the master root, and a
later launch now recovers it:
unsloth_home()falls back to theshare/.unsloth-master-rootnote setup writes, so node, whisper.cpp and llama.cpp are still found beside
studio/once theUNSLOTH_HOME=... unsloth studio updatecommand's environment is gone. Before that, even acorrectly known studio root sent all three to its
studio/child, one level off from where theinstaller had put them.
The outer installers still do not read the variable, so setting
UNSLOTH_HOMEon its own is nota working flow end to end:
install.shplaces Studio at~/.unsloth/studiowhile the CLIresolves
<master>/studioand reports that Studio is not set up, and given an explicitUNSLOTH_STUDIO_HOME=<master>/studiothe POSIX launcher writesUNSLOTH_LLAMA_CPP_PATH=<master>/studio/llama.cppwhile setup installs at<master>/llama.cpp.That variable is explicit, so it outranks the note.
That half belongs to the follow-up PR that adds
--rootand--portable. Nothing here changesbehaviour for anyone who does not set the variable, and no installer sets it. The note is written
only for a master-root install, so a default tree acquires no root by accident.
What this changes on screen
Settings > System > Storage, the "Models folder" row. It is the only place a user ever sees
where downloaded models live, and it renders
cache_homestraight fromGET /api/settings/hugging-face-cache, so it is where this PR's effect on the Hugging Facecache becomes visible.
Two isolated installs, merge base
5f00349e7on the left and headed04cb31aon the right,photographed by one scene driven against both.
UNSLOTH_PORTABLE=1is set on BOTH sides, andHF_HOME,HF_HUB_CACHE,HF_XET_CACHEand friends are cleared on both: the merge base has nosuch variable, so it reads the platform default and the row is unchanged there, which is the
point. An explicit cache home is the one case where this PR deliberately declines to move
anything, so an inherited value would have made the right side correctly show no change.
The input ellipsises a long path, so both halves render only its first ~34 characters and the
picture cannot carry the claim on its own. The full values, read from the same servers that were
photographed:
/mnt/disks/unslothai/daniel1/.cache/huggingface<studio home>/cache/huggingfacecache_home/mnt/disks/unslothai/daniel1/.cache/huggingface<studio home>/cache/huggingfacehub_cache.../.cache/huggingface/hub<studio home>/cache/huggingface/hubxet_cache.../.cache/huggingface/xet<studio home>/cache/huggingface/xetsourcedefaultdefaultis_customfalsefalsesourceandis_customdo not move, which is the part worth checking: the cache is relocated bythe portable default, not by pretending the user set it. Everything else on the page, the disk
figures, the Environment table, the llama.cpp rows, is identical across the pair, which is what
makes it a pair rather than two pictures.
The pair was taken at
ed04cb31a. The three review fixes pushed since then touch_usable_dir,which gates only the six compile-cache variables in
_TOOLCHAIN_PATH_KEYS, plusuninstall.shand
setup.ps1. No Hugging Face variable passes through any of them, so this row has not moved.Review pass
A simulation pass over this branch found four defects, each reproduced before
being fixed, and all four are now on it:
setup.shwrites it at$STUDIO_HOME/share, andSTUDIO_HOMEnever derives fromUNSLOTH_HOME, so the documentedUNSLOTH_HOME=/mnt/portable unsloth studio updateon an ordinary install recorded a root all four readers then rejected. And the legacy
default:
UNSLOTH_HOME=$HOME/.unslothis refused by both uninstallers but was honouredby
storage_roots, so one command naming the directory the install was already inflipped
portable_mode()on for every later bare launch and movedHF_HUB_CACHEoff~/.cache/huggingface. Neither is recorded now, an old note carrying the legacy root iscleared on the next run, and the stranded-runtime case prints what happened.
_stored_cache_hometreatedFileNotFoundErroras proof the database is absent. POSIXraises
NotADirectoryErrorfor a parent that is a file; Windows collapses that intoFileNotFoundError, so the cache home chosen in Settings was discarded on Windows andnowhere else. This branch's own
test_uninspectable_studio_db_keeps_the_stored_cache_home[not_a_directory]was red onwindows-latestand green everywhere else._recorded_master_rootcached a note read that failed for a reason other than absence,so an EACCES on
share/pinned a long-lived backend to the legacy runtime paths for itswhole lifetime.
forget_recorded_master_root()has no callers in production._usable_dirleftos.closeunguarded, and theUNSLOTH_PORTABLEwarning promised thatan off value would leave portable mode off, which a master root overrides.
Differential across three operating systems, base against head, same sixteen files:
ubuntu-latest0 real failures on both arms,macos-15the same 5 on both, andwindows-latest82 on both once the guard above is fixed. The three checks that were redon the previous head were all failing on
mainin the same window and are unrelated to thisbranch.
What this changes in the UI
Settings, System tab, Storage section, on two installs built from this branch's merge base
(
04c9951b4) and its head (2b61d6059), both launched withUNSLOTH_HOMEpointing at a masterroot and with every ambient
HF_*variable cleared:Models foldermoves from the host cache to the install:/api/settings/hugging-face-cachecache_home<XDG_CACHE_HOME>/huggingface<install>/cache/huggingfacehub_cache<XDG_CACHE_HOME>/huggingface/hub<install>/cache/huggingface/hubxet_cache<XDG_CACHE_HOME>/huggingface/xet<install>/cache/huggingface/xetsourcedefaultdefaultsourcestayingdefaultis the part worth checking: the relocation does not present itself asan environment override, so the field stays editable and Settings can still move it. Without a
master root both sides are identical, which is the intended no-op for an ordinary install.
The screenshots were taken at
2b61d6059. They still describe the current head: the only twofiles behind that panel,
studio/backend/utils/hf_cache_settings.pyandstudio/backend/utils/paths/storage_roots.py, are AST-identical between that commit and thehead (comments and docstrings only), and nothing else under
studio/changed in between.