KublaiKhan1 commited on
Commit
fef4fe8
·
verified ·
1 Parent(s): 5d3d16d

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -95,3 +95,4 @@ dt_nolog/810001.tmp filter=lfs diff=lfs merge=lfs -text
95
  1e-4_no_sampling/810001.tmp filter=lfs diff=lfs merge=lfs -text
96
  1e-6_no_sampling/810001.tmp filter=lfs diff=lfs merge=lfs -text
97
  2e-5_no_sampling/810001.tmp filter=lfs diff=lfs merge=lfs -text
 
 
95
  1e-4_no_sampling/810001.tmp filter=lfs diff=lfs merge=lfs -text
96
  1e-6_no_sampling/810001.tmp filter=lfs diff=lfs merge=lfs -text
97
  2e-5_no_sampling/810001.tmp filter=lfs diff=lfs merge=lfs -text
98
+ registers/810001.tmp filter=lfs diff=lfs merge=lfs -text
registers/810001.tmp ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ec4eb6c89197aa6f922b93395cea6c24714d1c38b4da1c9244f5331726ec57ff
3
+ size 2097911357
registers/log.txt ADDED
The diff for this file is too large to render. See raw diff
 
registers/model.py ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Any, Callable, Optional, Tuple, Type, Sequence, Union
3
+ import flax.linen as nn
4
+ import jax
5
+ import jax.numpy as jnp
6
+ from einops import rearrange
7
+
8
+ from flax import nnx
9
+
10
+ Array = Any
11
+ PRNGKey = Any
12
+ Shape = Tuple[int]
13
+ Dtype = Any
14
+
15
+ from math_utils import get_2d_sincos_pos_embed, modulate
16
+ from jax._src import core
17
+ from jax._src import dtypes
18
+ from jax._src.nn.initializers import _compute_fans
19
+
20
+ def xavier_uniform_pytorchlike():
21
+ def init(key, shape, dtype):
22
+ dtype = dtypes.canonicalize_dtype(dtype)
23
+ #named_shape = core.as_named_shape(shape)
24
+ if len(shape) == 2: # Dense, [in, out]
25
+ fan_in = shape[0]
26
+ fan_out = shape[1]
27
+ elif len(shape) == 4: # Conv, [k, k, in, out]. Assumes patch-embed style conv.
28
+ fan_in = shape[0] * shape[1] * shape[2]
29
+ fan_out = shape[3]
30
+ else:
31
+ raise ValueError(f"Invalid shape {shape}")
32
+
33
+ variance = 2 / (fan_in + fan_out)
34
+ scale = jnp.sqrt(3 * variance)
35
+ param = jax.random.uniform(key, shape, dtype, -1) * scale
36
+
37
+ return param
38
+ return init
39
+
40
+
41
+ class TrainConfig:
42
+ def __init__(self, dtype):
43
+ self.dtype = dtype
44
+ def kern_init(self, name='default', zero=False):
45
+ if zero or 'bias' in name:
46
+ return nn.initializers.constant(0)
47
+ return xavier_uniform_pytorchlike()
48
+ def default_config(self):
49
+ return {
50
+ 'kernel_init': self.kern_init(),
51
+ 'bias_init': self.kern_init('bias', zero=True),
52
+ 'dtype': self.dtype,
53
+ }
54
+
55
+ class TimestepEmbedder(nn.Module):
56
+ """
57
+ Embeds scalar timesteps into vector representations.
58
+ """
59
+ hidden_size: int
60
+ tc: TrainConfig
61
+ frequency_embedding_size: int = 256
62
+
63
+ @nn.compact
64
+ def __call__(self, t):
65
+ x = self.timestep_embedding(t)
66
+ x = nn.Dense(self.hidden_size, kernel_init=nn.initializers.normal(0.02),
67
+ bias_init=self.tc.kern_init('time_bias'), dtype=self.tc.dtype)(x)
68
+ x = nn.silu(x)
69
+ x = nn.Dense(self.hidden_size, kernel_init=nn.initializers.normal(0.02),
70
+ bias_init=self.tc.kern_init('time_bias'))(x)
71
+ return x
72
+
73
+ # t is between [0, 1].
74
+ def timestep_embedding(self, t, max_period=10000):
75
+ """
76
+ Create sinusoidal timestep embeddings.
77
+ :param t: a 1-D Tensor of N indices, one per batch element.
78
+ These may be fractional.
79
+ :param dim: the dimension of the output.
80
+ :param max_period: controls the minimum frequency of the embeddings.
81
+ :return: an (N, D) Tensor of positional embeddings.
82
+ """
83
+ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
84
+ t = jax.lax.convert_element_type(t, jnp.float32)
85
+ # t = t * max_period
86
+ dim = self.frequency_embedding_size
87
+ half = dim // 2
88
+ freqs = jnp.exp( -math.log(max_period) * jnp.arange(start=0, stop=half, dtype=jnp.float32) / half)
89
+ args = t[:, None] * freqs[None]
90
+ embedding = jnp.concatenate([jnp.cos(args), jnp.sin(args)], axis=-1)
91
+ embedding = embedding.astype(self.tc.dtype)
92
+ return embedding
93
+
94
+ class LabelEmbedder(nn.Module):
95
+ """
96
+ Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
97
+ """
98
+ num_classes: int
99
+ hidden_size: int
100
+ tc: TrainConfig
101
+
102
+ @nn.compact
103
+ def __call__(self, labels):
104
+ embedding_table = nn.Embed(self.num_classes + 1, self.hidden_size,
105
+ embedding_init=nn.initializers.normal(0.02), dtype=self.tc.dtype)
106
+ embeddings = embedding_table(labels)
107
+ return embeddings
108
+
109
+ class PatchEmbed(nn.Module):
110
+ """ 2D Image to Patch Embedding """
111
+ patch_size: int
112
+ hidden_size: int
113
+ tc: TrainConfig
114
+ bias: bool = True
115
+
116
+ @nn.compact
117
+ def __call__(self, x):
118
+ B, H, W, C = x.shape
119
+ patch_tuple = (self.patch_size, self.patch_size)
120
+ num_patches = (H // self.patch_size)
121
+ x = nn.Conv(self.hidden_size, patch_tuple, patch_tuple, use_bias=self.bias, padding="VALID",
122
+ kernel_init=self.tc.kern_init('patch'), bias_init=self.tc.kern_init('patch_bias', zero=True),
123
+ dtype=self.tc.dtype)(x) # (B, P, P, hidden_size)
124
+ x = rearrange(x, 'b h w c -> b (h w) c', h=num_patches, w=num_patches)
125
+ return x
126
+
127
+ class MlpBlock(nn.Module):
128
+ """Transformer MLP / feed-forward block."""
129
+ mlp_dim: int
130
+ tc: TrainConfig
131
+ out_dim: Optional[int] = None
132
+ dropout_rate: float = None
133
+ train: bool = False
134
+
135
+ @nn.compact
136
+ def __call__(self, inputs):
137
+ """It's just an MLP, so the input shape is (batch, len, emb)."""
138
+ actual_out_dim = inputs.shape[-1] if self.out_dim is None else self.out_dim
139
+ x = nn.Dense(features=self.mlp_dim, **self.tc.default_config())(inputs)
140
+ x = nn.gelu(x)
141
+ x = nn.Dropout(rate=self.dropout_rate, deterministic=(not self.train))(x)
142
+ output = nn.Dense(features=actual_out_dim, **self.tc.default_config())(x)
143
+ output = nn.Dropout(rate=self.dropout_rate, deterministic=(not self.train))(output)
144
+ return output
145
+
146
+ def modulate(x, shift, scale):
147
+ # scale = jnp.clip(scale, -1, 1)
148
+ #print("modulate input shapes", x.shape)
149
+ #print(shift.shape)
150
+ #print("scale", scale.shape)
151
+ scale = scale.reshape(x.shape[0], -1, x.shape[-1])
152
+ #print(scale.shape)
153
+ shift = shift.reshape(x.shape[0], -1, x.shape[-1])
154
+ # return x * (1 + scale[:, None]) + shift[:, None]
155
+ return x * (1 + scale) + shift
156
+
157
+ #We forgot the 1+X...
158
+
159
+ from flax import nnx
160
+ from typing import Optional
161
+ from einops import rearrange, repeat
162
+ import math
163
+
164
+ def rotate_half(x):
165
+ x = rearrange(x, '... (d r) -> ... d r', r=2)
166
+ x1, x2 = x[..., 0], x[..., 1]
167
+ x = jnp.stack((-x2, x1), axis=-1)
168
+ return rearrange(x, '... d r -> ... (d r)')
169
+
170
+ def broadcat(tensors, dim: int = -1):
171
+ num_tensors = len(tensors)
172
+ shape_lens = set(list(map(lambda t: len(t.shape), tensors)))
173
+ assert len(shape_lens) == 1, 'tensors must all have the same number of dimensions'
174
+ shape_len = list(shape_lens)[0]
175
+ dim = (dim + shape_len) if dim < 0 else dim
176
+
177
+ dims = list(zip(*map(lambda t: list(t.shape), tensors)))
178
+ expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim]
179
+ assert all([*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]), 'invalid dimensions for broadcastable concatentation'
180
+
181
+ max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims))
182
+ expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims))
183
+ expanded_dims.insert(dim, (dim, dims[dim]))
184
+
185
+ expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims)))
186
+ tensors = [jnp.broadcast_to(t, shape) for t, shape in zip(tensors, expandable_shapes)]
187
+ return jnp.concatenate(tensors, axis=dim)
188
+
189
+ class VisionRotaryEmbeddingFast(nn.Module):
190
+
191
+ dim: int
192
+ pt_seq_len: int = 16
193
+ ft_seq_len: Optional[int] = None
194
+ custom_freqs: Optional[jnp.ndarray] = None
195
+ freqs_for: str = 'lang'
196
+ theta: float = 10000.0
197
+ max_freq: float = 10.0
198
+ num_freqs: int = 1
199
+
200
+
201
+ def setup(self):
202
+ if self.custom_freqs is not None:
203
+ freqs = self.custom_freqs
204
+ elif self.freqs_for == 'lang':
205
+ freqs = 1. / (self.theta ** (jnp.arange(0, self.dim, 2)[:(self.dim // 2)].astype(jnp.float32) / self.dim))
206
+ elif self.freqs_for == 'pixel':
207
+ freqs = jnp.linspace(1., self.max_freq / 2, self.dim // 2) * math.pi
208
+ elif self.freqs_for == 'constant':
209
+ freqs = jnp.ones(self.num_freqs, dtype=jnp.float32)
210
+ else:
211
+ raise ValueError(f'unknown modality {self.freqs_for}')
212
+
213
+ ft_seq_len = self.ft_seq_len if self.ft_seq_len is not None else self.pt_seq_len
214
+ t = jnp.arange(ft_seq_len) / ft_seq_len * self.pt_seq_len
215
+
216
+ freqs = jnp.einsum('..., f -> ... f', t, freqs)
217
+ freqs = repeat(freqs, '... n -> ... (n r)', r=2)
218
+
219
+ freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim=-1)
220
+
221
+ self.freqs_cos = jnp.cos(freqs).reshape(-1, freqs.shape[-1])
222
+ self.freqs_sin = jnp.sin(freqs).reshape(-1, freqs.shape[-1])
223
+
224
+ def __call__(self, t):
225
+ # print("t shape", t.shape)
226
+ # print(self.freqs_cos.shape)
227
+ freqs_cos_expanded = self.freqs_cos[None, :, None, :] # Shape: (1, 256, 1, 64)
228
+ freqs_sin_expanded = self.freqs_sin[None, :, None, :] # Shape: (1, 256, 1, 64)
229
+
230
+ #basically for this, t just needs to be trimmed to not include registers
231
+ if True:#registers
232
+ t = t[:,:-4,:,:]
233
+ return t * freqs_cos_expanded + rotate_half(t) * freqs_sin_expanded
234
+
235
+ ################################################################################
236
+ # Core DiT Model #
237
+ #################################################################################
238
+
239
+ class DiTBlock(nn.Module):
240
+ """
241
+ A DiT block with adaptive layer norm zero (adaLN-Zero) conditioning.
242
+ """
243
+ hidden_size: int
244
+ num_heads: int
245
+ tc: TrainConfig
246
+ mlp_ratio: float = 4.0
247
+ dropout: float = 0.0
248
+ train: bool = False
249
+ rope : VisionRotaryEmbeddingFast = None
250
+
251
+
252
+ # @functools.partial(jax.checkpoint, policy=jax.checkpoint_policies.nothing_saveable)
253
+ @nn.compact
254
+ def __call__(self, x, c):
255
+ # Calculate adaLn modulation parameters.
256
+ #print("Doing adaln")
257
+ c = nn.silu(c)
258
+ c = nn.Dense(6 * self.hidden_size, **self.tc.default_config())(c)
259
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = jnp.split(c, 6, axis=-1)
260
+
261
+ # Attention Residual.
262
+ #x_norm = nn.LayerNorm(use_bias=False, use_scale=False, dtype=self.tc.dtype)(x)
263
+ x_norm = nnx.RMSNorm(self.hidden_size, use_scale=False,dtype=self.tc.dtype,rngs=nnx.Rngs(0))(x)
264
+
265
+ #print("x norm shap", x_norm.shape)
266
+ x_modulated = modulate(x_norm, shift_msa, scale_msa)
267
+
268
+ #For some reason the modulate is adding an extra dim
269
+ channels_per_head = self.hidden_size // self.num_heads
270
+ k = nn.Dense(self.hidden_size, **self.tc.default_config())(x_modulated)
271
+ q = nn.Dense(self.hidden_size, **self.tc.default_config())(x_modulated)
272
+ v = nn.Dense(self.hidden_size, **self.tc.default_config())(x_modulated)
273
+
274
+ #print("x mod shape", x_modulated.shape)
275
+ #So the issue is here with the reshape, for some reason...
276
+ #print("k shape", k.shape)#With decoupled, it is.... one side bigger, some reason?
277
+
278
+ k = jnp.reshape(k, (k.shape[0], k.shape[1], self.num_heads, channels_per_head))
279
+ q = jnp.reshape(q, (q.shape[0], q.shape[1], self.num_heads, channels_per_head))
280
+ v = jnp.reshape(v, (v.shape[0], v.shape[1], self.num_heads, channels_per_head))
281
+
282
+ #In va vae, they do soemthing else. norm q/k I think
283
+ if self.rope != None:
284
+ #print("qshape", q.shape)#1,260,12,??
285
+ q_registers = q[:,-4:,:,:]
286
+ k_registers = k[:,-4:,:,:]
287
+ q = self.rope(q)
288
+ k = self.rope(k)
289
+
290
+ q = jnp.concat((q, q_registers), axis = 1)
291
+ k = jnp.concat((k, k_registers), axis = 1)
292
+ #we don't apply rope, and thus drop the 4 tokens, so need to concat them back
293
+
294
+
295
+
296
+
297
+ q = q / q.shape[3] # (1/d) scaling.
298
+ w = jnp.einsum('bqhc,bkhc->bhqk', q, k) # [B, HW, HW, num_heads]
299
+ w = w.astype(jnp.float32)
300
+ w = nn.softmax(w, axis=-1)
301
+
302
+ y = jnp.einsum('bhqk,bkhc->bqhc', w, v) # [B, HW, num_heads, channels_per_head]
303
+ y = jnp.reshape(y, x.shape) # [B, H, W, C] (C = heads * channels_per_head)
304
+ attn_x = nn.Dense(self.hidden_size, **self.tc.default_config())(y)
305
+ #x = x + (gate_msa[:, None] * attn_x)
306
+ x = x + gate_msa.reshape(x.shape[0], -1, x.shape[-1]) * attn_x
307
+
308
+ # MLP Residual.
309
+ # x_norm2 = nn.LayerNorm(use_bias=False, use_scale=False, dtype=self.tc.dtype)(x)
310
+ x_norm2 = nnx.RMSNorm(self.hidden_size, use_scale=False,dtype=self.tc.dtype,rngs=nnx.Rngs(0))(x)
311
+
312
+ #print("Modulate 2", x_norm2.shape)
313
+ x_modulated2 = modulate(x_norm2, shift_mlp, scale_mlp)
314
+ #print(x_modulated.shape)
315
+ #mlp_x = MlpBlock(mlp_dim=int(self.hidden_size * self.mlp_ratio), tc=self.tc,
316
+ # dropout_rate=self.dropout, train=self.train)(x_modulated2)
317
+
318
+ mlp_x = SwiGLUFFN(self.hidden_size, int(2/3*self.hidden_size*self.mlp_ratio))(x_modulated2)
319
+
320
+
321
+ # x = x + (gate_mlp[:, None] * mlp_x)
322
+ x = x + gate_mlp.reshape(x.shape[0], -1,x.shape[-1]) * mlp_x
323
+ return x
324
+
325
+
326
+ class SwiGLUFFN(nn.Module):
327
+
328
+ #So they have in features, hidden, out
329
+ #Although they pass in only in and hidden
330
+ #And set out to in
331
+ #So
332
+
333
+ in_features: int
334
+ hidden_features: int
335
+
336
+ @nn.compact
337
+ def __call__(self, x):
338
+
339
+ #In compact, we just craete them and go
340
+ #We also only need to include the output size
341
+ x = nn.Dense(2*self.hidden_features, use_bias=True)(x)
342
+ x1, x2 = jnp.split(x, 2, axis = -1)
343
+ hidden = nn.silu(x1) * x2
344
+ x = nn.Dense(self.in_features, use_bias = True)(hidden)
345
+ return x
346
+
347
+
348
+ class FinalLayer(nn.Module):
349
+ """
350
+ The final layer of DiT.
351
+ """
352
+ patch_size: int
353
+ out_channels: int
354
+ hidden_size: int
355
+ tc: TrainConfig
356
+
357
+ @nn.compact
358
+ def __call__(self, x, c):
359
+ c = nn.silu(c)
360
+ c = nn.Dense(2 * self.hidden_size, kernel_init=self.tc.kern_init(zero=True),
361
+ bias_init=self.tc.kern_init('bias', zero=True), dtype=self.tc.dtype)(c)
362
+ shift, scale = jnp.split(c, 2, axis=-1)
363
+ # x = nn.LayerNorm(use_bias=False, use_scale=False, dtype=self.tc.dtype)(x)
364
+ x = nnx.RMSNorm(self.hidden_size, use_scale=False,dtype=self.tc.dtype,rngs=nnx.Rngs(0))(x)
365
+
366
+
367
+ x = modulate(x, shift, scale)
368
+ x = nn.Dense(self.patch_size * self.patch_size * self.out_channels,
369
+ kernel_init=self.tc.kern_init('final', zero=True),
370
+ bias_init=self.tc.kern_init('final_bias', zero=True), dtype=self.tc.dtype)(x)
371
+ return x
372
+
373
+ class DiT(nn.Module):
374
+ """
375
+ Diffusion model with a Transformer backbone.
376
+ """
377
+ patch_size: int
378
+ hidden_size: int
379
+ depth: int
380
+ num_heads: int
381
+ mlp_ratio: float
382
+ out_channels: int
383
+ class_dropout_prob: float
384
+ num_classes: int
385
+ ignore_dt: bool = False
386
+ dropout: float = 0.0
387
+ dtype: Dtype = jnp.bfloat16
388
+ rope : VisionRotaryEmbeddingFast = None
389
+
390
+
391
+ @nn.compact
392
+ def __call__(self, x, t, dt, y, train=False, return_activations=False):
393
+ # (x = (B, H, W, C) image, t = (B,) timesteps, y = (B,) class labels)
394
+ print("DiT: Input of shape", x.shape, "dtype", x.dtype)
395
+ activations = {}
396
+
397
+ batch_size = x.shape[0]
398
+ input_size = x.shape[1]
399
+ in_channels = x.shape[-1]
400
+ num_patches = (input_size // self.patch_size) ** 2
401
+ num_patches_side = input_size // self.patch_size
402
+
403
+
404
+ tc = TrainConfig(dtype=self.dtype)
405
+
406
+ if self.ignore_dt:
407
+ dt = jnp.zeros_like(t)
408
+
409
+ # pos_embed = self.param("pos_embed", get_2d_sincos_pos_embed, self.hidden_size, num_patches)
410
+ # pos_embed = jax.lax.stop_gradient(pos_embed)
411
+
412
+ #Extra patches for registers
413
+ pos_embed = get_2d_sincos_pos_embed(None, self.hidden_size, num_patches)
414
+
415
+ #Decoupled
416
+ s = PatchEmbed(self.patch_size, self.hidden_size, tc=tc)(x) # (B, num_patches, hidden_size)
417
+
418
+
419
+ x = PatchEmbed(self.patch_size, self.hidden_size, tc=tc)(x) # (B, num_patches, hidden_size)
420
+ print("DiT: After patch embed, shape is", x.shape, "dtype", x.dtype)
421
+ activations['patch_embed'] = x
422
+
423
+ x = x + pos_embed
424
+
425
+ if True:#registers get added here
426
+ #nobody cares about num patches now
427
+ registers = jnp.ones((x.shape[0], 4, x.shape[-1]))
428
+ x = jnp.concat((x, registers), axis = 1)
429
+
430
+
431
+
432
+ #x = x + pos_embed
433
+ x = x.astype(self.dtype)
434
+
435
+
436
+ #More decoupled
437
+ s = s + pos_embed
438
+ s = s.astype(self.dtype)
439
+
440
+ te = TimestepEmbedder(self.hidden_size, tc=tc)(t) # (B, hidden_size)
441
+ dte = TimestepEmbedder(self.hidden_size, tc=tc)(dt) # (B, hidden_size)
442
+ ye = LabelEmbedder(self.num_classes, self.hidden_size, tc=tc)(y) # (B, hidden_size)
443
+ c = te + ye + dte
444
+
445
+
446
+ activations['pos_embed'] = pos_embed
447
+ activations['time_embed'] = te
448
+ activations['dt_embed'] = dte
449
+ activations['label_embed'] = ye
450
+ activations['conditioning'] = c
451
+
452
+ print("DiT: Patch Embed of shape", x.shape, "dtype", x.dtype)
453
+ print("DiT: Conditioning of shape", c.shape, "dtype", c.dtype)
454
+
455
+ if True:#Use rope
456
+ half_head_dim = self.hidden_size // self.num_heads // 2
457
+ hw_seq_len = input_size // self.patch_size #This part is quite awkward, but it's basically just image shape - probably 16 or 32
458
+ print("selfh idden", self.hidden_size)
459
+ print("self heads", self.num_heads)
460
+ print("hw_swq", hw_seq_len)
461
+ print("xshape", x.shape)
462
+ #selfh idden 768
463
+ #self heads 12
464
+ #hw_swq 128
465
+ #xshape (1, 256, 768)
466
+ #t shape (1, 256, 12, 64)
467
+ #(16384, 64)
468
+ rope = VisionRotaryEmbeddingFast(dim=half_head_dim, pt_seq_len=hw_seq_len)
469
+
470
+
471
+ decoupled = False
472
+
473
+ #So the original decoupled code we created was wrong. Let's try normal..?
474
+ if False:#Old code
475
+ extra_depth = 0
476
+ if decoupled:
477
+ for i in range(4):#Manually set to 4
478
+ s = DiTBlock(self.hidden_size, self.num_heads, tc, self.mlp_ratio, self.dropout, train, rope)(s,c)
479
+ #I don't even know what the fucking shapes are bro....
480
+ s = nn.silu(te.reshape(s.shape[0],-1,s.shape[-1]) + dte.reshape(s.shape[0],-1,s.shape[-1]) + s)#Add conditioning back, somewhat.
481
+ if True:
482
+ c = s#Replace conditioning
483
+ else:#Instead of replacing conditioning, we will..... leave c as is?
484
+ pass
485
+ else:#Probably turn extra length to true instead
486
+ extra = True
487
+ extra_depth = 4
488
+
489
+ for i in range(self.depth + extra_depth):
490
+ x = DiTBlock(self.hidden_size, self.num_heads, tc, self.mlp_ratio, self.dropout, train, rope)(x,c)
491
+ activations[f'dit_block_{i}'] = x
492
+ if False:#decoupled new/working
493
+ for i in range(4):#Manually set to 4
494
+ s = DiTBlock(self.hidden_size, self.num_heads, tc, self.mlp_ratio, self.dropout, train, rope)(s,c)
495
+ s = nn.silu(te.reshape(s.shape[0],-1,s.shape[-1]) + dte.reshape(s.shape[0],-1,s.shape[-1]) + s)#Add conditioning back, somewhat.
496
+ if True:
497
+ c = s#Replace conditioning
498
+ for i in range(self.depth - 4):
499
+ x = DiTBlock(self.hidden_size, self.num_heads, tc, self.mlp_ratio, self.dropout, train, rope)(x,c)
500
+ activations[f'dit_block_{i}'] = x
501
+
502
+ else:#Normal
503
+ for i in range(self.depth):
504
+ x = DiTBlock(self.hidden_size, self.num_heads, tc, self.mlp_ratio, self.dropout, train, rope)(x,c)
505
+ activations[f'dit_block_{i}'] = x
506
+
507
+
508
+
509
+ x = FinalLayer(self.patch_size, self.out_channels, self.hidden_size, tc)(x, c) # (B, num_patches, p*p*c)
510
+ activations['final_layer'] = x
511
+ # print("DiT: FinalLayer of shape", x.shape, "dtype", x.dtype)
512
+ if True:#more registers
513
+ #Need to remove the registers
514
+ registers = x[:,-4:,:]
515
+ x = x[:,:-4, :]
516
+
517
+
518
+ x = jnp.reshape(x, (batch_size, num_patches_side, num_patches_side,
519
+ self.patch_size, self.patch_size, self.out_channels))
520
+ x = jnp.einsum('bhwpqc->bhpwqc', x)
521
+ x = rearrange(x, 'B H P W Q C -> B (H P) (W Q) C', H=int(num_patches_side), W=int(num_patches_side))
522
+ assert x.shape == (batch_size, input_size, input_size, self.out_channels)
523
+
524
+ t_discrete = jnp.floor(t * 256).astype(jnp.int32)
525
+ logvars = nn.Embed(256, 1, embedding_init=nn.initializers.constant(0))(t_discrete) * 100
526
+
527
+ if return_activations:
528
+ return x, logvars, activations
529
+ return x