Repository navigation
add TPU support for basal 2.0 - #15
Conversation
Reviewer's GuideThis PR introduces an optional, experimental plain-JAX/XLA TPU backend for basal 2.0, integrates it with the server and benchmark paths using GraphBackend-compatible sharing and streaming semantics, and covers the implementation with CPU-JAX parity tests, TPU documentation, and a Colab workflow. Sequence diagram for TPU request batching and streamingsequenceDiagram
participant Client
participant Server
participant TPUBackend
participant XLA
participant TPU
Client->>Server: submit request
Server->>TPUBackend: run_shared(groups, policy, done)
TPUBackend->>TPUBackend: _units(groups)
TPUBackend->>TPUBackend: _chunks(unit lengths)
TPUBackend->>XLA: _forward_rows(packed rows)
XLA->>TPU: forward(params, ids, pos, end)
TPU-->>XLA: hidden states
XLA-->>TPUBackend: readout logits
TPUBackend->>TPUBackend: _softmax(option logits)
TPUBackend-->>Server: done(group, result)
Server-->>Client: streamed group result
Flow diagram for TPU compilation and inferenceflowchart TD
Start[Initialize TPUBackend] --> Config[Load Llama config and safetensors]
Config --> Params[Stack weights and place on device]
Params --> Shapes[Build length and batch shape grid]
Shapes --> Warm[Warm up JAX compiled programs]
Warm --> Request[Receive packed prompt groups]
Request --> Context{Prompt within max-len?}
Context -->|no| Reject[Refuse or apply server context overflow]
Context -->|yes| Bucket[Select length and batch bucket]
Bucket --> Attention{Prompt above 3072 tokens?}
Attention -->|no| Dense[Standard causal attention]
Attention -->|yes| Blocked[Blocked online-softmax attention]
Dense --> Readout[Read 256 letter slots]
Blocked --> Readout
Readout --> Probabilities[Compute option probabilities]
Probabilities --> Done[Return group result via done callback]
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/server.py" line_range="73" />
<code_context>
"gguf": ("gguf", None, False), # llama.cpp in process on a GGUF file (--gguf; Metal, CUDA or CPU)
"ollama": ("ollama", None, False), # Ollama with the GGUF exports (1.5); --ollama-url, --ollama-model
"llamacpp": ("llamacpp", None, False), # llama.cpp server with the GGUF exports (1.5); --llamacpp-url
+ "tpu": ("tpu", None, False), # Google TPU (experimental, basal[tpu]): JAX / XLA, SOAM, one program per shape
}
</code_context>
<issue_to_address>
**TPU calibration file is ignored**
When a model directory contains a TPU-specific calibration file and the caller does not pass `--calibration` explicitly, `calibration_name` does not recognize the newly registered `tpu` kind, so `calibration_file` falls back to `CALIBRATION.json` even when the model provides `CALIBRATION.tpu.json`; the TPU then serves with the wrong calibration.
Include `tpu` in the per-engine calibration-name selection and cover it with a calibration-file selection test.
</issue_to_address>
### Comment 2
<location path="basal/server.py" line_range="89-90" />
<code_context>
return "mlx"
except ImportError:
return "mps"
+ from .tpu import tpu_available
+ if tpu_available():
+ return "tpu"
return "eager"
</code_context>
<issue_to_address>
**Broken JAX prevents CPU startup**
When JAX is discoverable but fails to import or initialize on a machine that would otherwise use eager mode, `default_mode()` calls `tpu_available()`, whose `import jax` is not guarded; when JAX is present but fails during import, the exception escapes and prevents the server from falling back to eager on a non-TPU machine.
Treat JAX import and initialization failures as TPU unavailable in the default-mode probe, while leaving explicit `--mode tpu` errors visible.
Also at `basal/tpu.py:162`.
</issue_to_address>
### Comment 3
<location path="basal/tpu.py" line_range="243-246" />
<code_context>
+ for b in self.BATCHES:
+ if b * L <= self.TOKEN_BUDGET or b == 1:
+ self._forward_rows([([0] * L, list(range(L)), [0] * L, [L - 1] * R0, [-1])] * b, b, L)
+ h = jnp.zeros((1, L, self.cfg["hidden"]), self.params["embed"].dtype, device=self.device)
+ R = 4
+ while R <= self.WARM_READOUTS:
+ self._read(self.params, h, np.zeros(R, np.int32), np.zeros(R, np.int32), self._lids)
+ R *= 2
+
</code_context>
<issue_to_address>
**Requests stall for JIT compilation**
When a request uses a batch size greater than one, rounds to two readouts, or needs more than 64 readouts, `_warm` compiles `_read` only for batch size 1 and readout counts from 4 through 64, while `_forward_rows` uses the actual batch size and rounds readouts to powers of two. JAX compiles the missing shape during serving, so the request stalls.
Warm `_read` for the batch sizes and padded readout counts that requests can use, including 2 and counts above 64.
Also at `basal/tpu.py:249`, `basal/tpu.py:285`.
</issue_to_address>
### Comment 4
<location path="basal/bench.py" line_range="45-47" />
<code_context>
if not path:
raise SystemExit("mode gguf needs --gguf <file.gguf> (or gguf@<file.gguf>)")
return GGUFBackend(md, path)
+ if mode in ("tpu", "tpu-fp32"): # Google TPU (basal[tpu]); tpu-fp32: the same engine in fp32 (parity reference)
+ from .tpu import TPUBackend
+ return TPUBackend(md, "float32" if mode == "tpu-fp32" else "bfloat16", warm=False)
kind, quant, comp = MODES[mode]
if kind == "eager":
</code_context>
<issue_to_address>
**Default benchmark skips TPU**
When `basal-bench` is run without `--modes` on a TPU VM, `default_modes()` does not use TPU availability when choosing its default modes, so `basal-bench` without `--modes` selects the non-TPU fallback instead of benchmarking the serving default on a TPU VM.
Have `default_modes()` include TPU detection, preferably by sharing the serving default-mode selection logic.
</issue_to_address>|
Thanks, clean port, and the parity table is exactly what I need. We'll merge after 2.2.0 (Mon 19 Oct) as an experimental, community-maintained backend. Before that: (1) rebase onto v2.2.0; (2) a line on why tests/test_calibration2.py changes; (3) add yourself to CODEOWNERS for basal/tpu*.py and tests/test_tpu.py; (4) in HARDWARE.md, the bf16 flip rate on a larger public sample (~2,000 rows) next to the 44-example table. |
|
Ok. I am merging it now. It will be in 2.2. Than you for your contribution. |
One line per external contributor whose commits are in main or in 2.2, with what they added and the PR: Paweł Kiszczak (#4), Piotr Durlej (#8), Kuba Sołtys (#15), Michał Kardyś (#14); names from their GitHub profiles and commit authors. README and WHATS_NEW 2.2 list basal-export-gguf, --mode tpu and --mode strix; NOTICE names the contributors.
|
Thank you, Kuba! The TPU backend is merged and ships in basal v2.2.0 What we added on top:
Here, If you'd like, we'd be glad to list you in CODEOWNERS for |
Closes #11. Supersedes #12 (closed, I had to recreate my fork), ported to basal 2.0.0 as requested in the review there.
Overview
Adds Google TPU inference (
--mode tpu), written in plain JAX on XLA. It's an experimental, community-maintainedbackend and is installed only through the optional extra
basal[tpu].Port to the 2.0 engine (review points from #12)
--orders1/2/auto/2le: the backend no longer decides on its own when to share prefixes. It takes the server'sown rule,
shared = orders != 1 or --soam on, likeGraphBackend.run_shared(groups, policy=None, done=None): followsGraphBackend.run_shared. It reuses_units/_chunksand calls
done(k, res)for each group as soon as all its units are read out, so streaming works withinflight=1.LETTER_SLOTS = 256output-head rows are read per position. The number isfixed, so a new set of option codes needs no recompile.
--max-len(clamped to the model's positions) setscontext/context_reason, so--context-overflowworks as on the other engines. A group longer than--max-lenis bisected, and a single promptlonger than that is refused.
tpu = ["jax[tpu]==0.11.1; python_version >= '3.12' and sys_platform == 'linux'"],with libtpu also from PyPI. Only
basal/tpu.pyandbasal/tpu_kernels.pyimport JAX.this with
uv exportagainst main's lock.uv.lockdiff: it adds 4 packages for the extra (jax, jaxlib, libtpu, opt-einsum, plus their deps scipy,ml-dtypes and requests). The other ~40 changed lines are uv re-normalising markers, which happens with any new
extra (even
tpu = ["numpy"]gives the same −42 lines). No locked version changes.Engine
jax.lax.scanover stacked layer weights, so compiles are short and the HLOgraphs compact.
np.memmap,ml_dtypes).so serving doesn't recompile.
--dtype bfloat16(default) orfloat32(exact mode with HIGHEST-precision matmuls).--mode tpuis chosen automatically on a TPU VM that hasbasal[tpu]installed.--media, early exit, quantisation.Parity and speed (Colab TPU v5e-1, JAX 0.11.1)
basal-bench, all 44 bundled examples, with transformers fp32 on the CPU as the reference:HTTP (
basal-servedefaults, 32 clients): basal-2.0 17.1 ms p50, 59.6 dec/s; mini 7.3 ms p50, 165.5 dec/s.Identity paths (items from
basal/identity.py, each prompt against transformers fp32 alone; 40 readouts persingle path, 60 per request path; prompt p50 1,794 tokens, long states 3.9k–5.7k):
add no error.
max |Δp| is 0.01–0.05.
0.027. With 40 readouts, one flip falls below the 0.999 gate.
basal-2.0-max (11B) doesn't fit in a v5e-1's 16 GB of HBM.
To reproduce on your private development sample:
basal-bench --model Remek/basal-2.0-4.5B --modes eager-fp32 tpu --questions <file>Docs, tests, notebook
docs/INSTALL.md: TPU install section.docs/SERVING.md: mode row.docs/HARDWARE.md: a draft of the "experimental, community-maintained" section with the numbers above, for youto keep, edit or drop.
tests/test_tpu.pyhas 10 tests. They run on CPU JAX locally and on the TPU when one is present (parityvs torch,
done=with several roots, bisecting above--max-len, 60 option codes, blocked attention, dtype anddevice errors).
notebooks/tpu.ipynbis a Colab notebook that installs, runs, serves and benchmarks basal-2.0 on aTPU. Colab's TPU image ships torchvision / torchaudio / torch-xla built for torch 2.9, so the notebook uninstalls
them after the torch upgrade. Closes [Feature] Add Cloud TPU backend via JAX/XLA (--mode tpu) #11. Supersedes feat(engine): add Cloud TPU backend via JAX/XLA (--mode tpu) #12 (closed), ported to basal 2.0.0 as requested in the review there.
Overview
Adds Google TPU inference (
--mode tpu), written in plain JAX on XLA. It's an experimental, community-maintainedbackend and is installed only through the optional extra
basal[tpu].Port to the 2.0 engine (review points from #12)
--orders1/2/auto/2le: the backend no longer decides on its own when to share prefixes. It takes the server'sown rule,
shared = orders != 1 or --soam on, likeGraphBackend.run_shared(groups, policy=None, done=None): followsGraphBackend.run_shared. It reuses_units/_chunksand calls
done(k, res)for each group as soon as all its units are read out, so streaming works withinflight=1.LETTER_SLOTS = 256output-head rows are read per position. The number isfixed, so a new set of option codes needs no recompile.
--max-len(clamped to the model's positions) setscontext/context_reason, so--context-overflowworks as on the other engines. A group longer than--max-lenis bisected, and a single promptlonger than that is refused.
tpu = ["jax[tpu]==0.11.1; python_version >= '3.12' and sys_platform == 'linux'"],with libtpu also from PyPI. Only
basal/tpu.pyandbasal/tpu_kernels.pyimport JAX.this with
uv exportagainst main's lock.uv.lockdiff: it adds 4 packages for the extra (jax, jaxlib, libtpu, opt-einsum, plus their deps scipy,ml-dtypes and requests). The other ~40 changed lines are uv re-normalising markers, which happens with any new
extra (even
tpu = ["numpy"]gives the same −42 lines). No locked version changes.Engine
jax.lax.scanover stacked layer weights, so compiles are short and the HLOgraphs compact.
np.memmap,ml_dtypes).so serving doesn't recompile.
--dtype bfloat16(default) orfloat32(exact mode with HIGHEST-precision matmuls).--mode tpuis chosen automatically on a TPU VM that hasbasal[tpu]installed.--media, early exit, quantisation.Parity and speed (Colab TPU v5e-1, JAX 0.11.1)
basal-bench, all 44 bundled examples, with transformers fp32 on the CPU as the reference:HTTP (
basal-servedefaults, 32 clients): basal-2.0 17.1 ms p50, 59.6 dec/s; mini 7.3 ms p50, 165.5 dec/s.Identity paths (items from
basal/identity.py, each prompt against transformers fp32 alone; 40 readouts persingle path, 60 per request path; prompt p50 1,794 tokens, long states 3.9k–5.7k):
add no error.
max |Δp| is 0.01–0.05.
0.027. With 40 readouts, one flip falls below the 0.999 gate.
basal-2.0-max (11B) doesn't fit in a v5e-1's 16 GB of HBM.
To reproduce on your private development sample:
basal-bench --model Remek/basal-2.0-4.5B --modes eager-fp32 tpu --questions <file>Docs, tests, notebook
docs/INSTALL.md: TPU install section.docs/SERVING.md: mode row.docs/HARDWARE.md: a draft of the "experimental, community-maintained" section with the numbers above, for youto keep, edit or drop.
tests/test_tpu.pyhas 10 tests. They run on CPU JAX locally and on the TPU when one is present (parityvs torch,
done=with several roots, bisecting above--max-len, 60 option codes, blocked attention, dtype anddevice errors).
notebooks/tpu.ipynbis a Colab notebook that installs, runs, serves and benchmarks basal-2.0 on aTPU. Colab's TPU image ships torchvision / torchaudio / torch-xla built for torch 2.9, so the notebook uninstalls
them after the torch upgrade.
Summary by Sourcery
Add experimental JAX/XLA support for running basal 2.0 inference on Google TPUs.
New Features:
Enhancements:
Build:
Documentation:
Tests: