paddle_helper.py 8.2 KB
Newer Older
Y
yelrose 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
# Copyright (c) 2019 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.
"""
paddle_helper package contain some simple function to help building
paddle models.
"""
import warnings
import numpy as np

import paddle
from paddle.fluid import core
import paddle.fluid as fluid
import paddle.fluid.layer_helper as layer_helper
Y
Yelrose 已提交
25
import paddle.fluid.layers as L
Y
yelrose 已提交
26 27 28 29 30 31
from pgl.utils.logger import log


def gather(input, index):
    """Gather input from given index.

Y
Yelrose 已提交
32
    Slicing input data with given index. This function rewrite paddle.L.gather
Y
yelrose 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45
    to fix issue: https://github.com/PaddlePaddle/Paddle/issues/17509 when paddlepaddle's
    version is less than 1.5.

    Args:
        input: Input tensor to be sliced

        index: Slice index

    Return:
        A tensor that are sliced from given input data.
    """
    try:
        # PaddlePaddle 1.5
Y
Yelrose 已提交
46
        output = L.gather(input, index, overwrite=False)
Y
yelrose 已提交
47 48 49 50 51 52
        return output
    except TypeError as e:
        warnings.warn("Your paddle version is less than 1.5"
                      " gather may be slower.")

        if index.dtype == core.VarDesc.VarType.INT32:
Y
Yelrose 已提交
53
            index = L.cast(index, "int64")
Y
yelrose 已提交
54
            if index.shape[-1] != 1:
Y
Yelrose 已提交
55
                index = L.reshape(index, shape=[-1, 1])
Y
yelrose 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
            index.stop_gradient = True

        helper = layer_helper.LayerHelper("gather", **locals())  #**locals())
        dtype = input.dtype
        tmp = helper.create_variable_for_type_inference(dtype)
        padding_idx = -1
        helper.append_op(
            type='lookup_table',
            inputs={'Ids': index,
                    'W': input},
            outputs={'Out': tmp},
            attrs={
                'is_sparse': False,
                'is_distributed': False,
                'remote_prefetch': False,
                'padding_idx': padding_idx
            })
        return tmp


def constant(name, value, dtype, hide_batch_size=True):
    """Create constant variable with given data.

    This function helps to create constants variable with
    given numpy.ndarray data.

    Args:
        name: variable name

        value: numpy.ndarray the value of constant

        dtype: the type of constant

        hide_batch_size: If set the first dimenstion as unknown, the explicit
                         batch size may cause some error in paddle. For example,
                         when the value has a shape of (batch_size, dim1, dim2),
                         it will return a variable with shape (-1, dim1, dim2).

    Return:
        A tuple contain the constant variable and the constant
        variable initialize function.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            constant_var, constant_var_init = constant(name="constant",
                              value=np.array([5.0],
                              dtype="float32"))
            exe.run(fluid.default_startup_program())
            # Run After default startup
            constant_var_init(place)

    """
    if not isinstance(value, np.ndarray):
        raise TypeError("value should be Numpy array.")

    value = value.astype(dtype)
Y
Yelrose 已提交
116
    data = L.create_global_var(
Y
yelrose 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
        shape=value.shape,
        value=0,
        dtype=value.dtype,
        name=name,
        persistable=True)
    data.stop_gradient = True

    if hide_batch_size:
        shape = list(value.shape)
        shape[0] = -1
        data.desc.set_shape(shape)

    def initializer(place):
        if isinstance(place, fluid.CUDAPlace):
            pass
        elif isinstance(place, fluid.CUDAPinnedPlace):
            pass
        elif isinstance(place, fluid.CPUPlace):
            pass
        else:
            raise TypeError(
                "The input of initializer is not in"
                " [fluid.CUDAPlace, fluid.CPUPlace, fluid.CUDAPinnedPlace]")
        var = fluid.global_scope().var(data.name).get_tensor()
        var.set(value, place)

    return data, initializer


def lod_constant(name, value, lod, dtype):
    """Create constant lod variable with given data,

    This function helps to create constants lod variable with given numpy.ndarray data
    and lod information.

    Args:
        name: variable name

        value: numpy.ndarray the value of constant

        dtype: the type of constant

        lod: lod infos of given value.

    Return:
        A tuple contain the constant variable and the constant
        variable initialize function.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            constant_var, constant_var_init = lod_constant(name="constant",
                              value=np.array([[5.0], [1.0], [2.0]],
                              lod=[2, 1],
                              dtype="float32"))
            exe.run(fluid.default_startup_program())
            # Run After default startup
            constant_var_init(place)
    """
    data, data_initializer = constant(
        name=name, value=value, dtype=dtype, hide_batch_size=True)

    _lod = [0]
    for l in lod:
        _lod.append(_lod[-1] + l)
Y
Yelrose 已提交
185
    output = L.lod_reset(data, target_lod=_lod)
Y
yelrose 已提交
186 187 188
    return output, data_initializer


F
fengshikun01 已提交
189
def sequence_softmax(x, beta=None):
Y
yelrose 已提交
190 191 192
    """Compute sequence softmax over paddle LodTensor

    This function compute softmax normalization along with the length of sequence.
Y
Yelrose 已提交
193
    This function is an extention of :code:`L.sequence_softmax` which can only
Y
yelrose 已提交
194 195 196 197
    deal with LodTensor whose last dimension is 1.

    Args:
        x: The input variable which is a LodTensor.
F
fengshikun01 已提交
198
        beta: Inverse Temperature
Y
yelrose 已提交
199 200 201 202

    Return:
        Output of sequence_softmax
    """
F
fengshikun01 已提交
203 204 205 206

    if beta is not None:
        x =  x * beta
    
Y
Yelrose 已提交
207 208
    x_max = L.sequence_pool(x, "max")
    x_max = L.sequence_expand_as(x_max, x)
Y
yelrose 已提交
209
    x = x - x_max
Y
Yelrose 已提交
210 211 212
    exp_x = L.exp(x)
    sum_exp_x = L.sequence_pool(exp_x, "sum")
    sum_exp_x = L.sequence_expand_as(sum_exp_x, exp_x)
Y
yelrose 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
    return exp_x / sum_exp_x


def scatter_add(input, index, updates):
    """Scatter add updates to input by given index.

    Adds sparse updates to input variables.

    Args:
        input: Input tensor to be updated

        index: Slice index

        updates: Must have same type as input.

    Return:
        Same type and shape as input.
    """

Y
Yelrose 已提交
232
    output = L.scatter(input, index, updates, overwrite=False)
Y
Yelrose 已提交
233 234
    return output

L
update  
liweibin 已提交
235

Y
Yelrose 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
def scatter_max(input, index, updates):
    """Scatter max updates to input by given index.

    Adds sparse updates to input variables.

    Args:
        input: Input tensor to be updated

        index: Slice index

        updates: Must have same type as input.

    Return:
        Same type and shape as input.
    """

Y
Yelrose 已提交
252
    output = L.scatter(input, index, updates, mode='max')
Y
yelrose 已提交
253
    return output
Y
Yelrose 已提交
254 255 256 257 258 259 260 261 262 263 264 265 266 267

def masked_select(input, mask):
    """masked_select
    
    Slice the value from given Mask
   
    Args:
        input: Input tensor to be selected
         
        mask: A bool tensor for sliced.
  
    Return:
        Part of inputs where mask is True. 
    """
Y
Yelrose 已提交
268 269
    index = L.where(mask)
    return L.gather(input, index)
Y
Yelrose 已提交
270

271 272

def ensure_dtype(input, dtype):
Y
Yelrose 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286
    """ensure_dtype

    If input is dtype, return input

    else cast input into dtype

    Args:
        input: Input tensor  

        dtype: a string of type
 
    Return:
        If input is dtype, return input, else cast input into dtype
    """
Y
Yelrose 已提交
287
    if str(input.dtype) == dtype:
288 289
        return input
    else:
Y
Yelrose 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
        return L.cast(input, dtype=dtype)

def lod_remove(input):
    """Lod Remove
    
    Remove the lod for LodTensor and Flatten the data into 1D-Tensor.

    Args:
        input: A tensor to be flattend

    Return:
        A 1D input
    """
    return L.reshape(L.reshape(input, [1, -1]), [-1])