
Welcome to LLM Fundamentals & Fine-Tuning. This opening lecture introduces the course, explains what you will build, and shows how every section connects to a single goal: understanding large language models well enough to adapt them to your own tasks.
We begin with a roadmap of the full journey. You will start with the core ideas behind LLMs, including tokens, embeddings, and the Transformer architecture. From there you will learn how models are pretrained, how they generate text, and how to set up a local development environment. The second half of the course focuses on practical customization: deciding when to fine-tune, preparing high-quality datasets, evaluating models, running supervised fine-tuning, applying LoRA and QLoRA, and finally deploying your model in a simple application.
This lecture also explains how the course is organized. Most sections combine short conceptual lectures with a hands-on lab, so you will not only read about each technique but also run it yourself. We cover what background helps most, such as basic Python and a general comfort with the command line, and we clarify that you do not need a research background or an expensive workstation to follow along.
You will also hear how to get the most from the course: watch each concept lecture first, then complete the lab, and compare your results with the examples shown. By the end of this lecture you will know what the course covers, what you will be able to do when you finish, and how to approach the material so that each section builds naturally on the one before it.
This lecture answers a foundational question: what exactly is a large language model, and why has it become one of the most important technologies in modern software? We start with a plain-language definition. An LLM is a neural network trained on very large collections of text to predict what comes next in a sequence. That simple objective, repeated across billions of examples, produces a system that can summarize, translate, answer questions, write code, and follow instructions.
We then look at why scale matters. As models grow in parameters, training data, and compute, they begin to show capabilities that smaller models do not, such as following complex instructions or reasoning through multi-step problems. You will learn what parameters actually are, why they are often described in billions, and how model size relates to cost, speed, and quality.
Next we explore why LLMs matter in practice. We review common applications, including customer support assistants, document analysis, coding tools, search, content drafting, and data extraction, and we discuss how teams decide whether an LLM is the right tool for a given problem. We also touch on the business and engineering reasons organizations choose to customize models instead of relying only on general-purpose chat tools.
Finally, we set expectations. LLMs are powerful but imperfect, and understanding their basic mechanics is the first step toward using them responsibly. By the end of this lecture you will be able to explain what an LLM is, describe why scale changed the field, and name several realistic use cases that motivate the rest of the course.
Terms like generative AI, natural language processing, and foundation models are often used interchangeably, but they describe different layers of the same landscape. This lecture sorts them out so that you can follow the rest of the course, and any industry discussion, with confidence.
We begin with natural language processing, or NLP, the long-standing field concerned with helping computers work with human language. You will see how classic NLP tasks such as classification, translation, named entity recognition, and summarization were once handled by separate, specialized models, each trained for a single job.
Next we introduce generative AI, which refers to systems that create new content such as text, images, audio, or code rather than only labeling existing data. We explain how language models fit within this category and how they differ from discriminative models that predict a label.
We then cover foundation models. These are large models trained on broad data that can be adapted to many downstream tasks, either through prompting or through additional training. You will learn why this idea changed the way teams build AI products: instead of training a new model for every task, you start from a capable base and customize it.
Finally, we connect these ideas to the workflow used throughout the course. A foundation model is pretrained, then often adapted through fine-tuning, and finally deployed for a specific use. After this lecture you will be able to explain how generative AI, NLP, and foundation models relate to one another and where LLMs sit among them.
Not every language model you download behaves the same way, and choosing the wrong type is a common beginner mistake. This lecture explains the three main categories you will encounter: base models, instruction-tuned models, and chat models.
We start with base models. These are produced by pretraining on large amounts of text and are very good at continuing a sequence. Ask a base model a question and it may answer, ramble, or simply generate more questions, because it has learned to predict text rather than to follow directions. You will see examples of this behavior so the difference becomes concrete.
Next we look at instruction-tuned models. These start from a base model and receive additional supervised training on examples of instructions paired with high-quality responses. The result is a model that reliably tries to complete the task you describe. We explain, at a high level, how this tuning data is structured and why it changes behavior so much.
Then we cover chat models, which are tuned to handle multi-turn conversations with roles such as system, user, and assistant. You will learn why chat models depend on specific message formats and why using the wrong format can quietly degrade results.
We finish with practical guidance on choosing between these types. If you plan to fine-tune, which starting point is best? When is a base model preferable? By the end you will be able to identify each model type from its name and documentation and pick the right one for your goal.
Understanding what LLMs can and cannot do is just as valuable as knowing how they work. This lecture gives you a realistic picture of their strengths and limits so that you can design better projects and avoid costly surprises.
We begin with strengths. LLMs are excellent at tasks involving language patterns: drafting and rewriting text, summarizing long documents, extracting structured information, translating between languages, explaining concepts, generating and reviewing code, and answering questions when given relevant context. You will see examples of each and learn why they work well.
We then examine the limitations. LLMs can produce confident but incorrect statements, a behavior commonly called hallucination. They have a fixed knowledge cutoff, so they do not know about events after training. They can struggle with precise arithmetic, long chains of logic, and tasks that require up-to-date or private data. They are also sensitive to how a prompt is worded, and they can reflect biases found in their training data.
Next we discuss how these limitations shape engineering decisions. Techniques such as providing context in the prompt, retrieval, tool use, validation of structured output, and fine-tuning can each reduce certain failure modes, but none removes the need for evaluation and human oversight.
Finally, we introduce simple habits for working safely: verify important claims, test on realistic examples, and measure results rather than relying on impressions. After this lecture you will be able to describe common LLM failure modes and decide whether a proposed use case is a good fit.
This lecture introduces the end-to-end project that gives the course its practical backbone. Rather than studying techniques in isolation, you will follow one fine-tuning project from a raw idea to a working, evaluated, and deployable model.
We start by describing the project goal and why it was chosen. A clear, narrow task makes it easier to build a dataset, define success, and see measurable improvement after training. You will learn how to think about a target behavior, such as responding in a consistent style, following a specific format, or handling a particular domain.
Next, we outline the project stages and show where each one appears in the course. First you will define the objective and gather or create training data. Then you will prepare and tokenize that data, measure the original model's performance to establish a baseline, and run supervised fine-tuning. After that you will explore parameter-efficient methods like LoRA and QLoRA, evaluate the results more rigorously, and finally serve the model locally behind a simple interface.
We also discuss why baselines matter from the very beginning. Without knowing how the unmodified model performs, you cannot tell whether fine-tuning actually helped.
By the end of this lecture you will understand the shape of the project, the artifacts you will produce along the way, and how each section contributes to the final result. This gives you a mental map to return to whenever you wonder why a particular technique matters.
It is time to get hands-on. In this lab you will run a language model on your own machine and carefully examine how it responds. The goal is not to build anything complex yet, but to develop intuition by observing a real model's behavior.
You will start by loading a small open-weight model using a Python workflow and sending it a series of prompts. We will walk through each step so you understand what the code does: loading the model and tokenizer, encoding a prompt, generating output, and decoding the result back into readable text.
Then you will explore. Try simple factual questions, formatting requests, instructions with constraints, and prompts the model is likely to struggle with. Notice where it follows directions, where it drifts, and where it produces confident but wrong answers. Compare how a small change in wording affects the response, and observe how the same prompt can produce different outputs across runs.
As you experiment, we recommend keeping short notes about what works and what fails. These observations become valuable later, when you design evaluation sets and measure whether fine-tuning improved the model.
We also talk about practical issues, such as response speed on your hardware, memory use, and what to do if the model does not fit on your machine. By the end of this lab you will have run a model locally, inspected its responses critically, and gathered first-hand evidence of the strengths and limits discussed earlier in the section.
This lecture provides the Hands-On Lab Package that accompanies the course. Think of it as your central toolkit: a single place to find the materials you will use while following the practical lectures, so that you can focus on learning rather than hunting for files.
We explain how to download the package and how to organize it on your computer. A tidy workspace helps you keep each lab separate and makes it easier to return to earlier exercises. We recommend creating a dedicated project folder and keeping your Python environment alongside it so that dependencies stay isolated.
The lecture also shows how the package maps to the course structure. Each hands-on lecture refers to specific materials, and you will learn how to match them to the section you are working on. We describe a simple workflow for each lab: read the instructions, run the setup steps, execute the exercises in order, and compare your results with the expected outcomes.
Because tools and libraries change over time, we also discuss how to handle version differences. If a library has been updated since the course was recorded, check the documentation, pin versions when you need reproducible results, and consult the course discussion area if you get stuck.
By the end of this lecture you will have the lab materials ready, know how they are organized, and understand how to use them effectively throughout the rest of the course.
Language models cannot read text the way people do. Before any computation happens, text must be converted into numbers, and this lecture explains how that conversion works through tokenization.
We begin with the basic idea. A tokenizer splits text into smaller units called tokens and maps each one to an integer ID from a fixed vocabulary. Tokens are not always whole words; they may be word pieces, punctuation, spaces, or even single characters. You will see why splitting text into subword units gives models a practical balance: common words stay intact, while rare or unfamiliar words can be assembled from smaller parts.
Next, we introduce the main subword approaches, including Byte Pair Encoding and related methods, and explain at a conceptual level how a vocabulary is learned from a large text corpus. You will learn why different models use different tokenizers and why a tokenizer must always match the model it was trained with.
We also cover consequences that affect real projects. Token counts determine cost, speed, and how much text fits into a context window. Numbers, code, and non-English languages often split into more tokens than plain English, which changes how efficiently a model can handle them. Special tokens, such as those marking the start or end of a sequence, play important roles that you will rely on during fine-tuning.
By the end of this lecture you will understand how text becomes token IDs, why tokenization choices matter, and how to reason about token counts in your own work.
Once text has been converted into token IDs, a model still needs a way to represent meaning. This lecture introduces embeddings, the vector representations that allow neural networks to work with language in a mathematical way.
We start with the limitation of raw IDs. An integer such as 4821 carries no information about what a token means or how it relates to other tokens. Embeddings solve this by mapping every token to a list of numbers, a vector, in a high-dimensional space. During training, the model adjusts these vectors so that tokens used in similar contexts end up close to one another.
You will build intuition for this idea through examples. Words with related meanings tend to cluster, and directions in the space can capture relationships, such as differences in tense, plurality, or topic. We explain how similarity is measured using distance and cosine similarity, and why these measures matter for tasks such as search and retrieval.
We then connect embeddings to the model architecture. The embedding layer is the first step in an LLM, turning token IDs into vectors that flow through later layers. We also distinguish between the token embeddings inside a language model and standalone embedding models used for semantic search and RAG.
By the end of this lecture you will be able to explain what an embedding is, why it is learned rather than hand-designed, and how vector similarity captures aspects of meaning.
The Transformer is the architecture behind nearly every modern large language model. This lecture gives you a clear, high-level map of how it is built, so that later lectures on attention and layers have a solid frame of reference.
We begin with the problem Transformers solved. Earlier sequence models processed text one step at a time, which made training slow and made long-range relationships hard to learn. The Transformer replaced this with attention, allowing every position in a sequence to look at every other position and enabling training to run in parallel on modern hardware.
Next, we walk through the major components. Input tokens become embeddings, positional information is added, and the data passes through a stack of identical blocks. Each block combines an attention mechanism with a feed-forward network, wrapped with residual connections and normalization that keep training stable. At the end, an output layer converts the final vectors into scores over the vocabulary.
We also compare the encoder-decoder design from the original paper with the decoder-only designs used by most modern chat and generative models, and explain why decoder-only models are well suited to text generation.
Finally, we discuss how scale emerges from this design: more layers, wider vectors, and more attention heads produce larger models. After this lecture you will be able to sketch the Transformer data flow and name the role of each major component.
Self-attention is the central idea that makes Transformers work. This lecture explains it step by step, using the concepts of queries, keys, and values to make the mechanism feel intuitive rather than mysterious.
We begin with the question attention answers: when processing a given token, which other tokens in the sequence matter, and how much? Consider the word "it" in a sentence; to understand it, the model must look back at the noun it refers to. Self-attention provides a learned way to do exactly that.
You will learn how each token's vector is projected into three different vectors. The query represents what a token is looking for, the key represents what a token offers, and the value carries the information that will be passed along. Comparing a query with all keys produces similarity scores, which are scaled and passed through a softmax to become attention weights that sum to one. These weights are then used to combine the values into a new, context-aware representation.
We walk through a small numerical example so that you can see each matrix multiplication and understand the shapes involved. We also explain why scaling matters for numerical stability and why attention cost grows with sequence length.
By the end, you will be able to describe the self-attention computation, interpret an attention weight, and explain why this mechanism lets models capture context across an entire passage.
Single attention can only capture one pattern of relationships at a time. This lecture explains multi-head attention, which lets a model look at the same text from several perspectives at once, and causal masking, which makes text generation possible.
We start with multi-head attention. Instead of computing one set of queries, keys, and values, the model splits its representation into several smaller heads, each with its own learned projections. Different heads can specialize, and researchers have observed heads that track syntax, nearby words, repeated patterns, or long-distance references. The outputs of all heads are concatenated and mixed through another learned projection, giving the next layer a richer representation.
Then we turn to causal masking. A language model is trained to predict the next token, so it must not be allowed to see future tokens during training. A causal mask blocks attention to positions that come later in the sequence, ensuring that each token only uses information from itself and earlier tokens. You will see how this mask is applied to the attention scores before the softmax, and how it allows the model to train on every position in a sequence in parallel.
We also contrast causal attention with the bidirectional attention used by encoder models.
By the end of this lecture you will understand why models use multiple heads, how masking enforces left-to-right prediction, and how both ideas appear in real implementations.
Attention alone does not make a complete Transformer. This lecture covers the remaining pieces that turn attention into a deep, stable, and expressive model: positional encoding, feed-forward networks, and the layer structure that stacks them together.
We begin with a puzzle. Self-attention treats its input as a set, so on its own it cannot tell whether a word comes first or last. Positional encoding solves this by injecting information about token order. You will learn about the original sinusoidal approach, learned position embeddings, and rotary position embeddings, which are widely used in modern open models and influence how well a model handles longer contexts.
Next, we examine the feed-forward network inside each block. After attention mixes information across tokens, this network processes each token independently, applying non-linear transformations that increase the model's capacity. A large share of a model's parameters lives here.
We then explain residual connections and layer normalization, which keep gradients healthy and make it practical to stack dozens of layers. You will see how repeating the same block many times lets the model build progressively more abstract representations.
Finally, we connect these elements to model size, showing how layer count, hidden dimension, and head count determine parameter totals. After this lecture you will be able to describe a full Transformer layer and explain the purpose of each component within it.
In this hands-on lecture you will see tokenization and attention for yourself using Python. Reading about tokens and attention weights is useful, but inspecting real values on a real model builds a much stronger intuition.
You will begin by loading a tokenizer and encoding several different strings. Compare how plain English sentences, rare words, numbers, code snippets, and text in other languages are split. Count the tokens, decode them back, and notice how spaces and punctuation are handled. This exercise makes the cost and context-window discussions from earlier lectures concrete.
Next, you will load a small Transformer model and run a short passage through it while requesting attention outputs. We will guide you through extracting the attention weights from a chosen layer and head, and you will visualize them as a heatmap. Look for patterns: which tokens attend to the previous token, which attend to the beginning of the sequence, and how pronouns or repeated words behave.
We encourage you to experiment. Change the input sentence, try different layers, and compare heads within the same layer. Pay attention to the effect of causal masking by checking that no token attends to a later position.
By the end of this lab you will have tokenized text, inspected real attention patterns, and developed a practical feel for how the concepts from this section appear in working code.
This lecture explains how large language models acquire their broad abilities through pretraining, the first and most resource-intensive stage in a model's life.
We begin with the data. Pretraining uses enormous collections of text drawn from web pages, books, articles, code repositories, and other sources. You will learn why data scale and diversity matter, and why teams invest heavily in filtering, deduplication, and quality control before training starts. Low-quality or repetitive data can harm a model, while carefully curated data can improve it substantially.
Next, we describe the training process at a conceptual level. The model reads sequences of tokens, makes predictions, measures its errors, and updates its parameters millions of times. We discuss why this requires large clusters of accelerators, what training runs cost, and why most practitioners start from an existing pretrained model rather than training their own.
We also cover what the model actually learns. Without any explicit labeling, pretraining teaches grammar, facts, common sense patterns, coding conventions, and the style of many kinds of writing. At the same time, the model inherits gaps, biases, and errors present in its data.
Finally, we connect pretraining to the rest of the course. Fine-tuning builds on the knowledge gained here, adjusting behavior rather than teaching language from scratch. After this lecture you will understand what pretraining involves, what it produces, and why it makes fine-tuning practical.
The core training objective of most modern language models is surprisingly simple: predict the next token. This lecture explains how that single task leads to such capable systems.
We start with the formal idea of language modeling. Given a sequence of tokens, the model outputs a probability distribution over every token in its vocabulary, representing how likely each one is to come next. During training, the correct next token is known from the text itself, so no human labeling is needed. You will see how a single passage produces many training examples, one for each position.
Next, we explain why this objective is so powerful. To predict the next word well across diverse text, a model must learn grammar, factual associations, reasoning patterns, and writing conventions. We illustrate this with examples where accurate prediction requires understanding context, such as completing a code function or continuing a logical argument.
We also contrast causal language modeling with other objectives, such as masked language modeling used by encoder models, and clarify why generative chat models rely on the causal approach.
Finally, we preview how the same objective is reused in fine-tuning. When you train on instruction-response pairs, you are still predicting next tokens, only on carefully chosen data. After this lecture you will be able to describe next-token prediction and explain how it supports both pretraining and fine-tuning.
To understand how a model improves during training, you need three connected ideas: loss functions, gradient descent, and backpropagation. This lecture introduces each one in practical, approachable terms.
We begin with the loss function, which measures how wrong a model's predictions are. For language models, the standard choice is cross-entropy loss, which compares the predicted probability for the correct token with the ideal outcome. A lower loss means the model assigns higher probability to the right answer. You will learn how to read loss values and why a related metric, perplexity, is sometimes used.
Next, we explain gradient descent. Imagine the loss as a landscape and the model's parameters as a position within it. The gradient tells us which direction increases the loss fastest, so we step in the opposite direction. You will see how the learning rate controls step size and why a value that is too high or too low causes problems.
Then we cover backpropagation, the algorithm that efficiently computes gradients for every parameter by applying the chain rule backward through the network. We explain this without heavy mathematics, focusing on the intuition.
We close by introducing optimizers such as Adam, which refine plain gradient descent. After this lecture you will understand the training loop and be ready to interpret loss curves during fine-tuning.
Teams often use the phrases pretraining, continued pretraining, and instruction fine-tuning loosely, which creates confusion about what each one achieves. This lecture draws clear lines between them so you can choose the right approach for your goal.
We start with pretraining from scratch. This builds a model's general language ability from a very large corpus and requires substantial compute. It is rarely the right choice for individual practitioners or small teams.
Next, we explain continued pretraining, sometimes called domain-adaptive pretraining. Here you take an existing model and keep training it on additional unlabeled text from a specialized area, such as legal, medical, or technical documents. The objective remains next-token prediction, and the goal is to absorb vocabulary and knowledge from that domain.
Then we cover instruction fine-tuning. This stage uses curated pairs of instructions and desired responses to teach a model how to behave: follow directions, adopt a format, or respond in a particular style. It changes behavior far more than it adds knowledge, and it typically needs much less data and compute.
We compare the three approaches across data requirements, cost, risks, and typical outcomes, and discuss how they can be combined in a pipeline.
After this lecture you will be able to decide which training stage matches your problem and explain why instruction fine-tuning is the main focus of the course.
After a model is trained, it must generate text, and the way it does so is controlled by settings you can adjust. This lecture explains inference and the sampling parameters that shape model output: temperature, Top-K, and Top-P.
We begin with the generation loop. The model produces a probability distribution for the next token, one token is selected, appended to the input, and the process repeats until a stopping condition is reached. How the token is selected makes an enormous difference in the character of the output.
First, we cover greedy decoding, which always picks the most likely token. It is deterministic but can be repetitive and dull. Then we introduce temperature, which reshapes the distribution: low values make the model more focused and predictable, while high values flatten the distribution and increase variety and risk.
Next, we explain Top-K sampling, which restricts choices to the K most likely tokens, and Top-P, or nucleus sampling, which keeps the smallest set of tokens whose combined probability reaches a threshold. You will learn how these controls work together and why they are often combined.
We also discuss practical guidance for different tasks, such as using low temperature for extraction and evaluation, and higher values for creative writing. After this lecture you will be able to choose sensible generation settings and explain how they influence a model's behavior.
Even a very capable model has boundaries. This lecture covers context windows, the nature of model knowledge, and the most common limitations you will meet when building with LLMs.
We start with the context window, the maximum number of tokens a model can consider at once, including both your prompt and its response. You will learn what happens when the limit is exceeded, why longer windows increase memory and compute costs, and why information in the middle of a very long prompt can sometimes be used less reliably.
Next, we examine what a model actually knows. Its knowledge is stored implicitly in its parameters, was fixed at training time, and has a cutoff date. It can be incomplete, outdated, or wrong, and it has no built-in way to verify claims. This explains hallucinations, in which a model produces fluent but unsupported statements.
We also discuss other limitations, including sensitivity to prompt wording, difficulty with exact calculation, inconsistent behavior across runs, and biases from training data. For each limitation we outline typical mitigations, such as supplying relevant context, using retrieval, validating outputs, and fine-tuning for specific behaviors.
By the end of this lecture you will be able to explain how context limits work, why models hallucinate, and how to plan around these weaknesses when designing LLM applications.
This lab turns the concepts from the section into direct observation. You will inspect token probabilities and experiment with text generation settings to see exactly how a model decides what to write.
You will start by loading a small language model and passing in a short prompt. Instead of immediately generating text, you will request the raw scores for the next token, convert them to probabilities, and display the top candidates. This makes the idea of a probability distribution over the vocabulary tangible, and you can see how confident or uncertain the model is at each step.
Next, you will generate text under different settings. Compare greedy decoding with sampling, then vary temperature from very low to high and observe how output changes in focus, variety, and accuracy. Add Top-K and Top-P limits and see how they trim unlikely tokens. Run the same prompt several times to notice which settings give repeatable results and which do not.
We also explore how prompt wording changes the distribution. A slightly different phrasing may shift probabilities toward a very different answer, which explains many surprising behaviors.
By the end of this lab you will be able to read token probabilities, tune generation parameters deliberately, and choose settings that fit tasks such as extraction, question answering, and creative writing.
Before you install any software, it helps to know what hardware LLM work actually demands. This lecture explains the roles of CPUs, GPUs, system RAM, and VRAM so that you can judge what your machine can handle and plan accordingly.
We begin with the CPU, which handles general-purpose tasks, data loading, and orchestration. While CPUs can run small models, they are slow for the large matrix operations that dominate deep learning. GPUs, by contrast, perform thousands of operations in parallel and are the standard choice for both training and inference.
Next, we focus on memory, the factor that most often limits practitioners. System RAM holds your data and program state, while VRAM, the memory on the GPU, must hold the model weights, activations, gradients, and optimizer states during training. You will learn a practical rule of thumb for estimating memory: parameter count multiplied by bytes per parameter, plus overhead that can multiply the requirement several times during full fine-tuning.
We then connect memory to the techniques covered later in the course. Lower numerical precision, LoRA, and quantization all exist largely to reduce VRAM requirements so that larger models fit on modest hardware.
We also discuss options if you lack a suitable GPU, including smaller models, cloud notebooks, and rented instances. After this lecture you will be able to estimate memory needs for a given model and choose a realistic setup for the labs.
A clean development environment saves hours of frustration. In this lecture you will install Python and create an isolated environment for the course so that library versions do not conflict with other projects on your machine.
We begin by checking which version of Python you have and explaining which versions work best with current machine learning libraries. If you need to install or upgrade, we walk through the recommended approach for your operating system.
Next, we explain why isolation matters. Machine learning packages depend on specific versions of one another, and installing everything globally quickly leads to broken setups. You will create a virtual environment using standard tooling, activate it, and confirm that your shell is using the right interpreter. We also mention alternatives, such as conda, and when you might prefer them.
Then we install a base set of packages using pip and show how to record dependencies in a requirements file, which makes your setup reproducible and easy to rebuild. You will learn how to verify an installation by importing the packages and printing their versions.
We finish with good habits: naming environments clearly, keeping one per project, avoiding mixed package managers, and knowing how to delete and recreate an environment when something goes wrong. After this lecture your machine will be ready for the PyTorch and Hugging Face work that follows.
PyTorch is the deep learning framework behind most open LLM tooling, and understanding its basics will make every later lab easier to follow. This lecture introduces the parts of PyTorch you need for working with language models.
We start with tensors, the multi-dimensional arrays at the heart of the library. You will create tensors, inspect their shapes and data types, and perform basic operations. We explain how tensors can live on a CPU or a GPU, and how to move them between devices.
Next, we cover automatic differentiation. PyTorch records operations and computes gradients for you, which is what makes training possible. You will see a tiny example in which a gradient is calculated and used to update a value, linking back to the gradient descent discussion from earlier.
Then we introduce modules and the typical training loop: a forward pass, a loss calculation, a backward pass, and an optimizer step. Although Hugging Face tools will hide much of this later, knowing what happens underneath helps you debug problems and interpret errors.
We also show how to check whether a GPU is available, how to select the right device, and how data types such as float16 and bfloat16 affect memory. After this lecture you will be comfortable reading basic PyTorch code and checking your environment for GPU support.
The Hugging Face Transformers library is the main toolkit used in this course for loading, running, and training language models. This lecture shows you how it is organized and how to use its most important pieces.
We begin with the Hugging Face Hub, a repository of models, datasets, and documentation. You will learn how to find a model, read its model card, check its license, and understand naming conventions that indicate size, type, and variant.
Next, we introduce the core classes. The tokenizer converts text to token IDs and back, and the model class loads pretrained weights and performs the computation. You will use the Auto classes, which choose the correct architecture automatically, and see how a single identifier is enough to download everything you need. We explain local caching so that you understand where files are stored and how to manage disk space.
Then we demonstrate text generation, including how to pass in inputs, set generation parameters, and decode outputs. We also discuss choosing precision and device placement when loading a model so that it fits in memory.
Finally, we introduce the pipeline helper for quick experiments and explain when to prefer the lower-level approach. After this lecture you will be able to load a model and tokenizer, generate text, and navigate the Hub effectively.
Good fine-tuning depends on handling data efficiently, and Hugging Face provides libraries built for the job. This lecture introduces the Datasets and Tokenizers libraries and shows how they fit into an LLM workflow.
We begin with Datasets. You will learn how to load public datasets from the Hub and local files such as JSON, JSONL, and CSV into a consistent format. We explain how datasets are stored on disk and memory-mapped, which allows you to work with data far larger than your RAM. You will practice inspecting examples, selecting columns, filtering rows, and splitting data into training and validation sets.
Next, we demonstrate the map function, which applies a transformation across an entire dataset. This is the standard way to format prompts and tokenize examples at scale, and we explain batching and caching so that processing stays fast.
Then we turn to the Tokenizers side. You will see how a pretrained tokenizer is applied to a dataset, how padding and truncation options work, and how to inspect special tokens. We touch on the idea that the fast tokenizer implementation is written for speed.
By the end of this lecture you will be able to load data, transform it, tokenize it, and prepare it for training, giving you a foundation for the data preparation sections ahead.
There are two common ways to work with models locally, and they serve different purposes. This lecture compares using Ollama for inference with using Python libraries for training and customization, so that you can pick the right tool for each task.
We start with Ollama, a tool that makes it easy to download and run models on your own computer with simple commands. It handles model packaging, optimized inference, and a local API, which makes it ideal for quickly trying a model, building demos, or serving a model to an application. You will learn what it does well and what it abstracts away.
Next, we turn to Python libraries such as Transformers, PEFT, and TRL. These give you direct control over data, training loops, and model weights, which is essential for fine-tuning. The tradeoff is a more involved setup and more responsibility for memory management and configuration.
We compare the two across several dimensions: ease of use, flexibility, hardware efficiency, support for training, and typical file formats. We also explain how they work together in practice: you might fine-tune a model with Python libraries, convert or package it, and then run it through Ollama for convenient local use.
After this lecture you will understand which tool fits each stage of a project and will be ready to use both throughout the course.
In this hands-on lab you will download a small open-weight model and run it on your own machine, bringing together the environment setup from the rest of the section.
You will begin by choosing a model that suits your hardware. We review how to read a model card, check parameter count, license, and recommended usage, and estimate whether it will fit in your available memory. A small model is intentionally chosen so that nearly everyone can complete the exercise.
Next, you will download the model and tokenizer using Hugging Face Transformers and run a first generation. We confirm that PyTorch can see your device, select an appropriate precision, and examine how long loading and generation take. You will also try the same model through a local inference tool to compare convenience and speed.
Then you will experiment with prompts, generation settings, and response length. Record how quickly the model responds, how much memory it uses, and how its outputs look. These observations become reference points for later sections, when you compare baseline behavior with fine-tuned behavior.
Finally, we cover troubleshooting for common problems, including out-of-memory errors, slow downloads, authentication requirements for gated models, and package version mismatches. By the end of this lab you will have a working local setup and a model you can use in every following exercise.
Before you consider training anything, you should push prompting as far as it will go. This lecture presents prompt engineering as the cheapest, fastest, and most reversible way to customize a model, and shows how to do it systematically.
We begin with the anatomy of a good prompt: a clear role or context, a precise task description, relevant input, constraints on format and length, and, when helpful, examples. You will see how vague instructions lead to vague results, and how small changes such as stating the audience, specifying the output structure, or asking for step-by-step reasoning can noticeably improve quality.
Next, we cover system prompts and how chat models use them to set persistent behavior, tone, and rules. We also discuss techniques for reducing errors, such as asking the model to quote sources from supplied text, to say when it is unsure, or to return output in a strict format like JSON that your code can validate.
Then we talk about treating prompts as engineered artifacts. Keep versions, test them against a fixed set of examples, and record what changed. This habit becomes essential when you later need to prove that fine-tuning beats a well-crafted prompt.
By the end of this lecture you will be able to write structured prompts, iterate on them methodically, and recognize the signs that prompting alone has reached its limits.
Zero-shot and few-shot learning describe how much guidance you give a model inside the prompt, and understanding the difference helps you get strong results without any training. This lecture explains both approaches with practical examples.
We start with zero-shot prompting, where you describe the task and ask the model to perform it with no examples. Modern instruction-tuned models handle many tasks this way, such as summarizing, classifying sentiment, or translating, because their training already exposed them to similar instructions. We discuss when zero-shot is enough and how to phrase requests so the model understands the desired output.
Next, we introduce few-shot prompting, where you include a handful of input-output examples before the real query. The model infers the pattern, including format, tone, and labeling conventions, directly from those examples. You will learn how to choose representative examples, how ordering and balance can influence results, and why inconsistent examples can confuse the model.
We also examine the tradeoffs. Few-shot examples consume context window space, increase cost and latency on every request, and may still fail to produce reliable behavior at scale. These costs are one of the main reasons teams turn to fine-tuning, which bakes the pattern into the model itself.
After this lecture you will be able to choose between zero-shot and few-shot prompting and explain what in-context learning can and cannot achieve.
Retrieval-Augmented Generation, or RAG, gives a language model access to information it was never trained on. This lecture explains how RAG works, what problems it solves, and where it falls short.
We begin with the motivation. A model's knowledge is frozen at training time and does not include your private documents, recent events, or constantly changing data. Rather than retraining, RAG retrieves relevant text at question time and places it in the prompt, so the model can answer using supplied evidence.
You will learn the typical pipeline. Documents are split into chunks, converted into embeddings, and stored in a vector database. When a user asks a question, the question is embedded, the most similar chunks are retrieved, and they are combined with the question in a prompt. The model then generates an answer grounded in that context. We discuss the key design choices: chunk size, retrieval count, metadata filtering, and re-ranking.
We also cover strengths and weaknesses. RAG makes it easy to update knowledge, supports citations, and reduces hallucination when retrieval is good. However, it adds infrastructure, can retrieve irrelevant passages, and does not change how the model writes or reasons.
By the end of this lecture you will be able to describe the RAG pipeline, identify tasks where it is the right choice, and explain why it addresses knowledge problems rather than behavior problems.
Fine-tuning is often described as teaching a model something new, but what actually changes inside it? This lecture gives you an accurate mental model of what fine-tuning does and does not do.
We start with the mechanics. A pretrained model has billions of parameters that encode its general abilities. Fine-tuning continues training on a smaller, targeted dataset, nudging those parameters so that the model assigns higher probability to the responses you want. The architecture stays the same; only the weights, or small added adapter weights, are modified.
Next, we discuss what fine-tuning is good at. It excels at changing behavior: adopting a consistent tone, following a complex output format, specializing in a task like classification or extraction, and responding reliably to domain-specific phrasing. It can also reduce prompt length, since instructions and examples no longer need to be repeated in every request.
We are equally clear about its limits. Fine-tuning is an unreliable way to inject large amounts of new factual knowledge, it cannot guarantee that facts stay accurate, and a poorly designed run can cause catastrophic forgetting, where the model loses useful general abilities.
Finally, we preview the costs, including data creation, compute, evaluation, and maintenance. After this lecture you will understand the real effect of fine-tuning and be able to set realistic expectations for your own project.
RAG and fine-tuning are often presented as competitors, but in practice they solve different problems and work well together. This lecture shows how to combine them in real-world applications.
We begin with a simple division of responsibilities. RAG supplies up-to-date, verifiable knowledge at request time, while fine-tuning shapes how the model behaves: its tone, structure, reasoning habits, and ability to use retrieved material effectively. When both are needed, each covers the weaknesses of the other.
You will walk through example architectures. In a customer support assistant, retrieval can bring in current policy documents, while a fine-tuned model answers in the company's voice, follows escalation rules, and returns structured responses. In a document analysis tool, fine-tuning can teach the model to cite passages consistently and to say when the retrieved context does not contain an answer.
We also cover how to train a model to work well with retrieval. This includes building training examples that contain retrieved context, teaching the model to ignore irrelevant passages, and rewarding grounded answers over unsupported ones.
Finally, we discuss evaluation and maintenance. A combined system has more moving parts, so you must test retrieval quality and generation quality separately as well as end to end. After this lecture you will be able to design a hybrid system and justify which responsibilities belong to each component.
Choosing how to customize a model is one of the most consequential decisions in an LLM project. This lecture compares four options side by side: prompting, retrieval-augmented generation, fine-tuning, and training from scratch.
We evaluate each approach across the same dimensions so the comparison is fair. These include upfront cost, time to first result, data requirements, technical skill needed, ongoing maintenance, ability to inject new knowledge, ability to change behavior, latency and inference cost, and risk of regressions.
Prompting is fast and cheap but limited by context length and consistency. RAG excels when knowledge changes frequently or must be traceable to sources, though it adds retrieval infrastructure. Fine-tuning gives strong control over style, format, and specialized task performance, at the cost of data preparation, training, and evaluation effort. Training from scratch offers maximum control but demands enormous data and compute, making it appropriate only for a small number of organizations.
We then offer a practical decision sequence: start with prompting, add retrieval if knowledge is the gap, fine-tune if behavior is the gap, and only consider pretraining if nothing else can meet your requirements.
After this lecture you will be able to match a problem to the simplest effective approach and explain your reasoning clearly to teammates and stakeholders.
This practical activity asks you to apply everything from the section by building a decision matrix for choosing the right customization approach. The goal is to turn a loose discussion into a repeatable, documented decision.
You will begin by listing several realistic scenarios, such as a support chatbot that must quote current policies, a model that must always return valid JSON, an internal assistant that must answer from private reports, and a writing tool that must match a specific brand voice. For each scenario, write down the real requirement: is it about knowledge, behavior, format, cost, or latency?
Next, you will define evaluation criteria and assign weights based on what matters most for your project. Then score prompting, few-shot prompting, RAG, fine-tuning, and combined approaches against each criterion, using a simple scale and short justifications. We provide a template and a worked example to guide you.
After scoring, calculate totals, but treat them as a conversation starter rather than an automatic answer. Examine close results, identify risks, and note what experiments could settle uncertainty, such as testing a strong prompt before committing to a dataset.
By the end of this activity you will have a reusable matrix and a clear rationale for your own fine-tuning project, which carries forward into the data work of the next section.
Every successful fine-tuning project begins with a precise objective. This lecture teaches you to define exactly what you want the model to do, so that data collection, training, and evaluation all point in the same direction.
We start with the difference between a vague goal, such as making the model better at support, and a testable objective, such as classifying incoming tickets into eight categories with at least ninety percent accuracy, or producing responses that follow a fixed template. You will learn to state the task, the input, the expected output, and the success criteria in a single clear description.
Next, we cover desired model behavior in detail. This includes tone and style, level of detail, handling of ambiguous or out-of-scope requests, refusal behavior, and format constraints. Writing these expectations down creates a specification that annotators and reviewers can follow consistently.
We also discuss scope. Narrow, well-defined tasks usually fine-tune more reliably than broad ones, and trying to teach too many behaviors at once makes problems hard to diagnose. You will see how to define boundaries and decide what should be left to prompting or retrieval.
Finally, we link the objective to measurement, since you cannot evaluate what you have not defined. After this lecture you will be able to write a fine-tuning specification that guides every later decision.
Training data is the foundation of fine-tuning, and where it comes from matters both technically and legally. This lecture explains how to identify suitable data sources and how to understand licensing before you use them.
We begin with common source categories: internal company documents, support transcripts, product documentation, public datasets, open-licensed corpora, and data you create or commission yourself. For each, we discuss typical quality, volume, relevance to your task, and the effort needed to clean it.
Next, we turn to licensing and usage rights. You will learn to read dataset cards and license terms, distinguish permissive licenses from restrictive ones, and notice conditions such as attribution requirements, non-commercial limits, and restrictions on using outputs to train other models. We also explain that base models have their own licenses, which can affect how you may deploy a fine-tuned version.
Then we cover provenance and documentation. Keep a record of where every dataset came from, what license applies, when it was collected, and what filtering you applied. This protects you if questions arise later and makes your work reproducible.
We close with a simple checklist for evaluating a source before using it. After this lecture you will be able to choose relevant data sources, assess their legal and ethical suitability, and document your decisions responsibly.
Training examples can come from several origins, and each has distinct strengths and weaknesses. This lecture compares human-curated, public, and synthetic data so that you can combine them wisely.
We begin with human-curated data, which is written or reviewed by people who understand the task. It is usually the highest quality and best aligned with your needs, but it is slow and expensive to produce. We discuss how to use human effort efficiently, for instance by creating a smaller gold set for evaluation and examples for guiding other data.
Next, we cover public datasets. These offer scale and convenience and are useful for experimentation, but they may not match your domain, may contain errors, and may carry licensing limits. We explain how to inspect them critically rather than assuming they are clean.
Then we introduce synthetic data, generated by a stronger model or by templates and rules. Synthetic data is fast and cheap and can cover edge cases, but it can be repetitive, inherit the generator's mistakes, and lack realistic variety. You will learn practices that improve it, such as diverse seed prompts, filtering, and human review of samples.
We finish by discussing blended datasets and how to track the contribution of each source. After this lecture you will be able to design a data mixture that balances quality, cost, and coverage.
Consistent, high-quality examples do not happen by accident; they come from clear annotation guidelines. This lecture shows you how to write guidelines and create examples that teach a model exactly what you intend.
We begin with the purpose of guidelines. They turn your fine-tuning objective into concrete instructions that anyone can follow, which reduces disagreement between annotators and prevents quiet drift in style over time. A good guideline defines the task, lists allowed and disallowed behaviors, describes the required format, and explains how to handle ambiguous cases.
Next, we examine what makes an example high quality. The instruction should be clear and realistic, the response should be correct, complete, and well formatted, and the pair should reflect real usage rather than artificial wording. You will see strong and weak examples side by side and learn to spot problems such as contradictory answers, unnecessary verbosity, and hidden errors.
We also cover the review process. Use a pilot round, compare annotators' work, resolve disagreements, and update the guidelines when new edge cases appear. Measuring agreement helps you find unclear rules.
Finally, we emphasize variety, including different phrasings, difficulty levels, and failure scenarios. After this lecture you will be able to write practical guidelines and produce examples that make your dataset consistent and trustworthy.
Training data often contains information about real people, and handling it carelessly can create legal, ethical, and security problems. This lecture explains how to identify and manage sensitive information, personally identifiable information, and privacy risks in fine-tuning datasets.
We begin with what counts as sensitive. Names, email addresses, phone numbers, account numbers, health details, credentials, and confidential business information can all appear in support logs, documents, and conversations. You will learn why models can memorize and later reproduce such content, making leaks possible even when the data seems harmless.
Next, we cover practical protection steps. These include collecting only what you need, removing or masking identifiers, replacing real values with realistic placeholders, using pattern matching and named-entity detection to find hidden items, and manually reviewing samples. We also discuss that automated tools miss things, so layered checks are important.
Then we introduce governance basics: understanding consent and regulations that may apply, such as data protection laws, restricting access to raw data, storing it securely, and keeping records of what was removed. We explain why deleting a source file later does not remove information already learned by a trained model.
After this lecture you will be able to build a privacy-conscious data workflow and reduce the risk that your fine-tuned model exposes sensitive information.
A model that scores well on data it has already seen tells you very little. This lecture explains how to split your data into training, validation, and test sets, and how to prevent data leakage that makes results look better than they really are.
We begin with the role of each split. The training set is used to update the model, the validation set guides decisions such as when to stop training and which settings to use, and the test set is kept untouched until the end to give an honest estimate of real-world performance. You will learn typical proportions and when small datasets require a more careful approach.
Next, we focus on leakage. Duplicates and near-duplicates that appear in both training and test data allow the model to memorize answers. Leakage can also happen through related examples from the same document, customer, or conversation, through template reuse, or through synthetic data generated from test items. We show how to detect these problems using exact matching, similarity checks, and grouping by source.
We also discuss stratification so that rare categories appear in every split, and the importance of fixing random seeds to make splits reproducible.
After this lecture you will be able to create trustworthy evaluation splits, find hidden leakage, and protect the integrity of your results.
In this hands-on lab you will build a synthetic instruction-response dataset for a custom assistant, putting the data design principles from this section into practice.
You will start by writing a short specification for your assistant: its purpose, audience, tone, supported tasks, and boundaries. From that specification you will create a set of seed topics and a variety of instruction templates covering different phrasings, difficulty levels, and edge cases, including requests the assistant should decline or redirect.
Next, you will use a language model to generate candidate instruction-response pairs. We show how to write a generation prompt that enforces your guidelines, how to request structured output, and how to vary temperature and seeds to avoid repetitive examples. You will run the generator at a small scale first to check quality before producing more.
Then comes quality control. You will filter out malformed, duplicated, or off-topic samples, scan for sensitive content, review a random sample by hand, and revise your prompts based on the problems you find. Finally, you will split the data into training, validation, and test sets and save it in a reusable format.
By the end of this lab you will have a clean, documented dataset that you can carry into the data preparation and fine-tuning work in the following sections.
Datasets for language models arrive in many shapes, and knowing the common structures will save you hours of confusion. This lecture introduces JSON, JSONL, CSV, and conversational dataset formats and explains when to use each one.
We begin with CSV, a simple table format that works well for flat data such as an instruction column and a response column. We discuss its weaknesses, including trouble with commas, quotation marks, line breaks, and nested information, all of which are common in text.
Next, we cover JSON, which supports nested structures and is widely used for configuration and exchange. We then focus on JSONL, where each line is an independent JSON object. This format is the standard for LLM training data because it can be streamed, appended, inspected line by line, and processed in parallel without loading everything into memory. You will see how a single malformed line can be isolated and fixed.
Then we examine conversational structures, in which each example holds a list of messages with roles such as system, user, and assistant. We compare this layout with simple instruction-response fields and show how to convert between them.
You will also learn to validate files by checking for missing fields, empty values, wrong types, and encoding problems. After this lecture you will be able to choose an appropriate format, read and write each one in Python, and load them into Hugging Face Datasets.
The way a training example is formatted teaches the model how to behave, so choosing a format is a real design decision. This lecture compares three common layouts: instruction-response, prompt-completion, and chat formats.
We start with instruction-response data, where each example has an instruction, an optional input, and a target output. This layout is intuitive and works well for single-turn tasks such as classification, extraction, and rewriting. Next, we cover prompt-completion data, where the model is trained to continue a prompt with a specific completion. It is simple and flexible and often used for narrow tasks with a fixed template.
Then we explain chat formats, in which an example is a sequence of messages with roles. This layout supports system instructions, multi-turn conversations, and tool or context messages, and it matches how most instruction-tuned models were trained.
We discuss the key rule: format your training data to match how you will prompt the model at inference time. Mismatches between training and deployment formats are a frequent cause of disappointing results.
Finally, we show how to convert one format into another and how to decide which suits your project. After this lecture you will be able to structure examples correctly for your task and base model.
Chat models do not simply read your messages; they expect them to be wrapped in a precise template with special tokens. This lecture explains chat templates, special tokens, and role-based messages, and why getting them right matters so much.
We begin with roles. A conversation consists of messages labeled system, user, and assistant, and each role tells the model who is speaking and how to treat the text. You will see how a system message sets durable behavior while user and assistant turns carry the dialogue.
Next, we look at special tokens, reserved markers that indicate the start and end of messages, roles, and sequences. Different model families use different markers, so a conversation that works perfectly for one model may behave badly with another. You will learn how a chat template, stored with the tokenizer, converts a list of messages into the exact string the model was trained on.
We demonstrate applying the template with Hugging Face tools, inspecting the formatted output, and adding the generation prompt that signals the assistant should respond. We also cover common mistakes, such as double-adding beginning-of-sequence tokens, omitting end-of-sequence tokens so the model never learns to stop, and mixing templates.
After this lecture you will be able to format conversations correctly for any chat model and diagnose template-related problems.
Raw data is rarely ready for training. This lecture shows how to clean, filter, deduplicate, and normalize a dataset so that your model learns from consistent, high-quality examples rather than noise.
We begin with cleaning. Remove broken encoding, stray markup, boilerplate text, truncated entries, and empty or placeholder fields. We discuss how aggressive to be, since overcleaning can erase useful variation, and how to document each rule.
Next, we cover filtering. Use simple heuristics such as length limits, language detection, and repetition checks to catch problematic examples, and consider model-based scoring for subtler issues like incorrect or unhelpful responses. We emphasize inspecting what each filter removes so that you do not silently discard valuable data.
Then we turn to deduplication. Exact duplicates are easy to remove, but near-duplicates are more common and can cause the model to overweight certain patterns or memorize them. You will learn practical approaches based on normalized text, hashing, and similarity measures.
Finally, we discuss normalization, including consistent whitespace, punctuation, casing conventions, and formatting of structured elements. We recommend recording counts before and after each step. After this lecture you will be able to build a transparent cleaning process that improves data quality and can be repeated.
Once your data is formatted, it must be converted into token sequences that fit the model's limits. This lecture covers tokenization, truncation, sequence length, and packing, the practical details that determine how efficiently and correctly training runs.
We begin with tokenization for training. You will see how formatted conversations become token IDs, how attention masks mark real tokens versus padding, and how special tokens are placed. We highlight the importance of using the exact tokenizer that belongs to your base model.
Next, we discuss sequence length. Every model has a maximum context, and longer training sequences require more memory. You will learn to examine the distribution of token lengths in your dataset and choose a maximum length that covers most examples without wasting resources.
Then we explain truncation and what it can silently break. Cutting off an example may remove the assistant's answer or the end-of-sequence token, teaching the model the wrong behavior. We discuss alternatives, such as filtering overly long examples or splitting documents sensibly.
Finally, we cover padding and packing. Padding short examples to equal length wastes computation, while packing combines several examples into one sequence to improve throughput, provided that attention boundaries are handled properly. After this lecture you will be able to prepare tokenized batches that are efficient and faithful to your data.
Not every token in a training example should contribute to the loss. This lecture explains label masking and how to select exactly which tokens the model learns from.
We begin with the problem. In an instruction-response example, the prompt tokens are context that the model will always receive at inference time, while the response tokens are what we want it to produce. If we compute loss on everything, the model spends effort learning to reproduce prompts and system messages rather than focusing on good answers.
You will learn how labels work in practice. In most frameworks, tokens whose label is set to a special ignore value, commonly negative one hundred, are excluded from the loss calculation. We show how to mask the user and system portions while keeping the assistant response, and how to handle multi-turn conversations where only assistant turns should be trained.
We also discuss pitfalls. Misaligned masks caused by template changes or truncation can accidentally hide the response or include the prompt. Padding tokens must be ignored, and the end-of-sequence token should usually be trained so that the model learns when to stop.
Finally, we show quick ways to inspect labels and confirm correctness. After this lecture you will be able to implement assistant-only loss and verify your masks before spending compute on training.
In this hands-on lab you will create a reusable Python pipeline that prepares and validates data for fine-tuning, combining everything from this section into code you can run again and again.
You will start by loading a raw dataset from JSONL and defining a clear schema that lists required fields and acceptable values. We then write functions to clean text, remove duplicates, and filter out examples that violate your rules, logging how many records each step removes so that nothing disappears unnoticed.
Next, you will convert each record into the chat or instruction format required by your base model, apply its chat template, and tokenize the result. You will measure token length distributions, choose a maximum length, and handle over-length examples deliberately. Then you will build labels with masking so that only assistant tokens contribute to the loss, and add checks that decode a few examples back into text to confirm the masks are correct.
Finally, you will split the data into training and validation sets, save processed outputs and a summary report, and package the steps into functions or a small module with simple tests.
By the end of this lab you will own a dependable, documented pipeline that you can reuse in the fine-tuning sections that follow.
Before you change a model, you need to know how well it performs today. This lecture explains why baseline evaluation matters and how it protects you from wasted effort and misleading conclusions.
We begin with a simple question: how will you know that fine-tuning helped? Without a measured starting point, improvements are guesswork, and impressions based on a few lucky examples can be very misleading. A baseline provides the reference against which every later experiment is compared.
Next, we explain what to measure. This includes task quality, format compliance, safety behavior, latency, and cost, depending on your objective. You will also learn to establish several baselines: the original model with a basic prompt, the same model with your best engineered prompt, and, where relevant, a simple heuristic or a stronger model for context.
We discuss how baselines can reveal surprising results. Sometimes a good prompt already meets your needs, which means fine-tuning may not be worth the cost. In other cases the baseline exposes specific failure categories that guide your data collection.
Finally, we describe good practice: freeze the evaluation set, record every setting, and save outputs for later inspection. After this lecture you will understand why baselines come first and how to treat them as a core part of the workflow.
An evaluation is only as good as the examples behind it. This lecture teaches you how to design a representative held-out evaluation dataset that reflects real usage and gives trustworthy results.
We begin with representativeness. Your evaluation set should mirror the kinds of inputs the model will actually see, including common cases, difficult cases, rare categories, ambiguous requests, and inputs that should be refused or handled gracefully. You will learn to sample from real or realistic sources and to check that the distribution matches your expectations.
Next, we discuss size and balance. A set that is too small produces noisy results, while one that is unbalanced can hide poor performance on important minority cases. We explain how to estimate whether differences between models are meaningful and how to create slices, such as by category or difficulty, for deeper analysis.
Then we emphasize separation. The held-out set must never be used for training, prompt tuning, or hyperparameter decisions, otherwise it stops being an honest measure. We discuss checking for leakage and keeping a final untouched test set.
Finally, we cover labeling and documentation: write clear reference answers or grading criteria, record sources, and version the set. After this lecture you will be able to build an evaluation dataset that supports sound decisions.
Different tasks call for different measurements. This lecture covers the main classification metrics, accuracy, precision, recall, and F1, and shows how to validate structured outputs such as JSON.
We start with accuracy, the share of correct predictions, and explain why it can be misleading when classes are imbalanced. A model that always predicts the majority class may look strong while being useless. Next, we introduce precision, which asks how many of the model's positive predictions were correct, and recall, which asks how many of the true positives it found. You will learn the confusion matrix that underlies these measures and how to read it.
Then we combine precision and recall into the F1 score and discuss macro, micro, and weighted averaging for multi-class problems. We explain how to choose the metric that matches the cost of mistakes in your application.
Next, we turn to structured-output validation. Many LLM applications need valid JSON or a fixed schema. You will learn to check parseability, required fields, allowed values, and types, and to report a format-compliance rate separately from content correctness.
By the end of this lecture you will be able to pick suitable metrics, compute them correctly, and validate structured responses automatically.
Open-ended generation, such as summaries, explanations, and drafts, has no single correct answer, which makes evaluation harder. This lecture shows how to evaluate such outputs reliably using task-specific rubrics.
We begin with why simple overlap metrics are often insufficient. Measures that compare words against a reference can reward surface similarity while missing correctness, helpfulness, or tone. A rubric gives you a more meaningful alternative.
You will learn to design a rubric by identifying the qualities that matter for your task, such as factual accuracy, completeness, relevance, clarity, format adherence, and safety. For each criterion, define a small scale with clear descriptions of what each score means and include examples of strong and weak responses. Keeping criteria separate prevents a single impression from dominating.
Next, we discuss applying rubrics. Human reviewers can score outputs directly, and a strong language model can act as a judge when carefully prompted. We explain the strengths and risks of model-based judging, including bias toward length or style, and recommend calibrating it against human scores.
We also cover consistency: use the same prompts and blind comparisons when possible. After this lecture you will be able to create and apply rubrics that make open-ended evaluation structured and repeatable.
Numbers alone rarely tell you why a model fails. This lecture explains how human evaluation and error classification reveal the patterns behind poor outputs and point directly to improvements.
We begin with when human judgment is needed: for subjective qualities, for validating automated metrics, and for catching issues that scripts cannot see. You will learn how to organize a review, including clear instructions, a consistent rating interface, randomized order, and hidden model identities to reduce bias.
Next, we introduce error classification. Instead of labeling an output simply as bad, assign it to categories such as factual error, missing information, wrong format, ignored instruction, unsafe content, verbosity, or inconsistent tone. Counting these categories shows which problems are most common and which are most severe, and it turns vague dissatisfaction into an actionable list.
We discuss measuring agreement between reviewers, resolving disagreements, and updating guidelines when categories prove unclear. We also describe how error analysis guides the next steps: some failures call for better prompts, others for additional training examples, and others for retrieval or a different base model.
After this lecture you will be able to run a lightweight human review, build an error taxonomy, and use the findings to prioritize improvements.
Evaluation results are only meaningful if they can be reproduced. This lecture explains how to control prompts, sampling settings, and test conditions so that comparisons between models are fair and repeatable.
We begin with prompts. Use the same template, system message, and formatting for every model you compare, and store them in version control. A tiny wording difference can change results, so treat the prompt as part of the experiment.
Next, we discuss sampling settings. Temperature, Top-K, Top-P, maximum tokens, and stop sequences all influence output. For evaluation, you will typically use low temperature or greedy decoding for stability, and when randomness is needed, run multiple samples with fixed seeds and report the average and spread.
Then we cover other conditions: the exact model version and revision, tokenizer, library versions, hardware, precision, and batch settings, since each can subtly affect outputs. We recommend writing all of this into a configuration file and saving it with every result.
Finally, we describe logging raw outputs, scores, and timing so that you can audit and rerun experiments later. After this lecture you will be able to set up an evaluation harness whose results you and your teammates can trust and reproduce.
We also walk through a short checklist to run before every comparison: confirm the evaluation set is unchanged, confirm the prompt template and generation settings match across models, rerun one baseline example to check that results still match what you recorded earlier, and note any differences in hardware or library versions. Following this routine takes only a few minutes and prevents the most common causes of confusing or contradictory evaluation results.
In this hands-on lab you will build a baseline evaluation report for the original, unmodified model, creating the reference point that every later experiment will be compared against.
You will start by loading your held-out evaluation dataset and the base model with a fixed prompt template and fixed generation settings. We then run the model across every example, saving raw outputs along with the prompt, settings, and timing so that the run is fully reproducible.
Next, you will score the results. Depending on your task, this includes accuracy, precision, recall, and F1, structured-output validity, and rubric scores for open-ended responses. You will also classify a sample of failures into an error taxonomy and count the categories to see where the model struggles most.
Then you will assemble a report. Include the setup, metric tables, results broken down by category or difficulty, representative good and bad examples, and a short summary of conclusions and next steps. Visualizing results with simple charts can make patterns easier to see.
Finally, we discuss how to store the report and configuration together, with version information, so that you can reuse them. By the end of this lab you will have a clear, reproducible baseline and a data-driven view of what fine-tuning needs to improve.
Supervised fine-tuning, or SFT, is the most common way to adapt a language model to a specific task or behavior, and this lecture explains exactly what it is and how it works.
We begin with the core idea. You start with a pretrained model and continue training it on a curated set of examples that show the input and the response you want. Because each example includes the correct answer, the training is called supervised. The objective is the same next-token prediction used in pretraining, but applied to targeted data with loss computed on the response tokens.
Next, we walk through the SFT workflow. Define the objective, prepare and validate the dataset, choose a base model, configure training settings, run training while monitoring metrics, evaluate against your baseline, and iterate. You will see how each earlier section feeds into this process.
We discuss what SFT is good at, such as teaching format, style, and task-specific behavior, and what it is not good at, such as reliably adding large amounts of new knowledge. We also contrast SFT with later alignment methods like preference optimization.
Finally, we cover practical expectations: how much data is typically needed, how long training can take, and what kind of improvement to anticipate. After this lecture you will be able to explain SFT clearly and describe the steps of a typical run.
Three settings have an outsized effect on whether fine-tuning succeeds: the learning rate, the number of epochs, and the optimizer. This lecture explains each and gives practical starting points.
We begin with the learning rate, which controls how large each update step is. Fine-tuning generally uses much smaller learning rates than pretraining, because large steps can damage the knowledge a model already has. You will learn symptoms of a rate that is too high, such as unstable or exploding loss, and one that is too low, such as barely moving metrics.
Next, we discuss epochs, the number of complete passes through the training data. Too few epochs leave the model undertrained, while too many encourage memorization and overfitting, especially on small datasets. We explain how to use validation results to decide when more training stops helping.
Then we introduce optimizers. You will learn the role of Adam and its variant AdamW, why they are the standard for transformer training, and how memory-saving variants, including 8-bit optimizers, reduce the footprint of training. We explain the key ideas of momentum and adaptive step sizes without heavy mathematics.
Finally, we provide sensible defaults and a strategy for adjusting one setting at a time. After this lecture you will be able to choose starting values and recognize when to change them.
Memory limits often decide which training settings you can use. This lecture covers batch size, gradient accumulation, and context length, and how to balance them for stable, efficient training.
We start with batch size, the number of examples processed together before an update. Larger batches give smoother gradient estimates and better hardware utilization, but they require more memory. Smaller batches use less memory but produce noisier updates. You will learn to distinguish the per-device batch size from the effective batch size.
Next, we explain gradient accumulation. Instead of updating after every small batch, the trainer accumulates gradients across several steps and then applies one update. This simulates a large batch without needing the memory for it. We walk through the arithmetic and discuss how it interacts with the learning rate and the number of optimization steps.
Then we cover context length. Longer sequences increase memory use sharply, so choose a maximum length based on your actual data rather than the model's theoretical limit. We discuss how truncation and packing relate to this decision.
We also describe techniques that save memory, such as gradient checkpointing and mixed precision. Finally, we show a method for finding the largest batch that fits, then tuning accumulation to reach your target. After this lecture you will be able to configure these settings confidently.
Training does not have to use one fixed learning rate. This lecture explains weight decay, learning rate scheduling, and warmup, three tools that make fine-tuning more stable and often produce better results.
We begin with weight decay, a form of regularization that gently penalizes large weights. It discourages overfitting and keeps the model from drifting too far from sensible values. You will learn typical values and why decay is usually not applied to certain parameters, such as biases and normalization weights.
Next, we cover learning rate schedules. Rather than holding the rate constant, a schedule changes it over time. Common choices include linear decay and cosine decay, which gradually reduce the rate so that the model settles into a good solution near the end of training. We compare these with a constant schedule and discuss when each makes sense.
Then we explain warmup. At the start of training, the optimizer's statistics are unreliable and large steps can destabilize the model, so the learning rate is increased gradually from near zero over the first portion of steps. You will learn how to choose a warmup ratio.
We also show how these settings appear in Hugging Face training arguments. After this lecture you will be able to select and justify a schedule for your run.
A long training run should never be a black box. This lecture explains checkpoints, logging, and evaluation intervals, the habits that let you monitor progress, recover from failures, and choose the best model.
We begin with checkpoints, saved snapshots of the model, optimizer state, and training progress. Regular checkpoints protect you from crashes and interruptions, allow you to resume training, and let you return to an earlier, better version if later steps cause overfitting. We discuss how often to save, how much disk space checkpoints require, and how to keep only the most useful ones.
Next, we cover logging. You will learn which metrics to track, including training loss, validation loss, learning rate, gradient norm, and throughput, and how to record them with tools such as TensorBoard or Weights & Biases. We explain how to read curves and spot problems early.
Then we discuss evaluation intervals. Running validation too rarely hides problems, while running it too often wastes time. You will see how to set evaluation by steps or by epochs and how to use the results to select the best checkpoint automatically.
We also recommend recording configuration and random seeds with every run. After this lecture you will be able to set up monitoring that makes experiments transparent and recoverable.
Overfitting is the most common reason a fine-tuned model looks excellent during training and disappoints afterward. This lecture explains how to detect it and how early stopping helps you avoid it.
We start with the definition. An overfit model has memorized the training examples, including their quirks and noise, rather than learning general patterns. It performs well on seen data but poorly on new inputs. You will learn the classic sign: training loss keeps falling while validation loss flattens or begins to rise.
Next, we examine other warning signs, such as outputs that repeat training phrases, sudden drops in performance on general tasks, and a widening gap between training and evaluation metrics. We also discuss the related risk of catastrophic forgetting.
Then we introduce early stopping, which monitors a validation metric and ends training when it stops improving for a set number of evaluations, often combined with restoring the best checkpoint. You will learn how to choose patience and thresholds sensibly.
We also describe other remedies: more or more diverse data, fewer epochs, a lower learning rate, weight decay, and parameter-efficient methods. After this lecture you will be able to read validation curves, recognize overfitting early, and configure early stopping in your own runs.
In this hands-on lab you will prepare and validate a complete supervised fine-tuning configuration before spending any compute on training, a habit that saves time and money.
You will begin by gathering the inputs: your processed dataset, the chosen base model and tokenizer, and the evaluation set from earlier sections. We then define a configuration, ideally in a single file, covering learning rate, epochs, batch size, gradient accumulation, sequence length, scheduler, warmup, weight decay, precision, logging, checkpoint, and evaluation settings.
Next, you will validate it. Calculate the effective batch size and the total number of optimization steps, estimate memory use against your hardware, and run a very small dry run on a handful of examples to confirm that the data loads, labels are masked correctly, the loss is computed, and checkpoints are written. We show how to decode a batch and inspect it to make sure the formatting is right.
Then you will add safety checks, such as fixed seeds, saved configuration files, and a clear output directory structure. Finally, you will document your choices and the reasons for them.
By the end of this lab you will have a reviewed configuration, ready to use in your first end-to-end training run.
Choosing the right base model is one of the highest-leverage decisions in a fine-tuning project. This lecture explains how to compare candidates and select one that fits your task, data, and hardware.
We begin with the main criteria. Size matters, since larger models are generally more capable but require more memory, time, and money. Model type matters, too: decide between base and instruction-tuned versions, and check whether a chat template is provided. Language coverage, context length, and performance on tasks similar to yours also deserve attention.
Next, we discuss practical constraints. Read the license carefully to confirm that it allows your intended use, including commercial deployment if relevant. Check the community and documentation, the availability of quantized versions, and compatibility with the tools you plan to use.
Then we describe a simple selection process. Shortlist a few models, run them on your baseline evaluation set with identical prompts, compare quality, speed, and memory use, and pick the smallest model that meets your requirements. Starting small speeds up iteration, and you can scale up later if needed.
Finally, we mention leaderboards and benchmarks, and why they should guide but never replace testing on your own data. After this lecture you will be able to choose a base model with confidence and justify the decision.
Before training begins, the model, tokenizer, and dataset must be loaded correctly. This lecture walks through each step so that your first run starts from a sound foundation.
We begin with the tokenizer. You will load it from the same repository as the model, inspect its special tokens, and set a padding token when the model does not define one. We discuss padding side and why it matters for training versus generation.
Next, we load the model. You will learn how to select precision such as bfloat16, place the model on the right device, and enable options that reduce memory use. We examine how to check the number of parameters and confirm that the architecture and configuration look as expected. We also explain how to disable the cache during training when using gradient checkpointing.
Then we load the prepared dataset using Hugging Face Datasets, confirm the splits and fields, and view a few formatted examples after applying the chat template. We emphasize checking that the text includes the end-of-sequence token and that lengths fit your chosen maximum.
Finally, we run simple sanity checks: pass one batch through the model, confirm that a loss value appears, and note memory use. After this lecture you will be able to assemble all inputs for training reliably.
The TRL library from Hugging Face provides the SFTTrainer, a convenient class that handles many details of supervised fine-tuning. This lecture explains how to configure it correctly.
We begin with an overview of what the trainer does for you: formatting examples, tokenizing, batching, masking, running the training loop, evaluating, logging, and saving checkpoints. You will learn how it builds on the standard Transformers training tools.
Next, we walk through the configuration object. You will set output directory, learning rate, epochs, batch sizes, gradient accumulation, scheduler, warmup, logging steps, evaluation strategy, and save strategy. We explain options that affect memory and speed, including mixed precision and gradient checkpointing, and show how to control maximum sequence length and packing.
Then we cover how the trainer receives the model, tokenizer, datasets, and optional formatting or collating logic. You will see how to train only on assistant responses, a setting that connects directly to the label masking lecture. We also discuss how to pass a parameter-efficient configuration, which you will use in later sections.
Finally, we point out version differences between library releases and how to read the documentation when argument names change. After this lecture you will be able to set up an SFTTrainer instance ready to run.
This is the moment where everything comes together: you will launch your first supervised fine-tuning run and learn how to supervise it while it trains.
We begin with a short pre-flight checklist. Confirm the configuration, verify that the dataset and labels look correct, check available memory, and make sure the output directory is set. We recommend a very short trial run first, a few steps only, to catch problems before committing to a long job.
Next, you will start the full run and learn what to watch. Observe the training loss, which should decrease overall, though not smoothly; the evaluation loss at each interval; the learning rate following its schedule; and the throughput and memory use. We explain what typical healthy curves look like and how to interpret noise.
Then we discuss practical matters, such as how to run training in the background, how to resume from a checkpoint if something interrupts it, and how to keep a record of the run's configuration and logs.
Finally, we show how to confirm that training finished successfully and where the saved outputs are located. After this lecture you will have completed an actual fine-tuning run and know how to read the signals it produces.
Training will not always go smoothly, and knowing how to read the signals saves hours of frustration. This lecture covers how to interpret training loss, make use of checkpoints, and fix common errors.
We begin with the loss. You will learn what a healthy decline looks like, why the initial value depends on the model and data, and what unusual patterns mean: a flat line may indicate a learning rate that is too low or masked labels, spikes may signal instability or bad examples, and a loss that falls to nearly zero often points to memorization or leakage.
Next, we discuss checkpoints. You will see how to compare checkpoints using validation results, resume interrupted runs, and choose the best one rather than assuming the last is best.
Then we turn to common errors. Out-of-memory failures can be addressed by reducing batch size or sequence length, enabling gradient checkpointing, or using lower precision. We also cover tokenizer and padding errors, shape mismatches, missing chat templates, authentication problems, and version incompatibilities, with a general debugging approach: reproduce on a tiny dataset, read the error carefully, and change one thing at a time.
After this lecture you will be able to diagnose most beginner training issues and recover efficiently.
A fine-tuned model is only valuable if it measurably outperforms what you started with. This lecture shows how to test your tuned model against the baseline fairly and draw honest conclusions.
We begin with the setup. Use the same evaluation dataset, prompts, and generation settings that you used for the baseline, changing only the model. This isolates the effect of fine-tuning and keeps the comparison reproducible.
Next, we run both models and compute the same metrics, including accuracy-style measures, format compliance, and rubric scores where relevant. You will look beyond averages by examining results by category and difficulty, since an overall gain can hide regressions in important areas.
Then we perform side-by-side qualitative review. Read paired outputs, note improvements and new failure modes, and classify errors using your taxonomy. We also check general abilities and safety behavior to make sure that tuning has not harmed the model elsewhere.
We discuss interpreting small differences cautiously and considering the size of your evaluation set. If results disappoint, we outline likely causes, including data quality issues, hyperparameters, and mismatched formats.
Finally, we describe how to summarize findings clearly for stakeholders. After this lecture you will be able to decide whether a fine-tuning run succeeded and what to try next.
In this hands-on lab you will complete the full fine-tuning cycle: train a model, save it, reload it from disk, and evaluate your first customized LLM.
You will begin from your validated configuration and processed dataset, launching training with the SFTTrainer and monitoring loss curves and evaluation metrics. When training completes, you will select the best checkpoint rather than automatically taking the last one.
Next, you will save the model and tokenizer together in a clean output directory, along with the configuration and a brief description of how it was trained. We emphasize saving everything needed to reproduce and reload the model later, including special token settings and the chat template.
Then you will reload the saved model in a fresh session, which proves that the artifacts are complete and works as a safeguard against hidden dependence on variables from your notebook. You will run inference with the same prompt format used in training.
Finally, you will evaluate the reloaded model on your held-out set, compare it with your baseline report, and summarize improvements, remaining errors, and ideas for the next iteration.
By the end of this lab you will have trained, saved, reloaded, and measured your own customized model, completing a full end-to-end fine-tuning workflow.
This course contains the use of artificial intelligence.
Master Large Language Models, Transformers, LoRA, QLoRA, Hugging Face, and AI Model Customization
Want to understand how Large Language Models (LLMs) actually work and learn how to customize them for real-world applications? This comprehensive, hands-on course takes you from LLM fundamentals to advanced fine-tuning techniques, helping you develop practical skills in Generative AI, Natural Language Processing (NLP), Machine Learning, and Deep Learning.
Whether you're an aspiring AI Engineer, Machine Learning Engineer, Data Scientist, Python Developer, or Generative AI enthusiast, this course will help you understand, train, evaluate, and deploy customized language models using popular open-source AI frameworks.
What You'll Learn
1. Large Language Model Fundamentals
Understand the foundations of Artificial Intelligence (AI), Generative AI, Natural Language Processing, and Transformer Architecture. Explore tokenization, embeddings, self-attention, multi-head attention, positional encoding, neural networks, pretraining, and next-token prediction.
2. LLM Customization Strategies
Discover when to use Prompt Engineering, Retrieval-Augmented Generation (RAG), Supervised Fine-Tuning (SFT), and domain adaptation. Learn how to select the right approach based on model performance, business requirements, and available resources.
3. Data Preparation for Fine-Tuning
Learn essential LLM dataset preparation techniques, including data collection, cleaning, preprocessing, tokenization, synthetic data generation, instruction-response formatting, JSONL datasets, training-validation-test splitting, and data quality assessment.
4. Hands-On LLM Fine-Tuning
Gain practical experience with Python, PyTorch, Hugging Face Transformers, Hugging Face Datasets, and TRL. Configure training parameters, understand learning rates, batch sizes, epochs, gradient accumulation, optimizers, training loss, and model checkpoints.
5. Parameter-Efficient Fine-Tuning
Explore Parameter-Efficient Fine-Tuning (PEFT) techniques, including Low-Rank Adaptation (LoRA) and Quantized Low-Rank Adaptation (QLoRA). Understand 4-bit quantization, model compression, GPU memory optimization, adapter training, and efficient LLM customization.
6. LLM Evaluation and Optimization
Evaluate models using accuracy, precision, recall, F1-score, human evaluation, task-specific benchmarks, and hallucination testing. Learn to identify overfitting, underfitting, catastrophic forgetting, and data leakage, while improving model quality through experimentation.
7. LLM Deployment and Inference
Discover how to serve customized AI models using Ollama, Hugging Face, FastAPI, Streamlit, and local inference frameworks. Explore model serving, inference optimization, API development, and AI application deployment.
Build a Real-World Fine-Tuning Project
Apply your knowledge through a practical end-to-end LLM fine-tuning capstone project. Prepare a custom dataset, establish baseline performance, fine-tune an open-weight language model using LoRA or QLoRA, evaluate improvements, and build a working AI-powered application.
Who Should Enroll?
This course is ideal for AI Developers, Software Engineers, Python Programmers, Data Scientists, ML Engineers, AI Architects, NLP Practitioners, and technology professionals who want practical experience with Large Language Models and Generative AI development.
Basic Python knowledge is recommended, but previous LLM fine-tuning experience is not required.
Start Building Customized AI Models
Move beyond simply using AI tools. Learn how language models work, when customization makes sense, and how to create specialized solutions through LLM training, fine-tuning, evaluation, and deployment.
Enroll today and start developing the practical LLM engineering skills needed to build customized Generative AI applications!