liuhuohuo commited on
Commit
5af269e
1 Parent(s): e1c5899
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. app.py +211 -0
  2. configs/inference_image_512_512.yaml +118 -0
  3. configs/inference_video_320_512.yaml +122 -0
  4. eval_data/3d_1.png +0 -0
  5. eval_data/anime_1.jpg +0 -0
  6. eval_data/craft_1.jpg +0 -0
  7. eval_data/craft_2.png +0 -0
  8. eval_data/digital_art_2.jpeg +0 -0
  9. eval_data/icon_1.png +0 -0
  10. eval_data/ink_2.jpeg +0 -0
  11. eval_data/oil_paint_2.jpg +0 -0
  12. header.html +36 -0
  13. lvdm/__pycache__/basics.cpython-39.pyc +0 -0
  14. lvdm/__pycache__/common.cpython-39.pyc +0 -0
  15. lvdm/__pycache__/distributions.cpython-39.pyc +0 -0
  16. lvdm/__pycache__/ema.cpython-39.pyc +0 -0
  17. lvdm/basics.py +100 -0
  18. lvdm/common.py +95 -0
  19. lvdm/distributions.py +95 -0
  20. lvdm/ema.py +76 -0
  21. lvdm/models/__pycache__/autoencoder.cpython-39.pyc +0 -0
  22. lvdm/models/__pycache__/ddpm3d.cpython-39.pyc +0 -0
  23. lvdm/models/__pycache__/ddpm3d_cond.cpython-39.pyc +0 -0
  24. lvdm/models/__pycache__/utils_diffusion.cpython-39.pyc +0 -0
  25. lvdm/models/autoencoder.py +219 -0
  26. lvdm/models/ddpm3d.py +781 -0
  27. lvdm/models/ddpm3d_cond.py +141 -0
  28. lvdm/models/samplers/__pycache__/ddim.cpython-39.pyc +0 -0
  29. lvdm/models/samplers/ddim.py +420 -0
  30. lvdm/models/utils_diffusion.py +104 -0
  31. lvdm/modules/__pycache__/attention.cpython-39.pyc +0 -0
  32. lvdm/modules/attention.py +851 -0
  33. lvdm/modules/encoders/__pycache__/adapter.cpython-39.pyc +0 -0
  34. lvdm/modules/encoders/__pycache__/arch_transformer.cpython-39.pyc +0 -0
  35. lvdm/modules/encoders/__pycache__/condition.cpython-39.pyc +0 -0
  36. lvdm/modules/encoders/__pycache__/condition2.cpython-39.pyc +0 -0
  37. lvdm/modules/encoders/__pycache__/ip_resampler.cpython-39.pyc +0 -0
  38. lvdm/modules/encoders/__pycache__/transformers.cpython-39.pyc +0 -0
  39. lvdm/modules/encoders/adapter.py +190 -0
  40. lvdm/modules/encoders/arch_transformer.py +252 -0
  41. lvdm/modules/encoders/condition.py +461 -0
  42. lvdm/modules/encoders/ip_resampler.py +136 -0
  43. lvdm/modules/networks/__pycache__/ae_modules.cpython-39.pyc +0 -0
  44. lvdm/modules/networks/__pycache__/openaimodel3d.cpython-39.pyc +0 -0
  45. lvdm/modules/networks/ae_modules.py +845 -0
  46. lvdm/modules/networks/openaimodel3d.py +641 -0
  47. lvdm/modules/x_transformer.py +640 -0
  48. scripts/evaluation/__pycache__/style_inference.cpython-39.pyc +0 -0
  49. scripts/evaluation/ddp_wrapper.py +48 -0
  50. scripts/evaluation/funcs.py +237 -0
app.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import sys
4
+ import argparse
5
+ import random
6
+ import time
7
+ from omegaconf import OmegaConf
8
+ import torch
9
+ import torchvision
10
+ from pytorch_lightning import seed_everything
11
+ from huggingface_hub import hf_hub_download
12
+ from einops import repeat
13
+ import torchvision.transforms as transforms
14
+ from torchvision.utils import make_grid
15
+ from utils.utils import instantiate_from_config
16
+
17
+ from collections import OrderedDict
18
+
19
+ sys.path.insert(0, "scripts/evaluation")
20
+ from lvdm.models.samplers.ddim import DDIMSampler, DDIMStyleSampler
21
+
22
+
23
+ def load_model_checkpoint(model, ckpt):
24
+ state_dict = torch.load(ckpt, map_location="cpu")
25
+ if "state_dict" in list(state_dict.keys()):
26
+ state_dict = state_dict["state_dict"]
27
+ else:
28
+ # deepspeed
29
+ state_dict = OrderedDict()
30
+ for key in state_dict['module'].keys():
31
+ state_dict[key[16:]]=state_dict['module'][key]
32
+
33
+ model.load_state_dict(state_dict, strict=False)
34
+ print('>>> model checkpoint loaded.')
35
+ return model
36
+
37
+
38
+ def download_model():
39
+ REPO_ID = 'VideoCrafter/Text2Video-512'
40
+ filename_list = ['model.ckpt']
41
+ os.makedirs('./checkpoints/videocrafter_t2v_320_512/', exist_ok=True)
42
+ for filename in filename_list:
43
+ local_file = os.path.join('./checkpoints/videocrafter_t2v_320_512/', filename)
44
+ if not os.path.exists(local_file):
45
+ hf_hub_download(repo_id=REPO_ID, filename=filename, local_dir='./checkpoints/videocrafter_t2v_320_512/', force_download=True)
46
+
47
+ REPO_ID = 'liuhuohuo/StyleCrafter'
48
+ filename_list = ['adapter_v1.pth', 'temporal_v1.pth']
49
+ os.makedirs('./checkpoints/stylecrafter', exist_ok=True)
50
+ for filename in filename_list:
51
+ local_file = os.path.join('./checkpoints/stylecrafter', filename)
52
+ if not os.path.exists(local_file):
53
+ hf_hub_download(repo_id=REPO_ID, filename=filename, local_dir='./checkpoints/stylecrafter', force_download=True)
54
+
55
+
56
+ def infer(image, prompt, infer_type='image', seed=123, style_strength=1.0, steps=50):
57
+ download_model()
58
+ ckpt_path = 'checkpoints/videocrafter_t2v_320_512/model.ckpt'
59
+ adapter_ckpt_path = 'checkpoints/stylecrafter/adapter_v1.pth'
60
+ temporal_ckpt_path = 'checkpoints/stylecrafter/temporal_v1.pth'
61
+ if infer_type == 'image':
62
+ config_file='configs/inference_image_512_512.yaml'
63
+ h, w = 512 // 8, 512 // 8
64
+ unconditional_guidance_scale = 7.5
65
+ unconditional_guidance_scale_style = None
66
+ else:
67
+ config_file='configs/inference_video_320_512.yaml'
68
+ h, w = 320 // 8, 512 // 8
69
+ unconditional_guidance_scale = 15.0
70
+ unconditional_guidance_scale_style = 7.5
71
+
72
+ config = OmegaConf.load(config_file)
73
+ model_config = config.pop("model", OmegaConf.create())
74
+ model_config['params']['adapter_config']['params']['scale'] = style_strength
75
+
76
+
77
+ model = instantiate_from_config(model_config)
78
+ model = model.cuda()
79
+
80
+ # load ckpt
81
+ assert os.path.exists(ckpt_path), "Error: checkpoint Not Found!"
82
+ assert os.path.exists(adapter_ckpt_path), "Error: adapter checkpoint Not Found!"
83
+ assert os.path.exists(temporal_ckpt_path), "Error: temporal checkpoint Not Found!"
84
+ model = load_model_checkpoint(model, ckpt_path)
85
+ model.load_pretrained_adapter(adapter_ckpt_path)
86
+ if infer_type == 'video':
87
+ model.load_pretrained_temporal(temporal_ckpt_path)
88
+ model.eval()
89
+
90
+
91
+ seed_everything(seed)
92
+
93
+ batch_size=1
94
+ channels = model.channels
95
+ frames = model.temporal_length if infer_type == 'video' else 1
96
+ noise_shape = [batch_size, channels, frames, h, w]
97
+
98
+ # text cond
99
+ cond = model.get_learned_conditioning([prompt])
100
+ neg_prompt = batch_size * [""]
101
+ uc = model.get_learned_conditioning(neg_prompt)
102
+
103
+ # style cond
104
+ style_transforms = torchvision.transforms.Compose([
105
+ torchvision.transforms.Resize(512),
106
+ torchvision.transforms.CenterCrop(512),
107
+ torchvision.transforms.ToTensor(),
108
+ torchvision.transforms.Lambda(lambda x: x * 2. - 1.),
109
+ ])
110
+
111
+ style_img = style_transforms(image).unsqueeze(0).cuda()
112
+ style_cond = model.get_batch_style(style_img)
113
+ append_to_context = model.adapter(style_cond)
114
+
115
+ scale_scalar = model.adapter.scale_predictor(torch.concat([append_to_context, cond], dim=1))
116
+
117
+ ddim_sampler = DDIMSampler(model) if infer_type == 'image' else DDIMStyleSampler(model)
118
+
119
+ samples, _ = ddim_sampler.sample(S=steps,
120
+ conditioning=cond,
121
+ batch_size=noise_shape[0],
122
+ shape=noise_shape[1:],
123
+ verbose=False,
124
+ unconditional_guidance_scale=unconditional_guidance_scale,
125
+ unconditional_guidance_scale_style=unconditional_guidance_scale_style,
126
+ unconditional_conditioning=uc,
127
+ eta=1.0,
128
+ temporal_length=noise_shape[2],
129
+ append_to_context=append_to_context,
130
+ scale_scalar=scale_scalar
131
+ )
132
+ samples = model.decode_first_stage(samples)
133
+
134
+ if infer_type == 'image':
135
+ samples = samples[:, :, 0, :, :].detach().cpu()
136
+ out_path = "./output.png"
137
+ torchvision.utils.save_image(samples, out_path, nrow=1, normalize=True, range=(-1, 1))
138
+
139
+ elif infer_type == 'video':
140
+ samples = samples.detach().cpu()
141
+ out_path = "./output.mp4"
142
+ video = torch.clamp(samples, -1, 1)
143
+ video = video.permute(2, 0, 1, 3, 4) # [T, B, C, H, W]
144
+ frame_grids = [torchvision.utils.make_grid(video[t], nrow=1) for t in range(video.shape[0])]
145
+ grid = torch.stack(frame_grids, dim=0)
146
+ grid = (grid + 1.0) / 2.0
147
+ grid = (grid * 255).permute(0, 2, 3, 1).numpy().astype('uint8')
148
+ torchvision.io.write_video(out_path, grid, fps=8, video_codec='h264', options={'crf': '10'})
149
+
150
+
151
+ return out_path
152
+
153
+
154
+ def read_content(file_path: str) -> str:
155
+ """read the content of target file
156
+ """
157
+ with open(file_path, 'r', encoding='utf-8') as f:
158
+ content = f.read()
159
+
160
+ return content
161
+
162
+
163
+ demo_exaples = [
164
+ ['eval_data/3d_1.png', 'A bouquet of flowers in a vase.', 'image', 123, 1.0, 50],
165
+ ['eval_data/craft_1.png', 'A modern cityscape with towering skyscrapers.', 'image', 124, 1.0, 50],
166
+ ['eval_data/digital_art_2.jpeg', 'A lighthouse standing tall on a rocky coast.', 'image', 123, 1.0, 50],
167
+ ['eval_data/oil_paint_2.jpg', 'A man playing the guitar on a city street.', 'image', 123, 1.0, 50],
168
+ ['eval_data/craft_2.jpg', 'City street at night with bright lights and busy traffic.', 'video', 123, 1.0, 50],
169
+ ['eval_data/anime_1.jpg', 'A field of sunflowers on a sunny day.', 'video', 123, 1.0, 50],
170
+ ['eval_data/ink_2.jpeg', 'A knight riding a horse through a field.', 'video', 123, 1.0, 50],
171
+ ['eval_data/oil_paint_2.jpg', 'A street performer playing the guitar.', 'video', 121, 1.0, 50],
172
+ ['eval_data/icon_1.png', 'A campfire surrounded by tents.', 'video', 123, 1.0, 50],
173
+ ]
174
+ css = """
175
+ #input_img {max-height: 512px}
176
+ #output_vid {max-width: 512px;}
177
+ """
178
+
179
+ with gr.Blocks(analytics_enabled=False, css=css) as demo_iface:
180
+ gr.HTML(read_content("header.html"))
181
+
182
+ with gr.Tab(label='Stylized Generation'):
183
+ with gr.Column():
184
+ with gr.Row():
185
+ with gr.Column():
186
+ with gr.Row():
187
+ input_style_ref = gr.Image(label="Style Reference",elem_id="input_img")
188
+ with gr.Row():
189
+ input_prompt = gr.Text(label='Prompts')
190
+ with gr.Row():
191
+ input_seed = gr.Slider(label='Random Seed', minimum=0, maximum=10000, step=1, value=123)
192
+ input_style_strength = gr.Slider(minimum=0.0, maximum=2.0, step=0.01, label='Style Strength', value=1.0)
193
+ with gr.Row():
194
+ input_step = gr.Slider(minimum=1, maximum=75, step=1, elem_id="i2v_steps", label="Sampling steps", value=50)
195
+ input_type = gr.Radio(choices=["image", "video"], label="Generation Type", value="image")
196
+ input_end_btn = gr.Button("Generate")
197
+ # with gr.Tab(label='Result'):
198
+ with gr.Row():
199
+ output_result = gr.Video(label="Generated Results",elem_id="output_vid",autoplay=True,show_share_button=True)
200
+
201
+ gr.Examples(examples=demo_exaples,
202
+ inputs=[input_style_ref, input_prompt, input_type, input_seed, input_style_strength, input_step],
203
+ outputs=[output_result],
204
+ fn = infer,
205
+ )
206
+ input_end_btn.click(inputs=[input_style_ref, input_prompt, input_type, input_seed, input_style_strength, input_step],
207
+ outputs=[output_result],
208
+ fn = infer
209
+ )
210
+
211
+ demo_iface.queue(max_size=12).launch(show_api=True)
configs/inference_image_512_512.yaml ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ target: lvdm.models.ddpm3d_cond.T2IAdapterStyleAS
3
+ params:
4
+ linear_start: 0.00085
5
+ linear_end: 0.012
6
+ num_timesteps_cond: 1
7
+ log_every_t: 200
8
+ timesteps: 1000
9
+ first_stage_key: video
10
+ cond_stage_key: caption
11
+ cond_stage_trainable: false
12
+ conditioning_key: crossattn
13
+ image_size: [64, 64]
14
+ channels: 4
15
+ #monitor: val/loss_simple
16
+ scale_by_std: false
17
+ scale_factor: 0.18215
18
+ # training related
19
+ use_ema: false
20
+ uncond_prob: 0.0
21
+ uncond_type: 'empty_seq'
22
+ scheduler_config:
23
+ target: utils.lr_scheduler.LambdaLRScheduler
24
+ interval: 'step'
25
+ frequency: 100
26
+ params:
27
+ start_step: 0
28
+ final_decay_ratio: 0.01
29
+ decay_steps: 20000
30
+
31
+ unet_config:
32
+ target: lvdm.modules.networks.openaimodel3d.UNet2DModel
33
+ params:
34
+ in_channels: 4
35
+ out_channels: 4
36
+ model_channels: 320
37
+ attention_resolutions: [4, 2, 1]
38
+ num_res_blocks: 2
39
+ channel_mult: [1, 2, 4, 4]
40
+ #num_heads: 8
41
+ num_head_channels: 64 # need to fix for flash-attn
42
+ transformer_depth: 1
43
+ context_dim: 1024
44
+ use_linear: true
45
+ use_checkpoint: true
46
+ temporal_conv: false
47
+ temporal_attention: true
48
+ temporal_selfatt_only: true
49
+ use_relative_position: true
50
+ use_causal_attention: false
51
+ temporal_length: 16
52
+ addition_attention: true
53
+
54
+ first_stage_config:
55
+ target: lvdm.models.autoencoder.AutoencoderKL
56
+ params:
57
+ embed_dim: 4
58
+ monitor: val/rec_loss
59
+ ddconfig:
60
+ double_z: true
61
+ z_channels: 4
62
+ resolution: 256
63
+ in_channels: 3
64
+ out_ch: 3
65
+ ch: 128
66
+ ch_mult: [1, 2, 4, 4]
67
+ num_res_blocks: 2
68
+ attn_resolutions: []
69
+ dropout: 0.0
70
+ lossconfig:
71
+ target: torch.nn.Identity
72
+
73
+ cond_stage_config:
74
+ target: lvdm.modules.encoders.condition.FrozenOpenCLIPEmbedder
75
+ params:
76
+ freeze: true
77
+ layer: "penultimate"
78
+ # version: checkpoints/open_clip/CLIP-ViT-H-14-laion2B-s32B-b79K/open_clip_pytorch_model.bin
79
+
80
+ style_stage_config:
81
+ target: lvdm.modules.encoders.condition.FrozenOpenCLIPImageEmbedder
82
+ params:
83
+ # version: checkpoints/open_clip/CLIP-ViT-H-14-laion2B-s32B-b79K/open_clip_pytorch_model.bin
84
+ freeze: true
85
+ only_cls: false
86
+ use_proj: false
87
+ use_shuffle: false
88
+ mask_ratio: 0.0
89
+
90
+ adapter_config:
91
+ target: lvdm.modules.encoders.adapter.StyleAdapterDualAttnAS
92
+ cond_name: style
93
+ trainable: true
94
+ params:
95
+ scale: 1.0
96
+ use_norm: true
97
+ image_context_config:
98
+ target: lvdm.modules.encoders.adapter.StyleTransformer
99
+ params:
100
+ in_dim: 1280
101
+ out_dim: 1024
102
+ num_heads: 8
103
+ num_tokens: 8
104
+ n_layers: 3
105
+ scale_predictor_config:
106
+ target: lvdm.modules.encoders.adapter.ScaleEncoder
107
+ params:
108
+ in_dim: 1024
109
+ out_dim: 1
110
+ num_heads: 8
111
+ num_tokens: 16
112
+ n_layers: 2
113
+ # target: lvdm.modules.encoders.adapter.ImageContext
114
+ # params:
115
+ # width: 1024
116
+ # context_dim: 1024
117
+ # token_num: 4
118
+
configs/inference_video_320_512.yaml ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ target: lvdm.models.ddpm3d_cond.T2VFintoneStyleAS
3
+ params:
4
+ linear_start: 0.00085
5
+ linear_end: 0.012
6
+ num_timesteps_cond: 1
7
+ log_every_t: 200
8
+ timesteps: 1000
9
+ first_stage_key: video
10
+ cond_stage_key: caption
11
+ cond_stage_trainable: false
12
+ conditioning_key: crossattn
13
+ image_size: [64, 64]
14
+ channels: 4
15
+ #monitor: val/loss_simple
16
+ scale_by_std: false
17
+ scale_factor: 0.18215
18
+ # training related
19
+ use_ema: false
20
+ uncond_prob: 0.0
21
+ uncond_type: 'empty_seq'
22
+
23
+
24
+ scheduler_config:
25
+ target: utils.lr_scheduler.LambdaLRScheduler
26
+ interval: 'step'
27
+ frequency: 100
28
+ params:
29
+ start_step: 0
30
+ final_decay_ratio: 0.01
31
+ decay_steps: 20000
32
+
33
+ # train_strategy: 'video_only'
34
+
35
+ unet_config:
36
+ target: lvdm.modules.networks.openaimodel3d.UNetModel
37
+ params:
38
+ in_channels: 4
39
+ out_channels: 4
40
+ model_channels: 320
41
+ attention_resolutions: [4, 2, 1]
42
+ num_res_blocks: 2
43
+ channel_mult: [1, 2, 4, 4]
44
+ #num_heads: 8
45
+ num_head_channels: 64 # need to fix for flash-attn
46
+ transformer_depth: 1
47
+ context_dim: 1024
48
+ use_linear: true
49
+ use_checkpoint: true
50
+ temporal_conv: false
51
+ temporal_attention: true
52
+ temporal_selfatt_only: true
53
+ use_relative_position: true
54
+ use_causal_attention: false
55
+ temporal_length: 16
56
+ addition_attention: true
57
+
58
+ first_stage_config:
59
+ target: lvdm.models.autoencoder.AutoencoderKL
60
+ params:
61
+ embed_dim: 4
62
+ monitor: val/rec_loss
63
+ ddconfig:
64
+ double_z: true
65
+ z_channels: 4
66
+ resolution: 256
67
+ in_channels: 3
68
+ out_ch: 3
69
+ ch: 128
70
+ ch_mult: [1, 2, 4, 4]
71
+ num_res_blocks: 2
72
+ attn_resolutions: []
73
+ dropout: 0.0
74
+ lossconfig:
75
+ target: torch.nn.Identity
76
+
77
+ cond_stage_config:
78
+ target: lvdm.modules.encoders.condition.FrozenOpenCLIPEmbedder
79
+ params:
80
+ version: checkpoints/open_clip/CLIP-ViT-H-14-laion2B-s32B-b79K/open_clip_pytorch_model.bin
81
+ freeze: true
82
+ layer: "penultimate"
83
+
84
+ style_stage_config:
85
+ target: lvdm.modules.encoders.condition.FrozenOpenCLIPImageEmbedder
86
+ params:
87
+ version: checkpoints/open_clip/CLIP-ViT-H-14-laion2B-s32B-b79K/open_clip_pytorch_model.bin
88
+ freeze: true
89
+ only_cls: false
90
+ use_proj: false
91
+ use_shuffle: false
92
+ mask_ratio: 0.0
93
+
94
+ adapter_config:
95
+ target: lvdm.modules.encoders.adapter.StyleAdapterDualAttnAS
96
+ cond_name: style
97
+ trainable: true
98
+ params:
99
+ scale: 1.0
100
+ use_norm: true
101
+ image_context_config:
102
+ target: lvdm.modules.encoders.adapter.StyleTransformer
103
+ params:
104
+ in_dim: 1280
105
+ out_dim: 1024
106
+ num_heads: 8
107
+ num_tokens: 8
108
+ n_layers: 3
109
+ scale_predictor_config:
110
+ target: lvdm.modules.encoders.adapter.ScaleEncoder
111
+ params:
112
+ in_dim: 1024
113
+ out_dim: 1
114
+ num_heads: 8
115
+ num_tokens: 16
116
+ n_layers: 2
117
+ # target: lvdm.modules.encoders.adapter.ImageContext
118
+ # params:
119
+ # width: 1024
120
+ # context_dim: 1024
121
+ # token_num: 4
122
+
eval_data/3d_1.png ADDED
eval_data/anime_1.jpg ADDED
eval_data/craft_1.jpg ADDED
eval_data/craft_2.png ADDED
eval_data/digital_art_2.jpeg ADDED
eval_data/icon_1.png ADDED
eval_data/ink_2.jpeg ADDED
eval_data/oil_paint_2.jpg ADDED
header.html ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <style>
2
+ .button-container {
3
+ display: flex;
4
+ justify-content: center;
5
+ align-items: center;
6
+ gap: 1rem;
7
+ }
8
+ </style>
9
+
10
+ <div style="text-align: center; max-width: 900px; margin: 0 auto;">
11
+ <div>
12
+ <h1>
13
+ StyleCrafter: Enhancing Stylized Text-to-Video Generation with Style Adapter
14
+ </h1>
15
+ </div>
16
+
17
+ &nbsp;
18
+
19
+ <div style="text-align: center; max-width: 600px; margin: 0 auto;">
20
+ <p style="align-items: center; margin-bottom: 7px;">
21
+ This is a online demo for StyleCrafter, a model that can generate images/videos with your favorite style.
22
+ </p>
23
+ <p style="align-items: center; margin-bottom: 7px;">
24
+ You can upload your own style image and text description, and StyleCrafter will intelligently combine the style elements from the image and the text to create a unique and visually appealing output.
25
+ </p>
26
+ </div>
27
+
28
+ &nbsp;
29
+
30
+ <div class="column has-text-centered button-container">
31
+ <a href='https://arxiv.org/abs/2312.00330'><img src='https://img.shields.io/badge/arXiv-2312.00330-b31b1b.svg'></a>
32
+ <a href='https://gongyeliu.github.io/StyleCrafter.github.io/'><img src='https://img.shields.io/badge/Project-Page-Green'></a>
33
+ <a href='https://github.com/GongyeLiu/StyleCrafter'><img src='https://img.shields.io/badge/GitHub-Code-181717?logo=github&labelCase=asis'></a>
34
+ </div>
35
+
36
+ </div>
lvdm/__pycache__/basics.cpython-39.pyc ADDED
Binary file (3.25 kB). View file
 
lvdm/__pycache__/common.cpython-39.pyc ADDED
Binary file (4.51 kB). View file
 
lvdm/__pycache__/distributions.cpython-39.pyc ADDED
Binary file (3.81 kB). View file
 
lvdm/__pycache__/ema.cpython-39.pyc ADDED
Binary file (2.99 kB). View file
 
lvdm/basics.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # adopted from
2
+ # https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
3
+ # and
4
+ # https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
5
+ # and
6
+ # https://github.com/openai/guided-diffusion/blob/0ba878e517b276c45d1195eb29f6f5f72659a05b/guided_diffusion/nn.py
7
+ #
8
+ # thanks!
9
+
10
+ import torch.nn as nn
11
+ from utils.utils import instantiate_from_config
12
+
13
+
14
+ def disabled_train(self, mode=True):
15
+ """Overwrite model.train with this function to make sure train/eval mode
16
+ does not change anymore."""
17
+ return self
18
+
19
+ def zero_module(module):
20
+ """
21
+ Zero out the parameters of a module and return it.
22
+ """
23
+ for p in module.parameters():
24
+ p.detach().zero_()
25
+ return module
26
+
27
+ def scale_module(module, scale):
28
+ """
29
+ Scale the parameters of a module and return it.
30
+ """
31
+ for p in module.parameters():
32
+ p.detach().mul_(scale)
33
+ return module
34
+
35
+
36
+ def conv_nd(dims, *args, **kwargs):
37
+ """
38
+ Create a 1D, 2D, or 3D convolution module.
39
+ """
40
+ if dims == 1:
41
+ return nn.Conv1d(*args, **kwargs)
42
+ elif dims == 2:
43
+ return nn.Conv2d(*args, **kwargs)
44
+ elif dims == 3:
45
+ return nn.Conv3d(*args, **kwargs)
46
+ raise ValueError(f"unsupported dimensions: {dims}")
47
+
48
+
49
+ def linear(*args, **kwargs):
50
+ """
51
+ Create a linear module.
52
+ """
53
+ return nn.Linear(*args, **kwargs)
54
+
55
+
56
+ def avg_pool_nd(dims, *args, **kwargs):
57
+ """
58
+ Create a 1D, 2D, or 3D average pooling module.
59
+ """
60
+ if dims == 1:
61
+ return nn.AvgPool1d(*args, **kwargs)
62
+ elif dims == 2:
63
+ return nn.AvgPool2d(*args, **kwargs)
64
+ elif dims == 3:
65
+ return nn.AvgPool3d(*args, **kwargs)
66
+ raise ValueError(f"unsupported dimensions: {dims}")
67
+
68
+
69
+ def nonlinearity(type='silu'):
70
+ if type == 'silu':
71
+ return nn.SiLU()
72
+ elif type == 'leaky_relu':
73
+ return nn.LeakyReLU()
74
+
75
+
76
+ class GroupNormSpecific(nn.GroupNorm):
77
+ def forward(self, x):
78
+ return super().forward(x.float()).type(x.dtype)
79
+
80
+
81
+ def normalization(channels, num_groups=32):
82
+ """
83
+ Make a standard normalization layer.
84
+ :param channels: number of input channels.
85
+ :return: an nn.Module for normalization.
86
+ """
87
+ return GroupNormSpecific(num_groups, channels)
88
+
89
+
90
+ class HybridConditioner(nn.Module):
91
+
92
+ def __init__(self, c_concat_config, c_crossattn_config):
93
+ super().__init__()
94
+ self.concat_conditioner = instantiate_from_config(c_concat_config)
95
+ self.crossattn_conditioner = instantiate_from_config(c_crossattn_config)
96
+
97
+ def forward(self, c_concat, c_crossattn):
98
+ c_concat = self.concat_conditioner(c_concat)
99
+ c_crossattn = self.crossattn_conditioner(c_crossattn)
100
+ return {'c_concat': [c_concat], 'c_crossattn': [c_crossattn]}
lvdm/common.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from inspect import isfunction
3
+ import torch
4
+ from torch import nn
5
+ import torch.distributed as dist
6
+
7
+
8
+ def gather_data(data, return_np=True):
9
+ ''' gather data from multiple processes to one list '''
10
+ data_list = [torch.zeros_like(data) for _ in range(dist.get_world_size())]
11
+ dist.all_gather(data_list, data) # gather not supported with NCCL
12
+ if return_np:
13
+ data_list = [data.cpu().numpy() for data in data_list]
14
+ return data_list
15
+
16
+ def autocast(f):
17
+ def do_autocast(*args, **kwargs):
18
+ with torch.cuda.amp.autocast(enabled=True,
19
+ dtype=torch.get_autocast_gpu_dtype(),
20
+ cache_enabled=torch.is_autocast_cache_enabled()):
21
+ return f(*args, **kwargs)
22
+ return do_autocast
23
+
24
+
25
+ def extract_into_tensor(a, t, x_shape):
26
+ b, *_ = t.shape
27
+ out = a.gather(-1, t)
28
+ return out.reshape(b, *((1,) * (len(x_shape) - 1)))
29
+
30
+
31
+ def noise_like(shape, device, repeat=False):
32
+ repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
33
+ noise = lambda: torch.randn(shape, device=device)
34
+ return repeat_noise() if repeat else noise()
35
+
36
+
37
+ def default(val, d):
38
+ if exists(val):
39
+ return val
40
+ return d() if isfunction(d) else d
41
+
42
+ def exists(val):
43
+ return val is not None
44
+
45
+ def identity(*args, **kwargs):
46
+ return nn.Identity()
47
+
48
+ def uniq(arr):
49
+ return{el: True for el in arr}.keys()
50
+
51
+ def mean_flat(tensor):
52
+ """
53
+ Take the mean over all non-batch dimensions.
54
+ """
55
+ return tensor.mean(dim=list(range(1, len(tensor.shape))))
56
+
57
+ def ismap(x):
58
+ if not isinstance(x, torch.Tensor):
59
+ return False
60
+ return (len(x.shape) == 4) and (x.shape[1] > 3)
61
+
62
+ def isimage(x):
63
+ if not isinstance(x,torch.Tensor):
64
+ return False
65
+ return (len(x.shape) == 4) and (x.shape[1] == 3 or x.shape[1] == 1)
66
+
67
+ def max_neg_value(t):
68
+ return -torch.finfo(t.dtype).max
69
+
70
+ def shape_to_str(x):
71
+ shape_str = "x".join([str(x) for x in x.shape])
72
+ return shape_str
73
+
74
+ def init_(tensor):
75
+ dim = tensor.shape[-1]
76
+ std = 1 / math.sqrt(dim)
77
+ tensor.uniform_(-std, std)
78
+ return tensor
79
+
80
+ ckpt = torch.utils.checkpoint.checkpoint
81
+ def checkpoint(func, inputs, params, flag):
82
+ """
83
+ Evaluate a function without caching intermediate activations, allowing for
84
+ reduced memory at the expense of extra compute in the backward pass.
85
+ :param func: the function to evaluate.
86
+ :param inputs: the argument sequence to pass to `func`.
87
+ :param params: a sequence of parameters `func` depends on but does not
88
+ explicitly take as arguments.
89
+ :param flag: if False, disable gradient checkpointing.
90
+ """
91
+ if flag:
92
+ return ckpt(func, *inputs)
93
+ else:
94
+ return func(*inputs)
95
+
lvdm/distributions.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+
5
+ class AbstractDistribution:
6
+ def sample(self):
7
+ raise NotImplementedError()
8
+
9
+ def mode(self):
10
+ raise NotImplementedError()
11
+
12
+
13
+ class DiracDistribution(AbstractDistribution):
14
+ def __init__(self, value):
15
+ self.value = value
16
+
17
+ def sample(self):
18
+ return self.value
19
+
20
+ def mode(self):
21
+ return self.value
22
+
23
+
24
+ class DiagonalGaussianDistribution(object):
25
+ def __init__(self, parameters, deterministic=False):
26
+ self.parameters = parameters
27
+ self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
28
+ self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
29
+ self.deterministic = deterministic
30
+ self.std = torch.exp(0.5 * self.logvar)
31
+ self.var = torch.exp(self.logvar)
32
+ if self.deterministic:
33
+ self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device)
34
+
35
+ def sample(self, noise=None):
36
+ if noise is None:
37
+ noise = torch.randn(self.mean.shape)
38
+
39
+ x = self.mean + self.std * noise.to(device=self.parameters.device)
40
+ return x
41
+
42
+ def kl(self, other=None):
43
+ if self.deterministic:
44
+ return torch.Tensor([0.])
45
+ else:
46
+ if other is None:
47
+ return 0.5 * torch.sum(torch.pow(self.mean, 2)
48
+ + self.var - 1.0 - self.logvar,
49
+ dim=[1, 2, 3])
50
+ else:
51
+ return 0.5 * torch.sum(
52
+ torch.pow(self.mean - other.mean, 2) / other.var
53
+ + self.var / other.var - 1.0 - self.logvar + other.logvar,
54
+ dim=[1, 2, 3])
55
+
56
+ def nll(self, sample, dims=[1,2,3]):
57
+ if self.deterministic:
58
+ return torch.Tensor([0.])
59
+ logtwopi = np.log(2.0 * np.pi)
60
+ return 0.5 * torch.sum(
61
+ logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
62
+ dim=dims)
63
+
64
+ def mode(self):
65
+ return self.mean
66
+
67
+
68
+ def normal_kl(mean1, logvar1, mean2, logvar2):
69
+ """
70
+ source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12
71
+ Compute the KL divergence between two gaussians.
72
+ Shapes are automatically broadcasted, so batches can be compared to
73
+ scalars, among other use cases.
74
+ """
75
+ tensor = None
76
+ for obj in (mean1, logvar1, mean2, logvar2):
77
+ if isinstance(obj, torch.Tensor):
78
+ tensor = obj
79
+ break
80
+ assert tensor is not None, "at least one argument must be a Tensor"
81
+
82
+ # Force variances to be Tensors. Broadcasting helps convert scalars to
83
+ # Tensors, but it does not work for torch.exp().
84
+ logvar1, logvar2 = [
85
+ x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor)
86
+ for x in (logvar1, logvar2)
87
+ ]
88
+
89
+ return 0.5 * (
90
+ -1.0
91
+ + logvar2
92
+ - logvar1
93
+ + torch.exp(logvar1 - logvar2)
94
+ + ((mean1 - mean2) ** 2) * torch.exp(-logvar2)
95
+ )
lvdm/ema.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+
4
+
5
+ class LitEma(nn.Module):
6
+ def __init__(self, model, decay=0.9999, use_num_upates=True):
7
+ super().__init__()
8
+ if decay < 0.0 or decay > 1.0:
9
+ raise ValueError('Decay must be between 0 and 1')
10
+
11
+ self.m_name2s_name = {}
12
+ self.register_buffer('decay', torch.tensor(decay, dtype=torch.float32))
13
+ self.register_buffer('num_updates', torch.tensor(0,dtype=torch.int) if use_num_upates
14
+ else torch.tensor(-1,dtype=torch.int))
15
+
16
+ for name, p in model.named_parameters():
17
+ if p.requires_grad:
18
+ #remove as '.'-character is not allowed in buffers
19
+ s_name = name.replace('.','')
20
+ self.m_name2s_name.update({name:s_name})
21
+ self.register_buffer(s_name,p.clone().detach().data)
22
+
23
+ self.collected_params = []
24
+
25
+ def forward(self,model):
26
+ decay = self.decay
27
+
28
+ if self.num_updates >= 0:
29
+ self.num_updates += 1
30
+ decay = min(self.decay,(1 + self.num_updates) / (10 + self.num_updates))
31
+
32
+ one_minus_decay = 1.0 - decay
33
+
34
+ with torch.no_grad():
35
+ m_param = dict(model.named_parameters())
36
+ shadow_params = dict(self.named_buffers())
37
+
38
+ for key in m_param:
39
+ if m_param[key].requires_grad:
40
+ sname = self.m_name2s_name[key]
41
+ shadow_params[sname] = shadow_params[sname].type_as(m_param[key])
42
+ shadow_params[sname].sub_(one_minus_decay * (shadow_params[sname] - m_param[key]))
43
+ else:
44
+ assert not key in self.m_name2s_name
45
+
46
+ def copy_to(self, model):
47
+ m_param = dict(model.named_parameters())
48
+ shadow_params = dict(self.named_buffers())
49
+ for key in m_param:
50
+ if m_param[key].requires_grad:
51
+ m_param[key].data.copy_(shadow_params[self.m_name2s_name[key]].data)
52
+ else:
53
+ assert not key in self.m_name2s_name
54
+
55
+ def store(self, parameters):
56
+ """
57
+ Save the current parameters for restoring later.
58
+ Args:
59
+ parameters: Iterable of `torch.nn.Parameter`; the parameters to be
60
+ temporarily stored.
61
+ """
62
+ self.collected_params = [param.clone() for param in parameters]
63
+
64
+ def restore(self, parameters):
65
+ """
66
+ Restore the parameters stored with the `store` method.
67
+ Useful to validate the model with EMA parameters without affecting the
68
+ original optimization process. Store the parameters before the
69
+ `copy_to` method. After validation (or model saving), use this to
70
+ restore the former parameters.
71
+ Args:
72
+ parameters: Iterable of `torch.nn.Parameter`; the parameters to be
73
+ updated with the stored parameters.
74
+ """
75
+ for c_param, param in zip(self.collected_params, parameters):
76
+ param.data.copy_(c_param.data)
lvdm/models/__pycache__/autoencoder.cpython-39.pyc ADDED
Binary file (7.22 kB). View file
 
lvdm/models/__pycache__/ddpm3d.cpython-39.pyc ADDED
Binary file (23.4 kB). View file
 
lvdm/models/__pycache__/ddpm3d_cond.cpython-39.pyc ADDED
Binary file (5.79 kB). View file
 
lvdm/models/__pycache__/utils_diffusion.cpython-39.pyc ADDED
Binary file (3.9 kB). View file
 
lvdm/models/autoencoder.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from contextlib import contextmanager
3
+ import torch
4
+ import numpy as np
5
+ from einops import rearrange
6
+ import torch.nn.functional as F
7
+ import pytorch_lightning as pl
8
+ from lvdm.modules.networks.ae_modules import Encoder, Decoder
9
+ from lvdm.distributions import DiagonalGaussianDistribution
10
+ from utils.utils import instantiate_from_config
11
+
12
+
13
+ class AutoencoderKL(pl.LightningModule):
14
+ def __init__(self,
15
+ ddconfig,
16
+ lossconfig,
17
+ embed_dim,
18
+ ckpt_path=None,
19
+ ignore_keys=[],
20
+ image_key="image",
21
+ colorize_nlabels=None,
22
+ monitor=None,
23
+ test=False,
24
+ logdir=None,
25
+ input_dim=4,
26
+ test_args=None,
27
+ ):
28
+ super().__init__()
29
+ self.image_key = image_key
30
+ self.encoder = Encoder(**ddconfig)
31
+ self.decoder = Decoder(**ddconfig)
32
+ self.loss = instantiate_from_config(lossconfig)
33
+ assert ddconfig["double_z"]
34
+ self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1)
35
+ self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
36
+ self.embed_dim = embed_dim
37
+ self.input_dim = input_dim
38
+ self.test = test
39
+ self.test_args = test_args
40
+ self.logdir = logdir
41
+ if colorize_nlabels is not None:
42
+ assert type(colorize_nlabels)==int
43
+ self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
44
+ if monitor is not None:
45
+ self.monitor = monitor
46
+ if ckpt_path is not None:
47
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
48
+ if self.test:
49
+ self.init_test()
50
+
51
+ def init_test(self,):
52
+ self.test = True
53
+ save_dir = os.path.join(self.logdir, "test")
54
+ if 'ckpt' in self.test_args:
55
+ ckpt_name = os.path.basename(self.test_args.ckpt).split('.ckpt')[0] + f'_epoch{self._cur_epoch}'
56
+ self.root = os.path.join(save_dir, ckpt_name)
57
+ else:
58
+ self.root = save_dir
59
+ if 'test_subdir' in self.test_args:
60
+ self.root = os.path.join(save_dir, self.test_args.test_subdir)
61
+
62
+ self.root_zs = os.path.join(self.root, "zs")
63
+ self.root_dec = os.path.join(self.root, "reconstructions")
64
+ self.root_inputs = os.path.join(self.root, "inputs")
65
+ os.makedirs(self.root, exist_ok=True)
66
+
67
+ if self.test_args.save_z:
68
+ os.makedirs(self.root_zs, exist_ok=True)
69
+ if self.test_args.save_reconstruction:
70
+ os.makedirs(self.root_dec, exist_ok=True)
71
+ if self.test_args.save_input:
72
+ os.makedirs(self.root_inputs, exist_ok=True)
73
+ assert(self.test_args is not None)
74
+ self.test_maximum = getattr(self.test_args, 'test_maximum', None)
75
+ self.count = 0
76
+ self.eval_metrics = {}
77
+ self.decodes = []
78
+ self.save_decode_samples = 2048
79
+
80
+ def init_from_ckpt(self, path, ignore_keys=list()):
81
+ sd = torch.load(path, map_location="cpu")
82
+ try:
83
+ self._cur_epoch = sd['epoch']
84
+ sd = sd["state_dict"]
85
+ except:
86
+ self._cur_epoch = 'null'
87
+ keys = list(sd.keys())
88
+ for k in keys:
89
+ for ik in ignore_keys:
90
+ if k.startswith(ik):
91
+ print("Deleting key {} from state_dict.".format(k))
92
+ del sd[k]
93
+ self.load_state_dict(sd, strict=False)
94
+ # self.load_state_dict(sd, strict=True)
95
+ print(f"Restored from {path}")
96
+
97
+ def encode(self, x, **kwargs):
98
+
99
+ h = self.encoder(x)
100
+ moments = self.quant_conv(h)
101
+ posterior = DiagonalGaussianDistribution(moments)
102
+ return posterior
103
+
104
+ def decode(self, z, **kwargs):
105
+ z = self.post_quant_conv(z)
106
+ dec = self.decoder(z)
107
+ return dec
108
+
109
+ def forward(self, input, sample_posterior=True):
110
+ posterior = self.encode(input)
111
+ if sample_posterior:
112
+ z = posterior.sample()
113
+ else:
114
+ z = posterior.mode()
115
+ dec = self.decode(z)
116
+ return dec, posterior
117
+
118
+ def get_input(self, batch, k):
119
+ x = batch[k]
120
+ if x.dim() == 5 and self.input_dim == 4:
121
+ b,c,t,h,w = x.shape
122
+ self.b = b
123
+ self.t = t
124
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
125
+
126
+ return x
127
+
128
+ def training_step(self, batch, batch_idx, optimizer_idx):
129
+ inputs = self.get_input(batch, self.image_key)
130
+ reconstructions, posterior = self(inputs)
131
+
132
+ if optimizer_idx == 0:
133
+ # train encoder+decoder+logvar
134
+ aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
135
+ last_layer=self.get_last_layer(), split="train")
136
+ self.log("aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
137
+ self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False)
138
+ return aeloss
139
+
140
+ if optimizer_idx == 1:
141
+ # train the discriminator
142
+ discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
143
+ last_layer=self.get_last_layer(), split="train")
144
+
145
+ self.log("discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
146
+ self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False)
147
+ return discloss
148
+
149
+ def validation_step(self, batch, batch_idx):
150
+ inputs = self.get_input(batch, self.image_key)
151
+ reconstructions, posterior = self(inputs)
152
+ aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, 0, self.global_step,
153
+ last_layer=self.get_last_layer(), split="val")
154
+
155
+ discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, 1, self.global_step,
156
+ last_layer=self.get_last_layer(), split="val")
157
+
158
+ self.log("val/rec_loss", log_dict_ae["val/rec_loss"])
159
+ self.log_dict(log_dict_ae)
160
+ self.log_dict(log_dict_disc)
161
+ return self.log_dict
162
+
163
+ def configure_optimizers(self):
164
+ lr = self.learning_rate
165
+ opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
166
+ list(self.decoder.parameters())+
167
+ list(self.quant_conv.parameters())+
168
+ list(self.post_quant_conv.parameters()),
169
+ lr=lr, betas=(0.5, 0.9))
170
+ opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
171
+ lr=lr, betas=(0.5, 0.9))
172
+ return [opt_ae, opt_disc], []
173
+
174
+ def get_last_layer(self):
175
+ return self.decoder.conv_out.weight
176
+
177
+ @torch.no_grad()
178
+ def log_images(self, batch, only_inputs=False, **kwargs):
179
+ log = dict()
180
+ x = self.get_input(batch, self.image_key)
181
+ x = x.to(self.device)
182
+ if not only_inputs:
183
+ xrec, posterior = self(x)
184
+ if x.shape[1] > 3:
185
+ # colorize with random projection
186
+ assert xrec.shape[1] > 3
187
+ x = self.to_rgb(x)
188
+ xrec = self.to_rgb(xrec)
189
+ log["samples"] = self.decode(torch.randn_like(posterior.sample()))
190
+ log["reconstructions"] = xrec
191
+ log["inputs"] = x
192
+ return log
193
+
194
+ def to_rgb(self, x):
195
+ assert self.image_key == "segmentation"
196
+ if not hasattr(self, "colorize"):
197
+ self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
198
+ x = F.conv2d(x, weight=self.colorize)
199
+ x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
200
+ return x
201
+
202
+ class IdentityFirstStage(torch.nn.Module):
203
+ def __init__(self, *args, vq_interface=False, **kwargs):
204
+ self.vq_interface = vq_interface # TODO: Should be true by default but check to not break older stuff
205
+ super().__init__()
206
+
207
+ def encode(self, x, *args, **kwargs):
208
+ return x
209
+
210
+ def decode(self, x, *args, **kwargs):
211
+ return x
212
+
213
+ def quantize(self, x, *args, **kwargs):
214
+ if self.vq_interface:
215
+ return x, None, [None, None, None]
216
+ return x
217
+
218
+ def forward(self, x, *args, **kwargs):
219
+ return x
lvdm/models/ddpm3d.py ADDED
@@ -0,0 +1,781 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ wild mixture of
3
+ https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
4
+ https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
5
+ https://github.com/CompVis/taming-transformers
6
+ -- merci
7
+ """
8
+
9
+ from functools import partial
10
+ from contextlib import contextmanager
11
+ import numpy as np
12
+ from tqdm import tqdm
13
+ from einops import rearrange, repeat
14
+ import logging
15
+ mainlogger = logging.getLogger('mainlogger')
16
+ import torch
17
+ import torch.nn as nn
18
+ from torchvision.utils import make_grid
19
+ import pytorch_lightning as pl
20
+ from utils.utils import instantiate_from_config
21
+ from lvdm.ema import LitEma
22
+ from lvdm.distributions import DiagonalGaussianDistribution
23
+ from lvdm.models.utils_diffusion import make_beta_schedule
24
+ from lvdm.modules.encoders.ip_resampler import ImageProjModel, Resampler
25
+ from lvdm.basics import disabled_train
26
+ from lvdm.common import (
27
+ extract_into_tensor,
28
+ noise_like,
29
+ exists,
30
+ default
31
+ )
32
+
33
+
34
+ __conditioning_keys__ = {'concat': 'c_concat',
35
+ 'crossattn': 'c_crossattn',
36
+ 'adm': 'y'}
37
+
38
+ class DDPM(pl.LightningModule):
39
+ # classic DDPM with Gaussian diffusion, in image space
40
+ def __init__(self,
41
+ unet_config,
42
+ timesteps=1000,
43
+ beta_schedule="linear",
44
+ loss_type="l2",
45
+ ckpt_path=None,
46
+ ignore_keys=[],
47
+ load_only_unet=False,
48
+ monitor=None,
49
+ use_ema=True,
50
+ first_stage_key="image",
51
+ image_size=256,
52
+ channels=3,
53
+ log_every_t=100,
54
+ clip_denoised=True,
55
+ linear_start=1e-4,
56
+ linear_end=2e-2,
57
+ cosine_s=8e-3,
58
+ given_betas=None,
59
+ original_elbo_weight=0.,
60
+ v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
61
+ l_simple_weight=1.,
62
+ conditioning_key=None,
63
+ parameterization="eps", # all assuming fixed variance schedules
64
+ scheduler_config=None,
65
+ use_positional_encodings=False,
66
+ learn_logvar=False,
67
+ logvar_init=0.
68
+ ):
69
+ super().__init__()
70
+ assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"'
71
+ self.parameterization = parameterization
72
+ mainlogger.info(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
73
+ self.cond_stage_model = None
74
+ self.clip_denoised = clip_denoised
75
+ self.log_every_t = log_every_t
76
+ self.first_stage_key = first_stage_key
77
+ self.channels = channels
78
+ self.temporal_length = unet_config.params.temporal_length
79
+ self.image_size = image_size
80
+ if isinstance(self.image_size, int):
81
+ self.image_size = [self.image_size, self.image_size]
82
+ self.use_positional_encodings = use_positional_encodings
83
+ self.model = DiffusionWrapper(unet_config, conditioning_key)
84
+ self.use_ema = use_ema
85
+ if self.use_ema:
86
+ self.model_ema = LitEma(self.model)
87
+ mainlogger.info(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
88
+
89
+ self.use_scheduler = scheduler_config is not None
90
+ if self.use_scheduler:
91
+ self.scheduler_config = scheduler_config
92
+
93
+ self.v_posterior = v_posterior
94
+ self.original_elbo_weight = original_elbo_weight
95
+ self.l_simple_weight = l_simple_weight
96
+
97
+ if monitor is not None:
98
+ self.monitor = monitor
99
+ if ckpt_path is not None:
100
+ self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet)
101
+
102
+ self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
103
+ linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
104
+
105
+ self.loss_type = loss_type
106
+
107
+ self.learn_logvar = learn_logvar
108
+ self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
109
+ if self.learn_logvar:
110
+ self.logvar = nn.Parameter(self.logvar, requires_grad=True)
111
+
112
+
113
+ def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
114
+ linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
115
+ if exists(given_betas):
116
+ betas = given_betas
117
+ else:
118
+ betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
119
+ cosine_s=cosine_s)
120
+ alphas = 1. - betas
121
+ alphas_cumprod = np.cumprod(alphas, axis=0)
122
+ alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
123
+
124
+ timesteps, = betas.shape
125
+ self.num_timesteps = int(timesteps)
126
+ self.linear_start = linear_start
127
+ self.linear_end = linear_end
128
+ assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
129
+
130
+ to_torch = partial(torch.tensor, dtype=torch.float32)
131
+
132
+ self.register_buffer('betas', to_torch(betas))
133
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
134
+ self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
135
+
136
+ # calculations for diffusion q(x_t | x_{t-1}) and others
137
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
138
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
139
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
140
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
141
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
142
+
143
+ # calculations for posterior q(x_{t-1} | x_t, x_0)
144
+ posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
145
+ 1. - alphas_cumprod) + self.v_posterior * betas
146
+ # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
147
+ self.register_buffer('posterior_variance', to_torch(posterior_variance))
148
+ # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
149
+ self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
150
+ self.register_buffer('posterior_mean_coef1', to_torch(
151
+ betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
152
+ self.register_buffer('posterior_mean_coef2', to_torch(
153
+ (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
154
+
155
+ if self.parameterization == "eps":
156
+ lvlb_weights = self.betas ** 2 / (
157
+ 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
158
+ elif self.parameterization == "x0":
159
+ lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
160
+ else:
161
+ raise NotImplementedError("mu not supported")
162
+ # TODO how to choose this term
163
+ lvlb_weights[0] = lvlb_weights[1]
164
+ self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
165
+ assert not torch.isnan(self.lvlb_weights).all()
166
+
167
+ @contextmanager
168
+ def ema_scope(self, context=None):
169
+ if self.use_ema:
170
+ self.model_ema.store(self.model.parameters())
171
+ self.model_ema.copy_to(self.model)
172
+ if context is not None:
173
+ mainlogger.info(f"{context}: Switched to EMA weights")
174
+ try:
175
+ yield None
176
+ finally:
177
+ if self.use_ema:
178
+ self.model_ema.restore(self.model.parameters())
179
+ if context is not None:
180
+ mainlogger.info(f"{context}: Restored training weights")
181
+
182
+ def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
183
+ sd = torch.load(path, map_location="cpu")
184
+ if "state_dict" in list(sd.keys()):
185
+ sd = sd["state_dict"]
186
+ keys = list(sd.keys())
187
+ for k in keys:
188
+ for ik in ignore_keys:
189
+ if k.startswith(ik):
190
+ mainlogger.info("Deleting key {} from state_dict.".format(k))
191
+ del sd[k]
192
+ missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
193
+ sd, strict=False)
194
+ mainlogger.info(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
195
+ if len(missing) > 0:
196
+ mainlogger.info(f"Missing Keys: {missing}")
197
+ if len(unexpected) > 0:
198
+ mainlogger.info(f"Unexpected Keys: {unexpected}")
199
+
200
+ def q_mean_variance(self, x_start, t):
201
+ """
202
+ Get the distribution q(x_t | x_0).
203
+ :param x_start: the [N x C x ...] tensor of noiseless inputs.
204
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
205
+ :return: A tuple (mean, variance, log_variance), all of x_start's shape.
206
+ """
207
+ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
208
+ variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
209
+ log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
210
+ return mean, variance, log_variance
211
+
212
+ def predict_start_from_noise(self, x_t, t, noise):
213
+ return (
214
+ extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
215
+ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
216
+ )
217
+
218
+ def q_posterior(self, x_start, x_t, t):
219
+ posterior_mean = (
220
+ extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
221
+ extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
222
+ )
223
+ posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
224
+ posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
225
+ return posterior_mean, posterior_variance, posterior_log_variance_clipped
226
+
227
+ def p_mean_variance(self, x, t, clip_denoised: bool):
228
+ model_out = self.model(x, t)
229
+ if self.parameterization == "eps":
230
+ x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
231
+ elif self.parameterization == "x0":
232
+ x_recon = model_out
233
+ if clip_denoised:
234
+ x_recon.clamp_(-1., 1.)
235
+
236
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
237
+ return model_mean, posterior_variance, posterior_log_variance
238
+
239
+ @torch.no_grad()
240
+ def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
241
+ b, *_, device = *x.shape, x.device
242
+ model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
243
+ noise = noise_like(x.shape, device, repeat_noise)
244
+ # no noise when t == 0
245
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
246
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
247
+
248
+ @torch.no_grad()
249
+ def p_sample_loop(self, shape, return_intermediates=False):
250
+ device = self.betas.device
251
+ b = shape[0]
252
+ img = torch.randn(shape, device=device)
253
+ intermediates = [img]
254
+ for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
255
+ img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
256
+ clip_denoised=self.clip_denoised)
257
+ if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
258
+ intermediates.append(img)
259
+ if return_intermediates:
260
+ return img, intermediates
261
+ return img
262
+
263
+ @torch.no_grad()
264
+ def sample(self, batch_size=16, return_intermediates=False):
265
+ image_size = self.image_size
266
+ channels = self.channels
267
+ return self.p_sample_loop((batch_size, channels, image_size, image_size),
268
+ return_intermediates=return_intermediates)
269
+
270
+ def q_sample(self, x_start, t, noise=None):
271
+ noise = default(noise, lambda: torch.randn_like(x_start))
272
+ return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start *
273
+ extract_into_tensor(self.scale_arr, t, x_start.shape) +
274
+ extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
275
+
276
+ def get_input(self, batch, k):
277
+ x = batch[k]
278
+ x = x.to(memory_format=torch.contiguous_format).float()
279
+ return x
280
+
281
+ def _get_rows_from_list(self, samples):
282
+ n_imgs_per_row = len(samples)
283
+ denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
284
+ denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
285
+ denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
286
+ return denoise_grid
287
+
288
+ @torch.no_grad()
289
+ def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
290
+ log = dict()
291
+ x = self.get_input(batch, self.first_stage_key)
292
+ N = min(x.shape[0], N)
293
+ n_row = min(x.shape[0], n_row)
294
+ x = x.to(self.device)[:N]
295
+ log["inputs"] = x
296
+
297
+ # get diffusion row
298
+ diffusion_row = list()
299
+ x_start = x[:n_row]
300
+
301
+ for t in range(self.num_timesteps):
302
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
303
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
304
+ t = t.to(self.device).long()
305
+ noise = torch.randn_like(x_start)
306
+ x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
307
+ diffusion_row.append(x_noisy)
308
+
309
+ log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
310
+
311
+ if sample:
312
+ # get denoise row
313
+ with self.ema_scope("Plotting"):
314
+ samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
315
+
316
+ log["samples"] = samples
317
+ log["denoise_row"] = self._get_rows_from_list(denoise_row)
318
+
319
+ if return_keys:
320
+ if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
321
+ return log
322
+ else:
323
+ return {key: log[key] for key in return_keys}
324
+ return log
325
+
326
+
327
+ class LatentDiffusion(DDPM):
328
+ """main class"""
329
+ def __init__(self,
330
+ first_stage_config,
331
+ cond_stage_config,
332
+ num_timesteps_cond=None,
333
+ cond_stage_key="caption",
334
+ cond_stage_trainable=False,
335
+ cond_stage_forward=None,
336
+ conditioning_key=None,
337
+ uncond_prob=0.2,
338
+ uncond_type="empty_seq",
339
+ scale_factor=1.0,
340
+ scale_by_std=False,
341
+ encoder_type="2d",
342
+ only_model=False,
343
+ use_scale=False,
344
+ scale_a=1,
345
+ scale_b=0.3,
346
+ mid_step=400,
347
+ fix_scale_bug=False,
348
+ perframe_ae=True,
349
+ *args, **kwargs):
350
+ self.num_timesteps_cond = default(num_timesteps_cond, 1)
351
+ self.scale_by_std = scale_by_std
352
+ assert self.num_timesteps_cond <= kwargs['timesteps']
353
+ # for backwards compatibility after implementation of DiffusionWrapper
354
+ ckpt_path = kwargs.pop("ckpt_path", None)
355
+ ignore_keys = kwargs.pop("ignore_keys", [])
356
+ conditioning_key = default(conditioning_key, 'crossattn')
357
+ super().__init__(conditioning_key=conditioning_key, *args, **kwargs)
358
+
359
+ self.cond_stage_trainable = cond_stage_trainable
360
+ self.cond_stage_key = cond_stage_key
361
+ self.perframe_ae = perframe_ae
362
+
363
+ # scale factor
364
+ self.use_scale=use_scale
365
+ if self.use_scale:
366
+ self.scale_a=scale_a
367
+ self.scale_b=scale_b
368
+ if fix_scale_bug:
369
+ scale_step=self.num_timesteps-mid_step
370
+ else: #bug
371
+ scale_step = self.num_timesteps
372
+
373
+ scale_arr1 = np.linspace(scale_a, scale_b, mid_step)
374
+ scale_arr2 = np.full(scale_step, scale_b)
375
+ scale_arr = np.concatenate((scale_arr1, scale_arr2))
376
+ scale_arr_prev = np.append(scale_a, scale_arr[:-1])
377
+ to_torch = partial(torch.tensor, dtype=torch.float32)
378
+ self.register_buffer('scale_arr', to_torch(scale_arr))
379
+
380
+ try:
381
+ self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
382
+ except:
383
+ self.num_downs = 0
384
+ if not scale_by_std:
385
+ self.scale_factor = scale_factor
386
+ else:
387
+ self.register_buffer('scale_factor', torch.tensor(scale_factor))
388
+ self.instantiate_first_stage(first_stage_config)
389
+ self.instantiate_cond_stage(cond_stage_config)
390
+ self.first_stage_config = first_stage_config
391
+ self.cond_stage_config = cond_stage_config
392
+ self.clip_denoised = False
393
+
394
+ self.cond_stage_forward = cond_stage_forward
395
+ self.encoder_type = encoder_type
396
+ assert(encoder_type in ["2d", "3d"])
397
+ self.uncond_prob = uncond_prob
398
+ self.classifier_free_guidance = True if uncond_prob > 0 else False
399
+ assert(uncond_type in ["zero_embed", "empty_seq"])
400
+ self.uncond_type = uncond_type
401
+
402
+
403
+ self.restarted_from_ckpt = False
404
+ if ckpt_path is not None:
405
+ self.init_from_ckpt(ckpt_path, ignore_keys, only_model=only_model)
406
+ self.restarted_from_ckpt = True
407
+
408
+
409
+ def make_cond_schedule(self, ):
410
+ self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
411
+ ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
412
+ self.cond_ids[:self.num_timesteps_cond] = ids
413
+
414
+ def q_sample(self, x_start, t, noise=None):
415
+ noise = default(noise, lambda: torch.randn_like(x_start))
416
+ if self.use_scale:
417
+ return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start *
418
+ extract_into_tensor(self.scale_arr, t, x_start.shape) +
419
+ extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
420
+ else:
421
+ return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
422
+ extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
423
+
424
+
425
+ def _freeze_model(self):
426
+ for name, para in self.model.diffusion_model.named_parameters():
427
+ para.requires_grad = False
428
+
429
+ def instantiate_first_stage(self, config):
430
+ model = instantiate_from_config(config)
431
+ self.first_stage_model = model.eval()
432
+ self.first_stage_model.train = disabled_train
433
+ for param in self.first_stage_model.parameters():
434
+ param.requires_grad = False
435
+
436
+ def instantiate_cond_stage(self, config):
437
+ if not self.cond_stage_trainable:
438
+ model = instantiate_from_config(config)
439
+ self.cond_stage_model = model.eval()
440
+ self.cond_stage_model.train = disabled_train
441
+ for param in self.cond_stage_model.parameters():
442
+ param.requires_grad = False
443
+ else:
444
+ model = instantiate_from_config(config)
445
+ self.cond_stage_model = model
446
+
447
+ def get_learned_conditioning(self, c):
448
+ if self.cond_stage_forward is None:
449
+ if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
450
+ c = self.cond_stage_model.encode(c)
451
+ if isinstance(c, DiagonalGaussianDistribution):
452
+ c = c.mode()
453
+ else:
454
+ c = self.cond_stage_model(c)
455
+ else:
456
+ assert hasattr(self.cond_stage_model, self.cond_stage_forward)
457
+ c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
458
+ return c
459
+
460
+ def get_first_stage_encoding(self, encoder_posterior, noise=None):
461
+ if isinstance(encoder_posterior, DiagonalGaussianDistribution):
462
+ z = encoder_posterior.sample(noise=noise)
463
+ elif isinstance(encoder_posterior, torch.Tensor):
464
+ z = encoder_posterior
465
+ else:
466
+ raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
467
+ return self.scale_factor * z
468
+
469
+ @torch.no_grad()
470
+ def encode_first_stage(self, x):
471
+ if self.encoder_type == "2d" and x.dim() == 5 and not self.perframe_ae:
472
+ b, _, t, _, _ = x.shape
473
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
474
+ reshape_back = True
475
+ else:
476
+ reshape_back = False
477
+
478
+ if not self.perframe_ae:
479
+ encoder_posterior = self.first_stage_model.encode(x)
480
+ results = self.get_first_stage_encoding(encoder_posterior).detach()
481
+ else:
482
+ results = []
483
+ for index in range(x.shape[2]):
484
+ frame_batch = self.first_stage_model.encode(x[:,:,index,:,:])
485
+ frame_result = self.get_first_stage_encoding(frame_batch).detach()
486
+ results.append(frame_result)
487
+ results = torch.stack(results, dim=2)
488
+
489
+ if reshape_back:
490
+ results = rearrange(results, '(b t) c h w -> b c t h w', b=b,t=t)
491
+
492
+ return results
493
+
494
+ @torch.no_grad()
495
+ def encode_first_stage_2DAE(self, x):
496
+
497
+ b, _, t, _, _ = x.shape
498
+ results = torch.cat([self.get_first_stage_encoding(self.first_stage_model.encode(x[:,:,i])).detach().unsqueeze(2) for i in range(t)], dim=2)
499
+
500
+ return results
501
+
502
+ def decode_core(self, z, **kwargs):
503
+ if self.encoder_type == "2d" and z.dim() == 5 and not self.perframe_ae:
504
+ b, _, t, _, _ = z.shape
505
+ z = rearrange(z, 'b c t h w -> (b t) c h w')
506
+ reshape_back = True
507
+ else:
508
+ reshape_back = False
509
+
510
+ if not self.perframe_ae:
511
+ z = 1. / self.scale_factor * z
512
+ results = self.first_stage_model.decode(z, **kwargs)
513
+ else:
514
+ results = []
515
+ for index in range(z.shape[2]):
516
+ frame_z = 1. / self.scale_factor * z[:,:,index,:,:]
517
+ frame_result = self.first_stage_model.decode(frame_z, **kwargs)
518
+ results.append(frame_result)
519
+ results = torch.stack(results, dim=2)
520
+
521
+
522
+ if reshape_back:
523
+ results = rearrange(results, '(b t) c h w -> b c t h w', b=b,t=t)
524
+ return results
525
+
526
+ @torch.no_grad()
527
+ def decode_first_stage(self, z, **kwargs):
528
+ return self.decode_core(z, **kwargs)
529
+
530
+ def apply_model(self, x_noisy, t, cond, **kwargs):
531
+ if isinstance(cond, dict):
532
+ # hybrid case, cond is exptected to be a dict
533
+ pass
534
+ else:
535
+ if not isinstance(cond, list):
536
+ cond = [cond]
537
+ key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
538
+ cond = {key: cond}
539
+
540
+ x_recon = self.model(x_noisy, t, **cond, **kwargs)
541
+
542
+ if isinstance(x_recon, tuple):
543
+ return x_recon[0]
544
+ else:
545
+ return x_recon
546
+
547
+ def _get_denoise_row_from_list(self, samples, desc=''):
548
+ denoise_row = []
549
+ for zd in tqdm(samples, desc=desc):
550
+ denoise_row.append(self.decode_first_stage(zd.to(self.device)))
551
+ n_log_timesteps = len(denoise_row)
552
+
553
+ denoise_row = torch.stack(denoise_row) # n_log_timesteps, b, C, H, W
554
+
555
+ if denoise_row.dim() == 5:
556
+ # img, num_imgs= n_log_timesteps * bs, grid_size=[bs,n_log_timesteps]
557
+ denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
558
+ denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
559
+ denoise_grid = make_grid(denoise_grid, nrow=n_log_timesteps)
560
+ elif denoise_row.dim() == 6:
561
+ # video, grid_size=[n_log_timesteps*bs, t]
562
+ video_length = denoise_row.shape[3]
563
+ denoise_grid = rearrange(denoise_row, 'n b c t h w -> b n c t h w')
564
+ denoise_grid = rearrange(denoise_grid, 'b n c t h w -> (b n) c t h w')
565
+ denoise_grid = rearrange(denoise_grid, 'n c t h w -> (n t) c h w')
566
+ denoise_grid = make_grid(denoise_grid, nrow=video_length)
567
+ else:
568
+ raise ValueError
569
+
570
+ return denoise_grid
571
+
572
+
573
+ @torch.no_grad()
574
+ def decode_first_stage_2DAE(self, z, **kwargs):
575
+
576
+ b, _, t, _, _ = z.shape
577
+ z = 1. / self.scale_factor * z
578
+ results = torch.cat([self.first_stage_model.decode(z[:,:,i], **kwargs).unsqueeze(2) for i in range(t)], dim=2)
579
+
580
+ return results
581
+
582
+
583
+ def p_mean_variance(self, x, c, t, clip_denoised: bool, return_x0=False, score_corrector=None, corrector_kwargs=None, **kwargs):
584
+ t_in = t
585
+ model_out = self.apply_model(x, t_in, c, **kwargs)
586
+
587
+ if score_corrector is not None:
588
+ assert self.parameterization == "eps"
589
+ model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
590
+
591
+ if self.parameterization == "eps":
592
+ x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
593
+ elif self.parameterization == "x0":
594
+ x_recon = model_out
595
+ else:
596
+ raise NotImplementedError()
597
+
598
+ if clip_denoised:
599
+ x_recon.clamp_(-1., 1.)
600
+
601
+ model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
602
+
603
+ if return_x0:
604
+ return model_mean, posterior_variance, posterior_log_variance, x_recon
605
+ else:
606
+ return model_mean, posterior_variance, posterior_log_variance
607
+
608
+ @torch.no_grad()
609
+ def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False, return_x0=False, \
610
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, **kwargs):
611
+ b, *_, device = *x.shape, x.device
612
+ outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised, return_x0=return_x0, \
613
+ score_corrector=score_corrector, corrector_kwargs=corrector_kwargs, **kwargs)
614
+ if return_x0:
615
+ model_mean, _, model_log_variance, x0 = outputs
616
+ else:
617
+ model_mean, _, model_log_variance = outputs
618
+
619
+ noise = noise_like(x.shape, device, repeat_noise) * temperature
620
+ if noise_dropout > 0.:
621
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
622
+ # no noise when t == 0
623
+ nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
624
+
625
+ if return_x0:
626
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
627
+ else:
628
+ return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
629
+
630
+ @torch.no_grad()
631
+ def p_sample_loop(self, cond, shape, return_intermediates=False, x_T=None, verbose=True, callback=None, \
632
+ timesteps=None, mask=None, x0=None, img_callback=None, start_T=None, log_every_t=None, **kwargs):
633
+
634
+ if not log_every_t:
635
+ log_every_t = self.log_every_t
636
+ device = self.betas.device
637
+ b = shape[0]
638
+ # sample an initial noise
639
+ if x_T is None:
640
+ img = torch.randn(shape, device=device)
641
+ else:
642
+ img = x_T
643
+
644
+ intermediates = [img]
645
+ if timesteps is None:
646
+ timesteps = self.num_timesteps
647
+ if start_T is not None:
648
+ timesteps = min(timesteps, start_T)
649
+
650
+ iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(range(0, timesteps))
651
+
652
+ if mask is not None:
653
+ assert x0 is not None
654
+ assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
655
+
656
+ for i in iterator:
657
+ ts = torch.full((b,), i, device=device, dtype=torch.long)
658
+ if self.shorten_cond_schedule:
659
+ assert self.model.conditioning_key != 'hybrid'
660
+ tc = self.cond_ids[ts].to(cond.device)
661
+ cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
662
+
663
+ img = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, **kwargs)
664
+ if mask is not None:
665
+ img_orig = self.q_sample(x0, ts)
666
+ img = img_orig * mask + (1. - mask) * img
667
+
668
+ if i % log_every_t == 0 or i == timesteps - 1:
669
+ intermediates.append(img)
670
+ if callback: callback(i)
671
+ if img_callback: img_callback(img, i)
672
+
673
+ if return_intermediates:
674
+ return img, intermediates
675
+ return img
676
+
677
+
678
+ class LatentVisualDiffusion(LatentDiffusion):
679
+ def __init__(self, cond_img_config, finegrained=False, random_cond=False, *args, **kwargs):
680
+ super().__init__(*args, **kwargs)
681
+ self.random_cond = random_cond
682
+ self.instantiate_img_embedder(cond_img_config, freeze=True)
683
+ num_tokens = 16 if finegrained else 4
684
+ self.image_proj_model = self.init_projector(use_finegrained=finegrained, num_tokens=num_tokens, input_dim=1024,\
685
+ cross_attention_dim=1024, dim=1280)
686
+
687
+ def instantiate_img_embedder(self, config, freeze=True):
688
+ embedder = instantiate_from_config(config)
689
+ if freeze:
690
+ self.embedder = embedder.eval()
691
+ self.embedder.train = disabled_train
692
+ for param in self.embedder.parameters():
693
+ param.requires_grad = False
694
+
695
+ def init_projector(self, use_finegrained, num_tokens, input_dim, cross_attention_dim, dim):
696
+ if not use_finegrained:
697
+ image_proj_model = ImageProjModel(clip_extra_context_tokens=num_tokens, cross_attention_dim=cross_attention_dim,
698
+ clip_embeddings_dim=input_dim
699
+ )
700
+ else:
701
+ image_proj_model = Resampler(dim=input_dim, depth=4, dim_head=64, heads=12, num_queries=num_tokens,
702
+ embedding_dim=dim, output_dim=cross_attention_dim, ff_mult=4
703
+ )
704
+ return image_proj_model
705
+
706
+ ## Never delete this func: it is used in log_images() and inference stage
707
+ def get_image_embeds(self, batch_imgs):
708
+ ## img: b c h w
709
+ img_token = self.embedder(batch_imgs)
710
+ img_emb = self.image_proj_model(img_token)
711
+ return img_emb
712
+
713
+
714
+ class DiffusionWrapper(pl.LightningModule):
715
+ def __init__(self, diff_model_config, conditioning_key):
716
+ super().__init__()
717
+ self.diffusion_model = instantiate_from_config(diff_model_config)
718
+ self.conditioning_key = conditioning_key
719
+
720
+ def forward(self, x, t, c_concat: list = None, c_crossattn: list = None,
721
+ c_adm=None, s=None, mask=None, **kwargs):
722
+ # temporal_context = fps is foNone
723
+ if self.conditioning_key is None:
724
+ out = self.diffusion_model(x, t)
725
+ elif self.conditioning_key == 'concat':
726
+ xc = torch.cat([x] + c_concat, dim=1)
727
+ out = self.diffusion_model(xc, t, **kwargs)
728
+ elif self.conditioning_key == 'crossattn':
729
+ cc = torch.cat(c_crossattn, 1)
730
+ out = self.diffusion_model(x, t, context=cc, **kwargs)
731
+ elif self.conditioning_key == 'hybrid':
732
+ ## it is just right [b,c,t,h,w]: concatenate in channel dim
733
+ xc = torch.cat([x] + c_concat, dim=1)
734
+ cc = torch.cat(c_crossattn, 1)
735
+ out = self.diffusion_model(xc, t, context=cc)
736
+ elif self.conditioning_key == 'resblockcond':
737
+ cc = c_crossattn[0]
738
+ out = self.diffusion_model(x, t, context=cc)
739
+ elif self.conditioning_key == 'adm':
740
+ cc = c_crossattn[0]
741
+ out = self.diffusion_model(x, t, y=cc)
742
+ elif self.conditioning_key == 'hybrid-adm':
743
+ assert c_adm is not None
744
+ xc = torch.cat([x] + c_concat, dim=1)
745
+ cc = torch.cat(c_crossattn, 1)
746
+ out = self.diffusion_model(xc, t, context=cc, y=c_adm)
747
+ elif self.conditioning_key == 'hybrid-time':
748
+ assert s is not None
749
+ xc = torch.cat([x] + c_concat, dim=1)
750
+ cc = torch.cat(c_crossattn, 1)
751
+ out = self.diffusion_model(xc, t, context=cc, s=s)
752
+ elif self.conditioning_key == 'concat-time-mask':
753
+ # assert s is not None
754
+ # mainlogger.info('x & mask:',x.shape,c_concat[0].shape)
755
+ xc = torch.cat([x] + c_concat, dim=1)
756
+ out = self.diffusion_model(xc, t, context=None, s=s, mask=mask)
757
+ elif self.conditioning_key == 'concat-adm-mask':
758
+ # assert s is not None
759
+ # mainlogger.info('x & mask:',x.shape,c_concat[0].shape)
760
+ if c_concat is not None:
761
+ xc = torch.cat([x] + c_concat, dim=1)
762
+ else:
763
+ xc = x
764
+ out = self.diffusion_model(xc, t, context=None, y=s, mask=mask)
765
+ elif self.conditioning_key == 'hybrid-adm-mask':
766
+ cc = torch.cat(c_crossattn, 1)
767
+ if c_concat is not None:
768
+ xc = torch.cat([x] + c_concat, dim=1)
769
+ else:
770
+ xc = x
771
+ out = self.diffusion_model(xc, t, context=cc, y=s, mask=mask)
772
+ elif self.conditioning_key == 'hybrid-time-adm': # adm means y, e.g., class index
773
+ # assert s is not None
774
+ assert c_adm is not None
775
+ xc = torch.cat([x] + c_concat, dim=1)
776
+ cc = torch.cat(c_crossattn, 1)
777
+ out = self.diffusion_model(xc, t, context=cc, s=s, y=c_adm)
778
+ else:
779
+ raise NotImplementedError()
780
+
781
+ return out
lvdm/models/ddpm3d_cond.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, random
2
+ from einops import rearrange, repeat
3
+
4
+ import torch
5
+ from utils.utils import instantiate_from_config
6
+ from lvdm.models.ddpm3d import LatentDiffusion
7
+ from lvdm.models.samplers.ddim import DDIMSampler
8
+ from lvdm.modules.attention import TemporalTransformer
9
+
10
+ class T2VAdapterDepth(LatentDiffusion):
11
+ def __init__(self, depth_stage_config, adapter_config, *args, **kwargs):
12
+ super().__init__(*args, **kwargs)
13
+ self.depth_stage = instantiate_from_config(depth_stage_config)
14
+ self.adapter = instantiate_from_config(adapter_config)
15
+ self.condtype = adapter_config.cond_name
16
+
17
+ if 'pretrained' in adapter_config:
18
+ self.load_pretrained_adapter(adapter_config.pretrained)
19
+
20
+ for param in self.depth_stage.parameters():
21
+ param.requires_grad = False
22
+
23
+ def prepare_midas_input(self, x):
24
+ # x: (b, c, h, w)
25
+ h, w = x.shape[-2:]
26
+ x_midas = torch.nn.functional.interpolate(x, size=(h, w), mode='bilinear')
27
+ return x_midas
28
+
29
+ @torch.no_grad()
30
+ def get_batch_depth(self, x, target_size):
31
+ # x: (b, c, t, h, w)
32
+ # get depth image, reshape to target_size and normalize to [-1, 1]
33
+ b, c, t, h, w = x.shape
34
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
35
+ x_midas = self.prepare_midas_input(x)
36
+ cond_depth = self.depth_stage(x_midas)
37
+ cond_depth = torch.nn.functional.interpolate(cond_depth, size=target_size, mode='bilinear')
38
+ depth_min, depth_max = torch.amin(cond_depth, dim=[1, 2, 3], keepdim=True), torch.amax(cond_depth, dim=[1, 2, 3], keepdim=True)
39
+ cond_depth = (cond_depth - depth_min) / (depth_max - depth_min + 1e-7)
40
+ cond_depth = 2. * cond_depth - 1.
41
+ cond_depth = rearrange(cond_depth, '(b t) c h w -> b c t h w', b=b, t=t)
42
+ return cond_depth
43
+
44
+ def load_pretrained_adapter(self, adapter_ckpt):
45
+ # load pretrained adapter
46
+ print(">>> Load pretrained adapter checkpoint.")
47
+ try:
48
+ state_dict = torch.load(adapter_ckpt, map_location="cpu")
49
+ if "state_dict" in list(state_dict.keys()):
50
+ state_dict = state_dict["state_dict"]
51
+ self.adapter.load_state_dict(state_dict, strict=True)
52
+ except:
53
+ state_dict = torch.load(adapter_ckpt, map_location=f"cpu")
54
+ if "state_dict" in list(state_dict.keys()):
55
+ state_dict = state_dict["state_dict"]
56
+ model_state_dict = self.adapter.state_dict()
57
+ n_unmatched = 0
58
+ for n, p in model_state_dict.items():
59
+ if p.shape != state_dict[n].shape:
60
+ state_dict.pop(n)
61
+ n_unmatched += 1
62
+ model_state_dict.update(state_dict)
63
+ self.adapter.load_state_dict(model_state_dict)
64
+ print(f"Pretrained adapter IS NOT complete [{n_unmatched} units have unmatched shape].")
65
+
66
+
67
+ class T2IAdapterStyleAS(LatentDiffusion):
68
+ def __init__(self, style_stage_config, adapter_config, *args, **kwargs):
69
+ super(T2IAdapterStyleAS, self).__init__(*args, **kwargs)
70
+ self.adapter = instantiate_from_config(adapter_config)
71
+ self.condtype = adapter_config.cond_name
72
+ ## adapter loading / saving paths
73
+ self.style_stage_model = instantiate_from_config(style_stage_config)
74
+
75
+ self.adapter.create_cross_attention_adapter(self.model.diffusion_model)
76
+
77
+ if 'pretrained' in adapter_config:
78
+ self.load_pretrained_adapter(adapter_config.pretrained)
79
+
80
+ # freeze the style stage model
81
+ for param in self.style_stage_model.parameters():
82
+ param.requires_grad = False
83
+
84
+ def load_pretrained_adapter(self, pretrained):
85
+ state_dict = torch.load(pretrained, map_location=f"cpu")
86
+
87
+ if "state_dict" in list(state_dict.keys()):
88
+ state_dict = state_dict["state_dict"]
89
+ self.adapter.load_state_dict(state_dict, strict=False)
90
+ print('>>> adapter checkpoint loaded.')
91
+
92
+ @torch.no_grad()
93
+ def get_batch_style(self, batch_x):
94
+ b, c, h, w = batch_x.shape
95
+ cond_style = self.style_stage_model(batch_x)
96
+ return cond_style
97
+
98
+ class T2VFintoneStyleAS(T2IAdapterStyleAS):
99
+ def _get_temp_attn_parameters(self):
100
+ temp_attn_params = []
101
+ def register_recr(net_, name):
102
+ if isinstance(net_, TemporalTransformer):
103
+ temp_attn_params.extend(net_.parameters())
104
+ else:
105
+ for sub_name, net in net_.named_children():
106
+ register_recr(net, f"{name}.{sub_name}")
107
+
108
+ for name, net in self.model.diffusion_model.named_children():
109
+ register_recr(net, name)
110
+ return temp_attn_params
111
+
112
+ def _get_temp_attn_state_dict(self):
113
+ temp_attn_state_dict = {}
114
+ def register_recr(net_, name):
115
+ if isinstance(net_, TemporalTransformer):
116
+ temp_attn_state_dict[name] = net_.state_dict()
117
+ else:
118
+ for sub_name, net in net_.named_children():
119
+ register_recr(net, f"{name}.{sub_name}")
120
+
121
+ for name, net in self.model.diffusion_model.named_children():
122
+ register_recr(net, name)
123
+ return temp_attn_state_dict
124
+
125
+ def _load_temp_attn_state_dict(self, temp_attn_state_dict):
126
+ def register_recr(net_, name):
127
+ if isinstance(net_, TemporalTransformer):
128
+ net_.load_state_dict(temp_attn_state_dict[name], strict=True)
129
+ else:
130
+ for sub_name, net in net_.named_children():
131
+ register_recr(net, f"{name}.{sub_name}")
132
+
133
+ for name, net in self.model.diffusion_model.named_children():
134
+ register_recr(net, name)
135
+
136
+ def load_pretrained_temporal(self, pretrained):
137
+ temp_attn_ckpt = torch.load(pretrained, map_location=f"cpu")
138
+ if "state_dict" in list(temp_attn_ckpt.keys()):
139
+ temp_attn_ckpt = temp_attn_ckpt["state_dict"]
140
+ self._load_temp_attn_state_dict(temp_attn_ckpt)
141
+ print('>>> Temporal Attention checkpoint loaded.')
lvdm/models/samplers/__pycache__/ddim.cpython-39.pyc ADDED
Binary file (10.5 kB). View file
 
lvdm/models/samplers/ddim.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from tqdm import tqdm
3
+ import torch
4
+ from lvdm.models.utils_diffusion import make_ddim_sampling_parameters, make_ddim_timesteps
5
+ from lvdm.common import noise_like
6
+
7
+
8
+ class DDIMSampler(object):
9
+ def __init__(self, model, schedule="linear", **kwargs):
10
+ super().__init__()
11
+ self.model = model
12
+ self.ddpm_num_timesteps = model.num_timesteps
13
+ self.schedule = schedule
14
+ self.counter = 0
15
+
16
+ def register_buffer(self, name, attr):
17
+ if type(attr) == torch.Tensor:
18
+ if attr.device != torch.device("cuda"):
19
+ attr = attr.to(torch.device("cuda"))
20
+ setattr(self, name, attr)
21
+
22
+ def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
23
+ self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
24
+ num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
25
+ alphas_cumprod = self.model.alphas_cumprod
26
+ assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
27
+ to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
28
+
29
+ self.register_buffer('betas', to_torch(self.model.betas))
30
+ self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
31
+ self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
32
+ self.use_scale = self.model.use_scale
33
+
34
+ if self.use_scale:
35
+ self.register_buffer('scale_arr', to_torch(self.model.scale_arr))
36
+ ddim_scale_arr = self.scale_arr.cpu()[self.ddim_timesteps]
37
+ self.register_buffer('ddim_scale_arr', ddim_scale_arr)
38
+ ddim_scale_arr = np.asarray([self.scale_arr.cpu()[0]] + self.scale_arr.cpu()[self.ddim_timesteps[:-1]].tolist())
39
+ self.register_buffer('ddim_scale_arr_prev', ddim_scale_arr)
40
+
41
+ # calculations for diffusion q(x_t | x_{t-1}) and others
42
+ self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
43
+ self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
44
+ self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
45
+ self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
46
+ self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
47
+
48
+ # ddim sampling parameters
49
+ ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
50
+ ddim_timesteps=self.ddim_timesteps,
51
+ eta=ddim_eta,verbose=verbose)
52
+ self.register_buffer('ddim_sigmas', ddim_sigmas)
53
+ self.register_buffer('ddim_alphas', ddim_alphas)
54
+ self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
55
+ self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
56
+ sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
57
+ (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
58
+ 1 - self.alphas_cumprod / self.alphas_cumprod_prev))
59
+ self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
60
+
61
+ @torch.no_grad()
62
+ def sample(self,
63
+ S,
64
+ batch_size,
65
+ shape,
66
+ conditioning=None,
67
+ callback=None,
68
+ normals_sequence=None,
69
+ img_callback=None,
70
+ quantize_x0=False,
71
+ eta=0.,
72
+ mask=None,
73
+ x0=None,
74
+ temperature=1.,
75
+ noise_dropout=0.,
76
+ score_corrector=None,
77
+ corrector_kwargs=None,
78
+ verbose=True,
79
+ schedule_verbose=False,
80
+ x_T=None,
81
+ log_every_t=100,
82
+ unconditional_guidance_scale=1.,
83
+ unconditional_conditioning=None,
84
+ # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
85
+ **kwargs
86
+ ):
87
+
88
+ # check condition bs
89
+ if conditioning is not None:
90
+ if isinstance(conditioning, dict):
91
+ try:
92
+ cbs = conditioning[list(conditioning.keys())[0]].shape[0]
93
+ except:
94
+ cbs = conditioning[list(conditioning.keys())[0]][0].shape[0]
95
+
96
+ if cbs != batch_size:
97
+ print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
98
+ else:
99
+ if conditioning.shape[0] != batch_size:
100
+ print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
101
+
102
+ self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=schedule_verbose)
103
+
104
+ # make shape
105
+ if len(shape) == 3:
106
+ C, H, W = shape
107
+ size = (batch_size, C, H, W)
108
+ elif len(shape) == 4:
109
+ C, T, H, W = shape
110
+ size = (batch_size, C, T, H, W)
111
+ # print(f'Data shape for DDIM sampling is {size}, eta {eta}')
112
+
113
+ samples, intermediates = self.ddim_sampling(conditioning, size,
114
+ callback=callback,
115
+ img_callback=img_callback,
116
+ quantize_denoised=quantize_x0,
117
+ mask=mask, x0=x0,
118
+ ddim_use_original_steps=False,
119
+ noise_dropout=noise_dropout,
120
+ temperature=temperature,
121
+ score_corrector=score_corrector,
122
+ corrector_kwargs=corrector_kwargs,
123
+ x_T=x_T,
124
+ log_every_t=log_every_t,
125
+ unconditional_guidance_scale=unconditional_guidance_scale,
126
+ unconditional_conditioning=unconditional_conditioning,
127
+ verbose=verbose,
128
+ **kwargs)
129
+ return samples, intermediates
130
+
131
+ @torch.no_grad()
132
+ def ddim_sampling(self, cond, shape,
133
+ x_T=None, ddim_use_original_steps=False,
134
+ callback=None, timesteps=None, quantize_denoised=False,
135
+ mask=None, x0=None, img_callback=None, log_every_t=100,
136
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
137
+ unconditional_guidance_scale=1., unconditional_conditioning=None, verbose=True,
138
+ cond_tau=1., target_size=None, start_timesteps=None,
139
+ **kwargs):
140
+ device = self.model.betas.device
141
+ b = shape[0]
142
+ if x_T is None:
143
+ img = torch.randn(shape, device=device)
144
+ else:
145
+ img = x_T
146
+
147
+ if timesteps is None:
148
+ timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
149
+ elif timesteps is not None and not ddim_use_original_steps:
150
+ subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
151
+ timesteps = self.ddim_timesteps[:subset_end]
152
+
153
+ intermediates = {'x_inter': [img], 'pred_x0': [img]}
154
+ time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
155
+ total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
156
+ if verbose:
157
+ iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
158
+ else:
159
+ iterator = time_range
160
+
161
+ init_x0 = False
162
+ clean_cond = kwargs.pop("clean_cond", False)
163
+ for i, step in enumerate(iterator):
164
+ index = total_steps - i - 1
165
+ ts = torch.full((b,), step, device=device, dtype=torch.long)
166
+ if start_timesteps is not None:
167
+ assert x0 is not None
168
+ if step > start_timesteps*time_range[0]:
169
+ continue
170
+ elif not init_x0:
171
+ img = self.model.q_sample(x0, ts)
172
+ init_x0 = True
173
+
174
+ # use mask to blend noised original latent (img_orig) & new sampled latent (img)
175
+ if mask is not None:
176
+ assert x0 is not None
177
+ if clean_cond:
178
+ img_orig = x0
179
+ else:
180
+ img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass? <ddim inversion>
181
+ img = img_orig * mask + (1. - mask) * img # keep original & modify use img
182
+
183
+ index_clip = int((1 - cond_tau) * total_steps)
184
+ if index <= index_clip and target_size is not None:
185
+ target_size_ = [target_size[0], target_size[1]//8, target_size[2]//8]
186
+ img = torch.nn.functional.interpolate(
187
+ img,
188
+ size=target_size_,
189
+ mode="nearest",
190
+ )
191
+ outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
192
+ quantize_denoised=quantize_denoised, temperature=temperature,
193
+ noise_dropout=noise_dropout, score_corrector=score_corrector,
194
+ corrector_kwargs=corrector_kwargs,
195
+ unconditional_guidance_scale=unconditional_guidance_scale,
196
+ unconditional_conditioning=unconditional_conditioning,
197
+ x0=x0,
198
+ **kwargs)
199
+
200
+ img, pred_x0 = outs
201
+ if callback: callback(i)
202
+ if img_callback: img_callback(pred_x0, i)
203
+
204
+ if index % log_every_t == 0 or index == total_steps - 1:
205
+ intermediates['x_inter'].append(img)
206
+ intermediates['pred_x0'].append(pred_x0)
207
+
208
+ return img, intermediates
209
+
210
+ @torch.no_grad()
211
+ def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
212
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
213
+ unconditional_guidance_scale=1., unconditional_conditioning=None,
214
+ uc_type=None, conditional_guidance_scale_temporal=None, **kwargs):
215
+ b, *_, device = *x.shape, x.device
216
+ if x.dim() == 5:
217
+ is_video = True
218
+ else:
219
+ is_video = False
220
+
221
+ uncond_kwargs = kwargs.copy()
222
+ uncond_kwargs['append_to_context'] = None
223
+
224
+ if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
225
+ e_t = self.model.apply_model(x, t, c, **kwargs) # unet denoiser
226
+ else:
227
+ # with unconditional condition
228
+ if isinstance(c, torch.Tensor):
229
+ e_t = self.model.apply_model(x, t, c, **kwargs)
230
+ e_t_uncond = self.model.apply_model(x, t, unconditional_conditioning, **uncond_kwargs)
231
+ elif isinstance(c, dict):
232
+ e_t = self.model.apply_model(x, t, c, **kwargs)
233
+ e_t_uncond = self.model.apply_model(x, t, unconditional_conditioning, **uncond_kwargs)
234
+ else:
235
+ raise NotImplementedError
236
+ # text cfg
237
+ if uc_type is None:
238
+ e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)
239
+ else:
240
+ if uc_type == 'cfg_original':
241
+ e_t = e_t + unconditional_guidance_scale * (e_t - e_t_uncond)
242
+ elif uc_type == 'cfg_ours':
243
+ e_t = e_t + unconditional_guidance_scale * (e_t_uncond - e_t)
244
+ else:
245
+ raise NotImplementedError
246
+ # temporal guidance
247
+ if conditional_guidance_scale_temporal is not None:
248
+ e_t_temporal = self.model.apply_model(x, t, c, **kwargs)
249
+ e_t_image = self.model.apply_model(x, t, c, no_temporal_attn=True, **kwargs)
250
+ e_t = e_t + conditional_guidance_scale_temporal * (e_t_temporal - e_t_image)
251
+
252
+ if score_corrector is not None:
253
+ assert self.model.parameterization == "eps"
254
+ e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
255
+
256
+ alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
257
+ alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
258
+ sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
259
+ sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
260
+ # select parameters corresponding to the currently considered timestep
261
+
262
+ if is_video:
263
+ size = (b, 1, 1, 1, 1)
264
+ else:
265
+ size = (b, 1, 1, 1)
266
+ a_t = torch.full(size, alphas[index], device=device)
267
+ a_prev = torch.full(size, alphas_prev[index], device=device)
268
+ sigma_t = torch.full(size, sigmas[index], device=device)
269
+ sqrt_one_minus_at = torch.full(size, sqrt_one_minus_alphas[index],device=device)
270
+
271
+ # current prediction for x_0
272
+ pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
273
+ if quantize_denoised:
274
+ pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
275
+ # direction pointing to x_t
276
+ dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
277
+
278
+ noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
279
+ if noise_dropout > 0.:
280
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
281
+
282
+ alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
283
+ if self.use_scale:
284
+ scale_arr = self.model.scale_arr if use_original_steps else self.ddim_scale_arr
285
+ scale_t = torch.full(size, scale_arr[index], device=device)
286
+ scale_arr_prev = self.model.scale_arr_prev if use_original_steps else self.ddim_scale_arr_prev
287
+ scale_t_prev = torch.full(size, scale_arr_prev[index], device=device)
288
+ pred_x0 /= scale_t
289
+ x_prev = a_prev.sqrt() * scale_t_prev * pred_x0 + dir_xt + noise
290
+ else:
291
+ x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
292
+
293
+ return x_prev, pred_x0
294
+
295
+
296
+ @torch.no_grad()
297
+ def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
298
+ # fast, but does not allow for exact reconstruction
299
+ # t serves as an index to gather the correct alphas
300
+ if use_original_steps:
301
+ sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
302
+ sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
303
+ else:
304
+ sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
305
+ sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
306
+
307
+ if noise is None:
308
+ noise = torch.randn_like(x0)
309
+
310
+ def extract_into_tensor(a, t, x_shape):
311
+ b, *_ = t.shape
312
+ out = a.gather(-1, t)
313
+ return out.reshape(b, *((1,) * (len(x_shape) - 1)))
314
+
315
+ return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +
316
+ extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)
317
+
318
+ @torch.no_grad()
319
+ def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,
320
+ use_original_steps=False):
321
+
322
+ timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
323
+ timesteps = timesteps[:t_start]
324
+
325
+ time_range = np.flip(timesteps)
326
+ total_steps = timesteps.shape[0]
327
+ print(f"Running DDIM Sampling with {total_steps} timesteps")
328
+
329
+ iterator = tqdm(time_range, desc='Decoding image', total=total_steps)
330
+ x_dec = x_latent
331
+ for i, step in enumerate(iterator):
332
+ index = total_steps - i - 1
333
+ ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)
334
+ x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,
335
+ unconditional_guidance_scale=unconditional_guidance_scale,
336
+ unconditional_conditioning=unconditional_conditioning)
337
+ return x_dec
338
+
339
+
340
+ class DDIMStyleSampler(DDIMSampler):
341
+ @torch.no_grad()
342
+ def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
343
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
344
+ unconditional_guidance_scale=1., unconditional_guidance_scale_style=None, unconditional_conditioning=None,
345
+ uc_type=None, conditional_guidance_scale_temporal=None, **kwargs):
346
+ b, *_, device = *x.shape, x.device
347
+ if x.dim() == 5:
348
+ is_video = True
349
+ else:
350
+ is_video = False
351
+ uncond_kwargs = kwargs.copy()
352
+ uncond_kwargs['append_to_context'] = None
353
+
354
+ if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
355
+ e_t = self.model.apply_model(x, t, c, **kwargs) # unet denoiser
356
+ else:
357
+ # with unconditional condition
358
+ if isinstance(c, torch.Tensor):
359
+ e_t = self.model.apply_model(x, t, c, **kwargs)
360
+ e_t_uncond = self.model.apply_model(x, t, unconditional_conditioning, **uncond_kwargs)
361
+ if unconditional_guidance_scale_style is not None:
362
+ e_t_uncond_style = self.model.apply_model(x, t, c, **uncond_kwargs)
363
+ elif isinstance(c, dict):
364
+ e_t = self.model.apply_model(x, t, c, **kwargs)
365
+ e_t_uncond = self.model.apply_model(x, t, unconditional_conditioning, **uncond_kwargs)
366
+ if unconditional_guidance_scale_style is not None:
367
+ e_t_uncond_style = self.model.apply_model(x, t, c, **uncond_kwargs)
368
+ else:
369
+ raise NotImplementedError
370
+
371
+ if unconditional_guidance_scale_style is None:
372
+ e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond)
373
+ else:
374
+ e_t = e_t + unconditional_guidance_scale_style * (e_t - e_t_uncond_style) + \
375
+ unconditional_guidance_scale * (e_t_uncond_style - e_t_uncond)
376
+
377
+ # temporal guidance
378
+ if conditional_guidance_scale_temporal is not None:
379
+ e_t_temporal = self.model.apply_model(x, t, c, **kwargs)
380
+ e_t_image = self.model.apply_model(x, t, c, no_temporal_attn=True, **kwargs)
381
+ e_t = e_t + conditional_guidance_scale_temporal * (e_t_temporal - e_t_image)
382
+
383
+ if score_corrector is not None:
384
+ assert self.model.parameterization == "eps"
385
+ e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
386
+
387
+ alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
388
+ alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
389
+ sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
390
+ sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
391
+ # select parameters corresponding to the currently considered timestep
392
+
393
+ if is_video:
394
+ size = (b, 1, 1, 1, 1)
395
+ else:
396
+ size = (b, 1, 1, 1)
397
+ a_t = torch.full(size, alphas[index], device=device)
398
+ a_prev = torch.full(size, alphas_prev[index], device=device)
399
+ sigma_t = torch.full(size, sigmas[index], device=device)
400
+ sqrt_one_minus_at = torch.full(size, sqrt_one_minus_alphas[index],device=device)
401
+
402
+ # current prediction for x_0
403
+ pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
404
+ # print(f't={t}, pred_x0, min={torch.min(pred_x0)}, max={torch.max(pred_x0)}',file=f)
405
+ if quantize_denoised:
406
+ pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
407
+ # direction pointing to x_t
408
+ dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
409
+ # # norm pred_x0
410
+ # p=2
411
+ # s=()
412
+ # pred_x0 = pred_x0 - torch.max(torch.abs(pred_x0))
413
+
414
+ noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
415
+ if noise_dropout > 0.:
416
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
417
+
418
+ x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
419
+
420
+ return x_prev, pred_x0
lvdm/models/utils_diffusion.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numpy as np
3
+ from einops import repeat
4
+ import torch
5
+ import torch.nn.functional as F
6
+
7
+
8
+ def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
9
+ """
10
+ Create sinusoidal timestep embeddings.
11
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
12
+ These may be fractional.
13
+ :param dim: the dimension of the output.
14
+ :param max_period: controls the minimum frequency of the embeddings.
15
+ :return: an [N x dim] Tensor of positional embeddings.
16
+ """
17
+ if not repeat_only:
18
+ half = dim // 2
19
+ freqs = torch.exp(
20
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
21
+ ).to(device=timesteps.device)
22
+ args = timesteps[:, None].float() * freqs[None]
23
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
24
+ if dim % 2:
25
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
26
+ else:
27
+ embedding = repeat(timesteps, 'b -> b d', d=dim)
28
+ return embedding
29
+
30
+
31
+ def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
32
+ if schedule == "linear":
33
+ betas = (
34
+ torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2
35
+ )
36
+
37
+ elif schedule == "cosine":
38
+ timesteps = (
39
+ torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s
40
+ )
41
+ alphas = timesteps / (1 + cosine_s) * np.pi / 2
42
+ alphas = torch.cos(alphas).pow(2)
43
+ alphas = alphas / alphas[0]
44
+ betas = 1 - alphas[1:] / alphas[:-1]
45
+ betas = np.clip(betas, a_min=0, a_max=0.999)
46
+
47
+ elif schedule == "sqrt_linear":
48
+ betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64)
49
+ elif schedule == "sqrt":
50
+ betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5
51
+ else:
52
+ raise ValueError(f"schedule '{schedule}' unknown.")
53
+ return betas.numpy()
54
+
55
+
56
+ def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True):
57
+ if ddim_discr_method == 'uniform':
58
+ c = num_ddpm_timesteps // num_ddim_timesteps
59
+ ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c)))
60
+ elif ddim_discr_method == 'quad':
61
+ ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int)
62
+ else:
63
+ raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"')
64
+
65
+ # assert ddim_timesteps.shape[0] == num_ddim_timesteps
66
+ # add one to get the final alpha values right (the ones from first scale to data during sampling)
67
+ steps_out = ddim_timesteps + 1
68
+ if verbose:
69
+ print(f'Selected timesteps for ddim sampler: {steps_out}')
70
+ return steps_out
71
+
72
+
73
+ def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):
74
+ # select alphas for computing the variance schedule
75
+ # print(f'ddim_timesteps={ddim_timesteps}, len_alphacums={len(alphacums)}')
76
+ alphas = alphacums[ddim_timesteps]
77
+ alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist())
78
+
79
+ # according the the formula provided in https://arxiv.org/abs/2010.02502
80
+ sigmas = eta * np.sqrt((1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev))
81
+ if verbose:
82
+ print(f'Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}')
83
+ print(f'For the chosen value of eta, which is {eta}, '
84
+ f'this results in the following sigma_t schedule for ddim sampler {sigmas}')
85
+ return sigmas, alphas, alphas_prev
86
+
87
+
88
+ def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
89
+ """
90
+ Create a beta schedule that discretizes the given alpha_t_bar function,
91
+ which defines the cumulative product of (1-beta) over time from t = [0,1].
92
+ :param num_diffusion_timesteps: the number of betas to produce.
93
+ :param alpha_bar: a lambda that takes an argument t from 0 to 1 and
94
+ produces the cumulative product of (1-beta) up to that
95
+ part of the diffusion process.
96
+ :param max_beta: the maximum beta to use; use values lower than 1 to
97
+ prevent singularities.
98
+ """
99
+ betas = []
100
+ for i in range(num_diffusion_timesteps):
101
+ t1 = i / num_diffusion_timesteps
102
+ t2 = (i + 1) / num_diffusion_timesteps
103
+ betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
104
+ return np.array(betas)
lvdm/modules/__pycache__/attention.cpython-39.pyc ADDED
Binary file (24.6 kB). View file
 
lvdm/modules/attention.py ADDED
@@ -0,0 +1,851 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+ import torch
3
+ from torch import nn, einsum
4
+ import torch.nn.functional as F
5
+ from einops import rearrange, repeat
6
+ try:
7
+ import xformers
8
+ import xformers.ops
9
+ XFORMERS_IS_AVAILBLE = True
10
+ except:
11
+ XFORMERS_IS_AVAILBLE = False
12
+ from lvdm.common import (
13
+ checkpoint,
14
+ exists,
15
+ default,
16
+ )
17
+ from lvdm.basics import (
18
+ zero_module,
19
+ )
20
+
21
+ class RelativePosition(nn.Module):
22
+ """ https://github.com/evelinehong/Transformer_Relative_Position_PyTorch/blob/master/relative_position.py """
23
+
24
+ def __init__(self, num_units, max_relative_position):
25
+ super().__init__()
26
+ self.num_units = num_units
27
+ self.max_relative_position = max_relative_position
28
+ self.embeddings_table = nn.Parameter(torch.Tensor(max_relative_position * 2 + 1, num_units))
29
+ nn.init.xavier_uniform_(self.embeddings_table)
30
+
31
+ def forward(self, length_q, length_k):
32
+ device = self.embeddings_table.device
33
+ range_vec_q = torch.arange(length_q, device=device)
34
+ range_vec_k = torch.arange(length_k, device=device)
35
+ distance_mat = range_vec_k[None, :] - range_vec_q[:, None]
36
+ distance_mat_clipped = torch.clamp(distance_mat, -self.max_relative_position, self.max_relative_position)
37
+ final_mat = distance_mat_clipped + self.max_relative_position
38
+ final_mat = final_mat.long()
39
+ embeddings = self.embeddings_table[final_mat]
40
+ return embeddings
41
+
42
+
43
+ class CrossAttention(nn.Module):
44
+
45
+ def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.,
46
+ relative_position=False, temporal_length=None, img_cross_attention=False):
47
+ super().__init__()
48
+ inner_dim = dim_head * heads
49
+ context_dim = default(context_dim, query_dim)
50
+
51
+ self.scale = dim_head**-0.5
52
+ self.heads = heads
53
+ self.dim_head = dim_head
54
+ self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
55
+ self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
56
+ self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
57
+ self.to_out = nn.Sequential(nn.Linear(inner_dim, query_dim), nn.Dropout(dropout))
58
+
59
+ self.image_cross_attention_scale = 1.0
60
+ self.text_context_len = 77
61
+ self.img_cross_attention = img_cross_attention
62
+ if self.img_cross_attention:
63
+ self.to_k_ip = nn.Linear(context_dim, inner_dim, bias=False)
64
+ self.to_v_ip = nn.Linear(context_dim, inner_dim, bias=False)
65
+
66
+ self.relative_position = relative_position
67
+ if self.relative_position:
68
+ assert(temporal_length is not None)
69
+ self.relative_position_k = RelativePosition(num_units=dim_head, max_relative_position=temporal_length)
70
+ self.relative_position_v = RelativePosition(num_units=dim_head, max_relative_position=temporal_length)
71
+ else:
72
+ ## only used for spatial attention, while NOT for temporal attention
73
+ if XFORMERS_IS_AVAILBLE and temporal_length is None:
74
+ self.forward = self.efficient_forward
75
+
76
+ def forward(self, x, context=None, mask=None, is_imgbatch=False, **kwargs):
77
+ h = self.heads
78
+
79
+ q = self.to_q(x)
80
+ context = default(context, x)
81
+ ## considering image token additionally
82
+ if context is not None and self.img_cross_attention:
83
+ context, context_img = context[:,:self.text_context_len,:], context[:,self.text_context_len:,:]
84
+ k = self.to_k(context)
85
+ v = self.to_v(context)
86
+ k_ip = self.to_k_ip(context_img)
87
+ v_ip = self.to_v_ip(context_img)
88
+ else:
89
+ k = self.to_k(context)
90
+ v = self.to_v(context)
91
+
92
+ q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
93
+ sim = torch.einsum('b i d, b j d -> b i j', q, k) * self.scale
94
+ if self.relative_position and not is_imgbatch:
95
+ len_q, len_k, len_v = q.shape[1], k.shape[1], v.shape[1]
96
+ k2 = self.relative_position_k(len_q, len_k)
97
+ sim2 = einsum('b t d, t s d -> b t s', q, k2) * self.scale # TODO check
98
+ sim += sim2
99
+ del k
100
+
101
+ if exists(mask):
102
+ ## feasible for causal attention mask only
103
+ max_neg_value = -torch.finfo(sim.dtype).max
104
+ mask = repeat(mask, 'b i j -> (b h) i j', h=h)
105
+ sim.masked_fill_(~(mask>0.5), max_neg_value)
106
+
107
+ # attention, what we cannot get enough of
108
+ sim = sim.softmax(dim=-1)
109
+ out = torch.einsum('b i j, b j d -> b i d', sim, v)
110
+ if self.relative_position and not is_imgbatch:
111
+ v2 = self.relative_position_v(len_q, len_v)
112
+ out2 = einsum('b t s, t s d -> b t d', sim, v2) # TODO check
113
+ out += out2
114
+ out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
115
+
116
+ ## considering image token additionally
117
+ if context is not None and self.img_cross_attention:
118
+ k_ip, v_ip = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (k_ip, v_ip))
119
+ sim_ip = torch.einsum('b i d, b j d -> b i j', q, k_ip) * self.scale
120
+ del k_ip
121
+ sim_ip = sim_ip.softmax(dim=-1)
122
+ out_ip = torch.einsum('b i j, b j d -> b i d', sim_ip, v_ip)
123
+ out_ip = rearrange(out, '(b h) n d -> b n (h d)', h=h)
124
+ out = out + self.image_cross_attention_scale * out_ip
125
+ del q
126
+
127
+ return self.to_out(out)
128
+
129
+ def efficient_forward(self, x, context=None, mask=None, is_imgbatch=False, **kwargs):
130
+ q = self.to_q(x)
131
+ context = default(context, x)
132
+
133
+ ## considering image token additionally
134
+ if context is not None and self.img_cross_attention:
135
+ context, context_img = context[:,:self.text_context_len,:], context[:,self.text_context_len:,:]
136
+ k = self.to_k(context)
137
+ v = self.to_v(context)
138
+ k_ip = self.to_k_ip(context_img)
139
+ v_ip = self.to_v_ip(context_img)
140
+ else:
141
+ k = self.to_k(context)
142
+ v = self.to_v(context)
143
+
144
+ b, _, _ = q.shape
145
+ q, k, v = map(
146
+ lambda t: t.unsqueeze(3)
147
+ .reshape(b, t.shape[1], self.heads, self.dim_head)
148
+ .permute(0, 2, 1, 3)
149
+ .reshape(b * self.heads, t.shape[1], self.dim_head)
150
+ .contiguous(),
151
+ (q, k, v),
152
+ )
153
+ # actually compute the attention, what we cannot get enough of
154
+ out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=None)
155
+
156
+ ## considering image token additionally
157
+ if context is not None and self.img_cross_attention:
158
+ k_ip, v_ip = map(
159
+ lambda t: t.unsqueeze(3)
160
+ .reshape(b, t.shape[1], self.heads, self.dim_head)
161
+ .permute(0, 2, 1, 3)
162
+ .reshape(b * self.heads, t.shape[1], self.dim_head)
163
+ .contiguous(),
164
+ (k_ip, v_ip),
165
+ )
166
+ out_ip = xformers.ops.memory_efficient_attention(q, k_ip, v_ip, attn_bias=None, op=None)
167
+ out_ip = (
168
+ out_ip.unsqueeze(0)
169
+ .reshape(b, self.heads, out.shape[1], self.dim_head)
170
+ .permute(0, 2, 1, 3)
171
+ .reshape(b, out.shape[1], self.heads * self.dim_head)
172
+ )
173
+
174
+ if exists(mask):
175
+ raise NotImplementedError
176
+ out = (
177
+ out.unsqueeze(0)
178
+ .reshape(b, self.heads, out.shape[1], self.dim_head)
179
+ .permute(0, 2, 1, 3)
180
+ .reshape(b, out.shape[1], self.heads * self.dim_head)
181
+ )
182
+ if context is not None and self.img_cross_attention:
183
+ out = out + self.image_cross_attention_scale * out_ip
184
+ return self.to_out(out)
185
+
186
+
187
+ class BasicTransformerBlock(nn.Module):
188
+
189
+ def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True,
190
+ disable_self_attn=False, attention_cls=None, img_cross_attention=False):
191
+ super().__init__()
192
+ attn_cls = CrossAttention if attention_cls is None else attention_cls
193
+ self.disable_self_attn = disable_self_attn
194
+ self.attn1 = attn_cls(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout,
195
+ context_dim=context_dim if self.disable_self_attn else None)
196
+ self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
197
+ self.attn2 = attn_cls(query_dim=dim, context_dim=context_dim, heads=n_heads, dim_head=d_head, dropout=dropout,
198
+ img_cross_attention=img_cross_attention)
199
+ self.norm1 = nn.LayerNorm(dim)
200
+ self.norm2 = nn.LayerNorm(dim)
201
+ self.norm3 = nn.LayerNorm(dim)
202
+ self.checkpoint = checkpoint
203
+
204
+ def forward(self, x, context=None, mask=None, emb=None, scale_scalar=None, is_imgbatch=False):
205
+ ## implementation tricks: because checkpointing doesn't support non-tensor (e.g. None or scalar) arguments
206
+ input_tuple = (x,) ## should not be (x), otherwise *input_tuple will decouple x into multiple arguments
207
+ if context is not None:
208
+ input_tuple = (x, context, None, emb, scale_scalar, is_imgbatch)
209
+ if mask is not None:
210
+ forward_mask = partial(self._forward, mask=mask, is_imgbatch=is_imgbatch)
211
+ return checkpoint(forward_mask, (x,), self.parameters(), self.checkpoint)
212
+ if context is not None and mask is not None:
213
+ input_tuple = (x, context, mask, emb, scale_scalar, is_imgbatch)
214
+ return checkpoint(self._forward, input_tuple, self.parameters(), self.checkpoint)
215
+
216
+ def _forward(self, x, context=None, mask=None, emb=None, scale_scalar=None, is_imgbatch=False):
217
+ x = self.attn1(self.norm1(x), context=context if self.disable_self_attn else None, mask=mask, emb=emb, scale_scalar=scale_scalar, is_imgbatch=is_imgbatch) + x
218
+ x = self.attn2(self.norm2(x), context=context, mask=mask, emb=emb, scale_scalar=scale_scalar, is_imgbatch=is_imgbatch) + x
219
+ x = self.ff(self.norm3(x)) + x
220
+ return x
221
+
222
+
223
+ class SpatialTransformer(nn.Module):
224
+ """
225
+ Transformer block for image-like data in spatial axis.
226
+ First, project the input (aka embedding)
227
+ and reshape to b, t, d.
228
+ Then apply standard transformer action.
229
+ Finally, reshape to image
230
+ NEW: use_linear for more efficiency instead of the 1x1 convs
231
+ """
232
+
233
+ def __init__(self, in_channels, n_heads, d_head, depth=1, dropout=0., context_dim=None,
234
+ use_checkpoint=True, disable_self_attn=False, use_linear=False, img_cross_attention=False):
235
+ super().__init__()
236
+ self.in_channels = in_channels
237
+ inner_dim = n_heads * d_head
238
+ self.norm = torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
239
+ if not use_linear:
240
+ self.proj_in = nn.Conv2d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
241
+ else:
242
+ self.proj_in = nn.Linear(in_channels, inner_dim)
243
+
244
+ self.transformer_blocks = nn.ModuleList([
245
+ BasicTransformerBlock(
246
+ inner_dim,
247
+ n_heads,
248
+ d_head,
249
+ dropout=dropout,
250
+ context_dim=context_dim,
251
+ img_cross_attention=img_cross_attention,
252
+ disable_self_attn=disable_self_attn,
253
+ checkpoint=use_checkpoint) for d in range(depth)
254
+ ])
255
+ if not use_linear:
256
+ self.proj_out = zero_module(nn.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0))
257
+ else:
258
+ self.proj_out = zero_module(nn.Linear(inner_dim, in_channels))
259
+ self.use_linear = use_linear
260
+
261
+
262
+ def forward(self, x, context=None, emb=None, scale_scalar=None):
263
+ b, c, h, w = x.shape
264
+ x_in = x
265
+ x = self.norm(x)
266
+ if not self.use_linear:
267
+ x = self.proj_in(x)
268
+ x = rearrange(x, 'b c h w -> b (h w) c').contiguous()
269
+ if self.use_linear:
270
+ x = self.proj_in(x)
271
+ for i, block in enumerate(self.transformer_blocks):
272
+ x = block(x, context=context, emb=emb, scale_scalar=scale_scalar)
273
+ if self.use_linear:
274
+ x = self.proj_out(x)
275
+ x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous()
276
+ if not self.use_linear:
277
+ x = self.proj_out(x)
278
+ return x + x_in
279
+
280
+
281
+ class TemporalTransformer(nn.Module):
282
+ """
283
+ Transformer block for image-like data in temporal axis.
284
+ First, reshape to b, t, d.
285
+ Then apply standard transformer action.
286
+ Finally, reshape to image
287
+ """
288
+ def __init__(self, in_channels, n_heads, d_head, depth=1, dropout=0., context_dim=None,
289
+ use_checkpoint=True, use_linear=False, only_self_att=True, causal_attention=False,
290
+ relative_position=False, temporal_length=None):
291
+ super().__init__()
292
+ self.only_self_att = only_self_att
293
+ self.relative_position = relative_position
294
+ self.causal_attention = causal_attention
295
+ self.in_channels = in_channels
296
+ inner_dim = n_heads * d_head
297
+ self.norm = torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
298
+ self.proj_in = nn.Conv1d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
299
+ if not use_linear:
300
+ self.proj_in = nn.Conv1d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
301
+ else:
302
+ self.proj_in = nn.Linear(in_channels, inner_dim)
303
+
304
+ if relative_position:
305
+ assert(temporal_length is not None)
306
+ attention_cls = partial(CrossAttention, relative_position=True, temporal_length=temporal_length)
307
+ else:
308
+ attention_cls = None
309
+ if self.causal_attention:
310
+ assert(temporal_length is not None)
311
+ self.mask = torch.tril(torch.ones([1, temporal_length, temporal_length]))
312
+
313
+ if self.only_self_att:
314
+ context_dim = None
315
+ self.transformer_blocks = nn.ModuleList([
316
+ BasicTransformerBlock(
317
+ inner_dim,
318
+ n_heads,
319
+ d_head,
320
+ dropout=dropout,
321
+ context_dim=context_dim,
322
+ attention_cls=attention_cls,
323
+ checkpoint=use_checkpoint) for d in range(depth)
324
+ ])
325
+ if not use_linear:
326
+ self.proj_out = zero_module(nn.Conv1d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0))
327
+ else:
328
+ self.proj_out = zero_module(nn.Linear(inner_dim, in_channels))
329
+ self.use_linear = use_linear
330
+
331
+ def forward(self, x, context=None, is_imgbatch=False, emb=None):
332
+ b, c, t, h, w = x.shape
333
+ x_in = x
334
+ x = self.norm(x)
335
+ x = rearrange(x, 'b c t h w -> (b h w) c t').contiguous()
336
+ if not self.use_linear:
337
+ x = self.proj_in(x)
338
+ x = rearrange(x, 'bhw c t -> bhw t c').contiguous()
339
+ if self.use_linear:
340
+ x = self.proj_in(x)
341
+
342
+ if is_imgbatch:
343
+ maks = torch.eye(t).unsqueeze(0)
344
+ maks = maks.to(x.device)
345
+ maks = repeat(maks, 'l i j -> (l bhw) i j', bhw=b*h*w)
346
+ elif self.causal_attention:
347
+ mask = self.mask.to(x.device)
348
+ mask = repeat(mask, 'l i j -> (l bhw) i j', bhw=b*h*w)
349
+ else:
350
+ mask = None
351
+
352
+ if self.only_self_att:
353
+ ## note: if no context is given, cross-attention defaults to self-attention
354
+ for i, block in enumerate(self.transformer_blocks):
355
+ x = block(x, mask=mask)
356
+ x = rearrange(x, '(b hw) t c -> b hw t c', b=b).contiguous()
357
+ else:
358
+ x = rearrange(x, '(b hw) t c -> b hw t c', b=b).contiguous()
359
+ context = rearrange(context, '(b t) l con -> b t l con', t=t).contiguous()
360
+ for i, block in enumerate(self.transformer_blocks):
361
+ # calculate each batch one by one (since number in shape could not greater then 65,535 for some package)
362
+ for j in range(b):
363
+ context_j = repeat(
364
+ context[j],
365
+ 't l con -> (t r) l con', r=(h * w) // t, t=t).contiguous()
366
+ ## note: causal mask will not applied in cross-attention case
367
+ x[j] = block(x[j], context=context_j, is_imgbatch=is_imgbatch)
368
+
369
+ if self.use_linear:
370
+ x = self.proj_out(x)
371
+ x = rearrange(x, 'b (h w) t c -> b c t h w', h=h, w=w).contiguous()
372
+ if not self.use_linear:
373
+ x = rearrange(x, 'b hw t c -> (b hw) c t').contiguous()
374
+ x = self.proj_out(x)
375
+ x = rearrange(x, '(b h w) c t -> b c t h w', b=b, h=h, w=w).contiguous()
376
+
377
+ return x + x_in
378
+
379
+
380
+ class GEGLU(nn.Module):
381
+ def __init__(self, dim_in, dim_out):
382
+ super().__init__()
383
+ self.proj = nn.Linear(dim_in, dim_out * 2)
384
+
385
+ def forward(self, x):
386
+ x, gate = self.proj(x).chunk(2, dim=-1)
387
+ return x * F.gelu(gate)
388
+
389
+
390
+ class FeedForward(nn.Module):
391
+ def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
392
+ super().__init__()
393
+ inner_dim = int(dim * mult)
394
+ dim_out = default(dim_out, dim)
395
+ project_in = nn.Sequential(
396
+ nn.Linear(dim, inner_dim),
397
+ nn.GELU()
398
+ ) if not glu else GEGLU(dim, inner_dim)
399
+
400
+ self.net = nn.Sequential(
401
+ project_in,
402
+ nn.Dropout(dropout),
403
+ nn.Linear(inner_dim, dim_out)
404
+ )
405
+
406
+ def forward(self, x):
407
+ return self.net(x)
408
+
409
+
410
+ class LinearAttention(nn.Module):
411
+ def __init__(self, dim, heads=4, dim_head=32):
412
+ super().__init__()
413
+ self.heads = heads
414
+ hidden_dim = dim_head * heads
415
+ self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias = False)
416
+ self.to_out = nn.Conv2d(hidden_dim, dim, 1)
417
+
418
+ def forward(self, x):
419
+ b, c, h, w = x.shape
420
+ qkv = self.to_qkv(x)
421
+ q, k, v = rearrange(qkv, 'b (qkv heads c) h w -> qkv b heads c (h w)', heads = self.heads, qkv=3)
422
+ k = k.softmax(dim=-1)
423
+ context = torch.einsum('bhdn,bhen->bhde', k, v)
424
+ out = torch.einsum('bhde,bhdn->bhen', context, q)
425
+ out = rearrange(out, 'b heads c (h w) -> b (heads c) h w', heads=self.heads, h=h, w=w)
426
+ return self.to_out(out)
427
+
428
+
429
+ class SpatialSelfAttention(nn.Module):
430
+ def __init__(self, in_channels):
431
+ super().__init__()
432
+ self.in_channels = in_channels
433
+
434
+ self.norm = torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
435
+ self.q = torch.nn.Conv2d(in_channels,
436
+ in_channels,
437
+ kernel_size=1,
438
+ stride=1,
439
+ padding=0)
440
+ self.k = torch.nn.Conv2d(in_channels,
441
+ in_channels,
442
+ kernel_size=1,
443
+ stride=1,
444
+ padding=0)
445
+ self.v = torch.nn.Conv2d(in_channels,
446
+ in_channels,
447
+ kernel_size=1,
448
+ stride=1,
449
+ padding=0)
450
+ self.proj_out = torch.nn.Conv2d(in_channels,
451
+ in_channels,
452
+ kernel_size=1,
453
+ stride=1,
454
+ padding=0)
455
+
456
+ def forward(self, x):
457
+ h_ = x
458
+ h_ = self.norm(h_)
459
+ q = self.q(h_)
460
+ k = self.k(h_)
461
+ v = self.v(h_)
462
+
463
+ # compute attention
464
+ b,c,h,w = q.shape
465
+ q = rearrange(q, 'b c h w -> b (h w) c')
466
+ k = rearrange(k, 'b c h w -> b c (h w)')
467
+ w_ = torch.einsum('bij,bjk->bik', q, k)
468
+
469
+ w_ = w_ * (int(c)**(-0.5))
470
+ w_ = torch.nn.functional.softmax(w_, dim=2)
471
+
472
+ # attend to values
473
+ v = rearrange(v, 'b c h w -> b c (h w)')
474
+ w_ = rearrange(w_, 'b i j -> b j i')
475
+ h_ = torch.einsum('bij,bjk->bik', v, w_)
476
+ h_ = rearrange(h_, 'b c (h w) -> b c h w', h=h)
477
+ h_ = self.proj_out(h_)
478
+
479
+ return x+h_
480
+
481
+
482
+ class CrossAttentionProcessor(nn.Module):
483
+ def forward(self, attn, x, context=None, mask=None, is_imgbatch=False):
484
+ h = attn.heads
485
+ q = attn.to_q(x)
486
+ context = default(context, x)
487
+ k = attn.to_k(context)
488
+ v = attn.to_v(context)
489
+
490
+ q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
491
+ sim = torch.einsum('b i d, b j d -> b i j', q, k) * attn.scale
492
+ if attn.relative_position and not is_imgbatch:
493
+ len_q, len_k, len_v = q.shape[1], k.shape[1], v.shape[1]
494
+ k2 = attn.relative_position_k(len_q, len_k)
495
+ sim2 = einsum('b t d, t s d -> b t s', q, k2) * attn.scale # TODO check
496
+ sim += sim2
497
+ del q, k
498
+
499
+ if exists(mask):
500
+ raise NotImplementedError
501
+
502
+ # attention, what we cannot get enough of
503
+ sim = sim.softmax(dim=-1)
504
+
505
+ out = torch.einsum('b i j, b j d -> b i d', sim, v)
506
+ if attn.relative_position and not is_imgbatch:
507
+ v2 = attn.relative_position_v(len_q, len_v)
508
+ out2 = einsum('b t s, t s d -> b t d', sim, v2) # TODO check
509
+ out += out2
510
+ out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
511
+ return attn.to_out(out)
512
+
513
+ def efficient_forward(self, attn, x, context=None, mask=None, **kwargs):
514
+ q = attn.to_q(x)
515
+ context = default(context, x)
516
+ k = attn.to_k(context)
517
+ v = attn.to_v(context)
518
+
519
+ b, _, _ = q.shape
520
+
521
+ q, k, v = map(
522
+ lambda t: t.unsqueeze(3)
523
+ .reshape(b, t.shape[1], attn.heads, attn.dim_head)
524
+ .permute(0, 2, 1, 3)
525
+ .reshape(b * attn.heads, t.shape[1], attn.dim_head)
526
+ .contiguous(),
527
+ (q, k, v),
528
+ )
529
+ # actually compute the attention, what we cannot get enough of
530
+ out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=None)
531
+
532
+ if exists(mask):
533
+ raise NotImplementedError
534
+ out = (
535
+ out.unsqueeze(0)
536
+ .reshape(b, attn.heads, out.shape[1], attn.dim_head)
537
+ .permute(0, 2, 1, 3)
538
+ .reshape(b, out.shape[1], attn.heads * attn.dim_head)
539
+ )
540
+ return attn.to_out(out)
541
+
542
+ def __call__(self, **kwargs):
543
+ if XFORMERS_IS_AVAILBLE:
544
+ return self.efficient_forward(**kwargs)
545
+ else:
546
+ return self.forward(**kwargs)
547
+
548
+
549
+ def register_attn_processor(unet):
550
+ Attn_processor = {}
551
+ def attn_forward(self):
552
+ assert hasattr(self, "processor")
553
+ def forward(x, context=None, mask=None, **kwargs):
554
+ return self.processor(self, x, context, mask, **kwargs)
555
+
556
+ return forward
557
+
558
+ def register_recr_in_block(net_, name):
559
+ """
560
+ find and register cross attention in the SpatialTransformer block
561
+ assert only one cross attention in each block
562
+ """
563
+ if net_.__class__.__name__ == 'BasicTransformerBlock':
564
+ processor_name = f"{name}.attn2.processor"
565
+ net_.attn2.processor = CrossAttentionProcessor()
566
+ net_.attn2.forward = attn_forward(net_.attn2)
567
+ Attn_processor.update({processor_name: net_.attn2.processor})
568
+ print(f"Register Attention Processor in {processor_name} successfully!")
569
+ elif hasattr(net_, 'children'):
570
+ for sub_name, net in net_.named_children():
571
+ register_recr_in_block(net, f"{name}.{sub_name}")
572
+ return
573
+
574
+ def register_recr(net_, name):
575
+ # find SpatialTransformer block
576
+ if isinstance(net_, SpatialTransformer):
577
+ register_recr_in_block(net_, name)
578
+ elif hasattr(net_, 'children'):
579
+ for sub_name, net in net_.named_children():
580
+ register_recr(net, f"{name}.{sub_name}")
581
+
582
+
583
+ for name, net in unet.named_children():
584
+ register_recr(net, name)
585
+
586
+ print("==========================================")
587
+ print(f"Totally {len(Attn_processor.keys())} processors are registered successfully! hiahiahia")
588
+
589
+ return Attn_processor
590
+
591
+
592
+ def set_attn_processor(unet, processor):
593
+
594
+ def register_recr(net_, name):
595
+ if hasattr(net_, "processor"):
596
+ net_.processor = processor[f"{name}.processor"]
597
+ print(f"Set New Attention Processor in {name}.processor successfully!")
598
+
599
+ else:
600
+ for sub_name, net in net_.named_children():
601
+ register_recr(net, f"{name}.{sub_name}")
602
+
603
+ for name, net in unet.named_children():
604
+ register_recr(net, name)
605
+
606
+ return
607
+
608
+
609
+ def get_attn_processor(unet):
610
+ processor_dict = {}
611
+ def register_recr(net_, name):
612
+ if hasattr(net_, "processor"):
613
+ processor_dict[f"{name}.processor"] = net_.processor
614
+
615
+ else:
616
+ for sub_name, net in net_.named_children():
617
+ register_recr(net, f"{name}.{sub_name}")
618
+
619
+ for name, net in unet.named_children():
620
+ register_recr(net, name)
621
+
622
+ return processor_dict
623
+
624
+
625
+ class DualCrossAttnProcessor(nn.Module):
626
+ def __init__(self, context_dim, inner_dim, scale=1.0, state_dict=None, use_norm=False, layer_idx=0):
627
+ super().__init__()
628
+ self.to_k_style = nn.Linear(context_dim, inner_dim, bias=False)
629
+ self.to_v_style = nn.Linear(context_dim, inner_dim, bias=False)
630
+ self.scale = scale
631
+ self.layer_idx = layer_idx
632
+
633
+ if state_dict is not None:
634
+ self.to_k_style.load_state_dict(state_dict['k'], strict=True)
635
+ self.to_v_style.load_state_dict(state_dict['v'], strict=True)
636
+
637
+ self.use_norm = use_norm
638
+ if use_norm:
639
+ self.norm_style = nn.LayerNorm(inner_dim)
640
+ else:
641
+ self.norm_style = lambda x: x
642
+
643
+ def forward(self, attn, x, context=None, mask=None, context_style=None, **kwargs):
644
+ h = attn.heads
645
+ q = attn.to_q(x)
646
+ context = default(context, x)
647
+ k = attn.to_k(context)
648
+ v = attn.to_v(context)
649
+
650
+ q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
651
+ sim = torch.einsum('b i d, b j d -> b i j', q, k) * attn.scale
652
+
653
+ if exists(mask):
654
+ ## feasible for causal attention mask only
655
+ max_neg_value = -torch.finfo(sim.dtype).max
656
+ mask = repeat(mask, 'b i j -> (b h) i j', h=h)
657
+ sim.masked_fill_(~(mask>0.5), max_neg_value)
658
+
659
+ # attention, what we cannot get enough of
660
+ sim = sim.softmax(dim=-1)
661
+
662
+ out = torch.einsum('b i j, b j d -> b i d', sim, v)
663
+ out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
664
+
665
+ # for another cross attention
666
+ if context_style is not None:
667
+ k_style = self.to_k_style(context_style)
668
+ v_style = self.to_v_style(context_style)
669
+
670
+ k_style, v_style = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (k_style, v_style))
671
+ sim_style = torch.einsum('b i d, b j d -> b i j', q, k_style)
672
+ sim_style = sim_style.softmax(dim=-1)
673
+ out_style = torch.einsum('b i j, b j d -> b i d', sim_style, v_style)
674
+ out_style = rearrange(out_style, '(b h) n d -> b n (h d)', h=h)
675
+
676
+ out = out + out_style
677
+
678
+ return attn.to_out(out)
679
+
680
+ def efficient_forward(self, attn, x, context=None, mask=None, context_style=None, **kwargs):
681
+ q = attn.to_q(x)
682
+ context = default(context, x)
683
+ k = attn.to_k(context)
684
+ v = attn.to_v(context)
685
+
686
+ b, _, _ = q.shape
687
+
688
+ q, k, v = map(
689
+ lambda t: t.unsqueeze(3)
690
+ .reshape(b, t.shape[1], attn.heads, attn.dim_head)
691
+ .permute(0, 2, 1, 3)
692
+ .reshape(b * attn.heads, t.shape[1], attn.dim_head)
693
+ .contiguous(),
694
+ (q, k, v),
695
+ )
696
+ out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=None)
697
+
698
+ out = (
699
+ out.unsqueeze(0)
700
+ .reshape(b, attn.heads, out.shape[1], attn.dim_head)
701
+ .permute(0, 2, 1, 3)
702
+ .reshape(b, out.shape[1], attn.heads * attn.dim_head)
703
+ )
704
+
705
+
706
+ if context_style is not None:
707
+ k_style = self.to_k_style(context_style)
708
+ v_style = self.to_v_style(context_style)
709
+
710
+ k_style, v_style = map(
711
+ lambda t: t.unsqueeze(3)
712
+ .reshape(b, t.shape[1], attn.heads, attn.dim_head)
713
+ .permute(0, 2, 1, 3)
714
+ .reshape(b * attn.heads, t.shape[1], attn.dim_head)
715
+ .contiguous(),
716
+ (k_style, v_style),
717
+ )
718
+ out_style = xformers.ops.memory_efficient_attention(q, k_style, v_style, attn_bias=None, op=None)
719
+
720
+ out_style = (
721
+ out_style.unsqueeze(0)
722
+ .reshape(b, attn.heads, out_style.shape[1], attn.dim_head)
723
+ .permute(0, 2, 1, 3)
724
+ .reshape(b, out_style.shape[1], attn.heads * attn.dim_head)
725
+ )
726
+
727
+ out = out + out_style
728
+
729
+ return attn.to_out(out)
730
+
731
+ def __call__(self, attn, x, context=None, mask=None, **kwargs):
732
+ # print("Hello! I am working!")
733
+
734
+ # separate the context
735
+ # print(context.shape)
736
+ if context.shape[1] == 77:
737
+ context_style = None
738
+ else:
739
+ context_style = context[:, 77:, :]
740
+ context = context[:, :77, :]
741
+
742
+ if XFORMERS_IS_AVAILBLE:
743
+ return self.efficient_forward(attn, x, context=context, mask=mask, context_style=context_style, **kwargs)
744
+ else:
745
+ return self.forward(attn, x, context=context, mask=mask, context_style=context_style, **kwargs)
746
+
747
+
748
+
749
+ class DualCrossAttnProcessorAS(DualCrossAttnProcessor):
750
+ def forward(self, attn, x, context=None, mask=None, context_style=None, scale_scalar=None, **kwargs):
751
+ h = attn.heads
752
+ q = attn.to_q(x)
753
+ context = default(context, x)
754
+ k = attn.to_k(context)
755
+ v = attn.to_v(context)
756
+
757
+ q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
758
+ sim = torch.einsum('b i d, b j d -> b i j', q, k) * attn.scale
759
+
760
+ # attention, what we cannot get enough of
761
+ sim = sim.softmax(dim=-1)
762
+
763
+ out = torch.einsum('b i j, b j d -> b i d', sim, v)
764
+ out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
765
+
766
+ # for another cross attention
767
+ if context_style is not None:
768
+ k_style = self.to_k_style(context_style)
769
+ v_style = self.to_v_style(context_style)
770
+
771
+ k_style, v_style = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (k_style, v_style))
772
+ sim_style = torch.einsum('b i d, b j d -> b i j', q, k_style)
773
+ sim_style = sim_style.softmax(dim=-1)
774
+ out_style = torch.einsum('b i j, b j d -> b i d', sim_style, v_style)
775
+ out_style = rearrange(out_style, '(b h) n d -> b n (h d)', h=h)
776
+
777
+ if scale_scalar is not None:
778
+ scale = 1 + scale_scalar[:, self.layer_idx]
779
+ scale = scale[:, None]
780
+ else:
781
+ scale = 1.0
782
+
783
+ if self.use_norm:
784
+ out_style = self.norm_style(out_style)
785
+
786
+ out = out + scale * out_style * self.scale
787
+
788
+ return attn.to_out(out)
789
+
790
+ def efficient_forward(self, attn, x, context=None, mask=None, context_style=None, scale_scalar=None, **kwargs):
791
+ q = attn.to_q(x)
792
+ context = default(context, x)
793
+ k = attn.to_k(context)
794
+ v = attn.to_v(context)
795
+
796
+ b, _, _ = q.shape
797
+
798
+ q, k, v = map(
799
+ lambda t: t.unsqueeze(3)
800
+ .reshape(b, t.shape[1], attn.heads, attn.dim_head)
801
+ .permute(0, 2, 1, 3)
802
+ .reshape(b * attn.heads, t.shape[1], attn.dim_head)
803
+ .contiguous(),
804
+ (q, k, v),
805
+ )
806
+ out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=None)
807
+
808
+ out = (
809
+ out.unsqueeze(0)
810
+ .reshape(b, attn.heads, out.shape[1], attn.dim_head)
811
+ .permute(0, 2, 1, 3)
812
+ .reshape(b, out.shape[1], attn.heads * attn.dim_head)
813
+ )
814
+
815
+ if context_style is not None:
816
+ k_style = self.to_k_style(context_style)
817
+ v_style = self.to_v_style(context_style)
818
+
819
+ k_style, v_style = map(
820
+ lambda t: t.unsqueeze(3)
821
+ .reshape(b, t.shape[1], attn.heads, attn.dim_head)
822
+ .permute(0, 2, 1, 3)
823
+ .reshape(b * attn.heads, t.shape[1], attn.dim_head)
824
+ .contiguous(),
825
+ (k_style, v_style),
826
+ )
827
+ out_style = xformers.ops.memory_efficient_attention(q, k_style, v_style, attn_bias=None, op=None)
828
+
829
+ out_style = (
830
+ out_style.unsqueeze(0)
831
+ .reshape(b, attn.heads, out_style.shape[1], attn.dim_head)
832
+ .permute(0, 2, 1, 3)
833
+ .reshape(b, out_style.shape[1], attn.heads * attn.dim_head)
834
+ )
835
+
836
+ if scale_scalar is not None:
837
+ scale = 1 + scale_scalar[:, self.layer_idx]
838
+ scale = scale[:, None]
839
+ else:
840
+ scale = 1.0
841
+
842
+
843
+ if self.use_norm:
844
+ out_style = self.norm_style(out_style)
845
+
846
+ out = out + scale * out_style * self.scale
847
+
848
+ return attn.to_out(out)
849
+
850
+
851
+
lvdm/modules/encoders/__pycache__/adapter.cpython-39.pyc ADDED
Binary file (6.75 kB). View file
 
lvdm/modules/encoders/__pycache__/arch_transformer.cpython-39.pyc ADDED
Binary file (8.34 kB). View file
 
lvdm/modules/encoders/__pycache__/condition.cpython-39.pyc ADDED
Binary file (15.2 kB). View file
 
lvdm/modules/encoders/__pycache__/condition2.cpython-39.pyc ADDED
Binary file (14.5 kB). View file
 
lvdm/modules/encoders/__pycache__/ip_resampler.cpython-39.pyc ADDED
Binary file (3.97 kB). View file
 
lvdm/modules/encoders/__pycache__/transformers.cpython-39.pyc ADDED
Binary file (8.36 kB). View file
 
lvdm/modules/encoders/adapter.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from collections import OrderedDict
4
+ from lvdm.basics import (
5
+ zero_module,
6
+ conv_nd,
7
+ avg_pool_nd
8
+ )
9
+ from einops import rearrange
10
+ from lvdm.modules.attention import register_attn_processor, set_attn_processor, DualCrossAttnProcessor, get_attn_processor
11
+ from lvdm.modules.attention import DualCrossAttnProcessorAS
12
+ from utils.utils import instantiate_from_config
13
+
14
+ from lvdm.modules.encoders.arch_transformer import Transformer
15
+
16
+
17
+ class StyleTransformer(nn.Module):
18
+ def __init__(self, in_dim=1024, out_dim=1024, num_heads=8, num_tokens=4, n_layers=2):
19
+ super().__init__()
20
+ scale = in_dim ** -0.5
21
+ self.num_tokens = num_tokens
22
+ self.style_emb = nn.Parameter(torch.randn(1, num_tokens, in_dim) * scale)
23
+ self.transformer_blocks = Transformer(
24
+ width=in_dim,
25
+ layers=n_layers,
26
+ heads=num_heads,
27
+ )
28
+ self.ln1 = nn.LayerNorm(in_dim)
29
+ self.ln2 = nn.LayerNorm(in_dim)
30
+ self.proj = nn.Parameter(torch.randn(in_dim, out_dim) * scale)
31
+
32
+ def forward(self, x):
33
+ style_emb = self.style_emb.repeat(x.shape[0], 1, 1)
34
+ x = torch.cat([style_emb, x], dim=1)
35
+ # x = torch.cat([x, style_emb], dim=1)
36
+ x = self.ln1(x)
37
+
38
+ x = x.permute(1, 0, 2)
39
+ x = self.transformer_blocks(x)
40
+ x = x.permute(1, 0, 2)
41
+
42
+ x = self.ln2(x[:, :self.num_tokens, :])
43
+ x = x @ self.proj
44
+ return x
45
+
46
+
47
+ class ScaleEncoder(nn.Module):
48
+ def __init__(self, in_dim=1024, out_dim=1, num_heads=8, num_tokens=16, n_layers=2):
49
+ super().__init__()
50
+ scale = in_dim ** -0.5
51
+ self.num_tokens = num_tokens
52
+ self.scale_emb = nn.Parameter(torch.randn(1, num_tokens, in_dim) * scale)
53
+ self.transformer_blocks = Transformer(
54
+ width=in_dim,
55
+ layers=n_layers,
56
+ heads=num_heads,
57
+ )
58
+ self.ln1 = nn.LayerNorm(in_dim)
59
+ self.ln2 = nn.LayerNorm(in_dim)
60
+
61
+ self.out = nn.Sequential(
62
+ nn.Linear(in_dim, 32),
63
+ nn.GELU(),
64
+ nn.Linear(32, out_dim),
65
+ nn.Tanh(),
66
+ )
67
+
68
+ def forward(self, x):
69
+ scale_emb = self.scale_emb.repeat(x.shape[0], 1, 1)
70
+ x = torch.cat([scale_emb, x], dim=1)
71
+ x = self.ln1(x)
72
+
73
+ x = x.permute(1, 0, 2)
74
+ x = self.transformer_blocks(x)
75
+ x = x.permute(1, 0, 2)
76
+
77
+ x = self.ln2(x[:, :self.num_tokens, :])
78
+ x = self.out(x)
79
+ return x
80
+
81
+
82
+ class DropPath(nn.Module):
83
+ r"""DropPath but without rescaling and supports optional all-zero and/or all-keep.
84
+ """
85
+ def __init__(self, p):
86
+ super(DropPath, self).__init__()
87
+ self.p = p
88
+
89
+ def forward(self, *args, zero=None, keep=None):
90
+ if not self.training:
91
+ return args[0] if len(args) == 1 else args
92
+
93
+ # params
94
+ x = args[0]
95
+ b = x.size(0)
96
+ n = (torch.rand(b) < self.p).sum()
97
+
98
+ # non-zero and non-keep mask
99
+ mask = x.new_ones(b, dtype=torch.bool)
100
+ if keep is not None:
101
+ mask[keep] = False
102
+ if zero is not None:
103
+ mask[zero] = False
104
+
105
+ # drop-path index
106
+ index = torch.where(mask)[0]
107
+ index = index[torch.randperm(len(index))[:n]]
108
+ if zero is not None:
109
+ index = torch.cat([index, torch.where(zero)[0]], dim=0)
110
+
111
+ # drop-path multiplier
112
+ multiplier = x.new_ones(b)
113
+ multiplier[index] = 0.0
114
+ output = tuple(u * self.broadcast(multiplier, u) for u in args)
115
+ return output[0] if len(args) == 1 else output
116
+
117
+ def broadcast(self, src, dst):
118
+ assert src.size(0) == dst.size(0)
119
+ shape = (dst.size(0), ) + (1, ) * (dst.ndim - 1)
120
+ return src.view(shape)
121
+
122
+
123
+ class ImageContext(nn.Module):
124
+ def __init__(self, width=1024, context_dim=768, token_num=1):
125
+ super().__init__()
126
+ self.width = width
127
+ self.token_num = token_num
128
+ self.context_dim = context_dim
129
+
130
+ self.fc = nn.Sequential(
131
+ nn.Linear(context_dim, width),
132
+ nn.SiLU(),
133
+ nn.Linear(width, token_num * context_dim),
134
+ )
135
+ self.drop_path = DropPath(0.5)
136
+
137
+ def forward(self, x):
138
+ # x shape [B, C]
139
+ out = self.drop_path(self.fc(x))
140
+ out = rearrange(out, 'b (n c) -> b n c', n=self.token_num)
141
+ return out
142
+
143
+
144
+ class StyleAdapterDualAttnAS(nn.Module):
145
+ def __init__(self, image_context_config, scale_predictor_config, scale=1.0, use_norm=False, time_embed_dim=1024, mid_dim=32):
146
+ super().__init__()
147
+ self.image_context_model = instantiate_from_config(image_context_config)
148
+ self.scale_predictor = instantiate_from_config(scale_predictor_config)
149
+ self.scale = scale
150
+ self.use_norm = use_norm
151
+ self.time_embed_dim = time_embed_dim
152
+ self.mid_dim = mid_dim
153
+
154
+ def create_cross_attention_adapter(self, unet):
155
+ ori_processor = register_attn_processor(unet)
156
+ dual_attn_processor = {}
157
+ for idx, key in enumerate(ori_processor.keys()):
158
+ kv_state_dicts = {
159
+ 'k': {'weight': unet.state_dict()[key[:-10] + '.to_k.weight']},
160
+ 'v': {'weight': unet.state_dict()[key[:-10] + '.to_v.weight']},
161
+ }
162
+ context_dim = kv_state_dicts['k']['weight'].shape[1]
163
+ inner_dim = kv_state_dicts['k']['weight'].shape[0]
164
+ print(key, context_dim, inner_dim)
165
+
166
+ dual_attn_processor[key] = DualCrossAttnProcessorAS(
167
+ context_dim=context_dim,
168
+ inner_dim=inner_dim,
169
+ state_dict=kv_state_dicts,
170
+ scale=self.scale,
171
+ use_norm=self.use_norm,
172
+ layer_idx=idx,
173
+ )
174
+
175
+ set_attn_processor(unet, dual_attn_processor)
176
+
177
+ dual_attn_processor = {key.replace('.', '_'): value for key, value in dual_attn_processor.items()}
178
+ self.add_module('kv_attn_layers', nn.ModuleDict(dual_attn_processor))
179
+
180
+ def set_cross_attention_adapter(self, unet):
181
+ dual_attn_processor = get_attn_processor(unet)
182
+ for key in dual_attn_processor.keys():
183
+ module_key = key.replace('.', '_')
184
+ dual_attn_processor[key] = self.kv_attn_layers[module_key]
185
+ print('set', key, module_key)
186
+ set_attn_processor(unet, dual_attn_processor)
187
+
188
+ def forward(self, x):
189
+ # x shape [B, C]
190
+ return self.image_context_model(x)
lvdm/modules/encoders/arch_transformer.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ import math
3
+ from typing import Callable, Optional, Sequence, Tuple
4
+
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+ from torch.utils.checkpoint import checkpoint
9
+
10
+ class LayerNormFp32(nn.LayerNorm):
11
+ """Subclass torch's LayerNorm to handle fp16 (by casting to float32 and back)."""
12
+
13
+ def forward(self, x: torch.Tensor):
14
+ orig_type = x.dtype
15
+ x = F.layer_norm(x.to(torch.float32), self.normalized_shape, self.weight, self.bias, self.eps)
16
+ return x.to(orig_type)
17
+
18
+
19
+ class LayerNorm(nn.LayerNorm):
20
+ """Subclass torch's LayerNorm (with cast back to input dtype)."""
21
+
22
+ def forward(self, x: torch.Tensor):
23
+ orig_type = x.dtype
24
+ x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
25
+ return x.to(orig_type)
26
+
27
+
28
+ class QuickGELU(nn.Module):
29
+ # NOTE This is slower than nn.GELU or nn.SiLU and uses more GPU memory
30
+ def forward(self, x: torch.Tensor):
31
+ return x * torch.sigmoid(1.702 * x)
32
+
33
+
34
+ class LayerScale(nn.Module):
35
+ def __init__(self, dim, init_values=1e-5, inplace=False):
36
+ super().__init__()
37
+ self.inplace = inplace
38
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
39
+
40
+ def forward(self, x):
41
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
42
+
43
+
44
+ class PatchDropout(nn.Module):
45
+ """
46
+ https://arxiv.org/abs/2212.00794
47
+ """
48
+
49
+ def __init__(self, prob, exclude_first_token=True):
50
+ super().__init__()
51
+ assert 0 <= prob < 1.
52
+ self.prob = prob
53
+ self.exclude_first_token = exclude_first_token # exclude CLS token
54
+
55
+ def forward(self, x):
56
+ if not self.training or self.prob == 0.:
57
+ return x
58
+
59
+ if self.exclude_first_token:
60
+ cls_tokens, x = x[:, :1], x[:, 1:]
61
+ else:
62
+ cls_tokens = torch.jit.annotate(torch.Tensor, x[:, :1])
63
+
64
+ batch = x.size()[0]
65
+ num_tokens = x.size()[1]
66
+
67
+ batch_indices = torch.arange(batch)
68
+ batch_indices = batch_indices[..., None]
69
+
70
+ keep_prob = 1 - self.prob
71
+ num_patches_keep = max(1, int(num_tokens * keep_prob))
72
+
73
+ rand = torch.randn(batch, num_tokens)
74
+ patch_indices_keep = rand.topk(num_patches_keep, dim=-1).indices
75
+
76
+ x = x[batch_indices, patch_indices_keep]
77
+
78
+ if self.exclude_first_token:
79
+ x = torch.cat((cls_tokens, x), dim=1)
80
+
81
+ return x
82
+
83
+
84
+ class Attention(nn.Module):
85
+ def __init__(
86
+ self,
87
+ dim,
88
+ num_heads=8,
89
+ qkv_bias=True,
90
+ scaled_cosine=False,
91
+ scale_heads=False,
92
+ logit_scale_max=math.log(1. / 0.01),
93
+ attn_drop=0.,
94
+ proj_drop=0.
95
+ ):
96
+ super().__init__()
97
+ self.scaled_cosine = scaled_cosine
98
+ self.scale_heads = scale_heads
99
+ assert dim % num_heads == 0, 'dim should be divisible by num_heads'
100
+ self.num_heads = num_heads
101
+ self.head_dim = dim // num_heads
102
+ self.scale = self.head_dim ** -0.5
103
+ self.logit_scale_max = logit_scale_max
104
+
105
+ # keeping in_proj in this form (instead of nn.Linear) to match weight scheme of original
106
+ self.in_proj_weight = nn.Parameter(torch.randn((dim * 3, dim)) * self.scale)
107
+ if qkv_bias:
108
+ self.in_proj_bias = nn.Parameter(torch.zeros(dim * 3))
109
+ else:
110
+ self.in_proj_bias = None
111
+
112
+ if self.scaled_cosine:
113
+ self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1))))
114
+ else:
115
+ self.logit_scale = None
116
+ self.attn_drop = nn.Dropout(attn_drop)
117
+ if self.scale_heads:
118
+ self.head_scale = nn.Parameter(torch.ones((num_heads, 1, 1)))
119
+ else:
120
+ self.head_scale = None
121
+ self.out_proj = nn.Linear(dim, dim)
122
+ self.out_drop = nn.Dropout(proj_drop)
123
+
124
+ def forward(self, x, attn_mask: Optional[torch.Tensor] = None):
125
+ L, N, C = x.shape
126
+ q, k, v = F.linear(x, self.in_proj_weight, self.in_proj_bias).chunk(3, dim=-1)
127
+ q = q.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
128
+ k = k.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
129
+ v = v.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1)
130
+
131
+ if self.logit_scale is not None:
132
+ attn = torch.bmm(F.normalize(q, dim=-1), F.normalize(k, dim=-1).transpose(-1, -2))
133
+ logit_scale = torch.clamp(self.logit_scale, max=self.logit_scale_max).exp()
134
+ attn = attn.view(N, self.num_heads, L, L) * logit_scale
135
+ attn = attn.view(-1, L, L)
136
+ else:
137
+ q = q * self.scale
138
+ attn = torch.bmm(q, k.transpose(-1, -2))
139
+
140
+ if attn_mask is not None:
141
+ if attn_mask.dtype == torch.bool:
142
+ new_attn_mask = torch.zeros_like(attn_mask, dtype=q.dtype)
143
+ new_attn_mask.masked_fill_(attn_mask, float("-inf"))
144
+ attn_mask = new_attn_mask
145
+ attn += attn_mask
146
+
147
+ attn = attn.softmax(dim=-1)
148
+ attn = self.attn_drop(attn)
149
+
150
+ x = torch.bmm(attn, v)
151
+ if self.head_scale is not None:
152
+ x = x.view(N, self.num_heads, L, C) * self.head_scale
153
+ x = x.view(-1, L, C)
154
+ x = x.transpose(0, 1).reshape(L, N, C)
155
+ x = self.out_proj(x)
156
+ x = self.out_drop(x)
157
+ return x
158
+
159
+
160
+ class ResidualAttentionBlock(nn.Module):
161
+ def __init__(
162
+ self,
163
+ d_model: int,
164
+ n_head: int,
165
+ mlp_ratio: float = 4.0,
166
+ ls_init_value: float = None,
167
+ act_layer: Callable = nn.GELU,
168
+ norm_layer: Callable = LayerNorm,
169
+ is_cross_attention: bool = False,
170
+ ):
171
+ super().__init__()
172
+
173
+ self.ln_1 = norm_layer(d_model)
174
+ self.attn = nn.MultiheadAttention(d_model, n_head)
175
+ self.ls_1 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
176
+ if is_cross_attention:
177
+ self.ln_1_kv = norm_layer(d_model)
178
+
179
+ self.ln_2 = norm_layer(d_model)
180
+ mlp_width = int(d_model * mlp_ratio)
181
+ self.mlp = nn.Sequential(OrderedDict([
182
+ ("c_fc", nn.Linear(d_model, mlp_width)),
183
+ ("gelu", act_layer()),
184
+ ("c_proj", nn.Linear(mlp_width, d_model))
185
+ ]))
186
+ self.ls_2 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity()
187
+
188
+ def attention(
189
+ self,
190
+ q_x: torch.Tensor,
191
+ k_x: Optional[torch.Tensor] = None,
192
+ v_x: Optional[torch.Tensor] = None,
193
+ attn_mask: Optional[torch.Tensor] = None,
194
+ ):
195
+ k_x = k_x if k_x is not None else q_x
196
+ v_x = v_x if v_x is not None else q_x
197
+
198
+ attn_mask = attn_mask.to(q_x.dtype) if attn_mask is not None else None
199
+ return self.attn(
200
+ q_x, k_x, v_x, need_weights=False, attn_mask=attn_mask
201
+ )[0]
202
+
203
+ def forward(
204
+ self,
205
+ q_x: torch.Tensor,
206
+ k_x: Optional[torch.Tensor] = None,
207
+ v_x: Optional[torch.Tensor] = None,
208
+ attn_mask: Optional[torch.Tensor] = None,
209
+ ):
210
+ k_x = self.ln_1_kv(k_x) if hasattr(self, "ln_1_kv") and k_x is not None else None
211
+ v_x = self.ln_1_kv(v_x) if hasattr(self, "ln_1_kv") and v_x is not None else None
212
+
213
+ x = q_x + self.ls_1(self.attention(q_x=self.ln_1(q_x), k_x=k_x, v_x=v_x, attn_mask=attn_mask))
214
+ x = x + self.ls_2(self.mlp(self.ln_2(x)))
215
+ return x
216
+
217
+
218
+ class Transformer(nn.Module):
219
+ def __init__(
220
+ self,
221
+ width: int,
222
+ layers: int,
223
+ heads: int,
224
+ mlp_ratio: float = 4.0,
225
+ ls_init_value: float = None,
226
+ act_layer: Callable = nn.GELU,
227
+ norm_layer: Callable = LayerNorm,
228
+ ):
229
+ super().__init__()
230
+ self.width = width
231
+ self.layers = layers
232
+ self.grad_checkpointing = False
233
+
234
+ self.resblocks = nn.ModuleList([
235
+ ResidualAttentionBlock(
236
+ width, heads, mlp_ratio, ls_init_value=ls_init_value, act_layer=act_layer, norm_layer=norm_layer)
237
+ for _ in range(layers)
238
+ ])
239
+
240
+ def get_cast_dtype(self) -> torch.dtype:
241
+ if hasattr(self.resblocks[0].mlp.c_fc, 'int8_original_dtype'):
242
+ return self.resblocks[0].mlp.c_fc.int8_original_dtype
243
+ return self.resblocks[0].mlp.c_fc.weight.dtype
244
+
245
+ def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None):
246
+ for r in self.resblocks:
247
+ if self.grad_checkpointing and not torch.jit.is_scripting():
248
+ # TODO: handle kwargs https://github.com/pytorch/pytorch/issues/79887#issuecomment-1161758372
249
+ x = checkpoint(r, x, None, None, attn_mask)
250
+ else:
251
+ x = r(x, attn_mask=attn_mask)
252
+ return x
lvdm/modules/encoders/condition.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.utils.checkpoint import checkpoint
4
+ import kornia
5
+ import open_clip
6
+ from transformers import T5Tokenizer, T5EncoderModel, CLIPTokenizer, CLIPTextModel
7
+ from lvdm.common import autocast
8
+ from utils.utils import count_params
9
+ import os
10
+
11
+ class AbstractEncoder(nn.Module):
12
+ def __init__(self):
13
+ super().__init__()
14
+
15
+ def encode(self, *args, **kwargs):
16
+ raise NotImplementedError
17
+
18
+
19
+ class IdentityEncoder(AbstractEncoder):
20
+
21
+ def encode(self, x):
22
+ return x
23
+
24
+
25
+ class ClassEmbedder(nn.Module):
26
+ def __init__(self, embed_dim, n_classes=1000, key='class', ucg_rate=0.1):
27
+ super().__init__()
28
+ self.key = key
29
+ self.embedding = nn.Embedding(n_classes, embed_dim)
30
+ self.n_classes = n_classes
31
+ self.ucg_rate = ucg_rate
32
+
33
+ def forward(self, batch, key=None, disable_dropout=False):
34
+ if key is None:
35
+ key = self.key
36
+ # this is for use in crossattn
37
+ c = batch[key][:, None]
38
+ if self.ucg_rate > 0. and not disable_dropout:
39
+ mask = 1. - torch.bernoulli(torch.ones_like(c) * self.ucg_rate)
40
+ c = mask * c + (1 - mask) * torch.ones_like(c) * (self.n_classes - 1)
41
+ c = c.long()
42
+ c = self.embedding(c)
43
+ return c
44
+
45
+ def get_unconditional_conditioning(self, bs, device="cuda"):
46
+ uc_class = self.n_classes - 1 # 1000 classes --> 0 ... 999, one extra class for ucg (class 1000)
47
+ uc = torch.ones((bs,), device=device) * uc_class
48
+ uc = {self.key: uc}
49
+ return uc
50
+
51
+
52
+ def disabled_train(self, mode=True):
53
+ """Overwrite model.train with this function to make sure train/eval mode
54
+ does not change anymore."""
55
+ return self
56
+
57
+
58
+ class FrozenT5Embedder(AbstractEncoder):
59
+ """Uses the T5 transformer encoder for text"""
60
+
61
+ def __init__(self, version="google/t5-v1_1-large", device="cuda", max_length=77,
62
+ freeze=True): # others are google/t5-v1_1-xl and google/t5-v1_1-xxl
63
+ super().__init__()
64
+ self.tokenizer = T5Tokenizer.from_pretrained(version)
65
+ self.transformer = T5EncoderModel.from_pretrained(version)
66
+ self.device = device
67
+ self.max_length = max_length # TODO: typical value?
68
+ if freeze:
69
+ self.freeze()
70
+
71
+ def freeze(self):
72
+ self.transformer = self.transformer.eval()
73
+ # self.train = disabled_train
74
+ for param in self.parameters():
75
+ param.requires_grad = False
76
+
77
+ def forward(self, text):
78
+ batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
79
+ return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
80
+ tokens = batch_encoding["input_ids"].to(self.device)
81
+ outputs = self.transformer(input_ids=tokens)
82
+
83
+ z = outputs.last_hidden_state
84
+ return z
85
+
86
+ def encode(self, text):
87
+ return self(text)
88
+
89
+
90
+ class FrozenCLIPEmbedder(AbstractEncoder):
91
+ """Uses the CLIP transformer encoder for text (from huggingface)"""
92
+ LAYERS = [
93
+ "last",
94
+ "pooled",
95
+ "hidden"
96
+ ]
97
+
98
+ def __init__(self, version="openai/clip-vit-large-patch14", device="cuda", max_length=77,
99
+ freeze=True, layer="last", layer_idx=None): # clip-vit-base-patch32
100
+ super().__init__()
101
+ assert layer in self.LAYERS
102
+ self.tokenizer = CLIPTokenizer.from_pretrained(version)
103
+ self.transformer = CLIPTextModel.from_pretrained(version)
104
+ self.device = device
105
+ self.max_length = max_length
106
+ if freeze:
107
+ self.freeze()
108
+ self.layer = layer
109
+ self.layer_idx = layer_idx
110
+ if layer == "hidden":
111
+ assert layer_idx is not None
112
+ assert 0 <= abs(layer_idx) <= 12
113
+
114
+ def freeze(self):
115
+ self.transformer = self.transformer.eval()
116
+ # self.train = disabled_train
117
+ for param in self.parameters():
118
+ param.requires_grad = False
119
+
120
+ def forward(self, text):
121
+ batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
122
+ return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
123
+ tokens = batch_encoding["input_ids"].to(self.device)
124
+ outputs = self.transformer(input_ids=tokens, output_hidden_states=self.layer == "hidden")
125
+ if self.layer == "last":
126
+ z = outputs.last_hidden_state
127
+ elif self.layer == "pooled":
128
+ z = outputs.pooler_output[:, None, :]
129
+ else:
130
+ z = outputs.hidden_states[self.layer_idx]
131
+ return z
132
+
133
+ def encode(self, text):
134
+ return self(text)
135
+
136
+
137
+ class ClipImageEmbedder(nn.Module):
138
+ def __init__(
139
+ self,
140
+ model,
141
+ jit=False,
142
+ device='cuda' if torch.cuda.is_available() else 'cpu',
143
+ antialias=True,
144
+ ucg_rate=0.
145
+ ):
146
+ super().__init__()
147
+ from clip import load as load_clip
148
+ self.model, _ = load_clip(name=model, device=device, jit=jit)
149
+
150
+ self.antialias = antialias
151
+
152
+ self.register_buffer('mean', torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False)
153
+ self.register_buffer('std', torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False)
154
+ self.ucg_rate = ucg_rate
155
+
156
+ def preprocess(self, x):
157
+ # normalize to [0,1]
158
+ x = kornia.geometry.resize(x, (224, 224),
159
+ interpolation='bicubic', align_corners=True,
160
+ antialias=self.antialias)
161
+ x = (x + 1.) / 2.
162
+ # re-normalize according to clip
163
+ x = kornia.enhance.normalize(x, self.mean, self.std)
164
+ return x
165
+
166
+ def forward(self, x, no_dropout=False):
167
+ # x is assumed to be in range [-1,1]
168
+ out = self.model.encode_image(self.preprocess(x))
169
+ out = out.to(x.dtype)
170
+ if self.ucg_rate > 0. and not no_dropout:
171
+ out = torch.bernoulli((1. - self.ucg_rate) * torch.ones(out.shape[0], device=out.device))[:, None] * out
172
+ return out
173
+
174
+
175
+ class FrozenOpenCLIPEmbedder(AbstractEncoder):
176
+ """
177
+ Uses the OpenCLIP transformer encoder for text
178
+ """
179
+ LAYERS = [
180
+ # "pooled",
181
+ "last",
182
+ "penultimate"
183
+ ]
184
+
185
+ def __init__(self, arch="ViT-H-14", version="laion2b_s32b_b79k", device="cuda", max_length=77,
186
+ freeze=True, layer="last"):
187
+ super().__init__()
188
+ assert layer in self.LAYERS
189
+ model, _, _ = open_clip.create_model_and_transforms(arch, device=torch.device('cpu'), pretrained=version,)
190
+ del model.visual
191
+ self.model = model
192
+
193
+ self.device = device
194
+ self.max_length = max_length
195
+ if freeze:
196
+ self.freeze()
197
+ self.layer = layer
198
+ if self.layer == "last":
199
+ self.layer_idx = 0
200
+ elif self.layer == "penultimate":
201
+ self.layer_idx = 1
202
+ else:
203
+ raise NotImplementedError()
204
+
205
+ def freeze(self):
206
+ self.model = self.model.eval()
207
+ for param in self.parameters():
208
+ param.requires_grad = False
209
+
210
+ def forward(self, text):
211
+ self.device = self.model.positional_embedding.device
212
+ tokens = open_clip.tokenize(text)
213
+ z = self.encode_with_transformer(tokens.to(self.device))
214
+ return z
215
+
216
+ def encode_with_transformer(self, text):
217
+ x = self.model.token_embedding(text) # [batch_size, n_ctx, d_model]
218
+ x = x + self.model.positional_embedding
219
+ x = x.permute(1, 0, 2) # NLD -> LND
220
+ x = self.text_transformer_forward(x, attn_mask=self.model.attn_mask)
221
+ x = x.permute(1, 0, 2) # LND -> NLD
222
+ x = self.model.ln_final(x)
223
+ return x
224
+
225
+ def text_transformer_forward(self, x: torch.Tensor, attn_mask=None):
226
+ for i, r in enumerate(self.model.transformer.resblocks):
227
+ if i == len(self.model.transformer.resblocks) - self.layer_idx:
228
+ break
229
+ if self.model.transformer.grad_checkpointing and not torch.jit.is_scripting():
230
+ x = checkpoint(r, x, attn_mask)
231
+ else:
232
+ x = r(x, attn_mask=attn_mask)
233
+ return x
234
+
235
+ def encode(self, text):
236
+ return self(text)
237
+
238
+
239
+ class FrozenOpenCLIPImageEmbedder(AbstractEncoder):
240
+ """
241
+ Uses the OpenCLIP vision transformer encoder for images
242
+ """
243
+
244
+ def __init__(self, arch="ViT-H-14", version="laion2b_s32b_b79k", device="cuda", max_length=77,
245
+ freeze=True, layer="pooled", antialias=True, ucg_rate=0., only_cls=True, use_proj=True,
246
+ use_shuffle=False, mask_ratio=0.0):
247
+ super().__init__()
248
+ model, _, _ = open_clip.create_model_and_transforms(arch, device=torch.device('cpu'),
249
+ pretrained=version, )
250
+ del model.transformer
251
+ self.model = model
252
+ self.mask_ratio = mask_ratio
253
+ # self.patch_dropout = PatchDropout(prob=patch_dropout, exclude_first_token=True) if patch_dropout > 0.0 else nn.Identity()
254
+
255
+ self.device = device
256
+ self.max_length = max_length
257
+ if freeze:
258
+ self.freeze()
259
+ self.layer = layer
260
+ if self.layer == "penultimate":
261
+ raise NotImplementedError()
262
+ self.layer_idx = 1
263
+
264
+ self.antialias = antialias
265
+
266
+ self.register_buffer('mean', torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False)
267
+ self.register_buffer('std', torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False)
268
+ self.ucg_rate = ucg_rate
269
+ self.only_cls = only_cls
270
+ self.use_proj = use_proj
271
+ self.use_shuffle = use_shuffle
272
+
273
+ def preprocess(self, x):
274
+ # normalize to [0,1]
275
+ x = kornia.geometry.resize(x, (224, 224),
276
+ interpolation='bicubic', align_corners=True,
277
+ antialias=self.antialias)
278
+ x = (x + 1.) / 2.
279
+ # renormalize according to clip
280
+ x = kornia.enhance.normalize(x, self.mean, self.std)
281
+ return x
282
+
283
+ def freeze(self):
284
+ self.model = self.model.eval()
285
+ for param in self.parameters():
286
+ param.requires_grad = False
287
+
288
+ @autocast
289
+ def forward(self, image, use_shuffle=False, drop_prob=None):
290
+ with torch.no_grad():
291
+ z = self.encode_with_vision_transformer(image, use_shuffle, drop_prob)
292
+ return z.detach().half()
293
+
294
+ @torch.no_grad()
295
+ def encode_with_vision_transformer(self, img, use_shuffle=False, mask_ratio=None):
296
+ if mask_ratio is None:
297
+ mask_ratio = self.mask_ratio
298
+ assert 0 <= mask_ratio < 1.
299
+
300
+ x = self.preprocess(img)
301
+
302
+ assert not self.model.visual.input_patchnorm
303
+ x = self.model.visual.conv1(x) # shape = [*, width, grid, grid]
304
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
305
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
306
+
307
+ # shuffle
308
+ if use_shuffle:
309
+ x = x[:, torch.randperm(x.shape[1]), :]
310
+
311
+ # class embeddings and positional embeddings
312
+ x = torch.cat(
313
+ [self.model.visual.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device),
314
+ x], dim=1) # shape = [*, grid ** 2 + 1, width]
315
+ x = x + self.model.visual.positional_embedding.to(x.dtype)
316
+
317
+ # patch dropout
318
+ x = self.random_masking(x, mask_ratio, exclude_first_token=True)
319
+
320
+ x = self.model.visual.ln_pre(x)
321
+
322
+ x = x.permute(1, 0, 2) # NLD -> LND
323
+ x = self.model.visual.transformer(x)
324
+ x = x.permute(1, 0, 2) # LND -> NLD
325
+
326
+ assert self.model.visual.attn_pool is None
327
+ pooled, tokens = self.model.visual._global_pool(x)
328
+ pooled = self.model.visual.ln_post(pooled)
329
+
330
+ if self.model.visual.proj is not None and self.use_proj:
331
+ pooled = pooled @ self.model.visual.proj
332
+
333
+ if self.only_cls:
334
+ out = pooled.unsqueeze(1)
335
+ else:
336
+ out = torch.cat([pooled.unsqueeze(1), tokens], dim=1)
337
+ return out
338
+
339
+ def encode(self, text):
340
+ return self(text)
341
+
342
+ def random_masking(self, x, mask_ratio, exclude_first_token=True):
343
+ if mask_ratio == 0.:
344
+ return x
345
+
346
+ N, L, D = x.shape
347
+ if exclude_first_token:
348
+ L = L - 1
349
+
350
+ len_keep = int(L * (1 - mask_ratio))
351
+ noise = torch.rand(N, L, device=x.device)
352
+
353
+ # sort noise for each sample
354
+ ids_shuffle = torch.argsort(noise, dim=1)
355
+ ids_restore = torch.argsort(ids_shuffle, dim=1)
356
+
357
+ # keep the first subset
358
+ ids_keep = ids_shuffle[:, :len_keep]
359
+ if exclude_first_token:
360
+ ids_keep = ids_keep + 1
361
+ ids_keep = torch.cat([torch.zeros(N, 1, device=x.device, dtype=torch.long), ids_keep], dim=1)
362
+ x_masked = torch.gather(x, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, D))
363
+
364
+ return x_masked
365
+
366
+
367
+ class FrozenOpenCLIPImageEmbedderV2(AbstractEncoder):
368
+ """
369
+ Uses the OpenCLIP vision transformer encoder for images
370
+ """
371
+
372
+ def __init__(self, arch="ViT-H-14", version="laion2b_s32b_b79k", device="cuda",
373
+ freeze=True, layer="pooled", antialias=True):
374
+ super().__init__()
375
+ model, _, _ = open_clip.create_model_and_transforms(arch, device=torch.device('cpu'),
376
+ pretrained=version, )
377
+ del model.transformer
378
+ self.model = model
379
+ self.device = device
380
+
381
+ if freeze:
382
+ self.freeze()
383
+ self.layer = layer
384
+ if self.layer == "penultimate":
385
+ raise NotImplementedError()
386
+ self.layer_idx = 1
387
+
388
+ self.antialias = antialias
389
+ self.register_buffer('mean', torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False)
390
+ self.register_buffer('std', torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False)
391
+
392
+
393
+ def preprocess(self, x):
394
+ # normalize to [0,1]
395
+ x = kornia.geometry.resize(x, (224, 224),
396
+ interpolation='bicubic', align_corners=True,
397
+ antialias=self.antialias)
398
+ x = (x + 1.) / 2.
399
+ # renormalize according to clip
400
+ x = kornia.enhance.normalize(x, self.mean, self.std)
401
+ return x
402
+
403
+ def freeze(self):
404
+ self.model = self.model.eval()
405
+ for param in self.model.parameters():
406
+ param.requires_grad = False
407
+
408
+ def forward(self, image, no_dropout=False):
409
+ ## image: b c h w
410
+ z = self.encode_with_vision_transformer(image)
411
+ return z
412
+
413
+ def encode_with_vision_transformer(self, x):
414
+ x = self.preprocess(x)
415
+
416
+ # to patches - whether to use dual patchnorm - https://arxiv.org/abs/2302.01327v1
417
+ if self.model.visual.input_patchnorm:
418
+ # einops - rearrange(x, 'b c (h p1) (w p2) -> b (h w) (c p1 p2)')
419
+ x = x.reshape(x.shape[0], x.shape[1], self.model.visual.grid_size[0], self.model.visual.patch_size[0], self.model.visual.grid_size[1], self.model.visual.patch_size[1])
420
+ x = x.permute(0, 2, 4, 1, 3, 5)
421
+ x = x.reshape(x.shape[0], self.model.visual.grid_size[0] * self.model.visual.grid_size[1], -1)
422
+ x = self.model.visual.patchnorm_pre_ln(x)
423
+ x = self.model.visual.conv1(x)
424
+ else:
425
+ x = self.model.visual.conv1(x) # shape = [*, width, grid, grid]
426
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
427
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
428
+
429
+ # class embeddings and positional embeddings
430
+ x = torch.cat(
431
+ [self.model.visual.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device),
432
+ x], dim=1) # shape = [*, grid ** 2 + 1, width]
433
+ x = x + self.model.visual.positional_embedding.to(x.dtype)
434
+
435
+ # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in
436
+ x = self.model.visual.patch_dropout(x)
437
+ x = self.model.visual.ln_pre(x)
438
+
439
+ x = x.permute(1, 0, 2) # NLD -> LND
440
+ x = self.model.visual.transformer(x)
441
+ x = x.permute(1, 0, 2) # LND -> NLD
442
+
443
+ return x
444
+
445
+
446
+ class FrozenCLIPT5Encoder(AbstractEncoder):
447
+ def __init__(self, clip_version="openai/clip-vit-large-patch14", t5_version="google/t5-v1_1-xl", device="cuda",
448
+ clip_max_length=77, t5_max_length=77):
449
+ super().__init__()
450
+ self.clip_encoder = FrozenCLIPEmbedder(clip_version, device, max_length=clip_max_length)
451
+ self.t5_encoder = FrozenT5Embedder(t5_version, device, max_length=t5_max_length)
452
+ print(f"{self.clip_encoder.__class__.__name__} has {count_params(self.clip_encoder) * 1.e-6:.2f} M parameters, "
453
+ f"{self.t5_encoder.__class__.__name__} comes with {count_params(self.t5_encoder) * 1.e-6:.2f} M params.")
454
+
455
+ def encode(self, text):
456
+ return self(text)
457
+
458
+ def forward(self, text):
459
+ clip_z = self.clip_encoder.encode(text)
460
+ t5_z = self.t5_encoder.encode(text)
461
+ return [clip_z, t5_z]
lvdm/modules/encoders/ip_resampler.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/mlfoundations/open_flamingo/blob/main/open_flamingo/src/helpers.py
2
+ import math
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+
7
+ class ImageProjModel(nn.Module):
8
+ """Projection Model"""
9
+ def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024, clip_extra_context_tokens=4):
10
+ super().__init__()
11
+ self.cross_attention_dim = cross_attention_dim
12
+ self.clip_extra_context_tokens = clip_extra_context_tokens
13
+ self.proj = nn.Linear(clip_embeddings_dim, self.clip_extra_context_tokens * cross_attention_dim)
14
+ self.norm = nn.LayerNorm(cross_attention_dim)
15
+
16
+ def forward(self, image_embeds):
17
+ #embeds = image_embeds
18
+ embeds = image_embeds.type(list(self.proj.parameters())[0].dtype)
19
+ clip_extra_context_tokens = self.proj(embeds).reshape(-1, self.clip_extra_context_tokens, self.cross_attention_dim)
20
+ clip_extra_context_tokens = self.norm(clip_extra_context_tokens)
21
+ return clip_extra_context_tokens
22
+
23
+ # FFN
24
+ def FeedForward(dim, mult=4):
25
+ inner_dim = int(dim * mult)
26
+ return nn.Sequential(
27
+ nn.LayerNorm(dim),
28
+ nn.Linear(dim, inner_dim, bias=False),
29
+ nn.GELU(),
30
+ nn.Linear(inner_dim, dim, bias=False),
31
+ )
32
+
33
+
34
+ def reshape_tensor(x, heads):
35
+ bs, length, width = x.shape
36
+ #(bs, length, width) --> (bs, length, n_heads, dim_per_head)
37
+ x = x.view(bs, length, heads, -1)
38
+ # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
39
+ x = x.transpose(1, 2)
40
+ # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
41
+ x = x.reshape(bs, heads, length, -1)
42
+ return x
43
+
44
+
45
+ class PerceiverAttention(nn.Module):
46
+ def __init__(self, *, dim, dim_head=64, heads=8):
47
+ super().__init__()
48
+ self.scale = dim_head**-0.5
49
+ self.dim_head = dim_head
50
+ self.heads = heads
51
+ inner_dim = dim_head * heads
52
+
53
+ self.norm1 = nn.LayerNorm(dim)
54
+ self.norm2 = nn.LayerNorm(dim)
55
+
56
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
57
+ self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
58
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
59
+
60
+
61
+ def forward(self, x, latents):
62
+ """
63
+ Args:
64
+ x (torch.Tensor): image features
65
+ shape (b, n1, D)
66
+ latent (torch.Tensor): latent features
67
+ shape (b, n2, D)
68
+ """
69
+ x = self.norm1(x)
70
+ latents = self.norm2(latents)
71
+
72
+ b, l, _ = latents.shape
73
+
74
+ q = self.to_q(latents)
75
+ kv_input = torch.cat((x, latents), dim=-2)
76
+ k, v = self.to_kv(kv_input).chunk(2, dim=-1)
77
+
78
+ q = reshape_tensor(q, self.heads)
79
+ k = reshape_tensor(k, self.heads)
80
+ v = reshape_tensor(v, self.heads)
81
+
82
+ # attention
83
+ scale = 1 / math.sqrt(math.sqrt(self.dim_head))
84
+ weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards
85
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
86
+ out = weight @ v
87
+
88
+ out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
89
+
90
+ return self.to_out(out)
91
+
92
+
93
+ class Resampler(nn.Module):
94
+ def __init__(
95
+ self,
96
+ dim=1024,
97
+ depth=8,
98
+ dim_head=64,
99
+ heads=16,
100
+ num_queries=8,
101
+ embedding_dim=768,
102
+ output_dim=1024,
103
+ ff_mult=4,
104
+ ):
105
+ super().__init__()
106
+
107
+ self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)
108
+
109
+ self.proj_in = nn.Linear(embedding_dim, dim)
110
+
111
+ self.proj_out = nn.Linear(dim, output_dim)
112
+ self.norm_out = nn.LayerNorm(output_dim)
113
+
114
+ self.layers = nn.ModuleList([])
115
+ for _ in range(depth):
116
+ self.layers.append(
117
+ nn.ModuleList(
118
+ [
119
+ PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
120
+ FeedForward(dim=dim, mult=ff_mult),
121
+ ]
122
+ )
123
+ )
124
+
125
+ def forward(self, x):
126
+
127
+ latents = self.latents.repeat(x.size(0), 1, 1)
128
+
129
+ x = self.proj_in(x)
130
+
131
+ for attn, ff in self.layers:
132
+ latents = attn(x, latents) + latents
133
+ latents = ff(latents) + latents
134
+
135
+ latents = self.proj_out(latents)
136
+ return self.norm_out(latents)
lvdm/modules/networks/__pycache__/ae_modules.cpython-39.pyc ADDED
Binary file (20.5 kB). View file
 
lvdm/modules/networks/__pycache__/openaimodel3d.cpython-39.pyc ADDED
Binary file (15.6 kB). View file
 
lvdm/modules/networks/ae_modules.py ADDED
@@ -0,0 +1,845 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pytorch_diffusion + derived encoder decoder
2
+ import math
3
+ import torch
4
+ import numpy as np
5
+ import torch.nn as nn
6
+ from einops import rearrange
7
+ from utils.utils import instantiate_from_config
8
+ from lvdm.modules.attention import LinearAttention
9
+
10
+ def nonlinearity(x):
11
+ # swish
12
+ return x*torch.sigmoid(x)
13
+
14
+
15
+ def Normalize(in_channels, num_groups=32):
16
+ return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True)
17
+
18
+
19
+
20
+ class LinAttnBlock(LinearAttention):
21
+ """to match AttnBlock usage"""
22
+ def __init__(self, in_channels):
23
+ super().__init__(dim=in_channels, heads=1, dim_head=in_channels)
24
+
25
+
26
+ class AttnBlock(nn.Module):
27
+ def __init__(self, in_channels):
28
+ super().__init__()
29
+ self.in_channels = in_channels
30
+
31
+ self.norm = Normalize(in_channels)
32
+ self.q = torch.nn.Conv2d(in_channels,
33
+ in_channels,
34
+ kernel_size=1,
35
+ stride=1,
36
+ padding=0)
37
+ self.k = torch.nn.Conv2d(in_channels,
38
+ in_channels,
39
+ kernel_size=1,
40
+ stride=1,
41
+ padding=0)
42
+ self.v = torch.nn.Conv2d(in_channels,
43
+ in_channels,
44
+ kernel_size=1,
45
+ stride=1,
46
+ padding=0)
47
+ self.proj_out = torch.nn.Conv2d(in_channels,
48
+ in_channels,
49
+ kernel_size=1,
50
+ stride=1,
51
+ padding=0)
52
+
53
+ def forward(self, x):
54
+ h_ = x
55
+ h_ = self.norm(h_)
56
+ q = self.q(h_)
57
+ k = self.k(h_)
58
+ v = self.v(h_)
59
+
60
+ # compute attention
61
+ b,c,h,w = q.shape
62
+ q = q.reshape(b,c,h*w) # bcl
63
+ q = q.permute(0,2,1) # bcl -> blc l=hw
64
+ k = k.reshape(b,c,h*w) # bcl
65
+
66
+ w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
67
+ w_ = w_ * (int(c)**(-0.5))
68
+ w_ = torch.nn.functional.softmax(w_, dim=2)
69
+
70
+ # attend to values
71
+ v = v.reshape(b,c,h*w)
72
+ w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q)
73
+ 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]
74
+ h_ = h_.reshape(b,c,h,w)
75
+
76
+ h_ = self.proj_out(h_)
77
+
78
+ return x+h_
79
+
80
+ def make_attn(in_channels, attn_type="vanilla"):
81
+ assert attn_type in ["vanilla", "linear", "none"], f'attn_type {attn_type} unknown'
82
+ #print(f"making attention of type '{attn_type}' with {in_channels} in_channels")
83
+ if attn_type == "vanilla":
84
+ return AttnBlock(in_channels)
85
+ elif attn_type == "none":
86
+ return nn.Identity(in_channels)
87
+ else:
88
+ return LinAttnBlock(in_channels)
89
+
90
+ class Downsample(nn.Module):
91
+ def __init__(self, in_channels, with_conv):
92
+ super().__init__()
93
+ self.with_conv = with_conv
94
+ self.in_channels = in_channels
95
+ if self.with_conv:
96
+ # no asymmetric padding in torch conv, must do it ourselves
97
+ self.conv = torch.nn.Conv2d(in_channels,
98
+ in_channels,
99
+ kernel_size=3,
100
+ stride=2,
101
+ padding=0)
102
+ def forward(self, x):
103
+ if self.with_conv:
104
+ pad = (0,1,0,1)
105
+ x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
106
+ x = self.conv(x)
107
+ else:
108
+ x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
109
+ return x
110
+
111
+ class Upsample(nn.Module):
112
+ def __init__(self, in_channels, with_conv):
113
+ super().__init__()
114
+ self.with_conv = with_conv
115
+ self.in_channels = in_channels
116
+ if self.with_conv:
117
+ self.conv = torch.nn.Conv2d(in_channels,
118
+ in_channels,
119
+ kernel_size=3,
120
+ stride=1,
121
+ padding=1)
122
+
123
+ def forward(self, x):
124
+ x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
125
+ if self.with_conv:
126
+ x = self.conv(x)
127
+ return x
128
+
129
+ def get_timestep_embedding(timesteps, embedding_dim):
130
+ """
131
+ This matches the implementation in Denoising Diffusion Probabilistic Models:
132
+ From Fairseq.
133
+ Build sinusoidal embeddings.
134
+ This matches the implementation in tensor2tensor, but differs slightly
135
+ from the description in Section 3.5 of "Attention Is All You Need".
136
+ """
137
+ assert len(timesteps.shape) == 1
138
+
139
+ half_dim = embedding_dim // 2
140
+ emb = math.log(10000) / (half_dim - 1)
141
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
142
+ emb = emb.to(device=timesteps.device)
143
+ emb = timesteps.float()[:, None] * emb[None, :]
144
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
145
+ if embedding_dim % 2 == 1: # zero pad
146
+ emb = torch.nn.functional.pad(emb, (0,1,0,0))
147
+ return emb
148
+
149
+
150
+
151
+ class ResnetBlock(nn.Module):
152
+ def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
153
+ dropout, temb_channels=512):
154
+ super().__init__()
155
+ self.in_channels = in_channels
156
+ out_channels = in_channels if out_channels is None else out_channels
157
+ self.out_channels = out_channels
158
+ self.use_conv_shortcut = conv_shortcut
159
+
160
+ self.norm1 = Normalize(in_channels)
161
+ self.conv1 = torch.nn.Conv2d(in_channels,
162
+ out_channels,
163
+ kernel_size=3,
164
+ stride=1,
165
+ padding=1)
166
+ if temb_channels > 0:
167
+ self.temb_proj = torch.nn.Linear(temb_channels,
168
+ out_channels)
169
+ self.norm2 = Normalize(out_channels)
170
+ self.dropout = torch.nn.Dropout(dropout)
171
+ self.conv2 = torch.nn.Conv2d(out_channels,
172
+ out_channels,
173
+ kernel_size=3,
174
+ stride=1,
175
+ padding=1)
176
+ if self.in_channels != self.out_channels:
177
+ if self.use_conv_shortcut:
178
+ self.conv_shortcut = torch.nn.Conv2d(in_channels,
179
+ out_channels,
180
+ kernel_size=3,
181
+ stride=1,
182
+ padding=1)
183
+ else:
184
+ self.nin_shortcut = torch.nn.Conv2d(in_channels,
185
+ out_channels,
186
+ kernel_size=1,
187
+ stride=1,
188
+ padding=0)
189
+
190
+ def forward(self, x, temb):
191
+ h = x
192
+ h = self.norm1(h)
193
+ h = nonlinearity(h)
194
+ h = self.conv1(h)
195
+
196
+ if temb is not None:
197
+ h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]
198
+
199
+ h = self.norm2(h)
200
+ h = nonlinearity(h)
201
+ h = self.dropout(h)
202
+ h = self.conv2(h)
203
+
204
+ if self.in_channels != self.out_channels:
205
+ if self.use_conv_shortcut:
206
+ x = self.conv_shortcut(x)
207
+ else:
208
+ x = self.nin_shortcut(x)
209
+
210
+ return x+h
211
+
212
+ class Model(nn.Module):
213
+ def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
214
+ attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
215
+ resolution, use_timestep=True, use_linear_attn=False, attn_type="vanilla"):
216
+ super().__init__()
217
+ if use_linear_attn: attn_type = "linear"
218
+ self.ch = ch
219
+ self.temb_ch = self.ch*4
220
+ self.num_resolutions = len(ch_mult)
221
+ self.num_res_blocks = num_res_blocks
222
+ self.resolution = resolution
223
+ self.in_channels = in_channels
224
+
225
+ self.use_timestep = use_timestep
226
+ if self.use_timestep:
227
+ # timestep embedding
228
+ self.temb = nn.Module()
229
+ self.temb.dense = nn.ModuleList([
230
+ torch.nn.Linear(self.ch,
231
+ self.temb_ch),
232
+ torch.nn.Linear(self.temb_ch,
233
+ self.temb_ch),
234
+ ])
235
+
236
+ # downsampling
237
+ self.conv_in = torch.nn.Conv2d(in_channels,
238
+ self.ch,
239
+ kernel_size=3,
240
+ stride=1,
241
+ padding=1)
242
+
243
+ curr_res = resolution
244
+ in_ch_mult = (1,)+tuple(ch_mult)
245
+ self.down = nn.ModuleList()
246
+ for i_level in range(self.num_resolutions):
247
+ block = nn.ModuleList()
248
+ attn = nn.ModuleList()
249
+ block_in = ch*in_ch_mult[i_level]
250
+ block_out = ch*ch_mult[i_level]
251
+ for i_block in range(self.num_res_blocks):
252
+ block.append(ResnetBlock(in_channels=block_in,
253
+ out_channels=block_out,
254
+ temb_channels=self.temb_ch,
255
+ dropout=dropout))
256
+ block_in = block_out
257
+ if curr_res in attn_resolutions:
258
+ attn.append(make_attn(block_in, attn_type=attn_type))
259
+ down = nn.Module()
260
+ down.block = block
261
+ down.attn = attn
262
+ if i_level != self.num_resolutions-1:
263
+ down.downsample = Downsample(block_in, resamp_with_conv)
264
+ curr_res = curr_res // 2
265
+ self.down.append(down)
266
+
267
+ # middle
268
+ self.mid = nn.Module()
269
+ self.mid.block_1 = ResnetBlock(in_channels=block_in,
270
+ out_channels=block_in,
271
+ temb_channels=self.temb_ch,
272
+ dropout=dropout)
273
+ self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
274
+ self.mid.block_2 = ResnetBlock(in_channels=block_in,
275
+ out_channels=block_in,
276
+ temb_channels=self.temb_ch,
277
+ dropout=dropout)
278
+
279
+ # upsampling
280
+ self.up = nn.ModuleList()
281
+ for i_level in reversed(range(self.num_resolutions)):
282
+ block = nn.ModuleList()
283
+ attn = nn.ModuleList()
284
+ block_out = ch*ch_mult[i_level]
285
+ skip_in = ch*ch_mult[i_level]
286
+ for i_block in range(self.num_res_blocks+1):
287
+ if i_block == self.num_res_blocks:
288
+ skip_in = ch*in_ch_mult[i_level]
289
+ block.append(ResnetBlock(in_channels=block_in+skip_in,
290
+ out_channels=block_out,
291
+ temb_channels=self.temb_ch,
292
+ dropout=dropout))
293
+ block_in = block_out
294
+ if curr_res in attn_resolutions:
295
+ attn.append(make_attn(block_in, attn_type=attn_type))
296
+ up = nn.Module()
297
+ up.block = block
298
+ up.attn = attn
299
+ if i_level != 0:
300
+ up.upsample = Upsample(block_in, resamp_with_conv)
301
+ curr_res = curr_res * 2
302
+ self.up.insert(0, up) # prepend to get consistent order
303
+
304
+ # end
305
+ self.norm_out = Normalize(block_in)
306
+ self.conv_out = torch.nn.Conv2d(block_in,
307
+ out_ch,
308
+ kernel_size=3,
309
+ stride=1,
310
+ padding=1)
311
+
312
+ def forward(self, x, t=None, context=None):
313
+ #assert x.shape[2] == x.shape[3] == self.resolution
314
+ if context is not None:
315
+ # assume aligned context, cat along channel axis
316
+ x = torch.cat((x, context), dim=1)
317
+ if self.use_timestep:
318
+ # timestep embedding
319
+ assert t is not None
320
+ temb = get_timestep_embedding(t, self.ch)
321
+ temb = self.temb.dense[0](temb)
322
+ temb = nonlinearity(temb)
323
+ temb = self.temb.dense[1](temb)
324
+ else:
325
+ temb = None
326
+
327
+ # downsampling
328
+ hs = [self.conv_in(x)]
329
+ for i_level in range(self.num_resolutions):
330
+ for i_block in range(self.num_res_blocks):
331
+ h = self.down[i_level].block[i_block](hs[-1], temb)
332
+ if len(self.down[i_level].attn) > 0:
333
+ h = self.down[i_level].attn[i_block](h)
334
+ hs.append(h)
335
+ if i_level != self.num_resolutions-1:
336
+ hs.append(self.down[i_level].downsample(hs[-1]))
337
+
338
+ # middle
339
+ h = hs[-1]
340
+ h = self.mid.block_1(h, temb)
341
+ h = self.mid.attn_1(h)
342
+ h = self.mid.block_2(h, temb)
343
+
344
+ # upsampling
345
+ for i_level in reversed(range(self.num_resolutions)):
346
+ for i_block in range(self.num_res_blocks+1):
347
+ h = self.up[i_level].block[i_block](
348
+ torch.cat([h, hs.pop()], dim=1), temb)
349
+ if len(self.up[i_level].attn) > 0:
350
+ h = self.up[i_level].attn[i_block](h)
351
+ if i_level != 0:
352
+ h = self.up[i_level].upsample(h)
353
+
354
+ # end
355
+ h = self.norm_out(h)
356
+ h = nonlinearity(h)
357
+ h = self.conv_out(h)
358
+ return h
359
+
360
+ def get_last_layer(self):
361
+ return self.conv_out.weight
362
+
363
+
364
+ class Encoder(nn.Module):
365
+ def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
366
+ attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
367
+ resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla",
368
+ **ignore_kwargs):
369
+ super().__init__()
370
+ if use_linear_attn: attn_type = "linear"
371
+ self.ch = ch
372
+ self.temb_ch = 0
373
+ self.num_resolutions = len(ch_mult)
374
+ self.num_res_blocks = num_res_blocks
375
+ self.resolution = resolution
376
+ self.in_channels = in_channels
377
+
378
+ # downsampling
379
+ self.conv_in = torch.nn.Conv2d(in_channels,
380
+ self.ch,
381
+ kernel_size=3,
382
+ stride=1,
383
+ padding=1)
384
+
385
+ curr_res = resolution
386
+ in_ch_mult = (1,)+tuple(ch_mult)
387
+ self.in_ch_mult = in_ch_mult
388
+ self.down = nn.ModuleList()
389
+ for i_level in range(self.num_resolutions):
390
+ block = nn.ModuleList()
391
+ attn = nn.ModuleList()
392
+ block_in = ch*in_ch_mult[i_level]
393
+ block_out = ch*ch_mult[i_level]
394
+ for i_block in range(self.num_res_blocks):
395
+ block.append(ResnetBlock(in_channels=block_in,
396
+ out_channels=block_out,
397
+ temb_channels=self.temb_ch,
398
+ dropout=dropout))
399
+ block_in = block_out
400
+ if curr_res in attn_resolutions:
401
+ attn.append(make_attn(block_in, attn_type=attn_type))
402
+ down = nn.Module()
403
+ down.block = block
404
+ down.attn = attn
405
+ if i_level != self.num_resolutions-1:
406
+ down.downsample = Downsample(block_in, resamp_with_conv)
407
+ curr_res = curr_res // 2
408
+ self.down.append(down)
409
+
410
+ # middle
411
+ self.mid = nn.Module()
412
+ self.mid.block_1 = ResnetBlock(in_channels=block_in,
413
+ out_channels=block_in,
414
+ temb_channels=self.temb_ch,
415
+ dropout=dropout)
416
+ self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
417
+ self.mid.block_2 = ResnetBlock(in_channels=block_in,
418
+ out_channels=block_in,
419
+ temb_channels=self.temb_ch,
420
+ dropout=dropout)
421
+
422
+ # end
423
+ self.norm_out = Normalize(block_in)
424
+ self.conv_out = torch.nn.Conv2d(block_in,
425
+ 2*z_channels if double_z else z_channels,
426
+ kernel_size=3,
427
+ stride=1,
428
+ padding=1)
429
+
430
+ def forward(self, x):
431
+ # timestep embedding
432
+ temb = None
433
+
434
+ # print(f'encoder-input={x.shape}')
435
+ # downsampling
436
+ hs = [self.conv_in(x)]
437
+ # print(f'encoder-conv in feat={hs[0].shape}')
438
+ for i_level in range(self.num_resolutions):
439
+ for i_block in range(self.num_res_blocks):
440
+ h = self.down[i_level].block[i_block](hs[-1], temb)
441
+ # print(f'encoder-down feat={h.shape}')
442
+ if len(self.down[i_level].attn) > 0:
443
+ h = self.down[i_level].attn[i_block](h)
444
+ hs.append(h)
445
+ if i_level != self.num_resolutions-1:
446
+ # print(f'encoder-downsample (input)={hs[-1].shape}')
447
+ hs.append(self.down[i_level].downsample(hs[-1]))
448
+ # print(f'encoder-downsample (output)={hs[-1].shape}')
449
+
450
+ # middle
451
+ h = hs[-1]
452
+ h = self.mid.block_1(h, temb)
453
+ # print(f'encoder-mid1 feat={h.shape}')
454
+ h = self.mid.attn_1(h)
455
+ h = self.mid.block_2(h, temb)
456
+ # print(f'encoder-mid2 feat={h.shape}')
457
+
458
+ # end
459
+ h = self.norm_out(h)
460
+ h = nonlinearity(h)
461
+ h = self.conv_out(h)
462
+ # print(f'end feat={h.shape}')
463
+ return h
464
+
465
+
466
+ class Decoder(nn.Module):
467
+ def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
468
+ attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
469
+ resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
470
+ attn_type="vanilla", **ignorekwargs):
471
+ super().__init__()
472
+ if use_linear_attn: attn_type = "linear"
473
+ self.ch = ch
474
+ self.temb_ch = 0
475
+ self.num_resolutions = len(ch_mult)
476
+ self.num_res_blocks = num_res_blocks
477
+ self.resolution = resolution
478
+ self.in_channels = in_channels
479
+ self.give_pre_end = give_pre_end
480
+ self.tanh_out = tanh_out
481
+
482
+ # compute in_ch_mult, block_in and curr_res at lowest res
483
+ in_ch_mult = (1,)+tuple(ch_mult)
484
+ block_in = ch*ch_mult[self.num_resolutions-1]
485
+ curr_res = resolution // 2**(self.num_resolutions-1)
486
+ self.z_shape = (1,z_channels,curr_res,curr_res)
487
+ print("AE working on z of shape {} = {} dimensions.".format(
488
+ self.z_shape, np.prod(self.z_shape)))
489
+
490
+ # z to block_in
491
+ self.conv_in = torch.nn.Conv2d(z_channels,
492
+ block_in,
493
+ kernel_size=3,
494
+ stride=1,
495
+ padding=1)
496
+
497
+ # middle
498
+ self.mid = nn.Module()
499
+ self.mid.block_1 = ResnetBlock(in_channels=block_in,
500
+ out_channels=block_in,
501
+ temb_channels=self.temb_ch,
502
+ dropout=dropout)
503
+ self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
504
+ self.mid.block_2 = ResnetBlock(in_channels=block_in,
505
+ out_channels=block_in,
506
+ temb_channels=self.temb_ch,
507
+ dropout=dropout)
508
+
509
+ # upsampling
510
+ self.up = nn.ModuleList()
511
+ for i_level in reversed(range(self.num_resolutions)):
512
+ block = nn.ModuleList()
513
+ attn = nn.ModuleList()
514
+ block_out = ch*ch_mult[i_level]
515
+ for i_block in range(self.num_res_blocks+1):
516
+ block.append(ResnetBlock(in_channels=block_in,
517
+ out_channels=block_out,
518
+ temb_channels=self.temb_ch,
519
+ dropout=dropout))
520
+ block_in = block_out
521
+ if curr_res in attn_resolutions:
522
+ attn.append(make_attn(block_in, attn_type=attn_type))
523
+ up = nn.Module()
524
+ up.block = block
525
+ up.attn = attn
526
+ if i_level != 0:
527
+ up.upsample = Upsample(block_in, resamp_with_conv)
528
+ curr_res = curr_res * 2
529
+ self.up.insert(0, up) # prepend to get consistent order
530
+
531
+ # end
532
+ self.norm_out = Normalize(block_in)
533
+ self.conv_out = torch.nn.Conv2d(block_in,
534
+ out_ch,
535
+ kernel_size=3,
536
+ stride=1,
537
+ padding=1)
538
+
539
+ def forward(self, z):
540
+ #assert z.shape[1:] == self.z_shape[1:]
541
+ self.last_z_shape = z.shape
542
+
543
+ # print(f'decoder-input={z.shape}')
544
+ # timestep embedding
545
+ temb = None
546
+
547
+ # z to block_in
548
+ h = self.conv_in(z)
549
+ # print(f'decoder-conv in feat={h.shape}')
550
+
551
+ # middle
552
+ h = self.mid.block_1(h, temb)
553
+ h = self.mid.attn_1(h)
554
+ h = self.mid.block_2(h, temb)
555
+ # print(f'decoder-mid feat={h.shape}')
556
+
557
+ # upsampling
558
+ for i_level in reversed(range(self.num_resolutions)):
559
+ for i_block in range(self.num_res_blocks+1):
560
+ h = self.up[i_level].block[i_block](h, temb)
561
+ if len(self.up[i_level].attn) > 0:
562
+ h = self.up[i_level].attn[i_block](h)
563
+ # print(f'decoder-up feat={h.shape}')
564
+ if i_level != 0:
565
+ h = self.up[i_level].upsample(h)
566
+ # print(f'decoder-upsample feat={h.shape}')
567
+
568
+ # end
569
+ if self.give_pre_end:
570
+ return h
571
+
572
+ h = self.norm_out(h)
573
+ h = nonlinearity(h)
574
+ h = self.conv_out(h)
575
+ # print(f'decoder-conv_out feat={h.shape}')
576
+ if self.tanh_out:
577
+ h = torch.tanh(h)
578
+ return h
579
+
580
+
581
+ class SimpleDecoder(nn.Module):
582
+ def __init__(self, in_channels, out_channels, *args, **kwargs):
583
+ super().__init__()
584
+ self.model = nn.ModuleList([nn.Conv2d(in_channels, in_channels, 1),
585
+ ResnetBlock(in_channels=in_channels,
586
+ out_channels=2 * in_channels,
587
+ temb_channels=0, dropout=0.0),
588
+ ResnetBlock(in_channels=2 * in_channels,
589
+ out_channels=4 * in_channels,
590
+ temb_channels=0, dropout=0.0),
591
+ ResnetBlock(in_channels=4 * in_channels,
592
+ out_channels=2 * in_channels,
593
+ temb_channels=0, dropout=0.0),
594
+ nn.Conv2d(2*in_channels, in_channels, 1),
595
+ Upsample(in_channels, with_conv=True)])
596
+ # end
597
+ self.norm_out = Normalize(in_channels)
598
+ self.conv_out = torch.nn.Conv2d(in_channels,
599
+ out_channels,
600
+ kernel_size=3,
601
+ stride=1,
602
+ padding=1)
603
+
604
+ def forward(self, x):
605
+ for i, layer in enumerate(self.model):
606
+ if i in [1,2,3]:
607
+ x = layer(x, None)
608
+ else:
609
+ x = layer(x)
610
+
611
+ h = self.norm_out(x)
612
+ h = nonlinearity(h)
613
+ x = self.conv_out(h)
614
+ return x
615
+
616
+
617
+ class UpsampleDecoder(nn.Module):
618
+ def __init__(self, in_channels, out_channels, ch, num_res_blocks, resolution,
619
+ ch_mult=(2,2), dropout=0.0):
620
+ super().__init__()
621
+ # upsampling
622
+ self.temb_ch = 0
623
+ self.num_resolutions = len(ch_mult)
624
+ self.num_res_blocks = num_res_blocks
625
+ block_in = in_channels
626
+ curr_res = resolution // 2 ** (self.num_resolutions - 1)
627
+ self.res_blocks = nn.ModuleList()
628
+ self.upsample_blocks = nn.ModuleList()
629
+ for i_level in range(self.num_resolutions):
630
+ res_block = []
631
+ block_out = ch * ch_mult[i_level]
632
+ for i_block in range(self.num_res_blocks + 1):
633
+ res_block.append(ResnetBlock(in_channels=block_in,
634
+ out_channels=block_out,
635
+ temb_channels=self.temb_ch,
636
+ dropout=dropout))
637
+ block_in = block_out
638
+ self.res_blocks.append(nn.ModuleList(res_block))
639
+ if i_level != self.num_resolutions - 1:
640
+ self.upsample_blocks.append(Upsample(block_in, True))
641
+ curr_res = curr_res * 2
642
+
643
+ # end
644
+ self.norm_out = Normalize(block_in)
645
+ self.conv_out = torch.nn.Conv2d(block_in,
646
+ out_channels,
647
+ kernel_size=3,
648
+ stride=1,
649
+ padding=1)
650
+
651
+ def forward(self, x):
652
+ # upsampling
653
+ h = x
654
+ for k, i_level in enumerate(range(self.num_resolutions)):
655
+ for i_block in range(self.num_res_blocks + 1):
656
+ h = self.res_blocks[i_level][i_block](h, None)
657
+ if i_level != self.num_resolutions - 1:
658
+ h = self.upsample_blocks[k](h)
659
+ h = self.norm_out(h)
660
+ h = nonlinearity(h)
661
+ h = self.conv_out(h)
662
+ return h
663
+
664
+
665
+ class LatentRescaler(nn.Module):
666
+ def __init__(self, factor, in_channels, mid_channels, out_channels, depth=2):
667
+ super().__init__()
668
+ # residual block, interpolate, residual block
669
+ self.factor = factor
670
+ self.conv_in = nn.Conv2d(in_channels,
671
+ mid_channels,
672
+ kernel_size=3,
673
+ stride=1,
674
+ padding=1)
675
+ self.res_block1 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
676
+ out_channels=mid_channels,
677
+ temb_channels=0,
678
+ dropout=0.0) for _ in range(depth)])
679
+ self.attn = AttnBlock(mid_channels)
680
+ self.res_block2 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
681
+ out_channels=mid_channels,
682
+ temb_channels=0,
683
+ dropout=0.0) for _ in range(depth)])
684
+
685
+ self.conv_out = nn.Conv2d(mid_channels,
686
+ out_channels,
687
+ kernel_size=1,
688
+ )
689
+
690
+ def forward(self, x):
691
+ x = self.conv_in(x)
692
+ for block in self.res_block1:
693
+ x = block(x, None)
694
+ x = torch.nn.functional.interpolate(x, size=(int(round(x.shape[2]*self.factor)), int(round(x.shape[3]*self.factor))))
695
+ x = self.attn(x)
696
+ for block in self.res_block2:
697
+ x = block(x, None)
698
+ x = self.conv_out(x)
699
+ return x
700
+
701
+
702
+ class MergedRescaleEncoder(nn.Module):
703
+ def __init__(self, in_channels, ch, resolution, out_ch, num_res_blocks,
704
+ attn_resolutions, dropout=0.0, resamp_with_conv=True,
705
+ ch_mult=(1,2,4,8), rescale_factor=1.0, rescale_module_depth=1):
706
+ super().__init__()
707
+ intermediate_chn = ch * ch_mult[-1]
708
+ self.encoder = Encoder(in_channels=in_channels, num_res_blocks=num_res_blocks, ch=ch, ch_mult=ch_mult,
709
+ z_channels=intermediate_chn, double_z=False, resolution=resolution,
710
+ attn_resolutions=attn_resolutions, dropout=dropout, resamp_with_conv=resamp_with_conv,
711
+ out_ch=None)
712
+ self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=intermediate_chn,
713
+ mid_channels=intermediate_chn, out_channels=out_ch, depth=rescale_module_depth)
714
+
715
+ def forward(self, x):
716
+ x = self.encoder(x)
717
+ x = self.rescaler(x)
718
+ return x
719
+
720
+
721
+ class MergedRescaleDecoder(nn.Module):
722
+ def __init__(self, z_channels, out_ch, resolution, num_res_blocks, attn_resolutions, ch, ch_mult=(1,2,4,8),
723
+ dropout=0.0, resamp_with_conv=True, rescale_factor=1.0, rescale_module_depth=1):
724
+ super().__init__()
725
+ tmp_chn = z_channels*ch_mult[-1]
726
+ self.decoder = Decoder(out_ch=out_ch, z_channels=tmp_chn, attn_resolutions=attn_resolutions, dropout=dropout,
727
+ resamp_with_conv=resamp_with_conv, in_channels=None, num_res_blocks=num_res_blocks,
728
+ ch_mult=ch_mult, resolution=resolution, ch=ch)
729
+ self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=z_channels, mid_channels=tmp_chn,
730
+ out_channels=tmp_chn, depth=rescale_module_depth)
731
+
732
+ def forward(self, x):
733
+ x = self.rescaler(x)
734
+ x = self.decoder(x)
735
+ return x
736
+
737
+
738
+ class Upsampler(nn.Module):
739
+ def __init__(self, in_size, out_size, in_channels, out_channels, ch_mult=2):
740
+ super().__init__()
741
+ assert out_size >= in_size
742
+ num_blocks = int(np.log2(out_size//in_size))+1
743
+ factor_up = 1.+ (out_size % in_size)
744
+ print(f"Building {self.__class__.__name__} with in_size: {in_size} --> out_size {out_size} and factor {factor_up}")
745
+ self.rescaler = LatentRescaler(factor=factor_up, in_channels=in_channels, mid_channels=2*in_channels,
746
+ out_channels=in_channels)
747
+ self.decoder = Decoder(out_ch=out_channels, resolution=out_size, z_channels=in_channels, num_res_blocks=2,
748
+ attn_resolutions=[], in_channels=None, ch=in_channels,
749
+ ch_mult=[ch_mult for _ in range(num_blocks)])
750
+
751
+ def forward(self, x):
752
+ x = self.rescaler(x)
753
+ x = self.decoder(x)
754
+ return x
755
+
756
+
757
+ class Resize(nn.Module):
758
+ def __init__(self, in_channels=None, learned=False, mode="bilinear"):
759
+ super().__init__()
760
+ self.with_conv = learned
761
+ self.mode = mode
762
+ if self.with_conv:
763
+ print(f"Note: {self.__class__.__name} uses learned downsampling and will ignore the fixed {mode} mode")
764
+ raise NotImplementedError()
765
+ assert in_channels is not None
766
+ # no asymmetric padding in torch conv, must do it ourselves
767
+ self.conv = torch.nn.Conv2d(in_channels,
768
+ in_channels,
769
+ kernel_size=4,
770
+ stride=2,
771
+ padding=1)
772
+
773
+ def forward(self, x, scale_factor=1.0):
774
+ if scale_factor==1.0:
775
+ return x
776
+ else:
777
+ x = torch.nn.functional.interpolate(x, mode=self.mode, align_corners=False, scale_factor=scale_factor)
778
+ return x
779
+
780
+ class FirstStagePostProcessor(nn.Module):
781
+
782
+ def __init__(self, ch_mult:list, in_channels,
783
+ pretrained_model:nn.Module=None,
784
+ reshape=False,
785
+ n_channels=None,
786
+ dropout=0.,
787
+ pretrained_config=None):
788
+ super().__init__()
789
+ if pretrained_config is None:
790
+ assert pretrained_model is not None, 'Either "pretrained_model" or "pretrained_config" must not be None'
791
+ self.pretrained_model = pretrained_model
792
+ else:
793
+ assert pretrained_config is not None, 'Either "pretrained_model" or "pretrained_config" must not be None'
794
+ self.instantiate_pretrained(pretrained_config)
795
+
796
+ self.do_reshape = reshape
797
+
798
+ if n_channels is None:
799
+ n_channels = self.pretrained_model.encoder.ch
800
+
801
+ self.proj_norm = Normalize(in_channels,num_groups=in_channels//2)
802
+ self.proj = nn.Conv2d(in_channels,n_channels,kernel_size=3,
803
+ stride=1,padding=1)
804
+
805
+ blocks = []
806
+ downs = []
807
+ ch_in = n_channels
808
+ for m in ch_mult:
809
+ blocks.append(ResnetBlock(in_channels=ch_in,out_channels=m*n_channels,dropout=dropout))
810
+ ch_in = m * n_channels
811
+ downs.append(Downsample(ch_in, with_conv=False))
812
+
813
+ self.model = nn.ModuleList(blocks)
814
+ self.downsampler = nn.ModuleList(downs)
815
+
816
+
817
+ def instantiate_pretrained(self, config):
818
+ model = instantiate_from_config(config)
819
+ self.pretrained_model = model.eval()
820
+ # self.pretrained_model.train = False
821
+ for param in self.pretrained_model.parameters():
822
+ param.requires_grad = False
823
+
824
+
825
+ @torch.no_grad()
826
+ def encode_with_pretrained(self,x):
827
+ c = self.pretrained_model.encode(x)
828
+ if isinstance(c, DiagonalGaussianDistribution):
829
+ c = c.mode()
830
+ return c
831
+
832
+ def forward(self,x):
833
+ z_fs = self.encode_with_pretrained(x)
834
+ z = self.proj_norm(z_fs)
835
+ z = self.proj(z)
836
+ z = nonlinearity(z)
837
+
838
+ for submodel, downmodel in zip(self.model,self.downsampler):
839
+ z = submodel(z,temb=None)
840
+ z = downmodel(z)
841
+
842
+ if self.do_reshape:
843
+ z = rearrange(z,'b c h w -> b (h w) c')
844
+ return z
845
+
lvdm/modules/networks/openaimodel3d.py ADDED
@@ -0,0 +1,641 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+ from abc import abstractmethod
3
+ import torch
4
+ import torch.nn as nn
5
+ from einops import rearrange
6
+ import torch.nn.functional as F
7
+ from lvdm.models.utils_diffusion import timestep_embedding
8
+ from lvdm.common import checkpoint
9
+ from lvdm.basics import (
10
+ zero_module,
11
+ conv_nd,
12
+ linear,
13
+ avg_pool_nd,
14
+ normalization
15
+ )
16
+ from lvdm.modules.attention import SpatialTransformer, TemporalTransformer
17
+
18
+
19
+ class TimestepBlock(nn.Module):
20
+ """
21
+ Any module where forward() takes timestep embeddings as a second argument.
22
+ """
23
+ @abstractmethod
24
+ def forward(self, x, emb):
25
+ """
26
+ Apply the module to `x` given `emb` timestep embeddings.
27
+ """
28
+
29
+
30
+ class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
31
+ """
32
+ A sequential module that passes timestep embeddings to the children that
33
+ support it as an extra input.
34
+ """
35
+
36
+ def forward(self, x, emb, context=None, batch_size=None, is_imgbatch=False, use_temp=True, scale_scalar=None):
37
+ for layer in self:
38
+ if isinstance(layer, TimestepBlock):
39
+ x = layer(x, emb, batch_size, is_imgbatch=is_imgbatch)
40
+ elif isinstance(layer, SpatialTransformer):
41
+ x = layer(x, context, emb, scale_scalar=scale_scalar)
42
+ elif isinstance(layer, TemporalTransformer):
43
+ if use_temp:
44
+ x = rearrange(x, '(b f) c h w -> b c f h w', b=batch_size)
45
+ x = layer(x, context, is_imgbatch=is_imgbatch, emb=emb)
46
+ x = rearrange(x, 'b c f h w -> (b f) c h w')
47
+ else:
48
+ pass
49
+ else:
50
+ x = layer(x,)
51
+ return x
52
+
53
+
54
+ class Downsample(nn.Module):
55
+ """
56
+ A downsampling layer with an optional convolution.
57
+ :param channels: channels in the inputs and outputs.
58
+ :param use_conv: a bool determining if a convolution is applied.
59
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
60
+ downsampling occurs in the inner-two dimensions.
61
+ """
62
+
63
+ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):
64
+ super().__init__()
65
+ self.channels = channels
66
+ self.out_channels = out_channels or channels
67
+ self.use_conv = use_conv
68
+ self.dims = dims
69
+ stride = 2 if dims != 3 else (1, 2, 2)
70
+ if use_conv:
71
+ self.op = conv_nd(
72
+ dims, self.channels, self.out_channels, 3, stride=stride, padding=padding
73
+ )
74
+ else:
75
+ assert self.channels == self.out_channels
76
+ self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
77
+
78
+ def forward(self, x):
79
+ assert x.shape[1] == self.channels
80
+ return self.op(x)
81
+
82
+
83
+ class Upsample(nn.Module):
84
+ """
85
+ An upsampling layer with an optional convolution.
86
+ :param channels: channels in the inputs and outputs.
87
+ :param use_conv: a bool determining if a convolution is applied.
88
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
89
+ upsampling occurs in the inner-two dimensions.
90
+ """
91
+
92
+ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):
93
+ super().__init__()
94
+ self.channels = channels
95
+ self.out_channels = out_channels or channels
96
+ self.use_conv = use_conv
97
+ self.dims = dims
98
+ if use_conv:
99
+ self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding)
100
+
101
+ def forward(self, x):
102
+ assert x.shape[1] == self.channels
103
+ if self.dims == 3:
104
+ x = F.interpolate(x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode='nearest')
105
+ else:
106
+ x = F.interpolate(x, scale_factor=2, mode='nearest')
107
+ if self.use_conv:
108
+ x = self.conv(x)
109
+ return x
110
+
111
+
112
+ class ResBlock(TimestepBlock):
113
+ """
114
+ A residual block that can optionally change the number of channels.
115
+ :param channels: the number of input channels.
116
+ :param emb_channels: the number of timestep embedding channels.
117
+ :param dropout: the rate of dropout.
118
+ :param out_channels: if specified, the number of out channels.
119
+ :param use_conv: if True and out_channels is specified, use a spatial
120
+ convolution instead of a smaller 1x1 convolution to change the
121
+ channels in the skip connection.
122
+ :param dims: determines if the signal is 1D, 2D, or 3D.
123
+ :param up: if True, use this block for upsampling.
124
+ :param down: if True, use this block for downsampling.
125
+ """
126
+
127
+ def __init__(
128
+ self,
129
+ channels,
130
+ emb_channels,
131
+ dropout,
132
+ out_channels=None,
133
+ use_scale_shift_norm=False,
134
+ dims=2,
135
+ use_checkpoint=False,
136
+ use_conv=False,
137
+ up=False,
138
+ down=False,
139
+ use_temporal_conv=False,
140
+ tempspatial_aware=False
141
+ ):
142
+ super().__init__()
143
+ self.channels = channels
144
+ self.emb_channels = emb_channels
145
+ self.dropout = dropout
146
+ self.out_channels = out_channels or channels
147
+ self.use_conv = use_conv
148
+ self.use_checkpoint = use_checkpoint
149
+ self.use_scale_shift_norm = use_scale_shift_norm
150
+ self.use_temporal_conv = use_temporal_conv
151
+
152
+ self.in_layers = nn.Sequential(
153
+ normalization(channels),
154
+ nn.SiLU(),
155
+ conv_nd(dims, channels, self.out_channels, 3, padding=1),
156
+ )
157
+
158
+ self.updown = up or down
159
+
160
+ if up:
161
+ self.h_upd = Upsample(channels, False, dims)
162
+ self.x_upd = Upsample(channels, False, dims)
163
+ elif down:
164
+ self.h_upd = Downsample(channels, False, dims)
165
+ self.x_upd = Downsample(channels, False, dims)
166
+ else:
167
+ self.h_upd = self.x_upd = nn.Identity()
168
+
169
+ self.emb_layers = nn.Sequential(
170
+ nn.SiLU(),
171
+ nn.Linear(
172
+ emb_channels,
173
+ 2 * self.out_channels if use_scale_shift_norm else self.out_channels,
174
+ ),
175
+ )
176
+ self.out_layers = nn.Sequential(
177
+ normalization(self.out_channels),
178
+ nn.SiLU(),
179
+ nn.Dropout(p=dropout),
180
+ zero_module(nn.Conv2d(self.out_channels, self.out_channels, 3, padding=1)),
181
+ )
182
+
183
+ if self.out_channels == channels:
184
+ self.skip_connection = nn.Identity()
185
+ elif use_conv:
186
+ self.skip_connection = conv_nd(dims, channels, self.out_channels, 3, padding=1)
187
+ else:
188
+ self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
189
+
190
+ if self.use_temporal_conv:
191
+ self.temopral_conv = TemporalConvBlock(
192
+ self.out_channels,
193
+ self.out_channels,
194
+ dropout=0.1,
195
+ spatial_aware=tempspatial_aware
196
+ )
197
+
198
+ def forward(self, x, emb, batch_size=None, is_imgbatch=False):
199
+ """
200
+ Apply the block to a Tensor, conditioned on a timestep embedding.
201
+ :param x: an [N x C x ...] Tensor of features.
202
+ :param emb: an [N x emb_channels] Tensor of timestep embeddings.
203
+ :return: an [N x C x ...] Tensor of outputs.
204
+ """
205
+ input_tuple = (x, emb,)
206
+ if batch_size:
207
+ forward_batchsize = partial(self._forward, batch_size=batch_size, is_imgbatch=is_imgbatch)
208
+ return checkpoint(forward_batchsize, input_tuple, self.parameters(), self.use_checkpoint)
209
+ return checkpoint(self._forward, input_tuple, self.parameters(), self.use_checkpoint)
210
+
211
+ def _forward(self, x, emb, batch_size=None, is_imgbatch=False):
212
+ if self.updown:
213
+ in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
214
+ h = in_rest(x)
215
+ h = self.h_upd(h)
216
+ x = self.x_upd(x)
217
+ h = in_conv(h)
218
+ else:
219
+ h = self.in_layers(x)
220
+ emb_out = self.emb_layers(emb).type(h.dtype)
221
+ while len(emb_out.shape) < len(h.shape):
222
+ emb_out = emb_out[..., None]
223
+ if self.use_scale_shift_norm:
224
+ out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
225
+ scale, shift = torch.chunk(emb_out, 2, dim=1)
226
+ h = out_norm(h) * (1 + scale) + shift
227
+ h = out_rest(h)
228
+ else:
229
+ h = h + emb_out
230
+ h = self.out_layers(h)
231
+ h = self.skip_connection(x) + h
232
+
233
+ if self.use_temporal_conv and batch_size and not is_imgbatch:
234
+ h = rearrange(h, '(b t) c h w -> b c t h w', b=batch_size)
235
+ h = self.temopral_conv(h)
236
+ h = rearrange(h, 'b c t h w -> (b t) c h w')
237
+ return h
238
+
239
+
240
+ class TemporalConvBlock(nn.Module):
241
+ """
242
+ Adapted from modelscope: https://github.com/modelscope/modelscope/blob/master/modelscope/models/multi_modal/video_synthesis/unet_sd.py
243
+ """
244
+
245
+ def __init__(self, in_channels, out_channels=None, dropout=0.0, spatial_aware=False):
246
+ super(TemporalConvBlock, self).__init__()
247
+ if out_channels is None:
248
+ out_channels = in_channels
249
+ self.in_channels = in_channels
250
+ self.out_channels = out_channels
251
+ kernel_shape = (3, 1, 1) if not spatial_aware else (3, 3, 3)
252
+ padding_shape = (1, 0, 0) if not spatial_aware else (1, 1, 1)
253
+
254
+ # conv layers
255
+ self.conv1 = nn.Sequential(
256
+ nn.GroupNorm(32, in_channels), nn.SiLU(),
257
+ nn.Conv3d(in_channels, out_channels, kernel_shape, padding=padding_shape))
258
+ self.conv2 = nn.Sequential(
259
+ nn.GroupNorm(32, out_channels), nn.SiLU(), nn.Dropout(dropout),
260
+ nn.Conv3d(out_channels, in_channels, kernel_shape, padding=padding_shape))
261
+ self.conv3 = nn.Sequential(
262
+ nn.GroupNorm(32, out_channels), nn.SiLU(), nn.Dropout(dropout),
263
+ nn.Conv3d(out_channels, in_channels, (3, 1, 1), padding=(1, 0, 0)))
264
+ self.conv4 = nn.Sequential(
265
+ nn.GroupNorm(32, out_channels), nn.SiLU(), nn.Dropout(dropout),
266
+ nn.Conv3d(out_channels, in_channels, (3, 1, 1), padding=(1, 0, 0)))
267
+
268
+ # zero out the last layer params,so the conv block is identity
269
+ nn.init.zeros_(self.conv4[-1].weight)
270
+ nn.init.zeros_(self.conv4[-1].bias)
271
+
272
+ def forward(self, x):
273
+ identity = x
274
+ x = self.conv1(x)
275
+ x = self.conv2(x)
276
+ x = self.conv3(x)
277
+ x = self.conv4(x)
278
+
279
+ return x + identity
280
+
281
+
282
+ class UNetModel(nn.Module):
283
+ """
284
+ The full UNet model with attention and timestep embedding.
285
+ :param in_channels: in_channels in the input Tensor.
286
+ :param model_channels: base channel count for the model.
287
+ :param out_channels: channels in the output Tensor.
288
+ :param num_res_blocks: number of residual blocks per downsample.
289
+ :param attention_resolutions: a collection of downsample rates at which
290
+ attention will take place. May be a set, list, or tuple.
291
+ For example, if this contains 4, then at 4x downsampling, attention
292
+ will be used.
293
+ :param dropout: the dropout probability.
294
+ :param channel_mult: channel multiplier for each level of the UNet.
295
+ :param conv_resample: if True, use learned convolutions for upsampling and
296
+ downsampling.
297
+ :param dims: determines if the signal is 1D, 2D, or 3D.
298
+ :param num_classes: if specified (as an int), then this model will be
299
+ class-conditional with `num_classes` classes.
300
+ :param use_checkpoint: use gradient checkpointing to reduce memory usage.
301
+ :param num_heads: the number of attention heads in each attention layer.
302
+ :param num_heads_channels: if specified, ignore num_heads and instead use
303
+ a fixed channel width per attention head.
304
+ :param num_heads_upsample: works with num_heads to set a different number
305
+ of heads for upsampling. Deprecated.
306
+ :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
307
+ :param resblock_updown: use residual blocks for up/downsampling.
308
+ """
309
+
310
+ def __init__(self,
311
+ in_channels,
312
+ model_channels,
313
+ out_channels,
314
+ num_res_blocks,
315
+ attention_resolutions,
316
+ dropout=0.0,
317
+ channel_mult=(1, 2, 4, 8),
318
+ conv_resample=True,
319
+ dims=2,
320
+ context_dim=None,
321
+ use_scale_shift_norm=False,
322
+ resblock_updown=False,
323
+ num_heads=-1,
324
+ num_head_channels=-1,
325
+ transformer_depth=1,
326
+ use_linear=False,
327
+ use_checkpoint=False,
328
+ temporal_conv=False,
329
+ tempspatial_aware=False,
330
+ temporal_attention=True,
331
+ temporal_selfatt_only=True,
332
+ use_relative_position=True,
333
+ use_causal_attention=False,
334
+ temporal_length=None,
335
+ use_fp16=False,
336
+ addition_attention=False,
337
+ use_image_attention=False,
338
+ temporal_transformer_depth=1,
339
+ fps_cond=False,
340
+ ):
341
+ super(UNetModel, self).__init__()
342
+ if num_heads == -1:
343
+ assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
344
+ if num_head_channels == -1:
345
+ assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
346
+
347
+ self.in_channels = in_channels
348
+ self.model_channels = model_channels
349
+ self.out_channels = out_channels
350
+ self.num_res_blocks = num_res_blocks
351
+ self.attention_resolutions = attention_resolutions
352
+ self.dropout = dropout
353
+ self.channel_mult = channel_mult
354
+ self.conv_resample = conv_resample
355
+ self.temporal_attention = temporal_attention
356
+ time_embed_dim = model_channels * 4
357
+ self.use_checkpoint = use_checkpoint
358
+ self.dtype = torch.float16 if use_fp16 else torch.float32
359
+ self.addition_attention=addition_attention
360
+ self.use_image_attention = use_image_attention
361
+ self.fps_cond=fps_cond
362
+
363
+
364
+
365
+ self.time_embed = nn.Sequential(
366
+ linear(model_channels, time_embed_dim),
367
+ nn.SiLU(),
368
+ linear(time_embed_dim, time_embed_dim),
369
+ )
370
+ if self.fps_cond:
371
+ self.fps_embedding = nn.Sequential(
372
+ linear(model_channels, time_embed_dim),
373
+ nn.SiLU(),
374
+ linear(time_embed_dim, time_embed_dim),
375
+ )
376
+
377
+ self.input_blocks = nn.ModuleList(
378
+ [
379
+ TimestepEmbedSequential(conv_nd(dims, in_channels, model_channels, 3, padding=1))
380
+ ]
381
+ )
382
+ if self.addition_attention:
383
+ self.init_attn=TimestepEmbedSequential(
384
+ TemporalTransformer(
385
+ model_channels,
386
+ n_heads=8,
387
+ d_head=num_head_channels,
388
+ depth=transformer_depth,
389
+ context_dim=context_dim,
390
+ use_checkpoint=use_checkpoint, only_self_att=temporal_selfatt_only,
391
+ causal_attention=use_causal_attention, relative_position=use_relative_position,
392
+ temporal_length=temporal_length))
393
+
394
+ input_block_chans = [model_channels]
395
+ ch = model_channels
396
+ ds = 1
397
+ for level, mult in enumerate(channel_mult):
398
+ for _ in range(num_res_blocks):
399
+ layers = [
400
+ ResBlock(ch, time_embed_dim, dropout,
401
+ out_channels=mult * model_channels, dims=dims, use_checkpoint=use_checkpoint,
402
+ use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware,
403
+ use_temporal_conv=temporal_conv
404
+ )
405
+ ]
406
+ ch = mult * model_channels
407
+ if ds in attention_resolutions:
408
+ if num_head_channels == -1:
409
+ dim_head = ch // num_heads
410
+ else:
411
+ num_heads = ch // num_head_channels
412
+ dim_head = num_head_channels
413
+ layers.append(
414
+ SpatialTransformer(ch, num_heads, dim_head,
415
+ depth=transformer_depth, context_dim=context_dim, use_linear=use_linear,
416
+ use_checkpoint=use_checkpoint, disable_self_attn=False,
417
+ img_cross_attention=self.use_image_attention
418
+ )
419
+ )
420
+ if self.temporal_attention:
421
+ layers.append(
422
+ TemporalTransformer(ch, num_heads, dim_head,
423
+ depth=temporal_transformer_depth, context_dim=context_dim, use_linear=use_linear,
424
+ use_checkpoint=use_checkpoint, only_self_att=temporal_selfatt_only,
425
+ causal_attention=use_causal_attention, relative_position=use_relative_position,
426
+ temporal_length=temporal_length
427
+ )
428
+ )
429
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
430
+ input_block_chans.append(ch)
431
+ if level != len(channel_mult) - 1:
432
+ out_ch = ch
433
+ self.input_blocks.append(
434
+ TimestepEmbedSequential(
435
+ ResBlock(ch, time_embed_dim, dropout,
436
+ out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint,
437
+ use_scale_shift_norm=use_scale_shift_norm,
438
+ down=True
439
+ )
440
+ if resblock_updown
441
+ else Downsample(ch, conv_resample, dims=dims, out_channels=out_ch)
442
+ )
443
+ )
444
+ ch = out_ch
445
+ input_block_chans.append(ch)
446
+ ds *= 2
447
+
448
+ if num_head_channels == -1:
449
+ dim_head = ch // num_heads
450
+ else:
451
+ num_heads = ch // num_head_channels
452
+ dim_head = num_head_channels
453
+ layers = [
454
+ ResBlock(ch, time_embed_dim, dropout,
455
+ dims=dims, use_checkpoint=use_checkpoint,
456
+ use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware,
457
+ use_temporal_conv=temporal_conv
458
+ ),
459
+ SpatialTransformer(ch, num_heads, dim_head,
460
+ depth=transformer_depth, context_dim=context_dim, use_linear=use_linear,
461
+ use_checkpoint=use_checkpoint, disable_self_attn=False,
462
+ img_cross_attention=self.use_image_attention
463
+ )
464
+ ]
465
+ if self.temporal_attention:
466
+ layers.append(
467
+ TemporalTransformer(ch, num_heads, dim_head,
468
+ depth=temporal_transformer_depth, context_dim=context_dim, use_linear=use_linear,
469
+ use_checkpoint=use_checkpoint, only_self_att=temporal_selfatt_only,
470
+ causal_attention=use_causal_attention, relative_position=use_relative_position,
471
+ temporal_length=temporal_length
472
+ )
473
+ )
474
+ layers.append(
475
+ ResBlock(ch, time_embed_dim, dropout,
476
+ dims=dims, use_checkpoint=use_checkpoint,
477
+ use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware,
478
+ use_temporal_conv=temporal_conv
479
+ )
480
+ )
481
+ self.middle_block = TimestepEmbedSequential(*layers)
482
+
483
+ self.output_blocks = nn.ModuleList([])
484
+ for level, mult in list(enumerate(channel_mult))[::-1]:
485
+ for i in range(num_res_blocks + 1):
486
+ ich = input_block_chans.pop()
487
+ layers = [
488
+ ResBlock(ch + ich, time_embed_dim, dropout,
489
+ out_channels=mult * model_channels, dims=dims, use_checkpoint=use_checkpoint,
490
+ use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware,
491
+ use_temporal_conv=temporal_conv
492
+ )
493
+ ]
494
+ ch = model_channels * mult
495
+ if ds in attention_resolutions:
496
+ if num_head_channels == -1:
497
+ dim_head = ch // num_heads
498
+ else:
499
+ num_heads = ch // num_head_channels
500
+ dim_head = num_head_channels
501
+ layers.append(
502
+ SpatialTransformer(ch, num_heads, dim_head,
503
+ depth=transformer_depth, context_dim=context_dim, use_linear=use_linear,
504
+ use_checkpoint=use_checkpoint, disable_self_attn=False,
505
+ img_cross_attention=self.use_image_attention
506
+ )
507
+ )
508
+ if self.temporal_attention:
509
+ layers.append(
510
+ TemporalTransformer(ch, num_heads, dim_head,
511
+ depth=temporal_transformer_depth, context_dim=context_dim, use_linear=use_linear,
512
+ use_checkpoint=use_checkpoint, only_self_att=temporal_selfatt_only,
513
+ causal_attention=use_causal_attention, relative_position=use_relative_position,
514
+ temporal_length=temporal_length
515
+ )
516
+ )
517
+ if level and i == num_res_blocks:
518
+ out_ch = ch
519
+ layers.append(
520
+ ResBlock(ch, time_embed_dim, dropout,
521
+ out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint,
522
+ use_scale_shift_norm=use_scale_shift_norm,
523
+ up=True
524
+ )
525
+ if resblock_updown
526
+ else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
527
+ )
528
+ ds //= 2
529
+ self.output_blocks.append(TimestepEmbedSequential(*layers))
530
+
531
+ self.out = nn.Sequential(
532
+ normalization(ch),
533
+ nn.SiLU(),
534
+ zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),
535
+ )
536
+
537
+ def forward(self, x, timesteps, context=None, append_to_context=None, features_adapter=None, scale_scalar=None, is_imgbatch=False, fps=16, **kwargs):
538
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
539
+ emb = self.time_embed(t_emb)
540
+
541
+ # add style context
542
+ if append_to_context is not None:
543
+ context = torch.cat((context, append_to_context), dim=1)
544
+
545
+
546
+ if self.fps_cond:
547
+ if type(fps) == int:
548
+ fps = torch.full_like(timesteps, fps)
549
+ fps_emb = timestep_embedding(fps,self.model_channels, repeat_only=False)
550
+ emb += self.fps_embedding(fps_emb)
551
+
552
+ b,_,t,_,_ = x.shape
553
+ ## repeat t times for context [(b t) 77 768] & time embedding
554
+ if not is_imgbatch:
555
+ context = context.repeat_interleave(repeats=t, dim=0)
556
+ if scale_scalar is not None:
557
+ scale_scalar = scale_scalar.repeat_interleave(repeats=t, dim=0)
558
+
559
+ emb = emb.repeat_interleave(repeats=t, dim=0)
560
+
561
+ ## always in shape (b t) c h w, except for temporal layer
562
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
563
+
564
+ h = x.type(self.dtype)
565
+ adapter_idx = 0
566
+ hs = []
567
+ for id, module in enumerate(self.input_blocks):
568
+ h = module(h, emb, context=context, batch_size=b, is_imgbatch=is_imgbatch, scale_scalar=scale_scalar)
569
+ if id ==0 and self.addition_attention:
570
+ h = self.init_attn(h, emb, context=context, batch_size=b, is_imgbatch=is_imgbatch, scale_scalar=scale_scalar)
571
+ ## plug-in adapter features
572
+ if ((id+1)%3 == 0) and features_adapter is not None:
573
+ h = h + features_adapter[adapter_idx]
574
+ adapter_idx += 1
575
+ hs.append(h)
576
+ if features_adapter is not None:
577
+ assert len(features_adapter)==adapter_idx, 'Wrong features_adapter'
578
+
579
+ h = self.middle_block(h, emb, context=context, batch_size=b, is_imgbatch=is_imgbatch, scale_scalar=scale_scalar)
580
+ for module in self.output_blocks:
581
+ h = torch.cat([h, hs.pop()], dim=1)
582
+ h = module(h, emb, context=context, batch_size=b, is_imgbatch=is_imgbatch, scale_scalar=scale_scalar)
583
+ h = h.type(x.dtype)
584
+ y = self.out(h)
585
+
586
+ # reshape back to (b c t h w)
587
+ y = rearrange(y, '(b t) c h w -> b c t h w', b=b)
588
+ return y
589
+
590
+
591
+
592
+ class UNet2DModel(UNetModel):
593
+ def forward(self, x, timesteps, context=None, append_to_context=None, features_adapter=None, scale_scalar=None, fps=16, use_temp=False, **kwargs):
594
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
595
+ emb = self.time_embed(t_emb)
596
+
597
+ if self.fps_cond:
598
+ if type(fps) == int:
599
+ fps = torch.full_like(timesteps, fps)
600
+ fps_emb = timestep_embedding(fps,self.model_channels, repeat_only=False)
601
+ emb += self.fps_embedding(fps_emb)
602
+
603
+ b,_,t,_,_ = x.shape
604
+ ## repeat t times for context [(b t) 77 768] & time embedding
605
+ if context.shape[0] != b*t:
606
+ context = context.repeat_interleave(repeats=t, dim=0)
607
+ if emb.shape[0] != b*t:
608
+ emb = emb.repeat_interleave(repeats=t, dim=0)
609
+
610
+ # add style context
611
+ if append_to_context is not None:
612
+ context = torch.cat((context, append_to_context), dim=1)
613
+
614
+ ## always in shape (b t) c h w, except for temporal layer
615
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
616
+
617
+ h = x.type(self.dtype)
618
+ adapter_idx = 0
619
+ hs = []
620
+ for id, module in enumerate(self.input_blocks):
621
+ h = module(h, emb, context=context, batch_size=b, is_imgbatch=True, use_temp=use_temp, scale_scalar=scale_scalar)
622
+ if id ==0 and self.addition_attention:
623
+ h = self.init_attn(h, emb, context=context, batch_size=b, is_imgbatch=True, use_temp=use_temp, scale_scalar=scale_scalar)
624
+ ## plug-in adapter features
625
+ if ((id+1)%3 == 0) and features_adapter is not None:
626
+ h = h + features_adapter[adapter_idx]
627
+ adapter_idx += 1
628
+ hs.append(h)
629
+ if features_adapter is not None:
630
+ assert len(features_adapter)==adapter_idx, 'Wrong features_adapter'
631
+
632
+ h = self.middle_block(h, emb, context=context, batch_size=b, is_imgbatch=True, use_temp=use_temp, scale_scalar=scale_scalar)
633
+ for module in self.output_blocks:
634
+ h = torch.cat([h, hs.pop()], dim=1)
635
+ h = module(h, emb, context=context, batch_size=b, is_imgbatch=True, use_temp=use_temp, scale_scalar=scale_scalar)
636
+ h = h.type(x.dtype)
637
+ y = self.out(h)
638
+
639
+ # reshape back to (b c t h w)
640
+ y = rearrange(y, '(b t) c h w -> b c t h w', b=b)
641
+ return y
lvdm/modules/x_transformer.py ADDED
@@ -0,0 +1,640 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """shout-out to https://github.com/lucidrains/x-transformers/tree/main/x_transformers"""
2
+ from functools import partial
3
+ from inspect import isfunction
4
+ from collections import namedtuple
5
+ from einops import rearrange, repeat
6
+ import torch
7
+ from torch import nn, einsum
8
+ import torch.nn.functional as F
9
+
10
+ # constants
11
+ DEFAULT_DIM_HEAD = 64
12
+
13
+ Intermediates = namedtuple('Intermediates', [
14
+ 'pre_softmax_attn',
15
+ 'post_softmax_attn'
16
+ ])
17
+
18
+ LayerIntermediates = namedtuple('Intermediates', [
19
+ 'hiddens',
20
+ 'attn_intermediates'
21
+ ])
22
+
23
+
24
+ class AbsolutePositionalEmbedding(nn.Module):
25
+ def __init__(self, dim, max_seq_len):
26
+ super().__init__()
27
+ self.emb = nn.Embedding(max_seq_len, dim)
28
+ self.init_()
29
+
30
+ def init_(self):
31
+ nn.init.normal_(self.emb.weight, std=0.02)
32
+
33
+ def forward(self, x):
34
+ n = torch.arange(x.shape[1], device=x.device)
35
+ return self.emb(n)[None, :, :]
36
+
37
+
38
+ class FixedPositionalEmbedding(nn.Module):
39
+ def __init__(self, dim):
40
+ super().__init__()
41
+ inv_freq = 1. / (10000 ** (torch.arange(0, dim, 2).float() / dim))
42
+ self.register_buffer('inv_freq', inv_freq)
43
+
44
+ def forward(self, x, seq_dim=1, offset=0):
45
+ t = torch.arange(x.shape[seq_dim], device=x.device).type_as(self.inv_freq) + offset
46
+ sinusoid_inp = torch.einsum('i , j -> i j', t, self.inv_freq)
47
+ emb = torch.cat((sinusoid_inp.sin(), sinusoid_inp.cos()), dim=-1)
48
+ return emb[None, :, :]
49
+
50
+
51
+ # helpers
52
+
53
+ def exists(val):
54
+ return val is not None
55
+
56
+
57
+ def default(val, d):
58
+ if exists(val):
59
+ return val
60
+ return d() if isfunction(d) else d
61
+
62
+
63
+ def always(val):
64
+ def inner(*args, **kwargs):
65
+ return val
66
+ return inner
67
+
68
+
69
+ def not_equals(val):
70
+ def inner(x):
71
+ return x != val
72
+ return inner
73
+
74
+
75
+ def equals(val):
76
+ def inner(x):
77
+ return x == val
78
+ return inner
79
+
80
+
81
+ def max_neg_value(tensor):
82
+ return -torch.finfo(tensor.dtype).max
83
+
84
+
85
+ # keyword argument helpers
86
+
87
+ def pick_and_pop(keys, d):
88
+ values = list(map(lambda key: d.pop(key), keys))
89
+ return dict(zip(keys, values))
90
+
91
+
92
+ def group_dict_by_key(cond, d):
93
+ return_val = [dict(), dict()]
94
+ for key in d.keys():
95
+ match = bool(cond(key))
96
+ ind = int(not match)
97
+ return_val[ind][key] = d[key]
98
+ return (*return_val,)
99
+
100
+
101
+ def string_begins_with(prefix, str):
102
+ return str.startswith(prefix)
103
+
104
+
105
+ def group_by_key_prefix(prefix, d):
106
+ return group_dict_by_key(partial(string_begins_with, prefix), d)
107
+
108
+
109
+ def groupby_prefix_and_trim(prefix, d):
110
+ kwargs_with_prefix, kwargs = group_dict_by_key(partial(string_begins_with, prefix), d)
111
+ kwargs_without_prefix = dict(map(lambda x: (x[0][len(prefix):], x[1]), tuple(kwargs_with_prefix.items())))
112
+ return kwargs_without_prefix, kwargs
113
+
114
+
115
+ # classes
116
+ class Scale(nn.Module):
117
+ def __init__(self, value, fn):
118
+ super().__init__()
119
+ self.value = value
120
+ self.fn = fn
121
+
122
+ def forward(self, x, **kwargs):
123
+ x, *rest = self.fn(x, **kwargs)
124
+ return (x * self.value, *rest)
125
+
126
+
127
+ class Rezero(nn.Module):
128
+ def __init__(self, fn):
129
+ super().__init__()
130
+ self.fn = fn
131
+ self.g = nn.Parameter(torch.zeros(1))
132
+
133
+ def forward(self, x, **kwargs):
134
+ x, *rest = self.fn(x, **kwargs)
135
+ return (x * self.g, *rest)
136
+
137
+
138
+ class ScaleNorm(nn.Module):
139
+ def __init__(self, dim, eps=1e-5):
140
+ super().__init__()
141
+ self.scale = dim ** -0.5
142
+ self.eps = eps
143
+ self.g = nn.Parameter(torch.ones(1))
144
+
145
+ def forward(self, x):
146
+ norm = torch.norm(x, dim=-1, keepdim=True) * self.scale
147
+ return x / norm.clamp(min=self.eps) * self.g
148
+
149
+
150
+ class RMSNorm(nn.Module):
151
+ def __init__(self, dim, eps=1e-8):
152
+ super().__init__()
153
+ self.scale = dim ** -0.5
154
+ self.eps = eps
155
+ self.g = nn.Parameter(torch.ones(dim))
156
+
157
+ def forward(self, x):
158
+ norm = torch.norm(x, dim=-1, keepdim=True) * self.scale
159
+ return x / norm.clamp(min=self.eps) * self.g
160
+
161
+
162
+ class Residual(nn.Module):
163
+ def forward(self, x, residual):
164
+ return x + residual
165
+
166
+
167
+ class GRUGating(nn.Module):
168
+ def __init__(self, dim):
169
+ super().__init__()
170
+ self.gru = nn.GRUCell(dim, dim)
171
+
172
+ def forward(self, x, residual):
173
+ gated_output = self.gru(
174
+ rearrange(x, 'b n d -> (b n) d'),
175
+ rearrange(residual, 'b n d -> (b n) d')
176
+ )
177
+
178
+ return gated_output.reshape_as(x)
179
+
180
+
181
+ # feedforward
182
+
183
+ class GEGLU(nn.Module):
184
+ def __init__(self, dim_in, dim_out):
185
+ super().__init__()
186
+ self.proj = nn.Linear(dim_in, dim_out * 2)
187
+
188
+ def forward(self, x):
189
+ x, gate = self.proj(x).chunk(2, dim=-1)
190
+ return x * F.gelu(gate)
191
+
192
+
193
+ class FeedForward(nn.Module):
194
+ def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
195
+ super().__init__()
196
+ inner_dim = int(dim * mult)
197
+ dim_out = default(dim_out, dim)
198
+ project_in = nn.Sequential(
199
+ nn.Linear(dim, inner_dim),
200
+ nn.GELU()
201
+ ) if not glu else GEGLU(dim, inner_dim)
202
+
203
+ self.net = nn.Sequential(
204
+ project_in,
205
+ nn.Dropout(dropout),
206
+ nn.Linear(inner_dim, dim_out)
207
+ )
208
+
209
+ def forward(self, x):
210
+ return self.net(x)
211
+
212
+
213
+ # attention.
214
+ class Attention(nn.Module):
215
+ def __init__(
216
+ self,
217
+ dim,
218
+ dim_head=DEFAULT_DIM_HEAD,
219
+ heads=8,
220
+ causal=False,
221
+ mask=None,
222
+ talking_heads=False,
223
+ sparse_topk=None,
224
+ use_entmax15=False,
225
+ num_mem_kv=0,
226
+ dropout=0.,
227
+ on_attn=False
228
+ ):
229
+ super().__init__()
230
+ if use_entmax15:
231
+ raise NotImplementedError("Check out entmax activation instead of softmax activation!")
232
+ self.scale = dim_head ** -0.5
233
+ self.heads = heads
234
+ self.causal = causal
235
+ self.mask = mask
236
+
237
+ inner_dim = dim_head * heads
238
+
239
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
240
+ self.to_k = nn.Linear(dim, inner_dim, bias=False)
241
+ self.to_v = nn.Linear(dim, inner_dim, bias=False)
242
+ self.dropout = nn.Dropout(dropout)
243
+
244
+ # talking heads
245
+ self.talking_heads = talking_heads
246
+ if talking_heads:
247
+ self.pre_softmax_proj = nn.Parameter(torch.randn(heads, heads))
248
+ self.post_softmax_proj = nn.Parameter(torch.randn(heads, heads))
249
+
250
+ # explicit topk sparse attention
251
+ self.sparse_topk = sparse_topk
252
+
253
+ # entmax
254
+ #self.attn_fn = entmax15 if use_entmax15 else F.softmax
255
+ self.attn_fn = F.softmax
256
+
257
+ # add memory key / values
258
+ self.num_mem_kv = num_mem_kv
259
+ if num_mem_kv > 0:
260
+ self.mem_k = nn.Parameter(torch.randn(heads, num_mem_kv, dim_head))
261
+ self.mem_v = nn.Parameter(torch.randn(heads, num_mem_kv, dim_head))
262
+
263
+ # attention on attention
264
+ self.attn_on_attn = on_attn
265
+ self.to_out = nn.Sequential(nn.Linear(inner_dim, dim * 2), nn.GLU()) if on_attn else nn.Linear(inner_dim, dim)
266
+
267
+ def forward(
268
+ self,
269
+ x,
270
+ context=None,
271
+ mask=None,
272
+ context_mask=None,
273
+ rel_pos=None,
274
+ sinusoidal_emb=None,
275
+ prev_attn=None,
276
+ mem=None
277
+ ):
278
+ b, n, _, h, talking_heads, device = *x.shape, self.heads, self.talking_heads, x.device
279
+ kv_input = default(context, x)
280
+
281
+ q_input = x
282
+ k_input = kv_input
283
+ v_input = kv_input
284
+
285
+ if exists(mem):
286
+ k_input = torch.cat((mem, k_input), dim=-2)
287
+ v_input = torch.cat((mem, v_input), dim=-2)
288
+
289
+ if exists(sinusoidal_emb):
290
+ # in shortformer, the query would start at a position offset depending on the past cached memory
291
+ offset = k_input.shape[-2] - q_input.shape[-2]
292
+ q_input = q_input + sinusoidal_emb(q_input, offset=offset)
293
+ k_input = k_input + sinusoidal_emb(k_input)
294
+
295
+ q = self.to_q(q_input)
296
+ k = self.to_k(k_input)
297
+ v = self.to_v(v_input)
298
+
299
+ q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h=h), (q, k, v))
300
+
301
+ input_mask = None
302
+ if any(map(exists, (mask, context_mask))):
303
+ q_mask = default(mask, lambda: torch.ones((b, n), device=device).bool())
304
+ k_mask = q_mask if not exists(context) else context_mask
305
+ k_mask = default(k_mask, lambda: torch.ones((b, k.shape[-2]), device=device).bool())
306
+ q_mask = rearrange(q_mask, 'b i -> b () i ()')
307
+ k_mask = rearrange(k_mask, 'b j -> b () () j')
308
+ input_mask = q_mask * k_mask
309
+
310
+ if self.num_mem_kv > 0:
311
+ mem_k, mem_v = map(lambda t: repeat(t, 'h n d -> b h n d', b=b), (self.mem_k, self.mem_v))
312
+ k = torch.cat((mem_k, k), dim=-2)
313
+ v = torch.cat((mem_v, v), dim=-2)
314
+ if exists(input_mask):
315
+ input_mask = F.pad(input_mask, (self.num_mem_kv, 0), value=True)
316
+
317
+ dots = einsum('b h i d, b h j d -> b h i j', q, k) * self.scale
318
+ mask_value = max_neg_value(dots)
319
+
320
+ if exists(prev_attn):
321
+ dots = dots + prev_attn
322
+
323
+ pre_softmax_attn = dots
324
+
325
+ if talking_heads:
326
+ dots = einsum('b h i j, h k -> b k i j', dots, self.pre_softmax_proj).contiguous()
327
+
328
+ if exists(rel_pos):
329
+ dots = rel_pos(dots)
330
+
331
+ if exists(input_mask):
332
+ dots.masked_fill_(~input_mask, mask_value)
333
+ del input_mask
334
+
335
+ if self.causal:
336
+ i, j = dots.shape[-2:]
337
+ r = torch.arange(i, device=device)
338
+ mask = rearrange(r, 'i -> () () i ()') < rearrange(r, 'j -> () () () j')
339
+ mask = F.pad(mask, (j - i, 0), value=False)
340
+ dots.masked_fill_(mask, mask_value)
341
+ del mask
342
+
343
+ if exists(self.sparse_topk) and self.sparse_topk < dots.shape[-1]:
344
+ top, _ = dots.topk(self.sparse_topk, dim=-1)
345
+ vk = top[..., -1].unsqueeze(-1).expand_as(dots)
346
+ mask = dots < vk
347
+ dots.masked_fill_(mask, mask_value)
348
+ del mask
349
+
350
+ attn = self.attn_fn(dots, dim=-1)
351
+ post_softmax_attn = attn
352
+
353
+ attn = self.dropout(attn)
354
+
355
+ if talking_heads:
356
+ attn = einsum('b h i j, h k -> b k i j', attn, self.post_softmax_proj).contiguous()
357
+
358
+ out = einsum('b h i j, b h j d -> b h i d', attn, v)
359
+ out = rearrange(out, 'b h n d -> b n (h d)')
360
+
361
+ intermediates = Intermediates(
362
+ pre_softmax_attn=pre_softmax_attn,
363
+ post_softmax_attn=post_softmax_attn
364
+ )
365
+
366
+ return self.to_out(out), intermediates
367
+
368
+
369
+ class AttentionLayers(nn.Module):
370
+ def __init__(
371
+ self,
372
+ dim,
373
+ depth,
374
+ heads=8,
375
+ causal=False,
376
+ cross_attend=False,
377
+ only_cross=False,
378
+ use_scalenorm=False,
379
+ use_rmsnorm=False,
380
+ use_rezero=False,
381
+ rel_pos_num_buckets=32,
382
+ rel_pos_max_distance=128,
383
+ position_infused_attn=False,
384
+ custom_layers=None,
385
+ sandwich_coef=None,
386
+ par_ratio=None,
387
+ residual_attn=False,
388
+ cross_residual_attn=False,
389
+ macaron=False,
390
+ pre_norm=True,
391
+ gate_residual=False,
392
+ **kwargs
393
+ ):
394
+ super().__init__()
395
+ ff_kwargs, kwargs = groupby_prefix_and_trim('ff_', kwargs)
396
+ attn_kwargs, _ = groupby_prefix_and_trim('attn_', kwargs)
397
+
398
+ dim_head = attn_kwargs.get('dim_head', DEFAULT_DIM_HEAD)
399
+
400
+ self.dim = dim
401
+ self.depth = depth
402
+ self.layers = nn.ModuleList([])
403
+
404
+ self.has_pos_emb = position_infused_attn
405
+ self.pia_pos_emb = FixedPositionalEmbedding(dim) if position_infused_attn else None
406
+ self.rotary_pos_emb = always(None)
407
+
408
+ assert rel_pos_num_buckets <= rel_pos_max_distance, 'number of relative position buckets must be less than the relative position max distance'
409
+ self.rel_pos = None
410
+
411
+ self.pre_norm = pre_norm
412
+
413
+ self.residual_attn = residual_attn
414
+ self.cross_residual_attn = cross_residual_attn
415
+
416
+ norm_class = ScaleNorm if use_scalenorm else nn.LayerNorm
417
+ norm_class = RMSNorm if use_rmsnorm else norm_class
418
+ norm_fn = partial(norm_class, dim)
419
+
420
+ norm_fn = nn.Identity if use_rezero else norm_fn
421
+ branch_fn = Rezero if use_rezero else None
422
+
423
+ if cross_attend and not only_cross:
424
+ default_block = ('a', 'c', 'f')
425
+ elif cross_attend and only_cross:
426
+ default_block = ('c', 'f')
427
+ else:
428
+ default_block = ('a', 'f')
429
+
430
+ if macaron:
431
+ default_block = ('f',) + default_block
432
+
433
+ if exists(custom_layers):
434
+ layer_types = custom_layers
435
+ elif exists(par_ratio):
436
+ par_depth = depth * len(default_block)
437
+ assert 1 < par_ratio <= par_depth, 'par ratio out of range'
438
+ default_block = tuple(filter(not_equals('f'), default_block))
439
+ par_attn = par_depth // par_ratio
440
+ depth_cut = par_depth * 2 // 3 # 2 / 3 attention layer cutoff suggested by PAR paper
441
+ par_width = (depth_cut + depth_cut // par_attn) // par_attn
442
+ assert len(default_block) <= par_width, 'default block is too large for par_ratio'
443
+ par_block = default_block + ('f',) * (par_width - len(default_block))
444
+ par_head = par_block * par_attn
445
+ layer_types = par_head + ('f',) * (par_depth - len(par_head))
446
+ elif exists(sandwich_coef):
447
+ assert sandwich_coef > 0 and sandwich_coef <= depth, 'sandwich coefficient should be less than the depth'
448
+ layer_types = ('a',) * sandwich_coef + default_block * (depth - sandwich_coef) + ('f',) * sandwich_coef
449
+ else:
450
+ layer_types = default_block * depth
451
+
452
+ self.layer_types = layer_types
453
+ self.num_attn_layers = len(list(filter(equals('a'), layer_types)))
454
+
455
+ for layer_type in self.layer_types:
456
+ if layer_type == 'a':
457
+ layer = Attention(dim, heads=heads, causal=causal, **attn_kwargs)
458
+ elif layer_type == 'c':
459
+ layer = Attention(dim, heads=heads, **attn_kwargs)
460
+ elif layer_type == 'f':
461
+ layer = FeedForward(dim, **ff_kwargs)
462
+ layer = layer if not macaron else Scale(0.5, layer)
463
+ else:
464
+ raise Exception(f'invalid layer type {layer_type}')
465
+
466
+ if isinstance(layer, Attention) and exists(branch_fn):
467
+ layer = branch_fn(layer)
468
+
469
+ if gate_residual:
470
+ residual_fn = GRUGating(dim)
471
+ else:
472
+ residual_fn = Residual()
473
+
474
+ self.layers.append(nn.ModuleList([
475
+ norm_fn(),
476
+ layer,
477
+ residual_fn
478
+ ]))
479
+
480
+ def forward(
481
+ self,
482
+ x,
483
+ context=None,
484
+ mask=None,
485
+ context_mask=None,
486
+ mems=None,
487
+ return_hiddens=False
488
+ ):
489
+ hiddens = []
490
+ intermediates = []
491
+ prev_attn = None
492
+ prev_cross_attn = None
493
+
494
+ mems = mems.copy() if exists(mems) else [None] * self.num_attn_layers
495
+
496
+ for ind, (layer_type, (norm, block, residual_fn)) in enumerate(zip(self.layer_types, self.layers)):
497
+ is_last = ind == (len(self.layers) - 1)
498
+
499
+ if layer_type == 'a':
500
+ hiddens.append(x)
501
+ layer_mem = mems.pop(0)
502
+
503
+ residual = x
504
+
505
+ if self.pre_norm:
506
+ x = norm(x)
507
+
508
+ if layer_type == 'a':
509
+ out, inter = block(x, mask=mask, sinusoidal_emb=self.pia_pos_emb, rel_pos=self.rel_pos,
510
+ prev_attn=prev_attn, mem=layer_mem)
511
+ elif layer_type == 'c':
512
+ out, inter = block(x, context=context, mask=mask, context_mask=context_mask, prev_attn=prev_cross_attn)
513
+ elif layer_type == 'f':
514
+ out = block(x)
515
+
516
+ x = residual_fn(out, residual)
517
+
518
+ if layer_type in ('a', 'c'):
519
+ intermediates.append(inter)
520
+
521
+ if layer_type == 'a' and self.residual_attn:
522
+ prev_attn = inter.pre_softmax_attn
523
+ elif layer_type == 'c' and self.cross_residual_attn:
524
+ prev_cross_attn = inter.pre_softmax_attn
525
+
526
+ if not self.pre_norm and not is_last:
527
+ x = norm(x)
528
+
529
+ if return_hiddens:
530
+ intermediates = LayerIntermediates(
531
+ hiddens=hiddens,
532
+ attn_intermediates=intermediates
533
+ )
534
+
535
+ return x, intermediates
536
+
537
+ return x
538
+
539
+
540
+ class Encoder(AttentionLayers):
541
+ def __init__(self, **kwargs):
542
+ assert 'causal' not in kwargs, 'cannot set causality on encoder'
543
+ super().__init__(causal=False, **kwargs)
544
+
545
+
546
+
547
+ class TransformerWrapper(nn.Module):
548
+ def __init__(
549
+ self,
550
+ *,
551
+ num_tokens,
552
+ max_seq_len,
553
+ attn_layers,
554
+ emb_dim=None,
555
+ max_mem_len=0.,
556
+ emb_dropout=0.,
557
+ num_memory_tokens=None,
558
+ tie_embedding=False,
559
+ use_pos_emb=True
560
+ ):
561
+ super().__init__()
562
+ assert isinstance(attn_layers, AttentionLayers), 'attention layers must be one of Encoder or Decoder'
563
+
564
+ dim = attn_layers.dim
565
+ emb_dim = default(emb_dim, dim)
566
+
567
+ self.max_seq_len = max_seq_len
568
+ self.max_mem_len = max_mem_len
569
+ self.num_tokens = num_tokens
570
+
571
+ self.token_emb = nn.Embedding(num_tokens, emb_dim)
572
+ self.pos_emb = AbsolutePositionalEmbedding(emb_dim, max_seq_len) if (
573
+ use_pos_emb and not attn_layers.has_pos_emb) else always(0)
574
+ self.emb_dropout = nn.Dropout(emb_dropout)
575
+
576
+ self.project_emb = nn.Linear(emb_dim, dim) if emb_dim != dim else nn.Identity()
577
+ self.attn_layers = attn_layers
578
+ self.norm = nn.LayerNorm(dim)
579
+
580
+ self.init_()
581
+
582
+ self.to_logits = nn.Linear(dim, num_tokens) if not tie_embedding else lambda t: t @ self.token_emb.weight.t()
583
+
584
+ # memory tokens (like [cls]) from Memory Transformers paper
585
+ num_memory_tokens = default(num_memory_tokens, 0)
586
+ self.num_memory_tokens = num_memory_tokens
587
+ if num_memory_tokens > 0:
588
+ self.memory_tokens = nn.Parameter(torch.randn(num_memory_tokens, dim))
589
+
590
+ # let funnel encoder know number of memory tokens, if specified
591
+ if hasattr(attn_layers, 'num_memory_tokens'):
592
+ attn_layers.num_memory_tokens = num_memory_tokens
593
+
594
+ def init_(self):
595
+ nn.init.normal_(self.token_emb.weight, std=0.02)
596
+
597
+ def forward(
598
+ self,
599
+ x,
600
+ return_embeddings=False,
601
+ mask=None,
602
+ return_mems=False,
603
+ return_attn=False,
604
+ mems=None,
605
+ **kwargs
606
+ ):
607
+ b, n, device, num_mem = *x.shape, x.device, self.num_memory_tokens
608
+ x = self.token_emb(x)
609
+ x += self.pos_emb(x)
610
+ x = self.emb_dropout(x)
611
+
612
+ x = self.project_emb(x)
613
+
614
+ if num_mem > 0:
615
+ mem = repeat(self.memory_tokens, 'n d -> b n d', b=b)
616
+ x = torch.cat((mem, x), dim=1)
617
+
618
+ # auto-handle masking after appending memory tokens
619
+ if exists(mask):
620
+ mask = F.pad(mask, (num_mem, 0), value=True)
621
+
622
+ x, intermediates = self.attn_layers(x, mask=mask, mems=mems, return_hiddens=True, **kwargs)
623
+ x = self.norm(x)
624
+
625
+ mem, x = x[:, :num_mem], x[:, num_mem:]
626
+
627
+ out = self.to_logits(x) if not return_embeddings else x
628
+
629
+ if return_mems:
630
+ hiddens = intermediates.hiddens
631
+ new_mems = list(map(lambda pair: torch.cat(pair, dim=-2), zip(mems, hiddens))) if exists(mems) else hiddens
632
+ new_mems = list(map(lambda t: t[..., -self.max_mem_len:, :].detach(), new_mems))
633
+ return out, new_mems
634
+
635
+ if return_attn:
636
+ attn_maps = list(map(lambda t: t.post_softmax_attn, intermediates.attn_intermediates))
637
+ return out, attn_maps
638
+
639
+ return out
640
+
scripts/evaluation/__pycache__/style_inference.cpython-39.pyc ADDED
Binary file (10.6 kB). View file
 
scripts/evaluation/ddp_wrapper.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, sys
2
+ import datetime, time
3
+ import argparse, importlib
4
+ from pytorch_lightning import seed_everything
5
+
6
+ import torch
7
+ import torch.distributed as dist
8
+ #from inference import run_inference, get_parser
9
+
10
+ def setup_dist(local_rank):
11
+ if dist.is_initialized():
12
+ return
13
+ torch.cuda.set_device(local_rank)
14
+ torch.distributed.init_process_group('nccl', init_method='env://')
15
+
16
+
17
+ def get_dist_info():
18
+ if dist.is_available():
19
+ initialized = dist.is_initialized()
20
+ else:
21
+ initialized = False
22
+ if initialized:
23
+ rank = dist.get_rank()
24
+ world_size = dist.get_world_size()
25
+ else:
26
+ rank = 0
27
+ world_size = 1
28
+ return rank, world_size
29
+
30
+
31
+ if __name__ == '__main__':
32
+ now = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
33
+ parser = argparse.ArgumentParser()
34
+ parser.add_argument("--module", type=str, help="module name", default="inference")
35
+ parser.add_argument("--local_rank", type=int, nargs="?", help="for ddp", default=0)
36
+ args, unknown = parser.parse_known_args()
37
+ inference_api = importlib.import_module(args.module, package=None)
38
+
39
+ inference_parser = inference_api.get_parser()
40
+ inference_args, unknown = inference_parser.parse_known_args()
41
+
42
+ seed_everything(inference_args.seed)
43
+ setup_dist(args.local_rank)
44
+ torch.backends.cudnn.benchmark = True
45
+ rank, gpu_num = get_dist_info()
46
+
47
+ print("@CoLVDM Inference [rank%d]: %s"%(rank, now))
48
+ inference_api.run_inference(inference_args, gpu_num, rank)
scripts/evaluation/funcs.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse, os, sys, glob, yaml, math, random
2
+ import datetime, time
3
+ import numpy as np
4
+ from omegaconf import OmegaConf
5
+ from tqdm import trange, tqdm
6
+ from einops import repeat
7
+ from collections import OrderedDict
8
+ from decord import VideoReader, cpu
9
+
10
+ import torch
11
+ import torchvision
12
+ sys.path.insert(1, os.path.join(sys.path[0], '..', '..'))
13
+ from lvdm.models.samplers.ddim import DDIMSampler
14
+
15
+
16
+ def batch_ddim_sampling(model, cond, noise_shape, n_samples=1, ddim_steps=50, ddim_eta=1.0,\
17
+ cfg_scale=1.0, temporal_cfg_scale=None, **kwargs):
18
+ ddim_sampler = DDIMSampler(model)
19
+ uncond_type = model.uncond_type
20
+ batch_size = noise_shape[0]
21
+
22
+ ## construct unconditional guidance
23
+ if cfg_scale != 1.0:
24
+ if isinstance(cond, dict):
25
+ c_cat, text_emb = cond["c_concat"][0], cond["c_crossattn"][0]
26
+ else:
27
+ text_emb = cond
28
+
29
+ if uncond_type == "empty_seq":
30
+ prompts = batch_size * [""]
31
+ uc = model.get_learned_conditioning(prompts)
32
+ elif uncond_type == "zero_embed":
33
+ uc = torch.zeros_like(text_emb)
34
+ else:
35
+ raise NotImplementedError
36
+
37
+ ## hybrid case
38
+ if isinstance(cond, dict):
39
+ uc_hybrid = {"c_concat": [c_cat], "c_crossattn": [uc]}
40
+ if 'c_adm' in cond:
41
+ uc_hybrid.update({'c_adm': cond['c_adm']})
42
+ uc = uc_hybrid
43
+ else:
44
+ uc = None
45
+
46
+ ## sampling
47
+ batch_variants = []
48
+ for _ in range(n_samples):
49
+ if ddim_sampler is not None:
50
+ kwargs.update({"clean_cond": True})
51
+ samples, _ = ddim_sampler.sample(S=ddim_steps,
52
+ conditioning=cond,
53
+ batch_size=noise_shape[0],
54
+ shape=noise_shape[1:],
55
+ verbose=False,
56
+ unconditional_guidance_scale=cfg_scale,
57
+ unconditional_conditioning=uc,
58
+ eta=ddim_eta,
59
+ temporal_length=noise_shape[2],
60
+ conditional_guidance_scale_temporal=temporal_cfg_scale,
61
+ x_T=None,
62
+ **kwargs
63
+ )
64
+ ## reconstruct from latent to pixel space
65
+ batch_images = model.decode_first_stage(samples)
66
+ batch_variants.append(batch_images)
67
+ ## batch, <samples>, c, t, h, w
68
+ batch_variants = torch.stack(batch_variants, dim=1)
69
+ return batch_variants
70
+
71
+
72
+ def batch_sliding_interpolation(model, cond, base_videos, base_stride, noise_shape, n_samples=1,\
73
+ ddim_steps=50, ddim_eta=1.0, cfg_scale=1.0, temporal_cfg_scale=None, **kwargs):
74
+ '''
75
+ Current implementation has a flaw: the inter-episode keyframe is used as pre-last and cur-first, so keyframe repeated.
76
+ For example, cond_frames=[0,4,7], model.temporal_length=8, base_stride=4, then
77
+ base frame : 0 4 8 12 16 20 24 28
78
+ interplation: (0~7) (8~15) (16~23) (20~27)
79
+ '''
80
+ b,c,t,h,w = noise_shape
81
+ base_z0 = model.encode_first_stage(base_videos)
82
+ unit_length = model.temporal_length
83
+ n_base_frames = base_videos.shape[2]
84
+ n_refs = len(model.cond_frames)
85
+ sliding_steps = (n_base_frames-1) // (n_refs-1)
86
+ sliding_steps = sliding_steps+1 if (n_base_frames-1) % (n_refs-1) > 0 else sliding_steps
87
+
88
+ cond_mask = model.cond_mask.to("cuda")
89
+ proxy_z0 = torch.zeros((b,c,unit_length,h,w), dtype=torch.float32).to("cuda")
90
+ batch_samples = None
91
+ last_offset = None
92
+ for idx in range(sliding_steps):
93
+ base_idx = idx * (n_refs-1)
94
+ ## check index overflow
95
+ if base_idx+n_refs > n_base_frames:
96
+ last_offset = base_idx - (n_base_frames - n_refs)
97
+ base_idx = n_base_frames - n_refs
98
+ cond_z0 = base_z0[:,:,base_idx:base_idx+n_refs,:,:]
99
+ proxy_z0[:,:,model.cond_frames,:,:] = cond_z0
100
+
101
+ if isinstance(cond, dict):
102
+ c_cat, text_emb = cond["c_concat"][0], cond["c_crossattn"][0]
103
+ episode_idx = idx * unit_length
104
+ if last_offset is not None:
105
+ episode_idx = episode_idx - last_offset * base_stride
106
+ cond_idx = {"c_concat": [c_cat[:,:,episode_idx:episode_idx+unit_length,:,:]], "c_crossattn": [text_emb]}
107
+ else:
108
+ cond_idx = cond
109
+ noise_shape_idx = [b,c,unit_length,h,w]
110
+ ## batch, <samples>, c, t, h, w
111
+ batch_idx = batch_ddim_sampling(model, cond_idx, noise_shape_idx, n_samples, ddim_steps, ddim_eta, cfg_scale, \
112
+ temporal_cfg_scale, mask=cond_mask, x0=proxy_z0, **kwargs)
113
+
114
+ if batch_samples is None:
115
+ batch_samples = batch_idx
116
+ else:
117
+ ## b,s,c,t,h,w
118
+ if last_offset is None:
119
+ batch_samples = torch.cat([batch_samples[:,:,:,:-1,:,:], batch_idx], dim=3)
120
+ else:
121
+ batch_samples = torch.cat([batch_samples[:,:,:,:-1,:,:], batch_idx[:,:,:,last_offset * base_stride:,:,:]], dim=3)
122
+
123
+ return batch_samples
124
+
125
+
126
+ def get_filelist(data_dir, ext='*'):
127
+ file_list = glob.glob(os.path.join(data_dir, '*.%s'%ext))
128
+ file_list.sort()
129
+ return file_list
130
+
131
+ def get_dirlist(path):
132
+ list = []
133
+ if (os.path.exists(path)):
134
+ files = os.listdir(path)
135
+ for file in files:
136
+ m = os.path.join(path,file)
137
+ if (os.path.isdir(m)):
138
+ list.append(m)
139
+ list.sort()
140
+ return list
141
+
142
+
143
+ def load_model_checkpoint(model, ckpt, adapter_ckpt=None):
144
+ def load_checkpoint(model, ckpt, full_strict):
145
+ state_dict = torch.load(ckpt, map_location="cpu")
146
+ try:
147
+ ## deepspeed
148
+ new_pl_sd = OrderedDict()
149
+ for key in state_dict['module'].keys():
150
+ new_pl_sd[key[16:]]=state_dict['module'][key]
151
+ model.load_state_dict(new_pl_sd, strict=full_strict)
152
+ except:
153
+ if "state_dict" in list(state_dict.keys()):
154
+ state_dict = state_dict["state_dict"]
155
+ model.load_state_dict(state_dict, strict=full_strict)
156
+ return model
157
+
158
+ if adapter_ckpt:
159
+ ## main model
160
+ load_checkpoint(model, ckpt, full_strict=False)
161
+ print('>>> model checkpoint loaded.')
162
+ ## adapter
163
+ state_dict = torch.load(adapter_ckpt, map_location="cpu")
164
+ if "state_dict" in list(state_dict.keys()):
165
+ state_dict = state_dict["state_dict"]
166
+ model.adapter.load_state_dict(state_dict, strict=True)
167
+ print('>>> adapter checkpoint loaded.')
168
+ else:
169
+ load_checkpoint(model, ckpt, full_strict=True)
170
+ print('>>> model checkpoint loaded.')
171
+ return model
172
+
173
+
174
+ def load_prompts(prompt_file):
175
+ f = open(prompt_file, 'r')
176
+ prompt_list = []
177
+ for idx, line in enumerate(f.readlines()):
178
+ l = line.strip()
179
+ if len(l) != 0:
180
+ prompt_list.append(l)
181
+ f.close()
182
+ return prompt_list
183
+
184
+
185
+ def load_video_batch(filepath_list, frame_stride, video_size=(256,256), video_frames=16):
186
+ '''
187
+ Notice about some special cases:
188
+ 1. video_frames=-1 means to take all the frames (with fs=1)
189
+ 2. when the total video frames is less than required, padding strategy will be used (repreated last frame)
190
+ '''
191
+ fps_list = []
192
+ batch_tensor = []
193
+ assert frame_stride > 0, "valid frame stride should be a positive interge!"
194
+ for filepath in filepath_list:
195
+ padding_num = 0
196
+ vidreader = VideoReader(filepath, ctx=cpu(0), width=video_size[1], height=video_size[0])
197
+ fps = vidreader.get_avg_fps()
198
+ total_frames = len(vidreader)
199
+ max_valid_frames = (total_frames-1) // frame_stride + 1
200
+ if video_frames < 0:
201
+ ## all frames are collected: fs=1 is a must
202
+ required_frames = total_frames
203
+ frame_stride = 1
204
+ else:
205
+ required_frames = video_frames
206
+ query_frames = min(required_frames, max_valid_frames)
207
+ frame_indices = [frame_stride*i for i in range(query_frames)]
208
+
209
+ ## [t,h,w,c] -> [c,t,h,w]
210
+ frames = vidreader.get_batch(frame_indices)
211
+ frame_tensor = torch.tensor(frames.asnumpy()).permute(3, 0, 1, 2).float()
212
+ frame_tensor = (frame_tensor / 255. - 0.5) * 2
213
+ if max_valid_frames < required_frames:
214
+ padding_num = required_frames - max_valid_frames
215
+ frame_tensor = torch.cat([frame_tensor, *([frame_tensor[:,-1:,:,:]]*padding_num)], dim=1)
216
+ print(f'{os.path.split(filepath)[1]} is not long enough: {padding_num} frames padded.')
217
+ batch_tensor.append(frame_tensor)
218
+ sample_fps = int(fps/frame_stride)
219
+ fps_list.append(sample_fps)
220
+
221
+ return torch.stack(batch_tensor, dim=0)
222
+
223
+
224
+ def save_videos(batch_tensors, savedir, filenames, fps=10):
225
+ # b,samples,c,t,h,w
226
+ n_samples = batch_tensors.shape[1]
227
+ for idx, vid_tensor in enumerate(batch_tensors):
228
+ video = vid_tensor.detach().cpu()
229
+ video = torch.clamp(video.float(), -1., 1.)
230
+ video = video.permute(2, 0, 1, 3, 4) # t,n,c,h,w
231
+ frame_grids = [torchvision.utils.make_grid(framesheet, nrow=int(n_samples)) for framesheet in video] #[3, 1*h, n*w]
232
+ grid = torch.stack(frame_grids, dim=0) # stack in temporal dim [t, 3, n*h, w]
233
+ grid = (grid + 1.0) / 2.0
234
+ grid = (grid * 255).to(torch.uint8).permute(0, 2, 3, 1)
235
+ savepath = os.path.join(savedir, f"{filenames[idx]}.mp4")
236
+ torchvision.io.write_video(savepath, grid, fps=fps, video_codec='h264', options={'crf': '10'})
237
+