Transformers & Large Language Models
Calculate self-attention from first principles, understand encoder and decoder architectures, trace autoregressive generation and evaluate how foundation models are adapted and deployed responsibly.
Attention(Q,K,V) = softmax(QKᵀ/√dₖ)VBy the End of This Level, You Can
Six Building Blocks of a Transformer
A transformer repeatedly builds context-aware token states and converts them into task outputs or next-token probabilities.
Token and position information represented by a dense vector.
A learned projection used to compare the current token with all legal keys.
A learned projection that determines how relevant a source position is.
The information mixed according to normalized attention weights.
Padding and causal masks enforce the legal information boundary.
Final hidden states are projected to vocabulary scores for prediction.
Transformers Remove the Recurrent Information Bottleneck
Every token can directly compare itself with other permitted positions instead of waiting for a hidden state to carry the entire past.
Processes one step after another. Earlier evidence must survive repeated hidden-state updates, limiting parallel training and making long paths difficult.
Builds pairwise relevance scores so a token can retrieve useful evidence from distant positions in one layer.
Combines multi-head attention, position-wise feed-forward networks, residual paths and normalization into a scalable block.
A recurrent network represents history through a state that is updated step by step. A transformer instead creates a contextual representation for each position by comparing its query with the keys of visible positions and mixing their values. This shortens the path between related tokens and allows all training positions to be processed in parallel. The cost is a dense attention matrix: ordinary self-attention requires memory and computation proportional to the square of sequence length. Transformers therefore improve parallelism and contextual access, but do not make long context free.
In “The student submitted the project because it was complete,” the token “it” can directly attend to “project” instead of relying on many recurrent updates.
Explain both benefits and cost: parallel training and short dependency paths versus quadratic attention and large memory requirements.
Attention weights show what information is mixed inside a layer; they are not automatically a complete causal explanation of the model’s decision.
Embeddings and Positions Create the Initial Token States
Attention alone has no built-in understanding of token order, so positional information must enter the sequence representation.
Split text into vocabulary units and assign IDs.
Look up a learned vector for every token ID.
Add or apply absolute, relative or rotary position information.
Block padding or future tokens before softmax.
Refine contextual states through stacked blocks.
Token embeddings identify learned lexical units, while position mechanisms distinguish “student teaches model” from “model teaches student.” Original transformers add sinusoidal position vectors. Learned absolute embeddings store one vector per position. Relative biases represent distance between query and key positions. Rotary position embeddings rotate query and key features so their dot product contains relative-position information. Padding masks prevent artificial batch padding from receiving attention, and causal masks ensure decoder position t can see only positions at or before t.
Without positions, permuting the same token embeddings would produce the same set of pairwise content comparisons. Position information breaks that symmetry.
When discussing context length, distinguish the tokenizer limit, positional method, trained length distribution, attention memory and serving budget.
A larger advertised context window does not guarantee that a model uses evidence equally well at every location or distance.
Scaled Dot-Product Attention Retrieves Relevant Evidence
Queries and keys calculate relevance; softmax converts scores into weights; values carry the retrieved information.
Q=XWQ, K=XWK, V=XWVLearn different views for seeking, matching and carrying information.
S=QKᵀ/√dₖCompare every legal query–key pair and control dot-product scale.
A=softmax(S+M)Apply the mask, then create a probability distribution per query.
H=AVBuild each contextual output as a weighted sum of value vectors.
For a sequence matrix X, learned matrices WQ, WK and WV create queries, keys and values. The dot product qᵢ·kⱼ measures compatibility between destination position i and source position j. Dividing by √dₖ prevents large-dimensional dot products from driving softmax into saturated, extremely sharp distributions. A mask adds a very negative value to forbidden scores before softmax. Each attention row then sums to one, and multiplying by V forms a context vector using the same weights.
If scaled scores are [1, 0, −1], subtract the maximum and exponentiate: [1, e⁻¹, e⁻²]. After division by their sum, the weights are approximately [0.665, 0.245, 0.090].
Always state tensor shapes: Q,K,V ∈ ℝⁿˣᵈ; QKᵀ ∈ ℝⁿˣⁿ; softmax operates across each key row.
The scaling factor uses the key/query head dimension dₖ, not the full sequence length and not necessarily the total model width.
🧠 Self-Attention Matrix Laboratory
Project token states into queries, keys and values; calculate every scaled score, apply a legal visibility mask, normalize each row and mix the value evidence.
Multi-Head Attention Learns Several Relationship Subspaces
Independent heads can specialize in different compatibility patterns before their outputs are concatenated and projected.
May emphasize nearby modifier, subject or dependency evidence.
May connect pronouns, entities or repeated concepts across positions.
May organize punctuation, delimiters, positions or semantic roles.
Head outputs are joined and mapped back to the model width.
The model width is divided across h heads, so each head usually uses dₖ=dmodel/h features. Every head owns separate query, key and value projections, calculates its own attention matrix and returns a context representation. Concatenating all head results restores the combined width, and an output matrix mixes their evidence. A transformer block then adds a residual connection and normalizes, applies the same feed-forward network independently at every position, and uses another residual-plus-normalization path.
X → attention → add & normalize → feed-forward → add & normalize. Modern variants often apply normalization before each sublayer.
Attention exchanges information across positions; the MLP transforms features within each position using shared parameters.
More heads do not automatically mean more useful diversity. Redundant or inactive heads can occur, and head dimension becomes smaller when width is fixed.
Encoder and Decoder Families Enforce Different Information Flows
The architecture and training objective decide which tokens are visible and which tasks are natural.
all tokens ↔ all tokensBERT-style understandingBidirectional representations support classification, retrieval and token labelling.
past → currentGPT-style generationCausal masking supports next-token prediction and autoregressive completion.
source → targetT5-style transformationAn encoder reads the source; a causal decoder attends to source and generated target tokens.
task-defined visibilityControlled contextSpecial masks combine bidirectional prefixes with autoregressive outputs.
Encoder-only models use bidirectional self-attention because a complete input is available before prediction. Decoder-only models use causal self-attention: token t cannot inspect future ground-truth tokens during training, matching left-to-right generation. Encoder–decoder models separate source understanding from target generation and add cross-attention from decoder queries to encoder keys and values. Model family should follow the information boundary and task, not brand popularity.
For low-latency intent classification, an encoder may be smaller and more natural. For open-ended response generation, a causal decoder is appropriate.
Compare BERT and GPT using visibility mask, objective, output behavior and common downstream use—not only parameter count.
A decoder-only model can perform classification through prompting or fine-tuning, but capability does not imply the best cost, latency or reliability choice.
Large Language Models Learn a Conditional Token Distribution
Pretraining compresses broad statistical regularities into parameters; inference repeatedly converts logits into one selected token.
−Σ log P(xₜ|x<t)Teacher forcing trains each causal position to predict its observed successor.
z = hWᵀThe final contextual state is projected to one score per vocabulary token.
softmax(z/T)Lower T sharpens differences; higher T spreads probability mass.
greedy / Top-K / Top-PA policy filters or selects from the next-token distribution.
During causal pretraining, one shifted sequence supplies many training targets. At inference, the model receives a prompt, produces logits for the next position, applies decoding controls, chooses one token, appends it and repeats. Greedy decoding always chooses the maximum. Top-K retains K candidates. Nucleus sampling retains the smallest probability-ranked set whose cumulative mass reaches p. Temperature rescales logits before softmax; it does not add knowledge. Generation ends at a stop token, stop sequence or length limit.
If logits are [3,2,1], T=0.5 makes them [6,4,2] and the distribution sharper; T=2 makes them [1.5,1,0.5] and less concentrated.
Explain decoding as a probability-policy layer separate from the model parameters and prompt context.
Lower temperature reduces sampling diversity but cannot guarantee factuality, safety or consistency when the underlying distribution is wrong.
⚡ Next-Token Generation & Decoding Workbench
Inspect candidate logits, rescale them, apply greedy, Top-K or nucleus filtering, calculate probabilities and generate a deterministic token sequence step by step.
Adaptation Changes Behavior Without Always Retraining Everything
Choose the smallest reliable intervention that supplies the missing instruction, domain evidence or task behavior.
Provide instructions, examples, constraints and context at inference time. Fast to change but consumes context and may be sensitive to wording.
Offers maximum flexibility but requires large training memory, careful regularization and deployment of a distinct model version.
Learn low-rank updates while keeping the base model frozen, reducing trainable parameters and storage.
Use ranked or preferred responses through supervised and preference-based objectives such as DPO or reward-guided training.
Prompting is appropriate when the model already has the required capability and the missing piece is instruction or temporary context. Retrieval supplies external evidence without encoding it permanently in weights. Supervised fine-tuning teaches examples of desired input–output behavior. LoRA represents a weight update as a product of two smaller matrices, reducing the number of trainable parameters. Preference tuning changes relative response likelihoods, but no adaptation method replaces task-specific evaluation, data governance or safety controls.
Instead of training a d×d update, learn B∈ℝᵈˣʳ and A∈ℝʳˣᵈ with small rank r, then use W′=W+(α/r)BA.
Answer “prompt or fine-tune?” by comparing knowledge freshness, behavior gap, data volume, privacy, cost, latency and evaluation evidence.
Fine-tuning is not a dependable database for frequently changing facts; retrieval is usually easier to refresh and cite.
LLM Quality Requires Task, System and Human Evaluation
Perplexity and benchmark scores cannot alone measure grounding, instruction following, operational reliability or harm.
Measure exact match, F1, ranking quality, groundedness, completeness or rubric scores appropriate to the output.
Use human or model-assisted rubrics with calibration; inspect factual claims, omissions, style and refusal behavior.
Track time to first token, tokens per second, context usage, cost, availability and tool or retrieval failures.
Test prompt injection, data leakage, harmful instructions, bias, over-refusal and high-impact domain boundaries.
Evaluate paraphrases, long context, noisy inputs, multilingual text, adversarial wording and distribution shift.
Log privacy-safe traces, version prompts and models, sample failures, capture feedback and maintain rollback paths.
Perplexity summarizes average next-token surprise on a corpus, but a lower value may not improve a specific product decision. Closed-ended tasks can use deterministic labels and exact metrics. Open-ended outputs need carefully defined rubrics, blinded human review and checks for evaluator bias. A production system must evaluate the complete chain—including retrieval, prompt construction, model, tools, decoding and post-processing—because a correct base model can still fail through stale evidence, truncated context or unsafe orchestration.
Separate unsupported claims caused by missing context, conflicting evidence, prompt ambiguity, model behavior and decoding.
Quantization reduces numerical precision; distillation trains a smaller student; KV caching reuses earlier attention states during decoding.
A fluent response is not evidence of truth. Language-model confidence and verbal certainty are not calibrated factual probabilities.
Transformer Logic Before Libraries
Use these compact procedures for coding, calculation and interviews.
- Project input states into Q, K and V.
- Calculate every query–key dot product.
- Divide scores by √dₖ.
- Add padding or causal mask values.
- Apply row-wise softmax and multiply by V.
- Tokenize the prompt and build legal positions.
- Run the decoder and take the last-position logits.
- Apply temperature and candidate filtering.
- Select or sample one token.
- Append it, reuse KV cache and repeat.
- Freeze the selected base-model matrix W.
- Create trainable low-rank matrices A and B.
- Compute W′x = Wx + (α/r)BAx.
- Backpropagate only through adapter parameters.
- Save, evaluate and version the adapter.
- Define task, users, risks and success rubric.
- Create representative and adversarial examples.
- Freeze model, prompt, tools and decoding settings.
- Measure quality, safety, latency and cost.
- Review failures, set gates and monitor production.
Trace Self-Attention from First Principles
Follow every query, key, dot-product feature, scaled score, softmax denominator and value-weighted context update. The cursor returns through all loops exactly as Python executes.
—Waiting for print(...)
💻 Transformer & LLM Challenges
Attempt each program independently. Workspaces, hints and model programs remain collapsed initially.
Test Your Transformer Reasoning
Select one answer per question. Results show your choice, the correct answer and a clear explanation.
Diagnose LLM Systems Like an AI Engineer
Identify whether failure comes from data, context, model, decoding, tools or the evaluation contract before changing architecture.
Check whether required evidence exists, was retrieved, fits the context window and is actually supported by the output.
Inspect prompt priority, conflicts, truncation, examples, output schema and fine-tuning distribution.
Freeze model version and prompt; inspect temperature, Top-P, seeds, tool results and asynchronous context.
Separate retrieval, prefill and decoding latency; inspect token count, model size, batching, caching and quantization.
Test the complete system boundary with threat models, access control, filtering, red teaming and human escalation.
Reduce unnecessary context and output, route simple tasks, cache safe results and compare smaller task-specific models.
🎤 Transformers & LLMs — Interview Questions
Answer aloud before selecting Show Answer for each detailed explanation.
A Transformer Is a Repeated Evidence-Routing System
Create token and position states.
Score every legal query–key pair.
Mix values using attention weights.
Apply residual and MLP blocks.
Predict, generate and verify.
Large language models become understandable when you separate tokenization, positional information, attention, learned parameters, decoding policy, external evidence and evaluation.
Eight Practical Transformer Habits
Write tensor shapes beside every Q, K, V and attention operation.
Apply masks before softmax and verify that forbidden probabilities become zero.
Separate prompt tokens, generated tokens, context limit and billing units.
Build deterministic evaluation before changing temperature or sampling.
Use retrieval for fresh evidence and adaptation for repeatable behavior.
Evaluate the whole system, not only the base model or one benchmark.
Version the model, tokenizer, prompt, tools, decoding and safety policy together.
Keep a smaller baseline and a safe fallback for cost or availability failures.
Strengthen Transformer Reasoning
Calculate intermediate values and defend each architecture, adaptation and evaluation choice.
- 01
Write the shapes of Q, K, V, QKᵀ and AV for n=8, dmodel=512 and h=8.
- 02
Calculate softmax weights for scaled scores [2,1,0].
- 03
Apply a causal mask to a 4×4 attention matrix.
- 04
Explain why √dₖ scaling stabilizes softmax.
- 05
Compare absolute, relative and rotary position methods.
- 06
Trace one multi-head attention block with two heads.
- 07
Compare pre-norm and post-norm transformer blocks.
- 08
Distinguish encoder-only, decoder-only and encoder–decoder use cases.
- 09
Calculate temperature-scaled probabilities from three logits.
- 10
Apply Top-K and Top-P filtering to one token distribution.
- 11
Explain how KV caching reduces repeated decoding work.
- 12
Calculate trainable LoRA parameters for given d and rank r.
- 13
Choose prompting, retrieval or fine-tuning for four business scenarios.
- 14
Design an evaluation set for a multilingual student-support assistant.
