AI Tutorial
Home All Courses Blog Interview Prep ↗ 0%
1
Curious builder 0 XP earned · 300 to level 2
0 days Finish a lesson to begin
Badge collection
0 of 5 unlocked
small wins to finish your path
Next lesson →

What is an LLM

A large language model is a neural network trained to predict the next token of text. That single, simple objective — applied to trillions of tokens with billions of parameters — produces systems that can write, summarise, translate, reason through problems, and write code. This lesson explains what an LLM is, how it is built and trained, and where its abilities and its failures come from.

Last updated: 01 Nov, 2026

Definitions: from AI to LLMs

These terms are often used interchangeably, but each is a subset of the one before it.

Definition · Artificial intelligence (AI)

The broad field of building software that performs tasks normally requiring human intelligence — understanding language, recognising images, planning, making decisions.

Definition · Machine learning (ML)

A branch of AI where systems learn patterns from data instead of following hand-written rules. You show a model many examples, and it adjusts internal numbers to make better predictions.

Definition · Deep learning

Machine learning using neural networks with many layers. Each layer transforms its input into a slightly more useful representation. Deep learning powers modern speech recognition, image models, and LLMs.

Definition · Language model

A model that assigns probabilities to sequences of text — most commonly by predicting the next token given the previous ones.

Definition · Large language model

A language model with a very large number of parameters (billions to trillions), trained on a very large text corpus, typically using the transformer architecture.

Diagram
┌──────────────────────── Artificial Intelligence ────────────────────────┐
│  rules engines, search, planning, ...                                    │
│  ┌─────────────────────── Machine Learning ──────────────────────────┐   │
│  │  decision trees, linear models, clustering, ...                    │   │
│  │  ┌───────────────────── Deep Learning ─────────────────────────┐   │   │
│  │  │  CNNs for images, speech models, ...                         │   │   │
│  │  │  ┌──────────── Large Language Models ────────────┐           │   │   │
│  │  │  │  GPT, Claude, Gemini, Llama, Mistral, Qwen ... │           │   │   │
│  │  │  └────────────────────────────────────────────────┘           │   │   │
│  │  └──────────────────────────────────────────────────────────────┘   │   │
│  └────────────────────────────────────────────────────────────────────┘   │
└──────────────────────────────────────────────────────────────────────────┘

What makes a language model “large”?

DimensionWhat it meansTypical scale
ParametersThe learned weights of the network — its “knowledge” and skills are stored in these numbers.Small open models: 1–8 billion. Frontier models: hundreds of billions to trillions (often undisclosed).
Training dataThe text (and often code, images, audio) the model learns from.Trillions of tokens from web pages, books, code, papers, and curated datasets.
ComputeThe processing power used to train it.Thousands of GPUs or TPUs running for weeks to months.

A key discovery of the last decade is that scaling these three together makes models predictably better — and unlocks abilities such as following instructions, translating between languages they were never explicitly taught to translate, and writing working code.

A language model in 20 lines of Python

To demystify the idea, here is the simplest possible language model: a bigram model. It counts which word follows which in some training text, then predicts the next word with probabilities. Real LLMs replace the counting with a giant neural network and words with tokens, but the job is identical: given what came before, how likely is each possible next piece?

Python
from collections import Counter, defaultdict

corpus = """the model reads the prompt . the model predicts the next token .
the model repeats . the user reads the answer ."""

words = corpus.split()
follows = defaultdict(Counter)
for current, nxt in zip(words, words[1:]):
    follows[current][nxt] += 1          # "training": count what follows what


def next_word_probs(word: str) -> dict[str, float]:
    counts = follows[word]
    total = sum(counts.values())
    return {w: round(c / total, 2) for w, c in counts.most_common()}


print(next_word_probs("the"))
print(next_word_probs("model"))
{'model': 0.43, 'prompt': 0.14, 'next': 0.14, 'user': 0.14, 'answer': 0.14} {'reads': 0.33, 'predicts': 0.33, 'repeats': 0.33}

This toy model already shows the essential behaviour: after the, it believes model is most likely. It has no understanding — only statistics of what tends to follow what. An LLM learns vastly richer statistics over long contexts, which is enough to capture grammar, facts, styles, and even step-by-step reasoning patterns.

The transformer, at a high level

Definition · Transformer

The neural-network architecture behind virtually every modern LLM, introduced in the 2017 paper “Attention Is All You Need”. Its key innovation is self-attention, which lets every token look at every earlier token and decide which ones are relevant.

You do not need to implement a transformer to build with LLMs, but knowing its four stages explains a lot of behaviour:

  1. Tokenisation and embedding. Text is split into tokens, and each token id is mapped to a vector of numbers (an embedding) that represents it. Position information is added so the model knows word order.
  2. Self-attention. In each layer, every token computes how much to “pay attention” to each previous token. In “The trophy did not fit in the suitcase because it was too big”, attention helps it connect to trophy.
  3. Feed-forward layers. After attention, each token's vector passes through a small neural network. These layers are thought to store much of the model's factual and procedural knowledge. Attention + feed-forward together form one transformer block, and models stack dozens of them.
  4. Output head. The final vector for the last position is converted into a score (logit) for every token in the vocabulary — the model's prediction of what comes next.
Note

Because attention compares tokens with each other, the cost of processing a prompt grows quickly with its length. That is the deep reason context windows are limited and long prompts are slower and more expensive.

How an LLM is trained

StageWhat happensResult
1. PretrainingThe model reads trillions of tokens and learns to predict the next token. No human labels — the text itself is the answer key (self-supervised learning).A base model: knows language and a lot about the world, but just continues text.
2. Supervised fine-tuning (SFT)Training on curated examples of instructions and high-quality responses, often written by people.A model that follows instructions and answers in a helpful format.
3. Preference tuning (RLHF, DPO, RLAIF)People or AI judges compare pairs of answers; the model is optimised to prefer the better ones. Reasoning models are additionally trained with reinforcement learning on verifiable tasks such as maths and code.A chat / instruct model that is more helpful, honest, and safe.
Definition · Base model vs chat model

A base model only continues text: give it “The capital of France is” and it continues “Paris. The capital of Germany is…”. A chat (instruct) model has been fine-tuned to treat input as a conversation and respond helpfully. Almost every API you call serves chat models.

Illustration
Prompt:  "Write a haiku about vectors."

Base model continues the text:
  "Write a haiku about vectors. Write a haiku about matrices.
   Write a haiku about ..."             <- it saw lists of prompts in training

Chat model answers the request:
  "Arrows in the dark /
   pointing where the meanings live /
   close means similar"

What LLMs are good at

  • Transforming text: summarising, rewriting, translating, changing tone, extracting fields into JSON.
  • Generating drafts: emails, documentation, test cases, marketing copy, code.
  • Reasoning over provided context: answering questions about a document you include in the prompt (the idea behind RAG).
  • Classification and routing without training a separate model: sentiment, intent, topic, priority.
  • Coding: writing, explaining, and fixing code in most languages.

What LLMs are bad at (and why)

Definition · Hallucination

When a model generates fluent, confident text that is false or unsupported — a made-up citation, a non-existent API, a wrong date. It happens because the model optimises for plausible continuations, not verified truth.

LimitationWhy it happensEngineering fix
HallucinationsPrediction of plausible text, not fact lookupGround answers in retrieved documents (RAG), ask for citations, verify.
Knowledge cutoffTraining data stops at a dateProvide fresh information in the prompt, or give the model a search tool.
No memory between callsEach API request is independentResend the conversation history, store memories in a database.
Exact arithmetic and countingNumbers are split into tokens; the model pattern-matchesLet the model call a calculator or run code.
Long-context recallAttention spreads thin; details in the middle can be missedRetrieve only relevant chunks; put key instructions at the start or end.
Inconsistent outputSampling introduces randomnessLower temperature, structured outputs, validation and retries.
Prompt injectionThe model cannot reliably tell instructions from dataSeparate trusted instructions, restrict tools, validate actions.

Discriminative vs generative models

KindJobOutputExamples
DiscriminativePredict a label or a number for an inputspam / not spam, a price, a risk scoreSpam filters, fraud detection, image classifiers
GenerativeCreate new content similar to the training dataText, code, images, audioLLMs, image generators, text-to-speech

LLMs are generative, but they are frequently used for discriminative tasks too — asking “Is this review positive or negative? Answer with one word.” turns a generator into a classifier.

The model landscape

TypeExamplesHow you use itTrade-offs
Closed-weight (proprietary)OpenAI GPT and o-series, Anthropic Claude, Google GeminiPaid HTTP APIUsually strongest; no infrastructure; data leaves your servers; per-token cost.
Open-weightMeta Llama, Mistral, Qwen, DeepSeek, Google GemmaDownload and run yourself, or use a hosting providerFull control and privacy; you manage GPUs and updates.
Small / on-deviceSmall Llama, Gemma, Phi, Qwen variantsLaptop, phone, or edge device via Ollama or llama.cppCheap, private, offline; less capable.
Reasoning modelsOpenAI o-series, Claude and Gemini thinking modes, DeepSeek-R1Same APIs, with extra “thinking” tokensMuch better at maths, code, and multi-step problems; slower and pricier.

LLM vs the product built on it

ChatGPT, Claude.ai, and Gemini are products. The LLM inside them only predicts tokens. The product adds a system prompt, conversation memory, web search and other tools, file uploads, safety filters, and a user interface. When you build with the API, you are responsible for those layers — which is exactly what the rest of this course and the RAG and Agents courses teach.

Try it
  1. Run the bigram model and add three sentences of your own to the corpus. How do the probabilities after the change?
  2. Write a function generate(start, n) that repeatedly picks the most likely next word. What happens after a few steps?
  3. List three tasks from your work and classify each as a good fit, a risky fit (needs grounding or verification), or a poor fit for an LLM.
Key takeaways
  • An LLM is a transformer neural network trained to predict the next token of text.
  • “Large” refers to parameters, training data, and compute — scaling all three unlocked new abilities.
  • Pretraining produces a base model; instruction tuning and preference tuning produce the chat models you call through APIs.
  • Hallucinations, knowledge cutoffs, and statelessness are consequences of how LLMs work, and each has an engineering fix.
  • The model only predicts tokens — memory, tools, retrieval, and safety are layers you build around it.