array.py 9.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   Copyright (c) 2020 PaddlePaddle 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.

# Define functions about array.

17 18
from ..fluid.data_feeder import check_type, check_variable_and_dtype
from ..framework import LayerHelper, _non_static_mode, core
19
from ..static import Variable
20

21 22
__all__ = []

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

def array_length(array):
    """
    This OP is used to get the length of the input array.

    Args:
        array (list|Tensor): The input array that will be used to compute the length. In dynamic mode, ``array`` is a Python list. But in static mode, array is a Tensor whose VarType is LOD_TENSOR_ARRAY.

    Returns:
        Tensor: 1-D Tensor with shape [1], which is the length of array.

    Examples:
        .. code-block:: python

            import paddle

            arr = paddle.tensor.create_array(dtype='float32')
            x = paddle.full(shape=[3, 3], fill_value=5, dtype="float32")
            i = paddle.zeros(shape=[1], dtype="int32")

            arr = paddle.tensor.array_write(x, i, array=arr)

            arr_len = paddle.tensor.array_length(arr)
            print(arr_len)  # 1
    """
48 49
    if _non_static_mode():
        assert isinstance(
50 51
            array, list
        ), "The 'array' in array_write must be a list in dygraph mode"
52 53
        return len(array)

54 55 56 57
    if (
        not isinstance(array, Variable)
        or array.type != core.VarDesc.VarType.LOD_TENSOR_ARRAY
    ):
58
        raise TypeError(
59 60
            "array should be tensor array vairable in array_length Op"
        )
61 62 63 64

    helper = LayerHelper('array_length', **locals())
    tmp = helper.create_variable_for_type_inference(dtype='int64')
    tmp.stop_gradient = True
65 66 67
    helper.append_op(
        type='lod_array_length', inputs={'X': [array]}, outputs={'Out': [tmp]}
    )
68
    return tmp
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


def array_read(array, i):
    """
    This OP is used to read data at the specified position from the input array.

    Case:

    .. code-block:: text

        Input:
            The shape of first three tensors are [1], and that of the last one is [1,2]:
                array = ([0.6], [0.1], [0.3], [0.4, 0.2])
            And:
                i = [3]

        Output:
            output = [0.4, 0.2]

    Args:
        array (list|Tensor): The input array. In dynamic mode, ``array`` is a Python list. But in static mode, array is a Tensor whose ``VarType`` is ``LOD_TENSOR_ARRAY``.
        i (Tensor): 1-D Tensor, whose shape is [1] and dtype is int64. It represents the
            specified read position of ``array``.

    Returns:
        Tensor: A Tensor that is read at the specified position of ``array``.

    Examples:
        .. code-block:: python

            import paddle

            arr = paddle.tensor.create_array(dtype="float32")
            x = paddle.full(shape=[1, 3], fill_value=5, dtype="float32")
            i = paddle.zeros(shape=[1], dtype="int32")

            arr = paddle.tensor.array_write(x, i, array=arr)

            item = paddle.tensor.array_read(arr, i)
            print(item)     # [[5., 5., 5.]]
    """
110 111
    if _non_static_mode():
        assert isinstance(
112 113
            array, list
        ), "The 'array' in array_read must be list in dygraph mode"
114 115 116 117 118 119 120 121 122 123 124
        assert isinstance(
            i, Variable
        ), "The index 'i' in array_read must be Variable in dygraph mode"
        assert i.shape == [
            1
        ], "The shape of index 'i' should be [1] in dygraph mode"
        i = i.numpy().item(0)
        return array[i]

    check_variable_and_dtype(i, 'i', ['int64'], 'array_read')
    helper = LayerHelper('array_read', **locals())
125 126 127 128
    if (
        not isinstance(array, Variable)
        or array.type != core.VarDesc.VarType.LOD_TENSOR_ARRAY
    ):
129 130
        raise TypeError("array should be tensor array vairable")
    out = helper.create_variable_for_type_inference(dtype=array.dtype)
131 132 133 134 135
    helper.append_op(
        type='read_from_array',
        inputs={'X': [array], 'I': [i]},
        outputs={'Out': [out]},
    )
136
    return out
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


def array_write(x, i, array=None):
    """
    This OP writes the input ``x`` into the i-th position of the ``array`` returns the modified array.
    If ``array`` is none, a new array will be created and returned.

    Args:
        x (Tensor): The input data to be written into array. It's multi-dimensional
            Tensor or LoDTensor. Data type: float32, float64, int32, int64 and bool.
        i (Tensor): 1-D Tensor with shape [1], which represents the position into which
            ``x`` is written.
        array (list|Tensor, optional): The array into which ``x`` is written. The default value is None,
            when a new array will be created and returned as a result. In dynamic mode, ``array`` is a Python list.
            But in static mode, array is a Tensor whose ``VarType`` is ``LOD_TENSOR_ARRAY``.

    Returns:
        list|Tensor: The input ``array`` after ``x`` is written into.

    Examples:
        .. code-block:: python

            import paddle

            arr = paddle.tensor.create_array(dtype="float32")
            x = paddle.full(shape=[1, 3], fill_value=5, dtype="float32")
            i = paddle.zeros(shape=[1], dtype="int32")

            arr = paddle.tensor.array_write(x, i, array=arr)

            item = paddle.tensor.array_read(arr, i)
            print(item)     # [[5., 5., 5.]]
    """
170 171 172 173 174 175 176 177 178 179 180 181 182 183
    if _non_static_mode():
        assert isinstance(
            x, Variable
        ), "The input data 'x' in array_write must be Variable in dygraph mode"
        assert isinstance(
            i, Variable
        ), "The index 'i' in array_write must be Variable in dygraph mode"
        assert i.shape == [
            1
        ], "The shape of index 'i' should be [1] in dygraph mode"
        i = i.numpy().item(0)
        if array is None:
            array = create_array(x.dtype)
        assert isinstance(
184 185
            array, list
        ), "The 'array' in array_write must be a list in dygraph mode"
186 187 188 189 190 191 192 193 194 195 196 197 198
        assert i <= len(
            array
        ), "The index 'i' should not be greater than the length of 'array' in dygraph mode"
        if i < len(array):
            array[i] = x
        else:
            array.append(x)
        return array

    check_variable_and_dtype(i, 'i', ['int64'], 'array_write')
    check_type(x, 'x', (Variable), 'array_write')
    helper = LayerHelper('array_write', **locals())
    if array is not None:
199 200 201 202
        if (
            not isinstance(array, Variable)
            or array.type != core.VarDesc.VarType.LOD_TENSOR_ARRAY
        ):
203
            raise TypeError(
204 205
                "array should be tensor array vairable in array_write Op"
            )
206 207 208 209
    if array is None:
        array = helper.create_variable(
            name="{0}.out".format(helper.name),
            type=core.VarDesc.VarType.LOD_TENSOR_ARRAY,
210 211 212 213 214 215 216
            dtype=x.dtype,
        )
    helper.append_op(
        type='write_to_array',
        inputs={'X': [x], 'I': [i]},
        outputs={'Out': [array]},
    )
217
    return array
218 219


220
def create_array(dtype, initialized_list=None):
221 222 223 224 225 226
    """
    This OP creates an array. It is used as the input of :ref:`api_paddle_tensor_array_array_read` and
    :ref:`api_paddle_tensor_array_array_write`.

    Args:
        dtype (str): The data type of the elements in the array. Support data type: float32, float64, int32, int64 and bool.
227 228
        initialized_list(list): Used to initialize as default value for created array.
                    All values in initialized list should be a Tensor.
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248

    Returns:
        list|Tensor: An empty array. In dynamic mode, ``array`` is a Python list. But in static mode, array is a Tensor
        whose ``VarType`` is ``LOD_TENSOR_ARRAY``.

    Examples:
        .. code-block:: python

            import paddle

            arr = paddle.tensor.create_array(dtype="float32")
            x = paddle.full(shape=[1, 3], fill_value=5, dtype="float32")
            i = paddle.zeros(shape=[1], dtype="int32")

            arr = paddle.tensor.array_write(x, i, array=arr)

            item = paddle.tensor.array_read(arr, i)
            print(item)     # [[5., 5., 5.]]

    """
249 250 251 252
    array = []
    if initialized_list is not None:
        if not isinstance(initialized_list, (list, tuple)):
            raise TypeError(
253 254 255 256
                "Require type(initialized_list) should be list/tuple, but received {}".format(
                    type(initialized_list)
                )
            )
257 258 259 260 261 262
        array = list(initialized_list)

    # NOTE: Only support plain list like [x, y,...], not support nested list in static mode.
    for val in array:
        if not isinstance(val, Variable):
            raise TypeError(
263 264 265 266
                "All values in `initialized_list` should be Variable, but recevied {}.".format(
                    type(val)
                )
            )
267 268 269 270 271 272 273 274

    if _non_static_mode():
        return array

    helper = LayerHelper("array", **locals())
    tensor_array = helper.create_variable(
        name="{0}.out".format(helper.name),
        type=core.VarDesc.VarType.LOD_TENSOR_ARRAY,
275 276
        dtype=dtype,
    )
277 278 279 280 281

    for val in array:
        array_write(x=val, i=array_length(tensor_array), array=tensor_array)

    return tensor_array