Download code/pimamba/models.py from eduzrh/training-model-material: direct link, hf CLI and curl.
- Browser
- Download file 17.9 kB
-
https://huggingface.co/datasets/eduzrh/training-model-material/resolve/main/code/pimamba/models.py
- Command line
-
hf download hf://datasets/eduzrh/training-model-material/code/pimamba/models.py
-
curl -L -o models.py https://huggingface.co/datasets/eduzrh/training-model-material/resolve/main/code/pimamba/models.py
17.9 kB
| """Sequence models for the HEA MD trajectory task. | |
| All models share the signature ``forward(static, x) -> dict(pred=(B,T,F))`` | |
| where ``pred`` is in the *normalised* target space defined by data.Normalizer. | |
| Implemented: | |
| * MLP - point-wise baseline (no history) | |
| * GRU / LSTM - recurrent baselines | |
| * Transformer- causal encoder baseline | |
| * Mamba - selective state-space (S6) backbone | |
| * Mamba2 - SSD-style multi-head gated SSM backbone | |
| * PIMamba - Mamba + static conditioning + micro->macro coupling | |
| """ | |
| from __future__ import annotations | |
| import math | |
| from typing import Optional | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| # --------------------------------------------------------------------------- | |
| # selective scan (chunked, numerically stable, pure PyTorch) | |
| # --------------------------------------------------------------------------- | |
| def selective_scan(u, delta, A, B, C, D=None, chunk: int = 8): | |
| """Linear time-invariant-in-A selective scan. | |
| u : (b, T, d) | |
| delta : (b, T, d) | |
| A : (d, n) negative real | |
| B, C : (b, T, n) | |
| returns (b, T, d) | |
| """ | |
| b, T, d = u.shape | |
| if A.dim() == 2: | |
| A = A.unsqueeze(0).unsqueeze(0) # (1,1,d,n) | |
| elif A.dim() == 3: | |
| A = A.unsqueeze(1) # (B,1,d,n) | |
| n = A.shape[-1] | |
| dt = delta.clamp(1e-4, 0.2) | |
| dev = u.device | |
| h = torch.zeros(b, d, n, device=dev, dtype=u.dtype) | |
| pad = (chunk - T % chunk) % chunk | |
| if pad: | |
| u = F.pad(u, (0, 0, 0, pad)) | |
| dt = F.pad(dt, (0, 0, 0, pad)) | |
| B = F.pad(B, (0, 0, 0, pad)) | |
| C = F.pad(C, (0, 0, 0, pad)) | |
| outs = [] | |
| Tp = u.shape[1] | |
| for s in range(0, Tp, chunk): | |
| uc = u[:, s:s + chunk] | |
| dtc = dt[:, s:s + chunk] | |
| Bc = B[:, s:s + chunk] | |
| Cc = C[:, s:s + chunk] | |
| a = torch.exp(dtc.unsqueeze(-1) * A) # (b,c,d,n) | |
| bu = (dtc * uc).unsqueeze(-1) * Bc.unsqueeze(2) # (b,c,d,n) | |
| P = torch.cumprod(a, dim=1) | |
| hloc = P * torch.cumsum(bu / P.clamp_min(1e-20), dim=1) | |
| hc = hloc + P * h.unsqueeze(1) | |
| h = hc[:, -1] | |
| y = (hc * Cc.unsqueeze(2)).sum(-1) | |
| outs.append(y) | |
| y = torch.cat(outs, dim=1)[:, :T] | |
| if D is not None: | |
| y = y + D.unsqueeze(0).unsqueeze(0) * u[:, :T] | |
| return y | |
| class RMSNorm(nn.Module): | |
| def __init__(self, d, eps=1e-5): | |
| super().__init__() | |
| self.w = nn.Parameter(torch.ones(d)) | |
| self.eps = eps | |
| def forward(self, x): | |
| return self.w * x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) | |
| class MambaBlock(nn.Module): | |
| def __init__(self, d_model, d_state=16, expand=2, d_conv=4, chunk=32): | |
| super().__init__() | |
| self.d_inner = int(expand * d_model) | |
| self.d_state = d_state | |
| self.chunk = chunk | |
| self.norm = RMSNorm(d_model) | |
| self.in_proj = nn.Linear(d_model, 2 * self.d_inner, bias=False) | |
| self.conv = nn.Conv1d(self.d_inner, self.d_inner, d_conv, | |
| groups=self.d_inner, padding=d_conv - 1) | |
| self.x_proj = nn.Linear(self.d_inner, 2 * d_state + 1, bias=False) | |
| self.dt_proj = nn.Linear(1, self.d_inner, bias=True) | |
| A = torch.empty(self.d_inner, d_state) | |
| nn.init.uniform_(A, 0.5, 8.0) # positive magnitude | |
| self.A_log = nn.Parameter(torch.log(A)) | |
| self.D = nn.Parameter(torch.ones(self.d_inner)) | |
| self.out_proj = nn.Linear(self.d_inner, d_model, bias=False) | |
| with torch.no_grad(): | |
| self.dt_proj.bias.uniform_(math.log(0.001), math.log(0.05)) | |
| def forward(self, x): | |
| b, T, _ = x.shape | |
| h = self.norm(x) | |
| xz = self.in_proj(h) | |
| xin, z = xz.chunk(2, dim=-1) | |
| xin = self.conv(xin.transpose(1, 2))[:, :, :T].transpose(1, 2) | |
| xin = F.silu(xin) | |
| proj = self.x_proj(xin) | |
| dt, Bc, Cc = torch.split(proj, [1, self.d_state, self.d_state], dim=-1) | |
| dt = F.softplus(self.dt_proj(dt)) | |
| A = -torch.exp(self.A_log) | |
| y = selective_scan(xin, dt, A, Bc, Cc, self.D, chunk=self.chunk) | |
| y = y * F.silu(z) | |
| return x + self.out_proj(y) | |
| class Mamba2Block(nn.Module): | |
| """Simplified SSD-style block: multi-head scalar decay + shared B/C groups.""" | |
| def __init__(self, d_model, nheads=4, d_state=64, expand=1, d_conv=4, | |
| n_groups=1, chunk=32): | |
| super().__init__() | |
| assert d_model % nheads == 0 | |
| self.d_model = d_model | |
| self.nheads = nheads | |
| self.headdim = d_model // nheads | |
| self.d_state = d_state | |
| self.n_groups = n_groups | |
| self.chunk = chunk | |
| self.norm = RMSNorm(d_model) | |
| self.in_proj = nn.Linear(d_model, 2 * d_model + 2 * d_state * n_groups + nheads, | |
| bias=False) | |
| self.conv = nn.Conv1d(d_model, d_model, d_conv, groups=d_model, | |
| padding=d_conv - 1) | |
| self.A_log = nn.Parameter(torch.log(torch.empty(nheads).uniform_(0.5, 8.0))) | |
| self.D = nn.Parameter(torch.ones(nheads)) | |
| self.dt_bias = nn.Parameter(torch.empty(nheads).uniform_(-4.0, -2.0)) | |
| self.norm_g = RMSNorm(d_model) | |
| self.out_proj = nn.Linear(d_model, d_model, bias=False) | |
| def forward(self, x): | |
| b, T, _ = x.shape | |
| h = self.norm(x) | |
| nh, hd, ng, ds = self.nheads, self.headdim, self.n_groups, self.d_state | |
| split = [self.d_model, self.d_model, ng * ds, ng * ds, nh] | |
| xin, z, Bc, Cc, dt = torch.split(self.in_proj(h), split, dim=-1) | |
| xin = self.conv(xin.transpose(1, 2))[:, :, :T].transpose(1, 2) | |
| xin = F.silu(xin).view(b, T, nh, hd) | |
| dt = F.softplus(dt + self.dt_bias).view(b, T, nh) # (b,T,nh) | |
| Bc = Bc.view(b, T, ng, ds) | |
| Cc = Cc.view(b, T, ng, ds) | |
| if ng != nh: | |
| rep = nh // ng | |
| Bc = Bc.repeat_interleave(rep, dim=2) | |
| Cc = Cc.repeat_interleave(rep, dim=2) | |
| # fold heads into batch, state dim = 1 -> reuse scalar scan | |
| xh = xin.permute(0, 2, 1, 3).reshape(b * nh, T, hd) | |
| dth = dt.permute(0, 2, 1).reshape(b * nh, T, 1).expand(-1, -1, hd) | |
| Bh = Bc.permute(0, 2, 1, 3).reshape(b * nh, T, ds) | |
| Ch = Cc.permute(0, 2, 1, 3).reshape(b * nh, T, ds) | |
| A = ((-torch.exp(self.A_log)).view(1, nh, 1, 1) | |
| .expand(b, nh, hd, 1).reshape(b * nh, 1, hd, 1)) | |
| y = selective_scan(xh, dth, A, Bh, Ch, None, chunk=self.chunk) | |
| y = y + xh * self.D.view(1, nh, 1, 1).expand(b, nh, hd, 1).reshape(b * nh, 1, hd) | |
| y = y.view(b, nh, T, hd).permute(0, 2, 1, 3).reshape(b, T, self.d_model) | |
| y = self.norm_g(y) * F.silu(z) | |
| return x + self.out_proj(y) | |
| class FiLM(nn.Module): | |
| def __init__(self, cond_dim, d_model): | |
| super().__init__() | |
| self.to_scale = nn.Linear(cond_dim, d_model) | |
| self.to_shift = nn.Linear(cond_dim, d_model) | |
| def forward(self, h, cond): | |
| s = 1.0 + self.to_scale(cond).unsqueeze(1) | |
| b = self.to_shift(cond).unsqueeze(1) | |
| return h * s + b | |
| # --------------------------------------------------------------------------- | |
| # full models | |
| # --------------------------------------------------------------------------- | |
| class SequenceModel(nn.Module): | |
| """Common wrapper: static encoder + backbone + multi-task heads.""" | |
| def __init__(self, n_static, n_out, d_model=64, n_layers=2, dropout=0.1, | |
| n_phase=4, n_rho=7, coupling=True, **kwargs): | |
| super().__init__() | |
| self.n_phase, self.n_rho = n_phase, n_rho | |
| self.n_micro = n_phase + n_rho + 1 | |
| self.static_enc = nn.Sequential( | |
| nn.Linear(n_static, d_model), nn.GELU(), | |
| nn.Dropout(dropout), nn.Linear(d_model, d_model)) | |
| self.cond_dim = d_model | |
| self.drop = nn.Dropout(dropout) | |
| self.coupling = coupling | |
| # ---- independent output head per physical variable (step 2 要求) ---- | |
| self.phase_head = nn.Linear(d_model, n_phase) | |
| mk = lambda: nn.Sequential(nn.Linear(d_model, max(8, d_model // 2)), | |
| nn.GELU(), | |
| nn.Linear(max(8, d_model // 2), 1)) | |
| self.rho_heads = nn.ModuleList([mk() for _ in range(n_rho)]) | |
| self.twin_head = mk() | |
| stress_in = 2 * d_model if coupling else d_model | |
| self.stress_head = nn.Sequential( | |
| nn.Linear(stress_in, d_model), nn.GELU(), nn.Linear(d_model, 1)) | |
| self.micro_proj = nn.Linear(self.n_micro, d_model) if coupling else None | |
| assert n_out == 1 + self.n_micro, (n_out, self.n_micro) | |
| def head(self, h, static): | |
| phase = torch.softmax(self.phase_head(h), dim=-1) | |
| rho = torch.cat([F.softplus(mi(h)) for mi in self.rho_heads], dim=-1) | |
| twin = F.softplus(self.twin_head(h)) | |
| micro_p = torch.cat([phase, rho, twin], dim=-1) | |
| if self.coupling: | |
| hs = torch.cat([h, self.micro_proj(micro_p)], dim=-1) | |
| else: | |
| hs = h | |
| sigma = self.stress_head(hs) | |
| return torch.cat([sigma, micro_p], dim=-1), micro_p | |
| class MLPModel(SequenceModel): | |
| def __init__(self, n_static, n_out, seq_dim=5, d_model=128, **kw): | |
| super().__init__(n_static, n_out, d_model=d_model, **kw) | |
| self.inp = nn.Sequential(nn.Linear(seq_dim + n_static, d_model), nn.GELU(), | |
| nn.Linear(d_model, d_model), nn.GELU()) | |
| def forward(self, static, x): | |
| b, T, _ = x.shape | |
| z = torch.cat([x, static.unsqueeze(1).expand(-1, T, -1)], dim=-1) | |
| h = self.inp(z) | |
| pred, micro = self.head(h, static) | |
| return {"pred": pred, "micro": micro, "h": h} | |
| class RNNModel(SequenceModel): | |
| def __init__(self, n_static, n_out, seq_dim=5, d_model=64, n_layers=2, | |
| rnn="gru", **kw): | |
| super().__init__(n_static, n_out, d_model=d_model, **kw) | |
| self.inp = nn.Linear(seq_dim, d_model) | |
| cls = nn.GRU if rnn == "gru" else nn.LSTM | |
| self.rnn = cls(d_model, d_model, num_layers=n_layers, batch_first=True, | |
| dropout=0.1 if n_layers > 1 else 0.0) | |
| self.film = FiLM(d_model, d_model) | |
| def forward(self, static, x): | |
| cond = self.static_enc(static) | |
| h = self.inp(x) | |
| h, _ = self.rnn(h) | |
| h = self.film(h, cond) | |
| pred, micro = self.head(h, static) | |
| return {"pred": pred, "micro": micro, "h": h} | |
| class TransformerModel(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.pos = nn.Parameter(torch.randn(1, 512, d_model) * 0.02) | |
| layer = nn.TransformerEncoderLayer(d_model, n_heads, 4 * d_model, | |
| dropout=0.1, batch_first=True, | |
| norm_first=True, activation="gelu") | |
| self.enc = nn.TransformerEncoder(layer, n_layers, enable_nested_tensor=False) | |
| self.film = FiLM(d_model, d_model) | |
| self.register_buffer("mask", torch.triu(torch.ones(512, 512), diagonal=1).bool()) | |
| def forward(self, static, x): | |
| b, T, _ = x.shape | |
| cond = self.static_enc(static) | |
| h = self.inp(x) + self.pos[:, :T] | |
| h = self.enc(h, mask=self.mask[:T, :T]) | |
| h = self.film(h, cond) | |
| pred, micro = self.head(h, static) | |
| return {"pred": pred, "micro": micro, "h": h} | |
| class MambaModel(SequenceModel): | |
| def __init__(self, n_static, n_out, seq_dim=5, d_model=64, n_layers=2, | |
| d_state=16, expand=2, **kw): | |
| super().__init__(n_static, n_out, d_model=d_model, **kw) | |
| self.inp = nn.Linear(seq_dim, d_model) | |
| self.blocks = nn.ModuleList([MambaBlock(d_model, d_state, expand) | |
| for _ in range(n_layers)]) | |
| self.norm = RMSNorm(d_model) | |
| self.cond_proj = nn.Linear(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.norm(h) | |
| pred, micro = self.head(h, static) | |
| return {"pred": pred, "micro": micro, "h": h} | |
| class Mamba2Model(SequenceModel): | |
| def __init__(self, n_static, n_out, seq_dim=5, d_model=64, n_layers=2, | |
| nheads=4, d_state=64, **kw): | |
| super().__init__(n_static, n_out, d_model=d_model, **kw) | |
| self.inp = nn.Linear(seq_dim, d_model) | |
| self.blocks = nn.ModuleList([Mamba2Block(d_model, nheads=nheads, | |
| d_state=d_state) | |
| for _ in range(n_layers)]) | |
| self.norm = RMSNorm(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.norm(h) | |
| pred, micro = self.head(h, static) | |
| return {"pred": pred, "micro": micro, "h": h} | |
| class PIMamba(SequenceModel): | |
| """Physics-informed Mamba: FiLM conditioning + micro -> macro coupling.""" | |
| def __init__(self, n_static, n_out, seq_dim=5, d_model=64, n_layers=2, | |
| d_state=16, expand=2, coupling=True, **kw): | |
| super().__init__(n_static, n_out, d_model=d_model, coupling=coupling, **kw) | |
| self.inp = nn.Linear(seq_dim, d_model) | |
| self.blocks = nn.ModuleList([MambaBlock(d_model, d_state, expand) | |
| for _ in range(n_layers)]) | |
| self.films = nn.ModuleList([FiLM(d_model, d_model) for _ in range(n_layers)]) | |
| self.norm = RMSNorm(d_model) | |
| def forward(self, static, x): | |
| cond = self.static_enc(static) | |
| h = self.inp(x) + cond.unsqueeze(1) | |
| for blk, film in zip(self.blocks, self.films): | |
| h = film(blk(h), cond) | |
| h = self.norm(h) | |
| pred, micro = self.head(h, static) | |
| return {"pred": pred, "micro": micro, "h": h} | |
| class PIMambaV2(SequenceModel): | |
| """PI-Mamba v2: Mamba-2 backbone + *Taylor-form* micro->macro coupling. | |
| The stress head reads ``[h, W z_micro, W2 phi(z_micro)]`` where ``phi`` | |
| contains ``sqrt(rho)`` and ``rho * twin`` terms. In physical units the | |
| Taylor relation is ``sigma = sigma_0 + M alpha G b sqrt(rho)``; here the | |
| model works in normalised units, so the square-root and the pair product | |
| give it the correct *functional form* while the affine map absorbs units. | |
| """ | |
| def __init__(self, n_static, n_out, seq_dim=5, d_model=64, n_layers=2, | |
| d_state=16, nheads=4, coupling=True, **kw): | |
| # build the shared heads first (no coupling), then install the | |
| # Taylor-form coupling and its own stress head | |
| SequenceModel.__init__(self, n_static, n_out, d_model=d_model, | |
| coupling=False, **kw) | |
| self.inp = nn.Linear(seq_dim, d_model) | |
| self.blocks = nn.ModuleList([Mamba2Block(d_model, nheads, d_state) | |
| for _ in range(n_layers)]) | |
| self.films = nn.ModuleList([FiLM(d_model, d_model) for _ in range(n_layers)]) | |
| self.norm = RMSNorm(d_model) | |
| if coupling: | |
| n_lin = 2 * d_model | |
| self.micro_proj = nn.Linear(self.n_micro, d_model) | |
| self.micro_nl = nn.Linear(self.n_rho + 2, d_model) # sqrt(dens) + rho*twin | |
| self.stress_head = nn.Sequential( | |
| nn.Linear(n_lin + d_model, d_model), nn.GELU(), nn.Linear(d_model, 1)) | |
| self.coupling = True | |
| else: | |
| self.micro_proj = None | |
| self.micro_nl = None | |
| self.stress_head = nn.Sequential( | |
| nn.Linear(d_model, d_model), nn.GELU(), nn.Linear(d_model, 1)) | |
| self.coupling = False | |
| def head(self, h, static): | |
| phase = torch.softmax(self.phase_head(h), dim=-1) | |
| rho = torch.cat([F.softplus(mi(h)) for mi in self.rho_heads], dim=-1) | |
| twin = F.softplus(self.twin_head(h)) | |
| micro_p = torch.cat([phase, rho, twin], dim=-1) | |
| if self.coupling: | |
| dens = torch.cat([rho, twin], dim=-1) # (b,T,n_rho+1) | |
| nl = torch.cat([torch.sqrt(dens + 1e-6), dens[..., :1] * dens[..., -1:]], dim=-1) | |
| hs = torch.cat([h, self.micro_proj(micro_p), self.micro_nl(nl)], dim=-1) | |
| else: | |
| hs = h | |
| sigma = self.stress_head(hs) | |
| return torch.cat([sigma, micro_p], dim=-1), micro_p | |
| def forward(self, static, x): | |
| cond = self.static_enc(static) | |
| h = self.inp(x) + cond.unsqueeze(1) | |
| for blk, film in zip(self.blocks, self.films): | |
| h = film(blk(h), cond) | |
| h = self.norm(h) | |
| pred, micro = self.head(h, static) | |
| return {"pred": pred, "micro": micro, "h": h} | |
| def build_model(name: str, n_static: int, n_out: int, **kw) -> SequenceModel: | |
| name = name.lower() | |
| table = {"mlp": MLPModel, "gru": RNNModel, "lstm": RNNModel, | |
| "transformer": TransformerModel, "mamba": MambaModel, | |
| "mamba2": Mamba2Model, "pimamba": PIMamba, "pimamba2": PIMambaV2} | |
| # next-generation backbones (2024-2026) live in models_next.py to keep the | |
| # import graph acyclic and this file readable. | |
| from . import models_next as NX | |
| table.update({"llama": NX.LLaMAModel, "xlstm": NX.xLSTMModel, | |
| "gdn": NX.GatedDeltaModel, "hymba": NX.HybridModel, | |
| "koopman": NX.KoopmanModel, "node": NX.NODEModel, | |
| "rssm": NX.RSSMModel, "flow": NX.FlowModel}) | |
| if name not in table: | |
| raise ValueError(f"unknown model {name}") | |
| if name == "lstm": | |
| kw["rnn"] = "lstm" | |
| return table[name](n_static, n_out, **kw) |