Skip to content
AI360XpertBeta
Playgrounds

Generative AI

Full Transformer Block

Trace how multi-head attention, residual connections and a feed-forward network transform token vectors inside one block.

Guided steps 1 / 6

Stage 1 of 6: Embeddings

Query occurrence-0 (The) at position 0; key/value occurrence-0 at position 0. Heads 2; positions on. Effective settings persist at every stage.

The, cat, sat; Embedding lookup; both residuals and normalisations active.

  1. 1. Embedding lookup
  2. 2. + positions
  3. 3. Sliced-head attention
  4. 4. + input → norm 1
  5. 5. Token-wise FFN
  6. 6. + norm 1 → norm 2

{"token":"The","known":true,"coordinates":[0.1,-0.2,0.5,0.8,0.1,-0.2,0.5,0.8,0.1,-0.2,0.5,0.8]}; coordinate 0: embedding 0.1.

Embeddings: 3×12; selected [0,0]=0.1. Rows current token position, columns features.

Embeddings, 3 rows, 12 columns. Raw signed values remain in inspection; compact cells use native selection.

Selected cell top-left: omitted; cell 0. Crowded labels omitted. Compact cells are structural; use native row/column selection.

  • Token
  • Architectural Block
  • Vector Matrix Cell
  • Attention Weight
Active Tokens3Active Tokens: 3
Attention Heads2Attention Heads: 2
Model Dimension12Model Dimension: 12
Selected head row sum1.000000Selected head row sum: 1.000000

Which occurrence uses this vocabulary row?

Distinct occurrences can share identical curated coordinates; these vectors are not pretrained.

  1. Input
  2. + positions
  3. MHA
  4. + input / Norm 1
  5. FFN
  6. + norm 1 / Norm 2
Embedding

A curated vector looked up by exact token spelling in this lab.

Check this stage

Check your understanding

Follow each token occurrence through a fixed post-norm block: sliced-input attention, signed residual additions, feature normalisation and a shared token-wise ReLU network.

What does this block compute?

This fixed Transformer block maps three token rows to three output rows, each with twelve coordinates. Trace one occurrence through embeddings, positions, sliced-input attention, an add-and-normalise step, a token-wise FFN and a second add-and-normalise step. It is a forward demonstration, not a trained language model.

The six stages reveal calculations that are always computed. Returning to an earlier stage retains the effective settings. Use Intermediate matrix to inspect any computed sublayer, Inspected head for each actual head, and the query/key occurrence and feature selectors to follow signed products and partial sums. Compact matrices omit labels or use structural cells; native row/column selection and the complete raw drawer retain every value. Display opacity and rounding never change arithmetic.

Which token is being followed?

The defaults are The, cat, sat. Occurrence identities stay attached to those three instances when Swap First Two Tokens moves them. Current position is a separate zero-based slot. A repeated token in the pure API has another occurrence but the same vocabulary vector. Vocabulary lookup is case-sensitive: The and the are distinct curated keys with identical coordinates; CAT is unknown and gets twelve zeros. Own-key lookup also safely treats constructor, toString and __proto__ as unknowns. This is a fixed vocabulary policy, not a general tokenizer.

The twelve embedding coordinates repeat a four-coordinate tile three times. They are curated examples, not pretrained or learned here. At position zero, positional coordinates alternate zero and one. For an even coordinate i, the pair is:

Pp,i=sin⁡(p/10000i/12),Pp,i+1=cos⁡(p/10000i/12).P_{p,i}=\sin\left(p/10000^{i/12}\right),\qquad P_{p,i+1}=\cos\left(p/10000^{i/12}\right).

Positions start at zero; arguments are radians. Both coordinates share angular frequency 1/10000i/121/10000^{i/12}. The attention input is X=E+PX=E+P, without embedding scaling. Switching positions off supplies a zero P. Embedding-only, positional-only and summed matrices remain separately inspectable. Other architectures can use learned or relative position mechanisms; sine/cosine addition is this lab's choice.

What exactly changes with the head count?

With h heads, each receives only a disjoint interval of width d=12/hd=12/h from X. Head h-index a takes original coordinates [ad,(a+1)d)[ad,(a+1)d). Local coordinate c maps to original coordinate ad+cad+c. Unlike canonical Transformer full-input projections, this implementation first slices the input, then uses square d-by-d Q/K/V matrices.

Every coefficient at zero-based row i and column j follows:

Wij(s)=0.5sin⁡(s+0.7(i+1)+1.3(j+1))+0.3cos⁡(1.7s+1.1(i+1)−0.6(j+1)).W_{ij}(s)=0.5\sin(s+0.7(i+1)+1.3(j+1)) +0.3\cos(1.7s+1.1(i+1)-0.6(j+1)).

Formula constants are 11+7a11+7a for Q, 23+7a23+7a for K, 37+7a37+7a for V, 101 for output projection, 131 for FFN expansion and 151 for FFN contraction. These are deterministic offsets, not random-generator seeds. Angle addition separates each trigonometric term into two outer products, so exact rank is at most four, bounded also by matrix shape. Distinct offsets guarantee neither full rank nor universally nonproportional matrices. Numerical rank needs an explicit tolerance.

Changing Attention Heads changes input slices, projection shapes and generated entries, and the score divisor together. Tokens, occurrence identities, vocabulary, positions, output/FFN coefficients, residuals, normalisation and evaluation stay fixed. This is not an isolated comparison of head count or evidence that more heads are better. There are 3(122)/h+122+2(12)(24)3(12^2)/h+12^2+2(12)(24) fixed coefficient entries and zero trainable parameters here. For n rows, the straightforward projection, score and value-blend products total n(3(122)/h+122+2(12)(24))+2n2(12)n(3(12^2)/h+12^2+2(12)(24))+2n^2(12) scalar multiplications; this excludes softmax, normalisation, activation and position calculations.

How does a query read values?

For each head, row-vector products give Q=XsliceWQQ=X_{slice}W_Q, K and V analogously. Expand the projection cards to inspect every original-coordinate product and partial sum. A selected query i and key j then use:

Sij=∑cQicKjcd,Aij=exp⁡(Sij−mi)∑kexp⁡(Sik−mi),mi=max⁡jSij.S_{ij}=\frac{\sum_c Q_{ic}K_{jc}}{\sqrt d},\qquad A_{ij}=\frac{\exp(S_{ij}-m_i)}{\sum_k\exp(S_{ik}-m_i)},\qquad m_i=\max_j S_{ij}.

Different Q/K projections mean QK-transpose need not be symmetric. Even symmetric scores can produce asymmetric row-normalised weights because denominators differ. The dot product includes magnitudes; it is neither cosine similarity nor proof of semantic agreement. Scaling by square-root d reduces score magnitude. The familiar variance motivation assumes independent zero-mean unit-variance coordinates, which these curated inputs need not satisfy.

The actual implementation subtracts the row maximum, exponentiates, accumulates the denominator in increasing-key order, and divides. Equal finite scores give equal weights mathematically: scores zero and log three give one quarter and three quarters. Adding one common constant leaves mathematical softmax unchanged, subject to finite representation. Tied maxima share a sharp limit rather than selecting a unique key. Floating row sums need tolerance; rounded labels can sum differently. Saturation and exponential underflow can produce computed zeros. Maximum subtraction avoids positive exponential overflow, while extreme finite subtraction can become negative infinity.

There is no temperature control, mask, dropout, padding exclusion or causal behaviour. Every token can read itself and every other token. Decoder masking remains contextual quiz material. Attention coefficients are mixing coefficients, not validated explanations, causal importance, confidence or semantic understanding.

Each head output coordinate accumulates ∑jAijVjc\sum_j A_{ij}V_{jc} in increasing j. Inspect every signed contribution and partial sum. With finite values and nonnegative normalised weights, each head blend is a convex combination of its V rows. Head outputs are concatenated in increasing head/local-coordinate order, not summed. The concatenated row then multiplies the actual signed 12×1212\times12 output matrix WOW_O. The output-projection card retains all twelve products and partial sums. Convex-combination bounds do not automatically survive that projection or later steps.

What do the residuals and normalisations do?

The first operands are X and attention output. Add them coordinate by coordinate, then normalise each token's features: this is post-norm. The second operands are norm-one and FFN output, followed by another identical normalisation. Both paths are unconditional. Native matrix selection can inspect either raw sum before scaling.

For a row z of width D, the exact convention is:

μ=1D∑czc,v=1D∑c(zc−μ)2,LN⁡(z)c=zc−μv+10−5.\mu=\frac1D\sum_c z_c,\quad v=\frac1D\sum_c(z_c-\mu)^2,\quad \operatorname{LN}(z)_c=\frac{z_c-\mu}{\sqrt{v+10^{-5}}}.

Both reductions accumulate in increasing feature order. The divisor is D, not D-minus-one; epsilon is inside the root. No learned gamma or beta exists. The drawer exposes the mean, centred coordinates, squared deviations, partial squared sums, variance, denominator and every output. For [1,3], mean is two, variance one and outputs are minus/plus 1/1.000011/\sqrt{1.00001}. Exact-arithmetic variance is v/(v+10−5)v/(v+10^{-5}), not universally one. A constant or singleton row becomes zero.

Normalisation is not whitening or batch normalisation. Residual terms can cancel; post-addition normalisation changes the result further. Neither operation guarantees information preservation, bounded results under invalid arithmetic, gradient health or successful training. This lab computes no loss, derivative or optimiser step. Pre-norm is architectural context, not a selectable mode.

Which features does the FFN mix?

Every token row reuses the same bias-free coefficients:

F(H)=ReLU⁡(HW1)W2,W1∈R12×24,W2∈R24×12.F(H)=\operatorname{ReLU}(HW_1)W_2,\qquad W_1\in\mathbb R^{12\times24},\quad W_2\in\mathbb R^{24\times12}.

Select a hidden coordinate to inspect all twelve signed expansion products, their preactivation sum and ReLU result. Negative preactivations become zero; zero maps to zero. Select an output coordinate to inspect all twenty-four contraction contributions. The same FFN mixes features within each row, with no new cross-token reduction. Other expansion ratios, biases and activations occur in real models but are not controls here.

What does the swap challenge establish?

Turn positions off, keep heads fixed and swap the first two occurrences. Align output rows by occurrence identity: outputs relocate with their inputs, up to floating-point accumulation differences. This is permutation equivariance, not invariance and not the claim that equal row indices keep equal values. The original challenge badge checks the off/order condition; the drawer separately reports the measured aligned maximum output difference.

Consistently permuting an already constructed X permutes the result even if X originally contained positional coordinates. The swap button instead moves token embeddings and recomputes positions at fixed slots. With positions enabled that different experiment can break the symmetry. It does not guarantee that every swap changes every output or prove understanding of word order. Repeated or identical embeddings, constants, zeros, projection nullspaces and other degeneracies can still yield equal outputs.

The comparison holds occurrence vocabulary, heads, projections, scaling, residuals, normalisation, FFN, absence of masks, selected identities and evaluation fixed. Only embedding order changes, with positions recomputed at slots when enabled. Head feature selects a projected Q/K/V and per-head blend coordinate independently of Output feature, which selects the final projected coordinate. A native W_O row selects its head/local concatenated coordinate; its column selects the final coordinate. Projection input selection resolves modulo each input width, and every product card names its effective selected term. Matrix view, selection and viewport changes are presentation only. Neither comparison establishes semantics, accuracy, usefulness or generalisation.

How do sharing and recovery work?

Share includes displayed stage, heads, position switch, swap order and all numeric inspection selectors. Fixed data/formula constants are bundled; links open guided. The infrastructure seed is unused. Predictions, sandbox identity, recovery and local progress are excluded. There is no inactive editable buffer or real algorithm prefix.

Load position-free swap saves the complete preceding in-memory experiment. Restore experiment recovers settings, selections, original stage, sandbox and prediction even after further edits. Reset controls defaults settings at the retained guided stage, enters guided and clears recovery/prediction. URL navigation also clears them. Mathematical, selection, view, stage and sandbox edits invalidate a guess; Help, inspection, presentation, motion and resize preserve it. Mark explored records local exploration, not assessed learning. There is no training timeline to play.

Sources and onward reading

The original Transformer architecture, sections 3.1–3.5 supplies the context; this lab's sliced input and fixed coefficients differ from its full-input learned projections. Layer Normalization, section 3 defines per-example statistics, while PyTorch LayerNorm makes epsilon and affine conventions explicit. SciPy softmax documents shifting, and NumPy numerical rank explains tolerance-dependent singular-value decisions. Return to Attention for its separate curated Q/K/V experiment or Embeddings for original-space retrieval. A standalone block is not a complete trained language model or decoder.

Stage recap

  1. Embeddings

    Distinct occurrences can share identical curated coordinates; these vectors are not pretrained.

  2. Positional Encoding

    Position-dependent sine/cosine coordinates are added at fixed slots; switching them off exposes permutation equivariance.

  3. Multi-Head Attention

    Each head projects a disjoint input slice, computes scaled scores and a value blend; W_O mixes the concatenated coordinates.

  4. Residual & Norm (1)

    Add X and the projected attention output, then normalise features within each token row.

  5. Feed-Forward

    The bias-free FFN mixes features through 12→24, ReLU and 24→12; coefficients are shared across rows.

  6. Residual & Norm (2)

    Add norm-one and FFN output, then normalise again. Constant rows give zero, not variance one.

Reference

Residual Connection
\text{LayerNorm}(x + \text{Sublayer}(x))
Sublayer
Multi-Head Attention or Feed-Forward Network
Attention (per head)
\text{softmax}(QK^\top / \sqrt{d_k})V
Multi-Head Attention
\text{concat}(\text{head}_1, \dots, \text{head}_h) W_O
Layer Norm
(x - \mu) / \sqrt{\sigma^2 + \epsilon}
Feed-Forward
\text{ReLU}(x W_1) W_2

Break it on purpose

Without positional coordinates, permuting input rows permutes output rows by token occurrence, up to floating-point rounding. This is equivariance, not order-invariant row values.