LLMs, Transformers and GPT
Part 1: Foundations
Tokens, embeddings, attention, context window, sampling, hallucinations.
On this page (29 sections)
- 1.1 What Generative AI is and how an LLM thinks
- 1.2 Transformer, attention and context
- 1.3 Model types and generation behaviour
- 1.4 Smaller, smarter and multimodal models
- 1.1 What Generative AI is and how an LLM thinks
- 1. What is Generative AI?
- 2. Machine Learning, Deep Learning and Neural Networks
- 3. What is an LLM? Next-Token Prediction
- 4. Tokens and Tokenization (BPE)
- 5. Embeddings
- 1.2 Transformer, attention and context
- 6. Transformer Architecture Overview
- 7. Attention and Self-Attention
- 8. Context Window and Its Limits
- 9. Pre-training, Post-training, Instruction Tuning, RLHF and DPO
- 10. Parameters, Model Size and Scaling Laws
- 1.3 Model types and generation behaviour — detailed notes
- 11. Decoder-only vs encoder-only vs encoder-decoder
- 12. Sampling: temperature, top-p, top-k and seed
- 13. Hallucinations and how to reduce them
- 14. Mixture of Experts (MoE)
- 15. KV cache, inference, latency, throughput and TTFT
- 1.4 Smaller, smarter and multimodal models — detailed notes
- 16. Quantization, distillation and small models
- 17. Reasoning models and test-time compute
- 18. Multimodal models: vision, audio and video
- 19. Diffusion models and image generation
- 20. Knowledge cutoff, training data, bias and limits
- Part 1 cheat sheet — interview answers
Like I'm 5: A huge library of text taught a very fast reader to guess the next word. Do that guess again and again and you get full answers. This part explains how that reader works inside.
1.1 What Generative AI is and how an LLM thinks
Topics to cover, in this order:
- What is Generative AI (vs traditional ML, generative vs discriminative)
- Machine learning, deep learning and neural networks in plain words
- What is an LLM and how it predicts the next word
- Tokens and tokenization (BPE) and why cost is per token
- Embeddings: meaning turned into numbers
1.2 Transformer, attention and context
Topics to cover, in this order:
- Transformer architecture overview
- Attention and self-attention
- Context window and its limits (lost in the middle)
- Pre-training, post-training, instruction tuning, RLHF and DPO
- Parameters, model size and scaling laws
1.3 Model types and generation behaviour
Topics to cover, in this order:
- Decoder-only vs encoder-only vs encoder-decoder (GPT vs BERT vs T5)
- Sampling: temperature, top-p, top-k, seed
- Hallucinations: why they happen and how to reduce them
- Mixture of Experts
- KV cache, inference, latency, throughput and time to first token
1.4 Smaller, smarter and multimodal models
Topics to cover, in this order:
- Quantization, distillation and small models
- Reasoning models, chain-of-thought and test-time compute
- Multimodal models (vision, audio, video)
- Diffusion models and image generation
- Knowledge cutoff, training data, bias and the limits of LLMs
1.1 What Generative AI is and how an LLM thinks
1. What is Generative AI?
LIKE I'M 5
Imagine a student who has read millions of books. You ask the student to write a story, draw a picture, or compose a song. The student creates something new using patterns learned from examples.
EXPLAINED SIMPLY
- Generative AI (artificial intelligence that creates new content) produces text, images, audio, video, or code.
- It learns patterns from training data (examples used to teach a model).
- A user provides a prompt (instructions or input). The model generates an output based on learned patterns.
- Common uses include chatbots, code assistants, document summaries, image generation, and speech generation.
- Discriminative AI predicts a label or class, such as spam or not spam. Generative AI creates content, such as an email.
- Use generative AI for language-heavy and creative tasks. Do not use it alone when exact calculations or guaranteed facts are required.
- Use ordinary code, databases, or calculators when they solve the task more reliably.
TRY IT
const userRequest = "Write a birthday message";
const generatedMessage =
"Happy birthday! Wishing you an amazing year!";
console.log(generatedMessage);
- The first line represents a user's request.
- The second line represents generated content.
- A real model creates the response; this example only represents the flow.
JARGON BOX
- AI → Machines performing tasks associated with intelligence.
- Generative → Creating new content.
- Discriminative → Classifying or predicting a label.
- Training data → Examples used to teach a model.
- Model → A trained mathematical system.
- Prompt → Instructions or input given to an AI.
COMPARE WITH LOOKALIKES
| Feature | Generative AI | Predictive or discriminative AI |
|---|---|---|
| Purpose | Creates content | Predicts or classifies |
| Output | Text, images, audio | Labels, scores, predictions |
| Example | ChatGPT | Spam detector |
| Best for | Creative and language tasks | Structured predictions |
INTERVIEW LENS
- If asked “What is Generative AI?” → Explain that it creates new content from learned patterns.
- Mention text, image, audio, video, and code generation.
- Model answer: Generative AI is a branch of AI that creates new content. It learns patterns from training data and generates outputs from user instructions. Common uses include chatbots, image generation, code generation, and document summarisation.
TRAPS
- Generative AI does not always copy and paste training data.
- Generative AI is not always correct.
- It is not limited to text.
- Traditional machine learning remains useful for many prediction tasks.
PRACTICE QUESTION
Question: Would you use Generative AI for email spam detection?
Model answer: I would first consider a classification model because spam detection is a classification task. Generative AI may be unnecessary unless language generation or deeper text interaction is also required.
Weak answer: I would use ChatGPT because it is more powerful.
ONE-LINE RECAP
Generative AI learns patterns from data and uses them to create new content.
2. Machine Learning, Deep Learning and Neural Networks
LIKE I'M 5
Imagine teaching a child to identify mangoes. You show many mangoes and explain their features. Eventually, the child recognises mangoes from examples.
EXPLAINED SIMPLY
- Machine Learning (ML) teaches computers to learn patterns from data instead of relying only on manually written rules.
- Deep Learning (DL) is a subset of ML. It uses neural networks with multiple processing layers.
- A neural network is a mathematical system made from connected units called neurons.
- Each connection has a weight (a learned numerical value). A bias (an additional learned value) can also affect the calculation.
- During training, inputs pass through the network and produce a prediction.
- The prediction is compared with the expected answer. A loss function measures the error.
- Backpropagation calculates how network parameters contributed to the error.
- An optimiser, such as Adam, updates parameters to reduce that error.
- An epoch means one complete pass through the training dataset.
- ML often works well with structured data. Deep Learning is useful for complex patterns in images, speech, and language.
- Deep Learning often needs more data and computing power. More layers do not automatically mean better results.
TRY IT
const inputs = [2, 3];
const weights = [0.5, 0.8];
const bias = 1;
const output =
inputs[0] * weights[0] +
inputs[1] * weights[1] + bias;
console.log(output); // 4.4
- Inputs contain two values.
- Weights control each input's influence.
- Bias adds another adjustable value.
- The calculation multiplies each input by its weight, then adds the results and bias.
- A real neuron may also apply an activation function.
JARGON BOX
- ML → Learning patterns from data.
- DL → Machine learning using deep neural networks.
- Neuron → A mathematical processing unit.
- Weight → A value controlling input influence.
- Bias → An adjustable additional value.
- Backpropagation → Calculates how parameters contributed to errors.
- Gradient descent → Updates parameters to reduce errors.
- Optimiser → Algorithm that updates model parameters.
- Epoch → One complete pass through training data.
- Activation function → Adds non-linear behaviour to a network.
COMPARE WITH LOOKALIKES
| Feature | Machine Learning | Deep Learning |
|---|---|---|
| Data | Often works with smaller datasets | Often benefits from large datasets |
| Features | Often manually selected | Can learn features automatically |
| Computing | Usually lower requirements | Often higher requirements |
| Example | House-price prediction | Image recognition |
INTERVIEW LENS
- If asked “How are ML and Deep Learning related?” → Say Deep Learning is a subset of ML.
- Model answer: Machine Learning allows computers to learn patterns from data. Deep Learning is a subset that uses neural networks with multiple layers. It can learn complex features but often needs more data and computing power.
TRAPS
- Deep Learning is not separate from Machine Learning.
- Neural networks are mathematical systems, not actual human brains.
- More layers do not guarantee better performance.
- Training and inference are different operations.
PRACTICE QUESTION
Question: Why does Deep Learning work well for image recognition?
Model answer: Deep Learning can learn hierarchical image features. Earlier layers may detect edges, while later layers combine patterns into objects. This reduces the need to manually define every visual feature.
Weak answer: Because deep learning has more layers.
ONE-LINE RECAP
Machine Learning learns patterns, while Deep Learning uses multiple neural-network layers to learn complex patterns.
3. What is an LLM? Next-Token Prediction
LIKE I'M 5
Imagine someone saying, “The sun rises in the...” You expect “east.” An LLM learns to predict likely next tokens from the tokens it has already received.
EXPLAINED SIMPLY
- An LLM (Large Language Model) is a neural network trained on large amounts of text and sometimes other data.
- Its common training objective is next-token prediction: predicting the next piece of text.
- Suppose the input is “I drink a cup of”. The model calculates possible next-token scores or probabilities.
- It selects a token using its generation settings. Then it predicts another token using the updated sequence.
- This repeats until a stopping condition is reached, such as an end token or output limit.
- The model does not necessarily retrieve a complete stored answer. It generates a sequence through repeated predictions.
- This explains why prompts affect answers, why output length affects latency, and why different sampling settings can produce different responses.
- LLMs are useful for chatbots, code assistants, content generation, and document analysis.
- They may need external tools for live information, exact calculations, and database records.
TRY IT
const predictions = {
"I drink a cup of": ["chai", "coffee", "water"]
};
const nextTokens = predictions["I drink a cup of"];
console.log(nextTokens[0]);
- The object represents a pretend prediction table.
- The array contains possible next tokens.
- The final line selects one candidate.
- A real LLM uses neural-network calculations, not a manually written lookup.
JARGON BOX
- LLM → Large Language Model.
- Token prediction → Predicting the next text unit.
- Probability → A numerical measure of likelihood.
- Inference → Using a trained model to generate output.
- Autoregressive → Generating each next token using previous tokens.
- Stopping condition → Rule that ends generation.
COMPARE WITH LOOKALIKES
| System | How it works |
|---|---|
| LLM | Predicts tokens to generate language |
| Search engine | Finds existing documents |
| Database | Retrieves stored structured records |
| Calculator | Performs exact mathematical operations |
INTERVIEW LENS
- If asked “How does ChatGPT generate text?” → Explain repeated next-token prediction.
- Model answer: An LLM is a neural network trained to learn patterns from large datasets. During generation, it predicts the next token using the existing context. It repeats this process until a stopping condition is reached.
TRAPS
- A token is not always a complete word.
- Next-token prediction does not mean the model searches the internet.
- High probability does not guarantee factual correctness.
- A larger model does not guarantee every answer is correct.
PRACTICE QUESTION
Question: Why can the same prompt produce different answers?
Model answer: Multiple next tokens may be plausible. Sampling settings influence which token is selected. Different selections create different continuation paths.
Weak answer: Because AI generates everything randomly.
ONE-LINE RECAP
An LLM generates language by repeatedly predicting the next token using the existing context.
4. Tokens and Tokenization (BPE)
LIKE I'M 5
Imagine breaking a long train into smaller coaches. Instead of treating the whole train as one object, you process its individual coaches. Tokenization breaks text into smaller pieces called tokens.
EXPLAINED SIMPLY
- A token is a piece of text processed by a language model.
- A token can represent a complete word, part of a word, punctuation, or whitespace.
- For example, “unbelievable” might be split into “un”, “believ”, and “able”. Actual splits depend on the tokenizer.
- Tokenization converts text into tokens that the model can process.
- BPE (Byte Pair Encoding) is a tokenisation method used by several tokenizers.
- In simplified BPE training, frequent adjacent units are repeatedly merged into larger units. This builds a reusable vocabulary.
- Tokens matter because context limits, API usage costs, and processing time are often measured in tokens.
- A rough English estimate is around four characters per token, or three-quarters of a word. This is not universal.
- Indian languages, code, unusual names, and mixed-language text can tokenize differently.
- Use the model's tokenizer to estimate production token counts and costs. Do not rely on word counts alone.
TRY IT
const text = "Hello, how are you?";
const illustrativeTokens = [
"Hello", ",", " how", " are", " you", "?"
];
console.log(illustrativeTokens.length); // 6
- The text variable contains the sentence.
- The array shows a hypothetical token split.
- The length property counts its pieces.
- Use the actual model tokenizer for real token counts.
JARGON BOX
- Token → A small piece of text.
- Tokenization → Breaking text into tokens.
- BPE → Byte Pair Encoding.
- Vocabulary → The token units a tokenizer knows.
- Tokenizer → Software that converts text into tokens.
- Input tokens → Tokens sent to a model.
- Output tokens → Tokens generated by a model.
- Token budget → Maximum tokens allocated to a task.
COMPARE WITH LOOKALIKES
| Unit | Example | Meaning |
|---|---|---|
| Character | H | One character |
| Word | Hello | A complete word |
| Token | Hel | A possible text piece |
| Sentence | Hello there! | Multiple words and tokens |
INTERVIEW LENS
- If asked “Why do LLM APIs use tokens instead of words?” → Explain the model's token vocabulary and token-based limits.
- Model answer: LLMs process text as tokens rather than ordinary words. Tokenization provides a reusable vocabulary of words and word fragments. Token counts also help manage context limits and API usage costs.
TRAPS
- One token does not always equal one word.
- Tokenization differs between models.
- Indian languages may use more tokens than expected.
- Spaces and punctuation can affect tokenization.
- Estimate production costs with the correct tokenizer.
PRACTICE QUESTION
Question: Your application sends 10,000 words to an LLM. How would you estimate token usage?
Model answer: I would use the tokenizer for the selected model. I would include message formatting and prompt instructions. I would also reserve room for expected output tokens.
Weak answer: 10,000 words always equal 10,000 tokens.
ONE-LINE RECAP
Tokenization converts text into smaller pieces that LLMs process and generate.
5. Embeddings
LIKE I'M 5
Imagine a kirana shop organising products using coordinates. Milk and curd are placed close together because they are related. Cricket bats and laptops may be placed far apart.
EXPLAINED SIMPLY
- An embedding is a list of numbers representing information, such as text, images, or other data.
- Example: “I love cricket” could map to a vector such as [0.21, 0.75, -0.32]. These numbers are illustrative.
- A vector is an ordered list of numbers. Each number is one dimension.
- An embedding model processes input and produces a vector.
- Related content often receives nearby vectors, depending on the model and training.
- Similarity calculations compare vectors. Common methods include cosine similarity, dot product, and Euclidean distance.
- Embeddings are used for semantic search, RAG, recommendations, duplicate detection, and clustering.
- An embedding model usually creates vectors. A generative LLM usually generates content.
- Embeddings can lose details. Similarity does not guarantee factual relevance.
- Different embedding models may use different vector spaces. Switching models may require re-embedding stored content.
TRY IT
const vectorA = [1, 2, 3];
const vectorB = [2, 4, 6];
const dotProduct = vectorA.reduce(
(sum, value, index) => sum + value * vectorB[index],
0
);
console.log(dotProduct); // 28
- The arrays represent two vectors.
- reduce processes each value in the first vector.
- Each value is multiplied by its matching value.
- The results are added to produce the dot product.
- This is not a complete similarity score.
JARGON BOX
- Embedding → Numerical representation of information.
- Vector → An ordered list of numbers.
- Dimension → One position in a vector.
- Semantic → Related to meaning.
- Similarity → How closely representations match.
- Cosine similarity → Compares vector directions.
- Embedding model → Model that creates embeddings.
- Vector database → Database designed to store and search vectors.
COMPARE WITH LOOKALIKES
| Feature | Embedding model | Generative LLM |
|---|---|---|
| Main purpose | Creates vectors | Generates content |
| Output | Numerical vector | Text or other content |
| Used for | Semantic search | Chatbots and generation |
| RAG role | Finds relevant content | Generates an answer |
INTERVIEW LENS
- If asked “What are embeddings and why are they important in RAG?” → Explain meaning representations and vector retrieval.
- Model answer: Embeddings convert text or other information into numerical vectors. Related meanings can produce vectors that are close in embedding space. RAG uses these vectors to retrieve relevant document chunks before generating answers.
TRAPS
- Embeddings are not simply word IDs.
- Similar vectors do not guarantee identical meanings.
- Dimensions are not necessarily human-readable concepts.
- Changing embedding models may require re-embedding documents.
- Vector similarity alone is not enough for high-quality retrieval.
PRACTICE QUESTION
Question: How would you build semantic search for a company documentation portal?
Model answer: I would split documents into suitable chunks and generate embeddings. I would store vectors with useful metadata. I would embed each query and retrieve similar chunks.
Weak answer: I would store documents as numbers and search those numbers.
ONE-LINE RECAP
Embeddings convert information into numerical vectors so computers can compare meaning and similarity.
1.2 Transformer, attention and context
6. Transformer Architecture Overview
LIKE I'M 5
Imagine a classroom where students read the same paragraph. They exchange information about important words and their relationships. A Transformer uses attention to process relationships between tokens.
EXPLAINED SIMPLY
- A Transformer is a neural-network architecture introduced in the 2017 paper Attention Is All You Need.
- It became the foundation of many modern language models.
- Earlier sequence models often processed text step by step. Transformers allow parallel processing during training.
- A simplified Transformer contains token embeddings, positional information, attention, feed-forward networks, normalisation, and residual connections.
- Token embeddings convert tokens into vectors. Positional information helps represent token order.
- Attention combines information from relevant tokens. A feed-forward network transforms each token's representation.
- Layer normalisation helps stabilise training. Residual connections provide shortcuts for information and gradients.
- Repeated Transformer blocks refine token representations.
- Advantages include efficient parallel training and strong modelling of token relationships.
- Standard attention can become expensive for long sequences. Compute and memory requirements can be high.
- A simplified decoder-only flow is: input tokens → embeddings and positions → Transformer blocks → output scores → next token.
TRY IT
const text = "I love AI";
const tokens = text.split(" ");
const simpleRepresentations = tokens.map((token) => ({
token,
value: token.length
}));
console.log(simpleRepresentations);
- The text is the input.
- split creates a simple list of words.
- map creates a pretend numerical representation for each word.
- This demonstrates a processing flow, not real Transformer embeddings.
JARGON BOX
- Transformer → Neural-network architecture based on attention.
- Architecture → Internal design of a system.
- Encoder → Processes input representations.
- Decoder → Produces output representations.
- Attention → Mechanism for combining token information.
- Feed-forward network → Network that transforms each position's representation.
- Positional encoding → Information representing token positions.
- Residual connection → Shortcut that adds earlier information.
- Layer normalisation → Technique that stabilises network values.
- Parallel processing → Processing multiple items simultaneously.
COMPARE WITH LOOKALIKES
| Feature | RNN | LSTM | Transformer |
|---|---|---|---|
| Processing | Sequential | Sequential | Parallel during training |
| Long-range relationships | Often difficult | Improved | Uses attention |
| Training at scale | Often less parallel | Often less parallel | Highly parallelisable |
| Common modern LLM base | Uncommon | Uncommon | Common |
INTERVIEW LENS
- If asked “Explain the Transformer architecture” → Describe embeddings, attention, feed-forward blocks, and output generation.
- Model answer: A Transformer is a neural-network architecture built around attention mechanisms. It converts tokens into representations and processes them through attention and feed-forward layers. Parallelisable training helped make large language models practical.
TRAPS
- Transformers are not the same thing as GPT.
- GPT is a model family using Transformer-based architecture.
- Attention is only one part of a Transformer block.
- Parallel training does not mean all generation steps happen simultaneously.
- Not every Transformer uses the same architecture.
PRACTICE QUESTION
Question: Why did Transformers become popular for language modelling?
Model answer: Transformers support parallel processing during training. Attention captures relationships between tokens. They also scale effectively with large datasets and computing resources.
Weak answer: Transformers are popular because they are faster.
ONE-LINE RECAP
Transformers use attention and repeated neural-network blocks to process relationships between tokens.
7. Attention and Self-Attention
LIKE I'M 5
Read: “Faizan gave Aaftab his laptop because he trusted him.” You examine surrounding words to understand who “he” refers to. Self-attention performs a mathematical version of information sharing between tokens.
EXPLAINED SIMPLY
- Attention lets a model combine relevant information from different tokens.
- Self-attention lets tokens in the same sequence interact with one another.
- It uses three learned projections: Query (Q), Key (K), and Value (V).
- Query represents what information a token is seeking. Key represents matching information. Value contains information that can be combined.
- The model compares queries with keys to calculate attention scores.
- Softmax converts scores into weights that sum to one. The weights combine the value vectors.
- The common scaled dot-product formula is:
$$ Attention(Q,K,V)=Softmax\left(\frac{QK^T}{\sqrt{d_k}}\right)V $$
- QK transpose compares queries and keys. The square-root scaling controls score magnitude. Softmax produces weights. Multiplication by V combines information.
- Multi-head attention performs several attention calculations in parallel. Their outputs are combined.
- Causal attention prevents a token from accessing future tokens during autoregressive generation.
- Standard full self-attention has quadratic computation with sequence length. Longer sequences can require much more compute and memory.
TRY IT
const scores = [2, 1, 0];
const exponentials = scores.map(Math.exp);
const total = exponentials.reduce((a, b) => a + b, 0);
const weights = exponentials.map(value => value / total);
console.log(weights);
- scores contains pretend attention scores.
- Math.exp converts each score to an exponential value.
- reduce calculates their total.
- Dividing each value by the total produces Softmax weights.
- The weights add up to approximately one. This is not complete self-attention.
JARGON BOX
- Attention → Combining relevant information.
- Self-attention → Tokens interacting within the same sequence.
- Query → What information is being sought.
- Key → Information used for matching.
- Value → Information that gets combined.
- Softmax → Converts scores into weights that sum to one.
- Multi-head attention → Multiple attention calculations in parallel.
- Causal mask → Prevents access to future tokens.
- Attention score → Numerical matching score.
- d_k → Dimension of each key vector.
COMPARE WITH LOOKALIKES
| Concept | Purpose |
|---|---|
| Self-attention | Tokens attend within the same sequence |
| Cross-attention | One sequence attends to another |
| Causal attention | Blocks access to future tokens |
| Multi-head attention | Runs multiple attention heads |
INTERVIEW LENS
- If asked “Explain self-attention” → Explain Q, K, V, score calculation, and weighted values.
- Model answer: Self-attention allows each token to combine information from other tokens in its sequence. It uses Query, Key, and Value vectors to calculate attention weights. Those weights determine how information is combined into updated token representations.
TRAPS
- Query, Key, and Value are learned mathematical projections.
- Attention weights are not necessarily human-style explanations of importance.
- Attention is not human consciousness.
- Causal masking matters for autoregressive generation.
- More heads do not automatically guarantee better results.
PRACTICE QUESTION
Question: Why does a Transformer need Query, Key, and Value?
Model answer: Query and Key calculate how strongly tokens should relate. Value contains the information that gets combined. This lets each token receive information from relevant context.
Weak answer: Query searches, Key stores data, and Value returns a database result.
ONE-LINE RECAP
Self-attention lets tokens exchange information using Query, Key, and Value calculations.
8. Context Window and Its Limits
LIKE I'M 5
Imagine a student taking an exam with limited answer-sheet space. The student cannot write unlimited information on that sheet. An LLM also has a limited context window.
EXPLAINED SIMPLY
- A context window is the maximum amount of tokens a model can process in one context.
- It can include system and developer instructions, user messages, conversation history, retrieved documents, and tool outputs.
- Input and generated output may both count against the applicable context or output limits.
- Example: With a hypothetical 32,000-token limit, 25,000 input tokens leave at most 7,000 tokens under this simplified calculation. Actual API limits can differ.
- If context becomes too large, a request may be rejected, truncated, summarised, or selectively shortened by the application.
- Lost in the Middle describes a finding where some models struggle to use relevant information placed in the middle of long inputs.
- A large context window does not guarantee perfect recall or reasoning.
- Manage context by keeping instructions concise, summarising older messages, removing irrelevant history, retrieving relevant documents, and reserving output capacity.
- Context is not memory. Context is available to the current request. Memory is stored separately and may be retrieved later.
- Use long context for analysing a bounded set of large files. Use RAG for large, changing, or selectively searched knowledge collections.
TRY IT
const contextLimit = 32000;
const inputTokens = 25000;
const outputBudget = contextLimit - inputTokens;
console.log(outputBudget); // 7000
- contextLimit stores a hypothetical limit.
- inputTokens stores consumed capacity.
- Subtraction estimates remaining capacity.
- Real APIs may have separate input and output limits.
JARGON BOX
- Context window → Maximum tokens processed in a context.
- Context budget → Available token capacity.
- Truncation → Removing part of an input.
- Summarisation → Compressing information into fewer words.
- Lost in the Middle → Reduced recall of information in some long inputs.
- RAG → Retrieval-Augmented Generation.
- Token limit → Maximum allowed token count.
COMPARE WITH LOOKALIKES
| Feature | Context window | Memory | RAG |
|---|---|---|---|
| Purpose | Holds current information | Retains information across interactions | Retrieves external knowledge |
| Storage | Request context | Separate storage | External documents or database |
| Main challenge | Token limits | Stale or incorrect memories | Retrieval quality |
| Best for | Current conversation | Personalisation | Knowledge retrieval |
INTERVIEW LENS
- If asked “How do you handle a conversation exceeding the context window?” → Explain context budgeting and retrieval.
- Model answer: I would remove irrelevant history and summarise older messages. For large knowledge collections, I would retrieve relevant information using RAG. I would also reserve sufficient tokens for the model's output.
TRAPS
- Context window is not permanent memory.
- Larger context does not guarantee better answers.
- Input and output both consume capacity, subject to API rules.
- A model cannot automatically access every document in your database.
- Blind truncation can remove important instructions.
PRACTICE QUESTION
Question: Your chatbot becomes slow after 100 conversation messages. What would you do?
Model answer: I would inspect token usage and identify irrelevant history. I would summarise older conversation sections while preserving important facts. I would retrieve external knowledge only when required.
Weak answer: I would simply increase the context window.
ONE-LINE RECAP
The context window limits how much information a model can process in one interaction.
9. Pre-training, Post-training, Instruction Tuning, RLHF and DPO
LIKE I'M 5
Imagine training a student. First, the student reads thousands of books. Then a teacher shows how to answer questions. Finally, the student receives feedback about which answers are better.
EXPLAINED SIMPLY
- Pre-training teaches broad patterns from a large dataset. For many language models, the objective includes predicting missing or next tokens.
- It can teach language structure, common facts, writing patterns, and code patterns when code is included.
- Post-training means additional training after pre-training. It improves behaviour for intended tasks.
- Supervised Fine-Tuning (SFT) trains on examples containing instructions and desired responses.
- Instruction tuning is SFT focused on following instructions. Example: “Explain React hooks simply” paired with a helpful explanation.
- RLHF (Reinforcement Learning from Human Feedback) uses human preferences to improve responses.
- A simplified RLHF process generates candidate answers, collects human comparisons, trains a reward model, and optimises the language model.
- PPO (Proximal Policy Optimisation) is one algorithm used in some RLHF pipelines.
- DPO (Direct Preference Optimisation) trains directly from preferred and rejected response pairs. It does not require a separately trained reward model during its optimisation process.
- Preference training can improve helpfulness and style. It does not guarantee factual accuracy.
- Actual model-training pipelines vary. Not every model uses every stage.
TRY IT
const trainingExample = {
instruction: "Explain APIs simply",
response: "An API lets software systems communicate."
};
console.log(trainingExample.instruction);
console.log(trainingExample.response);
- instruction stores the request.
- response stores the expected answer.
- Examples like these can teach instruction-following behaviour.
- This shows a data format; it does not train a model.
JARGON BOX
- Pre-training → Initial large-scale model training.
- Post-training → Training after pre-training.
- Instruction tuning → Teaching a model to follow instructions.
- SFT → Supervised Fine-Tuning using example answers.
- RLHF → Reinforcement Learning from Human Feedback.
- DPO → Direct Preference Optimisation.
- Reward model → Model that scores responses based on preferences.
- PPO → Proximal Policy Optimisation.
- Preference pair → A preferred answer and a rejected answer.
- Alignment → Making model behaviour better match intended goals.
COMPARE WITH LOOKALIKES
| Technique | Main purpose |
|---|---|
| Pre-training | Learn broad patterns |
| Instruction tuning | Follow instructions |
| RLHF | Learn from human preferences using reinforcement learning |
| DPO | Optimise directly using preference pairs |
INTERVIEW LENS
- If asked “How does a pretrained LLM become a helpful assistant?” → Explain SFT and preference optimisation.
- Model answer: Pre-training teaches general language and knowledge patterns. Supervised fine-tuning teaches the model to follow instructions. Preference methods such as RLHF or DPO can further improve responses according to preferred behaviours.
TRAPS
- Pre-training and post-training are not interchangeable.
- Instruction tuning is not the same as pre-training.
- RLHF does not mean humans approve every response.
- DPO is not simply another name for RLHF.
- Human preference does not guarantee truth.
- Not every model uses the same pipeline.
PRACTICE QUESTION
Question: A pretrained model writes well but ignores user instructions. What would you do?
Model answer: I would consider supervised instruction tuning with high-quality instruction-response examples. I would evaluate instruction-following behaviour. Preference optimisation could further improve response quality.
Weak answer: I would train it on more random internet data.
ONE-LINE RECAP
Pre-training builds general capabilities, while post-training teaches models to follow instructions and produce preferred responses.
10. Parameters, Model Size and Scaling Laws
LIKE I'M 5
Imagine a cricket player learning thousands of batting techniques. Each technique has adjustable details. A neural network also has adjustable numerical values called parameters.
EXPLAINED SIMPLY
- Parameters are learned numerical values inside a neural network. They influence how information flows through the model.
- Weights control input influence. Biases add adjustable values to calculations.
- Model size is often described by parameter count: 1B means one billion parameters; 7B means seven billion.
- Parameter count is not a direct quality rating. Data quality, architecture, training, and evaluation also matter.
- Scaling laws describe observed relationships between model performance and resources such as model size, training data, and compute.
- Increasing resources can improve performance, but returns may diminish. Each extra resource may provide a smaller improvement.
- Model parameters, training data, and compute interact. No single factor determines quality.
- A model's weights must be loaded into memory for inference.
- Approximate raw weight memory = parameter count × bytes per parameter.
- For a hypothetical 7-billion-parameter model: FP32 at 4 bytes is about 28 GB; FP16 at 2 bytes is about 14 GB; INT8 at 1 byte is about 7 GB; 4-bit is about 3.5 GB.
- These are decimal raw-weight estimates. Runtime overhead, activations, and KV cache require additional memory.
- Choose larger models when their quality is needed for complex tasks. Choose smaller models for high-volume, low-latency, or cost-sensitive tasks when quality is sufficient.
TRY IT
const parameterCount = 7_000_000_000;
const bytesPerParameter = 2;
const memoryInGB =
(parameterCount * bytesPerParameter) / 1_000_000_000;
console.log(memoryInGB); // 14
- parameterCount represents seven billion parameters.
- Each parameter uses two bytes in this estimate.
- Multiplication calculates raw bytes.
- Division converts bytes into decimal gigabytes.
- This excludes runtime overhead.
JARGON BOX
- Parameter → A learned numerical value.
- Model size → Often measured by parameter count.
- Weight → Learned connection value.
- Bias → Additional learned value.
- Scaling law → Observed relationship between resources and model performance.
- Compute → Processing resources.
- FP32 → 32-bit floating-point representation.
- FP16 → 16-bit floating-point representation.
- INT8 → 8-bit integer representation.
- Diminishing returns → Each extra resource provides less additional benefit.
COMPARE WITH LOOKALIKES
| Concept | Meaning |
|---|---|
| Parameters | Values learned by the model |
| Training data | Examples used to train the model |
| Compute | Processing power used for training |
| Model size | Often measured by parameter count |
| Context window | Amount of tokens processed in a context |
INTERVIEW LENS
- If asked “Does a larger LLM always perform better?” → Explain that parameter count is only one factor.
- Model answer: No, parameter count alone does not determine model quality. Performance also depends on training data, architecture, optimisation, and inference setup. A smaller specialised model can outperform a larger model on particular tasks.
TRAPS
- More parameters do not automatically mean better answers.
- Model size is not context-window size.
- Parameters are not training examples.
- FP16 does not mean half as many parameters.
- Raw weight memory is not the complete GPU memory requirement.
PRACTICE QUESTION
Question: Would you automatically select a 70B model over a 7B model for customer support?
Model answer: No. I would evaluate both against real support questions. I would compare answer quality, latency, memory, and total cost. I would select the smallest model that meets quality and reliability targets.
Weak answer: Yes, because 70B is ten times bigger and therefore better.
ONE-LINE RECAP
Parameters are learned numerical values, and model size affects capacity, memory, and computing costs.
1.3 Model types and generation behaviour — detailed notes
11. Decoder-only vs encoder-only vs encoder-decoder
LIKE I'M 5
A reader can either understand a page, write the next line, or read one language and rewrite it in another. Transformer families specialise in different jobs.
EXPLAINED SIMPLY
- Encoder-only models read the full input and build useful representations. They are strong at classification, search and understanding tasks. BERT is a familiar example.
- Decoder-only models predict the next token using previous tokens. They are strong at open-ended text generation. GPT-style models use this design.
- Encoder-decoder models encode an input, then decode an output. They suit transformation tasks such as translation and summarisation. T5 is an example.
- Bidirectional attention lets an encoder use words on both sides. Causal attention prevents a decoder from seeing future tokens.
- Choose based on the task, not brand popularity.
COMPARE WITH LOOKALIKES
| Architecture | Sees input | Typical strength | Example |
|---|---|---|---|
| Encoder-only | Both directions | Understand/classify | BERT |
| Decoder-only | Previous tokens | Generate | GPT |
| Encoder-decoder | Input encoder, output decoder | Transform | T5 |
INTERVIEW LENS
Model answer: Encoder-only models build contextual representations, decoder-only models generate autoregressively, and encoder-decoder models map an input sequence to an output sequence.
TRAPS
- GPT is not the only Transformer architecture.
- Decoder-only does not mean it cannot understand prompts.
- These are architecture families, not quality rankings.
ONE-LINE RECAP
Encoder reads, decoder writes, and encoder-decoder transforms.
12. Sampling: temperature, top-p, top-k and seed
LIKE I'M 5
Imagine choosing the next word from a basket. Sampling settings decide how adventurous the choice can be.
EXPLAINED SIMPLY
- The model produces scores for possible next tokens. Sampling converts those scores into a selection.
- Temperature changes how sharp or flat the probability distribution becomes. Lower values make high-probability choices more dominant; higher values increase variety.
- Top-k keeps only the k most likely candidates before sampling.
- Top-p (nucleus sampling) keeps the smallest candidate set whose combined probability reaches p.
- A seed initialises a random-number generator. Where supported, fixed seeds can improve repeatability, but do not guarantee identical output across changing infrastructure or model versions.
- Greedy decoding always chooses the highest-scoring token. It is predictable but can sound repetitive.
- Tune with a fixed evaluation set. Do not assume higher temperature means better creativity.
TRY IT
const candidates = ["chai", "coffee", "water"];
const selected = candidates[0]; // Greedy illustrative choice
console.log(selected);
This toy example picks the first candidate; a real sampler uses model probabilities and settings.
COMPARE WITH LOOKALIKES
| Setting | Controls | Main trade-off |
|---|---|---|
| Temperature | Probability sharpness | Predictability vs variety |
| Top-k | Candidate count | Narrow vs broad choices |
| Top-p | Cumulative probability mass | Adaptive candidate set |
| Seed | Random initial state | Repeatability where supported |
INTERVIEW LENS
Explain that temperature reshapes probabilities, while top-k and top-p restrict the candidate pool.
TRAPS
- Temperature 0 is not universally identical to deterministic execution.
- Top-k and top-p are different filters.
- Sampling cannot repair incorrect knowledge.
ONE-LINE RECAP
Sampling settings control how the model chooses among plausible next tokens.
13. Hallucinations and how to reduce them
LIKE I'M 5
A student who wants to answer every question may confidently invent a page number. An LLM can also produce fluent but unsupported claims.
EXPLAINED SIMPLY
- A hallucination is generated content that is false, fabricated or unsupported by the available evidence.
- LLMs optimise plausible continuation, not guaranteed truth. They can mix facts, fill gaps and invent citations.
- Risk increases with ambiguous prompts, missing context, obscure facts, outdated knowledge and pressure to provide an answer.
- Reduce risk by retrieving trusted sources, supplying relevant context, asking for citations, constraining output, and allowing the model to say “I don't know”.
- Verify important claims with authoritative sources or deterministic systems.
- RAG can ground answers, but retrieval itself can be wrong or incomplete. Citations must be checked against the cited passage.
- For high-impact workflows, add human review and measurable tests.
TRY IT
function answerFromEvidence(question, passages) {
if (passages.length === 0) return "I don't have enough evidence.";
return { question, evidence: passages };
}
This illustrates an abstention rule; it does not itself verify facts.
INTERVIEW LENS
Model answer: Hallucinations occur because language models generate likely sequences rather than querying a truth database. Grounding, retrieval, constrained outputs, verification and abstention reduce risk.
TRAPS
- A confident tone is not proof.
- RAG reduces some hallucinations but does not eliminate them.
- A citation is useful only if it supports the claim.
ONE-LINE RECAP
Treat model output as a proposal that needs evidence, not as automatic truth.
14. Mixture of Experts (MoE)
LIKE I'M 5
Instead of asking every worker to do every job, a manager sends each task to a few specialists.
EXPLAINED SIMPLY
- A Mixture of Experts model contains multiple expert sub-networks and a router that selects which experts process a token.
- In a sparse MoE, only a small subset of experts is activated for each token.
- This can increase total parameter capacity without activating every parameter for every token.
- Total parameters and active parameters are different. Active parameters influence compute per token.
- MoE can improve efficiency at scale, but routing, communication, memory and load balancing add complexity.
- Experts are learned neural networks, not manually assigned human job titles.
COMPARE WITH LOOKALIKES
| Dense model | Sparse MoE |
|---|---|
| Most parameters participate per token | Selected experts participate |
| Simpler routing | Needs expert routing |
| Compute grows with dense parameter use | Compute depends on active experts and system overhead |
INTERVIEW LENS
Describe the router, experts, sparse activation and trade-off between capacity and serving complexity.
TRAPS
- MoE does not mean multiple independent chatbots debate.
- More total parameters do not equal the same active compute.
- Efficient arithmetic does not guarantee cheaper real-world serving.
ONE-LINE RECAP
MoE routes each token through selected expert networks instead of activating one dense network fully.
15. KV cache, inference, latency, throughput and TTFT
LIKE I'M 5
When reading a long book, you keep bookmarks instead of rereading every page from the start. A KV cache stores attention information already computed.
EXPLAINED SIMPLY
- Inference is running a trained model to produce an output.
- Attention creates key and value tensors for tokens. The KV cache stores them so later generation steps can reuse them.
- Without caching, the model may repeat work for earlier tokens. With caching, decoding is usually faster.
- The cache consumes memory and grows with context length, layers, attention heads and concurrent requests.
- Latency is the time a request takes. TTFT is time to first token. Throughput is how much work a system completes per unit time.
- Prefill processes the prompt; decode generates output tokens. They have different compute patterns.
- Batching improves hardware utilisation but can increase an individual request's waiting time.
- Monitor p50/p95 latency, TTFT, tokens per second, queue time, memory and error rate.
TRY IT
const totalSeconds = 2.4;
const outputTokens = 120;
const tokensPerSecond = outputTokens / totalSeconds;
console.log(tokensPerSecond);
This calculates a simple output rate; production metrics must define whether queue and first-token time are included.
COMPARE WITH LOOKALIKES
| Metric | Meaning |
|---|---|
| TTFT | Wait until first output token |
| Inter-token latency | Gap between generated tokens |
| End-to-end latency | Total request duration |
| Throughput | Requests or tokens completed per time |
INTERVIEW LENS
Explain that KV caching avoids recomputing prior attention keys and values, trading memory for lower decoding work.
TRAPS
- KV cache is not a cache of final answers.
- Faster TTFT does not always mean higher total throughput.
- Long contexts and concurrency can exhaust memory.
ONE-LINE RECAP
KV cache reuses previous attention state; serving teams balance latency, throughput and memory.
1.4 Smaller, smarter and multimodal models — detailed notes
16. Quantization, distillation and small models
LIKE I'M 5
Quantization packs numbers into smaller boxes. Distillation teaches a smaller student to imitate a larger teacher.
EXPLAINED SIMPLY
- Quantization stores model weights or activations with fewer bits, such as lower-precision numeric formats.
- It can reduce memory use and sometimes improve speed. Quality may drop, depending on method, model and hardware.
- Distillation trains a smaller student model using outputs or behaviour from a larger teacher.
- Pruning removes selected weights or structures. It is different from quantization.
- Small models can be cheaper, faster and easier to run locally. Large models may perform better on complex tasks.
- Evaluate on your own workload: quality, latency, memory, throughput, hardware and cost.
- Quantization formats and hardware support change quickly. Check current model and runtime documentation.
COMPARE WITH LOOKALIKES
| Technique | What changes | Goal |
|---|---|---|
| Quantization | Numeric precision | Lower memory/compute |
| Distillation | Learned behaviour in a student | Smaller capable model |
| Pruning | Weights or structures | Reduce model size/work |
INTERVIEW LENS
Quantization compresses numeric representation; distillation transfers behaviour from teacher to student. They can be combined.
TRAPS
- Quantization is not simply deleting random weights.
- Smaller does not automatically mean better or worse.
- Benchmark on target hardware, not only a laptop.
ONE-LINE RECAP
Compression methods reduce deployment cost in different ways and must be measured for quality.
17. Reasoning models and test-time compute
LIKE I'M 5
For a tricky maths problem, a student may spend extra time checking steps before giving the answer. Some models use more computation at answer time for difficult tasks.
EXPLAINED SIMPLY
- Test-time compute is additional computation used while answering, rather than only during training.
- Reasoning-oriented models may use extra internal processing, search, sampling or verification to solve harder tasks.
- More compute can improve performance on some reasoning tasks, but increases latency and cost.
- A visible explanation is not necessarily a faithful record of the model's internal computation.
- Separate final-answer quality from explanation quality. Test with known problems and adversarial cases.
- Use reasoning effort where the task benefits: multi-step planning, code analysis or complex maths. Use faster models for simple classification or extraction.
COMPARE WITH LOOKALIKES
| Standard fast generation | Reasoning-oriented execution |
|---|---|
| Prioritises speed | May spend more compute |
| Good for simple tasks | Useful for harder multi-step tasks |
| Lower latency/cost in many cases | Often higher latency/cost |
INTERVIEW LENS
Explain the quality-cost-latency trade-off and why reasoning effort should be allocated by task complexity.
TRAPS
- A long chain of text does not prove correct reasoning.
- More compute does not guarantee a correct answer.
- Do not expose or depend on hidden chain-of-thought; request concise justifications or verifiable steps.
ONE-LINE RECAP
Test-time compute spends extra resources during inference to improve selected difficult tasks.
18. Multimodal models: vision, audio and video
LIKE I'M 5
A person can learn from a picture, a spoken sentence and a video. A multimodal model can work across more than one kind of input or output.
EXPLAINED SIMPLY
- Modality means a type of information, such as text, image, audio or video.
- A multimodal model can accept or produce multiple modalities.
- Images may be split into patches or represented through visual encoders. Audio may be represented as tokens, features or encoded chunks.
- Video combines visual frames with timing; audio-video systems must align information across time.
- Some systems convert everything into a shared representation. Others connect specialised encoders and decoders.
- Use cases include image question answering, transcription, voice assistants, video summaries and accessibility.
- Measure more than text accuracy: OCR quality, timestamps, speaker handling, latency, privacy and modality-specific errors.
INTERVIEW LENS
Describe how modality-specific encoders or token representations let a model process different data types, then explain alignment and evaluation challenges.
TRAPS
- Image understanding can miss small text or visual details.
- Video sampling may miss events between selected frames.
- Audio transcription can confuse names, accents and background speech.
ONE-LINE RECAP
Multimodal models process or generate more than text, but each modality adds its own failure modes.
19. Diffusion models and image generation
LIKE I'M 5
Imagine starting with a noisy TV screen and gradually cleaning it until a picture appears. A diffusion model learns how to reverse a noise process.
EXPLAINED SIMPLY
- A diffusion model is trained around adding noise to data and learning to reverse that process.
- During generation, it starts from noise and repeatedly denoises toward an image or other output.
- Text-to-image systems encode a text prompt and use it to guide generation.
- Many systems use a latent space: a compressed representation that makes generation more efficient.
- A scheduler controls denoising steps. More steps can improve results in some settings but increase time.
- Guidance strength affects how closely generation follows the prompt, with quality trade-offs.
- Diffusion is different from autoregressive text generation, although hybrid systems exist.
COMPARE WITH LOOKALIKES
| Autoregressive generation | Diffusion generation |
|---|---|
| Predicts next token/element | Iteratively denoises |
| Sequential token generation | Repeated refinement steps |
| Common for text | Common for images |
INTERVIEW LENS
Explain forward noising, learned reverse denoising, prompt conditioning and the quality-speed trade-off.
TRAPS
- It does not simply search for a matching stock image.
- More steps do not always improve the image.
- Text rendering and precise spatial relationships can still be difficult.
ONE-LINE RECAP
Diffusion generation turns noise into a sample through learned iterative denoising.
20. Knowledge cutoff, training data, bias and limits
LIKE I'M 5
A student can only know what they learned or can look up. If the textbook ends last year, today's news is missing.
EXPLAINED SIMPLY
- A model's knowledge cutoff is the latest point represented in its training knowledge, but exact dates and update behaviour depend on the model.
- Training data can include public, licensed and human-created examples. The exact mixture may not be fully disclosed.
- Data gaps and social patterns can create bias in outputs.
- Models can fail at exact arithmetic, private information, recent events, rare facts and tasks outside their training distribution.
- Retrieval, tools and fresh data can extend access to current information, but tool results still need validation.
- Protect sensitive data. Check provider retention, training-use, residency and access-control terms before sending private content.
- Use deterministic code for calculations and rules. Use human oversight for consequential decisions.
INTERVIEW LENS
Explain that model knowledge is bounded by training and system access. Retrieval and tools add fresh evidence, but do not remove bias or verification needs.
TRAPS
- A model may have browsing tools even if its base training has a cutoff.
- Cutoff dates differ by model and release.
- Bias is not fixed by one prompt or one filter.
ONE-LINE RECAP
LLMs are powerful pattern learners, not complete, current or unbiased sources of truth.
Part 1 cheat sheet — interview answers
- GPT vs BERT vs T5 → Decoder-only generates; encoder-only understands; encoder-decoder transforms.
- Temperature → Controls probability sharpness and output variety.
- Top-k vs top-p → Fixed candidate count vs cumulative probability mass.
- Hallucination → Fluent output unsupported by evidence; ground and verify.
- MoE → Router selects a subset of expert networks per token.
- KV cache → Reuses prior keys and values to avoid repeated attention work.
- TTFT → Time from request start until first generated token.
- Throughput → Completed tokens or requests per unit time.
- Quantization → Uses lower-precision numbers to reduce memory and possibly compute.
- Distillation → Trains a smaller student using a larger teacher's behaviour.
- Test-time compute → Extra inference work for difficult tasks.
- Multimodal → Processes or generates multiple data types.
- Diffusion → Generates by iteratively denoising noise.
- Knowledge cutoff → Training knowledge has a time boundary; tools can add fresh data.
- Production principle → Evaluate quality, latency, cost, privacy and failure modes on the real workload.