PROMETHEUS OS
NATIVE AI OPERATING SYSTEM
[INIT] Prometheus OS loading...
[CORE] Neural interface initializing...
[AI] LLM router connecting...
[MEM] Memory graph loading...
[AGT] Agent chains on standby...
[SEC] Security protocols active...
[NET] Provider mesh established...
[UI] Workspace rendering...
[DONE] All systems nominal.
Welcome to PROMETHEUS OS.
READY · OFFLINE · SECURE · PRIVATE
🎨 THEME ENGINE
PROMETHEUS OS · 23 THEMES
Trial version: Dark + Light themes only.
Full theme access with PROMETHEUS OS license.
Dark theme active
Experience all 23 themes in PROMETHEUS OS

How Large Language Models Work

Beginner 14 min· 4 exercises

See what happens inside a chatbot: text becomes tokens, a transformer predicts the next token using attention, training happens in stages, and sampling explains why answers vary and why models sometimes make things up.

By the end of this lesson you will be able to
  • Explain tokenisation and estimate token counts from word counts.
  • Compute next-token probabilities from logits with softmax at different temperatures, and apply top-p filtering.
  • Explain the cross-entropy training objective and interpret perplexity.
  • Describe the attention formula and work a small numeric attention example by hand.
  • Describe the stages that turn a pretrained base model into a chat assistant, and explain why hallucinations occur.

Before this: How Machines Learn

Why this matters

Chat assistants are the AI most people use every day. Knowing how they produce text explains their strengths, why the same question can get different answers, and why they sometimes invent facts with complete confidence.

A large language model (LLM) is a neural network, trained on a very large amount of text, whose core job is to predict what text comes next.

Step 1: text becomes tokens

Models don't read letters or whole words. They read tokens: chunks of text from a fixed vocabulary, typically tens of thousands to a few hundred thousand entries. Common words are usually one token; rare or long words are split into pieces; spaces and punctuation are often attached to or counted as tokens too. Each token is then turned into a number the network can work with.

An illustrative example (invented for teaching, not the output of any real tokenizer). The sentence:

The weather is unbelievably nice today.

might be split roughly like this:

The · weather · is · un · believ · ably · nice · today · .

That is 6 words but about 9 tokens, because the long word was split into three pieces and the full stop is its own token. Exact splits differ between models, so treat this as a sketch rather than the output of a specific tokenizer.

A useful rule of thumb for English, as published by OpenAI: one token is about four characters or about three-quarters of a word, so 100 tokens is roughly 75 words. Other languages often use more tokens per word. Tokens matter because models have limits on how many they can handle at once, and services charge by the token.

Step 2: predict the next token

Given a sequence of tokens, the model outputs a probability for every token in its vocabulary being the next one. An illustrative example with made-up numbers, for the text "The sky is":

Possible next tokenProbability
blue62%
clear11%
falling4%
the3%
everything else20%

One token is chosen, appended to the text, and the whole process repeats. A long answer is just this loop run hundreds or thousands of times. Nothing is written in advance; the reply is built one token at a time.

Step 3: the transformer and attention

Almost all modern LLMs use an architecture called the transformer, introduced in the 2017 research paper "Attention Is All You Need".

Its key idea is attention. When processing each token, the model looks back over all the earlier tokens and decides how much each one matters for the current step. In "The trophy didn't fit in the suitcase because it was too big", attention helps the model link "it" to "trophy". In plain words: attention lets every word consult every other relevant word, rather than reading strictly left to right and forgetting.

A transformer stacks many layers of attention plus ordinary neural-network layers. Earlier layers tend to capture simple patterns like grammar; later layers capture more abstract relationships. This is a simplification, but a fair one. Transformers also process all the tokens of a training passage in parallel, which made it practical to train on vast amounts of text using many graphics processors (GPUs).

Step 4: how a chatbot is trained, in stages

Pretraining. The model reads a huge collection of text, such as web pages, books and code, and learns to predict the next token. This is where it absorbs grammar, facts, styles and reasoning patterns. The result is a base model: knowledgeable, but it just continues text. Ask it a question and it might write three more questions.

Instruction tuning. The base model is trained further on many examples of instructions paired with good responses, written or curated by people. It learns to behave like an assistant that answers rather than rambles.

Preference training. People compare pairs of model responses and pick the better one. Those choices train the model further toward answers people prefer: more helpful, more honest, less harmful. The best-known version is reinforcement learning from human feedback (RLHF): OpenAI described using it for ChatGPT, training a separate reward model from human rankings and then optimising the chatbot against it. Developers also use variations, including feedback generated with the help of other AI models.

Why the same prompt gives different answers

At each step the model produces probabilities, not a single answer. The software then samples: it picks a token at random, weighted by those probabilities. In the "sky" example, "blue" wins about 62% of the time, but "clear" will sometimes be picked, and the rest of the sentence then follows a different path.

Temperature is a setting that controls how adventurous that sampling is. At low temperature the most likely tokens dominate, giving focused, repeatable answers. At higher temperature the probabilities are flattened, giving more varied and creative, but also more error-prone, text. At a temperature of zero, many systems always pick the top token, though small differences can still creep in for technical reasons.

Why LLMs hallucinate

A hallucination is a fluent, confident statement that is false, such as a made-up citation or a wrong date. It happens for understandable reasons:

  • The model is trained to produce plausible text, and a plausible-sounding falsehood can score well.
  • Facts are stored diffusely across billions of parameters, not in a lookup table, so rare facts are fuzzy.
  • Unless it is connected to search or documents, the model has no way to check a source.
  • Training has often rewarded giving an answer over admitting uncertainty, though developers now actively train against this.

Developers work hard to reduce hallucinations, but no current model is free of them.

Going deeper

This section puts numbers on three ideas from above: how scores become probabilities, what the model is trained to minimise, and what attention computes. All numbers are small and illustrative; real models do the same arithmetic with vocabularies of tens of thousands of tokens and vectors with thousands of entries.

From scores to probabilities: softmax and temperature

The network's last layer produces one raw score, called a logit, for every token in the vocabulary. A function called softmax turns logits into probabilities that are positive and add up to 1. With temperature TT:

pi=ezi/T∑jezj/Tp_i = \frac{e^{z_i / T}}{\sum_{j} e^{z_j / T}}

Here ziz_i is the logit of token ii, e≈2.718e \approx 2.718, and the sum in the denominator runs over every token in the vocabulary.

Worked example. Suppose that after "The sky is" only three tokens matter, with logits blue =2.0= 2.0, clear =0.5= 0.5, falling =−0.5= -0.5.

At T=1T = 1: e2.0=7.389e^{2.0} = 7.389, e0.5=1.649e^{0.5} = 1.649, e−0.5=0.607e^{-0.5} = 0.607. The total is 9.6449.644, so the probabilities are 7.389/9.644=0.7667.389 / 9.644 = 0.766, 0.1710.171 and 0.0630.063.

Changing the temperature divides every logit by TT before the softmax:

Temperatureblueclearfalling
0.50.9460.0470.006
1.00.7660.1710.063
2.00.5690.2690.163

Low temperature sharpens the distribution toward the top token; high temperature flattens it. As TT approaches 0, sampling becomes greedy decoding: always pick the highest-scoring token.

Many systems also apply top-p (nucleus) sampling: keep only the smallest set of top tokens whose probabilities add up to at least pp, then renormalise. With p=0.9p = 0.9 at T=1T = 1, "blue" alone (0.7660.766) is not enough, so "clear" is added (0.766+0.171=0.9370.766 + 0.171 = 0.937). "Falling" is dropped, and the survivors become 0.766/0.937=0.8180.766 / 0.937 = 0.818 and 0.1820.182. This cuts off the long tail of unlikely tokens that can derail a sentence.

The training objective: cross-entropy

During pretraining the correct next token is known, because it is simply the next token in the text. The loss for one position is the cross-entropy, the negative log of the probability the model gave the correct token:

L=−ln⁡pcorrect\mathcal{L} = -\ln p_{\text{correct}}

If the correct token was "blue" and the model gave it 0.766, the loss is −ln⁡0.766=0.266-\ln 0.766 = 0.266. Had the model given it only 0.01, the loss would be −ln⁡0.01=4.61-\ln 0.01 = 4.61. Confident mistakes are punished hard. Pretraining minimises the average of this loss over an enormous number of positions, using exactly the gradient descent described in the previous lesson.

A related number you will see in papers is perplexity, ee raised to the average cross-entropy. An average loss of 1.2 gives a perplexity of e1.2≈3.3e^{1.2} \approx 3.3: on average the model is about as uncertain as if it were choosing evenly among 3.3 tokens. Lower is better.

Attention in one formula

Each token's vector is projected into three new vectors: a query (what this position is looking for), a key (what this position offers) and a value (the information it passes on). Stacking these for all positions into matrices QQ, KK and VV, attention is

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{Q K^{\top}}{\sqrt{d_k}}\right) V

where dkd_k is the length of the key vectors. Dividing by dk\sqrt{d_k} keeps the scores from growing so large that the softmax becomes all-or-nothing.

Worked example (made-up two-number vectors). The query for "it" is q=(1,0)q = (1, 0). The keys are trophy =(2,0)= (2, 0) and suitcase =(0.5,1)= (0.5, 1), so dk=2d_k = 2.

  1. Dot products: q⋅ktrophy=2q \cdot k_{\text{trophy}} = 2 and q⋅ksuitcase=0.5q \cdot k_{\text{suitcase}} = 0.5.
  2. Divide by 2≈1.414\sqrt{2} \approx 1.414: scores 1.4141.414 and 0.3540.354.
  3. Softmax: e1.414=4.11e^{1.414} = 4.11 and e0.354=1.42e^{0.354} = 1.42, giving weights 0.7430.743 and 0.2570.257.
  4. If the values are trophy =(1,0)= (1, 0) and suitcase =(0,1)= (0, 1), the output is 0.743×(1,0)+0.257×(0,1)=(0.743,0.257)0.743 \times (1, 0) + 0.257 \times (0, 1) = (0.743, 0.257).

The new representation of "it" is about three-quarters "trophy". In a language model each position may only attend to itself and earlier positions (a causal mask), because it must not peek at the tokens it is trying to predict. Real transformers run many of these attention calculations side by side (multi-head attention), each free to track a different kind of relationship.

Sampling in code

import numpy as np

def softmax(logits, temperature=1.0):
    z = np.asarray(logits, dtype=float) / temperature
    z = z - z.max()                   # subtract the max for numerical stability
    e = np.exp(z)
    return e / e.sum()

tokens = ["blue", "clear", "falling"]
logits = [2.0, 0.5, -0.5]
for T in (0.5, 1.0, 2.0):
    p = softmax(logits, T)
    print(f"T={T}: " + ", ".join(f"{t} {q:.3f}" for t, q in zip(tokens, p)))

rng = np.random.default_rng(0)
draws = rng.choice(tokens, size=1000, p=softmax(logits))
print({t: int((draws == t).sum()) for t in tokens})

The loop reproduces the temperature table. The last two lines draw 1,000 tokens at T=1T = 1; the counts come out close to 766, 171 and 63 (here 752, 188 and 60), which is why the same prompt gives different continuations.

Common pitfalls

  • Expecting temperature 0 to mean "correct". It makes the choice more repeatable, not more accurate. The most likely token can still be wrong.
  • Comparing token counts across models. Different tokenizers split the same text differently, so prices and limits per token are not directly comparable.
  • Reading confident wording as calibrated confidence. The tone of a reply tells you little about the probability that it is right.
  • Asking letter-level questions without tools. Because models see tokens rather than letters, counting characters or reversing words is surprisingly error-prone.
  • Assuming everything in a long prompt is used equally well. Quality can drop when key facts are buried in very long contexts; put the important material clearly and close to the question.
  • Using a base model as an assistant. Without instruction tuning it continues text rather than following instructions.

In practice

  • Expect variation: if an answer matters, ask again or ask the model to check its own work.
  • Use lower-temperature settings, where available, for factual or technical tasks, and higher for brainstorming.
  • Give the model the source material (paste the document) instead of relying on its memory; it is far more accurate that way.
  • Verify names, numbers, quotes and citations independently before you rely on them.

Key takeaways

  • LLMs read and write tokens, word pieces that average about three-quarters of an English word.
  • A model generates text one token at a time by predicting probabilities for the next token and choosing one.
  • The transformer's attention mechanism lets each token draw on every relevant earlier token.
  • Chatbots are built in stages: pretraining on large text collections, instruction tuning, then preference training such as RLHF.
  • Sampling and temperature explain varied answers, and training for plausible text explains why models can hallucinate.

Terms in this lesson

Large language model (LLM)
A large neural network trained on text to predict the next token, used to understand and generate language.
Token
A chunk of text, often a word or part of a word, that a language model reads and writes.
Tokenizer
The component that splits text into tokens and converts them to numbers.
Transformer
The neural network design behind most modern language models, built around attention.
Attention
A mechanism that lets the model weigh how relevant each earlier token is when processing the current one.
Pretraining
The first, largest training stage, where a model learns to predict the next token over a huge body of text.
Instruction tuning
Further training on example instructions and good responses so the model behaves like an assistant.
RLHF
Reinforcement learning from human feedback: training a model toward responses that people ranked as better.
Temperature
A setting that controls how random the choice of the next token is.
Sampling
Choosing the next token at random according to the model's predicted probabilities.
Logit
The raw, unnormalised score a model assigns to each possible next token before softmax turns the scores into probabilities.
Softmax
A function that exponentiates a list of scores and divides by their sum, producing positive probabilities that add up to 1.
Cross-entropy loss
The negative logarithm of the probability a model assigned to the correct answer, averaged over examples; the standard training loss for language models.

Check your understanding

  1. 1.

    Roughly how many tokens would a 750-word English article use?

  2. 2.

    Why can the exact same prompt produce two different answers?

  3. 3.

    What does a base model that has only been pretrained typically do when given a question?

  4. 4.

    Two candidate tokens have logits 2 and 0. At temperature 1, roughly what probability does softmax give the first token?

  5. 5.

    What happens to the next-token distribution when you raise the temperature from 0.5 to 2.0?

Exercises

Work each problem before opening the solution.

  1. Exercise 1Core

    You want a model to summarise a 3,000-word English report in about 600 words. Using the rule of thumb of about three-quarters of a word per token, estimate the input tokens, the output tokens and the total. Would it fit in an 8,000-token context window?

    Show solution

    Tokens ≈ words ÷ 0.75. Input: 3000/0.75=40003000 / 0.75 = 4000 tokens. Output: 600/0.75=800600 / 0.75 = 800 tokens. Total ≈ 4,800 tokens (plus a few for instructions), which fits within 8,000. This is an estimate: technical text, code or other languages usually need more tokens per word.

  2. Exercise 2Core

    Three tokens have logits (1,1,0)(1, 1, 0). Compute their softmax probabilities at T=1T = 1 and at T=0.5T = 0.5.

    Show solution

    At T=1T = 1: e1=2.718e^1 = 2.718, e1=2.718e^1 = 2.718, e0=1e^0 = 1; total 6.4376.437. Probabilities: 0.4220.422, 0.4220.422, 0.1550.155.

    At T=0.5T = 0.5 the logits become (2,2,0)(2, 2, 0): 7.3897.389, 7.3897.389, 11; total 15.77815.778. Probabilities: 0.4680.468, 0.4680.468, 0.0630.063.

    Lowering the temperature moves probability away from the weaker token but cannot separate the two tied tokens; ties stay ties.

  3. Exercise 3Core

    Coding. Write a function top_p_sample(probs, p) that keeps the smallest set of most-likely tokens whose probabilities sum to at least p, renormalises them and samples one. Test it on the probabilities [0.766, 0.171, 0.063] with p = 0.9.

    Show solution
    import numpy as np
    
    def top_p_sample(probs, p=0.9, rng=None):
        rng = rng or np.random.default_rng()
        probs = np.asarray(probs, dtype=float)
        order = np.argsort(probs)[::-1]             # most likely first
        cumulative = np.cumsum(probs[order])
        cutoff = np.searchsorted(cumulative, p) + 1 # smallest set reaching p
        keep = order[:cutoff]
        kept = probs[keep] / probs[keep].sum()      # renormalise
        return int(rng.choice(keep, p=kept)), keep, kept
    
    probs = [0.766, 0.171, 0.063]                   # blue, clear, falling
    idx, keep, kept = top_p_sample(probs, p=0.9, rng=np.random.default_rng(1))
    print("kept tokens:", keep.tolist(), "renormalised:", kept.round(3).tolist())
    

    It prints kept tokens: [0, 1] renormalised: [0.818, 0.182]. Sorting puts tokens in descending order; the cumulative sums are 0.766, 0.937, 1.0; searchsorted finds the first position where the sum reaches 0.9 (index 1), and adding 1 converts that position into a count of tokens to keep.

  4. Exercise 4Challenge

    A query q=(1,1)q = (1, 1) attends over three positions with keys k1=(1,0)k_1 = (1, 0), k2=(0,1)k_2 = (0, 1), k3=(1,1)k_3 = (1, 1) and values equal to the keys. With dk=2d_k = 2, compute the attention weights and the output vector. Then explain in one or two sentences why the scaling by dk\sqrt{d_k} matters more as vectors get longer.

    Show solution

    Dot products: q⋅k1=1q\cdot k_1 = 1, q⋅k2=1q\cdot k_2 = 1, q⋅k3=2q\cdot k_3 = 2. Divide by 2\sqrt{2}: 0.7070.707, 0.7070.707, 1.4141.414. Exponentials: 2.0282.028, 2.0282.028, 4.1134.113; total 8.1698.169. Weights: 0.2480.248, 0.2480.248, 0.5030.503 (to three decimals).

    Output =0.248(1,0)+0.248(0,1)+0.503(1,1)≈(0.752,0.752)= 0.248(1,0) + 0.248(0,1) + 0.503(1,1) \approx (0.752, 0.752) (using unrounded weights 0.2483+0.5035=0.75170.2483 + 0.5035 = 0.7517).

    Scaling: if the entries of qq and kk are roughly independent with variance 1, their dot product has variance dkd_k, so with long vectors (for example 128 entries) raw scores become large. Softmax of large scores puts nearly all weight on one position and its gradients become tiny, which makes training slow and unstable. Dividing by dk\sqrt{d_k} brings the variance back to about 1.

Further reading

Go further

Sources

Fact-checked and last reviewed 2026-11-05

Stay in the loop
Prometheus OS™ · Native AI OS · Built for the future © 2025 - 2026