tensor.py 5.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
    'fill_constant_batch_size_like',
    'zeros',
Y
Yu Yang 已提交
43 44 45
]


46
@deprecated(since='1.8.0', update_to="paddle.fluid.layers.fill_constant")
Y
yuyang18 已提交
47
@templatedoc()
48 49 50 51 52 53 54 55 56
def fill_constant_batch_size_like(
    input,
    shape,
    dtype,
    value,
    input_dim_idx=0,
    output_dim_idx=0,
    force_cpu=False,
):
57
    """
T
tianshuo78520a 已提交
58
    This OP creates a Tesnor according the shape and dtype, and initializes the
W
wangchaochaohu 已提交
59 60 61 62
    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.
63 64

    Args:
W
wangchaochaohu 已提交
65 66 67 68 69
        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.
70
        value(float|int): The constant value used to initialize the Tensor to be created.
W
wangchaochaohu 已提交
71 72 73 74 75
        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 已提交
76
        force_cpu(bool): data should be on CPU if it's true, default value is False.
Y
yuyang18 已提交
77 78

    Returns:
W
wangchaochaohu 已提交
79
        Variable: Tensor which will be created according to dtype.
H
haowang101779990 已提交
80 81 82 83 84

    Examples:

        .. code-block:: python

85
             import paddle
86
             import paddle.fluid as fluid
87
             like = paddle.full(shape=[1,2], fill_value=10, dtype='int64') #like=[[10, 10]]
W
wangchaochaohu 已提交
88
             data = fluid.layers.fill_constant_batch_size_like(
W
wangchaochaohu 已提交
89
                    input=like, shape=[1], value=0, dtype='int64') #like=[[10, 10]] data=[0]
H
haowang101779990 已提交
90

91
    """
92 93 94 95 96 97 98
    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()
99 100 101
        out = _C_ops.full_batch_size_like(
            input, shape, dtype, value, input_dim_idx, output_dim_idx, place
        )
102 103
        out.stop_gradient = True
        return out
104
    else:
姜永久 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
        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 已提交
127 128


129
def zeros(shape, dtype, force_cpu=False, name=None):
Y
Yu Yang 已提交
130
    """
131 132
    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.
133

134
    Parameters:
135
        shape(tuple|list|Tensor): Shape of output Tensor, the data type of ``shape`` is int32 or int64.
W
wangchaochaohu 已提交
136
        dtype (np.dtype|str): Data type of output Tensor, it supports
137
            bool, float16, float32, float64, int32 and int64.
138 139
        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.
140
            Default: False.
141 142
        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`.
143 144

    Returns:
145
        Tensor: A tensor of data type :attr:`dtype` with shape :attr:`shape` and all elements set to 0.
146 147 148 149

    Examples:
        .. code-block:: python

150
          import paddle.fluid as fluid
151
          import paddle
152
          data = fluid.layers.zeros(shape=[3, 2], dtype='float32') # [[0., 0.], [0., 0.], [0., 0.]]
153

154
          # shape is a Tensor
155
          shape = paddle.full(shape=[2], dtype='int32', fill_value=2)
156
          data1 = fluid.layers.zeros(shape=shape, dtype='int32') #[[0, 0], [0, 0]]
Y
Yu Yang 已提交
157
    """
158 159 160 161 162 163
    # TODO: remove zeros
    from paddle.tensor import fill_constant

    return fill_constant(
        value=0.0, shape=shape, dtype=dtype, force_cpu=force_cpu, name=name
    )