-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathdit_blocks_test.py
More file actions
603 lines (553 loc) · 21.5 KB
/
dit_blocks_test.py
File metadata and controls
603 lines (553 loc) · 21.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
# Copyright 2026 Hackable Diffusion Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the DiT blocks."""
from hackable_diffusion.lib import test_helpers
from hackable_diffusion.lib.architecture import arch_typing
from hackable_diffusion.lib.architecture import dit_blocks
from hackable_diffusion.lib.architecture import normalization
import jax
import jax.numpy as jnp
from absl.testing import absltest
from absl.testing import parameterized
INVALID_INT = arch_typing.INVALID_INT
NormalizationType = arch_typing.NormalizationType
class DiTBlockTest(parameterized.TestCase):
"""Tests for unified DiTBlock module."""
def setUp(self):
super().setUp()
self.key = jax.random.PRNGKey(0)
self.batch, self.n, self.d, self.c = 2, 16, 32, 64
@parameterized.named_parameters(
dict(
testcase_name='rms_norm_swiglu',
norm_factory=normalization.NormalizationLayerFactory(
normalization_method=NormalizationType.RMS_NORM,
use_conditional_shift=False,
),
use_gates=False,
ffn_type='swiglu',
),
dict(
testcase_name='rms_norm_dense',
norm_factory=normalization.NormalizationLayerFactory(
normalization_method=NormalizationType.RMS_NORM,
use_conditional_shift=False,
),
use_gates=False,
ffn_type='dense',
),
dict(
testcase_name='ln_zero_swiglu',
norm_factory=normalization.NormalizationLayerFactory(
normalization_method=NormalizationType.LAYER_NORM,
use_bias=False,
use_scale=False,
),
use_gates=True,
ffn_type='swiglu',
),
dict(
testcase_name='ln_zero_dense',
norm_factory=normalization.NormalizationLayerFactory(
normalization_method=NormalizationType.LAYER_NORM,
use_bias=False,
use_scale=False,
),
use_gates=True,
ffn_type='dense',
),
)
def test_output_shape(self, norm_factory, use_gates, ffn_type):
input_shape = (self.batch, self.n, self.d)
cond_shape = (self.batch, self.c)
x = jnp.ones(input_shape)
cond = jnp.ones(cond_shape)
module = dit_blocks.DiTBlock(
hidden_size=self.d,
num_heads=4,
norm_factory=norm_factory,
use_gates=use_gates,
ffn_type=ffn_type,
)
variables = module.init(self.key, x, cond, is_training=False)
output = module.apply(variables, x, cond, is_training=False)
self.assertEqual(output.shape, input_shape)
@parameterized.named_parameters(
dict(
testcase_name='rms_norm',
norm_factory=normalization.NormalizationLayerFactory(
normalization_method=NormalizationType.RMS_NORM,
use_conditional_shift=False,
),
use_gates=False,
),
dict(
testcase_name='ln_zero',
norm_factory=normalization.NormalizationLayerFactory(
normalization_method=NormalizationType.LAYER_NORM,
use_bias=False,
use_scale=False,
),
use_gates=True,
),
)
def test_zero_init_is_identity(self, norm_factory, use_gates):
"""Tests identity-at-init."""
input_shape = (self.batch, self.n, self.d)
cond_shape = (self.batch, self.c)
x = jax.random.normal(self.key, input_shape)
cond = jnp.zeros(cond_shape)
module = dit_blocks.DiTBlock(
hidden_size=self.d,
num_heads=4,
norm_factory=norm_factory,
use_gates=use_gates,
)
variables = module.init(self.key, x, cond, is_training=False)
output = module.apply(variables, x, cond, is_training=False)
self.assertTrue(jnp.allclose(output, x, atol=1e-5))
def test_variable_shapes_ada_rms_norm(self):
"""Tests variable shapes with ada_rms_norm (SwiGLU)."""
input_shape = (self.batch, self.n, self.d)
cond_shape = (self.batch, self.c)
x = jnp.ones(input_shape)
cond = jnp.ones(cond_shape)
mlp_hidden = int(self.d * 4.0)
module = dit_blocks.DiTBlock(
hidden_size=self.d,
num_heads=4,
norm_factory=normalization.NormalizationLayerFactory(
normalization_method=NormalizationType.RMS_NORM,
use_conditional_shift=False,
),
use_gates=False,
ffn_type='swiglu',
)
variables = module.init(self.key, x, cond, is_training=False)
variables_shapes = test_helpers.get_pytree_shapes(variables)
expected_variables_shapes = {
'params': {
'ConditionalNorm_Attention': {
'Dense_0': {
'kernel': (self.c, self.d),
'bias': (self.d,),
},
'RMSNorm_0': {
'scale': (self.d,),
},
},
'ConditionalNorm_MLP': {
'Dense_0': {
'kernel': (self.c, self.d),
'bias': (self.d,),
},
'RMSNorm_0': {
'scale': (self.d,),
},
},
'ffn': {
'Dense_Up': {
'kernel': (self.d, mlp_hidden * 2),
'bias': (mlp_hidden * 2,),
},
'Dense_Down': {
'kernel': (mlp_hidden, self.d),
'bias': (self.d,),
},
},
'attn': {
'Dense_Q': {'kernel': (self.d, self.d), 'bias': (self.d,)},
'Dense_K': {'kernel': (self.d, self.d), 'bias': (self.d,)},
'Dense_V': {'kernel': (self.d, self.d), 'bias': (self.d,)},
'Dense_Output': {'kernel': (self.d, self.d), 'bias': (self.d,)},
'norm_qk_scale': (1, 1, 1, 1),
},
}
}
self.assertDictEqual(expected_variables_shapes, variables_shapes)
def test_variable_shapes_ada_ln_zero(self):
"""Tests variable shapes with ada_ln_zero (GELU)."""
input_shape = (self.batch, self.n, self.d)
cond_shape = (self.batch, self.c)
x = jnp.ones(input_shape)
cond = jnp.ones(cond_shape)
mlp_hidden = int(self.d * 4.0)
module = dit_blocks.DiTBlock(
hidden_size=self.d,
num_heads=4,
norm_factory=normalization.NormalizationLayerFactory(
normalization_method=NormalizationType.LAYER_NORM,
use_bias=False,
use_scale=False,
),
use_gates=True,
ffn_type='dense',
)
variables = module.init(self.key, x, cond, is_training=False)
variables_shapes = test_helpers.get_pytree_shapes(variables)
expected_variables_shapes = {
'params': {
'Dense_Gate_MSA': {
'kernel': (self.c, self.d),
'bias': (self.d,),
},
'Dense_Gate_MLP': {
'kernel': (self.c, self.d),
'bias': (self.d,),
},
'ConditionalNorm_Attention': {
'Dense_0': {
'kernel': (self.c, self.d * 2),
'bias': (self.d * 2,),
},
},
'ffn': {
'Dense_Up': {
'kernel': (self.d, mlp_hidden),
'bias': (mlp_hidden,),
},
'Dense_Down': {
'kernel': (mlp_hidden, self.d),
'bias': (self.d,),
},
},
'ConditionalNorm_MLP': {
'Dense_0': {
'kernel': (self.c, self.d * 2),
'bias': (self.d * 2,),
},
},
'attn': {
'Dense_Q': {'kernel': (self.d, self.d), 'bias': (self.d,)},
'Dense_K': {'kernel': (self.d, self.d), 'bias': (self.d,)},
'Dense_V': {'kernel': (self.d, self.d), 'bias': (self.d,)},
'Dense_Output': {'kernel': (self.d, self.d), 'bias': (self.d,)},
'norm_qk_scale': (1, 1, 1, 1),
},
}
}
self.assertDictEqual(expected_variables_shapes, variables_shapes)
# MARK: Validation error tests
def test_use_gates_false_without_zero_init_output_raises(self):
"""Verifies that use_gates=False with zero_init_output=False raises."""
module = dit_blocks.DiTBlock(
hidden_size=self.d,
num_heads=4,
norm_factory=normalization.NormalizationLayerFactory(
normalization_method=NormalizationType.RMS_NORM,
use_conditional_shift=False,
),
use_gates=False,
zero_init_output=False,
)
x = jnp.ones((self.batch, self.n, self.d))
cond = jnp.ones((self.batch, self.c))
with self.assertRaisesRegex(
ValueError, 'zero_init_output must be True when use_gates is False'
):
module.init(self.key, x, cond, is_training=False)
# MARK: ffn_use_bias tests
@parameterized.named_parameters(
('swiglu_no_bias', 'swiglu', False),
('swiglu_with_bias', 'swiglu', True),
('dense_no_bias', 'dense', False),
('dense_with_bias', 'dense', True),
)
def test_ffn_use_bias(self, ffn_type, ffn_use_bias):
"""Verifies that ffn_use_bias controls bias in the FFN sub-module."""
x = jnp.ones((self.batch, self.n, self.d))
cond = jnp.ones((self.batch, self.c))
module = dit_blocks.DiTBlock(
hidden_size=self.d,
num_heads=4,
norm_factory=normalization.NormalizationLayerFactory(
normalization_method=NormalizationType.RMS_NORM,
use_conditional_shift=False,
),
use_gates=False,
ffn_type=ffn_type,
ffn_use_bias=ffn_use_bias,
)
variables = module.init(self.key, x, cond, is_training=False)
leaves_with_paths = test_helpers.get_leaves_with_paths(variables)
ffn_bias_paths = [
p
for p in leaves_with_paths
if p.startswith('params/ffn/') and 'bias' in p
]
if ffn_use_bias:
self.assertLen(ffn_bias_paths, 2) # Dense_Up/bias + Dense_Down/bias
else:
self.assertEmpty(ffn_bias_paths)
class DiTBlockPresetsTest(parameterized.TestCase):
"""Tests for DiTBlock preset subclasses."""
def setUp(self):
super().setUp()
self.key = jax.random.PRNGKey(0)
self.batch, self.n, self.d, self.c = 2, 16, 32, 64
@parameterized.named_parameters(
('flux', dit_blocks.DiTBlockFlux),
('sd3', dit_blocks.DiTBlockSD3),
('ada_ln_zero', dit_blocks.DiTBlockAdaLNZero),
)
def test_preset_output_shape(self, block_cls):
"""Tests that preset subclasses produce the correct output shape."""
input_shape = (self.batch, self.n, self.d)
cond_shape = (self.batch, self.c)
x = jnp.ones(input_shape)
cond = jnp.ones(cond_shape)
module = block_cls(hidden_size=self.d, num_heads=4)
variables = module.init(self.key, x, cond, is_training=False)
output = module.apply(variables, x, cond, is_training=False)
self.assertEqual(output.shape, input_shape)
@parameterized.named_parameters(
('flux', dit_blocks.DiTBlockFlux),
('sd3', dit_blocks.DiTBlockSD3),
('ada_ln_zero', dit_blocks.DiTBlockAdaLNZero),
)
def test_preset_identity_at_init(self, block_cls):
"""Tests that preset subclasses satisfy identity-at-init."""
input_shape = (self.batch, self.n, self.d)
cond_shape = (self.batch, self.c)
x = jax.random.normal(self.key, input_shape)
cond = jnp.zeros(cond_shape)
module = block_cls(hidden_size=self.d, num_heads=4)
variables = module.init(self.key, x, cond, is_training=False)
output = module.apply(variables, x, cond, is_training=False)
self.assertTrue(jnp.allclose(output, x, atol=1e-5))
def test_flux_has_no_gates(self):
"""Verifies DiTBlockFlux has no gate parameters."""
x = jnp.ones((self.batch, self.n, self.d))
cond = jnp.ones((self.batch, self.c))
module = dit_blocks.DiTBlockFlux(hidden_size=self.d, num_heads=4)
variables = module.init(self.key, x, cond, is_training=False)
leaves_with_paths = test_helpers.get_leaves_with_paths(variables)
gate_paths = [p for p in leaves_with_paths if 'Gate' in p]
self.assertEmpty(gate_paths)
def test_sd3_has_gates(self):
"""Verifies DiTBlockSD3 has gate parameters."""
x = jnp.ones((self.batch, self.n, self.d))
cond = jnp.ones((self.batch, self.c))
module = dit_blocks.DiTBlockSD3(hidden_size=self.d, num_heads=4)
variables = module.init(self.key, x, cond, is_training=False)
leaves_with_paths = test_helpers.get_leaves_with_paths(variables)
gate_paths = [p for p in leaves_with_paths if 'Gate' in p]
self.assertNotEmpty(gate_paths)
def test_ada_ln_zero_has_gates(self):
"""Verifies DiTBlockAdaLNZero has gate parameters."""
x = jnp.ones((self.batch, self.n, self.d))
cond = jnp.ones((self.batch, self.c))
module = dit_blocks.DiTBlockAdaLNZero(hidden_size=self.d, num_heads=4)
variables = module.init(self.key, x, cond, is_training=False)
leaves_with_paths = test_helpers.get_leaves_with_paths(variables)
gate_paths = [p for p in leaves_with_paths if 'Gate' in p]
self.assertNotEmpty(gate_paths)
# MARK: qk_norm_method tests
@parameterized.named_parameters(
('l2_qk_norm_method', 'l2'),
('rms_norm_qk_norm_method', 'rms_norm'),
)
def test_preset_qk_norm_method_output_shape(self, qk_norm_method):
"""Tests that DiTBlock with each qk_norm_method produces correct shape."""
x = jnp.ones((self.batch, self.n, self.d))
cond = jnp.ones((self.batch, self.c))
module = dit_blocks.DiTBlock(
hidden_size=self.d,
num_heads=4,
norm_factory=normalization.NormalizationLayerFactory(
normalization_method=NormalizationType.RMS_NORM,
use_conditional_shift=False,
),
use_gates=False,
attn_normalize_qk=True,
attn_qk_norm_method=qk_norm_method,
)
variables = module.init(self.key, x, cond, is_training=False)
output = module.apply(variables, x, cond, is_training=False)
self.assertEqual(output.shape, (self.batch, self.n, self.d))
def test_flux_uses_rms_norm_qk(self):
"""Verifies DiTBlockFlux uses RMSNorm QK normalization."""
x = jnp.ones((self.batch, self.n, self.d))
cond = jnp.ones((self.batch, self.c))
module = dit_blocks.DiTBlockFlux(hidden_size=self.d, num_heads=4)
variables = module.init(self.key, x, cond, is_training=False)
leaves = test_helpers.get_leaves_with_paths(variables)
# Flux uses rms_norm method: should have RMSNorm_Q/K, no norm_qk_scale
rms_paths = [p for p in leaves if 'RMSNorm_Q' in p or 'RMSNorm_K' in p]
self.assertNotEmpty(rms_paths)
l2_paths = [p for p in leaves if 'norm_qk_scale' in p]
self.assertEmpty(l2_paths)
def test_sd3_uses_rms_norm_qk(self):
"""Verifies DiTBlockSD3 uses RMSNorm QK normalization."""
x = jnp.ones((self.batch, self.n, self.d))
cond = jnp.ones((self.batch, self.c))
module = dit_blocks.DiTBlockSD3(hidden_size=self.d, num_heads=4)
variables = module.init(self.key, x, cond, is_training=False)
leaves = test_helpers.get_leaves_with_paths(variables)
# SD3 uses rms_norm method: should have RMSNorm_Q/K, no norm_qk_scale
rms_paths = [p for p in leaves if 'RMSNorm_Q' in p or 'RMSNorm_K' in p]
self.assertNotEmpty(rms_paths)
l2_paths = [p for p in leaves if 'norm_qk_scale' in p]
self.assertEmpty(l2_paths)
def test_ada_ln_zero_has_no_qk_norm(self):
"""Verifies DiTBlockAdaLNZero has no QK normalization params."""
x = jnp.ones((self.batch, self.n, self.d))
cond = jnp.ones((self.batch, self.c))
module = dit_blocks.DiTBlockAdaLNZero(hidden_size=self.d, num_heads=4)
variables = module.init(self.key, x, cond, is_training=False)
leaves = test_helpers.get_leaves_with_paths(variables)
norm_paths = [
p
for p in leaves
if 'norm_qk' in p or 'RMSNorm_Q' in p or 'RMSNorm_K' in p
]
self.assertEmpty(norm_paths)
def test_dit_block_no_attn_bias_with_rms_norm_qk(self):
"""Verifies DiTBlock with use_bias=False and rms_norm QK norm."""
x = jnp.ones((self.batch, self.n, self.d))
cond = jnp.ones((self.batch, self.c))
module = dit_blocks.DiTBlock(
hidden_size=self.d,
num_heads=4,
norm_factory=normalization.NormalizationLayerFactory(
normalization_method=NormalizationType.RMS_NORM,
use_conditional_shift=False,
),
use_gates=False,
attn_normalize_qk=True,
attn_qk_norm_method='rms_norm',
attn_use_bias=False,
)
variables = module.init(self.key, x, cond, is_training=False)
leaves = test_helpers.get_leaves_with_paths(variables)
# No bias in attention
attn_bias_paths = [
p for p in leaves if p.startswith('params/attn/') and 'bias' in p
]
self.assertEmpty(attn_bias_paths)
# Has RMSNorm_Q/K
rms_paths = [p for p in leaves if 'RMSNorm_Q' in p or 'RMSNorm_K' in p]
self.assertNotEmpty(rms_paths)
class PositionalEmbeddingTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.key = jax.random.PRNGKey(0)
self.batch, self.n, self.d = 2, 16, 32
def test_output_shape(self):
input_shape = (self.batch, self.n, self.d)
x = jnp.ones(input_shape)
module = dit_blocks.PositionalEmbedding()
variables = module.init(self.key, x)
output = module.apply(variables, x)
self.assertEqual(output.shape, input_shape)
def test_variable_shapes(self):
input_shape = (self.batch, self.n, self.d)
x = jnp.ones(input_shape)
module = dit_blocks.PositionalEmbedding()
variables = module.init(self.key, x)
variables_shapes = test_helpers.get_pytree_shapes(variables)
expected_variables_shapes = {
'params': {
'PositionalEmbeddingTensor': (1, self.n, self.d),
}
}
self.assertDictEqual(expected_variables_shapes, variables_shapes)
class PatchifyTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.key = jax.random.PRNGKey(0)
self.batch, self.h, self.w, self.c = 2, 16, 16, 3
self.patch_size = (4, 4)
self.embedding_dim = 64
def test_output_shape(self):
x = jnp.ones((self.batch, self.h, self.w, self.c))
module = dit_blocks.Patchify(
patch_size=self.patch_size, embedding_dim=self.embedding_dim
)
variables = module.init(self.key, x)
output = module.apply(variables, x)
expected_n = (self.h // self.patch_size[0]) * (self.w // self.patch_size[1])
self.assertEqual(output.shape, (self.batch, expected_n, self.embedding_dim))
def test_raises_error_on_non_divisible_shape(self):
x = jnp.ones((self.batch, self.h + 1, self.w, self.c))
module = dit_blocks.Patchify(
patch_size=self.patch_size, embedding_dim=self.embedding_dim
)
with self.assertRaises(
ValueError,
msg=(
f'Height {self.h} must be divisible by patch height'
f' {self.patch_size[0]}.Width {self.w} must be divisible by patch'
f' width {self.patch_size[1]}.'
),
):
module.init(self.key, x)
def test_variable_shapes(self):
x = jnp.ones((self.batch, self.h, self.w, self.c))
module = dit_blocks.Patchify(
patch_size=self.patch_size, embedding_dim=self.embedding_dim
)
variables = module.init(self.key, x)
variables_shapes = test_helpers.get_pytree_shapes(variables)
expected_variables_shapes = {
'params': {
'Dense_Project': {
'kernel': (
self.patch_size[0] * self.patch_size[1] * self.c,
self.embedding_dim,
),
'bias': (self.embedding_dim,),
}
}
}
self.assertDictEqual(expected_variables_shapes, variables_shapes)
class DePatchifyTest(parameterized.TestCase):
def setUp(self):
super().setUp()
self.key = jax.random.PRNGKey(0)
self.batch, self.h, self.w, self.c = 2, 16, 16, 3
self.patch_size = (4, 4)
self.embedding_dim = 64
def test_output_shape(self):
n = (self.h // self.patch_size[0]) * (self.w // self.patch_size[1])
x = jnp.ones((self.batch, n, self.embedding_dim))
module = dit_blocks.DePatchify(
patch_size=self.patch_size, output_shape=(self.h, self.w, self.c)
)
variables = module.init(self.key, x)
output = module.apply(variables, x)
self.assertEqual(output.shape, (self.batch, self.h, self.w, self.c))
def test_variable_shapes(self):
n = (self.h // self.patch_size[0]) * (self.w // self.patch_size[1])
x = jnp.ones((self.batch, n, self.embedding_dim))
module = dit_blocks.DePatchify(
patch_size=self.patch_size,
output_shape=(self.h, self.w, self.c),
)
variables = module.init(self.key, x)
variables_shapes = test_helpers.get_pytree_shapes(variables)
expected_variables_shapes = {
'params': {
'Dense_Out': {
'kernel': (
self.embedding_dim,
self.patch_size[0] * self.patch_size[1] * self.c,
),
'bias': (self.patch_size[0] * self.patch_size[1] * self.c,),
},
}
}
self.assertDictEqual(expected_variables_shapes, variables_shapes)
if __name__ == '__main__':
absltest.main()