__init__.py 21 KB
Newer Older
Nianchen Deng's avatar
sync    
Nianchen Deng committed
1
2
3
4
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
Nianchen Deng's avatar
sync    
Nianchen Deng committed
5
6
7
#
# To install the _ext library, run the following command:
# > python setup.py build_ext --inplace
Nianchen Deng's avatar
sync    
Nianchen Deng committed
8
9
10
11
12
13
14
15
16
17
18
19

''' Modified based on: https://github.com/erikwijmans/Pointnet2_PyTorch '''
from __future__ import (
    division,
    absolute_import,
    with_statement,
    print_function,
    unicode_literals,
)
import torch
import torch.nn.functional as F
import numpy as np
Nianchen Deng's avatar
sync    
Nianchen Deng committed
20
21
22
23
from torch.autograd import Function
from torch.autograd.function import FunctionCtx, once_differentiable

import clib._ext as _ext
Nianchen Deng's avatar
sync    
Nianchen Deng committed
24
from utils.geometry import discretize_points
Nianchen Deng's avatar
sync    
Nianchen Deng committed
25
from utils import math
Nianchen Deng's avatar
sync    
Nianchen Deng committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49


class BallRayIntersect(Function):
    @staticmethod
    def forward(ctx, radius, n_max, points, ray_start, ray_dir):
        inds, min_depth, max_depth = _ext.ball_intersect(
            ray_start.float(), ray_dir.float(), points.float(), radius, n_max)
        min_depth = min_depth.type_as(ray_start)
        max_depth = max_depth.type_as(ray_start)

        ctx.mark_non_differentiable(inds)
        ctx.mark_non_differentiable(min_depth)
        ctx.mark_non_differentiable(max_depth)
        return inds, min_depth, max_depth

    @staticmethod
    def backward(ctx, a, b, c):
        return None, None, None, None, None


ball_ray_intersect = BallRayIntersect.apply


def aabb_ray_intersect(voxelsize: float, n_max: int, points: torch.Tensor, ray_start: torch.Tensor,
Nianchen Deng's avatar
sync    
Nianchen Deng committed
50
                       ray_dir: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
Nianchen Deng's avatar
sync    
Nianchen Deng committed
51
52
53
54
55
56
57
58
59
60
61
62
    """
    AABB-Ray intersect test

    :param voxelsize `float`: size of a voxel
    :param n_max `int`: maximum number of hits
    :param points `Tensor(M, 3)`: voxels' centers
    :param ray_start `Tensor(S, N, 3)`: rays' start positions
    :param ray_dir `Tensor(S, N, 3)`: rays' directions
    :return `Tensor(S, N, n_max)`: indices of intersected voxels or -1
    :return `Tensor(S, N, n_max)`: min depths of every intersected voxels
    :return `Tensor(S, N, n_max)`: max depths of every intersected voxels
    """
Nianchen Deng's avatar
sync    
Nianchen Deng committed
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
    # HACK: speed-up ray-voxel intersection by batching...
    G = min(2048, int(2e9 / points.numel()))   # HACK: avoid out-of-memory
    S, N = ray_start.shape[:2]
    K = math.ceil(N / G)
    G, K = 1, N  # HACK
    H = K * G
    if H > N:
        ray_start = torch.cat([ray_start, ray_start[:, :H - N]], 1)
        ray_dir = torch.cat([ray_dir, ray_dir[:, :H - N]], 1)
    ray_start = ray_start.reshape(S * G, K, 3)
    ray_dir = ray_dir.reshape(S * G, K, 3)
    points = points[None].expand(S * G, *points.size()).contiguous()

    inds, min_depth, max_depth = _ext.aabb_intersect(
        ray_start.float(), ray_dir.float(), points.float(), voxelsize, n_max)
    min_depth = min_depth.type_as(ray_start)
    max_depth = max_depth.type_as(ray_start)

    inds = inds.reshape(S, H, -1)
    min_depth = min_depth.reshape(S, H, -1)
    max_depth = max_depth.reshape(S, H, -1)
    if H > N:
        inds = inds[:, :N]
        min_depth = min_depth[:, :N]
        max_depth = max_depth[:, :N]

    return inds, min_depth, max_depth
Nianchen Deng's avatar
sync    
Nianchen Deng committed
90
91
92
93
94
95
96
97
98


class SparseVoxelOctreeRayIntersect(Function):
    @staticmethod
    def forward(ctx, voxelsize, n_max, points, children, ray_start, ray_dir):
        # HACK: avoid out-of-memory
        G = min(2048, int(2 * 10 ** 9 / (points.numel() + children.numel())))
        S, N = ray_start.shape[:2]
        K = int(np.ceil(N / G))
Nianchen Deng's avatar
sync    
Nianchen Deng committed
99
        G, K = 1, N  # HACK
Nianchen Deng's avatar
sync    
Nianchen Deng committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
        H = K * G
        if H > N:
            ray_start = torch.cat([ray_start, ray_start[:, :H - N]], 1)
            ray_dir = torch.cat([ray_dir, ray_dir[:, :H - N]], 1)
        ray_start = ray_start.reshape(S * G, K, 3)
        ray_dir = ray_dir.reshape(S * G, K, 3)
        points = points[None].expand(S * G, *points.size()).contiguous()
        children = children[None].expand(S * G, *children.size()).contiguous()
        inds, min_depth, max_depth = _ext.svo_intersect(
            ray_start.float(), ray_dir.float(), points.float(), children.int(), voxelsize, n_max)

        min_depth = min_depth.type_as(ray_start)
        max_depth = max_depth.type_as(ray_start)

        inds = inds.reshape(S, H, -1)
        min_depth = min_depth.reshape(S, H, -1)
        max_depth = max_depth.reshape(S, H, -1)
        if H > N:
            inds = inds[:, :N]
            min_depth = min_depth[:, :N]
            max_depth = max_depth[:, :N]

        ctx.mark_non_differentiable(inds)
        ctx.mark_non_differentiable(min_depth)
        ctx.mark_non_differentiable(max_depth)
        return inds, min_depth, max_depth

    @staticmethod
    def backward(ctx, a, b, c):
        return None, None, None, None, None


def octree_ray_intersect(voxelsize: float, n_max: int, points: torch.Tensor, children: torch.Tensor,
Nianchen Deng's avatar
sync    
Nianchen Deng committed
133
                         ray_start: torch.Tensor, ray_dir: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
Nianchen Deng's avatar
sync    
Nianchen Deng committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
    """
    Octree-Ray intersect test

    :param voxelsize `float`: size of a voxel
    :param n_max `int`: maximum number of hits
    :param points `Tensor(M, 3)`: voxels' centers
    :param children `Tensor(M, 9)`: flattened octree structure
    :param ray_start `Tensor(S, N, 3)`: rays' start positions
    :param ray_dir `Tensor(S, N, 3)`: rays' directions
    :return `Tensor(S, N, n_max)`: indices of intersected voxels or -1
    :return `Tensor(S, N, n_max)`: min depths of every intersected voxels
    :return `Tensor(S, N, n_max)`: max depths of every intersected voxels
    """
    return SparseVoxelOctreeRayIntersect.apply(voxelsize, n_max, points, children, ray_start,
                                               ray_dir)


class TriangleRayIntersect(Function):
    @staticmethod
    def forward(ctx, cagesize, blur_ratio, n_max, points, faces, ray_start, ray_dir):
        # HACK: speed-up ray-voxel intersection by batching...
        G = min(2048, int(2 * 10 ** 9 / (3 * faces.numel())))   # HACK: avoid out-of-memory
        S, N = ray_start.shape[:2]
        K = int(np.ceil(N / G))
        H = K * G
        if H > N:
            ray_start = torch.cat([ray_start, ray_start[:, :H - N]], 1)
            ray_dir = torch.cat([ray_dir, ray_dir[:, :H - N]], 1)
        ray_start = ray_start.reshape(S * G, K, 3)
        ray_dir = ray_dir.reshape(S * G, K, 3)
        face_points = F.embedding(faces.reshape(-1, 3), points.reshape(-1, 3))
        face_points = face_points.unsqueeze(0).expand(S * G, *face_points.size()).contiguous()
        inds, depth, uv = _ext.triangle_intersect(
            ray_start.float(), ray_dir.float(), face_points.float(), cagesize, blur_ratio, n_max)
        depth = depth.type_as(ray_start)
        uv = uv.type_as(ray_start)

        inds = inds.reshape(S, H, -1)
        depth = depth.reshape(S, H, -1, 3)
        uv = uv.reshape(S, H, -1)
        if H > N:
            inds = inds[:, :N]
            depth = depth[:, :N]
            uv = uv[:, :N]

        ctx.mark_non_differentiable(inds)
        ctx.mark_non_differentiable(depth)
        ctx.mark_non_differentiable(uv)
        return inds, depth, uv

    @staticmethod
    def backward(ctx, a, b, c):
        return None, None, None, None, None, None


triangle_ray_intersect = TriangleRayIntersect.apply


class UniformRaySampling(Function):
    @staticmethod
    def forward(ctx, pts_idx, min_depth, max_depth, step_size, max_ray_length, deterministic=False):
        G, N, P = 256, pts_idx.size(0), pts_idx.size(1)
        H = int(np.ceil(N / G)) * G
        if H > N:
            pts_idx = torch.cat([pts_idx, pts_idx[:H - N]], 0)
            min_depth = torch.cat([min_depth, min_depth[:H - N]], 0)
            max_depth = torch.cat([max_depth, max_depth[:H - N]], 0)
        pts_idx = pts_idx.reshape(G, -1, P)
        min_depth = min_depth.reshape(G, -1, P)
        max_depth = max_depth.reshape(G, -1, P)

        # pre-generate noise
        max_steps = int(max_ray_length / step_size)
        max_steps = max_steps + min_depth.size(-1) * 2
        noise = min_depth.new_zeros(*min_depth.size()[:-1], max_steps)
        if deterministic:
            noise += 0.5
        else:
            noise = noise.uniform_()

        # call cuda function
        sampled_idx, sampled_depth, sampled_dists = _ext.uniform_ray_sampling(
            pts_idx, min_depth.float(), max_depth.float(), noise.float(), step_size, max_steps)
        sampled_depth = sampled_depth.type_as(min_depth)
        sampled_dists = sampled_dists.type_as(min_depth)

        sampled_idx = sampled_idx.reshape(H, -1)
        sampled_depth = sampled_depth.reshape(H, -1)
        sampled_dists = sampled_dists.reshape(H, -1)
        if H > N:
            sampled_idx = sampled_idx[: N]
            sampled_depth = sampled_depth[: N]
            sampled_dists = sampled_dists[: N]

        max_len = sampled_idx.ne(-1).sum(-1).max()
        sampled_idx = sampled_idx[:, :max_len]
        sampled_depth = sampled_depth[:, :max_len]
        sampled_dists = sampled_dists[:, :max_len]

        ctx.mark_non_differentiable(sampled_idx)
        ctx.mark_non_differentiable(sampled_depth)
        ctx.mark_non_differentiable(sampled_dists)
        return sampled_idx, sampled_depth, sampled_dists

    @staticmethod
    def backward(ctx, a, b, c):
        return None, None, None, None, None, None


def uniform_ray_sampling(pts_idx: torch.Tensor, min_depth: torch.Tensor, max_depth: torch.Tensor,
Nianchen Deng's avatar
sync    
Nianchen Deng committed
244
                         step_size: float, max_ray_length: float, deterministic: bool = False) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
Nianchen Deng's avatar
sync    
Nianchen Deng committed
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
    """
    Sample along rays uniformly

    :param pts_idx `Tensor(N, P)`: indices of voxels intersected with rays
    :param min_depth `Tensor(N, P)`: min depth of intersections of rays and voxels
    :param max_depth `Tensor(N, P)`: max depth of intersections of rays and voxels
    :param step_size `float`: size of sampling step
    :param max_ray_length `float`: maximum sampling depth along rays
    :param deterministic `bool`: (optional) sample deterministically (or randomly), defaults to False
    :return `Tensor(N, P')`: voxel indices of sampled points
    :return `Tensor(N, P')`: depth of sampled points
    :return `Tensor(N, P')`: length of sampled points
    """
    return UniformRaySampling.apply(pts_idx, min_depth, max_depth, step_size, max_ray_length,
                                    deterministic)


class InverseCDFRaySampling(Function):
    @staticmethod
    def forward(ctx, pts_idx, min_depth, max_depth, probs, steps, fixed_step_size=-1, deterministic=False):
        G, N, P = 200, pts_idx.size(0), pts_idx.size(1)
        H = int(np.ceil(N / G)) * G

        if H > N:
            pts_idx = torch.cat([pts_idx, pts_idx[:1].expand(H - N, P)], 0)
            min_depth = torch.cat([min_depth, min_depth[:1].expand(H - N, P)], 0)
            max_depth = torch.cat([max_depth, max_depth[:1].expand(H - N, P)], 0)
            probs = torch.cat([probs, probs[:1].expand(H - N, P)], 0)
            steps = torch.cat([steps, steps[:1].expand(H - N)], 0)
        # print(G, P, np.ceil(N / G), N, H, pts_idx.shape, min_depth.device)
        pts_idx = pts_idx.reshape(G, -1, P)
        min_depth = min_depth.reshape(G, -1, P)
        max_depth = max_depth.reshape(G, -1, P)
        probs = probs.reshape(G, -1, P)
        steps = steps.reshape(G, -1)

        # pre-generate noise
        max_steps = steps.ceil().long().max() + P
        noise = min_depth.new_zeros(*min_depth.size()[:-1], max_steps)
        if deterministic:
            noise += 0.5
        else:
            noise = noise.uniform_().clamp(min=0.001, max=0.999)  # in case

        # call cuda function
        chunk_size = 4 * G  # to avoid oom?
        results = [
            _ext.inverse_cdf_sampling(
                pts_idx[:, i:i + chunk_size].contiguous(),
                min_depth.float()[:, i:i + chunk_size].contiguous(),
                max_depth.float()[:, i:i + chunk_size].contiguous(),
                noise.float()[:, i:i + chunk_size].contiguous(),
                probs.float()[:, i:i + chunk_size].contiguous(),
                steps.float()[:, i:i + chunk_size].contiguous(),
                fixed_step_size)
            for i in range(0, min_depth.size(1), chunk_size)
        ]
        sampled_idx, sampled_depth, sampled_dists = [
            torch.cat([r[i] for r in results], 1)
            for i in range(3)
        ]
        sampled_depth = sampled_depth.type_as(min_depth)
        sampled_dists = sampled_dists.type_as(min_depth)

        sampled_idx = sampled_idx.reshape(H, -1)
        sampled_depth = sampled_depth.reshape(H, -1)
        sampled_dists = sampled_dists.reshape(H, -1)
        if H > N:
            sampled_idx = sampled_idx[: N]
            sampled_depth = sampled_depth[: N]
            sampled_dists = sampled_dists[: N]

        max_len = sampled_idx.ne(-1).sum(-1).max()
        sampled_idx = sampled_idx[:, :max_len]
        sampled_depth = sampled_depth[:, :max_len]
        sampled_dists = sampled_dists[:, :max_len]

        ctx.mark_non_differentiable(sampled_idx)
        ctx.mark_non_differentiable(sampled_depth)
        ctx.mark_non_differentiable(sampled_dists)
        return sampled_idx, sampled_depth, sampled_dists

    @staticmethod
    def backward(ctx, a, b, c):
        return None, None, None, None, None, None, None


def inverse_cdf_sampling(pts_idx: torch.Tensor, min_depth: torch.Tensor, max_depth: torch.Tensor,
                         probs: torch.Tensor, steps: torch.Tensor, fixed_step_size: float = -1,
Nianchen Deng's avatar
sync    
Nianchen Deng committed
334
                         deterministic: bool = False) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
Nianchen Deng's avatar
sync    
Nianchen Deng committed
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
    """
    Sample along rays by inverse CDF

    :param pts_idx `Tensor(N, P)`: indices of voxels intersected with rays
    :param min_depth `Tensor(N, P)`: min depth of intersections of rays and voxels
    :param max_depth `Tensor(N, P)`: max depth of intersections of rays and voxels
    :param probs `Tensor(N, P)`:
    :param steps `Tensor(N)`: 
    :param fixed_step_size `float`:
    :param deterministic `bool`: (optional) sample deterministically (or randomly), defaults to False
    :return `Tensor(N, P')`: voxel indices of sampled points
    :return `Tensor(N, P')`: depth of sampled points
    :return `Tensor(N, P')`: length of sampled points
    """
    return InverseCDFRaySampling.apply(pts_idx, min_depth, max_depth, probs, steps, fixed_step_size,
                                       deterministic)


# back-up for ray point sampling
@torch.no_grad()
def _parallel_ray_sampling(MARCH_SIZE, pts_idx, min_depth, max_depth, deterministic=False):
    # uniform sampling
    _min_depth = min_depth.min(1)[0]
Nianchen Deng's avatar
sync    
Nianchen Deng committed
358
    _max_depth = max_depth.masked_fill(max_depth.eq(math.huge), 0).max(1)[0]
Nianchen Deng's avatar
sync    
Nianchen Deng committed
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
    max_ray_length = (_max_depth - _min_depth).max()

    delta = torch.arange(int(max_ray_length / MARCH_SIZE),
                         device=min_depth.device, dtype=min_depth.dtype)
    delta = delta[None, :].expand(min_depth.size(0), delta.size(-1))
    if deterministic:
        delta = delta + 0.5
    else:
        delta = delta + delta.clone().uniform_().clamp(min=0.01, max=0.99)
    delta = delta * MARCH_SIZE
    sampled_depth = min_depth[:, :1] + delta
    sampled_idx = (sampled_depth[:, :, None] >= min_depth[:, None, :]).sum(-1) - 1
    sampled_idx = pts_idx.gather(1, sampled_idx)

    # include all boundary points
    sampled_depth = torch.cat([min_depth, max_depth, sampled_depth], -1)
    sampled_idx = torch.cat([pts_idx, pts_idx, sampled_idx], -1)

    # reorder
    sampled_depth, ordered_index = sampled_depth.sort(-1)
    sampled_idx = sampled_idx.gather(1, ordered_index)
    sampled_dists = sampled_depth[:, 1:] - sampled_depth[:, :-1]          # distances
    sampled_depth = .5 * (sampled_depth[:, 1:] + sampled_depth[:, :-1])   # mid-points

    # remove all invalid depths
    min_ids = (sampled_depth[:, :, None] >= min_depth[:, None, :]).sum(-1) - 1
    max_ids = (sampled_depth[:, :, None] >= max_depth[:, None, :]).sum(-1)

    sampled_depth.masked_fill_(
        (max_ids.ne(min_ids)) |
        (sampled_depth > _max_depth[:, None]) |
Nianchen Deng's avatar
sync    
Nianchen Deng committed
390
        (sampled_dists == 0.0), math.huge)
Nianchen Deng's avatar
sync    
Nianchen Deng committed
391
    sampled_depth, ordered_index = sampled_depth.sort(-1)  # sort again
Nianchen Deng's avatar
sync    
Nianchen Deng committed
392
    sampled_masks = sampled_depth.eq(math.huge)
Nianchen Deng's avatar
sync    
Nianchen Deng committed
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
    num_max_steps = (~sampled_masks).sum(-1).max()

    sampled_depth = sampled_depth[:, :num_max_steps]
    sampled_dists = sampled_dists.gather(1, ordered_index).masked_fill_(
        sampled_masks, 0.0)[:, :num_max_steps]
    sampled_idx = sampled_idx.gather(1, ordered_index).masked_fill_(
        sampled_masks, -1)[:, :num_max_steps]

    return sampled_idx, sampled_depth, sampled_dists


@torch.no_grad()
def parallel_ray_sampling(MARCH_SIZE, pts_idx, min_depth, max_depth, deterministic=False):
    chunk_size = 4096
    full_size = min_depth.shape[0]
    if full_size <= chunk_size:
        return _parallel_ray_sampling(MARCH_SIZE, pts_idx, min_depth, max_depth, deterministic=deterministic)

    outputs = zip(*[
        _parallel_ray_sampling(
            MARCH_SIZE,
            pts_idx[i:i + chunk_size], min_depth[i:i + chunk_size], max_depth[i:i + chunk_size],
            deterministic=deterministic)
        for i in range(0, full_size, chunk_size)])
    sampled_idx, sampled_depth, sampled_dists = outputs

    def padding_points(xs, pad):
        if len(xs) == 1:
            return xs[0]

        maxlen = max([x.size(1) for x in xs])
        full_size = sum([x.size(0) for x in xs])
        xt = xs[0].new_ones(full_size, maxlen).fill_(pad)
        st = 0
        for i in range(len(xs)):
            xt[st: st + xs[i].size(0), :xs[i].size(1)] = xs[i]
            st += xs[i].size(0)
        return xt

    sampled_idx = padding_points(sampled_idx, -1)
Nianchen Deng's avatar
sync    
Nianchen Deng committed
433
    sampled_depth = padding_points(sampled_depth, math.huge)
Nianchen Deng's avatar
sync    
Nianchen Deng committed
434
435
436
437
    sampled_dists = padding_points(sampled_dists, 0.0)
    return sampled_idx, sampled_depth, sampled_dists


Nianchen Deng's avatar
sync    
Nianchen Deng committed
438
def build_easy_octree(points: torch.Tensor, half_voxel: float) -> tuple[torch.Tensor, torch.Tensor]:
Nianchen Deng's avatar
sync    
Nianchen Deng committed
439
440
441
442
443
444
445
446
447
448
449
450
451
452
    """
    Build an octree.

    :param points `Tensor(M, 3)`: centers of leaf voxels
    :param half_voxel `float`: half size of voxel
    :return `Tensor(M', 3)`: centers of all nodes in octree
    :return `Tensor(M', 9)`: flattened octree structure
    """
    coords, residual = discretize_points(points, half_voxel)
    ranges = coords.max(0)[0] - coords.min(0)[0]
    depths = torch.log2(ranges.max().float()).ceil_().long() - 1
    center = (coords.max(0)[0] + coords.min(0)[0]) / 2
    centers, children = _ext.build_octree(center, coords, int(depths))
    centers = centers.float() * half_voxel + residual   # transform back to float
Nianchen Deng's avatar
sync    
Nianchen Deng committed
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
    return centers, children


class MultiresHashEncode(Function):
    @staticmethod
    def forward(ctx: FunctionCtx, levels: int, coarse_levels: int, res_list: torch.Tensor,
                hash_table_offsets: torch.Tensor, x: torch.Tensor, hash_table: torch.Tensor,
                grad_enabled: bool) -> torch.Tensor:
        """
        [summary]

        :param ctx `FunctionCtx`: [description]
        :param levels `int`: [description]
        :param coarse_levels `int`: [description]
        :param res_list `Tensor(L, D)`: [description]
        :param hash_table_offsets `Tensor(L+1)`: [description]
        :param x `Tensor(N, D)`: [description]
        :param hash_table `Tensor(T, F)`: [description]
        :return `Tensor(L, N, F)`: [description]
        """
        
        x = x.contiguous()
        res_list = res_list.int().contiguous()
        hash_table_offsets = hash_table_offsets.int().contiguous()
        if grad_enabled and hash_table.requires_grad:
            encoded, weights, indices = _ext.multires_hash_encode_with_grad(
                levels, coarse_levels, x, res_list, hash_table, hash_table_offsets)
            ctx.save_for_backward(weights, indices.long())
            ctx.hash_table_shape = hash_table.shape
            return encoded
        print(hash_table)
        return _ext.multires_hash_encode(levels, coarse_levels, x, res_list, hash_table,
                                         hash_table_offsets)

    @staticmethod
    @once_differentiable
    def backward(ctx: FunctionCtx, grad_output: torch.Tensor):
        """
        [summary]

        :param ctx `FunctionCtx`: [description]
        :param grad_output `Tensor(L, N, F)`: [description]
        :return: [description]
        """
        weights, indices = ctx.saved_tensors  # (L, N, C)
        t = grad_output[..., None, :] * weights[..., None]  # (L, N, C, F)
        grad_hash_table = grad_output.new_zeros(*ctx.hash_table_shape)
        grad_hash_table.index_put_([indices], t, accumulate=True)
        return None, None, None, None, None, grad_hash_table, None


def multires_hash_encode(levels: int, coarse_levels: int, res_list: torch.Tensor,
                         hash_table_offsets: torch.Tensor, x: torch.Tensor, hash_table: torch.Tensor) -> torch.Tensor:
    """


    :param levels `int`: [description]
    :param coarse_levels `int`: [description]
    :param res_list `Tensor(L, D)`: [description]
    :param hash_table_offsets `Tensor(L+1)`: [description]
    :param x `Tensor(N, D)`: [description]
    :param hash_table `Tensor(T, F)`: [description]
    :return `Tensor(L, N, F)`: [description]
    """
    return MultiresHashEncode.apply(levels, coarse_levels, res_list, hash_table_offsets, x,
     hash_table, torch.is_grad_enabled())