Cross-attention and latent space

A few learned queries read millions of points into a small set of tokens; the model works there and answers at any point.

Outcome: Explain cross-attention: queries from one set, keys and values from another; build an encode–process–decode surrogate and give the cost of each stage; relate a latent space to POD, and say why latent rollouts can be cheap.

Builds on Self-attention and the transformer, Compressing fields: POD

Self-attention over a million points costs too much compute, and usually memory, for practical training on today’s hardware. One way round it has appeared in linear form: POD (Equation 3-5) writes a field as a mean plus a few modes, so a whole CpC_p distribution is summarised by, for example, ten coefficients. A latent space is the learned, nonlinear version.

Cross-attention is the way into and out of that space.

Cross-attention

In self-attention the queries, keys and values all come from the same tokens. In cross-attention the queries come from one set and the keys and values from another. The formula is unchanged; only the inputs differ. If there are MM queries and NN keys, the weight matrix is M×NM \times N.

Figure 6-3. The selected query reads every key, each line as wide as its attention weight (illustrative weights); switch between encoder and decoder above.

Reading in: a few latent queries

A set of M=256M = 256 learned vectors, the latent queries, attends to all NN mesh tokens. Each latent query returns a weighted summary of the points it read, a latent token.

Z=Attention⁡(LWQ,  XWK,  XWV)Z = \operatorname{Attention}\big(L W_Q,\; X W_K,\; X W_V\big)
(6-5)
LL: the MM learned latent queries, an M×dM \times d matrix shared by every case; XX: the NN point tokens, N×dN \times d; ZZ: the MM latent tokens. Attention is Equation 6-2, usually with several heads; its weight matrix is M×NM \times N.

The cost is N×MN \times M instead of N2N^2: for a million points, 2.6×1082.6 \times 10^8 weights instead of 101210^{12}. This is the Perceiver pattern, named after a general-purpose model (Jaegle et al. 2021) that used it to read images, audio and point clouds into a small fixed set of latent tokens.

Extra inputs such as inflow speed or design parameters can enter the same way, as extra keys and values, instead of being copied into every point token.

Reading out: any point is a query

The same mechanism works in reverse. For the field at a location, its coordinates are embedded into a token, used as a query that attends to the latent tokens. The query can be any point: on the surface, in the volume, on a mesh the model never saw in training. Because inputs and outputs are sets of points, such a model can be trained on one mesh and evaluated on another. That is the resolution independence of neural operators, with the same caveat: the model runs on any mesh, but its accuracy still depends on what the training data covered.

Encode, process, decode

The two are combined, with self-attention in between:

  1. Encode. The NN points are embedded as tokens, then MM latent queries read them. Cost N×MN \times M.
  2. Process. A stack of transformer blocks on the MM latent tokens only. Cost M2M^2, independent of the mesh.
  3. Decode. Each output location becomes a query that reads the latent tokens. Cost Q×MQ \times M for QQ query points.

DefinitionLatent space

The MM tokens of dd numbers into which an encoder compresses the input; the model works there, and a decoder reconstructs the field.
qqqmillions of pointslatentany query
Figure 6-4. Millions of points are encoded into a fixed set of latent tokens, processed there, and decoded at any query point.

The processor costs the same for a coarse and a fine mesh; only the encoder and the decoder grow with the number of points. The price is detail: everything the decoder will be asked for has to pass through MM tokens, so MM is a setting to test on validation runs, like the number of POD modes. UPT (Universal Physics Transformer; Alkin et al. 2024) is built this way: its paper uses 64 latent tokens for car surfaces of 3,600 points and 512 for its transient 2D flows. The latent grid of GINO is the same compression onto a set of fixed size, a regular grid in place of learned queries. UPT’s successor AB-UPT, which its authors apply to car meshes of about 140 million cells, works with anchors instead (decoders).

For transient problems, the processor can predict the next latent state from the current one, and the rollout happens entirely in latent space. Decoding is needed only at the times of interest, which can make long rollouts much cheaper than stepping the full mesh, with the accuracy still to be checked.

Example 6-4 builds one on the aircraft and trains it on the 36 training runs, 4 runs and 512 of their points at a time, as the query points too.

Example 6-4. An encode–process–decode surrogate on the aircraft, trained with PyTorch
import time
import numpy as np
import torch
from torch import nn
from aircraft import fourier, load_runs, split_runs

class LatentSurrogate(nn.Module):
    def __init__(self, f_in, d=128, M=256, L=4, heads=8):
        super().__init__()
        self.embed = nn.Linear(f_in, d)   # points to tokens
        self.query = nn.Sequential(       # points to queries
            nn.Linear(f_in + 24, d), nn.GELU(), nn.Linear(d, d))
        self.latents = nn.Parameter(torch.randn(M, d) * 0.02)1
        mha = lambda: nn.MultiheadAttention(
            d, heads, batch_first=True)
        self.enc, self.dec = mha(), mha()
        layer = nn.TransformerEncoderLayer(
            d, heads, 4 * d, dropout=0.0,
            batch_first=True, norm_first=True)2
        self.process = nn.TransformerEncoder(
            layer, L, enable_nested_tensor=False)
        self.head = nn.Sequential(
            nn.LayerNorm(d), nn.Linear(d, d), nn.GELU(),
            nn.Linear(d, 1))

    def forward(self, feats, out):
        # feats: (B, N, f_in) inputs; out: (B, Q, f_in) queries
        t = self.embed(feats)
        lat = self.latents.expand(len(t), -1, -1)
        z = lat + self.enc(lat, t, t)[0]  # encode: (B, M, d)3
        z = self.process(z)               # process M tokens
        q = self.query(torch.cat([out, fourier(out[..., :3])], -1))
        # Decode at any points: (B, Q, 1)
        return self.head(q + self.dec(q, z, z)[0])4

# The 8 inputs per point: xyz, normal, alpha, sweep.
d = load_runs()
train, val, test, in_box = split_runs(d)
D = np.stack([d["alpha"], d["sweep"]], axis=1)
design = np.repeat(D[:, None, :], 2000, axis=1)
X = np.concatenate([d["xyz"], d["normal"], design], axis=-1)
mu = X[train].reshape(-1, 8).mean(axis=0)5
sd = X[train].reshape(-1, 8).std(axis=0)
mu[3:6], sd[3:6] = 0.0, 1.0
X = torch.tensor((X - mu) / sd, dtype=torch.float32)  # (56, 2000, 8)
Y = torch.tensor(d["cp"], dtype=torch.float32)[..., None]

torch.manual_seed(0)
rng = np.random.default_rng(0)
model = LatentSurrogate(f_in=8, M=64)
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
steps = 3000
sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, steps)
t0 = time.time()
for step in range(steps):
    r = torch.as_tensor(rng.choice(train, 4))  # 4 runs
    i = torch.randint(0, 2000, (4, 512))       # 512 points each
    xb, yb = X[r[:, None], i], Y[r[:, None], i]
    loss = nn.functional.mse_loss(model(xb, xb), yb)
    opt.zero_grad()
    loss.backward()
    opt.step()
    sched.step()

model.eval()
with torch.no_grad():
    pred = model(X[val], X[val])          # all 2,000 points
err = (pred - Y[val]).norm(dim=(1, 2)) / Y[val].norm(dim=(1, 2))
print(f"validation relative L2 {err.mean():.1%}"
      f" ({time.time() - t0:.0f} s)")
  1. The MM latent queries LL of Equation 6-5: learned parameters, the same for every case. They start almost equal, so the residual of callout 3 is what tells them apart.
  2. norm_first=True gives the pre-norm block of Equation 6-4. dropout=0.0: the default 0.1 is on in training and off in evaluation, and on 36 runs the two then predict different fields.
  3. Encode: queries from the latents, keys and values from the point tokens, a weight matrix of M×NM \times N per head. Adding lat back keeps the tokens distinct; without it every token comes out nearly the same.
  4. Decode: each query point, from its 8 inputs and the Fourier features of Example 4-7, reads the latent tokens, Q×MQ \times M. The residual q + keeps where the point is; with both residuals removed, the decoder returns the same value at every point.
  5. The 8 inputs per point of Example 4-9, normalised with the training runs’ statistics; the normals are unit vectors already and stay as they are.

Example 6-4 prints validation relative L2 11.2% and the training time, about 75 s on one laptop CPU: behind the project’s neural field and far behind POD + GP (Table 4-2), on 36 training runs.