FrameXlabs commited on
Commit
40f6499
·
verified ·
1 Parent(s): 21b8201

Add trout/config.py

Browse files
Files changed (1) hide show
  1. trout/config.py +163 -0
trout/config.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trout configuration dataclasses.
2
+
3
+ Trout is a from-scratch reimplementation of the same *kind* of model as
4
+ tessera-small: a joint text+pixel bidirectional masked-diffusion transformer
5
+ for 16x16 palette pixel art. The "small" size preset matches the reference
6
+ model's parameter count (~47.6M trainable weights, frozen CLIP excluded).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import dataclasses
12
+ from dataclasses import asdict, dataclass, field
13
+ from typing import Any, Dict, List, Optional
14
+
15
+
16
+ @dataclass
17
+ class TroutConfig:
18
+ """Architecture hyper-parameters of the Trout denoiser."""
19
+
20
+ vocab_size: int = 512 # palette entries incl. transparent (index 0); MASK id == vocab_size
21
+ grid_size: int = 16 # the image is grid_size x grid_size pixel tokens
22
+ dim: int = 512 # residual stream width
23
+ n_heads: int = 8 # attention heads
24
+ depth_in: int = 2 # pixel-level blocks before the 2x2 merge
25
+ depth_core: int = 8 # patch-level blocks on the merged (grid/patch)^2 tokens
26
+ depth_out: int = 2 # pixel-level blocks after the unmerge
27
+ patch: int = 2 # hourglass merge factor (1 = flat model)
28
+ mlp_ratio: float = 3.0 # Conv-SwiGLU hidden width (rounded up to a multiple of 64)
29
+ n_registers: int = 4 # learnable register tokens at the front of the prefix
30
+ text_dim: int = 512 # hidden size of the frozen text encoder
31
+ text_len: int = 24 # number of text tokens fed to the denoiser
32
+ rope_theta: float = 100.0 # base of the 2D axial RoPE frequencies
33
+ conv_ffn: bool = True # depthwise 3x3 conv on the gate branch of image tokens
34
+ color_freqs: int = 6 # Fourier frequencies for the OKLab color features
35
+ self_cond: bool = True # feed the previous step's predicted distribution back in
36
+
37
+ @property
38
+ def mask_id(self) -> int:
39
+ return self.vocab_size
40
+
41
+ @property
42
+ def num_tokens(self) -> int:
43
+ return self.grid_size * self.grid_size
44
+
45
+ @property
46
+ def hourglass(self) -> bool:
47
+ return self.patch > 1 and self.depth_core > 0
48
+
49
+ @property
50
+ def head_dim(self) -> int:
51
+ return self.dim // self.n_heads
52
+
53
+ @property
54
+ def mlp_hidden(self) -> int:
55
+ h = int(self.dim * self.mlp_ratio)
56
+ return max(64, (h + 63) // 64 * 64)
57
+
58
+ def validate(self) -> None:
59
+ assert self.dim % self.n_heads == 0
60
+ assert self.head_dim % 4 == 0, "head_dim must be a multiple of 4 for 2D axial RoPE"
61
+ if self.hourglass:
62
+ assert self.grid_size % self.patch == 0
63
+
64
+ def to_dict(self) -> Dict[str, Any]:
65
+ return asdict(self)
66
+
67
+ @classmethod
68
+ def from_dict(cls, d: Dict[str, Any]) -> "TroutConfig":
69
+ names = {f.name for f in dataclasses.fields(cls)}
70
+ return cls(**{k: v for k, v in d.items() if k in names})
71
+
72
+
73
+ # Size presets. "small" = the same parameter count as tessera-small (~47.6M).
74
+ PRESETS: Dict[str, Dict[str, Any]] = {
75
+ "nano": dict(dim=256, n_heads=4, depth_in=1, depth_core=4, depth_out=1),
76
+ "tiny": dict(dim=384, n_heads=6, depth_in=2, depth_core=6, depth_out=2),
77
+ "small": dict(dim=512, n_heads=8, depth_in=2, depth_core=8, depth_out=2),
78
+ "base": dict(dim=768, n_heads=12, depth_in=3, depth_core=12, depth_out=3),
79
+ }
80
+
81
+
82
+ def config_from_preset(preset: str, **overrides: Any) -> TroutConfig:
83
+ if preset not in PRESETS:
84
+ raise ValueError(f"unknown preset {preset!r}; choose from {list(PRESETS)}")
85
+ kw = dict(PRESETS[preset])
86
+ kw.update(overrides)
87
+ cfg = TroutConfig(**kw)
88
+ cfg.validate()
89
+ return cfg
90
+
91
+
92
+ DEFAULT_PROMPTS: List[str] = [
93
+ "red health potion bottle",
94
+ "golden crown with blue gems",
95
+ "green slime monster",
96
+ "iron sword with a leather hilt",
97
+ "wooden treasure chest",
98
+ "pink cherry blossom tree",
99
+ "blue magic spellbook",
100
+ "orange fox head",
101
+ "glowing purple crystal",
102
+ "cheeseburger",
103
+ "skull with a candle",
104
+ "rocket ship",
105
+ "brown leather boots",
106
+ "yellow rubber duck",
107
+ "ice cream cone with strawberry scoop",
108
+ "black cat",
109
+ ]
110
+
111
+
112
+ @dataclass
113
+ class TrainConfig:
114
+ """Training hyper-parameters (CPU-tuned defaults; see the model card)."""
115
+
116
+ # data
117
+ data_dir: str = "/home/z/my-project/data/cache"
118
+ out_dir: str = "/home/z/my-project/runs/trout-small"
119
+
120
+ # model
121
+ preset: str = "small"
122
+ text_encoder: Optional[str] = None # None -> the one recorded in the data cache
123
+
124
+ # optimisation
125
+ batch_size: int = 16
126
+ grad_accum: int = 1
127
+ total_steps: int = 1000
128
+ lr: float = 4e-4
129
+ warmup_steps: int = 25
130
+ weight_decay: float = 0.05
131
+ beta1: float = 0.9
132
+ beta2: float = 0.95
133
+ grad_clip: float = 1.0
134
+ optimizer: str = "adamw" # CPU-friendly choice (reference used Muon+AdamW)
135
+ ema_decay: float = 0.99 # shortened for a short run
136
+
137
+ # masked diffusion
138
+ mask_schedule: str = "cosine" # "cosine" (MaskGIT) or "linear"
139
+ loss_weighting: str = "uniform" # mean over masked tokens
140
+ stratified_t: bool = True
141
+ smooth_mask_prob: float = 0.25 # fraction of samples with blob (spatially-correlated) masks
142
+ label_smoothing: float = 0.1 # perceptual (OKLab) label-smoothing weight
143
+ color_tau: float = 0.05
144
+ self_cond_prob: float = 0.25 # reduced from the reference's 0.5 to save CPU time
145
+ cond_drop_prob: float = 0.1 # classifier-free guidance dropout
146
+ subject_prob: float = 0.05 # use the short "subject" field instead of the caption
147
+ hflip_prob: float = 0.5 # horizontal flips (skipped for left/right captions)
148
+
149
+ # logging / eval / checkpoints
150
+ log_every: int = 5
151
+ eval_every: int = 50
152
+ ckpt_every: int = 25
153
+ sample_steps: int = 12
154
+ sample_cfg: float = 3.0
155
+ seed: int = 4242
156
+
157
+ def to_dict(self) -> Dict[str, Any]:
158
+ return asdict(self)
159
+
160
+ @classmethod
161
+ def from_dict(cls, d: Dict[str, Any]) -> "TrainConfig":
162
+ names = {f.name for f in dataclasses.fields(cls)}
163
+ return cls(**{k: v for k, v in d.items() if k in names})