Harley-ml commited on
Commit
6d2db08
·
verified ·
1 Parent(s): 4c4b868

Upload 3 files

Browse files
config.json CHANGED
@@ -1,11 +1,11 @@
1
  {
2
  "architectures": [
3
- "CustomModelForImageDiffusion"
4
  ],
5
  "auto_map": {
6
- "AutoConfig": "configuration_custom.CustomConfig",
7
- "AutoModel": "modeling_custom.CustomModel",
8
- "AutoModelForImageDiffusion": "modeling_custom.CustomModelForImageDiffusion"
9
  },
10
  "dtype": "float32",
11
  "head_dim": 24,
@@ -14,7 +14,7 @@
14
  "in_channels": 3,
15
  "initializer_range": 0.02,
16
  "intermediate_size": 160,
17
- "model_type": "custom_image_diffusion",
18
  "num_attention_heads": 4,
19
  "num_hidden_layers": 6,
20
  "num_key_value_heads": 2,
 
1
  {
2
  "architectures": [
3
+ "TinyImageGenModelForImageDiffusion"
4
  ],
5
  "auto_map": {
6
+ "AutoConfig": "configuration_tinyimagegen.TinyImageGenConfig",
7
+ "AutoModel": "modeling_tinyimagegen.TinyImageGenModel",
8
+ "AutoModelForImageDiffusion": "modeling_tinyimagegen.TinyImageGenModelForImageDiffusion"
9
  },
10
  "dtype": "float32",
11
  "head_dim": 24,
 
14
  "in_channels": 3,
15
  "initializer_range": 0.02,
16
  "intermediate_size": 160,
17
+ "model_type": "tinyimagegen",
18
  "num_attention_heads": 4,
19
  "num_hidden_layers": 6,
20
  "num_key_value_heads": 2,
configuration_tinyimagegen.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+
3
+ class TinyImageGenConfig(PretrainedConfig):
4
+ model_type = "tinyimagegen"
5
+
6
+ def __init__(
7
+ self,
8
+ image_size: int = 32,
9
+ in_channels: int = 3,
10
+ patch_size: int = 4,
11
+ hidden_size: int = 32,
12
+ num_hidden_layers: int = 6,
13
+ num_attention_heads: int = 4,
14
+ num_key_value_heads: int = 2,
15
+ intermediate_size: int = 48,
16
+ swiglu_interval: int = 3,
17
+ num_lanes: int = 4,
18
+ use_xsa: bool = False,
19
+ use_per_head_gating: bool = False,
20
+ rope_theta: float = 2500.0,
21
+ rms_norm_eps: float = 1e-5,
22
+ initializer_range: float = 0.02,
23
+ **kwargs,
24
+ ):
25
+ self.image_size = image_size
26
+ self.in_channels = in_channels
27
+ self.patch_size = patch_size
28
+ self.hidden_size = hidden_size
29
+ self.num_hidden_layers = num_hidden_layers
30
+ self.num_attention_heads = num_attention_heads
31
+ self.num_key_value_heads = num_key_value_heads
32
+ self.intermediate_size = intermediate_size
33
+ self.swiglu_interval = swiglu_interval
34
+ self.num_lanes = num_lanes
35
+ self.use_xsa = use_xsa
36
+ self.use_per_head_gating = use_per_head_gating
37
+ self.rope_theta = rope_theta
38
+ self.rms_norm_eps = rms_norm_eps
39
+ self.initializer_range = initializer_range
40
+ self.head_dim = hidden_size // num_attention_heads
41
+ self.num_patches_side = image_size // patch_size
42
+ self.num_patches = self.num_patches_side ** 2
43
+ self.patch_dim = in_channels * (patch_size ** 2)
44
+
45
+ self.auto_map = {
46
+ "AutoConfig": "configuration_tinyimagegen.TinyImageGenConfig",
47
+ "AutoModel": "modeling_tinyimagegen.TinyImageGenModel",
48
+ "AutoModelForImageDiffusion": "modeling_tinyimagegen.TinyImageGenModelForImageDiffusion",
49
+ }
50
+
51
+ super().__init__(**kwargs)
modeling_tinyimagegen.py ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from dataclasses import dataclass
3
+ from typing import Optional, Tuple, Union
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ import torch.utils.checkpoint as cp
8
+ from transformers.modeling_utils import PreTrainedModel
9
+ from transformers.utils import ModelOutput
10
+ from safetensors.torch import load_file
11
+ import os
12
+
13
+ try:
14
+ from .configuration_tinyimagegen import TinyImageGenConfig
15
+ except Exception:
16
+ from configuration_tinyimagegen import TinyImageGenConfig
17
+
18
+ @torch.no_grad()
19
+ def get_hadamard_matrix(d: int, dtype=torch.float32) -> torch.Tensor:
20
+ p2 = 1 << (d - 1).bit_length()
21
+ eye = torch.eye(p2, dtype=dtype)
22
+ h = 1
23
+ out = eye.clone()
24
+ while h < p2:
25
+ out = out.view(-1, 2, h)
26
+ u = out[:, 0, :]
27
+ v = out[:, 1, :]
28
+ out = torch.cat((u + v, u - v), dim=-2)
29
+ out = out.view(p2, p2)
30
+ h *= 2
31
+ out = out * (1.0 / math.sqrt(p2))
32
+ return out[:d, :d].contiguous()
33
+
34
+ class RMSNorm(nn.Module):
35
+ def __init__(self, dim: int, eps: float = 1e-5):
36
+ super().__init__()
37
+ self.eps = eps
38
+ self.weight = nn.Parameter(torch.ones(dim))
39
+
40
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
41
+ norm = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
42
+ return x * norm * self.weight
43
+
44
+ class TimestepEmbedder(nn.Module):
45
+ def __init__(self, hidden_size: int, frequency_embedding_size: int = 128):
46
+ super().__init__()
47
+ self.mlp = nn.Sequential(
48
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
49
+ nn.SiLU(),
50
+ nn.Linear(hidden_size, hidden_size, bias=True),
51
+ )
52
+ self.frequency_embedding_size = frequency_embedding_size
53
+
54
+ @staticmethod
55
+ def timestep_embedding(t: torch.Tensor, dim: int, max_period: float = 10000.0) -> torch.Tensor:
56
+ half = dim // 2
57
+ freqs = torch.exp(
58
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device) / half
59
+ )
60
+ args = t[:, None].float() * freqs[None]
61
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
62
+ if dim % 2:
63
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
64
+ return embedding
65
+
66
+ def forward(self, t: torch.Tensor) -> torch.Tensor:
67
+ t_freq = self.timestep_embedding(t * 1000.0, self.frequency_embedding_size)
68
+ return self.mlp(t_freq)
69
+
70
+ class RotaryEmbedding2D(nn.Module):
71
+ def __init__(self, head_dim: int, base: float = 10000.0):
72
+ super().__init__()
73
+ self.head_dim = head_dim
74
+ self.dim_h = 2 * (head_dim // 4)
75
+ self.dim_w = head_dim - self.dim_h
76
+ self.base = base
77
+
78
+ inv_freq_h = 1.0 / (self.base ** (torch.arange(0, self.dim_h, 2, dtype=torch.float32) / self.dim_h))
79
+ inv_freq_w = 1.0 / (self.base ** (torch.arange(0, self.dim_w, 2, dtype=torch.float32) / self.dim_w))
80
+ self.register_buffer("inv_freq_h", inv_freq_h, persistent=False)
81
+ self.register_buffer("inv_freq_w", inv_freq_w, persistent=False)
82
+
83
+ def forward(self, grid_h: int, grid_w: int, device: torch.device, dtype: torch.dtype = torch.float32):
84
+ t_h = torch.arange(grid_h, device=device, dtype=torch.float32)
85
+ t_w = torch.arange(grid_w, device=device, dtype=torch.float32)
86
+
87
+ freqs_h = torch.outer(t_h, self.inv_freq_h.to(device=device, dtype=torch.float32))
88
+ freqs_w = torch.outer(t_w, self.inv_freq_w.to(device=device, dtype=torch.float32))
89
+
90
+ emb_h = torch.cat((freqs_h, freqs_h), dim=-1)
91
+ emb_w = torch.cat((freqs_w, freqs_w), dim=-1)
92
+
93
+ emb_h_grid = emb_h[:, None, :].expand(-1, grid_w, -1).reshape(grid_h * grid_w, self.dim_h)
94
+ emb_w_grid = emb_w[None, :, :].expand(grid_h, -1, -1).reshape(grid_h * grid_w, self.dim_w)
95
+
96
+ cos_h = emb_h_grid.cos().to(dtype=dtype).unsqueeze(0).unsqueeze(0)
97
+ sin_h = emb_h_grid.sin().to(dtype=dtype).unsqueeze(0).unsqueeze(0)
98
+ cos_w = emb_w_grid.cos().to(dtype=dtype).unsqueeze(0).unsqueeze(0)
99
+ sin_w = emb_w_grid.sin().to(dtype=dtype).unsqueeze(0).unsqueeze(0)
100
+ return cos_h, sin_h, cos_w, sin_w
101
+
102
+ def rotate_half(x: torch.Tensor) -> torch.Tensor:
103
+ x1 = x[..., : x.shape[-1] // 2]
104
+ x2 = x[..., x.shape[-1] // 2 :]
105
+ return torch.cat((-x2, x1), dim=-1)
106
+
107
+ def apply_rotary_pos_emb_2d(q: torch.Tensor, k: torch.Tensor, cos_h: torch.Tensor, sin_h: torch.Tensor, cos_w: torch.Tensor, sin_w: torch.Tensor):
108
+ d_h = cos_h.shape[-1]
109
+ qh, qw = q[..., :d_h], q[..., d_h:]
110
+ kh, kw = k[..., :d_h], k[..., d_h:]
111
+
112
+ qh_rot = (qh * cos_h) + (rotate_half(qh) * sin_h)
113
+ qw_rot = (qw * cos_w) + (rotate_half(qw) * sin_w)
114
+ kh_rot = (kh * cos_h) + (rotate_half(kh) * sin_h)
115
+ kw_rot = (kw * cos_w) + (rotate_half(kw) * sin_w)
116
+
117
+ return torch.cat([qh_rot, qw_rot], dim=-1), torch.cat([kh_rot, kw_rot], dim=-1)
118
+
119
+ class HadamardMLP(nn.Module):
120
+ def __init__(self, config: TinyImageGenConfig):
121
+ super().__init__()
122
+ self.dim = config.hidden_size
123
+ self.scale1 = nn.Parameter(torch.ones(self.dim))
124
+ self.scale2 = nn.Parameter(torch.ones(self.dim))
125
+ self.gate = nn.Parameter(torch.ones(self.dim))
126
+ self.bias = nn.Parameter(torch.zeros(self.dim))
127
+
128
+ hadamard_mat = get_hadamard_matrix(self.dim)
129
+ self.register_buffer("hadamard_mat", hadamard_mat, persistent=False)
130
+
131
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
132
+ mat = self.hadamard_mat.type_as(x)
133
+ h = (x * self.scale1) @ mat
134
+ g = F.silu(x * self.gate)
135
+ out = ((h * g) @ mat) * self.scale2 + self.bias
136
+ return out
137
+
138
+ class SwiGLUMLP(nn.Module):
139
+ def __init__(self, config: TinyImageGenConfig):
140
+ super().__init__()
141
+ self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
142
+ self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
143
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
144
+
145
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
146
+ return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
147
+
148
+ class XSAGQAttention(nn.Module):
149
+ def __init__(self, config: TinyImageGenConfig):
150
+ super().__init__()
151
+ self.dim = config.hidden_size
152
+ self.n_heads = config.num_attention_heads
153
+ self.n_kv_heads = config.num_key_value_heads
154
+ self.head_dim = config.head_dim
155
+ self.num_kv_groups = self.n_heads // self.n_kv_heads
156
+ self.use_xsa = config.use_xsa
157
+ self.use_per_head_gating = config.use_per_head_gating
158
+
159
+ self.wq = nn.Linear(self.dim, self.n_heads * self.head_dim, bias=False)
160
+ self.wk = nn.Linear(self.dim, self.n_kv_heads * self.head_dim, bias=False)
161
+ self.wv = nn.Linear(self.dim, self.n_kv_heads * self.head_dim, bias=False)
162
+ self.wo = nn.Linear(self.n_heads * self.head_dim, self.dim, bias=False)
163
+
164
+ self.q_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
165
+ self.k_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
166
+
167
+ if self.use_per_head_gating:
168
+ self.head_gate = nn.Linear(self.dim, self.n_heads, bias=True)
169
+ nn.init.constant_(self.head_gate.bias, 1.0)
170
+ nn.init.zeros_(self.head_gate.weight)
171
+
172
+ def forward(self, x: torch.Tensor, cos_h: torch.Tensor, sin_h: torch.Tensor, cos_w: torch.Tensor, sin_w: torch.Tensor) -> torch.Tensor:
173
+ bsz, seqlen, _ = x.shape
174
+
175
+ xq = self.wq(x).view(bsz, seqlen, self.n_heads, self.head_dim).transpose(1, 2)
176
+ xk = self.wk(x).view(bsz, seqlen, self.n_kv_heads, self.head_dim).transpose(1, 2)
177
+ xv = self.wv(x).view(bsz, seqlen, self.n_kv_heads, self.head_dim).transpose(1, 2)
178
+
179
+ xq = self.q_norm(xq)
180
+ xk = self.k_norm(xk)
181
+
182
+ xq, xk = apply_rotary_pos_emb_2d(xq, xk, cos_h, sin_h, cos_w, sin_w)
183
+
184
+ if self.num_kv_groups > 1:
185
+ xk = xk.repeat_interleave(self.num_kv_groups, dim=1)
186
+ xv_expanded = xv.repeat_interleave(self.num_kv_groups, dim=1)
187
+ else:
188
+ xv_expanded = xv
189
+
190
+ attn_out = F.scaled_dot_product_attention(xq, xk, xv_expanded, is_causal=False)
191
+
192
+ if self.use_xsa:
193
+ vn = F.normalize(xv_expanded, p=2, dim=-1, eps=1e-6)
194
+ proj = (attn_out * vn).sum(dim=-1, keepdim=True)
195
+ attn_out = attn_out - proj * vn
196
+
197
+ if self.use_per_head_gating:
198
+ gate = torch.sigmoid(self.head_gate(x)).transpose(1, 2).unsqueeze(-1)
199
+ attn_out = attn_out * gate
200
+
201
+ out = attn_out.transpose(1, 2).contiguous().view(bsz, seqlen, -1)
202
+ return self.wo(out)
203
+
204
+ def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
205
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
206
+
207
+ class MultiLaneBlock(nn.Module):
208
+ def __init__(self, config: TinyImageGenConfig, layer_idx: int):
209
+ super().__init__()
210
+ self.num_lanes = config.num_lanes
211
+ self.dim = config.hidden_size
212
+ self.layer_idx = layer_idx
213
+
214
+ self.attn_norm = RMSNorm(self.dim, eps=config.rms_norm_eps)
215
+ self.attn = XSAGQAttention(config)
216
+
217
+ self.mlp_norm = RMSNorm(self.dim, eps=config.rms_norm_eps)
218
+ if config.swiglu_interval == 0:
219
+ self.use_swiglu = False
220
+ elif config.swiglu_interval == 1:
221
+ self.use_swiglu = True
222
+ else:
223
+ self.use_swiglu = ((layer_idx + 1) % config.swiglu_interval == 0)
224
+
225
+ if self.use_swiglu:
226
+ self.mlp = SwiGLUMLP(config)
227
+ else:
228
+ self.mlp = HadamardMLP(config)
229
+
230
+ self.lane_mix_attn = nn.Parameter(torch.eye(self.num_lanes) + 0.05 * torch.randn(self.num_lanes, self.num_lanes))
231
+ self.lane_mix_mlp = nn.Parameter(torch.eye(self.num_lanes) + 0.05 * torch.randn(self.num_lanes, self.num_lanes))
232
+
233
+ self.adaLN_modulation = nn.Sequential(
234
+ nn.SiLU(),
235
+ nn.Linear(config.hidden_size, 6 * config.hidden_size, bias=True)
236
+ )
237
+ nn.init.zeros_(self.adaLN_modulation[-1].weight)
238
+ nn.init.zeros_(self.adaLN_modulation[-1].bias)
239
+
240
+ def forward(self, lanes: torch.Tensor, t_emb: torch.Tensor, cos_h: torch.Tensor, sin_h: torch.Tensor, cos_w: torch.Tensor, sin_w: torch.Tensor) -> torch.Tensor:
241
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(t_emb).chunk(6, dim=-1)
242
+
243
+ primary = lanes[0]
244
+ normed_primary = modulate(self.attn_norm(primary), shift_msa, scale_msa)
245
+ attn_update = self.attn(normed_primary, cos_h, sin_h, cos_w, sin_w) * gate_msa.unsqueeze(1)
246
+
247
+ mixed = torch.matmul(self.lane_mix_attn, lanes.view(self.num_lanes, -1)).view_as(lanes)
248
+ lanes = torch.cat([(mixed[0] + attn_update).unsqueeze(0), mixed[1:]], dim=0)
249
+
250
+ normed_primary = modulate(self.mlp_norm(lanes[0]), shift_mlp, scale_mlp)
251
+ mlp_update = self.mlp(normed_primary) * gate_mlp.unsqueeze(1)
252
+
253
+ mixed = torch.matmul(self.lane_mix_mlp, lanes.view(self.num_lanes, -1)).view_as(lanes)
254
+ lanes = torch.cat([(mixed[0] + mlp_update).unsqueeze(0), mixed[1:]], dim=0)
255
+ return lanes
256
+
257
+ @dataclass
258
+ class DiffusionOutput(ModelOutput):
259
+ loss: Optional[torch.FloatTensor] = None
260
+ v_pred: Optional[torch.FloatTensor] = None
261
+
262
+ class TinyImageGenPreTrainedModel(PreTrainedModel):
263
+ config_class = TinyImageGenConfig
264
+ base_model_prefix = "model"
265
+ supports_gradient_checkpointing = True
266
+ _no_split_modules = ["MultiLaneBlock"]
267
+
268
+ def _init_weights(self, module):
269
+ std = self.config.initializer_range
270
+ if isinstance(module, (nn.Linear, nn.Embedding)):
271
+ module.weight.data.normal_(mean=0.0, std=std)
272
+ if hasattr(module, "bias") and module.bias is not None:
273
+ module.bias.data.zero_()
274
+ elif isinstance(module, RMSNorm):
275
+ module.weight.data.fill_(1.0)
276
+
277
+ @classmethod
278
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
279
+ config = kwargs.pop("config", None)
280
+ kwargs.pop("trust_remote_code", None)
281
+ torch_dtype = kwargs.pop("torch_dtype", None)
282
+ kwargs.pop("device_map", None)
283
+ kwargs.pop("low_cpu_mem_usage", None)
284
+
285
+ if config is None:
286
+ config = TinyImageGenConfig.from_pretrained(pretrained_model_name_or_path)
287
+
288
+ model = cls(config, *model_args)
289
+
290
+ st_file = os.path.join(pretrained_model_name_or_path, "model.safetensors")
291
+ bin_file = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin")
292
+
293
+ if os.path.exists(st_file):
294
+ state_dict = load_file(st_file)
295
+ model.load_state_dict(state_dict, strict=False)
296
+ elif os.path.exists(bin_file):
297
+ state_dict = torch.load(bin_file, map_location="cpu")
298
+ model.load_state_dict(state_dict, strict=False)
299
+ else:
300
+ return super().from_pretrained(pretrained_model_name_or_path, *model_args, config=config, **kwargs)
301
+
302
+ if torch_dtype is not None:
303
+ model.to(dtype=torch_dtype)
304
+
305
+ return model
306
+
307
+ class TinyImageGenModel(TinyImageGenPreTrainedModel):
308
+ def __init__(self, config: TinyImageGenConfig, *args, **kwargs):
309
+ super().__init__(config)
310
+ self.config = config
311
+ self.num_lanes = config.num_lanes
312
+ self.gradient_checkpointing = False
313
+
314
+ self.x_embedder = nn.Linear(config.patch_dim, config.hidden_size, bias=True)
315
+ self.t_embedder = TimestepEmbedder(config.hidden_size)
316
+ self.rotary_emb = RotaryEmbedding2D(config.head_dim, base=config.rope_theta)
317
+
318
+ self.layers = nn.ModuleList([
319
+ MultiLaneBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)
320
+ ])
321
+
322
+ self.lane_pool_weights = nn.Parameter(torch.tensor([1.0] + [0.1] * (config.num_lanes - 1)))
323
+ self.final_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
324
+ self.final_adaLN = nn.Sequential(
325
+ nn.SiLU(),
326
+ nn.Linear(config.hidden_size, 2 * config.hidden_size, bias=True)
327
+ )
328
+ self.final_proj = nn.Linear(config.hidden_size, config.patch_dim, bias=True)
329
+
330
+ nn.init.zeros_(self.final_adaLN[-1].weight)
331
+ nn.init.zeros_(self.final_adaLN[-1].bias)
332
+ nn.init.zeros_(self.final_proj.weight)
333
+ nn.init.zeros_(self.final_proj.bias)
334
+
335
+ self.post_init()
336
+
337
+ def patchify(self, x: torch.Tensor) -> torch.Tensor:
338
+ B, C, H, W = x.shape
339
+ p = self.config.patch_size
340
+ h_patches, w_patches = H // p, W // p
341
+ x = x.view(B, C, h_patches, p, w_patches, p)
342
+ x = torch.einsum("bchpwq->bhwpcq", x)
343
+ x = x.reshape(B, h_patches * w_patches, p * p * C)
344
+ return x
345
+
346
+ def unpatchify(self, x: torch.Tensor) -> torch.Tensor:
347
+ B, N, _ = x.shape
348
+ p = self.config.patch_size
349
+ h_patches = self.config.num_patches_side
350
+ w_patches = self.config.num_patches_side
351
+ c = self.config.in_channels
352
+ x = x.reshape(B, h_patches, w_patches, p, p, c)
353
+ x = torch.einsum("bhwpqc->bchpwq", x)
354
+ x = x.reshape(B, c, h_patches * p, w_patches * p)
355
+ return x
356
+
357
+ def forward(self, x_t: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
358
+ bsz = x_t.shape[0]
359
+
360
+ h0 = self.x_embedder(self.patchify(x_t))
361
+ t_emb = self.t_embedder(t)
362
+
363
+ lanes = h0.unsqueeze(0).repeat(self.num_lanes, 1, 1, 1)
364
+
365
+ cos_h, sin_h, cos_w, sin_w = self.rotary_emb(self.config.num_patches_side, self.config.num_patches_side, device=x_t.device, dtype=x_t.dtype)
366
+
367
+ for layer in self.layers:
368
+ if self.gradient_checkpointing and self.training:
369
+ lanes = cp.checkpoint(layer, lanes, t_emb, cos_h, sin_h, cos_w, sin_w, use_reentrant=False)
370
+ else:
371
+ lanes = layer(lanes, t_emb, cos_h, sin_h, cos_w, sin_w)
372
+
373
+ pool_weights = F.softmax(self.lane_pool_weights, dim=0).view(self.num_lanes, 1, 1, 1)
374
+ pooled = (lanes * pool_weights).sum(dim=0)
375
+
376
+ shift, scale = self.final_adaLN(t_emb).chunk(2, dim=-1)
377
+ out = modulate(self.final_norm(pooled), shift, scale)
378
+ out = self.final_proj(out)
379
+ return self.unpatchify(out)
380
+
381
+ @torch.no_grad()
382
+ def sample(self, num_samples: int, device: torch.device, num_steps: int = 25) -> torch.Tensor:
383
+ was_training = self.training
384
+ self.eval()
385
+ x = torch.randn((num_samples, self.config.in_channels, self.config.image_size, self.config.image_size), device=device)
386
+ dt = 1.0 / num_steps
387
+
388
+ for step in range(num_steps):
389
+ t_val = step / num_steps
390
+ t = torch.full((num_samples,), t_val, device=device, dtype=torch.float32)
391
+ v = self(x, t)
392
+ x = x + v * dt
393
+
394
+ if was_training:
395
+ self.train()
396
+ return x.clamp(-1.0, 1.0)
397
+
398
+ class TinyImageGenModelForImageDiffusion(TinyImageGenPreTrainedModel):
399
+ def __init__(self, config: TinyImageGenConfig, *args, **kwargs):
400
+ super().__init__(config)
401
+ self.model = TinyImageGenModel(config)
402
+ self.post_init()
403
+
404
+ def forward(
405
+ self,
406
+ pixel_values: Optional[torch.Tensor] = None,
407
+ x_t: Optional[torch.Tensor] = None,
408
+ t: Optional[torch.Tensor] = None,
409
+ return_dict: Optional[bool] = None,
410
+ ) -> DiffusionOutput:
411
+ return_dict = return_dict if return_dict is not None else getattr(self.config, "return_dict", True)
412
+
413
+ loss = None
414
+ v_pred = None
415
+
416
+ if pixel_values is not None:
417
+ x_1 = pixel_values
418
+ bsz = x_1.shape[0]
419
+ x_0 = torch.randn_like(x_1)
420
+ t_rand = torch.rand(bsz, device=x_1.device)
421
+ t_exp = t_rand.view(bsz, 1, 1, 1)
422
+
423
+ x_t_flow = (1.0 - t_exp) * x_0 + t_exp * x_1
424
+ v_target = x_1 - x_0
425
+
426
+ v_pred = self.model(x_t_flow, t_rand)
427
+ loss = F.mse_loss(v_pred, v_target)
428
+ elif x_t is not None and t is not None:
429
+ v_pred = self.model(x_t, t)
430
+ else:
431
+ raise ValueError("You must pass either 'pixel_values' for training or ('x_t', 't') for inference.")
432
+
433
+ if not return_dict:
434
+ return (loss, v_pred) if loss is not None else (v_pred,)
435
+
436
+ return DiffusionOutput(loss=loss, v_pred=v_pred)
437
+
438
+ @torch.no_grad()
439
+ def sample(self, num_samples: int, device: torch.device, num_steps: int = 25) -> torch.Tensor:
440
+ return self.model.sample(num_samples=num_samples, device=device, num_steps=num_steps)