Skip to Content
Recodocs

02 · Profile a transformer

Find where an operator waits when the Facilities Helpdesk sends the same F-250 dossier eight times.

9 min read
Part 1
Measure the model
Model
Qwen2.5-1.5B-Instruct
Data
Synthetic facilities helpdesk
Hardware
Tesla T4 and CPU, in Google Colab
Open in 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?

Illustrative factory ventilation fan representing the fictional F-250.

F-250 · Signed-in operator

“What is its maximum temperature?”

manual-F-250-r3
Maximum operating temperature · 101 °C

One dossier

F-250

Repeated dossier

F-250F-250F-250F-250F-250F-250F-250F-250
Read promptFirst tokenGenerate the rest
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.

Synthetic Facilities Helpdesk excerpt. Augapfel’s factory fan photo represents the fictional F-250 and is cropped in the layout · CC BY 2.0.

Change one fact. Keep the operator, question, saved asset and records identical. Change how many times the dossier appears.

What the desk sendsWhat the operator needs
One copy of the authorised dossierAnswer from the current F-250 manual
Eight copies of the same dossierAnswer 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 medianOne dossierRepeated dossier
Input tokens2791,105
Prefill, ms105.9326.1
Decode after first token, ms460.6484.1
Additional tokens per second17.416.5
Source: Lesson 02 verified Colab T4 export.

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) * 1000
Tmodel=Tprefill+Tdecode,T‾extra=TdecodeG−1.\begin{aligned} T_{\mathrm{model}} &= T_{\mathrm{prefill}} + T_{\mathrm{decode}}, \\ \overline{T}_{\mathrm{extra}} &= \frac{T_{\mathrm{decode}}}{G-1}. \end{aligned}

Here 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

2

Prefill through first-token selection

Milliseconds to select the first token

a
128 input tokens59.5 (57.5–501.6)
512 input tokens138.9 (127.8–183.7)
1,024 input tokens280.9 (245.4–295.8)
0510 ms

The following eight tokens

Milliseconds per additional token

b
128 input tokens59.3 (57.9–78.6)
512 input tokens60.3 (53.4–65.1)
1,024 input tokens57.4 (56.9–80.7)
090 ms
Source: Lesson 02 verified Colab T4 export.

DistServe 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 records

In 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.

S=P+G−1,MKV=2LBSHKVDb.\begin{aligned} S &= P + G - 1, \\ M_{\mathrm{KV}} &= 2 L B S H_{\mathrm{KV}} D b. \end{aligned}

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
PositionsKV: formula / measuredAfter prefillAfter decodePeak
1363.7 / 3.73.53.712.1
52014.2 / 14.214.014.248.4
1,03228.2 / 28.228.028.296.0
Source: Lesson 02 verified Colab T4 export. One request, above the loaded-model baseline.

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

4
English32 code points · 6 tokens

What is its maximum temperature?

68.5 ms warmed prefill median

Spanish31 code points · 8 tokens

¿Cuál es su temperatura máxima?

58.8 ms warmed prefill median

Hindi27 code points · 26 tokens

इसका अधिकतम तापमान क्या है?

59.4 ms warmed prefill median

Source: Lesson 02 verified Colab T4 export.

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)
di=si,repeat−si,one,Δ^=1N∑i=1Ndi.\begin{aligned} d_i &= s_{i,\mathrm{repeat}} - s_{i,\mathrm{one}}, \\ \widehat{\Delta} &= \frac{1}{N}\sum_{i=1}^{N} d_i. \end{aligned}

Every response failed the strict output contract

Strict passes by condition and development slice

5
Development sliceOne dossierRepeated dossier
Manual0/40/4
Numeric0/40/4
Multi-source0/40/4
Ambiguity0/40/4
Access boundary0/40/4
Follow-up0/40/4
Total0/240/24

Paired difference 0 percentage points; 95% interval [0, 0] on 12 families. All pairs had the same zero outcome.

Source: Lesson 02 verified Colab T4 export. The interval resamples equipment families.

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

6

Model and tokeniser load 19.52 s

PhaseFirst profileWarm median
Prefill3.680.11
Decode after first token1.000.46
Source: Lesson 02 verified Colab T4 export. First is one observation. Warm is the median across seven repeats.

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 measureOne dossierRepeated dossier
Prompt length279 tokens1,105 tokens
Warm prefill, median105.9 ms326.1 ms
Warm decode after first token, median460.6 ms484.1 ms
Final KV cache7.8 MiB30.4 MiB
Peak extra allocation25.3 MiB102.4 MiB
Strict pass, 24 matched development tickets0/240/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

SettingEvidence
HardwareTesla T4 · CUDA 13.0 · PyTorch 2.14.1+cu130
CheckpointQwen/Qwen2.5-1.5B-Instruct · Transformers 4.51.3 · revision 989aa7980e4cf806f80c7fef2b1adb7bc71aa306
Fixed-length control128, 512 and 1,024 input tokens · batch one · 9 outputs · 7 warm repeats per condition
F-250 profilesComplete authorised dossier once or eight times · same 9 outputs · 7 warm repeats
Quality run24 matched tickets across 12 development families and six slices · variants 0 and 1 · batches of 6 · up to 48 new tokens · greedy
Development registry120 tickets · 12 families · 51dbc208b6b20a620237dd76ce0a2db4f10aa75f4f8fc404121e301b8d79a0cf
Interval1,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.

  1. Add 768 to PROMPT_LENGTHS. Predict the final cache positions and bytes. Compare predicted_final_kv_bytes and measured_kv_tensor_bytes in the length rows.
  2. Change DOSSIER_COPIES from eight to seven. Predict the change in F-250 prefill and strict score. Compare input_tokens, median_prefill_ms and both raw responses.
  3. Raise QUALITY_TOKEN_BUDGET from 48 to 96 without changing the output contract. Check whether replies finish and whether the parser can use them. Look at raw, reason and 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