Repository navigation
Conversation
Reviewer's GuideThis 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 inferencesequenceDiagram
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
Flow diagram for TPU model loading and compilationflowchart 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
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
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>| 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) |
There was a problem hiding this comment.
🟡 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.|
@rkinas The PR is ready for review. All CI checks are passing, and I've addressed the initial sourcery-ai suggestions. |
|
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. |
Closes #11
Overview
This PR adds native Google TPU support (
--mode tpu) implemented in pure JAX and XLA.Key Changes
basal/tpu_kernels.py): Plain-JAX implementations of RMSNorm, fused QKV linear, SwiGLU, RoPE, and block-causal attention supporting SOAM prefix sharing.basal/tpu.py):jax.lax.scanover stacked layer weights for fast compilation and compact HLO graphs..safetensorsloading directly vianp.memmapandml_dtypes.bfloat16.LENSxBATCHES) with warmup (warm=True) and XLA disk cache to eliminate runtime recompilations.LETTER_SLOTS = 16), skipping full vocabulary projections.tests/test_tpu.pyand a Colab demo with benchmarks innotebooks/tpu.ipynb.Verification & Performance
fp32CPU reference (atol=1e-5in unit tests).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:
--mode tpu, including bf16 and fp32 execution, SOAM packing, shape bucketing, and long-prompt support.basal-bench.Enhancements:
Build:
tpudependency extra for JAX TPU support and update the lockfile.Documentation:
Tests: