AI-Built Inference Engine Cuts Time to First Token from 12 Seconds to 0.5 Seconds
An AI-generated inference engine reduced P90 time to first token (TTFT) from approximately 12 seconds to 0.48 seconds in real-world programming sessions, while maintaining nearly the same generation speed as a mature framework. This analysis examines why TTFT matters, the architecture challenges involved, and how scheduling, prefix caching, and hardware-level optimization can improve interactive LLM inference.
As AI-assisted programming becomes part of everyday development, one frustrating problem remains: when developers submit a long error log and source code to an AI assistant, they may wait several seconds before the first character appears. If the proposed fix is incorrect, they must submit additional logs and context, multiplying the waiting time and disrupting their development workflow.
Recently, a research team demonstrated a notable result in a benchmark focused on “agents building agents.” Under offline conditions, with fixed hardware and a strict 12-hour time limit, a frontier large language model autonomously built a complete inference engine.
In subsequent tests using real programming conversations, the AI-built engine reduced P90 time to first token from approximately 12 seconds with a mature conventional framework to just 0.48 seconds. Generation speed remained nearly unchanged. The result demonstrates not only that AI agents can build complex low-level systems, but also that they may offer a new path for optimizing large-model inference.
1. Time to First Token: The Core of Interactive Inference
Large-model inference is commonly evaluated using two key metrics: throughput and time to first token (TTFT).
Throughput measures the total number of requests or tokens a system can process within a given period. TTFT, by contrast, directly affects the user experience. It measures how long a user waits before the model begins responding.
The test used P90 TTFT. To calculate it, all requests are ordered by the time from submission to the first generated token. The value at the 90th percentile indicates the response-start time that 90% of requests meet.
P90 is particularly important in a real programming environment with 16 concurrent sessions because it reflects the user experience under heavy load. A 12-second P90 delay may cause a developer to switch back to the editor and scroll through multiple lines of code before the response begins. A delay of approximately 0.5 seconds, however, creates a much more seamless interactive experience.
2. Architectural Challenges in an AI-Built Inference Engine
Building an inference engine autonomously is far more difficult than generating isolated code snippets. The agent must understand distributed systems, concurrency, task scheduling, and hardware resource management.
Under the benchmark’s strict conditions—no network access, fixed hardware, and a 12-hour time limit—the engine needed to include several essential components:
- Request ingress and routing: Accept concurrent HTTP or gRPC requests from multiple users.
- Task scheduler: Place requests into queues according to priority or arrival time, then assign them dynamically to available GPU resources.
- Execution engine: Load model weights, allocate and release KV cache memory, and invoke low-level operators.
- Streaming response handling: Decode generated tokens in real time and stream them back to users.
The following simplified scheduler pseudocode illustrates how an AI-generated system might handle asynchronous tasks:
import asynciofrom concurrent.futures import ThreadPoolExecutorclass InferenceScheduler:def __init__(self, num_gpus):self.gpu_pool = ThreadPoolExecutor(max_workers=num_gpus)self.request_queue = asyncio.Queue()async def enqueue_request(self, prompt):# Add the request to the asynchronous queueawait self.request_queue.put(prompt)# Wait for the first token to be generatedreturn await self.process_stream()async def process_stream(self):# Reduce blocking through batching and asynchronous I/Oloop = asyncio.get_event_loop()result = await loop.run_in_executor(self.gpu_pool, self._run_model_batch)return resultdef _run_model_batch(self):# Low-level GPU execution logicpass
3. From 12 Seconds to 0.5 Seconds: Key Optimization Paths
Under the same hardware and model conditions, the custom engine achieved a dramatic reduction in TTFT by reworking the scheduling strategies used by traditional inference frameworks. The AI-generated engine may have optimized several areas.
3.1 Dynamic Batching and Queue Optimization
When handling high concurrency, traditional frameworks may use static batching. They wait for a batch to fill or for a timeout to expire before starting the forward pass. This can significantly increase the time users spend waiting for the first token.
A custom engine may instead use a more aggressive form of continuous dynamic batching. When a request arrives and compute resources are available, the engine can begin a forward pass immediately or use preemptive scheduling. This reduces queueing delays and improves responsiveness.
3.2 Efficient KV Cache Reuse and Management
Programming conversations often contain long and repetitive context. For example, developers may repeatedly submit the same source code together with updated logs.
An inference engine can calculate a hash for the prompt and use a prefix cache to reuse previously computed context. When repeated input is detected, the engine can skip attention computation for the cached prefix. This substantially reduces the work required before generating the first token and can bring response startup into the millisecond range.
3.3 Kernel Fusion and Memory-Access Optimization
The difference between 12 seconds and 0.5 seconds is not only a scheduling achievement. It can also depend on how efficiently the hardware executes the model.
A custom engine may redesign attention operators for a specific GPU architecture, reduce unnecessary data movement between GPU memory and on-chip SRAM, and combine operations such as LayerNorm and activation functions. These optimizations reduce the absolute execution time of each forward pass.
4. Why Similar Generation Speeds Point to Prefill as the Bottleneck
The test results showed that the median generation speeds of the two engines were nearly identical after response generation began—approximately 124 to 125 tokens per second.
This reveals an important engineering insight: during the pure decoding stage, different frameworks may already be approaching the practical limits of the available compute. The major difference in user experience instead comes from the prefill stage and task scheduling.
As a result, future inference optimization should move beyond throughput alone. Throughput is highly valuable for offline batch processing, but interactive applications also require extremely low TTFT.
Engineers should therefore focus more attention on:
- Network-layer I/O multiplexing
- Request-priority scheduling
- Context and prefix-cache management
- Efficient prefill execution
- Low-blocking streaming response paths
5. Cloud-Native Practices for Production Inference
Applying a highly optimized inference engine in an enterprise production environment also requires reliable cloud-native infrastructure. Elastic scaling, high availability, disaster recovery, and end-to-end observability all play an important role.
On a general cloud-native platform such as Baidu AI Cloud, developers can use container orchestration to scale inference nodes quickly during traffic spikes. Object storage can distribute multiple versions of model weights, while cloud monitoring and log services can provide near-real-time alerts for key metrics such as P90 latency.
Building a highly available, low-latency AI inference service therefore requires more than an optimized engine. It also depends on close integration between agent-built systems and mature cloud infrastructure.
Conclusion
The case of an AI agent autonomously building an inference engine and reducing P90 time to first token from approximately 12 seconds to 0.48 seconds is more than a successful demonstration of “agents building agents.” It also challenges conventional assumptions about inference-system design.
The result suggests that carefully designed dynamic scheduling, effective context-cache reuse, and a deep understanding of hardware execution can significantly improve the experience of high-concurrency, real-time inference.
As large models become more capable of system-level programming, AI may increasingly reshape foundational software infrastructure. Inference engines are likely to be one of the first areas where this capability produces measurable improvements in application development workflows.
