Skip to content

Commit 7d7d00f

Browse files
bottlerfacebook-github-bot
authored andcommitted
Move sample_pdf into PyTorch3D
Summary: Copy the sample_pdf operation from the NeRF project in to PyTorch3D, in preparation for optimizing it. Reviewed By: gkioxari Differential Revision: D27117930 fbshipit-source-id: 20286b007f589a4c4d53ed818c4bc5f2abd22833
1 parent b481cfb commit 7d7d00f

File tree

3 files changed

+162
-0
lines changed

3 files changed

+162
-0
lines changed
+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# Copyright (c) Facebook, Inc. and its affiliates.
2+
# All rights reserved.
3+
#
4+
# This source code is licensed under the BSD-style license found in the
5+
# LICENSE file in the root directory of this source tree.
6+
7+
8+
import torch
9+
10+
11+
def sample_pdf_python(
12+
bins: torch.Tensor,
13+
weights: torch.Tensor,
14+
N_samples: int,
15+
det: bool = False,
16+
eps: float = 1e-5,
17+
) -> torch.Tensor:
18+
"""
19+
Samples probability density functions defined by bin edges `bins` and
20+
the non-negative per-bin probabilities `weights`.
21+
22+
Note: This is a direct conversion of the TensorFlow function from the original
23+
release [1] to PyTorch.
24+
25+
Args:
26+
bins: Tensor of shape `(..., n_bins+1)` denoting the edges of the sampling bins.
27+
weights: Tensor of shape `(..., n_bins)` containing non-negative numbers
28+
representing the probability of sampling the corresponding bin.
29+
N_samples: The number of samples to draw from each set of bins.
30+
det: If `False`, the sampling is random. `True` yields deterministic
31+
uniformly-spaced sampling from the inverse cumulative density function.
32+
eps: A constant preventing division by zero in case empty bins are present.
33+
34+
Returns:
35+
samples: Tensor of shape `(..., N_samples)` containing `N_samples` samples
36+
drawn from each probability distribution.
37+
38+
Refs:
39+
[1] https://github.com/bmild/nerf/blob/55d8b00244d7b5178f4d003526ab6667683c9da9/run_nerf_helpers.py#L183 # noqa E501
40+
"""
41+
42+
# Get pdf
43+
weights = weights + eps # prevent nans
44+
if weights.min() <= 0:
45+
raise ValueError("Negative weights provided.")
46+
pdf = weights / weights.sum(dim=-1, keepdim=True)
47+
cdf = torch.cumsum(pdf, -1)
48+
cdf = torch.cat([torch.zeros_like(cdf[..., :1]), cdf], -1)
49+
50+
# Take uniform samples u of shape (..., N_samples)
51+
if det:
52+
u = torch.linspace(0.0, 1.0, N_samples, device=cdf.device, dtype=cdf.dtype)
53+
u = u.expand(list(cdf.shape[:-1]) + [N_samples]).contiguous()
54+
else:
55+
u = torch.rand(
56+
list(cdf.shape[:-1]) + [N_samples], device=cdf.device, dtype=cdf.dtype
57+
)
58+
59+
# Invert CDF
60+
inds = torch.searchsorted(cdf, u, right=True)
61+
# inds has shape (..., N_samples) identifying the bin of each sample.
62+
below = (inds - 1).clamp(0)
63+
above = inds.clamp(max=cdf.shape[-1] - 1)
64+
# Below and above are of shape (..., N_samples), identifying the bin
65+
# edges surrounding each sample.
66+
67+
inds_g = torch.stack([below, above], -1).view(
68+
*below.shape[:-1], below.shape[-1] * 2
69+
)
70+
cdf_g = torch.gather(cdf, -1, inds_g).view(*below.shape, 2)
71+
bins_g = torch.gather(bins, -1, inds_g).view(*below.shape, 2)
72+
# cdf_g and bins_g are of shape (..., N_samples, 2) and identify
73+
# the cdf and the index of the two bin edges surrounding each sample.
74+
75+
denom = cdf_g[..., 1] - cdf_g[..., 0]
76+
denom = torch.where(denom < eps, torch.ones_like(denom), denom)
77+
t = (u - cdf_g[..., 0]) / denom
78+
# t is of shape (..., N_samples) and identifies how far through
79+
# each sample is in its bin.
80+
81+
samples = bins_g[..., 0] + t * (bins_g[..., 1] - bins_g[..., 0])
82+
83+
return samples

tests/bm_sample_pdf.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Copyright (c) Facebook, Inc. and its affiliates.
2+
# All rights reserved.
3+
#
4+
# This source code is licensed under the BSD-style license found in the
5+
# LICENSE file in the root directory of this source tree.
6+
7+
from itertools import product
8+
9+
from fvcore.common.benchmark import benchmark
10+
from test_sample_pdf import TestSamplePDF
11+
12+
13+
def bm_sample_pdf() -> None:
14+
15+
backends = ["python_cuda", "python_cpu"]
16+
17+
kwargs_list = []
18+
sample_counts = [64]
19+
batch_sizes = [1024, 10240]
20+
bin_counts = [62, 600]
21+
test_cases = product(backends, sample_counts, batch_sizes, bin_counts)
22+
for case in test_cases:
23+
backend, n_samples, batch_size, n_bins = case
24+
kwargs_list.append(
25+
{
26+
"backend": backend,
27+
"n_samples": n_samples,
28+
"batch_size": batch_size,
29+
"n_bins": n_bins,
30+
}
31+
)
32+
33+
benchmark(TestSamplePDF.bm_fn, "SAMPLE_PDF", kwargs_list, warmup_iters=1)
34+
35+
36+
if __name__ == "__main__":
37+
bm_sample_pdf()

tests/test_sample_pdf.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Copyright (c) Facebook, Inc. and its affiliates.
2+
# All rights reserved.
3+
#
4+
# This source code is licensed under the BSD-style license found in the
5+
# LICENSE file in the root directory of this source tree.
6+
7+
import unittest
8+
9+
import torch
10+
from common_testing import TestCaseMixin
11+
from pytorch3d.renderer.implicit.sample_pdf import sample_pdf_python
12+
13+
14+
class TestSamplePDF(TestCaseMixin, unittest.TestCase):
15+
def setUp(self) -> None:
16+
super().setUp()
17+
torch.manual_seed(1)
18+
19+
def test_single_bin(self):
20+
bins = torch.arange(2).expand(5, 2) + 17
21+
weights = torch.ones(5, 1)
22+
output = sample_pdf_python(bins, weights, 100, True)
23+
calc = torch.linspace(17, 18, 100).expand(5, -1)
24+
self.assertClose(output, calc)
25+
26+
@staticmethod
27+
def bm_fn(*, backend: str, n_samples, batch_size, n_bins):
28+
f = sample_pdf_python
29+
weights = torch.rand(size=(batch_size, n_bins))
30+
bins = torch.cumsum(torch.rand(size=(batch_size, n_bins + 1)), dim=-1)
31+
32+
if "cuda" in backend:
33+
weights = weights.cuda()
34+
bins = bins.cuda()
35+
36+
torch.cuda.synchronize()
37+
38+
def output():
39+
f(bins, weights, n_samples)
40+
torch.cuda.synchronize()
41+
42+
return output

0 commit comments

Comments
 (0)