diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 89d100d5..e2568c4f 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -135,6 +135,202 @@ The number of encoded dimensions is `n_levels * n_features_per_level`. } ``` +### Permuto + +`Permuto` is a trainable N-dimensional permutohedral lattice encoding. The +factory accepts input widths `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, +`10`, `12`, `16`, and `24`. The input width passed to the factory is +authoritative. Callers must normalize each input value to `[0, 1]`. The +encoding does not scan device inputs to enforce this range. + +Each level produces `n_features_per_level` adjacent output features. The +supported feature widths are `1`, `2`, `4`, and `8`. Level `l` uses the scale +`base_scale * per_level_scale^l`. The unpadded output width is +`n_levels * n_features_per_level`. An alignment request can add zero-valued +padding after these features. The required output alignment is +`n_features_per_level`. The encoded features have no fixed value range because +the lattice entries are trainable parameters. + +```text +[x0, ..., xN-1] + | + v +levels 0 ... n_levels - 1 + | + v +[level 0 feature 0, ..., level L feature F-1] +``` + +```json5 +{ + "otype": "Permuto", // Component type. + "n_levels": 16, // Number of levels. Must be in [1, 32]. + "n_features_per_level": 2, // Must be 1, 2, 4, or 8. + "log2_hashmap_size": 19, // Base-2 logarithm of the entries per level. + "base_scale": 16.0, // Finite scale of level 0. + "per_level_scale": 2.0, // Positive finite scale multiplier. + "interpolation": "Linear", // Case-insensitive. Must be "Linear". + "max_input_grad_dims": 5, // Leading input dimensions with gradients. + "seed": 1337 // Unsigned seed for per-level lattice shifts. +} +``` + +`interpolation` accepts only `Linear`, case-insensitively. +`log2_hashmap_size` must be a nonnegative integer smaller than 32. The +parameter count must also fit in an unsigned 32-bit integer. Every derived +level scale must be finite and safe for the kernel's integer lattice +coordinates. `max_input_grad_dims` defaults to the input width and must not +exceed that width. +`seed` must be an integer in `[0, 2^32 - 1]`. + +The flat parameter array contains +`n_levels * 2^log2_hashmap_size * n_features_per_level` values. The layout +order is level, hashed entry, then feature. The features for one entry are +adjacent. Construction, `hyperparams()`, and reload preserve this layout. +`hyperparams()` includes the configured `seed`. Reloading the emitted +hyperparameters and the same flat parameter array therefore preserves the +lattice shifts and learned values. +`scales_table` and `shifts_table` are diagnostics derived from `seed`, +`base_scale`, and `per_level_scale`. They do not independently configure the +lattice. The factory accepts the tables only when they match those behavioral +fields. Each table contains `n_levels * input_width` values. + +`n_features` and `n_grid_features` are aliases for the total unpadded output +width. Either alias can replace `n_levels`. The aliases are mutually exclusive +with each other and with `n_levels`. An alias value must be a positive integer +that is divisible by `n_features_per_level`. `hyperparams()` always emits the +canonical `n_levels` and `n_features_per_level` fields. It does not emit either +alias. The factory ignores unrelated compatibility keys, including +`base_resolution`, `max_resolution`, and a JSON `n_dims_to_encode` field. + +The encoding supports first-order parameter and input gradients. It also +supports non-JIT double backward for parameter gradients and upstream +gradients. The input Hessian is zero inside each linear lattice simplex. +`max_input_grad_dims` applies at both derivative orders. It enables gradients +only for the leading input dimensions. The remaining input gradients are zero. +Parameter gradients honor `Overwrite`, `Accumulate`, and `Ignore` at both +derivative orders. + +### MultiLevelEncodingLoD + +`MultiLevelEncodingLoD` adds per-element level control to a multilevel +encoding. The public Grid and Permuto encodings are supported bases. The +wrapper accepts one more input dimension than its base. The first N values are +the base input. The final value is a level ratio. Callers normally provide a +finite ratio in `[0, 1]`. NaN and infinite ratios are outside the public +contract. + +```text +[x0, ..., xN-1, level_ratio] + | | + v v + base input LoD weights + \_____________/ + | + v + weighted features +``` + +```json5 +{ + "otype": "MultiLevelEncodingLoD", + "lod_type": "Soft", // Optional. Defaults to "Hard". + "base": { + "otype": "Permuto", // Can also be a Grid encoding. + "n_levels": 16, + "n_features_per_level": 2, + "log2_hashmap_size": 19, + "base_scale": 16.0, + "per_level_scale": 2.0, + "interpolation": "Linear", + "max_input_grad_dims": 5, + "seed": 1337 + } +} +``` + +`lod_type` accepts `Hard`, `Discontinuous`, `Soft`, and `Continuous`, +case-insensitively. `Discontinuous` is an alias for `Hard`. `Continuous` is an +alias for `Soft`. `hyperparams()` serializes the canonical value `Hard` or +`Soft` and preserves the base configuration as nested JSON. + +Both modes calculate the per-element level coordinate as follows: + +```text +level_f = level_ratio * n_levels + 1e-3 +level_i = floor(level_f) +``` + +Hard mode enables a complete zero-based level when the following predicate is +true: + +```text +level < level_f +``` + +Soft mode assigns weight `1` to levels below `level_i`. Soft mode assigns +weight `level_f - level_i` to level `level_i`. Soft mode assigns weight `0` to +finer levels. A ratio below the first boundary can disable all levels. A ratio +at or above the final boundary preserves all levels. The implementation does +not clamp the ratio. + +An inactive level produces zero output features and contributes no parameter +or position-input gradient. A partially active soft level applies the same +weight to its output and upstream gradient. The wrapper retains the unweighted +base output because native backward can require that value. Native double +backward applies the same soft weights to the upstream-gradient result. The +level-ratio input is scheduler state. Its input gradient is exactly zero in +both modes. + +The wrapper forwards the base level count, position dimensions, features per +level, parameter offsets, output alignment, layout, and padding. The wrapper +also preserves the base logical output order, flat parameter layout, inference +parameters, and `Overwrite`, `Accumulate`, and `Ignore` gradient modes. The +wrapper passes each gradient mode unchanged to the base at both derivative +orders. The base encoding therefore defines the final gradient-mode behavior +and any base-specific limitations. In particular, a half-precision Grid with +`n_features_per_level=1` uses a temporary floating-point parameter-gradient +accumulator. Its `Accumulate` path does not initialize that scratch buffer from +the existing half-precision gradients. A Grid-backed wrapper inherits this +pre-existing limitation. A nested `MultiLevelEncodingLoD` base is rejected +because nested wrappers cannot safely share the native mutable level-selection +state. + +A nonempty context-only forward is supported when the output pointer is null. +Soft mode also retains the unweighted base output for a later backward call. A +zero-element batch is valid for forward, backward, and double backward. +Empty-batch derivative calls clear parameter gradients in `Overwrite` mode and +preserve them in `Accumulate` and `Ignore` modes. + +#### Thread Safety + +`MultiLevelEncodingLoD` does not support concurrent host calls on one +instance. Do not start a call whose device work can overlap earlier work on +that instance. Use one CUDA stream, or insert and wait for an event dependency +before another stream accesses the same parameters, gradients, or per-call +state. Host-call serialization without a device dependency is insufficient. +These encodings do not establish a broader host-thread-safety contract for +TCNN. + +#### Build and JIT Support + +`Permuto` and `MultiLevelEncodingLoD` are available only in builds that contain +the offline forward and backward implementations. A build configured with +`TCNN_BUILD_NO_FWD_BWD=ON` does not register either encoding type. + +These encodings do not provide runtime-compiled CUDA device functions. When +automatic just-in-time (JIT) fusion attempts to compile a model that contains +either encoding, tiny-cuda-nn reports the unsupported device function, +disables JIT fusion, and falls back to the offline implementation. Manual JIT +device-function generation is unsupported. The no-forward-and-backward build +cannot use this fallback because the encoding types are not registered. + +The non-JIT `NetworkWithInputEncoding` double-backward path currently supports +one specific network shape: a `FullyFusedMLP` with one hidden layer, `ReLU`, and +no output activation. That path computes parameter and upstream gradients. It +does not compute a network input Hessian. Other network shapes report an +explicit runtime error instead of returning an incomplete second-order result. + ### Identity Leaves values untouched. Optionally, multiplies each dimension by a scalar and adds an offset. diff --git a/README.md b/README.md index db3465b5..204ae2d0 100644 --- a/README.md +++ b/README.md @@ -277,7 +277,9 @@ Following is a summary of the components of this framework. [The JSON documentat | Frequency | `include/tiny-cuda-nn/encodings/frequency.h` | NeRF's [[Mildenhall et al. 2020]](https://www.matthewtancik.com/nerf) positional encoding applied equally to all dimensions. | Grid | `include/tiny-cuda-nn/encodings/grid.h` | Encoding based on trainable multiresolution grids. Used for [Instant Neural Graphics Primitives [Müller et al. 2022]](https://nvlabs.github.io/instant-ngp/). The grids can be backed by hashtables, dense storage, or tiled storage. | Identity | `include/tiny-cuda-nn/encodings/identity.h` | Leaves values untouched. +| MultiLevelEncodingLoD | `include/tiny-cuda-nn/encodings/multi_level_lod.h` | Hard or soft per-element LoD for Grid and Permuto. | Oneblob | `include/tiny-cuda-nn/encodings/oneblob.h` | From Neural Importance Sampling [[Müller et al. 2019]](https://tom94.net/data/publications/mueller18neural/mueller18neural-v4.pdf) and Neural Control Variates [[Müller et al. 2020]](https://tom94.net/data/publications/mueller20neural/mueller20neural.pdf). +| Permuto | `include/tiny-cuda-nn/encodings/internal/permuto.h` | Trainable lattice for selected input and per-level feature widths. | SphericalHarmonics | `include/tiny-cuda-nn/encodings/spherical_harmonics.h` | A frequency-space encoding that is more suitable to direction vectors than component-wise ones. | TriangleWave | `include/tiny-cuda-nn/encodings/triangle_wave.h` | Low-cost alternative to the NeRF's encoding. Used in Neural Radiance Caching [[Müller et al. 2021]](https://tom94.net/). diff --git a/bindings/torch/tests/test_permuto.py b/bindings/torch/tests/test_permuto.py new file mode 100644 index 00000000..5b21ab53 --- /dev/null +++ b/bindings/torch/tests/test_permuto.py @@ -0,0 +1,455 @@ +# Copyright (c) 2020-2026, NVIDIA CORPORATION. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright notice, this list of +# conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials +# provided with the distribution. +# * Neither the name of the NVIDIA CORPORATION nor the names of its contributors may be used +# to endorse or promote products derived from this software without specific prior written +# permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import unittest + +import torch +import tinycudann as tcnn + + +ENCODING_CONFIG = { + "otype": "MultiLevelEncodingLoD", + "lod_type": "Hard", + "base": { + "otype": "Permuto", + "n_levels": 16, + "n_features_per_level": 2, + "log2_hashmap_size": 19, + "per_level_scale": 1.4472692374403782, + "base_scale": 16.0, + "interpolation": "Linear", + "max_input_grad_dims": 3, + }, +} + +NETWORK_CONFIG = { + "otype": "FullyFusedMLP", + "activation": "ReLU", + "output_activation": "none", + "n_neurons": 64, + "n_hidden_layers": 1, +} + + +class TestPermuto(unittest.TestCase): + def test_generalized_permuto_construction(self) -> None: + self.assertTrue(torch.cuda.is_available()) + + for n_input_dims, n_features_per_level in ((1, 1), (7, 4), (24, 8)): + with self.subTest(n_input_dims=n_input_dims, n_features_per_level=n_features_per_level): + module = tcnn.Encoding( + n_input_dims=n_input_dims, + encoding_config={ + "otype": "Permuto", + "n_levels": 2, + "n_features_per_level": n_features_per_level, + "log2_hashmap_size": 2, + "max_input_grad_dims": n_input_dims, + }, + seed=42, + dtype=torch.float32, + ) + module.jit_fusion = False + self.assertEqual(module.n_output_dims, 2 * n_features_per_level) + self.assertEqual(module.params.numel(), 2 * 4 * n_features_per_level) + + def test_soft_lod_native_forward_and_backward(self) -> None: + base_config = { + "otype": "Permuto", + "n_levels": 2, + "n_features_per_level": 2, + "log2_hashmap_size": 4, + "base_scale": 4.0, + "per_level_scale": 1.5, + "max_input_grad_dims": 3, + } + soft_config = { + "otype": "MultiLevelEncodingLoD", + "lod_type": "Soft", + "base": base_config, + } + base = tcnn.Encoding(5, base_config, seed=17, dtype=torch.float32) + module = tcnn.Encoding(6, soft_config, seed=19, dtype=torch.float32) + base.jit_fusion = False + module.jit_fusion = False + with torch.no_grad(): + base.params.copy_(module.params) + + torch.manual_seed(23) + positions = torch.rand((128, 5), device="cuda", dtype=torch.float32) + boundary = (1.0 - 1e-3) / 2 + max_finite = torch.finfo(torch.float32).max + ratios = torch.tensor( + [-max_finite, -0.25, 0.0, boundary, 0.5, 0.75, 1.0, 1.25, max_finite], + device=positions.device, + dtype=torch.float32, + ).repeat(15)[:128, None] + inputs = torch.cat((positions, ratios), dim=1).requires_grad_() + base_output = base(positions) + output = module(inputs) + + level_f = ratios * 2 + 1e-3 + level_indices = torch.arange(2, device=positions.device, dtype=torch.float32)[None, :] + weights = torch.clamp(level_f - level_indices, min=0.0, max=1.0).repeat_interleave(2, dim=1) + expected = base_output.clone() + expected[:, :4] *= weights + torch.testing.assert_close(output, expected, atol=1e-6, rtol=1e-5) + + probe = torch.randn_like(output) + input_gradient, parameter_gradient = torch.autograd.grad( + (output * probe).sum(), (inputs, module.params) + ) + self.assertTrue(torch.isfinite(input_gradient).all().item()) + self.assertTrue(torch.isfinite(parameter_gradient).all().item()) + self.assertGreater(torch.count_nonzero(input_gradient[:, :3]).item(), 0) + self.assertEqual(torch.count_nonzero(input_gradient[:, 3:]).item(), 0) + self.assertGreater(torch.count_nonzero(parameter_gradient).item(), 0) + + def test_grid_lod_native_construction_and_backward(self) -> None: + base_config = { + "otype": "HashGrid", + "n_levels": 17, + "n_features_per_level": 8, + "log2_hashmap_size": 4, + "base_resolution": 4, + "per_level_scale": 2.0, + "interpolation": "Linear", + } + for lod_type in ("Hard", "Soft"): + with self.subTest(lod_type=lod_type): + module = tcnn.Encoding( + 3, + { + "otype": "MultiLevelEncodingLoD", + "lod_type": lod_type, + "base": base_config, + }, + seed=29, + dtype=torch.float32, + ) + module.jit_fusion = False + torch.manual_seed(31) + inputs = torch.rand((128, 3), device="cuda", dtype=torch.float32) + inputs[:, -1] = 0.75 + inputs.requires_grad_() + output = module(inputs) + output.square().sum().backward() + + self.assertTrue(torch.isfinite(output).all().item()) + self.assertIsNotNone(inputs.grad) + self.assertGreater(torch.count_nonzero(inputs.grad[:, :2]).item(), 0) + self.assertEqual(torch.count_nonzero(inputs.grad[:, -1]).item(), 0) + self.assertIsNotNone(module.params.grad) + self.assertGreater(torch.count_nonzero(module.params.grad).item(), 0) + + def test_first_order_construction_backward_and_optimizer(self) -> None: + self.assertTrue(torch.cuda.is_available()) + + module = tcnn.NetworkWithInputEncoding( + n_input_dims=6, + n_output_dims=16, + encoding_config=ENCODING_CONFIG, + network_config=NETWORK_CONFIG, + seed=42, + ) + module.jit_fusion = False + + self.assertEqual(module.params.numel(), 16_780_288) + + torch.manual_seed(7) + positions = torch.rand((128, 5), device="cuda", dtype=torch.float32) + ratios = torch.tensor( + [0.0, 10 / 16, 12 / 16, 15 / 16, 1.0], + device=positions.device, + dtype=torch.float32, + ).repeat(26)[:128, None] + inputs = torch.cat((positions, ratios), dim=1).requires_grad_() + + optimizer = torch.optim.Adam(module.parameters(), lr=1e-3) + params_before = module.params.detach().clone() + output = module(inputs) + self.assertEqual(output.shape, (128, 16)) + self.assertTrue(torch.isfinite(output).all().item()) + + output.float().square().mean().backward() + self.assertIsNotNone(inputs.grad) + self.assertTrue(torch.isfinite(inputs.grad).all().item()) + self.assertGreater(torch.count_nonzero(inputs.grad[:, :3]).item(), 0) + self.assertEqual(torch.count_nonzero(inputs.grad[:, 3:]).item(), 0) + + self.assertIsNotNone(module.params.grad) + self.assertTrue(torch.isfinite(module.params.grad).all().item()) + self.assertGreater(torch.count_nonzero(module.params.grad).item(), 0) + + optimizer.step() + self.assertTrue(torch.isfinite(module.params).all().item()) + self.assertFalse(torch.equal(params_before, module.params.detach())) + + def test_double_backward_and_no_input_gradient_property(self) -> None: + module = tcnn.NetworkWithInputEncoding( + n_input_dims=6, + n_output_dims=16, + encoding_config=ENCODING_CONFIG, + network_config=NETWORK_CONFIG, + seed=42, + ) + module.jit_fusion = False + self.assertFalse(module.backward_backward_input_no_input_grad) + + torch.manual_seed(11) + inputs = torch.rand((128, 6), device="cuda", dtype=torch.float32) + inputs[:, -1] = 12 / 16 + first_order_probe = torch.randn((128, 16), device=inputs.device, dtype=module.dtype) * 0.01 + second_order_probe = torch.randn_like(inputs) * 0.01 + + gradients = [] + for skip_input_gradient in (False, True): + module.backward_backward_input_no_input_grad = skip_input_gradient + x = inputs.detach().clone().requires_grad_() + output = module(x) + input_gradient = torch.autograd.grad( + output, x, first_order_probe, create_graph=True + )[0] + gradient_loss = (input_gradient * second_order_probe).sum() + gradients.append( + torch.autograd.grad( + gradient_loss, (module.params, x), allow_unused=True + ) + ) + + (params_gradient, input_gradient), (params_gradient_optimized, input_gradient_optimized) = gradients + + self.assertTrue(torch.isfinite(params_gradient).all().item()) + self.assertGreater(torch.count_nonzero(params_gradient).item(), 0) + self.assertTrue(torch.allclose(params_gradient, params_gradient_optimized, atol=1e-5, rtol=1e-3)) + self.assertIsNotNone(input_gradient) + self.assertEqual(torch.count_nonzero(input_gradient).item(), 0) + self.assertIsNone(input_gradient_optimized) + + def test_double_backward_network_parameter_endpoints(self) -> None: + for encoded_width, hidden_width, output_width, batch_size in ( + (16, 16, 1, 1), + (48, 128, 17, 257), + ): + with self.subTest( + encoded_width=encoded_width, + hidden_width=hidden_width, + output_width=output_width, + batch_size=batch_size, + ): + encoding_config = { + **ENCODING_CONFIG, + "base": { + **ENCODING_CONFIG["base"], + "n_levels": encoded_width // 2, + "log2_hashmap_size": 8, + "base_scale": 4.0, + "per_level_scale": 1.2, + }, + } + network_config = {**NETWORK_CONFIG, "n_neurons": hidden_width} + module = tcnn.NetworkWithInputEncoding( + n_input_dims=6, + n_output_dims=output_width, + encoding_config=encoding_config, + network_config=network_config, + seed=42, + ) + module.jit_fusion = False + module.backward_backward_input_no_input_grad = True + self.assertEqual(module.dtype, torch.float16) + + padded_output_width = (output_width + 15) // 16 * 16 + input_weight_count = hidden_width * encoded_width + network_param_count = input_weight_count + padded_output_width * hidden_width + encoding = tcnn.Encoding(6, encoding_config, seed=42, dtype=torch.float16) + encoding.jit_fusion = False + encoding.backward_backward_input_no_input_grad = True + self.assertEqual(module.params.numel(), network_param_count + encoding.params.numel()) + + torch.manual_seed(encoded_width) + # Keep alternating ReLU masks away from zero so TCNN and PyTorch + # cannot select different branches because of FP16 accumulation order. + with torch.no_grad(): + controlled_input_weights = module.params[:input_weight_count].view(hidden_width, encoded_width) + controlled_input_weights.zero_() + hidden_indices = torch.arange(hidden_width, device=module.params.device) + controlled_input_weights[hidden_indices, hidden_indices % encoded_width] = 1.0 + controlled_input_weights[1::2].mul_(-1.0) + module.params[input_weight_count:network_param_count].fill_(0.0625) + module.params[network_param_count:].uniform_(0.05, 0.15) + encoding.params.copy_(module.params[network_param_count:]) + encoding.params.requires_grad_(False) + + inputs = torch.rand((batch_size, 6), device="cuda", dtype=torch.float32) + inputs[:, -1] = 1.0 + inputs.requires_grad_() + input_direction = torch.randn_like(inputs) * 0.01 + output_probe = torch.randn( + (batch_size, output_width), device=inputs.device, dtype=torch.float16 + ) * 0.01 + input_gradient = torch.autograd.grad( + module(inputs), inputs, output_probe, create_graph=True + )[0] + actual = torch.autograd.grad( + (input_gradient * input_direction).sum(), module.params + )[0][:network_param_count] + + # Obtain the encoded input direction for an independent network oracle. + encoding_inputs = inputs.detach().requires_grad_() + encoded = encoding(encoding_inputs) + jacobian_probe = torch.zeros_like(encoded, requires_grad=True) + encoded_input_gradient = torch.autograd.grad( + encoded, encoding_inputs, jacobian_probe, create_graph=True + )[0] + encoded_direction = torch.autograd.grad( + (encoded_input_gradient * input_direction).sum(), jacobian_probe + )[0] + + network_params = module.params[:network_param_count].detach().to(torch.float16) + input_weights = network_params[:input_weight_count].view(hidden_width, encoded_width) + output_weights = network_params[input_weight_count:].view(padded_output_width, hidden_width) + preactivation = encoded.detach().matmul(input_weights.T) + self.assertGreater(preactivation.abs().min().item(), 0.01) + hidden_mask = preactivation > 0 + self.assertGreater(torch.count_nonzero(hidden_mask).item(), 0) + self.assertGreater(torch.count_nonzero(~hidden_mask).item(), 0) + padded_output_probe = torch.nn.functional.pad( + output_probe, (0, padded_output_width - output_width) + ) + hidden_direction = encoded_direction.matmul(input_weights.T) * hidden_mask + hidden_probe = padded_output_probe.matmul(output_weights) * hidden_mask + expected_input_gradient = hidden_probe.T.matmul(encoded_direction) + expected_output_gradient = padded_output_probe.T.matmul(hidden_direction) + actual_input_gradient = actual[:input_weight_count].view(hidden_width, encoded_width) + actual_output_gradient = actual[input_weight_count:].view(padded_output_width, hidden_width) + + for gradient in ( + encoded_direction, + expected_input_gradient, + expected_output_gradient[:output_width], + actual_input_gradient, + actual_output_gradient[:output_width], + ): + self.assertGreater(torch.count_nonzero(gradient).item(), 0) + torch.testing.assert_close(actual_input_gradient, expected_input_gradient.float(), atol=1e-5, rtol=1e-3) + torch.testing.assert_close( + actual_output_gradient[:output_width], + expected_output_gradient[:output_width].float(), + atol=1e-5, + rtol=1e-3, + ) + self.assertEqual(torch.count_nonzero(actual_output_gradient[output_width:]).item(), 0) + + def test_empty_batch_backward(self) -> None: + module = tcnn.NetworkWithInputEncoding( + n_input_dims=6, + n_output_dims=16, + encoding_config=ENCODING_CONFIG, + network_config=NETWORK_CONFIG, + seed=42, + ) + module.jit_fusion = False + inputs = torch.empty((0, 6), device="cuda", requires_grad=True) + + output = module(inputs) + output.sum().backward() + torch.cuda.synchronize() + + self.assertEqual(output.shape, (0, 16)) + self.assertEqual(output.dtype, module.dtype) + self.assertEqual(output.device, inputs.device) + self.assertTrue(output.requires_grad) + self.assertIsNotNone(inputs.grad) + self.assertEqual(inputs.grad.shape, inputs.shape) + self.assertIsNotNone(module.params.grad) + self.assertEqual(module.params.grad.shape, module.params.shape) + self.assertEqual(torch.count_nonzero(module.params.grad).item(), 0) + + module.params.requires_grad_(False) + inference_output = module(inputs.detach()) + torch.cuda.synchronize() + self.assertEqual(inference_output.shape, output.shape) + + def test_upstream_double_gradient_without_parameter_or_input_result(self) -> None: + module = tcnn.Encoding( + n_input_dims=5, + encoding_config={ + "otype": "Permuto", + "n_levels": 4, + "n_features_per_level": 2, + "log2_hashmap_size": 8, + "base_scale": 4.0, + "per_level_scale": 1.5, + "max_input_grad_dims": 3, + }, + seed=17, + dtype=torch.float32, + ) + module.params.requires_grad_(False) + module.backward_backward_input_no_input_grad = True + + torch.manual_seed(19) + inputs = torch.rand((256, 5), device="cuda", dtype=torch.float32, requires_grad=True) + output_probe = torch.randn((256, 8), device=inputs.device, dtype=module.dtype, requires_grad=True) + second_order_probe = torch.randn((5, 256), device=inputs.device, dtype=inputs.dtype).T + self.assertFalse(second_order_probe.is_contiguous()) + input_gradient = torch.autograd.grad(module(inputs), inputs, output_probe, create_graph=True)[0] + upstream_gradient = torch.autograd.grad((input_gradient * second_order_probe).sum(), output_probe)[0] + + self.assertTrue(torch.isfinite(upstream_gradient).all().item()) + self.assertGreater(torch.count_nonzero(upstream_gradient).item(), 0) + + + def test_frozen_network_double_backward_input_gradient(self) -> None: + for activation, supported in (("ReLU", True), ("Tanh", False)): + with self.subTest(activation=activation): + module = tcnn.Network( + n_input_dims=3, + n_output_dims=16, + network_config={ + "otype": "FullyFusedMLP", + "activation": activation, + "output_activation": "None", + "n_neurons": 64, + "n_hidden_layers": 1, + }, + seed=5, + ) + module.params.requires_grad_(False) + + torch.manual_seed(23) + inputs = torch.rand((256, 3), device="cuda", dtype=torch.float32, requires_grad=True) + output_probe = torch.randn((256, 16), device=inputs.device, dtype=module.dtype) + input_gradient = torch.autograd.grad(module(inputs), inputs, output_probe, create_graph=True)[0] + gradient_loss = (input_gradient * torch.randn_like(input_gradient)).sum() + + if not supported: + with self.assertRaisesRegex(RuntimeError, "one hidden ReLU layer"): + torch.autograd.grad(gradient_loss, inputs) + continue + + (second_order_gradient,) = torch.autograd.grad(gradient_loss, inputs) + self.assertEqual(torch.count_nonzero(second_order_gradient).item(), 0) + +if __name__ == "__main__": + unittest.main() diff --git a/bindings/torch/tinycudann/bindings.cpp b/bindings/torch/tinycudann/bindings.cpp index a50b1367..5667d63f 100644 --- a/bindings/torch/tinycudann/bindings.cpp +++ b/bindings/torch/tinycudann/bindings.cpp @@ -219,21 +219,22 @@ class Module { } torch::Tensor dL_dinput; - if (input.requires_grad()) { + bool input_requires_grad = input.requires_grad() && !m_bwdbwd_no_input_grad; + if (input_requires_grad) { dL_dinput = torch::zeros({ batch_size, n_input_dims() }, torch::TensorOptions().dtype(torch::kFloat32).device(device)); } - if (dL_doutput.requires_grad() || params.requires_grad()) { + if (dL_doutput.requires_grad() || params.requires_grad() || input_requires_grad) { m_module->backward_backward_input( stream, ctx, batch_size, dL_ddLdinput.data_ptr(), input.data_ptr(), - (params.requires_grad() || input.requires_grad() ) ? void_data_ptr(dL_doutput) : nullptr, + void_data_ptr(dL_doutput), params.requires_grad() ? void_data_ptr(dL_dparams) : nullptr, dL_doutput.requires_grad() ? void_data_ptr(dL_ddLdoutput) : nullptr, - input.requires_grad() ? dL_dinput.data_ptr() : nullptr, + input_requires_grad ? dL_dinput.data_ptr() : nullptr, void_data_ptr(params) ); } @@ -263,8 +264,12 @@ class Module { bool jit_fusion() const { return m_module->jit_fusion(); } void set_jit_fusion(bool val) { m_module->set_jit_fusion(val); } + bool backward_backward_input_no_input_grad() const { return m_bwdbwd_no_input_grad; } + void set_backward_backward_input_no_input_grad(bool val) { m_bwdbwd_no_input_grad = val; } + private: std::unique_ptr m_module; + bool m_bwdbwd_no_input_grad = false; }; #if !defined(TCNN_NO_NETWORKS) @@ -332,6 +337,7 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { .def("hyperparams", &Module::hyperparams) .def("name", &Module::name) .def_property("jit_fusion", &Module::jit_fusion, &Module::set_jit_fusion) + .def_property("backward_backward_input_no_input_grad", &Module::backward_backward_input_no_input_grad, &Module::set_backward_backward_input_no_input_grad) ; #if !defined(TCNN_NO_NETWORKS) diff --git a/bindings/torch/tinycudann/modules.py b/bindings/torch/tinycudann/modules.py index db50a385..a62cd2b7 100644 --- a/bindings/torch/tinycudann/modules.py +++ b/bindings/torch/tinycudann/modules.py @@ -187,7 +187,7 @@ def backward(ctx, dinput_grad, dparams_grad): ctx.ctx_fwd.native_ctx, input, params, - dinput_grad, + dinput_grad.contiguous(), doutput ) # NOTE: be cautious when multiplying and dividing loss_scale @@ -259,6 +259,18 @@ def jit_fusion(self, val): def jit_fusion(self): raise AttributeError("`jit_fusion` can not be deleted") + @property + def backward_backward_input_no_input_grad(self): + return self.native_tcnn_module.backward_backward_input_no_input_grad + + @backward_backward_input_no_input_grad.setter + def backward_backward_input_no_input_grad(self, val): + self.native_tcnn_module.backward_backward_input_no_input_grad = val + + @backward_backward_input_no_input_grad.deleter + def backward_backward_input_no_input_grad(self): + raise AttributeError("`backward_backward_input_no_input_grad` can not be deleted") + class NetworkWithInputEncoding(Module): """ Input encoding, followed by a neural network. diff --git a/include/tiny-cuda-nn/encodings/grid.h b/include/tiny-cuda-nn/encodings/grid.h index 936e1c90..6b290df1 100644 --- a/include/tiny-cuda-nn/encodings/grid.h +++ b/include/tiny-cuda-nn/encodings/grid.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2025, NVIDIA CORPORATION. All rights reserved. + * Copyright (c) 2020-2026, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: @@ -239,7 +239,7 @@ __global__ void kernel_grid_backward( max_level = (max_level * num_grid_features) / N_FEATURES_PER_LEVEL; } - if (level > max_level + 1e-3f) { + if (level >= max_level + 1e-3f) { return; } @@ -379,7 +379,7 @@ __global__ void kernel_grid_backward_input_backward_grid( max_level = (max_level * num_grid_features) / N_FEATURES_PER_LEVEL; } - if (level > max_level + 1e-3f) { + if (level >= max_level + 1e-3f) { return; } @@ -485,7 +485,7 @@ __global__ void kernel_grid_backward_input_backward_input( max_level = (max_level * num_grid_features) / N_FEATURES_PER_LEVEL; } - if (level > max_level + 1e-3f) { + if (level >= max_level + 1e-3f) { return; } @@ -1108,6 +1108,10 @@ class GridEncodingTemplated : public MultiLevelEncoding { return N_POS_DIMS; } + uint32_t n_levels() const override { + return m_n_levels; + } + uint32_t n_features_per_level() const override { return N_FEATURES_PER_LEVEL; } diff --git a/include/tiny-cuda-nn/encodings/identity.h b/include/tiny-cuda-nn/encodings/identity.h index 024dd7f2..979c4c7c 100644 --- a/include/tiny-cuda-nn/encodings/identity.h +++ b/include/tiny-cuda-nn/encodings/identity.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2025, NVIDIA CORPORATION. All rights reserved. + * Copyright (c) 2020-2026, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: @@ -84,6 +84,26 @@ __global__ void identity_backward( dL_dx(j, i) = (T)((float)dL_dy(j, i) * scale); } +template +__global__ void identity_backward_backward_input( + const uint32_t num_outputs, + const uint32_t num_to_encode, + const uint32_t num_to_pad, + const float scale, + MatrixView dL_ddLdx, + MatrixView dL_ddLdy) +{ + const uint32_t encoded_index = threadIdx.x + blockIdx.x * blockDim.x; + if (encoded_index >= num_outputs) return; + + const uint32_t fan_out = num_to_encode + num_to_pad; + const uint32_t i = encoded_index / fan_out; + const uint32_t j = encoded_index - i * fan_out; + + // Padded outputs are constant and do not contribute to dL_dx. + dL_ddLdy(j, i) = j < num_to_encode ? (T)(dL_ddLdx(j, i) * scale) : (T)0.0f; +} + template class IdentityEncoding : public Encoding { public: @@ -139,6 +159,36 @@ class IdentityEncoding : public Encoding { dL_dinput->view() ); } + + void backward_backward_input_impl( + cudaStream_t stream, + const Context& ctx, + const GPUMatrixDynamic& input, + const GPUMatrixDynamic& dL_ddLdinput, + const GPUMatrixDynamic& dL_doutput, + GPUMatrixDynamic* dL_ddLdoutput = nullptr, + GPUMatrixDynamic* dL_dinput = nullptr, + bool use_inference_params = false, + GradientMode param_gradients_mode = GradientMode::Overwrite + ) override { + if (dL_ddLdoutput) { + linear_kernel(identity_backward_backward_input, 0, stream, + input.n() * padded_output_width(), + m_n_dims_to_encode, + m_n_to_pad, + m_scale, + dL_ddLdinput.view(), + dL_ddLdoutput->view() + ); + } + + // The encoding is linear, so its input Hessian is zero. + if (dL_dinput) { + parallel_for_gpu(stream, input.n() * m_n_dims_to_encode, [n_dims=m_n_dims_to_encode, dL_dx=dL_dinput->view()] __device__ (size_t index) { + dL_dx((uint32_t)(index % n_dims), (uint32_t)(index / n_dims)) = 0.0f; + }); + } + } #endif // !defined(TCNN_NO_FWD_BWD) uint32_t input_width() const override { diff --git a/include/tiny-cuda-nn/encodings/internal/permuto.h b/include/tiny-cuda-nn/encodings/internal/permuto.h new file mode 100644 index 00000000..53cf4562 --- /dev/null +++ b/include/tiny-cuda-nn/encodings/internal/permuto.h @@ -0,0 +1,1201 @@ +/* + * Copyright (c) 2021-2026, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted + * provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of + * conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** @file permuto.h + * @author Jianfei Guo, NVIDIA + * @brief Trainable hierarchy of N-D permutohedral lattice grids of floating point values. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace tcnn { + +static constexpr uint32_t PERMUTO_MAX_N_LEVELS = 32; + +inline constexpr TCNN_HOST_DEVICE bool permuto_level_is_inactive(uint32_t level, float max_level) { return level >= max_level + 1e-3f; } + +template +__device__ __forceinline__ void permuto_prepare( + uint32_t element, + uint32_t level, + float base_scale, + float log2_per_level_scale, + pcg32 rng, + MatrixView positions_in, + float* __restrict__ scales_per_dim, + float* __restrict__ elevated, + int* __restrict__ rem0, + int* __restrict__ rank +) { + float pos[N_DIMS]; + float shifts_per_dim[N_DIMS]; + const float scale = base_scale * exp2f(level * log2_per_level_scale); + rng.advance(level * N_DIMS); + TCNN_PRAGMA_UNROLL + for (uint32_t dim = 0; dim < N_DIMS; ++dim) { + pos[dim] = positions_in(dim, element); + scales_per_dim[dim] = scale * rsqrtf((dim + 1) * (dim + 2)); + shifts_per_dim[dim] = fmaf(rng.next_float(), 10.0f, -5.0f); + } + + float sum = 0; + TCNN_PRAGMA_UNROLL + for (int dim = N_DIMS; dim > 0; --dim) { + const float cf = (pos[dim - 1] + shifts_per_dim[dim - 1]) * scales_per_dim[dim - 1]; + elevated[dim] = sum - (float)dim * cf; + sum += cf; + } + elevated[0] = sum; + + int rem0_sum = 0; + TCNN_PRAGMA_UNROLL + for (uint32_t dim = 0; dim <= N_DIMS; ++dim) { + const float v = elevated[dim] * (1.0f / (N_DIMS + 1)); + const float up = ceil(v) * (N_DIMS + 1); + const float down = floor(v) * (N_DIMS + 1); + rem0[dim] = up - elevated[dim] < elevated[dim] - down ? (int)up : (int)down; + rem0_sum += rem0[dim]; + } + rem0_sum /= (int)(N_DIMS + 1); + + TCNN_PRAGMA_UNROLL + for (uint32_t dim = 0; dim < N_DIMS; ++dim) { + const float di = elevated[dim] - rem0[dim]; + for (uint32_t other_dim = dim + 1; other_dim <= N_DIMS; ++other_dim) { + if (di < elevated[other_dim] - rem0[other_dim]) { + ++rank[dim]; + } else { + ++rank[other_dim]; + } + } + } + + TCNN_PRAGMA_UNROLL + for (uint32_t dim = 0; dim <= N_DIMS; ++dim) { + rank[dim] += rem0_sum; + if (rank[dim] < 0) { + rank[dim] += (int)(N_DIMS + 1); + rem0[dim] += (int)(N_DIMS + 1); + } else if (rank[dim] > (int)N_DIMS) { + rank[dim] -= (int)(N_DIMS + 1); + rem0[dim] -= (int)(N_DIMS + 1); + } + } +} + +template +__global__ void kernel_permuto( + const uint32_t num_elements, + const uint32_t num_grid_features, + const ParamsOffsetTable offset_table, + const float base_scale, + const float log2_per_level_scale, + pcg32 rng, + float max_level, + const float* __restrict__ max_level_gpu, + const T* __restrict__ grid, + MatrixView positions_in, + MatrixView encoded_positions +) { + const uint32_t i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= num_elements) { + return; + } + + const uint32_t level = blockIdx.y; // <- the level is the same for all threads + + if (max_level_gpu) { + max_level = (max_level_gpu[i] * num_grid_features) / N_FEATURES_PER_LEVEL; + } else { + max_level = (max_level * num_grid_features) / N_FEATURES_PER_LEVEL; + } + + if (permuto_level_is_inactive(level, max_level)) { + TCNN_PRAGMA_UNROLL + for (uint32_t f = 0; f < N_FEATURES_PER_LEVEL; ++f) { + encoded_positions(level * N_FEATURES_PER_LEVEL + f, i) = (T)0.0f; + } + return; + } + + grid += offset_table.data[level] * N_FEATURES_PER_LEVEL; + const uint32_t hashmap_size = offset_table.data[level + 1] - offset_table.data[level]; + + float scales_per_dim[N_POS_DIMS]; + float elevated[N_POS_DIMS + 1]; + int rem0[N_POS_DIMS + 1]; + int rank[N_POS_DIMS + 1]{0}; + permuto_prepare(i, level, base_scale, log2_per_level_scale, rng, positions_in, scales_per_dim, elevated, rem0, rank); + + //---- Compute the barycentric coordinates (p.10 in [Adams etal 2010]) + float barycentric[N_POS_DIMS + 2]{0}; + TCNN_PRAGMA_UNROLL + for (uint32_t dim = 0; dim <= N_POS_DIMS; ++dim) { + const float delta = (elevated[dim] - rem0[dim]) * (1.0f / (N_POS_DIMS + 1)); + barycentric[(int)N_POS_DIMS - rank[dim]] += delta; + barycentric[(int)(N_POS_DIMS + 1) - rank[dim]] -= delta; + } + barycentric[0] += 1.0f + barycentric[N_POS_DIMS + 1]; + + //---- Prepare + tvec result((T)0.0f); + + //---- Interpolate the values to calculate encoded + uvec key; + TCNN_PRAGMA_UNROLL + for (uint32_t k = 0; k <= N_POS_DIMS; ++k) { // For each remainder-k vertex: for k \in {0,1,...,d} + // Compute the coordinates of the remainder-k vertex explicitly + // (all but the last coordinate - it's redundant because they sum to zero) + TCNN_PRAGMA_UNROLL + for (uint32_t dim = 0; dim < N_POS_DIMS; ++dim) { + key[dim] = rem0[dim] + (int)k; + if (rank[dim] > (int)(N_POS_DIMS - k)) { + key[dim] -= (int)(N_POS_DIMS + 1); + } + } + + // Accumulate vertex's feature value by the barycentric weight + const float weight = barycentric[k]; + const uint32_t index = (base_convert_hash(key) % hashmap_size) * N_FEATURES_PER_LEVEL; + const auto value = *(tvec < T, N_FEATURES_PER_LEVEL, PARAMS_ALIGNED ? sizeof(T) * N_FEATURES_PER_LEVEL : sizeof(T) > *)&grid[index]; + result = fma((T)weight, value, result); + } + + TCNN_PRAGMA_UNROLL + for (uint32_t f = 0; f < N_FEATURES_PER_LEVEL; ++f) { + encoded_positions(level * N_FEATURES_PER_LEVEL + f, i) = result[f]; + } +} + +template +__global__ void kernel_permuto_backward( + const uint32_t num_elements, + const uint32_t num_grid_features, + const ParamsOffsetTable offset_table, + const float base_scale, + const float log2_per_level_scale, + pcg32 rng, + float max_level, + const float* __restrict__ max_level_gpu, + // Inputs + MatrixView dL_dy, + MatrixView positions_in, + // Outputs + GRAD_T* __restrict__ grid_gradient +) { + const uint32_t i = ((blockIdx.x * blockDim.x + threadIdx.x) * N_FEATURES_PER_THREAD) / N_FEATURES_PER_LEVEL; + if (i >= num_elements) { + return; + } + + const uint32_t level = blockIdx.y; // <- the level is the same for all threads. + const uint32_t feature = (blockIdx.x * blockDim.x + threadIdx.x) * N_FEATURES_PER_THREAD - i * N_FEATURES_PER_LEVEL; + + if (max_level_gpu) { + max_level = (max_level_gpu[i] * num_grid_features) / N_FEATURES_PER_LEVEL; + } else { + max_level = (max_level * num_grid_features) / N_FEATURES_PER_LEVEL; + } + + if (permuto_level_is_inactive(level, max_level)) { + return; + } + + grid_gradient += offset_table.data[level] * N_FEATURES_PER_LEVEL; + const uint32_t hashmap_size = offset_table.data[level + 1] - offset_table.data[level]; + + float scales_per_dim[N_POS_DIMS]; + float elevated[N_POS_DIMS + 1]; + int rem0[N_POS_DIMS + 1]; + int rank[N_POS_DIMS + 1]{0}; + permuto_prepare(i, level, base_scale, log2_per_level_scale, rng, positions_in, scales_per_dim, elevated, rem0, rank); + + //---- Compute the barycentric coordinates (p.10 in [Adams etal 2010]) + float barycentric[N_POS_DIMS + 2]{0}; + TCNN_PRAGMA_UNROLL + for (uint32_t dim = 0; dim <= N_POS_DIMS; ++dim) { + const float delta = (elevated[dim] - rem0[dim]) * (1.0f / (N_POS_DIMS + 1)); + barycentric[(int)N_POS_DIMS - rank[dim]] += delta; + barycentric[(int)(N_POS_DIMS + 1) - rank[dim]] -= delta; + } + barycentric[0] += 1.0f + barycentric[N_POS_DIMS + 1]; + + // Force using float to ensure numerical stability + tvec grad; + TCNN_PRAGMA_UNROLL + for (uint32_t f = 0; f < N_FEATURES_PER_THREAD; ++f) { + grad[f] = (float)dL_dy(level * N_FEATURES_PER_LEVEL + feature + f, i); + } + + //---- Calculate grid_gradient + uvec key; + TCNN_PRAGMA_UNROLL + for (uint32_t k = 0; k <= N_POS_DIMS; ++k) { // For each remainder-k vertex: for k \in {0,1,...,d} + // Compute the coordinates of the remainder-k vertex explicitly + // (all but the last coordinate - it's redundant because they sum to zero) + TCNN_PRAGMA_UNROLL + for (uint32_t dim = 0; dim < N_POS_DIMS; ++dim) { + key[dim] = rem0[dim] + (int)k; + if (rank[dim] > (int)(N_POS_DIMS - k)) { + key[dim] -= (int)(N_POS_DIMS + 1); + } + } + + // Accumulate vertex's gradients by the barycentric weight + const float weight = barycentric[k]; + const uint32_t index = (base_convert_hash(key) % hashmap_size) * N_FEATURES_PER_LEVEL + feature; + atomic_add_gmem(grid_gradient + index, tvec(weight * grad)); + } +} + +template +__global__ void kernel_permuto_backward_input( + const uint32_t num_elements, + const uint32_t num_grid_features, + const ParamsOffsetTable offset_table, + const float base_scale, + const float log2_per_level_scale, + pcg32 rng, + float max_level, + const float* __restrict__ max_level_gpu, + const uint32_t max_input_grad_dims, // If we want to limit the computation to first-n dims + // Inputs + const T* __restrict__ grid, + MatrixView dL_dy, + MatrixView positions_in, + // Outputs + MatrixView dL_dx +) { + const uint32_t i = ((blockIdx.x * blockDim.x + threadIdx.x) * N_FEATURES_PER_THREAD) / N_FEATURES_PER_LEVEL; + if (i >= num_elements) { + return; + } + + const uint32_t level = blockIdx.y; // <- the level is the same for all threads. + const uint32_t feature = (blockIdx.x * blockDim.x + threadIdx.x) * N_FEATURES_PER_THREAD - i * N_FEATURES_PER_LEVEL; + + if (max_level_gpu) { + max_level = (max_level_gpu[i] * num_grid_features) / N_FEATURES_PER_LEVEL; + } else { + max_level = (max_level * num_grid_features) / N_FEATURES_PER_LEVEL; + } + + if (permuto_level_is_inactive(level, max_level)) { + return; + } + + grid += offset_table.data[level] * N_FEATURES_PER_LEVEL; + const uint32_t hashmap_size = offset_table.data[level + 1] - offset_table.data[level]; + + float scales_per_dim[N_POS_DIMS]; + float elevated[N_POS_DIMS + 1]; + int rem0[N_POS_DIMS + 1]; + int rank[N_POS_DIMS + 1]{0}; + permuto_prepare(i, level, base_scale, log2_per_level_scale, rng, positions_in, scales_per_dim, elevated, rem0, rank); + + // Force using float to ensure numerical stability + tvec grad; + TCNN_PRAGMA_UNROLL + for (uint32_t f = 0; f < N_FEATURES_PER_THREAD; ++f) { + grad[f] = (float)dL_dy(level * N_FEATURES_PER_LEVEL + feature + f, i); + } + + //---- Calculate dL_dx + // The upstream gradient dL/dy differentiates the loss with respect to the encoded value. + // If we require positions grad we want to obtain dL/dx + // dL/dx = dL/dy * dy/dB * dB/dE * dE/dx + // We need dy/dB which is the derivative of the sliced value wrt to the barycentric coords + // We need dB/dE which is the derivative of the barycentric wrt to the elevated value + // We need dE/dx which is the derivative of the elevated wrt to the position in xyz + + // dL/dB = dL/dy * dy/dB + uvec key; + float dL_dbarycentric[N_POS_DIMS + 2]{0}; + TCNN_PRAGMA_UNROLL + for (uint32_t k = 0; k <= N_POS_DIMS; ++k) { // For each remainder-k vertex: for k \in {0,1,...,d} + // Compute the coordinates of the remainder-k vertex explicitly + // (all but the last coordinate - it's redundant because they sum to zero) + TCNN_PRAGMA_UNROLL + for (uint32_t dim = 0; dim < N_POS_DIMS; ++dim) { + key[dim] = rem0[dim] + (int)k; + if (rank[dim] > (int)(N_POS_DIMS - k)) { + key[dim] -= (int)(N_POS_DIMS + 1); + } + } + + // Add to dL_d_barycentric + const uint32_t index = (base_convert_hash(key) % hashmap_size) * N_FEATURES_PER_LEVEL + feature; + const auto val = *(tvec < T, N_FEATURES_PER_THREAD, PARAMS_ALIGNED ? sizeof(T) * N_FEATURES_PER_THREAD : sizeof(T) > *)&grid[index]; + TCNN_PRAGMA_UNROLL + for (uint32_t f = 0; f < N_FEATURES_PER_THREAD; ++f) { + dL_dbarycentric[k] += (float)val[f] * (float)grad[f]; + } + } + dL_dbarycentric[N_POS_DIMS + 1] += dL_dbarycentric[0]; + + // dL/dE = dL/dB * dB/dE + float dL_delevated[N_POS_DIMS + 1]{0}; + TCNN_PRAGMA_UNROLL + for (uint32_t dim = 0; dim <= N_POS_DIMS; ++dim) { + dL_delevated[dim] += dL_dbarycentric[(int)N_POS_DIMS - rank[dim]] * (1.0f / (N_POS_DIMS + 1)); + dL_delevated[dim] -= dL_dbarycentric[(int)(N_POS_DIMS + 1) - rank[dim]] * (1.0f / (N_POS_DIMS + 1)); + } + + // dL/dx = dL/dE * dE/dx + tvec dL_dx_local(0.0f); + TCNN_PRAGMA_UNROLL + for (uint32_t dim = 0; dim < max_input_grad_dims; ++dim) { + float dL_dx_dim = 0; + TCNN_PRAGMA_UNROLL + for (uint32_t other_dim = 0; other_dim <= dim; ++other_dim) { + dL_dx_dim += dL_delevated[other_dim] * scales_per_dim[dim]; + } + dL_dx_dim -= dL_delevated[dim + 1] * scales_per_dim[dim] * (dim + 1); + dL_dx_local[dim] = dL_dx_dim; + } + + //---- Finish + // Should be atomic, since different levels of dL_dy can backward to the same input. + TCNN_PRAGMA_UNROLL + for (uint32_t dim = 0; dim < N_POS_DIMS; ++dim) { + atomicAdd(&dL_dx(dim, i), dL_dx_local[dim]); + } +} + +template +__global__ void kernel_permuto_backward_backward_input( + const uint32_t num_elements, + const uint32_t num_grid_features, + const ParamsOffsetTable offset_table, + const float base_scale, + const float log2_per_level_scale, + pcg32 rng, + float max_level, + const float* __restrict__ max_level_gpu, + const uint32_t max_input_grad_dims, + MatrixView dL_ddLdx, + MatrixView positions_in, + MatrixView dL_dy, + const T* __restrict__ grid, + GRAD_T* __restrict__ grid_gradient, + MatrixView dL_ddLdy +) { + const uint32_t i = ((blockIdx.x * blockDim.x + threadIdx.x) * N_FEATURES_PER_THREAD) / N_FEATURES_PER_LEVEL; + if (i >= num_elements) { + return; + } + + const uint32_t level = blockIdx.y; + const uint32_t feature = (blockIdx.x * blockDim.x + threadIdx.x) * N_FEATURES_PER_THREAD - i * N_FEATURES_PER_LEVEL; + + if (max_level_gpu) { + max_level = (max_level_gpu[i] * num_grid_features) / N_FEATURES_PER_LEVEL; + } else { + max_level = (max_level * num_grid_features) / N_FEATURES_PER_LEVEL; + } + + if (permuto_level_is_inactive(level, max_level)) { + if (dL_ddLdy.data) { + TCNN_PRAGMA_UNROLL + for (uint32_t f = 0; f < N_FEATURES_PER_THREAD; ++f) { + dL_ddLdy(level * N_FEATURES_PER_LEVEL + feature + f, i) = (T)0.0f; + } + } + return; + } + + grid += offset_table.data[level] * N_FEATURES_PER_LEVEL; + if (grid_gradient) { + grid_gradient += offset_table.data[level] * N_FEATURES_PER_LEVEL; + } + const uint32_t hashmap_size = offset_table.data[level + 1] - offset_table.data[level]; + + float scales_per_dim[N_POS_DIMS]; + float elevated[N_POS_DIMS + 1]; + int rem0[N_POS_DIMS + 1]; + int rank[N_POS_DIMS + 1]{0}; + permuto_prepare(i, level, base_scale, log2_per_level_scale, rng, positions_in, scales_per_dim, elevated, rem0, rank); + + float dL_delevated[N_POS_DIMS + 1]{0}; + TCNN_PRAGMA_UNROLL + for (uint32_t dim = 0; dim < max_input_grad_dims; ++dim) { + const float grad = dL_ddLdx(dim, i) * scales_per_dim[dim]; + TCNN_PRAGMA_UNROLL + for (uint32_t other_dim = 0; other_dim <= dim; ++other_dim) { + dL_delevated[other_dim] += grad; + } + dL_delevated[dim + 1] -= grad * (dim + 1); + } + + float dL_dbarycentric[N_POS_DIMS + 2]{0}; + TCNN_PRAGMA_UNROLL + for (uint32_t dim = 0; dim <= N_POS_DIMS; ++dim) { + const float grad = dL_delevated[dim] * (1.0f / (N_POS_DIMS + 1)); + dL_dbarycentric[(int)N_POS_DIMS - rank[dim]] += grad; + dL_dbarycentric[(int)(N_POS_DIMS + 1) - rank[dim]] -= grad; + } + dL_dbarycentric[0] += dL_dbarycentric[N_POS_DIMS + 1]; + + tvec dL_ddLdy_local(0.0f); + tvec dL_dy_local; + TCNN_PRAGMA_UNROLL + for (uint32_t f = 0; f < N_FEATURES_PER_THREAD; ++f) { + dL_dy_local[f] = (float)dL_dy(level * N_FEATURES_PER_LEVEL + feature + f, i); + } + + uvec key; + TCNN_PRAGMA_UNROLL + for (uint32_t k = 0; k <= N_POS_DIMS; ++k) { + TCNN_PRAGMA_UNROLL + for (uint32_t dim = 0; dim < N_POS_DIMS; ++dim) { + key[dim] = rem0[dim] + (int)k; + if (rank[dim] > (int)(N_POS_DIMS - k)) { + key[dim] -= (int)(N_POS_DIMS + 1); + } + } + + const uint32_t index = (base_convert_hash(key) % hashmap_size) * N_FEATURES_PER_LEVEL + feature; + if (dL_ddLdy.data) { + const auto value = *(tvec*)&grid[index]; + TCNN_PRAGMA_UNROLL + for (uint32_t f = 0; f < N_FEATURES_PER_THREAD; ++f) { + dL_ddLdy_local[f] = fmaf(dL_dbarycentric[k], (float)value[f], dL_ddLdy_local[f]); + } + } + + if (grid_gradient) { + atomic_add_gmem(grid_gradient + index, tvec(dL_dbarycentric[k] * dL_dy_local)); + } + } + + if (dL_ddLdy.data) { + TCNN_PRAGMA_UNROLL + for (uint32_t f = 0; f < N_FEATURES_PER_THREAD; ++f) { + dL_ddLdy(level * N_FEATURES_PER_LEVEL + feature + f, i) = (T)dL_ddLdy_local[f]; + } + } +} + +template +class PermutoEncodingTemplated : public MultiLevelEncoding { +public: +#if TCNN_MIN_GPU_ARCH >= 62 || TCNN_MIN_GPU_ARCH == 60 + // The GPUs that we tested this on do not have an efficient 1D fp16 + // atomicAdd feature. Thus, we accumulate gradients at fp32 if we're + // forced to use 1D atomicAdds. As soon as 2D or higher is possible, + // we can make use the efficient atomicAdd(half2) function. + using grad_t = std::conditional_t; +#else + // atomicAdd(__half2) is only supported with compute capability 60 and above. + // Since atomicAdd(__half) is relatively slow / doesn't exist for low compute + // capabilities, accumulate in fp32 instead. + using grad_t = float; +#endif + + PermutoEncodingTemplated( + uint32_t n_features, uint32_t log2_hashmap_size, float base_scale, float per_level_scale, uint32_t max_input_grad_dims, uint32_t seed = 1337 + ) : + m_n_features{n_features}, + m_rng{seed}, + m_seed{seed}, + m_log2_hashmap_size{log2_hashmap_size}, + m_max_input_grad_dims{max_input_grad_dims}, + m_per_level_scale{per_level_scale}, + m_base_scale{base_scale} { + if (n_features == 0 || n_features % N_FEATURES_PER_LEVEL != 0) { + throw std::runtime_error{fmt::format( + "PermutoEncoding: n_features={} must be a nonzero multiple of N_FEATURES_PER_LEVEL={}", n_features, N_FEATURES_PER_LEVEL + )}; + } + + m_n_levels = n_features / N_FEATURES_PER_LEVEL; + if (m_n_levels > PERMUTO_MAX_N_LEVELS) { + throw std::runtime_error{ + fmt::format("PermutoEncoding: m_n_levels={} must be at most PERMUTO_MAX_N_LEVELS={}", m_n_levels, PERMUTO_MAX_N_LEVELS) + }; + } + + if (log2_hashmap_size >= std::numeric_limits::digits) { + throw std::runtime_error{fmt::format( + "PermutoEncoding: log2_hashmap_size={} must be less than {}", log2_hashmap_size, std::numeric_limits::digits + )}; + } + if (max_input_grad_dims > N_POS_DIMS) { + throw std::runtime_error{"PermutoEncoding: max_input_grad_dims exceeds its input width."}; + } + if (!std::isfinite(base_scale)) { + throw std::runtime_error{"PermutoEncoding: base_scale must be finite."}; + } + if (!std::isfinite(per_level_scale) || per_level_scale <= 0.0f) { + throw std::runtime_error{"PermutoEncoding: per_level_scale must be positive and finite."}; + } + + const uint64_t params_in_level = uint64_t{1} << log2_hashmap_size; + const uint64_t n_params = params_in_level * m_n_levels * N_FEATURES_PER_LEVEL; + if (n_params > std::numeric_limits::max()) { + throw std::runtime_error{fmt::format( + "PermutoEncoding: parameter count={} exceeds the supported maximum={}", n_params, std::numeric_limits::max() + )}; + } + + const float log2_per_level_scale = std::log2(per_level_scale); + constexpr double max_abs_position = 1.0; + constexpr double max_abs_lattice_shift = 5.0; + const double rounded_coordinate_budget = static_cast(std::numeric_limits::max()) / (2.0 * (N_POS_DIMS + 1)); + const double max_abs_scale = (rounded_coordinate_budget - (N_POS_DIMS + 1)) / + (N_POS_DIMS * (max_abs_position + max_abs_lattice_shift)); + + uint64_t offset = 0; + for (uint32_t level = 0; level < m_n_levels; ++level) { + m_offset_table.data[level] = static_cast(offset); + offset += params_in_level; + + const float scale = base_scale * exp2f(level * log2_per_level_scale); + if (!std::isfinite(scale) || std::abs(static_cast(scale)) > max_abs_scale) { + throw std::runtime_error{ + fmt::format("PermutoEncoding: scale at level {} is outside the normalized-input coordinate range.", level) + }; + } + log_debug("PermutoEncoding at level {}: scale={} params_in_level={}", level, scale, params_in_level); + } + + m_offset_table.data[m_n_levels] = static_cast(offset); + m_offset_table.size = m_n_levels + 1; + m_n_params = static_cast(n_params); + } + +#if !defined(TCNN_NO_FWD_BWD) + std::unique_ptr forward_impl( + cudaStream_t stream, + const GPUMatrixDynamic& input, + GPUMatrixDynamic* output = nullptr, + bool use_inference_params = false, + bool prepare_input_gradients = false + ) override { + (void)prepare_input_gradients; + auto forward = std::make_unique(); + + const uint32_t num_elements = input.n(); + if (!output || num_elements == 0) { + return forward; + } + + SyncedMultiStream synced_streams{stream, m_n_to_pad > 0 ? 2u : 1u}; + + // Take care of padding on the auxiliary stream + if (m_n_to_pad > 0) { + if (output->layout() == AoS) { + parallel_for_gpu_aos( + synced_streams.get(1), + num_elements, + m_n_to_pad, + [n_features = m_n_features, out = output->pitched_ptr()] __device__(size_t elem, size_t dim) { + out(elem)[n_features + dim] = 0; + } + ); + } else { + parallel_for_gpu( + synced_streams.get(1), + num_elements * m_n_to_pad, + [out = output->view(), n_features = m_n_features, num_elements] __device__(size_t i) { + const uint32_t element = static_cast(i % num_elements); + const uint32_t padding_row = n_features + static_cast(i / num_elements); + out(padding_row, element) = (T)0; + } + ); + } + } + + // Idea: each block only takes care of _one_ hash level (but may iterate over multiple input elements). + // This way, only one level of the hashmap needs to fit into caches at a time (and it is reused for consecutive + // elements) until it is time to process the next level. + + static constexpr uint32_t N_THREADS_HASHGRID = 512; + const dim3 blocks_hashgrid = {div_round_up(num_elements, N_THREADS_HASHGRID), m_n_levels, 1}; + + MatrixView encoded_positions_soa = output->view(); + GPUMemoryArena::Allocation workspace; + if (output->layout() == AoS) { + workspace = allocate_workspace(synced_streams.get(0), num_elements * m_n_features * sizeof(T)); + encoded_positions_soa = {reinterpret_cast(workspace.data()), num_elements, 1u}; + } + + kernel_permuto<<>>( + num_elements, + m_n_features, + m_offset_table, + m_base_scale, + std::log2(m_per_level_scale), + m_rng, + this->m_max_level, + this->m_max_level_gpu, + use_inference_params ? this->inference_params() : this->params(), + input.view(), + encoded_positions_soa + ); + + if (output->layout() == AoS) { + // Transpose result (was stored row major due to coalescing) + const dim3 threads_transpose = transpose_threads(); + const uint32_t blocks_transpose = div_round_up(num_elements, threads_transpose.y); + transpose_encoded_position<<>>( + num_elements, encoded_positions_soa.data, output->pitched_ptr() + ); + } + + return forward; + } + + void backward_impl( + cudaStream_t stream, + const Context&, + const GPUMatrixDynamic& input, + const GPUMatrixDynamic&, + const GPUMatrixDynamic& dL_doutput, + GPUMatrixDynamic* dL_dinput = nullptr, + bool use_inference_params = false, + GradientMode param_gradients_mode = GradientMode::Overwrite + ) override { + const uint32_t num_elements = input.n(); + if (num_elements == 0) { + if (param_gradients_mode == GradientMode::Overwrite) { + CUDA_CHECK_THROW(cudaMemsetAsync(this->gradients(), 0, n_params() * sizeof(T), stream)); + } + return; + } + if (!dL_dinput && param_gradients_mode == GradientMode::Ignore) { + return; + } + + MatrixView dL_dy_soa = dL_doutput.view(); + + GPUMemoryArena::Allocation workspace; + if (dL_doutput.layout() == AoS) { + workspace = allocate_workspace(stream, num_elements * m_n_features * sizeof(T)); + + // Transpose dL_dy. Use the buffer previously occupied by the encoded positions + const dim3 threads_transpose = transpose_threads(); + const uint32_t blocks_transpose = div_round_up(num_elements, threads_transpose.y); + transpose_gradients + <<>>(num_elements, (T*)workspace.data(), dL_doutput.pitched_ptr()); + + dL_dy_soa = {reinterpret_cast(workspace.data()), num_elements, 1u}; + } + + if (param_gradients_mode != GradientMode::Ignore) { + // We accumulate gradients with grad_t precision, which, for performance reasons, is not always T. + // If not, accumulate in a temporary buffer and cast later. + grad_t* grid_gradient = nullptr; + GPUMemoryArena::Allocation grid_gradient_tmp; + constexpr bool uses_temporary_gradient = !std::is_same::value; + + if (uses_temporary_gradient) { + grid_gradient_tmp = allocate_workspace(stream, m_n_params * sizeof(grad_t)); + grid_gradient = (grad_t*)grid_gradient_tmp.data(); + } else { + grid_gradient = (grad_t*)this->gradients(); + } + + if (param_gradients_mode == GradientMode::Overwrite || uses_temporary_gradient) { + CUDA_CHECK_THROW(cudaMemsetAsync(grid_gradient, 0, n_params() * sizeof(grad_t), stream)); + } + + static constexpr uint32_t N_THREADS_HASHGRID = 256; + static constexpr uint32_t N_FEATURES_PER_THREAD = std::min(2u, N_FEATURES_PER_LEVEL); + const dim3 blocks_hashgrid = { + div_round_up(num_elements * N_FEATURES_PER_LEVEL / N_FEATURES_PER_THREAD, N_THREADS_HASHGRID), m_n_levels, 1 + }; + kernel_permuto_backward + <<>>( + num_elements, + m_n_features, + m_offset_table, + m_base_scale, + std::log2(m_per_level_scale), + m_rng, + this->m_max_level, + this->m_max_level_gpu, + dL_dy_soa, + input.view(), + grid_gradient + ); + + if (uses_temporary_gradient) { + const bool accumulate = param_gradients_mode == GradientMode::Accumulate; + parallel_for_gpu(stream, n_params(), [grad = this->gradients(), grad_tmp = grid_gradient, accumulate] __device__(size_t i) { + const grad_t value = grad_tmp[i] + (accumulate ? (grad_t)grad[i] : (grad_t)0); + grad[i] = (T)value; + }); + } + } + + if (dL_dinput) { + parallel_for_gpu(stream, num_elements, [grad = dL_dinput->view()] __device__(size_t i) { + TCNN_PRAGMA_UNROLL + for (uint32_t dim = 0; dim < N_POS_DIMS; ++dim) { + grad(dim, i) = 0; + } + }); + + static constexpr uint32_t N_THREADS_HASHGRID = 256; + static constexpr uint32_t N_FEATURES_PER_THREAD = std::min(2u, N_FEATURES_PER_LEVEL); + const dim3 blocks_hashgrid = { + div_round_up(num_elements * N_FEATURES_PER_LEVEL / N_FEATURES_PER_THREAD, N_THREADS_HASHGRID), m_n_levels, 1 + }; + kernel_permuto_backward_input + <<>>( + num_elements, + m_n_features, + m_offset_table, + m_base_scale, + std::log2(m_per_level_scale), + m_rng, + this->m_max_level, + this->m_max_level_gpu, + m_max_input_grad_dims, + use_inference_params ? this->inference_params() : this->params(), + dL_dy_soa, + input.view(), + dL_dinput->view() + ); + } + } + + void backward_backward_input_impl( + cudaStream_t stream, + const Context&, + const GPUMatrixDynamic& input, + const GPUMatrixDynamic& dL_ddLdinput, + const GPUMatrixDynamic& dL_doutput, + GPUMatrixDynamic* dL_ddLdoutput = nullptr, + GPUMatrixDynamic* dL_dinput = nullptr, + bool use_inference_params = false, + GradientMode param_gradients_mode = GradientMode::Overwrite + ) override { + const uint32_t num_elements = input.n(); + if (num_elements == 0) { + if (param_gradients_mode == GradientMode::Overwrite && n_params() > 0) { + CUDA_CHECK_THROW(cudaMemsetAsync(this->gradients(), 0, n_params() * sizeof(T), stream)); + } + return; + } + if (padded_output_width() == 0 || (!dL_ddLdoutput && !dL_dinput && param_gradients_mode == GradientMode::Ignore)) { + return; + } + + if (dL_ddLdoutput && m_n_to_pad > 0) { + parallel_for_gpu(stream, num_elements * m_n_to_pad, [out = dL_ddLdoutput->view(), n_features = m_n_features, num_elements] __device__(size_t idx) { + const uint32_t element = (uint32_t)(idx % num_elements); + const uint32_t feature = n_features + (uint32_t)(idx / num_elements); + out(feature, element) = (T)0.0f; + }); + } + + MatrixView dL_dy_soa = dL_doutput.view(); + GPUMemoryArena::Allocation dL_dy_workspace; + if (dL_doutput.layout() == AoS) { + dL_dy_workspace = allocate_workspace(stream, num_elements * m_n_features * sizeof(T)); + const dim3 threads_transpose = transpose_threads(); + const uint32_t blocks_transpose = div_round_up(num_elements, threads_transpose.y); + transpose_gradients<<>>( + num_elements, (T*)dL_dy_workspace.data(), dL_doutput.pitched_ptr() + ); + dL_dy_soa = {reinterpret_cast(dL_dy_workspace.data()), num_elements, 1u}; + } + + grad_t* grid_gradient = nullptr; + GPUMemoryArena::Allocation grid_gradient_tmp; + constexpr bool uses_temporary_gradient = !std::is_same::value; + if (param_gradients_mode != GradientMode::Ignore) { + if (uses_temporary_gradient) { + grid_gradient_tmp = allocate_workspace(stream, m_n_params * sizeof(grad_t)); + grid_gradient = (grad_t*)grid_gradient_tmp.data(); + } else { + grid_gradient = (grad_t*)this->gradients(); + } + + if (param_gradients_mode == GradientMode::Overwrite || uses_temporary_gradient) { + CUDA_CHECK_THROW(cudaMemsetAsync(grid_gradient, 0, n_params() * sizeof(grad_t), stream)); + } + } + + if (grid_gradient || dL_ddLdoutput) { + static constexpr uint32_t N_THREADS_HASHGRID = 256; + static constexpr uint32_t N_FEATURES_PER_THREAD = std::min(2u, N_FEATURES_PER_LEVEL); + const dim3 blocks_hashgrid = { + div_round_up(num_elements * N_FEATURES_PER_LEVEL / N_FEATURES_PER_THREAD, N_THREADS_HASHGRID), m_n_levels, 1 + }; + kernel_permuto_backward_backward_input + <<>>( + num_elements, + m_n_features, + m_offset_table, + m_base_scale, + std::log2(m_per_level_scale), + m_rng, + this->m_max_level, + this->m_max_level_gpu, + m_max_input_grad_dims, + dL_ddLdinput.view(), + input.view(), + dL_dy_soa, + use_inference_params ? this->inference_params() : this->params(), + grid_gradient, + dL_ddLdoutput ? dL_ddLdoutput->view() : MatrixView{} + ); + } + + if (uses_temporary_gradient && grid_gradient) { + const bool accumulate = param_gradients_mode == GradientMode::Accumulate; + parallel_for_gpu(stream, n_params(), [grad = this->gradients(), grad_tmp = grid_gradient, accumulate] __device__(size_t i) { + grad[i] = (T)(grad_tmp[i] + (accumulate ? (grad_t)grad[i] : (grad_t)0)); + }); + } + + if (dL_dinput) { + parallel_for_gpu(stream, num_elements, [gradient = dL_dinput->view()] __device__(size_t i) { + TCNN_PRAGMA_UNROLL + for (uint32_t dim = 0; dim < N_POS_DIMS; ++dim) { + gradient(dim, i) = 0.0f; + } + }); + } + } + + #endif // !defined(TCNN_NO_FWD_BWD) + + uint32_t input_width() const override { return N_POS_DIMS; } + + uint32_t padded_output_width() const override { return m_n_features + m_n_to_pad; } + + uint32_t output_width() const override { return padded_output_width(); } + + uint32_t required_input_alignment() const override { return 1; } + + void set_padded_output_width(uint32_t padded_output_width) override { + CHECK_THROW(padded_output_width >= m_n_features); + m_n_to_pad = padded_output_width - m_n_features; + } + + uint32_t required_output_alignment() const override { return N_FEATURES_PER_LEVEL; } + + MatrixLayout preferred_output_layout() const override { return SoA; } + + void set_params_impl(T* params, T* inference_params, T* gradients) override {} + + void initialize_params(pcg32& rnd, float* params_full_precision, float scale = 1) override { + // Initialize the hashgrid from the GPU, because the number of parameters can be quite large. + generate_random_uniform(rnd, n_params(), params_full_precision, -1e-4f * scale, 1e-4f * scale); + } + + size_t n_params() const override { return m_n_params; } + + size_t level_n_params(uint32_t level) const override { return level_params_offset(level + 1) - level_params_offset(level); } + + size_t level_params_offset(uint32_t level) const override { + if (level >= m_offset_table.size) { + throw std::runtime_error{"Out of bounds params offset request."}; + } + + return m_offset_table.data[level]; + } + + const ParamsOffsetTable& params_offset_table() const override { return m_offset_table; } + + std::vector> layer_sizes() const override { + // Even though we have parameters, they can't really be considered a "layer". + // So we return an empty array here. + return {}; + } + + uint32_t n_pos_dims() const override { return N_POS_DIMS; } + + uint32_t n_levels() const override { return m_n_levels; } + + uint32_t n_features_per_level() const override { return N_FEATURES_PER_LEVEL; } + + json hyperparams() const override { + std::vector scales_table(m_n_levels * N_POS_DIMS); + for (uint32_t i = 0; i < m_n_levels; ++i) { + const float scale = m_base_scale * exp2f(i * std::log2(m_per_level_scale)); + for (uint32_t dim = 0; dim < N_POS_DIMS; ++dim) { + scales_table[i * N_POS_DIMS + dim] = scale * rsqrtf((dim + 1) * (dim + 2)); + } + } + + std::vector shifts_table(m_n_levels * N_POS_DIMS); + for (uint32_t i = 0; i < m_n_levels; ++i) { + pcg32 rng_tmp = m_rng; + rng_tmp.advance(i * N_POS_DIMS); // Different level should draw differently + for (uint32_t dim = 0; dim < N_POS_DIMS; ++dim) { + shifts_table[i * N_POS_DIMS + dim] = (rng_tmp.next_float() - 0.5f) * 10.0f; // [-5, 5) + } + } + return { + {"otype", "Permuto" }, + {"n_levels", m_n_levels }, + {"n_features_per_level", N_FEATURES_PER_LEVEL }, + {"base_scale", m_base_scale }, + {"per_level_scale", m_per_level_scale }, + {"log2_hashmap_size", m_log2_hashmap_size }, + {"max_input_grad_dims", m_max_input_grad_dims}, + {"seed", m_seed }, + {"scales_table", scales_table }, + {"shifts_table", shifts_table } + }; + } + +private: + dim3 transpose_threads() const { + const uint32_t width = m_n_levels * N_FEATURES_PER_LEVEL; + return {width, std::min(8u, 1024u / width), 1}; + } + + ParamsOffsetTable m_offset_table; + + uint32_t m_n_features; + uint32_t m_n_levels; + uint32_t m_n_params; + + pcg32 m_rng; + uint32_t m_seed; + uint32_t m_log2_hashmap_size; + uint32_t m_max_input_grad_dims; + + uint32_t m_n_to_pad = 0; + + float m_per_level_scale; + float m_base_scale; +}; + +struct PermutoFactoryConfig { + uint32_t n_features; + uint32_t log2_hashmap_size; + float base_scale; + float per_level_scale; + uint32_t max_input_grad_dims; + uint32_t seed; +}; + +template +std::unique_ptr> make_permuto_encoding(const PermutoFactoryConfig& config) { + return std::make_unique>( + config.n_features, + config.log2_hashmap_size, + config.base_scale, + config.per_level_scale, + config.max_input_grad_dims, + config.seed + ); +} + +template +std::unique_ptr> dispatch_permuto_dimension(uint32_t n_dims_to_encode, const PermutoFactoryConfig& config) { + switch (n_dims_to_encode) { + case 1: return make_permuto_encoding(config); + case 2: return make_permuto_encoding(config); + case 3: return make_permuto_encoding(config); + case 4: return make_permuto_encoding(config); + case 5: return make_permuto_encoding(config); + case 6: return make_permuto_encoding(config); + case 7: return make_permuto_encoding(config); + case 8: return make_permuto_encoding(config); + case 9: return make_permuto_encoding(config); + case 10: return make_permuto_encoding(config); + case 12: return make_permuto_encoding(config); + case 16: return make_permuto_encoding(config); + case 24: return make_permuto_encoding(config); + default: throw std::runtime_error{"PermutoEncoding: input dimensions must be one of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, or 24."}; + } +} + +template +std::unique_ptr> dispatch_permuto_features( + uint32_t n_dims_to_encode, uint32_t n_features_per_level, const PermutoFactoryConfig& config +) { + switch (n_features_per_level) { + case 1: return dispatch_permuto_dimension(n_dims_to_encode, config); + case 2: return dispatch_permuto_dimension(n_dims_to_encode, config); + case 4: return dispatch_permuto_dimension(n_dims_to_encode, config); + case 8: return dispatch_permuto_dimension(n_dims_to_encode, config); + default: throw std::runtime_error{"PermutoEncoding: n_features_per_level must be 1, 2, 4, or 8."}; + } +} + +template MultiLevelEncoding* create_permuto_encoding(uint32_t n_dims_to_encode, const json& encoding) { + if (!encoding.is_object()) { + throw std::runtime_error{"PermutoEncoding configuration must be an object."}; + } + + const auto read_nonnegative_integer = [&encoding](const char* key, uint64_t default_value) -> uint64_t { + const auto value = encoding.find(key); + if (value == encoding.end()) { + return default_value; + } + if (!value->is_number_integer()) { + throw std::runtime_error{fmt::format("PermutoEncoding: {} must be an integer.", key)}; + } + if (value->is_number_unsigned()) { + return value->get(); + } + const int64_t signed_value = value->get(); + if (signed_value < 0) { + throw std::runtime_error{fmt::format("PermutoEncoding: {} must be nonnegative.", key)}; + } + return static_cast(signed_value); + }; + + const uint64_t n_features_per_level = read_nonnegative_integer("n_features_per_level", 2); + if (n_features_per_level != 1 && n_features_per_level != 2 && n_features_per_level != 4 && n_features_per_level != 8) { + throw std::runtime_error{"PermutoEncoding: n_features_per_level must be 1, 2, 4, or 8."}; + } + + const uint64_t log2_hashmap_size = read_nonnegative_integer("log2_hashmap_size", 19); + if (log2_hashmap_size >= std::numeric_limits::digits) { + throw std::runtime_error{"PermutoEncoding log2_hashmap_size is out of range."}; + } + + const bool has_n_features = encoding.contains("n_features"); + const bool has_n_grid_features = encoding.contains("n_grid_features"); + if (has_n_features && has_n_grid_features) { + throw std::runtime_error{"PermutoEncoding: n_features and n_grid_features are mutually exclusive."}; + } + if ((has_n_features || has_n_grid_features) && encoding.contains("n_levels")) { + throw std::runtime_error{"PermutoEncoding: total feature aliases and n_levels are mutually exclusive."}; + } + + uint64_t n_levels = 16; + if (has_n_features || has_n_grid_features) { + const char* key = has_n_features ? "n_features" : "n_grid_features"; + const uint64_t total_features = read_nonnegative_integer(key, 0); + if (total_features == 0) { + throw std::runtime_error{fmt::format("PermutoEncoding: {} must be positive.", key)}; + } + if (total_features % n_features_per_level != 0) { + throw std::runtime_error{fmt::format("PermutoEncoding: {} must be divisible by n_features_per_level.", key)}; + } + n_levels = total_features / n_features_per_level; + } else { + n_levels = read_nonnegative_integer("n_levels", 16); + } + if (n_levels == 0 || n_levels > PERMUTO_MAX_N_LEVELS) { + throw std::runtime_error{"PermutoEncoding n_levels is out of range."}; + } + + const uint64_t max_input_grad_dims = read_nonnegative_integer("max_input_grad_dims", n_dims_to_encode); + if (max_input_grad_dims > n_dims_to_encode) { + throw std::runtime_error{"PermutoEncoding max_input_grad_dims exceeds its input width."}; + } + + const uint64_t seed = read_nonnegative_integer("seed", 1337); + if (seed > std::numeric_limits::max()) { + throw std::runtime_error{"PermutoEncoding seed is out of range."}; + } + + const auto base_scale_value = encoding.find("base_scale"); + if (base_scale_value != encoding.end() && !base_scale_value->is_number()) { + throw std::runtime_error{"PermutoEncoding: base_scale must be numeric."}; + } + const double base_scale_wide = base_scale_value == encoding.end() ? 16.0 : base_scale_value->get(); + if (!std::isfinite(base_scale_wide) || std::abs(base_scale_wide) > std::numeric_limits::max()) { + throw std::runtime_error{"PermutoEncoding: base_scale must be finite and representable as float."}; + } + const float base_scale = static_cast(base_scale_wide); + + const auto per_level_scale_value = encoding.find("per_level_scale"); + if (per_level_scale_value != encoding.end() && !per_level_scale_value->is_number()) { + throw std::runtime_error{"PermutoEncoding: per_level_scale must be numeric."}; + } + const double per_level_scale_wide = per_level_scale_value == encoding.end() ? 2.0 : per_level_scale_value->get(); + if (!std::isfinite(per_level_scale_wide) || per_level_scale_wide <= 0.0 || per_level_scale_wide > std::numeric_limits::max()) { + throw std::runtime_error{"PermutoEncoding: per_level_scale must be positive, finite, and representable as float."}; + } + const float per_level_scale = static_cast(per_level_scale_wide); + + const auto interpolation_value = encoding.find("interpolation"); + if (interpolation_value != encoding.end() && !interpolation_value->is_string()) { + throw std::runtime_error{"PermutoEncoding: interpolation must be a string."}; + } + const std::string interpolation = encoding.value("interpolation", "Linear"); + if (!equals_case_insensitive(interpolation, "Linear")) { + throw std::runtime_error{"PermutoEncoding requires linear interpolation."}; + } + + const PermutoFactoryConfig config{ + static_cast(n_features_per_level * n_levels), + static_cast(log2_hashmap_size), + base_scale, + per_level_scale, + static_cast(max_input_grad_dims), + static_cast(seed), + }; + auto result = dispatch_permuto_features(n_dims_to_encode, static_cast(n_features_per_level), config); + + const json derived = result->hyperparams(); + for (const char* key : {"scales_table", "shifts_table"}) { + if (!encoding.contains(key)) { + continue; + } + + const json& supplied = encoding.at(key); + const auto expected = derived.at(key).get>(); + if (!supplied.is_array() || supplied.size() != expected.size()) { + throw std::runtime_error{fmt::format("PermutoEncoding: {} must contain exactly {} values.", key, expected.size())}; + } + + for (size_t i = 0; i < expected.size(); ++i) { + if (!supplied.at(i).is_number()) { + throw std::runtime_error{fmt::format("PermutoEncoding: {}[{}] must be numeric.", key, i)}; + } + const double actual = supplied.at(i).get(); + const double reference = static_cast(expected[i]); + const double tolerance = 8.0 * std::numeric_limits::epsilon() * std::max(1.0, std::abs(reference)); + if (!std::isfinite(actual) || std::abs(actual - reference) > tolerance) { + throw std::runtime_error{fmt::format("PermutoEncoding: {}[{}] does not match the derived lattice.", key, i)}; + } + } + } + + return result.release(); +} + +} // namespace tcnn diff --git a/include/tiny-cuda-nn/encodings/multi_level_interface.h b/include/tiny-cuda-nn/encodings/multi_level_interface.h index 0ab18dd3..361c631f 100644 --- a/include/tiny-cuda-nn/encodings/multi_level_interface.h +++ b/include/tiny-cuda-nn/encodings/multi_level_interface.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2025, NVIDIA CORPORATION. All rights reserved. + * Copyright (c) 2020-2026, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: @@ -91,6 +91,10 @@ template class MultiLevelEncoding : public Encoding { public: virtual uint32_t n_pos_dims() const = 0; + virtual uint32_t n_levels() const { + const uint32_t n_offsets = params_offset_table().size; + return n_offsets == 0 ? 0 : n_offsets - 1; + } virtual uint32_t n_features_per_level() const = 0; virtual size_t level_n_params(uint32_t level) const = 0; diff --git a/include/tiny-cuda-nn/encodings/multi_level_lod.h b/include/tiny-cuda-nn/encodings/multi_level_lod.h new file mode 100644 index 00000000..94361cce --- /dev/null +++ b/include/tiny-cuda-nn/encodings/multi_level_lod.h @@ -0,0 +1,394 @@ +/* + * Copyright (c) 2021-2026, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted + * provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of + * conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** @file multi_level_lod.h + * @brief Hard or soft per-element level control for multi-level encodings. + */ + +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace tcnn { + +template +__global__ void kernel_lod_copy( + const uint32_t n_elements, + const uint32_t n_levels, + const uint32_t n_features_per_level, + const uint32_t padded_output_width, + const bool apply_lod_weights, + const float* __restrict__ levels, + MatrixView input, + MatrixView output +) { + const uint32_t i = threadIdx.x + blockIdx.x * blockDim.x; + if (i >= n_elements) return; + + if (!apply_lod_weights) { + for (uint32_t feature = 0; feature < padded_output_width; ++feature) { + output(feature, i) = input(feature, i); + } + return; + } + + const float level_f = levels[i] * n_levels + 1e-3f; + const bool all_levels_active = level_f >= (float)n_levels; + const bool no_levels_active = level_f < 0.0f; + const int32_t level_i = all_levels_active || no_levels_active ? 0 : (int32_t)floorf(level_f); + for (uint32_t level = 0; level < n_levels; ++level) { + float weight = 0.0f; + if (all_levels_active || (!no_levels_active && (int32_t)level < level_i)) { + weight = 1.0f; + } else if (!no_levels_active && (int32_t)level == level_i) { + weight = level_f - level_i; + } + + for (uint32_t feature = 0; feature < n_features_per_level; ++feature) { + const uint32_t output_feature = level * n_features_per_level + feature; + output(output_feature, i) = weight == 0.0f ? (T)0.0f : (T)weight * input(output_feature, i); + } + } + + for (uint32_t feature = n_levels * n_features_per_level; feature < padded_output_width; ++feature) { + output(feature, i) = input(feature, i); + } +} + +template class MultiLevelEncodingLoD : public MultiLevelEncoding { +public: + MultiLevelEncodingLoD(uint32_t n_dims_to_encode, const json& encoding) { + if (n_dims_to_encode <= 1) { + throw std::runtime_error{"MultiLevelEncodingLoD requires at least two input dimensions."}; + } + + const std::string lod_type = encoding.value("lod_type", "Hard"); + if (equals_case_insensitive(lod_type, "Hard") || equals_case_insensitive(lod_type, "Discontinuous")) { + m_is_soft = false; + } else if (equals_case_insensitive(lod_type, "Soft") || equals_case_insensitive(lod_type, "Continuous")) { + m_is_soft = true; + } else { + throw std::runtime_error{"MultiLevelEncodingLoD: lod_type must be Hard, Discontinuous, Soft, or Continuous."}; + } + + const json& base_config = encoding.at("base"); + const std::string base_type = base_config.value("otype", ""); + if (equals_case_insensitive(base_type, "MultiLevelEncodingLoD")) { + throw std::runtime_error{"MultiLevelEncodingLoD cannot wrap another MultiLevelEncodingLoD."}; + } + + std::shared_ptr> base{create_encoding(n_dims_to_encode - 1, base_config, 1)}; + m_base = std::dynamic_pointer_cast>(base); + if (!m_base) { + throw std::runtime_error{"MultiLevelEncodingLoD requires a multi-level base encoding."}; + } + + m_base->set_alignment(m_base->required_output_alignment()); + } + +#if !defined(TCNN_NO_FWD_BWD) + std::unique_ptr forward_impl( + cudaStream_t stream, + const GPUMatrixDynamic& input, + GPUMatrixDynamic* output = nullptr, + bool use_inference_params = false, + bool prepare_input_gradients = false + ) override { + auto forward = std::make_unique(); + const uint32_t n_elements = input.n(); + if (padded_output_width() == 0 || n_elements == 0) { + return forward; + } + + const uint32_t n_pos_dims = m_base->input_width(); + const auto positions = GPUMatrixDynamic{input.data(), n_pos_dims, n_elements, input.layout(), input.stride()}; + + forward->levels = GPUMatrixDynamic{1, n_elements, stream}; + parallel_for_gpu(stream, n_elements, [ + input_view = input.view(), + levels = forward->levels.data(), + n_pos_dims, + max_level = this->m_max_level, + max_level_gpu = this->m_max_level_gpu + ] __device__(size_t i) { + levels[i] = fminf(input_view(n_pos_dims, i), max_level_gpu ? max_level_gpu[i] : max_level); + }); + + GPUMatrixDynamic* base_output = output; + const MatrixLayout base_layout = m_base->preferred_output_layout(); + if (m_is_soft || (output && (!output->is_contiguous() || output->layout() != base_layout))) { + forward->base_output = GPUMatrixDynamic{ + padded_output_width(), n_elements, stream, base_layout + }; + base_output = &forward->base_output; + } + + { + float* previous_max_level_gpu = m_base->max_level_gpu(); + m_base->set_max_level_gpu(forward->levels.data()); + ScopeGuard restore_max_level_gpu{[this, previous_max_level_gpu] { m_base->set_max_level_gpu(previous_max_level_gpu); }}; + forward->base = m_base->forward(stream, positions, base_output, use_inference_params, prepare_input_gradients); + } + + if (output && forward->base_output.data()) { + copy_with_lod_weights( + stream, n_elements, m_is_soft, forward->levels.data(), forward->base_output.view(), output->view() + ); + } + return forward; + } + + void backward_impl( + cudaStream_t stream, + const Context& ctx, + const GPUMatrixDynamic& input, + const GPUMatrixDynamic& output, + const GPUMatrixDynamic& dL_doutput, + GPUMatrixDynamic* dL_dinput = nullptr, + bool use_inference_params = false, + GradientMode param_gradients_mode = GradientMode::Overwrite + ) override { + const uint32_t n_elements = input.n(); + if (n_elements == 0) { + if (param_gradients_mode == GradientMode::Overwrite && n_params() > 0) { + CUDA_CHECK_THROW(cudaMemsetAsync(this->gradients(), 0, n_params() * sizeof(T), stream)); + } + return; + } + + if (padded_output_width() == 0 || (!dL_dinput && param_gradients_mode == GradientMode::Ignore)) { + return; + } + + const auto& forward = dynamic_cast(ctx); + const uint32_t n_pos_dims = m_base->input_width(); + const auto positions = GPUMatrixDynamic{input.data(), n_pos_dims, n_elements, input.layout(), input.stride()}; + + GPUMatrixDynamic dL_dpositions; + if (dL_dinput) { + dL_dpositions = GPUMatrixDynamic{dL_dinput->data(), n_pos_dims, n_elements, dL_dinput->layout(), dL_dinput->stride()}; + } + + GPUMatrixDynamic compact_dL_doutput; + const GPUMatrixDynamic* base_dL_doutput = &dL_doutput; + const MatrixLayout base_layout = m_base->preferred_output_layout(); + if (m_is_soft || !dL_doutput.is_contiguous() || dL_doutput.layout() != base_layout) { + compact_dL_doutput = GPUMatrixDynamic{dL_doutput.m(), dL_doutput.n(), stream, base_layout}; + copy_with_lod_weights( + stream, n_elements, m_is_soft, forward.levels.data(), dL_doutput.view(), compact_dL_doutput.view() + ); + base_dL_doutput = &compact_dL_doutput; + } + const GPUMatrixDynamic& base_output = forward.base_output.data() ? forward.base_output : output; + + { + float* previous_max_level_gpu = m_base->max_level_gpu(); + m_base->set_max_level_gpu(forward.levels.data()); + ScopeGuard restore_max_level_gpu{[this, previous_max_level_gpu] { m_base->set_max_level_gpu(previous_max_level_gpu); }}; + m_base->backward( + stream, + *forward.base, + positions, + base_output, + *base_dL_doutput, + dL_dinput ? &dL_dpositions : nullptr, + use_inference_params, + param_gradients_mode + ); + } + + if (dL_dinput) { + parallel_for_gpu(stream, n_elements, [gradient = dL_dinput->view(), n_pos_dims] __device__(size_t i) { + gradient(n_pos_dims, i) = 0.0f; + }); + } + } + + void backward_backward_input_impl( + cudaStream_t stream, + const Context& ctx, + const GPUMatrixDynamic& input, + const GPUMatrixDynamic& dL_ddLdinput, + const GPUMatrixDynamic& dL_doutput, + GPUMatrixDynamic* dL_ddLdoutput = nullptr, + GPUMatrixDynamic* dL_dinput = nullptr, + bool use_inference_params = false, + GradientMode param_gradients_mode = GradientMode::Overwrite + ) override { + const uint32_t n_elements = input.n(); + if (n_elements == 0) { + if (param_gradients_mode == GradientMode::Overwrite && n_params() > 0) { + CUDA_CHECK_THROW(cudaMemsetAsync(this->gradients(), 0, n_params() * sizeof(T), stream)); + } + return; + } + if (padded_output_width() == 0 || (!dL_ddLdoutput && !dL_dinput && param_gradients_mode == GradientMode::Ignore)) { + return; + } + + const auto& forward = dynamic_cast(ctx); + const uint32_t n_pos_dims = m_base->input_width(); + const auto positions = GPUMatrixDynamic{input.data(), n_pos_dims, n_elements, input.layout(), input.stride()}; + const auto dL_ddLdpositions = GPUMatrixDynamic{ + dL_ddLdinput.data(), n_pos_dims, n_elements, dL_ddLdinput.layout(), dL_ddLdinput.stride() + }; + + GPUMatrixDynamic dL_dpositions; + if (dL_dinput) { + dL_dpositions = GPUMatrixDynamic{ + dL_dinput->data(), n_pos_dims, n_elements, dL_dinput->layout(), dL_dinput->stride() + }; + } + + GPUMatrixDynamic compact_dL_doutput; + const GPUMatrixDynamic* base_dL_doutput = &dL_doutput; + const MatrixLayout base_layout = m_base->preferred_output_layout(); + if (m_is_soft || !dL_doutput.is_contiguous() || dL_doutput.layout() != base_layout) { + compact_dL_doutput = GPUMatrixDynamic{dL_doutput.m(), dL_doutput.n(), stream, base_layout}; + copy_with_lod_weights( + stream, n_elements, m_is_soft, forward.levels.data(), dL_doutput.view(), compact_dL_doutput.view() + ); + base_dL_doutput = &compact_dL_doutput; + } + + { + float* previous_max_level_gpu = m_base->max_level_gpu(); + m_base->set_max_level_gpu(forward.levels.data()); + ScopeGuard restore_max_level_gpu{[this, previous_max_level_gpu] { m_base->set_max_level_gpu(previous_max_level_gpu); }}; + m_base->backward_backward_input( + stream, + *forward.base, + positions, + dL_ddLdpositions, + *base_dL_doutput, + dL_ddLdoutput, + dL_dinput ? &dL_dpositions : nullptr, + use_inference_params, + param_gradients_mode + ); + } + + if (m_is_soft && dL_ddLdoutput) { + copy_with_lod_weights( + stream, n_elements, true, forward.levels.data(), dL_ddLdoutput->view(), dL_ddLdoutput->view() + ); + } + + if (dL_dinput) { + parallel_for_gpu(stream, n_elements, [gradient = dL_dinput->view(), n_pos_dims] __device__(size_t i) { + gradient(n_pos_dims, i) = 0.0f; + }); + } + } + #endif + + uint32_t input_width() const override { return m_base->input_width() + 1; } + + uint32_t padded_output_width() const override { return m_base->padded_output_width(); } + + uint32_t output_width() const override { return m_base->output_width(); } + + uint32_t required_input_alignment() const override { return 1; } + + void set_padded_output_width(uint32_t padded_output_width) override { m_base->set_padded_output_width(padded_output_width); } + + uint32_t required_output_alignment() const override { return m_base->required_output_alignment(); } + + MatrixLayout preferred_output_layout() const override { return m_base->preferred_output_layout(); } + + void set_params_impl(T* params, T* inference_params, T* gradients) override { m_base->set_params(params, inference_params, gradients); } + + void initialize_params(pcg32& rnd, float* params_full_precision, float scale = 1) override { + m_base->initialize_params(rnd, params_full_precision, scale); + } + + size_t n_params() const override { return m_base->n_params(); } + + std::vector> layer_sizes() const override { return m_base->layer_sizes(); } + + uint32_t n_pos_dims() const override { return m_base->n_pos_dims(); } + + uint32_t n_levels() const override { return m_base->n_levels(); } + + uint32_t n_features_per_level() const override { return m_base->n_features_per_level(); } + + size_t level_n_params(uint32_t level) const override { return m_base->level_n_params(level); } + + size_t level_params_offset(uint32_t level) const override { return m_base->level_params_offset(level); } + + const ParamsOffsetTable& params_offset_table() const override { return m_base->params_offset_table(); } + + json hyperparams() const override { + return { + {"otype", "MultiLevelEncodingLoD"}, + {"lod_type", m_is_soft ? "Soft" : "Hard"}, + {"base", m_base->hyperparams() }, + }; + } + +private: + void copy_with_lod_weights( + cudaStream_t stream, + uint32_t n_elements, + bool apply_lod_weights, + const float* levels, + MatrixView input, + MatrixView output + ) const { + linear_kernel( + kernel_lod_copy, + 0, + stream, + n_elements, + n_levels(), + n_features_per_level(), + padded_output_width(), + apply_lod_weights, + levels, + input, + output + ); + } + + struct ForwardContext : public Context { + GPUMatrixDynamic levels; + GPUMatrixDynamic base_output; + std::unique_ptr base; + }; + + std::shared_ptr> m_base; + bool m_is_soft = false; +}; + +} // namespace tcnn diff --git a/include/tiny-cuda-nn/network_with_input_encoding.h b/include/tiny-cuda-nn/network_with_input_encoding.h index 30aebae9..05419fcd 100644 --- a/include/tiny-cuda-nn/network_with_input_encoding.h +++ b/include/tiny-cuda-nn/network_with_input_encoding.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2025, NVIDIA CORPORATION. All rights reserved. + * Copyright (c) 2020-2026, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: @@ -58,6 +58,10 @@ class NetworkWithInputEncoding : public Network { virtual ~NetworkWithInputEncoding() { } void inference_mixed_precision_impl(cudaStream_t stream, const GPUMatrixDynamic& input, GPUMatrixDynamic& output, bool use_inference_params = true) override { + if (input.n() == 0) { + return; + } + GPUMatrixDynamic network_input = {m_encoding->padded_output_width(), input.n(), stream, m_encoding->preferred_output_layout()}; m_encoding->inference_mixed_precision(stream, input, network_input, use_inference_params); m_network->inference_mixed_precision(stream, network_input, output, use_inference_params); @@ -72,6 +76,9 @@ class NetworkWithInputEncoding : public Network { uint32_t batch_size = input.n(); auto forward = std::make_unique(); + if (batch_size == 0) { + return forward; + } forward->network_input = GPUMatrixDynamic{m_encoding->padded_output_width(), input.n(), stream, m_encoding->preferred_output_layout()}; forward->encoding_ctx = m_encoding->forward(stream, input, &forward->network_input, use_inference_params, prepare_input_gradients); @@ -90,6 +97,13 @@ class NetworkWithInputEncoding : public Network { bool use_inference_params = false, GradientMode param_gradients_mode = GradientMode::Overwrite ) override { + if (input.n() == 0) { + if (param_gradients_mode == GradientMode::Overwrite && n_params() > 0) { + CUDA_CHECK_THROW(cudaMemsetAsync(this->gradients(), 0, n_params() * sizeof(T), stream)); + } + return; + } + GPUMatrixDynamic dL_dnetwork_input; if (m_encoding->n_params() > 0 || dL_dinput) { dL_dnetwork_input = {m_encoding->padded_output_width(), input.n(), stream, m_encoding->preferred_output_layout()}; @@ -112,6 +126,74 @@ class NetworkWithInputEncoding : public Network { } } + void backward_backward_input_impl( + cudaStream_t stream, + const Context& ctx, + const GPUMatrixDynamic& input, + const GPUMatrixDynamic& dL_ddLdinput, + const GPUMatrixDynamic& dL_doutput, + GPUMatrixDynamic* dL_ddLdoutput = nullptr, + GPUMatrixDynamic* dL_dinput = nullptr, + bool use_inference_params = false, + GradientMode param_gradients_mode = GradientMode::Overwrite + ) override { + if (input.n() == 0) { + if (param_gradients_mode == GradientMode::Overwrite && n_params() > 0) { + CUDA_CHECK_THROW(cudaMemsetAsync(this->gradients(), 0, n_params() * sizeof(T), stream)); + } + return; + } + + const auto& forward = dynamic_cast(ctx); + + // Network::backward takes the network output. Recompute it so that forward() does not need to + // keep a copy that only double backward reads. + GPUMatrixDynamic network_output = {m_network->padded_output_width(), input.n(), stream, dL_doutput.layout()}; + m_network->inference_mixed_precision(stream, forward.network_input, network_output, use_inference_params); + + GPUMatrixDynamic dL_dnetwork_input = { + m_encoding->padded_output_width(), input.n(), stream, m_encoding->preferred_output_layout() + }; + GPUMatrixDynamic dL_ddLdnetwork_input = { + m_encoding->padded_output_width(), input.n(), stream, m_encoding->preferred_output_layout() + }; + + m_network->backward( + stream, + *forward.network_ctx, + forward.network_input, + network_output, + dL_doutput, + &dL_dnetwork_input, + use_inference_params, + GradientMode::Ignore + ); + + m_encoding->backward_backward_input( + stream, + *forward.encoding_ctx, + input, + dL_ddLdinput, + dL_dnetwork_input, + &dL_ddLdnetwork_input, + dL_dinput, + use_inference_params, + param_gradients_mode + ); + + m_network->backward_backward_input( + stream, + *forward.network_ctx, + forward.network_input, + dL_ddLdnetwork_input, + dL_doutput, + dL_ddLdoutput, + nullptr, + use_inference_params, + param_gradients_mode + ); + } + void set_params_impl(T* params, T* inference_params, T* gradients) override { size_t offset = 0; m_network->set_params(params + offset, inference_params + offset, gradients + offset); @@ -159,6 +241,11 @@ class NetworkWithInputEncoding : public Network { std::pair forward_activations(const Context& ctx, uint32_t layer) const override { const auto& forward = dynamic_cast(ctx); + // An empty batch has no network context and no activations, so the layout is never read. + if (layer > 0 && !forward.network_ctx) { + return {nullptr, CM}; + } + return layer == 0 ? std::make_pair(forward.network_input.data(), m_encoding->preferred_output_layout()) : m_network->forward_activations(*forward.network_ctx, layer - 1); } diff --git a/include/tiny-cuda-nn/networks/fully_fused_mlp.h b/include/tiny-cuda-nn/networks/fully_fused_mlp.h index c2b418e8..f2395409 100644 --- a/include/tiny-cuda-nn/networks/fully_fused_mlp.h +++ b/include/tiny-cuda-nn/networks/fully_fused_mlp.h @@ -59,6 +59,18 @@ class FullyFusedMLP : public Network { bool use_inference_params = false, GradientMode param_gradients_mode = GradientMode::Overwrite ) override; + + void backward_backward_input_impl( + cudaStream_t stream, + const Context& ctx, + const GPUMatrixDynamic& input, + const GPUMatrixDynamic& dL_ddLdinput, + const GPUMatrixDynamic& dL_doutput, + GPUMatrixDynamic* dL_ddLdoutput = nullptr, + GPUMatrixDynamic* dL_dinput = nullptr, + bool use_inference_params = false, + GradientMode param_gradients_mode = GradientMode::Overwrite + ) override; #endif // !defined(TCNN_NO_FWD_BWD) void set_params_impl(T* params, T* inference_params, T* gradients) override; diff --git a/src/encoding.cu b/src/encoding.cu index 21986616..47cba46f 100644 --- a/src/encoding.cu +++ b/src/encoding.cu @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2025, NVIDIA CORPORATION. All rights reserved. + * Copyright (c) 2020-2026, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: @@ -34,11 +34,14 @@ #include #include #include +#if !defined(TCNN_NO_FWD_BWD) +# include +# include +#endif #include #include #include - namespace tcnn { template @@ -74,6 +77,16 @@ auto register_builtin_encodings() { register_encoding(factories, "TiledGrid", grid_factory); register_encoding(factories, "DenseGrid", grid_factory); +#if !defined(TCNN_NO_FWD_BWD) + register_encoding(factories, "Permuto", [](uint32_t n_dims_to_encode, const json& encoding) { + return create_permuto_encoding(n_dims_to_encode, encoding); + }); + + register_encoding(factories, "MultiLevelEncodingLoD", [](uint32_t n_dims_to_encode, const json& encoding) { + return new MultiLevelEncodingLoD{n_dims_to_encode, encoding}; + }); +#endif + register_encoding(factories, "Identity", [](uint32_t n_dims_to_encode, const json& encoding) { return new IdentityEncoding{n_dims_to_encode, encoding.value("scale", 1.0f), encoding.value("offset", 0.0f)}; }); diff --git a/src/fully_fused_mlp.cu b/src/fully_fused_mlp.cu index a2bed7e4..b0970b48 100644 --- a/src/fully_fused_mlp.cu +++ b/src/fully_fused_mlp.cu @@ -835,6 +835,57 @@ void FullyFusedMLP::backward_impl( fc_multiply(stream, input_weight_matrix(use_inference_params).transposed(), backward_tmp.at(backward_tmp_idx-1), *dL_dinput); } } + +template +void FullyFusedMLP::backward_backward_input_impl( + cudaStream_t stream, + const Context& ctx, + const GPUMatrixDynamic&, + const GPUMatrixDynamic& dL_ddLdinput, + const GPUMatrixDynamic& dL_doutput, + GPUMatrixDynamic* dL_ddLdoutput, + GPUMatrixDynamic* dL_dinput, + bool use_inference_params, + GradientMode param_gradients_mode +) { + if (dL_dinput) { + throw std::runtime_error{"FullyFusedMLP non-JIT double backward does not support input Hessians."}; + } + + if (m_n_hidden_layers != 1 || m_activation != Activation::ReLU || m_output_activation != Activation::None) { + throw std::runtime_error{"FullyFusedMLP non-JIT double backward only supports one hidden ReLU layer with no output activation."}; + } + + if (!dL_ddLdoutput && param_gradients_mode == GradientMode::Ignore) { + return; + } + + const uint32_t batch_size = dL_ddLdinput.n(); + if (batch_size == 0) { + if (param_gradients_mode == GradientMode::Overwrite) { + CUDA_CHECK_THROW(cudaMemsetAsync(this->gradients(), 0, this->n_params() * sizeof(T), stream)); + } + return; + } + + const auto& forward = dynamic_cast(ctx); + GPUMatrix input_gradient_gradient{m_network_width, batch_size, stream}; + fc_multiply(stream, input_weight_matrix(use_inference_params), dL_ddLdinput, forward.hidden.front(), input_gradient_gradient, Activation::ReLU, true); + if (dL_ddLdoutput) { + fc_multiply(stream, output_weight_matrix(use_inference_params), input_gradient_gradient, *dL_ddLdoutput); + } + if (param_gradients_mode == GradientMode::Ignore) { + return; + } + + GPUMatrix hidden_gradient{m_network_width, batch_size, stream}; + fc_multiply(stream, output_weight_matrix(use_inference_params).transposed(), dL_doutput, forward.hidden.front(), hidden_gradient, Activation::ReLU, true); + + const uint32_t split_k_factor = batch_size / std::min(1u << 12u, batch_size); + const float gradient_beta = param_gradients_mode == GradientMode::Accumulate ? 1.0f : 0.0f; + fc_multiply_split_k(stream, dL_doutput, input_gradient_gradient.transposed(), output_gradient_matrix(), split_k_factor, gradient_beta); + fc_multiply_split_k(stream, hidden_gradient, dL_ddLdinput.transposed(), input_gradient_matrix(), split_k_factor, gradient_beta); +} #endif // !defined(TCNN_NO_FWD_BWD) template diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 0b3c8358..486a0704 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2020-2025, NVIDIA CORPORATION. All rights reserved. +# Copyright (c) 2020-2026, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted # provided that the following conditions are met: @@ -23,10 +23,13 @@ function (create_test TEST_NAME) add_executable(${TEST_NAME} ${TEST_NAME}.cu) target_link_libraries(${TEST_NAME} tiny-cuda-nn) - add_test(NAME ${TEST_NAME} COMMAND ${TEST_NAME}) + add_test(NAME ${TEST_NAME} COMMAND ${TEST_NAME} ${ARGN}) endfunction() create_test(test_encodings) create_test(test_grid) create_test(test_jit_losses) create_test(test_networks) +if (NOT TCNN_BUILD_NO_FWD_BWD) + create_test(test_permuto --warn NoTests) +endif() diff --git a/tests/test_encodings.cu b/tests/test_encodings.cu index b1cd40be..2481e1bc 100644 --- a/tests/test_encodings.cu +++ b/tests/test_encodings.cu @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020-2025, NVIDIA CORPORATION. All rights reserved. + * Copyright (c) 2020-2026, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: @@ -33,14 +33,38 @@ #include +#include + using namespace tcnn; +#if defined(TCNN_NO_FWD_BWD) +TEST_CASE("Offline-only encodings are absent without forward and backward", "[encoding][no-fwd-bwd]") { + const auto encodings = builtin_encodings(); + const auto contains = [&encodings](const char* name) { return std::find(encodings.begin(), encodings.end(), name) != encodings.end(); }; + + REQUIRE_FALSE(contains("Permuto")); + REQUIRE_FALSE(contains("MultiLevelEncodingLoD")); + const json permuto_config = { + {"otype", "Permuto"} + }; + const json lod_config = { + {"otype", "MultiLevelEncodingLoD"} + }; + REQUIRE_THROWS_AS(create_encoding(5, permuto_config, 16), std::runtime_error); + REQUIRE_THROWS_AS(create_encoding(6, lod_config, 16), std::runtime_error); +} +#endif + TEMPLATE_TEST_CASE("Various invariance checks for input encodings", "[encoding][jit]", network_precision_t, float) { using T = TestType; tcnn_test_setup(); for (const auto& encoding_name : builtin_encodings()) { + if (equals_case_insensitive(encoding_name, "Permuto") || equals_case_insensitive(encoding_name, "MultiLevelEncodingLoD")) { + continue; + } + SECTION(fmt::format("Testing {}", encoding_name)) { // Typical number of input dims is 3D (e.g. 3D space), but we need to special-case for some encodings that require more. const uint32_t n_dims = equals_case_insensitive(encoding_name, "NRC") || equals_case_insensitive(encoding_name, "OneBlobFrequency") ? 8 : 3; @@ -52,3 +76,56 @@ TEMPLATE_TEST_CASE("Various invariance checks for input encodings", "[encoding][ } } } + +#if !defined(TCNN_NO_FWD_BWD) +TEMPLATE_TEST_CASE("Identity double backward", "[encoding][double-backward]", network_precision_t, float) { + using T = TestType; + + tcnn_test_setup(); + + const uint32_t n_dims = 3; + const uint32_t batch_size = 256; + const float scale = 2.0f; + const json config = { + {"otype", "Identity"}, + {"scale", scale}, + {"offset", 0.5f}, + }; + std::shared_ptr> encoding{create_encoding(n_dims, config, 16)}; + const uint32_t n_outputs = encoding->padded_output_width(); + REQUIRE(n_outputs > n_dims); + + for (const auto layout : {CM, RM}) { + CAPTURE(layout == CM); + + pcg32 rng{1337}; + GPUMatrix input{n_dims, batch_size}; + GPUMatrix dL_ddLdinput{n_dims, batch_size}; + GPUMatrixDynamic dL_doutput{n_outputs, batch_size, layout}; + GPUMatrixDynamic dL_ddLdoutput{n_outputs, batch_size, layout}; + GPUMatrix dL_dinput{n_dims, batch_size}; + input.initialize_uniform(rng, -1.0f, 1.0f); + dL_ddLdinput.initialize_uniform(rng, -1.0f, 1.0f); + dL_doutput.initialize_uniform(rng, -1.0f, 1.0f); + dL_ddLdoutput.initialize_uniform(rng, 1.0f, 2.0f); + dL_dinput.initialize_uniform(rng, 1.0f, 2.0f); + + auto ctx = encoding->forward(input, nullptr, false, true); + encoding->backward_backward_input(*ctx, input, dL_ddLdinput, dL_doutput, &dL_ddLdoutput, &dL_dinput); + + const auto second_order = dL_ddLdinput.to_cpu_vector(); + const auto upstream = dL_ddLdoutput.to_cpu_vector(); + for (uint32_t i = 0; i < batch_size; ++i) { + for (uint32_t j = 0; j < n_outputs; ++j) { + const float actual = (float)upstream[layout == CM ? i * n_outputs + j : j * batch_size + i]; + const float expected = j < n_dims ? scale * second_order[i * n_dims + j] : 0.0f; + CAPTURE(i, j); + REQUIRE(actual == Approx(expected).epsilon(1e-2).margin(1e-3)); + } + } + + const auto input_gradient = dL_dinput.to_cpu_vector(); + REQUIRE(std::all_of(input_gradient.begin(), input_gradient.end(), [](float value) { return value == 0.0f; })); + } +} +#endif diff --git a/tests/test_networks.cu b/tests/test_networks.cu index 2212a3c1..58eb380f 100644 --- a/tests/test_networks.cu +++ b/tests/test_networks.cu @@ -32,6 +32,7 @@ #include "test_common.h" #include +#include using namespace tcnn; @@ -77,3 +78,143 @@ TEST_CASE("Various invariance checks for neural networks", "[network][jit]") { } } } + +TEST_CASE("FullyFusedMLP non-JIT double backward", "[network][double-backward]") { + using T = network_precision_t; + + tcnn_test_setup(); + if (MIN_GPU_ARCH <= 70) { + return; + } + + const auto [input_width, hidden_width, output_width, batch_size] = GENERATE(table({ + {32, 64, 16, 256}, + {16, 16, 1, 256}, + {32, 32, 16, 256}, + {48, 64, 17, 256}, + {128, 128, 32, 512}, + })); + CAPTURE(input_width, hidden_width, output_width, batch_size); + + json config = { + {"otype", "FullyFusedMLP"}, + {"activation", "ReLU"}, + {"output_activation", "None"}, + {"n_input_dims", input_width}, + {"n_output_dims", output_width}, + {"n_neurons", hidden_width}, + {"n_hidden_layers", 1}, + }; + + std::shared_ptr> network{create_network(config)}; + std::shared_ptr> optimizer{create_optimizer(json::object())}; + std::shared_ptr> loss{create_loss(json::object())}; + auto trainer = std::make_shared>(network, optimizer, loss); + network->set_jit_fusion(false); + + pcg32 rng{0xdeadbeef}; + GPUMatrix input{network->input_width(), batch_size}; + GPUMatrix output{network->padded_output_width(), batch_size}; + GPUMatrix output_gradient{network->padded_output_width(), batch_size}; + input.initialize_uniform(rng, -1.0f, 1.0f); + output_gradient.initialize_uniform(rng, -0.01f, 0.01f); + + auto ctx = network->forward(input, &output, false, true); + auto read_gradients = [&]() { + std::vector result(network->n_params()); + CUDA_CHECK_THROW(cudaMemcpy(result.data(), trainer->param_gradients(), result.size() * sizeof(T), cudaMemcpyDeviceToHost)); + return result; + }; + auto require_matching_max_error = [](const std::vector& expected, const std::vector& actual, size_t begin, size_t end) { + REQUIRE(expected.size() == actual.size()); + float max_expected = 0.0f; + float max_error = 0.0f; + for (size_t i = begin; i < end; ++i) { + max_expected = std::max(max_expected, std::abs((float)expected[i])); + max_error = std::max(max_error, std::abs((float)expected[i] - (float)actual[i])); + } + CAPTURE(begin, end, max_expected, max_error); + REQUIRE(max_expected > 0.0f); + REQUIRE(max_error < max_expected * 2e-2f + 1e-5f); + }; + + // ReLU is positively homogeneous. With dL/ddLdx = x, its parameter double gradient + // equals the ordinary parameter gradient for the same output gradient. + network->backward(*ctx, input, output, output_gradient, nullptr, false, GradientMode::Overwrite); + const auto reference = read_gradients(); + network->backward_backward_input(*ctx, input, input, output_gradient, nullptr, nullptr, false, GradientMode::Overwrite); + const auto double_backward = read_gradients(); + vector_match_rae(reference, double_backward, 2e-2, 0.999, true); + const size_t input_weight_count = input_width * hidden_width; + require_matching_max_error(reference, double_backward, 0, input_weight_count); + require_matching_max_error(reference, double_backward, input_weight_count, reference.size()); + + GPUMatrix upstream_gradient{network->padded_output_width(), batch_size}; + network->backward_backward_input(*ctx, input, input, output_gradient, &upstream_gradient, nullptr, false, GradientMode::Ignore); + const auto expected_upstream_gradient = output.to_cpu_vector(); + const auto actual_upstream_gradient = upstream_gradient.to_cpu_vector(); + vector_match_rae(expected_upstream_gradient, actual_upstream_gradient, 2e-2, 0.999, true); + require_matching_max_error(expected_upstream_gradient, actual_upstream_gradient, 0, expected_upstream_gradient.size()); + + if (input_width != 32 || hidden_width != 64 || output_width != 16 || batch_size != BATCH_SIZE_GRANULARITY) { + return; + } + + network->backward_backward_input(*ctx, input, input, output_gradient, nullptr, nullptr, false, GradientMode::Accumulate); + const auto accumulated = read_gradients(); + std::vector doubled(double_backward.size()); + std::transform(double_backward.begin(), double_backward.end(), doubled.begin(), [](T value) { return 2.0f * (float)value; }); + vector_match_rae(doubled, accumulated, 2e-2, 0.999, true); + + network->backward_backward_input(*ctx, input, input, output_gradient, nullptr, nullptr, false, GradientMode::Ignore); + REQUIRE(read_gradients() == accumulated); + + GPUMatrix unsupported_input_gradient{network->input_width(), batch_size}; + REQUIRE_THROWS_WITH( + network->backward_backward_input(*ctx, input, input, output_gradient, nullptr, &unsupported_input_gradient), + "FullyFusedMLP non-JIT double backward does not support input Hessians." + ); + + GPUMatrix empty_input{network->input_width(), 0}; + GPUMatrix empty_output_gradient{network->padded_output_width(), 0}; + network->backward_backward_input(*ctx, empty_input, empty_input, empty_output_gradient, nullptr, nullptr, false, GradientMode::Accumulate); + REQUIRE(read_gradients() == accumulated); + network->backward_backward_input(*ctx, empty_input, empty_input, empty_output_gradient, nullptr, nullptr, false, GradientMode::Overwrite); + const auto empty_gradients = read_gradients(); + REQUIRE(std::all_of(empty_gradients.begin(), empty_gradients.end(), [](T value) { return (float)value == 0.0f; })); +} + +TEST_CASE("NetworkWithInputEncoding empty-batch activations", "[network]") { + using T = network_precision_t; + + tcnn_test_setup(); + if (MIN_GPU_ARCH <= 70) { + return; + } + + json encoding = { + {"otype", "HashGrid"}, + }; + json network_config = { + {"otype", "FullyFusedMLP"}, + {"activation", "ReLU"}, + {"output_activation", "None"}, + {"n_neurons", 64}, + {"n_hidden_layers", 2}, + }; + + auto network = std::make_shared>(3, 16, encoding, network_config); + std::shared_ptr> optimizer{create_optimizer(json::object())}; + std::shared_ptr> loss{create_loss(json::object())}; + auto trainer = std::make_shared>(network, optimizer, loss); + + GPUMatrix empty_input{network->input_width(), 0}; + auto ctx = network->forward(empty_input); + for (uint32_t layer = 0; layer < network->num_forward_activations(); ++layer) { + CAPTURE(layer); + REQUIRE(network->forward_activations(*ctx, layer).first == nullptr); + + GPUMatrix visualization{network->width(layer), 0}; + network->visualize_activation(nullptr, layer, 0, empty_input, visualization); + } +} diff --git a/tests/test_permuto.cu b/tests/test_permuto.cu new file mode 100644 index 00000000..72777ea0 --- /dev/null +++ b/tests/test_permuto.cu @@ -0,0 +1,2694 @@ +/* + * Copyright (c) 2020-2026, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted + * provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of + * conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** @file test_permuto.cu + * @brief Test Permuto and multilevel level-of-detail encodings. + */ + +#include "test_common.h" + +#include +#include +#include +#include + +#include +#include + +using namespace tcnn; + +namespace { + +json permuto_config(uint32_t n_levels = 16, uint32_t log2_hashmap_size = 19, uint32_t n_features_per_level = 2) { + return { + {"otype", "Permuto" }, + {"n_levels", n_levels }, + {"n_features_per_level", n_features_per_level}, + {"log2_hashmap_size", log2_hashmap_size }, + {"per_level_scale", 1.4472692374403782 }, + {"base_scale", 16.0 }, + {"interpolation", "Linear" }, + {"max_input_grad_dims", 3 }, + }; +} + +json hard_lod_config(uint32_t n_levels = 16, uint32_t log2_hashmap_size = 19, uint32_t n_features_per_level = 2) { + return { + {"otype", "MultiLevelEncodingLoD"}, + {"lod_type", "Hard"}, + {"base", permuto_config(n_levels, log2_hashmap_size, n_features_per_level)}, + }; +} + +json soft_lod_config(uint32_t n_levels = 16, uint32_t log2_hashmap_size = 19, uint32_t n_features_per_level = 2) { + json result = hard_lod_config(n_levels, log2_hashmap_size, n_features_per_level); + result["lod_type"] = "Soft"; + return result; +} + +json grid_config(uint32_t n_levels = 2, uint32_t n_features_per_level = 2) { + return { + {"otype", "HashGrid"}, + {"n_levels", n_levels }, + {"n_features_per_level", n_features_per_level}, + {"log2_hashmap_size", 4 }, + {"base_resolution", 4 }, + {"per_level_scale", 2.0f }, + {"interpolation", "Linear" }, + }; +} + +json grid_lod_config(const char* lod_type, uint32_t n_levels = 2, uint32_t n_features_per_level = 2) { + return { + {"otype", "MultiLevelEncodingLoD"}, + {"lod_type", lod_type }, + {"base", grid_config(n_levels, n_features_per_level)}, + }; +} + +class LegacyMultiLevelEncoding : public MultiLevelEncoding { +public: + explicit LegacyMultiLevelEncoding(uint32_t n_offsets) { m_offsets.size = n_offsets; } + +#if !defined(TCNN_NO_FWD_BWD) + std::unique_ptr forward_impl( + cudaStream_t, + const GPUMatrixDynamic&, + GPUMatrixDynamic* = nullptr, + bool = false, + bool = false + ) override { + return std::make_unique(); + } + + void backward_impl( + cudaStream_t, + const Context&, + const GPUMatrixDynamic&, + const GPUMatrixDynamic&, + const GPUMatrixDynamic&, + GPUMatrixDynamic* = nullptr, + bool = false, + GradientMode = GradientMode::Overwrite + ) override { } +#endif + + uint32_t input_width() const override { return 1; } + uint32_t padded_output_width() const override { return 0; } + uint32_t output_width() const override { return 0; } + uint32_t required_input_alignment() const override { return 1; } + void set_padded_output_width(uint32_t) override { } + uint32_t required_output_alignment() const override { return 1; } + MatrixLayout preferred_output_layout() const override { return AoS; } + uint32_t n_pos_dims() const override { return 1; } + uint32_t n_features_per_level() const override { return 1; } + size_t level_n_params(uint32_t) const override { return 0; } + size_t level_params_offset(uint32_t) const override { return 0; } + const ParamsOffsetTable& params_offset_table() const override { return m_offsets; } + json hyperparams() const override { return {{"otype", "LegacyMultiLevelEncoding"}}; } + +private: + ParamsOffsetTable m_offsets; +}; + +float soft_lod_weight(float ratio, uint32_t n_levels, uint32_t level) { + const float level_f = ratio * n_levels + 1e-3f; + if (level_f < 0.0f) { + return 0.0f; + } + if (level_f >= (float)n_levels) { + return 1.0f; + } + const int32_t level_i = (int32_t)std::floor(level_f); + if ((int32_t)level < level_i) { + return 1.0f; + } + return (int32_t)level == level_i ? level_f - level_i : 0.0f; +} + +struct GuardedMatrix { + GuardedMatrix(uint32_t rows, uint32_t cols, MatrixLayout layout, uint32_t padding, float guard) + : rows{rows}, cols{cols}, layout{layout}, stride{(layout == AoS ? rows : cols) + padding}, guard{guard}, + storage{(layout == AoS ? cols : rows) * stride}, matrix{storage.data(), rows, cols, layout, stride}, + host(storage.size(), guard) { } + + size_t index(uint32_t row, uint32_t col) const { + return layout == AoS ? col * stride + row : row * stride + col; + } + + void set(uint32_t row, uint32_t col, float value) { + host[index(row, col)] = value; + } + + float get(uint32_t row, uint32_t col) const { + return host[index(row, col)]; + } + + void upload(cudaStream_t stream) { + CUDA_CHECK_THROW(cudaMemcpyAsync(storage.data(), host.data(), storage.get_bytes(), cudaMemcpyHostToDevice, stream)); + } + + void download(cudaStream_t stream) { + CUDA_CHECK_THROW(cudaMemcpyAsync(host.data(), storage.data(), storage.get_bytes(), cudaMemcpyDeviceToHost, stream)); + } + + void require_matches(const std::vector& contiguous) const { + const uint32_t contiguous_stride = layout == AoS ? rows : cols; + for (uint32_t row = 0; row < rows; ++row) { + for (uint32_t col = 0; col < cols; ++col) { + const size_t contiguous_index = layout == AoS ? col * contiguous_stride + row : row * contiguous_stride + col; + CAPTURE(row, col); + REQUIRE(get(row, col) == Approx(contiguous[contiguous_index]).margin(1e-5f).epsilon(1e-4f)); + } + } + + if (layout == AoS) { + for (uint32_t col = 0; col < cols; ++col) { + for (uint32_t row = rows; row < stride; ++row) { + REQUIRE(host[col * stride + row] == guard); + } + } + } else { + for (uint32_t row = 0; row < rows; ++row) { + for (uint32_t col = cols; col < stride; ++col) { + REQUIRE(host[row * stride + col] == guard); + } + } + } + } + + uint32_t rows; + uint32_t cols; + MatrixLayout layout; + uint32_t stride; + float guard; + GPUMemory storage; + GPUMatrixDynamic matrix; + std::vector host; +}; + +std::vector hard_lod_input(uint32_t batch_size, const std::vector& ratios) { + std::vector result(6 * batch_size); + for (uint32_t row = 0; row < batch_size; ++row) { + for (uint32_t dim = 0; dim < 5; ++dim) { + result[row * 6 + dim] = 0.05f + (float)((row + dim) % 13) / 20.0f; + } + result[row * 6 + 5] = ratios[row % ratios.size()]; + } + return result; +} + +std::vector reference_permuto_level( + const std::array& position, + const std::vector& params, + float scale, + uint32_t seed, + uint32_t level, + uint32_t parameter_offset, + uint32_t hashmap_size, + uint32_t n_features_per_level +) { + pcg32 rng{seed}; + rng.advance(level * 5); + std::array scales; + std::array shifts; + std::array elevated; + std::array rem0{}; + std::array rank{}; + + for (uint32_t dim = 0; dim < 5; ++dim) { + scales[dim] = scale / std::sqrt((dim + 1) * (dim + 2)); + shifts[dim] = std::fma(rng.next_float(), 10.0f, -5.0f); + } + + float sum = 0.0f; + for (int dim = 5; dim > 0; --dim) { + const uint32_t position_dim = static_cast(dim - 1); + const float coordinate = (position[position_dim] + shifts[position_dim]) * scales[position_dim]; + elevated[dim] = sum - dim * coordinate; + sum += coordinate; + } + elevated[0] = sum; + + int rem0_sum = 0; + for (uint32_t dim = 0; dim <= 5; ++dim) { + const float value = elevated[dim] / 6.0f; + const float up = std::ceil(value) * 6.0f; + const float down = std::floor(value) * 6.0f; + rem0[dim] = up - elevated[dim] < elevated[dim] - down ? static_cast(up) : static_cast(down); + rem0_sum += rem0[dim]; + } + rem0_sum /= 6; + + for (uint32_t dim = 0; dim < 5; ++dim) { + const float difference = elevated[dim] - rem0[dim]; + for (uint32_t other_dim = dim + 1; other_dim <= 5; ++other_dim) { + if (difference < elevated[other_dim] - rem0[other_dim]) { + ++rank[dim]; + } else { + ++rank[other_dim]; + } + } + } + for (uint32_t dim = 0; dim <= 5; ++dim) { + rank[dim] += rem0_sum; + if (rank[dim] < 0) { + rank[dim] += 6; + rem0[dim] += 6; + } else if (rank[dim] > 5) { + rank[dim] -= 6; + rem0[dim] -= 6; + } + } + + std::array barycentric{}; + for (uint32_t dim = 0; dim <= 5; ++dim) { + const float delta = (elevated[dim] - rem0[dim]) / 6.0f; + barycentric[5 - rank[dim]] += delta; + barycentric[6 - rank[dim]] -= delta; + } + barycentric[0] += 1.0f + barycentric[6]; + + std::vector result(n_features_per_level); + for (uint32_t vertex = 0; vertex <= 5; ++vertex) { + uint32_t hash = 0; + for (uint32_t dim = 0; dim < 5; ++dim) { + int coordinate = rem0[dim] + static_cast(vertex); + if (rank[dim] > static_cast(5 - vertex)) { + coordinate -= 6; + } + hash += static_cast(coordinate); + hash *= 2531011u; + } + const uint32_t parameter = parameter_offset + (hash % hashmap_size) * n_features_per_level; + for (uint32_t feature = 0; feature < n_features_per_level; ++feature) { + result[feature] = std::fma(barycentric[vertex], params[parameter + feature], result[feature]); + } + } + return result; +} + +std::vector reference_permuto_forward( + const std::array& position, + const std::vector& params, + float base_scale, + uint32_t seed, + uint32_t n_features_per_level = 2 +) { + std::vector result(2 * n_features_per_level); + constexpr uint32_t hashmap_size = 8; + const uint32_t parameters_per_level = hashmap_size * n_features_per_level; + for (uint32_t level = 0; level < 2; ++level) { + const auto level_result = reference_permuto_level( + position, + params, + std::ldexp(base_scale, static_cast(level)), + seed, + level, + level * parameters_per_level, + hashmap_size, + n_features_per_level + ); + for (uint32_t feature = 0; feature < n_features_per_level; ++feature) { + result[level * n_features_per_level + feature] = level_result[feature]; + } + } + return result; +} + +} // namespace + +TEST_CASE("Permuto validates its public configuration", "[encoding][permuto]") { + using T = network_precision_t; + REQUIRE_NOTHROW(create_encoding(5, permuto_config(2, 4), 16)); + REQUIRE_NOTHROW(create_encoding(6, hard_lod_config(), 16)); + + const auto require_invalid = [&](const char* key, const json& value) { + json config = permuto_config(); + config[key] = value; + INFO("key=" << key << ", value=" << value); + REQUIRE_THROWS_AS(create_encoding(5, config, 16), std::runtime_error); + }; + + require_invalid("n_features_per_level", 0); + require_invalid("n_features_per_level", 3); + require_invalid("n_features_per_level", 16); + require_invalid("n_features_per_level", -1); + require_invalid("n_features_per_level", 2.5); + require_invalid("n_features_per_level", true); + require_invalid("n_features_per_level", "2"); + require_invalid("n_features_per_level", nullptr); + require_invalid("n_levels", 0); + require_invalid("n_levels", 33); + require_invalid("n_levels", -1); + require_invalid("n_levels", 16.5); + require_invalid("n_levels", std::numeric_limits::max()); + require_invalid("n_levels", true); + require_invalid("n_levels", "16"); + require_invalid("n_levels", nullptr); + require_invalid("log2_hashmap_size", -1); + require_invalid("log2_hashmap_size", 19.5); + require_invalid("log2_hashmap_size", 32); + require_invalid("log2_hashmap_size", 27); + require_invalid("log2_hashmap_size", std::numeric_limits::max()); + require_invalid("log2_hashmap_size", true); + require_invalid("log2_hashmap_size", "19"); + require_invalid("log2_hashmap_size", nullptr); + require_invalid("max_input_grad_dims", -1); + require_invalid("max_input_grad_dims", 3.5); + require_invalid("max_input_grad_dims", 6); + require_invalid("max_input_grad_dims", std::numeric_limits::max()); + require_invalid("max_input_grad_dims", true); + require_invalid("max_input_grad_dims", "3"); + require_invalid("max_input_grad_dims", nullptr); + require_invalid("seed", -1); + require_invalid("seed", 1.5); + require_invalid("seed", std::numeric_limits::max()); + require_invalid("seed", true); + require_invalid("seed", "1337"); + require_invalid("seed", nullptr); + require_invalid("base_scale", "invalid"); + require_invalid("base_scale", std::numeric_limits::infinity()); + require_invalid("base_scale", std::numeric_limits::quiet_NaN()); + require_invalid("base_scale", 1e30); + require_invalid("base_scale", 1e100); + require_invalid("per_level_scale", "invalid"); + require_invalid("per_level_scale", 0.0); + require_invalid("per_level_scale", -1.0); + require_invalid("per_level_scale", std::numeric_limits::infinity()); + require_invalid("per_level_scale", std::numeric_limits::quiet_NaN()); + require_invalid("per_level_scale", 1e30); + require_invalid("per_level_scale", 1e100); + require_invalid("interpolation", "Smoothstep"); + require_invalid("interpolation", 1); + + REQUIRE_THROWS_WITH( + create_encoding(11, permuto_config(1, 2), 1), + "PermutoEncoding: input dimensions must be one of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, or 24." + ); + REQUIRE_THROWS_WITH( + create_encoding(5, permuto_config(1, 2, 3), 1), + "PermutoEncoding: n_features_per_level must be 1, 2, 4, or 8." + ); + + json alias_conflict = permuto_config(2, 2, 4); + alias_conflict["n_features"] = 8; + REQUIRE_THROWS_WITH( + create_encoding(5, alias_conflict, 1), "PermutoEncoding: total feature aliases and n_levels are mutually exclusive." + ); + + json nondivisible = permuto_config(1, 2, 4); + nondivisible.erase("n_levels"); + nondivisible["n_features"] = 6; + REQUIRE_THROWS_WITH( + create_encoding(5, nondivisible, 1), "PermutoEncoding: n_features must be divisible by n_features_per_level." + ); + + json parameter_overflow = permuto_config(1, 31, 2); + REQUIRE_THROWS_WITH( + create_encoding(5, parameter_overflow, 1), + "PermutoEncoding: parameter count=4294967296 exceeds the supported maximum=4294967295" + ); +} + +TEST_CASE("Permuto constructs its supported specialization matrix", "[encoding][permuto]") { + using T = network_precision_t; + constexpr std::array supported_dimensions = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24}; + constexpr std::array supported_feature_widths = {1, 2, 4, 8}; + + for (uint32_t n_dims : supported_dimensions) { + for (uint32_t n_features_per_level : supported_feature_widths) { + CAPTURE(n_dims, n_features_per_level); + json config = permuto_config(2, 2, n_features_per_level); + config["max_input_grad_dims"] = n_dims; + std::shared_ptr> encoding{create_encoding(n_dims, config, 1)}; + auto multi_level = std::dynamic_pointer_cast>(encoding); + + REQUIRE(multi_level != nullptr); + REQUIRE(encoding->input_width() == n_dims); + REQUIRE(encoding->output_width() == 2 * n_features_per_level); + REQUIRE(encoding->required_output_alignment() == n_features_per_level); + REQUIRE(encoding->n_params() == 8 * n_features_per_level); + REQUIRE(multi_level->n_pos_dims() == n_dims); + REQUIRE(multi_level->n_levels() == 2); + REQUIRE(multi_level->n_features_per_level() == n_features_per_level); + REQUIRE(encoding->hyperparams().at("n_levels") == 2); + } + } + + for (uint32_t unsupported_dimensions : {0u, 11u, 13u, 25u}) { + CAPTURE(unsupported_dimensions); + REQUIRE_THROWS_AS(create_encoding(unsupported_dimensions, permuto_config(1, 2), 1), std::runtime_error); + } +} + +TEST_CASE("Permuto supports defaults and total-feature aliases", "[encoding][permuto]") { + using T = network_precision_t; + std::shared_ptr> defaults{create_encoding(3, {{"otype", "Permuto"}}, 1)}; + const json default_hyperparams = defaults->hyperparams(); + REQUIRE(defaults->input_width() == 3); + REQUIRE(defaults->output_width() == 32); + REQUIRE(defaults->n_params() == 16u * (1u << 19) * 2u); + REQUIRE(default_hyperparams.at("n_levels") == 16); + REQUIRE(default_hyperparams.at("n_features_per_level") == 2); + REQUIRE(default_hyperparams.at("log2_hashmap_size") == 19); + REQUIRE(default_hyperparams.at("base_scale") == 16.0f); + REQUIRE(default_hyperparams.at("per_level_scale") == 2.0f); + REQUIRE(default_hyperparams.at("max_input_grad_dims") == 3); + REQUIRE(default_hyperparams.at("seed") == 1337); + + for (const char* alias : {"n_features", "n_grid_features"}) { + CAPTURE(alias); + json config = permuto_config(1, 2, 4); + config.erase("n_levels"); + config[alias] = 12; + std::shared_ptr> encoding{create_encoding(5, config, 1)}; + const json hyperparams = encoding->hyperparams(); + REQUIRE(encoding->output_width() == 12); + REQUIRE(hyperparams.at("n_levels") == 3); + REQUIRE(hyperparams.at("n_features_per_level") == 4); + REQUIRE_FALSE(hyperparams.contains("n_features")); + REQUIRE_FALSE(hyperparams.contains("n_grid_features")); + } + + json both_aliases = permuto_config(1, 2, 4); + both_aliases.erase("n_levels"); + both_aliases["n_features"] = 8; + both_aliases["n_grid_features"] = 8; + REQUIRE_THROWS_AS(create_encoding(5, both_aliases, 1), std::runtime_error); + + const auto require_invalid_alias = [&](const json& value) { + json config = permuto_config(1, 2, 4); + config.erase("n_levels"); + config["n_features"] = value; + INFO("n_features=" << value); + REQUIRE_THROWS_AS(create_encoding(5, config, 1), std::runtime_error); + }; + require_invalid_alias(0); + require_invalid_alias(-1); + require_invalid_alias(4.5); + require_invalid_alias(6); + require_invalid_alias(std::numeric_limits::max()); + require_invalid_alias(true); + require_invalid_alias("8"); + require_invalid_alias(nullptr); + + json maximum_levels = permuto_config(1, 2, 4); + maximum_levels.erase("n_levels"); + maximum_levels["n_features"] = 32 * 4; + std::shared_ptr> boundary_encoding; + REQUIRE_NOTHROW(boundary_encoding.reset(create_encoding(5, maximum_levels, 1))); + maximum_levels["n_features"] = 33 * 4; + REQUIRE_THROWS_AS(create_encoding(5, maximum_levels, 1), std::runtime_error); + + json maximum_hash = permuto_config(1, 31, 1); + maximum_hash["max_input_grad_dims"] = 1; + REQUIRE_NOTHROW(boundary_encoding.reset(create_encoding(1, maximum_hash, 1))); + maximum_hash["n_features_per_level"] = 2; + REQUIRE_THROWS_AS(create_encoding(1, maximum_hash, 1), std::runtime_error); + + json boundary_values = permuto_config(1, 2, 2); + boundary_values["max_input_grad_dims"] = 0; + boundary_values["seed"] = std::numeric_limits::max(); + boundary_values["base_scale"] = -16.0f; + boundary_values["interpolation"] = "linear"; + REQUIRE_NOTHROW(boundary_encoding.reset(create_encoding(5, boundary_values, 1))); + boundary_values["max_input_grad_dims"] = 5; + REQUIRE_NOTHROW(boundary_encoding.reset(create_encoding(5, boundary_values, 1))); +} + +TEST_CASE("Permuto canonical hyperparameters preserve generalized configurations", "[encoding][permuto]") { + tcnn_test_setup(); + + using T = network_precision_t; + json config = permuto_config(3, 2, 4); + config["max_input_grad_dims"] = 7; + config["seed"] = 42; + std::shared_ptr> encoding{create_encoding(7, config, 1)}; + const json hyperparams = encoding->hyperparams(); + + REQUIRE(hyperparams.at("n_levels") == 3); + REQUIRE(hyperparams.at("n_features_per_level") == 4); + REQUIRE(hyperparams.at("scales_table").size() == 3 * 7); + REQUIRE(hyperparams.at("shifts_table").size() == 3 * 7); + std::shared_ptr> restored{create_encoding(7, hyperparams, 1)}; + REQUIRE(restored->input_width() == encoding->input_width()); + REQUIRE(restored->output_width() == encoding->output_width()); + REQUIRE(restored->n_params() == encoding->n_params()); + REQUIRE(restored->hyperparams() == hyperparams); + + json compatibility_config = config; + compatibility_config["base_resolution"] = 8; + compatibility_config["max_resolution"] = 2048; + compatibility_config["n_dims_to_encode"] = 24; + std::shared_ptr> compatible{create_encoding(7, compatibility_config, 1)}; + REQUIRE(compatible->hyperparams() == hyperparams); + + GPUMemory params_gpu{encoding->n_params()}; + pcg32 rng{0xdeadbeef}; + generate_random_uniform(rng, params_gpu.size(), params_gpu.data(), (T)-0.125f, (T)0.125f); + encoding->set_params(params_gpu.data(), params_gpu.data(), nullptr); + compatible->set_params(params_gpu.data(), params_gpu.data(), nullptr); + + const uint32_t batch_size = BATCH_SIZE_GRANULARITY; + GPUMatrix input{7, batch_size}; + GPUMatrix output{encoding->padded_output_width(), batch_size}; + GPUMatrix compatible_output{compatible->padded_output_width(), batch_size}; + input.initialize_uniform(rng, 0.05f, 0.95f); + encoding->inference_mixed_precision(input, output); + compatible->inference_mixed_precision(input, compatible_output); + const auto output_host = output.to_cpu_vector(); + REQUIRE(std::any_of(output_host.begin(), output_host.end(), [](T value) { return (float)value != 0.0f; })); + REQUIRE(output_host == compatible_output.to_cpu_vector()); + + for (const char* key : {"scales_table", "shifts_table"}) { + CAPTURE(key); + const json expected = hyperparams.at(key); + const auto require_invalid_table = [&](const json& value) { + json invalid = hyperparams; + invalid[key] = value; + REQUIRE_THROWS_AS(create_encoding(7, invalid, 1), std::runtime_error); + }; + + require_invalid_table(json::array({expected.at(0)})); + require_invalid_table(1.0f); + + json nonnumeric = expected; + nonnumeric[0] = "invalid"; + require_invalid_table(nonnumeric); + + json not_finite = expected; + not_finite[0] = std::numeric_limits::quiet_NaN(); + require_invalid_table(not_finite); + not_finite[0] = std::numeric_limits::infinity(); + require_invalid_table(not_finite); + + json mismatched = expected; + mismatched[0] = expected.at(0).get() + 1.0f; + require_invalid_table(mismatched); + } +} + +TEST_CASE("Hard LoD constructs a generalized Permuto base", "[encoding][permuto][lod]") { + using T = network_precision_t; + json config = hard_lod_config(3, 2, 4); + config["base"]["max_input_grad_dims"] = 3; + std::shared_ptr> encoding{create_encoding(4, config, 1)}; + const json hyperparams = encoding->hyperparams(); + + REQUIRE(encoding->input_width() == 4); + REQUIRE(encoding->output_width() == 12); + REQUIRE(encoding->required_output_alignment() == 4); + REQUIRE(encoding->n_params() == 3 * 4 * 4); + REQUIRE(hyperparams.at("otype") == "MultiLevelEncodingLoD"); + REQUIRE(hyperparams.at("lod_type") == "Hard"); + REQUIRE(hyperparams.at("base").at("n_levels") == 3); + REQUIRE(hyperparams.at("base").at("n_features_per_level") == 4); +} + +TEST_CASE("Permuto matches an independent CPU reference and the frozen five-dimensional baseline", "[encoding][permuto]") { + tcnn_test_setup(); + constexpr uint32_t batch_size = BATCH_SIZE_GRANULARITY; + const std::array position = {0.137f, 0.271f, 0.419f, 0.583f, 0.731f}; + + for (uint32_t n_features_per_level : {1u, 2u, 4u, 8u}) { + CAPTURE(n_features_per_level); + json config = permuto_config(2, 3, n_features_per_level); + config["base_scale"] = 1.0f; + config["per_level_scale"] = 2.0f; + config["max_input_grad_dims"] = 3; + config["seed"] = 42; + std::shared_ptr> encoding{create_encoding(5, config, n_features_per_level)}; + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + if (n_features_per_level == 2) { + const json expected_hyperparams = { + {"otype", "Permuto"}, + {"n_levels", 2}, + {"n_features_per_level", 2}, + {"base_scale", 1.0f}, + {"per_level_scale", 2.0f}, + {"log2_hashmap_size", 3}, + {"max_input_grad_dims", 3}, + {"seed", 42}, + {"scales_table", std::vector{ + 0.707106769f, 0.408248305f, 0.288675129f, 0.223606795f, 0.182574183f, + 1.414213538f, 0.816496611f, 0.577350259f, 0.447213590f, 0.365148365f, + }}, + {"shifts_table", std::vector{ + -1.955292225f, 3.965381384f, -1.526242495f, 4.526897430f, 4.039040565f, + -0.820634365f, 0.276217461f, -0.485876799f, -4.565489292f, -2.433936596f, + }}, + }; + REQUIRE(encoding->n_params() == 32); + auto multi_level = std::dynamic_pointer_cast>(encoding); + REQUIRE(multi_level != nullptr); + REQUIRE(multi_level->level_params_offset(0) == 0); + REQUIRE(multi_level->level_params_offset(1) == 8); + REQUIRE(multi_level->level_params_offset(2) == 16); + REQUIRE(multi_level->level_n_params(0) == 8); + REQUIRE(multi_level->level_n_params(1) == 8); + REQUIRE(encoding->hyperparams() == expected_hyperparams); + } + + std::vector params(encoding->n_params()); + for (size_t i = 0; i < params.size(); ++i) { + params[i] = static_cast(static_cast((i * 17) % 29) - 14) / 128.0f; + } + CUDA_CHECK_THROW(cudaMemcpy(encoding->params(), params.data(), params.size() * sizeof(float), cudaMemcpyHostToDevice)); + + const uint32_t output_width = 2 * n_features_per_level; + std::vector upstream(output_width); + if (n_features_per_level == 2) { + upstream = {0.75f, -0.5f, 0.25f, 1.0f}; + } else { + for (uint32_t feature = 0; feature < output_width; ++feature) { + upstream[feature] = static_cast(static_cast(feature % 5) - 2) / 2.0f; + } + } + std::vector input_host(5 * batch_size); + std::vector upstream_host(output_width * batch_size, 0.0f); + for (uint32_t element = 0; element < batch_size; ++element) { + std::copy(position.begin(), position.end(), input_host.begin() + element * 5); + } + std::copy(upstream.begin(), upstream.end(), upstream_host.begin()); + + GPUMatrix input{5, batch_size}; + GPUMatrix output{output_width, batch_size}; + GPUMatrix output_gradient{output_width, batch_size}; + GPUMatrix input_gradient{5, batch_size}; + CUDA_CHECK_THROW(cudaMemcpy(input.data(), input_host.data(), input.n_bytes(), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW(cudaMemcpy(output_gradient.data(), upstream_host.data(), output_gradient.n_bytes(), cudaMemcpyHostToDevice)); + auto context = encoding->forward(input, &output, false, true); + encoding->backward(*context, input, output, output_gradient, &input_gradient, false, GradientMode::Overwrite); + + const auto reference_output = reference_permuto_forward(position, params, 1.0f, 42, n_features_per_level); + REQUIRE(std::any_of(reference_output.begin(), reference_output.end(), [](float value) { return value != 0.0f; })); + const auto output_host = output.to_cpu_vector(); + if (n_features_per_level == 2) { + const std::array frozen_output = {0.005886105f, 0.027815659f, -0.015179069f, -0.013158527f}; + for (uint32_t feature = 0; feature < output_width; ++feature) { + REQUIRE(output_host[feature] == Approx(frozen_output[feature]).margin(2e-5f).epsilon(2e-4f)); + } + } + for (uint32_t element = 0; element < batch_size; ++element) { + for (uint32_t feature = 0; feature < output_width; ++feature) { + REQUIRE( + output_host[element * output_width + feature] == Approx(reference_output[feature]).margin(2e-5f).epsilon(2e-4f) + ); + } + } + + const auto reference_loss = [&](const std::array& reference_position, const std::vector& reference_params) { + const auto reference = reference_permuto_forward(reference_position, reference_params, 1.0f, 42, n_features_per_level); + float result = 0.0f; + for (uint32_t feature = 0; feature < output_width; ++feature) { + result += reference[feature] * upstream[feature]; + } + return result; + }; + std::vector parameter_gradient(params.size()); + CUDA_CHECK_THROW(cudaMemcpy( + parameter_gradient.data(), encoding->gradients(), parameter_gradient.size() * sizeof(float), cudaMemcpyDeviceToHost + )); + if (n_features_per_level == 2) { + const std::array frozen_parameter_gradient = { + 0.120784193f, -0.080522791f, 0.020353220f, -0.013568814f, 0.083992347f, -0.055994898f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.367060781f, -0.244707197f, 0.0f, 0.0f, 0.157809451f, -0.105206303f, + 0.0f, 0.0f, 0.025160966f, 0.100643866f, 0.0f, 0.0f, 0.063755088f, 0.255020350f, + 0.090111226f, 0.360444903f, 0.015566609f, 0.062266435f, 0.055406105f, 0.221624419f, 0.0f, 0.0f, + }; + for (size_t i = 0; i < parameter_gradient.size(); ++i) { + REQUIRE(parameter_gradient[i] == Approx(frozen_parameter_gradient[i]).margin(2e-5f).epsilon(2e-4f)); + } + } + constexpr float parameter_epsilon = 1.0f / 256.0f; + bool has_parameter_gradient = false; + for (size_t i = 0; i < params.size(); ++i) { + auto lower = params; + auto upper = params; + lower[i] -= parameter_epsilon; + upper[i] += parameter_epsilon; + const float finite_difference = (reference_loss(position, upper) - reference_loss(position, lower)) / (2.0f * parameter_epsilon); + has_parameter_gradient |= finite_difference != 0.0f; + REQUIRE(parameter_gradient[i] == Approx(finite_difference).margin(5e-4f).epsilon(2e-3f)); + } + REQUIRE(has_parameter_gradient); + + const auto input_gradient_host = input_gradient.to_cpu_vector(); + if (n_features_per_level == 2) { + const std::array frozen_input_gradient = {0.092071205f, 0.005581521f, -0.020861289f, 0.0f, 0.0f}; + for (uint32_t dim = 0; dim < 5; ++dim) { + REQUIRE(input_gradient_host[dim] == Approx(frozen_input_gradient[dim]).margin(2e-5f).epsilon(2e-4f)); + } + } + constexpr float input_epsilon = 1.0f / 1024.0f; + bool has_input_gradient = false; + for (uint32_t dim = 0; dim < 3; ++dim) { + auto lower = position; + auto upper = position; + lower[dim] -= input_epsilon; + upper[dim] += input_epsilon; + const float expected = (reference_loss(upper, params) - reference_loss(lower, params)) / (2.0f * input_epsilon); + lower[dim] = position[dim] - input_epsilon * 0.5f; + upper[dim] = position[dim] + input_epsilon * 0.5f; + const float half_interval = (reference_loss(upper, params) - reference_loss(lower, params)) / input_epsilon; + REQUIRE(half_interval == Approx(expected).margin(1e-4f).epsilon(1e-3f)); + has_input_gradient |= expected != 0.0f; + REQUIRE(input_gradient_host[dim] == Approx(expected).margin(1e-3f).epsilon(5e-3f)); + } + REQUIRE(has_input_gradient); + REQUIRE(input_gradient_host[3] == 0.0f); + REQUIRE(input_gradient_host[4] == 0.0f); + for (uint32_t element = 1; element < batch_size; ++element) { + for (uint32_t dim = 0; dim < 5; ++dim) { + REQUIRE(input_gradient_host[element * 5 + dim] == 0.0f); + } + } + } +} + +TEST_CASE("Default five-dimensional Permuto supports forward, backward, and optimization", "[encoding][permuto]") { + tcnn_test_setup(); + + const json config = permuto_config(); + + using T = network_precision_t; + std::shared_ptr> encoding{create_encoding(5, config, 16)}; + + REQUIRE(encoding->input_width() == 5); + REQUIRE(encoding->output_width() == 32); + REQUIRE(encoding->n_params() == 16777216); + + auto* multi_level = dynamic_cast*>(encoding.get()); + REQUIRE(multi_level != nullptr); + for (uint32_t level = 0; level < 16; ++level) { + REQUIRE(multi_level->level_params_offset(level) == level * (1u << 19)); + REQUIRE(multi_level->level_n_params(level) == (1u << 19)); + } + REQUIRE(multi_level->level_params_offset(16) == 16u * (1u << 19)); + + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + + const uint32_t batch_size = BATCH_SIZE_GRANULARITY; + GPUMatrix input{5, batch_size}; + GPUMatrix input_gradient{5, batch_size}; + GPUMatrix output{32, batch_size}; + GPUMatrix output_gradient{32, batch_size}; + + pcg32 rng{0xdeadbeef}; + input.initialize_uniform(rng, 0.001f, 0.999f); + output_gradient.initialize_uniform(rng, -default_loss_scale(), default_loss_scale()); + std::vector params_before(encoding->n_params()); + CUDA_CHECK_THROW(cudaMemcpy(params_before.data(), encoding->params(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost)); + + auto context = encoding->forward(input, &output, false, true); + encoding->backward(*context, input, output, output_gradient, &input_gradient); + + const auto output_host = output.to_cpu_vector(); + REQUIRE(std::any_of(output_host.begin(), output_host.end(), [](T value) { return (float)value != 0.0f; })); + REQUIRE(std::all_of(output_host.begin(), output_host.end(), [](T value) { return std::isfinite((float)value); })); + + const auto input_gradient_host = input_gradient.to_cpu_vector(); + bool xyz_gradient_is_nonzero = false; + for (uint32_t row = 0; row < batch_size; ++row) { + for (uint32_t dim = 0; dim < 3; ++dim) { + const float value = input_gradient_host[row * 5 + dim]; + REQUIRE(std::isfinite(value)); + xyz_gradient_is_nonzero |= value != 0.0f; + } + REQUIRE(input_gradient_host[row * 5 + 3] == 0.0f); + REQUIRE(input_gradient_host[row * 5 + 4] == 0.0f); + } + REQUIRE(xyz_gradient_is_nonzero); + + std::vector parameter_gradient_host(encoding->n_params()); + CUDA_CHECK_THROW( + cudaMemcpy(parameter_gradient_host.data(), encoding->gradients(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost) + ); + REQUIRE(std::any_of(parameter_gradient_host.begin(), parameter_gradient_host.end(), [](T value) { return (float)value != 0.0f; })); + REQUIRE(std::all_of(parameter_gradient_host.begin(), parameter_gradient_host.end(), [](T value) { return std::isfinite((float)value); })); + + trainer->optimizer_step(default_loss_scale()); + std::vector params_after(encoding->n_params()); + CUDA_CHECK_THROW(cudaMemcpy(params_after.data(), encoding->params(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost)); + REQUIRE(params_after != params_before); +} + +TEST_CASE("Generalized Permuto specializations support native forward and backward", "[encoding][permuto]") { + tcnn_test_setup(); + + constexpr std::array, 4> test_configs = {{{1, 1}, {3, 4}, {5, 2}, {24, 8}}}; + using T = network_precision_t; + + for (const auto& [n_dims, n_features_per_level] : test_configs) { + CAPTURE(n_dims, n_features_per_level); + const bool maximum_width = n_features_per_level == 8; + json config = permuto_config(maximum_width ? 32 : 2, 2, n_features_per_level); + if (maximum_width) { + config["base_scale"] = 1.0f; + config["per_level_scale"] = 1.0f; + } + const uint32_t max_input_grad_dims = n_dims == 24 ? 7 : n_dims; + config["max_input_grad_dims"] = max_input_grad_dims; + std::shared_ptr> encoding{create_encoding(n_dims, config, n_features_per_level)}; + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + + const uint32_t batch_size = BATCH_SIZE_GRANULARITY; + GPUMatrix input{n_dims, batch_size}; + GPUMatrix input_gradient{n_dims, batch_size}; + GPUMatrix output{encoding->output_width(), batch_size}; + GPUMatrix output_gradient{encoding->output_width(), batch_size}; + pcg32 rng{0xdeadbeef}; + input.initialize_uniform(rng, 0.05f, 0.95f); + output_gradient.initialize_uniform(rng, -default_loss_scale(), default_loss_scale()); + + auto context = encoding->forward(input, &output, false, true); + encoding->backward(*context, input, output, output_gradient, &input_gradient, false, GradientMode::Overwrite); + + const auto output_host = output.to_cpu_vector(); + REQUIRE(std::any_of(output_host.begin(), output_host.end(), [](T value) { return (float)value != 0.0f; })); + REQUIRE(std::all_of(output_host.begin(), output_host.end(), [](T value) { return std::isfinite((float)value); })); + + const auto input_gradient_host = input_gradient.to_cpu_vector(); + REQUIRE(std::any_of( + input_gradient_host.begin(), input_gradient_host.end(), [](float value) { return value != 0.0f; } + )); + REQUIRE(std::all_of( + input_gradient_host.begin(), input_gradient_host.end(), [](float value) { return std::isfinite(value); } + )); + for (uint32_t element = 0; element < batch_size; ++element) { + for (uint32_t dim = max_input_grad_dims; dim < n_dims; ++dim) { + REQUIRE(input_gradient_host[element * n_dims + dim] == 0.0f); + } + } + + std::vector parameter_gradient(encoding->n_params()); + CUDA_CHECK_THROW(cudaMemcpy( + parameter_gradient.data(), encoding->gradients(), parameter_gradient.size() * sizeof(T), cudaMemcpyDeviceToHost + )); + REQUIRE(std::any_of(parameter_gradient.begin(), parameter_gradient.end(), [](T value) { return (float)value != 0.0f; })); + REQUIRE(std::all_of(parameter_gradient.begin(), parameter_gradient.end(), [](T value) { return std::isfinite((float)value); })); + } +} + +TEST_CASE("Generalized Permuto preserves requested output alignment", "[encoding][permuto]") { + tcnn_test_setup(); + + json config = permuto_config(2, 2, 4); + config["max_input_grad_dims"] = 3; + std::shared_ptr> encoding{create_encoding(3, config, 16)}; + REQUIRE(encoding->output_width() == 16); + REQUIRE(encoding->required_output_alignment() == 4); + + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + const uint32_t batch_size = BATCH_SIZE_GRANULARITY; + GPUMatrix input{3, batch_size}; + GPUMatrix output{encoding->output_width(), batch_size}; + pcg32 rng{0xdeadbeef}; + input.initialize_uniform(rng, 0.05f, 0.95f); + encoding->forward(input, &output); + + const auto output_host = output.to_cpu_vector(); + for (uint32_t element = 0; element < batch_size; ++element) { + for (uint32_t feature = 8; feature < encoding->output_width(); ++feature) { + REQUIRE(output_host[element * encoding->output_width() + feature] == 0.0f); + } + } +} + +TEST_CASE("Hard LoD hyperparameters round trip through the factory", "[encoding][permuto][lod]") { + tcnn_test_setup(); + + json config = hard_lod_config(2, 4); + config["base"]["seed"] = 42; + + using T = network_precision_t; + std::shared_ptr> encoding{create_encoding(6, config, 16)}; + const json hyperparams = encoding->hyperparams(); + + REQUIRE(hyperparams.at("otype") == "MultiLevelEncodingLoD"); + REQUIRE(hyperparams.at("lod_type") == "Hard"); + REQUIRE(hyperparams.at("base").at("otype") == "Permuto"); + REQUIRE(hyperparams.at("base").at("seed") == 42); + + std::shared_ptr> restored{create_encoding(encoding->input_width(), hyperparams, 16)}; + REQUIRE(restored->input_width() == encoding->input_width()); + REQUIRE(restored->output_width() == encoding->output_width()); + REQUIRE(restored->n_params() == encoding->n_params()); + REQUIRE(restored->hyperparams() == hyperparams); + + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + auto restored_optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto restored_loss = std::shared_ptr>{create_loss(json::object())}; + auto restored_trainer = std::make_shared>(restored, restored_optimizer, restored_loss); + CUDA_CHECK_THROW(cudaMemcpy(restored->params(), encoding->params(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToDevice)); + + const uint32_t batch_size = BATCH_SIZE_GRANULARITY; + GPUMatrix input{6, batch_size}; + GPUMatrix output{encoding->padded_output_width(), batch_size}; + GPUMatrix restored_output{restored->padded_output_width(), batch_size}; + const auto input_host = hard_lod_input(batch_size, {0.0f, 0.5f, 1.0f}); + CUDA_CHECK_THROW(cudaMemcpy(input.data(), input_host.data(), input.n_bytes(), cudaMemcpyHostToDevice)); + encoding->forward(input, &output); + restored->forward(input, &restored_output); + REQUIRE(output.to_cpu_vector() == restored_output.to_cpu_vector()); +} + +TEST_CASE("Hard LoD retains context without a forward output", "[encoding][permuto][lod]") { + tcnn_test_setup(); + + using T = network_precision_t; + std::shared_ptr> encoding{create_encoding(6, hard_lod_config(2, 4), 16)}; + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + + const uint32_t batch_size = BATCH_SIZE_GRANULARITY; + GPUMatrix input{6, batch_size}; + GPUMatrix input_gradient{6, batch_size}; + GPUMatrix output{encoding->padded_output_width(), batch_size}; + GPUMatrix output_gradient{encoding->padded_output_width(), batch_size}; + const auto input_host = hard_lod_input(batch_size, {1.0f}); + CUDA_CHECK_THROW(cudaMemcpy(input.data(), input_host.data(), input.n_bytes(), cudaMemcpyHostToDevice)); + + pcg32 rng{0xdeadbeef}; + output_gradient.initialize_uniform(rng, -default_loss_scale(), default_loss_scale()); + auto context = encoding->forward(input, nullptr, false, true); + encoding->backward(*context, input, output, output_gradient, &input_gradient, false, GradientMode::Ignore); + + const auto input_gradient_host = input_gradient.to_cpu_vector(); + REQUIRE(std::any_of(input_gradient_host.begin(), input_gradient_host.end(), [](float value) { return value != 0.0f; })); + for (uint32_t row = 0; row < batch_size; ++row) { + REQUIRE(input_gradient_host[row * 6 + 3] == 0.0f); + REQUIRE(input_gradient_host[row * 6 + 4] == 0.0f); + REQUIRE(input_gradient_host[row * 6 + 5] == 0.0f); + } + + context = encoding->forward(input, &output); + encoding->backward(*context, input, output, output_gradient, nullptr, false, GradientMode::Overwrite); + std::vector parameter_gradient_host(encoding->n_params()); + CUDA_CHECK_THROW( + cudaMemcpy(parameter_gradient_host.data(), encoding->gradients(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost) + ); + REQUIRE(std::any_of(parameter_gradient_host.begin(), parameter_gradient_host.end(), [](T value) { return (float)value != 0.0f; })); +} + +TEST_CASE("Permuto preserves parameter gradient modes", "[encoding][permuto]") { + tcnn_test_setup(); + + using T = network_precision_t; + std::shared_ptr> encoding{create_encoding(5, permuto_config(2, 4, 1), 16)}; + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + + const uint32_t batch_size = BATCH_SIZE_GRANULARITY; + GPUMatrix input{5, batch_size}; + GPUMatrix output{encoding->padded_output_width(), batch_size}; + GPUMatrix output_gradient{encoding->padded_output_width(), batch_size}; + pcg32 rng{0xdeadbeef}; + input.initialize_uniform(rng, 0.001f, 0.999f); + std::vector output_gradient_host(output_gradient.n_elements(), (T)0.0f); + std::fill_n(output_gradient_host.begin(), encoding->output_width(), (T)1.0f); + CUDA_CHECK_THROW(cudaMemcpy(output_gradient.data(), output_gradient_host.data(), output_gradient.n_bytes(), cudaMemcpyHostToDevice)); + auto context = encoding->forward(input, &output); + + encoding->backward(*context, input, output, output_gradient, nullptr, false, GradientMode::Overwrite); + std::vector overwrite(encoding->n_params()); + CUDA_CHECK_THROW(cudaMemcpy(overwrite.data(), encoding->gradients(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost)); + + encoding->backward(*context, input, output, output_gradient, nullptr, false, GradientMode::Accumulate); + std::vector accumulated(encoding->n_params()); + CUDA_CHECK_THROW(cudaMemcpy(accumulated.data(), encoding->gradients(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost)); + bool found_nonzero = false; + for (size_t i = 0; i < overwrite.size(); ++i) { + const float expected = 2.0f * (float)overwrite[i]; + const float tolerance = 0.02f * std::max(1.0f, std::abs(expected)); + REQUIRE(std::abs((float)accumulated[i] - expected) <= tolerance); + found_nonzero |= expected != 0.0f; + } + REQUIRE(found_nonzero); + + encoding->backward(*context, input, output, output_gradient, nullptr, false, GradientMode::Ignore); + std::vector ignored(encoding->n_params()); + CUDA_CHECK_THROW(cudaMemcpy(ignored.data(), encoding->gradients(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost)); + REQUIRE(ignored == accumulated); +} + +TEST_CASE("Multilevel encodings preserve parameter gradients for empty batches", "[encoding][permuto][grid][lod]") { + tcnn_test_setup(); + + using T = network_precision_t; + const std::vector> configurations = { + {5, permuto_config(2, 4)}, + {6, hard_lod_config(2, 4)}, + {6, soft_lod_config(2, 4)}, + {3, grid_lod_config("Hard")}, + {3, grid_lod_config("Soft")}, + }; + for (const auto& [input_width, config] : configurations) { + std::shared_ptr> encoding{create_encoding(input_width, config, 16)}; + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + + GPUMatrix input{input_width, 0}; + GPUMatrix dL_ddLdinput{input_width, 0}; + GPUMatrix output{encoding->padded_output_width(), 0}; + GPUMatrix output_gradient{encoding->padded_output_width(), 0}; + GPUMatrix dL_ddLdoutput{encoding->padded_output_width(), 0}; + std::vector sentinel(encoding->n_params(), (T)0.5f); + std::vector gradients(encoding->n_params()); + + for (GradientMode mode : {GradientMode::Overwrite, GradientMode::Accumulate, GradientMode::Ignore}) { + CUDA_CHECK_THROW(cudaMemcpy(encoding->gradients(), sentinel.data(), encoding->n_params() * sizeof(T), cudaMemcpyHostToDevice)); + auto context = encoding->forward(input, &output, false, true); + encoding->backward(*context, input, output, output_gradient, nullptr, false, mode); + CUDA_CHECK_THROW(cudaMemcpy(gradients.data(), encoding->gradients(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost)); + + if (mode == GradientMode::Overwrite) { + REQUIRE(std::all_of(gradients.begin(), gradients.end(), [](T value) { return (float)value == 0.0f; })); + } else { + REQUIRE(gradients == sentinel); + } + + CUDA_CHECK_THROW(cudaMemcpy(encoding->gradients(), sentinel.data(), encoding->n_params() * sizeof(T), cudaMemcpyHostToDevice)); + encoding->backward_backward_input( + *context, input, dL_ddLdinput, output_gradient, &dL_ddLdoutput, nullptr, false, mode + ); + CUDA_CHECK_THROW( + cudaMemcpy(gradients.data(), encoding->gradients(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost) + ); + if (mode == GradientMode::Overwrite) { + REQUIRE(std::all_of(gradients.begin(), gradients.end(), [](T value) { return (float)value == 0.0f; })); + } else { + REQUIRE(gradients == sentinel); + } + } + } +} + +TEST_CASE("Grid-backed LoD forwards parameter gradient modes at both derivative orders", "[encoding][grid][lod]") { + tcnn_test_setup(); + + using T = float; + constexpr uint32_t batch_size = BATCH_SIZE_GRANULARITY; + for (const char* lod_type : {"Hard", "Soft"}) { + CAPTURE(lod_type); + std::shared_ptr> base{create_encoding(2, grid_config(), 4)}; + std::shared_ptr> wrapped{create_encoding(3, grid_lod_config(lod_type), 4)}; + auto base_optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto wrapped_optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto base_trainer = std::make_shared>(base, base_optimizer, loss); + auto wrapped_trainer = std::make_shared>(wrapped, wrapped_optimizer, loss); + + REQUIRE(base->n_params() == wrapped->n_params()); + std::vector params(base->n_params()); + for (size_t i = 0; i < params.size(); ++i) { + params[i] = (T)(static_cast((i * 19) % 37) - 18) / 64.0f; + } + CUDA_CHECK_THROW(cudaMemcpy(base->params(), params.data(), base->n_params() * sizeof(T), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW( + cudaMemcpy(wrapped->params(), params.data(), wrapped->n_params() * sizeof(T), cudaMemcpyHostToDevice) + ); + + std::vector base_input_host(2 * batch_size); + std::vector wrapped_input_host(3 * batch_size); + for (uint32_t element = 0; element < batch_size; ++element) { + base_input_host[element * 2] = wrapped_input_host[element * 3] = 0.05f + (float)(element % 13) / 20.0f; + base_input_host[element * 2 + 1] = wrapped_input_host[element * 3 + 1] = + 0.1f + (float)((element + 5) % 11) / 16.0f; + wrapped_input_host[element * 3 + 2] = 1.0f; + } + + GPUMatrix base_input{2, batch_size}; + GPUMatrix wrapped_input{3, batch_size}; + GPUMatrix base_output{base->padded_output_width(), batch_size}; + GPUMatrix wrapped_output{wrapped->padded_output_width(), batch_size}; + GPUMatrix upstream{base->padded_output_width(), batch_size}; + GPUMatrix base_second_seed{2, batch_size}; + GPUMatrix wrapped_second_seed{3, batch_size}; + GPUMatrix base_input_gradient{2, batch_size}; + GPUMatrix wrapped_input_gradient{3, batch_size}; + GPUMatrix base_upstream_gradient{base->padded_output_width(), batch_size}; + GPUMatrix wrapped_upstream_gradient{wrapped->padded_output_width(), batch_size}; + CUDA_CHECK_THROW(cudaMemcpy(base_input.data(), base_input_host.data(), base_input.n_bytes(), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW( + cudaMemcpy(wrapped_input.data(), wrapped_input_host.data(), wrapped_input.n_bytes(), cudaMemcpyHostToDevice) + ); + pcg32 rng{0xdeadbeef}; + upstream.initialize_uniform(rng, -0.5f, 0.5f); + base_second_seed.initialize_uniform(rng, -0.5f, 0.5f); + std::vector wrapped_second_seed_host(3 * batch_size, 100.0f); + const auto base_second_seed_host = base_second_seed.to_cpu_vector(); + for (uint32_t element = 0; element < batch_size; ++element) { + std::copy_n(base_second_seed_host.data() + element * 2, 2, wrapped_second_seed_host.data() + element * 3); + } + CUDA_CHECK_THROW(cudaMemcpy( + wrapped_second_seed.data(), wrapped_second_seed_host.data(), wrapped_second_seed.n_bytes(), cudaMemcpyHostToDevice + )); + + auto base_context = base->forward(base_input, &base_output, false, true); + auto wrapped_context = wrapped->forward(wrapped_input, &wrapped_output, false, true); + + std::vector sentinel(base->n_params(), 0.25f); + std::vector first_overwrite; + std::vector second_overwrite; + for (bool second_order : {false, true}) { + CAPTURE(second_order); + std::vector& overwrite = second_order ? second_overwrite : first_overwrite; + for (GradientMode mode : {GradientMode::Overwrite, GradientMode::Accumulate, GradientMode::Ignore}) { + CAPTURE((int)mode); + CUDA_CHECK_THROW(cudaMemcpy(base->gradients(), sentinel.data(), base->n_params() * sizeof(T), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW( + cudaMemcpy(wrapped->gradients(), sentinel.data(), wrapped->n_params() * sizeof(T), cudaMemcpyHostToDevice) + ); + if (second_order) { + base->backward_backward_input( + *base_context, base_input, base_second_seed, upstream, &base_upstream_gradient, nullptr, false, mode + ); + wrapped->backward_backward_input( + *wrapped_context, + wrapped_input, + wrapped_second_seed, + upstream, + &wrapped_upstream_gradient, + nullptr, + false, + mode + ); + } else { + base->backward(*base_context, base_input, base_output, upstream, &base_input_gradient, false, mode); + wrapped->backward( + *wrapped_context, wrapped_input, wrapped_output, upstream, &wrapped_input_gradient, false, mode + ); + } + + std::vector base_gradient(base->n_params()); + std::vector wrapped_gradient(wrapped->n_params()); + CUDA_CHECK_THROW(cudaMemcpy( + base_gradient.data(), base->gradients(), base->n_params() * sizeof(T), cudaMemcpyDeviceToHost + )); + CUDA_CHECK_THROW(cudaMemcpy( + wrapped_gradient.data(), wrapped->gradients(), wrapped->n_params() * sizeof(T), cudaMemcpyDeviceToHost + )); + for (size_t i = 0; i < base_gradient.size(); ++i) { + CAPTURE(i); + REQUIRE(wrapped_gradient[i] == Approx(base_gradient[i]).margin(1e-5f).epsilon(1e-4f)); + } + if (mode == GradientMode::Overwrite) { + overwrite = base_gradient; + REQUIRE(std::any_of(overwrite.begin(), overwrite.end(), [](T value) { return value != 0.0f; })); + } else { + for (size_t i = 0; i < base_gradient.size(); ++i) { + const T expected = mode == GradientMode::Accumulate ? sentinel[i] + overwrite[i] : sentinel[i]; + REQUIRE(base_gradient[i] == Approx(expected).margin(1e-5f).epsilon(1e-4f)); + } + } + } + } + } +} + +TEST_CASE("Permuto honors pitched SoA matrix strides", "[encoding][permuto]") { + tcnn_test_setup(); + + using T = float; + constexpr uint32_t batch_size = BATCH_SIZE_GRANULARITY; + constexpr uint32_t output_stride = batch_size + 7; + constexpr uint32_t input_gradient_stride = batch_size + 5; + constexpr float guard = 0.5f; + std::shared_ptr> encoding{create_encoding(5, permuto_config(3, 4), 16)}; + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + const uint32_t output_width = encoding->padded_output_width(); + constexpr uint32_t active_width = 6; + + StreamAndEvent caller_stream; + const cudaStream_t stream = caller_stream.get(); + GPUMatrix input{5, batch_size}; + pcg32 rng{0xdeadbeef}; + input.initialize_uniform(rng, 0.001f, 0.999f); + + GPUMatrix contiguous_output{output_width, batch_size}; + GPUMemory pitched_output_storage{output_width * output_stride}; + std::vector pitched_output_host(output_width * output_stride, (T)guard); + CUDA_CHECK_THROW(cudaMemcpyAsync( + pitched_output_storage.data(), pitched_output_host.data(), pitched_output_host.size() * sizeof(T), cudaMemcpyHostToDevice, stream + )); + GPUMatrixDynamic pitched_output{pitched_output_storage.data(), output_width, batch_size, SoA, output_stride}; + + auto contiguous_context = encoding->forward(stream, input, &contiguous_output, false, true); + auto pitched_context = encoding->forward(stream, input, &pitched_output, false, true); + CUDA_CHECK_THROW(cudaStreamSynchronize(stream)); + const auto contiguous_output_host = contiguous_output.to_cpu_vector(); + CUDA_CHECK_THROW( + cudaMemcpy(pitched_output_host.data(), pitched_output_storage.data(), pitched_output_host.size() * sizeof(T), cudaMemcpyDeviceToHost) + ); + for (uint32_t row = 0; row < output_width; ++row) { + for (uint32_t element = 0; element < batch_size; ++element) { + REQUIRE((float)pitched_output_host[row * output_stride + element] == (float)contiguous_output_host[row * batch_size + element]); + } + for (uint32_t element = batch_size; element < output_stride; ++element) { + REQUIRE((float)pitched_output_host[row * output_stride + element] == guard); + } + } + for (uint32_t row = active_width; row < output_width; ++row) { + for (uint32_t element = 0; element < batch_size; ++element) { + REQUIRE((float)pitched_output_host[row * output_stride + element] == 0.0f); + } + } + + GPUMatrix contiguous_upstream{output_width, batch_size}; + contiguous_upstream.initialize_uniform(rng, -default_loss_scale(), default_loss_scale()); + const auto contiguous_upstream_host = contiguous_upstream.to_cpu_vector(); + GPUMemory pitched_upstream_storage{output_width * output_stride}; + std::vector pitched_upstream_host(output_width * output_stride, (T)guard); + for (uint32_t row = 0; row < output_width; ++row) { + std::copy_n(contiguous_upstream_host.data() + row * batch_size, batch_size, pitched_upstream_host.data() + row * output_stride); + } + CUDA_CHECK_THROW(cudaMemcpyAsync( + pitched_upstream_storage.data(), pitched_upstream_host.data(), pitched_upstream_host.size() * sizeof(T), cudaMemcpyHostToDevice, stream + )); + GPUMatrixDynamic pitched_upstream{pitched_upstream_storage.data(), output_width, batch_size, SoA, output_stride}; + GPUMatrix contiguous_input_gradient{5, batch_size}; + GPUMemory pitched_input_gradient_storage{5 * input_gradient_stride}; + std::vector pitched_input_gradient_host(5 * input_gradient_stride, guard); + CUDA_CHECK_THROW(cudaMemcpyAsync( + pitched_input_gradient_storage.data(), + pitched_input_gradient_host.data(), + pitched_input_gradient_host.size() * sizeof(float), + cudaMemcpyHostToDevice, + stream + )); + GPUMatrixDynamic pitched_input_gradient{pitched_input_gradient_storage.data(), 5, batch_size, SoA, input_gradient_stride}; + + encoding->backward( + stream, *pitched_context, input, pitched_output, pitched_upstream, &pitched_input_gradient, false, GradientMode::Overwrite + ); + std::vector pitched_parameter_gradient(encoding->n_params()); + CUDA_CHECK_THROW(cudaMemcpyAsync( + pitched_parameter_gradient.data(), encoding->gradients(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost, stream + )); + encoding->backward( + stream, *contiguous_context, input, contiguous_output, contiguous_upstream, &contiguous_input_gradient, false, GradientMode::Overwrite + ); + std::vector contiguous_parameter_gradient(encoding->n_params()); + CUDA_CHECK_THROW(cudaMemcpyAsync( + contiguous_parameter_gradient.data(), encoding->gradients(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost, stream + )); + CUDA_CHECK_THROW(cudaMemcpyAsync( + pitched_input_gradient_host.data(), + pitched_input_gradient_storage.data(), + pitched_input_gradient_host.size() * sizeof(float), + cudaMemcpyDeviceToHost, + stream + )); + CUDA_CHECK_THROW(cudaStreamSynchronize(stream)); + const auto contiguous_input_gradient_host = contiguous_input_gradient.to_cpu_vector(); + + for (uint32_t dim = 0; dim < 5; ++dim) { + for (uint32_t element = 0; element < batch_size; ++element) { + const float expected = contiguous_input_gradient_host[dim * batch_size + element]; + const float actual = pitched_input_gradient_host[dim * input_gradient_stride + element]; + if (expected == 0.0f) { + REQUIRE(actual == 0.0f); + } else { + const float difference = std::abs(actual - expected); + REQUIRE(difference <= 1e-4f * std::max(1.0f, std::abs(expected))); + } + } + for (uint32_t element = batch_size; element < input_gradient_stride; ++element) { + REQUIRE(pitched_input_gradient_host[dim * input_gradient_stride + element] == guard); + } + } + for (size_t i = 0; i < pitched_parameter_gradient.size(); ++i) { + const float expected = (float)contiguous_parameter_gradient[i]; + const float actual = (float)pitched_parameter_gradient[i]; + REQUIRE(std::abs(actual - expected) <= 0.02f * std::max(1.0f, std::abs(expected))); + } +} + +TEST_CASE("Multilevel LoD honors pitched matrix strides at both derivative orders", "[encoding][permuto][grid][lod]") { + tcnn_test_setup(); + + using Configuration = std::tuple; + const std::vector configurations = { + {"soft-permuto-soa", 6, soft_lod_config(2, 3), SoA}, + {"hard-grid-soa", 3, grid_lod_config("Hard"), SoA}, + {"hard-wide-grid-aos", 3, grid_lod_config("Hard", 17, 8), AoS}, + {"soft-wide-grid-aos", 3, grid_lod_config("Soft", 17, 8), AoS}, + }; + constexpr uint32_t batch_size = BATCH_SIZE_GRANULARITY; + constexpr float guard = 0.5f; + + for (const auto& [case_name, input_width, config, layout] : configurations) { + CAPTURE(case_name); + std::shared_ptr> encoding{create_encoding(input_width, config, 8)}; + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + const uint32_t output_width = encoding->padded_output_width(); + const MatrixLayout matrix_layout = layout; + const auto contiguous_index = [matrix_layout](uint32_t row, uint32_t col, uint32_t rows, uint32_t cols) { + return matrix_layout == AoS ? col * rows + row : row * cols + col; + }; + + StreamAndEvent caller_stream; + const cudaStream_t stream = caller_stream.get(); + std::vector params(encoding->n_params()); + for (size_t i = 0; i < params.size(); ++i) { + params[i] = (float)(static_cast((i * 19) % 37) - 18) / 64.0f; + } + CUDA_CHECK_THROW(cudaMemcpyAsync( + encoding->params(), params.data(), params.size() * sizeof(float), cudaMemcpyHostToDevice, stream + )); + + GPUMatrixDynamic input{input_width, batch_size, layout}; + std::vector input_host(input.n_elements()); + GuardedMatrix pitched_input{input_width, batch_size, layout, 5, guard}; + for (uint32_t element = 0; element < batch_size; ++element) { + for (uint32_t dim = 0; dim + 1 < input_width; ++dim) { + const float value = 0.05f + (float)((element + dim) % 13) / 20.0f; + input_host[contiguous_index(dim, element, input_width, batch_size)] = value; + pitched_input.set(dim, element, value); + } + input_host[contiguous_index(input_width - 1, element, input_width, batch_size)] = 0.75f; + pitched_input.set(input_width - 1, element, 0.75f); + } + CUDA_CHECK_THROW(cudaMemcpyAsync(input.data(), input_host.data(), input.n_bytes(), cudaMemcpyHostToDevice, stream)); + pitched_input.upload(stream); + + GPUMatrixDynamic contiguous_output{output_width, batch_size, layout}; + GuardedMatrix pitched_output{output_width, batch_size, layout, 7, guard}; + pitched_output.upload(stream); + auto contiguous_context = encoding->forward(stream, input, &contiguous_output, false, true); + auto pitched_context = encoding->forward(stream, pitched_input.matrix, &pitched_output.matrix, false, true); + pitched_output.download(stream); + CUDA_CHECK_THROW(cudaStreamSynchronize(stream)); + const auto contiguous_output_host = contiguous_output.to_cpu_vector(); + pitched_output.require_matches(contiguous_output_host); + REQUIRE(std::any_of( + contiguous_output_host.begin(), contiguous_output_host.end(), [](float value) { return value != 0.0f; } + )); + + GPUMatrixDynamic contiguous_upstream{output_width, batch_size, layout}; + std::vector contiguous_upstream_host(contiguous_upstream.n_elements()); + GuardedMatrix pitched_upstream{output_width, batch_size, layout, 7, guard}; + for (uint32_t row = 0; row < output_width; ++row) { + for (uint32_t element = 0; element < batch_size; ++element) { + const size_t index = contiguous_index(row, element, output_width, batch_size); + const float value = (float)(static_cast((index * 13) % 23) - 11) / 32.0f; + contiguous_upstream_host[index] = value; + pitched_upstream.set(row, element, value); + } + } + CUDA_CHECK_THROW(cudaMemcpyAsync( + contiguous_upstream.data(), + contiguous_upstream_host.data(), + contiguous_upstream.n_bytes(), + cudaMemcpyHostToDevice, + stream + )); + pitched_upstream.upload(stream); + + GPUMatrixDynamic contiguous_input_gradient{input_width, batch_size, layout}; + GuardedMatrix pitched_input_gradient{input_width, batch_size, layout, 5, guard}; + pitched_input_gradient.upload(stream); + encoding->backward( + stream, + *pitched_context, + pitched_input.matrix, + pitched_output.matrix, + pitched_upstream.matrix, + &pitched_input_gradient.matrix, + false, + GradientMode::Overwrite + ); + std::vector pitched_parameter_gradient(encoding->n_params()); + CUDA_CHECK_THROW(cudaMemcpyAsync( + pitched_parameter_gradient.data(), + encoding->gradients(), + encoding->n_params() * sizeof(float), + cudaMemcpyDeviceToHost, + stream + )); + encoding->backward( + stream, + *contiguous_context, + input, + contiguous_output, + contiguous_upstream, + &contiguous_input_gradient, + false, + GradientMode::Overwrite + ); + std::vector contiguous_parameter_gradient(encoding->n_params()); + CUDA_CHECK_THROW(cudaMemcpyAsync( + contiguous_parameter_gradient.data(), + encoding->gradients(), + encoding->n_params() * sizeof(float), + cudaMemcpyDeviceToHost, + stream + )); + pitched_input_gradient.download(stream); + pitched_upstream.download(stream); + CUDA_CHECK_THROW(cudaStreamSynchronize(stream)); + pitched_input_gradient.require_matches(contiguous_input_gradient.to_cpu_vector()); + pitched_upstream.require_matches(contiguous_upstream_host); + bool found_parameter_gradient = false; + for (size_t i = 0; i < pitched_parameter_gradient.size(); ++i) { + REQUIRE( + pitched_parameter_gradient[i] == Approx(contiguous_parameter_gradient[i]).margin(1e-5f).epsilon(1e-4f) + ); + found_parameter_gradient |= pitched_parameter_gradient[i] != 0.0f; + } + REQUIRE(found_parameter_gradient); + for (uint32_t element = 0; element < batch_size; ++element) { + REQUIRE(pitched_input_gradient.get(input_width - 1, element) == 0.0f); + } + + GPUMatrixDynamic second_seed{input_width, batch_size, layout}; + std::vector second_seed_host(second_seed.n_elements()); + GuardedMatrix pitched_second_seed{input_width, batch_size, layout, 6, guard}; + for (uint32_t element = 0; element < batch_size; ++element) { + for (uint32_t dim = 0; dim + 1 < input_width; ++dim) { + const float value = dim == 0 ? 1.0f : (dim == 1 ? -0.25f : 0.125f); + second_seed_host[contiguous_index(dim, element, input_width, batch_size)] = value; + pitched_second_seed.set(dim, element, value); + } + second_seed_host[contiguous_index(input_width - 1, element, input_width, batch_size)] = 100.0f; + pitched_second_seed.set(input_width - 1, element, 100.0f); + } + CUDA_CHECK_THROW(cudaMemcpyAsync( + second_seed.data(), second_seed_host.data(), second_seed.n_bytes(), cudaMemcpyHostToDevice, stream + )); + pitched_second_seed.upload(stream); + + GPUMatrixDynamic contiguous_upstream_gradient{output_width, batch_size, layout}; + GPUMatrixDynamic contiguous_second_input_gradient{input_width, batch_size, layout}; + GuardedMatrix pitched_upstream_gradient{output_width, batch_size, layout, 7, guard}; + GuardedMatrix pitched_second_input_gradient{input_width, batch_size, layout, 5, guard}; + pitched_upstream_gradient.upload(stream); + pitched_second_input_gradient.upload(stream); + encoding->backward_backward_input( + stream, + *pitched_context, + pitched_input.matrix, + pitched_second_seed.matrix, + pitched_upstream.matrix, + &pitched_upstream_gradient.matrix, + &pitched_second_input_gradient.matrix, + false, + GradientMode::Overwrite + ); + std::vector pitched_second_parameter_gradient(encoding->n_params()); + CUDA_CHECK_THROW(cudaMemcpyAsync( + pitched_second_parameter_gradient.data(), + encoding->gradients(), + encoding->n_params() * sizeof(float), + cudaMemcpyDeviceToHost, + stream + )); + encoding->backward_backward_input( + stream, + *contiguous_context, + input, + second_seed, + contiguous_upstream, + &contiguous_upstream_gradient, + &contiguous_second_input_gradient, + false, + GradientMode::Overwrite + ); + std::vector contiguous_second_parameter_gradient(encoding->n_params()); + CUDA_CHECK_THROW(cudaMemcpyAsync( + contiguous_second_parameter_gradient.data(), + encoding->gradients(), + encoding->n_params() * sizeof(float), + cudaMemcpyDeviceToHost, + stream + )); + pitched_upstream_gradient.download(stream); + pitched_second_input_gradient.download(stream); + pitched_input.download(stream); + pitched_second_seed.download(stream); + CUDA_CHECK_THROW(cudaStreamSynchronize(stream)); + pitched_upstream_gradient.require_matches(contiguous_upstream_gradient.to_cpu_vector()); + pitched_second_input_gradient.require_matches(contiguous_second_input_gradient.to_cpu_vector()); + pitched_input.require_matches(input_host); + pitched_second_seed.require_matches(second_seed_host); + bool found_second_parameter_gradient = false; + if (layout == AoS) { + vector_match_rae(pitched_second_parameter_gradient, contiguous_second_parameter_gradient, 1.2e-2, 0.999, true); + } else { + for (size_t i = 0; i < pitched_second_parameter_gradient.size(); ++i) { + REQUIRE( + pitched_second_parameter_gradient[i] == + Approx(contiguous_second_parameter_gradient[i]).margin(1e-5f).epsilon(1e-4f) + ); + } + } + for (float value : pitched_second_parameter_gradient) { + found_second_parameter_gradient |= value != 0.0f; + } + REQUIRE(found_second_parameter_gradient); + for (uint32_t element = 0; element < batch_size; ++element) { + REQUIRE(pitched_second_input_gradient.get(input_width - 1, element) == 0.0f); + } + } +} + +TEST_CASE("Multilevel LoD accepts generic bases and canonicalizes modes", "[encoding][permuto][grid][lod]") { + using T = network_precision_t; + for (const auto& [input_mode, canonical_mode] : std::array, 4>{ + {{"Hard", "Hard"}, {"discontinuous", "Hard"}, {"Soft", "Soft"}, {"continuous", "Soft"}} + }) { + CAPTURE(input_mode); + json config = hard_lod_config(2, 3); + config["lod_type"] = input_mode; + std::shared_ptr> encoding{create_encoding(6, config, 8)}; + auto multilevel = std::dynamic_pointer_cast>(encoding); + REQUIRE(multilevel != nullptr); + REQUIRE(multilevel->n_pos_dims() == 5); + REQUIRE(multilevel->n_levels() == 2); + REQUIRE(multilevel->n_features_per_level() == 2); + REQUIRE(encoding->hyperparams().at("lod_type") == canonical_mode); + std::shared_ptr> restored{create_encoding(encoding->input_width(), encoding->hyperparams(), 8)}; + REQUIRE(restored->hyperparams() == encoding->hyperparams()); + REQUIRE(restored->n_params() == encoding->n_params()); + } + + json invalid_mode = hard_lod_config(2, 3); + invalid_mode["lod_type"] = "Smooth"; + REQUIRE_THROWS_WITH( + create_encoding(6, invalid_mode, 8), + "MultiLevelEncodingLoD: lod_type must be Hard, Discontinuous, Soft, or Continuous." + ); + + json non_multilevel = hard_lod_config(2, 3); + non_multilevel["base"] = {{"otype", "Identity"}}; + REQUIRE_THROWS_WITH( + create_encoding(6, non_multilevel, 8), "MultiLevelEncodingLoD requires a multi-level base encoding." + ); + + json nested = hard_lod_config(2, 3); + nested["base"] = hard_lod_config(2, 3); + REQUIRE_THROWS_WITH( + create_encoding(7, nested, 8), "MultiLevelEncodingLoD cannot wrap another MultiLevelEncodingLoD." + ); + + std::shared_ptr> grid{create_encoding(2, grid_config(), 8)}; + std::shared_ptr> wrapped_grid{create_encoding(3, grid_lod_config("Hard"), 8)}; + auto grid_multilevel = std::dynamic_pointer_cast>(grid); + auto wrapped_multilevel = std::dynamic_pointer_cast>(wrapped_grid); + REQUIRE(grid_multilevel != nullptr); + REQUIRE(wrapped_multilevel != nullptr); + REQUIRE(wrapped_grid->input_width() == grid->input_width() + 1); + REQUIRE(wrapped_grid->output_width() == grid->output_width()); + REQUIRE(wrapped_grid->required_output_alignment() == grid->required_output_alignment()); + REQUIRE(wrapped_grid->preferred_output_layout() == grid->preferred_output_layout()); + REQUIRE(wrapped_grid->n_params() == grid->n_params()); + REQUIRE(wrapped_multilevel->n_pos_dims() == grid_multilevel->n_pos_dims()); + REQUIRE(wrapped_multilevel->n_levels() == grid_multilevel->n_levels()); + REQUIRE(wrapped_multilevel->n_features_per_level() == grid_multilevel->n_features_per_level()); + REQUIRE(wrapped_multilevel->params_offset_table().size == grid_multilevel->params_offset_table().size); + for (uint32_t level = 0; level < grid_multilevel->n_levels(); ++level) { + REQUIRE(wrapped_multilevel->level_n_params(level) == grid_multilevel->level_n_params(level)); + REQUIRE(wrapped_multilevel->level_params_offset(level) == grid_multilevel->level_params_offset(level)); + } + for (uint32_t i = 0; i < grid_multilevel->params_offset_table().size; ++i) { + REQUIRE(wrapped_multilevel->params_offset_table().data[i] == grid_multilevel->params_offset_table().data[i]); + } +} + +TEST_CASE("Multilevel interface derives a backward-compatible level count", "[encoding][permuto][grid][lod]") { + LegacyMultiLevelEncoding empty{0}; + LegacyMultiLevelEncoding three_offsets{3}; + + REQUIRE_FALSE(std::is_abstract::value); + REQUIRE(empty.n_levels() == 0); + REQUIRE(three_offsets.n_levels() == 2); +} + +TEST_CASE("Multilevel LoD composes inherited scalar and GPU level controls", "[encoding][permuto][grid][lod][double-backward]") { + tcnn_test_setup(); + + using T = float; + constexpr uint32_t batch_size = BATCH_SIZE_GRANULARITY; + for (const std::string base : {"Grid", "Permuto"}) { + for (const char* lod_type : {"Hard", "Soft"}) { + for (const bool use_gpu_control : {false, true}) { + CAPTURE(base, lod_type, use_gpu_control); + json config = base == "Grid" ? grid_lod_config(lod_type) : hard_lod_config(2, 3); + config["lod_type"] = lod_type; + const uint32_t input_width = base == "Grid" ? 3 : 6; + + std::shared_ptr> controlled{create_encoding(input_width, config, 4)}; + std::shared_ptr> reference{create_encoding(input_width, config, 4)}; + auto controlled_multilevel = std::dynamic_pointer_cast>(controlled); + REQUIRE(controlled_multilevel != nullptr); + controlled->set_jit_fusion(false); + reference->set_jit_fusion(false); + + auto controlled_optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto reference_optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto controlled_trainer = std::make_shared>(controlled, controlled_optimizer, loss); + auto reference_trainer = std::make_shared>(reference, reference_optimizer, loss); + + std::vector params(controlled->n_params()); + for (size_t i = 0; i < params.size(); ++i) { + params[i] = (T)(static_cast((i * 23) % 41) - 20) / 128.0f; + } + CUDA_CHECK_THROW(cudaMemcpy(controlled->params(), params.data(), controlled->n_params() * sizeof(T), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW(cudaMemcpy(reference->params(), params.data(), reference->n_params() * sizeof(T), cudaMemcpyHostToDevice)); + + std::vector controlled_input_host(input_width * batch_size); + std::vector reference_input_host(input_width * batch_size); + std::vector gpu_controls(batch_size); + for (uint32_t element = 0; element < batch_size; ++element) { + for (uint32_t dim = 0; dim + 1 < input_width; ++dim) { + const float value = 0.05f + (float)((element * 7 + dim * 11) % 89) / 100.0f; + controlled_input_host[element * input_width + dim] = value; + reference_input_host[element * input_width + dim] = value; + } + gpu_controls[element] = element % 2 == 0 ? 0.25f : 0.75f; + controlled_input_host[element * input_width + input_width - 1] = 1.0f; + reference_input_host[element * input_width + input_width - 1] = + use_gpu_control ? gpu_controls[element] : 0.25f; + } + + GPUMatrix gpu_control{1, batch_size}; + if (use_gpu_control) { + CUDA_CHECK_THROW(cudaMemcpy(gpu_control.data(), gpu_controls.data(), gpu_control.n_bytes(), cudaMemcpyHostToDevice)); + controlled_multilevel->set_max_level_gpu(gpu_control.data()); + } else { + controlled_multilevel->set_max_level(0.25f); + } + + GPUMatrix controlled_input{input_width, batch_size}; + GPUMatrix reference_input{input_width, batch_size}; + GPUMatrix controlled_output{controlled->padded_output_width(), batch_size}; + GPUMatrix reference_output{reference->padded_output_width(), batch_size}; + GPUMatrix dL_doutput{controlled->padded_output_width(), batch_size}; + GPUMatrix dL_ddLdinput{input_width, batch_size}; + GPUMatrix controlled_dL_dinput{input_width, batch_size}; + GPUMatrix reference_dL_dinput{input_width, batch_size}; + GPUMatrix controlled_dL_ddLdoutput{controlled->padded_output_width(), batch_size}; + GPUMatrix reference_dL_ddLdoutput{reference->padded_output_width(), batch_size}; + GPUMatrix controlled_second_dL_dinput{input_width, batch_size}; + GPUMatrix reference_second_dL_dinput{input_width, batch_size}; + CUDA_CHECK_THROW(cudaMemcpy( + controlled_input.data(), controlled_input_host.data(), controlled_input.n_bytes(), cudaMemcpyHostToDevice + )); + CUDA_CHECK_THROW(cudaMemcpy( + reference_input.data(), reference_input_host.data(), reference_input.n_bytes(), cudaMemcpyHostToDevice + )); + pcg32 rng{0xdeadbeef}; + dL_doutput.initialize_uniform(rng, -0.5f, 0.5f); + dL_ddLdinput.initialize_uniform(rng, -0.5f, 0.5f); + + auto controlled_context = controlled->forward(controlled_input, &controlled_output, false, true); + auto reference_context = reference->forward(reference_input, &reference_output, false, true); + vector_match_rae(controlled_output.to_cpu_vector(), reference_output.to_cpu_vector(), 1e-5); + + controlled->backward( + *controlled_context, controlled_input, controlled_output, dL_doutput, &controlled_dL_dinput, false, GradientMode::Overwrite + ); + reference->backward( + *reference_context, reference_input, reference_output, dL_doutput, &reference_dL_dinput, false, GradientMode::Overwrite + ); + vector_match_rae(controlled_dL_dinput.to_cpu_vector(), reference_dL_dinput.to_cpu_vector(), 1e-5); + std::vector controlled_parameter_gradient(controlled->n_params()); + std::vector reference_parameter_gradient(reference->n_params()); + CUDA_CHECK_THROW(cudaMemcpy( + controlled_parameter_gradient.data(), controlled->gradients(), controlled->n_params() * sizeof(T), cudaMemcpyDeviceToHost + )); + CUDA_CHECK_THROW(cudaMemcpy( + reference_parameter_gradient.data(), reference->gradients(), reference->n_params() * sizeof(T), cudaMemcpyDeviceToHost + )); + vector_match_rae(controlled_parameter_gradient, reference_parameter_gradient, 1.2e-2, 0.999, true); + + controlled->backward_backward_input( + *controlled_context, + controlled_input, + dL_ddLdinput, + dL_doutput, + &controlled_dL_ddLdoutput, + &controlled_second_dL_dinput, + false, + GradientMode::Overwrite + ); + reference->backward_backward_input( + *reference_context, + reference_input, + dL_ddLdinput, + dL_doutput, + &reference_dL_ddLdoutput, + &reference_second_dL_dinput, + false, + GradientMode::Overwrite + ); + vector_match_rae(controlled_dL_ddLdoutput.to_cpu_vector(), reference_dL_ddLdoutput.to_cpu_vector(), 1e-5); + vector_match_rae(controlled_second_dL_dinput.to_cpu_vector(), reference_second_dL_dinput.to_cpu_vector(), 1e-5); + CUDA_CHECK_THROW(cudaMemcpy( + controlled_parameter_gradient.data(), controlled->gradients(), controlled->n_params() * sizeof(T), cudaMemcpyDeviceToHost + )); + CUDA_CHECK_THROW(cudaMemcpy( + reference_parameter_gradient.data(), reference->gradients(), reference->n_params() * sizeof(T), cudaMemcpyDeviceToHost + )); + vector_match_rae(controlled_parameter_gradient, reference_parameter_gradient, 1.2e-2, 0.999, true); + } + } + } +} + +TEST_CASE("Soft LoD weights native Permuto forward and backward", "[encoding][permuto][lod]") { + tcnn_test_setup(); + + using T = float; + constexpr uint32_t n_levels = 2; + constexpr uint32_t n_features_per_level = 2; + constexpr uint32_t batch_size = BATCH_SIZE_GRANULARITY; + std::shared_ptr> base{create_encoding(5, permuto_config(n_levels, 3, n_features_per_level), 8)}; + std::shared_ptr> encoding{create_encoding(6, soft_lod_config(n_levels, 3, n_features_per_level), 8)}; + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + auto base_optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto base_loss = std::shared_ptr>{create_loss(json::object())}; + auto base_trainer = std::make_shared>(base, base_optimizer, base_loss); + + REQUIRE(encoding->n_params() == base->n_params()); + std::vector params(encoding->n_params()); + for (size_t i = 0; i < params.size(); ++i) { + params[i] = (T)(static_cast((i * 17) % 31) - 15) / 128.0f; + } + CUDA_CHECK_THROW(cudaMemcpy(encoding->params(), params.data(), encoding->n_params() * sizeof(T), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW(cudaMemcpy(base->params(), params.data(), base->n_params() * sizeof(T), cudaMemcpyHostToDevice)); + + const float boundary_ratio = (1.0f - 1e-3f) / n_levels; + const std::vector ratios = { + -std::numeric_limits::max(), -0.25f, 0.0f, boundary_ratio, 0.5f, 0.75f, 1.0f, 1.25f, + std::numeric_limits::max(), + }; + const auto input_host = hard_lod_input(batch_size, ratios); + std::vector base_input_host(5 * batch_size); + for (uint32_t element = 0; element < batch_size; ++element) { + std::copy_n(input_host.data() + element * 6, 5, base_input_host.data() + element * 5); + } + + GPUMatrix input{6, batch_size}; + GPUMatrix base_input{5, batch_size}; + GPUMatrix output{encoding->padded_output_width(), batch_size}; + GPUMatrix base_output{base->padded_output_width(), batch_size}; + CUDA_CHECK_THROW(cudaMemcpy(input.data(), input_host.data(), input.n_bytes(), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW(cudaMemcpy(base_input.data(), base_input_host.data(), base_input.n_bytes(), cudaMemcpyHostToDevice)); + + auto context = encoding->forward(input, &output, false, true); + auto base_context = base->forward(base_input, &base_output, false, true); + const auto output_host = output.to_cpu_vector(); + const auto base_output_host = base_output.to_cpu_vector(); + for (uint32_t element = 0; element < batch_size; ++element) { + const float ratio = ratios[element % ratios.size()]; + for (uint32_t feature = 0; feature < encoding->padded_output_width(); ++feature) { + const float weight = feature < n_levels * n_features_per_level + ? soft_lod_weight(ratio, n_levels, feature / n_features_per_level) + : 1.0f; + const float expected = weight * base_output_host[element * base->padded_output_width() + feature]; + REQUIRE(output_host[element * encoding->padded_output_width() + feature] == Approx(expected).margin(1e-6f)); + } + } + + GPUMatrix dL_doutput{encoding->padded_output_width(), batch_size}; + GPUMatrix base_dL_doutput{base->padded_output_width(), batch_size}; + std::vector dL_doutput_host(dL_doutput.n_elements()); + std::vector base_dL_doutput_host(base_dL_doutput.n_elements()); + for (uint32_t element = 0; element < batch_size; ++element) { + const float ratio = ratios[element % ratios.size()]; + for (uint32_t feature = 0; feature < encoding->padded_output_width(); ++feature) { + const size_t index = element * encoding->padded_output_width() + feature; + dL_doutput_host[index] = (T)(static_cast((index * 13) % 23) - 11) / 32.0f; + const float weight = feature < n_levels * n_features_per_level + ? soft_lod_weight(ratio, n_levels, feature / n_features_per_level) + : 1.0f; + base_dL_doutput_host[index] = weight * dL_doutput_host[index]; + } + } + CUDA_CHECK_THROW(cudaMemcpy(dL_doutput.data(), dL_doutput_host.data(), dL_doutput.n_bytes(), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW( + cudaMemcpy(base_dL_doutput.data(), base_dL_doutput_host.data(), base_dL_doutput.n_bytes(), cudaMemcpyHostToDevice) + ); + + GPUMatrix dL_dinput{6, batch_size}; + GPUMatrix base_dL_dinput{5, batch_size}; + encoding->backward(*context, input, output, dL_doutput, &dL_dinput, false, GradientMode::Overwrite); + base->backward(*base_context, base_input, base_output, base_dL_doutput, &base_dL_dinput, false, GradientMode::Overwrite); + const auto dL_dinput_host = dL_dinput.to_cpu_vector(); + const auto base_dL_dinput_host = base_dL_dinput.to_cpu_vector(); + for (uint32_t element = 0; element < batch_size; ++element) { + for (uint32_t dim = 0; dim < 5; ++dim) { + const float expected = base_dL_dinput_host[element * 5 + dim]; + REQUIRE(dL_dinput_host[element * 6 + dim] == Approx(expected).margin(1e-5f).epsilon(1e-4f)); + } + REQUIRE(dL_dinput_host[element * 6 + 5] == 0.0f); + } + + std::vector parameter_gradient(encoding->n_params()); + std::vector base_parameter_gradient(base->n_params()); + CUDA_CHECK_THROW( + cudaMemcpy(parameter_gradient.data(), encoding->gradients(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost) + ); + CUDA_CHECK_THROW( + cudaMemcpy(base_parameter_gradient.data(), base->gradients(), base->n_params() * sizeof(T), cudaMemcpyDeviceToHost) + ); + bool found_parameter_gradient = false; + for (size_t i = 0; i < parameter_gradient.size(); ++i) { + REQUIRE(parameter_gradient[i] == Approx(base_parameter_gradient[i]).margin(1e-5f).epsilon(1e-4f)); + found_parameter_gradient |= parameter_gradient[i] != 0.0f; + } + REQUIRE(found_parameter_gradient); + + encoding->backward(*context, input, output, dL_doutput, nullptr, false, GradientMode::Accumulate); + std::vector accumulated(encoding->n_params()); + CUDA_CHECK_THROW( + cudaMemcpy(accumulated.data(), encoding->gradients(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost) + ); + for (size_t i = 0; i < parameter_gradient.size(); ++i) { + REQUIRE(accumulated[i] == Approx(2.0f * parameter_gradient[i]).margin(1e-5f).epsilon(1e-4f)); + } + encoding->backward(*context, input, output, dL_doutput, nullptr, false, GradientMode::Ignore); + std::vector ignored(encoding->n_params()); + CUDA_CHECK_THROW(cudaMemcpy(ignored.data(), encoding->gradients(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost)); + REQUIRE(ignored == accumulated); + + auto context_only = encoding->forward(input, nullptr, false, true); + GPUMatrix context_only_dL_dinput{6, batch_size}; + encoding->backward( + *context_only, input, output, dL_doutput, &context_only_dL_dinput, false, GradientMode::Ignore + ); + const auto context_only_gradient = context_only_dL_dinput.to_cpu_vector(); + for (size_t i = 0; i < context_only_gradient.size(); ++i) { + REQUIRE(context_only_gradient[i] == Approx(dL_dinput_host[i]).margin(1e-5f).epsilon(1e-4f)); + } + + const auto scalar_loss = [&](const std::vector& candidate_input) { + CUDA_CHECK_THROW(cudaMemcpy(input.data(), candidate_input.data(), input.n_bytes(), cudaMemcpyHostToDevice)); + encoding->forward(input, &output); + const auto candidate_output = output.to_cpu_vector(); + float result = 0.0f; + for (size_t i = 0; i < candidate_output.size(); ++i) { + result += candidate_output[i] * dL_doutput_host[i]; + } + return result; + }; + constexpr float input_epsilon = 1e-4f; + constexpr uint32_t finite_difference_element = 5; + constexpr uint32_t finite_difference_index = finite_difference_element * 6; + auto lower_input = input_host; + auto upper_input = input_host; + lower_input[finite_difference_index] -= input_epsilon; + upper_input[finite_difference_index] += input_epsilon; + const float finite_difference = (scalar_loss(upper_input) - scalar_loss(lower_input)) / (2.0f * input_epsilon); + REQUIRE(dL_dinput_host[finite_difference_index] != 0.0f); + REQUIRE(finite_difference != 0.0f); + REQUIRE(dL_dinput_host[finite_difference_index] == Approx(finite_difference).margin(1e-2f).epsilon(2e-2f)); + + const auto parameter_it = std::find_if( + parameter_gradient.begin(), parameter_gradient.end(), [](T value) { return std::abs(value) > 1e-5f; } + ); + REQUIRE(parameter_it != parameter_gradient.end()); + const size_t parameter_index = parameter_it - parameter_gradient.begin(); + constexpr float parameter_epsilon = 1.0f / 256.0f; + auto lower_params = params; + auto upper_params = params; + lower_params[parameter_index] -= parameter_epsilon; + upper_params[parameter_index] += parameter_epsilon; + CUDA_CHECK_THROW( + cudaMemcpy(encoding->params(), upper_params.data(), encoding->n_params() * sizeof(T), cudaMemcpyHostToDevice) + ); + const float upper_loss = scalar_loss(input_host); + CUDA_CHECK_THROW( + cudaMemcpy(encoding->params(), lower_params.data(), encoding->n_params() * sizeof(T), cudaMemcpyHostToDevice) + ); + const float lower_loss = scalar_loss(input_host); + CUDA_CHECK_THROW(cudaMemcpy(encoding->params(), params.data(), encoding->n_params() * sizeof(T), cudaMemcpyHostToDevice)); + const float parameter_finite_difference = (upper_loss - lower_loss) / (2.0f * parameter_epsilon); + REQUIRE(parameter_gradient[parameter_index] == Approx(parameter_finite_difference).margin(1e-2f).epsilon(2e-2f)); +} + +TEST_CASE("Hard LoD isolates rows and retains its forward context", "[encoding][permuto][lod]") { + tcnn_test_setup(); + + using T = network_precision_t; + std::shared_ptr> encoding{create_encoding(6, hard_lod_config(), 16)}; + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + + REQUIRE(encoding->input_width() == 6); + REQUIRE(encoding->output_width() == 32); + REQUIRE(encoding->n_params() == 16777216); + + const std::vector ratios = {0.0f, 10.0f / 16.0f, 12.0f / 16.0f, 15.0f / 16.0f, 1.0f}; + const std::vector n_enabled_levels = {1, 11, 13, 16, 16}; + const uint32_t batch_size = BATCH_SIZE_GRANULARITY; + GPUMatrix input{6, batch_size}; + GPUMatrix input_gradient{6, batch_size}; + GPUMatrix output{32, batch_size}; + GPUMatrix output_gradient{32, batch_size}; + const auto input_host = hard_lod_input(batch_size, ratios); + CUDA_CHECK_THROW(cudaMemcpy(input.data(), input_host.data(), input.n_bytes(), cudaMemcpyHostToDevice)); + + pcg32 rng{0xdeadbeef}; + output_gradient.initialize_uniform(rng, -default_loss_scale(), default_loss_scale()); + auto context = encoding->forward(input, &output, false, true); + const auto output_host = output.to_cpu_vector(); + + for (uint32_t row = 0; row < ratios.size(); ++row) { + bool last_active_level_is_nonzero = false; + for (uint32_t feature = 2 * (n_enabled_levels[row] - 1); feature < 2 * n_enabled_levels[row]; ++feature) { + last_active_level_is_nonzero |= (float)output_host[row * 32 + feature] != 0.0f; + } + REQUIRE(last_active_level_is_nonzero); + + for (uint32_t feature = 2 * n_enabled_levels[row]; feature < 32; ++feature) { + REQUIRE((float)output_host[row * 32 + feature] == 0.0f); + } + } + + GPUMatrix repeated_input{6, batch_size}; + GPUMatrix repeated_output{32, batch_size}; + std::vector repeated_input_host(repeated_input.n_elements()); + for (uint32_t source_row = 0; source_row < ratios.size(); ++source_row) { + for (uint32_t row = 0; row < batch_size; ++row) { + std::copy_n(&input_host[source_row * 6], 6, &repeated_input_host[row * 6]); + } + CUDA_CHECK_THROW(cudaMemcpy(repeated_input.data(), repeated_input_host.data(), repeated_input.n_bytes(), cudaMemcpyHostToDevice)); + encoding->forward(repeated_input, &repeated_output); + + const auto repeated_output_host = repeated_output.to_cpu_vector(); + for (uint32_t feature = 0; feature < 32; ++feature) { + REQUIRE((float)output_host[source_row * 32 + feature] == (float)repeated_output_host[feature]); + } + } + + encoding->backward(*context, input, output, output_gradient, &input_gradient); + const auto input_gradient_host = input_gradient.to_cpu_vector(); + bool xyz_gradient_is_nonzero = false; + for (uint32_t row = 0; row < batch_size; ++row) { + for (uint32_t dim = 0; dim < 6; ++dim) { + const float value = input_gradient_host[row * 6 + dim]; + REQUIRE(std::isfinite(value)); + xyz_gradient_is_nonzero |= dim < 3 && value != 0.0f; + } + REQUIRE(input_gradient_host[row * 6 + 3] == 0.0f); + REQUIRE(input_gradient_host[row * 6 + 4] == 0.0f); + REQUIRE(input_gradient_host[row * 6 + 5] == 0.0f); + } + REQUIRE(xyz_gradient_is_nonzero); + + std::vector parameter_gradient_host(encoding->n_params()); + CUDA_CHECK_THROW( + cudaMemcpy(parameter_gradient_host.data(), encoding->gradients(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost) + ); + REQUIRE(std::any_of(parameter_gradient_host.begin(), parameter_gradient_host.end(), [](T value) { return (float)value != 0.0f; })); + REQUIRE(std::all_of(parameter_gradient_host.begin(), parameter_gradient_host.end(), [](T value) { return std::isfinite((float)value); })); +} + +TEST_CASE("Hard LoD masks parameter gradients above level zero", "[encoding][permuto][lod]") { + tcnn_test_setup(); + + using T = network_precision_t; + std::shared_ptr> encoding{create_encoding(6, hard_lod_config(), 16)}; + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + + const uint32_t batch_size = BATCH_SIZE_GRANULARITY; + GPUMatrix input{6, batch_size}; + GPUMatrix output{32, batch_size}; + GPUMatrix output_gradient{32, batch_size}; + const auto input_host = hard_lod_input(batch_size, {0.0f}); + CUDA_CHECK_THROW(cudaMemcpy(input.data(), input_host.data(), input.n_bytes(), cudaMemcpyHostToDevice)); + + pcg32 rng{0xdeadbeef}; + output_gradient.initialize_uniform(rng, -default_loss_scale(), default_loss_scale()); + std::vector parameter_gradient_host(encoding->n_params(), (T)1.0f); + CUDA_CHECK_THROW( + cudaMemcpy(encoding->gradients(), parameter_gradient_host.data(), encoding->n_params() * sizeof(T), cudaMemcpyHostToDevice) + ); + auto context = encoding->forward(input, &output); + encoding->backward(*context, input, output, output_gradient); + + CUDA_CHECK_THROW( + cudaMemcpy(parameter_gradient_host.data(), encoding->gradients(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost) + ); + const auto first_level_end = parameter_gradient_host.begin() + (1u << 20); + REQUIRE(std::all_of(parameter_gradient_host.begin(), parameter_gradient_host.end(), [](T value) { return std::isfinite((float)value); })); + REQUIRE(std::any_of(parameter_gradient_host.begin(), first_level_end, [](T value) { return (float)value != 0.0f; })); + REQUIRE(std::all_of(first_level_end, parameter_gradient_host.end(), [](T value) { return (float)value == 0.0f; })); +} + +TEST_CASE("Hard LoD excludes the epsilon boundary from forward and backward", "[encoding][permuto][lod]") { + tcnn_test_setup(); + + using T = network_precision_t; + std::shared_ptr> encoding{create_encoding(6, hard_lod_config(), 16)}; + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + + const uint32_t batch_size = BATCH_SIZE_GRANULARITY; + const float boundary_ratio = (10.0f - 1e-3f) / 16.0f; + REQUIRE((boundary_ratio * 32.0f) / 2.0f + 1e-3f == 10.0f); + + GPUMatrix input{6, batch_size}; + GPUMatrix input_gradient{6, batch_size}; + GPUMatrix output{32, batch_size}; + GPUMatrix output_gradient{32, batch_size}; + const auto input_host = hard_lod_input(batch_size, {boundary_ratio}); + std::vector output_gradient_host(output_gradient.n_elements(), (T)0.0f); + for (uint32_t row = 0; row < batch_size; ++row) { + output_gradient_host[row * 32 + 20] = (T)1.0f; + output_gradient_host[row * 32 + 21] = (T)1.0f; + } + std::vector parameter_gradient_host(encoding->n_params(), (T)1.0f); + CUDA_CHECK_THROW(cudaMemcpy(input.data(), input_host.data(), input.n_bytes(), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW(cudaMemcpy(output_gradient.data(), output_gradient_host.data(), output_gradient.n_bytes(), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW( + cudaMemcpy(encoding->gradients(), parameter_gradient_host.data(), encoding->n_params() * sizeof(T), cudaMemcpyHostToDevice) + ); + + auto context = encoding->forward(input, &output, false, true); + const auto output_host = output.to_cpu_vector(); + for (uint32_t row = 0; row < batch_size; ++row) { + for (uint32_t feature = 20; feature < 32; ++feature) { + REQUIRE((float)output_host[row * 32 + feature] == 0.0f); + } + } + + encoding->backward(*context, input, output, output_gradient, &input_gradient); + const auto input_gradient_host = input_gradient.to_cpu_vector(); + REQUIRE(std::all_of(input_gradient_host.begin(), input_gradient_host.end(), [](float value) { return value == 0.0f; })); + + CUDA_CHECK_THROW( + cudaMemcpy(parameter_gradient_host.data(), encoding->gradients(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost) + ); + REQUIRE(std::all_of(parameter_gradient_host.begin(), parameter_gradient_host.end(), [](T value) { return (float)value == 0.0f; })); +} + +TEST_CASE("Grid-backed hard LoD uses one exact boundary at both derivative orders", "[encoding][grid][lod][double-backward]") { + tcnn_test_setup(); + + using T = float; + constexpr uint32_t batch_size = BATCH_SIZE_GRANULARITY; + std::shared_ptr> encoding{create_encoding(3, grid_lod_config("Hard"), 4)}; + auto multilevel = std::dynamic_pointer_cast>(encoding); + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + REQUIRE(multilevel != nullptr); + REQUIRE(multilevel->n_levels() == 2); + + std::vector params(encoding->n_params()); + for (size_t i = 0; i < params.size(); ++i) { + params[i] = (T)(static_cast((i * 19) % 37) - 18) / 64.0f; + } + CUDA_CHECK_THROW(cudaMemcpy(encoding->params(), params.data(), encoding->n_params() * sizeof(T), cudaMemcpyHostToDevice)); + const size_t level_one_offset = multilevel->level_params_offset(1) * multilevel->n_features_per_level(); + + const float boundary_ratio = (1.0f - 1e-3f) / 2.0f; + for (const auto& [ratio, level_one_enabled] : std::array, 2>{{ + {boundary_ratio, false}, {0.5f, true} + }}) { + CAPTURE(ratio, level_one_enabled); + std::vector input_host(3 * batch_size); + std::vector dL_doutput_host(encoding->padded_output_width() * batch_size, 0.0f); + std::vector dL_ddLdinput_host(3 * batch_size); + for (uint32_t element = 0; element < batch_size; ++element) { + input_host[element * 3] = 0.137f; + input_host[element * 3 + 1] = 0.619f; + input_host[element * 3 + 2] = ratio; + dL_doutput_host[element * encoding->padded_output_width() + 2] = 0.75f; + dL_doutput_host[element * encoding->padded_output_width() + 3] = -0.5f; + dL_ddLdinput_host[element * 3] = 1.0f; + dL_ddLdinput_host[element * 3 + 1] = -0.25f; + dL_ddLdinput_host[element * 3 + 2] = 100.0f; + } + + GPUMatrix input{3, batch_size}; + GPUMatrix output{encoding->padded_output_width(), batch_size}; + GPUMatrix dL_doutput{encoding->padded_output_width(), batch_size}; + GPUMatrix dL_dinput{3, batch_size}; + GPUMatrix dL_ddLdinput{3, batch_size}; + GPUMatrix dL_ddLdoutput{encoding->padded_output_width(), batch_size}; + GPUMatrix second_dL_dinput{3, batch_size}; + CUDA_CHECK_THROW(cudaMemcpy(input.data(), input_host.data(), input.n_bytes(), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW(cudaMemcpy(dL_doutput.data(), dL_doutput_host.data(), dL_doutput.n_bytes(), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW( + cudaMemcpy(dL_ddLdinput.data(), dL_ddLdinput_host.data(), dL_ddLdinput.n_bytes(), cudaMemcpyHostToDevice) + ); + + auto context = encoding->forward(input, &output, false, true); + const auto output_host = output.to_cpu_vector(); + bool has_level_one_output = false; + for (uint32_t element = 0; element < batch_size; ++element) { + for (uint32_t feature = 2; feature < 4; ++feature) { + has_level_one_output |= output_host[element * encoding->padded_output_width() + feature] != 0.0f; + } + } + REQUIRE(has_level_one_output == level_one_enabled); + + encoding->backward(*context, input, output, dL_doutput, &dL_dinput, false, GradientMode::Overwrite); + const auto first_input_gradient = dL_dinput.to_cpu_vector(); + std::vector first_parameter_gradient(encoding->n_params()); + CUDA_CHECK_THROW(cudaMemcpy( + first_parameter_gradient.data(), + encoding->gradients(), + encoding->n_params() * sizeof(T), + cudaMemcpyDeviceToHost + )); + const bool has_first_input_gradient = std::any_of( + first_input_gradient.begin(), first_input_gradient.end(), [](float value) { return value != 0.0f; } + ); + const bool has_first_parameter_gradient = std::any_of( + first_parameter_gradient.begin() + level_one_offset, + first_parameter_gradient.end(), + [](T value) { return value != 0.0f; } + ); + REQUIRE(has_first_input_gradient == level_one_enabled); + REQUIRE(has_first_parameter_gradient == level_one_enabled); + for (uint32_t element = 0; element < batch_size; ++element) { + REQUIRE(first_input_gradient[element * 3 + 2] == 0.0f); + } + + encoding->backward_backward_input( + *context, + input, + dL_ddLdinput, + dL_doutput, + &dL_ddLdoutput, + &second_dL_dinput, + false, + GradientMode::Overwrite + ); + const auto upstream_gradient = dL_ddLdoutput.to_cpu_vector(); + const auto second_input_gradient = second_dL_dinput.to_cpu_vector(); + std::vector second_parameter_gradient(encoding->n_params()); + CUDA_CHECK_THROW(cudaMemcpy( + second_parameter_gradient.data(), + encoding->gradients(), + encoding->n_params() * sizeof(T), + cudaMemcpyDeviceToHost + )); + bool has_level_one_upstream_gradient = false; + for (uint32_t element = 0; element < batch_size; ++element) { + for (uint32_t feature = 2; feature < 4; ++feature) { + has_level_one_upstream_gradient |= upstream_gradient[element * encoding->padded_output_width() + feature] != 0.0f; + } + REQUIRE(second_input_gradient[element * 3 + 2] == 0.0f); + } + const bool has_second_input_gradient = std::any_of( + second_input_gradient.begin(), second_input_gradient.end(), [](float value) { return value != 0.0f; } + ); + const bool has_second_parameter_gradient = std::any_of( + second_parameter_gradient.begin() + level_one_offset, + second_parameter_gradient.end(), + [](T value) { return value != 0.0f; } + ); + REQUIRE(has_level_one_upstream_gradient == level_one_enabled); + REQUIRE(has_second_input_gradient == level_one_enabled); + REQUIRE(has_second_parameter_gradient == level_one_enabled); + } +} + +TEST_CASE("Grid-backed soft LoD weights native double backward", "[encoding][grid][lod][double-backward]") { + tcnn_test_setup(); + + using T = float; + constexpr uint32_t batch_size = BATCH_SIZE_GRANULARITY; + constexpr float ratio = 0.75f; + std::shared_ptr> base{create_encoding(2, grid_config(), 4)}; + std::shared_ptr> encoding{create_encoding(3, grid_lod_config("Soft"), 4)}; + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + auto base_optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto base_loss = std::shared_ptr>{create_loss(json::object())}; + auto base_trainer = std::make_shared>(base, base_optimizer, base_loss); + + std::vector params(encoding->n_params()); + for (size_t i = 0; i < params.size(); ++i) { + params[i] = (T)((static_cast((i * 23) % 41) - 20) / 128.0f); + } + CUDA_CHECK_THROW(cudaMemcpy(encoding->params(), params.data(), encoding->n_params() * sizeof(T), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW(cudaMemcpy(base->params(), params.data(), base->n_params() * sizeof(T), cudaMemcpyHostToDevice)); + + std::vector input_host(3 * batch_size); + std::vector base_input_host(2 * batch_size); + std::vector dL_ddLdinput_host(3 * batch_size); + std::vector base_dL_ddLdinput_host(2 * batch_size); + std::vector dL_doutput_host(encoding->padded_output_width() * batch_size); + std::vector base_dL_doutput_host(base->padded_output_width() * batch_size); + for (uint32_t element = 0; element < batch_size; ++element) { + input_host[element * 3] = base_input_host[element * 2] = 0.173f; + input_host[element * 3 + 1] = base_input_host[element * 2 + 1] = 0.587f; + input_host[element * 3 + 2] = ratio; + dL_ddLdinput_host[element * 3] = base_dL_ddLdinput_host[element * 2] = 0.75f; + dL_ddLdinput_host[element * 3 + 1] = base_dL_ddLdinput_host[element * 2 + 1] = -0.5f; + dL_ddLdinput_host[element * 3 + 2] = 100.0f; + for (uint32_t feature = 0; feature < encoding->padded_output_width(); ++feature) { + const size_t index = element * encoding->padded_output_width() + feature; + dL_doutput_host[index] = (T)(static_cast((index * 11) % 29) - 14) / 32.0f; + const float weight = feature < 4 ? soft_lod_weight(ratio, 2, feature / 2) : 1.0f; + base_dL_doutput_host[index] = weight * dL_doutput_host[index]; + } + } + + GPUMatrix input{3, batch_size}; + GPUMatrix base_input{2, batch_size}; + GPUMatrix output{encoding->padded_output_width(), batch_size}; + GPUMatrix base_output{base->padded_output_width(), batch_size}; + GPUMatrix dL_doutput{encoding->padded_output_width(), batch_size}; + GPUMatrix base_dL_doutput{base->padded_output_width(), batch_size}; + GPUMatrix dL_ddLdinput{3, batch_size}; + GPUMatrix base_dL_ddLdinput{2, batch_size}; + GPUMatrix dL_ddLdoutput{encoding->padded_output_width(), batch_size}; + GPUMatrix base_dL_ddLdoutput{base->padded_output_width(), batch_size}; + GPUMatrix dL_dinput{3, batch_size}; + GPUMatrix base_dL_dinput{2, batch_size}; + CUDA_CHECK_THROW(cudaMemcpy(input.data(), input_host.data(), input.n_bytes(), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW(cudaMemcpy(base_input.data(), base_input_host.data(), base_input.n_bytes(), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW(cudaMemcpy(dL_doutput.data(), dL_doutput_host.data(), dL_doutput.n_bytes(), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW( + cudaMemcpy(base_dL_doutput.data(), base_dL_doutput_host.data(), base_dL_doutput.n_bytes(), cudaMemcpyHostToDevice) + ); + CUDA_CHECK_THROW( + cudaMemcpy(dL_ddLdinput.data(), dL_ddLdinput_host.data(), dL_ddLdinput.n_bytes(), cudaMemcpyHostToDevice) + ); + CUDA_CHECK_THROW(cudaMemcpy( + base_dL_ddLdinput.data(), base_dL_ddLdinput_host.data(), base_dL_ddLdinput.n_bytes(), cudaMemcpyHostToDevice + )); + + auto context = encoding->forward(input, &output, false, true); + auto base_context = base->forward(base_input, &base_output, false, true); + encoding->backward_backward_input( + *context, input, dL_ddLdinput, dL_doutput, &dL_ddLdoutput, &dL_dinput, false, GradientMode::Overwrite + ); + base->backward_backward_input( + *base_context, + base_input, + base_dL_ddLdinput, + base_dL_doutput, + &base_dL_ddLdoutput, + &base_dL_dinput, + false, + GradientMode::Overwrite + ); + + const auto upstream_gradient = dL_ddLdoutput.to_cpu_vector(); + const auto base_upstream_gradient = base_dL_ddLdoutput.to_cpu_vector(); + const auto input_gradient = dL_dinput.to_cpu_vector(); + const auto base_input_gradient = base_dL_dinput.to_cpu_vector(); + bool found_upstream_gradient = false; + bool found_input_gradient = false; + for (uint32_t element = 0; element < batch_size; ++element) { + for (uint32_t feature = 0; feature < encoding->padded_output_width(); ++feature) { + const size_t index = element * encoding->padded_output_width() + feature; + const float weight = feature < 4 ? soft_lod_weight(ratio, 2, feature / 2) : 1.0f; + const float expected = weight * base_upstream_gradient[index]; + REQUIRE(upstream_gradient[index] == Approx(expected).margin(1e-5f).epsilon(1e-4f)); + found_upstream_gradient |= upstream_gradient[index] != 0.0f; + } + for (uint32_t dim = 0; dim < 2; ++dim) { + const float expected = base_input_gradient[element * 2 + dim]; + REQUIRE(input_gradient[element * 3 + dim] == Approx(expected).margin(1e-5f).epsilon(1e-4f)); + found_input_gradient |= input_gradient[element * 3 + dim] != 0.0f; + } + REQUIRE(input_gradient[element * 3 + 2] == 0.0f); + } + REQUIRE(found_upstream_gradient); + REQUIRE(found_input_gradient); + + std::vector parameter_gradient(encoding->n_params()); + std::vector base_parameter_gradient(base->n_params()); + CUDA_CHECK_THROW( + cudaMemcpy(parameter_gradient.data(), encoding->gradients(), encoding->n_params() * sizeof(T), cudaMemcpyDeviceToHost) + ); + CUDA_CHECK_THROW( + cudaMemcpy(base_parameter_gradient.data(), base->gradients(), base->n_params() * sizeof(T), cudaMemcpyDeviceToHost) + ); + bool found_parameter_gradient = false; + for (size_t i = 0; i < parameter_gradient.size(); ++i) { + REQUIRE(parameter_gradient[i] == Approx(base_parameter_gradient[i]).margin(1e-5f).epsilon(1e-4f)); + found_parameter_gradient |= parameter_gradient[i] != 0.0f; + } + REQUIRE(found_parameter_gradient); +} + +TEST_CASE("Multilevel LoD training supports CUDA graph capture", "[encoding][permuto][lod]") { + tcnn_test_setup(); + + using T = network_precision_t; + for (const char* lod_type : {"Hard", "Soft"}) { + CAPTURE(lod_type); + json config = hard_lod_config(); + config["lod_type"] = lod_type; + config["base"]["log2_hashmap_size"] = 4; + std::shared_ptr> encoding{create_encoding(6, config, 16)}; + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + + const uint32_t batch_size = BATCH_SIZE_GRANULARITY; + GPUMatrix input{6, batch_size}; + GPUMatrix input_gradient{6, batch_size}; + GPUMatrix target{32, batch_size}; + const auto input_host = hard_lod_input(batch_size, {0.0f, 10.0f / 16.0f, 1.0f}); + CUDA_CHECK_THROW(cudaMemcpy(input.data(), input_host.data(), input.n_bytes(), cudaMemcpyHostToDevice)); + + pcg32 rng{0xdeadbeef}; + target.initialize_uniform(rng, -1.0f, 1.0f); + StreamAndEvent training_stream; + auto context = trainer->training_step(training_stream.get(), input, target, nullptr, false, &input_gradient); + REQUIRE(context != nullptr); + CUDA_CHECK_THROW(cudaStreamSynchronize(training_stream.get())); + } +} + +TEST_CASE("Generalized Permuto supports native double backward", "[encoding][permuto][double-backward]") { + tcnn_test_setup(); + + const auto run_cases = [](auto precision) { + using T = decltype(precision); + (void)precision; + constexpr std::array, 2> test_configs = {{{1, 1}, {24, 8}}}; + for (const auto& [n_dims, n_features_per_level] : test_configs) { + CAPTURE(n_dims, n_features_per_level); + const bool maximum_width = n_features_per_level == 8; + json config = permuto_config(maximum_width ? 32 : 2, 2, n_features_per_level); + if (maximum_width) { + config["base_scale"] = 1.0f; + config["per_level_scale"] = 1.0f; + } + config["max_input_grad_dims"] = n_dims; + std::shared_ptr> encoding{create_encoding(n_dims, config, n_features_per_level)}; + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + + const uint32_t batch_size = BATCH_SIZE_GRANULARITY; + GPUMatrix input{n_dims, batch_size}; + GPUMatrix output{encoding->output_width(), batch_size}; + GPUMatrix dL_doutput{encoding->output_width(), batch_size}; + GPUMatrix dL_ddLdinput{n_dims, batch_size}; + GPUMatrix dL_ddLdoutput{encoding->output_width(), batch_size}; + GPUMatrix dL_dinput{n_dims, batch_size}; + pcg32 rng{0xdeadbeef}; + input.initialize_uniform(rng, 0.05f, 0.95f); + dL_doutput.initialize_uniform(rng, -0.25f, 0.25f); + dL_ddLdinput.initialize_uniform(rng, -1.0f, 1.0f); + dL_dinput.memset(0x7f); + + auto context = encoding->forward(input, &output, false, true); + encoding->backward_backward_input( + *context, input, dL_ddLdinput, dL_doutput, &dL_ddLdoutput, &dL_dinput, false, GradientMode::Overwrite + ); + + const auto dL_ddLdoutput_host = dL_ddLdoutput.to_cpu_vector(); + REQUIRE(std::any_of( + dL_ddLdoutput_host.begin(), dL_ddLdoutput_host.end(), [](T value) { return (float)value != 0.0f; } + )); + REQUIRE(std::all_of( + dL_ddLdoutput_host.begin(), dL_ddLdoutput_host.end(), [](T value) { return std::isfinite((float)value); } + )); + const auto dL_dinput_host = dL_dinput.to_cpu_vector(); + REQUIRE(std::all_of(dL_dinput_host.begin(), dL_dinput_host.end(), [](float value) { return value == 0.0f; })); + + std::vector parameter_gradient(encoding->n_params()); + CUDA_CHECK_THROW(cudaMemcpy( + parameter_gradient.data(), encoding->gradients(), parameter_gradient.size() * sizeof(T), cudaMemcpyDeviceToHost + )); + REQUIRE(std::any_of(parameter_gradient.begin(), parameter_gradient.end(), [](T value) { return (float)value != 0.0f; })); + REQUIRE(std::all_of(parameter_gradient.begin(), parameter_gradient.end(), [](T value) { return std::isfinite((float)value); })); + } + }; + + run_cases(float{}); + if constexpr (!std::is_same::value) { + run_cases(network_precision_t{}); + } +} + +TEST_CASE("Permuto supports native double backward", "[encoding][permuto][double-backward]") { + tcnn_test_setup(); + + json config = permuto_config(2, 3); + config["base_scale"] = 1.0f; + config["per_level_scale"] = 2.0f; + config["seed"] = 42; + std::shared_ptr> encoding{create_encoding(5, config, 2)}; + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + + std::vector params(encoding->n_params()); + for (size_t i = 0; i < params.size(); ++i) { + params[i] = static_cast(static_cast((i * 17) % 29) - 14) / 128.0f; + } + CUDA_CHECK_THROW(cudaMemcpy(encoding->params(), params.data(), params.size() * sizeof(float), cudaMemcpyHostToDevice)); + + constexpr uint32_t batch_size = BATCH_SIZE_GRANULARITY; + constexpr std::array position = {0.137f, 0.271f, 0.419f, 0.583f, 0.731f}; + constexpr std::array upstream = {0.75f, -0.5f, 0.25f, 1.0f}; + constexpr std::array second_seed = {1.0f, -0.5f, 0.25f, 7.0f, -9.0f}; + std::vector input_host(5 * batch_size, 0.0f); + std::vector upstream_host(4 * batch_size, 0.0f); + std::vector second_seed_host(5 * batch_size, 0.0f); + std::copy(position.begin(), position.end(), input_host.begin()); + std::copy(upstream.begin(), upstream.end(), upstream_host.begin()); + std::copy(second_seed.begin(), second_seed.end(), second_seed_host.begin()); + + GPUMatrix input{5, batch_size}; + GPUMatrix output{4, batch_size}; + GPUMatrix dL_doutput{4, batch_size}; + GPUMatrix dL_ddLdinput{5, batch_size}; + GPUMatrix dL_ddLdoutput{4, batch_size}; + GPUMatrix dL_dinput{5, batch_size}; + CUDA_CHECK_THROW(cudaMemcpy(input.data(), input_host.data(), input.n_bytes(), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW(cudaMemcpy(dL_doutput.data(), upstream_host.data(), dL_doutput.n_bytes(), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW(cudaMemcpy(dL_ddLdinput.data(), second_seed_host.data(), dL_ddLdinput.n_bytes(), cudaMemcpyHostToDevice)); + dL_dinput.memset(0x7f); + + auto context = encoding->forward(input, &output, false, true); + encoding->backward_backward_input( + *context, input, dL_ddLdinput, dL_doutput, &dL_ddLdoutput, &dL_dinput, false, GradientMode::Overwrite + ); + + const auto dL_ddLdoutput_host = dL_ddLdoutput.to_cpu_vector(); + const auto dL_dinput_host = dL_dinput.to_cpu_vector(); + REQUIRE(std::all_of(dL_dinput_host.begin(), dL_dinput_host.end(), [](float value) { return value == 0.0f; })); + + constexpr float input_epsilon = 1.0f / 1024.0f; + std::array reference_dL_ddLdoutput{}; + for (uint32_t dim = 0; dim < 3; ++dim) { + auto lower = position; + auto upper = position; + lower[dim] -= input_epsilon; + upper[dim] += input_epsilon; + const auto lower_output = reference_permuto_forward(lower, params, 1.0f, 42); + const auto upper_output = reference_permuto_forward(upper, params, 1.0f, 42); + for (uint32_t feature = 0; feature < 4; ++feature) { + reference_dL_ddLdoutput[feature] += second_seed[dim] * (upper_output[feature] - lower_output[feature]) / (2.0f * input_epsilon); + } + } + for (uint32_t feature = 0; feature < 4; ++feature) { + REQUIRE(dL_ddLdoutput_host[feature] == Approx(reference_dL_ddLdoutput[feature]).margin(2e-3f).epsilon(1e-2f)); + } + REQUIRE(std::all_of(dL_ddLdoutput_host.begin() + 4, dL_ddLdoutput_host.end(), [](float value) { return value == 0.0f; })); + + const auto reference_contraction = [&](const std::vector& reference_params) { + float result = 0.0f; + for (uint32_t dim = 0; dim < 3; ++dim) { + auto lower = position; + auto upper = position; + lower[dim] -= input_epsilon; + upper[dim] += input_epsilon; + const auto lower_output = reference_permuto_forward(lower, reference_params, 1.0f, 42); + const auto upper_output = reference_permuto_forward(upper, reference_params, 1.0f, 42); + for (uint32_t feature = 0; feature < 4; ++feature) { + result += second_seed[dim] * upstream[feature] * (upper_output[feature] - lower_output[feature]) / (2.0f * input_epsilon); + } + } + return result; + }; + + std::vector parameter_gradient(params.size()); + CUDA_CHECK_THROW( + cudaMemcpy(parameter_gradient.data(), encoding->gradients(), parameter_gradient.size() * sizeof(float), cudaMemcpyDeviceToHost) + ); + constexpr float parameter_epsilon = 1.0f / 256.0f; + bool has_parameter_gradient = false; + for (size_t i = 0; i < params.size(); ++i) { + auto lower = params; + auto upper = params; + lower[i] -= parameter_epsilon; + upper[i] += parameter_epsilon; + const float expected = (reference_contraction(upper) - reference_contraction(lower)) / (2.0f * parameter_epsilon); + has_parameter_gradient |= expected != 0.0f; + REQUIRE(parameter_gradient[i] == Approx(expected).margin(5e-3f).epsilon(2e-2f)); + } + REQUIRE(has_parameter_gradient); + + encoding->backward_backward_input( + *context, input, dL_ddLdinput, dL_doutput, &dL_ddLdoutput, nullptr, false, GradientMode::Accumulate + ); + std::vector accumulated(params.size()); + CUDA_CHECK_THROW(cudaMemcpy(accumulated.data(), encoding->gradients(), accumulated.size() * sizeof(float), cudaMemcpyDeviceToHost)); + for (size_t i = 0; i < params.size(); ++i) { + REQUIRE(accumulated[i] == Approx(2.0f * parameter_gradient[i]).margin(1e-5f).epsilon(1e-5f)); + } + encoding->backward_backward_input(*context, input, dL_ddLdinput, dL_doutput, &dL_ddLdoutput, nullptr, false, GradientMode::Ignore); + std::vector ignored(params.size()); + CUDA_CHECK_THROW(cudaMemcpy(ignored.data(), encoding->gradients(), ignored.size() * sizeof(float), cudaMemcpyDeviceToHost)); + REQUIRE(ignored == accumulated); + + std::fill(second_seed_host.begin(), second_seed_host.end(), 0.0f); + second_seed_host[3] = 1.0f; + second_seed_host[4] = -2.0f; + CUDA_CHECK_THROW(cudaMemcpy(dL_ddLdinput.data(), second_seed_host.data(), dL_ddLdinput.n_bytes(), cudaMemcpyHostToDevice)); + encoding->backward_backward_input( + *context, input, dL_ddLdinput, dL_doutput, &dL_ddLdoutput, &dL_dinput, false, GradientMode::Overwrite + ); + CUDA_CHECK_THROW(cudaMemcpy(parameter_gradient.data(), encoding->gradients(), parameter_gradient.size() * sizeof(float), cudaMemcpyDeviceToHost)); + REQUIRE(std::all_of(parameter_gradient.begin(), parameter_gradient.end(), [](float value) { return value == 0.0f; })); + const auto masked_dL_ddLdoutput = dL_ddLdoutput.to_cpu_vector(); + REQUIRE(std::all_of(masked_dL_ddLdoutput.begin(), masked_dL_ddLdoutput.end(), [](float value) { return value == 0.0f; })); +} + +TEST_CASE("Hard LoD delegates native double backward", "[encoding][permuto][lod][double-backward]") { + tcnn_test_setup(); + + json config = hard_lod_config(2, 3); + config["base"]["base_scale"] = 1.0f; + config["base"]["per_level_scale"] = 2.0f; + config["base"]["seed"] = 42; + std::shared_ptr> encoding{create_encoding(6, config, 2)}; + auto optimizer = std::shared_ptr>{create_optimizer(json::object())}; + auto loss = std::shared_ptr>{create_loss(json::object())}; + auto trainer = std::make_shared>(encoding, optimizer, loss); + + std::vector params(encoding->n_params()); + for (size_t i = 0; i < params.size(); ++i) { + params[i] = static_cast(static_cast((i * 17) % 29) - 14) / 128.0f; + } + CUDA_CHECK_THROW(cudaMemcpy(encoding->params(), params.data(), params.size() * sizeof(float), cudaMemcpyHostToDevice)); + + constexpr uint32_t batch_size = BATCH_SIZE_GRANULARITY; + constexpr std::array position = {0.137f, 0.271f, 0.419f, 0.583f, 0.731f}; + constexpr std::array upstream = {0.75f, -0.5f, 0.25f, 1.0f}; + const float boundary_ratio = (1.0f - 1e-3f) / 2.0f; + std::vector input_host(6 * batch_size, 0.0f); + std::vector upstream_host(4 * batch_size, 0.0f); + std::vector second_seed_host(6 * batch_size, 0.0f); + for (uint32_t element = 0; element < batch_size; ++element) { + std::copy(position.begin(), position.end(), input_host.begin() + element * 6); + } + input_host[5] = 0.0f; + input_host[11] = boundary_ratio; + input_host[17] = 1.0f; + for (uint32_t element = 0; element < 3; ++element) { + std::copy(upstream.begin(), upstream.end(), upstream_host.begin() + element * 4); + second_seed_host[element * 6] = 1.0f; + second_seed_host[element * 6 + 1] = -0.5f; + second_seed_host[element * 6 + 2] = 0.25f; + second_seed_host[element * 6 + 5] = 100.0f; + } + + GPUMatrix input{6, batch_size}; + GPUMatrix output{4, batch_size}; + GPUMatrix dL_doutput{4, batch_size}; + GPUMatrix dL_ddLdinput{6, batch_size}; + GPUMatrix dL_ddLdoutput{4, batch_size}; + GPUMatrix dL_dinput{6, batch_size}; + CUDA_CHECK_THROW(cudaMemcpy(input.data(), input_host.data(), input.n_bytes(), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW(cudaMemcpy(dL_doutput.data(), upstream_host.data(), dL_doutput.n_bytes(), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW(cudaMemcpy(dL_ddLdinput.data(), second_seed_host.data(), dL_ddLdinput.n_bytes(), cudaMemcpyHostToDevice)); + + auto context = encoding->forward(input, &output, false, true); + std::vector gradient_sentinel(params.size(), 0.5f); + CUDA_CHECK_THROW(cudaMemcpy(encoding->gradients(), gradient_sentinel.data(), gradient_sentinel.size() * sizeof(float), cudaMemcpyHostToDevice)); + encoding->backward_backward_input(*context, input, dL_ddLdinput, dL_doutput, &dL_ddLdoutput, nullptr, false, GradientMode::Ignore); + const auto dL_ddLdoutput_host = dL_ddLdoutput.to_cpu_vector(); + for (uint32_t element : {0u, 1u}) { + REQUIRE(dL_ddLdoutput_host[element * 4 + 2] == 0.0f); + REQUIRE(dL_ddLdoutput_host[element * 4 + 3] == 0.0f); + } + REQUIRE((dL_ddLdoutput_host[10] != 0.0f || dL_ddLdoutput_host[11] != 0.0f)); + std::vector ignored(params.size()); + CUDA_CHECK_THROW(cudaMemcpy(ignored.data(), encoding->gradients(), ignored.size() * sizeof(float), cudaMemcpyDeviceToHost)); + REQUIRE(ignored == gradient_sentinel); + + std::fill(upstream_host.begin() + 4, upstream_host.end(), 0.0f); + std::fill(second_seed_host.begin() + 6, second_seed_host.end(), 0.0f); + CUDA_CHECK_THROW(cudaMemcpy(dL_doutput.data(), upstream_host.data(), dL_doutput.n_bytes(), cudaMemcpyHostToDevice)); + CUDA_CHECK_THROW(cudaMemcpy(dL_ddLdinput.data(), second_seed_host.data(), dL_ddLdinput.n_bytes(), cudaMemcpyHostToDevice)); + dL_dinput.memset(0x7f); + encoding->backward_backward_input( + *context, input, dL_ddLdinput, dL_doutput, &dL_ddLdoutput, &dL_dinput, false, GradientMode::Overwrite + ); + std::vector parameter_gradient(params.size()); + CUDA_CHECK_THROW(cudaMemcpy(parameter_gradient.data(), encoding->gradients(), parameter_gradient.size() * sizeof(float), cudaMemcpyDeviceToHost)); + REQUIRE(std::any_of(parameter_gradient.begin(), parameter_gradient.begin() + parameter_gradient.size() / 2, [](float value) { return value != 0.0f; })); + REQUIRE(std::all_of(parameter_gradient.begin() + parameter_gradient.size() / 2, parameter_gradient.end(), [](float value) { return value == 0.0f; })); + const auto hessian = dL_dinput.to_cpu_vector(); + REQUIRE(std::all_of(hessian.begin(), hessian.end(), [](float value) { return value == 0.0f; })); + + std::fill(second_seed_host.begin(), second_seed_host.end(), 0.0f); + second_seed_host[5] = 1.0f; + CUDA_CHECK_THROW(cudaMemcpy(dL_ddLdinput.data(), second_seed_host.data(), dL_ddLdinput.n_bytes(), cudaMemcpyHostToDevice)); + encoding->backward_backward_input( + *context, input, dL_ddLdinput, dL_doutput, &dL_ddLdoutput, &dL_dinput, false, GradientMode::Overwrite + ); + CUDA_CHECK_THROW(cudaMemcpy(parameter_gradient.data(), encoding->gradients(), parameter_gradient.size() * sizeof(float), cudaMemcpyDeviceToHost)); + REQUIRE(std::all_of(parameter_gradient.begin(), parameter_gradient.end(), [](float value) { return value == 0.0f; })); + const auto ratio_dL_ddLdoutput = dL_ddLdoutput.to_cpu_vector(); + REQUIRE(std::all_of(ratio_dL_ddLdoutput.begin(), ratio_dL_ddLdoutput.end(), [](float value) { return value == 0.0f; })); + const auto ratio_dL_dinput = dL_dinput.to_cpu_vector(); + REQUIRE(std::all_of(ratio_dL_dinput.begin(), ratio_dL_dinput.end(), [](float value) { return value == 0.0f; })); +}