Skip to content

feat(engine): add Cloud TPU backend via JAX/XLA (--mode tpu) - #12

Closed
qooba wants to merge 5 commits into
rkinas:mainfrom
qooba:tpu-engine
Closed

qooba wants to merge 5 commits into
rkinas:mainfrom
qooba:tpu-engine

Conversation

@qooba

@qooba qooba commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Closes #11

Overview

This PR adds native Google TPU support (--mode tpu) implemented in pure JAX and XLA.

Key Changes

  • JAX Kernels (basal/tpu_kernels.py): Plain-JAX implementations of RMSNorm, fused QKV linear, SwiGLU, RoPE, and block-causal attention supporting SOAM prefix sharing.
  • TPU Backend (basal/tpu.py):
  • Uses jax.lax.scan over stacked layer weights for fast compilation and compact HLO graphs.
  • Torch-free .safetensors loading directly via np.memmap and ml_dtypes.bfloat16.
  • Static shape bucketing (LENS x BATCHES) with warmup (warm=True) and XLA disk cache to eliminate runtime recompilations.
  • Selective readout restricted to candidate option tokens (LETTER_SLOTS = 16), skipping full vocabulary projections.
  • Tests & Notebook: Added unit tests in tests/test_tpu.py and a Colab demo with benchmarks in notebooks/tpu.ipynb.

Verification & Performance

  • Parity: Achieves 1.000 decision agreement against the PyTorch fp32 CPU reference (atol=1e-5 in unit tests).
  • Speed (TPU v5e-1):
    • basal-1.5-mini: 6.7 ms / decision (146 dec/s).
    • basal-1.5 (4.5B): 17.7 ms / decision (49.5 dec/s).

Summary by Sourcery

Add native Google TPU inference through a JAX/XLA backend with optimized serving, benchmarking, documentation, and validation.

New Features:

  • Add a JAX/XLA Google TPU backend with --mode tpu, including bf16 and fp32 execution, SOAM packing, shape bucketing, and long-prompt support.
  • Automatically select TPU mode when a TPU device is available and expose TPU benchmarking support through basal-bench.
  • Provide a Colab notebook for running, serving, and benchmarking basal on Google TPUs.

Enhancements:

  • Add TPU-specific hardware documentation, setup guidance, performance results, and backend usage details.
  • Add parity and behavior coverage for TPU kernels, packed-prefix execution, blocked attention, batching, device handling, and prompt limits.

Build:

  • Add a pinned tpu dependency extra for JAX TPU support and update the lockfile.

Documentation:

  • Document Google TPU installation, operation, limitations, resource requirements, and measured performance in the README and hardware guide.

Tests:

  • Add CPU-runnable TPU backend tests covering numerical parity with PyTorch reference execution and supported runtime behaviors.

@sourcery-ai

sourcery-ai Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR adds a native Google TPU backend built from plain JAX kernels and XLA, integrating memory-mapped safetensors loading, scanned decoder execution, SOAM prefix packing, static shape compilation/caching, and selective token readout into serving and benchmarking; tests validate numerical parity against PyTorch and documentation provides TPU deployment and performance guidance.

Sequence diagram for SOAM TPU inference

sequenceDiagram
    participant Client
    participant Server
    participant TPUBackend
    participant XLA
    participant TPU

    Client->>Server: POST /v1/systemone
    Server->>TPUBackend: run_shared(groups)
    TPUBackend->>TPUBackend: _units(groups)
    TPUBackend->>TPUBackend: _bucket(length, batch)
    TPUBackend->>XLA: _fwd(params, ids, pos, end)
    XLA->>TPU: Execute lax.scan decoder layers
    TPU-->>XLA: Hidden states
    XLA-->>TPUBackend: _read selective letter logits
    TPUBackend-->>Server: Assemble option probabilities
    Server-->>Client: Decision response
Loading

Flow diagram for TPU model loading and compilation

flowchart TD
    Start[TPUBackend initialization] --> Config[model_config]
    Config --> Files[Load safetensors files]
    Files --> Map[load_safetensors via np.memmap]
    Map --> Stack[stack_params with fused QKV and stacked layers]
    Stack --> Device[jax.device_put parameters]
    Device --> Warm{warm enabled}
    Warm -->|yes| Compile[Compile bucket shapes with jax.jit and XLA]
    Compile --> Cache[Store executables in JAX compilation cache]
    Warm -->|no| Ready[Backend ready]
    Cache --> Ready
Loading

File-Level Changes

Change Details Files
Added a pure-JAX/XLA Llama inference implementation for Google TPU execution.
  • Implemented RMSNorm, linear/QKV fusion, SwiGLU, RoPE, grouped-query attention, and prefix-trie causal masking.
  • Stacked decoder parameters and executed layers with jax.lax.scan.
  • Added bf16/fp32 checkpoint loading from safetensors via memory-mapped NumPy arrays, including tied embeddings and optional biases.
basal/tpu.py
basal/tpu_kernels.py
Integrated TPU inference into benchmarking and HTTP serving with shape-aware compilation and SOAM batching.
  • Added tpu and tpu-fp32 backend selection, TPU auto-detection, device naming, and memory reporting.
  • Reused GraphBackend packing for shared-prefix requests and added static length/batch buckets, warmup, compilation caching, long-prompt fallback buckets, and readout-only candidate token projection.
  • Restricted TPU behavior/documentation to supported Llama checkpoints and documented unsupported features and resource limits.
basal/bench.py
basal/server.py
basal/engine.py
README.md
docs/HARDWARE.md
pyproject.toml
uv.lock
Added TPU parity coverage and an executable TPU usage and benchmarking walkthrough.
  • Compared packed and separate TPU/JAX outputs against a tiny PyTorch Llama reference, including GQA, biases, RoPE, batching, long prompts, and non-shared option orders.
  • Added a Colab notebook covering installation, model loading, serving, SOAM behavior, benchmarks, and optional fp32 agreement checks.
tests/test_tpu.py
notebooks/tpu.ipynb

Assessment against linked issues

Issue Objective Addressed Explanation
#11 Add a functional --mode tpu backend for Cloud TPU using JAX/XLA, including integration with serving, benchmarking, default-mode detection, and installation support. ✅
#11 Implement the required TPU model execution features: plain-JAX RMSNorm, fused QKV, SwiGLU, RoPE, SOAM prefix-trie attention masking, stacked-layer lax.scan execution, static shape bucketing with warmup and compilation caching, and selective candidate-token readout. ✅
#11 Provide torch-free safetensors weight loading plus validation, documentation, tests, and a runnable Cloud TPU/Colab demonstration with parity and performance verification. ✅

Possibly linked issues


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 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="basal/tpu.py" line_range="203" />
<code_context>
+        for x in xs:
+            if n <= x:
+                return x
+        return -(-n // 512) * 512  # beyond the largest bucket: one extra compiled length per 512 tokens
+
+    def _letter_slots(self, ids_list):
</code_context>
<issue_to_address>
**Oversized prompts exhaust TPU resources**

When an unauthenticated caller submits state that produces a prompt beyond the largest configured bucket, `_bucket` rounds the prompt to a fresh length, and `_fwd` compiles it with quadratic attention intermediates; a sufficiently large request exhausts TPU memory or compilation resources and takes the service offline.

Reject or cap prompts beyond the largest supported bucket before `_bucket` compiles them.
</issue_to_address>

### Comment 2
<location path="basal/tpu.py" line_range="187" />
<code_context>
+        self.prefill = PREFILL
+        self.shared = shared
+        self.cfg, self.params = load_params(model_dir, dtype)
+        self.device = jax.devices()[0]
+        c = self.cfg
+        self._fwd = jax.jit(lambda p, ids, pos, end: forward(p, ids, pos, end, c=c))
</code_context>
<issue_to_address>
**TPU mode runs on the wrong device**

When explicit `--mode tpu` is selected while JAX's default device is not a TPU or no TPU is exposed, `jax.devices()[0]` selects a device without checking its platform, so the model runs on CPU or another accelerator instead of failing clearly, despite callers selecting TPU mode.

Select a TPU device explicitly and raise a clear error when none is available.
</issue_to_address>

### Comment 3
<location path="basal/tpu.py" line_range="55" />
<code_context>
+    [in, out]. Biases are always present (zeros when the checkpoint has none), so the compiled program does not depend
+    on the checkpoint."""
+    from ml_dtypes import bfloat16
+    dt = {"bfloat16": bfloat16, "float32": np.float32}[dtype]
+    L, H, F = c["layers"], c["hidden"], c["ffn"]
+    Q, KV = c["heads"] * c["head_dim"], c["kv_heads"] * c["head_dim"]
</code_context>
<issue_to_address>
**Unsupported dtype crashes startup**

When TPU mode receives a dtype other than `bfloat16` or `float32`, `stack_params` indexes its two-entry dtype map and raises `KeyError`, so the server exits during startup with an opaque error.

Validate the TPU dtype before `stack_params` and raise a clear error listing the supported values.
</issue_to_address>

### Comment 4
<location path="basal/tpu.py" line_range="197" />
<code_context>
+                for b in self.BATCHES:
+                    if b * L <= self.TOKEN_BUDGET or b == 1:
+                        row = ([0] * L, list(range(L)), [0] * L, [L - 1] * (2 if shared else 1), [-1])
+                        self._forward_rows([row] * b, b, L)
+
+    def _bucket(self, n, xs):
</code_context>
<issue_to_address>
**First multi-question request compiles**

When a SOAM request needs more readouts than the constructor's one-or-two-per-row warm-up, `_forward_rows` warms `_read` only for the warm-up readout count, but requests use a larger rounded readout shape; JAX compiles that unseen shape after serving starts, stalling the first request.

Warm `_read` for the possible rounded readout shapes before serving, or constrain requests to warmed shapes.
</issue_to_address>

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

Comment thread basal/tpu.py Resolved
Comment thread basal/tpu.py Resolved
Comment thread basal/tpu.py Resolved
Comment thread basal/tpu.py Outdated
for b in self.BATCHES:
if b * L <= self.TOKEN_BUDGET or b == 1:
row = ([0] * L, list(range(L)), [0] * L, [L - 1] * (2 if shared else 1), [-1])
self._forward_rows([row] * b, b, L)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · First multi-question request compiles

When a SOAM request needs more readouts than the constructor's one-or-two-per-row warm-up, _forward_rows warms _read only for the warm-up readout count, but requests use a larger rounded readout shape; JAX compiles that unseen shape after serving starts, stalling the first request.

Warm _read for the possible rounded readout shapes before serving, or constrain requests to warmed shapes.

Prompt for AI agents
In `basal/tpu.py` at line 197:

**First multi-question request compiles**

When a SOAM request needs more readouts than the constructor's one-or-two-per-row warm-up, `_forward_rows` warms `_read` only for the warm-up readout count, but requests use a larger rounded readout shape; JAX compiles that unseen shape after serving starts, stalling the first request.

Warm `_read` for the possible rounded readout shapes before serving, or constrain requests to warmed shapes.

@qooba

qooba commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

@rkinas The PR is ready for review. All CI checks are passing, and I've addressed the initial sourcery-ai suggestions.
Whenever you have a moment, I'd appreciate your feedback ;)

@rkinas

rkinas commented Oct 14, 2026

Copy link
Copy Markdown
Owner

Impressive work, and parity 1.000 against fp32 is exactly the bar. The engine changed a lot in v2.0.0, so it needs a port before we can merge: --orders now takes 1/2/auto/2le (default auto), so shared=a.orders == 2 no longer selects the shared path; GraphBackend.run_shared takes done=; and 2.0 models use prompt format 2 with up to 255 options. Please also make JAX an optional extra (basal[tpu]) so the default install and lock don't change, and report parity and speed on basal-2.0-mini and basal-2.0 (4.5B); max at 11B needs more HBM than a v5e-1 has. We'll then list it as an experimental, community-maintained backend in docs/HARDWARE.md.

@qooba qooba closed this by deleting the head repository Oct 14, 2026
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.

[Feature] Add Cloud TPU backend via JAX/XLA (--mode tpu)

2 participants