File size: 19,843 Bytes
773c429 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 | """Next-generation backbones (2024-2026) under the same multi-task protocol.
Every model here re-uses ``SequenceModel``'s multi-task heads (per-variable
heads, softmax phases, softplus densities) and the optional micro->macro
coupling, so the comparison against PI-Mamba / Mamba is apples-to-apples:
same inputs, same loss, same budget.
Implemented
-----------
llama modern decoder-only Transformer: RoPE + RMSNorm + SwiGLU + SDPA
xlstm mLSTM block (matrix memory, exponential input/forget gates), 2024
gdn Gated DeltaNet: delta-rule fast weights with per-step decay, 2024-25
hymba hybrid stack: Mamba block interleaved with attention (Jamba/Hymba)
koopman Deep Koopman: *linear* latent dynamics with a learnable eigen-spectrum
node Neural ODE: continuous-time latent dynamics, RK4 integration
rssm latent world model: deterministic h_t + stochastic z_t, ELBO training
flow conditional flow matching over the whole curve (generative)
"""
from __future__ import annotations
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from .models import FiLM, RMSNorm, MambaBlock, SequenceModel
# ---------------------------------------------------------------------------
# helpers
# ---------------------------------------------------------------------------
def _rope(t, dim, device, base=10000.0):
inv = base ** (-torch.arange(0, dim, 2, device=device).float() / dim)
fr = torch.outer(torch.arange(t, device=device).float(), inv)
emb = torch.cat([fr, fr], dim=-1) # (T, dim)
return emb.cos(), emb.sin()
def _rot(x):
x1, x2 = x.chunk(2, dim=-1)
return torch.cat([-x2, x1], dim=-1)
class SwiGLU(nn.Module):
def __init__(self, d, mult=2):
super().__init__()
self.w1 = nn.Linear(d, mult * d)
self.w3 = nn.Linear(d, mult * d)
self.w2 = nn.Linear(mult * d, d)
def forward(self, x):
return self.w2(F.silu(self.w1(x)) * self.w3(x))
class LLaMABlock(nn.Module):
"""Pre-norm attention + SwiGLU FFN, RoPE positions, SDPA kernel."""
def __init__(self, d, n_heads=4, dropout=0.1):
super().__init__()
assert d % n_heads == 0
self.h, self.dh = n_heads, d // n_heads
self.n1 = RMSNorm(d)
self.qkv = nn.Linear(d, 3 * d)
self.o = nn.Linear(d, d)
self.n2 = RMSNorm(d)
self.ff = SwiGLU(d)
self.p = dropout
def forward(self, x, cos, sin):
b, T, d = x.shape
q, k, v = self.qkv(self.n1(x)).chunk(3, dim=-1)
q = q.view(b, T, self.h, self.dh).transpose(1, 2)
k = k.view(b, T, self.h, self.dh).transpose(1, 2)
v = v.view(b, T, self.h, self.dh).transpose(1, 2)
q = q * cos + _rot(q) * sin
k = k * cos + _rot(k) * sin
y = F.scaled_dot_product_attention(
q, k, v, is_causal=True,
dropout_p=self.p if self.training else 0.0)
y = y.transpose(1, 2).reshape(b, T, d)
x = x + self.o(y)
return x + self.ff(self.n2(x))
class LLaMAModel(SequenceModel):
def __init__(self, n_static, n_out, seq_dim=5, d_model=64, n_layers=2,
n_heads=4, **kw):
super().__init__(n_static, n_out, d_model=d_model, **kw)
self.inp = nn.Linear(seq_dim, d_model)
self.blocks = nn.ModuleList([LLaMABlock(d_model, n_heads, kw.get("dropout", 0.1))
for _ in range(n_layers)])
self.norm = RMSNorm(d_model)
self.film = FiLM(d_model, d_model)
def forward(self, static, x):
b, T, _ = x.shape
cond = self.static_enc(static)
# RoPE operates on the per-head dimension dh = d_model / n_heads
cos, sin = _rope(T, self.blocks[0].dh, x.device)
h = self.inp(x) + cond.unsqueeze(1)
for blk in self.blocks:
h = blk(h, cos, sin)
h = self.film(self.norm(h), cond)
pred, micro = self.head(h, static)
return {"pred": pred, "micro": micro, "h": h}
class mLSTMBlock(nn.Module):
"""Matrix-memory LSTM (xLSTM, 2024) in recurrent form."""
def __init__(self, d, n_heads=4, dropout=0.1, expand=2):
super().__init__()
self.h, self.dh = n_heads, d // n_heads
self.qkv = nn.Linear(d, 3 * d)
self.gates = nn.Linear(d, 2 * n_heads) # input / forget logits
self.out = nn.Linear(d, d)
self.n = RMSNorm(d)
self.ff = SwiGLU(d, expand)
self.drop = nn.Dropout(dropout)
self.record = False
self.trace = []
def forward(self, x):
b, T, d = x.shape
q, k, v = self.qkv(x).chunk(3, dim=-1)
q = q.view(b, T, self.h, self.dh)
k = F.normalize(k.view(b, T, self.h, self.dh), dim=-1)
v = v.view(b, T, self.h, self.dh)
g = self.gates(x).view(b, T, 2, self.h)
i_gate = torch.exp(g[:, :, 0]) # input gate (exp)
f_gate = torch.sigmoid(g[:, :, 1]) # forget gate
C = x.new_zeros(b, self.h, self.dh, self.dh)
n = x.new_zeros(b, self.h, self.dh)
outs = []
for t in range(T):
ft = f_gate[:, t].unsqueeze(-1)
it = i_gate[:, t].unsqueeze(-1)
kt = k[:, t]
C = ft.unsqueeze(-1) * C + it.unsqueeze(-1) * (v[:, t].unsqueeze(-1) @ kt.unsqueeze(-2))
n = ft * n + it * kt
qt = q[:, t].unsqueeze(-1)
num = (C @ qt).squeeze(-1)
den = (n.unsqueeze(-1) * qt).sum(-2).abs().clamp(min=1.0)
outs.append(num / den)
if self.record:
self.trace.append((float(C.norm()), float(f_gate[:, t].mean())))
y = torch.stack(outs, 1).reshape(b, T, d)
x = x + self.drop(self.out(y))
return x + self.ff(self.n(x))
class xLSTMModel(SequenceModel):
def __init__(self, n_static, n_out, seq_dim=5, d_model=64, n_layers=2,
n_heads=4, **kw):
super().__init__(n_static, n_out, d_model=d_model, **kw)
self.inp = nn.Linear(seq_dim, d_model)
self.blocks = nn.ModuleList([mLSTMBlock(d_model, n_heads,
kw.get("dropout", 0.1))
for _ in range(n_layers)])
self.norm = RMSNorm(d_model)
self.film = FiLM(d_model, d_model)
def forward(self, static, x):
cond = self.static_enc(static)
h = self.inp(x) + cond.unsqueeze(1)
for blk in self.blocks:
h = blk(h)
h = self.film(self.norm(h), cond)
pred, micro = self.head(h, static)
return {"pred": pred, "micro": micro, "h": h}
class GatedDeltaBlock(nn.Module):
"""Gated delta rule: S <- a*S(I - b k k^T) + b v k^T (fast weights)."""
def __init__(self, d, n_heads=4, dropout=0.1, expand=2):
super().__init__()
self.h, self.dh = n_heads, d // n_heads
self.qkv = nn.Linear(d, 3 * d)
self.gates = nn.Linear(d, 2 * n_heads) # decay a, write b
self.out = nn.Linear(d, d)
self.n = RMSNorm(d)
self.ff = SwiGLU(d, expand)
self.drop = nn.Dropout(dropout)
self.record = False
self.trace = []
def forward(self, x):
b, T, d = x.shape
q, k, v = self.qkv(x).chunk(3, dim=-1)
q = F.normalize(q.view(b, T, self.h, self.dh), dim=-1)
k = F.normalize(k.view(b, T, self.h, self.dh), dim=-1)
v = v.view(b, T, self.h, self.dh)
g = self.gates(x).view(b, T, 2, self.h)
alpha = torch.sigmoid(g[:, :, 0]) # decay
beta = torch.sigmoid(g[:, :, 1]) # write strength
S = x.new_zeros(b, self.h, self.dh, self.dh)
outs = []
for t in range(T):
a = alpha[:, t].unsqueeze(-1).unsqueeze(-1)
bt = beta[:, t].unsqueeze(-1).unsqueeze(-1)
kt = k[:, t]
S = a * S
Sk = (S * kt.unsqueeze(-1)).sum(-2) # (b,h,dh)
S = S - bt * (Sk.unsqueeze(-1) * kt.unsqueeze(-2))
S = S + bt * (v[:, t].unsqueeze(-1) * kt.unsqueeze(-2))
outs.append((S * q[:, t].unsqueeze(-1)).sum(-2) / math.sqrt(self.dh))
if self.record:
self.trace.append((float(S.norm()), float(alpha[:, t].mean()),
float(beta[:, t].mean())))
y = torch.stack(outs, 1).reshape(b, T, d)
x = x + self.drop(self.out(y))
return x + self.ff(self.n(x))
class GatedDeltaModel(SequenceModel):
def __init__(self, n_static, n_out, seq_dim=5, d_model=64, n_layers=2,
n_heads=4, **kw):
super().__init__(n_static, n_out, d_model=d_model, **kw)
self.inp = nn.Linear(seq_dim, d_model)
self.blocks = nn.ModuleList([GatedDeltaBlock(d_model, n_heads,
kw.get("dropout", 0.1))
for _ in range(n_layers)])
self.norm = RMSNorm(d_model)
self.film = FiLM(d_model, d_model)
def forward(self, static, x):
cond = self.static_enc(static)
h = self.inp(x) + cond.unsqueeze(1)
for blk in self.blocks:
h = blk(h)
h = self.film(self.norm(h), cond)
pred, micro = self.head(h, static)
return {"pred": pred, "micro": micro, "h": h}
class HybridModel(SequenceModel):
"""Interleaved Mamba + attention (Jamba / Hymba style hybrid)."""
def __init__(self, n_static, n_out, seq_dim=5, d_model=64, n_layers=2,
d_state=16, n_heads=4, **kw):
super().__init__(n_static, n_out, d_model=d_model, **kw)
self.inp = nn.Linear(seq_dim, d_model)
self.mamba = nn.ModuleList([MambaBlock(d_model, d_state)
for _ in range(n_layers)])
self.attn = nn.ModuleList([LLaMABlock(d_model, n_heads,
kw.get("dropout", 0.1))
for _ in range(n_layers)])
self.norm = RMSNorm(d_model)
self.film = FiLM(d_model, d_model)
def forward(self, static, x):
b, T, _ = x.shape
cond = self.static_enc(static)
cos, sin = _rope(T, self.attn[0].dh, x.device)
h = self.inp(x) + cond.unsqueeze(1)
for mb, ab in zip(self.mamba, self.attn):
h = ab(mb(h), cos, sin)
h = self.film(self.norm(h), cond)
pred, micro = self.head(h, static)
return {"pred": pred, "micro": micro, "h": h}
class KoopmanModel(SequenceModel):
"""Deep Koopman: latent state evolves *linearly*, z_{t+1} = A z_t + B u_t.
A is block-diagonal with learnable (radius r, angle theta) pairs, so the
spectrum is explicit: tau = -1/ln r is the memory time of each mode.
"""
def __init__(self, n_static, n_out, seq_dim=5, d_model=64, n_layers=1,
d_lat=32, **kw):
super().__init__(n_static, n_out, d_model=d_model, **kw)
self.d_lat = d_lat
self.enc = nn.Sequential(nn.Linear(seq_dim + d_model, d_model), nn.GELU(),
nn.Linear(d_model, d_lat))
self.r_raw = nn.Parameter(torch.zeros(d_lat // 2))
self.theta = nn.Parameter(torch.linspace(0, 1.5, d_lat // 2))
self.B = nn.Linear(seq_dim + d_model, d_lat, bias=False)
self.dec = nn.Sequential(nn.Linear(d_lat, d_model), nn.GELU(),
nn.Linear(d_model, d_model))
self.film = FiLM(d_model, d_model)
def spectrum(self):
r = torch.exp(-F.softplus(self.r_raw)) # 0 < r < 1
return r, self.theta
def forward(self, static, x):
b, T, _ = x.shape
cond = self.static_enc(static)
u = torch.cat([x, cond.unsqueeze(1).expand(-1, T, -1)], dim=-1)
r, th = self.spectrum()
a = (r * torch.cos(th)).view(1, -1, 1)
c = (r * torch.sin(th)).view(1, -1, 1)
z = self.enc(u[:, 0])
Bu = self.B(u)
zs = []
for t in range(T):
z2 = z.view(b, -1, 2)
zr = z2[..., 0].unsqueeze(-1)
zi = z2[..., 1].unsqueeze(-1)
z = torch.cat([a * zr - c * zi, c * zr + a * zi], dim=-1).reshape(b, -1)
z = z + Bu[:, t]
zs.append(z)
z = torch.stack(zs, 1)
h = self.film(self.dec(z), cond)
pred, micro = self.head(h, static)
return {"pred": pred, "micro": micro, "h": h, "z": z}
class NODEModel(SequenceModel):
"""Neural ODE on a coarse grid (RK4), upsampled back to the strain grid."""
def __init__(self, n_static, n_out, seq_dim=5, d_model=64, n_layers=1,
d_lat=32, substep=4, **kw):
super().__init__(n_static, n_out, d_model=d_model, **kw)
self.sub = substep
self.d_lat = d_lat
d_in = d_lat + seq_dim + d_model
self.f = nn.Sequential(nn.Linear(d_in, 128), nn.Tanh(),
nn.Linear(128, 128), nn.Tanh(),
nn.Linear(128, d_lat))
self.enc = nn.Linear(seq_dim + d_model, d_lat)
self.dec = nn.Sequential(nn.Linear(d_lat, d_model), nn.GELU(),
nn.Linear(d_model, d_model))
self.film = FiLM(d_model, d_model)
self.record = False
self.trace = []
def _f(self, z, u, c):
return self.f(torch.cat([z, u, c], dim=-1))
def forward(self, static, x):
b, T, _ = x.shape
cond = self.static_enc(static)
c = cond
z = self.enc(torch.cat([x[:, 0], cond], dim=-1))
dt = 1.0 / max(1, T // self.sub)
zs = []
idx = list(range(0, T, self.sub))
for i in idx:
zs.append(z)
u = x[:, i]
k1 = self._f(z, u, c)
k2 = self._f(z + 0.5 * dt * k1, u, c)
k3 = self._f(z + 0.5 * dt * k2, u, c)
k4 = self._f(z + dt * k3, u, c)
if self.record:
self.trace.append(float(k1.norm(dim=-1).mean()))
z = z + dt / 6.0 * (k1 + 2 * k2 + 2 * k3 + k4)
zc = torch.stack(zs, 1) # (b, Tc, d)
zc = F.interpolate(zc.transpose(1, 2), size=T, mode="linear",
align_corners=True).transpose(1, 2)
h = self.film(self.dec(zc), cond)
pred, micro = self.head(h, static)
return {"pred": pred, "micro": micro, "h": h, "z": zc}
class RSSMModel(SequenceModel):
"""Latent world model: deterministic GRU state + stochastic latent (ELBO)."""
needs_y = True
def __init__(self, n_static, n_out, seq_dim=5, d_model=64, n_layers=1,
d_det=64, d_stoch=16, **kw):
super().__init__(n_static, n_out, d_model=d_model, **kw)
self.d_det, self.d_stoch, self.n_out = d_det, d_stoch, n_out
self.inp = nn.Linear(seq_dim, d_model)
self.cell = nn.GRUCell(d_model + d_model, d_det)
self.prior = nn.Linear(d_det, 2 * d_stoch)
self.post = nn.Linear(d_det + n_out, 2 * d_stoch)
self.dec = nn.Sequential(nn.Linear(d_det + d_stoch, d_model), nn.GELU(),
nn.Linear(d_model, d_model))
self.film = FiLM(d_model, d_model)
self.record = False
self.trace = []
def _q(self, h, y=None):
if y is not None:
return self.post(torch.cat([h, y], dim=-1))
return self.prior(h)
def forward(self, static, x, y=None, m=None):
b, T, _ = x.shape
cond = self.static_enc(static)
hd = x.new_zeros(b, self.d_det)
kl = x.new_zeros(())
hs, zs = [], []
for t in range(T):
hd = self.cell(torch.cat([self.inp(x[:, t]), cond], dim=-1), hd)
pr = self.prior(hd)
pm, plv = pr.chunk(2, dim=-1)
if self.training and y is not None:
po = self._q(hd, y[:, t])
qm, qlv = po.chunk(2, dim=-1)
kl = kl + _kl_diag(qm, qlv, pm, plv)
eps = torch.randn_like(qm)
z = qm + torch.exp(0.5 * qlv) * eps
else:
z = pm
if self.record:
self.trace.append(float(torch.exp(0.5 * plv).mean()))
hs.append(hd)
zs.append(z)
hd = torch.stack(hs, 1)
z = torch.stack(zs, 1)
h = self.film(self.dec(torch.cat([hd, z], dim=-1)), cond)
pred, micro = self.head(h, static)
aux = kl / max(1, T) * 1e-3
return {"pred": pred, "micro": micro, "h": h, "aux_loss": aux}
def _kl_diag(qm, qlv, pm, plv):
"""KL( N(qm, exp(qlv)) || N(pm, exp(plv)) ), summed over the last dim."""
qv, pv = torch.exp(qlv), torch.exp(plv)
return 0.5 * ((qlv - plv) + (qv + (qm - pm) ** 2) / pv - 1.0).sum(-1).mean()
class FlowModel(SequenceModel):
"""Conditional flow matching over the whole (T, 13) curve.
The velocity field is a gated 1-D convolutional U-net conditioned on the
static descriptor and on the strain/time channel. Training minimises the
CFM objective; at inference the ODE is integrated with Euler steps.
"""
needs_y = True
def __init__(self, n_static, n_out, seq_dim=5, d_model=64, n_layers=3,
steps=8, **kw):
super().__init__(n_static, n_out, d_model=d_model, **kw)
self.n_out, self.steps = n_out, steps
self.cond = nn.Sequential(nn.Linear(n_static, d_model), nn.GELU(),
nn.Linear(d_model, d_model))
ch = n_out + seq_dim + d_model + 1 # x_t, u_t, cond, tau
self.inp = nn.Conv1d(ch, d_model, 1)
self.blocks = nn.ModuleList([
nn.Sequential(nn.Conv1d(d_model, d_model, 5, padding=2),
nn.GELU(),
nn.Conv1d(d_model, d_model, 5, padding=2))
for _ in range(n_layers)])
self.norms = nn.ModuleList([nn.GroupNorm(1, d_model) for _ in range(n_layers)])
self.out = nn.Conv1d(d_model, n_out, 1)
def _v(self, xt, u, c, tau):
b, T, _ = xt.shape
cc = c.unsqueeze(1).expand(-1, T, -1)
tt = tau.view(b, 1, 1).expand(-1, T, 1)
z = self.inp(torch.cat([xt, u, cc, tt], dim=-1).transpose(1, 2))
for blk, nrm in zip(self.blocks, self.norms):
z = z + blk(nrm(z))
return self.out(z).transpose(1, 2)
def forward(self, static, x, y=None, m=None):
b, T, _ = x.shape
c = self.cond(static)
if self.training and y is not None:
tau = torch.rand(b, device=x.device)
x0 = torch.randn_like(y)
xt = (1 - tau.view(b, 1, 1)) * x0 + tau.view(b, 1, 1) * y
v = self._v(xt, x, c, tau)
w = (1.0 if m is None else m)
cfm = (((v - (y - x0)) ** 2) * w).sum() / w.sum().clamp(min=1.0)
else:
cfm = x.new_zeros(())
# sample (used for evaluation / reporting)
z = torch.randn(b, T, self.n_out, device=x.device)
for k in range(self.steps):
tau = torch.full((b,), k / self.steps, device=x.device)
z = z + self._v(z, x, c, tau) / self.steps
# z is already in the normalised target space -> it *is* the prediction
return {"pred": z, "micro": z[..., 1:], "h": z, "replace_loss": cfm}
@torch.no_grad()
def sample(self, static, x, k: int = 8):
"""Draw k curves per sample; returns (k, b, T, n_out) in raw units? -> normalised."""
b, T, _ = x.shape
c = self.cond(static)
out = []
for _ in range(k):
z = torch.randn(b, T, self.n_out, device=x.device)
for j in range(self.steps):
tau = torch.full((b,), j / self.steps, device=x.device)
z = z + self._v(z, x, c, tau) / self.steps
out.append(z)
return torch.stack(out, 0) |