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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
"""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)