How Large Language Models (LLMs) Work: From Tokenization to Text Generation
Hi! Modern large language models (LLMs), such as GPT-X, Claude X.X, Gemini, and Llama X, have transformed software development, data analysis, and content creation in recent years. To users, interacting with AI feels like having a conversation with a real person: you send a prompt and, in a fraction of a second, receive coherent text, working code, or a solution to a logic problem. Behind that experience, however, lies precise mathematics and a set of algorithms.
LLMs do not “think” in the human sense. They are powerful statistical machines whose predictive mechanism comes down to one task: determining which word (or part of a word) should come next. An LLM has no consciousness or understanding of things as humans do. Technically, a large language model is a complex, highly parameterized probabilistic autoregressive algorithm. Its core mathematical task is to calculate the probability of the next token based on all the preceding context.
- 1. Tokenization: Turning Text into Mathematical IDs
- The BPE (Byte Pair Encoding) Algorithm
- 2. Vector Embeddings and Positional Encoding: Giving Tokens Meaning
- The Semantic Vector Space
- Positional Encoding
- 3. The Heart of an LLM: Transformer Architecture and Self-Attention
- How Does Self-Attention Work?
- Multi-Head Attention
- 4. The Main Types of Transformer Architectures
- 5. The Three Stages of LLM Training
- Stage 1: Pre-training
- Stage 2: Supervised Fine-Tuning (SFT / Instruction Tuning)
- Stage 3: RLHF (Reinforcement Learning from Human Feedback) and DPO
- 6. Text Generation and Token Selection
- Temperature
- Top-K Sampling
- Top-P Sampling (Nucleus Sampling)
- 7. Why Do LLMs Hallucinate, and How Can We Address It?
- Why Hallucinations Happen
- How to Reduce Hallucinations
- 8. FAQ: Frequently Asked Questions About How LLMs Work
- How is an LLM different from a traditional database?
- What is a context window?
- What does the number of parameters in a model name (such as 7B, 70B, or 405B) mean?
- Why do LLMs sometimes struggle to count letters in words or solve simple math problems?
- Conclusion
In this article, I’ll walk through the complete LLM lifecycle: from processing raw text to large-scale training, response generation, and mitigating side effects such as “hallucinations.”
1. Tokenization: Turning Text into Mathematical IDs
CPUs, GPUs, and neural networks cannot process characters or words directly. The first step in processing any input text is tokenization—splitting a continuous string into meaningful chunks (tokens) and replacing them with numerical identifiers (IDs).
The BPE (Byte Pair Encoding) Algorithm
Most modern LLMs use variations of BPE (Byte Pair Encoding) or WordPiece. BPE works as follows:
- A base vocabulary is created from all individual characters (letters, punctuation marks, and special characters).
- The algorithm counts the most common pairs of consecutive characters and merges them into new tokens.
- This process repeats until the vocabulary reaches a specified size (typically 32,000 to 128,000 unique tokens).
This allows the model to encode common words efficiently as whole units, while splitting rare or unfamiliar terms into subwords.
| Input word / phrase | Tokens (subword split) | Numeric ID (example) |
|---|---|---|
programming | program, ming | [14205, 8812] |
LLM | L, LM | [43, 981] |
optimization | optim, ization | [22104, 5102] |
💡 Tokenization and Cyrillic scripts. Since many open language models were trained primarily on English-language internet content, their vocabularies contain fewer ready-made Cyrillic words. As a result, Ukrainian text, for example, is often split into smaller tokens. This increases the number of tokens required per prompt and reduces the effective context window.
2. Vector Embeddings and Positional Encoding: Giving Tokens Meaning
After tokenization, we have a vector of integers such as [14205, 8812]. But IDs alone carry no information about the meaning of words. To a model, ID 14205 and ID 14206 are simply arbitrary numbers with no mathematical relationship.
To give tokens semantic meaning, models use word embeddings.
The Semantic Vector Space
Each token ID is mapped to a high-dimensional vector (for example, 4096, 8192, or 12288 numbers in modern models). In this multidimensional space, the vector coordinates represent semantic properties of a word.
The famous semantic arithmetic of embeddings illustrates this principle:
Words used in similar contexts (for example, “cat” and “dog,” or “developer” and “programmer”) are located close to one another in vector space.
Positional Encoding
By design, a neural network processes all embeddings in an input sequence in parallel and has no innate understanding of word order. Yet order can fundamentally change meaning:
- “The cat eats the mouse”
- “The mouse eats the cat”
To preserve sentence structure, a positional encoding vector is added to each embedding vector. Modern architectures use advanced positional methods such as RoPE (Rotary Position Embedding) and ALiBi, which help models work effectively with context windows spanning hundreds of thousands or even millions of tokens.
3. The Heart of an LLM: Transformer Architecture and Self-Attention
The AI revolution took off in 2017 with the publication of Google researchers’ seminal paper, “Attention Is All You Need.” Before then, recurrent neural networks (RNNs and LSTMs) dominated natural language processing (NLP). They processed text sequentially, one word at a time, which made them slow and difficult to train in parallel across thousands of GPUs.
The Transformer architecture solved this problem by replacing recurrence with Self-Attention.

How Does Self-Attention Work?
Self-Attention allows each token, during processing, to “pay attention” to every other token in a sentence and weigh its importance for understanding the context.
Consider this sentence:
The server rejected the developer’s request because it was overloaded.
What does “it” refer to the server or the developer? Using Self-Attention, the model calculates mathematical relationship scores (attention weights). In this context, the weight between “it” and “server” will be much higher than the weight between “it” and “developer.” If we change the end of the sentence to “...because they made a syntax error,” the attention weights immediately shift toward “developer.”
Mathematically, three vectors are created for each token:
- Query (Q): what the token is looking for in the context.
- Key (K): the information the token offers.
- Value (V): the meaningful information passed on to the next layer.
The attention calculation formula (Scaled Dot-Product Attention):

Multi-Head Attention
LLMs perform this process not just once, but in parallel through dozens of “attention heads.” One head might track grammatical relationships, another the chronology of events, a third synonym relationships, and a fourth the type of object being described. Combining their results gives the model a richer, more nuanced representation of context.
4. The Main Types of Transformer Architectures
Depending on the task, Transformers fall into three main families:
| Architecture type | Examples | How it works | Typical tasks |
|---|---|---|---|
| Encoder-Only | BERT, RoBERTa | Bidirectional processing (can use context from both the left and the right). | Text classification, sentiment analysis, search indexing. |
| Decoder-Only | GPT-4, Llama 3, Claude, Mistral | Unidirectional autoregressive processing (sees only previous tokens). | Generative tasks, code generation, conversational systems, text writing. |
| Encoder-Decoder | T5, BART, Whisper | The encoder compresses the input text; the decoder generates new text from it. | Machine translation, summarization, speech recognition. |
Most modern chatbots and general-purpose AI systems are built on the Decoder-Only architecture.
5. The Three Stages of LLM Training
Building a modern LLM is a multimillion-dollar process that requires gigawatts of electricity, clusters of thousands of GPUs (such as Nvidia H100s or B200s), and three consecutive training stages.

Stage 1: Pre-training
- Goal: teach the model language, how the world is structured, facts, and basic reasoning.
- Data: terabytes of text (web pages, databases, Wikipedia, open-source code repositories, and books).
- Process: the model learns through unsupervised learning. It is given the beginning of a text and asked to predict the next word. By comparing its prediction with the actual text, the model adjusts billions of internal weights (parameters).
⚠️ Pre-training produces what is known as a base model. It is excellent at continuing text, but it does not yet know how to answer questions. If you ask it, “What is the capital of France?,” it might not answer “Paris”. Instead, it could continue with a list: “What is the capital of Spain? What is the capital of Italy?”—because it interprets your prompt as the beginning of a quiz.
Stage 2: Supervised Fine-Tuning (SFT / Instruction Tuning)
- Goal: teach the model to follow instructions and handle a question-and-answer format.
- Data: hundreds of thousands of high-quality, labeled Prompt–Ideal Response pairs created by expert annotators.
- Process: the model is further trained on high-quality conversations. After SFT, it becomes an instruct model and understands that it is expected to carry out a specific instruction.
Stage 3: RLHF (Reinforcement Learning from Human Feedback) and DPO
- Goal: align the model’s responses with human preferences, making it helpful, accurate, and safe (reducing toxicity, harmful advice, and outright falsehoods).
- Process:
- The model generates several possible responses to a single prompt.
- Human evaluators (or a dedicated evaluator model in RLAIF) rank the responses from best to worst.
- A reward model is trained using these rankings.
- The original LLM adjusts its weights using optimization algorithms (such as PPO or DPO — Direct Preference Optimization) to earn the highest reward for producing quality responses.
6. Text Generation and Token Selection
Once a model is trained and you send it a prompt, at each step of the autoregressive cycle it produces not a single token, but a probability distribution over every token in its vocabulary using the Softmax function.
For example, for the phrase “The best language for web development is...”, the model might assign the following probabilities to the next token:
JavaScript: 45%Python: 25%PHP: 15%watermelon: 0.00001%
Three main inference hyperparameters control which token is selected:

Temperature
This parameter reshapes the probability distribution before a token is selected:
- Temperature = 0.0 (Greedy Search): the model always picks the highest-probability token (fully deterministic). This is ideal for programming, math, and straightforward factual answers.
- Temperature = 0.7–1.0: the distribution becomes flatter, increasing the chance of selecting less obvious tokens. Responses become more varied and creative.
- Temperature > 1.5: the model starts selecting unlikely words, which can undermine coherence and produce “nonsense.”
Top-K Sampling
This limits the choice to the K most likely tokens. If Top-K = 50, the model ignores every token outside the top 50 and redistributes the probabilities among those candidates.
Top-P Sampling (Nucleus Sampling)
Instead of using a fixed number of words, the model selects the smallest set of most likely tokens whose combined probability reaches P (for example, 0.9, or 90%). If the top token alone has a 92% probability, it will be the only candidate. When there are many plausible options, the candidate list expands.
7. Why Do LLMs Hallucinate, and How Can We Address It?
One of the biggest challenges with language models is hallucination: cases where an LLM confidently produces convincing-sounding information that is entirely made up or incorrect.
Why Hallucinations Happen
- Probabilistic nature: the model does not verify facts against a database; it selects statistically plausible sequences of tokens.
- Outdated or contradictory training data: if the training corpus contains inaccurate information, the model may reproduce it.
- Sycophancy: the model may try to please the user by confirming false assumptions embedded in the prompt.
How to Reduce Hallucinations
- RAG (Retrieval-Augmented Generation): connect an LLM to an external vector database. Before generating a response, the system retrieves relevant documents from your data, adds them to the prompt context, and instructs the model to answer only on the basis of the supplied facts.
- System prompts: provide clear instructions such as: “If you cannot determine the answer from the text provided, say: ‘I don’t have that information.’”
- Chain of Thought (reasoning models): encourage the model to break a task into sequential reasoning steps before giving its final answer (as in OpenAI’s o1/o3 series or DeepSeek R1).
8. FAQ: Frequently Asked Questions About How LLMs Work
How is an LLM different from a traditional database?
A database stores precise, structured facts and retrieves them in response to a query. An LLM does not store the facts themselves; it stores abstract mathematical weights and relationships between concepts, reconstructing text from scratch each time it generates a response. It is more like a "compressed associative memory" than a file repository.
What is a context window?
A context window is the maximum amount of text, measured in tokens, that a model can keep in view at once while processing a prompt. This includes the conversation history, system prompt, and generated response. Context windows in modern models range from 8,000 to more than 2,000,000 tokens.
What does the number of parameters in a model name (such as 7B, 70B, or 405B) mean?
Parameters (weights) are numerical values inside a neural network that are adjusted during training. "7B" means 7 billion parameters. In general, models with more parameters handle complex reasoning tasks better, encode more factual knowledge, and capture language nuances more effectively — but they also require substantially more memory (VRAM) to run.
Why do LLMs sometimes struggle to count letters in words or solve simple math problems?
This is a direct consequence of tokenization. The model sees a word not as a sequence of individual letters, but as a single token ID. For example, the word "programming" might be represented to the model as two units: [14205, 8812]. Without additional character-by-character analysis, it literally cannot "see" the individual letters inside a token.
Conclusion
Large language models are not magical boxes with minds of their own. They are an impressive result of combining advanced algebra, probability theory, computational optimization, and enormous datasets.
Understanding Transformer architecture, Self-Attention, tokenization, and the stages of RLHF helps developers and engineers write better prompts, design reliable RAG systems, reduce hallucinations, and integrate AI effectively into their products.
