Skip to main content

Building LLM Serving from Scratch: Lessons from Emmy

An engineer's introduction to tokens, GPU execution, KV caches, and serving systems

By Slawomir Strumecki•September 24, 2026
TutorialsLLMGPU
Hero image for Building LLM Serving from Scratch: Lessons from Emmy - Tutorials, LLM, GPU article

LLM serving is the software that makes a large language model available to applications. It receives a request, runs the model, and returns generated text. From the client's side, this can look like an ordinary web API.

This article is for engineers who understand software services but are new to language models. It explains how a server turns input text into model input, generates an answer one piece at a time, and sends that answer to the client. You will learn what tokens and model scores mean, why generation has two phases, and how a cache avoids repeated work. Later sections cover execution on a graphics processing unit (GPU), memory management, and the HTTP server. We won't go into the details in this article. In depth coverage of each of these topics will be covered separately, in follow-up articles.

We will use Emmy, our project for compiling and serving language models, as a practical example. The general concepts come first. Code examples and lessons from the implementation follow.

1. What are we serving?

Text, tokens, and model input

The input text supplied to a model is called a prompt. In a chat application, it can include the conversation history as well as the latest message. The model does not process this text directly as a string. It works with numbers.

A token is a unit of text with a numerical identifier called a token ID. A token can represent a word, part of a word, punctuation, or bytes that form a character. A tokenizer splits text into these units and converts them into token IDs. It also converts output token IDs back into text.

Tokens give the model a way to represent text with a fixed set of identifiers, called its vocabulary. A tokenizer can represent a new word with smaller pieces instead of needing a separate identifier for every possible word. For example, one word might become several tokens, while a common word might use just one. The split depends on the tokenizer.

The model converts each token ID into a list of numbers called a vector. This operation is called an embedding. The model's numerical calculations operate on these vectors.

A vector can be viewed as a point in a space with many dimensions. During training, the model learns token vectors that help it predict text. Tokens used in similar contexts often develop similar vectors. Their positions can reflect relationships in meaning, grammar, and usage. As the model processes a sentence, its layers transform these vectors to include information from the surrounding text.

Weights, configuration, and inference

A trained language model contains weights: numbers learned during training. Its architecture describes the calculation steps, organized into layers, that combine these weights with the input. Together, they form a learned next-token predictor. The server uses this predictor in a loop: calculate scores, select a token, and repeat with the extended sequence (prompt's tokens plus previously generated tokens).

A checkpoint stores the trained weights and the associated configuration. The configuration describes how to construct the model, such as its model type, number of layers, and vector sizes. These settings let the software load the weights into the correct structure.

Serving uses an already-trained model to process requests. This is inference. The weights stay fixed while the server generates an answer. The conversation is input to the model. It does not train the model or update the weights.

Scores and the next token

For the text-generation models discussed here, the model produces a numerical score for every possible next token. Score is a single number called a logit. A higher score gives a token a higher rank as a possible continuation of the text. Scores are not percentages, and a high score does not guarantee that an answer is factually correct.

For example, a prompt can contain this text:

The capital of France is

The model might give the token for “ Paris” the highest score. Greedy selection chooses the token with the highest score. Another method, sampling, converts the scores into probabilities and selects a token randomly according to those probabilities. Thus, the server does not always choose the highest-scoring token. These choices will be explained in a later section.

The selected token joins the sequence, and the model produces scores for the next token. This is the central generation loop: calculate scores, select a token, and use that token to continue. The model generates an answer through repeated steps rather than producing the whole answer in one operation.

Remembering earlier work

Generation needs information from earlier tokens. A key/value cache, or KV cache, stores intermediate results from those tokens in memory. The server can reuse those results instead of recalculating the entire sequence at each step. It stores data used by the model, not a finished answer. Later sections explain what keys and values contain.

KV cache doesn't mean key-value map such as a hash table. Usually it's contiguous buffer(s) or multiple blocks of memory, where we store the keys and values calculated during prefill and each decode step.

2. Request processing

With these terms defined, we can follow a request through the server. The main stages are:

  1. Tokenization: Convert the input text into tokens.
  2. Prefill: Process the input tokens to populate the KV cache and produce scores for the first output token.
  3. Token selection: Choose an output token from those scores, either greedily or by sampling.
  4. Streaming: Convert the selected token into text and send any complete text to the client. Without streaming, collect the output for a single response.
  5. Decode: If generation should continue, process the selected token using the KV cache to produce the next scores, then repeat from step 3.
LLM serving pipeline: tokenization and prefill lead to sampling and streaming, with a decoding loop that reuses the KV cache.
LLM serving pipeline: tokenization and prefill lead to sampling and streaming, with a decoding loop that reuses the KV cache.

Prefill produces the scores for the first output token. Each selected token then feeds the decode loop to produce the next scores. Token IDs in this illustration are examples, not the output of a specific tokenizer.

An API gives clients a consistent interface to this process. Many servers implement a subset of the OpenAI API. Emmy exposes completion and chat-completion endpoints.

Emmy uses Axum for HTTP requests and routing. Its async handlers run on the Tokio runtime, while a dedicated worker thread owns GPU execution.

Endpoint registration is straightforward:

pub fn router(app: App) -> Router {
    Router::new()
        .route("/health", get(health))
        .route("/v1/models", get(models))
        .route("/v1/completions", post(completions))
        .route("/v1/chat/completions", post(chat))
        .fallback(|| async { ApiError(StatusCode::NOT_FOUND, "unknown endpoint".into()) })
        .layer(DefaultBodyLimit::max(MAX_BODY_BYTES))
        .with_state(app)
}

axum::serve(listener, router(app))
     .with_graceful_shutdown(signal)
     .await?;

A chat request adds some preparation before the main processing loop. Messages have roles such as system, user, and assistant. The model expects those messages in a particular format, including special markers.

A chat template (Hugging Face's documentation) turns the structured conversation into the text format the model was trained to consume. Chat models usually come with a predefined chat template that specifies how messages should be formatted. Templates are often written in Jinja, a templating language with loops and conditionals. In Emmy, we use the MiniJinja crate to render them.

In Emmy, chat request preparation includes this call to the checkpoint's template:

Ok(self.templates.get_template("chat")?.render(context! {
    messages => messages, add_generation_prompt => true, enable_thinking => false
})?)

Formatted messages are then encoded into token IDs for the model to process.

// Format messages according to the chat template and encode them into token IDs.
let ids = self.text.encode(&self.text.render(messages)?, true)?;

Using the checkpoint's template keeps formatting consistent with the model instead of inventing a prompt format inside the HTTP handler.

Here, the true parameter explicitly identifies chat input. The wrapper disables automatic special-token insertion because the template already supplies those markers.

The whole process from chat messages to model output looks like this:

Chat messages
     ↓
Apply the model's chat template
     ↓
Convert text into token IDs
     ↓
Process the prompt and build its cache       ← prefill
     ↓
Choose an output token
     ↓
Convert output IDs into text and stream it
     ↓
Stop, or process the selected token         ← decode
and return to token selection

The server also checks the request before starting expensive work. It checks if prompt size and output budget fit within the model's context window. The context window is the sequence length the model and serving configuration can handle. The prompt and continuation share that space. If a server allows 4,096 tokens and reserves 1,000 for the answer, it cannot also accept a 4,000-token prompt without reducing or rejecting something.

Emmy's first native implementation used a 4,096-token capacity and rejected requests whose prompt plus output budget exceeded it. An explicit error is easier to reason about than silently removing part of a conversation.

3. Prefill and decode

Prefill processes the input prompt. Its tokens are already known, so a suitable implementation can process many of them together. This stage contributes to the delay before the first output token appears (therefore time to first token (TTFT)).

Decode generates the continuation. The next input token depends on the previously generated tokens, so generation advances one step at a time for each request. Without a KV cache, every new token generated is added to the sequence which is procesed again in the next step. Using a KV cache avoids recomputing the entire sequence for each new token, significantly improving efficiency. This stage determines how quickly the answer continues to arrive (what is called time per output token (TPOT)).

Consider a request with a 500-token prompt and a 100-token answer. The server first processes the prompt. The scores at the last prompt position let it choose the first output token. It then feeds selected tokens back into the model to obtain the rest of the answer.

We began with a simple design in Emmy: prefill and decode both used a program that processes one token at a time. Prefill walked through the prompt sequentially. This made state handling easier to verify, but left an obvious optimization for later: a dedicated program that processes several prompt tokens together.

Here is the core of Emmy's original non-streaming generation loop:

self.start(prompt, sampling)?;
let mut tokens = Vec::new();
while tokens.len() < max_new_tokens && !self.stopped {
    if let Some(token) = self.advance(capture, false)? {
        tokens.push(token);
    }
}

start initializes the request. Each advance processes one input token. While consuming the earlier prompt positions, it returns no output token. At the final prompt position and during decode, it returns a selected token that the loop collects. The loop ends at the output limit or when the model selects an end-of-sequence token. The two arguments to advance control graph replay and whether to ignore that end marker. Before this loop, the runtime checks that the prompt and output budget fit the context capacity. Afterward, it marks the request as stopped and returns the collected token IDs.

4. KV cache

A transformer uses attention to combine information from the current and earlier positions in the sequence. Each attention layer computes queries, keys, and values. For one attention head, standard scaled dot-product attention is:

Attention⁡(Q,K,V)=softmax⁡(QK⊤dk+M)V\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V

Here, QQ contains the queries, KK the keys, and VV the values. Multiplying QQ by the transposed keys K⊤K^\top scores how strongly each query matches each key. The divisor dk\sqrt{d_k} scales those scores, where dkd_k is the number of components in each query and key vector.

The causal mask MM is zero for allowed positions and −∞-\infty for future positions, preventing a token from attending to later tokens. Softmax converts each row of scores into nonnegative weights that sum to one. Multiplying those weights by VV produces a weighted combination of the value vectors.

Without caching, a simple generation loop could rerun the growing sequence every time it wants another token. The key/value cache, usually called the KV cache, retains those representations instead.

As each new token is processed, the server appends its keys and values. Later steps reuse the stored history. Attention still has to read and use that history. Caching does not make the cost of a longer context disappear.

This creates three important kinds of GPU memory:

MemoryWhat it containsHow it behaves
Model weightsThe trained modelUsually shared across requests
KV cacheAttention state for processed tokensTracks individual request history
Working memoryIntermediate results and temporary storageDepends on the operations and shapes being executed

A model fitting into GPU memory does not mean the server can handle any number of requests. Their caches and working memory need room too. Long prompts and concurrent requests make that distinction especially important.

For example, Qwen3-0.6B FP16, using its rounded parameter count of 600 million, one copy of the weights takes approximately:

Mweights≈600,000,000×2 bytes≈1.12 GiBM_{\text{weights}} \approx 600{,}000{,}000 \times 2\ \text{bytes} \approx 1.12\ \text{GiB}

Its model configuration specifies 28 layers, 8 key/value heads per layer, and 128 values per head. Each cached token needs both a key and a value at every layer:

MKV per token=2×28×8×128×2 bytes=112 KiBM_{\text{KV per token}} = 2 \times 28 \times 8 \times 128 \times 2\ \text{bytes} = 112\ \text{KiB}

The first factor of two counts keys and values. The last counts bytes per FP16 value. Reserving cache space for 4,096 tokens therefore takes 448 MiB per request, including room for both prompt and generated tokens.

AllocationOne request, 4,096-token capacityFour requests, 4,096 tokens each
One shared copy of FP16 weights, approximately1.12 GiB1.12 GiB
FP16 KV cache, without shared prefixes0.4375 GiB1.75 GiB
Weights + cache subtotal, approximately1.56 GiB2.87 GiB

These are storage estimates, not measured Emmy memory use or minimum GPU requirements. Working buffers, runtime allocations, and any duplicated weights need additional space. Their size depends on the implementation and workload, so the complete server's peak memory must be measured. The example shows why adding requests grows cache demand even when they share the same model weights.

The runtime revision used here defaults to contiguous KV storage. The next section explains its optional paged storage and how attention accesses it.

The native server keeps the KV cache in GPU memory across generation steps. With contiguous storage, each attention layer has two persistent buffers: one for keys and one for values. Those buffers hold information computed for earlier tokens, so each new token can reuse it.

Buffers are allocated when the compiled model pack is loaded. Rust passes the cache's GPU addresses to the kernels as arguments. Prefill and decode share the same allocations, so there is no cache transfer between them.

for name in &launch.args {
    // Check for a TMA (Tensor Memory Accelerator) descriptor for this argument.
    if let Some(descriptor) = descriptors.get(&(index, name.clone())) {
        params.push(Param::Ptr(descriptor.ptr));
    } else {
        params.push(Param::Ptr(self.address(name)?));
    }
}

The cache is updated by CUDA kernels compiled from Emmy's Python operation definitions. These kernels read and write the KV cache directly in GPU memory, using the addresses provided by the Rust runtime.

new_keys = store(self.rotate(k, kv_heads, c, s))
new_values = store(v.view(rows, kv_heads, head_dim))
# Each element of the chunk names its own position.
index = positions.view(rows, 1, 1).expand(rows, kv_heads, head_dim)
return rotated, keys.scatter(0, index, new_keys), values.scatter(0, index, new_values)

5. Paged attention

A KV cache avoids repeated computation, but its storage also needs management. Requests have different lengths, and their caches grow as generation continues. Reserving one large buffer for each request can leave unused space.

Paged attention lets attention read a KV cache divided into fixed-size blocks, called pages. The pages do not need adjacent addresses in GPU memory. A page table maps each logical page in the token sequence to its memory location. The PagedAttention paper describes this approach in vLLM.

For example, suppose each page holds 16 tokens. The cache can have this layout:

Logical pageToken positionsGPU storage
00–15Allocation A
116–31Allocation C
232–47Allocation B

The page table preserves the token order even when the allocations have a different physical order. An allocator can add pages as a request grows and reuse them after it ends. This reduces unused reserved capacity. It does not reduce the number of keys and values needed for the same tokens.

How Emmy implements it

Emmy implements this through its compiler's general paged buffer support. The same mechanism can address KV caches and other buffers. It does not require a separate model implementation for paged attention.

The native implementation divides the work into three parts:

  1. Python preparation declares the key and value buffers for each attention layer. Each buffer has shape [context_length, kv_heads, head_dim]. A page size smaller than the context capacity enables paging along the token-position axis. The page size must divide that capacity.
  2. The compiler changes cache reads and writes to use page tables. A kernel receives a table of page addresses instead of one address for the entire buffer. The compiler design describes this conversion.
  3. The Rust runtime allocates the GPU pages and uploads their addresses into page tables. Prefill and decode share the same cache pages through these tables. There is no cache copy between generation steps.

This pseudocode shows the lookup for one key and value element. Each table entry refers to one page:

page = token_position // tokens_per_page
offset = token_position % tokens_per_page

key = key_pages[page][offset, head, component]
value = value_pages[page][offset, head, component]

With 16 tokens per page, token position 37 uses logical page 2 and offset 5. Cache writes use the same mapping. Attention reads the required keys and values across pages. It does not restrict attention to the new token's page. The attention formula and causal mask still apply.

What this implementation provides

The native runtime defaults to contiguous storage. When paging is enabled, current revision allocates all pages for the configured context capacity at model load. It does not allocate KV pages on demand as a request grows. The cache stays in GPU memory, and the native HTTP server accepts one active request.

// this snippet is part of alloc_pages() - called during Executor loading

let count = paging.page_count(buffer, &self.env)?;
let bytes = paging.page_bytes(buffer, &self.env)?;

// allocate the individual pages
let pages = (0..count)
   .map(|_| Region::allocate(bytes, stream))
   .collect::<Result<Vec<_>>>()?;

// build page table
let addresses: Vec<u8> = pages.iter().flat_map(|p| p.ptr.to_le_bytes()).collect();
let table = Region::allocate(addresses.len(), stream)?;

Other steps like attention math, cache writes and page address calculation run in compiled GPU kernels. All preparation for it is done during compilation in Python.

Emmy provides paged addressing, but this native path does not yet provide a shared pool that grows and shrinks for concurrent requests. It also does not share cached prefixes between requests. Those policies are separate from the page-table lookup. Paging alone does not establish a memory saving or a serving speedup for this implementation.

6. Sampling and next token selection

The highest-scoring token is not the only possible choice. Greedy decoding always chooses that token. Sampling converts the scores into probabilities and draws from the resulting distribution.

Two common controls are temperature and top-p:

  • Temperature adjusts how concentrated the probabilities are. Lower positive values favor the strongest choices more heavily. Higher values spread probability more broadly. Serving APIs commonly use zero to select greedy decoding (Emmy does it too).
  • Top-p keeps the most probable tokens whose combined probability reaches a threshold, then samples from that set after renormalizing its probabilities. The Wikipedia article explains top-p sampling in more detail.

Suppose the possible next tokens have these illustrative probabilities:

TokenProbability
Paris0.70
Lyon0.20
London0.06
Other tokens combined0.04

Greedy decoding selects Paris. With top-p set to 0.9, the sampler keeps Paris and Lyon. Paris is still more likely, but Lyon can be selected too. These settings change the selection procedure and they do not guarantee a more factual or useful answer.

In runtime, greedy selection happens in a compiled CUDA kernel. If temperature is nonzero, the runtime copies the logits to the CPU and samples there. The following excerpt shows that selection step, with validation checks omitted for brevity.

let token = if self.sampling.temperature == 0.0 {
    // The program's own greedy pick
    words(&executor.output("token")?)[0]
} else {
    let bytes = executor.output("logits")?;
    let logits: Vec<f32> = bytes
        .as_chunks::<LOGIT_BYTES>()
        .0
        .iter()
        .map(|word| f32::from_le_bytes(*word))
        .collect();
    // The generated-token index: one for the first token after the prompt.
    sample(
        &logits,
        &self.sampling,
        (self.position + 1 - self.prompt.len()) as u64,
    )?
};

The following Rust-style pseudocode separates nucleus selection and the random draw into helpers for clarity. The published implementation performs these operations within sample. Each candidate keeps its original token ID alongside its weight. Its position in the filtered list is not its vocabulary ID.

fn sample(logits: &[f32], sampling: &Sampling, index: u64) -> Result<i64> {
    ensure!(logits.iter().all(|value| value.is_finite()), "nonfinite logit");
    // Keep each candidate's original token ID and its weight.
    let (kept, mass) = nucleus(logits, sampling);
    let target = uniform(sampling.seed, index) * mass;
    let (mut cumulative, mut last) = (0.0, None);
    for (token, weight) in kept {
        last = Some(token as i64);
        cumulative += weight;
        if target < cumulative {
            return Ok(token as i64);
        }
    }
    // Fall back to the last candidate if rounding reaches the final boundary.
    last.context("no token carries weight")
}

A seed initializes the random choices. It helps reproduce an experiment when the model calculation and sampling implementation stay the same. It is not a promise of identical text across different hardware or implementations.

7. Preparing the model and GPU computation

Before requests arrive, something must load the model and prepare the GPU computation. A GPU kernel is a program that performs part of that computation, such as a matrix multiplication or a normalization.

Serving systems may use prebuilt libraries, compile kernels, or combine both approaches. Emmy uses a compiler to turn model operations into CUDA programs. CUDA is NVIDIA's GPU programming platform.

You can find multiple examples of LLM architecture on Sebastian Raschka's web page: LLM Architecture Gallery.

The serving path for these models shares common building blocks:

  • Tokenizer (converts text into token IDs and vice versa)
  • Embedding (converts token IDs into numerical vectors)
  • Output head (produces scores for the next token)
  • Token selection (chooses the next token based on the scores)
  • Generation loop (repeats the process of scoring and selecting tokens until completion)

These models are autoregressive: each new token depends on the preceding tokens. They approximate:

P(xt∣x1,...,xt−1)P (x_t | x_1, ..., x_{t-1})

which means guessing the next token given all the previous tokens in the sequence.

The biggest differences lie in neural network layers and how they process the token representations. Dense models use the same feed-forward network for every token, while mixture-of-experts models route tokens to selected expert networks.

Models can differ in how they use earlier context. Some rely on attention and others combine attention with recurrent processing. These choices can coexist in one model and affect computation, memory usage and model quality. Attention mechanisms also vary to make processing long sequences more efficient.

Our division of responsibilities looks like this:

ComponentResponsibility in Emmy
Python compilerPrepare the model, generate GPU programs, and package their weights and execution plan
Rust runtimeOwn GPU allocations, retain request state, and submit the prepared operations
CUDA kernelsPerform the numerical computation on the GPU
HTTP and text layerAccept requests, tokenize input, stream text, and handle cancellation

The execution plan specifies what to run and in what order. Packaging it with the compiled kernels and weights creates an artifact the runtime can load without running Python model operations during generation.

Loading proceeds in three steps:

  1. Rust deserializes the execution plan into RawPlan and builds a Program describing buffers, kernels, and launch order.
  2. An Artifact groups that program with its weights, compiled binaries, and target GPU architecture.
  3. An Executor allocates device memory, loads the kernels, and submits the planned work on a CUDA stream.

The full plan and artifact definitions and CUDA executor show the implementation details. The important boundary is between preparing the model and executing it: the worker can load a prepared artifact without running the Python compiler.

This separation helped us test each side independently. We could prepare an artifact, then run it in a worker without the Python compiler available. We also expanded the runtime so existing Python workflows could call the same Rust executor instead of maintaining two separate GPU execution implementations.

Rust does not automatically make the model's matrix multiplications faster. Those calculations run in GPU kernels. The host language affects how the system prepares and submits work, manages resources, and handles requests.

8. HTTP requests, streaming, and failures

Emmy native server architecture: Python prepares the model bundle. Rust HTTP tasks admit one request to a dedicated worker that runs GPU generation and returns text through a bounded output channel.
Emmy native server architecture: Python prepares the model bundle. Rust HTTP tasks admit one request to a dedicated worker that runs GPU generation and returns text through a bounded output channel.

The diagram above illustrates the architecture of Emmy's native server. Python prepares the model bundle, while Rust HTTP tasks handle incoming requests by admitting one request to a dedicated worker. The worker runs GPU generation and returns text through a bounded output channel. The native server's architecture is documented in ARCHITECTURE.md.

Owning GPU state also means deciding when work can stop and when another request can safely reuse that state.

What happens when a client disconnects? The server should stop generating an answer nobody will receive. However, disconnecting does not instantly stop a kernel already running. The server must finish or safely retire that work before allowing another request to reuse its memory.

Emmy's Worker uses this small check before submitting another generation step and while waiting to send output. Output here is a bounded channel (tokio::sync::mpsc::channel) that the client (HTTP response handler) reads from.

fn cancelled(job: &Job, shutdown: &AtomicBool) -> bool {
    job.output.is_closed() || shutdown.load(Ordering::Acquire)
}

The first condition detects that the response's receiving side has gone away. The second reads a shutdown flag shared with the server. Either condition tells the worker to stop producing more output. The check does not interrupt GPU work already submitted.

What happens when a client reads slowly? For streaming, a slow client eventually fills the network buffers. A bounded queue applies backpressure: once full, it stops the producer from getting further ahead of the consumer. Emmy's output channel holds eight events.

match job.output.try_send(item) {
    Ok(()) => return true,
    Err(mpsc::error::TrySendError::Closed(_)) => return false,
    Err(mpsc::error::TrySendError::Full(value)) => {
        item = value;
        std::thread::sleep(OUTPUT_POLL);
    }
}

The worker retries every 5 ms (as defined by OUTPUT_POLL) until the output channel can accept the item, the receiver closes, or shutdown is requested.

What happens when too many requests arrive? A server needs an admission policy. Our initial native server accepts one active request and returns a busy response to additional requests. This gives each request exclusive ownership of generation state until its GPU work finishes. Concurrent serving would need scheduling and separate request state.

let permit = match app.admission.clone().try_acquire_owned() {
    Ok(p) => p,
    Err(_) => {
        return ApiError(
            StatusCode::TOO_MANY_REQUESTS,
            "model busy; one active request is supported".into(),
        )
        .into_response();
    }
};

admission is a tokio::sync::Semaphore that controls how many concurrent requests the server will accept.

What happens when GPU execution fails? Returning an error is not always enough. Some failures leave device state unusable. The server must stop reporting itself as ready and recover through an appropriate process restart, rather than continue with uncertain state.

Streaming adds text-specific details too. A token need not end at a complete Unicode character. A stop string can span multiple tokens. The text layer must hold incomplete output until it can decide what is safe to send.

In Emmy, a GPU execution error causes the server to mark itself as not ready and release device state before reporting the error. This ensures that subsequent requests do not proceed with potentially corrupted state.

if let Err(error) = self.request(&job, &shutdown) {
    ready.store(false, Ordering::Release);
    drop(self); // Synchronize/release device state before the job releases admission.
    send(&job, Output::Error(ApiError::unavailable()), &shutdown);
    return;
}

The HTTP server stays running, but health checks and subsequent generation requests return 503. There is no automatic retry or GPU context recreation. The process needs restarting.

9. Lessons from building Emmy

Building Emmy taught us lessons about both numerical correctness and performance. The following examples show how testing and measurement shaped the implementation.

The examples follow that implementation as it evolved. The sequential generation loop describes the initial design. The CPU sampling examples illustrate the behavior in runtime. The September 2026 numerical investigations below tested earlier revisions with GPU sampling, so their results apply to those recorded configurations.

Test the numbers, not just the answer

A plausible sentence is a weak correctness test. A broken implementation can still produce fluent text, and two correct implementations can occasionally choose different words.

Floating-point arithmetic explains part of that tension. Formats such as FP16 and FP32 store numbers with 16 and 32 bits. FP16 saves memory, but intermediate calculations can lose more precision. Small differences matter when two next-token scores are nearly tied. Once a different token is chosen, subsequent text can diverge.

In one Emmy test, two candidate tokens had scores of approximately 20.0812 and 20.0780. Storing those scores in FP16 rounded both to 20.078125. The sampler now saw a tie and selected a different token under its tie-breaking rule. Keeping the output scores in FP32 preserved their ordering and fixed this failure. Increasing precision afterward would not help—the distinction had already been lost. The output-precision investigation records the failure and its fix.

An earlier long-context investigation exposed a separate precision problem. Short tests passed, but rounding errors accumulated through layers and cached history. Keeping selected intermediate calculations in FP32 fixed the observed failures while weights and the KV cache stayed in FP16.

The useful lesson is the testing sequence:

  1. Check individual operations against an independent reference.
  2. Check a small complete model so errors across layers become visible.
  3. Compare next-token scores on the same input sequence, before different selected tokens change the inputs.
  4. Test longer prompts, repeated generation, and requests near the context limit.
  5. Run consecutive requests to verify that state resets correctly.

That earlier investigation's checks covered 17 cases, including two 4,096-position prompts. They passed the numerical criteria we had established for that checkpoint and configuration. This was bounded evidence of implementation correctness, not proof of general model quality. The detailed numerical investigation is available for readers who want to explore the failures and precision choices. Both investigations used GPU sampling in their recorded revisions. They do not validate the later CPU sampler shown in section 5.

Measure the part the user is waiting for

LLM serving has several performance measures because users experience different kinds of delay.

MeasureWhat it tells you
Time to first tokenHow long the user waits before output starts, including queueing and prompt processing
Time per output tokenHow quickly output continues after it starts
ThroughputHow much work the server completes across requests over time
Memory useHow much capacity remains for longer contexts or more simultaneous requests

Improving one measure can hurt another. Combining several requests into a batch can improve GPU utilization and total throughput, while waiting to form that batch can increase individual latency.

Our early measurements also challenged a common assumption: replacing Python with Rust would necessarily make generation much faster. The existing integration already used CUDA graphs, which record a sequence of GPU operations for replay with less CPU submission work.

The runtime experiment compared Python and Rust executing identical small GPU programs. Rust reduced CPU submission overhead, but with CUDA graph replay, GPU execution time was nearly unchanged for the smallest cases. This was a single-operation comparison, not evidence of a full-model serving speedup.

Separately, our serving baseline compared Emmy's compiled execution inside vLLM with stock vLLM. Profiling showed that GPU work dominated the measured execution time, making the compiled GPU programs the main performance limitation in those workloads.

For any optimization, ask what is currently making the user wait. Faster HTTP handling cannot compensate for slow GPU kernels. Faster kernels may have little visible effect when requests spend most of their time in a queue.


The numerical and performance investigations describe work recorded in September 2026. Runtime and HTTP implementation links are pinned to revision 45e539c6ab. Historical examples link to their recorded revisions. For details, see the native generation design, shared runtime design, and experimental HTTP server. These are examples of engineering choices, not a claim of production performance.

Related Articles