Inside the Black Box

How Large Language Models Work

LLMsLLMLarge Language Model — a deep learning model trained on massive text corpora to understand and generate human language. are often referred to as black boxes. In this guide, we break down the core mechanics — from tokensTokenA basic unit of text (such as a word or subword fragment) processed by a language model. to self-attentionSelf-AttentionAn attention mechanism relating different positions of a single sequence to compute a representation of the sequence., and decoding to agentic loopsloopsIterative processes where a model performs actions, observes the results, and reflects on them repeatedly to solve a task..

S0

The Roots: How We Got Here

Modern Transformer architectures didn't emerge in a vacuum. They are the evolutionary culmination of biological brain modeling, classical symbolic logic, and sequential neural architectures. Click a card to explore their core mechanics and bottlenecks.

🧠

Biological Neural Networks

Brain-inspired computes
Expand ▼
💾

Symbolic & Rule-Based AI

Logical "If-Else" Engines
Expand ▼
🔄

Recurrent & Sequential AI

Early NLP (RNNs & LSTMs)
Expand ▼
S1

Tokens & Embeddings

Models cannot read text directly. First, a tokenizerTokenizerThe component that splits text into tokens (subword units) that the model processes. Common types: BPE, SentencePiece. splits text into subword fragments called tokensTokenA basic unit of text (such as a word or subword fragment) processed by a language model.. Common prefixes or suffixes (like ##ing or BPE space markers Ġ) are isolated to allow the model to recognize grammatical roots [Radford et al. 2018].

Each tokenTokenA basic unit of text (such as a word or subword fragment) processed by a language model. is mapped to a unique integerIntegerA whole number representing a token's index position inside a vocabulary table. ID. Then, a lookup table translates these IDs into embeddingsEmbeddingA high-dimensional vector representing the semantic meaning of a token, grouping similar words close together in vector space.: dense vectorsVectorA list of numerical values representing a coordinate in high-dimensional space, used to encode semantic meanings.(often 4096+ dimensions) that position words in a semantic space. In this space, words with similar meanings (like "king" and "queen") are grouped close together.

Interactive Tokenizer Sandbox

Atten#19338
##tion#28732
Ġ#220
is#8370
Ġ#220
all#11673
Ġ#220
you#34839
Ġ#220
need#7302
Ġ#220
for#16577
Ġ#220
learn#26020
##ing#40338
Ġ#220
artif#37544
##icial#16214
Ġ#220
intell#42858
##igence#26337
.#5046

💡 Space characters are replaced with BPE visualizers (Ġ) and long words are split into subword fragments (e.g. ##ing).

Sequence: 22 tokens
Vocab Size (|V|): 50,257
Embedding Dim (d): 4,096 dimensions
S2

Self-Attention & Transformers

The core engine of the TransformerTransformerNeural network architecture using self-attention to process entire sequences in parallel. Replaced RNNs and enabled massive scaling. is Self-AttentionSelf-AttentionAn attention mechanism relating different positions of a single sequence to compute a representation of the sequence. [Vaswani et al. 2017]. In a sentence, words depend on contextContextThe text or prompt preceding a generation that the model uses to understand what it is currently processing.. For example, in "The llmLLMLarge Language Model — a deep learning model trained on massive text corpora to understand and generate human language. read the promptPromptThe input text or instruction provided to a language model to guide its output. because "it" was relevant", what does "it" refer to?

Self-Attention calculates a set of queryQueryIn self-attention, the vector representing the current token seeking context from other parts of the sequence., keyKeyIn self-attention, the vector representing what information a token contains, matched against queries to compute attention weights., and value vectorsVectorA list of numerical values representing a coordinate in high-dimensional space, used to encode semantic meanings.. The query for "it" is compared with keysKeyIn self-attention, the vector representing what information a token contains, matched against queries to compute attention weights. for all other words. The model computes weights representing how much "attentionAttentionA mechanism in Transformers that determines how much focus to place on other words in a sequence when processing the current word." to pay to each word.

TransformersTransformerNeural network architecture using self-attention to process entire sequences in parallel. Replaced RNNs and enabled massive scaling. run multiple Attention HeadsHeadsIndependent attention mechanisms running in parallel, allowing the model to capture multiple relationships at once. in parallel. This allows the model to capture different relations simultaneously (e.g. tracking pronouns in one head, verbs in another).

Interactive Attention Map

Resolves coreferences. Hover over 'it' to see how the model connects the pronoun back to 'prompt' and 'llm'.

Query Word
The
llm
read
the
prompt
because
it
was
relevant
Key Word
The
llm
read
the
prompt
because
it
was
relevant

💡 Hover over words in the left column. Highlighted lines show key coordinates influencing that token's contextual state.

S3

Pre-Training to Alignment

FrontierFrontierThe absolute leading edge of AI model capability, representing state-of-the-art parameters, compute, and benchmark performance. models go through three major training phases to become reliable and safe assistants [Ouyang et al. 2022]. Click through the phases below to see how datasets and model behaviors change.

1. Pre-Training

Self-Supervised Learning

The model is fed trillions of tokens of raw web text. It optimizes cross-entropy loss to predict the next tokentokenA basic unit of text (such as a word or subword fragment) processed by a language model. given a context windowContext windowThe maximum number of tokens a model can process in a single input. Ranges from 2K to 10M+.. This creates a base model with extensive world knowledge and autocomplete capabilities.

Training Input Sample
The capital of France is...
Expected Output / Behavior
Paris. Located on the Seine River, it is the center of...
S4

Decoding (Temperature & Top-P)

At inferenceInferenceUsing a trained model to generate predictions or outputs (as opposed to training it)., an LLMLLMLarge Language Model — a deep learning model trained on massive text corpora to understand and generate human language. outputs logits (raw scores) for every tokenTokenA basic unit of text (such as a word or subword fragment) processed by a language model. in its vocabulary. These are turned into probabilities using SoftmaxSoftmaxA mathematical function that converts a vector of raw scores (logits) into a probability distribution summing to 1.. We control the randomness and diversity of outputs using two parametersParameterA variable or weight inside a neural network that is adjusted during training to store knowledge.:

  • 🌡️ TemperatureTemperatureA hyperparameter controlling the randomness of outputs; lower values make outputs more deterministic, higher values make them more creative.:Controls distribution scale. Low temperature (< 0.5) compresses values, sharpening the peaks so the model repeatedly picks the absolute highest score (factual/deterministicDeterministicAn execution mode or output that is completely predictable, always yielding the identical response for a given input.). High temperature (> 1.0) flattens the curves, increasing diversity (creative/unpredictable).
  • 🎯 Top-P (Nucleus Sampling): TruncatesTruncateTo cut off or discard the tail end of a text sequence or a probability distribution. the probability distribution to include only a subset whose cumulative sum is under P. TokensTokenA basic unit of text (such as a word or subword fragment) processed by a language model. in the tail whose sum exceedsP are completely discarded.

Decoding Parameter Simulator

Temperature: 0.7Balanced
Top-P (Nucleus): 0.9Broad Selection
Next Token Probabilities (Prompt: "The weather is very...")
"sunny"
logit: 460.2%
"cold"
logit: 3.219.2%
"rainy"
logit: 2.810.8%
"beautiful"
logit: 2.57.1%Cutoff
"hot"
logit: 1.82.6%Cutoff
"potato"
logit: -0.80.1%Cutoff
S5

RAG & Agentic Loops

Retrieval-Augmented Generation (RAG)

LLMsLLMLarge Language Model — a deep learning model trained on massive text corpora to understand and generate human language. have knowledge cutoff limits. RAGRAGRetrieval-Augmented Generation — combining a language model with a search/retrieval system to ground responses in external knowledge. resolves this by fetching externalexternalResources, files, or services outside of the model's static weights, such as APIs or search engines. sources dynamically from a vectorvectorA list of numerical values representing a coordinate in high-dimensional space, used to encode semantic meanings. store, then feeding the data to the LLMLLMLarge Language Model — a deep learning model trained on massive text corpora to understand and generate human language. contextContextThe text or prompt preceding a generation that the model uses to understand what it is currently processing. [Lewis et al. 2020].

11. Query Embedding

The user queryqueryIn self-attention, the vector representing the current token seeking context from other parts of the sequence. is processed by an embeddingembeddingA high-dimensional vector representing the semantic meaning of a token, grouping similar words close together in vector space. model, yielding a high-dimensional vectorvectorA list of numerical values representing a coordinate in high-dimensional space, used to encode semantic meanings. representing semantic intent.

22. Vector Database Retrieval
33. Context Injection
44. LLM Answer Generation
Process Output

Query: "What is GPT-4's size?" ➔ Vector: [0.15, -0.42, 0.87, ...]

Autonomous Agentic Loops (ReAct)

Rather than single-step execution, agents run loopsloopsIterative processes where a model performs actions, observes the results, and reflects on them repeatedly to solve a task. (Reason-Act-ObserveReason-Act-ObserveThe execution cycle of an agent (often using the ReAct framework) where it reasons about a task, calls a tool, and observes the feedback.). They review their thoughts and callcallAn invocation of a tool or function (like web search or a calculator) by the model to gather external data. externalexternalResources, files, or services outside of the model's static weights, such as APIs or search engines. tools iteratively [Yao et al. 2022].

Iteration Step: 1 / 8
Thought

The agent analyzes the task and reasons about what to do next. It decides it needs externalexternalResources, files, or services outside of the model's static weights, such as APIs or search engines. web information.

Thought: I need to compare the release dates of Gemini 1.5 and GPT-4o. I will search for Gemini 1.5 first.

💡 Click "Next" to step through the agent's reasoning logs.

Bibliography & Research Citations

[Vaswani et al. 2017]

Attention Is All You Need

Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin.

View Paper on arXiv
[Radford et al. 2018]

Improving Language Understanding by Generative Pre-Training (GPT-1)

Alec Radford, Karthik Narasimhan, Tim Salimans, Ilya Sutskever.

View Paper PDF
[Ouyang et al. 2022]

Training language models to follow instructions with human feedback (InstructGPT)

Long Ouyang, Jeffrey Wu, Xu Jiang, Diogo Almeida, Carroll Wainwright, Pamela Mishkin, Chong Zhang, Sandhini Agarwal, Katarina Slama, Alex Ray, John Schulman, Jacob Hilton, Fraser Kelton, Luke Miller, Maddie Simens, Amanda Askell, Peter Welinder, Paul F. Christiano, Jan Leike, Ryan Lowe.

View Paper on arXiv
[Lewis et al. 2020]

Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (RAG)

Patrick Lewis, Ethan Perez, Aleksandara Piktus, Fabio Petroni, Vladimir Karpukhin, Naman Goyal, Heinrich Küttler, Mike Lewis, Wen-tau Yih, Tim Rocktäschel, Sebastian Riedel, Douwe Kiela.

View Paper on arXiv
[Yao et al. 2022]

ReAct: Synergizing Reasoning and Acting in Language Models

Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, Yuan Cao.

View Paper on arXiv