AbstractPhil commited on
Commit
2f5bd86
·
verified ·
1 Parent(s): d0d1188

Create model_v4.py

Browse files
Files changed (1) hide show
  1. model_v4.py +1547 -0
model_v4.py ADDED
@@ -0,0 +1,1547 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ TinyFlux-Deep v4.1 with Dual Expert System
3
+
4
+ Integrates two complementary expert pathways:
5
+ - Lune: Trajectory guidance via vec modulation (global conditioning)
6
+ - Sol: Attention prior via temperature/spatial bias (structural guidance)
7
+
8
+ Key insight: Sol's geometric knowledge lives in its ATTENTION PATTERNS,
9
+ not its features. We extract attention statistics (locality, entropy, clustering)
10
+ and spatial importance maps to bias TinyFlux's weak 4-head attention.
11
+
12
+ This avoids the twin-tail paradox: V-pred (Sol) is fundamentally incompatible
13
+ with linear flow-matching (TinyFlux), so we don't inject features directly.
14
+ Instead, we translate Sol's structural understanding into attention biases.
15
+
16
+ Architecture:
17
+ - Lune ExpertPredictor: (t, clip) → expert_signal → ADD to vec
18
+ - Sol AttentionPrior: (t, clip) → temperature, spatial_mod → BIAS attention
19
+ - David-inspired gate: 70% geometric (timestep), 30% learned (content)
20
+
21
+ Based on TinyFlux-Deep: 15 double + 25 single blocks.
22
+ """
23
+
24
+ __version__ = "4.1.0"
25
+
26
+ import torch
27
+ import torch.nn as nn
28
+ import torch.nn.functional as F
29
+ import math
30
+ import json
31
+ from dataclasses import dataclass, asdict
32
+ from typing import Optional, Tuple, Dict, List, Union
33
+ from pathlib import Path
34
+
35
+
36
+ # =============================================================================
37
+ # Configuration
38
+ # =============================================================================
39
+
40
+ @dataclass
41
+ class TinyFluxConfig:
42
+ """
43
+ Configuration for TinyFlux-Deep v4.1 model.
44
+
45
+ This config fully defines the model architecture and can be used to:
46
+ 1. Initialize a new model
47
+ 2. Convert checkpoints between versions
48
+ 3. Validate checkpoint compatibility
49
+
50
+ All dimension constraints are validated on creation.
51
+ """
52
+
53
+ # Core architecture
54
+ hidden_size: int = 512
55
+ num_attention_heads: int = 4
56
+ attention_head_dim: int = 128
57
+
58
+ in_channels: int = 16
59
+ patch_size: int = 1
60
+
61
+ joint_attention_dim: int = 768 # T5 sequence dim
62
+ pooled_projection_dim: int = 768 # CLIP pooled dim
63
+
64
+ num_double_layers: int = 15
65
+ num_single_layers: int = 25
66
+
67
+ mlp_ratio: float = 4.0
68
+ axes_dims_rope: Tuple[int, int, int] = (16, 56, 56)
69
+
70
+ # Lune expert predictor config (trajectory guidance)
71
+ use_lune_expert: bool = True
72
+ lune_expert_dim: int = 1280 # SD1.5 mid-block dimension
73
+ lune_hidden_dim: int = 512
74
+ lune_dropout: float = 0.1
75
+
76
+ # Sol attention prior config (structural guidance)
77
+ use_sol_prior: bool = True
78
+ sol_spatial_size: int = 8 # Sol's feature map resolution
79
+ sol_hidden_dim: int = 256
80
+ sol_geometric_weight: float = 0.7 # David's 70/30 split
81
+
82
+ # T5 enhancement config
83
+ use_t5_vec: bool = True # Add T5 pooled to vec pathway
84
+ t5_pool_mode: str = "attention" # "attention", "mean", "cls"
85
+
86
+ # Loss config
87
+ lune_distill_mode: str = "cosine" # "hard", "soft", "cosine", "huber"
88
+ use_huber_loss: bool = True
89
+ huber_delta: float = 0.1
90
+
91
+ # Legacy (for backward compat)
92
+ use_expert_predictor: bool = True # Maps to use_lune_expert
93
+ expert_dim: int = 1280
94
+ expert_hidden_dim: int = 512
95
+ expert_dropout: float = 0.1
96
+ guidance_embeds: bool = False
97
+
98
+ def __post_init__(self):
99
+ """Validate configuration constraints."""
100
+ # Validate attention dimensions
101
+ expected_hidden = self.num_attention_heads * self.attention_head_dim
102
+ if self.hidden_size != expected_hidden:
103
+ raise ValueError(
104
+ f"hidden_size ({self.hidden_size}) must equal "
105
+ f"num_attention_heads * attention_head_dim ({expected_hidden})"
106
+ )
107
+
108
+ # Validate RoPE dimensions
109
+ if isinstance(self.axes_dims_rope, list):
110
+ self.axes_dims_rope = tuple(self.axes_dims_rope)
111
+
112
+ rope_sum = sum(self.axes_dims_rope)
113
+ if rope_sum != self.attention_head_dim:
114
+ raise ValueError(
115
+ f"sum(axes_dims_rope) ({rope_sum}) must equal "
116
+ f"attention_head_dim ({self.attention_head_dim})"
117
+ )
118
+
119
+ # Validate sol_geometric_weight
120
+ if not 0.0 <= self.sol_geometric_weight <= 1.0:
121
+ raise ValueError(f"sol_geometric_weight must be in [0, 1], got {self.sol_geometric_weight}")
122
+
123
+ # Legacy mapping
124
+ if self.use_expert_predictor and not self.use_lune_expert:
125
+ self.use_lune_expert = True
126
+ self.lune_expert_dim = self.expert_dim
127
+ self.lune_hidden_dim = self.expert_hidden_dim
128
+ self.lune_dropout = self.expert_dropout
129
+
130
+ def to_dict(self) -> Dict:
131
+ """Convert to JSON-serializable dict."""
132
+ d = asdict(self)
133
+ d["axes_dims_rope"] = list(d["axes_dims_rope"])
134
+ return d
135
+
136
+ @classmethod
137
+ def from_dict(cls, d: Dict) -> "TinyFluxConfig":
138
+ """Create from dict, ignoring unknown keys."""
139
+ known_fields = {f.name for f in cls.__dataclass_fields__.values()}
140
+ filtered = {k: v for k, v in d.items() if k in known_fields and not k.startswith("_")}
141
+ return cls(**filtered)
142
+
143
+ @classmethod
144
+ def from_json(cls, path: Union[str, Path]) -> "TinyFluxConfig":
145
+ """Load config from JSON file."""
146
+ with open(path) as f:
147
+ d = json.load(f)
148
+ return cls.from_dict(d)
149
+
150
+ def save_json(self, path: Union[str, Path], metadata: Optional[Dict] = None):
151
+ """Save config to JSON file with optional metadata."""
152
+ d = self.to_dict()
153
+ if metadata:
154
+ d["_metadata"] = metadata
155
+ with open(path, "w") as f:
156
+ json.dump(d, f, indent=2)
157
+
158
+ def validate_checkpoint(self, state_dict: Dict[str, torch.Tensor]) -> List[str]:
159
+ """
160
+ Validate that a checkpoint matches this config.
161
+
162
+ Returns list of warnings (empty if perfect match).
163
+ """
164
+ warnings = []
165
+
166
+ # Check double block count
167
+ max_double = 0
168
+ for key in state_dict:
169
+ if key.startswith("double_blocks."):
170
+ idx = int(key.split(".")[1])
171
+ max_double = max(max_double, idx + 1)
172
+ if max_double != self.num_double_layers:
173
+ warnings.append(f"double_blocks: checkpoint has {max_double}, config expects {self.num_double_layers}")
174
+
175
+ # Check single block count
176
+ max_single = 0
177
+ for key in state_dict:
178
+ if key.startswith("single_blocks."):
179
+ idx = int(key.split(".")[1])
180
+ max_single = max(max_single, idx + 1)
181
+ if max_single != self.num_single_layers:
182
+ warnings.append(f"single_blocks: checkpoint has {max_single}, config expects {self.num_single_layers}")
183
+
184
+ # Check hidden size from a known weight
185
+ if "img_in.weight" in state_dict:
186
+ w = state_dict["img_in.weight"]
187
+ if w.shape[0] != self.hidden_size:
188
+ warnings.append(f"hidden_size: checkpoint has {w.shape[0]}, config expects {self.hidden_size}")
189
+
190
+ # Check for v4.1 components
191
+ has_sol = any(k.startswith("sol_prior.") for k in state_dict)
192
+ has_t5 = any(k.startswith("t5_pool.") for k in state_dict)
193
+ has_lune = any(k.startswith("lune_predictor.") for k in state_dict)
194
+
195
+ if self.use_sol_prior and not has_sol:
196
+ warnings.append("config expects sol_prior but checkpoint missing it")
197
+ if self.use_t5_vec and not has_t5:
198
+ warnings.append("config expects t5_pool but checkpoint missing it")
199
+ if self.use_lune_expert and not has_lune:
200
+ warnings.append("config expects lune_predictor but checkpoint missing it")
201
+
202
+ return warnings
203
+
204
+
205
+ # Backwards compatibility alias
206
+ TinyFluxDeepConfig = TinyFluxConfig
207
+
208
+
209
+ # =============================================================================
210
+ # Normalization
211
+ # =============================================================================
212
+
213
+ class RMSNorm(nn.Module):
214
+ """Root Mean Square Layer Normalization."""
215
+
216
+ def __init__(self, dim: int, eps: float = 1e-6, elementwise_affine: bool = True):
217
+ super().__init__()
218
+ self.eps = eps
219
+ self.elementwise_affine = elementwise_affine
220
+ if elementwise_affine:
221
+ self.weight = nn.Parameter(torch.ones(dim))
222
+ else:
223
+ self.register_parameter('weight', None)
224
+
225
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
226
+ norm = x.float().pow(2).mean(-1, keepdim=True).add(self.eps).rsqrt()
227
+ out = (x * norm).type_as(x)
228
+ if self.weight is not None:
229
+ out = out * self.weight
230
+ return out
231
+
232
+
233
+ # =============================================================================
234
+ # RoPE - Cached frequency buffers
235
+ # =============================================================================
236
+
237
+ class EmbedND(nn.Module):
238
+ """Original TinyFlux RoPE with cached frequency buffers."""
239
+
240
+ def __init__(self, theta: float = 10000.0, axes_dim: Tuple[int, int, int] = (16, 56, 56)):
241
+ super().__init__()
242
+ self.theta = theta
243
+ self.axes_dim = axes_dim
244
+
245
+ for i, dim in enumerate(axes_dim):
246
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim))
247
+ self.register_buffer(f'freqs_{i}', freqs, persistent=True)
248
+
249
+ def forward(self, ids: torch.Tensor) -> torch.Tensor:
250
+ device = ids.device
251
+ n_axes = ids.shape[-1]
252
+ emb_list = []
253
+
254
+ for i in range(n_axes):
255
+ freqs = getattr(self, f'freqs_{i}').to(device)
256
+ pos = ids[:, i].float()
257
+ angles = pos.unsqueeze(-1) * freqs.unsqueeze(0)
258
+ cos = angles.cos()
259
+ sin = angles.sin()
260
+ emb = torch.stack([cos, sin], dim=-1).flatten(-2)
261
+ emb_list.append(emb)
262
+
263
+ rope = torch.cat(emb_list, dim=-1)
264
+ return rope.unsqueeze(1)
265
+
266
+
267
+ def apply_rotary_emb_old(x: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor:
268
+ """Apply rotary embeddings (old interleaved format)."""
269
+ freqs = freqs_cis.squeeze(1)
270
+ cos = freqs[:, 0::2].repeat_interleave(2, dim=-1)
271
+ sin = freqs[:, 1::2].repeat_interleave(2, dim=-1)
272
+ cos = cos[None, None, :, :].to(x.device)
273
+ sin = sin[None, None, :, :].to(x.device)
274
+ x_real, x_imag = x.reshape(*x.shape[:-1], -1, 2).unbind(-1)
275
+ x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(-2)
276
+ return (x.float() * cos + x_rotated.float() * sin).to(x.dtype)
277
+
278
+
279
+ # =============================================================================
280
+ # Embeddings
281
+ # =============================================================================
282
+
283
+ class MLPEmbedder(nn.Module):
284
+ """MLP for embedding scalars (timestep)."""
285
+
286
+ def __init__(self, hidden_size: int):
287
+ super().__init__()
288
+ self.mlp = nn.Sequential(
289
+ nn.Linear(256, hidden_size),
290
+ nn.SiLU(),
291
+ nn.Linear(hidden_size, hidden_size),
292
+ )
293
+
294
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
295
+ half_dim = 128
296
+ emb = math.log(10000) / (half_dim - 1)
297
+ emb = torch.exp(torch.arange(half_dim, device=x.device, dtype=x.dtype) * -emb)
298
+ emb = x.unsqueeze(-1) * emb.unsqueeze(0)
299
+ emb = torch.cat([emb.sin(), emb.cos()], dim=-1)
300
+ return self.mlp(emb)
301
+
302
+
303
+ # =============================================================================
304
+ # Lune Expert Predictor (Trajectory Guidance → vec)
305
+ # =============================================================================
306
+
307
+ class LuneExpertPredictor(nn.Module):
308
+ """
309
+ Predicts Lune's trajectory features from (timestep_emb, CLIP_pooled).
310
+
311
+ Lune learned rich textures and detail via rectified flow.
312
+ Its mid-block features encode "how the denoising trajectory should flow."
313
+
314
+ Output: expert_signal added to vec (global conditioning).
315
+ """
316
+
317
+ def __init__(
318
+ self,
319
+ time_dim: int = 512,
320
+ clip_dim: int = 768,
321
+ expert_dim: int = 1280,
322
+ hidden_dim: int = 512,
323
+ output_dim: int = 512,
324
+ dropout: float = 0.1,
325
+ ):
326
+ super().__init__()
327
+
328
+ self.expert_dim = expert_dim
329
+ self.dropout = dropout
330
+
331
+ # Input fusion
332
+ self.input_proj = nn.Linear(time_dim + clip_dim, hidden_dim)
333
+
334
+ # Predictor core
335
+ self.predictor = nn.Sequential(
336
+ nn.SiLU(),
337
+ nn.Linear(hidden_dim, hidden_dim),
338
+ nn.SiLU(),
339
+ nn.Dropout(dropout),
340
+ nn.Linear(hidden_dim, hidden_dim),
341
+ nn.SiLU(),
342
+ nn.Linear(hidden_dim, expert_dim),
343
+ )
344
+
345
+ # Project to vec dimension
346
+ self.output_proj = nn.Sequential(
347
+ nn.LayerNorm(expert_dim),
348
+ nn.Linear(expert_dim, output_dim),
349
+ )
350
+
351
+ # Learnable gate - store in logit space so sigmoid gives 0.5 at init
352
+ self.expert_gate = nn.Parameter(torch.tensor(0.0)) # sigmoid(0) = 0.5
353
+
354
+ self._init_weights()
355
+
356
+ def _init_weights(self):
357
+ for m in self.modules():
358
+ if isinstance(m, nn.Linear):
359
+ nn.init.xavier_uniform_(m.weight, gain=0.5)
360
+ if m.bias is not None:
361
+ nn.init.zeros_(m.bias)
362
+
363
+ def forward(
364
+ self,
365
+ time_emb: torch.Tensor,
366
+ clip_pooled: torch.Tensor,
367
+ real_expert_features: Optional[torch.Tensor] = None,
368
+ ) -> Dict[str, torch.Tensor]:
369
+ """
370
+ Returns:
371
+ expert_signal: [B, output_dim] - add to vec
372
+ expert_pred: [B, expert_dim] - for distillation loss
373
+ """
374
+ combined = torch.cat([time_emb, clip_pooled], dim=-1)
375
+ hidden = self.input_proj(combined)
376
+ expert_pred = self.predictor(hidden)
377
+
378
+ if real_expert_features is not None:
379
+ expert_features = real_expert_features
380
+ expert_used = 'real'
381
+ else:
382
+ expert_features = expert_pred
383
+ expert_used = 'predicted'
384
+
385
+ gate = torch.sigmoid(self.expert_gate)
386
+ expert_signal = gate * self.output_proj(expert_features)
387
+
388
+ return {
389
+ 'expert_signal': expert_signal,
390
+ 'expert_pred': expert_pred,
391
+ 'expert_used': expert_used,
392
+ }
393
+
394
+
395
+ # =============================================================================
396
+ # Sol Attention Prior (Structural Guidance → Attention Bias)
397
+ # =============================================================================
398
+
399
+ class SolAttentionPrior(nn.Module):
400
+ """
401
+ Predicts Sol's attention behavior from (timestep_emb, CLIP_pooled).
402
+
403
+ Sol learned geometric structure via DDPM + David assessment.
404
+ Its value isn't in features, but in ATTENTION PATTERNS:
405
+ - locality: how local vs global is attention?
406
+ - entropy: how focused vs diffuse?
407
+ - clustering: how structured vs uniform?
408
+ - spatial_importance: WHERE does structure exist?
409
+
410
+ Output: Temperature scaling and Q/K modulation for TinyFlux attention.
411
+
412
+ Follows David's philosophy: 70% geometric routing (timestep-based),
413
+ 30% learned routing (content-based).
414
+ """
415
+
416
+ def __init__(
417
+ self,
418
+ time_dim: int = 512,
419
+ clip_dim: int = 768,
420
+ hidden_dim: int = 256,
421
+ num_heads: int = 4,
422
+ spatial_size: int = 8,
423
+ geometric_weight: float = 0.7,
424
+ ):
425
+ super().__init__()
426
+
427
+ self.num_heads = num_heads
428
+ self.spatial_size = spatial_size
429
+ self.geometric_weight = geometric_weight
430
+
431
+ # Statistics predictor: (t, clip) → [locality, entropy, clustering]
432
+ self.stat_predictor = nn.Sequential(
433
+ nn.Linear(time_dim + clip_dim, hidden_dim),
434
+ nn.SiLU(),
435
+ nn.Linear(hidden_dim, hidden_dim),
436
+ nn.SiLU(),
437
+ nn.Linear(hidden_dim, 3),
438
+ )
439
+
440
+ # Spatial importance predictor: (t, clip) → [H, W] importance map
441
+ self.spatial_predictor = nn.Sequential(
442
+ nn.Linear(time_dim + clip_dim, hidden_dim),
443
+ nn.SiLU(),
444
+ nn.Linear(hidden_dim, hidden_dim),
445
+ nn.SiLU(),
446
+ nn.Linear(hidden_dim, spatial_size * spatial_size),
447
+ )
448
+
449
+ # Convert statistics → per-head temperature
450
+ self.stat_to_temperature = nn.Sequential(
451
+ nn.Linear(3, hidden_dim // 2),
452
+ nn.SiLU(),
453
+ nn.Linear(hidden_dim // 2, num_heads),
454
+ nn.Softplus(), # Positive temperatures
455
+ )
456
+
457
+ # Convert spatial → Q/K modulation
458
+ # Zero-init: starts as identity (no modulation)
459
+ self.spatial_to_qk_scale = nn.Linear(1, num_heads)
460
+ nn.init.zeros_(self.spatial_to_qk_scale.weight)
461
+ nn.init.ones_(self.spatial_to_qk_scale.bias)
462
+
463
+ # Learnable blend between geometric and predicted
464
+ # Store in logit space so sigmoid(x) = geometric_weight at init
465
+ self.blend_gate = nn.Parameter(self._to_logit(geometric_weight))
466
+
467
+ self._init_weights()
468
+
469
+ @staticmethod
470
+ def _to_logit(p: float) -> torch.Tensor:
471
+ """Convert probability to logit for proper sigmoid init."""
472
+ p = max(1e-4, min(p, 1 - 1e-4))
473
+ return torch.tensor(math.log(p / (1 - p)))
474
+
475
+ def _init_weights(self):
476
+ for m in [self.stat_predictor, self.spatial_predictor, self.stat_to_temperature]:
477
+ for layer in m:
478
+ if isinstance(layer, nn.Linear):
479
+ nn.init.xavier_uniform_(layer.weight, gain=0.5)
480
+ if layer.bias is not None:
481
+ nn.init.zeros_(layer.bias)
482
+
483
+ def geometric_temperature(self, t_normalized: torch.Tensor) -> torch.Tensor:
484
+ """
485
+ Timestep-based temperature prior.
486
+
487
+ Early (high t): Higher temperature → softer, more global attention
488
+ Late (low t): Lower temperature → sharper, more local attention
489
+
490
+ This matches how denoising naturally progresses:
491
+ - Early: global structure decisions
492
+ - Late: local detail refinement
493
+ """
494
+ B = t_normalized.shape[0]
495
+
496
+ # Base temperature: 1.0 at t=0, 2.0 at t=1
497
+ base_temp = 1.0 + t_normalized # [B]
498
+
499
+ # Per-head variation (some heads more local, some more global)
500
+ head_bias = torch.linspace(-0.2, 0.2, self.num_heads, device=t_normalized.device)
501
+
502
+ # [B, num_heads]
503
+ temperatures = base_temp.unsqueeze(-1) + head_bias.unsqueeze(0)
504
+ return temperatures.clamp(min=0.5, max=3.0)
505
+
506
+ def geometric_spatial(self, t_normalized: torch.Tensor) -> torch.Tensor:
507
+ """
508
+ Timestep-based spatial prior.
509
+
510
+ Early (high t): Uniform importance (everything matters for structure)
511
+ Late (low t): Center-biased (details typically in center)
512
+
513
+ Returns: [B, H, W] spatial importance
514
+ """
515
+ B = t_normalized.shape[0]
516
+ H = W = self.spatial_size
517
+ device = t_normalized.device
518
+
519
+ # Create center-biased gaussian
520
+ y = torch.linspace(-1, 1, H, device=device)
521
+ x = torch.linspace(-1, 1, W, device=device)
522
+ yy, xx = torch.meshgrid(y, x, indexing='ij')
523
+ center_dist = (xx**2 + yy**2).sqrt()
524
+ center_bias = torch.exp(-center_dist * 2) # Gaussian centered
525
+
526
+ # Blend: high t → uniform, low t → center-biased
527
+ uniform = torch.ones(H, W, device=device)
528
+
529
+ # t as blend factor: high t (1.0) → uniform, low t (0.0) → center
530
+ blend = t_normalized.view(B, 1, 1)
531
+ spatial = blend * uniform + (1 - blend) * center_bias.unsqueeze(0)
532
+
533
+ return spatial
534
+
535
+ def forward(
536
+ self,
537
+ time_emb: torch.Tensor,
538
+ clip_pooled: torch.Tensor,
539
+ t_normalized: torch.Tensor,
540
+ real_stats: Optional[torch.Tensor] = None,
541
+ real_spatial: Optional[torch.Tensor] = None,
542
+ ) -> Dict[str, torch.Tensor]:
543
+ """
544
+ Args:
545
+ time_emb: [B, time_dim]
546
+ clip_pooled: [B, clip_dim]
547
+ t_normalized: [B] timestep in [0, 1]
548
+ real_stats: [B, 3] real Sol statistics (training)
549
+ real_spatial: [B, H, W] real Sol spatial importance (training)
550
+
551
+ Returns:
552
+ temperature: [B, num_heads] - attention temperature per head
553
+ spatial_mod: [B, num_heads, N] - Q/K modulation per position
554
+ pred_stats: [B, 3] - for distillation loss
555
+ pred_spatial: [B, H, W] - for distillation loss
556
+ """
557
+ B = time_emb.shape[0]
558
+ device = time_emb.device
559
+
560
+ combined = torch.cat([time_emb, clip_pooled], dim=-1)
561
+
562
+ # === Predict statistics ===
563
+ pred_stats = self.stat_predictor(combined) # [B, 3]
564
+
565
+ # === Predict spatial importance ===
566
+ pred_spatial = self.spatial_predictor(combined) # [B, 64]
567
+ pred_spatial = pred_spatial.view(B, self.spatial_size, self.spatial_size)
568
+ pred_spatial = torch.sigmoid(pred_spatial) # [0, 1] importance
569
+
570
+ # === Geometric priors ===
571
+ geo_temperature = self.geometric_temperature(t_normalized)
572
+ geo_spatial = self.geometric_spatial(t_normalized)
573
+
574
+ # === Learned components ===
575
+ # Use real values if provided (training), else predicted (inference)
576
+ stats = real_stats if real_stats is not None else pred_stats
577
+ spatial = real_spatial if real_spatial is not None else pred_spatial
578
+
579
+ learned_temperature = self.stat_to_temperature(stats) # [B, num_heads]
580
+
581
+ # === Blend geometric and learned (David's 70/30) ===
582
+ blend = torch.sigmoid(self.blend_gate) # Learnable, initialized to 0.7
583
+
584
+ temperature = blend * geo_temperature + (1 - blend) * learned_temperature
585
+
586
+ # For spatial: blend then convert to Q/K modulation
587
+ blended_spatial = blend * geo_spatial + (1 - blend) * spatial # [B, H, W]
588
+
589
+ return {
590
+ 'temperature': temperature, # [B, num_heads]
591
+ 'spatial_importance': blended_spatial, # [B, H, W] at sol resolution
592
+ 'pred_stats': pred_stats, # [B, 3] for distillation
593
+ 'pred_spatial': pred_spatial, # [B, H, W] for distillation
594
+ }
595
+
596
+
597
+ # =============================================================================
598
+ # AdaLayerNorm
599
+ # =============================================================================
600
+
601
+ class AdaLayerNormZero(nn.Module):
602
+ """AdaLN-Zero for double-stream blocks (6 params)."""
603
+
604
+ def __init__(self, hidden_size: int):
605
+ super().__init__()
606
+ self.silu = nn.SiLU()
607
+ self.linear = nn.Linear(hidden_size, 6 * hidden_size, bias=True)
608
+ self.norm = RMSNorm(hidden_size)
609
+
610
+ def forward(self, x: torch.Tensor, emb: torch.Tensor):
611
+ emb_out = self.linear(self.silu(emb))
612
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = emb_out.chunk(6, dim=-1)
613
+ x = self.norm(x) * (1 + scale_msa.unsqueeze(1)) + shift_msa.unsqueeze(1)
614
+ return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
615
+
616
+
617
+ class AdaLayerNormZeroSingle(nn.Module):
618
+ """AdaLN-Zero for single-stream blocks (3 params)."""
619
+
620
+ def __init__(self, hidden_size: int):
621
+ super().__init__()
622
+ self.silu = nn.SiLU()
623
+ self.linear = nn.Linear(hidden_size, 3 * hidden_size, bias=True)
624
+ self.norm = RMSNorm(hidden_size)
625
+
626
+ def forward(self, x: torch.Tensor, emb: torch.Tensor):
627
+ emb_out = self.linear(self.silu(emb))
628
+ shift, scale, gate = emb_out.chunk(3, dim=-1)
629
+ x = self.norm(x) * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
630
+ return x, gate
631
+
632
+
633
+ # =============================================================================
634
+ # Attention with Sol Prior Support
635
+ # =============================================================================
636
+
637
+ class Attention(nn.Module):
638
+ """
639
+ Multi-head attention with optional Sol attention prior.
640
+
641
+ Sol prior provides:
642
+ - temperature: per-head attention sharpness
643
+ - spatial_mod: per-position Q/K scaling
644
+ """
645
+
646
+ def __init__(
647
+ self,
648
+ hidden_size: int,
649
+ num_heads: int,
650
+ head_dim: int,
651
+ use_bias: bool = False,
652
+ sol_spatial_size: int = 8,
653
+ ):
654
+ super().__init__()
655
+ self.num_heads = num_heads
656
+ self.head_dim = head_dim
657
+ self.scale = head_dim ** -0.5
658
+ self.sol_spatial_size = sol_spatial_size
659
+
660
+ self.qkv = nn.Linear(hidden_size, 3 * num_heads * head_dim, bias=use_bias)
661
+ self.out_proj = nn.Linear(num_heads * head_dim, hidden_size, bias=use_bias)
662
+
663
+ # Sol spatial → per-head Q/K modulation
664
+ # Zero-init weight AND bias so exp(0)=1 at init (true identity)
665
+ self.spatial_to_mod = nn.Conv2d(1, num_heads, kernel_size=1, bias=True)
666
+ nn.init.zeros_(self.spatial_to_mod.weight)
667
+ nn.init.zeros_(self.spatial_to_mod.bias)
668
+
669
+ def forward(
670
+ self,
671
+ x: torch.Tensor,
672
+ rope: Optional[torch.Tensor] = None,
673
+ sol_temperature: Optional[torch.Tensor] = None,
674
+ sol_spatial: Optional[torch.Tensor] = None,
675
+ spatial_size: Optional[Tuple[int, int]] = None,
676
+ num_txt_tokens: int = 0,
677
+ ) -> torch.Tensor:
678
+ """
679
+ Args:
680
+ x: [B, N, hidden_size]
681
+ rope: RoPE embeddings
682
+ sol_temperature: [B, num_heads] - attention temperature per head
683
+ sol_spatial: [B, H_sol, W_sol] - spatial importance from Sol
684
+ spatial_size: (H, W) of the image tokens for upsampling sol_spatial
685
+ num_txt_tokens: number of text tokens at start of sequence (for single-stream)
686
+ """
687
+ B, N, _ = x.shape
688
+
689
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim)
690
+ q, k, v = qkv.permute(2, 0, 3, 1, 4) # [B, heads, N, head_dim]
691
+
692
+ if rope is not None:
693
+ q = apply_rotary_emb_old(q, rope)
694
+ k = apply_rotary_emb_old(k, rope)
695
+
696
+ # === Sol Spatial Modulation ===
697
+ if sol_spatial is not None and spatial_size is not None:
698
+ H, W = spatial_size
699
+ N_img = H * W
700
+
701
+ # Upsample Sol spatial to match image token resolution
702
+ sol_up = F.interpolate(
703
+ sol_spatial.unsqueeze(1), # [B, 1, H_sol, W_sol]
704
+ size=(H, W),
705
+ mode='bilinear',
706
+ align_corners=False,
707
+ ) # [B, 1, H, W]
708
+
709
+ # Convert to per-head modulation for IMAGE tokens only
710
+ img_mod = self.spatial_to_mod(sol_up) # [B, heads, H, W]
711
+ img_mod = img_mod.reshape(B, self.num_heads, N_img) # [B, heads, N_img]
712
+
713
+ # exp(0) = 1 at init (true identity), learns to scale up/down
714
+ img_mod = torch.exp(img_mod.clamp(-2, 2)) # Clamp for stability
715
+
716
+ # For single-stream: prepend ones for text tokens (no modulation)
717
+ if num_txt_tokens > 0:
718
+ txt_mod = torch.ones(B, self.num_heads, num_txt_tokens, device=x.device, dtype=img_mod.dtype)
719
+ mod = torch.cat([txt_mod, img_mod], dim=2) # [B, heads, N_txt + N_img]
720
+ else:
721
+ mod = img_mod
722
+
723
+ # Modulate Q and K (amplify at important positions)
724
+ q = q * mod.unsqueeze(-1) # [B, heads, N, head_dim]
725
+ k = k * mod.unsqueeze(-1)
726
+
727
+ # Compute attention scores
728
+ scores = torch.matmul(q, k.transpose(-2, -1)) * self.scale # [B, heads, N, N]
729
+
730
+ # === Sol Temperature Scaling ===
731
+ if sol_temperature is not None:
732
+ # temperature: [B, num_heads] → [B, heads, 1, 1]
733
+ temp = sol_temperature.unsqueeze(-1).unsqueeze(-1).clamp(min=0.1)
734
+ scores = scores / temp
735
+
736
+ attn = F.softmax(scores, dim=-1)
737
+ out = torch.matmul(attn, v)
738
+ out = out.transpose(1, 2).reshape(B, N, -1)
739
+
740
+ return self.out_proj(out)
741
+
742
+
743
+ class JointAttention(nn.Module):
744
+ """
745
+ Joint attention for double-stream blocks with Sol prior support.
746
+
747
+ Image tokens get Sol modulation, text tokens don't.
748
+ """
749
+
750
+ def __init__(
751
+ self,
752
+ hidden_size: int,
753
+ num_heads: int,
754
+ head_dim: int,
755
+ use_bias: bool = False,
756
+ sol_spatial_size: int = 8,
757
+ ):
758
+ super().__init__()
759
+ self.num_heads = num_heads
760
+ self.head_dim = head_dim
761
+ self.scale = head_dim ** -0.5
762
+ self.sol_spatial_size = sol_spatial_size
763
+
764
+ self.txt_qkv = nn.Linear(hidden_size, 3 * num_heads * head_dim, bias=use_bias)
765
+ self.img_qkv = nn.Linear(hidden_size, 3 * num_heads * head_dim, bias=use_bias)
766
+
767
+ self.txt_out = nn.Linear(num_heads * head_dim, hidden_size, bias=use_bias)
768
+ self.img_out = nn.Linear(num_heads * head_dim, hidden_size, bias=use_bias)
769
+
770
+ # Sol spatial modulation for image tokens
771
+ # Zero-init so exp(0)=1 at init (true identity)
772
+ self.spatial_to_mod = nn.Conv2d(1, num_heads, kernel_size=1, bias=True)
773
+ nn.init.zeros_(self.spatial_to_mod.weight)
774
+ nn.init.zeros_(self.spatial_to_mod.bias)
775
+
776
+ def forward(
777
+ self,
778
+ txt: torch.Tensor,
779
+ img: torch.Tensor,
780
+ rope: Optional[torch.Tensor] = None,
781
+ sol_temperature: Optional[torch.Tensor] = None,
782
+ sol_spatial: Optional[torch.Tensor] = None,
783
+ spatial_size: Optional[Tuple[int, int]] = None,
784
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
785
+ B, L, _ = txt.shape
786
+ _, N, _ = img.shape
787
+
788
+ txt_qkv = self.txt_qkv(txt).reshape(B, L, 3, self.num_heads, self.head_dim)
789
+ img_qkv = self.img_qkv(img).reshape(B, N, 3, self.num_heads, self.head_dim)
790
+
791
+ txt_q, txt_k, txt_v = txt_qkv.permute(2, 0, 3, 1, 4)
792
+ img_q, img_k, img_v = img_qkv.permute(2, 0, 3, 1, 4)
793
+
794
+ if rope is not None:
795
+ img_q = apply_rotary_emb_old(img_q, rope)
796
+ img_k = apply_rotary_emb_old(img_k, rope)
797
+
798
+ # === Sol Spatial Modulation (image only) ===
799
+ if sol_spatial is not None and spatial_size is not None:
800
+ H, W = spatial_size
801
+
802
+ sol_up = F.interpolate(
803
+ sol_spatial.unsqueeze(1),
804
+ size=(H, W),
805
+ mode='bilinear',
806
+ align_corners=False,
807
+ )
808
+
809
+ mod = self.spatial_to_mod(sol_up)
810
+ mod = mod.reshape(B, self.num_heads, H * W)
811
+ mod = torch.exp(mod.clamp(-2, 2)) # exp(0)=1 at init, clamp for stability
812
+
813
+ img_q = img_q * mod.unsqueeze(-1)
814
+ img_k = img_k * mod.unsqueeze(-1)
815
+
816
+ # Concatenate for joint attention
817
+ k = torch.cat([txt_k, img_k], dim=2)
818
+ v = torch.cat([txt_v, img_v], dim=2)
819
+
820
+ # Text attention (NO Sol temperature - text is not spatial)
821
+ txt_scores = torch.matmul(txt_q, k.transpose(-2, -1)) * self.scale
822
+ txt_attn = F.softmax(txt_scores, dim=-1)
823
+ txt_out = torch.matmul(txt_attn, v)
824
+ txt_out = txt_out.transpose(1, 2).reshape(B, L, -1)
825
+
826
+ # Image attention (Sol temperature applies here only)
827
+ img_scores = torch.matmul(img_q, k.transpose(-2, -1)) * self.scale
828
+ if sol_temperature is not None:
829
+ temp = sol_temperature.unsqueeze(-1).unsqueeze(-1).clamp(min=0.1)
830
+ img_scores = img_scores / temp
831
+ img_attn = F.softmax(img_scores, dim=-1)
832
+ img_out = torch.matmul(img_attn, v)
833
+ img_out = img_out.transpose(1, 2).reshape(B, N, -1)
834
+
835
+ return self.txt_out(txt_out), self.img_out(img_out)
836
+
837
+
838
+ # =============================================================================
839
+ # MLP
840
+ # =============================================================================
841
+
842
+ class MLP(nn.Module):
843
+ """Feed-forward network with GELU activation."""
844
+
845
+ def __init__(self, hidden_size: int, mlp_ratio: float = 4.0):
846
+ super().__init__()
847
+ mlp_hidden = int(hidden_size * mlp_ratio)
848
+ self.fc1 = nn.Linear(hidden_size, mlp_hidden, bias=True)
849
+ self.act = nn.GELU(approximate='tanh')
850
+ self.fc2 = nn.Linear(mlp_hidden, hidden_size, bias=True)
851
+
852
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
853
+ return self.fc2(self.act(self.fc1(x)))
854
+
855
+
856
+ # =============================================================================
857
+ # Transformer Blocks
858
+ # =============================================================================
859
+
860
+ class DoubleStreamBlock(nn.Module):
861
+ """Double-stream transformer block with Sol prior support."""
862
+
863
+ def __init__(self, config: TinyFluxConfig):
864
+ super().__init__()
865
+ hidden = config.hidden_size
866
+ heads = config.num_attention_heads
867
+ head_dim = config.attention_head_dim
868
+
869
+ self.img_norm1 = AdaLayerNormZero(hidden)
870
+ self.txt_norm1 = AdaLayerNormZero(hidden)
871
+ self.attn = JointAttention(
872
+ hidden, heads, head_dim,
873
+ use_bias=False,
874
+ sol_spatial_size=config.sol_spatial_size,
875
+ )
876
+ self.img_norm2 = RMSNorm(hidden)
877
+ self.txt_norm2 = RMSNorm(hidden)
878
+ self.img_mlp = MLP(hidden, config.mlp_ratio)
879
+ self.txt_mlp = MLP(hidden, config.mlp_ratio)
880
+
881
+ def forward(
882
+ self,
883
+ txt: torch.Tensor,
884
+ img: torch.Tensor,
885
+ vec: torch.Tensor,
886
+ rope: Optional[torch.Tensor] = None,
887
+ sol_temperature: Optional[torch.Tensor] = None,
888
+ sol_spatial: Optional[torch.Tensor] = None,
889
+ spatial_size: Optional[Tuple[int, int]] = None,
890
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
891
+
892
+ img_normed, img_gate_msa, img_shift_mlp, img_scale_mlp, img_gate_mlp = self.img_norm1(img, vec)
893
+ txt_normed, txt_gate_msa, txt_shift_mlp, txt_scale_mlp, txt_gate_mlp = self.txt_norm1(txt, vec)
894
+
895
+ txt_attn_out, img_attn_out = self.attn(
896
+ txt_normed, img_normed, rope,
897
+ sol_temperature=sol_temperature,
898
+ sol_spatial=sol_spatial,
899
+ spatial_size=spatial_size,
900
+ )
901
+
902
+ txt = txt + txt_gate_msa.unsqueeze(1) * txt_attn_out
903
+ img = img + img_gate_msa.unsqueeze(1) * img_attn_out
904
+
905
+ txt_mlp_in = self.txt_norm2(txt) * (1 + txt_scale_mlp.unsqueeze(1)) + txt_shift_mlp.unsqueeze(1)
906
+ img_mlp_in = self.img_norm2(img) * (1 + img_scale_mlp.unsqueeze(1)) + img_shift_mlp.unsqueeze(1)
907
+
908
+ txt = txt + txt_gate_mlp.unsqueeze(1) * self.txt_mlp(txt_mlp_in)
909
+ img = img + img_gate_mlp.unsqueeze(1) * self.img_mlp(img_mlp_in)
910
+
911
+ return txt, img
912
+
913
+
914
+ class SingleStreamBlock(nn.Module):
915
+ """Single-stream transformer block with Sol prior support."""
916
+
917
+ def __init__(self, config: TinyFluxConfig):
918
+ super().__init__()
919
+ hidden = config.hidden_size
920
+ heads = config.num_attention_heads
921
+ head_dim = config.attention_head_dim
922
+
923
+ self.norm = AdaLayerNormZeroSingle(hidden)
924
+ self.attn = Attention(
925
+ hidden, heads, head_dim,
926
+ use_bias=False,
927
+ sol_spatial_size=config.sol_spatial_size,
928
+ )
929
+ self.mlp = MLP(hidden, config.mlp_ratio)
930
+ self.norm2 = RMSNorm(hidden)
931
+
932
+ def forward(
933
+ self,
934
+ txt: torch.Tensor,
935
+ img: torch.Tensor,
936
+ vec: torch.Tensor,
937
+ rope: Optional[torch.Tensor] = None,
938
+ sol_temperature: Optional[torch.Tensor] = None,
939
+ sol_spatial: Optional[torch.Tensor] = None,
940
+ spatial_size: Optional[Tuple[int, int]] = None,
941
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
942
+ L = txt.shape[1] # Number of text tokens
943
+ x = torch.cat([txt, img], dim=1)
944
+ x_normed, gate = self.norm(x, vec)
945
+
946
+ # For single stream: text tokens come first, then image tokens
947
+ # Sol spatial only applies to image portion
948
+ x = x + gate.unsqueeze(1) * self.attn(
949
+ x_normed, rope,
950
+ sol_temperature=sol_temperature,
951
+ sol_spatial=sol_spatial,
952
+ spatial_size=spatial_size,
953
+ num_txt_tokens=L, # Tell attention how many text tokens to skip
954
+ )
955
+ x = x + self.mlp(self.norm2(x))
956
+ txt, img = x.split([L, x.shape[1] - L], dim=1)
957
+ return txt, img
958
+
959
+
960
+ # =============================================================================
961
+ # Main Model
962
+ # =============================================================================
963
+
964
+ class TinyFluxDeep(nn.Module):
965
+ """
966
+ TinyFlux-Deep v4.1 with Dual Expert System.
967
+
968
+ Lune: Trajectory guidance → vec modulation (global conditioning)
969
+ Sol: Attention prior → temperature/spatial (structural guidance)
970
+ """
971
+
972
+ def __init__(self, config: Optional[TinyFluxConfig] = None):
973
+ super().__init__()
974
+ self.config = config or TinyFluxConfig()
975
+ cfg = self.config
976
+
977
+ # Input projections
978
+ self.img_in = nn.Linear(cfg.in_channels, cfg.hidden_size, bias=True)
979
+ self.txt_in = nn.Linear(cfg.joint_attention_dim, cfg.hidden_size, bias=True)
980
+
981
+ # Conditioning
982
+ self.time_in = MLPEmbedder(cfg.hidden_size)
983
+ self.vector_in = nn.Sequential(
984
+ nn.SiLU(),
985
+ nn.Linear(cfg.pooled_projection_dim, cfg.hidden_size, bias=True)
986
+ )
987
+
988
+ # === T5 Enhancement: Add T5 to vec pathway ===
989
+ if cfg.use_t5_vec:
990
+ self.t5_pool = nn.Sequential(
991
+ nn.Linear(cfg.joint_attention_dim, cfg.hidden_size),
992
+ nn.SiLU(),
993
+ nn.Linear(cfg.hidden_size, cfg.hidden_size),
994
+ )
995
+ # Learnable balance: sigmoid(0) = 0.5 (equal weight at init)
996
+ self.text_balance = nn.Parameter(torch.tensor(0.0))
997
+ else:
998
+ self.t5_pool = None
999
+ self.text_balance = None
1000
+
1001
+ # === Lune Expert Predictor (trajectory → vec) ===
1002
+ if cfg.use_lune_expert:
1003
+ self.lune_predictor = LuneExpertPredictor(
1004
+ time_dim=cfg.hidden_size,
1005
+ clip_dim=cfg.pooled_projection_dim,
1006
+ expert_dim=cfg.lune_expert_dim,
1007
+ hidden_dim=cfg.lune_hidden_dim,
1008
+ output_dim=cfg.hidden_size,
1009
+ dropout=cfg.lune_dropout,
1010
+ )
1011
+ else:
1012
+ self.lune_predictor = None
1013
+
1014
+ # === Sol Attention Prior (structure → attention bias) ===
1015
+ if cfg.use_sol_prior:
1016
+ self.sol_prior = SolAttentionPrior(
1017
+ time_dim=cfg.hidden_size,
1018
+ clip_dim=cfg.pooled_projection_dim,
1019
+ hidden_dim=cfg.sol_hidden_dim,
1020
+ num_heads=cfg.num_attention_heads,
1021
+ spatial_size=cfg.sol_spatial_size,
1022
+ geometric_weight=cfg.sol_geometric_weight,
1023
+ )
1024
+ else:
1025
+ self.sol_prior = None
1026
+
1027
+ # === Legacy support ===
1028
+ # Map old expert_predictor API to lune_predictor
1029
+ self.expert_predictor = self.lune_predictor
1030
+
1031
+ # Legacy guidance
1032
+ if cfg.guidance_embeds:
1033
+ self.guidance_in = MLPEmbedder(cfg.hidden_size)
1034
+ else:
1035
+ self.guidance_in = None
1036
+
1037
+ # RoPE
1038
+ self.rope = EmbedND(theta=10000.0, axes_dim=cfg.axes_dims_rope)
1039
+
1040
+ # Transformer blocks
1041
+ self.double_blocks = nn.ModuleList([
1042
+ DoubleStreamBlock(cfg) for _ in range(cfg.num_double_layers)
1043
+ ])
1044
+ self.single_blocks = nn.ModuleList([
1045
+ SingleStreamBlock(cfg) for _ in range(cfg.num_single_layers)
1046
+ ])
1047
+
1048
+ # Output
1049
+ self.final_norm = RMSNorm(cfg.hidden_size)
1050
+ self.final_linear = nn.Linear(cfg.hidden_size, cfg.in_channels, bias=True)
1051
+
1052
+ self._init_weights()
1053
+
1054
+ def _init_weights(self):
1055
+ def _init(module):
1056
+ if isinstance(module, nn.Linear):
1057
+ nn.init.xavier_uniform_(module.weight)
1058
+ if module.bias is not None:
1059
+ nn.init.zeros_(module.bias)
1060
+ self.apply(_init)
1061
+ nn.init.zeros_(self.final_linear.weight)
1062
+
1063
+ def forward(
1064
+ self,
1065
+ hidden_states: torch.Tensor,
1066
+ encoder_hidden_states: torch.Tensor,
1067
+ pooled_projections: torch.Tensor,
1068
+ timestep: torch.Tensor,
1069
+ img_ids: torch.Tensor,
1070
+ txt_ids: Optional[torch.Tensor] = None,
1071
+ guidance: Optional[torch.Tensor] = None,
1072
+ # Lune inputs
1073
+ lune_features: Optional[torch.Tensor] = None,
1074
+ # Sol inputs
1075
+ sol_stats: Optional[torch.Tensor] = None,
1076
+ sol_spatial: Optional[torch.Tensor] = None,
1077
+ # Legacy API
1078
+ expert_features: Optional[torch.Tensor] = None,
1079
+ return_expert_pred: bool = False,
1080
+ ) -> torch.Tensor:
1081
+ """
1082
+ Forward pass.
1083
+
1084
+ Args:
1085
+ hidden_states: [B, N, C] - image latents (flattened)
1086
+ encoder_hidden_states: [B, L, D] - T5 text embeddings
1087
+ pooled_projections: [B, D] - CLIP pooled features
1088
+ timestep: [B] - diffusion timestep in [0, 1]
1089
+ img_ids: [N, 3] or [B, N, 3] - image position IDs
1090
+ txt_ids: [L, 3] or [B, L, 3] - text position IDs (optional)
1091
+ guidance: [B] - legacy guidance scale
1092
+ lune_features: [B, 1280] - real Lune features (training)
1093
+ sol_stats: [B, 3] - real Sol statistics (training)
1094
+ sol_spatial: [B, H, W] - real Sol spatial importance (training)
1095
+ expert_features: [B, 1280] - legacy API, maps to lune_features
1096
+ return_expert_pred: if True, return (output, expert_info) tuple
1097
+
1098
+ Returns:
1099
+ output: [B, N, C] - predicted velocity
1100
+ expert_info: dict (if return_expert_pred=True)
1101
+ """
1102
+ B = hidden_states.shape[0]
1103
+ L = encoder_hidden_states.shape[1]
1104
+ N = hidden_states.shape[1]
1105
+
1106
+ # Infer spatial dimensions
1107
+ H = W = int(math.sqrt(N))
1108
+ assert H * W == N, f"N={N} is not a perfect square, cannot infer spatial size. Pass explicit spatial_size."
1109
+ spatial_size = (H, W)
1110
+
1111
+ # Legacy API mapping
1112
+ if expert_features is not None and lune_features is None:
1113
+ lune_features = expert_features
1114
+
1115
+ # Input projections
1116
+ img = self.img_in(hidden_states)
1117
+ txt = self.txt_in(encoder_hidden_states)
1118
+
1119
+ # Conditioning: time + text
1120
+ time_emb = self.time_in(timestep)
1121
+ clip_vec = self.vector_in(pooled_projections)
1122
+
1123
+ # === T5 Enhancement: Pool T5 and add to vec ===
1124
+ t5_pooled = None
1125
+ if self.t5_pool is not None:
1126
+ # Attention-weighted pooling of T5 sequence
1127
+ t5_attn_logits = encoder_hidden_states.mean(dim=-1) # [B, L]
1128
+ t5_attn = F.softmax(t5_attn_logits, dim=-1) # [B, L]
1129
+ t5_pooled = (encoder_hidden_states * t5_attn.unsqueeze(-1)).sum(dim=1) # [B, D]
1130
+ t5_vec = self.t5_pool(t5_pooled)
1131
+
1132
+ # Balanced combination of CLIP and T5
1133
+ balance = torch.sigmoid(self.text_balance)
1134
+ text_vec = balance * clip_vec + (1 - balance) * t5_vec
1135
+ else:
1136
+ text_vec = clip_vec
1137
+
1138
+ vec = time_emb + text_vec
1139
+
1140
+ # === Lune: trajectory guidance → vec ===
1141
+ lune_info = None
1142
+ if self.lune_predictor is not None:
1143
+ lune_out = self.lune_predictor(
1144
+ time_emb=time_emb,
1145
+ clip_pooled=pooled_projections,
1146
+ real_expert_features=lune_features,
1147
+ )
1148
+ vec = vec + lune_out['expert_signal']
1149
+ lune_info = lune_out
1150
+
1151
+ # === Sol: attention prior → temperature, spatial ===
1152
+ sol_temperature = None
1153
+ sol_spatial_blend = None
1154
+ sol_info = None
1155
+
1156
+ if self.sol_prior is not None:
1157
+ sol_out = self.sol_prior(
1158
+ time_emb=time_emb,
1159
+ clip_pooled=pooled_projections,
1160
+ t_normalized=timestep,
1161
+ real_stats=sol_stats,
1162
+ real_spatial=sol_spatial,
1163
+ )
1164
+ sol_temperature = sol_out['temperature']
1165
+ sol_spatial_blend = sol_out['spatial_importance']
1166
+ sol_info = sol_out
1167
+
1168
+ # Legacy guidance (fallback)
1169
+ if self.guidance_in is not None and guidance is not None:
1170
+ vec = vec + self.guidance_in(guidance)
1171
+
1172
+ # Handle img_ids shape
1173
+ if img_ids.ndim == 3:
1174
+ img_ids = img_ids[0]
1175
+ img_rope = self.rope(img_ids)
1176
+
1177
+ # Double-stream blocks
1178
+ for block in self.double_blocks:
1179
+ txt, img = block(
1180
+ txt, img, vec, img_rope,
1181
+ sol_temperature=sol_temperature,
1182
+ sol_spatial=sol_spatial_blend,
1183
+ spatial_size=spatial_size,
1184
+ )
1185
+
1186
+ # Build full sequence RoPE for single-stream
1187
+ if txt_ids is None:
1188
+ txt_ids = torch.zeros(L, 3, device=img_ids.device, dtype=img_ids.dtype)
1189
+ elif txt_ids.ndim == 3:
1190
+ txt_ids = txt_ids[0]
1191
+
1192
+ all_ids = torch.cat([txt_ids, img_ids], dim=0)
1193
+ full_rope = self.rope(all_ids)
1194
+
1195
+ # Single-stream blocks
1196
+ for block in self.single_blocks:
1197
+ txt, img = block(
1198
+ txt, img, vec, full_rope,
1199
+ sol_temperature=sol_temperature,
1200
+ sol_spatial=sol_spatial_blend,
1201
+ spatial_size=spatial_size,
1202
+ )
1203
+
1204
+ # Output
1205
+ img = self.final_norm(img)
1206
+ output = self.final_linear(img)
1207
+
1208
+ if return_expert_pred:
1209
+ expert_info = {
1210
+ 'lune': lune_info,
1211
+ 'sol': sol_info,
1212
+ # Legacy API
1213
+ 'expert_signal': lune_info['expert_signal'] if lune_info else None,
1214
+ 'expert_pred': lune_info['expert_pred'] if lune_info else None,
1215
+ 'expert_used': lune_info['expert_used'] if lune_info else None,
1216
+ }
1217
+ return output, expert_info
1218
+ return output
1219
+
1220
+ def compute_loss(
1221
+ self,
1222
+ output: torch.Tensor,
1223
+ target: torch.Tensor,
1224
+ expert_info: Optional[Dict] = None,
1225
+ lune_features: Optional[torch.Tensor] = None,
1226
+ sol_stats: Optional[torch.Tensor] = None,
1227
+ sol_spatial: Optional[torch.Tensor] = None,
1228
+ lune_weight: float = 0.1,
1229
+ sol_weight: float = 0.05,
1230
+ # New options
1231
+ use_huber: bool = True,
1232
+ huber_delta: float = 0.1,
1233
+ lune_distill_mode: str = "cosine",
1234
+ spatial_weighting: bool = True,
1235
+ ) -> Dict[str, torch.Tensor]:
1236
+ """
1237
+ Compute combined loss with Huber and soft distillation.
1238
+
1239
+ Args:
1240
+ output: [B, N, C] model prediction
1241
+ target: [B, N, C] flow matching target (data - noise)
1242
+ expert_info: dict from forward pass
1243
+ lune_features: [B, 1280] real Lune features
1244
+ sol_stats: [B, 3] real Sol statistics
1245
+ sol_spatial: [B, H, W] real Sol spatial importance
1246
+ lune_weight: weight for Lune distillation loss
1247
+ sol_weight: weight for Sol distillation loss
1248
+ use_huber: use Huber loss instead of MSE for main loss
1249
+ huber_delta: Huber delta (smaller = tighter MSE behavior)
1250
+ lune_distill_mode: "hard" (MSE), "cosine" (directional), "soft" (temp-scaled)
1251
+ spatial_weighting: weight main loss by Sol spatial importance
1252
+
1253
+ Returns:
1254
+ dict with losses
1255
+ """
1256
+ device = output.device
1257
+ B, N, C = output.shape
1258
+
1259
+ # === Main Flow Matching Loss ===
1260
+ if use_huber:
1261
+ # Huber loss: MSE for small errors, MAE for large (robust to outliers)
1262
+ main_loss_unreduced = F.huber_loss(
1263
+ output, target,
1264
+ reduction='none',
1265
+ delta=huber_delta
1266
+ ) # [B, N, C]
1267
+ else:
1268
+ main_loss_unreduced = (output - target).pow(2) # [B, N, C]
1269
+
1270
+ # === Sol Spatial Weighting ===
1271
+ if spatial_weighting and sol_spatial is not None:
1272
+ # Upsample Sol spatial to match token resolution
1273
+ H = W = int(math.sqrt(N))
1274
+ sol_weight_map = F.interpolate(
1275
+ sol_spatial.unsqueeze(1), # [B, 1, H_sol, W_sol]
1276
+ size=(H, W),
1277
+ mode='bilinear',
1278
+ align_corners=False,
1279
+ ).reshape(B, N, 1) # [B, N, 1]
1280
+
1281
+ # Normalize to mean=1 (doesn't change loss scale, just distribution)
1282
+ sol_weight_map = sol_weight_map / (sol_weight_map.mean() + 1e-6)
1283
+
1284
+ # Apply spatial weighting
1285
+ main_loss_unreduced = main_loss_unreduced * sol_weight_map
1286
+
1287
+ main_loss = main_loss_unreduced.mean()
1288
+
1289
+ losses = {
1290
+ 'main': main_loss,
1291
+ 'lune_distill': torch.tensor(0.0, device=device),
1292
+ 'sol_stat_distill': torch.tensor(0.0, device=device),
1293
+ 'sol_spatial_distill': torch.tensor(0.0, device=device),
1294
+ 'total': main_loss,
1295
+ }
1296
+
1297
+ if expert_info is None:
1298
+ return losses
1299
+
1300
+ # === Lune Distillation (Soft/Directional) ===
1301
+ if expert_info.get('lune') and lune_features is not None:
1302
+ lune_pred = expert_info['lune']['expert_pred']
1303
+
1304
+ if lune_distill_mode == "cosine":
1305
+ # Directional matching - Lune is a guide, not exact target
1306
+ # "Go in the same direction" without forcing exact values
1307
+ pred_norm = F.normalize(lune_pred, dim=-1)
1308
+ real_norm = F.normalize(lune_features, dim=-1)
1309
+ cosine_sim = (pred_norm * real_norm).sum(dim=-1)
1310
+ losses['lune_distill'] = (1 - cosine_sim).mean()
1311
+
1312
+ elif lune_distill_mode == "soft":
1313
+ # Temperature-scaled MSE (mushier matching)
1314
+ temp = 2.0 # Higher = softer
1315
+ mse = (lune_pred - lune_features).pow(2).mean(dim=-1)
1316
+ losses['lune_distill'] = (mse / temp).mean()
1317
+
1318
+ elif lune_distill_mode == "huber":
1319
+ # Huber for distillation too
1320
+ losses['lune_distill'] = F.huber_loss(
1321
+ lune_pred, lune_features, delta=1.0
1322
+ )
1323
+
1324
+ else: # "hard" - original MSE
1325
+ losses['lune_distill'] = F.mse_loss(lune_pred, lune_features)
1326
+
1327
+ # === Sol Distillation (keeps MSE - small vectors, precision matters) ===
1328
+ if expert_info.get('sol'):
1329
+ if sol_stats is not None:
1330
+ sol_pred_stats = expert_info['sol']['pred_stats']
1331
+ losses['sol_stat_distill'] = F.mse_loss(sol_pred_stats, sol_stats)
1332
+
1333
+ if sol_spatial is not None:
1334
+ sol_pred_spatial = expert_info['sol']['pred_spatial']
1335
+ losses['sol_spatial_distill'] = F.mse_loss(sol_pred_spatial, sol_spatial)
1336
+
1337
+ # === Total ===
1338
+ losses['total'] = (
1339
+ main_loss +
1340
+ lune_weight * losses['lune_distill'] +
1341
+ sol_weight * (losses['sol_stat_distill'] + losses['sol_spatial_distill'])
1342
+ )
1343
+
1344
+ return losses
1345
+
1346
+ @staticmethod
1347
+ def create_img_ids(batch_size: int, height: int, width: int, device: torch.device) -> torch.Tensor:
1348
+ """Create image position IDs for RoPE."""
1349
+ img_ids = torch.zeros(height * width, 3, device=device)
1350
+ for i in range(height):
1351
+ for j in range(width):
1352
+ idx = i * width + j
1353
+ img_ids[idx, 0] = 0
1354
+ img_ids[idx, 1] = i
1355
+ img_ids[idx, 2] = j
1356
+ return img_ids
1357
+
1358
+ @staticmethod
1359
+ def create_txt_ids(text_len: int, device: torch.device) -> torch.Tensor:
1360
+ """Create text position IDs."""
1361
+ txt_ids = torch.zeros(text_len, 3, device=device)
1362
+ txt_ids[:, 0] = torch.arange(text_len, device=device)
1363
+ return txt_ids
1364
+
1365
+ def count_parameters(self) -> Dict[str, int]:
1366
+ """Count parameters by component."""
1367
+ counts = {}
1368
+ counts['img_in'] = sum(p.numel() for p in self.img_in.parameters())
1369
+ counts['txt_in'] = sum(p.numel() for p in self.txt_in.parameters())
1370
+ counts['time_in'] = sum(p.numel() for p in self.time_in.parameters())
1371
+ counts['vector_in'] = sum(p.numel() for p in self.vector_in.parameters())
1372
+
1373
+ if self.t5_pool is not None:
1374
+ counts['t5_pool'] = sum(p.numel() for p in self.t5_pool.parameters()) + 1 # +1 for balance param
1375
+ if self.lune_predictor is not None:
1376
+ counts['lune_predictor'] = sum(p.numel() for p in self.lune_predictor.parameters())
1377
+ if self.sol_prior is not None:
1378
+ counts['sol_prior'] = sum(p.numel() for p in self.sol_prior.parameters())
1379
+ if self.guidance_in is not None:
1380
+ counts['guidance_in'] = sum(p.numel() for p in self.guidance_in.parameters())
1381
+
1382
+ counts['double_blocks'] = sum(p.numel() for p in self.double_blocks.parameters())
1383
+ counts['single_blocks'] = sum(p.numel() for p in self.single_blocks.parameters())
1384
+ counts['final'] = sum(p.numel() for p in self.final_norm.parameters()) + \
1385
+ sum(p.numel() for p in self.final_linear.parameters())
1386
+ counts['total'] = sum(p.numel() for p in self.parameters())
1387
+ return counts
1388
+
1389
+
1390
+ # =============================================================================
1391
+ # Test
1392
+ # =============================================================================
1393
+
1394
+ def test_model():
1395
+ """Test TinyFlux-Deep v4.1 with Dual Expert System."""
1396
+ print("=" * 60)
1397
+ print(f"TinyFlux-Deep v{__version__} - Dual Expert Test")
1398
+ print("=" * 60)
1399
+
1400
+ config = TinyFluxConfig(
1401
+ use_lune_expert=True,
1402
+ use_sol_prior=True,
1403
+ lune_expert_dim=1280,
1404
+ sol_spatial_size=8,
1405
+ sol_geometric_weight=0.7,
1406
+ use_t5_vec=True,
1407
+ lune_distill_mode="cosine",
1408
+ use_huber_loss=True,
1409
+ huber_delta=0.1,
1410
+ )
1411
+ model = TinyFluxDeep(config)
1412
+
1413
+ counts = model.count_parameters()
1414
+ print(f"\nConfig:")
1415
+ print(f" hidden_size: {config.hidden_size}")
1416
+ print(f" num_double_layers: {config.num_double_layers}")
1417
+ print(f" num_single_layers: {config.num_single_layers}")
1418
+ print(f" use_lune_expert: {config.use_lune_expert}")
1419
+ print(f" use_sol_prior: {config.use_sol_prior}")
1420
+ print(f" sol_geometric_weight: {config.sol_geometric_weight}")
1421
+ print(f" use_t5_vec: {config.use_t5_vec}")
1422
+ print(f" lune_distill_mode: {config.lune_distill_mode}")
1423
+ print(f" use_huber_loss: {config.use_huber_loss}")
1424
+
1425
+ print(f"\nParameters:")
1426
+ for name, count in counts.items():
1427
+ print(f" {name}: {count:,}")
1428
+
1429
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
1430
+ model = model.to(device)
1431
+
1432
+ B, H, W = 2, 64, 64
1433
+ L = 77
1434
+
1435
+ hidden_states = torch.randn(B, H * W, config.in_channels, device=device)
1436
+ encoder_hidden_states = torch.randn(B, L, config.joint_attention_dim, device=device)
1437
+ pooled_projections = torch.randn(B, config.pooled_projection_dim, device=device)
1438
+ timestep = torch.rand(B, device=device)
1439
+ img_ids = TinyFluxDeep.create_img_ids(B, H, W, device)
1440
+
1441
+ # Expert inputs
1442
+ lune_features = torch.randn(B, config.lune_expert_dim, device=device)
1443
+ sol_stats = torch.randn(B, 3, device=device)
1444
+ sol_spatial = torch.rand(B, config.sol_spatial_size, config.sol_spatial_size, device=device)
1445
+
1446
+ print("\n[Test 1: Training mode with dual experts]")
1447
+ model.train()
1448
+ with torch.no_grad():
1449
+ output, expert_info = model(
1450
+ hidden_states=hidden_states,
1451
+ encoder_hidden_states=encoder_hidden_states,
1452
+ pooled_projections=pooled_projections,
1453
+ timestep=timestep,
1454
+ img_ids=img_ids,
1455
+ lune_features=lune_features,
1456
+ sol_stats=sol_stats,
1457
+ sol_spatial=sol_spatial,
1458
+ return_expert_pred=True,
1459
+ )
1460
+ print(f" Output shape: {output.shape}")
1461
+ print(f" Lune used: {expert_info['lune']['expert_used']}")
1462
+ print(f" Sol temperature shape: {expert_info['sol']['temperature'].shape}")
1463
+ print(f" Sol spatial shape: {expert_info['sol']['spatial_importance'].shape}")
1464
+
1465
+ print("\n[Test 2: Inference mode (no expert inputs)]")
1466
+ model.eval()
1467
+ with torch.no_grad():
1468
+ output = model(
1469
+ hidden_states=hidden_states,
1470
+ encoder_hidden_states=encoder_hidden_states,
1471
+ pooled_projections=pooled_projections,
1472
+ timestep=timestep,
1473
+ img_ids=img_ids,
1474
+ )
1475
+ print(f" Output shape: {output.shape}")
1476
+ print(f" Output range: [{output.min():.4f}, {output.max():.4f}]")
1477
+
1478
+ print("\n[Test 3: Loss computation with Huber + Cosine distillation]")
1479
+ target = torch.randn_like(output)
1480
+ model.train()
1481
+ output, expert_info = model(
1482
+ hidden_states=hidden_states,
1483
+ encoder_hidden_states=encoder_hidden_states,
1484
+ pooled_projections=pooled_projections,
1485
+ timestep=timestep,
1486
+ img_ids=img_ids,
1487
+ lune_features=lune_features,
1488
+ sol_stats=sol_stats,
1489
+ sol_spatial=sol_spatial,
1490
+ return_expert_pred=True,
1491
+ )
1492
+ losses = model.compute_loss(
1493
+ output=output,
1494
+ target=target,
1495
+ expert_info=expert_info,
1496
+ lune_features=lune_features,
1497
+ sol_stats=sol_stats,
1498
+ sol_spatial=sol_spatial,
1499
+ lune_weight=0.1,
1500
+ sol_weight=0.05,
1501
+ use_huber=True,
1502
+ huber_delta=0.1,
1503
+ lune_distill_mode="cosine",
1504
+ spatial_weighting=True,
1505
+ )
1506
+ print(f" Main loss (Huber): {losses['main']:.4f}")
1507
+ print(f" Lune distill (cosine): {losses['lune_distill']:.4f}")
1508
+ print(f" Sol stat distill: {losses['sol_stat_distill']:.4f}")
1509
+ print(f" Sol spatial distill: {losses['sol_spatial_distill']:.4f}")
1510
+ print(f" Total loss: {losses['total']:.4f}")
1511
+
1512
+ print("\n[Test 4: Legacy API compatibility]")
1513
+ with torch.no_grad():
1514
+ output, expert_info = model(
1515
+ hidden_states=hidden_states,
1516
+ encoder_hidden_states=encoder_hidden_states,
1517
+ pooled_projections=pooled_projections,
1518
+ timestep=timestep,
1519
+ img_ids=img_ids,
1520
+ expert_features=lune_features, # Legacy API
1521
+ return_expert_pred=True,
1522
+ )
1523
+ print(f" Legacy expert_pred shape: {expert_info['expert_pred'].shape}")
1524
+ print(f" Legacy expert_used: {expert_info['expert_used']}")
1525
+
1526
+ print("\n[Test 5: T5 Enhancement check]")
1527
+ if model.t5_pool is not None:
1528
+ balance = torch.sigmoid(model.text_balance).item()
1529
+ print(f" T5 pool: enabled")
1530
+ print(f" Text balance (CLIP vs T5): {balance:.2f} / {1-balance:.2f}")
1531
+ else:
1532
+ print(f" T5 pool: disabled")
1533
+
1534
+ print("\n[Test 6: Config serialization]")
1535
+ config_dict = config.to_dict()
1536
+ config_restored = TinyFluxConfig.from_dict(config_dict)
1537
+ print(f" Serialized keys: {len(config_dict)}")
1538
+ print(f" Restored hidden_size: {config_restored.hidden_size}")
1539
+ print(f" Round-trip successful: {config.hidden_size == config_restored.hidden_size}")
1540
+
1541
+ print("\n" + "=" * 60)
1542
+ print("✓ All tests passed!")
1543
+ print("=" * 60)
1544
+
1545
+
1546
+ if __name__ == "__main__":
1547
+ test_model()