How the weight of Attention becomes a new expression
Two sets of two-dimensional teaching vectors are used to calculate matching scores, attention weights and output, and to examine each of them separately. causal mask and padding mask 。
Learning objectives and first steps4 objectives • 3 first fixes
Try to do it after reading
- Mark source and matrix shape for Query, Key, Value
- Manual scale point, line by line softmax and Value weighted
- Distinction causal mask 、 padding mask and loss mask
- What does a focus-heavy attempt suggest
Suggested first
- Matrix Multiplication and Conversion
- Pointing and vectoring
- Softmax with numerical stability
How to get a location from another location
When processing a sequence, the indication of the current location often needs to be combined with the other locations. Attention calculates the level of matching and then the weights obtained by the matching are aggregated. This is not so simple as to “select the most important word”: the calculation is the relationship between the vectors, and the results of the aggregation follow.
This chapter calculates only One head size point core count for Attention I don't know. Q, K, V in the example is an artificial synthetic teaching vector, not a word vector extracted by a true model, and does not represent the interpretation of the actual sentence. Multiple headings, output projection, debris, statization and FFN are not in this smallest calculation.
Q, K, V each for what
Query is the current query to match, Key provides the matching vector, and Value provides the elements to be aggregated. Set number of queries as nq, readable position is nk, match dimension as dk, content dimension is dv:
| Matrix | Shape | What does every line mean |
|---|---|---|
| Q | nq × dk | A query vector |
| K | nk × dk | A matching vector for readable locations |
| V | nk × dv | Content provided by the same location |
Therefore, the numbers of the rows for Q and K must be identical, and the rows for K and V must correspond, and instead dk It doesn't have to be the same dvI don't know. Self-attention usually obtained by different projectiles from the same input Q/ K/ V; Cross-attention can obtain queries and readings from different input.Original Transformer dissertation A bit of volume and multi-headed structure is given.
Each line here follows all key positions to do softmax. Mathematically allowed reading places are 0 in M, which is forbidden to bear endless weights; After softmax, the prohibited position is given a weight of 0. The semantic of the Boolean mask for specific API may be different and it is not possible to transfer True/ False from one library directly to another.
From input projection to match space
The actual self-attention usually gets Q, K, V from different linear projection input to X, instead of setting them in the same matrix. If X Yes. T × dmodel , WQ 、 WK Yes. dmodel × dk , WV Yes. dmodel × dv , the projection enters the core calculation of this chapter. Q matches the K description, and V retrieves what; The same place can play different roles in different spaces. This example is intended to facilitate the calculation of the order Q = K, but it is not possible to judge the same weight matrix for the last two scales of training.
A conditional variance calculation explains scaling. If components of q and k are mutually independent with zero mean and unit variance, their dot product sums dk products and has variance dk. Dividing by √dk gives variance approximately one. Real networks need not satisfy these assumptions, and scaling does not automatically stabilize gradients, but it prevents scores growing systematically just because more terms are summed. Excessive scores can make softmax nearly one-hot and shrink non-maximum gradients.
Finish two rows of vectors
Take Q=K=[[1,0],[0,1]],V=[[2,0],[0,4]],dk=2I don't know. Q by K for conversion to the unit matrix; After the first row is divided by §2 [0.70710678,0]。
Calculated for this line softmax: first is exp(0.7071)/(exp(0.7071)+1)≈0.66976155The second is about 0.33023845I don't know. The original score is not taken directly as weight, as it may be negative or guaranteed.
| Situation | First row weight | Second line weight |
|---|---|---|
| No mask | [0.66976155, 0.33023845] | [0.33023845, 0.66976155] |
| Standard causal mask | [1, 0] | [0.33023845, 0.66976155] |
When no mask, first line output is 0.66976155×[2,0]+0.33023845×[0,4], i.e., an agreement [1.33952310,1.32095380]; The second line is about [0.66047690,2.67904620]I don't know. The weight determines the mix ratio, and the Value determines the specific content to be mixed.
For the core calculation of this chapter, the weight of the legitimate line is not negative and is equal to one, so the output is a contour at the Value vector. The two Values are connected to their segments; When a position is blocked, the remaining individual item weights are one and the output can only be equal to that item. The complete model, which is followed by an output projection, residue and non-linearness, ultimately means that it is no longer subject to the simple conclusion that it is “in the original Value contour”.
mask changes readable range
Standard self-return causal mask Allows the current position to read itself and earlier, and does not allow the future to be read. In these two position examples, the first line cannot read the second position, and then becomes weight [1,0]Output [2,0]; The second line has no place for the future and the results remain unchanged.
Padding mask The problem is different: if the second position is merely a placeholder that completes the length, it should not be used as a valid placeholder key Read by another location. This does not automatically mean that all padding query output has been cleared. Which locations were involved in the calculation of the target during the training, and by loss mask It was decided that the same switch could not be confused.
It should also be checked that reading is prohibited in a row as a whole: there is no definition of normal softmax as being unicoded in the absence of a valid entry. This condition should be clearly stated and should not be revealed. NaN or add to an even distribution.
A line-by-line calculation
Only standard Python and math; The causal switch is expressed in a permitted position to avoid hiding the Boolean synonym in a frame.
import math
Q, K = [[1, 0], [0, 1]], [[1, 0], [0, 1]]V = [[2, 0], [0, 4]]causal = Trueweights, output = [], []for i, query in enumerate(Q): scores = [sum(q * k for q, k in zip(query, key)) / math.sqrt(2) for key in K] allowed = [not causal or j <= i for j in range(len(K))] if not any(allowed): raise ValueError("这一行没有可读取的位置") peak = max(s for s, ok in zip(scores, allowed) if ok) terms = [math.exp(s - peak) if ok else 0.0 for s, ok in zip(scores, allowed)] row = [value / sum(terms) for value in terms] weights.append(row) output.append([sum(row[j] * V[j][d] for j in range(len(V))) for d in range(2)])print(weights)print(output)Minus the maximum value in the line does not change softmax, but avoids too large an index. (a) The weight shall be not negative and equal to 1 for legal lines that have not been completely blocked; The output shape should read nq×dvI don't know. These conditions are better suited for inspection than “heat attempts seem reasonable”.
Unvariable positioning for error
After checking the weight and shape of a row, three minor disturbances can be made. Add all permitted points in the same row to the same constant and the weight should be the same; Zoom in only one Value, with the weight unchanged and the output changed; Adds an invisible future position to the end of the sequence, with causal output already available to be consistent. They check separately whether softmax values are processed, matches are confused with content, and whether mask is really blocking the future.
A distinction must also be drawn between training and reasoning. Attention dropout The weight path is changed during the training and the reasoning should be closed by model configuration; Multiple projections, synthesizing and output transformations must not be missed. The integration algorithms of the framework sometimes do not explicitly return to the full weight matrix, which is memory and performance design and does not mean that no attention is counted. The T x T matrix for all layers and all heads to be forcibly saved for graphic purposes may significantly increase the cost of memory.
Boolean mask is the easiest to make an error "Looking able to run": some interfaces interpret reality as permissible or others as prohibited; Added mask usually keeps zero and is inexhaustible. Before you actually access a frame, you should look at the function as a copy of the document and use the two locations in this chapter to assert the result instead of guessing by name. The full cover boundary should also be detected before calling, as the treatment of non-limited values may vary from one calculation to another.
Check understanding
Change the second Value from [0,4] to [0,8], will the weight change?
Not in this chapter's fixed Q/ K. The weight is determined by Q, K, scaling and mask, and the output of the second dimension changes. In the complete network, the upstream input changes are analysed separately.
Why divide by √dk?
In a common analysis of volumes that are close to independence and similar to the difference, the point-to-count variance increases with dk; Scales allow for a more stable fraction scale. This is a hypothetical statistical intuition, not a strict guarantee of all data.
Is it necessarily the most important reason for the final answer?
That is not the way to judge. Value, output projection, residue and follow-up layers influence the results; The weight of attention shows the mix of the current calculations and does not amount to a proven explanation of cause and effect.
Should the weight of the output change by adding the allowed fractions of a row to a thousand?
Mathematically, the public multipliers in the index are not the same, as they are offset by the molecular denominator. Direct demand indexes may spill, so achieving the maximum allowable value less; This is the combination of equivalents and numerical stability.
Only one valid key output is determined by fraction size?
As long as the fractions are limited and are legalized, the weight is one and the output is equal to its Value. If the mixed results are still available, it is indicated that mask does not really exclude other keys.
padding key When it's blocked, do you want to check it again? loss mask ?
Yes. key mask Control who can be read, loss mask Control of which target locations are involved in oversight is not the same axis. padding query Values may still be generated, but not involved in the target.
The next step is to expand from here to multiple head, position code and integrity. Transformer block , and then distinguish between the labels that were moved during the language model training loss mask 。 Read it further CS336 Spring 2025 model to construct the main line and D2L Chapter Attention I don't know. Source core for 2026-10-29; Values have been independently recovered and no model has been downloaded or the framework/ GPU experiment is claimed to have been implemented.
Change a variable
Change mask only. How's it changed?
Fixed Q = K = I2, V 0 = [2,0], V 1 = [0,4].
- weighted V
- [2.0000, 0.0000]
The weights are regularized according to the current query line. Mask controls the visible range and weights cannot be interpreted directly as causal importance.
Displays the calculation of the default parameters at the moment. The parameters can be changed when JavaScript is turned on.
Sources and reconciliations
Definitions, methods and interfaces are available.
- Attention Is All You Need
- Stanford CS336 — Language Modeling from Scratch, Spring 2025
- Dive into Deep Learning — Attention Mechanisms and Transformers
Figures and calculations are reorganized according to this chapter. Mathematical measurements, framework operations and real business effects are described separately in the body of the text.