forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshape_functions_1.h
416 lines (342 loc) · 10.8 KB
/
shape_functions_1.h
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
R"=====(" ### DO NOT REMOVE THIS STRING!!!
# this file is included in torch/csrc/jit/runtime/symbolic_shape_registry.cpp
# at compile time and turned into a "raw" string
# there's a matching one at the bottom
# mypy: ignore-errors
# flake8: noqa
from typing import List, Any, Optional, Tuple, TypeVar, Union
number = TypeVar('number', bound=Union[int, float])
import torch
#### SHAPE COMPUTE FUNCTIONS START ###
def broadcast(a: List[int], b: List[int]):
dimsA = len(a)
dimsB = len(b)
ndim = max(dimsA, dimsB)
expandedSizes: List[int] = []
for i in range(ndim):
offset = ndim - 1 - i
dimA = dimsA - 1 - offset
dimB = dimsB - 1 - offset
sizeA = a[dimA] if (dimA >= 0) else 1
sizeB = b[dimB] if (dimB >= 0) else 1
if sizeA != sizeB and sizeA != 1 and sizeB != 1:
# TODO: only assertion error is bound in C++ compilation right now
raise AssertionError(
"The size of tensor a {} must match the size of tensor b ("
"{}) at non-singleton dimension {}".format(sizeA, sizeB, i)
)
expandedSizes.append(sizeB if sizeA == 1 else sizeA)
return expandedSizes
def broadcast_three(a: List[int], b: List[int], c: List[int]):
return broadcast(broadcast(a, b), c)
def broadcast_one_three(a: List[int], b: Any, c: List[int]):
return broadcast(a, c)
def adaptive_avg_pool2d(self: List[int], out: List[int]):
assert len(out) == 2
assert len(self) == 3 or len(self) == 4
for i in range(1, len(self)):
assert self[i] != 0
shape: List[int] = []
for i in range(0, len(self) - 2):
shape.append(self[i])
for elem in out:
shape.append(elem)
return shape
def _copy(self: List[int]):
out: List[int] = []
for elem in self:
out.append(elem)
return out
def unary(self: List[int]):
return _copy(self)
def broadcast_inplace(a: List[int], b: List[int]):
dimsA = len(a)
dimsB = len(b)
if dimsB > dimsA:
raise AssertionError(
"The dims of tensor b ({}) must be less than or equal to"
"the dims of tensor a ({}) ".format(dimsB, dimsA)
)
for dimA in range(dimsA):
dimB = dimsB - dimsA + dimA
sizeA = a[dimA]
sizeB = b[dimB] if (dimB >= 0) else 1
if sizeA != sizeB and sizeB != 1:
# TODO: only assertion error is bound in C++ compilation right now
raise AssertionError(
"The size of tensor a {} must match the size of tensor b ("
"{}) at non-singleton dimension {}".format(sizeA, sizeB, dimA)
)
return _copy(a)
def expand(self: List[int], sizes: List[int]):
assert len(sizes) >= len(self)
ndim = len(sizes)
tensor_dim = len(self)
if ndim == 0:
return _copy(sizes)
out: List[int] = []
for i in range(ndim):
offset = ndim - 1 - i
dim = tensor_dim - 1 - offset
size = self[dim] if dim >= 0 else 1
targetSize = sizes[i]
if targetSize == -1:
assert dim >= 0
targetSize = size
if size != targetSize:
assert size == 1
size = targetSize
out.append(size)
return out
def expand_one_unused(self: List[int], sizes: List[int], inp0: Any):
return expand(self, sizes)
def infer_size_impl(shape: List[int], numel: int) -> List[int]:
newsize = 1
infer_dim: Optional[int] = None
for dim in range(len(shape)):
if shape[dim] == -1:
if infer_dim is not None:
raise AssertionError("only one dimension can be inferred")
infer_dim = dim
elif shape[dim] >= 0:
newsize *= shape[dim]
else:
raise AssertionError("invalid shape dimensions")
if not (
numel == newsize
or (infer_dim is not None and newsize > 0 and numel % newsize == 0)
):
raise AssertionError("invalid shape")
out = _copy(shape)
if infer_dim is not None:
out[infer_dim] = numel // newsize
return out
def numel(sizes: List[int]):
numel = 1
for elem in sizes:
numel *= elem
return numel
def view(self: List[int], sizes: List[int]):
return infer_size_impl(sizes, numel(self))
def view_one_unused(self: List[int], sizes: List[int], *, implicit: bool = False):
return view(self, sizes)
def mean_dim(self: List[int], dims: List[int], keep_dim: bool, dt: Any):
out: List[int] = []
for idx in range(len(self)):
is_mean_dim: bool = False
for reduce_dim in dims:
if idx == maybe_wrap_dim(reduce_dim, len(self)):
is_mean_dim = True
if is_mean_dim:
if keep_dim:
out.append(1)
else:
out.append(self[idx])
return out
def max_dim(self: List[int], dim: int, keep_dim: bool):
out = mean_dim(self, [dim], keep_dim, None)
return out, out
# note: python already rounds down towards negative infinity on integer division, special arithmetic not needed
def div_rtn(x: int, y: int):
return x // y
def pooling_output_shape_pad_lr(
inputSize: int,
kernelSize: int,
pad_l: int,
pad_r: int,
stride: int,
dilation: int,
ceil_mode: bool,
):
outputSize = (
div_rtn(
inputSize
+ pad_l
+ pad_r
- dilation * (kernelSize - 1)
- 1
+ (stride - 1 if ceil_mode else 0),
stride,
)
+ 1
)
if ceil_mode:
if (outputSize - 1) * stride >= inputSize + pad_l:
outputSize = outputSize - 1
return outputSize
def pooling_output_shape(
inputSize: int,
kernelSize: int,
pad_l: int,
stride: int,
dilation: int,
ceil_mode: bool,
):
assert stride != 0, "stride should not be zeero"
return pooling_output_shape_pad_lr(
inputSize, kernelSize, pad_l, pad_l, stride, dilation, ceil_mode
)
def pool2d_shape_check(
input: List[int],
kH: int,
kW: int,
dH: int,
dW: int,
padH: int,
padW: int,
dilationH: int,
dilationW: int,
nInputPlane: int,
inputHeight: int,
inputWidth: int,
outputHeight: int,
outputWidth: int,
):
ndim = len(input)
nOutputPlane = nInputPlane
assert kW > 0 and kH > 0
assert dW > 0 and dH > 0
assert dilationH > 0 and dilationW > 0
valid_dims = input[1] != 0 and input[2] != 0
assert (
ndim == 3
and input[0] != 0
and valid_dims
or (ndim == 4 and valid_dims and input[3] != 0)
)
assert kW // 2 >= padW and kH // 2 >= padH
assert outputWidth >= 1 and outputHeight >= 1
def max_pool2d(
input: List[int],
kernel_size: List[int],
stride: List[int],
padding: List[int],
dilation: List[int],
ceil_mode: bool,
):
assert (
len(kernel_size) == 1 or len(kernel_size) == 2
), "max_pool2d: kernel_size must either be a single int, or a tuple of two ints"
kH = kernel_size[0]
kW = kH if len(kernel_size) == 1 else kernel_size[1]
assert (
len(stride) == 0 or len(stride) == 1 or len(stride) == 2
), "max_pool2d: stride must either be omitted, a single int, or a tuple of two ints"
dH = kH if len(stride) == 0 else stride[0]
if len(stride) == 0:
dW = kW
elif len(stride) == 1:
dW = dH
else:
dW = stride[1]
assert (
len(padding) == 1 or len(padding) == 2
), "max_pool2d: padding must be either be a single int, or a tuple of two ints"
padH = padding[0]
padW = padH if len(padding) == 1 else padding[1]
assert (
len(dilation) == 1 or len(dilation) == 2
), "max_pool2d: dilation must be either a single int, or a tuple of two ints"
dilationH = dilation[0]
dilationW = dilationH if len(dilation) == 1 else dilation[1]
assert len(input) == 3 or len(input) == 4
nbatch = input[-4] if len(input) == 4 else 1
nInputPlane = input[-3]
inputHeight = input[-2]
inputWidth = input[-1]
outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, dilationH, ceil_mode)
outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, dilationW, ceil_mode)
pool2d_shape_check(
input,
kH,
kW,
dH,
dW,
padH,
padW,
dilationH,
dilationW,
nInputPlane,
inputHeight,
inputWidth,
outputHeight,
outputWidth,
)
if len(input) == 3:
return [nInputPlane, outputHeight, outputWidth]
else:
return [nbatch, nInputPlane, outputHeight, outputWidth]
def max_pool2d_with_indices(
input: List[int],
kernel_size: List[int],
stride: List[int],
padding: List[int],
dilation: List[int],
ceil_mode: bool,
):
out = max_pool2d(input, kernel_size, stride, padding, dilation, ceil_mode)
return (out, out)
def upsample_nearest2d(
input: List[int],
output_size: Optional[List[int]],
scale_factors: Optional[List[float]],
):
out: List[int] = []
out.append(input[0])
out.append(input[1])
if output_size is not None:
assert (
scale_factors is None
), "Must specify exactly one of output_size and scale_factors"
assert len(output_size) == 2
out.append(output_size[0])
out.append(output_size[1])
return out
if scale_factors is not None:
assert (
output_size is None
), "Must specify exactly one of output_size and scale_factors"
assert len(scale_factors) == 2
out.append(int(input[2] * scale_factors[0]))
out.append(int(input[3] * scale_factors[1]))
return out
assert 0, "Either output_size or scale_factors must be presented"
def mm(self: List[int], mat2: List[int]):
assert len(self) == 2, "self must be a matrix"
assert len(mat2) == 2, "mat2 must be a matrix"
assert self[1] == mat2[0]
return [self[0], mat2[1]]
def dot(self: List[int], tensor: List[int]):
assert len(self) == 1 and len(tensor) == 1
assert self[0] == tensor[0]
out: List[int] = []
return out
def mv(self: List[int], vec: List[int]):
assert len(self) == 2 and len(vec) == 1
assert self[1] == vec[0]
# TODO: return self
return [self[0]]
def unsqueeze(li: List[int], dim: int):
dim = maybe_wrap_dim(dim, len(li) + 1)
out = _copy(li)
out.insert(dim, 1)
return out
def squeeze_nodim(li: List[int]):
out: List[int] = []
for i in range(len(li)):
if li[i] != 1:
out.append(li[i])
return out
def squeeze(li: List[int], dim: int):
out: List[int] = []
wrapped_dim = maybe_wrap_dim(dim, len(li))
for i in range(len(li)):
if i == wrapped_dim:
if li[i] != 1:
out.append(li[i])
else:
out.append(li[i])
return out
#### SHAPE COMPUTE FUNCTIONS END ###
### DO NOT REMOVE THIS STRING!!! #
")====="