Upload Mica Preview (step 291,000 EMA weights, portable code, gallery, and model card)
Browse filesFiles changed (17)
- .gitattributes+11
- README.mdAdded+103
- config.jsonAdded+51
- ctx_proj.safetensorsAdded+3
- gallery/01_alpine_sunrise.pngAdded
- gallery/02_iceland_aurora.pngAdded
- gallery/03_kyoto_autumn.pngAdded
- gallery/04_redwood_mist.pngAdded
- gallery/05_sahara_dunes.pngAdded
- gallery/06_amalfi_coast.pngAdded
- gallery/07_scottish_highlands.pngAdded
- gallery/08_patagonia_lake.pngAdded
- gallery/09_canyon_river.pngAdded
- gallery/10_lavender_provence.pngAdded
- gallery/gallery_grid.jpgAdded
- generator.safetensorsAdded+3
- mica_modeling.pyAdded+599
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363738394041424344454632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textgallery/01_alpine_sunrise.png filter=lfs diff=lfs merge=lfs -textgallery/02_iceland_aurora.png filter=lfs diff=lfs merge=lfs -textgallery/03_kyoto_autumn.png filter=lfs diff=lfs merge=lfs -textgallery/04_redwood_mist.png filter=lfs diff=lfs merge=lfs -textgallery/05_sahara_dunes.png filter=lfs diff=lfs merge=lfs -textgallery/06_amalfi_coast.png filter=lfs diff=lfs merge=lfs -textgallery/07_scottish_highlands.png filter=lfs diff=lfs merge=lfs -textgallery/08_patagonia_lake.png filter=lfs diff=lfs merge=lfs -textgallery/09_canyon_river.png filter=lfs diff=lfs merge=lfs -textgallery/10_lavender_provence.png filter=lfs diff=lfs merge=lfs -textgallery/gallery_grid.jpg filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103---license: apache-2.0language: - enpipeline_tag: text-to-imagelibrary_name: pytorchtags: - mica - text-to-image - flow-matching - fcdm - convnext - perceiver - 768px - preview---
# Mica Preview
**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.
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.
---
## Sample Gallery
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):

| Sample | Prompt ||---|---|| `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 || `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 || `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 || `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 || `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 || `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 || `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 || `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 || `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 || `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 |
---
## Architecture & Training
Mica Preview separates global semantic planning from local spatial rendering in plain PyTorch (`mica_modeling.py`, no custom CUDA extensions required):
- **Parameters:** 194,328,196 total (`192,230,532` generator + `2,097,664` text adapter, released as EMA weights `decay = 0.9995`)- **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)- **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)- **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`)- **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- **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`)
---
## Quick Start
```pythonimport torchfrom diffusers import AutoencoderKLfrom huggingface_hub import hf_hub_downloadfrom safetensors.torch import load_filefrom mica_modeling import DistillT5TextEncoder, MicaConfig, MicaGenerator, VAE_REPO, sample_mica
repo_id = "Emergent-Knowledge/mica-preview"device = "cuda" if torch.cuda.is_available() else "cpu"
model = MicaGenerator(MicaConfig())model.load_state_dict(load_file(hf_hub_download(repo_id, "generator.safetensors")), strict=True)model = model.to(device).eval()
text_enc = DistillT5TextEncoder(device=device).load()text_enc.ctx_proj.load_state_dict(load_file(hf_hub_download(repo_id, "ctx_proj.safetensors")), strict=True)
vae = AutoencoderKL.from_pretrained(VAE_REPO, torch_dtype=torch.bfloat16 if device == "cuda" else torch.float32).to(device).eval()
images = sample_mica( model, text_enc, vae, prompts=["A breathtaking sunrise over snow-capped Alpine peaks reflected in a calm turquoise glacial lake"], steps=50, cfg=4.0, shift=2.5, resolution=768, seed=42, device=device,)images[0].save("mica_sample.png")```
---
## Limitations
- **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.- **Square 768×768 native:** Tuned for square 768×768 generation; arbitrary aspect ratios are not yet supported.- **English prompts:** Text conditioning is trained on English captions via DistillT5.
---
## Acknowledgements & License
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).
Released under the **Apache-2.0** license.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051{ "model_type": "mica_v5_fcdm_thinker2", "step": 291000, "samples_seen": 4656000, "ema": true, "resolution_px": 768, "latent_size": 96, "vae_repo": "stabilityai/sd-vae-ft-mse", "vae_scale": 0.18215, "text_encoder_repo": "LifuWang/DistillT5", "tokenizer_repo": "google-t5/t5-base", "default_steps": 50, "default_cfg": 4.0, "default_shift": 2.5, "latent_ch": 4, "widths": [ 288, 832, 1664 ], "depths": [ 4, 6, 2 ], "steer_rank": [ 128, 256, 256 ], "expansion": 3, "ctx_dim": 512, "dim": 640, "p_dim": 256, "perceiver_depth": 4, "prelude": 3, "core": 3, "coda": 2, "loops": 4, "grid": 24, "n_global": 16, "n_freq": 6, "head_dim": 64, "read_ch": 96, "read_depth": 2, "up_rank": 32, "outer_mode": "flat", "coord_res": true, "rope": true, "vae_downsample": 8}123version https://git-lfs.github.com/spec/v1oid sha256:796b2cabb25697be53e89a23d9a912dc4bc184647f4c7b4488115a30c9ef9387size 8390832123version https://git-lfs.github.com/spec/v1oid sha256:165bc0668ebb3cedaccb10507362d571304adb6761d194d2a177183c718f1aafsize 768982904123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599"""Mica Preview (v5, 768px): Portable PyTorch inference model & pipeline.
Architecture: - 192.2M-param FCDM-Thinker2-MR (flat 768px mode, 96x96 SD-VAE latent grid) * Perceiver-based recurrent Thinker (24x24 spatial plan + 16 global tokens, 4 perceiver blocks, 3 prelude + 3 recurrent core x 4 loops + 2 coda blocks, 2D RoPE + QK-RMSNorm + multi-res ConvRead) * Pure-ConvNeXt V2 SpatialMod U-Net renderer (widths [288, 832, 1664], depths [4, 6, 2], expansion 3, steer_rank [128, 256, 256], PlanUp + CoordIn) - DistillT5 text encoder (LifuWang/DistillT5 + google-t5/t5-base tokenizer) with learned 4096 -> 512 ctx_proj adapter (2.1M params). - Frozen stabilityai/sd-vae-ft-mse (scale 0.18215)."""from __future__ import annotations
import mathfrom dataclasses import dataclass, field
import torchimport torch.nn as nnimport torch.nn.functional as F
N_COORD = 3COUNT_K = (1, 2, 4, 8)COUNT_W = (1.0, 0.7, 0.5, 0.35)DISTILLT5_REPO = "LifuWang/DistillT5"DISTILLT5_TOKENIZER_REPO = "google-t5/t5-base"DISTILLT5_D_MODEL = 768DISTILLT5_OUT_DIM = 4096MICA_CTX_DIM = 512VAE_REPO = "stabilityai/sd-vae-ft-mse"VAE_SCALE = 0.18215
@dataclassclass MicaConfig: latent_ch: int = 4 widths: list[int] = field(default_factory=lambda: [288, 832, 1664]) depths: list[int] = field(default_factory=lambda: [4, 6, 2]) steer_rank: list[int] = field(default_factory=lambda: [128, 256, 256]) expansion: int = 3 ctx_dim: int = 512 dim: int = 640 p_dim: int = 256 perceiver_depth: int = 4 prelude: int = 3 core: int = 3 coda: int = 2 loops: int = 4 grid: int = 24 n_global: int = 16 n_freq: int = 6 head_dim: int = 64 read_ch: int = 96 read_depth: int = 2 up_rank: int = 32 outer_mode: str = "flat" coord_res: bool = True rope: bool = True resolution_px: int = 768 vae_downsample: int = 8 vae_scale: float = VAE_SCALE
class LayerNorm2d(nn.Module): def __init__(self, dim: int, affine: bool = True, eps: float = 1e-6): super().__init__() self.ln = nn.LayerNorm(dim, eps=eps, elementwise_affine=affine)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.ln(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
class GRN(nn.Module): def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.gamma = nn.Parameter(torch.zeros(1, dim, 1, 1)) self.beta = nn.Parameter(torch.zeros(1, dim, 1, 1)) self.eps = eps
def forward(self, x: torch.Tensor) -> torch.Tensor: gx = torch.linalg.vector_norm(x.float(), dim=(2, 3), keepdim=True) nx = gx / (gx.mean(dim=1, keepdim=True) + self.eps) return self.gamma * (x * nx.to(x.dtype)) + self.beta + x
class TimestepEmbedder(nn.Module): def __init__(self, dim: int, freq_dim: int = 256): super().__init__() self.freq_dim = freq_dim self.mlp = nn.Sequential(nn.Linear(freq_dim, dim), nn.SiLU(), nn.Linear(dim, dim))
def forward(self, t: torch.Tensor) -> torch.Tensor: half = self.freq_dim // 2 freqs = torch.exp(-math.log(10000.0) * torch.arange(half, device=t.device) / half) args = t[:, None].float() * freqs[None] * 1000.0 return self.mlp(torch.cat([torch.cos(args), torch.sin(args)], dim=-1))
def fourier_coords(h: int, w: int, n_freq: int, device) -> torch.Tensor: ys = (torch.arange(h, device=device, dtype=torch.float32) + 0.5) / h * 2 - 1 xs = (torch.arange(w, device=device, dtype=torch.float32) + 0.5) / w * 2 - 1 yy, xx = torch.meshgrid(ys, xs, indexing="ij") f = (2.0 ** torch.arange(n_freq, device=device, dtype=torch.float32)) * math.pi feats = [fn(c.reshape(-1, 1) * f) for c in (xx, yy) for fn in (torch.sin, torch.cos)] return torch.cat(feats, 1)
def raw_coords(h: int, w: int, device, dtype=torch.float32) -> torch.Tensor: ys = (torch.arange(h, device=device, dtype=torch.float32) + 0.5) / h * 2 - 1 xs = (torch.arange(w, device=device, dtype=torch.float32) + 0.5) / w * 2 - 1 yy, xx = torch.meshgrid(ys, xs, indexing="ij") return torch.stack([xx, yy, (xx ** 2 + yy ** 2).sqrt()])[None].to(dtype)
def rope_freqs(head_dim: int, device) -> torch.Tensor: n = head_dim // 4 return math.pi * 2.0 ** torch.linspace(-1.0, 3.0, n, device=device, dtype=torch.float32)
def grid_xy(h: int, w: int, device) -> torch.Tensor: ys = (torch.arange(h, device=device, dtype=torch.float32) + 0.5) / h * 2 - 1 xs = (torch.arange(w, device=device, dtype=torch.float32) + 0.5) / w * 2 - 1 yy, xx = torch.meshgrid(ys, xs, indexing="ij") return torch.stack([xx.reshape(-1), yy.reshape(-1)], 1)
def rope_angles(xy: torch.Tensor, head_dim: int, n_unrotated: int = 0) -> torch.Tensor: f = rope_freqs(head_dim, xy.device) ang = torch.cat([xy[:, :1] * f, xy[:, 1:] * f], 1) if n_unrotated: ang = torch.cat([ang, ang.new_zeros(n_unrotated, ang.shape[1])], 0) return ang
def apply_rope(x: torch.Tensor, ang: torch.Tensor | None) -> torch.Tensor: if ang is None: return x with torch.autocast(x.device.type, enabled=False): xf = x.float() x1, x2 = xf[..., 0::2], xf[..., 1::2] c, s = ang.cos(), ang.sin() out = torch.stack([x1 * c - x2 * s, x1 * s + x2 * c], -1).flatten(-2) return out.to(x.dtype)
def zero_last(m: nn.Module) -> nn.Module: last = [x for x in m.modules() if isinstance(x, (nn.Linear, nn.Conv2d))][-1] nn.init.zeros_(last.weight) if last.bias is not None: nn.init.zeros_(last.bias) return m
def subsample(z: torch.Tensor, native: int) -> torch.Tensor: s = z.shape[-1] // native if z.shape[-1] == native: return z if s * native != z.shape[-1] or z.shape[-2] != z.shape[-1] or s != 2: raise ValueError(f"latent {tuple(z.shape[-2:])}: only {native}^2 and {2 * native}^2 supported") return z[..., ::2, ::2]
def res_scale(z: torch.Tensor, native: int) -> torch.Tensor: return torch.full((z.shape[0],), math.log2(z.shape[-1] / native), device=z.device)
class Attn(nn.Module): def __init__(self, dim: int, kv_dim: int, head_dim: int = 64): super().__init__() self.h, self.d = dim // head_dim, head_dim self.q = nn.Linear(dim, dim) self.kv = nn.Linear(kv_dim, 2 * dim) self.qn, self.kn = nn.RMSNorm(head_dim), nn.RMSNorm(head_dim) self.out = nn.Linear(dim, dim)
def forward(self, x, kv, pad=None, ang_q=None, ang_k=None): B, N, _ = x.shape q = self.q(x).view(B, N, self.h, self.d).transpose(1, 2) k, v = self.kv(kv).view(B, kv.shape[1], 2, self.h, self.d).permute(2, 0, 3, 1, 4) q, k = apply_rope(self.qn(q), ang_q), apply_rope(self.kn(k), ang_k) m = None if pad is None else ~pad[:, None, None, :] o = F.scaled_dot_product_attention(q, k, v, attn_mask=m) return self.out(o.transpose(1, 2).reshape(B, N, -1))
class XBlock2(nn.Module): def __init__(self, dim: int, ctx_dim: int | None, self_attn: bool = True, mlp: int = 2, head_dim: int = 64): super().__init__() self.sa = Attn(dim, dim, head_dim) if self_attn else None self.n_sa = nn.LayerNorm(dim) if self_attn else None self.xa = Attn(dim, ctx_dim, head_dim) if ctx_dim else None self.n_xa = nn.LayerNorm(dim) if ctx_dim else None self.n_ctx = nn.LayerNorm(ctx_dim) if ctx_dim else None self.n_mlp = nn.LayerNorm(dim) self.mlp = nn.Sequential(nn.Linear(dim, mlp * dim), nn.GELU(), nn.Linear(mlp * dim, dim))
def forward(self, q, ctx=None, pad=None, ang_q=None, ang_ctx=None): if self.sa is not None: h = self.n_sa(q) q = q + self.sa(h, h, None, ang_q, ang_q) if self.xa is not None: c = self.n_ctx(ctx) q = q + self.xa(self.n_xa(q), c, pad, ang_q if ang_ctx is not None else None, ang_ctx) return q + self.mlp(self.n_mlp(q))
class ResEmbed(nn.Module): def __init__(self, dim: int, zero_init: bool = True): super().__init__() self.emb = TimestepEmbedder(dim) if zero_init: zero_last(self.emb)
def forward(self, r): return self.emb(r) - self.emb(torch.zeros_like(r))
class FiLMConvNeXt(nn.Module): def __init__(self, ch: int, cond_dim: int, expansion: int = 2): super().__init__() self.dw = nn.Conv2d(ch, ch, 7, padding=3, groups=ch) self.norm = LayerNorm2d(ch, affine=False) self.film = nn.Linear(cond_dim, 3 * ch) self.pw1 = nn.Conv2d(ch, expansion * ch, 1) self.pw2 = nn.Conv2d(expansion * ch, ch, 1) nn.init.zeros_(self.film.weight) nn.init.zeros_(self.film.bias)
def forward(self, x, cond): shift, scale, gate = self.film(cond)[:, :, None, None].chunk(3, 1) h = self.norm(self.dw(x)) * (1 + scale) + shift return x + (1 + gate) * self.pw2(F.gelu(self.pw1(h)))
class ConvRead(nn.Module): def __init__(self, latent_ch: int, out_dim: int, cond_dim: int, ch: int = 96, depth: int = 2): super().__init__() self.stem = nn.Conv2d(latent_ch + N_COORD, ch, 3, padding=1) self.blocks = nn.ModuleList(FiLMConvNeXt(ch, cond_dim) for _ in range(depth)) self.norm = LayerNorm2d(ch) self.proj = zero_last(nn.Linear(ch, out_dim))
def forward(self, z_hr, coords_hr, cond, grid_hw): h = self.stem(torch.cat([z_hr, coords_hr.expand(z_hr.shape[0], -1, -1, -1).to(z_hr.dtype)], 1)) for b in self.blocks: h = b(h, cond) h = F.adaptive_avg_pool2d(self.norm(h), grid_hw) return self.proj(h.flatten(2).transpose(1, 2))
class SpatialModBlock(nn.Module): def __init__(self, dim: int, d_mod: int, expansion: int = 3): super().__init__() self.dwconv = nn.Conv2d(dim, dim, 7, padding=3, groups=dim) self.norm = LayerNorm2d(dim, affine=False) self.pw1 = nn.Conv2d(dim, expansion * dim, 1) self.act = nn.GELU() self.grn = GRN(expansion * dim) self.pw2 = nn.Conv2d(expansion * dim, dim, 1) self.mod = nn.Conv2d(d_mod, 3 * dim, 1) nn.init.zeros_(self.mod.weight) nn.init.zeros_(self.mod.bias)
def forward(self, x: torch.Tensor, m: torch.Tensor) -> torch.Tensor: mod = self.mod(m) if mod.shape[-2:] != x.shape[-2:]: mod = F.interpolate(mod, size=x.shape[-2:], mode="bilinear", align_corners=False) shift, scale, gate = mod.chunk(3, dim=1) h = self.norm(self.dwconv(x)) * (1 + scale) + shift h = self.pw2(self.grn(self.act(self.pw1(h)))) return x + gate * h
class CoordIn(nn.Module): def __init__(self, ch: int, res_channel: bool = False): super().__init__() self.res_channel = res_channel self.proj = zero_last(nn.Conv2d(N_COORD + int(res_channel), ch, 1))
def forward(self, x, r: float = 0.0): c = raw_coords(x.shape[-2], x.shape[-1], x.device, x.dtype) if self.res_channel: c = torch.cat([c, torch.full_like(c[:, :1], float(r))], 1) return x + self.proj(c)
class PlanUp(nn.Module): def __init__(self, dim: int, rank: int = 32, kernel: int = 5, latent_ch: int = 4): super().__init__() self.dw = nn.Conv2d(dim, dim, kernel, padding=kernel // 2, groups=dim) self.dw2 = nn.Conv2d(dim, dim, kernel, padding=kernel // 2, groups=dim) self.down = nn.Conv2d(dim, rank, 1) self.coord = nn.Conv2d(N_COORD, rank, 1) self.guide = nn.Conv2d(latent_ch, rank, 3, padding=1) self.up = zero_last(nn.Conv2d(rank, dim, 1))
def forward(self, m, z): size = z.shape[-2:] b = F.interpolate(m, size=size, mode="bilinear", align_corners=False) h = (self.down(self.dw2(F.gelu(self.dw(b)))) + self.coord(raw_coords(*size, m.device, b.dtype)) + self.guide(z.to(b.dtype))) return b + self.up(F.gelu(h))
def count_features(n: torch.Tensor) -> torch.Tensor: nf = n.float() th = math.pi * torch.log2(nf.clamp(1, 16)) / 4 parts = [w * f(k * th) for k, w in zip(COUNT_K, COUNT_W) for f in (torch.cos, torch.sin)] parts += [torch.log2(nf.clamp(min=1)) / 4, (nf > 16).float()] return torch.stack(parts, -1)
class CountCode(nn.Module): def __init__(self, ctx_dim: int): super().__init__() self.proj = nn.Linear(10, ctx_dim) self.gate = nn.Parameter(torch.zeros(ctx_dim))
def forward(self, ctx, counts=None): if counts is None: return ctx counts = counts.to(ctx.device) on = (counts > 0).to(ctx.dtype)[..., None] code = self.proj(count_features(counts).to(ctx.dtype)) return ctx + on * self.gate.to(ctx.dtype) * (code - ctx)
class MicaThinker(nn.Module): def __init__(self, cfg: MicaConfig): super().__init__() self.grid, self.n_global, self.n_freq, self.rope = cfg.grid, cfg.n_global, cfg.n_freq, cfg.rope self.loops = cfg.loops self.native = 2 * cfg.grid self.head_dim = cfg.head_dim pos = 4 * cfg.n_freq self.queries = nn.Parameter(torch.randn(cfg.grid * cfg.grid + cfg.n_global, cfg.p_dim) * 0.02) self.q_pos = nn.Linear(pos, cfg.p_dim) self.t1 = TimestepEmbedder(cfg.p_dim) self.t2 = TimestepEmbedder(cfg.dim) self.in_latent = nn.Linear(cfg.latent_ch * 4 + pos, cfg.p_dim) self.perceiver = nn.ModuleList( XBlock2(cfg.p_dim, cfg.p_dim, self_attn=False, head_dim=cfg.head_dim) for _ in range(cfg.perceiver_depth) ) self.lift = nn.Linear(cfg.p_dim, cfg.dim) self.prelude = nn.ModuleList( XBlock2(cfg.dim, cfg.ctx_dim, head_dim=cfg.head_dim) for _ in range(cfg.prelude) ) self.core = nn.ModuleList( XBlock2(cfg.dim, cfg.ctx_dim, head_dim=cfg.head_dim) for _ in range(cfg.core) ) self.coda = nn.ModuleList( XBlock2(cfg.dim, cfg.ctx_dim, head_dim=cfg.head_dim) for _ in range(cfg.coda) ) self.adapter = nn.Linear(2 * cfg.dim, cfg.dim) self.norm = nn.LayerNorm(cfg.dim) self.mr_taps = zero_last(nn.Linear(cfg.latent_ch * 16, cfg.p_dim)) self.mr_read = ConvRead(cfg.latent_ch, cfg.p_dim, cond_dim=cfg.p_dim, ch=cfg.read_ch, depth=cfg.read_depth) self.mr_res_q = ResEmbed(cfg.p_dim) self.mr_res_s = ResEmbed(cfg.dim) self.mr_res_c = ResEmbed(cfg.p_dim, zero_init=False)
def read(self, z, t_emb, r): B = z.shape[0] zb = subsample(z, self.native) hb, wb = zb.shape[-2:] pos = fourier_coords(hb // 2, wb // 2, self.n_freq, z.device)[None].expand(B, -1, -1) lat = F.pixel_unshuffle(zb, 2).flatten(2).transpose(1, 2) kv = self.in_latent(torch.cat([lat, pos], -1)) coords = raw_coords(*z.shape[-2:], z.device) if z.shape[-1] == 2 * self.native: z_hr, c_hr = z, coords else: z_hr = F.interpolate(z, scale_factor=2, mode="nearest") c_hr = F.interpolate(coords, scale_factor=2, mode="nearest") taps = F.pixel_unshuffle(z_hr, 4).flatten(2).transpose(1, 2) cond = t_emb + self.mr_res_c(r) return kv + self.mr_taps(taps) + self.mr_read(z_hr, c_hr, cond, (hb // 2, wb // 2)), (hb, wb)
def forward(self, z, t, ctx, mask, loops: int | None = None, mask_all: bool = False): B = z.shape[0] g, dev = self.grid, z.device loops = self.loops if loops is None else loops r = res_scale(z, self.native) t1 = self.t1(t) kv, (hb, wb) = self.read(z, t1, r) q = self.queries[None].expand(B, -1, -1).clone() q[:, :g * g] = q[:, :g * g] + self.q_pos(fourier_coords(g, g, self.n_freq, dev)[None].expand(B, -1, -1)) q = q + t1[:, None] + self.mr_res_q(r)[:, None] ang_pq = ang_pk = ang_q = None if self.rope: ang_pq = rope_angles(grid_xy(g, g, dev), self.head_dim, self.n_global) ang_pk = rope_angles(grid_xy(hb // 2, wb // 2, dev), self.head_dim) ang_q = ang_pq for blk in self.perceiver: q = blk(q, kv, None, ang_pq, ang_pk) q = self.lift(q) + self.t2(t)[:, None] + self.mr_res_s(r)[:, None] pad = None if mask_all else ~mask.bool() for blk in self.prelude: q = blk(q, ctx, pad, ang_q) e, s = q, q for _ in range(loops): s = self.adapter(torch.cat([s, e], -1)) for blk in self.core: s = blk(s, ctx, pad, ang_q) for blk in self.coda: s = blk(s, ctx, pad, ang_q) out = self.norm(s) return out[:, :g * g].transpose(1, 2).reshape(B, -1, g, g)
class MicaGenerator(nn.Module): def __init__(self, cfg: MicaConfig | None = None): super().__init__() cfg = cfg or MicaConfig() self.cfg = cfg self.native = 2 * cfg.grid self.loops = cfg.loops self.thinker = MicaThinker(cfg) self.mr_count = CountCode(cfg.ctx_dim)
w0, w1, w2 = cfg.widths d0, d1, d2 = cfg.depths sr = cfg.steer_rank self.steer_in = nn.ModuleDict({ lvl: nn.Conv2d(cfg.dim, r, 1) for lvl, r in zip(("l0", "l1", "l2"), sr) if r }) d_in = [r or cfg.dim for r in sr] self.stem = nn.Conv2d(cfg.latent_ch, w0, 3, padding=1) mk = lambda w, dm, n: nn.ModuleList(SpatialModBlock(w, dm, cfg.expansion) for _ in range(n)) self.enc0 = mk(w0, d_in[0], d0) self.enc1 = mk(w1, d_in[1], d1) self.mid = mk(w2, d_in[2], 2 * d2) self.dec1 = mk(w1, d_in[1], d1) self.dec0 = mk(w0, d_in[0], d0) self.down0 = nn.Sequential(LayerNorm2d(w0), nn.Conv2d(w0, w1, 2, stride=2)) self.down1 = nn.Sequential(LayerNorm2d(w1), nn.Conv2d(w1, w2, 2, stride=2)) self.up1 = nn.ConvTranspose2d(w2, w1, 2, stride=2) self.up0 = nn.ConvTranspose2d(w1, w0, 2, stride=2) self.final_norm = LayerNorm2d(w0, affine=False) self.final_mod = nn.Conv2d(cfg.dim, 2 * w0, 1) self.final_conv = nn.Conv2d(w0, cfg.latent_ch, 3, padding=1) self.plan_up = PlanUp(cfg.dim, cfg.up_rank, 5, cfg.latent_ch) self.coord = nn.ModuleDict({ k: CoordIn(w, cfg.coord_res) for k, w in (("enc0", w0), ("enc1", w1), ("mid", w2), ("dec1", w1), ("dec0", w0)) })
def _run(self, blocks, x, s): for blk in blocks: x = blk(x, s) return x
def _steer(self, lvl, m, x, m_up=None): if m_up is not None and m_up.shape[-2:] == x.shape[-2:]: m = m_up s = self.steer_in[lvl](m) if lvl in self.steer_in else m if s.shape[-1] > x.shape[-1]: return F.adaptive_avg_pool2d(s, x.shape[-2:]) if s.shape[-1] < x.shape[-1]: return F.interpolate(s, size=x.shape[-2:], mode="bilinear", align_corners=False) return s
def forward(self, z, t, ctx, mask, loops: int | None = None, counts=None, mask_all: bool = False): ctx = self.mr_count(ctx.float(), counts) m = self.thinker(z, t, ctx, mask, self.loops if loops is None else loops, mask_all=mask_all) r = math.log2(z.shape[-1] / self.native) m_up = self.plan_up(m, z) if m.shape[-1] < z.shape[-1] else None h = self.stem(z) c = self.coord x0 = self._run(self.enc0, c["enc0"](h, r), self._steer("l0", m, h, m_up)) x = self.down0(x0) x1 = self._run(self.enc1, c["enc1"](x, r), self._steer("l1", m, x, m_up)) x = self.down1(x1) x = self._run(self.mid, c["mid"](x, r), self._steer("l2", m, x, m_up)) x = self.up1(x) + x1 x = self._run(self.dec1, c["dec1"](x, r), self._steer("l1", m, x, m_up)) x = self.up0(x) + x0 feat = self._run(self.dec0, c["dec0"](x, r), self._steer("l0", m, x, m_up)) fm = self.final_mod(m_up if m_up is not None else m) if fm.shape[-2:] != feat.shape[-2:]: fm = F.interpolate(fm, size=feat.shape[-2:], mode="bilinear", align_corners=False) shift, scale = fm.chunk(2, dim=1) return self.final_conv(self.final_norm(feat) * (1 + scale) + shift)
class DistillT5TextEncoder: """LifuWang/DistillT5 (with explicit key remap) + google-t5/t5-base tokenizer + Mica ctx_proj."""
def __init__(self, device: str = "cuda", max_len: int = 512): self.device = device self.max_len = max_len self.tokenizer = None self.encoder = None self.final_projection = None self.ctx_proj = nn.Linear(DISTILLT5_OUT_DIM, MICA_CTX_DIM)
def load(self): from huggingface_hub import hf_hub_download from safetensors import safe_open from transformers import AutoTokenizer, T5EncoderModel
self.tokenizer = AutoTokenizer.from_pretrained(DISTILLT5_TOKENIZER_REPO) self.encoder = T5EncoderModel.from_pretrained(DISTILLT5_REPO, dtype=torch.float32).to(self.device) path = hf_hub_download(DISTILLT5_REPO, "model.safetensors") mapped = {} with safe_open(path, framework="pt") as f: for k in f.keys(): if k.startswith("encoder.encoder."): mapped[k[len("encoder."):]] = f.get_tensor(k) elif k == "encoder.shared.weight": mapped["shared.weight"] = f.get_tensor(k) mapped["encoder.embed_tokens.weight"] = f.get_tensor(k) missing, unexpected = self.encoder.load_state_dict(mapped, strict=False) if missing or unexpected: raise RuntimeError(f"DistillT5 remap incomplete: missing={missing} unexpected={unexpected}")
self.final_projection = nn.Sequential( nn.Linear(DISTILLT5_D_MODEL, DISTILLT5_OUT_DIM, bias=False), nn.ReLU(), nn.Dropout(0.1), nn.Linear(DISTILLT5_OUT_DIM, DISTILLT5_OUT_DIM, bias=False), ) with safe_open(path, framework="pt") as f: self.final_projection[0].weight.data.copy_(f.get_tensor("final_projection.0.weight")) self.final_projection[3].weight.data.copy_(f.get_tensor("final_projection.3.weight"))
self.final_projection = self.final_projection.to(self.device).eval() self.ctx_proj = self.ctx_proj.to(self.device).eval() self.encoder.eval() return self
@torch.no_grad() def encode_texts(self, texts: list[str]): t = self.tokenizer(texts, padding="longest", truncation=True, max_length=self.max_len, return_tensors="pt") ids, mask = t["input_ids"].to(self.device), t["attention_mask"].to(self.device) with torch.autocast(self.device, dtype=torch.bfloat16, enabled=self.device == "cuda"): hidden = self.encoder(input_ids=ids, attention_mask=mask).last_hidden_state hidden = self.final_projection(hidden) hidden = self.ctx_proj(hidden) return hidden.float(), mask
def shift_t(t: float, shift: float) -> float: if shift == 1.0: return t s = 1.0 - t return 1.0 - shift * s / (1.0 + (shift - 1.0) * s)
@torch.no_grad()def sample_mica(model: MicaGenerator, text_enc: DistillT5TextEncoder, vae, prompts: list[str], steps: int = 50, cfg: float = 4.0, shift: float = 2.0, resolution: int = 768, seed: int = 42, device: str = "cuda"): """Euler flow-matching sampler from t=0 (noise) -> t=1 (data) with CFG.""" from PIL import Image import numpy as np
B = len(prompts) H = W = resolution // 8 gen = torch.Generator(device=device).manual_seed(seed) z = torch.randn((B, 4, H, W), generator=gen, device=device, dtype=torch.float32)
ctx_c, mask_c = text_enc.encode_texts(prompts) ctx_u, mask_u = text_enc.encode_texts([""] * B) # Pad cond & uncond to same length for single batched CFG pass L = max(ctx_c.shape[1], ctx_u.shape[1]) if ctx_c.shape[1] < L: ctx_c = F.pad(ctx_c, (0, 0, 0, L - ctx_c.shape[1])) mask_c = F.pad(mask_c, (0, L - mask_c.shape[1])) if ctx_u.shape[1] < L: ctx_u = F.pad(ctx_u, (0, 0, 0, L - ctx_u.shape[1])) mask_u = F.pad(mask_u, (0, L - mask_u.shape[1])) ctx_both = torch.cat([ctx_u, ctx_c], dim=0) mask_both = torch.cat([mask_u, mask_c], dim=0)
ts = [shift_t(i / steps, shift) for i in range(steps + 1)] for i in range(steps): t_cur, t_nxt = ts[i], ts[i + 1] dt = t_nxt - t_cur t_vec = torch.full((2 * B,), t_cur, device=device, dtype=torch.float32) z_in = torch.cat([z, z], dim=0) with torch.autocast(device, dtype=torch.bfloat16, enabled=device == "cuda"): v_both = model(z_in, t_vec, ctx_both, mask_both) vu, vc = v_both.float().chunk(2, dim=0) v = vu + cfg * (vc - vu) z = z + dt * v
images = [] for b in range(B): lat = (z[b:b + 1] / VAE_SCALE).to(dtype=vae.dtype) img = vae.decode(lat).sample.float().clamp(-1, 1) arr = ((img[0].permute(1, 2, 0).cpu().numpy() + 1.0) * 127.5).round().clip(0, 255).astype(np.uint8) images.append(Image.fromarray(arr)) return images.gitattributes+11
README.mdAdded+103
config.jsonAdded+51
ctx_proj.safetensorsAdded+3
gallery/01_alpine_sunrise.pngAdded

Large File Pointer Details
- SHA256: 4517a668507aefff00309805fd4a497a25ff6e3133cff02df53de78184778dc6
- Pointer size: 131 Bytes
- Size of remote file: 985 kB
gallery/02_iceland_aurora.pngAdded

Large File Pointer Details
- SHA256: 71ab0552ea3b3f19d72232ad637b86bfe2be6efadff9a92eed0c2ec206e96327
- Pointer size: 131 Bytes
- Size of remote file: 517 kB
gallery/03_kyoto_autumn.pngAdded

Large File Pointer Details
- SHA256: b77a4557b01906fc76002b909425b0ef634f52785c20752df49a9c2622f97670
- Pointer size: 132 Bytes
- Size of remote file: 1.26 MB
gallery/04_redwood_mist.pngAdded

Large File Pointer Details
- SHA256: 5b62782c2a7ca465943792dea1227af5caa3648e9f9e38ca745b0d55ac408898
- Pointer size: 132 Bytes
- Size of remote file: 1.27 MB
gallery/05_sahara_dunes.pngAdded

Large File Pointer Details
- SHA256: bc9917c3adcc7e254db7e7a4718d5ed1c029b584890ebce8612defb673d63b4e
- Pointer size: 131 Bytes
- Size of remote file: 630 kB
gallery/06_amalfi_coast.pngAdded

Large File Pointer Details
- SHA256: 3f217442f0fd4850db454999f57deb9f4002f0923bf34393e5f496ea8093808d
- Pointer size: 132 Bytes
- Size of remote file: 1.06 MB
gallery/07_scottish_highlands.pngAdded

Large File Pointer Details
- SHA256: 9b731054a0f88ce51203cd6db5b1311c23e81ccae4e54df4781683b1794fd327
- Pointer size: 131 Bytes
- Size of remote file: 884 kB
gallery/08_patagonia_lake.pngAdded

Large File Pointer Details
- SHA256: 8c3b04fdcd235052e9fca6ed191bd7d449f18618d9bbb22978dbfd7ba37f0f9e
- Pointer size: 131 Bytes
- Size of remote file: 904 kB
gallery/09_canyon_river.pngAdded

Large File Pointer Details
- SHA256: 74bcd992b423d2934a32745f1b91fac85f36e510ee562abe0b9bbf3e4fd0027e
- Pointer size: 131 Bytes
- Size of remote file: 871 kB
gallery/10_lavender_provence.pngAdded

Large File Pointer Details
- SHA256: deec0b32a2f77cbb3101f54395bf7227b5de2961cac2fda3f99bb936426ec5e4
- Pointer size: 131 Bytes
- Size of remote file: 849 kB
gallery/gallery_grid.jpgAdded

Large File Pointer Details
- SHA256: 831b7ff79854de0fff7348a62ce694d94c612ed85b8b72ee937ab06c554472da
- Pointer size: 131 Bytes
- Size of remote file: 403 kB
generator.safetensorsAdded+3
mica_modeling.pyAdded+599