-
Notifications
You must be signed in to change notification settings - Fork 1
/
imagen_pytorch3D.py
2442 lines (1910 loc) · 88.2 KB
/
imagen_pytorch3D.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 sys
import math
import copy
from random import random
import numpy as np
from beartype.typing import List, Union
from beartype import beartype
from tqdm.auto import tqdm
from functools import partial, wraps
from contextlib import contextmanager, nullcontext
from pathlib import Path
import torch
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataParallel
from torch import nn, einsum
from torch.special import expm1
import torchvision.transforms as T
import kornia.augmentation as K
from einops import rearrange, repeat, reduce, pack, unpack
from einops.layers.torch import Rearrange, Reduce
from einops_exts import rearrange_many, repeat_many, check_shape
from imagen_video import Unet3D
from utils_mine import convertVolume2subVolume, merge_sub_volumes, volume_to_slices
import matplotlib.pyplot as plt
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
import torch.autograd
from percept_loss import *
torch.autograd.set_detect_anomaly(True)
# helper functions
def boundary_pad(img, batch_sample_factor=3):
b, c, h = img.shape[0], img.shape[1], img.shape[2]
A = h+2
B = h
big_patch_size = h*batch_sample_factor
img = merge_sub_volumes(img, original_shape=(1,c,big_patch_size,big_patch_size,big_patch_size)) #1,C,96,96,96
img = F.pad(img, (1,1,1,1,1,1), "constant") #1,C,98,98,98
sub_volumes = img.unfold(2, A, B).unfold(3, A, B).unfold(4, A, B).permute(0,4,3,2,1,5,6,7).reshape(b, c, A, A, A)
return sub_volumes
def exists(val):
return val is not None
def identity(t, *args, **kwargs):
return t
def divisible_by(numer, denom):
return (numer % denom) == 0
def first(arr, d = None):
if len(arr) == 0:
return d
return arr[0]
def maybe(fn):
@wraps(fn)
def inner(x):
if not exists(x):
return x
return fn(x)
return inner
def min_max_norm(img):
return (img-img.min())/(img.max()-img.min())
def once(fn):
called = False
@wraps(fn)
def inner(x):
nonlocal called
if called:
return
called = True
return fn(x)
return inner
print_once = once(print)
def default(val, d):
if exists(val):
return val
return d() if callable(d) else d
def cast_tuple(val, length = None):
if isinstance(val, list):
val = tuple(val)
output = val if isinstance(val, tuple) else ((val,) * default(length, 1))
if exists(length):
assert len(output) == length
return output
def cast_uint8_images_to_float(images):
if not images.dtype == torch.uint8:
return images
return images / 255
def module_device(module):
return next(module.parameters()).device
def zero_init_(m):
nn.init.zeros_(m.weight)
if exists(m.bias):
nn.init.zeros_(m.bias)
def eval_decorator(fn):
def inner(model, *args, **kwargs):
was_training = model.training
model.eval()
out = fn(model, *args, **kwargs)
model.train(was_training)
return out
return inner
def pad_tuple_to_length(t, length, fillvalue = None):
remain_length = length - len(t)
if remain_length <= 0:
return t
return (*t, *((fillvalue,) * remain_length))
# helper classes
class Identity(nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
def forward(self, x, *args, **kwargs):
return x
# tensor helpers
def log(t, eps: float = 1e-12):
return torch.log(t.clamp(min = eps))
def l2norm(t):
return F.normalize(t, dim = -1)
def right_pad_dims_to(x, t):
padding_dims = x.ndim - t.ndim
if padding_dims <= 0:
return t
return t.view(*t.shape, *((1,) * padding_dims)) #bs c h w d
def masked_mean(t, *, dim, mask = None):
if not exists(mask):
return t.mean(dim = dim)
denom = mask.sum(dim = dim, keepdim = True)
mask = rearrange(mask, 'b n -> b n 1')
masked_t = t.masked_fill(~mask, 0.)
return masked_t.sum(dim = dim) / denom.clamp(min = 1e-5)
def resize_image_to(
image,
target_image_size,
clamp_range = None,
mode = 'nearest'
):
orig_image_size = image.shape[-1]
if orig_image_size == target_image_size:
return image
out = F.interpolate(image, target_image_size, mode = mode)
if exists(clamp_range):
out = out.clamp(*clamp_range)
return out
def calc_all_frame_dims(
downsample_factors: List[int],
frames
):
if not exists(frames):
return (tuple(),) * len(downsample_factors)
all_frame_dims = []
for divisor in downsample_factors:
assert divisible_by(frames, divisor)
all_frame_dims.append((frames // divisor,))
return all_frame_dims
def safe_get_tuple_index(tup, index, default = None):
if len(tup) <= index:
return default
return tup[index]
# image normalization functions
# ddpms expect images to be in the range of -1 to 1
def normalize_neg_one_to_one(img):
return img * 2 - 1
def unnormalize_zero_to_one(normed_img):
return (normed_img + 1) * 0.5
# classifier free guidance functions
def prob_mask_like(shape, prob, device):
if prob == 1:
return torch.ones(shape, device = device, dtype = torch.bool)
elif prob == 0:
return torch.zeros(shape, device = device, dtype = torch.bool)
else:
return torch.zeros(shape, device = device).float().uniform_(0, 1) < prob
# gaussian diffusion with continuous time helper functions and classes
# large part of this was thanks to @crowsonkb at https://github.com/crowsonkb/v-diffusion-jax/blob/master/diffusion/utils.py
@torch.jit.script
def beta_linear_log_snr(t):
return -torch.log(expm1(1e-4 + 10 * (t ** 2)))
@torch.jit.script
def alpha_cosine_log_snr(t, s: float = 0.008):
return -log((torch.cos((t + s) / (1 + s) * math.pi * 0.5) ** -2) - 1, eps = 1e-5) # not sure if this accounts for beta being clipped to 0.999 in discrete version
def log_snr_to_alpha_sigma(log_snr):
return torch.sqrt(torch.sigmoid(log_snr)), torch.sqrt(torch.sigmoid(-log_snr))
class GaussianDiffusionContinuousTimes(nn.Module):
def __init__(self, *, noise_schedule, timesteps = 1000):
super().__init__()
if noise_schedule == "linear":
self.log_snr = beta_linear_log_snr
elif noise_schedule == "cosine":
self.log_snr = alpha_cosine_log_snr
else:
raise ValueError(f'invalid noise schedule {noise_schedule}')
self.num_timesteps = timesteps
def get_times(self, batch_size, noise_level, *, device):
return torch.full((batch_size,), noise_level, device = device, dtype = torch.float32)
def sample_random_times(self, batch_size, *, device):
random_tensor_cpu = torch.zeros((batch_size,)).float().uniform_(0, 1)
random_tensor_gpu = random_tensor_cpu.to(device)
return random_tensor_gpu
def get_condition(self, times):
return maybe(self.log_snr)(times)
def get_sampling_timesteps(self, batch, *, device):
times = torch.linspace(1., 0., self.num_timesteps + 1, device = device)
times = repeat(times, 't -> b t', b = batch)
times = torch.stack((times[:, :-1], times[:, 1:]), dim = 0)
times = times.unbind(dim = -1)
return times
def get_sampling_timesteps_non_uniform(self, batch, *, device):
large_timesteps=10000
gamma = torch.tensor(10)
times = torch.linspace(1., 0., large_timesteps)
probs = torch.exp(-gamma * times).type(torch.float64)
probs = probs / probs.sum()
ts = torch.tensor(np.random.choice(times, self.num_timesteps, p=probs, replace=False))
if torch.tensor([1.0]) not in ts:
ts = torch.cat((ts, torch.tensor([1.0])))
if torch.tensor([0.0]) not in ts:
ts = torch.cat((ts, torch.tensor([0.0])))
ts = torch.sort(ts,descending=True).values.to(device)
ts = repeat(ts, 't -> b t', b = batch)
ts = torch.stack((ts[:, :-1], ts[:, 1:]), dim = 0)
ts = ts.unbind(dim = -1)
return ts
def q_posterior(self, x_start, x_t, t, *, t_next = None):
#Calculates predicted mean and variance for x_s given x_t. Here x_s is x_start (not necessarily x_T)
t_next = default(t_next, lambda: (t - 1. / self.num_timesteps).clamp(min = 0.))
""" https://openreview.net/attachment?id=2LdBqxc1Yv&name=supplementary_material """
log_snr = self.log_snr(t)
log_snr_next = self.log_snr(t_next)
log_snr, log_snr_next = map(partial(right_pad_dims_to, x_t), (log_snr, log_snr_next))
alpha, sigma = log_snr_to_alpha_sigma(log_snr)
alpha_next, sigma_next = log_snr_to_alpha_sigma(log_snr_next)
# c - as defined near eq 33
c = -expm1(log_snr - log_snr_next)
posterior_mean = alpha_next * (x_t * (1 - c) / alpha + c * x_start)
# following (eq. 33)
posterior_variance = (sigma_next ** 2) * c
posterior_log_variance_clipped = log(posterior_variance, eps = 1e-20)
return posterior_mean, posterior_variance, posterior_log_variance_clipped
def q_sample(self, x_start, t, noise = None):
dtype = x_start.dtype
if isinstance(t, float):
batch = x_start.shape[0]
t = torch.full((batch,), t, device = x_start.device, dtype = dtype)
noise = default(noise, lambda: torch.randn_like(x_start))
log_snr = self.log_snr(t).type(dtype)
log_snr_padded_dim = right_pad_dims_to(x_start, log_snr)
alpha, sigma = log_snr_to_alpha_sigma(log_snr_padded_dim)
return alpha * x_start + sigma * noise, log_snr, alpha, sigma
def q_sample_from_to(self, x_from, from_t, to_t, noise = None):
shape, device, dtype = x_from.shape, x_from.device, x_from.dtype
batch = shape[0]
if isinstance(from_t, float):
from_t = torch.full((batch,), from_t, device = device, dtype = dtype)
if isinstance(to_t, float):
to_t = torch.full((batch,), to_t, device = device, dtype = dtype)
noise = default(noise, lambda: torch.randn_like(x_from))
log_snr = self.log_snr(from_t)
log_snr_padded_dim = right_pad_dims_to(x_from, log_snr)
alpha, sigma = log_snr_to_alpha_sigma(log_snr_padded_dim)
log_snr_to = self.log_snr(to_t)
log_snr_padded_dim_to = right_pad_dims_to(x_from, log_snr_to)
alpha_to, sigma_to = log_snr_to_alpha_sigma(log_snr_padded_dim_to)
return x_from * (alpha_to / alpha) + noise * (sigma_to * alpha - sigma * alpha_to) / alpha
def predict_start_from_v(self, x_t, t, v):
log_snr = self.log_snr(t)
log_snr = right_pad_dims_to(x_t, log_snr)
alpha, sigma = log_snr_to_alpha_sigma(log_snr)
return alpha * x_t - sigma * v
def predict_start_from_noise(self, x_t, t, noise):
#generate x_t-1 from x_t
log_snr = self.log_snr(t)
log_snr = right_pad_dims_to(x_t, log_snr)
alpha, sigma = log_snr_to_alpha_sigma(log_snr)
return (x_t - sigma * noise) / alpha.clamp(min = 1e-8)
# norms and residuals
class LayerNorm(nn.Module):
def __init__(self, feats, stable = False, dim = -1):
super().__init__()
self.stable = stable
self.dim = dim
self.g = nn.Parameter(torch.ones(feats, *((1,) * (-dim - 1))))
def forward(self, x):
dtype, dim = x.dtype, self.dim
if self.stable:
x = x / x.amax(dim = dim, keepdim = True).detach()
eps = 1e-5 if x.dtype == torch.float32 else 1e-3
var = torch.var(x, dim = dim, unbiased = False, keepdim = True)
mean = torch.mean(x, dim = dim, keepdim = True)
# print(self.g.shape, mean.shape, var.shape, x.shape)
return (x - mean) * (var + eps).rsqrt().type(dtype) * self.g.type(dtype)
ChanLayerNorm = partial(LayerNorm, dim = -4) # h c h w d
class Always():
def __init__(self, val):
self.val = val
def __call__(self, *args, **kwargs):
return self.val
class Residual(nn.Module):
def __init__(self, fn):
super().__init__()
self.fn = fn
def forward(self, x, **kwargs):
return self.fn(x, **kwargs) + x
class Parallel(nn.Module):
def __init__(self, *fns):
super().__init__()
self.fns = nn.ModuleList(fns)
def forward(self, x):
outputs = [fn(x) for fn in self.fns]
return sum(outputs)
def Upsample(dim, dim_out = None):
dim_out = default(dim_out, dim)
return nn.Sequential(
nn.Upsample(scale_factor = 2, mode = 'trilinear'),
nn.Conv3d(dim, dim_out, 3, padding = 1)
)
class PixelShuffle3D(nn.Module):
'''
This class is a 3d version of pixelshuffle.
'''
def __init__(self, scale):
'''
:param scale: upsample scale
'''
super().__init__()
self.scale = scale
def forward(self, input):
batch_size, channels, in_depth, in_height, in_width = input.size()
nOut = channels // self.scale ** 3
out_depth = in_depth * self.scale
out_height = in_height * self.scale
out_width = in_width * self.scale
input_view = input.contiguous().view(batch_size, nOut, self.scale, self.scale, self.scale, in_depth, in_height, in_width)
output = input_view.permute(0, 1, 5, 2, 6, 3, 7, 4).contiguous()
return output.view(batch_size, nOut, out_depth, out_height, out_width)
class Deconv3D(nn.Module):
def __init__(self, inp_feat, out_feat, kernel=3, stride=2, padding=1):
super(Deconv3D, self).__init__()
self.deconv = nn.Sequential(
nn.ConvTranspose3d(inp_feat, out_feat, kernel_size=(kernel, kernel, kernel),
stride=(stride, stride, stride), padding=(padding, padding, padding), output_padding=1, bias=True),
nn.Mish())
def forward(self, x):
return self.deconv(x)
def Upsample_deconv(dim, dim_out = None):
dim_out = default(dim_out, dim)
return Deconv3D(dim, dim_out)
class PixelShuffleUpsample(nn.Module):
"""
code shared by @MalumaDev at DALLE2-pytorch for addressing checkboard artifacts
https://arxiv.org/ftp/arxiv/papers/1707/1707.02937.pdf
"""
def __init__(self, dim, dim_out = None):
super().__init__()
dim_out = default(dim_out, dim)
conv = nn.Conv3d(dim, dim_out * 8, 1, padding_mode='replicate')
self.net = nn.Sequential(
conv,
nn.Mish(),
PixelShuffle3D(2)
)
self.init_conv_(conv)
def init_conv_(self, conv):
o, i, h, w, d = conv.weight.shape
conv_weight = torch.empty(o // 4, i, h, w, d)
nn.init.kaiming_uniform_(conv_weight)
conv_weight = repeat(conv_weight, 'o ... -> (o 4) ...')
conv.weight.data.copy_(conv_weight)
nn.init.zeros_(conv.bias.data)
def forward(self, x):
return self.net(x)
def Downsample(dim, dim_out = None):
# https://arxiv.org/abs/2208.03641 shows this is the most optimal way to downsample
# named SP-conv in the paper, but basically a pixel unshuffle
dim_out = default(dim_out, dim)
return nn.Sequential(
Rearrange('b c (h s1) (w s2) (d s3) -> b (c s1 s2 s3) h w d', s1 = 2, s2 = 2, s3 = 2),
nn.Conv3d(dim * 8, dim_out, 1)
)
def Downsample2(dim, dim_out = None):
# https://arxiv.org/abs/2208.03641 shows this is the most optimal way to downsample
# named SP-conv in the paper, but basically a pixel unshuffle
dim_out = default(dim_out, dim)
return nn.Sequential(
nn.Conv3d(dim, dim_out, 3, padding = 1, stride=2)
)
class SinusoidalPosEmb(nn.Module):
def __init__(self, dim):
super().__init__()
self.dim = dim
def forward(self, x):
half_dim = self.dim // 2
emb = math.log(10000) / (half_dim - 1)
emb = torch.exp(torch.arange(half_dim, device = x.device) * -emb)
emb = rearrange(x, 'i -> i 1') * rearrange(emb, 'j -> 1 j')
return torch.cat((emb.sin(), emb.cos()), dim = -1)
class LearnedSinusoidalPosEmb(nn.Module):
""" following @crowsonkb 's lead with learned sinusoidal pos emb """
""" https://github.com/crowsonkb/v-diffusion-jax/blob/master/diffusion/models/danbooru_128.py#L8 """
def __init__(self, dim):
super().__init__()
assert (dim % 2) == 0
half_dim = dim // 2
self.weights = nn.Parameter(torch.randn(half_dim))
def forward(self, x):
x = rearrange(x, 'b -> b 1')
freqs = x * rearrange(self.weights, 'd -> 1 d') * 2 * math.pi
fouriered = torch.cat((freqs.sin(), freqs.cos()), dim = -1)
fouriered = torch.cat((x, fouriered), dim = -1)
return fouriered
class Block(nn.Module):
def __init__(
self,
dim,
dim_out,
groups = 8,
norm = True,
boundary = False,
factor = 3
):
super().__init__()
self.groupnorm = nn.GroupNorm(groups, dim) if norm else Identity()
self.activation = nn.Mish()
self.boundary = boundary
self.factor = factor
if self.boundary:
self.project = nn.Conv3d(dim, dim_out, 3)
else:
self.project = nn.Conv3d(dim, dim_out, 3, padding = 1)
def forward(self, x, scale_shift = None):
x = self.groupnorm(x)
if exists(scale_shift):
scale, shift = scale_shift
x = x * (scale + 1) + shift
x = self.activation(x)
if self.boundary:
x = boundary_pad(x, batch_sample_factor=self.factor)
return self.project(x)
class ResnetBlock(nn.Module):
def __init__(
self,
dim,
dim_out,
time_cond_dim = None,
groups = 8,
use_se = False,
boundary = False,
factor = 3
):
super().__init__()
self.time_mlp = None
self.boundary = boundary
self.factor = factor
if exists(time_cond_dim):
self.time_mlp = nn.Sequential(
nn.Mish(),
nn.Linear(time_cond_dim, dim_out * 2)
)
self.block1 = Block(dim, dim_out, groups = groups, boundary=self.boundary, factor = self.factor)
self.block2 = Block(dim_out, dim_out, groups = groups, boundary=self.boundary, factor = self.factor)
self.se = SE3D(dim_out, reduction=16) if use_se else Identity()
self.res_conv = nn.Conv3d(dim, dim_out, 1) if dim != dim_out else Identity()
def forward(self, x, time_emb = None):
scale_shift = None
if exists(self.time_mlp) and exists(time_emb):
time_emb = self.time_mlp(time_emb)
time_emb = rearrange(time_emb, 'b c -> b c 1 1 1')
scale_shift = time_emb.chunk(2, dim = 1)
h = self.block1(x)
h = self.block2(h, scale_shift = scale_shift)
#h = h * self.gca(h)
h = self.se(h)
out = h + self.res_conv(x)
return out
class SE3D(nn.Module):
def __init__(self, channel, reduction=16):
super(SE3D, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool3d(1)
self.fc = nn.Sequential(
nn.Linear(channel, channel // reduction, bias=False),
nn.ReLU(inplace=True),
nn.Linear(channel // reduction, channel, bias=False),
nn.Sigmoid()
)
def forward(self, x):
b, c, _, _, _ = x.size()
y = self.avg_pool(x).view(b, c)
y = self.fc(y).view(b, c, 1, 1, 1)
return x * y.expand_as(x)
class GlobalContext(nn.Module):
""" basically a superior form of squeeze-excitation that is attention-esque """
def __init__(
self,
*,
dim_in,
dim_out
):
super().__init__()
self.to_k = nn.Conv3d(dim_in, 1, 1)
hidden_dim = max(3, dim_out // 2)
self.net = nn.Sequential(
nn.Conv3d(dim_in, hidden_dim, 1),
nn.Mish(),
nn.Conv3d(hidden_dim, dim_out, 1),
nn.Sigmoid()
)
def forward(self, x):
context = self.to_k(x)
x, context = rearrange_many((x, context), 'b n ... -> b n (...)')
out = einsum('b i n, b c n -> b c i', context.softmax(dim = -1), x)
out = rearrange(out, '... -> ... 1 1')
return self.net(out)
class CrossEmbedLayer(nn.Module):
def __init__(
self,
dim_in,
kernel_sizes,
dim_out = None,
stride = 2
):
super().__init__()
assert all([*map(lambda t: (t % 2) == (stride % 2), kernel_sizes)])
dim_out = default(dim_out, dim_in)
kernel_sizes = sorted(kernel_sizes)
num_scales = len(kernel_sizes)
# calculate the dimension at each scale
dim_scales = [int(dim_out / (2 ** i)) for i in range(1, num_scales)]
dim_scales = [*dim_scales, dim_out - sum(dim_scales)]
self.convs = nn.ModuleList([])
for kernel, dim_scale in zip(kernel_sizes, dim_scales):
self.convs.append(nn.Conv3d(dim_in, dim_scale, kernel, stride = stride, padding = (kernel - stride) // 2))
def forward(self, x):
fmaps = tuple(map(lambda conv: conv(x), self.convs))
return torch.cat(fmaps, dim = 1)
class UpsampleCombiner(nn.Module):
def __init__(
self,
dim,
*,
enabled = False,
dim_ins = tuple(),
dim_outs = tuple()
):
super().__init__()
dim_outs = cast_tuple(dim_outs, len(dim_ins))
assert len(dim_ins) == len(dim_outs)
self.enabled = enabled
if not self.enabled:
self.dim_out = dim
return
self.fmap_convs = nn.ModuleList([Block(dim_in, dim_out) for dim_in, dim_out in zip(dim_ins, dim_outs)])
self.dim_out = dim + (sum(dim_outs) if len(dim_outs) > 0 else 0)
def forward(self, x, fmaps = None):
target_size = x.shape[-1]
fmaps = default(fmaps, tuple())
if not self.enabled or len(fmaps) == 0 or len(self.fmap_convs) == 0:
return x
fmaps = [resize_image_to(fmap, target_size) for fmap in fmaps]
outs = [conv(fmap) for fmap, conv in zip(fmaps, self.fmap_convs)]
return torch.cat((x, *outs), dim = 1)
################################################################################################
class TransformerEncoderBlock(nn.Module):
def __init__(self,
emb_size: int = 256,
num_heads: int = 8,
dim_head: int = 64,
drop_p: float = 0.,
forward_expansion: int = 4,
forward_drop_p: float = 0.0,
patch_num: int = 4,
local: bool=True):
super().__init__()
self.block = nn.Sequential(
ResidualAdd(nn.Sequential(
nn.LayerNorm(emb_size),
MultiHeadAttention(emb_size, num_heads = num_heads, dropout = drop_p, dim_head= dim_head),
nn.Dropout(drop_p)
)),
ResidualAdd(nn.Sequential(
nn.LayerNorm(emb_size),
FeedForwardBlock(
emb_size, expansion=forward_expansion, drop_p=forward_drop_p, patch_num=patch_num, local=local),
nn.Dropout(drop_p)
))
)
def forward(self, x):
return self.block(x)
class TransformerEncoder(nn.Module):
def __init__(self, depth: int = 12, **kwargs):
super().__init__()
self.layers = nn.ModuleList([TransformerEncoderBlock(**kwargs) for _ in range(depth)])
def forward(self, x):
for layer in self.layers:
x = layer(x)
return x
class ResidualAdd(nn.Module):
def __init__(self, fn):
super().__init__()
self.fn = fn
def forward(self, x, **kwargs):
res = x
x = self.fn(x, **kwargs)
x += res
return x
class FeedForwardBlock(nn.Sequential):
def __init__(self, emb_size: int, expansion: int = 4, drop_p: float = 0., patch_num: int = 4, local=False):
super().__init__()
if local:
self.up_proj = nn.Sequential(
Rearrange('b (h w d) c -> b c h w d', h=patch_num, w=patch_num, d=patch_num),
nn.Conv3d(emb_size, emb_size*expansion, kernel_size=1),
nn.Mish()
)
self.depth_conv = nn.Sequential(
depthwise_separable_conv3d(emb_size*expansion, emb_size*expansion, kernel_size=3, stride=1, padding=1),
nn.Mish()
)
self.down_proj = nn.Sequential(
nn.Conv3d(emb_size*expansion, emb_size, kernel_size=1),
nn.Dropout(drop_p),
Rearrange('b c h w d ->b (h w d) c')
)
self.net = nn.Sequential(
self.up_proj,
self.depth_conv,
self.down_proj
)
else:
self.net = nn.Sequential(
nn.Linear(emb_size, expansion * emb_size),
nn.Mish(),
nn.Dropout(drop_p),
nn.Linear(expansion * emb_size, emb_size),
)
def forward(self, x):
return self.net(x)
class MultiHeadAttention(nn.Module):
def __init__(self, emb_size: int = 128, num_heads: int = 8, dim_head: int = 64, dropout: float = 0):
super().__init__()
self.mid_emb_size = emb_size
self.emb_size = emb_size
self.dim_head = dim_head
self.num_heads = num_heads
self.inner_dim = dim_head * num_heads
self.qkv = nn.Linear(self.mid_emb_size , self.inner_dim* 3)
self.att_drop = nn.Dropout(dropout)
self.projection = nn.Linear(self.inner_dim , emb_size)
self.scaling = self.dim_head ** -0.5
def forward(self, x, mask = None):
qkv = rearrange(self.qkv(x), "b n (h d qkv) -> qkv b h n d", h=self.num_heads, qkv=3)
queries, keys, values = qkv[0], qkv[1], qkv[2]
energy = torch.einsum('bhqd, bhkd -> bhqk', queries, keys) * self.scaling
if mask is not None:
fill_value = torch.finfo(torch.float32).min
energy.mask_fill(~mask, fill_value)
att = F.softmax(energy, dim=-1)
att = self.att_drop(att)
out = torch.einsum('bhal, bhlv -> bhav ', att, values)
out = rearrange(out, "b h n d -> b n (h d)")
out = self.projection(out)
return out
class PatchEmbedding(nn.Module):
def __init__(self, in_channels: int = 3, patch_size: int = 4, emb_size: int = 128, img_size: int = 224, reduction: bool = False):
self.patch_size = patch_size
super().__init__()
self.projection = nn.Sequential(
depthwise_separable_conv3d(in_channels, emb_size, kernel_size=patch_size, stride=patch_size), #nn.Conv3d(in_channels, emb_size, kernel_size=patch_size, stride=patch_size),
Rearrange('b e (h) (w) (d)-> b (h w d) e')
)
self.positions = nn.Parameter(torch.randn((img_size // patch_size) **3, emb_size))
def forward(self, x):
x = self.projection(x)
x += self.positions
return x
class depthwise_separable_conv3d(nn.Module):
def __init__(self, input_dim, output_dim, kernel_size, stride, padding=0):
super(depthwise_separable_conv3d, self).__init__()
self.depthwise = nn.Conv3d(input_dim, input_dim, kernel_size=kernel_size, stride=stride, padding=padding,
groups=input_dim)
self.pointwise = nn.Conv3d(input_dim, output_dim, kernel_size=1)
def forward(self, x):
x = self.depthwise(x)
x = self.pointwise(x)
return x
class ViT3D(nn.Module):
def __init__(self,
in_channels: int = 3,
patch_size: int = 16,
num_heads: int = 8,
dim_head: int = 64,
img_size: int = 224,
depth: int = 1,
drop_p: float = 0.1,
forward_drop_p: float = 0.3,
forward_expansion: int = 2,
reduction: bool = False, #VERSION reduction is deprecated and it refers to version of self attention
local: bool = True,
groups: int = 1,
**kwargs):
super().__init__()
self.reduction = reduction
self.emb_size = in_channels
self.patch_embedding = PatchEmbedding(in_channels, patch_size, self.emb_size, img_size, reduction=self.reduction)
self.transformer_encoder = TransformerEncoder(depth, emb_size=self.emb_size, num_heads=num_heads, dim_head=dim_head, patch_num=img_size//patch_size, drop_p = drop_p, forward_drop_p = forward_drop_p, forward_expansion = forward_expansion, local = local,**kwargs)
# self.reconstruction = nn.Sequential(
# Rearrange('b (h w d) c ->b c (h w d)', h=img_size//patch_size, w=img_size//patch_size, d=img_size//patch_size),
# nn.Conv1d(in_channels, in_channels * (patch_size ** 3), kernel_size=1, groups = groups),
# Rearrange('b (c p1 p2 p3) (h w d) -> b c (h p1) (w p2) (d p3)', p1=patch_size, p2=patch_size, p3=patch_size, h=img_size//patch_size, w=img_size//patch_size, d=img_size//patch_size)
# )
self.reconstruction = nn.Sequential(
nn.LayerNorm(in_channels),
Rearrange('b (h w d) c ->b c h w d', h=img_size//patch_size, w=img_size//patch_size, d=img_size//patch_size),
nn.Upsample(scale_factor=patch_size, mode='trilinear', align_corners=True),
depthwise_separable_conv3d(in_channels, in_channels, kernel_size=3, stride=1, padding=1),
ChanLayerNorm(in_channels)
)
def forward(self, x):
x = self.patch_embedding(x)
x = self.transformer_encoder(x)
out = self.reconstruction(x)
return out
#######################################################################################################################
class Patchify(nn.Module):
def __init__(self, in_channels: int = 3, patch_size: int = 4, emb_size: int = 128, img_size: int = 224, reduction: bool = False):
self.patch_size = patch_size
super().__init__()
self.norm = ChanLayerNorm(in_channels)
self.projection = depthwise_separable_conv3d(in_channels, emb_size, kernel_size=patch_size, stride=patch_size) #nn.Conv3d(in_channels, emb_size, kernel_size=patch_size, stride=patch_size),
def forward(self, x):
x = self.norm(x)
x = self.projection(x)
return x
class LinearAttention(nn.Module):
def __init__(
self,
dim,
dim_head = 32,
heads = 8,
dropout = 0.05,
context_dim = None,
patch_size = 2, # it must be 4 times smaller than original patch (e.g. 2 for 8x8x8 patch)
img_size = 48,
patch = False,
groups = 1,
**kwargs
):
super().__init__()
self.patch = patch
self.patch_size = patch_size
self.scale = dim_head ** -0.5
self.heads = heads
inner_dim = dim_head * heads
self.norm = ChanLayerNorm(dim)
self.nonlin = nn.Mish()
if self.patch:
self.patch_embed = Patchify(in_channels=dim, patch_size=patch_size, emb_size=dim, img_size=img_size) # H*C*W*C*D
self.reconstruct = nn.Sequential(
#nn.Conv3d(dim, dim*(patch_size ** 3), kernel_size=1, groups = groups),
nn.Upsample(scale_factor=patch_size, mode='trilinear', align_corners=True),
depthwise_separable_conv3d(dim, dim, kernel_size=3, stride=1, padding=1),
# Rearrange('b (c p1 p2 p3) h w d -> b c (h p1) (w p2) (d p3)', p1=patch_size, p2=patch_size, p3=patch_size, h=(img_size//patch_size),
# w=(img_size//patch_size), d=(img_size//patch_size)),
ChanLayerNorm(dim)
)
self.to_q = nn.Sequential(
nn.Dropout(dropout),
nn.Conv3d(dim, inner_dim, 1, bias = False),
nn.Conv3d(inner_dim, inner_dim, 3, bias = False, padding = 1, groups = inner_dim)
)
self.to_k = nn.Sequential(
nn.Dropout(dropout),
nn.Conv3d(dim, inner_dim, 1, bias = False),
nn.Conv3d(inner_dim, inner_dim, 3, bias = False, padding = 1, groups = inner_dim)
)
self.to_v = nn.Sequential(
nn.Dropout(dropout),
nn.Conv3d(dim, inner_dim, 1, bias = False),
nn.Conv3d(inner_dim, inner_dim, 3, bias = False, padding = 1, groups = inner_dim)
)
self.to_context = nn.Sequential(nn.LayerNorm(context_dim), nn.Linear(context_dim, inner_dim * 2, bias = False)) if exists(context_dim) else None
self.to_out = nn.Sequential(
nn.Conv3d(inner_dim, dim, 1, bias = False),
ChanLayerNorm(dim)
)
def forward(self, fmap, context = None):
if self.patch:
fmap = self.patch_embed(fmap)
h, x, y, z= self.heads, *fmap.shape[-3:]
fmap = self.norm(fmap)
q, k, v = map(lambda fn: fn(fmap), (self.to_q, self.to_k, self.to_v))
q, k, v = rearrange_many((q, k, v), 'b (h c) x y z-> (b h) (x y z) c', h = h)
if exists(context):
assert exists(self.to_context)
ck, cv = self.to_context(context).chunk(2, dim = -1)
ck, cv = rearrange_many((ck, cv), 'b n (h d) -> (b h) n d', h = h)
k = torch.cat((k, ck), dim = -2)