Following a sentence from raw text to a finished answer, and how the model that answers it was made
Large language models generate text by predicting the next token, then repeating that process. A tokenizer splits text into pieces, embeddings turn those pieces into numerical vectors, and transformer layers use attention to process their context. Pre-training builds broad language abilities, while fine-tuning and alignment shape the model for specific tasks and more useful responses.
When using a model, token counts affect cost and speed, the context window limits how much text it can consider, and sampling settings influence which tokens it chooses. Hugging Face provides models you can run yourself, while agents combine models with tools to gather information and take action. These systems can produce convincing errors, and their internal decisions remain difficult to explain, so a fluent answer is no guarantee of a correct one.
A large language model (LLM) is, at its heart, a giant next-token predictor. You give it some text, and it guesses what comes next, over and over. That sounds almost too simple to be useful. But trained on enough text, predicting the next word forces the model to absorb grammar, facts, reasoning patterns, and style. Scale that up and the predictor starts to look like something that can write, answer, and reason.
The model itself is a pile of numbers called weights (also called parameters): billions of adjustable values, learned from data, that are the model. “7B params” means 7 billion of these numbers. Everything the model does is math run over them. Nobody types in rules; the rules are baked into the weights during training.
This guide follows the natural journey:
Models don’t read words. They read numbers. A tokenizer breaks your text into pieces (tokens) and gives each piece a number ID.
Input text: "I'm using Python!"
Tokenizer output (illustrative IDs):
I → 45
'm → 2157
using → 1823
Python → 8934
! → 12
model_input = [45, 2157, 1823, 8934, 12]
The IDs above are illustrative; a real tokenizer assigns its own. A token isn’t necessarily a word. It could be a word, half a word, or punctuation. Notice the leading spaces above: in most modern tokenizers the space is part of the token, so Python (with a space) and Python (without) can be two different tokens with different IDs. This surprises people and explains a lot of odd tokenizer behavior.
A useful rule of thumb for English is that 4 characters is roughly 1 token, or about three-quarters of a word. So a 100-word message is around 130 tokens. That intuition matters because token count drives two practical things.
One point people get wrong: you don’t choose how your text is split, because the tokenizer is fixed. A common contraction like don't already becomes something like don plus 't, and that is normal, efficient behavior rather than waste. Tokenization only gets genuinely awkward for rare words, long strings of numbers, or non-English and code-heavy text, where words get chopped into many small pieces.
How does a tokenizer decide where to split? The most common method is Byte Pair Encoding (BPE):
The merge rules are learned from the training data, and those merges define the vocabulary. Common sequences such as the or ing get merged early and become single tokens, while rare sequences stay split into many pieces. That is the link back to cost: frequent words are cheap (one token) and rare ones are expensive (several).
Because BPE works at the byte level, it can represent any text (every emoji, every language), so there is almost never a truly unknown word in modern models.
Not every token is content. Some are markers that tell the model about structure rather than meaning.
When you send a system prompt to an API, behind the scenes it gets wrapped in these markers. One common format, OpenAI’s “ChatML”, looks like this:
<bos><|im_start|>system
You are a threat analyst.
<|im_end|><|im_start|>user
Check this IP address.
<|im_end|><|im_start|>assistant
The model reads these tokens and understands the structure: system instruction first, then user input, then its turn to respond. Note the pipe characters in <|im_start|>, and note that this is only one convention. Llama, Mistral, and others use different markers; there is no single universal standard. These tokens never appear in the visible output, because they live inside the infrastructure.
Token IDs are just labels. The number 8934 means nothing on its own. The first thing the model does is turn each token ID into an embedding: a list of numbers (a vector) that captures meaning. Tokens with similar meanings end up with similar vectors, sitting close together in this number-space.
A classic intuition: in a good embedding space, “king” and “queen” sit near each other, and the direction from “king” to “queen” is similar to the direction from “man” to “woman”. The model is not told this; it falls out of training. Embeddings are the actual numbers the rest of the model does math on.
One more ingredient is needed. Because the transformer looks at all words at once (see the next section), it also needs a separate signal for word order, called positional information. Without it, “the cat sat” and “sat the cat” would look identical. Position is added on top of each embedding so the model knows where each token sits in the sequence.
The architecture has a short history worth knowing. Early approaches used RNNs (recurrent neural networks): read words one at a time, left to right, carrying a memory forward as you go.
The cat sat on the mat
Step 1: Read "The" - store in memory
Step 2: Read "cat" → recall "The" AND "cat"
Step 3: Read "sat" → remember all 3
Step 4: Read "on" → remember all 4
That works, but it has two problems. First, each step depends on the one before it, so you cannot spread the work across many processors at once; the sequential dependency is the bottleneck. Second, the memory tends to fade, so long-range connections get lost.
Then came CNNs (convolutional networks), which use the same idea as image recognition: filters that scan for patterns in text. They are much faster and run in parallel, but a filter has a narrow view. A filter looking at 3 words does not know what is happening 10 words away.
The transformer took a different route: do not just read left to right, but look at all the words at once and figure out which ones matter to each other. When generating, it still produces one token at a time, but within each pass it can see all the earlier words at once instead of recalling them one by one.
Consider the sentence “The bank approved the loan because it had strong financials.”
To figure out what “it” refers to, the model checks all the words and scores how relevant each one is to “it”:
It then uses those scores to resolve “it” as “bank”. Nothing was coded about pronouns; the model learned this pattern from billions of examples. Pronoun resolution is only one example. Every word attends to every other word, for all kinds of relationships such as grammar, meaning, and reference.
Attention(Q, K, V) = softmax(Q * KT / sqrt(d_k)) * V
The match score comes from comparing each word’s query against every word’s key, and the result decides how much of each word’s value to pull in.
The real transformer does not run attention just once. It runs several attention passes in parallel, called heads, each free to focus on a different kind of relationship. One head might track grammar while another tracks meaning. It then stacks these attention blocks into many layers, from dozens to over a hundred in large models, refining its understanding of the sentence at each layer.
The key advantage is that all of this happens for every word at once, which GPUs can process in parallel. That speed is why transformers won.
See more: The original transformer paper, “Attention Is All You Need” (arxiv.org)
The transformer core has not changed since 2017, but the attention step has one expensive habit: it compares every token with every other token, so the work grows quadratically with length. Double the text and you roughly quadruple the cost. Most architecture research since then is about getting around that bill, and by 2026 four directions stand out.
For context, the models people compare in 2026 include GPT-5.5, Claude Opus 4.8, Gemini 3.1 Pro, Grok 4.3, and Llama 4. The field genuinely debates what comes next: one camp expects transformers to stay dominant but heavily optimized, while another expects hybrids to take over. The current consensus leans toward hybrid backbones that combine attention, state-space models, and MoE, tuned for different workloads. Either way, the attention idea from Part 2 stays the conceptual center.
See more: Mamba and the rise of post-transformer AI (Medium)
A model gets its abilities in stages, and each stage does something different.
Give the model an enormous amount of text and ask it, billions of times: what is the next word? The models we use for chat, such as GPT, Llama, and Claude, are causal models. They predict the next token using only the words before it, sliding left to right.
Data: internet text, books, code (terabytes of it)
For each sequence:
- Hide the NEXT word (the model only sees the words before it)
- Ask the model: what comes next?
- Compare its guess to the real next word
- If wrong, nudge the weights to be a little less wrong
- Slide forward one word and repeat
There is another approach, masked language modeling, used by BERT. It hides a word in the middle and guesses it from both sides. That works well for understanding and classification, but our chatbots are the next-word kind, because that is what lets them generate text.
Why does this simple game teach so much? Because the best way to predict the next word in “The capital of France is ___” is to have actually absorbed the fact. So across billions of examples the model is pushed to learn:
Take a pre-trained model and specialize it on your own data. Use a low learning rate (careful nudges, not aggressive ones) and a small dataset (thousands of high-quality examples, not billions, since quality matters more than raw count).
Example: build a spam detector.
Start: language model (pre-trained)
Add: 50,000 labeled emails (spam / not spam)
Train: for each email, predict spam or not spam
Result: a model that is good at spam detection
The costs of the two stages differ enormously, which is the key takeaway:
Pre-training teaches general language. Fine-tuning teaches your specific task, at a tiny fraction of the cost.
The spam example skips a step, and it is the one that makes ChatGPT feel like ChatGPT. A purely pre-trained model does not answer questions; it just continues text. Hand it "Explain SQL injection:" and it might continue with more questions, or with a random web-page footer. Two more steps fix that:
Almost everything you associate with an assistant’s behavior comes from this stage rather than from pre-training: being helpful and polite, following instructions, refusing harmful requests, saying “I don’t know”, and keeping a consistent persona.
Inference is what happens when you actually use the model. It generates the answer one token at a time: predict a token, append it, predict the next. That is why you see text stream out word by word.
At each step the model has a probability for every possible next token, for example “31% the, 12% a, …”. Temperature controls how adventurous it is when choosing from those options:
Temperature is why you get a different answer when you re-ask the same thing. If you want repeatable output, for example when testing, set it near 0. If you want brainstorming variety, push it up. The related settings top_p and top_k limit which long-shot tokens are even allowed, which is the same goal reached with a different lever.
A model can only see so many tokens at once. This limit is its context window, which holds the prompt plus the answer so far. It is why very long chats get slower and why a model can seem to forget how a long conversation began: the earliest tokens eventually fall outside what it can see.
Hugging Face is, in effect, GitHub for machine learning models. You can download pre-trained models, their tokenizers, and documentation, with no need to train from scratch.
When you download a model you get:
https://huggingface.co/meta-llama/Llama-2-7b
- model weights (7B params, ~13GB)
- tokenizer configuration
- architecture configuration
- documentation
from transformers import AutoModelForCausalLM, AutoTokenizer
# Download and load
model_id = "meta-llama/Llama-2-7b"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id)
# Generate
prompt = "Explain SQL injection:"
inputs = tokenizer(prompt, return_tensors="pt")
output = model.generate(
**inputs,
max_new_tokens=200,
do_sample=True, # required, or temperature is ignored
temperature=0.7,
)
print(tokenizer.decode(output[0]))
transformers library, generate() uses greedy decoding by default and ignores temperature unless you also pass do_sample=True. Leave it out and your temperature setting silently does nothing.
That is the whole flow: load, tokenize, generate, decode. No training required.
More at huggingface.co
A plain model does exactly one thing: text in, text out. You ask, and it answers. An agent wraps a loop and tools around that same model so it can fetch information before answering.
The agent loop works like this. The model checks whether it can answer directly. If not, it calls a tool (an API, a database, a file), reads the result, and loops again, gathering more until it has enough to respond. Then it writes the final answer based on what it found.
This corrects a common myth. The real contrast is not “ChatGPT versus agents”. Modern ChatGPT is an agent: it browses the web, runs Python, and calls tools, performing exactly this loop. The real distinction is:
The same underlying model can be either; it depends on how it is set up, not on the brand name. When an agent decides it needs more information, that decision is steered by the surrounding scaffolding and prompting. It is clever orchestration, not genuine self-awareness.
Models work, but we cannot fully explain why, at least not in clean, human terms. It helps to separate two meanings of “black box”:
You might hope the attention weights from earlier give you the explanation. Take “The bank approved the loan because it had strong financials”. The model scores “bank” at about 70%, “loan” at about 15%, and the rest at about 15%, and it correctly resolves “it” as “bank”. It is tempting to call that the reason.
But attention weights are not a faithful explanation. Researchers have shown, in “Attention is not Explanation” (Jain and Wallace, 2019), that you can often change the attention weights substantially and get the same output, or reach the same output from very different attention patterns. Attention is just one internal signal among many: there are dozens of layers and heads, plus the feed-forward weights that hold most of the model’s stored knowledge. A single head’s percentages are a hint about where one part of the model looked, not the cause.
The honest situation is that the real reason is spread across billions of weights with no clean human story. That is fine for using a model, since if it works you can use it. But it is why interpretability research, which tries to understand how they work, and safety research, which tries to predict when they will fail, are active and unsolved problems.