Macalinao StudioLearnAll lessons ↗

TAKE THE LONGER ROUTE

Open the complete college extension →

Worked explanations, full local narration, and connected Signal Room, Workbench and Field Notes.

SIGNAL ROOM

Q / K / VUnderstand the moving parts.

The matrices that turn embeddings into queries, keys, values.

Suggested preparation: 12

WORKBENCH / CHANGE ONE THING

Project the same input three ways

Change a query projection while keys and values stay fixed.

Computed teaching example · fixed assumptions shown below

LISTEN & FOLLOW / GUIDED RECAP

Audio starts only when you choose.

FIELD NOTES / THE COMPLETE READING

Take the longer way.

The full lesson narrative, equations and code. Switch views without losing your place.

A slower starting point

Three different questions about one object give three different descriptions.

Where this deserves more time

Projection parameter gradients; shape tracing; shared versus separate heads.

Open the complete high-school reading

Moment 01 / 09

Introduction to Q, K, V Projections

We begin with the Query, Key, and Value projections, the learned linear maps that turn a residual-stream embedding into the three tensors attention actually consumes. This is the entry point to Vaswani et al. 2017.

Start from the embedding: each token is a dense vector in the residual stream, and attention reweights it by context. The mechanism decides, per position, which other tokens are relevant and by how much.

The three roles are distinct. The Query is what a token is looking for; the Key is what a token advertises it contains; the Value is the payload actually aggregated into the output once a match is scored.

These roles are produced by learned projection matrices, W-Q, W-K, and W-V. Each is a separate linear map from the model dimension into the attention dimension, so the same embedding yields three different views.

Formally, Q equals X times W-Q, K equals X times W-K, V equals X times W-V, with X the stacked embeddings. All parameters are trained end to end by backpropagation through the cross-entropy loss.

Attention then scores compatibility as Q K transpose over the square root of d-k, applies a softmax, and returns a convex combination of the Value rows. The scaling keeps logits from saturating the softmax.

The PyTorch snippet instantiates these maps as linear layers without bias, applied to a batch of embeddings. Note the shapes: sequence length is preserved while the feature dimension is projected.

Together these projections are the inductive bias of self-attention: content-based routing learned from data, not fixed by position. Master Q, K, V here and multi-head attention, causal masking, and RoPE become straightforward extensions.

Equations, code and original cards

Query, Key, and Value Projections

Embeddings and the Residual Stream

• Tokens embedded as dense vectors
• Attention reweights by context
• Position-wise relevance scoring

Roles of Q, K, V

• Query: what a token seeks
• Key: what a token advertises
• Value: payload aggregated
• Scores from Q-K compatibility

Learned Projection Matrices

• Parameters: W_Q, W_K, W_V
• Linear maps d_model to d_k
• Trained by backpropagation

Q = X W_Q, \quad K = X W_K, \quad V = X W_V
\text{Attention}(Q,K,V) = \text{softmax}\left(\frac{Q K^T}{\sqrt{d_k}}\right) V
# Learned linear projections (no bias)

W_Q = nn.Linear(embed_dim, proj_dim)

W_K = nn.Linear(embed_dim, proj_dim)

W_V = nn.Linear(embed_dim, proj_dim)



X = torch.randn(batch_size, seq_len, embed_dim)

Q = W_Q(X)  # (batch, seq_len, proj_dim)

K = W_K(X)

V = W_V(X)

Moment 02 / 09

Mathematical Formulation of Q, K, V

The query, key, and value projections are the linear backbone of scaled dot-product attention, the mechanism introduced by Vaswani and colleagues in 2017.

Denote by X the residual-stream matrix whose rows are the token embeddings for a sequence; every attention head reads from this shared representation and writes its update back into it.

Concretely, X has shape N by d, with N the sequence length and d the model dimension; stacking tokens as rows lets a single matrix multiply serve the entire sequence at once.

The projections are Q equals X times W-Q, K equals X times W-K, and V equals X times W-V, where each W is a learned d by d-k matrix. These projections are the only trainable parameters here; the attention aggregation itself is a fixed, parameter-free routing rule.

Compatibility scores come from Q K transpose divided by the square root of d-k, then a softmax converts them into convex weights over V. This is content-based addressing: geometry in the projected space decides who attends to whom.

So self-attention reduces to three learned linear maps feeding a normalized dot-product kernel; the expressivity lives in the projections, not in the weighted average.

Equations, code and original cards

Q, K, V: Learned Linear Projections

• Residual-stream matrix X (token embeddings)

• Learned projections W_Q, W_K, W_V — the only parameters

• Q = X·W_Q, K = X·W_K, V = X·W_V

Q = X W_{Q}, \quad K = X W_{K}, \quad V = X W_{V}

• X: shape [N, d]; N = sequence length, d = model dim

• W_Q, W_K, W_V: shape [d, d_k]; one matmul serves all N tokens

• Attention: softmax(QKᵀ / √d_k) · V — content-based routing

Moment 03 / 09

Gradient Derivations and Backpropagation

Write the input as rows of X, with Q equals X times W Q. The query projection gradient is X transpose times the upstream gradient with respect to Q. The key projection follows the same rule using the gradient with respect to K.

Check shapes before multiplying. The input X, not the other attention projection, appears in the gradient of a projection weight matrix. Attention itself has additional score and softmax derivatives.

Clarification: Projection gradients use the input X, not K. Projection gradients use the input X, not Q.

Equations, code and original cards

Backpropagation Through Q, K, V Projections

Key Ideas

• Linear maps from the residual stream are differentiable end to end

• dL/dW_Q = X^T dL/dQ; analogously for W_K and W_V

• Cross entropy shapes attention by updating these projections

\nabla_{W_Q}L=X^\top\nabla_Q L
\nabla_{W_K}L=X^\top\nabla_K L
# autograd equivalent: dL/dW_Q = X^T dL/dQgrad_WQ = X.T @ grad_Qgrad_WK = X.T @ grad_K

Moment 04 / 09

Interactive QKV Projection Visualization

Here we trace how each token embedding is linearly projected into Query, Key, and Value vectors, the three operands of scaled dot-product attention.

Vary the embedding entries and watch how each component propagates through the projections into the downstream vectors.

Each input row is multiplied by the learned weight matrices W-Q, W-K, and W-V, mapping the d-model dimensional embedding into per-head query, key, and value subspaces of dimension d-k and d-v.

Sweep across several embeddings and observe the projections respond linearly: these maps define the geometry in which attention scores are computed, as in Vaswani et al. 2017.

Equations, code and original cards

Moment 05 / 09

Advanced Optimization Techniques (2024-2026)

Let's examine projection-layer optimization circa 2024 to 2026: the QKV projections account for roughly a third of a transformer's parameter FLOPs, so compressing them buys real wall-clock savings.

Here we see efficiency gains targeted at very large models. The objective is scaling capacity without the quadratic attention cost and the linear projection cost growing unchecked.

This slide outlines three levers: scaling-law-guided pruning of projection ranks, sparse attention patterns that skip redundant score computations, and low-rank factorization of the projection matrices themselves.

Consider this low-rank approximation of the query projection W-q. Decomposing it into factors A and B with rank r much smaller than d cuts parameters from d squared to two d r, reducing both memory traffic and matmul cost.

Here is a PyTorch snippet implementing the factorized projection. Note that W-q is stored as the product of two skinny matrices, so the forward pass performs two small matmuls instead of one large one, with minimal accuracy loss if r is chosen well.

This expression gives the baseline: Q equals X times W-q, an n by d input against a d by d weight, costing n d squared FLOPs per layer. Keep this baseline in mind so you can quantify exactly what the low-rank and sparse variants save.

In summary, these techniques trade a controlled approximation error for large gains in throughput and memory. The design skill is choosing rank, sparsity pattern, and quantization bit-width so the loss curve barely moves.

Equations, code and original cards

Advanced Optimization Techniques (2024-2026)

QKV projection efficiency: low-rank factorization,

scaling-law-guided pruning, and sparse attention

• Projections are roughly one third of transformer FLOPs

• Rank r ≪ d cuts parameters from d² to 2dr

• Accuracy loss is minimal when r matches intrinsic rank

# PyTorch: factorized low-rank QKV projectionW_q = torch.nn.Parameter(torch.randn(d_model, rank) @ torch.randn(rank, d_model))
\mathbf{Q}=\mathbf{X} \mathbf{W}_q,\quad \mathbf{K}=\mathbf{X} \mathbf{W}_k,\quad \mathbf{V}=\mathbf{X} \mathbf{W}_v
\mathbf{W}_q \approx \mathbf{A} \mathbf{B}, \quad \mathbf{A} \in \mathbb{R}^{d \times r}, \ \mathbf{B} \in \mathbb{R}^{r \times d}

Moment 06 / 09

2026 Research Trends and Alignment

Welcome to today's session on 2026 Research Trends and Alignment. We examine recent advances in model scaling, attention mechanism design, and query-key-value projection schemes, and how these choices govern alignment, robustness, and optimization stability in transformer architectures.

First, consider scaling trends: parameter counts now reach hundreds of billions, and Chinchilla-style compute-optimal training pairs roughly twenty tokens per parameter. The interaction between scale, data budget, and generalization determines whether added capacity yields robust performance or merely memorization.

Next, we turn to attention alignment through alternative QKV projection schemes. Researchers vary head dimension, shared versus decoupled projections, and low-rank factorizations to improve gradient flow, reduce parameter count, and stabilize the attention logits during training.

An open question: how do these projection choices shape gradient flow through backpropagation? The Jacobian of the projection directly scales gradients entering the residual stream, so poorly conditioned projections can produce vanishing or exploding gradient norms across layers.

In PyTorch, a fused projection maps the hidden state to three times the projection dimension, then reshapes into query, key, and value tensors. Implementing variants such as multi-query or grouped-query attention lets you empirically measure their effect on stability and throughput.

To summarize: we surveyed compute-optimal scaling, projection variants for attention alignment, and open questions on gradient dynamics. These directions sit at the frontier of robust, efficient transformer design and merit careful ablation in your own work.

Equations, code and original cards

2026 Research Trends and Alignment

• Compute-optimal scaling: Chinchilla N ≈ 20D, generalization at 10^23+ FLOPs

• QKV projection variants: MQA, GQA, low-rank and fused projections

• Open questions: gradient flow, logit stability, attention robustness

# PyTorch: fused QKV projection, alignment-awareproj = nn.Linear(hidden_dim, 3 * proj_dim, bias=False)  # fused QKVqkv = proj(x).reshape(batch, seq_len, 3, proj_dim)

Q: How does the projection Jacobian shape gradient norms and attention robustness?

Moment 07 / 09

Implementation Details: Python and PyTorch Examples

Today we examine how query, key, and value projections are implemented in PyTorch, and how these linear maps feed into multi-head attention.

First, the projection matrices themselves. Each is a learned affine transformation from the residual stream dimension d-model into the attention dimensions d-k and d-v, letting the model carve out subspaces specialized for matching and for content.

Here the class Projections subclasses nn.Module and registers three nn.Linear layers. Registration matters: declaring them as attributes places their weights in the module's parameter list, so the optimizer and backpropagation see them.

Next, the forward pass, where queries, keys, and values are computed explicitly before entering the attention score computation.

The forward method applies each projection to the input tensor, which carries batch, sequence, and feature axes, and returns Q, K, and V. Because these are differentiable linear maps, gradients flow through them end to end during training.

This pattern is the foundation for any custom attention variant, whether you are implementing multi-query attention, grouped-query attention, or low-rank projections.

In summary: learned projections in PyTorch reduce to three registered linear layers, the forward pass computes Q, K, and V in a handful of lines, and this is the machinery multi-head attention builds on. Keep it in mind as we scale up to full attention blocks.

Equations, code and original cards

Implementation Details: Python and PyTorch Examples

1. PyTorch Learned Projection Matrices

import torch.nn as nnclass Projections(nn.Module):  def __init__(self, d_model, d_k, d_v):    super().__init__()    self.W_Q = nn.Linear(d_model, d_k)  # registered parameter    self.W_K = nn.Linear(d_model, d_k)    self.W_V = nn.Linear(d_model, d_v)

2. Forward Pass: Q, K, V Computation

def forward(self, x):  # x: (batch_size, seq_len, d_model)  Q = self.W_Q(x)  # (batch, seq, d_k)  K = self.W_K(x)  # (batch, seq, d_k)  V = self.W_V(x)  # (batch, seq, d_v)  return Q, K, V  # differentiable end to end

Moment 08 / 09

Cutting-Edge Variations and Open Research

We turn now to frontier variations on the QKV projection and the open problems they raise. This survey covers experimental designs that relax the static, linear assumptions of standard attention, along with their costs.

First, adaptive and dynamic projection matrices. Rather than fixed weights, these schemes condition the projections on the input itself, through gating or hypernetwork-style parameter generation, buying expressiveness at the price of optimization difficulty.

Second, non-linear and kernelized attention. Kernel approximations to the softmax, as in the Performer, reduce attention from quadratic to linear time in sequence length, while learned similarity measures move beyond the plain dot product.

Third, the open problems. Dynamic projections complicate optimization and can destabilize training; added parameters strain inference latency; and most of these variants lack the theoretical grounding that standard attention now enjoys.

Treat this slide as a map of the research frontier in projection design. Tracking these developments matters, since several of today's efficiency tricks began as exactly this kind of speculative variant.

To summarize: adaptive projections, kernelized and non-linear attention, and the unresolved questions of stability and theory. That foundation prepares you to implement, ablate, and critically evaluate advanced attention mechanisms in your own work.

Equations, code and original cards

Cutting-Edge Variations and Open Research

Survey of experimental and emerging QKV projection methods

Adaptive and Dynamic Projection Matrices

• Projections conditioned on input: gating, hypernetworks

• Weights become functions of the residual stream

• Expressiveness gains versus optimization cost

Non-linear and Kernelized Attention Variants

• Kernel approximations to softmax (Performer, linear attention)

• Complexity drops from O(n²d) toward linear in sequence length

• Learned similarity measures beyond the dot product

Challenges and Open Research Questions

• Training stability with input-dependent weights

• Parameter overhead versus inference latency

• Little theory: scaling and generalization behavior unproven

Moment 09 / 09

Challenging Quiz: Conceptual & Computational

Time to probe whether the query-key-value projection machinery actually landed. Work each question independently; they target both the geometry and the compute cost.

Once you submit, we'll walk the solutions together and isolate exactly where the intuition broke.

Equations, code and original cards

MAKE IT YOURS

Explain the change.

References, scope & corrections

Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.

3 correction entries · expansion notes

Reset this lesson?

This removes only this lesson’s saved notes, experiments and progress.