nn.py 14.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
# Copyright (c) 2018 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.
Y
Yu Yang 已提交
14
"""
15
All layers just related to the neural network.
Y
Yu Yang 已提交
16
"""
P
peizhilin 已提交
17
import os
S
sneaxiy 已提交
18
import inspect
19 20 21 22 23
import warnings

import numpy as np

import paddle
Y
Yu Yang 已提交
24
from ..layer_helper import LayerHelper
25 26 27 28 29 30 31 32 33 34 35
from ..framework import (
    Variable,
    OpProtoHolder,
    dygraph_only,
    _dygraph_tracer,
    default_main_program,
    _varbase_creator,
    static_only,
    _global_flags,
    in_dygraph_mode,
)
36
from ..framework import _current_expected_place
37
from .. import dygraph_utils
Y
yangyaming 已提交
38
from ..param_attr import ParamAttr
39 40 41 42 43
from .layer_function_generator import (
    autodoc,
    templatedoc,
    _generate_doc_string_,
)
44

F
fengjiayi 已提交
45
from .. import unique_name
46
from .. import core
47
from ...utils import deprecated
48 49 50 51 52 53
from ..data_feeder import (
    convert_dtype,
    check_variable_and_dtype,
    check_type,
    check_dtype,
)
54
from paddle.utils import deprecated
55
from paddle import _C_ops, _legacy_C_ops
56 57
from collections.abc import Iterable

Y
Yu Yang 已提交
58 59

__all__ = [
X
Xin Pan 已提交
60 61
    'embedding',
    'autoincreased_step_counter',
Y
Yu Yang 已提交
62 63
]

64

T
tangwei12 已提交
65
@deprecated(since="2.0.0", update_to="paddle.nn.functional.embedding")
66 67 68 69 70 71 72 73 74
def embedding(
    input,
    size,
    is_sparse=False,
    is_distributed=False,
    padding_idx=None,
    param_attr=None,
    dtype='float32',
):
75
    r"""
76
    :api_attr: Static Graph
77

78 79 80 81 82 83 84 85 86 87 88 89
    **WARING:** This OP will be deprecated in a future release. This OP requires the
    last dimension of Tensor shape must be equal to 1. It is recommended to use
    fluid. :ref:`api_fluid_embedding` .

    The operator is used to lookup embeddings vector of ids provided by :attr:`input` .
    It automatically constructs a 2D embedding matrix based on the
    input :attr:`size` (vocab_size, emb_size) and :attr:`dtype` .

    This OP requires the last dimension of Tensor shape must be equal to 1. The shape
    of output Tensor is generated by replacing the last dimension of the input Tensor shape
    with emb_size.

90
    **Note:** The id in :attr:`input` must satisfy :math:`0 =< id < size[0]` ,
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
    otherwise the program will throw an exception and exit.

    .. code-block:: text

        Case 1:

        input is a Tensor. padding_idx = -1
            input.data = [[[1], [3]], [[2], [4]], [[4], [127]]]
            input.shape = [3, 2, 1]
        Given size = [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]],
108

109 110 111 112
                        [[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
        It will pad all-zero data when ids is 127.
113

114
        Case 2:
115

116 117 118 119 120 121 122 123 124 125 126 127 128 129
        input is a LoDTensor with 1-level LoD. padding_idx = 0
            input.lod = [[2, 3]]
            input.data = [[1], [3], [2], [4], [0]]
            input.shape = [5, 1]
        Given size = [128, 16]
        output is a LoDTensor:
            out.lod = [[2, 3]]
            out.shape = [5, 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.0,         0.0,         ..., 0.0        ]]  # padding data
        It will pad all-zero data when ids is 0.
Y
Yu Yang 已提交
130 131

    Args:
132 133 134 135 136 137
        input(Variable): A Tensor or LoDTensor with type int64, which contains the id information.
            The last dimension of Tensor shape must be equal to 1. The value of the input id should
            satisfy :math:`0<= id < size[0]` .
        size(tuple|list): The 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.
        is_sparse(bool): The flag indicating whether to use sparse update. This parameter only
138
            affects the performance of the backwards gradient update. It is recommended to set
139
            True because sparse update is faster. But some optimizer does not support sparse update,
140
            such as :ref:`api_fluid_optimizer_AdadeltaOptimizer` , :ref:`api_fluid_optimizer_AdamaxOptimizer` ,
141 142 143 144 145
            :ref:`api_fluid_optimizer_DecayedAdagradOptimizer` , :ref:`api_fluid_optimizer_FtrlOptimizer` ,
            :ref:`api_fluid_optimizer_LambOptimizer` and :ref:`api_fluid_optimizer_LarsMomentumOptimizer` .
            In these case, is_sparse must be False. Default: False.
        is_distributed(bool): Whether to store the embedding matrix in a distributed manner. Only used
            in multi-machine distributed CPU training. Default: False.
146
        padding_idx(int|long|None): padding_idx needs to be in the interval [-vocab_size, vocab_size).
147 148 149 150 151 152
            If :math:`padding\_idx < 0`, the :math:`padding\_idx` will automatically be converted
            to :math:`vocab\_size + padding\_idx` . It will output all-zero padding data whenever lookup
            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.
        param_attr(ParamAttr): To specify the weight parameter property. Default: None, which means the
            default weight parameter property is used. See usage for details in :ref:`api_fluid_ParamAttr` . In addition,
153
            user-defined or pre-trained word vectors can be loaded with the :attr:`param_attr` parameter.
154
            The local word vector needs to be transformed into numpy format, and the shape of local word
T
tianshuo78520a 已提交
155
            vector should be consistent with :attr:`size` . Then :ref:`api_fluid_initializer_NumpyArrayInitializer`
156 157 158
            is used to load custom or pre-trained word vectors. See code example 2 for details.
        dtype(str|core.VarDesc.VarType): It refers to the data type of output Tensor.
            It must be float32 or float64. Default: float32.
Y
Yu Yang 已提交
159

160
    Returns:
161
        Variable: Embedding Tensor or LoDTensor mapped by input. The data type is the same as :attr:`dtype` .
Y
Yu Yang 已提交
162

163 164
    Examples:
        .. code-block:: python
Y
Yu Yang 已提交
165

B
bdzhuxiaoning 已提交
166
          import paddle.fluid as fluid
167
          import numpy as np
168 169
          import paddle
          paddle.enable_static()
170

171
          data = paddle.static.data(name='x', shape=[None, 1], dtype='int64')
172

T
tianshuo78520a 已提交
173
          # example 1
174
          emb_1 = paddle.static.nn.embedding(input=data, size=[128, 64])
175 176 177 178 179 180

          # example 2: load custom or pre-trained word vectors
          weight_data = np.random.random(size=(128, 100))  # word vectors with numpy format
          w_param_attrs = fluid.ParamAttr(
              name="emb_weight",
              learning_rate=0.5,
181
              initializer=paddle.nn.initializer.Assign(weight_data),
182
              trainable=True)
183
          emb_2 = fluid.layers.embedding(input=data, size=(128, 100), param_attr=w_param_attrs, dtype='float32')
Y
Yu Yang 已提交
184 185 186
    """

    helper = LayerHelper('embedding', **locals())
187 188 189 190 191 192 193 194 195
    check_variable_and_dtype(
        input, 'input', ['int64'], 'fluid.layers.embedding'
    )
    check_dtype(
        dtype,
        'dtype',
        ['uint16', 'float16', 'float32', 'float64'],
        'fluid.layers.embedding',
    )
196 197 198 199 200 201 202 203 204

    if is_distributed:
        is_distributed = False
        warnings.warn(
            "is_distributed is go out of use, `fluid.contrib.layers.sparse_embedding` is your needed"
        )

    remote_prefetch = True if is_sparse else False

205 206 207
    w = helper.create_parameter(
        attr=helper.param_attr, shape=size, dtype=dtype, is_bias=False
    )
X
Xin Pan 已提交
208
    tmp = helper.create_variable_for_type_inference(dtype)
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    padding_idx = (
        -1
        if padding_idx is None
        else padding_idx
        if padding_idx >= 0
        else (size[0] + padding_idx)
    )
    helper.append_op(
        type='lookup_table',
        inputs={'Ids': input, 'W': w},
        outputs={'Out': tmp},
        attrs={
            'is_sparse': is_sparse,
            'is_distributed': is_distributed,
            'remote_prefetch': remote_prefetch,
            'padding_idx': padding_idx,
        },
    )
Y
Yu Yang 已提交
227 228 229
    return tmp


230 231 232
def _pull_gpups_sparse(
    input, size, dtype='float32', is_distributed=False, is_sparse=False
):
Y
yaoxuefeng 已提交
233 234 235 236 237 238 239 240 241 242 243 244 245
    r"""
    **Pull GpuPS Sparse Layer**

    This layer is used to lookup embeddings of IDs, provided by :attr:`input`, in
    GpuPS lookup table. The result of this lookup is the embedding of each ID in the
    :attr:`input`.

    Args:
        input(Variable|list of Variable): Input is a Tensor<int64> Variable, which
            contains the IDs information.
        size(int|list of int): The embedding size parameter of each input, which indicates the size of
            each embedding vector respectively.
        dtype(str): The dtype refers to the data type of output tensor. Only supports
246
        float32 now.
Y
yaoxuefeng 已提交
247 248 249 250 251 252 253 254 255 256

    Returns:
        Variable|list of Variable: The tensor variable storing the embeddings of the \
                  supplied inputs, whose size are indicated by size respectively.

    Examples:
        .. code-block:: python

          import paddle.fluid as fluid
          slots = []
G
GGBond8488 已提交
257
          data_1 = paddle.static.data(name='sequence', shape=[-1,1], dtype='int64', lod_level=1)
Y
yaoxuefeng 已提交
258
          slots.append(data_1)
G
GGBond8488 已提交
259
          data_2 = paddle.static.data(name='sequence', shape=[-1,1], dtype='int64', lod_level=1)
Y
yaoxuefeng 已提交
260 261 262 263 264 265
          slots.append(data_2)
          embs = fluid.layers.pull_gpups_sparse(input=slots, size=[11, 35])
    """
    helper = LayerHelper('pull_gpups_sparse', **locals())
    if dtype != 'float32':
        raise ValueError(
266 267 268
            "GpuPS only support float type embedding now, and your type is: "
            + dtype
        )
Y
yaoxuefeng 已提交
269 270 271 272 273 274
    helper.input_dtype()
    inputs = helper.multiple_input()
    outs = [
        helper.create_variable_for_type_inference(dtype)
        for i in range(len(inputs))
    ]
275 276 277 278 279 280 281 282 283 284 285 286 287
    w = helper.create_parameter(
        attr=helper.param_attr, shape=[size[0]], dtype=dtype, is_bias=False
    )
    helper.append_op(
        type='pull_gpups_sparse',
        inputs={'Ids': inputs, 'W': w},
        outputs={'Out': outs},
        attrs={
            'size': size,
            'is_distributed': is_distributed,
            'is_sparse': is_sparse,
        },
    )
Y
yaoxuefeng 已提交
288
    if len(outs) == 1:
289 290 291 292
        return outs[0]
    return outs


293 294 295
def _pull_box_sparse(
    input, size, dtype='float32', is_distributed=False, is_sparse=False
):
296
    r"""
H
hutuxian 已提交
297 298 299 300 301 302 303
    **Pull Box Sparse Layer**

    This layer is used to lookup embeddings of IDs, provided by :attr:`input`, in
    BoxPS lookup table. The result of this lookup is the embedding of each ID in the
    :attr:`input`.

    Args:
304
        input(Variable|list of Variable): Input is a Tensor<int64> Variable, which
H
hutuxian 已提交
305
            contains the IDs information.
306
        size(int): The embedding size parameter, which indicates the size of
H
hutuxian 已提交
307
            each embedding vector respectively.
308
        dtype(str): The dtype refers to the data type of output tensor. Only supports
309
        float32 now.
H
hutuxian 已提交
310 311 312 313 314 315 316 317 318

    Returns:
        Variable|list of Variable: The tensor variable storing the embeddings of the \
                  supplied inputs.

    Examples:
        .. code-block:: python

          import paddle.fluid as fluid
G
GGBond8488 已提交
319
          data = paddle.static.data(name='sequence', shape=[-1,1], dtype='int64', lod_level=1)
320
          emb = fluid.layers.pull_box_sparse(input=data, size=[11])
H
hutuxian 已提交
321 322 323 324
    """
    helper = LayerHelper('pull_box_sparse', **locals())
    if dtype != 'float32':
        raise ValueError(
325 326 327
            "BoxPS only support float type embedding now, and your type is: "
            + dtype
        )
H
hutuxian 已提交
328 329 330 331 332 333
    helper.input_dtype()
    inputs = helper.multiple_input()
    outs = [
        helper.create_variable_for_type_inference(dtype)
        for i in range(len(inputs))
    ]
334 335 336 337 338 339 340 341 342 343 344 345 346
    w = helper.create_parameter(
        attr=helper.param_attr, shape=[size], dtype=dtype, is_bias=False
    )
    helper.append_op(
        type='pull_box_sparse',
        inputs={'Ids': inputs, 'W': w},
        outputs={'Out': outs},
        attrs={
            'size': size,
            'is_distributed': is_distributed,
            'is_sparse': is_sparse,
        },
    )
H
hutuxian 已提交
347 348 349 350 351
    if len(outs) == 1:
        return outs[0]
    return outs


Y
Yu Yang 已提交
352
def autoincreased_step_counter(counter_name=None, begin=1, step=1):
Y
Yu Yang 已提交
353
    """
354 355
    :api_attr: Static Graph

356 357
    Create an auto-increase variable. which will be automatically increased
    by 1 in every iteration. By default, the first return of this counter is 1,
Y
Yibing Liu 已提交
358
    and the step size is 1.
Y
Yu Yang 已提交
359 360

    Args:
Y
Yibing Liu 已提交
361 362 363
        counter_name(str, optional): The counter name. Default '@STEP_COUNTER@'.
        begin(int, optional): The first return value of this counter. Default 1.
        step(int, optional): The step size. Default 1.
Y
Yu Yang 已提交
364

365
    Returns:
Y
Yibing Liu 已提交
366
        Variable: The auto-increased Variable with data type int64.
Y
yi.wu 已提交
367 368 369 370

    Examples:
        .. code-block:: python

371
           import paddle.fluid as fluid
372 373
           import paddle
           paddle.enable_static()
Y
yi.wu 已提交
374
           global_step = fluid.layers.autoincreased_step_counter(
Y
Yibing Liu 已提交
375
               counter_name='@LR_DECAY_COUNTER@', begin=0, step=1)
Y
Yu Yang 已提交
376 377
    """
    helper = LayerHelper('global_step_counter')
Y
Yu Yang 已提交
378 379
    if counter_name is None:
        counter_name = '@STEP_COUNTER@'
Y
Yu Yang 已提交
380
    counter, is_new_var = helper.create_or_get_global_variable(
H
hong 已提交
381 382 383 384
        name=counter_name,
        dtype='int64',
        shape=[1],
        persistable=True,
385 386
        belong_to_optimizer=True,
    )
Y
Yu Yang 已提交
387
    if is_new_var:
388
        helper.set_variable_initializer(
389 390 391 392
            counter,
            initializer=paddle.nn.initializer.ConstantInitializer(
                value=begin - 1, force_cpu=True
            ),
393
        )
W
Wu Yi 已提交
394
        helper.main_program.global_block()._prepend_op(
Y
Yu Yang 已提交
395 396
            type='increment',
            inputs={'X': [counter]},
Y
Yu Yang 已提交
397
            outputs={'Out': [counter]},
398 399
            attrs={'step': float(step)},
        )
Y
Yu Yang 已提交
400 401 402
        counter.stop_gradient = True

    return counter