tensor.py 10.9 KB
Newer Older
1
#   Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
Y
yuyang18 已提交
9
# Unlessf required by applicable law or agreed to in writing, software
D
dzhwinter 已提交
10 11 12 13 14
# 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.

15
import paddle
16 17 18
import numpy
import warnings

Y
Yu Yang 已提交
19
from ..layer_helper import LayerHelper
20 21 22 23 24 25
from ..framework import (
    _current_expected_place,
    convert_np_dtype_to_dtype_,
    _varbase_creator,
    in_dygraph_mode,
)
X
xuwei06 已提交
26
from ..framework import Variable
27
from ..core import VarDesc
28
from .. import core
29
from .layer_function_generator import templatedoc
L
Leo Chen 已提交
30
from . import utils
31 32 33 34 35 36
from ..data_feeder import (
    check_variable_and_dtype,
    check_type,
    check_dtype,
    convert_dtype,
)
37
from paddle.utils import deprecated
38

39
from .utils import check_shape
40
from paddle import _C_ops, _legacy_C_ops
Y
Yu Yang 已提交
41 42

__all__ = [
43 44 45
    'fill_constant_batch_size_like',
    'fill_constant',
    'zeros',
Y
Yu Yang 已提交
46 47 48
]


49
def fill_constant(shape, dtype, value, force_cpu=False, out=None, name=None):
Y
Yu Yang 已提交
50
    """
S
swtkiwi 已提交
51

W
wangchaochaohu 已提交
52
    This OP creates a Tensor with specified `shape` and `dtype`, and
T
tianshuo78520a 已提交
53
    initializes it with a constant specified by `value`.
K
kavyasrinet 已提交
54

T
tianshuo78520a 已提交
55
    The attribute `stop_gradient` of the created Tensor is set to True.
56 57

    Args:
58 59 60
        shape(list|tuple|Tensor): Shape of the output Tensor, the data type of ``shape`` is int32 or int64.
            If ``shape`` is a list or tuple, the elements of it should be integers or Tensors with shape [1].
            If ``shape`` is an Tensor, it should be an 1-D Tensor with date type int32 or int64.
W
wangchaochaohu 已提交
61
        dtype(np.dtype|str): Data type of the output Tensor which can
62
            be float16, float32, float64, uint8, int16, int32, int64.
63
        value(bool|float|int|Tensor): The constant value used to initialize
64 65
            the Tensor to be created. If ``value`` is an Tensor, it should be an 1-D Tensor.
        force_cpu(bool, optional): data should be on CPU if it's true, default value is False.
66
        out(Tensor, optional): Optional output which can be any created
67 68
            Tensor that meets the requirements to store the result of operation.
            if ``out`` is None, a new Tensor will be create to store the result.
69 70
        name(str, optional): The default value is None.  Normally there is no need for user to set this
            property.  For more information, please refer to :ref:`api_guide_Name`.
71 72

    Returns:
73
        Tensor: Tensor which is created according to shape and dtype.
W
wangchaochaohu 已提交
74

75 76 77
    Examples:
        .. code-block:: python

78
          import paddle.fluid as fluid
79
          # attr shape is a list which doesn't contain  Tensor.
80 81
          data1 = fluid.layers.fill_constant(shape=[2,1], value=0, dtype='int64') # data1=[[0],[0]]
          data2 = fluid.layers.fill_constant(shape=[2,1], value=5, dtype='int64', out=data1)
82
          # data1=[[5], [5]] data2=[[5], [5]]
83

84
          # attr shape is a list which contains Tensor.
85
          positive_2 = fluid.layers.fill_constant([1], "int32", 2)
86
          data3 = fluid.layers.fill_constant(shape=[1, positive_2], dtype='float32', value=1.5) # data3=[[1.5, 1.5]]
87

88
          # attr shape is a Tensor.
89
          shape = fluid.layers.fill_constant([2], "int32", 2) # shape=[2,2]
90
          data4 = fluid.layers.fill_constant(shape=shape, dtype='bool', value=True) # data4=[[True,True],[True,True]]
91

92
          # attr value is a Tensor.
W
wangchaochaohu 已提交
93 94
          val = fluid.layers.fill_constant([1], "float32", 2.0) # val=[2.0]
          data5 = fluid.layers.fill_constant(shape=[2,1], value=val, dtype='float32') #data5=[[2.0],[2.0]]
Y
Yu Yang 已提交
95
    """
96

97 98 99 100 101
    if in_dygraph_mode():
        place = _current_expected_place()
        if force_cpu:
            place = core.CPUPlace()
        if isinstance(shape, (list, tuple)):
102
            shape = utils.convert_shape_to_list(shape)
103 104 105 106 107

        if not isinstance(dtype, core.VarDesc.VarType):
            dtype = convert_np_dtype_to_dtype_(dtype)

        if out is None:
108
            out = _C_ops.full(shape, float(value), dtype, place)
109 110 111
            out.stop_gradient = True
            return out

112 113
        if out is not None:
            # final state mode is support out is not None.
114
            _C_ops.full_(out, shape, float(value), dtype, place)
115 116
            out.stop_gradient = True
            return out
姜永久 已提交
117
    else:
118 119 120 121 122 123 124 125 126 127
        attrs = {'force_cpu': force_cpu}
        dtype = convert_dtype(dtype)
        if not isinstance(value, Variable):
            if dtype in ['uint8', 'int16', 'int32', 'int64']:
                attrs['str_value'] = str(int(value))
                attrs['value'] = int(value)
            else:
                attrs['str_value'] = str(float(value))
                attrs['value'] = float(value)

姜永久 已提交
128 129
        helper = LayerHelper("fill_constant", **locals())
        inputs = {}
130
        if isinstance(value, Variable):
姜永久 已提交
131
            if convert_dtype(value.dtype) != dtype:
132
                value = paddle.cast(value, dtype)
姜永久 已提交
133 134 135 136 137
            inputs['ValueTensor'] = value

        check_shape(shape)
        check_dtype(
            dtype,
138
            'dtype',
姜永久 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151
            [
                'bool',
                'float16',
                'float32',
                'float64',
                'uint8',
                'int16',
                'int32',
                'int64',
                'complex64',
                'complex128',
            ],
            'fill_constant',
152
        )
姜永久 已提交
153
        check_type(shape, 'shape', (Variable, list, tuple), 'fill_constant')
154

姜永久 已提交
155 156 157 158
        if out is not None:
            check_variable_and_dtype(
                out, 'out', [convert_dtype(dtype)], 'fill_constant'
            )
159

姜永久 已提交
160 161 162
        helper = LayerHelper("fill_constant", **locals())
        utils.get_shape_tensor_inputs(
            inputs=inputs, attrs=attrs, shape=shape, op_type='fill_constant'
163
        )
164

姜永久 已提交
165 166 167 168 169 170 171 172 173 174 175 176
        if out is None:
            out = helper.create_variable_for_type_inference(dtype=dtype)
        attrs['dtype'] = out.dtype
        helper.append_op(
            type='fill_constant',
            inputs=inputs,
            outputs={'Out': [out]},
            attrs=attrs,
            stop_gradient=True,
        )
        out.stop_gradient = True
        return out
Y
Yu Yang 已提交
177 178


179
@deprecated(since='1.8.0', update_to="paddle.fluid.layers.fill_constant")
Y
yuyang18 已提交
180
@templatedoc()
181 182 183 184 185 186 187 188 189
def fill_constant_batch_size_like(
    input,
    shape,
    dtype,
    value,
    input_dim_idx=0,
    output_dim_idx=0,
    force_cpu=False,
):
190
    """
T
tianshuo78520a 已提交
191
    This OP creates a Tesnor according the shape and dtype, and initializes the
W
wangchaochaohu 已提交
192 193 194 195
    Tensor with the constants provided in ``value``. When the input is LoDTensor
    and the input_dim_idx is 0, the output_dim_idx dimension is set to the value
    of the batch_size input by the input, the Stop_gradient attribute of the created
    Tensor is False by default.
196 197

    Args:
W
wangchaochaohu 已提交
198 199 200 201 202
        input(Variable): Tensor which data type is float32, float64, int32 and int64.
        shape(list): The shape of Tensor to be created, Tensor's shape may be changed
            according the input.
        dtype(np.dtype|core.VarDesc.VarType|str): The data type of created Tensor which
            can be float32, float64, int32, int64.
203
        value(float|int): The constant value used to initialize the Tensor to be created.
W
wangchaochaohu 已提交
204 205 206 207 208
        input_dim_idx(int): When the value is 0 and the input is LoDTensor, the output_dim_idx
            dimension of the created Tensor is set to the batch_size value of input.
            The default value is 0.
        output_dim_idx(int): Used to specify which dimension of Tensor is created to be set
            the value of batch_size of input Tensor. The default value is 0.
T
tianshuo78520a 已提交
209
        force_cpu(bool): data should be on CPU if it's true, default value is False.
Y
yuyang18 已提交
210 211

    Returns:
W
wangchaochaohu 已提交
212
        Variable: Tensor which will be created according to dtype.
H
haowang101779990 已提交
213 214 215 216 217

    Examples:

        .. code-block:: python

218
             import paddle.fluid as fluid
W
wangchaochaohu 已提交
219
             like = fluid.layers.fill_constant(shape=[1,2], value=10, dtype='int64') #like=[[10, 10]]
W
wangchaochaohu 已提交
220
             data = fluid.layers.fill_constant_batch_size_like(
W
wangchaochaohu 已提交
221
                    input=like, shape=[1], value=0, dtype='int64') #like=[[10, 10]] data=[0]
H
haowang101779990 已提交
222

223
    """
224 225 226 227 228 229 230
    if in_dygraph_mode():
        if not isinstance(dtype, core.VarDesc.VarType):
            dtype = convert_np_dtype_to_dtype_(dtype)

        place = _current_expected_place()
        if force_cpu:
            place = core.CPUPlace()
231 232 233
        out = _C_ops.full_batch_size_like(
            input, shape, dtype, value, input_dim_idx, output_dim_idx, place
        )
234 235
        out.stop_gradient = True
        return out
236
    else:
姜永久 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
        helper = LayerHelper("fill_constant_batch_size_like", **locals())
        out = helper.create_variable_for_type_inference(dtype=dtype)
        attrs = {
            'shape': shape,
            'dtype': out.dtype,
            'value': float(value),
            'input_dim_idx': input_dim_idx,
            'output_dim_idx': output_dim_idx,
            'force_cpu': force_cpu,
        }
        if convert_dtype(dtype) in ['int64', 'int32']:
            attrs['str_value'] = str(int(value))
        else:
            attrs['str_value'] = str(float(value))
        helper.append_op(
            type='fill_constant_batch_size_like',
            inputs={'Input': input},
            outputs={'Out': [out]},
            attrs=attrs,
        )
        out.stop_gradient = True
        return out
Y
Yu Yang 已提交
259 260


261
def zeros(shape, dtype, force_cpu=False, name=None):
Y
Yu Yang 已提交
262
    """
263 264
    The OP creates a tensor of specified :attr:`shape` and :attr:`dtype`, and fills it with 0.
    Its :attr:`stop_gradient` will be set to True to stop gradient computation.
265

266
    Parameters:
267
        shape(tuple|list|Tensor): Shape of output Tensor, the data type of ``shape`` is int32 or int64.
W
wangchaochaohu 已提交
268
        dtype (np.dtype|str): Data type of output Tensor, it supports
269
            bool, float16, float32, float64, int32 and int64.
270 271
        force_cpu (bool, optional): Whether force to store the output Tensor in CPU memory.
            If :attr:`force_cpu` is False, the output Tensor will be stored in running device memory.
272
            Default: False.
273 274
        name(str, optional): The default value is None.  Normally there is no need for user to set this
            property.  For more information, please refer to :ref:`api_guide_Name`.
275 276

    Returns:
277
        Tensor: A tensor of data type :attr:`dtype` with shape :attr:`shape` and all elements set to 0.
278 279 280 281

    Examples:
        .. code-block:: python

282
          import paddle.fluid as fluid
283
          data = fluid.layers.zeros(shape=[3, 2], dtype='float32') # [[0., 0.], [0., 0.], [0., 0.]]
284

285 286 287
          # shape is a Tensor
          shape = fluid.layers.fill_constant(shape=[2], dtype='int32', value=2)
          data1 = fluid.layers.zeros(shape=shape, dtype='int32') #[[0, 0], [0, 0]]
Y
Yu Yang 已提交
288 289
    """
    return fill_constant(value=0.0, **locals())