forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TensorCompareKernel.cpp
439 lines (393 loc) · 15.2 KB
/
TensorCompareKernel.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 <ATen/native/TensorCompare.h>
#include <numeric>
#include <iterator>
#include <algorithm>
#include <utility>
#include <vector>
#include <ATen/Dispatch.h>
#include <ATen/Parallel.h>
#include <ATen/NumericUtils.h>
#include <c10/util/Optional.h>
#include <ATen/native/TensorIterator.h>
#include <ATen/native/ReduceOpsUtils.h>
#include <ATen/native/Resize.h>
#include <ATen/native/cpu/Loops.h>
namespace at { namespace native { namespace {
template <typename scalar_t, typename scalar_t_2 = int64_t, typename loop1d_t>
static inline void compare_base_kernel_core(
Tensor& result1,
Tensor& result2,
const Tensor& self,
int64_t dim,
bool keepdim,
const loop1d_t& loop) {
auto self_sizes = ensure_nonempty_vec(self.sizes().vec());
self_sizes[dim] = 1;
// result1 and result2 may be a empty tensor, if not,
// reshape them as self dims
if (!keepdim) {
if (result1.ndimension() >= dim) {
result1.unsqueeze_(dim);
}
if (result2.ndimension() >= dim) {
result2.unsqueeze_(dim);
}
}
at::native::resize_output(result1, self_sizes);
at::native::resize_output(result2, self_sizes);
auto iter = TensorIteratorConfig()
.check_all_same_dtype(false)
.resize_outputs(false)
.declare_static_shape(self.sizes(), /*squash_dims=*/dim)
.add_output(result1)
.add_output(result2)
.add_input(self)
.build();
iter.for_each(loop, /* grain_size */ 1);
if (!keepdim) {
result1.squeeze_(dim);
result2.squeeze_(dim);
}
}
template <typename scalar_t, typename scalar_t_2=int64_t, typename func_t>
static inline void compare_base_kernel(Tensor& result1, Tensor& result2,
const Tensor& self,
int64_t dim,
bool keepdim,
const func_t& f) {
auto self_dim_stride = ensure_nonempty_stride(self, dim);
auto loop = [&](char** data, const int64_t* strides, int64_t n) {
auto* result1_data_bytes = data[0];
auto* result2_data_bytes = data[1];
const auto* self_data_bytes = data[2];
for (int64_t i = 0; i < n; ++i) {
f((scalar_t*)result1_data_bytes,
(scalar_t_2*)result2_data_bytes,
(scalar_t*)self_data_bytes,
self_dim_stride);
result1_data_bytes += strides[0];
result2_data_bytes += strides[1];
self_data_bytes += strides[2];
}
};
compare_base_kernel_core<scalar_t, scalar_t_2>(
result1, result2, self, dim, keepdim, loop);
}
static void min_kernel_impl(
Tensor& result,
Tensor& indice,
const Tensor& self,
int64_t dim,
bool keepdim) {
auto wrap_dim = maybe_wrap_dim(dim, self.dim());
int64_t self_dim_size = ensure_nonempty_size(self, wrap_dim);
TORCH_CHECK(result.scalar_type() == self.scalar_type() && indice.scalar_type() == kLong,
"Expect dtype ", self.scalar_type(), "and torch.long, but got ", result.scalar_type(), "and", indice.scalar_type());
AT_DISPATCH_ALL_TYPES_AND3(ScalarType::Half, ScalarType::BFloat16, ScalarType::Bool, self.scalar_type(), "min_cpu", [&] {
compare_base_kernel<scalar_t>(result, indice, self, wrap_dim, keepdim, [&] (
scalar_t* result_data, int64_t* indice_data,
const scalar_t* self_data, auto self_dim_stride) {
using value_t = typename c10::scalar_value_type<scalar_t>::type;
value_t (*zabs_)(scalar_t) = zabs<scalar_t, value_t>;
scalar_t min_number = self_data[0];
int64_t index = 0;
for (int64_t i = 0; i < self_dim_size; ++i) {
scalar_t value = self_data[i * self_dim_stride];
if (!(zabs_(value) >= zabs_(min_number))) {
min_number = value;
index = i;
if (_isnan<scalar_t>(value)) {
break;
}
}
}
*result_data = min_number;
*indice_data = index;
}
);
});
}
static void max_kernel_impl(
Tensor& result,
Tensor& indice,
const Tensor& self,
int64_t dim,
bool keepdim) {
auto wrap_dim = maybe_wrap_dim(dim, self.dim());
int64_t self_dim_size = ensure_nonempty_size(self, wrap_dim);
TORCH_CHECK(result.scalar_type() == self.scalar_type() && indice.scalar_type() == kLong,
"Expect dtype ", self.scalar_type(), "and torch.long, but got ", result.scalar_type(), "and", indice.scalar_type());
AT_DISPATCH_ALL_TYPES_AND3(ScalarType::Half, ScalarType::BFloat16, ScalarType::Bool, self.scalar_type(), "max_cpu", [&] {
compare_base_kernel<scalar_t>(result, indice, self, wrap_dim, keepdim, [&] (
scalar_t* result_data, int64_t* indice_data,
const scalar_t* self_data, auto self_dim_stride) {
using value_t = typename c10::scalar_value_type<scalar_t>::type;
value_t (*zabs_)(scalar_t) = zabs<scalar_t, value_t>;
scalar_t max_number = self_data[0];
int64_t index = 0;
for (int64_t i = 0; i < self_dim_size; ++i) {
scalar_t value = self_data[i * self_dim_stride];
if (!(zabs_(value) <= zabs_(max_number))) {
max_number = value;
index = i;
if (_isnan<scalar_t>(value)) {
break;
}
}
}
*result_data = max_number;
*indice_data = index;
}
);
});
}
static void _aminmax_kernel_impl(
Tensor& min_result,
Tensor& max_result,
const Tensor& self,
int64_t dim,
bool keepdim) {
auto wrap_dim = maybe_wrap_dim(dim, self.dim());
int64_t self_dim_size = ensure_nonempty_size(self, wrap_dim);
TORCH_CHECK(min_result.scalar_type() == self.scalar_type() && max_result.scalar_type() == self.scalar_type(),
"Expect min and max dtype ", self.scalar_type(),
" but got ", min_result.scalar_type(), " and ", max_result.scalar_type());
AT_DISPATCH_ALL_TYPES_AND(ScalarType::Bool, self.scalar_type(), "_aminmax_cpu", [&] {
compare_base_kernel<scalar_t, scalar_t>(min_result, max_result, self, wrap_dim, keepdim, [&] (
scalar_t* min_result_data, scalar_t* max_result_data,
const scalar_t* self_data, auto self_dim_stride) {
scalar_t min_number = self_data[0];
scalar_t max_number = self_data[0];
for (int64_t i = 0; i < self_dim_size; ++i) {
scalar_t value = self_data[i * self_dim_stride];
// note: comparison is written this way to handle NaN correctly
if (!(value >= min_number)) {
min_number = value;
if (_isnan<scalar_t>(value)) {
max_number = value;
break;
}
} else if (!(value <= max_number)) {
max_number = value;
}
}
*min_result_data = min_number;
*max_result_data = max_number;
}
);
});
}
static void where_kernel_impl(TensorIterator &iter, ScalarType condition_type) {
AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(at::ScalarType::Half, at::ScalarType::BFloat16, at::ScalarType::Bool,
iter.dtype(), "where_cpu", [&] {
if (condition_type == at::ScalarType::Byte) {
cpu_kernel(
iter,
[=](uint8_t cond_val, scalar_t self_val, scalar_t other_val) -> scalar_t {
return cond_val ? self_val : other_val;
});
} else {
cpu_kernel(
iter,
[=](bool cond_val, scalar_t self_val, scalar_t other_val) -> scalar_t {
return cond_val ? self_val : other_val;
});
}
});
}
static void isposinf_kernel_impl(TensorIterator& iter) {
AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.input_dtype(), "isposinf_cpu", [&]() {
cpu_kernel(iter, [](scalar_t a) -> bool { return a == std::numeric_limits<scalar_t>::infinity(); });
});
}
static void isneginf_kernel_impl(TensorIterator& iter) {
AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.input_dtype(), "isneginf_cpu", [&]() {
cpu_kernel(iter, [](scalar_t a) -> bool { return a == -std::numeric_limits<scalar_t>::infinity(); });
});
}
static void mode_kernel_impl(
Tensor& values,
Tensor& indices,
const Tensor& self,
int64_t dim,
bool keepdim) {
auto self_dim_size = ensure_nonempty_size(self, dim);
auto self_dim_stride = ensure_nonempty_stride(self, dim);
AT_DISPATCH_ALL_TYPES_AND3(
kHalf, kBFloat16, kBool, self.scalar_type(), "mode_cpu", [&] {
auto loop = [&](char** data, const int64_t* strides, int64_t n) {
auto* values_data_bytes = data[0];
auto* indices_data_bytes = data[1];
const auto* self_data_bytes = data[2];
std::vector<std::pair<scalar_t, int64_t>> elements(self_dim_size);
for (int64_t k = 0; k < n; ++k) {
scalar_t* values_data = (scalar_t*)values_data_bytes;
int64_t* indices_data = (int64_t*)indices_data_bytes;
const scalar_t* self_data = (scalar_t*)self_data_bytes;
scalar_t mode = 0;
int64_t modei = 0;
int64_t temp_freq = 0;
int64_t max_freq = 0;
for (int64_t i = 0; i < self_dim_size; i++) {
elements[i] = std::make_pair(self_data[i * self_dim_stride], i);
}
// Even though, theoretically, we don't need to specify this lambda
// (it's basically the same as std::less), doing so degrades
// performance. That is because its implementation for std::pair
// uses 3 comparisons.
std::sort(
elements.begin(),
elements.end(),
[=](const auto& i, const auto& j) {
return i.first < j.first;
});
for (int64_t i = 0; i < self_dim_size; i++) {
temp_freq++;
if ((i == self_dim_size - 1) ||
(elements[i].first != elements[i + 1].first)) {
if (temp_freq > max_freq) {
mode = elements[i].first;
modei = elements[i].second;
max_freq = temp_freq;
}
temp_freq = 0;
}
}
*values_data = mode;
*indices_data = modei;
values_data_bytes += strides[0];
indices_data_bytes += strides[1];
self_data_bytes += strides[2];
}
};
compare_base_kernel_core<scalar_t>(
values, indices, self, dim, keepdim, loop);
});
}
// Default brute force implementation of isin(). Used when the number of test elements is small.
// Iterates through each element and checks it against each test element.
static void isin_default_kernel_cpu(
const Tensor& elements,
const Tensor& test_elements,
bool invert,
const Tensor& out) {
// Since test elements is not an input of the TensorIterator, type promotion
// must be done manually.
ScalarType common_type = at::result_type(elements, test_elements);
Tensor test_elements_flat = test_elements.to(common_type).ravel();
Tensor promoted_elements = elements.to(common_type);
auto iter = TensorIteratorConfig()
.add_output(out)
.add_input(promoted_elements)
.check_all_same_dtype(false)
.build();
// Dispatch based on promoted type.
AT_DISPATCH_ALL_TYPES(iter.dtype(1), "isin_default_cpu", [&]() {
cpu_kernel(iter, [&](scalar_t element_val) -> bool {
const auto* test_element_data = reinterpret_cast<scalar_t*>(test_elements_flat.data_ptr());
for (auto j = 0; j < test_elements_flat.numel(); ++j) {
if (element_val == test_element_data[j]) {
return !invert;
}
}
return invert;
});
});
}
static void clamp_kernel_impl(TensorIterator& iter) {
AT_DISPATCH_ALL_TYPES_AND(kBFloat16, iter.common_dtype(), "clamp_cpu", [&]() {
cpu_kernel_vec(iter,
[](scalar_t a, scalar_t min, scalar_t max) -> scalar_t {
return std::min(std::max(a, min), max);
},
[](Vectorized<scalar_t> a, Vectorized<scalar_t> min, Vectorized<scalar_t> max) {
return vec::clamp(a, min, max);
});
});
}
static void clamp_scalar_kernel_impl(TensorIterator& iter, Scalar min_, Scalar max_) {
AT_DISPATCH_ALL_TYPES_AND(kBFloat16, iter.common_dtype(), "clamp_scalar_cpu", [&]() {
const auto min = min_.to<scalar_t>();
const auto max = max_.to<scalar_t>();
const Vectorized<scalar_t> min_vec(min);
const Vectorized<scalar_t> max_vec(max);
cpu_kernel_vec(iter,
[=](scalar_t a) -> scalar_t {
return std::min(std::max(a, min), max);
},
[=](Vectorized<scalar_t> a) {
return vec::clamp(a, min_vec, max_vec);
});
});
}
static void clamp_max_kernel_impl(TensorIterator& iter) {
AT_DISPATCH_ALL_TYPES_AND(kBFloat16, iter.common_dtype(), "clamp_max_cpu", [&]() {
cpu_kernel_vec(iter,
[](scalar_t a, scalar_t max) -> scalar_t {
return std::min(a, max);
},
[](Vectorized<scalar_t> a, Vectorized<scalar_t> max) {
return vec::clamp_max(a, max);
});
});
}
static void clamp_max_scalar_kernel_impl(TensorIterator& iter, Scalar max_) {
AT_DISPATCH_ALL_TYPES_AND(kBFloat16, iter.common_dtype(), "clamp_max_scalar_cpu", [&]() {
const auto max = max_.to<scalar_t>();
const Vectorized<scalar_t> max_vec(max);
cpu_kernel_vec(iter,
[=](scalar_t a) -> scalar_t {
return std::min(a, max);
},
[=](Vectorized<scalar_t> a) {
return vec::clamp_max(a, max_vec);
});
});
}
static void clamp_min_kernel_impl(TensorIterator& iter) {
AT_DISPATCH_ALL_TYPES_AND(kBFloat16, iter.common_dtype(), "clamp_min_cpu", [&]() {
cpu_kernel_vec(iter,
[](scalar_t a, scalar_t min) -> scalar_t {
return std::max(a, min);
},
[](Vectorized<scalar_t> a, Vectorized<scalar_t> min) {
return vec::clamp_min(a, min);
});
});
}
static void clamp_min_scalar_kernel_impl(TensorIterator& iter, Scalar min_) {
AT_DISPATCH_ALL_TYPES_AND(kBFloat16, iter.common_dtype(), "clamp_min_cpu", [&]() {
const auto min = min_.to<scalar_t>();
const Vectorized<scalar_t> min_vec(min);
cpu_kernel_vec(iter,
[=](scalar_t a) -> scalar_t {
return std::max(a, min);
},
[=](Vectorized<scalar_t> a) {
return vec::clamp_min(a, min_vec);
});
});
}
} // anonymous namespace
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(max_stub, &max_kernel_impl);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(min_stub, &min_kernel_impl);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(_aminmax_stub, &_aminmax_kernel_impl);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(where_kernel, &where_kernel_impl);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(isposinf_stub, &isposinf_kernel_impl);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(isneginf_stub, &isneginf_kernel_impl);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_DISPATCH(mode_stub, &mode_kernel_impl);
REGISTER_DISPATCH(clamp_stub, &clamp_kernel_impl);
REGISTER_DISPATCH(clamp_min_stub, &clamp_min_kernel_impl);
REGISTER_DISPATCH(clamp_max_stub, &clamp_max_kernel_impl);
REGISTER_DISPATCH(clamp_scalar_stub, &clamp_scalar_kernel_impl);
REGISTER_DISPATCH(clamp_min_scalar_stub, &clamp_min_scalar_kernel_impl);
REGISTER_DISPATCH(clamp_max_scalar_stub, &clamp_max_scalar_kernel_impl);
REGISTER_DISPATCH(isin_default_stub, &isin_default_kernel_cpu);
}} // namespace at::native