Skip to content

About

A minimal from scratch clone of vLLM's LLMEngine, built to understand LLM inference.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

13 Commits

Folders and files

Repository files navigation

tiny-serve

A minimal, from-scratch clone of vLLM's LLMEngine orchestration layer, built to understand how an LLM inference engine actually works. It is a learning project that happens to run: you can submit prompts, generate tokens concurrently across multiple requests, abort mid-generation, and fan one prompt out into several completions.

It uses a HuggingFace model (GPT-2 by default) as the backend instead of a real GPU execution engine. The goal is not speed. The goal is to reproduce the shape of a real engine's request lifecycle, one component at a time, so that reading the real vLLM source becomes legible.

Why this exists

vLLM's LLMEngine is the entry point most people interact with, but it is hard to understand in isolation because it delegates almost everything to other files (InputProcessor, OutputProcessor, EngineCoreClient, the scheduler, the attention kernels). Reading it top to bottom tells you what it calls, not why the design is shaped that way.

tiny-serve rebuilds the orchestration skeleton with a dumb backend, so the structure is the only thing left to look at. Once you have written add_request and step yourself, the real file reads as a scaled-up version of the same idea.

What it does

  • Turns a raw prompt into a tokenized request object
  • Generates text one token at a time, driving the model manually instead of calling model.generate()
  • Runs multiple requests concurrently, advancing each by one token per step
  • Streams output token by token as it is produced
  • Aborts a request mid-generation without disturbing the others
  • Fans one prompt out into N completions and reassembles them under the original request id

Architecture

The engine is a coordinator. The four components never talk to each other directly. They all read and write one shared dictionary of active requests, and the Engine moves data between them.

prompt
  |
  v
Engine.add_request()          entry point: tokenize, then store
  |
  v
InputProcessor.process()      prompt -> Request (tokenized)
  |
  v
self.requests: dict[str, Request]      the shared state everything orbits
  |
  v
Engine.step()   (called in a loop)     one forward pass per request -> one token
  |
  v
OutputProcessor.process()     token id -> text delta, checks stop condition
  |
  v
text out (per request)

Components

Request Holds all state for a single request: its id, the tokenized prompt, the KV cache, the tokens generated so far, a done flag, a parent id (for fan-out), and the accumulated text. Everything else in the engine reads and writes this object.

InputProcessor The front door for input. It owns the tokenizer and does one job: take a prompt string and a request id, tokenize the text, and return a ready-to-run Request. Nothing downstream needs to know how tokenization works.

OutputProcessor The mirror image of InputProcessor. It takes the newest token a request produced, decodes just that piece into a text delta, and reports whether the request is done. This is the natural home for stop-string detection, because checking for a stop string needs decoded text rather than raw token ids.

Engine The hub. It owns the model, the two processors, and the dictionary of active requests. It exposes add_request, step, has_unfinished_requests, and abort_request. Every operation reads or writes self.requests.

The two ideas that matter

The KV cache is why generation is incremental

The core of the engine is advance_one_token, which produces exactly one new token for a request. The important detail is these two branches:

if req.past_key_values is None:
    model_input = req.input_ids                     # first step: feed the whole prompt
else:
    model_input = req.generated_ids[-1].view(1, 1)  # after that: feed only the newest token

On the first step the model processes the entire prompt and stores its attention state (the keys and values) in past_key_values. On every step after that, the model already remembers everything it has seen, so it only needs the single newest token. The cache carries the rest.

This is what makes generation practical. Without the cache, generating token 100 would mean reprocessing the previous 99 tokens, and the cost per token would grow with the sequence. With the cache, every step costs the same: one token of work, no matter how long the sequence already is.

This is also the exact thing real vLLM's PagedAttention is built to manage. The KV cache is powerful but it consumes GPU memory, and every concurrent request needs its cache to live somewhere. vLLM's contribution is managing that memory efficiently across many requests. tiny-serve does not do any of that. It just keeps each request's cache as a plain Python attribute.

Everything orbits one dictionary

self.requests: dict[str, Request] is the heart of the design. add_request puts entries in it. step iterates over it and updates each request. has_unfinished_requests checks whether it is empty. abort_request removes an entry from it.

Because state lives in a dictionary keyed by id, concurrency comes almost for free. Running three requests instead of one is just three entries instead of one, and step already loops over all of them. Aborting a request is a single del. This is why the jump from one request to many required no change to the engine at all.

Usage

from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained("gpt2")
tok = AutoTokenizer.from_pretrained("gpt2")

engine = Engine(model, tok)

Single request:

engine.add_request("r1", "The weather today is")

while engine.has_unfinished_requests():
    for out in engine.step():
        print(out["text_delta"], end="")

Multiple concurrent requests:

engine.add_request("r1", "The weather today is")
engine.add_request("r2", "My favorite food is")
engine.add_request("r3", "The best way to learn is")

while engine.has_unfinished_requests():
    for out in engine.step():
        print(f"[{out['request_id']}] {out['text_delta']!r}")

The output interleaves: one token for r1, one for r2, one for r3, then back around. That interleaving is the whole reason step loops over a dictionary.

Abort a request mid-generation:

engine.abort_request("r2")   # r1 and r3 keep going, r2 stops immediately

Fan one prompt out into N completions:

engine.add_request("r1", "The best way to learn is", n=3)

while engine.has_unfinished_requests():
    engine.step()

for parent_id, completions in engine.finished.items():
    print(f"=== {parent_id} ({len(completions)} completions) ===")
    for i, text in enumerate(completions):
        print(f"  [{i}] {text!r}")

With n=3 the engine creates three child requests (r1-0, r1-1, r1-2), each tagged with the parent id r1, generates them concurrently, and groups their results back under r1 when they finish.

What this does NOT do

tiny-serve deliberately stops at the orchestration layer. It does not attempt any of the things that make real vLLM fast:

  • No PagedAttention or custom KV cache memory management. Each request keeps its cache as a plain attribute, with no paging, no block tables, and no eviction.
  • No true batched GPU execution. Requests are advanced in a Python loop, one after another per step, not fused into a single forward pass. This is the biggest performance difference from real vLLM.
  • No scheduler. There is no admission control, no preemption, no priority, and no continuous batching policy. Every request in the dictionary is advanced every step.
  • No multi-process or multi-GPU architecture. Everything runs in one process. There is no separate engine core, no data parallelism, and no distributed coordination.
  • No sampling yet. Decoding is greedy (argmax), so multiple completions of the same prompt come out identical. This is why the n>1 demo produces the same text three times. Adding temperature and top-p sampling is the natural next step and would make fan-out produce genuinely different completions.
  • Naive detokenization. Tokens are decoded one at a time, which can look slightly off for partial word pieces or multi-byte characters. Real engines handle incremental detokenization more carefully.

None of these are oversights. They are the scope boundary. The point was to build the request lifecycle correctly, not to build a production server.

What I took away from building it

The request lifecycle of an inference engine is not complicated once you separate the two things that are easy to conflate: preparing and formatting data (the processors, which never touch the model) versus actually running the model (advance_one_token, inside step). The engine itself is just a coordinator holding a dictionary.

The parts that felt hard turned out to be one idea each. Incremental generation is the KV cache. Concurrency is a dictionary you loop over. Fan-out is N ordinary requests that share a prompt and a parent id. The real vLLM adds enormous sophistication on top, but the skeleton underneath is exactly this.

About

A minimal from scratch clone of vLLM's LLMEngine, built to understand LLM inference.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages