Transformers and Neural State-Space Architectures

Michael BrenndoerferJune 26, 202643 min read

Part of World Models Handbook

Compare attention-based transformers, structured state-space models, and hybrid architectures for world models.

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

Transformers and Neural State-Space Architectures

Imagine a household robot operating in a kitchen. Ten minutes ago, it saw a coffee mug placed behind the microwave. The mug is now out of view. Remembering its location could let the robot fetch it directly; forgetting might force a search. In many partially observable tasks, useful evidence arrives at separated times. A short episode may fit in memory in full, but retaining and consulting an arbitrarily long raw history becomes costly under a finite storage and compute budget.

A recurrent state-space model of the kind we built in the previous chapter carries a fixed-size joint state (ht,zt)(h_t,z_t). With finite numerical precision, that state has only finitely many representable values. A task may nevertheless admit a finite-dimensional sufficient statistic, such as a correctly specified Kalman filter's mean and covariance in ideal arithmetic; its numerical implementation is an approximation. The difficulty arises when the retained state merges histories that require different predictions or actions. Contractive linear recurrences attenuate old input contributions; gated and other recurrences can retain or transform them differently. Once a relevant distinction is absent from the state and any external memory, later computation cannot recover it from that state alone.

This chapter studies two architectural families with different memory costs. Transformers retain token representations and use attention to compute content-dependent weighted readouts within the available context. Retention makes access possible; it does not guarantee that the representation preserves a detail or that training learns to retrieve it. Neural state-space layers retain a fixed-size recurrent state, using structured transitions that can be evaluated efficiently. Fixed-coefficient and input-selective variants differ in both their mathematics and implementation. Hybrid sequence architectures combine these mechanisms. We will examine named examples, then compare two small predictors on a controlled task rather than infer a universal ranking.

Throughout, keep our standing distinction in mind: a world model predicts environment-relevant quantities that an agent may use for planning or policy learning. Its performance must be checked under the trajectories where it will be used. Four quality axes help organize that evaluation:

  • Predictive fidelity: accuracy of forecasts at specified horizons and under specified conditioning.
  • Representation quality: retention of information relevant to the prediction or decision task, not necessarily reconstruction of every physical state variable.
  • Uncertainty quality: calibration and informativeness of predictive distributions, not simply a large or small variance.
  • Decision usefulness: performance of plans or policies when evaluated in the environment.

These axes are related but not interchangeable. The experiment below measures point-prediction errors and an attention diagnostic. It does not test distant event recall, calibrated uncertainty, or a controller.

Attention over Trajectories

This section develops self-attention as the core mechanism of transformer world models: how a trajectory becomes tokens, how attention computes a content-based weighted average over the past, and why that mechanism is so well suited to partially observable decision problems.

A transformer can retain multiple token representations instead of depending only on a single recurrent history summary. For each query it computes a new fixed-width readout from that memory. Tokenization, embeddings, value projections, and the readout can all discard information; this is not lossless storage. One possible tokenization, used below, embeds an observation-action pair. For observation width dod_o, action width dad_a, and embedding width dd, define ot∈Rdoo_t\in\mathbb R^{d_o}, at∈Rdaa_t\in\mathbb R^{d_a}, and zt,pt∈Rdz_t,p_t\in\mathbb R^d:

zt=Win[otat]+pt,z_t = W_{\text{in}} \begin{bmatrix} o_t \\ a_t \end{bmatrix} + p_t,

where:

  • oto_t: the observation received at timestep tt
  • ata_t: the action taken at timestep tt
  • Win∈Rd×(do+da)W_{\text{in}}\in\mathbb R^{d\times(d_o+d_a)}: a learned embedding of the stacked observation-action pair
  • ptp_t: an additive positional encoding for timestep tt

The projection embeds the pair; it need not reduce dimension or information. Our code expands two inputs to sixteen features. Without positional signals or an order-dependent mask, self-attention is permutation-equivariant: permuting input rows permutes output rows, and the key-value collection has no intrinsic order. A causal mask changes that statement because different positions have different accessible prefixes; repeated content can then produce different outputs even without explicit positions. Positional encodings provide additional temporal information. The original Transformer uses sinusoidal or learned additive encodings. Rotary encodings instead rotate query and key coordinates inside attention, so they are not literally the additive ptp_t in this equation. Transformer blocks combine attention, feed-forward layers, residual connections, and normalization. Residual paths allow incremental updates and can improve gradient propagation, but they do not guarantee stable gradients.

The heart of the mechanism is scaled dot-product attention. Each token emits three vectors through learned linear maps:

Q=ZWQ,K=ZWK,V=ZWV,Q = ZW_Q, \qquad K = ZW_K, \qquad V = ZW_V,

where:

  • Z∈RT×dZ\in\mathbb R^{T\times d}: the matrix with row tt equal to zt⊤z_t^\top
  • WQ,WK∈Rd×dkW_Q,W_K\in\mathbb R^{d\times d_k} and WV∈Rd×dvW_V\in\mathbb R^{d\times d_v}: learned projections, giving Q,K∈RT×dkQ,K\in\mathbb R^{T\times d_k} and V∈RT×dvV\in\mathbb R^{T\times d_v}
  • qi=Qi,:⊤q_i=Q_{i,:}^\top, kj=Kj,:⊤k_j=K_{j,:}^\top, and vj=Vj,:⊤v_j=V_{j,:}^\top: column vectors for the query, key, and value; the attention output below is also a column

It is worth pausing on why the same tokens produce three different roles. The query encodes what the current position is looking for; the key encodes what each position advertises about itself, the label under which it can be found; and the value encodes the information each position contributes once selected. Separating these roles, rather than using the raw embedding for all three, is what lets the network learn asymmetric relationships: a token predicting a collision can learn to search for tokens advertising recent velocities, while advertising, under its own key, something unrelated such as its object identity. The attention output for token ii is a weighted average over all value vectors (in the causal models trained below, the sum runs only over j≤ij \le i, but we first present the unmasked form):

Attn(Q,K,V)i=∑jexp⁡ ⁣(qi⊤kj/dk)∑j′exp⁡ ⁣(qi⊤kj′/dk) vj,\text{Attn}(Q, K, V)_i = \sum_j \frac{\exp\!\big(q_i^\top k_j / \sqrt{d_k}\big)}{\sum_{j'} \exp\!\big(q_i^\top k_{j'} / \sqrt{d_k}\big)} \, v_j,

where:

  • jj: the index ranging over all tokens in the sequence
  • j′j': a dummy index used only inside the normalizing constant, so that the sum in the denominator is independent of the sum in the numerator
  • qi⊤kjq_i^\top k_j: the dot product between the query of token ii and the key of token jj, measuring how relevant token jj is to token ii
  • dk\sqrt{d_k}: the square root of the key dimension dkd_k, by which the scores are scaled to keep the softmax gradients well behaved when dkd_k is large
  • ∑j′exp⁡ ⁣(qi⊤kj′/dk)\sum_{j'} \exp\!\big(q_i^\top k_{j'} / \sqrt{d_k}\big): the normalizing constant that turns the scores into convex weights summing to one
  • vjv_j: the value vector of token jj, the content that gets retrieved

For finite logits and a nonempty allowed set, the softmax weights are nonnegative and sum to one. Thus the per-head output before its output projection is a convex combination of value vectors. The unmasked expression includes current and future positions; a causal mask restricts it to j≤ij\le i. This convexity does not describe the entire block after residual, projection, and feed-forward operations. If query and key components are independent, zero-mean, unit-variance variables, independent across coordinates, then Var⁡(q⊤k)=dk\operatorname{Var}(q^\top k)=d_k. Dividing by dk\sqrt{d_k} gives unit variance under those assumptions. It can reduce softmax saturation; learned projections can still produce saturated scores.

Attention as soft lookup

Attention is a differentiable content-addressed weighted lookup. Queries and keys determine compatibility; values provide the retrieved representation. In a causal model, available values can represent real observations or earlier generated tokens. The readout is itself a fixed-width summary. A hard argmax lookup has locally constant routing away from score ties, although gradients still reach the selected value. Softmax permits gradients through unmasked scores, but actual gradients may vanish or cancel, for example, when all values are identical.

Two properties explain why this matters for world models:

  • Content-based addressing. Scores depend on token content and any positional mechanism, rather than only on a fixed decay schedule. An old retained token can receive high weight if the learned query matches it. A Kalman filter instead weights the current innovation using predicted covariance, measurement covariance, and the observation model; its fixed-size state can still be sufficient for its specified task. Attention recomputes compatibility with retained learned keys, not necessarily raw evidence.
  • Short gradient paths. Full attention provides a token-to-token path within a layer whose length does not grow with temporal separation. A recurrent path may contain many state-update Jacobians. Attention therefore shortens temporal dependency paths, but saturated scores, depth, and normalization can still cause optimization problems.

The price depends on which operation is measured. At fixed widths and layer count, dense full-sequence attention performs O(T2)O(T^2) pairwise arithmetic. Materializing its score matrix uses O(T2)O(T^2) memory, but this is not an intrinsic memory lower bound: FlashAttention computes exact attention with memory-efficient tiled evaluation. An uncompressed fixed-width KV cache uses O(T)O(T) storage. With that cache, one new query performs O(T)O(T) attention work; a fixed-width recurrent update instead has cost independent of elapsed history. These are asymptotic statements at fixed batch size, precision, and architecture, not wall-clock speed predictions.

Multi-head attention repeats the lookup with separate projections, then concatenates and linearly mixes the head outputs. Heads may learn different patterns, but assigning one head to each physical state factor requires evidence. The predictive representation is produced jointly by embeddings, attention, residual paths, and feed-forward layers; heads alone do not define a Bayesian belief. Inspecting their weights is one diagnostic, alongside state probes, interventions, ablations, and predictive tests. Attention is not Explanation gives examples where attention weights do not uniquely explain predictions.

Causal Sequence Modeling

This section explains how transformers are trained as predictive models of trajectories: the causal mask, the autoregressive factorization of the likelihood, and what a transformer trained this way computes when an agent uses it inside a decision loop.

An action-conditioned predictor must not read its future targets. During training, a trajectory with TT observed positions provides T−1T-1 adjacent next-observation targets. A causal mask excludes attention from position ii to j>ij>i, usually by assigning those scores negative infinity. Provided an allowed finite score remains in each row, the masked weights are zero. With aligned targets and no other leakage paths, all positions can be supervised in one layerwise-parallel forward pass. This reuses computation across prediction tasks without removing attention's quadratic pairwise arithmetic.

Causal masking

The causal mask enforces the arrow of time inside the network. Without it, the model could cheat by attending to future observations, and its "predictions" would leak information that no deployed agent could possess. Such a model might even achieve lower training loss than a correctly masked one, since seeing the future helps predict the present, which makes the bug insidious: it degrades deployed behavior while appearing to improve the training metric. The mask, aligned targets, and leakage-free input construction together support autoregressive prediction.

Formally, the model defines an autoregressive factorization of trajectory likelihood, echoing the probabilistic framing of Part II:

p(o1:T,a1:T)=∏t=1Tp(ot∣o<t,a<t)  p(at∣o≤t,a<t),p(o_{1:T}, a_{1:T}) = \prod_{t=1}^{T} p(o_t \mid o_{<t}, a_{<t}) \; p(a_t \mid o_{\le t}, a_{<t}),

where:

  • o1:To_{1:T} and a1:Ta_{1:T}: the full sequences of observations and actions from timestep 11 to TT
  • p(ot∣o<t,a<t)p(o_t \mid o_{<t}, a_{<t}): the probability mass or density of observation oto_t given all earlier observations and actions, the world-model factor
  • p(at∣o≤t,a<t)p(a_t \mid o_{\le t}, a_{<t}): the probability mass or density of action ata_t given the observations seen up to and including time tt and all earlier actions, the policy factor

The chain rule uses the ordering o1,a1,o2,a2,…,oT,aTo_1,a_1,o_2,a_2,\ldots,o_T,a_T. For t=1t=1, the observation factor is the marginal p(o1)p(o_1). Training both observation and action factors would model environment observations and the data-collecting policy, respectively. However, the paired token (ot,at)(o_t,a_t) used below already contains ata_t: an action head reading that same token would leak its target despite a causal mask. Joint supervision needs separately ordered observation/action tokens or an action-excluded, appropriately shifted input path. The observation-only objective below does not train action probabilities. A behavior-policy estimate can support off-policy weighting only with reliable propensities and suitable support; learning such a head is not itself a validity guarantee.

A next-observation world model maximizes the expected log-likelihood of observations under the data distribution, estimated as the empirical average over NN training trajectories, with teacher forcing:

L(θ)=1N∑n=1N∑t=1T−1log⁡pθ(ot+1(n)∣o≤t(n),a≤t(n))\mathcal{L}(\theta) = \frac{1}{N} \sum_{n=1}^{N} \sum_{t=1}^{T-1} \log p_\theta(o_{t+1}^{(n)} \mid o_{\le t}^{(n)}, a_{\le t}^{(n)})

where:

  • L(θ)\mathcal{L}(\theta): the empirical trajectory-average log-likelihood, maximized during training; minimizing −L-\mathcal{L} is equivalent
  • θ\theta: the model parameters
  • NN: the number of trajectories; superscript (n)(n) identifies observations and actions from trajectory nn
  • TT: the common number of observed positions in this equation, giving T−1T-1 adjacent prediction targets
  • pθ(ot+1(n)∣o≤t(n),a≤t(n))p_\theta(o_{t+1}^{(n)}\mid o_{\le t}^{(n)},a_{\le t}^{(n)}): the next-observation distribution conditioned on the recorded prefix and current action

This is a conditional likelihood, not a variational ELBO. The later simulator uses TT for its number of transitions and allocates T+1T+1 observation slots, including a zero start marker; its target count therefore differs from this equation's convention.

For continuous observations, pθp_\theta is a density, not the probability of one exact value. The code below minimizes mean squared error. For a scalar Gaussian observation model with the network output as its mean and a fixed positive variance, negative log-likelihood differs from squared error only by a positive constant factor and an additive constant. With the same targets and weighting, the objectives therefore have the same minimizers; this interpretation does not mean that the code learns or calibrates a predictive variance.

Teacher forcing conditions on recorded observations; a recursive open-loop forecast under fixed candidate actions conditions on its own later predictions. Closed-loop control is different: it uses newly observed environment feedback to choose or revise actions. Identical one-step errors need not produce identical rollout errors. To see why, consider the local error recursion et+1≈Jtet+δte_{t+1}\approx J_t e_t+\delta_t, where JtJ_t propagates an existing error and δt\delta_t is a new disturbance or model mismatch. In the idealized scalar unit-gain additive case with zero initial error, independent zero-mean disturbances with common finite variance σ2\sigma^2 give root-mean-square error σH\sigma\sqrt H; a constant bias bb instead gives signed error HbHb. Contractive propagation can bound either effect; unstable propagation can amplify it. Feeding predictions back can introduce dependent errors, but neither correlation nor monotonic growth is inevitable.

There is a second, quieter gap in the same objective: it is an average over the data-collecting distribution, so it weights trajectories exactly as the logging policy produced them. A planning agent, by contrast, will steer its rollouts toward states it finds interesting or valuable, which may be rare or absent in the training data. Predictive fidelity on the data distribution therefore bounds neither fidelity nor uncertainty quality under the agent's own exploration distribution, a fragility we return to in the limitations section.

A causal transformer produces a learned predictive representation, not automatically a Bayesian belief or a statistically sufficient state. Let Ht=(o≤t,a<t)\mathcal H_t=(o_{\le t},a_{<t}) denote available history and bt=p(st∣Ht)b_t=p(s_t\mid\mathcal H_t) the Bayesian posterior in a specified POMDP. Under its transition and observation assumptions, this belief supports prediction for supplied future actions. A learned feature rt=gθ(Ht,at)r_t=g_\theta(\mathcal H_t,a_t) always determines its own prediction head, but statistical sufficiency would additionally require p(ot+1∣Ht,at)=p(ot+1∣rt)p(o_{t+1}\mid\mathcal H_t,a_t)=p(o_{t+1}\mid r_t) for the true data-generating distribution. Finite context, lossy representations, limited capacity, or unsuccessful optimization can break that equality. Retained token representations provide addressable memory from which the network computes features; they are neither the full raw history nor the posterior by definition.

This view is what makes sequence-modeling world models work at all:

  • Trajectory Transformer (Janner et al., 2021) discretizes trajectory components including observations, actions, and rewards and fits an autoregressive model. A separate beam-search procedure uses that model for trajectory optimization; action proposals and reward predictions are not the whole planning algorithm.
  • Decision Transformer (Chen et al., 2021) produces actions from desired return-to-go and state/action history. It is a return-conditioned policy, not necessarily an environment-transition predictor or an online search planner.
  • VideoGPT uses autoregressive prediction of learned video tokens, while Gato applies sequence modeling to multimodal policy outputs. Shared sequence machinery is useful, but modality-specific representations, data, and objectives remain important.

A planner knows each candidate open-loop action sequence it proposes; a feedback policy instead chooses later actions in response to later observations. An action-conditioned model can compute a forecast for either kind of query, but observational conditioning is not automatically a valid intervention model. Appropriate action support and causal assumptions are needed, for example, actions randomized independently of hidden disturbances, or a history sufficient to remove action-outcome confounding. If a logging policy uses hidden information unavailable to the model, its action may reveal that information rather than cause the observed outcome. Our simulator uses independent random controls and a known transition mechanism. System identification likewise may use deliberately designed excitation inputs, not only inputs selected by someone else.

Long-Context Memory and Efficient Recurrence

This section develops fixed linear state-space layers, then distinguishes their input-selective relatives and other subquadratic sequence models. Stability and efficient evaluation depend on the particular recurrence and implementation.

For a long trajectory, full attention's pairwise arithmetic and retained KV storage can become expensive. An hour at 30 Hz contains 108,000 steps. At fixed batch size, width, depth, and precision, an append-only KV cache grows linearly with retained tokens. Truncation discards old entries; compression reduces their representation and can lose information, but need not create a globally fixed-size state. A recurrent layer instead maintains a state whose width is independent of sequence length. Whether that state preserves enough information is a task question, not a consequence of efficient implementation alone.

The canonical continuous-time form is the linear state-space system we met during system identification in Part II, now with learned parameters:

h˙(t)=A h(t)+B x(t),y(t)=C h(t),\dot{h}(t) = A\, h(t) + B\, x(t), \qquad y(t) = C\, h(t),

where:

  • h(t)∈Rnh(t)\in\mathbb R^n: the continuous-time state
  • x(t)∈Rmx(t)\in\mathbb R^m: the input signal
  • y(t)∈Rpy(t)\in\mathbb R^p: the output
  • A∈Rn×nA\in\mathbb R^{n\times n}: the state-transition generator
  • B∈Rn×mB\in\mathbb R^{n\times m}: the input map into the state derivative
  • C∈Rp×nC\in\mathbb R^{p\times n}: the state readout

The lineage here is worth appreciating. Classical system identification, from subspace methods to prediction-error methods, spent decades estimating exactly these matrices from input-output data for engineering models of known dimension. The neural state-space program takes the same mathematical object and embeds it as a layer inside a deep network, with the matrices as parameters trained by gradient descent end to end. What was once a standalone modeling methodology becomes a differentiable component, and the analysis tools, stability theory in particular, come along for free.

Discretizing with step Δ\Delta via the zero-order-hold rule gives the recurrent form used at inference:

ht=Aˉ ht−1+Bˉ xt,yt=C ht,Aˉ=eAΔ,Bˉ=∫0ΔeAuB du.h_t = \bar{A}\, h_{t-1} + \bar{B}\, x_t, \qquad y_t = C\, h_t, \qquad \bar{A} = e^{A\Delta}, \qquad \bar B=\int_0^\Delta e^{Au}B\,du.

where:

  • hth_t: the discrete-time latent state after processing token tt, with the initial state h0h_0 set to zero
  • Aˉ=eAΔ\bar{A} = e^{A\Delta}: the discretized transition matrix, obtained by exact matrix exponentiation of AA over the step size Δ\Delta
  • Bˉ\bar{B}: the discretized input matrix, derived from AA, BB, and Δ\Delta under the zero-order-hold assumption that xx is constant over the step
  • xtx_t: the input token at timestep tt
  • CC: the same output matrix as in continuous time

Here xtx_t is held constant over ((t−1)Δ,tΔ]((t-1)\Delta,t\Delta] and hth_t is the state at the interval's end. Variation of constants gives the integral for Bˉ\bar B: it accumulates the input's contribution while the continuous dynamics evolve. If AA is invertible, Bˉ=A−1(eAΔ−I)B\bar B=A^{-1}(e^{A\Delta}-I)B; the integral also covers singular AA. For a fixed stable mode aa, retention per token is eaΔe^{a\Delta}. A smaller positive step moves this multiplier toward one and, under zero-order hold, also shrinks the input write approximately to BΔB\Delta. A larger step forgets more per token. Learning Δ\Delta therefore changes token-scale dynamics, not the physical-time constant of a fixed AA in isolation.

Because Aˉ=eAΔ\bar{A} = e^{A\Delta}, a fixed positive step Δ\Delta maps each eigenvalue aia_i with negative real part to a discrete multiplier of magnitude ∣eaiΔ∣=eRe⁡(ai)Δ<1|e^{a_i\Delta}|=e^{\operatorname{Re}(a_i)\Delta}<1. For a fixed diagonal recurrence, the initial-state contribution therefore decays. With bounded inputs and fixed finite input and output matrices, its forced response is bounded as well. This is a property of that recurrent layer, not a guarantee that every activation or gradient in the surrounding network remains bounded. Three design choices help explain the modern SSM lineage:

  • Diagonal AA. S4 (Gu et al., 2021) used a diagonal-plus-low-rank representation; S4D, S5, and Mamba use diagonal state transitions. The scalar channels can be real or complex. Real negative continuous-time eigenvalues yield nonoscillatory decays, whereas complex conjugate channels can encode damped oscillations. A diagonal representation is not intrinsically less expressive than a diagonalizable full matrix when complex coordinates and suitable input/output maps are allowed. The real, positive-decay example below is more restrictive. Negative real parts, a positive discretization step, and bounded forcing give the fixed-layer stability conditions stated above.
  • HiPPO-style initialization. HiPPO (High-order Polynomial Projection Operators) derives online dynamics for optimal polynomial projection under a specified time-dependent weighting measure. LegS weights the elapsed interval [0,t][0,t] uniformly and has time-dependent 1/t1/t dynamics; LagT uses exponentially recency-weighted history. These are properties of the specified projection operators. S4 uses HiPPO-related structure to motivate its parameterization and initialization, but an arbitrary fixed or subsequently learned SSM does not inherit exact projection optimality.
  • Parallel training via convolution. For fixed coefficients and h0=0h_0=0, unrolling gives ht=∑k=0t−1AˉkBˉxt−kh_t=\sum_{k=0}^{t-1}\bar A^k\bar Bx_{t-k} and yt=∑k=0t−1Kkxt−ky_t=\sum_{k=0}^{t-1}K_kx_{t-k} with Kk=CAˉkBˉK_k=C\bar A^k\bar B. This matrix-valued impulse response measures each past input's linear influence. Stable modes have decaying envelopes, but their mixture may initially grow or oscillate; it need not be a monotone low-pass curve. At fixed channel dimensions, zero-padded FFT convolution costs O(Tlog⁡T)O(T\log T) work for a full sequence, while cached recurrence has O(1)O(1) work per new token with respect to history length. This duality applies to the fixed linear layer. A nonlinear RNN lacks one global LTI kernel, though local Jacobians and trajectory perturbations remain inspectable.

A fixed-size state must compress its history, and input dependence changes what the model retains. Classical structured SSM layers use input-independent coefficients. S5 replaces S4's bank of single-input single-output systems with a multi-input multi-output formulation and evaluates its recurrence by parallel scan; it should not be grouped with Mamba as introducing learned input-dependent selectivity. See the S5 paper, introduction and Section 2.2. Mamba makes BtB_t, CtC_t, and the discretization step Δt\Delta_t depend on the current input while retaining a learned input-independent continuous-time AA. Its Appendix B.1 explicitly credits S5's scan and distinguishes Mamba's selection mechanism and hardware-aware implementation. For real ai<0a_i<0 and Δt,i>0\Delta_{t,i}>0, the effective decay Aˉt,i=exp⁡(Δt,iai)\bar A_{t,i}=\exp(\Delta_{t,i}a_i) lies strictly between zero and one in exact arithmetic. Complex eigenvalues instead give complex multipliers whose magnitudes are below one. Selection changes both retention and the input-dependent write; a large discretization step can suppress old state while admitting new information. Because these coefficients depend on the sequence, one fixed convolution kernel no longer describes the layer, so Mamba uses a hardware-aware scan. Conditional on a sequence of coefficients, the update is affine in the previous state; the full input-to-output mapping is not a linear time-invariant system. Pointwise decay below one alone does not ensure bounded response to arbitrary forcing: a uniform contraction bound and bounded writes are sufficient, whereas decays approaching one need separate analysis. Finite-precision exponentials and softplus also require numerical care.

The memory-computation exchange

At fixed dimensions, dense full-sequence attention has O(T2)O(T^2) pairwise work, an uncompressed cache has O(T)O(T) storage, and a cached new query has O(T)O(T) attention work. A fixed-width recurrence has O(T)O(T) sequence work and constant state storage; a work-efficient scan preserves linear work, while FFT convolution uses O(Tlog⁡T)O(T\log T). These costs concern specified implementations, not guarantees of recall. If a task admits an adequate filtering state, recurrence can preserve what matters. Addressable memory can make isolated-event retrieval easier, but a suitable recurrent or symbolic state can also retain such events. This is a design tradeoff to test, not an exclusive division of capability.

Linear transformers make the connection explicit. Let feature-mapped keys and queries be columns in Rdk\mathbb R^{d_k} and values be columns in Rdv\mathbb R^{d_v}. With S0=0S_0=0, the numerator accumulator is St=St−1+ktvt⊤∈Rdk×dvS_t=S_{t-1}+k_tv_t^\top\in\mathbb R^{d_k\times d_v}, and its column readout is St⊤qt=∑j≤t(qt⊤kj)vjS_t^\top q_t=\sum_{j\le t}(q_t^\top k_j)v_j. Normalized linear attention also keeps ct=ct−1+ktc_t=c_{t-1}+k_t and divides by qt⊤ctq_t^\top c_t when that denominator is positive. These are statistics sufficient to compute this attention rule, not necessarily the environment's state. RWKV uses recurrent, temporally weighted key-value memory; Transformer-XL reuses preceding-segment representations; Block-Recurrent Transformers update persistent state vectors with attention and gates. Each changes what is retained and how it is read. Tasks with smoothly accumulating evidence and tasks with consequential object relocations suggest different tests, but neither task label establishes an architecture winner.

Transformer and State-Space Hybrids

This section surveys architectures that combine attention and state-space recurrence, the design patterns they follow, and why mixing the two mechanisms is a hypothesis worth testing for long-horizon world models.

Can recurrence reduce memory cost while attention preserves useful access to selected context representations? Several 2024 hybrid language-model reports explore this design hypothesis. Static layer interleaving does not dynamically identify valuable events: it applies its assigned layers to every token. Savings come from using fewer attention layers, restricting their span, or sharing parameters. Their value for a world-model task still requires task-specific evaluation.

One pattern is layer interleaving. Jamba (AI21, 2024) uses an attention-to-Mamba ratio of 1:7 in its reported architecture. Zamba (Zyphra, 2024) repeatedly invokes a shared attention-plus-MLP module among Mamba blocks, saving parameters relative to separate copies. Griffin and Hawk (De et al., 2024) use gated linear recurrence: Griffin retains local attention, whereas Hawk is recurrent-only. Their reported quality and inference-cost comparisons concern specified language benchmarks, model scales, contexts, and hardware, not all world models. Griffin's held-out-book experiments also test length extrapolation beyond training context. A length-independent recurrence is a plausible contributing bias, but that alone neither proves the mechanism nor guarantees extrapolation.

For world models specifically, hybridization predates the recent wave of SSM-based hybrids and takes a second form: transformer dynamics inside a stochastic latent world model.

  • TransDreamer (Chen et al., 2022) introduces the Transformer State-Space Model (TSSM). It replaces recurrent dynamics with transformer dynamics and modifies posterior conditioning to permit parallel training. Its 2D and 3D Hidden Order Discovery tasks involve discovering and remembering object orders through interaction. Reported gains over Dreamer are empirical, not a proof that finite recurrent state cannot solve these tasks or that memory is the only changing factor.
  • TWM (Robine et al., 2023), not TSSM, uses Transformer-XL dynamics over latent states, actions, and rewards with a separate observation model. It reports results under Atari 100k's 100,000-interaction budget. Short attention paths are a possible benefit, but the reported comparison does not isolate them as the cause of sample efficiency.
  • A possible chunked hybrid runs local recurrence within windows and attention over their summaries. This should not be confused with the named Block-Recurrent Transformer, whose state update uses attention and gates. For one full summary-attention pass with M≈T/WM\approx T/W fixed-width summaries and linear within-window work, total work is O(T+M2)=O(T+(T/W)2)O(T+M^2)=O(T+(T/W)^2). Fixed WW leaves a quadratic term; bounded MM, or growth no faster than order T\sqrt T, gives linear-order total work. Recomputing summary attention at every token would change this accounting.
Division of labor in hybrids

The proposed division of labor is a hypothesis about useful representations. Linear recurrence can efficiently integrate signals whose dependencies match its learned dynamics; addressable attention can help retrieve isolated events. Neither behavior is exclusive to that mechanism, and finite-score soft attention does not guarantee exact recall. Interleaving lets both mechanisms process every token, which may contain both evolving quantities and a newly observed event. Probes and interventions are needed to establish what a trained hybrid learns.

A third design axis changes attention's retained memory. Sliding windows restrict direct access to recent tokens; cache compression can select, merge, or quantize stored representations. Global tokens provide shared access points, but they become a recurrent cross-segment summary only if an explicit update-and-carry mechanism is implemented with the required causal restrictions. Chunked prefill is different: it schedules processing in chunks and need not reduce retained KV state or change the memory representation. These choices trade cost against available information, with consequences revisited in Part VI.

For a new task, ask what history distinctions predictions or decisions require. One useful test places a decision-critical observation at varying temporal distances while controlling its content, distractors, and task difficulty. Plot error against distance alongside aggregate prediction loss. A fixed-decay system may lose usable event information as distance grows; an attention model may fail when the relevant representation leaves its context. These are hypotheses, not guaranteed curve shapes: learned retrieval can fail inside a window, and selective recurrence can retain events through distractors. A distance-controlled experiment reveals failures that an average can hide, but our smooth-dynamics experiment below does not perform this rare-event test.

Worked Example: Attention as Content-Based Lookup

Before the full experiment, let us build direct intuition for attention with a tiny hand-computed lookup. Suppose a trajectory contains three tokens, each describing an object with a one-hot identity feature and an associated position value. A query token asks, in effect, "where is the red object?" In a real transformer the query, keys, and values are learned projections, but the hand-designed example uses the same weighted-lookup operation. Training optimizes the projections for an objective; useful semantic alignment must be learned rather than assumed.

In[3]:
Code
import numpy as np

## Query: "looking for red" (third feature)
q = np.array([0.0, 0.0, 1.0])

## Keys: one-hot object identities for blue block, green block, red key
K = np.array(
    [
        [1.0, 0.0, 0.0],  # token 1: blue block
        [0.0, 1.0, 0.0],  # token 2: green block
        [0.0, 0.0, 1.0],  # token 3: red key
    ]
)

## Values: observed positions of each object
V = np.array([[2.0], [7.0], [9.0]])

scores = K @ q / np.sqrt(3)
w = np.exp(scores - scores.max())
w = w / w.sum()
out = w @ V

print("attention weights:", np.round(w, 3))
print("attended output (retrieved position):", np.round(out, 3)[0])
Out[3]:
Console
attention weights: [0.264 0.264 0.471]
attended output (retrieved position): 6.62

With the one-hot scores divided by 3\sqrt{3}, the matching token receives weight about 0.47 and each other token about 0.26. The output is 6.62, not the red key's stored position 9.0. Increasing the matching score's margin would concentrate the weights toward that value. This example illustrates standard scaled dot-product attention and maximum-subtracted softmax; these details are not universal to every attention variant. A retained token can be accessed at a long lag if useful keys, queries, and values are learned. When it is removed, direct access is lost, although another retained representation may preserve its content. In a fixed stable SSM, an input's contribution propagates through powers of the transition matrix. Its amplitude can decay while usable recall either deteriorates gradually or fails abruptly through finite precision, interference, or decoding thresholds. Selective retention can change that behavior; it is not implemented by the fixed-coefficient SSM below.

Code Implementation

Now we build a synthetic, partially observable linear-Gaussian system: a two-dimensional hidden state, scalar control, and noisy scalar observation. A single scalar reading does not identify the state, so observation and control history can improve prediction. A correctly specified Kalman filter would use dynamics- and covariance-dependent prediction/correction updates, generally with time-varying gains before steady state. Because the dynamics are coupled and oscillatory and controls are consequential, a plain running average is not an established approximation to that filter. Environment structure, model capacity, and optimization all influence the comparison below.

We train two models on the same data with the same next-observation objective: a tiny causal transformer with one self-attention block, and a tiny diagonal SSM with a stable, input-independent learned recurrence (a time-invariant member of the family, since its decay, input matrix, and output matrix do not depend on the token, unlike the selective SSMs described above). Then we compare one-step accuracy against recursive rollout error under held-out action sequences, distinguishing open-loop prediction quality from the compounding behavior an agent would experience. Keeping the models tiny is a deliberate methodological choice: at roughly 3,300 parameters for the transformer and 1,200 for the SSM, we can inspect the mechanisms directly. Their capacities still differ, so the comparison does not isolate architecture from scale.

First, the system and dataset. We simulate trajectories of

st+1=Ast+But+wt,yt+1=Cst+1+vt+1,s_{t+1} = A s_t + B u_t + w_t, \qquad y_{t+1} = C s_{t+1} + v_{t+1},

where:

  • st∈R2s_t \in \mathbb{R}^2: the latent state, hidden from the learner
  • utu_t: the scalar control input chosen by the experimenter
  • yty_t: the noisy scalar observation
  • A,B,CA, B, C: the transition, input, and observation matrices, matching the system used in the simulation code below
  • wtw_t: process noise added to the state transition
  • vt+1v_{t+1}: observation noise added to the sensor reading at time t+1t+1

The observation matrix CC projects the two-dimensional state onto a single scalar with a fixed linear combination of the two components, so the observation is a lossy, noise-corrupted shadow of the state. The eigenvalues of AA have magnitude slightly below one, so the latent dynamics are stable and gently contract, and the off-diagonal entries couple the two channels so that neither component evolves independently. Tokens are (yt,ut)(y_t, u_t) pairs and the target at position tt is yt+1y_{t+1}, so every model is trained with teacher forcing under the causal objective from the previous section. Position 0 is a start-of-sequence exception: the simulator never emits y0y_0, so the first token carries a placeholder zero observation paired with u0u_0: it is (0,u0)(0, u_0), not a real observation pair, and genuine observation-control pairs begin at position 1.

In[4]:
Code
import numpy as np
import torch
import torch.nn as nn

torch.manual_seed(0)
rng = np.random.default_rng(0)
A_sys = np.array([[0.97, 0.10], [-0.10, 0.96]])
B_sys = np.array([[0.6], [0.1]])
C_sys = np.array([[1.0, 0.6]])
T = 32


def simulate(n_traj, rng):
    us = rng.normal(size=(n_traj, T, 1))
    xs = np.zeros((n_traj, T + 1, 2))
    ys = np.zeros((n_traj, T + 1, 1))
    for t in range(T):
        xs[:, t + 1] = (
            xs[:, t] @ A_sys.T
            + us[:, t] * B_sys.T
            + rng.normal(0, 0.02, size=(n_traj, 2))
        )
        ys[:, t + 1] = xs[:, t + 1] @ C_sys.T + rng.normal(
            0, 0.1, size=(n_traj, 1)
        )
    return ys, us


train_ys, train_us = simulate(512, rng)
test_ys, test_us = simulate(128, rng)


def make_tensors(ys, us):
    x = torch.tensor(
        np.concatenate([ys[:, :T], us], axis=2), dtype=torch.float32
    )
    target = torch.tensor(ys[:, 1:], dtype=torch.float32)
    return x, target


x_train, y_train = make_tensors(train_ys, train_us)
x_test, y_test = make_tensors(test_ys, test_us)

Apart from the zero start marker, each token carries a scalar observation and its aligned action; the target is the next observation. Optimal conditional prediction can use history without recovering the hidden state exactly, and fresh process and sensor noise prevent perfect forecasts. Training and test trajectories use the same simulator and independent control/noise laws. Recursive evaluation changes observation feedback after its prefix; its start position and prefix-length distribution also differ from the pooled all-position teacher-forced score. We therefore compare conditioning regimes without claiming to isolate every causal source of their difference.

Next, the two architectures. The transformer uses a single-head causal attention block, learned positional embeddings, a feed-forward sublayer, and a linear head. The SSM uses a real diagonal recurrence with input-independent BB and CC. We clamp each sigmoid decay to [ϵ,1−ϵ][\epsilon,1-\epsilon], with ϵ=10−4\epsilon=10^{-4}, so sigmoid saturation cannot produce a unit multiplier in this float32 implementation. With bounded finite writes, the uniformly contractive recurrence has a bounded state in exact arithmetic. Finite-precision overflow is still possible at extreme scales; the bound is not a guarantee for other dtypes, unbounded inputs, nonfinite parameters, or the entire training process. A learned skip connection passes the current embedding to the output without routing it through recurrent memory.

In[5]:
Code
class TinyTransformer(nn.Module):
    def __init__(self, d_in=2, d_model=16, nhead=1, d_ff=32, max_len=64):
        super().__init__()
        self.embed = nn.Linear(d_in, d_model)
        self.pos = nn.Parameter(torch.randn(1, max_len, d_model) * 0.02)
        self.attn = nn.MultiheadAttention(d_model, nhead, batch_first=True)
        self.mlp = nn.Sequential(
            nn.Linear(d_model, d_ff), nn.GELU(), nn.Linear(d_ff, d_model)
        )
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.head = nn.Linear(d_model, 1)

    def forward(self, x):
        L = x.size(1)
        h = self.embed(x) + self.pos[:, :L]
        mask = torch.triu(torch.ones(L, L, dtype=torch.bool), diagonal=1)
        a, w = self.attn(
            h,
            h,
            h,
            attn_mask=mask,
            need_weights=True,
            average_attn_weights=True,
        )
        h = self.norm1(h + a)
        h = self.norm2(h + self.mlp(h))
        return self.head(h), w


class TinySSM(nn.Module):
    def __init__(self, d_in=2, d_state=16, d_model=32):
        super().__init__()
        self.embed = nn.Linear(d_in, d_model)
        self.logit_decay = nn.Parameter(torch.full((d_state,), 2.2))
        self.B = nn.Parameter(torch.randn(d_state, d_model) * 0.1)
        self.C = nn.Parameter(torch.randn(d_model, d_state) * 0.1)
        self.skip = nn.Parameter(torch.zeros(d_model))
        self.head = nn.Linear(d_model, 1)

    def forward(self, x):
        z = self.embed(x)
        decay = torch.sigmoid(self.logit_decay).clamp(1e-4, 1 - 1e-4)
        h = torch.zeros(z.size(0), self.B.size(0))
        outs = []
        for t in range(z.size(1)):
            h = decay * h + z[:, t] @ self.B.T
            outs.append(h @ self.C.T + self.skip * z[:, t])
        return self.head(torch.stack(outs, dim=1)), None


transformer = TinyTransformer()
ssm = TinySSM()

A few implementation details connect directly to the chapter's formalism. In the transformer, the mask is built with torch.triu above the diagonal, so position ii is forbidden from attending to positions j>ij > i, the causal constraint rendered as a boolean matrix. The forward method returns the attention weights as well as the predictions, which we will use later for the diagnostic plot; average_attn_weights=True averages over heads into a single weight matrix; the model as defined uses a single head (nhead=1), so this averaging is a no-op and the returned matrix is that head's attention directly. In the SSM, the loop over time steps is the explicit recurrence ht=Aˉht−1+Bˉxth_t = \bar{A} h_{t-1} + \bar{B} x_t, written out step by step for clarity rather than hidden inside a parallel scan; on this short sequence the loop is harmless, but on longer sequences, parallel scan or convolution can avoid this Python-level sequential loop. For fixed state size, a work-efficient scan has linear total work and logarithmic parallel depth, while FFT convolution takes O(Tlog⁡T)O(T\log T) work. Both models are small (roughly 3,300 and 1,200 parameters respectively), but their unequal capacities remain a confound. Both use full-batch Adam and the same learning rate and epoch count; matching that recipe does not guarantee equally effective optimization.

In[6]:
Code
def train_model(model, x, target, epochs=80, lr=3e-3):
    opt = torch.optim.Adam(model.parameters(), lr=lr)
    losses = []
    for _ in range(epochs):
        opt.zero_grad()
        pred, _ = model(x)
        loss = torch.mean((pred - target) ** 2)
        loss.backward()
        opt.step()
        losses.append(loss.item())
    return losses


loss_tr = train_model(transformer, x_train, y_train)
loss_ssm = train_model(ssm, x_train, y_train)

with torch.no_grad():
    pred_tr, _ = transformer(x_test)
    pred_ssm, _ = ssm(x_test)
one_step_tr = torch.mean((pred_tr - y_test) ** 2).item()
one_step_ssm = torch.mean((pred_ssm - y_test) ** 2).item()
Out[7]:
Console
final train loss  transformer: 0.06859   SSM: 0.05490
one-step test MSE transformer: 0.06768
one-step test MSE SSM:         0.05626

Both models learn a useful one-step predictor in this run; the printed test errors are measured rather than assumed. The observation-noise variance is 0.12=0.010.1^2=0.01, but that is not the full achievable one-step error: process noise and uncertainty about the hidden state also matter. We do not implement a Kalman or fitted linear baseline here, so these two scores do not establish how close either model is to optimal. The environment has coupled, oscillatory dynamics, while our SSM has only real positive decay channels; it is not the exact model class for this system. To examine recursive prediction, we warm-start each model with the start token (0,u0)(0,u_0) and the first genuine observation token (y1,u1)(y_1,u_1), preserving their training positions. The first forecast targets y2y_2. Each subsequent token pairs the predicted observation at time tt with the known control utu_t, and the prediction is scored against the raw held-out observation at time t+1t+1. After the warm start, no new real observation enters the prefix.

In[8]:
Code
def rollout_errors(model, y_true, u_seq, horizon=16, start=1):
    """Forecast y[start+1:start+horizon+1] from the recorded prefix through start.

    y_true: raw (N, T+1, 1) observations, not shifted training targets.
    u_seq: (N, T, 1) controls. Token t is (y_t, u_t).
    """
    if y_true.ndim != 3 or u_seq.ndim != 3:
        raise ValueError("Expected batched observation and control sequences")
    if y_true.shape != (u_seq.shape[0], u_seq.shape[1] + 1, 1):
        raise ValueError("Use raw T+1 observations, not shifted targets")
    if (
        u_seq.shape[2] != 1
        or start < 0
        or horizon < 1
        or start + horizon > u_seq.shape[1]
    ):
        raise ValueError("Forecast must stay inside the control sequence")
    observations = torch.as_tensor(y_true, dtype=torch.float32)
    controls = torch.as_tensor(u_seq, dtype=torch.float32)
    prefix = torch.cat(
        [observations[:, : start + 1], controls[:, : start + 1]], dim=2
    )
    errs = np.zeros(horizon)
    with torch.no_grad():
        for step in range(horizon):
            t = start + step
            out, _ = model(prefix)
            y_next = out[:, -1:, :]
            errs[step] = torch.mean(
                (y_next - observations[:, t + 1 : t + 2]) ** 2
            ).item()
            if step + 1 < horizon:
                token = torch.cat([y_next, controls[:, t + 1 : t + 2]], dim=2)
                prefix = torch.cat([prefix, token], dim=1)
    return errs


horizon = 16
rollout_tr = rollout_errors(transformer, test_ys, test_us, horizon)
rollout_ssm = rollout_errors(ssm, test_ys, test_us, horizon)
print("rollout MSE transformer:", np.round(rollout_tr, 4))
print("rollout MSE SSM:", np.round(rollout_ssm, 4))
Out[8]:
Console
rollout MSE transformer: [0.0295 0.0419 0.0489 0.0524 0.0743 0.0843 0.1025 0.1374 0.1634 0.1697
 0.2057 0.2134 0.1962 0.1799 0.1963 0.198 ]
rollout MSE SSM: [0.0415 0.0664 0.0871 0.1058 0.115  0.1282 0.108  0.126  0.1089 0.1102
 0.1126 0.0997 0.0753 0.0713 0.0564 0.0639]

Two details matter for interpreting this procedure. The warm start consists of the zero start marker and the first genuine observation, each paired with its aligned control; later observation components are predictions. Known controls remain aligned with the timestep of each token. Thus the experiment changes observation feedback after the prefix without shifting the initial token positions or pairing observations with the wrong actions.

We also inspect how the trained transformer distributes attention across temporal lags. To avoid mixing query positions with different available context lengths, every example contributes only its final query, which can access all 32 tokens. We compare the mean weights with uniform attention over that same context. This is a descriptive memory diagnostic, not proof that the model performs Bayesian filtering or uses the most informative observations.

In[9]:
Code
with torch.no_grad():
    _, attn = transformer(x_test)  # (N, L, L), averaged over heads


def matched_query_lag_weights(weights):
    """Mean weights at the final query, ordered from lag 0 to lag L-1."""
    if (
        weights.ndim != 3
        or weights.shape[0] == 0
        or weights.shape[1] != weights.shape[2]
        or weights.shape[1] == 0
    ):
        raise ValueError(
            "Expected nonempty (batch, length, length) attention weights"
        )
    return weights[:, -1, :].mean(dim=0).flip(0).detach().cpu().numpy()


L = attn.size(-1)
lag_weights = matched_query_lag_weights(attn)
uniform_lag_weights = np.full(L, 1.0 / L)

At the final query i=L−1i=L-1, lag kk selects key j=L−1−kj=L-1-k. Reversing that query's key axis places self-attention at lag zero, and averaging across held-out sequences keeps query length fixed. The complete LL-lag profile sums to one up to numerical error. The plot displays only its first eight entries, not a renormalized eight-token distribution. Its dashed reference is 1/L1/L, uniform attention over all available tokens.

Pooling all query positions would introduce a baseline effect: even uniform causal attention has weights 1/(i+1)1/(i+1) at query ii, so averaging its eligible pairs at each lag produces a declining curve. The matched-query construction avoids that particular confound. We can now ask whether this final-query profile favors recent tokens relative to uniform attention, while remembering that learned values, residual paths, and other components also determine predictions.

Out[10]:
Visualization
Eight lag-weight bars for queries with equal context length, compared with a horizontal uniform-attention reference.
Mean attention weight at the final query of each held-out sequence, plotted by lag. Every query has 32 available tokens; the dashed line is uniform attention over that same context. Only the first eight lags are shown. Lag zero is self-attention, and this profile alone does not establish belief tracking.

The environment's coupled oscillatory transition is not exactly representable by this real positive-decay SSM. The model can still fit useful finite-horizon predictions, but an observed advantage would not prove an exact model-class match. Nor does this experiment isolate architecture alone: the models have different parameter counts and parameterizations, and identical optimizer settings need not suit them equally. It is one controlled data-generating task and one training seed, not evidence of a consistent ranking across environments.

The two rollout curves below plot recursive open-loop MSE against horizon, with each model’s all-position teacher-forced MSE as a dashed reference.

Out[11]:
Visualization
Transformer and SSM recursive forecast errors across sixteen horizons, with dashed all-position teacher-forced error references.
Recursive open-loop MSE after the start token (0, u0) and first observation token (y1, u1). Dashed lines show teacher-forced MSE averaged over all test positions; they are descriptive references, not horizon-matched lower bounds.

These rollout curves measure prediction error after genuine observations stop arriving. Growth can reflect both model error and irreducible multi-step uncertainty from process noise. The dashed lines summarize teacher-forced error over all test positions; they are not horizon-matched noise floors, so a crossing is a descriptive comparison rather than a theorem about compounding. Both models condition on their own predicted observations after the warm start. The transformer can still attend to the supplied start token and first observation, but it cannot retrieve later observations that were never supplied. Inspect the printed curves for this run rather than assuming monotonic growth or a stable ordering between architectures.

Separating the quality axes prevents overreading this experiment. Teacher-forced test MSE measures one-step predictive fidelity, and the recursive curves measure a different conditioning regime. Neither deterministic point predictor supplies a calibrated uncertainty distribution, so we have not evaluated uncertainty quality. No controller acts on the forecasts, so we have not measured decision usefulness either. Good performance on either plotted error metric does not settle those remaining questions.

The attention-by-lag plot can suggest hypotheses about retrieval or integration, but it cannot uniquely locate a failure. Query formation, key/value representations, residual paths, and dynamics layers can produce similar visible weight patterns. Test a suspected mechanism by intervening on relevant tokens, probing state information, or ablating components before selecting a remedy. Here the model explicitly returns weights, making inspection convenient; in other implementations requesting them can add memory or prevent use of an optimized attention path.

Limitations and Impact

Attention and structured recurrence offer different ways to represent history in learned predictors. They did not invent long-horizon partially observable control: classical filtering and belief-space planning, as well as pre-transformer external-memory networks such as Neural Turing Machines, already addressed aspects of it. Modern transformer deployments demonstrate large context capacities (for example, Llama 3.1's reported 128K context), but capacity is not a guarantee of useful world-model memory. Structured SSMs connect learned sequence layers with linear-system analysis; hybrids combine mechanisms without removing their task and resource dependencies.

Several limitations matter when using these architectures.

  • Recursive prediction. Our two models train with recorded observations and are evaluated with self-fed predictions. No architecture alone guarantees accurate forecasts under model mismatch, but exact or contractive dynamics need not exhibit growing model error. Attention can read retained real context during imagination while newer tokens are synthetic; whether that helps depends on learned representations and queries. Scheduled sampling and suitable rollout-aware objectives can reduce some conditioning mismatch. Their statistical interpretation must be assessed separately: not every multistep objective sacrifices a valid likelihood.
  • Retained information. Attention cannot directly read absent KV entries, although summaries or other representations may preserve related information. An append-only cache grows with tokens; bounded windows need not grow without bound. Fixed-width finite-precision recurrence may merge histories requiring different predictions or actions. A sufficient task state avoids that problem, whereas more training data alone cannot reverse a distinction already absent from the representation.
  • Hybrid configuration. Layer ratios, state widths, sharing, and cache policies add design choices. Complexity and stability analysis constrain some choices but do not identify the best task-specific configuration. Kernel and debugging support must be checked for the chosen implementation rather than assumed uniformly mature or immature.

Architecture choice must be evaluated against intended use. Memory probes and closed-loop environment tests complement one-step and recursive forecasts. Point MSE, as used here, scores a point prediction. Negative log-likelihood instead scores a predictive distribution: it is sensitive to assigned probabilities, though one aggregate value does not separately diagnose calibration, representation sufficiency, and decision utility. A planner can exploit poorly modeled regions outside the logged distribution. Likelihood directly supervises observed contexts and targets; extrapolation elsewhere depends on learned parameters and inductive biases, without a general off-support calibration guarantee. These issues motivate Part VI and Part XII.

Summary

The chapter connects attention-based predictive memory, structured recurrence, and selected hybrids.

  • Attention forms query-dependent weighted readouts from retained token representations. Neither the memory nor the readout is necessarily lossless or statistically sufficient. At fixed dimensions, dense sequence attention has quadratic pairwise arithmetic, uncompressed KV storage is linear in context, and cached per-query attention work is linear in context.
  • Causal masking supports parallel next-observation supervision only with aligned, leakage-free inputs and targets. Joint action supervision needs an input path that does not already contain the action being predicted. Observational action conditioning requires additional causal and support assumptions before it is used for intervention forecasts.
  • Fixed-coefficient linear SSM layers admit recurrent, scan, or convolutional evaluation. Input-selective affine recurrences generally do not have one fixed convolution kernel. Stability claims require the appropriate contraction, forcing, and numerical conditions. HiPPO's optimality concerns its specified weighted projection dynamics, not arbitrary learned fixed recurrences.
  • Hybrids combine attention and recurrence or place transformer dynamics inside a stochastic latent world model. Integration versus event retrieval is a useful testing hypothesis, not an exclusive allocation of capabilities.

In the experiment, both models learn finite one-step errors, and recursive errors vary with horizon without a fixed ordering or monotonic-growth guarantee. Unequal capacities and optimization remain confounders. The matched-query attention plot compares learned weights with uniform attention at equal context length; it does not prove a memory mechanism.

The methodological lesson is to compare predictions under the conditioning and actions where they will be used. One-step loss, recursive error, and attention profiles provide complementary diagnostics, not a complete assessment of state representation, uncertainty, or decision usefulness. Those require additional probes, probabilistic evaluation, and controllers tested in the environment. Our short smooth-dynamics task also leaves the opening's distant-event memory problem untested. The next chapter develops autoregressive token world models, including video and action representations, with these distinctions still in force.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about transformers, neural state-space architectures, and their role in world models.

Transformers and Neural State-Space Architectures

Question 1 of 80 of 8 completed
In scaled dot-product attention, why are the dot products between queries and keys divided by dk?\sqrt{d_k}?

Comments

No comments yet. Be the first to share your thoughts!

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026transformersneural, author = {Michael Brenndoerfer}, title = {Transformers and Neural State-Space Architectures}, year = {2026}, url = {https://mbrenndoerfer.com/writing/transformers-neural-state-space-architectures-world-models}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-10-15} }
APAAcademic
Michael Brenndoerfer (2026). Transformers and Neural State-Space Architectures. Retrieved from https://mbrenndoerfer.com/writing/transformers-neural-state-space-architectures-world-models
MLAAcademic
Michael Brenndoerfer. "Transformers and Neural State-Space Architectures." 2026. Web. October 15, 2026. <https://mbrenndoerfer.com/writing/transformers-neural-state-space-architectures-world-models>.
CHICAGOAcademic
Michael Brenndoerfer. "Transformers and Neural State-Space Architectures." Accessed October 15, 2026. https://mbrenndoerfer.com/writing/transformers-neural-state-space-architectures-world-models.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Transformers and Neural State-Space Architectures'. Available at: https://mbrenndoerfer.com/writing/transformers-neural-state-space-architectures-world-models (Accessed: October 15, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Transformers and Neural State-Space Architectures. https://mbrenndoerfer.com/writing/transformers-neural-state-space-architectures-world-models

About the author

Continue with the full handbook

This chapter is part of World Models Handbook. Use the handbook page to browse the complete table of contents and continue reading in sequence.

Explore World Models Handbook
Newsletter

Stay up to date

Get articles, book updates, and news delivered to your inbox.

No spam, unsubscribe anytime.

or

Join the community

Sign in to remove popups, track your reading progress, and join the discussion.