Skip to content

perf(fast): torch.compile's cache in ~/.cache/basal/torchinductor (starts after a reboot reuse the compiled code) - #47

Merged
rkinas merged 5 commits into
rkinas:mainfrom
Butterski:perf/compile-cache
Nov 2, 2026
Merged

rkinas merged 5 commits into
rkinas:mainfrom
Butterski:perf/compile-cache

Conversation

@Butterski

@Butterski Butterski commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

--mode fast compiles its forwards at every cold start: on an RTX 4060 Ti most of basal-2.0-4.5B's ~14-minute start
is 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 (/tmp
a tmpfs, or cleaned at boot), so the first start after every reboot compiles everything again.

Change

persist_compile_cache() (basal/engine.py), called first in GraphBackend.__init__ and GDNGraphBackend.__init__
when they compile (--mode fast): TORCHINDUCTOR_CACHE_DIR = ~/.cache/basal/torchinductor, as --mode tpu keeps
JAX's cache in ~/.cache/basal/jax. Inductor puts its Triton kernels under that directory too (unless
TRITON_CACHE_DIR is set).

  • Importing transformers' models already makes Inductor write its /tmp default into TORCHINDUCTOR_CACHE_DIR
    (cache_dir() sets the variable). basal/__init__.py records 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 set
    in-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 own temporary_cache_dir does; if that fails, the
    previous value comes back.
  • No home directory or account, or a cache directory without write access: nothing changes.
  • fast-nocompile leaves 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 is
simulated (/tmp/torchinductor_* removed), this branch starts again, main starts after the same wipe.
basal-serve --mode fast ready time, then the answers to 10 requests (compress over 1.5k-6k tokens, 5-40 questions;
679 probabilities) at each start:

model branch, cold branch, after the reboot main, after the reboot
basal-2.0-mini 434 s 238 s 417 s
basal-2.0-4.5B 842 s 519 s 823 s

Every 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

  • New test_graph_engine_keeps_the_compile_cache_across_reboots_unless_set (tests/test_engine.py, next to the
    cuBLAS 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 cache
    directory. Each time Inductor's cache_dir() and its memoised CacheBase.get_local_cache_path() resolve under the
    expected 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/ (without test_gguf.py): CPU 755 passed, 81 skipped.

…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.
@sourcery-ai

sourcery-ai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Fast-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 initialization

sequenceDiagram
    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
Loading

Flow diagram for fast-mode cache reuse after reboot

flowchart 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
Loading

File-Level Changes

Change Details Files
Persist torch.compile/Inductor artifacts under a user cache directory across reboots while preserving explicit user configuration.
  • Added cache initialization that treats Inductor’s temporary default as unset, creates ~/.cache/basal/torchinductor, updates TORCHINDUCTOR_CACHE_DIR, and clears memoized Inductor paths.
  • Invoked cache setup before model loading or compilation in both graph backends.
  • Leaves an explicitly configured cache directory and handles cache-directory creation failures without changing behavior.
basal/engine.py
basal/gdn_graph.py
Documented the new fast-mode cache location and its operational controls.
  • Explained the reboot-persistent cache, override environment variable, and deletion procedure.
  • Added release-note performance results and cache-size information.
docs/INSTALL.md
docs/WHATS_NEW.md
Added coverage for cache selection and precedence behavior.
  • Tested unset, Inductor-default, and user-selected TORCHINDUCTOR_CACHE_DIR cases, including cache_dir() results and directory creation.
tests/test_engine.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

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

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>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread basal/engine.py Resolved
Comment thread basal/engine.py Resolved
Comment thread basal/engine.py Resolved
Comment thread basal/engine.py Resolved
Comment thread basal/engine.py Resolved
Comment thread tests/test_engine.py Resolved
…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.
@rkinas

rkinas commented Oct 28, 2026

Copy link
Copy Markdown
Owner

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 (basal-prepare / --prepared) now call persist_compile_cache() before loading, so a prepared start finds its artifacts. The PR will close when 2.5 is published on main.

@rkinas
rkinas merged commit 5f11325 into rkinas:main Nov 2, 2026
1 check passed
rkinas added a commit that referenced this pull request Nov 2, 2026
…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.
rkinas added a commit that referenced this pull request Nov 2, 2026
rkinas added a commit that referenced this pull request Nov 2, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants