Repository navigation
perf(fast): torch.compile's cache in ~/.cache/basal/torchinductor (starts after a reboot reuse the compiled code) - #47
Conversation
…t under /tmp Inductor keeps its compiled graphs (and the Triton kernels under them) in /tmp/torchinductor_<user> by default, which a reboot empties on most systems, so the first start after one compiled every forward again. The graph engine now sets TORCHINDUCTOR_CACHE_DIR to ~/.cache/basal/torchinductor unless it is set, as --mode tpu keeps JAX's cache in ~/.cache/basal/jax.
… written its /tmp default Importing transformers' models already makes Inductor write its default (/tmp/torchinductor_<user>) into TORCHINDUCTOR_CACHE_DIR, so the check for a value the user set took that for one and the cache stayed under /tmp. That value now counts as not set, and Inductor's memoised paths are cleared after the switch (as its temporary_cache_dir does). INSTALL.md: where the cache lives.
Reviewer's GuideFast-mode graph backends now redirect Inductor’s ephemeral default cache to ~/.cache/basal/torchinductor before compilation, allowing compiled graphs and Triton kernels to be reused after reboots while respecting explicit user paths; documentation, release notes, and regression coverage describe and verify the behavior. Sequence diagram for persistent torch.compile cache initializationsequenceDiagram
participant Backend as GraphBackend
participant Cache as persist_compile_cache
participant Inductor as TorchInductor
participant Disk as PersistentCache
Backend->>Cache: persist_compile_cache()
Cache->>Inductor: default_cache_dir()
alt User cache directory is explicitly set
Cache-->>Backend: Keep existing TORCHINDUCTOR_CACHE_DIR
else Default or Inductor temporary directory is detected
Cache->>Disk: mkdir ~/.cache/basal/torchinductor
Cache->>Inductor: clear_caches()
Cache-->>Backend: Set TORCHINDUCTOR_CACHE_DIR
end
Backend->>Inductor: torch.compile()
Inductor->>Disk: Read or write compiled graphs and Triton kernels
Flow diagram for fast-mode cache reuse after rebootflowchart LR
Start[Fast-mode backend starts] --> Configure["persist_compile_cache()"]
Configure --> Cache[~/.cache/basal/torchinductor]
Cache --> Compile[torch.compile uses cached graphs and kernels]
Compile --> Ready[Fast-mode service becomes ready]
Reboot[System reboot] --> Cache
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 6 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="basal/engine.py" line_range="463-466" />
<code_context>
+ return
+ path = Path.home() / ".cache" / "basal" / "torchinductor"
+ try:
+ path.mkdir(parents=True, exist_ok=True)
+ except OSError:
+ return
+ os.environ["TORCHINDUCTOR_CACHE_DIR"] = str(path)
+ from torch._inductor.utils import clear_caches
+ clear_caches()
</code_context>
<issue_to_address>
**Compilation fails on unwritable cache**
When the home cache directory already exists but the serving process cannot write to it, `path.mkdir(parents=True, exist_ok=True)` succeeds, so `persist_compile_cache()` assigns the unwritable path to `TORCHINDUCTOR_CACHE_DIR`; Inductor’s later cache writes fail during compilation and the server does not start.
Verify the directory is writable before assigning it to `TORCHINDUCTOR_CACHE_DIR`, and keep the prior cache configuration if it is not.
</issue_to_address>
### Comment 2
<location path="basal/engine.py" line_range="458-460" />
<code_context>
+ (importing transformers' models already asks), so that value counts as not set; the paths Inductor memoised are
+ cleared after the switch, as its temporary_cache_dir does. Left as it is when the directory cannot be created."""
+ from torch._inductor.runtime.cache_dir_utils import default_cache_dir
+ set_to = os.environ.get("TORCHINDUCTOR_CACHE_DIR")
+ if set_to and os.path.abspath(set_to) != os.path.abspath(default_cache_dir()):
+ return
+ path = Path.home() / ".cache" / "basal" / "torchinductor"
+ try:
</code_context>
<issue_to_address>
**Backend construction aborts without home**
When the home directory cannot be resolved, or `default_cache_dir()` cannot resolve the account, `Path.home()` or `default_cache_dir()` raises before the directory-creation `try`, so `persist_compile_cache()` aborts backend construction instead of leaving Inductor’s existing cache configuration unchanged.
Handle failures while resolving the home and default cache paths by returning without changing the cache configuration.
Also at `basal/engine.py:461`.
</issue_to_address>
### Comment 3
<location path="basal/engine.py" line_range="459" />
<code_context>
+ cleared after the switch, as its temporary_cache_dir does. Left as it is when the directory cannot be created."""
+ from torch._inductor.runtime.cache_dir_utils import default_cache_dir
+ set_to = os.environ.get("TORCHINDUCTOR_CACHE_DIR")
+ if set_to and os.path.abspath(set_to) != os.path.abspath(default_cache_dir()):
+ return
+ path = Path.home() / ".cache" / "basal" / "torchinductor"
</code_context>
<issue_to_address>
**Requested cache location is ignored**
When the user explicitly sets `TORCHINDUCTOR_CACHE_DIR` to `default_cache_dir()`, `persist_compile_cache()` treats the explicit setting as Inductor’s automatic setting and replaces it with the basal cache path, ignoring the user’s requested location.
Honor an explicitly set `TORCHINDUCTOR_CACHE_DIR` instead of inferring that it is automatic from its equality with `default_cache_dir()`.
Also at `basal/engine.py:460`.
</issue_to_address>
### Comment 4
<location path="basal/engine.py" line_range="986" />
<code_context>
def __init__(self, model_dir, dtype="bfloat16", quant=None, compile=False, shared=True, warm=True, attn="auto",
merge="auto", lean=False, tree="dense", state_cache_gb=0, prefix=False, batches="default",
readout_layer="off", template="off", gemma_attn="auto"):
+ persist_compile_cache() # before anything compiles
what = recurrent_layers(model_dir) # before anything is loaded
if what:
</code_context>
<issue_to_address>
**Non-compiling mode changes global cache**
When a caller constructs a graph backend with `compile=False` and later compiles other code in the same process, `persist_compile_cache()` sets the process-wide `TORCHINDUCTOR_CACHE_DIR` even though `compile=False`; later `torch.compile` calls by other code in the process therefore use basal’s cache directory instead of Inductor’s default, surprising callers that selected a non-compiling mode.
Only change the cache directory when this backend will compile, or make the process-wide cache change an explicit opt-in.
</issue_to_address>
### Comment 5
<location path="basal/engine.py" line_range="466-468" />
<code_context>
+ path.mkdir(parents=True, exist_ok=True)
+ except OSError:
+ return
+ os.environ["TORCHINDUCTOR_CACHE_DIR"] = str(path)
+ from torch._inductor.utils import clear_caches
+ clear_caches()
+
+
</code_context>
<issue_to_address>
**Cache switch can remain half-applied**
When `clear_caches()` raises before Inductor’s memoized cache paths are cleared and the caller catches the constructor failure and retries in the same process, `os.environ` already points to the persistent directory when `clear_caches()` raises before clearing Inductor’s memoized paths. A later call returns early because the environment now differs from the default, so compilation continues with stale paths and the new cache is not reliably reused after restart.
On failure, restore the previous environment value or ensure a retry still clears Inductor’s memoized paths before returning.
</issue_to_address>
### Comment 6
<location path="tests/test_engine.py" line_range="269" />
<code_context>
+ except Exception:
+ pass
+ assert os.environ["TORCHINDUCTOR_CACHE_DIR"] == str(want) and cache_dir() == str(want)
+ assert default.is_dir()
</code_context>
<issue_to_address>
**Stale compiler paths go undetected**
When inductor’s memoized cache paths remain pointed at `/tmp` after the environment variable is switched, the test checks only the environment variable and `cache_dir()`; if Inductor’s memoized cache paths still point to `/tmp`, both checks can report the new environment value and pass, while later compiles continue using the non-persistent cache.
Exercise an Inductor cache path that uses the memoized state after the switch, and assert that it resolves under the selected persistent directory.
</issue_to_address>…usable homes alone - basal records whether TORCHINDUCTOR_CACHE_DIR was set before anything imported torch's compiler (basal.INDUCTOR_CACHE_DIR_GIVEN): such a value is kept, Inductor's own default included; only the default Inductor writes on import is replaced. - No home directory or account, or a cache directory without write access: nothing changes. If clearing Inductor's memoised paths fails, the previous value comes back. - Only a backend that compiles moves the cache. - The test covers these cases and Inductor's memoised cache path.
|
Thank you, Miłosz! The persisted compile cache is merged into the basal 2.5 release branch with your commits as you wrote them. One small fix on top: 2.5's new prepared start-ups ( |
…d compile cache basal-serve loads a prepared directory before the engine is built, and Inductor writes the loaded artifacts into its cache directory at that moment; the engine then moved the cache to ~/.cache/basal/torchinductor (#47) and missed them, so a prepared start compiled everything again. prepared.load sets the directory first (persist_compile_cache, which is idempotent); the test checks where the artifacts are loaded.
…fast engine; --mode mps and --long-lane refused for it (branch pico-25) Conflict in gdn_graph.py: imports and GDNGraphBackend.__init__ of start-25 (graph_memory_gb), #47 (persist_compile_cache) and pico-25 (device); every side kept.
Problem
--mode fastcompiles its forwards at every cold start: on an RTX 4060 Ti most of basal-2.0-4.5B's ~14-minute startis the first call of the compiled forward (two Inductor compiles of the 60-layer model; #43's phase timers). Inductor
caches the compiled code, but by default in
/tmp/torchinductor_<user>, which a reboot empties on most systems (/tmpa tmpfs, or cleaned at boot), so the first start after every reboot compiles everything again.
Change
persist_compile_cache()(basal/engine.py), called first inGraphBackend.__init__andGDNGraphBackend.__init__when they compile (
--mode fast):TORCHINDUCTOR_CACHE_DIR=~/.cache/basal/torchinductor, as--mode tpukeepsJAX's cache in
~/.cache/basal/jax. Inductor puts its Triton kernels under that directory too (unlessTRITON_CACHE_DIRis set)./tmpdefault intoTORCHINDUCTOR_CACHE_DIR(
cache_dir()sets the variable).basal/__init__.pyrecords whether the variable was set before that(
INDUCTOR_CACHE_DIR_GIVEN): a value given then is kept, Inductor's default too, as is another directory setin-process since; only the default Inductor wrote itself is replaced. After the switch Inductor's memoised paths
are cleared (
torch._inductor.utils.clear_caches), as its owntemporary_cache_dirdoes; if that fails, theprevious value comes back.
fast-nocompileleaves the process's Inductor configuration alone.A cached graph is the compiled code itself, so the kernels and the answers are the same.
Measurements
RTX 4060 Ti 16 GB, torch 2.13.0+cu130,
main= b20f0f9 (2.4.1). Per model: this branch starts cold, a reboot issimulated (
/tmp/torchinductor_*removed), this branch starts again,mainstarts after the same wipe.basal-serve --mode fastready time, then the answers to 10 requests (compress over 1.5k-6k tokens, 5-40 questions;679 probabilities) at each start:
main, after the rebootEvery probability bit-identical across the three starts of each model. The cache took 43 MB for mini, 55 MB with
the 4.5B added. Not measured: basal-omni and basal-omni-pico, which go through the same two constructors (pico on
2.4.0 started in 183 s with warm caches against 411 s cold on the same card, #43's measurements).
Tests
test_graph_engine_keeps_the_compile_cache_across_reboots_unless_set(tests/test_engine.py, next to thecuBLAS workspace test): the variable unset; set to Inductor's own default by its import (basal-serve's case); the
same default given before basal was imported; another directory set in-process;
compile=False; a read-only cachedirectory. Each time Inductor's
cache_dir()and its memoisedCacheBase.get_local_cache_path()resolve under theexpected directory. It fails without the change and with a version that only checked whether the variable was set
(which is what a first GPU run of this branch caught).
docs/INSTALL.md: where the cache lives, how to move or delete it.tests/(withouttest_gguf.py): CPU 755 passed, 81 skipped.