NIRVANALAN commited on
Commit
267d055
1 Parent(s): e505b8e
Files changed (3) hide show
  1. app.py +453 -10
  2. app_demo.py +14 -0
  3. gradio_app.py +0 -457
app.py CHANGED
@@ -1,14 +1,457 @@
1
- import gradio as gr
2
- import spaces
3
  import torch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
- zero = torch.Tensor([0]).cuda()
6
- print(zero.device) # <-- 'cpu' 🤔
7
 
8
- @spaces.GPU
9
- def greet(n):
10
- print(zero.device) # <-- 'cuda:0' 🤗
11
- return f"Hello {zero + n} Tensor"
12
 
13
- demo = gr.Interface(fn=greet, inputs=gr.Number(), outputs=gr.Text())
14
- demo.launch()
 
 
 
1
  import torch
2
+ import torchvision
3
+ from torchvision import transforms
4
+ import numpy as np
5
+
6
+ import os
7
+ from omegaconf import OmegaConf
8
+ from PIL import Image
9
+
10
+ import gradio as gr
11
+
12
+ import rembg
13
+
14
+ import spaces
15
+
16
+ from huggingface_hub import hf_hub_download
17
+
18
+
19
+ """
20
+ Generate a large batch of image samples from a model and save them as a large
21
+ numpy array. This can be used to produce samples for FID evaluation.
22
+ """
23
+
24
+ import argparse
25
+ import json
26
+ import sys
27
+ import os
28
+
29
+ sys.path.append('.')
30
+
31
+ from pdb import set_trace as st
32
+ import imageio
33
+ import numpy as np
34
+ import torch as th
35
+ import torch.distributed as dist
36
+
37
+ from guided_diffusion import dist_util, logger
38
+ from guided_diffusion.script_util import (
39
+ NUM_CLASSES,
40
+ model_and_diffusion_defaults,
41
+ create_model_and_diffusion,
42
+ add_dict_to_argparser,
43
+ args_to_dict,
44
+ continuous_diffusion_defaults,
45
+ control_net_defaults,
46
+ )
47
+
48
+ th.backends.cuda.matmul.allow_tf32 = True
49
+ th.backends.cudnn.allow_tf32 = True
50
+ th.backends.cudnn.enabled = True
51
+
52
+ from pathlib import Path
53
+
54
+ from tqdm import tqdm, trange
55
+ import dnnlib
56
+ from nsr.train_util_diffusion import TrainLoop3DDiffusion as TrainLoop
57
+ from guided_diffusion.continuous_diffusion import make_diffusion as make_sde_diffusion
58
+ import nsr
59
+ import nsr.lsgm
60
+ from nsr.script_util import create_3DAE_model, encoder_and_nsr_defaults, loss_defaults, AE_with_Diffusion, rendering_options_defaults, eg3d_options_default, dataset_defaults
61
+
62
+ from datasets.shapenet import load_eval_data
63
+ from torch.utils.data import Subset
64
+ from datasets.eg3d_dataset import init_dataset_kwargs
65
+
66
+ from transport.train_utils import parse_transport_args
67
+
68
+ from utils.infer_utils import remove_background, resize_foreground
69
+
70
+ SEED = 0
71
+
72
+ def resize_to_224(img):
73
+ img = transforms.functional.resize(img, 224,
74
+ interpolation=transforms.InterpolationMode.LANCZOS)
75
+ return img
76
+
77
+
78
+ def set_white_background(image):
79
+ image = np.array(image).astype(np.float32) / 255.0
80
+ mask = image[:, :, 3:4]
81
+ image = image[:, :, :3] * mask + (1 - mask)
82
+ image = Image.fromarray((image * 255.0).astype(np.uint8))
83
+ return image
84
+
85
+
86
+ def check_input_image(input_image):
87
+ if input_image is None:
88
+ raise gr.Error("No image uploaded!")
89
+
90
+
91
+
92
+ def main(args):
93
+
94
+ # args.rendering_kwargs = rendering_options_defaults(args)
95
+
96
+ dist_util.setup_dist(args)
97
+ logger.configure(dir=args.logdir)
98
+
99
+ th.cuda.empty_cache()
100
+
101
+ th.cuda.manual_seed_all(SEED)
102
+ np.random.seed(SEED)
103
+
104
+ # * set denoise model args
105
+ logger.log("creating model and diffusion...")
106
+ args.img_size = [args.image_size_encoder]
107
+ # ! no longer required for LDM
108
+ # args.denoise_in_channels = args.out_chans
109
+ # args.denoise_out_channels = args.out_chans
110
+ args.image_size = args.image_size_encoder # 224, follow the triplane size
111
+
112
+ denoise_model, diffusion = create_model_and_diffusion(
113
+ **args_to_dict(args,
114
+ model_and_diffusion_defaults().keys()))
115
+
116
+ # if 'cldm' in args.trainer_name:
117
+ # assert isinstance(denoise_model, tuple)
118
+ # denoise_model, controlNet = denoise_model
119
+
120
+ # controlNet.to(dist_util.dev())
121
+ # controlNet.train()
122
+ # else:
123
+ # controlNet = None
124
+
125
+ opts = eg3d_options_default()
126
+ if args.sr_training:
127
+ args.sr_kwargs = dnnlib.EasyDict(
128
+ channel_base=opts.cbase,
129
+ channel_max=opts.cmax,
130
+ fused_modconv_default='inference_only',
131
+ use_noise=True
132
+ ) # ! close noise injection? since noise_mode='none' in eg3d
133
+
134
+ # denoise_model.load_state_dict(
135
+ # dist_util.load_state_dict(args.ddpm_model_path, map_location="cpu"))
136
+ denoise_model.to(dist_util.dev())
137
+ if args.use_fp16:
138
+ denoise_model.convert_to_fp16()
139
+ denoise_model.eval()
140
+
141
+ # * auto-encoder reconstruction model
142
+ logger.log("creating 3DAE...")
143
+ auto_encoder = create_3DAE_model(
144
+ **args_to_dict(args,
145
+ encoder_and_nsr_defaults().keys()))
146
+
147
+ auto_encoder.to(dist_util.dev())
148
+ auto_encoder.eval()
149
+
150
+ # TODO, how to set the scale?
151
+ logger.log("create dataset")
152
+
153
+ if args.objv_dataset:
154
+ from datasets.g_buffer_objaverse import load_data, load_eval_data, load_memory_data, load_wds_data
155
+ else: # shapenet
156
+ from datasets.shapenet import load_data, load_eval_data, load_memory_data
157
+
158
+ # load data if i23d
159
+ if args.i23d:
160
+ data = load_eval_data(
161
+ file_path=args.eval_data_dir,
162
+ batch_size=args.eval_batch_size,
163
+ reso=args.image_size,
164
+ reso_encoder=args.image_size_encoder, # 224 -> 128
165
+ num_workers=args.num_workers,
166
+ load_depth=True, # for evaluation
167
+ preprocess=auto_encoder.preprocess,
168
+ **args_to_dict(args,
169
+ dataset_defaults().keys()))
170
+ else:
171
+ data = None # t23d sampling, only caption required
172
+
173
+
174
+ TrainLoop = {
175
+ 'sgm_legacy':
176
+ nsr.lsgm.sgm_DiffusionEngine.DiffusionEngineLSGM,
177
+ 'flow_matching':
178
+ nsr.lsgm.flow_matching_trainer.FlowMatchingEngine,
179
+ }[args.trainer_name]
180
+
181
+ # continuous
182
+ sde_diffusion = None
183
+
184
+ auto_encoder.decoder.rendering_kwargs = args.rendering_kwargs
185
+
186
+ training_loop_class = TrainLoop(rec_model=auto_encoder,
187
+ denoise_model=denoise_model,
188
+ control_model=None, # to remove
189
+ diffusion=diffusion,
190
+ sde_diffusion=sde_diffusion,
191
+ loss_class=None,
192
+ data=data,
193
+ eval_data=None,
194
+ **vars(args))
195
+
196
+ @spaces.GPU()
197
+ def reconstruct_and_export(*args, **kwargs):
198
+ return training_loop_class.eval_i23d_and_export(*args, **kwargs)
199
+
200
+
201
+ css = """
202
+ h1 {
203
+ text-align: center;
204
+ display:block;
205
+ }
206
+ """
207
+
208
+
209
+ def preprocess(input_image, preprocess_background=True, foreground_ratio=0.85):
210
+ if preprocess_background:
211
+ rembg_session = rembg.new_session()
212
+ image = input_image.convert("RGB")
213
+ image = remove_background(image, rembg_session)
214
+ image = resize_foreground(image, foreground_ratio)
215
+ image = set_white_background(image)
216
+ else:
217
+ image = input_image
218
+ if image.mode == "RGBA":
219
+ image = set_white_background(image)
220
+ image = resize_to_224(image)
221
+ return image
222
+
223
+
224
+ with gr.Blocks(css=css) as demo:
225
+ gr.Markdown(
226
+ """
227
+ # LN3Diff (Scalable Latent Neural Fields Diffusion for Speedy 3D Generation)
228
+
229
+ **LN3Diff (ECCV 2024)** [[code](https://github.com/NIRVANALAN/LN3Diff), [project page](https://nirvanalan.github.io/projects/ln3diff/)] is a scalable 3D latent diffusion model that supports speedy 3D assets generation.
230
+ It first trains a 3D VAE on **Objaverse**, which compress each 3D asset into a compact 3D-aware latent. After that, a image/text-conditioned diffusion model is trained following LDM paradigm.
231
+ The model used in the demo adopts DiT-L/2 architecture and flow-matching framework, and supports single-image condition.
232
+ It is trained on 8 A100 GPUs for 1M iterations with batch size 256.
233
+ Locally, on an NVIDIA A100/A10 GPU, each image-conditioned diffusion generation can be done in 10~20 seconds (time varies due to the adaptive-step ODE solver used in flow-mathcing.)
234
+ Upload an image of an object or click on one of the provided examples to see how the LN3Diff works.
235
+ The 3D viewer will render a .obj object exported from the triplane, where the mesh resolution and iso-surface can be set manually.
236
+ For best results run the demo locally and render locally - to do so, clone the [main repository](https://github.com/NIRVANALAN/LN3Diff).
237
+ """
238
+ )
239
+ with gr.Row(variant="panel"):
240
+ with gr.Column():
241
+ with gr.Row():
242
+ input_image = gr.Image(
243
+ label="Input Image",
244
+ image_mode="RGBA",
245
+ sources="upload",
246
+ type="pil",
247
+ elem_id="content_image",
248
+ )
249
+ processed_image = gr.Image(label="Processed Image", interactive=False)
250
+
251
+ # params
252
+ with gr.Row():
253
+ with gr.Column():
254
+ with gr.Row():
255
+ # with gr.Group():
256
+
257
+ unconditional_guidance_scale = gr.Number(
258
+ label="CFG-scale", value=4.0, interactive=True,
259
+ )
260
+ seed = gr.Number(
261
+ label="Seed", value=42, interactive=True,
262
+ )
263
+
264
+ num_steps = gr.Number(
265
+ label="ODE Sampling Steps", value=250, interactive=True,
266
+ )
267
+
268
+ # with gr.Column():
269
+ with gr.Row():
270
+ mesh_size = gr.Number(
271
+ label="Mesh Resolution", value=192, interactive=True,
272
+ )
273
+
274
+ mesh_thres = gr.Number(
275
+ label="Mesh Iso-surface", value=10, interactive=True,
276
+ )
277
+
278
+ with gr.Row():
279
+ with gr.Group():
280
+ preprocess_background = gr.Checkbox(
281
+ label="Remove Background", value=True
282
+ )
283
+ with gr.Row():
284
+ submit = gr.Button("Generate", elem_id="generate", variant="primary")
285
+
286
+ with gr.Row(variant="panel"):
287
+ gr.Examples(
288
+ examples=[
289
+ str(path) for path in sorted(Path('./assets/i23d_examples').glob('**/*.png'))
290
+ ],
291
+ inputs=[input_image],
292
+ cache_examples=False,
293
+ label="Examples",
294
+ examples_per_page=20,
295
+ )
296
+
297
+ with gr.Column():
298
+ with gr.Row():
299
+ with gr.Tab("Reconstruction"):
300
+ with gr.Column():
301
+ output_video = gr.Video(value=None, width=384, label="Rendered Video", autoplay=True, loop=True)
302
+ output_model = gr.Model3D(
303
+ height=384,
304
+ clear_color=(1,1,1,1),
305
+ label="Output Model",
306
+ interactive=False
307
+ )
308
+
309
+ gr.Markdown(
310
+ """
311
+ ## Comments:
312
+ 1. The sampling time varies since ODE-based sampling method (dopri5 by default) has adaptive internal step, and reducing sampling steps may not reduce the overal sampling time. Sampling steps=250 is the emperical value that works well in most cases.
313
+ 2. The 3D viewer shows a colored .glb mesh extracted from volumetric tri-plane, and may differ slightly with the volume rendering result.
314
+ 3. If you find your result unsatisfying, tune the CFG scale and change the random seed. Usually slightly increase the CFG value can lead to better performance.
315
+ 3. Known limitations include:
316
+ - Texture details missing: since our VAE is trained on 192x192 resolution due the the resource constraints, the texture details generated by the final 3D-LDM may be blurry. We will keep improving the performance in the future.
317
+ 4. Regarding reconstruction performance, our model is slightly inferior to state-of-the-art multi-view LRM-based method (e.g. InstantMesh), but offers much better diversity, flexibility and editing potential due to the intrinsic nature of diffusion model.
318
+
319
+ ## How does it work?
320
+
321
+ LN3Diff is a feedforward 3D Latent Diffusion Model that supports direct 3D asset generation via diffusion sampling.
322
+ Compared to SDS-based ([DreamFusion](https://dreamfusion3d.github.io/)), mulit-view generation-based ([MVDream](https://arxiv.org/abs/2308.16512), [Zero123++](https://github.com/SUDO-AI-3D/zero123plus), [Instant3D](https://instant-3d.github.io/)) and feedforward 3D reconstruction-based ([LRM](https://yiconghong.me/LRM/), [InstantMesh](https://github.com/TencentARC/InstantMesh), [LGM](https://github.com/3DTopia/LGM)),
323
+ LN3Diff supports feedforward 3D generation with a unified framework.
324
+ Like 2D/Video AIGC pipeline, LN3Diff first trains a 3D-VAE and then conduct LDM training (text/image conditioned) on the learned latent space. Some related methods from the industry ([Shape-E](https://github.com/openai/shap-e), [CLAY](https://github.com/CLAY-3D/OpenCLAY), [Meta 3D Gen](https://arxiv.org/abs/2303.05371)) also follow the same paradigm.
325
+ Though currently the performance of the origin 3D LDM's works are overall inferior to reconstruction-based methods, we believe the proposed method has much potential and scales better with more data and compute resources, and may yield better 3D editing performance due to its compatability with diffusion model.
326
+ For more results see the [project page](https://szymanowiczs.github.io/splatter-image) and the [ECCV article](https://arxiv.org/pdf/2403.12019).
327
+ """
328
+ )
329
+
330
+ submit.click(fn=check_input_image, inputs=[input_image]).success(
331
+ fn=preprocess,
332
+ inputs=[input_image, preprocess_background],
333
+ outputs=[processed_image],
334
+ ).success(
335
+ # fn=reconstruct_and_export,
336
+ # inputs=[processed_image],
337
+ # outputs=[output_model, output_video],
338
+ fn=reconstruct_and_export,
339
+ inputs=[processed_image, num_steps, seed, mesh_size, mesh_thres, unconditional_guidance_scale],
340
+ outputs=[output_video, output_model],
341
+ )
342
+
343
+ demo.queue(max_size=1)
344
+ demo.launch(share=True)
345
+
346
+ # training_loop_class.eval_i23d_and_export(
347
+ # # prompt=args.prompt,
348
+ # # prompt=prompt,
349
+ # unconditional_guidance_scale=args.
350
+ # unconditional_guidance_scale,
351
+ # # unconditional_guidance_scale=unconditional_guidance_scale,
352
+ # # use_ddim=args.use_ddim,
353
+ # # save_img=args.save_img,
354
+ # # use_train_trajectory=args.use_train_trajectory,
355
+ # camera=camera,
356
+ # num_instances=args.num_instances,
357
+ # num_samples=args.num_samples,
358
+ # export_mesh=True,
359
+ # idx_to_render=seeds,
360
+ # )
361
+
362
+
363
+
364
+
365
+ def create_argparser():
366
+ defaults = dict(
367
+ image_size_encoder=224,
368
+ triplane_scaling_divider=1.0, # divide by this value
369
+ diffusion_input_size=-1,
370
+ trainer_name='adm',
371
+ use_amp=False,
372
+ # triplane_scaling_divider=1.0, # divide by this value
373
+
374
+ # * sampling flags
375
+ clip_denoised=False,
376
+ num_samples=10,
377
+ num_instances=10, # for i23d, loop different condition
378
+ use_ddim=False,
379
+ ddpm_model_path="",
380
+ cldm_model_path="",
381
+ rec_model_path="",
382
+
383
+ # * eval logging flags
384
+ logdir="/mnt/lustre/yslan/logs/nips23/",
385
+ data_dir="",
386
+ eval_data_dir="",
387
+ eval_batch_size=1,
388
+ num_workers=1,
389
+
390
+ # * training flags for loading TrainingLoop class
391
+ overfitting=False,
392
+ image_size=128,
393
+ iterations=150000,
394
+ schedule_sampler="uniform",
395
+ anneal_lr=False,
396
+ lr=5e-5,
397
+ weight_decay=0.0,
398
+ lr_anneal_steps=0,
399
+ batch_size=1,
400
+ microbatch=-1, # -1 disables microbatches
401
+ ema_rate="0.9999", # comma-separated list of EMA values
402
+ log_interval=50,
403
+ eval_interval=2500,
404
+ save_interval=10000,
405
+ resume_checkpoint="",
406
+ resume_cldm_checkpoint="",
407
+ resume_checkpoint_EG3D="",
408
+ use_fp16=False,
409
+ fp16_scale_growth=1e-3,
410
+ load_submodule_name='', # for loading pretrained auto_encoder model
411
+ ignore_resume_opt=False,
412
+ freeze_ae=False,
413
+ denoised_ae=True,
414
+ # inference prompt
415
+ prompt="a red chair",
416
+ interval=1,
417
+ save_img=False,
418
+ use_train_trajectory=
419
+ False, # use train trajectory to sample images for fid calculation
420
+ unconditional_guidance_scale=1.0,
421
+ use_eos_feature=False,
422
+ export_mesh=False,
423
+ cond_key='caption',
424
+ allow_tf32=True,
425
+ )
426
+
427
+ defaults.update(model_and_diffusion_defaults())
428
+ defaults.update(encoder_and_nsr_defaults()) # type: ignore
429
+ defaults.update(loss_defaults())
430
+ defaults.update(continuous_diffusion_defaults())
431
+ defaults.update(control_net_defaults())
432
+ defaults.update(dataset_defaults())
433
+
434
+ parser = argparse.ArgumentParser()
435
+ add_dict_to_argparser(parser, defaults)
436
+
437
+ parse_transport_args(parser)
438
+
439
+ return parser
440
+
441
+
442
+ if __name__ == "__main__":
443
+
444
+ # os.environ["TORCH_CPP_LOG_LEVEL"] = "INFO"
445
+ # os.environ["NCCL_DEBUG"] = "INFO"
446
+
447
+ os.environ[
448
+ "TORCH_DISTRIBUTED_DEBUG"] = "DETAIL" # set to DETAIL for runtime logging.
449
+
450
+ args = create_argparser().parse_args()
451
 
452
+ args.local_rank = int(os.environ["LOCAL_RANK"])
453
+ args.gpus = th.cuda.device_count()
454
 
455
+ args.rendering_kwargs = rendering_options_defaults(args)
 
 
 
456
 
457
+ main(args)
 
app_demo.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import spaces
3
+ import torch
4
+
5
+ zero = torch.Tensor([0]).cuda()
6
+ print(zero.device) # <-- 'cpu' 🤔
7
+
8
+ @spaces.GPU
9
+ def greet(n):
10
+ print(zero.device) # <-- 'cuda:0' 🤗
11
+ return f"Hello {zero + n} Tensor"
12
+
13
+ demo = gr.Interface(fn=greet, inputs=gr.Number(), outputs=gr.Text())
14
+ demo.launch()
gradio_app.py DELETED
@@ -1,457 +0,0 @@
1
- import torch
2
- import torchvision
3
- from torchvision import transforms
4
- import numpy as np
5
-
6
- import os
7
- from omegaconf import OmegaConf
8
- from PIL import Image
9
-
10
- import gradio as gr
11
-
12
- import rembg
13
-
14
- import spaces
15
-
16
- from huggingface_hub import hf_hub_download
17
-
18
-
19
- """
20
- Generate a large batch of image samples from a model and save them as a large
21
- numpy array. This can be used to produce samples for FID evaluation.
22
- """
23
-
24
- import argparse
25
- import json
26
- import sys
27
- import os
28
-
29
- sys.path.append('.')
30
-
31
- from pdb import set_trace as st
32
- import imageio
33
- import numpy as np
34
- import torch as th
35
- import torch.distributed as dist
36
-
37
- from guided_diffusion import dist_util, logger
38
- from guided_diffusion.script_util import (
39
- NUM_CLASSES,
40
- model_and_diffusion_defaults,
41
- create_model_and_diffusion,
42
- add_dict_to_argparser,
43
- args_to_dict,
44
- continuous_diffusion_defaults,
45
- control_net_defaults,
46
- )
47
-
48
- th.backends.cuda.matmul.allow_tf32 = True
49
- th.backends.cudnn.allow_tf32 = True
50
- th.backends.cudnn.enabled = True
51
-
52
- from pathlib import Path
53
-
54
- from tqdm import tqdm, trange
55
- import dnnlib
56
- from nsr.train_util_diffusion import TrainLoop3DDiffusion as TrainLoop
57
- from guided_diffusion.continuous_diffusion import make_diffusion as make_sde_diffusion
58
- import nsr
59
- import nsr.lsgm
60
- from nsr.script_util import create_3DAE_model, encoder_and_nsr_defaults, loss_defaults, AE_with_Diffusion, rendering_options_defaults, eg3d_options_default, dataset_defaults
61
-
62
- from datasets.shapenet import load_eval_data
63
- from torch.utils.data import Subset
64
- from datasets.eg3d_dataset import init_dataset_kwargs
65
-
66
- from transport.train_utils import parse_transport_args
67
-
68
- from utils.infer_utils import remove_background, resize_foreground
69
-
70
- SEED = 0
71
-
72
- def resize_to_224(img):
73
- img = transforms.functional.resize(img, 224,
74
- interpolation=transforms.InterpolationMode.LANCZOS)
75
- return img
76
-
77
-
78
- def set_white_background(image):
79
- image = np.array(image).astype(np.float32) / 255.0
80
- mask = image[:, :, 3:4]
81
- image = image[:, :, :3] * mask + (1 - mask)
82
- image = Image.fromarray((image * 255.0).astype(np.uint8))
83
- return image
84
-
85
-
86
- def check_input_image(input_image):
87
- if input_image is None:
88
- raise gr.Error("No image uploaded!")
89
-
90
-
91
-
92
- def main(args):
93
-
94
- # args.rendering_kwargs = rendering_options_defaults(args)
95
-
96
- dist_util.setup_dist(args)
97
- logger.configure(dir=args.logdir)
98
-
99
- th.cuda.empty_cache()
100
-
101
- th.cuda.manual_seed_all(SEED)
102
- np.random.seed(SEED)
103
-
104
- # * set denoise model args
105
- logger.log("creating model and diffusion...")
106
- args.img_size = [args.image_size_encoder]
107
- # ! no longer required for LDM
108
- # args.denoise_in_channels = args.out_chans
109
- # args.denoise_out_channels = args.out_chans
110
- args.image_size = args.image_size_encoder # 224, follow the triplane size
111
-
112
- denoise_model, diffusion = create_model_and_diffusion(
113
- **args_to_dict(args,
114
- model_and_diffusion_defaults().keys()))
115
-
116
- # if 'cldm' in args.trainer_name:
117
- # assert isinstance(denoise_model, tuple)
118
- # denoise_model, controlNet = denoise_model
119
-
120
- # controlNet.to(dist_util.dev())
121
- # controlNet.train()
122
- # else:
123
- # controlNet = None
124
-
125
- opts = eg3d_options_default()
126
- if args.sr_training:
127
- args.sr_kwargs = dnnlib.EasyDict(
128
- channel_base=opts.cbase,
129
- channel_max=opts.cmax,
130
- fused_modconv_default='inference_only',
131
- use_noise=True
132
- ) # ! close noise injection? since noise_mode='none' in eg3d
133
-
134
- # denoise_model.load_state_dict(
135
- # dist_util.load_state_dict(args.ddpm_model_path, map_location="cpu"))
136
- denoise_model.to(dist_util.dev())
137
- if args.use_fp16:
138
- denoise_model.convert_to_fp16()
139
- denoise_model.eval()
140
-
141
- # * auto-encoder reconstruction model
142
- logger.log("creating 3DAE...")
143
- auto_encoder = create_3DAE_model(
144
- **args_to_dict(args,
145
- encoder_and_nsr_defaults().keys()))
146
-
147
- auto_encoder.to(dist_util.dev())
148
- auto_encoder.eval()
149
-
150
- # TODO, how to set the scale?
151
- logger.log("create dataset")
152
-
153
- if args.objv_dataset:
154
- from datasets.g_buffer_objaverse import load_data, load_eval_data, load_memory_data, load_wds_data
155
- else: # shapenet
156
- from datasets.shapenet import load_data, load_eval_data, load_memory_data
157
-
158
- # load data if i23d
159
- if args.i23d:
160
- data = load_eval_data(
161
- file_path=args.eval_data_dir,
162
- batch_size=args.eval_batch_size,
163
- reso=args.image_size,
164
- reso_encoder=args.image_size_encoder, # 224 -> 128
165
- num_workers=args.num_workers,
166
- load_depth=True, # for evaluation
167
- preprocess=auto_encoder.preprocess,
168
- **args_to_dict(args,
169
- dataset_defaults().keys()))
170
- else:
171
- data = None # t23d sampling, only caption required
172
-
173
-
174
- TrainLoop = {
175
- 'sgm_legacy':
176
- nsr.lsgm.sgm_DiffusionEngine.DiffusionEngineLSGM,
177
- 'flow_matching':
178
- nsr.lsgm.flow_matching_trainer.FlowMatchingEngine,
179
- }[args.trainer_name]
180
-
181
- # continuous
182
- sde_diffusion = None
183
-
184
- auto_encoder.decoder.rendering_kwargs = args.rendering_kwargs
185
-
186
- training_loop_class = TrainLoop(rec_model=auto_encoder,
187
- denoise_model=denoise_model,
188
- control_model=None, # to remove
189
- diffusion=diffusion,
190
- sde_diffusion=sde_diffusion,
191
- loss_class=None,
192
- data=data,
193
- eval_data=None,
194
- **vars(args))
195
-
196
- @spaces.GPU()
197
- def reconstruct_and_export(*args, **kwargs):
198
- return training_loop_class.eval_i23d_and_export(*args, **kwargs)
199
-
200
-
201
- css = """
202
- h1 {
203
- text-align: center;
204
- display:block;
205
- }
206
- """
207
-
208
-
209
- def preprocess(input_image, preprocess_background=True, foreground_ratio=0.85):
210
- if preprocess_background:
211
- rembg_session = rembg.new_session()
212
- image = input_image.convert("RGB")
213
- image = remove_background(image, rembg_session)
214
- image = resize_foreground(image, foreground_ratio)
215
- image = set_white_background(image)
216
- else:
217
- image = input_image
218
- if image.mode == "RGBA":
219
- image = set_white_background(image)
220
- image = resize_to_224(image)
221
- return image
222
-
223
-
224
- with gr.Blocks(css=css) as demo:
225
- gr.Markdown(
226
- """
227
- # LN3Diff (Scalable Latent Neural Fields Diffusion for Speedy 3D Generation)
228
-
229
- **LN3Diff (ECCV 2024)** [[code](https://github.com/NIRVANALAN/LN3Diff), [project page](https://nirvanalan.github.io/projects/ln3diff/)] is a scalable 3D latent diffusion model that supports speedy 3D assets generation.
230
- It first trains a 3D VAE on **Objaverse**, which compress each 3D asset into a compact 3D-aware latent. After that, a image/text-conditioned diffusion model is trained following LDM paradigm.
231
- The model used in the demo adopts DiT-L/2 architecture and flow-matching framework, and supports single-image condition.
232
- It is trained on 8 A100 GPUs for 1M iterations with batch size 256.
233
- Locally, on an NVIDIA A100/A10 GPU, each image-conditioned diffusion generation can be done in 10~20 seconds (time varies due to the adaptive-step ODE solver used in flow-mathcing.)
234
- Upload an image of an object or click on one of the provided examples to see how the LN3Diff works.
235
- The 3D viewer will render a .obj object exported from the triplane, where the mesh resolution and iso-surface can be set manually.
236
- For best results run the demo locally and render locally - to do so, clone the [main repository](https://github.com/NIRVANALAN/LN3Diff).
237
- """
238
- )
239
- with gr.Row(variant="panel"):
240
- with gr.Column():
241
- with gr.Row():
242
- input_image = gr.Image(
243
- label="Input Image",
244
- image_mode="RGBA",
245
- sources="upload",
246
- type="pil",
247
- elem_id="content_image",
248
- )
249
- processed_image = gr.Image(label="Processed Image", interactive=False)
250
-
251
- # params
252
- with gr.Row():
253
- with gr.Column():
254
- with gr.Row():
255
- # with gr.Group():
256
-
257
- unconditional_guidance_scale = gr.Number(
258
- label="CFG-scale", value=4.0, interactive=True,
259
- )
260
- seed = gr.Number(
261
- label="Seed", value=42, interactive=True,
262
- )
263
-
264
- num_steps = gr.Number(
265
- label="ODE Sampling Steps", value=250, interactive=True,
266
- )
267
-
268
- # with gr.Column():
269
- with gr.Row():
270
- mesh_size = gr.Number(
271
- label="Mesh Resolution", value=192, interactive=True,
272
- )
273
-
274
- mesh_thres = gr.Number(
275
- label="Mesh Iso-surface", value=10, interactive=True,
276
- )
277
-
278
- with gr.Row():
279
- with gr.Group():
280
- preprocess_background = gr.Checkbox(
281
- label="Remove Background", value=True
282
- )
283
- with gr.Row():
284
- submit = gr.Button("Generate", elem_id="generate", variant="primary")
285
-
286
- with gr.Row(variant="panel"):
287
- gr.Examples(
288
- examples=[
289
- str(path) for path in sorted(Path('./assets/i23d_examples').glob('**/*.png'))
290
- ],
291
- inputs=[input_image],
292
- cache_examples=False,
293
- label="Examples",
294
- examples_per_page=20,
295
- )
296
-
297
- with gr.Column():
298
- with gr.Row():
299
- with gr.Tab("Reconstruction"):
300
- with gr.Column():
301
- output_video = gr.Video(value=None, width=384, label="Rendered Video", autoplay=True, loop=True)
302
- output_model = gr.Model3D(
303
- height=384,
304
- clear_color=(1,1,1,1),
305
- label="Output Model",
306
- interactive=False
307
- )
308
-
309
- gr.Markdown(
310
- """
311
- ## Comments:
312
- 1. The sampling time varies since ODE-based sampling method (dopri5 by default) has adaptive internal step, and reducing sampling steps may not reduce the overal sampling time. Sampling steps=250 is the emperical value that works well in most cases.
313
- 2. The 3D viewer shows a colored .glb mesh extracted from volumetric tri-plane, and may differ slightly with the volume rendering result.
314
- 3. If you find your result unsatisfying, tune the CFG scale and change the random seed. Usually slightly increase the CFG value can lead to better performance.
315
- 3. Known limitations include:
316
- - Texture details missing: since our VAE is trained on 192x192 resolution due the the resource constraints, the texture details generated by the final 3D-LDM may be blurry. We will keep improving the performance in the future.
317
- 4. Regarding reconstruction performance, our model is slightly inferior to state-of-the-art multi-view LRM-based method (e.g. InstantMesh), but offers much better diversity, flexibility and editing potential due to the intrinsic nature of diffusion model.
318
-
319
- ## How does it work?
320
-
321
- LN3Diff is a feedforward 3D Latent Diffusion Model that supports direct 3D asset generation via diffusion sampling.
322
- Compared to SDS-based ([DreamFusion](https://dreamfusion3d.github.io/)), mulit-view generation-based ([MVDream](https://arxiv.org/abs/2308.16512), [Zero123++](https://github.com/SUDO-AI-3D/zero123plus), [Instant3D](https://instant-3d.github.io/)) and feedforward 3D reconstruction-based ([LRM](https://yiconghong.me/LRM/), [InstantMesh](https://github.com/TencentARC/InstantMesh), [LGM](https://github.com/3DTopia/LGM)),
323
- LN3Diff supports feedforward 3D generation with a unified framework.
324
- Like 2D/Video AIGC pipeline, LN3Diff first trains a 3D-VAE and then conduct LDM training (text/image conditioned) on the learned latent space. Some related methods from the industry ([Shape-E](https://github.com/openai/shap-e), [CLAY](https://github.com/CLAY-3D/OpenCLAY), [Meta 3D Gen](https://arxiv.org/abs/2303.05371)) also follow the same paradigm.
325
- Though currently the performance of the origin 3D LDM's works are overall inferior to reconstruction-based methods, we believe the proposed method has much potential and scales better with more data and compute resources, and may yield better 3D editing performance due to its compatability with diffusion model.
326
- For more results see the [project page](https://szymanowiczs.github.io/splatter-image) and the [ECCV article](https://arxiv.org/pdf/2403.12019).
327
- """
328
- )
329
-
330
- submit.click(fn=check_input_image, inputs=[input_image]).success(
331
- fn=preprocess,
332
- inputs=[input_image, preprocess_background],
333
- outputs=[processed_image],
334
- ).success(
335
- # fn=reconstruct_and_export,
336
- # inputs=[processed_image],
337
- # outputs=[output_model, output_video],
338
- fn=reconstruct_and_export,
339
- inputs=[processed_image, num_steps, seed, mesh_size, mesh_thres, unconditional_guidance_scale],
340
- outputs=[output_video, output_model],
341
- )
342
-
343
- demo.queue(max_size=1)
344
- demo.launch(share=True)
345
-
346
- # training_loop_class.eval_i23d_and_export(
347
- # # prompt=args.prompt,
348
- # # prompt=prompt,
349
- # unconditional_guidance_scale=args.
350
- # unconditional_guidance_scale,
351
- # # unconditional_guidance_scale=unconditional_guidance_scale,
352
- # # use_ddim=args.use_ddim,
353
- # # save_img=args.save_img,
354
- # # use_train_trajectory=args.use_train_trajectory,
355
- # camera=camera,
356
- # num_instances=args.num_instances,
357
- # num_samples=args.num_samples,
358
- # export_mesh=True,
359
- # idx_to_render=seeds,
360
- # )
361
-
362
-
363
-
364
-
365
- def create_argparser():
366
- defaults = dict(
367
- image_size_encoder=224,
368
- triplane_scaling_divider=1.0, # divide by this value
369
- diffusion_input_size=-1,
370
- trainer_name='adm',
371
- use_amp=False,
372
- # triplane_scaling_divider=1.0, # divide by this value
373
-
374
- # * sampling flags
375
- clip_denoised=False,
376
- num_samples=10,
377
- num_instances=10, # for i23d, loop different condition
378
- use_ddim=False,
379
- ddpm_model_path="",
380
- cldm_model_path="",
381
- rec_model_path="",
382
-
383
- # * eval logging flags
384
- logdir="/mnt/lustre/yslan/logs/nips23/",
385
- data_dir="",
386
- eval_data_dir="",
387
- eval_batch_size=1,
388
- num_workers=1,
389
-
390
- # * training flags for loading TrainingLoop class
391
- overfitting=False,
392
- image_size=128,
393
- iterations=150000,
394
- schedule_sampler="uniform",
395
- anneal_lr=False,
396
- lr=5e-5,
397
- weight_decay=0.0,
398
- lr_anneal_steps=0,
399
- batch_size=1,
400
- microbatch=-1, # -1 disables microbatches
401
- ema_rate="0.9999", # comma-separated list of EMA values
402
- log_interval=50,
403
- eval_interval=2500,
404
- save_interval=10000,
405
- resume_checkpoint="",
406
- resume_cldm_checkpoint="",
407
- resume_checkpoint_EG3D="",
408
- use_fp16=False,
409
- fp16_scale_growth=1e-3,
410
- load_submodule_name='', # for loading pretrained auto_encoder model
411
- ignore_resume_opt=False,
412
- freeze_ae=False,
413
- denoised_ae=True,
414
- # inference prompt
415
- prompt="a red chair",
416
- interval=1,
417
- save_img=False,
418
- use_train_trajectory=
419
- False, # use train trajectory to sample images for fid calculation
420
- unconditional_guidance_scale=1.0,
421
- use_eos_feature=False,
422
- export_mesh=False,
423
- cond_key='caption',
424
- allow_tf32=True,
425
- )
426
-
427
- defaults.update(model_and_diffusion_defaults())
428
- defaults.update(encoder_and_nsr_defaults()) # type: ignore
429
- defaults.update(loss_defaults())
430
- defaults.update(continuous_diffusion_defaults())
431
- defaults.update(control_net_defaults())
432
- defaults.update(dataset_defaults())
433
-
434
- parser = argparse.ArgumentParser()
435
- add_dict_to_argparser(parser, defaults)
436
-
437
- parse_transport_args(parser)
438
-
439
- return parser
440
-
441
-
442
- if __name__ == "__main__":
443
-
444
- # os.environ["TORCH_CPP_LOG_LEVEL"] = "INFO"
445
- # os.environ["NCCL_DEBUG"] = "INFO"
446
-
447
- os.environ[
448
- "TORCH_DISTRIBUTED_DEBUG"] = "DETAIL" # set to DETAIL for runtime logging.
449
-
450
- args = create_argparser().parse_args()
451
-
452
- args.local_rank = int(os.environ["LOCAL_RANK"])
453
- args.gpus = th.cuda.device_count()
454
-
455
- args.rendering_kwargs = rendering_options_defaults(args)
456
-
457
- main(args)