renderer.cpp 55.3 KB
Newer Older
Patrick Labatut's avatar
Patrick Labatut committed
1
2
3
4
5
6
7
8
/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

Christoph Lassner's avatar
Christoph Lassner committed
9
10
11
12
13
14
#include "./renderer.h"
#include "../include/commands.h"
#include "./camera.h"
#include "./util.h"

#include <ATen/ATen.h>
Christoph Lassner's avatar
Christoph Lassner committed
15
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
16
17
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
Christoph Lassner's avatar
Christoph Lassner committed
18
#endif
Christoph Lassner's avatar
Christoph Lassner committed
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

namespace PRE = ::pulsar::Renderer;

namespace pulsar {
namespace pytorch {

Renderer::Renderer(
    const unsigned int& width,
    const unsigned int& height,
    const unsigned int& max_n_balls,
    const bool& orthogonal_projection,
    const bool& right_handed_system,
    const float& background_normalization_depth,
    const uint& n_channels,
    const uint& n_track) {
  LOG_IF(INFO, PULSAR_LOG_INIT) << "Initializing renderer.";
Peter Bell's avatar
Peter Bell committed
35
36
37
38
  TORCH_CHECK_ARG(width > 0, 1, "image width must be > 0!");
  TORCH_CHECK_ARG(height > 0, 2, "image height must be > 0!");
  TORCH_CHECK_ARG(max_n_balls > 0, 3, "max_n_balls must be > 0!");
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
39
40
41
42
      background_normalization_depth > 0.f &&
          background_normalization_depth < 1.f,
      5,
      "background_normalization_depth must be in ]0., 1.[");
Peter Bell's avatar
Peter Bell committed
43
44
  TORCH_CHECK_ARG(n_channels > 0, 6, "n_channels must be > 0");
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
      n_track > 0 && n_track <= MAX_GRAD_SPHERES,
      7,
      ("n_track must be > 0 and <" + std::to_string(MAX_GRAD_SPHERES) +
       ". Is " + std::to_string(n_track) + ".")
          .c_str());
  LOG_IF(INFO, PULSAR_LOG_INIT)
      << "Image width: " << width << ", height: " << height;
  this->renderer_vec.emplace_back();
  this->device_type = c10::DeviceType::CPU;
  this->device_index = -1;
  PRE::construct<false>(
      this->renderer_vec.data(),
      max_n_balls,
      width,
      height,
      orthogonal_projection,
      right_handed_system,
      background_normalization_depth,
      n_channels,
      n_track);
  this->device_tracker = torch::zeros(1);
};

Renderer::~Renderer() {
  if (this->device_type == c10::DeviceType::CUDA) {
Christoph Lassner's avatar
Christoph Lassner committed
70
71
// Can't happen in the case that not compiled with CUDA.
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
72
73
74
75
    at::cuda::CUDAGuard device_guard(this->device_tracker.device());
    for (auto nrend : this->renderer_vec) {
      PRE::destruct<true>(&nrend);
    }
Christoph Lassner's avatar
Christoph Lassner committed
76
#endif
Christoph Lassner's avatar
Christoph Lassner committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
  } else {
    for (auto nrend : this->renderer_vec) {
      PRE::destruct<false>(&nrend);
    }
  }
}

bool Renderer::operator==(const Renderer& rhs) const {
  LOG_IF(INFO, PULSAR_LOG_INIT) << "Equality check.";
  bool renderer_agrees = (this->renderer_vec[0] == rhs.renderer_vec[0]);
  LOG_IF(INFO, PULSAR_LOG_INIT) << "  Renderer agrees: " << renderer_agrees;
  bool device_agrees =
      (this->device_tracker.device() == rhs.device_tracker.device());
  LOG_IF(INFO, PULSAR_LOG_INIT) << "  Device agrees: " << device_agrees;
  return (renderer_agrees && device_agrees);
};

void Renderer::ensure_on_device(torch::Device device, bool /*non_blocking*/) {
Peter Bell's avatar
Peter Bell committed
95
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
96
97
98
99
100
101
      device.type() == c10::DeviceType::CUDA ||
          device.type() == c10::DeviceType::CPU,
      1,
      "Only CPU and CUDA device types are supported.");
  if (device.type() != this->device_type ||
      device.index() != this->device_index) {
Christoph Lassner's avatar
Christoph Lassner committed
102
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
    LOG_IF(INFO, PULSAR_LOG_INIT)
        << "Transferring render buffers between devices.";
    int prev_active;
    cudaGetDevice(&prev_active);
    if (this->device_type == c10::DeviceType::CUDA) {
      LOG_IF(INFO, PULSAR_LOG_INIT) << "  Destructing on CUDA.";
      cudaSetDevice(this->device_index);
      for (auto& nrend : this->renderer_vec) {
        PRE::destruct<true>(&nrend);
      }
    } else {
      LOG_IF(INFO, PULSAR_LOG_INIT) << "  Destructing on CPU.";
      for (auto& nrend : this->renderer_vec) {
        PRE::destruct<false>(&nrend);
      }
    }
    if (device.type() == c10::DeviceType::CUDA) {
      LOG_IF(INFO, PULSAR_LOG_INIT) << "  Constructing on CUDA.";
      cudaSetDevice(device.index());
      for (auto& nrend : this->renderer_vec) {
        PRE::construct<true>(
            &nrend,
            this->renderer_vec[0].max_num_balls,
            this->renderer_vec[0].cam.film_width,
            this->renderer_vec[0].cam.film_height,
            this->renderer_vec[0].cam.orthogonal_projection,
            this->renderer_vec[0].cam.right_handed,
            this->renderer_vec[0].cam.background_normalization_depth,
            this->renderer_vec[0].cam.n_channels,
            this->n_track());
      }
    } else {
      LOG_IF(INFO, PULSAR_LOG_INIT) << "  Constructing on CPU.";
      for (auto& nrend : this->renderer_vec) {
        PRE::construct<false>(
            &nrend,
            this->renderer_vec[0].max_num_balls,
            this->renderer_vec[0].cam.film_width,
            this->renderer_vec[0].cam.film_height,
            this->renderer_vec[0].cam.orthogonal_projection,
            this->renderer_vec[0].cam.right_handed,
            this->renderer_vec[0].cam.background_normalization_depth,
            this->renderer_vec[0].cam.n_channels,
            this->n_track());
      }
    }
    cudaSetDevice(prev_active);
    this->device_type = device.type();
    this->device_index = device.index();
Christoph Lassner's avatar
Christoph Lassner committed
152
153
154
155
156
#else
    throw std::runtime_error(
        "pulsar was built without CUDA "
        "but a device move to a CUDA device was initiated.");
#endif
Christoph Lassner's avatar
Christoph Lassner committed
157
158
159
160
161
162
163
164
165
166
167
168
  }
};

void Renderer::ensure_n_renderers_gte(const size_t& batch_size) {
  if (this->renderer_vec.size() < batch_size) {
    ptrdiff_t diff = batch_size - this->renderer_vec.size();
    LOG_IF(INFO, PULSAR_LOG_INIT)
        << "Increasing render buffers by " << diff
        << " to account for batch size " << batch_size;
    for (ptrdiff_t i = 0; i < diff; ++i) {
      this->renderer_vec.emplace_back();
      if (this->device_type == c10::DeviceType::CUDA) {
Christoph Lassner's avatar
Christoph Lassner committed
169
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
170
171
172
173
174
175
176
177
178
179
        PRE::construct<true>(
            &this->renderer_vec[this->renderer_vec.size() - 1],
            this->max_num_balls(),
            this->width(),
            this->height(),
            this->renderer_vec[0].cam.orthogonal_projection,
            this->renderer_vec[0].cam.right_handed,
            this->renderer_vec[0].cam.background_normalization_depth,
            this->renderer_vec[0].cam.n_channels,
            this->n_track());
Christoph Lassner's avatar
Christoph Lassner committed
180
#endif
Christoph Lassner's avatar
Christoph Lassner committed
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
      } else {
        PRE::construct<false>(
            &this->renderer_vec[this->renderer_vec.size() - 1],
            this->max_num_balls(),
            this->width(),
            this->height(),
            this->renderer_vec[0].cam.orthogonal_projection,
            this->renderer_vec[0].cam.right_handed,
            this->renderer_vec[0].cam.background_normalization_depth,
            this->renderer_vec[0].cam.n_channels,
            this->n_track());
      }
    }
  }
}

std::tuple<size_t, size_t, bool, torch::Tensor> Renderer::arg_check(
    const torch::Tensor& vert_pos,
    const torch::Tensor& vert_col,
    const torch::Tensor& vert_radii,
    const torch::Tensor& cam_pos,
    const torch::Tensor& pixel_0_0_center,
    const torch::Tensor& pixel_vec_x,
    const torch::Tensor& pixel_vec_y,
    const torch::Tensor& focal_length,
    const torch::Tensor& principal_point_offsets,
    const float& gamma,
    const float& max_depth,
    float& min_depth,
    const c10::optional<torch::Tensor>& bg_col,
    const c10::optional<torch::Tensor>& opacity,
    const float& percent_allowed_difference,
    const uint& max_n_hits,
    const uint& mode) {
  LOG_IF(INFO, PULSAR_LOG_FORWARD || PULSAR_LOG_BACKWARD) << "Arg check.";
  size_t batch_size = 1;
  size_t n_points;
  bool batch_processing = false;
  if (vert_pos.ndimension() == 3) {
    // Check all parameters adhere batch size.
    batch_processing = true;
    batch_size = vert_pos.size(0);
Peter Bell's avatar
Peter Bell committed
223
    TORCH_CHECK_ARG(
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
224
225
        vert_col.ndimension() == 3 &&
            vert_col.size(0) == static_cast<int64_t>(batch_size),
Christoph Lassner's avatar
Christoph Lassner committed
226
227
        2,
        "vert_col needs to have batch size.");
Peter Bell's avatar
Peter Bell committed
228
    TORCH_CHECK_ARG(
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
229
230
        vert_radii.ndimension() == 2 &&
            vert_radii.size(0) == static_cast<int64_t>(batch_size),
Christoph Lassner's avatar
Christoph Lassner committed
231
232
        3,
        "vert_radii must be specified per batch.");
Peter Bell's avatar
Peter Bell committed
233
    TORCH_CHECK_ARG(
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
234
235
        cam_pos.ndimension() == 2 &&
            cam_pos.size(0) == static_cast<int64_t>(batch_size),
Christoph Lassner's avatar
Christoph Lassner committed
236
237
        4,
        "cam_pos must be specified per batch and have the correct batch size.");
Peter Bell's avatar
Peter Bell committed
238
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
239
        pixel_0_0_center.ndimension() == 2 &&
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
240
            pixel_0_0_center.size(0) == static_cast<int64_t>(batch_size),
Christoph Lassner's avatar
Christoph Lassner committed
241
242
        5,
        "pixel_0_0_center must be specified per batch.");
Peter Bell's avatar
Peter Bell committed
243
    TORCH_CHECK_ARG(
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
244
245
        pixel_vec_x.ndimension() == 2 &&
            pixel_vec_x.size(0) == static_cast<int64_t>(batch_size),
Christoph Lassner's avatar
Christoph Lassner committed
246
247
        6,
        "pixel_vec_x must be specified per batch.");
Peter Bell's avatar
Peter Bell committed
248
    TORCH_CHECK_ARG(
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
249
250
        pixel_vec_y.ndimension() == 2 &&
            pixel_vec_y.size(0) == static_cast<int64_t>(batch_size),
Christoph Lassner's avatar
Christoph Lassner committed
251
252
        7,
        "pixel_vec_y must be specified per batch.");
Peter Bell's avatar
Peter Bell committed
253
    TORCH_CHECK_ARG(
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
254
255
        focal_length.ndimension() == 1 &&
            focal_length.size(0) == static_cast<int64_t>(batch_size),
Christoph Lassner's avatar
Christoph Lassner committed
256
257
        8,
        "focal_length must be specified per batch.");
Peter Bell's avatar
Peter Bell committed
258
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
259
        principal_point_offsets.ndimension() == 2 &&
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
260
            principal_point_offsets.size(0) == static_cast<int64_t>(batch_size),
Christoph Lassner's avatar
Christoph Lassner committed
261
262
263
        9,
        "principal_point_offsets must be specified per batch.");
    if (opacity.has_value()) {
Peter Bell's avatar
Peter Bell committed
264
      TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
265
          opacity.value().ndimension() == 2 &&
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
266
              opacity.value().size(0) == static_cast<int64_t>(batch_size),
Christoph Lassner's avatar
Christoph Lassner committed
267
268
269
270
271
          13,
          "Opacity needs to be specified batch-wise.");
    }
    // Check all parameters are for a matching number of points.
    n_points = vert_pos.size(1);
Peter Bell's avatar
Peter Bell committed
272
    TORCH_CHECK_ARG(
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
273
        vert_col.size(1) == static_cast<int64_t>(n_points),
Christoph Lassner's avatar
Christoph Lassner committed
274
275
276
277
278
        2,
        ("The number of points for vertex positions (" +
         std::to_string(n_points) + ") and vertex colors (" +
         std::to_string(vert_col.size(1)) + ") doesn't agree.")
            .c_str());
Peter Bell's avatar
Peter Bell committed
279
    TORCH_CHECK_ARG(
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
280
        vert_radii.size(1) == static_cast<int64_t>(n_points),
Christoph Lassner's avatar
Christoph Lassner committed
281
282
283
284
285
286
        3,
        ("The number of points for vertex positions (" +
         std::to_string(n_points) + ") and vertex radii (" +
         std::to_string(vert_col.size(1)) + ") doesn't agree.")
            .c_str());
    if (opacity.has_value()) {
Peter Bell's avatar
Peter Bell committed
287
      TORCH_CHECK_ARG(
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
288
          opacity.value().size(1) == static_cast<int64_t>(n_points),
Christoph Lassner's avatar
Christoph Lassner committed
289
290
291
292
          13,
          "Opacity needs to be specified per point.");
    }
    // Check all parameters have the correct last dimension size.
Peter Bell's avatar
Peter Bell committed
293
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
294
295
296
297
298
        vert_pos.size(2) == 3,
        1,
        ("Vertex positions must be 3D (have shape " +
         std::to_string(vert_pos.size(2)) + ")!")
            .c_str());
Peter Bell's avatar
Peter Bell committed
299
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
300
301
302
303
304
305
        vert_col.size(2) == this->renderer_vec[0].cam.n_channels,
        2,
        ("Vertex colors must have the right number of channels (have shape " +
         std::to_string(vert_col.size(2)) + ", need " +
         std::to_string(this->renderer_vec[0].cam.n_channels) + ")!")
            .c_str());
Peter Bell's avatar
Peter Bell committed
306
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
307
308
309
310
311
        cam_pos.size(1) == 3,
        4,
        ("Camera position must be 3D (has shape " +
         std::to_string(cam_pos.size(1)) + ")!")
            .c_str());
Peter Bell's avatar
Peter Bell committed
312
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
313
314
315
316
317
        pixel_0_0_center.size(1) == 3,
        5,
        ("pixel_0_0_center must be 3D (has shape " +
         std::to_string(pixel_0_0_center.size(1)) + ")!")
            .c_str());
Peter Bell's avatar
Peter Bell committed
318
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
319
320
321
322
323
        pixel_vec_x.size(1) == 3,
        6,
        ("pixel_vec_x must be 3D (has shape " +
         std::to_string(pixel_vec_x.size(1)) + ")!")
            .c_str());
Peter Bell's avatar
Peter Bell committed
324
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
325
326
327
328
329
        pixel_vec_y.size(1) == 3,
        7,
        ("pixel_vec_y must be 3D (has shape " +
         std::to_string(pixel_vec_y.size(1)) + ")!")
            .c_str());
Peter Bell's avatar
Peter Bell committed
330
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
331
332
333
334
335
336
337
        principal_point_offsets.size(1) == 2,
        9,
        "principal_point_offsets must contain x and y offsets.");
    // Ensure enough renderers are available for the batch.
    ensure_n_renderers_gte(batch_size);
  } else {
    // Check all parameters are of correct dimension.
Peter Bell's avatar
Peter Bell committed
338
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
339
        vert_col.ndimension() == 2, 2, "vert_col needs to have dimension 2.");
Peter Bell's avatar
Peter Bell committed
340
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
341
        vert_radii.ndimension() == 1, 3, "vert_radii must have dimension 1.");
Peter Bell's avatar
Peter Bell committed
342
343
    TORCH_CHECK_ARG(cam_pos.ndimension() == 1, 4, "cam_pos must have dimension 1.");
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
344
345
346
        pixel_0_0_center.ndimension() == 1,
        5,
        "pixel_0_0_center must have dimension 1.");
Peter Bell's avatar
Peter Bell committed
347
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
348
        pixel_vec_x.ndimension() == 1, 6, "pixel_vec_x must have dimension 1.");
Peter Bell's avatar
Peter Bell committed
349
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
350
        pixel_vec_y.ndimension() == 1, 7, "pixel_vec_y must have dimension 1.");
Peter Bell's avatar
Peter Bell committed
351
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
352
353
354
        focal_length.ndimension() == 0,
        8,
        "focal_length must have dimension 0.");
Peter Bell's avatar
Peter Bell committed
355
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
356
357
358
359
        principal_point_offsets.ndimension() == 1,
        9,
        "principal_point_offsets must have dimension 1.");
    if (opacity.has_value()) {
Peter Bell's avatar
Peter Bell committed
360
      TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
361
362
363
364
365
366
          opacity.value().ndimension() == 1,
          13,
          "Opacity needs to be specified per sample.");
    }
    // Check each.
    n_points = vert_pos.size(0);
Peter Bell's avatar
Peter Bell committed
367
    TORCH_CHECK_ARG(
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
368
        vert_col.size(0) == static_cast<int64_t>(n_points),
Christoph Lassner's avatar
Christoph Lassner committed
369
370
371
372
373
        2,
        ("The number of points for vertex positions (" +
         std::to_string(n_points) + ") and vertex colors (" +
         std::to_string(vert_col.size(0)) + ") doesn't agree.")
            .c_str());
Peter Bell's avatar
Peter Bell committed
374
    TORCH_CHECK_ARG(
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
375
        vert_radii.size(0) == static_cast<int64_t>(n_points),
Christoph Lassner's avatar
Christoph Lassner committed
376
377
378
379
380
381
        3,
        ("The number of points for vertex positions (" +
         std::to_string(n_points) + ") and vertex radii (" +
         std::to_string(vert_col.size(0)) + ") doesn't agree.")
            .c_str());
    if (opacity.has_value()) {
Peter Bell's avatar
Peter Bell committed
382
      TORCH_CHECK_ARG(
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
383
          opacity.value().size(0) == static_cast<int64_t>(n_points),
Christoph Lassner's avatar
Christoph Lassner committed
384
385
386
387
          12,
          "Opacity needs to be specified per point.");
    }
    // Check all parameters have the correct last dimension size.
Peter Bell's avatar
Peter Bell committed
388
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
389
390
391
392
393
        vert_pos.size(1) == 3,
        1,
        ("Vertex positions must be 3D (have shape " +
         std::to_string(vert_pos.size(1)) + ")!")
            .c_str());
Peter Bell's avatar
Peter Bell committed
394
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
395
396
397
398
399
400
        vert_col.size(1) == this->renderer_vec[0].cam.n_channels,
        2,
        ("Vertex colors must have the right number of channels (have shape " +
         std::to_string(vert_col.size(1)) + ", need " +
         std::to_string(this->renderer_vec[0].cam.n_channels) + ")!")
            .c_str());
Peter Bell's avatar
Peter Bell committed
401
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
402
403
404
405
406
        cam_pos.size(0) == 3,
        4,
        ("Camera position must be 3D (has shape " +
         std::to_string(cam_pos.size(0)) + ")!")
            .c_str());
Peter Bell's avatar
Peter Bell committed
407
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
408
409
410
411
412
        pixel_0_0_center.size(0) == 3,
        5,
        ("pixel_0_0_center must be 3D (has shape " +
         std::to_string(pixel_0_0_center.size(0)) + ")!")
            .c_str());
Peter Bell's avatar
Peter Bell committed
413
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
414
415
416
417
418
        pixel_vec_x.size(0) == 3,
        6,
        ("pixel_vec_x must be 3D (has shape " +
         std::to_string(pixel_vec_x.size(0)) + ")!")
            .c_str());
Peter Bell's avatar
Peter Bell committed
419
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
420
421
422
423
424
        pixel_vec_y.size(0) == 3,
        7,
        ("pixel_vec_y must be 3D (has shape " +
         std::to_string(pixel_vec_y.size(0)) + ")!")
            .c_str());
Peter Bell's avatar
Peter Bell committed
425
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
426
427
428
429
430
431
        principal_point_offsets.size(0) == 2,
        9,
        "principal_point_offsets must have x and y component.");
  }
  // Check device placement.
  auto dev = torch::device_of(vert_pos).value();
Peter Bell's avatar
Peter Bell committed
432
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
433
434
435
436
437
438
439
440
441
      dev.type() == this->device_type && dev.index() == this->device_index,
      1,
      ("Vertex positions must be stored on device " +
       c10::DeviceTypeName(this->device_type) + ", index " +
       std::to_string(this->device_index) + "! Are stored on " +
       c10::DeviceTypeName(dev.type()) + ", index " +
       std::to_string(dev.index()) + ".")
          .c_str());
  dev = torch::device_of(vert_col).value();
Peter Bell's avatar
Peter Bell committed
442
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
443
444
445
446
447
448
449
450
451
      dev.type() == this->device_type && dev.index() == this->device_index,
      2,
      ("Vertex colors must be stored on device " +
       c10::DeviceTypeName(this->device_type) + ", index " +
       std::to_string(this->device_index) + "! Are stored on " +
       c10::DeviceTypeName(dev.type()) + ", index " +
       std::to_string(dev.index()) + ".")
          .c_str());
  dev = torch::device_of(vert_radii).value();
Peter Bell's avatar
Peter Bell committed
452
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
453
454
455
456
457
458
459
460
461
      dev.type() == this->device_type && dev.index() == this->device_index,
      3,
      ("Vertex radii must be stored on device " +
       c10::DeviceTypeName(this->device_type) + ", index " +
       std::to_string(this->device_index) + "! Are stored on " +
       c10::DeviceTypeName(dev.type()) + ", index " +
       std::to_string(dev.index()) + ".")
          .c_str());
  dev = torch::device_of(cam_pos).value();
Peter Bell's avatar
Peter Bell committed
462
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
463
464
465
466
467
468
469
470
471
      dev.type() == this->device_type && dev.index() == this->device_index,
      4,
      ("Camera position must be stored on device " +
       c10::DeviceTypeName(this->device_type) + ", index " +
       std::to_string(this->device_index) + "! Are stored on " +
       c10::DeviceTypeName(dev.type()) + ", index " +
       std::to_string(dev.index()) + ".")
          .c_str());
  dev = torch::device_of(pixel_0_0_center).value();
Peter Bell's avatar
Peter Bell committed
472
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
473
474
475
476
477
478
479
480
481
      dev.type() == this->device_type && dev.index() == this->device_index,
      5,
      ("pixel_0_0_center must be stored on device " +
       c10::DeviceTypeName(this->device_type) + ", index " +
       std::to_string(this->device_index) + "! Are stored on " +
       c10::DeviceTypeName(dev.type()) + ", index " +
       std::to_string(dev.index()) + ".")
          .c_str());
  dev = torch::device_of(pixel_vec_x).value();
Peter Bell's avatar
Peter Bell committed
482
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
483
484
485
486
487
488
489
490
491
      dev.type() == this->device_type && dev.index() == this->device_index,
      6,
      ("pixel_vec_x must be stored on device " +
       c10::DeviceTypeName(this->device_type) + ", index " +
       std::to_string(this->device_index) + "! Are stored on " +
       c10::DeviceTypeName(dev.type()) + ", index " +
       std::to_string(dev.index()) + ".")
          .c_str());
  dev = torch::device_of(pixel_vec_y).value();
Peter Bell's avatar
Peter Bell committed
492
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
493
494
495
496
497
498
499
500
501
      dev.type() == this->device_type && dev.index() == this->device_index,
      7,
      ("pixel_vec_y must be stored on device " +
       c10::DeviceTypeName(this->device_type) + ", index " +
       std::to_string(this->device_index) + "! Are stored on " +
       c10::DeviceTypeName(dev.type()) + ", index " +
       std::to_string(dev.index()) + ".")
          .c_str());
  dev = torch::device_of(principal_point_offsets).value();
Peter Bell's avatar
Peter Bell committed
502
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
503
504
505
506
507
508
509
510
511
512
      dev.type() == this->device_type && dev.index() == this->device_index,
      9,
      ("principal_point_offsets must be stored on device " +
       c10::DeviceTypeName(this->device_type) + ", index " +
       std::to_string(this->device_index) + "! Are stored on " +
       c10::DeviceTypeName(dev.type()) + ", index " +
       std::to_string(dev.index()) + ".")
          .c_str());
  if (opacity.has_value()) {
    dev = torch::device_of(opacity.value()).value();
Peter Bell's avatar
Peter Bell committed
513
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
514
515
516
517
518
519
520
521
522
523
        dev.type() == this->device_type && dev.index() == this->device_index,
        13,
        ("opacity must be stored on device " +
         c10::DeviceTypeName(this->device_type) + ", index " +
         std::to_string(this->device_index) + "! Is stored on " +
         c10::DeviceTypeName(dev.type()) + ", index " +
         std::to_string(dev.index()) + ".")
            .c_str());
  }
  // Type checks.
Peter Bell's avatar
Peter Bell committed
524
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
525
      vert_pos.scalar_type() == c10::kFloat, 1, "pulsar requires float types.");
Peter Bell's avatar
Peter Bell committed
526
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
527
      vert_col.scalar_type() == c10::kFloat, 2, "pulsar requires float types.");
Peter Bell's avatar
Peter Bell committed
528
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
529
530
531
      vert_radii.scalar_type() == c10::kFloat,
      3,
      "pulsar requires float types.");
Peter Bell's avatar
Peter Bell committed
532
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
533
      cam_pos.scalar_type() == c10::kFloat, 4, "pulsar requires float types.");
Peter Bell's avatar
Peter Bell committed
534
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
535
536
537
      pixel_0_0_center.scalar_type() == c10::kFloat,
      5,
      "pulsar requires float types.");
Peter Bell's avatar
Peter Bell committed
538
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
539
540
541
      pixel_vec_x.scalar_type() == c10::kFloat,
      6,
      "pulsar requires float types.");
Peter Bell's avatar
Peter Bell committed
542
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
543
544
545
      pixel_vec_y.scalar_type() == c10::kFloat,
      7,
      "pulsar requires float types.");
Peter Bell's avatar
Peter Bell committed
546
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
547
548
549
      focal_length.scalar_type() == c10::kFloat,
      8,
      "pulsar requires float types.");
Peter Bell's avatar
Peter Bell committed
550
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
551
552
553
554
555
556
557
      // Unfortunately, the PyTorch interface is inconsistent for
      // Int32: in Python, there exists an explicit int32 type, in
      // C++ this is currently `c10::kInt`.
      principal_point_offsets.scalar_type() == c10::kInt,
      9,
      "principal_point_offsets must be provided as int32.");
  if (opacity.has_value()) {
Peter Bell's avatar
Peter Bell committed
558
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
559
560
561
562
563
        opacity.value().scalar_type() == c10::kFloat,
        13,
        "opacity must be a float type.");
  }
  // Content checks.
Peter Bell's avatar
Peter Bell committed
564
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
565
566
567
568
569
570
      (vert_radii > FEPS).all().item<bool>(),
      3,
      ("Vertex radii must be > FEPS (min is " +
       std::to_string(vert_radii.min().item<float>()) + ").")
          .c_str());
  if (this->orthogonal()) {
Peter Bell's avatar
Peter Bell committed
571
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
572
573
574
575
576
577
        (focal_length == 0.f).all().item<bool>(),
        8,
        ("for an orthogonal projection focal length must be zero (abs max: " +
         std::to_string(focal_length.abs().max().item<float>()) + ").")
            .c_str());
  } else {
Peter Bell's avatar
Peter Bell committed
578
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
579
580
581
582
583
584
        (focal_length > FEPS).all().item<bool>(),
        8,
        ("for a perspective projection focal length must be > FEPS (min " +
         std::to_string(focal_length.min().item<float>()) + ").")
            .c_str());
  }
Peter Bell's avatar
Peter Bell committed
585
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
586
587
588
589
590
591
      gamma <= 1.f && gamma >= 1E-5f,
      10,
      ("gamma must be in [1E-5, 1] (" + std::to_string(gamma) + ").").c_str());
  if (min_depth == 0.f) {
    min_depth = focal_length.max().item<float>() + 2.f * FEPS;
  }
Peter Bell's avatar
Peter Bell committed
592
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
593
594
595
596
597
      min_depth > focal_length.max().item<float>(),
      12,
      ("min_depth must be > focal_length (" + std::to_string(min_depth) +
       " vs. " + std::to_string(focal_length.max().item<float>()) + ").")
          .c_str());
Peter Bell's avatar
Peter Bell committed
598
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
599
600
601
602
603
      max_depth > min_depth + FEPS,
      11,
      ("max_depth must be > min_depth + FEPS (" + std::to_string(max_depth) +
       " vs. " + std::to_string(min_depth + FEPS) + ").")
          .c_str());
Peter Bell's avatar
Peter Bell committed
604
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
605
606
607
608
609
      percent_allowed_difference >= 0.f && percent_allowed_difference < 1.f,
      14,
      ("percent_allowed_difference must be in [0., 1.[ (" +
       std::to_string(percent_allowed_difference) + ").")
          .c_str());
Peter Bell's avatar
Peter Bell committed
610
611
  TORCH_CHECK_ARG(max_n_hits > 0, 14, "max_n_hits must be > 0!");
  TORCH_CHECK_ARG(mode < 2, 15, "mode must be in {0, 1}.");
Christoph Lassner's avatar
Christoph Lassner committed
612
613
  torch::Tensor real_bg_col;
  if (bg_col.has_value()) {
Peter Bell's avatar
Peter Bell committed
614
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
615
616
617
618
        bg_col.value().device().type() == this->device_type &&
            bg_col.value().device().index() == this->device_index,
        13,
        "bg_col must be stored on the renderer device!");
Peter Bell's avatar
Peter Bell committed
619
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
620
621
622
623
624
625
626
627
628
629
630
631
        bg_col.value().ndimension() == 1 &&
            bg_col.value().size(0) == renderer_vec[0].cam.n_channels,
        13,
        "bg_col must have the same number of channels as the image,).");
    real_bg_col = bg_col.value();
  } else {
    real_bg_col = torch::ones(
                      {renderer_vec[0].cam.n_channels},
                      c10::Device(this->device_type, this->device_index))
                      .to(c10::kFloat);
  }
  if (opacity.has_value()) {
Peter Bell's avatar
Peter Bell committed
632
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
633
634
635
        (opacity.value() >= 0.f).all().item<bool>(),
        13,
        "opacity must be >= 0.");
Peter Bell's avatar
Peter Bell committed
636
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
        (opacity.value() <= 1.f).all().item<bool>(),
        13,
        "opacity must be <= 1.");
  }
  LOG_IF(INFO, PULSAR_LOG_FORWARD || PULSAR_LOG_BACKWARD)
      << "  batch_size: " << batch_size;
  LOG_IF(INFO, PULSAR_LOG_FORWARD || PULSAR_LOG_BACKWARD)
      << "  n_points: " << n_points;
  LOG_IF(INFO, PULSAR_LOG_FORWARD || PULSAR_LOG_BACKWARD)
      << "  batch_processing: " << batch_processing;
  return std::tuple<size_t, size_t, bool, torch::Tensor>(
      batch_size, n_points, batch_processing, real_bg_col);
}

std::tuple<torch::Tensor, torch::Tensor> Renderer::forward(
    const torch::Tensor& vert_pos,
    const torch::Tensor& vert_col,
    const torch::Tensor& vert_radii,
    const torch::Tensor& cam_pos,
    const torch::Tensor& pixel_0_0_center,
    const torch::Tensor& pixel_vec_x,
    const torch::Tensor& pixel_vec_y,
    const torch::Tensor& focal_length,
    const torch::Tensor& principal_point_offsets,
    const float& gamma,
    const float& max_depth,
    float min_depth,
    const c10::optional<torch::Tensor>& bg_col,
    const c10::optional<torch::Tensor>& opacity,
    const float& percent_allowed_difference,
    const uint& max_n_hits,
    const uint& mode) {
  // Parameter checks.
  this->ensure_on_device(this->device_tracker.device());
  size_t batch_size;
  size_t n_points;
  bool batch_processing;
  torch::Tensor real_bg_col;
  std::tie(batch_size, n_points, batch_processing, real_bg_col) =
      this->arg_check(
          vert_pos,
          vert_col,
          vert_radii,
          cam_pos,
          pixel_0_0_center,
          pixel_vec_x,
          pixel_vec_y,
          focal_length,
          principal_point_offsets,
          gamma,
          max_depth,
          min_depth,
          bg_col,
          opacity,
          percent_allowed_difference,
          max_n_hits,
          mode);
  LOG_IF(INFO, PULSAR_LOG_FORWARD) << "Extracting camera objects...";
  // Create the camera information.
  std::vector<CamInfo> cam_infos(batch_size);
  if (batch_processing) {
    for (size_t batch_i = 0; batch_i < batch_size; ++batch_i) {
      cam_infos[batch_i] = cam_info_from_params(
          cam_pos[batch_i],
          pixel_0_0_center[batch_i],
          pixel_vec_x[batch_i],
          pixel_vec_y[batch_i],
          principal_point_offsets[batch_i],
          focal_length[batch_i].item<float>(),
          this->renderer_vec[0].cam.film_width,
          this->renderer_vec[0].cam.film_height,
          min_depth,
          max_depth,
          this->renderer_vec[0].cam.right_handed);
    }
  } else {
    cam_infos[0] = cam_info_from_params(
        cam_pos,
        pixel_0_0_center,
        pixel_vec_x,
        pixel_vec_y,
        principal_point_offsets,
        focal_length.item<float>(),
        this->renderer_vec[0].cam.film_width,
        this->renderer_vec[0].cam.film_height,
        min_depth,
        max_depth,
        this->renderer_vec[0].cam.right_handed);
  }
  LOG_IF(INFO, PULSAR_LOG_FORWARD) << "Processing...";
  // Let's go!
  // Contiguous version of opacity, if available. We need to create this object
  // in scope to keep it alive.
  torch::Tensor opacity_contiguous;
  float const* opacity_ptr = nullptr;
  if (opacity.has_value()) {
    opacity_contiguous = opacity.value().contiguous();
    opacity_ptr = opacity_contiguous.data_ptr<float>();
  }
  if (this->device_type == c10::DeviceType::CUDA) {
Christoph Lassner's avatar
Christoph Lassner committed
737
738
739
740
// No else check necessary - if not compiled with CUDA
// we can't even reach this code (the renderer can't be
// moved to a CUDA device).
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
    int prev_active;
    cudaGetDevice(&prev_active);
    cudaSetDevice(this->device_index);
#ifdef PULSAR_TIMINGS_BATCHED_ENABLED
    START_TIME_CU(batch_forward);
#endif
    if (batch_processing) {
      for (size_t batch_i = 0; batch_i < batch_size; ++batch_i) {
        // These calls are non-blocking and just kick off the computations.
        PRE::forward<true>(
            &this->renderer_vec[batch_i],
            vert_pos[batch_i].contiguous().data_ptr<float>(),
            vert_col[batch_i].contiguous().data_ptr<float>(),
            vert_radii[batch_i].contiguous().data_ptr<float>(),
            cam_infos[batch_i],
            gamma,
            percent_allowed_difference,
            max_n_hits,
            real_bg_col.contiguous().data_ptr<float>(),
            opacity_ptr,
            n_points,
            mode,
            at::cuda::getCurrentCUDAStream());
      }
    } else {
      PRE::forward<true>(
          this->renderer_vec.data(),
          vert_pos.contiguous().data_ptr<float>(),
          vert_col.contiguous().data_ptr<float>(),
          vert_radii.contiguous().data_ptr<float>(),
          cam_infos[0],
          gamma,
          percent_allowed_difference,
          max_n_hits,
          real_bg_col.contiguous().data_ptr<float>(),
          opacity_ptr,
          n_points,
          mode,
          at::cuda::getCurrentCUDAStream());
    }
#ifdef PULSAR_TIMINGS_BATCHED_ENABLED
    STOP_TIME_CU(batch_forward);
    float time_ms;
    GET_TIME_CU(batch_forward, &time_ms);
    std::cout << "Forward render batched time per example: "
              << time_ms / static_cast<float>(batch_size) << "ms" << std::endl;
#endif
    cudaSetDevice(prev_active);
Christoph Lassner's avatar
Christoph Lassner committed
789
#endif
Christoph Lassner's avatar
Christoph Lassner committed
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
  } else {
#ifdef PULSAR_TIMINGS_BATCHED_ENABLED
    START_TIME(batch_forward);
#endif
    if (batch_processing) {
      for (size_t batch_i = 0; batch_i < batch_size; ++batch_i) {
        // These calls are non-blocking and just kick off the computations.
        PRE::forward<false>(
            &this->renderer_vec[batch_i],
            vert_pos[batch_i].contiguous().data_ptr<float>(),
            vert_col[batch_i].contiguous().data_ptr<float>(),
            vert_radii[batch_i].contiguous().data_ptr<float>(),
            cam_infos[batch_i],
            gamma,
            percent_allowed_difference,
            max_n_hits,
            real_bg_col.contiguous().data_ptr<float>(),
            opacity_ptr,
            n_points,
            mode,
            nullptr);
      }
    } else {
      PRE::forward<false>(
          this->renderer_vec.data(),
          vert_pos.contiguous().data_ptr<float>(),
          vert_col.contiguous().data_ptr<float>(),
          vert_radii.contiguous().data_ptr<float>(),
          cam_infos[0],
          gamma,
          percent_allowed_difference,
          max_n_hits,
          real_bg_col.contiguous().data_ptr<float>(),
          opacity_ptr,
          n_points,
          mode,
          nullptr);
    }
#ifdef PULSAR_TIMINGS_BATCHED_ENABLED
    STOP_TIME(batch_forward);
    float time_ms;
    GET_TIME(batch_forward, &time_ms);
    std::cout << "Forward render batched time per example: "
              << time_ms / static_cast<float>(batch_size) << "ms" << std::endl;
#endif
  }
  LOG_IF(INFO, PULSAR_LOG_FORWARD) << "Extracting results...";
  // Create the results.
  std::vector<torch::Tensor> results(batch_size);
  std::vector<torch::Tensor> forw_infos(batch_size);
  for (size_t batch_i = 0; batch_i < batch_size; ++batch_i) {
    results[batch_i] = from_blob(
        this->renderer_vec[batch_i].result_d,
        {this->renderer_vec[0].cam.film_height,
         this->renderer_vec[0].cam.film_width,
         this->renderer_vec[0].cam.n_channels},
        this->device_type,
        this->device_index,
        torch::kFloat,
        this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
850
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
851
            ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
852
853
854
#else
            ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
855
856
857
858
859
860
861
862
863
864
865
866
            : (cudaStream_t) nullptr);
    if (mode == 1)
      results[batch_i] = results[batch_i].slice(2, 0, 1, 1);
    forw_infos[batch_i] = from_blob(
        this->renderer_vec[batch_i].forw_info_d,
        {this->renderer_vec[0].cam.film_height,
         this->renderer_vec[0].cam.film_width,
         3 + 2 * this->n_track()},
        this->device_type,
        this->device_index,
        torch::kFloat,
        this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
867
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
868
            ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
869
870
871
#else
            ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
            : (cudaStream_t) nullptr);
  }
  LOG_IF(INFO, PULSAR_LOG_FORWARD) << "Forward render complete.";
  if (batch_processing) {
    return std::tuple<torch::Tensor, torch::Tensor>(
        torch::stack(results), torch::stack(forw_infos));
  } else {
    return std::tuple<torch::Tensor, torch::Tensor>(results[0], forw_infos[0]);
  }
};

std::tuple<
    at::optional<torch::Tensor>,
    at::optional<torch::Tensor>,
    at::optional<torch::Tensor>,
    at::optional<torch::Tensor>,
    at::optional<torch::Tensor>,
    at::optional<torch::Tensor>,
    at::optional<torch::Tensor>,
    at::optional<torch::Tensor>>
Renderer::backward(
    const torch::Tensor& grad_im,
    const torch::Tensor& image,
    const torch::Tensor& forw_info,
    const torch::Tensor& vert_pos,
    const torch::Tensor& vert_col,
    const torch::Tensor& vert_radii,
    const torch::Tensor& cam_pos,
    const torch::Tensor& pixel_0_0_center,
    const torch::Tensor& pixel_vec_x,
    const torch::Tensor& pixel_vec_y,
    const torch::Tensor& focal_length,
    const torch::Tensor& principal_point_offsets,
    const float& gamma,
    const float& max_depth,
    float min_depth,
    const c10::optional<torch::Tensor>& bg_col,
    const c10::optional<torch::Tensor>& opacity,
    const float& percent_allowed_difference,
    const uint& max_n_hits,
    const uint& mode,
    const bool& dif_pos,
    const bool& dif_col,
    const bool& dif_rad,
    const bool& dif_cam,
    const bool& dif_opy,
    const at::optional<std::pair<uint, uint>>& dbg_pos) {
  this->ensure_on_device(this->device_tracker.device());
  size_t batch_size;
  size_t n_points;
  bool batch_processing;
  torch::Tensor real_bg_col;
  std::tie(batch_size, n_points, batch_processing, real_bg_col) =
      this->arg_check(
          vert_pos,
          vert_col,
          vert_radii,
          cam_pos,
          pixel_0_0_center,
          pixel_vec_x,
          pixel_vec_y,
          focal_length,
          principal_point_offsets,
          gamma,
          max_depth,
          min_depth,
          bg_col,
          opacity,
          percent_allowed_difference,
          max_n_hits,
          mode);
  // Additional checks for the gradient computation.
Peter Bell's avatar
Peter Bell committed
944
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
945
946
947
948
949
950
951
952
      (grad_im.ndimension() == 3 + batch_processing &&
       static_cast<uint>(grad_im.size(0 + batch_processing)) ==
           this->height() &&
       static_cast<uint>(grad_im.size(1 + batch_processing)) == this->width() &&
       static_cast<uint>(grad_im.size(2 + batch_processing)) ==
           this->renderer_vec[0].cam.n_channels),
      1,
      "The gradient image size is not correct.");
Peter Bell's avatar
Peter Bell committed
953
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
954
955
956
957
958
959
960
      (image.ndimension() == 3 + batch_processing &&
       static_cast<uint>(image.size(0 + batch_processing)) == this->height() &&
       static_cast<uint>(image.size(1 + batch_processing)) == this->width() &&
       static_cast<uint>(image.size(2 + batch_processing)) ==
           this->renderer_vec[0].cam.n_channels),
      2,
      "The result image size is not correct.");
Peter Bell's avatar
Peter Bell committed
961
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
962
963
964
      grad_im.scalar_type() == c10::kFloat,
      1,
      "The gradient image must be of float type.");
Peter Bell's avatar
Peter Bell committed
965
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
966
967
968
969
      image.scalar_type() == c10::kFloat,
      2,
      "The image must be of float type.");
  if (dif_opy) {
Peter Bell's avatar
Peter Bell committed
970
    TORCH_CHECK_ARG(opacity.has_value(), 13, "dif_opy set requires opacity values.");
Christoph Lassner's avatar
Christoph Lassner committed
971
972
  }
  if (batch_processing) {
Peter Bell's avatar
Peter Bell committed
973
    TORCH_CHECK_ARG(
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
974
        grad_im.size(0) == static_cast<int64_t>(batch_size),
Christoph Lassner's avatar
Christoph Lassner committed
975
976
        1,
        "Gradient image batch size must agree.");
Peter Bell's avatar
Peter Bell committed
977
    TORCH_CHECK_ARG(
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
978
979
980
        image.size(0) == static_cast<int64_t>(batch_size),
        2,
        "Image batch size must agree.");
Peter Bell's avatar
Peter Bell committed
981
    TORCH_CHECK_ARG(
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
982
        forw_info.size(0) == static_cast<int64_t>(batch_size),
Christoph Lassner's avatar
Christoph Lassner committed
983
984
985
        3,
        "forward info must have batch size.");
  }
Peter Bell's avatar
Peter Bell committed
986
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
987
988
989
990
991
992
993
994
995
      (forw_info.ndimension() == 3 + batch_processing &&
       static_cast<uint>(forw_info.size(0 + batch_processing)) ==
           this->height() &&
       static_cast<uint>(forw_info.size(1 + batch_processing)) ==
           this->width() &&
       static_cast<uint>(forw_info.size(2 + batch_processing)) ==
           3 + 2 * this->n_track()),
      3,
      "The forward info image size is not correct.");
Peter Bell's avatar
Peter Bell committed
996
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
997
998
999
1000
1001
      forw_info.scalar_type() == c10::kFloat,
      3,
      "The forward info must be of float type.");
  // Check device.
  auto dev = torch::device_of(grad_im).value();
Peter Bell's avatar
Peter Bell committed
1002
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
1003
1004
1005
1006
1007
1008
1009
1010
1011
      dev.type() == this->device_type && dev.index() == this->device_index,
      1,
      ("grad_im must be stored on device " +
       c10::DeviceTypeName(this->device_type) + ", index " +
       std::to_string(this->device_index) + "! Are stored on " +
       c10::DeviceTypeName(dev.type()) + ", index " +
       std::to_string(dev.index()) + ".")
          .c_str());
  dev = torch::device_of(image).value();
Peter Bell's avatar
Peter Bell committed
1012
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
1013
1014
1015
1016
1017
1018
1019
1020
1021
      dev.type() == this->device_type && dev.index() == this->device_index,
      2,
      ("image must be stored on device " +
       c10::DeviceTypeName(this->device_type) + ", index " +
       std::to_string(this->device_index) + "! Are stored on " +
       c10::DeviceTypeName(dev.type()) + ", index " +
       std::to_string(dev.index()) + ".")
          .c_str());
  dev = torch::device_of(forw_info).value();
Peter Bell's avatar
Peter Bell committed
1022
  TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
1023
1024
1025
1026
1027
1028
1029
1030
1031
      dev.type() == this->device_type && dev.index() == this->device_index,
      3,
      ("forw_info must be stored on device " +
       c10::DeviceTypeName(this->device_type) + ", index " +
       std::to_string(this->device_index) + "! Are stored on " +
       c10::DeviceTypeName(dev.type()) + ", index " +
       std::to_string(dev.index()) + ".")
          .c_str());
  if (dbg_pos.has_value()) {
Peter Bell's avatar
Peter Bell committed
1032
    TORCH_CHECK_ARG(
Christoph Lassner's avatar
Christoph Lassner committed
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
        dbg_pos.value().first < this->width() &&
            dbg_pos.value().second < this->height(),
        23,
        "The debug position must be within image bounds.");
  }
  // Prepare the return value.
  std::tuple<
      at::optional<torch::Tensor>,
      at::optional<torch::Tensor>,
      at::optional<torch::Tensor>,
      at::optional<torch::Tensor>,
      at::optional<torch::Tensor>,
      at::optional<torch::Tensor>,
      at::optional<torch::Tensor>,
      at::optional<torch::Tensor>>
      ret;
1049
  if (mode == 1 || (!dif_pos && !dif_col && !dif_rad && !dif_cam && !dif_opy)) {
Christoph Lassner's avatar
Christoph Lassner committed
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
    return ret;
  }
  // Create the camera information.
  std::vector<CamInfo> cam_infos(batch_size);
  if (batch_processing) {
    for (size_t batch_i = 0; batch_i < batch_size; ++batch_i) {
      cam_infos[batch_i] = cam_info_from_params(
          cam_pos[batch_i],
          pixel_0_0_center[batch_i],
          pixel_vec_x[batch_i],
          pixel_vec_y[batch_i],
          principal_point_offsets[batch_i],
          focal_length[batch_i].item<float>(),
          this->renderer_vec[0].cam.film_width,
          this->renderer_vec[0].cam.film_height,
          min_depth,
          max_depth,
          this->renderer_vec[0].cam.right_handed);
    }
  } else {
    cam_infos[0] = cam_info_from_params(
        cam_pos,
        pixel_0_0_center,
        pixel_vec_x,
        pixel_vec_y,
        principal_point_offsets,
        focal_length.item<float>(),
        this->renderer_vec[0].cam.film_width,
        this->renderer_vec[0].cam.film_height,
        min_depth,
        max_depth,
        this->renderer_vec[0].cam.right_handed);
  }
  // Let's go!
  // Contiguous version of opacity, if available. We need to create this object
  // in scope to keep it alive.
  torch::Tensor opacity_contiguous;
  float const* opacity_ptr = nullptr;
  if (opacity.has_value()) {
    opacity_contiguous = opacity.value().contiguous();
    opacity_ptr = opacity_contiguous.data_ptr<float>();
  }
  if (this->device_type == c10::DeviceType::CUDA) {
Christoph Lassner's avatar
Christoph Lassner committed
1093
1094
1095
// No else check necessary - it's not possible to move
// the renderer to a CUDA device if not built with CUDA.
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
    int prev_active;
    cudaGetDevice(&prev_active);
    cudaSetDevice(this->device_index);
#ifdef PULSAR_TIMINGS_BATCHED_ENABLED
    START_TIME_CU(batch_backward);
#endif
    if (batch_processing) {
      for (size_t batch_i = 0; batch_i < batch_size; ++batch_i) {
        // These calls are non-blocking and just kick off the computations.
        if (dbg_pos.has_value()) {
          PRE::backward_dbg<true>(
              &this->renderer_vec[batch_i],
              grad_im[batch_i].contiguous().data_ptr<float>(),
              image[batch_i].contiguous().data_ptr<float>(),
              forw_info[batch_i].contiguous().data_ptr<float>(),
              vert_pos[batch_i].contiguous().data_ptr<float>(),
              vert_col[batch_i].contiguous().data_ptr<float>(),
              vert_radii[batch_i].contiguous().data_ptr<float>(),
              cam_infos[batch_i],
              gamma,
              percent_allowed_difference,
              max_n_hits,
              opacity_ptr,
              n_points,
              mode,
              dif_pos,
              dif_col,
              dif_rad,
              dif_cam,
              dif_opy,
              dbg_pos.value().first,
              dbg_pos.value().second,
              at::cuda::getCurrentCUDAStream());
        } else {
          PRE::backward<true>(
              &this->renderer_vec[batch_i],
              grad_im[batch_i].contiguous().data_ptr<float>(),
              image[batch_i].contiguous().data_ptr<float>(),
              forw_info[batch_i].contiguous().data_ptr<float>(),
              vert_pos[batch_i].contiguous().data_ptr<float>(),
              vert_col[batch_i].contiguous().data_ptr<float>(),
              vert_radii[batch_i].contiguous().data_ptr<float>(),
              cam_infos[batch_i],
              gamma,
              percent_allowed_difference,
              max_n_hits,
              opacity_ptr,
              n_points,
              mode,
              dif_pos,
              dif_col,
              dif_rad,
              dif_cam,
              dif_opy,
              at::cuda::getCurrentCUDAStream());
        }
      }
    } else {
      if (dbg_pos.has_value()) {
        PRE::backward_dbg<true>(
            this->renderer_vec.data(),
            grad_im.contiguous().data_ptr<float>(),
            image.contiguous().data_ptr<float>(),
            forw_info.contiguous().data_ptr<float>(),
            vert_pos.contiguous().data_ptr<float>(),
            vert_col.contiguous().data_ptr<float>(),
            vert_radii.contiguous().data_ptr<float>(),
            cam_infos[0],
            gamma,
            percent_allowed_difference,
            max_n_hits,
            opacity_ptr,
            n_points,
            mode,
            dif_pos,
            dif_col,
            dif_rad,
            dif_cam,
            dif_opy,
            dbg_pos.value().first,
            dbg_pos.value().second,
            at::cuda::getCurrentCUDAStream());
      } else {
        PRE::backward<true>(
            this->renderer_vec.data(),
            grad_im.contiguous().data_ptr<float>(),
            image.contiguous().data_ptr<float>(),
            forw_info.contiguous().data_ptr<float>(),
            vert_pos.contiguous().data_ptr<float>(),
            vert_col.contiguous().data_ptr<float>(),
            vert_radii.contiguous().data_ptr<float>(),
            cam_infos[0],
            gamma,
            percent_allowed_difference,
            max_n_hits,
            opacity_ptr,
            n_points,
            mode,
            dif_pos,
            dif_col,
            dif_rad,
            dif_cam,
            dif_opy,
            at::cuda::getCurrentCUDAStream());
      }
    }
    cudaSetDevice(prev_active);
#ifdef PULSAR_TIMINGS_BATCHED_ENABLED
    STOP_TIME_CU(batch_backward);
    float time_ms;
    GET_TIME_CU(batch_backward, &time_ms);
    std::cout << "Backward render batched time per example: "
              << time_ms / static_cast<float>(batch_size) << "ms" << std::endl;
#endif
Christoph Lassner's avatar
Christoph Lassner committed
1210
#endif // WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
  } else {
#ifdef PULSAR_TIMINGS_BATCHED_ENABLED
    START_TIME(batch_backward);
#endif
    if (batch_processing) {
      for (size_t batch_i = 0; batch_i < batch_size; ++batch_i) {
        // These calls are non-blocking and just kick off the computations.
        if (dbg_pos.has_value()) {
          PRE::backward_dbg<false>(
              &this->renderer_vec[batch_i],
              grad_im[batch_i].contiguous().data_ptr<float>(),
              image[batch_i].contiguous().data_ptr<float>(),
              forw_info[batch_i].contiguous().data_ptr<float>(),
              vert_pos[batch_i].contiguous().data_ptr<float>(),
              vert_col[batch_i].contiguous().data_ptr<float>(),
              vert_radii[batch_i].contiguous().data_ptr<float>(),
              cam_infos[batch_i],
              gamma,
              percent_allowed_difference,
              max_n_hits,
              opacity_ptr,
              n_points,
              mode,
              dif_pos,
              dif_col,
              dif_rad,
              dif_cam,
              dif_opy,
              dbg_pos.value().first,
              dbg_pos.value().second,
              nullptr);
        } else {
          PRE::backward<false>(
              &this->renderer_vec[batch_i],
              grad_im[batch_i].contiguous().data_ptr<float>(),
              image[batch_i].contiguous().data_ptr<float>(),
              forw_info[batch_i].contiguous().data_ptr<float>(),
              vert_pos[batch_i].contiguous().data_ptr<float>(),
              vert_col[batch_i].contiguous().data_ptr<float>(),
              vert_radii[batch_i].contiguous().data_ptr<float>(),
              cam_infos[batch_i],
              gamma,
              percent_allowed_difference,
              max_n_hits,
              opacity_ptr,
              n_points,
              mode,
              dif_pos,
              dif_col,
              dif_rad,
              dif_cam,
              dif_opy,
              nullptr);
        }
      }
    } else {
      if (dbg_pos.has_value()) {
        PRE::backward_dbg<false>(
            this->renderer_vec.data(),
            grad_im.contiguous().data_ptr<float>(),
            image.contiguous().data_ptr<float>(),
            forw_info.contiguous().data_ptr<float>(),
            vert_pos.contiguous().data_ptr<float>(),
            vert_col.contiguous().data_ptr<float>(),
            vert_radii.contiguous().data_ptr<float>(),
            cam_infos[0],
            gamma,
            percent_allowed_difference,
            max_n_hits,
            opacity_ptr,
            n_points,
            mode,
            dif_pos,
            dif_col,
            dif_rad,
            dif_cam,
            dif_opy,
            dbg_pos.value().first,
            dbg_pos.value().second,
            nullptr);
      } else {
        PRE::backward<false>(
            this->renderer_vec.data(),
            grad_im.contiguous().data_ptr<float>(),
            image.contiguous().data_ptr<float>(),
            forw_info.contiguous().data_ptr<float>(),
            vert_pos.contiguous().data_ptr<float>(),
            vert_col.contiguous().data_ptr<float>(),
            vert_radii.contiguous().data_ptr<float>(),
            cam_infos[0],
            gamma,
            percent_allowed_difference,
            max_n_hits,
            opacity_ptr,
            n_points,
            mode,
            dif_pos,
            dif_col,
            dif_rad,
            dif_cam,
            dif_opy,
            nullptr);
      }
    }
#ifdef PULSAR_TIMINGS_BATCHED_ENABLED
    STOP_TIME(batch_backward);
    float time_ms;
    GET_TIME(batch_backward, &time_ms);
    std::cout << "Backward render batched time per example: "
              << time_ms / static_cast<float>(batch_size) << "ms" << std::endl;
#endif
  }
  if (dif_pos) {
    if (batch_processing) {
      std::vector<torch::Tensor> results(batch_size);
      for (size_t batch_i = 0; batch_i < batch_size; ++batch_i) {
        results[batch_i] = from_blob(
            reinterpret_cast<float*>(this->renderer_vec[batch_i].grad_pos_d),
            {static_cast<ptrdiff_t>(n_points), 3},
            this->device_type,
            this->device_index,
            torch::kFloat,
            this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1334
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1335
                ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
1336
1337
1338
#else
                ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
                : (cudaStream_t) nullptr);
      }
      std::get<0>(ret) = torch::stack(results);
    } else {
      std::get<0>(ret) = from_blob(
          reinterpret_cast<float*>(this->renderer_vec[0].grad_pos_d),
          {static_cast<ptrdiff_t>(n_points), 3},
          this->device_type,
          this->device_index,
          torch::kFloat,
          this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1350
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1351
              ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
1352
1353
1354
#else
              ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
              : (cudaStream_t) nullptr);
    }
  }
  if (dif_col) {
    if (batch_processing) {
      std::vector<torch::Tensor> results(batch_size);
      for (size_t batch_i = 0; batch_i < batch_size; ++batch_i) {
        results[batch_i] = from_blob(
            reinterpret_cast<float*>(this->renderer_vec[batch_i].grad_col_d),
            {static_cast<ptrdiff_t>(n_points),
             this->renderer_vec[0].cam.n_channels},
            this->device_type,
            this->device_index,
            torch::kFloat,
            this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1370
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1371
                ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
1372
1373
1374
#else
                ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
                : (cudaStream_t) nullptr);
      }
      std::get<1>(ret) = torch::stack(results);
    } else {
      std::get<1>(ret) = from_blob(
          reinterpret_cast<float*>(this->renderer_vec[0].grad_col_d),
          {static_cast<ptrdiff_t>(n_points),
           this->renderer_vec[0].cam.n_channels},
          this->device_type,
          this->device_index,
          torch::kFloat,
          this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1387
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1388
              ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
1389
1390
1391
#else
              ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
              : (cudaStream_t) nullptr);
    }
  }
  if (dif_rad) {
    if (batch_processing) {
      std::vector<torch::Tensor> results(batch_size);
      for (size_t batch_i = 0; batch_i < batch_size; ++batch_i) {
        results[batch_i] = from_blob(
            reinterpret_cast<float*>(this->renderer_vec[batch_i].grad_rad_d),
            {static_cast<ptrdiff_t>(n_points)},
            this->device_type,
            this->device_index,
            torch::kFloat,
            this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1406
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1407
                ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
1408
1409
1410
#else
                ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
                : (cudaStream_t) nullptr);
      }
      std::get<2>(ret) = torch::stack(results);
    } else {
      std::get<2>(ret) = from_blob(
          reinterpret_cast<float*>(this->renderer_vec[0].grad_rad_d),
          {static_cast<ptrdiff_t>(n_points)},
          this->device_type,
          this->device_index,
          torch::kFloat,
          this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1422
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1423
              ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
1424
1425
1426
#else
              ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
              : (cudaStream_t) nullptr);
    }
  }
  if (dif_cam) {
    if (batch_processing) {
      std::vector<torch::Tensor> res_p1(batch_size);
      std::vector<torch::Tensor> res_p2(batch_size);
      std::vector<torch::Tensor> res_p3(batch_size);
      std::vector<torch::Tensor> res_p4(batch_size);
      for (size_t batch_i = 0; batch_i < batch_size; ++batch_i) {
        res_p1[batch_i] = from_blob(
            reinterpret_cast<float*>(this->renderer_vec[batch_i].grad_cam_d),
            {3},
            this->device_type,
            this->device_index,
            torch::kFloat,
            this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1444
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1445
                ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
1446
1447
1448
#else
                ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
1449
1450
1451
1452
1453
1454
1455
1456
1457
                : (cudaStream_t) nullptr);
        res_p2[batch_i] = from_blob(
            reinterpret_cast<float*>(
                this->renderer_vec[batch_i].grad_cam_d + 3),
            {3},
            this->device_type,
            this->device_index,
            torch::kFloat,
            this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1458
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1459
                ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
1460
1461
1462
#else
                ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
1463
1464
1465
1466
1467
1468
1469
1470
1471
                : (cudaStream_t) nullptr);
        res_p3[batch_i] = from_blob(
            reinterpret_cast<float*>(
                this->renderer_vec[batch_i].grad_cam_d + 6),
            {3},
            this->device_type,
            this->device_index,
            torch::kFloat,
            this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1472
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1473
                ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
1474
1475
1476
#else
                ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
1477
1478
1479
1480
1481
1482
1483
1484
1485
                : (cudaStream_t) nullptr);
        res_p4[batch_i] = from_blob(
            reinterpret_cast<float*>(
                this->renderer_vec[batch_i].grad_cam_d + 9),
            {3},
            this->device_type,
            this->device_index,
            torch::kFloat,
            this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1486
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1487
                ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
1488
1489
1490
#else
                ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
                : (cudaStream_t) nullptr);
      }
      std::get<3>(ret) = torch::stack(res_p1);
      std::get<4>(ret) = torch::stack(res_p2);
      std::get<5>(ret) = torch::stack(res_p3);
      std::get<6>(ret) = torch::stack(res_p4);
    } else {
      std::get<3>(ret) = from_blob(
          reinterpret_cast<float*>(this->renderer_vec[0].grad_cam_d),
          {3},
          this->device_type,
          this->device_index,
          torch::kFloat,
          this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1505
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1506
              ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
1507
1508
1509
#else
              ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
1510
1511
1512
1513
1514
1515
1516
1517
              : (cudaStream_t) nullptr);
      std::get<4>(ret) = from_blob(
          reinterpret_cast<float*>(this->renderer_vec[0].grad_cam_d + 3),
          {3},
          this->device_type,
          this->device_index,
          torch::kFloat,
          this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1518
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1519
              ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
1520
1521
1522
#else
              ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
1523
1524
1525
1526
1527
1528
1529
1530
              : (cudaStream_t) nullptr);
      std::get<5>(ret) = from_blob(
          reinterpret_cast<float*>(this->renderer_vec[0].grad_cam_d + 6),
          {3},
          this->device_type,
          this->device_index,
          torch::kFloat,
          this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1531
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1532
              ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
1533
1534
1535
#else
              ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
1536
1537
1538
1539
1540
1541
1542
1543
              : (cudaStream_t) nullptr);
      std::get<6>(ret) = from_blob(
          reinterpret_cast<float*>(this->renderer_vec[0].grad_cam_d + 9),
          {3},
          this->device_type,
          this->device_index,
          torch::kFloat,
          this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1544
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1545
              ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
1546
1547
1548
#else
              ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
              : (cudaStream_t) nullptr);
    }
  }
  if (dif_opy) {
    if (batch_processing) {
      std::vector<torch::Tensor> results(batch_size);
      for (size_t batch_i = 0; batch_i < batch_size; ++batch_i) {
        results[batch_i] = from_blob(
            reinterpret_cast<float*>(this->renderer_vec[batch_i].grad_opy_d),
            {static_cast<ptrdiff_t>(n_points)},
            this->device_type,
            this->device_index,
            torch::kFloat,
            this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1563
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1564
                ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
1565
1566
1567
#else
                ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
                : (cudaStream_t) nullptr);
      }
      std::get<7>(ret) = torch::stack(results);
    } else {
      std::get<7>(ret) = from_blob(
          reinterpret_cast<float*>(this->renderer_vec[0].grad_opy_d),
          {static_cast<ptrdiff_t>(n_points)},
          this->device_type,
          this->device_index,
          torch::kFloat,
          this->device_type == c10::DeviceType::CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1579
#ifdef WITH_CUDA
Christoph Lassner's avatar
Christoph Lassner committed
1580
              ? at::cuda::getCurrentCUDAStream()
Christoph Lassner's avatar
Christoph Lassner committed
1581
1582
1583
#else
              ? (cudaStream_t) nullptr
#endif
Christoph Lassner's avatar
Christoph Lassner committed
1584
1585
1586
1587
1588
1589
1590
1591
              : (cudaStream_t) nullptr);
    }
  }
  return ret;
};

} // namespace pytorch
} // namespace pulsar