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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
"""
Mamba-2 (SSD-style) language model -- "semi-official", mirroring model.mamba.

Like `model.mamba.Mamba`, this keeps a hand-written block (in_proj / depthwise
conv1d / gated RMSNorm / out_proj) but delegates the heavy state-space scan to
the OFFICIAL fused Triton kernel `mamba_chunk_scan_combined` from the
`mamba_ssm` package WHEN it is available and `config.use_cuda=True`. If the
package (mamba_ssm >= 2.2 with a `Mamba2`) is not installed, it transparently
falls back to the self-contained pure-PyTorch chunked SSD scan below, so the
exact same code runs in either environment.

It mirrors the public interface of `model.mamba.Mamba` (forward(idx, targets)
-> (logits, loss), .generate(), .configure_optimizers(), .get_num_params(), and
a `.layers` ModuleList) so it plugs directly into train_maze.py / test_maze.py
/ maze_kstep_detour_test.py.

Key differences from Mamba-1 (model.mamba):
  * Multi-head structure: d_inner is split into `nheads` heads of `headdim`.
  * The state-transition A is a single scalar PER HEAD (A = -exp(A_log),
    A_log shape (nheads,)) instead of a full (d_inner, d_state) matrix. This is
    the Mamba-2 "scalar-times-identity" SSD simplification.
  * dt (the discretization step) is per-head, shape (B, L, nheads).
  * A single depthwise conv is applied jointly to (x, B, C).
  * Output is gated-RMSNorm'd with the z branch before the final projection.

The linear recurrence H[t] = a[t] * H[t-1] + X[t] is computed with the
chunked SSD ("state-space duality") algorithm from the Mamba-2 paper. Instead
of materializing the full (B, L, d_inner, d_state) per-timestep state for the
whole sequence (as a naive parallel scan would), the sequence is split into
chunks of `chunk_size`: outputs within a chunk are computed with an
attention-like matmul, and only small chunk-level states (B, nheads, headdim,
d_state) are carried across chunks. This is dramatically faster and lighter on
memory than a full scan, which is the whole point of Mamba-2.
"""

import math
import inspect
from dataclasses import dataclass
from typing import Union

import torch
import torch.nn as nn
import torch.nn.functional as F

# Official fused Triton SSD kernel (mamba_ssm >= 2.2). Optional: if it is not
# installed we fall back to the pure-PyTorch chunked scan in `_ssd` below.
try:
    from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined
    _HAS_MAMBA2_KERNEL = True
except Exception:  # pragma: no cover - import guard
    mamba_chunk_scan_combined = None
    _HAS_MAMBA2_KERNEL = False


class RMSNorm(nn.Module):
    def __init__(self, n_embd: int, eps: float = 1e-5):
        super().__init__()

        self.eps = eps
        self.weight = nn.Parameter(torch.ones(n_embd))

    def forward(self, x):
        output = (
            x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight
        )

        return output


@dataclass
class Mamba2Config:
    n_embd: int                       # D (model dimension)
    n_layer: int

    d_state: int = 64                 # N: SSM state size per head
    expand_factor: int = 2            # E: d_inner = E * D
    headdim: int = 64                 # P: dimension per head (d_inner must be divisible by it)
    ngroups: int = 1                  # number of (B, C) groups (1 == shared across all heads)
    d_conv: int = 4
    chunk_size: int = 64              # SSD chunk length for the chunked scan

    vocab_size: int = 64

    dt_min: float = 0.001
    dt_max: float = 0.1
    dt_init_floor: float = 1e-4
    A_init_min: float = 1.0           # A_log initialized from U(log(A_init_min), log(A_init_max))
    A_init_max: float = 16.0

    rms_norm_eps: float = 1e-5

    bias: bool = False
    conv_bias: bool = True

    pscan: bool = True                # kept for config compatibility (always parallel scan here)
    use_cuda: bool = False            # use the official fused Triton kernel when mamba_ssm>=2.2 is installed (auto-fallback to pure PyTorch otherwise)

    model_type: str = "mamba2"
    pad_id: int = -1

    def __post_init__(self):
        self.d_inner = self.expand_factor * self.n_embd
        assert self.d_inner % self.headdim == 0, (
            f"d_inner ({self.d_inner}) must be divisible by headdim ({self.headdim})")
        self.nheads = self.d_inner // self.headdim


class RMSNormGated(nn.Module):
    """RMSNorm with a SiLU gate (Mamba-2 output normalization): normalize x * silu(z)."""

    def __init__(self, n_embd: int, eps: float = 1e-5):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(n_embd))

    def forward(self, x, z):
        x = x * F.silu(z)
        return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight


def _segsum(x):
    """Stable segment-sum: x (..., T) -> (..., T, T) lower-triangular cumulative sums."""
    T = x.size(-1)
    x = x.unsqueeze(-1).expand(*x.shape, T)
    mask = torch.tril(torch.ones(T, T, device=x.device, dtype=torch.bool), diagonal=-1)
    x = x.masked_fill(~mask, 0)
    x_segsum = torch.cumsum(x, dim=-2)
    mask = torch.tril(torch.ones(T, T, device=x.device, dtype=torch.bool), diagonal=0)
    x_segsum = x_segsum.masked_fill(~mask, float('-inf'))
    return x_segsum


def _ssd(X, A, B, C, chunk_size):
    """Chunked state-space-duality scan (Mamba-2).

    Args:
        X : (b, l, h, p)  input (already scaled by dt)
        A : (b, l, h)     per-step log-decay (= dt * A_scalar)
        B : (b, l, h, n)
        C : (b, l, h, n)
        chunk_size : int, must divide l
    Returns:
        Y : (b, l, h, p)
    """
    b, l, h, p = X.shape
    c = l // chunk_size
    X = X.reshape(b, c, chunk_size, h, p)
    A = A.reshape(b, c, chunk_size, h).permute(0, 3, 1, 2)   # (b, h, c, k)
    B = B.reshape(b, c, chunk_size, h, B.size(-1))
    C = C.reshape(b, c, chunk_size, h, C.size(-1))

    A_cumsum = torch.cumsum(A, dim=-1)                        # (b, h, c, k)

    # 1. intra-chunk (diagonal) outputs
    Lmat = torch.exp(_segsum(A))                             # (b, h, c, k, k)
    Y_diag = torch.einsum("bclhn,bcshn,bhcls,bcshp->bclhp", C, B, Lmat, X)

    # 2. each chunk's end state
    decay_states = torch.exp(A_cumsum[..., -1:] - A_cumsum)  # (b, h, c, k)
    states = torch.einsum("bclhn,bhcl,bclhp->bchpn", B, decay_states, X)

    # 3. inter-chunk recurrence (scan over chunks only)
    init = torch.zeros_like(states[:, :1])
    states = torch.cat([init, states], dim=1)               # (b, c+1, h, p, n)
    decay_chunk = torch.exp(_segsum(F.pad(A_cumsum[..., -1], (1, 0))))  # (b, h, c+1, c+1)
    new_states = torch.einsum("bhzc,bchpn->bzhpn", decay_chunk, states)
    states = new_states[:, :-1]                             # (b, c, h, p, n)

    # 4. add the contribution of each chunk's initial state to its outputs
    state_decay_out = torch.exp(A_cumsum)                   # (b, h, c, k)
    Y_off = torch.einsum("bclhn,bchpn,bhcl->bclhp", C, states, state_decay_out)

    return (Y_diag + Y_off).reshape(b, l, h, p)


class Mamba2Block(nn.Module):
    def __init__(self, config: Mamba2Config):
        super().__init__()
        self.config = config
        d_inner = config.d_inner
        nheads = config.nheads
        ngroups = config.ngroups
        d_state = config.d_state

        # in_proj produces [z, x, B, C, dt]
        conv_dim = d_inner + 2 * ngroups * d_state
        d_in_proj = 2 * d_inner + 2 * ngroups * d_state + nheads
        self.in_proj = nn.Linear(config.n_embd, d_in_proj, bias=config.bias)

        # depthwise conv over the (x, B, C) channels
        self.conv_dim = conv_dim
        self.conv1d = nn.Conv1d(
            in_channels=conv_dim,
            out_channels=conv_dim,
            kernel_size=config.d_conv,
            groups=conv_dim,
            bias=config.conv_bias,
            padding=config.d_conv - 1,
        )

        # dt bias (per head); softplus(dt + dt_bias) at runtime
        dt = torch.exp(
            torch.rand(nheads) * (math.log(config.dt_max) - math.log(config.dt_min))
            + math.log(config.dt_min)
        ).clamp(min=config.dt_init_floor)
        inv_dt = dt + torch.log(-torch.expm1(-dt))  # inverse softplus
        self.dt_bias = nn.Parameter(inv_dt)

        # per-head scalar A (stored in log space to keep A < 0 via A = -exp(A_log))
        A = torch.empty(nheads).uniform_(config.A_init_min, config.A_init_max)
        self.A_log = nn.Parameter(torch.log(A))
        self.A_log._no_weight_decay = True

        # per-head skip connection D
        self.D = nn.Parameter(torch.ones(nheads))
        self.D._no_weight_decay = True

        self.norm = RMSNormGated(d_inner, eps=config.rms_norm_eps)
        self.out_proj = nn.Linear(d_inner, config.n_embd, bias=config.bias)

        # Use the official fused Triton kernel only if requested AND available.
        self.use_kernel = bool(config.use_cuda) and _HAS_MAMBA2_KERNEL

    def forward(self, u):
        # u : (B, L, D)
        B_, L, _ = u.shape
        cfg = self.config
        d_inner, nheads, headdim = cfg.d_inner, cfg.nheads, cfg.headdim
        ngroups, d_state = cfg.ngroups, cfg.d_state

        zxbcdt = self.in_proj(u)  # (B, L, d_in_proj)
        z, xBC, dt = torch.split(
            zxbcdt, [d_inner, self.conv_dim, nheads], dim=-1)

        # depthwise conv (causal) over (x, B, C)
        xBC = xBC.transpose(1, 2)               # (B, conv_dim, L)
        xBC = self.conv1d(xBC)[:, :, :L]        # causal: drop the right padding
        xBC = xBC.transpose(1, 2)               # (B, L, conv_dim)
        xBC = F.silu(xBC)

        x, Bmat, Cmat = torch.split(
            xBC, [d_inner, ngroups * d_state, ngroups * d_state], dim=-1)

        A = -torch.exp(self.A_log.float())                       # (nheads,)
        x = x.view(B_, L, nheads, headdim)                       # (B, L, H, P)
        Bmat = Bmat.view(B_, L, ngroups, d_state)
        Cmat = Cmat.view(B_, L, ngroups, d_state)

        if self.use_kernel:
            # --- official fused Triton SSD kernel ---
            # It applies softplus(dt + dt_bias), the chunked scan, and the
            # per-head D skip connection internally. B/C keep the ngroups dim.
            y = mamba_chunk_scan_combined(
                x, dt, A, Bmat, Cmat,
                chunk_size=cfg.chunk_size,
                D=self.D,
                z=None,
                dt_bias=self.dt_bias,
                dt_softplus=True,
            )                                                    # (B, L, H, P)
            y = y.reshape(B_, L, d_inner).to(z.dtype)
        else:
            # --- pure-PyTorch chunked SSD scan (float32 for stability) ---
            dt = F.softplus(dt + self.dt_bias)                   # (B, L, nheads)
            # heads per group (ngroups==1 -> shared across all heads)
            rep = nheads // ngroups
            Bh = Bmat.repeat_interleave(rep, dim=2)              # (B, L, H, N)
            Ch = Cmat.repeat_interleave(rep, dim=2)             # (B, L, H, N)

            dt_f = dt.float()
            X_in = x.float() * dt_f.unsqueeze(-1)                # (B, L, H, P)
            A_in = A * dt_f                                      # (B, L, H)
            Bf = Bh.float()
            Cf = Ch.float()

            chunk = min(self.config.chunk_size, L)
            pad_len = (chunk - L % chunk) % chunk                # pad L up to a multiple of chunk
            if pad_len:
                X_in = F.pad(X_in, (0, 0, 0, 0, 0, pad_len))
                A_in = F.pad(A_in, (0, 0, 0, pad_len))
                Bf = F.pad(Bf, (0, 0, 0, 0, 0, pad_len))
                Cf = F.pad(Cf, (0, 0, 0, 0, 0, pad_len))

            y = _ssd(X_in, A_in, Bf, Cf, chunk)                 # (B, L_pad, H, P)
            y = y[:, :L]                                        # drop the padded steps
            y = y + self.D.float().view(1, 1, nheads, 1) * x.float()  # per-head skip
            y = y.reshape(B_, L, d_inner).to(z.dtype)           # back to input dtype

        y = self.norm(y, z)                                    # gated RMSNorm
        return self.out_proj(y)                                # (B, L, D)


class ResidualBlock2(nn.Module):
    def __init__(self, config: Mamba2Config):
        super().__init__()
        self.mixer = Mamba2Block(config)
        self.norm = RMSNorm(config.n_embd, config.rms_norm_eps)

    def forward(self, x):
        return self.mixer(self.norm(x)) + x


class Mamba2(nn.Module):
    def __init__(self, config: Mamba2Config):
        super().__init__()
        self.config = config

        self.embedding = nn.Embedding(config.vocab_size, config.n_embd, padding_idx=0)
        self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
        self.lm_head.weight = self.embedding.weight  # weight tying

        self.layers = nn.ModuleList([ResidualBlock2(config) for _ in range(config.n_layer)])
        self.out_norm = RMSNorm(config.n_embd, config.rms_norm_eps)

        self.apply(self._init_weights)
        for pn, p in self.named_parameters():
            if pn.endswith("out_proj.weight"):
                torch.nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * config.n_layer))

        print(f"number of parameters: {self.get_num_params() / 1e6:.2f}M")

        if config.use_cuda and _HAS_MAMBA2_KERNEL:
            print("[mamba2] using official fused Triton kernel (mamba_chunk_scan_combined)")
        elif config.use_cuda and not _HAS_MAMBA2_KERNEL:
            print("[mamba2] use_cuda=True but mamba_ssm kernel not found -> "
                  "falling back to pure-PyTorch chunked SSD")
        else:
            print("[mamba2] using pure-PyTorch chunked SSD scan")

    def _init_weights(self, module):
        if isinstance(module, nn.Linear):
            torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
            if module.bias is not None:
                torch.nn.init.zeros_(module.bias)
        elif isinstance(module, nn.Embedding):
            torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)

    def forward(self, idx, targets=None):
        x = self.embedding(idx)
        for layer in self.layers:
            x = layer(x)
        x = self.out_norm(x)

        if targets is not None:
            logits = self.lm_head(x)
            loss = F.cross_entropy(
                logits.view(-1, logits.size(-1)),
                targets.view(-1),
                ignore_index=self.config.pad_id,
            )
        else:
            logits = self.lm_head(x[:, [-1], :])
            loss = None
        return logits, loss

    @torch.no_grad()
    def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None, return_confidence=False):
        """Autoregressive generation matching model.mamba.Mamba.generate's contract."""
        confidences = [] if return_confidence else None
        top3_tokens = [] if return_confidence else None
        top3_probs = [] if return_confidence else None
        B = idx.size(0)

        for _ in range(max_new_tokens):
            logits, _ = self(idx)
            if temperature <= 0:
                probs = F.softmax(logits[:, -1, :], dim=-1)
                idx_next = probs.argmax(dim=-1, keepdim=True)
            else:
                logits = logits[:, -1, :] / temperature
                if top_k is not None:
                    v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
                    logits[logits < v[:, [-1]]] = -float('Inf')
                probs = F.softmax(logits, dim=-1)
                idx_next = torch.multinomial(probs, num_samples=1)

            if return_confidence:
                sampled_probs = probs.gather(1, idx_next).squeeze(-1)
                confidences.append(sampled_probs.cpu().tolist())
                top3_prob_vals, top3_token_ids = torch.topk(probs, 3, dim=-1)
                top3_tokens.append(top3_token_ids.cpu().tolist())
                top3_probs.append(top3_prob_vals.cpu().tolist())

            idx = torch.cat((idx, idx_next), dim=1)

        if return_confidence:
            if B == 1:
                return (idx,
                        [c[0] for c in confidences],
                        [t[0] for t in top3_tokens],
                        [p[0] for p in top3_probs])
            T = len(confidences)
            conf_bs = [[confidences[t][b] for t in range(T)] for b in range(B)]
            tok_bs = [[top3_tokens[t][b] for t in range(T)] for b in range(B)]
            prob_bs = [[top3_probs[t][b] for t in range(T)] for b in range(B)]
            return idx, conf_bs, tok_bs, prob_bs
        return idx

    def configure_optimizers(self, weight_decay, learning_rate, betas, device_type):
        param_dict = {pn: p for pn, p in self.named_parameters() if p.requires_grad}
        decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]
        nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2]
        optim_groups = [
            {"params": decay_params, "weight_decay": weight_decay},
            {"params": nodecay_params, "weight_decay": 0.0},
        ]
        num_decay = sum(p.numel() for p in decay_params)
        num_nodecay = sum(p.numel() for p in nodecay_params)
        print(f"num decayed parameter tensors: {len(decay_params)}, with {num_decay:,} parameters")
        print(f"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay:,} parameters")
        fused_available = "fused" in inspect.signature(torch.optim.AdamW).parameters
        use_fused = fused_available and device_type == "cuda"
        extra_args = dict(fused=True) if use_fused else {}
        optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, **extra_args)
        print(f"using fused AdamW: {use_fused}")
        return optimizer

    def estimate_mfu(self, fwdbwd_per_iter, dt):
        return -1

    def get_num_params(self, non_embedding=True):
        n_params = sum(p.numel() for p in self.parameters())
        if non_embedding:
            n_params -= self.embedding.weight.numel()
        return n_params