
Language Models · v1.0.4
2026-11-03 01:40:25
Built already
Handed forward
(batch, tokens, embedding dim).Built here

The mechanism and its rationale; the full transformer block belongs to a later unit.

Self-attention relates positions within one sequence; ordinary attention relates two.

For a query token \(x^{(q)}\) among \(T\) tokens:
\[\omega_{q,i} = x^{(q)} \cdot x^{(i)}\] \[\alpha_{q,\cdot} = \operatorname{softmax}(\omega_{q,\cdot})\] \[z^{(q)} = \sum_{i} \alpha_{q,i}\, x^{(i)}\]


\[q^{(i)} = W_q x^{(i)},\quad k^{(i)} = W_k x^{(i)},\quad v^{(i)} = W_v x^{(i)}\]

\[\alpha_{q,\cdot} = \operatorname{softmax}\!\left(\frac{q^{(q)} \cdot k^{(\cdot)}}{\sqrt{d_k}}\right)\]
class SelfAttention(nn.Module):
def __init__(self, d_in, d_out):
L = nn.Linear
self.W_q = L(d_in, d_out, bias=0)
self.W_k = L(d_in, d_out, bias=0)
self.W_v = L(d_in, d_out, bias=0)
def forward(self, x):
q = self.W_q(x)
k = self.W_k(x)
v = self.W_v(x)
s = q @ k.T / d_out**0.5
return softmax(s, dim=-1) @ vA bias-free linear layer computes the same operation as a raw parameter matrix, with a better weight initialization.


Next-token prediction requires a token to consider only positions prior to it.
Two equivalent routes:
The second is preferred: one softmax pass, no renormalization.



d_out, then an output projection.Next: implementing a GPT model from scratch — attention is one sub-layer of the transformer block.