GPT from Scratch: From Next-Token Prediction to GPT

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play

1/34

flashcard set

Earn XP

Description and Tags

Practice exam flashcards covering sequence modeling, causality, the Transformer architecture, decoding methods, evaluation metrics, and inference optimization based on the lecture 'GPT from scratch'.

35 Terms

1
New cards

How is next-token prediction framed as a classification task for a vocabulary VV?

At each position, the model predicts a probability distribution pθ(xt=v∣x<t)p_\theta(x_t = v \mid x_{<t}), producing V=∣V∣V = |V| scores over the vocabulary VV.

2
New cards

What trade-offs are associated with character, word, and subword tokenization units?

Character tokenization uses a small vocabulary but produces long sequences; word tokenization results in a large vocabulary; subword tokenization balances sequence length and vocabulary size.

3
New cards

According to the chain rule of probability, how is the probability of an entire sequence pθ(x1,…,xT)p_\theta(x_1, \ldots, x_T) expressed?

It is the product of all conditional next-token probabilities: pθ(x1,…,xT)=∏t=1Tpθ(xt∣x<t)p_\theta(x_1, \ldots, x_T) = \prod_{t=1}^T p_\theta(x_t \mid x_{<t}).

4
New cards

What is the maximum likelihood objective used for training a language model on a corpus D\mathcal{D}?

min⁡θ−∑x∈D∑tlog⁡(pθ(xt∣x<t))\min_\theta -\sum_{x \in \mathcal{D}} \sum_t \log(p_\theta(x_t \mid x_{<t}))

5
New cards

What is the cross-entropy loss value for a target token probability of 0.50.5, and what is it for a uniform prediction over vocabulary VV?

A target probability of 0.50.5 gives a loss of approximately 0.693 nats0.693\text{ nats}, whereas a uniform prediction gives a loss of log⁡(V)\log(V).

6
New cards

What is teacher forcing during training, and what computational benefit does it provide?

Training supplies ground-truth prefix tokens directly from the corpus rather than generated tokens, allowing all sequence positions to be evaluated simultaneously in parallel.

7
New cards

In the tensor contract of the small GPT model, what are the shapes for Token IDs, Shifted targets, Hidden states, and Logits?

Token IDs have shape (B,T)(B, T), Shifted targets have shape (B,T)(B, T), Hidden states have shape (B,T,C)(B, T, C), and Logits have shape (B,T,V)(B, T, V), where BB is batch size, TT is context length, CC is hidden width, and VV is vocabulary size.

8
New cards

How many next-token predictions are evaluated in a full unpadded batch of shape (B,T)(B, T)?

There are BTBT predictions in a full unpadded batch.

9
New cards

How is the causal mask MijM_{ij} defined, and why does it keep the diagonal?

The causal mask is defined as Mij=0M_{ij} = 0 for j≤ij \le i and Mij=−∞M_{ij} = -\infty for j>ij > i. The diagonal is kept because the current input at position ii is known.

10
New cards

How does the bigram baseline compute next-token logits ztz_t, and how many trainable logits does it have?

It computes logits via lookup zt=W[xt,:]z_t = W[x_t, :] where W∈RV×VW \in \mathbb{R}^{V \times V}, using V2V^2 trainable logits.

11
New cards

What fundamental limitation does a bigram baseline exhibit when processing sequences such as 'go' and 'goo'?

Because both prefixes end with the same final character, the bigram model produces identical next-token logits for both, being unable to distinguish preceding context.

12
New cards

How are input representations XiX_i constructed from token and position embeddings in the small GPT?

They are combined by vector addition after lookup: Xi=E[xi]+P[i]X_i = E[x_i] + P[i], where E∈RV×CE \in \mathbb{R}^{V \times C} and P∈RTmax⁡×CP \in \mathbb{R}^{T_{\max} \times C}, preserving hidden width CC.

13
New cards

What are the primary differences between a BERT-style encoder and a GPT-style language model?

BERT uses bidirectional attention, a masked-token objective, and can attend to right context; GPT uses causal attention, an autoregressive next-token objective, and accesses only the prefix.

14
New cards

In the causal self-attention formula Y=AUY = AU where A=softmaxrow(QK⊤dh+M)A = \text{softmax}_{\text{row}}\left(\frac{QK^\top}{\sqrt{d_h}} + M\right), why is UU used for values instead of VV?

UU is used to denote value representations because VV is reserved for vocabulary size.

15
New cards

In multi-head attention with hidden width CC and number of heads HH, what is the dimension dhd_h of each head?

dh=CHd_h = \frac{C}{H}, where HH must divide CC.

16
New cards

What are the two equations defining a pre-normalization Transformer block?

X′=X+Attention(LN1(X))X' = X + \text{Attention}(\text{LN}_1(X)) and X′′=X′+MLP(LN2(X′))X'' = X' + \text{MLP}(\text{LN}_2(X')), where the MLP operates with an internal expansion of C→4C→CC \rightarrow 4C \rightarrow C.

17
New cards

What formal test checks that an implementation satisfies causality without future-token leakage?

Given two input sequences sharing a prefix x≤k=x≤k′x_{\le k} = x'_{\le k}, the model in evaluation mode must produce matching prefix logits z≤k≃z≤k′z_{\le k} \simeq z'_{\le k} within a small floating-point tolerance.

18
New cards

Why does future-token leakage produce misleadingly low training loss?

Without proper causal masking, position ii can attend directly to input token xi+1x_{i+1}, which is its exact prediction target, making training artificially easy while failing completely at generation time.

19
New cards

What diagnostic test should be performed on a small fixed batch before corpus-level training?

Overfit a separate diagnostic model on a small fixed batch with dropout disabled to verify that loss decreases strongly with repeated updates, confirming optimization correctness.

20
New cards
<p>What phenomenon is illustrated by the diverging relationship between training and validation loss curves over updates?</p>

What phenomenon is illustrated by the diverging relationship between training and validation loss curves over updates?

It illustrates overfitting, demonstrating that a decreasing training loss alone is insufficient and checkpoints must be chosen using validation performance.

21
New cards

How is perplexity (PPL) mathematically defined from sequence log-probabilities?

PPL=exp⁡(−1N∑t=1Nlog⁡(pθ(xt∣x<t)))\text{PPL} = \exp\left(-\frac{1}{N} \sum_{t=1}^N \log(p_\theta(x_t \mid x_{<t}))\right), representing the geometric-mean inverse target probability.

22
New cards

In the recorded notebook comparison, what were the validation cross-entropy per character scores for the Bigram, Count bigram, and Small GPT models?

The Bigram baseline achieved 2.54922.5492 (500500 updates), the add-one smoothed Count bigram achieved 2.47202.4720, and the Small GPT achieved 2.39892.3989 (1,5001,500 updates).

23
New cards

In the ablation experiment comparing Small GPT with and without learned position embeddings over 1,0001,000 updates, what were the recorded cross-entropy results?

The model with learned positions scored 2.4752 nats/char2.4752\text{ nats/char} (112,577112,577 parameters) while the model without positions scored 2.4312 nats/char2.4312\text{ nats/char} (108,481108,481 parameters), a difference of −0.0440 nats/char-0.0440\text{ nats/char}.

24
New cards

Why does greedy decoding fail to find the globally optimal sequence probability?

Greedy decoding chooses the single locally most probable token at each step (xt+1=arg⁡max⁡vzvx_{t+1} = \arg\max_v z_v), which can miss sequences whose initial tokens have lower individual probability but lead to a higher cumulative product.

25
New cards

How does temperature τ>0\tau > 0 affect the logit distribution qτ(v)=ezv/τ∑uezu/τq_\tau(v) = \frac{e^{z_v/\tau}}{\sum_u e^{z_u/\tau}}, and how does it impact greedy decoding?

τ<1\tau < 1 concentrates probability on larger logits while τ>1\tau > 1 flattens the distribution; because positive temperature preserves relative rankings, greedy decoding output remains completely unchanged.

26
New cards

What does entropy H(q)=−∑vq(v)log⁡(q(v))H(q) = -\sum_v q(v) \log(q(v)) indicate about a model's prediction distribution?

Entropy measures the spread or dispersion of token probabilities (uncertainty), not factual correctness; a low-entropy distribution indicates high confidence but can still be factually incorrect.

27
New cards

How does top-p (nucleus) sampling select candidate tokens compared to top-k sampling?

Top-k selects a fixed count kk of highest-probability tokens, whereas top-p dynamically selects the smallest set of ranked tokens whose cumulative probability meets or exceeds threshold ρ\rho.

28
New cards

What is the standard convention regarding the order of operations for temperature scaling, filtering, and sampling?

Divide logits by temperature τ>0\tau > 0, apply the filtering rule (top-k or top-p), normalize the retained probabilities, and sample the next token.

29
New cards

What scoring metric does beam search maximize across candidate prefixes?

It ranks hypotheses by cumulative log-probability: score(x1:t)=∑i=1tlog⁡(pθ(xi∣x<i))\text{score}(x_{1:t}) = \sum_{i=1}^t \log(p_\theta(x_i \mid x_{<i})), maintaining up to bb hypotheses.

30
New cards

What is the operational distinction between prefill and incremental decoding in language model inference?

Prefill processes all prompt positions simultaneously in parallel to build the initial key-value cache, whereas incremental decoding processes one newly chosen token per step to extend the cache sequentially.

31
New cards

What is the approximate formula for the total number of elements stored in a standard multi-head attention KV cache?

≈2LBTHKVdh\approx 2 L B T H_{\text{KV}} d_h elements, where LL is layers, BB is batch size, TT is cached positions, and HKVdh=CH_{\text{KV}} d_h = C.

32
New cards

How does computational complexity scale for full-window attention recomputation versus a single query step using a KV cache?

Full-window attention recomputation scales quadratically as O(T2)O(T^2) per head, whereas a single cached query scores linearly against roughly O(T)O(T) past keys.

33
New cards

Why does a sliding window cache fail when paired naively with learned absolute position embeddings?

Reindexing position embeddings inside the sliding window alters the positional representations assigned to past tokens, causing cached key-value states to diverge from recomputed values.

34
New cards

What is the key limitation of constrained decoding using formal grammars or schemas?

Constrained decoding strictly guarantees syntactic and schema conformity, but valid structure does not ensure that the generated content contains correct factual statements.

35
New cards

What training steps are used to adapt a base pre-trained language model into an assistant model?

Base pre-training learns corpus continuation, supervised instruction tuning teaches dialogue format and response patterns, and preference-based training shapes alignment and conversational behaviour.