Foundation Models: Tokens, Attention, And Generation · Lesson 10

How AI Generates 1 Token At A Time

Ordinary autoregressive inference processes a known prompt, selects an output token, appends it and computes the next step. Temporary cached attention state can avoid repeated work; streaming and stopping conditions determine how the application receives and checks the result.

Study And Save Progress

Watch The Lesson

7 min 40 sec

Read the video transcript

Suppose the museum assistant begins displaying an answer quickly, but the visitor still waits for the complete explanation. The 1st visible words give us evidence that generation has started. What computation remains, and how will the application know whether the answer finished? Follow the known prompt into processing,

then follow a selected token back into the next input. We will connect that loop to streaming and the reason a response stops. Keep the trained checkpoint fixed for this lesson. The request contains its instructions, approved museum information and conversation

text in the chosen format. Ordinary inference computes with that input and the saved parameters. The parameter-learning signal from the previous lesson belongs to a different operation. For an inspectable trace, we will stipulate classroom sequence units instead of claim a production tokenizer result.

The initial prompt-processing phase is often called prefill. The prompt positions are already known, so their computations can be processed together under the model's causal mask. The last prompt position produces scores for the 1st new token. Earlier positions still have

their own information restrictions. This 1st pass also provides intermediate attention states that a suitable implementation can retain for subsequent steps. Use the supplied prefix The exhibition. Suppose the selection rule chooses opens. Append that selected unit, giving The exhibition opens.

The next computation can now select on. Append it, and the next input is The exhibition opens on. A further selection gives Monday. These are supplied choices for tracing the dependency. The later computation uses the extended input; our trace supplies no hidden,

prewritten complete answer or measured museum response. A key-value cache can avoid recomputing earlier attention keys and values. Each layer retains the relevant states for positions already processed. When the newly selected token enters the next computation, its keys and values join the earlier cache, and that

computation produces scores for the following token. Cached states depend on the earlier prefix, positions and model configuration. Matching only the last visible word is insufficient evidence that 2 requests can share them. A dated serving-system example makes the retained-state mechanism concrete.

Kwon and colleagues' September 2023 paper introduced PagedAttention and the vLLM serving system. It separated processing the known prompt from sequential generation and managed the growing key-value state. We use that historical design to inspect the dependency and memory problem. Its reported throughput results belong to its

tested models and workloads; this lesson supplies no speed measurement for our museum service. Caching removes some repeated computation while using memory for the retained state. It leaves the dependency between ordinary autoregressive steps: a later step needs earlier selected output. A long answer therefore requires

further work after the 1st token. Queueing, request processing, batching and delivery also affect observed delay. Record time to 1st output and time to completion separately before deciding what made a service feel faster. Streaming sends portions of the generated output while the process continues.

A displayed chunk can contain several tokens, and token pieces may need decoding or buffering before they form readable text. The application might display Museum hours followed later by an exception for Saturday. A staff member or automated workflow needs a way to distinguish that partial draft from the complete response.

Collect the required result and check its fields, evidence and exceptions before using it for an action. Generation can stop for different reasons. A model may select a configured end-of-sequence token. A maximum-output setting can stop a response before its sentence

or required fields are complete. An application can also enforce a stopping string, cancellation or another limit. Record the actual stopping condition under the implementation's contract. Even a normal end token leaves the application responsible for checking whether the result satisfies the task.

A useful trace therefore keeps several identities together: the exact checkpoint, tokenizer, formatted prompt, selection settings and output limit. Record the selected sequence, whether caching was used, 1st-output and completion times, and the stopping reason. A cache-sharing decision needs the relevant prefix and configuration to match

under the engine's supported rules. These records help separate a processing problem, a delivery delay and an incomplete result. Our worksheet leaves observation fields blank until an actual authorized run. Pause at the supplied trace. The prefix is The exhibition, and a baseline trace selects opens,

then on, then Monday. What full input is available immediately before the computation that selects Monday? In a separate run with the same supplied 1st choices, the maximum number of new tokens is 2. What output can that run deliver, and what does reaching its

cap tell us about completion? Why can a longer answer require further work after an early 1st token? Immediately before selecting Monday, the input contains The exhibition opens on. In the separate capped run, the 2 new units are opens and on. Reaching that output cap

can leave an unfinished continuation; it supplies no proof that the requested answer is complete. Each remaining selected unit requires its dependent step; that work continues after the 1st output. Inspect the stopping reason and the actual task requirements.

This reasoning follows the stipulated units and choices, rather than a production token-count measurement. Try a rail-service transfer. 2 requests end with the same word, but their earlier text specifies different routes and dates. A colleague proposes reusing the complete key-value cache solely because that final word matches.

What must be checked before accepting that reuse? The service also streams an answer that ends at a length limit. How would you decide whether it is ready to show as a final travel answer? Pause and make a brief plan.

The last word alone cannot establish compatible cached state. Earlier context and positions influence the retained keys and values. Check the relevant exact prefix, model configuration and the engine's supported reuse rules; process the new input when that match is absent.

For the travel answer, inspect the actual stopping reason, required fields and source-supported route and date. A length-limited fragment may need completion or repair before final use. The supplied scenario includes no observed journey or model result. The museum's early visible words now

have a useful interpretation: prompt processing and an initial selection have occurred, while later selections may still be pending. The application follows the growing sequence, temporary cache and stopping condition, then validates the complete task output. You can trace that dependency and diagnose a truncated response.

Next we will inspect the selection rules that choose among candidate tokens, including how temperature and candidate filters change the resulting sequence.

Main Point

Ordinary autoregressive inference processes a known prompt, selects an output token, appends it and computes the next step. Temporary cached attention state can avoid repeated work; streaming and stopping conditions determine how the application receives and checks the result.

Key Points

1. Separate the 1st output from the complete response

The museum’s fictional assistant begins displaying an answer while the explanation is still being generated. An early visible fragment tells the team that output has begun. To diagnose total delay, it also needs the remaining generation work and delivery conditions. No actual latency measurement is supplied.

Keep the checkpoint fixed. The formatted request contains instructions, approved evidence and conversation text. The learned parameters define the computation; the request and its temporary state provide the current conditions. This lesson follows ordinary inference rather than a parameter-training update.

2. Process the prompt, then follow the dependency

Prefill computes the known prompt positions under the causal mask and produces a distribution for the 1st new token. The known positions can be processed together; this does not grant an earlier position access to prohibited future input.

Use the supplied classroom prefix `The exhibition` and the stipulated selected units `opens`, `on`, `Monday`. Actual tokenizers can divide text differently.

SelectionInput available for that predictionSupplied selected token
1The exhibitionopens
2The exhibition openson
3The exhibition opens onMonday

Append each selected token before the next computation. The trace explains a dependency; it is not a recorded production response or evidence of a hidden complete answer prepared before generation.

3. Retain useful intermediate state

A KV cache stores attention keys and values for positions already processed in the relevant layer. At the next step, the newly selected token is processed using retained earlier states; its new keys and values join the cache while the model computes scores for the following token.

The cache holds computed state with a memory cost. It does not replace the saved model parameters or establish a lasting learned update. The same final word following a different prefix can have different cached state. Prefix sharing requires the relevant exact input/configuration and the serving engine’s supported reuse rules; word identity alone is insufficient.

Kwon and colleagues’ September 2023 PagedAttention/vLLM paper makes this an inspectable historical serving design. It distinguishes the prompt and sequential generation phases and addresses management of the changing KV state. Its performance findings belong to its tested configurations. This lesson adopts the state/dependency mechanism without importing a throughput claim into the museum scenario.

4. Interpret responsiveness and streaming

A longer output can require more dependent steps after the 1st token. Caching can remove repeated computations while preserving that dependency. Queueing, batching, processing and delivery also affect the observed delay. Record time to 1st output and time to completion separately.

Streaming delivers portions while generation proceeds. A transport chunk need not equal 1 token: decoding and buffering may combine pieces into readable text. The application should identify partial drafts and interrupted responses. For an automated action, wait for the required result, then validate fields, supporting evidence and exceptions. An early fragment may lack a qualification delivered later.

5. Read the stopping reason

Stopping conditionWhat to inspect
Configured end-of-sequence tokenWhether the ended output satisfies the task
Maximum new-output allowanceWhether the cap cut off a sentence, field or explanation
Configured stop stringThe exact implementation rule and its effect on the returned output
Cancellation or other application limitWhether the result is partial and how recovery is handled

Hugging Face Transformers v4.57.1, released 14 October 2025, provides a pinned implementation example. Its generation configuration documents `max_new_tokens` as an allowance excluding prompt tokens and separately documents end-token and stopping settings. The release date identifies the example; it is not a claim that these are every current service’s defaults. Newer documentation versions were advertised during the current source check, and the actual service’s contract still needs inspection.

6. Keep a useful trace

Record the exact checkpoint, tokenizer, message format, prompt, generation settings and output limit. Add selected output, caching/reuse conditions, first-output/completion times and stopping reason when an actual authorized run provides them. Observation fields remain blank in the worksheet until then.

This record helps distinguish processing, delivery and incomplete-output problems. It also prevents a matching final word from being mistaken for a complete cached-prefix match.

7. Closing

The museum can now follow known prompt → selected token → extended input → later step, then separate a partial stream from the complete task result. Temporary caching and the stop record make that trace more useful. The next lesson examines which selection rules choose among candidate tokens.

8. Learning Checks

Attempt each question before opening the explanation. Use the blank worksheet for your trace and diagnosis.

M14-L10-Q01

Use the supplied prefix “The exhibition”. A baseline trace selects “opens”, then “on”, then “Monday”; treat each displayed unit as 1 classroom token. What input is available immediately before computing the selection of Monday? In a separate run with the same supplied first choices and a maximum of 2 new tokens, what output can appear? What does the cap establish about completion, and why can a longer answer need more time after an early first token?

Your trace and explanation: ____________________

Show explanation after your attempt

The input before the Monday selection is “The exhibition opens on”. The separate 2-new-token run can emit “opens on” under the supplied choices. Reaching that cap can leave an unfinished continuation and does not establish task completion. Remaining ordinary autoregressive selections depend on earlier selected output, so work can continue after a fast first token. Inspect the actual stopping reason and the task’s required result.

M14-L10-P01

2 rail requests end with the same word, but their earlier text names different routes and dates. A colleague proposes reusing the complete KV cache solely because that final word matches. What must be checked before accepting reuse? A streamed answer also stops at a length limit. How would you decide whether it is ready as a final travel answer?

Your trace and explanation: ____________________

Show explanation after your attempt

Matching only the final word does not establish compatible cached keys and values: earlier context, positions and model configuration affect those states. Check the relevant exact prefix/configuration and the engine’s supported reuse rules, and process the new input where that match is absent. For the travel answer, check the stopping reason, required fields and route/date support against the actual source. A length-limited fragment can require completion or repair before final use. No journey or model run is observed in this case.

Sources

Learner Materials

Download Lesson 10 Learner Materials

Use the supplied fictional cases and templates for practice.

Practice

Write your answer, compare it with the model answer and decide what to revisit. These written checkpoints are self-assessed.

Use the supplied prefix “The exhibition”. A baseline trace selects “opens”, then “on”, then “Monday”; treat each displayed unit as 1 classroom token. What input is available immediately before computing the selection of Monday? In a separate run with the same supplied first choices and a maximum of 2 new tokens, what output can appear? What does the cap establish about completion, and why can a longer answer need more time after an early first token? Your trace and explanation: ____________________

Show The Model Answer

The input before the Monday selection is “The exhibition opens on”. The separate 2-new-token run can emit “opens on” under the supplied choices. Reaching that cap can leave an unfinished continuation and does not establish task completion. Remaining ordinary autoregressive selections depend on earlier selected output, so work can continue after a fast first token. Inspect the actual stopping reason and the task’s required result.

Compare your reasoning with the model answer. These written checks are self-assessed.

2 rail requests end with the same word, but their earlier text names different routes and dates. A colleague proposes reusing the complete KV cache solely because that final word matches. What must be checked before accepting reuse? A streamed answer also stops at a length limit. How would you decide whether it is ready as a final travel answer? Your trace and explanation: ____________________

Show The Model Answer

Matching only the final word does not establish compatible cached keys and values: earlier context, positions and model configuration affect those states. Check the relevant exact prefix/configuration and the engine’s supported reuse rules, and process the new input where that match is absent. For the travel answer, check the stopping reason, required fields and route/date support against the actual source. A length-limited fragment can require completion or repair before final use. No journey or model run is observed in this case.

Compare your reasoning with the model answer. These written checks are self-assessed.

Open Practice And Save Your Work