{"slug": "from-cuda-and-jax-to-torchtpu-lessons-from-a-cayley-graph-solver", "title": "From CUDA and JAX to TorchTPU: Lessons from a Cayley Graph Solver", "summary": "A Cayley graph solver ported from PyTorch on A100 GPUs and JAX on TPUs to Google's newly open-sourced TorchTPU backend initially ran 1.65x slower in training and 5.7x slower in beam search than the JAX version, but after optimizing eager execution, rewriting attention, eliminating dynamic tensor shapes and fixing a deduplication bug, the TorchTPU beam search became 25% faster per level than JAX on the same eight-chip v6e machine, producing the same total solution length across six test puzzles. The investigation also produced an upstream TorchTPU GitHub issue (google-pytorch/torch_tpu #6304) that led to attention-routing fixes. The 3.4M-parameter PieceTransformer solver, built for the CayleyPy Professor Tetraminx competition's 1000 scrambled puzzles, was implemented by coding agents Claude Code and Codex, with training reaching comparable wall-clock performance to the A100's 142.7 seconds per epoch.", "body_md": "## From CUDA and JAX to TorchTPU: Lessons from a Cayley Graph Solver\n\nSome time ago I shared a [blog post](https://andlukyane.com/blog/cayleypy-kaggle-with-claude) about working with Cayley graphs, where I solved combinatorial puzzles using AI coding agents, PyTorch on GPUs, and JAX on TPUs. Recently, Google [released](https://cloud.google.com/blog/topics/ai-infrastructure/torchtpu-is-now-open-source-run-native-pytorch-on-tpus) TorchTPU, a native PyTorch backend for TPUs, and I wanted to see how well it works on the same task: whether a PyTorch-native TPU stack could match my A100 training pipeline and my JAX beam search in speed and solution quality, or maybe even beat them.\n\nThe short version: getting TorchTPU to work was easy; getting it to work efficiently was considerably harder. My initial training port was **1.65x** slower than the A100 implementation, while the first TPU beam search was **5.7x** slower than its JAX counterpart.\n\nAfter optimizing eager execution, rewriting attention, eliminating dynamic tensor shapes, fixing a subtle deduplication bug, and investigating an attention-routing regression, the results changed substantially. Training reached comparable wall-clock performance to the A100, and the optimized TorchTPU beam search became **25% faster** per level than JAX on the same eight-chip v6e machine, producing the same total solution length across six test puzzles.\n\nAlong the way, the investigation improved the solver itself and resulted in an upstream TorchTPU GitHub [issue](https://github.com/google-pytorch/torch_tpu/issues/6304) that led to attention-routing fixes.\n\nThe code is available on Kaggle notebooks running on a free TPU v5e-8:\n\nAs in the previous 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 judge the results, and they did the implementation and the profiling.\n\n### The problem\n\nThe [CayleyPy Professor Tetraminx](https://www.kaggle.com/competitions/cayley-py-professor-tetraminx-solve-optimally) competition requires finding the shortest sequence of moves that solves 1000 scrambled puzzles. Formally, it is a shortest-path problem in a Cayley graph (each puzzle state is a node, and each of the 24 possible moves is an edge) with an 88-sticker state.\n\nMy solver uses a beam search guided by a learned neural heuristic — a 3.4M-parameter **PieceTransformer**. Instead of treating the 88 stickers individually, it groups them into 50 physical pieces, turns each piece into a token, adds a class token (51 tokens in total), and runs four small transformer layers with eight heads of size 32. At the end, an all-neighbours Q head (a head that predicts, for each of the 24 moves, the distance to solved after that move) outputs 24 numbers. So the beam scores all 24 children of a state with one forward pass on the parent.\n\nFor training, the signal is a mix of cheap random walks and exact ground truth:\n\n- Random walks of 2–40 moves from the solved state. A state `p` moves into a walk has two known labels: undoing the last move gives distance`p - 1` , and continuing the walk gives`p + 1` .\n- Exact 24-way labels from a breadth-first search (BFS) table at depth 5 or less.\n- The puzzle’s 24 spatial symmetries, used as data augmentation.\n\nOn the A100, one epoch takes **142.7 seconds**. My best checkpoint is epoch 1500 of a 2000-epoch run, about 80 hours in total.\n\n### What is TorchTPU\n\nTorchTPU is **not PyTorch/XLA**: there is no `LazyTensor` tracing, no `xm.mark_step()`, and no `xla_device()`. Instead, TorchTPU lowers ATen ops directly to StableHLO and runs through PJRT and `libtpu` (PyTorch’s core ops are translated straight into XLA’s input format and executed by the TPU runtime). Once you `import torch`, `\"tpu\"` works as a device string just like `\"cuda\"`.\n\nIt has three execution modes:\n\n- **Eager (the default):** runs one op at a time asynchronously.\n- **Fused eager (`TORCH_TPU_DEFER_AND_FUSE=1`):** defers ops and fuses them across op boundaries without needing`torch.compile` .\n- **Compiled (`torch.compile(fn, dynamic=False)`):** graph compilation targeting the TPU backend.\n\nThree rules matter in practice:\n\n- Static shapes were the reliable path: with the TorchTPU builds and operators I used, fixed tensor shapes and `torch.compile(..., dynamic=False)` worked best, and every new shape meant a full recompile.\n- Data-dependent output sizes were the most expensive: ops like `nonzero` ,`masked_select` ,`unique` ,`bincount` , and even`x[bool_mask]` still run in eager mode, but they force a`.cpu().item()` host round-trip to learn their output size, and a compiled graph gets specialized to that one size, so each new size means another compile.\n- Nothing falls back silently to the CPU: an op that TorchTPU doesn’t implement raises an error instead of quietly running slowly.\n\n### Part 1: training, from 1.65x slower to 1.08x faster\n\nI ran the first port on a Cloud TPU machine with four v6e chips, using DDP with one process per chip and a global batch of 512, so each epoch saw exactly the same number of samples as on the A100. Before the code could run on the TPU at all, I had to remove four GPU idioms (`masked_select` in the loss, boolean-mask indexing when expanding labels, 12 `.item()` metric reads per step, and sampling training anchors on the CPU instead of keeping the 0.19 GB anchor table in TPU memory). This first working version took **234.8 seconds per epoch**, 1.65x slower than the A100. I was able to bring it down to 132 seconds with two changes.\n\n#### Fused eager\n\nThe first win was practically free: turning on fused eager (`TORCH_TPU_DEFER_AND_FUSE=1`). Only the model’s forward and backward pass ran under `torch.compile`; the rest of the trainer (the random-walk sampler with its 40-iteration loop, label expansion, the loss, and the metrics) ran in eager mode, one op at a time. In default eager mode, that data pipeline took **61.3 ms per step**. Wrapping it in `torch.compile` brought it down to 29.7 ms, while fused eager, which fuses the ops at run time without any code changes, got it to **13.1 ms**. The pipeline is many tiny ops, and on this workload they fused better than they compiled; I didn’t profile why, since the cheaper option was also the faster one. Setting that single environment variable dropped the epoch time from 234.8 s to **176.5 s**.\n\n#### The attention rewrite that was almost thrown away\n\nStill, 176.5 s was slower than the A100, and the GPU profile was useless as a guide. On the A100, the input stage and embedding gradient took **67% of the step**; on the TPU, the same stage took only **0.96 ms (0.8%)**, and the model was spending **~90% of its time in attention**.\n\nA roofline at the model’s own shapes explained why. A square 8192³ GEMM hits 361 TFLOP/s on one v6e chip, and the model’s QKV and FFN GEMMs hit 212–259 TFLOP/s, while attention ran at **3.0 TFLOP/s**. With `T = 51` and `head_dim = 32`, every attention matmul is 51x32x51 on a 128x128 matrix unit (MXU) — roughly **2.5% tile occupancy**. Padding `head_dim` to 128 or `T` to 64 actually made things slower (0.83x and 0.81x). As a result, attention is about 3% of the model’s FLOPs but about 90% of its time on the TPU.\n\nIf you want to keep the same model (for a fair comparison), you need to keep the same shapes and find other improvements. Standard `scaled_dot_product_attention` (SDPA) expects `(B, H, T, Dh)`, so the QKV tensor has to be permuted to move the heads to the second dimension. Rewriting attention with `torch.einsum` keeps the heads in their original dimension and avoids the permutes:\n\n```\nq, k, v = qkv.view(B, T, 3, H, Dh).unbind(2)        # heads never leave dim 2\ns = torch.einsum(\"bthd,bshd->bhts\", q, k) * scale\np = s.float().softmax(-1).to(v.dtype)               # fp32 softmax, on purpose\na = torch.einsum(\"bhts,bshd->bthd\", p, v)\n```\n\nThe fp32 softmax is there for numerics. On the TPU, the einsum and SDPA versions disagreed by a relative 3.3e-3, so I checked both against a float64 reference on the CPU: both were about 4.6e-3 away from it, because the TPU’s matrix unit uses a single-pass bf16 multiply even for “fp32” matmuls unless you raise `torch.tpu.precision`. In bf16, keeping only the softmax in fp32 closed the remaining gap between the two versions.\n\nThis change was almost rejected. The agent first measured it on the forward pass only, where it looked slower (einsum 5.51 ms vs SDPA 4.56 ms), and discarded it on that basis. Thankfully, I decided to check the full forward+backward pass: the profiler attributed much of the backward-pass overhead to layout conversions around SDPA’s saved tensors, which cost far more than the forward pass saved. Across forward+backward, one layer dropped from **25.14 ms to 14.85 ms** (1.69x faster). That pushed the whole epoch down to **132.0 s — 1.08x faster than the A100**.\n\n#### A checkpoint that deadlocks\n\nThe most confusing bug was in checkpointing. Saving a checkpoint only from rank 0 is a standard pattern:\n\n```\nif is_main:\n    torch.save(model.state_dict(), path)      # deadlocks under fused eager + DDP\n```\n\nUnder fused eager, the tensors in `state_dict` are still deferred. When rank 0 reads them, it executes a graph that includes this step’s DDP collectives, while the other ranks are already waiting at the next barrier. The checkpoint file would grow to 1.1 MB, then 2.2 MB, and freeze forever while every rank sat busy. The fix is to move the tensors to the CPU on every rank and write the file on one:\n\n```\ncpu_state = {k: v.detach().to(\"cpu\") for k, v in model.state_dict().items()}   # all ranks\nif is_main:\n    torch.save(cpu_state, path)\n```\n\nThe trap only fires in the mode that gives the speedup, which made it harder to find.\n\n#### Summary of training changes\n\n| What changed | Why it mattered on TPU | Impact | \n|---|---|---|\n| `masked_select` /`x[bool_mask]` →`where` /`scatter_` | Avoids data-dependent output sizes, host syncs, and recompiles | Required for static graphs | \n| 12 `.item()` reads → device accumulator; host anchors → HBM | Eliminates per-step graph cuts and `cpu` transfers (0.19 GB table) | Clean async execution | \n| `TORCH_TPU_DEFER_AND_FUSE=1` | Fuses tiny eager ops in the sampler, loss, and metrics | 1.33x faster epoch | \n| `attn_impl=\"einsum\"` (training only) | Avoids layout conversions around SDPA’s saved tensors in the backward pass | 1.34x faster epoch | \n| Materialize `state_dict` on all ranks | Prevents deferred DDP collectives from deadlocking rank 0 | Fixes checkpoint hang | \n| Same validation size in smoke test and full run | Avoids a 28736-row validation graph OOM at epoch 25 | Unblocked the Kaggle full run | \n\n#### Training results\n\n| Configuration (4x TPU v6e) | Seconds per epoch | vs A100 (142.7) | \n|---|---|---|\n| first working port | 234.8 | 1.65x slower | \n| + fused eager | 176.5 | 1.24x slower | \n| + einsum attention | **132.0** | **1.08x faster** | \n\nTo check that this holds on hardware anyone can use, I ran the same script on Kaggle’s free v5e-8 (eight chips, 64 samples per chip). The first full run died at epoch 25, its first checkpoint, with an out-of-memory compile error: the validation pass compiled a single 28736-row graph per chip, 30 times larger than a training step, and the smoke run had validated on fewer samples, so it never compiled that graph. With the smoke run using the same validation size, the rerun used its whole budget: 186 epochs in 7.41 hours, with a median of **142.4 seconds per epoch**, against the A100’s median of 144.2 s over the same epochs.\n\nOver epochs 177-186, the training loss 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 epoch 186 is on par with the A100 checkpoint at epoch 200: its best predicted move is truly optimal for 99.0% of states, against 98.9%. The best checkpoint trained eight times longer and is still better.\n\n### Part 2: beam search, first attempt\n\nWith training done, the second half was porting my beam search solver (`KhoruzhiiSolver`, the CUDA beam searcher from the previous post) to TorchTPU. Training needed targeted fixes; the solver needed a rewrite. It relied on `torch.unique` for deduplication, boolean-mask indexing, and dynamic tensor shapes (`cand.index_select(0, unique_pos[:B])`), none of which works well on a TPU.\n\nSo I wrote `beam_tpu.py` from scratch in pure PyTorch with fixed shapes across every step. Instead of dropping duplicates, I sort candidates by hash, flag adjacent matches, and assign duplicate scores `+inf` so `topk` simply never picks them:\n\n```\nsort_h, sort_idx = h.sort()\ndup_sorted = torch.cat([no, sort_h[1:] == sort_h[:-1]])\ndup = dup_sorted[sort_idx.argsort()]\nscore = torch.where(dup | ~valid, BIG, score)\n```\n\nTo share a 1M-wide beam across chips, each chip holds an equal share of the beam slots, and a child’s owner chip is determined by its hash. Every step runs the Q-head forward on local parents, routes children to their owners via `all_to_all_single`, deduplicates globally on each owner, and runs `topk` for the next level. States are stored as `int8`, and the tree bookkeeping stays outside the compiled step so the level counter doesn’t trigger a recompilation.\n\nThe search doesn’t go all the way to the solved state: it stops as soon as a beam state appears in the exact depth-6 BFS table (27.8M states), and the table supplies the optimal last six moves. In the first TorchTPU version, this endgame tail (a Zobrist hash and a `searchsorted` over the table for each level, each ending in `.item()`) ran as eager ops on the TPU and took ~176 s after a 73 s solve. The JAX driver had always 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 model over fixed-size chunks inside a single `scan` didn’t change the step speed, but it kept one copy of the model in the compiled graph instead of one per chunk, shrinking the cached compiled code from 363 to 162 MiB.\n\nI first tested an August pre-release of TorchTPU on six hard scrambles (1M beam, 4x v6e). It matched my JAX kernel on path length (186 vs 185 moves, every path replay-verified) but was 5.7x slower (1973 s vs 345 s). The profile showed that cross-chip `all_to_all` cost only 0.6 ms per step, while model inference took ~83% of the time. Then I moved to the public `torch_tpu==0.2.0` on Kaggle, and the results were surprising: the gap narrowed to 2.8x per beam level, but quality dropped, with TorchTPU finding **194 moves** where JAX reproduced its 185.\n\n#### When a backend change exposed an algorithmic bug\n\nBecause Kaggle has a long TPU queue, I moved to Cloud TPU v6e to debug the 8 moves lost 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 order back to an unstable default, and `bf16` attention on sequence lengths that are not a multiple of 128 no longer ran the whole module in `fp32` (more on attention below).\n\nOn eight v6e chips, forcing the old low-index tie-breaking in `topk` took 0.2.0 from 193 moves back to 187, the pre-release’s number there. But why should tie-breaking change path length at all? On four chips, every fixed tie order I tried (lowest index first, highest first, a random shuffle) gave 185 moves; only 0.2.0’s native order gave 188. Something in the beam was turning tie order into path length, and that something was my deduplication.\n\nBecause the Q head scores children from the parent, a state reached from two parents arrives as two copies with different scores. My dedup sorted candidates by hash and kept the first copy in each run, and since `torch.sort` is unstable on both builds, “first” was whichever copy the backend left in front. When 0.2.0 changed the tie order, good states started to disappear because their worse duplicate survived. JAX’s dedup uses a stable `argsort` on score-sorted buckets, so it keeps the better copy.\n\nReplacing “keep first” with a segment-min over `(score, index)` (so duplicates always keep their best score) added 0.5% overhead and fixed the issue:\n\n| Configuration | 4x v6e | 8x v6e | 8x v5e (Kaggle) | \n|---|---|---|---|\n| `0.2.0` , old dedup | 188 | 193 | 194 | \n| **`0.2.0`, best-copy dedup** | **184** | **185** | **185** | \n| Pre-release, best-copy dedup | 184 | 185 | — | \n\nOn ten more puzzles, this fix cut total moves from **319 down to 302**, improving seven of them and worsening none.\n\n#### Flash attention and the GitHub issue\n\nOne regression really was TorchTPU’s: on the same chips, 0.2.0 ran a beam level **1.7x slower** than the pre-release. Timing each piece of a level separately showed that everything except attention was as fast or faster in 0.2.0. The cause was routing: 0.2.0 sends short attention shapes to its Flash attention kernel, which pads the 51-token sequence to a 128-token tile, so 84% of each score tile is padding. Turning Flash off with `torch.backends.cuda.enable_flash_sdp(False)` puts attention back on the plain XLA path (yes, `.cuda.` — TorchTPU respects PyTorch’s standard SDPA backend switches, which live under `torch.backends.cuda`):\n\n| Single v6e chip | `0.1.1.dev20260824` | `0.2.0` (Flash on) | `0.2.0` (Flash off) | Nightly `2026-11-04` | \n|---|---|---|---|---|\n| `bf16` attention call`(8192, 8, 51, 32)` | 9.8 ms | 50.3 ms | **7.3 ms** | 7.3 ms | \n| Model forward (16 chunks in `scan` ) | 1.67 s | 3.52 s | **0.64 s** | 0.68 s | \n| One beam level (real search) | 2.21 s | 3.74 s | **0.93 s** | 0.98 s | \n\nWith Flash off, a full beam level is 4x faster than with `0.2.0`’s default and 2.4x faster than the pre-release. The 2026-11-04 nightly, which already routes short sequences away from Flash, is as fast as the workaround.\n\nTwo things hid this at first. The `--fp32-attn` arm that I added to test attention precision still went through Flash, so it only made things slower. And PyTorch’s AOTAutograd cache is keyed on the graph, not on the attention backend flag, so a second process quietly reused the Flash-compiled graph and reported identical times until each run got its own cache directory.\n\nMy agent wrote up the measurements and [reported the issue](https://github.com/google-pytorch/torch_tpu/issues/6304) to the TorchTPU repository with a Colab reproduction and a table of attention timings across head sizes and sequence lengths. It turned out that the short-sequence fix had already landed on main three days after 0.2.0 was tagged, but it hadn’t been released. The report also noted that a newer routing rule on main would make some 128–256-token shapes slower. The TorchTPU team picked it up, merged a series of attention-routing fixes, and closed the issue on November 21.\n\n#### Attention call time: Flash vs StableHLO\n\nMilliseconds per SDPA call on one TPU v6e chip, TorchTPU 0.2.0 · lower is better\n\n[torch_tpu issue 6304](https://github.com/google-pytorch/torch_tpu/issues/6304).\n\n## Data table\n\n| Head dim | Tokens | Flash, ms | StableHLO, ms | \n|---|---|---|---|\n| 32 | 51 | 50.30 | 7.25 | \n| 32 | 64 | 41.37 | 6.47 | \n| 32 | 128 | 18.11 | 3.41 | \n| 32 | 256 | 12.06 | 2.78 | \n| 32 | 512 | 8.97 | 5.08 | \n| 32 | 1024 | 9.11 | 11.86 | \n| 64 | 51 | 50.78 | 11.35 | \n| 64 | 64 | 41.84 | 10.23 | \n| 64 | 128 | 18.75 | 6.70 | \n| 64 | 256 | 12.71 | 11.88 | \n| 64 | 512 | 9.60 | 9.86 | \n| 64 | 1024 | 9.83 | 34.90 | \n| 128 | 51 | 51.27 | 8.53 | \n| 128 | 64 | 36.33 | 5.28 | \n| 128 | 128 | 15.07 | 24.76 | \n| 128 | 256 | 8.92 | 21.42 | \n| 128 | 512 | 5.57 | 22.70 | \n| 128 | 1024 | 6.10 | 39.37 | \n\n#### Summary of beam search changes\n\n| Component | GPU / initial approach | TPU rewrite and fix | \n|---|---|---|\n| Deduplication | `torch.unique` + dynamic indexing | Sort by hash, score dups `+inf` ; segment-min keeps the best-scored duplicate | \n| Cross-chip beam | Dynamic per-rank pools | Hash-based owner assignment + `all_to_all_single` (0.6 ms/step) | \n| State and hash memory | `int64` tensors | `int8` states; a cheap dot-product hash for all children, the endgame table’s Zobrist hash (a standard XOR-based hash for game states) only for the survivors | \n| Model chunking | Unrolled chunks | `scan` over fixed chunks (cached graph 363 → 162 MiB) | \n| Endgame tail and hit check | Eager TPU `searchsorted` ;`all_reduce` | Host NumPy tail (176 s → negligible); `all_gather` + host min | \n| `0.2.0` attention routing | Default Flash kernel (padded to 128) | `enable_flash_sdp(False)` until a release with the fix ([PR 6759](https://github.com/google-pytorch/torch_tpu/pull/6759) and related routing changes) | \n\n#### Beam search results\n\nWith the dedup fixed and Flash turned off, I reran the comparison on one eight-chip v6e machine with the public `torch_tpu==0.2.0` and JAX 0.11.0 (the version in Kaggle’s TPU image).\n\n| Eight v6e chips | JAX | TorchTPU, Flash off | TorchTPU, Flash on (0.2.0 default) | \n|---|---|---|---|\n| moves, six scrambles | 185 | 185 | 185 | \n| seconds per beam level | 1.27 | **1.02** | 3.95 | \n| median seconds per scramble | 31.6 | **28.3** | 110.3 | \n| whole process, including compilation | 310 | **277** | 744 | \n\nTorchTPU now runs a beam level 1.25x faster than JAX with the same quality.\n\nOn Kaggle’s v5e-8, the picture is closer. TorchTPU with Flash off is still about 10% faster per beam level, but the median scramble takes slightly longer (49.9 vs 48.7 s), because it checks the hit flag only every four levels and runs extra levels, and it found one move more (186 vs 185):\n\n| Eight v5e chips (Kaggle) | JAX | TorchTPU, Flash off | TorchTPU, Flash on (0.2.0 default) | \n|---|---|---|---|\n| moves, six scrambles | 185 | 186 | 185 | \n| seconds per beam level | 1.97 | **1.79** | 5.48 | \n| median seconds per scramble | **48.7** | 49.9 | 153.4 | \n\nJAX remains my main beam search solution for now as I have yet to run TorchTPU on wider beam. And the investigations helped push the JAX kernel further: bounding temporary buffers reduced the compile-time memory for a 128M beam from 39.5 to 12 GiB per chip, and a 256M-state beam works on eight v6e chips.\n\n### A100 vs TPU: the differences that mattered\n\n|  | A100 + CUDA | TPU + TorchTPU | \n|---|---|---|\n| getting started | `.to(\"cuda\")` | `.to(\"tpu\")` , the backend loads with`import torch` | \n| default execution | eager, kernels launched asynchronously | eager, one op at a time; fused eager is one environment variable away | \n| `torch.compile` | optional, dynamic shapes are fine | `dynamic=False` , one compile per shape | \n| data-dependent sizes ( `nonzero` ,`unique` ,`x[mask]` ) | fine | host round-trip and a recompile per distinct size | \n| `.item()` in the loop | a sync | a sync that also ends the deferred graph | \n| attention at 51 tokens, head size 32 | flash attention, no problem | ~2.5% matrix unit occupancy, the dominant cost | \n| hotspot of this model | input stage (67%) | attention (~90% of model time) | \n| “fp32” matmul | fp32/TF32 | single-pass bf16 unless `torch.tpu.precision` is raised | \n| rank-0-only work | fine | must not materialize anything the other ranks also need | \n| tie order of `topk` /`sort` | stable at these sizes (measured) | not guaranteed and changed between builds | \n| unimplemented op | rare | raises an error, no silent CPU fallback | \n\n### Conclusions\n\nI started this experiment to see whether TorchTPU could replace my A100 + JAX setup, and on this task it can: the same model trains at the A100’s speed or slightly faster, and the beam search matches JAX on quality and is a bit faster per level.\n\nHowever, a native PyTorch API does not eliminate the need for hardware-aware engineering. Static shapes, deferred execution, tensor layouts, compilation caching, and kernel selection all mattered considerably. Optimizations that helped training did not necessarily help inference, and seemingly minor changes in backend behaviour exposed a latent bug in my search algorithm.\n\nThe migration also improved both implementations: fixing deduplication reduced solution lengths, the attention investigation contributed to upstream TorchTPU improvements, and revisiting memory management enabled larger beams in JAX.\n\nMore broadly, this project demonstrated how AI coding agents can participate in experimental engineering rather than simply code generation. Claude Code and Codex implemented alternative approaches, profiled execution, constructed controlled experiments, investigated regressions, and prepared reproducible bug reports. My role was to formulate hypotheses, choose meaningful metrics, question misleading measurements, and decide which trade-offs were acceptable.\n\n[blogpost](https://andlukyane.com/tag/blogpost)\n\n[pytorch](https://andlukyane.com/tag/pytorch)\n\n[tpu](https://andlukyane.com/tag/tpu)\n\n[jax](https://andlukyane.com/tag/jax)\n\n[cayley](https://andlukyane.com/tag/cayley)", "url": "https://wpnews.pro/news/from-cuda-and-jax-to-torchtpu-lessons-from-a-cayley-graph-solver", "canonical_source": "https://andlukyane.com/blog/cayley-graphs-and-torchtpu", "published_at": "2026-11-24 00:00:00+00:00", "updated_at": "2026-11-24 09:43:48.851771+00:00", "lang": "en", "topics": ["machine-learning", "ai-research", "ai-infrastructure", "ai-chips", "developer-tools"], "entities": ["Google", "TorchTPU", "PyTorch", "JAX", "CUDA", "Claude Code", "Codex", "Kaggle"], "also_reported_by": [], "takeaway": "On an eight-chip TPU v6e, an optimized TorchTPU beam search ran 25% faster per level than JAX with identical solution lengths, after fixes including eliminating dynamic tensor shapes and rewriting attention; the unoptimized port was 5.7x slower.", "recommendation": {"advice": "When porting PyTorch workloads to TorchTPU, eliminate dynamic tensor shapes and rewrite attention before benchmarking; the unoptimized port was 5.7x slower than JAX, while the optimized version ran 25% faster per level.", "playbook": "inference-serving", "playbook_url": "https://wpnews.pro/playbooks/inference-serving"}, "alternates": {"html": "https://wpnews.pro/news/from-cuda-and-jax-to-torchtpu-lessons-from-a-cayley-graph-solver", "markdown": "https://wpnews.pro/news/from-cuda-and-jax-to-torchtpu-lessons-from-a-cayley-graph-solver.md", "text": "https://wpnews.pro/news/from-cuda-and-jax-to-torchtpu-lessons-from-a-cayley-graph-solver.txt", "jsonld": "https://wpnews.pro/news/from-cuda-and-jax-to-torchtpu-lessons-from-a-cayley-graph-solver.jsonld"}}