How LLMs Work?
From the publisher’s feed, collected in the ZeroLabs newsroom.
A walkthrough of the full pipeline behind Large Language Models and how they generate responses.IntroductionWhile interacting with an LLM may feel as simple as typing a prompt and receiving an answer, the underlying system performs a complex pipeline involving tokenization, embeddings, self-attention, probability calculations, and continuous learning through optimization. Each stage plays a critical role in enabling the model to understand context, recognize patterns, and predict the most appropriate next token.Now let’s put it all together. The image below shows the complete training pipeline of a language model. Here’s what each stage means.Phase 1: DatasetsEverything starts with data. LLMs are trained on enormous collections of text — web pages crawled from the internet (like Common Crawl), books, Wikipedia, academic papers, GitHub repositories, and more. This raw data is cleaned, deduplicated, and filtered for quality.Example: GPT-3 was trained on roughly 570GB of compressed text — more than a million books’ worth of content.Phase 2: Tokenize (Text → IDs)Raw text can’t be fed directly into a neural network. It must first be tokenized — broken into small units called tokens, each assigned a numeric ID.In this journey, we will let LLM to predict the next word of the sentence we have given as below.Each token maps to a unique ID in the vocabularyAs shown in the diagram: the word “the” might be token ID 278, “france” might be 3444, and “is” might be 338. Most modern LLMs use Byte Pair Encoding (BPE) or SentencePiece tokenization, which splits text into subword units.Example: The word “unbelievable” might be tokenized as [“un”, “believ”, “able”] — three tokens, not one. This lets the model handle rare or new words by composing them from known parts.How about the data preparation, here is to visualizePhase 3: Embedding (ID → Vectors)Token IDs are integers — but neural networks work with continuous numbers. An embedding layer converts each token ID into a high-dimensional vector (typically 768 to 12,288 dimensions in modern models).These vectors are not random — they’re learned during training so that tokens with similar meanings end up close together in this high-dimensional space. The classic example: the vector for “king” minus “man” plus “woman” ≈ the vector for “queen.”Example: The words “happy,” “joyful,” and “elated” will have very similar embedding vectors. The word “sad” will be far away — but in a predictable direction from “happy,” because the model has learned the concept of emotional polarity.Phase 4: Self-AttentionThis is the core innovation of the Transformer architecture, introduced by Google in the landmark 2017 paper “Attention Is All You Need.”Self-attention allows every token in a sequence to “attend” to every other token — weighting how much each token should influence the representation of every other token.As shown in the diagram, processing the sequence “I see with my…” — the token “see” will attend strongly to “I” (who is seeing) and potentially to “eyes” if it appeared — building up rich, context-aware representations.Q= “search” — What am I looking for?K= “match” — How do I match with others?V= “content” — What information do I provide if chosen?Modern LLMs stack many layers of self-attention (GPT-4 has 96 layers), each refining the representations further.WOW!! You see how well each word recognizes each other. (Do not forget that is the core/main idea of the LLMs)Phase 5: LogitsAfter passing through all attention layers, the model produces a logit — a raw score — for every token in its vocabulary (typically 50,000–100,000+ tokens).These scores represent the model’s “vote” for how likely each token is to come next. A high logit for “Paris” and a very low logit for “banana” when predicting the completion of “The capital of France is…”Phase 6: SoftmaxThe logits are fed through a Softmax function, which converts the raw scores into a valid probability distribution — all values between 0 and 1, summing to exactly 1.Logits: [4.2, 1.1, -0.5, 3.8, ...] ↓Softmax: [0.52, 0.06, 0.01, 0.39, ...] ↓Probabilities sum to 1.0The model then samples from this distribution (or picks the highest value, depending on settings like temperature) to select the next token.Phase 7: Cross-Entropy LossDuring training, the model knows what the correct next token should be (it’s in the training data). Cross-entropy loss measures how wrong the model’s predicted probability distribution is compared to the actual answer.If the correct token is “Paris” but the model only assigns 2% probability to it, the loss is high. If it assigns 95%, the loss is low. The formula is:Loss = -Σ y_i · log(ŷ_i)Where y_i is 1 for the correct token and 0 for all others, and ŷ_i is the model’s predicted probability.The goal of training: minimize this loss across the entire training dataset.De-tokenization (Numbers → Human Text)After the model selects the most probable token ID at each step, the IDs are converted back into subwords and joined into readable text. This is the inverse of the tokenization step.Phase 8: BackpropagationOnce the loss is computed, backpropagation traces the error backward through the network — computing how much each parameter contributed to the error. This is done using the chain rule of calculus, calculating gradients for every one of the model’s billions of parameters.Real-world analogy: Imagine a factory where a defective product is traced back through every step of assembly to find exactly which worker made which mistake, and by how much. Backpropagation does this for every parameter in the model, simultaneously.Phase 9: Optimizer (Adam, SGD, etc.)Once we know the gradients, an optimizer uses them to update the model’s parameters in a direction that reduces the loss.SGD (Stochastic Gradient Descent): The original optimizer — simple but slow to convergeAdam (Adaptive Moment Estimation): The most common modern optimizer. Adapts the learning rate for each parameter individually, converging much faster and more stably.This entire cycle — forward pass → loss → backprop → optimizer update — is repeated trillions of times across the training dataset, over weeks or months of compute time on thousands of GPUs.Example: Training GPT-4 is estimated to have required thousands of A100 GPUs running for months, consuming compute resources valued at tens or hundreds of millions of dollars.As you read, those are the phases of how LLMs work basically. I did my best to visualize whole pipeline at once. I hope you understand well!ConclusionUnderstanding these building blocks helps demystify how modern AI systems operate. While today’s models are incredibly powerful, they are ultimately the result of repeated cycles of prediction, feedback, and learning. The combination of tokenization, embeddings, attention mechanisms, and optimization forms the foundation of the AI systems that are reshaping how humans interact with information and technology.You may also check this if you around there since in Turkish :)A huge congrats to you as you reached till here and now you are informed on behalf of the mechanism of LLMs — which are the crucial part of our lives from now on!How LLMs Work? was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.