Agent-driven workflows with the TPU Agent Suite¶
Prerequisites: Correctness: parity gates and numerical checks, Performance you can defend: benchmarks, MFU, SLOs
Every step of TPU bring-up in this book took you an afternoon the first time: porting a model, proving it computes the right thing, reading a trace, placing an op against its roofline, writing and tuning a Pallas kernel. A coding agent can run the same steps in minutes. Google's TPU Agent Suite, released in preview alongside TorchTPU, packages them as specialist agents behind one front end that runs inside Claude Code or Antigravity. The question that remains is whether to believe what it hands back. The suite's own source records the kind of failure to expect: the router skill's frontmatter notes a router that "still executed 48 XProf invocations itself rather than delegating once", and the runtime's artifact check notes that "a recorded session spent 33 minutes measuring, wrote no files at all". A third is easy to reproduce, and this chapter does: a 10% error in one layer that the model's final output hides. None of these failures looks like a failure from the outside. This chapter covers what the suite is, how its ladder from onboarding to a tuned kernel reuses the methods of earlier chapters, which gates keep each step honest, and how to run the CPU-checkable half of the workflow from this repository. It then turns to the reviewer's side: what to trust in a hand-off, what to re-verify by hand, and the failure modes to look for. It ends with a design exercise in which you build an agent workflow for your own model, gates first.
What this chapter covers¶
- The TPU Agent Suite's architecture: one router skill, four specialists, and a runtime that validates every request and result.
- The ladder from onboarding to a tuned kernel, and the earlier chapter whose method each step reuses.
- A gated pipeline that stops on a schema, parity, artifact or noise-floor failure, with a negative control for every gate, dry-run on a laptop before a TPU is booked.
- Reviewing an agent's hand-off from its artifacts, parity verdict, baseline and replicates: which claims to accept, rerun or reject.
- Three failure modes that look like success: a metric that is not the goal, unverified speedups and schema drift.
What the TPU Agent Suite is¶
The suite is an open-source package published under google-pytorch on GitHub, in preview, and in its launch video described as "currently in preview for PyTorch inference workloads on Cloud TPUs". It runs inside the coding agent you already use. The repository's README says the release works in Claude Code and Antigravity, with Codex and Cursor "coming soon". It knows how to run code on a Cloud TPU VM or a GKE cluster. The version this chapter reads is 0.7.0.
The video frames the suite's job in two halves. "Make it run": which serving engine to use, whether the model fits in memory, whether the output is still correct. "Make it fast": whether there is a bottleneck, and whether a custom kernel would help. You talk to one front-end agent, which routes each request to a specialist:
The release build of tpu-agent-suite 0.7.0. Every request crosses the schema hook on its way to a specialist, and every TPU job, whichever specialist starts it, goes through the Compute CLI (one arrow stands for all of them); no agent talks to the chips any other way.
| Part | What it is | What it does | Hand-off you read |
|---|---|---|---|
tpu-agent |
A skill: the one entry point | Routes each request; declares only read, write and ask tools, so where that list is enforced it cannot run commands |
Its final report, built from the specialists' summaries |
tpu-knowledge-base |
An agent with a keyword index of public sources | Looks keys up, fetches pages, answers with a citation; its prompt says "You hold no knowledge" | kb-result: status, sources, references |
tpu-model-onboarding |
An agent that follows a fixed checklist | Checks the hardware, runs preflight, serves or benchmarks the model, runs the parity check; delegates CUDA rewrites to tpu-unwiring |
onboarding-result: parity_verdict, output_files |
tpu-diagnostics |
The only agent allowed to read XProf | Captures and reads traces, returns the metrics asked for and ranked bottlenecks | profiling-result: metrics, coverage, hot_ops, levers |
tpu-kernel-development |
An orchestrator with no shell | Turns one computation into a Pallas kernel in a bounded loop, one fresh kernel-worker per iteration |
kernel-result: speedup_factor, baseline_verified, iterations |
| Framework | compiler.py, installer.py, runtime.py |
Builds the package per harness, installs it, and at run time validates every request and result and runs every TPU job through runtime.py compute |
The run's journal.jsonl and artifacts |
| Evals | Harbor suites in eval/ |
Score what the hardware and tools report, against a control arm with no package installed | Scores per dimension |
Three design choices run through all of it, and the video names them: the agents are grounded, bounded and checked. Each has a concrete mechanism in the code.
- Grounded. Facts about TPUs come from the knowledge base, an index that ships under
package/data/tpu-knowledge-base/, with a URL you can check. The knowledge-base result'sstatustells you whether anything was actually read:cachedandpartialserved pages, whilecited-onlymeans the catalog knew where to look but read nothing (for example with crawling off), anduncitedmeans the answer "came from the model alone". A design note in the repository adds the tenet that applies to everything else: "the performance numbers it claims come from runs on real TPU hardware. When a number is an estimate, the agent says so". - Bounded. In the video's words, "Kernel tuning runs go one attempt at a time. It records each result and stops after a certain number of attempts. Then it hands you back a table of what it tried and the best version, and the next step is your call." In the request schema,
max_iterations(default 5) is "the loop's only stop condition", with "deliberately no time or target-speedup budget". - Checked. Onboarding "checks the math on the TPU against the original PyTorch model on CPU. Only then does it hand you back the endpoint." The runtime also refuses a result that does not match its schema, and a
completedresult that lists no artifact.
Two structural rules explain how the suite behaves in a session. The router never executes. Its frontmatter comment records why: with a shell, a long run "still executed 48 XProf invocations itself rather than delegating once". On Claude Code a hook enforces the tool list from the moment the skill is invoked; on Antigravity the router's agent definition does; on Codex the rule "rests on the prompt". Only a skill can ask you anything. A specialist runs with its caller blocked, so a question from it "reaches nobody"; the compiler rejects any agent that declares the ask tool, and a specialist that needs input returns status: "needs_input" for the router to put to you.
What ships is defined by a file. package.release.json releases two skills, tpu-agent and tpu-agent-export-trajectory, and a user gets exactly the agents they reach. The repository holds more: an experimental build adds eleven skills, among them decompose-optimization (joins an XProf capture against a modelled roofline and ranks root causes, proposing no fix), write-tpu-kernels (a design-first kernel campaign with a float64 oracle, a fault-injection positive control and per-phase floors), workload-microbenchmark (derives per-rank microbenchmarks from a finished serving job) and roofline-analysis. Agents such as tpu-roofline are in the repository but no released skill delegates to them in 0.7.0. When you read about a capability, check which build it ships in.
The workflow from onboarding to tuning¶
The router's own skill file lays out the canonical "onboard and optimize" flow in five stages: baseline onboarding, empirical profiling, kernel optimization, re-benchmarking the served model, and a second trace to verify the gain. This chapter adds the roofline step that the experimental build and the walkthrough in TPU Agent Suite: Onboard, Profile and Tune PyTorch on Cloud TPU put between profiling and kernel work, because it is where you decide whether a kernel can pay at all. The table below starts one step earlier, with the plan and the facts it rests on, splits the parity check out of onboarding, and folds the re-benchmark and the second trace into one verify step: seven steps in all. Each step reuses a method from an earlier chapter, and each ends in a hand-off with a gate.
The seven steps of the table below, with what each step hands on or must show before the next one starts. The two amber steps run on the host and touch no TPU; the roofline step is in the suite's experimental build, or done by you.
| Step | Agent | Method it reuses | Hand-off | Gate |
|---|---|---|---|---|
| Plan and facts | tpu-agent, tpu-knowledge-base |
Spec tables and ridge points (ch. 1, ch. 2) | A plan you approve; kb-result |
Status cached or partial before a fact is used |
| Onboard | tpu-model-onboarding |
The porting checklist (ch. 9), serving engines (ch. 18) | Endpoint, deployments_json, launch_recipe |
Health check, then parity |
| Parity | tpu-model-onboarding |
Module-level parity with a reference (ch. 23) | parity_report.json, parity_verdict |
PASS; UNVERIFIED is not a pass |
| Profile | tpu-diagnostics |
Reading XProf (ch. 10), the lever order (ch. 11) | levers, hot_ops, coverage |
Coverage of every device; route on the first lever |
| Roofline | experimental roofline-analysis, or you |
Arithmetic intensity against the ridge (ch. 2) | A result with provenance: "modeled" |
Headroom between measured time and modelled floor |
| Kernel | tpu-kernel-development |
Pallas kernels, block sizes, VMEM (ch. 12) | kernel-result, journal, best kernel file |
Parity per iteration, budget, baseline_verified |
| Verify | tpu-agent, tpu-diagnostics |
Steady-state comparison (ch. 24) | Two benchmark files and a second trace | One change, same request, noise floor |
Plan and facts¶
Before it delegates an onboarding, the router follows a reference called query-understanding.md: pin the model id, ask the knowledge base for every fact the plan turns on, then show you a plan, "what it looked up and what it will run", and wait. This is where the plan approval in the launch video happens, and it has to happen in the router, because onboarding cannot ask you anything. The knowledge-base request is small and closed (additionalProperties: false); it requires only query.
Read the result's status before any number in it. The agent-suite workflow in the sample code, code/samples/agent_suite/, ships a real knowledge-base result, produced offline with crawling off for the keys vmem and pallas-double-buffer. Both keys matched, and the status is cited-only: the summary says "nothing kept to serve ... Nothing on them is established." A VMEM figure that appears next to that status in a report is the model's memory, not a fact. The suite's measured reference page, references/write-tpu-kernels/hardware-facts.md, gives the v7x figures the kernel step below uses: 64 MiB of VMEM per TensorCore and a default scoped limit of 32 MiB that a kernel compiles against.
Onboard¶
tpu-model-onboarding follows the same checklist every time, from references/tpu-model-onboarding/torch-tpu-inference.md. It reads the hardware with compute inspect (device count and HBM per device, never inferred from a VM name), runs preflight and an engine compatibility check, and delegates any CUDA-only code to tpu-unwiring when preflight reports ONBOARDING_REQUIRED. It tries vLLM on TorchTPU first; if vLLM cannot serve the model, it falls back to native PyTorch on TorchTPU (a custom_fastapi engine), "without asking the user". It writes the serving code, submits it, waits on log lines rather than a sleep loop, and only then checks parity. This is chapter 9's porting checklist and chapter 18's serving bring-up, run by a script that cannot skip a step.
Two routing rules matter to you as the person writing the request. First, the mode: a request that says serve, deploy or host gets serving mode, and the server is left running; anything else gets verification mode, and the deployment is cancelled after it is checked, "so a request that never asked for a server does not leave one holding the chips". Second, for an "onboard, then optimize" ask, the router delegates only the baseline, with mode: "inference", and must "not let it proceed to tuning". Onboarding returns output_files.deployments_json and output_files.launch_recipe, the serving configuration that every later step receives verbatim.
Parity¶
The parity step is where "checked" lives, and it is chapter 23's method run by a script. capture_parity.py builds a frozen probe and runs the model twice on it, teacher-forced (one forward pass over a fixed token sequence, so one flipped token cannot cascade): once as the reference on the CPU through the model's own plain-PyTorch path, once as the candidate on the TPU. Forward hooks capture the modules the TPU patches replaced. compare_parity.py grades every captured tensor by max_rel, the largest absolute difference divided by that tensor's own peak magnitude, against DEFAULT_REL_TOLERANCE = 0.05.
The 5% is calibrated, and the comment above the constant says how: on mamba-130m, CPU bf16 against TPU v6e bf16 with identical code, "device noise alone reached 2.92% at layer 23 and 3.09% on the logits", while a deliberate 10% error in one layer read 10.85%. That calibration gives you two limits to carry into every review. A wrong rewrite that changes a module by less than about 3% is, in the reference's words, "indistinguishable from device noise". And UNVERIFIED is not a weak pass: it means the model had no independent plain-PyTorch path, so both sides ran the same rewritten code and "the check could not be performed".
The workflow's driver, run_workflow.py, reproduces the rule on a CPU with the sample code's TinyTransformerBlock(256, 4): an fp32 reference, a bf16 candidate as a stand-in for device rounding, and then the same candidate with fc1's weight multiplied by 1.10.
A 10% fault in fc1 reaches the block output as 2.2%, under tolerance: an output-only check passes it. The per-module rows catch it, and the first breach in execution order, fc1, names the layer to open; fc2 reads higher only because it is downstream.
This is the same residual dilution you met in chapter 23, and it is why an agent's parity verdict is only as good as what it hooked. One inconsistency inside the suite is worth knowing: the inference checklist calls parity "MANDATORY before concluding the model works", while the parity reference makes it mandatory only after ONBOARDING_REQUIRED. Ask for it in your request, and check that the result's parity_verdict is one of PASS, FAIL, UNVERIFIED or not_run and that the report file exists.
Profile¶
The router has a "mandatory profiling gate": it may not dispatch any throughput optimization until tpu-diagnostics has captured the running baseline and returned ranked bottlenecks. The request points at the live server and its serving_config; the analyst captures in place and never restarts it, and a needs_input asking for a restart is your decision, because on a preemptible cluster a restart can lose the slice.
Each trace in the result carries metrics (with the XProf tool each came from), coverage (which devices carry op events), hot_ops (fusion, call shapes, per-call time) and levers, biggest first. A lever's kind is one of nine: kernel-block, exposed-collective, sharding-overhead, load-imbalance, host-critical-path, recompilation-padding, scheduler-batching, memory-capacity or other. You have diagnosed most of these by hand: a host sync in chapter 10, recompilation in chapter 7, an exposed all-gather in chapter 14. The analyst ranks on decode unless you name another metric, so say "time to first token" when you mean prefill.
Two rules from the router's instructions decide what happens next. It routes on the first lever and does not re-rank. And only kernel-block goes to kernel development; for anything else it shows you the levers and asks whether to try the lever's next_step as a serving-configuration change, or to write a kernel anyway. A coverage that leaves devices out means "the ranking describes those devices alone".
Roofline¶
The roofline step asks whether a kernel can pay before anyone writes one. It is chapter 2's arithmetic: FLOPs over HBM bytes for the op, against the chip's ridge point. In the suite it belongs to the experimental build (roofline-analysis, and the unreleased tpu-roofline agent, which "runs no workload and touches no accelerator"), and its result schema makes the honesty structural: roofline-result.json has a provenance field whose only allowed value is the constant "modeled".
The driver models the fused residual RMSNorm + SwiGLU block that the walkthrough profiles, at hidden 1,024 and intermediate 2,048. Unfused, XLA writes the normalized activations, the gate and the up projection to HBM and reads them back; fused, the sample code's Pallas kernel reads its inputs once and writes once:
rows chip kind FLOP/B ridge bound floor us
32 TPU v7 (1 TensorCore) unfused 28.6 313 memory 2.54
32 TPU v7 (1 TensorCore) fused 31.0 313 memory 2.34
2048 TPU v7 (1 TensorCore) unfused 240.9 313 memory 19.32
2048 TPU v7 (1 TensorCore) fused 682.6 313 compute 14.89
At the 2,048-row prefill shape, fusing moves the op from 241 to 683 FLOPs per byte, across the v7x ridge of 313, and removes 23% of the modelled floor. At 32 decode rows it barely moves (29 to 31), because the two weight matrices dominate the bytes either way. That second line is the evaluation this step exists for: if the profile's top lever were this op in decode, the kernel would be the wrong target, whatever the agent was asked to do.
Kernel¶
tpu-kernel-development turns one computation into a Pallas kernel, and it is built around chapter 12's rule that correctness comes before speed. What its prompt makes it do, in order:
- Library first. It asks the knowledge base whether Tokamax already ships a TPU kernel for the
target_op. If so, one iteration calls it and measures it against the baseline before anything is written; if it fails or is not faster, the loop builds one. - A verified baseline. The PyTorch source becomes
base.py, an idiomatic JAX baseline, "the denominator of every number this run reports". It is produced by a mechanicaltorchaxoracle or by an LLM port (the default), and gated against golden values captured from your module. Ifport_verifiedis false after three repairs, the loop stops, because "Five iterations optimizing against a wrongbase.pyend in a confident, wrong speedup". - State on disk, one worker per iteration. The loop's state is
state.json, re-read "at every decision point"; each iteration is a freshkernel-workerwith no memory of the last, which plans, implements, compiles, tests against the baseline atatolandrtol, autotunes and profiles. - One stop condition.
max_iterations, default 5. An iteration that fails to commit is retried, and more than three attempts trigger an emergency stop that reaps the run's jobs. - Timing it can trust.
run_autotune.pyranks trials only on theRESULT_TIME: <ms> msline its harness prints, because process wall clock would rank on JAX compilation.
Two inputs decide whether the loop tunes the right thing. When the hot op is a fusion XLA generated (no custom call, so no kernel file), the router extracts a standalone PyTorch reference to base_kernel.py and passes fusion_context, served_calls and serving_config copied verbatim from the profile. The router's instructions record why: rewritten as prose, "a 16-token decode call came back as 16 sequences and a 2048-token prefill call as a 2048-8192 range, and the loop tuned for calls the server never made." And a CUDA kernel is never the input: input_language: "cuda" is not in the schema; a .cu file goes in reference_paths, where the planner mines it for ideas and never runs it.
The hand-off is a kernel-result. For an optimized status the runtime requires best_kernel_artifact, best_latency_ms, speedup_factor, iterations_run and artifacts; the result also carries baseline_latency_ms and baseline_verified, and the router is told to "quote baseline_verified alongside the speedup". Read what the denominator is: for a PyTorch source, every number is relative to base.py on the TPU, not to your original model. The agent's own Finish section says it plainly: "a kernel reporting 3x here may have mostly beaten a slow reference."
Verify the gain¶
After the kernel, the router patches the served model, reruns the baseline's exact bench_request against the changed server so "the two results_json differ only by the change", and asks tpu-diagnostics for a second capture "so the end-to-end gain is attributed by a trace rather than only asserted". Its final report must list every lever that was not worked on, with its kind, share_pct and next_step. This is chapter 24's comparison rule with one thing changed, and the trace is its attribution.
The gates that keep an agent honest¶
An agent is a fast, tireless source of claims. Part VI's gates are what turn claims into results, and the suite enforces some of them itself. Know which, because the rest are yours.
| Gate | What it checks | Who enforces it | What it does not check |
|---|---|---|---|
| Schema | Every request matches the callee's accepts schema and every result its produces schema; status_requires makes an optimized kernel result without speedup_factor invalid |
The runtime's validate-schema hook, before each delegation and when each specialist stops |
Whether the values are true |
| Artifact | A completed result lists at least one artifact |
check_completed_has_artifact in the runtime |
Whether the files exist or say what the summary says: it checks a non-empty list |
| Parity | Module-level max_rel under 5% on the probes run |
compare_parity.py in onboarding; atol and rtol per kernel iteration |
Faults under about 3%; models with no independent reference (UNVERIFIED) |
| Budget | The loop stops at max_iterations |
tpu-kernel-development's control loop |
Whether the budget was enough |
| Noise floor | A win must clear a pre-registered noise floor, with enough replicates and every admissibility gate passed | framework/study.py (the in-repo study store; its driving agent ships in neither 0.7.0 build) |
Nothing, if you do not set a floor |
The noise-floor verdict is short enough to memorize, and the driver's noise_floor_verdict() follows study.py's compute_arm_verdict line for line:
if not telemetry_valid or metric_value is None or baseline_value <= 0:
return "invalid", None
delta_pct = ... # percent change in the optimizing direction
if not gates_passed:
return "invalid", delta_pct # faster but failed parity: inadmissible
if replicates < required_replicates:
return "tie", delta_pct # too few runs to claim anything
if delta_pct > noise_floor_pct:
return "win", delta_pct
elif abs(delta_pct) <= noise_floor_pct:
return "tie", delta_pct
else:
return "loss", delta_pct
Its order is the order of Part VI: correctness before speed, repetition before a claim, and a floor before a win. The study store adds one more rule worth copying into your own workflows: a gate marked same_execution must come from the same execution as the throughput it admits, because "throughput from one run and accuracy from another do not describe the same configuration".
Two habits from Part VI apply to these gates as much as to your own. A gate that has never failed may be unable to fail, so give each one a negative control (chapter 23). And a gate you can switch off will be switched off on a bad day: any non-empty TPU_AGENT_SUITE_DISABLE_SCHEMA_VERIFIERS turns off the schema hook on both sides of every delegation. Never set it in a run whose results you will act on.
Running the CPU-checkable workflow¶
No agent runs on a laptop, but every check around one does. The agent-suite workflow in the sample code, code/samples/agent_suite/ (source), holds the six request payloads of the ladder, the vendored 0.7.0 schemas, a captured knowledge-base result and a driver that runs the CPU half of every step by importing the sample code next to it. From the repository root:
python code/samples/agent_suite/run_workflow.py --cpu-smoke # every CPU-checkable step
python code/samples/agent_suite/run_workflow.py --validate-only # the payloads against the schemas
The hand-off summary at the end of the smoke run is what a reviewer reads:
requests valid: 7/7
kb: status cited-only, established=False
onboard: parity_verdict PASS; fault in fc1 caught at module level (FAIL), missed by output-only (PASS)
profile: 1 trace file(s) at .../tpu-diagnostics/capture
roofline: Prefill case (2048 rows): unfused 241 FLOP/B vs fused 683 FLOP/B against a v7x ridge of 313; fusing removes 23% of the modelled floor.
kernel: 5/5 iterations, kept block_rows=256, latency: TPU only
Read each line for what it proves and what it does not. Six requests and one captured result validate (7/7) against the real schemas, so a live router would not reject them at the boundary. The knowledge base established nothing. Module parity catches the injected fault that the output misses. A trace was captured; ranking it is tpu-diagnostics' job on a TPU host. The roofline is modelled. The kernel loop spent its budget and kept a block size, and it reports no latency because a CPU cannot measure one. The driver's parity section also runs the sample code's cpu_vs_tpu_parity() (the check chapter 9 adapts), which on a laptop compares the CPU with the CPU: it proves the plumbing and nothing else.
Putting the gates around it¶
The driver reports; it does not decide. The chapter's companion script code/ch26_agents/gate_demo.py (source) wraps it in six gates, stops at the first one that fails, and refuses acceptance unless all pass. The parity gate carries its own negative control (the same 10% fc1 fault must FAIL, or the gate reports that it cannot fail), and the artifact gate opens the trace files instead of trusting a list. Its smoke run executes three pipelines whose outcomes are known in advance:
== clean run, with the illustrative claim (1000 -> 1150 output tok/s, 3 replicates) ==
gate status detail
schema pass 7/7 payloads valid (Draft202012Validator, Draft7Validator)
parity pass PASS, worst module norm2 0.63% < 5%; negative control FAIL as it must
artifact pass 1 trace file(s) exist and are non-empty
roofline pass Prefill case (2048 rows): unfused 241 FLOP/B vs fused 683 FLOP/B ...
kernel pass 5/5 iterations, kept block_rows=256, 4 rejected; latency TPU only
performance pass claim 1150 vs 1000 output tok/s (+15.0%), 3/3 replicates, noise floor 2%: win
decision: ACCEPT: correct, and faster beyond the noise floor
== broken parity: fc1 weight x1.10 in the candidate, same claim ==
schema pass 7/7 payloads valid (Draft202012Validator, Draft7Validator)
parity fail FAIL, first breach fc1 (max_rel 10.01%); output-only check: PASS
artifact skipped blocked by the parity gate
roofline skipped blocked by the parity gate
kernel skipped blocked by the parity gate
performance fail claim 1150 vs 1000 output tok/s (+15.0%), 3/3 replicates, noise floor 2%: invalid
decision: REJECT: blocked at the parity gate
== schema drift: kernel request with input_language 'cuda' ==
schema fail 05-kernel-request.json with input_language='cuda': $/input_language: 'cuda' is not one of ['jax', 'pallas', 'pytorch', 'specification']
...
decision: REJECT: blocked at the schema gate
cpu-smoke: OK
The second pipeline is the one to remember. The same 15% throughput claim that wins in the clean run is classified invalid once parity fails, and the kernel loop never starts. A faster model that computes something else is not a speedup. The claimed numbers are an input you supply, here the chapter's worked example, so the 1000 to 1150 output tok/s figure is illustrative, not a measurement; on a TPU you pass measured ones with --claim BASELINE CANDIDATE REPLICATES.
The kernel stage is a bounded hill climb, and it is the agent loop in miniature. Each iteration proposes a block size for the fused RMSNorm + SwiGLU kernel at the served prefill shape (2,048 x 1,024 x 2,048, bf16), tests a row-blocked candidate for parity against the extracted base kernel with the request's atol and rtol of 0.02, measures it, and accepts it only if it passes and improves on the best so far. On a CPU the measurement is the modelled VMEM plan from the sample code's plan_pallas_tiles() and grid step count, the same proxy the agent-suite workflow's kernel loop uses; on a TPU it is latency on the RESULT_TIME line.
Two gates per iteration, in a fixed order. The candidate that drops the RMSNorm weight is the kind of plausible edit a tuning loop proposes; it is rejected before anyone measures it, so it can never win on speed. The loop stops at its budget with 128 untried, and says so.
Running the workflow on a TPU¶
On a host with a TPU profile, the same requests go to the agents. Install a release archive into your project with its installer, then create a compute profile and check it:
tar -xzf tpu-agent-suite-<harness>-<version>.tar.gz
python3 tpu-agent-suite-<harness>-<version>/framework/installer.py install --destination /path/to/project
R="python3 $HOME/.tpu-agent-suite/packages/tpu-agent-suite@0.7.0/framework/runtime.py compute --package tpu-agent-suite@0.7.0"
$R setup plan --backend gke_job --json
$R setup apply --profile default --answers answers.json
$R setup verify --profile default --smoke-test
The profile picks one of five backends (local, gce_tpu_vm, gke_pod, gke_job, gke_xpk), and the agents' instructions name commands, never backends, so switching from a TPU VM to a GKE Job is a profile change. The suite's docs/using.md recommends writing a detailed prompt to a file and referencing it, using the instructions in eval/datasets/ as models. Two operational details decide what happens to your chips: a SessionEnd hook cancels the run's jobs when the session ends, and a lease watcher cancels them 120 seconds (LEASE_GRACE_SECONDS) after a killed session disappears; but jobs submitted for serving are exempt, so an endpoint outlives its session until you cancel it with compute job cancel or compute job reap --include-serving.
Evaluating agent output¶
Review a hand-off the way you review a pull request: by the artifacts, not the summary.
The runtime enforces the schema gate and half of the artifact gate: it checks that a completed result lists an artifact. The onboarding agent grades parity itself. Opening the files, reading the parity rows in order and judging a speedup against its noise floor are yours; the two trees below are those checks.
What you can trust without re-running. A result that passed the schema hook has the fields its status requires; an optimized kernel result has a speedup_factor. A roofline result is modelled by construction. A cited-only, near or uncited knowledge-base status reliably tells you nothing was read. A refusal (invalid_input, needs_input, a failed emergency stop) is usually the most honest thing an agent returns; the eval briefs say it outright: "A truthful partial result is worth more than a claimed success."
What you re-verify by hand. Open experiment.md and the raw files each number came from; the eval briefs' standard is that "every benchmark row must be traceable to the raw output it came from". Read the parity rows in execution order, not only the verdict. Recompute the roofline for the op the kernel targets, with chapter 2's ridge points, and check that the measured time sits above the floor (below it, an input is wrong). Check the kernel's denominator: baseline_verified, reference_mode, and whether the speedup is against base.py or against your served model. Rerun any end-to-end claim the chapter 24 way, with replicates and the same request, before acting on it.
As two decisions: first whether the bring-up holds, then whether a speed claim does.
Review the files, not the summary: the runtime has already checked the schema, and these checks are the ones it leaves to you. A PASS is accepted only when the worst module row also sits under about 3%, the level of device noise.
Judge a speed claim in the order of the noise-floor verdict: a number whose gates failed or come from another execution is invalid whatever its size, one from too few runs or inside the floor is a tie, and one below the floor is a loss.
| You see in the hand-off | Do | Because |
|---|---|---|
parity_verdict: PASS, every module row under 3% |
Accept the bring-up | Within measured device noise on the probes that ran |
PASS, one module between 3% and 5% |
Widen the probe set before shipping | Below about 3% is noise; a real error of a few percent hides in that band |
UNVERIFIED |
Treat as not checked; build an independent reference | Both sides ran the same rewritten code |
A KB fact with cited-only, near or uncited |
Look it up yourself | Nothing was read from a source |
speedup_factor with baseline_verified: false |
Rerun against a verified baseline | The denominator may be wrong |
reference_mode: "llm_port", port_verified: true |
Say "agrees within atol", not "is the same computation" |
The gate is by value only; the agent's prompt cites a dropped epsilon at 7.8e-05 that passes it |
| A speedup from one run, or inside your noise floor | Rerun with replicates | It is a tie until it clears the floor |
A lever that is not kernel-block |
Try its next_step as a serving change first |
The kernel is not the bottleneck |
coverage shows one device of eight |
Recapture before ranking | The ranking describes that device alone |
needs_input asking for a restart or a bucket |
Answer it yourself | On a preemptible slice a restart can lose the chips |
How the suite itself is judged. Google scores the package with Harbor suites against a control arm, claude-code/baseline, which uses the same image and tools with no package installed; a version "has to beat the plain harness model ... not just work". For the onboard-and-optimize tasks, reward.toml computes (0.3 * onboarding_success + 0.3 * hillclimb + 0.3 * speedup_score + 0.1 * efficiency) * (1 - cheating), where a binary cheating judge zeroes the score. The repository publishes no pass rates, so this chapter quotes none. If you want to know whether the suite beats a bare coding agent on your models, the control arm is how you find out.
Failure modes¶
The three failure modes this chapter is about look like successes from the outside. Each row below follows from a mechanism described above.
| Symptom | Cause | Fix |
|---|---|---|
| A kernel wins in isolation and the served model gets no faster | The loop optimized the op without its fusion context; a kernel is a fusion boundary and can break the fusion XLA had | Pass fusion_context verbatim; judge only the end-to-end rerun and the second trace |
| The loop tuned shapes the server never runs | Call shapes were restated in prose (a 16-token decode call became 16 sequences) | Copy served_calls from hot_ops verbatim; check them in state.json |
| A "speedup" measured against a slow denominator | A PyTorch source was ported to a base.py that is slow, or unverified |
Read baseline_verified and reference_mode; compare against your served baseline end to end |
| An eval passes while the brief's goal is missed | The metric is not the goal: the onboard-and-optimize reward counts hill-climb success from 1% more output throughput, while the same task's brief (tpu-inference-gpt-oss-20b-vllm) asks for 10% |
Write the definition of done into the brief and judge against it, not against the score |
| A kernel candidate is faster and wrong | A plausible edit (a dropped scale, a skipped tile) passes a weak or absent test | Parity before measurement in every iteration, with a negative control |
| A speedup from one run, or from a run other than the one that passed its accuracy gates | No replicates; throughput and accuracy from different executions | Pre-register replicates and a noise floor; tie gates to the same execution |
A model with CUDA rewrites passes parity at UNVERIFIED and is reported working |
No independent reference existed, so both sides ran the rewrite | Treat UNVERIFIED as unchecked; build a reference from upstream or an earlier commit |
| A 2% layer bug ships | Under about 3%, a fault is indistinguishable from device noise at the probe size | Widen probes; for a known-risky module, compare like with like at higher precision (chapter 23) |
| A request is refused mid-run after an upgrade | Schema drift: your payload was written for another version's schema | Validate payloads against the installed version's schemas before the run; keep vendored copies byte-identical (the agent-suite workflow's tests check this) |
| Everything validates, yet a field is ignored | Schema verification was disabled with TPU_AGENT_SUITE_DISABLE_SCHEMA_VERIFIERS |
Never set it; check the environment of every run you will act on |
| A completed result with numbers that exist nowhere | The artifact check accepts a non-empty list without opening it; numbers lived only in the conversation | Open every artifact; reject numbers with no file behind them |
| Chips keep billing after the session | Serving jobs are exempt from reaping | Cancel endpoints with compute job cancel or reap --include-serving |
| The router runs tools itself on Codex or Cursor | The tool limit is enforced by a hook only on Claude Code, and by the agent definition on Antigravity | Use a supported harness for the release; on others, the rule rests on the prompt |
Design exercise: an agent workflow for your model¶
The brief. Design, dry-run and gate an agent-driven onboard-and-optimize run for a model you care about, so that every claim it can hand back is either checkable by a gate you wrote or explicitly marked as unchecked. Deliver the brief, the payloads, the gates with their negative controls, and a review plan, all exercised on a CPU before a TPU is booked.
What you build.
- The brief, as a file. Start from an
instruction.mdin the suite'seval/datasets/nightly-onboard-optimize/and adapt it: model and engine, the regimes to benchmark, the definition of done (with numbers), what not to touch, the parity tolerance and probe set, the noise floor and replicate count, and the sentence about partial results. - The payloads. Write
kb,onboarding,profilingandkernelrequests for your model next to the ones incode/samples/agent_suite/requests/, list them inworkflow.json, and makerun_workflow.py --validate-onlypass. Use a placeholder string for any number only a TPU can produce, as the kernel request incode/samples/agent_suite/requests/does forper_call_us. - The gates, each with a control that fails. Extend
gate_demo.py, or write your own, so that: a broken payload is blocked at the schema gate; a fault injected into the module your change touches is blocked at the parity gate while an output-only check passes it; a kernel candidate with a plausible bug is rejected before it is measured; and a claim inside your noise floor, or from too few replicates, is a tie. - The kernel plan. Put your served shapes into the kernel request and predict, before running
--hill-climb, which candidates fit the scoped VMEM limit. If none can, say what design change the loop cannot make for you. - The review plan. List, before the run, which artifact files you will open, which parity row would make you reject, which lever kinds you let the agent act on without asking, and what you will rerun by hand.
- On a TPU, if you have one. Run it, review the hand-off with the trust table above, and compare the agent's
parity_report.jsonand kernel table with what your laptop run predicted.
Deliverables. A finished design contains:
| Area | What it contains |
|---|---|
| Brief | A file, adapted from an eval brief, that states the model, engine, regimes, a numeric definition of done, forbidden actions and the partial-result rule |
| Payloads | Requests that validate against the installed schemas, with placeholders marked as such, and a broken copy of each that is rejected with the error you predicted |
| Parity gate | Module rows judged at a stated tolerance, a negative control that fails while an output-only check passes, and a reference independent of any rewrite, so UNVERIFIED cannot occur |
| Performance gate | A pre-registered noise floor (measured from an A/A run) and replicate count, the verdict function applied, and throughput and its accuracy gates from the same execution |
| Kernel plan | Served shapes copied from the profile, a VMEM prediction made before the run, and a stated redesign if no block size can fit |
| Review plan | Named artifacts to open, the parity rows that mean rejection, the actions you reserve for yourself, and the claims you will rerun by hand with the method for each |
| Evidence | A run in which each gate fails on its control and passes on the clean run and, on a TPU, a review of the hand-off against the laptop prediction, with differences explained |
Verifying the result¶
A workflow is ready to hand to an agent when all of these hold, and the companion code checks the CPU half:
python code/samples/agent_suite/run_workflow.py --cpu-smoke # ends with "requests valid: 7/7" and a hand-off summary
python code/ch26_agents/gate_demo.py --cpu-smoke # clean accepted, broken parity and schema blocked, "cpu-smoke: OK"
python code/ch26_agents/gate_demo.py --break-parity fc1; echo $? # 1: blocked at the parity gate
pytest tests/ch26 tests/samples/test_agent_suite_workflow.py -q
- The requests are schema-valid. Every payload validates against the schemas of the suite version you will run, and a deliberately broken copy is rejected with the error you predicted.
- The gates produce results, and each can fail. The clean pipeline passes every gate; a deliberately broken parity step blocks the pipeline before profiling, roofline and kernel work start, and turns a 15% speed claim into
invalid; a claim inside the noise floor is a tie. - The kernel loop is bounded and journaled. It stops at
max_iterations, every result injournal.jsonlhas a verdict and an evidence file that exists, a candidate that fails parity is never measured, and no latency appears on a CPU. - On a TPU, the hand-off survives review.
parity_verdictisPASSwith module rows under about 3%;baseline_verifiedis true; the end-to-end gain is measured on the same request as the baseline, with replicates, above your floor, and attributed by a second trace.
Worked problems¶
Problem 1. Your noise floor is 2%, you require 3 replicates, and the baseline is 1,000 output tokens per second. Classify each claim with the noise-floor verdict: (a) 1,015 tokens per second over 3 runs; (b) 1,150 over 3 runs with parity FAIL; (c) 1,150 from a single run; (d) 980 over 3 runs.
Answer
(a) \(+1.5\%\), inside the 2% floor: tie. (b) \(+15\%\), but an admissibility gate failed: invalid, whatever the number. (c) \(+15\%\) from 1 of 3 required replicates: tie, too few runs to claim anything. (d) \(-2.0\%\): \(|\Delta| \le 2\), so tie, not a loss. Only a gain above the floor, from every required replicate, with every gate passing, is a win. gate_demo.py --claim 1000 1015 3 and tests/ch26/test_gate_demo.py reproduce (a) and (c).
Problem 2. An onboarding hand-off shows these module rows against the CPU reference: norm1 0.4%, qkv 0.3%, proj 0.4%, norm2 0.6%, fc1 10.0%, fc2 12.6%, output 2.2%. The agent's summary says "output matches within 2.2%, parity looks fine". What is the verdict, which module do you open, and why not the highest row?
Answer
FAIL: two rows exceed the 5% max_rel tolerance, whatever the output row says. Open fc1, the first breach in execution order. fc2 reads higher because it consumes fc1's wrong output and errors compound as they flow forward; the parity reference says to name the module with the highest max_rel, and this example shows why reading the rows in order is the refinement. The output row is under tolerance because the residual stream dilutes the MLP's error, which is exactly why an output-only check would have passed this model.
Problem 3. A teammate changes the served shape in the kernel request to hidden 4,096 and intermediate 14,336 and runs the bounded loop with block sizes 2,048 down to 128. Predict every iteration's verdict before running it, and say what the loop cannot do about it.
Answer
Every iteration is refuted at the VMEM step. plan_pallas_tiles() in the sample code counts each BlockSpec block twice for double buffering, and the two weight matrices alone are \(2 \times 2 \times 4096 \times 14336 \times 2\) bytes, 448 MiB, above both the 32 MiB scoped limit and the 64 MiB of physical VMEM per v7x TensorCore. The plans come out at 880, 664, 556, 502 and 475 MiB for 2,048 to 128 rows; shrinking block_rows only trims the activation blocks. The loop spends its budget and keeps nothing. Tuning a block size cannot fix this: the kernel has to tile the intermediate dimension as well, which changes its grid and its parity test, and the next step is your call.
Problem 4. A kernel-result reports status: "optimized", speedup_factor: 2.4, reference_mode: "llm_port", port_verified: true, baseline_verified: true, five iterations, and the input was a PyTorch module. A manager wants to announce "2.4x faster serving". Evaluate.
Answer
The claim does not follow. The 2.4x is the best Pallas kernel against base.py, an agent-written JAX port of your PyTorch op, timed on the RESULT_TIME line for one op in isolation. The port was verified by value against golden outputs from your module, which supports "agrees with the source within atol", not "is the same computation". None of that is your served model: the agent's own instructions warn that "a kernel reporting 3x here may have mostly beaten a slow reference", and a kernel can win in isolation and break a fusion end to end. What would support a serving claim: the kernel patched into the served model, the baseline's exact bench_request rerun against both servers with replicates, a gain above the pre-registered floor from the same execution as its accuracy gates, and a second trace that shows the op's share dropping. Until then, report it as "a 2.4x faster kernel for this op against its JAX baseline".
Problem 5. A profile of a served model returns coverage with op events on one device of eight, a first lever host-critical-path at 38% and a second kernel-block at 21%. The user asked the agent to "write kernels for the bottlenecks". What should happen, and what do you do before accepting any of it?
Answer
The router routes on the first lever without re-ranking, and only kernel-block goes to kernel development, so it should not start with a kernel: it shows the levers and asks whether to try host-critical-path's next_step as a serving change or write a kernel anyway, saying the kernel is not the biggest bottleneck. Before accepting either, recapture: a coverage of one device means "the ranking describes those devices alone", and on eight devices a host-side stall or an imbalance on the others could reorder the levers. A host-critical-path lever also points back to chapter 10's host syncs and chapter 7's recompilation, which a kernel cannot fix.
Problem 6. An agent's final report says: "Integrated the kernel; output throughput improved 12% (run 7); parity PASS (run 3)." The parity check and the throughput come from different runs, and run 7 is a single run. Judge the claim with the gates in this chapter.
Answer
Not admissible as stated. The study store's same_execution rule exists for this: "throughput from one run and accuracy from another do not describe the same configuration", so the run that was measured fast was never shown to be correct. And one run is fewer replicates than any sensible protocol, so the verdict function returns a tie at best. Ask for the accuracy gates and the benchmark from the same execution (or the same build and configuration, recorded), rerun with the pre-registered replicates, and judge the delta against the noise floor. The 12% may well be real; it is not yet evidence.
Problem 7. Design the gates for an agent run that onboards a model whose attention is rewritten from CUDA by tpu-unwiring, then tunes one kernel. Name each gate, its rule, its source, and the negative control that proves it can fail.
Answer
Schema: every request and result against the installed version's schemas; control, the kernel request with input_language: "cuda" (refused) and a payload with no run_id. Parity: module rows at 5% max_rel with hooks on the unwired attention modules; because the rewrite replaces the only CUDA path, plan an independent reference (the model's own PyTorch path on the CPU, or the upstream module at an earlier commit) so the verdict cannot be UNVERIFIED; control, the attention output projection scaled by 1.10, which must FAIL while the output row passes. Artifact: every listed file opened and non-empty; control, a result whose artifact list names a missing file. Kernel: parity per iteration at the request's atol and rtol before measurement, max_iterations as the only stop, baseline_verified required for any speedup you quote; control, a candidate that drops a scale, rejected unmeasured. Performance: a pre-registered noise floor from an A/A run, three replicates, throughput and its accuracy gates from the same execution; control, a claim inside the floor, which must tie. gate_demo.py already implements the schema, parity, kernel and performance controls on the CPU; extend it with the artifact control and your attention module.
Quick questions¶
- Which skill do you talk to, which four specialists does it route to in the 0.7.0 release, and why does the router have no shell?
- What does a knowledge-base result with status
cited-onlytell you, and which statuses mean pages were actually read? - Name the two modes of the onboarding workflow and what each leaves running.
- How does
compare_parity.pygrade a tensor, what is its tolerance, and where does the number come from? - What does
UNVERIFIEDmean, and why is it not a weak pass? - Which lever kind routes to kernel development, and what does the router do with every other kind?
- What is the only stop condition of the kernel loop, and what happens when an iteration fails to commit three times?
- What is
base.py, and why must you readbaseline_verifiednext tospeedup_factor? - Which fields of a kernel request must be copied verbatim from the profile, and what goes wrong when they are paraphrased?
- What does the runtime's artifact check verify, and what does it leave to you?
- State the noise-floor verdict's order of checks.
- What does the suite's eval compare a version against, and why does that matter for your own adoption decision?
Key takeaways¶
- The TPU Agent Suite is one router skill,
tpu-agent, in front of specialists for cited facts, onboarding, profiling and kernels, built per harness by a compiler and run through one runtime that validates every request and result and runs every TPU job. Check which build a capability ships in: the release has two skills; the experimental build adds eleven. - The ladder is the book's method in order: plan from cited facts, onboard (ch. 9), check module-level parity (ch. 23), profile and route on the first lever (ch. 10), model the roofline (ch. 2), tune a kernel in a bounded loop (ch. 12), and verify the gain with the same request and a second trace (ch. 24).
- Grounded, bounded and checked are mechanisms, not slogans: a knowledge-base status that says whether anything was read,
max_iterationsas the loop's only stop, and parity graded per module at a calibrated 5%, withUNVERIFIEDmeaning not checked. - The runtime enforces schemas and the presence of artifacts. Opening the artifacts, reading the parity rows in execution order, checking the kernel's denominator and judging a speedup against a pre-registered noise floor, with replicates and from the same execution, are yours.
- A gate earns trust only when it has been seen to fail: put a negative control in every gate, and never disable the schema hook in a run you will act on.
- The failures to look for look like success: a metric that is not the goal, a speedup against a slow or unverified baseline, shapes and fusions lost in paraphrase, and payloads that drifted from the installed schemas.
- Design an agent workflow gates first, and dry-run it on a laptop: validated payloads, a parity gate that catches what the output hides, a bounded loop that never measures a wrong candidate, and a performance gate that turns a faster-but-wrong result into
invalid.
That is the end of the book: the Appendix collects what it adds up to, where to read next, and a production readiness checklist that gathers the checks of every Part.
References¶
- Introducing the TPU agent suite (preview): Open source agents for PyTorch on Cloud TPU: Google Cloud Tech launch video
- TPU Agent Suite: Onboard, Profile and Tune PyTorch on Cloud TPU: a walkthrough of the ladder, module parity, the roofline step, the kernel loop and the review gates
- TPU agent suite README: harnesses, architecture, quickstart and CI; the repository's
docs/hold the design notes, install and usage guides package.release.json: what the release build shipstpu-agentskill: the router's tools, flow, profiling gate and routing rules- TorchTPU Onboarding Workflow: the onboarding agent's modes and hand-off
decompose-optimizationskill: one of the experimental skills- Torch TPU Inference Workflow: the onboarding checklist
compare_parity.py: module-level parity and its calibrated 5% tolerance- Chip constants and compiler hard limits: v7x VMEM figures
- Schemas: request and result schemas for every specialist
framework/runtime.py: schema verification, the artifact check and job execution- Nightly onboard-and-optimize eval dataset: task briefs and the reward definition
- torchtpu-sprint-26h4: sample code for the agent-suite workflow and the scripts it imports
- Companion code for this chapter






