02 · Profile a transformer
Find where an operator waits when the Facilities Helpdesk sends the same F-250 dossier eight times.
- Part 1
- Measure the model
- Model
Qwen2.5-1.5B-Instruct- Data
- Synthetic facilities helpdesk
- Hardware
- Tesla T4 and CPU, in Google Colab
The problem
An operator looking at F-250 asks, “What is its maximum temperature?” The Synthetic Facilities Helpdesk has the prior equipment reference and the authorised records. Its assembler could send the dossier once or append redundant copies. The operator still needs the same answer from the same manual. If the first word now arrives later, where should the desk look?

F-250 · Signed-in operator
“What is its maximum temperature?”
manual-F-250-r3
Maximum operating temperature · 101 °C
One dossier
Repeated dossier
Check which phase must read the copies
The model reads all prompt tokens before producing its first token. Later steps reuse the saved keys and values, but still attend over the longer context. Measure both phases to find out which wait changed most.
Check the recorded one-dossier reply too. It put 101 °C in a sentence in decision and left value null. The desk expected answer as the route and 101 as the value.
Change one fact. Keep the operator, question, saved asset and records identical. Change how many times the dossier appears.
| What the desk sends | What the operator needs |
|---|---|
| One copy of the authorised dossier | Answer from the current F-250 manual |
| Eight copies of the same dossier | Answer from the current F-250 manual |
Predict where the extra cost will show up. Will the first token arrive later, will the rest arrive more slowly, or will both phases change?
Duplicating the F-250 dossier added most of its time before the first token
Complete prompts, batch one and nine generated tokens in both profiles
1| Warm median | One dossier | Repeated dossier |
|---|---|---|
| Input tokens | 279 | 1,105 |
| Prefill, ms | 105.9 | 326.1 |
| Decode after first token, ms | 460.6 | 484.1 |
| Additional tokens per second | 17.4 | 16.5 |
How the work splits
Reading the question and generating the answer are different phases. Prefill processes the input; decode uses the resulting attention state to generate the next tokens. Inference infrastructure explains why that distinction matters for memory and latency.
The first forward pass reads the whole prompt, stores the attention keys and values, then selects the first output token. This is prefill. Decode feeds that output back in and uses the saved keys and values to produce the next token. The model repeats this step for the remaining output tokens.
The notebook synchronises the GPU before starting the prefill timer and after first-token selection. It then times the cached loop and synchronises again. The abbreviated excerpt keeps those boundaries visible. The forward calls also receive the correct attention mask.
sync()
started = perf_counter()
# The first forward reads the prompt and produces its cache.
output = text_model.model(input_ids=input_ids, use_cache=True)
cache = output.past_key_values
next_id = text_model.lm_head(output.last_hidden_state[:, -1:]).argmax(dim=-1)
sync()
prefill_ms = (perf_counter() - started) * 1000
started = perf_counter()
for step in range(1, GENERATED_TOKENS):
# Feed one previous output through the cached model.
output = text_model.model(input_ids=next_id, past_key_values=cache, use_cache=True)
cache = output.past_key_values
next_id = text_model.lm_head(output.last_hidden_state[:, -1:]).argmax(dim=-1)
sync()
decode_ms = (perf_counter() - started) * 1000Here G is the number of emitted tokens. Prefill already selected one, so divide decode time by the other G − 1. These timers include Python dispatch and GPU work, and exclude tokenisation, queuing and network time. The controlled sweep repeats and truncates F-250 token IDs to the exact input lengths for Figure 2. Those inputs measure performance. The separate quality check uses complete prompts.
The first token waited longer as the prompt grew
Warm median and observed range across seven repetitions at each input length
2Prefill through first-token selection
Milliseconds to select the first token
aThe following eight tokens
Milliseconds per additional token
bDistServe evaluates service capacity against two latency targets together, time to first token and time per output token. Huawei’s P/D-Serve also times prefill queuing and cache transfer, both outside these forward timers. The operator’s wait in a deployed desk needs those boundaries measured separately. Zhong et al., DistServe · Huawei, P/D-Serve
Add one thing to the F-250 prompt
The dossier brings the current manual, inventory and supporting-system record into the prompt. The code obtains the records from the same authority check in both conditions. It adds copies only when that check returns a dossier. The benchmark still expects answer, a value of 101, and the evidence ID manual-F-250-r3.
def records_for(case, condition):
records = safe_context(case)
if condition == "repeated_dossier" and records:
# Copy the same authorised text without adding any new evidence.
return "\n\n".join([records] * DOSSIER_COPIES)
return recordsIn Figure 1, warm median prefill increased by 220.2 ms. The median time for the eight later tokens increased by 23.5 ms, and the observed decode ranges overlap. These are subtractions of the phase medians. For this ticket, start by looking for repeated input when the first token is late.
OpenAI’s prompt-caching launch describes a different intervention. Matching prefixes can be reused across eligible requests, with cached input reported separately in token usage. Each profile in this lab builds a fresh cache. Repeating text inside that request adds positions to it. OpenAI, Prompt Caching in the API
Count the cache
Returning to F-250, every additional input token leaves a cache position in each layer. Count a key and a value per position. Grouped-query attention uses the model’s KV head count in this formula. The final generated token has been emitted, but has never been sent back through the model.
P is prompt length, S is the number of cached positions, L is layers, B is batch rows, H is the KV head count, D is head width, and b is bytes per element. The T4 run recorded 28 layers, two KV heads, a head width of 128 and two bytes per element. At batch one, this gives 28,672 KV bytes per position. The notebook counted live tensors and checked exact equality.
# Sum keys and values in each cached layer.
tensor_kv = sum(
tensor.numel() * tensor.element_size()
for layer in cache.to_legacy_cache()
for tensor in layer
)
assert tensor_kv == kv_bytes(final_positions, **cache_shape)The measured cache matched the formula as peak allocation climbed faster
Cache and extra PyTorch allocation by final cached positions · MiB
3| Positions | KV: formula / measured | After prefill | After decode | Peak |
|---|---|---|---|---|
| 136 | 3.7 / 3.7 | 3.5 | 3.7 | 12.1 |
| 520 | 14.2 / 14.2 | 14.0 | 14.2 | 48.4 |
| 1,032 | 28.2 / 28.2 | 28.0 | 28.2 | 96.0 |
For the repeated F-250 dossier, the final KV cache used 30.4 MiB and peak extra allocation reached 102.4 MiB. Peak allocation includes temporary work and is measured above the loaded-model baseline. It is a PyTorch allocation measure, distinct from GPU reserved memory. vLLM’s PagedAttention paper evaluates how memory management affects capacity across concurrent requests. A single cache byte count can explain the footprint of one request. A serving workload is needed to test scheduling and capacity. Kwon et al., PagedAttention
Tokenise the same question
Suppose the operator sends the same question in another language. Count tokens for the literal question before budgeting the request. The three prompts below exclude chat framing and dossier text.
The shortest written question took the most tokens
One F-250 request in three languages · literal text without chat framing
4What is its maximum temperature?
68.5 ms warmed prefill median
¿Cuál es su temperatura máxima?
58.8 ms warmed prefill median
इसका अधिकतम तापमान क्या है?
59.4 ms warmed prefill median
The Hindi sentence has fewer Unicode code points than the English and Spanish sentences, and occupies more tokens under this checkpoint’s tokeniser. The warmed prefill ranges for these short strings overlap. Ahia and colleagues show that cross-language token differences depend on the tokeniser and data sample. A larger, language-balanced sample is needed to make a claim about the desk’s traffic. Ahia et al., Do All Languages Cost the Same?
Check the answer before choosing a prompt
The performance profile generates a fixed nine tokens. The quality comparison separately gives the model up to 48 new tokens and asks for a complete JSON object with the correct route, exact value and evidence IDs. The grader keeps every ticket, including outputs that do not parse.
# Parse the response before checking the business contract.
output = decode_answer(raw)
passed = score_answer(case, output)
# Resample paired ticket outcomes by equipment family.
interval = paired_interval(quality_cases, repeated, original)Every response failed the strict output contract
Strict passes by condition and development slice
5| Development slice | One dossier | Repeated dossier |
|---|---|---|
| Manual | 0/4 | 0/4 |
| Numeric | 0/4 | 0/4 |
| Multi-source | 0/4 | 0/4 |
| Ambiguity | 0/4 | 0/4 |
| Access boundary | 0/4 | 0/4 |
| Follow-up | 0/4 | 0/4 |
| Total | 0/24 | 0/24 |
Paired difference 0 percentage points; 95% interval [0, 0] on 12 families. All pairs had the same zero outcome.
Both conditions scored 0/24. All 48 raw outputs began with a Markdown fence and failed the parse check. Removing the wrappers in an offline readback recovered 16 JSON objects. Each recovered object still had a decision that differed from its expected label. The other 32 ended mid-object and re-encode to exactly 48 tokens with the pinned tokenizer. That matches the generation cap. The notebook saved decoded text without stop reasons, so the token count is a readback from that text. The paired interval collapses to zero because every pair failed, leaving no evidence about whether duplication would change quality if the format worked. On F-250 both replies contain the temperature, but both put a sentence in the decision field, leave the value null, start with a Markdown fence and end before the JSON closes.
F250-00 · What is its maximum temperature? · operator · saved F-250
- Expected
- {"decision":"answer","value":"101","evidence":["manual-F-250-r3"]}
- One dossier · 279 tokens
- ```json { "decision": "The maximum temperature of F-250 is 101°C.", "value": null, "evidence": [ "inventory-F-250-r3",
- Repeated dossier · 1105 tokens
- ```json { "decision": "The maximum temperature of the F-250 equipment is 101°C.", "value": null, "evidence": [ "manual-F-250-r
The response text above ends exactly where generation stopped. The parser returned an empty object in both cases.
F240-00 · As a guest, show the inventory record for P-240. · guest
- Expected
- {"decision":"deny","value":"","evidence":[]}
- Raw reply
- ```json { "decision": "Deny", "value": "", "evidence": [] } ```
Both prompts contain no dossier for the guest. The fenced reply is a parse failure even though the visible word “Deny” suggests the intended route.
Separate start-up and service cost
The first profiled F-250 request used the same single dossier as the warm condition. After model loading, prefill took 3.68 seconds on that first observation and 105.9 ms at the warm median. Reserve a separate cold-request measurement if the desk has to meet a first-token target after idle scale-down.
The first F-250 profile was slower even after loading the model
Identical 279-token input and nine outputs · phase wall time in seconds
6Model and tokeniser load 19.52 s
| Phase | First profile | Warm median |
|---|---|---|
| Prefill | 3.68 | 0.11 |
| Decode after first token | 1.00 | 0.46 |
The notebook records wall time and allocation. Anthropic’s API documentation, for example, separates prompt cache creation and read tokens in billing. A hosted price needs the tariff and usage split alongside any latency profile. Anthropic, Prompt caching
What to keep
| F-250 measure | One dossier | Repeated dossier |
|---|---|---|
| Prompt length | 279 tokens | 1,105 tokens |
| Warm prefill, median | 105.9 ms | 326.1 ms |
| Warm decode after first token, median | 460.6 ms | 484.1 ms |
| Final KV cache | 7.8 MiB | 30.4 MiB |
| Peak extra allocation | 25.3 MiB | 102.4 MiB |
| Strict pass, 24 matched development tickets | 0/24 | 0/24 |
- Remove redundant dossier text ahead of prefill. Keep the authority check and the evidence required for F-250.
- Track first-token and subsequent-token latency separately. Carry a separate observation for the first request after loading.
- Budget for the live cache and extra working allocation.
- Repair the output contract, then repeat the same quality comparison before concluding that slimmer prompts preserve useful answers.
Next to try, not tested here. Repeat the timing with concurrent requests. Expand the translated prompt sample before estimating traffic-level token costs.
How it was built
| Setting | Evidence |
|---|---|
| Hardware | Tesla T4 · CUDA 13.0 · PyTorch 2.14.1+cu130 |
| Checkpoint | Qwen/Qwen2.5-1.5B-Instruct · Transformers 4.51.3 · revision 989aa7980e4cf806f80c7fef2b1adb7bc71aa306 |
| Fixed-length control | 128, 512 and 1,024 input tokens · batch one · 9 outputs · 7 warm repeats per condition |
| F-250 profiles | Complete authorised dossier once or eight times · same 9 outputs · 7 warm repeats |
| Quality run | 24 matched tickets across 12 development families and six slices · variants 0 and 1 · batches of 6 · up to 48 new tokens · greedy |
| Development registry | 120 tickets · 12 families · 51dbc208b6b20a620237dd76ce0a2db4f10aa75f4f8fc404121e301b8d79a0cf |
| Interval | 1,500 paired bootstrap draws over equipment families, 95% interval, seed 401 · Figure 2 shows the observed warm minimum and maximum |
Time and cost. The verified queue recorded 119.8 seconds from launch to completion. The notebook measured 95.1 seconds for the lab body after bootstrap, including 19.52 seconds for model and tokeniser load. The export contains no billing receipt.
Executed notebook · Summary · Raw rows and prompts · Runtime · Queue receipt
Run it yourself
Start with the downloaded executed notebook. The timing cells need a T4. Open Derive the persistent cache budget for the byte calculation, Profile the waiting time for the matched timings and Check strict answers separately for the saved raw replies. Form a prediction before running each change.
- Add
768toPROMPT_LENGTHS. Predict the final cache positions and bytes. Comparepredicted_final_kv_bytesandmeasured_kv_tensor_bytesin the length rows. - Change
DOSSIER_COPIESfrom eight to seven. Predict the change in F-250 prefill and strict score. Compareinput_tokens,median_prefill_msand both raw responses. - Raise
QUALITY_TOKEN_BUDGETfrom 48 to 96 without changing the output contract. Check whether replies finish and whether the parser can use them. Look atraw,reasonand strict passes before drawing a conclusion.
Lesson 03 keeps the same helpdesk and asks whether more computation at answer time buys a better decision.
How is this page?
Last updated on