Read complete course notes

All guides

Introduction to Generative AI

Eleven lessons on how generative models work, from tokens and attention to training, prompting, retrieval and the risks, with hands-on sliders and checks.

A foundations course for first-time learners using original worked examples. It explains concepts and rules of thumb, not product-specific features, and does not teach programming.

Basic arithmetic, percentages and the idea of probability.

Course outline

  1. What a generative model actually does

    Separate generating new content from labeling existing content, and describe a language model as next-token prediction.

  2. Tokens and the context window

    Explain what a token is and budget the context window for a task.

  3. Embeddings: meaning as position

    Describe how tokens become vectors and why nearby vectors mean related things.

  4. Attention: which earlier tokens matter

    Explain self-attention at a conceptual level and why long inputs cost more.

  5. How a model is trained

    Describe pretraining as predicting the next token and measure it with a loss.

  6. From base model to assistant

    Explain instruction tuning and learning from human preferences.

  7. Sampling and temperature

    Explain how temperature changes which token is chosen.

  8. Prompting: instructions, examples and structure

    Write a prompt that states task, context, format and constraints.

  9. Hallucination and checking claims

    Explain why models invent content and decide how to verify outputs.

  10. Retrieval-augmented generation and tools

    Describe how retrieval and tools ground answers in sources.

  11. Risk, law and responsible use

    Name the main risks of generative AI and the public frameworks that address them.

Sources and curriculum note

Reviewed October 13, 2026 against the cited sources. Rules of thumb such as 0.75 words per token are estimates and differ by model. Regulation and guidance change; check the linked official pages for the current text.

Complete course reading notes

Read every lesson below. The interactive reader above contains the same explanations, with visual tools and quizzes.

1. What a generative model actually does

Learning goal: Separate generating new content from labeling existing content, and describe a language model as next-token prediction.

A classifier takes an input and returns a label: spam or not spam, cat or dog. A generative model learns the patterns in its training data well enough to produce new examples that look like them. Text, images, audio, code and video can all be generated this way. The word generative describes the output, not a level of intelligence.

A large language model works on text by predicting the next token given all the tokens so far. It produces a probability for every token in its vocabulary, one token is chosen, that token is added to the text, and the process repeats. A paragraph is the result of many small predictions chained together. Nothing in this loop looks facts up unless the system around the model adds a way to do so.

This view explains both the strengths and the limits. Fluent, well-formed text is exactly what next-token prediction is trained to produce, so fluency is cheap. Truth is not the training target, so a confident sentence can be wrong. Keep this picture in mind for the rest of the course: probabilities in, one token out, repeat.

Worked example

A model is given the text: The capital of France is. It gives Paris 0.92, Lyon 0.03 and other tokens 0.05 combined. What does the model output?

  1. It scores the possible next tokens; Paris is by far the most likely, so it is usually the one chosen.
  2. Avoid this mistake: Assuming a fluent answer is a checked answer.
Practice problem and solution

A model gives three candidate next tokens probabilities 0.5, 0.3 and 0.2. How many percent of the probability is on the two least likely tokens together?

0.3 + 0.2 = 0.5, which is 50 percent.

Mental model: Generate by predicting the next token, again and again.

Common trap: Assuming a fluent answer is a checked answer.

2. Tokens and the context window

Learning goal: Explain what a token is and budget the context window for a task.

Models do not read letters or words directly. A tokenizer splits text into tokens, which can be whole common words, pieces of rarer words, punctuation or single characters. Byte-pair encoding, introduced for translation by Sennrich and colleagues in 2015, builds a vocabulary by repeatedly merging frequent pairs of symbols. A rare word becomes several tokens, while a common one is often a single token.

A common rule of thumb for English is that one token is about three quarters of a word, or about four characters. It is only an estimate. Other languages, code and numbers can use more tokens for the same meaning, and each tokenizer behaves differently, so always check with the tokenizer for the model you use.

The context window is the maximum number of tokens the model can handle at one time. It covers the instructions you give, any documents you paste, the conversation so far and the reply being generated. If the total is too large, text is cut or the request fails. Good use of a model starts with a simple budget: window minus instructions minus documents equals what is left for the answer.

Worked example

An invented model has an 8,000-token window. You paste 3,000 words and write 500 tokens of instructions. Use 0.75 words per token.

  1. 3,000 words is 4,000 tokens. 8,000 - 4,000 - 500 leaves 3,500 tokens for the reply.
  2. Avoid this mistake: Counting words and forgetting that the reply also uses the window.
Practice problem and solution

An invented model has a 16,000-token window. A document is 9,000 words (0.75 words per token) and the instructions use 1,000 tokens. How many tokens are left for the reply? Enter a number.

9,000 / 0.75 = 12,000. 16,000 - 12,000 - 1,000 = 3,000.

Mental model: Window minus input equals room for the reply.

Common trap: Counting words and forgetting that the reply also uses the window.

3. Embeddings: meaning as position

Learning goal: Describe how tokens become vectors and why nearby vectors mean related things.

Inside the model each token is turned into a list of numbers called an embedding. These numbers are learned during training so that tokens used in similar ways end up with similar vectors. You can imagine a map where related words sit close together, although real embeddings have hundreds or thousands of dimensions that cannot be drawn.

Closeness is usually measured with cosine similarity, which compares the direction of two vectors. A value near 1 means very similar direction, near 0 means unrelated, and negative values mean opposite. Whole sentences and documents can also be embedded, which is why embeddings are used in search: you embed the question and find documents whose vectors are nearby.

Embeddings capture patterns of use, not definitions. Words that appear in similar contexts can be close even when their meanings differ, for example hot and cold often appear in similar sentences. They also carry the biases of the data they came from. Treat similarity scores as a useful signal for ranking, not as proof that two texts mean the same thing.

Worked example

Two vectors are a = (1, 0) and b = (0, 1). What is their cosine similarity?

  1. The vectors are at right angles, so cosine similarity is 0.
  2. Avoid this mistake: Treating a high score as proof of equivalence.
Practice problem and solution

Query vector q = (3, 4) and a document vector d = (6, 8). Their cosine similarity equals the dot product divided by the product of lengths. Enter the cosine similarity.

The vectors point in the same direction: d = 2q, so the similarity is 1.

Mental model: Close vectors mean related use, not identical meaning.

Common trap: Treating a high score as proof of equivalence.

4. Attention: which earlier tokens matter

Learning goal: Explain self-attention at a conceptual level and why long inputs cost more.

The Transformer, introduced in the 2017 paper Attention Is All You Need, is the design behind most modern language models. Its central idea is self-attention. For each token, the model works out how much weight to give every other token in the input, then mixes their information according to those weights. In the sentence The trophy did not fit in the suitcase because it was too big, attention helps link it back to the trophy.

Attention weights are numbers between 0 and 1 that add up to 1 for each token. A high weight means that earlier token influences the current one strongly. Models stack many layers and run many attention patterns in parallel, called heads, so different heads can pick up different relationships such as grammar or reference.

In standard self-attention each token is compared with every other token, so the work grows with the square of the input length. Doubling the number of tokens makes that part of the cost about four times larger. This is one reason long contexts are expensive and why many systems use shortcuts for very long inputs.

Worked example

A token gives weights 0.6, 0.3 and 0.1 to three earlier tokens. What do these weights show?

  1. The first token influences it most. The weights sum to 1.
  2. Avoid this mistake: Reading attention weights as proof of correct reasoning.
Practice problem and solution

Standard attention compares every token with every token. For an input of 2,000 tokens, how many token pairs is that? Enter a number.

2,000 x 2,000 = 4,000,000.

Mental model: Attention mixes information by learned weights.

Common trap: Reading attention weights as proof of correct reasoning.

5. How a model is trained

Learning goal: Describe pretraining as predicting the next token and measure it with a loss.

Pretraining shows the model enormous amounts of text. At each position it predicts the next token, the prediction is compared with the real next token, and the model's numbers, called parameters, are adjusted to make the real token a little more probable next time. Repeated trillions of times, this teaches grammar, facts and styles as a side effect of getting the next token right.

The usual measure is cross-entropy loss, the negative logarithm of the probability the model gave to the correct token. If it gave the right token probability 0.5, the loss is 1 bit using base-2 logs. Probability 0.25 gives 2 bits, and 0.125 gives 3 bits. Lower is better, and a loss of 0 would mean certainty in the right answer.

Researchers found that loss falls smoothly and predictably as model size, data and compute grow, reported as scaling laws by Kaplan and colleagues in 2020. A later study by Hoffmann and colleagues in 2022, often called Chinchilla, found that for a fixed compute budget, many large models had been trained on too little data and that parameters and training tokens should grow together. Lower loss does not by itself guarantee correct or safe answers.

Worked example

A model gives the correct next token a probability of 0.25. Compute the loss in bits.

  1. Loss is -log2(0.25) = 2 bits.
  2. Avoid this mistake: Equating low loss with truthfulness.
Practice problem and solution

A model gives the correct token probability 0.125. Enter the loss in bits.

-log2(0.125) = 3, since 2^3 = 8.

Mental model: Probability on the right token drives the loss.

Common trap: Equating low loss with truthfulness.

6. From base model to assistant

Learning goal: Explain instruction tuning and learning from human preferences.

A base model trained only to predict the next token will continue text in the style it was shown, which is not the same as helping. To make assistants, developers fine-tune the model on examples of instructions paired with good responses. This is called supervised fine-tuning or instruction tuning.

A second stage uses human preferences. People compare two or more answers to the same prompt and say which is better. A reward model is trained to predict those choices, and the language model is then adjusted to produce answers that score higher. This method is called reinforcement learning from human feedback, or RLHF. The 2022 InstructGPT paper reported that human raters preferred outputs from a 1.3 billion parameter InstructGPT model over those from the 175 billion parameter GPT-3, showing alignment can matter more than size.

Preferences are a human signal, so they carry human limits. The model can learn to sound agreeable or confident because raters liked that. Alignment training lowers some harms but does not remove errors, and it does not turn the model into a source of verified facts.

Worked example

Four answers to one prompt are ranked 1 to 4 by a person. How many pairs of answers can be compared from one ranking?

  1. Choosing 2 from 4 gives 6 pairs.
  2. Avoid this mistake: Treating an assistant as a verified source.
Practice problem and solution

30 prompts each have 4 ranked answers. Each ranking gives all pairwise comparisons. How many comparisons in total? Enter a number.

4 answers give 6 pairs. 30 x 6 = 180.

Mental model: Tuning shapes behaviour, not the facts the model knows.

Common trap: Treating an assistant as a verified source.

7. Sampling and temperature

Learning goal: Explain how temperature changes which token is chosen.

The model first produces raw scores for each token, called logits. A function called softmax converts them into probabilities that add up to 1. Higher logits give higher probability, and the gaps between logits control how sharply the probability concentrates.

Temperature divides the logits before softmax. A temperature below 1 sharpens the distribution, so the top token is chosen more often and replies become more predictable. A temperature above 1 flattens it, so less likely tokens are chosen more often and replies become more varied. Temperature near 0 approaches always picking the top token. Other settings, such as top-p, limit choices to the most probable tokens.

Low temperature suits tasks with one right form, such as extracting a date. Higher temperature suits brainstorming. Lower temperature does not make facts truer. A model can confidently and repeatedly give the same wrong answer when it is the most probable one.

Worked example

Logits are 2, 1 and 0. At temperature 1 the probabilities are about 66.5, 24.5 and 9.0 percent. What happens at temperature 0.5?

  1. The top token rises to about 86.7 percent, so output is more predictable.
  2. Avoid this mistake: Thinking low temperature means truthful.
Practice problem and solution

Logits 2, 1 and 0 at temperature 0.5 give the top token about 86.7 percent. Enter that rounded to the nearest whole percent.

e^4 = 54.6, e^2 = 7.39, e^0 = 1. 54.6 / 62.99 = 0.867, so 87 percent.

Mental model: Temperature trades predictability for variety.

Common trap: Thinking low temperature means truthful.

8. Prompting: instructions, examples and structure

Learning goal: Write a prompt that states task, context, format and constraints.

A prompt is the input that steers the model. The GPT-3 paper showed that a large model can do a new task from a description alone, called zero-shot, or from a few worked examples placed in the prompt, called few-shot, with no change to its parameters. This is why examples are such a strong tool: they show the pattern better than a description.

A strong prompt names the task, gives the background the model cannot know, says who the reader is, and fixes the output format, for instance a table with three columns. It also states constraints such as length, tone or things to avoid. Asking for reasoning steps can help on multi-step problems, but check the steps rather than trusting them.

Treat prompting as drafting and testing. Run a prompt on several realistic inputs, look at failures, and change one thing at a time. Do not put secrets or personal data into a tool unless its data terms allow it. Text pasted from untrusted sources can contain instructions that the model may follow, which is called prompt injection.

Worked example

A prompt has 3 examples of 40 tokens each, 60 tokens of instruction and a 100-token new input. How many tokens is the prompt?

  1. 3 x 40 + 60 + 100 = 280 tokens.
  2. Avoid this mistake: Pasting untrusted text and assuming it is only data.
Practice problem and solution

A prompt has 3 examples of 40 tokens each, 60 tokens of instruction and a new input of 100 tokens. Enter the total tokens.

120 + 60 + 100 = 280.

Mental model: Task, context, format and limits.

Common trap: Pasting untrusted text and assuming it is only data.

9. Hallucination and checking claims

Learning goal: Explain why models invent content and decide how to verify outputs.

A hallucination is output that sounds plausible but is not supported by the source or by fact. A survey by Ji and colleagues in 2022 separates two kinds: intrinsic, which contradicts the source text provided, and extrinsic, which adds content that cannot be checked from the source. Fabricated citations, invented quotations and wrong numbers are common examples. NIST uses the term confabulation for the same risk.

The causes follow from how models work. The model is trained to produce likely text, not verified text. When it lacks knowledge it may still produce a fluent answer. Gaps in training data, outdated information and prompts that assume a false premise all raise the risk.

Verification should match the stakes. Check names, dates, numbers and citations against a primary source. Ask for the source passage and read it, because a model can attach a real-looking reference to a false claim. For high-stakes work such as law, medicine or finance, a qualified person must review the result.

Worked example

A model-written summary has 250 factual claims, and a check finds 4 percent unsupported. How many claims are unsupported?

  1. 4 percent of 250 is 10 claims.
  2. Avoid this mistake: Asking the model to verify itself and accepting the answer.
Practice problem and solution

A summary has 250 factual claims and 4 percent are unsupported. Enter the number of unsupported claims.

0.04 x 250 = 10.

Mental model: Plausible is not the same as supported.

Common trap: Asking the model to verify itself and accepting the answer.

10. Retrieval-augmented generation and tools

Learning goal: Describe how retrieval and tools ground answers in sources.

Retrieval-augmented generation, introduced by Lewis and colleagues in 2020, gives the model relevant passages at question time instead of relying only on what it stored in training. The documents are split into chunks, each chunk is embedded, and the question is embedded too. The nearest chunks are fetched and placed in the prompt so the model can answer from them.

Chunking is a design choice. Chunks that are too small lose context, and chunks that are too large waste window space. Overlap between chunks reduces the chance that an answer is split across a boundary. The number of retrieved chunks times the chunk size must fit in the context window along with the instructions and the reply.

Retrieval reduces unsupported answers but does not remove them. The wrong chunk may be retrieved, the right chunk may be missed, or the model may ignore the evidence. Good systems show the source passages so the reader can check them. Tools extend the idea: the model can call a calculator, a database or a search engine and use the result.

Worked example

A 12,000-word document is split into 300-word chunks that overlap by 50 words, so each new chunk starts 250 words after the last. The last chunk may be shorter. How many chunks are needed?

  1. Starts at 0, 250, ... 11,500 give 47 chunks, covering up to word 11,800. One more chunk is needed for the last words, so 48.
  2. Avoid this mistake: Assuming retrieval guarantees a correct answer.
Practice problem and solution

A 12,000-word document is split into 300-word chunks with a 250-word step. The last chunk may be shorter. How many chunks are needed? Enter a number.

Starts 0 to 11,500 give 47 chunks and reach word 11,800. A 48th chunk covers the last 200 words.

Mental model: Retrieve the evidence, then generate from it.

Common trap: Assuming retrieval guarantees a correct answer.

11. Risk, law and responsible use

Learning goal: Name the main risks of generative AI and the public frameworks that address them.

NIST published the Generative AI Profile, NIST AI 600-1, in July 2024 as a companion to its AI Risk Management Framework. It lists risks that are new or made worse by generative AI, including confabulation, data privacy, information integrity, intellectual property, harmful or biased content and information security. Its suggested actions are voluntary.

In the European Union, Regulation 2024/1689, the AI Act, sets risk-based rules. It places transparency duties on certain uses, such as telling people when they interact with an AI system or when content is AI-generated, and separate duties on providers of general-purpose models. In the United States, the Copyright Office has been publishing reports on copyright and AI, covering questions such as when AI-generated material can be protected. Check the current text of any rule before relying on it, because this area changes.

Good personal practice is simple. Do not paste confidential or personal data into tools without permission. Keep a human responsible for important decisions. Check facts that matter. Say when you used AI where a course, employer or publisher expects disclosure. Keep the sources you relied on.

Worked example

A chatbot invents a court case, and a person files it without checking. Which NIST risk term fits?

  1. Confabulation: the model produced confident but false content.
  2. Avoid this mistake: Delegating responsibility to the tool.
Practice problem and solution

An invented chatbot invents a citation that a user files in court without checking. Enter the NIST risk term (one word) for this failure.

NIST AI 600-1 uses confabulation for confident but false generated content.

Mental model: Know the risk, check the output, keep a person accountable.

Common trap: Delegating responsibility to the tool.