Make DensityGrid plug-and-play for the base Graph and the base Sampler. (#205)

This commit is contained in:
Ruilong Li(李瑞龙) authored and GitHub committed 2022-07-26 18:02:18 -07:00
1 parent 512842938a
commit 31c2c2608d
11 files changed
+327 -99

No files matched your search

+16
View File
@@ -25,6 +25,7 @@ morton3D_invert = _C.morton3D_invert
raymarching = _C.raymarching
volumetric_rendering_forward = _C.volumetric_rendering_forward
volumetric_rendering_backward = _C.volumetric_rendering_backward
occupancy_query = _C.occupancy_query
# pylint: disable=abstract-method,arguments-differ
class VolumeRenderer(torch.autograd.Function):
@@ -77,3 +78,18 @@ class VolumeRenderer(torch.autograd.Function):
)
# corresponds to the input argument list of forward()
return None, None, None, grad_sigmas, grad_rgbs
def unpackbits(x: torch.Tensor) -> torch.Tensor:
"""Unpack uint8 bits back to a boolen mask.
Args:
x: uint8 bit tensor with shape [N]
Returns:
unpacked boolen tensor with shape [N * 8]
"""
assert x.dtype == torch.uint8 and x.dim() == 1
bits = x.element_size() * 8
mask = 2 ** torch.arange(bits - 1, -1, -1).to(x)
return x.unsqueeze(-1).bitwise_and(mask).ne(0).flip(-1).bool().reshape(-1)
@@ -56,6 +56,18 @@ std::vector<torch::Tensor> volumetric_rendering_backward(
torch::Tensor rgbs
) {};
std::vector<torch::Tensor> occupancy_query(
// samples
const torch::Tensor positions,
const torch::Tensor deltas,
// density grid
const float grid_center,
const float grid_scale,
const int grid_cascades,
const int grid_size,
const torch::Tensor grid_bitfield
) {};
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
{
m.def("packbits", &packbits);
@@ -65,4 +77,5 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
m.def("raymarching", &raymarching);
m.def("volumetric_rendering_forward", &volumetric_rendering_forward);
m.def("volumetric_rendering_backward", &volumetric_rendering_backward);
m.def("occupancy_query", &occupancy_query);
}
@@ -56,6 +56,18 @@ std::vector<torch::Tensor> volumetric_rendering_backward(
torch::Tensor rgbs
);
std::vector<torch::Tensor> occupancy_query(
// samples
const torch::Tensor positions,
const torch::Tensor deltas,
// density grid
const float grid_center,
const float grid_scale,
const int grid_cascades,
const int grid_size,
const torch::Tensor grid_bitfield
);
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
{
m.def("packbits", &packbits);
@@ -65,4 +77,5 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
m.def("raymarching", &raymarching);
m.def("volumetric_rendering_forward", &volumetric_rendering_forward);
m.def("volumetric_rendering_backward", &volumetric_rendering_backward);
m.def("occupancy_query", &occupancy_query);
}
+157 -52
View File
@@ -15,44 +15,45 @@ inline __device__ float max_step_size(uint32_t grid_cascades, uint32_t grid_size
// 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);
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));
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));
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;
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;
// TODO(ruilongli): if the x, y, z is outside the aabb, it will be clipped into aabb!!! We should just return false
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;
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(
@@ -60,11 +61,11 @@ inline __device__ bool grid_occupied_at(
const uint8_t* grid_bitfield,
uint32_t mip, int grid_size, float grid_center, float grid_scale
) {
uint32_t idx = (
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));
return grid_bitfield[idx/8] & (1<<(idx%8));
}
inline __device__ float distance_to_next_voxel(
@@ -74,13 +75,13 @@ inline __device__ float distance_to_next_voxel(
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);
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);
return fmaxf(t / res, 0.0f);
}
inline __device__ float advance_to_next_voxel(
@@ -89,14 +90,14 @@ inline __device__ float advance_to_next_voxel(
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(
// 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;
do {
t += dt_min;
} while (t < t_target);
return t;
}
template <typename scalar_t>
@@ -143,10 +144,10 @@ __global__ void kernel_raymarching(
// 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;
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;
@@ -156,33 +157,33 @@ __global__ void kernel_raymarching(
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);
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;
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(
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);
uint32_t base = atomicAdd(numsteps_counter, numsteps);
if (base + numsteps > max_total_samples) return;
// locate
origins_out += base * 3;
dirs_out += base * 3;
@@ -191,13 +192,13 @@ __global__ void kernel_raymarching(
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 + 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;
t0 = near;
dt = calc_dt(t0, cone_angle, dt_min, dt_max);
t1 = t0 + dt;
t_mid = (t0 + t1) / 2.;
@@ -207,7 +208,7 @@ __global__ void kernel_raymarching(
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);
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;
@@ -220,25 +221,75 @@ __global__ void kernel_raymarching(
ends_out[j] = t1;
++j;
// march to next sample
t0 = t1;
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(
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;
}
template <typename scalar_t>
__global__ void kernel_occupancy_query(
// samples info
const uint32_t n_samples,
const scalar_t* positions,
const scalar_t* deltas,
// density grid
const float grid_center,
const float grid_scale,
const int grid_cascades,
const int grid_size,
const uint8_t* grid_bitfield,
// outputs
int32_t* mip_levels, // output mip level
int32_t* indices, // output indices
bool* occupancies // output occupancy
) {
CUDA_GET_THREAD_ID(i, n_samples);
// locate
positions += i * 3;
deltas += i;
mip_levels += i;
indices += i;
occupancies += i;
// current point
const float x = positions[0];
const float y = positions[1];
const float z = positions[2];
const float dt = deltas[0];
int32_t mip = mip_from_dt(x, y, z, grid_cascades, dt, grid_size, grid_center, grid_scale);
mip_levels[0] = mip;
int32_t idx = (
cascaded_grid_idx_at(x, y, z, mip, grid_size, grid_center, grid_scale)
+ grid_mip_offset(mip, grid_size)
);
indices[0] = idx;
if (grid_bitfield) {
bool occ = grid_bitfield[idx/8] & (1<<(idx%8));
occupancies[0] = occ;
}
return;
}
/**
* @brief Sample points by ray marching.
*
@@ -344,4 +395,58 @@ std::vector<torch::Tensor> raymarching(
}));
return {packed_info, origins, dirs, starts, ends};
}
}
std::vector<torch::Tensor> occupancy_query(
// samples
const torch::Tensor positions,
const torch::Tensor deltas,
// density grid
const float grid_center,
const float grid_scale,
const int grid_cascades,
const int grid_size,
const torch::Tensor grid_bitfield
) {
DEVICE_GUARD(positions);
CHECK_INPUT(positions);
CHECK_INPUT(deltas);
CHECK_INPUT(grid_bitfield);
const int n_samples = positions.size(0);
const int threads = 256;
const int blocks = CUDA_N_BLOCKS_NEEDED(n_samples, threads);
// outputs
torch::Tensor mip_levels = torch::empty({n_samples}, positions.options().dtype(torch::kInt32));
torch::Tensor indices = torch::empty({n_samples}, positions.options().dtype(torch::kInt32));
torch::Tensor occupancies = torch::empty({n_samples}, positions.options().dtype(torch::kBool));
AT_DISPATCH_FLOATING_TYPES_AND_HALF(
positions.scalar_type(),
"occupancy_query",
([&]
{ kernel_occupancy_query<scalar_t><<<blocks, threads>>>(
// samples
n_samples,
positions.data_ptr<scalar_t>(),
deltas.data_ptr<scalar_t>(),
// density grid
grid_center,
grid_scale,
grid_cascades,
grid_size,
grid_bitfield.data_ptr<uint8_t>(),
// outputs
mip_levels.data_ptr<int32_t>(),
indices.data_ptr<int32_t>(),
occupancies.data_ptr<bool>()
);
}));
return {mip_levels, indices, occupancies};
}
+19 -19
View File
@@ -35,24 +35,24 @@ __global__ void volumetric_rendering_forward_kernel(
// accumulated rendering
scalar_t T = 1.f;
scalar_t EPSILON = 1e-4f;
int j = 0;
scalar_t EPSILON = 1e-4f;
int j = 0;
for (; j < numsteps; ++j) {
if (T < EPSILON) {
break;
}
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;
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);
}
T *= (1.f - alpha);
}
mask[0] = true;
}
@@ -100,25 +100,25 @@ __global__ void volumetric_rendering_backward_kernel(
// backward of accumulated rendering
scalar_t T = 1.f;
scalar_t EPSILON = 1e-4f;
int j = 0;
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;
}
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;
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);
T *= (1.f - alpha);
grad_rgbs[j * 3 + 0] = grad_color[0] * weight;
grad_rgbs[j * 3 + 1] = grad_color[1] * weight;
@@ -131,7 +131,7 @@ __global__ void volumetric_rendering_backward_kernel(
grad_weight[0] * (1.f - accumulated_weight[0]) +
grad_depth[0] * (t * T - (accumulated_depth[0] - d))
);
}
}
}
/**