Update Instant-NGP & Density Grid with CUDA supports. Much faster and better PSNR. (#193)

This commit is contained in:
Ruilong Li(李瑞龙) authored and GitHub committed 2022-07-24 22:22:44 -07:00
1 parent 31b52ae186
commit 12cd321e1a
39 files changed
+1721 -650

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
#pragma once
#ifdef __CUDACC__
#define CUDA_HOSTDEV __host__ __device__
#else
#define CUDA_HOSTDEV
#endif
#include <torch/extension.h>
inline constexpr CUDA_HOSTDEV float __SQRT3() { return 1.73205080757f; }
template <typename scalar_t>
inline CUDA_HOSTDEV void __swap(scalar_t &a, scalar_t &b)
{
scalar_t c = a;
a = b;
b = c;
}
inline CUDA_HOSTDEV float __clamp(float f, float a, float b) { return fmaxf(a, fminf(f, b)); }
inline CUDA_HOSTDEV int __clamp(int f, int a, int b) { return std::max(a, std::min(f, b)); }
inline CUDA_HOSTDEV float __sign(float x) { return copysignf(1.0, x); }
inline CUDA_HOSTDEV uint32_t __expand_bits(uint32_t v)
{
v = (v * 0x00010001u) & 0xFF0000FFu;
v = (v * 0x00000101u) & 0x0F00F00Fu;
v = (v * 0x00000011u) & 0xC30C30C3u;
v = (v * 0x00000005u) & 0x49249249u;
return v;
}
inline CUDA_HOSTDEV uint32_t __morton3D(uint32_t x, uint32_t y, uint32_t z)
{
uint32_t xx = __expand_bits(x);
uint32_t yy = __expand_bits(y);
uint32_t zz = __expand_bits(z);
return xx | (yy << 1) | (zz << 2);
}
inline CUDA_HOSTDEV uint32_t __morton3D_invert(uint32_t x)
{
x = x & 0x49249249;
x = (x | (x >> 2)) & 0xc30c30c3;
x = (x | (x >> 4)) & 0x0f00f00f;
x = (x | (x >> 8)) & 0xff0000ff;
x = (x | (x >> 16)) & 0x0000ffff;
return x;
}
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include "helpers.h"
#include <c10/cuda/CUDAGuard.h>
#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor")
#define CHECK_CONTIGUOUS(x) \
TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
#define CHECK_INPUT(x) \
CHECK_CUDA(x); \
CHECK_CONTIGUOUS(x)
#define CUDA_GET_THREAD_ID(tid, Q) \
const int tid = blockIdx.x * blockDim.x + threadIdx.x; \
if (tid >= Q) \
return
#define CUDA_N_BLOCKS_NEEDED(Q, CUDA_N_THREADS) ((Q - 1) / CUDA_N_THREADS + 1)
#define DEVICE_GUARD(_ten) \
const at::cuda::OptionalCUDAGuard device_guard(device_of(_ten));
+118
View File
@@ -0,0 +1,118 @@
#include "include/helpers_cuda.h"
template <typename scalar_t>
inline __host__ __device__ void _ray_aabb_intersect(
const scalar_t* rays_o,
const scalar_t* rays_d,
const scalar_t* aabb,
scalar_t* near,
scalar_t* far
) {
// aabb is [xmin, ymin, zmin, xmax, ymax, zmax]
scalar_t tmin = (aabb[0] - rays_o[0]) / rays_d[0];
scalar_t tmax = (aabb[3] - rays_o[0]) / rays_d[0];
if (tmin > tmax) __swap(tmin, tmax);
scalar_t tymin = (aabb[1] - rays_o[1]) / rays_d[1];
scalar_t tymax = (aabb[4] - rays_o[1]) / rays_d[1];
if (tymin > tymax) __swap(tymin, tymax);
if (tmin > tymax || tymin > tmax){
*near = std::numeric_limits<scalar_t>::max();
*far = std::numeric_limits<scalar_t>::max();
return;
}
if (tymin > tmin) tmin = tymin;
if (tymax < tmax) tmax = tymax;
scalar_t tzmin = (aabb[2] - rays_o[2]) / rays_d[2];
scalar_t tzmax = (aabb[5] - rays_o[2]) / rays_d[2];
if (tzmin > tzmax) __swap(tzmin, tzmax);
if (tmin > tzmax || tzmin > tmax){
*near = std::numeric_limits<scalar_t>::max();
*far = std::numeric_limits<scalar_t>::max();
return;
}
if (tzmin > tmin) tmin = tzmin;
if (tzmax < tmax) tmax = tzmax;
*near = tmin;
*far = tmax;
return;
}
template <typename scalar_t>
__global__ void kernel_ray_aabb_intersect(
const int N,
const scalar_t* rays_o,
const scalar_t* rays_d,
const scalar_t* aabb,
scalar_t* t_min,
scalar_t* t_max
){
// aabb is [xmin, ymin, zmin, xmax, ymax, zmax]
CUDA_GET_THREAD_ID(thread_id, N);
// locate
rays_o += thread_id * 3;
rays_d += thread_id * 3;
t_min += thread_id;
t_max += thread_id;
_ray_aabb_intersect<scalar_t>(rays_o, rays_d, aabb, t_min, t_max);
scalar_t zero = static_cast<scalar_t>(0.f);
*t_min = *t_min > zero ? *t_min : zero;
return;
}
/**
* @brief Ray AABB Test
*
* @param rays_o Ray origins. Tensor with shape [N, 3].
* @param rays_d Normalized ray directions. Tensor with shape [N, 3].
* @param aabb Scene AABB [xmin, ymin, zmin, xmax, ymax, zmax]. Tensor with shape [6].
* @return std::vector<torch::Tensor>
* Ray AABB intersection {t_min, t_max} with shape [N] respectively. Note the t_min is
* clipped to minimum zero.
*/
std::vector<torch::Tensor> ray_aabb_intersect(
const torch::Tensor rays_o, const torch::Tensor rays_d, const torch::Tensor aabb
) {
DEVICE_GUARD(rays_o);
CHECK_INPUT(rays_o);
CHECK_INPUT(rays_d);
CHECK_INPUT(aabb);
TORCH_CHECK(rays_o.ndimension() == 2 & rays_o.size(1) == 3)
TORCH_CHECK(rays_d.ndimension() == 2 & rays_d.size(1) == 3)
TORCH_CHECK(aabb.ndimension() == 1 & aabb.size(0) == 6)
const int N = rays_o.size(0);
const int threads = 256;
const int blocks = CUDA_N_BLOCKS_NEEDED(N, threads);
torch::Tensor t_min = torch::empty({N}, rays_o.options());
torch::Tensor t_max = torch::empty({N}, rays_o.options());
AT_DISPATCH_FLOATING_TYPES_AND_HALF(
rays_o.scalar_type(), "ray_aabb_intersect",
([&] {
kernel_ray_aabb_intersect<scalar_t><<<blocks, threads>>>(
N,
rays_o.data_ptr<scalar_t>(),
rays_d.data_ptr<scalar_t>(),
aabb.data_ptr<scalar_t>(),
t_min.data_ptr<scalar_t>(),
t_max.data_ptr<scalar_t>()
);
})
);
return {t_min, t_max};
}
+107
View File
@@ -0,0 +1,107 @@
#include "include/helpers_cuda.h"
template <typename index_t>
__global__ void kernel_morton3D(
const int N,
const index_t* coords,
index_t* indices
){
CUDA_GET_THREAD_ID(thread_id, N);
// locate
coords += thread_id * 3;
indices += thread_id;
uint32_t index = __morton3D(
static_cast<uint32_t>(coords[0]),
static_cast<uint32_t>(coords[1]),
static_cast<uint32_t>(coords[2])
);
*indices = static_cast<index_t>(index);
return;
}
template <typename index_t>
__global__ void kernel_morton3D_invert(
const int N,
const index_t* indices,
index_t* coords
){
CUDA_GET_THREAD_ID(thread_id, N);
// locate
coords += thread_id * 3;
indices += thread_id;
uint32_t index = static_cast<uint32_t>(indices[0]);
coords[0] = static_cast<index_t>(__morton3D_invert(index >> 0));
coords[1] = static_cast<index_t>(__morton3D_invert(index >> 1));
coords[2] = static_cast<index_t>(__morton3D_invert(index >> 2));
return;
}
/**
* @brief Convert 3D coords to indices in z-order
*
* @param coords Integer coords with shape [N, 3]
* @return torch::Tensor Integer indices with shape [N]
*/
torch::Tensor morton3D(const torch::Tensor coords){
DEVICE_GUARD(coords);
CHECK_INPUT(coords);
TORCH_CHECK(coords.ndimension() == 2 & coords.size(1) == 3)
const int N = coords.size(0);
const int threads = 256;
const int blocks = CUDA_N_BLOCKS_NEEDED(N, threads);
torch::Tensor indices = torch::empty({N}, coords.options());
AT_DISPATCH_INDEX_TYPES(
coords.scalar_type(), "morton3D",
([&] {
kernel_morton3D<index_t><<<blocks, threads>>>(
N,
coords.data_ptr<index_t>(),
indices.data_ptr<index_t>()
);
})
);
return indices;
}
/**
* @brief Convert 3D indices to coords in z-order
*
* @param indices Integer indices with shape [N]
* @return torch::Tensor Integer coords with shape [N, 3]
*/
torch::Tensor morton3D_invert(const torch::Tensor indices){
DEVICE_GUARD(indices);
CHECK_INPUT(indices);
TORCH_CHECK(indices.ndimension() == 1)
const int N = indices.size(0);
const int threads = 256;
const int blocks = CUDA_N_BLOCKS_NEEDED(N, threads);
torch::Tensor coords = torch::empty({N, 3}, indices.options());
AT_DISPATCH_INDEX_TYPES(
indices.scalar_type(), "morton3D_invert",
([&] {
kernel_morton3D_invert<index_t><<<blocks, threads>>>(
N,
indices.data_ptr<index_t>(),
coords.data_ptr<index_t>()
);
})
);
return coords;
}
+59
View File
@@ -0,0 +1,59 @@
#include "include/helpers_cuda.h"
template <typename scalar_t>
__global__ void kernel_packbits(
const int N,
const float threshold,
const scalar_t* data,
uint8_t* bitfield
){
CUDA_GET_THREAD_ID(thread_id, N);
data += thread_id * 8;
bitfield += thread_id;
uint8_t bits = 0;
#pragma unroll 8
for (uint8_t i = 0; i < 8; i++) {
bits |= (data[i] > threshold) ? ((uint8_t)1 << i) : 0;
}
bitfield[0] = bits;
}
/**
* @brief Pack data into uint8 bits based on threshold.
*
* @param data: Tensor with any shape. Total elements must be N * 8.
* @param threshold:
* @return Tensor: bitfield that has shape of [N]
*/
torch::Tensor packbits(
const torch::Tensor data, const float threshold
) {
DEVICE_GUARD(data);
CHECK_INPUT(data);
TORCH_CHECK(data.numel() % 8 == 0)
const int N = data.numel() / 8;
const int threads = 256;
const int blocks = CUDA_N_BLOCKS_NEEDED(N, threads);
torch::Tensor bitfield = torch::empty(
{N,}, data.options().dtype(torch::kUInt8));
AT_DISPATCH_FLOATING_TYPES_AND_HALF(
data.scalar_type(), "packbits",
([&] {
kernel_packbits<scalar_t><<<blocks, threads>>>(
N,
threshold,
data.data_ptr<scalar_t>(),
bitfield.data_ptr<uint8_t>()
);
})
);
return bitfield;
}
+68
View File
@@ -0,0 +1,68 @@
#include "include/helpers.h"
torch::Tensor packbits(
const torch::Tensor data, const float threshold
) {};
std::vector<torch::Tensor> ray_aabb_intersect(
const torch::Tensor rays_o,
const torch::Tensor rays_d,
const torch::Tensor aabb
) {};
torch::Tensor morton3D(const torch::Tensor coords) {};
torch::Tensor morton3D_invert(const torch::Tensor indices) {};
std::vector<torch::Tensor> raymarching(
// rays
const torch::Tensor rays_o,
const torch::Tensor rays_d,
const torch::Tensor t_min,
const torch::Tensor t_max,
// density grid
const float grid_center,
const float grid_scale,
const int grid_cascades,
const int grid_size,
const torch::Tensor grid_bitfield,
// sampling args
const int max_total_samples,
const int num_steps,
const float cone_angle,
const float step_scale
) {};
std::vector<torch::Tensor> volumetric_rendering_forward(
torch::Tensor packed_info,
torch::Tensor starts,
torch::Tensor ends,
torch::Tensor sigmas,
torch::Tensor rgbs
) {};
std::vector<torch::Tensor> volumetric_rendering_backward(
torch::Tensor accumulated_weight,
torch::Tensor accumulated_depth,
torch::Tensor accumulated_color,
torch::Tensor grad_weight,
torch::Tensor grad_depth,
torch::Tensor grad_color,
torch::Tensor packed_info,
torch::Tensor starts,
torch::Tensor ends,
torch::Tensor sigmas,
torch::Tensor rgbs
) {};
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
{
m.def("packbits", &packbits);
m.def("ray_aabb_intersect", &ray_aabb_intersect);
m.def("morton3D", &morton3D);
m.def("morton3D_invert", &morton3D_invert);
m.def("raymarching", &raymarching);
m.def("volumetric_rendering_forward", &volumetric_rendering_forward);
m.def("volumetric_rendering_backward", &volumetric_rendering_backward);
}
+68
View File
@@ -0,0 +1,68 @@
#include "include/helpers_cuda.h"
torch::Tensor packbits(
const torch::Tensor data, const float threshold
);
std::vector<torch::Tensor> ray_aabb_intersect(
const torch::Tensor rays_o,
const torch::Tensor rays_d,
const torch::Tensor aabb
);
torch::Tensor morton3D(const torch::Tensor coords);
torch::Tensor morton3D_invert(const torch::Tensor indices);
std::vector<torch::Tensor> raymarching(
// rays
const torch::Tensor rays_o,
const torch::Tensor rays_d,
const torch::Tensor t_min,
const torch::Tensor t_max,
// density grid
const float grid_center,
const float grid_scale,
const int grid_cascades,
const int grid_size,
const torch::Tensor grid_bitfield,
// sampling args
const int max_total_samples,
const int num_steps,
const float cone_angle,
const float step_scale
);
std::vector<torch::Tensor> volumetric_rendering_forward(
torch::Tensor packed_info,
torch::Tensor starts,
torch::Tensor ends,
torch::Tensor sigmas,
torch::Tensor rgbs
);
std::vector<torch::Tensor> volumetric_rendering_backward(
torch::Tensor accumulated_weight,
torch::Tensor accumulated_depth,
torch::Tensor accumulated_color,
torch::Tensor grad_weight,
torch::Tensor grad_depth,
torch::Tensor grad_color,
torch::Tensor packed_info,
torch::Tensor starts,
torch::Tensor ends,
torch::Tensor sigmas,
torch::Tensor rgbs
);
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
{
m.def("packbits", &packbits);
m.def("ray_aabb_intersect", &ray_aabb_intersect);
m.def("morton3D", &morton3D);
m.def("morton3D_invert", &morton3D_invert);
m.def("raymarching", &raymarching);
m.def("volumetric_rendering_forward", &volumetric_rendering_forward);
m.def("volumetric_rendering_backward", &volumetric_rendering_backward);
}
+347
View File
@@ -0,0 +1,347 @@
#include "include/helpers_cuda.h"
inline __device__ float min_step_size(uint32_t num_steps) {
return __SQRT3() / num_steps;
}
// Maximum step size is the width of the coarsest gridsize cell.
inline __device__ float max_step_size(uint32_t grid_cascades, uint32_t grid_size) {
// Note(ruilongli): use mip=0 step size?
return __SQRT3() * (1 << (grid_cascades-1)) / grid_size;
}
// Perform fixed-size stepping in unit-cube scenes (like original NeRF) and exponential
// stepping in larger scenes.
inline __device__ float calc_dt(float t, float cone_angle, float dt_min, float dt_max) {
// TODO(ruilongli): scene_scale related to cone_angle?
return __clamp(t * cone_angle, dt_min, dt_max);
}
inline __device__ int mip_from_pos(float x, float y, float z, uint32_t grid_cascades, float grid_center, float grid_scale) {
float maxval = fmaxf(fmaxf(fabsf(x - grid_center), fabsf(y - grid_center)), fabsf(z - grid_center)) / grid_scale;
int exponent; frexpf(maxval, &exponent);
return min(grid_cascades-1, max(0, exponent+1));
}
inline __device__ int mip_from_dt(
float x, float y, float z, uint32_t grid_cascades, float dt, int grid_size, float grid_center, float grid_scale
) {
int mip = mip_from_pos(x, y, z, grid_cascades, grid_center, grid_scale);
dt *= 2 * grid_size;
if (dt<1.f) return mip; // exponent would be zero
int exponent; frexpf(dt, &exponent);
return min(grid_cascades-1, max(exponent, mip));
}
inline __device__ uint32_t grid_mip_offset(uint32_t mip, int grid_size) {
return (grid_size * grid_size * grid_size) * mip;
}
inline __device__ uint32_t cascaded_grid_idx_at(
float x, float y, float z, uint32_t mip, int grid_size, float grid_center, float grid_scale
) {
float mip_scale = scalbnf(1.0f, -mip) / grid_scale;
int ix = (int)((mip_scale * (x - grid_center) + 0.5f) * grid_size);
int iy = (int)((mip_scale * (y - grid_center) + 0.5f) * grid_size);
int iz = (int)((mip_scale * (z - grid_center) + 0.5f) * grid_size);
// printf("[input] x %f, y %f, z %f, mip %d, grid_size %d, grid_center %f\n", x, y, z, mip, grid_size, grid_center);
// printf("[output] mip_scale %f, ix %d iy %d, iz %d\n", mip_scale, ix, iy, iz);
uint32_t idx = __morton3D(
__clamp(ix, 0, grid_size-1),
__clamp(iy, 0, grid_size-1),
__clamp(iz, 0, grid_size-1)
);
return idx;
}
inline __device__ bool grid_occupied_at(
float x, float y, float z,
const uint8_t* grid_bitfield,
uint32_t mip, int grid_size, float grid_center, float grid_scale
) {
uint32_t idx = (
cascaded_grid_idx_at(x, y, z, mip, grid_size, grid_center, grid_scale)
+ grid_mip_offset(mip, grid_size)
);
return grid_bitfield[idx/8] & (1<<(idx%8));
}
inline __device__ float distance_to_next_voxel(
float x, float y, float z,
float dir_x, float dir_y, float dir_z,
float idir_x, float idir_y, float idir_z,
float res
) { // dda like step
// TODO: warning: expression has no effect?
x, y, z = res * x, res * y, res * z;
float tx = (floorf(x + 0.5f + 0.5f * __sign(dir_x)) - x) * idir_x;
float ty = (floorf(y + 0.5f + 0.5f * __sign(dir_y)) - y) * idir_y;
float tz = (floorf(z + 0.5f + 0.5f * __sign(dir_z)) - z) * idir_z;
float t = min(min(tx, ty), tz);
return fmaxf(t / res, 0.0f);
}
inline __device__ float advance_to_next_voxel(
float t,
float x, float y, float z,
float dir_x, float dir_y, float dir_z,
float idir_x, float idir_y, float idir_z,
float res, float dt_min) {
// Regular stepping (may be slower but matches non-empty space)
float t_target = t + distance_to_next_voxel(
x, y, z, dir_x, dir_y, dir_z, idir_x, idir_y, idir_z, res
);
do {
t += dt_min;
} while (t < t_target);
return t;
}
template <typename scalar_t>
__global__ void kernel_raymarching(
// rays info
const uint32_t n_rays,
const scalar_t* rays_o,
const scalar_t* rays_d,
const scalar_t* t_min,
const scalar_t* t_max,
// density grid
const float grid_center,
const float grid_scale,
const int grid_cascades,
const int grid_size,
const uint8_t* grid_bitfield,
// sampling
const int max_total_samples,
const int num_steps, // default 1024
const float cone_angle, // default 0. for nerf-syn and 1/256 for large scene
const float step_scale,
int* numsteps_counter,
int* rays_counter,
int* packed_info_out,
scalar_t* origins_out,
scalar_t* dirs_out,
scalar_t* starts_out,
scalar_t* ends_out
) {
CUDA_GET_THREAD_ID(i, n_rays);
// locate
rays_o += i * 3;
rays_d += i * 3;
t_min += i;
t_max += i;
const float ox = rays_o[0], oy = rays_o[1], oz = rays_o[2];
const float dx = rays_d[0], dy = rays_d[1], dz = rays_d[2];
const float rdx = 1 / dx, rdy = 1 / dy, rdz = 1 / dz;
const float near = t_min[0], far = t_max[0];
// TODO(ruilongli): perturb `near` as in ngp_pl?
// TODO(ruilongli): pre-compute `dt_min`, `dt_max` as it is a constant?
float dt_min = min_step_size(num_steps) * step_scale;
float dt_max = max_step_size(grid_cascades, grid_size) * grid_scale;
// first pass to compute an accurate number of steps
uint32_t j = 0;
float t0 = near;
float dt = calc_dt(t0, cone_angle, dt_min, dt_max);
float t1 = t0 + dt;
float t_mid = (t0 + t1) * 0.5f;
while (t_mid < far && j < num_steps) {
// current center
const float x = ox + t_mid * dx;
const float y = oy + t_mid * dy;
const float z = oz + t_mid * dz;
uint32_t mip = mip_from_dt(x, y, z, grid_cascades, dt, grid_size, grid_center, grid_scale);
if (grid_occupied_at(x, y, z, grid_bitfield, mip, grid_size, grid_center, grid_scale)) {
++j;
// march to next sample
t0 = t1;
dt = calc_dt(t0, cone_angle, dt_min, dt_max);
t1 = t0 + dt;
t_mid = (t0 + t1) * 0.5f;
}
else {
// march to next sample
float res = (grid_size >> mip) * grid_scale;
t_mid = advance_to_next_voxel(
t_mid, x, y, z, dx, dy, dz, rdx, rdy, rdz, res, dt_min
);
dt = calc_dt(t_mid, cone_angle, dt_min, dt_max);
t0 = t_mid - dt * 0.5f;
t1 = t_mid + dt * 0.5f;
}
}
if (j == 0) return;
uint32_t numsteps = j;
uint32_t base = atomicAdd(numsteps_counter, numsteps);
if (base + numsteps > max_total_samples) return;
// locate
origins_out += base * 3;
dirs_out += base * 3;
starts_out += base;
ends_out += base;
uint32_t ray_idx = atomicAdd(rays_counter, 1);
packed_info_out[ray_idx * 3 + 0] = i; // ray idx in {rays_o, rays_d}
packed_info_out[ray_idx * 3 + 1] = base; // point idx start.
packed_info_out[ray_idx * 3 + 2] = numsteps; // point idx shift.
// Second round
j = 0;
t0 = near;
dt = calc_dt(t0, cone_angle, dt_min, dt_max);
t1 = t0 + dt;
t_mid = (t0 + t1) / 2.;
while (t_mid < far && j < num_steps) {
// current center
const float x = ox + t_mid * dx;
const float y = oy + t_mid * dy;
const float z = oz + t_mid * dz;
uint32_t mip = mip_from_dt(x, y, z, grid_cascades, dt, grid_size, grid_center, grid_scale);
if (grid_occupied_at(x, y, z, grid_bitfield, mip, grid_size, grid_center, grid_scale)) {
origins_out[j * 3 + 0] = ox;
origins_out[j * 3 + 1] = oy;
origins_out[j * 3 + 2] = oz;
dirs_out[j * 3 + 0] = dx;
dirs_out[j * 3 + 1] = dy;
dirs_out[j * 3 + 2] = dz;
starts_out[j] = t0;
ends_out[j] = t1;
++j;
// march to next sample
t0 = t1;
dt = calc_dt(t0, cone_angle, dt_min, dt_max);
t1 = t0 + dt;
t_mid = (t0 + t1) * 0.5f;
}
else {
// march to next sample
float res = (grid_size >> mip) * grid_scale;
t_mid = advance_to_next_voxel(
t_mid, x, y, z, dx, dy, dz, rdx, rdy, rdz, res, dt_min
);
dt = calc_dt(t_mid, cone_angle, dt_min, dt_max);
t0 = t_mid - dt * 0.5f;
t1 = t_mid + dt * 0.5f;
}
}
return;
}
/**
* @brief Sample points by ray marching.
*
* @param rays_o Ray origins Shape of [n_rays, 3].
* @param rays_d Normalized ray directions. Shape of [n_rays, 3].
* @param t_min Near planes of rays. Shape of [n_rays].
* @param t_max Far planes of rays. Shape of [n_rays].
* @param grid_center Density grid center. TODO: support 3-dims.
* @param grid_scale Density grid base level scale. TODO: support 3-dims.
* @param grid_cascades Density grid levels.
* @param grid_size Density grid resolution.
* @param grid_bitfield Density grid uint8 bit field.
* @param max_total_samples Maximum total number of samples in this batch.
* @param num_steps Used to define the minimal step size: SQRT3() / num_steps.
* @param cone_angle 0. for nerf-synthetic and 1./256 for real scenes.
* @param step_scale Scale up the step size by this much. Usually equals to scene scale.
* @return std::vector<torch::Tensor>
* - packed_info: Stores how to index the ray samples from the returned values.
* Shape of [n_rays, 3]. First value is the ray index. Second value is the sample
* start index in the results for this ray. Third value is the number of samples for
* this ray. Note for rays that have zero samples, we simply skip them so the `packed_info`
* has some zero padding in the end.
* - origins: Ray origins for those samples. [max_total_samples, 3]
* - dirs: Ray directions for those samples. [max_total_samples, 3]
* - starts: Where the frustum-shape sample starts along a ray. [max_total_samples, 1]
* - ends: Where the frustum-shape sample ends along a ray. [max_total_samples, 1]
*/
std::vector<torch::Tensor> raymarching(
// rays
const torch::Tensor rays_o,
const torch::Tensor rays_d,
const torch::Tensor t_min,
const torch::Tensor t_max,
// density grid
const float grid_center,
const float grid_scale,
const int grid_cascades,
const int grid_size,
const torch::Tensor grid_bitfield,
// sampling args
const int max_total_samples,
const int num_steps,
const float cone_angle,
const float step_scale
) {
DEVICE_GUARD(rays_o);
CHECK_INPUT(rays_o);
CHECK_INPUT(rays_d);
CHECK_INPUT(t_min);
CHECK_INPUT(t_max);
CHECK_INPUT(grid_bitfield);
const int n_rays = rays_o.size(0);
const int threads = 256;
const int blocks = CUDA_N_BLOCKS_NEEDED(n_rays, threads);
// helper counter
torch::Tensor numsteps_counter = torch::zeros(
{1}, rays_o.options().dtype(torch::kInt32));
torch::Tensor rays_counter = torch::zeros(
{1}, rays_o.options().dtype(torch::kInt32));
// output samples
torch::Tensor packed_info = torch::zeros(
{n_rays, 3}, rays_o.options().dtype(torch::kInt32)); // ray_id, sample_id, num_samples
torch::Tensor origins = torch::zeros({max_total_samples, 3}, rays_o.options());
torch::Tensor dirs = torch::zeros({max_total_samples, 3}, rays_o.options());
torch::Tensor starts = torch::zeros({max_total_samples, 1}, rays_o.options());
torch::Tensor ends = torch::zeros({max_total_samples, 1}, rays_o.options());
AT_DISPATCH_FLOATING_TYPES_AND_HALF(
rays_o.scalar_type(),
"raymarching_train",
([&]
{ kernel_raymarching<scalar_t><<<blocks, threads>>>(
// rays
n_rays,
rays_o.data_ptr<scalar_t>(),
rays_d.data_ptr<scalar_t>(),
t_min.data_ptr<scalar_t>(),
t_max.data_ptr<scalar_t>(),
// density grid
grid_center,
grid_scale,
grid_cascades,
grid_size,
grid_bitfield.data_ptr<uint8_t>(),
// sampling args
max_total_samples,
num_steps,
cone_angle,
step_scale,
numsteps_counter.data_ptr<int>(), // total samples.
rays_counter.data_ptr<int>(), // total rays.
packed_info.data_ptr<int>(),
origins.data_ptr<scalar_t>(),
dirs.data_ptr<scalar_t>(),
starts.data_ptr<scalar_t>(),
ends.data_ptr<scalar_t>()
);
}));
return {packed_info, origins, dirs, starts, ends};
}
+260
View File
@@ -0,0 +1,260 @@
#include "include/helpers_cuda.h"
template <typename scalar_t>
__global__ void volumetric_rendering_forward_kernel(
const uint32_t n_rays,
const int* packed_info, // input ray & point indices.
const scalar_t* starts, // input start t
const scalar_t* ends, // input end t
const scalar_t* sigmas, // input density after activation
const scalar_t* rgbs, // input rgb after activation
// should be all-zero initialized
scalar_t* accumulated_weight, // output
scalar_t* accumulated_depth, // output
scalar_t* accumulated_color, // output
bool* mask // output
) {
CUDA_GET_THREAD_ID(thread_id, n_rays);
// locate
const int i = packed_info[thread_id * 3 + 0]; // ray idx in {rays_o, rays_d}
const int base = packed_info[thread_id * 3 + 1]; // point idx start.
const int numsteps = packed_info[thread_id * 3 + 2]; // point idx shift.
if (numsteps == 0) return;
starts += base;
ends += base;
sigmas += base;
rgbs += base * 3;
accumulated_weight += i;
accumulated_depth += i;
accumulated_color += i * 3;
mask += i;
// accumulated rendering
scalar_t T = 1.f;
scalar_t EPSILON = 1e-4f;
int j = 0;
for (; j < numsteps; ++j) {
if (T < EPSILON) {
break;
}
const scalar_t delta = ends[j] - starts[j];
const scalar_t t = (ends[j] + starts[j]) * 0.5f;
const scalar_t alpha = 1.f - __expf(-sigmas[j] * delta);
const scalar_t weight = alpha * T;
accumulated_weight[0] += weight;
accumulated_depth[0] += weight * t;
accumulated_color[0] += weight * rgbs[j * 3 + 0];
accumulated_color[1] += weight * rgbs[j * 3 + 1];
accumulated_color[2] += weight * rgbs[j * 3 + 2];
T *= (1.f - alpha);
}
mask[0] = true;
}
template <typename scalar_t>
__global__ void volumetric_rendering_backward_kernel(
const uint32_t n_rays,
const int* packed_info, // input ray & point indices.
const scalar_t* starts, // input start t
const scalar_t* ends, // input end t
const scalar_t* sigmas, // input density after activation
const scalar_t* rgbs, // input rgb after activation
const scalar_t* accumulated_weight, // forward output
const scalar_t* accumulated_depth, // forward output
const scalar_t* accumulated_color, // forward output
const scalar_t* grad_weight, // input
const scalar_t* grad_depth, // input
const scalar_t* grad_color, // input
scalar_t* grad_sigmas, // output
scalar_t* grad_rgbs // output
) {
CUDA_GET_THREAD_ID(thread_id, n_rays);
// locate
const int i = packed_info[thread_id * 3 + 0]; // ray idx in {rays_o, rays_d}
const int base = packed_info[thread_id * 3 + 1]; // point idx start.
const int numsteps = packed_info[thread_id * 3 + 2]; // point idx shift.
if (numsteps == 0) return;
starts += base;
ends += base;
sigmas += base;
rgbs += base * 3;
grad_sigmas += base;
grad_rgbs += base * 3;
accumulated_weight += i;
accumulated_depth += i;
accumulated_color += i * 3;
grad_weight += i;
grad_depth += i;
grad_color += i * 3;
// backward of accumulated rendering
scalar_t T = 1.f;
scalar_t EPSILON = 1e-4f;
int j = 0;
scalar_t r = 0, g = 0, b = 0, d = 0;
for (; j < numsteps; ++j) {
if (T < EPSILON) {
break;
}
const scalar_t delta = ends[j] - starts[j];
const scalar_t t = (ends[j] + starts[j]) * 0.5f;
const scalar_t alpha = 1.f - __expf(-sigmas[j] * delta);
const scalar_t weight = alpha * T;
r += weight * rgbs[j * 3 + 0];
g += weight * rgbs[j * 3 + 1];
b += weight * rgbs[j * 3 + 2];
d += weight * t;
T *= (1.f - alpha);
grad_rgbs[j * 3 + 0] = grad_color[0] * weight;
grad_rgbs[j * 3 + 1] = grad_color[1] * weight;
grad_rgbs[j * 3 + 2] = grad_color[2] * weight;
grad_sigmas[j] = delta * (
grad_color[0] * (T * rgbs[j * 3 + 0] - (accumulated_color[0] - r)) +
grad_color[1] * (T * rgbs[j * 3 + 1] - (accumulated_color[1] - g)) +
grad_color[2] * (T * rgbs[j * 3 + 2] - (accumulated_color[2] - b)) +
grad_weight[0] * (1.f - accumulated_weight[0]) +
grad_depth[0] * (t * T - (accumulated_depth[0] - d))
);
}
}
/**
* @brief Volumetric Rendering: Accumulating samples in the forward pass.
* The inputs, excepct for `sigmas` and `rgbs`, are the outputs of our
* cuda ray marching function in `raymarching.cu`
*
* @param packed_info Stores how to index the ray samples from the returned values.
* Shape of [n_rays, 3]. First value is the ray index. Second value is the sample
* start index in the results for this ray. Third value is the number of samples for
* this ray. Note for rays that have zero samples, we simply skip them so the `packed_info`
* has some zero padding in the end.
* @param starts: Where the frustum-shape sample starts along a ray. [total_samples, 1]
* @param ends: Where the frustum-shape sample ends along a ray. [total_samples, 1]
* @param sigmas Densities at those samples. [total_samples, 1]
* @param rgbs RGBs at those samples. [total_samples, 3]
* @return std::vector<torch::Tensor>
* - accumulated_weight: Ray opacity. [n_rays, 1]
* - accumulated_depth: Ray depth. [n_rays, 1]
* - accumulated_color: Ray color. [n_rays, 3]
* - mask: Boolen value store if this ray has valid samples from packed_info. [n_rays]
*/
std::vector<torch::Tensor> volumetric_rendering_forward(
torch::Tensor packed_info,
torch::Tensor starts,
torch::Tensor ends,
torch::Tensor sigmas,
torch::Tensor rgbs
) {
DEVICE_GUARD(packed_info);
CHECK_INPUT(packed_info);
CHECK_INPUT(starts);
CHECK_INPUT(ends);
CHECK_INPUT(sigmas);
CHECK_INPUT(rgbs);
TORCH_CHECK(packed_info.ndimension() == 2 & packed_info.size(1) == 3);
TORCH_CHECK(starts.ndimension() == 2 & starts.size(1) == 1);
TORCH_CHECK(ends.ndimension() == 2 & ends.size(1) == 1);
TORCH_CHECK(sigmas.ndimension() == 2 & sigmas.size(1) == 1);
TORCH_CHECK(rgbs.ndimension() == 2 & rgbs.size(1) == 3);
const uint32_t n_rays = packed_info.size(0);
const int threads = 256;
const int blocks = CUDA_N_BLOCKS_NEEDED(n_rays, threads);
// outputs
torch::Tensor accumulated_weight = torch::zeros({n_rays, 1}, sigmas.options());
torch::Tensor accumulated_depth = torch::zeros({n_rays, 1}, sigmas.options());
torch::Tensor accumulated_color = torch::zeros({n_rays, 3}, sigmas.options());
// The rays that are not skipped during sampling.
torch::Tensor mask = torch::zeros({n_rays}, sigmas.options().dtype(torch::kBool));
AT_DISPATCH_FLOATING_TYPES_AND_HALF(
sigmas.scalar_type(),
"volumetric_rendering_forward",
([&]
{ volumetric_rendering_forward_kernel<scalar_t><<<blocks, threads>>>(
n_rays,
packed_info.data_ptr<int>(),
starts.data_ptr<scalar_t>(),
ends.data_ptr<scalar_t>(),
sigmas.data_ptr<scalar_t>(),
rgbs.data_ptr<scalar_t>(),
accumulated_weight.data_ptr<scalar_t>(),
accumulated_depth.data_ptr<scalar_t>(),
accumulated_color.data_ptr<scalar_t>(),
mask.data_ptr<bool>()
);
}));
return {accumulated_weight, accumulated_depth, accumulated_color, mask};
}
/**
* @brief Volumetric Rendering: Accumulating samples in the backward pass.
*/
std::vector<torch::Tensor> volumetric_rendering_backward(
torch::Tensor accumulated_weight,
torch::Tensor accumulated_depth,
torch::Tensor accumulated_color,
torch::Tensor grad_weight,
torch::Tensor grad_depth,
torch::Tensor grad_color,
torch::Tensor packed_info,
torch::Tensor starts,
torch::Tensor ends,
torch::Tensor sigmas,
torch::Tensor rgbs
) {
DEVICE_GUARD(packed_info);
const uint32_t n_rays = packed_info.size(0);
const int threads = 256;
const int blocks = CUDA_N_BLOCKS_NEEDED(n_rays, threads);
// outputs
torch::Tensor grad_sigmas = torch::zeros(sigmas.sizes(), sigmas.options());
torch::Tensor grad_rgbs = torch::zeros(rgbs.sizes(), rgbs.options());
AT_DISPATCH_FLOATING_TYPES_AND_HALF(
sigmas.scalar_type(),
"volumetric_rendering_backward",
([&]
{ volumetric_rendering_backward_kernel<scalar_t><<<blocks, threads>>>(
n_rays,
packed_info.data_ptr<int>(),
starts.data_ptr<scalar_t>(),
ends.data_ptr<scalar_t>(),
sigmas.data_ptr<scalar_t>(),
rgbs.data_ptr<scalar_t>(),
accumulated_weight.data_ptr<scalar_t>(),
accumulated_depth.data_ptr<scalar_t>(),
accumulated_color.data_ptr<scalar_t>(),
grad_weight.data_ptr<scalar_t>(),
grad_depth.data_ptr<scalar_t>(),
grad_color.data_ptr<scalar_t>(),
grad_sigmas.data_ptr<scalar_t>(),
grad_rgbs.data_ptr<scalar_t>()
);
}));
return {grad_sigmas, grad_rgbs};
}