-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfq_models.py
More file actions
2247 lines (1868 loc) · 92.5 KB
/
fq_models.py
File metadata and controls
2247 lines (1868 loc) · 92.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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from pathlib import Path
from functools import partial
from collections import defaultdict
from collections import OrderedDict
import math
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import torchvision.utils as vision_utils
import lpips
from torchinfo import summary
from torch.utils.data import DataLoader, random_split
import os
from einops import rearrange
from torch.nn.utils import spectral_norm
def compute_entropy_loss(affinity, loss_type="softmax", temperature=0.01):
flat_affinity = affinity.reshape(-1, affinity.shape[-1])
flat_affinity /= temperature
probs = F.softmax(flat_affinity, dim=-1)
log_probs = F.log_softmax(flat_affinity + 1e-5, dim=-1)
if loss_type == "softmax":
target_probs = probs
else:
raise ValueError("Entropy loss {} not supported".format(loss_type))
avg_probs = torch.mean(target_probs, dim=0)
avg_entropy = - torch.sum(avg_probs * torch.log(avg_probs + 1e-5))
sample_entropy = - torch.mean(torch.sum(target_probs * log_probs, dim=-1))
loss = sample_entropy - avg_entropy
return loss
class FQVectorQuantizer(nn.Module):
def __init__(self, n_e, e_dim, beta, entropy_loss_ratio, l2_norm, show_usage):
super().__init__()
# Same initialization as original
self.n_e = n_e
self.e_dim = e_dim
self.beta = beta
self.entropy_loss_ratio = entropy_loss_ratio
self.l2_norm = l2_norm
self.show_usage = show_usage
self.embedding = nn.Embedding(self.n_e, self.e_dim)
self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e)
if self.l2_norm:
self.embedding.weight.data = F.normalize(self.embedding.weight.data, p=2, dim=-1)
if self.show_usage:
self.register_buffer("codebook_used", nn.Parameter(torch.zeros(65536)))
def forward(self, z):
# reshape z -> (batch, height, width, depth, channel) and flatten
z = torch.einsum('b c h w d -> b h w d c', z).contiguous() # Changed permute to handle 3D
z_flattened = z.view(-1, self.e_dim)
if self.l2_norm:
z = F.normalize(z, p=2, dim=-1)
z_flattened = F.normalize(z_flattened, p=2, dim=-1)
embedding = F.normalize(self.embedding.weight, p=2, dim=-1)
else:
embedding = self.embedding.weight
d = torch.sum(z_flattened ** 2, dim=1, keepdim=True) + \
torch.sum(embedding**2, dim=1) - 2 * \
torch.einsum('bd,dn->bn', z_flattened, torch.einsum('n d -> d n', embedding))
min_encoding_indices = torch.argmin(d, dim=1)
z_q = embedding[min_encoding_indices].view(z.shape)
# Rest of the function remains the same
perplexity = None
min_encodings = None
vq_loss = None
commit_loss = None
entropy_loss = None
codebook_usage = 0
if self.show_usage and self.training:
cur_len = min_encoding_indices.shape[0]
self.codebook_used[:-cur_len] = self.codebook_used[cur_len:].clone()
self.codebook_used[-cur_len:] = min_encoding_indices
codebook_usage = len(torch.unique(self.codebook_used)) / self.n_e
if self.training:
vq_loss = torch.mean((z_q - z.detach()) ** 2)
commit_loss = self.beta * torch.mean((z_q.detach() - z) ** 2)
entropy_loss = self.entropy_loss_ratio * compute_entropy_loss(-d)
# preserve gradients
z_q = z + (z_q - z).detach()
# reshape back to match original input shape
z_q = torch.einsum('b h w d c -> b c h w d', z_q) # Changed permute to handle 3D
return z_q, (vq_loss, commit_loss, entropy_loss, codebook_usage), (perplexity, min_encodings, min_encoding_indices)
def get_codebook_entry(self, indices, shape=None, channel_first=True):
# shape = (batch, channel, height, width, depth) if channel_first else (batch, height, width, depth, channel)
if self.l2_norm:
embedding = F.normalize(self.embedding.weight, p=2, dim=-1)
else:
embedding = self.embedding.weight
z_q = embedding[indices]
if shape is not None:
if channel_first:
z_q = z_q.reshape(shape[0], shape[2], shape[3], shape[4], shape[1])
# reshape back to match original input shape
z_q = z_q.permute(0, 4, 1, 2, 3).contiguous()
else:
z_q = z_q.view(shape)
return z_q
class FQEMAVectorQuantizer(nn.Module):
def __init__(self, n_e, e_dim, decay=0.99, eps=1e-5, l2_norm=False):
super().__init__()
self.n_e = n_e # Number of embeddings
self.e_dim = e_dim # Embedding dimension
self.decay = decay # EMA decay factor (higher = slower updates)
self.eps = eps # Small constant for numerical stability
self.l2_norm = l2_norm # Whether to normalize embeddings
# Initialize embeddings - use uniform initialization like in FQVectorQuantizer
embedding = torch.randn(n_e, e_dim)
if l2_norm:
embedding = F.normalize(embedding, p=2, dim=-1)
# Initialize EMA tracking variables
self.register_buffer('cluster_size', torch.zeros(n_e))
self.register_buffer('embedding_avg', embedding.clone())
self.register_buffer('embedding', embedding)
self.register_buffer('codebook_used', torch.zeros(65536)) # For usage tracking
def forward(self, z):
# Reshape z -> (batch, height, width, depth, channel) and flatten
z = torch.einsum('b c h w d -> b h w d c', z).contiguous()
z_flattened = z.view(-1, self.e_dim)
# Apply L2 normalization if specified
if self.l2_norm:
z_flattened = F.normalize(z_flattened, p=2, dim=-1)
embedding = F.normalize(self.embedding, p=2, dim=-1)
else:
embedding = self.embedding
# Compute distances
d = torch.sum(z_flattened ** 2, dim=1, keepdim=True) + \
torch.sum(embedding ** 2, dim=1) - \
2 * torch.einsum('bd,nd->bn', z_flattened, embedding)
# Find nearest codebook entries
encoding_indices = torch.argmin(d, dim=1)
encodings = F.one_hot(encoding_indices, self.n_e).type_as(z_flattened)
# Track codebook usage
if self.training:
cur_len = encoding_indices.shape[0]
self.codebook_used[:-cur_len] = self.codebook_used[cur_len:].clone()
self.codebook_used[-cur_len:] = encoding_indices
codebook_usage = len(torch.unique(self.codebook_used)) / self.n_e
else:
codebook_usage = 0
# EMA update of embeddings - only in training mode
if self.training:
n_total = encodings.sum(0)
self.cluster_size.data.mul_(self.decay).add_(n_total, alpha=1 - self.decay)
# Update embedding average
dw = torch.matmul(encodings.t(), z_flattened)
self.embedding_avg.data.mul_(self.decay).add_(dw, alpha=1 - self.decay)
# Update the embedding with EMA
n = self.cluster_size.sum()
cluster_size = (self.cluster_size + self.eps) / (n + self.n_e * self.eps) * n
# Update embedding weights with normalized averages
embed_normalized = self.embedding_avg / cluster_size.unsqueeze(1)
self.embedding.data.copy_(embed_normalized)
# Apply L2 norm to updated embeddings if needed
if self.l2_norm:
self.embedding.data = F.normalize(self.embedding.data, p=2, dim=-1)
# Get quantized latent vectors
z_q = torch.matmul(encodings, embedding)
z_q = z_q.view(z.shape)
# IMPORTANT: Implement straight-through estimator
# This is crucial for gradient flow in the encoder
z_q = z + (z_q - z).detach()
# Reshape back to match original input shape
z_q = torch.einsum('b h w d c -> b c h w d', z_q)
# Return in the same format as FQVectorQuantizer, but with zeros for losses
# The EMA update doesn't need explicit gradient-based losses
vq_loss = torch.tensor(0.0, device=z.device)
commit_loss = torch.tensor(0.0, device=z.device)
entropy_loss = torch.tensor(0.0, device=z.device)
return z_q, (vq_loss, commit_loss, entropy_loss, codebook_usage), (None, None, encoding_indices)
def get_codebook_entry(self, indices, shape=None, channel_first=True):
# Get quantized latents
embedding = self.embedding
if self.l2_norm:
embedding = F.normalize(embedding, p=2, dim=-1)
z_q = embedding[indices]
if shape is not None:
if channel_first:
z_q = z_q.reshape(shape[0], shape[2], shape[3], shape[4], shape[1])
# reshape back to match original input shape
z_q = z_q.permute(0, 4, 1, 2, 3).contiguous()
else:
z_q = z_q.view(shape)
return z_q
class ResidualAttentionBlock(nn.Module):
def __init__(
self,
d_model,
n_head,
mlp_ratio=4.0,
act_layer=nn.GELU,
norm_layer=nn.LayerNorm
):
super().__init__()
self.ln_1 = norm_layer(d_model)
self.attn = nn.MultiheadAttention(d_model, n_head)
self.mlp_ratio = mlp_ratio
if mlp_ratio > 0:
self.ln_2 = norm_layer(d_model)
mlp_width = int(d_model * mlp_ratio)
self.mlp = nn.Sequential(OrderedDict([
("c_fc", nn.Linear(d_model, mlp_width)),
("gelu", act_layer()),
("c_proj", nn.Linear(mlp_width, d_model))
]))
def attention(self, x: torch.Tensor):
return self.attn(x, x, x, need_weights=False)[0]
def forward(self, x: torch.Tensor):
attn_output = self.attention(x=self.ln_1(x))
x = x + attn_output
if self.mlp_ratio > 0:
x = x + self.mlp(self.ln_2(x))
return x
class FactorizedAdapter(nn.Module):
def __init__(self, resolution, down_factor):
super().__init__()
# Modified for 3D: grid_size now represents volume size
self.grid_size = resolution // down_factor # volume size // down-sample ratio
self.width = 256 # same dim as VQ encoder output
self.num_layers = 6
self.num_heads = 8
scale = self.width ** -0.5
# Modified for 3D: positional embedding now handles cubic volume
self.positional_embedding = nn.Parameter(scale * torch.randn(self.grid_size ** 3, self.width))
self.ln_pre = nn.LayerNorm(self.width)
self.transformer = nn.ModuleList([
ResidualAttentionBlock(self.width, self.num_heads, mlp_ratio=4.0)
for _ in range(self.num_layers)
])
self.ln_post = nn.LayerNorm(self.width)
def forward(self, x):
# Modified for 3D: reshape from 5D to sequence
h = x.shape[-1] # depth dimension
x = rearrange(x, 'b c h w d -> b (h w d) c') # flatten 3D volume to sequence
x = x + self.positional_embedding.to(x.dtype)
x = self.ln_pre(x)
x = x.permute(1, 0, 2) # NLD -> LND
for transformer in self.transformer:
x = transformer(x)
x = x.permute(1, 0, 2) # LND -> NLD
x = self.ln_post(x)
# Modified for 3D: reshape back to 5D
x = rearrange(
x,
'b (h w d) c -> b c h w d',
h=self.grid_size,
w=self.grid_size,
d=self.grid_size
)
return x
class Downsample(nn.Module):
def __init__(self, in_channels, padding_mode='constant'):
super().__init__()
self.padding_mode = padding_mode
self.conv = torch.nn.Conv3d(in_channels, in_channels, kernel_size=3, stride=2, padding=0)
def forward(self, x):
pad = (0, 1, 0, 1, 0, 1) # Padding for all 3 dimensions
# x = torch.nn.functional.pad(x, pad, mode="constant", value=0) # padding the right and the bottom with 0s
x = torch.nn.functional.pad(x, pad, mode=self.padding_mode) # padding the right and the bottom with 0s
x = self.conv(x)
return x
class Upsample(nn.Module):
def __init__(self, in_channels, padding_mode='zeros'):
super().__init__()
self.conv = nn.Conv3d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, padding_mode=padding_mode)
def forward(self, x):
x = F.interpolate(x, scale_factor=2.0, mode="nearest")
x = self.conv(x)
return x
def normalize(in_channels, num_groups=32):
return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True) # divides the channels into 32 groups, and normalizes each group. More effective for smaller batch size than batch norm
@torch.jit.script
def swish(x):
return x*torch.sigmoid(x) # swish activation function, compiled using torch.jit.script. Smooth, non-linear activation function, works better than ReLu in some cases. swish (x) = x * sigmoid(x)
class ResBlock(nn.Module):
def __init__(self, in_channels, out_channels=None, num_groups=32, padding_mode='zeros'):
super(ResBlock, self).__init__()
self.in_channels = in_channels
self.out_channels = in_channels if out_channels is None else out_channels
self.norm1 = normalize(in_channels, num_groups) # Pass num_groups here
self.conv1 = nn.Conv3d(in_channels, out_channels, kernel_size=3, stride=1, padding=1, padding_mode=padding_mode)
self.norm2 = normalize(out_channels, num_groups) # Pass num_groups here
self.conv2 = nn.Conv3d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, padding_mode=padding_mode)
self.conv_out = nn.Conv3d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
def forward(self, x_in):
x = x_in
x = self.norm1(x)
x = swish(x)
x = self.conv1(x)
x = self.norm2(x)
x = swish(x)
x = self.conv2(x)
if self.in_channels != self.out_channels:
x_in = self.conv_out(x_in)
return x + x_in
class AttnBlock(nn.Module):
def __init__(self, in_channels):
super().__init__()
self.in_channels = in_channels
self.norm = normalize(in_channels)
# Convert all 2D convolutions to 3D
self.q = torch.nn.Conv3d(
in_channels,
in_channels,
kernel_size=1,
stride=1,
padding=0
)
self.k = torch.nn.Conv3d(
in_channels,
in_channels,
kernel_size=1,
stride=1,
padding=0
)
self.v = torch.nn.Conv3d(
in_channels,
in_channels,
kernel_size=1,
stride=1,
padding=0
)
self.proj_out = torch.nn.Conv3d(
in_channels,
in_channels,
kernel_size=1,
stride=1,
padding=0
)
def forward(self, x):
h_ = x
h_ = self.norm(h_)
q = self.q(h_)
k = self.k(h_)
v = self.v(h_)
# compute attention
b, c, h, w, d = q.shape
q = q.reshape(b, c, h*w*d) # Flatten all spatial dimensions
q = q.permute(0, 2, 1) # b, hwd, c
k = k.reshape(b, c, h*w*d) # b, c, hwd
w_ = torch.bmm(q, k) # b, hwd, hwd
w_ = w_ * (int(c)**(-0.5)) # Scale dot products
w_ = F.softmax(w_, dim=2) # Softmax over spatial positions
# attend to values
v = v.reshape(b, c, h*w*d)
w_ = w_.permute(0, 2, 1) # b, hwd, hwd (first hwd of k, second of q)
h_ = torch.bmm(v, w_) # b, c, hwd
h_ = h_.reshape(b, c, h, w, d) # Restore spatial structure
h_ = self.proj_out(h_)
return x + h_
def Normalize(in_channels, norm_type='group'):
assert norm_type in ['group', 'batch']
if norm_type == 'group':
return nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
elif norm_type == 'batch':
return nn.SyncBatchNorm(in_channels)
def nonlinearity(x):
# swish
return x*torch.sigmoid(x)
class Encoder(nn.Module):
def __init__(self, in_channels, nf, out_channels, ch_mult, num_res_blocks, resolution, padding_mode='zeros'):
super().__init__()
self.nf = nf
self.num_resolutions = len(ch_mult)
self.num_res_blocks = num_res_blocks
self.resolution = resolution
self.conv_in = nn.Conv3d(in_channels, nf, kernel_size=3, stride=1, padding=1, padding_mode=padding_mode)
in_ch_mult = (1,) + tuple(ch_mult)
self.conv_blocks = nn.ModuleList()
for i_level in range(self.num_resolutions):
conv_block = nn.Module()
# res & attn
res_block = nn.ModuleList()
attn_block = nn.ModuleList()
block_in = nf * in_ch_mult[i_level]
block_out = nf * ch_mult[i_level]
for _ in range(self.num_res_blocks):
res_block.append(ResBlock(block_in, block_out, padding_mode=padding_mode))
block_in = block_out
if i_level == self.num_resolutions - 1:
attn_block.append(AttnBlock(block_in))
conv_block.res = res_block
conv_block.attn = attn_block
# downsample
if i_level != self.num_resolutions-1:
conv_block.downsample = Downsample(block_in)
self.conv_blocks.append(conv_block)
# middle
self.mid = nn.ModuleList()
self.mid.append(ResBlock(block_in, block_in, padding_mode=padding_mode))
self.mid.append(AttnBlock(block_in))
self.mid.append(ResBlock(block_in, block_in, padding_mode=padding_mode))
if self.num_resolutions == 5:
down_factor = 16
elif self.num_resolutions == 4:
down_factor = 8
elif self.num_resolutions == 3:
down_factor = 4
else:
raise NotImplementedError
# semantic head
self.style_head = nn.ModuleList()
self.style_head.append(FactorizedAdapter(self.resolution, down_factor))
# structural details head
self.structure_head = nn.ModuleList()
self.structure_head.append(FactorizedAdapter(self.resolution, down_factor))
# end
self.norm_out_style = Normalize(block_in)
self.conv_out_style = nn.Conv3d(block_in, out_channels, kernel_size=3, stride=1, padding=1, padding_mode=padding_mode)
self.norm_out_struct = Normalize(block_in)
self.conv_out_struct = nn.Conv3d(block_in, out_channels, kernel_size=3, stride=1, padding=1, padding_mode=padding_mode)
# blocks = []
# # Initial convolution - now 3D
# blocks.append(
# nn.Conv3d(
# in_channels,
# nf,
# kernel_size=3,
# stride=1,
# padding=1
# )
# )
# # Residual and downsampling blocks, with attention on specified resolutions
# for i in range(self.num_resolutions):
# block_in_ch = nf * in_ch_mult[i]
# block_out_ch = nf * ch_mult[i]
# # Add ResBlocks
# for _ in range(self.num_res_blocks):
# blocks.append(ResBlock(block_in_ch, block_out_ch))
# block_in_ch = block_out_ch
# # Add attention if we're at the right resolution
# if curr_res in attn_resolutions:
# blocks.append(AttnBlock(block_in_ch))
# # Add downsampling block if not the last resolution
# if i != self.num_resolutions - 1:
# blocks.append(Downsample(block_in_ch))
# curr_res = curr_res // 2
# # Final blocks
# blocks.append(ResBlock(block_in_ch, block_in_ch))
# blocks.append(AttnBlock(block_in_ch))
# blocks.append(ResBlock(block_in_ch, block_in_ch))
# # Normalize and convert to latent size
# blocks.append(normalize(block_in_ch))
# blocks.append(
# nn.Conv3d(
# block_in_ch,
# out_channels,
# kernel_size=3,
# stride=1,
# padding=1
# )
# )
def forward(self, x):
h = self.conv_in(x)
# downsampling
for i_level, block in enumerate(self.conv_blocks):
for i_block in range(self.num_res_blocks):
h = block.res[i_block](h)
if len(block.attn) > 0:
h = block.attn[i_block](h)
if i_level != self.num_resolutions - 1:
h = block.downsample(h)
# middle
for mid_block in self.mid:
h = mid_block(h)
h_style = h
h_struct = h
# style head
for blk in self.style_head:
h_style = blk(h_style)
h_style = self.norm_out_style(h_style)
h_style = nonlinearity(h_style)
h_style = self.conv_out_style(h_style)
# structure head
for blk in self.structure_head:
h_struct = blk(h_struct)
h_struct = self.norm_out_struct(h_struct)
h_struct = nonlinearity(h_struct)
h_struct = self.conv_out_struct(h_struct)
return h_style, h_struct
# for block in self.blocks:
# x = block(x)
# return x
class Generator(nn.Module):
def __init__(self, H, z_channels=256):
super().__init__()
self.nf = H.nf
self.ch_mult = H.ch_mult
self.num_resolutions = len(self.ch_mult)
self.num_res_blocks = H.res_blocks
self.resolution = H.img_size
self.attn_resolutions = H.attn_resolutions
self.in_channels = H.emb_dim
self.out_channels = H.n_channels
block_in = self.nf * self.ch_mult[self.num_resolutions-1]
# z to block_in
# self.conv_in = nn.Conv3d(z_channels * 2, block_in, kernel_size=3, stride=1, padding=1)
#TODO: trying addition instead of concat
self.conv_in = nn.Conv3d(z_channels, block_in, kernel_size=3, stride=1, padding=1)
# middle
self.mid = nn.ModuleList()
self.mid.append(ResBlock(block_in, block_in))
# self.mid.append(AttnBlock(block_in))
self.mid.append(ResBlock(block_in, block_in))
# upsampling
self.conv_blocks = nn.ModuleList()
for i_level in reversed(range(self.num_resolutions)):
conv_block = nn.Module()
# res & attn
res_block = nn.ModuleList()
attn_block = nn.ModuleList()
block_out = self.nf * self.ch_mult[i_level]
for _ in range(self.num_res_blocks + 1):
res_block.append(ResBlock(block_in, block_out))
block_in = block_out
if i_level == self.num_resolutions - 1:
attn_block.append(AttnBlock(block_in))
conv_block.res = res_block
conv_block.attn = attn_block
# downsample
if i_level != 0:
conv_block.upsample = Upsample(block_in)
self.conv_blocks.append(conv_block)
# end
self.norm_out = Normalize(block_in)
self.conv_out = nn.Conv3d(block_in, H.n_channels, kernel_size=3, stride=1, padding=1)
@property
def last_layer(self):
return self.conv_out.weight
def forward(self, z):
#TODO: trying addition instead of concat
B, C, H, W, D = z.shape
z_style = z[:, :C//2] # First half of channels
z_struct = z[:, C//2:] # Second half of channels
# Add the vectors
z_add = z_style + z_struct
# z to block_in
h = self.conv_in(z_add)
# middle
for mid_block in self.mid:
h = mid_block(h)
# upsampling
for i_level, block in enumerate(self.conv_blocks):
for i_block in range(self.num_res_blocks + 1):
h = block.res[i_block](h)
if len(block.attn) > 0:
h = block.attn[i_block](h)
if i_level != self.num_resolutions - 1:
h = block.upsample(h)
# end
h = self.norm_out(h)
h = nonlinearity(h)
h = self.conv_out(h)
return h
class TwoStageGenerator(nn.Module):
def __init__(self, H):
super().__init__()
self.nf = H.nf
self.ch_mult = H.ch_mult
self.num_resolutions = len(self.ch_mult)
self.num_res_blocks = H.res_blocks
self.combine_method = H.combine_method
self.resolution = H.img_size
self.detach = H.detach_binary_recon
if self.detach:
print("Detaching binary reconstruction from comp graph for final loss")
# First stage: structure codes -> binary map
block_in = self.nf * self.ch_mult[self.num_resolutions-1]
# Structure decoder (similar to current Generator but outputs single channel)
self.struct_conv_in = nn.Conv3d(H.z_channels, block_in, kernel_size=3, stride=1, padding=1)
# Middle blocks for structure
self.struct_mid = nn.ModuleList([
ResBlock(block_in, block_in),
ResBlock(block_in, block_in)
])
# Upsampling blocks for structure
self.struct_up_blocks = nn.ModuleList()
for i_level in reversed(range(self.num_resolutions)):
up_block = nn.Module()
res_block = nn.ModuleList()
block_out = self.nf * self.ch_mult[i_level]
for _ in range(self.num_res_blocks + 1):
res_block.append(ResBlock(block_in, block_out))
block_in = block_out
if i_level != 0:
up_block.upsample = Upsample(block_in)
up_block.res = res_block
self.struct_up_blocks.append(up_block)
# Final layers for binary output
self.struct_norm_out = Normalize(block_in)
self.struct_conv_out = nn.Conv3d(block_in, 1, kernel_size=3, stride=1, padding=1)
# Calculate combined channels
if self.combine_method == 'concat':
combined_channels = 1 + H.z_channels # 33 channels
else: # multiply
combined_channels = block_in
# Just use a single conv layer to map from combined_channels to block_in
self.initial_conv = nn.Conv3d(combined_channels, block_in, kernel_size=3, stride=1, padding=1)
# Then process with regular blocks using standard grouping
self.final_blocks = nn.ModuleList([
ResBlock(block_in, block_in), # Now everything uses block_in channels
ResBlock(block_in, block_in)
])
self.norm_out = normalize(block_in)
self.conv_out = nn.Conv3d(block_in, H.n_channels, kernel_size=3, stride=1, padding=1)
def forward(self, z):
# Split input into structure and style codes
B, C, H, W, D = z.shape
z_struct = z[:, :C//2] # First half of channels
z_style = z[:, C//2:] # Second half of channels
# Structure path
h_struct = self.struct_conv_in(z_struct)
for mid_block in self.struct_mid:
h_struct = mid_block(h_struct)
for block in self.struct_up_blocks:
for res_block in block.res:
h_struct = res_block(h_struct)
if hasattr(block, 'upsample'):
h_struct = block.upsample(h_struct)
h_struct = self.struct_norm_out(h_struct)
h_struct = nonlinearity(h_struct)
binary_out = self.struct_conv_out(h_struct)
binary_out = torch.sigmoid(binary_out) # Convert to probabilities
# Simply upsample style codes to match spatial dimensions
h_style = F.interpolate(z_style, size=(self.resolution, self.resolution, self.resolution), mode='trilinear', align_corners=False)
if self.detach:
detached_binary_out = binary_out.detach()
# --- Combine (Identical) ---
if self.combine_method == 'concat':
h_combined = torch.cat([detached_binary_out, h_style], dim=1)
else:
h_combined = detached_binary_out * h_style
else:
if self.combine_method == 'concat':
h_combined = torch.cat([binary_out, h_style], dim=1)
else:
h_combined = binary_out * h_style
# # After combining binary_out and style
# if self.combine_method == 'concat':
# h_combined = torch.cat([binary_out, h_style], dim=1)
# else: # multiply
# h_combined = binary_out * h_style
# First map to block_in channels
h_combined = self.initial_conv(h_combined)
# Then process with regular blocks
for block in self.final_blocks:
h_combined = block(h_combined)
h_combined = self.norm_out(h_combined)
h_combined = nonlinearity(h_combined)
out = self.conv_out(h_combined)
return out, binary_out # Return both final output and binary reconstruction
class DumbTwoStageGenerator(nn.Module):
def __init__(self, H):
super().__init__()
self.nf = H.nf
self.ch_mult = H.ch_mult
self.num_resolutions = len(self.ch_mult)
# Note: H.res_blocks is used for the final stage, keep it.
self.num_res_blocks = H.res_blocks
self.combine_method = H.combine_method
self.resolution = H.img_size
self.emb_dim = H.emb_dim # Dimension of z_struct / z_style
# --- Simplified First Stage ---
# Directly map upsampled structure codes to binary output
# Input channels = H.emb_dim (dimension of z_struct)
# Output channels = 1
self.struct_to_binary_conv = nn.Conv3d(
self.emb_dim, 1, kernel_size=3, stride=1, padding=1
)
# Removed: struct_conv_in, struct_mid, struct_up_blocks, struct_norm_out, struct_conv_out
# --- Second Stage (Identical Logic to Original) ---
# This defines the channel depth expected by the final ResBlocks
# Uses the same logic as the original to determine this depth
block_in_final_stage = self.nf * self.ch_mult[self.num_resolutions-1]
# Calculate combined channels based on combine_method and input dims
if self.combine_method == 'concat':
# 1 channel from binary_out + emb_dim channels from h_style
combined_channels = 1 + self.emb_dim
else: # multiply
# binary_out * h_style -> channel dim remains emb_dim
combined_channels = self.emb_dim
# Initial conv for the second stage
self.initial_conv = nn.Conv3d(
combined_channels,
block_in_final_stage,
kernel_size=3, stride=1, padding=1
)
# Final processing blocks (same as original)
self.final_blocks = nn.ModuleList([
ResBlock(block_in_final_stage, block_in_final_stage)
for _ in range(self.num_res_blocks) # Using H.res_blocks here
])
# Final output layers (same as original)
self.norm_out = Normalize(block_in_final_stage) # Assuming Normalize is GroupNorm
self.conv_out = nn.Conv3d(
block_in_final_stage, H.n_channels, kernel_size=3, stride=1, padding=1
)
def forward(self, z):
# Input z shape: [B, C, H', W', D'] where C = 2 * emb_dim
# H', W', D' are the latent spatial dimensions
B, C, H_latent, W_latent, D_latent = z.shape
# Split input into structure and style codes
# Each has shape [B, emb_dim, H', W', D']
z_struct = z[:, :self.emb_dim]
z_style = z[:, self.emb_dim:]
# --- Simplified Structure Path ---
# 1. Upsample structure codes directly to target resolution
h_struct_upsampled = F.interpolate(
z_struct,
size=(self.resolution, self.resolution, self.resolution),
mode='trilinear', # Using trilinear for smoother interpolation pre-conv
align_corners=False
) # Shape: [B, emb_dim, resolution, resolution, resolution]
# 2. Apply single conv layer to get binary logits
binary_logits = self.struct_to_binary_conv(h_struct_upsampled)
# Shape: [B, 1, resolution, resolution, resolution]
# 3. Apply sigmoid
binary_out = torch.sigmoid(binary_logits)
# Shape: [B, 1, resolution, resolution, resolution]
# --- Style Path (Identical to Original) ---
# Upsample style codes to match spatial dimensions
h_style = F.interpolate(
z_style,
size=(self.resolution, self.resolution, self.resolution),
mode='trilinear',
align_corners=False
) # Shape: [B, emb_dim, resolution, resolution, resolution]
# --- Combine (Identical to Original) ---
if self.combine_method == 'concat':
h_combined = torch.cat([binary_out, h_style], dim=1)
# Shape: [B, 1 + emb_dim, resolution, resolution, resolution]
else: # multiply
# Broadcasting handles the shapes: [B, 1, ...] * [B, emb_dim, ...]
h_combined = binary_out * h_style
# Shape: [B, emb_dim, resolution, resolution, resolution]
# --- Final Stage (Identical to Original) ---
# Map combined representation to the input depth for final blocks
h_combined = self.initial_conv(h_combined)
# Process with final ResBlocks
for block in self.final_blocks:
h_combined = block(h_combined)
# Final normalization, nonlinearity, and output convolution
h_combined = self.norm_out(h_combined)
h_combined = nonlinearity(h_combined) # Assuming nonlinearity is swish
out = self.conv_out(h_combined)
# Shape: [B, n_channels, resolution, resolution, resolution]
return out, binary_out
class SlightlyLessDumbTwoStageGenerator(nn.Module):
def __init__(self, H):
super().__init__()
self.nf = H.nf
self.ch_mult = H.ch_mult
self.num_resolutions = len(self.ch_mult)
self.num_res_blocks = H.res_blocks # Used for final stage
self.combine_method = H.combine_method
self.resolution = H.img_size
self.emb_dim = H.emb_dim
self.padding_mode = H.padding_mode
self.detach = H.detach_binary_recon
if self.detach:
print("Detaching binary reconstruction from comp graph for final loss")
# --- Slightly Enhanced First Stage ---
# Still simpler than original, but with a bit more capacity
# 1. Optional: Add a ResBlock after upsampling
# Use the embedding dimension as the channel count here.
# self.struct_resblock = ResBlock(self.emb_dim, self.emb_dim, padding_mode=self.padding_mode)
self.struct_resblock = ResBlock(self.emb_dim, self.emb_dim, padding_mode=self.padding_mode, num_groups=self.emb_dim // 2)
# 2. Add Norm and Nonlinearity before the final conv
# self.struct_norm_out = Normalize(self.emb_dim) # Use Normalize/GroupNorm
self.struct_norm_out = nn.GroupNorm(num_groups=self.emb_dim // 2, num_channels=self.emb_dim, eps=1e-6, affine=True)
# 3. Final Conv to binary output (kernel 3x3x3 might be better than 1x1x1)
self.struct_to_binary_conv = nn.Conv3d(self.emb_dim, 1, kernel_size=3, stride=1, padding=1, padding_mode=self.padding_mode)
# --- Second Stage (Identical Logic to Original Dumb Version) ---
block_in_final_stage = self.nf * self.ch_mult[self.num_resolutions-1]
if self.combine_method == 'concat':
combined_channels = 1 + self.emb_dim
else:
combined_channels = self.emb_dim
self.initial_conv = nn.Conv3d(
combined_channels, block_in_final_stage, kernel_size=3, stride=1, padding=1, padding_mode=self.padding_mode
)
self.final_blocks = nn.ModuleList([
ResBlock(block_in_final_stage, block_in_final_stage, padding_mode=self.padding_mode)
for _ in range(self.num_res_blocks)
])
self.norm_out = Normalize(block_in_final_stage)
self.conv_out = nn.Conv3d(
block_in_final_stage, H.n_channels, kernel_size=3, stride=1, padding=1, padding_mode=self.padding_mode
)
def forward(self, z):
B, C, H_latent, W_latent, D_latent = z.shape
z_struct = z[:, :self.emb_dim]
z_style = z[:, self.emb_dim:]
# --- Slightly Enhanced Structure Path ---
# 1. Upsample structure codes
h_struct_upsampled = F.interpolate(
z_struct,
size=(self.resolution, self.resolution, self.resolution),
mode='trilinear',
align_corners=False
) # Shape: [B, emb_dim, resolution, resolution, resolution]
# 1.5 Apply ResBlock
h_struct_proc = self.struct_resblock(h_struct_upsampled)
# 2. Apply Norm and Nonlinearity
h_struct_proc = self.struct_norm_out(h_struct_proc)
h_struct_proc = nonlinearity(h_struct_proc) # Apply swish
# 3. Apply final conv layer to get binary logits
binary_logits = self.struct_to_binary_conv(h_struct_proc)
# 4. Apply sigmoid
binary_out = torch.sigmoid(binary_logits)
# --- Style Path (Identical) ---
h_style = F.interpolate(
z_style, size=(self.resolution, self.resolution, self.resolution),
mode='trilinear', align_corners=False
)
if self.detach:
detached_binary_out = binary_out.detach()
# --- Combine (Identical) ---
if self.combine_method == 'concat':
h_combined = torch.cat([detached_binary_out, h_style], dim=1)
else:
h_combined = detached_binary_out * h_style
else:
if self.combine_method == 'concat':
h_combined = torch.cat([binary_out, h_style], dim=1)
else:
h_combined = binary_out * h_style
# --- Final Stage (Identical) ---