How Modern LLMs Work: A Deep Dive Without the Marketing Hype.
Modern LLMs, tokenization, transformers, attention, autoregression, RAG, hybrid search, RLHF, quantization, PEFT, context windows

The vast majority of discussions about LLMs take place on a superficial level. Many people know terms like "transformer," "attention," and "next-token prediction," but almost no one understands their role within the overall system.
By dissecting every element deeply, we see that the model does not function as a mysterious "neural network," but rather as an extremely logical and rational computing engine, whose behavior is entirely determined by data structure and engineering constraints.
NB: Terms and abbreviations are provided at the end of the article.
Tokenization: The Foundation of the Entire Architecture
A model's input consists not of words or sentences, but of tokens. All subsequent work performed by the transformer is impossible without proper tokenization. This is not a mechanical splitting of text into words, but a compression algorithm that determines sequence length and generalization quality.
If a model relies on characters, sequences become too long, and the computational cost grows quadratically. If it relies on whole words, the vocabulary becomes gargantuan and fails at the slightest textual variation. Subwords, and especially byte-level tokens, have found the optimal niche between these extremes.
Byte-level BPE allows the model to avoid encountering "unknown words." Any word, slang, neologism, or typo is decomposed into stable chunks that the model has already seen. As a result, tokenization becomes a miniature language compressor, tailoring the text to the model's capabilities.
The choice of tokenization directly impacts the model's cost, speed, and quality. It determines which linguistic structures the model can learn and at what scale.
Token Space and Why Models "Think" Statistically
Tokens are more than just text compression. Each token corresponds to a vector in a high-dimensional space. This space is continuously refined during training. When a model predicts the next token, it is essentially searching for a direction in this space toward which the meaning of the phrase "strives."
This direction is set by weights, and the probability is selected via softmax. This means the model never operates with logic in the strict sense. It functions as navigation through a continuous, multi-dimensional field. When people say models have "learned to reason," what they actually mean is that the data distribution was so regular that the model discovered stable geometric structures corresponding to logic and sequence.
In other words, an LLM does not derive knowledge like a human; instead, it reconstructs the most probable trajectory in a multidimensional space. Large models demonstrate skills that were not explicitly programmed: arithmetic, logic, and the structuring of complex queries. This may seem like magic, but it is explained by the statistical properties of high-dimensional spaces.
When the number of parameters and data crosses a certain threshold, the model begins to represent abstract concepts as stable structures within the parametric space. These structures then manifest as "new" abilities. This isn't novelty in the human sense; it is a complex byproduct of large-scale training, analogous to phase transitions in physics.
Attention as a Mechanism for Dynamic Context
A transformer is not just a sequence of matrices and nonlinearities. Its core is the attention mechanism, which allows each token to evaluate which other tokens are important at any given moment. To understand attention, one must move away from analogies involving biological attention. This is a purely computational process.
Each token generates three projections: query, key, and value. The query determines what question the current token is asking the context. The key shows which questions that specific token can satisfy. The value contains the useful information that the token will contribute if it proves relevant.
Thanks to multi-head attention, the model can view the text from several angles simultaneously: grammatical, semantic, positional, and structural. Some heads detect long-range dependencies in documents, others track sentence structure, and others learn specific tasks like variable binding in code.
The operation of attention makes the transformer a universal engine for contextual analysis, capable of reconstructing meaning from distributed information.
Autoregression and the Dominance of Decoder-Only Models
Modern LLMs can be viewed as sequence completion simulators. They are trained to predict the next token based on previous ones. This task is so simple and scalable that as parameters increase, the model begins to exhibit multi-layered abilities: reasoning, generalization, and understanding task structures.
Encoder-decoder architectures, such as T5, are ideal for translation and similar tasks, but for general intelligence, they proved too specialized. Decoder-only models, such as GPT, Claude, Gemini, and LLaMA, have gained massive popularity because they have a single goal, a single computational direction, and a single system of optimization.
Autoregression integrates naturally with prompting. Examples, instructions, and step-by-step reasoning are simply additional tokens preceding the continuation. Such a model does not need a separate understanding mechanism; it interprets the context as part of the sequence.
Remarkably, it was this very simplicity that enabled powerful scaling, where the growth of parameters and data led to the emergence of new properties—qualitatively new behaviors that were not manually encoded.
Sampling as a Regulator of Creativity and Precision
During generation, the model does not choose a single best token. It generates a probability distribution. The actual word is determined by a sampling procedure. Temperature determines how sharp or smooth that probability distribution will be. Low temperature turns the model into an almost deterministic algorithm. High temperature provides diversity and creativity.
But temperature is only part of the mechanism. Constraints like top-k and top-p reduce the space of unlikely options. They allow the model to avoid nonsensical words that appear in the tails of the distribution.
In production, sampling is a tool for managing the model's personality. It determines whether the model sounds cautious and precise or free-flowing and creative.
The deeper the generation system, the more important sampling becomes. It can fundamentally change the perception of the model in real-world applications.
The Context Window as a Computational Limit
Every model has a fixed context length. This is not an abstraction, but a physical limit of computation. Attention has quadratic complexity relative to the sequence length. Every extra token increases the cost and degrades the model's ability to focus.
Context window degradation occurs when a sequence contains a large amount of irrelevant text. Dialogue history, repetitive instructions, or document fragments in RAG can all occupy a large portion of the window without improving quality.
Engineering work involves dialogue compression, information filtering, creating long-term memory mechanisms, offloading parts of the context to external systems, and prompt optimization. The context window is a model's most expensive resource. It must be used sparingly.
Many people think that when the attention window is exceeded, the model simply forgets the old text. In reality, something else happens. Within the window, all tokens can interact with each other. But if part of the text disappears, the model loses access to that information not gradually, but instantly. This is called attention boundary tearing. This leads to an effect where the model confidently continues the text based on incorrect premises, creating stable but false chains of thought.
When a model doesn't know a fact, it doesn't say "I don't know." It selects the token with the highest probability in the distribution. If the distribution is flat, the model will still pick the most probable token. But that token might be completely wrong. The model lies confidently because confidence is a mathematical function, not an understanding of truth.
LLMs do not "understand" the world. They model the probabilistic surface of human text. If they seem smart, it is because human language is deeply structured. The model learns this structure. It replicates it with impressive accuracy, but always through the lens of probabilities. This is exactly why LLMs can be deceived by incorrect prompts, strange formats, or ambiguous tasks. It doesn't work top-down like a human. It works bottom-up, based on statistics.
Embeddings and RAG as a way to reduce hallucinations
Large models shouldn't know all the data internally. That is expensive, slow, and inefficient. RAG turns an LLM into a processor of meaning that connects to an external knowledge base. This is analogous to memory in computer architecture. The model becomes the CPU, and the vector database becomes the RAM.
Document text is split into chunks, converted into embeddings, and stored in a vector database. When a user asks a question, the system searches for the most relevant chunks based on semantic similarity and passes them to the model.
Embeddings represent the meaning of the text, not its form. Semantically similar chunks are located near each other in the vector space.
This approach eliminates many types of hallucinations, as the model begins to rely on real data rather than guesswork.
Hybrid search and the problem of literal matches
Semantic search works brilliantly for general questions. However, in technical and legal documents, literal matches are crucial: article numbers, ID codes, specific formulas.
Semantics can smooth over the difference between similar terms. Therefore, hybrid search is used, combining semantic similarity with keyword searching.
This combination allows the system to find a document that doesn't just "relate to the topic," but contains the exact fact needed.
The hybrid approach has become the standard for enterprise RAG systems.
RLHF as a mechanism for alignment with human norms
To ensure a model doesn't just generate text, but does so safely, consistently, and socially acceptably, RLHF (Reinforcement Learning from Human Feedback) is used. Its purpose is to train the model to align with human preferences.
First, examples of "good answers" are collected. Then, a reward model is trained to rank these answers. Finally, the main model is optimized to maximize the score given by this reward model.
The problem is that the reward model is an approximation, not the truth. It can produce superficial, overly cautious answers. Sometimes, models begin to avoid questions that seem risky to them.
RLHF improves behavior but requires careful control, as it can easily introduce biases.
Quantization as a way to make models cheaper
Modern models are massive. Full FP16 or FP32 precision is too expensive. Quantization allows weights to be represented in a more compact form, such as INT8 or INT4.
Naive quantization performs poorly: the activation distribution contains outliers that stretch the range and degrade accuracy. Modern methods analyze each channel separately, keeping sensitive parts at high precision while quantizing the rest.
This provides a two-fold reduction in memory with minimal loss in quality.
PEFT as a fine-tuning mechanism
Full model retraining is inaccessible to most companies. PEFT (Parameter-Efficient Fine-Tuning) allows for training small adapters that are then inserted into a frozen model. LoRA has become the industry standard. QLoRA adds 4-bit quantization to this for even greater efficiency.
These methods allow models to be adapted to niche industries without consuming gargantuan computational resources. In effect, PEFT has democratized LLM training.
People often ask why a 70B model performs better than a 7B model if both have seen the same data. A larger model can "fit" more factors into its parameters: rare expressions, logical patterns, and long-range dependencies. A smaller model is forced to aggressively smooth out the statistics and loses detail. This is called the capacity limit. However, sufficient fine-tuning or a good adapter architecture can elevate a small model to the level of a medium-sized one.
Production metrics as a true measure of quality
LMMs cannot be evaluated by benchmarks alone. Factuality, latency, stability, citation capability, hallucination rate, cost per thousand tokens, behavior under load, and regression susceptibility are all vital.
In production, models are double-checked by their own verifiers, answers are analyzed by additional systems, and the effects of drift and unforeseen deviations are monitored.
- Tokenization compresses text.
- Attention reshapes context.
- Autoregression predicts continuations.
- Sampling controls style.
- Context sets the boundaries. RAG adds facts. Hybrid search improves accuracy.
- RLHF sets behavioral norms.
- Quantization makes the model accessible.
- PEFT allows it to be adapted.
Terms and Definitions
LLM: Large Language Model.
Transformer: A neural network architecture that uses an attention mechanism to process sequences.
Token: The smallest unit of text a model works with—a subword, a piece of a word, or a byte.
Tokenization: The process of converting text into tokens.
BPE: Byte Pair Encoding, an algorithm for subword tokenization.
Byte BPE: BPE at the byte level, the modern standard in GPT models.
Attention: An attention mechanism that calculates relevance between tokens.
Self Attention: Attention within a single sequence.
Multi Head Attention: Multi-head attention, involving several parallel attention matrices.
Embedding: An embedding, a numerical vector representing the meaning of a word, token, or document.
Context Window: The maximum sequence length a model can process.
Context Overflow: Context window overflow.
RAG: Retrieval Augmented Generation, retrieving text from a database and providing it to the model as context.
Vector Embedding: a vector representation of a text fragment.
Vector Database: a vector database that supports nearest neighbor search.
ANN: Approximate Nearest Neighbor Search, an approximation method for finding the closest neighbors.
BM25: a classic keyword-based search algorithm.
TF-IDF: a statistical method for weighting words to enable precise searching.
Hybrid Search: a combined search approach that merges BM25 and vector search.
Zero Shot: performing a task without any prior examples.
Few Shot: performing a task using a few provided examples.
Chain of Thought: a reasoning chain where the model verbalizes its problem-solving steps.
Sampling: selecting the next token from a probability distribution.
Temperature: a coefficient used to smooth or sharpen token probabilities.
RLHF: Reinforcement Learning from Human Feedback, training models using human feedback.
SFT: Supervised Fine-Tuning, initial supervised fine-tuning using human-curated examples.
RM: Reward Model, a model used to rank different responses.
PPO: Proximal Policy Optimization, a reinforcement learning algorithm for models.
Hallucination: a hallucination, where the model provides a plausible but false answer.
Drift: model drift, the change in model behavior over time.
Monitoring: a system for tracking model metrics in production.
PEFT: Parameter-Efficient Fine-Tuning, methods for efficient fine-tuning.
LoRA: Low-Rank Adaptation, fine-tuning using small, low-rank matrices.
QLoRA: Quantized LoRA, applying LoRA on top of a 4-bit quantized model.
Prefix Tuning: a fine-tuning method that adds trainable prefixes to the input.
Adapter Tuning: inserting small, trainable modules into the model layers.
Quantization: quantization, the process of converting model weights to a lower precision.
If you are interested in AI, technology, and the future—welcome to my channel to discuss and share updates.
Translated from Russian. Original on vc.ru: Как устроены современные LLM? Глубокий разбор без маркетинга.