How Large Language Models Work: Tokens, Transformers, and Inference
Learn how LLMs turn text into tokens, predict the next token with transformers, and produce reliable outputs in real products.
AI-generated explainer by Dilectus · · 7 min read
Large language models can feel magical because they turn a prompt into fluent text in one shot. Under the hood, though, they do something much simpler: they convert text into tokens, run those tokens through a transformer, and repeatedly predict the next token until a response is complete.
If you understand that pipeline, you can reason about latency, cost, hallucinations, context limits, and why some prompts work better than others.
The core idea: predict the next token
An LLM is trained to answer one question over and over:
Given the tokens so far, what token should come next?
That sounds small, but at scale it becomes powerful. If a model is good at next-token prediction across huge amounts of text, it learns patterns in language, code, reasoning steps, and style.
A practical way to think about it:
- You type a prompt.
- The model breaks it into tokens.
- It computes a probability distribution over possible next tokens.
- It picks one token.
- It appends that token to the context and repeats.
This is why generation is autoregressive: each new token depends on the tokens before it.
Tokens: the model never sees raw text
LLMs do not read characters or words directly. They read tokens, which are chunks of text produced by a tokenizer. A token may be a whole word, part of a word, punctuation, or even whitespace.
For example, the phrase unbelievable results might become something like:
unbelievableresults
The exact split depends on the tokenizer used by the model.
Why this matters:
- Cost is usually tied to token count, not character count.
- Very long words or uncommon terms may split into multiple tokens.
- Prompt length affects both latency and the amount of context the model can use.
Tokenization trade-offs
| Aspect | Fewer/larger tokens | More/smaller tokens |
|---|---|---|
| Prompt cost | Usually lower | Usually higher |
| Vocabulary coverage | Harder for rare text | Better for rare text |
| Sequence length | Shorter | Longer |
| Efficiency | Often better | Often worse |
In interviews and product work, token budgeting is a real skill. A prompt that looks short to a human can be expensive if it contains code, JSON, logs, or long identifiers.
What a transformer does with those tokens
The transformer is the neural network architecture behind most modern LLMs. Its job is to turn a sequence of tokens into useful internal representations, while paying attention to which earlier tokens matter most for the current position.
At a high level, the model does three things:
- Converts each token into an embedding vector.
- Mixes information across tokens using attention.
- Repeats this across many layers to build richer representations.
Prompt text
|
v
Tokenizer
|
v
Token IDs -> Embeddings -> Transformer layers -> Next-token probabilities
|
v
Sample one token
|
v
Append and repeat
Embeddings: turning tokens into vectors
A token ID is just an integer. The model first maps that ID to an embedding, which is a vector of numbers. Similar tokens tend to end up with related vectors, though the exact meaning is learned during training.
You can think of embeddings as the model’s internal coordinate system for language. They help the model represent relationships like:
Parisis closer toFrancethan tobananaJavain a programming context differs fromJavathe island- code tokens and natural-language tokens can live in the same space
Attention: deciding what to focus on
Self-attention lets the model look back at earlier tokens and decide which ones matter for the current token.
For example, in the sentence:
The shipment arrived late because the truck broke down.
When predicting or refining the meaning of late, the model should pay attention to shipment and truck broke down, not just the nearest word.
This is one reason transformers work well on long-range dependencies. They are not limited to a fixed window of nearby words in the same way as older sequence models were.
What happens during inference
Inference is the phase where the trained model is used to generate output. Training is expensive and happens offline; inference is what your application pays for every time a user sends a prompt.
A simplified inference flow looks like this:
- The user sends a prompt.
- The system adds any system instructions, conversation history, retrieved documents, or tool outputs.
- The tokenizer converts the full input into token IDs.
- The model processes the tokens and produces logits, which are raw scores for the next token.
- A decoding strategy chooses the next token.
- The token is appended to the context.
- Steps 4–6 repeat until the model stops.
Decoding is not the same as “thinking”
The model produces probabilities; your application chooses how to turn them into text. Common strategies include:
- Greedy decoding: pick the highest-probability token each time.
- Sampling: choose from a probability distribution for more variety.
- Top-k / top-p: restrict choices to likely tokens.
- Temperature: control randomness.
A lower temperature usually makes outputs more deterministic. A higher temperature can produce more diverse answers, but also more errors or drift.
| Strategy | Output style | Best for | Risk |
|---|---|---|---|
| Greedy | Deterministic | Classification, extraction | Repetitive, less creative |
| Sampling | Diverse | Brainstorming, generation | More variance |
| Top-p | Balanced | Chat, creative tasks | Can still drift |
| Low temperature | Conservative | Factual formatting | May become dull |
Why LLMs can sound smart but still be wrong
An LLM is optimized to generate plausible next tokens, not to verify truth. That distinction explains many failure modes.
Common issues:
- Hallucinations: the model produces confident but incorrect details.
- Instruction drift: it starts well, then loses the original constraint.
- Context overload: too much input makes it miss important parts.
- Ambiguity: if the prompt is vague, the model fills gaps with guesses.
This is why production systems should not treat the model as a source of truth by itself. For reliable products, combine the model with retrieval, validation, structured outputs, and domain-specific checks.
Practical reliability pattern
For a support assistant, a safer flow is:
- Retrieve the relevant policy or document.
- Put only the needed excerpts into the prompt.
- Ask for a structured answer.
- Validate the output against rules.
- Fall back to a human or deterministic workflow when confidence is low.
That approach usually beats “just ask the model” for accuracy and auditability.
When to use it (and when not to)
LLMs are a good fit when the task involves language variation, fuzzy inputs, or synthesis across many documents.
Use an LLM when you need to:
- summarize long text
- classify messy user input
- draft responses
- extract entities from semi-structured text
- answer questions over retrieved documents
- transform text from one format to another
Avoid using an LLM as the only component when you need:
- exact arithmetic
- guaranteed factual correctness
- strict compliance logic
- deterministic business rules
- low-latency decisions with simple conditions
A useful rule: if a normal program can solve the problem exactly and cheaply, use the program. Use the LLM where language understanding or generation adds real value.
What affects latency, cost, and quality
In production, the same prompt can feel fast in one case and slow in another because several factors stack up.
Main levers
- Input token count: more context means more work.
- Output token count: longer answers take longer and cost more.
- Model size: larger models usually improve quality but increase cost and latency.
- Context window usage: very long prompts can slow inference and raise the chance of missing details.
- Decoding settings: sampling can add variability; greedy decoding is often more stable.
A simple mental model:
- 200 input tokens + 50 output tokens: usually cheap and quick
- 8,000 input tokens + 1,000 output tokens: much slower and more expensive
The exact numbers depend on the model and serving setup, but the relationship is consistent: token volume drives cost.
How this comes up in interviews
Interviewers usually want to see whether you understand the pipeline, not just the buzzwords.
What they often probe
- What is a token, and why does tokenization matter?
- What does a transformer do differently from older sequence models?
- What happens during inference step by step?
- Why do LLMs hallucinate?
- How would you make an LLM-based feature more reliable?
- How do temperature and top-p affect output?
How to answer well
A strong answer is usually structured like this:
- Start with the pipeline: text → tokens → embeddings → transformer → next-token prediction.
- Explain inference as repeated token generation.
- Mention that the model outputs probabilities, and decoding chooses the final token.
- Connect the internals to product concerns like latency, cost, and hallucination.
- Close with a reliability strategy such as retrieval, validation, or tool use.
If asked to design an LLM feature, do not jump straight to the model. First clarify the task, then discuss prompt design, context limits, retrieval, output format, and fallback paths.
Key takeaways
- LLMs work by predicting the next token, one step at a time.
- Tokenization matters because the model never sees raw text directly.
- Transformers use attention to combine information across the input context.
- Inference is a repeated loop of scoring, decoding, and appending tokens.
- LLMs generate plausible text, not guaranteed truth, so product reliability needs extra guardrails.
- Token count, model size, and decoding settings strongly affect latency and cost.
Frequently asked questions
- What is the difference between training and inference in an LLM?
- Training is when the model learns patterns from huge datasets and updates its weights. Inference is when a trained model is used to answer a prompt and generate text. Training is expensive and offline; inference is what your product uses at runtime.
- Why do LLMs use tokens instead of words?
- Tokens give the model a flexible vocabulary that can handle common words, rare words, punctuation, code, and multilingual text. A word-based system would struggle with unseen terms and would waste a lot of vocabulary on rare forms. Tokenization also helps keep the model efficient.
- Why do LLMs sometimes hallucinate?
- Because the model is optimized to produce the most likely next token, not to verify facts. If the prompt is ambiguous, incomplete, or outside the model’s knowledge, it may generate something that sounds correct but is not. Retrieval, validation, and structured outputs reduce this risk.
- Is a bigger model always better?
- Not always. Bigger models often improve quality, but they also increase cost, latency, and operational complexity. For many product tasks, a smaller model with good prompting, retrieval, and validation is the better engineering choice.

