Skip to content

Uncertainty, structured prediction, and causal learning · Uncertainty, structured prediction, and causal learning · UNC018 · Model

Attentive neural process (ANP)

Use attention to preserve target-specific information from a context set while retaining a global latent path for coherent uncertainty.

Needs a data type CodeSplash doesn't load yet Component demo, not a trained model CodeSplash's run and the reference's record

In CodeSplash

Running this needs images, audio, video, graphs or another data type CodeSplash doesn't load yet.

Availability
Needs a data type CodeSplash doesn't load yet
Code example
Component demo, not a trained model
Who ran it
CodeSplash's run and the reference's record
CodeSplash's run
The reference's example ran in Python and R here, and they agree.
The reference's record
Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

Use attention to preserve target-specific information from a context set while retaining a global latent path for coherent uncertainty. ANPs address the information bottleneck of using only one mean-aggregated context vector for every target. They are a distinct context-retrieval architecture within the neural-process family, not a renamed generic Transformer.

Question / hypotheses

Which context observations are useful for each target location, and what shared function uncertainty remains after observing them? Evaluate both local reconstruction and global sample variability on unseen functions.

Architecture / computational structure

A deterministic path encodes context pairs and cross-attends from target inputs to context keys/values. Self-attention can enrich context representations before aggregation. A latent path summarizes context into a distribution over shared z. The decoder combines target x, target-specific context representation and z to predict a likelihood.

Assumptions

Context sets must use consistent input coordinates and data semantics. Attention preserves permutation symmetry over the context when keys/values are permuted together, but positional features must not introduce arbitrary list-order dependence. Training tasks and context density must support the target use.

Formula / computational definition

For context keys K, values V and target queries Q, RT=softmax⁡(QKT/dk)VR_T=\operatorname{softmax}(QK^T/\sqrt{d_k})V in a dot-product convention, where dkd_k is the key dimension. Decode p(yj∣xj,RT,j,z)p(y_j\mid x_j,R_{T,j},z) and train with the neural-process variational likelihood-minus-KL objective. Multihead or other attention choices alter the parameterization, not the need to define the latent inference path.

Parameters and notation

Learned: context encoders, query/key/value projections, attention/output projections, latent encoder and decoder. Hyperparameters: heads, key/value dimensions, context size policy, latent dimension, likelihood scale floor, optimizer and Monte Carlo samples. Dense cross-attention costs O(|C||T|) score evaluations; self-attention adds context-quadratic work.

Fitting, fine-tuning, and adaptation

Condition on new context with weights fixed for ordinary adaptation. For domain transfer, train a decoder or attention projections first and then unfreeze encoders if validation warrants it. Re-evaluate both uncertainty and context-order invariance; changing coordinate units requires corresponding preprocessing and possible retraining.

How to use and calibrate

Compare to CNP and latent NP using identical task splits and context budgets. Examine target likelihood, context reconstruction, error versus context distance, and latency as context grows. Plot attention weights as a retrieval diagnostic, not as proof of causal importance.

Example application

Reconstruct an irregularly sampled physical field while each query attends most strongly to useful observed locations. Show target-specific attention maps together with several coherent latent-function samples.

Interpretation / pitfalls

Watch out

Good interpolation need not imply trustworthy extrapolation. Attention can concentrate on irrelevant or corrupted context; a deterministic path may dominate and leave the latent unused. Independent target noise should not be confused with coherent posterior function uncertainty.

Python and R code examples

Scope: Target-specific cross-attention and shared-latent decoder component with fixed projections. The context-permutation check verifies the set symmetry; it is not a complete trained ANP.

Dependencies / validation: use the shared NumPy/SciPy or base-R setup above. Python executed successfully with assertions; R reviewed but not executed.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Component demo, not a trained model — Target-specific cross-attention and shared-latent decoder component with fixed projections. The context-permutation check verifies the set symmetry; it is not a complete trained ANP.

Shared setup for this chapter
import numpy as np
from scipy.special import logsumexp, gammaln
from scipy.linalg import expm
from itertools import product

def rbf(a, b, ell=1.0):
    a, b = np.atleast_2d(a), np.atleast_2d(b)
    return np.exp(-np.sum((a[:, None, :] - b[None, :, :])**2, axis=2)/(2*ell**2))
xc=np.array([[-1.],[0.],[1.]]); yc=np.array([[-.6],[.1],[.8]])
xt=np.array([[-.5],[.7]]); K=np.column_stack([xc[:,0],xc[:,0]**2])
Q=np.column_stack([xt[:,0],xt[:,0]**2]); V=np.column_stack([yc[:,0],xc[:,0]*yc[:,0]])
def attend(k,v):
    scores=Q@k.T/np.sqrt(2); weights=np.exp(scores-logsumexp(scores,axis=1,keepdims=True))
    return weights@v,weights
r,w=attend(K,V); perm=np.array([2,0,1]); rp,_=attend(K[perm],V[perm])
z=.2; mean=r[:,0]+.1*r[:,1]+z*xt[:,0]
assert np.allclose(r,rp) and np.allclose(w.sum(axis=1),1)
print({'attention':w.tolist(),'target_means':mean.tolist(),'shared_latent':z})
R

Component demo, not a trained model — Target-specific cross-attention and shared-latent decoder component with fixed projections. The context-permutation check verifies the set symmetry; it is not a complete trained ANP.

Shared setup for this chapter
lse <- function(z) { m <- max(z); m + log(sum(exp(z-m))) }
rbf <- function(a,b,ell=1) {
  a <- as.matrix(a); b <- as.matrix(b)
  D <- outer(rowSums(a*a),rowSums(b*b),"+")-2*a%*%t(b)
  exp(-pmax(D,0)/(2*ell^2))
}
xc <- c(-1,0,1); yc <- c(-.6,.1,.8); xt <- c(-.5,.7)
K <- cbind(xc,xc^2); Q <- cbind(xt,xt^2); V <- cbind(yc,xc*yc)
attend <- function(k,v) {
 scores <- Q%*%t(k)/sqrt(2)
 weights <- exp(sweep(scores,1,apply(scores,1,lse),"-"))
 list(r=weights%*%v,w=weights)
}
a <- attend(K,V); perm <- c(3,1,2); b <- attend(K[perm,],V[perm,])
z <- .2; m <- a$r[,1]+.1*a$r[,2]+z*xt
stopifnot(max(abs(a$r-b$r))<1e-12,max(abs(rowSums(a$w)-1))<1e-12)
print(list(attention=a$w,target_means=m,shared_latent=z))

Sources

From the CodeSplash reference, entry UNC018.