• Transformer Architecture: How Transformers Work, From Self-Attention to Modern LLMs

    transformers architecture

    The transformer is the neural network architecture behind ChatGPT and nearly every other large language model: it reads a whole sequence at once and lets each token decide, through self-attention, which other tokens matter to it. Eight Google researchers introduced it in 2017 for machine translation, and their paper, “Attention Is All You Need“, is now the seventh most-cited scientific paper of the 21st century.

    This guide explains how the transformer architecture works, step by step: tokens and embeddings, positional encoding, self-attention computed on real numbers, multi-head attention, the feed-forward layers, residual connections and normalization, and how a model generates text with a KV cache. Then we build a GPT-style transformer with 0.8 million parameters in PyTorch, train it in 13 minutes on a single CPU core and break it on purpose to see what each part does. Finally, we compare it with an LSTM on a memory task and look at what changed in the architecture between 2017 and the end of 2026, with parameter and memory numbers for real models. We ran all the experiments specifically for this article.

    Key takeaways

    • A transformer is a stack of identical blocks. In each block, attention lets tokens exchange information and a feed-forward network then processes every token on its own; residual connections and normalization keep a deep stack trainable.
    • Self-attention compares every token with every other token, softmax(QKT/√dk)·V. This gives direct access to any earlier word and lets training run in parallel, but the cost grows with the square of the context length.
    • Every part of the block earns its place, but some matter far more than others. In our experiments with a model of about 800,000 parameters, removing residual connections left the model unable to learn anything beyond character frequencies, removing normalization or the feed-forward layers did the most damage after that, and the modern Llama-style block (RMSNorm, RoPE, SwiGLU) lowered the loss from 1.66 to 1.50.
    • Attention gives direct access to everything in the context. In our recall test, a two-layer transformer found a value by its key in lists of up to 64 pairs with 99.96% to 100% accuracy. An LSTM of the same size answered correctly 34% of the time with 4 pairs and 12% with 64, even though on ordinary text it did better than our baseline transformer.
    • The 2026 transformer keeps the 2017 skeleton but replaces most parts: RMSNorm, rotary positions, SwiGLU, grouped or latent attention, mixture of experts and, in the newest models, hybrid layers. The KV cache per token fell from 320 KiB in Llama 3.1 70B to 27 KiB in Kimi K3.

    What is a transformer?

    A transformer is a deep learning architecture for sequences: text, code, speech, image patches, even protein sequences. It splits the input into tokens, turns every token into a vector and passes these vectors through a stack of identical blocks. In each block, a token’s vector is updated with information taken from other tokens, so that by the end the vector for “it” in “the cat ate the fish because it was hungry” knows that “it” means the cat.

    Before 2017, sequences were mostly handled by recurrent neural networks and their improved version, the LSTM. An RNN reads text one token at a time and carries everything it has read in a single hidden state. That has two problems: training cannot be parallelized across positions, because step 100 needs the result of step 99, and information from far back fades as it is passed along. In 2014, Dzmitry Bahdanau, Kyunghyun Cho and Yoshua Bengio added an attention mechanism to an RNN translator: when producing each word, the decoder could look back at all words of the source sentence. The transformer kept the attention and threw away the recurrence.

    That is why it won. All positions of a sequence are processed at once, which suits GPUs; any token can reach any other in a single step, so long-range dependencies do not fade; and quality keeps improving as models, data and compute grow. Today the same architecture, with modifications, powers AI systems for text, images, video, speech, robotics and biology. The fundamentals this article builds on, from neurons to backpropagation and gradient descent, are collected in our AI basics section.

    There are three main types of transformers: encoder-only models such as BERT, which read and understand text; decoder-only models such as GPT, Llama, DeepSeek and Qwen, which generate text and are behind today’s chatbots; and encoder-decoder models, like the original 2017 transformer, T5 and Whisper, which turn one sequence into another. We compare them below.

    Attention Is All You Need: the 2017 paper in numbers

    The paper by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser and Illia Polosukhin appeared on arXiv on 12 June 2017 and was presented at NeurIPS 2017. The task was machine translation: English to German and English to French on the WMT 2014 datasets. The authors built an encoder and a decoder of six blocks each and trained two sizes:

    Transformer (base) Transformer (big)
    Blocks in encoder and decoder 6 + 6 6 + 6
    Model dimension, dmodel 512 1,024
    Feed-forward dimension, dff 2,048 4,096
    Attention heads 8 16
    Parameters 65 million 213 million
    Training 12 hours on 8 NVIDIA P100 3.5 days on 8 NVIDIA P100
    BLEU, English to German 27.3 28.4
    BLEU, English to French 38.1 41.8

    The big model beat the best previous results, including ensembles, by more than 2 BLEU on English to German, and its training cost a fraction of what earlier systems needed. Besides the overall design, the paper introduced the pieces this article is about: scaled dot-product attention, multi-head attention, sinusoidal positional encoding, and a learning-rate schedule with warmup. The title is a play on the Beatles’ “All You Need Is Love”, and the name Transformer was picked because Uszkoreit liked how it sounded.

    For scale: the base model had 65 million parameters. Kimi K3, one of the largest open models of 2026, has 2.8 trillion, about 43,000 times more, yet its blocks are still recognizably the blocks from this paper.

    Transformer architecture at a glance

    Here is the path a piece of text takes through a decoder-only transformer, the type used in modern language models:

    Transformer architecture diagram: tokens, embeddings and positions, a block with masked multi-head self-attention and a feed-forward network repeated N times, then softmax over the next token
    A decoder-only transformer, the type behind most LLMs: tokens become vectors that flow through N identical blocks, and every block adds the results of attention and of a feed-forward network to them
    1. Tokenization. A tokenizer splits the text into tokens, usually pieces of words, and replaces each with its number in a fixed vocabulary.
    2. Embeddings and positions. Each token number is replaced by a learned vector of dmodel numbers, and information about the token’s position is added.
    3. A stack of N blocks. Every block has two parts. Attention lets each token gather information from the tokens before it. The feed-forward network, also called the MLP, then transforms each token’s vector separately. Both parts add their result to the token’s vector instead of replacing it.
    4. Output. After a final normalization, a linear layer turns each vector into a score for every token in the vocabulary, and softmax turns the scores into probabilities of the next token.

    A useful way to picture this, popularized by Anthropic’s interpretability team, is the residual stream: each token has a vector that flows from the bottom of the network to the top, and every block reads from it and writes a correction back into it. Attention is the only place where information moves between tokens; everything else works on one token at a time.

    Tokens, embeddings and positional encoding

    A transformer never sees letters. A tokenizer, usually based on byte-pair encoding (BPE), cuts text into frequent pieces: common words become one token, rare words are split into several. The vocabulary size is a design choice, and it has been growing: GPT-2 uses 50,257 tokens, Llama 3.1 uses 128,256, Kimi K3 163,840 and Qwen3.5 248,320, according to their configuration files.

    The embedding layer is a table with one row per token. For GPT-2 small it holds 50,257 × 768 = 38.6 million numbers, almost a third of the model’s 124 million parameters. During training these rows move so that tokens used in similar contexts get similar vectors, the same idea as in word2vec.

    Then comes a subtle problem. Attention, as we will see, compares tokens by their content. Nothing in that computation depends on where a token stands, so without extra information a transformer cannot tell “dog bites man” from “man bites dog”. This is easy to check. Below, a small PyTorch encoder computes an average vector for both sentences, first without positions, then with learned position vectors added to the embeddings:

    import torch
    import torch.nn as nn
    
    torch.manual_seed(0)
    words = ['dog', 'bites', 'man']
    vocab = {w: i for i, w in enumerate(words)}
    emb = nn.Embedding(len(words), 16)
    pos = nn.Embedding(8, 16)
    encoder = nn.TransformerEncoder(nn.TransformerEncoderLayer(16, 2, 32, dropout=0.0, batch_first=True), 2).eval()
    
    
    def sentence_vector(sentence, use_positions):
        ids = torch.tensor([[vocab[w] for w in sentence.split()]])
        x = emb(ids)
        if use_positions:
            x = x + pos(torch.arange(ids.shape[1]))
        return encoder(x).mean(dim=1)          # average over tokens
    
    
    with torch.no_grad():
        for use_positions in (False, True):
            a = sentence_vector('dog bites man', use_positions)
            b = sentence_vector('man bites dog', use_positions)
            print('positions:', use_positions, 'difference:', round((a - b).abs().max().item(), 6))
    positions: False difference: 0.0
    positions: True difference: 0.292132

    Without positions the two sentences produce exactly the same vector: for the model they are the same bag of words. Adding positions fixes that. There are several ways to do it:

    • Sinusoidal encoding (the 2017 paper): a fixed vector of sines and cosines of different frequencies is added to each embedding, PE(pos, 2i) = sin(pos / 100002i/d) and PE(pos, 2i+1) = cos(pos / 100002i/d).
    • Learned positions (BERT, GPT-2): one trainable vector per position, up to a maximum length such as 512 or 1,024.
    • Rotary positional embedding, RoPE (Su et al., 2021): instead of adding anything, queries and keys are rotated by an angle that grows with the position, so the attention score between two tokens depends on their distance. RoPE is used by Llama, Qwen, Mistral, DeepSeek and most other open models.
    • No positional encoding at all. Surprisingly, a decoder with a causal mask can work without it: each token sees a different number of predecessors, and the model can infer order from that. Researchers have shown this for language models, and Kimi K3 uses no positional encoding at all: the order is carried by its linear-attention layers. Our own test of this is in the experiments section.

    Self-attention, step by step with real numbers

    Self-attention is the core of the transformer. For every token, the model computes three vectors from its embedding, using three learned matrices:

    • a query (Q): what this token is looking for;
    • a key (K): what this token offers, used to decide whether it is relevant to someone’s query;
    • a value (V): the information this token passes on if it is chosen.

    The attention score between two tokens is the dot product of one token’s query and the other’s key: the more they align, the higher the score. The scores of a token are divided by √dk, the square root of the key length, and turned into weights that sum to 1 with softmax. The output for the token is the weighted sum of all value vectors. In matrix form, for all tokens at once:

    Attention(Q, K, V) = softmax(Q·KT / √dk) · V

    The division by √dk is what “scaled” means in “scaled dot-product attention”. Dot products of long vectors are large, and large inputs push softmax into a regime where one weight is almost 1, the others almost 0 and gradients nearly vanish; the paper’s authors added the scaling to avoid that.

    Let us compute attention by hand on a sentence of four tokens: “cat ate fish it”. Real models learn their vectors, but here we choose them so that we can follow every number. Each token gets four features: animate, action, food and pronoun. The query matrix WQ makes the pronoun ask “who here is animate?”, and the key matrix WK makes animate words answer “I am”. The values just carry each token’s features.

    import torch
    
    torch.set_printoptions(precision=2, sci_mode=False)
    
    # Four tokens, four features: [animate, action, food, pronoun]
    tokens = ['cat', 'ate', 'fish', 'it']
    X = torch.tensor([[1.0, 0.0, 0.0, 0.0],   # cat
                      [0.0, 1.0, 0.0, 0.0],   # ate
                      [0.3, 0.0, 1.0, 0.0],   # fish
                      [0.0, 0.0, 0.0, 1.0]])  # it
    
    # The pronoun asks "who is animate?", animate words answer "I am".
    W_q = torch.zeros(4, 4)
    W_q[3, 0] = 2.0            # pronoun -> query "animate?"
    W_k = torch.zeros(4, 4)
    W_k[0, 0] = 2.0            # animate -> key "animate"
    W_v = torch.eye(4)         # values just carry the token's features
    
    Q, K, V = X @ W_q, X @ W_k, X @ W_v
    d_k = Q.shape[-1]
    scores = Q @ K.T / d_k ** 0.5
    mask = torch.ones(4, 4).tril().bool()      # a token sees itself and the past
    scores = scores.masked_fill(~mask, float('-inf'))
    weights = torch.softmax(scores, dim=-1)
    out = weights @ V
    
    print('scores:')
    print(scores)
    print('weights:')
    print(weights)
    print('output for "it":', out[3])
    scores:
    tensor([[0.00, -inf, -inf, -inf],
            [0.00, 0.00, -inf, -inf],
            [0.00, 0.00, 0.00, -inf],
            [2.00, 0.00, 0.60, 0.00]])
    weights:
    tensor([[1.00, 0.00, 0.00, 0.00],
            [0.50, 0.50, 0.00, 0.00],
            [0.33, 0.33, 0.33, 0.00],
            [0.66, 0.09, 0.16, 0.09]])
    output for "it": tensor([0.71, 0.09, 0.16, 0.09])

    Here is what happened, row by row:

    • Scores. The query of “it” is [2, 0, 0, 0]. Its dot product with the key of “cat”, also [2, 0, 0, 0], is 4; divided by √4 = 2, the score is 2.0. “Fish” is a little animate (0.3), so its score is 0.6; “ate” and “it” itself score 0.
    • Mask. In a decoder, a token may not look at tokens that come after it, otherwise the model could cheat during training by reading the word it is supposed to predict. The scores of future tokens are set to minus infinity, and softmax turns them into exact zeros.
    • Weights. Softmax of [2.0, 0, 0.6, 0] is [0.66, 0.09, 0.16, 0.09]: “it” pays two thirds of its attention to “cat”. The first three tokens ask nothing in particular (their queries are zero), so they spread attention evenly over what they are allowed to see.
    • Output. The new vector for “it” is 0.66 × cat + 0.09 × ate + 0.16 × fish + 0.09 × it = [0.71, 0.09, 0.16, 0.09]. The pronoun, which had only the “pronoun” feature, now mostly carries the meaning of “cat”.
    Self-attention weights for the tokens cat, ate, fish, it with a causal mask: it gives 0.66 of its attention to cat
    Attention weights from the example: the pronoun it pays two thirds of its attention to cat, and grey cells are hidden by the causal mask

    In a real model nobody designs WQ, WK and WV by hand: they are learned by backpropagation along with everything else, the vectors have 64 to 256 numbers per head, and the attention matrix covers thousands of tokens. But the computation is exactly this one.

    Multi-head attention

    One attention operation produces one weighted average per token, which means it can follow one kind of relationship at a time. Multi-head attention runs several attention operations, called heads, in parallel. The vector of size dmodel is split into h parts of dmodel/h numbers; each head has its own WQ, WK and WV and computes attention in its own subspace. The outputs of all heads are concatenated and mixed by one more matrix, WO. The 2017 base model had 8 heads of 64 numbers each, 8 × 64 = 512. Because each head is smaller, multi-head attention costs about the same as a single large head.

    Different heads learn different jobs. Some look at the previous token, some connect a pronoun with its noun, some copy a word that appeared earlier in a similar context; this last kind, the induction head, was described by Anthropic researchers as a mechanism behind in-context learning. In our recall experiment you can see a head that learned to find the right key in a list of pairs.

    During text generation, every head needs the keys and values of all previous tokens, and storing them takes a lot of memory. This led to variants that share keys and values between heads:

    • Multi-query attention, MQA (Shazeer, 2019): one set of keys and values for all heads.
    • Grouped-query attention, GQA (Ainslie et al., 2023): heads are split into groups that share keys and values. Llama 3.1 8B has 32 query heads but only 8 key-value heads.
    • Multi-head latent attention, MLA (DeepSeek-V2, 2024): keys and values are compressed into a short shared vector of 512 numbers and unpacked per head when needed. DeepSeek-V3 and Kimi K3 use it.

    How much these tricks save is shown in the 2026 section.

    Feed-forward network, residual connections and normalization

    Attention mixes information between tokens, but it is a weighted average: it moves information around more than it transforms it. The transformation happens in the second half of each block, the feed-forward network (FFN), also called the MLP. It is a small two-layer network applied to every token separately and identically: FFN(x) = W2 · activation(W1 · x). In the 2017 paper the hidden layer was four times wider than the model dimension, 2,048 for dmodel = 512, with a ReLU between the layers.

    The feed-forward layers hold most of the weights. In GPT-2, the MLP of each block has 8·d² parameters against 4·d² in attention, two thirds of the block. Research suggests these layers work like key-value memories: the first layer detects patterns in the token’s vector and the second writes the associated information back, so much of what a model “knows” is stored here. The activation function changed over time, from ReLU to GELU in BERT and GPT-2, then to SwiGLU (Shazeer, 2020), a gated variant used by Llama, Qwen, DeepSeek and most current models; our guide to activation functions covers them in detail.

    Large modern models replace this single network with a mixture of experts (MoE): many FFNs, the experts, plus a small router that sends each token to a few of them. DeepSeek-V3 has 256 routed experts per layer and activates 8 of them plus one shared expert for each token, so the model has 671 billion parameters but uses about 37 billion per token. Kimi K3 goes further: 896 experts, 16 active.

    Two more pieces make a deep stack trainable:

    • Residual connections. Each part of the block adds its output to its input, x + f(x), instead of replacing it. The idea comes from ResNet: gradients get a direct path from the output to the first layers, and a block that has nothing useful to add can simply output values close to zero. This is the residual stream from the diagram above.
    • Normalization. Layer normalization rescales each token’s vector to zero mean and unit variance and then applies a learned scale and shift. The 2017 transformer normalized after adding the residual (post-norm). GPT-2 and almost all later models normalize the input of each sublayer instead (pre-norm), which trains more stably and needs less learning-rate warmup. Most current models use RMSNorm (Zhang and Sennrich, 2019), a cheaper version that only rescales.

    With pre-norm, a whole transformer block is two lines:

    x = x + Attention(Norm(x))
    x = x + FFN(Norm(x))

    Encoder, decoder and the three types of transformers

    The original transformer had two stacks. The encoder reads the source sentence with bidirectional self-attention: every token sees every other token. The decoder generates the translation one token at a time with masked self-attention, and in each block it also runs cross-attention: its queries come from the decoder, while the keys and values come from the encoder’s output, so every generated word can look at the whole source sentence. Later models kept one or both stacks:

    Type Attention Trained to Examples Used for
    Encoder-only Bidirectional: each token sees all tokens Fill in masked words BERT (2018), RoBERTa, most embedding models Classification, search, embeddings
    Decoder-only Causal: each token sees only earlier tokens Predict the next token GPT, Llama, Qwen, DeepSeek, Kimi, Mistral, gpt-oss Chatbots, code, agents: almost all LLMs
    Encoder-decoder Encoder bidirectional, decoder causal plus cross-attention Turn one sequence into another Original transformer (2017), T5, BART, Whisper Translation, speech recognition, summarization

    BERT showed in 2018 that an encoder pretrained on huge amounts of text can be fine-tuned for almost any understanding task. The GPT line went the other way: a decoder trained only to predict the next token turned out to be able to do any task that can be phrased as continuing a text, and with GPT-3 in 2020 this approach reached 175 billion parameters. Today almost every chatbot and coding assistant is a decoder-only transformer. Encoder-decoders remain where input and output are different kinds of data: Whisper, for example, encodes audio and decodes text.

    How transformers are trained and how they generate text

    A decoder-only transformer is trained on one task: predict the next token. The loss is the cross-entropy between the predicted distribution and the token that actually comes next. Thanks to the causal mask, one forward pass over a sequence of 128 tokens produces 128 predictions at once, each made with only the tokens to its left visible. An RNN would have to make those predictions one after another; a transformer gets them in a single batch of matrix multiplications, which is why transformers could be trained on trillions of tokens. Pretraining is followed by fine-tuning on dialogues and by reinforcement learning, which turn a text predictor into an assistant; our guide to deep learning explains the training loop itself.

    Generation is a loop. The model computes probabilities for the next token, picks one (usually sampling with a temperature, not always the most likely), appends it to the text and runs again. Every new token needs a pass through the whole network.

    Without tricks, that pass would recompute the keys and values of all previous tokens every time, even though they have not changed. The KV cache stores them: at each step the model computes Q, K and V only for the new token and reads the rest from memory. We measured the effect on a randomly initialized model with 6 blocks and dmodel = 256 on two CPU cores; with and without the cache, greedy decoding produced the same tokens:

    New tokens Without KV cache, s With KV cache, s Speed-up
    128 1.02 0.24 4.2 times
    256 3.61 0.52 7.0 times
    512 11.43 1.10 10.4 times
    1,024 44.18 2.65 16.7 times

    The price is memory. For every token in the context, the cache keeps 2 × layers × key-value heads × head size numbers. For Llama 3.1 8B that is 2 × 32 × 8 × 128 numbers, or 128 KiB per token in bf16, and 16 GiB at its maximum context of 131,072 tokens: more than the 15 GiB its weights take in bf16. That is why long contexts are expensive and why so many of the architecture changes of recent years target the cache.

    Build a mini transformer in PyTorch

    The whole decoder-only transformer fits in about 60 lines of PyTorch. To keep it simple, the tokenizer works on characters: each of the 65 distinct characters in the training text is a token. The model has 4 blocks, 4 heads, dmodel = 128 and a context of 128 characters, which comes to 813,440 parameters. We train it on Tiny Shakespeare, 1.1 million characters of Shakespeare’s plays, holding out the last 10% to measure the validation loss:

    import math
    import sys
    import time
    import torch
    import torch.nn as nn
    import torch.nn.functional as F
    
    torch.manual_seed(1337)
    path = sys.argv[1] if len(sys.argv) > 1 else 'input.txt'
    steps = int(sys.argv[2]) if len(sys.argv) > 2 else 2000
    prompt = sys.argv[3] if len(sys.argv) > 3 else 'ROMEO:'
    
    text = open(path, encoding='utf-8').read()
    chars = sorted(set(text))                      # character-level "tokenizer"
    stoi = {c: i for i, c in enumerate(chars)}
    data = torch.tensor([stoi[c] for c in text])
    n = int(0.9 * len(data))
    train_data, val_data = data[:n], data[n:]
    
    vocab, d_model, n_head, n_layer, ctx = len(chars), 128, 4, 4, 128
    
    
    class SelfAttention(nn.Module):
        def __init__(self):
            super().__init__()
            self.qkv = nn.Linear(d_model, 3 * d_model, bias=False)
            self.proj = nn.Linear(d_model, d_model, bias=False)
    
        def forward(self, x):
            B, T, C = x.shape
            q, k, v = self.qkv(x).split(C, dim=2)
            # split d_model into heads: (B, T, C) -> (B, n_head, T, C // n_head)
            q, k, v = [t.view(B, T, n_head, C // n_head).transpose(1, 2) for t in (q, k, v)]
            att = q @ k.transpose(-2, -1) / math.sqrt(C // n_head)
            mask = torch.ones(T, T, dtype=torch.bool).tril()          # no peeking at the future
            att = att.masked_fill(~mask, float('-inf')).softmax(dim=-1)
            y = (att @ v).transpose(1, 2).reshape(B, T, C)            # concatenate the heads
            return self.proj(y)
    
    
    class Block(nn.Module):
        def __init__(self):
            super().__init__()
            self.ln1, self.ln2 = nn.LayerNorm(d_model), nn.LayerNorm(d_model)
            self.attn = SelfAttention()
            self.mlp = nn.Sequential(nn.Linear(d_model, 4 * d_model, bias=False), nn.GELU(),
                                     nn.Linear(4 * d_model, d_model, bias=False))
    
        def forward(self, x):
            x = x + self.attn(self.ln1(x))    # tokens exchange information
            x = x + self.mlp(self.ln2(x))     # each token is processed on its own
            return x
    
    
    class GPT(nn.Module):
        def __init__(self):
            super().__init__()
            self.tok = nn.Embedding(vocab, d_model)
            self.pos = nn.Embedding(ctx, d_model)
            self.blocks = nn.Sequential(*[Block() for _ in range(n_layer)])
            self.ln_f = nn.LayerNorm(d_model)
            self.head = nn.Linear(d_model, vocab, bias=False)
            self.head.weight = self.tok.weight    # one matrix reads and writes tokens
            for m in self.modules():
                if isinstance(m, (nn.Linear, nn.Embedding)):
                    nn.init.normal_(m.weight, std=0.02)
    
        def forward(self, idx):
            T = idx.shape[1]
            x = self.tok(idx) + self.pos(torch.arange(T))
            return self.head(self.ln_f(self.blocks(x)))
    
    
    def get_batch(src, batch=32):
        ix = torch.randint(len(src) - ctx - 1, (batch,))
        x = torch.stack([src[i:i + ctx] for i in ix])
        y = torch.stack([src[i + 1:i + 1 + ctx] for i in ix])
        return x, y
    
    
    def lr_at(step, max_lr=1e-3, warmup=100):
        if step < warmup:
            return max_lr * (step + 1) / warmup
        progress = (step - warmup) / (steps - warmup)
        return max_lr * (0.1 + 0.45 * (1 + math.cos(math.pi * progress)))
    
    
    @torch.no_grad()
    def generate(model, prompt, n_chars=300, temperature=0.8):
        idx = torch.tensor([[stoi[c] for c in prompt]])
        for _ in range(n_chars):
            logits = model(idx[:, -ctx:])[:, -1, :] / temperature
            nxt = torch.multinomial(logits.softmax(dim=-1), 1)
            idx = torch.cat([idx, nxt], dim=1)
        return ''.join(chars[i] for i in idx[0].tolist())
    
    
    model = GPT()
    print(sum(p.numel() for p in model.parameters()), 'parameters')
    opt = torch.optim.AdamW(model.parameters(), lr=1e-3, betas=(0.9, 0.95), weight_decay=0.1)
    start = time.time()
    for step in range(steps + 1):
        if step % 500 == 0:
            model.eval()
            with torch.no_grad():
                val = sum(F.cross_entropy(model(xv).view(-1, vocab), yv.view(-1)).item()
                          for xv, yv in (get_batch(val_data) for _ in range(20))) / 20
            model.train()
            print(f'step {step}: val loss {val:.3f}, {time.time() - start:.0f} s')
        if step == steps:
            break
        for g in opt.param_groups:
            g['lr'] = lr_at(step)
        x, y = get_batch(train_data)
        loss = F.cross_entropy(model(x).view(-1, vocab), y.view(-1))
        opt.zero_grad()
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step()
    
    model.eval()
    print(generate(model, prompt))

    A few details worth noticing:

    • self.qkv computes queries, keys and values for all heads with one matrix multiplication, and view(...).transpose(1, 2) splits the 128 numbers of each token into 4 heads of 32.
    • The mask is a lower-triangular matrix: position 5 sees positions 0 to 5 and nothing after them.
    • The output layer shares its weights with the embedding table (weight tying, as in GPT-2): the same matrix turns tokens into vectors and vectors back into token scores.
    • In production code, the four lines from att = ... to att @ v are replaced by F.scaled_dot_product_attention(q, k, v, is_causal=True), which computes the same thing faster and without storing the full attention matrix.

    Save the code as gpt.py, put the text next to it as input.txt and run python3 gpt.py. On one CPU core, the 2,000 training steps took 13 minutes, and the script printed:

    813440 parameters
    step 0: val loss 4.198, 3 s
    step 500: val loss 2.117, 198 s
    step 1000: val loss 1.861, 388 s
    step 1500: val loss 1.723, 579 s
    step 2000: val loss 1.654, 768 s
    ROMEO:
    Stannot in the doop.
    
    PETRUCHIO:
    I know, and sun I sea the the son?
    
    Second Murderer:
    O, old you that is unmorna the poor jeden a that
    Prishered them ever on lost. Ay, eart thou shalt you.
    
    COMISA:
    Well you hear to fight that makes after well.
    
    JULIET:
    
    PAPEY:
    
    Well;
    
    LUCIO:
    What you spuster on my

    The validation loss is the average cross-entropy on text the model has not seen, in nats per character. At the start it is 4.2, close to ln 65 ≈ 4.17: an untrained model spreads its guesses evenly over all 65 characters. A loss of 1.65 means that the model is, on average, as unsure as if it were choosing between e1.65 ≈ 5 characters. For comparison, a model that only knows how often each character occurs gets 3.35 on the same text, and one that also looks at the previous character gets 2.48.
    Here is how the model learns to write. These samples come from the baseline run of our experiments, which has the same configuration; all four use the same random numbers, so the differences come only from training:
    Before training:

    Dt!'maYAe:cLs:vEoYSkyMY!t'QSUQSNsSEMMEXQuG
    RYabfjk-YGFymf?:ZtzuO RUKHhUkTwKbOqh'ZsVu TOMch'Hp3gbIJ;EgAKc3YcMXD'lSLH:t;Fgx!Y&TkZNLftE'x'
    KAMj

    After 200 steps:

    ARN'Tan hocos:
    Eord, latt eal Souer semou hir be meest mer stour bof harsater, fes is aveallld bersegandave e mald at;
    An ol thit than's fon
    Ag tr gorowilt thur hinsson t arivrssked; warvild y mes.

    After 500 steps:

    At 'Tand ofor: loodk ladt, and suer semoul
    React my thame the me rof haverter, fes is a cheapl beare
    And in eand forte he old the theat
    Whoure and geace loutsty himsstn thative;
    kewe wath lam ave thee drought to then ond

    After 2,000 steps:

    Duke, my lord: lord, letters will there fortune!
    
    BENVOLIO:
    I well a have tempeath in the could should day.
    
    DUKE VINCENTIO:
    This then's for law them own with your soon than
    vrisked Edward's grave weep touch good in thee,

    After 200 steps, the model already knows the shape of the text: short lines, capital letters, spaces between chunks that look like words. After 500 steps, real words appear. After 2,000 steps, it writes names of characters followed by a colon, punctuation and line breaks in the right places and mostly real words, although the sentences still make no sense. It is a tiny model: GPT-2 small, the smallest version of GPT-2 (2019), has 124 million parameters, 150 times more.

    Experiments: what each part of the transformer does

    Every description of the transformer explains what each part is for, but this is easy to check for yourself. We took the model from the previous section and trained it again and again, changing one thing at a time: removing a part, or replacing it with the 2017 version or with a modern one. Every run had the same budget of 2,000 steps with batches of 32 sequences of 128 characters, about eight passes over Tiny Shakespeare, and the validation loss was measured on the same 40 batches of held-out text. Two reference points help to read the numbers: a model that only knows how often each character occurs gets 3.35 on this text, and one that also looks at the previous character gets 2.48.

    Variant What changed Parameters Validation loss
    Baseline GPT-2-style block: pre-norm LayerNorm, learned positions, GELU feed-forward, 4 heads 813,440 1.656
    Baseline, another seed Same model, different random initialization and batches 813,440 1.657
    Modern block RMSNorm, rotary positions (RoPE) and SwiGLU, as in Llama 800,000 1.496
    Rotary positions only Baseline with RoPE instead of learned positions 797,056 1.565
    Sinusoidal positions Fixed positions from the 2017 paper 797,056 1.780
    No positions No positional information at all 797,056 1.794
    One head One attention head of 128 numbers instead of four of 32 813,440 1.673
    No feed-forward layers Attention only, MLP removed from every block 289,152 1.982
    Post-norm Normalization after adding the residual, as in 2017 813,184 1.815
    No normalization No LayerNorm anywhere 811,136 2.178
    No residual connections x = f(x) instead of x = x + f(x) 813,440 3.343
    LSTM Two-layer LSTM with a state of 240 numbers, learning rate 0.002 841,905 1.596
    Validation loss of a small transformer after 2,000 steps: baseline 1.66, modern block 1.50, rotary positions 1.56, LSTM 1.60, one head 1.67, sinusoidal positions 1.78, no positions 1.79, post-norm 1.81, no feed-forward layers 1.98, no normalization 2.18, no residual connections 3.34
    Validation loss of the same small transformer after 2,000 training steps with one part changed at a time, and of an LSTM of similar size; lower is better

    What the results show:

    • Differences of a few hundredths are real. Two runs of the baseline with different random seeds ended 0.001 apart, so the gaps below are not noise.
    • Without residual connections, the model learned nothing but character frequencies. Its loss fell to 3.34 within the first 250 steps and stayed there until the end, the level of a model that ignores the context altogether. Without the shortcut, every attention layer replaces a token’s vector with a weighted mix of the vectors of all tokens it can see, so information about the current character has to survive all eight sublayers, and the gradients have to come back through all of them. After 2,000 steps, this model still writes a stream of letters with the right frequencies: trabf Tett mft s eet roadhU ateh, es u Ta ch' pd tIbsegA eaicweDnlh
    • Normalization comes next. Without a single LayerNorm, the loss stopped at 2.18, worse than the baseline after 500 steps. The 2017 arrangement, post-norm, reached 1.81. Post-norm is known to need a long learning-rate warmup (4,000 steps in the original paper, 100 here), which is one of the reasons why GPT-2 and almost every model after it normalize before each sublayer. Xiong et al. (2020) showed that this pre-norm arrangement trains well even without warmup.
    • Feed-forward layers hold most of the parameters. Without them, the model has 289,152 parameters instead of 813,440 and reaches 1.98. Part of the loss comes simply from the smaller size, but attention by itself only mixes tokens, and the per-token processing has to happen somewhere. Research on large models suggests that feed-forward layers work as a key-value memory that stores much of what the model knows.
    • A model without positions still learns, but worse. With no positional encoding at all, the loss rose from 1.66 to 1.79, yet the model still learned to write: as explained above, the causal mask itself tells each token how many tokens precede it. Sinusoidal positions from the 2017 paper gave 1.78, only slightly better than no positions at all, while rotary positions gave 1.56, much better than learned ones. Rotary positions encode the distance between two tokens directly in their attention score, and this is one reason why most LLMs since Llama use them.
    • Four heads are slightly better than one. A single head of 128 numbers instead of four heads of 32 raised the loss by 0.02. That is small, but well above the noise, and it comes at no cost: the number of parameters is the same.
    • The modern block is the biggest improvement. RMSNorm, rotary positions and SwiGLU, as in Llama, lowered the loss from 1.66 to 1.50 with slightly fewer parameters, and after 750 steps the modern model was already better than the baseline after 2,000. Rotary positions alone account for 57% of this gain: 1.56 instead of 1.66. RMSNorm and SwiGLU add the rest.
    • An LSTM is a strong rival on this task. A two-layer LSTM with 841,905 parameters reached 1.60: better than the GPT-2-style baseline, though not as good as the modern block. This is not a fluke. In character-level text, much of what matters is in the last few dozen characters, and recurrent networks handle that well: back in 2015, Andrej Karpathy generated Shakespeare with an LSTM. The advantages of the transformer lie elsewhere. Training runs in parallel over the whole sequence, which suits GPUs, and every token has direct access to the entire context. Kaplan et al. (2020) found that LSTMs perform as well as transformers on the first tokens of a context but fall behind on later ones. The next experiment shows the difference directly.

    Transformer vs LSTM: finding a value by its key

    Language models constantly need to retrieve something mentioned earlier: a name, a number, a variable defined 300 lines above. A clean test of this ability is associative recall. The model reads a list of pairs such as “A 4, B 11, C 8, …”, then gets questions such as “A?” and must answer with the value stored under that key. Each pair is one input position, the sum of a key embedding and a value embedding; there are 128 possible keys and 16 values, so random guessing gives 6.25%. We trained a two-layer transformer with rotary positions (109,264 parameters) and an LSTM with a state of 128 numbers (110,672 parameters) on lists of 4 to 64 pairs, 3,000 steps each, and tested both on 2,048 new lists:

    Pairs in the list Transformer LSTM
    4 99.96% 33.46%
    8 100.00% 25.97%
    16 100.00% 19.06%
    32 100.00% 14.47%
    64 99.98% 12.08%
    Associative recall accuracy for lists of 4 to 64 key-value pairs: the transformer stays at 100%, an LSTM of the same size falls from 34% to 12%
    Associative recall: a two-layer transformer and an LSTM of the same size find the value stored under a key in a list of pairs

    By the first check, after 250 training steps, the transformer already answered 99.7% to 100% of questions correctly at every list length. The LSTM got stuck early and stayed there: about a third of correct answers with 4 pairs, falling to 12% with 64. We checked that this is not just bad luck with settings: on 4 pairs, an LSTM with a four times larger state (512 numbers) and a run twice as long with a lower learning rate both stopped at the same 34%.

    The reason is the bottleneck. An LSTM has to squeeze all the pairs into its fixed-size state while reading them, before it knows which ones will be asked about, and it has to learn a way to bind each value to its key inside that state. A transformer keeps every pair in its keys and values and simply compares the question with all of them. The attention map of the trained model shows exactly this:

    Attention map of a trained two-layer transformer: each question attends almost entirely to the pair with the same key
    Attention of one head in the trained transformer: each question looks almost entirely at the pair with the same key (letters are keys, numbers are values)

    For each question, one head of the first layer puts 70% to 100% of its attention on the one pair with the same key, and the rest of the network copies that pair’s value into the answer; on this example, all eight answers were correct. A study of this kind of task, Zoology, found the same gap at a much larger scale between attention and modern recurrent architectures, and it is the main reason why even the hybrid models of 2026 keep some full-attention layers.

    These are small models trained on small tasks, and apart from the baseline, each variant was trained once, so the exact numbers should not be taken too far. The directions, though, match what is known from much larger models.

    Why transformers replaced RNNs, and what attention costs

    The 2017 paper compared three types of layers in a small table that explains the whole story. Here n is the length of the sequence, d the size of the vectors and k the kernel size of a convolution:

    Layer type Computation per layer Sequential operations Longest path between two tokens
    Self-attention O(n²·d) O(1) O(1)
    Recurrent O(n·d²) O(n) O(n)
    Convolutional O(k·n·d²) O(1) O(logk n)

    Source: Vaswani et al., 2017, Table 1.

    Self-attention needs no sequential steps, so all positions are computed in parallel, and it connects any two tokens directly, while in a recurrent network information has to travel through every step in between. The price is the n² term: every token is compared with every other token.

    We measured what this means in practice with one block of the 2017 base size (dmodel = 512, 8 heads, feed-forward layer of 2,048) on two CPU cores. “Linear layers” are the projections to Q, K and V, the output projection and the feed-forward network; “attention” is the part that compares tokens: the scores, softmax and the weighted sum. We timed it in two versions: a naive one that builds the whole n × n matrix, and PyTorch’s fused scaled_dot_product_attention:

    Context, tokens Linear layers, ms Attention, naive, ms Attention, fused, ms Attention matrix, naive
    256 9.2 1.8 1.1 2 MiB
    512 14.9 5.0 3.0 8 MiB
    1,024 27.6 22.9 8.4 32 MiB
    2,048 52.3 180.3 28.9 128 MiB
    4,096 103.5 805.9 103.9 512 MiB
    8,192 236.3 3,304.5 367.4 2.0 GiB
    Time of one transformer block on two CPU cores for contexts of 256 to 8,192 tokens: linear layers grow from 9 to 236 ms, naive attention from 2 ms to 3.3 s, fused attention from 1 to 367 ms
    Time of one transformer block of the 2017 base size on two CPU cores: attention grows with the square of the context, the other layers linearly

    Linear layers grow in proportion to the context: twice the tokens, about twice the time. Attention grows with its square: when the context grew four times, from 2,048 to 8,192 tokens, naive attention took 18 times longer, from 180 ms to 3.3 s, and its score matrix took 2 GiB for a single layer. At 256 tokens, attention took a sixth of the time of the block; at 8,192, naive attention took 14 times longer than all the linear layers together. The fused version computes the same result, but it processes keys and values in small blocks and never stores the whole matrix; at 8,192 tokens it was 9 times faster than the naive one. It still does n² work, though, and at 4,096 tokens it caught up with the linear layers.

    On GPUs the same idea is called FlashAttention (Dao et al., 2022): attention is computed in tiles that fit into the fast on-chip memory, so the full n × n matrix is never written to the main memory of the GPU. The result is mathematically identical, the memory grows linearly with the context, and the authors reported training GPT-2 three times faster. Some version of it now runs inside virtually every LLM training and inference system.

    When does the n² term start to dominate? For the 2017 layout, the attention math overtakes the rest of a block once the context exceeds about 6 × dmodel tokens, 3,072 for dmodel = 512. For Llama 3.1 8B, by our calculation from its configuration, generating a token costs about 15 billion operations in the linear layers, while attention adds 524,288 operations per token of context, so the two are equal at about 28,600 tokens. Below that, a long prompt is expensive mostly because of the KV cache, not because of the attention math.

    Transformer architecture in 2026: what changed since 2017

    If you open the configuration of a large open model released in 2026, you will still find embeddings, a stack of blocks with attention and feed-forward layers, residual connections and a softmax over the vocabulary. Almost every individual part, though, has been replaced:

    Part Transformer, 2017 Typical open LLM, 2026
    Layout Encoder and decoder, 6 blocks each Decoder only, dozens of blocks: 32 in Llama 3.1 8B, 61 in DeepSeek-V3, 93 in Kimi K3
    Positions Sinusoidal vectors added to embeddings RoPE inside attention; some hybrids use no positional encoding at all
    Normalization LayerNorm after each sublayer (post-norm) RMSNorm before each sublayer (pre-norm), often extra normalization of queries and keys
    Attention Multi-head attention in every layer GQA or MLA; in the newest models, mixed with linear attention (Gated DeltaNet, KDA), Mamba-2 layers, sliding-window or compressed sparse attention
    Feed-forward ReLU, 4 times wider than the model SwiGLU; mixture of experts with hundreds of experts
    Residual connections x + f(x) Mostly the same; DeepSeek V4 mixes four parallel residual streams, Kimi K3 lets each layer attend over the outputs of earlier layers
    Context Sentences 128,000 to 1 million tokens
    Size 65 and 213 million parameters Up to 1.6 trillion (DeepSeek V4-Pro) and 2.8 trillion (Kimi K3)
    Training data About 4.5 million sentence pairs for English to German 15 to 33 trillion tokens

    The first wave of changes was settled by 2023. Llama put pre-normalization with RMSNorm, SwiGLU and RoPE together, and since then this combination has been the default recipe for open models; our ablation of the “modern block” tested exactly this trio. Mixture of experts followed: Google’s Switch Transformer reached a trillion parameters back in 2021, Mixtral 8x7B brought MoE to popular open models at the end of 2023, and today the largest open models are all sparse. Google describes its Gemini 2.5 models as sparse mixture-of-experts transformers too; most closed models do not publish their architecture at all.

    The second wave is about memory. With contexts of hundreds of thousands of tokens, the KV cache, not the weights, becomes the bottleneck. We calculated how much cache real models need per token from their configuration files on Hugging Face. Parameters were counted by building each model in the transformers library without loading weights; for DeepSeek V4-Flash, whose compressed attention is harder to count, we use Sebastian Raschka’s estimate:

    Model Year Parameters Active per token Attention KV cache per token KV cache, 131,072 tokens
    GPT-2 small 2019 124M 124M MHA: 12 heads 36.0 KiB — (context up to 1,024 tokens)
    Llama 3.1 8B 2024 8.0B 8.0B GQA: 32 query heads, 8 key-value heads 128.0 KiB 16.0 GiB
    Llama 3.1 70B 2024 70.6B 70.6B GQA: 64 / 8 heads 320.0 KiB 40.0 GiB
    DeepSeek-V3 2024 671B 37.5B MLA: latent vector of 512 + 64 numbers 68.6 KiB 8.6 GiB
    Qwen3-235B-A22B 2025 235B 22.2B GQA: 64 / 4 heads 188.0 KiB 23.5 GiB
    gpt-oss-120b 2025 117B 5.1B GQA; half of the layers see only the last 128 tokens 36.0 KiB 4.5 GiB
    Qwen3.5-397B-A17B 2026 397B 17B 45 Gated DeltaNet + 15 full-attention layers 30.0 KiB 3.8 GiB
    Kimi K3 2026 2.8T 104B 69 KDA + 24 MLA layers 27.0 KiB 3.4 GiB
    DeepSeek V4-Flash 2026 284B 13B Compressed sparse and heavily compressed attention 6.72 KiB 0.84 GiB
    KV cache for a 131,072-token request in bf16: from 40 GiB for Llama 3.1 70B to 3.4 GiB for Kimi K3 and 0.8 GiB for DeepSeek V4-Flash
    KV cache for one 131,072-token request: GQA shares keys and values between heads, MLA compresses them, hybrids keep a cache only in some layers. DeepSeek V4-Flash: estimate by Sebastian Raschka

    The path from Llama 3.1 70B to Kimi K3 shows three ways to shrink the cache. GQA shares keys and values between heads. MLA stores a compressed vector instead: DeepSeek-V3 with full multi-head attention over its 128 heads would need about 4.8 MiB per token, 71 times more than with MLA. Hybrids go further and give most layers no growing cache at all. In Qwen3.5, three of every four layers use Gated DeltaNet, a form of linear attention that keeps a fixed-size state instead of a list of keys and values; only 15 of 60 layers keep a KV cache, while the fixed state of the other 45 takes, by our calculation, about 90 MiB in bf16 whatever the context length. Kimi K3 uses the same 3:1 pattern with its Kimi Delta Attention and MLA, and NVIDIA’s Nemotron 3 models interleave Mamba-2 layers with a few attention layers. DeepSeek V4 keeps an attention layer in every block but compresses it: according to NVIDIA, its mix of compressed sparse attention and heavily compressed attention is designed to cut per-token compute by 73% and KV-cache memory by 90% compared with DeepSeek-V3.2.

    The shift is now general. By Sebastian Raschka’s count, none of the open models released in the second half of 2026 use full attention in every layer: half mix full attention with cheaper layers, and the other half have no dense global attention layer at all. These models are still called transformers, and they are, but the “attention is all you need” part has become “attention in some of the layers”.

    A few other directions are worth knowing:

    • Diffusion language models keep the transformer but change how text is produced: instead of one token at a time, they refine a whole block of text in a few steps, like image diffusion models. ByteDance’s Seed Diffusion showed this for code.
    • Looped transformers run the same blocks several times, spending more computation per token without adding parameters; Thinking Machines’ Inkling 2 Mini is a recent open example.
    • State space models such as Mamba were proposed as a full replacement for attention. In practice they ended up inside hybrid transformers rather than replacing them, because pure recurrent models are worse at recalling exact details from long contexts, the weakness our recall experiment shows on a small scale.

    Where transformers are used

    • Text and code. Chatbots, coding agents, translation, search and summarization: almost all of it runs on decoder-only transformers, with encoder models such as BERT and its successors behind search ranking and text embeddings.
    • Images. The Vision Transformer, ViT, splits a picture into 16 × 16-pixel patches and treats them as tokens. ViT-style encoders now compete with convolutional networks in classification and segmentation and serve as the “eyes” of multimodal models.
    • Image and video generation. Diffusion transformers (DiT) replaced the U-Net inside diffusion models: Stable Diffusion 3, FLUX and most current video generators are built this way.
    • Speech. Whisper and most modern speech recognizers are encoder-decoder transformers; voice assistants generate speech with transformers too.
    • Science. AlphaFold 2 predicts protein structures with an attention-based network, and protein language models such as ESM Cambrian treat amino acids as tokens.
    • Robotics and world models. Vision-language-action models turn camera images and instructions into robot actions, and world models generate interactive environments frame by frame.

    Limitations of transformers

    • Quadratic attention. Doubling the context quadruples the cost of full attention, and the KV cache grows linearly with it. This is the main driver of the 2026 architecture changes.
    • A fixed context window. A model sees only the tokens that fit into its context; everything else has to be brought in from outside, for example by retrieval.
    • Hunger for data and compute. Transformers have few built-in assumptions about their data. That makes them universal but means they need far more examples than, say, a CNN on small image datasets.
    • Fixed computation per token. Every token gets the same number of layers, whether it is a comma or the answer to a hard problem. Reasoning models work around this by writing out long chains of thought, looped transformers by repeating layers.
    • Opacity. We can describe each operation exactly, as in the example with “cat ate fish it”, and still not know why a model with billions of parameters gave a particular answer.

    FAQ

    What is a transformer in AI, in simple terms?

    It is a type of neural network that processes a whole sequence, such as a sentence, at once. For every word or word piece it decides which other words are relevant and mixes in their information. Stacking dozens of such steps lets the model understand context, and training it to predict the next word turns it into a language model like ChatGPT.

    Why is it called a transformer?

    It transforms one sequence into another: the original model turned English sentences into German ones. The name itself was picked because one of the authors, Jakob Uszkoreit, liked how the word sounded. It has nothing to do with electrical transformers.

    What is the difference between a transformer and an RNN or LSTM?

    An RNN reads a sequence one token at a time and keeps everything in a single hidden state, so training is sequential and old information fades. A transformer looks at all tokens at once through attention: training runs in parallel and any token can reach any other directly. The price is that attention cost grows with the square of the sequence length, while an RNN’s cost grows linearly. In our recall test, a two-layer transformer found values by key in lists of up to 64 pairs almost without errors, while an LSTM of the same size answered only 12% to 34% of questions correctly.

    What are query, key and value in attention?

    Three vectors computed from each token by three learned matrices. The query describes what the token is looking for, the key describes what it offers, and the value is the information it passes on. Attention scores are dot products of queries with keys; after softmax, they become the weights for averaging the values.

    Is ChatGPT a transformer?

    Yes. GPT stands for “generative pre-trained transformer”, and the GPT models are decoder-only transformers trained to predict the next token and then fine-tuned to follow instructions. The same is true of most other chatbots, although the details of closed models are not published.

    What is the difference between an encoder and a decoder?

    In an encoder, every token sees all other tokens; it is used to understand text, as in BERT. In a decoder, each token sees only the tokens before it, which allows the model to generate text one token at a time, as in GPT. Translation and speech models often use both, connected by cross-attention.

    What is a KV cache?

    Memory where a model stores the keys and values of tokens it has already processed, so that it does not recompute them for every new token. It makes generation much faster (in our test with a small model, generating 1,024 tokens was 17 times faster), but it grows with the context: Llama 3.1 8B needs 128 KiB per token.

    Are transformers being replaced?

    Not replaced, but rebuilt. Alternatives such as state space models and linear attention ended up as layers inside hybrid transformers. In the open models of late 2026, full attention is used in only some of the layers or replaced with compressed and sparse variants, while the overall structure of the transformer stays the same.


    bnr2mob
    Subscribe
    Notify of
    guest

    0 Comments
    Oldest
    Newest Most Voted