mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-11-25 10:29:51 +08:00
Speed-up NGP inference by 3x. (#211)
This commit is contained in:
1 parent
934bd4bd72
commit
3e28a40c44
10 files changed
+243
-104
No files matched your search
@@ -171,24 +171,32 @@ class Graph(AbstractGraph):
|
||||
"""Run forward starting with a ray bundle."""
|
||||
if self.collider is not None:
|
||||
intersected_ray_bundle = self.collider(ray_bundle)
|
||||
valid_mask = intersected_ray_bundle.valid_mask[..., 0]
|
||||
else:
|
||||
# NOTE(ruilongli): we don't need collider for ngp
|
||||
intersected_ray_bundle = ray_bundle
|
||||
valid_mask = None
|
||||
|
||||
if batch is None:
|
||||
# during inference, keep all rays
|
||||
outputs = self.get_outputs(intersected_ray_bundle)
|
||||
return outputs
|
||||
|
||||
# during training, keep only the rays that intersect the scene. discard the rest
|
||||
valid_mask = intersected_ray_bundle.valid_mask[..., 0]
|
||||
masked_intersected_ray_bundle = intersected_ray_bundle[valid_mask]
|
||||
masked_batch = get_masked_dict(batch, valid_mask) # NOTE(ethan): this is really slow if on CPU!
|
||||
outputs = self.get_outputs(masked_intersected_ray_bundle)
|
||||
metrics_dict = self.get_metrics_dict(outputs=outputs, batch=masked_batch)
|
||||
if valid_mask is not None:
|
||||
intersected_ray_bundle = intersected_ray_bundle[valid_mask]
|
||||
# during training, keep only the rays that intersect the scene. discard the rest
|
||||
batch = get_masked_dict(batch, valid_mask) # NOTE(ethan): this is really slow if on CPU!
|
||||
|
||||
outputs = self.get_outputs(intersected_ray_bundle)
|
||||
metrics_dict = self.get_metrics_dict(outputs=outputs, batch=batch)
|
||||
loss_dict = self.get_loss_dict(
|
||||
outputs=outputs, batch=masked_batch, metrics_dict=metrics_dict, loss_coefficients=self.loss_coefficients
|
||||
outputs=outputs, batch=batch, metrics_dict=metrics_dict, loss_coefficients=self.loss_coefficients
|
||||
)
|
||||
|
||||
# scaling losses by coefficients.
|
||||
for loss_name in loss_dict.keys():
|
||||
if loss_name in self.loss_coefficients:
|
||||
loss_dict[loss_name] *= self.loss_coefficients[loss_name]
|
||||
return outputs, loss_dict, metrics_dict
|
||||
|
||||
def forward(self, ray_indices: TensorType["num_rays", 3], batch: Union[str, Dict[str, torch.tensor]] = None):
|
||||
|
||||
@@ -86,31 +86,99 @@ class NGPGraph(Graph):
|
||||
# TODO(ruilongli)
|
||||
# - train test difference
|
||||
# - visualize "depth_density_grid"
|
||||
ray_samples, packed_info, t_min, t_max = self.sampler(ray_bundle, self.field.aabb)
|
||||
num_rays = len(ray_bundle)
|
||||
device = ray_bundle.origins.device
|
||||
|
||||
field_outputs = self.field.forward(ray_samples)
|
||||
rgbs = field_outputs[FieldHeadNames.RGB]
|
||||
sigmas = field_outputs[FieldHeadNames.DENSITY]
|
||||
if self.training:
|
||||
ray_samples, packed_info, t_min, t_max = self.sampler(ray_bundle, self.field.aabb)
|
||||
|
||||
accumulated_weight, accumulated_depth, accumulated_color, mask = nerfactory_cuda.VolumeRenderer.apply(
|
||||
packed_info, ray_samples.frustums.starts, ray_samples.frustums.ends, sigmas, rgbs
|
||||
)
|
||||
accumulated_depth = torch.clip(accumulated_depth, t_min[:, None], t_max[:, None])
|
||||
accumulated_color = accumulated_color + colors.WHITE.to(accumulated_color) * (1.0 - accumulated_weight)
|
||||
field_outputs = self.field.forward(ray_samples)
|
||||
rgbs = field_outputs[FieldHeadNames.RGB]
|
||||
sigmas = field_outputs[FieldHeadNames.DENSITY]
|
||||
|
||||
opacities = torch.zeros((num_rays, 1), device=device)
|
||||
(
|
||||
accumulated_weight,
|
||||
accumulated_depth,
|
||||
accumulated_color,
|
||||
alive_ray_mask,
|
||||
) = nerfactory_cuda.VolumeRenderer.apply(
|
||||
packed_info, ray_samples.frustums.starts, ray_samples.frustums.ends, sigmas, rgbs, opacities
|
||||
)
|
||||
accumulated_depth = torch.clip(accumulated_depth, t_min[:, None], t_max[:, None])
|
||||
accumulated_color = accumulated_color + colors.WHITE.to(accumulated_color) * (1.0 - accumulated_weight)
|
||||
|
||||
else:
|
||||
accumulated_weight = torch.zeros((num_rays, 1), device=device)
|
||||
accumulated_depth = torch.zeros((num_rays, 1), device=device)
|
||||
accumulated_color = torch.zeros((num_rays, 3), device=device)
|
||||
alive_ray_mask = torch.ones((num_rays), device=device, dtype=torch.bool) # the ray we kept from sampler
|
||||
|
||||
t_min, t_max = None, None
|
||||
t_marching = None
|
||||
samples = 0
|
||||
while samples < self.sampler.num_samples:
|
||||
num_alive = alive_ray_mask.sum().item()
|
||||
if num_alive == 0:
|
||||
break
|
||||
|
||||
min_samples = 1
|
||||
num_samples = max(min(num_rays // num_alive, 64), min_samples)
|
||||
samples += num_samples
|
||||
|
||||
ray_samples, packed_info, t_marching, t_max = self.sampler(
|
||||
ray_bundle, self.field.aabb, marching_steps=num_samples, t_min=t_marching, t_max=t_max
|
||||
)
|
||||
if t_min is None:
|
||||
t_min = t_marching
|
||||
|
||||
field_outputs = self.field.forward(ray_samples)
|
||||
rgbs = field_outputs[FieldHeadNames.RGB]
|
||||
sigmas = field_outputs[FieldHeadNames.DENSITY]
|
||||
|
||||
(
|
||||
_accumulated_weight,
|
||||
_accumulated_depth,
|
||||
_accumulated_color,
|
||||
_,
|
||||
) = nerfactory_cuda.VolumeRenderer.apply(
|
||||
packed_info,
|
||||
ray_samples.frustums.starts,
|
||||
ray_samples.frustums.ends,
|
||||
sigmas,
|
||||
rgbs,
|
||||
accumulated_weight,
|
||||
)
|
||||
accumulated_weight += _accumulated_weight
|
||||
accumulated_depth += _accumulated_depth
|
||||
accumulated_color += _accumulated_color
|
||||
|
||||
# all samples for this ray have been drawn
|
||||
alive_ray_mask[packed_info[:, 2] < num_samples] = False
|
||||
|
||||
# this ray has converged
|
||||
alive_ray_mask[accumulated_weight[:, 0] > 1.0 - 1e-4] = False
|
||||
|
||||
# march forward and skip those are not alive
|
||||
t_marching = ray_samples.frustums.ends.reshape(num_rays, num_samples).max(dim=-1).values
|
||||
t_marching[~alive_ray_mask] = 1e10
|
||||
|
||||
accumulated_depth = torch.clip(accumulated_depth, t_min[:, None], t_max[:, None])
|
||||
accumulated_color = accumulated_color + colors.WHITE.to(accumulated_color) * (1.0 - accumulated_weight)
|
||||
|
||||
outputs = {
|
||||
"rgb": accumulated_color,
|
||||
"accumulation": accumulated_weight,
|
||||
"depth": accumulated_depth,
|
||||
"mask": mask, # the rays we skipped from sampler
|
||||
"alive_ray_mask": alive_ray_mask, # the rays we kept from sampler
|
||||
}
|
||||
return outputs
|
||||
|
||||
def get_loss_dict(self, outputs, batch, metrics_dict, loss_coefficients):
|
||||
device = self.get_device()
|
||||
image = batch["image"].to(device)
|
||||
if "mask" in outputs:
|
||||
mask = outputs["mask"]
|
||||
if "alive_ray_mask" in outputs:
|
||||
mask = outputs["alive_ray_mask"]
|
||||
rgb_loss = self.rgb_loss(image[mask], outputs["rgb"][mask])
|
||||
else:
|
||||
rgb_loss = self.rgb_loss(image, outputs["rgb"])
|
||||
|
||||
@@ -357,6 +357,9 @@ class NGPSpacedSampler(Sampler):
|
||||
ray_bundle: RayBundle,
|
||||
aabb: TensorType[2, 3],
|
||||
num_samples: Optional[int] = None,
|
||||
marching_steps: Optional[int] = 128,
|
||||
t_min: Optional[TensorType["num_rays"]] = None,
|
||||
t_max: Optional[TensorType["num_rays"]] = None,
|
||||
) -> Tuple[RaySamples, TensorType["total_samples", 3], TensorType["total_samples"], TensorType["total_samples"]]:
|
||||
"""Generate ray samples in a bounding box.
|
||||
|
||||
@@ -379,13 +382,24 @@ class NGPSpacedSampler(Sampler):
|
||||
aabb = aabb.flatten()
|
||||
rays_o = ray_bundle.origins.contiguous()
|
||||
rays_d = ray_bundle.directions.contiguous()
|
||||
t_min, t_max = nerfactory_cuda.ray_aabb_intersect(rays_o, rays_d, aabb)
|
||||
scene_scale = (aabb[3:6] - aabb[0:3]).max()
|
||||
|
||||
# TODO(ruilongli): * 16 is for original impl for training. Need to run
|
||||
# some profiling test with this choice.
|
||||
max_samples_per_batch = len(rays_o) * num_samples
|
||||
if t_min is None or t_max is None:
|
||||
# TODO(ruilongli): this clipping here is stupid. Try to avoid that.
|
||||
t_min, t_max = nerfactory_cuda.ray_aabb_intersect(rays_o, rays_d, aabb)
|
||||
t_min = torch.clamp(t_min, max=1e10)
|
||||
t_max = torch.clamp(t_max, max=1e10)
|
||||
|
||||
# sampling arguments
|
||||
if self.training:
|
||||
# TODO(ruilongli): * 16 is for original impl for training. Need to run
|
||||
# some profiling test with this choice.
|
||||
marching_steps = -1
|
||||
max_samples_per_batch = len(rays_o) * num_samples
|
||||
else:
|
||||
max_samples_per_batch = len(rays_o) * marching_steps
|
||||
|
||||
# marching
|
||||
packed_info, origins, dirs, starts, ends = nerfactory_cuda.raymarching(
|
||||
# rays
|
||||
rays_o,
|
||||
@@ -399,20 +413,28 @@ class NGPSpacedSampler(Sampler):
|
||||
self.density_field.resolution,
|
||||
self.density_field.density_bitfield,
|
||||
# sampling args
|
||||
marching_steps,
|
||||
max_samples_per_batch,
|
||||
num_samples,
|
||||
0.0,
|
||||
scene_scale,
|
||||
)
|
||||
total_samples = max(packed_info[:, -1].sum(), 1)
|
||||
origins = origins[:total_samples]
|
||||
dirs = dirs[:total_samples]
|
||||
starts = starts[:total_samples]
|
||||
ends = ends[:total_samples]
|
||||
|
||||
# squeeze valid samples
|
||||
if self.training:
|
||||
total_samples = max(packed_info[:, -1].sum(), 1)
|
||||
origins = origins[:total_samples]
|
||||
dirs = dirs[:total_samples]
|
||||
starts = starts[:total_samples]
|
||||
ends = ends[:total_samples]
|
||||
valid_mask = None
|
||||
else:
|
||||
valid_mask = (dirs != 0.0).any(dim=-1, keepdim=True)
|
||||
|
||||
# return samples
|
||||
zeros = torch.zeros_like(origins[:, :1])
|
||||
|
||||
ray_samples = RaySamples(
|
||||
frustums=Frustums(origins=origins, directions=dirs, starts=starts, ends=ends, pixel_area=zeros),
|
||||
valid_mask=valid_mask,
|
||||
)
|
||||
return ray_samples, packed_info, t_min, t_max
|
||||
Reference in new issue
Block a user