AI Engineer Code Summit 2026
Inference Engineering for Coding Agents — Philip Kiely, Baseten
Loading slides…
Read the talk
Inference Engineering for Coding Agents
Philip Kiely explains how Baseten trains a model router, decides when a subagent should give up a warm KV cache, and uses coding agents to find GPU optimizations that make the whole model faster.
From a talk by Philip Kiely
At a glance
Ideas worth remembering
Route on expected success and total task cost. A tenfold discount per token disappears if the model uses ten times as many tokens.
Repeated attempts help separate routing skill from luck. Baseten averaged four Opus runs and eight GLM runs per task, then used task features and GLM’s internal activations to predict which model was worth using.
One benchmark comparison yielded 72% lower cost with less than a one-point quality loss, against an unspecified baseline. The routing decision itself added at most 429 ms at p95.
A short subagent request can benefit from keeping the parent’s session affinity. Compaction becomes economical when enough future turns use the shorter context to repay summarization and the initial cache miss.
Give a kernel-writing agent the production workload profile and require both correctness and end-to-end gains. Removing memory transfers, overlapping independent work or reducing CPU submissions may save more time than accelerating a single operation.
Choose the model before optimizing its inference
You can spend a lot of engineering time making inference 5% cheaper when choosing a different model might save you 50%. That’s why Philip Kiely starts Baseten’s work on coding agents with request routing, even though deciding which model gets a request sits a little outside traditional inference engineering.
The apparent size of the routing problem is intimidating. There are millions of models to choose from, with different combinations of capability, speed and price. In practice, the coding agents Kiely looks at usually give their router two or three choices. There’s a frontier model, a cheaper Flash model and occasionally something in between.
Even the two-model problem is hard. When was the last time you sat down to write some code, estimated it would take two hours and finished in two hours? A router has to make a similar judgment before anybody has started the work. A request to build a web page or fix a kernel gives it surprisingly little to go on.
Baseten’s experiment pairs Opus, the more capable and expensive option, with GLM Flash, which is substantially cheaper and faster. Ideally, GLM gets every task it can handle well enough. The hard part is estimating how much additional probability of success you buy by sending a particular task to Opus.
One way to express that decision is to give each candidate model a score for task .
Here is the expected cost of doing the whole task, and expresses how much cost matters relative to success. Pick the model with the higher score. If one model charges a tenth as much per token but uses ten times as many tokens, its apparent price advantage disappears. The router needs to predict how much work each model will do.
Run the same coding task enough times to learn from it
Training that predictor requires traces of both models attempting comparable tasks. Production traces from your own coding agent would give you a useful starting distribution. Baseten used public benchmarks so it could compare models on common ground, repair broken task environments, add safeguards against cheating and remove problematic examples. What kind of work would this router learn to recognize? More than 90% of the data came from software engineering benchmarks such as SWE-bench.
Running each model once on each task would give you a dataset quickly. It would also make two kinds of luck look like intelligence.
- Label noise. The same model can pass a task on one attempt and fail on the next. A single pass tells you it can solve the problem, but gives you a poor estimate of how reliably it will do so.
- Selection noise. Even a router that flips a coin can happen to pick GLM on a task where GLM succeeds. Enough lucky selections make the routing policy itself look better than it is.
Baseten ran each task four times with Opus and eight times with GLM. The subsequent comparisons use averages over those runs. That costs considerably more tokens, but gives the team a much better estimate of each model’s performance on each task. As Kiely points out, tokens are one thing an inference company tends to have lying around.
The coin flip is worth keeping as a baseline. Heads goes to Opus, tails to GLM. A learned router needs to beat random allocation by a statistically meaningful margin before you can credit its choice of tasks for the improvement.
What can you predict before generating an answer?
Start with the task instructions. An existing embedding model such as Qwen3-Embedding or EmbeddingGemma can turn them into a vector of semantic features. Using the benchmark traces as training data, fit separate prediction heads on those features to estimate each candidate’s probability of success and expected cost. This lets you train the predictors without training an entire language model from scratch.
Baseten compared three ways of making the decision.
- Success advantage alone. Estimate how much more likely one model is to solve the task.
- Cost advantage alone. Estimate how much money you could save by choosing one model over the other.
- Success relative to cost. Estimate both advantages and decide whether the improvement in success justifies the extra expense.
The combined approach worked best. An expensive model might have a small edge on many tasks, but you’d like to reserve the extra spending for the tasks where that edge is large. There’s also a feature-selection problem. An embedding gives you hundreds or thousands of numbers. When the team investigated which features actually helped make that decision, task category emerged as a useful signal.
The more interesting experiment was to ask whether GLM already knew something about how much trouble it was going to have. Baseten ran the task through GLM without generating a response, captured intermediate activations and trained a head to predict the number of steps in the eventual response. That estimate turned out to be a strong signal of task difficulty. The team didn’t have equivalent access to Opus’s internal state.
How do those observations fit into one routing decision? At request time, the trained predictors can estimate outcomes for both models from the instructions. GLM contributes an additional estimate of the effort ahead. The router can combine those estimates with structured facts about the task without paying for two complete answers.
Three sources of information for one routing decision
Read the diagram as text
- Incoming coding task. The instructions are available before either candidate generates an answer.
- Structured attributes. Task category is one useful feature.
- Instruction embedding. A pretrained embedding model represents the meaning of the request.
- GLM forward pass. Capture intermediate activations without decoding a response.
- Per-model predictions. Estimate success probability and task cost for Opus and GLM.
- Predicted response steps. A head trained on GLM’s activations estimates how much work is ahead.
- Choose Opus or GLM. Weigh the expected improvement in success against the additional task cost.
- Incoming coding task → Structured attributes: Identify task attributes.
- Incoming coding task → Instruction embedding: Embed instructions.
- Incoming coding task → GLM forward pass: Process the prompt.
- Instruction embedding → Per-model predictions: Apply prediction heads.
- GLM forward pass → Predicted response steps: Predict step count.
- Structured attributes → Choose Opus or GLM: Task features.
- Per-model predictions → Choose Opus or GLM: Expected advantages.
- Predicted response steps → Choose Opus or GLM: Difficulty signal.
How much quality does the cheaper route give up?
To read the router comparison, pick a level of task success and ask how cheaply each strategy reaches it. Or hold spending fixed and compare success rates. The most useful points form a Pareto frontier, where improving one measure requires giving something up on the other. Baseten’s combined router reached that frontier on its benchmark.
At one operating point, Kiely reports 72% lower cost with less than a one-point drop in output quality. He doesn’t specify the baseline for that particular comparison in his explanation. The routing model itself added at most 429 milliseconds at the 95th percentile in the measurements he presented. That latency is the time spent deciding where to send the request. For this particular saving, Kiely was happy to spend roughly half a second making the decision.
There’s a good reason to resist reading the comparison as a general ranking of routers. Other teams may have trained for different tasks or optimized for different objectives. The method is more widely useful. Collect repeated outcomes for the models you actually serve, find features that predict their relative advantages, and include the router’s own time and cost when deciding whether to deploy it.
Then a real user comes along and types something like please fix this. Even a very good embedding of those three words won’t tell you much about the work ahead. Much of the useful information is in the preceding conversation.
Why the expensive model might get the easy follow-up
Imagine you’ve just asked the frontier model to implement a complex feature. It finishes, you look at the result, and you ask it to center the div. Taken on its own, that follow-up looks like an obvious job for the cheap model. But the expensive model may already have almost the entire conversation in its key-value cache.
The KV cache holds attention keys and values computed for earlier tokens. When the next request begins with the same sequence of tokens, prefix caching lets the serving engine reuse that work. Switching models can mean processing the long history again just to make a tiny CSS change. That cost belongs in the routing decision.
The client can help by sending a consistent session ID in the provider’s affinity header across turns. That gives the provider a reason to expect a long prefix match in a recent cache and route the request accordingly. The header is a hint. The reusable work comes from the matching tokens.
Forking a subagent makes the choice more interesting. Should the side request keep the parent’s session ID or get a new one? That depends on how much of the parent’s prefix the subagent will actually carry forward.
How many turns will it take to pay for compaction?
Context compaction replaces a long history with a shorter account of what the agent needs to continue. Kiely passes along a recommendation from Baseten’s research team to let the model write that summary. The models they work with practice summarizing their own context during reinforcement learning, which makes a prompt to the model an attractive alternative to fixed compaction rules in the agent harness.
Summarizing has two upfront costs. You pay for the summary itself, and the serving engine has to compute KV entries for the changed, uncached input. The payoff comes on subsequent turns, when the subagent carries a shorter prefix. Even cached input can cost money, so shortening a prefix you’ll use repeatedly can be worthwhile.
Where do those costs cross? Call the extra one-time expense of switching to a summary and the average saving on each subsequent turn . In a simplified calculation with positive, constant savings, compaction pays off after turns when
The break-even point in Kiely’s example is illustrative. It moves with the model, how much context the summary removes, and the price of cached input relative to ordinary input. A generous cache discount makes the existing long prefix more attractive.
That gives the harness a practical way to choose what happens when the main agent delegates work.
- A quick side request. Keep the parent’s context and affinity header, do the one turn or short sequence, and return to the main agent. There are few opportunities to recover the cost of a summary.
- A longer investigation. If enough turns remain, compact the context and let the subagent build up a cache around its shorter prefix. As the shared prefix shrinks, there’s less reason to preserve affinity with the parent’s session.
A short detour into speculative decoding
Speculative decoding exploits the predictability of upcoming tokens. A cheaper mechanism proposes tokens for the main model to verify. Kiely favors DSpark over DFlash, pointing to an additional prediction head that introduces sequential dependence between draft tokens and helps more of them get accepted.
For a DSpark speculator serving coding agents, his advice is to narrow the training data to the domain. A learned speculator can predict new sequences. Code completion and revision may admit an even simpler solution when much of the code repeats. An n-gram lookup can find matching token sequences and propose the tokens that followed them previously, avoiding a separate learned draft model. The SGLang speculative decoding guide describes how to try that approach.
The agent made the matrix multiply faster. Why is the model still slow?
Now turn the relationship around and put the coding agent to work on inference itself. Kiely’s example starts with a general matrix multiplication kernel, or GEMM, that takes 0.03 milliseconds. The agent improves it to 0.02 milliseconds. A third of the kernel’s runtime is gone. The model runs just as fast as before.
The absolute saving in this illustration is ten microseconds per invocation. Whether the user ever sees that saving depends on how often the operation runs, how much of the request waits for it and whether the improvement survives the production workload. Change the batch size, the traffic mix or how full the batches are, and a different kernel configuration may win.
Getting the replacement into vLLM, SGLang or TensorRT-LLM adds another complication. The kernel operates inside a serving engine with other work to schedule and data to move. A benchmark that times one operation in isolation can miss both the cost of integrating it and a larger opportunity to eliminate work between operations.
Baseten gives its optimization agent two levels of work. At the model level, profile the full workload, find where time goes and propose changes that address those bottlenecks. At the kernel level, work on individual implementations once the profile has identified them as consequential.
A proposed kernel has to pass a correctness check and an end-to-end performance check before the framework retains it as a candidate for further improvement. The agent records lessons from both successful and failed attempts in memory. A correct, faster GEMM that leaves model latency unchanged is a useful failure to remember. It tells the next attempt something about where to spend its effort.
Remove memory trips, overlap kernels and cut CPU launches
Kernel fusion removes a memory round trip. Suppose one kernel produces a value that the next kernel immediately consumes. Running them separately can require writing the intermediate value to GPU memory and reading it back. A fused implementation can keep that intermediate local and do both operations in one launch. You save launch overhead and memory bandwidth. The latter is particularly valuable during token-by-token decoding, when reading weights and moving intermediate values through GPU memory can already limit performance.
Programmatic Dependent Launch (PDL) changes when work can start. Suppose kernel B consumes results from kernel A. In the ordinary schedule Kiely describes, B waits for A to finish and make its results available in memory. How much of B could start earlier? With PDL, blocks of B can begin independent work while A is still finishing. The part that reads A’s output must still synchronize before using it.
The opportunity comes from separating the start of B from the first point at which B actually needs A’s data. Moving independent work into that interval can close some of the gap between kernels while preserving the dependency that makes the computation correct.
Grouping launches reduces work on the host CPU. With asynchronous launches, the CPU should stay ahead of the GPU and leave it a queue of pending work. Scheduling hundreds of kernels individually can make the CPU control loop the bottleneck. Grouping the operations into a small number of execution graphs reduces the number of submissions the host has to make. The GPU can stay busy even if none of the individual kernels gets faster.
Where the agent found room to improve whole models
For a production example, Baseten tried its framework on two image generation models, Qwen-Image and FLUX.2. The choice was deliberate. The common language model paths in vLLM, SGLang and TensorRT-LLM already benefit from extensive kernel optimization. Kiely saw more room for large improvements in image generation.
How much did each image generation workload benefit? The agent proposed and implemented the optimizations itself, including kernel fusion. Kiely reports substantial performance improvements across these experiments. The gains depend on the workload and how much room its existing implementation left for optimization, so they don’t establish a general speedup factor for coding models.
The change in the agent’s assignment is easy to miss. Give it a GEMM and a stopwatch, and it can discover how to save ten microseconds. Give it the workload profile and a way to test the full model, and it can discover that two kernels should be one, or that the GPU is waiting on the CPU. Extend that visibility to routing, speculation and cache reuse, and the agent can help decide which part of its own inference system is worth improving next.
Resources
Further reading
Chapter 4 covers kernel selection, fusion and profiling. Chapter 5 develops speculative decoding, prefix caching and cache-aware routing. Chapter 6 extends the discussion to image generation kernels.
Explains how RadixAttention reuses cached attention state across language model calls, providing background for the subagent affinity decision.
Configuration examples for learned draft models and n-gram speculation, including parameters that control how many proposed tokens the target model verifies.
Kiely and Pankaj Gupta’s archived workshop materials walk through building an inference engine, deploying it and comparing performance under different request loads. The exercises use historical dependency versions.
Full transcript
Loading transcript…