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


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

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

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

    Examples:

        .. code-block:: python

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

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