Calling model.generate() is enough for one local prompt. A service also has to accept requests, decide when they may run, retain state while they run, stream results, and release resources when they finish. Those tasks continue even when the model and decoding algorithm stay the same.
This post follows one request through a serving engine. The small engine below runs one request at a time so that the boundaries are visible. Production engines add batching and a paged KV cache.
In this post, you will learn about:
- How a request moves through a serving engine
- How to build a small asynchronous generation worker and streamer
- How cancellation, backpressure, and metrics shape the service
Let’s get started.
Overview #
This post is divided into four parts; they are:
- The Request Path
- A Minimal Asynchronous Engine
- Cancellation, Backpressure, and Failure
- Metrics and Production Interfaces
The Request Path #
A text-generation workflow from request to response has several components:
The API parser validates the prompt, token limit, and decoding settings before work reaches the GPU. The tokenizer turns text into token IDs. The waiting queue holds requests that cannot run yet. The scheduler chooses work for the next model iteration, subject to limits on active sequences, tokens, and KV cache space. The model executor produces logits. Keeping it supplied with eligible work can improve utilization. The sampler selects token IDs, and the streamer turns them into client-visible text.
The cache manager owns the per-layer keys and values created during prefill and decode. It allocates storage in the layout expected by the attention kernel and maps each sequence’s logical token positions to their physical cache locations. In a paged cache, individual blocks are contiguous, but the complete cache for a sequence need not be. The manager must retain these blocks while a sequence can continue and reclaim them when the sequence ends. Releasing a request object without releasing its cache blocks would eventually exhaust device memory.
The interfaces between these components matter. A scheduler needs token counts and a cache-capacity estimate before admission. An executor needs the selected token positions and cache locations, but does not need to know the client’s HTTP connection. A streamer needs output tokens and a request ID, but does not need direct access to model weights. Keeping these responsibilities separate makes cancellation and measurement easier to reason about.
Offline inference can process a known list of prompts without a waiting queue or network server. An interactive single-user runtime has a queue of at most one request. A multi-user service needs admission control because arrivals and output lengths vary independently.
A Minimal Asynchronous Engine #
The following example uses a small public checkpoint and requires PyTorch and transformers (python -m pip install torch transformers). Run the block in a Python environment with those packages installed. It downloads sshleifer/tiny-gpt2 on the first run. The model is intentionally small; it is used to test the request path, not to provide a reliable answer. This is a teaching example that exposes the jobs an engine coordinates. You can use vLLM for a real service rather than implementing this engine for an application.
Run a minimal asynchronous inference engine.
import asyncio
import threading
import time
from dataclasses import dataclass, field
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
@dataclass
class Request:
prompt: str
max_new_tokens: int
arrived: float = field(default_factory=time.perf_counter)
output: asyncio.Queue = field(default_factory=asyncio.Queue)
cancelled: threading.Event = field(default_factory=threading.Event)
started: float | None = None
first_token: float | None = None
last_token: float | None = None
output_tokens: int = 0
class MiniEngine:
def __init__(self, model_id="sshleifer/tiny-gpt2", max_waiting=4):
self.tokenizer = AutoTokenizer.from_pretrained(model_id)
self.model = AutoModelForCausalLM.from_pretrained(model_id).eval()
self.waiting = asyncio.Queue(maxsize=max_waiting)
self.loop = asyncio.get_running_loop()
self.stats = []
self.worker = asyncio.create_task(self._worker())
def _emit(self, request, value):
self.loop.call_soon_threadsafe(request.output.put_nowait, value)
def _generate(self, request):
try:
inputs = self.tokenizer(request.prompt, return_tensors="pt")
token_ids = []
with torch.inference_mode():
result = self.model(**inputs, use_cache=True)
cache = result.past_key_values
next_id = int(result.logits[0, -1].argmax())
for _ in range(request.max_new_tokens):
if request.cancelled.is_set():
break
token_ids.append(next_id)
self._emit(request, (token_ids.copy(), time.perf_counter()))
if next_id == self.tokenizer.eos_token_id:
break
if len(token_ids) == request.max_new_tokens:
break
result = self.model(
torch.tensor([[next_id]]),
past_key_values=cache,
use_cache=True,
)
cache = result.past_key_values
next_id = int(result.logits[0, -1].argmax())
except Exception as exc:
self._emit(request, exc)
finally:
self._emit(request, None)
async def _worker(self):
while True:
request = await self.waiting.get()
if request is None:
self.waiting.task_done()
return
request.started = time.perf_counter()
if not request.cancelled.is_set():
await asyncio.to_thread(self._generate, request)
else:
request.output.put_nowait(None)
self.waiting.task_done()
async def stream(self, prompt, max_new_tokens=24):
if not prompt or max_new_tokens < 1:
raise ValueError("prompt must be nonempty and max_new_tokens positive")
request = Request(prompt, max_new_tokens)
try:
self.waiting.put_nowait(request)
except asyncio.QueueFull as exc:
raise RuntimeError("waiting queue is full") from exc
try:
while True:
item = await request.output.get()
if item is None:
break
if isinstance(item, Exception):
raise item
token_ids, timestamp = item
request.first_token = request.first_token or timestamp
request.last_token = timestamp
request.output_tokens = len(token_ids)
yield self.tokenizer.decode(token_ids, skip_special_tokens=True)
finally:
request.cancelled.set()
if request.started is not None:
self.stats.append({
"queue_s": request.started - request.arrived,
"ttft_s": (
None if request.first_token is None
else request.first_token - request.arrived
),
"decode_s": (
None if request.first_token is None
else request.last_token - request.first_token
),
"output_tokens": request.output_tokens,
})
async def close(self):
await self.waiting.put(None)
await self.worker
async def main():
engine = MiniEngine()
try:
async for text in engine.stream("The capital of France is"):
latest_text = text
print("output:", latest_text)
print("metrics:", engine.stats[-1])
finally:
await engine.close()
if __name__ == "__main__":
asyncio.run(main())
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
import asyncioimport threadingimport timefrom dataclasses import dataclass, field import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer # Keep the state and timing information for one request together.@dataclassclass Request: prompt: str max_new_tokens: int arrived: float = field(default_factory=time.perf_counter) output: asyncio.Queue = field(default_factory=asyncio.Queue) cancelled: threading.Event = field(default_factory=threading.Event) started: float | None = None first_token: float | None = None last_token: float | None = None output_tokens: int = 0 class MiniEngine: def __init__(self, model_id="sshleifer/tiny-gpt2", max_waiting=4): # Load the model once, then create a bounded admission queue and worker. self.tokenizer = AutoTokenizer.from_pretrained(model_id) self.model = AutoModelForCausalLM.from_pretrained(model_id).eval() self.waiting = asyncio.Queue(maxsize=max_waiting) self.loop = asyncio.get_running_loop() self.stats = [] self.worker = asyncio.create_task(self._worker()) def _emit(self, request, value): # Safely send worker-thread results back to the asyncio event loop. self.loop.call_soon_threadsafe(request.output.put_nowait, value) def _generate(self, request): # Run blocking model execution in the worker thread. try: inputs = self.tokenizer(request.prompt, return_tensors="pt") token_ids = [] with torch.inference_mode(): # Prefill the prompt once and retain its KV cache for decoding. result = self.model(**inputs, use_cache=True) cache = result.past_key_values next_id = int(result.logits[0, -1].argmax()) # Decode one token at a time, emitting cumulative token IDs. for _ in range(request.max_new_tokens): if request.cancelled.is_set(): break token_ids.append(next_id) self._emit(request, (token_ids.copy(), time.perf_counter())) if next_id == self.tokenizer.eos_token_id: break if len(token_ids) == request.max_new_tokens: break result = self.model( torch.tensor([[next_id]]), past_key_values=cache, use_cache=True, ) cache = result.past_key_values next_id = int(result.logits[0, -1].argmax()) except Exception as exc: # Deliver model failures to the request's async consumer. self._emit(request, exc) finally: # A None sentinel marks the end of this output stream. self._emit(request, None) async def _worker(self): # Process admitted requests serially while leaving the event loop free. while True: request = await self.waiting.get() if request is None: self.waiting.task_done() return request.started = time.perf_counter() if not request.cancelled.is_set(): await asyncio.to_thread(self._generate, request) else: request.output.put_nowait(None) self.waiting.task_done() async def stream(self, prompt, max_new_tokens=24): # Validate and admit the request without waiting on a full queue. if not prompt or max_new_tokens < 1: raise ValueError("prompt must be nonempty and max_new_tokens positive") request = Request(prompt, max_new_tokens) try: self.waiting.put_nowait(request) except asyncio.QueueFull as exc: raise RuntimeError("waiting queue is full") from exc try: # Convert cumulative token IDs into text as worker updates arrive. while True: item = await request.output.get() if item is None: break if isinstance(item, Exception): raise item token_ids, timestamp = item request.first_token = request.first_token or timestamp request.last_token = timestamp request.output_tokens = len(token_ids) yield self.tokenizer.decode(token_ids, skip_special_tokens=True) finally: # Cancel abandoned work and record metrics for requests that started. request.cancelled.set() if request.started is not None: self.stats.append({ "queue_s": request.started - request.arrived, "ttft_s": ( None if request.first_token is None else request.first_token - request.arrived ), "decode_s": ( None if request.first_token is None else request.last_token - request.first_token ), "output_tokens": request.output_tokens, }) async def close(self): # Stop the worker through the same queue and wait for clean shutdown. await self.waiting.put(None) await self.worker async def main(): # Submit one request, consume its stream, and display the final metrics. engine = MiniEngine() try: async for text in engine.stream("The capital of France is"): latest_text = text print("output:", latest_text) print("metrics:", engine.stats[-1]) finally: await engine.close() if __name__ == "__main__": asyncio.run(main())
The worker executes blocking PyTorch calls in a thread so the event loop can accept requests and deliver output. The thread sends cumulative token IDs back to the event loop, where the streamer decodes them. Cumulative decoding avoids treating each token’s bytes as a complete piece of text.
This engine still executes only one request at a time. Using asyncio keeps the interface responsive; it does not make the model run requests concurrently. It also uses the model’s ordinary cache object rather than a paged cache manager.
The _worker() method is a minimal scheduler. It takes requests from the bounded waiting queue in FIFO order and runs one request to completion before starting the next. The queue provides basic admission control, while the worker determines execution order. This scheduler does not batch requests, preempt a running request, or choose work one token at a time.
The example also simplifies KV cache management. The cache variable in _generate() holds the transformers past_key_values object returned after prefill and passes it back to the model during each decode step. When _generate() returns, the engine drops that reference. There is no shared cache pool, block table, reference counting, capacity tracking, or explicit block reclamation.
Cancellation, Backpressure, and Failure #
The waiting queue has a fixed capacity. The put_nowait() call rejects a request when it is full instead of allowing unbounded memory growth. A real HTTP server should turn that condition into a documented retryable response and should also bound the number of active requests.
If a consumer stops reading the async generator, its finally block sets a cancellation flag. The worker checks the flag between generated tokens. Cancellation is therefore cooperative: it cannot interrupt an already-running GPU kernel. The final event still releases the stream, and the worker drops its model cache reference when _generate() returns.
The example’s per-request output queue is unbounded to keep the thread-to-event-loop handoff simple. A production streamer needs a bounded output buffer and a slow-client policy. Otherwise, a client that reads slowly can retain a growing number of tokens in host memory. The engine must also handle tokenizer errors, model errors, timeouts, and worker death without leaving requests waiting forever.
When a service uses an explicit paged KV cache, cancellation has one more step: remove the request from future schedules and decrement its block references. The same cleanup is required after EOS, a length limit, and an error.
Metrics and Production Interfaces #
The example records queue time, time to first token (TTFT), decode interval, and output token count. Queue time ends when the worker starts. TTFT begins when the request enters the engine and ends at the first produced token. Decode interval spans the first to the last output token; divide it by output_tokens - 1 for average time per later token when at least two tokens were produced. These timestamps do not separately expose tokenization, prefill, or network transit.
Production services should attach one request ID to parsing, admission, execution, streaming, and failure events. They should also record active and waiting requests, per-request prompt length, generated length, and KV cache occupancy. A device-wide memory reading is not the same as live KV occupancy: weights, workspaces, and reserved cache blocks also consume device memory.
Run this command on a supported GPU to see a full API server. It downloads the public facebook/opt-125m checkpoint. Keep the server running in one terminal and use a second terminal to query its metrics endpoint:
Start a vLLM server and inspect its Prometheus metrics.
vllm serve facebook/opt-125m --max-model-len 512
curl -s http://127.0.0.1:8000/metrics | grep '^vllm:' | head
123
vllm serve facebook/opt-125m --max-model-len 512# In another terminal:curl -s http://127.0.0.1:8000/metrics | grep '^vllm:' | head
vLLM supplies the API parser, scheduler, model executor, KV cache manager, and streamer. The command does not expose all of those as separate Python objects, but their responsibilities are the same as in the request path above. Other engines such as TensorRT-LLM, Hugging Face TGI, SGLang, and llama.cpp make different implementation choices while solving the same request-lifecycle problem.
Further Reading #
- vLLM documentation. Serve CLI . Documents the API server and configuration flags.
- vLLM documentation. Metrics . Documents the metrics endpoint and request, cache, and latency measurements.
- Hugging Face Transformers documentation. Caching . Explains the key-value state used during incremental generation.
Summary #
An inference engine connects request admission, tokenization, scheduling, model execution, cache ownership, sampling, streaming, and measurement. Each component changes the resources a request occupies and the latency the user sees. The minimal engine makes those boundaries visible, while later posts add iteration-level scheduling and explicit cache management.