AI Models Transformers - spinningideas/resources GitHub Wiki

AI Models and Transformers

Transformers

The Transformer is the neural network architecture behind modern AI. It was introduced in the 2017 paper "Attention Is All You Need" by Vaswani et al. at Google, and it now powers text-generating models like OpenAI's GPT, Meta's Llama, Google's Gemini, and Anthropic's Claude. The same architecture is also used for audio generation, image recognition, protein structure prediction, and game playing.

The core idea is next-token prediction: given a prompt, the model computes the most probable next token (a word or part of a word), then repeats. What makes the architecture work is the self-attention mechanism, which lets the model weigh the relationships between all tokens in a sequence at once, rather than reading them one at a time like older recurrent networks.

The three components of a text-generating Transformer

Every text-generating Transformer has three parts:

  1. Embedding. The input text is split into tokens, and each token is converted into a numerical vector that captures its meaning, plus a vector that encodes its position in the sequence.
  2. Transformer blocks. A stack of identical processing blocks. Each block contains a self-attention layer, which lets tokens share information with each other, and an MLP (multilayer perceptron) layer, which refines each token's representation on its own.
  3. Output probabilities. A final linear layer produces a score (a logit) for every token in the vocabulary, and a softmax function turns those scores into a probability distribution for the next token.

Step by step through the architecture

Embedding

  1. Tokenization. The text is split into tokens from a fixed vocabulary. Common words map to one token each, and rarer words are split into pieces. GPT-2's vocabulary has 50,257 tokens.
  2. Token embedding. Each token is looked up in a learned matrix and becomes a vector. GPT-2 (small) uses 768-dimensional vectors, so this matrix alone holds about 39 million parameters. Tokens with similar meanings end up close together in this space.
  3. Positional encoding. A second vector encodes where each token sits in the sequence, because the model would otherwise have no sense of order. GPT-2 learns its positional encodings during training.
  4. Final embedding. The token and positional vectors are added together, giving one vector per token that captures both meaning and position.

The Transformer block

Models stack these blocks, and each block refines the token representations further. GPT-2 (small) has 12 blocks.

Multi-head self-attention runs in four steps:

  1. Each token's vector is projected into three learned vectors: Query (Q), Key (K), and Value (V). The usual intuition: the query asks "what am I looking for", the key advertises "what do I contain", and the value is the content passed along when a query matches a key.
  2. The Q, K, and V vectors are split into multiple heads. GPT-2 (small) uses 12 heads, and each head can learn a different kind of relationship, e.g., one may track short-range grammar while another tracks broader context.
  3. Inside each head, masked self-attention is computed. The dot product of Q and K gives an attention score for every token pair. The scores are scaled, and a mask blocks every token from seeing tokens that come after it, so the model cannot peek ahead when predicting the next token. A softmax turns the scores into weights that sum to one.
  4. The attention weights multiply the V vectors, the outputs of all heads are concatenated, and a final linear projection merges them.

The MLP layer then processes each token independently. In GPT-2 it expands each vector from 768 to 3072 dimensions, applies a GELU activation, and compresses it back to 768. Attention routes information between tokens, and the MLP enriches each token's representation.

Auxiliary features keep training stable: layer normalization is applied before the attention and MLP sublayers, dropout randomly deactivates weights during training to prevent overfitting, and residual connections add each sublayer's input to its output so gradients can flow through deep stacks.

Output probabilities and sampling

After the last block, a linear layer projects each position's vector into a 50,257-dimensional space, giving every vocabulary token a logit. Softmax converts the logits into probabilities, and the model samples the next token from that distribution. Three knobs shape the sampling:

  • Temperature divides the logits before softmax. Below 1 it sharpens the distribution and makes output more predictable. Above 1 it flattens the distribution and makes output more random.
  • Top-k limits sampling to the k most probable tokens.
  • Top-p limits sampling to the smallest set of tokens whose cumulative probability exceeds p.

Model families

Family Shape Examples Typical use
Encoder-only Reads the whole sequence at once, no generation BERT Classification, search, embeddings
Decoder-only Masked attention, generates left to right GPT, Llama, Claude, Gemini Text generation, chat, agents
Encoder-decoder Encoder reads input, decoder generates output T5, original 2017 Transformer Translation, summarization

The interactive tool below uses GPT-2, a decoder-only model, but the components it shows (embeddings, attention heads, MLP layers, softmax sampling) are the same ones in today's largest models.


Transformer Explainer

Transformer Explainer is a free interactive tool that shows how a Transformer works from the inside. It runs a live GPT-2 (small) model, 124 million parameters, directly in the browser, so you can type your own text and watch each component process it in real time.

What you can do with it

  • Enter your own prompt and watch the model predict the next token, with Sankey-style diagrams showing how information flows through embeddings, attention heads, and Transformer blocks.
  • Expand any component to see the underlying math, or stay at the high-level view.
  • Hover over tokens in the attention maps to see which other tokens each one focuses on.
  • Adjust the temperature slider and switch between top-k and top-p sampling to see how the output distribution changes.

How it is built

The model is derived from Andrej Karpathy's nanoGPT implementation, converted to ONNX Runtime so it executes in the browser. The interface uses Svelte for the front end and D3.js for the visualizations, with all numerical values updating live from user input.

Who built it

Transformer Explainer was created by Aeree Cho, Grace C. Kim, Alexander Karpekov, Alec Helbling, Jay Wang, Seongmin Lee, Benjamin Hoover, and Polo Chau at Georgia Tech's Polo Club of Data Science, working with IBM Research. It drew about 150,000 users in its first three months and has been used by more than 500,000 people. A research paper on the tool was accepted to CHI 2026.

Links

More ways to learn the architecture


Visualizations

Other interactive tools for seeing inside Transformer models, ranked by how complete and compelling the experience is.

  1. LLM Visualization (GitHub) by Brendan Bycroft. A 3D fly-through of a GPT computing a completion, zoomable all the way down to every individual matrix multiply. Covers both a GPT-2-small-scale model and a GPT-3-scale diagram. The deepest visualization available.
  2. Inside a Transformer. A real tiny transformer running in your browser on a fixed sentence. Zoom from "text in, next word out" down to a single attention score, switch off components like the causal mask or the residual stream and watch what breaks, follow a 27-stop guided tour, and use 10 playgrounds covering the tokenizer, RoPE, softmax, and the KV cache. The most interactive option.
  3. Neuronpedia. A public database and toolset for looking inside real models: sparse autoencoder features, 8.6 million MLP neurons, feature steering, and circuit tracing that draws attribution graphs of a model's internal steps. Its HeadVis tool, built by Anthropic, has dashboards for over 36,000 attention heads across 37 models.
  4. Anthropic's Mapping the Mind of a Large Language Model. An interactive explorer for interpretable features inside Claude Sonnet, including the famous "Golden Gate Claude" feature. Polished, and the clearest demonstration that features, not neurons, are the unit to study.
  5. BertViz by Jesse Vig. The original interactive attention tool. Offers head, model, and neuron views for BERT, GPT-2, and most Hugging Face models, and runs in Jupyter or Colab.
  6. Dodrio (GitHub), from the same Polo Club lab. Analyzes attention heads against linguistic knowledge such as semantics and syntactic dependencies, rather than walking the whole pipeline.
  7. LM Debugger. Inspects individual GPT-2 neurons and shows how each one updates the output distribution, token by token.
  8. Attention Visualizer. A hands-on lab that computes queries, keys, and values on embeddings small enough to read. You can toggle the causal mask, drag the temperature, and inspect named head patterns.
  9. LLM Transparency Tool from Meta. An open-source toolkit that draws contribution graphs showing how much each token and attention head contributed to a prediction.
  10. OpenAI Neuron Explainer. GPT-4-generated plain-language explanations for every neuron in GPT-2, browsable in the browser.
  11. Gemma Scope from DeepMind. A sparse autoencoder feature explorer for the Gemma family, aimed at the safety and interpretability community. The original release covers Gemma 2, and Gemma Scope 2 covers Gemma 3 with an interactive demo hosted on Neuronpedia.
  12. OpenAI Transformer Debugger. An open-source tool that combines neuron and attention inspection with automated interpretation, for GPT-2-scale models.
  13. Inspectus. An attention visualization library that runs inside Jupyter notebooks through a Python API.
  14. CircuitsVis and TransformerLens. The libraries most mechanistic interpretability demos are built on, for Python and Jupyter rather than as a standalone website.

Related visualizations