Why model.generate() Isn't a Service Yet: A Mini LLM Engine with a 4-Request Queue
A single model.generate() call handles one prompt, but a service also has to accept requests, line them up in a queue, and free GPU memory. Machine Learning Mastery author Adrian Tam built a teaching engine on tiny-gpt2 with a queue of four slots; the fifth request is rejected immediately. While a request runs, its KV cache sits in memory, holding the stored attention data so the text does not have to be recomputed from scratch. For a real service, the author recommends vLLM rather than his own code.
AI-processed from Machine Learning Mastery; edited by Hamidun News
Imagine you run a model on your laptop: one model.generate() call, and the answer is ready. Now imagine dozens of users send requests to the same model at once. Who gets answered first? What happens when every slot is taken? Where does GPU memory go when a client closes the tab halfway through a response? Transformer tutorials usually skip all of this. Adrian Tam of Machine Learning Mastery walked through this path for a single request and built a teaching engine where the boundaries between components are visible right in the code.
The request path: what the engine is made of
A request passes through several stages. First, the API parser checks the prompt, the token limit, and the decoding settings before the work reaches the GPU. The tokenizer turns the text into numeric token IDs. Requests that have no room yet wait in a queue. The scheduler decides what goes into the next model iteration, taking into account limits on active sequences, tokens, and space in the KV cache. The model executor produces logits (scores for the probability of the next token), the sampler picks a token, and the streamer turns tokens into text for the client.
The cache manager has a separate role. The KV cache holds the attention keys and values for each layer, computed during the prefill stage (processing the prompt) and the decode stage (generating the response token by token). Without it, the model would recompute the entire text at every step. The manager maps the logical positions of tokens to physical locations in memory. In a paged cache, individual blocks are stored contiguously, while the cache for a whole sequence may be scattered across memory. If you free the request object but not its cache blocks, device memory will eventually run out.
The author stresses the importance of interfaces. Before admitting a request, the scheduler needs the number of tokens and an estimate of free cache. The executor needs token positions and cache addresses, but it does not need to know the client's HTTP connection. The streamer needs output tokens and the request ID, but not the model weights. This separation simplifies both cancellation and measurement.
The mini engine: what it does and what it doesn't
The example uses the tiny model sshleifer/tiny-gpt2, along with PyTorch and transformers. The model's output is meaningless, but the whole path is visible. A request is stored in a single object together with its timings. The queue is bounded, with four slots by default: when it is full, put_nowait() rejects the request immediately instead of letting memory grow without control. Blocking PyTorch calls run in a separate thread so the event loop can keep accepting new requests and delivering tokens. The thread sends back the accumulated list of token IDs, and the streamer decodes it as a whole, so the bytes of one token are not mistaken for a finished piece of text.
An honest limitation: the engine processes one request at a time. Asyncio keeps the interface responsive, but it does not make the model run in parallel. The scheduler here is simply a FIFO queue, with no batching, preemption, or selection of work by token count. The cache is the plain past_key_values from transformers, discarded when generation finishes, with no pool, block tables, or reference counting. For a real application, the author explicitly recommends using vLLM rather than writing an engine yourself.
Cancellation, backpressure, and metrics
If a client stops reading the stream, a finally block sets a cancellation flag. The worker checks the flag between tokens, so cancellation is cooperative: it cannot interrupt a GPU kernel that is already running. In production, there is one more step: remove the request from future schedules and decrement the reference counts on its cache blocks. This has to happen after EOS (the end-of-sequence token), after hitting the length limit, and after an error.
The output queue in the example is unbounded for simplicity. A real service needs a bounded buffer and a policy for slow clients; otherwise, a client that reads slowly will pile up tokens in the host's RAM. The engine also has to survive tokenizer and model errors, timeouts, and worker crashes, so that requests do not hang forever.
The engine measures time in queue, TTFT (time to first token, from the moment the request enters the engine until the first token), the decode interval, and the number of output tokens. The average time per subsequent token is the interval divided by output_tokens − 1. These timestamps do not separately show tokenization, prefill, or network time. The author advises that in production you tie a single request ID to parsing, admission, execution, streaming, and errors, and track the number of active and waiting requests, prompt and response lengths, and KV cache occupancy. Total GPU memory usage is not the same as cache occupancy: it also includes weights, working buffers, and reserved blocks.
What to do with this
For practitioners, the useful part is the checklist. Before choosing between vLLM, TensorRT-LLM, TGI, SGLang, or llama.cpp, it helps to understand which responsibilities the engine takes on and which remain yours: queue limits, the response to a client when the system is overloaded, the policy for slow clients, and metrics. A quick check with vLLM: running vllm serve facebook/opt-125m with a 512-token length limit and querying the /metrics endpoint will show Prometheus metrics for requests, cache, and latency. In upcoming parts of the series, the author promises to move on to iteration-level scheduling and explicit cache management.
- Jul 5, 2026Pocket: Meta's AI App for Building Mini-Games From Text Prompts
- Nov 26, 2026Weavy AI adds a catalog of ready-made tools and generation in the feed
- Sep 25, 2026SGLang Speeds Up Choosing Among 16 Options on Qwen3-8B: 95% of Responses in 20.6 ms vs 54.1 ms
- Nov 21, 2026llama.cpp Hits Version 1.0.0: Faster on NVIDIA, Intel, and ARM, SSRF Holes Closed
Key Questions Answered
What are the key details on The request path: what the engine is made of?
A request passes through several stages. First, the API parser checks the prompt, the token limit, and the decoding settings before the work reaches the GPU. The tokenizer turns the text into numeric token IDs. Requests that have no room yet wait in a queue. The scheduler decides what goes into the next model iteration, taking into account limits on active sequences, tokens, and space in the KV cache.
What are the key details on The mini engine: what it does and what it doesn't?
The example uses the tiny model sshleifer/tiny-gpt2, along with PyTorch and transformers. The model's output is meaningless, but the whole path is visible. A request is stored in a single object together with its timings. The queue is bounded, with four slots by default: when it is full, put_nowait() rejects the request immediately instead of letting memory grow without control. Blocking PyTorch calls run in a separate thread so the event loop can keep accepting new requests and delivering tokens.
What are the key details on Cancellation, backpressure, and metrics?
If a client stops reading the stream, a finally block sets a cancellation flag. The worker checks the flag between tokens, so cancellation is cooperative: it cannot interrupt a GPU kernel that is already running. In production, there is one more step: remove the request from future schedules and decrement the reference counts on its cache blocks. This has to happen after EOS (the end-of-sequence token), after hitting the length limit, and after an error. The output queue in the example is unbounded for simplicity.
Test Frontier LLMs & Autonomous Agents in One Workspace
Run Claude Opus 5.5, GPT-6, Gemini 3.1, and DeepSeek side-by-side in Nomad AI (nomadnet.ai) — unified model routing, deep research, and multimodal workflows under one subscription.
Daily 60-sec AI Voice Brief + Weekly Production AI Agent Playbook
Listen to a 60-second AI news brief every morning and get a weekly hands-on playbook for shipping AI agents to production — tools, MCP servers and patterns that work. Curated by Jemal Hamidun, Head of AI at Alpina Digital.
