---
title: Stochastic Attention (SA)
url: https://www.emergentmind.com/topics/stochastic-attention-sa
type: topic
---

# Stochastic Attention (SA)

Stochastic Attention (SA) denotes a family of attention mechanisms in which the selection, weighting, routing, or dynamics of attention are treated as random variables rather than as purely deterministic functions. In the cited literature, this includes latent-variable glimpse policies for recurrent attention, simplex-constrained random attention weights learned in Bayesian or variational form, data-adaptive sparse graph sampling, permutation-based randomized routing for linear-time attention, Sequential Monte Carlo state-space transformers, Langevin samplers on modern Hopfield energies, continuous-time stochastic-logit formulations, and hardware-oriented stochastic spiking implementations [1509.06812] [2010.10604] [2210.15541] [2604.00754] [2603.06875] [2605.26061]. The term is therefore polysemous: it refers not to a single canonical layer, but to a recurring design principle in which uncertainty or randomized structure is injected into attention itself.

## 1. Terminological scope and recurring structure

Across the cited record, SA is best understood as a family resemblance rather than a single architecture. The common element is explicit stochasticity over the object that attention manipulates: glimpse trajectories, simplex weights, sparse masks, latent attention states, query trajectories, logits, or routing permutations. What changes from paper to paper is the role of that stochasticity: inference, regularization, uncertainty quantification, efficiency, or generation.

| Family | Stochastic object | Representative mechanism |
|---|---|---|
| Latent glimpse attention | $z=(z_1,\dots,z_N)$ | Recurrent glimpses with a recognition network |
| Bayesian/variational attention | $s_i$ or $w_i$ | Normalize sampled positive weights to the simplex |
| Sparse or routed transformer attention | $M$ or $\sigma$ | Sampled graphs or random permutations |
| State-space attention | $\zeta_t=\{q(t),\kappa(t),v(t),z(t)\}$ | Sequential Monte Carlo posterior approximation |
| Hopfield/Langevin attention | $q$ or $\xi$ | Sampling from $p_\beta \propto \exp(-\beta E)$ |
| Continuous-time or hardware SA | $X_t$, clocks, spike streams | OU-SDE logits, clock meeting kernels, Bernoulli bit-streams |

A frequent source of confusion is that stochastic attention is not synonymous with noisy softmax. In some formulations the stochastic quantity is outside the softmax, as with latent glimpses or graph masks; in others it is the pre-normalized weight vector itself; in still others the stochasticity appears in a state-space model, a Langevin diffusion, or an SDE over logits. Another common misunderstanding is that SA always increases inference cost. Some variants are training-time devices that revert to deterministic computation at test time, while others are explicitly training-free or are designed to preserve an $O(nw)$ or linear-in-edges budget [1904.09853] [2604.00754] [2603.14717].

## 2. Latent glimpse variables and wake–sleep recurrent attention

A central early formulation treats attention as a latent-variable model over glimpses. In the Wake–Sleep Recurrent Attention Model, the observed input is $x$, the target is $y$, and the latent random variables $z=(z_1,\dots,z_N)$ encode a sequence of glimpse locations, scales, or related actions. At each step $n$, the model samples $z_n \sim p(z_n \mid z_{1:n-1}, x; \theta)$, extracts a local observation $o_n=g(z_n,x)$, processes it with a recurrent prediction network, and after $N$ glimpses emits $p(y \mid z_{1:N}, x; \theta)$. The joint conditional model is
$$
p(y,z \mid x;\theta)=p(z \mid x;\theta)\,p(y \mid z,x;\theta),
$$
while exact posterior inference for $p(z \mid x,y;\theta)$ is intractable, motivating a recurrent recognition network
$$
q(z \mid x,y;\phi)=\prod_{n=1}^N q(z_n \mid z_{1:n-1},x,y;\phi)
$$
that conditions additionally on the known target [1509.06812].

Wake–sleep training alternates two phases. In the wake phase, $\partial_\theta \ell(\theta)$ for $\ell(\theta)=\log p(y\mid x;\theta)$ is estimated with importance samples $z^m \sim q(z\mid x,y;\phi)$ and normalized importance weights
$$
w^m=\frac{p(z^m\mid x;\theta)\,p(y\mid z^m,x;\theta)}{q(z^m\mid x,y;\phi)}, \qquad \bar w^m=\frac{w^m}{\sum_i w^i}.
$$
The resulting estimator is
$$
\partial_\theta \ell(\theta) \approx \sum_{m=1}^M \bar w^m \left[\partial_\theta \log p(y\mid z^m,x;\theta)+\partial_\theta \log p(z^m\mid x;\theta)\right].
$$
In the sleep phase, the inference network is fit by minimizing $D_{\mathrm{KL}}(p(z\mid x,y;\theta)\,\|\,q(z\mid x,y;\phi))$, with importance-sampled gradient
$$
\partial_\phi D = -\sum_{m=1}^M \bar w^m \,\partial_\phi \log q(z^m\mid x,y;\phi).
$$
The method also uses control variates derived from identities such as $\mathbb E_q[(p(z)/q(z))\,\partial_\theta \log p(z)]=0$ and $\mathbb E_q[\partial_\phi \log q(z)]=0$ to reduce gradient variance [1509.06812].

The architectural instantiations in that work are concrete. For translated and scaled MNIST classification, the prediction network is a two-layer recurrent net with ReLU units; $z_n=(\text{location}\in\mathbb R^2,\text{scale}\in\{1,\dots,K\})$ is sampled as a Gaussian plus multinomial; $o_n$ is a crop of the $100\times 100$ image; and after $N=4$ glimpses the top recurrent layer outputs a softmax over $10$ classes. For Flickr8K caption generation, a pretrained CNN produces multiple feature maps at different resolutions, each glimpse selects both layer and spatial location, the selected feature vector is fed into an LSTM decoder, and the inference network additionally receives the previously generated word [1509.06812].

Empirically, the paper reports that on translated-and-scaled MNIST after $10\,\mathrm{M}$ updates with $M=5$ samples, the variational baseline without control variates yields $3.11\%$ error, WS-RAM without $q$ and without control variates yields $4.23\%$, WS-RAM+$q$ without control variates yields $2.59\%$, and with control variates the errors become $1.81\%$, $1.85\%$, and $1.62\%$ respectively. On Flickr8K, BLEU scores after convergence are reported as Variational: BLEU@1 $=62.3$, @2 $=41.6$, @3 $=26.9$, @4 $=17.2$, and WS-RAM+$q$: @1 $=61.1$, @2 $=40.4$, @3 $=26.9$, @4 $=17.8$. The reported significance is primarily computational: WS-RAM reaches similar or better performance in fewer updates, with improved effective sample size and reduced gradient variance [1509.06812].

## 3. Bayesian and variational stochastic weights

A second major line of work makes the attention weights themselves stochastic while preserving differentiability. In Bayesian Attention Modules, deterministic scores $e_i=f_\theta(q,k_i)$ and softmax-normalized coefficients $\alpha_i=\exp(e_i)/\sum_j \exp(e_j)$ are replaced by positive random variables $s_i \sim q_\phi(\mathbf s \mid q,K)$, followed by simplex normalization
$$
\alpha_i=\frac{s_i}{\sum_{j=1}^N s_j}.
$$
The distributions are reparameterizable, with examples including a Log-normal parameterization
$$
s_i=\exp(\mu_{\phi,i}+\sigma_{\phi,i}\varepsilon_i), \qquad \varepsilon_i\sim\mathcal N(0,1),
$$
and a Weibull parameterization
$$
s_i=\lambda_{\phi,i}(-\ln U_i)^{1/k_{\phi,i}}, \qquad U_i\sim \mathrm{Uniform}(0,1).
$$
A Bayesian prior $p_\psi(\mathbf s\mid q,K)$ is introduced, either factorized or contextual, and training maximizes the ELBO
$$
\mathcal L(\phi,\psi,\theta)
=\mathbb E_{q_\phi(\mathbf s\mid x)}[\log p_\theta(y\mid x,\alpha(\mathbf s))]
-\mathrm{KL}(q_\phi(\mathbf s\mid x)\,\|\,p_\psi(\mathbf s\mid x)),
$$
with sigmoid KL annealing. This formulation was used in GAT, MCAN, Att2in, neural machine translation, and pretrained Transformers, with reported gains that include $+0.8$ BLEU on IWSLT’14 and consistent $+0.5$ to $+1.2$ absolute gains across $8$ GLUE tasks and SQuAD-1.1/2.0 for ALBERT fine-tuning. The contextual prior variants LC and WC are reported to outperform factorized variants, and the contextual Weibull posterior/prior WC is described as the strongest among the tested choices [2010.10604].

Neural Processes with stochastic attention adapt this idea to context selection. Here the local attention weights for target $x_i$ are latent variables $w_i$, obtained by sampling unnormalized scores $\hat w_{ij} \sim \mathrm{Weibull}(k,\lambda_i)$, normalizing them to the simplex, and computing
$$
r_i=\sum_j w_{ij}v_j.
$$
The prior is $\mathrm{Gamma}(\alpha_i,\beta)$, yielding a closed-form KL divergence between Weibull and Gamma. The task-level ELBO includes both the usual global latent term and a local stochastic-attention regularizer,
$$
\mathcal L
=\mathbb E_{q_\phi(z\mid X,Y)\,q_\phi(W\mid X,X_c)}
\Bigl[\sum_{i=1}^N \log p_\theta(y_i\mid x_i,z,r_i)\Bigr]
-\mathrm{KL}\bigl(q_\phi(z\mid X,Y)\,\|\,q_\phi(z\mid X_c,Y_c)\bigr)
-\sum_{i=1}^N \mathrm{KL}\bigl(q_\phi(w_i\mid x_i,X_c)\,\|\,q_\phi(w_i\mid X_c)\bigr).
$$
The paper further states that the negative ELBO upper-bounds $-I(y_i;D\mid x_i)+I(Z,x_i\mid D)$, thereby encouraging genuine context use rather than shortcut memorization. Reported results include $1$D regression context-set log-likelihood $\approx 1.37$ versus ANP $\approx 0.25$, target log-likelihood under periodic shift $\approx -0.61$ versus ANP $\approx -0.95$, predator–prey real-data target log-likelihood $\approx -1.77$ versus ANP $\approx -3.74$, CelebA context log-likelihood $\approx 4.12$ versus best baseline $\approx 3.58$, and MovieLens-100k RMSE $\approx 0.895$ versus ANP $\approx 0.909$ [2204.05449].

These Bayesian and variational formulations make stochasticity serve regularization and uncertainty quantification rather than routing or efficiency. A plausible implication is that, in this branch of the literature, SA is less about sparse computation than about replacing a single deterministic attention map by a posterior distribution over admissible maps.

## 4. Transformer-era stochasticity: latent states, sampled graphs, and randomized routing

In the Monte Carlo Transformer, queries, keys, values, and attention vectors are the latent stochastic states of a state-space model. The latent state is
$$
\zeta_t \coloneqq \{q(t),\kappa(t),v(t),z(t)\},
$$
with Gaussian transitions for $q(t)$, $\kappa(t)$, and $v(t)$, random attention weights
$$
\pi(t+1)=\mathrm{softmax}[q(t)\cdot K(t+1)^\top/\sqrt r],
$$
and a stochastic attention vector
$$
z(t+1)=\sum_{s=1}^L \pi_s(t+1)\,v(t+1-s)+\Sigma_z^{1/2}\epsilon_z(t+1).
$$
The observation model is $X_t=G_{\eta_{\mathrm{obs}}}(z(t))+\epsilon_t$, and posterior inference uses Sequential Monte Carlo with weighted particles, resampling, propagation, and importance weighting. Gradient estimation uses Fisher’s identity, and after training the predictive distribution is represented as a mixture over particles rather than as a single-point estimate. The reported benefits are full predictive distributions, well-calibrated uncertainty, and the ability to capture multimodality and heteroscedasticity; the reported drawbacks are extra computational cost at training and classical path-degeneracy. Empirically, the paper states that on synthetic AR models only the SMC Transformer recovers the true variance, and on five real-world time series it achieves best PICP $\approx 95\%$ with narrow MPIW, outperforming MC-dropout LSTM/Transformer and Bayesian LSTM in nearly every setting [2007.08620].

SBM-Transformer introduces stochastic attention by endowing each head with a mixed-membership Stochastic Block Model. For queries $i$ and keys $j$ with memberships $\pi_i$ and $\pi'_j$ and block matrix $B$, the edge probability is
$$
p(A_{ij}=1)=\pi_i^\top B\,\pi'_j.
$$
A sparse bipartite graph $M$ is then sampled with the fastRG algorithm and used as an attention mask in
$$
\mathrm{SA}(Q,K,V;M)=\bigl[M\odot \mathrm{softmax}(QK^\top/\sqrt{d_h})\bigr]V.
$$
Because the mask is discrete, training uses a Straight-Through Estimator, with the backward pass treating the sampled mask as its probability matrix. The paper emphasizes that forward and backward cost are linear in the realized number of edges, and that the model is a universal approximator in expectation. On Long Range Arena, the model is reported to outperform or match prior efficient models and even full attention on five tasks while using only $18$–$30\%$ of all possible edges on average at test time; on GLUE its average mask density is $\simeq 13.5\%$ [2210.15541].

A distinct efficiency-oriented formulation appears in the connectome-inspired SA for sliding-window attention. Here a uniform random permutation $\sigma\in S_n$ is applied to the token sequence, standard sliding-window attention of width $w$ is computed in permuted space, and the output is restored to the original order:
$$
\tilde Q=P_\sigma Q,\quad \tilde K=P_\sigma K,\quad \tilde V=P_\sigma V,\quad
Y^{\mathrm{sto}}=P_{\sigma^{-1}}\mathrm{SWA}(\tilde Q,\tilde K,\tilde V;w).
$$
This makes each token attend to a random neighborhood that uniformly covers the sequence, while preserving per-layer complexity $O(nw)$. The receptive-field analysis states that independently sampled permutations yield exponentially growing receptive fields, achieving full sequence coverage in $O(\log_w n)$ layers versus $O(n/w)$ for SWA. In $360$M-parameter decoder-only pre-training, SA+SWA with $w=256$ yields the best average zero-shot accuracy, $35.9$, versus $34.9$ for full attention, $35.1$ for SWA, and $34.3$ for pure SA. In training-free inference on Qwen3-8B and Qwen3-30B-A3B, SA is reported to recover full-attention quality faster than SWA and to match or exceed Mixture of Block Attention at comparable budgets; for example, on Qwen3-30B at $w_{\mathrm{eff}}=64$, SA gives $73.2$ versus SWA $47.0$, MoBA $66.3$, and full attention $77.4$. Profiling on A100 reports, for SA with $w=256$ versus full attention, $5.4$ ms versus $8.0$ ms at $n=2$K, $15.2$ ms versus $99.7$ ms at $8$K, and $52.8$ ms versus $1{,}477$ ms at $32$K [2604.00754].

Taken together, these transformer-era variants distribute stochasticity over different structural degrees of freedom: latent hidden states, sampled sparse edges, or randomized token neighborhoods. This suggests that in transformer research SA has become a mechanism for trading deterministic all-to-all structure for adaptive inference, uncertainty-aware prediction, or linear-time global communication.

## 5. Training-free stochastic attention from Hopfield energies

A different branch of the literature reinterprets attention itself as energy-based retrieval on a modern Hopfield landscape. With query $q\in\mathbb R^d$, key matrix $K=[k_1,\dots,k_K]$, inverse temperature $\beta>0$, and
$$
E(q)=\frac12\|q\|^2-\frac1\beta \log\sum_j \exp(\beta k_j^\top q),
$$
the gradient is
$$
\nabla_q E(q)=q-K\,\mathrm{softmax}(\beta K^\top q).
$$
A single unit gradient-descent step therefore recovers softmax attention, and adding Gaussian noise yields Unadjusted Langevin sampling from
$$
p_\beta(q)\propto \exp(-\beta E(q)),
$$
with update
$$
q_{t+1}=(1-\alpha)q_t+\alpha Xa_t+\sqrt{2\alpha/\beta}\,\epsilon_t,
$$
where $a_t=\mathrm{softmax}(\beta X^\top q_t)$ and $\epsilon_t\sim \mathcal N(0,I)$. The paper distinguishes a retrieval regime, as $T\to 0$ and $\beta\to\infty$, from a generation regime at higher temperature, and proposes an SNR-based temperature rule. On MNIST digit “3”, in the generation regime $(\beta=200,\mathrm{SNR}=0.036)$ SA achieves novelty $N=0.548\pm 0.002$ and diversity $\bar D=0.885\pm 0.002$, compared with a VAE baseline at $N=0.214$ and $\bar D=0.441$; the abstract summarizes this as $2.6$ times more novel and $2.0$ times more diverse than the best learned baseline. On Simpsons faces at $d=4096$, SA yields $N=0.159\pm 0.000$ and $\bar D=0.293\pm 0.001$, versus bootstrap $N=0.000$ and $\bar D=0.117$ [2603.06875].

The protein-sequence variant applies the same principle to a multiple-sequence alignment. Seed sequences are one-hot encoded, centered, projected by PCA to $d$ dimensions, normalized to unit norm as memories $m_k$, and collected in $X=[m_1,\dots,m_K]$. The energy becomes
$$
E(\xi)=\frac12\|\xi\|^2-\frac1\beta \log\sum_{k=1}^K \exp(\beta m_k^\top \xi),
$$
with score
$$
\nabla_\xi \log p_\beta(\xi)=\beta\bigl(X\,\mathrm{softmax}(\beta X^\top \xi)-\xi\bigr).
$$
Sampling again uses the Langevin update
$$
\xi_{t+1}=(1-\alpha)\xi_t+\alpha X\,\mathrm{softmax}(\beta X^\top \xi_t)+\sqrt{2\alpha/\beta}\,\epsilon_t,
$$
followed by inverse PCA and argmax decoding at each sequence position. A distinctive feature is automatic temperature selection: the critical temperature is predicted from PCA dimension as
$$
\beta^* \simeq 1.57 + 0.28\sqrt d, \qquad R^2=0.97,
$$
and generation uses $\beta_{\mathrm{gen}}=\lceil 2\beta^*\rceil$. The computational cost is $O(dK)$ per Langevin step, with typical $d\approx 30$–$180$ and $K\approx 20$–$420$, each step costing $<1$ ms on a modern CPU, and $N_c=30$ chains with $T=5{,}000$ steps taking $0.2$–$4.6$ s for $150$ sequences. Across eight Pfam families, reported generation properties include amino-acid composition KL divergence to seed $<0.06$ in every family, PCA-space novelty in $[0.40,\dots,0.65]$, moderate identity $51$–$66\%$, and predicted structural plausibility by ESMFold and AlphaFold2; the abstract states that generated sequences fold more faithfully to canonical family structures than natural members in six of eight families [2603.14717].

These training-free Hopfield formulations are unusual within attention research because they replace learned score networks by closed-form energies whose gradients are exactly softmax attention maps. A plausible implication is that they blur the boundary between retrieval, sampling, and generation: deterministic attention appears as the zero-noise limit of a broader stochastic dynamics.

## 6. Continuous-time, alignment, hardware, and theoretical extensions

Several specialized variants extend stochastic attention beyond standard discrete-time transformer blocks. The Neuronal Stochastic Attention Circuit models each attention logit as an Ornstein–Uhlenbeck SDE
$$
dX_t=\kappa(u)\bigl(\phi(u)-X_t\bigr)\,dt+\psi(u)\,dW_t,
$$
with input-dependent $\kappa(u)=\mathrm{softplus}(f_\kappa(u))$, $\phi(u)=\tanh(f_\phi(u))$, and $\psi(u)=\mathrm{softplus}(f_\psi(u))$ produced by a sparse sensory–interneuron–command circuit derived from C. elegans Neuronal Circuit Policies wiring. The resulting Gaussian logits induce a logistic-normal distribution over attention weights after softmax. Training minimizes
$$
\mathcal L=\mathcal L_{\mathrm{NLL}}+\lambda \mathcal L_{\mathrm{reg}},
$$
where the second term is an epistemic-separation regularizer. Reported evaluations span irregular CT function approximation, multivariate regression, long-range forecasting, Industry 4.0 prognostics, and autonomous-vehicle steering, with examples including spiral-task MSE $=0.0002$, CRPS $=0.0095$, NLL $=-2.348$, and Jena-Climate MSE $=0.1675$, NLL $=-1.911$, CRPS $=0.1422$ [2605.26061].

Stochastic clock attention addresses monotonic alignment for continuous ordered sequences. It introduces learned nonnegative clocks $\lambda_s^X$ and $\lambda_t^Y$ for source and target, and derives attention as the meeting probability of these clocks under a Gaussian small-fluctuation approximation. The resulting score is
$$
\mathrm{Score}(s,t)=-\frac{(\lambda_s^x-\lambda_t^y)^2}{2\,\Sigma_{s,t}^2}+C,
$$
with normalized and unnormalized clock regimes for parallel and autoregressive decoding. In a Transformer text-to-speech setting on LJSpeech, the normalized-clock model at MPR $=6.0$ reports WER $=7.03\%$ and CER $=3.66\%$, compared with scaled dot-product attention at WER $=7.39\%$ and CER $=3.94\%$; in autoregressive decoding, SDPA largely fails with WER/CER $\approx 100\%$, whereas unnormalized-clock SCA yields WER $=66.5\%$ and CER $=48.5\%$ [2509.14678].

At the hardware end of the spectrum, Stochastic Spiking Attention converts normalized real-valued inputs into Bernoulli spike trains and implements attention products by AND gates in stochastic computing. The key identity is
$$
\mathbb E[x^t \land y^t]=\mathrm{norm}(a)\,\mathrm{norm}(b),
$$
which allows dot products and weighted sums to be approximated by simple binary logic. On CIFAR-10 with ViT-Small, $6$ encoder layers, $8$ heads per layer, INT8 weights, and $T=10$ time steps, the reported accuracies are Baseline ANN $83.66\%$, Spikformer SNN $83.41\%$, and SSA $83.53\%$. The FPGA implementation is reported at $0.0033$ ms and $1.47$ W versus GPU $0.159$ ms and $22.41$ W, corresponding to $48\times$ lower latency and $15\times$ lower power, while the ASIC projection gives $6.3\times$ compute-energy reduction and $1.7\times$ memory-access reduction versus the ANN baseline [2402.09109].

Stochasticity has also been injected into channel-attention pooling rather than token-to-token scoring. Stochastic Region Pooling replaces global average pooling during training by random square-region pooling, with SS-SRP and MS-SRP variants, but reverts to standard GAP at inference so that no extra test-time cost is incurred. On ImageNet with ResNet-50, the reported top-1/top-5 accuracies are $75.30\%/92.20\%$ for ResNet-50, $76.71\%/93.38\%$ for SE-ResNet-50, and $78.09\%/94.40\%$ for MS-SRP-D; on CUB-200-2011, one-stage ResNet-50 achieves $81.7\%$, SS-SRP-D $84.9\%$, and MS-SRP-D $85.6\%$ [1904.09853].

Finally, theoretical work on stochastic training establishes convergence guarantees for attention layers under mild regularization. For an empirical MSE attention loss with query, key, and value parameters, and for LoRA-factorized shallow networks, the corresponding Gibbs measure is shown to satisfy a Poincaré inequality. This implies that the SDE
$$
d\theta_t=-\nabla \tilde L(\theta_t)\,dt+\sqrt s\,dB_t
$$
converges geometrically to the Gibbs law, with expected excess loss bounded by an $O(s)$ equilibrium term plus an exponentially decaying transient, yielding $O(\log(1/\epsilon))$ time to $\epsilon$-optimality. The paper emphasizes that these results do not rely on assumptions on the data or the size of the architecture, beyond mild regularization [2605.07959].

Across these specialized variants, stochastic attention functions as a general modeling strategy rather than a fixed operator. It can encode uncertainty directly in logits, impose monotone alignment geometry, exploit Bernoulli hardware primitives, regularize channel descriptors, or support convergence analyses of stochastic optimization. The unifying theme is the relocation of attention from a deterministic weighting rule to a probabilistic object whose randomness is structured, parameterized, and task-dependent.

Source: https://www.emergentmind.com/topics/stochastic-attention-sa