Download code/pimamba/models_next.py from eduzrh/training-model-material: direct link, hf CLI and curl.
- Browser
- Download file 19.8 kB
-
https://huggingface.co/datasets/eduzrh/training-model-material/resolve/main/code/pimamba/models_next.py
- Command line
-
hf download hf://datasets/eduzrh/training-model-material/code/pimamba/models_next.py
-
curl -L -o models_next.py https://huggingface.co/datasets/eduzrh/training-model-material/resolve/main/code/pimamba/models_next.py
19.8 kB
| """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} | |
| 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) |