Approaches to biomedical knowledge

Session #9: Transformer Architecture (Continued)

Peter N Robinson

Free University Berlin

2026-04-26

Overview

Game plan

This lecture provides an introduction to the transformer architecture with a focus on the decoder.

Important: - https://arxiv.org/pdf/2305.17026

Transformer models

Transformer models

An embarassment of riches

  • As can be seen in the previous slide, a large number of different transformer models have been developed
  • They can be grouped largerly in encoder-decoder, encoder-only, and decoder-only
  • The original paper, “Attention is all you need…”, described an encoder-decoder transformer
  • This architecture is well suited for sequence-to-sequence tasks such as machine translation
  • Last week, we focused on an introduction to the encoder model
  • This week, we will provide additional detail and focus mainly on decoder-only models and on training

Decoder models

A decoder-only transformer is an autoregressive neural network architecture that uses masked causal self-attention to predict the next token in a sequence.

  • Input processing:
    • GPT-like models are decoder-only models
    • Inputs (i.e., tokenized prompt) are embedded and encoded
    • Positional encodings are added to the input embeddings
    • Attention calculation, similar to previously described
    • Large matrix multiplications, heavy usage of GPU hardward accelerator
    • Parallel process

Recap

  • Recall encoder algorithm from the previous lecture:
Tensor Dimension Example Explanation
Input sequence
[BOS] The quick brown fox jumps over the lazy dog [EOS]
Input tokens with additional beginning/end of sequence tokens
Tokenized Input sequence
[50256, 791, 4062, 14198, 39935, 35308, 927, 279, 16053, 5679, 50256]
\(N\) \(11\) Number of tokens, including [BOS]/[EOS]
\(\mathbf{X}\): Input embeddings \(N\times d_{hidden}\) \(11\times 512\) \(d_{hidden}\) is the embedding dimension
\(\mathbf{W}^Q\): query weights
\(\mathbf{W}^K\): key weights
\(\mathbf{W}^V\): value weights
\(d_{hidden}\times d_{hidden}\) \(512\times 512\) Learnable model weights (single-head attention, so \(d_k=d_{hidden}\))
\(\mathbf{Q}=\mathbf{XW}^Q\): query matrix
\(\mathbf{K}=\mathbf{XW}^K\): key matrix
\(\mathbf{V}=\mathbf{XW}^V\): value matrix
\(N\times d_{hidden}\) \(11\times 512\) \(\mathbf{Q}\): What each token needs to know from others
\(\mathbf{K}\): What information each token provides
\(\mathbf{V}\): Content each token shares when attended to
\(\mathbf{QK}^T\): attention scores \(N\times N\) \(11\times 11\) How well each token’s query matches the keys of the other tokens
\(\mathrm{softmax}\left(\dfrac{\mathbf{QK}^T}{\sqrt{d_k}}\right)\mathbf{V}\) \(N\times d_{hidden}\) \(11\times 512\) Attention weights applied to Values — context-aware token representations
\(\times\ \mathbf{W}^O\): output projection (optional here) \(N\times d_{hidden}\) \(11\times 512\) Required to combine multiple heads back to \(d_{hidden}\); with a single head the shape already matches, so \(W^O\) is optional (often kept anyway for extra learnable capacity)
Add & Norm \(N\times d_{hidden}\) \(11\times 512\) Residual connection + LayerNorm (see Part 1)
FFN: \(\text{GELU}(\mathbf{X}W_1+b_1)W_2+b_2\) \(N\times d_{hidden}\) \(11\times 512\) Position-wise, applied independently per token; expands to \(d_{ff}\) (e.g. \(2048\)) and projects back (see Part 1)

This recap shows single-head attention, so \(d_k=d_{hidden}\)

Adapted from: Simon J Decoder-only inference: A step-by-step dive (video)

Multihead attention

  • Scaled dot-product attention

  • Multihead attention – several attention layers running in parallel

Multihead attention

  • Instead of performing a single attention function with \(d_{hidden}\)-dimensional keys, queries, and values
  • It is beneficial to linearly project the queries, keys, and values \(h\) times with different linear Projections
  • The results are concatenated and once again projected resulting in the final values

\[ \mathrm{MultiHead}(Q,K,V) = \mathrm{Concat}(\mathrm{head}_1, \ldots,\mathrm{head}_h)\mathrm{W}^{O} \] where \[ \mathrm{head}_i = \mathrm{Attention}(QW_i^Q, KW_i^K, VW_i^V) \]

  • In the original paper, the authors use \(h=8\) (8 heads)
  • Then, \(d_k=d_v=d_{hidden}/h = 64\) because \(d_{hidden} =512\) (In the paper \(d_{hidden}\) is called \(d_{model}\))
  • dimension check: \(W_i^Q\) and \(W_i^K\) are \(d_{hidden}\times d_k\), \(W_i^V\) is \(d_{hidden}\times d_v\), and \(\mathrm{W}^{O}\) is \(hd_v \times d_{hidden}\)

Multihead attention

  • All heads get the full input sequence, but only see a subset of the embedding dimensions
  • Each head has its own Q,K,V matrices
  • All heads compute attention scores in parallel
  • Main benefit: Multihead attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this.
  • i.e., MHA yields better models!

MHA step by step

Tensor Dimension Example Explanation
Input sequence
[BOS] The quick brown fox jumps over the lazy dog [EOS]
Input tokens with additional beginning/end of sequence tokens
Tokenized Input sequence
[50256, 791, 4062, 14198, 39935, 35308, 927, 279, 16053, 5679, 50256]
\(N\) \(11\) Number of tokens, including [BOS]/[EOS]
\(\mathbf{X}\): Input embeddings \(N\times d_{hidden}\) \(11\times 512\) \(d_{hidden}\) is the embedding dimension
\(\mathbf{W}^{Q_i}\): query weights
\(\mathbf{W}^{K_i}\): key weights
\(\mathbf{W}^{V_i}\): value weights
\(d_{hidden}\times d_{mha}\) \(512\times 64\) \(d_{mha}=d_{hidden}/h\), where \(h\) is the number of heads
each head has its own weight matrices
\(\mathbf{Q}_i=\mathbf{XW}^{Q_i}\): query matrix
\(\mathbf{K}_i=\mathbf{XW}^{K_i}\): key matrix
\(\mathbf{V}_i=\mathbf{XW}^{V_i}\): value matrix
\(N\times d_{mha}\) \(11\times 64\) all heads run in parallel
\(\mathbf{Q}_i\mathbf{K}_i^T\): attention scores \(N\times N\) \(11\times 11\) How well each token’s query matches the keys of the other tokens
\(\mathrm{softmax}\left(\dfrac{\mathbf{Q}_i\mathbf{K}^T}{\sqrt{d_k}}\right)\mathbf{V}_i\) \(N\times d_{mha}\) \(11\times 64\) Attention weights applied to Values — context-aware token representations
Concatenate head outputs \(N\times d_{hidden}\) \(11\times 512\) Attention weights applied to Values — context-aware token representations
\(\times\ \mathbf{W}^O\): output projection (optional here) \(N\times d_{hidden}\) \(11\times 512\) Required to combine multiple heads back to \(d_{hidden}\); with a single head the shape already matches, so \(W^O\) is optional (often kept anyway for extra learnable capacity)
Add & Norm \(N\times d_{hidden}\) \(11\times 512\) Residual connection + LayerNorm (see Part 1)
FFN: \(\text{GELU}(\mathbf{X}W_1+b_1)W_2+b_2\) \(N\times d_{hidden}\) \(11\times 512\) Position-wise, applied independently per token; expands to \(d_{ff}\) (e.g. \(2048\)) and projects back (see Part 1)
  • Gray background: Identical to single-head attention case

Adapted from: Simon J Decoder-only inference: A step-by-step dive (video)

Output generation

  • Unlike input generation, output generation is a sequential process
    • The answer is generated one token at a time
    • Each generated token is appended to the previous input
    • Process repeated until we get an \(\langle \mathrm{EOS}\rangle\) token1 or the maximum length is reached

Autoregressive text generation

  • Output is generated one token at a time

Text generation: step by step

Tensor Dimension Example Explanation
Attention output for the input sequence
(aka prefill)
\(N\times d_{hidden}\) \(11\times 512\) This matrix represets the input embeddings that have been updated to consider the context of other tokens
Attention output for the last token \(1\times d_{hidden}\) \(11\times 512\)
\(\mathbf{W}_{out}\): linear layer
(aka project layer)
\(V\times d_{hidden}\) \(100,000\times 512\) \(V\) is the vocabulary size, i.e., number of tokens
\(\text{Logits} = \text{attention output}\times \mathbf{W}_{out}^T\) \(1\times V\) \(1\times 100,000\) Raw scores for all tokens
\(\text{softmax}(\text{Logits})\) \(1\times V\) \(1\times 100,000\) token probabilities
Decode the token 1 token 1 outside the model; see next page

Token decoding: Deterministic Methods

Deterministic methods:

  • generate text by selecting the continuation with the highest probability determined by the LM.
  • Deterministic methods may lead to model degeneration
    • output becomes “unnatural”
    • output is marked repetitive and overly predictable language.
    • text lacks variety and fails to reflect natural human expression.

Token decoding: Stochastic methods

Stochastic methods:

Human-generated text exhibits greater variance in token probabilities, reflecting a diverse range of word choices, often unexpected.

In contrast, the output from deterministic methods shows minimal variance, resulting in more predictable and potentially repetitive text.

  • Stochastic approaches introduce randomness during the decoding process, leading to more diverse and natural text generation.

Token decoding: Top-\(k\) sampling

  • The \(k\) most probable next words are selected1
  • The probability of the \(k\) top words is redistributed to form a new distribution, i.e., the probabilities of these k tokens are then normalized to sum to 1, resulting in a truncated distribution.
  • A token is then randomly sampled from this distribution and appended to the current sequence.
  • This process is repeated iteratively until a termination condition is satisfied.

Fan A (2018) [Hierarchical Neural Story Generation. arXiv 1805.04833]https://arxiv.org/abs/1805.04833)

Token decoding: Top-\(p\) (Nucleus) Sampling

  • Selects the smallest set of words whose cumulative probability meets or exceeds a predefined threshold \(p\).
  • Rather than sampling exclusively from the top \(k\) most probable words, Top-\(p\) redistributes the probability mass across this dynamic set.
  • This adaptive approach allows the size of the word set (i.e., the number of included words) to increase or decrease based on the shape of the next-token probability distribution.
  • Rest of approach is identical

Holtzman A (2020) [The Curious Case of Neural Text Degeneration. arXiv 1904.09751]https://arxiv.org/abs/1904.09751)

Token decoding: Temperature Sampling

  • The core idea of temperature sampling is to control the “sharpness” of the probability distribution by introducing a temperature parameter \(t\).
  • This parameter is applied in the softmax function after the transformer’s final layer to compute token probabilities.
  • The temperature t directly influences the level of randomness in the sampling process, with higher values increasing randomness and lower values reducing it.

Token decoding: Temperature Sampling

  • The core idea of temperature sampling is to control the “sharpness” of the probability distribution by introducing a temperature parameter \(t\).
  • This parameter is applied in the softmax function after the transformer’s final layer to compute token probabilities.
  • The temperature \(t\) directly influences the level of randomness in the sampling process, with higher values increasing randomness and lower values reducing it.1

\[ P(x_i) = \frac{\exp(z_i / t)}{\sum_j \exp(z_j / t)} \]

  • \(t=1\): standard softmax (no change)
  • \(t<1\): sharper distribution — closer to greedy/argmax as \(t\to 0\)
  • \(t>1\): flatter distribution — closer to uniform as \(t\to\infty\)

Temperature: worked example

  • Let the following be the logits for the next token after “The cat sat on the”:
token logit \(z_i\)
mat 2.0
floor 1.0
bed 0.1
couch -1.0
Temperature mat floor bed couch
0 t=0.5 0.862 0.117 0.019 0.002
1 t=1.0 0.638 0.235 0.095 0.032
2 t=2.0 0.451 0.274 0.174 0.101
  • At \(t=0.5\): “mat” dominates (≈0.86) — the model behaves almost deterministically
  • At \(t=1.0\): the raw model distribution (≈0.64 for “mat”)
  • At \(t=2.0\): much flatter (≈0.45 for “mat”) — “couch” and “floor” become far more likely than under the original distribution

Combining temperature with top-\(k\) / top-\(p\)

  • Temperature and truncation (top-\(k\), top-\(p\)) are typically applied together, in sequence:
    1. Scale logits by \(1/t\)
    2. Apply softmax to get the temperature-adjusted distribution
    3. Truncate: keep only the top-\(k\) tokens, or the smallest set whose cumulative probability exceeds \(p\) (nucleus sampling)1
    4. Renormalize the remaining probabilities to sum to 1
    5. Sample from the renormalized distribution
  • Example: applying top-\(k=2\) after \(t=0.5\) scaling keeps only {mat: 0.862, floor: 0.117}, renormalized to {mat: 0.880, floor: 0.120} — “bed” and “couch” are excluded entirely
  • Intuition:
    • temperature reshapes how peaked the whole distribution is
    • top-\(k\)/top-\(p\) decide how much of the tail is eligible for sampling at all.
  • Many chat APIs expose both temperature and top_p as independent parameters.

Training LLMs

  • The next sections will cover several aspects of how to train LLMs
  • For the most part, LLMs are synonymous with decoder-only transformers; from now on we will say LLM for conciseness.

Training LLMs: Causal (Masked) Self-Attention

The problem

  • Encoder self-attention lets every token attend to every other token — including tokens that come later in the sequence.
  • A decoder predicts tokens one at a time, left to right. If some token \(i\) can attend to a token \(j\) during training with \(j>i\), the model can simply “read the answer” instead of learning to predict it.
  • This would make the training loss trivially low — the model learns nothing about actually predicting the future, since the future is already visible.
  • We need a mechanism that lets us train on the full sequence in parallel (for efficiency), while still preventing this kind of “leakage.”

Masked Self-Attention

  • Recall: \(\text{Attention}(Q,K,V) = \text{softmax}\left(\dfrac{QK^\top}{\sqrt{d_k}}\right)V\)
  • We modify this by adding a mask matrix \(M\) to the scores, before the softmax step:

\[ \text{MaskedAttention}(Q,K,V) = \text{softmax}\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V \]

  • \(M\) is an \(n\times n\) matrix, defined entrywise as:

\[ M_{i,j} = \begin{cases} 0 & j \le i \quad \text{(allowed: current or past token)} \\ -\infty & j > i \quad \text{(disallowed: future token)} \end{cases} \]

  • Adding \(-\infty\) to a score, then applying softmax, transforms the entry tp exactly \(0\).
  • In practice, implementations use a large negative finite number (e.g. \(-10^9\)) instead of literal \(-\infty\), for numerical stability — the same spirit as the \(\epsilon\) we added inside LayerNorm in Part 1.1

Worked Example: The Mask Matrix

  • For our 4-token sentence “I am an automaton” (\(n=4\)), the mask matrix is:

\[ M = \begin{bmatrix} 0 & -\infty & -\infty & -\infty \\ 0 & 0 & -\infty & -\infty \\ 0 & 0 & 0 & -\infty \\ 0 & 0 & 0 & 0 \end{bmatrix} \]

  • Row \(i\) corresponds to the query token; column \(j\) to the key token.
  • Row 0 (“I”): only column 0 is unmasked — the first token can only attend to itself.
  • Row 3 (“automaton”): all four columns are unmasked — the last token can attend to the entire sequence, since nothing comes after it.
  • Causal masking is often just called “triangular masking.”

Worked Example: From Raw Scores to Masked Attention Weights

Suppose the raw attention scores \(S =\frac{QK^\top}{\sqrt{d_k}}\) for our sentence. - The masking procedure is as follows

\[ \mathbf{S} + \mathbf{M} = \begin{bmatrix} 0.9 & 0.2 & -0.1 & 0.4 \\ 0.3 & 1.1 & 0.5 & -0.2 \\ 0.1 & 0.4 & 1.3 & 0.6 \\ -0.2 & 0.3 & 0.7 & 1.5 \end{bmatrix} + \begin{bmatrix} 0 & -\infty & -\infty & -\infty \\ 0 & 0 & -\infty & -\infty \\ 0 & 0 & 0 & -\infty \\ 0 & 0 & 0 & 0 \end{bmatrix} = \begin{bmatrix} 0.9 & -\infty & -\infty & -\infty \\ 0.3 & 1.1 & -\infty & -\infty \\ 0.1 & 0.4 & 1.3 &-\infty \\ -0.2 & 0.3 & 0.7 & 1.5 \end{bmatrix} \]

  • Applying softmax row-by-row yields

\[ \mathrm{softmax}(\mathbf{S} + \mathbf{M}) = \begin{bmatrix} 1.0 & 0 & 0 & 0 \\ 0.31 & 0,690 & 0 & 0 \\ 0.176 & 0.238 & 0.586 &0 \\ 0.094 & 0.156 & 0.232 & 0.517 \end{bmatrix} \]

  • Row “I”: weight \([1.000, 0, 0, 0]\) — with only itself unmasked, softmax trivially assigns it all the probability mass.
  • Row “am”: weight \(\approx[0.310, 0.690, 0, 0]\) — splits attention only between “I” and “am”.
  • Row “automaton”: weight \(\approx[0.095, 0.156, 0.233, 0.517]\) — the only row using the full softmax, since nothing is masked.
  • Notice the upper triangle is exactly \(0\) in every row

Pretraining

Traditional ML:

  • train a separate model for each task from scratch
  • Some ML tasks are similar. For instance
    • Spam detection
    • sentiment Analysis
    • machine translation
  • All three tasks require the model to understand natural language
  • The transfer learning approach reused a trained model for a new task by “tuning” the previously trained model
  • LLMs take this approach to an extreme: Pretraining

Pretraining

  • Pre-training is the foundation for the power of Large Language Models (LLMs)
  • Train by predicting the next work (token) on large collections of text data
  • Most LLMs are trained on general data (“all” web pages, “all” books, etc.)
  • Conversation text may help LLMs get better at chatting (train on social media data, e.g., Reddit)
  • Books: May help LLMs “understand” complicated topics better than webpages/social media
  • Stack exchange/GitHub: Help LLMs “understand” code

Pretraining

  • Size of training data
LLM Param count Size
GPT-3 (2020) 175 billion \(\sim\) 350 GB
 LLaMA-2 (2023) 7B, 13B, 70B \(\sim\) 14 GB–140 GB
 Llama 3   15 trillion tokens \(\sim\) 60 TB
 GPT-4  (Estimated)~1.8 trillion  Proprietary

Pretraining: Size matters

  • Language modeling performance improves smoothly as we increase the model size, datasetset size, and amount of compute2 used for training.
  • Coversely, the authors found very weak dependence on many architectural and optimization hyperparameters.

Optimal model size

  • On the other hand, what if we have a fixed compute budget and cannot increase the number of parameters or the amount of data without limit?
  • The authors investigatef the optimal model size and number of tokens for training a transformer language model under a given compute budget.
  • They found that current large language models are significantly undertrained, a consequence of the recent focus on scaling language models whilst keeping the amount of training data constant.

Pretraining: Learning parameters

Causal language modeling

  • A decoder is trained to predict each token given only the tokens that came before it.
  • The basic back-propagation from previous lectures is used to train LLM parameters as well
  • An Adam optimizer is most frequently used to implement gradient descent
  • This is an autoregressive factorization of the joint probability of a sequence:

\[ P(x_1,\ldots,x_n) = \prod_{t=1}^n P(x_t \mid x_1,\ldots,x_{t-1}) \]

  • The model doesn’t predict the whole sentence at once — it predicts one conditional distribution per position, and the chain rule of probability guarantees these conditionals multiply out to the joint probability of the full sequence.
  • This factorization is exactly why causal masking (Section 2) is needed: each factor \(P(x_t \mid x_1,\ldots,x_{t-1})\) must only depend on the past, or the factorization isn’t valid.

The Loss Function

  • Training uses cross-entropy loss between the predicted next-token distribution and the true next token.
  • For a single position \(t\), with true token \(x_t\) and predicted probability \(\hat{P}(x_t \mid x_{<t})\):

\[ \mathcal{L}_t = -\log \hat{P}(x_t \mid x_1,\ldots,x_{t-1}) \]

  • The total loss for a sequence is the sum (or mean) over all positions:

\[ \mathcal{L} = -\sum_{t=1}^n \log \hat{P}(x_t \mid x_1,\ldots,x_{t-1}) \]

Teacher forcing

  • Teacher forcing: during training, the true previous tokens are fed as input at every position — not the model’s own (possibly wrong) predictions.
  • This is what makes it possible to compute the loss for all \(n\) positions in a single parallel forward pass, using the causal mask from Section 2 to prevent each position from seeing its own answer.
  • At inference time there is no ground truth to feed back in — this is exactly the “Append and reprocess” loop from our decoding-steps diagram, where each new token is the model’s own prediction, fed back as input for the next step.

Image: https://www.deeplearning.ai/

Worked Example: Cross-Entropy Loss

Continuing “I am an automaton” — suppose after “I am an” the model’s predicted distribution over the next token is:

token P(token)
automaton 0.55
apple 0.05
idea 0.15
the 0.25
  • The true next token is “automaton,” with predicted probability \(0.55\).
  • The loss at this position is \(-\log(0.55) \approx 0.598\).
  • If the model had instead assigned “automaton” a probability of, say, \(0.01\), the loss would jump to \(-\log(0.01)\approx 4.6\) — cross-entropy penalizes confident wrong predictions much more heavily than uncertain ones.

KV Cache

  • Let us return to the input processing (prefill) for decoder-only transformers
    • Inputs (tokenized prompt) are embedded and positionally encoded
    • Multihead attention (MHA) computes keys and values (KV)
    • Lots of matrix multiplications, high usage of hardware accelerator on the GPU
  • Output is sequential (one token at a time)
    • Generated token is appended to previous input, …, again and again
    • MHA process is repeated each time
    • sequential means we cannot parallelize much!

KV Cache

  • Can we avoid recomputing KV values again and again?
  • We only really need to compute KV values for the newly generated token
  • The KV Cache stores the keys and values for all tokens we have previously generated

  • We do not need to regenerate keys or values for “I” and “love” when we generate a new token “tofu”
  • Queries are never cached and never reused, for any token, at any step.
    • a query is only ever used once, at the moment its own token is being generated, to compute that token’s output.
  • We need to compute: Q, K, V for the new token “tofu”: all three must be computed fresh — Q because it’s a brand-new token needing its own query, and K/V because “tofu” also needs to contribute its own key/value pair to the cache for future tokens to attend to.

KV Cache

  • When processing \(\mathrm{token}[k]\), we only need the \(k^{th}\) row of \(\mathbf{Q}\).
  • When processing \(\mathrm{token}[k]\), we need the full \(K\) and \(V\) tensons, but we can mostly reuse the cached values
  • Add the value for \(k+1\) as we go along

Image credit: Generative LLM inference with Neuron (https://awsdocs-neuron.readthedocs-hosted.com/)

KV Cache: Size

  • The Cache size (FP16) can be calculated as

\[ 2\times 2\times\text{batch-size}\times\text{seq-length}\times\text{num-layers}\times\text{embedding dimension} \] - We need to multiply by 2 because we have \(K\) and \(V\) - We need to multiply by 2 again because we have 16 bits (FP16) - Usually gigabytes of memory required - Many different attempts to shrink cache size to allow the batch size to be increased

HBM:

  • The data for the KV Cache is typically stored in the High-Bandwidth Memory, which is off GPU
  • Quadratic complexity for KV Cache access

Multihead latent attention

  • Introduced by DeepSeek for version 2
  • Some previous approaches to reduce size of KV Cache used fewer keys and values (CQA, MQA)
  • MLA
    • Does not cache K and V
    • uses a low-rank representation that is learned during training and cached
    • also learn a projection matrix to shring K and V during training
    • Much lower KV cache usage (90%+ savings)
    • 5-6x inference speedup
    • Hgher accuracy than vanilla MHA

Multihead latent attention

Tensor Dimension Example Explanation
\(\mathbf{X}\): input embeddings \(N\times d_{hidden}\) \(11\times 512\) Embedded input tokens
\(\mathbf{W}^{Q_i}\): query weights
\(\mathbf{W}^{K_i}\): key weights
\(\mathbf{W}^{V_i}\): value weights
\(d_{hidden}\times d_{mha}\) \(512\times 64\) \(d_{mha}=d_{hidden}/h\), where \(h\) is the number of heads
each head has its own weight matrices
\(W_{down}\): down-projection matrix
\(W_{up}\): up-projection matrix
\(d_{mha}\times d_{mha-latent}\)
\(d_{latent}\times d_{hidden}\)
\(64\times 4\)
\(32\times 512\)
\(d_{latent}\) should be much smaller than \(d_{hidden}\) (here, \(d_{latent}=32\) and \(d_{hidden}=512\))
\(d_{mha-latent} = d_{latent}/h\) where \(h\) is the number of attention heads (e.g. \(8\))
\(\mathbf{Q}_i=\mathbf{XW}^{Q_i}\): query matrix
\(\mathbf{K}_i=\mathbf{XW}^{K_i}\mathbf{W}_{down}\): key matrix
\(\mathbf{V}_i=\mathbf{XW}^{V_i}\mathbf{W}_{down}\): value matrix
\(N\times d_{mha}\)
\(N\times d_{mha-latent}\)
\(11\times 64\)
\(11\times 4\)
\(11\times 4\)
all heads run in parallel
\(\mathbf{Q}_i\mathbf{W}_{down}\mathbf{K}_i^T\): attention scores \(N\times N\) \(11\times 11\) All heads run in parallel. \(Q\) is down-projected for this calculation only and not cached.
\(\mathrm{softmax}\left(\dfrac{\mathbf{Q}_i\mathbf{W}_{down}\mathbf{K}_i^T}{\sqrt{d_k}}\right)\mathbf{V}_i\) \(N\times d_{mha-latent}\) \(11\times 4\) Attention weights applied to Values — all heads run this in parallel
Concatenate head outputs \(N\times d_{latent}\) \(11\times 32\)
\(\mathrm{Outputs}\times \mathbf{W}_{up}\) \(N\times d_{hidden}\) \(11\times 512\) Project output back to original dimension
Remaining steps \(\ldots\) \(\ldots\) as before
  • The \(d_{hidden}\) dimension is hurting us. Let’s downproject from 512 to 32.
  • Because we are doing multihead attention, we project 64 to 4 (same factor)
  • K and V are stored in KV cache and are \(d_{hidden}/d_{latent}\) times smaller–\(512/32=16\)
  • The tradeoff is that there is an extra matmut to compute \(K_i\) and \(V_i\)
  • \(Q\) is not changed because it is not cached!

LORA

  • We will return to low-rank approximation (LORA) in a subsequent lecture

Sources