File size: 45,962 Bytes
c5dd0d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
"""
trout.py -- a from-scratch diffusion language model for 16x16 pixel art.

Trout treats a 16x16 sprite as a 256-token "sentence" over a learned 512-color
palette (token 0 = transparent). A bidirectional transformer denoiser starts
from a fully masked canvas and unmasks all pixels in parallel over ~16 steps,
conditioned on a frozen CLIP text tower. No VAE, no latent space, no
autoregression -- absorbing-state masked (discrete) diffusion.

Architecture (hourglass dual-resolution denoiser, 47.6M params for the small
preset), reimplemented from scratch following the design published with
Tessera-small by Jagrat Patel (TheJagStudio), whose model card and open demo
space document every choice below:

  * joint [registers | text tokens | pixel tokens] bidirectional attention
  * hourglass: depth_in pixel-level blocks -> 2x2 patch-merged core blocks
    -> depth_out pixel-level blocks, with a residual skip around the core
  * QK-RMSNorm, 2D axial RoPE (theta=100) with sub-pixel-aligned patch centers
  * Conv-SwiGLU: depthwise 3x3 conv on the gate branch over image tokens
  * adaLN-single conditioning: shared MLP on (pooled text + mask ratio
    Fourier features) with per-block learned modulation offsets and
    zero-initialized gates (blocks start as identity)
  * color-grounded token embeddings: learned vector + MLP(Fourier(OKLab))
  * 4 register tokens in the prefix
  * self-conditioning: the previous step's predicted color distribution is
    projected and added at masked positions

Theory sources (the "knowledge" this model is built on):
  * Absorbing-state / masked discrete diffusion:
      Sahoo et al., "Simple and Effective Masked Diffusion Language Models",
      NeurIPS 2024 (arXiv:2406.07524)  -- MDLM
      Shi et al., "Simplified and Generalized Masked Diffusion for Discrete
      Data", NeurIPS 2024 (arXiv:2406.04329)
      Labadie & Ye, "Absorbing State Discrete Diffusion" survey, 2025.
  * Parallel confidence-ordered decoding: Chang et al., "MaskGIT: Masked
      Generative Image Transformer", CVPR 2022.
  * Hourglass transformer: Blecher et al., "Nougat" (arXiv:2308.13418).
  * adaLN-single: Peebles & Xie, "DiT" (arXiv:2212.09748); PixArt-alpha.
  * Registers: Darcet et al., "Vision Transformers Need Registers" (ICLR 2024).
  * QK-norm: Gemma/Henry et al. "Training Transformers with ... QK-Norm".
  * Self-conditioning: Chen, "Analog Bits" (arXiv:2208.04202).
  * Muon optimizer: Jordan et al. (arXiv:2502.16982) and Moonshot
      "Muon is Scalable" (arXiv:2508.02535) for the 0.2*sqrt(max(m,n)) scale.
  * OKLab: Bjorn Ottosson, "A perceptual color space for image processing"
      (2020) -- public-domain reference formulas.

Written by Z.ai for the user's "Trout" project; trained code lives in
train_trout.py. Apache-2.0.
"""

from __future__ import annotations

import json
import math
import os
from dataclasses import asdict, dataclass, field
from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

DEFAULT_TEXT_ENCODER = "openai/clip-vit-base-patch32"


# ---------------------------------------------------------------------------
# configuration
# ---------------------------------------------------------------------------

@dataclass
class TroutConfig:
    """Architecture hyper-parameters for the Trout denoiser."""
    vocab_size: int = 512      # palette entries incl. transparent (index 0); MASK id == vocab_size
    grid_size: int = 16         # image is grid_size x grid_size tokens
    dim: int = 512              # residual width
    n_heads: int = 8
    depth_in: int = 2           # pixel-level blocks before the 2x2 merge
    depth_core: int = 8         # patch-level blocks on merged (grid/patch)^2 tokens
    depth_out: int = 2          # pixel-level blocks after the unmerge
    patch: int = 2              # hourglass merge factor (1 = flat model)
    mlp_ratio: float = 3.0      # SwiGLU hidden = mlp_ratio * dim
    n_registers: int = 4        # learnable register tokens in the prefix
    text_dim: int = 512         # hidden size of the frozen CLIP text tower
    text_len: int = 24          # text tokens fed to the denoiser
    rope_theta: float = 100.0   # base of the 2D axial RoPE frequencies
    conv_ffn: bool = True       # depthwise 3x3 conv on the gate branch
    color_freqs: int = 6        # Fourier frequencies for OKLab color embeddings
    self_cond: bool = True      # feed previous-step predictions back as input

    @property
    def mask_id(self) -> int:
        return self.vocab_size

    @property
    def num_tokens(self) -> int:
        return self.grid_size * self.grid_size

    @property
    def hourglass(self) -> bool:
        return self.patch > 1 and self.depth_core > 0

    @property
    def head_dim(self) -> int:
        return self.dim // self.n_heads

    @property
    def mlp_hidden(self) -> int:
        return int(self.dim * self.mlp_ratio)

    def validate(self) -> None:
        assert self.dim % self.n_heads == 0
        assert self.head_dim % 4 == 0, "head_dim must be divisible by 4 (2D axial RoPE)"
        if self.hourglass:
            assert self.grid_size % self.patch == 0

    def to_dict(self) -> Dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, d: Dict[str, Any]) -> "TroutConfig":
        import dataclasses as _dc
        names = {f.name for f in _dc.fields(cls)}
        keep = {k: v for k, v in d.items() if k in names}
        cfg = cls(**keep)
        cfg.validate()
        return cfg


SMALL_PRESET: Dict[str, Any] = dict(
    dim=512, n_heads=8, depth_in=2, depth_core=8, depth_out=2,
)  # matches Tessera-small; ~47.6M parameters


# ---------------------------------------------------------------------------
# OKLab color math (Bjorn Ottosson's public-domain formulas)
# ---------------------------------------------------------------------------

def _srgb_to_linear_np(c):
    return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)


def _linear_to_srgb_np(c):
    c = np.clip(c, 0.0, 1.0)
    return np.where(c <= 0.0031308, 12.92 * c, 1.055 * np.maximum(c, 1e-12) ** (1 / 2.4) - 0.055)


def srgb_to_oklab(rgb: np.ndarray) -> np.ndarray:
    """rgb: (..., 3) in [0,255]. Returns OKLab (..., 3) float32."""
    x = np.asarray(rgb, dtype=np.float64) / 255.0
    lin = _srgb_to_linear_np(x)
    r, g, b = lin[..., 0], lin[..., 1], lin[..., 2]
    l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b
    m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b
    s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b
    l_, m_, s_ = np.cbrt(np.maximum(l, 0)), np.cbrt(np.maximum(m, 0)), np.cbrt(np.maximum(s, 0))
    L = 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_
    A = 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_
    B = 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_
    return np.stack([L, A, B], -1).astype(np.float32)


def _torch_srgb_to_linear(c):
    return torch.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)


def srgb_to_oklab_t(rgb: torch.Tensor) -> torch.Tensor:
    x = rgb.float() / 255.0
    lin = _torch_srgb_to_linear(x)
    r, g, b = lin[..., 0], lin[..., 1], lin[..., 2]
    l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b
    m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b
    s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b
    l_ = torch.pow(l.clamp(min=0), 1 / 3)
    m_ = torch.pow(m.clamp(min=0), 1 / 3)
    s_ = torch.pow(s.clamp(min=0), 1 / 3)
    L = 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_
    A = 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_
    B = 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_
    return torch.stack([L, A, B], -1).float()


def rgb_to_key(rgb: np.ndarray) -> np.ndarray:
    rgb = rgb.astype(np.int64)
    return (rgb[..., 0] << 16) | (rgb[..., 1] << 8) | rgb[..., 2]


def key_to_rgb(key: np.ndarray) -> np.ndarray:
    key = np.asarray(key, dtype=np.int64)
    return np.stack([(key >> 16) & 255, (key >> 8) & 255, key & 255], -1).astype(np.uint8)


# ---------------------------------------------------------------------------
# palette: 512 colors, frequency-weighted k-means in OKLab, snapped to data
# ---------------------------------------------------------------------------

def _weighted_kmeans(x: torch.Tensor, w: torch.Tensor, k: int, iters: int = 60,
                     seed: int = 0) -> torch.Tensor:
    """Weighted k-means with k-means++ init. x: (U,3), w: (U,). Returns (k,3)."""
    g = torch.Generator().manual_seed(seed)
    U = x.shape[0]
    w = w.float()
    first = torch.multinomial(w, 1, generator=g).item()
    centers = [x[first]]
    d2 = ((x - x[first]) ** 2).sum(1)
    for _ in range(1, k):
        p = (w * d2)
        if p.sum() <= 0:
            j = int(torch.randint(U, (1,), generator=g))
        else:
            j = torch.multinomial(p.clamp(min=0), 1, generator=g).item()
        centers.append(x[j])
        d2 = torch.minimum(d2, ((x - x[j]) ** 2).sum(1))
    C = torch.stack(centers).clone()
    for _ in range(iters):
        # nearest assignment, chunked to bound memory
        idx = torch.empty(U, dtype=torch.long)
        mind = torch.empty(U)
        c2 = (C * C).sum(1)
        for s in range(0, U, 1 << 18):
            p = x[s:s + (1 << 18)]
            d = (p * p).sum(1, keepdim=True) - 2 * p @ C.T + c2[None]
            dv, di = d.min(1)
            idx[s:s + p.shape[0]] = di
            mind[s:s + p.shape[0]] = dv.clamp(min=0)
        sums = torch.zeros_like(C).index_add_(0, idx, x * w[:, None])
        ws = torch.zeros(k).index_add_(0, idx, w)
        newC = torch.where((ws <= 0)[:, None], C, sums / ws.clamp(min=1e-12)[:, None])
        nempty = int((ws <= 0).sum())
        if nempty > 0:
            worst = torch.topk(w * mind, nempty).indices
            newC[ws <= 0] = x[worst]
        shift = (newC - C).norm(dim=1).max().item()
        C = newC
        if shift < 1e-7:
            break
    return C


class Palette:
    """A fixed list of colors. Index 0 = transparent; 1..K-1 opaque sRGB."""

    def __init__(self, colors: np.ndarray, name: str = "custom"):
        colors = np.asarray(colors, dtype=np.uint8).reshape(-1, 3).copy()
        colors[0] = 0
        self.colors = colors
        self.name = name
        lab = srgb_to_oklab(colors)
        lab[0] = 0.0
        self.lab = lab

    @property
    def size(self) -> int:
        return int(self.colors.shape[0])

    def __len__(self) -> int:
        return self.size

    def rgba_table(self) -> np.ndarray:
        t = np.concatenate([self.colors, np.full((self.size, 1), 255, np.uint8)], 1)
        t[0] = 0
        return t

    def tokens_to_rgba(self, tokens) -> np.ndarray:
        if isinstance(tokens, torch.Tensor):
            tokens = tokens.detach().cpu().numpy()
        tokens = np.asarray(tokens).astype(np.int64)
        table = np.concatenate([self.rgba_table(), np.array([[255, 0, 255, 255]], np.uint8)], 0)
        return table[np.clip(tokens, 0, self.size)]

    def nearest_index(self, rgb: np.ndarray) -> np.ndarray:
        """Nearest opaque entry (1..K-1) in OKLab for (M,3) uint8."""
        if rgb.shape[0] == 0:
            return np.zeros(0, np.int64)
        pts = torch.from_numpy(srgb_to_oklab(rgb))
        cen = torch.from_numpy(self.lab[1:])
        idx, _ = self._nearest(pts, cen)
        return idx.numpy() + 1

    @staticmethod
    def _nearest(points: torch.Tensor, centers: torch.Tensor, chunk: int = 1 << 18):
        idx = torch.empty(points.shape[0], dtype=torch.long)
        dist = torch.empty(points.shape[0])
        c2 = (centers * centers).sum(1)
        for s in range(0, points.shape[0], chunk):
            p = points[s:s + chunk]
            d = (p * p).sum(1, keepdim=True) - 2 * p @ centers.T + c2[None]
            dv, di = d.min(1)
            idx[s:s + p.shape[0]] = di
            dist[s:s + p.shape[0]] = dv.clamp(min=0)
        return idx, dist

    def build_lut(self, keys: np.ndarray) -> Dict[str, np.ndarray]:
        keys = np.unique(np.asarray(keys, dtype=np.int64))
        idx = self.nearest_index(key_to_rgb(keys))
        return {"keys": keys, "idx": idx.astype(np.uint16)}

    def quantize_rgba(self, rgba: np.ndarray, alpha_threshold: int = 128,
                      lut: Optional[dict] = None) -> np.ndarray:
        """uint8 RGBA (...,4) -> uint16 tokens (...); alpha<thresh -> transparent."""
        rgba = np.asarray(rgba)
        shape = rgba.shape[:-1]
        flat = rgba.reshape(-1, 4)
        opaque = flat[:, 3] >= alpha_threshold
        out = np.zeros(flat.shape[0], np.uint16)
        if opaque.any():
            keys = rgb_to_key(flat[opaque, :3])
            if lut is None:
                lut = self.build_lut(keys)
            pos = np.searchsorted(lut["keys"], keys)
            pos = np.clip(pos, 0, len(lut["keys"]) - 1)
            hit = lut["keys"][pos] == keys
            vals = lut["idx"][pos]
            if not hit.all():
                miss = ~hit
                vals = vals.copy()
                vals[miss] = self.nearest_index(key_to_rgb(keys[miss]))
            out[opaque] = vals
        return out.reshape(shape)

    def soft_targets(self, tau: float = 0.05) -> torch.Tensor:
        """(K,K) row-stochastic matrix for perceptual label smoothing:
        row c = softmax over opaque colors of -dE(c,.)^2 / tau^2."""
        lab = torch.from_numpy(self.lab).double()
        d2 = torch.cdist(lab, lab) ** 2
        logits = -d2 / (tau * tau)
        logits[:, 0] = -math.inf
        S = torch.softmax(logits, dim=1)
        S[0] = 0.0
        S[0, 0] = 1.0
        return S.float()

    def to_dict(self) -> Dict[str, Any]:
        return {"name": self.name, "colors": self.colors.tolist()}

    @classmethod
    def from_dict(cls, d: Dict[str, Any]) -> "Palette":
        return cls(np.array(d["colors"], dtype=np.uint8), name=d.get("name", "custom"))

    def save(self, path: str) -> None:
        with open(path, "w") as f:
            json.dump(self.to_dict(), f)

    @classmethod
    def load(cls, path: str) -> "Palette":
        with open(path) as f:
            return cls.from_dict(json.load(f))

    def preview(self, cell: int = 12, cols: int = 32) -> "Image":
        from PIL import Image
        rows = math.ceil(self.size / cols)
        img = np.full((rows * cell, cols * cell, 3), 255, np.uint8)
        for i in range(self.size):
            r, c = divmod(i, cols)
            if i == 0:
                yy, xx = np.mgrid[0:cell, 0:cell]
                img[r * cell:(r + 1) * cell, c * cell:(c + 1) * cell] = np.where(
                    (((yy // 3) + (xx // 3)) % 2 == 0)[..., None], 200, 140)
            else:
                img[r * cell:(r + 1) * cell, c * cell:(c + 1) * cell] = self.colors[i]
        return Image.fromarray(img)

    @classmethod
    def build_kmeans(cls, keys: np.ndarray, counts: np.ndarray, size: int = 512,
                     weight_power: float = 0.5, iters: int = 60, seed: int = 0) -> "Palette":
        """Data-driven palette: 1 transparent + size-1 opaque colors chosen by
        frequency-weighted (tempered by weight_power) k-means in OKLab, with
        centroids snapped to real dataset colors so exact hues survive."""
        keys = np.asarray(keys, dtype=np.int64)
        counts = np.asarray(counts, dtype=np.float64)
        k = size - 1
        rgb = key_to_rgb(keys)
        if keys.shape[0] <= k:
            colors = np.concatenate([np.zeros((1, 3), np.uint8), rgb], 0)
            return cls._sorted(colors, name=f"exact{len(colors)}")
        x = torch.from_numpy(srgb_to_oklab(rgb))
        w = torch.from_numpy(counts ** weight_power)
        C = _weighted_kmeans(x, w, k, iters=iters, seed=seed)
        snap_idx, _ = cls._nearest(C, x)
        snap_idx = snap_idx.numpy()
        chosen = list(dict.fromkeys(snap_idx.tolist()))
        if len(chosen) < k:  # fill duplicate slots with worst-represented colors
            cen = x[torch.as_tensor(chosen)]
            _, dist = cls._nearest(x, cen)
            order = torch.argsort(w * dist, descending=True).numpy()
            for j in order:
                if len(chosen) >= k:
                    break
                if int(j) not in chosen:
                    chosen.append(int(j))
        colors = np.concatenate([np.zeros((1, 3), np.uint8), rgb[np.array(chosen[:k])]], 0)
        return cls._sorted(colors, name=f"kmeans{size}")

    @classmethod
    def _sorted(cls, colors: np.ndarray, name: str) -> "Palette":
        """Order opaque colors by hue bucket then lightness (readable palette)."""
        opaque = colors[1:]
        lab = srgb_to_oklab(opaque)
        chroma = np.sqrt(lab[:, 1] ** 2 + lab[:, 2] ** 2)
        hue = np.arctan2(lab[:, 2], lab[:, 1])
        bucket = np.where(chroma < 0.03, -1, np.floor((hue + np.pi) / (2 * np.pi) * 12)).astype(np.int64)
        order = np.lexsort((lab[:, 0], bucket))
        return cls(np.concatenate([colors[:1], opaque[order]], 0), name=name)


def quantization_report(palette: Palette, rgba: np.ndarray, tokens: np.ndarray,
                        max_pixels: int = 2_000_000) -> Dict[str, float]:
    """Mean/p95 OKLab error introduced by quantization on opaque pixels."""
    flat = rgba.reshape(-1, 4)
    tok = tokens.reshape(-1)
    if flat.shape[0] > max_pixels:
        sel = np.random.default_rng(0).integers(0, flat.shape[0], max_pixels)
        flat, tok = flat[sel], tok[sel]
    op = flat[:, 3] >= 128
    if not op.any():
        return {"mean_dE": 0.0, "p95_dE": 0.0, "exact_frac": 1.0}
    src = srgb_to_oklab(flat[op, :3])
    dst = palette.lab[tok[op].astype(np.int64)]
    d = np.linalg.norm(src - dst, axis=1)
    exact = (palette.colors[tok[op].astype(np.int64)] == flat[op, :3]).all(1)
    return {"mean_dE": float(d.mean()), "p95_dE": float(np.percentile(d, 95)),
            "max_dE": float(d.max()), "exact_frac": float(exact.mean())}


# ---------------------------------------------------------------------------
# model building blocks
# ---------------------------------------------------------------------------

class RMSNorm(nn.Module):
    def __init__(self, dim: int, eps: float = 1e-6, affine: bool = True):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(dim)) if affine else None

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        dtype = x.dtype
        x32 = x.float()
        y = x32 * torch.rsqrt(x32.pow(2).mean(-1, keepdim=True) + self.eps)
        if self.weight is not None:
            y = y * self.weight.float()
        return y.to(dtype)


def _rope_freqs(head_dim: int, theta: float) -> torch.Tensor:
    n = head_dim // 4  # rotation pairs per axis
    return 1.0 / (theta ** (torch.arange(n, dtype=torch.float64) / n))


def build_rope(n_prefix: int, grid: int, head_dim: int, theta: float,
               stride: int = 1) -> Tuple[torch.Tensor, torch.Tensor]:
    """cos/sin tables for 2D axial RoPE. Image token (i,j) at a level with
    `stride` pixels per token sits at pixel-space centre
    (i*stride + (stride-1)/2, j*stride + (stride-1)/2); prefix angle 0."""
    f = _rope_freqs(head_dim, theta)
    ii, jj = torch.meshgrid(torch.arange(grid, dtype=torch.float64),
                             torch.arange(grid, dtype=torch.float64), indexing="ij")
    off = (stride - 1) / 2.0
    rows = (ii.reshape(-1) * stride + off)[:, None] * f[None]
    cols = (jj.reshape(-1) * stride + off)[:, None] * f[None]
    ang = torch.cat([rows, cols], 1)  # (grid^2, head_dim/2)
    ang = torch.cat([torch.zeros(n_prefix, ang.shape[1], dtype=ang.dtype), ang], 0)
    return ang.cos().float(), ang.sin().float()


def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
    # x: (B,H,N,hd); cos/sin: (N, hd/2)
    x1, x2 = x.float().chunk(2, dim=-1)
    out = torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)
    return out.to(x.dtype)


def fourier_features(x: torch.Tensor, n_freqs: int) -> torch.Tensor:
    """x: (...,C) roughly in [-1,1] -> (..., C*2*n_freqs) sin/cos features."""
    freqs = (2.0 ** torch.arange(n_freqs, dtype=torch.float32)) * math.pi
    ang = x.float().unsqueeze(-1) * freqs
    return torch.cat([ang.sin(), ang.cos()], dim=-1).flatten(-2)


class Attention(nn.Module):
    def __init__(self, dim: int, n_heads: int):
        super().__init__()
        self.n_heads = n_heads
        self.head_dim = dim // n_heads
        self.qkv = nn.Linear(dim, 3 * dim, bias=False)
        self.proj = nn.Linear(dim, dim, bias=False)
        self.q_norm = RMSNorm(self.head_dim)
        self.k_norm = RMSNorm(self.head_dim)

    def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
        B, N, D = x.shape
        qkv = self.qkv(x).view(B, N, 3, self.n_heads, self.head_dim).permute(2, 0, 3, 1, 4)
        q, k, v = qkv.unbind(0)
        q = apply_rope(self.q_norm(q), cos, sin)
        k = apply_rope(self.k_norm(k), cos, sin)
        o = F.scaled_dot_product_attention(q, k, v)
        return self.proj(o.transpose(1, 2).reshape(B, N, D))


class ConvSwiGLU(nn.Module):
    """SwiGLU whose gate branch gets a residual depthwise 3x3 conv over the
    image grid (local pixel structure)."""

    def __init__(self, dim: int, hidden: int, conv: bool = True):
        super().__init__()
        self.w12 = nn.Linear(dim, 2 * hidden, bias=False)
        self.w3 = nn.Linear(hidden, dim, bias=False)
        self.dw = nn.Conv2d(hidden, hidden, 3, padding=1, groups=hidden, bias=True) if conv else None

    def forward(self, x: torch.Tensor, n_prefix: int, hw: Tuple[int, int]) -> torch.Tensor:
        a, g = self.w12(x).chunk(2, dim=-1)
        if self.dw is not None:
            B, _, C = g.shape
            H, W = hw
            g_pre, g_img = g[:, :n_prefix], g[:, n_prefix:]
            conv = self.dw(g_img.transpose(1, 2).reshape(B, C, H, W)).flatten(2).transpose(1, 2)
            g = torch.cat([g_pre, g_img + conv.to(g_img.dtype)], dim=1)
        return self.w3(a * F.silu(g))


class Block(nn.Module):
    def __init__(self, cfg: TroutConfig):
        super().__init__()
        self.norm1 = RMSNorm(cfg.dim, affine=False)
        self.attn = Attention(cfg.dim, cfg.n_heads)
        self.norm2 = RMSNorm(cfg.dim, affine=False)
        self.mlp = ConvSwiGLU(cfg.dim, cfg.mlp_hidden, conv=cfg.conv_ffn)
        # per-block offsets added to the shared adaLN-single modulation
        # (shift/scale/gate) x (attn/mlp)
        self.mod_bias = nn.Parameter(torch.zeros(6, cfg.dim))

    def forward(self, x, mod, cos, sin, n_prefix: int, hw: Tuple[int, int]):
        m = (mod + self.mod_bias).unsqueeze(2)  # (B,6,1,D)
        sh1, sc1, g1, sh2, sc2, g2 = m.unbind(1)
        h = self.norm1(x) * (1 + sc1) + sh1
        x = x + g1 * self.attn(h, cos, sin)
        h = self.norm2(x) * (1 + sc2) + sh2
        x = x + g2 * self.mlp(h, n_prefix, hw)
        return x


# ---------------------------------------------------------------------------
# the model
# ---------------------------------------------------------------------------

class TroutModel(nn.Module):
    """Dual-resolution (hourglass) masked-diffusion transformer denoiser."""

    def __init__(self, cfg: TroutConfig, palette_lab: Optional[torch.Tensor] = None,
                 palette_rgb: Optional[torch.Tensor] = None):
        super().__init__()
        cfg.validate()
        self.cfg = cfg
        K, D, G = cfg.vocab_size, cfg.dim, cfg.grid_size
        self.mask_id = cfg.mask_id
        if palette_lab is None:
            palette_lab = torch.zeros(K, 3)
        if palette_rgb is None:
            palette_rgb = torch.zeros(K, 3, dtype=torch.uint8)
        assert palette_lab.shape == (K, 3), f"palette has {palette_lab.shape[0]} colors, config says {K}"
        # the palette travels with the checkpoint
        self.register_buffer("palette_lab", palette_lab.float().clone())
        self.register_buffer("palette_rgb", palette_rgb.to(torch.uint8).clone())

        # ---- token embeddings (color-grounded) ----
        self.tok_emb = nn.Embedding(K + 1, D)  # +1 for MASK
        n_feat = 3 + 3 * 2 * cfg.color_freqs + 1
        self.color_mlp = nn.Sequential(nn.Linear(n_feat, D), nn.SiLU(), nn.Linear(D, D))
        self.pos_emb = nn.Parameter(torch.zeros(1, G * G, D))
        self.sc_proj = nn.Linear(K, D, bias=False) if cfg.self_cond else None
        # ---- text conditioning ----
        self.text_norm = RMSNorm(cfg.text_dim)
        self.text_proj = nn.Linear(cfg.text_dim, D)
        self.null_text = nn.Parameter(torch.zeros(1, cfg.text_len, D))
        self.pool_mlp = nn.Sequential(RMSNorm(cfg.text_dim), nn.Linear(cfg.text_dim, D), nn.SiLU(), nn.Linear(D, D))
        self.null_cond = nn.Parameter(torch.zeros(1, D))
        self.ratio_mlp = nn.Sequential(nn.Linear(2 * 8, D), nn.SiLU(), nn.Linear(D, D))
        self.registers = nn.Parameter(torch.zeros(1, cfg.n_registers, D))
        self.t_block = nn.Sequential(nn.SiLU(), nn.Linear(D, 6 * D))
        # ---- hourglass backbone ----
        p = cfg.patch
        self.blocks_in = nn.ModuleList([Block(cfg) for _ in range(cfg.depth_in)])
        self.down = nn.Sequential(RMSNorm(p * p * D), nn.Linear(p * p * D, D))
        self.blocks_core = nn.ModuleList([Block(cfg) for _ in range(cfg.depth_core)])
        self.up = nn.Linear(D, p * p * D)
        self.blocks_out = nn.ModuleList([Block(cfg) for _ in range(cfg.depth_out)])
        self.norm_out = RMSNorm(D, affine=False)
        self.final_mod = nn.Sequential(nn.SiLU(), nn.Linear(D, 2 * D))
        self.head = nn.Linear(D, K)
        # ---- fixed tables ----
        n_pre = cfg.n_registers + cfg.text_len
        self.n_prefix = n_pre
        cf, sf = build_rope(n_pre, G, cfg.head_dim, cfg.rope_theta, stride=1)
        self.register_buffer("rope_cos", cf, persistent=False)
        self.register_buffer("rope_sin", sf, persistent=False)
        cc, sc = build_rope(n_pre, G // cfg.patch, cfg.head_dim, cfg.rope_theta, stride=cfg.patch)
        self.register_buffer("rope_cos_core", cc, persistent=False)
        self.register_buffer("rope_sin_core", sc, persistent=False)
        self.register_buffer("color_feats", self._color_features(self.palette_lab), persistent=False)
        self.grad_checkpointing = False
        self._init_weights()

    # ------------------------------------------------------------------
    def _color_features(self, lab: torch.Tensor) -> torch.Tensor:
        x = torch.stack([lab[:, 0] * 2 - 1, lab[:, 1] / 0.4, lab[:, 2] / 0.4], -1)
        alpha = torch.ones(lab.shape[0], 1)
        alpha[0] = 0.0  # token 0 = transparent
        x = x * alpha
        return torch.cat([x, fourier_features(x, self.cfg.color_freqs), alpha], -1)

    def set_palette(self, palette_lab: torch.Tensor, palette_rgb: torch.Tensor) -> None:
        self.palette_lab.copy_(palette_lab.float())
        self.palette_rgb.copy_(palette_rgb.to(torch.uint8))
        self.color_feats = self._color_features(self.palette_lab.detach().cpu()).to(self.palette_lab.device)

    def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs):
        super()._load_from_state_dict(state_dict, prefix, *args, **kwargs)
        self.color_feats = self._color_features(self.palette_lab.detach().cpu()).to(self.palette_lab.device)

    def _init_weights(self) -> None:
        def init(m):
            if isinstance(m, nn.Linear):
                nn.init.trunc_normal_(m.weight, std=0.02)
                if m.bias is not None:
                    nn.init.zeros_(m.bias)
            elif isinstance(m, nn.Embedding):
                nn.init.normal_(m.weight, std=0.02)
        self.apply(init)
        nn.init.trunc_normal_(self.pos_emb, std=0.02)
        nn.init.normal_(self.null_text, std=0.02)
        nn.init.normal_(self.null_cond, std=0.02)
        nn.init.normal_(self.registers, std=0.02)
        # zero-init: conditioning projections, gates, head, self-cond, up path
        for m in [self.t_block[-1], self.final_mod[-1], self.head]:
            nn.init.zeros_(m.weight)
            nn.init.zeros_(m.bias)
        if self.sc_proj is not None:
            nn.init.zeros_(self.sc_proj.weight)
        nn.init.zeros_(self.up.weight)
        nn.init.zeros_(self.up.bias)
        for blk in list(self.blocks_in) + list(self.blocks_core) + list(self.blocks_out):
            if blk.mlp.dw is not None:
                nn.init.zeros_(blk.mlp.dw.weight)
                nn.init.zeros_(blk.mlp.dw.bias)

    # ------------------------------------------------------------------
    def _merge(self, h: torch.Tensor) -> torch.Tensor:
        B, N, D = h.shape
        G, p = self.cfg.grid_size, self.cfg.patch
        g = G // p
        h = h.view(B, g, p, g, p, D).permute(0, 1, 3, 2, 4, 5).reshape(B, g * g, p * p * D)
        return self.down(h)

    def _split(self, h: torch.Tensor) -> torch.Tensor:
        B = h.shape[0]
        G, p, D = self.cfg.grid_size, self.cfg.patch, self.cfg.dim
        g = G // p
        h = self.up(h).view(B, g, g, p, p, D).permute(0, 1, 3, 2, 4, 5).reshape(B, G * G, D)
        return h

    def _run(self, blk: Block, xs, mod, cos, sin, n_pre: int, hw):
        if self.grad_checkpointing and self.training and torch.is_grad_enabled():
            return torch.utils.checkpoint.checkpoint(blk, xs, mod, cos, sin, n_pre, hw,
                                                     use_reentrant=False)
        return blk(xs, mod, cos, sin, n_pre, hw)

    def embed_table(self) -> torch.Tensor:
        K = self.cfg.vocab_size
        w = self.tok_emb.weight
        colors = w[:K] + self.color_mlp(self.color_feats).to(w.dtype)
        return torch.cat([colors, w[K:]], 0)

    def forward(self, x: torch.Tensor, text_states: torch.Tensor, text_pooled: torch.Tensor,
                mask_ratio: Optional[torch.Tensor] = None,
                sc_probs: Optional[torch.Tensor] = None,
                drop_text: Optional[torch.Tensor] = None) -> torch.Tensor:
        """
        x:           (B,N) long palette ids or mask_id
        text_states: (B,L,text_dim) frozen text-encoder token states
        text_pooled: (B,text_dim) pooled text embedding
        mask_ratio:  (B,) fraction masked (computed from x if None)
        sc_probs:    (B,N,K) previous-step predicted distribution or None
        drop_text:   (B,) bool -> use learned null condition (CFG)
        returns logits (B,N,K) float32
        """
        cfg = self.cfg
        B, N = x.shape
        D, G = cfg.dim, cfg.grid_size
        is_mask = x == self.mask_id
        if mask_ratio is None:
            mask_ratio = is_mask.float().mean(1)
        # ---- image tokens ----
        h = F.embedding(x, self.embed_table()).float() + self.pos_emb
        if self.sc_proj is not None and sc_probs is not None:
            h = h + self.sc_proj(sc_probs.to(self.sc_proj.weight.dtype)).float() * is_mask.unsqueeze(-1)
        # ---- text tokens + global conditioning ----
        t = self.text_proj(self.text_norm(text_states.float())).float()
        c = self.pool_mlp(text_pooled.float()).float()
        if drop_text is not None:
            t = torch.where(drop_text.view(B, 1, 1), self.null_text, t)
            c = torch.where(drop_text.view(B, 1), self.null_cond, c)
        r = mask_ratio.float().view(B, 1) * 2 - 1
        g = c + self.ratio_mlp(fourier_features(r, 8).view(B, -1)).float()
        mod = self.t_block(g).float().view(B, 6, D)
        prefix = torch.cat([self.registers.expand(B, -1, -1), t], 1)
        n_pre = prefix.shape[1]
        xs = torch.cat([prefix, h], 1)
        # ---- pixel level (in) ----
        for blk in self.blocks_in:
            xs = self._run(blk, xs, mod, self.rope_cos, self.rope_sin, n_pre, (G, G))
        # ---- patch level (core) ----
        pre, img = xs[:, :n_pre], xs[:, n_pre:]
        skip = img
        xs = torch.cat([pre, self._merge(img).float()], 1)
        gc = G // cfg.patch
        for blk in self.blocks_core:
            xs = self._run(blk, xs, mod, self.rope_cos_core, self.rope_sin_core, n_pre, (gc, gc))
        pre, core = xs[:, :n_pre], xs[:, n_pre:]
        xs = torch.cat([pre, skip + self._split(core).float()], 1)
        # ---- pixel level (out) ----
        for blk in self.blocks_out:
            xs = self._run(blk, xs, mod, self.rope_cos, self.rope_sin, n_pre, (G, G))
        img = xs[:, n_pre:]
        shift, scale = self.final_mod(g).float().unsqueeze(1).chunk(2, dim=-1)
        img = self.norm_out(img) * (1 + scale) + shift
        return self.head(img).float()

    def num_params(self, trainable_only: bool = True) -> int:
        return sum(p.numel() for p in self.parameters() if p.requires_grad or not trainable_only)


# ---------------------------------------------------------------------------
# sampler: parallel confidence-ordered unmasking (MaskGIT-style) with CFG,
# Gumbel-annealed choice, spatial NMS and self-conditioning feedback
# ---------------------------------------------------------------------------

def filter_logits(logits: torch.Tensor, top_k: int = 0, top_p: float = 1.0,
                  min_p: float = 0.0) -> torch.Tensor:
    if top_k and top_k > 0 and top_k < logits.shape[-1]:
        kth = torch.topk(logits, top_k, dim=-1).values[..., -1:]
        logits = logits.masked_fill(logits < kth, -math.inf)
    if min_p and min_p > 0:
        p = logits.softmax(-1)
        logits = logits.masked_fill(p < min_p * p.amax(-1, keepdim=True), -math.inf)
    if top_p is not None and top_p < 1.0:
        sorted_l, idx = torch.sort(logits, dim=-1, descending=True)
        sp = sorted_l.softmax(-1)
        remove = (sp.cumsum(-1) - sp) > top_p
        sorted_l = sorted_l.masked_fill(remove, -math.inf)
        logits = torch.full_like(logits, -math.inf).scatter(-1, idx, sorted_l)
    return logits


def cfg_weight(scale: float, schedule: str, frac: float) -> float:
    if schedule == "constant":
        return scale
    if schedule == "linear":
        return 1.0 + (scale - 1.0) * frac
    if schedule == "cosine":
        return 1.0 + (scale - 1.0) * (1 - math.cos(math.pi * frac)) / 2
    raise ValueError(f"unknown cfg schedule {schedule!r}")


def _gumbel(shape, device, generator):
    u = torch.rand(shape, device=device, generator=generator).clamp_(1e-10, 1 - 1e-10)
    return -torch.log(-torch.log(u))


def _nms_eligible(score: torch.Tensor, masked: torch.Tensor, certain: torch.Tensor,
                  grid: int) -> torch.Tensor:
    B, N = score.shape
    cand = masked & ~certain
    s = torch.where(cand, score, torch.full_like(score, -math.inf)).view(B, 1, grid, grid)
    local_max = F.max_pool2d(s, 3, stride=1, padding=1).view(B, N)
    return certain | (cand & (score >= local_max))


@torch.no_grad()
def sample(model: TroutModel, text_states: torch.Tensor, text_pooled: torch.Tensor,
           steps: int = 16, cfg_scale: float = 3.0, cfg_schedule: str = "constant",
           temperature: float = 1.0, temperature_end: Optional[float] = None,
           top_k: int = 0, top_p: float = 1.0, min_p: float = 0.0,
           choice_temperature: float = 2.0, spatial_nms: bool = True,
           nms_threshold: float = 0.9, polish_steps: int = 0, polish_frac: float = 0.08,
           init_tokens: Optional[torch.Tensor] = None, keep_mask: Optional[torch.Tensor] = None,
           self_cond: bool = True, generator: Optional[torch.Generator] = None,
           return_history: bool = False):
    """Generate palette-token canvases (B, N); inpainting via init_tokens+keep_mask."""
    cfg = model.cfg
    device = text_pooled.device
    B, N, K, M, G = text_pooled.shape[0], cfg.num_tokens, cfg.vocab_size, cfg.mask_id, cfg.grid_size
    if init_tokens is not None and keep_mask is not None:
        init_tokens = init_tokens.to(device).long()
        x = torch.where(keep_mask.to(device).bool(), init_tokens, torch.full_like(init_tokens, M))
    else:
        x = torch.full((B, N), M, dtype=torch.long, device=device)
    masked = x == M
    conf_map = torch.where(masked, torch.zeros(B, N, device=device),
                           torch.full((B, N), math.inf, device=device))
    n_start = masked.sum(1)
    use_cfg = cfg_scale is not None and abs(cfg_scale - 1.0) > 1e-6
    if use_cfg:
        ts2 = torch.cat([text_states, text_states])
        tp2 = torch.cat([text_pooled, text_pooled])
        drop2 = torch.cat([torch.zeros(B, dtype=torch.bool, device=device),
                           torch.ones(B, dtype=torch.bool, device=device)])
    sc = torch.zeros(B, N, K, device=device) if (cfg.self_cond and self_cond) else None
    history = []

    def predict(x_in, sc_in, frac):
        ratio = (x_in == M).float().mean(1)
        if use_cfg:
            sc2 = torch.cat([sc_in, sc_in]) if sc_in is not None else None
            out = model(torch.cat([x_in, x_in]), ts2, tp2, torch.cat([ratio, ratio]),
                        sc2, drop2).float()
            lc, lu = out.chunk(2)
            w = cfg_weight(cfg_scale, cfg_schedule, frac)
            return lu + w * (lc - lu)
        return model(x_in, text_states, text_pooled, ratio, sc_in, None).float()

    for k in range(steps):
        if not masked.any():
            break
        frac = (k + 1) / steps
        logits = predict(x, sc, frac)
        probs_full = logits.softmax(-1)
        T = temperature if temperature_end is None else temperature + (temperature_end - temperature) * (k / max(1, steps - 1))
        if T <= 0:
            sampled = logits.argmax(-1)
            p_sel = probs_full.gather(-1, sampled.unsqueeze(-1)).squeeze(-1)
        else:
            probs = filter_logits(logits / T, top_k, top_p, min_p).softmax(-1)
            sampled = torch.multinomial(probs.view(-1, K), 1, generator=generator).view(B, N)
            p_sel = probs.gather(-1, sampled.unsqueeze(-1)).squeeze(-1)
        n_masked = masked.sum(1)
        remaining = torch.floor(n_start.float() * math.cos(math.pi / 2 * frac)).long()
        if k == steps - 1:
            remaining = torch.zeros_like(remaining)
        n_commit = torch.minimum((n_masked - remaining).clamp(min=1), n_masked)
        score = torch.log(p_sel.clamp(min=1e-12))
        if choice_temperature > 0:  # Gumbel-annealed choice (MaskGIT)
            score = score + choice_temperature * (1.0 - frac) * _gumbel(score.shape, device, generator)
        priority = score
        if spatial_nms:  # don't commit two uncertain neighbours in one step
            elig = _nms_eligible(score, masked, p_sel >= nms_threshold, G)
            priority = score + elig.float() * 1e4
        priority = torch.where(masked, priority, torch.full_like(priority, -math.inf))
        ranks = priority.argsort(1, descending=True).argsort(1)
        commit = (ranks < n_commit.unsqueeze(1)) & masked
        x = torch.where(commit, sampled, x)
        conf_map = torch.where(commit, p_sel, conf_map)
        masked = masked & ~commit
        if sc is not None:
            sc = probs_full
        if return_history:
            history.append(x.clone())

    # ---- optional polish: re-mask the least confident committed pixels ----
    n_re = max(1, int(round(polish_frac * N)))
    for _ in range(polish_steps):
        low = torch.topk(-conf_map, n_re, dim=1).indices
        remask = torch.zeros(B, N, dtype=torch.bool, device=device).scatter_(1, low, True)
        remask &= torch.isfinite(conf_map)
        x_in = torch.where(remask, torch.full_like(x, M), x)
        logits = predict(x_in, sc, 1.0)
        probs_full = logits.softmax(-1)
        new = logits.argmax(-1)
        x = torch.where(remask, new, x)
        conf_map = torch.where(remask, probs_full.gather(-1, new.unsqueeze(-1)).squeeze(-1), conf_map)
        if sc is not None:
            sc = probs_full
        if return_history:
            history.append(x.clone())

    if return_history:
        return x, history
    return x


# ---------------------------------------------------------------------------
# checkpoint helpers (same schema semantics as the Tessera distribution:
# ema weights + model_config + palette + text-encoder id + step)
# ---------------------------------------------------------------------------

def save_checkpoint(path: str, model: TroutModel, palette: Palette, step: int,
                    ema_state: Optional[Dict[str, torch.Tensor]] = None,
                    raw_state: Optional[Dict[str, torch.Tensor]] = None,
                    text_encoder: str = DEFAULT_TEXT_ENCODER, half: bool = False) -> None:
    def prep(sd):
        out = {}
        for k, v in sd.items():
            out[k] = (v.half() if half and v.is_floating_point() else v).cpu()
        return out
    ckpt = {"model_config": model.cfg.to_dict(), "palette": palette.to_dict(),
            "text_encoder": text_encoder, "step": step}
    if ema_state is not None:
        ckpt["ema"] = prep(ema_state)
    if raw_state is not None:
        ckpt["model"] = prep(raw_state)
    torch.save(ckpt, path)


def load_model_from_checkpoint(path: str, device="cpu", use_ema: bool = True):
    ckpt = torch.load(path, map_location="cpu", weights_only=False)
    mcfg = TroutConfig.from_dict(ckpt["model_config"])
    palette = Palette.from_dict(ckpt["palette"])
    model = TroutModel(mcfg, torch.from_numpy(palette.lab), torch.from_numpy(palette.colors))
    key = "ema" if (use_ema and "ema" in ckpt) else "model"
    sd = {k: v.float() if v.is_floating_point() else v for k, v in ckpt[key].items()}
    model.load_state_dict(sd)
    model.to(device).eval().requires_grad_(False)
    return model, palette, ckpt


# ---------------------------------------------------------------------------
# visualization helpers
# ---------------------------------------------------------------------------

def tokens_to_images(tokens, palette: Palette, grid: int = 16) -> List:
    from PIL import Image
    if isinstance(tokens, torch.Tensor):
        tokens = tokens.detach().cpu().numpy()
    toks = np.asarray(tokens).reshape(-1, grid * grid)
    imgs = []
    for row in toks:
        rgba = palette.tokens_to_rgba(row.reshape(grid, grid))
        imgs.append(Image.fromarray(rgba, mode="RGBA"))
    return imgs


def upscale(image, scale: int = 16, checker: bool = True):
    """Nearest-neighbour upscale with an optional checkerboard background."""
    from PIL import Image
    w, h = image.size
    big = image.resize((w * scale, h * scale), Image.NEAREST)
    if not checker:
        return big
    bg = Image.new("RGBA", big.size, (255, 255, 255, 255))
    s = 4 * 2  # checker cell in big pixels
    yy, xx = np.mgrid[0:big.size[1], 0:big.size[0]]
    mask = (((yy // s) + (xx // s)) % 2 == 0)
    light = Image.fromarray(np.where(mask[..., None], np.array([238, 238, 238, 255], np.uint8),
                                     np.array([204, 204, 204, 255], np.uint8)), "RGBA")
    light.alpha_composite(big)
    return light


def make_grid(images, ncols: int = 8, scale: int = 8, checker: bool = True):
    from PIL import Image
    cells = [upscale(im, scale, checker) for im in images]
    cw, ch = cells[0].size
    rows = math.ceil(len(cells) / ncols)
    out = Image.new("RGBA", (ncols * cw, rows * ch), (255, 255, 255, 255))
    for i, c in enumerate(cells):
        out.alpha_composite(c, ((i % ncols) * cw, (i // ncols) * ch))
    return out


# ---------------------------------------------------------------------------
# frozen CLIP text tower wrapper
# ---------------------------------------------------------------------------

def load_tokenizer(name: str):
    from transformers import AutoTokenizer
    return AutoTokenizer.from_pretrained(name)


def tokenize_texts(tokenizer, texts: Sequence[str], text_len: int) -> Tuple[np.ndarray, np.ndarray]:
    """Fixed-length tokenization; pad with pad id; over-long prompts truncated
    while keeping the final EOS token."""
    eos = tokenizer.eos_token_id
    pad = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else eos
    n = len(texts)
    out = np.full((n, text_len), pad, dtype=np.int32)
    lengths = np.zeros(n, dtype=np.int32)
    enc = tokenizer(list(texts), add_special_tokens=True, truncation=False)["input_ids"]
    for i, ids in enumerate(enc):
        lengths[i] = len(ids)
        if len(ids) > text_len:
            ids = list(ids[:text_len - 1]) + [eos]
        out[i, :len(ids)] = ids
    return out, lengths


class FrozenTextEncoder:
    """Wraps a Hugging Face CLIP text tower. Not an nn.Module on purpose so its
    weights never end up in the trainable model, optimizer or checkpoints."""

    def __init__(self, name: str = DEFAULT_TEXT_ENCODER, text_len: int = 24,
                 device="cpu", dtype: torch.dtype = torch.float32):
        from transformers import CLIPTextModel
        from transformers.utils import logging as hf_logging
        self.name = name
        self.text_len = text_len
        self.device = torch.device(device)
        self.dtype = dtype
        self.tokenizer = load_tokenizer(name)
        prev = hf_logging.get_verbosity()
        hf_logging.set_verbosity_error()
        try:
            model = CLIPTextModel.from_pretrained(name)
        finally:
            hf_logging.set_verbosity(prev)
        self.model = model.to(device=self.device, dtype=dtype).eval().requires_grad_(False)
        self.dim = int(model.config.hidden_size)

    def tokenize(self, texts: Sequence[str]) -> torch.Tensor:
        ids, _ = tokenize_texts(self.tokenizer, list(texts), self.text_len)
        return torch.from_numpy(ids).long().to(self.device)

    @torch.no_grad()
    def __call__(self, ids: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
        out = self.model(input_ids=ids.long().to(self.device))
        return out.last_hidden_state, out.pooler_output

    @torch.no_grad()
    def encode(self, texts: Sequence[str]) -> Tuple[torch.Tensor, torch.Tensor]:
        return self(self.tokenize(texts))