LLM Fundamentals

Following a sentence from raw text to a finished answer, and how the model that answers it was made

Share

LLM Fundamentals

A practical guide to how large language models read, learn, generate answers, use tools, and where their limits matter.

Cyber Academy

Summary

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.

The Big Picture

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:

  • Part 1, How a model reads your words. Turning text into numbers, first tokens and then embeddings.
  • Part 2, How the model thinks. The transformer and self-attention.
  • Part 3, Where its abilities come from. Pre-training, fine-tuning, and alignment.
  • Part 4, Using a model. Generating answers, running one yourself, and agents.
  • Part 5, Limits. Why models are black boxes.
Part 1 · How a model reads your words

Tokenization

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.

Cost. Hosted providers such as OpenAI and Anthropic charge per token, counting both the tokens you send in and the tokens generated back. Longer prompts and longer answers cost more. Across a million requests, that adds up to real money.
Speed. More tokens mean more to process and generate, which means a longer wait. Fewer tokens mean a faster answer. This is exactly why very long chats start to feel sluggish.

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.

Byte Pair Encoding

How does a tokenizer decide where to split? The most common method is Byte Pair Encoding (BPE):

  1. Start with individual bytes. Modern tokenizers work on raw bytes rather than characters, which is why it is called byte pair encoding.
  2. Find the most common pair of symbols that appear next to each other.
  3. Merge that pair into a single new token.
  4. Repeat thousands of times.
  5. Stop when the vocabulary reaches the size you want, for example 50K or 100K tokens.

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.

Special Tokens

Not every token is content. Some are markers that tell the model about structure rather than meaning.

<bos>
Beginning of sequence (start)
<eos>
End of sequence (stop)
<|im_start|>
Message block starts here (“im” stands for instant message)
<|im_end|>
Message block ends here
<pad>
Padding (filler so a batch of inputs is the same length)
<unk>
Unknown token (rare now, because byte-level BPE means almost nothing is truly unknown)

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.

Security angle. These markers are what separate the system instruction from the user input. That boundary is the target of prompt-injection attacks: an attacker tries to smuggle or fake these structural tokens inside user-supplied text, blurring the line so the model treats their input as a trusted instruction. Understanding the tokenization boundary is understanding the attack surface.

From Tokens to Meaning: Embeddings

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.

Part 2 · How the model thinks

Transformer Architecture

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.

Self-Attention

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”:

  • “bank” → 70%
  • “loan” → 15%
  • “financials” → 10%
  • all else → 5%

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 Formula
Attention(Q, K, V) = softmax(Q * KT / sqrt(d_k)) * V
Q (query)
What the current word is looking for
K (key)
A label each word advertises about itself
V (value)
The actual content a word hands over once it is matched
softmax
Turns the match scores into percentages that add up to 100%
sqrt(d_k)
A scaling factor that keeps the numbers stable

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.

Multi-Head Attention and Layers

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)

Where Transformers Are Heading

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.

Mixture-of-Experts (MoE)
Instead of running the whole network for every token, route each token to a few specialized sub-networks (“experts”). A very large model then costs about as much per token as a much smaller one. Meta’s Llama 4 family (April 2025) is built this way, and MoE is now common across frontier models.
FlashAttention
A smarter way to run the exact same attention math on the GPU, created by Tri Dao and now in its third version (FlashAttention-3). It makes attention much faster and lighter on memory, which is what makes today’s long context windows practical.
State-space models (Mamba)
An alternative to attention that scales linearly with length rather than quadratically, so it handles very long inputs far more cheaply. It is the leading candidate for a “post-transformer” backbone.
Hybrids
Rather than pick one, recent systems mix them. Jamba (AI21 Labs) interleaves transformer attention with Mamba layers and adds MoE on top, and Nvidia’s Nemotron 3 family (December 2025) uses a hybrid Mamba-transformer MoE design aimed at long context and high throughput.

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)

Part 3 · Where its abilities come from

Pre-Training, Fine-Tuning, and Alignment

A model gets its abilities in stages, and each stage does something different.

Stage 1, Pre-Training

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:

  • Syntax and grammar
  • Facts (who, what, when)
  • Reasoning patterns
  • Tones and styles
Why models hallucinate. The pre-training goal rewards plausible-sounding continuations, not true ones. So when the model lacks a solid pattern, it still produces a confident, fluent guess. That guess is a hallucination, a direct side effect of being optimized for plausibility rather than truth.

Stage 2, Fine-Tuning

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: tens to hundreds of millions of dollars, months, thousands of GPUs.
  • Fine-tuning: often tens to a few hundred dollars on a single GPU for small jobs, using efficient methods such as LoRA. Larger fine-tuning efforts across several GPUs run higher.

Pre-training teaches general language. Fine-tuning teaches your specific task, at a tiny fraction of the cost.

Stage 3, Alignment (Instruction Tuning and RLHF)

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:

  • Instruction tuning: fine-tune on many “instruction, then good answer” pairs, so the model learns to follow requests instead of just continuing text.
  • RLHF (Reinforcement Learning from Human Feedback): humans rank competing answers, and the model is trained to prefer the kind people approve of. Think of a chef adjusting recipes based on diners’ ratings.

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.

Security angle. Alignment is powerful but imperfect. Guardrails are learned preferences, not hard rules, which is exactly why models can sometimes be talked around their safety training (jailbreaks) or be confidently wrong. Making alignment robust is an open research area.
Part 4 · Using a model

Inference: Generating an Answer

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.

Temperature and Sampling

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:

  • Low (near 0): almost always grab the single most likely token. Focused, repeatable, and a little plain, so the same prompt tends to give the same answer.
  • High (above 1): take more chances on long-shot tokens. Creative and surprising, but more likely to wander or make mistakes.
  • Around 0.7: a sensible middle, natural and varied while staying coherent. It is a common default.

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.

The Context Window

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.

Running a Model Yourself: Hugging Face

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

How to Use It

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]))
Common pitfall. In the 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

Agents: Models That Take Action

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:

  • Plain or base model: pure text prediction, no actions.
  • Agent: that same model given tools and a loop.

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.

Part 5 · Limits

Why Models Are Black Boxes

Models work, but we cannot fully explain why, at least not in clean, human terms. It helps to separate two meanings of “black box”:

  • What is actually true: we cannot read out a tidy rule for any single decision.
  • What is a myth: the idea that we know nothing about them. We built every part of these models and know the architecture, the training process, and the math exactly. What we cannot do is point to a clause and say “that is the rule it used”.

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.

References