GEN‑AI · Alex’s Studybook
Generative AI · SS26 · Offline exam companion

From tokens to Transformers—and beyond.

A self-contained studybook for Alex: concepts explained from first principles, every supplied exercise resolved, every calculation checked, and every priority tied back to the actual course evidence.

664 PDF pages reviewed115 notebook cells reviewed29 course sources inventoriedMath + diagrams firstGenerated 14 July 2026
How to use this book

Learn in dependency order, revise in exam order

The exam note says to expect substantial mathematics and likely diagram questions, while the supplied work is coding-heavy. First build the dependency chain; then switch on “Exam-core only,” reproduce each diagram, and work the numerical exercises without looking.

16:00Exam time noted in README
1 × A4Handwritten sheet allowed
≈90%Coding emphasis reported
No backgroundAssumed in this book

Dependency route

Priority legend. 🔴 is a probable hand-calculation, derivation, shape trace, or core diagram. 🟠 is implementation/application knowledge. 🟡 is enabling context. ⚪ is low-yield catalogue/history. 🗑️ is decorative slide noise. Each substantial concept below carries exactly one label.
Chapter 0 · Foundations

The small toolkit everything else reuses

If matrix shapes, conditional probability, or logarithms feel automatic, skim this. If not, master it before attention or state-space models: nearly every later “hard” formula is a composition of these pieces.

🔴 Exam-core

Shapes are type signatures

A vector is an ordered list; a matrix is a function from one vector space to another. Multiplication (m×n)(n×p)→(m×p) is legal only when the inner dimensions match. Each result entry is a row–column dot product.

Cij = Σk=1n AikBkjRead: output row i, column j is the sum of elementwise row/column products.

Evidence: 6-presentation-architecture.pdf pp. 2–5; 6-practical.ipynb cell 3.

🔴 Exam-core

Conditional probability and the chain rule

A language model asks: “given the prefix, how plausible is the next token?” Multiplying those conditional probabilities gives the probability of the whole sequence.

P(w₁,…,wₙ) = ∏t=1n P(wt | w₁,…,wt−1)A Markov model shortens the condition to a fixed-size recent context.

Evidence: 2-presentation-markov.pdf pp. 18, 34–39.

🔴 Exam-core

Logarithms turn products into sums

Probabilities are tiny; logs prevent numerical underflow and make products additive. The base changes the unit: natural log gives nats, log₂ gives bits. Perplexity exponentiates average negative log-likelihood back into an “effective branching factor.”

NLL = −Σ log pt   ;   PPL = exp(NLL / N)Use one log base consistently; exp pairs with natural log.

Evidence: Markov pp. 37–39; Word2Vec notebook Questions; log_10.png.

🔴 Exam-core

Softmax makes a categorical distribution

Exponentiate logits and normalize. Subtracting the largest logit leaves the result unchanged but avoids overflow.

softmax(z)i = ezᵢ−m / Σjezⱼ−m,   m=max(z)Inputs are dimensionless scores; outputs are non-negative and sum to one.

Evidence: 4-presentation-rnn.pdf pp. 12–15; 6-presentation-architecture.pdf pp. 106–114.

Formula contract: cross-entropy

L = −Σc yc log pc = −log ptrueFor one-hot y, only the true class survives.
Meaning
Surprise assigned to the correct class.
Inputs
Target distribution y and predicted probabilities p; both length |V|.
Assumptions
p is normalized and the true class has nonzero probability.
Use
Next-token or masked-token training.
Common mistake
Applying cross-entropy to probabilities when a library function already expects raw logits.
Worked value
If the correct-token probability is 0.206, then L = −ln(0.206) ≈ 1.58 nats.
Chapter 1

Markov language models: count, condition, generate

A Markov model is a directed weighted graph over contexts. It is interpretable and easy to sample, but fixed memory creates state explosion and zero-probability failures.

🔴 Exam-core

The Markov assumption

An order-k model says the next token depends only on the previous k tokens. A bigram uses one-token context; a trigram normally uses two-token context. Count every context→next transition, then normalize outgoing counts.

P(wt|h) = count(h,wt) / Σv∈Vcount(h,v)h is the retained history; probabilities leaving h sum to 1.

Evidence: 2-presentation-markov.pdf pp. 3–24; notebook Tasks 2–6.

🔴 Exam-core

Perplexity

Perplexity is the inverse geometric mean probability per predicted token. Lower is better only on the same tokenization and evaluation set. A single unsmoothed zero-probability transition makes it infinite.

PPL(w₁…wₙ) = [∏t=1nP(wt|ht)]−1/nDimensionless; N must match the number of predicted tokens in the convention used.

Evidence: Markov pp. 37–40; notebook Tasks 8–9.

Original Markov language model diagramSTARTIYoulikewanthavehatecoffeebookstimerain½½¼
Original reconstruction of the supplied simple-model structure: probabilities are attached to outgoing choices. Redraw this pattern and label normalization, context, and transition probability.
🟠 Exam-practical

Generation

Start at a seed context; sample a next token from its outgoing distribution; append it; shift the context window; repeat until an end condition. Temperature is not inherent to counts, but one can transform probabilities with pᵢ1/T and renormalize.

Evidence: Markov notebook Tasks 5–6; Markov pp. 20–24.

🔴 Exam-core

State explosion

With vocabulary V and k retained context tokens, there are at most |V|k contexts and |V|k+1 directed next-token transitions. Sparse maps store only observed ones. Do not confuse “trigram” (three tokens per probability) with a state that itself stores three tokens.

Evidence: Markov pp. 34–36; notebook Task 7. The slides’ combination count is corrected in the discrepancy ledger.

Chapter 2

Representing text: from counts to learned geometry

A representation turns a symbolic token into numbers a model can compare and transform. Count vectors are interpretable but sparse; learned embeddings compress distributional similarity into dense coordinates.

🟡 Context

One-hot and bag-of-words

One-hot vectors identify tokens; their dot product is zero for different words, so they encode no graded similarity. Bag-of-words sums token counts and discards order.

Embeddings pp. 9–23.

🔴 Exam-core

TF–IDF

TF rewards frequency in a document; IDF suppresses terms appearing in many documents. The course uses a smoothed base-10 convention.

TF(t,d)=count(t,d)/|d|   ;   IDF(t)=log₁₀(1+N/df(t))

Embeddings pp. 24–31; Word2Vec notebook Questions.

🟠 Exam-practical

Word2Vec

CBOW predicts a center token from surrounding context; skip-gram predicts context from a center token. The embedding matrix row is the learned word vector; the output/unembedding matrix need not be identical.

Embeddings pp. 32–43; Word2Vec notebook cells 1–11.

Context matters. A single static vector for “bank” blends senses. Contextual Transformer embeddings instead produce a vector for a token occurrence after it attends to its sentence.
Chapter 3

RNNs and LSTMs: sequence state before attention

An RNN reuses the same transition at every time step. That parameter sharing handles variable-length sequences; the compressed hidden state and difficult gradient path limit long-range memory.

🔴 Exam-core

Vanilla recurrence

ht=tanh(Wxhxt+Whhht−1+bh)
pt+1=softmax(Whyht+by)

Shapes: xₜ∈ℝd, hₜ∈ℝH, Wxh∈ℝH×d, Whh∈ℝH×H. Unrolling is a diagram of repeated computation, not separate parameter sets.

RNN pp. 16–21; RNN notebook.

🔴 Exam-core

LSTM gates

fₜ=σ(Wf[hₜ₋₁,xₜ]+bf)
iₜ=σ(…); ĝₜ=tanh(…); cₜ=fₜ⊙cₜ₋₁+iₜ⊙ĝₜ
oₜ=σ(…); hₜ=oₜ⊙tanh(cₜ)

The cell state provides an additive path. Forget gate near 1 retains a component; near 0 erases it. Gates are vectors, so memory is controlled componentwise.

RNN pp. 22–24; bidirectional LSTM notebook.

🟠 Exam-practical

Bidirectionality is not causal generation

A bidirectional layer combines left-to-right and right-to-left states when the whole input is known—useful for classification or tagging. A standard autoregressive decoder cannot use future target tokens. The supplied prefix-based generator can be trained, but calling its recurrent layer “bidirectional” does not grant access to unknown future words at inference; it is a pedagogical architecture, not a causal decoder design.

Attention pp. 4–9; bidirectional-LSTM-generator.ipynb cells 1–15.

Chapter 4

Attention: content-addressable working memory

Instead of compressing a source sequence into one fixed vector, attention lets each query retrieve a weighted mixture of values. Keys determine addressability; values carry the retrieved content.

Scaled dot-product attention pipelineQ · queriesK · keysV · valuesscoresQKᵀ / √dₖrow softmaxattention weightsweighted retrievalA · Vn queries × n keys → n×n weights; weights × n×dᵥ values → n×dᵥ output
Original reconstruction. The two n×n objects are the score and weight matrices; the output is n×dᵥ. This corrects reversed shape comments in the practical notebook.
🔴 Exam-core

Scaled dot-product attention

Attention(Q,K,V)=softmax(QKᵀ/√dk)V

Scaling matters because a dot product of dₖ roughly unit-variance components has variance proportional to dₖ. Without √dₖ, softmax becomes overly sharp and gradients shrink.

Attention pp. 18–23; Architecture pp. 53–75.

🔴 Exam-core

Masking

A causal mask adds −∞ to scores for future key positions before softmax. Those probabilities become zero. A padding mask suppresses dummy tokens; it is a different mask for a different reason.

Architecture pp. 85–89.

Chapter 5

The Transformer: an end-to-end shape story

The block alternates token mixing (attention) and channel mixing (the position-wise feed-forward network), stabilized by residual paths and normalization. Track the sequence axis n and model axis d throughout.

Transformer decoder pipelinetokensnembedding+ positionmaskedMHAAdd + Normn×dFFNd→dff→dAdd + Normn×dunembedn×|V|softmaxp(next)residual paths preserve a direct signal route
Original decoder-block overview. In a stack, the attention/add-norm/FFN/add-norm pattern repeats; its parameters are different per layer.
🔴 Exam-core

Embedding + position

Lookup gives X∈ℝn×d. Add a position vector of the same shape; addition preserves n×d. Sinusoidal encoding alternates sine/cosine frequencies.

PE(pos,2i)=sin(pos/100002i/d)
PE(pos,2i+1)=cos(pos/100002i/d)

Architecture pp. 11–52.

🔴 Exam-core

Multi-head attention

Each head projects X into smaller Q,K,V spaces, retrieves a different relation, then concatenation returns n×(h·dᵥ). Wᴼ maps that back to d.

Architecture pp. 53–84.

🔴 Exam-core

FFN + residual + norm

The same two-layer MLP is applied independently to every position. Residual addition requires equal shapes. LayerNorm normalizes across each token’s feature dimension, then learns scale γ and shift β.

LN(x)=γ⊙(x−μ)/√(σ²+ε)+β

Architecture pp. 90–105.

Formula contract: scaled attention

Meaning
For each query, compare every allowed key and average the corresponding values.
Shapes
Q: nq×dₖ; K: nk×dₖ; V: nk×dᵥ; output: nq×dᵥ.
Units
Dimensionless learned coordinates; output has the value representation’s coordinates.
Assumptions
Q and K share dₖ; masks are applied before softmax.
Use
Self-attention if Q,K,V come from one sequence; cross-attention if queries and key/value memory differ.
Do not use
As a nearest-neighbor claim without the learned projections and normalization context.
Common mistake
Softmax over the wrong axis. Normalize each query row across keys.
Chapter 6

Modern Transformer techniques

The base equations stay recognizable; modern systems change position encoding, share attention projections, constrain connectivity, improve kernels, and activate only part of the feed-forward capacity.

🔴 Exam-core

RoPE

Rotary position embedding rotates pairs of query/key coordinates by a position-dependent angle. Their dot product then depends on relative displacement; values are not rotated in the basic form.

Technique pp. 49–60.

🔴 Exam-core

GQA

Grouped-query attention keeps many query heads but shares fewer key/value heads across groups. It reduces KV-cache memory and decoding bandwidth between MHA and multi-query attention.

Technique pp. 61–69.

🟡 Context

Local and fused attention

Sliding windows reduce the number of connected pairs. FlashAttention computes exact attention with tiled memory-efficient kernels; it is not an approximation and does not change the mathematical output.

Technique pp. 70–76.

🟠 Exam-practical

GELU and SwiGLU

GELU smoothly gates by input magnitude. SwiGLU splits the hidden projection: one branch is SiLU-gated and multiplied elementwise by another, then projected back.

Technique pp. 77–78.

🟠 Exam-practical

Mixture of experts

A router scores experts per token, activates top-k, normalizes selected weights, and sums expert outputs. Sparse activation increases parameter capacity without proportional per-token compute; load-balancing loss fights expert collapse.

y(x)=Σi∈TopK(x) gi(x)Ei(x)

Technique pp. 79–89; Models pp. 55–84; 04_moe_layer.py.

⚪ Low priority

Scaling catalogues

Context-length charts and named model tables establish why efficiency matters, but memorizing volatile product numbers has little evidence value compared with deriving attention and routing.

Technique pp. 35–48; Models pp. 42–54.

Chapter 7

Model families, training objectives, and adaptation

🔴 Exam-core

Encoder-only and masked language modeling

Bidirectional self-attention produces contextual token representations. BERT-style corruption selects 15% of tokens: of those selected positions, 80% become [MASK], 10% a random token, and 10% remain unchanged; loss is computed only at selected positions.

Models pp. 14–33; practical Parts 1–3. Original reference: Devlin et al., BERT (2018).

🔴 Exam-core

Decoder-only causal modeling

A triangular mask permits each position to attend only leftward. Teacher forcing trains all next-token positions in parallel; generation is sequential because each new sample becomes part of the next prefix.

Models pp. 34–41; Architecture pp. 115–119.

🟠 Exam-practical

Fine-tuning and LoRA

Full fine-tuning updates all weights. LoRA freezes W and learns a low-rank update ΔW=BA with rank r≪d, reducing trainable parameters and optimizer memory. At inference the update can be merged.

Models pp. 98–107. Original reference: Hu et al., LoRA (2021).

🟠 Exam-practical

Training memory and parallelism

Memory includes parameters, gradients, optimizer states, activations, and temporary buffers. Data parallelism replicates the model; tensor/pipeline parallelism partitions computation; ZeRO partitions optimizer state, gradients, then parameters by stage.

Models pp. 85–97.

Chapter 8

State-space models and Mamba

SSMs start as dynamical systems: an input drives a latent state and the state produces an output. Discretization turns the continuous equation into a sequence recurrence; unrolling reveals a convolution for parallel training.

🔴 Exam-core

Continuous state

ḣ(t)=Ah(t)+Bx(t)   ;   y(t)=Ch(t)+Dx(t)

For a mass–spring–damper, choose state h=[position, velocity]ᵀ. Then velocity is the derivative of position and acceleration comes from mÿ+cẏ+ky=x(t).

SSM pp. 30–49.

🔴 Exam-core

Discrete recurrence

hk=Āhk−1+B̄xk   ;   yk=Chk

Under zero-order hold with step Δ: Ā=eΔA and B̄=A−1(eΔA−I)B when A is invertible. Bilinear/Tustin is a different approximation: Ā=(I−ΔA/2)−1(I+ΔA/2).

SSM pp. 42–63. The slide shorthand is clarified here.

🔴 Exam-core

Recurrence ↔ convolution

With h₋₁=0, unroll: y₀=CB̄x₀; y₁=CĀB̄x₀+CB̄x₁. Thus kernel K=[CB̄,CĀB̄,C²B̄,…] convolves with x. Compute K once and train in parallel; step the recurrence for constant-memory inference.

SSM pp. 64–77.

🔴 Exam-core

Selectivity and Mamba

A fixed linear time-invariant kernel cannot decide to store one token and ignore another based on content. Mamba makes discretization/input/output parameters input-dependent and uses a parallel associative scan. Selectivity improves content routing but gives up a single fixed convolution kernel.

SSM pp. 98–124. Original reference: Gu & Dao, Mamba (2023).

Correction to a slide phrase: in the Laplace domain, differentiation maps to multiplication by s (with initial-condition terms), not to a “past value.” Delay in the z-domain is represented by z−1. Keep those operations distinct.
Chapter 9

Retrieval-augmented generation: external memory with evidence

RAG indexing and query pipelinesOffline indexingOnline querydocumentschunk + metadataembedvector indexuser questionquery embeddingretrieve + rerankprompt with evidenceanswer + citations
Original reconstruction of the two-phase RAG system. Evaluation must separate retrieval failure from generation failure.
🟠 Exam-practical

Retrieval stack

Chunk documents, preserve metadata, embed chunks, and index them. Dense nearest-neighbor search finds semantic candidates; HNSW trades exactness for fast graph traversal. A cross-encoder can rerank a small candidate set more accurately than a bi-encoder.

RAG pp. 11–25.

🟠 Exam-practical

Failure decomposition

If the needed passage was not retrieved, fix chunking/query/index/search. If good evidence was retrieved but the answer is wrong, fix prompt grounding, context ordering, model behavior, and citation checks. Measure recall@k separately from answer faithfulness.

RAG pp. 26–31. Original reference: Lewis et al., RAG (2020).

Chapter 10

AI-assisted programming: useful output is untrusted input

🟠 Exam-practical

Evidence loop

Specify constraints and acceptance tests; ask for small reviewable changes; run linters, types, unit/integration/security tests; inspect the diff; verify dependencies and licenses; keep a human accountable for deployment.

AI programming pp. 15–29.

⚪ Low priority

History and tool catalogue

Product timelines show rapid capability change, but exact vendor features age quickly. The durable exam lesson is the workflow: prompts do not replace specifications, testing, provenance, or threat modeling.

AI programming pp. 1–14.

Complete solution manual

Every supplied task, worked in source order

Numbering preserves the source notebook task labels or PDF page prompts. Where a source depends on an absent corpus or large model download, the solution gives executable reference code, deterministic shape/value checks, and the result that can be established without inventing a training run.

🔴 Exam-core

Markov notebook · Tasks 1–6 — corpus to generator and graph

markov-generator.ipynb cells 2–16; visualize_utils.py lines 1–66

Requested parts

  1. Prepare plain text.
  2. Normalize it to words.
  3. Create adjacent tuples.
  4. Build transition counts/probabilities.
  5. Generate text.
  6. Visualize a bounded subgraph.

Complete reference solution

import re, random from collections import defaultdict, Counter def file_to_words(path): text = open(path, encoding="utf-8").read().lower() return re.findall(r"[a-z]+(?:'[a-z]+)?|[.!?]", text) def adjacent_pairs(words): return list(zip(words, words[1:])) def build_chain(words): counts = defaultdict(Counter) for a, b in adjacent_pairs(words): counts[a][b] += 1 return {a: {b: c/sum(cs.values()) for b,c in cs.items()} for a,cs in counts.items()} def generate(chain, start, length=30, rng=random): out = [start] for _ in range(length-1): choices = chain.get(out[-1]) if not choices: break out.append(rng.choices(list(choices), weights=choices.values(), k=1)[0]) return " ".join(out) # For visualization: random.sample(list(graph.nodes), k), not NodeView directly.
Final result: the chain stores normalized observed edges only; every outgoing probability sum is 1 (within floating error). Generation is weighted sampling over those edges.
Check. Assert all(abs(sum(p.values())-1)<1e-12 for p in chain.values()); verify every generated adjacent pair exists in the chain.
🔴 Exam-core

Markov notebook · Task 7 — scaling a trigram model

markov-generator.ipynb cell 17; 2-presentation-markov.pdf pp. 34–36

Given

Vocabulary |V|=10,000; each token ID is a 64-bit integer (8 bytes).

Resolve the terminology first

In the standard convention, a trigram probability predicts the third word from the previous two. Therefore context states: |V|²=10⁸. Possible directed (context,next) transitions: |V|³=10¹². If the task literally calls each 3-word tuple a “state,” there are 10¹² such tuples.

Storage

Storing every 3-ID tuple explicitly costs 10¹²×3×8 = 24×10¹² bytes = 24 TB decimal (≈21.83 TiB), before hash-table counts/pointers. Storing all possible standard trigram transitions also needs 10¹² counts; at 8 bytes/count alone, 8 TB.

Final answer: standard trigram context states = 10⁸; possible trigram transitions = 10¹². Literal three-token state tuples = 10¹² and raw IDs alone require 24 TB.
Sanity check. Increasing context length by one multiplies dense storage by |V|=10,000—why real n-gram models use sparse observed counts and smoothing.
🔴 Exam-core

Markov notebook · Tasks 8–9 — manual and implemented perplexity

markov-generator.ipynb cells 18–20; Simple_Model.png; Markov pp. 37–40

(8a) “I want coffee”

Using the course convention that includes the initial-word probability: P=½×¼×⅛=1/64. N=3, so PPL=(64)1/3=4.

(8b) “I like you”

The supplied graph has no transition from “like” to “you”; its probability is zero. Hence NLL=∞ and PPL=.

(9) Numerically stable implementation

import math def perplexity(tokens, transition_prob, start_prob=None): logp, n = 0.0, 0 if start_prob is not None: p = start_prob.get(tokens[0], 0.0) if p == 0: return math.inf logp += math.log(p); n += 1 for a,b in zip(tokens, tokens[1:]): p = transition_prob.get(a, {}).get(b, 0.0) if p == 0: return math.inf logp += math.log(p); n += 1 return math.exp(-logp/n)
Final answers: PPL(“I want coffee”)=4; PPL(“I like you”)=∞. The implementation agrees and avoids multiplying tiny probabilities.
Convention check. If the first token is treated as given, N=2 and the first result becomes √32≈5.657. The slides’ p.39 example uses N=3, so 4 is the course-aligned answer.
🟠 Exam-practical

Word2Vec notebook · Parts 0–4 — complete corrected pipeline

word2vec_tutorial.ipynb cells 1–9; checkpoint cells 1–9

Solution

Load 2–5 UTF-8 books; lowercase/tokenize; train TF–IDF over book documents and Word2Vec over sentence-token lists; obtain dense vectors; reduce with UMAP; visualize. The source’s UMAP line must call fit_transform, and a downloaded gensim model must be assigned from api.load.

from pathlib import Path from gensim.utils import simple_preprocess from gensim.models import Word2Vec from sklearn.feature_extraction.text import TfidfVectorizer import umap docs = [p.read_text(encoding="utf-8") for p in Path("books").glob("*.txt")] sentences = [simple_preprocess(line) for doc in docs for line in doc.splitlines() if line.strip()] tfidf = TfidfVectorizer(lowercase=True).fit_transform(docs) w2v = Word2Vec(sentences, vector_size=100, window=5, min_count=2, workers=1, seed=7) words = list(w2v.wv.index_to_key)[:500] xy = umap.UMAP(n_components=2, random_state=7).fit_transform(w2v.wv[words]) # scatter xy[:,0], xy[:,1], annotate selected words
Final result: TF–IDF produces one sparse vector per document; Word2Vec produces one dense learned vector per vocabulary word. UMAP produces a 500×2 visualization array, not the embedding model itself.
Check. tfidf.shape[0]==len(docs), w2v.wv.vectors.shape[1]==100, and xy.shape==(len(words),2).
🔴 Exam-core

Word2Vec notebook · Questions (a–b)

word2vec_tutorial.ipynb cells 10–11; Embeddings pp. 24–43

(a) Advantage of Word2Vec over TF–IDF

Word2Vec learns dense distributional similarity: words used in similar contexts can be close even if they are different tokens. TF–IDF is sparse, document-level, and primarily measures discriminative occurrence; it does not directly learn semantic neighborhoods. Word2Vec sacrifices direct interpretability and still gives one vector per word type.

(b) TF–IDF of “listened” in D2

D2 has five tokens and “listened” once: TF=1/5=0.2. It occurs in two of three documents: df=2, N=3. With the lecture’s formula, IDF=log₁₀(1+3/2)=log₁₀(2.5)=0.39794. Multiply: 0.2×0.39794=0.079588.

Final answers: Word2Vec adds dense learned similarity; course-convention TF–IDF(“listened”,D2) ≈ 0.0796.
Convention check. Unsmoothed log₁₀(N/df) would give 0.03522. That is valid elsewhere but not the formula printed on slide p.29.
🟠 Exam-practical

RNN notebook · setup, experiments, comparison, improvements

RNN-generator.ipynb cells 1–9; rnn.py lines 1–159

Instantiate correctly

The class requires a text path, omitted in one notebook cell: rnn = RNNGenerator("input.txt", mode="word"). Train multiple seeds/epochs with fixed random seeds; compare held-out NLL/perplexity and generated coherence.

Resolved comparison

ModelMemoryStrengthFailure
Markovexplicit fixed contextinterpretable counts, cheap trainingsparsity and state explosion
RNNlearned fixed-width hidden stateshares statistical strength across contextssequential training, vanishing/exploding gradients

Concrete improvements

Use LSTM/GRU gates, gradient clipping, dropout, validation-based early stopping, pretrained subword tokenization, larger/better-cleaned corpus, and temperature/top-k sampling. Evaluate perplexity on the same held-out tokens.

Final result: the RNN replaces an explicit context table with a learned recurrent state; improvements target gradient flow, generalization, data coverage, and decoding.
Check. Generation quality alone is not a controlled comparison; hold tokenization and test corpus fixed.
🔴 Exam-core

RNN notebook · theoretical Questions 1–2

RNN-generator.ipynb cells 10–11; RNN pp. 12–24

1. Softmax of z=[1,0,2,1]

Denominator = e¹+e⁰+e²+e¹ = (e+1)² ≈ 13.8256. Therefore softmax ≈ [0.196612, 0.072329, 0.534447, 0.196612]. Sum=1.

2. LSTM forget gate

Concatenate [hₜ₋₁,xₜ], apply affine transform and sigmoid: fₜ=σ(Wf[hₜ₋₁,xₜ]+bf). Then retained old memory is fₜ⊙cₜ₋₁. Values are in (0,1); all vectors have cell-width H.

Final answers: the third class is most probable at 0.534447; the forget gate multiplicatively retains or erases each prior cell component.
Check. Softmax preserves ties: positions 1 and 4 both have logit 1 and probability 0.196612.
🟠 Exam-practical

Bidirectional-LSTM notebook · all Questions

bidirectional-LSTM-generator.ipynb cells 1–15

1–2. Tokenizer, corpus, and padding

The tokenizer maps vocabulary strings to integer IDs and reserves 0 for padding; IDs are categorical labels, not magnitudes. A larger/cleaner corpus improves coverage but increases vocabulary/training cost. Training examples are prefixes→next-token; left padding makes equal batch lengths, and masking should prevent padding from affecting the sequence representation.

3. Architecture bullets

  • +1 vocabulary size: reserve index 0 for padding/out-of-vocabulary convention.
  • 150: embedding dimension chosen as a capacity hyperparameter, not derived from vocabulary size.
  • return_sequences: True returns an output per time step; False returns one final representation. Next-token classification from a padded prefix needs one vector.
  • Bidirectional: concatenates forward/backward representations of the known prefix; doubles output width unless merged differently.
  • Dropout: regularizes by zeroing random activations only during training.
  • Dense/ReLU/L2: adds nonlinear classification capacity and penalizes large weights.
  • Final softmax: one probability per vocabulary ID.

4–5. Generation and experiments

Sequence length fixes the maximum prefix window; output_word controls generated steps; tokenizer must match training. Temperature T<1 sharpens, T>1 diversifies. Compare model size/epochs with validation loss, held-out perplexity, repeated-seed generation, and overfitting gap.

Final result: every layer’s role and generation parameter is accounted for; index 0 is reserved, not an extra semantic word. Bidirectionality is acceptable only over the already-known prefix, not future targets.
Check. Final Dense width must equal vocabulary size; target IDs must lie in [1,|V|−1] when 0 is padding.
🔴 Exam-core

Architecture slides p.2 · matrix multiplication exercise

6-presentation-architecture.pdf pp. 2–5

For A=[[2,4,−1],[3,1,5]], A is 2×3, so AAᵀ is 2×2 and AᵀA is 3×3.

AAᵀ = [[21, 5], [5, 35]]
AᵀA = [[13,11,13],[11,17,1],[13,1,26]]

Example off-diagonal: row₁·row₂ = 2·3+4·1+(−1)·5=6+4−5=5.

Final answer shown above. The slide’s 7 in AAᵀ is an arithmetic error; every other displayed entry agrees with independent NumPy multiplication.
Check. Both Gram matrices are symmetric and positive semidefinite; trace(AAᵀ)=21+35=56 equals trace(AᵀA)=13+17+26=56.
🔴 Exam-core

Transformer practical · §1 Matrix Multiplication (a–b)

6-practical.ipynb cells 2–3

(a) Implementation

def matmul(A, B): assert len(A[0]) == len(B) return [[sum(A[i][k]*B[k][j] for k in range(len(B))) for j in range(len(B[0]))] for i in range(len(A))]

(b) Tests

Test identity, a hand-computed rectangular case, and incompatible shapes. For A above, compare against the two verified Gram matrices in the preceding solution.

Final result: the implementation calculates each row–column dot product and rejects illegal inner dimensions.
Check. matmul([[1,0],[0,1]],B)==B.
🔴 Exam-core

Transformer practical · §2 Embeddings (i–v)

6-practical.ipynb cells 4–6; Architecture pp. 11–26
  1. Create vocabulary with reserved <pad>=0, <unk>=1.
  2. Map each token with vocab.get(token,1).
  3. Initialize E∈ℝ|V|×d with seeded small random values.
  4. Lookup row E[id] for each sequence ID, producing X∈ℝn×d.
  5. Use torch.nn.Embedding(|V|,d,padding_idx=0); compare the same shape and verify the padding row remains zero under updates.
tokens = ["the","small","cat","is","outside"] vocab = {"<pad>":0,"<unk>":1, **{w:i+2 for i,w in enumerate(dict.fromkeys(tokens))}} ids = torch.tensor([vocab[w] for w in tokens]) # (5,) embed = torch.nn.Embedding(len(vocab), 4, padding_idx=0) X = embed(ids) # (5,4)
Final result: IDs have shape (5,), the embedding table has shape (7,4), and this sequence’s embedding matrix has shape (5,4).
Check. Token IDs are indices; never multiply or average them as numeric magnitudes.
🔴 Exam-core

Transformer practical · §3 Positional Encoding (i–iii)

6-practical.ipynb cells 7–9; Architecture pp. 27–52
  1. Implement the printed sine/cosine equations.
  2. Add PE∈ℝn×d elementwise to embeddings X∈ℝn×d.
  3. Visualize positions versus dimensions as a heatmap; low dimension pairs oscillate faster, high pairs slower.
def sinusoidal_pe(n, d): pos = torch.arange(n)[:,None].float() i = torch.arange(0,d,2)[None,:].float() angles = pos / (10000 ** (i/d)) pe = torch.zeros(n,d) pe[:,0::2] = torch.sin(angles) pe[:,1::2] = torch.cos(angles[:,:pe[:,1::2].shape[1]]) return pe X_pos = X + sinusoidal_pe(len(ids), X.shape[1])

For pos=0,d=4, PE=[0,1,0,1]. For pos=1, approximately [0.84147,0.54030,0.01000,0.99995].

Final result: PE and X both have shape 5×4; their sum preserves that shape and makes identical token embeddings position-distinguishable.
Check. At every position and frequency pair, sin²+cos²=1 up to rounding.
🔴 Exam-core

Transformer practical · §4 Self-Attention (i–vii)

6-practical.ipynb cells 10–13; Architecture pp. 53–89
  1. Choose dₖ and initialize WQ,WK,WV∈ℝd×dₖ.
  2. Q=XWQ, K=XWK, V=XWV, each n×dₖ.
  3. Scores=QKᵀ/√dₖ, shape n×n.
  4. Row-softmax scores; each row sums to 1.
  5. Output=weights·V, shape n×dₖ.
  6. Visualize weights as query-row/key-column heatmap.
  7. For causal attention set entries j>i to −∞ before softmax.
Q, K, V = X_pos@Wq, X_pos@Wk, X_pos@Wv scores = Q@K.T / math.sqrt(dk) # (n,n) causal = torch.triu(torch.ones(n,n,dtype=torch.bool), diagonal=1) scores = scores.masked_fill(causal, float("-inf")) weights = torch.softmax(scores, dim=-1) # (n,n) Y = weights@V # (n,dk)
Final result: score and weight matrices are n×n; the attention output is n×dₖ. The original notebook’s adjacent shape comments reverse these two and are corrected here.
Check. Every finite weight row sums to 1; every future-position weight is exactly 0 after the causal mask.
🔴 Exam-core

Transformer practical · §§5–8 Residual/Norm, FFN, unembedding, full model

6-practical.ipynb cells 14–29; Architecture pp. 90–119

§5 (i–ii)

Project attention output to d if needed, add X, then LayerNorm over the last dimension. Mean should be ≈0 and variance ≈1 per token before learned γ/β change it.

§6 optional (i–ii)

FFN(x)=W₂·ReLU(W₁x+b₁)+b₂, d→dff→d; apply independently to all n rows; add residual and normalize.

§7 (i–ii)

Unembedding WU∈ℝd×|V| maps each token state to logits; softmax along vocabulary yields probabilities. Decode greedy argmax or sample with temperature/top-k.

§8 recommended complete module

class MyTransformer(nn.Module): def __init__(self, vocab, d=64, heads=4, dff=128): super().__init__() self.emb = nn.Embedding(vocab,d) self.attn = nn.MultiheadAttention(d,heads,batch_first=True) self.n1,self.n2 = nn.LayerNorm(d),nn.LayerNorm(d) self.ff = nn.Sequential(nn.Linear(d,dff),nn.ReLU(),nn.Linear(dff,d)) self.out = nn.Linear(d,vocab,bias=False) def forward(self, ids): x = self.emb(ids) + sinusoidal_pe(ids.size(1),self.emb.embedding_dim).to(ids.device) mask = torch.triu(torch.ones(ids.size(1),ids.size(1),device=ids.device,dtype=torch.bool),1) a,_ = self.attn(x,x,x,attn_mask=mask) x = self.n1(x+a) x = self.n2(x+self.ff(x)) return self.out(x)
Final result: input (batch,n) → logits (batch,n,|V|). The source’s def MyTransformer(nn.Module) must be class MyTransformer(nn.Module).
Check. Shift training: compare logits[:,:-1] with targets ids[:,1:]; never train a token to predict itself.
🔴 Exam-core

Architecture slides p.48 · input embedding exercise (all items)

6-presentation-architecture.pdf pp. 48–52

Sentence: “the small cat is outside”; n=5,d=4, vocabulary size 6. (1) Tokenize to five IDs. (2) Select the five corresponding rows of E∈ℝ6×4, giving X∈ℝ5×4. (3) Compute PE for positions 0…4, giving 5×4. (4) Add elementwise X′=X+PE. (5) Output stays 5×4.

Verified PE rows begin [0,1,0,1], [0.84147,0.54030,0.01000,0.99995], [0.90930,−0.41615,0.02000,0.99980]. The fifth position must also be present even though an incremental slide view visually truncates the table.

Final answer: the model input is the five looked-up word rows plus the five positional rows, with shape 5×4. Vocabulary size affects E’s row count, not sequence length.
Check. Addition is legal only because both matrices are 5×4.
🔴 Exam-core

Technique slides p.3 · end-to-end Transformer walkthrough

7-presentation-technique.pdf pp. 3–34
  1. Token IDs select embedding rows; add position encodings.
  2. Each head computes Q=XWQ,K=XWK,V=XWV.
  3. Compute scaled score rows, row-softmax, and weighted values.
  4. Concatenate two head outputs and multiply by Wᴼ.
  5. Add the original stream and normalize.
  6. Apply FFN, add, normalize.
  7. Project to vocabulary logits; softmax.
  8. For the slide’s correct-class probability 0.206, cross-entropy is −ln(0.206)=1.579≈1.58.
  9. Backpropagate gradients and update parameters, e.g. W←W−η∇W.
Final result: the walkthrough preserves the sequence length through the block, returns the model width after head concatenation, and ends with |V| logits per position; the printed loss 1.58 is independently verified.
Check. At each residual add, both operands have identical shapes; at each softmax, probabilities sum to one on its stated axis.
🟠 Exam-practical

Practical Part 1 · MLM corruption, head, training, pooling, discussion

01_mlm_training.py lines 1–190; practical README Part 1

Complete logic

selected = (torch.rand(ids.shape,device=ids.device)<.15) & attention_mask.bool() & ~special_mask labels = ids.clone(); labels[~selected] = -100 r = torch.rand(ids.shape,device=ids.device) masked = ids.clone() masked[selected & (r<.8)] = mask_id random_pos = selected & (r>=.8) & (r<.9) masked[random_pos] = torch.randint(vocab_size, ids.shape, device=ids.device)[random_pos] # remaining selected 10% unchanged logits = lm_head(encoder(masked, attention_mask).last_hidden_state) loss = F.cross_entropy(logits.view(-1,vocab_size), labels.view(-1), ignore_index=-100)

Pooling: CLS uses one designated token; mean pooling averages non-padding tokens; max pooling takes featurewise maxima after masking pads. MLM prevents a trivial copy identity because most selected targets are hidden or changed; unchanged/random cases reduce the train–test mismatch of seeing [MASK]. Only selected labels contribute to loss.

Final result: expected selected rate ≈15%; within selected positions ≈80/10/10; logits shape batch×length×vocabulary; ignored labels contribute zero loss.
Check. Count ratios over a large synthetic batch and assert gradients are finite. Special and padding tokens must never be selected.
🟠 Exam-practical

Practical Part 2 · embedding visualization and discussion

02_visualize_embeddings.py lines 1–148; practical README Part 2

Obtain the static input embedding row for each token ID and the contextual last-hidden-state at its occurrence. Reduce a stacked array with PCA/UMAP, keeping labels and sentence contexts aligned.

with torch.no_grad(): static = model.get_input_embeddings()(ids) contextual = model(**batch).last_hidden_state # mask padding before reshape; fit reducer once to the combined comparison array xy = PCA(n_components=2).fit_transform(vectors.cpu().numpy())

Static vectors give one point per vocabulary item. Contextual vectors move with sentence meaning and layer. Dimensionality reduction can distort global distances; compare neighborhoods and multiple seeds, not just a pretty 2-D plot.

Final result: static “bank” has one coordinate; contextual “bank” has distinct coordinates for river/finance contexts. Reduction is a visualization, not proof of semantic structure.
Check. Exclude padding and subword-continuation mistakes; record which token position is plotted.
🟠 Exam-practical

Practical Part 3 · sentiment fine-tuning and discussion

03_finetune_sentiment.py lines 1–181; practical README Part 3
class Sentiment(nn.Module): def __init__(self, encoder, hidden, classes=2): super().__init__(); self.encoder=encoder; self.drop=nn.Dropout(.1); self.head=nn.Linear(hidden,classes) def forward(self, input_ids, attention_mask): h=self.encoder(input_ids=input_ids,attention_mask=attention_mask).last_hidden_state mask=attention_mask.unsqueeze(-1) pooled=(h*mask).sum(1)/mask.sum(1).clamp_min(1) return self.head(self.drop(pooled)) # optimizer.zero_grad(); loss=F.cross_entropy(model(...),labels); loss.backward(); # clip_grad_norm_(model.parameters(),1.0); optimizer.step()

Freeze the encoder for a cheap baseline, then unfreeze with a smaller encoder learning rate. Use stratified train/validation splits, macro-F1 for imbalance, and early stopping. The classifier head maps hidden width→2 logits.

Final result: each batch produces batch×2 logits; cross-entropy learns from integer class labels. Fine-tuning adapts contextual features; freezing tests whether existing features are linearly separable.
Check. Evaluate under model.eval() and torch.no_grad(); do not report training accuracy as generalization.
🟠 Exam-practical

Practical Part 4 · sparse MoE layer and discussion

04_moe_layer.py lines 1–185; practical README Part 4
class MoE(nn.Module): def __init__(self,d,dff,E=4,k=2): super().__init__(); self.router=nn.Linear(d,E); self.experts=nn.ModuleList([ nn.Sequential(nn.Linear(d,dff),nn.GELU(),nn.Linear(dff,d)) for _ in range(E)]) self.k=k def forward(self,x): score=self.router(x); val,idx=score.topk(self.k,dim=-1) gate=val.softmax(-1); out=torch.zeros_like(x) for e,expert in enumerate(self.experts): for slot in range(self.k): m=idx[...,slot]==e out[m]+=gate[...,slot][m,None]*expert(x[m]) return out,score

Top-k makes routing sparse; k=1 is cheapest but brittle, larger k improves mixture/redundancy. Expert collapse means a few experts receive most tokens; use an auxiliary importance/load loss, router noise, and capacity limits. Capacity factor sets buffer size relative to average tokens per expert; overflow tokens may be dropped or rerouted.

Final result: output shape equals input batch×length×d; only k of E expert outputs contribute per token; normalized selected gates sum to 1.
Check. Histogram routed tokens per expert and backpropagate a scalar output; confirm selected expert/router parameters receive finite gradients.
🟡 Context

Models slides p.42 · three LLMs and differentiators

8-presentation-models.pdf p. 42

Stable examples, described by architectural/use distinctions rather than volatile leaderboard claims: (1) GPT-family decoder-only causal models—general generation/tool use; (2) BERT-family encoder-only masked models—representation/classification; (3) T5-family encoder–decoder denoising models—conditional sequence-to-sequence tasks. A valid three-LLM answer can instead name current systems, but must state objective, architecture/access, context/tool modality, and intended use with a dated source.

Final answer: GPT (decoder-only generation), BERT (encoder-only understanding), T5 (encoder–decoder transformation) form three clearly differentiated families.
Check. BERT is a language model but not normally an autoregressive chat generator; labels should match architecture.
🔴 Exam-core

SSM slides pp.30–77 · derive state, discretize, unroll

9-presentation-ssm.pdf pp. 30–77

(1) State form of mass–spring–damper

mÿ+cẏ+ky=x. Let h₁=y, h₂=ẏ. Then ḣ₁=h₂ and ḣ₂=−(k/m)h₁−(c/m)h₂+(1/m)x.

A=[[0,1],[−k/m,−c/m]], B=[[0],[1/m]], C=[1,0]

(2) Discretize

For zero-order-held input over Δ: Ā=eΔA, B̄=∫₀ΔeτAB dτ. If A invertible, B̄=A⁻¹(Ā−I)B.

(3) Unroll

With h₋₁=0: h₀=B̄x₀; h₁=ĀB̄x₀+B̄x₁; h₂=²B̄x₀+ĀB̄x₁+B̄x₂. Multiply C to obtain the convolution coefficients.

Final result: K₀=CB̄, K₁=CĀB̄, K₂=C²B̄,…; y is the causal convolution of K with x.
Check. Setting A=0 gives Ā=I and B̄=ΔB by the integral form, even though the A⁻¹ shortcut is unavailable.
🔴 Exam-core

SSM slides pp.93–97 · diagonalization and kernel calculation

9-presentation-ssm.pdf pp. 85–97

If A=VΛV⁻¹, then Ak=VΛkV⁻¹. Transform B′=V⁻¹B and C′=CV. Each diagonal mode evolves independently: Kk=Σᵢ C′ᵢ λᵢkB′ᵢ. This replaces repeated dense matrix powers with elementwise powers of eigenvalues.

Final result: diagonalization reduces the k-th kernel coefficient to a sum of scalar geometric modes. Stability in discrete time requires |λᵢ|<1 for decaying modes.
Check. Reconstruct K₀: ΣᵢC′ᵢB′ᵢ = CVV⁻¹B = CB.
🟠 Exam-practical

RAG slides prompts · nearest neighbors, key design question, debugging

10-presentation-rag.pdf pp. 15, 22, 27–30

p.15: find k nearest neighbors

Embed query q with the same model as chunks, score cosine similarity q·d/(‖q‖‖d‖), retrieve top-k. For normalized vectors this is just dot product. Use HNSW for fast approximate search at scale.

p.22: key design question

Retrieve the smallest set of chunks that jointly contains sufficient evidence while fitting the model context. Tune chunk boundaries/overlap, k, filters, hybrid dense+sparse search, and reranking on labeled queries.

p.27: answer/debug

Log query, candidates, scores, reranked set, final context, answer, and cited spans. If gold evidence absent from candidates, retrieval failed; if present but unused/misrepresented, generation/grounding failed.

Final answer: normalized dot-product top-k supplies candidates; rerank and assemble evidence; evaluate retrieval recall and grounded answer quality separately.
Check. An eloquent answer without retrieved support is not a successful RAG result.
One-page companion

Exam toolkit: formulas, diagrams, and error checks

No separate formula sheet was supplied. This is an independently assembled cheat-sheet companion derived from repeated course evidence—compress it onto the permitted handwritten A4 page in your own notation.

Probability & loss

P(sequence)=∏ conditional probabilities
NLL=−Σln ptrue
PPL=exp(NLL/N)
CE=−ln ptrue
softmax(z)ᵢ=ezᵢ−max z/Σezⱼ−max z

Attention

Q=XWQ, K=XWK, V=XWV
S=QKᵀ/√dₖ → n×n
A=row-softmax(mask(S)) → n×n
Y=AV → n×dᵥ
MHA=Concat(heads)Wᴼ

Transformer block

X←Embed(ids)+PE
X←LN(X+MHA(X))
X←LN(X+FFN(X))
logits=XWU; p=softmax(logits)
PE(pos,2i)=sin(pos/100002i/d)

RNN/LSTM

hₜ=tanh(Wxₜ+Uhₜ₋₁+b)
cₜ=fₜ⊙cₜ₋₁+iₜ⊙ĝₜ
hₜ=oₜ⊙tanh(cₜ)
Gate values ∈(0,1)

SSM

ḣ=Ah+Bx; y=Ch+Dx
hₖ=Āhₖ₋₁+B̄xₖ
K=[CB̄,CĀB̄,C²B̄,…]
train: convolution; infer: recurrence

Instant checks

Inner matrix shapes match.
Probability rows sum to 1.
Residual operands have equal shape.
Causal future weights are 0.
Gram matrices are symmetric.
Lower PPL requires same tokenization.

Five diagrams to reproduce from memory

  1. Markov graph: context nodes, directed probabilities, normalized outgoing edges.
  2. LSTM cell: f/i/candidate/o gates, additive cell-state highway.
  3. Attention: Q,K → scores → mask/softmax; weights with V → output.
  4. Transformer decoder block: embeddings/position, masked MHA, residual+norm, FFN, residual+norm, logits.
  5. SSM/RAG: recurrence↔convolution; and offline index vs online query pipeline.
Reference

Glossary

Autoregressive
Factorizes a sequence left-to-right and predicts the next token from a prefix.
Bi-encoder
Embeds query and document separately for fast similarity search.
Cross-encoder
Jointly processes a query-document pair for slower but stronger reranking.
Embedding
A learned dense vector representation indexed by or contextualized for a token.
Epoch
One pass through the training dataset.
Hidden state
A learned summary carried across sequence steps.
HNSW
Hierarchical Navigable Small World graph for approximate nearest-neighbor search.
KV cache
Stored key/value projections from earlier generated tokens, avoiding recomputation.
LayerNorm
Per-token feature normalization with learned scale and shift.
Logit
An unnormalized class score before softmax.
MLM
Masked language modeling: predict selected corrupted tokens using bidirectional context.
Perplexity
Exponentiated mean negative log-likelihood; effective branching factor under fixed evaluation conditions.
Residual
An identity shortcut that adds a block input to its transformed output.
State space
A latent dynamical representation whose state evolves under inputs and emits outputs.
Token
A discrete unit produced by a tokenizer; may be a word, subword, byte, or punctuation mark.
Teacher forcing
Training with the true prior tokens as decoder inputs rather than sampled predictions.
Evidence & provenance

Source traceability and coverage

All physical pages are preserved because several decks use incremental-reveal exports. The full machine-auditable map is alongside the extraction workspace in .studybook_work/source_map.json; the table below is the human index.

SourceReviewedBook destinationsStrongest evidence
1-presentation-intro.pdf14/14 pagesScopecourse flow pp.13–14
2-presentation-markov.pdf43/43Markov, solutionsgraphs pp.3–24; scaling/perplexity pp.34–40
3-presentation-word-embedding.pdf48/48Embeddings, solutionsTF–IDF pp.24–31; Word2Vec pp.32–43
4-presentation-rnn.pdf25/25RNN/LSTMsoftmax pp.12–15; recurrence/gates pp.16–24
5-presentation-attention.pdf24/24Attentionencoder–decoder/attention pp.10–23
6-presentation-architecture.pdf122/122Transformer, solutionsnumerical derivations pp.2–5, 27–119
7-presentation-technique.pdf90/90Modern techniquesend-to-end pp.3–34; RoPE/GQA pp.49–69; MoE pp.79–89
8-presentation-models.pdf107/107Families/adaptationMLM pp.14–33; MoE pp.55–84; training/LoRA pp.85–107
9-presentation-ssm.pdf130/130SSM/Mamba, solutionsderivation pp.30–77; HiPPO/Mamba pp.85–124
10-presentation-rag.pdf32/32RAG, solutionsretrieval and pipeline pp.11–30
11-pres-ai-assisted-programming.pdf29/29AI programmingfailure/risk/workflow pp.15–29
7 notebooks, including 2 checkpoints115/115 cellsComplete solutionsall Tasks, Questions, code, and visible outputs
6 Python filesall linesComplete solutionssupport code and four Transformer practicals
2 PNG + 1 draw.ioallMarkov/embeddingssimple graph and log plot
README.txt + practical README.mdall linesscope/solutionsexam constraints and task definitions
2 user-supplied mock-exam photographsboth full-resolution imagesMock cheat sheettopic coverage and independently corrected calculations

Primary technical references used for correction checks

Integrity ledger

Corrections, discrepancies, and limits

Source locatorObserved issueResolution in this book
Architecture pp.32–34The displayed MHA result does not equal the displayed concatenated heads multiplied by the displayed Wᴼ.Recomputed first row as [0.46,0.50,0.40,0.37], not [0.39,0.45,0.38,0.31]; full corrected matrix appears on Cheat Side C.
Architecture pp.2–5AAᵀ off-diagonal printed as 7.Recomputed as 5; symmetry, trace, and NumPy confirm.
6-practical §4Comments reverse attention-weight and attention-output shapes.Weights n×n; output n×dₖ.
6-practical §8def MyTransformer(nn.Module) is invalid class syntax.Complete solution uses class.
Markov pp.34–36 / Task 7“trigram state” and combination-based transition counts mix conventions and overcount allowed directed transitions.Standard context-state and literal tuple interpretations both stated with storage.
Markov Tasks 8–9Whether the initial word is predicted changes N and PPL.Use the slide p.39 convention including the initial probability; alternate shown.
Embeddings p.29Course IDF is a nonstandard smoothed base-10 form.Exercise uses it exactly and reports the unsmoothed alternative separately.
RNN slide p.18“No limited context problem” overstates vanilla RNN ability.Clarified: formal recurrence is unbounded, but fixed state and gradients limit practical memory.
RNN notebookConstructor call omits required textfile.Corrected instantiation supplied.
Word2Vec notebookIgnored api.load result; fictitious local load; UMAP uses fit rather than fit_transform.Corrected reproducible pipeline supplied.
Bidirectional LSTM notebookBidirectionality can be mistaken for causal access to future output tokens.Clarified its use over known prefixes and limitation for standard generation.
SSM pp.42–63Laplace derivative wording and discretization shorthand are misleading.Separated Laplace derivative, z-delay, exact zero-order hold, and Tustin formulas.
Practical READMEPart 3 says Part 4 covers LoRA; supplied Part 4 is MoE.MoE practical solved; LoRA covered from model slides, not mislabeled as the practical.
Notebook experimentsCorpora and heavyweight pretrained downloads are not bundled.Complete corrected code, deterministic calculations, shape invariants, and evaluation contracts supplied; no fabricated training metrics.
Authorship status. Explanations, diagrams, worked answers, code repairs, priorities, and discrepancy judgments in this studybook are independently generated study aids. They are not instructor-endorsed. Instructor-provided material is cited by exact filename and page/cell.
Mock-exam evidence · corrected copy-ready blueprint

Your three-page A4 cheat sheet

Sides A–B mirror the topic coverage in the two photographed mock-exam sheets. Side C adds the highest-yield by-hand calculations from the supplied practicals and worked lecture exercises. All arithmetic and notation are independently checked.

Five corrections before you copy anything: for vocabulary 1000 and six-token context, dense context states are 1000⁶=10¹⁸, not 10⁶; synonyms should be nearby rather than identical vectors; sinusoidal PE uses base 10000; exact “cat” and “cats” are different tokens without stemming; and the photographed GQA score −0.33/√2 is −0.2333, not approximately −0.289.
The course note says one handwritten A4 sheet. Treat this as a copying guide; use Side C as an additional physical page only if the professor explicitly permits it, otherwise copy its highest-yield blocks into your remaining allowed space.
GENERATIVE AI · SIDE AMarkov · TF–IDF · embeddings · PE · attention · RoPE
Rule: define symbols → shapes → order → substitute → check

0 · Notation spine write first

V=vocabulary size; n=sequence length; d=model width; h=query heads; dₖ=d/h normally; B=batch size.

X: n×d   W: d×r   XW: n×r
(m×n)(n×p)→m×p

Exam sequence: asked quantity → givens → symbol meanings → last formula → missing intermediates → numbers → range/shape check.

1 · Markov probability + state explosion

P(w₁…wₙ)=∏ₜP(wₜ|historyₜ)
P(next=v|h)=count(h,v)/Σᵤcount(h,u)

Order-k assumption: next token depends only on last k tokens.

Solved: P(“You like tea”)=¼·½·¼=1/32.

Dense maximum: contexts=Vᵏ; context→next transitions=Vᵏ⁺¹.

V=1000,k=6: 10¹⁸ contexts, 10²¹ directed next-token transitions. Do not use n(n−1)/2; that counts unordered graph pairs.

2 · Perplexity (PPL)

PPL=exp[−(1/N)Σₜln pₜ]=(∏ₜpₜ)−1/N

pₜ=probability assigned to the actual token; N=number of predicted tokens in the chosen convention. Lower is better only with same data/tokenization.

Solved “I want coffee”: p=(½,¼,⅛). Product=1/64; N=3; PPL=641/3=4. Missing edge → p=0 → PPL=∞.
Casio: (1÷((1÷2)(1÷4)(1÷8)))^(1÷3)

3 · TF–IDF

TF(t,d)=count(t,d)/|d|
IDF(t)=log₁₀(1+N/df(t)); TFIDF=TF·IDF

|d|=tokens in document; N=documents; df=documents containing exact token t.

Solved: “listened” once in 5-token D₂; appears in 2 of N=3 docs. TF=.2; IDF=log₁₀(2.5)=.39794; TF–IDF=.079588.
Casio: (1÷5)×log(1+3÷2)

4 · Softmax → cross-entropy

m=max(z); pᵢ=ezᵢ−m/Σⱼezⱼ−m
CE(one-hot target)=−ln ptrue
Solved z=[1,0,2,1]: shift by m=2 → [−1,−2,0,−1]. exp sum=1.87109. p=[.196612,.072329,.534447,.196612]. If class 3 is true, CE=−ln(.534447)=.6265.

Checks: pᵢ∈(0,1); Σpᵢ=1; largest logit → largest p; loss≥0.

5 · Tokens → embedding → position

One-hot O: n×V; embedding table Wᴱ: V×d.

X=O·Wᴱ   (n×V)(V×d)=n×d
equivalently: lookup Wᴱ[token_id]

Different words have different rows. Synonyms may learn nearby vectors, never assume equality. Static Word2Vec gives one vector/word; contextual models give one vector/occurrence.

PE(pos,2i)=sin(pos/100002i/d)
PE(pos,2i+1)=cos(pos/100002i/d)
X₀=X+PE
Solved pos=1,d=4: i=0 angle=1; i=1 angle=.01. PE≈[sin1,cos1,sin.01,cos.01]=[.84147,.54030,.01000,.99995]. Use radians.

6 · Matrix multiplication / transpose

Cᵢⱼ=ΣₖAᵢₖBₖⱼ;   (AB)ᵀ=BᵀAᵀ
Solved: A=[[2,4,−1],[3,1,5]] (2×3).
AAᵀ=[[21,5],[5,35]] (2×2).
AᵀA=[[13,11,13],[11,17,1],[13,1,26]] (3×3).

Checks: Gram matrix symmetric; trace(AAᵀ)=trace(AᵀA)=56.

7 · Scaled dot-product attention

Q=XWQ; K=XWK; V=XWV
S=QKᵀ/√dₖ; A=row-softmax(S+mask); Y=AV

Q,K:n×dₖ; S,A:n×n; V,Y:n×dᵥ

One-query solved: q=[1,0], k₁=[1,0], k₂=[0,1], v₁=[2,0], v₂=[0,4], dₖ=2.
S=[1/√2,0]=[.707,0]; softmax=[.670,.330]; Y=.670v₁+.330v₂=[1.340,1.320].

Meaning: Q asks; K is address; V is returned content. Softmax is across keys for each query row.

8 · Causal/padding masks

S′ᵢⱼ=Sᵢⱼ if allowed; −∞ if forbidden
softmax(−∞)=0

Causal: forbid j>i (future). Padding: forbid pad keys. Apply mask before softmax. Purpose: no future leakage; valid autoregressive generation.

9 · RoPE

R(θ)=[cosθ −sinθ; sinθ cosθ]
[x′;y′]=R(θ)[x;y]; θpos,i=pos·10000−2i/d

Rotate paired Q/K coordinates; values unchanged. Dot products depend on relative position gap.

Solved: [x,y]=[1,.5], θ=2 rad. cos2=−.4161,sin2=.9093 → [x′,y′]=[−.4161−.4546,.9093−.2081]=[−.8708,.7012].

Same relative gap → same relative rotation; supports length extrapolation better than fixed learned absolute positions.

GENERATIVE AI · SIDE BMHA · normalization · MLM · retrieval/RAG · GQA
Insurance: LSTM · MoE/LoRA · SSM/Mamba · checks

10 · Multi-head attention (MHA)

For head r: Qᵣ=XWQᵣ, Kᵣ=XWKᵣ, Vᵣ=XWVᵣ; headᵣ=Attention(Qᵣ,Kᵣ,Vᵣ).

H=Concat(head₁…headₕ)   n×(h·dᵥ)
MHA=HWO;   WO:(h·dᵥ)×d → n×d

Concatenate along feature axis, never sequence axis. Different heads can learn different relations.

Shape example: n=3,d=4,h=2,dₖ=dᵥ=2. Each head 3×2; concat 3×4; WO 4×4; MHA 3×4.

11 · Residual + LayerNorm + FFN

R=X+MHA(X)   (same n×d shape)
LN(x)=γ⊙(x−μ)/√(σ²+ε)+β
FFN(x)=W₂φ(W₁x+b₁)+b₂

LN mean/variance are across features of each row/token. Residual preserves signal/gradient path; FFN mixes channels independently per token.

LN solved x=[1,2,3,4]: μ=2.5; σ²=[2.25+.25+.25+2.25]/4=1.25. With γ=1,β=0,ε≈0 → [−1.342,−.447,.447,1.342]. Mean≈0,var≈1.

12 · De-embedding / next token

H:n×d; Wᵁ:d×V; Z=HWᵁ:n×V
P=row-softmax(Z)

For next-token generation use the last sequence row Z[n−1,:], then greedy argmax or sampling. Weight tying may use Wᵁ=(Wᴱ)ᵀ.

Shape: H=5×4,V=6 → Wᵁ=4×6 → logits Z=5×6; last row contains six next-token logits.

13 · BERT / masked language modeling

Select 15% token positions. Of selected:

  • 80% → [MASK] (12% of all tokens)
  • 10% → random token (1.5% overall)
  • 10% → unchanged (1.5% overall)
LMLM=−Σselected positionsln p(true token)

Non-selected labels ignored (often −100). Bidirectional encoder sees left+right context; corruption prevents trivial copying and reduces [MASK] mismatch.

14 · Bi-encoder vs cross-encoder

BiCross
Inputq,d separately[q;d] jointly
Scorecos/dotlearned pair score
Docsprecomputeruntime
Usefast retrievalaccurate rerank

Typical pipeline: bi-encoder top-k → cross-encoder rerank small candidate set.

15 · Similarity + nearest neighbor

cos(q,d)=q·d/(‖q‖‖d‖)
‖q−d‖₂=√Σᵢ(qᵢ−dᵢ)²
Solved: q=[1,1], d₁=[1,0], d₂=[1,1]. cos(q,d₁)=1/√2=.707; cos(q,d₂)=1 → d₂ nearest by cosine.

ANN/HNSW approximates nearest neighbors faster; measure recall@k.

16 · RAG: three phases + diagnosis

  1. Index: documents → chunks+metadata → embeddings → vector index.
  2. Retrieve: embed query → ANN top-k → optional rerank.
  3. Ground/generate: prompt with evidence → answer + citations.

If gold passage absent: retrieval failure. If present but answer wrong: generation/grounding failure. Chunk size/overlap, k, filters, hybrid dense+sparse search are tunable.

17 · Grouped-query attention (GQA)

hq query heads but fewer hkv K/V heads; group size=hq/hkv. Queries stay distinct; K/V cache shared within group.

Example: d=8,hq=4,hkv=2,dhead=2. q₀,q₁ share KV₀; q₂,q₃ share KV₁. MHA caches 4 KV pairs/layer; GQA caches 2 → half KV pairs.
Score correction: q₀=[.1,.7], k₀=[.2,−.5]. q·k=.02−.35=−.33; scaled score=−.33/√2=−.2333.

MHA: hq=hkv. MQA: hkv=1. GQA lies between quality and cache efficiency.

18 · RNN/LSTM insurance

hₜ=tanh(Wₓxₜ+Wₕhₜ₋₁+b)
fₜ=σ(Wf[hₜ₋₁,xₜ]+bf)
cₜ=fₜ⊙cₜ₋₁+iₜ⊙ĝₜ; hₜ=oₜ⊙tanh(cₜ)

f≈1 retain, f≈0 erase. LSTM additive cell path helps gradients. Bidirectional uses future known input; not valid future-token access for causal generation.

19 · MoE + LoRA insurance

MoE(x)=Σe∈TopKgₑ(x)Eₑ(x)
LoRA: W′=W+BA, rank r≪d

MoE: router → top-k experts → normalize selected gates → weighted sum. Risk: expert collapse; use load-balancing/capacity. LoRA freezes W and trains low-rank A,B; fewer trainable parameters/optimizer states.

20 · SSM / Mamba insurance

continuous: ḣ=Ah+Bx; y=Ch+Dx
discrete: hₖ=Āhₖ₋₁+B̄xₖ; yₖ=Chₖ
K=[CB̄,CĀB̄,C²B̄,…]

Training: convolution K*x in parallel. Inference: recurrence with constant state. Mamba makes parameters input-dependent (selectivity) and uses parallel scan. Never mix continuous A,B with discrete Ā,B̄.

21 · fx‑991CW micro-recipes

  • PE/RoPE: radians.
  • TF–IDF: log=base10; PPL/CE: ln and eˣ.
  • Matrix: HOME→Matrix; QKᵀ via MatA×Trn(MatB); max 4×4.
  • LayerNorm: Statistics 1-Variable; use population σx, not sample sx.
  • Use (−) for a negative number; parentheses around negative bases/whole denominators; round final only.

22 · Last 30-second checks

Probability: rows sum 1; loss≥0; PPL≥1.
Shapes: inner dimensions match; residual operands equal.
Mask: before softmax; forbidden weight 0.
Matrix: Gram symmetric.
LN: per-token features; population variance.
Answer: final value + interpretation + source convention.

GENERATIVE AI · SIDE CPRACTICALS · BY-HAND ANSWERS
EXACT=supplied task data · METHOD=same task, checked small numbers

23 · How to write the exam answer USE THIS

Asked: symbol + shape/unit. Given: translate data to symbols. Formula: target on left. Work: substitute one dependency at a time. Answer: boxed value + meaning. Check: one shape/range/sum test.

givens → intermediate(s) → requested value → interpretation

Never invent a learned matrix. If WQ/WK/WV/WO/WU values are absent: give shapes and leave the result symbolic unless identity is explicitly stated.

24 · Markov Task 7: trigram scaling COURSE EXACT

markov-generator.ipynb cell 17; Markov pp.34–36

Given: |V|=10,000; trigram predicts wₜ from two previous words; uint64 ID=8 B.

contexts=V²=10⁸
directed (context,next) entries=V³=10¹²
If storing each 3-ID tuple: 10¹²·3·8 B=24·10¹² B=24 TB (≈21.83 TiB), before counts/pointers. If the wording literally calls every trigram a “state,” state-tuples=10¹²; state the convention.

Check: one more token multiplies dense possibilities by V=10⁴; observed sparse graph is far smaller.

25 · Embedding lookup + position COURSE EXACT

6-practical §§Embedding–PE; Architecture exercise pp.20–24

Given: vocab V=6; “the small cat is outside”; n=5,d=4.

O:5×6; Wᴱ:6×4; E=OWᴱ:5×4
PE:5×4; X⁽⁰⁾=E+PE:5×4

One-hot multiplication selects rows: E[i,:]=Wᴱ[token_idᵢ,:]. PE rows start:

pos0=[0,1,0,1]
pos1≈[.84147,.54030,.01000,.99995]
pos2≈[.90930,−.41615,.02000,.99980]

Exam answer: “Add elementwise; do not concatenate. Vocabulary controls Wᴱ rows; sequence length controls E rows.”

26 · Causal self-attention SLIDE EXACT

Architecture pp.35–37; 6-practical Attention (i–iv)

S=QKᵀ/√2 + M; A=row-softmax(S); Y=AV

With the supplied Q,K (5×2), the causal weight matrix is approximately:

A≈[[1,0,0,0,0],
[.33,.67,0,0,0],
[.33,.33,.33,0,0],
[.25,.25,.25,.25,0],
[.25,.12,.12,.25,.25]]

Supplied v₁=[.5,.1],v₂=[.2,.7],v₃=[.4,.3]. Thus y₁=v₁=[.5,.1]; y₂≈.33v₁+.67v₂=[.30,.50]; y₃≈(v₁+v₂+v₃)/3=[.367,.367].

Checks: each A row sums 1; all j>i weights are 0; S,A are 5×5, Y is 5×2. Building S causes O(n²) attention storage.

27 · Four-head concat + Wᴼ SLIDE CORRECTED

Architecture pp.32–34; 6-practical Attention (vi)

Four supplied heads are each 5×2. Join the same token row across heads:

C=Concat(head₁…head₄):5×8
MHA=CWᴼ; Wᴼ:8×4 → MHA:5×4
C[0,:]=[.1,.2 | .5,.1 | .2,.6 | .3,.3]
First output coordinate:
.1(.1)+.2(.2)+.5(.3)+.1(.1)+.2(.2)+.6(.1)+.3(.3)+.3(.2)=.46.

Verified result from the displayed C and Wᴼ:

MHA=[[.46,.50,.40,.37],
[.37,.40,.30,.38],
[.45,.43,.44,.37],
[.33,.40,.35,.38],
[.49,.38,.42,.42]]

The slide’s displayed 5×4 result is arithmetically inconsistent. Use row×column multiplication above.

28 · Residual → LN → FFN PRACTICAL METHOD

6-practical Residual/Norm + FFN; Architecture pp.38–41

R₁=X⁽⁰⁾+MHA(X⁽⁰⁾); N₁=LNrow(R₁)
F=ReLU(N₁W₁+b₁)W₂+b₂
R₂=N₁+F; H⁽ᴸ⁾=LNrow(R₂)

X,MHA,R₁,N₁,F,R₂,H⁽ᴸ⁾: n×d
W₁:d×dff; W₂:dff×d

Shorthand answer: “Residual operands match; LN uses μ,σ² over the d features of each token row; FFN changes d→dff→d independently per token.”

29 · Unembedding + next token SLIDE EXACT

Architecture pp.42–45; 6-practical De-embedding (i–ii)

H⁽ᴸ⁾:5×4; Wᵁ:4×6; Z=H⁽ᴸ⁾Wᵁ:5×6
znext=Z[4,:]; p=softmax(znext)

Supplied final hidden row h=[.5,.2,.1,0]. Example token-ID 4 logit:

z₄=h·Wᵁ[:,4]=.5(.43)+.2(.59)+.1(.54)+0(.11)=.387.
znext≈[.183,.289,.334,.301,.387,.175]
p≈[.151,.168,.176,.170,.185,.150]
argmax=ID 4 → “mat”.

Wᵁ is learned unembedding/vocabulary projection; it produces V logits. Weight tying may set Wᵁ=(Wᴱ)ᵀ.

30 · Training loss shorthand SLIDE EXACT

Technique walkthrough pp.3–34; Architecture pp.45–46

Lₜ=−ln pₜ(true next token); L=meanₜ Lₜ
If ptrue=.206: L=−ln(.206)=1.579≈1.58.
Teacher forcing: input [the,cat,sat,on] → targets [cat,sat,on,mat].

Greedy argmax can use logits directly; sampling requires softmax probabilities. Training compares every allowed position with its shifted true target.

31 · Bonus: SSM unroll SLIDE DERIVATION

SSM pp.64–77

h₋₁=0; h₀=B̄x₀
h₁=ĀB̄x₀+B̄x₁
h₂=²B̄x₀+ĀB̄x₁+B̄x₂

Multiply by C: K=[CB̄,CĀB̄,C²B̄,…], so y=K*x. Check: power counts delay; newest x has Ā⁰.

Coverage evidence: Sides A–B use two user-provided photographs from a friend who attended the mock exam, visually reviewed on 14 July 2026; the photographs are not instructor-endorsed solutions. Side C uses the cited course notebook cells and lecture pages. All displayed formula values were independently checked against the course sources and the studybook’s numerical verification ledger.

Exam translation layer · Casio fx‑991CW UK

How to turn a question into a formula sequence

The calculator can execute arithmetic; it cannot decide what the symbols mean or which formula comes first. Use this page to perform that translation explicitly. Do not touch the calculator until steps 1–5 are written on paper.

The governing rule: start with the quantity the question asks for, choose the formula whose left side is that quantity, then work backwards through every right-side symbol you do not yet know. This creates the calculation order.

The seven-line exam worksheet

LineWhat you writeExample: “Find the perplexity of I want coffee”
1 · AskedOne output, with symbol and shape/unit.PPL, one positive dimensionless number.
2 · GivenTranslate every supplied number/object into a symbol.p₁=½, p₂=¼, p₃=⅛; N=3 predicted words.
3 · MeaningWrite a one-line dictionary for every symbol.pₜ is the probability assigned to word t; N is how many such probabilities are averaged.
4 · Target formulaFormula with the asked symbol alone on the left.PPL=(∏ₜpₜ)−1/N.
5 · Dependency orderList intermediate values from givens to target.product p → reciprocal → N-th root.
6 · SubstituteNumbers in parentheses before calculating.PPL=[(½)(¼)(⅛)]−1/3.
7 · CheckRange, shape, sign, normalization, and interpretation.Product=1/64; cube root of 64 is 4; PPL≥1, so plausible.
🔴 Exam-core

How to identify the task family

  • “Probability of a sequence” → multiply conditional probabilities.
  • “Average surprise / loss” → take negative logs; for one-hot cross-entropy select the true class.
  • “Perplexity” → probabilities → log/product → inverse geometric mean.
  • “Distribution from logits” → stabilized exponentials → row sum → divide: softmax.
  • “Representation at position” → embedding lookup → positional encoding → addition.
  • “Attention output” → Q,K,V → scores → mask → row-softmax → weighted values.
  • “One recurrent/SSM step” → old state + current input → new state → output.
  • “Similarity / nearest item” → dot product or cosine for each candidate → largest score.
🔴 Exam-core

How to choose the sequence

Draw a tiny dependency chain. Every arrow means “must be known before.”

givens → intermediate 1 → intermediate 2 → requested output

If an intermediate formula uses another unknown, add another step to the left. Never substitute all formulas into one enormous calculator expression until the chain works on paper.

Exam method derived from the repeated worked calculations in Markov pp.37–39, Architecture pp.48–119, Technique pp.3–34, and SSM pp.30–77.

Symbol dictionaries and required order

Formula familySymbols in plain EnglishCalculation orderFast check
TF–IDF
TF·IDF
count(t,d): occurrences of term t in document d; |d|: token count in d; N: number of documents; df(t): documents containing t.count and |d| → TF; N and df → IDF; TF×IDF.Common-in-all-documents term should have smaller IDF than a rare term.
Softmax
ezᵢ−m/Σezⱼ−m
zᵢ: logit for class i; m: largest logit in the same row; j: denominator index over all classes.find m → subtract m from every logit → exponentiate → sum → divide each exponential by the same sum.All outputs in (0,1), sum≈1, largest logit gets largest probability.
Cross-entropy
−ln ptrue
ptrue: softmax probability at the correct class; “true” is an index, not the value 1.logits → softmax → locate target class → select its probability → −ln.Better correct-class probability means smaller non-negative loss.
Perplexity
exp[−(1/N)Σln pₜ]
t: predicted-token position; pₜ: probability assigned to the actual token; N: number of predicted tokens included.collect one pₜ per target → ln each → sum → divide by N → negate → exp.A zero probability gives infinite unsmoothed PPL; lower is better only under the same tokenization.
Matrix product
Cij=ΣₖAikBkj
i: output row; j: output column; k: paired position across A’s row and B’s column.check inner shapes → choose output cell (i,j) → multiply paired entries → sum → repeat cells.(m×n)(n×p)→m×p. A Gram matrix AAᵀ is symmetric.
Attention
softmax(QKᵀ/√dₖ)V
n: tokens; d: model width; dₖ: key/query width; Q: what each token seeks; K: what each token offers as an address; V: content returned.XWQ/XWK/XWV → QKᵀ → ÷√dₖ → add mask → row-softmax → weights·V.scores/weights n×n; output n×dᵥ; each weight row sums to 1.
Position encodingpos: position starting at 0; j: embedding column; i=⌊j/2⌋: frequency-pair index; d: total embedding width.determine even/odd j → compute i → exponent 2i/d → denominator → angle → sin if even, cos if odd.At pos=0, every sin entry is 0 and every cos entry is 1.
LayerNormxᵢ: one token’s feature i; d: feature count; μ: that token’s feature mean; σ²: population variance; ε: small stability constant; γ,β: learned scale/shift.μ → deviations → squared deviations → average for σ² → add ε → square root → normalize each xᵢ → apply γ,β.Before γ,β, normalized feature mean≈0 and population variance≈1.
Discrete SSM
hₖ=Āhₖ₋₁+B̄xₖ; yₖ=Chₖ
k: time step; hₖ₋₁: old state; xₖ: current input; Ā: state transition; B̄: input injection; C: readout. Bars mean already discretized.Āhₖ₋₁ → B̄xₖ → add for hₖ → Chₖ for yₖ → carry hₖ forward.Never mix continuous A,B with discrete Ā,B̄ in one recurrence.
Cosine similarityq,d: query/document vectors; q·d: paired-product sum; ‖q‖,‖d‖: Euclidean lengths.dot product → each squared-length sum → roots → multiply lengths → divide → repeat candidates → rank.For nonzero real vectors, result lies in [−1,1].

fx‑991CW setup: do this before practice

General arithmetic

  1. HOME → Calculate.
  2. Use SETTINGS → Input/Output → MathI/MathO so fractions, roots, and powers look like the written formula.
  3. Use the FORMAT menu to switch an exact fraction/root result to Decimal.
  4. Use parentheses around every substituted numerator, denominator, and negative base.
  5. For a negative number use the calculator’s (−) sign, not the subtraction operator. Casio explicitly warns that −2² and (−2)² differ.

Angles and memory

  1. For positional encoding and course trigonometric formulas, set SETTINGS → Angle Unit → Radian.
  2. The latest result is Ans; continue with it to avoid rounding/retyping.
  3. For a repeated denominator, store the displayed result in a variable through the variable list: choose A= → Store, then recall A.
  4. Keep full precision internally; round only the reported final answer unless the question says otherwise.

Calculator walkthrough 1: perplexity

Question data: p=[½,¼,⅛], N=3. Paper sequence: product → inverse → cube root.

Calculate app entry:

(1 ÷ ((1÷2) × (1÷4) × (1÷8))) (1÷3)

Press EXE. Result: 4. A log-form entry gives the same result:

e−((ln(1÷2)+ln(1÷4)+ln(1÷8))÷3)

Which form should you use? Direct product is quickest for three clean fractions. Log form is safer for many tiny decimal probabilities. The alternate eˣ function is printed above ln; insert it with SHIFT then ln if using the keypad.

Calculator walkthrough 2: TF–IDF

Question data: “listened” occurs once in a 5-token document; N=3 documents; df=2. The course uses log₁₀(1+N/df).

Paper sequence: TF=1/5; IDF=log₁₀(1+3/2); multiply.

(1÷5) × log(1 + 3÷2)

In Calculate, the ordinary log function is base 10; press EXE → 0.079588…. Do not use ln here—the base is part of the course formula.

Calculator walkthrough 3: softmax and cross-entropy

Question data: z=[1,0,2,1]. First write m=max(z)=2. Then shifted logits are [−1,−2,0,−1].

  1. Enter the common denominator e^(−1)+e^(−2)+1+e^(−1) → EXE. It is about 1.871094.
  2. Store this result as variable A.
  3. Evaluate e^(−1)÷A, e^(−2)÷A, 1÷A, e^(−1)÷A.

Result: [0.196612, 0.072329, 0.534447, 0.196612]. Add the four rounded values: approximately 1.

If class 3 is correct, select ptrue=0.534447 and enter (−)ln(0.534447) → loss ≈0.6265. If ptrue=0.206 in another task, (−)ln(0.206)≈1.58.

Calculator walkthrough 4: positional encoding

Question: pos=1,d=4. For columns j=0,1 use pair i=0 and angle 1/10000⁰=1. For j=2,3 use i=1 and angle 1/100002/4=0.01.

  1. Confirm the top indicator shows Radian.
  2. Enter sin(1) → 0.84147098.
  3. Enter cos(1) → 0.54030231.
  4. Enter sin(1÷10000^(2÷4)) → 0.00999983.
  5. Enter cos(1÷10000^(2÷4)) → 0.99995000.
PE(1,:)≈[0.84147, 0.54030, 0.01000, 0.99995]. Pair check: sin²(angle)+cos²(angle)≈1.

Calculator walkthrough 5: matrices and attention scores

The fx‑991CW Matrix app supports matrices up to 4×4—enough for the course’s small hand examples, not real model tensors.

  1. HOME → Matrix. Open the matrix variable list.
  2. Define MatA; choose its Rows and Columns; enter values row by row. Define MatB similarly.
  3. For AAᵀ, insert MatA, multiplication, then CATALOG → Matrix → Matrix Calc → Transposition and place MatA inside the transposition.
  4. For attention QKᵀ/√dₖ, store Q as MatA and K as MatB; calculate (1÷√dₖ)×MatA×Trn(MatB).
  5. Copy each result row to paper. Softmax must then be performed row by row in Calculate; the Matrix app does not choose the softmax axis for you.

For A=[[2,4,−1],[3,1,5]], calculate MatA×Trn(MatA) → [[21,5],[5,35]]. Then calculate Trn(MatA)×MatA → the verified 3×3 result in the solution manual.

Calculator walkthrough 6: LayerNorm with Statistics

For one token vector only, you may use HOME → Statistics → 1-Variable. Enter its d feature values as observations.

  1. Read the mean ; this is μ.
  2. Read the population standard deviation σx, not sample sx. LayerNorm divides variance by d.
  3. For each feature enter (xᵢ−x̄)÷√(σx²+ε).
  4. If γ and β are supplied, finish with γᵢ×normalizedᵢ+βᵢ.

Use Statistics only for the arithmetic. On paper you must still state that normalization is across the features of one token, not across tokens or the batch.

What the calculator cannot decide

  • It cannot tell whether N means tokens, documents, classes, or a matrix dimension. You must define it from the question.
  • It cannot know the softmax axis. “Row-softmax” is a reasoning decision.
  • It cannot know whether A means a learned matrix, a continuous SSM matrix, a discretized Ā, or calculator variable A.
  • It cannot perform genuine model-size tensors; Matrix is limited to 4×4.
  • It cannot repair a wrong formula sequence. A numerically precise answer to the wrong target is still wrong.
  • The Equation/Solver app is useful only when the requested variable is genuinely implicit. Do not use it instead of showing a derivation the exam asks for.

Thirty-second pre-EXE checklist

Meaning
Have I defined every symbol in this question, not from memory alone?
Order
Does every intermediate exist before I use it?
Shape
Do matrix inner dimensions and residual shapes match?
Mode
Radians? Base-10 log or ln? Population or sample variance?
Entry
Parentheses around fractions, negative values, powers, and whole denominators?
Check
Probability sum, allowed range, symmetry, sign, and interpretation?

Calculator operations verified against Casio’s official fx‑570CW/fx‑991CW online user guide: Calculator Apps, Matrix Calculations, Function Analysis, Memory Functions, Result Format, and Calculation Priority Sequence. Menu labels may be faster and less error-prone than memorizing icon positions.