Opening

In this post

  1. 1. The expensive way to generate text
  2. 2. Attention, as far as the cost needs it
  3. 3. The KV cache, and what it costs in memory
  4. 4. Prefill and decode, measured
  5. 5. Why an edit near the start is so expensive
  6. 6. What changes with many users
  7. 7. What to do with this
  8. Sources

Article

AI engineering · Fundamentals

Before the First Token: What an LLM Does With Your Prompt

Send a prompt again with a new last line and the model reads it in 0.3 seconds instead of 19. Change the start and the gain is gone. The machinery behind that, with the math, the code and measurements you can repeat.

Author
Lovenish Singh Panwar
Published
Reading time
12 min read
Start reading

I sent a prompt of about 1,000 tokens to a small model on my laptop. Reading it took 18.89 seconds. I sent the same prompt again with a different last line, and that took 0.29 seconds. Then I changed one number in the first few tokens, and it took 18.81 seconds. Those are medians across repeated runs, and how I took them is in section 4.

Nothing about the model changed between those runs. What changed is how much work the server could skip. One LLM request is really two workloads, prefill and decode, with a growing cache between them. Most of what you see in latency and in prompt caching rules follows from those three things.

These are one small model’s numbers on one laptop CPU, as of November 2026. Your numbers will differ. The shapes are the point, and the full script is at the end so you can check them.

1. The expensive way to generate text

A language model does one thing: given a sequence of tokens, it produces a probability for every possible next token. To generate text, you pick a token, append it, and run the model again.

Done naively, each run processes the whole sequence again from the start. The thousandth token repeats the work of the first 999, and since attention compares tokens with the ones before them, one step’s attention costs about n² for n tokens. With a cache, a step handles one new token and reads n stored entries, which one recent study describes as going “from quadratic to linear”. Each step still costs more as n grows, which matters in section 4. To see why that cache can exist at all, you need one formula.

2. Attention, as far as the cost needs it

Attention is the operation that lets a token use the tokens around it. The original Transformer paper describes it this way: “An attention function can be described as mapping a query and a set of key-value pairs to an output.” Each token gets three vectors. Its query asks what it is looking for, its key says what it offers, and its value is what it passes on:

Attention(Q, K, V) = softmax(Q Kᵀ / √d_k) V

In a language model a token may look only at positions before it. The paper’s wording is that a prediction “can depend only on the known outputs at positions less than” its own. So when a new token arrives, the keys and values of the earlier tokens do not change. They can be stored, and only the new token needs computing. This sketch shows one attention head with the rest of the model left out:

def attend(q, k, v):
    return softmax(q @ k.T / sqrt(k.shape[-1])) @ v

# Without a cache: compute keys and values for all tokens, at every step.
out = attend(query(x[-1:]), key(x), value(x))

# With a cache: compute them for the new token only, and append.
past_k = concat([past_k, key(x[-1:])])
past_v = concat([past_v, value(x[-1:])])
out = attend(query(x[-1:]), past_k, past_v)

The two branches give the same answer. I checked the cached version against the full masked computation on random data, and they match.

3. The KV cache, and what it costs in memory

That store of keys and values is the KV cache. Its size follows directly from the model’s config, and every layer holds its own copy:

bytes = 2 × layers × KV heads × head dimension × bytes per value × tokens

The 2 is one key and one value. For the model I measured, that is 112 KB per token, assuming 16-bit values, or 896 MB at 8,192 tokens. PagedAttention, the paper behind the vLLM server, works the same sum for the 13B OPT model: 800 KB per token and up to 1.6 GB for one 2,048-token request.

The cache grows with every token, and an edit discards what follows it

2 × 28 layers × 8 heads × 128 × 2 bytes = 112 KB per token

224 MB for this one request

Edit after 512 tokens. Those 56 MB can be kept. The other 1,536 tokens are recomputed.

Config source: the model file I measured, read with ollama show

KV cache size for each model
ModelThe sum256 tokens8,192 tokensConfig source
Llama 3.2, 3B2 × 28 layers × 8 heads × 128 × 2 bytes = 112 KB per token28 MB896 MBthe model file I measured, read with ollama show
OPT 6.7B2 × 32 layers × 32 heads × 128 × 2 bytes = 512 KB per token128 MB4.0 GBthe facebook/opt-6.7b config
OPT 13B2 × 40 layers × 40 heads × 128 × 2 bytes = 800 KB per token200 MB6.3 GBthe facebook/opt-13b config

An edit keeps the tokens before it. It and every token after it are recomputed.

Sizes come from each model's published config and use 1,024-byte KB, MB and GB. They cover the KV cache only, for one request, assuming 16-bit values. The edit is the rule from section 5: this figure shows token counts, not timings.

This is why serving is often limited by memory and not only by compute. The cache “grows and shrinks dynamically”, every request in a batch needs its own, and in the systems PagedAttention measured, “only 20.4% - 38.2% of the KV cache memory is used to store the actual token states”. The rest was lost to fragmentation, which meant fewer requests fit in a batch.

4. Prefill and decode, measured

The cache also splits a request into two phases that behave very differently. Sarathi-Serve, a paper on serving LLMs on GPUs, puts it precisely: “The prefill phase is compute-bound because it processes all tokens of an input prompt in parallel”, and “the decode phase is memory-bound because it processes only one token per-request at a time.”

Prefill Decode
What it does Reads the whole prompt and fills the cache Makes one token, reads the cache, adds one entry
Tokens per step Many, in parallel One per request
Limited by (on GPUs, per Sarathi-Serve) Compute Memory
What you see Time to first token Time per output token

One request, from text to the last token

  1. Step 1

    Tokenise

    Server

    The text becomes token IDs. The new request's cache is empty.

  2. Step 2

    Look for a stored prefix

    Server

    If the server still holds the state for the start of this prompt, it can reuse it and skip those tokens.

  3. Step 3

    Prefill the rest

    ModelPrefillOn GPUs, limited by: compute

    The remaining prompt tokens run through the model. The cache now holds keys and values for the whole prompt.

  4. Step 4

    Pick the first token

    ModelPrefillOn GPUs, limited by: compute

    The output at the last position gives the next-token probabilities. Time to first token ends here.

  5. Step 5

    Decode, one token at a time

    ModelDecodeOn GPUs, limited by: memory

    The new token computes its own keys and values, reads every entry in the cache, and appends. Repeat until the model stops.

A simplified path through one local server. Time to first token is any wait in a queue, plus steps 1 to 4. Hosted services add their own steps. The limits are Sarathi-Serve's findings on GPUs, not something I measured.

I measured both phases at growing context, using Llama 3.2 (3B, quantized) on a laptop CPU. Both get slower per token as context grows. Prefill goes from 14.57 ms per token over the first 280 or so tokens to 26.79 ms for the burst ending at about 4,440, or 1.84 times. Decode goes from 93.10 ms to 227.25 ms over the same range, or 2.44 times. Generating a token took about 6 times as long as reading one at short context and about 8.5 times at the deep end.

In my test, every extra token of context made the next token slower

DecodePrefill

Milliseconds per token

Tokens in context, about

Tokens in context, about 4,442: Decode 227.25 ms, Prefill 26.79 ms.

Median and range across repeats at each point, in ms
Tokens in context, aboutDecode (ms)Prefill (ms)Decode rangePrefill range
28293.1014.5792.41 to 94.1214.34 to 14.83
54498.5916.6489.56 to 98.8616.41 to 17.16
827106.3817.16105.08 to 107.8117.03 to 17.50
1,096114.3518.36113.97 to 114.4718.03 to 18.89
1,374122.2918.80122.04 to 123.4618.52 to 19.13
1,645129.8919.85129.55 to 132.0719.30 to 19.95
1,916137.1720.02136.15 to 142.8319.96 to 20.88
2,183144.0321.18142.28 to 150.0220.53 to 21.49
2,564155.7922.24150.33 to 162.9921.78 to 23.06
2,867160.9322.62147.17 to 162.8921.67 to 23.20
3,165171.8223.32167.90 to 176.1422.68 to 23.95
3,466182.9424.41177.70 to 193.3123.88 to 25.48
3,717194.2724.92187.56 to 198.6723.55 to 25.39
3,954200.2625.65192.13 to 207.3424.30 to 26.10
4,204216.5225.88210.06 to 236.1624.81 to 27.15
4,442227.2526.79211.07 to 244.3225.53 to 29.13
Llama 3.2 3B (Q4_K_M) through Ollama 0.34.4, on an Intel i9-9880H CPU with 4 threads, measured 2 November 2026. Lines are medians of 5 repeats and bands are their range. A prefill point times the burst of about 250 tokens ending at that depth, not a full prompt from cold. A decode point averages up to 32 tokens generated from that depth. CPU only, so it says nothing about GPUs.

If each token costs more than the one before, total time grows faster than prompt length. In my test, long context was not just more tokens at a fixed cost. Hosted systems may differ, and what you pay on an API is set by its price list, not by this curve.

I can’t tell you why from this data. The obvious suspect is attention, whose cost “grows quadratically with sequence length”. But the same Sarathi-Serve paper found that “linear operators still contribute more than 80% to the total time even at high sequence lengths”, on its GPU setups. Decode’s rise fits its statement that “attention cost depends on the accumulated context length”, but I did not isolate the cause in my test, and memory effects may contribute too.

5. Why an edit near the start is so expensive

Now the opening numbers make sense. Each token’s stored state was computed by looking at everything before it. Keep the start of a prompt identical and all of that state is still correct. Change an early token, and everything after it was computed from something that is no longer there. That is why a changed last line cost 0.29 seconds and a changed number at the start cost 18.81.

Hosted APIs state the same rule, though not this reason, which is my explanation. Anthropic’s docs say “Cache hits require 100 percent identical prompt segments”, and OpenAI’s say “Cache reuse requires the entire rendered prefix to match”. Both also charge for it separately. As of November 2026, Anthropic charges 1.25 times the base input price to write to its default 5-minute cache and 0.1 times to read, with lower read rates on some models. OpenAI discounts cached input by “up to 95%” and, on GPT-5.6 and later, charges 1.25 times to write.

Don’t assume more than that about what happens on their servers. OpenAI’s docs warn that the cache lifetime “does not guarantee that every request reuses stored KV tensors or has lower latency”. A cache hit is a billing fact first.

The practical rule is short: put what stays the same first and what changes last. A timestamp or a request ID at the top of a system prompt can lose you the whole cache, on every call.

6. What changes with many users

On a shared server these two phases collide. Older systems batched whole requests, so “requests that have finished earlier than other requests in a batch cannot return to the client”, and new arrivals had to wait for the batch to finish. Orca fixed that in 2022 by scheduling one model iteration at a time, so requests can join and leave between steps.

That creates a new problem. If a long prefill runs between decode steps, everyone already generating has to wait for it. Sarathi-Serve reports that such a stall in vLLM “can last over several seconds”. Its fix is to split a prefill into chunks and run them alongside the ongoing decodes, and it reports “almost negligible overhead” with a token budget of 2048.

If this sounds familiar, it is the trade-off from Scalable Is Not Fast: throughput and latency meet in a queue. Prefill and decode are what is in that queue, and a long prompt is the large job that holds up the small ones.

7. What to do with this

If you call an API:

  • Order prompts for cache hits: tools and system text first, changing content last.
  • Track time to first token and time per output token separately. They have different causes.
  • Measure what long context does on your provider. On my laptop it cost more per token in both phases, and hosted systems may differ.

If you serve models:

  • Estimate KV cache memory from the config before you choose a batch size.
  • Measure prefill and decode separately, and watch what long prefills do to decode latency.

To run it yourself, here is the script as one file. It needs Ollama, ollama pull llama3.2, and any long English text file. It takes a while, because it waits for the CPU to cool before every call. The thermal checks rely on a macOS reading I have only tested on an Intel Mac. Where that reading is missing they switch off, so watch for throttling yourself and expect more noise.

"""Time prefill and decode at growing context depth, in short bursts, through a local Ollama server.

Usage: python3 measure_kv.py some-long-english-text.txt
Needs: Ollama running, and `ollama pull llama3.2`. Standard library only.
"""
import json
import random
import re
import statistics
import subprocess
import sys
import threading
import time
import urllib.request

MODEL = "llama3.2"
URL = "http://127.0.0.1:11434/api/generate"
OPTIONS = {"num_predict": 32, "temperature": 0, "seed": 1, "num_ctx": 8192, "num_thread": 4}
REPEATS, STEPS, WORDS_PER_STEP = 5, 16, 192  # each step adds about 250 tokens
COOL_LIMIT, MIN_LIMIT = 90, 40  # start a call at this CPU speed limit; drop it if it falls below this


def speed_limit():
    """The CPU speed limit on macOS, from 0 to 100. None elsewhere, which turns the thermal checks off."""
    try:
        out = subprocess.run(["pmset", "-g", "therm"], capture_output=True, text=True).stdout
    except OSError:
        return None
    found = re.search(r"CPU_Speed_Limit\s*=\s*(\d+)", out)
    return int(found.group(1)) if found else None


def generate(prompt):
    started = time.time()
    while (limit := speed_limit()) is not None and limit < COOL_LIMIT and time.time() - started < 300:
        time.sleep(5)

    samples, done = [limit] if limit is not None else [], threading.Event()

    def sample():
        while not done.wait(5):
            if (value := speed_limit()) is not None:
                samples.append(value)

    threading.Thread(target=sample, daemon=True).start()
    body = {"model": MODEL, "prompt": prompt, "stream": False, "keep_alive": "30m", "options": OPTIONS}
    request = urllib.request.Request(URL, json.dumps(body).encode(), {"Content-Type": "application/json"})
    with urllib.request.urlopen(request, timeout=1800) as response:
        reply = json.load(response)
    done.set()
    return {
        "tokens": reply["prompt_eval_count"],
        "prefill_s": reply["prompt_eval_duration"] / 1e9,
        "decode_ms": reply["eval_duration"] / 1e6 / max(reply["eval_count"], 1),
        "cool": not samples or min(samples) >= MIN_LIMIT,
    }


def main(path):
    corpus = open(path).read().split()
    rng = random.Random()
    session = int(time.time())  # a server can keep old prompts, so never send the same text in two runs
    excerpt = lambda n: [corpus[(start + i) % len(corpus)] for start in [rng.randrange(len(corpus))] for i in range(n)]
    generate("warm up")

    # Grow one prompt. The server keeps the prefix, so each call evaluates only the new step.
    results = {}
    for repeat in range(REPEATS):
        text, previous = excerpt(WORDS_PER_STEP * STEPS), 0
        for step in range(1, STEPS + 1):
            run = generate(f"Run {session}-{1000 + repeat}. " + " ".join(text[: WORDS_PER_STEP * step]))
            new_tokens, previous = run["tokens"] - previous, run["tokens"]
            if run["cool"]:
                results.setdefault(step, []).append((run["tokens"], 1000 * run["prefill_s"] / new_tokens, run["decode_ms"]))

    print("depth  prefill ms/token  decode ms/token  runs kept")
    for step, rows in sorted(results.items()):
        depth, prefill, decode = (statistics.median(column) for column in zip(*rows))
        print(f"{depth:5.0f}  {prefill:16.2f}  {decode:15.2f}  {len(rows):9d}")

    # The same prefix three times: first send, a changed last line, a change near the start.
    print("\n     first s     repeat s early edit s")
    for repeat in range(REPEATS):
        base = " ".join(excerpt(770))  # about 1,000 tokens
        first = generate(f"Run {session}-{2000 + repeat}. {base}\nName one topic above.")
        again = generate(f"Run {session}-{2000 + repeat}. {base}\nName one person above.")
        edited = generate(f"Run {session}-{3000 + repeat}. {base}\nName one topic above.")
        print(" ".join(f"{run['prefill_s']:12.2f}" if run["cool"] else f"{'hot':>12}" for run in (first, again, edited)))


if __name__ == "__main__":
    main(sys.argv[1])

This single file combines the two scripts behind the numbers above, using the same settings. My published numbers came from the two-file version.

Sources

Related posts

Get an email when a new post is out

Used only to email you when a new post is out. Held by Kit. Unsubscribe anytime. Privacy

All posts

↑ ↓ moveEnter openEsc closeTap a result to open it