Skip to content
AI360XpertBeta
Playgrounds

Modern ML

Attention

Change the attention weights and inspect how they blend the corresponding value vectors.

Guided steps 1 / 5

Stage 1 of 5: Tokens

Compact plots use native selectors; very narrow plots omit SVG marks while retaining complete calculations. Rows ↓ query i; columns → key/value j. Selected query 5 bank reads key/value 4 river. Effective T=1; settings remain active at every stage.

6 tokens, not yet connected: She, sat, by, the, river, bank.

Query 5 Q=[-0.68,-1.59,-0.69,-0.12,-0.12,-1.69]; key/value 4 K=[-1.09,-1.52,0.04,-0.08,-0.4,-2.17]; V=[0.92,0.08]. Curated coordinates; value axes River, Money.

  • Token
  • Focused token: bolder ring and label
Adjust parameters

Selected query row; native selection and token marks use the same identity.

Which token asks, and which supplies a value?

Positions identify six fixed tokens. Their Q/K/V vectors are manually curated, not learned here. River and Money are assigned illustration axes.

Query, key, value

A query scores keys; each key identity has a corresponding value to blend.

Check this stage

Check your understanding

Attention computes coefficients from query–key scores, then blends corresponding value vectors. Trace every product and normalisation in this fixed toy experiment; its geometric output does not demonstrate word meaning or model quality.

What you are looking at

This attention mechanism visualisation traces one fixed forward computation: six curated query vectors score six curated keys; softmax makes a row of coefficients; those coefficients blend six corresponding value vectors. The five stages retain Tokens, Scores, Weights, Reading and The blend. Nothing is trained.

Positions are zero-based: 0 She, 1 sat, 2 by, 3 the, 4 river, 5 bank. A matrix row identifies the query doing the reading; a column identifies both the key being scored and its corresponding value. Reading is query → key/value. Arrows show the opposite information flow: value → query output, including self-reading.

The token labels and screen positions identify observations; they are not input embeddings. Q and K each have shape 6×6, with unnamed coordinates 0 through 5. V has shape 6×2. Scores and weights each have shape 6×6; the output has shape 6×2. The complete original coordinates are in Inspect. They are manually curated, neither pretrained nor generated or learned here. There is no X, XW_Q, XW_K, XW_V or output projection W_O. River and Money are assigned illustration-axis names, not learned universal semantic directions or empirical evidence.

From a selected pair to a score

Select a query token and key/value token using the native controls, a token mark or a matrix cell. Inspect a Q/K coordinate to follow its original product and running sum. All six terms contribute even when only one coordinate is selected.

For query bank and key river, the products in coordinate order are:

CoordinateQuery × keyProduct
0−0.68 × −1.090.7412
1−1.59 × −1.522.4168
2−0.69 × 0.04−0.0276
3−0.12 × −0.080.0096
4−0.12 × −0.400.0480
5−1.69 × −2.173.6673

The unscaled dot product is 6.8553, subject to binary floating-point rounding. Divide by √6, approximately 2.44949, to get the scaled score, approximately 2.79866. Six is the key/query dimension, not the two-dimensional value width or merely the number of tokens. The pure API allows different query and key counts when all vectors have the same positive dimension; the fixed UI happens to have six of each.

A dot product is not cosine similarity: magnitudes matter. A positive result does not mean identical direction or semantic agreement; a negative result does not establish semantic opposition. Q differs from K, so QKᵀ need not be symmetric. Even symmetric scores can give asymmetric weights after separate row normalisation. No diagonal preference is enforced: the and bank score highest against river.

The usual √d motivation assumes independent zero-mean, unit-variance coordinates, under which dot-product variance grows with d. Dividing by √d counters that growth. It does not bound arbitrary scores, guarantee stability or establish better training in this lab. The original Transformer paper, section 3.2 and footnote 1 states the assumptions and separates this mechanism from learned multi-head projections.

From scores to coefficients

Temperature divides the scaled scores. With a fixed row of scores s, the mathematical coefficients are:

aj=exp⁡(sj/T)∑kexp⁡(sk/T).a_j=\frac{\exp(s_j/T)}{\sum_k\exp(s_k/T)}.

The implementation first finds the row maximum m, computes (s_j−m)/T, then exponentiates. It sums exponentials from left to right starting at zero, then divides each exponential by that denominator. Inspect exposes the unshifted s/T, shifted arguments, exponentials, denominator partial sums and weights separately. Subtracting before dividing is the actual arithmetic order; evaluating large unshifted logits first is not numerically interchangeable. For scores [0, ln(3)] at T=1, shifted exponentials are [1/3,1], denominator 4/3 and weights [1/4,3/4].

The UI requests 0.1–10 in steps of 0.05, initially 1. The pure API accepts finite requests and uses max(0.01, requested). Negative or zero finite requests therefore use the floor, not the mathematical zero-temperature limit. Requested and effective temperatures are distinct inspection fields; nonfinite requests and scores are rejected. Empty score rows return empty weights, not a uniform row. There is no mask and hence no all-masked-row policy, causal attention, padding exclusion or decoder inference to demonstrate.

For finite scores, subtracting the maximum leaves at least one exponential of one. Small exponentials can still underflow to zero, and extreme finite subtraction can overflow negatively to minus infinity. Mathematical normalisation gives a sum of one; floating-point sums may differ slightly, and rounded cell labels need not sum to one. Shifting every score by a common constant leaves exact mathematical softmax unchanged, subject to representing that shift in floating point. The softmax numerical-analysis paper, sections 2–4 explains why shifting helps without eliminating numerical error.

Temperature and concentration

Holding tokens/order, Q/K/V, dimensions, candidates, single-head configuration, absence of masks/projections, √6 scaling, normalisation and query fixed, raising positive temperature reduces score differences and broadens the row. The display scale and geometric evaluation stay fixed too. Matrix display selection changes presentation only; it does not change any score, weight or output.

Finite sharp or broad rows generally remain neither exact one-hot nor exact uniform. For fixed finite scores, T→∞ gives the uniform distribution. As positive T→0, all tied maxima share the mass equally; only a unique maximum has a one-hot limit. The UI never reaches either limit. The displayed top token is the first key position at an exact maximum-weight tie; this display choice does not alter tied weights.

Entropy uses natural logarithms, in nats: H=−Σ a ln(a), with zero terms omitted. Effective tokens is exp(H), between 1 and 6 for this normalised nonempty row. It is a concentration measure, not a literal count of tokens read. Broad attention is not inherently useless, and sharp attention is not inherently failure. Near-one-hot coefficients in this row do not prove an entire model discarded all other context.

The compatibility regime names describe thresholds: first, maximum weight ≥0.9 is called one-hot; otherwise maximum absolute deviation from 1/n less than 0.05 is called uniform; otherwise selective. Precedence matters for singleton rows. These are approximate labels, not exact distribution identities or task-quality judgements. Inspect reports the actual coefficients and deviation, not just the label.

Follow every weighted value

For each output coordinate c, compute O[i,c]=Σ_j A[i,j]V[j,c], accumulating keys in position order from zero. The final-stage aligned grids and selected calculation connect weight, original value, scalar contribution, running output and final result. Inspect contains every query/key row even when an arc or printed label is omitted.

At T=1, bank gives river approximately 0.556 and itself approximately 0.306. Its output is approximately (0.690,0.232) in the assigned value space. This is a weighted vector calculation; it does not prove that an ambiguous word was disambiguated. Attention coefficients are not automatically explanations, causal importance, confidence or semantic similarity. Jain and Wallace’s experiments illustrate why an attention distribution alone need not explain a downstream decision; this lab has no such downstream evaluation.

With corresponding finite value vectors and nonnegative normalised weights, the mathematical output is in their convex hull. That guarantee concerns geometry, not usefulness. The general blendOutput API does not enforce those conditions: it accepts arbitrary weights, skips missing corresponding values and ignores extra values; signed or unnormalised weights can leave the hull, and nonfinite arithmetic can propagate. These general inputs are not editable UI modes.

If all values equal v, every normalised row produces v, up to rounding. More generally, values (0,0),(1,0),(2,0) give the same centroid (1,0) for uniform weights, (0.5,0,0.5) and (0,1,0). An output at the centroid need not imply uniform weights. Different rows and value configurations can give similar or identical outputs.

What centroid displacement measures

The value centroid is their coordinate mean. Maximum radius is the largest Euclidean distance of any value from that centroid. Output spread is the largest Euclidean distance between any two query outputs. Distances use assigned value-coordinate units; there is no conversion to semantic confidence or accuracy.

Centroid displacement, formerly labelled Sense resolved, is output-to-centroid distance divided by maximum radius. It is dimensionless. There is no epsilon or clamp: exactly zero radius returns the API sentinel zero. Empty values have centroid (0,0) and radius zero; empty/singleton output collections have spread zero. Repeated, constant and rank-deficient value arrangements need no inverse or full-rank assumption. A concentrated row can have low displacement if it selects a value near the centroid. Function words do not universally carry little information; their locations here were chosen by the author.

The challenge retains displacement >0.95 on the original fixed Q/K/V and selected query. Only bank and river can clear it on the temperature grid. bank at 0.20 reaches about 0.958, while 0.25 fails. This is a geometric exploration goal, neither word-sense resolution nor a model assessment. At T=10, output spread is about 0.049, versus 0.503 at T=1 with everything else held fixed; the outputs are close, not identical.

Inspection, limits and replay

Native query/key/coordinate selectors and keyboard-operable marks/cells share the same identities. Where 44-pixel targets fit, token marks select queries. When spacing is tighter, structural compact marks use native query selection and smaller radii, without shrinking text. Plots below 110 usable pixels omit SVG marks; native calculations and Inspect retain the experiment. Score/weight cells select query and key/value. Blend cells select key or value coordinate; all settings survive stage return. The score/weight display switch never changes the computation. Tokens have fixed display positions, not learned embedding positions. Signed score opacity uses magnitude divided by the matrix maximum; values and outputs share the maximum absolute V scale. Weight opacity and minimum/maximum display styling do not renormalise the raw coefficients. Arc width is max(1,3×weight) pixels and weights ≤0.01 omit the arc only. Node/label layers paint above connections. The selected key/value arc uses the model role; the native selector retains its identity when that arc is omitted. Compressed matrix column labels use position indices; crowded token labels are omitted. Compressed cell labels are omitted instead of shrinking text, while complete raw values remain in the drawer.

The pure score API rejects ragged/unequal/nonfinite/zero-dimensional vectors and nonfinite dot accumulations. Empty query/key collections retain their natural matrix shape. Equal scores, ties, singleton, zero, negative and repeated finite vectors are supported. The raw entropy helper skips nonpositive entries, so its probability bounds do not apply to arbitrary signed or unnormalised inputs. Empty entropy is zero and exp(H)=1; empty regime is uniform by compatibility convention, not a measurement of an empty probability distribution. Raw geometric helpers do not validate arbitrary nonfinite values: centroid/radius/displacement may propagate infinity or NaN, and the compatibility spread maximum can return zero when NaN distances never win a comparison. That is not a valid measured spread. The fixed finite UI does not reach those inputs. Unknown inspection identities fall back to bank, river and coordinate zero. Bounded UI data do not expose arbitrary-vector numerical limits.

Share reproduces the display stage, temperature, query/key/component identities and matrix display using bundled fixed data, and opens in guided mode. The infrastructure seed is fixed and unused: there is no randomness or seed action. Guesses, recovery and sandbox identity stay local. Reset restores defaults at the retained guided stage, enters guided and clears guesses/recovery; URL restoration clears them too. Experiment, selection, view, stage and sandbox edits invalidate prediction. Inspection and Help preserve it. Load broad row saves the complete preceding experiment; Restore experiment also restores its stage, sandbox and prediction after further edits. Mark explored records local progress, not learning success. No optimiser, playback or algorithm history is implied by a stage or selection change. A real transformer includes mechanisms and training beyond this isolated row; this lab establishes no calibrated confidence, accuracy, training improvement or generalisation.

Stage recap

  1. Tokens

    Positions identify six fixed tokens. Their Q/K/V vectors are manually curated, not learned here. River and Money are assigned illustration axes.

  2. Scores

    Sum six coordinate products Q[i,d]×K[j,d], then divide by √6. Dot product includes magnitude; its sign does not establish semantic agreement or opposition.

  3. Weights

    Softmax normalises each query row. Mathematical sums are one; floating-point sums can differ slightly. exp(entropy) is a concentration measure, not a literal token count.

  4. Reading

    Rows are queries; columns are corresponding keys and values. Arrows carry value information from the key/value token toward the query. Self-reading is allowed; no mask exists.

  5. The blend

    Multiply each coefficient by its corresponding V coordinates and sum. Centroid displacement is a geometric ratio; it demonstrates neither word-sense resolution nor confidence.

Reference

Scores
S[i,j]=Σd Q[i,d] K[j,d]/√6; curated Q,K are 6×6, V is 6×2.
Weights
A=softmax(S/T), row by row. Subtract row maximum before division/exponentiation.
Temperature
UI .1–10 step .05; pure API floors finite requests at .01 and rejects nonfinite values.
Output
O[i,c]=Σj A[i,j] V[j,c]. No output projection.
Effective tokens
exp(H), H=−Σ a ln(a) in nats, skipping zeros; [1,6] for this probability row.
Centroid displacement
Distance from mean V divided by maximum value radius; zero-radius sentinel zero. Not word meaning.
Regimes
one-hot threshold: max ≥.9 first; uniform threshold: max deviation <.05 next; selective otherwise. Labels are approximate, not quality.
Limits
Fixed finite scores: T→∞ gives uniform; T→0 shares weight equally among tied maxima. Neither is a finite-temperature guarantee.

Break it on purpose

Sharp and broad rows are concentration regimes, not evidence of failure or usefulness. The failure to avoid is reading a geometric blend as demonstrated word meaning or model quality.