Inside TorchTPU: PyTorch, StableHLO, PjRt, Mosaic, and the Open-Source TPU Compiler Boundary
A source-level tour of TorchTPU and the open TPU compilation stack—following eager and torch.compile execution through StableHLO, PjRt, Pallas, and Mosaic, and identifying where open source ends at libtpu.
This post studies TorchTPU — A Hybrid Eager/Compiled Architecture for Native PyTorch Execution on TPU, arXiv v4, together with the open-source implementation. A newer paper revision exists, but this article follows the v4 URL requested above. Performance results are the paper authors’ measurements; I did not reproduce them.
Source links are pinned to
google-pytorch/torch_tpu@4a22cca,openxla/xla@281e9b2, andjax-ml/jax@928f647.
TPU architecture before the compiler
A TPU is a domain-specific matrix processor rather than a GPU-style collection of independently programmed threads. Google describes the physical hierarchy as:
1
2
3
4
5
6
7
8
9
10
11
12
13
TPU Pod
|
+-- TPU slice: chips connected by high-speed ICI
| |
| +-- TPU chip
| |
| +-- one or more TensorCores
| |
| +-- one or more MXUs
| +-- vector unit
| +-- scalar unit
|
+-- additional slices connected through the data-center network
The terminology can be confusing. A TPU TensorCore is a processor containing matrix, vector, and scalar execution resources; it is not the same thing as an NVIDIA Tensor Core.
Google’s TPU architecture documentation describes the main responsibilities:
| Component | Role |
|---|---|
| MXU | Dense matrix multiply-accumulate using a systolic array |
| Vector unit | Activations, softmax, reductions, and other vector computation |
| Scalar unit | Control flow, address calculation, and maintenance work |
| HBM | High-capacity storage for model parameters, activations, and results |
| SparseCore | Embedding, gather/scatter, and sparse workloads on supported generations |
| DMA engines | Host/device and remote data movement |
Inside a TensorCore
The following is a conceptual diagram, not a physical floor plan:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
TPU chip
+-------------------------------------------------------+
| HBM |
| parameters, activations, and outputs |
+--------------------------+----------------------------+
|
data movement
|
+--------------------------v----------------------------+
| TensorCore |
| |
| +---------------+ +---------------+ +-----------+ |
| | Scalar unit | | Vector unit | | MXU | |
| | | | | | | |
| | control flow | | activation | | matrix | |
| | addresses | | softmax | | multiply | |
| | loop/control | | elementwise | | accumulate| |
| +---------------+ +---------------+ +-----+-----+ |
| | |
| FP32 accumulators|
+-------------------------------------------------------+
The Matrix Multiplication Unit is a physical systolic array of connected multiply-accumulate cells:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
B / weight tile
|
v
+-----+-----+-----+-----+
A ---> | MAC | MAC | MAC | MAC |
tile +-----+-----+-----+-----+
| MAC | MAC | MAC | MAC | values and partial sums
+-----+-----+-----+-----+ move between neighboring cells
| MAC | MAC | MAC | MAC |
+-----+-----+-----+-----+
| MAC | MAC | MAC | MAC |
+-----+-----+-----+-----+
|
v
accumulated tile
The 4-by-4 picture represents a much larger array:
- TPU v5p and earlier generations use 128-by-128 MXUs.
- TPU v6e and TPU7x use 256-by-256 MXUs.
- BF16 and supported lower-precision inputs are accumulated into FP32.
Once tiles enter the MXU, data and partial sums flow through neighboring cells. The array performs many multiply-accumulates without repeatedly returning each intermediate result to HBM. This regular dataflow is what makes matrix shape, tiling, layout, and pipeline scheduling central compiler decisions.
From one chip to a TPU Pod
A TPU workload also has a system topology:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
one TPU slice
TPU VM host 0 TPU VM host 1
| |
+----+----+ +----+----+
| chip 0 |<--------- ICI ---------->| chip 2 |
+----+----+ +----+----+
^ ^
| ICI | ICI
v v
+----+----+ +----+----+
| chip 1 |<--------- ICI ---------->| chip 3 |
+---------+ +---------+
slice A ===== data-center network ===== slice B
The exact topology depends on TPU generation:
- a slice is a set of chips connected by high-speed inter-chip interconnect (ICI);
- slices can use two-dimensional or three-dimensional topologies;
- a
4x4x4TPU cube contains 64 chips; - larger jobs can combine slices through the data-center network (DCN); and
- one TPU VM host may be attached to one or more chips.
The compiler and distributed runtime must respect this topology. Tensor, data, pipeline, and expert parallel dimensions should be placed so that their communication matches the available ICI and DCN links. A mathematically equivalent sharding can perform very differently when it changes which collectives cross slice boundaries.
The official reference for chips, slices, topologies, cubes, and multislice connectivity is Google Cloud’s TPU system architecture guide.
The question: how much of a TPU compiler can we actually read?
For NVIDIA GPUs, a developer can inspect Triton, MLIR, LLVM’s NVPTX backend, PTX, and often final SASS. The TPU software stack has a different boundary.
TorchTPU makes a large and useful part of the path open:
1
2
3
4
5
6
7
PyTorch program
-> ATen dispatcher or TorchDynamo FX graph
-> TorchTPU deferred operations
-> StableHLO MLIR
-> PjRt client API
-> libtpu
-> TPU executable
The upper part is open source. The final compiler and machine interface are not:
1
2
3
4
5
6
7
8
9
10
11
open source closed/proprietary
─────────────────────────────────────┬─────────────────────────────
PyTorch │
TorchDynamo / FX │
TorchTPU backend │
StableHLO │
OpenXLA interfaces and many passes │
Pallas / Mosaic input dialect │
PjRt API │ libtpu
│ final TPU backend compilation
│ TPU ISA and machine code
That means this cannot be the same kind of instruction-by-instruction tour as the Triton-to-PTX post. We can follow a PyTorch operation all the way to StableHLO, the PJRT_Client_Compile boundary, and a serialized Mosaic custom call. We cannot inspect the production pass pipeline that converts those inputs into TPU machine instructions.
This distinction is the most important conclusion of the source search: the TPU-facing interface is open, but the final TPU backend is not.
What the TorchTPU paper contributes
The paper presents TorchTPU as a native PyTorch backend rather than a wrapper around JAX or the older lazy-tensor execution model. Its design goals are:
- normal PyTorch device semantics through
.to("tpu"); - useful eager execution instead of requiring full-graph compilation;
torch.compile(..., backend="tpu")through TorchDynamo;- PyTorch
ProcessGroupintegration for distributed collectives; and - access to optimized Pallas and library kernels when generated StableHLO is not sufficient.
The implementation is available at google-pytorch/torch_tpu. The repository is Apache-2.0 licensed and contains the PyTorch integration, eager runtime, deferred graph construction, StableHLO builders, compilation cache, PjRt calls, distributed backend, and custom-kernel glue.
The paper’s central architectural idea is hybrid eager/compiled execution: every PyTorch operation can behave eagerly, but TorchTPU still represents and compiles that operation through StableHLO. Multiple eager operations can also be deferred and fused into a larger compilation unit.
1. From TPU architecture to compiler IR
The programmer normally does not directly select an MXU instruction. Instead, the compiler receives tensor operations, layouts, shapes, sharding, and precision requirements, then maps them onto the MXU, vector and scalar units, memory hierarchy, and interconnect.
This makes high-level structure particularly important. StableHLO preserves operations such as:
1
2
3
4
5
6
dot_general
convolution
reduce
all_reduce
dynamic_slice
dynamic_update_slice
These are much closer to an ML graph than PTX instructions. The closed TPU backend can use tensor shape and operation semantics to select implementation strategies that would be difficult to recover from scalarized code.
One matmul, two compiler entry paths
For
\[C_{M \times N} = A_{M \times K} B_{K \times N},\]a framework graph normally reaches the TPU compiler as a whole-tensor operation:
func.func @matmul(
%a: tensor<128x256xbf16>,
%b: tensor<256x128xbf16>
) -> tensor<128x128xbf16> {
%c = stablehlo.dot_general %a, %b,
contracting_dims = [1] x [0]
: (tensor<128x256xbf16>, tensor<256x128xbf16>)
-> tensor<128x128xbf16>
return %c : tensor<128x128xbf16>
}
stablehlo.dot_general describes the contraction, shapes, and element types. It does not specify:
- how the matrices are tiled;
- which MXU configuration executes the dot;
- how tiles are distributed across TPU cores;
- where values reside in HBM, VMEM, or registers;
- how DMA overlaps with matrix computation; or
- which synchronization operations are required.
The TPU backend is responsible for those choices.
A custom Pallas kernel enters through a different path. The programmer provides a tiled kernel, memory references, a launch grid, and block mappings; Pallas then lowers that kernel to Mosaic.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
framework operation path
────────────────────────
JAX / PyTorch / TensorFlow
-> StableHLO / XLA HLO
-> graph optimization, fusion, layout, and partitioning
-> TPU backend
-> LLO
-> executable
custom kernel path
──────────────────
Pallas
-> JAXPR plus BlockSpecs and grid semantics
-> Mosaic MLIR
-> Mosaic TPU compilation
-> LLO
-> executable
Mosaic is therefore not a mandatory stage that every StableHLO operation passes through. The two paths are integrated into the same XLA/PjRt compilation, but serve different purposes:
- StableHLO lets the backend choose an implementation for a whole-tensor operation.
- Pallas/Mosaic lets a kernel author provide a more explicit execution and memory plan.
2. TorchTPU enters through PyTorch’s dispatcher
TorchTPU is implemented as a PyTorch PrivateUse1 device backend. ATen operations dispatched to a TPU tensor reach registrations such as:
csrc/eager/tpu_aten_kernels.cc
1
2
3
TORCH_LIBRARY_IMPL(aten, PrivateUse1, m) {
...
}
Instead of immediately running one hardware instruction, an eager operation creates a deferred representation associated with a TPU device buffer. The DeferredOp design is documented near device_buffer.h:86-90.
Operation-specific builders create StableHLO. For example, binary multiplication is connected to mlir::stablehlo::Mul in binary.cc:
1
TT_BINARY_BUILDER_(BuildMulShlo, mlir::stablehlo::Mul);
The useful mental model is:
1
2
3
4
5
aten::mul
-> TorchTPU PrivateUse1 kernel
-> deferred operation
-> StableHLO builder
-> materialization and compilation
This is still eager from the PyTorch user’s perspective, even though each operation passes through a compiler representation.
3. Eager execution is still compilation
The paper describes three user-facing eager behaviors:
- Strict eager: compile and launch operations individually;
- Debug eager: block so failures and stack traces are easier to localize;
- DeferAndFuse: accumulate operations until a materialization point and compile them together.
The C++ enum uses internal names including kDeferAndFuse, kDeferNever, and kDeferNeverAndLaunchBlocking (eager_mode.h:23-45).
DeferAndFuse waits until an operation requires a concrete result. Examples of materialization points include:
1
2
3
x.cpu()
x.item()
print(x)
At materialization, TorchTPU:
- walks the reachable deferred operations;
- determines which values remain live outputs;
- preserves side-effecting operations such as collectives;
- computes a compilation-cache key;
- reuses or compiles the StableHLO module; and
- enqueues the resulting executable.
The central implementation is Materialize(), with deferred-node discovery earlier in the same file.
The paper reports DeferAndFuse as at least 50% faster than strict eager in its tested cases, while also reducing peak HBM. The reason is familiar from GPU compilers: a larger graph enables fusion, removes intermediate materialization, and amortizes compilation and launch overhead.
The compilation cache is part of execution semantics
Eager compilation would be unusable if every repeated operation triggered a fresh compiler invocation. TorchTPU therefore uses a multi-tier cache:
- process-local memory;
- host shared memory; and
- an optional remote filesystem such as GCS.
The source contains the main CompilationCache and separate tier-two and tier-three implementations.
Shape, graph structure, compilation options, and software versions affect the key. This is why apparently small changes can cause a TPU recompilation:
- a new tensor shape;
- different compile options;
- a different deferred graph;
- changed TorchTPU, libtpu, or PjRt versions; or
- a dynamic shape that cannot reuse a bounded executable.
4. PyTorch views versus StableHLO SSA
PyTorch permits storage aliasing and views. Operations such as transpose, slice, expand, and as_strided can produce tensors that share underlying storage.
StableHLO is value-oriented SSA. It does not expose a general mutable as_strided storage view with arbitrary overlap. TorchTPU must therefore translate PyTorch’s storage semantics into functional tensor operations.
The paper describes view decomposition using combinations of:
1
2
3
4
5
6
transpose
reshape
broadcast
slice
concatenate
bitcast
A read reconstructs the logical view from its base tensor. A write applies an inverse transformation to produce a new base value, often using an operation conceptually similar to dynamic_update_slice, then updates the storage to refer to that new value.
This reveals a general compiler issue: a frontend’s semantics do not always fit the target IR directly. The backend must preserve user-visible behavior while expressing it in legal target operations.
Overlapping or broadcasted writes remain difficult because a functional SSA update needs an unambiguous mapping from view elements back to base storage.
The same functional model changes allocation. The paper says torch.empty does not immediately allocate TPU memory; it becomes a deferred NaN fill. Allocation is determined later by compilation and liveness rather than at the Python call site.
5. torch.compile: FX graph to one StableHLO program
TorchTPU registers a TorchDynamo backend named "tpu":
src/torch_tpu/_internal/compile/__init__.py:30-31
1
registry.register_backend(compiler_fn=TpuBackend(), name="tpu")
User code can therefore request:
1
compiled_model = torch.compile(model, backend="tpu")
TorchDynamo captures an FX GraphModule. TorchTPU traverses that graph while deferring all operations, producing one StableHLO compilation unit instead of materializing each eager operation. The C++ extraction path includes ExtractMlirFromGraph and TraverseAndCompile in compiled_mode.cc.
The paper explicitly explains why TorchTPU did not begin as a TorchInductor backend:
- eager and compiled execution can share the same StableHLO builders;
- XLA’s TPU optimization stack is mature;
- Triton’s thread/block programming model is designed around GPUs and is not a natural match for TPU execution; and
- one direct path avoids translating Inductor’s loop-level IR into another tensor compiler.
This does not mean Inductor-style scheduling is universally wrong. It means TorchTPU chose to preserve tensor operations and rely on the TPU compiler already behind PjRt.
Dynamic shapes remain a hard boundary
The current compiled path described by the paper forces dynamic=False. Bounded dynamism is under development:
- a symbolic size becomes a scalar tensor input;
- the physical tensor is padded to an upper bound;
- metadata records the logical dimension;
- XLA’s
DynamicPadderensures padded elements use the correct identity values; and - operations carry the logical size through the graph.
OpenXLA exposes the DynamicPadder pass, while TorchTPU contains its dimension-size operations in dynamism_ops.cc.
Padding enables executable reuse, but it can waste memory and compute. This is the familiar compiler tradeoff between shape specialization and generality.
6. The actual compilation boundary: PjRt
TorchTPU constructs a TPU PjRt client through:
csrc/pjrt/pjrt_client.cc:31-42
1
xla::GetCApiClient("tpu", ...)
Compilation then reaches functions such as Compile and CompileAndLoadMlirModule in compilation.cc.
PjRt defines a portable client/runtime contract. The open C API describes a program and a client compile request in:
xla/pjrt/c/pjrt_c_api.h:741-775
Conceptually:
1
2
3
4
5
6
7
PJRT_Program {
code
format
}
PJRT_Client_Compile(client, program, compile_options)
-> PJRT_LoadedExecutable
The TPU-specific header exposes GetPjrtApi():
That declaration is open; its production implementation is supplied by libtpu.
Why libtpu matters
The Python package depends on libtpu, configures its library path, and then uses the TPU PjRt plugin. libtpu is distributed as a binary package under Google Cloud terms rather than as an open-source GitHub repository.
Therefore:
1
2
3
4
5
6
7
8
9
StableHLO / Mosaic payload
│
│ open PjRt API
▼
libtpu binary
│
│ closed TPU optimization and code generation
▼
TPU executable using a proprietary ISA
The paper itself says the TPU ISA is proprietary, subject to change, and not publicly available. The final fusion, layout, scheduling, instruction selection, and machine-code generation pipeline cannot be followed in public source in the same way that LLVM NVPTX and PTX can.
This does not make the open code unimportant. It establishes and transforms the program that the closed compiler receives: operations, shapes, precision, sharding, dynamic bounds, custom calls, and collective structure.
7. Pallas and Mosaic: the custom-kernel path
StableHLO is designed for graph-level ML operations. A performance-critical kernel sometimes needs a lower-level programming model.
Pallas provides a Python kernel language in JAX. On TPU, Pallas lowers through Mosaic. The open source includes:
- Pallas tracing and lowering rules;
- the Mosaic TPU dialect’s operation/type definitions;
- serialization of a Mosaic module;
- a
tpu_custom_callwrapper; and - TorchTPU integration that exports a Pallas kernel for TPU.
The important path is:
1
2
3
4
5
6
7
8
Pallas Python kernel
-> JAXPR
-> Mosaic TPU MLIR
-> serialized MLIR bytecode
-> stablehlo.custom_call @tpu_custom_call
-> PjRt / libtpu
-> LLO
-> TPU executable
The serialized custom-call payload is how the Mosaic kernel is embedded in an outer StableHLO program. Conceptually, the kernel itself lowers toward LLO, while the custom call connects that kernel to the surrounding graph.
Pallas exposes concepts familiar to Triton programmers:
| Kernel concept | Triton | Pallas |
|---|---|---|
| Program instance | tl.program_id() | pl.program_id() |
| Load | tl.load() | Ref indexing or pl.load() |
| Store | tl.store() | Ref assignment or pl.store() |
| Tile mapping | Block tensors and pointer expressions | BlockSpec and Ref views |
| Launch space | Triton grid | pallas_call(..., grid=...) |
| TPU backend | Not applicable | Mosaic |
An illustrative tiled matmul has the following structure:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from functools import partial
import jax
import jax.numpy as jnp
from jax.experimental import pallas as pl
def matmul_kernel(x_ref, y_ref, output_ref, *, block_k):
accumulator = jnp.zeros(
(x_ref.shape[0], y_ref.shape[1]),
dtype=jnp.float32,
)
for k in range(x_ref.shape[1] // block_k):
x = x_ref[:, k * block_k : (k + 1) * block_k]
y = y_ref[k * block_k : (k + 1) * block_k, :]
accumulator += x @ y
output_ref[:, :] = accumulator.astype(output_ref.dtype)
kernel = pl.pallas_call(
partial(matmul_kernel, block_k=128),
out_shape=jax.ShapeDtypeStruct((512, 1024), jnp.float32),
in_specs=[
pl.BlockSpec((128, 256), lambda m, n: (m, 0)),
pl.BlockSpec((256, 256), lambda m, n: (0, n)),
],
out_specs=pl.BlockSpec((128, 256), lambda m, n: (m, n)),
grid=(4, 4),
)
The structure follows the official Pallas design’s templated matmul. It is illustrative rather than a portable tuned TPU kernel: supported block sizes, memory spaces, compiler parameters, and pipelining constraints depend on the TPU generation and JAX version.
JAX registers the custom-call primitive in tpu_custom_call.py and emits mlir.custom_call("tpu_custom_call", ...) around lines 466-478.
Pallas-to-Mosaic lowering is implemented in jax/_src/pallas/mosaic/lowering.py, with a table of operation lowering rules earlier in the file.
The Mosaic TPU dialect definitions now live in OpenXLA XLA under xla/mosaic/dialect/tpu/. The definitions include operations for reductions, stores, semaphores, and collectives.
The public Pallas design describes the lowering more precisely: Pallas primitives become mostly MLIR vector and arith operations, while BlockSpecs become Mosaic pipeline schedules (design.md:514-521). Mosaic then consumes that lower-level MLIR and emits TPU LLO.
TorchTPU exposes a Pallas bridge through torch.tpu.pallas.jax_op. Its source exports JAX code for the TPU platform:
TorchTPU can also build a tpu_custom_call carrying a base64-serialized Mosaic kernel in mosaic_custom_call.cc:65-78.
The Mosaic dialect is open; final TPU lowering is not
This distinction is easy to miss. The public dialect tells us what operations and types a Mosaic module may contain. The public JAX code shows how a Pallas program becomes that module and how it is serialized.
The public design states that Mosaic consumes mostly standard MLIR and emits TPU LLO. However, the complete production implementation that optimizes LLO and generates the TPU executable is not present in the pinned source trees examined for this article. The serialized payload crosses into libtpu, just like StableHLO.
Mosaic is therefore more analogous to an open target-facing IR than to a fully open LLVM-style hardware backend.
LLO: observable output from a closed compiler
OpenXLA’s documentation defines:
- HLO, the hardware-independent high-level optimizer; and
- LLO, the TPU-specific Low Level Optimizer responsible for execution on bare-metal TPU silicon.
The definition is public in docs/hlo_dumps.md:1-12. LLO is not LLVM IR, PTX, or a documented TPU assembly language. It is the lower-level representation used by the proprietary TPU backend.
There is an important distinction between observability and an open compiler implementation:
- users can request textual LLO dumps from a normal TPU compilation;
- some LLO categories expose original IR, post-register-allocation codegen, memory-space assignment, fingerprints, and program artifacts;
- there is no documented standalone
HLO -> LLOconversion library or stable public LLO API; and - the compiler source that creates and optimizes those dumps remains inside
libtpu.
On a TPU machine, OpenXLA documents:
1
export LIBTPU_INIT_ARGS="--xla_jf_dump_to=/tmp/llo_dumps"
The flag must be passed through LIBTPU_INIT_ARGS, not XLA_FLAGS (hlo_dumps.md:47-54). Categories can be restricted:
1
2
export LIBTPU_INIT_ARGS="--xla_jf_dump_to=/tmp/llo_dumps \
--xla_jf_dump_category_filter=original,codegen,msa,program"
The documented categories include original unoptimized LLO, code-generation and post-register-allocation artifacts, fingerprints, executable program outputs, and memory-space assignment (hlo_dumps.md:182-204).
Mosaic pass dumps are available separately:
1
export LIBTPU_INIT_ARGS="--xla_mosaic_dump_to=/tmp/mosaic_dumps"
This is also a LIBTPU_INIT_ARGS flag on TPU, as documented in hlo_dumps.md:414-432. These files are valuable for studying layout and pipeline transformations, but they are diagnostic dumps rather than a compatibility promise for a stable serialized compiler API.
The resulting public inspection surface is:
| Capability | Available? | Interface |
|---|---|---|
| JAX program to StableHLO text | Yes | jax.jit(...).lower(...).as_text() |
| HLO before and after optimization | Yes | XLA_FLAGS=--xla_dump_to=... |
| Pallas to Mosaic intermediates | Yes, on TPU | --xla_mosaic_dump_to through LIBTPU_INIT_ARGS |
| Normal StableHLO compilation to TPU executable | Yes, on TPU | XLA/PjRt through libtpu |
| LLO diagnostic dumps | Yes, on TPU | --xla_jf_dump_to through LIBTPU_INIT_ARGS |
| Supported standalone HLO-to-LLO conversion API | No documented API | Internal TPU backend |
| Public TPU ISA or stable assembly format | No | Proprietary |
8. Inspect StableHLO without owning a TPU
The open frontend and IR can be explored on a CPU machine. This example asks JAX to lower a matrix multiplication and prints the StableHLO module:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import jax
import jax.numpy as jnp
@jax.jit
def matmul(a, b):
return a @ b
a = jnp.ones((64, 32), dtype=jnp.bfloat16)
b = jnp.ones((32, 128), dtype=jnp.bfloat16)
lowered = matmul.lower(a, b)
print(lowered.as_text())
The relevant operation resembles:
%0 = stablehlo.dot_general %arg0, %arg1,
contracting_dims = [1] x [0]
: (tensor<64x32xbf16>, tensor<32x128xbf16>)
-> tensor<64x128xbf16>
This proves only the frontend lowering. Running it with a CPU JAX installation does not invoke the TPU backend or reveal TPU machine instructions.
Inspect a Pallas kernel and run it in interpretation mode
A small Pallas add kernel can run through the interpreter on CPU:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import jax
import jax.numpy as jnp
from jax.experimental import pallas as pl
def add_kernel(x_ref, y_ref, output_ref):
output_ref[...] = x_ref[...] + y_ref[...]
def add(x, y):
return pl.pallas_call(
add_kernel,
out_shape=jax.ShapeDtypeStruct(x.shape, x.dtype),
interpret=True,
)(x, y)
x = jnp.ones((8, 128), dtype=jnp.float32)
print(add(x, x))
Removing interpret=True and exporting for platforms=["tpu"] can produce a StableHLO module containing stablehlo.custom_call @tpu_custom_call, whose backend configuration carries serialized Mosaic MLIR. That export still does not generate a TPU executable; libtpu performs the unavailable final compilation.
9. Distributed execution exposes MPMD versus SPMD
TorchTPU integrates collectives through PyTorch’s c10d::Backend and lowers them to StableHLO collective operations. Unlike CUDA, there is no NCCL layer separate from the TPU compiler.
The difficult part is the mismatch between:
- MPMD PyTorch execution: each process can independently reach a collective; and
- SPMD TPU compilation: all participating devices must agree on one globally consistent program.
If different ranks compile different collective structures, execution can deadlock or corrupt memory.
TorchTPU’s conservative default uses skinny collectives: compile each collective as a small separate StableHLO module. The paper reports a 30–40% end-to-end cost for this safety.
The @spmd_safe mechanism marks a region whose processes are expected to execute the same structure:
This can fuse collectives with surrounding computation, but correctness now depends on the user’s SPMD claim. The paper also discusses a compile handshake as a future safer mechanism.
10. What is open source, exactly?
| Layer | Open? | What can be inspected |
|---|---|---|
| PyTorch, ATen, Dynamo, FX | Yes | Capture, dispatch, graph breaks, decompositions |
| TorchTPU | Yes | Eager runtime, deferred ops, StableHLO builders, cache, distributed integration |
| StableHLO | Yes | ML operation semantics and serialization |
| OpenXLA XLA | Largely yes | HLO infrastructure, PjRt APIs, many generic transformations |
| Pallas frontend | Yes | Kernel tracing and operation lowering |
| Mosaic TPU dialect | Yes | TPU-facing MLIR operations, types, and serialization |
| TPU PjRt interface | Yes | Client/plugin API contract |
libtpu implementation | No public source | Production TPU compiler and runtime plugin |
| LLO diagnostic output | Inspectable, not an open implementation | Text dumps from libtpu; no stable standalone conversion API |
| TPU ISA | No | Proprietary machine interface |
| Final TPU executable | Opaque | Loaded and executed through the runtime |
OpenXLA contains real compiler infrastructure, but its open tree should not be mistaken for the complete production TPU backend. An open API declaration such as PJRT_Client_Compile tells us how compilation is requested, not how the TPU compiler implements fusion, layout, scheduling, or instruction selection.
Likewise, an open Mosaic operation definition tells us what an input program can express. LLO dumps can reveal what the closed compiler produced, but not the source implementation that selected and optimized those operations.
A GPU/TPU compiler comparison
| Layer | NVIDIA GPU path | TPU path |
|---|---|---|
| Framework IR | FX, StableHLO, or framework graph | FX, StableHLO, or XLA HLO |
| Custom-kernel DSL | Triton | Pallas |
| Kernel-oriented IR | TTIR and TTGIR | Mosaic MLIR |
| Lower-level compiler form | LLVM IR and PTX | LLO diagnostic representation |
| Machine instructions | SASS | Proprietary TPU ISA |
| Public final backend source | LLVM NVPTX is open; NVIDIA ptxas is closed | Production TPU backend in libtpu is closed |
This comparison is approximate rather than a claim that the layers are isomorphic. PTX is a documented virtual ISA, while LLO is a compiler-internal TPU representation exposed through diagnostic dumps.
11. Source-reading map
The following paths provide a practical tour:
| Question | Source |
|---|---|
| How is the Dynamo backend registered? | compile/__init__.py:30-31 |
| Where do ATen TPU kernels enter? | tpu_aten_kernels.cc:375 |
| Where is a deferred operation associated with a buffer? | device_buffer.h:86-90 |
| How does an operation become StableHLO? | binary.cc:65 |
| Where does eager graph materialization happen? | materialize.cc:690-735 |
| How does an FX graph become MLIR? | compiled_mode.cc:298-356 |
| Where is the TPU PjRt client obtained? | pjrt_client.cc:31-42 |
| Where does TorchTPU submit MLIR compilation? | compilation.cc:239-280 |
| What does the open PjRt compile API contain? | pjrt_c_api.h:741-775 |
| How does Pallas lower toward Mosaic? | pallas/mosaic/lowering.py |
| How are Pallas blocks turned into Mosaic schedules? | Pallas design:514-521 |
| How is a Mosaic kernel wrapped as a custom call? | tpu_custom_call.py:466-478 |
| Which TPU operations does the open Mosaic dialect define? | xla/mosaic/dialect/tpu/ |
| How can HLO, LLO, and Mosaic passes be dumped? | docs/hlo_dumps.md |
The final lowering has no corresponding public implementation source file, although it can emit LLO diagnostics:
1
2
3
4
5
StableHLO or Mosaic
-> PJRT_Client_Compile
-> libtpu
-> LLO diagnostics, when dump flags are enabled
-> proprietary TPU executable
12. Results reported by the paper
The paper reports broad framework coverage and large-scale results:
- 4,821 of 4,917 Hugging Face model tests completed without crashing;
- 638 of 657 tested models met the paper’s numerical-parity criterion;
- Muse Glimmer 30B reached 59% MFU for single-chip prefill;
- Qwen3 MoE 235B reached 28.8% MFU on 1,024 TPU v7 chips and near-flat weak scaling through 16,384 TensorCores;
- FLUX.1-dev improved from 11.49 seconds per step in eager mode to 3.02 seconds with
torch.compile, then 2.78 seconds with additional peephole rewrites; and - TorchRec reached parity with the cited JAX baseline on SparseCore.
These figures establish that the architecture can support real workloads, but they should be interpreted carefully:
- the authors report the results;
- the article does not independently reproduce them;
- model “coverage” includes a no-crash tier and tolerance-based numerical checks rather than identical outputs;
- optimized Pallas and library kernels contribute substantially to peak performance; and
- the paper does not provide a complete ablation against PyTorch/XLA or every alternative backend.
13. Current limitations
The paper identifies or implies several constraints:
- bounded dynamic shapes are still under development;
- compiled mode currently forces static specialization;
- one process is used per TPU device;
- MPMD collective safety remains difficult;
- skinny collectives impose a reported 30–40% cost;
- overlapping or broadcast view writes are unsupported;
- FlexAttention was not supported in the reported TorchTitan port;
- custom Pallas or library kernels remain important for peak performance;
- the final backend source and TPU ISA are unavailable, even though LLO diagnostics can be dumped; and
- the codebase and paper are evolving rapidly.
The paper’s v4 architecture is therefore a snapshot, not a finished static contract.
Closing perspective
TorchTPU demonstrates that “eager” and “compiled” do not need to be opposing execution models. Strict eager can compile one deferred StableHLO operation at a time, DeferAndFuse can compile a short region, and torch.compile can hand the same infrastructure an entire FX graph.
The source-visible path is:
1
2
3
4
PyTorch ATen or FX
-> TorchTPU deferred operations
-> StableHLO
-> PjRt API
The custom-kernel path is:
1
2
3
4
Pallas
-> Mosaic TPU MLIR
-> tpu_custom_call
-> PjRt API
Both paths then cross the same boundary:
1
2
3
4
PjRt
-> libtpu
-> LLO
-> proprietary TPU executable and ISA
That boundary determines what open-source compiler engineers can study. We can inspect PyTorch semantics, graph capture, StableHLO construction, deferred materialization, caching, dynamic-shape encoding, collectives, and Mosaic payload generation. We can also request LLO and Mosaic diagnostic dumps from the closed compiler. We cannot inspect the implementation that performs final TPU instruction selection or machine-code generation.
For practical learning, the best approach is therefore:
- print StableHLO from a small operation;
- trace its TorchTPU builder and materialization path;
- inspect the PjRt compile request;
- build a Pallas kernel and inspect its Mosaic custom call; and
- on a TPU machine, compare HLO, Mosaic, and LLO dumps while treating their producing
libtpuimplementation as a closed boundary.