forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReduceOpsKernel.cpp
439 lines (401 loc) · 15.9 KB
/
ReduceOpsKernel.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#include <numeric>
#include <iterator>
#include <algorithm>
#include <ATen/Dispatch.h>
#include <ATen/cpu/vec/vec.h>
#include <ATen/native/ReduceOps.h>
#include <ATen/native/ReduceOpsUtils.h>
#include <ATen/native/Resize.h>
#include <ATen/native/TensorIterator.h>
#include <ATen/native/SharedReduceOps.h>
#include <ATen/native/ReduceOpsUtils.h>
#include <ATen/native/cpu/Reduce.h>
#include <c10/util/Optional.h>
#include <ATen/AccumulateType.h>
namespace at { namespace native { namespace {
using namespace vec;
template <typename scalar_t, typename func_t>
static inline void cpu_cum_base_kernel(Tensor& result,
const Tensor& self,
int64_t dim,
const func_t& f,
scalar_t init_val) {
if (result.sizes() != self.sizes()) {
at::native::resize_output(result, self.sizes());
}
if (self.numel() == 0) {
return;
}
const auto input_ndim = self.dim();
if (input_ndim == 0) {
result.fill_(self);
return;
}
// TODO This probably should be using at::native::make_reduction
auto iter = TensorIteratorConfig()
.check_all_same_dtype(false)
.resize_outputs(false)
// NOLINTNEXTLINE(bugprone-argument-comment)
.declare_static_shape(self.sizes(), /*squash_dim=*/dim)
.add_borrowed_output(result)
.add_borrowed_input(self)
.build();
auto result_dim_stride = ensure_nonempty_stride(result, dim);
auto self_dim_stride = ensure_nonempty_stride(self, dim);
auto loop = [&](char** data, const int64_t* strides, int64_t n) {
auto* result_data_bytes = data[0];
const auto* self_data_bytes = data[1];
for (int64_t i = 0; i < n; ++i) {
f(
(scalar_t*)result_data_bytes, result_dim_stride,
(scalar_t*)self_data_bytes, self_dim_stride, init_val
);
result_data_bytes += strides[0];
self_data_bytes += strides[1];
}
};
iter.for_each(loop);
}
static void cumsum_cpu_kernel(Tensor& result, const Tensor& self, int64_t dim) {
auto wrap_dim = maybe_wrap_dim(dim, self.dim());
int64_t self_dim_size = ensure_nonempty_size(self, wrap_dim);
AT_DISPATCH_ALL_TYPES_AND_COMPLEX(self.scalar_type(), "cumsum_out_cpu", [&] {
cpu_cum_base_kernel<scalar_t>(result, self, wrap_dim, [&] (
scalar_t* result_data, auto result_dim_stride,
const scalar_t* self_data, auto self_dim_stride, scalar_t init_val) {
// NOLINTNEXTLINE(bugprone-signed-char-misuse)
auto cum_number = (at::acc_type<scalar_t, false>)init_val;
for (int64_t i = 0; i < self_dim_size; ++i) {
cum_number += self_data[i * self_dim_stride];
result_data[i * result_dim_stride] = (scalar_t)cum_number;
}
}, /*init_val=*/ 0
);
});
}
static void cumprod_cpu_kernel(Tensor& result, const Tensor& self, int64_t dim) {
auto wrap_dim = maybe_wrap_dim(dim, self.dim());
int64_t self_dim_size = ensure_nonempty_size(self, wrap_dim);
AT_DISPATCH_ALL_TYPES_AND_COMPLEX(self.scalar_type(), "cumprod_out_cpu", [&] {
cpu_cum_base_kernel<scalar_t>(result, self, wrap_dim, [&] (
scalar_t* result_data, auto result_dim_stride,
const scalar_t* self_data, auto self_dim_stride, scalar_t init_val) {
// NOLINTNEXTLINE(bugprone-signed-char-misuse)
auto cum_number = (at::acc_type<scalar_t, false>)init_val;
for (int64_t i = 0; i < self_dim_size; ++i) {
cum_number *= self_data[i * self_dim_stride];
result_data[i * result_dim_stride] = (scalar_t)cum_number;
}
}, /*init_val=*/ 1
);
});
}
static void logcumsumexp_cpu_kernel(Tensor& result, const Tensor& self, int64_t dim) {
auto wrap_dim = maybe_wrap_dim(dim, self.dim());
int64_t self_dim_size = ensure_nonempty_size(self, wrap_dim);
AT_DISPATCH_FLOATING_TYPES(self.scalar_type(), "logcumsumexp_out_cpu", [&] {
cpu_cum_base_kernel<scalar_t>(result, self, wrap_dim, [&] (
scalar_t* result_data, auto result_dim_stride,
const scalar_t* self_data, auto self_dim_stride, scalar_t init_val) {
scalar_t cum_number = (at::acc_type<scalar_t, false>)init_val;
for (int64_t i = 0; i < self_dim_size; ++i) {
scalar_t x = self_data[i * self_dim_stride];
// Reference : https://www.tensorflow.org/api_docs/python/tf/math/cumulative_logsumexp
auto log_add_exp = [](scalar_t x, scalar_t y) -> scalar_t {
scalar_t min = std::isnan(y) ? y : std::min(x,y); //std::min returns first arg if one of the args is nan
scalar_t max = std::isnan(y) ? y : std::max(x,y); //std::max returns first arg if one of the args is nan
if (min != max || std::isfinite(min)) {
// nan will be propagated here
return std::log1p(std::exp(min - max)) + max;
} else {
// special case to correctly handle infinite cases
return x;
}
};
cum_number = log_add_exp(x, cum_number);
result_data[i * result_dim_stride] = static_cast<scalar_t>(cum_number);
}
}, /*init_val=*/ -std::numeric_limits<scalar_t>::infinity()
);
});
}
// TODO: Implement `nansum` similar to the stable `sum`
// implementation in cpu/SumKernel.cpp
static void nansum_kernel_impl(TensorIterator& iter) {
if (iter.dtype() == ScalarType::Half){
binary_kernel_reduce(iter, NanSumOps<float, c10::Half>{}, float{0});
} else {
AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "nansum_cpu", [&] {
binary_kernel_reduce(iter, NanSumOps<scalar_t, scalar_t>{}, scalar_t{0});
});
}
}
static void mean_kernel_impl(TensorIterator& iter) {
AT_DISPATCH_ALL_TYPES_AND_COMPLEX(iter.dtype(), "mean_cpu", [&] {
scalar_t factor = scalar_t(iter.num_output_elements()) / scalar_t(iter.numel());
binary_kernel_reduce(
iter,
MeanOps<scalar_t, scalar_t> {factor},
scalar_t(0)
);
});
}
static void std_var_kernel_impl(TensorIterator& iter, int64_t correction, bool take_sqrt) {
AT_DISPATCH_FLOATING_TYPES_AND_HALF(iter.dtype(), "std_cpu", [&] {
binary_kernel_reduce(
iter,
WelfordOps<
scalar_t,
double,
int64_t,
double,
std::tuple<scalar_t, scalar_t>>{correction, take_sqrt},
WelfordData<double, int64_t, double>());
});
}
static void prod_kernel_impl(TensorIterator& iter) {
// Workaround for the error: '*' in boolean context, suggest '&&' instead [-Werror=int-in-bool-context]
if (iter.dtype() == ScalarType::Bool) {
using scalar_t = bool;
binary_kernel_reduce_vec(
iter,
[=](scalar_t a, scalar_t b) -> scalar_t { return a && b; },
[=](Vectorized<scalar_t> a, Vectorized<scalar_t> b) { return a && b; },
// NOLINTNEXTLINE(bugprone-argument-comment)
/*identity=*/1);
} else {
AT_DISPATCH_ALL_TYPES_AND_COMPLEX(iter.dtype(), "prod_cpu", [&] {
binary_kernel_reduce_vec(
iter,
[=](scalar_t a, scalar_t b) -> scalar_t { return a * b; },
[=](Vectorized <scalar_t> a, Vectorized <scalar_t> b) { return a * b; },
// NOLINTNEXTLINE(bugprone-argument-comment)
/*identity=*/1);
});
}
}
static void norm_kernel_tensor_iterator_impl(
TensorIterator& iter,
const Scalar& p) {
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
float val;
if (p.isIntegral(false)) {
val = p.to<int64_t>();
} else if (p.isFloatingPoint()) {
// NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions)
val = p.to<double>();
} else {
AT_ERROR("norm_kernel_tensor_iterator_impl expects norm to be integer or float");
}
// In the dispatch code blocks below, reduction kernels accumulate results as
// the type `acc_t`. When `scalar_t` is complex, `acc_t` is the downgraded
// real number type. Otherwise, `acc_t` and `scalar_t` are the same type.
if (val == 0) {
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kHalf, kBFloat16, iter.input_dtype(), "norm_cpu", [&] {
using acc_t = typename scalar_value_type<scalar_t>::type;
binary_kernel_reduce(
iter,
NormZeroOps<scalar_t, acc_t>(),
acc_t(0)
);
});
} else if (val == 1) {
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kHalf, kBFloat16, iter.input_dtype(), "norm_cpu", [&] {
using acc_t = typename scalar_value_type<scalar_t>::type;
binary_kernel_reduce(
iter,
NormOneOps<scalar_t, acc_t>(),
acc_t(0)
);
});
} else if (val == 2) {
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kHalf, kBFloat16, iter.input_dtype(), "norm_cpu", [&] {
using acc_t = typename scalar_value_type<scalar_t>::type;
binary_kernel_reduce(
iter,
NormTwoOps<scalar_t, acc_t>(),
acc_t(0)
);
});
} else if (val == INFINITY) {
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kHalf, kBFloat16, iter.input_dtype(), "norm_cpu", [&] {
using acc_t = typename scalar_value_type<scalar_t>::type;
binary_kernel_reduce(
iter,
AbsMaxOps<scalar_t, acc_t>(),
acc_t(0)
);
});
} else if (val == -INFINITY) {
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kHalf, kBFloat16, iter.input_dtype(), "norm_cpu", [&] {
using acc_t = typename scalar_value_type<scalar_t>::type;
binary_kernel_reduce(
iter,
AbsMinOps<scalar_t, acc_t>(),
std::numeric_limits<acc_t>::max()
);
});
} else {
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kHalf, kBFloat16, iter.input_dtype(), "norm_cpu", [&] {
using acc_t = typename scalar_value_type<scalar_t>::type;
binary_kernel_reduce(
iter,
NormOps<scalar_t, acc_t> { acc_t(val) },
acc_t(0)
);
});
}
// For complex outputs, the above kernels do not touch the imaginary values,
// so we must zero them out
if (isComplexType(iter.output().scalar_type())) {
at::imag(iter.output()).zero_();
}
}
static void and_kernel_impl(TensorIterator& iter) {
if (iter.dtype() == ScalarType::Byte) {
// Refer [all, any : uint8 compatibility]
binary_kernel_reduce_vec(
iter,
[=](uint8_t a, uint8_t b) -> uint8_t { return (a && b) ? 1 : 0; },
[=](Vectorized<uint8_t> a, Vectorized<uint8_t> b) {
Vectorized<uint8_t> c = Vectorized<uint8_t>();
for (decltype(c.size()) i = 0; i != Vectorized<uint8_t>::size(); i++) {
c[i] = (a[i] && b[i]) ? 1 : 0;
}
return c;
},
/*ident=*/true);
} else {
binary_kernel_reduce_vec(
iter,
[=](bool a, bool b) -> bool { return a && b; },
[=](Vectorized<bool> a, Vectorized<bool> b) {
// Adding the implementation here instead of in vec256_base to avoid
// return value inconsistency. Other comparison operators in
// vec256_base return -1/0 (all bit 1 / all bit 0) as true/false to
// follow the AVX2 convention. This would be convenient when combined
// with other vectorized operations. For example, one can use the
// logical operation results as a mask for a bit operation to
// retrieve/reset multiple elements in a vector.
//
// In this method, users would expect, e.g., all(), to return 1/0 as
// true/false.
Vectorized<bool> c = Vectorized<bool>();
for (decltype(c.size()) i = 0; i != Vectorized<bool>::size(); i++) {
c[i] = a[i] && b[i];
}
return c;
},
/*ident=*/true);
}
}
static void or_kernel_impl(TensorIterator& iter) {
if (iter.dtype() == ScalarType::Byte) {
// Refer [all, any : uint8 compatibility]
binary_kernel_reduce_vec(
iter,
[=](uint8_t a, uint8_t b) -> uint8_t { return (a || b) ? 1 : 0; },
[=](Vectorized<uint8_t> a, Vectorized<uint8_t> b) {
Vectorized<uint8_t> c = Vectorized<uint8_t>();
for (decltype(c.size()) i = 0; i != Vectorized<uint8_t>::size(); i++) {
c[i] = (a[i] || b[i]) ? 1 : 0;
}
return c;
},
/*ident=*/false);
} else {
binary_kernel_reduce_vec(
iter,
[=](bool a, bool b) -> bool { return a || b; },
[=](Vectorized<bool> a, Vectorized<bool> b) {
Vectorized<bool> c = Vectorized<bool>();
for (decltype(c.size()) i = 0; i != Vectorized<bool>::size(); i++) {
c[i] = a[i] || b[i];
}
return c;
},
/*ident=*/false);
}
}
template<typename scalar_t>
struct MinValuesOps: public at::native::MinOps<scalar_t> {
using arg_t = typename MinOps<scalar_t>::arg_t;
static scalar_t project(arg_t arg) {
return arg.first;
}
};
static void min_values_kernel_impl(TensorIterator& iter) {
if (iter.dtype() == kLong) {
// This case is special because of Vectorized<int64_t> does not
// handle upper_bound<int64_t>().
// See: https://github.com/pytorch/pytorch/issues/43254
using scalar_t = int64_t;
binary_kernel_reduce(
iter,
MinValuesOps<scalar_t>{},
std::pair<scalar_t, int64_t>(upper_bound<scalar_t>(), -1));
return;
}
AT_DISPATCH_ALL_TYPES_AND3(kBFloat16, kHalf, kBool, iter.dtype(), "min_values_cpu", [&iter] {
binary_kernel_reduce_vec(
iter,
[](scalar_t a, scalar_t b) -> scalar_t { return min_impl(a, b); },
[](Vectorized<scalar_t> a, Vectorized<scalar_t> b) { return minimum(a, b); },
static_cast<double>(upper_bound<scalar_t>()));
});
}
static void max_values_kernel_impl(TensorIterator& iter) {
AT_DISPATCH_ALL_TYPES_AND3(kBFloat16, kHalf, kBool, iter.dtype(), "max_values_cpu", [&iter] {
binary_kernel_reduce_vec(
iter,
[](scalar_t a, scalar_t b) -> scalar_t { return max_impl(a, b); },
[](Vectorized<scalar_t> a, Vectorized<scalar_t> b) { return maximum(a, b); },
lower_bound<scalar_t>());
});
}
static void argmax_kernel_impl(TensorIterator &iter) {
AT_DISPATCH_ALL_TYPES_AND2(kHalf, kBFloat16, iter.dtype(1), "argmax_cpu", [&] {
binary_kernel_reduce(
iter,
ArgMaxOps<scalar_t>{},
std::pair<scalar_t, int64_t>(lower_bound<scalar_t>(), 0));
});
}
static void argmin_kernel_impl(TensorIterator &iter) {
AT_DISPATCH_ALL_TYPES_AND2(kHalf, kBFloat16, iter.dtype(1), "argmin_cpu", [&] {
binary_kernel_reduce(
iter,
ArgMinOps<scalar_t>{},
std::pair<scalar_t, int64_t>(upper_bound<scalar_t>(), 0));
});
}
} // anonymous namespace
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(nansum_stub, &nansum_kernel_impl);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(std_var_stub, &std_var_kernel_impl);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(prod_stub, &prod_kernel_impl);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(mean_stub, &mean_kernel_impl);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(norm_stub, &norm_kernel_tensor_iterator_impl);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(and_stub, &and_kernel_impl);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(or_stub, &or_kernel_impl);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(min_values_stub, &min_values_kernel_impl);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(max_values_stub, &max_values_kernel_impl);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(argmax_stub, &argmax_kernel_impl);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(argmin_stub, &argmin_kernel_impl);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(cumprod_stub, &cumprod_cpu_kernel);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(cumsum_stub, &cumsum_cpu_kernel);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(logcumsumexp_stub, &logcumsumexp_cpu_kernel);
}} // namespace at::native