Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 107 additions & 1 deletion python/singa/autograd.py
Original file line number Diff line number Diff line change
Expand Up @@ -4671,7 +4671,7 @@ def backward(self, dy):
follow https://math.stackexchange.com/a/1923705
Args:
dy (CTensor): gradient tensor.
Raises:
Return:
the gradient tensor over input tensor.
"""
a, b, ad, bd, ap, bp, ret = self.cache
Expand Down Expand Up @@ -4699,6 +4699,112 @@ def cossim(a, b):
return CosSim()(a, b)[0]


class Expand(Operator):
"""
Expand operator following ONNX Operator Schemas
https://github.com/onnx/onnx/blob/master/docs/Operators.md#Expand

Example usage::
data = [[1.], [2.], [3.]]

# dim_changed
shape = [2, 1, 6]
output = [[[1., 1., 1., 1., 1., 1.],
[2., 2., 2., 2., 2., 2.],
[3., 3., 3., 3., 3., 3.]],
[[1., 1., 1., 1., 1., 1.],
[2., 2., 2., 2., 2., 2.],
[3., 3., 3., 3., 3., 3.]]]

# dim_unchanged
shape = [3, 4]
output = [[1., 1., 1., 1.],
[2., 2., 2., 2.],
[3., 3., 3., 3.]]
"""

def __init__(self, shape):
"""
Args:
shape (list[int]: indicates the shape you want to expand to,
following the broadcast rule
"""
super(Expand, self).__init__()
self.shape = shape

def forward(self, x):
if isinstance(self.shape, np.ndarray):
self.shape = self.shape.tolist()
else:
self.shape = list(self.shape)
self.dim_changed = True
self.x_shape = list(x.shape())
x_shape = self.x_shape.copy()
for s_1, s_2 in zip(self.shape[::-1], x_shape[::-1]):
if s_1 != 1 and s_2 != 1:
if len(self.shape) != len(x_shape):
assert False, ('not support dim_unchanged mode')
self.dim_changed = False
break
if self.dim_changed:
tmp_tensor = singa.Tensor(self.shape, x.device())
tmp_tensor.SetFloatValue(1.)
x = singa.__mul__(x, tmp_tensor)
else:
for axis, s_1, s_2 in zip(range(len(self.shape)), self.shape,
x_shape):
if s_1 == s_2:
continue
xs = [x] * (s_1 // s_2)
x = singa.VecTensor(xs)
x = singa.ConcatOn(x, axis)
return x

def backward(self, dy):
x_shape = self.x_shape
if self.dim_changed:
dy = tensor.from_raw_tensor(dy)
if len(self.shape) > len(x_shape):
x_shape = [1] * (len(self.shape) - len(x_shape)) + x_shape
for axis, s in zip(range(len(self.shape))[::-1], x_shape[::1]):
if s == 1:
dy = tensor.sum(dy, axis)
dy = dy.data
else:
for axis, s_1, s_2 in zip(
range(len(self.shape))[::-1], self.shape[::-1],
x_shape[::-1]):
if s_1 > s_2:
duplic = s_1 // s_2
dxs = []
for i in range(s_2):
tmp_tensor = None
for j in range(duplic):
if not tmp_tensor:
tmp_tensor = singa.SliceOn(
dy, j * s_2 + i, j * s_2 + i + 1, axis)
else:
tmp_tensor += singa.SliceOn(
dy, j * s_2 + i, j * s_2 + i + 1, axis)
dxs.append(tmp_tensor)
dxs = singa.VecTensor(dxs)
dy = singa.ConcatOn(dxs, axis)
dy = singa.Reshape(dy, self.x_shape)
return dy

def expand(x, shape):
"""
Produces a Expand operator
Args:
x (Tensor): input tensor.
shape (list[int]: indicates the shape you want to expand to,
following the broadcast rule
Returns:
the output Tensor.
"""
return Expand(shape)(x)[0]


class Pad(Operator):
"""
Pad operator following ONNX Operator Schemas
Expand Down
16 changes: 16 additions & 0 deletions python/singa/sonnx.py
Original file line number Diff line number Diff line change
Expand Up @@ -1110,6 +1110,7 @@ class SingaBackend(Backend):
'Reshape': 'Reshape',
'Slice': 'Slice',
'Clip': 'Clip',
'Expand': 'Expand',
'Pad': 'Pad',
'Upsample': 'UpSample',
'Gemm': 'layer.Gemm', # layer
Expand Down Expand Up @@ -1150,6 +1151,7 @@ class SingaBackend(Backend):
'Conv': '_create_conv',
'MaxPool': '_create_max_avg_pool',
'AveragePool': '_create_max_avg_pool',
'Expand': '_create_expand',
'Pad': '_create_pad',
'Upsample': '_create_upsample',
}
Expand Down Expand Up @@ -1187,6 +1189,20 @@ def _create_upsample(cls, onnx_node, operator, opset_version=_opset_version):
onnx_node.set_attr_inputs(onnx_node.inputs[1], 'scales')
return operator(mode, None)

@classmethod
def _create_expand(cls, onnx_node, operator, opset_version=_opset_version):
"""
get the Expand operator from onnx node
Args:
onnx_node (OnnxNode): a given onnx node
operator (Operator Class): a singa operator class
opset_version (int): the opset version
Returns:
singa operator instance
"""
onnx_node.set_attr_inputs(onnx_node.inputs[1], 'shape')
return operator(None)

@classmethod
def _create_cast(cls, onnx_node, operator, opset_version=_opset_version):
"""
Expand Down
34 changes: 34 additions & 0 deletions test/python/test_operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -3081,6 +3081,40 @@ def test_cossim_cpu(self):
def test_cossim_gpu(self):
self.cossim_helper(gpu_dev)

def expand_helper(self, dev):
shape = [3, 1]
X = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32),
shape)
x = tensor.from_numpy(X)
x.to_device(dev)

# dim_changed
new_shape = [2, 1, 6]
y_t = X * np.ones(new_shape, dtype=np.float32)
dy = tensor.from_numpy(y_t)
dy.to_device(dev)
y = autograd.expand(x, new_shape)
dx = y.creator.backward(dy.data)
np.testing.assert_array_almost_equal(tensor.to_numpy(y), y_t)
self.check_shape(dx.shape(), tuple(shape))

# dim_unchanged
new_shape_2 = [3, 4]
y_t2 = np.tile(X, 4)
dy2 = tensor.from_numpy(y_t2)
dy2.to_device(dev)
y2 = autograd.expand(x, new_shape_2)
dx2 = y2.creator.backward(dy2.data)
np.testing.assert_array_almost_equal(tensor.to_numpy(y2), y_t2)
self.check_shape(dx2.shape(), tuple(shape))

def test_expand_cpu(self):
self.expand_helper(cpu_dev)

@unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled')
def test_expand_gpu(self):
self.expand_helper(gpu_dev)

def pad_helper(self, dev):
X = np.array([
[1.0, 1.2],
Expand Down