dygraph_grad_clip.py 8.5 KB
Newer Older
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) 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.

from __future__ import print_function

import copy
import six

import functools

from . import layers
from . import framework
from . import core
25
from .dygraph import base as imperative_base
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

__all__ = [
    'GradClipByValue',
    'GradClipByNorm',
    'GradClipByGlobalNorm',
]


class GradClipBase(object):
    def __str__(self):
        raise NotImplementedError()

    def _clip(self, para_and_grad):
        raise NotImplementedError

41
    @imperative_base.no_grad
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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
    def __call__(self, para_and_grad):
        return self._clip(para_and_grad)


class GradClipByValue(GradClipBase):
    """
    Clips gradient values to the range [min_value, max_value].

    Given a gradient g, this operation clips its value to min_value and max_value.

    - Any values less than min_value are set to min_value.
    - Any values greater than max_value are set to max_value.

    Args:
        max_value (float): The maximum value to clip by. 
        min (float, optional): The minimum value to clip by. if not set by user, \
        will be set to -max_value(max_value MUST be postive) by framework. 

    Examples:
        .. code-block:: python
        
            import numpy as np
            import paddle
            import paddle.fluid as fluid

            from paddle.fluid.dygraph.base import to_variable
            from paddle.fluid.dygraph.nn import FC

            from paddle.fluid.clip import GradClipByValue, GradClipByNorm, GradClipByGlobalNorm

            from paddle.fluid.optimizer import SGDOptimizer

            with fluid.dygraph.guard():
                value_clip = GradClipByValue( -1.0, 1.0 )
                sgd = SGDOptimizer(learning_rate=1.0)
                
                init_value = np.random.uniform( -1, 1, (10, 10)).astype('float32')

                fc = FC( "fc", 10)

                out = fc( to_variable(init_value) )

                loss = fluid.layers.reduce_mean( out )

                loss.backward()
                sgd.minimize(loss, grad_clip = value_clip)
            
    """

91
    @imperative_base.no_grad
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 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
    def __init__(self, min_value, max_value=None):

        if min_value is None:
            assert (max_value > 0.0)
            min_value = -max_value
        else:
            min_value = float(min_value)
        self.max_value = max_value
        self.min_value = min_value

    def __str__(self):
        return "ClipByValue, min = %f, max=%f" % (self.min_value,
                                                  self.max_value)

    def _clip(self, para_and_grad):
        out = []
        for p, g in para_and_grad:
            if g is None:
                out.append((p, g))
                continue

            new_grad = layers.clip(x=g, min=self.min_value, max=self.max_value)

            out.append((p, new_grad))

        return out


class GradClipByNorm(GradClipBase):
    """
    Clips tensor values to a maximum L2-norm.

    This operator limits the L2 norm of the input :math:`X` within :math:`max\_norm`.
    If the L2 norm of :math:`X` is less than or equal to :math:`max\_norm`, :math:`Out`
    will be the same as :math:`X`. If the L2 norm of :math:`X` is greater than
    :math:`max\_norm`, :math:`X` will be linearly scaled to make the L2 norm of
    :math:`Out` equal to :math:`max\_norm`, as shown in the following formula:

    .. math::

        Out = \\frac{max\_norm * X}{norm(X)},

    where :math:`norm(X)` represents the L2 norm of :math:`X`.

    Args:
        clip_norm (float): The maximum norm value

    Examples:
        .. code-block:: python

            import numpy as np
            import paddle
            import paddle.fluid as fluid

            from paddle.fluid.dygraph.base import to_variable
            from paddle.fluid.dygraph.nn import FC

            from paddle.fluid.clip import GradClipByValue, GradClipByNorm, GradClipByGlobalNorm

            from paddle.fluid.optimizer import SGDOptimizer

            with fluid.dygraph.guard():
                norm_clip = GradClipByNorm( 5.0 )
                sgd = SGDOptimizer(learning_rate=1.0)
                
                init_value = np.random.uniform( -1, 1, (10, 10)).astype('float32')

                fc = FC( "fc", 10)

                out = fc( to_variable(init_value) )

                loss = fluid.layers.reduce_mean( out )

                loss.backward()
                sgd.minimize(loss, grad_clip = norm_clip)

    """

170
    @imperative_base.no_grad
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
    def __init__(self, clip_norm):
        self.clip_norm = clip_norm

    def __str__(self):
        return "ClipByNorm, clip_norm=%f" % self.clip_norm

    def _clip(self, para_and_grad):
        out = []

        for p, g in para_and_grad:
            if g is None:
                out.append((p, g))
                continue
            new_g = layers.clip_by_norm(x=g, max_norm=self.clip_norm)

            out.append((p, new_g))

        return out


class GradClipByGlobalNorm(GradClipBase):
    """
    Clips values of multiple tensors by the ratio of the sum of their norms.

195 196
    Given a list of tensors t_list, and a clipping ratio max_global_norm, this
    operation returns a list of clipped tensors list_clipped.
197 198 199 200 201

    To perform the clipping, the values :math:`t\_list[i]` are set to:

    .. math::

202
        t\_list[i] = t\_list[i] * \\frac{max\_global\_norm}{\max(global\_norm, max\_global\_norm)}
203 204 205 206 207 208 209

    where:

    .. math::

        global\_norm = \sqrt{\sum_{i=0}^{N-1}(l2norm(t\_list[i]))^2}

210
    If :math:`max\_global\_norm > global\_norm` then the entries in t_list remain as they are,
211 212 213
    otherwise they're all shrunk by the global ratio.

    Args:
214 215
        max_global_norm (float): The maximum norm value.
        dtype (str, optional): The type of max_global_norm. Default: "float32".
216 217 218 219 220 221 222 223 224 225 226

    Examples:
        .. code-block:: python
        
            import numpy as np
            import paddle
            import paddle.fluid as fluid

            from paddle.fluid.dygraph.base import to_variable
            from paddle.fluid.dygraph.nn import FC

227
            from paddle.fluid.dygraph_grad_clip import GradClipByValue, GradClipByNorm, GradClipByGlobalNorm
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248

            from paddle.fluid.optimizer import SGDOptimizer

            with fluid.dygraph.guard():
                gloabl_norm_clip = GradClipByGlobalNorm( 5.0 )
                sgd = SGDOptimizer(learning_rate=1.0)
                
                init_value = np.random.uniform( -1, 1, (10, 10)).astype('float32')

                fc = FC( "fc", 10)

                out = fc( to_variable(init_value) )

                loss = fluid.layers.reduce_mean( out )

                loss.backward()
                sgd.minimize(loss, grad_clip = gloabl_norm_clip)
   

    """

249
    @imperative_base.no_grad
250
    def __init__(self, max_global_norm, dtype='float32'):
251
        self.max_global_norm = layers.fill_constant(
252
            shape=[1], dtype=dtype, value=max_global_norm)
253 254 255 256 257 258 259 260 261 262 263 264

    def __str__(self):
        return "ClipByGlobalNorm, max_global_norm=%f" % (self.max_global_norm)

    def _clip(self, para_and_grad):

        out = []

        norm_arr = []
        for p, g in para_and_grad:
            if g is None:
                continue
265
            merge_grad = g
266
            if g.type == core.VarDesc.VarType.SELECTED_ROWS:
267 268 269
                merge_grad = layers.merge_selected_rows(g)
                merge_grad = layers.get_tensor_from_selected_rows(merge_grad)
            power = layers.square(merge_grad)
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
            sum_t = layers.reduce_sum(power)
            norm_arr.append(sum_t)

        norm_global = layers.concat(norm_arr)
        norm_global = layers.reduce_sum(norm_global)
        norm_global = layers.sqrt(norm_global)

        clip_scale = layers.elementwise_div(
            x=self.max_global_norm,
            y=layers.elementwise_max(
                x=norm_global, y=self.max_global_norm))

        for p, g in para_and_grad:
            if g is None:
                out.append((p, g))
                continue
286
            new_grad = layers.elementwise_mul(x=g, y=clip_scale)
287 288 289 290

            out.append((p, new_grad))

        return out