TExcelTAD
Home › Generative AI & LLMs › How LLMs Work

How LLMs Work

A large language model is a neural network trained to predict the next piece of text. Everything else — chatting, summarising, writing code — is built on that single skill. This lesson gives you the whole pipeline at a glance; the following lessons zoom in on each step.

The pipeline

text
"The sky is"                                   your prompt (text)
   │ 1. tokenize
[464, 6766, 318]                               token IDs (integers)
   │ 2. embed
[[0.12, -0.4, …], [...], [...]]                one vector per token
   │ 3. transformer layers (attention + feed-forward), many times
[[...], [...], [...]]                          context-aware vectors
   │ 4. output layer
logits: {" blue": 7.1, " clear": 5.3, …}       one score per vocabulary token
   │ 5. softmax + sampling
" blue"                                        the chosen next token
   │ 6. append and repeat
"The sky is blue"

(The IDs and numbers above are illustrative, not from a real model.)

  1. Tokenize — split the text into tokens (words or word pieces) and map each to an integer ID.
  2. Embed — look up a learned vector for every ID.
  3. Transform — a stack of Transformer layers lets each token's vector absorb information from earlier tokens via attention.
  4. Score — the final vector is turned into a logit (a raw score) for every token in the vocabulary, often 100,000 or more.
  5. Sample — logits become probabilities with softmax; one token is chosen, greedily or randomly.
  6. Repeat — the new token is appended and the whole process runs again, until a stop token or a length limit.

A toy version of every step

The program below implements the loop with a hand-made model. Its "network" is just a table of logits for which word follows which — but the flow from text to IDs to scores to probabilities to a chosen token is the real one.

python · try it yourself
import math

vocab = ["<end>", "the", "sky", "is", "blue", "grey", "today"]
token_id = {tok: i for i, tok in enumerate(vocab)}

# Toy "model": logits for the next token, given only the last token.
LOGITS = {
    "the":   [0, 0, 3, 0, 0, 0, 0],
    "sky":   [0, 0, 0, 3, 0, 0, 0],
    "is":    [0, 0, 0, 0, 2.5, 1.5, 0],
    "blue":  [1, 0, 0, 0, 0, 0, 2],
    "grey":  [1, 0, 0, 0, 0, 0, 2],
    "today": [3, 0, 0, 0, 0, 0, 0],
}

def softmax(xs):
    exps = [math.exp(x) for x in xs]
    total = sum(exps)
    return [e / total for e in exps]

ids = [token_id[w] for w in "the sky".split()]          # 1. tokenize
while len(ids) < 10:
    logits = LOGITS[vocab[ids[-1]]]                     # 2-4. "model" gives scores
    probs = softmax(logits)                             # 5. probabilities
    next_id = max(range(len(vocab)), key=probs.__getitem__)  # greedy choice
    print(f"{vocab[ids[-1]]:>6} -> {vocab[next_id]:<6} p={probs[next_id]:.2f}")
    if vocab[next_id] == "<end>":
        break
    ids.append(next_id)                                 # 6. append, repeat

print("text:", " ".join(vocab[i] for i in ids))
   sky -> is     p=0.77
    is -> blue   p=0.56
  blue -> today  p=0.49
 today -> <end>  p=0.77
text: the sky is blue today

A real LLM differs in the parts that matter for quality: its logits depend on the whole context (not just the last token), they come from billions of learned parameters rather than a hand-written table, and the vocabulary is enormous.

Probabilities, not facts

The model never "looks up" an answer. It outputs a probability distribution over possible next tokens. If the training data made a wrong continuation plausible, the model can produce it fluently — this is the root of hallucinations.

python · try it yourself
import math

def softmax(scores):
    exps = {k: math.exp(v) for k, v in scores.items()}
    total = sum(exps.values())
    return {k: v / total for k, v in exps.items()}

# Hypothetical logits after "The capital of Australia is"
logits = {" Canberra": 4.0, " Sydney": 3.2, " Melbourne": 1.5, " a": 0.5}
for token, p in sorted(softmax(logits).items(), key=lambda kv: -kv[1]):
    print(f"{token:<11} {p:6.1%}")
 Canberra    64.0%
 Sydney      28.8%
 Melbourne    5.3%
 a            1.9%

In this made-up example the correct answer is most likely, but a popular wrong answer still gets a sizeable share of probability. With random sampling it would sometimes be chosen.

What "large" means

Aspect Toy model above Typical modern LLM (order of magnitude)
Parameters 42 numbers billions to hundreds of billions
Vocabulary 7 words tens of thousands to a few hundred thousand tokens
Context used last word many thousands to hundreds of thousands of tokens
Training text none (hand-written) trillions of tokens

Chat is a text format

A chat assistant is still a next-token predictor. The conversation is formatted into one long text with special markers for each role, and the model continues it from the assistant's turn. When the model emits an end-of-turn token, the app stops and shows you the reply. You will meet this again in the APIs and system prompts lessons.

Note: Modern assistants also use extra training (instruction tuning and RLHF), tools and retrieval. But the generation loop you just ran is still at the centre.

Test yourself

What does an LLM output at each generation step?

  1. A finished paragraph
  2. A score (logit) for every token in its vocabulary
  3. A database query
  4. Exactly one word from a dictionary lookup

Which function turns logits into probabilities that sum to 1?

  1. tokenize
  2. softmax
  3. embed
  4. argmax

Why can an LLM state something false fluently?

  1. It looks facts up in a broken database
  2. It generates likely-sounding text from probabilities, which is not the same as checking facts
  3. It is programmed to lie
  4. Because tokenization removes facts