decorator.py 11.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# 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.

from ... import default_main_program
from ... import default_startup_program
from ... import layers
from ... import unique_name
19
from ... import program_guard
20
from . import fp16_utils
21
from .fp16_utils import rewrite_program
22
from .fp16_utils import update_role_var_grad
J
Jie Fang 已提交
23
from .fp16_lists import AutoMixedPrecisionLists
24 25
from .amp_nn import check_finite_and_unscale
from .amp_nn import update_loss_scaling
26 27 28 29

__all__ = ["decorate"]


Z
Zhen Wang 已提交
30
class OptimizerWithMixedPrecision(object):
31 32
    """
    Optimizer with mixed-precision (MP) training. This is a wrapper of a common 
Z
Zhen Wang 已提交
33
    optimizer, plus the support of mixed-precision pre-training. The object
34 35 36 37 38 39 40
    of this class almost has the same behavior as the common optimizer, with the 
    methods `minimize()`, `backward()`, `apply_gradients()` implemented. 
    Additionally, it enables the MP training automatically, i.e, the creation 
    and maintenance of master parameters, scaling of loss, etc.

    Args:
        optimizer (Optimizer): A common Optimizer object.
J
Jie Fang 已提交
41
        amp_lists (AutoMixedPrecisionLists): An AutoMixedPrecisionLists object.
42 43
        init_loss_scaling (float): The initial loss scaling factor.
        use_dynamic_loss_scaling (bool): Whether to use dynamic loss scaling.
J
Jie Fang 已提交
44 45 46 47 48 49 50 51 52 53
        incr_every_n_steps(int): Increases loss scaling every n consecutive 
                                 steps with finite gradients.
        decr_every_n_nan_or_inf(int): Decreases loss scaling every n 
                                      accumulated steps with nan or 
                                      inf gradients.
        incr_ratio(float): The multiplier to use when increasing the loss 
                           scaling.
        decr_ratio(float): The less-than-one-multiplier to use when decreasing 
                           the loss scaling.

54 55
    """

J
Jie Fang 已提交
56 57 58
    def __init__(self, optimizer, amp_lists, init_loss_scaling,
                 use_dynamic_loss_scaling, incr_every_n_steps,
                 decr_every_n_nan_or_inf, incr_ratio, decr_ratio):
59
        self._optimizer = optimizer
J
Jie Fang 已提交
60
        self._amp_lists = amp_lists
61
        self._param_grads = None
62 63
        self._train_program = None

64
        self._is_distributed = False
65
        self._scaled_loss = None
66 67
        self._loss_scaling = None
        self._init_loss_scaling = init_loss_scaling
68
        self._use_dynamic_loss_scaling = use_dynamic_loss_scaling
J
Jie Fang 已提交
69
        if self._use_dynamic_loss_scaling:
70 71
            self._incr_every_n_steps = incr_every_n_steps
            self._decr_every_n_nan_or_inf = decr_every_n_nan_or_inf
J
Jie Fang 已提交
72 73
            self._incr_ratio = incr_ratio
            self._decr_ratio = decr_ratio
74 75 76
            self._num_good_steps = None
            self._num_bad_steps = None

77 78 79 80 81 82
    def _set_distributed(self, flag):
        # if distributed, all cards will communication with each other,
        # overlap communication and computation by split the
        # check_finite_and_unscale op.
        self._is_distributed = flag

83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    def get_loss_scaling(self):
        """Return the real-time loss scaling factor.
        """
        return self._loss_scaling

    def get_scaled_loss(self):
        """Return the scaled loss.
        It's useful when you feed customed loss into executor.
        """
        return self._scaled_loss

    def _init_amp_var(self):
        self._loss_scaling = layers.create_global_var(
            name=unique_name.generate("loss_scaling"),
            shape=[1],
            value=self._init_loss_scaling,
            dtype='float32',
            persistable=True)

        if self._use_dynamic_loss_scaling:
J
Jie Fang 已提交
103 104 105 106 107 108 109 110 111 112 113 114
            self._num_good_steps = layers.create_global_var(
                name=unique_name.generate("num_good_steps"),
                shape=[1],
                value=0,
                dtype='int32',
                persistable=True)
            self._num_bad_steps = layers.create_global_var(
                name=unique_name.generate("num_bad_steps"),
                shape=[1],
                value=0,
                dtype='int32',
                persistable=True)
115

116
        # Ensure the data type of learning rate vars is float32 (same as the
117
        # master parameter dtype)
118 119 120 121 122 123 124 125
        if isinstance(self._optimizer._learning_rate, float):
            self._optimizer._learning_rate_map[default_main_program()] = \
                    layers.create_global_var(
                    name=unique_name.generate("learning_rate"),
                    shape=[1],
                    value=float(self._optimizer._learning_rate),
                    dtype='float32',
                    persistable=True)
126

127 128 129 130 131 132 133
    def backward(self,
                 loss,
                 startup_program=None,
                 parameter_list=None,
                 no_grad_set=None,
                 callbacks=None):
        """
Z
Zhen Wang 已提交
134
        Backward propagation or auto differentiation for gradients' computation.
135 136 137 138 139 140 141

        Args:
            loss (Variable): The loss Variable to minimize.
            startup_program (Program|None): The startup Program for initializing 
                                       parameters in `parameter_list`.
            parameter_list (list|None): A list of Variables to update.
            no_grad_set (set|None): A set of Variables should be ignored.
Z
Zhen Wang 已提交
142
            callbacks (list|None): A list of callable objects to run when appending
143 144 145 146 147 148
                                   backward operator for one parameter.

        Returns:
            A list of (param, grad), which is a tuple of a parameter and its 
            gradient respectively, and the scaled loss.
        """
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
        train_program = loss.block.program
        self._train_program = train_program

        with program_guard(train_program, startup_program):
            self._init_amp_var()

            rewrite_program(train_program, self._amp_lists)
            self._scaled_loss = loss * self._loss_scaling
            params_grads = self._optimizer.backward(
                self._scaled_loss, startup_program, parameter_list, no_grad_set,
                callbacks)
            # Change the op_role_var attr for some ops, so that gradients
            # transferred across GPUs can be FP16.
            update_role_var_grad(train_program, params_grads)
        return params_grads
164

165
    def apply_gradients(self, params_grads):
166
        """
167 168
        Check scaled gradients to determine whether to update loss scaling and update 
        parameters by their scaled gradients, 
169 170
  
        Args:
171
            params_grads (list): A list of params and scaled grads.
172 173 174 175
    
        Returns:
            A list of optimize operators.
        """
J
Jie Fang 已提交
176

177
        grads = [g for _, g in params_grads]
178 179 180 181 182 183 184 185 186 187 188 189 190
        if not self._is_distributed:
            with self._train_program._optimized_guard(grads):
                grads, found_inf = check_finite_and_unscale(
                    grads, self._loss_scaling, name="find_infinite_scale")
        else:
            # if distributed, split check_finite_and_unscale to overlap
            # unscale with communication
            found_infs = []
            for p, g in params_grads:
                with self._train_program._optimized_guard([p, g]):
                    _, found_inf = check_finite_and_unscale(
                        [g, ], self._loss_scaling, name="find_infinite_scale")
                    found_infs.append(found_inf)
J
Jie Fang 已提交
191

192
        if self._use_dynamic_loss_scaling:
193 194 195 196 197 198 199
            if self._is_distributed:
                with self._train_program._optimized_guard([]):
                    all_infs = layers.concat(found_infs)
                    found_inf = layers.reduce_any(all_infs)

            with self._train_program._optimized_guard([]):
                update_loss_scaling(
200 201 202 203 204 205 206 207 208 209 210
                    grads,
                    found_inf,
                    self._loss_scaling,
                    self._num_good_steps,
                    self._num_bad_steps,
                    self._incr_every_n_steps,
                    self._decr_every_n_nan_or_inf,
                    self._incr_ratio,
                    self._decr_ratio,
                    name="update_loss_scaling")

211
        optimize_ops = self._optimizer.apply_gradients(params_grads)
212 213
        return optimize_ops

214 215 216 217 218 219
    def apply_optimize(self, loss, startup_program, params_grads):
        program = loss.block.program
        with program_guard(program, startup_program):
            optimize_ops = self.apply_gradients(params_grads)
        return optimize_ops

G
gongweibao 已提交
220 221 222 223 224
    def minimize(self,
                 loss,
                 startup_program=None,
                 parameter_list=None,
                 no_grad_set=None):
225 226 227 228 229
        """
        Perform optimization by minimizing the given loss.

        Args:
            loss (Variable): The loss Variable.
G
gongweibao 已提交
230 231 232 233
            startup_program (Program): startup_program for initializing parameters
                in `parameter_list`.
            parameter_list (list): list of Variables to update.
            no_grad_set (set|None): set of Variables should be ignored.
234 235 236

        Returns:
            The scaled loss by scaling factor, the list of optimize ops, and a
237
            list of scaled parameters and gradients.
238
        """
239
        scaled_params_grads = self.backward(
G
gongweibao 已提交
240 241 242 243 244
            loss,
            startup_program=startup_program,
            parameter_list=parameter_list,
            no_grad_set=no_grad_set)

245 246
        optimize_ops = self.apply_optimize(loss, startup_program,
                                           scaled_params_grads)
247

G
gongweibao 已提交
248
        return optimize_ops, scaled_params_grads
249 250


J
Jie Fang 已提交
251
def decorate(optimizer,
J
Jie Fang 已提交
252
             amp_lists=None,
253
             init_loss_scaling=2**15,
J
Jie Fang 已提交
254 255 256 257
             incr_every_n_steps=1000,
             decr_every_n_nan_or_inf=2,
             incr_ratio=2.0,
             decr_ratio=0.8,
258
             use_dynamic_loss_scaling=True):
259 260 261 262 263
    """ 
    Decorate the given optimizer to adapt to the mixed-precision training.

    Args:
        optimizer(Optimizer): A common Optimizer.
J
Jie Fang 已提交
264
        amp_lists (AutoMixedPrecisionLists): An AutoMixedPrecisionLists object.
265
        init_loss_scaling(float): The initial loss scaling factor.
J
Jie Fang 已提交
266 267 268 269 270 271 272 273 274
        incr_every_n_steps(int): Increases loss scaling every n consecutive 
                                 steps with finite gradients.
        decr_every_n_nan_or_inf(int): Decreases loss scaling every n 
                                      accumulated steps with nan or 
                                      inf gradients.
        incr_ratio(float): The multiplier to use when increasing the loss 
                           scaling.
        decr_ratio(float): The less-than-one-multiplier to use when decreasing 
                           the loss scaling.
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
        use_dynamic_loss_scaling(bool): Whether to use dynamic loss scaling.

    Returns:
        An optimizer acting like a normal one but with mixed-precision training 
        enabled.

    Examples:
	.. code-block:: python

	    loss = network()
            optimizer = fluid.optimizer.Adam(learning_rate=0.001)
	
            mp_optimizer = fluid.contrib.mixed_precision.decorate(
	              optimizer=optimizer, init_loss_scaling=8.0)
	
G
gongweibao 已提交
290
            ops, param_grads = mp_optimizer.minimize(loss)
291
            scaled_loss = mp_optimizer.get_scaled_loss()
292
    """
J
Jie Fang 已提交
293 294
    if amp_lists is None:
        amp_lists = AutoMixedPrecisionLists()
Z
Zhen Wang 已提交
295
    mp_optimizer = OptimizerWithMixedPrecision(
J
Jie Fang 已提交
296
        optimizer, amp_lists, init_loss_scaling, use_dynamic_loss_scaling,
J
Jie Fang 已提交
297
        incr_every_n_steps, decr_every_n_nan_or_inf, incr_ratio, decr_ratio)
298 299

    return mp_optimizer