input.py 9.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 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.

15
from paddle import _C_ops, _legacy_C_ops
16 17

from ...fluid.data_feeder import check_variable_and_dtype
J
Jiabin Yang 已提交
18
from ...fluid.framework import _in_legacy_dygraph, in_dygraph_mode
19 20
from ...fluid.layer_helper import LayerHelper
from ...static import Variable
21

22 23
__all__ = []

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

def one_hot(x, num_classes, name=None):
    """

    The operator converts each id in the input 'x' to an one-hot vector with a
    num_classes length. The value in the vector dimension corresponding to the id
    is 1, and the value in the remaining dimension is 0.

    The shape of output Tensor is generated by appending num_classes dimension
    behind the last dimension of the 'x' shape.

    .. code-block:: text

        Example 1:

        input:
            x.shape = [4]
            x.data = [1, 1, 3, 0]
            num_classes = 4

        output:
            Out.shape = [4, 4]
            Out.data = [[0., 1., 0., 0.],
                        [0., 1., 0., 0.],
                        [0., 0., 0., 1.],
                        [1., 0., 0., 0.]]

        Example 2:

        input:
            x.shape = [4]
            x.data = [1, 1, 5, 0]
            num_classes = 4

        output: Throw an exception for Illegal value
            The second dimension in X is 5, which is greater than num_classes,
            so it throws an exception.


    Args:
        x(Tensor): Tensor with shape :math:`[N_1, N_2, ..., N_k]` ,
            which contains at least one dimension. The data type is int32 or int64.
        num_classes(int): An integer defining the num_classes of the one hot dimension. If input 'x'
            is word id, num_classes is generally the dictionary size.

    Returns:
        Tensor: The one-hot representations of 'x'. A Tensor with type float32.

    Examples:
        .. code-block:: python

75
            import paddle
76
            # Correspond to the first example above, where label.shape is 4 and one_hot_label.shape is [4, 4].
Y
yukavio 已提交
77
            label = paddle.to_tensor([1, 1, 3, 0], dtype='int64')
78
            # label.shape = [4]
Y
yukavio 已提交
79
            one_hot_label = paddle.nn.functional.one_hot(label, num_classes=4)
80
            # one_hot_label.shape = [4, 4]
Y
yukavio 已提交
81 82 83 84
            # one_hot_label = [[0., 1., 0., 0.],
            #                  [0., 1., 0., 0.],
            #                  [0., 0., 0., 1.],
            #                  [1., 0., 0., 0.]]
T
tangwei12 已提交
85

86 87
    """

J
Jiabin Yang 已提交
88
    if in_dygraph_mode():
89
        return _C_ops.one_hot(x, num_classes)
90
    else:
J
Jiabin Yang 已提交
91
        if _in_legacy_dygraph():
92 93 94
            return _legacy_C_ops.one_hot_v2(
                x, 'depth', num_classes, 'allow_out_of_range', False
            )
95
        else:
96 97 98
            check_variable_and_dtype(
                x, 'input', ['int32', 'int64'], 'one_hot_v2'
            )
J
Jiabin Yang 已提交
99 100 101
            helper = LayerHelper("one_hot_v2", **locals())

            one_hot_out = helper.create_variable_for_type_inference(
102 103
                dtype='float32'
            )
J
Jiabin Yang 已提交
104 105 106 107 108 109 110 111
            if not isinstance(num_classes, Variable):
                # user attribute
                inputs = {'X': x}
                attrs = {'depth': num_classes, 'allow_out_of_range': False}
            else:
                num_classes.stop_gradient = True
                inputs = {'X': x, 'depth_tensor': num_classes}
                attrs = {'allow_out_of_range': False}
112 113 114 115 116 117 118
            helper.append_op(
                type="one_hot_v2",
                inputs=inputs,
                attrs=attrs,
                outputs={'Out': one_hot_out},
                stop_gradient=True,
            )
J
Jiabin Yang 已提交
119
            return one_hot_out
T
tangwei12 已提交
120 121 122


def embedding(x, weight, padding_idx=None, sparse=False, name=None):
123
    r"""
124
    Used to lookup embeddings vector of ids provided by :attr:`x` .
T
tangwei12 已提交
125 126 127

    The shape of output Tensor is generated by appending the last dimension of the input Tensor shape
    with embedding size.
T
tangwei12 已提交
128

129 130 131
    Note:
        The id in :attr:`x` must satisfy :math:`0 =< id < weight.shape[0]` ,
        otherwise the program will throw an exception and exit.
T
tangwei12 已提交
132 133

    .. code-block:: text
134

T
tangwei12 已提交
135
            x is a Tensor.
T
tangwei12 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149
                padding_idx = -1
                x.data = [[1, 3], [2, 4], [4, 127]]
                x.shape = [3, 2]
                weight.shape = [128, 16]
            output is a Tensor:
                out.shape = [3, 2, 16]
                out.data = [[[0.129435295, 0.244512452, ..., 0.436322452],
                            [0.345421456, 0.524563927, ..., 0.144534654]],
                            [[0.345249859, 0.124939536, ..., 0.194353745],
                            [0.945345345, 0.435394634, ..., 0.435345365]],
                            [[0.945345345, 0.435394634, ..., 0.435345365],
                            [0.0,         0.0,         ..., 0.0        ]]]  # padding data

            The input padding_idx is less than 0, it is automatically converted to padding_idx = -1 + 128 = 127
T
tangwei12 已提交
150
            It will pad all-zero data when id is 127.
T
tangwei12 已提交
151 152 153 154 155 156

    Args:
        x(Tensor): A Tensor with type int32/int64, which contains the id information. The value of the input id should
            satisfy :math:`0<= id < weight.shape[0]` .
        weight (Tensor): The weight. A Tensor with shape of lookup table parameter. It should have two elements which
            indicates the size of the dictionary of embeddings and the size of each embedding vector respectively.
157
        sparse(bool, optional): The flag indicating whether to use sparse update. This parameter only
T
tangwei12 已提交
158 159
            affects the performance of the backwards gradient update. It is recommended to set
            True because sparse update is faster. But some optimizers does not support sparse update,
T
tangwei12 已提交
160
            such as :ref:`api_paddle_optimizer_adadelta_Adadelta` , :ref:`api_paddle_optimizer_adamax_Adamax` , :ref:`api_paddle_optimizer_lamb_Lamb`.
T
tangwei12 已提交
161
            In these cases, sparse must be False. Default: False.
162
        padding_idx(int|long|None, optional): padding_idx needs to be in the interval [-weight.shape[0], weight.shape[0]).
T
tangwei12 已提交
163
            If :math:`padding\_idx < 0`, the :math:`padding\_idx` will automatically be converted
T
tangwei12 已提交
164
            to :math:`weight.shape[0] + padding\_idx` . It will output all-zero padding data whenever lookup
T
tangwei12 已提交
165 166
            encounters :math:`padding\_idx` in id. And the padding data will not be updated while training.
            If set None, it makes no effect to output. Default: None.
167
        name(str|None, optional): For detailed information, please refer
T
tangwei12 已提交
168 169 170 171
           to :ref:`api_guide_Name`. Usually name is no need to set and
           None by default.

    Returns:
T
tangwei12 已提交
172
        Tensor: Embedding Tensor  mapped by x. The data type is the same as :attr:`weight`.
T
tangwei12 已提交
173 174 175 176

    Examples:

        .. code-block:: python
177

T
tangwei12 已提交
178 179 180
            import paddle
            import paddle.nn as nn

181 182
            x0 = paddle.arange(3, 6).reshape((3, 1)).astype(paddle.int64)
            w0 = paddle.full(shape=(10, 3), fill_value=2).astype(paddle.float32)
T
tangwei12 已提交
183

T
tangwei12 已提交
184 185 186
            # x.data = [[3], [4], [5]]
            # x.shape = [3, 1]
            x = paddle.to_tensor(x0, stop_gradient=False)
T
tangwei12 已提交
187

T
tangwei12 已提交
188 189 190
            # w.data = [[2. 2. 2.] ... [2. 2. 2.]]
            # w.shape = [10, 3]
            w = paddle.to_tensor(w0, stop_gradient=False)
T
tangwei12 已提交
191

T
tangwei12 已提交
192 193 194 195
            # emb.data = [[[2., 2., 2.]], [[2., 2., 2.]], [[2., 2., 2.]]]
            # emb.shape = [3, 1, 3]
            emb = nn.functional.embedding(
                    x=x, weight=w, sparse=True, name="embedding")
T
tangwei12 已提交
196 197

    """
198 199 200 201 202 203 204
    padding_idx = (
        -1
        if padding_idx is None
        else padding_idx
        if padding_idx >= 0
        else (weight.shape[0] + padding_idx)
    )
205 206

    if padding_idx >= weight.shape[0] or padding_idx < -weight.shape[0]:
207 208 209 210 211
        raise ValueError(
            "padding_idx must be within [-{}, {})".format(
                weight.shape[0], weight.shape[0]
            )
        )
212

Z
zyfncg 已提交
213
    if in_dygraph_mode():
214
        return _C_ops.embedding(x, weight, padding_idx, sparse)
Z
zyfncg 已提交
215
    elif _in_legacy_dygraph():
216 217 218 219 220 221 222 223 224 225 226 227
        return _legacy_C_ops.lookup_table_v2(
            weight,
            x,
            'is_sparse',
            sparse,
            'is_distributed',
            False,
            'remote_prefetch',
            False,
            'padding_idx',
            padding_idx,
        )
T
tangwei12 已提交
228 229
    else:
        helper = LayerHelper('embedding', **locals())
230
        dtype = helper.input_dtype(input_param_name='weight')
T
tangwei12 已提交
231

232 233 234 235 236 237
        check_variable_and_dtype(
            x,
            'input',
            ['uint8', 'int8', 'int16', 'int32', 'int64'],
            'embedding',
        )
T
tangwei12 已提交
238 239 240 241 242

        is_distributed = False
        remote_prefetch = sparse and (not is_distributed)

        tmp = helper.create_variable_for_type_inference(dtype)
T
tangwei12 已提交
243

244 245 246 247 248 249 250 251 252 253 254
        helper.append_op(
            type='lookup_table_v2',
            inputs={'Ids': x, 'W': weight},
            outputs={'Out': tmp},
            attrs={
                'is_sparse': sparse,
                'is_distributed': is_distributed,
                'remote_prefetch': remote_prefetch,
                'padding_idx': padding_idx,
            },
        )
T
tangwei12 已提交
255
        return tmp