← All posts

AI basics › From statistics to AGI

What is an LLM? How large language models write text

An LLM is a large neural network trained to predict the next token. How that works, how chat models are made from it, and what it does well or poorly.

If you’ve ever asked ChatGPT, Claude, or Gemini a question, you’ve already talked to an LLM. The term shows up in news about AI and in announcements of new models, and these days it turns up in developer job postings too. Still, if someone asked what an LLM actually is, perhaps the only answer that comes to mind is that the letters stand for large language model.

An LLM is a large neural network trained on an enormous amount of text to predict the next token. Given some text, it weighs which small piece of text, called a token, is likely to come next, adds one, and repeats. Answering a question and writing code both rest on that one move. Once such models learned to follow instructions written in everyday language, the chat services built on them became tools for writing, studying, and coding, and that’s why the word seems to be everywhere now. This post is the fourth in the series “From statistics to AGI,” and it picks up where the previous one left off. Deep learning, covered there, is about neural networks with many layers learning features on their own, and an LLM is one of those networks made very large and trained on text.

What it means to predict the next token

A token is the unit a model reads and writes in, and it can be a whole word, part of a word, or a punctuation mark. Each model has its own tokenizer that cuts text into tokens from a fixed vocabulary, and predicting the next token means giving every token in that vocabulary a probability of coming next. It may help to picture the word suggestions above your phone’s keyboard. An LLM, though, has learned from far more text and looks much further back.

Training works the same way. You hide the next token in some training text, let the model guess, and then adjust its parameters, the numbers inside the network, so the right answer gets a little more probability. Repeat that over trillions of tokens, and the model picks up grammar, facts that appear often, styles of writing, and the patterns of code. Since the answer is already in the text, nobody has to label anything by hand, and this stage is called pretraining.

Watching a small model pick the next token

Let’s check this with a real model. I used SmolLM2-135M, which Hugging Face released publicly. According to its model card, it was trained on 2 trillion tokens, and with weights of about 270 MB it runs on an ordinary computer’s CPU. The code below shows the five most likely tokens after “The capital of France is,” along with their probabilities, and then lets the model write twelve more tokens. All you need is pip install torch transformers, and the model downloads itself on the first run.

import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

name = "HuggingFaceTB/SmolLM2-135M"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, dtype="float32")
print(f"{model.num_parameters():,} parameters, {len(tok):,} tokens in the vocabulary")

ids = tok("The capital of France is", return_tensors="pt").input_ids
print([tok.decode(t) for t in ids[0]])  # the sentence as the model sees it

with torch.no_grad():
    probs = model(ids).logits[0, -1].softmax(-1)  # one probability per token
top = probs.topk(5)
for p, t in zip(top.values, top.indices):
    print(f"{tok.decode(t)!r:12} {p:.3f}")

# Greedy decoding: take the most likely token, append it, repeat
for _ in range(12):
    with torch.no_grad():
        next_id = model(ids).logits[0, -1].argmax()
    ids = torch.cat([ids, next_id.view(1, 1)], dim=1)
print(tok.decode(ids[0]))

Nothing here is random, and it runs on the CPU in float32, so running it again gives the same result.

134,515,008 parameters, 49,152 tokens in the vocabulary
['The', ' capital', ' of', ' France', ' is']
' the'       0.262
' Paris'     0.094
' located'   0.073
' called'    0.044
' a'         0.039
The capital of France is the capital of the country.

The capital of France

The model has about 135 million parameters and picks the next token from 49,152 candidates. Each word became one token, and the space before a word belongs to that word’s token. Among the candidates, Paris is second at 9.4% and the is first at 26.2%, which makes sense, since a sentence that goes on as “the city of Paris” is perfectly natural too. But when greedy decoding takes the top candidate every time, the result reads smoothly while saying nothing, calling the capital of France the capital of the country, and soon it starts to repeat. The Transformers docs on generation strategies point out this same weakness of greedy search on longer outputs, and describe sampling, which picks tokens at random according to their probabilities, as the alternative. If a chat service answers the same question a little differently each time, sampling of this kind is often the reason.

The transformer, parameters, and the context window

The network inside an LLM is usually a transformer, first proposed in 2017 by Ashish Vaswani and colleagues in Attention Is All You Need. Its central piece, attention, lets each token decide how much to draw on the tokens before it, which is how the word France can directly shape the prediction at the end of our sentence. The paper built its model on attention alone, without the recurrent or convolutional layers the leading models of the time relied on, and reported that it parallelizes well and takes much less time to train. That, in turn, made it easier to train bigger models on more text.

A model’s size is usually given as how many parameters it has. Our model has 135 million, while GPT-3, described in the 2020 paper Language Models are Few-Shot Learners, had 175 billion, about 1,300 times as many. That same year, Jared Kaplan and colleagues reported that as model size, data, and compute grow, a language model’s loss, roughly how far off its predictions are, falls following a power law (Scaling Laws for Neural Language Models).

The context window is how much text a model can see at once. Anthropic’s docs on context windows describe it as all the text a model can reference when generating a response, including the response itself, and compare it to a working memory that is separate from the training data. Our small model’s settings allow up to 8,192 tokens, and the same page says Claude models hold up to 1M tokens depending on the model, as of October 27, 2026. The model can’t see anything outside the window, so in a long chat the earliest parts may be forgotten or summarized.

From continuing text to following instructions

A model that has only been pretrained is called a base model. It’s good at continuing text, but it doesn’t really know it’s supposed to answer you. The InstructGPT paper that OpenAI published in 2022 opens with a sentence saying that making language models bigger does not by itself make them better at following what a user intends.

So a second round of training follows. First comes instruction tuning, which keeps training the model on instructions paired with good responses, and then comes a step that uses human preferences. For InstructGPT, too, labelers wrote example responses that were used to fine-tune GPT-3, then ranked several outputs from the model, and those rankings were used to refine it further with reinforcement learning. This is RLHF, reinforcement learning from human feedback. In the paper’s human evaluations, people preferred answers from the 1.3B InstructGPT over those from the 175B GPT-3, despite its having 100 times fewer parameters.

SmolLM2 also comes as SmolLM2-135M-Instruct, which went through supervised fine-tuning (SFT) and DPO, a preference-tuning method, so let’s ask both models the same question.

from transformers import AutoTokenizer, AutoModelForCausalLM

chat = [{"role": "user", "content": "What is the capital of France?"}]
for name in ["HuggingFaceTB/SmolLM2-135M", "HuggingFaceTB/SmolLM2-135M-Instruct"]:
    tok = AutoTokenizer.from_pretrained(name)
    model = AutoModelForCausalLM.from_pretrained(name, dtype="float32")
    text = chat[0]["content"]
    if tok.chat_template:  # only the instruct model ships a chat format
        text = tok.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
    out = model.generate(**tok(text, return_tensors="pt"), max_new_tokens=20, do_sample=False)
    print(f"--- {name}\n{tok.decode(out[0]).strip()}")
--- HuggingFaceTB/SmolLM2-135M
What is the capital of France?

The capital of France is Paris.

What is the capital of France?
--- HuggingFaceTB/SmolLM2-135M-Instruct
<|im_start|>system
You are a helpful AI assistant named SmolLM, trained by Hugging Face<|im_end|>
<|im_start|>user
What is the capital of France?<|im_end|>
<|im_start|>assistant
The capital of France is Paris.<|im_end|>

The base model answered, wrote the question again, and stopped only when it hit the 20-token limit. Perhaps its training text often had questions and answers following one another, like a quiz. The instruct model, on the other hand, received the chat as a single piece of text with markers like <|im_start|> and <|im_end|>. As the Transformers docs on chat templates explain, even a chat-trained model is still continuing a sequence of tokens, and the chat template turns the list of messages into that sequence. The model wrote its answer and then produced <|im_end|>, which marks the end of a turn, so generation stopped right there. The system line is worth a look too, since I never wrote it. The chat template added it on its own.

A model and the product built around it

That system line leads to a distinction that’s easy to miss. The name of a chat service and the name of the model running inside it are different things. Anthropic’s models overview introduces Claude as a family of large language models and lists an API ID for each model, such as claude-opus-5-5, while the chat app people use is at claude.ai. A chat service often wraps a model with a system prompt written in advance, the conversation history, and tools such as web search, and the model inside can change while the service keeps its name.

Layer What it does Example
Base model Continues whatever text it’s given SmolLM2-135M
Instruction-tuned model Answers in a chat format and ends its turn SmolLM2-135M-Instruct
Chat service Adds a system prompt, history, and tools around a model ChatGPT, the Claude app

So when you hear that an LLM can do something, it helps to ask whether that’s the model or the service around it. Fetching today’s news from the web is the service’s job, while choosing the next token is the model’s.

What LLMs do well, and where to be careful

LLMs tend to be strong when one text needs to become another, such as drafting, summarizing, translating, and writing or explaining code. Their training text holds countless examples of these patterns, and a person can read the result and judge it fairly quickly. That’s why they often work best as a fast first draft that someone then checks.

The best-known weakness is hallucination, an answer that sounds plausible but isn’t true. In the 2025 paper Why Language Models Hallucinate, Adam Tauman Kalai and colleagues argue that models guess when they’re uncertain because training and evaluation reward guessing over admitting uncertainty. A model also doesn’t know what happened after its knowledge cutoff, the point where its training data ends, unless a service looks it up and puts it into the context window. Anthropic’s models overview lists June 2026 as the reliable knowledge cutoff for its current models, as of October 27, 2026.

Exact arithmetic is another weak spot, since numbers are also written one predicted token at a time. In the GPT-3 paper, the 175B model, shown a few worked examples first in what’s called the few-shot setting, got 2-digit addition right 100% of the time but 5-digit addition only 9.3% of the time. That was a 2020 model, so today’s numbers would differ. Still, when you need an exact figure, it’s safer to have the model write and run code, or to check the result yourself.

Where to start

If you’re new to this, I’d suggest running the first example above and changing the sentence. Watch how the five probabilities shift between a sentence whose next word is obvious and one where it isn’t, then give the same request to both models, and the difference between the two training stages becomes clearer. To go further, Hugging Face’s free LLM Course covers the Transformers library and the transformer architecture step by step from its first chapter.

The next post in the series steps back to look at artificial intelligence as a whole field and where LLMs fit within it. I ran these examples on October 27, 2026, on a Mac’s CPU with Python 3.13.12, PyTorch 2.14.1, and Transformers 5.20.2.

AI tools helped with the research for this post.