LLMs & GenAIintermediatemust-know5 min

Pretraining → SFT → RLHF

The three stages that turn a pile of internet text into a helpful assistant.

Building modern production Large Language Models involves three sequential training stages: Pretraining, Supervised Fine Tuning (SFT), and Reinforcement Learning from Human Feedback (RLHF / DPO). Pretraining consumes trillions of web text tokens via next token prediction to build raw world knowledge. SFT fine-tunes base models on high quality instruction prompt-response pairs to learn conversational formatting. RLHF / DPO aligns models with human preferences for helpfulness, honesty, and safety.

LLMs & GenAIintermediatemust-know5 min

Fine-Tune vs RAG vs Prompt: Choosing

The most common GenAI design question: prompt it, give it documents, or train it?

Choosing between Prompt Engineering, RAG, and Fine Tuning depends on task requirements. Prompt Engineering adapts baseline LLM behavior quickly using zero shot instructions. Retrieval Augmented Generation (RAG) injects dynamic, up to date external knowledge into context to prevent hallucinations and cite sources. Fine Tuning modifies model weights to internalize specific formatting, style, tone, or specialized domain syntax.

LLMs & GenAIintermediatemust-know5 min

Retrieval-Augmented Generation

How to let a model answer from your documents instead of its memory.

A language model only knows what was in its training data, and it cannot see your company's documents. RAG fixes that. When a question comes in, the system first searches a store of your documents for the most relevant passages, then pastes those passages into the prompt alongside the question. The model answers from that text instead of from memory. This keeps answers current, lets the system cite its sources, and greatly reduces made-up answers, all without retraining the model.

LLMs & GenAIintermediatemust-know5 min

Why LLMs Hallucinate

Why language models state false things with total confidence.

Hallucination is when a language model states something false with full confidence. It happens because the model is trained to predict the most likely next word, not the true one, and nothing in that training rewards saying "I don't know". Gaps or errors in its training data make it worse. A wrong answer and a right one can look identical from the outside. The main fixes are giving the model real source text to answer from, asking it to cite that text, and checking claims against trusted sources.

LLMs & GenAIadvancedmust-know5 min

RLHF Explained

How chatbots learned which answers people actually prefer.

A pretrained model writes fluently but has no sense of which answers people actually prefer. RLHF teaches it that. First, people compare pairs of answers and pick the better one. Those choices train a separate reward model that learns to score any answer the way people would. Then the main model is fine-tuned to earn high scores from it, usually with an algorithm called PPO, plus a penalty for drifting too far from how it wrote before, so it cannot learn to game the scorer.

LLMs & GenAIadvancedmust-know5 min

LoRA & Parameter-Efficient Fine-Tuning

Fine-tune a huge model by training less than one percent of it.

Fine-tuning a large model normally means updating billions of weights, which needs a lot of GPU memory. LoRA freezes the original model and trains only two small extra matrices beside each layer, whose product is the adjustment the task needs. That cuts the number of trainable weights by around 99 percent. After training, the small matrices can be merged back in, so answers come just as fast as before. You can also keep one base model and swap small LoRA adapters for different tasks.

LLMs & GenAIadvancedmust-know5 min

Evaluating LLM Systems

Why grading an LLM is so much harder than grading a classifier.

Evaluating LLM Systems requires moving beyond classical ML metrics (Accuracy, F1) to handle non-deterministic, open-ended text generations. Evaluation methods form a 3-tier hierarchy: 1) Automated String & Overlap Metrics (ROUGE, BLEU, Exact Match), 2) Model-Based Evaluators (BERTScore, RAGAS, G-Eval), and 3) LLM-as-a-Judge or Human Preference Rating (Elo rating / A/B testing). A robust LLM evaluation pipeline combines continuous CI/CD automated test suites with golden dataset benchmarks.

LLMs & GenAIbeginner5 min

Why Next-Token Prediction Works

Guessing the next word sounds trivial. It is how these models learn almost everything.

Next Token Prediction is the foundational self supervised training objective for Large Language Models. By predicting the probability distribution of the single next token given all preceding context tokens P(x_t | x_1...x_t-1), language models are forced to compress vast internet world knowledge, grammar, logic, and reasoning into model parameters. Scaling next token prediction across billions of parameters unlocks emergent zero shot capabilities, in context learning, and instruction following.

LLMs & GenAIbeginner5 min

Prompt Engineering That Works

Simple ways to write prompts that get more accurate, reliable answers.

Prompt Engineering is the practice of designing input prompt structures to guide Large Language Model behavior effectively. Key techniques include assigning System Personas, providing explicit Delimiters, setting structural Output Constraints (JSON / Markdown), using Negative Constraints, and employing Few-Shot Exemplars. Systematic prompt engineering turns unpredictable LLM responses into reliable, production-ready outputs.

LLMs & GenAIbeginner5 min

Zero-shot, Few-shot & In-Context Learning

Why showing a model a few examples often beats explaining the task.

Zero-Shot, Few-Shot, and In-Context Learning (ICL) describe methods for directing LLM task performance using context prompts without modifying model weights. Zero-Shot prompting asks a model to execute a task using instructions alone. Few-Shot prompting provides K input-output exemplars in the prompt context. In-Context Learning is an emergent property where self attention mechanisms process exemplars in forward passes to infer task patterns dynamically.

LLMs & GenAIbeginner5 min

Temperature, Top-p & Sampling

The settings that decide whether a model plays it safe or gets creative.

When a model writes, it gives every possible next word a probability, and these settings control how it picks from that list. Temperature reshapes the list: near zero it almost always takes the top word, which is predictable, while above one unlikely words get more chances, which is creative but riskier. Top-k allows only the k most likely words. Top-p allows the smallest group whose probabilities add up to p, so the group shrinks when the model is sure and grows when it is not.

LLMs & GenAIintermediate5 min

Chain-of-Thought & Reasoning Models

Why asking a model to think step by step makes it noticeably smarter.

Chain of thought means getting a model to write out its reasoning step by step before giving a final answer. It works because a model spends roughly the same effort on every word it writes. Writing the steps gives it more words, and so more thinking, before it has to commit to an answer. That makes a big difference on maths, code and multi-step logic. Newer reasoning models, such as OpenAI's o1 and DeepSeek-R1, are trained to produce long reasoning like this on their own.

LLMs & GenAIintermediate5 min

Chunking Strategies for RAG

Most broken RAG systems are broken at how the documents were split.

Chunking Strategies split raw documents into smaller text passages for vector embedding and retrieval in RAG pipelines. Choosing chunk size involves trade-offs: small chunks preserve precise search specificity but lose global context, while large chunks capture broad context but dilute vector retrieval precision. Strategies range from Fixed Size Chunking with Overlap to Document Structure Aware Chunking, Semantic Chunking based on embedding distance shifts, and Parent Child Hierarchical Chunking.

LLMs & GenAIintermediate5 min

Vector Databases & ANN Search

How apps search millions of meanings in a few milliseconds.

Vector Databases store, index, and query high dimensional vector embeddings for RAG and semantic search systems. Traditional relational databases rely on exact B-tree comparisons that fail in high dimensions. Vector Databases use Approximate Nearest Neighbor (ANN) search algorithms (HNSW, IVF, PQ) to trade 100 percent exact recall for sub-millisecond search speed across millions of vectors.

LLMs & GenAIintermediate5 min

Grounding & Citation Enforcement

Making a model show exactly where each of its claims came from.

Grounding and Citation Enforcement ensure Large Language Model outputs are strictly anchored to verified retrieved context passages. Un-grounded generation leads to hallucinations and compliance failures in legal and medical applications. Techniques include System Prompt Constraints, In-Text Citation Formatting ([Doc 1, Page 4]), Post-Generation Attribution Checking (NLI Fact Verification), and Constrained Decoding.

LLMs & GenAIintermediate5 min

Context Windows & Long-Context Tricks

What to do when everything you want to send will not fit in the prompt.

Context Window Management optimizes how text tokens are packed, truncated, and cached inside an LLM's finite context window (e.g. 8k to 128k tokens). Key strategies include Prompt Truncation (FIFO vs Sliding Window), Dynamic Summarization of past turns, KV Cache Prompt Caching, and Needle in a Haystack retrieval testing. Managing context budgets reduces API token costs, lowers time-to-first-token (TTFT) latency, and prevents Lost in the Middle retrieval degradation.

LLMs & GenAIintermediate4 min

Lost in the Middle

Models remember the start and end of a long prompt, and lose the middle.

Lost in the middle describes a weakness in language models reading long prompts. They are good at using information placed at the very start or the very end, but noticeably worse at using facts buried in the middle. A Stanford study showed accuracy drops sharply as the key fact moves toward the centre. In practice, put the most important context at the top or bottom, and in RAG, rank the best passages first rather than stuffing in as many as possible.

LLMs & GenAIintermediate5 min

Tool Use & Function Calling

How a language model goes from writing text to actually doing things.

Tool Use and Function Calling allow LLMs to interact with external databases, web APIs, and code execution environments. Instead of executing code internally, Function Calling instructs the LLM to output a structured JSON payload specifying function name and argument parameters. An external application executes the function call, returning the API result back into prompt context so the LLM can synthesize a final response.

LLMs & GenAIintermediate5 min

Model Context Protocol (MCP)

One standard way to plug AI apps into tools and data, like USB for AI.

Model Context Protocol, or MCP, is an open standard from Anthropic for connecting AI apps to tools and data. Without it, every app needs its own custom code for every service, like GitHub, a database or Slack. With MCP, each service is wrapped once as an MCP server that offers its data, actions and prompt templates in a standard way. Any MCP-aware app, such as Claude Desktop or a code editor, can then use any server. Think of it as a USB port for AI tools.

LLMs & GenAIintermediate5 min

Structured Output & Constrained Decoding

How to guarantee a model's reply is always valid JSON.

Asking a model to reply only in JSON works most of the time, but not every time, because it picks words with some randomness. Constrained decoding makes the format guaranteed. At each step, the system works out which next tokens would still produce valid output for your schema, and blocks every other option before the model chooses. The model can only pick a token that keeps the output valid, so your code can always parse it. Outlines, vLLM and OpenAI Structured Outputs all do this.

LLMs & GenAIintermediate4 min

Prompt Caching

Stop paying again for the same long prompt every single time.

Prompt Caching avoids re-computing the Transformer prefill phase for shared or static prompt prefixes (e.g. system instructions, long document contexts, multi-turn chat history). By storing the computed KV Cache of a static prefix in server memory, subsequent user queries matching that prefix bypass prompt prefill computation. Prompt Caching reduces Time-To-First-Token (TTFT) latency from seconds to milliseconds and lowers API token input costs by up to 80-90%.

LLMs & GenAIintermediate5 min

Cutting LLM Cost in Production

Practical ways to cut a GenAI bill without making the answers worse.

Production LLM deployments can quickly incur massive monthly API and GPU bills if un-optimized. Cost reduction strategies span the entire AI stack: 1) Model Routing & Cascading (routing easy queries to 8B models and hard queries to 70B/GPT-4), 2) Prompt Compression & Caching (LLMLingua, Anthropic Prompt Caching), 3) Quantization & Self-Hosting (vLLM, FP8, INT4), and 4) Task Distillation (fine-tuning a small 8B model to replace a 175B model for specific tasks).

LLMs & GenAIintermediate5 min

Prompt Injection & Jailbreaks

When text from a user quietly hijacks your model's instructions.

Prompt Injection is a fundamental security vulnerability in LLM applications where untrusted input strings manipulate the model into ignoring system instructions. Direct Prompt Injection (Jailbreaking) occurs when a user explicitly instructs the model to bypass safety constraints ("Ignore previous instructions"). Indirect Prompt Injection occurs when an untrusted external document retrieved via RAG or web search contains hidden malicious instructions. Defense requires input isolation (delimiter tags), dual-LLM privileged architecture, strict input sanitization, and output guardrail filters.

LLMs & GenAIintermediate5 min

Guardrails & Output Filtering

The checks around a model that stop bad inputs and unsafe outputs.

LLM Guardrails provide safety, structure, and compliance envelopes around raw LLM generations. Input Guardrails sanitize user prompts, detect prompt injections, and block inappropriate topics before reaching the core model. Output Guardrails audit model responses for hallucinations, PII leaks, toxic language, and JSON schema compliance. Frameworks (NeMo Guardrails, Guardrails AI, Llama Guard) combine fast classification models, regular expressions, and constrained decoding.

LLMs & GenAIintermediate5 min

Choosing an Embedding Model

Picking the embedding model that actually makes your search work.

Choosing an Embedding Model determines vector retrieval precision, index storage footprint, and latency in RAG pipelines. Selection criteria include vector dimensionality (e.g. 384-d vs 1536-d vs Matryoshka Flexible Embeddings), MTEB Benchmark rankings (Massive Text Embedding Benchmark), domain adaptation (general vs code vs medical), and Symmetric vs Asymmetric search (matching short queries against long documents).

LLMs & GenAIintermediate5 min

Helpful, Honest, Harmless

Helpful, honest, harmless, and why those three pull against each other.

Helpful, honest and harmless is Anthropic's short list for what a well-behaved AI assistant should be. Helpful means actually doing what the user asked. Honest means stating true things, admitting uncertainty and not making things up. Harmless means refusing to help with things like violence, crime or self-harm. The hard part is that these pull against each other. A model that refuses too much is safe but useless, and one that never refuses is helpful but dangerous. Getting that balance right is the real challenge.

LLMs & GenAIintermediate4 min

Chat Templates

The hidden formatting that turns a conversation into text a model understands.

Chat Templates standardize how multi turn conversation messages (System, User, Assistant) are formatted into raw text strings for LLMs. Different model families (ChatML, LLaMA 3, Mistral) use unique control tokens like <|im_start|> user ... <|im_end|> to delineate speaker turns. HuggingFace tokenizers use Jinja2 templates via tokenizer.apply_chat_template to automatically format conversation dictionaries into model specific prompt strings, preventing formatting mismatches during fine tuning and inference.

LLMs & GenAIintermediate4 min

Semantic Caching

Answering repeat questions instantly, even when they are worded differently.

Semantic Caching (GPTCache, Redis Semantic Cache) stores prompt embeddings and their corresponding LLM responses in a fast Vector DB. Traditional exact-string caching fails when users paraphrase prompts ("What is the weather in NYC?" vs "How's the weather in New York City?"). Semantic Caching embeds incoming user prompts, computes cosine similarity against cached prompt vectors, and returns the pre-computed response instantly if similarity exceeds threshold τ (e.g. τ ≥ 0.95), bypassing LLM inference.

LLMs & GenAIadvanced5 min

Reward Models & Reward Hacking

The model that scores answers, and why the chatbot will cheat it if it can.

A Reward Model (RM) is a regression network that outputs a single scalar score representing human preference for a prompt-response pair. Reward Models are trained on pairwise comparison datasets using Bradley-Terry preference loss. Reward Hacking (Goodhart Law) occurs when the policy model discovers unintended shortcuts or vulnerabilities in the Reward Model, earning high scores while producing degenerate, verbose, or incoherent text.

LLMs & GenAIadvanced5 min

DPO vs PPO

Two ways to teach a model your preferences, and why most teams pick the simpler one.

DPO (Direct Preference Optimization) and PPO (Proximal Policy Optimization) are the two primary alignment algorithms for Large Language Models. PPO is an actor critic RL framework that optimizes a policy against a separate Reward Model using online sampling and value function estimation. DPO mathematically re-formulates the RL objective to optimize policy parameters directly on offline preference pairs using binary cross entropy, bypassing reward model training and actor critic complexity.

LLMs & GenAIadvanced5 min

Constitutional AI & RLAIF

Teaching a model to be safe with a written list of rules, not thousands of ratings.

Constitutional AI is Anthropic's way of training a model to be safe with far less human labelling. Instead of paying people to rate thousands of answers, you write down a short list of principles, called the constitution. The model critiques its own answers against those principles, rewrites the bad ones, and learns from the improved versions. Later, an AI rather than a person judges which of two answers better follows the principles. That step is called RLAIF: reinforcement learning from AI feedback.

LLMs & GenAIadvanced5 min

Scaling Laws & Chinchilla

Why bigger models improve so predictably, and why data matters as much as size.

Scaling laws describe how a language model gets better, smoothly and predictably, as you give it more compute, more parameters and more training text. That predictability lets labs plan a huge training run before spending the money. An early OpenAI study said model size mattered more than data. DeepMind's Chinchilla work later showed both should grow together, at about 20 training tokens for every parameter. Many earlier models were too big for the data they saw, and smaller models trained on more text beat them.

LLMs & GenAIadvanced5 min

Emergent Abilities: Real or Mirage?

Do big models suddenly gain new skills, or does it only look that way?

Emergent abilities are skills, like multi-step arithmetic, that seem missing in small models and then suddenly appear once a model is big enough. The debate is whether that jump is real. A later study argued it is mostly a measurement effect: if you score answers as simply right or wrong, slow steady progress looks like a sudden leap. Score with a measure that gives partial credit, and the same skills improve gradually as models grow. The safe interview answer is partly real, partly how we measure.

LLMs & GenAIadvanced5 min

Mixture of Experts

How a model can hold huge knowledge but use only a small slice per word.

A Mixture of Experts model splits part of the network into many smaller sub-networks, called experts, plus a router. For each word, the router picks just a few experts to handle it, often two out of eight, and the rest stay idle. So the model can hold a huge number of parameters in total while using only a small slice of them for any one word. You get the knowledge of a big model at close to the running cost of a much smaller one. Mixtral is a known example.

LLMs & GenAIadvanced5 min

QLoRA & 4-bit Fine-Tuning

Fine-tune a 70 billion parameter model on a single GPU.

QLoRA lets you fine-tune a very large model on a single GPU. It stores the frozen base model in a compressed 4-bit format instead of the usual 16-bit, which cuts its memory use about four times, then trains small LoRA adapters on top. Two extra tricks save more: it also compresses some of its own bookkeeping numbers, and it moves memory to the CPU during spikes instead of crashing. The result is that a 70 billion parameter model can be fine-tuned on one 48 GB GPU.

LLMs & GenAIadvanced5 min

Instruction Tuning & Data Curation

How a model that only predicts text learns to follow instructions and chat.

A base model only predicts the next word, so if you ask it a question it may just continue your text. Instruction tuning fixes that by fine-tuning it on examples of instructions paired with good responses, which teaches it to follow requests and hold a conversation. The big lesson from research such as LIMA is that quality beats quantity: around a thousand carefully chosen examples can match tens of thousands of noisy ones. So most of the work is cleaning the data and covering many kinds of task.

LLMs & GenAIadvanced5 min

Test-Time Compute & Inference Scaling

Letting a model think longer when it answers, instead of training a bigger one.

Test-Time Compute Scaling (Inference Scaling) shifts compute allocation from pre-training parameters to inference-time reasoning. Instead of relying on single-pass forward generation, systems trade extra GPU FLOPs at inference time for higher accuracy. Techniques include Search over Reasoning Trees (Monte Carlo Tree Search - MCTS, Process Reward Models), Majority Voting (Self-Consistency), and native reasoning models (OpenAI o1) trained via RL to execute adaptive internal thinking steps before returning answers.

LLMs & GenAIadvanced5 min

HNSW vs IVF vs Flat Indexes

The two main tricks for finding similar vectors fast without checking every one.

Vector Search Indexing algorithms trade memory and build time for sub millisecond query retrieval speed. Flat Indexing performs exact 100 percent brute force search, scaling linearly O(N * d). Inverted File Indexing (IVF) clusters vector space into Voronoi cells to search candidate centroids. Hierarchical Navigable Small World (HNSW) builds multi layer proximity graphs, delivering state of the art sub-millisecond search speed and 99 percent recall.

LLMs & GenAIadvanced5 min

Hybrid Search & Reranking

Why the best search combines plain keyword matching with meaning-based search.

Hybrid Search and Reranking represent state of the art retrieval pipelines for production RAG systems. Hybrid Search combines sparse lexical keyword search (BM25) with dense semantic vector embeddings (Dense Retrieval) using Reciprocal Rank Fusion (RRF) to capture both exact domain terms and broad conceptual intent. A two stage retrieval pipeline uses fast hybrid search to retrieve top 100 candidate chunks, followed by a heavy Cross Encoder Reranker to compute deep pairwise attention scores, boosting top 5 RAG precision.

LLMs & GenAIadvanced5 min

Evaluating a RAG Pipeline

How to tell whether your RAG system failed at finding or at answering.

Evaluating a RAG Pipeline requires disentangling Retrieval performance from LLM Generation performance. The RAG Triad framework (Ragas / TruLens) measures three core dimensions: Context Relevance (evaluating whether vector search retrieved accurate context chunks), Groundedness / Faithfulness (evaluating whether the LLM answer is supported by retrieved context), and Answer Relevance (evaluating whether the LLM answered the user question).

LLMs & GenAIadvanced5 min

GraphRAG & Structured Retrieval

How to answer big-picture questions across thousands of documents.

Normal RAG is good at specific questions, like finding one fact in one document. It struggles with big-picture questions, like asking what the main themes are across five thousand documents, because no single passage holds that answer. GraphRAG, from Microsoft, first turns the documents into a map of people, things and how they connect. It groups related items into clusters and writes a summary of each cluster. Big-picture questions are then answered from those summaries, not from scattered passages.

LLMs & GenAIadvanced5 min

Agent Loops & Planning

What really makes something an agent, and why knowing when to stop is hard.

AI Agents are autonomous systems driven by Large Language Models that execute multi step goal directed tasks. Instead of single turn text generation, Agents operate in iterative Perception Action Feedback Loops. Frameworks like ReAct (Reason + Act) combine step-by-step reasoning thoughts with external tool actions, allowing agents to observe environmental feedback, self-correct errors, and execute complex workflows.

LLMs & GenAIadvanced5 min

Multi-Agent Systems

When splitting work across several AI agents helps, and when it just adds chaos.

Multi-Agent Systems (AutoGen, CrewAI, LangGraph) decompose complex workflows into networks of specialized LLM agents (e.g. Researcher, Coder, Reviewer, Manager). Specializing individual agent personas with focused system prompts and restricted tool scopes outperforms single monolithic LLM prompts. Orchestration topologies include Sequential Pipelines, Hierarchical Supervisory Trees, and Asynchronous Peer-to-Peer Message Buses.

LLMs & GenAIadvanced5 min

Agent Memory & State

How an agent remembers what happened five minutes ago, and five weeks ago.

Agent Memory enables autonomous systems to maintain state, recall past user preferences, and learn from execution experiences across multi-turn sessions. Memory is structured into Short-Term Memory (in-context working memory of current session turns), Long-Term Semantic Memory (vector DB indexes of past facts and documents), and Long-Term Episodic Memory (vectorized execution logs of past actions and reflection critiques).

LLMs & GenAIadvanced5 min

LLM-as-a-Judge

Using one model to grade another, and the biases that come with it.

LLM as a judge means using a strong model to grade other models' answers, which is far cheaper and faster than asking people. It can compare two answers and pick the better one, or score a single answer against a checklist. It agrees with human ratings reasonably well, but it has known biases: it tends to favour the answer shown first, longer answers, and answers written in its own style. Good setups ask the judge to explain its reasoning and swap the answer order to cancel those biases.

LLMs & GenAIadvanced5 min

Inference Optimization & Batching

Serving a model is limited by memory, not maths. Here is how to speed it up.

When a model writes text, its speed is usually limited by how fast the GPU can move data from memory, not by how fast it can calculate. Most speed-ups attack that. Continuous batching slots new requests in as soon as others finish. PagedAttention stores the model's working memory in small pages so less is wasted. Quantization stores weights in fewer bits, so there is less to move. FlashAttention avoids needless memory trips. Together they can serve five to twenty times more requests on the same hardware.

LLMs & GenAIadvanced5 min

Speculative Decoding

A small model guesses, a big model checks, and answers arrive two to three times faster.

Speculative decoding makes a big model answer faster without changing what it says. A small, fast model guesses the next few words. The big model then checks all those guesses at once, in a single pass, keeping every guess that matches what it would have written and correcting the first one that does not. Checking several words at once is much cheaper for the big model than writing them one by one. You typically get two to three times the speed, with exactly the same output.

LLMs & GenAIadvanced5 min

Multimodal Models (VLMs)

How one model learns to read text, images and audio together.

Multimodal Large Language Models (MLLMs - GPT-4o, Gemini, LLaVA, Claude 3.5 Sonnet) process multiple modalities (Images, Audio, Video, Text) simultaneously. Visual inputs are processed via Vision Encoders (ViT / CLIP), which partition images into patches, convert patches to dense visual tokens, and project them into the LLM's text embedding space using Linear or Cross-Attention Projection layers. Native multimodal architectures (GPT-4o, Gemini 1.5) process text, audio, and visual tokens end-to-end within a single unified Transformer backbone.

LLMs & GenAIadvanced5 min

Synthetic Data Generation

Using a strong model to write training data for a smaller one.

Synthetic Data Generation uses powerful frontier LLMs (GPT-4o, Claude 3.5 Sonnet) to create artificial training datasets for fine-tuning smaller models. Techniques include Self-Instruct (generating diverse prompts and responses automatically), Evol-Instruct (iteratively increasing prompt complexity), and Model-Based Filtering (using rejection sampling and reward models to discard low-quality synthetic generations). Synthetic data powers modern open models (Phi-3, LLaMA-3, UltraChat) to achieve frontier-level task performance.

LLMs & GenAIadvanced5 min

Distilling a Large Model into a Small One

Shrinking a big model's skill into a small, cheap one.

Distillation trains a small, cheap student model to copy a large, expensive teacher model. The classic way trains the student to match the teacher's full spread of probabilities over possible answers, not just its top answer, because that spread carries extra information about how the teacher thinks. With modern language models the common way is simpler: have the teacher write lots of high-quality answers and step-by-step reasoning, then fine-tune the student on that text. You keep much of the quality at a fraction of the cost.

LLMs & GenAIadvanced5 min

Direct Preference Optimization

The simpler alternative to RLHF that skips the reward model entirely.

Direct Preference Optimization, or DPO, is a simpler alternative to RLHF for teaching a model which answers people prefer. RLHF trains a separate reward model and then runs reinforcement learning against it, which is complex and unstable. DPO skips both. It trains the model directly on pairs of answers, one preferred and one rejected, nudging it to make the preferred one more likely, measured against a frozen copy of the original model. It uses less GPU memory and is much easier to get working.

LLMs & GenAIadvanced5 min

KTO & ORPO

Teaching preferences when you only have thumbs up or down, not ranked pairs.

KTO (Kahneman Tversky Optimization) and ORPO (Odds Ratio Preference Optimization) represent next generation post DPO alignment methods. KTO eliminates paired preference data requirements by optimizing directly on binary thumbs up or thumbs down feedback per sample. ORPO eliminates the separate reference model entirely by penalizing the odds ratio of dispreferred responses directly inside the SFT cross entropy loss step.

LLMs & GenAIadvanced5 min

Curating Preference Data

Good preference data matters more than which training algorithm you pick.

Preference Data Curation generates pairwise comparison datasets containing a Prompt x, a Chosen response y_w (winning), and a Rejected response y_l (losing). These datasets train Reward Models for RLHF and directly align models using DPO. Quality depends on Annotator Inter Rater Reliability, hard negative sampling, domain diversity, and filtering out superficial biases like response length.

LLMs & GenAIadvanced5 min

Sycophancy & Over-Refusal

Stopping a model from just telling users what they want to hear.

Sycophancy and Over Refusal are two major failure modes introduced by naive AI alignment. Sycophancy happens when an LLM falsely agrees with incorrect user premises or flatters user opinions rather than telling the truth. Over Refusal happens when a model becomes overly conservative, refusing safe benign requests because they contain trigger words like kill or bomb. Mitigation strategies include synthetic anti sycophancy training data, fine-grained safety rubrics, and Constitutional AI alignment.

LLMs & GenAIadvanced4 min

Per-Token Loss Masking

Why a model should learn from its answers, not from copying your prompt.

Per Token Loss Masking is an essential implementation detail in Supervised Fine Tuning (SFT) for Large Language Models. During SFT training, an instruction example contains both a Prompt and a Target Response. Loss masking sets target labels for all input prompt tokens to minus 100, ignoring them during cross entropy loss calculation so model gradients update weights exclusively based on generating accurate target response tokens.

LLMs & GenAIadvanced5 min

Agentic RAG

Letting the model decide what to search for, and when to search again.

Agentic RAG transforms passive single-shot retrieval pipelines into autonomous control loops where an LLM agent dynamically controls retrieval strategy. Capabilities include Dynamic Query Routing (directing queries to specialized vector DBs, SQL, or Web Search), Adaptive Retrieval (evaluating whether retrieved context is sufficient and re-formulating queries if incomplete), and Corrective RAG (CRAG - using web search fallbacks when internal retrieval precision is low).

LLMs & GenAIadvanced5 min

Multimodal RAG

Answering questions from documents full of tables, charts and images.

Multimodal RAG extends Retrieval-Augmented Generation to process complex documents containing tables, charts, diagrams, and embedded images. Architectural patterns include: 1) Text Summarization RAG (extracting images/tables, generating text summaries using Vision LLMs, and indexing summaries in standard vector DBs), 2) Native Multimodal Embedding RAG (using CLIP / ColPali to embed image patches directly), and 3) Multimodal VLM Generation (passing retrieved raw images alongside text to Vision LLMs like GPT-4o).

LLMs & GenAIadvanced5 min

RAG Evaluation Frameworks

The three checks that tell you if a RAG answer is right and grounded.

Evaluating RAG architectures requires auditing both the Retrieval component and the Generation component independently. The RAG Triad framework (RAGAS / TruLens) breaks down evaluation into three fundamental metrics: 1) Context Precision (evaluating if retrieved context chunks are relevant to the query), 2) Faithfulness (measuring what share of the answer's claims are supported by the retrieved context), and 3) Answer Relevance (evaluating if the LLM output directly answers the user prompt).

LLMs & GenAIadvanced5 min

Mitigating Hallucination

There is no single fix for hallucination, so you stack several.

There is no single fix for hallucination, so in practice you stack several. The biggest is grounding: retrieve real documents and tell the model to answer only from them. Ask it to cite sources so claims can be checked. Use a low temperature so it picks likely words over creative ones. Tell it plainly that saying it does not know is fine. You can also ask the same question several times and flag answers that disagree, since invented details change between attempts while real facts stay put.

LLMs & GenAIadvanced5 min

GGUF, AWQ & LLM Quantization

Shrinking a model to 4 bits so it runs on a laptop.

LLM Weight Quantization converts 16-bit floating-point weights (FP16/BF16) into lower-precision integer or float representations (INT8, INT4, FP8) to shrink VRAM memory footprint and accelerate inference. GGUF (llama.cpp) is optimized for CPU and Apple Silicon unified memory using k-quant block quantization. GPTQ (One-shot Post-Training Quantization) uses second-order Hessian information for 4-bit GPU inference. AWQ (Activation-aware Weight Quantization) protects the 1% most critical weight channels based on activation magnitudes, achieving superior 4-bit accuracy on GPUs.

SCROLL · SAVE · TAP TO GO DEEPER