← All posts

From Attention scores to attention outputs

In my previous post, I went through how we take token IDs, convert them into embeddings, project them into Q, K and V, and finally calculate raw attention scores using matrix multiplication.

In my previous post, I went through how we take token IDs, convert them into embeddings, project them into Q, K and V, and finally calculate raw attention scores using matrix multiplication.

Today, I continued building my small attention implementation in PyTorch. The goal here is to understand how we take these raw scores and turn them into an output that the model can use.

There are four steps I worked through: scaling, causal masking, softmax, and multiplying by the value vectors.

1. Scaling the attention scores

Previously, we calculated:

but there is a problem here as the number of features in our query and key vectors increases, the dot products can become quite large in magnitude.

This matters because we eventually pass these scores through softmax. If the scores are too far apart, softmax can become extremely concentrated on one token.

Here the denominator is the number of features in each key vector.

Why the square root ? now i do not fully understand this but the variance of a dot product grows with the number of features, while its standard deviation grows with the square root of that number and we want to keep it as minimal as possible before applying softmax

For example, if we have 64 key features and a raw attention score of 24:

In PyTorch, I implemented this using:

scaled_attention_scores = (
    masked_attention_scores / math.sqrt(keys.shape[-1])
)

I’ll explain the masking operation next. Scaling and masking can be performed in either order here because masked entries remain negative infinity.

2. Causal masking

now this was the part that made the attention mechanism much clearer to me so in a decoder-only language model (need to study what kind of other models are available) a token should not be able to attend to tokens that come after it.

lets study this with an example suppose we have three tokens:

The cat sleeps

When processing “cat”, the model can attend to “The” and “cat”, but not “sleeps”.So we need a causal mask and for three tokens, that mask looks like:

Here, 1 represents an allowed position and 0 represents a blocked position.

I wrote this in python this using:

causal_mask = torch.tril(torch.ones(3, 3))

But there is an interesting detail. we cannot simply replace the blocked attention scores with zero. Why ? Because softmax uses exponentials, and:

A score of zero would still receive a positive attention weight and instead, we replace the blocked positions with negative infinity.

masked_attention_scores = attention_scores.masked_fill(
    causal_mask == 0,
    float("-inf")
)

This works because the exponential of negative infinity is zero in the mathematical limit so after softmax, those blocked positions receive zero attention weight and that was the whole goal

3. Applying softmax

Now that we have scaled and masked our attention scores, we need to convert them into attention weights, and we use something called as softmax

It converts each row of attention scores into a distribution whose values sum to 1. In our example, each row represents a query token, and each column represents a key token.

So we apply softmax across each row:

attention_weights = torch.softmax(
    scaled_attention_scores,
    dim=-1
)

When I ran my code, I got:

tensor([
    [1.0000, 0.0000, 0.0000],
    [0.5208, 0.4792, 0.0000],
    [0.3802, 0.4487, 0.1711]
])

This helped me understand what was actually happening. lets dive a bit deeper

so the first token attends only to itself and the second token assigns around 52% attention to the first token and 48% to itself the third token distributes its attention across all three tokens. Also one thing to notice all the blocked ones or the negative ones have 0 attention

4. Multiplying attention weights by V

We now have attention weights. But we still need to produce the actual attention output, from earlier remember, Q and K helped us calculate how strongly tokens match each other but V contains the information that gets combined according to those attention weights (This is from the research paper attention is all you need)

So our final operation is:

In PyTorch that looks something like this:

attention_output = attention_weights @ values

Each of our three tokens now has an attention output containing two values, Nothing more to study in this final step it just a simple multiplication.

What clicked today

The biggest realization for me was that attention scores and attention outputs are two different things.

Q and K determine the compatibility scores between tokens. Scaling controls their magnitude, causal masking prevents access to future tokens, and softmax converts the scores into attention weights, those weights are then used to combine the V vectors.

We’ve now implemented the main calculation for single-head causal self-attention:

Here, (M) is zero for allowed positions and negative infinity for blocked positions. our implementation is still small. It uses three tokens, randomly initialized weights, and a single attention head. We haven’t trained a language model.

But we now have a working attention computation rather than just the mathematical formulas

Views —

Read next

Nov 9, 2026From Token Ids to attention Scores