add gradio example
Browse files- gradio_app.py +237 -0
- main.py +1 -1
- nerf/utils.py +24 -14
- readme.md +6 -0
gradio_app.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import argparse
|
| 3 |
+
|
| 4 |
+
from nerf.provider import NeRFDataset
|
| 5 |
+
from nerf.utils import *
|
| 6 |
+
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import gc
|
| 9 |
+
|
| 10 |
+
print(f'[INFO] loading options..')
|
| 11 |
+
|
| 12 |
+
# fake config object, this should not be used in CMD, only allow change from gradio UI.
|
| 13 |
+
parser = argparse.ArgumentParser()
|
| 14 |
+
parser.add_argument('--text', default=None, help="text prompt")
|
| 15 |
+
# parser.add_argument('-O', action='store_true', help="equals --fp16 --cuda_ray --dir_text")
|
| 16 |
+
# parser.add_argument('-O2', action='store_true', help="equals --fp16 --dir_text")
|
| 17 |
+
parser.add_argument('--test', action='store_true', help="test mode")
|
| 18 |
+
parser.add_argument('--save_mesh', action='store_true', help="export an obj mesh with texture")
|
| 19 |
+
parser.add_argument('--eval_interval', type=int, default=10, help="evaluate on the valid set every interval epochs")
|
| 20 |
+
parser.add_argument('--workspace', type=str, default='trial_gradio')
|
| 21 |
+
parser.add_argument('--guidance', type=str, default='stable-diffusion', help='choose from [stable-diffusion, clip]')
|
| 22 |
+
parser.add_argument('--seed', type=int, default=0)
|
| 23 |
+
|
| 24 |
+
### training options
|
| 25 |
+
parser.add_argument('--iters', type=int, default=10000, help="training iters")
|
| 26 |
+
parser.add_argument('--lr', type=float, default=1e-3, help="initial learning rate")
|
| 27 |
+
parser.add_argument('--ckpt', type=str, default='latest')
|
| 28 |
+
parser.add_argument('--cuda_ray', action='store_true', help="use CUDA raymarching instead of pytorch")
|
| 29 |
+
parser.add_argument('--max_steps', type=int, default=1024, help="max num steps sampled per ray (only valid when using --cuda_ray)")
|
| 30 |
+
parser.add_argument('--num_steps', type=int, default=64, help="num steps sampled per ray (only valid when not using --cuda_ray)")
|
| 31 |
+
parser.add_argument('--upsample_steps', type=int, default=64, help="num steps up-sampled per ray (only valid when not using --cuda_ray)")
|
| 32 |
+
parser.add_argument('--update_extra_interval', type=int, default=16, help="iter interval to update extra status (only valid when using --cuda_ray)")
|
| 33 |
+
parser.add_argument('--max_ray_batch', type=int, default=4096, help="batch size of rays at inference to avoid OOM (only valid when not using --cuda_ray)")
|
| 34 |
+
parser.add_argument('--albedo_iters', type=int, default=1000, help="training iters that only use albedo shading")
|
| 35 |
+
# model options
|
| 36 |
+
parser.add_argument('--bg_radius', type=float, default=1.4, help="if positive, use a background model at sphere(bg_radius)")
|
| 37 |
+
parser.add_argument('--density_thresh', type=float, default=10, help="threshold for density grid to be occupied")
|
| 38 |
+
# network backbone
|
| 39 |
+
parser.add_argument('--fp16', action='store_true', help="use amp mixed precision training")
|
| 40 |
+
parser.add_argument('--backbone', type=str, default='grid', help="nerf backbone, choose from [grid, tcnn, vanilla]")
|
| 41 |
+
# rendering resolution in training, decrease this if CUDA OOM.
|
| 42 |
+
parser.add_argument('--w', type=int, default=64, help="render width for NeRF in training")
|
| 43 |
+
parser.add_argument('--h', type=int, default=64, help="render height for NeRF in training")
|
| 44 |
+
parser.add_argument('--jitter_pose', action='store_true', help="add jitters to the randomly sampled camera poses")
|
| 45 |
+
|
| 46 |
+
### dataset options
|
| 47 |
+
parser.add_argument('--bound', type=float, default=1, help="assume the scene is bounded in box(-bound, bound)")
|
| 48 |
+
parser.add_argument('--dt_gamma', type=float, default=0, help="dt_gamma (>=0) for adaptive ray marching. set to 0 to disable, >0 to accelerate rendering (but usually with worse quality)")
|
| 49 |
+
parser.add_argument('--min_near', type=float, default=0.1, help="minimum near distance for camera")
|
| 50 |
+
parser.add_argument('--radius_range', type=float, nargs='*', default=[1.0, 1.5], help="training camera radius range")
|
| 51 |
+
parser.add_argument('--fovy_range', type=float, nargs='*', default=[40, 70], help="training camera fovy range")
|
| 52 |
+
parser.add_argument('--dir_text', action='store_true', help="direction-encode the text prompt, by appending front/side/back/overhead view")
|
| 53 |
+
parser.add_argument('--angle_overhead', type=float, default=30, help="[0, angle_overhead] is the overhead region")
|
| 54 |
+
parser.add_argument('--angle_front', type=float, default=60, help="[0, angle_front] is the front region, [180, 180+angle_front] the back region, otherwise the side region.")
|
| 55 |
+
|
| 56 |
+
parser.add_argument('--lambda_entropy', type=float, default=1e-4, help="loss scale for alpha entropy")
|
| 57 |
+
parser.add_argument('--lambda_opacity', type=float, default=0, help="loss scale for alpha value")
|
| 58 |
+
parser.add_argument('--lambda_orient', type=float, default=1e-2, help="loss scale for orientation")
|
| 59 |
+
|
| 60 |
+
### GUI options
|
| 61 |
+
parser.add_argument('--gui', action='store_true', help="start a GUI")
|
| 62 |
+
parser.add_argument('--W', type=int, default=800, help="GUI width")
|
| 63 |
+
parser.add_argument('--H', type=int, default=800, help="GUI height")
|
| 64 |
+
parser.add_argument('--radius', type=float, default=3, help="default GUI camera radius from center")
|
| 65 |
+
parser.add_argument('--fovy', type=float, default=60, help="default GUI camera fovy")
|
| 66 |
+
parser.add_argument('--light_theta', type=float, default=60, help="default GUI light direction in [0, 180], corresponding to elevation [90, -90]")
|
| 67 |
+
parser.add_argument('--light_phi', type=float, default=0, help="default GUI light direction in [0, 360), azimuth")
|
| 68 |
+
parser.add_argument('--max_spp', type=int, default=1, help="GUI rendering max sample per pixel")
|
| 69 |
+
|
| 70 |
+
opt = parser.parse_args()
|
| 71 |
+
|
| 72 |
+
# default to use -O !!!
|
| 73 |
+
opt.fp16 = True
|
| 74 |
+
opt.dir_text = True
|
| 75 |
+
opt.cuda_ray = True
|
| 76 |
+
# opt.lambda_entropy = 1e-4
|
| 77 |
+
# opt.lambda_opacity = 0
|
| 78 |
+
|
| 79 |
+
if opt.backbone == 'vanilla':
|
| 80 |
+
from nerf.network import NeRFNetwork
|
| 81 |
+
elif opt.backbone == 'tcnn':
|
| 82 |
+
from nerf.network_tcnn import NeRFNetwork
|
| 83 |
+
elif opt.backbone == 'grid':
|
| 84 |
+
from nerf.network_grid import NeRFNetwork
|
| 85 |
+
else:
|
| 86 |
+
raise NotImplementedError(f'--backbone {opt.backbone} is not implemented!')
|
| 87 |
+
|
| 88 |
+
print(opt)
|
| 89 |
+
|
| 90 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 91 |
+
|
| 92 |
+
print(f'[INFO] loading models..')
|
| 93 |
+
|
| 94 |
+
if opt.guidance == 'stable-diffusion':
|
| 95 |
+
from nerf.sd import StableDiffusion
|
| 96 |
+
guidance = StableDiffusion(device)
|
| 97 |
+
elif opt.guidance == 'clip':
|
| 98 |
+
from nerf.clip import CLIP
|
| 99 |
+
guidance = CLIP(device)
|
| 100 |
+
else:
|
| 101 |
+
raise NotImplementedError(f'--guidance {opt.guidance} is not implemented.')
|
| 102 |
+
|
| 103 |
+
train_loader = NeRFDataset(opt, device=device, type='train', H=opt.h, W=opt.w, size=100).dataloader()
|
| 104 |
+
valid_loader = NeRFDataset(opt, device=device, type='val', H=opt.H, W=opt.W, size=5).dataloader()
|
| 105 |
+
test_loader = NeRFDataset(opt, device=device, type='test', H=opt.H, W=opt.W, size=100).dataloader()
|
| 106 |
+
|
| 107 |
+
print(f'[INFO] everything loaded!')
|
| 108 |
+
|
| 109 |
+
trainer = None
|
| 110 |
+
model = None
|
| 111 |
+
|
| 112 |
+
def reset_params(m):
|
| 113 |
+
|
| 114 |
+
@torch.no_grad()
|
| 115 |
+
def _reset(m: nn.Module):
|
| 116 |
+
reset_parameters = getattr(m, "reset_parameters", None)
|
| 117 |
+
if callable(reset_parameters):
|
| 118 |
+
m.reset_parameters()
|
| 119 |
+
|
| 120 |
+
model.apply(fn=_reset)
|
| 121 |
+
|
| 122 |
+
# define UI
|
| 123 |
+
|
| 124 |
+
with gr.Blocks(css=".gradio-container {max-width: 512px;}") as demo:
|
| 125 |
+
|
| 126 |
+
# title
|
| 127 |
+
gr.Markdown('[Stable-DreamFusion](https://github.com/ashawkey/stable-dreamfusion) Text-to-3D Example')
|
| 128 |
+
|
| 129 |
+
# inputs
|
| 130 |
+
prompt = gr.Textbox(label="Prompt", max_lines=1, value="a DSLR photo of a koi fish")
|
| 131 |
+
iters = gr.Slider(label="Iters", minimum=1000, maximum=20000, value=5000, step=100)
|
| 132 |
+
seed = gr.Slider(label="Seed", minimum=0, maximum=2147483647, step=1, randomize=True)
|
| 133 |
+
button = gr.Button('Generate')
|
| 134 |
+
|
| 135 |
+
# outputs
|
| 136 |
+
image = gr.Image(label="image", visible=True)
|
| 137 |
+
video = gr.Video(label="video", visible=False)
|
| 138 |
+
logs = gr.Textbox(label="logging")
|
| 139 |
+
|
| 140 |
+
# gradio main func
|
| 141 |
+
def submit(text, iters, seed):
|
| 142 |
+
|
| 143 |
+
global trainer, model
|
| 144 |
+
|
| 145 |
+
# seed
|
| 146 |
+
opt.seed = seed
|
| 147 |
+
opt.text = text
|
| 148 |
+
opt.iters = iters
|
| 149 |
+
|
| 150 |
+
seed_everything(seed)
|
| 151 |
+
|
| 152 |
+
# clean up
|
| 153 |
+
if trainer is not None:
|
| 154 |
+
del model
|
| 155 |
+
del trainer
|
| 156 |
+
gc.collect()
|
| 157 |
+
torch.cuda.empty_cache()
|
| 158 |
+
print('[INFO] clean up!')
|
| 159 |
+
|
| 160 |
+
# simply reload everything...
|
| 161 |
+
model = NeRFNetwork(opt)
|
| 162 |
+
optimizer = lambda model: torch.optim.Adam(model.get_params(opt.lr), betas=(0.9, 0.99), eps=1e-15)
|
| 163 |
+
scheduler = lambda optimizer: optim.lr_scheduler.LambdaLR(optimizer, lambda iter: 0.1 ** min(iter / opt.iters, 1))
|
| 164 |
+
|
| 165 |
+
trainer = Trainer('df', opt, model, guidance, device=device, workspace=opt.workspace, optimizer=optimizer, ema_decay=0.95, fp16=opt.fp16, lr_scheduler=scheduler, use_checkpoint=opt.ckpt, eval_interval=opt.eval_interval, scheduler_update_every_step=True)
|
| 166 |
+
|
| 167 |
+
# train (every ep only contain 8 steps, so we can get some vis every ~10s)
|
| 168 |
+
STEPS = 8
|
| 169 |
+
max_epochs = np.ceil(opt.iters / STEPS).astype(np.int32)
|
| 170 |
+
|
| 171 |
+
# we have to get the explicit training loop out here to yield progressive results...
|
| 172 |
+
loader = iter(valid_loader)
|
| 173 |
+
|
| 174 |
+
start_t = time.time()
|
| 175 |
+
|
| 176 |
+
for epoch in range(max_epochs):
|
| 177 |
+
|
| 178 |
+
trainer.train_gui(train_loader, step=STEPS)
|
| 179 |
+
|
| 180 |
+
# manual test and get intermediate results
|
| 181 |
+
try:
|
| 182 |
+
data = next(loader)
|
| 183 |
+
except StopIteration:
|
| 184 |
+
loader = iter(valid_loader)
|
| 185 |
+
data = next(loader)
|
| 186 |
+
|
| 187 |
+
trainer.model.eval()
|
| 188 |
+
|
| 189 |
+
if trainer.ema is not None:
|
| 190 |
+
trainer.ema.store()
|
| 191 |
+
trainer.ema.copy_to()
|
| 192 |
+
|
| 193 |
+
with torch.no_grad():
|
| 194 |
+
with torch.cuda.amp.autocast(enabled=trainer.fp16):
|
| 195 |
+
preds, preds_depth = trainer.test_step(data, perturb=False)
|
| 196 |
+
|
| 197 |
+
if trainer.ema is not None:
|
| 198 |
+
trainer.ema.restore()
|
| 199 |
+
|
| 200 |
+
pred = preds[0].detach().cpu().numpy()
|
| 201 |
+
# pred_depth = preds_depth[0].detach().cpu().numpy()
|
| 202 |
+
|
| 203 |
+
pred = (pred * 255).astype(np.uint8)
|
| 204 |
+
|
| 205 |
+
yield {
|
| 206 |
+
image: gr.update(value=pred, visible=True),
|
| 207 |
+
video: gr.update(visible=False),
|
| 208 |
+
logs: f"training iters: {epoch * STEPS} / {iters}, lr: {trainer.optimizer.param_groups[0]['lr']:.6f}",
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
# test
|
| 213 |
+
trainer.test(test_loader)
|
| 214 |
+
|
| 215 |
+
results = glob.glob(os.path.join(opt.workspace, 'results', '*rgb*.mp4'))
|
| 216 |
+
assert results is not None, "cannot retrieve results!"
|
| 217 |
+
results.sort(key=lambda x: os.path.getmtime(x)) # sort by mtime
|
| 218 |
+
|
| 219 |
+
end_t = time.time()
|
| 220 |
+
|
| 221 |
+
yield {
|
| 222 |
+
image: gr.update(visible=False),
|
| 223 |
+
video: gr.update(value=results[-1], visible=True),
|
| 224 |
+
logs: f"Generation Finished in {(end_t - start_t)/ 60:.4f} minutes!",
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
button.click(
|
| 229 |
+
submit,
|
| 230 |
+
[prompt, iters, seed],
|
| 231 |
+
[image, video, logs]
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
# concurrency_count: only allow ONE running progress, else GPU will OOM.
|
| 235 |
+
demo.queue(concurrency_count=1)
|
| 236 |
+
|
| 237 |
+
demo.launch()
|
main.py
CHANGED
|
@@ -138,7 +138,7 @@ if __name__ == '__main__':
|
|
| 138 |
scheduler = lambda optimizer: optim.lr_scheduler.LambdaLR(optimizer, lambda iter: 0.1 ** min(iter / opt.iters, 1))
|
| 139 |
# scheduler = lambda optimizer: optim.lr_scheduler.OneCycleLR(optimizer, max_lr=opt.lr, total_steps=opt.iters, pct_start=0.1)
|
| 140 |
|
| 141 |
-
trainer = Trainer('df', opt, model, guidance, device=device, workspace=opt.workspace, optimizer=optimizer, ema_decay=
|
| 142 |
|
| 143 |
if opt.gui:
|
| 144 |
trainer.train_loader = train_loader # attach dataloader to trainer
|
|
|
|
| 138 |
scheduler = lambda optimizer: optim.lr_scheduler.LambdaLR(optimizer, lambda iter: 0.1 ** min(iter / opt.iters, 1))
|
| 139 |
# scheduler = lambda optimizer: optim.lr_scheduler.OneCycleLR(optimizer, max_lr=opt.lr, total_steps=opt.iters, pct_start=0.1)
|
| 140 |
|
| 141 |
+
trainer = Trainer('df', opt, model, guidance, device=device, workspace=opt.workspace, optimizer=optimizer, ema_decay=None, fp16=opt.fp16, lr_scheduler=scheduler, use_checkpoint=opt.ckpt, eval_interval=opt.eval_interval, scheduler_update_every_step=True)
|
| 142 |
|
| 143 |
if opt.gui:
|
| 144 |
trainer.train_loader = train_loader # attach dataloader to trainer
|
nerf/utils.py
CHANGED
|
@@ -195,9 +195,6 @@ class Trainer(object):
|
|
| 195 |
self.scheduler_update_every_step = scheduler_update_every_step
|
| 196 |
self.device = device if device is not None else torch.device(f'cuda:{local_rank}' if torch.cuda.is_available() else 'cpu')
|
| 197 |
self.console = Console()
|
| 198 |
-
|
| 199 |
-
# text prompt
|
| 200 |
-
ref_text = self.opt.text
|
| 201 |
|
| 202 |
model.to(self.device)
|
| 203 |
if self.world_size > 1:
|
|
@@ -208,20 +205,13 @@ class Trainer(object):
|
|
| 208 |
# guide model
|
| 209 |
self.guidance = guidance
|
| 210 |
|
|
|
|
| 211 |
if self.guidance is not None:
|
| 212 |
-
|
| 213 |
-
|
| 214 |
for p in self.guidance.parameters():
|
| 215 |
p.requires_grad = False
|
| 216 |
|
| 217 |
-
|
| 218 |
-
self.text_z = self.guidance.get_text_embeds([ref_text])
|
| 219 |
-
else:
|
| 220 |
-
self.text_z = []
|
| 221 |
-
for d in ['front', 'side', 'back', 'side', 'overhead', 'bottom']:
|
| 222 |
-
text = f"{ref_text}, {d} view"
|
| 223 |
-
text_z = self.guidance.get_text_embeds([text])
|
| 224 |
-
self.text_z.append(text_z)
|
| 225 |
|
| 226 |
else:
|
| 227 |
self.text_z = None
|
|
@@ -257,7 +247,7 @@ class Trainer(object):
|
|
| 257 |
"results": [], # metrics[0], or valid_loss
|
| 258 |
"checkpoints": [], # record path of saved ckpt, to automatically remove old ckpt
|
| 259 |
"best_result": None,
|
| 260 |
-
|
| 261 |
|
| 262 |
# auto fix
|
| 263 |
if len(metrics) == 0 or self.use_loss_as_metric:
|
|
@@ -297,6 +287,23 @@ class Trainer(object):
|
|
| 297 |
self.log(f"[INFO] Loading {self.use_checkpoint} ...")
|
| 298 |
self.load_checkpoint(self.use_checkpoint)
|
| 299 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
def __del__(self):
|
| 301 |
if self.log_ptr:
|
| 302 |
self.log_ptr.close()
|
|
@@ -447,6 +454,9 @@ class Trainer(object):
|
|
| 447 |
### ------------------------------
|
| 448 |
|
| 449 |
def train(self, train_loader, valid_loader, max_epochs):
|
|
|
|
|
|
|
|
|
|
| 450 |
if self.use_tensorboardX and self.local_rank == 0:
|
| 451 |
self.writer = tensorboardX.SummaryWriter(os.path.join(self.workspace, "run", self.name))
|
| 452 |
|
|
|
|
| 195 |
self.scheduler_update_every_step = scheduler_update_every_step
|
| 196 |
self.device = device if device is not None else torch.device(f'cuda:{local_rank}' if torch.cuda.is_available() else 'cpu')
|
| 197 |
self.console = Console()
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
model.to(self.device)
|
| 200 |
if self.world_size > 1:
|
|
|
|
| 205 |
# guide model
|
| 206 |
self.guidance = guidance
|
| 207 |
|
| 208 |
+
# text prompt
|
| 209 |
if self.guidance is not None:
|
| 210 |
+
|
|
|
|
| 211 |
for p in self.guidance.parameters():
|
| 212 |
p.requires_grad = False
|
| 213 |
|
| 214 |
+
self.prepare_text_embeddings()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
|
| 216 |
else:
|
| 217 |
self.text_z = None
|
|
|
|
| 247 |
"results": [], # metrics[0], or valid_loss
|
| 248 |
"checkpoints": [], # record path of saved ckpt, to automatically remove old ckpt
|
| 249 |
"best_result": None,
|
| 250 |
+
}
|
| 251 |
|
| 252 |
# auto fix
|
| 253 |
if len(metrics) == 0 or self.use_loss_as_metric:
|
|
|
|
| 287 |
self.log(f"[INFO] Loading {self.use_checkpoint} ...")
|
| 288 |
self.load_checkpoint(self.use_checkpoint)
|
| 289 |
|
| 290 |
+
# calculate the text embs.
|
| 291 |
+
def prepare_text_embeddings(self):
|
| 292 |
+
|
| 293 |
+
if self.opt.text is None:
|
| 294 |
+
self.log(f"[WARN] text prompt is not provided.")
|
| 295 |
+
self.text_z = None
|
| 296 |
+
return
|
| 297 |
+
|
| 298 |
+
if not self.opt.dir_text:
|
| 299 |
+
self.text_z = self.guidance.get_text_embeds([self.opt.text])
|
| 300 |
+
else:
|
| 301 |
+
self.text_z = []
|
| 302 |
+
for d in ['front', 'side', 'back', 'side', 'overhead', 'bottom']:
|
| 303 |
+
text = f"{self.opt.text}, {d} view"
|
| 304 |
+
text_z = self.guidance.get_text_embeds([text])
|
| 305 |
+
self.text_z.append(text_z)
|
| 306 |
+
|
| 307 |
def __del__(self):
|
| 308 |
if self.log_ptr:
|
| 309 |
self.log_ptr.close()
|
|
|
|
| 454 |
### ------------------------------
|
| 455 |
|
| 456 |
def train(self, train_loader, valid_loader, max_epochs):
|
| 457 |
+
|
| 458 |
+
assert self.text_z is not None, 'Training must provide a text prompt!'
|
| 459 |
+
|
| 460 |
if self.use_tensorboardX and self.local_rank == 0:
|
| 461 |
self.writer = tensorboardX.SummaryWriter(os.path.join(self.workspace, "run", self.name))
|
| 462 |
|
readme.md
CHANGED
|
@@ -86,6 +86,12 @@ python main.py --text "a hamburger" --workspace trial -O --albedo_iters 10000 #
|
|
| 86 |
# 2. use a smaller density regularization weight:
|
| 87 |
python main.py --text "a hamburger" --workspace trial -O --lambda_entropy 1e-5
|
| 88 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
## after the training is finished:
|
| 90 |
# test (exporting 360 video)
|
| 91 |
python main.py --workspace trial -O --test
|
|
|
|
| 86 |
# 2. use a smaller density regularization weight:
|
| 87 |
python main.py --text "a hamburger" --workspace trial -O --lambda_entropy 1e-5
|
| 88 |
|
| 89 |
+
# you can also train in a GUI to visualize the training progress:
|
| 90 |
+
python main.py --text "a hamburger" --workspace trial -O --gui
|
| 91 |
+
|
| 92 |
+
# A Gradio GUI is also possible (with less options):
|
| 93 |
+
python gradio_app.py # open in web browser
|
| 94 |
+
|
| 95 |
## after the training is finished:
|
| 96 |
# test (exporting 360 video)
|
| 97 |
python main.py --workspace trial -O --test
|