Explore our next generation products
Built for developers and teams in the agent-first era
Everything you need to stay up-to-date and get help
Autonomous Codebase Optimization with Antigravity & Gemini

Agents in Google Antigravity, powered by Gemini, deliver up to 2.69× speedups on DeepSeek-V4 TPU kernels, find candidate scheduling changes that cut TPU workload interruptions by 55.1% in offline replays of production traces on Google’s Borg cluster scheduler, and achieve a +5.0% speedup on the DPC4 CPU data-prefetcher benchmark, beating the best human (+3.5%) and prior AI (+3.8%) designs in under a quarter of the time and a fifth of the evaluations.
Real-world codebase optimization presents a distinct challenge: progress is governed by a quantitative benchmark, and running that benchmark is often far slower than generating candidate edits. The agents behind these results solve this by jointly discovering what to optimize and how to measure progress cheaply. We ran these campaigns in Google Antigravity using /teamwork, where this codebase optimization capability is rolling out in the next update.
The limitations of standard agent loops for codebase optimization
Most coding agents and discovery systems share a quiet assumption: evaluating a candidate solution is fast. On real production systems, this assumption breaks down. Benchmarking a TPU kernel suite routinely takes tens of minutes, measuring an LLM serving engine like vLLM takes nearly 1.5 hours per candidate, and simulating a CPU microarchitecture design across realistic workload traces can take more than a day. Under a practical wall-clock budget, a standard agent loop can afford only a handful of true evaluations before time runs out.
Mitigating this bottleneck requires fast evaluations, yet hand-crafting microbenchmarks ahead of time does not scale. Every bottleneck needs its own proxy, and static proxies quickly fall prey to Goodhart’s law: as an agent optimizes against a fixed proxy, it learns to exploit small gaps between the proxy and the true benchmark, driving the proxy score up while real performance stagnates or regresses. Simply throwing more parallel agents at the problem does not fix it either; without fast feedback to iterate on and coordination across branches, independent agents crowd onto the same obvious hotspots, duplicate each other’s search, and spend most of their budget idling on slow benchmarks.
Autonomous optimization in real engineering environments therefore requires more than a better search loop over code. The system itself must discover how to evaluate progress efficiently, verify that its fast proxies remain faithful as the code evolves, and reserve expensive true evaluations for confirmations.
TPU kernel optimization results
To test this approach in Google Antigravity on frontier accelerator workloads, we ran it on five DeepSeek-V4 Pallas TPU kernels (four of which are in the open-source vLLM TPU-Inference repository): Multi-Head Latent Attention (MLA), Sliding-Window Attention MLA (MLA SWA), Masked Dense MLA, Sparse MLA, and Streamindex TopK.
Importantly, the baseline (1.00×) for every kernel is the existing Pallas reference kernel written by performance engineers. We evaluated this approach on these five kernels using both Gemini Carbon (our strongest long-horizon reasoning model) and Gemini Hydrogen (our fast, lower-cost execution model).
DeepSeek-V4 TPU Kernel Speedups with Teamwork
Speedup over Pallas reference kernels (higher is better) using Gemini Carbon and Gemini Hydrogen
Figure 1: DeepSeek-V4 TPU kernel speedups over the Pallas reference baseline (1.00× dashed line). Both Gemini Carbon and Gemini Hydrogen discover substantial speedups across all five kernels, reaching 1.97× and 2.10× geometric mean respectively.
Across all five DeepSeek-V4 kernels, the agents consistently unlocked 1.50× to 2.69× speedups while passing every correctness and tolerance test. Rather than making narrow parameter tweaks, worker agents isolated individual kernel stages, built fast per-stage yardsticks, explored different tiling, memory-layout, and scheduling strategies in parallel, and combined complementary gains into verified end-to-end kernels.
Turning lower per-token cost into stronger search: Carbon vs. Hydrogen
One of the takeaways from these runs is how multi-agent orchestration changes the economics of model selection. Gemini Hydrogen costs $1.50 / $0.075 / $7.50 per million uncached input, cached input, and output tokens, which is 2.67× cheaper per token than Gemini Carbon ($4.00 / $0.20 / $20.00). Because Hydrogen is substantially cheaper per token and faster per call, a comparable overall budget buys far more autonomous search volume. Table 1 compares the total token usage and cost over all five DeepSeek-V4 kernel optimization campaigns.
| 5-Kernel Campaign Metric | Gemini Carbon | Gemini Hydrogen | Hydrogen / Carbon |
|---|---|---|---|
| Geometric-mean speedup | 1.97× | 2.10× | 1.06× |
| Total agents (root + subagents) | 208 | 334 | 1.61× |
| Total LLM calls | 33,195 | 163,797 | 4.93× |
| Total prompt tokens (cache hit rate) | 5.14B (48.4%) | 26.23B (85.7%) | 5.10× |
| Output tokens (thinking + response) | 59.6M | 202.1M | 3.39× |
| Estimated API cost | $12,305 | $8,826 | 0.72× |
Table 1: Aggregate agent scale, token usage, and estimated API cost across all five DeepSeek-V4 TPU kernel optimization campaigns. Note: Prompt cache hit rates also affected realized cost (85.7% on Hydrogen vs. 48.4% on Carbon, where uncached input is priced 20× higher than cached reads; normalized to an equal 85.7% cache hit rate, the five Carbon runs would total roughly $5,016).
Even though Hydrogen is a faster, lower-cost model than Carbon, at a comparable overall cost across the five kernels (with realized spend also shaped by prompt cache hit rates, as noted in Table 1), the agents ran nearly 5× as many LLM calls (163,797 vs. 33,195) and 3.4× as many output tokens (202.1M vs. 59.6M). Guided by fast local yardsticks, statistical fidelity checks, and clean-room verification, Hydrogen converted that extra search volume into results that matched or exceeded Carbon: closely trailing on MLA (2.05× vs. 2.11×) and MLA SWA (1.82× vs. 1.85×), while pulling ahead on Masked Dense MLA (2.69× vs. 2.56×), Sparse MLA (2.31× vs. 2.00×), and Streamindex TopK (1.76× vs. 1.50×) for a 2.10× overall geometric mean versus Carbon’s 1.97×.
Data center scheduling optimization results
Beyond TPU kernels, we tested the same codebase optimization workflow on Borg, Google’s large-scale cluster management system. Borg’s C++ scheduler has been continuously tuned for years, and evaluating a single candidate requires replaying hours of production cluster traces, while enforcing strict placement invariants, availability guardrails, and unit tests.
Using Gemini Carbon, we ran three autonomous optimization campaigns spanning both scheduling quality (reducing workload interruptions) and scheduler execution efficiency (increasing scheduling throughput and cutting CPU usage). All results below come from offline simulations and replays of production cluster traces; they represent promising candidate changes that are currently under review with the Borg team and have not yet been validated or deployed in production.
- TPU colocation scheduling policy: In 12-hour multi-cluster replays, the agents proposed a redesigned placement scoring order across 15 C++ files to prioritize protecting active workloads over aggressive bin-packing and minimize disruption when preemption is unavoidable, cutting overall interruptions per chip-hour by 55.1% (2.23× improvement), serving interruptions by 72%–83%, training interruptions by 54%–93%, and disrupted chips by 41.8%, while passing all availability and disruption guardrails.
- TPU colocation scheduler throughput: Targeting execution speed in the same TPU colocation subsystem under exact placement invariance, the agents eliminated redundant work when evaluating candidate placements across 24 C++ files (hoisting invariant checks, caching tree lookups, removing hot-path allocations, and fusing multi-pass traversals), cutting colocation subsystem CPU usage by 71.3% (3.49× subsystem speedup) and lifting steady-state scheduling throughput by +27.1% in paired trace replays with zero change to placement decisions.
- Core host scheduler throughput: Targeting Borg’s core host scheduler under saturated peak-load replays averaging ~2.7 hours per evaluation, the agents identified candidate optimizations across 26 files yielding +37.3% higher steady-state throughput, +34.3% more tasks placed per pass, and 1.56× less CPU per placement, with zero infeasible placements.
CPU design optimization results
Building on recent progress in AI-driven hardware design, we applied the same approach to CPU data-prefetcher design under the DPC4 benchmark. DPC4 grades designs under a fixed storage cap, simulator, and trace suite with each evaluation spanning over 1,700 simulations and taking up to 28 hours. Within this setting, Antigravity with Gemini Carbon achieves a +5.0% geometric-mean speedup across all three evaluation regimes (single-core full bandwidth, single-core limited bandwidth, and multi-core), exceeding both the best human-crafted entry, BertiGO (+3.5%), and the prior AlphaEvolve-based system, ArchAgent v2 (+3.8%). Whereas ArchAgent v2 spent over 40 days and graded more than 12,000 candidates, we obtained these results in just 9.6 days across 2,244 graded candidates. To put this margin in perspective, single-core CPU performance currently advances by roughly 3.5% per year despite heavy engineering investment.
Together, these results (spanning frontier TPU kernels, large-scale cluster schedulers, and CPU microarchitecture design) show that this codebase optimization approach generalizes across the computing stack, uncovering promising algorithmic improvements and deep execution speedups across dozens of files even when true evaluations take hours or days.
How it works
The workflow behind these results is based on the research behind our paper DuoDiscover: Scaling Autonomous Discovery Beyond the Evaluation Bottleneck, which we ran in Antigravity via /teamwork. It reframes optimization under expensive evaluation around three tightly coupled mechanisms: target and yardstick co-discovery, a two-loop search protected by continuous statistical fidelity testing, and bottom-up fleet orchestration with a clean-room trust boundary.
1. Co-discovering targets and yardsticks
Rather than asking a human engineer to manually annotate mutable hot loops, or relying on a central planner to decompose the codebase up front, each worker agent explores the codebase bottom-up. The workers profile execution, estimate each region’s cost share and reducible gap to its analytical floor (such as Amdahl’s law or hardware roofline), and jointly choose two things:
- An optimization target: A focused region of code with meaningful score-weighted headroom.
- A target-specific yardstick: A proxy evaluator built by the worker itself that checks local correctness and scores candidate edits 20× to 50× faster than the true evaluation.
The two are discovered together because a target is only practical to search aggressively if a fast, faithful proxy can be built for it, and a yardstick is only worth climbing if its target can move the overall true objective. Crucially, a yardstick does not need to match the true benchmark’s absolute scale, it only needs to rank candidate edits in the same order as the true evaluation.
2. The two-loop search: fast yardsticks and slow true evaluations
Once a worker co-discovers a target and builds its yardstick, it operates across two nested feedback loops: a fast inner loop running in seconds and a slow outer loop running in minutes or hours.
Inside Each Worker: Fast Inner Loop vs. Slow Outer Loop
Each worker hill-climbs a fast, target-specific yardstick while clean-room true evaluations confirm gains and detect proxy drift
Profile code & pick high-headroom bottleneck (Amdahl’s law / roofline)
Reduced inputs · Hot-loop harness · Filtered tests · Static cost model
- Edit code on isolated branch
- Tune parameters & layouts
- Test alternative algorithms
- Fast rank-preserving proxy
- 20× to 50× faster than true eval
- Local score + quick correctness
- Stages allowlisted diff on pristine baseline
- Audits candidate against benchmark gaming
- Runs full test suite & canonical benchmark
- Records median score to evaluation ledger
- Pairs yardstick vs. true candidate scores
- Filters out pairs within noise floor
- Measures rank correlation (Kendall’s tau)
- Rechecked after every true evaluation
Promoted to best solution & shared (cross-seed / combine)
Figure 2: Inside each worker. In the fast inner loop, the worker agent co-discovers a target and yardstick and hill-climbs candidate edits in seconds. Promising milestones exit to the slow outer loop, where an isolated Evaluator runs the full test suite and true benchmark, updates the append-only ledger, and runs a statistical fidelity test that either validates the yardstick or triggers an in-place rebuild when proxy drift occurs.
In the fast inner loop, the worker edits code inside its isolated branch, scores each candidate with its yardstick, keeps improvements that clear local measurement noise, and reverts regressions. Because each yardstick check takes seconds instead of tens of minutes, workers can go beyond tweaking parameters to test different algorithms and data layouts against the yardstick, keeping the fastest approach and screening out more than 80% of unpromising edits before ever spending an expensive true evaluation.
Whenever a worker reaches a milestone on its yardstick, it triggers the slow outer loop by dispatching an Evaluator. The evaluator copies only the allowlisted mutable files onto a pristine baseline branch, audits the diff for benchmark gaming (such as input-keyed lookup tables, timer manipulation, or loosened numerical tolerances), runs the full test suite and canonical benchmark, and records the median true score in an append-only evaluation ledger.
Every time a true evaluation lands, the system automatically runs a statistical fidelity test pairing the worker’s yardstick scores against the confirmed true scores across distinct candidates. Pairs whose true scores fall within the benchmark’s measured noise floor are filtered out so timing jitter never creates spurious signal; on the remaining resolved pairs, the evaluator measures Kendall’s τ rank correlation:
- Validated: When rank correlation clears the fidelity threshold (τ ≥ 0.5), the yardstick is trusted to track the true objective. The worker keeps climbing, and confirmed gains that clear the noise threshold are promoted to the campaign’s verified best solution and shared with the rest of the fleet.
- Drifted (lying yardstick): If proxy optimization causes rank inversion, puts the wrong candidate in first place, or passes a candidate that fails the real test suite, the fidelity test invalidates the yardstick. Rather than discarding the worker’s engineering effort and killing the slot, the orchestrator instructs the worker to rebuild its yardstick (or pick a sharper target) while preserving its branch and accumulated lessons.
In our empirical studies, over 40% of initially valid yardsticks eventually drifted as code evolved, underscoring why continuous re-testing is essential. Because every reported improvement must pass a clean-room true evaluation, a false gain on a yardstick can never be injected into the final result.
3. Bottom-up agent orchestration
The agent team uses a lightweight Orchestrator coordinating a fleet of self-directed, branched workers alongside on-demand reviewers and strict verification gates.
Codebase Optimization in Teamwork: Agent Orchestration Overview
Bottom-up target and yardstick co-discovery across isolated branches, coordinated by an orchestrator and verified through a clean-room trust boundary
Quantitative metric (latency, throughput, memory, kernel speed)
Scopes contract & allowlisted paths
Measures baseline & noise spread
Never edits source; guides bottom-up
Climbs fast inner loop (seconds / edit)
Diverse regions & structural families
Seeded from best solution + peer snapshots; reconciles edits & keeps only gains that compose cleanly under true evaluation
- 1. Stage allowlisted diff
- 2. Audit against gaming
- 3. Run full tests & bench
- 4. Rank fidelity test
Sole writer to Ledger
& verified best snapshots
Verifies provenance & diff integrity
Re-runs full tests & benchmark from scratch
True scores · Fidelity verdicts
Verified solution snapshots
Published to workspace
Spots convergence, plateaus & missed merges; returns structural directives to Orchestrator
Runs correctness-cheat & dominance probes; flags lying yardsticks or edge-case regressions
Figure 3: End-to-end agent orchestration overview. The Sentinel scopes the campaign contract and baseline; the Orchestrator coordinates parallel branched Workers and Combiners without assigning rigid subtasks; on-demand Critics and an Analyst pressure-test yardsticks and diagnose fleet-wide plateaus; and the Evaluator and independent Victory Auditor enforce a strict trust boundary before publishing verified code.
Every role in the team has a clean separation of authority:
- Sentinel (
/teamworkrouter): Records the optimization contract, measures the untouched baseline and noise spread, and stays available throughout the campaign so you can inspect live progress or steer priorities mid-run. - Orchestrator: Coordinates the fleet without ever editing source files itself. It deduplicates redundant searches, briefs workers with fleet discoveries, cross-seeds confirmed wins onto peer branches so workers start from the latest verified best solution rather than the baseline, spawns Combiner workers to merge complementary confirmed gains into a single unified patch, and retires stalled or redundant slots while protecting workers mid-rewrite or mid-evaluation.
- Parallel Workers: The workers independently profile the code for bottlenecks, build fast local yardsticks, iterate on parameter tweaks and alternative algorithms in the inner loop, and submit promising milestones to the Evaluator. Each worker runs in its own branched copy of the codebase, so concurrent refactors never collide.
- On-Demand Critic & Analyst (read-only): Workers and the Orchestrator can summon a Critic to verify that a yardstick cannot be fooled. If the fleet plateaus, converges on one approach, or leaves disjoint wins unmerged, the Orchestrator summons an Analyst to diagnose the whole-fleet blindspot and return structured steering directives.
- Evaluator & Victory Auditor (trust boundary): Workers can never write to the evaluation ledger or declare victory. Only the isolated Evaluator grades allowlisted diffs on a pristine baseline branch and publishes verified best-solution updates. When the campaign stops, an independent Victory Auditor checks the full ledger timeline, audits the published diff against every original user constraint and anti-gaming rule, and re-executes the complete test and benchmark commands from scratch before delivering the final optimized code. If anything fails the audit, the result is rejected and the fleet resumes to address the findings.
Use cases
This approach works with any existing codebase that already has a runnable correctness test and a quantitative benchmark command, and you want to push a measurable metric as far as possible without breaking functionality. Typical workloads include:
- TPU and GPU kernel acceleration: Optimizing Triton, CUDA, or Pallas kernels across production tensor shapes while preserving strict numerical tolerances.
- Repository-level performance engineering: Finding speedups across large projects such as scientific Python libraries, C/C++ engines, parsers, compilers, or data processing pipelines while passing extensive test suites.
- Inference and serving stack optimization: Improving latency, throughput, memory footprint, or power efficiency across complex serving stacks.
- CPU architecture design: Designing and tuning microarchitectural components such as data prefetchers, branch predictors, or cache policies on cycle-level simulators across large workload trace suites.
Getting started
You can try Google Antigravity today, and run this optimization workflow on your own codebase with the next update:
- Open your repository with a runnable test and benchmark command in Google Antigravity.
- Invoke
/teamworkand state the metric to optimize (such as latency, throughput, runtime, memory usage, binary size, or kernel speed). For example: “Optimize the p95 latency of this parser on bench/run.sh while keeping all unit tests passing” or “Optimize this Pallas kernel against bench/eval.py.” - Antigravity automatically dispatches this agent team, measures your baseline, runs parallel workers with clean-room evaluation, and returns an independently audited diff.
Contributors to the DuoDiscover research, TPU kernel, Borg scheduling, and Teamwork integration work featured in this post include Mike Heddes, Nanyun (Violet) Peng, Chun-Liang Li, Vahab Mirrokni, Burak Gokturk, Parthasarathy Ranganathan, Tomas Pfister, Shubham Agarwal, Akshat Gupta, Dilara Soylu, Rui Meng, Patrick Tser Jern Kon, Zhenwen Liang, Jiefeng Chen, Mert Cemri, Shu Liu, Abe Gonzalez, Akanksha Jain, Bhavana Dalvi Mishra, Linfeng Song, Vilobh Meshram, Xiangru Tang, Jinsung Yoon, Aditya Parameswaran, Ion Stoica, Song Zuo, Yuan Deng, Vishnu Veeramachaneni, Guangxiang Du, Jacob Platin, Qiliang Cui, Patrick Heisel, Yinan Li, and Jordan Firnbach.