{"slug": "transformers-explained-visually", "title": "Transformers Explained Visually", "summary": "The Transformer neural network architecture, introduced in the 2017 paper \"Attention is All You Need,\" has become the go-to deep learning architecture for text-generative models including OpenAI's GPT, Meta's Llama, and Google's Gemini, and is also applied to audio generation, image recognition, protein structure prediction, and game playing. Text-generative Transformers operate on next-token prediction, with their core innovation being the self-attention mechanism that captures long-range dependencies; the Transformer Explainer tool is powered by OpenAI's GPT-2 (small) model with 124 million parameters. Every text-generative Transformer consists of three key components: embedding, the Transformer block (attention mechanism plus MLP layer), and output probabilities produced by final linear and softmax layers.", "body_md": "# What is a Transformer?\n\nTransformer is a neural network architecture that has fundamentally changed the approach to\n\t\t\tArtificial Intelligence. Transformer was first introduced in the seminal paper\n\t\t\t[\"Attention is All You Need\"](https://dl.acm.org/doi/10.5555/3295222.3295349)\n\t\t\tin 2017 and has since become the go-to architecture for deep learning models, powering text-generative\n\t\t\tmodels like OpenAI's **GPT**, Meta's **Llama**, and Google's\n\t\t\t**Gemini**. Beyond text, Transformer is also applied in\n\t\t\t[audio generation](https://huggingface.co/learn/audio-course/en/chapter3/introduction),\n\t\t\t[image recognition](https://huggingface.co/learn/computer-vision-course/unit3/vision-transformers/vision-transformers-for-image-classification),\n\t\t\t[protein structure prediction](https://elifesciences.org/articles/82819), and even\n\t\t\t[game playing](https://www.deeplearning.ai/the-batch/reinforcement-learning-plus-transformers-equals-efficiency/), demonstrating its versatility across numerous domains.\n\nFundamentally, text-generative Transformer models operate on the principle of **next-token prediction**: given a text prompt from the user, what is the\n\t\t\t*most probable next token (a word or part of a word)* that will follow this input? The core\n\t\t\tinnovation and power of Transformers lie in their use of self-attention mechanism, which allows\n\t\t\tthem to process entire sequences and capture long-range dependencies more effectively than previous\n\t\t\tarchitectures.\n\nGPT-2 family of models are prominent examples of text-generative Transformers. Transformer\n\t\t\tExplainer is powered by the\n\t\t\t[GPT-2](https://huggingface.co/openai-community/gpt2)\n\t\t\t(small) model which has 124 million parameters. While it is not the latest or most powerful Transformer\n\t\t\tmodel, it shares many of the same architectural components and principles found in the current\n\t\t\tstate-of-the-art models making it an ideal starting point for understanding the basics.\n\n# Transformer Architecture\n\nEvery text-generative Transformer consists of these **three key components**:\n\n1. **Embedding** : Text input is divided into smaller units\n\t\t\t\tcalled tokens, which can be words or subwords. These tokens are converted into numerical\n\t\t\t\tvectors called embeddings, which capture the semantic meaning of words.\n2. **Transformer Block** is the fundamental building block of\n\t\t\t\tthe model that processes and transforms the input data. Each block includes:\n  - **Attention Mechanism** , the core component of the Transformer block. It\n\t\t\t\t\t\tallows tokens to communicate with other tokens, capturing contextual information and\n\t\t\t\t\t\trelationships between words.\n  - **MLP (Multilayer Perceptron) Layer** , a feed-forward network that operates\n\t\t\t\t\t\ton each token independently. While the goal of the attention layer is to route\n\t\t\t\t\t\tinformation between tokens, the goal of the MLP is to refine each token's\n\t\t\t\t\t\trepresentation.\n3. **Output Probabilities** : The final linear and softmax\n\t\t\t\tlayers transform the processed embeddings into probabilities, enabling the model to make\n\t\t\t\tpredictions about the next token in a sequence.\n\n## Embedding\n\nLet's say you want to generate text using a Transformer model. You add the prompt like this\n\t\t\tone: `“Data visualization empowers users to”`. This input needs to be converted\n\t\t\tinto a format that the model can understand and process. That is where embedding comes in: it\n\t\t\ttransforms the text into a numerical representation that the model can work with. To convert a\n\t\t\tprompt into embedding, we need to 1) tokenize the input, 2) obtain token embeddings, 3) add\n\t\t\tpositional information, and finally 4) add up token and position encodings to get the final\n\t\t\tembedding. Let’s see how each of these steps is done.\n\n### Step 1: Tokenization\n\nTokenization is the process of breaking down the input text into smaller, more manageable\n\t\t\t\tpieces called tokens. These tokens can be a word or a subword. The words `\"Data\"`\n\t\t\t\tand `\"visualization\"` correspond to unique tokens, while the word\n\t\t\t\t`\"empowers\"`\n\t\t\t\tis split into two tokens. The full vocabulary of tokens is decided before training the model:\n\t\t\t\tGPT-2's vocabulary has `50,257` unique tokens. Now that we split our input text into\n\t\t\t\ttokens with distinct IDs, we can obtain their vector representation from embeddings.\n\n### Step 2. Token Embedding\n\nGPT-2 (small) represents each token in the vocabulary as a 768-dimensional vector; the\n\t\t\t\tdimension of the vector depends on the model. These embedding vectors are stored in a matrix\n\t\t\t\tof shape `(50,257, 768)`, containing approximately 39 million parameters! This\n\t\t\t\textensive matrix allows the model to assign semantic meaning to each token, in the sense\n\t\t\t\tthat tokens with similar usage or meaning in language are placed close together in this\n\t\t\t\thigh-dimensional space, while dissimilar tokens are farther apart.\n\n### Step 3. Positional Encoding\n\nThe Embedding layer also encodes information about each token's position in the input prompt. Different models use various methods for positional encoding. GPT-2 trains its own positional encoding matrix from scratch, integrating it directly into the training process.\n\n### Step 4. Final Embedding\n\nFinally, we sum the token and positional encodings to get the final embedding representation. This combined representation captures both the semantic meaning of the tokens and their position in the input sequence.\n\n## Transformer Block\n\nThe core of the Transformer's processing lies in the Transformer block, which comprises\n\t\t\tmulti-head self-attention and a Multi-Layer Perceptron layer. Most models consist of multiple\n\t\t\tsuch blocks that are stacked sequentially one after the other. The token representations\n\t\t\tevolve through layers, from the first block to the last one, allowing the model to build up an\n\t\t\tintricate understanding of each token. This layered approach leads to higher-order\n\t\t\trepresentations of the input. The GPT-2 (small) model we are examining consists of `12` such blocks.\n\n### Multi-Head Self-Attention\n\nThe self-attention mechanism enables the model to capture relationships among tokens in a sequence, so that each token’s representation is influenced by the others. Multiple attention heads allow the model to consider these relationships from different perspectives; for example, one head may capture short-range syntactic links while another tracks broader semantic context. In the following section, we will walk through how multi-head self-attention is computed step by step.\n\n#### Step 1: Query, Key, and Value Matrices\n\nEach token's embedding vector is transformed into three vectors: Query (Q), Key (K), and Value (V). These vectors are derived by multiplying the input embedding matrix with learned weight matrices for Q, K, and V. Here's a web search analogy to help us build some intuition behind these matrices:\n\n- **Query (Q)** is the search text you type in the\n\t\t\t\t\tsearch engine bar. This is the token you want to*\"find more information about\"* .\n- **Key (K)** is the title of each web page in the search\n\t\t\t\t\tresult window. It represents the possible tokens the query can attend to.\n- **Value (V)** is the actual content of web pages shown.\n\t\t\t\t\tOnce we matched the appropriate search term (Query) with the relevant results (Key), we want\n\t\t\t\t\tto get the content (Value) of the most relevant pages.\n\nBy using these QKV values, the model can calculate attention scores, which determine how much focus each token should receive when generating predictions.\n\n#### Step 2: Multi-Head Splitting\n\nQuery, key, and\n\t\t\t\tValue\n\t\t\t\tvectors are split into multiple heads—in GPT-2 (small)'s case, into\n\t\t\t\t`12` heads. Each head processes a segment of the embeddings independently, capturing\n\t\t\t\tdifferent syntactic and semantic relationships. This design facilitates parallel learning of\n\t\t\t\tdiverse linguistic features, enhancing the model's representational power.\n\n#### Step 3: Masked Self-Attention\n\nIn each head, we perform masked self-attention calculations. This mechanism allows the model to generate sequences by focusing on relevant parts of the input while preventing access to future tokens.\n\n- **Dot Product** : The dot product of\n\t\t\t\t\tQuery\n\t\t\t\t\tand Key matrices determines the**attention score** , producing a square matrix that reflects the relationship\n\t\t\t\t\tbetween all input tokens.\n- **Scaling · Mask** : The attention scores are scaled and a mask is applied to\n\t\t\t\t\tthe upper triangle of the attention matrix to prevent the model from accessing future\n\t\t\t\t\ttokens, setting these values to negative infinity. The model needs to learn how to predict\n\t\t\t\t\tthe next token without “peeking” into the future.\n- **Softmax · Dropout** : After masking and scaling, the attention scores are\n\t\t\t\t\tconverted into probabilities by the softmax operation, then optionally regularized with\n\t\t\t\t\tdropout. Each row of the matrix sums to one and indicates the relevance of every other\n\t\t\t\t\ttoken to the left of it.\n\n#### Step 4: Output and Concatenation\n\nThe model uses the masked self-attention scores and multiplies them with the\n\t\t\t\tValue matrix to get the\n\t\t\t\tfinal output\n\t\t\t\tof the self-attention mechanism. GPT-2 has `12` self-attention heads, each capturing\n\t\t\t\tdifferent relationships between tokens. The outputs of these heads are concatenated and passed\n\t\t\t\tthrough a linear projection.\n\n### MLP: Multi-Layer Perceptron\n\nAfter the multiple heads of self-attention capture the diverse relationships between the input\n\t\t\ttokens, the concatenated outputs are passed through the Multilayer Perceptron (MLP) layer to\n\t\t\tenhance the model's representational capacity. The MLP block consists of two linear\n\t\t\ttransformations with a [GELU](<https://en.wikipedia.org/wiki/Rectified_linear_unit#Gaussian-error_linear_unit_(GELU)>) activation function in between.\n\nThe first linear transformation expands the dimensionality of the input four-fold from `768`\n\t\t\tto\n\t\t\t`3072`. This expansion step allows the model to project the token representations\n\t\t\tinto a higher-dimensional space, where it can capture richer and more complex patterns that\n\t\t\tmay not be visible in the original dimension.\n\nThe second linear transformation then reduces the dimensionality back to the original size of `768`.This compression step brings the representations back to a manageable size while retaining\n\t\t\tthe useful nonlinear transformations introduced in the expansion step.\n\nUnlike the self-attention mechanism, which integrates information across tokens, the MLP processes tokens independently and simply maps each token representation from one space to another, enriching the overall model capacity.\n\n## Output Probabilities\n\nAfter the input has been processed through all Transformer blocks, the output is passed\n\t\t\tthrough the final linear layer to prepare it for token prediction. This layer projects the\n\t\t\tfinal representations into a `50,257`\n\t\t\tdimensional space, where every token in the vocabulary has a corresponding value called\n\t\t\t`logit`. Any token can be the next word, so this process allows us to simply rank\n\t\t\tthese tokens by their likelihood of being that next word. We then apply the softmax function\n\t\t\tto convert the logits into a probability distribution that sums to one. This will allow us to\n\t\t\tsample the next token based on its likelihood.\n\nThe final step is to generate the next token by sampling from this distribution The `temperature`\n\t\t\thyperparameter plays a critical role in this process. Mathematically speaking, it is a very simple\n\t\t\toperation: model output logits are simply divided by the\n\t\t\t`temperature`:\n\n- `temperature = 1` : Dividing logits by one has no effect on the softmax outputs.\n- `temperature < 1` : Lower temperature makes the model more confident and\n\t\t\t\tdeterministic by sharpening the probability distribution, leading to more predictable\n\t\t\t\toutputs.\n- `temperature > 1` : Higher temperature creates a softer probability\n\t\t\t\tdistribution, allowing for more randomness in the generated text – what some refer to as\n\t\t\t\tmodel*“creativity”* .\n\nIn addition, the sampling process can be further refined using `top-k`\n\t\t\tand\n\t\t\t`top-p` parameters:\n\n- `top-k sampling` : Limits the candidate tokens to the top k tokens with the\n\t\t\t\thighest probabilities, filtering out less likely options.\n- `top-p sampling` : Considers the smallest set of tokens whose cumulative\n\t\t\t\tprobability exceeds a threshold p, ensuring that only the most likely tokens contribute\n\t\t\t\twhile still allowing for diversity.\n\nBy tuning `temperature`, `top-k`, and `top-p`, you can\n\t\t\tbalance between deterministic and diverse outputs, tailoring the model's behavior to your\n\t\t\tspecific needs.\n\n## Auxiliary Architectural Features\n\nThere are several auxiliary architectural features that enhance the performance of Transformer models. While important for the model's overall performance, they are not as important for understanding the core concepts of the architecture. Layer Normalization, Dropout, and Residual Connections are crucial components in Transformer models, particularly during the training phase. Layer Normalization stabilizes training and helps the model converge faster. Dropout prevents overfitting by randomly deactivating neurons. Residual Connections allows gradients to flow directly through the network and helps to prevent the vanishing gradient problem.\n\n### Layer Normalization\n\nLayer Normalization helps to stabilize the training process and improves convergence. It works by normalizing the inputs across the features, ensuring that the mean and variance of the activations are consistent. This normalization helps mitigate issues related to internal covariate shift, allowing the model to learn more effectively and reducing the sensitivity to the initial weights. Layer Normalization is applied twice in each Transformer block, once before the self-attention mechanism and once before the MLP layer.\n\n### Dropout\n\nDropout is a regularization technique used to prevent overfitting in neural networks by randomly setting a fraction of model weights to zero during training. This encourages the model to learn more robust features and reduces dependency on specific neurons, helping the network generalize better to new, unseen data. During model inference, dropout is deactivated. This essentially means that we are using an ensemble of the trained subnetworks, which leads to a better model performance.\n\n### Residual Connections\n\nResidual connections were first introduced in the ResNet model in 2015. This architectural innovation revolutionized deep learning by enabling the training of very deep neural networks. Essentially, residual connections are shortcuts that bypass one or more layers, adding the input of a layer to its output. This helps mitigate the vanishing gradient problem, making it easier to train deep networks with multiple Transformer blocks stacked on top of each other. In GPT-2, residual connections are used twice within each Transformer block: once before the MLP and once after, ensuring that gradients flow more easily, and earlier layers receive sufficient updates during backpropagation.\n\n# Interactive Features\n\nTransformer Explainer is built to be interactive and allows you to explore the inner workings of the Transformer. Here are some of the interactive features you can play with:\n\n- **Input your own text sequence** to see how the model processes it and predicts\n\t\t\t\tthe next word. Explore attention weights, intermediate computations, and see how the final output\n\t\t\t\tprobabilities are calculated.\n- **Use temperature slider** to control the randomness of the model’s predictions.\n\t\t\t\tExplore how you can make the model output more deterministic or more creative by changing the\n\t\t\t\ttemperature value.\n- **Select top-k and top-p sampling methods** to adjust sampling behavior during inference.\n\t\t\t\tExperiment with different values and see how the probability distribution changes and influences\n\t\t\t\tthe model's predictions.\n- **Interact with attention maps** to see how the model focuses on different tokens\n\t\t\t\tin the input sequence. Hover over tokens to highlight their attention weights and explore how\n\t\t\t\tthe model captures context and relationships between words.\n\n## Video Tutorial\n\n## How is Transformer Explainer Implemented?\n\nTransformer Explainer features a live GPT-2 (small) model running directly in the browser.\n\t\t\tThis model is derived from the PyTorch implementation of GPT by Andrej Karpathy's\n\t\t\t[nanoGPT project](https://github.com/karpathy/nanoGPT)\n\t\t\tand has been converted to\n\t\t\t[ONNX Runtime](https://onnxruntime.ai/)\n\t\t\tfor seamless in-browser execution. The interface is built using JavaScript, with\n\t\t\t[Svelte](https://kit.svelte.dev/)\n\t\t\tas a front-end framework and\n\t\t\t[D3.js](https://d3js.org/)\n\t\t\tfor creating dynamic visualizations. Numerical values are updated live following the user input.\n\n## Who developed the Transformer Explainer?\n\nTransformer Explainer was created by\n\t\t\t[Aeree Cho](https://aereeeee.github.io/),\n\t\t\t[Grace C. Kim](https://www.linkedin.com/in/chaeyeonggracekim/),\n\t\t\t[Alexander Karpekov](https://alexkarpekov.com/),\n\t\t\t[Alec Helbling](https://alechelbling.com/),\n\t\t\t[Jay Wang](https://zijie.wang/),\n\t\t\t[Seongmin Lee](https://seongmin.xyz/),\n\t\t\t[Benjamin Hoover](https://bhoov.com/), and\n\t\t\t[Polo Chau](https://poloclub.github.io/polochau/)\n\t\t\tat the Georgia Institute of Technology.", "url": "https://wpnews.pro/news/transformers-explained-visually", "canonical_source": "https://poloclub.github.io/transformer-explainer/", "published_at": "2026-09-21 19:43:49+00:00", "updated_at": "2026-09-21 19:53:55.159412+00:00", "lang": "en", "topics": ["artificial-intelligence", "machine-learning", "large-language-models", "neural-networks", "natural-language-processing"], "entities": ["Transformer", "Attention is All You Need", "OpenAI", "GPT", "Meta", "Llama", "Google", "Gemini"], "alternates": {"html": "https://wpnews.pro/news/transformers-explained-visually", "markdown": "https://wpnews.pro/news/transformers-explained-visually.md", "text": "https://wpnews.pro/news/transformers-explained-visually.txt", "jsonld": "https://wpnews.pro/news/transformers-explained-visually.jsonld"}}