From CUDA and Jax to TorchTPU: Lessons from a Cayley Graph Solver

Hacker News by 19 min read 509x views
From CUDA and Jax to TorchTPU: Lessons from a Cayley Graph Solver

Share Post

Main image

Some period ago, I shared a blog post concerning operating alongside Cayley graphs, anywhere I solved combinatorial puzzles using AI coding agents, PyTorch on GPUs, and JAX on TPUs. Recently, Google released TorchTPU, a native PyTorch backend for TPUs, and I wanted to see how fine it plant on the identical task: whether a PyTorch-native TPU stack could equivalent my A100 training pipeline and my JAX beam hunt in speed and resolution quality, or perchance equal attack them.

The abbreviated version: getting TorchTPU to activity was easy; getting it to activity efficiently was considerably harder. My first training harbor was 1.65x slower than the A100 implementation, during the archetypal TPU beam hunt was 5.7x slower than its JAX counterpart.

After optimizing enthusiastic execution, rewriting attention, eliminating energetic tensor shapes, fixing a subtle deduplication bug, and examining an attention-routing regression, the results changed substantially. Training reached comparable wall-clock achievement to the A100, and the optimized TorchTPU beam hunt became 25% faster per flat than JAX on the identical eight-chip v6e machine, producing the identical total resolution dimension throughout six test puzzles.

Along the way, the inquiry improved the solver itself and caused an upstream TorchTPU GitHub issue that led to attention-routing fixes.

The code is accessible on Kaggle notebooks operating on a liberated TPU v5e-8:

As in the former post, the code and the experiments were done by coding agents (Claude Code and Codex): I decided what to port, what to measure, and how to fairness the results, and they did the implementation and the profiling.

The problem

The CayleyPy Professor Tetraminx competition requires finding the shortest sequence of moves that solves 1000 scrambled puzzles. Formally, it is a shortest-path issue in a Cayley chart (each puzzle province is a node, and all of the 24 imaginable moves is an edge) alongside an 88-sticker state.

My solver uses beam hunt guided by a learned neural heuristic — a 3.4M-parameter PieceTransformer. Instead of treating the 88 stickers individually, it groups them into 50 bodily pieces, turns all part into a token, adds a category token (51 tokens in total), and runs four small transformer layers alongside eight heads of size 32. At the end, an all-neighbours Q caput (a caput that predicts, for all of the 24 moves, the extend to solved following that move) outputs 24 numbers. So the beam scores all 24 children of a province alongside one onward continue on the parent.

For training, the indication is a mix of cheap random walks and exact dirt truth:

  • Random walks of 2–40 moves from the solved state. A province p moves into a stroll has two known labels: undoing the final move gives extend p - 1, and continuing the stroll gives p + 1.
  • Exact 24-way labels from a breadth-first hunt (BFS) array at degree 5 or less.
  • The puzzle’s 24 spatial symmetries, used as data augmentation.

On the A100, one era takes 142.7 seconds. My finest checkpoint is era 1500 of a 2000-epoch run, concerning 80 hours in total.

What is TorchTPU

Training speed on 4x TPU v6e vs the A100

TorchTPU is not PyTorch/XLA: there is no LazyTensor tracing, no xm.mark_step(), and no xla_device(). Instead, TorchTPU lowers ATen ops immediately to StableHLO and runs through PJRT and libtpu (PyTorch’s center ops are translated direct into XLA’s input format and executed by the TPU runtime). Once you import torch, "tpu" plant as a equipment cord fair akin "cuda".

It has three implementation modes:

  • Eager (the default): runs one op at a period asynchronously.
  • Fused enthusiastic (TORCH_TPU_DEFER_AND_FUSE=1): defers ops and fuses them throughout op boundaries without needing torch.compile.
  • Compiled (torch.compile(fn, dynamic=False)): chart compilation targeting the TPU backend.

Three rules matter in practice:

  • Static shapes were the dependable path: alongside the TorchTPU builds and operators I used, fixed tensor shapes and torch.compile(..., dynamic=False) worked best, and all new form meant a complete recompile.
  • Data-dependent output sizes were the most expensive: ops akin nonzero, masked_select, unique, bincount, and equal x[bool_mask] motionless run in enthusiastic mode, but they power a .cpu().item() presenter round-trip to study their output size, and a compiled chart gets specialized to that one size, so all new size method another compile.
  • Nothing falls rear silently to the CPU: an op that TorchTPU doesn’t execute raises an error alternatively of quietly operating slowly.

Part 1: training, from 1.65x slower to 1.08x faster

I ran the archetypal harbor on a Cloud TPU device alongside four v6e chips, using DDP alongside one procedure per part and a earth lot of 512, so all era saw exactly the identical figure of samples as on the A100. Before the code could run on the TPU at all, I had to eliminate four GPU idioms (masked_select in the loss, boolean-mask indexing whenever expanding labels, 12 .item() metric says per step, and sampling training anchors on the CPU alternatively of keeping the 0.19 GB anchor array in TPU memory). This archetypal operating type took 234.8 seconds per epoch, 1.65x slower than the A100. I was capable to bring it downward to 132 seconds alongside two changes.

Training speed on 4x TPU v6e vs the A100

Fused eager

The archetypal win was practically free: turning on fused enthusiastic (TORCH_TPU_DEFER_AND_FUSE=1). Only the model’s onward and backward continue ran under torch.compile; the remainder of the trainer (the random-walk sampler alongside its 40-iteration loop, tag expansion, the loss, and the metrics) ran in enthusiastic mode, one op at a time. In default enthusiastic mode, that data pipeline took 61.3 ms per step. Wrapping it in torch.compile brought it downward to 29.7 ms, during fused eager, which fuses the ops at run period without any code changes, got it to 13.1 ms. The pipeline is many small ops, and on this workload they fused improved than they compiled; I didn’t overview why, since the cheaper choice was additionally the faster one. Setting that sole surroundings changeable dropped the era period from 234.8 s to 176.5 s.

The notice rewrite that was nearly thrown away

Still, 176.5 s was slower than the A100, and the GPU overview didn’t help. On the A100, the input phase and embedding gradient took 67% of the step; on the TPU, the identical phase took lone 0.96 ms (0.8%), and the example was spending ~90% of its period in attention.

A roofline at the model’s own shapes explained why. A quadrate 8192³ GEMM hits 361 TFLOP/s on one v6e chip, and the model’s QKV and FFN GEMMs hit 212–259 TFLOP/s, during notice ran at 3.0 TFLOP/s. With T = 51 and head_dim = 32, all notice matmul is 51x32x51 on a 128x128 matrix component (MXU) — approximately 2.5% tile occupancy. Padding head_dim to 128 or T to 64 really made things slower (0.83x and 0.81x). As a result, notice is concerning 3% of the model’s FLOPs but concerning 90% of its period on the TPU.

Achieved TFLOP/s per procedure on one TPU v6e chip

If you desire to keep the identical example (for a fair comparison), you need to keep the identical shapes and discover another improvements. Standard scaled_dot_product_attention (SDPA) expects (B, H, T, Dh), so the QKV tensor have to be permuted to move the heads to the second dimension. Rewriting notice alongside torch.einsum keeps the heads in their first size and avoids the permutes:

q, k, v = qkv.view(B, T, 3, H, Dh).unbind(2) # heads never depart dim 2 s = torch.einsum("bthd,bshd->bhts", q, k) * scale p = s.float().softmax(-1).to(v.dtype) # fp32 softmax, on purpose a = torch.einsum("bhts,bshd->bthd", p, v) 

The fp32 softmax is there for numerics. On the TPU, the einsum and SDPA versions disagreed by a related 3.3e-3, so I checked the two against a float64 citation on the CPU: the two were concerning 4.6e-3 distant from it, since the TPU’s matrix component uses a single-pass bf16 multiply equal for “fp32” matmuls unless you lift torch.tpu.precision. In bf16, keeping lone the softmax in fp32 closed the remaining gap between the two versions.

This alter was nearly rejected. The delegate archetypal measured it on the onward continue only, anywhere it looked slower (einsum 5.51 ms vs SDPA 4.56 ms), and abandoned it on that basis. Thankfully, I decided to inspect the complete forward+backward pass: the profiler attributed much of the backward-pass overhead to layout conversions about SDPA’s saved tensors, which disbursal far additional than the onward continue saved. Across forward+backward, one tier dropped from 25.14 ms to 14.85 ms (1.69x faster). That pushed the entire era downward to 132.0 s — 1.08x faster than the A100.

A checkpoint alongside deadlocks

The most confusing bug was in checkpointing. Saving a checkpoint lone from position 0 is a norm pattern:

if is_main: torch.save(model.state_dict(), path) # deadlocks under fused enthusiastic + DDP 

Under fused eager, the tensors in state_dict are motionless deferred. When position 0 says them, it executes a chart that includes this step’s DDP collectives, during the another ranks are already waiting at the next barrier. The checkpoint document would develop to 1.1 MB, afterward 2.2 MB, and freeze everlastingly during all position sat busy. The fix is to move the tensors to the CPU on all position and compose the document on one:

cpu_state = {k: v.detach().to("cpu") for k, v in model.state_dict().items()} # all ranks if is_main: torch.save(cpu_state, path) 

The trap lone fires in the manner that gives the speedup, which made it harder to find.

Summary of training changes

What changed Why it mattered on TPU Impact
masked_select / x[bool_mask] → anywhere / scatter_ Avoids data-dependent output sizes, presenter syncs, and recompiles Required for fixed graphs
12 .item() says → equipment accumulator; presenter anchors → HBM Eliminates per-step chart cuts and cpu transfers (0.19 GB table) Clean async execution
TORCH_TPU_DEFER_AND_FUSE=1 Fuses small enthusiastic ops in the sampler, loss, and metrics 1.33x faster epoch
attn_impl="einsum" (training only) Avoids layout conversions about SDPA’s saved tensors in the backward pass 1.34x faster epoch
Materialize state_dict on all ranks Prevents deferred DDP collectives from deadlocking position 0 Fixes checkpoint hang
Same validation size in fume test and complete run Avoids a 28736-row validation chart OOM at era 25 Unblocked the Kaggle complete run

Training results

Configuration (4x TPU v6e) Seconds per epoch vs A100 (142.7)
first operating port 234.8 1.65x slower
+ fused eager 176.5 1.24x slower
+ einsum attention 132.0 1.08x faster

On Kaggle’s liberated v5e-8 (eight chips, 64 samples per chip), the training notebook run 186 epochs in 7.41 hours, alongside a median of 142.4 seconds per epoch against the A100’s 144.2 complete the identical epochs.

Training defeat and top-1 accuracy, TPU v5e-8 vs A100

Over epochs 177-186, the training defeat averaged 15.131 on the v5e-8 and 15.132 on the A100, and top-1 accuracy was 0.488 against 0.483. On exact labels, the TPU checkpoint at era 186 is on par alongside the A100 checkpoint at era 200: its finest predicted move is really optimal for 99.0% of states, against 98.9%. The finest checkpoint trained eight times longer and is motionless better.

Part 2: beam search, archetypal attempt

With training done, the second fractional was porting my beam hunt solver (KhoruzhiiSolver, the CUDA beam searcher from the former post) to TorchTPU. Training needed targeted fixes; the solver needed a rewrite. It relied on torch.unique for deduplication, boolean-mask indexing, and energetic tensor shapes (cand.index_select(0, unique_pos[:B])), none of which plant fine on a TPU.

So I wrote beam_tpu.py from scratch in clean PyTorch alongside fixed shapes throughout all step. Instead of dropping duplicates, I kind candidates by hash, emblem neighboring matches, and allocate copy scores +inf so topk merely never picks them:

sort_h, sort_idx = h.sort() dup_sorted = torch.cat([no, sort_h[1:] == sort_h[:-1]]) dup = dup_sorted[sort_idx.argsort()] score = torch.where(dup | ~valid, BIG, score) 

To portion a 1M-wide beam throughout chips, all part holds an equal portion of the beam slots, and a child’s owner part is resolute by its hash. Every stage runs the Q-head onward on local parents, routes children to their owners via all_to_all_single, deduplicates globally on all owner, and runs topk for the next level. States are stored as int8, and the tree bookkeeping stays exterior the compiled stage so the flat oppose doesn’t trigger a recompilation.

 score, hash, route, deduplicate, top-k, endgame check

The hunt doesn’t go all the way to the solved state: it stops as shortly as a beam province appears in the exact depth-6 BFS array (27.8M states), and the array supplies the optimal final six moves. In the archetypal TorchTPU version, this endgame rear (a Zobrist hash and a searchsorted complete the array for all level, all ending in .item()) ran as enthusiastic ops on the TPU and took ~176 s following a 73 s solve. The JAX controller had continually done it in NumPy on the host, so I did the same: identical moves on 3000 checked states, at under a millisecond per state. Running the example complete fixed-size chunks inner a sole scan didn’t alter the stage speed, but it kept one copy of the example in the compiled chart alternatively of one per chunk, shrinking the cached compiled code from 363 to 162 MiB.

I archetypal tested an August pre-release of TorchTPU on six difficult scrambles (1M beam, 4x v6e). It matched my JAX kernel on way dimension (186 vs 185 moves, all way replay-verified) but was 5.7x slower (1973 s vs 345 s). The overview showed that cross-chip all_to_all disbursal lone 0.6 ms per step, during example conclusion took ~83% of the time. Then I moved to the community torch_tpu==0.2.0 on Kaggle, and the results were surprising: the gap narrowed to 2.8x per beam level, but norm dropped, alongside TorchTPU finding 194 moves anywhere JAX reproduced its 185.

When a backend alter exposed an algorithmic bug

Because Kaggle has a lengthy TPU queue, I moved to Cloud TPU v6e to debug the 8 moves misplaced between the pre-release (186) and 0.2.0 (194). Two things had changed in 0.2.0: torch.topk had reverted from a stable tie-breaking command rear to an unstable default, and bf16 notice on sequence lengths that are not a multiple of 128 no longer ran the entire component in fp32 (more on notice below).

On eight v6e chips, forcing the old low-index tie-breaking in topk took 0.2.0 from 193 moves rear to 187, the pre-release’s figure there. But why should tie-breaking alter way dimension at all? On four chips, all fixed tie command I tried (lowest indicator first, highest first, a random shuffle) gave 185 moves; lone 0.2.0’s native command gave 188. Something in the beam was turning tie command into way length, and that item was my deduplication.

How the old and fixed dedup choose between two copies of the identical state

Because the Q caput scores children from the parent, a province reached from two parents arrives as two copies alongside distinct scores. My dedup sorted candidates by hash and kept the archetypal copy in all run, and since torch.sort is unstable on the two builds, “first” was whichever copy the backend remaining in front. When 0.2.0 changed the tie order, fine states started to disappear since their worse copy survived. JAX’s dedup uses a stable argsort on score-sorted buckets, so it keeps the improved copy.

Replacing “keep first” alongside a segment-min complete (score, index) (so duplicates continually keep their finest score) added 0.5% overhead and fixed the issue:

Configuration 4x v6e 8x v6e 8x v5e (Kaggle)
0.2.0, old dedup 188 193 194
0.2.0, best-copy dedup 184 185 185
Pre-release, best-copy dedup 184 185 —

On ten additional puzzles, this fix cut total moves from 319 downward to 302, improving seven of them and worsening none.

Flash notice and the GitHub issue

One regression really was TorchTPU’s: on the identical chips, 0.2.0 ran a beam flat 1.7x slower than the pre-release. Timing all part of a flat separately showed that everything apart from notice was as accelerated or faster in 0.2.0. The logic was routing: 0.2.0 sends abbreviated notice shapes to its Flash notice kernel, which pads the 51-token sequence to a 128-token tile, so 84% of all mark tile is padding. Turning Flash off alongside torch.backends.cuda.enable_flash_sdp(False) puts notice rear on the plain XLA way (yes, .cuda. — TorchTPU respects PyTorch’s norm SDPA backend switches, which live under torch.backends.cuda):

Single v6e chip 0.1.1.dev20260824 0.2.0 (Flash on) 0.2.0 (Flash off) Nightly 2026-11-04
bf16 notice call (8192, 8, 51, 32) 9.8 ms 50.3 ms 7.3 ms 7.3 ms
Model onward (16 chunks in scan) 1.67 s 3.52 s 0.64 s 0.68 s
One beam flat (real search) 2.21 s 3.74 s 0.93 s 0.98 s

With Flash off, a complete beam flat is 4x faster than alongside 0.2.0’s default and 2.4x faster than the pre-release. The 2026-11-04 nightly, which already routes abbreviated sequences distant from Flash, is as accelerated as the workaround.

Flash notice tile padding at 51 tokens and per-level beam period by TorchTPU build

Two things hid this at first. The --fp32-attn arm that I added to test notice precision motionless went through Flash, so it lone made things slower. And PyTorch’s AOTAutograd cache is keyed on the graph, not on the notice backend flag, so a second procedure quietly reused the Flash-compiled chart and reported identical times until all run got its own cache directory.

My delegate wrote up the measurements and reported the issue to the TorchTPU repository alongside a Colab reproduction and a array of notice timings throughout caput sizes and sequence lengths. It turned out that the short-sequence fix had already landed on chief three days following 0.2.0 was tagged, but it hadn’t been released. The study additionally noted that a newer routing regulation on chief would create several 128–256-token shapes slower. The TorchTPU squad picked it up, merged a sequence of attention-routing fixes, and closed the matter on November 21.

Attention call time: Flash vs StableHLO

Milliseconds per SDPA call on one TPU v6e chip, TorchTPU 0.2.0 · lesser is better

Head dim:

Flash (0.2.0 default) StableHLO (Flash off)

bf16, 8 heads, sequence dimension × lot rows fixed at 417792 tokens per call. Source: torch_tpu matter 6304.
Data table
Head dimTokensFlash, msStableHLO, ms
325150.307.25
326441.376.47
3212818.113.41
3225612.062.78
325128.975.08
3210249.1111.86
645150.7811.35
646441.8410.23
6412818.756.70
6425612.7111.88
645129.609.86
6410249.8334.90
1285151.278.53
1286436.335.28
12812815.0724.76
1282568.9221.42
1285125.5722.70
12810246.1039.37

Summary of beam hunt changes

Component GPU / first approach TPU rewrite and fix
Deduplication torch.unique + energetic indexing Sort by hash, mark dups +inf; segment-min keeps the best-scored duplicate
Cross-chip beam Dynamic per-rank pools Hash-based owner project + all_to_all_single (0.6 ms/step)
State and hash memory int64 tensors int8 states; a cheap dot-product hash for all children, the endgame table’s Zobrist hash (a norm XOR-based hash for equivalent states) lone for the survivors
Model chunking Unrolled chunks scan complete fixed chunks (cached chart 363 → 162 MiB)
Endgame rear and hit check Eager TPU searchsorted; all_reduce Host NumPy rear (176 s → negligible); all_gather + presenter min
0.2.0 notice routing Default Flash kernel (padded to 128) enable_flash_sdp(False) until a publish alongside the fix (PR 6759 and connected routing changes)

Beam hunt results

With the dedup fixed and Flash turned off, I reran the difference on one eight-chip v6e device alongside the community torch_tpu==0.2.0 and JAX 0.11.0 (the type in Kaggle’s TPU image).

Eight v6e chips JAX TorchTPU, Flash off TorchTPU, Flash on (0.2.0 default)
moves, six scrambles 185 185 185
seconds per beam level 1.27 1.02 3.95
median seconds per scramble 31.6 28.3 110.3
whole process, including compilation 310 277 744

TorchTPU now runs a beam flat 1.25x faster than JAX alongside the identical quality.

On Kaggle’s v5e-8, the image is closer. TorchTPU alongside Flash off is motionless concerning 10% faster per beam level, but the median scramble takes slightly longer (49.9 vs 48.7 s), since it checks the hit emblem lone all four levels and runs additional levels, and it established one move additional (186 vs 185):

Eight v5e chips (Kaggle) JAX TorchTPU, Flash off TorchTPU, Flash on (0.2.0 default)
moves, six scrambles 185 186 185
seconds per beam level 1.97 1.79 5.48
median seconds per scramble 48.7 49.9 153.4

 JAX vs TorchTPU alongside Flash on and off

JAX remains my chief beam hunt resolution for now as I have yet to run TorchTPU on a wider beam. And the investigations helped shove the JAX kernel further: bounding impermanent buffers reduced the compile-time recollection for a 128M beam from 39.5 to 12 GiB per chip, and a 256M-state beam plant on eight v6e chips.

A100 vs TPU: the differences that mattered

  A100 + CUDA TPU + TorchTPU
getting started .to("cuda") .to("tpu"), the backend loads alongside import torch
default execution eager, kernels launched asynchronously eager, one op at a time; fused enthusiastic is one surroundings changeable away
torch.compile optional, energetic shapes are fine dynamic=False, one compile per shape
data-dependent sizes (nonzero, unique, x[mask]) fine host round-trip and a recompile per distinct size
.item() in the loop a sync a sync that additionally ends the deferred graph
attention at 51 tokens, caput size 32 flash attention, no problem ~2.5% matrix component occupancy, the foremost cost
hotspot of this model input phase (67%) attention (~90% of example time)
“fp32” matmul fp32/TF32 single-pass bf16 unless torch.tpu.precision is raised
rank-0-only work fine must not materialize item the another ranks additionally need
tie command of topk / sort stable at these sizes (measured) not guaranteed and changed between builds
unimplemented op rare raises an error, no silent CPU fallback

Conclusions

I started this test to see whether TorchTPU could substitute my A100 + JAX setup, and on this project it can: the identical example trains at the A100’s speed or slightly faster, and the beam hunt matches JAX on norm and is a bit faster per level.

However, a native PyTorch API does not eliminate the need for hardware-aware engineering. Static shapes, deferred execution, tensor layouts, compilation caching, and kernel choice all mattered considerably. Optimizations that helped training did not necessarily assistance inference, and apparently insignificant changes in backend behavior exposed a latent bug in my hunt algorithm.

The immigration additionally improved the two implementations: fixing deduplication reduced resolution lengths, the notice inquiry contributed to upstream TorchTPU improvements, and revisiting recollection administration enabled larger beams in JAX.

More broadly, this project demonstrated how AI coding agents can act in experimental engineering fairly than merely code generation. Claude Code and Codex implemented substitute approaches, profiled execution, constructed controlled experiments, investigated regressions, and prepared reproducible bug reports. My function was to formulate hypotheses, choose meaningful metrics, inquiry misleading measurements, and decide which trade-offs were acceptable.

blogpost pytorch tpu jax cayley kaggle

Share this:

Other Article Hacker News
↑
Close Right Ads
Close Left Ads