Trout / trout /config.py
FrameXlabs's picture
Add trout/config.py
6f98a2e verified
Raw History Blame Contribute Delete
6.21 kB
"""Trout configuration dataclasses.
Trout is a from-scratch reimplementation of the same *kind* of model as
tessera-small: a joint text+pixel bidirectional masked-diffusion transformer
for 16x16 palette pixel art. The "small" size preset matches the reference
model's parameter count (~47.6M trainable weights, frozen CLIP excluded).
"""
from __future__ import annotations
import dataclasses
from dataclasses import asdict, dataclass, field
from typing import Any, Dict, List, Optional
@dataclass
class TroutConfig:
"""Architecture hyper-parameters of the Trout denoiser."""
vocab_size: int = 512 # palette entries incl. transparent (index 0); MASK id == vocab_size
grid_size: int = 16 # the image is grid_size x grid_size pixel tokens
dim: int = 512 # residual stream width
n_heads: int = 8 # attention heads
depth_in: int = 2 # pixel-level blocks before the 2x2 merge
depth_core: int = 8 # patch-level blocks on the 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 # Conv-SwiGLU hidden width (rounded up to a multiple of 64)
n_registers: int = 4 # learnable register tokens at the front of the prefix
text_dim: int = 512 # hidden size of the frozen text encoder
text_len: int = 24 # number of 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 of image tokens
color_freqs: int = 6 # Fourier frequencies for the OKLab color features
self_cond: bool = True # feed the previous step's predicted distribution back in
@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:
h = int(self.dim * self.mlp_ratio)
return max(64, (h + 63) // 64 * 64)
def validate(self) -> None:
assert self.dim % self.n_heads == 0
assert self.head_dim % 4 == 0, "head_dim must be a multiple of 4 for 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":
names = {f.name for f in dataclasses.fields(cls)}
return cls(**{k: v for k, v in d.items() if k in names})
# Size presets. "small" = the same parameter count as tessera-small (~47.6M).
PRESETS: Dict[str, Dict[str, Any]] = {
"nano": dict(dim=256, n_heads=4, depth_in=1, depth_core=4, depth_out=1),
"tiny": dict(dim=384, n_heads=6, depth_in=2, depth_core=6, depth_out=2),
"small": dict(dim=512, n_heads=8, depth_in=2, depth_core=8, depth_out=2),
"base": dict(dim=768, n_heads=12, depth_in=3, depth_core=12, depth_out=3),
}
def config_from_preset(preset: str, **overrides: Any) -> TroutConfig:
if preset not in PRESETS:
raise ValueError(f"unknown preset {preset!r}; choose from {list(PRESETS)}")
kw = dict(PRESETS[preset])
kw.update(overrides)
cfg = TroutConfig(**kw)
cfg.validate()
return cfg
DEFAULT_PROMPTS: List[str] = [
"red health potion bottle",
"golden crown with blue gems",
"green slime monster",
"iron sword with a leather hilt",
"wooden treasure chest",
"pink cherry blossom tree",
"blue magic spellbook",
"orange fox head",
"glowing purple crystal",
"cheeseburger",
"skull with a candle",
"rocket ship",
"brown leather boots",
"yellow rubber duck",
"ice cream cone with strawberry scoop",
"black cat",
]
@dataclass
class TrainConfig:
"""Training hyper-parameters (CPU-tuned defaults; see the model card)."""
# data
data_dir: str = "/home/z/my-project/data/cache"
out_dir: str = "/home/z/my-project/runs/trout-small"
# model
preset: str = "small"
text_encoder: Optional[str] = None # None -> the one recorded in the data cache
# optimisation
batch_size: int = 16
grad_accum: int = 1
total_steps: int = 1000
lr: float = 4e-4
warmup_steps: int = 25
weight_decay: float = 0.05
beta1: float = 0.9
beta2: float = 0.95
grad_clip: float = 1.0
optimizer: str = "adamw" # CPU-friendly choice (reference used Muon+AdamW)
ema_decay: float = 0.99 # shortened for a short run
# masked diffusion
mask_schedule: str = "cosine" # "cosine" (MaskGIT) or "linear"
loss_weighting: str = "uniform" # mean over masked tokens
stratified_t: bool = True
smooth_mask_prob: float = 0.25 # fraction of samples with blob (spatially-correlated) masks
label_smoothing: float = 0.1 # perceptual (OKLab) label-smoothing weight
color_tau: float = 0.05
self_cond_prob: float = 0.25 # reduced from the reference's 0.5 to save CPU time
cond_drop_prob: float = 0.1 # classifier-free guidance dropout
subject_prob: float = 0.05 # use the short "subject" field instead of the caption
hflip_prob: float = 0.5 # horizontal flips (skipped for left/right captions)
# logging / eval / checkpoints (loosened for the long CPU continuation run)
log_every: int = 5
eval_every: int = 100
ckpt_every: int = 50
sample_steps: int = 12
sample_cfg: float = 3.0
seed: int = 4242
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@classmethod
def from_dict(cls, d: Dict[str, Any]) -> "TrainConfig":
names = {f.name for f in dataclasses.fields(cls)}
return cls(**{k: v for k, v in d.items() if k in names})