LevelUpWith

Explore / Serving LLMs in Production: Engines, Scale and Cost / Lesson 1

Lesson 1: One Request, Token by Token

You follow a single chat request through tokenisation, the forward pass, sampling and detokenisation to see that an LLM generates one token per step, and that this loop is why serving is harder than an ordinary API call.

Free to read, no account needed. Part of Serving LLMs in Production: Engines, Scale and Cost.

By the end of this level you'll be able to

  • Use a Hugging Face tokenizer and a small open model in Python to step through the generation loop by hand and print each sampled token
  • Explain why the work done per output token is roughly the same at every step, and why output length matters more to cost than input length suggests
  • Count the tokens in a set of real prompts and replies and estimate how many forward passes each request needs

Why one request is not one call

When you call a model API, it looks like any other HTTP request: JSON goes in, JSON comes out. Inside the server it works very differently. A language model does not write a reply in one go. It produces one token per step. Each step runs the whole network once, and the next step can't start until the current one has finished. A 300-token reply takes about 300 trips through the model, one after another.

A good comparison is a typist who must re-read the whole page before each keystroke and can't press two keys at once. Most of this course is about making that typist faster, cheaper and able to share the work. First you need to watch the loop happen, so let's step through it by hand.

The four stages

  1. Tokenise. Text becomes integer IDs from the model's vocabulary. Chat messages are first wrapped in the model's chat template, its special role markers.
  2. Forward pass. The IDs go through every layer. Out comes a vector of logits, one score for every token in the vocabulary, giving a guess at what comes next.
  3. Sample. Turn the scores into probabilities, apply temperature, and pick one token ID.
  4. Detokenise. Turn the ID back into text, stream it to the user, append it to the input and go back to stage 2. Stop when the model emits an end-of-sequence (EOS) token or you hit max_new_tokens.

Walkthrough: the loop by hand

We'll use Qwen/Qwen2.5-0.5B-Instruct. It has about 0.49B parameters, an Apache-2.0 licence and 24 layers, so it runs on any rented GPU and even on a laptop CPU.

pip install -U torch transformers accelerate
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

MODEL = "Qwen/Qwen2.5-0.5B-Instruct"
tok = AutoTokenizer.from_pretrained(MODEL)
# dtype="auto" loads the BF16 weights as stored (older code says torch_dtype, now deprecated)
model = AutoModelForCausalLM.from_pretrained(MODEL, dtype="auto", device_map="auto")
model.eval()

# 1. Tokenise: apply the chat template as a string, then encode it.
#    This two-step form behaves the same across transformers versions.
messages = [{"role": "user", "content": "Name three uses of a GPU."}]
text = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
ids = tok(text, return_tensors="pt").input_ids.to(model.device)
print(ids.shape[1], "prompt tokens")
print(tok.convert_ids_to_tokens(ids[0])[:10])   # see the template markers

eos = model.generation_config.eos_token_id
eos = set(eos if isinstance(eos, list) else [eos])  # Qwen lists two stop IDs

generated = []
with torch.no_grad():
    for step in range(80):                                # cap = max_new_tokens
        # 2. Forward pass over the WHOLE sequence so far
        logits = model(ids, use_cache=False).logits       # [1, seq_len, vocab]
        next_logits = logits[0, -1].float() / 0.7         # last position, temperature 0.7
        # 3. Sample
        probs = torch.softmax(next_logits, dim=-1)
        next_id = torch.multinomial(probs, num_samples=1)
        if next_id.item() in eos:
            print(f"step {step}: EOS, stop")
            break
        generated.append(next_id.item())
        # 4. Detokenise this one token and append it to the input
        print(f"step {step:2d}  {tok.decode(next_id)!r:14}  p={probs[next_id].item():.2f}")
        ids = torch.cat([ids, next_id.view(1, 1)], dim=1)

print(tok.decode(generated))

The output looks like this (yours will differ, because sampling is random):

30 prompt tokens
['<|im_start|>', 'system', 'Ċ', 'You', ...]
step  0  '1'             p=0.71
step  1  '.'             p=0.98
step  2  ' **'           p=0.44
step  3  'G'             p=0.62
...
step 57: EOS, stop

Things to notice:

  • Your one-line question became about 30 tokens. Qwen's template adds a default system prompt and role markers, which you pay for on every request.
  • Tokens are often pieces of words. A leading space belongs to the token (' **').
  • The model never outputs text. It outputs a score for every vocabulary entry, and your code picks one.

Gotcha: decoding one token at a time. A token can hold part of a multi-byte character such as an emoji or a CJK glyph. If you decode each token on its own, you can get �. Streaming servers decode incrementally and hold bytes back until they form a complete character. Decoding the full list at the end, as the last line does, is always correct.

Gotcha: our loop is wasteful on purpose. use_cache=False makes every step re-read the whole growing sequence. model.generate() and every real engine keep a cache so that each step handles only the new token. Level 3 explains that cache. Keep the naive version for now, because it shows the loop plainly.

Why output length dominates

Every step runs every layer and touches every weight. A common rule of thumb is about two floating-point operations per parameter per token. For our 0.5B model that is roughly 1 GFLOP for each new token. For a 70B model it is about 140 GFLOP, and the model has to stream all 70B weights from GPU memory at every step. That fixed cost of moving the weights is why each output token costs about the same, whether it is token 5 or token 500.

Input behaves differently. All 1,000 prompt tokens are already known, so the model can process them together, in parallel, in one pass. Output tokens can't be processed that way. Token 42 depends on token 41, so 300 output tokens mean 300 passes, one after another. Work out the number of passes:

prompt_tokens, output_tokens = 1_000, 300
passes = output_tokens + 1   # first pass reads the prompt and emits token 1; +1 for the EOS step
print(passes)                # 301 sequential forward passes. The 1,000 input tokens added just one.

This is why hosted price lists charge more for output. OpenAI's flagship models currently charge five to six times as much per output token as per input token, for example $2 in and $10 out per million tokens. It is also why "please be concise" is a real cost lever, and why the speed of a reply depends mostly on how many tokens it has.

Exercise: count your own traffic

On one rented GPU or your laptop, take five prompts from something you've built, say a classifier, a RAG answer, a summary and a chat turn. Run each through the model and record the token counts:

def measure(messages, max_new_tokens=512):
    text = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    inp = tok(text, return_tensors="pt").to(model.device)
    out = model.generate(**inp, max_new_tokens=max_new_tokens)
    n_in = inp.input_ids.shape[1]
    n_out = out.shape[1] - n_in
    return n_in, n_out, n_out   # passes is about the number of output tokens

for m in my_prompts:          # your list of message lists
    print(measure(m))

Make a table with the columns prompt tokens, output tokens and forward passes. Compare it with the rule of thumb of about 0.75 English words per token. Then find the request where the input is small but the passes are high. That is the request your future server will struggle with most.

Key takeaways

  • An LLM generates one token per forward pass: tokenise, then run the forward pass, sample and detokenise, repeating until EOS or the token limit.
  • The model outputs scores over the whole vocabulary. Sampling settings such as temperature decide which token is picked.
  • Each output step runs the whole network, so the work per output token is roughly constant.
  • Prompt tokens are processed in parallel, while output tokens are processed one after another. The number of forward passes is about the number of output tokens.
  • Chat templates add hidden tokens. Count what the model actually sees, not what you typed.

A 6-question knowledge check follows this lesson in the app, free and without an account.

More like this