File size: 27,362 Bytes
e33fdea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
"""loopmm: a small looped, natively multimodal language model, in plain PyTorch.

Needs torch, safetensors and tokenizers (pillow for images, huggingface_hub to download). Runs on CPU or GPU.

    from modeling_loopmm import LoopMM
    model, tok = LoopMM.from_pretrained("MostLime/loopmm-base")
    print(model.complete(tok, "The best way to learn a new language is", max_new_tokens=30))

It also loads through transformers:

    from transformers import AutoModelForCausalLM, AutoTokenizer
    model = AutoModelForCausalLM.from_pretrained("MostLime/loopmm-base", trust_remote_code=True)

Layout: 24 layers in the LFM3 order (c = gated short conv, G = global attention, S = sliding-window attention):
    prelude  layers  0-5   c c G c S c          run once
    core     layers  6-17  G c S c G c S c G c S c    run n_loops times (3 by default) with the same weights
    coda     layers 18-23  S c G c S c ... (the rest)  run once
There is no running residual sum. Each sublayer reads a softmax mix over earlier "blocks" (Block AttnRes,
arXiv 2603.15031): the token embedding, the sums of finished blocks of 6 sublayers, and the current block so far.
Core pass r >= 2 starts from a gated mix of pass r-1's blocks. Images enter as raw 32 x 32 pixel patches through
a small MLP stem; there is no separate vision encoder.
"""
import json
import math
import os
from dataclasses import dataclass, field, fields, asdict

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

LAYER_TYPES = ['conv', 'conv', 'full', 'conv', 'swa', 'conv', 'full', 'conv', 'swa', 'conv', 'full', 'conv', 'swa',
               'conv', 'full', 'conv', 'swa', 'conv', 'full', 'conv', 'swa', 'conv', 'full', 'conv']
BOS, EOS, IM_START, IM_END = 1, 2, 6, 7
IMG_NEWLINE, IMG_PATCH, IMG_START, IMG_END = 395, 396, 498, 499
PIX_MEAN = (0.48145466, 0.4578275, 0.40821073)
PIX_STD = (0.26862954, 0.26130258, 0.27577711)


@dataclass
class LoopMMConfig:
    vocab_size: int = 65536
    hidden_size: int = 640
    layer_types: list = field(default_factory=lambda: list(LAYER_TYPES))
    num_attention_heads: int = 5
    num_key_value_heads: int = 1
    head_dim: int = 128
    intermediate_size: int = 2432
    conv_kernel: int = 7
    sliding_window: int = 256
    global_rope_theta: float = 1e6
    global_partial_rotary_factor: float = 0.5
    swa_rope_theta: float = 1e4
    rms_norm_eps: float = 1e-5
    prelude_layers: int = 6
    core_layers: int = 12
    num_loops: int = 3
    message_mode: str = 'start'       # 'start': gated message from the previous pass into the pass start; 'none'
    gate_rank: int = 64
    attnres_block: int = 6            # sublayers per AttnRes block
    patch_size: int = 32
    max_grid: int = 64
    image_bidirectional: bool = True
    attention_sink: bool = True
    max_image_tokens: int = 256
    bos_token_id: int = BOS

    @classmethod
    def from_dict(cls, d):
        names = {f.name for f in fields(cls)}
        return cls(**{k: v for k, v in d.items() if k in names})

    @classmethod
    def from_train_cfg(cls, d):
        """Map the training code's config (loopmm model.Cfg) to this one."""
        assert d.get('msg_mode', 'start') in ('start', 'none'), d.get('msg_mode')
        assert d.get('attnres', True)
        return cls(vocab_size=d['vocab'], hidden_size=d['d'], layer_types=list(d['layer_types']),
                   num_attention_heads=d['n_heads'], num_key_value_heads=d['n_kv'], head_dim=d['head_dim'],
                   intermediate_size=d['ff'], conv_kernel=d['conv_k'], sliding_window=d['window'],
                   global_rope_theta=d['full_theta'], global_partial_rotary_factor=d['full_partial'],
                   swa_rope_theta=d['swa_theta'], rms_norm_eps=d['eps'], prelude_layers=d['prelude'],
                   core_layers=d['core'], num_loops=d['n_loops'], message_mode=d['msg_mode'], gate_rank=d['gate_rank'],
                   attnres_block=d['ar_block'], patch_size=d['patch'], max_grid=d['max_grid'],
                   image_bidirectional=d['img_bidir'], attention_sink=d.get('attn_sink', 'none') == 'logit')


# ----------------------------------------------------------------------------- pieces
def rms(x, eps=1e-5):
    x = x.float()
    return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)


class RMSNorm(nn.Module):
    def __init__(self, d, eps):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(d))

    def forward(self, x):
        return (self.weight.float() * rms(x, self.eps)).to(x.dtype)


def rope_inv_freq(head_dim, theta, partial):
    """The first partial * head_dim / 2 frequencies of the usual progression; the rest are 0 (not rotated)."""
    n = int(partial * head_dim) // 2
    inv = 1.0 / (theta ** (torch.arange(0, 2 * n, 2, dtype=torch.float) / head_dim))
    return torch.cat([inv, torch.zeros(head_dim // 2 - n)])


def apply_rope(x, pos, inv_freq):
    """x [B, T, H, D], pos [T] absolute positions. rotate_half convention, fp32 math."""
    f = pos.float()[:, None] * inv_freq.to(x.device)[None]
    e = torch.cat([f, f], -1)
    cos, sin = e.cos()[None, :, None], e.sin()[None, :, None]
    xf = x.float()
    x1, x2 = xf.chunk(2, -1)
    return (xf * cos + torch.cat([-x2, x1], -1) * sin).to(x.dtype)


def attn_mask(q_pos, k_pos, img_q, img_k, window, bidir):
    """[B, Tq, Tk] bool. Keys: not after the query (or same image when bidir), not an empty slot (pos < 0),
    and within the window when window > 0."""
    m = (k_pos[None, :] <= q_pos[:, None])[None]
    if bidir:
        m = m | ((img_q[:, :, None] == img_k[:, None, :]) & (img_q[:, :, None] > 0))
    m = m & (k_pos >= 0)[None, None, :]
    if window:
        m = m & ((q_pos[:, None] - k_pos[None, :]).abs() < window)[None]
    return m


class Attention(nn.Module):
    """GQA, QK RMSNorm, RoPE, a sigmoid output gate per head, and an optional learned sink logit per head."""
    def __init__(self, c: LoopMMConfig, kind):
        super().__init__()
        self.c, self.kind = c, kind
        H, Hk, D, d = c.num_attention_heads, c.num_key_value_heads, c.head_dim, c.hidden_size
        self.q_proj = nn.Linear(d, H * D, bias=False)
        self.k_proj = nn.Linear(d, Hk * D, bias=False)
        self.v_proj = nn.Linear(d, Hk * D, bias=False)
        self.o_proj = nn.Linear(H * D, d, bias=False)
        self.q_norm = RMSNorm(D, c.rms_norm_eps)
        self.k_norm = RMSNorm(D, c.rms_norm_eps)
        self.gate_proj = nn.Linear(d, H, bias=False)
        self.sink = nn.Parameter(torch.zeros(H)) if c.attention_sink else None
        self.window = c.sliding_window if kind == 'swa' else 0
        if kind == 'full':
            self.rope = (c.global_rope_theta, c.global_partial_rotary_factor)
        else:
            self.rope = (c.swa_rope_theta, 1.0)

    def forward(self, x, pos, img, past=None):
        """x [B, T, d]; pos [T]; img [B, T] image id of each new token (0 = text); past = (k, v, k_pos) with
        k/v [B, P, Hk, D] and k_pos [P], or None. Returns (out, (k, v, k_pos)) including the new tokens."""
        c = self.c
        B, T, _ = x.shape
        H, Hk, D = c.num_attention_heads, c.num_key_value_heads, c.head_dim
        inv = rope_inv_freq(D, *self.rope)
        q = apply_rope(self.q_norm(self.q_proj(x).view(B, T, H, D)), pos, inv)
        k = apply_rope(self.k_norm(self.k_proj(x).view(B, T, Hk, D)), pos, inv)
        v = self.v_proj(x).view(B, T, Hk, D)
        if past is not None:
            pk, pv, ppos = past
            k, v = torch.cat([pk, k], 1), torch.cat([pv, v], 1)
            k_pos = torch.cat([ppos, pos])
            img_k = torch.cat([torch.zeros(B, pk.shape[1], dtype=img.dtype, device=img.device), img], 1)
        else:
            k_pos, img_k = pos, img
        mask = attn_mask(pos, k_pos, img, img_k, self.window, c.image_bidirectional)
        rep = H // Hk
        qt = q.transpose(1, 2).float()
        kt = k.repeat_interleave(rep, 2).transpose(1, 2).float()
        vt = v.repeat_interleave(rep, 2).transpose(1, 2).float()
        s = (qt @ kt.transpose(-1, -2)) / math.sqrt(D)
        s = s.masked_fill(~mask[:, None], float('-inf'))
        if self.sink is not None:       # one more softmax column per head with logit sink[h] and no value
            col = self.sink.float()[None, :, None, None].expand(B, H, T, 1)
            p = torch.cat([s, col], -1).softmax(-1)[..., :-1]
        else:
            p = s.softmax(-1)
        o = (p @ vt).transpose(1, 2).to(x.dtype)                     # [B, T, H, D]
        o = o * torch.sigmoid(self.gate_proj(x)).unsqueeze(-1).to(o.dtype)
        return self.o_proj(o.reshape(B, T, H * D)), (k, v, k_pos)


class ShortConv(nn.Module):
    """Gated short conv (LFM2/LFM3): (b, c, x) = in_proj(h); y = b * x; z = causal depthwise conv(y); out_proj(c * z).
    The state is the last K-1 values of y (zeros at the start of a sequence)."""
    def __init__(self, c: LoopMMConfig):
        super().__init__()
        self.c = c
        d = c.hidden_size
        self.in_proj = nn.Linear(d, 3 * d, bias=False)
        self.conv_w = nn.Parameter(torch.zeros(d, c.conv_kernel))
        self.out_proj = nn.Linear(d, d, bias=False)

    def forward(self, x, pos=None, img=None, past=None):
        B, T, d = x.shape
        K = self.c.conv_kernel
        b, cg, xx = self.in_proj(x).chunk(3, -1)
        y = (b * xx).float()
        if past is None:
            past = torch.zeros(B, K - 1, d, dtype=y.dtype, device=y.device)
        full = torch.cat([past.float(), y], 1)                      # [B, K-1+T, d]
        w = self.conv_w.float()
        z = full[:, 0:T] * w[:, 0]
        for i in range(1, K):
            z = z + full[:, i:i + T] * w[:, i]
        return self.out_proj((cg.float() * z).to(x.dtype)), full[:, T:]


class MLP(nn.Module):
    def __init__(self, c: LoopMMConfig):
        super().__init__()
        self.w13 = nn.Linear(c.hidden_size, 2 * c.intermediate_size, bias=False)
        self.w2 = nn.Linear(c.intermediate_size, c.hidden_size, bias=False)

    def forward(self, x, pos=None, img=None, past=None):
        a, b = self.w13(x).chunk(2, -1)
        return self.w2(F.silu(a) * b), None


class Sub(nn.Module):
    """One sublayer: RMSNorm -> operator -> RMSNorm (sandwich norm). Returns (v, new state)."""
    def __init__(self, op, c: LoopMMConfig):
        super().__init__()
        self.pre = RMSNorm(c.hidden_size, c.rms_norm_eps)
        self.op = op
        self.post = RMSNorm(c.hidden_size, c.rms_norm_eps)

    def forward(self, h, pos, img, past=None):
        y, st = self.op(self.pre(h), pos, img, past)
        return self.post(y), st


class Gate(nn.Module):
    """Message gate: u = W_down [rms(x), rms(m)]; x' = (1 - tanh(W_forget u)) x + tanh(W_gain u) m."""
    def __init__(self, d, r):
        super().__init__()
        self.down = nn.Linear(2 * d, r, bias=False)
        self.gain = nn.Linear(r, d, bias=False)
        self.forget = nn.Linear(r, d, bias=False)

    def forward(self, x, m):
        u = self.down(torch.cat([rms(x), rms(m)], -1).to(self.down.weight.dtype))
        g = torch.tanh(self.gain(u).float())
        f = torch.tanh(self.forget(u).float())
        return ((1 - f) * x.float() + g * m.float()).to(x.dtype)


class PatchStem(nn.Module):
    """Raw pixels -> image token embeddings. One token = 32 x 32 pixels = 2 x 2 sub-patches of 16 x 16.
    Each sub-patch: Linear -> RMSNorm -> GELU; a second Linear joins the four; then row/col embeddings and RMSNorm."""
    def __init__(self, c: LoopMMConfig):
        super().__init__()
        q = c.patch_size // 2
        self.q, d = q, c.hidden_size
        self.lin1 = nn.Linear(3 * q * q, d, bias=True)
        self.norm1 = RMSNorm(d, c.rms_norm_eps)
        self.lin2 = nn.Linear(4 * d, d, bias=True)
        self.row = nn.Parameter(torch.zeros(c.max_grid, d))
        self.col = nn.Parameter(torch.zeros(c.max_grid, d))
        self.norm = RMSNorm(d, c.rms_norm_eps)

    def forward(self, pix, rc):
        """pix [M, p, p, 3] uint8 (or float in 0..255); rc [M, 2] row/col of each token in its image grid."""
        M, q = pix.shape[0], self.q
        x = pix.float() / 255.0
        x = (x - torch.tensor(PIX_MEAN, device=x.device)) / torch.tensor(PIX_STD, device=x.device)
        x = x.reshape(M, 2, q, 2, q, 3).permute(0, 1, 3, 2, 4, 5).reshape(M, 4, 3 * q * q)
        h = F.gelu(self.norm1(self.lin1(x.to(self.lin1.weight.dtype))))
        e = self.lin2(h.reshape(M, -1)) + self.row[rc[:, 0]] + self.col[rc[:, 1]]
        return self.norm(e)


def ar_mix(vals, q):
    """Block AttnRes: softmax over sources of rms(v_i) . q, then the weighted sum of the v_i."""
    if len(vals) == 1:
        return vals[0]
    logits = torch.stack([(rms(v) * q.float()).sum(-1) for v in vals], 0)
    a = logits.softmax(0)
    h = a[0, ..., None] * vals[0].float()
    for i in range(1, len(vals)):
        h = h + a[i, ..., None] * vals[i].float()
    return h.to(vals[0].dtype)


# ----------------------------------------------------------------------------- image helpers
def image_grid(h, w, max_tokens=256, p=32, min_tokens=16, max_side=64):
    """Grid (rows, cols) of 32 x 32 tokens for an h x w image: keep the aspect ratio, at most max_tokens."""
    native = (h / p) * (w / p)
    target = min(max_tokens, max(native, min_tokens))
    s = math.sqrt(target / native)
    gh, gw = max(1, round(h / p * s)), max(1, round(w / p * s))
    gh, gw = min(gh, max_side), min(gw, max_side)
    while gh * gw > max_tokens:
        if gh >= gw: gh -= 1
        else: gw -= 1
    return gh, gw


def image_span(gh, gw):
    """Token ids of one image: <|image_start|> ([<image>] * gw + <newline slot>) * gh <|image_end|>."""
    return [IMG_START] + ([IMG_PATCH] * gw + [IMG_NEWLINE]) * gh + [IMG_END]


def load_image(image, max_tokens=256, p=32):
    """PIL image or path -> (pix [gh*gw, p, p, 3] uint8, rc [gh*gw, 2], gh, gw)."""
    from PIL import Image
    import numpy as np
    im = Image.open(image) if isinstance(image, (str, os.PathLike)) else image
    im = im.convert('RGB')
    gh, gw = image_grid(im.height, im.width, max_tokens, p)
    a = np.asarray(im.resize((gw * p, gh * p), Image.BICUBIC)).copy()
    pix = torch.from_numpy(a).view(gh, p, gw, p, 3).permute(0, 2, 1, 3, 4).reshape(gh * gw, p, p, 3)
    r = torch.arange(gh).repeat_interleave(gw)
    c = torch.arange(gw).repeat(gh)
    return pix, torch.stack([r, c], 1), gh, gw


# ----------------------------------------------------------------------------- model
class Cache:
    """Per-sublayer states, keyed by part ('pre', 'core0', 'core1', ..., 'coda') and sublayer index. Each core pass
    keeps its own key/value cache and conv state."""
    def __init__(self):
        self.parts, self.n = {}, 0

    def part(self, tag):
        return self.parts.setdefault(tag, {})


class _LoopMMBody:
    """Modules and math shared by the plain model (LoopMM) and the transformers wrapper (LoopMMForCausalLM)."""
    def _build(self, c: LoopMMConfig):
        self.cfg = c
        d = c.hidden_size
        self.emb = nn.Embedding(c.vocab_size, d)
        subs = []
        for t in c.layer_types:
            subs.append(Sub(ShortConv(c) if t == 'conv' else Attention(c, t), c))
            subs.append(Sub(MLP(c), c))
        self.subs = nn.ModuleList(subs)
        self.ar_q = nn.Parameter(torch.zeros(len(subs) + 1, d))
        if c.message_mode == 'start':
            self.msg_q = nn.Parameter(torch.zeros(1, d))
            self.gates = nn.ModuleList([Gate(d, c.gate_rank)])
        self.stem = PatchStem(c)
        self.norm = RMSNorm(d, c.rms_norm_eps)

    # ---- the three parts (also used by the ONNX export)
    def run_subs(self, j0, j1, srcs, pos, img, states):
        """Sublayers j0..j1-1 with Block AttnRes. states: {j: past state} (updated in place). Returns the block sums
        made here (the last may be partial)."""
        B = self.cfg.attnres_block
        new, partial = [], None
        for j in range(j0, j1):
            if partial is not None and (j - j0) % B == 0:
                srcs = srcs + [partial]
                new.append(partial)
                partial = None
            h = ar_mix(srcs + ([] if partial is None else [partial]), self.ar_q[j])
            v, st = self.subs[j](h, pos, img, states.get(j))
            if st is not None: states[j] = st
            partial = v if partial is None else partial + v
        new.append(partial)
        return new

    def prelude(self, x, pos, img, states):
        P = 2 * self.cfg.prelude_layers
        return [x] + self.run_subs(0, P, [x], pos, img, states)

    def core_pass(self, base, bank, pos, img, states):
        """One core pass. bank: the previous pass's core blocks, or None for the first pass."""
        c = self.cfg
        P, C = 2 * c.prelude_layers, 2 * c.core_layers
        srcs = base
        if bank is not None and c.message_mode == 'start':
            bv = [rms(v).to(v.dtype) for v in bank]
            m = ar_mix(bv, self.msg_q[0])
            srcs = base[:-1] + [self.gates[0](base[-1], m)]
        return self.run_subs(P, P + C, srcs, pos, img, states)

    def coda(self, srcs, pos, img, states):
        c = self.cfg
        P, C, S = 2 * c.prelude_layers, 2 * c.core_layers, len(self.subs)
        out = self.run_subs(P + C, S, srcs, pos, img, states)
        return self.norm(ar_mix(srcs + out, self.ar_q[S]))

    def embed(self, ids, pix=None, rc=None, slot=None):
        x = self.emb(ids)
        if pix is None or pix.shape[0] == 0:
            return x
        B, T, d = x.shape
        e = self.stem(pix, rc).to(x.dtype)
        return x.reshape(B * T, d).index_copy(0, slot, e).view(B, T, d)

    def hidden(self, x, pos, img, cache, n_loops=None):
        c = self.cfg
        n_loops = n_loops or c.num_loops
        base = self.prelude(x, pos, img, cache.part('pre'))
        core = None
        for r in range(n_loops):
            core = self.core_pass(base, core, pos, img, cache.part(f'core{r}'))
        h = self.coda(base + core, pos, img, cache.part('coda'))
        # sliding-window layers only need the last `window` keys
        for part in cache.parts.values():
            for j, st in part.items():
                op = self.subs[j].op
                if isinstance(op, Attention) and op.window and st[2].shape[0] > op.window:
                    part[j] = (st[0][:, -op.window:], st[1][:, -op.window:], st[2][-op.window:])
        return h

    def logits_from(self, ids, pix=None, rc=None, slot=None, img=None, cache=None, n_loops=None):
        """ids [B, T] continue the sequence in `cache` (a new Cache when None). img [B, T]: image id per token
        (0 = text; patches, row ends and <|image_end|> of one image share an id > 0). pix/rc/slot: image patches,
        their grid row/col, and their flat index into ids. Returns logits [B, T, V]."""
        cache = Cache() if cache is None else cache
        B, T = ids.shape
        pos = cache.n + torch.arange(T, device=ids.device)
        if img is None:
            img = torch.zeros_like(ids)
        x = self.embed(ids, pix, rc, slot)
        h = self.hidden(x, pos, img, cache, n_loops)
        cache.n += T
        return F.linear(h, self.emb.weight)

    # ---- generation
    def _encode(self, tok, text):
        e = tok.encode(text, add_special_tokens=False)
        return list(e.ids) if hasattr(e, 'ids') else list(e)

    def _decode(self, tok, ids):
        return tok.decode(ids, skip_special_tokens=True)

    def build_inputs(self, pieces, max_image_tokens=None):
        """pieces: list of token-id lists and images (PIL or path) in order -> ids, img, pix, rc, slot."""
        max_image_tokens = max_image_tokens or self.cfg.max_image_tokens
        ids, img, pix, rc, slot, n_img = [], [], [], [], [], 0
        for p in pieces:
            if isinstance(p, (list, tuple)):
                ids += list(p); img += [0] * len(p)
                continue
            px, r, gh, gw = load_image(p, max_image_tokens, self.cfg.patch_size)
            n_img += 1
            s = len(ids)
            ids += image_span(gh, gw)
            img += [0] + [n_img] * (gh * (gw + 1) + 1)
            pix.append(px); rc.append(r)
            slot.append(s + 1 + r[:, 0] * (gw + 1) + r[:, 1])
        dev = self.emb.weight.device
        out = dict(ids=torch.tensor([ids], device=dev), img=torch.tensor([img], device=dev))
        if pix:
            out.update(pix=torch.cat(pix).to(dev), rc=torch.cat(rc).to(dev), slot=torch.cat(slot).to(dev))
        return out

    @torch.no_grad()
    def generate_from(self, inputs, max_new_tokens=100, temperature=0.7, top_p=0.9, top_k=0, repetition_penalty=1.0,
                      n_loops=None, stop_ids=(EOS, IM_END)):
        """inputs from build_inputs. Returns the new token ids."""
        cache = Cache()
        logits = self.logits_from(inputs['ids'], inputs.get('pix'), inputs.get('rc'), inputs.get('slot'),
                                  inputs['img'], cache, n_loops)[:, -1]
        out, seen = [], inputs['ids'][0].tolist()
        for _ in range(max_new_tokens):
            lg = logits[0].float()
            if repetition_penalty != 1.0 and seen:
                idx = torch.tensor(sorted(set(seen)), device=lg.device)
                v = lg[idx]
                lg[idx] = torch.where(v > 0, v / repetition_penalty, v * repetition_penalty)
            if temperature <= 0:
                nxt = int(lg.argmax())
            else:
                lg = lg / temperature
                if top_k:
                    kth = lg.topk(top_k).values[-1]
                    lg = lg.masked_fill(lg < kth, float('-inf'))
                pr = lg.softmax(-1)
                if top_p < 1.0:
                    sp, si = pr.sort(descending=True)
                    keep = sp.cumsum(0) - sp < top_p
                    pr = torch.zeros_like(pr).scatter(0, si[keep], sp[keep])
                nxt = int(torch.multinomial(pr / pr.sum(), 1))
            if nxt in stop_ids:
                break
            out.append(nxt); seen.append(nxt)
            ids = torch.tensor([[nxt]], device=self.emb.weight.device)
            logits = self.logits_from(ids, img=torch.zeros_like(ids), cache=cache, n_loops=n_loops)[:, -1]
        return out

    def complete(self, tok, text, image=None, **kw):
        """Continue `text` (base-model use). With `image`, the image comes first, then the text."""
        pieces = [[BOS]] + ([image] if image is not None else []) + [self._encode(tok, text)]
        kw.setdefault('stop_ids', (BOS, EOS))
        return self._decode(tok, self.generate_from(self.build_inputs(pieces), **kw))

    def chat(self, tok, messages, thinking=True, max_image_tokens=576, **kw):
        """messages: [{'role': 'user', 'content': 'text', 'images': [PIL or path, ...]}, ...] (images optional; they
        go right after the role line, before the text). ChatML format of the chat model. The reply starts with a
        <think> block; thinking=False asks for an empty one (system prompt "Thinking: off"). Returns the reply text,
        think block included (split it with split_thinking)."""
        msgs = list(messages)
        if not thinking:
            if msgs and msgs[0]['role'] == 'system':
                msgs[0] = dict(msgs[0], content=msgs[0]['content'] + '\nThinking: off')
            else:
                msgs = [{'role': 'system', 'content': 'Thinking: off'}] + msgs
        pieces = [[BOS]]
        for m in msgs:
            pieces.append(self._encode(tok, f"<|im_start|>{m['role']}\n"))
            pieces += list(m.get('images') or [])
            pieces.append(self._encode(tok, f"{m['content']}<|im_end|>\n"))
        prefill = '' if thinking else '<think>\n</think>\n\n'
        pieces.append(self._encode(tok, '<|im_start|>assistant\n' + prefill))
        kw.setdefault('temperature', 0.2)
        out = self.generate_from(self.build_inputs(pieces, max_image_tokens), **kw)
        return prefill + self._decode(tok, out)


def split_thinking(reply):
    """'<think>\n...\n</think>\n\nanswer' -> (thinking, answer)."""
    if '<think>' in reply and '</think>' in reply:
        a, b = reply.split('</think>', 1)
        return a.split('<think>', 1)[1].strip(), b.strip()
    return '', reply.strip()


class LoopMM(nn.Module, _LoopMMBody):
    def __init__(self, config: LoopMMConfig):
        super().__init__()
        self.config = config
        self._build(config)

    def forward(self, input_ids, n_loops=None, **image_inputs):
        return self.logits_from(input_ids, n_loops=n_loops, **image_inputs)

    @classmethod
    def from_pretrained(cls, repo_or_dir="MostLime/loopmm-base", revision=None, device='cpu', dtype=torch.float32):
        """Returns (model, tokenizer). repo_or_dir: a local folder or a Hugging Face repo id."""
        from safetensors.torch import load_file
        from tokenizers import Tokenizer

        def path(name):
            if os.path.isdir(repo_or_dir):
                return os.path.join(repo_or_dir, name)
            from huggingface_hub import hf_hub_download
            return hf_hub_download(repo_or_dir, name, revision=revision)

        cfg = LoopMMConfig.from_dict(json.load(open(path('config.json'))))
        m = cls(cfg)
        m.load_state_dict(load_file(path('model.safetensors')), strict=True)
        return m.to(device=device, dtype=dtype).eval(), Tokenizer.from_file(path('tokenizer.json'))


# ----------------------------------------------------------------------------- transformers wrapper (optional)
try:
    from transformers import PretrainedConfig, PreTrainedModel
    from transformers.modeling_outputs import CausalLMOutput

    class LoopMMHFConfig(PretrainedConfig):
        model_type = 'loopmm'

        def __init__(self, **kw):
            base = asdict(LoopMMConfig())
            for k in list(base):
                if k in kw: base[k] = kw.pop(k)
            for k, v in base.items():
                setattr(self, k, v)
            kw.setdefault('tie_word_embeddings', True)
            super().__init__(**kw)

    class LoopMMForCausalLM(PreTrainedModel, _LoopMMBody):
        config_class = LoopMMHFConfig
        base_model_prefix = ''
        _no_split_modules = ['Sub']

        def __init__(self, config):
            super().__init__(config)
            self._build(LoopMMConfig.from_dict(config.to_dict()))
            self.post_init()

        def _init_weights(self, module):
            pass                                  # every weight comes from the checkpoint

        def get_input_embeddings(self):
            return self.emb

        def forward(self, input_ids=None, labels=None, n_loops=None, pix=None, rc=None, slot=None, img=None, **kw):
            logits = self.logits_from(input_ids, pix, rc, slot, img, None, n_loops)
            loss = None
            if labels is not None:
                loss = F.cross_entropy(logits[:, :-1].flatten(0, 1).float(), labels[:, 1:].flatten(), ignore_index=-100)
            return CausalLMOutput(loss=loss, logits=logits)
except ImportError:      # transformers is optional
    pass


if __name__ == '__main__':
    import sys
    d = sys.argv[1] if len(sys.argv) > 1 else 'MostLime/loopmm-base'
    model, tok = LoopMM.from_pretrained(d)
    print(model.complete(tok, sys.argv[2] if len(sys.argv) > 2 else 'The best way to learn a new language is',
                         max_new_tokens=40))