LabCanvas

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

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.

Contents

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.
Scaled dot-product attention, typeset with TeX Live 2026 (pdfLaTeX) from the code below, exactly as it is in fraserlove/nntikz.
Copyright (c) 2024 Fraser Love · MIT licence (full text). The licence asks that this notice stay with the code: keep the first lines when you reuse it.
% 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

Variations

Our own code, written for this page and typeset with TeX Live 2026 like the figure above. Each one is a complete example: copy it, or open it in the TikZ editor and change it. This code is CC0 1.0, free to use without conditions.

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.
multi-head attention: three stacked copies of the attention block, Concat and Linear
Preamble: \usepackage{tikz} \usetikzlibrary{positioning, arrows.meta}
\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}
Open in the TikZ editor
Full document
A complete file you can compile as it is.
\documentclass[border=4pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning, arrows.meta}
\begin{document}
\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}
\end{document}

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.
a causal attention-weight matrix for four tokens, the masked cells in grey
Preamble: \usepackage{tikz}
\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}
Open in the TikZ editor
Full document
A complete file you can compile as it is.
\documentclass[border=4pt]{standalone}
\usepackage{tikz}
\begin{document}
\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}
\end{document}

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

  1. fraserlove/nntikz at commit 3dc29cf: tikz/dot_product_attention.tex (MIT licence)github.com
  2. PGF/TikZ manual, §13.4.1 Specifying Relative Coordinates (++)tikz.dev
  3. PGF/TikZ manual, §13.5.3 The Syntax of Partway Modifierstikz.dev
  4. PGF/TikZ manual, §16.4.4 Defining Shorthands (the > key)tikz.dev
  5. PGF/TikZ manual, §17.5.3 Advanced Placement Options (positioning)tikz.dev
  6. PGF/TikZ manual, §17.11 Connecting Nodes: Using Nodes as Coordinatestikz.dev
  7. PGF/TikZ manual, §88 Repeating Things: The Foreach Statementtikz.dev
  8. PGF/TikZ manual, §94.3.8 Miscellaneous Functions (array)tikz.dev
  9. PGF/TikZ manual, §97 Number Printing (\pgfmathprintnumber)tikz.dev

The walkthrough was checked against these sources and the pictures are the code typeset with TeX Live 2026. The original figure is © Fraser Love, under the MIT licence; the variations on this page are ours, CC0 1.0.

TikZ guides for these techniques

More figures explained

Change this figure in your browserOpen the figure or any variation in the free TikZ editor: it is typeset with TeX Live as you type, with errors pointed at their line.

Open the figure in the TikZ editor