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 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 queries and keys, the weight matrix is .
Reading in: a few latent queries
A set of learned vectors, the latent queries, attends to all mesh tokens. Each latent query returns a weighted summary of the points it read, a latent token.
The cost is instead of : for a million points, weights instead of . 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:
- Encode. The points are embedded as tokens, then latent queries read them. Cost .
- Process. A stack of transformer blocks on the latent tokens only. Cost , independent of the mesh.
- Decode. Each output location becomes a query that reads the latent tokens. Cost for query points.
DefinitionLatent space
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 tokens, so 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)")
- The latent queries 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.
norm_first=Truegives 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.- Encode: queries from the latents, keys and values from the point tokens, a weight matrix of per head. Adding
latback keeps the tokens distinct; without it every token comes out nearly the same. - Decode: each query point, from its 8 inputs and the Fourier features of Example 4-7, reads the latent tokens, . The residual
q +keeps where the point is; with both residuals removed, the decoder returns the same value at every point. - 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.