PROMETHEUS OS
NATIVE AI OPERATING SYSTEM
[INIT] Prometheus OS loading...
[CORE] Neural interface initializing...
[AI] LLM router connecting...
[MEM] Memory graph loading...
[AGT] Agent chains on standby...
[SEC] Security protocols active...
[NET] Provider mesh established...
[UI] Workspace rendering...
[DONE] All systems nominal.
Welcome to PROMETHEUS OS.
READY · OFFLINE · SECURE · PRIVATE
🎨 THEME ENGINE
PROMETHEUS OS · 23 THEMES
Trial version: Dark + Light themes only.
Full theme access with PROMETHEUS OS license.
Dark theme active
Experience all 23 themes in PROMETHEUS OS

Beyond Transformers: GNNs, State-Space Models and Hybrids

Advanced 20 min· 4 exercises

Explain and implement graph neural networks and selective state-space models, analyse why 2024-2025 hybrid models mix attention with SSM or linear-attention layers, and choose the right architecture for a given data shape and cost budget.

By the end of this lesson you will be able to
  • Implement message passing and a graph convolutional layer and compute a GCN update by hand
  • Derive the recurrent and convolutional views of a discretized state-space model and compute both
  • Explain how Mamba's input-dependent parameters make an SSM selective and why that requires a parallel scan
  • Compare linear attention, SSMs and softmax attention in compute, memory and recall ability
  • Analyse the KV-cache savings of hybrid attention/SSM models using documented examples
  • Choose between transformers, GNNs, SSMs, hybrids, MoE and diffusion transformers for a given problem

Before this: Transformers: A Deep Dive, Recurrent Networks and Sequence Modelling

Why look beyond the transformer

Transformers dominate, but they make two assumptions that do not always fit. They treat input as a sequence (or a set) of tokens, while molecules, road networks, supply chains and social graphs are graphs with explicit connections. And their attention cost grows with the square of sequence length while the KV cache grows linearly, which makes very long contexts and high-concurrency serving expensive. This lesson covers the main architectural answers: graph neural networks for relational data, state-space models and linear attention for linear-time sequence modelling, the hybrid models that mix them with attention, mixture-of-experts as a way to scale parameters without scaling compute, and transformers used as diffusion denoisers. The goal is to know what each one buys you and when to reach for it.

Intuition: match the architecture to the shape of the data and the cost you can pay

A CNN assumes a grid, an RNN assumes a chain, and a transformer assumes every token may need to talk to every other token. A graph neural network assumes information flows along given edges — like gossip spreading only between friends. A state-space model is a return to the RNN's running summary, rebuilt so that it trains in parallel and chooses what to remember. A hybrid model is a pragmatic compromise: most layers keep a cheap fixed-size memory, and a few layers keep full attention for the moments when the model must look something up exactly.

Part 1: Graph neural networks

A graph G=(V,E)G = (\mathcal{V}, \mathcal{E}) has NN nodes with feature vectors xv∈Rdx_v \in \mathbb{R}^{d}, and edges, encoded in an adjacency matrix A∈{0,1}N×NA \in \{0,1\}^{N \times N} with Auv=1A_{uv} = 1 if uu and vv are connected. Tasks are node-level (classify each account as fraud or not), edge-level (predict a missing link: will this user buy this item?) or graph-level (predict a molecule's toxicity).

Message passing

Almost every GNN fits the message-passing template (formalized by Gilmer et al., 2017). In layer ll, each node gathers messages from its neighbours N(v)\mathcal{N}(v), aggregates them with a permutation-invariant function, and updates its state:

mv(l)=⨁u∈N(v)ψ(hu(l),hv(l),euv),hv(l+1)=ϕ(hv(l),mv(l))m_v^{(l)} = \bigoplus_{u \in \mathcal{N}(v)} \psi\big(h_u^{(l)}, h_v^{(l)}, e_{uv}\big), \qquad h_v^{(l+1)} = \phi\big(h_v^{(l)}, m_v^{(l)}\big)

⨁\bigoplus is sum, mean or max (it must not depend on neighbour order, since graphs have none), ψ\psi and ϕ\phi are small neural networks, and euve_{uv} are optional edge features. After LL layers a node's representation depends on its LL-hop neighbourhood — the graph analogue of a receptive field. For graph-level tasks, a readout (sum or mean over all nodes) produces one vector per graph.

Graph convolutional network (GCN)

The GCN of Kipf and Welling (2016) is the simplest widely used instance. Add self-loops, A~=A+I\tilde{A} = A + I, let D~\tilde{D} be the diagonal degree matrix of A~\tilde{A}, and set

H(l+1)=σ ⁣(D~−1/2A~D~−1/2H(l)W(l))H^{(l+1)} = \sigma\!\left(\tilde{D}^{-1/2} \tilde{A} \tilde{D}^{-1/2} H^{(l)} W^{(l)}\right)

H(l)∈RN×dlH^{(l)} \in \mathbb{R}^{N \times d_l} stacks node states, W(l)W^{(l)} is a learned weight matrix shared by all nodes (weight sharing again), and σ\sigma is a nonlinearity. The normalized matrix A^=D~−1/2A~D~−1/2\hat{A} = \tilde{D}^{-1/2}\tilde{A}\tilde{D}^{-1/2} has entries A^uv=1/d~ud~v\hat{A}_{uv} = 1/\sqrt{\tilde{d}_u \tilde{d}_v} for connected u,vu, v: each node averages itself and its neighbours, down-weighting high-degree hubs so they do not dominate.

Worked example. Path graph 1 — 2 — 3 with scalar features x=(1,2,3)x = (1, 2, 3) and W=1W = 1. With self-loops the degrees are d~=(2,3,2)\tilde{d} = (2, 3, 2). So A^11=1/2\hat{A}_{11} = 1/2, A^12=1/6=0.408\hat{A}_{12} = 1/\sqrt{6} = 0.408, A^22=1/3\hat{A}_{22} = 1/3, A^23=0.408\hat{A}_{23} = 0.408, A^33=1/2\hat{A}_{33} = 1/2.

  • Node 1: 0.5⋅1+0.408⋅2=1.3160.5 \cdot 1 + 0.408 \cdot 2 = 1.316
  • Node 2: 0.408⋅1+0.333⋅2+0.408⋅3=2.3000.408 \cdot 1 + 0.333 \cdot 2 + 0.408 \cdot 3 = 2.300
  • Node 3: 0.408⋅2+0.5⋅3=2.3160.408 \cdot 2 + 0.5 \cdot 3 = 2.316

Each node's new value blends its own feature with its neighbours'. Repeat this many times and all nodes converge toward similar values — over-smoothing, the reason most GNNs use only 2–4 layers.

import torch, torch.nn as nn

class GCNLayer(nn.Module):
    def __init__(self, d_in, d_out):
        super().__init__()
        self.lin = nn.Linear(d_in, d_out, bias=False)
    def forward(self, X, A):                         # X: (N, d_in); A: (N, N) 0/1
        A_t = A + torch.eye(A.shape[0])              # self-loops
        d_inv_sqrt = A_t.sum(1).pow(-0.5)
        A_hat = d_inv_sqrt[:, None] * A_t * d_inv_sqrt[None, :]   # D^-1/2 A D^-1/2
        return A_hat @ self.lin(X)

A = torch.tensor([[0, 1, 0], [1, 0, 1], [0, 1, 0]], dtype=torch.float32)
X = torch.tensor([[1.0], [2.0], [3.0]])
layer = GCNLayer(1, 1)
with torch.no_grad():
    layer.lin.weight.fill_(1.0)
    print(layer(X, A).squeeze())                     # tensor([1.3165, 2.2997, 2.3165])

class GCN(nn.Module):                                # 2-layer node classifier
    def __init__(self, d_in, d_hidden, n_classes):
        super().__init__()
        self.l1, self.l2 = GCNLayer(d_in, d_hidden), GCNLayer(d_hidden, n_classes)
    def forward(self, X, A):
        return self.l2(torch.relu(self.l1(X, A)), A)  # per-node logits

Dense adjacency is fine for teaching; real graphs are sparse, so libraries such as PyTorch Geometric and DGL use edge lists and scatter operations. Other important variants: GraphSAGE samples neighbours to scale to huge graphs; graph attention networks (GAT) learn per-edge weights with attention; graph transformers let all nodes attend to each other with structural position encodings. A transformer is in fact a GNN on a fully connected graph. GNNs are used for molecular property prediction, recommendation over user–item graphs, fraud rings in transaction graphs, traffic forecasting and chip design.

Part 2: State-space models

The continuous model and its two faces

A linear state-space model (SSM) maps an input signal x(t)x(t) to an output y(t)y(t) through a hidden state h(t)∈RNh(t) \in \mathbb{R}^N:

h′(t)=A h(t)+B x(t),y(t)=C h(t)h'(t) = A\, h(t) + B\, x(t), \qquad y(t) = C\, h(t)

with A∈RN×NA \in \mathbb{R}^{N \times N}, B∈RN×1B \in \mathbb{R}^{N \times 1}, C∈R1×NC \in \mathbb{R}^{1 \times N}. To apply it to tokens, discretize with a step size Δ\Delta. The zero-order-hold rule gives

Aˉ=eΔA,Bˉ=(ΔA)−1(eΔA−I) ΔB,ht=Aˉht−1+Bˉxt,yt=Cht\bar{A} = e^{\Delta A}, \qquad \bar{B} = (\Delta A)^{-1}\big(e^{\Delta A} - I\big)\, \Delta B, \qquad h_t = \bar{A} h_{t-1} + \bar{B} x_t, \quad y_t = C h_t

This is a linear RNN: constant work and memory per step at inference. Because Aˉ,Bˉ,C\bar{A}, \bar{B}, C are the same at every step (linear time-invariant), unrolling gives yt=∑k≥0CAˉkBˉ xt−ky_t = \sum_{k \ge 0} C \bar{A}^k \bar{B}\, x_{t-k}, which is a convolution with kernel Kˉ=(CBˉ,CAˉBˉ,CAˉ2Bˉ,… )\bar{K} = (C\bar{B}, C\bar{A}\bar{B}, C\bar{A}^2\bar{B}, \dots). Training can therefore run as one long parallel convolution (via FFT), and inference as a recurrence.

Worked example. Scalar A=−1A = -1, B=C=1B = C = 1, Δ=0.5\Delta = 0.5. Then Aˉ=e−0.5=0.6065\bar{A} = e^{-0.5} = 0.6065 and Bˉ=1−0.5(0.6065−1)(0.5)=0.3935\bar{B} = \frac{1}{-0.5}(0.6065 - 1)(0.5) = 0.3935. Inputs x=(1,0,0,2)x = (1, 0, 0, 2):

  • Recurrence: h1=0.3935h_1 = 0.3935, h2=0.6065⋅0.3935=0.2387h_2 = 0.6065 \cdot 0.3935 = 0.2387, h3=0.1447h_3 = 0.1447, h4=0.6065⋅0.1447+0.3935⋅2=0.0878+0.7869=0.8747h_4 = 0.6065 \cdot 0.1447 + 0.3935 \cdot 2 = 0.0878 + 0.7869 = 0.8747.
  • Convolution: Kˉ=(0.3935,0.2387,0.1447,0.0878)\bar{K} = (0.3935, 0.2387, 0.1447, 0.0878), so y4=Kˉ0x4+Kˉ3x1=0.7869+0.0878=0.8747y_4 = \bar{K}_0 x_4 + \bar{K}_3 x_1 = 0.7869 + 0.0878 = 0.8747. Same answer.

The state is a decaying memory: the impulse at step 1 fades by a factor of 0.6065 per step.

S4: making SSMs work for long sequences

Gu, Goel and Ré's S4 (2021) made deep SSMs practical. It initializes AA with a structure derived from the HiPPO theory of compressing history onto orthogonal polynomials, and parameterizes AA (normal plus low-rank) so the convolution kernel can be computed efficiently and stably. S4 reached state-of-the-art results on every task of the Long Range Arena benchmark, including the 16k-length Path-X task that earlier models had failed. But on language it still trailed transformers.

Mamba: selective state spaces

The weakness of time-invariant SSMs is that they treat every token the same; they cannot decide, based on content, to remember this name and ignore that filler word. Mamba (Gu and Dao, 2023) makes the SSM selective: the step size Δt\Delta_t and the matrices BtB_t and CtC_t become functions of the current input xtx_t (via small linear projections), while AA stays a learned diagonal matrix with negative entries:

Δt=softplus⁡(WΔxt),Bt=WBxt,Ct=WCxt,ht=eΔtAht−1+ΔtBtxt,yt=Ctht\Delta_t = \operatorname{softplus}(W_\Delta x_t), \quad B_t = W_B x_t, \quad C_t = W_C x_t, \qquad h_t = e^{\Delta_t A} h_{t-1} + \Delta_t B_t x_t, \quad y_t = C_t h_t

(Mamba uses this simplified Bˉ≈ΔB\bar{B} \approx \Delta B.) A large Δt\Delta_t drives eΔtAe^{\Delta_t A} toward 0 — forget the past and focus on this token; a small Δt\Delta_t keeps the state and nearly ignores the input. This is an input-dependent gate, much like an LSTM's forget gate, but on a linear recurrence.

The price is that the model is no longer time-invariant, so the convolution trick is gone. Mamba instead uses a hardware-aware parallel scan: the linear recurrence is associative, so it can be computed in O(log⁡T)O(\log T) parallel depth, and the kernel keeps the expanded state in fast SRAM rather than writing it to HBM — the same IO-awareness idea as FlashAttention. The paper reports training cost linear in sequence length, inference throughput about 5× that of transformers of similar size, and improving results on real data up to million-token sequences. Mamba-2 (Dao and Gu, 2024) restricted AA further to a scalar per head, showed a formal duality between this SSM and a form of masked linear attention, and used that duality for a faster, matrix-multiply-based training algorithm.

import torch, torch.nn as nn, torch.nn.functional as F

class NaiveSelectiveSSM(nn.Module):
    """Mamba-style selective SSM as a slow sequential loop, for understanding only."""
    def __init__(self, d, N=16):
        super().__init__()
        self.A_log = nn.Parameter(torch.log(torch.arange(1, N + 1).float()).repeat(d, 1))
        self.to_B, self.to_C, self.to_delta = nn.Linear(d, N), nn.Linear(d, N), nn.Linear(d, d)
    def forward(self, x):                                   # x: (B, T, d)
        Bsz, T, d = x.shape
        A = -torch.exp(self.A_log)                          # (d, N), negative = decaying
        delta = F.softplus(self.to_delta(x))                # (B, T, d), input-dependent
        Bt, Ct = self.to_B(x), self.to_C(x)                 # (B, T, N), input-dependent
        h = x.new_zeros(Bsz, d, A.shape[1])                 # fixed-size state
        ys = []
        for t in range(T):
            dA = torch.exp(delta[:, t, :, None] * A)        # (B, d, N)
            dB = delta[:, t, :, None] * Bt[:, t, None, :]   # (B, d, N)
            h = dA * h + dB * x[:, t, :, None]
            ys.append((h * Ct[:, t, None, :]).sum(-1))      # (B, d)
        return torch.stack(ys, dim=1)                       # (B, T, d)

print(NaiveSelectiveSSM(d=8)(torch.randn(2, 20, 8)).shape)  # torch.Size([2, 20, 8])

Each of the dd channels runs its own NN-dimensional state. A real Mamba block wraps this in an input projection, a short causal convolution, a gating branch and an output projection, and replaces the Python loop with the fused scan kernel.

Linear attention and the delta rule

A parallel line of work reaches the same place from the attention side. Replace softmax⁡(qt⊤ks)\operatorname{softmax}(q_t^\top k_s) with a kernel ϕ(qt)⊤ϕ(ks)\phi(q_t)^\top \phi(k_s); then causal attention becomes

ot=ϕ(qt)⊤Stϕ(qt)⊤zt,St=St−1+ϕ(kt) vt⊤,zt=zt−1+ϕ(kt)o_t = \frac{\phi(q_t)^\top S_t}{\phi(q_t)^\top z_t}, \qquad S_t = S_{t-1} + \phi(k_t)\, v_t^\top, \qquad z_t = z_{t-1} + \phi(k_t)

— a recurrence with a fixed-size matrix state St∈Rdk×dvS_t \in \mathbb{R}^{d_k \times d_v}. Plain additive updates never forget and blur memories together, so newer variants add gates (decay of SS) and the delta rule, which overwrites the value stored under a key instead of adding to it: in a common form, St=St−1+βt kt(vt−St−1⊤kt)⊤S_t = S_{t-1} + \beta_t\, k_t (v_t - S_{t-1}^\top k_t)^\top with a learned write strength βt\beta_t. Gated DeltaNet (Yang et al., 2024) combines gating and the delta rule, and Kimi Delta Attention is a refinement of it.

The fundamental trade-off

A fixed-size state is what makes these models cheap, and it is also their limit: a state of a few megabytes cannot hold an exact copy of an arbitrarily long context. Pure recurrent models do well on language modelling perplexity but tend to struggle on tasks that require exact retrieval or copying of specific earlier content, where attention, with its growing cache, can simply look back. That observation drives the hybrid designs below.

Part 3: Hybrid architectures

A hybrid model interleaves a minority of full-attention layers with a majority of SSM or linear-attention layers. The attention layers provide precise lookup; the others provide cheap, constant-memory sequence mixing. As of November 2026, publicly documented examples include:

Model (developer)ReleasedLayer mixNotes from the developer's documentation
Jamba (AI21 Labs)Mar 20241 attention : 7 Mamba layers per block; MoE every other layer (16 experts, top-2)52B total / 12B active parameters; up to 256K context; 4 GB KV cache at 256K versus 32 GB for Mixtral
Nemotron-H (NVIDIA)2025About 8% of layers are self-attention; the rest split between Mamba-2 and MLP layers (8B: 4 attention, 24 Mamba-2, 24 MLP)Reported up to 3× faster inference than similarly sized transformers
Granite 4.0-H (IBM)Oct 2025Mamba-2 to transformer blocks at 9:1; Tiny and Small variants are MoEIBM reports over 70% less RAM for long inputs and concurrent batches; Apache 2.0
Qwen3-Next-80B-A3B (Alibaba Qwen)Sep 20253 Gated DeltaNet : 1 gated attention (36 + 12 of 48 layers); MoE with 512 experts, 10 routed per token plus a shared expertAbout 3B active of 80B; claims more than 10× throughput over Qwen3-32B beyond 32K context
Kimi Linear 48B-A3B (Moonshot AI)Oct 2025About 3 Kimi Delta Attention : 1 MLA layerLinear-attention-majority design with a small number of full-attention layers

The memory effect is easy to compute with the KV-cache formula 2×layers×KV heads×head dim×bytes2 \times \text{layers} \times \text{KV heads} \times \text{head dim} \times \text{bytes}. A 32-layer transformer with 8 KV heads of dimension 128 in 16-bit stores 2×32×8×128×2=131,0722 \times 32 \times 8 \times 128 \times 2 = 131{,}072 bytes (128 KiB) per token, which is 32 GiB at 262,144 tokens. Keep attention in only 4 of 32 layers (a 1:7 ratio) and the cache becomes 16 KiB per token, or 4 GiB — an 8× reduction, matching Jamba's reported ratio — plus a fixed recurrent state for the other layers that does not grow with context. Faster decoding follows, because decode speed is largely bounded by bytes read per token (see tokens-per-second).

The trade-offs: fewer mature kernels and runtimes support SSM layers (IBM ships a pure-transformer Granite 4.0 Micro for platforms without hybrid support), quantization and serving tools lag behind, and the right ratio and placement of attention layers are still active research.

Part 4: Mixture-of-experts, recapped

Mixture-of-experts (MoE) is orthogonal to the attention-versus-recurrence question: it changes the MLP. A router g(x)=Wrxg(x) = W_r x scores EE expert MLPs; the token is sent to the top kk and the outputs are combined with normalized router weights:

y=∑i∈TopK⁡(g(x))pi(x) MLP⁡i(x),pi(x)=egi(x)∑j∈TopK⁡egj(x)y = \sum_{i \in \operatorname{TopK}(g(x))} p_i(x)\, \operatorname{MLP}_i(x), \qquad p_i(x) = \frac{e^{g_i(x)}}{\sum_{j \in \operatorname{TopK}} e^{g_j(x)}}

Compute per token scales with kk, while total parameters scale with EE, so MoE buys capacity without proportional FLOPs. An auxiliary load-balancing loss keeps the router from sending everything to a few experts, and many designs add an always-on shared expert. Note from the table that hybrids and MoE combine naturally (Jamba, Granite 4.0-H Tiny/Small, Qwen3-Next). The memory catch: all experts must be resident, so memory follows total parameters while speed follows active parameters. Details are in mixture-of-experts.

Part 5: Diffusion transformers

Diffusion image generators were long built on U-Net convolutional denoisers. Peebles and Xie's Diffusion Transformer (DiT) (2022) showed that a plain transformer works as the denoiser: the image's latent representation (from a pretrained autoencoder) is cut into patches exactly as in a ViT, the timestep and class label condition each block through adaptive layer norm, and the output patches predict the noise. DiT's quality improved consistently with forward-pass compute (Gflops), from deeper or wider models or more tokens, and DiT-XL/2 reached an FID of 2.27 on class-conditional ImageNet 256×256, state of the art at the time. Transformer denoisers have since become common in large image and video generators; see diffusion-models.

Where each architecture wins

ArchitectureWins whenWatch out for
TransformerMost language, vision and multimodal tasks; exact in-context retrieval; best toolingQuadratic prefill, KV cache growth with context and concurrency
GNNData is a graph with meaningful edges: molecules, transactions, networksOver-smoothing, neighbour explosion on large graphs, dynamic graphs
SSM / linear attentionVery long sequences, streaming, constant-memory inference, audio and genomicsWeaker exact recall; less mature kernels and serving support
HybridLong-context LLM serving where memory and throughput dominate costAttention-layer ratio and placement; runtime support
MoENeed more capacity at fixed per-token computeTotal memory, routing imbalance, harder fine-tuning and serving
Diffusion transformerImage, video and audio generation at scaleMany denoising steps; quadratic cost in patch count at high resolution

Common pitfalls

  • Treating graph data as a table: flattening relational data throws away the structure a GNN would exploit — and conversely, forcing a GNN onto data whose edges carry no signal.
  • Deep GNNs: stacking many GCN layers over-smooths node features; prefer 2–4 layers plus residuals or jumping-knowledge connections.
  • Leakage in graph splits: in link prediction, test edges must be removed from the message-passing graph.
  • Judging SSMs by perplexity alone: evaluate retrieval and long-context tasks too, where fixed-state models may lag.
  • Assuming a hybrid runs everywhere: check that your inference runtime, quantization format and hardware support its layer types before committing.
  • Confusing MoE active and total parameters when sizing memory.

In practice

  • Use PyTorch Geometric or DGL for GNNs, start with a 2-layer GCN or GraphSAGE baseline, and compare against a gradient-boosted model on hand-built graph features.
  • For long-context or high-concurrency LLM serving, compare candidate models on cost per token at your real context lengths; hybrid and linear-attention models can win by large factors there while matching transformers at short context.
  • Verify claims in model cards against your own evaluations, especially long-context recall.
  • Keep transformers as the default when tooling, ecosystem and exact retrieval matter more than raw efficiency.

Key takeaways

  • GNNs pass messages along edges with permutation-invariant aggregation; a GCN averages each node with its degree-normalized neighbours.
  • A discretized linear SSM is both a linear RNN (cheap inference) and a long convolution (parallel training).
  • Mamba makes the step size and the B and C matrices depend on the input, giving content-based forgetting at linear cost via a hardware-aware scan.
  • Fixed-size recurrent state makes SSMs and linear attention cheap but limits exact recall, which is why hybrids keep a few attention layers.
  • Documented hybrids such as Jamba, Nemotron-H, Granite 4.0-H and Qwen3-Next keep attention in roughly 8-25% of layers and cut KV-cache memory accordingly.
  • MoE scales parameters without scaling per-token compute, and diffusion transformers apply the ViT recipe to denoising.

Terms in this lesson

Message passing
The GNN computation in which each node aggregates transformed messages from its neighbours and updates its own representation.
Graph convolutional network (GCN)
A GNN layer that multiplies node features by a learned matrix and averages them over each node's self-looped neighbourhood using symmetric degree normalization.
Over-smoothing
The tendency of node representations in deep GNNs to converge to similar values as repeated averaging spreads information across the graph.
State-space model (SSM)
A sequence model defined by a linear recurrence h_t = A-bar h_{t-1} + B-bar x_t with readout y_t = C h_t, obtained by discretizing a continuous linear system.
Selective SSM
An SSM whose discretization step and input and output matrices are computed from the current input, letting it choose what to keep or forget.
Linear attention
An attention variant that replaces the softmax with a kernel feature map so causal attention can be computed as a recurrence over a fixed-size state.
Hybrid architecture
A model that interleaves a small number of full-attention layers with a majority of SSM or linear-attention layers.
Diffusion transformer (DiT)
A diffusion model whose denoising network is a transformer operating on patches of a latent image rather than a convolutional U-Net.

Check your understanding

  1. 1.

    In a GCN, what is the purpose of the symmetric normalization D^-1/2 (A + I) D^-1/2?

  2. 2.

    In Mamba's selective SSM, which quantities are computed from the current input token?

  3. 3.

    A pharmaceutical team wants to predict the solubility of small molecules from their atom-bond structure. Which architecture is the most natural first choice?

  4. 4.

    A 32-layer transformer is converted into a hybrid that keeps attention in 4 layers and uses Mamba layers elsewhere, with the same KV-head configuration. By roughly what factor does the KV cache at a fixed context shrink?

  5. 5.

    Why do most production hybrid models keep some full-attention layers rather than going fully recurrent?

Exercises

Work each problem before opening the solution.

  1. Exercise 1Core

    A star graph has a centre node 1 connected to leaves 2, 3 and 4. Features are x=(4,0,0,0)x = (4, 0, 0, 0) and W=1W = 1 with no nonlinearity. Apply two GCN propagation steps A^x\hat{A} x and A^(A^x)\hat{A}(\hat{A} x), showing A^\hat{A}. What do you notice, and what does it suggest about depth?

    Show solution

    With self-loops the degrees are d~=(4,2,2,2)\tilde{d} = (4, 2, 2, 2). Entries: A^11=1/4\hat{A}_{11} = 1/4, A^1j=A^j1=1/8=0.3536\hat{A}_{1j} = \hat{A}_{j1} = 1/\sqrt{8} = 0.3536 for leaves jj, A^jj=1/2\hat{A}_{jj} = 1/2, and 0 between different leaves.

    Step 1: centre =0.25⋅4=1.0= 0.25 \cdot 4 = 1.0; each leaf =0.3536⋅4=1.4142= 0.3536 \cdot 4 = 1.4142. So h(1)=(1.0,1.414,1.414,1.414)h^{(1)} = (1.0, 1.414, 1.414, 1.414).

    Step 2: centre =0.25⋅1.0+0.3536⋅(3×1.4142)=0.25+1.5=1.75= 0.25 \cdot 1.0 + 0.3536 \cdot (3 \times 1.4142) = 0.25 + 1.5 = 1.75; each leaf =0.3536⋅1.0+0.5⋅1.4142=1.0607= 0.3536 \cdot 1.0 + 0.5 \cdot 1.4142 = 1.0607. So h(2)=(1.75,1.061,1.061,1.061)h^{(2)} = (1.75, 1.061, 1.061, 1.061).

    The signal that started only at the centre has spread to all nodes, and the leaves are identical (they are structurally symmetric). With more steps the values settle into a fixed pattern proportional to d~v\sqrt{\tilde{d}_v} (here centre:leaf =2:1≈1.41= \sqrt{2} : 1 \approx 1.41; the ratio goes 0.71→1.650.71 \to 1.65 and oscillates toward 1.41), a pattern that depends only on the graph's degrees and no longer on where the signal started. That loss of node-specific information is over-smoothing. That is why GCNs are usually 2-4 layers deep and use residual connections when deeper.

  2. Exercise 2Core

    A scalar SSM has A=−2A = -2, B=C=1B = C = 1, Δ=0.25\Delta = 0.25. (a) Compute Aˉ\bar{A} and Bˉ\bar{B} with zero-order hold. (b) For inputs x=(2,0,1)x = (2, 0, 1) compute y1,y2,y3y_1, y_2, y_3 by recurrence, and verify y3y_3 with the convolution kernel. (c) In a selective SSM, what happens at a step where the model outputs a very large Δt\Delta_t?

    Show solution

    (a) ΔA=−0.5\Delta A = -0.5. Aˉ=e−0.5=0.6065\bar{A} = e^{-0.5} = 0.6065. Bˉ=(ΔA)−1(eΔA−1)ΔB=1−0.5(0.6065−1)(0.25)=0.1967\bar{B} = (\Delta A)^{-1}(e^{\Delta A} - 1)\Delta B = \frac{1}{-0.5}(0.6065 - 1)(0.25) = 0.1967.

    (b) Recurrence with h0=0h_0 = 0:

    • h1=0.1967⋅2=0.3935h_1 = 0.1967 \cdot 2 = 0.3935, so y1=0.3935y_1 = 0.3935
    • h2=0.6065⋅0.3935=0.2387h_2 = 0.6065 \cdot 0.3935 = 0.2387, so y2=0.2387y_2 = 0.2387
    • h3=0.6065⋅0.2387+0.1967⋅1=0.1447+0.1967=0.3415h_3 = 0.6065 \cdot 0.2387 + 0.1967 \cdot 1 = 0.1447 + 0.1967 = 0.3415

    Kernel Kˉk=CAˉkBˉ=(0.1967,0.1193,0.0724)\bar{K}_k = C\bar{A}^k\bar{B} = (0.1967, 0.1193, 0.0724). y3=Kˉ0x3+Kˉ1x2+Kˉ2x1=0.1967+0+0.0724⋅2=0.3415y_3 = \bar{K}_0 x_3 + \bar{K}_1 x_2 + \bar{K}_2 x_1 = 0.1967 + 0 + 0.0724 \cdot 2 = 0.3415. Matches.

    (c) With A<0A < 0, a very large Δt\Delta_t makes Aˉt=eΔtA≈0\bar{A}_t = e^{\Delta_t A} \approx 0, wiping the previous state, while the input term ΔtBtxt\Delta_t B_t x_t becomes large: the model resets and stores the current token. A tiny Δt\Delta_t does the opposite, keeping the state and nearly ignoring the token. This is content-dependent forgetting.

  3. Exercise 3Challenge

    Compare memory at a 131,072-token context for two 48-layer models with 8 KV heads of dimension 128 in 16-bit: (A) all layers are full attention; (B) a 3:1 hybrid with 12 full-attention layers and 36 linear-attention layers, each linear layer keeping 16 heads of 128 x 128 state in 16-bit. Compute the per-token KV cache, total context memory for one sequence, and the ratio. Then explain why per-token decode is still not constant-time for model B.

    Show solution

    Model A: per token 2×48×8×128×2=196,6082 \times 48 \times 8 \times 128 \times 2 = 196{,}608 bytes =192= 192 KiB. At 131,072 tokens: 192 KiB×131,072=24192 \text{ KiB} \times 131{,}072 = 24 GiB.

    Model B: attention layers: 2×12×8×128×2=49,1522 \times 12 \times 8 \times 128 \times 2 = 49{,}152 bytes =48= 48 KiB per token, so 6 GiB at 131,072 tokens. Linear-attention state: 16×128×128×2=524,28816 \times 128 \times 128 \times 2 = 524{,}288 bytes =512= 512 KiB per layer, times 36 layers =18= 18 MiB, independent of context. Total about 6.026.02 GiB.

    Ratio: about 24/6.02≈4.0×24 / 6.02 \approx 4.0\times less memory per sequence, which also means roughly 4x more concurrent long sequences in the same memory.

    Decode for model B is still O(n)O(n) per token because its 12 attention layers must read the whole cached context for every new token; only the 36 linear layers are constant-time. The attention share is 4x smaller, so the context-dependent part of decode cost drops about 4x, but it still grows with context.

  4. Exercise 4Challenge

    Show in code that causal linear attention with feature map ϕ(z)=elu⁡(z)+1\phi(z) = \operatorname{elu}(z) + 1 can be computed either in a parallel form (masked matrix products, as in training) or as a recurrence with a constant-size state (as in inference), and that the two give identical outputs.

    Show solution
    import torch, torch.nn.functional as F
    torch.manual_seed(0)
    T, dk, dv = 6, 4, 3
    phi = lambda z: F.elu(z) + 1                      # strictly positive features
    Q, K, V = torch.randn(T, dk), torch.randn(T, dk), torch.randn(T, dv)
    q, k = phi(Q), phi(K)
    
    # parallel form: causal mask on the (unnormalized) kernel scores
    scores = (q @ k.T) * torch.tril(torch.ones(T, T))
    par = (scores @ V) / scores.sum(-1, keepdim=True)
    
    # recurrent form: state S (dk x dv) and normalizer z (dk)
    S, z, rec = torch.zeros(dk, dv), torch.zeros(dk), []
    for t in range(T):
        S = S + torch.outer(k[t], V[t])
        z = z + k[t]
        rec.append((q[t] @ S) / (q[t] @ z))
    rec = torch.stack(rec)
    print(torch.allclose(par, rec, atol=1e-5))        # True
    

    Both compute ot=∑s≤t(qt⊤ks)vs/∑s≤tqt⊤kso_t = \sum_{s \le t} (q_t^\top k_s) v_s / \sum_{s \le t} q_t^\top k_s. The parallel form costs O(T2)O(T^2) but uses big matrix multiplies (good for training on GPUs, and chunked variants reduce it further); the recurrent form costs O(1)O(1) per token with a dk×dvd_k \times d_v state (good for generation). Softmax attention has no such factorization because eq⊤ke^{q^\top k} does not split into a product of separate functions of qq and kk with a finite feature map.

Further reading

Go further

Sources

Fact-checked and last reviewed 2026-11-05

Stay in the loop
Prometheus OS™ · Native AI OS · Built for the future © 2025 - 2026