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

S
ShenLiang 已提交
15
import paddle
16 17
from paddle.static import program_guard, default_main_program
from paddle.static import default_startup_program
Y
Yi Liu 已提交
18
from .meta_optimizer_base import MetaOptimizerBase
19
from .common import CollectiveHelper, OP_ROLE_KEY, OpRole
Y
Yi Liu 已提交
20

21 22
__all__ = []

Y
Yi Liu 已提交
23 24 25

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

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

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

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

45 46 47 48
        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)
49
            or isinstance(self.inner_opt, paddle.fluid.optimizer.SGD)
50
        )
Y
Yi Liu 已提交
51 52 53

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

56
    def _enable_strategy(self, dist_strategy, context):
57
        dist_strategy.localsgd = True
58
        dist_strategy.localsgd_configs = {"k_steps": 1, "begin_step": 1}
59

Y
Yi Liu 已提交
60 61 62
    def snapshot_name(self, param_name):
        return param_name + self.snapshot_key

63 64 65 66 67 68 69 70 71 72
    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:
73 74 75 76 77 78 79
            snapshot = block.create_var(
                name=self.snapshot_name(param.name),
                shape=param.shape,
                persistable=True,
                stop_gradient=True,
                dtype=param.dtype,
            )
80 81 82 83 84 85
            p2s.append([param, snapshot])
        return p2s

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

88 89 90 91 92 93
    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
        )
Y
Yi Liu 已提交
94

95 96
        k_steps_value = self.user_defined_strategy.localsgd_configs['k_steps']
        begin_step_value = self.user_defined_strategy.localsgd_configs[
97 98
            'begin_step'
        ]
Y
Yi Liu 已提交
99 100 101 102 103 104 105 106

        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)
107 108
        p2s = self.create_snapshot_vars(startup_program)
        self.init_snapshot_vars(startup_program, p2s)
Y
Yi Liu 已提交
109

110 111
        p2s = self.create_snapshot_vars(main_block.program)
        with program_guard(main_block.program, startup_program):
112 113
            step = paddle.fluid.layers.autoincreased_step_counter(begin=1)
            k_steps = paddle.static.create_global_var(
114 115 116 117 118 119 120
                name="k_steps",
                shape=[1],
                value=k_steps_value,
                dtype='int64',
                persistable=True,
            )

121
            begin_step = paddle.static.create_global_var(
122 123 124 125 126 127 128
                name="begin_step",
                shape=[1],
                value=begin_step_value,
                dtype='int64',
                persistable=True,
            )

129
            last_step = paddle.static.create_global_var(
130 131 132 133 134 135
                name="last_step",
                shape=[1],
                value=begin_step_value,
                dtype='int64',
                persistable=True,
            )
Y
Yi Liu 已提交
136 137

            def communicate():
138
                sub_block = default_main_program().current_block()
Y
Yi Liu 已提交
139
                ring_id = -1
140
                for param, snapshot in p2s:
141 142 143 144 145 146 147 148 149 150 151 152
                    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},
                    )
153
                    ring_id = (ring_id + 1) % self.nrings
154 155 156 157 158 159 160 161 162
                    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 已提交
163 164

                for ring_id in range(self.nrings):
165 166 167 168 169 170 171 172 173
                    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,
                        },
                    )
Y
Yi Liu 已提交
174

175
                for param, snapshot in p2s:
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
                    sub_block.append_op(
                        type='scale',
                        inputs={'X': [param]},
                        outputs={'Out': [param]},
                        attrs={
                            'scale': 1.0 / self.role_maker._worker_num(),
                            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},
                    )
197
                paddle.assign(step, last_step)
Y
Yi Liu 已提交
198

199
            def begin_localsgd():
200
                paddle.static.nn.cond(step - last_step == k_steps, communicate)
Y
Yi Liu 已提交
201

202 203 204
            paddle.static.nn.cond(
                step > begin_step, begin_localsgd, communicate
            )
Y
Yi Liu 已提交
205
        return minimized
206 207 208 209


class AdaptiveLocalSGDOptimizer(MetaOptimizerBase):
    def __init__(self, optimizer):
210
        super().__init__(optimizer)
211
        self.inner_opt = optimizer
212
        self.meta_optimizers_white_list = ['AMPOptimizer']
213
        self.meta_optimizers_black_list = [
214 215
            "GraphExecutionOptimizer",
            "LocalSGDOptimizer",
216 217 218 219 220 221 222 223 224 225
        ]
        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

226
        if self.role_maker._worker_num() <= 1:
227 228
            return False

229
        return (
230
            isinstance(self.inner_opt, paddle.optimizer.Momentum)
231 232
            or isinstance(self.inner_opt, paddle.fluid.optimizer.Momentum)
            or isinstance(self.inner_opt, paddle.optimizer.sgd.SGD)
233
            or isinstance(self.inner_opt, paddle.fluid.optimizer.SGD)
234
        )
235 236 237 238 239 240 241 242 243

    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,
244
            "begin_step": 1,
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
        }

    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:
260 261 262 263 264 265 266
            snapshot = block.create_var(
                name=self.snapshot_name(param.name),
                shape=param.shape,
                persistable=True,
                stop_gradient=True,
                dtype=param.dtype,
            )
267 268 269 270 271 272
            p2s.append([param, snapshot])
        return p2s

    def init_snapshot_vars(self, startup_program, param2snapshot):
        with program_guard(startup_program):
            for param, snapshot in param2snapshot:
273
                paddle.assign(param, snapshot)
274 275

    def _generate_avg_loss(self, program_block, loss, avg_loss):
276 277 278 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
        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={
                'scale': 1.0 / self.role_maker._worker_num(),
                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
        )
309 310

        init_k_steps = self.user_defined_strategy.adaptive_localsgd_configs[
311 312
            'init_k_steps'
        ]
313
        begin_step_value = self.user_defined_strategy.adaptive_localsgd_configs[
314 315
            'begin_step'
        ]
316 317 318 319 320 321 322 323 324 325 326 327 328

        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):
329
            step = paddle.fluid.layers.autoincreased_step_counter(begin=1)
330

331
            k_steps = paddle.static.create_global_var(
332 333 334 335 336 337 338
                name="k_steps",
                shape=[1],
                value=int(init_k_steps),
                dtype='int64',
                persistable=True,
            )

339
            begin_step = paddle.static.create_global_var(
340 341 342 343 344 345 346
                name="begin_step",
                shape=[1],
                value=int(begin_step_value),
                dtype='int64',
                persistable=True,
            )

347
            last_step = paddle.static.create_global_var(
348 349 350 351 352 353 354
                name="last_step",
                shape=[1],
                value=int(0),
                dtype='int64',
                persistable=True,
            )

355
            avg_loss = paddle.static.create_global_var(
356 357 358 359 360 361 362
                name="avg_loss",
                shape=[1],
                value=float(0),
                dtype=loss.dtype,
                persistable=True,
            )

363
            lr_0 = paddle.static.create_global_var(
364 365 366 367 368 369 370
                name="lr_0",
                shape=[1],
                value=float(0),
                dtype='float32',
                persistable=True,
            )

371
            loss_0 = paddle.static.create_global_var(
372 373 374 375 376 377
                name="loss_0",
                shape=[1],
                value=float(0),
                dtype='float32',
                persistable=True,
            )
378 379 380 381 382

            global_lr = self.inner_opt._global_learning_rate()

            def initialize():
                self._generate_avg_loss(main_block, loss, avg_loss)
383 384
                paddle.assign(avg_loss, loss_0)
                paddle.assign(global_lr, lr_0)
385

386
            paddle.static.nn.cond(step == 1, initialize)
387 388 389 390 391

            def communicate():
                sub_block = default_main_program().current_block()
                ring_id = -1
                for param, snapshot in p2s:
392 393 394 395 396 397 398 399 400 401 402 403
                    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},
                    )
404
                    ring_id = (ring_id + 1) % self.nrings
405 406 407 408 409 410 411 412 413
                    sub_block.append_op(
                        type='c_allreduce_sum',
                        inputs={'X': [param]},
                        outputs={'Out': [param]},
                        attrs={
                            'ring_id': ring_id,
                            OP_ROLE_KEY: OpRole.Optimize,
                        },
                    )
414 415

                for ring_id in range(self.nrings):
416 417 418 419 420 421 422 423 424
                    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,
                        },
                    )
425 426

                for param, snapshot in p2s:
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
                    sub_block.append_op(
                        type='scale',
                        inputs={'X': [param]},
                        outputs={'Out': [param]},
                        attrs={
                            'scale': 1.0 / self.role_maker._worker_num(),
                            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},
                    )
448
                paddle.assign(step, last_step)
449 450 451 452

            def communicate_avg_loss():
                communicate()
                self._generate_avg_loss(main_block, loss, avg_loss)
453 454

                next_local_steps = paddle.cast(
455 456
                    paddle.ceil(
                        paddle.sqrt(
457 458 459 460 461 462 463 464
                            lr_0
                            * avg_loss
                            / (global_lr * loss_0)
                            * float(init_k_steps)
                        )
                    ),
                    dtype='int64',
                )
465 466
                max_local_steps = paddle.full(
                    shape=[1], dtype='int64', fill_value=16
467
                )
468 469
                min_local_steps = paddle.full(
                    shape=[1], dtype='int64', fill_value=1
470
                )
471
                next_local_steps = paddle.minimum(
472 473
                    next_local_steps, max_local_steps
                )
H
HongyuJia 已提交
474
                next_local_steps = paddle.maximum(
475 476
                    next_local_steps, min_local_steps
                )
477
                paddle.assign(next_local_steps, k_steps)
478 479

            def begin_localsgd():
480 481 482
                paddle.static.nn.cond(
                    step - last_step == k_steps, communicate_avg_loss
                )
483

484 485 486
            paddle.static.nn.cond(
                step > begin_step, begin_localsgd, communicate
            )
487 488

        return minimized