ashawkey commited on
Commit
90fd8f8
1 Parent(s): d8cab09
app.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tyro
3
+ import imageio
4
+ import numpy as np
5
+ import tqdm
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ import torchvision.transforms.functional as TF
10
+ from safetensors.torch import load_file
11
+ import rembg
12
+ import gradio as gr
13
+
14
+ import kiui
15
+ from kiui.op import recenter
16
+ from kiui.cam import orbit_camera
17
+
18
+ from core.options import AllConfigs, Options
19
+ from core.models import LGM
20
+ from mvdream.pipeline_mvdream import MVDreamPipeline
21
+
22
+ IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406)
23
+ IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225)
24
+ GRADIO_VIDEO_PATH = 'gradio_output.mp4'
25
+ GRADIO_PLY_PATH = 'gradio_output.ply'
26
+
27
+ opt = tyro.cli(AllConfigs)
28
+
29
+ # model
30
+ model = LGM(opt)
31
+
32
+ # resume pretrained checkpoint
33
+ if opt.resume is not None:
34
+ if opt.resume.endswith('safetensors'):
35
+ ckpt = load_file(opt.resume, device='cpu')
36
+ else:
37
+ ckpt = torch.load(opt.resume, map_location='cpu')
38
+ model.load_state_dict(ckpt, strict=False)
39
+ print(f'[INFO] Loaded checkpoint from {opt.resume}')
40
+ else:
41
+ print(f'[WARN] model randomly initialized, are you sure?')
42
+
43
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
44
+ model = model.half().to(device)
45
+ model.eval()
46
+
47
+ tan_half_fov = np.tan(0.5 * np.deg2rad(opt.fovy))
48
+ proj_matrix = torch.zeros(4, 4, dtype=torch.float32, device=device)
49
+ proj_matrix[0, 0] = 1 / tan_half_fov
50
+ proj_matrix[1, 1] = 1 / tan_half_fov
51
+ proj_matrix[2, 2] = (opt.zfar + opt.znear) / (opt.zfar - opt.znear)
52
+ proj_matrix[3, 2] = - (opt.zfar * opt.znear) / (opt.zfar - opt.znear)
53
+ proj_matrix[2, 3] = 1
54
+
55
+ # load dreams
56
+ pipe_text = MVDreamPipeline.from_pretrained(
57
+ 'ashawkey/mvdream-sd2.1-diffusers', # remote weights
58
+ torch_dtype=torch.float16,
59
+ trust_remote_code=True,
60
+ # local_files_only=True,
61
+ )
62
+ pipe_text = pipe_text.to(device)
63
+
64
+ pipe_image = MVDreamPipeline.from_pretrained(
65
+ "ashawkey/imagedream-ipmv-diffusers", # remote weights
66
+ torch_dtype=torch.float16,
67
+ trust_remote_code=True,
68
+ # local_files_only=True,
69
+ )
70
+ pipe_image = pipe_image.to(device)
71
+
72
+ # load rembg
73
+ bg_remover = rembg.new_session()
74
+
75
+ # process function
76
+ def process(input_image, prompt, prompt_neg='', input_elevation=0, input_num_steps=30, input_seed=42):
77
+
78
+ # seed
79
+ kiui.seed_everything(input_seed)
80
+
81
+ os.makedirs(opt.workspace, exist_ok=True)
82
+ output_video_path = os.path.join(opt.workspace, GRADIO_VIDEO_PATH)
83
+ output_ply_path = os.path.join(opt.workspace, GRADIO_PLY_PATH)
84
+
85
+ # text-conditioned
86
+ if input_image is None:
87
+ mv_image_uint8 = pipe_text(prompt, negative_prompt=prompt_neg, num_inference_steps=input_num_steps, guidance_scale=7.5, elevation=input_elevation)
88
+ mv_image_uint8 = (mv_image_uint8 * 255).astype(np.uint8)
89
+ # bg removal
90
+ mv_image = []
91
+ for i in range(4):
92
+ image = rembg.remove(mv_image_uint8[i], session=bg_remover) # [H, W, 4]
93
+ # to white bg
94
+ image = image.astype(np.float32) / 255
95
+ image = recenter(image, image[..., 0] > 0, border_ratio=0.2)
96
+ image = image[..., :3] * image[..., -1:] + (1 - image[..., -1:])
97
+ mv_image.append(image)
98
+ # image-conditioned (may also input text, but no text usually works too)
99
+ else:
100
+ input_image = np.array(input_image) # uint8
101
+ # bg removal
102
+ carved_image = rembg.remove(input_image, session=bg_remover) # [H, W, 4]
103
+ mask = carved_image[..., -1] > 0
104
+ image = recenter(carved_image, mask, border_ratio=0.2)
105
+ image = image.astype(np.float32) / 255.0
106
+ image = image[..., :3] * image[..., 3:4] + (1 - image[..., 3:4])
107
+ mv_image = pipe_image(prompt, image, negative_prompt=prompt_neg, num_inference_steps=input_num_steps, guidance_scale=5.0, elevation=input_elevation)
108
+
109
+ mv_image_grid = np.concatenate([
110
+ np.concatenate([mv_image[1], mv_image[2]], axis=1),
111
+ np.concatenate([mv_image[3], mv_image[0]], axis=1),
112
+ ], axis=0)
113
+
114
+ # generate gaussians
115
+ input_image = np.stack([mv_image[1], mv_image[2], mv_image[3], mv_image[0]], axis=0) # [4, 256, 256, 3], float32
116
+ input_image = torch.from_numpy(input_image).permute(0, 3, 1, 2).float().to(device) # [4, 3, 256, 256]
117
+ input_image = F.interpolate(input_image, size=(opt.input_size, opt.input_size), mode='bilinear', align_corners=False)
118
+ input_image = TF.normalize(input_image, IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD)
119
+
120
+ rays_embeddings = model.prepare_default_rays(device, elevation=input_elevation)
121
+ input_image = torch.cat([input_image, rays_embeddings], dim=1).unsqueeze(0) # [1, 4, 9, H, W]
122
+
123
+ with torch.no_grad():
124
+ with torch.autocast(device_type='cuda', dtype=torch.float16):
125
+ # generate gaussians
126
+ gaussians = model.forward_gaussians(input_image)
127
+
128
+ # save gaussians
129
+ model.gs.save_ply(gaussians, output_ply_path)
130
+
131
+ # render 360 video
132
+ images = []
133
+ elevation = 0
134
+ if opt.fancy_video:
135
+ azimuth = np.arange(0, 720, 4, dtype=np.int32)
136
+ for azi in tqdm.tqdm(azimuth):
137
+
138
+ cam_poses = torch.from_numpy(orbit_camera(elevation, azi, radius=opt.cam_radius, opengl=True)).unsqueeze(0).to(device)
139
+
140
+ cam_poses[:, :3, 1:3] *= -1 # invert up & forward direction
141
+
142
+ # cameras needed by gaussian rasterizer
143
+ cam_view = torch.inverse(cam_poses).transpose(1, 2) # [V, 4, 4]
144
+ cam_view_proj = cam_view @ proj_matrix # [V, 4, 4]
145
+ cam_pos = - cam_poses[:, :3, 3] # [V, 3]
146
+
147
+ scale = min(azi / 360, 1)
148
+
149
+ image = model.gs.render(gaussians, cam_view.unsqueeze(0), cam_view_proj.unsqueeze(0), cam_pos.unsqueeze(0), scale_modifier=scale)['image']
150
+ images.append((image.squeeze(1).permute(0,2,3,1).contiguous().float().cpu().numpy() * 255).astype(np.uint8))
151
+ else:
152
+ azimuth = np.arange(0, 360, 2, dtype=np.int32)
153
+ for azi in tqdm.tqdm(azimuth):
154
+
155
+ cam_poses = torch.from_numpy(orbit_camera(elevation, azi, radius=opt.cam_radius, opengl=True)).unsqueeze(0).to(device)
156
+
157
+ cam_poses[:, :3, 1:3] *= -1 # invert up & forward direction
158
+
159
+ # cameras needed by gaussian rasterizer
160
+ cam_view = torch.inverse(cam_poses).transpose(1, 2) # [V, 4, 4]
161
+ cam_view_proj = cam_view @ proj_matrix # [V, 4, 4]
162
+ cam_pos = - cam_poses[:, :3, 3] # [V, 3]
163
+
164
+ image = model.gs.render(gaussians, cam_view.unsqueeze(0), cam_view_proj.unsqueeze(0), cam_pos.unsqueeze(0), scale_modifier=1)['image']
165
+ images.append((image.squeeze(1).permute(0,2,3,1).contiguous().float().cpu().numpy() * 255).astype(np.uint8))
166
+
167
+ images = np.concatenate(images, axis=0)
168
+ imageio.mimwrite(output_video_path, images, fps=30)
169
+
170
+ return mv_image_grid, output_video_path, output_ply_path
171
+
172
+ # gradio UI
173
+
174
+ _TITLE = '''LGM: Large Multi-View Gaussian Model for High-Resolution 3D Content Creation'''
175
+
176
+ _DESCRIPTION = '''
177
+ <div>
178
+ <a style="display:inline-block" href="https://me.kiui.moe/lgm/"><img src='https://img.shields.io/badge/public_website-8A2BE2'></a>
179
+ <a style="display:inline-block; margin-left: .5em" href="https://github.com/3DTopia/LGM"><img src='https://img.shields.io/github/stars/3DTopia/LGM?style=social'/></a>
180
+ </div>
181
+
182
+ * Input can be only text, only image, or both image and text.
183
+ * If you find the output unsatisfying, try using different seeds!
184
+ '''
185
+
186
+ block = gr.Blocks(title=_TITLE).queue()
187
+ with block:
188
+ with gr.Row():
189
+ with gr.Column(scale=1):
190
+ gr.Markdown('# ' + _TITLE)
191
+ gr.Markdown(_DESCRIPTION)
192
+
193
+ with gr.Row(variant='panel'):
194
+ with gr.Column(scale=1):
195
+ # input image
196
+ input_image = gr.Image(label="image", type='pil')
197
+ # input prompt
198
+ input_text = gr.Textbox(label="prompt")
199
+ # negative prompt
200
+ input_neg_text = gr.Textbox(label="negative prompt", value='ugly, blurry, pixelated obscure, unnatural colors, poor lighting, dull, unclear, cropped, lowres, low quality, artifacts, duplicate')
201
+ # elevation
202
+ input_elevation = gr.Slider(label="elevation", minimum=-90, maximum=90, step=1, value=0)
203
+ # inference steps
204
+ input_num_steps = gr.Slider(label="inference steps", minimum=1, maximum=100, step=1, value=30)
205
+ # random seed
206
+ input_seed = gr.Slider(label="random seed", minimum=0, maximum=100000, step=1, value=0)
207
+ # gen button
208
+ button_gen = gr.Button("Generate")
209
+
210
+
211
+ with gr.Column(scale=1):
212
+ with gr.Tab("Video"):
213
+ # final video results
214
+ output_video = gr.Video(label="video")
215
+ # ply file
216
+ output_file = gr.File(label="ply")
217
+ with gr.Tab("Multi-view Image"):
218
+ # multi-view results
219
+ output_image = gr.Image(interactive=False, show_label=False)
220
+
221
+ button_gen.click(process, inputs=[input_image, input_text, input_neg_text, input_elevation, input_num_steps, input_seed], outputs=[output_image, output_video, output_file])
222
+
223
+ gr.Examples(
224
+ examples=[
225
+ "data_test/anya_rgba.png",
226
+ "data_test/bird_rgba.png",
227
+ "data_test/catstatue_rgba.png",
228
+ ],
229
+ inputs=[input_image],
230
+ outputs=[output_image, output_video, output_file],
231
+ fn=lambda x: process(input_image=x, prompt=''),
232
+ cache_examples=False,
233
+ label='Image-to-3D Examples'
234
+ )
235
+
236
+ gr.Examples(
237
+ examples=[
238
+ "a motorbike",
239
+ "a hamburger",
240
+ "a furry red fox head",
241
+ ],
242
+ inputs=[input_text],
243
+ outputs=[output_image, output_video, output_file],
244
+ fn=lambda x: process(input_image=None, prompt=x),
245
+ cache_examples=False,
246
+ label='Text-to-3D Examples'
247
+ )
248
+
249
+ block.launch()
core/__init__.py ADDED
File without changes
core/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (123 Bytes). View file
 
core/__pycache__/attention.cpython-39.pyc ADDED
Binary file (4.36 kB). View file
 
core/__pycache__/gs.cpython-39.pyc ADDED
Binary file (5.48 kB). View file
 
core/__pycache__/models.cpython-39.pyc ADDED
Binary file (4.47 kB). View file
 
core/__pycache__/options.cpython-39.pyc ADDED
Binary file (2.46 kB). View file
 
core/__pycache__/provider_objaverse.cpython-39.pyc ADDED
Binary file (7.74 kB). View file
 
core/__pycache__/unet.cpython-39.pyc ADDED
Binary file (7.45 kB). View file
 
core/__pycache__/utils.cpython-39.pyc ADDED
Binary file (2.54 kB). View file
 
core/attention.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ # References:
7
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
8
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
9
+
10
+ import os
11
+ import warnings
12
+
13
+ from torch import Tensor
14
+ from torch import nn
15
+
16
+ XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None
17
+ try:
18
+ if XFORMERS_ENABLED:
19
+ from xformers.ops import memory_efficient_attention, unbind
20
+
21
+ XFORMERS_AVAILABLE = True
22
+ warnings.warn("xFormers is available (Attention)")
23
+ else:
24
+ warnings.warn("xFormers is disabled (Attention)")
25
+ raise ImportError
26
+ except ImportError:
27
+ XFORMERS_AVAILABLE = False
28
+ warnings.warn("xFormers is not available (Attention)")
29
+
30
+
31
+ class Attention(nn.Module):
32
+ def __init__(
33
+ self,
34
+ dim: int,
35
+ num_heads: int = 8,
36
+ qkv_bias: bool = False,
37
+ proj_bias: bool = True,
38
+ attn_drop: float = 0.0,
39
+ proj_drop: float = 0.0,
40
+ ) -> None:
41
+ super().__init__()
42
+ self.num_heads = num_heads
43
+ head_dim = dim // num_heads
44
+ self.scale = head_dim**-0.5
45
+
46
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
47
+ self.attn_drop = nn.Dropout(attn_drop)
48
+ self.proj = nn.Linear(dim, dim, bias=proj_bias)
49
+ self.proj_drop = nn.Dropout(proj_drop)
50
+
51
+ def forward(self, x: Tensor) -> Tensor:
52
+ B, N, C = x.shape
53
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
54
+
55
+ q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]
56
+ attn = q @ k.transpose(-2, -1)
57
+
58
+ attn = attn.softmax(dim=-1)
59
+ attn = self.attn_drop(attn)
60
+
61
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
62
+ x = self.proj(x)
63
+ x = self.proj_drop(x)
64
+ return x
65
+
66
+
67
+ class MemEffAttention(Attention):
68
+ def forward(self, x: Tensor, attn_bias=None) -> Tensor:
69
+ if not XFORMERS_AVAILABLE:
70
+ if attn_bias is not None:
71
+ raise AssertionError("xFormers is required for using nested tensors")
72
+ return super().forward(x)
73
+
74
+ B, N, C = x.shape
75
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
76
+
77
+ q, k, v = unbind(qkv, 2)
78
+
79
+ x = memory_efficient_attention(q, k, v, attn_bias=attn_bias)
80
+ x = x.reshape([B, N, C])
81
+
82
+ x = self.proj(x)
83
+ x = self.proj_drop(x)
84
+ return x
85
+
86
+
87
+ class CrossAttention(nn.Module):
88
+ def __init__(
89
+ self,
90
+ dim: int,
91
+ dim_q: int,
92
+ dim_k: int,
93
+ dim_v: int,
94
+ num_heads: int = 8,
95
+ qkv_bias: bool = False,
96
+ proj_bias: bool = True,
97
+ attn_drop: float = 0.0,
98
+ proj_drop: float = 0.0,
99
+ ) -> None:
100
+ super().__init__()
101
+ self.dim = dim
102
+ self.num_heads = num_heads
103
+ head_dim = dim // num_heads
104
+ self.scale = head_dim**-0.5
105
+
106
+ self.to_q = nn.Linear(dim_q, dim, bias=qkv_bias)
107
+ self.to_k = nn.Linear(dim_k, dim, bias=qkv_bias)
108
+ self.to_v = nn.Linear(dim_v, dim, bias=qkv_bias)
109
+ self.attn_drop = nn.Dropout(attn_drop)
110
+ self.proj = nn.Linear(dim, dim, bias=proj_bias)
111
+ self.proj_drop = nn.Dropout(proj_drop)
112
+
113
+ def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
114
+ # q: [B, N, Cq]
115
+ # k: [B, M, Ck]
116
+ # v: [B, M, Cv]
117
+ # return: [B, N, C]
118
+
119
+ B, N, _ = q.shape
120
+ M = k.shape[1]
121
+
122
+ q = self.scale * self.to_q(q).reshape(B, N, self.num_heads, self.dim // self.num_heads).permute(0, 2, 1, 3) # [B, nh, N, C/nh]
123
+ k = self.to_k(k).reshape(B, M, self.num_heads, self.dim // self.num_heads).permute(0, 2, 1, 3) # [B, nh, M, C/nh]
124
+ v = self.to_v(v).reshape(B, M, self.num_heads, self.dim // self.num_heads).permute(0, 2, 1, 3) # [B, nh, M, C/nh]
125
+
126
+ attn = q @ k.transpose(-2, -1) # [B, nh, N, M]
127
+
128
+ attn = attn.softmax(dim=-1) # [B, nh, N, M]
129
+ attn = self.attn_drop(attn)
130
+
131
+ x = (attn @ v).transpose(1, 2).reshape(B, N, -1) # [B, nh, N, M] @ [B, nh, M, C/nh] --> [B, nh, N, C/nh] --> [B, N, nh, C/nh] --> [B, N, C]
132
+ x = self.proj(x)
133
+ x = self.proj_drop(x)
134
+ return x
135
+
136
+
137
+ class MemEffCrossAttention(CrossAttention):
138
+ def forward(self, q: Tensor, k: Tensor, v: Tensor, attn_bias=None) -> Tensor:
139
+ if not XFORMERS_AVAILABLE:
140
+ if attn_bias is not None:
141
+ raise AssertionError("xFormers is required for using nested tensors")
142
+ return super().forward(x)
143
+
144
+ B, N, _ = q.shape
145
+ M = k.shape[1]
146
+
147
+ q = self.scale * self.to_q(q).reshape(B, N, self.num_heads, self.dim // self.num_heads) # [B, N, nh, C/nh]
148
+ k = self.to_k(k).reshape(B, M, self.num_heads, self.dim // self.num_heads) # [B, M, nh, C/nh]
149
+ v = self.to_v(v).reshape(B, M, self.num_heads, self.dim // self.num_heads) # [B, M, nh, C/nh]
150
+
151
+ x = memory_efficient_attention(q, k, v, attn_bias=attn_bias)
152
+ x = x.reshape(B, N, -1)
153
+
154
+ x = self.proj(x)
155
+ x = self.proj_drop(x)
156
+ return x
core/gs.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+ from diff_gaussian_rasterization import (
8
+ GaussianRasterizationSettings,
9
+ GaussianRasterizer,
10
+ )
11
+
12
+ from core.options import Options
13
+
14
+ import kiui
15
+
16
+ class GaussianRenderer:
17
+ def __init__(self, opt: Options):
18
+
19
+ self.opt = opt
20
+ self.bg_color = torch.tensor([1, 1, 1], dtype=torch.float32, device="cuda")
21
+
22
+ # intrinsics
23
+ self.tan_half_fov = np.tan(0.5 * np.deg2rad(self.opt.fovy))
24
+ self.proj_matrix = torch.zeros(4, 4, dtype=torch.float32)
25
+ self.proj_matrix[0, 0] = 1 / self.tan_half_fov
26
+ self.proj_matrix[1, 1] = 1 / self.tan_half_fov
27
+ self.proj_matrix[2, 2] = (opt.zfar + opt.znear) / (opt.zfar - opt.znear)
28
+ self.proj_matrix[3, 2] = - (opt.zfar * opt.znear) / (opt.zfar - opt.znear)
29
+ self.proj_matrix[2, 3] = 1
30
+
31
+ def render(self, gaussians, cam_view, cam_view_proj, cam_pos, bg_color=None, scale_modifier=1):
32
+ # gaussians: [B, N, 14]
33
+ # cam_view, cam_view_proj: [B, V, 4, 4]
34
+ # cam_pos: [B, V, 3]
35
+
36
+ device = gaussians.device
37
+ B, V = cam_view.shape[:2]
38
+
39
+ # loop of loop...
40
+ images = []
41
+ alphas = []
42
+ for b in range(B):
43
+
44
+ # pos, opacity, scale, rotation, shs
45
+ means3D = gaussians[b, :, 0:3].contiguous().float()
46
+ opacity = gaussians[b, :, 3:4].contiguous().float()
47
+ scales = gaussians[b, :, 4:7].contiguous().float()
48
+ rotations = gaussians[b, :, 7:11].contiguous().float()
49
+ rgbs = gaussians[b, :, 11:].contiguous().float() # [N, 3]
50
+
51
+ for v in range(V):
52
+
53
+ # render novel views
54
+ view_matrix = cam_view[b, v].float()
55
+ view_proj_matrix = cam_view_proj[b, v].float()
56
+ campos = cam_pos[b, v].float()
57
+
58
+ raster_settings = GaussianRasterizationSettings(
59
+ image_height=self.opt.output_size,
60
+ image_width=self.opt.output_size,
61
+ tanfovx=self.tan_half_fov,
62
+ tanfovy=self.tan_half_fov,
63
+ bg=self.bg_color if bg_color is None else bg_color,
64
+ scale_modifier=scale_modifier,
65
+ viewmatrix=view_matrix,
66
+ projmatrix=view_proj_matrix,
67
+ sh_degree=0,
68
+ campos=campos,
69
+ prefiltered=False,
70
+ debug=False,
71
+ )
72
+
73
+ rasterizer = GaussianRasterizer(raster_settings=raster_settings)
74
+
75
+ # Rasterize visible Gaussians to image, obtain their radii (on screen).
76
+ rendered_image, radii, rendered_depth, rendered_alpha = rasterizer(
77
+ means3D=means3D,
78
+ means2D=torch.zeros_like(means3D, dtype=torch.float32, device=device),
79
+ shs=None,
80
+ colors_precomp=rgbs,
81
+ opacities=opacity,
82
+ scales=scales,
83
+ rotations=rotations,
84
+ cov3D_precomp=None,
85
+ )
86
+
87
+ rendered_image = rendered_image.clamp(0, 1)
88
+
89
+ images.append(rendered_image)
90
+ alphas.append(rendered_alpha)
91
+
92
+ images = torch.stack(images, dim=0).view(B, V, 3, self.opt.output_size, self.opt.output_size)
93
+ alphas = torch.stack(alphas, dim=0).view(B, V, 1, self.opt.output_size, self.opt.output_size)
94
+
95
+ return {
96
+ "image": images, # [B, V, 3, H, W]
97
+ "alpha": alphas, # [B, V, 1, H, W]
98
+ }
99
+
100
+
101
+ def save_ply(self, gaussians, path, compatible=True):
102
+ # gaussians: [B, N, 14]
103
+ # compatible: save pre-activated gaussians as in the original paper
104
+
105
+ assert gaussians.shape[0] == 1, 'only support batch size 1'
106
+
107
+ from plyfile import PlyData, PlyElement
108
+
109
+ means3D = gaussians[0, :, 0:3].contiguous().float()
110
+ opacity = gaussians[0, :, 3:4].contiguous().float()
111
+ scales = gaussians[0, :, 4:7].contiguous().float()
112
+ rotations = gaussians[0, :, 7:11].contiguous().float()
113
+ shs = gaussians[0, :, 11:].unsqueeze(1).contiguous().float() # [N, 1, 3]
114
+
115
+ # prune by opacity
116
+ mask = opacity.squeeze(-1) >= 0.005
117
+ means3D = means3D[mask]
118
+ opacity = opacity[mask]
119
+ scales = scales[mask]
120
+ rotations = rotations[mask]
121
+ shs = shs[mask]
122
+
123
+ # invert activation to make it compatible with the original ply format
124
+ if compatible:
125
+ opacity = kiui.op.inverse_sigmoid(opacity)
126
+ scales = torch.log(scales + 1e-8)
127
+ shs = (shs - 0.5) / 0.28209479177387814
128
+
129
+ xyzs = means3D.detach().cpu().numpy()
130
+ f_dc = shs.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()
131
+ opacities = opacity.detach().cpu().numpy()
132
+ scales = scales.detach().cpu().numpy()
133
+ rotations = rotations.detach().cpu().numpy()
134
+
135
+ l = ['x', 'y', 'z']
136
+ # All channels except the 3 DC
137
+ for i in range(f_dc.shape[1]):
138
+ l.append('f_dc_{}'.format(i))
139
+ l.append('opacity')
140
+ for i in range(scales.shape[1]):
141
+ l.append('scale_{}'.format(i))
142
+ for i in range(rotations.shape[1]):
143
+ l.append('rot_{}'.format(i))
144
+
145
+ dtype_full = [(attribute, 'f4') for attribute in l]
146
+
147
+ elements = np.empty(xyzs.shape[0], dtype=dtype_full)
148
+ attributes = np.concatenate((xyzs, f_dc, opacities, scales, rotations), axis=1)
149
+ elements[:] = list(map(tuple, attributes))
150
+ el = PlyElement.describe(elements, 'vertex')
151
+
152
+ PlyData([el]).write(path)
153
+
154
+ def load_ply(self, path, compatible=True):
155
+
156
+ from plyfile import PlyData, PlyElement
157
+
158
+ plydata = PlyData.read(path)
159
+
160
+ xyz = np.stack((np.asarray(plydata.elements[0]["x"]),
161
+ np.asarray(plydata.elements[0]["y"]),
162
+ np.asarray(plydata.elements[0]["z"])), axis=1)
163
+ print("Number of points at loading : ", xyz.shape[0])
164
+
165
+ opacities = np.asarray(plydata.elements[0]["opacity"])[..., np.newaxis]
166
+
167
+ shs = np.zeros((xyz.shape[0], 3))
168
+ shs[:, 0] = np.asarray(plydata.elements[0]["f_dc_0"])
169
+ shs[:, 1] = np.asarray(plydata.elements[0]["f_dc_1"])
170
+ shs[:, 2] = np.asarray(plydata.elements[0]["f_dc_2"])
171
+
172
+ scale_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("scale_")]
173
+ scales = np.zeros((xyz.shape[0], len(scale_names)))
174
+ for idx, attr_name in enumerate(scale_names):
175
+ scales[:, idx] = np.asarray(plydata.elements[0][attr_name])
176
+
177
+ rot_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("rot_")]
178
+ rots = np.zeros((xyz.shape[0], len(rot_names)))
179
+ for idx, attr_name in enumerate(rot_names):
180
+ rots[:, idx] = np.asarray(plydata.elements[0][attr_name])
181
+
182
+ gaussians = np.concatenate([xyz, opacities, scales, rots, shs], axis=1)
183
+ gaussians = torch.from_numpy(gaussians).float() # cpu
184
+
185
+ if compatible:
186
+ gaussians[..., 3:4] = torch.sigmoid(gaussians[..., 3:4])
187
+ gaussians[..., 4:7] = torch.exp(gaussians[..., 4:7])
188
+ gaussians[..., 11:] = 0.28209479177387814 * gaussians[..., 11:] + 0.5
189
+
190
+ return gaussians
core/models.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import numpy as np
5
+
6
+ import kiui
7
+ from kiui.lpips import LPIPS
8
+
9
+ from core.unet import UNet
10
+ from core.options import Options
11
+ from core.gs import GaussianRenderer
12
+
13
+
14
+ class LGM(nn.Module):
15
+ def __init__(
16
+ self,
17
+ opt: Options,
18
+ ):
19
+ super().__init__()
20
+
21
+ self.opt = opt
22
+
23
+ # unet
24
+ self.unet = UNet(
25
+ 9, 14,
26
+ down_channels=self.opt.down_channels,
27
+ down_attention=self.opt.down_attention,
28
+ mid_attention=self.opt.mid_attention,
29
+ up_channels=self.opt.up_channels,
30
+ up_attention=self.opt.up_attention,
31
+ )
32
+
33
+ # last conv
34
+ self.conv = nn.Conv2d(14, 14, kernel_size=1) # NOTE: maybe remove it if train again
35
+
36
+ # Gaussian Renderer
37
+ self.gs = GaussianRenderer(opt)
38
+
39
+ # activations...
40
+ self.pos_act = lambda x: x.clamp(-1, 1)
41
+ self.scale_act = lambda x: 0.1 * F.softplus(x)
42
+ self.opacity_act = lambda x: torch.sigmoid(x)
43
+ self.rot_act = F.normalize
44
+ self.rgb_act = lambda x: 0.5 * torch.tanh(x) + 0.5 # NOTE: may use sigmoid if train again
45
+
46
+ # LPIPS loss
47
+ if self.opt.lambda_lpips > 0:
48
+ self.lpips_loss = LPIPS(net='vgg')
49
+ self.lpips_loss.requires_grad_(False)
50
+
51
+
52
+ def state_dict(self, **kwargs):
53
+ # remove lpips_loss
54
+ state_dict = super().state_dict(**kwargs)
55
+ for k in list(state_dict.keys()):
56
+ if 'lpips_loss' in k:
57
+ del state_dict[k]
58
+ return state_dict
59
+
60
+
61
+ def prepare_default_rays(self, device, elevation=0):
62
+
63
+ from kiui.cam import orbit_camera
64
+ from core.utils import get_rays
65
+
66
+ cam_poses = np.stack([
67
+ orbit_camera(elevation, 0, radius=self.opt.cam_radius),
68
+ orbit_camera(elevation, 90, radius=self.opt.cam_radius),
69
+ orbit_camera(elevation, 180, radius=self.opt.cam_radius),
70
+ orbit_camera(elevation, 270, radius=self.opt.cam_radius),
71
+ ], axis=0) # [4, 4, 4]
72
+ cam_poses = torch.from_numpy(cam_poses)
73
+
74
+ rays_embeddings = []
75
+ for i in range(cam_poses.shape[0]):
76
+ rays_o, rays_d = get_rays(cam_poses[i], self.opt.input_size, self.opt.input_size, self.opt.fovy) # [h, w, 3]
77
+ rays_plucker = torch.cat([torch.cross(rays_o, rays_d, dim=-1), rays_d], dim=-1) # [h, w, 6]
78
+ rays_embeddings.append(rays_plucker)
79
+
80
+ ## visualize rays for plotting figure
81
+ # kiui.vis.plot_image(rays_d * 0.5 + 0.5, save=True)
82
+
83
+ rays_embeddings = torch.stack(rays_embeddings, dim=0).permute(0, 3, 1, 2).contiguous().to(device) # [V, 6, h, w]
84
+
85
+ return rays_embeddings
86
+
87
+
88
+ def forward_gaussians(self, images):
89
+ # images: [B, 4, 9, H, W]
90
+ # return: Gaussians: [B, dim_t]
91
+
92
+ B, V, C, H, W = images.shape
93
+ images = images.view(B*V, C, H, W)
94
+
95
+ x = self.unet(images) # [B*4, 14, h, w]
96
+ x = self.conv(x) # [B*4, 14, h, w]
97
+
98
+ x = x.reshape(B, 4, 14, self.opt.splat_size, self.opt.splat_size)
99
+
100
+ ## visualize multi-view gaussian features for plotting figure
101
+ # tmp_alpha = self.opacity_act(x[0, :, 3:4])
102
+ # tmp_img_rgb = self.rgb_act(x[0, :, 11:]) * tmp_alpha + (1 - tmp_alpha)
103
+ # tmp_img_pos = self.pos_act(x[0, :, 0:3]) * 0.5 + 0.5
104
+ # kiui.vis.plot_image(tmp_img_rgb, save=True)
105
+ # kiui.vis.plot_image(tmp_img_pos, save=True)
106
+
107
+ x = x.permute(0, 1, 3, 4, 2).reshape(B, -1, 14)
108
+
109
+ pos = self.pos_act(x[..., 0:3]) # [B, N, 3]
110
+ opacity = self.opacity_act(x[..., 3:4])
111
+ scale = self.scale_act(x[..., 4:7])
112
+ rotation = self.rot_act(x[..., 7:11])
113
+ rgbs = self.rgb_act(x[..., 11:])
114
+
115
+ gaussians = torch.cat([pos, opacity, scale, rotation, rgbs], dim=-1) # [B, N, 14]
116
+
117
+ return gaussians
118
+
119
+
120
+ def forward(self, data, step_ratio=1):
121
+ # data: output of the dataloader
122
+ # return: loss
123
+
124
+ results = {}
125
+ loss = 0
126
+
127
+ images = data['input'] # [B, 4, 9, h, W], input features
128
+
129
+ # use the first view to predict gaussians
130
+ gaussians = self.forward_gaussians(images) # [B, N, 14]
131
+
132
+ results['gaussians'] = gaussians
133
+
134
+ # random bg for training
135
+ if self.training:
136
+ bg_color = torch.rand(3, dtype=torch.float32, device=gaussians.device)
137
+ else:
138
+ bg_color = torch.ones(3, dtype=torch.float32, device=gaussians.device)
139
+
140
+ # use the other views for rendering and supervision
141
+ results = self.gs.render(gaussians, data['cam_view'], data['cam_view_proj'], data['cam_pos'], bg_color=bg_color)
142
+ pred_images = results['image'] # [B, V, C, output_size, output_size]
143
+ pred_alphas = results['alpha'] # [B, V, 1, output_size, output_size]
144
+
145
+ results['images_pred'] = pred_images
146
+ results['alphas_pred'] = pred_alphas
147
+
148
+ gt_images = data['images_output'] # [B, V, 3, output_size, output_size], ground-truth novel views
149
+ gt_masks = data['masks_output'] # [B, V, 1, output_size, output_size], ground-truth masks
150
+
151
+ gt_images = gt_images * gt_masks + bg_color.view(1, 1, 3, 1, 1) * (1 - gt_masks)
152
+
153
+ loss_mse = F.mse_loss(pred_images, gt_images) + F.mse_loss(pred_alphas, gt_masks)
154
+ loss = loss + loss_mse
155
+
156
+ if self.opt.lambda_lpips > 0:
157
+ loss_lpips = self.lpips_loss(
158
+ # gt_images.view(-1, 3, self.opt.output_size, self.opt.output_size) * 2 - 1,
159
+ # pred_images.view(-1, 3, self.opt.output_size, self.opt.output_size) * 2 - 1,
160
+ # downsampled to at most 256 to reduce memory cost
161
+ F.interpolate(gt_images.view(-1, 3, self.opt.output_size, self.opt.output_size) * 2 - 1, (256, 256), mode='bilinear', align_corners=False),
162
+ F.interpolate(pred_images.view(-1, 3, self.opt.output_size, self.opt.output_size) * 2 - 1, (256, 256), mode='bilinear', align_corners=False),
163
+ ).mean()
164
+ results['loss_lpips'] = loss_lpips
165
+ loss = loss + self.opt.lambda_lpips * loss_lpips
166
+
167
+ results['loss'] = loss
168
+
169
+ # metric
170
+ with torch.no_grad():
171
+ psnr = -10 * torch.log10(torch.mean((pred_images.detach() - gt_images) ** 2))
172
+ results['psnr'] = psnr
173
+
174
+ return results
core/options.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tyro
2
+ from dataclasses import dataclass
3
+ from typing import Tuple, Literal, Dict, Optional
4
+
5
+
6
+ @dataclass
7
+ class Options:
8
+ ### model
9
+ # Unet image input size
10
+ input_size: int = 256
11
+ # Unet definition
12
+ down_channels: Tuple[int] = (64, 128, 256, 512, 1024, 1024)
13
+ down_attention: Tuple[bool] = (False, False, False, True, True, True)
14
+ mid_attention: bool = True
15
+ up_channels: Tuple[int] = (1024, 1024, 512, 256)
16
+ up_attention: Tuple[bool] = (True, True, True, False)
17
+ # Unet output size, dependent on the input_size and U-Net structure!
18
+ splat_size: int = 64
19
+ # gaussian render size
20
+ output_size: int = 256
21
+
22
+ ### dataset
23
+ # data mode (only support s3 now)
24
+ data_mode: Literal['s3'] = 's3'
25
+ # fovy of the dataset
26
+ fovy: float = 49.1
27
+ # camera near plane
28
+ znear: float = 0.5
29
+ # camera far plane
30
+ zfar: float = 2.5
31
+ # number of all views (input + output)
32
+ num_views: int = 12
33
+ # number of views
34
+ num_input_views: int = 4
35
+ # camera radius
36
+ cam_radius: float = 1.5 # to better use [-1, 1]^3 space
37
+ # num workers
38
+ num_workers: int = 8
39
+
40
+ ### training
41
+ # workspace
42
+ workspace: str = './workspace'
43
+ # resume
44
+ resume: Optional[str] = None
45
+ # batch size (per-GPU)
46
+ batch_size: int = 8
47
+ # gradient accumulation
48
+ gradient_accumulation_steps: int = 1
49
+ # training epochs
50
+ num_epochs: int = 30
51
+ # lpips loss weight
52
+ lambda_lpips: float = 1.0
53
+ # gradient clip
54
+ gradient_clip: float = 1.0
55
+ # mixed precision
56
+ mixed_precision: str = 'bf16'
57
+ # learning rate
58
+ lr: float = 4e-4
59
+ # augmentation prob for grid distortion
60
+ prob_grid_distortion: float = 0.5
61
+ # augmentation prob for camera jitter
62
+ prob_cam_jitter: float = 0.5
63
+
64
+ ### testing
65
+ # test image path
66
+ test_path: Optional[str] = None
67
+
68
+ ### misc
69
+ # nvdiffrast backend setting
70
+ force_cuda_rast: bool = False
71
+ # render fancy video with gaussian scaling effect
72
+ fancy_video: bool = False
73
+
74
+
75
+ # all the default settings
76
+ config_defaults: Dict[str, Options] = {}
77
+ config_doc: Dict[str, str] = {}
78
+
79
+ config_doc['lrm'] = 'the default settings for LGM'
80
+ config_defaults['lrm'] = Options()
81
+
82
+ config_doc['small'] = 'small model with lower resolution Gaussians'
83
+ config_defaults['small'] = Options(
84
+ input_size=256,
85
+ splat_size=64,
86
+ output_size=256,
87
+ batch_size=8,
88
+ gradient_accumulation_steps=1,
89
+ mixed_precision='bf16',
90
+ )
91
+
92
+ config_doc['big'] = 'big model with higher resolution Gaussians'
93
+ config_defaults['big'] = Options(
94
+ input_size=256,
95
+ up_channels=(1024, 1024, 512, 256, 128), # one more decoder
96
+ up_attention=(True, True, True, False, False),
97
+ splat_size=128,
98
+ output_size=512, # render & supervise Gaussians at a higher resolution.
99
+ batch_size=8,
100
+ num_views=8,
101
+ gradient_accumulation_steps=1,
102
+ mixed_precision='bf16',
103
+ )
104
+
105
+ config_doc['tiny'] = 'tiny model for ablation'
106
+ config_defaults['tiny'] = Options(
107
+ input_size=256,
108
+ down_channels=(32, 64, 128, 256, 512),
109
+ down_attention=(False, False, False, False, True),
110
+ up_channels=(512, 256, 128),
111
+ up_attention=(True, False, False, False),
112
+ splat_size=64,
113
+ output_size=256,
114
+ batch_size=16,
115
+ num_views=8,
116
+ gradient_accumulation_steps=1,
117
+ mixed_precision='bf16',
118
+ )
119
+
120
+ AllConfigs = tyro.extras.subcommand_type_from_defaults(config_defaults, config_doc)
core/provider_objaverse.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import random
4
+ import numpy as np
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ import torchvision.transforms.functional as TF
10
+ from torch.utils.data import Dataset
11
+
12
+ import kiui
13
+ from core.options import Options
14
+ from core.utils import get_rays, grid_distortion, orbit_camera_jitter
15
+
16
+ IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406)
17
+ IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225)
18
+
19
+
20
+ class ObjaverseDataset(Dataset):
21
+
22
+ def _warn(self):
23
+ raise NotImplementedError('this dataset is just an example and cannot be used directly, you should modify it to your own setting! (search keyword TODO)')
24
+
25
+ def __init__(self, opt: Options, training=True):
26
+
27
+ self.opt = opt
28
+ self.training = training
29
+
30
+ # TODO: remove this barrier
31
+ self._warn()
32
+
33
+ # TODO: load the list of objects for training
34
+ self.items = []
35
+ with open('TODO: file containing the list', 'r') as f:
36
+ for line in f.readlines():
37
+ self.items.append(line.strip())
38
+
39
+ # naive split
40
+ if self.training:
41
+ self.items = self.items[:-self.opt.batch_size]
42
+ else:
43
+ self.items = self.items[-self.opt.batch_size:]
44
+
45
+ # default camera intrinsics
46
+ self.tan_half_fov = np.tan(0.5 * np.deg2rad(self.opt.fovy))
47
+ self.proj_matrix = torch.zeros(4, 4, dtype=torch.float32)
48
+ self.proj_matrix[0, 0] = 1 / self.tan_half_fov
49
+ self.proj_matrix[1, 1] = 1 / self.tan_half_fov
50
+ self.proj_matrix[2, 2] = (self.opt.zfar + self.opt.znear) / (self.opt.zfar - self.opt.znear)
51
+ self.proj_matrix[3, 2] = - (self.opt.zfar * self.opt.znear) / (self.opt.zfar - self.opt.znear)
52
+ self.proj_matrix[2, 3] = 1
53
+
54
+
55
+ def __len__(self):
56
+ return len(self.items)
57
+
58
+ def __getitem__(self, idx):
59
+
60
+ uid = self.items[idx]
61
+ results = {}
62
+
63
+ # load num_views images
64
+ images = []
65
+ masks = []
66
+ cam_poses = []
67
+
68
+ vid_cnt = 0
69
+
70
+ # TODO: choose views, based on your rendering settings
71
+ if self.training:
72
+ # input views are in (36, 72), other views are randomly selected
73
+ vids = np.random.permutation(np.arange(36, 73))[:self.opt.num_input_views].tolist() + np.random.permutation(100).tolist()
74
+ else:
75
+ # fixed views
76
+ vids = np.arange(36, 73, 4).tolist() + np.arange(100).tolist()
77
+
78
+ for vid in vids:
79
+
80
+ image_path = os.path.join(uid, 'rgb', f'{vid:03d}.png')
81
+ camera_path = os.path.join(uid, 'pose', f'{vid:03d}.txt')
82
+
83
+ try:
84
+ # TODO: load data (modify self.client here)
85
+ image = np.frombuffer(self.client.get(image_path), np.uint8)
86
+ image = torch.from_numpy(cv2.imdecode(image, cv2.IMREAD_UNCHANGED).astype(np.float32) / 255) # [512, 512, 4] in [0, 1]
87
+ c2w = [float(t) for t in self.client.get(camera_path).decode().strip().split(' ')]
88
+ c2w = torch.tensor(c2w, dtype=torch.float32).reshape(4, 4)
89
+ except Exception as e:
90
+ # print(f'[WARN] dataset {uid} {vid}: {e}')
91
+ continue
92
+
93
+ # TODO: you may have a different camera system
94
+ # blender world + opencv cam --> opengl world & cam
95
+ c2w[1] *= -1
96
+ c2w[[1, 2]] = c2w[[2, 1]]
97
+ c2w[:3, 1:3] *= -1 # invert up and forward direction
98
+
99
+ # scale up radius to fully use the [-1, 1]^3 space!
100
+ c2w[:3, 3] *= self.opt.cam_radius / 1.5 # 1.5 is the default scale
101
+
102
+ image = image.permute(2, 0, 1) # [4, 512, 512]
103
+ mask = image[3:4] # [1, 512, 512]
104
+ image = image[:3] * mask + (1 - mask) # [3, 512, 512], to white bg
105
+ image = image[[2,1,0]].contiguous() # bgr to rgb
106
+
107
+ images.append(image)
108
+ masks.append(mask.squeeze(0))
109
+ cam_poses.append(c2w)
110
+
111
+ vid_cnt += 1
112
+ if vid_cnt == self.opt.num_views:
113
+ break
114
+
115
+ if vid_cnt < self.opt.num_views:
116
+ print(f'[WARN] dataset {uid}: not enough valid views, only {vid_cnt} views found!')
117
+ n = self.opt.num_views - vid_cnt
118
+ images = images + [images[-1]] * n
119
+ masks = masks + [masks[-1]] * n
120
+ cam_poses = cam_poses + [cam_poses[-1]] * n
121
+
122
+ images = torch.stack(images, dim=0) # [V, C, H, W]
123
+ masks = torch.stack(masks, dim=0) # [V, H, W]
124
+ cam_poses = torch.stack(cam_poses, dim=0) # [V, 4, 4]
125
+
126
+ # normalized camera feats as in paper (transform the first pose to a fixed position)
127
+ transform = torch.tensor([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, self.opt.cam_radius], [0, 0, 0, 1]], dtype=torch.float32) @ torch.inverse(cam_poses[0])
128
+ cam_poses = transform.unsqueeze(0) @ cam_poses # [V, 4, 4]
129
+
130
+ images_input = F.interpolate(images[:self.opt.num_input_views].clone(), size=(self.opt.input_size, self.opt.input_size), mode='bilinear', align_corners=False) # [V, C, H, W]
131
+ cam_poses_input = cam_poses[:self.opt.num_input_views].clone()
132
+
133
+ # data augmentation
134
+ if self.training:
135
+ # apply random grid distortion to simulate 3D inconsistency
136
+ if random.random() < self.opt.prob_grid_distortion:
137
+ images_input[1:] = grid_distortion(images_input[1:])
138
+ # apply camera jittering (only to input!)
139
+ if random.random() < self.opt.prob_cam_jitter:
140
+ cam_poses_input[1:] = orbit_camera_jitter(cam_poses_input[1:])
141
+
142
+ images_input = TF.normalize(images_input, IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD)
143
+
144
+ # resize render ground-truth images, range still in [0, 1]
145
+ results['images_output'] = F.interpolate(images, size=(self.opt.output_size, self.opt.output_size), mode='bilinear', align_corners=False) # [V, C, output_size, output_size]
146
+ results['masks_output'] = F.interpolate(masks.unsqueeze(1), size=(self.opt.output_size, self.opt.output_size), mode='bilinear', align_corners=False) # [V, 1, output_size, output_size]
147
+
148
+ # build rays for input views
149
+ rays_embeddings = []
150
+ for i in range(self.opt.num_input_views):
151
+ rays_o, rays_d = get_rays(cam_poses_input[i], self.opt.input_size, self.opt.input_size, self.opt.fovy) # [h, w, 3]
152
+ rays_plucker = torch.cat([torch.cross(rays_o, rays_d, dim=-1), rays_d], dim=-1) # [h, w, 6]
153
+ rays_embeddings.append(rays_plucker)
154
+
155
+
156
+ rays_embeddings = torch.stack(rays_embeddings, dim=0).permute(0, 3, 1, 2).contiguous() # [V, 6, h, w]
157
+ final_input = torch.cat([images_input, rays_embeddings], dim=1) # [V=4, 9, H, W]
158
+ results['input'] = final_input
159
+
160
+ # opengl to colmap camera for gaussian renderer
161
+ cam_poses[:, :3, 1:3] *= -1 # invert up & forward direction
162
+
163
+ # cameras needed by gaussian rasterizer
164
+ cam_view = torch.inverse(cam_poses).transpose(1, 2) # [V, 4, 4]
165
+ cam_view_proj = cam_view @ self.proj_matrix # [V, 4, 4]
166
+ cam_pos = - cam_poses[:, :3, 3] # [V, 3]
167
+
168
+ results['cam_view'] = cam_view
169
+ results['cam_view_proj'] = cam_view_proj
170
+ results['cam_pos'] = cam_pos
171
+
172
+ return results
core/unet.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ import numpy as np
6
+ from typing import Tuple, Optional, Literal
7
+ from functools import partial
8
+
9
+ from core.attention import MemEffAttention, MemEffCrossAttention
10
+
11
+ class MVAttention(nn.Module):
12
+ def __init__(
13
+ self,
14
+ dim: int,
15
+ num_heads: int = 8,
16
+ qkv_bias: bool = False,
17
+ proj_bias: bool = True,
18
+ attn_drop: float = 0.0,
19
+ proj_drop: float = 0.0,
20
+ groups: int = 32,
21
+ eps: float = 1e-5,
22
+ residual: bool = True,
23
+ skip_scale: float = 1,
24
+ num_frames: int = 4, # WARN: hardcoded!
25
+ ):
26
+ super().__init__()
27
+
28
+ self.residual = residual
29
+ self.skip_scale = skip_scale
30
+ self.num_frames = num_frames
31
+
32
+ self.norm = nn.GroupNorm(num_groups=groups, num_channels=dim, eps=eps, affine=True)
33
+ self.attn = MemEffAttention(dim, num_heads, qkv_bias, proj_bias, attn_drop, proj_drop)
34
+
35
+ def forward(self, x):
36
+ # x: [B*V, C, H, W]
37
+ BV, C, H, W = x.shape
38
+ B = BV // self.num_frames # assert BV % self.num_frames == 0
39
+
40
+ res = x
41
+ x = self.norm(x)
42
+
43
+ x = x.reshape(B, self.num_frames, C, H, W).permute(0, 1, 3, 4, 2).reshape(B, -1, C)
44
+ x = self.attn(x)
45
+ x = x.reshape(B, self.num_frames, H, W, C).permute(0, 1, 4, 2, 3).reshape(BV, C, H, W)
46
+
47
+ if self.residual:
48
+ x = (x + res) * self.skip_scale
49
+ return x
50
+
51
+ class ResnetBlock(nn.Module):
52
+ def __init__(
53
+ self,
54
+ in_channels: int,
55
+ out_channels: int,
56
+ resample: Literal['default', 'up', 'down'] = 'default',
57
+ groups: int = 32,
58
+ eps: float = 1e-5,
59
+ skip_scale: float = 1, # multiplied to output
60
+ ):
61
+ super().__init__()
62
+
63
+ self.in_channels = in_channels
64
+ self.out_channels = out_channels
65
+ self.skip_scale = skip_scale
66
+
67
+ self.norm1 = nn.GroupNorm(num_groups=groups, num_channels=in_channels, eps=eps, affine=True)
68
+ self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
69
+
70
+ self.norm2 = nn.GroupNorm(num_groups=groups, num_channels=out_channels, eps=eps, affine=True)
71
+ self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
72
+
73
+ self.act = F.silu
74
+
75
+ self.resample = None
76
+ if resample == 'up':
77
+ self.resample = partial(F.interpolate, scale_factor=2.0, mode="nearest")
78
+ elif resample == 'down':
79
+ self.resample = nn.AvgPool2d(kernel_size=2, stride=2)
80
+
81
+ self.shortcut = nn.Identity()
82
+ if self.in_channels != self.out_channels:
83
+ self.shortcut = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=True)
84
+
85
+
86
+ def forward(self, x):
87
+ res = x
88
+
89
+ x = self.norm1(x)
90
+ x = self.act(x)
91
+
92
+ if self.resample:
93
+ res = self.resample(res)
94
+ x = self.resample(x)
95
+
96
+ x = self.conv1(x)
97
+ x = self.norm2(x)
98
+ x = self.act(x)
99
+ x = self.conv2(x)
100
+
101
+ x = (x + self.shortcut(res)) * self.skip_scale
102
+
103
+ return x
104
+
105
+ class DownBlock(nn.Module):
106
+ def __init__(
107
+ self,
108
+ in_channels: int,
109
+ out_channels: int,
110
+ num_layers: int = 1,
111
+ downsample: bool = True,
112
+ attention: bool = True,
113
+ attention_heads: int = 16,
114
+ skip_scale: float = 1,
115
+ ):
116
+ super().__init__()
117
+
118
+ nets = []
119
+ attns = []
120
+ for i in range(num_layers):
121
+ in_channels = in_channels if i == 0 else out_channels
122
+ nets.append(ResnetBlock(in_channels, out_channels, skip_scale=skip_scale))
123
+ if attention:
124
+ attns.append(MVAttention(out_channels, attention_heads, skip_scale=skip_scale))
125
+ else:
126
+ attns.append(None)
127
+ self.nets = nn.ModuleList(nets)
128
+ self.attns = nn.ModuleList(attns)
129
+
130
+ self.downsample = None
131
+ if downsample:
132
+ self.downsample = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=2, padding=1)
133
+
134
+ def forward(self, x):
135
+ xs = []
136
+
137
+ for attn, net in zip(self.attns, self.nets):
138
+ x = net(x)
139
+ if attn:
140
+ x = attn(x)
141
+ xs.append(x)
142
+
143
+ if self.downsample:
144
+ x = self.downsample(x)
145
+ xs.append(x)
146
+
147
+ return x, xs
148
+
149
+
150
+ class MidBlock(nn.Module):
151
+ def __init__(
152
+ self,
153
+ in_channels: int,
154
+ num_layers: int = 1,
155
+ attention: bool = True,
156
+ attention_heads: int = 16,
157
+ skip_scale: float = 1,
158
+ ):
159
+ super().__init__()
160
+
161
+ nets = []
162
+ attns = []
163
+ # first layer
164
+ nets.append(ResnetBlock(in_channels, in_channels, skip_scale=skip_scale))
165
+ # more layers
166
+ for i in range(num_layers):
167
+ nets.append(ResnetBlock(in_channels, in_channels, skip_scale=skip_scale))
168
+ if attention:
169
+ attns.append(MVAttention(in_channels, attention_heads, skip_scale=skip_scale))
170
+ else:
171
+ attns.append(None)
172
+ self.nets = nn.ModuleList(nets)
173
+ self.attns = nn.ModuleList(attns)
174
+
175
+ def forward(self, x):
176
+ x = self.nets[0](x)
177
+ for attn, net in zip(self.attns, self.nets[1:]):
178
+ if attn:
179
+ x = attn(x)
180
+ x = net(x)
181
+ return x
182
+
183
+
184
+ class UpBlock(nn.Module):
185
+ def __init__(
186
+ self,
187
+ in_channels: int,
188
+ prev_out_channels: int,
189
+ out_channels: int,
190
+ num_layers: int = 1,
191
+ upsample: bool = True,
192
+ attention: bool = True,
193
+ attention_heads: int = 16,
194
+ skip_scale: float = 1,
195
+ ):
196
+ super().__init__()
197
+
198
+ nets = []
199
+ attns = []
200
+ for i in range(num_layers):
201
+ cin = in_channels if i == 0 else out_channels
202
+ cskip = prev_out_channels if (i == num_layers - 1) else out_channels
203
+
204
+ nets.append(ResnetBlock(cin + cskip, out_channels, skip_scale=skip_scale))
205
+ if attention:
206
+ attns.append(MVAttention(out_channels, attention_heads, skip_scale=skip_scale))
207
+ else:
208
+ attns.append(None)
209
+ self.nets = nn.ModuleList(nets)
210
+ self.attns = nn.ModuleList(attns)
211
+
212
+ self.upsample = None
213
+ if upsample:
214
+ self.upsample = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
215
+
216
+ def forward(self, x, xs):
217
+
218
+ for attn, net in zip(self.attns, self.nets):
219
+ res_x = xs[-1]
220
+ xs = xs[:-1]
221
+ x = torch.cat([x, res_x], dim=1)
222
+ x = net(x)
223
+ if attn:
224
+ x = attn(x)
225
+
226
+ if self.upsample:
227
+ x = F.interpolate(x, scale_factor=2.0, mode='nearest')
228
+ x = self.upsample(x)
229
+
230
+ return x
231
+
232
+
233
+ # it could be asymmetric!
234
+ class UNet(nn.Module):
235
+ def __init__(
236
+ self,
237
+ in_channels: int = 3,
238
+ out_channels: int = 3,
239
+ down_channels: Tuple[int] = (64, 128, 256, 512, 1024),
240
+ down_attention: Tuple[bool] = (False, False, False, True, True),
241
+ mid_attention: bool = True,
242
+ up_channels: Tuple[int] = (1024, 512, 256),
243
+ up_attention: Tuple[bool] = (True, True, False),
244
+ layers_per_block: int = 2,
245
+ skip_scale: float = np.sqrt(0.5),
246
+ ):
247
+ super().__init__()
248
+
249
+ # first
250
+ self.conv_in = nn.Conv2d(in_channels, down_channels[0], kernel_size=3, stride=1, padding=1)
251
+
252
+ # down
253
+ down_blocks = []
254
+ cout = down_channels[0]
255
+ for i in range(len(down_channels)):
256
+ cin = cout
257
+ cout = down_channels[i]
258
+
259
+ down_blocks.append(DownBlock(
260
+ cin, cout,
261
+ num_layers=layers_per_block,
262
+ downsample=(i != len(down_channels) - 1), # not final layer
263
+ attention=down_attention[i],
264
+ skip_scale=skip_scale,
265
+ ))
266
+ self.down_blocks = nn.ModuleList(down_blocks)
267
+
268
+ # mid
269
+ self.mid_block = MidBlock(down_channels[-1], attention=mid_attention, skip_scale=skip_scale)
270
+
271
+ # up
272
+ up_blocks = []
273
+ cout = up_channels[0]
274
+ for i in range(len(up_channels)):
275
+ cin = cout
276
+ cout = up_channels[i]
277
+ cskip = down_channels[max(-2 - i, -len(down_channels))] # for assymetric
278
+
279
+ up_blocks.append(UpBlock(
280
+ cin, cskip, cout,
281
+ num_layers=layers_per_block + 1, # one more layer for up
282
+ upsample=(i != len(up_channels) - 1), # not final layer
283
+ attention=up_attention[i],
284
+ skip_scale=skip_scale,
285
+ ))
286
+ self.up_blocks = nn.ModuleList(up_blocks)
287
+
288
+ # last
289
+ self.norm_out = nn.GroupNorm(num_channels=up_channels[-1], num_groups=32, eps=1e-5)
290
+ self.conv_out = nn.Conv2d(up_channels[-1], out_channels, kernel_size=3, stride=1, padding=1)
291
+
292
+
293
+ def forward(self, x):
294
+ # x: [B, Cin, H, W]
295
+
296
+ # first
297
+ x = self.conv_in(x)
298
+
299
+ # down
300
+ xss = [x]
301
+ for block in self.down_blocks:
302
+ x, xs = block(x)
303
+ xss.extend(xs)
304
+
305
+ # mid
306
+ x = self.mid_block(x)
307
+
308
+ # up
309
+ for block in self.up_blocks:
310
+ xs = xss[-len(block.nets):]
311
+ xss = xss[:-len(block.nets)]
312
+ x = block(x, xs)
313
+
314
+ # last
315
+ x = self.norm_out(x)
316
+ x = F.silu(x)
317
+ x = self.conv_out(x) # [B, Cout, H', W']
318
+
319
+ return x
core/utils.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+ import roma
8
+ from kiui.op import safe_normalize
9
+
10
+ def get_rays(pose, h, w, fovy, opengl=True):
11
+
12
+ x, y = torch.meshgrid(
13
+ torch.arange(w, device=pose.device),
14
+ torch.arange(h, device=pose.device),
15
+ indexing="xy",
16
+ )
17
+ x = x.flatten()
18
+ y = y.flatten()
19
+
20
+ cx = w * 0.5
21
+ cy = h * 0.5
22
+
23
+ focal = h * 0.5 / np.tan(0.5 * np.deg2rad(fovy))
24
+
25
+ camera_dirs = F.pad(
26
+ torch.stack(
27
+ [
28
+ (x - cx + 0.5) / focal,
29
+ (y - cy + 0.5) / focal * (-1.0 if opengl else 1.0),
30
+ ],
31
+ dim=-1,
32
+ ),
33
+ (0, 1),
34
+ value=(-1.0 if opengl else 1.0),
35
+ ) # [hw, 3]
36
+
37
+ rays_d = camera_dirs @ pose[:3, :3].transpose(0, 1) # [hw, 3]
38
+ rays_o = pose[:3, 3].unsqueeze(0).expand_as(rays_d) # [hw, 3]
39
+
40
+ rays_o = rays_o.view(h, w, 3)
41
+ rays_d = safe_normalize(rays_d).view(h, w, 3)
42
+
43
+ return rays_o, rays_d
44
+
45
+ def orbit_camera_jitter(poses, strength=0.1):
46
+ # poses: [B, 4, 4], assume orbit camera in opengl format
47
+ # random orbital rotate
48
+
49
+ B = poses.shape[0]
50
+ rotvec_x = poses[:, :3, 1] * strength * np.pi * (torch.rand(B, 1, device=poses.device) * 2 - 1)
51
+ rotvec_y = poses[:, :3, 0] * strength * np.pi / 2 * (torch.rand(B, 1, device=poses.device) * 2 - 1)
52
+
53
+ rot = roma.rotvec_to_rotmat(rotvec_x) @ roma.rotvec_to_rotmat(rotvec_y)
54
+ R = rot @ poses[:, :3, :3]
55
+ T = rot @ poses[:, :3, 3:]
56
+
57
+ new_poses = poses.clone()
58
+ new_poses[:, :3, :3] = R
59
+ new_poses[:, :3, 3:] = T
60
+
61
+ return new_poses
62
+
63
+ def grid_distortion(images, strength=0.5):
64
+ # images: [B, C, H, W]
65
+ # num_steps: int, grid resolution for distortion
66
+ # strength: float in [0, 1], strength of distortion
67
+
68
+ B, C, H, W = images.shape
69
+
70
+ num_steps = np.random.randint(8, 17)
71
+ grid_steps = torch.linspace(-1, 1, num_steps)
72
+
73
+ # have to loop batch...
74
+ grids = []
75
+ for b in range(B):
76
+ # construct displacement
77
+ x_steps = torch.linspace(0, 1, num_steps) # [num_steps], inclusive
78
+ x_steps = (x_steps + strength * (torch.rand_like(x_steps) - 0.5) / (num_steps - 1)).clamp(0, 1) # perturb
79
+ x_steps = (x_steps * W).long() # [num_steps]
80
+ x_steps[0] = 0
81
+ x_steps[-1] = W
82
+ xs = []
83
+ for i in range(num_steps - 1):
84
+ xs.append(torch.linspace(grid_steps[i], grid_steps[i + 1], x_steps[i + 1] - x_steps[i]))
85
+ xs = torch.cat(xs, dim=0) # [W]
86
+
87
+ y_steps = torch.linspace(0, 1, num_steps) # [num_steps], inclusive
88
+ y_steps = (y_steps + strength * (torch.rand_like(y_steps) - 0.5) / (num_steps - 1)).clamp(0, 1) # perturb
89
+ y_steps = (y_steps * H).long() # [num_steps]
90
+ y_steps[0] = 0
91
+ y_steps[-1] = H
92
+ ys = []
93
+ for i in range(num_steps - 1):
94
+ ys.append(torch.linspace(grid_steps[i], grid_steps[i + 1], y_steps[i + 1] - y_steps[i]))
95
+ ys = torch.cat(ys, dim=0) # [H]
96
+
97
+ # construct grid
98
+ grid_x, grid_y = torch.meshgrid(xs, ys, indexing='xy') # [H, W]
99
+ grid = torch.stack([grid_x, grid_y], dim=-1) # [H, W, 2]
100
+
101
+ grids.append(grid)
102
+
103
+ grids = torch.stack(grids, dim=0).to(images.device) # [B, H, W, 2]
104
+
105
+ # grid sample
106
+ images = F.grid_sample(images, grids, align_corners=False)
107
+
108
+ return images
109
+
data_test/anya_rgba.png ADDED
data_test/bird_rgba.png ADDED
data_test/catstatue_rgba.png ADDED
mvdream/__pycache__/mv_unet.cpython-39.pyc ADDED
Binary file (23.4 kB). View file
 
mvdream/__pycache__/pipeline_mvdream.cpython-39.pyc ADDED
Binary file (15.7 kB). View file
 
mvdream/mv_unet.py ADDED
@@ -0,0 +1,1005 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numpy as np
3
+ from inspect import isfunction
4
+ from typing import Optional, Any, List
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from einops import rearrange, repeat
10
+
11
+ from diffusers.configuration_utils import ConfigMixin
12
+ from diffusers.models.modeling_utils import ModelMixin
13
+
14
+ # require xformers!
15
+ import xformers
16
+ import xformers.ops
17
+
18
+ from kiui.cam import orbit_camera
19
+
20
+ def get_camera(
21
+ num_frames, elevation=0, azimuth_start=0, azimuth_span=360, blender_coord=True, extra_view=False,
22
+ ):
23
+ angle_gap = azimuth_span / num_frames
24
+ cameras = []
25
+ for azimuth in np.arange(azimuth_start, azimuth_span + azimuth_start, angle_gap):
26
+
27
+ pose = orbit_camera(elevation, azimuth, radius=1) # [4, 4]
28
+
29
+ # opengl to blender
30
+ if blender_coord:
31
+ pose[2] *= -1
32
+ pose[[1, 2]] = pose[[2, 1]]
33
+
34
+ cameras.append(pose.flatten())
35
+
36
+ if extra_view:
37
+ cameras.append(np.zeros_like(cameras[0]))
38
+
39
+ return torch.from_numpy(np.stack(cameras, axis=0)).float() # [num_frames, 16]
40
+
41
+
42
+ def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
43
+ """
44
+ Create sinusoidal timestep embeddings.
45
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
46
+ These may be fractional.
47
+ :param dim: the dimension of the output.
48
+ :param max_period: controls the minimum frequency of the embeddings.
49
+ :return: an [N x dim] Tensor of positional embeddings.
50
+ """
51
+ if not repeat_only:
52
+ half = dim // 2
53
+ freqs = torch.exp(
54
+ -math.log(max_period)
55
+ * torch.arange(start=0, end=half, dtype=torch.float32)
56
+ / half
57
+ ).to(device=timesteps.device)
58
+ args = timesteps[:, None] * freqs[None]
59
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
60
+ if dim % 2:
61
+ embedding = torch.cat(
62
+ [embedding, torch.zeros_like(embedding[:, :1])], dim=-1
63
+ )
64
+ else:
65
+ embedding = repeat(timesteps, "b -> b d", d=dim)
66
+ # import pdb; pdb.set_trace()
67
+ return embedding
68
+
69
+
70
+ def zero_module(module):
71
+ """
72
+ Zero out the parameters of a module and return it.
73
+ """
74
+ for p in module.parameters():
75
+ p.detach().zero_()
76
+ return module
77
+
78
+
79
+ def conv_nd(dims, *args, **kwargs):
80
+ """
81
+ Create a 1D, 2D, or 3D convolution module.
82
+ """
83
+ if dims == 1:
84
+ return nn.Conv1d(*args, **kwargs)
85
+ elif dims == 2:
86
+ return nn.Conv2d(*args, **kwargs)
87
+ elif dims == 3:
88
+ return nn.Conv3d(*args, **kwargs)
89
+ raise ValueError(f"unsupported dimensions: {dims}")
90
+
91
+
92
+ def avg_pool_nd(dims, *args, **kwargs):
93
+ """
94
+ Create a 1D, 2D, or 3D average pooling module.
95
+ """
96
+ if dims == 1:
97
+ return nn.AvgPool1d(*args, **kwargs)
98
+ elif dims == 2:
99
+ return nn.AvgPool2d(*args, **kwargs)
100
+ elif dims == 3:
101
+ return nn.AvgPool3d(*args, **kwargs)
102
+ raise ValueError(f"unsupported dimensions: {dims}")
103
+
104
+
105
+ def default(val, d):
106
+ if val is not None:
107
+ return val
108
+ return d() if isfunction(d) else d
109
+
110
+
111
+ class GEGLU(nn.Module):
112
+ def __init__(self, dim_in, dim_out):
113
+ super().__init__()
114
+ self.proj = nn.Linear(dim_in, dim_out * 2)
115
+
116
+ def forward(self, x):
117
+ x, gate = self.proj(x).chunk(2, dim=-1)
118
+ return x * F.gelu(gate)
119
+
120
+
121
+ class FeedForward(nn.Module):
122
+ def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.0):
123
+ super().__init__()
124
+ inner_dim = int(dim * mult)
125
+ dim_out = default(dim_out, dim)
126
+ project_in = (
127
+ nn.Sequential(nn.Linear(dim, inner_dim), nn.GELU())
128
+ if not glu
129
+ else GEGLU(dim, inner_dim)
130
+ )
131
+
132
+ self.net = nn.Sequential(
133
+ project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out)
134
+ )
135
+
136
+ def forward(self, x):
137
+ return self.net(x)
138
+
139
+
140
+ class MemoryEfficientCrossAttention(nn.Module):
141
+ # https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
142
+ def __init__(
143
+ self,
144
+ query_dim,
145
+ context_dim=None,
146
+ heads=8,
147
+ dim_head=64,
148
+ dropout=0.0,
149
+ ip_dim=0,
150
+ ip_weight=1,
151
+ ):
152
+ super().__init__()
153
+
154
+ inner_dim = dim_head * heads
155
+ context_dim = default(context_dim, query_dim)
156
+
157
+ self.heads = heads
158
+ self.dim_head = dim_head
159
+
160
+ self.ip_dim = ip_dim
161
+ self.ip_weight = ip_weight
162
+
163
+ if self.ip_dim > 0:
164
+ self.to_k_ip = nn.Linear(context_dim, inner_dim, bias=False)
165
+ self.to_v_ip = nn.Linear(context_dim, inner_dim, bias=False)
166
+
167
+ self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
168
+ self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
169
+ self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
170
+
171
+ self.to_out = nn.Sequential(
172
+ nn.Linear(inner_dim, query_dim), nn.Dropout(dropout)
173
+ )
174
+ self.attention_op: Optional[Any] = None
175
+
176
+ def forward(self, x, context=None):
177
+ q = self.to_q(x)
178
+ context = default(context, x)
179
+
180
+ if self.ip_dim > 0:
181
+ # context: [B, 77 + 16(ip), 1024]
182
+ token_len = context.shape[1]
183
+ context_ip = context[:, -self.ip_dim :, :]
184
+ k_ip = self.to_k_ip(context_ip)
185
+ v_ip = self.to_v_ip(context_ip)
186
+ context = context[:, : (token_len - self.ip_dim), :]
187
+
188
+ k = self.to_k(context)
189
+ v = self.to_v(context)
190
+
191
+ b, _, _ = q.shape
192
+ q, k, v = map(
193
+ lambda t: t.unsqueeze(3)
194
+ .reshape(b, t.shape[1], self.heads, self.dim_head)
195
+ .permute(0, 2, 1, 3)
196
+ .reshape(b * self.heads, t.shape[1], self.dim_head)
197
+ .contiguous(),
198
+ (q, k, v),
199
+ )
200
+
201
+ # actually compute the attention, what we cannot get enough of
202
+ out = xformers.ops.memory_efficient_attention(
203
+ q, k, v, attn_bias=None, op=self.attention_op
204
+ )
205
+
206
+ if self.ip_dim > 0:
207
+ k_ip, v_ip = map(
208
+ lambda t: t.unsqueeze(3)
209
+ .reshape(b, t.shape[1], self.heads, self.dim_head)
210
+ .permute(0, 2, 1, 3)
211
+ .reshape(b * self.heads, t.shape[1], self.dim_head)
212
+ .contiguous(),
213
+ (k_ip, v_ip),
214
+ )
215
+ # actually compute the attention, what we cannot get enough of
216
+ out_ip = xformers.ops.memory_efficient_attention(
217
+ q, k_ip, v_ip, attn_bias=None, op=self.attention_op
218
+ )
219
+ out = out + self.ip_weight * out_ip
220
+
221
+ out = (
222
+ out.unsqueeze(0)
223
+ .reshape(b, self.heads, out.shape[1], self.dim_head)
224
+ .permute(0, 2, 1, 3)
225
+ .reshape(b, out.shape[1], self.heads * self.dim_head)
226
+ )
227
+ return self.to_out(out)
228
+
229
+
230
+ class BasicTransformerBlock3D(nn.Module):
231
+
232
+ def __init__(
233
+ self,
234
+ dim,
235
+ n_heads,
236
+ d_head,
237
+ context_dim,
238
+ dropout=0.0,
239
+ gated_ff=True,
240
+ ip_dim=0,
241
+ ip_weight=1,
242
+ ):
243
+ super().__init__()
244
+
245
+ self.attn1 = MemoryEfficientCrossAttention(
246
+ query_dim=dim,
247
+ context_dim=None, # self-attention
248
+ heads=n_heads,
249
+ dim_head=d_head,
250
+ dropout=dropout,
251
+ )
252
+ self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
253
+ self.attn2 = MemoryEfficientCrossAttention(
254
+ query_dim=dim,
255
+ context_dim=context_dim,
256
+ heads=n_heads,
257
+ dim_head=d_head,
258
+ dropout=dropout,
259
+ # ip only applies to cross-attention
260
+ ip_dim=ip_dim,
261
+ ip_weight=ip_weight,
262
+ )
263
+ self.norm1 = nn.LayerNorm(dim)
264
+ self.norm2 = nn.LayerNorm(dim)
265
+ self.norm3 = nn.LayerNorm(dim)
266
+
267
+ def forward(self, x, context=None, num_frames=1):
268
+ x = rearrange(x, "(b f) l c -> b (f l) c", f=num_frames).contiguous()
269
+ x = self.attn1(self.norm1(x), context=None) + x
270
+ x = rearrange(x, "b (f l) c -> (b f) l c", f=num_frames).contiguous()
271
+ x = self.attn2(self.norm2(x), context=context) + x
272
+ x = self.ff(self.norm3(x)) + x
273
+ return x
274
+
275
+
276
+ class SpatialTransformer3D(nn.Module):
277
+
278
+ def __init__(
279
+ self,
280
+ in_channels,
281
+ n_heads,
282
+ d_head,
283
+ context_dim, # cross attention input dim
284
+ depth=1,
285
+ dropout=0.0,
286
+ ip_dim=0,
287
+ ip_weight=1,
288
+ ):
289
+ super().__init__()
290
+
291
+ if not isinstance(context_dim, list):
292
+ context_dim = [context_dim]
293
+
294
+ self.in_channels = in_channels
295
+
296
+ inner_dim = n_heads * d_head
297
+ self.norm = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
298
+ self.proj_in = nn.Linear(in_channels, inner_dim)
299
+
300
+ self.transformer_blocks = nn.ModuleList(
301
+ [
302
+ BasicTransformerBlock3D(
303
+ inner_dim,
304
+ n_heads,
305
+ d_head,
306
+ context_dim=context_dim[d],
307
+ dropout=dropout,
308
+ ip_dim=ip_dim,
309
+ ip_weight=ip_weight,
310
+ )
311
+ for d in range(depth)
312
+ ]
313
+ )
314
+
315
+ self.proj_out = zero_module(nn.Linear(in_channels, inner_dim))
316
+
317
+
318
+ def forward(self, x, context=None, num_frames=1):
319
+ # note: if no context is given, cross-attention defaults to self-attention
320
+ if not isinstance(context, list):
321
+ context = [context]
322
+ b, c, h, w = x.shape
323
+ x_in = x
324
+ x = self.norm(x)
325
+ x = rearrange(x, "b c h w -> b (h w) c").contiguous()
326
+ x = self.proj_in(x)
327
+ for i, block in enumerate(self.transformer_blocks):
328
+ x = block(x, context=context[i], num_frames=num_frames)
329
+ x = self.proj_out(x)
330
+ x = rearrange(x, "b (h w) c -> b c h w", h=h, w=w).contiguous()
331
+
332
+ return x + x_in
333
+
334
+
335
+ class PerceiverAttention(nn.Module):
336
+ def __init__(self, *, dim, dim_head=64, heads=8):
337
+ super().__init__()
338
+ self.scale = dim_head ** -0.5
339
+ self.dim_head = dim_head
340
+ self.heads = heads
341
+ inner_dim = dim_head * heads
342
+
343
+ self.norm1 = nn.LayerNorm(dim)
344
+ self.norm2 = nn.LayerNorm(dim)
345
+
346
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
347
+ self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
348
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
349
+
350
+ def forward(self, x, latents):
351
+ """
352
+ Args:
353
+ x (torch.Tensor): image features
354
+ shape (b, n1, D)
355
+ latent (torch.Tensor): latent features
356
+ shape (b, n2, D)
357
+ """
358
+ x = self.norm1(x)
359
+ latents = self.norm2(latents)
360
+
361
+ b, l, _ = latents.shape
362
+
363
+ q = self.to_q(latents)
364
+ kv_input = torch.cat((x, latents), dim=-2)
365
+ k, v = self.to_kv(kv_input).chunk(2, dim=-1)
366
+
367
+ q, k, v = map(
368
+ lambda t: t.reshape(b, t.shape[1], self.heads, -1)
369
+ .transpose(1, 2)
370
+ .reshape(b, self.heads, t.shape[1], -1)
371
+ .contiguous(),
372
+ (q, k, v),
373
+ )
374
+
375
+ # attention
376
+ scale = 1 / math.sqrt(math.sqrt(self.dim_head))
377
+ weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards
378
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
379
+ out = weight @ v
380
+
381
+ out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
382
+
383
+ return self.to_out(out)
384
+
385
+
386
+ class Resampler(nn.Module):
387
+ def __init__(
388
+ self,
389
+ dim=1024,
390
+ depth=8,
391
+ dim_head=64,
392
+ heads=16,
393
+ num_queries=8,
394
+ embedding_dim=768,
395
+ output_dim=1024,
396
+ ff_mult=4,
397
+ ):
398
+ super().__init__()
399
+ self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim ** 0.5)
400
+ self.proj_in = nn.Linear(embedding_dim, dim)
401
+ self.proj_out = nn.Linear(dim, output_dim)
402
+ self.norm_out = nn.LayerNorm(output_dim)
403
+
404
+ self.layers = nn.ModuleList([])
405
+ for _ in range(depth):
406
+ self.layers.append(
407
+ nn.ModuleList(
408
+ [
409
+ PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
410
+ nn.Sequential(
411
+ nn.LayerNorm(dim),
412
+ nn.Linear(dim, dim * ff_mult, bias=False),
413
+ nn.GELU(),
414
+ nn.Linear(dim * ff_mult, dim, bias=False),
415
+ )
416
+ ]
417
+ )
418
+ )
419
+
420
+ def forward(self, x):
421
+ latents = self.latents.repeat(x.size(0), 1, 1)
422
+ x = self.proj_in(x)
423
+ for attn, ff in self.layers:
424
+ latents = attn(x, latents) + latents
425
+ latents = ff(latents) + latents
426
+
427
+ latents = self.proj_out(latents)
428
+ return self.norm_out(latents)
429
+
430
+
431
+ class CondSequential(nn.Sequential):
432
+ """
433
+ A sequential module that passes timestep embeddings to the children that
434
+ support it as an extra input.
435
+ """
436
+
437
+ def forward(self, x, emb, context=None, num_frames=1):
438
+ for layer in self:
439
+ if isinstance(layer, ResBlock):
440
+ x = layer(x, emb)
441
+ elif isinstance(layer, SpatialTransformer3D):
442
+ x = layer(x, context, num_frames=num_frames)
443
+ else:
444
+ x = layer(x)
445
+ return x
446
+
447
+
448
+ class Upsample(nn.Module):
449
+ """
450
+ An upsampling layer with an optional convolution.
451
+ :param channels: channels in the inputs and outputs.
452
+ :param use_conv: a bool determining if a convolution is applied.
453
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
454
+ upsampling occurs in the inner-two dimensions.
455
+ """
456
+
457
+ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):
458
+ super().__init__()
459
+ self.channels = channels
460
+ self.out_channels = out_channels or channels
461
+ self.use_conv = use_conv
462
+ self.dims = dims
463
+ if use_conv:
464
+ self.conv = conv_nd(
465
+ dims, self.channels, self.out_channels, 3, padding=padding
466
+ )
467
+
468
+ def forward(self, x):
469
+ assert x.shape[1] == self.channels
470
+ if self.dims == 3:
471
+ x = F.interpolate(
472
+ x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
473
+ )
474
+ else:
475
+ x = F.interpolate(x, scale_factor=2, mode="nearest")
476
+ if self.use_conv:
477
+ x = self.conv(x)
478
+ return x
479
+
480
+
481
+ class Downsample(nn.Module):
482
+ """
483
+ A downsampling layer with an optional convolution.
484
+ :param channels: channels in the inputs and outputs.
485
+ :param use_conv: a bool determining if a convolution is applied.
486
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
487
+ downsampling occurs in the inner-two dimensions.
488
+ """
489
+
490
+ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):
491
+ super().__init__()
492
+ self.channels = channels
493
+ self.out_channels = out_channels or channels
494
+ self.use_conv = use_conv
495
+ self.dims = dims
496
+ stride = 2 if dims != 3 else (1, 2, 2)
497
+ if use_conv:
498
+ self.op = conv_nd(
499
+ dims,
500
+ self.channels,
501
+ self.out_channels,
502
+ 3,
503
+ stride=stride,
504
+ padding=padding,
505
+ )
506
+ else:
507
+ assert self.channels == self.out_channels
508
+ self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
509
+
510
+ def forward(self, x):
511
+ assert x.shape[1] == self.channels
512
+ return self.op(x)
513
+
514
+
515
+ class ResBlock(nn.Module):
516
+ """
517
+ A residual block that can optionally change the number of channels.
518
+ :param channels: the number of input channels.
519
+ :param emb_channels: the number of timestep embedding channels.
520
+ :param dropout: the rate of dropout.
521
+ :param out_channels: if specified, the number of out channels.
522
+ :param use_conv: if True and out_channels is specified, use a spatial
523
+ convolution instead of a smaller 1x1 convolution to change the
524
+ channels in the skip connection.
525
+ :param dims: determines if the signal is 1D, 2D, or 3D.
526
+ :param up: if True, use this block for upsampling.
527
+ :param down: if True, use this block for downsampling.
528
+ """
529
+
530
+ def __init__(
531
+ self,
532
+ channels,
533
+ emb_channels,
534
+ dropout,
535
+ out_channels=None,
536
+ use_conv=False,
537
+ use_scale_shift_norm=False,
538
+ dims=2,
539
+ up=False,
540
+ down=False,
541
+ ):
542
+ super().__init__()
543
+ self.channels = channels
544
+ self.emb_channels = emb_channels
545
+ self.dropout = dropout
546
+ self.out_channels = out_channels or channels
547
+ self.use_conv = use_conv
548
+ self.use_scale_shift_norm = use_scale_shift_norm
549
+
550
+ self.in_layers = nn.Sequential(
551
+ nn.GroupNorm(32, channels),
552
+ nn.SiLU(),
553
+ conv_nd(dims, channels, self.out_channels, 3, padding=1),
554
+ )
555
+
556
+ self.updown = up or down
557
+
558
+ if up:
559
+ self.h_upd = Upsample(channels, False, dims)
560
+ self.x_upd = Upsample(channels, False, dims)
561
+ elif down:
562
+ self.h_upd = Downsample(channels, False, dims)
563
+ self.x_upd = Downsample(channels, False, dims)
564
+ else:
565
+ self.h_upd = self.x_upd = nn.Identity()
566
+
567
+ self.emb_layers = nn.Sequential(
568
+ nn.SiLU(),
569
+ nn.Linear(
570
+ emb_channels,
571
+ 2 * self.out_channels if use_scale_shift_norm else self.out_channels,
572
+ ),
573
+ )
574
+ self.out_layers = nn.Sequential(
575
+ nn.GroupNorm(32, self.out_channels),
576
+ nn.SiLU(),
577
+ nn.Dropout(p=dropout),
578
+ zero_module(
579
+ conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)
580
+ ),
581
+ )
582
+
583
+ if self.out_channels == channels:
584
+ self.skip_connection = nn.Identity()
585
+ elif use_conv:
586
+ self.skip_connection = conv_nd(
587
+ dims, channels, self.out_channels, 3, padding=1
588
+ )
589
+ else:
590
+ self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
591
+
592
+ def forward(self, x, emb):
593
+ if self.updown:
594
+ in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
595
+ h = in_rest(x)
596
+ h = self.h_upd(h)
597
+ x = self.x_upd(x)
598
+ h = in_conv(h)
599
+ else:
600
+ h = self.in_layers(x)
601
+ emb_out = self.emb_layers(emb).type(h.dtype)
602
+ while len(emb_out.shape) < len(h.shape):
603
+ emb_out = emb_out[..., None]
604
+ if self.use_scale_shift_norm:
605
+ out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
606
+ scale, shift = torch.chunk(emb_out, 2, dim=1)
607
+ h = out_norm(h) * (1 + scale) + shift
608
+ h = out_rest(h)
609
+ else:
610
+ h = h + emb_out
611
+ h = self.out_layers(h)
612
+ return self.skip_connection(x) + h
613
+
614
+
615
+ class MultiViewUNetModel(ModelMixin, ConfigMixin):
616
+ """
617
+ The full multi-view UNet model with attention, timestep embedding and camera embedding.
618
+ :param in_channels: channels in the input Tensor.
619
+ :param model_channels: base channel count for the model.
620
+ :param out_channels: channels in the output Tensor.
621
+ :param num_res_blocks: number of residual blocks per downsample.
622
+ :param attention_resolutions: a collection of downsample rates at which
623
+ attention will take place. May be a set, list, or tuple.
624
+ For example, if this contains 4, then at 4x downsampling, attention
625
+ will be used.
626
+ :param dropout: the dropout probability.
627
+ :param channel_mult: channel multiplier for each level of the UNet.
628
+ :param conv_resample: if True, use learned convolutions for upsampling and
629
+ downsampling.
630
+ :param dims: determines if the signal is 1D, 2D, or 3D.
631
+ :param num_classes: if specified (as an int), then this model will be
632
+ class-conditional with `num_classes` classes.
633
+ :param num_heads: the number of attention heads in each attention layer.
634
+ :param num_heads_channels: if specified, ignore num_heads and instead use
635
+ a fixed channel width per attention head.
636
+ :param num_heads_upsample: works with num_heads to set a different number
637
+ of heads for upsampling. Deprecated.
638
+ :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
639
+ :param resblock_updown: use residual blocks for up/downsampling.
640
+ :param use_new_attention_order: use a different attention pattern for potentially
641
+ increased efficiency.
642
+ :param camera_dim: dimensionality of camera input.
643
+ """
644
+
645
+ def __init__(
646
+ self,
647
+ image_size,
648
+ in_channels,
649
+ model_channels,
650
+ out_channels,
651
+ num_res_blocks,
652
+ attention_resolutions,
653
+ dropout=0,
654
+ channel_mult=(1, 2, 4, 8),
655
+ conv_resample=True,
656
+ dims=2,
657
+ num_classes=None,
658
+ num_heads=-1,
659
+ num_head_channels=-1,
660
+ num_heads_upsample=-1,
661
+ use_scale_shift_norm=False,
662
+ resblock_updown=False,
663
+ transformer_depth=1,
664
+ context_dim=None,
665
+ n_embed=None,
666
+ num_attention_blocks=None,
667
+ adm_in_channels=None,
668
+ camera_dim=None,
669
+ ip_dim=0, # imagedream uses ip_dim > 0
670
+ ip_weight=1.0,
671
+ **kwargs,
672
+ ):
673
+ super().__init__()
674
+ assert context_dim is not None
675
+
676
+ if num_heads_upsample == -1:
677
+ num_heads_upsample = num_heads
678
+
679
+ if num_heads == -1:
680
+ assert (
681
+ num_head_channels != -1
682
+ ), "Either num_heads or num_head_channels has to be set"
683
+
684
+ if num_head_channels == -1:
685
+ assert (
686
+ num_heads != -1
687
+ ), "Either num_heads or num_head_channels has to be set"
688
+
689
+ self.image_size = image_size
690
+ self.in_channels = in_channels
691
+ self.model_channels = model_channels
692
+ self.out_channels = out_channels
693
+ if isinstance(num_res_blocks, int):
694
+ self.num_res_blocks = len(channel_mult) * [num_res_blocks]
695
+ else:
696
+ if len(num_res_blocks) != len(channel_mult):
697
+ raise ValueError(
698
+ "provide num_res_blocks either as an int (globally constant) or "
699
+ "as a list/tuple (per-level) with the same length as channel_mult"
700
+ )
701
+ self.num_res_blocks = num_res_blocks
702
+
703
+ if num_attention_blocks is not None:
704
+ assert len(num_attention_blocks) == len(self.num_res_blocks)
705
+ assert all(
706
+ map(
707
+ lambda i: self.num_res_blocks[i] >= num_attention_blocks[i],
708
+ range(len(num_attention_blocks)),
709
+ )
710
+ )
711
+ print(
712
+ f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "
713
+ f"This option has LESS priority than attention_resolutions {attention_resolutions}, "
714
+ f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "
715
+ f"attention will still not be set."
716
+ )
717
+
718
+ self.attention_resolutions = attention_resolutions
719
+ self.dropout = dropout
720
+ self.channel_mult = channel_mult
721
+ self.conv_resample = conv_resample
722
+ self.num_classes = num_classes
723
+ self.num_heads = num_heads
724
+ self.num_head_channels = num_head_channels
725
+ self.num_heads_upsample = num_heads_upsample
726
+ self.predict_codebook_ids = n_embed is not None
727
+
728
+ self.ip_dim = ip_dim
729
+ self.ip_weight = ip_weight
730
+
731
+ if self.ip_dim > 0:
732
+ self.image_embed = Resampler(
733
+ dim=context_dim,
734
+ depth=4,
735
+ dim_head=64,
736
+ heads=12,
737
+ num_queries=ip_dim, # num token
738
+ embedding_dim=1280,
739
+ output_dim=context_dim,
740
+ ff_mult=4,
741
+ )
742
+
743
+ time_embed_dim = model_channels * 4
744
+ self.time_embed = nn.Sequential(
745
+ nn.Linear(model_channels, time_embed_dim),
746
+ nn.SiLU(),
747
+ nn.Linear(time_embed_dim, time_embed_dim),
748
+ )
749
+
750
+ if camera_dim is not None:
751
+ time_embed_dim = model_channels * 4
752
+ self.camera_embed = nn.Sequential(
753
+ nn.Linear(camera_dim, time_embed_dim),
754
+ nn.SiLU(),
755
+ nn.Linear(time_embed_dim, time_embed_dim),
756
+ )
757
+
758
+ if self.num_classes is not None:
759
+ if isinstance(self.num_classes, int):
760
+ self.label_emb = nn.Embedding(self.num_classes, time_embed_dim)
761
+ elif self.num_classes == "continuous":
762
+ # print("setting up linear c_adm embedding layer")
763
+ self.label_emb = nn.Linear(1, time_embed_dim)
764
+ elif self.num_classes == "sequential":
765
+ assert adm_in_channels is not None
766
+ self.label_emb = nn.Sequential(
767
+ nn.Sequential(
768
+ nn.Linear(adm_in_channels, time_embed_dim),
769
+ nn.SiLU(),
770
+ nn.Linear(time_embed_dim, time_embed_dim),
771
+ )
772
+ )
773
+ else:
774
+ raise ValueError()
775
+
776
+ self.input_blocks = nn.ModuleList(
777
+ [
778
+ CondSequential(
779
+ conv_nd(dims, in_channels, model_channels, 3, padding=1)
780
+ )
781
+ ]
782
+ )
783
+ self._feature_size = model_channels
784
+ input_block_chans = [model_channels]
785
+ ch = model_channels
786
+ ds = 1
787
+ for level, mult in enumerate(channel_mult):
788
+ for nr in range(self.num_res_blocks[level]):
789
+ layers: List[Any] = [
790
+ ResBlock(
791
+ ch,
792
+ time_embed_dim,
793
+ dropout,
794
+ out_channels=mult * model_channels,
795
+ dims=dims,
796
+ use_scale_shift_norm=use_scale_shift_norm,
797
+ )
798
+ ]
799
+ ch = mult * model_channels
800
+ if ds in attention_resolutions:
801
+ if num_head_channels == -1:
802
+ dim_head = ch // num_heads
803
+ else:
804
+ num_heads = ch // num_head_channels
805
+ dim_head = num_head_channels
806
+
807
+ if num_attention_blocks is None or nr < num_attention_blocks[level]:
808
+ layers.append(
809
+ SpatialTransformer3D(
810
+ ch,
811
+ num_heads,
812
+ dim_head,
813
+ context_dim=context_dim,
814
+ depth=transformer_depth,
815
+ ip_dim=self.ip_dim,
816
+ ip_weight=self.ip_weight,
817
+ )
818
+ )
819
+ self.input_blocks.append(CondSequential(*layers))
820
+ self._feature_size += ch
821
+ input_block_chans.append(ch)
822
+ if level != len(channel_mult) - 1:
823
+ out_ch = ch
824
+ self.input_blocks.append(
825
+ CondSequential(
826
+ ResBlock(
827
+ ch,
828
+ time_embed_dim,
829
+ dropout,
830
+ out_channels=out_ch,
831
+ dims=dims,
832
+ use_scale_shift_norm=use_scale_shift_norm,
833
+ down=True,
834
+ )
835
+ if resblock_updown
836
+ else Downsample(
837
+ ch, conv_resample, dims=dims, out_channels=out_ch
838
+ )
839
+ )
840
+ )
841
+ ch = out_ch
842
+ input_block_chans.append(ch)
843
+ ds *= 2
844
+ self._feature_size += ch
845
+
846
+ if num_head_channels == -1:
847
+ dim_head = ch // num_heads
848
+ else:
849
+ num_heads = ch // num_head_channels
850
+ dim_head = num_head_channels
851
+
852
+ self.middle_block = CondSequential(
853
+ ResBlock(
854
+ ch,
855
+ time_embed_dim,
856
+ dropout,
857
+ dims=dims,
858
+ use_scale_shift_norm=use_scale_shift_norm,
859
+ ),
860
+ SpatialTransformer3D(
861
+ ch,
862
+ num_heads,
863
+ dim_head,
864
+ context_dim=context_dim,
865
+ depth=transformer_depth,
866
+ ip_dim=self.ip_dim,
867
+ ip_weight=self.ip_weight,
868
+ ),
869
+ ResBlock(
870
+ ch,
871
+ time_embed_dim,
872
+ dropout,
873
+ dims=dims,
874
+ use_scale_shift_norm=use_scale_shift_norm,
875
+ ),
876
+ )
877
+ self._feature_size += ch
878
+
879
+ self.output_blocks = nn.ModuleList([])
880
+ for level, mult in list(enumerate(channel_mult))[::-1]:
881
+ for i in range(self.num_res_blocks[level] + 1):
882
+ ich = input_block_chans.pop()
883
+ layers = [
884
+ ResBlock(
885
+ ch + ich,
886
+ time_embed_dim,
887
+ dropout,
888
+ out_channels=model_channels * mult,
889
+ dims=dims,
890
+ use_scale_shift_norm=use_scale_shift_norm,
891
+ )
892
+ ]
893
+ ch = model_channels * mult
894
+ if ds in attention_resolutions:
895
+ if num_head_channels == -1:
896
+ dim_head = ch // num_heads
897
+ else:
898
+ num_heads = ch // num_head_channels
899
+ dim_head = num_head_channels
900
+
901
+ if num_attention_blocks is None or i < num_attention_blocks[level]:
902
+ layers.append(
903
+ SpatialTransformer3D(
904
+ ch,
905
+ num_heads,
906
+ dim_head,
907
+ context_dim=context_dim,
908
+ depth=transformer_depth,
909
+ ip_dim=self.ip_dim,
910
+ ip_weight=self.ip_weight,
911
+ )
912
+ )
913
+ if level and i == self.num_res_blocks[level]:
914
+ out_ch = ch
915
+ layers.append(
916
+ ResBlock(
917
+ ch,
918
+ time_embed_dim,
919
+ dropout,
920
+ out_channels=out_ch,
921
+ dims=dims,
922
+ use_scale_shift_norm=use_scale_shift_norm,
923
+ up=True,
924
+ )
925
+ if resblock_updown
926
+ else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
927
+ )
928
+ ds //= 2
929
+ self.output_blocks.append(CondSequential(*layers))
930
+ self._feature_size += ch
931
+
932
+ self.out = nn.Sequential(
933
+ nn.GroupNorm(32, ch),
934
+ nn.SiLU(),
935
+ zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),
936
+ )
937
+ if self.predict_codebook_ids:
938
+ self.id_predictor = nn.Sequential(
939
+ nn.GroupNorm(32, ch),
940
+ conv_nd(dims, model_channels, n_embed, 1),
941
+ # nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
942
+ )
943
+
944
+ def forward(
945
+ self,
946
+ x,
947
+ timesteps=None,
948
+ context=None,
949
+ y=None,
950
+ camera=None,
951
+ num_frames=1,
952
+ ip=None,
953
+ ip_img=None,
954
+ **kwargs,
955
+ ):
956
+ """
957
+ Apply the model to an input batch.
958
+ :param x: an [(N x F) x C x ...] Tensor of inputs. F is the number of frames (views).
959
+ :param timesteps: a 1-D batch of timesteps.
960
+ :param context: conditioning plugged in via crossattn
961
+ :param y: an [N] Tensor of labels, if class-conditional.
962
+ :param num_frames: a integer indicating number of frames for tensor reshaping.
963
+ :return: an [(N x F) x C x ...] Tensor of outputs. F is the number of frames (views).
964
+ """
965
+ assert (
966
+ x.shape[0] % num_frames == 0
967
+ ), "input batch size must be dividable by num_frames!"
968
+ assert (y is not None) == (
969
+ self.num_classes is not None
970
+ ), "must specify y if and only if the model is class-conditional"
971
+
972
+ hs = []
973
+
974
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
975
+
976
+ emb = self.time_embed(t_emb)
977
+
978
+ if self.num_classes is not None:
979
+ assert y is not None
980
+ assert y.shape[0] == x.shape[0]
981
+ emb = emb + self.label_emb(y)
982
+
983
+ # Add camera embeddings
984
+ if camera is not None:
985
+ emb = emb + self.camera_embed(camera)
986
+
987
+ # imagedream variant
988
+ if self.ip_dim > 0:
989
+ x[(num_frames - 1) :: num_frames, :, :, :] = ip_img # place at [4, 9]
990
+ ip_emb = self.image_embed(ip)
991
+ context = torch.cat((context, ip_emb), 1)
992
+
993
+ h = x
994
+ for module in self.input_blocks:
995
+ h = module(h, emb, context, num_frames=num_frames)
996
+ hs.append(h)
997
+ h = self.middle_block(h, emb, context, num_frames=num_frames)
998
+ for module in self.output_blocks:
999
+ h = torch.cat([h, hs.pop()], dim=1)
1000
+ h = module(h, emb, context, num_frames=num_frames)
1001
+ h = h.type(x.dtype)
1002
+ if self.predict_codebook_ids:
1003
+ return self.id_predictor(h)
1004
+ else:
1005
+ return self.out(h)
mvdream/pipeline_mvdream.py ADDED
@@ -0,0 +1,559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ import inspect
4
+ import numpy as np
5
+ from typing import Callable, List, Optional, Union
6
+ from transformers import CLIPTextModel, CLIPTokenizer, CLIPVisionModel, CLIPImageProcessor
7
+ from diffusers import AutoencoderKL, DiffusionPipeline
8
+ from diffusers.utils import (
9
+ deprecate,
10
+ is_accelerate_available,
11
+ is_accelerate_version,
12
+ logging,
13
+ )
14
+ from diffusers.configuration_utils import FrozenDict
15
+ from diffusers.schedulers import DDIMScheduler
16
+ from diffusers.utils.torch_utils import randn_tensor
17
+
18
+ from mvdream.mv_unet import MultiViewUNetModel, get_camera
19
+
20
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
21
+
22
+
23
+ class MVDreamPipeline(DiffusionPipeline):
24
+
25
+ _optional_components = ["feature_extractor", "image_encoder"]
26
+
27
+ def __init__(
28
+ self,
29
+ vae: AutoencoderKL,
30
+ unet: MultiViewUNetModel,
31
+ tokenizer: CLIPTokenizer,
32
+ text_encoder: CLIPTextModel,
33
+ scheduler: DDIMScheduler,
34
+ # imagedream variant
35
+ feature_extractor: CLIPImageProcessor,
36
+ image_encoder: CLIPVisionModel,
37
+ requires_safety_checker: bool = False,
38
+ ):
39
+ super().__init__()
40
+
41
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1: # type: ignore
42
+ deprecation_message = (
43
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
44
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " # type: ignore
45
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
46
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
47
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
48
+ " file"
49
+ )
50
+ deprecate(
51
+ "steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False
52
+ )
53
+ new_config = dict(scheduler.config)
54
+ new_config["steps_offset"] = 1
55
+ scheduler._internal_dict = FrozenDict(new_config)
56
+
57
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True: # type: ignore
58
+ deprecation_message = (
59
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
60
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
61
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
62
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
63
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
64
+ )
65
+ deprecate(
66
+ "clip_sample not set", "1.0.0", deprecation_message, standard_warn=False
67
+ )
68
+ new_config = dict(scheduler.config)
69
+ new_config["clip_sample"] = False
70
+ scheduler._internal_dict = FrozenDict(new_config)
71
+
72
+ self.register_modules(
73
+ vae=vae,
74
+ unet=unet,
75
+ scheduler=scheduler,
76
+ tokenizer=tokenizer,
77
+ text_encoder=text_encoder,
78
+ feature_extractor=feature_extractor,
79
+ image_encoder=image_encoder,
80
+ )
81
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
82
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
83
+
84
+ def enable_vae_slicing(self):
85
+ r"""
86
+ Enable sliced VAE decoding.
87
+
88
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
89
+ steps. This is useful to save some memory and allow larger batch sizes.
90
+ """
91
+ self.vae.enable_slicing()
92
+
93
+ def disable_vae_slicing(self):
94
+ r"""
95
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
96
+ computing decoding in one step.
97
+ """
98
+ self.vae.disable_slicing()
99
+
100
+ def enable_vae_tiling(self):
101
+ r"""
102
+ Enable tiled VAE decoding.
103
+
104
+ When this option is enabled, the VAE will split the input tensor into tiles to compute decoding and encoding in
105
+ several steps. This is useful to save a large amount of memory and to allow the processing of larger images.
106
+ """
107
+ self.vae.enable_tiling()
108
+
109
+ def disable_vae_tiling(self):
110
+ r"""
111
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously invoked, this method will go back to
112
+ computing decoding in one step.
113
+ """
114
+ self.vae.disable_tiling()
115
+
116
+ def enable_sequential_cpu_offload(self, gpu_id=0):
117
+ r"""
118
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
119
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
120
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
121
+ Note that offloading happens on a submodule basis. Memory savings are higher than with
122
+ `enable_model_cpu_offload`, but performance is lower.
123
+ """
124
+ if is_accelerate_available() and is_accelerate_version(">=", "0.14.0"):
125
+ from accelerate import cpu_offload
126
+ else:
127
+ raise ImportError(
128
+ "`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higher"
129
+ )
130
+
131
+ device = torch.device(f"cuda:{gpu_id}")
132
+
133
+ if self.device.type != "cpu":
134
+ self.to("cpu", silence_dtype_warnings=True)
135
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
136
+
137
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
138
+ cpu_offload(cpu_offloaded_model, device)
139
+
140
+ def enable_model_cpu_offload(self, gpu_id=0):
141
+ r"""
142
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
143
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
144
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
145
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
146
+ """
147
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
148
+ from accelerate import cpu_offload_with_hook
149
+ else:
150
+ raise ImportError(
151
+ "`enable_model_offload` requires `accelerate v0.17.0` or higher."
152
+ )
153
+
154
+ device = torch.device(f"cuda:{gpu_id}")
155
+
156
+ if self.device.type != "cpu":
157
+ self.to("cpu", silence_dtype_warnings=True)
158
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
159
+
160
+ hook = None
161
+ for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:
162
+ _, hook = cpu_offload_with_hook(
163
+ cpu_offloaded_model, device, prev_module_hook=hook
164
+ )
165
+
166
+ # We'll offload the last model manually.
167
+ self.final_offload_hook = hook
168
+
169
+ @property
170
+ def _execution_device(self):
171
+ r"""
172
+ Returns the device on which the pipeline's models will be executed. After calling
173
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
174
+ hooks.
175
+ """
176
+ if not hasattr(self.unet, "_hf_hook"):
177
+ return self.device
178
+ for module in self.unet.modules():
179
+ if (
180
+ hasattr(module, "_hf_hook")
181
+ and hasattr(module._hf_hook, "execution_device")
182
+ and module._hf_hook.execution_device is not None
183
+ ):
184
+ return torch.device(module._hf_hook.execution_device)
185
+ return self.device
186
+
187
+ def _encode_prompt(
188
+ self,
189
+ prompt,
190
+ device,
191
+ num_images_per_prompt,
192
+ do_classifier_free_guidance: bool,
193
+ negative_prompt=None,
194
+ ):
195
+ r"""
196
+ Encodes the prompt into text encoder hidden states.
197
+
198
+ Args:
199
+ prompt (`str` or `List[str]`, *optional*):
200
+ prompt to be encoded
201
+ device: (`torch.device`):
202
+ torch device
203
+ num_images_per_prompt (`int`):
204
+ number of images that should be generated per prompt
205
+ do_classifier_free_guidance (`bool`):
206
+ whether to use classifier free guidance or not
207
+ negative_prompt (`str` or `List[str]`, *optional*):
208
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
209
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
210
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
211
+ prompt_embeds (`torch.FloatTensor`, *optional*):
212
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
213
+ provided, text embeddings will be generated from `prompt` input argument.
214
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
215
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
216
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
217
+ argument.
218
+ """
219
+ if prompt is not None and isinstance(prompt, str):
220
+ batch_size = 1
221
+ elif prompt is not None and isinstance(prompt, list):
222
+ batch_size = len(prompt)
223
+ else:
224
+ raise ValueError(
225
+ f"`prompt` should be either a string or a list of strings, but got {type(prompt)}."
226
+ )
227
+
228
+ text_inputs = self.tokenizer(
229
+ prompt,
230
+ padding="max_length",
231
+ max_length=self.tokenizer.model_max_length,
232
+ truncation=True,
233
+ return_tensors="pt",
234
+ )
235
+ text_input_ids = text_inputs.input_ids
236
+ untruncated_ids = self.tokenizer(
237
+ prompt, padding="longest", return_tensors="pt"
238
+ ).input_ids
239
+
240
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
241
+ text_input_ids, untruncated_ids
242
+ ):
243
+ removed_text = self.tokenizer.batch_decode(
244
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
245
+ )
246
+ logger.warning(
247
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
248
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
249
+ )
250
+
251
+ if (
252
+ hasattr(self.text_encoder.config, "use_attention_mask")
253
+ and self.text_encoder.config.use_attention_mask
254
+ ):
255
+ attention_mask = text_inputs.attention_mask.to(device)
256
+ else:
257
+ attention_mask = None
258
+
259
+ prompt_embeds = self.text_encoder(
260
+ text_input_ids.to(device),
261
+ attention_mask=attention_mask,
262
+ )
263
+ prompt_embeds = prompt_embeds[0]
264
+
265
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
266
+
267
+ bs_embed, seq_len, _ = prompt_embeds.shape
268
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
269
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
270
+ prompt_embeds = prompt_embeds.view(
271
+ bs_embed * num_images_per_prompt, seq_len, -1
272
+ )
273
+
274
+ # get unconditional embeddings for classifier free guidance
275
+ if do_classifier_free_guidance:
276
+ uncond_tokens: List[str]
277
+ if negative_prompt is None:
278
+ uncond_tokens = [""] * batch_size
279
+ elif type(prompt) is not type(negative_prompt):
280
+ raise TypeError(
281
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
282
+ f" {type(prompt)}."
283
+ )
284
+ elif isinstance(negative_prompt, str):
285
+ uncond_tokens = [negative_prompt]
286
+ elif batch_size != len(negative_prompt):
287
+ raise ValueError(
288
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
289
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
290
+ " the batch size of `prompt`."
291
+ )
292
+ else:
293
+ uncond_tokens = negative_prompt
294
+
295
+ max_length = prompt_embeds.shape[1]
296
+ uncond_input = self.tokenizer(
297
+ uncond_tokens,
298
+ padding="max_length",
299
+ max_length=max_length,
300
+ truncation=True,
301
+ return_tensors="pt",
302
+ )
303
+
304
+ if (
305
+ hasattr(self.text_encoder.config, "use_attention_mask")
306
+ and self.text_encoder.config.use_attention_mask
307
+ ):
308
+ attention_mask = uncond_input.attention_mask.to(device)
309
+ else:
310
+ attention_mask = None
311
+
312
+ negative_prompt_embeds = self.text_encoder(
313
+ uncond_input.input_ids.to(device),
314
+ attention_mask=attention_mask,
315
+ )
316
+ negative_prompt_embeds = negative_prompt_embeds[0]
317
+
318
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
319
+ seq_len = negative_prompt_embeds.shape[1]
320
+
321
+ negative_prompt_embeds = negative_prompt_embeds.to(
322
+ dtype=self.text_encoder.dtype, device=device
323
+ )
324
+
325
+ negative_prompt_embeds = negative_prompt_embeds.repeat(
326
+ 1, num_images_per_prompt, 1
327
+ )
328
+ negative_prompt_embeds = negative_prompt_embeds.view(
329
+ batch_size * num_images_per_prompt, seq_len, -1
330
+ )
331
+
332
+ # For classifier free guidance, we need to do two forward passes.
333
+ # Here we concatenate the unconditional and text embeddings into a single batch
334
+ # to avoid doing two forward passes
335
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
336
+
337
+ return prompt_embeds
338
+
339
+ def decode_latents(self, latents):
340
+ latents = 1 / self.vae.config.scaling_factor * latents
341
+ image = self.vae.decode(latents).sample
342
+ image = (image / 2 + 0.5).clamp(0, 1)
343
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
344
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
345
+ return image
346
+
347
+ def prepare_extra_step_kwargs(self, generator, eta):
348
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
349
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
350
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
351
+ # and should be between [0, 1]
352
+
353
+ accepts_eta = "eta" in set(
354
+ inspect.signature(self.scheduler.step).parameters.keys()
355
+ )
356
+ extra_step_kwargs = {}
357
+ if accepts_eta:
358
+ extra_step_kwargs["eta"] = eta
359
+
360
+ # check if the scheduler accepts generator
361
+ accepts_generator = "generator" in set(
362
+ inspect.signature(self.scheduler.step).parameters.keys()
363
+ )
364
+ if accepts_generator:
365
+ extra_step_kwargs["generator"] = generator
366
+ return extra_step_kwargs
367
+
368
+ def prepare_latents(
369
+ self,
370
+ batch_size,
371
+ num_channels_latents,
372
+ height,
373
+ width,
374
+ dtype,
375
+ device,
376
+ generator,
377
+ latents=None,
378
+ ):
379
+ shape = (
380
+ batch_size,
381
+ num_channels_latents,
382
+ height // self.vae_scale_factor,
383
+ width // self.vae_scale_factor,
384
+ )
385
+ if isinstance(generator, list) and len(generator) != batch_size:
386
+ raise ValueError(
387
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
388
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
389
+ )
390
+
391
+ if latents is None:
392
+ latents = randn_tensor(
393
+ shape, generator=generator, device=device, dtype=dtype
394
+ )
395
+ else:
396
+ latents = latents.to(device)
397
+
398
+ # scale the initial noise by the standard deviation required by the scheduler
399
+ latents = latents * self.scheduler.init_noise_sigma
400
+ return latents
401
+
402
+ def encode_image(self, image, device, num_images_per_prompt):
403
+ dtype = next(self.image_encoder.parameters()).dtype
404
+
405
+ if image.dtype == np.float32:
406
+ image = (image * 255).astype(np.uint8)
407
+
408
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
409
+ image = image.to(device=device, dtype=dtype)
410
+
411
+ image_embeds = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
412
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
413
+
414
+ return torch.zeros_like(image_embeds), image_embeds
415
+
416
+ def encode_image_latents(self, image, device, num_images_per_prompt):
417
+
418
+ dtype = next(self.image_encoder.parameters()).dtype
419
+
420
+ image = torch.from_numpy(image).unsqueeze(0).permute(0, 3, 1, 2).to(device=device) # [1, 3, H, W]
421
+ image = 2 * image - 1
422
+ image = F.interpolate(image, (256, 256), mode='bilinear', align_corners=False)
423
+ image = image.to(dtype=dtype)
424
+
425
+ posterior = self.vae.encode(image).latent_dist
426
+ latents = posterior.sample() * self.vae.config.scaling_factor # [B, C, H, W]
427
+ latents = latents.repeat_interleave(num_images_per_prompt, dim=0)
428
+
429
+ return torch.zeros_like(latents), latents
430
+
431
+ @torch.no_grad()
432
+ def __call__(
433
+ self,
434
+ prompt: str = "",
435
+ image: Optional[np.ndarray] = None,
436
+ height: int = 256,
437
+ width: int = 256,
438
+ elevation: float = 0,
439
+ num_inference_steps: int = 50,
440
+ guidance_scale: float = 7.0,
441
+ negative_prompt: str = "",
442
+ num_images_per_prompt: int = 1,
443
+ eta: float = 0.0,
444
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
445
+ output_type: Optional[str] = "numpy", # pil, numpy, latents
446
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
447
+ callback_steps: int = 1,
448
+ num_frames: int = 4,
449
+ device=torch.device("cuda:0"),
450
+ ):
451
+ self.unet = self.unet.to(device=device)
452
+ self.vae = self.vae.to(device=device)
453
+ self.text_encoder = self.text_encoder.to(device=device)
454
+
455
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
456
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
457
+ # corresponds to doing no classifier free guidance.
458
+ do_classifier_free_guidance = guidance_scale > 1.0
459
+
460
+ # Prepare timesteps
461
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
462
+ timesteps = self.scheduler.timesteps
463
+
464
+ # imagedream variant
465
+ if image is not None:
466
+ assert isinstance(image, np.ndarray) and image.dtype == np.float32
467
+ self.image_encoder = self.image_encoder.to(device=device)
468
+ image_embeds_neg, image_embeds_pos = self.encode_image(image, device, num_images_per_prompt)
469
+ image_latents_neg, image_latents_pos = self.encode_image_latents(image, device, num_images_per_prompt)
470
+
471
+ _prompt_embeds = self._encode_prompt(
472
+ prompt=prompt,
473
+ device=device,
474
+ num_images_per_prompt=num_images_per_prompt,
475
+ do_classifier_free_guidance=do_classifier_free_guidance,
476
+ negative_prompt=negative_prompt,
477
+ ) # type: ignore
478
+ prompt_embeds_neg, prompt_embeds_pos = _prompt_embeds.chunk(2)
479
+
480
+ # Prepare latent variables
481
+ actual_num_frames = num_frames if image is None else num_frames + 1
482
+ latents: torch.Tensor = self.prepare_latents(
483
+ actual_num_frames * num_images_per_prompt,
484
+ 4,
485
+ height,
486
+ width,
487
+ prompt_embeds_pos.dtype,
488
+ device,
489
+ generator,
490
+ None,
491
+ )
492
+
493
+ if image is not None:
494
+ camera = get_camera(num_frames, elevation=elevation, extra_view=True).to(dtype=latents.dtype, device=device)
495
+ else:
496
+ camera = get_camera(num_frames, elevation=elevation, extra_view=False).to(dtype=latents.dtype, device=device)
497
+ camera = camera.repeat_interleave(num_images_per_prompt, dim=0)
498
+
499
+ # Prepare extra step kwargs.
500
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
501
+
502
+ # Denoising loop
503
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
504
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
505
+ for i, t in enumerate(timesteps):
506
+ # expand the latents if we are doing classifier free guidance
507
+ multiplier = 2 if do_classifier_free_guidance else 1
508
+ latent_model_input = torch.cat([latents] * multiplier)
509
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
510
+
511
+ unet_inputs = {
512
+ 'x': latent_model_input,
513
+ 'timesteps': torch.tensor([t] * actual_num_frames * multiplier, dtype=latent_model_input.dtype, device=device),
514
+ 'context': torch.cat([prompt_embeds_neg] * actual_num_frames + [prompt_embeds_pos] * actual_num_frames),
515
+ 'num_frames': actual_num_frames,
516
+ 'camera': torch.cat([camera] * multiplier),
517
+ }
518
+
519
+ if image is not None:
520
+ unet_inputs['ip'] = torch.cat([image_embeds_neg] * actual_num_frames + [image_embeds_pos] * actual_num_frames)
521
+ unet_inputs['ip_img'] = torch.cat([image_latents_neg] + [image_latents_pos]) # no repeat
522
+
523
+ # predict the noise residual
524
+ noise_pred = self.unet.forward(**unet_inputs)
525
+
526
+ # perform guidance
527
+ if do_classifier_free_guidance:
528
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
529
+ noise_pred = noise_pred_uncond + guidance_scale * (
530
+ noise_pred_text - noise_pred_uncond
531
+ )
532
+
533
+ # compute the previous noisy sample x_t -> x_t-1
534
+ latents: torch.Tensor = self.scheduler.step(
535
+ noise_pred, t, latents, **extra_step_kwargs, return_dict=False
536
+ )[0]
537
+
538
+ # call the callback, if provided
539
+ if i == len(timesteps) - 1 or (
540
+ (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
541
+ ):
542
+ progress_bar.update()
543
+ if callback is not None and i % callback_steps == 0:
544
+ callback(i, t, latents) # type: ignore
545
+
546
+ # Post-processing
547
+ if output_type == "latent":
548
+ image = latents
549
+ elif output_type == "pil":
550
+ image = self.decode_latents(latents)
551
+ image = self.numpy_to_pil(image)
552
+ else: # numpy
553
+ image = self.decode_latents(latents)
554
+
555
+ # Offload last model to CPU
556
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
557
+ self.final_offload_hook.offload()
558
+
559
+ return image
requirements.txt ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu118
2
+ torch
3
+ --extra-index-url https://download.pytorch.org/whl/cu118
4
+ xformers
5
+ numpy
6
+ tyro
7
+ diffusers
8
+ dearpygui
9
+ einops
10
+ accelerate
11
+ gradio
12
+ imageio
13
+ imageio-ffmpeg
14
+ lpips
15
+ matplotlib
16
+ packaging
17
+ Pillow
18
+ pygltflib
19
+ rembg[gpu,cli]
20
+ rich
21
+ safetensors
22
+ scikit-image
23
+ scikit-learn
24
+ scipy
25
+ tqdm
26
+ transformers
27
+ trimesh
28
+ kiui >= 0.2.3
29
+ xatlas
30
+ roma