-
Notifications
You must be signed in to change notification settings - Fork 1
/
TensorUtils.cpp
389 lines (346 loc) · 12 KB
/
TensorUtils.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
#include <ATen/Config.h>
#include <ATen/TensorUtils.h>
#include <ATen/ATen.h>
#include <ostream>
#include <sstream>
namespace at {
std::ostream& operator<<(std::ostream & out, TensorGeometryArg t) {
if (t.pos == 0) {
// 0 is distinguished; it usually indicates 'self' or the return
// tensor
out << "'" << t.name << "'";
} else {
out << "argument #" << t.pos << " '" << t.name << "'";
}
return out;
}
void checkDim(CheckedFrom c, const TensorGeometryArg& t, int64_t dim) {
TORCH_CHECK(t->dim() == dim,
"Expected ", dim, "-dimensional tensor, but got ", t->dim(),
"-dimensional tensor for ", t," (while checking arguments for ", c, ")");
}
void checkDimRange(CheckedFrom c, const TensorGeometryArg& t, int64_t dim_start, int64_t dim_end) {
TORCH_CHECK(
t->dim() >= dim_start && t->dim() < dim_end,
"Expected ", dim_start, " to ", (dim_end - 1), " dimensions, but got ",
t->dim(), "-dimensional tensor for ", t, " (while checking arguments for ",
c, ")");
}
void checkContiguous(CheckedFrom c, const TensorGeometryArg& t) {
TORCH_CHECK(
t->is_contiguous(),
"Expected contiguous tensor, but got non-contiguous tensor for ", t,
" (while checking arguments for ", c, ")");
}
void checkAllContiguous(CheckedFrom c, at::ArrayRef<TensorArg> ts) {
for (auto& t : ts) {
if (!t->defined()) continue;
checkContiguous(c, t);
}
}
void checkSize(CheckedFrom c, const TensorGeometryArg& t, IntArrayRef sizes) {
checkDim(c, t, sizes.size());
TORCH_CHECK(
t->sizes().equals(sizes),
"Expected tensor of size ", sizes, ", but got tensor of size ", t->sizes(),
" for ", t, " (while checking arguments for ", c, ")");
}
void checkSize(CheckedFrom c, const TensorGeometryArg& t, int64_t dim, int64_t size) {
TORCH_CHECK(
t->size(dim) == size,
"Expected tensor to have size ", size, " at dimension ", dim,
", but got size ", t->size(dim), " for ", t,
" (while checking arguments for ", c, ")");
}
void checkAllSame(CheckedFrom c, ArrayRef<TensorArg> tensors, void(*fn)(CheckedFrom, const TensorArg&, const TensorArg&)) {
const TensorArg* t0 = nullptr;
for (auto& t : tensors) {
if (!t->defined()) continue;
if (t0 != nullptr) {
fn(c, *t0, t);
} else {
t0 = &t;
}
}
}
void checkSameSize(CheckedFrom c, const TensorArg& t1, const TensorArg& t2) {
TORCH_CHECK(
t1->sizes().equals(t2->sizes()),
"Expected tensor for ", t1, " to have same size as tensor for ", t2,
"; but ", t1->sizes(), " does not equal ", t2->sizes(),
" (while checking arguments for ", c, ")");
}
void checkAllSameSize(CheckedFrom c, ArrayRef<TensorArg> tensors) {
checkAllSame(c, tensors, checkSameSize);
}
void checkNumel(CheckedFrom c, const TensorGeometryArg& t, int64_t numel) {
TORCH_CHECK(
t->numel() == numel,
"Expected tensor for ", t, " to have ", numel,
" elements; but it actually has ", t->numel(), " elements",
" (while checking arguments for ", c, ")");
}
void checkSameNumel(CheckedFrom c, const TensorArg& t1, const TensorArg& t2) {
TORCH_CHECK(
t1->numel() == t2->numel(),
"Expected tensor for ", t1,
" to have same number of elements as tensor for ", t2, "; but ",
t1->numel(), " does not equal ", t2->numel(),
" (while checking arguments for ", c, ")");
}
void checkAllSameNumel(CheckedFrom c, ArrayRef<TensorArg> tensors) {
checkAllSame(c, tensors, checkSameNumel);
}
void checkSameGPU(CheckedFrom c, const TensorArg& t1, const TensorArg& t2) {
if (! (t1->is_cuda()) || ! (t2->is_cuda())) {
std::ostringstream oss;
if (! t1->is_cuda()) {
oss << "Tensor for " << t1 << " is on CPU, ";
}
if (! t2->is_cuda()) {
oss << "Tensor for " << t2 << " is on CPU, ";
}
oss << "but expected " << ((!(t1->is_cuda() || t2->is_cuda())) ? "them" : "it")
<< " to be on GPU (while checking arguments for " << c << ")";
AT_ERROR(oss.str());
}
TORCH_CHECK(
t1->get_device() == t2->get_device(),
"Expected tensor for ", t1, " to have the same device as tensor for ", t2,
"; but device ", t1->get_device(), " does not equal ", t2->get_device(),
" (while checking arguments for ", c, ")");
}
void checkAllSameGPU(CheckedFrom c, ArrayRef<TensorArg> tensors) {
checkAllSame(c, tensors, checkSameGPU);
}
void checkSameType(CheckedFrom c, const TensorArg& t1, const TensorArg& t2) {
TORCH_CHECK(
t1->type() == t2->type(),
"Expected tensor for ", t1, " to have the same type as tensor for ", t2,
"; but type ", t1->toString(), " does not equal ", t2->toString(),
" (while checking arguments for ", c, ")");
}
void checkScalarType(CheckedFrom c, const TensorArg& t, ScalarType ty) {
TORCH_CHECK(
t->scalar_type() == ty,
"Expected tensor for ", t, " to have scalar type ", toString(ty),
"; but got ", t->toString(), " instead (while checking arguments for ", c,
")");
}
void checkScalarTypes(CheckedFrom c, const TensorArg& t,
at::ArrayRef<ScalarType> l) {
if (std::find(l.begin(), l.end(), t->scalar_type()) == l.end()) {
std::ostringstream oss;
oss << "Expected tensor for " << t << " to have one of the following "
<< "scalar types: ";
size_t i = 0;
for (auto ty : l) {
if (i != 0) {
oss << ", ";
}
oss << toString(ty);
i++;
}
oss << "; but got " << t->toString()
<< " instead (while checking arguments for " << c << ")";
AT_ERROR(oss.str());
}
}
void checkAllSameType(CheckedFrom c, ArrayRef<TensorArg> tensors) {
checkAllSame(c, tensors, checkSameType);
}
void checkSameDim(CheckedFrom c, const TensorGeometryArg& t1, const TensorGeometryArg& t2) {
TORCH_CHECK(
t1->dim() == t2->dim(),
"Expected tensor for ", t1, " to have the same dimension as tensor for ",
t2, "; but ", t1->dim(), " does not equal ", t2->dim(),
" (while checking arguments for ", c, ")");
}
void checkDefined(CheckedFrom c, const TensorArg& t) {
TORCH_CHECK(
t->defined(),
"Expected tensor for ", t, " to be non-null, but it was undefined ",
" (while checking arguments for ", c, ")");
}
void checkAllDefined(CheckedFrom c, ArrayRef<TensorArg> ts) {
// NB: don't filter defined here
for (auto t : ts) {
checkDefined(c, t);
}
}
void checkBackend(CheckedFrom c, const Tensor& t, Backend backend) {
TORCH_CHECK(
!t.defined() || t.type().backend() == backend,
"Expected tensor to have ", toString(backend),
" Backend, but got tensor with ", toString(t.type().backend()), " Backend ",
"(while checking arguments for ", c, ")");
}
void checkBackend(CheckedFrom c, at::ArrayRef<Tensor> tensors, at::Backend backend) {
for (auto &t : tensors) {
checkBackend(c, t, backend);
}
}
void checkDeviceType(CheckedFrom c, const Tensor& t, DeviceType device_type) {
TORCH_CHECK(
!t.defined() || t.type().device_type() == device_type,
"Expected tensor to have ", device_type,
" DeviceType, but got tensor with ", t.type().device_type(), " DeviceType ",
"(while checking arguments for ", c, ")");
}
void checkDeviceType(CheckedFrom c, at::ArrayRef<Tensor> tensors, at::DeviceType device_type) {
for (auto &t : tensors) {
checkDeviceType(c, t, device_type);
}
}
void checkLayout(CheckedFrom c, const Tensor& t, Layout layout) {
TORCH_CHECK(
!t.defined() || t.layout() == layout,
"Expected tensor to have ", layout,
" Layout, but got tensor with ", t.layout(), " Layout ",
"(while checking arguments for ", c, ")");
}
void checkLayout(CheckedFrom c, at::ArrayRef<Tensor> tensors, at::Layout layout) {
for (auto &t : tensors) {
checkLayout(c, t, layout);
}
}
void * maybe_data_ptr(const Tensor& tensor) {
return tensor.defined() ? (void *)tensor.data_ptr() : nullptr;
}
void * maybe_data_ptr(const TensorArg& tensor) {
return tensor->defined() ? (void *)tensor->data_ptr() : nullptr;
}
// See TensorUtils.h on why this is useful now that we cache is_contiguous.
bool geometry_is_contiguous(IntArrayRef sizes, IntArrayRef strides) {
int64_t dim = sizes.size();
int64_t expected_stride = 1;
bool contig_if_nonempty = true;
for (int64_t i = dim - 1; i >= 0; i--) {
if (sizes[i] == 0) {
return true;
}
if (contig_if_nonempty) {
if (sizes[i] != 1 && strides[i] != expected_stride) {
contig_if_nonempty = false;
}
expected_stride *= sizes[i];
}
}
return contig_if_nonempty;
}
// Correspond to THCUNN_check_dim_size/THNN_check_dim_size
void check_dim_size(
const Tensor& tensor,
int64_t dim,
int64_t dim_size,
int64_t size) {
/* Check dimension size of a tensor */
TORCH_CHECK(
tensor.dim() == dim && tensor.size(dim_size) == size,
"Expected a tensor of dimension ",
dim,
" and tensor.size[",
dim_size,
"] == ",
size,
" but got: dimension ",
tensor.dim(),
" and tensor.size[",
dim_size,
"] = ",
tensor.size(dim_size));
}
namespace detail {
std::vector<int64_t> defaultStrides(IntArrayRef sizes) {
std::vector<int64_t> strides(sizes.size());
int64_t stride = 1;
for(size_t i = sizes.size(); i > 0; --i) {
strides[i-1] = stride;
stride *= sizes[i-1];
}
return strides;
}
int64_t computeStorageSize(IntArrayRef sizes, IntArrayRef strides) {
// size of the underlying storage is 1 bigger than the offset
// of the last element according to stride
int64_t size = 1;
for(size_t i = 0; i < sizes.size(); i++) {
if(sizes[i] == 0) {
return 0;
}
size += strides[i]*(sizes[i]-1);
}
return size;
}
// On a high level,
// 1. separate `oldshape` into chunks of dimensions, where the dimensions are
// ``contiguous'' in each chunk, i.e., oldstride[i] = oldshape[i+1] *
// oldstride[i+1]
// 2. `newshape` must be able to be separated into same number of chunks as
// `oldshape` was separated into, where each chunk of newshape has matching
// ``numel'', i.e., number of subspaces, as the corresponding chunk of
// `oldshape`.
c10::optional<std::vector<int64_t>> computeStride(
IntArrayRef oldshape,
IntArrayRef oldstride,
IntArrayRef newshape) {
if (oldshape.empty()) {
return std::vector<int64_t>(newshape.size(), 1);
}
// NOTE: stride is arbitrary in the numel() == 0 case;
// to match NumPy behavior we copy the strides if the size matches, otherwise
// we use the stride as if it were computed via resize.
// This could perhaps be combined with the below code, but the complexity
// didn't seem worth it.
int64_t numel = std::accumulate(oldshape.begin(), oldshape.end(), 1,
std::multiplies<int64_t>());
if (numel == 0 && oldshape.equals(newshape)) {
return oldstride.vec();
}
std::vector<int64_t> newstride(newshape.size());
if (numel == 0) {
for (int64_t view_d = newshape.size() - 1; view_d >= 0; view_d--) {
if (view_d == (int64_t)(newshape.size() - 1)) {
newstride[view_d] = 1;
} else {
newstride[view_d] =
std::max<int64_t>(newshape[view_d+1], 1) * newstride[view_d+1];
}
}
return newstride;
}
int64_t view_d = newshape.size() - 1;
// stride for each subspace in the chunk
int64_t chunk_base_stride = oldstride.back();
// numel in current chunk
int64_t tensor_numel = 1;
int64_t view_numel = 1;
for (int64_t tensor_d = oldshape.size() - 1; tensor_d >= 0; tensor_d--) {
tensor_numel *= oldshape[tensor_d];
// if end of tensor size chunk, check view
if ((tensor_d == 0) ||
(oldshape[tensor_d - 1] != 1 &&
oldstride[tensor_d - 1] != tensor_numel * chunk_base_stride)) {
while (view_d >= 0 &&
(view_numel < tensor_numel || newshape[view_d] == 1)) {
newstride[view_d] = view_numel * chunk_base_stride;
view_numel *= newshape[view_d];
view_d--;
}
if (view_numel != tensor_numel) {
return c10::nullopt;
}
if (tensor_d > 0) {
chunk_base_stride = oldstride[tensor_d - 1];
tensor_numel = 1;
view_numel = 1;
}
}
}
if (view_d != -1) {
return c10::nullopt;
}
return newstride;
}
} // namespace detail
} // namespace at