FAU Erlangen-Nürnberg
Institute of Micro- and Nanostructure Research
notebooks/week10_attention_gnn.ipynb — self-attention from scratch, a mini-ViT on synthetic diffraction patterns (with a positional-encoding ablation), and a hand-written message-passing layer on an atom-column graph.By the end of this week you can:

A CNN can learn long-range relations — through depth and pooling — but it pays in layers and data. Attention couples any two inputs in one layer.
d["key"] → value — exact match or nothing.\[ Q = XW_Q,\quad K = XW_K,\quad V = XW_V \qquad X\in\mathbb{R}^{L\times d} \]
\[ \boxed{\;\mathrm{Attention}(Q,K,V) = \underbrace{\mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)}_{A\,\in\,\mathbb{R}^{L\times L}\text{, rows sum to 1}} V\;} \]

Four patch tokens, \(d_k = 2\), \(Q = K\) except D:
| token | \(\mathbf{q}\) | \(\mathbf{k}\) | \(\mathbf{v}\) |
|---|---|---|---|
| A bright disc | (1,0) | (1,0) | (1,0) |
| B weak disc | (0,1) | (0,1) | (0,1) |
| C disc pair | (1,1) | (1,1) | (1,1) |
| D background | (0,0) | (−1,0) | (0,0) |
Row C: scores \((0.71, 0.71, 1.41, -0.71)\) → weights \((0.23, 0.23, 0.47, 0.06)\) → \(\mathbf{z}_C = (0.71, 0.71)\).


\[ \mathrm{head}_h = \mathrm{Attention}(XW_Q^{(h)}, XW_K^{(h)}, XW_V^{(h)}) \] \[ \mathrm{MHA}(X) = [\mathrm{head}_1,\dots,\mathrm{head}_H]\,W_O \]

Fix at the input, not in the operator: add a positional encoding to each token, \(\tilde{\mathbf{x}}_i = \mathbf{x}_i + \mathbf{p}_i\).
\[ \mathrm{PE}(p, 2i) = \sin\!\big(p / 10000^{2i/d}\big),\quad \mathrm{PE}(p, 2i+1) = \cos\!\big(p / 10000^{2i/d}\big) \]

Diagnostic: ablate the positional encoding. If accuracy does not drop, your task did not use geometry — or your model found a shortcut.
\[ \begin{aligned} X' &= X + \mathrm{MHA}(\mathrm{LN}(X))\\ X'' &= X' + \mathrm{MLP}(\mathrm{LN}(X')) \end{aligned} \]
class Block(nn.Module):
def __init__(self, d, heads):
super().__init__()
self.n1 = nn.LayerNorm(d)
self.n2 = nn.LayerNorm(d)
self.attn = SelfAttention(d, heads)
self.mlp = nn.Sequential(
nn.Linear(d, 2*d), nn.GELU(),
nn.Linear(2*d, d))
def forward(self, x):
x = x + self.attn(self.n1(x))
return x + self.mlp(self.n2(x))

(a) Square patches on a diffraction pattern: simple, but discs can straddle patch seams. (b) One token per detected Bragg disc, embedding radius, angle and intensity — the geometry becomes explicit. (c) Spectral windows along the energy loss axis; the positional encoding must carry absolute energy.


Left: example 32×32 synthetic spot patterns (random orientation, lattice scale, excitation, Poisson noise). Right: test accuracy of a ~60 k-parameter mini-ViT (patch 4 → 64 tokens, \(d=48\), 4 heads, 3 blocks), trained on 3 000 patterns on a CPU, with and without learned positional embeddings.

Attention is a hypothesis about what matters. An intervention (occlusion, ablation, counterfactual) is the test.
Top: last-layer CLS attention (head mean) overlaid on three test patterns. Bottom: occlusion sensitivity — the drop in predicted-class probability when each 4×4 patch is blanked. Spearman rank correlation per pattern in the titles; mean over 100 test patterns in the header.
Mean Spearman correlation, attention vs occlusion (100 patterns): ≈ 0.04 — essentially none.
Left: synthetic HAADF image with brighter substitutional columns and vacancies. Middle: the graph — nodes are detected columns, edges connect columns closer than a cutoff \(r_c\); red nodes are host columns next to a substitution (a label that needs neighbour information). Right: the receptive field of node \(i\) after one and two message-passing layers.
\[ \boxed{\;\mathbf{h}_i^{(\ell+1)} = U\Big(\mathbf{h}_i^{(\ell)},\; \bigoplus_{j\in\mathcal{N}(i)} M\big(\mathbf{h}_i^{(\ell)}, \mathbf{h}_j^{(\ell)}, \mathbf{e}_{ij}\big)\Big)\;} \]
index_add_.

One update rule for all: \[ \mathbf{h}_i' = \phi\Big(\mathbf{h}_i,\ \sum_{j \in \mathcal{N}(i)} w_{ij}\, \psi(\mathbf{h}_j)\Big) \]
| graph \(\mathcal{N}(i)\) | weights \(w_{ij}\) | |
|---|---|---|
| CNN | grid, \(k\times k\) | fixed by relative offset |
| GNN | sparse, from physics | from message fn / edge features |
| Transformer | complete | \(\mathrm{softmax}(\mathbf{q}_i^\top\mathbf{k}_j/\sqrt{d_k})\) |
| RNN | chain (past) | fixed, shared over time |
| EM data | structure | first choice | consider |
|---|---|---|---|
| SEM/TEM micrograph segmentation | local texture on a grid | U-Net (W7) | ViT/SAM backbone if pretrained |
| Diffraction pattern (orientation, phase, strain) | long-range, symmetric | disc-token transformer or CNN baseline | MAE pretraining on unlabelled scans |
| EELS/EDS spectrum | 1-D physical axis, long-range edges | 1-D CNN / PCA+trees (W3, W5) | spectral transformer with energy PE |
| Atom-column positions | irregular set with neighbours | GNN | descriptors + trees (W5) as baseline |
| Grain/particle networks | objects + relations | GNN | tabular descriptors (W5) |
| In-situ movie | frames + causal time | frame-wise CNN + tracking | temporal transformer / latent sequence |
| Small labelled data (< 500) | any | simplest model that respects the physics | pretrained features + linear probe (W8) |
week10_attention_gnn.ipynbMaterial beyond the 90-minute lecture path, for self-study and questions.



©Philipp Pelz - FAU Erlangen-Nürnberg - Data Science for Electron Microscopy