ACloudViewer  3.9.4
A Modern Library for 3D Data Processing
ContinuousConvBackpropFilter.cuh
Go to the documentation of this file.
1 // ----------------------------------------------------------------------------
2 // - CloudViewer: www.cloudViewer.org -
3 // ----------------------------------------------------------------------------
4 // Copyright (c) 2018-2024 www.cloudViewer.org
5 // SPDX-License-Identifier: MIT
6 // ----------------------------------------------------------------------------
7 
8 #pragma once
9 #define EIGEN_USE_GPU
10 
11 #include <Helper.h>
12 #include <cutlass/gemm/gemm.h>
13 #include <cutlass/gemm/sgemm_traits.h>
14 
15 #include "ml/impl/continuous_conv/ContinuousConvCUDAKernels.h"
16 #include "ml/impl/misc/MemoryAllocation.h"
17 
18 using cloudViewer::utility::DivUp;
19 
20 namespace cloudViewer {
21 namespace ml {
22 namespace impl {
23 
24 /// Computes the backprop for the filter of a continuous convolution.
25 ///
26 /// All pointer arguments point to device memory unless stated otherwise.
27 ///
28 /// \tparam TFeat Type for the features and weights
29 /// \tparam TOut Type for the output features
30 /// \tparam TReal Type for point positions and extents
31 /// \tparam TIndex Type for neighbor indexing
32 ///
33 /// \param temp Pointer to temporary memory. If nullptr then the required
34 /// size of temporary memory will be written to \p temp_size and no
35 /// work is done. This function can make use of more memory and
36 /// returns the maximum size that can be used in max_temp_size.
37 ///
38 /// \param temp_size The size of the temporary memory in bytes. This is
39 /// used as an output if temp is nullptr and returns the minimum temp
40 /// size required.
41 ///
42 /// \param max_temp_size This is used as an output if temp is nullptr and
43 /// returns the maximum temp size that can be used.
44 ///
45 /// \param texture_alignment The texture alignment in bytes. This is used
46 /// for allocating segments within the temporary memory.
47 ///
48 /// \param filter_backrop Output array for the computed filter gradient
49 /// with shape [depth,height,witdth, inp channels, out channels]
50 ///
51 /// \param filter_dims The sizes of the filter dimensions. The size of
52 /// filter_dims must be 5. The order is
53 /// [depth, height, width, inp channels, out channels].
54 ///
55 /// \param num_out The number of output points.
56 ///
57 /// \param out_positions The positions of the output points. The shape is
58 /// [num_out, 3].
59 ///
60 /// \param num_inp The number of input points.
61 ///
62 /// \param inp_positions The positions of the input points. The shape is
63 /// [num_inp, 3].
64 ///
65 /// \param inp_features The input features with shape
66 /// [num_inp, in_channels].
67 ///
68 /// \param inp_importance Optional importance for each input point with
69 /// shape [num_inp]. Set to null to disable.
70 ///
71 /// \param neighbors_index_size The size of the neighbors_index array.
72 ///
73 /// \param neighbors_index The array with lists of neighbors for each
74 /// output point. The start and end of each sublist is defined by
75 /// \p neighbors_row_splits.
76 ///
77 /// \param neighbors_importance Optional importance for each entry in
78 /// \p neighbors_index. Set to null to disable.
79 ///
80 /// \param neighbors_row_splits The prefix sum which defines the start
81 /// and end of the sublists in \p neighbors_index. The size of the
82 /// array is \p num_out + 1.
83 ///
84 /// \param extents The spatial extents of the filter in coordinate units.
85 /// extents can be a scalar or a 1D array of shape [num_out] or a
86 /// 2D array of shape [num_out,3]. The shape depends on
87 /// \p individual_extent and \p isotropic_extent.
88 ///
89 /// \param offsets A single 3D vector used in the filter coordinate
90 /// computation. The shape is [3].
91 ///
92 /// \param interpolation The interpolation mode. Either LINEAR or
93 /// NEAREST_NEIGHBOR.
94 ///
95 /// \param coordinate_mapping The coordinate mapping function. One of
96 /// IDENTITY, BALL_TO_CUBE_RADIAL, BALL_TO_CUBE_VOLUME_PRESERVING.
97 ///
98 /// \param align_corners If true then the voxel centers of the outer voxels
99 /// of the filter array are mapped to the boundary of the filter shape.
100 /// If false then the boundary of the filter array is mapped to the
101 /// boundary of the filter shape.
102 ///
103 /// \param individual_extent If true each output point has an individual
104 /// extent.
105 ///
106 /// \param isotropic_extent If true each then the extent is isotropic for
107 /// each output point.
108 ///
109 /// \param normalize If true then the output features are normalized either
110 /// by the number of points (neighbors_importance is null) or by the sum
111 /// of the respective values in neighbors_importance.
112 ///
113 template <class TFeat, class TOut, class TReal, class TIndex>
114 void CConvBackpropFilterCUDA(const cudaStream_t& stream,
115  void* temp,
116  size_t& temp_size,
117  size_t& max_temp_size,
118  int texture_alignment,
119  TOut* filter_backprop,
120  const std::vector<int>& filter_dims,
121  TIndex num_out,
122  const TReal* out_positions,
123  TIndex num_inp,
124  const TReal* inp_positions,
125  const TFeat* inp_features,
126  const TFeat* inp_importance,
127  size_t neighbors_index_size,
128  const TIndex* neighbors_index,
129  const TFeat* neighbors_importance,
130  const int64_t* neighbors_row_splits,
131  const TReal* extents,
132  const TReal* offsets,
133  const TFeat* out_features_gradient,
134  InterpolationMode interpolation,
135  CoordinateMapping coordinate_mapping,
136  bool align_corners,
137  bool individual_extent,
138  bool isotropic_extent,
139  bool normalize) {
140  const bool get_temp_size = !temp;
141 
142  if (get_temp_size) {
143  temp = (char*)1; // worst case alignment
144  temp_size = std::numeric_limits<int64_t>::max();
145  }
146 
147  MemoryAllocation mem_temp(temp, temp_size, texture_alignment);
148 
149  const int in_channels = filter_dims[filter_dims.size() - 2];
150  const int out_channels = filter_dims[filter_dims.size() - 1];
151 
152  int spatial_filter_size = 1;
153  for (int i = 0; i < 3; ++i) spatial_filter_size *= filter_dims[i];
154 
155  // this defines how much temporary storage we need at least
156  // we want to allocate memory for at least 32 output points.
157  const size_t min_num_cols_per_run = std::min(size_t(num_out), size_t(32));
158  const size_t max_num_cols_per_run = num_out;
159  const size_t bytes_per_column =
160  sizeof(TFeat) * (spatial_filter_size * in_channels);
161  const size_t min_temp_size_bytes = min_num_cols_per_run * bytes_per_column;
162  const size_t max_temp_size_bytes = max_num_cols_per_run * bytes_per_column;
163 
164  if (get_temp_size) {
165  std::pair<char*, size_t> tmp =
166  mem_temp.Alloc<char>(min_temp_size_bytes);
167  temp_size = mem_temp.MaxUsed();
168  mem_temp.Free(tmp);
169  mem_temp.Alloc<char>(max_temp_size_bytes);
170  max_temp_size = mem_temp.MaxUsed();
171  return;
172  }
173 
174  // Request segment using all of the temporary memory
175  std::pair<void*, size_t> mem_columns = mem_temp.AllocLargestSegment();
176 
177  if (mem_columns.second < min_temp_size_bytes) {
178  std::stringstream ss;
179  ss << "temp is too small " << mem_columns.second
180  << " bytes. Expected at least " << min_temp_size_bytes << " bytes\n";
181  throw std::runtime_error(ss.str());
182  }
183 
184  // init output
185  cudaMemsetAsync(
186  filter_backprop, 0,
187  sizeof(TOut) * spatial_filter_size * in_channels * out_channels,
188  stream);
189 
190  size_t num_cols_per_run =
191  std::min(mem_columns.second / bytes_per_column, size_t(num_out));
192 
193  typedef cutlass::gemm::SgemmTraits<
194  cutlass::MatrixLayout::kColumnMajor, // layout of A matrix
195  cutlass::MatrixLayout::kRowMajor, // layout of B matrix
196  cutlass::Shape<8, 64, 64> // threadblock tile size
197  >
198  GemmTraits;
199 
200  typedef cutlass::gemm::Gemm<GemmTraits> Gemm;
201 
202  TFeat* columns = (TFeat*)mem_columns.first;
203 
204  // if we cannot process all data at once we need multiple runs
205  size_t num_runs = DivUp(num_out, num_cols_per_run);
206  for (size_t run_i = 0; run_i < num_runs; ++run_i) {
207  const TIndex begin_idx = run_i * num_cols_per_run;
208  const TIndex end_idx =
209  std::min(size_t(num_out), (run_i + 1) * num_cols_per_run);
210  const size_t num_cols_this_run = end_idx - begin_idx;
211 
212  FillColumn<TFeat, TReal, TIndex>(
213  stream, columns, in_channels, begin_idx, end_idx, num_out,
214  out_positions, num_inp, inp_positions, inp_features,
215  inp_importance, neighbors_index_size, neighbors_index,
216  neighbors_importance, neighbors_row_splits, extents, offsets,
217  filter_dims, interpolation, coordinate_mapping, align_corners,
218  individual_extent, isotropic_extent, normalize);
219 
220  typename Gemm::Params params;
221  // C is MxN
222  // B is KxN
223  // A is MxK
224  int m = out_channels;
225  int k = num_cols_this_run;
226  int n = spatial_filter_size * in_channels;
227  float alpha = 1;
228  const float* const A = out_features_gradient +
229  (run_i * num_cols_per_run * out_channels);
230  int lda = m;
231  const float* const B = columns;
232  int ldb = n;
233  float beta = 1;
234  float* C = filter_backprop;
235  int ldc = m;
236 
237  int result = params.initialize(m, // GEMM M dimension
238  n, // GEMM N dimension
239  k, // GEMM K dimension
240  alpha, // scalar alpha
241  A, // matrix A operand
242  lda,
243  B, // matrix B operand
244  ldb,
245  beta, // scalar beta
246  C, // source matrix C
247  ldc,
248  C, // destination matrix C
249  ldc);
250 
251  if (result) {
252  throw std::runtime_error(
253  "Failed to initialize CUTLASS Gemm::Params object.");
254  }
255 
256  Gemm::launch(params, stream);
257  }
258 }
259 
260 } // namespace impl
261 } // namespace ml
262 } // namespace cloudViewer