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
30 31 32 33 34 35
from ..data_feeder import (
    check_variable_and_dtype,
    check_type,
    check_dtype,
    convert_dtype,
)
36
from paddle.utils import deprecated
37

38
from paddle import _C_ops, _legacy_C_ops
Y
Yu Yang 已提交
39 40

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


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

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

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

    Args:
56 57 58
        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 已提交
59
        dtype(np.dtype|str): Data type of the output Tensor which can
60
            be float16, float32, float64, uint8, int16, int32, int64.
61
        value(bool|float|int|Tensor): The constant value used to initialize
62 63
            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.
64
        out(Tensor, optional): Optional output which can be any created
65 66
            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.
67 68
        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`.
69 70

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

73 74 75
    Examples:
        .. code-block:: python

76
          import paddle.fluid as fluid
77
          # attr shape is a list which doesn't contain  Tensor.
78 79
          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)
80
          # data1=[[5], [5]] data2=[[5], [5]]
81

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

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

90
          # attr value is a Tensor.
W
wangchaochaohu 已提交
91 92
          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 已提交
93
    """
94

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

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

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

110 111
        if out is not None:
            # final state mode is support out is not None.
112
            _C_ops.full_(out, shape, float(value), dtype, place)
113 114
            out.stop_gradient = True
            return out
姜永久 已提交
115
    else:
116 117 118 119 120 121 122 123 124 125
        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)

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

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

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

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

姜永久 已提交
164 165 166 167 168 169 170 171 172 173 174 175
        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 已提交
176 177


178
@deprecated(since='1.8.0', update_to="paddle.fluid.layers.fill_constant")
Y
yuyang18 已提交
179
@templatedoc()
180 181 182 183 184 185 186 187 188
def fill_constant_batch_size_like(
    input,
    shape,
    dtype,
    value,
    input_dim_idx=0,
    output_dim_idx=0,
    force_cpu=False,
):
189
    """
T
tianshuo78520a 已提交
190
    This OP creates a Tesnor according the shape and dtype, and initializes the
W
wangchaochaohu 已提交
191 192 193 194
    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.
195 196

    Args:
W
wangchaochaohu 已提交
197 198 199 200 201
        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.
202
        value(float|int): The constant value used to initialize the Tensor to be created.
W
wangchaochaohu 已提交
203 204 205 206 207
        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 已提交
208
        force_cpu(bool): data should be on CPU if it's true, default value is False.
Y
yuyang18 已提交
209 210

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

    Examples:

        .. code-block:: python

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

222
    """
223 224 225 226 227 228 229
    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()
230 231 232
        out = _C_ops.full_batch_size_like(
            input, shape, dtype, value, input_dim_idx, output_dim_idx, place
        )
233 234
        out.stop_gradient = True
        return out
235
    else:
姜永久 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
        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 已提交
258 259


260
def zeros(shape, dtype, force_cpu=False, name=None):
Y
Yu Yang 已提交
261
    """
262 263
    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.
264

265
    Parameters:
266
        shape(tuple|list|Tensor): Shape of output Tensor, the data type of ``shape`` is int32 or int64.
W
wangchaochaohu 已提交
267
        dtype (np.dtype|str): Data type of output Tensor, it supports
268
            bool, float16, float32, float64, int32 and int64.
269 270
        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.
271
            Default: False.
272 273
        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`.
274 275

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

    Examples:
        .. code-block:: python

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

284 285 286
          # 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 已提交
287 288
    """
    return fill_constant(value=0.0, **locals())