Skip to content

Expert: deep learning and AI · NLP, embeddings and large language models · topic 51 of 62 · 35 min

How large language models work

Explanation

A large language model (LLM) is a huge transformer network trained to predict the next token of text. It reads text as sub-word tokens, sees a limited context window, and generates answers one token at a time by sampling from its predicted probabilities. Temperature controls how random that sampling is. Because it predicts likely text, not checked facts, it can confidently make things up.

Next-token prediction

At heart, an LLM does one thing: given the text so far, it outputs a probability for every possible next token. "The capital of India is" → " New" gets a high probability. The model picks a token, adds it to the text, and repeats. Long answers, code and translations all come from repeating this single step. Models such as GPT, Claude, Gemini, Llama and Mistral all work on this principle, with different training data and designs.

Tokens

LLMs do not read whole words. A tokenizer splits text into sub-word pieces using methods such as byte-pair encoding (BPE): common words are one token, rare words are split into several pieces ("unbelievable" might become "un", "believ", "able"). For English text, one token is very roughly 4 characters or three-quarters of a word. Many tokenizers need more tokens for Hindi and other Indian scripts, which makes those languages costlier per word; this varies by model.

The context window

The context window is the maximum number of tokens the model can look at at once: your instructions, any documents you paste, the chat history and its own answer so far. Anything outside the window is invisible to it. Window sizes vary a lot between models and change often, from a few thousand tokens to hundreds of thousands or more. Long contexts cost more and the model may pay less attention to details in the middle.

Training in stages

  1. Pre-training: the model reads a vast amount of text and learns to predict the next token. This teaches grammar, facts, reasoning patterns and also biases present in the data.
  2. Instruction tuning (supervised fine-tuning): it is trained on examples of instructions and good answers, so it follows requests.
  3. Preference training, such as RLHF (reinforcement learning from human feedback): people compare answers, and the model is tuned towards the preferred ones, for helpfulness and safety.

Attention, briefly

Inside, the transformer uses self-attention (module 9): for each token, it weighs how relevant every earlier token is. That is how "it" in a long paragraph gets linked to the right noun. Stacking many attention layers lets the model build up complex patterns.

Sampling and temperature

The model gives scores (logits) for the next token; softmax turns them into probabilities. Greedy decoding always picks the most likely token: stable but sometimes repetitive. Sampling picks randomly according to the probabilities. Temperature T divides the logits before softmax: T below 1 sharpens the distribution (more predictable), T above 1 flattens it (more varied and more error-prone). Use low temperature for extraction and facts, higher for brainstorming.

python
import math

def softmax_t(logits, t):
    scaled = [v / t for v in logits]
    m = max(scaled)
    exps = [math.exp(v - m) for v in scaled]
    return [round(e / sum(exps), 4) for e in exps]

print(softmax_t([2.0, 1.0, 0.1], 0.5))
print(softmax_t([2.0, 1.0, 0.1], 2.0))
Shows [0.8638, 0.1169, 0.0193] then [0.5017, 0.3043, 0.194]. Low temperature makes the top token dominate; high temperature spreads the chances.

Why LLMs hallucinate

An LLM produces text that sounds likely, not text it has verified. If it lacks the fact, it may still produce a fluent, confident and wrong answer: a made-up court case, a fake citation, a wrong GST rate. This is called hallucination. Giving it trusted documents (RAG, module 11), asking it to say when it does not know, and checking outputs reduce the problem but do not remove it.

Cost and speed

Hosted LLM APIs usually charge per token, often with a different price for input and output tokens, quoted per million tokens. Longer prompts and answers cost more and take longer. Prices change frequently, so always check the provider's current price page.

Common mistakes

  • Treating LLM output as fact. Check anything important.
  • Pasting huge documents and assuming the model read every detail. Retrieve the relevant parts instead.
  • Using high temperature for tasks that need exact, repeatable answers.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

How large language models work · 1/7

Next-token prediction

A large language model predicts the next token, again and again.

Prefer a video by a teacher? Find free videos on “how large language models work tokens context window temperature explained” on YouTube ↗

In real life: An LLM writes a product description

A seller on an online marketplace asks an LLM to write a description for a handloom saree from a few bullet points. The model generates it token by token. At temperature 0.2 it produces a safe, plain description; at 0.9 it is more creative but once invented "hand-painted gold motifs" that were not in the bullet points. The seller now keeps a low temperature and checks every claim against the actual product.

Practice (0/3 done)

Task 1 · Code · Python

Write greedy_next(probs) where probs is a dict mapping candidate tokens to probabilities. Return the token with the highest probability; on a tie, return the alphabetically smallest token.

Task 2 · Code · Python

Write softmax_temperature(logits, t) that divides every logit by t, then applies softmax (subtract the max before math.exp). Return the probabilities rounded to 4 decimal places. Raise ValueError if t <= 0.

Task 3 · Code · Python

Write api_cost(input_tokens, output_tokens, in_price_per_million, out_price_per_million) that returns the cost of one call in the same currency as the prices: input_tokens × in_price / 1,000,000 + output_tokens × out_price / 1,000,000, rounded to 4 decimal places.

Quick quiz

Question 1

1.At its core, what does an LLM predict?

Question 2

2.What is the context window?

Question 3

3.You need the same extracted invoice fields every time. Which temperature setting fits best?

Question 4

4.Why can an LLM state a wrong fact confidently?

Question 5

5.What is RLHF used for?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

At its core, what does an LLM predict?

Answer: The next token, given the text so far

Generation is next-token prediction repeated.

What is the context window?

Answer: The maximum number of tokens the model can consider at once

Instructions, documents, history and output must all fit.

You need the same extracted invoice fields every time. Which temperature setting fits best?

Answer: Low, near 0

Low temperature gives focused, repeatable output.

Why can an LLM state a wrong fact confidently?

Answer: It generates likely-sounding text and does not verify facts

That is hallucination; check important outputs.

What is RLHF used for?

Answer: Tuning the model towards answers people prefer

Human preference comparisons guide the model's behaviour.

Besides answer quality, what should an LLM app track?Related

Answer: Latency, cost per request and safety failures

A correct answer that is too slow or too costly can still fail the product.

From Evaluating LLM apps

Which instruction best reduces made-up answers?Related

Answer: "If the answer is not in the text, reply UNKNOWN"

A clear way out lowers the pressure to invent an answer.

From Prompting well

Why did transformers largely replace RNNs for language?Related

Answer: They process all positions in parallel and handle long-range links well

Parallel training and attention made them faster and stronger.

From CNNs, RNNs and transformers at a glance

Why lowercase text before counting words?Related

Answer: So "Refund" and "refund" are counted as the same word

Otherwise the counts are split across spellings.

From Working with text: tokens and cleaning

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “NLP, embeddings and large language models” before its exam: Prompting well.
  2. Module 10 exam: NLP, embeddings and large language models · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Building with generative AI, and MLOps. 62 topics left in the course before the final exam.

← Previous: Embeddings and cosine similarity