trainval.py 6.28 KB
Newer Older
Ruilong Li's avatar
Ruilong Li committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import math
import time

import numpy as np
import torch
import torch.nn.functional as F
import tqdm
from datasets.nerf_synthetic import SubjectLoader
from datasets.utils import namedtuple_map
from radiance_fields.ngp import NGPradianceField

from nerfacc import OccupancyField, volumetric_rendering


Ruilong Li's avatar
readme  
Ruilong Li committed
15
def render_image(radiance_field, rays, render_bkgd):
Ruilong Li's avatar
Ruilong Li committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    """Render the pixels of an image.

    Args:
      radiance_field: the radiance field of nerf.
      rays: a `Rays` namedtuple, the rays to be rendered.

    Returns:
      rgb: torch.tensor, rendered color image.
      depth: torch.tensor, rendered depth image.
      acc: torch.tensor, rendered accumulated weights per pixel.
    """
    rays_shape = rays.origins.shape
    if len(rays_shape) == 3:
        height, width, _ = rays_shape
        num_rays = height * width
        rays = namedtuple_map(lambda r: r.reshape([num_rays] + list(r.shape[2:])), rays)
    else:
        num_rays, _ = rays_shape
    results = []
35
    chunk = torch.iinfo(torch.int32).max if radiance_field.training else 81920
Ruilong Li's avatar
Ruilong Li committed
36
37
    for i in range(0, num_rays, chunk):
        chunk_rays = namedtuple_map(lambda r: r[i : i + chunk], rays)
Ruilong Li's avatar
readme  
Ruilong Li committed
38
        chunk_color, chunk_depth, chunk_weight, alive_ray_mask, = volumetric_rendering(
Ruilong Li's avatar
Ruilong Li committed
39
40
41
42
43
44
45
46
47
            query_fn=radiance_field.forward,  # {x, dir} -> {rgb, density}
            rays_o=chunk_rays.origins,
            rays_d=chunk_rays.viewdirs,
            scene_aabb=occ_field.aabb,
            scene_occ_binary=occ_field.occ_grid_binary,
            scene_resolution=occ_field.resolution,
            render_bkgd=render_bkgd,
            render_n_samples=render_n_samples,
        )
Ruilong Li's avatar
readme  
Ruilong Li committed
48
49
        results.append([chunk_color, chunk_depth, chunk_weight, alive_ray_mask])
    rgb, depth, acc, alive_ray_mask = [torch.cat(r, dim=0) for r in zip(*results)]
Ruilong Li's avatar
Ruilong Li committed
50
51
52
53
    return (
        rgb.view((*rays_shape[:-1], -1)),
        depth.view((*rays_shape[:-1], -1)),
        acc.view((*rays_shape[:-1], -1)),
Ruilong Li's avatar
readme  
Ruilong Li committed
54
        alive_ray_mask.view(*rays_shape[:-1]),
Ruilong Li's avatar
Ruilong Li committed
55
56
57
58
    )


if __name__ == "__main__":
59
    torch.manual_seed(42)
Ruilong Li's avatar
Ruilong Li committed
60
61
62
63
64
65
66

    device = "cuda:0"

    # setup dataset
    train_dataset = SubjectLoader(
        subject_id="lego",
        root_fp="/home/ruilongli/data/nerf_synthetic/",
Ruilong Li's avatar
Ruilong Li committed
67
        split="val",
Ruilong Li's avatar
Ruilong Li committed
68
69
70
71
72
73
74
75
        num_rays=8192,
    )
    train_dataloader = torch.utils.data.DataLoader(
        train_dataset,
        num_workers=10,
        batch_size=1,
        collate_fn=getattr(train_dataset.__class__, "collate_fn"),
    )
Ruilong Li's avatar
Ruilong Li committed
76
    test_dataset = SubjectLoader(
Ruilong Li's avatar
Ruilong Li committed
77
78
        subject_id="lego",
        root_fp="/home/ruilongli/data/nerf_synthetic/",
Ruilong Li's avatar
Ruilong Li committed
79
        split="test",
Ruilong Li's avatar
Ruilong Li committed
80
81
        num_rays=None,
    )
Ruilong Li's avatar
Ruilong Li committed
82
83
    test_dataloader = torch.utils.data.DataLoader(
        test_dataset,
84
        num_workers=10,
Ruilong Li's avatar
Ruilong Li committed
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
        batch_size=1,
        collate_fn=getattr(train_dataset.__class__, "collate_fn"),
    )

    # setup the scene bounding box.
    scene_aabb = torch.tensor([-1.5, -1.5, -1.5, 1.5, 1.5, 1.5])

    # setup the scene radiance field. Assume you have a NeRF model and
    # it has following functions:
    # - query_density(): {x} -> {density}
    # - forward(): {x, dirs} -> {rgb, density}
    radiance_field = NGPradianceField(aabb=scene_aabb).to(device)

    # setup some rendering settings
    render_n_samples = 1024
    render_step_size = (
        (scene_aabb[3:] - scene_aabb[:3]).max() * math.sqrt(3) / render_n_samples
    )

    optimizer = torch.optim.Adam(radiance_field.parameters(), lr=3e-3, eps=1e-15)

    # setup occupancy field with eval function
    def occ_eval_fn(x: torch.Tensor) -> torch.Tensor:
        """Evaluate occupancy given positions.

        Args:
            x: positions with shape (N, 3).
        Returns:
            occupancy values with shape (N, 1).
        """
        density_after_activation = radiance_field.query_density(x)
Ruilong Li's avatar
Ruilong Li committed
116
        # those two are similar when density is small.
117
        # occupancy = 1.0 - torch.exp(-density_after_activation * render_step_size)
Ruilong Li's avatar
Ruilong Li committed
118
119
120
121
122
123
124
125
126
127
        occupancy = density_after_activation * render_step_size
        return occupancy

    occ_field = OccupancyField(
        occ_eval_fn=occ_eval_fn, aabb=scene_aabb, resolution=128
    ).to(device)

    # training
    step = 0
    tic = time.time()
Ruilong Li's avatar
Ruilong Li committed
128
    for epoch in range(200):
Ruilong Li's avatar
Ruilong Li committed
129
130
131
132
133
134
135
136
137
138
139
140
141
142
        for data in train_dataloader:
            step += 1
            if step > 30_000:
                print("training stops")
                exit()

            # generate rays from data and the gt pixel color
            rays = namedtuple_map(lambda x: x.to(device), data["rays"])
            pixels = data["pixels"].to(device)
            render_bkgd = data["color_bkgd"].to(device)

            # update occupancy grid
            occ_field.every_n_step(step)

Ruilong Li's avatar
readme  
Ruilong Li committed
143
144
145
            rgb, depth, acc, alive_ray_mask = render_image(
                radiance_field, rays, render_bkgd
            )
Ruilong Li's avatar
Ruilong Li committed
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164

            # compute loss
            loss = F.mse_loss(rgb, pixels)

            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

            if step % 50 == 0:
                elapsed_time = time.time() - tic
                print(
                    f"elapsed_time={elapsed_time:.2f}s | {step=} | loss={loss.item(): .5f}"
                )

            if step % 30_000 == 0 and step > 0:
                # evaluation
                radiance_field.eval()
                psnrs = []
                with torch.no_grad():
Ruilong Li's avatar
Ruilong Li committed
165
                    for data in tqdm.tqdm(test_dataloader):
Ruilong Li's avatar
Ruilong Li committed
166
167
168
169
170
                        # generate rays from data and the gt pixel color
                        rays = namedtuple_map(lambda x: x.to(device), data["rays"])
                        pixels = data["pixels"].to(device)
                        render_bkgd = data["color_bkgd"].to(device)
                        # rendering
Ruilong Li's avatar
readme  
Ruilong Li committed
171
                        rgb, depth, acc, alive_ray_mask = render_image(
Ruilong Li's avatar
Ruilong Li committed
172
173
174
175
176
177
178
179
                            radiance_field, rays, render_bkgd
                        )
                        mse = F.mse_loss(rgb, pixels)
                        psnr = -10.0 * torch.log(mse) / np.log(10.0)
                        psnrs.append(psnr.item())
                psnr_avg = sum(psnrs) / len(psnrs)
                print(f"evaluation: {psnr_avg=}")

Ruilong Li's avatar
Ruilong Li committed
180
# "train"
Ruilong Li's avatar
Ruilong Li committed
181
182
# elapsed_time=317.59s | step=30000 | loss= 0.00028
# evaluation: psnr_avg=33.27096959114075 (6.24 it/s)
Ruilong Li's avatar
Ruilong Li committed
183
184
185
186

# "trainval"
# elapsed_time=389.08s | step=30000 | loss= 0.00030
# evaluation: psnr_avg=34.00573859214783 (6.26 it/s)