Caffe2 - Python API
A deep learning, cross platform ML framework
utils.py
1 import torch
2 from functools import reduce
3 
4 
5 def maybe_view(tensor, size, check_same_size=True):
6  if check_same_size and tensor.size() == size:
7  return tensor
8  return tensor.contiguous().view(size)
9 
10 
11 def maybe_unexpand(tensor, old_size, check_same_size=True):
12  if check_same_size and tensor.size() == old_size:
13  return tensor
14  num_unsqueezed = tensor.dim() - len(old_size)
15  expanded_dims = [dim for dim, (expanded, original)
16  in enumerate(zip(tensor.size()[num_unsqueezed:], old_size))
17  if expanded != original]
18 
19  for _ in range(num_unsqueezed):
20  tensor = tensor.sum(0, keepdim=False)
21  for dim in expanded_dims:
22  tensor = tensor.sum(dim, keepdim=True)
23  return tensor
24 
25 
26 # Generate paddings in ONNX order based on pad in pytorch.
27 # Arguments:
28 # dim: the dimension of the tensor.
29 # pad: the paddings in pytorch.
30 # The order is dim_n_begin, dim_n_end, dim_n-1_begin, dim_n-1_end, ...
31 def prepare_onnx_paddings(dim, pad):
32  assert isinstance(dim, int)
33  # The desired order of paddings is
34  # dim_0_begin, dim_1_begin, ... , dim_0_end, ..., dim_n_end.
35  # n is the dimension of input.
36  assert len(pad) <= dim * 2
37  # assume zero-dimensions in the beginning
38  paddings = list(pad[:]) + [0] * (dim * 2 - len(pad))
39  # reverse order and collate first beginnings and then ends
40  paddings = paddings[-2::-2] + paddings[-1::-2]
41  assert len(paddings) == dim * 2
42  return paddings
43 
44 
45 # Check whether the op enable broadcasting, and whether it is supported by ONNX.
46 # If dims1 and dims2 are different, then broadcast is True.
47 # We always assume the combination of dims1 and dims2 is broadcastable.
48 # The following types of broadcasting are supported in ONNX:
49 # 1) Only one element in dims2, such as dims2 = [1, 1]
50 # 2) dims2 is suffix of dims1, such as dims1 = [2, 3, 4], and dims2 = [3, 4]
51 # Details can be found here: https://github.com/onnx/onnx/blob/master/docs/Operators.md#Gemm
52 def check_onnx_broadcast(dims1, dims2):
53  broadcast = False
54  supported = True
55  len1 = len(dims1)
56  len2 = len(dims2)
57  numel1 = reduce(lambda x, y: x * y, dims1)
58  numel2 = reduce(lambda x, y: x * y, dims2)
59  if len1 < len2:
60  broadcast = True
61  if numel2 != 1:
62  supported = False
63  elif len1 > len2:
64  broadcast = True
65  if numel2 != 1 and dims1[len1 - len2:] != dims2:
66  supported = False
67  else:
68  if dims1 != dims2:
69  broadcast = True
70  if numel2 != 1:
71  supported = False
72 
73  if not supported:
74  raise ValueError("Numpy style broadcasting is not supported in ONNX. "
75  "Input dims are: {}, {}".format(dims1, dims2))
76  return broadcast