"ppocr/utils/e2e_utils/extract_textpoint_fast.py" did not exist on "55c28ed5b4d5d3482c7ad0bb5b8706eaf122a755"
train_ngp_nerf.py 9.94 KB
Newer Older
1
2
3
4
"""
Copyright (c) 2022 Ruilong Li, UC Berkeley.
"""

Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
5
6
import argparse
import math
Jingchen Ye's avatar
Jingchen Ye committed
7
import pathlib
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import time

import imageio
import numpy as np
import torch
import torch.nn.functional as F
import tqdm
from radiance_fields.ngp import NGPradianceField
from utils import render_image, set_random_seed

from nerfacc import ContractionType, OccupancyGrid

if __name__ == "__main__":

    device = "cuda:0"
    set_random_seed(42)

    parser = argparse.ArgumentParser()
Jingchen Ye's avatar
Jingchen Ye committed
26
27
28
29
30
31
    parser.add_argument(
        "--data_root",
        type=str,
        default=str(pathlib.Path.cwd() / "data"),
        help="the root dir of the dataset",
    )
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
    parser.add_argument(
        "--train_split",
        type=str,
        default="trainval",
        choices=["train", "trainval"],
        help="which train split to use",
    )
    parser.add_argument(
        "--scene",
        type=str,
        default="lego",
        choices=[
            # nerf synthetic
            "chair",
            "drums",
            "ficus",
            "hotdog",
            "lego",
            "materials",
            "mic",
            "ship",
            # mipnerf360 unbounded
            "garden",
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
55
56
57
58
59
60
            "bicycle",
            "bonsai",
            "counter",
            "kitchen",
            "room",
            "stump",
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
        ],
        help="which scene to use",
    )
    parser.add_argument(
        "--aabb",
        type=lambda s: [float(item) for item in s.split(",")],
        default="-1.5,-1.5,-1.5,1.5,1.5,1.5",
        help="delimited list input",
    )
    parser.add_argument(
        "--test_chunk_size",
        type=int,
        default=8192,
    )
    parser.add_argument(
        "--unbounded",
        action="store_true",
        help="whether to use unbounded rendering",
    )
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
80
81
82
83
84
    parser.add_argument(
        "--auto_aabb",
        action="store_true",
        help="whether to automatically compute the aabb",
    )
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
85
86
87
88
89
90
91
92
    parser.add_argument("--cone_angle", type=float, default=0.0)
    args = parser.parse_args()

    render_n_samples = 1024

    # setup the dataset
    train_dataset_kwargs = {}
    test_dataset_kwargs = {}
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
93
    if args.unbounded:
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
94
95
96
97
98
        from datasets.nerf_360_v2 import SubjectLoader

        target_sample_batch_size = 1 << 20
        train_dataset_kwargs = {"color_bkgd_aug": "random", "factor": 4}
        test_dataset_kwargs = {"factor": 4}
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
99
        grid_resolution = 256
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
100
101
102
103
104
105
106
107
    else:
        from datasets.nerf_synthetic import SubjectLoader

        target_sample_batch_size = 1 << 18
        grid_resolution = 128

    train_dataset = SubjectLoader(
        subject_id=args.scene,
Jingchen Ye's avatar
Jingchen Ye committed
108
        root_fp=args.data_root,
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
109
110
111
112
113
114
115
        split=args.train_split,
        num_rays=target_sample_batch_size // render_n_samples,
        **train_dataset_kwargs,
    )

    test_dataset = SubjectLoader(
        subject_id=args.scene,
Jingchen Ye's avatar
Jingchen Ye committed
116
        root_fp=args.data_root,
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
117
118
119
120
121
        split="test",
        num_rays=None,
        **test_dataset_kwargs,
    )

Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
    if args.auto_aabb:
        camera_locs = torch.cat(
            [train_dataset.camtoworlds, test_dataset.camtoworlds]
        )[:, :3, -1]
        args.aabb = torch.cat(
            [camera_locs.min(dim=0).values, camera_locs.max(dim=0).values]
        ).tolist()
        print("Using auto aabb", args.aabb)

    # setup the scene bounding box.
    if args.unbounded:
        print("Using unbounded rendering")
        contraction_type = ContractionType.UN_BOUNDED_SPHERE
        # contraction_type = ContractionType.UN_BOUNDED_TANH
        scene_aabb = None
        near_plane = 0.2
        far_plane = 1e4
        render_step_size = 1e-2
140
        alpha_thre = 1e-2
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
141
142
143
144
145
146
147
148
149
150
    else:
        contraction_type = ContractionType.AABB
        scene_aabb = torch.tensor(args.aabb, dtype=torch.float32, device=device)
        near_plane = None
        far_plane = None
        render_step_size = (
            (scene_aabb[3:] - scene_aabb[:3]).max()
            * math.sqrt(3)
            / render_n_samples
        ).item()
151
        alpha_thre = 0.0
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
152
153

    # setup the radiance field we want to train.
154
    max_steps = 20000
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
155
156
157
158
159
160
161
162
163
164
165
166
167
168
    grad_scaler = torch.cuda.amp.GradScaler(2**10)
    radiance_field = NGPradianceField(
        aabb=args.aabb,
        unbounded=args.unbounded,
    ).to(device)
    optimizer = torch.optim.Adam(
        radiance_field.parameters(), lr=1e-2, eps=1e-15
    )
    scheduler = torch.optim.lr_scheduler.MultiStepLR(
        optimizer,
        milestones=[max_steps // 2, max_steps * 3 // 4, max_steps * 9 // 10],
        gamma=0.33,
    )

Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
    occupancy_grid = OccupancyGrid(
        roi_aabb=args.aabb,
        resolution=grid_resolution,
        contraction_type=contraction_type,
    ).to(device)

    # training
    step = 0
    tic = time.time()
    for epoch in range(10000000):
        for i in range(len(train_dataset)):
            radiance_field.train()
            data = train_dataset[i]

            render_bkgd = data["color_bkgd"]
            rays = data["rays"]
            pixels = data["pixels"]

187
188
189
190
191
192
193
194
195
196
197
198
199
            def occ_eval_fn(x):
                if args.cone_angle > 0.0:
                    # randomly sample a camera for computing step size.
                    camera_ids = torch.randint(
                        0, len(train_dataset), (x.shape[0],), device=device
                    )
                    origins = train_dataset.camtoworlds[camera_ids, :3, -1]
                    t = (origins - x).norm(dim=-1, keepdim=True)
                    # compute actual step size used in marching, based on the distance to the camera.
                    step_size = torch.clamp(
                        t * args.cone_angle, min=render_step_size
                    )
                    # filter out the points that are not in the near far plane.
200
                    if (near_plane is not None) and (far_plane is not None):
201
202
203
204
205
206
207
208
209
210
211
                        step_size = torch.where(
                            (t > near_plane) & (t < far_plane),
                            step_size,
                            torch.zeros_like(step_size),
                        )
                else:
                    step_size = render_step_size
                # compute occupancy
                density = radiance_field.query_density(x)
                return density * step_size

Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
212
            # update occupancy grid
213
            occupancy_grid.every_n_step(step=step, occ_eval_fn=occ_eval_fn)
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
214
215
216
217
218
219
220
221
222
223
224
225
226

            # render
            rgb, acc, depth, n_rendering_samples = render_image(
                radiance_field,
                occupancy_grid,
                rays,
                scene_aabb,
                # rendering options
                near_plane=near_plane,
                far_plane=far_plane,
                render_step_size=render_step_size,
                render_bkgd=render_bkgd,
                cone_angle=args.cone_angle,
227
                alpha_thre=alpha_thre,
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
228
            )
229
230
            if n_rendering_samples == 0:
                continue
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249

            # dynamic batch size for rays to keep sample batch size constant.
            num_rays = len(pixels)
            num_rays = int(
                num_rays
                * (target_sample_batch_size / float(n_rendering_samples))
            )
            train_dataset.update_num_rays(num_rays)
            alive_ray_mask = acc.squeeze(-1) > 0

            # compute loss
            loss = F.smooth_l1_loss(rgb[alive_ray_mask], pixels[alive_ray_mask])

            optimizer.zero_grad()
            # do not unscale it because we are using Adam.
            grad_scaler.scale(loss).backward()
            optimizer.step()
            scheduler.step()

Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
250
            if step % 10000 == 0:
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
251
252
253
                elapsed_time = time.time() - tic
                loss = F.mse_loss(rgb[alive_ray_mask], pixels[alive_ray_mask])
                print(
Matthew Tancik's avatar
Matthew Tancik committed
254
                    f"elapsed_time={elapsed_time:.2f}s | step={step} | "
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
255
256
257
258
259
                    f"loss={loss:.5f} | "
                    f"alive_ray_mask={alive_ray_mask.long().sum():d} | "
                    f"n_rendering_samples={n_rendering_samples:d} | num_rays={len(pixels):d} |"
                )

Jingchen Ye's avatar
Jingchen Ye committed
260
            if step > 0 and step % max_steps == 0:
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
                # evaluation
                radiance_field.eval()

                psnrs = []
                with torch.no_grad():
                    for i in tqdm.tqdm(range(len(test_dataset))):
                        data = test_dataset[i]
                        render_bkgd = data["color_bkgd"]
                        rays = data["rays"]
                        pixels = data["pixels"]

                        # rendering
                        rgb, acc, depth, _ = render_image(
                            radiance_field,
                            occupancy_grid,
                            rays,
                            scene_aabb,
                            # rendering options
279
280
                            near_plane=near_plane,
                            far_plane=far_plane,
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
281
282
283
                            render_step_size=render_step_size,
                            render_bkgd=render_bkgd,
                            cone_angle=args.cone_angle,
284
                            alpha_thre=alpha_thre,
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
                            # test options
                            test_chunk_size=args.test_chunk_size,
                        )
                        mse = F.mse_loss(rgb, pixels)
                        psnr = -10.0 * torch.log(mse) / np.log(10.0)
                        psnrs.append(psnr.item())
                        # imageio.imwrite(
                        #     "acc_binary_test.png",
                        #     ((acc > 0).float().cpu().numpy() * 255).astype(np.uint8),
                        # )
                        # imageio.imwrite(
                        #     "rgb_test.png",
                        #     (rgb.cpu().numpy() * 255).astype(np.uint8),
                        # )
                        # break
                psnr_avg = sum(psnrs) / len(psnrs)
Matthew Tancik's avatar
Matthew Tancik committed
301
                print(f"evaluation: psnr_avg={psnr_avg}")
Ruilong Li(李瑞龙)'s avatar
Ruilong Li(李瑞龙) committed
302
303
304
305
306
307
308
                train_dataset.training = True

            if step == max_steps:
                print("training stops")
                exit()

            step += 1