-
Notifications
You must be signed in to change notification settings - Fork 26
/
model.py
2187 lines (1695 loc) · 91.8 KB
/
model.py
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
import torch
import torch.nn as nn
import torch.nn.functional as F
from resnet import ResNet,Bottleneck, resnet18
import torchvision.models as models
import math
import colored_traceback.auto
from torchsummary import summary
from resnet50 import ResNet50
from memory_profiler import profile
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import colored_traceback.auto
import cv2
from facenet_pytorch import InceptionResnetV1
import torchvision.transforms as transforms
from torchvision.transforms.functional import to_pil_image, to_tensor
from PIL import Image
from skimage.transform import PiecewiseAffineTransform, warp
import face_recognition
from lpips import LPIPS
from mysixdrepnet import SixDRepNet_Detector
# Set this flag to True for DEBUG mode, False for INFO mode
debug_mode = False
# Configure logging
if debug_mode:
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
else:
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# keep the code in one mega class for copying and pasting into Claude.ai
FEATURE_SIZE_AVG_POOL = 2 # use 2 - not 4. https://github.com/johndpope/MegaPortrait-hack/issues/23
FEATURE_SIZE = (2, 2)
COMPRESS_DIM = 512 # 🤷 TODO 1: maybe 256 or 512, 512 may be more reasonable for Emtn/app compression
# Define the device globally
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class Conv2d_WS(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, groups=1, bias=True):
super(Conv2d_WS, self).__init__(in_channels, out_channels, kernel_size, stride,
padding, dilation, groups, bias)
def forward(self, x):
weight = self.weight
weight_mean = weight.mean(dim=1, keepdim=True).mean(dim=2,
keepdim=True).mean(dim=3, keepdim=True)
weight = weight - weight_mean
std = weight.view(weight.size(0), -1).std(dim=1).view(-1, 1, 1, 1) + 1e-5
weight = weight / std.expand_as(weight)
return F.conv2d(x, weight, self.bias, self.stride,
self.padding, self.dilation, self.groups)
class Conv3D_WS(nn.Conv3d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, groups=1, bias=True):
super(Conv3D_WS, self).__init__(in_channels, out_channels, kernel_size, stride,
padding, dilation, groups, bias)
def forward(self, x):
weight = self.weight
weight_mean = weight.mean(dim=1, keepdim=True).mean(dim=2,
keepdim=True).mean(dim=3, keepdim=True).mean(
dim=4, keepdim=True)
weight = weight - weight_mean
std = weight.view(weight.size(0), -1).std(dim=1).view(-1, 1, 1, 1, 1) + 1e-5
weight = weight / std.expand_as(weight)
return F.conv3d(x, weight, self.bias, self.stride,
self.padding, self.dilation, self.groups)
class ResBlock_Custom(nn.Module):
def __init__(self, dimension, in_channels, out_channels):
super().__init__()
self.dimension = dimension
self.in_channels = in_channels
self.out_channels = out_channels
if dimension == 2:
self.conv_res = nn.Conv2d(self.in_channels, self.out_channels, 3, padding=1)
self.conv_ws = Conv2d_WS(in_channels=self.in_channels,
out_channels=self.out_channels,
kernel_size=3,
padding=1)
self.conv = nn.Conv2d(self.out_channels, self.out_channels, 3, padding=1)
elif dimension == 3:
self.conv_res = nn.Conv3d(self.in_channels, self.out_channels, 3, padding=1)
self.conv_ws = Conv3D_WS(in_channels=self.in_channels,
out_channels=self.out_channels,
kernel_size=3,
padding=1)
self.conv = nn.Conv3d(self.out_channels, self.out_channels, 3, padding=1)
# @profile
def forward(self, x):
logging.debug(f"ResBlock_Custom > x.shape: %s",x.shape)
# logging.debug(f"x:",x)
out2 = self.conv_res(x)
out1 = F.group_norm(x, num_groups=32)
out1 = F.relu(out1)
out1 = self.conv_ws(out1)
out1 = F.group_norm(out1, num_groups=32)
out1 = F.relu(out1)
out1 = self.conv(out1)
output = out1 + out2
# Assertions for shape and values
assert output.shape[1] == self.out_channels, f"Expected {self.out_channels} channels, got {output.shape[1]}"
assert output.shape[2] == x.shape[2] and output.shape[3] == x.shape[3], \
f"Expected spatial dimensions {(x.shape[2], x.shape[3])}, got {(output.shape[2], output.shape[3])}"
return output
# we need custom resnet blocks - so use the ResNet50 es.shape: torch.Size([1, 512, 1, 1])
# n.b. emoportraits reduced this from 512 -> 128 dim - these are feature maps / identity fingerprint of image
class CustomResNet50(nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
resnet = models.resnet50(*args, **kwargs)
self.conv1 = resnet.conv1
self.bn1 = resnet.bn1
# self.relu = resnet.relu
self.maxpool = resnet.maxpool
self.layer1 = resnet.layer1
self.layer2 = resnet.layer2
self.layer3 = resnet.layer3
# Remove the last residual block (layer4)
# self.layer4 = resnet.layer4
# Add an adaptive average pooling layer
self.adaptive_avg_pool = nn.AdaptiveAvgPool2d(FEATURE_SIZE_AVG_POOL)
# Add a 1x1 convolutional layer to reduce the number of channels to 512
self.conv_reduce = nn.Conv2d(1024, 512, kernel_size=1)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = F.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
# Remove the forward pass through layer4
# x = self.layer4(x)
# Apply adaptive average pooling
x = self.adaptive_avg_pool(x)
# Apply the 1x1 convolutional layer to reduce the number of channels
x = self.conv_reduce(x)
return x
'''
Eapp Class:
The Eapp class represents the appearance encoder (Eapp) in the diagram.
It consists of two parts: producing volumetric features (vs) and producing a global descriptor (es).
Producing Volumetric Features (vs):
The conv layer corresponds to the 7x7-Conv-64 block in the diagram.
The resblock_128, resblock_256, resblock_512 layers correspond to the ResBlock2D-128, ResBlock2D-256, ResBlock2D-512 blocks respectively, with average pooling (self.avgpool) in between.
The conv_1 layer corresponds to the GN, ReLU, 1x1-Conv2D-1536 block in the diagram.
The output of conv_1 is reshaped to (batch_size, 96, 16, height, width) and passed through resblock3D_96 and resblock3D_96_2, which correspond to the two ResBlock3D-96 blocks in the diagram.
The final output of this part is the volumetric features (vs).
Producing Global Descriptor (es):
The resnet50 layer corresponds to the ResNet50 block in the diagram.
It takes the input image (x) and produces the global descriptor (es).
Forward Pass:
During the forward pass, the input image (x) is passed through both parts of the Eapp network.
The first part produces the volumetric features (vs) by passing the input through the convolutional layers, residual blocks, and reshaping operations.
The second part produces the global descriptor (es) by passing the input through the ResNet50 network.
The Eapp network returns both vs and es as output.
In summary, the Eapp class in the code aligns well with the appearance encoder (Eapp) shown in the diagram. The network architecture follows the same structure, with the corresponding layers and blocks mapped accurately. The conv, resblock_128, resblock_256, resblock_512, conv_1, resblock3D_96, and resblock3D_96_2 layers in the code correspond to the respective blocks in the diagram for producing volumetric features. The resnet50 layer in the code corresponds to the ResNet50 block in the diagram for producing the global descriptor.
'''
class Eapp(nn.Module):
def __init__(self):
super().__init__()
# First part: producing volumetric features vs
self.conv = nn.Conv2d(3, 64, 7, stride=1, padding=3)
self.resblock_128 = ResBlock_Custom(dimension=2, in_channels=64, out_channels=128)
self.resblock_256 = ResBlock_Custom(dimension=2, in_channels=128, out_channels=256)
self.resblock_512 = ResBlock_Custom(dimension=2, in_channels=256, out_channels=512)
# round 0
self.resblock3D_96 = ResBlock3D_Adaptive(in_channels=96, out_channels=96)
self.resblock3D_96_2 = ResBlock3D_Adaptive(in_channels=96, out_channels=96)
# round 1
self.resblock3D_96_1 = ResBlock3D_Adaptive(in_channels=96, out_channels=96)
self.resblock3D_96_1_2 = ResBlock3D_Adaptive(in_channels=96, out_channels=96)
# round 2
self.resblock3D_96_2 = ResBlock3D_Adaptive(in_channels=96, out_channels=96)
self.resblock3D_96_2_2 = ResBlock3D_Adaptive(in_channels=96, out_channels=96)
self.conv_1 = nn.Conv2d(in_channels=512, out_channels=1536, kernel_size=1, stride=1, padding=0)
# Adjusted AvgPool to reduce spatial dimensions effectively
self.avgpool = nn.AvgPool2d(kernel_size=2, stride=2, padding=0)
# Second part: producing global descriptor es
self.custom_resnet50 = CustomResNet50()
'''
### TODO 2: Change vs/es here for vector size
According to the description of the paper (Page11: predict the head pose and expression vector),
zs should be a global descriptor, which is a vector. Otherwise, the existence of Emtn and Eapp is of little significance.
The output feature is a matrix, which means it is basically not compressed. This encoder can be completely replaced by a VAE.
'''
filters = [64, 256, 512, 1024, 2048]
outputs=COMPRESS_DIM
self.fc = torch.nn.Linear(filters[4], outputs)
def forward(self, x):
# First part
logging.debug(f"image x: {x.shape}") # [1, 3, 256, 256]
out = self.conv(x)
logging.debug(f"After conv: {out.shape}") # [1, 3, 256, 256]
out = self.resblock_128(out)
logging.debug(f"After resblock_128: {out.shape}") # [1, 128, 256, 256]
out = self.avgpool(out)
logging.debug(f"After avgpool: {out.shape}")
out = self.resblock_256(out)
logging.debug(f"After resblock_256: {out.shape}")
out = self.avgpool(out)
logging.debug(f"After avgpool: {out.shape}")
out = self.resblock_512(out)
logging.debug(f"After resblock_512: {out.shape}") # [1, 512, 64, 64]
out = self.avgpool(out) # at 512x512 image training - we need this 🤷 i rip this out so we can keep things 64x64 - it doesnt align to diagram though
# logging.debug(f"After avgpool: {out.shape}") # [1, 256, 64, 64]
out = F.group_norm(out, num_groups=32)
out = F.relu(out)
out = self.conv_1(out)
logging.debug(f"After conv_1: {out.shape}") # [1, 1536, 32, 32]
# reshape 1546 -> C96 x D16
vs = out.view(out.size(0), 96, 16, *out.shape[2:]) # 🤷 this maybe inaccurate
logging.debug(f"reshape 1546 -> C96 x D16 : {vs.shape}")
# 1
vs = self.resblock3D_96(vs)
logging.debug(f"After resblock3D_96: {vs.shape}")
vs = self.resblock3D_96_2(vs)
logging.debug(f"After resblock3D_96_2: {vs.shape}") # [1, 96, 16, 32, 32]
# 2
vs = self.resblock3D_96_1(vs)
logging.debug(f"After resblock3D_96_1: {vs.shape}") # [1, 96, 16, 32, 32]
vs = self.resblock3D_96_1_2(vs)
logging.debug(f"After resblock3D_96_1_2: {vs.shape}")
# 3
vs = self.resblock3D_96_2(vs)
logging.debug(f"After resblock3D_96_2: {vs.shape}") # [1, 96, 16, 32, 32]
vs = self.resblock3D_96_2_2(vs)
logging.debug(f"After resblock3D_96_2_2: {vs.shape}")
# Second part
es_resnet = self.custom_resnet50(x)
### TODO 2
# print(f"🍌 es:{es_resnet.shape}") # [1, 512, 2, 2]
es_flatten = torch.flatten(es_resnet, start_dim=1)
es = self.fc(es_flatten) # torch.Size([bs, 2048]) -> torch.Size([bs, 2])
return vs, es
class AdaptiveGroupNorm(nn.Module):
def __init__(self, num_channels, num_groups=32):
super(AdaptiveGroupNorm, self).__init__()
self.num_channels = num_channels
self.num_groups = num_groups
self.weight = nn.Parameter(torch.ones(1, num_channels, 1, 1, 1))
self.bias = nn.Parameter(torch.zeros(1, num_channels, 1, 1, 1))
self.group_norm = nn.GroupNorm(num_groups, num_channels)
def forward(self, x):
normalized = self.group_norm(x)
return normalized * self.weight + self.bias
class ResBlock(nn.Module):
def __init__(self, in_channels, out_channels, downsample=False):
super().__init__()
if downsample:
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=2, padding=1)
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=2),
nn.BatchNorm2d(out_channels)
)
else:
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.shortcut = nn.Sequential()
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.bn1 = nn.BatchNorm2d(out_channels)
self.bn2 = nn.BatchNorm2d(out_channels)
def forward(self, input):
shortcut = self.shortcut(input)
input = nn.ReLU()(self.bn1(self.conv1(input)))
input = nn.ReLU()(self.bn2(self.conv2(input)))
input = input + shortcut
return nn.ReLU()(input)
class ResBlock2D_Adaptive(nn.Module):
def __init__(self, in_channels, out_channels, upsample=False, scale_factors=(1, 1)):
super().__init__()
self.upsample = upsample
self.scale_factors = scale_factors
self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1)
self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1)
self.norm1 = AdaptiveGroupNorm(out_channels)
self.norm2 = AdaptiveGroupNorm(out_channels)
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.norm1(out)
out = F.relu(out)
out = self.conv2(out)
out = self.norm2(out)
out += residual
out = F.relu(out)
if self.upsample:
out = F.interpolate(out, scale_factor=self.scale_factors, mode='bilinear', align_corners=False)
return out
class ResBlock3D_Adaptive(nn.Module):
def __init__(self, in_channels, out_channels, upsample=False, scale_factors=(1, 1, 1)):
super().__init__()
self.upsample = upsample
self.scale_factors = scale_factors
self.conv1 = nn.Conv3d(in_channels, out_channels, 3, padding=1)
self.conv2 = nn.Conv3d(out_channels, out_channels, 3, padding=1)
self.norm1 = AdaptiveGroupNorm(out_channels)
self.norm2 = AdaptiveGroupNorm(out_channels)
if in_channels != out_channels:
self.residual_conv = nn.Conv3d(in_channels, out_channels, 1)
else:
self.residual_conv = nn.Identity()
# @profile
def forward(self, x):
residual = x
logging.debug(f" 🍒 ResBlock3D x.shape:{x.shape}")
out = self.conv1(x)
logging.debug(f" conv1 > out.shape:{out.shape}")
out = self.norm1(out)
logging.debug(f" norm1 > out.shape:{out.shape}")
out = F.relu(out)
logging.debug(f" F.relu(out) > out.shape:{out.shape}")
out = self.conv2(out)
logging.debug(f" conv2 > out.shape:{out.shape}")
out = self.norm2(out)
logging.debug(f" norm2 > out.shape:{out.shape}")
residual = self.residual_conv(residual)
logging.debug(f" residual > residual.shape:{residual.shape}",)
out += residual
out = F.relu(out)
if self.upsample:
out = F.interpolate(out, scale_factor=self.scale_factors, mode='trilinear', align_corners=False)
return out
class FlowField(nn.Module):
"""Network for generating flow fields from feature embeddings"""
def __init__(self):
super().__init__()
# Initial 1x1 convolution
self.conv1x1 = nn.Conv2d(512, 2048, kernel_size=1)
# 3D processing branch
self.resblock1 = ResBlock3D_Adaptive(in_channels=512, out_channels=256)
self.resblock2 = ResBlock3D_Adaptive(in_channels=256, out_channels=128)
self.resblock3 = ResBlock3D_Adaptive(in_channels=128, out_channels=64)
self.resblock4 = ResBlock3D_Adaptive(in_channels=64, out_channels=32)
# Final 3x3x3 convolution
self.conv3x3x3 = nn.Conv3d(32, 3, kernel_size=3, padding=1)
self.gn = nn.GroupNorm(1, 3)
def forward(self, zs, adaptive_gamma, adaptive_beta):
x = self.conv1x1(zs)
# Reshape to 3D volume
b = x.shape[0]
x = x.view(b, 512, 4, *x.shape[2:])
# Apply ResBlocks with upsampling
x = F.interpolate(self.resblock1(x), scale_factor=(2, 2, 2))
x = F.interpolate(self.resblock2(x), scale_factor=(2, 2, 2))
x = F.interpolate(self.resblock3(x), scale_factor=(1, 2, 2))
x = F.interpolate(self.resblock4(x), scale_factor=(1, 2, 2))
# Final convolutions
x = self.conv3x3x3(x)
x = self.gn(x)
x = F.relu(x)
x = torch.tanh(x)
return x
# produce a 3D warping field w𝑠→
'''
The ResBlock3D class represents a 3D residual block. It consists of two 3D convolutional layers (conv1 and conv2) with group normalization (norm1 and norm2) and ReLU activation. The residual connection is implemented using a shortcut connection.
Let's break down the code:
The init method initializes the layers of the residual block.
conv1 and conv2 are 3D convolutional layers with the specified input and output channels, kernel size of 3, and padding of 1.
norm1 and norm2 are group normalization layers with 32 groups and the corresponding number of channels.
If the input and output channels are different, a shortcut connection is created using a 1x1 convolutional layer and group normalization to match the dimensions.
The forward method defines the forward pass of the residual block.
The input x is stored as the residual.
The input is passed through the first convolutional layer (conv1), followed by group normalization (norm1) and ReLU activation.
The output is then passed through the second convolutional layer (conv2) and group normalization (norm2).
If a shortcut connection exists (i.e., input and output channels are different), the residual is passed through the shortcut connection.
The residual is added to the output of the second convolutional layer.
Finally, ReLU activation is applied to the sum.
The ResBlock3D class can be used as a building block in a larger 3D convolutional neural network architecture. It allows for the efficient training of deep networks by enabling the gradients to flow directly through the shortcut connection, mitigating the vanishing gradient problem.
You can create an instance of the ResBlock3D class by specifying the input and output channels:'''
class ResBlock3D(nn.Module):
def __init__(self, in_channels, out_channels, upsample=False, scale_factors=(1, 1, 1)):
super(ResBlock3D, self).__init__()
self.upsample = upsample
self.scale_factors = scale_factors
self.conv1 = nn.Conv3d(in_channels, out_channels, kernel_size=3, padding=1)
self.gn1 = nn.GroupNorm(num_groups=32, num_channels=out_channels)
self.conv2 = nn.Conv3d(out_channels, out_channels, kernel_size=3, padding=1)
self.gn2 = nn.GroupNorm(num_groups=32, num_channels=out_channels)
self.shortcut = nn.Conv3d(in_channels, out_channels, kernel_size=1) if in_channels != out_channels else nn.Identity()
def forward(self, x):
identity = self.shortcut(x)
out = self.conv1(x)
out = self.gn1(out)
out = F.relu(out, inplace=True)
out = self.conv2(out)
out = self.gn2(out)
out += identity
out = F.relu(out, inplace=True)
if self.upsample:
out = F.interpolate(out, scale_factor=self.scale_factors, mode='trilinear', align_corners=False)
return out
'''
G3d Class:
- The G3d class represents the 3D convolutional network (G3D) in the diagram.
- It consists of a downsampling path and an upsampling path.
Downsampling Path:
- The downsampling block in the code corresponds to the downsampling path in the diagram.
- It consists of a series of ResBlock3D and 3D average pooling (nn.AvgPool3d) operations.
- The architecture of the downsampling path follows the structure shown in the diagram:
- ResBlock3D(in_channels, 96) corresponds to the ResBlock3D-96 block.
- nn.AvgPool3d(kernel_size=2, stride=2) corresponds to the downsampling operation after ResBlock3D-96.
- ResBlock3D(96, 192) corresponds to the ResBlock3D-192 block.
- nn.AvgPool3d(kernel_size=2, stride=2) corresponds to the downsampling operation after ResBlock3D-192.
- ResBlock3D(192, 384) corresponds to the ResBlock3D-384 block.
- nn.AvgPool3d(kernel_size=2, stride=2) corresponds to the downsampling operation after ResBlock3D-384.
- ResBlock3D(384, 768) corresponds to the ResBlock3D-768 block.
Upsampling Path:
- The upsampling block in the code corresponds to the upsampling path in the diagram.
- It consists of a series of ResBlock3D and 3D upsampling (nn.Upsample) operations.
- The architecture of the upsampling path follows the structure shown in the diagram:
- ResBlock3D(768, 384) corresponds to the ResBlock3D-384 block.
- nn.Upsample(scale_factor=2, mode='trilinear', align_corners=True) corresponds to the upsampling operation after ResBlock3D-384.
- ResBlock3D(384, 192) corresponds to the ResBlock3D-192 block.
- nn.Upsample(scale_factor=2, mode='trilinear', align_corners=True) corresponds to the upsampling operation after ResBlock3D-192.
- ResBlock3D(192, 96) corresponds to the ResBlock3D-96 block.
- nn.Upsample(scale_factor=2, mode='trilinear', align_corners=True) corresponds to the upsampling operation after ResBlock3D-96.
Final Convolution:
- The final_conv layer in the code corresponds to the GN, ReLU, 3x3x3-Conv3D-96 block in the diagram.
- It takes the output of the upsampling path and applies a 3D convolution with a kernel size of 3 and padding of 1 to produce the final output.
Forward Pass:
- During the forward pass, the input tensor x is passed through the downsampling path, then through the upsampling path, and finally through the final convolution layer.
- The output of the G3d network is a tensor of the same spatial dimensions as the input, but with 96 channels.
In summary, the G3d class in the code aligns well with the 3D convolutional network (G3D) shown in the diagram. The downsampling path, upsampling path, and final convolution layer in the code correspond to the respective blocks in the diagram. The ResBlock3D and pooling/upsampling operations are consistent with the diagram, and the forward pass follows the expected flow of data through the network.
'''
class G3d(nn.Module):
def __init__(self, in_channels):
super(G3d, self).__init__()
self.downsampling = nn.Sequential(
ResBlock3D(in_channels, 96),
nn.AvgPool3d(kernel_size=2, stride=2),
ResBlock3D(96, 192),
nn.AvgPool3d(kernel_size=2, stride=2),
ResBlock3D(192, 384),
nn.AvgPool3d(kernel_size=2, stride=2),
ResBlock3D(384, 768),
)
self.upsampling = nn.Sequential(
ResBlock3D(768, 384),
nn.Upsample(scale_factor=2, mode='trilinear', align_corners=True),
ResBlock3D(384, 192),
nn.Upsample(scale_factor=2, mode='trilinear', align_corners=True),
ResBlock3D(192, 96),
nn.Upsample(scale_factor=2, mode='trilinear', align_corners=True),
)
self.final_conv = nn.Conv3d(96, 96, kernel_size=3, padding=1)
def forward(self, x):
x = self.downsampling(x)
x = self.upsampling(x)
x = self.final_conv(x)
return x
class ResBlock2D(nn.Module):
def __init__(self, in_channels, out_channels, downsample=False):
super(ResBlock2D, self).__init__()
self.downsample = downsample
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.bn1 = nn.BatchNorm2d(out_channels)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
self.bn2 = nn.BatchNorm2d(out_channels)
if self.downsample:
self.downsample_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=2)
self.downsample_bn = nn.BatchNorm2d(out_channels)
if in_channels != out_channels:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1),
nn.BatchNorm2d(out_channels)
)
else:
self.shortcut = nn.Identity()
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = nn.ReLU(inplace=True)(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample:
identity = self.downsample_conv(x)
identity = self.downsample_bn(identity)
identity = self.shortcut(identity)
out += identity
out = nn.ReLU(inplace=True)(out)
return out
'''
This class, AntiAliasInterpolation2d, is a PyTorch module designed for band-limited downsampling of images, which helps preserve the input signal quality by applying a Gaussian filter before resizing. Here's an intuition breakdown of the code:
This approach ensures that the downsampled image retains more of the original signal's details by reducing high-frequency components that could cause aliasing.
'''
class AntiAliasInterpolation2d(nn.Module):
"""
Band-limited downsampling, for better preservation of the input signal.
"""
def __init__(self, channels, scale):
super(AntiAliasInterpolation2d, self).__init__()
sigma = (1 / scale - 1) / 2
kernel_size = 2 * round(sigma * 4) + 1
self.ka = kernel_size // 2
self.kb = self.ka - 1 if kernel_size % 2 == 0 else self.ka
kernel_size = [kernel_size, kernel_size]
sigma = [sigma, sigma]
# The gaussian kernel is the product of the
# gaussian function of each dimension.
kernel = 1
meshgrids = torch.meshgrid(
[
torch.arange(size, dtype=torch.float32)
for size in kernel_size
]
)
for size, std, mgrid in zip(kernel_size, sigma, meshgrids):
mean = (size - 1) / 2
kernel *= torch.exp(-(mgrid - mean) ** 2 / (2 * std ** 2))
# Make sure sum of values in gaussian kernel equals 1.
kernel = kernel / torch.sum(kernel)
# Reshape to depthwise convolutional weight
kernel = kernel.view(1, 1, *kernel.size())
kernel = kernel.repeat(channels, *[1] * (kernel.dim() - 1))
self.register_buffer('weight', kernel)
self.groups = channels
self.scale = scale
def forward(self, input):
if self.scale == 1.0:
return input
out = F.pad(input, (self.ka, self.kb, self.ka, self.kb))
out = F.conv2d(out, weight=self.weight, groups=self.groups)
out = F.interpolate(out, scale_factor=(self.scale, self.scale))
return out
'''
The G2d class consists of the following components:
The input has 96 channels (C96)
The input has a depth dimension of 16 (D16)
The output should have 1536 channels (C1536)
The depth dimension (D16) is present because the input to G2d is a 3D tensor
(volumetric features) with shape (batch_size, 96, 16, height/4, width/4).
The reshape operation is meant to collapse the depth dimension and increase the number of channels.
The ResBlock2D layers have 512 channels, not 1536 channels as I previously stated.
The diagram clearly shows 8 ResBlock2D-512 layers before the upsampling blocks that reduce the number of channels.
To summarize, the G2D network takes the orthographically projected 2D feature map from the 3D volumetric features as input.
It first reshapes the number of channels to 512 using a 1x1 convolution layer.
Then it passes the features through 8 residual blocks (ResBlock2D) that maintain 512 channels.
This is followed by upsampling blocks that progressively halve the number of channels while doubling the spatial resolution,
going from 512 to 256 to 128 to 64 channels.
Finally, a 3x3 convolution outputs the synthesized image with 3 color channels.
'''
class G2d(nn.Module):
def __init__(self, in_channels):
super(G2d, self).__init__()
self.reshape = nn.Conv2d(96, 1536, kernel_size=1) # Reshape C96xD16 → C1536
self.conv1x1 = nn.Conv2d(1536, 512, kernel_size=1) # 1x1 convolution to reduce channels to 512
self.res_blocks = nn.Sequential(
ResBlock2D(512, 512),
ResBlock2D(512, 512),
ResBlock2D(512, 512),
ResBlock2D(512, 512),
ResBlock2D(512, 512),
ResBlock2D(512, 512),
ResBlock2D(512, 512),
ResBlock2D(512, 512),
)
self.upsample1 = nn.Sequential(
nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True),
ResBlock2D(512, 256)
)
self.upsample2 = nn.Sequential(
nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True),
ResBlock2D(256, 128)
)
self.upsample3 = nn.Sequential(
nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True),
ResBlock2D(128, 64)
)
self.final_conv = nn.Sequential(
nn.GroupNorm(num_groups=32, num_channels=64),
nn.ReLU(inplace=True),
nn.Conv2d(64, 3, kernel_size=3, padding=1),
nn.Sigmoid()
)
def forward(self, x):
logging.debug(f"G2d > x:{x.shape}")
x = self.reshape(x)
x = self.conv1x1(x) # Added 1x1 convolution to reduce channels to 512
x = self.res_blocks(x)
x = self.upsample1(x)
x = self.upsample2(x)
x = self.upsample3(x)
x = self.final_conv(x)
return x
'''
In this expanded version of compute_rt_warp, we first compute the rotation matrix from the rotation parameters using the compute_rotation_matrix function. The rotation parameters are assumed to be a tensor of shape (batch_size, 3), representing rotation angles in degrees around the x, y, and z axes.
Inside compute_rotation_matrix, we convert the rotation angles from degrees to radians and compute the individual rotation matrices for each axis using the rotation angles. We then combine the rotation matrices using matrix multiplication to obtain the final rotation matrix.
Next, we create a 4x4 affine transformation matrix and set the top-left 3x3 submatrix to the computed rotation matrix. We also set the first three elements of the last column to the translation parameters.
Finally, we create a grid of normalized coordinates using F.affine_grid based on the affine transformation matrix.
The grid size is assumed to be 64x64x64, but you can adjust it according to your specific requirements.
The resulting grid represents the warping transformations based on the given rotation and translation parameters, which can be used to warp the volumetric features or other tensors.
https://github.com/Kevinfringe/MegaPortrait/issues/4
'''
def compute_rt_warp(rotation, translation, invert=False, grid_size=64):
"""
Computes the rotation/translation warpings (w_rt).
Args:
rotation (torch.Tensor): The rotation angles (in degrees) of shape (batch_size, 3).
translation (torch.Tensor): The translation vector of shape (batch_size, 3).
invert (bool): If True, invert the transformation matrix.
Returns:
torch.Tensor: The resulting transformation grid.
"""
# Compute the rotation matrix from the rotation parameters
rotation_matrix = compute_rotation_matrix(rotation)
# Create a 4x4 affine transformation matrix
affine_matrix = torch.eye(4, device=rotation.device).repeat(rotation.shape[0], 1, 1)
# Set the top-left 3x3 submatrix to the rotation matrix
affine_matrix[:, :3, :3] = rotation_matrix
# Set the first three elements of the last column to the translation parameters
affine_matrix[:, :3, 3] = translation
# Invert the transformation matrix if needed
if invert:
affine_matrix = torch.inverse(affine_matrix)
# # Create a grid of normalized coordinates
grid = F.affine_grid(affine_matrix[:, :3], (rotation.shape[0], 1, grid_size, grid_size, grid_size), align_corners=False)
# # Transpose the dimensions of the grid to match the expected shape
grid = grid.permute(0, 4, 1, 2, 3)
return grid
def compute_rotation_matrix(rotation):
"""
Computes the rotation matrix from rotation angles.
Args:
rotation (torch.Tensor): The rotation angles (in degrees) of shape (batch_size, 3).
Returns:
torch.Tensor: The rotation matrix of shape (batch_size, 3, 3).
"""
# Assumes rotation is a tensor of shape (batch_size, 3), representing rotation angles in degrees
rotation_rad = rotation * (torch.pi / 180.0) # Convert degrees to radians
cos_alpha = torch.cos(rotation_rad[:, 0])
sin_alpha = torch.sin(rotation_rad[:, 0])
cos_beta = torch.cos(rotation_rad[:, 1])
sin_beta = torch.sin(rotation_rad[:, 1])
cos_gamma = torch.cos(rotation_rad[:, 2])
sin_gamma = torch.sin(rotation_rad[:, 2])
# Compute the rotation matrix using the rotation angles
zero = torch.zeros_like(cos_alpha)
one = torch.ones_like(cos_alpha)
R_alpha = torch.stack([
torch.stack([one, zero, zero], dim=1),
torch.stack([zero, cos_alpha, -sin_alpha], dim=1),
torch.stack([zero, sin_alpha, cos_alpha], dim=1)
], dim=1)
R_beta = torch.stack([
torch.stack([cos_beta, zero, sin_beta], dim=1),
torch.stack([zero, one, zero], dim=1),
torch.stack([-sin_beta, zero, cos_beta], dim=1)
], dim=1)
R_gamma = torch.stack([
torch.stack([cos_gamma, -sin_gamma, zero], dim=1),
torch.stack([sin_gamma, cos_gamma, zero], dim=1),
torch.stack([zero, zero, one], dim=1)
], dim=1)
# Combine the rotation matrices
rotation_matrix = torch.matmul(R_alpha, torch.matmul(R_beta, R_gamma))
return rotation_matrix
'''
In the updated Emtn class, we use two separate networks (head_pose_net and expression_net) to predict the head pose and expression parameters, respectively.
The head_pose_net is a ResNet-18 model pretrained on ImageNet, with the last fully connected layer replaced to output 6 values (3 for rotation and 3 for translation).
The expression_net is another ResNet-18 model with the last fully connected layer adjusted to output the desired dimensions of the expression vector (e.g., 50).
In the forward method, we pass the input x through both networks to obtain the head pose and expression predictions. We then split the head pose output into rotation and translation parameters.
The Emtn module now returns the rotation parameters (Rs, Rd), translation parameters (ts, td), and expression vectors (zs, zd) for both the source and driving images.
Note: Make sure to adjust the dimensions of the rotation, translation, and expression parameters according to your specific requirements and the details provided in the MegaPortraits paper.'''
class Emtn(nn.Module):
def __init__(self):
super().__init__()
# https://github.com/johndpope/MegaPortrait-hack/issues/19
# replace this with off the shelf SixDRepNet
self.head_pose_net = resnet18(pretrained=True)
self.head_pose_net.fc = nn.Linear(self.head_pose_net.fc.in_features, 6) # 6 corresponds to rotation and translation parameters
self.rotation_net = SixDRepNet_Detector()
model = resnet18(pretrained=False,num_classes=512) # 512 feature_maps = resnet18(input_image) -> Should print: torch.Size([1, 512, 7, 7])
# Remove the fully connected layer and the adaptive average pooling layer
self.expression_net = nn.Sequential(*list(model.children())[:-1])
self.expression_net.adaptive_pool = nn.AdaptiveAvgPool2d(FEATURE_SIZE) # https://github.com/neeek2303/MegaPortraits/issues/3
# self.expression_net.adaptive_pool = nn.AdaptiveAvgPool2d((7, 7)) #OPTIONAL 🤷 - 16x16 is better?
## TODO 2
outputs=COMPRESS_DIM ## 512,,方便后面的WarpS2C操作 512 -> 2048 channel
self.fc = torch.nn.Linear(2048, outputs)
def forward(self, x):
# Forward pass through head pose network
rotations,_ = self.rotation_net.predict(x)
logging.debug(f"📐 rotation :{rotations}")
head_pose = self.head_pose_net(x)
# Split head pose into rotation and translation parameters
# rotation = head_pose[:, :3] - this is shit
translation = head_pose[:, 3:]
# Forward pass image through expression network
expression_resnet = self.expression_net(x)
### TODO 2
expression_flatten = torch.flatten(expression_resnet, start_dim=1)
expression = self.fc(expression_flatten) # (bs, 2048) ->>> (bs, COMPRESS_DIM)
return rotations, translation, expression
#This encoder outputs head rotations R𝑠/𝑑 ,translations t𝑠/𝑑 , and latent expression descriptors z𝑠/𝑑
'''
Rotation and Translation Warping (𝑤𝑟𝑡_wrt_):
For 𝑤𝑟𝑡→𝑑_wrt_→_d_: This warping applies a transformation matrix (rotation and translation) to an identity grid.
For 𝑤𝑟𝑡𝑠→_wrts_→: This warping applies an inverse transformation matrix to an identity grid.
Expression Warping (𝑤𝑒𝑚_wem_):
Separate warping generators are used for source to canonical (𝑤𝑒𝑚𝑠→_wems_→) and canonical to driver (𝑤𝑒𝑚→𝑑_wem_→_d_).
Both warping generators share the same architecture, which includes several 3D residual blocks with Adaptive GroupNorms.
Inputs to these generators are the sums of the expression and appearance descriptors (𝑧𝑠+𝑒𝑠_zs_+_es_ for source and 𝑧𝑑+𝑒𝑠_zd_+_es_ for driver).
Adaptive parameters are generated by multiplying these sums with learned matrices.
'''
class WarpGeneratorS2C(nn.Module):
"""Warping generator for source-to-canonical transformation"""
def __init__(self, num_channels):
super().__init__()
self.num_channels = num_channels
self.flowfield = FlowField()
# Adaptive matrices for generating parameters
self.adaptive_matrix_gamma = nn.Parameter(torch.randn(num_channels, num_channels))
self.adaptive_matrix_beta = nn.Parameter(torch.randn(num_channels, num_channels))
def forward(self, Rs, ts, zs, es):
# Validate input shapes
assert Rs.shape[1] == 3, f"Expected Rs shape (batch_size, 3), got {Rs.shape}"
assert ts.shape[1] == 3, f"Expected ts shape (batch_size, 3), got {ts.shape}"
assert zs.shape == es.shape, f"Expected matching shapes for zs and es, got {zs.shape} vs {es.shape}"
# Combine expression and identity features
zs_sum = zs + es
# Generate adaptive parameters using learned matrices
zs_sum = torch.matmul(zs_sum, self.adaptive_matrix_gamma)
zs_sum = zs_sum.unsqueeze(-1).unsqueeze(-1)
# Generate warping field using FlowField
w_em_s2c = self.flowfield(zs_sum, adaptive_gamma=0, adaptive_beta=0)
# Generate rotation/translation warping
w_rt_s2c = compute_rt_warp(Rs, ts, invert=True, grid_size=64)
# Resize expression warping to match rotation warping
w_em_s2c_resized = F.interpolate(
w_em_s2c,
size=w_rt_s2c.shape[2:],
mode='trilinear',
align_corners=False
)
# Combine both warpings
w_s2c = w_rt_s2c + w_em_s2c_resized
return w_s2c
class WarpGeneratorC2D(nn.Module):
"""Warping generator for canonical-to-driving transformation"""
def __init__(self, num_channels):
super().__init__()
self.num_channels = num_channels
self.flowfield = FlowField()
# Adaptive matrices for generating parameters
self.adaptive_matrix_gamma = nn.Parameter(torch.randn(num_channels, num_channels))
self.adaptive_matrix_beta = nn.Parameter(torch.randn(num_channels, num_channels))
def forward(self, Rd, td, zd, es):
# Validate input shapes
assert Rd.shape[1] == 3, f"Expected Rd shape (batch_size, 3), got {Rd.shape}"
assert td.shape[1] == 3, f"Expected td shape (batch_size, 3), got {td.shape}"
assert zd.shape == es.shape, f"Expected matching shapes for zd and es, got {zd.shape} vs {es.shape}"
# Combine expression and identity features
zd_sum = zd + es
# Generate adaptive parameters using learned matrices
zd_sum = torch.matmul(zd_sum, self.adaptive_matrix_gamma)
zd_sum = zd_sum.unsqueeze(-1).unsqueeze(-1)
# Generate warping field using FlowField
w_em_c2d = self.flowfield(zd_sum, adaptive_gamma=0, adaptive_beta=0)
# Generate rotation/translation warping
w_rt_c2d = compute_rt_warp(Rd, td, invert=False, grid_size=64)
# Resize expression warping to match rotation warping
w_em_c2d_resized = F.interpolate(
w_em_c2d,
size=w_rt_c2d.shape[2:],
mode='trilinear',
align_corners=False
)
# Combine both warpings
w_c2d = w_rt_c2d + w_em_c2d_resized
return w_c2d
# Function to apply the 3D warping field
def apply_warping_field(v, warp_field):
"""Apply 3D warping field to volume"""
B, C, D, H, W = v.size()
device = v.device
# Resize warp field to match volume dimensions
warp_field = F.interpolate(
warp_field,
size=(D, H, W),
mode='trilinear',
align_corners=True
)
# Create canonical coordinate grid