j0no12 commited on
Commit
66f440c
·
verified ·
1 Parent(s): 5dbb64d

Upload Mica Preview (step 291,000 EMA weights, portable code, gallery, and model card)

Browse files
.gitattributes CHANGED
@@ -33,3 +33,14 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ gallery/01_alpine_sunrise.png filter=lfs diff=lfs merge=lfs -text
37
+ gallery/02_iceland_aurora.png filter=lfs diff=lfs merge=lfs -text
38
+ gallery/03_kyoto_autumn.png filter=lfs diff=lfs merge=lfs -text
39
+ gallery/04_redwood_mist.png filter=lfs diff=lfs merge=lfs -text
40
+ gallery/05_sahara_dunes.png filter=lfs diff=lfs merge=lfs -text
41
+ gallery/06_amalfi_coast.png filter=lfs diff=lfs merge=lfs -text
42
+ gallery/07_scottish_highlands.png filter=lfs diff=lfs merge=lfs -text
43
+ gallery/08_patagonia_lake.png filter=lfs diff=lfs merge=lfs -text
44
+ gallery/09_canyon_river.png filter=lfs diff=lfs merge=lfs -text
45
+ gallery/10_lavender_provence.png filter=lfs diff=lfs merge=lfs -text
46
+ gallery/gallery_grid.jpg filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ pipeline_tag: text-to-image
6
+ library_name: pytorch
7
+ tags:
8
+ - mica
9
+ - text-to-image
10
+ - flow-matching
11
+ - fcdm
12
+ - convnext
13
+ - perceiver
14
+ - 768px
15
+ - preview
16
+ ---
17
+
18
+ # Mica Preview
19
+
20
+ **Mica Preview** is a small, experimental 194M-parameter English text-to-image flow-matching model trained from scratch at 768×768 resolution. It is our first working research preview from the Mica image-generation family — built to test whether a recurrent Perceiver "thinker" paired with a pure-ConvNeXt V2 renderer can produce coherent high-resolution imagery at a fraction of the parameter count of standard diffusion Transformers.
21
+
22
+ It is still early. Trained to step 291,000 (~4.66M image-caption samples seen), Mica Preview is not meant to rival large billion-parameter image models yet — it is a transparent, self-contained checkpoint and a starting point for what comes next.
23
+
24
+ ---
25
+
26
+ ## Sample Gallery
27
+
28
+ All samples below were generated directly from the released EMA weights at **768×768** (`50` Euler steps, CFG `4.0`, resolution shift `2.5`, uncurated single seed per prompt):
29
+
30
+ ![Mica Preview 10-Prompt Landscape Gallery](gallery/gallery_grid.jpg)
31
+
32
+ | Sample | Prompt |
33
+ |---|---|
34
+ | `01_alpine_sunrise` | A breathtaking sunrise over snow-capped Swiss Alpine peaks, warm golden sunlight catching jagged ridges, a crystal-clear turquoise glacial lake in the foreground reflecting the pink and amber sky, pine trees along the rocky shore, crisp mountain air, ultra-detailed landscape photography |
35
+ | `02_iceland_aurora` | Vibrant emerald and violet northern lights dancing across a starry night sky over a black-sand beach in Iceland, jagged basalt sea stacks rising from calm dark ocean water reflecting the glowing aurora, thin mist near the horizon, long-exposure landscape photography |
36
+ | `03_kyoto_autumn` | A tranquil Japanese hillside garden in peak autumn, fiery crimson maple trees arching over a moss-covered stone bridge and a quiet koi pond, a wooden pavilion nestled among golden ginkgo trees, soft morning mist filtering warm sunlight through the canopy |
37
+ | `04_redwood_mist` | Towering ancient coastal redwood trees in northern California shrouded in cool morning fog, dramatic shafts of golden sunlight streaming diagonally through the dense canopy onto lush green ferns and a winding dirt trail, atmospheric nature photography |
38
+ | `05_sahara_dunes` | Sweeping golden sand dunes of the Sahara Desert at late afternoon sunset, sharp wind-carved S-curve ridges casting long deep indigo shadows across rippled sand, warm orange and lavender desert sky, minimalist fine-art landscape photography |
39
+ | `06_amalfi_coast` | Sunlit cliffs of the Amalfi Coast overlooking a deep sapphire Mediterranean Sea, pastel-colored terraced villages cascading down steep rocky slopes surrounded by lemon groves and cypress trees, small white sailboats gliding across sparkling coastal waters at golden hour |
40
+ | `07_scottish_highlands` | Dramatic moody clouds parting over the Scottish Highlands, rolling heather-covered moorland in rich purples and rust tones, a winding silver river cutting through a wide glaciated valley, a single beam of afternoon sunlight illuminating distant rugged peaks |
41
+ | `08_patagonia_lake` | Granite spires of Patagonia towering behind an electric-blue alpine lake dotted with drifting icebergs, windswept tussock grass in the foreground, dramatic lenticular clouds glowing coral pink at dusk, wide-angle wilderness photography |
42
+ | `09_canyon_river` | Aerial overlook of a sweeping horseshoe bend carved into towering red sandstone canyon walls in the American Southwest, an emerald-green river winding far below, warm sunset light illuminating layered terracotta rock cliffs under a clear twilight sky |
43
+ | `10_lavender_provence` | Endless rows of blooming purple lavender stretching across rolling hills in Provence toward a distant limestone mountain range, a weathered stone farmhouse framed by dark green cypress trees on the ridge, warm golden sunset light and soft pastel clouds |
44
+
45
+ ---
46
+
47
+ ## Architecture & Training
48
+
49
+ Mica Preview separates global semantic planning from local spatial rendering in plain PyTorch (`mica_modeling.py`, no custom CUDA extensions required):
50
+
51
+ - **Parameters:** 194,328,196 total (`192,230,532` generator + `2,097,664` text adapter, released as EMA weights `decay = 0.9995`)
52
+ - **Thinker (Global Planner):** Perceiver-style Transformer operating on a 24×24 spatial plan grid + 16 global tokens (`p_dim = 256`, `dim = 640`, 4 perceiver blocks, 3 prelude + 3 recurrent core × 4 loops + 2 coda blocks, 2D RoPE, QK-RMSNorm, multi-resolution ConvRead branch)
53
+ - **Renderer (Local Denoiser):** Pure-ConvNeXt V2 SpatialMod U-Net with GRN (`widths = [288, 832, 1664]`, `depths = [4, 6, 2]`, expansion `3`, low-rank steering `[128, 256, 256]`, guided `PlanUp` upsampler, and `CoordIn` coordinate injection)
54
+ - **Latent Space & VAE:** 768×768 output via frozen [`stabilityai/sd-vae-ft-mse`](https://huggingface.co/stabilityai/sd-vae-ft-mse) (`96×96×4` latent grid, scale `0.18215`)
55
+ - **Text Conditioning:** Frozen [`LifuWang/DistillT5`](https://huggingface.co/LifuWang/DistillT5) (with [`google-t5/t5-base`](https://huggingface.co/google-t5/t5-base) tokenizer) mapped into 512-dim context via a learned `ctx_proj` linear adapter
56
+ - **Training Recipe:** Rectified flow-matching (`t = 0` noise → `t = 1` data, velocity prediction) trained to **291,000 steps** (**4,656,000 samples seen**, EMA flow loss `0.679`)
57
+
58
+ ---
59
+
60
+ ## Quick Start
61
+
62
+ ```python
63
+ import torch
64
+ from diffusers import AutoencoderKL
65
+ from huggingface_hub import hf_hub_download
66
+ from safetensors.torch import load_file
67
+ from mica_modeling import DistillT5TextEncoder, MicaConfig, MicaGenerator, VAE_REPO, sample_mica
68
+
69
+ repo_id = "Emergent-Knowledge/mica-preview"
70
+ device = "cuda" if torch.cuda.is_available() else "cpu"
71
+
72
+ model = MicaGenerator(MicaConfig())
73
+ model.load_state_dict(load_file(hf_hub_download(repo_id, "generator.safetensors")), strict=True)
74
+ model = model.to(device).eval()
75
+
76
+ text_enc = DistillT5TextEncoder(device=device).load()
77
+ text_enc.ctx_proj.load_state_dict(load_file(hf_hub_download(repo_id, "ctx_proj.safetensors")), strict=True)
78
+
79
+ vae = AutoencoderKL.from_pretrained(VAE_REPO, torch_dtype=torch.bfloat16 if device == "cuda" else torch.float32).to(device).eval()
80
+
81
+ images = sample_mica(
82
+ model, text_enc, vae,
83
+ prompts=["A breathtaking sunrise over snow-capped Alpine peaks reflected in a calm turquoise glacial lake"],
84
+ steps=50, cfg=4.0, shift=2.5, resolution=768, seed=42, device=device,
85
+ )
86
+ images[0].save("mica_sample.png")
87
+ ```
88
+
89
+ ---
90
+
91
+ ## Limitations
92
+
93
+ - **Research preview:** Trained on ~4.66M samples at 194M parameters, so fine anatomy, hands, dense text rendering, and complex multi-object counts can still break down.
94
+ - **Square 768×768 native:** Tuned for square 768×768 generation; arbitrary aspect ratios are not yet supported.
95
+ - **English prompts:** Text conditioning is trained on English captions via DistillT5.
96
+
97
+ ---
98
+
99
+ ## Acknowledgements & License
100
+
101
+ Mica Preview builds on open research and open weights from the community — including FCDM (`arXiv:2603.09408`), Agate Thinker-Renderer architectures, [`LifuWang/DistillT5`](https://huggingface.co/LifuWang/DistillT5), [`google-t5/t5-base`](https://huggingface.co/google-t5/t5-base), and [`stabilityai/sd-vae-ft-mse`](https://huggingface.co/stabilityai/sd-vae-ft-mse).
102
+
103
+ Released under the **Apache-2.0** license.
config.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "mica_v5_fcdm_thinker2",
3
+ "step": 291000,
4
+ "samples_seen": 4656000,
5
+ "ema": true,
6
+ "resolution_px": 768,
7
+ "latent_size": 96,
8
+ "vae_repo": "stabilityai/sd-vae-ft-mse",
9
+ "vae_scale": 0.18215,
10
+ "text_encoder_repo": "LifuWang/DistillT5",
11
+ "tokenizer_repo": "google-t5/t5-base",
12
+ "default_steps": 50,
13
+ "default_cfg": 4.0,
14
+ "default_shift": 2.5,
15
+ "latent_ch": 4,
16
+ "widths": [
17
+ 288,
18
+ 832,
19
+ 1664
20
+ ],
21
+ "depths": [
22
+ 4,
23
+ 6,
24
+ 2
25
+ ],
26
+ "steer_rank": [
27
+ 128,
28
+ 256,
29
+ 256
30
+ ],
31
+ "expansion": 3,
32
+ "ctx_dim": 512,
33
+ "dim": 640,
34
+ "p_dim": 256,
35
+ "perceiver_depth": 4,
36
+ "prelude": 3,
37
+ "core": 3,
38
+ "coda": 2,
39
+ "loops": 4,
40
+ "grid": 24,
41
+ "n_global": 16,
42
+ "n_freq": 6,
43
+ "head_dim": 64,
44
+ "read_ch": 96,
45
+ "read_depth": 2,
46
+ "up_rank": 32,
47
+ "outer_mode": "flat",
48
+ "coord_res": true,
49
+ "rope": true,
50
+ "vae_downsample": 8
51
+ }
ctx_proj.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:796b2cabb25697be53e89a23d9a912dc4bc184647f4c7b4488115a30c9ef9387
3
+ size 8390832
gallery/01_alpine_sunrise.png ADDED

Git LFS Details

  • SHA256: 4517a668507aefff00309805fd4a497a25ff6e3133cff02df53de78184778dc6
  • Pointer size: 131 Bytes
  • Size of remote file: 985 kB
gallery/02_iceland_aurora.png ADDED

Git LFS Details

  • SHA256: 71ab0552ea3b3f19d72232ad637b86bfe2be6efadff9a92eed0c2ec206e96327
  • Pointer size: 131 Bytes
  • Size of remote file: 517 kB
gallery/03_kyoto_autumn.png ADDED

Git LFS Details

  • SHA256: b77a4557b01906fc76002b909425b0ef634f52785c20752df49a9c2622f97670
  • Pointer size: 132 Bytes
  • Size of remote file: 1.26 MB
gallery/04_redwood_mist.png ADDED

Git LFS Details

  • SHA256: 5b62782c2a7ca465943792dea1227af5caa3648e9f9e38ca745b0d55ac408898
  • Pointer size: 132 Bytes
  • Size of remote file: 1.27 MB
gallery/05_sahara_dunes.png ADDED

Git LFS Details

  • SHA256: bc9917c3adcc7e254db7e7a4718d5ed1c029b584890ebce8612defb673d63b4e
  • Pointer size: 131 Bytes
  • Size of remote file: 630 kB
gallery/06_amalfi_coast.png ADDED

Git LFS Details

  • SHA256: 3f217442f0fd4850db454999f57deb9f4002f0923bf34393e5f496ea8093808d
  • Pointer size: 132 Bytes
  • Size of remote file: 1.06 MB
gallery/07_scottish_highlands.png ADDED

Git LFS Details

  • SHA256: 9b731054a0f88ce51203cd6db5b1311c23e81ccae4e54df4781683b1794fd327
  • Pointer size: 131 Bytes
  • Size of remote file: 884 kB
gallery/08_patagonia_lake.png ADDED

Git LFS Details

  • SHA256: 8c3b04fdcd235052e9fca6ed191bd7d449f18618d9bbb22978dbfd7ba37f0f9e
  • Pointer size: 131 Bytes
  • Size of remote file: 904 kB
gallery/09_canyon_river.png ADDED

Git LFS Details

  • SHA256: 74bcd992b423d2934a32745f1b91fac85f36e510ee562abe0b9bbf3e4fd0027e
  • Pointer size: 131 Bytes
  • Size of remote file: 871 kB
gallery/10_lavender_provence.png ADDED

Git LFS Details

  • SHA256: deec0b32a2f77cbb3101f54395bf7227b5de2961cac2fda3f99bb936426ec5e4
  • Pointer size: 131 Bytes
  • Size of remote file: 849 kB
gallery/gallery_grid.jpg ADDED

Git LFS Details

  • SHA256: 831b7ff79854de0fff7348a62ce694d94c612ed85b8b72ee937ab06c554472da
  • Pointer size: 131 Bytes
  • Size of remote file: 403 kB
generator.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:165bc0668ebb3cedaccb10507362d571304adb6761d194d2a177183c718f1aaf
3
+ size 768982904
mica_modeling.py ADDED
@@ -0,0 +1,599 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mica Preview (v5, 768px): Portable PyTorch inference model & pipeline.
2
+
3
+ Architecture:
4
+ - 192.2M-param FCDM-Thinker2-MR (flat 768px mode, 96x96 SD-VAE latent grid)
5
+ * Perceiver-based recurrent Thinker (24x24 spatial plan + 16 global tokens,
6
+ 4 perceiver blocks, 3 prelude + 3 recurrent core x 4 loops + 2 coda blocks,
7
+ 2D RoPE + QK-RMSNorm + multi-res ConvRead)
8
+ * Pure-ConvNeXt V2 SpatialMod U-Net renderer (widths [288, 832, 1664],
9
+ depths [4, 6, 2], expansion 3, steer_rank [128, 256, 256], PlanUp + CoordIn)
10
+ - DistillT5 text encoder (LifuWang/DistillT5 + google-t5/t5-base tokenizer)
11
+ with learned 4096 -> 512 ctx_proj adapter (2.1M params).
12
+ - Frozen stabilityai/sd-vae-ft-mse (scale 0.18215).
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import math
17
+ from dataclasses import dataclass, field
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+
23
+ N_COORD = 3
24
+ COUNT_K = (1, 2, 4, 8)
25
+ COUNT_W = (1.0, 0.7, 0.5, 0.35)
26
+ DISTILLT5_REPO = "LifuWang/DistillT5"
27
+ DISTILLT5_TOKENIZER_REPO = "google-t5/t5-base"
28
+ DISTILLT5_D_MODEL = 768
29
+ DISTILLT5_OUT_DIM = 4096
30
+ MICA_CTX_DIM = 512
31
+ VAE_REPO = "stabilityai/sd-vae-ft-mse"
32
+ VAE_SCALE = 0.18215
33
+
34
+
35
+ @dataclass
36
+ class MicaConfig:
37
+ latent_ch: int = 4
38
+ widths: list[int] = field(default_factory=lambda: [288, 832, 1664])
39
+ depths: list[int] = field(default_factory=lambda: [4, 6, 2])
40
+ steer_rank: list[int] = field(default_factory=lambda: [128, 256, 256])
41
+ expansion: int = 3
42
+ ctx_dim: int = 512
43
+ dim: int = 640
44
+ p_dim: int = 256
45
+ perceiver_depth: int = 4
46
+ prelude: int = 3
47
+ core: int = 3
48
+ coda: int = 2
49
+ loops: int = 4
50
+ grid: int = 24
51
+ n_global: int = 16
52
+ n_freq: int = 6
53
+ head_dim: int = 64
54
+ read_ch: int = 96
55
+ read_depth: int = 2
56
+ up_rank: int = 32
57
+ outer_mode: str = "flat"
58
+ coord_res: bool = True
59
+ rope: bool = True
60
+ resolution_px: int = 768
61
+ vae_downsample: int = 8
62
+ vae_scale: float = VAE_SCALE
63
+
64
+
65
+ class LayerNorm2d(nn.Module):
66
+ def __init__(self, dim: int, affine: bool = True, eps: float = 1e-6):
67
+ super().__init__()
68
+ self.ln = nn.LayerNorm(dim, eps=eps, elementwise_affine=affine)
69
+
70
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
71
+ return self.ln(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
72
+
73
+
74
+ class GRN(nn.Module):
75
+ def __init__(self, dim: int, eps: float = 1e-6):
76
+ super().__init__()
77
+ self.gamma = nn.Parameter(torch.zeros(1, dim, 1, 1))
78
+ self.beta = nn.Parameter(torch.zeros(1, dim, 1, 1))
79
+ self.eps = eps
80
+
81
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
82
+ gx = torch.linalg.vector_norm(x.float(), dim=(2, 3), keepdim=True)
83
+ nx = gx / (gx.mean(dim=1, keepdim=True) + self.eps)
84
+ return self.gamma * (x * nx.to(x.dtype)) + self.beta + x
85
+
86
+
87
+ class TimestepEmbedder(nn.Module):
88
+ def __init__(self, dim: int, freq_dim: int = 256):
89
+ super().__init__()
90
+ self.freq_dim = freq_dim
91
+ self.mlp = nn.Sequential(nn.Linear(freq_dim, dim), nn.SiLU(), nn.Linear(dim, dim))
92
+
93
+ def forward(self, t: torch.Tensor) -> torch.Tensor:
94
+ half = self.freq_dim // 2
95
+ freqs = torch.exp(-math.log(10000.0) * torch.arange(half, device=t.device) / half)
96
+ args = t[:, None].float() * freqs[None] * 1000.0
97
+ return self.mlp(torch.cat([torch.cos(args), torch.sin(args)], dim=-1))
98
+
99
+
100
+ def fourier_coords(h: int, w: int, n_freq: int, device) -> torch.Tensor:
101
+ ys = (torch.arange(h, device=device, dtype=torch.float32) + 0.5) / h * 2 - 1
102
+ xs = (torch.arange(w, device=device, dtype=torch.float32) + 0.5) / w * 2 - 1
103
+ yy, xx = torch.meshgrid(ys, xs, indexing="ij")
104
+ f = (2.0 ** torch.arange(n_freq, device=device, dtype=torch.float32)) * math.pi
105
+ feats = [fn(c.reshape(-1, 1) * f) for c in (xx, yy) for fn in (torch.sin, torch.cos)]
106
+ return torch.cat(feats, 1)
107
+
108
+
109
+ def raw_coords(h: int, w: int, device, dtype=torch.float32) -> torch.Tensor:
110
+ ys = (torch.arange(h, device=device, dtype=torch.float32) + 0.5) / h * 2 - 1
111
+ xs = (torch.arange(w, device=device, dtype=torch.float32) + 0.5) / w * 2 - 1
112
+ yy, xx = torch.meshgrid(ys, xs, indexing="ij")
113
+ return torch.stack([xx, yy, (xx ** 2 + yy ** 2).sqrt()])[None].to(dtype)
114
+
115
+
116
+ def rope_freqs(head_dim: int, device) -> torch.Tensor:
117
+ n = head_dim // 4
118
+ return math.pi * 2.0 ** torch.linspace(-1.0, 3.0, n, device=device, dtype=torch.float32)
119
+
120
+
121
+ def grid_xy(h: int, w: int, device) -> torch.Tensor:
122
+ ys = (torch.arange(h, device=device, dtype=torch.float32) + 0.5) / h * 2 - 1
123
+ xs = (torch.arange(w, device=device, dtype=torch.float32) + 0.5) / w * 2 - 1
124
+ yy, xx = torch.meshgrid(ys, xs, indexing="ij")
125
+ return torch.stack([xx.reshape(-1), yy.reshape(-1)], 1)
126
+
127
+
128
+ def rope_angles(xy: torch.Tensor, head_dim: int, n_unrotated: int = 0) -> torch.Tensor:
129
+ f = rope_freqs(head_dim, xy.device)
130
+ ang = torch.cat([xy[:, :1] * f, xy[:, 1:] * f], 1)
131
+ if n_unrotated:
132
+ ang = torch.cat([ang, ang.new_zeros(n_unrotated, ang.shape[1])], 0)
133
+ return ang
134
+
135
+
136
+ def apply_rope(x: torch.Tensor, ang: torch.Tensor | None) -> torch.Tensor:
137
+ if ang is None:
138
+ return x
139
+ with torch.autocast(x.device.type, enabled=False):
140
+ xf = x.float()
141
+ x1, x2 = xf[..., 0::2], xf[..., 1::2]
142
+ c, s = ang.cos(), ang.sin()
143
+ out = torch.stack([x1 * c - x2 * s, x1 * s + x2 * c], -1).flatten(-2)
144
+ return out.to(x.dtype)
145
+
146
+
147
+ def zero_last(m: nn.Module) -> nn.Module:
148
+ last = [x for x in m.modules() if isinstance(x, (nn.Linear, nn.Conv2d))][-1]
149
+ nn.init.zeros_(last.weight)
150
+ if last.bias is not None:
151
+ nn.init.zeros_(last.bias)
152
+ return m
153
+
154
+
155
+ def subsample(z: torch.Tensor, native: int) -> torch.Tensor:
156
+ s = z.shape[-1] // native
157
+ if z.shape[-1] == native:
158
+ return z
159
+ if s * native != z.shape[-1] or z.shape[-2] != z.shape[-1] or s != 2:
160
+ raise ValueError(f"latent {tuple(z.shape[-2:])}: only {native}^2 and {2 * native}^2 supported")
161
+ return z[..., ::2, ::2]
162
+
163
+
164
+ def res_scale(z: torch.Tensor, native: int) -> torch.Tensor:
165
+ return torch.full((z.shape[0],), math.log2(z.shape[-1] / native), device=z.device)
166
+
167
+
168
+ class Attn(nn.Module):
169
+ def __init__(self, dim: int, kv_dim: int, head_dim: int = 64):
170
+ super().__init__()
171
+ self.h, self.d = dim // head_dim, head_dim
172
+ self.q = nn.Linear(dim, dim)
173
+ self.kv = nn.Linear(kv_dim, 2 * dim)
174
+ self.qn, self.kn = nn.RMSNorm(head_dim), nn.RMSNorm(head_dim)
175
+ self.out = nn.Linear(dim, dim)
176
+
177
+ def forward(self, x, kv, pad=None, ang_q=None, ang_k=None):
178
+ B, N, _ = x.shape
179
+ q = self.q(x).view(B, N, self.h, self.d).transpose(1, 2)
180
+ k, v = self.kv(kv).view(B, kv.shape[1], 2, self.h, self.d).permute(2, 0, 3, 1, 4)
181
+ q, k = apply_rope(self.qn(q), ang_q), apply_rope(self.kn(k), ang_k)
182
+ m = None if pad is None else ~pad[:, None, None, :]
183
+ o = F.scaled_dot_product_attention(q, k, v, attn_mask=m)
184
+ return self.out(o.transpose(1, 2).reshape(B, N, -1))
185
+
186
+
187
+ class XBlock2(nn.Module):
188
+ def __init__(self, dim: int, ctx_dim: int | None, self_attn: bool = True, mlp: int = 2, head_dim: int = 64):
189
+ super().__init__()
190
+ self.sa = Attn(dim, dim, head_dim) if self_attn else None
191
+ self.n_sa = nn.LayerNorm(dim) if self_attn else None
192
+ self.xa = Attn(dim, ctx_dim, head_dim) if ctx_dim else None
193
+ self.n_xa = nn.LayerNorm(dim) if ctx_dim else None
194
+ self.n_ctx = nn.LayerNorm(ctx_dim) if ctx_dim else None
195
+ self.n_mlp = nn.LayerNorm(dim)
196
+ self.mlp = nn.Sequential(nn.Linear(dim, mlp * dim), nn.GELU(), nn.Linear(mlp * dim, dim))
197
+
198
+ def forward(self, q, ctx=None, pad=None, ang_q=None, ang_ctx=None):
199
+ if self.sa is not None:
200
+ h = self.n_sa(q)
201
+ q = q + self.sa(h, h, None, ang_q, ang_q)
202
+ if self.xa is not None:
203
+ c = self.n_ctx(ctx)
204
+ q = q + self.xa(self.n_xa(q), c, pad, ang_q if ang_ctx is not None else None, ang_ctx)
205
+ return q + self.mlp(self.n_mlp(q))
206
+
207
+
208
+ class ResEmbed(nn.Module):
209
+ def __init__(self, dim: int, zero_init: bool = True):
210
+ super().__init__()
211
+ self.emb = TimestepEmbedder(dim)
212
+ if zero_init:
213
+ zero_last(self.emb)
214
+
215
+ def forward(self, r):
216
+ return self.emb(r) - self.emb(torch.zeros_like(r))
217
+
218
+
219
+ class FiLMConvNeXt(nn.Module):
220
+ def __init__(self, ch: int, cond_dim: int, expansion: int = 2):
221
+ super().__init__()
222
+ self.dw = nn.Conv2d(ch, ch, 7, padding=3, groups=ch)
223
+ self.norm = LayerNorm2d(ch, affine=False)
224
+ self.film = nn.Linear(cond_dim, 3 * ch)
225
+ self.pw1 = nn.Conv2d(ch, expansion * ch, 1)
226
+ self.pw2 = nn.Conv2d(expansion * ch, ch, 1)
227
+ nn.init.zeros_(self.film.weight)
228
+ nn.init.zeros_(self.film.bias)
229
+
230
+ def forward(self, x, cond):
231
+ shift, scale, gate = self.film(cond)[:, :, None, None].chunk(3, 1)
232
+ h = self.norm(self.dw(x)) * (1 + scale) + shift
233
+ return x + (1 + gate) * self.pw2(F.gelu(self.pw1(h)))
234
+
235
+
236
+ class ConvRead(nn.Module):
237
+ def __init__(self, latent_ch: int, out_dim: int, cond_dim: int, ch: int = 96, depth: int = 2):
238
+ super().__init__()
239
+ self.stem = nn.Conv2d(latent_ch + N_COORD, ch, 3, padding=1)
240
+ self.blocks = nn.ModuleList(FiLMConvNeXt(ch, cond_dim) for _ in range(depth))
241
+ self.norm = LayerNorm2d(ch)
242
+ self.proj = zero_last(nn.Linear(ch, out_dim))
243
+
244
+ def forward(self, z_hr, coords_hr, cond, grid_hw):
245
+ h = self.stem(torch.cat([z_hr, coords_hr.expand(z_hr.shape[0], -1, -1, -1).to(z_hr.dtype)], 1))
246
+ for b in self.blocks:
247
+ h = b(h, cond)
248
+ h = F.adaptive_avg_pool2d(self.norm(h), grid_hw)
249
+ return self.proj(h.flatten(2).transpose(1, 2))
250
+
251
+
252
+ class SpatialModBlock(nn.Module):
253
+ def __init__(self, dim: int, d_mod: int, expansion: int = 3):
254
+ super().__init__()
255
+ self.dwconv = nn.Conv2d(dim, dim, 7, padding=3, groups=dim)
256
+ self.norm = LayerNorm2d(dim, affine=False)
257
+ self.pw1 = nn.Conv2d(dim, expansion * dim, 1)
258
+ self.act = nn.GELU()
259
+ self.grn = GRN(expansion * dim)
260
+ self.pw2 = nn.Conv2d(expansion * dim, dim, 1)
261
+ self.mod = nn.Conv2d(d_mod, 3 * dim, 1)
262
+ nn.init.zeros_(self.mod.weight)
263
+ nn.init.zeros_(self.mod.bias)
264
+
265
+ def forward(self, x: torch.Tensor, m: torch.Tensor) -> torch.Tensor:
266
+ mod = self.mod(m)
267
+ if mod.shape[-2:] != x.shape[-2:]:
268
+ mod = F.interpolate(mod, size=x.shape[-2:], mode="bilinear", align_corners=False)
269
+ shift, scale, gate = mod.chunk(3, dim=1)
270
+ h = self.norm(self.dwconv(x)) * (1 + scale) + shift
271
+ h = self.pw2(self.grn(self.act(self.pw1(h))))
272
+ return x + gate * h
273
+
274
+
275
+ class CoordIn(nn.Module):
276
+ def __init__(self, ch: int, res_channel: bool = False):
277
+ super().__init__()
278
+ self.res_channel = res_channel
279
+ self.proj = zero_last(nn.Conv2d(N_COORD + int(res_channel), ch, 1))
280
+
281
+ def forward(self, x, r: float = 0.0):
282
+ c = raw_coords(x.shape[-2], x.shape[-1], x.device, x.dtype)
283
+ if self.res_channel:
284
+ c = torch.cat([c, torch.full_like(c[:, :1], float(r))], 1)
285
+ return x + self.proj(c)
286
+
287
+
288
+ class PlanUp(nn.Module):
289
+ def __init__(self, dim: int, rank: int = 32, kernel: int = 5, latent_ch: int = 4):
290
+ super().__init__()
291
+ self.dw = nn.Conv2d(dim, dim, kernel, padding=kernel // 2, groups=dim)
292
+ self.dw2 = nn.Conv2d(dim, dim, kernel, padding=kernel // 2, groups=dim)
293
+ self.down = nn.Conv2d(dim, rank, 1)
294
+ self.coord = nn.Conv2d(N_COORD, rank, 1)
295
+ self.guide = nn.Conv2d(latent_ch, rank, 3, padding=1)
296
+ self.up = zero_last(nn.Conv2d(rank, dim, 1))
297
+
298
+ def forward(self, m, z):
299
+ size = z.shape[-2:]
300
+ b = F.interpolate(m, size=size, mode="bilinear", align_corners=False)
301
+ h = (self.down(self.dw2(F.gelu(self.dw(b))))
302
+ + self.coord(raw_coords(*size, m.device, b.dtype))
303
+ + self.guide(z.to(b.dtype)))
304
+ return b + self.up(F.gelu(h))
305
+
306
+
307
+ def count_features(n: torch.Tensor) -> torch.Tensor:
308
+ nf = n.float()
309
+ th = math.pi * torch.log2(nf.clamp(1, 16)) / 4
310
+ parts = [w * f(k * th) for k, w in zip(COUNT_K, COUNT_W) for f in (torch.cos, torch.sin)]
311
+ parts += [torch.log2(nf.clamp(min=1)) / 4, (nf > 16).float()]
312
+ return torch.stack(parts, -1)
313
+
314
+
315
+ class CountCode(nn.Module):
316
+ def __init__(self, ctx_dim: int):
317
+ super().__init__()
318
+ self.proj = nn.Linear(10, ctx_dim)
319
+ self.gate = nn.Parameter(torch.zeros(ctx_dim))
320
+
321
+ def forward(self, ctx, counts=None):
322
+ if counts is None:
323
+ return ctx
324
+ counts = counts.to(ctx.device)
325
+ on = (counts > 0).to(ctx.dtype)[..., None]
326
+ code = self.proj(count_features(counts).to(ctx.dtype))
327
+ return ctx + on * self.gate.to(ctx.dtype) * (code - ctx)
328
+
329
+
330
+ class MicaThinker(nn.Module):
331
+ def __init__(self, cfg: MicaConfig):
332
+ super().__init__()
333
+ self.grid, self.n_global, self.n_freq, self.rope = cfg.grid, cfg.n_global, cfg.n_freq, cfg.rope
334
+ self.loops = cfg.loops
335
+ self.native = 2 * cfg.grid
336
+ self.head_dim = cfg.head_dim
337
+ pos = 4 * cfg.n_freq
338
+ self.queries = nn.Parameter(torch.randn(cfg.grid * cfg.grid + cfg.n_global, cfg.p_dim) * 0.02)
339
+ self.q_pos = nn.Linear(pos, cfg.p_dim)
340
+ self.t1 = TimestepEmbedder(cfg.p_dim)
341
+ self.t2 = TimestepEmbedder(cfg.dim)
342
+ self.in_latent = nn.Linear(cfg.latent_ch * 4 + pos, cfg.p_dim)
343
+ self.perceiver = nn.ModuleList(
344
+ XBlock2(cfg.p_dim, cfg.p_dim, self_attn=False, head_dim=cfg.head_dim)
345
+ for _ in range(cfg.perceiver_depth)
346
+ )
347
+ self.lift = nn.Linear(cfg.p_dim, cfg.dim)
348
+ self.prelude = nn.ModuleList(
349
+ XBlock2(cfg.dim, cfg.ctx_dim, head_dim=cfg.head_dim) for _ in range(cfg.prelude)
350
+ )
351
+ self.core = nn.ModuleList(
352
+ XBlock2(cfg.dim, cfg.ctx_dim, head_dim=cfg.head_dim) for _ in range(cfg.core)
353
+ )
354
+ self.coda = nn.ModuleList(
355
+ XBlock2(cfg.dim, cfg.ctx_dim, head_dim=cfg.head_dim) for _ in range(cfg.coda)
356
+ )
357
+ self.adapter = nn.Linear(2 * cfg.dim, cfg.dim)
358
+ self.norm = nn.LayerNorm(cfg.dim)
359
+ self.mr_taps = zero_last(nn.Linear(cfg.latent_ch * 16, cfg.p_dim))
360
+ self.mr_read = ConvRead(cfg.latent_ch, cfg.p_dim, cond_dim=cfg.p_dim,
361
+ ch=cfg.read_ch, depth=cfg.read_depth)
362
+ self.mr_res_q = ResEmbed(cfg.p_dim)
363
+ self.mr_res_s = ResEmbed(cfg.dim)
364
+ self.mr_res_c = ResEmbed(cfg.p_dim, zero_init=False)
365
+
366
+ def read(self, z, t_emb, r):
367
+ B = z.shape[0]
368
+ zb = subsample(z, self.native)
369
+ hb, wb = zb.shape[-2:]
370
+ pos = fourier_coords(hb // 2, wb // 2, self.n_freq, z.device)[None].expand(B, -1, -1)
371
+ lat = F.pixel_unshuffle(zb, 2).flatten(2).transpose(1, 2)
372
+ kv = self.in_latent(torch.cat([lat, pos], -1))
373
+ coords = raw_coords(*z.shape[-2:], z.device)
374
+ if z.shape[-1] == 2 * self.native:
375
+ z_hr, c_hr = z, coords
376
+ else:
377
+ z_hr = F.interpolate(z, scale_factor=2, mode="nearest")
378
+ c_hr = F.interpolate(coords, scale_factor=2, mode="nearest")
379
+ taps = F.pixel_unshuffle(z_hr, 4).flatten(2).transpose(1, 2)
380
+ cond = t_emb + self.mr_res_c(r)
381
+ return kv + self.mr_taps(taps) + self.mr_read(z_hr, c_hr, cond, (hb // 2, wb // 2)), (hb, wb)
382
+
383
+ def forward(self, z, t, ctx, mask, loops: int | None = None, mask_all: bool = False):
384
+ B = z.shape[0]
385
+ g, dev = self.grid, z.device
386
+ loops = self.loops if loops is None else loops
387
+ r = res_scale(z, self.native)
388
+ t1 = self.t1(t)
389
+ kv, (hb, wb) = self.read(z, t1, r)
390
+ q = self.queries[None].expand(B, -1, -1).clone()
391
+ q[:, :g * g] = q[:, :g * g] + self.q_pos(fourier_coords(g, g, self.n_freq, dev)[None].expand(B, -1, -1))
392
+ q = q + t1[:, None] + self.mr_res_q(r)[:, None]
393
+ ang_pq = ang_pk = ang_q = None
394
+ if self.rope:
395
+ ang_pq = rope_angles(grid_xy(g, g, dev), self.head_dim, self.n_global)
396
+ ang_pk = rope_angles(grid_xy(hb // 2, wb // 2, dev), self.head_dim)
397
+ ang_q = ang_pq
398
+ for blk in self.perceiver:
399
+ q = blk(q, kv, None, ang_pq, ang_pk)
400
+ q = self.lift(q) + self.t2(t)[:, None] + self.mr_res_s(r)[:, None]
401
+ pad = None if mask_all else ~mask.bool()
402
+ for blk in self.prelude:
403
+ q = blk(q, ctx, pad, ang_q)
404
+ e, s = q, q
405
+ for _ in range(loops):
406
+ s = self.adapter(torch.cat([s, e], -1))
407
+ for blk in self.core:
408
+ s = blk(s, ctx, pad, ang_q)
409
+ for blk in self.coda:
410
+ s = blk(s, ctx, pad, ang_q)
411
+ out = self.norm(s)
412
+ return out[:, :g * g].transpose(1, 2).reshape(B, -1, g, g)
413
+
414
+
415
+ class MicaGenerator(nn.Module):
416
+ def __init__(self, cfg: MicaConfig | None = None):
417
+ super().__init__()
418
+ cfg = cfg or MicaConfig()
419
+ self.cfg = cfg
420
+ self.native = 2 * cfg.grid
421
+ self.loops = cfg.loops
422
+ self.thinker = MicaThinker(cfg)
423
+ self.mr_count = CountCode(cfg.ctx_dim)
424
+
425
+ w0, w1, w2 = cfg.widths
426
+ d0, d1, d2 = cfg.depths
427
+ sr = cfg.steer_rank
428
+ self.steer_in = nn.ModuleDict({
429
+ lvl: nn.Conv2d(cfg.dim, r, 1) for lvl, r in zip(("l0", "l1", "l2"), sr) if r
430
+ })
431
+ d_in = [r or cfg.dim for r in sr]
432
+ self.stem = nn.Conv2d(cfg.latent_ch, w0, 3, padding=1)
433
+ mk = lambda w, dm, n: nn.ModuleList(SpatialModBlock(w, dm, cfg.expansion) for _ in range(n))
434
+ self.enc0 = mk(w0, d_in[0], d0)
435
+ self.enc1 = mk(w1, d_in[1], d1)
436
+ self.mid = mk(w2, d_in[2], 2 * d2)
437
+ self.dec1 = mk(w1, d_in[1], d1)
438
+ self.dec0 = mk(w0, d_in[0], d0)
439
+ self.down0 = nn.Sequential(LayerNorm2d(w0), nn.Conv2d(w0, w1, 2, stride=2))
440
+ self.down1 = nn.Sequential(LayerNorm2d(w1), nn.Conv2d(w1, w2, 2, stride=2))
441
+ self.up1 = nn.ConvTranspose2d(w2, w1, 2, stride=2)
442
+ self.up0 = nn.ConvTranspose2d(w1, w0, 2, stride=2)
443
+ self.final_norm = LayerNorm2d(w0, affine=False)
444
+ self.final_mod = nn.Conv2d(cfg.dim, 2 * w0, 1)
445
+ self.final_conv = nn.Conv2d(w0, cfg.latent_ch, 3, padding=1)
446
+ self.plan_up = PlanUp(cfg.dim, cfg.up_rank, 5, cfg.latent_ch)
447
+ self.coord = nn.ModuleDict({
448
+ k: CoordIn(w, cfg.coord_res)
449
+ for k, w in (("enc0", w0), ("enc1", w1), ("mid", w2), ("dec1", w1), ("dec0", w0))
450
+ })
451
+
452
+ def _run(self, blocks, x, s):
453
+ for blk in blocks:
454
+ x = blk(x, s)
455
+ return x
456
+
457
+ def _steer(self, lvl, m, x, m_up=None):
458
+ if m_up is not None and m_up.shape[-2:] == x.shape[-2:]:
459
+ m = m_up
460
+ s = self.steer_in[lvl](m) if lvl in self.steer_in else m
461
+ if s.shape[-1] > x.shape[-1]:
462
+ return F.adaptive_avg_pool2d(s, x.shape[-2:])
463
+ if s.shape[-1] < x.shape[-1]:
464
+ return F.interpolate(s, size=x.shape[-2:], mode="bilinear", align_corners=False)
465
+ return s
466
+
467
+ def forward(self, z, t, ctx, mask, loops: int | None = None, counts=None, mask_all: bool = False):
468
+ ctx = self.mr_count(ctx.float(), counts)
469
+ m = self.thinker(z, t, ctx, mask, self.loops if loops is None else loops, mask_all=mask_all)
470
+ r = math.log2(z.shape[-1] / self.native)
471
+ m_up = self.plan_up(m, z) if m.shape[-1] < z.shape[-1] else None
472
+ h = self.stem(z)
473
+ c = self.coord
474
+ x0 = self._run(self.enc0, c["enc0"](h, r), self._steer("l0", m, h, m_up))
475
+ x = self.down0(x0)
476
+ x1 = self._run(self.enc1, c["enc1"](x, r), self._steer("l1", m, x, m_up))
477
+ x = self.down1(x1)
478
+ x = self._run(self.mid, c["mid"](x, r), self._steer("l2", m, x, m_up))
479
+ x = self.up1(x) + x1
480
+ x = self._run(self.dec1, c["dec1"](x, r), self._steer("l1", m, x, m_up))
481
+ x = self.up0(x) + x0
482
+ feat = self._run(self.dec0, c["dec0"](x, r), self._steer("l0", m, x, m_up))
483
+ fm = self.final_mod(m_up if m_up is not None else m)
484
+ if fm.shape[-2:] != feat.shape[-2:]:
485
+ fm = F.interpolate(fm, size=feat.shape[-2:], mode="bilinear", align_corners=False)
486
+ shift, scale = fm.chunk(2, dim=1)
487
+ return self.final_conv(self.final_norm(feat) * (1 + scale) + shift)
488
+
489
+
490
+ class DistillT5TextEncoder:
491
+ """LifuWang/DistillT5 (with explicit key remap) + google-t5/t5-base tokenizer + Mica ctx_proj."""
492
+
493
+ def __init__(self, device: str = "cuda", max_len: int = 512):
494
+ self.device = device
495
+ self.max_len = max_len
496
+ self.tokenizer = None
497
+ self.encoder = None
498
+ self.final_projection = None
499
+ self.ctx_proj = nn.Linear(DISTILLT5_OUT_DIM, MICA_CTX_DIM)
500
+
501
+ def load(self):
502
+ from huggingface_hub import hf_hub_download
503
+ from safetensors import safe_open
504
+ from transformers import AutoTokenizer, T5EncoderModel
505
+
506
+ self.tokenizer = AutoTokenizer.from_pretrained(DISTILLT5_TOKENIZER_REPO)
507
+ self.encoder = T5EncoderModel.from_pretrained(DISTILLT5_REPO, dtype=torch.float32).to(self.device)
508
+ path = hf_hub_download(DISTILLT5_REPO, "model.safetensors")
509
+ mapped = {}
510
+ with safe_open(path, framework="pt") as f:
511
+ for k in f.keys():
512
+ if k.startswith("encoder.encoder."):
513
+ mapped[k[len("encoder."):]] = f.get_tensor(k)
514
+ elif k == "encoder.shared.weight":
515
+ mapped["shared.weight"] = f.get_tensor(k)
516
+ mapped["encoder.embed_tokens.weight"] = f.get_tensor(k)
517
+ missing, unexpected = self.encoder.load_state_dict(mapped, strict=False)
518
+ if missing or unexpected:
519
+ raise RuntimeError(f"DistillT5 remap incomplete: missing={missing} unexpected={unexpected}")
520
+
521
+ self.final_projection = nn.Sequential(
522
+ nn.Linear(DISTILLT5_D_MODEL, DISTILLT5_OUT_DIM, bias=False),
523
+ nn.ReLU(),
524
+ nn.Dropout(0.1),
525
+ nn.Linear(DISTILLT5_OUT_DIM, DISTILLT5_OUT_DIM, bias=False),
526
+ )
527
+ with safe_open(path, framework="pt") as f:
528
+ self.final_projection[0].weight.data.copy_(f.get_tensor("final_projection.0.weight"))
529
+ self.final_projection[3].weight.data.copy_(f.get_tensor("final_projection.3.weight"))
530
+
531
+ self.final_projection = self.final_projection.to(self.device).eval()
532
+ self.ctx_proj = self.ctx_proj.to(self.device).eval()
533
+ self.encoder.eval()
534
+ return self
535
+
536
+ @torch.no_grad()
537
+ def encode_texts(self, texts: list[str]):
538
+ t = self.tokenizer(texts, padding="longest", truncation=True, max_length=self.max_len, return_tensors="pt")
539
+ ids, mask = t["input_ids"].to(self.device), t["attention_mask"].to(self.device)
540
+ with torch.autocast(self.device, dtype=torch.bfloat16, enabled=self.device == "cuda"):
541
+ hidden = self.encoder(input_ids=ids, attention_mask=mask).last_hidden_state
542
+ hidden = self.final_projection(hidden)
543
+ hidden = self.ctx_proj(hidden)
544
+ return hidden.float(), mask
545
+
546
+
547
+ def shift_t(t: float, shift: float) -> float:
548
+ if shift == 1.0:
549
+ return t
550
+ s = 1.0 - t
551
+ return 1.0 - shift * s / (1.0 + (shift - 1.0) * s)
552
+
553
+
554
+ @torch.no_grad()
555
+ def sample_mica(model: MicaGenerator, text_enc: DistillT5TextEncoder, vae,
556
+ prompts: list[str], steps: int = 50, cfg: float = 4.0,
557
+ shift: float = 2.0, resolution: int = 768, seed: int = 42,
558
+ device: str = "cuda"):
559
+ """Euler flow-matching sampler from t=0 (noise) -> t=1 (data) with CFG."""
560
+ from PIL import Image
561
+ import numpy as np
562
+
563
+ B = len(prompts)
564
+ H = W = resolution // 8
565
+ gen = torch.Generator(device=device).manual_seed(seed)
566
+ z = torch.randn((B, 4, H, W), generator=gen, device=device, dtype=torch.float32)
567
+
568
+ ctx_c, mask_c = text_enc.encode_texts(prompts)
569
+ ctx_u, mask_u = text_enc.encode_texts([""] * B)
570
+ # Pad cond & uncond to same length for single batched CFG pass
571
+ L = max(ctx_c.shape[1], ctx_u.shape[1])
572
+ if ctx_c.shape[1] < L:
573
+ ctx_c = F.pad(ctx_c, (0, 0, 0, L - ctx_c.shape[1]))
574
+ mask_c = F.pad(mask_c, (0, L - mask_c.shape[1]))
575
+ if ctx_u.shape[1] < L:
576
+ ctx_u = F.pad(ctx_u, (0, 0, 0, L - ctx_u.shape[1]))
577
+ mask_u = F.pad(mask_u, (0, L - mask_u.shape[1]))
578
+ ctx_both = torch.cat([ctx_u, ctx_c], dim=0)
579
+ mask_both = torch.cat([mask_u, mask_c], dim=0)
580
+
581
+ ts = [shift_t(i / steps, shift) for i in range(steps + 1)]
582
+ for i in range(steps):
583
+ t_cur, t_nxt = ts[i], ts[i + 1]
584
+ dt = t_nxt - t_cur
585
+ t_vec = torch.full((2 * B,), t_cur, device=device, dtype=torch.float32)
586
+ z_in = torch.cat([z, z], dim=0)
587
+ with torch.autocast(device, dtype=torch.bfloat16, enabled=device == "cuda"):
588
+ v_both = model(z_in, t_vec, ctx_both, mask_both)
589
+ vu, vc = v_both.float().chunk(2, dim=0)
590
+ v = vu + cfg * (vc - vu)
591
+ z = z + dt * v
592
+
593
+ images = []
594
+ for b in range(B):
595
+ lat = (z[b:b + 1] / VAE_SCALE).to(dtype=vae.dtype)
596
+ img = vae.decode(lat).sample.float().clamp(-1, 1)
597
+ arr = ((img[0].permute(1, 2, 0).cpu().numpy() + 1.0) * 127.5).round().clip(0, 255).astype(np.uint8)
598
+ images.append(Image.fromarray(arr))
599
+ return images