collective.py 19.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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

import logging
meteor135's avatar
meteor135 已提交
15
import os
16

meteor135's avatar
meteor135 已提交
17
import paddle
18
import paddle.distributed.transpiler.distribute_transpiler as dist_transpiler
19 20
import paddle.fluid as fluid
import paddle.fluid.io as io
21
from paddle.distributed.fleet.meta_optimizers import RawProgramOptimizer
22
from paddle.fluid.compiler import CompiledProgram
meteor135's avatar
meteor135 已提交
23
from paddle.fluid.executor import Executor
24
from paddle.fluid.framework import Program
25 26
from paddle.fluid.incubate.checkpoint.checkpoint_saver import (
    CheckpointSaver,
meteor135's avatar
meteor135 已提交
27 28 29 30 31 32
    PaddleModel,
)
from paddle.incubate.distributed.fleet.base import (
    DistributedOptimizer,
    Fleet,
    Mode,
33
)
34 35


36 37
class Collective(Fleet):
    def __init__(self):
38
        super().__init__(Mode.COLLECTIVE)
T
tangwei12 已提交
39
        self._local_ip = 0
40

41 42
        self.startup_program = None
        self._origin_program = None
43
        self._transpiled_program = None
44
        self.main_program = None
G
gongweibao 已提交
45
        self._checkpoint_prefix = "__paddle_fleet_checkpoint__"
46
        self._param_file_name = "_paddle_fleet_param__"
47

T
tangwei12 已提交
48
    def init_worker(self):
49
        logging.warn(
50 51
            "You should not call 'init_worker' method for collective mode."
        )
52

T
tangwei12 已提交
53
    def run_worker(self, main_programs=None, scopes=None):
54
        logging.warn(
55 56
            "You should not call 'run_worker' method for collective mode."
        )
57

T
tangwei12 已提交
58
    def init_server(self, model_dir=None):
59
        logging.warn(
60 61
            "You should not call 'init_server' method for collective mode."
        )
62

T
tangwei12 已提交
63
    def run_server(self):
64
        logging.warn(
65 66
            "You should not call 'run_server' method for collective mode."
        )
67 68 69

    def stop_worker(self):
        logging.warn(
70 71
            "You should not call 'stop_worker' method for collective mode."
        )
72 73

    def distributed_optimizer(self, optimizer, strategy=None):
74
        self._optimizer = CollectiveOptimizer(optimizer, strategy)
T
tangwei12 已提交
75
        return self._optimizer
76

77 78 79 80 81 82 83 84 85
    def save_inference_model(
        self,
        executor,
        dirname,
        feeded_var_names=None,
        target_vars=None,
        main_program=None,
        export_for_deployment=True,
    ):
86 87 88 89 90
        """
        Prune the given `main_program` to build a new program especially for
        inference, and then save it and all related parameters to given
        `dirname` by the `executor`.
        """
91 92
        assert isinstance(executor, Executor), (
            "In fleet.save_inference_model() function, executor must be as"
93
            " Executor type."
94
        )
95 96 97

        if main_program is None:
            main_program = self._origin_program
98 99
        assert isinstance(main_program, Program), (
            "In fleet.save_inference_model() function, main_program "
100
            "must be as Program type."
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
        )

        io.save_inference_model(
            dirname,
            feeded_var_names,
            target_vars,
            executor,
            main_program,
            None,
            None,
            export_for_deployment,
        )

    def save_persistables(
        self, executor, dirname, main_program=None, filename=None
    ):
117 118 119 120 121 122 123 124 125 126
        """
        This function filters out all variables with `persistable==True` from
        the give `main_program` and then saves these variables to the folder
        `dirname` or file `filename`.

        The `dirname` is used to specify the folder where persistable variables
        are going to be saved. If you would like to save variables in separate
        files, set `filename` None; if you would like to save all variables in a
        single file, use `filename` to specify the file name.
        """
127 128
        assert isinstance(executor, Executor), (
            "In fleet.save_inference_model() function, executor must be as"
129
            " Executor type."
130
        )
131 132 133 134

        if main_program is None:
            main_program = self._origin_program

135 136
        assert isinstance(main_program, Program), (
            "In fleet.save_inference_model() function, main_program "
137
            "must be as Program type."
138
        )
139

140 141 142
        paddle.distributed.io.save_persistables(
            executor, dirname, main_program, filename=filename
        )
143

144 145 146 147 148 149 150 151 152 153 154
    def save_checkpoint(
        self,
        executor,
        path,
        trainer_id,
        train_status,
        fs,
        main_program=None,
        local_cache_path=".cache",
        remain_all_checkpoint=True,
    ):
155 156 157
        """
        This function save persistables and current epoch num to path.
        """
158
        if main_program is None:
159 160
            main_program = self._transpiled_program

161 162 163 164 165 166 167
        m = PaddleModel(executor, main_program)
        t = train_status
        c = CheckpointSaver(fs)
        real_path, checkpoint_no = c.save_checkpoint(
            path=path,
            slists=[m, t],
            trainer_id=trainer_id,
168 169
            local_cache_path=local_cache_path,
        )
170 171

        if not remain_all_checkpoint:
172 173 174
            c.clean_redundant_checkpoints(path)

        return real_path, checkpoint_no
G
gongweibao 已提交
175

176 177 178 179 180 181 182 183 184 185 186
    def load_checkpoint(
        self,
        executor,
        path,
        trainer_id,
        train_status,
        fs,
        main_program=None,
        local_cache_path=".cache",
        ignore_empty=True,
    ):
187 188 189 190
        """
        This function load persistables and current epoch num from path.
        """

191
        if main_program is None:
192 193
            main_program = self._transpiled_program

194 195
        m = PaddleModel(executor, main_program)
        c = CheckpointSaver(fs)
196 197 198 199 200 201 202
        return c.load_checkpoint(
            path,
            [m, train_status],
            trainer_id=trainer_id,
            ignore_empty=ignore_empty,
            local_cache_path=local_cache_path,
        )
203

204 205 206 207

fleet = Collective()


208 209 210 211 212 213
class DistributedStrategy(fluid.BuildStrategy):
    """
    Init function of DistributedStrategy
    """

    def __init__(self):
214
        super().__init__()
215 216 217 218 219 220
        self.use_local_sgd = False
        self.use_dist_fc = False

        self.dist_fc_config = None  # DistFCConfig
        self.mode = "nccl2"  # or collective
        self.collective_mode = None  # local_sgd or grad_allreduce
G
gongweibao 已提交
221
        self.nccl_comm_num = 1
M
mapingshuo 已提交
222
        self.forward_recompute = False  # use RecomputeOptimizer
M
mapingshuo 已提交
223
        self.recompute_checkpoints = []
M
mapingshuo 已提交
224 225
        self.use_amp = False  # use mixed precision optimizer
        self.amp_loss_scaling = 2**15
226 227 228

        self.exec_strategy = fluid.ExecutionStrategy()

229 230 231
        # configurations below are used for unit test
        self._ut4grad_allreduce = False

232

233 234
class CollectiveOpBasedOptimizer(DistributedOptimizer):
    """
235 236
    Collective Operator Base Class For Distributed Optimizer
    The class is invisible to a user
237 238 239
    """

    def __init__(self, optimizer, strategy=None):
240
        assert isinstance(
241 242
            strategy, DistributedStrategy
        ), "strategy must be DistributedStrategy"
243
        super().__init__(optimizer, strategy)
244

245 246 247 248 249 250 251 252 253 254 255
    def backward(
        self,
        loss,
        startup_program=None,
        parameter_list=None,
        no_grad_set=None,
        callbacks=None,
    ):
        return self._optimizer.backward(
            loss, startup_program, parameter_list, no_grad_set, callbacks
        )
256 257 258 259 260

    def apply_gradients(self, params_grads):
        return self._optimizer.apply_gradients(params_grads)


261 262 263 264 265 266 267 268 269 270 271
class CollectiveOptimizer(DistributedOptimizer):
    """
    DistributedOptimizer is a wrapper for paddle.fluid.optimizer
    A user should pass a paddle.fluid.optimizer to DistributedOptimizer
    minimize() function is implemented.
    DistributedOptimizer is the starting point for a user who wants to
    run distributed training. The optimized information will be stored in
    Fleet() instance who holds the global information about current distributed
    training.
    """

272
    def __init__(self, optimizer, strategy=DistributedStrategy()):
273 274
        if strategy is None:
            strategy = DistributedStrategy()
275
        super().__init__(optimizer, strategy)
M
mapingshuo 已提交
276
        self._forward_recompute = strategy.forward_recompute
277 278 279 280
        if not isinstance(strategy.recompute_checkpoints, list):
            raise ValueError(
                "DistStrategy.recompute_checkpoints should" "be a List"
            )
M
mapingshuo 已提交
281 282 283
        self._recompute_checkpoints = strategy.recompute_checkpoints
        self._use_amp = strategy.use_amp
        self._amp_loss_scaling = strategy.amp_loss_scaling
284
        self.print_config = False
285

286 287 288 289 290 291 292 293 294 295 296
    def backward(
        self,
        loss,
        startup_program=None,
        parameter_list=None,
        no_grad_set=None,
        callbacks=None,
    ):
        return self._optimizer.backward(
            loss, startup_program, parameter_list, no_grad_set, callbacks
        )
297 298 299 300

    def apply_gradients(self, params_grads):
        return self._optimizer.apply_gradients(params_grads)

301
    def _check_condition(self, name, **kwargs):
302
        for k, v in kwargs.items():
303
            if v is True:
304 305 306
                raise AssertionError(
                    "you can't use %s and %s together" % (name, k)
                )
307 308 309

    def _check_collective_mode(self, main_program, optimizer, strategy):
        """
T
tianshuo78520a 已提交
310
        Check the conflict conditions.
311 312
        """
        if strategy.use_local_sgd:
313 314
            strategy.mode = "collective"
            strategy.collective_mode = "local_sgd"
315 316 317 318 319 320
            self._check_condition(
                "use_local_sgd",
                use_dgc=main_program._enable_dgc,
                use_dist_fc=strategy.use_dist_fc,
                use_lamb=main_program._use_lamb,
            )
321 322

        if strategy.use_dist_fc:
323 324 325 326 327 328 329 330 331
            self._check_condition(
                "use_dist_fc",
                use_dgc=main_program._enable_dgc,
                use_local_sgd=strategy.use_local_sgd,
                use_lamb=main_program._use_lamb,
            )
            assert (
                strategy.dist_fc_config is not None
            ), "DistributedStrategy.dist_fc_config should be set"
332

333 334 335
        if strategy._ut4grad_allreduce:
            strategy.mode = "collective"
            strategy.collective_mode = "grad_allreduce"
336 337 338 339 340
            self._check_condition(
                "_ut4grad_allreduce",
                use_dgc=main_program._enable_dgc,
                use_lamb=main_program._use_lamb,
            )
341

342 343 344 345 346 347 348
        if (
            self._strategy.collective_mode == "local_sgd"
            or self._strategy.collective_mode == "grad_allreduce"
        ):
            assert (
                self._strategy.mode == "collective"
            ), "local_sgd and grad_allreduce can be used under collective mode"
349 350 351 352 353 354 355 356 357 358 359 360

    def _transpile(self, startup_program, main_program):
        """
        Transpile the programs to distributed programs. And add the variables.
        """
        worker_endpoints = fleet.worker_endpoints()
        trainer_id = fleet.worker_index()
        current_endpoint = fleet.worker_endpoints()[trainer_id]
        worker_endpoints_env = ','.join(worker_endpoints)
        trainers_num = fleet.worker_num()

        if self.print_config:
361 362 363 364 365 366
            print(
                "worker_endpoints:{} trainers_num:{} current_endpoint:{} \
                  trainer_id:{}".format(
                    worker_endpoints, trainers_num, current_endpoint, trainer_id
                )
            )
367 368 369 370 371 372 373

        # call transpiler
        config = dist_transpiler.DistributeTranspilerConfig()
        config.mode = self._strategy.mode
        config.collective_mode = self._strategy.collective_mode

        config.nccl_comm_num = self._strategy.nccl_comm_num
374 375 376 377 378 379
        config.use_hierarchical_allreduce = (
            self._strategy.use_hierarchical_allreduce
        )
        config.hierarchical_allreduce_inter_nranks = (
            self._strategy.hierarchical_allreduce_inter_nranks
        )
380 381

        t = dist_transpiler.DistributeTranspiler(config=config)
382 383 384 385 386 387 388
        t.transpile(
            trainer_id=trainer_id,
            trainers=worker_endpoints_env,
            startup_program=startup_program,
            program=main_program,
            current_endpoint=current_endpoint,
        )
389

G
gongweibao 已提交
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
    def _get_node_ips_from_endpoints(self, endpoints):
        ss = set()
        ips = []
        for ep in endpoints:
            ip = ep.split(":")[0].strip()
            if ip not in ss:
                ss.add(ip)
                ips.append(ip)
            else:
                continue

        return ips

    def _node_num(self):
        worker_endpoints = fleet.worker_endpoints()
        current_endpoint = fleet.worker_endpoints()[fleet.worker_index()]
        worker_endpoints_env = ','.join(worker_endpoints)

        node_ips = self._get_node_ips_from_endpoints(worker_endpoints)
        node_ip = current_endpoint.split(":")[0].strip()

        node_num = len(node_ips)

        return node_num

415
    def _try_to_compile(self, startup_program, main_program):
G
gongweibao 已提交
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 441 442
        node_num = self._node_num()
        assert node_num >= 1, "nccl2 node_num must >= 1, now:{}" % node_num

        exec_strategy = self._strategy.exec_strategy

        if node_num <= 1:
            if self._strategy.nccl_comm_num > 1:
                logging.warn("set nccl_comm_num=1 since you only have 1 node.")
            self._strategy.nccl_comm_num = 1

            if self._strategy.use_hierarchical_allreduce:
                logging.warn(
                    "set use_hierarchical_allreduce=False since you only have 1 node."
                )
            self._strategy.use_hierarchical_allreduce = False

        sync_allreduce = os.getenv("FLAGS_sync_nccl_allreduce")
        if sync_allreduce is None or sync_allreduce == "1":
            exec_strategy.num_threads = self._strategy.nccl_comm_num + 1
            if self._strategy.use_hierarchical_allreduce:
                exec_strategy.num_threads = 2 * self._strategy.nccl_comm_num + 1
            if exec_strategy.num_threads > 4:
                logging.warn(
                    "if you use use_hierarchical_allreduce or "
                    "with multi nccl comm, please export FLAGS_sync_nccl_allreduce = 0"
                )

443 444 445 446 447 448 449 450 451 452 453
        # NOTE. open sync_batch_norm will hang when use multi num_threads
        sync_batch_norm = self._strategy.sync_batch_norm
        if sync_batch_norm is not None and sync_batch_norm is True:
            self._strategy.nccl_comm_num = 1
            self._strategy.use_hierarchical_allreduce = False
            exec_strategy.num_threads = 1
            logging.warn(
                "use sync_batch_norm will hang when set num_threads > 1, so "
                "set num_threads=1, nccl_comm_num=1, use_hierarchical_allreduce=False."
            )

G
gongweibao 已提交
454
        if self.print_config:
455 456 457 458 459 460 461 462 463 464 465 466
            print(
                "node_num:",
                node_num,
                "num_threads:",
                exec_strategy.num_threads,
                "use_hierarchical_allreduce:",
                self._strategy.use_hierarchical_allreduce,
                "nccl_comm_num:",
                self._strategy.nccl_comm_num,
                "FLAGS_sync_nccl_allreduce:",
                sync_allreduce,
            )
G
gongweibao 已提交
467

468 469 470 471 472 473 474 475 476 477
        self._transpile(startup_program, main_program)

        if self._strategy.mode == "collective":
            return main_program

        self._strategy.num_trainers = fleet.worker_num()
        self._strategy.trainer_id = fleet.worker_index()
        self._strategy.trainers_endpoints = fleet.worker_endpoints()
        self._strategy.enable_backward_optimizer_op_deps = True

478 479 480 481 482 483 484 485 486 487 488 489 490
        comm_opt = RawProgramOptimizer(self._optimizer)
        comm_opt.fuse_all_reduce_ops = True
        comm_opt.fuse_grad_size_in_num = True
        comm_opt.endpoints = self._strategy.trainers_endpoints
        comm_opt.current_endpoint = comm_opt.endpoints[fleet.worker_index()]
        comm_opt.rank = fleet.worker_index()
        comm_opt.nranks = fleet.worker_num()
        comm_opt.main_program = main_program
        if comm_opt.nranks > 1:
            comm_opt._transpile_main_program(self._loss)

        self._compiled_program = CompiledProgram(
            comm_opt.main_program, build_strategy=self._strategy
491
        )
492 493 494

        return self._compiled_program

M
mapingshuo 已提交
495
    def raiseOptimizeError(self, strategy_name, optimize_name):
496 497 498 499 500 501 502 503
        raise ValueError(
            "can not use {0} when you set DistStrategy.{1} "
            "as True".format(optimize_name, strategy_name)
        )

    def minimize(
        self, loss, startup_program=None, parameter_list=None, no_grad_set=None
    ):
504 505 506 507 508 509 510 511 512 513 514 515
        """
        minimize a program through loss
        Args:
            loss (Variable|Variable List): loss variable or loss variable list to run optimization.
            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.
        Returns:
            tuple: (optimize_ops, params_grads) which are, list of operators appended;
            and list of (param, grad) Variables pair for optimization.
        Note that in parameter server mode, a worker will not get anything about optimize_os
T
tianshuo78520a 已提交
516
        Because optimizer algorithms run on pserver side. We will make this usable in pserver
517 518 519
        process, but currently the optimization part is written into Fleet(). A user does not
        need to care about how to startup a pserver node.
        """
M
mapingshuo 已提交
520 521 522 523

        # check optimizer conflicts
        if self._forward_recompute:
            if self._recompute_checkpoints == []:
524 525 526 527
                raise ValueError(
                    "please set strategy.recompute_checkpoints"
                    "when set strategy.forward_recompute as True"
                )
M
mapingshuo 已提交
528
            if self._optimizer.__class__.__name__ in [
529 530
                "RecomputeOptimizer",
                "OptimizerWithMixedPrecision",
M
mapingshuo 已提交
531
            ]:
532 533 534
                self.raiseOptimizeError(
                    "forward_recompute", self._optimizer.__class__.__name__
                )
M
mapingshuo 已提交
535

536 537 538
            self._optimizer = fluid.optimizer.RecomputeOptimizer(
                self._optimizer
            )
M
mapingshuo 已提交
539 540 541 542
            self._optimizer._set_checkpoints(self._recompute_checkpoints)

        if self._use_amp:
            if self._optimizer.__class__.__name__ in [
543 544
                "OptimizerWithMixedPrecision",
                "DGCMomentumOptimizer",
M
mapingshuo 已提交
545
            ]:
546 547 548
                self.raiseOptimizeError(
                    "mixed_precision", self._optimizer.__class__.__name__
                )
549
            self._optimizer = paddle.static.amp.decorate(
M
mapingshuo 已提交
550 551
                self._optimizer,
                init_loss_scaling=self._amp_loss_scaling,
552 553
                use_dynamic_loss_scaling=True,
            )
M
mapingshuo 已提交
554

555 556 557 558
        main_program = loss.block.program
        if startup_program is None:
            startup_program = fluid.default_startup_program()
        fleet.startup_program = startup_program
559

560
        self._loss = loss
561

562 563 564
        self._check_collective_mode(
            main_program, self._optimizer, self._strategy
        )
565

566
        optimize_ops, param_grads = self._optimizer.minimize(
567 568
            loss, startup_program, parameter_list, no_grad_set=no_grad_set
        )
569

570 571
        fleet._origin_program = main_program.clone(for_test=False)
        fleet._transpiled_program = main_program
572
        fleet.main_program = self._try_to_compile(startup_program, main_program)
573 574

        return optimize_ops, param_grads