localsgd_optimizer.py 16.5 KB
Newer Older
Y
Yi Liu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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.

from __future__ import print_function

S
ShenLiang 已提交
17
import paddle
18
from paddle.fluid import program_guard, layers, default_main_program
Y
Yi Liu 已提交
19 20 21 22 23 24 25 26
from .meta_optimizer_base import MetaOptimizerBase
from .common import OpRole, OP_ROLE_KEY, CollectiveHelper, is_update_op


class LocalSGDOptimizer(MetaOptimizerBase):
    def __init__(self, optimizer):
        super(LocalSGDOptimizer, self).__init__(optimizer)
        self.inner_opt = optimizer
27
        self.meta_optimizers_white_list = ['AMPOptimizer']
28
        self.meta_optimizers_black_list = [
29 30
            "GraphExecutionOptimizer",
            "AdaptiveLocalSGDOptimizer",
31
        ]
Y
Yi Liu 已提交
32 33 34
        self.snapshot_key = '@SNAPSHOT'

    def _can_apply(self):
35 36 37
        if not self.role_maker._is_collective:
            return False

Y
Yi Liu 已提交
38 39 40
        if not self.user_defined_strategy.localsgd:
            return False

41
        if self.role_maker._worker_num() <= 1:
Y
Yi Liu 已提交
42 43
            return False

S
ShenLiang 已提交
44
        return isinstance(self.inner_opt, paddle.optimizer.momentum.Momentum) \
45 46 47
            or isinstance(self.inner_opt, paddle.fluid.optimizer.Momentum) \
            or isinstance(self.inner_opt, paddle.optimizer.sgd.SGD) \
            or isinstance(self.inner_opt, paddle.fluid.optimizer.SGD)
Y
Yi Liu 已提交
48 49 50

    def _disable_strategy(self, dist_strategy):
        dist_strategy.localsgd = False
51
        dist_strategy.localsgd_configs = {}
Y
Yi Liu 已提交
52

53
    def _enable_strategy(self, dist_strategy, context):
54
        dist_strategy.localsgd = True
55
        dist_strategy.localsgd_configs = {"k_steps": 1, "begin_step": 1}
56

Y
Yi Liu 已提交
57 58 59
    def snapshot_name(self, param_name):
        return param_name + self.snapshot_key

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
    def create_snapshot_vars(self, program):
        block = program.global_block()

        non_dist_params = []
        for param in block.iter_parameters():
            if not param.is_distributed:
                non_dist_params.append(param)

        p2s = []
        for param in non_dist_params:
            snapshot = block.create_var(
                name=self.snapshot_name(param.name),
                shape=param.shape,
                persistable=True,
                stop_gradient=True,
                dtype=param.dtype)
            p2s.append([param, snapshot])
        return p2s

    def init_snapshot_vars(self, startup_program, param2snapshot):
        with program_guard(startup_program):
            for param, snapshot in param2snapshot:
                layers.assign(param, snapshot)

Y
Yi Liu 已提交
84 85 86 87 88 89 90 91
    def minimize_impl(self,
                      loss,
                      startup_program=None,
                      parameter_list=None,
                      no_grad_set=None):
        minimized = self.inner_opt.minimize(
            loss, startup_program=startup_program)

92 93 94
        k_steps_value = self.user_defined_strategy.localsgd_configs['k_steps']
        begin_step_value = self.user_defined_strategy.localsgd_configs[
            'begin_step']
Y
Yi Liu 已提交
95 96 97 98 99 100 101 102

        if startup_program is None:
            startup_program = default_startup_program()
        main_block = loss.block

        self.nrings = 2
        collective_helper = CollectiveHelper(self.role_maker, self.nrings)
        collective_helper.update_startup_program(startup_program)
103 104
        p2s = self.create_snapshot_vars(startup_program)
        self.init_snapshot_vars(startup_program, p2s)
Y
Yi Liu 已提交
105

106 107
        p2s = self.create_snapshot_vars(main_block.program)
        with program_guard(main_block.program, startup_program):
108
            step = layers.autoincreased_step_counter(begin=1)
Y
Yi Liu 已提交
109 110 111
            k_steps = layers.create_global_var(
                name="k_steps",
                shape=[1],
112
                value=k_steps_value,
Y
Yi Liu 已提交
113 114
                dtype='int64',
                persistable=True)
115 116 117 118 119 120 121 122

            begin_step = layers.create_global_var(
                name="begin_step",
                shape=[1],
                value=begin_step_value,
                dtype='int64',
                persistable=True)

Y
Yi Liu 已提交
123 124 125
            last_step = layers.create_global_var(
                name="last_step",
                shape=[1],
126
                value=begin_step_value,
Y
Yi Liu 已提交
127 128 129 130
                dtype='int64',
                persistable=True)

            def communicate():
131
                sub_block = default_main_program().current_block()
Y
Yi Liu 已提交
132
                ring_id = -1
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
                for param, snapshot in p2s:
                    sub_block.append_op(
                        type='elementwise_sub',
                        inputs={'X': [snapshot],
                                'Y': [param]},
                        outputs={'Out': [param]},
                        attrs={OP_ROLE_KEY: OpRole.Optimize})
                    sub_block.append_op(
                        type='c_sync_calc_stream',
                        inputs={'X': param},
                        outputs={'Out': param},
                        attrs={OP_ROLE_KEY: OpRole.Optimize})
                    ring_id = (ring_id + 1) % self.nrings
                    sub_block.append_op(
                        type='c_allreduce_sum',
                        inputs={'X': [param]},
                        outputs={'Out': [param]},
                        attrs={
                            'ring_id': ring_id,
                            OP_ROLE_KEY: OpRole.Optimize
                        })
Y
Yi Liu 已提交
154 155

                for ring_id in range(self.nrings):
156
                    sub_block.append_op(
Y
Yi Liu 已提交
157 158 159 160 161 162 163 164
                        type='c_sync_comm_stream',
                        inputs={'X': param},
                        outputs={'Out': param},
                        attrs={
                            'ring_id': ring_id,
                            OP_ROLE_KEY: OpRole.Optimize
                        })

165 166
                for param, snapshot in p2s:
                    sub_block.append_op(
Y
Yi Liu 已提交
167 168 169 170
                        type='scale',
                        inputs={'X': [param]},
                        outputs={'Out': [param]},
                        attrs={
171
                            'scale': 1.0 / self.role_maker._worker_num(),
Y
Yi Liu 已提交
172 173
                            OP_ROLE_KEY: OpRole.Optimize
                        })
174
                    sub_block.append_op(
Y
Yi Liu 已提交
175 176 177 178 179
                        type='elementwise_sub',
                        inputs={'X': [snapshot],
                                'Y': [param]},
                        outputs={'Out': [param]},
                        attrs={OP_ROLE_KEY: OpRole.Optimize})
180
                    sub_block.append_op(
Y
Yi Liu 已提交
181 182 183 184 185 186
                        type='assign',
                        inputs={'X': [param]},
                        outputs={'Out': [snapshot]},
                        attrs={OP_ROLE_KEY: OpRole.Optimize})
                layers.assign(step, last_step)

187 188
            def begin_localsgd():
                layers.cond(step - last_step == k_steps, communicate)
Y
Yi Liu 已提交
189

190
            layers.cond(step > begin_step, begin_localsgd, communicate)
Y
Yi Liu 已提交
191
        return minimized
192 193 194 195 196 197


class AdaptiveLocalSGDOptimizer(MetaOptimizerBase):
    def __init__(self, optimizer):
        super(AdaptiveLocalSGDOptimizer, self).__init__(optimizer)
        self.inner_opt = optimizer
198
        self.meta_optimizers_white_list = ['AMPOptimizer']
199 200 201 202 203 204 205 206 207 208 209 210
        self.meta_optimizers_black_list = [
            "GraphExecutionOptimizer", "LocalSGDOptimizer"
        ]
        self.snapshot_key = '@SNAPSHOT'

    def _can_apply(self):
        if not self.role_maker._is_collective:
            return False

        if not self.user_defined_strategy.adaptive_localsgd:
            return False

211
        if self.role_maker._worker_num() <= 1:
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
            return False

        return isinstance(self.inner_opt, paddle.optimizer.momentum.Momentum) \
            or isinstance(self.inner_opt, paddle.fluid.optimizer.Momentum) \
            or isinstance(self.inner_opt, paddle.optimizer.sgd.SGD) \
            or isinstance(self.inner_opt, paddle.fluid.optimizer.SGD)

    def _disable_strategy(self, dist_strategy):
        dist_strategy.adaptive_localsgd = False
        dist_strategy.adaptive_localsgd_configs = {}

    def _enable_strategy(self, dist_strategy, context):
        dist_strategy.adaptive_localsgd = True
        dist_strategy.adaptive_localsgd_configs = {
            "init_k_steps": 1,
            "begin_step": 1
        }

    def snapshot_name(self, param_name):
        return param_name + self.snapshot_key

    def create_snapshot_vars(self, program):
        block = program.global_block()

        non_dist_params = []
        for param in block.iter_parameters():
            if not param.is_distributed:
                non_dist_params.append(param)

        p2s = []
        for param in non_dist_params:
            snapshot = block.create_var(
                name=self.snapshot_name(param.name),
                shape=param.shape,
                persistable=True,
                stop_gradient=True,
                dtype=param.dtype)
            p2s.append([param, snapshot])
        return p2s

    def init_snapshot_vars(self, startup_program, param2snapshot):
        with program_guard(startup_program):
            for param, snapshot in param2snapshot:
                layers.assign(param, snapshot)

    def _generate_avg_loss(self, program_block, loss, avg_loss):
        program_block.append_op(
            type='c_allreduce_sum',
            inputs={'X': [loss]},
            outputs={'Out': [avg_loss]},
            attrs={
                'ring_id': 0,
                OP_ROLE_KEY: OpRole.Optimize,
                'use_calc_stream': True
            })
        program_block.append_op(
            type='c_sync_calc_stream',
            inputs={'X': [avg_loss]},
            outputs={'Out': [avg_loss]},
            attrs={OP_ROLE_KEY: OpRole.Optimize})

        program_block.append_op(
            type='scale',
            inputs={'X': [avg_loss]},
            outputs={'Out': [avg_loss]},
            attrs={
278
                'scale': 1.0 / self.role_maker._worker_num(),
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
                OP_ROLE_KEY: OpRole.Optimize
            })

    def minimize_impl(self,
                      loss,
                      startup_program=None,
                      parameter_list=None,
                      no_grad_set=None):
        minimized = self.inner_opt.minimize(
            loss, startup_program=startup_program)

        init_k_steps = self.user_defined_strategy.adaptive_localsgd_configs[
            'init_k_steps']
        begin_step_value = self.user_defined_strategy.adaptive_localsgd_configs[
            'begin_step']

        if startup_program is None:
            startup_program = default_startup_program()
        main_block = loss.block

        self.nrings = 2
        collective_helper = CollectiveHelper(self.role_maker, self.nrings)
        collective_helper.update_startup_program(startup_program)
        p2s = self.create_snapshot_vars(startup_program)
        self.init_snapshot_vars(startup_program, p2s)

        p2s = self.create_snapshot_vars(main_block.program)
        with program_guard(main_block.program, startup_program):
            step = layers.autoincreased_step_counter(begin=1)

            k_steps = layers.create_global_var(
                name="k_steps",
                shape=[1],
                value=int(init_k_steps),
                dtype='int64',
                persistable=True)

            begin_step = layers.create_global_var(
                name="begin_step",
                shape=[1],
                value=int(begin_step_value),
                dtype='int64',
                persistable=True)

            last_step = layers.create_global_var(
                name="last_step",
                shape=[1],
                value=int(0),
                dtype='int64',
                persistable=True)

            avg_loss = layers.create_global_var(
                name="avg_loss",
                shape=[1],
                value=float(0),
                dtype=loss.dtype,
                persistable=True)

            lr_0 = layers.create_global_var(
                name="lr_0",
                shape=[1],
                value=float(0),
                dtype='float32',
                persistable=True)

            loss_0 = layers.create_global_var(
                name="loss_0",
                shape=[1],
                value=float(0),
                dtype='float32',
                persistable=True)

            global_lr = self.inner_opt._global_learning_rate()

            def initialize():
                self._generate_avg_loss(main_block, loss, avg_loss)
                layers.assign(avg_loss, loss_0)
                layers.assign(global_lr, lr_0)

            layers.cond(step == 1, initialize)

            def communicate():
                sub_block = default_main_program().current_block()
                ring_id = -1
                for param, snapshot in p2s:
                    sub_block.append_op(
                        type='elementwise_sub',
                        inputs={'X': [snapshot],
                                'Y': [param]},
                        outputs={'Out': [param]},
                        attrs={OP_ROLE_KEY: OpRole.Optimize})
                    sub_block.append_op(
                        type='c_sync_calc_stream',
                        inputs={'X': param},
                        outputs={'Out': param},
                        attrs={OP_ROLE_KEY: OpRole.Optimize})
                    ring_id = (ring_id + 1) % self.nrings
                    sub_block.append_op(
                        type='c_allreduce_sum',
                        inputs={'X': [param]},
                        outputs={'Out': [param]},
                        attrs={
                            'ring_id': ring_id,
                            OP_ROLE_KEY: OpRole.Optimize
                        })

                for ring_id in range(self.nrings):
                    sub_block.append_op(
                        type='c_sync_comm_stream',
                        inputs={'X': param},
                        outputs={'Out': param},
                        attrs={
                            'ring_id': ring_id,
                            OP_ROLE_KEY: OpRole.Optimize
                        })

                for param, snapshot in p2s:
                    sub_block.append_op(
                        type='scale',
                        inputs={'X': [param]},
                        outputs={'Out': [param]},
                        attrs={
401
                            'scale': 1.0 / self.role_maker._worker_num(),
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
                            OP_ROLE_KEY: OpRole.Optimize
                        })
                    sub_block.append_op(
                        type='elementwise_sub',
                        inputs={'X': [snapshot],
                                'Y': [param]},
                        outputs={'Out': [param]},
                        attrs={OP_ROLE_KEY: OpRole.Optimize})
                    sub_block.append_op(
                        type='assign',
                        inputs={'X': [param]},
                        outputs={'Out': [snapshot]},
                        attrs={OP_ROLE_KEY: OpRole.Optimize})
                layers.assign(step, last_step)

            def communicate_avg_loss():
                communicate()
                self._generate_avg_loss(main_block, loss, avg_loss)
                next_local_steps = layers.cast(
                    layers.ceil(
                        layers.sqrt(lr_0 * avg_loss / (global_lr * loss_0) *
                                    float(init_k_steps))),
                    dtype='int64')
                max_local_steps = layers.fill_constant(
                    shape=[1], dtype='int64', value=16)
                min_local_steps = layers.fill_constant(
                    shape=[1], dtype='int64', value=1)
                next_local_steps = layers.elementwise_min(next_local_steps,
                                                          max_local_steps)
                next_local_steps = layers.elementwise_max(next_local_steps,
                                                          min_local_steps)
                layers.assign(next_local_steps, k_steps)

            def begin_localsgd():
                layers.cond(step - last_step == k_steps, communicate_avg_loss)

            layers.cond(step > begin_step, begin_localsgd, communicate)

        return minimized