# How Does the Final Hidden State Become the Next Token?

> How a transformer turns its last hidden state into scores, chances and one chosen token, explained simply for your AI interview.

**In short:** The last hidden state is a vector for the newest position. A linear layer turns it into one score per possible next token, softmax turns those scores into chances, and the model picks one token, adds it to the text and repeats.

AI and LLM interview question Q068, Transformer architecture. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/how-does-the-final-hidden-state-become-the-next-token

## Say it in 30 seconds

At the end of a transformer, each position gets a vector called the hidden state. A linear layer turns that vector into one score for every token in the vocabulary. Softmax turns the scores into chances that add up to one. The model then picks a token, either the most likely one or a random draw, adds it to the text, and runs again.

## Say it in 2 minutes

Think of the same claims handler from earlier, typing a reply. Their notes list the likely next words, each with a rough chance, and they pick one, read the sentence again and repeat. A transformer ends the same way. The newest position's hidden state holds everything the model has worked out so far, and the last steps turn it into one word.

First, a linear layer gives one raw score for every token in the vocabulary. Softmax then turns those scores into chances that add up to one. In a bank's support bot that has written 'Your refund will be', made-up scores might give 'processed' about 67 percent, 'in' about 24 percent and 'delayed' about 9 percent. The 2017 transformer paper describes this same final step in one sentence.

Then the model picks. Greedy decoding always takes the most likely token, which is repeatable but can repeat itself on long replies. Sampling draws a token by its chance. That adds variety, and also the risk of an odd wording. The chosen token joins the text, and the whole model runs again for the next one.

For a bank, I would keep the pick steady for policy answers and never let the model's wording be the only check on a fee. The amount should come from the rate sheet in code, and the model only explains it.

## What is the last step inside a transformer, in plain words?

Google's machine learning course calls LLMs, the large language models behind AI chat tools, essentially autocomplete mechanisms that predict tokens. A transformer is the neural network design behind modern language models, and it is where the hidden state comes from. A token is a piece of text the model reads and writes: a whole word, or part of one.

After the layers have read your text, each position holds a hidden state: a vector of numbers that carries what the model has worked out there. The model can't write that vector. It has to become scores, then chances, then one token.

Think of a claims handler at an insurer typing a reply. Their notes list likely next words with a rough confidence for each. They choose one, read the sentence again and repeat. A bank's support bot writing 'Your refund will be' works the same way, with its notes coming from the hidden state.

- **Hidden state:** The vector of numbers a transformer makes for one position in the text.
- **Vocabulary:** The fixed list of tokens the model can write, from word pieces to whole words.
- **Score:** A raw number for one token. Higher means the model leans to it more. It is not a chance yet.
- **Softmax:** A step that turns scores into chances, all positive and adding up to one.

## How does the last hidden state become one score per token?

The vocabulary is the list of tokens the model can write. The final linear layer has one row for each token. Multiplying the hidden state with each row gives one score per token, and a higher score means the model leans more to that token.

*Diagram, From the last hidden state to one token: The last hidden state goes through one linear layer, then softmax, then a pick. The chosen token joins the text, and the loop runs again.*
1. The last hidden state goes into one linear layer.
2. The layer gives one raw score per vocabulary token.
3. Softmax turns the raw scores into chances that add up to 1.
4. The model picks one token: the top one, or a random draw.
5. The chosen token is added to the text.
6. The whole model runs again for the next token.

The layer is a plain weighted sum for each token. The 2017 paper that introduced the transformer describes this final step in one sentence:

> "We also use the usual learned linear transformation and softmax function to convert the decoder output to predicted next-token probabilities." (Vaswani et al., Attention Is All You Need (2017))

The same paper shared one weight matrix between its two embedding layers and this final layer. Its English-German setup had a shared vocabulary of about 37,000 tokens, so its final layer made about 37,000 scores at each step, one per token.

## How does softmax turn scores into probabilities?

Softmax does two jobs. It raises the constant e (about 2.72) to the power of each score, so every value is positive and a higher score grows much faster. Then it divides each value by the total, so the results add up to one.

Here are made-up scores for the next word after 'Your refund will be'. The code runs softmax, prints the chances and picks the top one.

```python
import math

# Made-up scores a model gives the next word after "Your refund will be"
scores = {"processed": 2.0, "in": 1.0, "delayed": 0.0}

def softmax(scores):
    # Turn raw scores into probabilities that add up to 1.
    exps = {word: math.exp(s) for word, s in scores.items()}
    total = sum(exps.values())
    return {word: e / total for word, e in exps.items()}

probs = softmax(scores)
for word, p in sorted(probs.items(), key=lambda kv: -kv[1]):
    print(f"{word:<10} {p:.2f}")
print("sum", round(sum(probs.values()), 2))
best = max(probs, key=probs.get)
print("greedy picks:", best)
```

Output:

```text
processed  0.67
in         0.24
delayed    0.09
sum 1.0
greedy picks: processed
```

That is why 'processed' gets about 2.7 times the chance of 'in'.

## How is the next token picked?

Greedy decoding takes the top token every time. Sampling draws one at random, weighted by its chance, so a less likely token can win. Hugging Face's docs describe both:

> "It selects the next most likely token at each step." (Hugging Face, Transformers docs)
>
> "Sampling, or multinomial sampling, randomly selects a token based on the probability distribution over the entire model's vocabulary (as opposed to the most likely token, as in greedy search)." (Hugging Face, Transformers docs)

*Diagram, Greedy vs sampling on the same chances: Both methods start from the same chances. Greedy always takes the top token, while sampling draws one, so the wording can change between runs.*
1. Greedy looks at the same chances and takes the top one.
2. Sampling draws a token by its chance, so a less likely one can win.
3. Same input and setup, same path, so the wording repeats.
4. Each run can take a different path, so the wording varies.

Greedy is steady, but it breaks down on longer outputs because it begins to repeat itself. Two settings change only this pick step. Temperature makes the chances sharper or flatter before the draw. Top-p limits the draw to the most likely tokens, whose chances add up to a set share.

### How would you explain two different answers to the same question?

Ask the bot twice with sampling on, and the two wordings can differ. Each word was a draw from the chances, so a different draw takes a different path. Greedy decoding, with the same input and setup, follows the same path each time.

> **Tip:** Say that the pick is one step, and fix it at the right layer. For policy wording, use greedy or a low temperature. For a fee, take the number from the rate sheet in code, not from the model.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] The last hidden state is a vector for one position, not a word.
- [ ] One linear layer gives one score per vocabulary token.
- [ ] Softmax turns the scores into chances that add up to one.
- [ ] The model picks one token, greedy or by sampling, then repeats.
- [ ] Temperature and top-p change only the pick step.
- [ ] Facts like fees come from code and data, not from the picked word.

**Common traps**

- Trap: "The hidden state is already the next word." Better: It is a vector. It becomes scores, then chances, then one token.
- Trap: "Softmax picks the best word." Better: Softmax only turns scores into chances. The pick step, greedy or sampling, chooses.
- Trap: "Temperature changes what the model knows." Better: It reshapes the chances the pick step draws from.

## Can you spot the wrong step?

**Spot the step:** A refund bot's code turns its raw scores into chances that add up to 1. Which line does that?

A. probs = scores * 0.5
B. probs = max(scores)
C. probs = softmax(scores)
D. probs = list(scores)

**Answer:** C. Softmax makes every value positive and divides by the total, so the chances add up to one. Halving keeps raw numbers, max keeps one value, and list only copies the scores.

**Quick check:** A bank's FAQ bot must word the same answer the same way every time for one question. Which pick method suits that best?

A. Sample at a high temperature
B. Take the most likely token at each step
C. Pick any token from the vocabulary at random
D. Use a bigger model with more parameters

**Answer:** B. Greedy decoding takes the top token at each step, so the same input and setup give the same path. Greedy can repeat itself on long replies, which is the trade-off. Sampling adds variety, and a bigger model doesn't change the pick rule.

## Can you answer these from memory?

**Flash cards**

- **What is the hidden state?** The vector a transformer makes for one position in the text.
- **What does the linear layer output?** One raw score per vocabulary token.
- **What does softmax do?** Turns scores into chances that are positive and add up to 1.
- **Greedy vs sampling?** Greedy takes the top token. Sampling draws one by its chance.
- **What does temperature change?** The chances the pick step draws from.
- **What happens after a token is picked?** It joins the text, and the model runs again.

## Likely follow-up questions

- Q013 Greedy vs beam search vs sampling? https://designervenkat.online/interview/ai/greedy-vs-beam-search-vs-sampling
- Q010 What does temperature control? https://designervenkat.online/interview/ai/what-does-temperature-control
- Q012 What is top-p (nucleus) sampling? https://designervenkat.online/interview/ai/what-is-top-p-nucleus-sampling
- Q067 What is weight tying? (full answer coming)
- Q065 Prefill vs decode phases? https://designervenkat.online/interview/ai/prefill-vs-decode-phases
- Q073 Walk through one decoder block's forward pass. https://designervenkat.online/interview/ai/walk-through-one-decoder-block-forward-pass

## Learn it in depth

- [Transformers](https://designervenkat.online/learn/machine-learning/transformers)
- [Sampling Parameters](https://designervenkat.online/learn/ai-engineering/sampling-parameters)
