# Scaled dot-product attention in TikZ, explained line by line

> The scaled dot-product attention block in TikZ, explained: nodes placed above computed midpoints with positioning and calc, arrows, and two variations.

URL: https://www.labcanvas.com/tikz/examples/machine-learning/scaled-dot-product-attention

Updated 2026-11-22. Original figure: Scaled dot-product attention, © Fraser Love, MIT licence (licence text: https://www.labcanvas.com/tikz-library/credits.html#nntikz), from https://github.com/fraserlove/nntikz/blob/3dc29cfda3bd18db2d1e73830f95b4d0985e050f/tikz/dot_product_attention.tex. Walkthrough and variations by LabCanvas; the variation code is CC0 1.0 (https://creativecommons.org/publicdomain/zero/1.0/). Pictures typeset with TeX Live 2026 and PGF 3.1.12. Category: [TikZ neural network and machine learning examples](https://www.labcanvas.com/tikz/examples/machine-learning).

## Quick answer

This figure is the attention block of the transformer: Q and K go through MatMul, Scale, an optional Mask and Softmax, and a second MatMul combines the result with V. It is drawn with a single `layer` style and the `positioning` library, but the first and last boxes are placed above computed points, `$(Q)!0.5!(K)$` and `$(Q)!0.8!(V)$`, rather than above other nodes. The long arrow from V is a fixed 14.5em, the same distance that places the last MatMul, so its tip lands exactly on that box.

## The figure and its code

![Scaled dot-product attention block: Q and K at the bottom with arrows into MatMul, then Scale, Mask (opt.) and Softmax stacked above, a second MatMul at the top receiving Softmax and a long arrow from V, and the title Scaled Dot-Product Attention above it.](https://www.labcanvas.com/tikz-snippets/fig-scaled-dot-product-attention/original.webp)

Copyright (c) 2024 Fraser Love, MIT licence (https://www.labcanvas.com/tikz-library/credits.html#nntikz). The code below is exactly the library's file (pdfLaTeX); its first lines name the source and the licence, and the MIT licence asks that they stay with the code. Open it in the TikZ editor from the page: https://www.labcanvas.com/tikz/examples/machine-learning/scaled-dot-product-attention

```latex
% Scaled dot-product attention
% Source: https://github.com/fraserlove/nntikz/blob/3dc29cfda3bd18db2d1e73830f95b4d0985e050f/tikz/dot_product_attention.tex
% Copyright (c) 2024 Fraser Love. MIT licence: https://github.com/fraserlove/nntikz/blob/main/LICENSE
% The licence’s copyright and permission notice: https://www.labcanvas.com/tikz-library/credits.html
\documentclass{standalone}

\usepackage{tikz}

\usetikzlibrary{positioning,chains,shapes.geometric,fit,shapes,arrows.meta,calc}

\begin{document}

\begin{tikzpicture}[
    >=LaTeX,
    % Styles
    layer/.style={
        rectangle,
        fill=white!10,
        rounded corners=2mm,
        minimum height=2em,
        minimum width=3em,
        draw,
        thick
    },
    arrow/.style={
        -latex,
        very thick
    }
]

    % Layers
    \node[] (Q) {$\mathbf{Q}$};
    \node[, right=1em of Q] (K) {$\mathbf{K}$};
    \node[, right=1em of K] (V) {$\mathbf{V}$};

    \node[layer, above=2em of $(Q)!0.5!(K)$] (matmul) {MatMul};
    \node[layer, above=1em of matmul] (scale) {Scale};
    \node[layer, above=1em of scale] (mask) {Mask (opt.)};
    \node[layer, above=1em of mask] (softmax) {Softmax};
    \node[layer, above=14.5em of $(Q)!0.8!(V)$] (matmul2) {MatMul};
    \node[above=1.4em of matmul2] (result) {Scaled Dot-Product Attention};

    % Paths
    \draw[arrow] (Q) -- (matmul);
    \draw[arrow] (K) -- (matmul);
    \draw[arrow] (matmul) -- (scale);
    \draw[arrow] (scale) -- (mask);
    \draw[arrow] (mask) -- (softmax);
    \draw[arrow] (softmax) -- (matmul2);
    \draw[arrow] (matmul2) -- (result);
    \path[draw, arrow] (V) -- ++(0, 14.5em);
\end{tikzpicture}

\end{document}
```

## One style for every box

*Lines 13–29 of the code.*

The options of the `tikzpicture` define two styles. `layer` is a rounded rectangle with `minimum height=2em` and `minimum width=3em`: the boxes grow with their labels (“Mask (opt.)” is wider than “Scale”) but never get smaller than that. `fill=white!10` mixes 10% white with white, so it is simply white. `arrow` combines the old `-latex` tip with `very thick`.

As in the other figures of this collection, `>=LaTeX` sets the tip used by `->`, but every arrow here comes from the `arrow` style, so that line could be removed without any change to the picture.

## Q, K and V on one line

*Lines 32–34 of the code.*

The inputs are plain text nodes. Q sits at the origin, and `right=1em of Q` puts K’s west anchor 1em to the right of Q’s east anchor; V follows K the same way. Because `west` and `east` are at mid-height, the three nodes share one centre line, which the arrow from V relies on later. The empty first entry in `[, right=1em of Q]` is harmless: an empty option does nothing.

## Boxes placed above computed points

*Lines 36–41 of the code.*

The first MatMul is placed with `above=2em of $(Q)!0.5!(K)$`. The of-part here is not a node name but a coordinate from the `calc` library: `!0.5!` is the point halfway from Q’s centre to K’s centre. With a coordinate, `positioning` puts the node’s `south` anchor 2em above that point; with a node name it would measure from the node’s border instead. Scale, Mask and Softmax then follow with `above=1em of` the box below, gap to gap.

The second MatMul uses `above=14.5em of $(Q)!0.8!(V)$`: 80% of the way from Q to V, so it sits to the right of the stack, over V. The 14.5em is hand-tuned to clear Softmax; it is not computed from the boxes below. The title is a node `above=1.4em of matmul2`, joined to it by an arrow.

## The arrows, and why the V arrow is exactly 14.5em

*Lines 44–51 of the code.*

Arrows between named nodes run from border to border along the line between their centres. That is why Q and K enter MatMul at an angle (MatMul is centred between them) and why the arrow from Softmax to the second MatMul is slanted (the boxes are 0.5 and 0.8 of the way along).

The arrow from V is different: `\path[draw, arrow] (V) -- ++(0, 14.5em);` (the same as `\draw[arrow]`) goes straight up 14.5em from V’s centre, starting at V’s border. The second MatMul’s south anchor is also 14.5em above a point on that centre line, so the tip lands exactly on its bottom edge. The two numbers are linked: change one and you must change the other. Writing `(V) -- (V |- matmul2.south)` instead would end the arrow on the box whatever its height.

## Techniques used

- [Placement with positioning](https://www.labcanvas.com/tikz/nodes): `above=1em of mask` measures between borders; `above=2em of $(Q)!0.5!(K)$` measures from a point.
- [Partway coordinates with calc](https://www.labcanvas.com/tikz/coordinates): `$(Q)!0.8!(V)$` is 80% of the way from Q to V, used as a node position.
- [Arrows between nodes](https://www.labcanvas.com/tikz/arrows): node-to-node arrows end on the borders; `++(0, 14.5em)` draws a fixed-length arrow instead.
- [Neural network diagrams](https://www.labcanvas.com/tikz/neural-networks): attention blocks, multi-head attention and how transformer figures are usually composed.

## Variations

Our own code, CC0 1.0, each typeset with TeX Live 2026 in a standalone document with the preamble lines shown.

### Multi-head attention: stacked copies drawn back to front

The usual next figure: h attention heads side by side, each with its own Linear layers, joined by Concat and a final Linear. The heads are one `\foreach \h in {2,1,0}` loop with a `shift` per copy; drawing the back copy first lets the filled front copy cover it. Node names carry the head number (`att0`, `q0`), `\ifnum\h=0` draws the inner arrows on the front copy only, and the arrows after the loop connect to it.

![Multi-head attention diagram: three overlapping copies of a block with three Linear boxes feeding a violet Scaled dot-product attention box, labelled h heads, with inputs Q, K and V below and Concat and Linear boxes above.](https://www.labcanvas.com/tikz-snippets/fig-scaled-dot-product-attention/multi-head.webp)

*multi-head attention: three stacked copies of the attention block, Concat and Linear*

Preamble: `\usepackage{tikz}`, `\usetikzlibrary{positioning, arrows.meta}`

```latex
\begin{tikzpicture}[
    >={Latex[length=2mm]}, thick,
    box/.style={draw, rounded corners=2mm, minimum height=2em, align=center, font=\small},
  ]
  % three heads, drawn back to front so the front one covers the others
  \foreach \h in {2,1,0} {
    \begin{scope}[shift={(0.18*\h, 0.18*\h)}]
      \node[box, fill=violet!15, minimum width=4.6cm] (att\h) at (0, 1.7)
        {Scaled dot-product attention};
      \foreach \x/\nm in {-1.6/q, 0/k, 1.6/v} {
        \node[box, fill=gray!10, minimum width=1.3cm] (\nm\h) at (\x, 0) {Linear};
        % arrows only on the front copy, so the stack stays readable
        \ifnum\h=0 \draw[->] (\nm\h) -- (\nm\h |- att\h.south); \fi
      }
    \end{scope}
  }
  \node[box, fill=orange!20, minimum width=2.4cm, above=6mm of att0] (cat) {Concat};
  \node[box, fill=gray!10, minimum width=2.4cm, above=5mm of cat] (out) {Linear};
  \draw[->] (att0) -- (cat);
  \draw[->] (cat) -- (out);
  \draw[->] (out) -- ++(0, 1);
  \foreach \nm/\l in {q/Q, k/K, v/V}
    \draw[<-] (\nm0) -- ++(0, -1) node[below] {$\mathbf{\l}$};
  \node[right=2mm of att2.east, font=\small] {$h$ heads};
\end{tikzpicture}
```

### What Mask and Softmax produce: the attention weights

The block’s output is a weighted sum of the values, and the weights are worth showing too. This heat map draws softmax(QKᵀ/√d) for four tokens with the causal mask that “Mask (opt.)” stands for: a token may only attend to itself and earlier tokens, so the cells above the diagonal are greyed out and every row sums to 1. The weights are a pgfmath array read with `\W[\i][\j]`, and `y=-1.1cm` flips the y axis so that row 0 is at the top.

![A 4 by 4 grid with the tokens the, cat, sat, down along the top (key) and the left side (query); the lower triangle holds weights such as 1, 0.62 and 0.38 in shades of blue, darker for larger values, and the upper triangle is grey, marked as masked.](https://www.labcanvas.com/tikz-snippets/fig-scaled-dot-product-attention/attention-weights.webp)

*a causal attention-weight matrix for four tokens, the masked cells in grey*

Preamble: `\usepackage{tikz}`

```latex
\begin{tikzpicture}[x=1.1cm, y=-1.1cm, font=\small]
  % softmax(QK^T / sqrt(d)) for four tokens, with the causal mask: row i may
  % only attend to columns j <= i (each row sums to 1)
  \def\W{{{1,0,0,0},{0.62,0.38,0,0},{0.15,0.55,0.30,0},{0.10,0.20,0.45,0.25}}}
  \foreach \word [count=\i from 0] in {the, cat, sat, down} {
    \node[anchor=east] at (-0.6, \i) {\word};
    \node[anchor=south] at (\i, -0.6) {\word};
  }
  \foreach \i in {0,...,3} {
    \foreach \j in {0,...,3} {
      \ifnum\j>\i
        \filldraw[fill=gray!20, draw=white, thick] (\j-0.5, \i-0.5) rectangle +(1,1);
      \else
        \pgfmathsetmacro\v{\W[\i][\j]}
        \pgfmathtruncatemacro\p{100*\v}
        \ifnum\p>50 \def\ink{white}\else\def\ink{black}\fi
        \filldraw[fill=blue!\p, draw=white, thick] (\j-0.5, \i-0.5) rectangle +(1,1);
        \node[text=\ink] at (\j, \i) {\pgfmathprintnumber[fixed, precision=2]{\v}};
      \fi
    }
  }
  \node[rotate=90] at (-1.75, 1.5) {query};
  \node at (1.5, -1.25) {key};
  \node[anchor=north west, text=gray] at (-0.5, 3.6) {grey: masked (a later token)};
\end{tikzpicture}
```

## Frequently asked questions

### How do I draw multi-head attention in TikZ?

Draw one head inside a scope and repeat it in a \foreach loop with a small shift for each copy, from the back copy to the front one, so that the filled front copy covers the others. Then add Concat and Linear boxes above the front copy, as in the variation on this page.

### Why does the arrow from V not reach the box when I change the layout?

Its length is fixed: ++(0, 14.5em) goes up 14.5em from V. The box above is also placed 14.5em above the input line, so the two only meet while both numbers agree. End the arrow on the box instead: \draw[arrow] (V) -- (V |- matmul2.south);

### What does above=2em of $(Q)!0.5!(K)$ mean?

It places the node’s bottom (its south anchor) 2em above the point halfway between the centres of Q and K. The calc library computes the point; the positioning library does the placing.

## References

- [fraserlove/nntikz at commit 3dc29cf: tikz/dot_product_attention.tex (MIT licence)](https://github.com/fraserlove/nntikz/blob/3dc29cfda3bd18db2d1e73830f95b4d0985e050f/tikz/dot_product_attention.tex)
- [PGF/TikZ manual, §13.4.1 Specifying Relative Coordinates (++)](https://tikz.dev/tikz-coordinates#sec-13.4.1)
- [PGF/TikZ manual, §13.5.3 The Syntax of Partway Modifiers](https://tikz.dev/tikz-coordinates#sec-13.5.3)
- [PGF/TikZ manual, §16.4.4 Defining Shorthands (the > key)](https://tikz.dev/tikz-arrows#sec-16.4.4)
- [PGF/TikZ manual, §17.5.3 Advanced Placement Options (positioning)](https://tikz.dev/tikz-shapes#sec-17.5.3)
- [PGF/TikZ manual, §17.11 Connecting Nodes: Using Nodes as Coordinates](https://tikz.dev/tikz-shapes#sec-17.11)
- [PGF/TikZ manual, §88 Repeating Things: The Foreach Statement](https://tikz.dev/pgffor)
- [PGF/TikZ manual, §94.3.8 Miscellaneous Functions (array)](https://tikz.dev/math-parsing#sec-94.3.8)
- [PGF/TikZ manual, §97 Number Printing (\pgfmathprintnumber)](https://tikz.dev/math-numberprinting)

## TikZ guides for these techniques

- [TikZ neural network diagrams: perceptron, MLP, CNN, LSTM and transformer](https://www.labcanvas.com/tikz/neural-networks): Neural network diagrams in LaTeX with TikZ: perceptron, MLP from \foreach loops, labelled weights, CNN feature maps, RNN, LSTM, autoencoder, transformer.
- [TikZ nodes: shapes, anchors, positioning and labels](https://www.labcanvas.com/tikz/nodes): How TikZ nodes work: shapes, size (inner sep, minimum size), all anchors, the positioning library (right=of, node distance), labels, pins and scaling.
- [TikZ coordinates, paths, \foreach, scopes and styles](https://www.labcanvas.com/tikz/coordinates): TikZ coordinates (polar, relative ++, named, calc, intersections), paths and controls, \foreach loops, scopes, \tikzset styles, decorations and grids.
- [TikZ arrows: arrow tips, sizes, curves and labels](https://www.labcanvas.com/tikz/arrows): All TikZ arrow tips in one rendered table, arrows.meta sizing (length, width, scale, open, round), and curved, labelled, thick, block and squiggly arrows.
- [TikZ matrix: matrices, arrays of nodes and array diagrams](https://www.labcanvas.com/tikz/matrix): TikZ matrix library: matrix of nodes and math nodes, & and \\, cell names like (m-1-2), styles, brackets, highlighted cells, and array diagrams.
