RamAnanth1 commited on
Commit
b6b5d48
β€’
1 Parent(s): 8fbdfd9

Upload 14 files

Browse files
lvdm/data/webvid.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import bisect
4
+
5
+ import pandas as pd
6
+
7
+ import omegaconf
8
+ import torch
9
+ from torch.utils.data import Dataset
10
+ from torchvision import transforms
11
+ from decord import VideoReader, cpu
12
+ import torchvision.transforms._transforms_video as transforms_video
13
+
14
+ class WebVid(Dataset):
15
+ """
16
+ WebVid Dataset.
17
+ Assumes webvid data is structured as follows.
18
+ Webvid/
19
+ videos/
20
+ 000001_000050/ ($page_dir)
21
+ 1.mp4 (videoid.mp4)
22
+ ...
23
+ 5000.mp4
24
+ ...
25
+ """
26
+ def __init__(self,
27
+ meta_path,
28
+ data_dir,
29
+ subsample=None,
30
+ video_length=16,
31
+ resolution=[256, 512],
32
+ frame_stride=1,
33
+ spatial_transform=None,
34
+ crop_resolution=None,
35
+ fps_max=None,
36
+ load_raw_resolution=False,
37
+ fps_schedule=None,
38
+ fs_probs=None,
39
+ bs_per_gpu=None,
40
+ trigger_word='',
41
+ dataname='',
42
+ ):
43
+ self.meta_path = meta_path
44
+ self.data_dir = data_dir
45
+ self.subsample = subsample
46
+ self.video_length = video_length
47
+ self.resolution = [resolution, resolution] if isinstance(resolution, int) else resolution
48
+ self.frame_stride = frame_stride
49
+ self.fps_max = fps_max
50
+ self.load_raw_resolution = load_raw_resolution
51
+ self.fs_probs = fs_probs
52
+ self.trigger_word = trigger_word
53
+ self.dataname = dataname
54
+
55
+ self._load_metadata()
56
+ if spatial_transform is not None:
57
+ if spatial_transform == "random_crop":
58
+ self.spatial_transform = transforms_video.RandomCropVideo(crop_resolution)
59
+ elif spatial_transform == "resize_center_crop":
60
+ assert(self.resolution[0] == self.resolution[1])
61
+ self.spatial_transform = transforms.Compose([
62
+ transforms.Resize(resolution),
63
+ transforms_video.CenterCropVideo(resolution),
64
+ ])
65
+ else:
66
+ raise NotImplementedError
67
+ else:
68
+ self.spatial_transform = None
69
+
70
+ self.fps_schedule = fps_schedule
71
+ self.bs_per_gpu = bs_per_gpu
72
+ if self.fps_schedule is not None:
73
+ assert(self.bs_per_gpu is not None)
74
+ self.counter = 0
75
+ self.stage_idx = 0
76
+
77
+ def _load_metadata(self):
78
+ metadata = pd.read_csv(self.meta_path)
79
+ if self.subsample is not None:
80
+ metadata = metadata.sample(self.subsample, random_state=0)
81
+ metadata['caption'] = metadata['name']
82
+ del metadata['name']
83
+ self.metadata = metadata
84
+ self.metadata.dropna(inplace=True)
85
+ # self.metadata['caption'] = self.metadata['caption'].str[:350]
86
+
87
+ def _get_video_path(self, sample):
88
+ if self.dataname == "loradata":
89
+ rel_video_fp = str(sample['videoid']) + '.mp4'
90
+ full_video_fp = os.path.join(self.data_dir, rel_video_fp)
91
+ else:
92
+ rel_video_fp = os.path.join(sample['page_dir'], str(sample['videoid']) + '.mp4')
93
+ full_video_fp = os.path.join(self.data_dir, 'videos', rel_video_fp)
94
+ return full_video_fp, rel_video_fp
95
+
96
+ def get_fs_based_on_schedule(self, frame_strides, schedule):
97
+ assert(len(frame_strides) == len(schedule) + 1) # nstage=len_fps_schedule + 1
98
+ global_step = self.counter // self.bs_per_gpu # TODO: support resume.
99
+ stage_idx = bisect.bisect(schedule, global_step)
100
+ frame_stride = frame_strides[stage_idx]
101
+ # log stage change
102
+ if stage_idx != self.stage_idx:
103
+ print(f'fps stage: {stage_idx} start ... new frame stride = {frame_stride}')
104
+ self.stage_idx = stage_idx
105
+ return frame_stride
106
+
107
+ def get_fs_based_on_probs(self, frame_strides, probs):
108
+ assert(len(frame_strides) == len(probs))
109
+ return random.choices(frame_strides, weights=probs)[0]
110
+
111
+ def get_fs_randomly(self, frame_strides):
112
+ return random.choice(frame_strides)
113
+
114
+ def __getitem__(self, index):
115
+
116
+ if isinstance(self.frame_stride, list) or isinstance(self.frame_stride, omegaconf.listconfig.ListConfig):
117
+ if self.fps_schedule is not None:
118
+ frame_stride = self.get_fs_based_on_schedule(self.frame_stride, self.fps_schedule)
119
+ elif self.fs_probs is not None:
120
+ frame_stride = self.get_fs_based_on_probs(self.frame_stride, self.fs_probs)
121
+ else:
122
+ frame_stride = self.get_fs_randomly(self.frame_stride)
123
+ else:
124
+ frame_stride = self.frame_stride
125
+ assert(isinstance(frame_stride, int)), type(frame_stride)
126
+
127
+ while True:
128
+ index = index % len(self.metadata)
129
+ sample = self.metadata.iloc[index]
130
+ video_path, rel_fp = self._get_video_path(sample)
131
+ caption = sample['caption']+self.trigger_word
132
+
133
+ # make reader
134
+ try:
135
+ if self.load_raw_resolution:
136
+ video_reader = VideoReader(video_path, ctx=cpu(0))
137
+ else:
138
+ video_reader = VideoReader(video_path, ctx=cpu(0), width=self.resolution[1], height=self.resolution[0])
139
+ if len(video_reader) < self.video_length:
140
+ print(f"video length ({len(video_reader)}) is smaller than target length({self.video_length})")
141
+ index += 1
142
+ continue
143
+ else:
144
+ pass
145
+ except:
146
+ index += 1
147
+ print(f"Load video failed! path = {video_path}")
148
+ continue
149
+
150
+ # sample strided frames
151
+ all_frames = list(range(0, len(video_reader), frame_stride))
152
+ if len(all_frames) < self.video_length: # recal a max fs
153
+ frame_stride = len(video_reader) // self.video_length
154
+ assert(frame_stride != 0)
155
+ all_frames = list(range(0, len(video_reader), frame_stride))
156
+
157
+ # select a random clip
158
+ rand_idx = random.randint(0, len(all_frames) - self.video_length)
159
+ frame_indices = all_frames[rand_idx:rand_idx+self.video_length]
160
+ try:
161
+ frames = video_reader.get_batch(frame_indices)
162
+ break
163
+ except:
164
+ print(f"Get frames failed! path = {video_path}")
165
+ index += 1
166
+ continue
167
+
168
+ assert(frames.shape[0] == self.video_length),f'{len(frames)}, self.video_length={self.video_length}'
169
+ frames = torch.tensor(frames.asnumpy()).permute(3, 0, 1, 2).float() # [t,h,w,c] -> [c,t,h,w]
170
+ if self.spatial_transform is not None:
171
+ frames = self.spatial_transform(frames)
172
+ if self.resolution is not None:
173
+ assert(frames.shape[2] == self.resolution[0] and frames.shape[3] == self.resolution[1]), f'frames={frames.shape}, self.resolution={self.resolution}'
174
+ frames = (frames / 255 - 0.5) * 2
175
+
176
+ fps_ori = video_reader.get_avg_fps()
177
+ fps_clip = fps_ori // frame_stride
178
+ if self.fps_max is not None and fps_clip > self.fps_max:
179
+ fps_clip = self.fps_max
180
+
181
+ data = {'video': frames, 'caption': caption, 'path': video_path, 'fps': fps_clip, 'frame_stride': frame_stride}
182
+
183
+ if self.fps_schedule is not None:
184
+ self.counter += 1
185
+ return data
186
+
187
+ def __len__(self):
188
+ return len(self.metadata)
lvdm/models/autoencoder.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import pytorch_lightning as pl
3
+ import torch.nn.functional as F
4
+ import os
5
+ from einops import rearrange
6
+
7
+ from lvdm.models.modules.autoencoder_modules import Encoder, Decoder
8
+ from lvdm.models.modules.distributions import DiagonalGaussianDistribution
9
+ from lvdm.utils.common_utils import instantiate_from_config
10
+
11
+ class AutoencoderKL(pl.LightningModule):
12
+ def __init__(self,
13
+ ddconfig,
14
+ lossconfig,
15
+ embed_dim,
16
+ ckpt_path=None,
17
+ ignore_keys=[],
18
+ image_key="image",
19
+ colorize_nlabels=None,
20
+ monitor=None,
21
+ test=False,
22
+ logdir=None,
23
+ input_dim=4,
24
+ test_args=None,
25
+ ):
26
+ super().__init__()
27
+ self.image_key = image_key
28
+ self.encoder = Encoder(**ddconfig)
29
+ self.decoder = Decoder(**ddconfig)
30
+ self.loss = instantiate_from_config(lossconfig)
31
+ assert ddconfig["double_z"]
32
+ self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1)
33
+ self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
34
+ self.embed_dim = embed_dim
35
+ self.input_dim = input_dim
36
+ self.test = test
37
+ self.test_args = test_args
38
+ self.logdir = logdir
39
+ if colorize_nlabels is not None:
40
+ assert type(colorize_nlabels)==int
41
+ self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
42
+ if monitor is not None:
43
+ self.monitor = monitor
44
+ if ckpt_path is not None:
45
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
46
+ if self.test:
47
+ self.init_test()
48
+
49
+ def init_test(self,):
50
+ self.test = True
51
+ save_dir = os.path.join(self.logdir, "test")
52
+ if 'ckpt' in self.test_args:
53
+ ckpt_name = os.path.basename(self.test_args.ckpt).split('.ckpt')[0] + f'_epoch{self._cur_epoch}'
54
+ self.root = os.path.join(save_dir, ckpt_name)
55
+ else:
56
+ self.root = save_dir
57
+ if 'test_subdir' in self.test_args:
58
+ self.root = os.path.join(save_dir, self.test_args.test_subdir)
59
+
60
+ self.root_zs = os.path.join(self.root, "zs")
61
+ self.root_dec = os.path.join(self.root, "reconstructions")
62
+ self.root_inputs = os.path.join(self.root, "inputs")
63
+ os.makedirs(self.root, exist_ok=True)
64
+
65
+ if self.test_args.save_z:
66
+ os.makedirs(self.root_zs, exist_ok=True)
67
+ if self.test_args.save_reconstruction:
68
+ os.makedirs(self.root_dec, exist_ok=True)
69
+ if self.test_args.save_input:
70
+ os.makedirs(self.root_inputs, exist_ok=True)
71
+ assert(self.test_args is not None)
72
+ self.test_maximum = getattr(self.test_args, 'test_maximum', None) #1500 # 12000/8
73
+ self.count = 0
74
+ self.eval_metrics = {}
75
+ self.decodes = []
76
+ self.save_decode_samples = 2048
77
+
78
+ def init_from_ckpt(self, path, ignore_keys=list()):
79
+ sd = torch.load(path, map_location="cpu")
80
+ try:
81
+ self._cur_epoch = sd['epoch']
82
+ sd = sd["state_dict"]
83
+ except:
84
+ self._cur_epoch = 'null'
85
+ keys = list(sd.keys())
86
+ for k in keys:
87
+ for ik in ignore_keys:
88
+ if k.startswith(ik):
89
+ print("Deleting key {} from state_dict.".format(k))
90
+ del sd[k]
91
+ self.load_state_dict(sd, strict=False)
92
+ # self.load_state_dict(sd, strict=True)
93
+ print(f"Restored from {path}")
94
+
95
+ def encode(self, x, **kwargs):
96
+
97
+ h = self.encoder(x)
98
+ moments = self.quant_conv(h)
99
+ posterior = DiagonalGaussianDistribution(moments)
100
+ return posterior
101
+
102
+ def decode(self, z, **kwargs):
103
+ z = self.post_quant_conv(z)
104
+ dec = self.decoder(z)
105
+ return dec
106
+
107
+ def forward(self, input, sample_posterior=True):
108
+ posterior = self.encode(input)
109
+ if sample_posterior:
110
+ z = posterior.sample()
111
+ else:
112
+ z = posterior.mode()
113
+ dec = self.decode(z)
114
+ return dec, posterior
115
+
116
+ def get_input(self, batch, k):
117
+ x = batch[k]
118
+ # if len(x.shape) == 3:
119
+ # x = x[..., None]
120
+ # if x.dim() == 4:
121
+ # x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
122
+ if x.dim() == 5 and self.input_dim == 4:
123
+ b,c,t,h,w = x.shape
124
+ self.b = b
125
+ self.t = t
126
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
127
+
128
+ return x
129
+
130
+ def training_step(self, batch, batch_idx, optimizer_idx):
131
+ inputs = self.get_input(batch, self.image_key)
132
+ reconstructions, posterior = self(inputs)
133
+
134
+ if optimizer_idx == 0:
135
+ # train encoder+decoder+logvar
136
+ aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
137
+ last_layer=self.get_last_layer(), split="train")
138
+ self.log("aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
139
+ self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False)
140
+ return aeloss
141
+
142
+ if optimizer_idx == 1:
143
+ # train the discriminator
144
+ discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
145
+ last_layer=self.get_last_layer(), split="train")
146
+
147
+ self.log("discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
148
+ self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False)
149
+ return discloss
150
+
151
+ def validation_step(self, batch, batch_idx):
152
+ inputs = self.get_input(batch, self.image_key)
153
+ reconstructions, posterior = self(inputs)
154
+ aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, 0, self.global_step,
155
+ last_layer=self.get_last_layer(), split="val")
156
+
157
+ discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, 1, self.global_step,
158
+ last_layer=self.get_last_layer(), split="val")
159
+
160
+ self.log("val/rec_loss", log_dict_ae["val/rec_loss"])
161
+ self.log_dict(log_dict_ae)
162
+ self.log_dict(log_dict_disc)
163
+ return self.log_dict
164
+
165
+ def configure_optimizers(self):
166
+ lr = self.learning_rate
167
+ opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
168
+ list(self.decoder.parameters())+
169
+ list(self.quant_conv.parameters())+
170
+ list(self.post_quant_conv.parameters()),
171
+ lr=lr, betas=(0.5, 0.9))
172
+ opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
173
+ lr=lr, betas=(0.5, 0.9))
174
+ return [opt_ae, opt_disc], []
175
+
176
+ def get_last_layer(self):
177
+ return self.decoder.conv_out.weight
178
+
179
+ @torch.no_grad()
180
+ def log_images(self, batch, only_inputs=False, **kwargs):
181
+ log = dict()
182
+ x = self.get_input(batch, self.image_key)
183
+ x = x.to(self.device)
184
+ if not only_inputs:
185
+ xrec, posterior = self(x)
186
+ if x.shape[1] > 3:
187
+ # colorize with random projection
188
+ assert xrec.shape[1] > 3
189
+ x = self.to_rgb(x)
190
+ xrec = self.to_rgb(xrec)
191
+ log["samples"] = self.decode(torch.randn_like(posterior.sample()))
192
+ log["reconstructions"] = xrec
193
+ log["inputs"] = x
194
+ return log
195
+
196
+ def to_rgb(self, x):
197
+ assert self.image_key == "segmentation"
198
+ if not hasattr(self, "colorize"):
199
+ self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
200
+ x = F.conv2d(x, weight=self.colorize)
201
+ x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
202
+ return x
lvdm/models/ddpm3d.py ADDED
@@ -0,0 +1,1435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import random
4
+ import itertools
5
+ from functools import partial
6
+ from contextlib import contextmanager
7
+
8
+ import numpy as np
9
+ from tqdm import tqdm
10
+ from einops import rearrange, repeat
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ from torch.optim.lr_scheduler import LambdaLR
15
+ from torchvision.utils import make_grid
16
+ import pytorch_lightning as pl
17
+ from pytorch_lightning.utilities.distributed import rank_zero_only
18
+
19
+ from lvdm.models.modules.distributions import normal_kl, DiagonalGaussianDistribution
20
+ from lvdm.models.modules.util import make_beta_schedule, extract_into_tensor, noise_like
21
+ from lvdm.models.modules.lora import inject_trainable_lora
22
+ from lvdm.samplers.ddim import DDIMSampler
23
+ from lvdm.utils.common_utils import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config, check_istarget
24
+
25
+
26
+ def disabled_train(self, mode=True):
27
+ """Overwrite model.train with this function to make sure train/eval mode
28
+ does not change anymore."""
29
+ return self
30
+
31
+
32
+ def uniform_on_device(r1, r2, shape, device):
33
+ return (r1 - r2) * torch.rand(*shape, device=device) + r2
34
+
35
+
36
+ def split_video_to_clips(video, clip_length, drop_left=True):
37
+ video_length = video.shape[2]
38
+ shape = video.shape
39
+ if video_length % clip_length != 0 and drop_left:
40
+ video = video[:, :, :video_length // clip_length * clip_length, :, :]
41
+ print(f'[split_video_to_clips] Drop frames from {shape} to {video.shape}')
42
+ nclips = video_length // clip_length
43
+ clips = rearrange(video, 'b c (nc cl) h w -> (b nc) c cl h w', cl=clip_length, nc=nclips)
44
+ return clips
45
+
46
+ def merge_clips_to_videos(clips, bs):
47
+ nclips = clips.shape[0] // bs
48
+ video = rearrange(clips, '(b nc) c t h w -> b c (nc t) h w', nc=nclips)
49
+ return video
50
+
51
+ class DDPM(pl.LightningModule):
52
+ # classic DDPM with Gaussian diffusion, in pixel space
53
+ def __init__(self,
54
+ unet_config,
55
+ timesteps=1000,
56
+ beta_schedule="linear",
57
+ loss_type="l2",
58
+ ckpt_path=None,
59
+ ignore_keys=[],
60
+ load_only_unet=False,
61
+ monitor="val/loss",
62
+ use_ema=True,
63
+ first_stage_key="image",
64
+ image_size=256,
65
+ video_length=None,
66
+ channels=3,
67
+ log_every_t=100,
68
+ clip_denoised=True,
69
+ linear_start=1e-4,
70
+ linear_end=2e-2,
71
+ cosine_s=8e-3,
72
+ given_betas=None,
73
+ original_elbo_weight=0.,
74
+ v_posterior=0.,
75
+ l_simple_weight=1.,
76
+ conditioning_key=None,
77
+ parameterization="eps",
78
+ scheduler_config=None,
79
+ learn_logvar=False,
80
+ logvar_init=0.,
81
+ *args, **kwargs
82
+ ):
83
+ super().__init__()
84
+ assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"'
85
+ self.parameterization = parameterization
86
+ print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
87
+ self.cond_stage_model = None
88
+ self.clip_denoised = clip_denoised
89
+ self.log_every_t = log_every_t
90
+ self.first_stage_key = first_stage_key
91
+ self.image_size = image_size # try conv?
92
+
93
+ if isinstance(self.image_size, int):
94
+ self.image_size = [self.image_size, self.image_size]
95
+ self.channels = channels
96
+ self.model = DiffusionWrapper(unet_config, conditioning_key)
97
+ self.conditioning_key = conditioning_key # also register conditioning_key in diffusion
98
+
99
+ self.temporal_length = video_length if video_length is not None else unet_config.params.temporal_length
100
+ count_params(self.model, verbose=True)
101
+ self.use_ema = use_ema
102
+
103
+ self.use_scheduler = scheduler_config is not None
104
+ if self.use_scheduler:
105
+ self.scheduler_config = scheduler_config
106
+
107
+ self.v_posterior = v_posterior
108
+ self.original_elbo_weight = original_elbo_weight
109
+ self.l_simple_weight = l_simple_weight
110
+
111
+ if monitor is not None:
112
+ self.monitor = monitor
113
+ if ckpt_path is not None:
114
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet)
115
+
116
+ self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
117
+ linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
118
+
119
+ self.loss_type = loss_type
120
+
121
+ self.learn_logvar = learn_logvar
122
+ self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
123
+ if self.learn_logvar:
124
+ self.logvar = nn.Parameter(self.logvar, requires_grad=True)
125
+
126
+ def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
127
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
128
+ if exists(given_betas):
129
+ betas = given_betas
130
+ else:
131
+ betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
132
+ cosine_s=cosine_s)
133
+ alphas = 1. - betas
134
+ alphas_cumprod = np.cumprod(alphas, axis=0)
135
+ alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
136
+
137
+ timesteps, = betas.shape
138
+ self.num_timesteps = int(timesteps)
139
+ self.linear_start = linear_start
140
+ self.linear_end = linear_end
141
+ assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
142
+
143
+ to_torch = partial(torch.tensor, dtype=torch.float32)
144
+
145
+ self.register_buffer('betas', to_torch(betas))
146
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
147
+ self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
148
+
149
+ # calculations for diffusion q(x_t | x_{t-1}) and others
150
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
151
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
152
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
153
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
154
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
155
+
156
+ # calculations for posterior q(x_{t-1} | x_t, x_0)
157
+ posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
158
+ 1. - alphas_cumprod) + self.v_posterior * betas
159
+ # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
160
+ self.register_buffer('posterior_variance', to_torch(posterior_variance))
161
+ # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
162
+ self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
163
+ self.register_buffer('posterior_mean_coef1', to_torch(
164
+ betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
165
+ self.register_buffer('posterior_mean_coef2', to_torch(
166
+ (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
167
+
168
+ if self.parameterization == "eps":
169
+ lvlb_weights = self.betas ** 2 / (
170
+ 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
171
+ elif self.parameterization == "x0":
172
+ lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
173
+ else:
174
+ raise NotImplementedError("mu not supported")
175
+ # TODO how to choose this term
176
+ lvlb_weights[0] = lvlb_weights[1]
177
+ self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
178
+ assert not torch.isnan(self.lvlb_weights).all()
179
+
180
+ @contextmanager
181
+ def ema_scope(self, context=None):
182
+ if self.use_ema:
183
+ self.model_ema.store(self.model.parameters())
184
+ self.model_ema.copy_to(self.model)
185
+ if context is not None:
186
+ print(f"{context}: Switched to EMA weights")
187
+ try:
188
+ yield None
189
+ finally:
190
+ if self.use_ema:
191
+ self.model_ema.restore(self.model.parameters())
192
+ if context is not None:
193
+ print(f"{context}: Restored training weights")
194
+
195
+ def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
196
+ sd = torch.load(path, map_location="cpu")
197
+ if "state_dict" in list(sd.keys()):
198
+ sd = sd["state_dict"]
199
+ keys = list(sd.keys())
200
+ for k in keys:
201
+ for ik in ignore_keys:
202
+ if k.startswith(ik) or (ik.startswith('**') and ik.split('**')[-1] in k):
203
+ print("Deleting key {} from state_dict.".format(k))
204
+ del sd[k]
205
+ missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
206
+ sd, strict=False)
207
+ print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
208
+ if len(missing) > 0:
209
+ print(f"Missing Keys: {missing}")
210
+ if len(unexpected) > 0:
211
+ print(f"Unexpected Keys: {unexpected}")
212
+
213
+ def q_mean_variance(self, x_start, t):
214
+ """
215
+ Get the distribution q(x_t | x_0).
216
+ :param x_start: the [N x C x ...] tensor of noiseless inputs.
217
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
218
+ :return: A tuple (mean, variance, log_variance), all of x_start's shape.
219
+ """
220
+ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
221
+ variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
222
+ log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
223
+ return mean, variance, log_variance
224
+
225
+ def predict_start_from_noise(self, x_t, t, noise):
226
+ return (
227
+ extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
228
+ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
229
+ )
230
+
231
+ def q_posterior(self, x_start, x_t, t):
232
+ posterior_mean = (
233
+ extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
234
+ extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
235
+ )
236
+ posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
237
+ posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
238
+ return posterior_mean, posterior_variance, posterior_log_variance_clipped
239
+
240
+ def p_mean_variance(self, x, t, clip_denoised: bool):
241
+ model_out = self.model(x, t)
242
+ if self.parameterization == "eps":
243
+ x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
244
+ elif self.parameterization == "x0":
245
+ x_recon = model_out
246
+ if clip_denoised:
247
+ x_recon.clamp_(-1., 1.)
248
+
249
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
250
+ return model_mean, posterior_variance, posterior_log_variance
251
+
252
+ @torch.no_grad()
253
+ def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
254
+ b, *_, device = *x.shape, x.device
255
+ model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
256
+ noise = noise_like(x.shape, device, repeat_noise)
257
+ # no noise when t == 0
258
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
259
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
260
+
261
+ @torch.no_grad()
262
+ def p_sample_loop(self, shape, return_intermediates=False):
263
+ device = self.betas.device
264
+ b = shape[0]
265
+ img = torch.randn(shape, device=device)
266
+ intermediates = [img]
267
+ for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
268
+ img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
269
+ clip_denoised=self.clip_denoised)
270
+ if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
271
+ intermediates.append(img)
272
+ if return_intermediates:
273
+ return img, intermediates
274
+ return img
275
+
276
+ @torch.no_grad()
277
+ def sample(self, batch_size=16, return_intermediates=False):
278
+ channels = self.channels
279
+ video_length = self.total_length
280
+ size = (batch_size, channels, video_length, *self.image_size)
281
+ return self.p_sample_loop(size,
282
+ return_intermediates=return_intermediates)
283
+
284
+ def q_sample(self, x_start, t, noise=None):
285
+ noise = default(noise, lambda: torch.randn_like(x_start))
286
+ return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
287
+ extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
288
+
289
+ def get_loss(self, pred, target, mean=True, mask=None):
290
+ if self.loss_type == 'l1':
291
+ loss = (target - pred).abs()
292
+ if mean:
293
+ loss = loss.mean()
294
+ elif self.loss_type == 'l2':
295
+ if mean:
296
+ loss = torch.nn.functional.mse_loss(target, pred)
297
+ else:
298
+ loss = torch.nn.functional.mse_loss(target, pred, reduction='none')
299
+ else:
300
+ raise NotImplementedError("unknown loss type '{loss_type}'")
301
+ if mask is not None:
302
+ assert(mean is False)
303
+ assert(loss.shape[2:] == mask.shape[2:]) #thw need be the same
304
+ loss = loss * mask
305
+ return loss
306
+
307
+ def p_losses(self, x_start, t, noise=None):
308
+ noise = default(noise, lambda: torch.randn_like(x_start))
309
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
310
+ model_out = self.model(x_noisy, t)
311
+
312
+ loss_dict = {}
313
+ if self.parameterization == "eps":
314
+ target = noise
315
+ elif self.parameterization == "x0":
316
+ target = x_start
317
+ else:
318
+ raise NotImplementedError(f"Paramterization {self.parameterization} not yet supported")
319
+
320
+ loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3, 4])
321
+
322
+ log_prefix = 'train' if self.training else 'val'
323
+
324
+ loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()})
325
+ loss_simple = loss.mean() * self.l_simple_weight
326
+
327
+ loss_vlb = (self.lvlb_weights[t] * loss).mean()
328
+ loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb})
329
+
330
+ loss = loss_simple + self.original_elbo_weight * loss_vlb
331
+
332
+ loss_dict.update({f'{log_prefix}/loss': loss})
333
+
334
+ return loss, loss_dict
335
+
336
+ def forward(self, x, *args, **kwargs):
337
+ t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
338
+ return self.p_losses(x, t, *args, **kwargs)
339
+
340
+ def get_input(self, batch, k):
341
+ x = batch[k]
342
+ x = x.to(memory_format=torch.contiguous_format).float()
343
+ return x
344
+
345
+ def shared_step(self, batch):
346
+ x = self.get_input(batch, self.first_stage_key)
347
+ loss, loss_dict = self(x)
348
+ return loss, loss_dict
349
+
350
+ def training_step(self, batch, batch_idx):
351
+ loss, loss_dict = self.shared_step(batch)
352
+
353
+ self.log_dict(loss_dict, prog_bar=True,
354
+ logger=True, on_step=True, on_epoch=True)
355
+
356
+ self.log("global_step", self.global_step,
357
+ prog_bar=True, logger=True, on_step=True, on_epoch=False)
358
+
359
+ if self.use_scheduler:
360
+ lr = self.optimizers().param_groups[0]['lr']
361
+ self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
362
+
363
+ if self.log_time:
364
+ total_train_time = (time.time() - self.start_time) / (3600*24)
365
+ avg_step_time = (time.time() - self.start_time) / (self.global_step + 1)
366
+ left_time_2w_step = (20000-self.global_step -1) * avg_step_time / (3600*24)
367
+ left_time_5w_step = (50000-self.global_step -1) * avg_step_time / (3600*24)
368
+ with open(self.logger_path, 'w') as f:
369
+ print(f'total_train_time = {total_train_time:.1f} days \n\
370
+ total_train_step = {self.global_step + 1} steps \n\
371
+ left_time_2w_step = {left_time_2w_step:.1f} days \n\
372
+ left_time_5w_step = {left_time_5w_step:.1f} days', file=f)
373
+ return loss
374
+
375
+ @torch.no_grad()
376
+ def validation_step(self, batch, batch_idx):
377
+ # _, loss_dict_no_ema = self.shared_step_validate(batch)
378
+ # with self.ema_scope():
379
+ # _, loss_dict_ema = self.shared_step_validate(batch)
380
+ # loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema}
381
+ # self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
382
+ # self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
383
+ if (self.global_step) % self.val_fvd_interval == 0 and self.global_step != 0:
384
+ print(f'sample for fvd...')
385
+ self.log_images_kwargs = {
386
+ 'inpaint': False,
387
+ 'plot_diffusion_rows': False,
388
+ 'plot_progressive_rows': False,
389
+ 'ddim_steps': 50,
390
+ 'unconditional_guidance_scale': 15.0,
391
+ }
392
+ torch.cuda.empty_cache()
393
+ logs = self.log_images(batch, **self.log_images_kwargs)
394
+ self.log("batch_idx", batch_idx,
395
+ prog_bar=True, on_step=True, on_epoch=False)
396
+ return {'real': logs['inputs'], 'fake': logs['samples'], 'conditioning_txt_img': logs['conditioning_txt_img']}
397
+
398
+ def get_condition_validate(self, prompt):
399
+ """ text embd
400
+ """
401
+ if isinstance(prompt, str):
402
+ prompt = [prompt]
403
+ c = self.get_learned_conditioning(prompt)
404
+ bs = c.shape[0]
405
+
406
+ return c
407
+
408
+ def on_train_batch_end(self, *args, **kwargs):
409
+ if self.use_ema:
410
+ self.model_ema(self.model)
411
+
412
+ def training_epoch_end(self, outputs):
413
+
414
+ if (self.current_epoch == 0) or self.resume_new_epoch == 0:
415
+ self.epoch_start_time = time.time()
416
+ self.current_epoch_time = 0
417
+ self.total_time = 0
418
+ self.epoch_time_avg = 0
419
+ else:
420
+ self.current_epoch_time = time.time() - self.epoch_start_time
421
+ self.epoch_start_time = time.time()
422
+ self.total_time += self.current_epoch_time
423
+ self.epoch_time_avg = self.total_time / self.current_epoch
424
+ self.resume_new_epoch += 1
425
+ epoch_avg_loss = torch.stack([x['loss'] for x in outputs]).mean()
426
+
427
+ self.log('train/epoch/loss', epoch_avg_loss, logger=True, on_epoch=True)
428
+ self.log('train/epoch/idx', self.current_epoch, logger=True, on_epoch=True)
429
+ self.log('train/epoch/time', self.current_epoch_time, logger=True, on_epoch=True)
430
+ self.log('train/epoch/time_avg', self.epoch_time_avg, logger=True, on_epoch=True)
431
+ self.log('train/epoch/time_avg_min', self.epoch_time_avg / 60, logger=True, on_epoch=True)
432
+
433
+ def _get_rows_from_list(self, samples):
434
+ n_imgs_per_row = len(samples)
435
+ denoise_grid = rearrange(samples, 'n b c t h w -> b n c t h w')
436
+ denoise_grid = rearrange(denoise_grid, 'b n c t h w -> (b n) c t h w')
437
+ denoise_grid = rearrange(denoise_grid, 'n c t h w -> (n t) c h w')
438
+ denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
439
+ return denoise_grid
440
+
441
+ @torch.no_grad()
442
+ def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None,
443
+ plot_diffusion_rows=True, plot_denoise_rows=True, **kwargs):
444
+ """ log images for DDPM """
445
+ log = dict()
446
+ x = self.get_input(batch, self.first_stage_key)
447
+ N = min(x.shape[0], N)
448
+ n_row = min(x.shape[0], n_row)
449
+ x = x.to(self.device)[:N]
450
+ log["inputs"] = x
451
+ if 'fps' in batch:
452
+ log['fps'] = batch['fps']
453
+
454
+ if plot_diffusion_rows:
455
+ # get diffusion row
456
+ diffusion_row = list()
457
+ x_start = x[:n_row]
458
+
459
+ for t in range(self.num_timesteps):
460
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
461
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
462
+ t = t.to(self.device).long()
463
+ noise = torch.randn_like(x_start)
464
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
465
+ diffusion_row.append(x_noisy)
466
+
467
+ log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
468
+
469
+ if sample:
470
+ # get denoise row
471
+ with self.ema_scope("Plotting"):
472
+ samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
473
+
474
+ log["samples"] = samples
475
+ if plot_denoise_rows:
476
+ log["denoise_row"] = self._get_rows_from_list(denoise_row)
477
+
478
+ if return_keys:
479
+ if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
480
+ return log
481
+ else:
482
+ return {key: log[key] for key in return_keys}
483
+ return log
484
+
485
+ def configure_optimizers(self):
486
+ lr = self.learning_rate
487
+ params = list(self.model.parameters())
488
+ if self.learn_logvar:
489
+ params = params + [self.logvar]
490
+ opt = torch.optim.AdamW(params, lr=lr)
491
+ return opt
492
+
493
+
494
+ class LatentDiffusion(DDPM):
495
+ """main class"""
496
+ def __init__(self,
497
+ first_stage_config,
498
+ cond_stage_config,
499
+ num_timesteps_cond=None,
500
+ cond_stage_key="image",
501
+ cond_stage_trainable=False,
502
+ concat_mode=True,
503
+ cond_stage_forward=None,
504
+ conditioning_key=None,
505
+ scale_factor=1.0,
506
+ scale_by_std=False,
507
+ encoder_type="2d",
508
+ shift_factor=0.0,
509
+ split_clips=True,
510
+ downfactor_t=None,
511
+ clip_length=None,
512
+ only_model=False,
513
+ lora_args={},
514
+ *args, **kwargs):
515
+ self.num_timesteps_cond = default(num_timesteps_cond, 1)
516
+ self.scale_by_std = scale_by_std
517
+ assert self.num_timesteps_cond <= kwargs['timesteps']
518
+ # for backwards compatibility after implementation of DiffusionWrapper
519
+
520
+ if conditioning_key is None:
521
+ conditioning_key = 'concat' if concat_mode else 'crossattn'
522
+ if cond_stage_config == '__is_unconditional__':
523
+ conditioning_key = None
524
+ ckpt_path = kwargs.pop("ckpt_path", None)
525
+ ignore_keys = kwargs.pop("ignore_keys", [])
526
+ super().__init__(conditioning_key=conditioning_key, *args, **kwargs)
527
+ self.concat_mode = concat_mode
528
+ self.cond_stage_trainable = cond_stage_trainable
529
+ self.cond_stage_key = cond_stage_key
530
+ try:
531
+ self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
532
+ except:
533
+ self.num_downs = 0
534
+ if not scale_by_std:
535
+ self.scale_factor = scale_factor
536
+ else:
537
+ self.register_buffer('scale_factor', torch.tensor(scale_factor))
538
+ self.instantiate_first_stage(first_stage_config)
539
+ self.instantiate_cond_stage(cond_stage_config)
540
+ self.cond_stage_forward = cond_stage_forward
541
+ self.clip_denoised = False
542
+ self.bbox_tokenizer = None
543
+ self.cond_stage_config = cond_stage_config
544
+ self.first_stage_config = first_stage_config
545
+ self.encoder_type = encoder_type
546
+ assert(encoder_type in ["2d", "3d"])
547
+ self.restarted_from_ckpt = False
548
+ self.shift_factor = shift_factor
549
+ if ckpt_path is not None:
550
+ self.init_from_ckpt(ckpt_path, ignore_keys, only_model=only_model)
551
+ self.restarted_from_ckpt = True
552
+ self.split_clips = split_clips
553
+ self.downfactor_t = downfactor_t
554
+ self.clip_length = clip_length
555
+ # lora related args
556
+ self.inject_unet = getattr(lora_args, "inject_unet", False)
557
+ self.inject_clip = getattr(lora_args, "inject_clip", False)
558
+ self.inject_unet_key_word = getattr(lora_args, "inject_unet_key_word", None)
559
+ self.inject_clip_key_word = getattr(lora_args, "inject_clip_key_word", None)
560
+ self.lora_rank = getattr(lora_args, "lora_rank", 4)
561
+
562
+ def make_cond_schedule(self, ):
563
+ self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
564
+ ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
565
+ self.cond_ids[:self.num_timesteps_cond] = ids
566
+
567
+ def inject_lora(self, lora_scale=1.0):
568
+ if self.inject_unet:
569
+ self.lora_require_grad_params, self.lora_names = inject_trainable_lora(self.model, self.inject_unet_key_word,
570
+ r=self.lora_rank,
571
+ scale=lora_scale
572
+ )
573
+ if self.inject_clip:
574
+ self.lora_require_grad_params_clip, self.lora_names_clip = inject_trainable_lora(self.cond_stage_model, self.inject_clip_key_word,
575
+ r=self.lora_rank,
576
+ scale=lora_scale
577
+ )
578
+
579
+ @rank_zero_only
580
+ @torch.no_grad()
581
+ def on_train_batch_start(self, batch, batch_idx, dataloader_idx=None):
582
+ # only for very first batch, reset the self.scale_factor
583
+ if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt:
584
+ assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'
585
+ # set rescale weight to 1./std of encodings
586
+ print("### USING STD-RESCALING ###")
587
+ x = super().get_input(batch, self.first_stage_key)
588
+ x = x.to(self.device)
589
+ encoder_posterior = self.encode_first_stage(x)
590
+ z = self.get_first_stage_encoding(encoder_posterior).detach()
591
+ del self.scale_factor
592
+ self.register_buffer('scale_factor', 1. / z.flatten().std())
593
+ print(f"setting self.scale_factor to {self.scale_factor}")
594
+ print("### USING STD-RESCALING ###")
595
+ print(f"std={z.flatten().std()}")
596
+
597
+ def register_schedule(self,
598
+ given_betas=None, beta_schedule="linear", timesteps=1000,
599
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
600
+ super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)
601
+
602
+ self.shorten_cond_schedule = self.num_timesteps_cond > 1
603
+ if self.shorten_cond_schedule:
604
+ self.make_cond_schedule()
605
+
606
+ def instantiate_first_stage(self, config):
607
+ model = instantiate_from_config(config)
608
+ self.first_stage_model = model.eval()
609
+ self.first_stage_model.train = disabled_train
610
+ for param in self.first_stage_model.parameters():
611
+ param.requires_grad = False
612
+
613
+ def instantiate_cond_stage(self, config):
614
+ if config is None:
615
+ self.cond_stage_model = None
616
+ return
617
+ if not self.cond_stage_trainable:
618
+ if config == "__is_first_stage__":
619
+ print("Using first stage also as cond stage.")
620
+ self.cond_stage_model = self.first_stage_model
621
+ elif config == "__is_unconditional__":
622
+ print(f"Training {self.__class__.__name__} as an unconditional model.")
623
+ self.cond_stage_model = None
624
+ else:
625
+ model = instantiate_from_config(config)
626
+ self.cond_stage_model = model.eval()
627
+ self.cond_stage_model.train = disabled_train
628
+ for param in self.cond_stage_model.parameters():
629
+ param.requires_grad = False
630
+ else:
631
+ assert config != '__is_first_stage__'
632
+ assert config != '__is_unconditional__'
633
+ model = instantiate_from_config(config)
634
+ self.cond_stage_model = model
635
+
636
+
637
+ def get_first_stage_encoding(self, encoder_posterior, noise=None):
638
+ if isinstance(encoder_posterior, DiagonalGaussianDistribution):
639
+ z = encoder_posterior.sample(noise=noise)
640
+ elif isinstance(encoder_posterior, torch.Tensor):
641
+ z = encoder_posterior
642
+ else:
643
+ raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
644
+ z = self.scale_factor * (z + self.shift_factor)
645
+ return z
646
+
647
+
648
+ def get_learned_conditioning(self, c):
649
+ if self.cond_stage_forward is None:
650
+ if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
651
+ c = self.cond_stage_model.encode(c)
652
+ if isinstance(c, DiagonalGaussianDistribution):
653
+ c = c.mode()
654
+ else:
655
+ c = self.cond_stage_model(c)
656
+ else:
657
+ assert hasattr(self.cond_stage_model, self.cond_stage_forward)
658
+ c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
659
+ return c
660
+
661
+
662
+ @torch.no_grad()
663
+ def get_condition(self, batch, x, bs, force_c_encode, k, cond_key, is_imgs=False):
664
+ is_conditional = self.model.conditioning_key is not None # crossattn
665
+ if is_conditional:
666
+ if cond_key is None:
667
+ cond_key = self.cond_stage_key
668
+
669
+ # get condition batch of different condition type
670
+ if cond_key != self.first_stage_key:
671
+ assert(cond_key in ["caption", "txt"])
672
+ xc = batch[cond_key]
673
+ else:
674
+ xc = x
675
+
676
+ # if static video
677
+ if self.static_video:
678
+ xc_ = [c + ' (static)' for c in xc]
679
+ xc = xc_
680
+
681
+ # get learned condition.
682
+ # can directly skip it: c = xc
683
+ if self.cond_stage_config is not None and (not self.cond_stage_trainable or force_c_encode):
684
+ if isinstance(xc, torch.Tensor):
685
+ xc = xc.to(self.device)
686
+ c = self.get_learned_conditioning(xc)
687
+ else:
688
+ c = xc
689
+
690
+ if self.classfier_free_guidance:
691
+ if cond_key in ['caption', "txt"] and self.uncond_type == 'empty_seq':
692
+ for i, ci in enumerate(c):
693
+ if random.random() < self.prob:
694
+ c[i] = ""
695
+ elif cond_key == 'class_label' and self.uncond_type == 'zero_embed':
696
+ pass
697
+ elif cond_key == 'class_label' and self.uncond_type == 'learned_embed':
698
+ import pdb;pdb.set_trace()
699
+ for i, ci in enumerate(c):
700
+ if random.random() < self.prob:
701
+ c[i]['class_label'] = self.n_classes
702
+
703
+ else:
704
+ raise NotImplementedError
705
+
706
+ if self.zero_cond_embed:
707
+ import pdb;pdb.set_trace()
708
+ c = torch.zeros_like(c)
709
+
710
+ # process c
711
+ if bs is not None:
712
+ if (is_imgs and not self.static_video):
713
+ c = c[:bs*self.temporal_length] # each random img (in T axis) has a corresponding prompt
714
+ else:
715
+ c = c[:bs]
716
+
717
+ else:
718
+ c = None
719
+ xc = None
720
+
721
+ return c, xc
722
+
723
+ @torch.no_grad()
724
+ def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,
725
+ cond_key=None, return_original_cond=False, bs=None, mask_temporal=False):
726
+ """ Get input in LDM
727
+ """
728
+ # get input imgaes
729
+ x = super().get_input(batch, k) # k = first_stage_key=image
730
+ is_imgs = True if k == 'jpg' else False
731
+ if is_imgs:
732
+ if self.static_video:
733
+ # repeat single img to a static video
734
+ x = x.unsqueeze(2) # bchw -> bc1hw
735
+ x = x.repeat(1,1,self.temporal_length,1,1) # bc1hw -> bcthw
736
+ else:
737
+ # rearrange to videos with T random img
738
+ bs_load = x.shape[0] // self.temporal_length
739
+ x = x[:bs_load*self.temporal_length, ...]
740
+ x = rearrange(x, '(b t) c h w -> b c t h w', t=self.temporal_length, b=bs_load)
741
+
742
+ if bs is not None:
743
+ x = x[:bs]
744
+
745
+ x = x.to(self.device)
746
+ x_ori = x
747
+
748
+ b, _, t, h, w = x.shape
749
+
750
+ # encode video frames x to z via a 2D encoder
751
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
752
+ encoder_posterior = self.encode_first_stage(x, mask_temporal)
753
+ z = self.get_first_stage_encoding(encoder_posterior).detach()
754
+ z = rearrange(z, '(b t) c h w -> b c t h w', b=b, t=t)
755
+
756
+
757
+ c, xc = self.get_condition(batch, x, bs, force_c_encode, k, cond_key, is_imgs)
758
+ out = [z, c]
759
+
760
+ if return_first_stage_outputs:
761
+ xrec = self.decode_first_stage(z, mask_temporal=mask_temporal)
762
+ out.extend([x_ori, xrec])
763
+ if return_original_cond:
764
+ if isinstance(xc, torch.Tensor) and xc.dim() == 4:
765
+ xc = rearrange(xc, '(b t) c h w -> b c t h w', b=b, t=t)
766
+ out.append(xc)
767
+
768
+ return out
769
+
770
+ @torch.no_grad()
771
+ def decode(self, z, **kwargs,):
772
+ z = 1. / self.scale_factor * z - self.shift_factor
773
+ results = self.first_stage_model.decode(z,**kwargs)
774
+ return results
775
+
776
+ @torch.no_grad()
777
+ def decode_first_stage_2DAE(self, z, decode_bs=16, return_cpu=True, **kwargs):
778
+ b, _, t, _, _ = z.shape
779
+ z = rearrange(z, 'b c t h w -> (b t) c h w')
780
+ if decode_bs is None:
781
+ results = self.decode(z, **kwargs)
782
+ else:
783
+ z = torch.split(z, decode_bs, dim=0)
784
+ if return_cpu:
785
+ results = torch.cat([self.decode(z_, **kwargs).cpu() for z_ in z], dim=0)
786
+ else:
787
+ results = torch.cat([self.decode(z_, **kwargs) for z_ in z], dim=0)
788
+ results = rearrange(results, '(b t) c h w -> b c t h w', b=b,t=t).contiguous()
789
+ return results
790
+
791
+ @torch.no_grad()
792
+ def decode_first_stage(self, z, decode_bs=16, return_cpu=True, **kwargs):
793
+ assert(self.encoder_type == "2d" and z.dim() == 5)
794
+ return self.decode_first_stage_2DAE(z, decode_bs=decode_bs, return_cpu=return_cpu, **kwargs)
795
+
796
+ @torch.no_grad()
797
+ def encode_first_stage_2DAE(self, x, encode_bs=16):
798
+ b, _, t, _, _ = x.shape
799
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
800
+ if encode_bs is None:
801
+ results = self.first_stage_model.encode(x)
802
+ else:
803
+ x = torch.split(x, encode_bs, dim=0)
804
+ zs = []
805
+ for x_ in x:
806
+ encoder_posterior = self.first_stage_model.encode(x_)
807
+ z = self.get_first_stage_encoding(encoder_posterior).detach()
808
+ zs.append(z)
809
+ results = torch.cat(zs, dim=0)
810
+ results = rearrange(results, '(b t) c h w -> b c t h w', b=b,t=t)
811
+ return results
812
+
813
+ @torch.no_grad()
814
+ def encode_first_stage(self, x):
815
+ assert(self.encoder_type == "2d" and x.dim() == 5)
816
+ b, _, t, _, _ = x.shape
817
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
818
+ results = self.first_stage_model.encode(x)
819
+ results = rearrange(results, '(b t) c h w -> b c t h w', b=b,t=t)
820
+ return results
821
+
822
+ def shared_step(self, batch, **kwargs):
823
+ """ shared step of LDM.
824
+ If learned condition, c is raw condition (e.g. text)
825
+ Encoding condition is performed in below forward function.
826
+ """
827
+ x, c = self.get_input(batch, self.first_stage_key)
828
+ loss = self(x, c)
829
+ return loss
830
+
831
+ def forward(self, x, c, *args, **kwargs):
832
+ start_t = getattr(self, "start_t", 0)
833
+ end_t = getattr(self, "end_t", self.num_timesteps)
834
+ t = torch.randint(start_t, end_t, (x.shape[0],), device=self.device).long()
835
+
836
+ if self.model.conditioning_key is not None:
837
+ assert c is not None
838
+ if self.cond_stage_trainable:
839
+ c = self.get_learned_conditioning(c)
840
+ if self.classfier_free_guidance and self.uncond_type == 'zero_embed':
841
+ for i, ci in enumerate(c):
842
+ if random.random() < self.prob:
843
+ c[i] = torch.zeros_like(c[i])
844
+ if self.shorten_cond_schedule: # TODO: drop this option
845
+ tc = self.cond_ids[t].to(self.device)
846
+ c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))
847
+
848
+ return self.p_losses(x, c, t, *args, **kwargs)
849
+
850
+ def apply_model(self, x_noisy, t, cond, return_ids=False, **kwargs):
851
+
852
+ if isinstance(cond, dict):
853
+ # hybrid case, cond is exptected to be a dict
854
+ pass
855
+ else:
856
+ if not isinstance(cond, list):
857
+ cond = [cond]
858
+ key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
859
+ cond = {key: cond}
860
+
861
+ x_recon = self.model(x_noisy, t, **cond, **kwargs)
862
+
863
+ if isinstance(x_recon, tuple) and not return_ids:
864
+ return x_recon[0]
865
+ else:
866
+ return x_recon
867
+
868
+ def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
869
+ return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \
870
+ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
871
+
872
+ def _prior_bpd(self, x_start):
873
+ """
874
+ Get the prior KL term for the variational lower-bound, measured in
875
+ bits-per-dim.
876
+ This term can't be optimized, as it only depends on the encoder.
877
+ :param x_start: the [N x C x ...] tensor of inputs.
878
+ :return: a batch of [N] KL values (in bits), one per batch element.
879
+ """
880
+ batch_size = x_start.shape[0]
881
+ t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
882
+ qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
883
+ kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
884
+ return mean_flat(kl_prior) / np.log(2.0)
885
+
886
+ def p_losses(self, x_start, cond, t, noise=None, skip_qsample=False, x_noisy=None, cond_mask=None, **kwargs,):
887
+ if not skip_qsample:
888
+ noise = default(noise, lambda: torch.randn_like(x_start))
889
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
890
+ else:
891
+ assert(x_noisy is not None)
892
+ assert(noise is not None)
893
+ model_output = self.apply_model(x_noisy, t, cond, **kwargs)
894
+
895
+ loss_dict = {}
896
+ prefix = 'train' if self.training else 'val'
897
+
898
+ if self.parameterization == "x0":
899
+ target = x_start
900
+ elif self.parameterization == "eps":
901
+ target = noise
902
+ else:
903
+ raise NotImplementedError()
904
+
905
+ loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3, 4])
906
+ loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
907
+ if self.logvar.device != self.device:
908
+ self.logvar = self.logvar.to(self.device)
909
+ logvar_t = self.logvar[t]
910
+ loss = loss_simple / torch.exp(logvar_t) + logvar_t
911
+ if self.learn_logvar:
912
+ loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
913
+ loss_dict.update({'logvar': self.logvar.data.mean()})
914
+
915
+ loss = self.l_simple_weight * loss.mean()
916
+
917
+ loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3, 4))
918
+ loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
919
+ loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
920
+ loss += (self.original_elbo_weight * loss_vlb)
921
+ loss_dict.update({f'{prefix}/loss': loss})
922
+
923
+ return loss, loss_dict
924
+
925
+ def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,
926
+ return_x0=False, score_corrector=None, corrector_kwargs=None,
927
+ unconditional_guidance_scale=1., unconditional_conditioning=None,
928
+ uc_type=None,):
929
+ t_in = t
930
+ if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
931
+ model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)
932
+ else:
933
+ # with unconditional condition
934
+ if isinstance(c, torch.Tensor):
935
+ x_in = torch.cat([x] * 2)
936
+ t_in = torch.cat([t] * 2)
937
+ c_in = torch.cat([unconditional_conditioning, c])
938
+ model_out_uncond, model_out = self.apply_model(x_in, t_in, c_in, return_ids=return_codebook_ids).chunk(2)
939
+ elif isinstance(c, dict):
940
+ model_out = self.apply_model(x, t, c, return_ids=return_codebook_ids)
941
+ model_out_uncond = self.apply_model(x, t, unconditional_conditioning, return_ids=return_codebook_ids)
942
+ else:
943
+ raise NotImplementedError
944
+ if uc_type is None:
945
+ model_out = model_out_uncond + unconditional_guidance_scale * (model_out - model_out_uncond)
946
+ else:
947
+ if uc_type == 'cfg_original':
948
+ model_out = model_out + unconditional_guidance_scale * (model_out - model_out_uncond)
949
+ elif uc_type == 'cfg_ours':
950
+ model_out = model_out + unconditional_guidance_scale * (model_out_uncond - model_out)
951
+ else:
952
+ raise NotImplementedError
953
+
954
+ if score_corrector is not None:
955
+ assert self.parameterization == "eps"
956
+ model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
957
+
958
+ if return_codebook_ids:
959
+ model_out, logits = model_out
960
+
961
+ if self.parameterization == "eps":
962
+ x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
963
+ elif self.parameterization == "x0":
964
+ x_recon = model_out
965
+ else:
966
+ raise NotImplementedError()
967
+
968
+ if clip_denoised:
969
+ x_recon.clamp_(-1., 1.)
970
+ if quantize_denoised:
971
+ x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)
972
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
973
+ if return_codebook_ids:
974
+ return model_mean, posterior_variance, posterior_log_variance, logits
975
+ elif return_x0:
976
+ return model_mean, posterior_variance, posterior_log_variance, x_recon
977
+ else:
978
+ return model_mean, posterior_variance, posterior_log_variance
979
+
980
+ @torch.no_grad()
981
+ def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,
982
+ return_codebook_ids=False, quantize_denoised=False, return_x0=False,
983
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
984
+ unconditional_guidance_scale=1., unconditional_conditioning=None,
985
+ uc_type=None,):
986
+ b, *_, device = *x.shape, x.device
987
+ outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,
988
+ return_codebook_ids=return_codebook_ids,
989
+ quantize_denoised=quantize_denoised,
990
+ return_x0=return_x0,
991
+ score_corrector=score_corrector, corrector_kwargs=corrector_kwargs,
992
+ unconditional_guidance_scale=unconditional_guidance_scale,
993
+ unconditional_conditioning=unconditional_conditioning,
994
+ uc_type=uc_type,)
995
+ if return_codebook_ids:
996
+ raise DeprecationWarning("Support dropped.")
997
+ elif return_x0:
998
+ model_mean, _, model_log_variance, x0 = outputs
999
+ else:
1000
+ model_mean, _, model_log_variance = outputs
1001
+
1002
+ noise = noise_like(x.shape, device, repeat_noise) * temperature
1003
+ if noise_dropout > 0.:
1004
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
1005
+
1006
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
1007
+
1008
+ if return_codebook_ids:
1009
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)
1010
+ if return_x0:
1011
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
1012
+ else:
1013
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
1014
+
1015
+ @torch.no_grad()
1016
+ def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,
1017
+ img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,
1018
+ score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,
1019
+ log_every_t=None):
1020
+ if not log_every_t:
1021
+ log_every_t = self.log_every_t
1022
+ timesteps = self.num_timesteps
1023
+ if batch_size is not None:
1024
+ b = batch_size if batch_size is not None else shape[0]
1025
+ shape = [batch_size] + list(shape)
1026
+ else:
1027
+ b = batch_size = shape[0]
1028
+ if x_T is None:
1029
+ img = torch.randn(shape, device=self.device)
1030
+ else:
1031
+ img = x_T
1032
+ intermediates = []
1033
+ if cond is not None:
1034
+ if isinstance(cond, dict):
1035
+ cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
1036
+ list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
1037
+ else:
1038
+ cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
1039
+
1040
+ if start_T is not None:
1041
+ timesteps = min(timesteps, start_T)
1042
+ iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',
1043
+ total=timesteps) if verbose else reversed(
1044
+ range(0, timesteps))
1045
+ if type(temperature) == float:
1046
+ temperature = [temperature] * timesteps
1047
+
1048
+ for i in iterator:
1049
+ ts = torch.full((b,), i, device=self.device, dtype=torch.long)
1050
+ if self.shorten_cond_schedule:
1051
+ assert self.model.conditioning_key != 'hybrid'
1052
+ tc = self.cond_ids[ts].to(cond.device)
1053
+ cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
1054
+
1055
+ img, x0_partial = self.p_sample(img, cond, ts,
1056
+ clip_denoised=self.clip_denoised,
1057
+ quantize_denoised=quantize_denoised, return_x0=True,
1058
+ temperature=temperature[i], noise_dropout=noise_dropout,
1059
+ score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
1060
+ if mask is not None:
1061
+ assert x0 is not None
1062
+ img_orig = self.q_sample(x0, ts)
1063
+ img = img_orig * mask + (1. - mask) * img
1064
+
1065
+ if i % log_every_t == 0 or i == timesteps - 1:
1066
+ intermediates.append(x0_partial)
1067
+ if callback: callback(i)
1068
+ if img_callback: img_callback(img, i)
1069
+ return img, intermediates
1070
+
1071
+ @torch.no_grad()
1072
+ def p_sample_loop(self, cond, shape, return_intermediates=False,
1073
+ x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,
1074
+ mask=None, x0=None, img_callback=None, start_T=None,
1075
+ log_every_t=None,
1076
+ unconditional_guidance_scale=1., unconditional_conditioning=None,
1077
+ uc_type=None,):
1078
+
1079
+ if not log_every_t:
1080
+ log_every_t = self.log_every_t
1081
+ device = self.betas.device
1082
+ b = shape[0]
1083
+
1084
+ # sample an initial noise
1085
+ if x_T is None:
1086
+ img = torch.randn(shape, device=device)
1087
+ else:
1088
+ img = x_T
1089
+
1090
+ intermediates = [img]
1091
+ if timesteps is None:
1092
+ timesteps = self.num_timesteps
1093
+
1094
+ if start_T is not None:
1095
+ timesteps = min(timesteps, start_T)
1096
+ iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(
1097
+ range(0, timesteps))
1098
+
1099
+ if mask is not None:
1100
+ assert x0 is not None
1101
+ assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
1102
+
1103
+ for i in iterator:
1104
+ ts = torch.full((b,), i, device=device, dtype=torch.long)
1105
+ if self.shorten_cond_schedule:
1106
+ assert self.model.conditioning_key != 'hybrid'
1107
+ tc = self.cond_ids[ts].to(cond.device)
1108
+ cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
1109
+
1110
+ img = self.p_sample(img, cond, ts,
1111
+ clip_denoised=self.clip_denoised,
1112
+ quantize_denoised=quantize_denoised,
1113
+ unconditional_guidance_scale=unconditional_guidance_scale,
1114
+ unconditional_conditioning=unconditional_conditioning,
1115
+ uc_type=uc_type)
1116
+ if mask is not None:
1117
+ img_orig = self.q_sample(x0, ts)
1118
+ img = img_orig * mask + (1. - mask) * img
1119
+
1120
+ if i % log_every_t == 0 or i == timesteps - 1:
1121
+ intermediates.append(img)
1122
+ if callback: callback(i)
1123
+ if img_callback: img_callback(img, i)
1124
+
1125
+ if return_intermediates:
1126
+ return img, intermediates
1127
+ return img
1128
+
1129
+ @torch.no_grad()
1130
+ def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,
1131
+ verbose=True, timesteps=None, quantize_denoised=False,
1132
+ mask=None, x0=None, shape=None, **kwargs):
1133
+ if shape is None:
1134
+ shape = (batch_size, self.channels, self.total_length, *self.image_size)
1135
+ if cond is not None:
1136
+ if isinstance(cond, dict):
1137
+ cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
1138
+ list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
1139
+ else:
1140
+ cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
1141
+ return self.p_sample_loop(cond,
1142
+ shape,
1143
+ return_intermediates=return_intermediates, x_T=x_T,
1144
+ verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,
1145
+ mask=mask, x0=x0,)
1146
+
1147
+ @torch.no_grad()
1148
+ def sample_log(self,cond,batch_size,ddim, ddim_steps,**kwargs):
1149
+
1150
+ if ddim:
1151
+ ddim_sampler = DDIMSampler(self)
1152
+ shape = (self.channels, self.total_length, *self.image_size)
1153
+ samples, intermediates =ddim_sampler.sample(ddim_steps,batch_size,
1154
+ shape,cond,verbose=False, **kwargs)
1155
+
1156
+ else:
1157
+ samples, intermediates = self.sample(cond=cond, batch_size=batch_size,
1158
+ return_intermediates=True, **kwargs)
1159
+
1160
+ return samples, intermediates
1161
+
1162
+ @torch.no_grad()
1163
+ def log_condition(self, log, batch, xc, x, c, cond_stage_key=None):
1164
+ """
1165
+ xc: oringinal condition before enconding.
1166
+ c: condition after encoding.
1167
+ """
1168
+ if x.dim() == 5:
1169
+ txt_img_shape = [x.shape[3], x.shape[4]]
1170
+ elif x.dim() == 4:
1171
+ txt_img_shape = [x.shape[2], x.shape[3]]
1172
+ else:
1173
+ raise ValueError
1174
+ if self.model.conditioning_key is not None: #concat-time-mask
1175
+ if hasattr(self.cond_stage_model, "decode"):
1176
+ xc = self.cond_stage_model.decode(c)
1177
+ log["conditioning"] = xc
1178
+ elif cond_stage_key in ["caption", "txt"]:
1179
+ log["conditioning_txt_img"] = log_txt_as_img(txt_img_shape, batch[cond_stage_key], size=x.shape[3]//25)
1180
+ log["conditioning_txt"] = batch[cond_stage_key]
1181
+ elif cond_stage_key == 'class_label':
1182
+ try:
1183
+ xc = log_txt_as_img(txt_img_shape, batch["human_label"], size=x.shape[3]//25)
1184
+ except:
1185
+ xc = log_txt_as_img(txt_img_shape, batch["class_name"], size=x.shape[3]//25)
1186
+ log['conditioning'] = xc
1187
+ elif isimage(xc):
1188
+ log["conditioning"] = xc
1189
+ if ismap(xc):
1190
+ log["original_conditioning"] = self.to_rgb(xc)
1191
+ if isinstance(c, dict) and 'mask' in c:
1192
+ log['mask'] =self.mask_to_rgb(c['mask'])
1193
+ return log
1194
+
1195
+ @torch.no_grad()
1196
+ def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., unconditional_guidance_scale=1.0,
1197
+ first_stage_key2=None, cond_key2=None,
1198
+ c=None,
1199
+ **kwargs):
1200
+ """ log images for LatentDiffusion """
1201
+ use_ddim = ddim_steps is not None
1202
+ is_imgs = first_stage_key2 is not None
1203
+ if is_imgs:
1204
+ assert(cond_key2 is not None)
1205
+ log = dict()
1206
+
1207
+ # get input
1208
+ z, c, x, xrec, xc = self.get_input(batch,
1209
+ k=self.first_stage_key if first_stage_key2 is None else first_stage_key2,
1210
+ return_first_stage_outputs=True,
1211
+ force_c_encode=True,
1212
+ return_original_cond=True,
1213
+ bs=N,
1214
+ cond_key=cond_key2 if cond_key2 is not None else None,
1215
+ )
1216
+
1217
+ N_ori = N
1218
+ N = min(z.shape[0], N)
1219
+ n_row = min(x.shape[0], n_row)
1220
+
1221
+ if unconditional_guidance_scale != 1.0:
1222
+ prompts = N * self.temporal_length * [""] if (is_imgs and not self.static_video) else N * [""]
1223
+ uc = self.get_condition_validate(prompts)
1224
+
1225
+ else:
1226
+ uc = None
1227
+
1228
+ log["inputs"] = x
1229
+ log["reconstruction"] = xrec
1230
+ log = self.log_condition(log, batch, xc, x, c,
1231
+ cond_stage_key=self.cond_stage_key if cond_key2 is None else cond_key2
1232
+ )
1233
+
1234
+ if sample:
1235
+ with self.ema_scope("Plotting"):
1236
+ samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
1237
+ ddim_steps=ddim_steps,eta=ddim_eta,
1238
+ temporal_length=self.video_length,
1239
+ unconditional_guidance_scale=unconditional_guidance_scale,
1240
+ unconditional_conditioning=uc, **kwargs,
1241
+ )
1242
+ # decode samples
1243
+ x_samples = self.decode_first_stage(samples)
1244
+ log["samples"] = x_samples
1245
+ return log
1246
+
1247
+ def configure_optimizers(self):
1248
+ """ configure_optimizers for LatentDiffusion """
1249
+ lr = self.learning_rate
1250
+
1251
+ # --------------------------------------------------------------------------------
1252
+ # set parameters
1253
+ if hasattr(self, "only_optimize_empty_parameters") and self.only_optimize_empty_parameters:
1254
+ print("[INFO] Optimize only empty parameters!")
1255
+ assert(hasattr(self, "empty_paras"))
1256
+ params = [p for n, p in self.model.named_parameters() if n in self.empty_paras]
1257
+ elif hasattr(self, "only_optimize_pretrained_parameters") and self.only_optimize_pretrained_parameters:
1258
+ print("[INFO] Optimize only pretrained parameters!")
1259
+ assert(hasattr(self, "empty_paras"))
1260
+ params = [p for n, p in self.model.named_parameters() if n not in self.empty_paras]
1261
+ assert(len(params) != 0)
1262
+ elif getattr(self, "optimize_empty_and_spatialattn", False):
1263
+ print("[INFO] Optimize empty parameters + spatial transformer!")
1264
+ assert(hasattr(self, "empty_paras"))
1265
+ empty_paras = [p for n, p in self.model.named_parameters() if n in self.empty_paras]
1266
+ SA_list = [".attn1.", ".attn2.", ".ff.", ".norm1.", ".norm2.", ".norm3."]
1267
+ SA_params = [p for n, p in self.model.named_parameters() if check_istarget(n, SA_list)]
1268
+ if getattr(self, "spatial_lr_decay", False):
1269
+ params = [
1270
+ {"params": empty_paras},
1271
+ {"params": SA_params, "lr": lr * self.spatial_lr_decay}
1272
+ ]
1273
+ else:
1274
+ params = empty_paras + SA_params
1275
+ else:
1276
+ # optimize whole denoiser
1277
+ if hasattr(self, "spatial_lr_decay") and self.spatial_lr_decay:
1278
+ print("[INFO] Optimize the whole net with different lr!")
1279
+ print(f"[INFO] {lr} for empty paras, {lr * self.spatial_lr_decay} for pretrained paras!")
1280
+ empty_paras = [p for n, p in self.model.named_parameters() if n in self.empty_paras]
1281
+ # assert(len(empty_paras) == len(self.empty_paras)) # self.empty_paras:cond_stage_model.embedding.weight not in diffusion model params
1282
+ pretrained_paras = [p for n, p in self.model.named_parameters() if n not in self.empty_paras]
1283
+ params = [
1284
+ {"params": empty_paras},
1285
+ {"params": pretrained_paras, "lr": lr * self.spatial_lr_decay}
1286
+ ]
1287
+ print(f"[INFO] Empty paras: {len(empty_paras)}, Pretrained paras: {len(pretrained_paras)}")
1288
+
1289
+ else:
1290
+ params = list(self.model.parameters())
1291
+
1292
+ if hasattr(self, "generator_trainable") and not self.generator_trainable:
1293
+ # fix unet denoiser
1294
+ params = list()
1295
+
1296
+ if self.inject_unet:
1297
+ params = itertools.chain(*self.lora_require_grad_params)
1298
+
1299
+ if self.inject_clip:
1300
+ if self.inject_unet:
1301
+ params = list(params)+list(itertools.chain(*self.lora_require_grad_params_clip))
1302
+ else:
1303
+ params = itertools.chain(*self.lora_require_grad_params_clip)
1304
+
1305
+
1306
+ # append paras
1307
+ # ------------------------------------------------------------------
1308
+ def add_cond_model(cond_model, params):
1309
+ if isinstance(params[0], dict):
1310
+ # parameter groups
1311
+ params.append({"params": list(cond_model.parameters())})
1312
+ else:
1313
+ # parameter list: [torch.nn.parameter.Parameter]
1314
+ params = params + list(cond_model.parameters())
1315
+ return params
1316
+ # ------------------------------------------------------------------
1317
+
1318
+ if self.cond_stage_trainable:
1319
+ # print(f"{self.__class__.__name__}: Also optimizing conditioner params!")
1320
+ params = add_cond_model(self.cond_stage_model, params)
1321
+
1322
+ if self.learn_logvar:
1323
+ print('Diffusion model optimizing logvar')
1324
+ if isinstance(params[0], dict):
1325
+ params.append({"params": [self.logvar]})
1326
+ else:
1327
+ params.append(self.logvar)
1328
+
1329
+ # --------------------------------------------------------------------------------
1330
+ opt = torch.optim.AdamW(params, lr=lr)
1331
+
1332
+ # lr scheduler
1333
+ if self.use_scheduler:
1334
+ assert 'target' in self.scheduler_config
1335
+ scheduler = instantiate_from_config(self.scheduler_config)
1336
+
1337
+ print("Setting up LambdaLR scheduler...")
1338
+ scheduler = [
1339
+ {
1340
+ 'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),
1341
+ 'interval': 'step',
1342
+ 'frequency': 1
1343
+ }]
1344
+ return [opt], scheduler
1345
+
1346
+ return opt
1347
+
1348
+ @torch.no_grad()
1349
+ def to_rgb(self, x):
1350
+ x = x.float()
1351
+ if not hasattr(self, "colorize"):
1352
+ self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)
1353
+ x = nn.functional.conv2d(x, weight=self.colorize)
1354
+ x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.
1355
+ return x
1356
+
1357
+ @torch.no_grad()
1358
+ def mask_to_rgb(self, x):
1359
+ x = x * 255
1360
+ x = x.int()
1361
+ return x
1362
+
1363
+ class DiffusionWrapper(pl.LightningModule):
1364
+ def __init__(self, diff_model_config, conditioning_key):
1365
+ super().__init__()
1366
+ self.diffusion_model = instantiate_from_config(diff_model_config)
1367
+ print('Successfully initialize the diffusion model !')
1368
+ self.conditioning_key = conditioning_key
1369
+ # assert self.conditioning_key in [None, 'concat', 'crossattn', 'hybrid', 'adm', 'resblockcond', 'hybrid-adm', 'hybrid-time']
1370
+
1371
+ def forward(self, x, t, c_concat: list = None, c_crossattn: list = None,
1372
+ c_adm=None, s=None, mask=None, **kwargs):
1373
+ # temporal_context = fps is foNone
1374
+ if self.conditioning_key is None:
1375
+ out = self.diffusion_model(x, t, **kwargs)
1376
+ elif self.conditioning_key == 'concat':
1377
+ xc = torch.cat([x] + c_concat, dim=1)
1378
+ out = self.diffusion_model(xc, t, **kwargs)
1379
+ elif self.conditioning_key == 'crossattn':
1380
+ cc = torch.cat(c_crossattn, 1)
1381
+ out = self.diffusion_model(x, t, context=cc, **kwargs)
1382
+ elif self.conditioning_key == 'hybrid':
1383
+ xc = torch.cat([x] + c_concat, dim=1)
1384
+ cc = torch.cat(c_crossattn, 1)
1385
+ out = self.diffusion_model(xc, t, context=cc, **kwargs)
1386
+ elif self.conditioning_key == 'resblockcond':
1387
+ cc = c_crossattn[0]
1388
+ out = self.diffusion_model(x, t, context=cc, **kwargs)
1389
+ elif self.conditioning_key == 'adm':
1390
+ cc = c_crossattn[0]
1391
+ out = self.diffusion_model(x, t, y=cc, **kwargs)
1392
+ elif self.conditioning_key == 'hybrid-adm':
1393
+ assert c_adm is not None
1394
+ xc = torch.cat([x] + c_concat, dim=1)
1395
+ cc = torch.cat(c_crossattn, 1)
1396
+ out = self.diffusion_model(xc, t, context=cc, y=c_adm, **kwargs)
1397
+ elif self.conditioning_key == 'hybrid-time':
1398
+ assert s is not None
1399
+ xc = torch.cat([x] + c_concat, dim=1)
1400
+ cc = torch.cat(c_crossattn, 1)
1401
+ out = self.diffusion_model(xc, t, context=cc, s=s, **kwargs)
1402
+ elif self.conditioning_key == 'concat-time-mask':
1403
+ # assert s is not None
1404
+ # print('x & mask:',x.shape,c_concat[0].shape)
1405
+ xc = torch.cat([x] + c_concat, dim=1)
1406
+ out = self.diffusion_model(xc, t, context=None, s=s, mask=mask, **kwargs)
1407
+ elif self.conditioning_key == 'concat-adm-mask':
1408
+ # assert s is not None
1409
+ # print('x & mask:',x.shape,c_concat[0].shape)
1410
+ if c_concat is not None:
1411
+ xc = torch.cat([x] + c_concat, dim=1)
1412
+ else:
1413
+ xc = x
1414
+ out = self.diffusion_model(xc, t, context=None, y=s, mask=mask, **kwargs)
1415
+ elif self.conditioning_key == 'crossattn-adm':
1416
+ cc = torch.cat(c_crossattn, 1)
1417
+ out = self.diffusion_model(x, t, context=cc, y=s, **kwargs)
1418
+ elif self.conditioning_key == 'hybrid-adm-mask':
1419
+ cc = torch.cat(c_crossattn, 1)
1420
+ if c_concat is not None:
1421
+ xc = torch.cat([x] + c_concat, dim=1)
1422
+ else:
1423
+ xc = x
1424
+ out = self.diffusion_model(xc, t, context=cc, y=s, mask=mask, **kwargs)
1425
+ elif self.conditioning_key == 'hybrid-time-adm': # adm means y, e.g., class index
1426
+ # assert s is not None
1427
+ assert c_adm is not None
1428
+ xc = torch.cat([x] + c_concat, dim=1)
1429
+ cc = torch.cat(c_crossattn, 1)
1430
+ out = self.diffusion_model(xc, t, context=cc, s=s, y=c_adm, **kwargs)
1431
+ else:
1432
+ raise NotImplementedError()
1433
+
1434
+ return out
1435
+
lvdm/models/modules/attention_temporal.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Any
2
+
3
+ import torch
4
+ import torch as th
5
+ from torch import nn, einsum
6
+ from einops import rearrange, repeat
7
+ try:
8
+ import xformers
9
+ import xformers.ops
10
+ XFORMERS_IS_AVAILBLE = True
11
+ except:
12
+ XFORMERS_IS_AVAILBLE = False
13
+
14
+ from lvdm.models.modules.util import (
15
+ GEGLU,
16
+ exists,
17
+ default,
18
+ Normalize,
19
+ checkpoint,
20
+ zero_module,
21
+ )
22
+
23
+
24
+ # ---------------------------------------------------------------------------------------------------
25
+ class FeedForward(nn.Module):
26
+ def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
27
+ super().__init__()
28
+ inner_dim = int(dim * mult)
29
+ dim_out = default(dim_out, dim)
30
+ project_in = nn.Sequential(
31
+ nn.Linear(dim, inner_dim),
32
+ nn.GELU()
33
+ ) if not glu else GEGLU(dim, inner_dim)
34
+
35
+ self.net = nn.Sequential(
36
+ project_in,
37
+ nn.Dropout(dropout),
38
+ nn.Linear(inner_dim, dim_out)
39
+ )
40
+
41
+ def forward(self, x):
42
+ return self.net(x)
43
+
44
+
45
+ # ---------------------------------------------------------------------------------------------------
46
+ class RelativePosition(nn.Module):
47
+ """ https://github.com/evelinehong/Transformer_Relative_Position_PyTorch/blob/master/relative_position.py """
48
+
49
+ def __init__(self, num_units, max_relative_position):
50
+ super().__init__()
51
+ self.num_units = num_units
52
+ self.max_relative_position = max_relative_position
53
+ self.embeddings_table = nn.Parameter(th.Tensor(max_relative_position * 2 + 1, num_units))
54
+ nn.init.xavier_uniform_(self.embeddings_table)
55
+
56
+ def forward(self, length_q, length_k):
57
+ device = self.embeddings_table.device
58
+ range_vec_q = th.arange(length_q, device=device)
59
+ range_vec_k = th.arange(length_k, device=device)
60
+ distance_mat = range_vec_k[None, :] - range_vec_q[:, None]
61
+ distance_mat_clipped = th.clamp(distance_mat, -self.max_relative_position, self.max_relative_position)
62
+ final_mat = distance_mat_clipped + self.max_relative_position
63
+ final_mat = final_mat.long()
64
+ embeddings = self.embeddings_table[final_mat]
65
+ return embeddings
66
+
67
+
68
+ # ---------------------------------------------------------------------------------------------------
69
+ class TemporalCrossAttention(nn.Module):
70
+ def __init__(self,
71
+ query_dim,
72
+ context_dim=None,
73
+ heads=8,
74
+ dim_head=64,
75
+ dropout=0.,
76
+ use_relative_position=False, # whether use relative positional representation in temporal attention.
77
+ temporal_length=None, # relative positional representation
78
+ **kwargs,
79
+ ):
80
+ super().__init__()
81
+ inner_dim = dim_head * heads
82
+ context_dim = default(context_dim, query_dim)
83
+ self.context_dim = context_dim
84
+ self.scale = dim_head ** -0.5
85
+ self.heads = heads
86
+ self.temporal_length = temporal_length
87
+ self.use_relative_position = use_relative_position
88
+ self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
89
+ self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
90
+ self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
91
+ self.to_out = nn.Sequential(
92
+ nn.Linear(inner_dim, query_dim),
93
+ nn.Dropout(dropout)
94
+ )
95
+
96
+ if use_relative_position:
97
+ assert(temporal_length is not None)
98
+ self.relative_position_k = RelativePosition(num_units=dim_head, max_relative_position=temporal_length)
99
+ self.relative_position_v = RelativePosition(num_units=dim_head, max_relative_position=temporal_length)
100
+
101
+ nn.init.constant_(self.to_q.weight, 0)
102
+ nn.init.constant_(self.to_k.weight, 0)
103
+ nn.init.constant_(self.to_v.weight, 0)
104
+ nn.init.constant_(self.to_out[0].weight, 0)
105
+ nn.init.constant_(self.to_out[0].bias, 0)
106
+
107
+ def forward(self, x, context=None, mask=None):
108
+ nh = self.heads
109
+ out = x
110
+
111
+ # cal qkv
112
+ q = self.to_q(out)
113
+ context = default(context, x)
114
+ k = self.to_k(context)
115
+ v = self.to_v(context)
116
+
117
+ q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=nh), (q, k, v))
118
+ sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
119
+
120
+ # relative positional embedding
121
+ if self.use_relative_position:
122
+ len_q, len_k, len_v = q.shape[1], k.shape[1], v.shape[1]
123
+ k2 = self.relative_position_k(len_q, len_k)
124
+ sim2 = einsum('b t d, t s d -> b t s', q, k2) * self.scale
125
+ sim += sim2
126
+
127
+ # mask attention
128
+ if mask is not None:
129
+ max_neg_value = -1e9
130
+ sim = sim + (1-mask.float()) * max_neg_value # 1=masking,0=no masking
131
+
132
+ # attend to values
133
+ attn = sim.softmax(dim=-1)
134
+ out = einsum('b i j, b j d -> b i d', attn, v)
135
+
136
+ # relative positional embedding
137
+ if self.use_relative_position:
138
+ v2 = self.relative_position_v(len_q, len_v)
139
+ out2 = einsum('b t s, t s d -> b t d', attn, v2)
140
+ out += out2
141
+
142
+ # merge head
143
+ out = rearrange(out, '(b h) n d -> b n (h d)', h=nh)
144
+ return self.to_out(out)
145
+
146
+
147
+ # ---------------------------------------------------------------------------------------------------
148
+ class CrossAttention(nn.Module):
149
+ def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.,
150
+ **kwargs,):
151
+ super().__init__()
152
+ inner_dim = dim_head * heads
153
+ context_dim = default(context_dim, query_dim)
154
+
155
+ self.scale = dim_head ** -0.5
156
+ self.heads = heads
157
+
158
+ self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
159
+ self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
160
+ self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
161
+
162
+ self.to_out = nn.Sequential(
163
+ nn.Linear(inner_dim, query_dim),
164
+ nn.Dropout(dropout)
165
+ )
166
+
167
+ def forward(self, x, context=None, mask=None):
168
+ h = self.heads
169
+ b = x.shape[0]
170
+
171
+ q = self.to_q(x)
172
+ context = default(context, x)
173
+ k = self.to_k(context)
174
+ v = self.to_v(context)
175
+
176
+ q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
177
+
178
+ sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
179
+
180
+ if exists(mask):
181
+ mask = rearrange(mask, 'b ... -> b (...)')
182
+ max_neg_value = -torch.finfo(sim.dtype).max
183
+ mask = repeat(mask, 'b j -> (b h) () j', h=h)
184
+ sim.masked_fill_(~mask, max_neg_value)
185
+
186
+ attn = sim.softmax(dim=-1)
187
+
188
+ out = einsum('b i j, b j d -> b i d', attn, v)
189
+ out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
190
+ return self.to_out(out)
191
+
192
+
193
+ # ---------------------------------------------------------------------------------------------------
194
+ class MemoryEfficientCrossAttention(nn.Module):
195
+ """https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
196
+ """
197
+ def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0,
198
+ **kwargs,):
199
+ super().__init__()
200
+ print(f"Setting up {self.__class__.__name__}. Query dim is {query_dim}, context_dim is {context_dim} and using "
201
+ f"{heads} heads."
202
+ )
203
+ inner_dim = dim_head * heads
204
+ context_dim = default(context_dim, query_dim)
205
+
206
+ self.heads = heads
207
+ self.dim_head = dim_head
208
+
209
+ self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
210
+ self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
211
+ self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
212
+
213
+ self.to_out = nn.Sequential(nn.Linear(inner_dim, query_dim), nn.Dropout(dropout))
214
+ self.attention_op: Optional[Any] = None
215
+
216
+ def forward(self, x, context=None, mask=None):
217
+ q = self.to_q(x)
218
+ context = default(context, x)
219
+ k = self.to_k(context)
220
+ v = self.to_v(context)
221
+
222
+ b, _, _ = q.shape
223
+ q, k, v = map(
224
+ lambda t: t.unsqueeze(3)
225
+ .reshape(b, t.shape[1], self.heads, self.dim_head)
226
+ .permute(0, 2, 1, 3)
227
+ .reshape(b * self.heads, t.shape[1], self.dim_head)
228
+ .contiguous(),
229
+ (q, k, v),
230
+ )
231
+ out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=self.attention_op)
232
+
233
+ if exists(mask):
234
+ raise NotImplementedError
235
+ out = (
236
+ out.unsqueeze(0)
237
+ .reshape(b, self.heads, out.shape[1], self.dim_head)
238
+ .permute(0, 2, 1, 3)
239
+ .reshape(b, out.shape[1], self.heads * self.dim_head)
240
+ )
241
+ return self.to_out(out)
242
+
243
+
244
+ # ---------------------------------------------------------------------------------------------------
245
+ class BasicTransformerBlockST(nn.Module):
246
+ """
247
+ if no context is given to forward function, cross-attention defaults to self-attention
248
+ """
249
+ def __init__(self,
250
+ # Spatial
251
+ dim,
252
+ n_heads,
253
+ d_head,
254
+ dropout=0.,
255
+ context_dim=None,
256
+ gated_ff=True,
257
+ checkpoint=True,
258
+ # Temporal
259
+ temporal_length=None,
260
+ use_relative_position=True,
261
+ **kwargs,
262
+ ):
263
+ super().__init__()
264
+
265
+ # spatial self attention (if context_dim is None) and spatial cross attention
266
+ if XFORMERS_IS_AVAILBLE:
267
+ self.attn1 = MemoryEfficientCrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout, **kwargs,)
268
+ self.attn2 = MemoryEfficientCrossAttention(query_dim=dim, context_dim=context_dim,
269
+ heads=n_heads, dim_head=d_head, dropout=dropout, **kwargs,)
270
+ else:
271
+ self.attn1 = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout, **kwargs,)
272
+ self.attn2 = CrossAttention(query_dim=dim, context_dim=context_dim,
273
+ heads=n_heads, dim_head=d_head, dropout=dropout, **kwargs,)
274
+ self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
275
+
276
+ self.norm1 = nn.LayerNorm(dim)
277
+ self.norm2 = nn.LayerNorm(dim)
278
+ self.norm3 = nn.LayerNorm(dim)
279
+ self.checkpoint = checkpoint
280
+
281
+ # Temporal attention
282
+ self.attn1_tmp = TemporalCrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout,
283
+ temporal_length=temporal_length,
284
+ use_relative_position=use_relative_position,
285
+ **kwargs,
286
+ )
287
+ self.attn2_tmp = TemporalCrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout,
288
+ # cross attn
289
+ context_dim=None,
290
+ # temporal attn
291
+ temporal_length=temporal_length,
292
+ use_relative_position=use_relative_position,
293
+ **kwargs,
294
+ )
295
+ self.norm4 = nn.LayerNorm(dim)
296
+ self.norm5 = nn.LayerNorm(dim)
297
+
298
+ def forward(self, x, context=None, **kwargs):
299
+ return checkpoint(self._forward, (x, context), self.parameters(), self.checkpoint)
300
+
301
+ def _forward(self, x, context=None, mask=None,):
302
+ assert(x.dim() == 5), f"x shape = {x.shape}"
303
+ b, c, t, h, w = x.shape
304
+
305
+ # spatial self attention
306
+ x = rearrange(x, 'b c t h w -> (b t) (h w) c')
307
+ x = self.attn1(self.norm1(x)) + x
308
+ x = rearrange(x, '(b t) (h w) c -> b c t h w', b=b,h=h)
309
+
310
+ # temporal self attention
311
+ x = rearrange(x, 'b c t h w -> (b h w) t c')
312
+ x = self.attn1_tmp(self.norm4(x), mask=mask) + x
313
+ x = rearrange(x, '(b h w) t c -> b c t h w', b=b,h=h,w=w) # 3d -> 5d
314
+
315
+ # spatial cross attention
316
+ x = rearrange(x, 'b c t h w -> (b t) (h w) c')
317
+ if context is not None:
318
+ context_ = []
319
+ for i in range(context.shape[0]):
320
+ context_.append(context[i].unsqueeze(0).repeat(t, 1, 1))
321
+ context_ = torch.cat(context_,dim=0)
322
+ else:
323
+ context_ = None
324
+ x = self.attn2(self.norm2(x), context=context_) + x
325
+ x = rearrange(x, '(b t) (h w) c -> b c t h w', b=b,h=h)
326
+
327
+ # temporal cross attention
328
+ x = rearrange(x, 'b c t h w -> (b h w) t c')
329
+ x = self.attn2_tmp(self.norm5(x), context=None, mask=mask) + x
330
+
331
+ # feedforward
332
+ x = self.ff(self.norm3(x)) + x
333
+ x = rearrange(x, '(b h w) t c -> b c t h w', b=b,h=h,w=w) # 3d -> 5d
334
+
335
+ return x
336
+
337
+
338
+ # ---------------------------------------------------------------------------------------------------
339
+ class SpatialTemporalTransformer(nn.Module):
340
+ """
341
+ Transformer block for video-like data (5D tensor).
342
+ First, project the input (aka embedding) with NO reshape.
343
+ Then apply standard transformer action.
344
+ The 5D -> 3D reshape operation will be done in the specific attention module.
345
+ """
346
+ def __init__(
347
+ self,
348
+ in_channels, n_heads, d_head,
349
+ depth=1, dropout=0.,
350
+ context_dim=None,
351
+ # Temporal
352
+ temporal_length=None,
353
+ use_relative_position=True,
354
+ **kwargs,
355
+ ):
356
+ super().__init__()
357
+
358
+ self.in_channels = in_channels
359
+ inner_dim = n_heads * d_head
360
+
361
+ self.norm = Normalize(in_channels)
362
+ self.proj_in = nn.Conv3d(in_channels,
363
+ inner_dim,
364
+ kernel_size=1,
365
+ stride=1,
366
+ padding=0)
367
+
368
+ self.transformer_blocks = nn.ModuleList(
369
+ [BasicTransformerBlockST(
370
+ inner_dim, n_heads, d_head, dropout=dropout,
371
+ # cross attn
372
+ context_dim=context_dim,
373
+ # temporal attn
374
+ temporal_length=temporal_length,
375
+ use_relative_position=use_relative_position,
376
+ **kwargs
377
+ ) for d in range(depth)]
378
+ )
379
+
380
+ self.proj_out = zero_module(nn.Conv3d(inner_dim,
381
+ in_channels,
382
+ kernel_size=1,
383
+ stride=1,
384
+ padding=0))
385
+
386
+ def forward(self, x, context=None, **kwargs):
387
+
388
+ assert(x.dim() == 5), f"x shape = {x.shape}"
389
+ x_in = x
390
+
391
+ x = self.norm(x)
392
+ x = self.proj_in(x)
393
+
394
+ for block in self.transformer_blocks:
395
+ x = block(x, context=context, **kwargs)
396
+
397
+ x = self.proj_out(x)
398
+
399
+ return x + x_in
lvdm/models/modules/autoencoder_modules.py ADDED
@@ -0,0 +1,596 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+ import numpy as np
5
+ from torch import nn
6
+ from einops import rearrange
7
+
8
+
9
+ def get_timestep_embedding(timesteps, embedding_dim):
10
+ """
11
+ This matches the implementation in Denoising Diffusion Probabilistic Models:
12
+ From Fairseq.
13
+ Build sinusoidal embeddings.
14
+ This matches the implementation in tensor2tensor, but differs slightly
15
+ from the description in Section 3.5 of "Attention Is All You Need".
16
+ """
17
+ assert len(timesteps.shape) == 1
18
+
19
+ half_dim = embedding_dim // 2
20
+ emb = math.log(10000) / (half_dim - 1)
21
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
22
+ emb = emb.to(device=timesteps.device)
23
+ emb = timesteps.float()[:, None] * emb[None, :]
24
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
25
+ if embedding_dim % 2 == 1: # zero pad
26
+ emb = torch.nn.functional.pad(emb, (0,1,0,0))
27
+ return emb
28
+
29
+ def nonlinearity(x):
30
+ # swish
31
+ return x*torch.sigmoid(x)
32
+
33
+
34
+ def Normalize(in_channels, num_groups=32):
35
+ return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True)
36
+
37
+
38
+
39
+ class LinearAttention(nn.Module):
40
+ def __init__(self, dim, heads=4, dim_head=32):
41
+ super().__init__()
42
+ self.heads = heads
43
+ hidden_dim = dim_head * heads
44
+ self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias = False)
45
+ self.to_out = nn.Conv2d(hidden_dim, dim, 1)
46
+
47
+ def forward(self, x):
48
+ b, c, h, w = x.shape
49
+ qkv = self.to_qkv(x)
50
+ q, k, v = rearrange(qkv, 'b (qkv heads c) h w -> qkv b heads c (h w)', heads = self.heads, qkv=3)
51
+ k = k.softmax(dim=-1)
52
+ context = torch.einsum('bhdn,bhen->bhde', k, v)
53
+ out = torch.einsum('bhde,bhdn->bhen', context, q)
54
+ out = rearrange(out, 'b heads c (h w) -> b (heads c) h w', heads=self.heads, h=h, w=w)
55
+ return self.to_out(out)
56
+
57
+
58
+ class LinAttnBlock(LinearAttention):
59
+ """to match AttnBlock usage"""
60
+ def __init__(self, in_channels):
61
+ super().__init__(dim=in_channels, heads=1, dim_head=in_channels)
62
+
63
+
64
+ class AttnBlock(nn.Module):
65
+ def __init__(self, in_channels):
66
+ super().__init__()
67
+ self.in_channels = in_channels
68
+
69
+ self.norm = Normalize(in_channels)
70
+ self.q = torch.nn.Conv2d(in_channels,
71
+ in_channels,
72
+ kernel_size=1,
73
+ stride=1,
74
+ padding=0)
75
+ self.k = torch.nn.Conv2d(in_channels,
76
+ in_channels,
77
+ kernel_size=1,
78
+ stride=1,
79
+ padding=0)
80
+ self.v = torch.nn.Conv2d(in_channels,
81
+ in_channels,
82
+ kernel_size=1,
83
+ stride=1,
84
+ padding=0)
85
+ self.proj_out = torch.nn.Conv2d(in_channels,
86
+ in_channels,
87
+ kernel_size=1,
88
+ stride=1,
89
+ padding=0)
90
+
91
+ def forward(self, x):
92
+ h_ = x
93
+ h_ = self.norm(h_)
94
+ q = self.q(h_)
95
+ k = self.k(h_)
96
+ v = self.v(h_)
97
+
98
+ # compute attention
99
+ b,c,h,w = q.shape
100
+ q = q.reshape(b,c,h*w) # bcl
101
+ q = q.permute(0,2,1) # bcl -> blc l=hw
102
+ k = k.reshape(b,c,h*w) # bcl
103
+
104
+ w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
105
+ w_ = w_ * (int(c)**(-0.5))
106
+ w_ = torch.nn.functional.softmax(w_, dim=2)
107
+
108
+ # attend to values
109
+ v = v.reshape(b,c,h*w)
110
+ w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q)
111
+ h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
112
+ h_ = h_.reshape(b,c,h,w)
113
+
114
+ h_ = self.proj_out(h_)
115
+
116
+ return x+h_
117
+
118
+
119
+ def make_attn(in_channels, attn_type="vanilla"):
120
+ assert attn_type in ["vanilla", "linear", "none"], f'attn_type {attn_type} unknown'
121
+ print(f"making attention of type '{attn_type}' with {in_channels} in_channels")
122
+ if attn_type == "vanilla":
123
+ return AttnBlock(in_channels)
124
+ elif attn_type == "none":
125
+ return nn.Identity(in_channels)
126
+ else:
127
+ return LinAttnBlock(in_channels)
128
+
129
+ class Downsample(nn.Module):
130
+ def __init__(self, in_channels, with_conv):
131
+ super().__init__()
132
+ self.with_conv = with_conv
133
+ self.in_channels = in_channels
134
+ if self.with_conv:
135
+ # no asymmetric padding in torch conv, must do it ourselves
136
+ self.conv = torch.nn.Conv2d(in_channels,
137
+ in_channels,
138
+ kernel_size=3,
139
+ stride=2,
140
+ padding=0)
141
+ def forward(self, x):
142
+ if self.with_conv:
143
+ pad = (0,1,0,1)
144
+ x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
145
+ x = self.conv(x)
146
+ else:
147
+ x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
148
+ return x
149
+
150
+ class Upsample(nn.Module):
151
+ def __init__(self, in_channels, with_conv):
152
+ super().__init__()
153
+ self.with_conv = with_conv
154
+ self.in_channels = in_channels
155
+ if self.with_conv:
156
+ self.conv = torch.nn.Conv2d(in_channels,
157
+ in_channels,
158
+ kernel_size=3,
159
+ stride=1,
160
+ padding=1)
161
+
162
+ def forward(self, x):
163
+ x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
164
+ if self.with_conv:
165
+ x = self.conv(x)
166
+ return x
167
+
168
+
169
+ class ResnetBlock(nn.Module):
170
+ def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
171
+ dropout, temb_channels=512):
172
+ super().__init__()
173
+ self.in_channels = in_channels
174
+ out_channels = in_channels if out_channels is None else out_channels
175
+ self.out_channels = out_channels
176
+ self.use_conv_shortcut = conv_shortcut
177
+
178
+ self.norm1 = Normalize(in_channels)
179
+ self.conv1 = torch.nn.Conv2d(in_channels,
180
+ out_channels,
181
+ kernel_size=3,
182
+ stride=1,
183
+ padding=1)
184
+ if temb_channels > 0:
185
+ self.temb_proj = torch.nn.Linear(temb_channels,
186
+ out_channels)
187
+ self.norm2 = Normalize(out_channels)
188
+ self.dropout = torch.nn.Dropout(dropout)
189
+ self.conv2 = torch.nn.Conv2d(out_channels,
190
+ out_channels,
191
+ kernel_size=3,
192
+ stride=1,
193
+ padding=1)
194
+ if self.in_channels != self.out_channels:
195
+ if self.use_conv_shortcut:
196
+ self.conv_shortcut = torch.nn.Conv2d(in_channels,
197
+ out_channels,
198
+ kernel_size=3,
199
+ stride=1,
200
+ padding=1)
201
+ else:
202
+ self.nin_shortcut = torch.nn.Conv2d(in_channels,
203
+ out_channels,
204
+ kernel_size=1,
205
+ stride=1,
206
+ padding=0)
207
+
208
+ def forward(self, x, temb):
209
+ h = x
210
+ h = self.norm1(h)
211
+ h = nonlinearity(h)
212
+ h = self.conv1(h)
213
+
214
+ if temb is not None:
215
+ h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]
216
+
217
+ h = self.norm2(h)
218
+ h = nonlinearity(h)
219
+ h = self.dropout(h)
220
+ h = self.conv2(h)
221
+
222
+ if self.in_channels != self.out_channels:
223
+ if self.use_conv_shortcut:
224
+ x = self.conv_shortcut(x)
225
+ else:
226
+ x = self.nin_shortcut(x)
227
+
228
+ return x+h
229
+
230
+ class Model(nn.Module):
231
+ def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
232
+ attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
233
+ resolution, use_timestep=True, use_linear_attn=False, attn_type="vanilla"):
234
+ super().__init__()
235
+ if use_linear_attn: attn_type = "linear"
236
+ self.ch = ch
237
+ self.temb_ch = self.ch*4
238
+ self.num_resolutions = len(ch_mult)
239
+ self.num_res_blocks = num_res_blocks
240
+ self.resolution = resolution
241
+ self.in_channels = in_channels
242
+
243
+ self.use_timestep = use_timestep
244
+ if self.use_timestep:
245
+ # timestep embedding
246
+ self.temb = nn.Module()
247
+ self.temb.dense = nn.ModuleList([
248
+ torch.nn.Linear(self.ch,
249
+ self.temb_ch),
250
+ torch.nn.Linear(self.temb_ch,
251
+ self.temb_ch),
252
+ ])
253
+
254
+ # downsampling
255
+ self.conv_in = torch.nn.Conv2d(in_channels,
256
+ self.ch,
257
+ kernel_size=3,
258
+ stride=1,
259
+ padding=1)
260
+
261
+ curr_res = resolution
262
+ in_ch_mult = (1,)+tuple(ch_mult)
263
+ self.down = nn.ModuleList()
264
+ for i_level in range(self.num_resolutions):
265
+ block = nn.ModuleList()
266
+ attn = nn.ModuleList()
267
+ block_in = ch*in_ch_mult[i_level]
268
+ block_out = ch*ch_mult[i_level]
269
+ for i_block in range(self.num_res_blocks):
270
+ block.append(ResnetBlock(in_channels=block_in,
271
+ out_channels=block_out,
272
+ temb_channels=self.temb_ch,
273
+ dropout=dropout))
274
+ block_in = block_out
275
+ if curr_res in attn_resolutions:
276
+ attn.append(make_attn(block_in, attn_type=attn_type))
277
+ down = nn.Module()
278
+ down.block = block
279
+ down.attn = attn
280
+ if i_level != self.num_resolutions-1:
281
+ down.downsample = Downsample(block_in, resamp_with_conv)
282
+ curr_res = curr_res // 2
283
+ self.down.append(down)
284
+
285
+ # middle
286
+ self.mid = nn.Module()
287
+ self.mid.block_1 = ResnetBlock(in_channels=block_in,
288
+ out_channels=block_in,
289
+ temb_channels=self.temb_ch,
290
+ dropout=dropout)
291
+ self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
292
+ self.mid.block_2 = ResnetBlock(in_channels=block_in,
293
+ out_channels=block_in,
294
+ temb_channels=self.temb_ch,
295
+ dropout=dropout)
296
+
297
+ # upsampling
298
+ self.up = nn.ModuleList()
299
+ for i_level in reversed(range(self.num_resolutions)):
300
+ block = nn.ModuleList()
301
+ attn = nn.ModuleList()
302
+ block_out = ch*ch_mult[i_level]
303
+ skip_in = ch*ch_mult[i_level]
304
+ for i_block in range(self.num_res_blocks+1):
305
+ if i_block == self.num_res_blocks:
306
+ skip_in = ch*in_ch_mult[i_level]
307
+ block.append(ResnetBlock(in_channels=block_in+skip_in,
308
+ out_channels=block_out,
309
+ temb_channels=self.temb_ch,
310
+ dropout=dropout))
311
+ block_in = block_out
312
+ if curr_res in attn_resolutions:
313
+ attn.append(make_attn(block_in, attn_type=attn_type))
314
+ up = nn.Module()
315
+ up.block = block
316
+ up.attn = attn
317
+ if i_level != 0:
318
+ up.upsample = Upsample(block_in, resamp_with_conv)
319
+ curr_res = curr_res * 2
320
+ self.up.insert(0, up) # prepend to get consistent order
321
+
322
+ # end
323
+ self.norm_out = Normalize(block_in)
324
+ self.conv_out = torch.nn.Conv2d(block_in,
325
+ out_ch,
326
+ kernel_size=3,
327
+ stride=1,
328
+ padding=1)
329
+
330
+ def forward(self, x, t=None, context=None):
331
+ #assert x.shape[2] == x.shape[3] == self.resolution
332
+ if context is not None:
333
+ # assume aligned context, cat along channel axis
334
+ x = torch.cat((x, context), dim=1)
335
+ if self.use_timestep:
336
+ # timestep embedding
337
+ assert t is not None
338
+ temb = get_timestep_embedding(t, self.ch)
339
+ temb = self.temb.dense[0](temb)
340
+ temb = nonlinearity(temb)
341
+ temb = self.temb.dense[1](temb)
342
+ else:
343
+ temb = None
344
+
345
+ # downsampling
346
+ hs = [self.conv_in(x)]
347
+ for i_level in range(self.num_resolutions):
348
+ for i_block in range(self.num_res_blocks):
349
+ h = self.down[i_level].block[i_block](hs[-1], temb)
350
+ if len(self.down[i_level].attn) > 0:
351
+ h = self.down[i_level].attn[i_block](h)
352
+ hs.append(h)
353
+ if i_level != self.num_resolutions-1:
354
+ hs.append(self.down[i_level].downsample(hs[-1]))
355
+
356
+ # middle
357
+ h = hs[-1]
358
+ h = self.mid.block_1(h, temb)
359
+ h = self.mid.attn_1(h)
360
+ h = self.mid.block_2(h, temb)
361
+
362
+ # upsampling
363
+ for i_level in reversed(range(self.num_resolutions)):
364
+ for i_block in range(self.num_res_blocks+1):
365
+ h = self.up[i_level].block[i_block](
366
+ torch.cat([h, hs.pop()], dim=1), temb)
367
+ if len(self.up[i_level].attn) > 0:
368
+ h = self.up[i_level].attn[i_block](h)
369
+ if i_level != 0:
370
+ h = self.up[i_level].upsample(h)
371
+
372
+ # end
373
+ h = self.norm_out(h)
374
+ h = nonlinearity(h)
375
+ h = self.conv_out(h)
376
+ return h
377
+
378
+ def get_last_layer(self):
379
+ return self.conv_out.weight
380
+
381
+
382
+ class Encoder(nn.Module):
383
+ def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
384
+ attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
385
+ resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla",
386
+ **ignore_kwargs):
387
+ super().__init__()
388
+ if use_linear_attn: attn_type = "linear"
389
+ self.ch = ch
390
+ self.temb_ch = 0
391
+ self.num_resolutions = len(ch_mult)
392
+ self.num_res_blocks = num_res_blocks
393
+ self.resolution = resolution
394
+ self.in_channels = in_channels
395
+
396
+ # downsampling
397
+ self.conv_in = torch.nn.Conv2d(in_channels,
398
+ self.ch,
399
+ kernel_size=3,
400
+ stride=1,
401
+ padding=1)
402
+
403
+ curr_res = resolution
404
+ in_ch_mult = (1,)+tuple(ch_mult)
405
+ self.in_ch_mult = in_ch_mult
406
+ self.down = nn.ModuleList()
407
+ for i_level in range(self.num_resolutions):
408
+ block = nn.ModuleList()
409
+ attn = nn.ModuleList()
410
+ block_in = ch*in_ch_mult[i_level]
411
+ block_out = ch*ch_mult[i_level]
412
+ for i_block in range(self.num_res_blocks):
413
+ block.append(ResnetBlock(in_channels=block_in,
414
+ out_channels=block_out,
415
+ temb_channels=self.temb_ch,
416
+ dropout=dropout))
417
+ block_in = block_out
418
+ if curr_res in attn_resolutions:
419
+ attn.append(make_attn(block_in, attn_type=attn_type))
420
+ down = nn.Module()
421
+ down.block = block
422
+ down.attn = attn
423
+ if i_level != self.num_resolutions-1:
424
+ down.downsample = Downsample(block_in, resamp_with_conv)
425
+ curr_res = curr_res // 2
426
+ self.down.append(down)
427
+
428
+ # middle
429
+ self.mid = nn.Module()
430
+ self.mid.block_1 = ResnetBlock(in_channels=block_in,
431
+ out_channels=block_in,
432
+ temb_channels=self.temb_ch,
433
+ dropout=dropout)
434
+ self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
435
+ self.mid.block_2 = ResnetBlock(in_channels=block_in,
436
+ out_channels=block_in,
437
+ temb_channels=self.temb_ch,
438
+ dropout=dropout)
439
+
440
+ # end
441
+ self.norm_out = Normalize(block_in)
442
+ self.conv_out = torch.nn.Conv2d(block_in,
443
+ 2*z_channels if double_z else z_channels,
444
+ kernel_size=3,
445
+ stride=1,
446
+ padding=1)
447
+
448
+ def forward(self, x):
449
+ # timestep embedding
450
+ temb = None
451
+
452
+ # print(f'encoder-input={x.shape}')
453
+ # downsampling
454
+ hs = [self.conv_in(x)]
455
+ # print(f'encoder-conv in feat={hs[0].shape}')
456
+ for i_level in range(self.num_resolutions):
457
+ for i_block in range(self.num_res_blocks):
458
+ h = self.down[i_level].block[i_block](hs[-1], temb)
459
+ # print(f'encoder-down feat={h.shape}')
460
+ if len(self.down[i_level].attn) > 0:
461
+ h = self.down[i_level].attn[i_block](h)
462
+ hs.append(h)
463
+ if i_level != self.num_resolutions-1:
464
+ # print(f'encoder-downsample (input)={hs[-1].shape}')
465
+ hs.append(self.down[i_level].downsample(hs[-1]))
466
+ # print(f'encoder-downsample (output)={hs[-1].shape}')
467
+
468
+ # middle
469
+ h = hs[-1]
470
+ h = self.mid.block_1(h, temb)
471
+ # print(f'encoder-mid1 feat={h.shape}')
472
+ h = self.mid.attn_1(h)
473
+ h = self.mid.block_2(h, temb)
474
+ # print(f'encoder-mid2 feat={h.shape}')
475
+
476
+ # end
477
+ h = self.norm_out(h)
478
+ h = nonlinearity(h)
479
+ h = self.conv_out(h)
480
+ # print(f'end feat={h.shape}')
481
+ return h
482
+
483
+
484
+ class Decoder(nn.Module):
485
+ def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
486
+ attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
487
+ resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
488
+ attn_type="vanilla", **ignorekwargs):
489
+ super().__init__()
490
+ if use_linear_attn: attn_type = "linear"
491
+ self.ch = ch
492
+ self.temb_ch = 0
493
+ self.num_resolutions = len(ch_mult)
494
+ self.num_res_blocks = num_res_blocks
495
+ self.resolution = resolution
496
+ self.in_channels = in_channels
497
+ self.give_pre_end = give_pre_end
498
+ self.tanh_out = tanh_out
499
+
500
+ # compute in_ch_mult, block_in and curr_res at lowest res
501
+ in_ch_mult = (1,)+tuple(ch_mult)
502
+ block_in = ch*ch_mult[self.num_resolutions-1]
503
+ curr_res = resolution // 2**(self.num_resolutions-1)
504
+ self.z_shape = (1,z_channels,curr_res,curr_res)
505
+ print("Working with z of shape {} = {} dimensions.".format(
506
+ self.z_shape, np.prod(self.z_shape)))
507
+
508
+ # z to block_in
509
+ self.conv_in = torch.nn.Conv2d(z_channels,
510
+ block_in,
511
+ kernel_size=3,
512
+ stride=1,
513
+ padding=1)
514
+
515
+ # middle
516
+ self.mid = nn.Module()
517
+ self.mid.block_1 = ResnetBlock(in_channels=block_in,
518
+ out_channels=block_in,
519
+ temb_channels=self.temb_ch,
520
+ dropout=dropout)
521
+ self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
522
+ self.mid.block_2 = ResnetBlock(in_channels=block_in,
523
+ out_channels=block_in,
524
+ temb_channels=self.temb_ch,
525
+ dropout=dropout)
526
+
527
+ # upsampling
528
+ self.up = nn.ModuleList()
529
+ for i_level in reversed(range(self.num_resolutions)):
530
+ block = nn.ModuleList()
531
+ attn = nn.ModuleList()
532
+ block_out = ch*ch_mult[i_level]
533
+ for i_block in range(self.num_res_blocks+1):
534
+ block.append(ResnetBlock(in_channels=block_in,
535
+ out_channels=block_out,
536
+ temb_channels=self.temb_ch,
537
+ dropout=dropout))
538
+ block_in = block_out
539
+ if curr_res in attn_resolutions:
540
+ attn.append(make_attn(block_in, attn_type=attn_type))
541
+ up = nn.Module()
542
+ up.block = block
543
+ up.attn = attn
544
+ if i_level != 0:
545
+ up.upsample = Upsample(block_in, resamp_with_conv)
546
+ curr_res = curr_res * 2
547
+ self.up.insert(0, up) # prepend to get consistent order
548
+
549
+ # end
550
+ self.norm_out = Normalize(block_in)
551
+ self.conv_out = torch.nn.Conv2d(block_in,
552
+ out_ch,
553
+ kernel_size=3,
554
+ stride=1,
555
+ padding=1)
556
+
557
+ def forward(self, z):
558
+ #assert z.shape[1:] == self.z_shape[1:]
559
+ self.last_z_shape = z.shape
560
+
561
+ # print(f'decoder-input={z.shape}')
562
+ # timestep embedding
563
+ temb = None
564
+
565
+ # z to block_in
566
+ h = self.conv_in(z)
567
+ # print(f'decoder-conv in feat={h.shape}')
568
+
569
+ # middle
570
+ h = self.mid.block_1(h, temb)
571
+ h = self.mid.attn_1(h)
572
+ h = self.mid.block_2(h, temb)
573
+ # print(f'decoder-mid feat={h.shape}')
574
+
575
+ # upsampling
576
+ for i_level in reversed(range(self.num_resolutions)):
577
+ for i_block in range(self.num_res_blocks+1):
578
+ h = self.up[i_level].block[i_block](h, temb)
579
+ if len(self.up[i_level].attn) > 0:
580
+ h = self.up[i_level].attn[i_block](h)
581
+ # print(f'decoder-up feat={h.shape}')
582
+ if i_level != 0:
583
+ h = self.up[i_level].upsample(h)
584
+ # print(f'decoder-upsample feat={h.shape}')
585
+
586
+ # end
587
+ if self.give_pre_end:
588
+ return h
589
+
590
+ h = self.norm_out(h)
591
+ h = nonlinearity(h)
592
+ h = self.conv_out(h)
593
+ # print(f'decoder-conv_out feat={h.shape}')
594
+ if self.tanh_out:
595
+ h = torch.tanh(h)
596
+ return h
lvdm/models/modules/condition_modules.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ from transformers import logging
3
+ from transformers import CLIPTokenizer, CLIPTextModel
4
+ logging.set_verbosity_error()
5
+
6
+
7
+ class AbstractEncoder(nn.Module):
8
+ def __init__(self):
9
+ super().__init__()
10
+
11
+ def encode(self, *args, **kwargs):
12
+ raise NotImplementedError
13
+
14
+
15
+ class FrozenCLIPEmbedder(AbstractEncoder):
16
+ """Uses the CLIP transformer encoder for text (from huggingface)"""
17
+ def __init__(self, version="openai/clip-vit-large-patch14", device="cuda", max_length=77):
18
+ super().__init__()
19
+ self.tokenizer = CLIPTokenizer.from_pretrained(version)
20
+ self.transformer = CLIPTextModel.from_pretrained(version)
21
+ self.device = device
22
+ self.max_length = max_length
23
+ self.freeze()
24
+
25
+ def freeze(self):
26
+ self.transformer = self.transformer.eval()
27
+ for param in self.parameters():
28
+ param.requires_grad = False
29
+
30
+ def forward(self, text):
31
+ batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
32
+ return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
33
+ tokens = batch_encoding["input_ids"].to(self.device)
34
+ outputs = self.transformer(input_ids=tokens)
35
+
36
+ z = outputs.last_hidden_state
37
+ return z
38
+
39
+ def encode(self, text):
40
+ return self(text)
lvdm/models/modules/distributions.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+
5
+ class DiagonalGaussianDistribution(object):
6
+ def __init__(self, parameters, deterministic=False):
7
+ self.parameters = parameters
8
+ self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
9
+ self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
10
+ self.deterministic = deterministic
11
+ self.std = torch.exp(0.5 * self.logvar)
12
+ self.var = torch.exp(self.logvar)
13
+ if self.deterministic:
14
+ self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device)
15
+
16
+ def sample(self, noise=None):
17
+ if noise is None:
18
+ noise = torch.randn(self.mean.shape)
19
+
20
+ x = self.mean + self.std * noise.to(device=self.parameters.device)
21
+ return x
22
+
23
+ def kl(self, other=None):
24
+ if self.deterministic:
25
+ return torch.Tensor([0.])
26
+ else:
27
+ if other is None:
28
+ return 0.5 * torch.sum(torch.pow(self.mean, 2)
29
+ + self.var - 1.0 - self.logvar,
30
+ dim=[1, 2, 3])
31
+ else:
32
+ return 0.5 * torch.sum(
33
+ torch.pow(self.mean - other.mean, 2) / other.var
34
+ + self.var / other.var - 1.0 - self.logvar + other.logvar,
35
+ dim=[1, 2, 3])
36
+
37
+ def nll(self, sample, dims=[1,2,3]):
38
+ if self.deterministic:
39
+ return torch.Tensor([0.])
40
+ logtwopi = np.log(2.0 * np.pi)
41
+ return 0.5 * torch.sum(
42
+ logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
43
+ dim=dims)
44
+
45
+ def mode(self):
46
+ return self.mean
47
+
48
+
49
+ def normal_kl(mean1, logvar1, mean2, logvar2):
50
+ """
51
+ source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12
52
+ Compute the KL divergence between two gaussians.
53
+ Shapes are automatically broadcasted, so batches can be compared to
54
+ scalars, among other use cases.
55
+ """
56
+ tensor = None
57
+ for obj in (mean1, logvar1, mean2, logvar2):
58
+ if isinstance(obj, torch.Tensor):
59
+ tensor = obj
60
+ break
61
+ assert tensor is not None, "at least one argument must be a Tensor"
62
+
63
+ # Force variances to be Tensors. Broadcasting helps convert scalars to
64
+ # Tensors, but it does not work for torch.exp().
65
+ logvar1, logvar2 = [
66
+ x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor)
67
+ for x in (logvar1, logvar2)
68
+ ]
69
+
70
+ return 0.5 * (
71
+ -1.0
72
+ + logvar2
73
+ - logvar1
74
+ + torch.exp(logvar1 - logvar2)
75
+ + ((mean1 - mean2) ** 2) * torch.exp(-logvar2)
76
+ )
lvdm/models/modules/lora.py ADDED
@@ -0,0 +1,1174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from itertools import groupby
3
+ from typing import Dict, List, Optional, Set, Tuple, Type, Union
4
+
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+
10
+ # try:
11
+ # from safetensors.torch import safe_open
12
+ # from safetensors.torch import save_file as safe_save
13
+
14
+ # safetensors_available = True
15
+ # except ImportError:
16
+ # from .safe_open import safe_open
17
+
18
+ # def safe_save(
19
+ # tensors: Dict[str, torch.Tensor],
20
+ # filename: str,
21
+ # metadata: Optional[Dict[str, str]] = None,
22
+ # ) -> None:
23
+ # raise EnvironmentError(
24
+ # "Saving safetensors requires the safetensors library. Please install with pip or similar."
25
+ # )
26
+
27
+ # safetensors_available = False
28
+
29
+
30
+ class LoraInjectedLinear(nn.Module):
31
+ def __init__(
32
+ self, in_features, out_features, bias=False, r=4, dropout_p=0.1, scale=1.0
33
+ ):
34
+ super().__init__()
35
+
36
+ if r > min(in_features, out_features):
37
+ raise ValueError(
38
+ f"LoRA rank {r} must be less or equal than {min(in_features, out_features)}"
39
+ )
40
+ self.r = r
41
+ self.linear = nn.Linear(in_features, out_features, bias)
42
+ self.lora_down = nn.Linear(in_features, r, bias=False)
43
+ self.dropout = nn.Dropout(dropout_p)
44
+ self.lora_up = nn.Linear(r, out_features, bias=False)
45
+ self.scale = scale
46
+ self.selector = nn.Identity()
47
+
48
+ nn.init.normal_(self.lora_down.weight, std=1 / r)
49
+ nn.init.zeros_(self.lora_up.weight)
50
+
51
+ def forward(self, input):
52
+ return (
53
+ self.linear(input)
54
+ + self.dropout(self.lora_up(self.selector(self.lora_down(input))))
55
+ * self.scale
56
+ )
57
+
58
+ def realize_as_lora(self):
59
+ return self.lora_up.weight.data * self.scale, self.lora_down.weight.data
60
+
61
+ def set_selector_from_diag(self, diag: torch.Tensor):
62
+ # diag is a 1D tensor of size (r,)
63
+ assert diag.shape == (self.r,)
64
+ self.selector = nn.Linear(self.r, self.r, bias=False)
65
+ self.selector.weight.data = torch.diag(diag)
66
+ self.selector.weight.data = self.selector.weight.data.to(
67
+ self.lora_up.weight.device
68
+ ).to(self.lora_up.weight.dtype)
69
+
70
+
71
+ class LoraInjectedConv2d(nn.Module):
72
+ def __init__(
73
+ self,
74
+ in_channels: int,
75
+ out_channels: int,
76
+ kernel_size,
77
+ stride=1,
78
+ padding=0,
79
+ dilation=1,
80
+ groups: int = 1,
81
+ bias: bool = True,
82
+ r: int = 4,
83
+ dropout_p: float = 0.1,
84
+ scale: float = 1.0,
85
+ ):
86
+ super().__init__()
87
+ if r > min(in_channels, out_channels):
88
+ raise ValueError(
89
+ f"LoRA rank {r} must be less or equal than {min(in_channels, out_channels)}"
90
+ )
91
+ self.r = r
92
+ self.conv = nn.Conv2d(
93
+ in_channels=in_channels,
94
+ out_channels=out_channels,
95
+ kernel_size=kernel_size,
96
+ stride=stride,
97
+ padding=padding,
98
+ dilation=dilation,
99
+ groups=groups,
100
+ bias=bias,
101
+ )
102
+
103
+ self.lora_down = nn.Conv2d(
104
+ in_channels=in_channels,
105
+ out_channels=r,
106
+ kernel_size=kernel_size,
107
+ stride=stride,
108
+ padding=padding,
109
+ dilation=dilation,
110
+ groups=groups,
111
+ bias=False,
112
+ )
113
+ self.dropout = nn.Dropout(dropout_p)
114
+ self.lora_up = nn.Conv2d(
115
+ in_channels=r,
116
+ out_channels=out_channels,
117
+ kernel_size=1,
118
+ stride=1,
119
+ padding=0,
120
+ bias=False,
121
+ )
122
+ self.selector = nn.Identity()
123
+ self.scale = scale
124
+
125
+ nn.init.normal_(self.lora_down.weight, std=1 / r)
126
+ nn.init.zeros_(self.lora_up.weight)
127
+
128
+ def forward(self, input):
129
+ return (
130
+ self.conv(input)
131
+ + self.dropout(self.lora_up(self.selector(self.lora_down(input))))
132
+ * self.scale
133
+ )
134
+
135
+ def realize_as_lora(self):
136
+ return self.lora_up.weight.data * self.scale, self.lora_down.weight.data
137
+
138
+ def set_selector_from_diag(self, diag: torch.Tensor):
139
+ # diag is a 1D tensor of size (r,)
140
+ assert diag.shape == (self.r,)
141
+ self.selector = nn.Conv2d(
142
+ in_channels=self.r,
143
+ out_channels=self.r,
144
+ kernel_size=1,
145
+ stride=1,
146
+ padding=0,
147
+ bias=False,
148
+ )
149
+ self.selector.weight.data = torch.diag(diag)
150
+
151
+ # same device + dtype as lora_up
152
+ self.selector.weight.data = self.selector.weight.data.to(
153
+ self.lora_up.weight.device
154
+ ).to(self.lora_up.weight.dtype)
155
+
156
+
157
+ UNET_DEFAULT_TARGET_REPLACE = {"MemoryEfficientCrossAttention","CrossAttention", "Attention", "GEGLU"}
158
+
159
+ UNET_EXTENDED_TARGET_REPLACE = {"TimestepEmbedSequential","SpatialTemporalTransformer", "MemoryEfficientCrossAttention","CrossAttention", "Attention", "GEGLU"}
160
+
161
+ TEXT_ENCODER_DEFAULT_TARGET_REPLACE = {"CLIPAttention"}
162
+
163
+ TEXT_ENCODER_EXTENDED_TARGET_REPLACE = {"CLIPMLP","CLIPAttention"}
164
+
165
+ DEFAULT_TARGET_REPLACE = UNET_DEFAULT_TARGET_REPLACE
166
+
167
+ EMBED_FLAG = "<embed>"
168
+
169
+
170
+ def _find_children(
171
+ model,
172
+ search_class: List[Type[nn.Module]] = [nn.Linear],
173
+ ):
174
+ """
175
+ Find all modules of a certain class (or union of classes).
176
+
177
+ Returns all matching modules, along with the parent of those moduless and the
178
+ names they are referenced by.
179
+ """
180
+ # For each target find every linear_class module that isn't a child of a LoraInjectedLinear
181
+ for parent in model.modules():
182
+ for name, module in parent.named_children():
183
+ if any([isinstance(module, _class) for _class in search_class]):
184
+ yield parent, name, module
185
+
186
+
187
+ def _find_modules_v2(
188
+ model,
189
+ ancestor_class: Optional[Set[str]] = None,
190
+ search_class: List[Type[nn.Module]] = [nn.Linear],
191
+ exclude_children_of: Optional[List[Type[nn.Module]]] = [
192
+ LoraInjectedLinear,
193
+ LoraInjectedConv2d,
194
+ ],
195
+ ):
196
+ """
197
+ Find all modules of a certain class (or union of classes) that are direct or
198
+ indirect descendants of other modules of a certain class (or union of classes).
199
+
200
+ Returns all matching modules, along with the parent of those moduless and the
201
+ names they are referenced by.
202
+ """
203
+
204
+ # Get the targets we should replace all linears under
205
+ if type(ancestor_class) is not set:
206
+ ancestor_class = set(ancestor_class)
207
+ print(ancestor_class)
208
+ if ancestor_class is not None:
209
+ ancestors = (
210
+ module
211
+ for module in model.modules()
212
+ if module.__class__.__name__ in ancestor_class
213
+ )
214
+ else:
215
+ # this, incase you want to naively iterate over all modules.
216
+ ancestors = [module for module in model.modules()]
217
+
218
+ # For each target find every linear_class module that isn't a child of a LoraInjectedLinear
219
+ for ancestor in ancestors:
220
+ for fullname, module in ancestor.named_children():
221
+ if any([isinstance(module, _class) for _class in search_class]):
222
+ # Find the direct parent if this is a descendant, not a child, of target
223
+ *path, name = fullname.split(".")
224
+ parent = ancestor
225
+ while path:
226
+ parent = parent.get_submodule(path.pop(0))
227
+ # Skip this linear if it's a child of a LoraInjectedLinear
228
+ if exclude_children_of and any(
229
+ [isinstance(parent, _class) for _class in exclude_children_of]
230
+ ):
231
+ continue
232
+ # Otherwise, yield it
233
+ yield parent, name, module
234
+
235
+
236
+ def _find_modules_old(
237
+ model,
238
+ ancestor_class: Set[str] = DEFAULT_TARGET_REPLACE,
239
+ search_class: List[Type[nn.Module]] = [nn.Linear],
240
+ exclude_children_of: Optional[List[Type[nn.Module]]] = [LoraInjectedLinear],
241
+ ):
242
+ ret = []
243
+ for _module in model.modules():
244
+ if _module.__class__.__name__ in ancestor_class:
245
+
246
+ for name, _child_module in _module.named_children():
247
+ if _child_module.__class__ in search_class:
248
+ ret.append((_module, name, _child_module))
249
+ print(ret)
250
+ return ret
251
+
252
+
253
+ _find_modules = _find_modules_v2
254
+
255
+
256
+ def inject_trainable_lora(
257
+ model: nn.Module,
258
+ target_replace_module: Set[str] = DEFAULT_TARGET_REPLACE,
259
+ r: int = 4,
260
+ loras=None, # path to lora .pt
261
+ verbose: bool = False,
262
+ dropout_p: float = 0.0,
263
+ scale: float = 1.0,
264
+ ):
265
+ """
266
+ inject lora into model, and returns lora parameter groups.
267
+ """
268
+
269
+ require_grad_params = []
270
+ names = []
271
+
272
+ if loras != None:
273
+ loras = torch.load(loras)
274
+
275
+ for _module, name, _child_module in _find_modules(
276
+ model, target_replace_module, search_class=[nn.Linear]
277
+ ):
278
+ weight = _child_module.weight
279
+ bias = _child_module.bias
280
+ if verbose:
281
+ print("LoRA Injection : injecting lora into ", name)
282
+ print("LoRA Injection : weight shape", weight.shape)
283
+ _tmp = LoraInjectedLinear(
284
+ _child_module.in_features,
285
+ _child_module.out_features,
286
+ _child_module.bias is not None,
287
+ r=r,
288
+ dropout_p=dropout_p,
289
+ scale=scale,
290
+ )
291
+ _tmp.linear.weight = weight
292
+ if bias is not None:
293
+ _tmp.linear.bias = bias
294
+
295
+ # switch the module
296
+ _tmp.to(_child_module.weight.device).to(_child_module.weight.dtype)
297
+ _module._modules[name] = _tmp
298
+
299
+ require_grad_params.append(_module._modules[name].lora_up.parameters())
300
+ require_grad_params.append(_module._modules[name].lora_down.parameters())
301
+
302
+ if loras != None:
303
+ _module._modules[name].lora_up.weight = loras.pop(0)
304
+ _module._modules[name].lora_down.weight = loras.pop(0)
305
+
306
+ _module._modules[name].lora_up.weight.requires_grad = True
307
+ _module._modules[name].lora_down.weight.requires_grad = True
308
+ names.append(name)
309
+
310
+ return require_grad_params, names
311
+
312
+
313
+ def inject_trainable_lora_extended(
314
+ model: nn.Module,
315
+ target_replace_module: Set[str] = UNET_EXTENDED_TARGET_REPLACE,
316
+ r: int = 4,
317
+ loras=None, # path to lora .pt
318
+ ):
319
+ """
320
+ inject lora into model, and returns lora parameter groups.
321
+ """
322
+
323
+ require_grad_params = []
324
+ names = []
325
+
326
+ if loras != None:
327
+ loras = torch.load(loras)
328
+
329
+ for _module, name, _child_module in _find_modules(
330
+ model, target_replace_module, search_class=[nn.Linear, nn.Conv2d]
331
+ ):
332
+ if _child_module.__class__ == nn.Linear:
333
+ weight = _child_module.weight
334
+ bias = _child_module.bias
335
+ _tmp = LoraInjectedLinear(
336
+ _child_module.in_features,
337
+ _child_module.out_features,
338
+ _child_module.bias is not None,
339
+ r=r,
340
+ )
341
+ _tmp.linear.weight = weight
342
+ if bias is not None:
343
+ _tmp.linear.bias = bias
344
+ elif _child_module.__class__ == nn.Conv2d:
345
+ weight = _child_module.weight
346
+ bias = _child_module.bias
347
+ _tmp = LoraInjectedConv2d(
348
+ _child_module.in_channels,
349
+ _child_module.out_channels,
350
+ _child_module.kernel_size,
351
+ _child_module.stride,
352
+ _child_module.padding,
353
+ _child_module.dilation,
354
+ _child_module.groups,
355
+ _child_module.bias is not None,
356
+ r=r,
357
+ )
358
+
359
+ _tmp.conv.weight = weight
360
+ if bias is not None:
361
+ _tmp.conv.bias = bias
362
+
363
+ # switch the module
364
+ _tmp.to(_child_module.weight.device).to(_child_module.weight.dtype)
365
+ if bias is not None:
366
+ _tmp.to(_child_module.bias.device).to(_child_module.bias.dtype)
367
+
368
+ _module._modules[name] = _tmp
369
+
370
+ require_grad_params.append(_module._modules[name].lora_up.parameters())
371
+ require_grad_params.append(_module._modules[name].lora_down.parameters())
372
+
373
+ if loras != None:
374
+ _module._modules[name].lora_up.weight = loras.pop(0)
375
+ _module._modules[name].lora_down.weight = loras.pop(0)
376
+
377
+ _module._modules[name].lora_up.weight.requires_grad = True
378
+ _module._modules[name].lora_down.weight.requires_grad = True
379
+ names.append(name)
380
+
381
+ return require_grad_params, names
382
+
383
+
384
+ def extract_lora_ups_down(model, target_replace_module=DEFAULT_TARGET_REPLACE):
385
+
386
+ loras = []
387
+
388
+ for _m, _n, _child_module in _find_modules(
389
+ model,
390
+ target_replace_module,
391
+ search_class=[LoraInjectedLinear, LoraInjectedConv2d],
392
+ ):
393
+ loras.append((_child_module.lora_up, _child_module.lora_down))
394
+
395
+ if len(loras) == 0:
396
+ raise ValueError("No lora injected.")
397
+
398
+ return loras
399
+
400
+
401
+ def extract_lora_as_tensor(
402
+ model, target_replace_module=DEFAULT_TARGET_REPLACE, as_fp16=True
403
+ ):
404
+
405
+ loras = []
406
+
407
+ for _m, _n, _child_module in _find_modules(
408
+ model,
409
+ target_replace_module,
410
+ search_class=[LoraInjectedLinear, LoraInjectedConv2d],
411
+ ):
412
+ up, down = _child_module.realize_as_lora()
413
+ if as_fp16:
414
+ up = up.to(torch.float16)
415
+ down = down.to(torch.float16)
416
+
417
+ loras.append((up, down))
418
+
419
+ if len(loras) == 0:
420
+ raise ValueError("No lora injected.")
421
+
422
+ return loras
423
+
424
+
425
+ def save_lora_weight(
426
+ model,
427
+ path="./lora.pt",
428
+ target_replace_module=DEFAULT_TARGET_REPLACE,
429
+ ):
430
+ weights = []
431
+ for _up, _down in extract_lora_ups_down(
432
+ model, target_replace_module=target_replace_module
433
+ ):
434
+ weights.append(_up.weight.to("cpu").to(torch.float16))
435
+ weights.append(_down.weight.to("cpu").to(torch.float16))
436
+
437
+ torch.save(weights, path)
438
+
439
+
440
+ def save_lora_as_json(model, path="./lora.json"):
441
+ weights = []
442
+ for _up, _down in extract_lora_ups_down(model):
443
+ weights.append(_up.weight.detach().cpu().numpy().tolist())
444
+ weights.append(_down.weight.detach().cpu().numpy().tolist())
445
+
446
+ import json
447
+
448
+ with open(path, "w") as f:
449
+ json.dump(weights, f)
450
+
451
+
452
+ def save_safeloras_with_embeds(
453
+ modelmap: Dict[str, Tuple[nn.Module, Set[str]]] = {},
454
+ embeds: Dict[str, torch.Tensor] = {},
455
+ outpath="./lora.safetensors",
456
+ ):
457
+ """
458
+ Saves the Lora from multiple modules in a single safetensor file.
459
+
460
+ modelmap is a dictionary of {
461
+ "module name": (module, target_replace_module)
462
+ }
463
+ """
464
+ weights = {}
465
+ metadata = {}
466
+
467
+ for name, (model, target_replace_module) in modelmap.items():
468
+ metadata[name] = json.dumps(list(target_replace_module))
469
+
470
+ for i, (_up, _down) in enumerate(
471
+ extract_lora_as_tensor(model, target_replace_module)
472
+ ):
473
+ rank = _down.shape[0]
474
+
475
+ metadata[f"{name}:{i}:rank"] = str(rank)
476
+ weights[f"{name}:{i}:up"] = _up
477
+ weights[f"{name}:{i}:down"] = _down
478
+
479
+ for token, tensor in embeds.items():
480
+ metadata[token] = EMBED_FLAG
481
+ weights[token] = tensor
482
+
483
+ print(f"Saving weights to {outpath}")
484
+ safe_save(weights, outpath, metadata)
485
+
486
+
487
+ def save_safeloras(
488
+ modelmap: Dict[str, Tuple[nn.Module, Set[str]]] = {},
489
+ outpath="./lora.safetensors",
490
+ ):
491
+ return save_safeloras_with_embeds(modelmap=modelmap, outpath=outpath)
492
+
493
+
494
+ def convert_loras_to_safeloras_with_embeds(
495
+ modelmap: Dict[str, Tuple[str, Set[str], int]] = {},
496
+ embeds: Dict[str, torch.Tensor] = {},
497
+ outpath="./lora.safetensors",
498
+ ):
499
+ """
500
+ Converts the Lora from multiple pytorch .pt files into a single safetensor file.
501
+
502
+ modelmap is a dictionary of {
503
+ "module name": (pytorch_model_path, target_replace_module, rank)
504
+ }
505
+ """
506
+
507
+ weights = {}
508
+ metadata = {}
509
+
510
+ for name, (path, target_replace_module, r) in modelmap.items():
511
+ metadata[name] = json.dumps(list(target_replace_module))
512
+
513
+ lora = torch.load(path)
514
+ for i, weight in enumerate(lora):
515
+ is_up = i % 2 == 0
516
+ i = i // 2
517
+
518
+ if is_up:
519
+ metadata[f"{name}:{i}:rank"] = str(r)
520
+ weights[f"{name}:{i}:up"] = weight
521
+ else:
522
+ weights[f"{name}:{i}:down"] = weight
523
+
524
+ for token, tensor in embeds.items():
525
+ metadata[token] = EMBED_FLAG
526
+ weights[token] = tensor
527
+
528
+ print(f"Saving weights to {outpath}")
529
+ safe_save(weights, outpath, metadata)
530
+
531
+
532
+ def convert_loras_to_safeloras(
533
+ modelmap: Dict[str, Tuple[str, Set[str], int]] = {},
534
+ outpath="./lora.safetensors",
535
+ ):
536
+ convert_loras_to_safeloras_with_embeds(modelmap=modelmap, outpath=outpath)
537
+
538
+
539
+ def parse_safeloras(
540
+ safeloras,
541
+ ) -> Dict[str, Tuple[List[nn.parameter.Parameter], List[int], List[str]]]:
542
+ """
543
+ Converts a loaded safetensor file that contains a set of module Loras
544
+ into Parameters and other information
545
+
546
+ Output is a dictionary of {
547
+ "module name": (
548
+ [list of weights],
549
+ [list of ranks],
550
+ target_replacement_modules
551
+ )
552
+ }
553
+ """
554
+ loras = {}
555
+ metadata = safeloras.metadata()
556
+
557
+ get_name = lambda k: k.split(":")[0]
558
+
559
+ keys = list(safeloras.keys())
560
+ keys.sort(key=get_name)
561
+
562
+ for name, module_keys in groupby(keys, get_name):
563
+ info = metadata.get(name)
564
+
565
+ if not info:
566
+ raise ValueError(
567
+ f"Tensor {name} has no metadata - is this a Lora safetensor?"
568
+ )
569
+
570
+ # Skip Textual Inversion embeds
571
+ if info == EMBED_FLAG:
572
+ continue
573
+
574
+ # Handle Loras
575
+ # Extract the targets
576
+ target = json.loads(info)
577
+
578
+ # Build the result lists - Python needs us to preallocate lists to insert into them
579
+ module_keys = list(module_keys)
580
+ ranks = [4] * (len(module_keys) // 2)
581
+ weights = [None] * len(module_keys)
582
+
583
+ for key in module_keys:
584
+ # Split the model name and index out of the key
585
+ _, idx, direction = key.split(":")
586
+ idx = int(idx)
587
+
588
+ # Add the rank
589
+ ranks[idx] = int(metadata[f"{name}:{idx}:rank"])
590
+
591
+ # Insert the weight into the list
592
+ idx = idx * 2 + (1 if direction == "down" else 0)
593
+ weights[idx] = nn.parameter.Parameter(safeloras.get_tensor(key))
594
+
595
+ loras[name] = (weights, ranks, target)
596
+
597
+ return loras
598
+
599
+
600
+ def parse_safeloras_embeds(
601
+ safeloras,
602
+ ) -> Dict[str, torch.Tensor]:
603
+ """
604
+ Converts a loaded safetensor file that contains Textual Inversion embeds into
605
+ a dictionary of embed_token: Tensor
606
+ """
607
+ embeds = {}
608
+ metadata = safeloras.metadata()
609
+
610
+ for key in safeloras.keys():
611
+ # Only handle Textual Inversion embeds
612
+ meta = metadata.get(key)
613
+ if not meta or meta != EMBED_FLAG:
614
+ continue
615
+
616
+ embeds[key] = safeloras.get_tensor(key)
617
+
618
+ return embeds
619
+
620
+ def net_load_lora(net, checkpoint_path, alpha=1.0, remove=False):
621
+ visited=[]
622
+ state_dict = torch.load(checkpoint_path)
623
+ for k, v in state_dict.items():
624
+ state_dict[k] = v.to(net.device)
625
+ # import pdb;pdb.set_trace()
626
+ for key in state_dict:
627
+ if ".alpha" in key or key in visited:
628
+ continue
629
+ layer_infos = key.split(".")[:-2] # remove lora_up and down weight
630
+ curr_layer = net
631
+ # find the target layer
632
+ temp_name = layer_infos.pop(0)
633
+ while len(layer_infos) > -1:
634
+ curr_layer = curr_layer.__getattr__(temp_name)
635
+ if len(layer_infos) > 0:
636
+ temp_name = layer_infos.pop(0)
637
+ elif len(layer_infos) == 0:
638
+ break
639
+ if curr_layer.__class__ not in [nn.Linear, nn.Conv2d]:
640
+ print('missing param at:', key)
641
+ continue
642
+ pair_keys = []
643
+ if "lora_down" in key:
644
+ pair_keys.append(key.replace("lora_down", "lora_up"))
645
+ pair_keys.append(key)
646
+ else:
647
+ pair_keys.append(key)
648
+ pair_keys.append(key.replace("lora_up", "lora_down"))
649
+
650
+ # update weight
651
+ if len(state_dict[pair_keys[0]].shape) == 4:
652
+ # for conv
653
+ weight_up = state_dict[pair_keys[0]].squeeze(3).squeeze(2).to(torch.float32)
654
+ weight_down = state_dict[pair_keys[1]].squeeze(3).squeeze(2).to(torch.float32)
655
+ if remove:
656
+ curr_layer.weight.data -= alpha * torch.mm(weight_up, weight_down).unsqueeze(2).unsqueeze(3)
657
+ else:
658
+ curr_layer.weight.data += alpha * torch.mm(weight_up, weight_down).unsqueeze(2).unsqueeze(3)
659
+ else:
660
+ # for linear
661
+ weight_up = state_dict[pair_keys[0]].to(torch.float32)
662
+ weight_down = state_dict[pair_keys[1]].to(torch.float32)
663
+ if remove:
664
+ curr_layer.weight.data -= alpha * torch.mm(weight_up, weight_down)
665
+ else:
666
+ curr_layer.weight.data += alpha * torch.mm(weight_up, weight_down)
667
+
668
+ # update visited list
669
+ for item in pair_keys:
670
+ visited.append(item)
671
+ print('load_weight_num:',len(visited))
672
+ return
673
+
674
+ def change_lora(model, inject_lora=False, lora_scale=1.0, lora_path='', last_time_lora='', last_time_lora_scale=1.0):
675
+ # remove lora
676
+ if last_time_lora != '':
677
+ net_load_lora(model, last_time_lora, alpha=last_time_lora_scale, remove=True)
678
+ # add new lora
679
+ if inject_lora:
680
+ net_load_lora(model, lora_path, alpha=lora_scale)
681
+
682
+
683
+
684
+ def load_safeloras(path, device="cpu"):
685
+ safeloras = safe_open(path, framework="pt", device=device)
686
+ return parse_safeloras(safeloras)
687
+
688
+
689
+ def load_safeloras_embeds(path, device="cpu"):
690
+ safeloras = safe_open(path, framework="pt", device=device)
691
+ return parse_safeloras_embeds(safeloras)
692
+
693
+
694
+ def load_safeloras_both(path, device="cpu"):
695
+ safeloras = safe_open(path, framework="pt", device=device)
696
+ return parse_safeloras(safeloras), parse_safeloras_embeds(safeloras)
697
+
698
+
699
+ def collapse_lora(model, alpha=1.0):
700
+
701
+ for _module, name, _child_module in _find_modules(
702
+ model,
703
+ UNET_EXTENDED_TARGET_REPLACE | TEXT_ENCODER_EXTENDED_TARGET_REPLACE,
704
+ search_class=[LoraInjectedLinear, LoraInjectedConv2d],
705
+ ):
706
+
707
+ if isinstance(_child_module, LoraInjectedLinear):
708
+ print("Collapsing Lin Lora in", name)
709
+
710
+ _child_module.linear.weight = nn.Parameter(
711
+ _child_module.linear.weight.data
712
+ + alpha
713
+ * (
714
+ _child_module.lora_up.weight.data
715
+ @ _child_module.lora_down.weight.data
716
+ )
717
+ .type(_child_module.linear.weight.dtype)
718
+ .to(_child_module.linear.weight.device)
719
+ )
720
+
721
+ else:
722
+ print("Collapsing Conv Lora in", name)
723
+ _child_module.conv.weight = nn.Parameter(
724
+ _child_module.conv.weight.data
725
+ + alpha
726
+ * (
727
+ _child_module.lora_up.weight.data.flatten(start_dim=1)
728
+ @ _child_module.lora_down.weight.data.flatten(start_dim=1)
729
+ )
730
+ .reshape(_child_module.conv.weight.data.shape)
731
+ .type(_child_module.conv.weight.dtype)
732
+ .to(_child_module.conv.weight.device)
733
+ )
734
+
735
+
736
+ def monkeypatch_or_replace_lora(
737
+ model,
738
+ loras,
739
+ target_replace_module=DEFAULT_TARGET_REPLACE,
740
+ r: Union[int, List[int]] = 4,
741
+ ):
742
+ for _module, name, _child_module in _find_modules(
743
+ model, target_replace_module, search_class=[nn.Linear, LoraInjectedLinear]
744
+ ):
745
+ _source = (
746
+ _child_module.linear
747
+ if isinstance(_child_module, LoraInjectedLinear)
748
+ else _child_module
749
+ )
750
+
751
+ weight = _source.weight
752
+ bias = _source.bias
753
+ _tmp = LoraInjectedLinear(
754
+ _source.in_features,
755
+ _source.out_features,
756
+ _source.bias is not None,
757
+ r=r.pop(0) if isinstance(r, list) else r,
758
+ )
759
+ _tmp.linear.weight = weight
760
+
761
+ if bias is not None:
762
+ _tmp.linear.bias = bias
763
+
764
+ # switch the module
765
+ _module._modules[name] = _tmp
766
+
767
+ up_weight = loras.pop(0)
768
+ down_weight = loras.pop(0)
769
+
770
+ _module._modules[name].lora_up.weight = nn.Parameter(
771
+ up_weight.type(weight.dtype)
772
+ )
773
+ _module._modules[name].lora_down.weight = nn.Parameter(
774
+ down_weight.type(weight.dtype)
775
+ )
776
+
777
+ _module._modules[name].to(weight.device)
778
+
779
+
780
+ def monkeypatch_or_replace_lora_extended(
781
+ model,
782
+ loras,
783
+ target_replace_module=DEFAULT_TARGET_REPLACE,
784
+ r: Union[int, List[int]] = 4,
785
+ ):
786
+ for _module, name, _child_module in _find_modules(
787
+ model,
788
+ target_replace_module,
789
+ search_class=[nn.Linear, LoraInjectedLinear, nn.Conv2d, LoraInjectedConv2d],
790
+ ):
791
+
792
+ if (_child_module.__class__ == nn.Linear) or (
793
+ _child_module.__class__ == LoraInjectedLinear
794
+ ):
795
+ if len(loras[0].shape) != 2:
796
+ continue
797
+
798
+ _source = (
799
+ _child_module.linear
800
+ if isinstance(_child_module, LoraInjectedLinear)
801
+ else _child_module
802
+ )
803
+
804
+ weight = _source.weight
805
+ bias = _source.bias
806
+ _tmp = LoraInjectedLinear(
807
+ _source.in_features,
808
+ _source.out_features,
809
+ _source.bias is not None,
810
+ r=r.pop(0) if isinstance(r, list) else r,
811
+ )
812
+ _tmp.linear.weight = weight
813
+
814
+ if bias is not None:
815
+ _tmp.linear.bias = bias
816
+
817
+ elif (_child_module.__class__ == nn.Conv2d) or (
818
+ _child_module.__class__ == LoraInjectedConv2d
819
+ ):
820
+ if len(loras[0].shape) != 4:
821
+ continue
822
+ _source = (
823
+ _child_module.conv
824
+ if isinstance(_child_module, LoraInjectedConv2d)
825
+ else _child_module
826
+ )
827
+
828
+ weight = _source.weight
829
+ bias = _source.bias
830
+ _tmp = LoraInjectedConv2d(
831
+ _source.in_channels,
832
+ _source.out_channels,
833
+ _source.kernel_size,
834
+ _source.stride,
835
+ _source.padding,
836
+ _source.dilation,
837
+ _source.groups,
838
+ _source.bias is not None,
839
+ r=r.pop(0) if isinstance(r, list) else r,
840
+ )
841
+
842
+ _tmp.conv.weight = weight
843
+
844
+ if bias is not None:
845
+ _tmp.conv.bias = bias
846
+
847
+ # switch the module
848
+ _module._modules[name] = _tmp
849
+
850
+ up_weight = loras.pop(0)
851
+ down_weight = loras.pop(0)
852
+
853
+ _module._modules[name].lora_up.weight = nn.Parameter(
854
+ up_weight.type(weight.dtype)
855
+ )
856
+ _module._modules[name].lora_down.weight = nn.Parameter(
857
+ down_weight.type(weight.dtype)
858
+ )
859
+
860
+ _module._modules[name].to(weight.device)
861
+
862
+
863
+ def monkeypatch_or_replace_safeloras(models, safeloras):
864
+ loras = parse_safeloras(safeloras)
865
+
866
+ for name, (lora, ranks, target) in loras.items():
867
+ model = getattr(models, name, None)
868
+
869
+ if not model:
870
+ print(f"No model provided for {name}, contained in Lora")
871
+ continue
872
+
873
+ monkeypatch_or_replace_lora_extended(model, lora, target, ranks)
874
+
875
+
876
+ def monkeypatch_remove_lora(model):
877
+ for _module, name, _child_module in _find_modules(
878
+ model, search_class=[LoraInjectedLinear, LoraInjectedConv2d]
879
+ ):
880
+ if isinstance(_child_module, LoraInjectedLinear):
881
+ _source = _child_module.linear
882
+ weight, bias = _source.weight, _source.bias
883
+
884
+ _tmp = nn.Linear(
885
+ _source.in_features, _source.out_features, bias is not None
886
+ )
887
+
888
+ _tmp.weight = weight
889
+ if bias is not None:
890
+ _tmp.bias = bias
891
+
892
+ else:
893
+ _source = _child_module.conv
894
+ weight, bias = _source.weight, _source.bias
895
+
896
+ _tmp = nn.Conv2d(
897
+ in_channels=_source.in_channels,
898
+ out_channels=_source.out_channels,
899
+ kernel_size=_source.kernel_size,
900
+ stride=_source.stride,
901
+ padding=_source.padding,
902
+ dilation=_source.dilation,
903
+ groups=_source.groups,
904
+ bias=bias is not None,
905
+ )
906
+
907
+ _tmp.weight = weight
908
+ if bias is not None:
909
+ _tmp.bias = bias
910
+
911
+ _module._modules[name] = _tmp
912
+
913
+
914
+ def monkeypatch_add_lora(
915
+ model,
916
+ loras,
917
+ target_replace_module=DEFAULT_TARGET_REPLACE,
918
+ alpha: float = 1.0,
919
+ beta: float = 1.0,
920
+ ):
921
+ for _module, name, _child_module in _find_modules(
922
+ model, target_replace_module, search_class=[LoraInjectedLinear]
923
+ ):
924
+ weight = _child_module.linear.weight
925
+
926
+ up_weight = loras.pop(0)
927
+ down_weight = loras.pop(0)
928
+
929
+ _module._modules[name].lora_up.weight = nn.Parameter(
930
+ up_weight.type(weight.dtype).to(weight.device) * alpha
931
+ + _module._modules[name].lora_up.weight.to(weight.device) * beta
932
+ )
933
+ _module._modules[name].lora_down.weight = nn.Parameter(
934
+ down_weight.type(weight.dtype).to(weight.device) * alpha
935
+ + _module._modules[name].lora_down.weight.to(weight.device) * beta
936
+ )
937
+
938
+ _module._modules[name].to(weight.device)
939
+
940
+
941
+ def tune_lora_scale(model, alpha: float = 1.0):
942
+ for _module in model.modules():
943
+ if _module.__class__.__name__ in ["LoraInjectedLinear", "LoraInjectedConv2d"]:
944
+ _module.scale = alpha
945
+
946
+
947
+ def set_lora_diag(model, diag: torch.Tensor):
948
+ for _module in model.modules():
949
+ if _module.__class__.__name__ in ["LoraInjectedLinear", "LoraInjectedConv2d"]:
950
+ _module.set_selector_from_diag(diag)
951
+
952
+
953
+ def _text_lora_path(path: str) -> str:
954
+ assert path.endswith(".pt"), "Only .pt files are supported"
955
+ return ".".join(path.split(".")[:-1] + ["text_encoder", "pt"])
956
+
957
+
958
+ def _ti_lora_path(path: str) -> str:
959
+ assert path.endswith(".pt"), "Only .pt files are supported"
960
+ return ".".join(path.split(".")[:-1] + ["ti", "pt"])
961
+
962
+
963
+ def apply_learned_embed_in_clip(
964
+ learned_embeds,
965
+ text_encoder,
966
+ tokenizer,
967
+ token: Optional[Union[str, List[str]]] = None,
968
+ idempotent=False,
969
+ ):
970
+ if isinstance(token, str):
971
+ trained_tokens = [token]
972
+ elif isinstance(token, list):
973
+ assert len(learned_embeds.keys()) == len(
974
+ token
975
+ ), "The number of tokens and the number of embeds should be the same"
976
+ trained_tokens = token
977
+ else:
978
+ trained_tokens = list(learned_embeds.keys())
979
+
980
+ for token in trained_tokens:
981
+ print(token)
982
+ embeds = learned_embeds[token]
983
+
984
+ # cast to dtype of text_encoder
985
+ dtype = text_encoder.get_input_embeddings().weight.dtype
986
+ num_added_tokens = tokenizer.add_tokens(token)
987
+
988
+ i = 1
989
+ if not idempotent:
990
+ while num_added_tokens == 0:
991
+ print(f"The tokenizer already contains the token {token}.")
992
+ token = f"{token[:-1]}-{i}>"
993
+ print(f"Attempting to add the token {token}.")
994
+ num_added_tokens = tokenizer.add_tokens(token)
995
+ i += 1
996
+ elif num_added_tokens == 0 and idempotent:
997
+ print(f"The tokenizer already contains the token {token}.")
998
+ print(f"Replacing {token} embedding.")
999
+
1000
+ # resize the token embeddings
1001
+ text_encoder.resize_token_embeddings(len(tokenizer))
1002
+
1003
+ # get the id for the token and assign the embeds
1004
+ token_id = tokenizer.convert_tokens_to_ids(token)
1005
+ text_encoder.get_input_embeddings().weight.data[token_id] = embeds
1006
+ return token
1007
+
1008
+
1009
+ def load_learned_embed_in_clip(
1010
+ learned_embeds_path,
1011
+ text_encoder,
1012
+ tokenizer,
1013
+ token: Optional[Union[str, List[str]]] = None,
1014
+ idempotent=False,
1015
+ ):
1016
+ learned_embeds = torch.load(learned_embeds_path)
1017
+ apply_learned_embed_in_clip(
1018
+ learned_embeds, text_encoder, tokenizer, token, idempotent
1019
+ )
1020
+
1021
+
1022
+ def patch_pipe(
1023
+ pipe,
1024
+ maybe_unet_path,
1025
+ token: Optional[str] = None,
1026
+ r: int = 4,
1027
+ patch_unet=True,
1028
+ patch_text=True,
1029
+ patch_ti=True,
1030
+ idempotent_token=True,
1031
+ unet_target_replace_module=DEFAULT_TARGET_REPLACE,
1032
+ text_target_replace_module=TEXT_ENCODER_DEFAULT_TARGET_REPLACE,
1033
+ ):
1034
+ if maybe_unet_path.endswith(".pt"):
1035
+ # torch format
1036
+
1037
+ if maybe_unet_path.endswith(".ti.pt"):
1038
+ unet_path = maybe_unet_path[:-6] + ".pt"
1039
+ elif maybe_unet_path.endswith(".text_encoder.pt"):
1040
+ unet_path = maybe_unet_path[:-16] + ".pt"
1041
+ else:
1042
+ unet_path = maybe_unet_path
1043
+
1044
+ ti_path = _ti_lora_path(unet_path)
1045
+ text_path = _text_lora_path(unet_path)
1046
+
1047
+ if patch_unet:
1048
+ print("LoRA : Patching Unet")
1049
+ monkeypatch_or_replace_lora(
1050
+ pipe.unet,
1051
+ torch.load(unet_path),
1052
+ r=r,
1053
+ target_replace_module=unet_target_replace_module,
1054
+ )
1055
+
1056
+ if patch_text:
1057
+ print("LoRA : Patching text encoder")
1058
+ monkeypatch_or_replace_lora(
1059
+ pipe.text_encoder,
1060
+ torch.load(text_path),
1061
+ target_replace_module=text_target_replace_module,
1062
+ r=r,
1063
+ )
1064
+ if patch_ti:
1065
+ print("LoRA : Patching token input")
1066
+ token = load_learned_embed_in_clip(
1067
+ ti_path,
1068
+ pipe.text_encoder,
1069
+ pipe.tokenizer,
1070
+ token=token,
1071
+ idempotent=idempotent_token,
1072
+ )
1073
+
1074
+ elif maybe_unet_path.endswith(".safetensors"):
1075
+ safeloras = safe_open(maybe_unet_path, framework="pt", device="cpu")
1076
+ monkeypatch_or_replace_safeloras(pipe, safeloras)
1077
+ tok_dict = parse_safeloras_embeds(safeloras)
1078
+ if patch_ti:
1079
+ apply_learned_embed_in_clip(
1080
+ tok_dict,
1081
+ pipe.text_encoder,
1082
+ pipe.tokenizer,
1083
+ token=token,
1084
+ idempotent=idempotent_token,
1085
+ )
1086
+ return tok_dict
1087
+
1088
+
1089
+ @torch.no_grad()
1090
+ def inspect_lora(model):
1091
+ moved = {}
1092
+
1093
+ for name, _module in model.named_modules():
1094
+ if _module.__class__.__name__ in ["LoraInjectedLinear", "LoraInjectedConv2d"]:
1095
+ ups = _module.lora_up.weight.data.clone()
1096
+ downs = _module.lora_down.weight.data.clone()
1097
+
1098
+ wght: torch.Tensor = ups.flatten(1) @ downs.flatten(1)
1099
+
1100
+ dist = wght.flatten().abs().mean().item()
1101
+ if name in moved:
1102
+ moved[name].append(dist)
1103
+ else:
1104
+ moved[name] = [dist]
1105
+
1106
+ return moved
1107
+
1108
+
1109
+ def save_all(
1110
+ unet,
1111
+ text_encoder,
1112
+ save_path,
1113
+ placeholder_token_ids=None,
1114
+ placeholder_tokens=None,
1115
+ save_lora=True,
1116
+ save_ti=True,
1117
+ target_replace_module_text=TEXT_ENCODER_DEFAULT_TARGET_REPLACE,
1118
+ target_replace_module_unet=DEFAULT_TARGET_REPLACE,
1119
+ safe_form=True,
1120
+ ):
1121
+ if not safe_form:
1122
+ # save ti
1123
+ if save_ti:
1124
+ ti_path = _ti_lora_path(save_path)
1125
+ learned_embeds_dict = {}
1126
+ for tok, tok_id in zip(placeholder_tokens, placeholder_token_ids):
1127
+ learned_embeds = text_encoder.get_input_embeddings().weight[tok_id]
1128
+ print(
1129
+ f"Current Learned Embeddings for {tok}:, id {tok_id} ",
1130
+ learned_embeds[:4],
1131
+ )
1132
+ learned_embeds_dict[tok] = learned_embeds.detach().cpu()
1133
+
1134
+ torch.save(learned_embeds_dict, ti_path)
1135
+ print("Ti saved to ", ti_path)
1136
+
1137
+ # save text encoder
1138
+ if save_lora:
1139
+
1140
+ save_lora_weight(
1141
+ unet, save_path, target_replace_module=target_replace_module_unet
1142
+ )
1143
+ print("Unet saved to ", save_path)
1144
+
1145
+ save_lora_weight(
1146
+ text_encoder,
1147
+ _text_lora_path(save_path),
1148
+ target_replace_module=target_replace_module_text,
1149
+ )
1150
+ print("Text Encoder saved to ", _text_lora_path(save_path))
1151
+
1152
+ else:
1153
+ assert save_path.endswith(
1154
+ ".safetensors"
1155
+ ), f"Save path : {save_path} should end with .safetensors"
1156
+
1157
+ loras = {}
1158
+ embeds = {}
1159
+
1160
+ if save_lora:
1161
+
1162
+ loras["unet"] = (unet, target_replace_module_unet)
1163
+ loras["text_encoder"] = (text_encoder, target_replace_module_text)
1164
+
1165
+ if save_ti:
1166
+ for tok, tok_id in zip(placeholder_tokens, placeholder_token_ids):
1167
+ learned_embeds = text_encoder.get_input_embeddings().weight[tok_id]
1168
+ print(
1169
+ f"Current Learned Embeddings for {tok}:, id {tok_id} ",
1170
+ learned_embeds[:4],
1171
+ )
1172
+ embeds[tok] = learned_embeds.detach().cpu()
1173
+
1174
+ save_safeloras_with_embeds(loras, embeds, save_path)
lvdm/models/modules/openaimodel3d.py ADDED
@@ -0,0 +1,662 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import abstractmethod
2
+ import math
3
+ from einops import rearrange
4
+ from functools import partial
5
+ import numpy as np
6
+ import torch as th
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from omegaconf.listconfig import ListConfig
10
+
11
+ from lvdm.models.modules.util import (
12
+ checkpoint,
13
+ conv_nd,
14
+ linear,
15
+ avg_pool_nd,
16
+ zero_module,
17
+ normalization,
18
+ timestep_embedding,
19
+ nonlinearity,
20
+ )
21
+
22
+ # dummy replace
23
+ def convert_module_to_f16(x):
24
+ pass
25
+
26
+ def convert_module_to_f32(x):
27
+ pass
28
+
29
+ ## go
30
+ # ---------------------------------------------------------------------------------------------------
31
+ class TimestepBlock(nn.Module):
32
+ """
33
+ Any module where forward() takes timestep embeddings as a second argument.
34
+ """
35
+
36
+ @abstractmethod
37
+ def forward(self, x, emb):
38
+ """
39
+ Apply the module to `x` given `emb` timestep embeddings.
40
+ """
41
+
42
+
43
+ # ---------------------------------------------------------------------------------------------------
44
+ class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
45
+ """
46
+ A sequential module that passes timestep embeddings to the children that
47
+ support it as an extra input.
48
+ """
49
+
50
+ def forward(self, x, emb, context, **kwargs):
51
+ for layer in self:
52
+ if isinstance(layer, TimestepBlock):
53
+ x = layer(x, emb, **kwargs)
54
+ elif isinstance(layer, STTransformerClass):
55
+ x = layer(x, context, **kwargs)
56
+ else:
57
+ x = layer(x)
58
+ return x
59
+
60
+
61
+ # ---------------------------------------------------------------------------------------------------
62
+ class Upsample(nn.Module):
63
+ """
64
+ An upsampling layer with an optional convolution.
65
+ :param channels: channels in the inputs and outputs.
66
+ :param use_conv: a bool determining if a convolution is applied.
67
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
68
+ upsampling occurs in the inner-two dimensions.
69
+ """
70
+
71
+ def __init__(self, channels, use_conv, dims=2, out_channels=None,
72
+ kernel_size_t=3,
73
+ padding_t=1,
74
+ ):
75
+ super().__init__()
76
+ self.channels = channels
77
+ self.out_channels = out_channels or channels
78
+ self.use_conv = use_conv
79
+ self.dims = dims
80
+ if use_conv:
81
+ self.conv = conv_nd(dims, self.channels, self.out_channels, (kernel_size_t, 3,3), padding=(padding_t, 1,1))
82
+
83
+ def forward(self, x):
84
+ assert x.shape[1] == self.channels
85
+ if self.dims == 3:
86
+ x = F.interpolate(
87
+ x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
88
+ )
89
+ else:
90
+ x = F.interpolate(x, scale_factor=2, mode="nearest")
91
+ if self.use_conv:
92
+ x = self.conv(x)
93
+ return x
94
+
95
+
96
+ # ---------------------------------------------------------------------------------------------------
97
+ class TransposedUpsample(nn.Module):
98
+ 'Learned 2x upsampling without padding'
99
+ def __init__(self, channels, out_channels=None, ks=5):
100
+ super().__init__()
101
+ self.channels = channels
102
+ self.out_channels = out_channels or channels
103
+
104
+ self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2)
105
+
106
+ def forward(self,x):
107
+ return self.up(x)
108
+
109
+
110
+ # ---------------------------------------------------------------------------------------------------
111
+ class Downsample(nn.Module):
112
+ """
113
+ A downsampling layer with an optional convolution.
114
+ :param channels: channels in the inputs and outputs.
115
+ :param use_conv: a bool determining if a convolution is applied.
116
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
117
+ downsampling occurs in the inner-two dimensions.
118
+ """
119
+
120
+ def __init__(self, channels, use_conv, dims=2, out_channels=None,
121
+ kernel_size_t=3,
122
+ padding_t=1,
123
+ ):
124
+ super().__init__()
125
+ self.channels = channels
126
+ self.out_channels = out_channels or channels
127
+ self.use_conv = use_conv
128
+ self.dims = dims
129
+ stride = 2 if dims != 3 else (1, 2, 2)
130
+ if use_conv:
131
+ self.op = conv_nd(
132
+ dims, self.channels, self.out_channels, (kernel_size_t, 3,3), stride=stride, padding=(padding_t, 1,1)
133
+ )
134
+ else:
135
+ assert self.channels == self.out_channels
136
+ self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
137
+
138
+ def forward(self, x):
139
+ assert x.shape[1] == self.channels
140
+ return self.op(x)
141
+
142
+
143
+ # ---------------------------------------------------------------------------------------------------
144
+ class ResBlock(TimestepBlock):
145
+ """
146
+ A residual block that can optionally change the number of channels.
147
+ :param channels: the number of input channels.
148
+ :param emb_channels: the number of timestep embedding channels.
149
+ :param dropout: the rate of dropout.
150
+ :param out_channels: if specified, the number of out channels.
151
+ :param use_conv: if True and out_channels is specified, use a spatial
152
+ convolution instead of a smaller 1x1 convolution to change the
153
+ channels in the skip connection.
154
+ :param dims: determines if the signal is 1D, 2D, or 3D.
155
+ :param use_checkpoint: if True, use gradient checkpointing on this module.
156
+ :param up: if True, use this block for upsampling.
157
+ :param down: if True, use this block for downsampling.
158
+ """
159
+
160
+ def __init__(
161
+ self,
162
+ channels,
163
+ emb_channels,
164
+ dropout,
165
+ out_channels=None,
166
+ use_conv=False,
167
+ use_scale_shift_norm=False,
168
+ dims=2,
169
+ use_checkpoint=False,
170
+ up=False,
171
+ down=False,
172
+ # temporal
173
+ kernel_size_t=3,
174
+ padding_t=1,
175
+ nonlinearity_type='silu',
176
+ **kwargs
177
+ ):
178
+ super().__init__()
179
+ self.channels = channels
180
+ self.emb_channels = emb_channels
181
+ self.dropout = dropout
182
+ self.out_channels = out_channels or channels
183
+ self.use_conv = use_conv
184
+ self.use_checkpoint = use_checkpoint
185
+ self.use_scale_shift_norm = use_scale_shift_norm
186
+ self.nonlinearity_type = nonlinearity_type
187
+
188
+ self.in_layers = nn.Sequential(
189
+ normalization(channels),
190
+ nonlinearity(nonlinearity_type),
191
+ conv_nd(dims, channels, self.out_channels, (kernel_size_t, 3,3), padding=(padding_t, 1,1)),
192
+ )
193
+
194
+ self.updown = up or down
195
+
196
+ if up:
197
+ self.h_upd = Upsample(channels, False, dims, kernel_size_t=kernel_size_t, padding_t=padding_t)
198
+ self.x_upd = Upsample(channels, False, dims, kernel_size_t=kernel_size_t, padding_t=padding_t)
199
+ elif down:
200
+ self.h_upd = Downsample(channels, False, dims, kernel_size_t=kernel_size_t, padding_t=padding_t)
201
+ self.x_upd = Downsample(channels, False, dims, kernel_size_t=kernel_size_t, padding_t=padding_t)
202
+ else:
203
+ self.h_upd = self.x_upd = nn.Identity()
204
+
205
+ self.emb_layers = nn.Sequential(
206
+ nonlinearity(nonlinearity_type),
207
+ linear(
208
+ emb_channels,
209
+ 2 * self.out_channels if use_scale_shift_norm else self.out_channels,
210
+ ),
211
+ )
212
+ self.out_layers = nn.Sequential(
213
+ normalization(self.out_channels),
214
+ nonlinearity(nonlinearity_type),
215
+ nn.Dropout(p=dropout),
216
+ zero_module(
217
+ conv_nd(dims, self.out_channels, self.out_channels, (kernel_size_t, 3,3), padding=(padding_t, 1,1))
218
+ ),
219
+ )
220
+
221
+ if self.out_channels == channels:
222
+ self.skip_connection = nn.Identity()
223
+ elif use_conv:
224
+ self.skip_connection = conv_nd(
225
+ dims, channels, self.out_channels, (kernel_size_t, 3,3), padding=(padding_t, 1,1)
226
+ )
227
+ else:
228
+ self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
229
+
230
+
231
+ def forward(self, x, emb, **kwargs):
232
+ """
233
+ Apply the block to a Tensor, conditioned on a timestep embedding.
234
+ :param x: an [N x C x ...] Tensor of features.
235
+ :param emb: an [N x emb_channels] Tensor of timestep embeddings.
236
+ :return: an [N x C x ...] Tensor of outputs.
237
+ """
238
+ return checkpoint(self._forward,
239
+ (x, emb),
240
+ self.parameters(),
241
+ self.use_checkpoint
242
+ )
243
+
244
+ def _forward(self, x, emb,):
245
+ if self.updown:
246
+ in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
247
+ h = in_rest(x)
248
+ h = self.h_upd(h)
249
+ x = self.x_upd(x)
250
+ h = in_conv(h)
251
+ else:
252
+ h = self.in_layers(x)
253
+
254
+ emb_out = self.emb_layers(emb).type(h.dtype)
255
+ if emb_out.dim() == 3: # btc for video data
256
+ emb_out = rearrange(emb_out, 'b t c -> b c t')
257
+ while len(emb_out.shape) < h.dim():
258
+ emb_out = emb_out[..., None] # bct -> bct11 or bc -> bc111
259
+
260
+ if self.use_scale_shift_norm:
261
+ out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
262
+ scale, shift = th.chunk(emb_out, 2, dim=1)
263
+ h = out_norm(h) * (1 + scale) + shift
264
+ h = out_rest(h)
265
+ else:
266
+ h = h + emb_out
267
+ h = self.out_layers(h)
268
+
269
+ out = self.skip_connection(x) + h
270
+
271
+ return out
272
+
273
+ # ---------------------------------------------------------------------------------------------------
274
+ def make_spatialtemporal_transformer(module_name='attention_temporal', class_name='SpatialTemporalTransformer'):
275
+ module = __import__(f"lvdm.models.modules.{module_name}", fromlist=[class_name])
276
+ global STTransformerClass
277
+ STTransformerClass = getattr(module, class_name)
278
+ return STTransformerClass
279
+
280
+ # ---------------------------------------------------------------------------------------------------
281
+ class UNetModel(nn.Module):
282
+ """
283
+ The full UNet model with attention and timestep embedding.
284
+ :param in_channels: channels in the input Tensor.
285
+ :param model_channels: base channel count for the model.
286
+ :param out_channels: channels in the output Tensor.
287
+ :param num_res_blocks: number of residual blocks per downsample.
288
+ :param attention_resolutions: a collection of downsample rates at which
289
+ attention will take place. May be a set, list, or tuple.
290
+ For example, if this contains 4, then at 4x downsampling, attention
291
+ will be used.
292
+ :param dropout: the dropout probability.
293
+ :param channel_mult: channel multiplier for each level of the UNet.
294
+ :param conv_resample: if True, use learned convolutions for upsampling and
295
+ downsampling.
296
+ :param dims: determines if the signal is 1D, 2D, or 3D.
297
+ :param num_classes: if specified (as an int), then this model will be
298
+ class-conditional with `num_classes` classes.
299
+ :param use_checkpoint: use gradient checkpointing to reduce memory usage.
300
+ :param num_heads: the number of attention heads in each attention layer.
301
+ :param num_heads_channels: if specified, ignore num_heads and instead use
302
+ a fixed channel width per attention head.
303
+ :param num_heads_upsample: works with num_heads to set a different number
304
+ of heads for upsampling. Deprecated.
305
+ :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
306
+ :param resblock_updown: use residual blocks for up/downsampling.
307
+ :param use_new_attention_order: use a different attention pattern for potentially
308
+ increased efficiency.
309
+ """
310
+
311
+ def __init__(
312
+ self,
313
+ image_size, # not used in UNetModel
314
+ in_channels,
315
+ model_channels,
316
+ out_channels,
317
+ num_res_blocks,
318
+ attention_resolutions,
319
+ dropout=0,
320
+ channel_mult=(1, 2, 4, 8),
321
+ conv_resample=True,
322
+ dims=3,
323
+ num_classes=None,
324
+ use_checkpoint=False,
325
+ use_fp16=False,
326
+ num_heads=-1,
327
+ num_head_channels=-1,
328
+ num_heads_upsample=-1,
329
+ use_scale_shift_norm=False,
330
+ resblock_updown=False,
331
+ transformer_depth=1, # custom transformer support
332
+ context_dim=None, # custom transformer support
333
+ legacy=True,
334
+ # temporal related
335
+ kernel_size_t=1,
336
+ padding_t=1,
337
+ use_temporal_transformer=True,
338
+ temporal_length=None,
339
+ use_relative_position=False,
340
+ cross_attn_on_tempoal=False,
341
+ temporal_crossattn_type="crossattn",
342
+ order="stst",
343
+ nonlinearity_type='silu',
344
+ temporalcrossfirst=False,
345
+ split_stcontext=False,
346
+ temporal_context_dim=None,
347
+ use_tempoal_causal_attn=False,
348
+ ST_transformer_module='attention_temporal',
349
+ ST_transformer_class='SpatialTemporalTransformer',
350
+ **kwargs,
351
+ ):
352
+ super().__init__()
353
+ assert(use_temporal_transformer)
354
+ if context_dim is not None:
355
+ if type(context_dim) == ListConfig:
356
+ context_dim = list(context_dim)
357
+
358
+ if num_heads_upsample == -1:
359
+ num_heads_upsample = num_heads
360
+
361
+ if num_heads == -1:
362
+ assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
363
+
364
+ if num_head_channels == -1:
365
+ assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
366
+
367
+ self.image_size = image_size
368
+ self.in_channels = in_channels
369
+ self.model_channels = model_channels
370
+ self.out_channels = out_channels
371
+ self.num_res_blocks = num_res_blocks
372
+ self.attention_resolutions = attention_resolutions
373
+ self.dropout = dropout
374
+ self.channel_mult = channel_mult
375
+ self.conv_resample = conv_resample
376
+ self.num_classes = num_classes
377
+ self.use_checkpoint = use_checkpoint
378
+ self.dtype = th.float16 if use_fp16 else th.float32
379
+ self.num_heads = num_heads
380
+ self.num_head_channels = num_head_channels
381
+ self.num_heads_upsample = num_heads_upsample
382
+
383
+ self.use_relative_position = use_relative_position
384
+ self.temporal_length = temporal_length
385
+ self.cross_attn_on_tempoal = cross_attn_on_tempoal
386
+ self.temporal_crossattn_type = temporal_crossattn_type
387
+ self.order = order
388
+ self.temporalcrossfirst = temporalcrossfirst
389
+ self.split_stcontext = split_stcontext
390
+ self.temporal_context_dim = temporal_context_dim
391
+ self.nonlinearity_type = nonlinearity_type
392
+ self.use_tempoal_causal_attn = use_tempoal_causal_attn
393
+
394
+
395
+ time_embed_dim = model_channels * 4
396
+ self.time_embed_dim = time_embed_dim
397
+ self.time_embed = nn.Sequential(
398
+ linear(model_channels, time_embed_dim),
399
+ nonlinearity(nonlinearity_type),
400
+ linear(time_embed_dim, time_embed_dim),
401
+ )
402
+
403
+ if self.num_classes is not None:
404
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim)
405
+
406
+ STTransformerClass = make_spatialtemporal_transformer(module_name=ST_transformer_module,
407
+ class_name=ST_transformer_class)
408
+
409
+ self.input_blocks = nn.ModuleList(
410
+ [
411
+ TimestepEmbedSequential(
412
+ conv_nd(dims, in_channels, model_channels, (kernel_size_t, 3,3), padding=(padding_t, 1,1))
413
+ )
414
+ ]
415
+ )
416
+ self._feature_size = model_channels
417
+ input_block_chans = [model_channels]
418
+ ch = model_channels
419
+ ds = 1
420
+ for level, mult in enumerate(channel_mult):
421
+ for _ in range(num_res_blocks):
422
+ layers = [
423
+ ResBlock(
424
+ ch,
425
+ time_embed_dim,
426
+ dropout,
427
+ out_channels=mult * model_channels,
428
+ dims=dims,
429
+ use_checkpoint=use_checkpoint,
430
+ use_scale_shift_norm=use_scale_shift_norm,
431
+ kernel_size_t=kernel_size_t,
432
+ padding_t=padding_t,
433
+ nonlinearity_type=nonlinearity_type,
434
+ **kwargs
435
+ )
436
+ ]
437
+ ch = mult * model_channels
438
+ if ds in attention_resolutions:
439
+ if num_head_channels == -1:
440
+ dim_head = ch // num_heads
441
+ else:
442
+ num_heads = ch // num_head_channels
443
+ dim_head = num_head_channels
444
+ if legacy:
445
+ dim_head = ch // num_heads if use_temporal_transformer else num_head_channels
446
+ layers.append(STTransformerClass(
447
+ ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
448
+ # temporal related
449
+ temporal_length=temporal_length,
450
+ use_relative_position=use_relative_position,
451
+ cross_attn_on_tempoal=cross_attn_on_tempoal,
452
+ temporal_crossattn_type=temporal_crossattn_type,
453
+ order=order,
454
+ temporalcrossfirst=temporalcrossfirst,
455
+ split_stcontext=split_stcontext,
456
+ temporal_context_dim=temporal_context_dim,
457
+ use_tempoal_causal_attn=use_tempoal_causal_attn,
458
+ **kwargs,
459
+ ))
460
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
461
+ self._feature_size += ch
462
+ input_block_chans.append(ch)
463
+ if level != len(channel_mult) - 1:
464
+ out_ch = ch
465
+ self.input_blocks.append(
466
+ TimestepEmbedSequential(
467
+ ResBlock(
468
+ ch,
469
+ time_embed_dim,
470
+ dropout,
471
+ out_channels=out_ch,
472
+ dims=dims,
473
+ use_checkpoint=use_checkpoint,
474
+ use_scale_shift_norm=use_scale_shift_norm,
475
+ down=True,
476
+ kernel_size_t=kernel_size_t,
477
+ padding_t=padding_t,
478
+ nonlinearity_type=nonlinearity_type,
479
+ **kwargs
480
+ )
481
+ if resblock_updown
482
+ else Downsample(
483
+ ch, conv_resample, dims=dims, out_channels=out_ch, kernel_size_t=kernel_size_t, padding_t=padding_t
484
+ )
485
+ )
486
+ )
487
+ ch = out_ch
488
+ input_block_chans.append(ch)
489
+ ds *= 2
490
+ self._feature_size += ch
491
+
492
+ if num_head_channels == -1:
493
+ dim_head = ch // num_heads
494
+ else:
495
+ num_heads = ch // num_head_channels
496
+ dim_head = num_head_channels
497
+ if legacy:
498
+ dim_head = ch // num_heads if use_temporal_transformer else num_head_channels
499
+ self.middle_block = TimestepEmbedSequential(
500
+ ResBlock(
501
+ ch,
502
+ time_embed_dim,
503
+ dropout,
504
+ dims=dims,
505
+ use_checkpoint=use_checkpoint,
506
+ use_scale_shift_norm=use_scale_shift_norm,
507
+ kernel_size_t=kernel_size_t,
508
+ padding_t=padding_t,
509
+ nonlinearity_type=nonlinearity_type,
510
+ **kwargs
511
+ ),
512
+ STTransformerClass(
513
+ ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
514
+ # temporal related
515
+ temporal_length=temporal_length,
516
+ use_relative_position=use_relative_position,
517
+ cross_attn_on_tempoal=cross_attn_on_tempoal,
518
+ temporal_crossattn_type=temporal_crossattn_type,
519
+ order=order,
520
+ temporalcrossfirst=temporalcrossfirst,
521
+ split_stcontext=split_stcontext,
522
+ temporal_context_dim=temporal_context_dim,
523
+ use_tempoal_causal_attn=use_tempoal_causal_attn,
524
+ **kwargs,
525
+ ),
526
+ ResBlock(
527
+ ch,
528
+ time_embed_dim,
529
+ dropout,
530
+ dims=dims,
531
+ use_checkpoint=use_checkpoint,
532
+ use_scale_shift_norm=use_scale_shift_norm,
533
+ kernel_size_t=kernel_size_t,
534
+ padding_t=padding_t,
535
+ nonlinearity_type=nonlinearity_type,
536
+ **kwargs
537
+ ),
538
+ )
539
+ self._feature_size += ch
540
+
541
+ self.output_blocks = nn.ModuleList([])
542
+ for level, mult in list(enumerate(channel_mult))[::-1]:
543
+ for i in range(num_res_blocks + 1):
544
+ ich = input_block_chans.pop()
545
+ layers = [
546
+ ResBlock(
547
+ ch + ich,
548
+ time_embed_dim,
549
+ dropout,
550
+ out_channels=model_channels * mult,
551
+ dims=dims,
552
+ use_checkpoint=use_checkpoint,
553
+ use_scale_shift_norm=use_scale_shift_norm,
554
+ kernel_size_t=kernel_size_t,
555
+ padding_t=padding_t,
556
+ nonlinearity_type=nonlinearity_type,
557
+ **kwargs
558
+ )
559
+ ]
560
+ ch = model_channels * mult
561
+ if ds in attention_resolutions:
562
+ if num_head_channels == -1:
563
+ dim_head = ch // num_heads
564
+ else:
565
+ num_heads = ch // num_head_channels
566
+ dim_head = num_head_channels
567
+ if legacy:
568
+ dim_head = ch // num_heads if use_temporal_transformer else num_head_channels
569
+ layers.append(
570
+ STTransformerClass(
571
+ ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
572
+ # temporal related
573
+ temporal_length=temporal_length,
574
+ use_relative_position=use_relative_position,
575
+ cross_attn_on_tempoal=cross_attn_on_tempoal,
576
+ temporal_crossattn_type=temporal_crossattn_type,
577
+ order=order,
578
+ temporalcrossfirst=temporalcrossfirst,
579
+ split_stcontext=split_stcontext,
580
+ temporal_context_dim=temporal_context_dim,
581
+ use_tempoal_causal_attn=use_tempoal_causal_attn,
582
+ **kwargs,
583
+ )
584
+ )
585
+ if level and i == num_res_blocks:
586
+ out_ch = ch
587
+ layers.append(
588
+ ResBlock(
589
+ ch,
590
+ time_embed_dim,
591
+ dropout,
592
+ out_channels=out_ch,
593
+ dims=dims,
594
+ use_checkpoint=use_checkpoint,
595
+ use_scale_shift_norm=use_scale_shift_norm,
596
+ up=True,
597
+ kernel_size_t=kernel_size_t,
598
+ padding_t=padding_t,
599
+ nonlinearity_type=nonlinearity_type,
600
+ **kwargs
601
+ )
602
+ if resblock_updown
603
+ else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch, kernel_size_t=kernel_size_t, padding_t=padding_t)
604
+ )
605
+ ds //= 2
606
+ self.output_blocks.append(TimestepEmbedSequential(*layers))
607
+ self._feature_size += ch
608
+
609
+ self.out = nn.Sequential(
610
+ normalization(ch),
611
+ nonlinearity(nonlinearity_type),
612
+ zero_module(conv_nd(dims, model_channels, out_channels, (kernel_size_t, 3,3), padding=(padding_t, 1,1))),
613
+ )
614
+
615
+
616
+ def convert_to_fp16(self):
617
+ """
618
+ Convert the torso of the model to float16.
619
+ """
620
+ self.input_blocks.apply(convert_module_to_f16)
621
+ self.middle_block.apply(convert_module_to_f16)
622
+ self.output_blocks.apply(convert_module_to_f16)
623
+
624
+ def convert_to_fp32(self):
625
+ """
626
+ Convert the torso of the model to float32.
627
+ """
628
+ self.input_blocks.apply(convert_module_to_f32)
629
+ self.middle_block.apply(convert_module_to_f32)
630
+ self.output_blocks.apply(convert_module_to_f32)
631
+
632
+ def forward(self, x, timesteps=None, time_emb_replace=None, context=None, y=None, **kwargs):
633
+ """
634
+ Apply the model to an input batch.
635
+ :param x: an [N x C x ...] Tensor of inputs.
636
+ :param timesteps: a 1-D batch of timesteps.
637
+ :param context: conditioning plugged in via crossattn
638
+ :param y: an [N] Tensor of labels, if class-conditional.
639
+ :return: an [N x C x ...] Tensor of outputs.
640
+ """
641
+
642
+ hs = []
643
+ if time_emb_replace is None:
644
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
645
+ emb = self.time_embed(t_emb)
646
+ else:
647
+ emb = time_emb_replace
648
+
649
+ if y is not None: # if class-conditional model, inject class labels
650
+ assert y.shape == (x.shape[0],)
651
+ emb = emb + self.label_emb(y)
652
+
653
+ h = x.type(self.dtype)
654
+ for module in self.input_blocks:
655
+ h = module(h, emb, context, **kwargs)
656
+ hs.append(h)
657
+ h = self.middle_block(h, emb, context, **kwargs)
658
+ for module in self.output_blocks:
659
+ h = th.cat([h, hs.pop()], dim=1)
660
+ h = module(h, emb, context, **kwargs)
661
+ h = h.type(x.dtype)
662
+ return self.out(h)
lvdm/models/modules/util.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from inspect import isfunction
3
+
4
+ import torch
5
+ import numpy as np
6
+ import torch.nn as nn
7
+ from einops import repeat
8
+ import torch.nn.functional as F
9
+
10
+ from lvdm.utils.common_utils import instantiate_from_config
11
+
12
+
13
+ def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
14
+ if schedule == "linear":
15
+ betas = (
16
+ torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2
17
+ )
18
+ elif schedule == "cosine":
19
+ timesteps = (
20
+ torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s
21
+ )
22
+ alphas = timesteps / (1 + cosine_s) * np.pi / 2
23
+ alphas = torch.cos(alphas).pow(2)
24
+ alphas = alphas / alphas[0]
25
+ betas = 1 - alphas[1:] / alphas[:-1]
26
+ betas = np.clip(betas, a_min=0, a_max=0.999)
27
+ elif schedule == "sqrt_linear":
28
+ betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64)
29
+ elif schedule == "sqrt":
30
+ betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5
31
+ else:
32
+ raise ValueError(f"schedule '{schedule}' unknown.")
33
+ return betas.numpy()
34
+
35
+
36
+ def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True):
37
+ if ddim_discr_method == 'uniform':
38
+ c = num_ddpm_timesteps // num_ddim_timesteps
39
+ ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c)))
40
+ elif ddim_discr_method == 'quad':
41
+ ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int)
42
+ else:
43
+ raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"')
44
+
45
+ # add one to get the final alpha values right (the ones from first scale to data during sampling)
46
+ steps_out = ddim_timesteps + 1
47
+ if verbose:
48
+ print(f'Selected timesteps for ddim sampler: {steps_out}')
49
+ return steps_out
50
+
51
+
52
+ def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):
53
+ # select alphas for computing the variance schedule
54
+ alphas = alphacums[ddim_timesteps]
55
+ alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist())
56
+
57
+ # according the the formula provided in https://arxiv.org/abs/2010.02502
58
+ sigmas = eta * np.sqrt((1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev))
59
+ if verbose:
60
+ print(f'Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}')
61
+ print(f'For the chosen value of eta, which is {eta}, '
62
+ f'this results in the following sigma_t schedule for ddim sampler {sigmas}')
63
+ return sigmas, alphas, alphas_prev
64
+
65
+
66
+ def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
67
+ """
68
+ Create a beta schedule that discretizes the given alpha_t_bar function,
69
+ which defines the cumulative product of (1-beta) over time from t = [0,1].
70
+ :param num_diffusion_timesteps: the number of betas to produce.
71
+ :param alpha_bar: a lambda that takes an argument t from 0 to 1 and
72
+ produces the cumulative product of (1-beta) up to that
73
+ part of the diffusion process.
74
+ :param max_beta: the maximum beta to use; use values lower than 1 to
75
+ prevent singularities.
76
+ """
77
+ betas = []
78
+ for i in range(num_diffusion_timesteps):
79
+ t1 = i / num_diffusion_timesteps
80
+ t2 = (i + 1) / num_diffusion_timesteps
81
+ betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
82
+ return np.array(betas)
83
+
84
+
85
+ def extract_into_tensor(a, t, x_shape):
86
+ b, *_ = t.shape
87
+ out = a.gather(-1, t)
88
+ return out.reshape(b, *((1,) * (len(x_shape) - 1)))
89
+
90
+
91
+ def checkpoint(func, inputs, params, flag):
92
+ """
93
+ Evaluate a function without caching intermediate activations, allowing for
94
+ reduced memory at the expense of extra compute in the backward pass.
95
+ :param func: the function to evaluate.
96
+ :param inputs: the argument sequence to pass to `func`.
97
+ :param params: a sequence of parameters `func` depends on but does not
98
+ explicitly take as arguments.
99
+ :param flag: if False, disable gradient checkpointing.
100
+ """
101
+ if flag:
102
+ args = tuple(inputs) + tuple(params)
103
+ return CheckpointFunction.apply(func, len(inputs), *args)
104
+ else:
105
+ return func(*inputs)
106
+
107
+
108
+ class CheckpointFunction(torch.autograd.Function):
109
+ @staticmethod
110
+ @torch.cuda.amp.custom_fwd
111
+ def forward(ctx, run_function, length, *args):
112
+ ctx.run_function = run_function
113
+ ctx.input_tensors = list(args[:length])
114
+ ctx.input_params = list(args[length:])
115
+
116
+ with torch.no_grad():
117
+ output_tensors = ctx.run_function(*ctx.input_tensors)
118
+ return output_tensors
119
+
120
+ @staticmethod
121
+ @torch.cuda.amp.custom_bwd
122
+ def backward(ctx, *output_grads):
123
+ ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
124
+ with torch.enable_grad():
125
+ # Fixes a bug where the first op in run_function modifies the
126
+ # Tensor storage in place, which is not allowed for detach()'d
127
+ # Tensors.
128
+ shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
129
+ output_tensors = ctx.run_function(*shallow_copies)
130
+ input_grads = torch.autograd.grad(
131
+ output_tensors,
132
+ ctx.input_tensors + ctx.input_params,
133
+ output_grads,
134
+ allow_unused=True,
135
+ )
136
+ del ctx.input_tensors
137
+ del ctx.input_params
138
+ del output_tensors
139
+ return (None, None) + input_grads
140
+
141
+
142
+ def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
143
+ """
144
+ Create sinusoidal timestep embeddings.
145
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
146
+ These may be fractional.
147
+ :param dim: the dimension of the output.
148
+ :param max_period: controls the minimum frequency of the embeddings.
149
+ :return: an [N x dim] Tensor of positional embeddings.
150
+ """
151
+ if not repeat_only:
152
+ half = dim // 2
153
+ freqs = torch.exp(
154
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
155
+ ).to(device=timesteps.device)
156
+ args = timesteps[:, None].float() * freqs[None]
157
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
158
+ if dim % 2:
159
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
160
+ else:
161
+ embedding = repeat(timesteps, 'b -> b d', d=dim)
162
+ return embedding
163
+
164
+
165
+ def zero_module(module):
166
+ """
167
+ Zero out the parameters of a module and return it.
168
+ """
169
+ for p in module.parameters():
170
+ p.detach().zero_()
171
+ return module
172
+
173
+
174
+ def scale_module(module, scale):
175
+ """
176
+ Scale the parameters of a module and return it.
177
+ """
178
+ for p in module.parameters():
179
+ p.detach().mul_(scale)
180
+ return module
181
+
182
+
183
+ def mean_flat(tensor):
184
+ """
185
+ Take the mean over all non-batch dimensions.
186
+ """
187
+ return tensor.mean(dim=list(range(1, len(tensor.shape))))
188
+
189
+
190
+ def normalization(channels):
191
+ """
192
+ Make a standard normalization layer.
193
+ :param channels: number of input channels.
194
+ :return: an nn.Module for normalization.
195
+ """
196
+ return GroupNorm32(32, channels)
197
+
198
+ def Normalize(in_channels):
199
+ return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
200
+
201
+ def identity(*args, **kwargs):
202
+ return nn.Identity()
203
+
204
+ class Normalization(nn.Module):
205
+ def __init__(self, output_size, eps=1e-5, norm_type='gn'):
206
+ super(Normalization, self).__init__()
207
+ # epsilon to avoid dividing by 0
208
+ self.eps = eps
209
+ self.norm_type = norm_type
210
+
211
+ if self.norm_type in ['bn', 'in']:
212
+ self.register_buffer('stored_mean', torch.zeros(output_size))
213
+ self.register_buffer('stored_var', torch.ones(output_size))
214
+
215
+ def forward(self, x):
216
+ if self.norm_type == 'bn':
217
+ out = F.batch_norm(x, self.stored_mean, self.stored_var, None,
218
+ None,
219
+ self.training, 0.1, self.eps)
220
+ elif self.norm_type == 'in':
221
+ out = F.instance_norm(x, self.stored_mean, self.stored_var,
222
+ None, None,
223
+ self.training, 0.1, self.eps)
224
+ elif self.norm_type == 'gn':
225
+ out = F.group_norm(x, 32)
226
+ elif self.norm_type == 'nonorm':
227
+ out = x
228
+ return out
229
+
230
+
231
+ class CCNormalization(nn.Module):
232
+ def __init__(self, embed_dim, feature_dim, *args, **kwargs):
233
+ super(CCNormalization, self).__init__()
234
+
235
+ self.embed_dim = embed_dim
236
+ self.feature_dim = feature_dim
237
+ self.norm = Normalization(feature_dim, *args, **kwargs)
238
+
239
+ self.gain = nn.Linear(self.embed_dim, self.feature_dim)
240
+ self.bias = nn.Linear(self.embed_dim, self.feature_dim)
241
+
242
+ def forward(self, x, y):
243
+ shape = [1] * (x.dim() - 2)
244
+ gain = (1 + self.gain(y)).view(y.size(0), -1, *shape)
245
+ bias = self.bias(y).view(y.size(0), -1, *shape)
246
+ return self.norm(x) * gain + bias
247
+
248
+
249
+ def nonlinearity(type='silu'):
250
+ if type == 'silu':
251
+ return nn.SiLU()
252
+ elif type == 'leaky_relu':
253
+ return nn.LeakyReLU()
254
+
255
+
256
+ class GEGLU(nn.Module):
257
+ def __init__(self, dim_in, dim_out):
258
+ super().__init__()
259
+ self.proj = nn.Linear(dim_in, dim_out * 2)
260
+
261
+ def forward(self, x):
262
+ x, gate = self.proj(x).chunk(2, dim=-1)
263
+ return x * F.gelu(gate)
264
+
265
+
266
+ class SiLU(nn.Module):
267
+ def forward(self, x):
268
+ return x * torch.sigmoid(x)
269
+
270
+
271
+ class GroupNorm32(nn.GroupNorm):
272
+ def forward(self, x):
273
+ return super().forward(x.float()).type(x.dtype)
274
+
275
+
276
+ def conv_nd(dims, *args, **kwargs):
277
+ """
278
+ Create a 1D, 2D, or 3D convolution module.
279
+ """
280
+ if dims == 1:
281
+ return nn.Conv1d(*args, **kwargs)
282
+ elif dims == 2:
283
+ return nn.Conv2d(*args, **kwargs)
284
+ elif dims == 3:
285
+ return nn.Conv3d(*args, **kwargs)
286
+ raise ValueError(f"unsupported dimensions: {dims}")
287
+
288
+
289
+ def linear(*args, **kwargs):
290
+ """
291
+ Create a linear module.
292
+ """
293
+ return nn.Linear(*args, **kwargs)
294
+
295
+
296
+ def avg_pool_nd(dims, *args, **kwargs):
297
+ """
298
+ Create a 1D, 2D, or 3D average pooling module.
299
+ """
300
+ if dims == 1:
301
+ return nn.AvgPool1d(*args, **kwargs)
302
+ elif dims == 2:
303
+ return nn.AvgPool2d(*args, **kwargs)
304
+ elif dims == 3:
305
+ return nn.AvgPool3d(*args, **kwargs)
306
+ raise ValueError(f"unsupported dimensions: {dims}")
307
+
308
+
309
+ class HybridConditioner(nn.Module):
310
+
311
+ def __init__(self, c_concat_config, c_crossattn_config):
312
+ super().__init__()
313
+ self.concat_conditioner = instantiate_from_config(c_concat_config)
314
+ self.crossattn_conditioner = instantiate_from_config(c_crossattn_config)
315
+
316
+ def forward(self, c_concat, c_crossattn):
317
+ c_concat = self.concat_conditioner(c_concat)
318
+ c_crossattn = self.crossattn_conditioner(c_crossattn)
319
+ return {'c_concat': [c_concat], 'c_crossattn': [c_crossattn]}
320
+
321
+
322
+ def noise_like(shape, device, repeat=False):
323
+ repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
324
+ noise = lambda: torch.randn(shape, device=device)
325
+ return repeat_noise() if repeat else noise()
326
+
327
+
328
+ def init_(tensor):
329
+ dim = tensor.shape[-1]
330
+ std = 1 / math.sqrt(dim)
331
+ tensor.uniform_(-std, std)
332
+ return tensor
333
+
334
+
335
+ def exists(val):
336
+ return val is not None
337
+
338
+
339
+ def uniq(arr):
340
+ return{el: True for el in arr}.keys()
341
+
342
+
343
+ def default(val, d):
344
+ if exists(val):
345
+ return val
346
+ return d() if isfunction(d) else d
347
+
348
+
lvdm/samplers/ddim.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SAMPLING ONLY."""
2
+
3
+ import torch
4
+ import numpy as np
5
+ from tqdm import tqdm
6
+
7
+ from lvdm.models.modules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like
8
+
9
+
10
+ class DDIMSampler(object):
11
+ def __init__(self, model, schedule="linear", **kwargs):
12
+ super().__init__()
13
+ self.model = model
14
+ self.ddpm_num_timesteps = model.num_timesteps
15
+ self.schedule = schedule
16
+ self.counter = 0
17
+
18
+ def register_buffer(self, name, attr):
19
+ if type(attr) == torch.Tensor:
20
+ if attr.device != torch.device("cuda"):
21
+ attr = attr.to(torch.device("cuda"))
22
+ setattr(self, name, attr)
23
+
24
+ def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
25
+ self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
26
+ num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
27
+ alphas_cumprod = self.model.alphas_cumprod
28
+ assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
29
+ to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
30
+
31
+ self.register_buffer('betas', to_torch(self.model.betas))
32
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
33
+ self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
34
+
35
+ # calculations for diffusion q(x_t | x_{t-1}) and others
36
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
37
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
38
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
39
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
40
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
41
+
42
+ # ddim sampling parameters
43
+ ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
44
+ ddim_timesteps=self.ddim_timesteps,
45
+ eta=ddim_eta,verbose=verbose)
46
+ self.register_buffer('ddim_sigmas', ddim_sigmas)
47
+ self.register_buffer('ddim_alphas', ddim_alphas)
48
+ self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
49
+ self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
50
+ sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
51
+ (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
52
+ 1 - self.alphas_cumprod / self.alphas_cumprod_prev))
53
+ self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
54
+
55
+ @torch.no_grad()
56
+ def sample(self,
57
+ S,
58
+ batch_size,
59
+ shape,
60
+ conditioning=None,
61
+ callback=None,
62
+ img_callback=None,
63
+ quantize_x0=False,
64
+ eta=0.,
65
+ mask=None,
66
+ x0=None,
67
+ temperature=1.,
68
+ noise_dropout=0.,
69
+ score_corrector=None,
70
+ corrector_kwargs=None,
71
+ verbose=True,
72
+ schedule_verbose=False,
73
+ x_T=None,
74
+ log_every_t=100,
75
+ unconditional_guidance_scale=1.,
76
+ unconditional_conditioning=None,
77
+ postprocess_fn=None,
78
+ sample_noise=None,
79
+ cond_fn=None,
80
+ # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
81
+ **kwargs
82
+ ):
83
+
84
+ # check condition bs
85
+ if conditioning is not None:
86
+ if isinstance(conditioning, dict):
87
+ try:
88
+ cbs = conditioning[list(conditioning.keys())[0]].shape[0]
89
+ if cbs != batch_size:
90
+ print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
91
+ except:
92
+ # cbs = conditioning[list(conditioning.keys())[0]][0].shape[0]
93
+ pass
94
+ else:
95
+ if conditioning.shape[0] != batch_size:
96
+ print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
97
+
98
+ self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=schedule_verbose)
99
+
100
+ # make shape
101
+ if len(shape) == 3:
102
+ C, H, W = shape
103
+ size = (batch_size, C, H, W)
104
+ elif len(shape) == 4:
105
+ C, T, H, W = shape
106
+ size = (batch_size, C, T, H, W)
107
+
108
+ samples, intermediates = self.ddim_sampling(conditioning, size,
109
+ callback=callback,
110
+ img_callback=img_callback,
111
+ quantize_denoised=quantize_x0,
112
+ mask=mask, x0=x0,
113
+ ddim_use_original_steps=False,
114
+ noise_dropout=noise_dropout,
115
+ temperature=temperature,
116
+ score_corrector=score_corrector,
117
+ corrector_kwargs=corrector_kwargs,
118
+ x_T=x_T,
119
+ log_every_t=log_every_t,
120
+ unconditional_guidance_scale=unconditional_guidance_scale,
121
+ unconditional_conditioning=unconditional_conditioning,
122
+ postprocess_fn=postprocess_fn,
123
+ sample_noise=sample_noise,
124
+ cond_fn=cond_fn,
125
+ verbose=verbose,
126
+ **kwargs
127
+ )
128
+ return samples, intermediates
129
+
130
+ @torch.no_grad()
131
+ def ddim_sampling(self, cond, shape,
132
+ x_T=None, ddim_use_original_steps=False,
133
+ callback=None, timesteps=None, quantize_denoised=False,
134
+ mask=None, x0=None, img_callback=None, log_every_t=100,
135
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
136
+ unconditional_guidance_scale=1., unconditional_conditioning=None,
137
+ postprocess_fn=None,sample_noise=None,cond_fn=None,
138
+ uc_type=None, verbose=True, **kwargs,
139
+ ):
140
+
141
+ device = self.model.betas.device
142
+
143
+ b = shape[0]
144
+ if x_T is None:
145
+ img = torch.randn(shape, device=device)
146
+ else:
147
+ img = x_T
148
+
149
+ if timesteps is None:
150
+ timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
151
+ elif timesteps is not None and not ddim_use_original_steps:
152
+ subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
153
+ timesteps = self.ddim_timesteps[:subset_end]
154
+ intermediates = {'x_inter': [img], 'pred_x0': [img]}
155
+ time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
156
+ total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
157
+ if verbose:
158
+ iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
159
+ else:
160
+ iterator = time_range
161
+
162
+ for i, step in enumerate(iterator):
163
+ index = total_steps - i - 1
164
+ ts = torch.full((b,), step, device=device, dtype=torch.long)
165
+
166
+ if postprocess_fn is not None:
167
+ img = postprocess_fn(img, ts)
168
+
169
+ outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
170
+ quantize_denoised=quantize_denoised, temperature=temperature,
171
+ noise_dropout=noise_dropout, score_corrector=score_corrector,
172
+ corrector_kwargs=corrector_kwargs,
173
+ unconditional_guidance_scale=unconditional_guidance_scale,
174
+ unconditional_conditioning=unconditional_conditioning,
175
+ sample_noise=sample_noise,cond_fn=cond_fn,uc_type=uc_type, **kwargs,)
176
+ img, pred_x0 = outs
177
+
178
+ if mask is not None:
179
+ # use mask to blend x_known_t-1 & x_sample_t-1
180
+ assert x0 is not None
181
+ x0 = x0.to(img.device)
182
+ mask = mask.to(img.device)
183
+ t = torch.tensor([step-1]*x0.shape[0], dtype=torch.long, device=img.device)
184
+ img_known = self.model.q_sample(x0, t)
185
+ img = img_known * mask + (1. - mask) * img
186
+
187
+ if callback: callback(i)
188
+ if img_callback: img_callback(pred_x0, i)
189
+
190
+ if index % log_every_t == 0 or index == total_steps - 1:
191
+ intermediates['x_inter'].append(img)
192
+ intermediates['pred_x0'].append(pred_x0)
193
+
194
+ return img, intermediates
195
+
196
+ @torch.no_grad()
197
+ def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
198
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
199
+ unconditional_guidance_scale=1., unconditional_conditioning=None, sample_noise=None,
200
+ cond_fn=None,uc_type=None, model_kwargs={},
201
+ **kwargs,
202
+ ):
203
+ b, *_, device = *x.shape, x.device
204
+ if x.dim() == 5:
205
+ is_video = True
206
+ else:
207
+ is_video = False
208
+ if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
209
+ e_t = self.model.apply_model(x, t, c, **model_kwargs) # unet denoiser
210
+ else:
211
+ # with unconditional condition
212
+ if isinstance(c, torch.Tensor):
213
+ e_t = self.model.apply_model(x, t, c, **model_kwargs)
214
+ e_t_uncond = self.model.apply_model(x, t, unconditional_conditioning, **model_kwargs)
215
+ elif isinstance(c, dict):
216
+ e_t = self.model.apply_model(x, t, c, **model_kwargs)
217
+ e_t_uncond = self.model.apply_model(x, t, unconditional_conditioning, **model_kwargs)
218
+ else:
219
+ raise NotImplementedError
220
+ # text cfg
221
+ if uc_type is None:
222
+ e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)
223
+ else:
224
+ if uc_type == 'cfg_original':
225
+ e_t = e_t + unconditional_guidance_scale * (e_t - e_t_uncond)
226
+ elif uc_type == 'cfg_ours':
227
+ e_t = e_t + unconditional_guidance_scale * (e_t_uncond - e_t)
228
+ else:
229
+ raise NotImplementedError
230
+
231
+ if score_corrector is not None:
232
+ assert self.model.parameterization == "eps"
233
+ e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
234
+
235
+ alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
236
+ alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
237
+ sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
238
+ sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
239
+ # select parameters corresponding to the currently considered timestep
240
+
241
+ if is_video:
242
+ size = (b, 1, 1, 1, 1)
243
+ else:
244
+ size = (b, 1, 1, 1)
245
+ a_t = torch.full(size, alphas[index], device=device)
246
+ a_prev = torch.full(size, alphas_prev[index], device=device)
247
+ sigma_t = torch.full(size, sigmas[index], device=device)
248
+ sqrt_one_minus_at = torch.full(size, sqrt_one_minus_alphas[index],device=device)
249
+
250
+ # current prediction for x_0
251
+ pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
252
+ # print(f't={t}, pred_x0, min={torch.min(pred_x0)}, max={torch.max(pred_x0)}',file=f)
253
+ if quantize_denoised:
254
+ pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
255
+ # direction pointing to x_t
256
+ dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
257
+
258
+ if sample_noise is None:
259
+ noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
260
+ if noise_dropout > 0.:
261
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
262
+ else:
263
+ noise = sigma_t * sample_noise * temperature
264
+
265
+ x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
266
+
267
+ return x_prev, pred_x0
lvdm/utils/common_utils.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import importlib
3
+
4
+ import torch
5
+ import numpy as np
6
+
7
+ from inspect import isfunction
8
+ from PIL import Image, ImageDraw, ImageFont
9
+
10
+
11
+ def str2bool(v):
12
+ if isinstance(v, bool):
13
+ return v
14
+ if v.lower() in ('yes', 'true', 't', 'y', '1'):
15
+ return True
16
+ elif v.lower() in ('no', 'false', 'f', 'n', '0'):
17
+ return False
18
+ else:
19
+ raise ValueError('Boolean value expected.')
20
+
21
+
22
+ def instantiate_from_config(config):
23
+ if not "target" in config:
24
+ if config == '__is_first_stage__':
25
+ return None
26
+ elif config == "__is_unconditional__":
27
+ return None
28
+ raise KeyError("Expected key `target` to instantiate.")
29
+
30
+ return get_obj_from_str(config["target"])(**config.get("params", dict()))
31
+
32
+ def get_obj_from_str(string, reload=False):
33
+ module, cls = string.rsplit(".", 1)
34
+ if reload:
35
+ module_imp = importlib.import_module(module)
36
+ importlib.reload(module_imp)
37
+ return getattr(importlib.import_module(module, package=None), cls)
38
+
39
+ def log_txt_as_img(wh, xc, size=10):
40
+ # wh a tuple of (width, height)
41
+ # xc a list of captions to plot
42
+ b = len(xc)
43
+ txts = list()
44
+ for bi in range(b):
45
+ txt = Image.new("RGB", wh, color="white")
46
+ draw = ImageDraw.Draw(txt)
47
+ font = ImageFont.truetype('data/DejaVuSans.ttf', size=size)
48
+ nc = int(40 * (wh[0] / 256))
49
+ lines = "\n".join(xc[bi][start:start + nc] for start in range(0, len(xc[bi]), nc))
50
+
51
+ try:
52
+ draw.text((0, 0), lines, fill="black", font=font)
53
+ except UnicodeEncodeError:
54
+ print("Cant encode string for logging. Skipping.")
55
+
56
+ txt = np.array(txt).transpose(2, 0, 1) / 127.5 - 1.0
57
+ txts.append(txt)
58
+ txts = np.stack(txts)
59
+ txts = torch.tensor(txts)
60
+ return txts
61
+
62
+
63
+ def ismap(x):
64
+ if not isinstance(x, torch.Tensor):
65
+ return False
66
+ return (len(x.shape) == 4) and (x.shape[1] > 3)
67
+
68
+
69
+ def isimage(x):
70
+ if not isinstance(x,torch.Tensor):
71
+ return False
72
+ return (len(x.shape) == 4) and (x.shape[1] == 3 or x.shape[1] == 1)
73
+
74
+
75
+ def exists(x):
76
+ return x is not None
77
+
78
+
79
+ def default(val, d):
80
+ if exists(val):
81
+ return val
82
+ return d() if isfunction(d) else d
83
+
84
+
85
+ def mean_flat(tensor):
86
+ """
87
+ https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86
88
+ Take the mean over all non-batch dimensions.
89
+ """
90
+ return tensor.mean(dim=list(range(1, len(tensor.shape))))
91
+
92
+
93
+ def count_params(model, verbose=False):
94
+ total_params = sum(p.numel() for p in model.parameters())
95
+ if verbose:
96
+ print(f"{model.__class__.__name__} has {total_params*1.e-6:.2f} M params.")
97
+ return total_params
98
+
99
+
100
+ def instantiate_from_config(config):
101
+ if not "target" in config:
102
+ if config == '__is_first_stage__':
103
+ return None
104
+ elif config == "__is_unconditional__":
105
+ return None
106
+ raise KeyError("Expected key `target` to instantiate.")
107
+
108
+ if "instantiate_with_dict" in config and config["instantiate_with_dict"]:
109
+ # input parameter is one dict
110
+ return get_obj_from_str(config["target"])(config.get("params", dict()), **kwargs)
111
+ else:
112
+ return get_obj_from_str(config["target"])(**config.get("params", dict()))
113
+
114
+
115
+ def get_obj_from_str(string, reload=False):
116
+ module, cls = string.rsplit(".", 1)
117
+ if reload:
118
+ module_imp = importlib.import_module(module)
119
+ importlib.reload(module_imp)
120
+ return getattr(importlib.import_module(module, package=None), cls)
121
+
122
+
123
+ def check_istarget(name, para_list):
124
+ """
125
+ name: full name of source para
126
+ para_list: partial name of target para
127
+ """
128
+ istarget=False
129
+ for para in para_list:
130
+ if para in name:
131
+ return True
132
+ return istarget
lvdm/utils/dist_utils.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.distributed as dist
3
+
4
+ def setup_dist(local_rank):
5
+ if dist.is_initialized():
6
+ return
7
+ torch.cuda.set_device(local_rank)
8
+ torch.distributed.init_process_group(
9
+ 'nccl',
10
+ init_method='env://'
11
+ )
12
+
13
+ def gather_data(data, return_np=True):
14
+ ''' gather data from multiple processes to one list '''
15
+ data_list = [torch.zeros_like(data) for _ in range(dist.get_world_size())]
16
+ dist.all_gather(data_list, data) # gather not supported with NCCL
17
+ if return_np:
18
+ data_list = [data.cpu().numpy() for data in data_list]
19
+ return data_list
lvdm/utils/saving_utils.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2
3
+ import os
4
+ import time
5
+ import imageio
6
+ from tqdm import tqdm
7
+ from PIL import Image
8
+ import os
9
+ import sys
10
+ sys.path.insert(1, os.path.join(sys.path[0], '..'))
11
+ import torch
12
+ import torchvision
13
+ from torchvision.utils import make_grid
14
+ from torch import Tensor
15
+ from torchvision.transforms.functional import to_tensor
16
+
17
+ # ----------------------------------------------------------------------------------------------
18
+ def savenp2sheet(imgs, savepath, nrow=None):
19
+ """ save multiple imgs (in numpy array type) to a img sheet.
20
+ img sheet is one row.
21
+
22
+ imgs:
23
+ np array of size [N, H, W, 3] or List[array] with array size = [H,W,3]
24
+ """
25
+ if imgs.ndim == 4:
26
+ img_list = [imgs[i] for i in range(imgs.shape[0])]
27
+ imgs = img_list
28
+
29
+ imgs_new = []
30
+ for i, img in enumerate(imgs):
31
+ if img.ndim == 3 and img.shape[0] == 3:
32
+ img = np.transpose(img,(1,2,0))
33
+
34
+ assert(img.ndim == 3 and img.shape[-1] == 3), img.shape # h,w,3
35
+ img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
36
+ imgs_new.append(img)
37
+ n = len(imgs)
38
+ if nrow is not None:
39
+ n_cols = nrow
40
+ else:
41
+ n_cols=int(n**0.5)
42
+ n_rows=int(np.ceil(n/n_cols))
43
+ print(n_cols)
44
+ print(n_rows)
45
+
46
+ imgsheet = cv2.vconcat([cv2.hconcat(imgs_new[i*n_cols:(i+1)*n_cols]) for i in range(n_rows)])
47
+ cv2.imwrite(savepath, imgsheet)
48
+ print(f'saved in {savepath}')
49
+
50
+ # ----------------------------------------------------------------------------------------------
51
+ def save_np_to_img(img, path, norm=True):
52
+ if norm:
53
+ img = (img + 1) / 2 * 255
54
+ img = img.astype(np.uint8)
55
+ image = Image.fromarray(img)
56
+ image.save(path, q=95)
57
+
58
+ # ----------------------------------------------------------------------------------------------
59
+ def npz_to_imgsheet_5d(data_path, res_dir, nrow=None,):
60
+ if isinstance(data_path, str):
61
+ imgs = np.load(data_path)['arr_0'] # NTHWC
62
+ elif isinstance(data_path, np.ndarray):
63
+ imgs = data_path
64
+ else:
65
+ raise Exception
66
+
67
+ if os.path.isdir(res_dir):
68
+ res_path = os.path.join(res_dir, f'samples.jpg')
69
+ else:
70
+ assert(res_dir.endswith('.jpg'))
71
+ res_path = res_dir
72
+ imgs = np.concatenate([imgs[i] for i in range(imgs.shape[0])], axis=0)
73
+ savenp2sheet(imgs, res_path, nrow=nrow)
74
+
75
+ # ----------------------------------------------------------------------------------------------
76
+ def npz_to_imgsheet_4d(data_path, res_path, nrow=None,):
77
+ if isinstance(data_path, str):
78
+ imgs = np.load(data_path)['arr_0'] # NHWC
79
+ elif isinstance(data_path, np.ndarray):
80
+ imgs = data_path
81
+ else:
82
+ raise Exception
83
+ print(imgs.shape)
84
+ savenp2sheet(imgs, res_path, nrow=nrow)
85
+
86
+
87
+ # ----------------------------------------------------------------------------------------------
88
+ def tensor_to_imgsheet(tensor, save_path):
89
+ """
90
+ save a batch of videos in one image sheet with shape of [batch_size * num_frames].
91
+ data: [b,c,t,h,w]
92
+ """
93
+ assert(tensor.dim() == 5)
94
+ b,c,t,h,w = tensor.shape
95
+ imgs = [tensor[bi,:,ti, :, :] for bi in range(b) for ti in range(t)]
96
+ torchvision.utils.save_image(imgs, save_path, normalize=True, nrow=t)
97
+
98
+
99
+ # ----------------------------------------------------------------------------------------------
100
+ def npz_to_frames(data_path, res_dir, norm, num_frames=None, num_samples=None):
101
+ start = time.time()
102
+ arr = np.load(data_path)
103
+ imgs = arr['arr_0'] # [N, T, H, W, 3]
104
+ print('original data shape: ', imgs.shape)
105
+
106
+ if num_samples is not None:
107
+ imgs = imgs[:num_samples, :, :, :, :]
108
+ print('after sample selection: ', imgs.shape)
109
+
110
+ if num_frames is not None:
111
+ imgs = imgs[:, :num_frames, :, :, :]
112
+ print('after frame selection: ', imgs.shape)
113
+
114
+ for vid in tqdm(range(imgs.shape[0]), desc='Video'):
115
+ video_dir = os.path.join(res_dir, f'video{vid:04d}')
116
+ os.makedirs(video_dir, exist_ok=True)
117
+ for fid in range(imgs.shape[1]):
118
+ frame = imgs[vid, fid, :, :, :] #HW3
119
+ save_np_to_img(frame, os.path.join(video_dir, f'frame{fid:04d}.jpg'), norm=norm)
120
+ print('Finish')
121
+ print(f'Total time = {time.time()- start}')
122
+
123
+ # ----------------------------------------------------------------------------------------------
124
+ def npz_to_gifs(data_path, res_dir, duration=0.2, start_idx=0, num_videos=None, mode='gif'):
125
+ os.makedirs(res_dir, exist_ok=True)
126
+ if isinstance(data_path, str):
127
+ imgs = np.load(data_path)['arr_0'] # NTHWC
128
+ elif isinstance(data_path, np.ndarray):
129
+ imgs = data_path
130
+ else:
131
+ raise Exception
132
+
133
+ for i in range(imgs.shape[0]):
134
+ frames = [imgs[i,j,:,:,:] for j in range(imgs[i].shape[0])] # [(h,w,3)]
135
+ if mode == 'gif':
136
+ imageio.mimwrite(os.path.join(res_dir, f'samples_{start_idx+i}.gif'), frames, format='GIF', duration=duration)
137
+ elif mode == 'mp4':
138
+ frames = [torch.from_numpy(frame) for frame in frames]
139
+ frames = torch.stack(frames, dim=0).to(torch.uint8) # [T, H, W, C]
140
+ torchvision.io.write_video(os.path.join(res_dir, f'samples_{start_idx+i}.mp4'),
141
+ frames, fps=0.5, video_codec='h264', options={'crf': '10'})
142
+ if i+ 1 == num_videos:
143
+ break
144
+
145
+ # ----------------------------------------------------------------------------------------------
146
+ def fill_with_black_squares(video, desired_len: int) -> Tensor:
147
+ if len(video) >= desired_len:
148
+ return video
149
+
150
+ return torch.cat([
151
+ video,
152
+ torch.zeros_like(video[0]).unsqueeze(0).repeat(desired_len - len(video), 1, 1, 1),
153
+ ], dim=0)
154
+
155
+ # ----------------------------------------------------------------------------------------------
156
+ def load_num_videos(data_path, num_videos):
157
+ # data_path can be either data_path of np array
158
+ if isinstance(data_path, str):
159
+ videos = np.load(data_path)['arr_0'] # NTHWC
160
+ elif isinstance(data_path, np.ndarray):
161
+ videos = data_path
162
+ else:
163
+ raise Exception
164
+
165
+ if num_videos is not None:
166
+ videos = videos[:num_videos, :, :, :, :]
167
+ return videos
168
+
169
+ # ----------------------------------------------------------------------------------------------
170
+ def npz_to_video_grid(data_path, out_path, num_frames=None, fps=8, num_videos=None, nrow=None, verbose=True):
171
+ if isinstance(data_path, str):
172
+ videos = load_num_videos(data_path, num_videos)
173
+ elif isinstance(data_path, np.ndarray):
174
+ videos = data_path
175
+ else:
176
+ raise Exception
177
+ n,t,h,w,c = videos.shape
178
+
179
+ videos_th = []
180
+ for i in range(n):
181
+ video = videos[i, :,:,:,:]
182
+ images = [video[j, :,:,:] for j in range(t)]
183
+ images = [to_tensor(img) for img in images]
184
+ video = torch.stack(images)
185
+ videos_th.append(video)
186
+
187
+ if num_frames is None:
188
+ num_frames = videos.shape[1]
189
+ if verbose:
190
+ videos = [fill_with_black_squares(v, num_frames) for v in tqdm(videos_th, desc='Adding empty frames')] # NTCHW
191
+ else:
192
+ videos = [fill_with_black_squares(v, num_frames) for v in videos_th] # NTCHW
193
+
194
+ frame_grids = torch.stack(videos).permute(1, 0, 2, 3, 4) # [T, N, C, H, W]
195
+ if nrow is None:
196
+ nrow = int(np.ceil(np.sqrt(n)))
197
+ if verbose:
198
+ frame_grids = [make_grid(fs, nrow=nrow) for fs in tqdm(frame_grids, desc='Making grids')]
199
+ else:
200
+ frame_grids = [make_grid(fs, nrow=nrow) for fs in frame_grids]
201
+
202
+ if os.path.dirname(out_path) != "":
203
+ os.makedirs(os.path.dirname(out_path), exist_ok=True)
204
+ frame_grids = (torch.stack(frame_grids) * 255).to(torch.uint8).permute(0, 2, 3, 1) # [T, H, W, C]
205
+ torchvision.io.write_video(out_path, frame_grids, fps=fps, video_codec='h264', options={'crf': '10'})
206
+
207
+ # ----------------------------------------------------------------------------------------------
208
+ def npz_to_gif_grid(data_path, out_path, n_cols=None, num_videos=20):
209
+ arr = np.load(data_path)
210
+ imgs = arr['arr_0'] # [N, T, H, W, 3]
211
+ imgs = imgs[:num_videos]
212
+ n, t, h, w, c = imgs.shape
213
+ assert(n == num_videos)
214
+ n_cols = n_cols if n_cols else imgs.shape[0]
215
+ n_rows = np.ceil(imgs.shape[0] / n_cols).astype(np.int8)
216
+ H, W = h * n_rows, w * n_cols
217
+ grid = np.zeros((t, H, W, c), dtype=np.uint8)
218
+
219
+ for i in range(n_rows):
220
+ for j in range(n_cols):
221
+ if i*n_cols+j < imgs.shape[0]:
222
+ grid[:, i*h:(i+1)*h, j*w:(j+1)*w, :] = imgs[i*n_cols+j, :, :, :, :]
223
+
224
+ videos = [grid[i] for i in range(grid.shape[0])] # grid: TH'W'C
225
+ imageio.mimwrite(out_path, videos, format='GIF', duration=0.5,palettesize=256)
226
+
227
+
228
+ # ----------------------------------------------------------------------------------------------
229
+ def torch_to_video_grid(videos, out_path, num_frames, fps, num_videos=None, nrow=None, verbose=True):
230
+ """
231
+ videos: -1 ~ 1, torch.Tensor, BCTHW
232
+ """
233
+ n,t,h,w,c = videos.shape
234
+ videos_th = [videos[i, ...] for i in range(n)]
235
+ if verbose:
236
+ videos = [fill_with_black_squares(v, num_frames) for v in tqdm(videos_th, desc='Adding empty frames')] # NTCHW
237
+ else:
238
+ videos = [fill_with_black_squares(v, num_frames) for v in videos_th] # NTCHW
239
+
240
+ frame_grids = torch.stack(videos).permute(1, 0, 2, 3, 4) # [T, N, C, H, W]
241
+ if nrow is None:
242
+ nrow = int(np.ceil(np.sqrt(n)))
243
+ if verbose:
244
+ frame_grids = [make_grid(fs, nrow=nrow) for fs in tqdm(frame_grids, desc='Making grids')]
245
+ else:
246
+ frame_grids = [make_grid(fs, nrow=nrow) for fs in frame_grids]
247
+
248
+ if os.path.dirname(out_path) != "":
249
+ os.makedirs(os.path.dirname(out_path), exist_ok=True)
250
+ frame_grids = ((torch.stack(frame_grids) + 1) / 2 * 255).to(torch.uint8).permute(0, 2, 3, 1) # [T, H, W, C]
251
+ torchvision.io.write_video(out_path, frame_grids, fps=fps, video_codec='h264', options={'crf': '10'})