Batch size, epochs and steps
Work out how many steps a run takes from examples, batch size, gradient accumulation and epochs, and why accumulation matches a larger batch.
Catastrophic forgetting
A tuned model can lose skills it had before. See how narrow training erases them, and how mixing in replay examples or training less keeps them.
Choosing a base model
Choose a starting model by memory fit, licence and score on your own questions, not by a leaderboard. Includes a runnable shortlist script.
Choosing useful context
Select context by permission, freshness and relevance, and keep a log of why each piece went in or stayed out. Includes a runnable selector.
Citations and honest refusals
A grounded RAG answer cites its sources and admits when they do not hold the answer. Check citations in code and refuse when retrieval finds nothing useful.
Cleaning data and checking quality
Remove duplicates, conflicting labels and personal data from training examples before they reach the model, with runnable checks and a by-eye review.
Collecting and creating examples
Gather training examples from records, experts and synthetic drafts, check that annotators agree, and confirm you may use each source. Includes runnable code.
Context for a code assistant
A code assistant cannot read a whole repository. Learn what to send in full, what to outline, and why agents fetch files on demand. Includes runnable code.
Context for a support bot
Build the full context for a support assistant in code: pick facts by permission and topic, order and escape every part, and hand over when nothing applies.
Context is a budget
A context window is a fixed budget shared by input and reply. Reserve the reply, fund the essentials first, then add optional parts in priority order.
Define the task and what success means
Write the task in one sentence, fix the labels, pick a score that counts the costly mistakes, and set a baseline before training. Includes runnable code.
Distillation
Train a small student model to copy a large teacher on one task, see how soft targets carry more signal, and work out when the saving repays the cost.
Embeddings and semantic search
An embedding turns text into numbers so passages with similar meaning sit close together. Rank them with cosine similarity, even when no words match.
Error analysis and the next round
Read failures, sort them into causes, count them and choose the next change from the pattern, then check the same cases again in the next round.
Evaluating a fine-tuned model
Compare a tuned model with its baseline on the same held-out cases, read gains and losses by slice, and judge whether the difference is more than noise.
Fine-tune a classifier
Train a small model to label support messages, then read a confusion matrix and compare with a keyword baseline. Includes runnable scoring code.
Fine-tune a model to follow instructions
Render chat examples with the model's template, train a small instruction model for two steps, and compare its replies before and after on held-out requests.
Fitting training into memory
Estimate where training memory goes, then cut it with smaller batches, gradient checkpointing, mixed precision and adapters. Includes a runnable estimator.
Formatting data for training
Store examples as JSON Lines, in prompt-and-completion or chat form, and validate every line before training. Includes runnable code that reports bad lines.
History and summaries
Long conversations outgrow the window. Compare a sliding window with pinned facts and a summary, and see in code which one keeps an order number alive.
Hosted fine-tuning and open-weight models
Compare fine-tuning through a provider's API with training open weights you control, and find the request volume where running your own pays off.
How a language model learns
Pre-training and fine-tuning use the same loop: predict the next token, measure the miss, adjust the weights. Only the data changes. Includes runnable code.
How context goes wrong
Wrong answers often trace to the context: a bad fact repeated, too much noise, rival sources or a stale rule. Learn four failures and a check for the last.
How LoRA works
Follow LoRA with real numbers: two small matrices add an update to a frozen layer, rank sets their size, and alpha sets how strongly the update counts.
How to chunk documents
Split documents into passages small enough to match one question and large enough to stay true. Compare fixed windows, overlap and heading splits in code.
Human review and model judges
Score qualities a formula cannot with a rubric, blind side-by-side review and a model judge, and check agreement and position bias in plain Python.
Hybrid search and reranking
Combine keyword and semantic rankings with reciprocal rank fusion, then reorder a short list with a reranker. See how each step changes the passages sent on.
Instructions and examples
Write instructions a model can follow and pick examples that teach the task. Select the closest examples for each request in code, edge cases included.
Keyword search and BM25
BM25 ranks passages by the words they share with a question, giving rare words more weight. Build it in 20 lines of Python and see where it fails.
Kinds of fine-tuning
Full, parameter-efficient, instruction, continued pre-training and classification tuning differ in what they change and cost. Compare them side by side.
Learning rate, warm-up and schedules
See how too high and too low learning rates behave, then build a warm-up and decay schedule and read its values step by step. Includes runnable code.
Loading and cleaning documents
Strip menus, scripts and duplicates from source documents before you index them, so retrieval returns useful text. Includes a runnable HTML cleaner.
LoRA in code
Attach a LoRA adapter with PEFT, check that it targets the right layers and trains only a small share of the weights, then save, reload and merge it.
Measuring answer faithfulness
Check that each sentence of a RAG answer is supported by the retrieved passages. Score faithfulness with a word-overlap check, then add a model judge.
Measuring retrieval quality
Test retrieval on its own with a list of questions and the passages that answer them. Score recall@k and MRR in code, then use the failures to improve search.
Metadata, filters and permissions in RAG
Store a source, a date and an audience with every chunk, then filter before ranking so users see only current text they may read. Includes a runnable filter.
Metrics for classification and generation
Calculate accuracy, precision, recall, F1, exact match, word overlap and perplexity in plain Python, and see what each one misses.
Order and labels in context
Where a part sits and how it is marked changes the answer. Put stable text first, label every part, and escape untrusted text so it cannot fake a label.
Other efficient methods
Compare prompt tuning, prefix tuning, adapter layers and DoRA with LoRA by where their trainable weights sit and how many there are.
Overfitting and underfitting
Tell memorising from learning by comparing training and validation scores, then fix it with early stopping, regularisation and more varied data.
Putting retrieved passages in a prompt
Build the RAG prompt: an instruction, numbered sources inside delimiters, then the question. Fit the passages to a token budget and order them with care.
Quantisation and QLoRA
See how storing weights in fewer bits saves memory and adds rounding error, then how QLoRA trains a LoRA adapter on a frozen 4-bit base model.
Query rewriting and multi-step retrieval
Rewrite follow-up questions into standalone searches and split compound questions into parts. Compare one search with several in code, and know when to stop.
Reading a training run
Read training and validation loss together, spot overfitting and failed runs, and pick the best checkpoint with a runnable early-stopping check.
Safety, licences and upkeep
Check licences, remove private data before training, test for harmful output and watch a released model for drift, with code for the scan and the alert.
Serving a fine-tuned model
Merge an adapter, pick a precision and size a GPU for real traffic, then estimate the cost of a request and re-check quality after every conversion.
Setting up your environment
Estimate the memory a model needs, check your GPU, and save the versions and settings that make a fine-tuning run repeatable. Includes runnable code.
Structured output and tool calls
Train a model to return JSON and tool calls, then parse, validate and permission-check every output in code before the application acts on it.
Testing a context change
Test every context change on a fixed question set. Remove one part at a time to see what each is worth, and catch a harmless-looking edit that breaks an answer.
The fine-tuning workflow
Define the task, set a baseline, prepare three splits, train, and test once. See the seven steps, what each costs, and where projects usually go wrong.
Fine-tuning
Tokenisation for training
See how text becomes token IDs, padding, attention masks and labels, and why the loss ignores the prompt with -100. Includes runnable code.
Tool results in context
A tool call can return far more than the model needs. Trim results to useful fields, cap long lists with a note, and treat what comes back as untrusted.
Training, validation and test sets
Split examples into training, validation and test sets by group or by time so related records stay together, and check for leakage with runnable code.
Tuning with preferences: RLHF and DPO
Learn how preference pairs train a reward model in RLHF or feed DPO directly, and compute the preference loss that DPO minimises in plain Python.
Vector indexes and approximate search
Exact vector search compares a question with every stored vector. Approximate indexes check only some. See the speed and recall trade in a short program.
What belongs in context?
Context is everything a model reads before it replies. Learn its six parts, who supplies each one, and how to check that a request has what it needs.
What is retrieval-augmented generation?
RAG searches your documents for passages that fit a question, then gives them to a language model so it answers from sources. See the steps in a short program.
Why RAG systems fail
Trace a wrong RAG answer through indexing, retrieval, the prompt budget and the model. A runnable diagnosis shows which stage lost the right passage.
Why train fewer parameters
Full fine-tuning copies and updates every weight. See what that costs in memory and storage, and how freezing the base model with adapters changes it.
Attention, step by step
Attention lets each token pull information from the tokens before it. Work through queries, keys, values and the mask in a few lines of NumPy.
Call a model from code
Run a small open model on your own computer with a few lines of Python, then see how hosted APIs take the same list of messages.
Choosing a model for a task
The best model is the cheapest one that passes your own tests. Build a small evaluation, compare quality, cost and speed, and start small.
From text predictor to assistant
A base model only continues text. Instruction tuning trains it on requests and good answers, and a chat template marks who said what.
How a model knows word order
Attention on its own ignores word order. See the problem in code, then compare the three ways models add position: learned, sine waves and rotary.
How a model writes a reply
A model writes one token at a time and feeds each one back in. Learn the loop, when it stops and why the reply counts against the context window.
How pre-training works
In pre-training, a model reads trillions of tokens and learns to predict each next one. The text is its own answer key, so no one has to label it.
Learning from human preferences
Comparing two answers is easier than writing a perfect one. See how RLHF and DPO turn people's preferences into training, and what can go wrong.
Loss and gradient descent
Loss is one number for how wrong the model was. Gradient descent nudges each parameter to lower it. Run both in plain Python and watch a bad learning rate fail.
Parameters and model size
Count GPT-2's 124 million parameters by hand, see where they sit, and work out how much memory a model needs at different precisions.
Large language models
Predicting the next token
At every step the model scores every token it knows. Softmax turns those scores into probabilities that add up to 1.
Scaling laws
Loss falls in a predictable way as models grow. Learn the compute formula, what Chinchilla changed, and why small models now read far more text.
Temperature, top-k and top-p
The model gives probabilities, and a sampling rule picks the token. See in code how temperature, top-k and top-p change that pick.
The transformer block
A transformer stacks one block many times. Each block has an attention step, a feed-forward step and shortcuts that carry the signal through.
Large language models
Tokens and tokenisers
A model reads tokens, not letters or words. See how byte pair encoding builds a vocabulary, and why token counts decide cost and length.
Large language models
Turning tokens into vectors
Each token id becomes a list of numbers called an embedding. Tokens with related meanings get similar lists, and the rest of the model works with those lists.
What a large language model is
An LLM learns one skill from a huge amount of text: guess the next piece of text. Chat, summaries and code all come from repeating that guess.
Why long prompts cost more
Attention compares every token with every earlier token, so work grows faster than the text. Learn prefill, decode and the KV cache that makes replies fast.
Why models make things up
A model writes likely text, not checked facts. Learn why it states false things with confidence, and four ways to catch and reduce it.
Writing a clear prompt
A model only knows what you put in the prompt. State the task, give the context, show examples and ask for a format you can check.
Build your first agent
Write a small agent in plain Python, run it, and read its trace. Then swap the stand-in decision for a real model.
Choosing useful sources
An agent is only as good as what it reads. Learn how to judge a source for relevance, trust and freshness, and what to do when sources disagree.
Context window optimisation
Long AI tasks fill the context window. Learn four ways to keep it lean—trim, summarise, retrieve, reorder—and when to use each.
Designing tools an agent can use
A tool is an interface for a model, not for a person. Learn the five habits that make an agent pick the right tool and use it correctly.
Goals, plans and steps
An agent can only aim at a goal you can check. Learn to write goals that can be tested, plans the agent can follow and when to change the plan.
Guardrails and safe failure
Checks in code catch what prompts cannot. Learn the limits, validations and fallbacks that keep a failing agent from doing harm.
How an agent uses tools
The model never runs a tool. It writes a request, and your program runs it. Learn the full round trip and how to guard it.
Memory between requests
A model forgets everything when a call ends. Learn the two kinds of agent memory, and how to decide what to store and what to forget.
Permissions and human approval
An agent should have the least power that lets it do the job. Learn to separate safe actions from risky ones and where a person must say yes.
Retrieval-augmented generation
Let the agent look things up instead of remembering them. Learn the four steps of RAG and what can go wrong at each one.
Testing an agent
The same task can follow a different path each run. Learn to test the outcome, repeat each case, and keep a set of examples that guards against regressions.
The agent loop
Every agent repeats one cycle: look, decide, act, read the result. Learn the cycle, and the three ways it should stop.
Agentic AI
Tokens and the context window
A model reads and writes tokens, and it can hold only so many at once. Learn how to estimate them and why the limit shapes every agent.
Watching an agent in production
Once real people use your agent, you need to see what it does. Learn what to record, what to measure and how to turn problems into fixes.
What an agent is made of
A model, instructions, tools, memory and a loop. Learn what each part does and which part to fix when the agent misbehaves.
What goes into a prompt?
The model sees one block of text on every call. Learn the six parts that fill it, and why the order matters.
What is agentic AI?
A chatbot answers one message. An agent works toward a goal, using tools and checking its own results. Learn what that changes and what it does not.
When to use several agents
One agent is simpler than many. Learn the two cases where splitting the work pays off, and what each hand-off costs.
Why agents fail
Small errors add up over many steps. Learn the arithmetic of long tasks and the five failure patterns that cause most real problems.
Workflows or agents?
In a workflow your code chooses the steps. In an agent the model chooses them. Learn how to pick, and why the simpler one usually wins.
What fine-tuning is
Learn what fine-tuning is, how training updates a language model's weights on your examples, and what you get at the end.
How retrieval works
Retrieval ranks stored passages against a question and returns the top few. See the two phases, the top-k choice and what a retriever hands to the model.
RAG or fine-tuning?
Fine-tuning changes how a model behaves. Retrieval changes what it can look up. Learn which problem you have and which fix is cheapest.