Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate tile python layer to functor #7305

Merged
merged 39 commits into from
Jan 24, 2022
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
d584632
tile implement
thinksoso Jan 10, 2022
5d14b4c
migrate repeat
thinksoso Jan 13, 2022
9fb74c7
of format
thinksoso Jan 13, 2022
9b5dbc8
align document with pytorch
thinksoso Jan 14, 2022
27f33d4
change input args to *size
thinksoso Jan 14, 2022
bfc1a0c
Merge branch 'master' into migrate_repeat_python_layer_to_functor
thinksoso Jan 17, 2022
ddab4cb
change with review comments
thinksoso Jan 17, 2022
202915f
Merge branch 'migrate_repeat_python_layer_to_functor' of github.com:O…
thinksoso Jan 17, 2022
89d2228
Merge branch 'migrate_repeat_python_layer_to_functor' into migrate_ti…
thinksoso Jan 18, 2022
7c0d7d6
migrate tile python layer to functor
thinksoso Jan 19, 2022
1c2fd2c
fix tile document
thinksoso Jan 19, 2022
9557ad6
fix tile document
thinksoso Jan 19, 2022
04a86bc
Merge branch 'master' into migrate_tile_python_layer_to_functor
thinksoso Jan 20, 2022
eee21cb
add document's function signature
thinksoso Jan 20, 2022
d52d4fb
Merge branch 'migrate_tile_python_layer_to_functor' of github.com:One…
thinksoso Jan 20, 2022
80cb2fa
Merge branch 'master' into migrate_tile_python_layer_to_functor
thinksoso Jan 20, 2022
9e68dcb
Merge branch 'master' into migrate_tile_python_layer_to_functor
oneflow-ci-bot Jan 20, 2022
a8be7a5
auto format by CI
oneflow-ci-bot Jan 20, 2022
b5033bb
add repeat document signature
thinksoso Jan 20, 2022
66f813e
Merge branch 'migrate_tile_python_layer_to_functor' of github.com:One…
thinksoso Jan 20, 2022
624c063
Merge branch 'master' into migrate_tile_python_layer_to_functor
oneflow-ci-bot Jan 20, 2022
9bc8bd0
Merge branch 'master' into migrate_tile_python_layer_to_functor
oneflow-ci-bot Jan 20, 2022
99e0a6e
fix document
thinksoso Jan 21, 2022
ea52e8a
Merge branch 'migrate_tile_python_layer_to_functor' of github.com:One…
thinksoso Jan 21, 2022
2e07b17
Merge branch 'master' into migrate_tile_python_layer_to_functor
thinksoso Jan 21, 2022
0e8cce2
fix document
thinksoso Jan 21, 2022
5025d02
Merge branch 'migrate_tile_python_layer_to_functor' of github.com:One…
thinksoso Jan 21, 2022
c1fdba2
Merge branch 'master' into migrate_tile_python_layer_to_functor
thinksoso Jan 21, 2022
d81219f
Merge branch 'master' into migrate_tile_python_layer_to_functor
oneflow-ci-bot Jan 21, 2022
54b1158
Merge branch 'master' into migrate_tile_python_layer_to_functor
thinksoso Jan 22, 2022
fffcc78
Merge branch 'master' into migrate_tile_python_layer_to_functor
oneflow-ci-bot Jan 22, 2022
1edef4c
Merge branch 'master' into migrate_tile_python_layer_to_functor
oneflow-ci-bot Jan 22, 2022
c76f080
Merge branch 'master' into migrate_tile_python_layer_to_functor
thinksoso Jan 22, 2022
70ca5ce
Merge branch 'master' into migrate_tile_python_layer_to_functor
thinksoso Jan 24, 2022
0da0c3e
Merge branch 'master' into migrate_tile_python_layer_to_functor
oneflow-ci-bot Jan 24, 2022
c794169
Merge branch 'master' into migrate_tile_python_layer_to_functor
thinksoso Jan 24, 2022
ab4218a
Merge branch 'master' into migrate_tile_python_layer_to_functor
oneflow-ci-bot Jan 24, 2022
4cb5648
Merge branch 'master' into migrate_tile_python_layer_to_functor
oneflow-ci-bot Jan 24, 2022
b53305f
Merge branch 'master' into migrate_tile_python_layer_to_functor
oneflow-ci-bot Jan 24, 2022
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
8 changes: 8 additions & 0 deletions oneflow/core/functional/functional_api.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -740,6 +740,14 @@
signature: "Tensor (Tensor dy, Int32List out, Int32List expand) => ExpandGrad"
bind_python: False

- name: "repeat"
signature: "Tensor (Tensor input, Shape repeat_shape) => Repeat"
bind_python: True

- name: "tile"
signature: "Tensor (Tensor input, Shape dims) => Tile"
bind_python: True

- name: "roll"
signature: "Tensor (Tensor x, Int32List[1] shifts, Int32List[1] dims=None) => Roll"
bind_python: True
Expand Down
71 changes: 71 additions & 0 deletions oneflow/core/functional/impl/array_functor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2523,6 +2523,75 @@ class GenTensorBufferFunctor {
std::shared_ptr<OpExpr> op_;
};

class RepeatFunctor {
public:
RepeatFunctor() {}
Maybe<Tensor> operator()(const std::shared_ptr<one::Tensor>& input,
const Shape& repeat_shape) const {
Shape input_shape = *(input->shape());
std::vector<int32_t> input_reshape_vec;
std::vector<int32_t> expand_shape_vec;
std::vector<int32_t> output_reshape_vec;

int32_t numaxes_diff = repeat_shape.NumAxes() - input_shape.NumAxes();
CHECK_GE_OR_RETURN(numaxes_diff, 0)
<< "RuntimeError: Number of dimensions of repeat dims can not be "
"smaller than number of dimensions of tensor";

for (int32_t i = repeat_shape.NumAxes() - 1; i >= 0; i--) {
if (i >= numaxes_diff) {
int32_t input_shape_val = input_shape.At(i - numaxes_diff);
int32_t repeat_shape_val = repeat_shape.At(i);
if (repeat_shape_val > 1) {
if (input_shape_val > 1) {
input_reshape_vec.insert(input_reshape_vec.begin(), input_shape_val);
input_reshape_vec.insert(input_reshape_vec.begin(), 1);
expand_shape_vec.insert(expand_shape_vec.begin(), input_shape_val);
expand_shape_vec.insert(expand_shape_vec.begin(), repeat_shape_val);
output_reshape_vec.insert(output_reshape_vec.begin(),
repeat_shape_val * input_shape_val);
} else {
input_reshape_vec.insert(input_reshape_vec.begin(), input_shape_val);
expand_shape_vec.insert(expand_shape_vec.begin(), repeat_shape_val);
output_reshape_vec.insert(output_reshape_vec.begin(), repeat_shape_val);
}
} else {
input_reshape_vec.insert(input_reshape_vec.begin(), input_shape_val);
expand_shape_vec.insert(expand_shape_vec.begin(), input_shape_val);
output_reshape_vec.insert(output_reshape_vec.begin(), input_shape_val);
}
} else {
expand_shape_vec.insert(expand_shape_vec.begin(), repeat_shape.At(i));
output_reshape_vec.insert(output_reshape_vec.begin(), repeat_shape.At(i));
}
}
Shape input_reshape(DimVector(input_reshape_vec.begin(), input_reshape_vec.end()));
Shape expand_shape(DimVector(expand_shape_vec.begin(), expand_shape_vec.end()));
Shape output_reshape(DimVector(output_reshape_vec.begin(), output_reshape_vec.end()));
std::shared_ptr<one::Tensor> new_tensor = JUST(Reshape(input, input_reshape));
thinksoso marked this conversation as resolved.
Show resolved Hide resolved
std::shared_ptr<one::Tensor> tmp_tensor = JUST(Expand(new_tensor, expand_shape));
std::shared_ptr<one::Tensor> result = JUST(Reshape(tmp_tensor, output_reshape));
return result;
}
};

class TileFunctor {
public:
TileFunctor() {}
Maybe<Tensor> operator()(const std::shared_ptr<one::Tensor>& input, const Shape& dims) const {
std::vector<int32_t> new_dims_vec;
int32_t numaxes_diff = input->shape()->NumAxes() - dims.NumAxes();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

input->shape()->NumAxes()可以改成input->ndim()
参考这个 https://github.com/Oneflow-Inc/oneflow/blob/master/oneflow/core/framework/tensor.h#L51

for (int32_t i = dims.NumAxes() - 1; i >= 0; i--) {
CHECK_GE_OR_RETURN(dims.At(i), 0)
<< "RuntimeError: Tring to create tensor with negative dimension " << dims.At(i);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里的报错还不能和pytorch完全一致,因为错误判断的实现位置不同,pytorch应该是不在tile层面检查,而是下到创建tensor时检查,这里的实现和python实现一致,在tile函数中提前检查。
image

new_dims_vec.insert(new_dims_vec.begin(), dims.At(i));
}
for (int32_t i = 0; i < numaxes_diff; i++) { new_dims_vec.insert(new_dims_vec.begin(), 1); }
Shape new_dims(DimVector(new_dims_vec.begin(), new_dims_vec.end()));
return JUST(Repeat(input, new_dims));
}
};

} // namespace impl

ONEFLOW_FUNCTION_LIBRARY(m) {
Expand Down Expand Up @@ -2626,6 +2695,8 @@ ONEFLOW_FUNCTION_LIBRARY(m) {
m.add_functor<impl::TensorToTensorBufferFunctor>("TensorToTensorBuffer");
m.add_functor<impl::TensorBufferToTensorFunctor>("TensorBufferToTensor");
m.add_functor<impl::GenTensorBufferFunctor>("GenTensorBuffer");
m.add_functor<impl::RepeatFunctor>("Repeat");
m.add_functor<impl::TileFunctor>("Tile");
};

} // namespace functional
Expand Down
4 changes: 2 additions & 2 deletions python/oneflow/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ def is_deprecated(func_or_class):
from oneflow._C import logical_not
from oneflow._C import gelu
from oneflow._C import mish
from oneflow._C import repeat
from oneflow._C import tile
from oneflow._C import sigmoid
from oneflow._C import tanh
from oneflow._C import silu
Expand Down Expand Up @@ -340,7 +342,6 @@ def atexit_hook(hook):
from oneflow.nn.modules.reduce_ops import prod_op as prod
from oneflow.nn.modules.reduce_ops import all_op as all
from oneflow.nn.modules.reduce_ops import any_op as any
from oneflow.nn.modules.repeat import repeat_op as repeat
from oneflow.nn.modules.reshape import reshape_op as reshape
from oneflow.nn.modules.reshape import view_op as view
from oneflow.nn.modules.slice import slice_op as slice
Expand All @@ -354,7 +355,6 @@ def atexit_hook(hook):
)
from oneflow.nn.modules.as_tensor import as_tensor
from oneflow.nn.modules.tensor_buffer import tensor_to_tensor_buffer
from oneflow.nn.modules.tile import tile_op as tile
from oneflow.nn.modules.consistent_cast import to_consistent_op as to_consistent
from oneflow.nn.modules.consistent_cast import to_local_op as to_local
from oneflow.nn.modules.where import where_op as where
Expand Down
2 changes: 2 additions & 0 deletions python/oneflow/framework/docstr/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,5 @@
from .clamp import *
from .erfinv import *
from .swapaxes import *
from .repeat import *
from .tile import *
49 changes: 49 additions & 0 deletions python/oneflow/framework/docstr/repeat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""
Copyright 2020 The OneFlow Authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import oneflow
from oneflow.framework.docstr.utils import add_docstr

add_docstr(
oneflow.repeat,
"""
oneflow.repeat(input, sizes)
thinksoso marked this conversation as resolved.
Show resolved Hide resolved

This operator repeat the input tensor to a larger size along the specified dimensions.

Args:
input (oneflow.Tensor): The input Tensor.
sizes (flow.Shape or List): The number of times to repeat this tensor along each dimension.

Returns:
oneflow.Tensor: The result Tensor.

For example:

.. code-block:: python

>>> import oneflow as flow
>>> import numpy as np
>>> np_arr = np.random.randn(5, 3, 6, 9).astype(np.float32)
>>> input = flow.Tensor(np_arr)
>>> out = input.repeat(1, 1, 2, 2)
>>> out.shape
oneflow.Size([5, 3, 12, 8])

>>> out = input.repeat(2, 1, 1, 2, 2)
>>> out.shape
oneflow.Size([2, 5, 3, 12, 8])
""",
)
14 changes: 14 additions & 0 deletions python/oneflow/framework/docstr/tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -782,3 +782,17 @@
Alias for :func:`oneflow.Tensor.clamp_`.
""",
)

add_docstr(
oneflow.Tensor.repeat,
"""
See :func:`oneflow.repeat`
""",
)

add_docstr(
oneflow.Tensor.tile,
"""
See :func:`oneflow.tile`
""",
)
Original file line number Diff line number Diff line change
Expand Up @@ -13,36 +13,34 @@
See the License for the specific language governing permissions and
limitations under the License.
"""
from typing import Union
import oneflow
from oneflow.framework.docstr.utils import add_docstr

import oneflow as flow
from oneflow.framework.tensor import register_tensor_op


@register_tensor_op("tile")
def tile_op(input, reps):
"""The interface is consistent with PyTorch.
add_docstr(
oneflow.tile,
"""
The interface is consistent with PyTorch.
The documentation is referenced from:
https://pytorch.org/docs/stable/generated/torch.tile.html

Constructs a tensor by repeating the elements of ``input``. The ``reps`` argument specifies the number
Constructs a tensor by repeating the elements of ``input``. The ``dims`` argument specifies the number
of repetitions in each dimension.

If ``reps`` specifies fewer dimensions than ``input`` has, then ones are prepended to ``reps`` until
all dimensions are specified. For example, if ``input`` has shape (8, 6, 4, 2) and ``reps`` is (2, 2),
then ``reps`` is treated as (1, 1, 2, 2).
If ``dims`` specifies fewer dimensions than ``input`` has, then ones are prepended to ``dims`` until
all dimensions are specified. For example, if ``input`` has shape (8, 6, 4, 2) and ``dims`` is (2, 2),
then ``dims`` is treated as (1, 1, 2, 2).

Analogously, if ``input`` has fewer dimensions than ``reps`` specifies, then ``input`` is treated as
if it were unsqueezed at dimension zero until it has as many dimensions as ``reps`` specifies.
For example, if ``input`` has shape (4, 2) and ``reps`` is (3, 3, 2, 2), then ``input`` is treated as
Analogously, if ``input`` has fewer dimensions than ``dims`` specifies, then ``input`` is treated as
if it were unsqueezed at dimension zero until it has as many dimensions as ``dims`` specifies.
For example, if ``input`` has shape (4, 2) and ``dims`` is (3, 3, 2, 2), then ``input`` is treated as
if it had the shape (1, 1, 4, 2).

.. note::
This function is similar to NumPy’s tile function.

Args:
input (oneflow.Tensor): the tensor whose elements to repeat.
reps (tuple): the number of repetitions per dimension.
dims (tuple): the number of repetitions per dimension.

For example:

Expand All @@ -51,32 +49,16 @@ def tile_op(input, reps):
>>> import oneflow as flow
>>> import numpy as np

>>> x = np.array([1, 2]).astype(np.int32)
>>> input = flow.tensor(x, dtype=flow.int32)
>>> out = input.tile(reps=(2,))
>>> out
tensor([1, 2, 1, 2], dtype=oneflow.int32)
>>> np_arr = np.random.randn(5, 3, 6, 9).astype(np.float32)
>>> input = flow.Tensor(np_arr)
>>> out = input.tile(2,1,2,1)
>>> out.shape
oneflow.Size([10,3,12,9])

>>> x = np.random.randn(5, 2, 1)
>>> input = flow.Tensor(x)
>>> out = input.tile(reps=(3, 4))
>>> out.size()
>>> out = input.tile(3,4)
>>> out.shape
oneflow.Size([5, 6, 4])

"""

for s in reps:
assert s > 0
input_shape = input.shape
diff = len(input_shape) - len(reps)
if diff > 0:
shape = [1 for _ in range(diff)]
shape.extend([i for i in reps])
reps = tuple(shape)
return input.repeat(reps)


if __name__ == "__main__":
import doctest

doctest.testmod(raise_on_error=True)
""",
)
22 changes: 22 additions & 0 deletions python/oneflow/framework/tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -745,6 +745,26 @@ def _gather(self, dim, index):
return flow._C.dim_gather(self, dim, index, False)


def _repeat(self, *sizes):
if len(sizes) == 1:
new_sizes = dim[0]
thinksoso marked this conversation as resolved.
Show resolved Hide resolved
if isinstance(new_sizes, int):
new_sizes = (new_sizes,)
else:
new_sizes = sizes
return flow._C.repeat(self, new_sizes)


def _tile(self, *dims):
if len(dims) == 1:
new_dims = dims[0]
if isinstance(new_dims, int):
new_dims = (new_dims,)
else:
new_dims = dims
return flow._C.tile(self, new_dims)


def _numpy(self):
assert (
not self.is_lazy
Expand Down Expand Up @@ -904,6 +924,8 @@ def RegisterMethods():
Tensor.roll = _roll
Tensor.bmm = _bmm
Tensor.chunk = _chunk
Tensor.repeat = _repeat
Tensor.tile = _tile
Tensor.split = _split
Tensor.squeeze = _squeeze
Tensor.swapaxes = _swapaxes
Expand Down
Loading