distributed_strategy.py 87.9 KB
Newer Older
1 2
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
# Copyright (c) 2021 NVIDIA Corporation. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15
#
# 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.

16
import paddle
17
from paddle.distributed.fleet.utils.log_util import logger
18
from paddle.distributed.fleet.proto import distributed_strategy_pb2
19
from paddle.fluid.framework import _global_flags
20
from paddle.fluid.wrapped_decorator import wrap_decorator
21
import google.protobuf.text_format
22
import google.protobuf
23

24
__all__ = []
25

26 27 28 29 30 31 32 33 34 35 36 37 38 39
non_auto_func_called = True


def __non_auto_func_called__(func):
    def __impl__(*args, **kwargs):
        global non_auto_func_called
        non_auto_func_called = False
        return func(*args, **kwargs)

    return __impl__


is_strict_auto = wrap_decorator(__non_auto_func_called__)

40

41 42 43 44 45 46 47 48 49 50 51 52 53
def get_msg_dict(msg):
    res_dict = {}
    fields = msg.DESCRIPTOR.fields
    for f in fields:
        res_dict[f.name] = getattr(msg, f.name)
    return res_dict


def assign_configs_value(msg, config):
    fields = msg.DESCRIPTOR.fields
    for key in config:
        for f in fields:
            if key == f.name:
54 55 56
                # LABEL_OPTIONAL = 1
                # LABEL_REPEATED = 3
                # LABEL_REQUIRED = 2
57 58 59 60 61 62 63 64 65 66 67 68
                if f.label == 3:
                    getattr(msg, f.name).extend(config[f.name])
                elif f.label == 1 or f.label == 2:
                    setattr(msg, f.name, config[f.name])


def check_configs_key(msg, config, field_name):
    key_list = msg.DESCRIPTOR.fields_by_name.keys()
    for key in config:
        assert key in key_list, "key:{} not in {}".format(key, field_name)


69
class DistributedJobInfo:
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
    """
    DistributedJobInfo will serialize all distributed training information
    Just for inner use: 1) debug 2) replicate experiments
    """

    def __init__(self):
        self.job_info = distributed_strategy_pb2.DistributedJobInfo()

    def _set_worker_num(self, worker_num):
        self.job_info.worker_num = worker_num

    def _set_server_num(self, server_num):
        self.job_info.server_num = server_num

    def _set_worker_ips(self, worker_ips):
        self.job_info.worker_ips.extend(worker_ips)

    def _set_server_endpoints(self, server_endpoints):
        self.job_info.server_endpoints.extend(server_endpoints)

    def _set_origin_startup(self, origin_startup_prog):
        self.job_info.origin_startup = str(origin_startup_prog)

    def _set_origin_main(self, origin_main_prog):
        self.job_info.origin_main = str(origin_main_prog)

    def _distributed_main(self, distributed_main_prog):
        self.job_info.distributed_main = str(distributed_main_prog)

    def _optimizer_name(self, optimizer_name):
        self.job_info.optimizer_name = optimizer_name

    def _set_distributed_strategy(self, dist_strategy):
        self.job_info.strategy = dist_strategy


106 107 108 109
ReduceStrategyFluid = paddle.fluid.BuildStrategy.ReduceStrategy
ReduceStrategyFleet = int


110
class DistributedStrategy:
111 112
    __lock_attr = False

113
    def __init__(self):
114
        """
115

116 117
        DistributedStrategy is the main configuration entry for distributed training of Paddle.
        All of the distributed training configurations can be configured in DistributedStrategy,
118
        such as automatic mixed precision (AMP), Layer-wise Adaptive Rate Scaling (LARS),
119
        asynchronous update parameter server(ASGD), etc.
1
123malin 已提交
120

121 122
        DistributedStrategy can be serialized into protobuf file or deserialized from protobuf file

123
        Users who run local training usually configure BuildStrategy and ExecutionStrategy, and
124 125 126
        DistributedStrategy supports configurations from BuildStrategy and ExecutionStrategy

        """
127
        self.strategy = distributed_strategy_pb2.DistributedStrategy()
128 129 130

        # Set the default values of the following flags to the ones set by users
        key = 'FLAGS_cudnn_batchnorm_spatial_persistent'
131
        if _global_flags().is_public(key):
132
            self.strategy.cudnn_batchnorm_spatial_persistent = bool(
133 134
                _global_flags()[key]
            )
135
        key = 'FLAGS_conv_workspace_size_limit'
136 137
        if _global_flags().is_public(key):
            self.strategy.conv_workspace_size_limit = int(_global_flags()[key])
138
        key = 'FLAGS_cudnn_exhaustive_search'
139 140
        if _global_flags().is_public(key):
            self.strategy.cudnn_exhaustive_search = bool(_global_flags()[key])
141
        key = 'FLAGS_sync_nccl_allreduce'
142 143
        if _global_flags().is_public(key):
            self.strategy.sync_nccl_allreduce = bool(_global_flags()[key])
144

145
        self.__lock_attr = True
146
        logger.info("distributed strategy initialized")
147 148 149

    def __setattr__(self, key, value):
        if self.__lock_attr and not hasattr(self, key):
150 151 152
            raise TypeError(
                "%s is not a attribute of %s" % (key, self.__class__.__name__)
            )
153
        object.__setattr__(self, key, value)
154

155
    def save_to_prototxt(self, output):
156
        """
157

158 159 160
        Serialize current DistributedStrategy to string and save to output file

        Examples:
161
            .. code-block:: python
1
123malin 已提交
162

163 164 165 166 167 168
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.dgc = True
                strategy.recompute = True
                strategy.recompute_configs = {"checkpoints": ["x"]}
                strategy.save_to_prototxt("dist_strategy.prototxt")
1
123malin 已提交
169

170
        """
171 172 173 174
        with open(output, "w") as fout:
            fout.write(str(self.strategy))

    def load_from_prototxt(self, pb_file):
175
        """
176

177 178 179
        Load from prototxt file for DistributedStrategy initialization

        Examples:
180
            .. code-block:: python
1
123malin 已提交
181

182 183 184
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.load_from_prototxt("dist_strategy.prototxt")
185 186 187 188

        """
        with open(pb_file, 'r') as f:
            self.strategy = google.protobuf.text_format.Merge(
189 190
                str(f.read()), self.strategy
            )
191 192 193 194 195 196 197

    @property
    def execution_strategy(self):
        """
        Configure ExecutionStrategy for DistributedStrategy

        Examples:
198
            .. code-block:: python
1
123malin 已提交
199

200 201 202 203 204
                import paddle
                exe_strategy = paddle.static.ExecutionStrategy()
                exe_strategy.num_threads = 10
                exe_strategy.num_iteration_per_drop_scope = 10
                exe_strategy.num_iteration_per_run = 10
205

206 207
                strategy = paddle.distributed.fleet.DistributedStrategy()
                strategy.execution_strategy = exe_strategy
208 209 210 211 212

        """
        execution_strategy = paddle.fluid.ExecutionStrategy()
        fields = self.strategy.execution_strategy.DESCRIPTOR.fields
        for f in fields:
213 214 215 216 217
            setattr(
                execution_strategy,
                f.name,
                getattr(self.strategy.execution_strategy, f.name),
            )
218 219 220
        return execution_strategy

    @execution_strategy.setter
221
    @is_strict_auto
222 223 224
    def execution_strategy(self, strategy):
        fields = self.strategy.execution_strategy.DESCRIPTOR.fields
        for f in fields:
225 226 227 228 229
            setattr(
                self.strategy.execution_strategy,
                f.name,
                getattr(strategy, f.name),
            )
230 231 232 233

    @property
    def build_strategy(self):
        """
234

235 236 237 238 239
        Configure BuildStrategy for DistributedStrategy
        Note that the properties of BuildStrategy are valid in DistributedStrategy
        only if the property is non-distributed strategy.

        Examples:
240
            .. code-block:: python
1
123malin 已提交
241

242 243 244 245 246 247 248 249 250 251
                import paddle
                build_strategy = paddle.static.BuildStrategy()
                build_strategy.enable_sequential_execution = True
                build_strategy.fuse_elewise_add_act_ops = True
                build_strategy.fuse_bn_act_ops = True
                build_strategy.enable_auto_fusion = True
                build_strategy.fuse_relu_depthwise_conv = True
                build_strategy.fuse_broadcast_ops = True
                build_strategy.fuse_all_optimizer_ops = True
                build_strategy.enable_inplace = True
252

253 254
                strategy = paddle.distributed.fleet.DistributedStrategy()
                strategy.build_strategy = build_strategy
1
123malin 已提交
255

256 257 258 259 260
        """

        build_strategy = paddle.fluid.BuildStrategy()
        fields = self.strategy.build_strategy.DESCRIPTOR.fields
        for f in fields:
261 262 263 264
            value = getattr(self.strategy.build_strategy, f.name)
            if f.name == 'reduce_strategy':
                value = ReduceStrategyFluid(value)
            setattr(build_strategy, f.name, value)
265 266 267
        return build_strategy

    @build_strategy.setter
268
    @is_strict_auto
269 270 271 272
    def build_strategy(self, strategy):
        fields = self.strategy.build_strategy.DESCRIPTOR.fields
        for f in fields:
            if f.label == 1 or f.label == 2:  # optional and required field
273 274 275 276
                value = getattr(strategy, f.name)
                if f.name == 'reduce_strategy':
                    value = ReduceStrategyFleet(value)
                setattr(self.strategy.build_strategy, f.name, value)
277
            elif f.label == 3:  # repeated field
278 279 280
                getattr(self.strategy.build_strategy, f.name).extend(
                    getattr(strategy, f.name)
                )
281 282

    @property
Y
Yuang Liu 已提交
283 284
    def gradient_scale_configs(self):
        """
285

Y
Yuang Liu 已提交
286
        Set the strategy of gradient scale
287

Y
Yuang Liu 已提交
288
        Examples:
289
            .. code-block:: python
Y
Yuang Liu 已提交
290

291 292 293
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.gradient_scale_configs = {'scale_strategy': 'avg'}
Y
Yuang Liu 已提交
294 295

        Note that, strategy must be in 'avg', 'sum' or 'customized'
296

Y
Yuang Liu 已提交
297 298 299 300 301 302
        """
        return get_msg_dict(self.strategy.gradient_scale_configs)

    @gradient_scale_configs.setter
    @is_strict_auto
    def gradient_scale_configs(self, config):
303 304 305 306 307
        check_configs_key(
            self.strategy.gradient_scale_configs,
            config,
            'gradient_scale_configs',
        )
Y
Yuang Liu 已提交
308 309 310
        assign_configs_value(self.strategy.gradient_scale_configs, config)

    @property
D
Dong Daxiang 已提交
311
    def a_sync(self):
312
        """
313

314
        Indicating whether we are using asynchronous stocastic gradient descent updates
315
        for training. This property is valid when we are using parameter server training,
316 317 318 319
        which is implied by setting approperate RoleMaker
        Default value: True

        Examples:
320
            .. code-block:: python
1
123malin 已提交
321

322 323 324
                import paddle.distributed.fleet as fleet
                role_maker = fleet.PaddleCloudRoleMaker()
                fleet.init(role_maker)
325

326 327
                strategy = fleet.DistributedStrategy()
                strategy.a_sync = True  # by default this is True
328

329 330
                # code block for defining loss and local optimizer
                # sgd = fleet.distributed_optimizer(optimizer, strategy)
1
123malin 已提交
331

332
        """
D
Dong Daxiang 已提交
333
        return self.strategy.a_sync
334

D
Dong Daxiang 已提交
335
    @a_sync.setter
336
    @is_strict_auto
D
Dong Daxiang 已提交
337
    def a_sync(self, flag):
338
        if isinstance(flag, bool):
D
Dong Daxiang 已提交
339
            self.strategy.a_sync = flag
340
            self.a_sync_configs = {"k_steps": 0}
341
        else:
342
            raise ValueError(
343 344 345 346
                "The type of `flag` is invalid, expected type is bool, but received {}".format(
                    type(flag)
                )
            )
347 348

    @property
D
Dong Daxiang 已提交
349
    def a_sync_configs(self):
350
        """
351

D
Dong Daxiang 已提交
352
        Set a_sync update configurations. In general, asynchronous parameter server
353 354
        training has serveral configurable settings that can be configured through
        a dict.
355

356
        **Notes**:
M
mapingshuo 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369
            k_step(int): number of local optimization updates before communication

            max_merge_var_num(int): maximum number of merged gradients before communication

            send_queue_size(int): a buffer size of worker communication

            independent_recv_thread(bool): if we are using independent recv thread for communication

            thread_pool_size(int): number of thread pool

            send_wait_times(int): waiting time for sending gradients

            runtime_split_send_recv(bool): if we are using Tensor split for send and recv during runtime
370

371
        Examples:
372
            .. code-block:: python
1
123malin 已提交
373

374 375 376
                import paddle.distributed.fleet as fleet
                role_maker = fleet.PaddleCloudRoleMaker()
                fleet.init(role_maker)
377

378 379 380 381
                strategy = fleet.DistributedStrategy()
                strategy.a_sync = True  # by default this is True
                configs = {"k_steps": 1024, "send_queue_size": 32}
                strategy.a_sync_configs = configs
382

383 384
                # code block for defining loss and local optimizer
                # sgd = fleet.distributed_optimizer(optimizer, strategy)
M
mapingshuo 已提交
385

386
        """
D
Dong Daxiang 已提交
387
        return get_msg_dict(self.strategy.a_sync_configs)
388

D
Dong Daxiang 已提交
389
    @a_sync_configs.setter
390
    @is_strict_auto
D
Dong Daxiang 已提交
391
    def a_sync_configs(self, configs):
392 393 394
        check_configs_key(
            self.strategy.a_sync_configs, configs, "a_sync_configs"
        )
D
Dong Daxiang 已提交
395
        assign_configs_value(self.strategy.a_sync_configs, configs)
396

397 398 399
    @property
    def trainer_desc_configs(self):
        """
400

401
        Set trainer desc configurations.
402 403 404 405 406 407 408 409

        **Notes**:
            dump_fields_path(str): the path of dump fields

            dump_fields(list(str)): the fields that you want to dump

            dump_param(list(str)): the param that you want to dump

410
            stat_var_names(list(str)):
411 412

        Examples:
413
            .. code-block:: python
414

415 416 417
                import paddle.distributed.fleet as fleet
                role_maker = fleet.PaddleCloudRoleMaker()
                fleet.init(role_maker)
418

419 420 421
                strategy = fleet.DistributedStrategy()
                configs = {"dump_fields_path": "./dump_data", "dump_fields": ["xxx", "yyy"]}
                strategy.trainer_desc_configs = configs
422

423 424
                # code block for defining loss and local optimizer
                # sgd = fleet.distributed_optimizer(optimizer, strategy)
425 426 427 428

        """
        return get_msg_dict(self.strategy.trainer_desc_configs)

429 430 431
    @property
    def adam_d2sum(self):
        """
432

433
        set adam_d2sum
W
wangguanqun 已提交
434
        Default value: False
435 436

        Examples:
437
            .. code-block:: python
438

439 440 441
                import paddle.distributed.fleet as fleet
                role_maker = fleet.PaddleCloudRoleMaker()
                fleet.init(role_maker)
442

443 444
                strategy = fleet.DistributedStrategy()
                strategy.adam_d2sum = True  # by default this is False
445

446 447
                # code block for defining loss and local optimizer
                # sgd = fleet.distributed_optimizer(optimizer, strategy)
448 449 450 451 452 453 454 455 456 457 458

        """
        return self.strategy.adam_d2sum

    @adam_d2sum.setter
    @is_strict_auto
    def adam_d2sum(self, flag):
        if isinstance(flag, bool):
            self.strategy.adam_d2sum = flag
        else:
            raise ValueError(
459 460 461 462
                "The type of `flag` is invalid, expected type is bool, but received {}".format(
                    type(flag)
                )
            )
463

464 465 466
    @trainer_desc_configs.setter
    @is_strict_auto
    def trainer_desc_configs(self, configs):
467 468 469
        check_configs_key(
            self.strategy.trainer_desc_configs, configs, "trainer_desc_configs"
        )
470 471
        assign_configs_value(self.strategy.trainer_desc_configs, configs)

472 473 474
    @property
    def fs_client_param(self):
        """
475

476
        Set fs client configurations.
477 478

        Note:
479
            uri(str): the uri of fs client
480

481
            user(str): the user_name of fs client
482

483
            passwd(str): the passwd of fs client
484

485
            hadoop_bin(str):
486

487
        Examples:
488 489 490 491 492 493 494 495 496 497 498
            .. code-block:: python

                import paddle.distributed.fleet as fleet
                role_maker = fleet.PaddleCloudRoleMaker()
                fleet.init(role_maker)
                strategy = fleet.DistributedStrategy()
                configs = {"uri": "xxx", "user": "xxx", passwd: "xxx"}
                strategy.fs_client_param = configs
                # code block for defining loss and local optimizer
                # sgd = fleet.distributed_optimizer(optimizer, strategy)

499 500 501 502 503 504
        """
        return self.strategy.fs_client_param

    @fs_client_param.setter
    @is_strict_auto
    def fs_client_param(self, configs):
505 506 507
        check_configs_key(
            self.strategy.fs_client_param, configs, "fs_client_param"
        )
508 509 510 511 512 513 514 515 516 517
        assign_configs_value(self.strategy.fs_client_param, configs)

    @property
    def sparse_table_configs(self):
        return self.strategy.downpour_table_param

    @sparse_table_configs.setter
    @is_strict_auto
    def sparse_table_configs(self, configs):
        from google.protobuf.descriptor import FieldDescriptor
518

519 520
        table_param = self.strategy.downpour_table_param

521
        def set_table_config(msg, config_name, configs, index=0):
522 523 524
            for field in msg.DESCRIPTOR.fields:
                name = config_name + "." + field.name
                if field.type == FieldDescriptor.TYPE_MESSAGE:
525
                    logger.debug(f"message: {name}")
526 527 528 529
                    if field.label == FieldDescriptor.LABEL_REPEATED:
                        if name + ".num" not in configs:
                            continue
                        num = configs[name + ".num"]
530
                        logger.debug(f"message num: {name} {num}")
531 532 533 534
                        for i in range(num):
                            data = getattr(msg, field.name).add()
                            set_table_config(data, name, configs, i)
                    else:
535 536 537
                        set_table_config(
                            getattr(msg, field.name), name, configs
                        )
538
                else:
539
                    logger.debug("not message:", name)
540 541 542 543 544
                    if name not in configs:
                        continue
                    if field.label == FieldDescriptor.LABEL_REPEATED:
                        getattr(msg, field.name).extend(configs[name])
                    else:
545 546 547 548
                        if type(configs[name]) == list:
                            setattr(msg, field.name, configs[name][index])
                        else:
                            setattr(msg, field.name, configs[name])
549

550
        if not configs:
551
            logger.info("table configs is empty")
552
        else:
553 554 555
            for table_name in configs:
                table_data = table_param.add()
                table_data.table_name = table_name
556 557 558 559 560
                set_table_config(
                    table_data,
                    "table_parameters." + table_name,
                    configs[table_name],
                )
561

562 563
    @sparse_table_configs.setter
    def fleet_desc_configs(self, configs):
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
        support_sparse_key_list = [
            'sparse_table_class',
            'sparse_compress_in_save',
            'sparse_shard_num',
            'sparse_accessor_class',
            'sparse_learning_rate',
            'sparse_initial_g2sum',
            'sparse_initial_range',
            'sparse_weight_bounds',
            'sparse_fea_dim',
            'sparse_embedx_dim',
            'sparse_embedx_threshold',
            'sparse_nonclk_coeff',
            'sparse_click_coeff',
            'sparse_base_threshold',
            'sparse_delta_threshold',
            'sparse_delta_keep_days',
            'sparse_delete_after_unseen_days',
            'sparse_show_click_decay_rate',
            'sparse_delete_threshold',
            'sparse_converter',
            'sparse_deconverter',
            'sparse_enable_cache',
            'sparse_cache_rate',
            'sparse_cache_file_num',
            'sparse_beta1_decay_rate',
            'sparse_beta2_decay_rate',
            'sparse_ada_epsilon',
            'sparse_optimizer',
            'sparse_ssd_unseenday_threshold',
            'embed_sparse_optimizer',
            'embed_sparse_learning_rate',
            'embed_sparse_weight_bounds',
            'embed_sparse_initial_range',
            'embed_sparse_initial_g2sum',
            'embed_sparse_beta1_decay_rate',
            'embed_sparse_beta2_decay_rate',
            'embedx_sparse_optimizer',
            'embedx_sparse_learning_rate',
            'embedx_sparse_weight_bounds',
            'embedx_sparse_initial_range',
            'embedx_sparse_initial_g2sum',
            'embedx_sparse_beta1_decay_rate',
            'embedx_sparse_beta2_decay_rate',
            'feature_learning_rate',
            'nodeid_slot',
        ]
611 612
        support_sparse_table_class = ['DownpourSparseTable']
        support_sparse_accessor_class = [
613 614 615 616 617 618
            'DownpourSparseValueAccessor',
            'DownpourCtrAccessor',
            'DownpourCtrDoubleAccessor',
            'DownpourUnitAccessor',
            'DownpourDoubleUnitAccessor',
            'DownpourCtrDymfAccessor',
619 620 621
        ]
        table_param = self.strategy.downpour_table_param

D
danleifeng 已提交
622
        def add_graph_config(graph, strategy):
623 624 625
            graph.feature_learning_rate = strategy.get(
                'feature_learning_rate', 0.05
            )
D
danleifeng 已提交
626 627
            graph.nodeid_slot = strategy.get('nodeid_slot', 9008)

628
        def sparse_optimizer_config(sgd, strategy, prefix):
629 630 631
            optimizer_name = strategy.get(
                prefix + "sparse_optimizer", "adagrad"
            )
632 633 634 635
            sgd.name = optimizer_name
            if optimizer_name == "naive":
                sgd.name = "SparseNaiveSGDRule"
                sgd.naive.learning_rate = strategy.get(
636 637
                    prefix + 'sparse_learning_rate', 0.05
                )
638
                sgd.naive.initial_range = strategy.get(
639 640 641 642 643
                    prefix + 'sparse_initial_range', 1e-4
                )
                bounds = strategy.get(
                    prefix + 'sparse_weight_bounds', [-10, 10]
                )
644 645 646 647
                sgd.naive.weight_bounds.extend(bounds)
            elif optimizer_name == "adagrad":
                sgd.name = 'SparseAdaGradSGDRule'
                sgd.adagrad.learning_rate = strategy.get(
648 649
                    prefix + 'sparse_learning_rate', 0.05
                )
650
                sgd.adagrad.initial_range = strategy.get(
651 652
                    prefix + 'sparse_initial_range', 1e-4
                )
653 654 655
                if prefix == "embed_":
                    sgd.adagrad.initial_range = 0
                sgd.adagrad.initial_g2sum = strategy.get(
656 657 658 659 660
                    prefix + 'sparse_initial_g2sum', 3
                )
                bounds = strategy.get(
                    prefix + 'sparse_weight_bounds', [-10, 10]
                )
661 662 663 664
                sgd.adagrad.weight_bounds.extend(bounds)
            elif optimizer_name == "std_adagrad":
                sgd.name = 'StdAdaGradSGDRule'
                sgd.adagrad.learning_rate = strategy.get(
665 666
                    prefix + 'sparse_learning_rate', 0.05
                )
667
                sgd.adagrad.initial_range = strategy.get(
668 669
                    prefix + 'sparse_initial_range', 1e-4
                )
670 671 672
                if prefix == "embed_":
                    sgd.adagrad.initial_range = 0
                sgd.adagrad.initial_g2sum = strategy.get(
673 674 675 676 677
                    prefix + 'sparse_initial_g2sum', 3
                )
                bounds = strategy.get(
                    prefix + 'sparse_weight_bounds', [-10, 10]
                )
678 679 680
                sgd.adagrad.weight_bounds.extend(bounds)
            elif optimizer_name == "adam":
                sgd.name = 'SparseAdamSGDRule'
D
danleifeng 已提交
681
                sgd.adam.learning_rate = strategy.get(
682 683
                    prefix + 'sparse_learning_rate', 0.001
                )
D
danleifeng 已提交
684
                sgd.adam.initial_range = strategy.get(
685 686
                    prefix + 'sparse_initial_range', 1e-4
                )
D
danleifeng 已提交
687
                sgd.adam.beta1_decay_rate = strategy.get(
688 689
                    prefix + 'sparse_beta1_decay_rate', 0.9
                )
D
danleifeng 已提交
690
                sgd.adam.beta2_decay_rate = strategy.get(
691 692
                    prefix + 'sparse_beta2_decay_rate', 0.999
                )
D
danleifeng 已提交
693
                sgd.adam.ada_epsilon = strategy.get(
694 695 696 697 698
                    prefix + 'sparse_ada_epsilon', 1e-8
                )
                bounds = strategy.get(
                    prefix + 'sparse_weight_bounds', [-10, 10]
                )
D
danleifeng 已提交
699 700 701
                sgd.adam.weight_bounds.extend(bounds)
            elif optimizer_name == "shared_adam":
                sgd.name = 'SparseSharedAdamSGDRule'
702
                sgd.adam.learning_rate = strategy.get(
703 704
                    prefix + 'sparse_learning_rate', 0.001
                )
705
                sgd.adam.initial_range = strategy.get(
706 707
                    prefix + 'sparse_initial_range', 1e-4
                )
708
                sgd.adam.beta1_decay_rate = strategy.get(
709 710
                    prefix + 'sparse_beta1_decay_rate', 0.9
                )
711
                sgd.adam.beta2_decay_rate = strategy.get(
712 713
                    prefix + 'sparse_beta2_decay_rate', 0.999
                )
714
                sgd.adam.ada_epsilon = strategy.get(
715 716 717 718 719
                    prefix + 'sparse_ada_epsilon', 1e-8
                )
                bounds = strategy.get(
                    prefix + 'sparse_weight_bounds', [-10, 10]
                )
720 721 722 723 724 725
                sgd.adam.weight_bounds.extend(bounds)

        def set_sparse_table_config(table_data, config):
            for key in config:
                if key not in support_sparse_key_list:
                    raise ValueError("strategy key '%s' not support" % (key))
726 727 728
            table_class = config.get(
                "sparse_table_class", "DownpourSparseTable"
            )
729 730 731
            if table_class not in support_sparse_table_class:
                raise ValueError(
                    "support sparse_table_class: ['DownpourSparseTable'], but actual %s"
732 733
                    % (table_class)
                )
734 735
            table_data.table_class = 'MemorySparseTable'
            table_data.shard_num = config.get('sparse_shard_num', 1000)
736
            table_data.enable_sparse_table_cache = config.get(
737 738
                'sparse_enable_cache', True
            )
739
            table_data.sparse_table_cache_rate = config.get(
740 741
                'sparse_cache_rate', 0.00055
            )
742
            table_data.sparse_table_cache_file_num = config.get(
743 744
                'sparse_cache_file_num', 16
            )
745

746 747 748
            accessor_class = config.get(
                "sparse_accessor_class", "DownpourCtrAccessor"
            )
749 750
            if accessor_class not in support_sparse_accessor_class:
                raise ValueError(
751
                    "support sparse_accessor_class: ['DownpourSparseValueAccessor', 'DownpourCtrAccessor', 'DownpourCtrDoubleAccessor', 'DownpourUnitAccessor', 'DownpourDoubleUnitAccessor'], but actual %s"
752 753
                    % (accessor_class)
                )
754

755 756
            if accessor_class.find("Double") >= 0:
                table_data.accessor.accessor_class = 'CtrDoubleAccessor'
757 758
            elif accessor_class.find("Dymf") >= 0:
                table_data.accessor.accessor_class = 'CtrDymfAccessor'
759
            else:
760 761 762
                table_data.accessor.accessor_class = 'CtrCommonAccessor'

            if not configs.get("use_cvm", True):
763 764 765 766 767
                table_data.accessor.accessor_class = 'SparseAccessor'

            table_data.accessor.embedx_dim = config.get('sparse_embedx_dim', 8)
            table_data.accessor.fea_dim = table_data.accessor.embedx_dim + 3
            table_data.accessor.embedx_threshold = config.get(
768 769
                'sparse_embedx_threshold', 10
            )
770

771 772 773 774 775
            if accessor_class == 'DownpourUnitAccessor':
                table_data.accessor.ctr_accessor_param.show_scale = False
            else:
                table_data.accessor.ctr_accessor_param.show_scale = True

776
            table_data.accessor.ctr_accessor_param.nonclk_coeff = config.get(
777 778
                'sparse_nonclk_coeff', 0.1
            )
779
            table_data.accessor.ctr_accessor_param.click_coeff = config.get(
780 781
                'sparse_click_coeff', 1
            )
782
            table_data.accessor.ctr_accessor_param.base_threshold = config.get(
783 784
                'sparse_base_threshold', 1.5
            )
785
            table_data.accessor.ctr_accessor_param.delta_threshold = config.get(
786 787
                'sparse_delta_threshold', 0.25
            )
788
            table_data.accessor.ctr_accessor_param.delta_keep_days = config.get(
789 790 791 792 793 794 795 796 797 798 799 800 801 802
                'sparse_delta_keep_days', 16
            )
            table_data.accessor.ctr_accessor_param.show_click_decay_rate = (
                config.get('sparse_show_click_decay_rate', 0.98)
            )
            table_data.accessor.ctr_accessor_param.delete_threshold = (
                config.get('sparse_delete_threshold', 0.8)
            )
            table_data.accessor.ctr_accessor_param.delete_after_unseen_days = (
                config.get('sparse_delete_after_unseen_days', 30)
            )
            table_data.accessor.ctr_accessor_param.ssd_unseenday_threshold = (
                config.get('sparse_ssd_unseenday_threshold', 1)
            )
803 804 805 806 807 808 809 810 811 812 813 814 815
            converter = config.get('sparse_converter', "")
            deconverter = config.get('sparse_deconverter', "")

            save_data1 = table_data.accessor.table_accessor_save_param.add()
            save_data1.param = 1
            save_data1.converter = converter
            save_data1.deconverter = deconverter

            save_data2 = table_data.accessor.table_accessor_save_param.add()
            save_data2.param = 2
            save_data2.converter = converter
            save_data2.deconverter = deconverter

816 817 818 819 820 821 822 823 824 825
            if (
                accessor_class == 'DownpourCtrAccessor'
                or accessor_class == 'DownpourCtrDoubleAccessor'
            ):
                sparse_optimizer_config(
                    table_data.accessor.embed_sgd_param, config, ''
                )
                sparse_optimizer_config(
                    table_data.accessor.embedx_sgd_param, config, ''
                )
826
            else:
827 828 829 830 831 832
                sparse_optimizer_config(
                    table_data.accessor.embed_sgd_param, config, 'embed_'
                )
                sparse_optimizer_config(
                    table_data.accessor.embedx_sgd_param, config, 'embedx_'
                )
D
danleifeng 已提交
833
            add_graph_config(table_data.accessor.graph_sgd_param, config)
834 835

        if not configs:
836
            logger.info("fleet desc config is empty")
837 838
        else:
            for table_name in configs:
839 840 841 842
                if (
                    table_name == 'dense_table'
                    or table_name == 'datanorm_table'
                ):
843 844 845 846 847 848 849
                    continue
                if type(configs[table_name]) != dict:
                    continue
                table_data = table_param.add()
                table_data.table_name = table_name
                set_sparse_table_config(table_data, configs[table_name])

850
    @property
851 852 853 854
    def amp(self):
        """
        Indicating whether we are using automatic mixed precision training
        Default Value: False
855

856
        Examples:
1
123malin 已提交
857

858
          .. code-block:: python
859

860
            import paddle.distributed.fleet as fleet
861 862
            strategy = fleet.DistributedStrategy()
            strategy.amp = True # by default this is false
863

864 865
        """
        return self.strategy.amp
866

867
    @amp.setter
868
    @is_strict_auto
869
    def amp(self, flag):
870
        if isinstance(flag, bool):
871
            self.strategy.amp = flag
872
        else:
873
            logger.warning("amp should have value of bool type")
874 875

    @property
876
    def amp_configs(self):
877
        """
878

879 880 881 882
        Set automatic mixed precision training configurations. In general, amp has serveral configurable
        settings that can be configured through a dict.

        **Notes**:
M
mapingshuo 已提交
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
            init_loss_scaling(float): The initial loss scaling factor. Default 32768.

            use_dynamic_loss_scaling(bool): Whether to use dynamic loss scaling. Default True.

            incr_every_n_steps(int): Increases loss scaling every n consecutive steps with finite gradients. Default 1000.

            decr_every_n_nan_or_inf(int): Decreases loss scaling every n accumulated steps with nan or inf gradients. Default 2.

            incr_ratio(float): The multiplier to use when increasing the loss scaling. Default 2.0.

            decr_ratio(float): The less-than-one-multiplier to use when decreasing the loss scaling. Default 0.5.

            custom_white_list(list[str]): Users' custom white list which always execution fp16.

            custom_black_list(list[str]): Users' custom black list which forbidden execution fp16.
898

899 900 901 902 903 904 905 906
            custom_black_varnames(list[str]): Users' custom black varibles' names.

            use_pure_fp16(bool): Whether to use the pure fp16 training. Default False.

            use_fp16_guard(bool): Whether to use `fp16_guard` when constructing the program.
                   Default True. Only takes effect when `use_pure_fp16` is turned on.

        Examples 1:
907
            .. code-block:: python
1
123malin 已提交
908

909 910 911 912 913 914
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.amp = True
                strategy.amp_configs = {
                    "init_loss_scaling": 32768,
                    "custom_white_list": ['conv2d']}
915 916

        Examples 2:
917 918 919 920 921 922 923 924 925 926
            .. code-block:: python

                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.amp = True
                # pure fp16
                strategy.amp_configs = {
                    "init_loss_scaling": 32768,
                    "use_pure_fp16": True
                }
927

928
        """
929
        return get_msg_dict(self.strategy.amp_configs)
930

931
    @amp_configs.setter
932
    @is_strict_auto
933 934 935
    def amp_configs(self, configs):
        check_configs_key(self.strategy.amp_configs, configs, "amp_configs")
        assign_configs_value(self.strategy.amp_configs, configs)
936

937 938 939
    @property
    def asp(self):
        """
940

941 942 943 944
        Indicating whether we are using automatic sparsity training
        Default Value: False

        Examples:
945
            .. code-block:: python
946

947 948 949
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.asp = True # by default this is false
950 951 952 953 954 955 956 957 958 959

        """
        return self.strategy.asp

    @asp.setter
    @is_strict_auto
    def asp(self, flag):
        if isinstance(flag, bool):
            self.strategy.asp = flag
        else:
960
            logger.warning("asp should have value of bool type")
961

962
    @property
963 964 965 966 967 968
    def recompute(self):
        """
        Indicating whether we are using forward recomputation for memory optimization
        Default value: False

        Examples:
969
            .. code-block:: python
1
123malin 已提交
970

971 972 973 974 975
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.recompute = True
                # suppose x and y are names of checkpoint tensors for recomputation
                strategy.recompute_configs = {"checkpoints": ["x", "y"]}
976 977 978

        """
        return self.strategy.recompute
979

980 981
    @property
    def sync_nccl_allreduce(self):
982
        """
983

984 985 986 987
        Indicating whether we are using synchronized all reduce in each communication thread
        We note that system overhead is usually lower when sync_nccl_allreduce = True

        Examples:
988
            .. code-block:: python
1
123malin 已提交
989

990 991 992
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.sync_nccl_allreduce = True
993 994

        """
995 996 997
        return self.strategy.sync_nccl_allreduce

    @sync_nccl_allreduce.setter
998
    @is_strict_auto
999 1000 1001 1002
    def sync_nccl_allreduce(self, flag):
        if isinstance(flag, bool):
            self.strategy.sync_nccl_allreduce = flag
        else:
1003
            logger.warning("sync_nccl_allreduce should have value of bool type")
1004

1005
    @property
1006
    def use_hierarchical_allreduce(self):
1007
        """
1008

1009 1010 1011 1012 1013
        Indicating whether we are using hierarchical allreduce in collective communication
        Hierarchical allreduce often does allreduce within a certain node group and then do
        allreduce among the leaders of each group

        Examples:
1014
            .. code-block:: python
1
123malin 已提交
1015

1016 1017 1018
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.use_hierarchical_allreduce = True
1019 1020

        """
1021
        return self.strategy.use_hierarchical_allreduce
1022

1023
    @use_hierarchical_allreduce.setter
1024
    @is_strict_auto
1025
    def use_hierarchical_allreduce(self, flag):
1026
        if isinstance(flag, bool):
1027
            self.strategy.use_hierarchical_allreduce = flag
1028
        else:
1029 1030
            logger.warning(
                "use_hierarchical_allreduce should have value of bool type"
1031 1032 1033
            )

    @property
1034
    def hierarchical_allreduce_inter_nranks(self):
1035
        """
1036

1037 1038 1039 1040
        Number of ranks for low level node groups in hierarchical allreduce
        Default value: number of GPU cards on each single GPU machine

        Example:
1041
            .. code-block:: python
1
123malin 已提交
1042

1043 1044 1045
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.hierarchical_allreduce_inter_nranks = 8
1046 1047

        """
1048
        return self.strategy.hierarchical_allreduce_inter_nranks
1049

1050
    @hierarchical_allreduce_inter_nranks.setter
1051
    @is_strict_auto
1052 1053 1054
    def hierarchical_allreduce_inter_nranks(self, value):
        if isinstance(value, int):
            self.strategy.hierarchical_allreduce_inter_nranks = value
1055
        else:
1056 1057
            logger.warning(
                "hierarchical_allreduce_inter_nranks should have value of int type"
1058 1059
            )

1060
    @property
1061
    def sync_batch_norm(self):
1062
        """
1063

1064
        Indicating whether we are using sync_batch_norm to do synchronous batch normalization among all training nodes.
1
123malin 已提交
1065

1066 1067 1068
        Default value: False

        Examples:
1069
            .. code-block:: python
1
123malin 已提交
1070

1071 1072 1073
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.sync_batch_norm = True
1074 1075 1076

        """

1077
        return self.strategy.sync_batch_norm
1078

1079
    @sync_batch_norm.setter
1080
    @is_strict_auto
1081
    def sync_batch_norm(self, flag):
1082
        if isinstance(flag, bool):
1083
            self.strategy.sync_batch_norm = flag
1084
        else:
1085
            logger.warning("sync_batch_norm should have value of bool type")
1086 1087 1088

    @property
    def fuse_all_reduce_ops(self):
1089
        """
1090

1091 1092 1093 1094
        Indicating whether we are using fuse_all_reduce_ops for gradient fusion during backward phase of training
        Default value: True

        Examples:
1095
            .. code-block:: python
1
123malin 已提交
1096

1097 1098 1099
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.fuse_all_reduce_ops = False
1100 1101

        """
1102 1103 1104
        return self.strategy.fuse_all_reduce_ops

    @fuse_all_reduce_ops.setter
1105
    @is_strict_auto
1106 1107 1108 1109
    def fuse_all_reduce_ops(self, flag):
        if isinstance(flag, bool):
            self.strategy.fuse_all_reduce_ops = flag
        else:
1110
            logger.warning("fuse_all_reduce_ops should have value of bool type")
1111

1112 1113
    @property
    def fuse_grad_size_in_MB(self):
1114
        """
1115

1116 1117 1118 1119 1120
        Specifying the size of gradient to fuse in Mega-Bytes

        Default value: 32

        Examples:
1121
            .. code-block:: python
1
123malin 已提交
1122

1123 1124 1125
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.fuse_grad_size_in_MB = 50
1
123malin 已提交
1126

1127
        """
1128 1129 1130
        return self.strategy.fuse_grad_size_in_MB

    @fuse_grad_size_in_MB.setter
1131
    @is_strict_auto
1132 1133 1134 1135
    def fuse_grad_size_in_MB(self, value):
        if isinstance(value, int):
            self.strategy.fuse_grad_size_in_MB = value
        else:
1136
            logger.warning("fuse_grad_size_in_MB should have value of int type")
1137

1138 1139 1140
    @property
    def last_comm_group_size_MB(self):
        """
1141

1142 1143 1144
        Specifying the size of gradient to fuse in Mega-Bytes when
        the last group of each batch communicates. Making the last group
        small is useful to improve performance.
1145 1146 1147 1148

        Default value: 1

        Examples:
1149 1150 1151 1152 1153
            .. code-block:: python

                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.last_comm_group_size_MB = 2
1154

1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
        """
        return self.strategy.last_comm_group_size_MB

    @last_comm_group_size_MB.setter
    @is_strict_auto
    def last_comm_group_size_MB(self, value):
        if value > 0:
            self.strategy.last_comm_group_size_MB = value
        else:
            raise ValueError("last_comm_group_size_MB should be greater than 0")

1166 1167 1168
    @property
    def find_unused_parameters(self):
        """
1169

1170
        Indicating whether we are using find_unused_parameters to
1171 1172
        find unused parameters in DataParallel.

1173
        Default value: False
1174 1175

        Examples:
1176
            .. code-block:: python
1177

1178 1179 1180
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.find_unused_parameters = True
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191

        """

        return self.strategy.find_unused_parameters

    @find_unused_parameters.setter
    @is_strict_auto
    def find_unused_parameters(self, flag):
        if isinstance(flag, bool):
            self.strategy.find_unused_parameters = flag
        else:
1192 1193
            logger.warning(
                "find_unused_parameters should have value of bool type"
1194
            )
1195

1196 1197 1198 1199 1200
    @property
    def _fuse_grad_size_in_TFLOPS(self):
        return self.strategy.fuse_grad_size_in_TFLOPS

    @_fuse_grad_size_in_TFLOPS.setter
1201
    @is_strict_auto
1202 1203 1204 1205
    def _fuse_grad_size_in_TFLOPS(self, value):
        if isinstance(value, float):
            self.strategy.fuse_grad_size_in_TFLOPS = value
        else:
1206 1207
            logger.warning(
                "fuse_grad_size_in_TFLOPS should have value of float type"
1208 1209
            )

1210
    @property
1211
    def nccl_comm_num(self):
1212
        """
1213

1214 1215 1216 1217 1218
        Specifying the number of NCCL communicator

        Default value: 1

        Examples:
1219
            .. code-block:: python
1
123malin 已提交
1220

1221 1222 1223
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.nccl_comm_num = 2
1
123malin 已提交
1224

1225 1226
        """

1227
        return self.strategy.nccl_comm_num
1228

1229
    @nccl_comm_num.setter
1230
    @is_strict_auto
1231
    def nccl_comm_num(self, value):
1232
        if isinstance(value, int):
1233
            self.strategy.nccl_comm_num = value
1234
        else:
1235
            logger.warning("nccl_comm_num should have value of int type")
1236

1237
    @recompute.setter
1238
    @is_strict_auto
1239
    def recompute(self, flag):
1240
        if isinstance(flag, bool):
1241
            self.strategy.recompute = flag
1242
        else:
1243
            logger.warning("recompute should have value of bool type")
1244 1245

    @property
1246 1247
    def recompute_configs(self):
        """
1248

1249 1250
        Set recompute configurations.

J
JZ-LIANG 已提交
1251 1252 1253 1254
        **Note**:
        checkpoints(list): list of string name of checkpoints. In general, the recompute
        strategy of current implementation should have some manually assign checkpoints.

1255
        enable_offload(bool): enable recompute checkpoints offload feature. this feature
J
JZ-LIANG 已提交
1256 1257 1258 1259 1260 1261
        will offload the checkpoint to host memory to allow even larger batch size. since
        the memcpy from host to device takes time, it is a trade off between larger batch
        size and training speed.

        checkpoint_shape(list): list of int that specific the shape of checkpoint. so far
        recompute-offload requires that all checkpoint to be same shape, and every dimension
1262
        specific here should be determined ("-1" is not allowed).
1263

1264
        Examples:
1265
            .. code-block:: python
1
123malin 已提交
1266

1267 1268 1269 1270 1271 1272 1273
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.recompute = True
                strategy.recompute_configs = {
                    "checkpoints": ["x", "y"],
                    "enable_offload": True,
                    "checkpoint_shape": [100, 512, 1024] }
1274 1275 1276 1277 1278

        """
        return get_msg_dict(self.strategy.recompute_configs)

    @recompute_configs.setter
1279
    @is_strict_auto
1280
    def recompute_configs(self, configs):
1281 1282 1283
        check_configs_key(
            self.strategy.recompute_configs, configs, "checkpoint_configs"
        )
1284
        assign_configs_value(self.strategy.recompute_configs, configs)
1285

1286 1287 1288
    @property
    def sharding(self):
        """
1289

1290
        Indicating whether we are using sharding Optimizer for memory
1291
        optimization. We implement the sharding optimizer following the ZeRO-DP
J
JZ-LIANG 已提交
1292 1293
        idea from [ZeRO: Memory Optimizations Toward Training Trillion Parameter Models](https://arxiv.org/abs/1910.02054).
        Model parameters and Optimizer State are sharded into different ranks allowing to fit larger model.
1294

1295 1296
        In Hybrid parallelism scenario, we use sharding config as uniform API to set each parallelism.

1297 1298 1299
        Default value: False

        Examples:
1300
            .. code-block:: python
1
123malin 已提交
1301

1302 1303 1304
                import paddle.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.sharding = True
1
123malin 已提交
1305

1306 1307 1308 1309 1310 1311 1312 1313 1314
        """
        return self.strategy.sharding

    @sharding.setter
    @is_strict_auto
    def sharding(self, flag):
        if isinstance(flag, bool):
            self.strategy.sharding = flag
        else:
1315
            logger.warning("sharding should have value of bool type")
1316 1317 1318 1319

    @property
    def sharding_configs(self):
        """
1320

1321
        Set sharding configurations.
1322 1323

        **Note**:
1324 1325
            sharding_segment_strategy(string, optional): strategy used to segment the program(forward & backward operations). two strategise are
            available: "segment_broadcast_MB" and "segment_anchors". segment is a concept used in sharding to overlap computation and
1326 1327
            communication. Default is segment_broadcast_MB.

1328
            segment_broadcast_MB(float, optional): segment by the parameters broadcast volume. sharding will introduce parameter broadcast operations into program, and
1329 1330 1331 1332
            after every segment_broadcast_MB size parameter being broadcasted, the program will be cutted into one segment.
            This configuration will affect the communication speed in sharding training, and should be an empirical value decided by your model size and network topology.
            Only enable when sharding_segment_strategy = segment_broadcast_MB. Default is 32.0 .

1333
            segment_anchors(list): list of anchors used to segment the program, which allows a finner control of program segmentation.
1334 1335 1336 1337 1338 1339
            this strategy is experimental by now. Only enable when sharding_segment_strategy = segment_anchors.

            sharding_degree(int, optional): specific the number of gpus within each sharding parallelism group; and sharding will be turn off if sharding_degree=1.  Default is 8.

            gradient_merge_acc_step(int, optional): specific the accumulation steps in gradient merge; and gradient merge will be turn off if gradient_merge_acc_step=1.  Default is 1.

1340
            optimize_offload(bool, optional): enable the optimizer offload which will offload the moment vars to Host memory in order to saving GPU memory for fitting larger model.
1341 1342 1343 1344 1345
            the moment var will be prefetch from and offloaded to Host memory during update stage. it is a stragtegy that trades off between training speed and GPU memory, and is recommened to be turn on only when gradient_merge_acc_step large, where
            the number of time of update stage will be relatively small compared with forward&backward's.  Default is False.

            dp_degree(int, optional): specific the number of data parallelism group; when dp_degree >= 2, it will introduce dp_degree ways data parallelism as the outer parallelsim for the inner parallelsim. User is responsible to ensure global_world_size = mp_degree * sharding_degree * pp_degree * dp_degree. Default is 1.

1346
            mp_degree(int, optional): [Hybrid parallelism ONLY] specific the number of gpus within each megatron parallelism group; and megatron parallelism will turn be off if mp_degree=1.  Default is 1.
1347

1348
            pp_degree(int, optional): [Hybrid parallelism ONLY] specific the number of gpus within each pipeline parallelism group; and pipeline parallelism will turn be off if pp_degree=1.  Default is 1.
1349

1350
            pp_allreduce_in_optimize(bool, optional): [Hybrid parallelism ONLY] move the allreduce operations from backward stage to update(optimize) stage when pipeline parallelsim is on.
1351
            This configuration will affect the communication speed of Hybrid parallelism training depeneded on network topology. this strategy is experimental by now..  Default is False.
J
JZ-LIANG 已提交
1352

1353 1354 1355
            optimize_cast(bool, optional): [Hybrid parallelism ONLY] Move the cast op of AMP which cast fp32 param to fp16 param to optimizer. optimize_cast will persist fp16 param, it
            will take more memory, but will be faster, trade space for time. Recommend to turn on only when using pipeline or gradient_merge_acc_step large.

J
JZ-LIANG 已提交
1356

1357
        Examples:
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
            .. code-block:: python

                # sharding-DP, 2 nodes with 8 gpus per node
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.sharding = True
                strategy.sharding_configs = {
                    "sharding_segment_strategy": "segment_broadcast_MB",
                    "segment_broadcast_MB": 32,
                    "sharding_degree": 8,
                    "dp_degree": 2,
                    "gradient_merge_acc_step": 4,
                    }
1
123malin 已提交
1371

1372 1373 1374 1375 1376 1377
        """
        return get_msg_dict(self.strategy.sharding_configs)

    @sharding_configs.setter
    @is_strict_auto
    def sharding_configs(self, configs):
1378 1379 1380
        check_configs_key(
            self.strategy.sharding_configs, configs, "sharding_configs"
        )
1381 1382
        assign_configs_value(self.strategy.sharding_configs, configs)

1383 1384 1385
    @property
    def without_graph_optimization(self):
        """
1386

1387 1388 1389
        Run program using Executor other than ParallelExecutor.

        Examples:
1390
            .. code-block:: python
1391

1392 1393 1394
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.without_graph_optimization = True
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404

        """
        return self.strategy.without_graph_optimization

    @without_graph_optimization.setter
    @is_strict_auto
    def without_graph_optimization(self, flag):
        if isinstance(flag, bool):
            self.strategy.without_graph_optimization = flag
        else:
1405 1406
            logger.warning(
                "without_graph_optimization should have value of bool type"
1407 1408
            )

1409 1410 1411
    @property
    def _calc_comm_same_stream(self):
        """
1412

1413 1414 1415
        This based on raw_program_optimizer program
        Set whether use same stream for calc and comm when fuse allreduce
        The default value for the calc_comm_same_stream is False
1416

1417
        Examples:
1418 1419 1420 1421 1422 1423
            .. code-block:: python

                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.calc_comm_same_stream = True

1424 1425 1426 1427 1428 1429 1430 1431 1432
        """
        return self.strategy.calc_comm_same_stream

    @_calc_comm_same_stream.setter
    @is_strict_auto
    def _calc_comm_same_stream(self, same):
        if isinstance(same, bool):
            self.strategy.calc_comm_same_stream = same
        else:
1433 1434
            logger.warning(
                "calc_comm_same_stream should have value of boolean type"
1435 1436
            )

1437 1438 1439
    @property
    def fuse_grad_merge(self):
        """
1440

1441 1442 1443
        Set whether fuse the grad for gradient merge.
        Note: this flag will only effect the gradient merge under pipeline mode
        The default value for the fuse_grad_merge is False
1444

1445
        Examples:
1446 1447 1448 1449 1450 1451
            .. code-block:: python

                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.fuse_param_grad = True

1452 1453 1454 1455 1456 1457 1458 1459 1460
        """
        return self.strategy.fuse_grad_merge

    @fuse_grad_merge.setter
    @is_strict_auto
    def fuse_grad_merge(self, fuse_grad_merge):
        if isinstance(fuse_grad_merge, bool):
            self.strategy.fuse_grad_merge = fuse_grad_merge
        else:
1461
            logger.warning("fuse_grad_merge should have value of boolean type")
1462

1463 1464 1465
    @property
    def fuse_grad_size_in_num(self):
        """
1466

1467
        This based on raw_program_optimizer program and allreduce the num of the fused op
1468

1469
        Examples:
1470 1471 1472 1473 1474 1475 1476
            .. code-block:: python

                import paddle.distributed.fleet as fleet

                strategy = fleet.DistributedStrategy()
                strategy.fuse_grad_size_in_num = 2

1477 1478 1479 1480 1481 1482 1483 1484 1485
        """
        return self.strategy.fuse_grad_size_in_num

    @fuse_grad_size_in_num.setter
    @is_strict_auto
    def fuse_grad_size_in_num(self, num):
        if isinstance(num, int):
            self.strategy.fuse_grad_size_in_num = num
        else:
1486 1487
            logger.warning(
                "fuse_grad_size_in_num should have value of int32 type"
1488
            )
1489

1490
    @property
1491 1492
    def pipeline(self):
        """
1493

1494 1495 1496 1497 1498 1499
        Indicating whether we are using pipeline parallelism for distributed training.
        Current implementation mainly focus on single GPU machine pipeline parallelism and
        data parallelism across GPU machine. The pipeline information is indicated through
        device_guard information in user-defined program.

        Examples:
1500
            .. code-block:: python
1
123malin 已提交
1501

1502 1503 1504
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.pipeline = True
1505 1506 1507

        """
        return self.strategy.pipeline
1508

1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
    @property
    def is_fl_ps_mode(self):
        return self.strategy.is_fl_ps_mode

    @is_fl_ps_mode.setter
    @is_strict_auto
    def is_fl_ps_mode(self, flag):
        if isinstance(flag, bool):
            self.strategy.is_fl_ps_mode = flag
        else:
1519
            logger.warning("is_fl_ps_mode should have value of bool type")
1520

1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
    @property
    def is_with_coordinator(self):
        return self.strategy.with_coordinator

    @is_with_coordinator.setter
    @is_strict_auto
    def is_with_coordinator(self, flag):
        if isinstance(flag, bool):
            self.strategy.with_coordinator = flag
        else:
1531
            logger.warning("with_coordinator should have value of bool type")
1532

1533
    @pipeline.setter
1534
    @is_strict_auto
1535
    def pipeline(self, flag):
1536
        if isinstance(flag, bool):
1537
            self.strategy.pipeline = flag
1538
        else:
1539
            logger.warning("pipeline should have value of bool type")
1540 1541

    @property
1542 1543
    def pipeline_configs(self):
        """
1544

1545 1546
        Set pipeline parallelism configurations. In pipeline parallelism,
        different parts of neural networks are running on different GPUS.
1547
        There are Tensor queue buffer between each pair of neighborhood GPUS
1548 1549 1550
        that are responsible for synchronizing hidden Tensor results between
        GPUs. Pipeline parallelism consists of serveral producer-consumer style
        hardware pairs, such as GPU-GPU, CPU-GPU, GPU-XPU. The best way to speedup
1551
        pipeline parallelism is to make the size of Tensor in Tensor queue smaller,
1552
        so that we will have a faster producer for downstream consumers.
1553

1554 1555
        **Notes**:
            **Detailed arguments for pipeline_configs**
M
mapingshuo 已提交
1556

1557
            **micro_batch_size**: the number of small batches in each user defined batch
1558

1559
        Examples:
1560
            .. code-block:: python
1
123malin 已提交
1561

1562 1563 1564 1565
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.pipeline = True
                strategy.pipeline_configs = {"micro_batch_size": 12}
1566

1567
        """
1568

1569
        return get_msg_dict(self.strategy.pipeline_configs)
1570

1571
    @pipeline_configs.setter
1572
    @is_strict_auto
1573
    def pipeline_configs(self, configs):
1574 1575 1576
        check_configs_key(
            self.strategy.pipeline_configs, configs, "pipeline_configs"
        )
1577
        assign_configs_value(self.strategy.pipeline_configs, configs)
1578

L
lilong12 已提交
1579 1580 1581
    @property
    def tensor_parallel(self):
        """
1582

L
lilong12 已提交
1583 1584 1585
        Indicating whether we are using tensor parallel for distributed training.

        Examples:
1586
            .. code-block:: python
L
lilong12 已提交
1587

1588 1589 1590
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.tensor_parallel = True
L
lilong12 已提交
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600

        """
        return self.strategy.tensor_parallel

    @tensor_parallel.setter
    @is_strict_auto
    def tensor_parallel(self, flag):
        if isinstance(flag, bool):
            self.strategy.tensor_parallel = flag
        else:
1601
            logger.warning("tensor_parallel should have value of bool type")
L
lilong12 已提交
1602 1603 1604 1605

    @property
    def tensor_parallel_configs(self):
        """
1606

L
lilong12 已提交
1607 1608 1609 1610
        Set tensor_parallel configurations.

        **Notes**:
            **Detailed arguments for tensor_parallel_configs**
1611

L
lilong12 已提交
1612
            **tensor_parallel_degree**: degree of tensor parallel
1613

1614 1615
            **tensor_init_seed**: parameter initialization random seed

L
lilong12 已提交
1616 1617

        Examples:
1618
            .. code-block:: python
L
lilong12 已提交
1619

1620 1621 1622 1623 1624
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.tensor_parallel = True
                strategy.tensor_parallel_configs = {"tensor_parallel_degree": 4,
                                                    "tensor_init_seed": 123}
L
lilong12 已提交
1625 1626 1627 1628 1629 1630 1631

        """
        return get_msg_dict(self.strategy.tensor_parallel_configs)

    @tensor_parallel_configs.setter
    @is_strict_auto
    def tensor_parallel_configs(self, configs):
1632 1633 1634 1635 1636
        check_configs_key(
            self.strategy.tensor_parallel_configs,
            configs,
            "tensor_parallel_configs",
        )
L
lilong12 已提交
1637 1638
        assign_configs_value(self.strategy.tensor_parallel_configs, configs)

1639 1640 1641
    @property
    def hybrid_configs(self):
        """
1642

1643
        Dynamic graph hybrid parallel strategy configuration. Three-way hybrid parallelism
1644 1645 1646 1647 1648
        needs to meet the following relationships

        total_number_GPUs = dp_degree * mp_degree * pp_degree

        **Note**:
1649
            **dp_degree(int)**: set number of GPUs in a data parallel group. Default -1.
1650
                                    This value should be an integer greater than 0.
1651
                                    If it is not set, or set to -1, its value will be inferred
1652 1653
                                    based on the total number of cards.

1654 1655 1656
            **mp_degree(int)**: set number of GPUs in a model parallel group. Default 1

            **pp_degree(int)**: set number of GPUs in a pipeline parallel group. Default 1
1657 1658

        Examples:
1659 1660 1661 1662 1663 1664 1665 1666 1667
            .. code-block:: python

                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.hybrid_configs = {
                    "dp_degree": 1,
                    "mp_degree": 2,
                    "pp_degree": 1}

1668 1669 1670 1671 1672
        """
        return get_msg_dict(self.strategy.hybrid_configs)

    @hybrid_configs.setter
    def hybrid_configs(self, configs):
1673 1674 1675
        check_configs_key(
            self.strategy.hybrid_configs, configs, "hybrid_configs"
        )
1676 1677
        assign_configs_value(self.strategy.hybrid_configs, configs)

1678
    @property
1679
    def localsgd(self):
1680
        """
1681

M
mapingshuo 已提交
1682 1683 1684
        Indicating whether we are using Local SGD training. Default Value: False
        For more details, please refer to
        `Don't Use Large Mini-Batches, Use Local SGD <https://arxiv.org/pdf/1808.07217.pdf>`_.
1685 1686 1687


        Examples:
1688
            .. code-block:: python
1
123malin 已提交
1689

1690 1691 1692
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.localsgd = True # by default this is false
1693 1694

        """
1695
        return self.strategy.localsgd
1696

1697
    @localsgd.setter
1698
    @is_strict_auto
1699 1700 1701
    def localsgd(self, flag):
        if isinstance(flag, bool):
            self.strategy.localsgd = flag
1702
        else:
1703
            logger.warning("localsgd should have value of bool type")
1704 1705

    @property
1706
    def localsgd_configs(self):
1707
        """
1708

1709 1710 1711 1712
        Set LocalSGD training configurations. LocalSGD has a configurable
        setting that can be configured through a dict.

        **Notes**:
M
mapingshuo 已提交
1713
            k_steps(int) The local steps for training before parameter synchronization. Default 1.
1714
            begin_step(int) The step of beginning training by localsgd. Default 1.
1715 1716

        Examples:
1717
            .. code-block:: python
1
123malin 已提交
1718

1719 1720 1721 1722 1723
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.localsgd = True
                strategy.localsgd_configs = {"k_steps": 4,
                                            "begin_step": 30}
1724 1725 1726

        """

1727
        return get_msg_dict(self.strategy.localsgd_configs)
1728

1729
    @localsgd_configs.setter
1730
    @is_strict_auto
1731
    def localsgd_configs(self, configs):
1732 1733 1734
        check_configs_key(
            self.strategy.localsgd_configs, configs, "localsgd_configs"
        )
1735
        assign_configs_value(self.strategy.localsgd_configs, configs)
1736

1737 1738 1739
    @property
    def adaptive_localsgd(self):
        """
1740

1741
        Indicating whether we are using Adaptive Local SGD training. Default Value: False
1742
        For more details, please refer to `Adaptive Communication Strategies to Achieve
1743 1744 1745
        the Best Error-Runtime Trade-off in Local-Update SGD <https://arxiv.org/pdf/1810.08313.pdf>`_.

        Examples:
1746
            .. code-block:: python
1
123malin 已提交
1747

1748 1749 1750
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.adaptive_localsgd = True # by default this is false
1751 1752

        """
1753
        return self.strategy.adaptive_localsgd
1754 1755 1756 1757 1758

    @adaptive_localsgd.setter
    @is_strict_auto
    def adaptive_localsgd(self, flag):
        if isinstance(flag, bool):
1759
            self.strategy.adaptive_localsgd = flag
1760
        else:
1761
            logger.warning("adaptive_localsgd should have value of bool type")
1762 1763 1764 1765

    @property
    def adaptive_localsgd_configs(self):
        """
1766

1767 1768 1769 1770 1771 1772 1773
        Set AdaptiveLocalSGD training configurations. AdaptiveLocalSGD has a configurable
        setting that can be configured through a dict.

        **Notes**:
            init_k_steps(int) The initial steps for training before adaptive localsgd.
                              Then, the adaptive localsgd method will modify init_k_steps automatically.
                              Default 1.
1774

1775
            begin_step(int) The step of beginning training by adaptive localsgd. Default 1.
1776 1777

        Examples:
1778
            .. code-block:: python
1
123malin 已提交
1779

1780 1781 1782 1783 1784
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.adaptive_localsgd = True
                strategy.adaptive_localsgd_configs = {"init_k_steps": 1,
                                                    "begin_step": 30}
1785 1786 1787 1788 1789 1790 1791 1792

        """

        return get_msg_dict(self.strategy.adaptive_localsgd_configs)

    @adaptive_localsgd_configs.setter
    @is_strict_auto
    def adaptive_localsgd_configs(self, configs):
1793 1794 1795 1796 1797
        check_configs_key(
            self.strategy.adaptive_localsgd_configs,
            configs,
            "adaptive_localsgd_configs",
        )
1798 1799
        assign_configs_value(self.strategy.adaptive_localsgd_configs, configs)

1800
    @property
1801
    def dgc(self):
1802
        """
1803

1804 1805 1806 1807 1808 1809
        Indicating whether we are using Deep Gradient Compression training. For more details, please refer to
        [Deep Gradient Compression](https://arxiv.org/abs/1712.01887).

        Default Value: False

        Examples:
1810
            .. code-block:: python
1
123malin 已提交
1811

1812 1813 1814
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.dgc = True # by default this is false
1815 1816

        """
1817
        return self.strategy.dgc
1818

1819
    @dgc.setter
1820
    @is_strict_auto
1821 1822 1823
    def dgc(self, flag):
        if isinstance(flag, bool):
            self.strategy.dgc = flag
1824
        else:
1825
            logger.warning("dgc should have value of bool type")
1826 1827

    @property
1828
    def dgc_configs(self):
1829
        r"""
1830

1831 1832 1833 1834
        Set Deep Gradient Compression training configurations. In general, dgc has serveral configurable
        settings that can be configured through a dict.

        **Notes**:
M
mapingshuo 已提交
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
            rampup_begin_step(int): The beginning step from which gradient compression is implemented. Default 0.

            rampup_step(int): Time steps used in sparsity warm-up periods. Default is 1. \
                    For example, if the sparsity is [0.75, 0.9375, 0.984375, 0.996, 0.999], and the rampup_step is 100, \
                    it will use 0.75 at 0~19 steps, and 0.9375 at 20~39 steps, and so on. And when reach sparsity array \
                    ends, it will use 0.999 then and after.

            sparsity(list[float]): Get top important element from gradient tensor, the ratio is (1 - sparsity). \
                    Default is [0.999]. For example, if the sparsity is [0.99, 0.999], the top [1%, 0.1%] important \
                    element will be transmitted.
1845 1846

        Examples:
1847
            .. code-block:: python
1
123malin 已提交
1848

1849 1850 1851 1852
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.dgc = True
                strategy.dgc_configs = {"rampup_begin_step": 1252}
1853 1854

        """
1855
        return get_msg_dict(self.strategy.dgc_configs)
1856

1857
    @dgc_configs.setter
1858
    @is_strict_auto
1859 1860 1861
    def dgc_configs(self, configs):
        check_configs_key(self.strategy.dgc_configs, configs, "dgc_configs")
        assign_configs_value(self.strategy.dgc_configs, configs)
1862

1863 1864 1865
    @property
    def fp16_allreduce(self):
        """
1866

1867 1868 1869 1870
        Indicating whether we are using fp16 gradient allreduce training
        Default Value: False

        Examples:
1871
            .. code-block:: python
1
123malin 已提交
1872

1873
                import paddle.distributed.fleet as fleet
1874

1875 1876
                strategy = fleet.DistributedStrategy()
                strategy.fp16_allreduce = True # by default this is false
1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887

        """
        return self.strategy.fp16_allreduce

    @fp16_allreduce.setter
    @is_strict_auto
    def fp16_allreduce(self, flag):
        if not isinstance(flag, bool):
            raise TypeError('fp16_allreduce must be value of bool type')
        self.strategy.fp16_allreduce = flag

1888
    @property
1889
    def gradient_merge(self):
1890
        """
1891

1892 1893 1894 1895 1896 1897 1898 1899 1900 1901
        Gradient Merge, also called as Gradient Accumulation,
        is a strategy for large batch training. With this strategy,
        model parameter will not be updated until user-defined steps.
        For each step, the forward network and the backward network
        will run to calculate the gradient of model parameters.
        For every k step, the optimization network will run,
        applying a specific optimization method (such as SGD, Adam)
        to model parameters.

        Examples:
1902
            .. code-block:: python
1
123malin 已提交
1903

1904 1905 1906 1907
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.gradient_merge = True
                strategy.gradient_merge_configs = {"k_steps": 4, "avg": True}
M
mapingshuo 已提交
1908

1909
        """
1910
        return self.strategy.gradient_merge
1911

1912
    @gradient_merge.setter
1913
    @is_strict_auto
1914
    def gradient_merge(self, flag):
1915
        if isinstance(flag, bool):
1916
            self.strategy.gradient_merge = flag
1917
        else:
1918
            logger.warning("gradient_merge should have value of bool type")
1919 1920 1921

    @property
    def gradient_merge_configs(self):
1922
        """
1923

1924
        the key-value configs of distribute_strategy
M
mapingshuo 已提交
1925 1926 1927 1928 1929 1930 1931

        **Note**:
            k_steps(int): the update period of the parameters.

            avg(bool): whether to average the gradients of each mini-batch, the default value is `True`

        Examples:
1932
            .. code-block:: python
1
123malin 已提交
1933

1934 1935 1936 1937
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.gradient_merge = True
                strategy.gradient_merge_configs = {"k_steps": 4, "avg": True}
M
mapingshuo 已提交
1938

1939
        """
1940 1941 1942
        return get_msg_dict(self.strategy.gradient_merge_configs)

    @gradient_merge_configs.setter
1943
    @is_strict_auto
1944
    def gradient_merge_configs(self, configs):
1945 1946 1947
        check_configs_key(
            self.strategy.gradient_merge_configs, configs, "gradient_configs"
        )
1948
        assign_configs_value(self.strategy.gradient_merge_configs, configs)
1949 1950

    @property
1951
    def lars(self):
1952
        """
1953

1954 1955
        Set lars configurations. lars is used to deal with the convergence problems when the global
        batch size is larger than 8k.  For more details, please refer to
1956 1957 1958 1959 1960
        [Large Batch Training of Convolutional Networks](https://arxiv.org/abs/1708.03888).

        Default Value: False

        Examples:
1961
            .. code-block:: python
1
123malin 已提交
1962

1963 1964 1965
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.lars = True # by default this is false
1966 1967

        """
1968
        return self.strategy.lars
1969

1970
    @lars.setter
1971
    @is_strict_auto
1972
    def lars(self, flag):
1973
        if isinstance(flag, bool):
1974
            self.strategy.lars = flag
1975
        else:
1976
            logger.warning("lars should have value of bool type")
1977

1978 1979
    @property
    def lars_configs(self):
1980
        """
1981

1982 1983 1984 1985 1986
        Set Lars training configurations.

        **Notes**:
        **lars_coeff (float)**: trust ratio in lars formula.
        **lars_weight_decay** (float): weight decay coefficient in lars formula.
1987 1988
        **epsilon (float)**: argument is used to avoid potential devision-by-zero
        when compute the local lr;
1989 1990 1991 1992
        **exclude_from_weight_decay ([string])**: is a list of name strings of layers which
        will be exclude from weight decay in lars formula.

        Examples:
1993
            .. code-block:: python
1
123malin 已提交
1994

1995 1996 1997 1998 1999 2000 2001 2002 2003
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.lars = True
                strategy.lars_configs = {
                            "lars_coeff": 0.01,
                            "lars_weight_decay": 0.0005,
                            "epsilon": 0,
                            "exclude_from_weight_decay": ['batch_norm', '.b_0']
                        }
M
mapingshuo 已提交
2004

2005
        """
2006 2007 2008
        return get_msg_dict(self.strategy.lars_configs)

    @lars_configs.setter
2009
    @is_strict_auto
2010 2011 2012 2013
    def lars_configs(self, configs):
        check_configs_key(self.strategy.lars_configs, configs, "lars_configs")
        assign_configs_value(self.strategy.lars_configs, configs)

2014
    @property
2015
    def lamb(self):
2016
        """
2017

2018 2019 2020
        Set lamb configurations. lamb is used to deal with the convergence problems for large
        batch size training, specially for attention-related model like BERT. For more details,
        please refer to
2021 2022 2023
        [Large Batch Optimization for Deep Learning: Training BERT in 76 minutes](https://arxiv.org/abs/1904.00962).

        Default Value: False
1
123malin 已提交
2024

2025
        Examples:
2026
            .. code-block:: python
1
123malin 已提交
2027

2028 2029 2030
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.lamb = True # by default this is false
2031 2032 2033

        """

2034
        return self.strategy.lamb
2035

2036
    @lamb.setter
2037
    @is_strict_auto
2038
    def lamb(self, flag):
2039
        if isinstance(flag, bool):
2040
            self.strategy.lamb = flag
2041
        else:
2042
            logger.warning("lamb should have value of bool type")
2043

2044 2045
    @property
    def lamb_configs(self):
2046
        """
2047

2048 2049 2050 2051 2052 2053 2054 2055
        Set Lars training configurations.

        **Notes**:
        **lamb_weight_decay** (float): weight decay coefficient in lamb formula.
        **exclude_from_weight_decay ([string])**: is a list of name strings of layers which
        will be exclude from weight decay in lamb formula.

        Examples:
2056 2057 2058 2059 2060 2061 2062 2063 2064
            .. code-block:: python

                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.lamb = True
                strategy.lamb_configs = {
                        'lamb_weight_decay': 0.01,
                        'exclude_from_weight_decay': [],
                    }
1
123malin 已提交
2065

2066
        """
2067 2068 2069
        return get_msg_dict(self.strategy.lamb_configs)

    @lamb_configs.setter
2070
    @is_strict_auto
2071 2072 2073 2074
    def lamb_configs(self, configs):
        check_configs_key(self.strategy.lamb_configs, configs, "lamb_configs")
        assign_configs_value(self.strategy.lamb_configs, configs)

2075 2076
    @property
    def elastic(self):
2077
        """
2078

2079 2080
        Indicating whether we want to do current distributed training on clusters with elastic resources.
        Currently, this is configuration is not valid.
2081

2082
        """
2083 2084 2085
        return self.strategy.elastic

    @elastic.setter
2086
    @is_strict_auto
2087 2088 2089 2090
    def elastic(self, flag):
        if isinstance(flag, bool):
            self.strategy.elastic = flag
        else:
2091
            logger.warning("elastic should have value of bool type")
2092 2093 2094

    @property
    def auto(self):
2095
        """
2096

2097
        Indicating whether we are using auto-parallel configuration
2098
        This feature is currently an experimental feature. Currently,
2099 2100 2101 2102 2103 2104
        auto-parallelism can be used only when a user does not set any other
        strategy configs except auto. For details, please reference the following
        code example
        Default Value: False

        Examples:
2105
            .. code-block:: python
1
123malin 已提交
2106

2107 2108 2109
                import paddle
                paddle.enable_static()
                import paddle.distributed.fleet as fleet
2110

2111 2112 2113 2114
                strategy = fleet.DistributedStrategy()
                strategy.auto = True
                # if set other strategy at the same time, auto will not apply
                # strategy.amp = True
2115

2116 2117
                optimizer = paddle.optimizer.SGD(learning_rate=0.01)
                optimizer = fleet.distributed_optimizer(optimizer, strategy)
2118 2119

        """
2120 2121 2122 2123 2124 2125 2126
        return self.strategy.auto

    @auto.setter
    def auto(self, flag):
        if isinstance(flag, bool):
            self.strategy.auto = flag
        else:
2127
            logger.warning("auto should have value of bool type")
2128

2129 2130 2131
    @property
    def semi_auto(self):
        """
2132

2133
        Indicating whether we are using semi-auto parallel function
2134
        This feature is currently an experimental feature. Currently,
2135 2136 2137 2138 2139 2140
        auto-parallelism can be used only when a user does not set any other
        strategy configs except semi-auto. For details, please reference the following
        code example
        Default Value: False

        Examples:
2141
            .. code-block:: python
2142

2143 2144 2145
                import paddle
                paddle.enable_static()
                import paddle.distributed.fleet as fleet
2146

2147 2148 2149 2150
                strategy = fleet.DistributedStrategy()
                strategy.semi_auto = True
                # if set other strategy at the same time, auto will not apply
                # strategy.amp = True
2151

2152 2153
                optimizer = paddle.optimizer.SGD(learning_rate=0.01)
                optimizer = fleet.distributed_optimizer(optimizer, strategy)
2154 2155 2156 2157 2158 2159 2160 2161 2162

        """
        return self.strategy.semi_auto

    @semi_auto.setter
    def semi_auto(self, flag):
        if isinstance(flag, bool):
            self.strategy.semi_auto = flag
        else:
2163
            logger.warning("semi-auto should have value of bool type")
2164

Z
zhaoyingli 已提交
2165 2166 2167
    @property
    def auto_search(self):
        """
2168

Z
zhaoyingli 已提交
2169 2170 2171
        Indicating whether we are using auto-search parallel function
        For details, please reference the following code example
        Default Value: False
2172

Z
zhaoyingli 已提交
2173
        Examples:
2174 2175 2176 2177 2178 2179 2180 2181 2182
            .. code-block:: python

                import paddle

                paddle.enable_static()
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.auto_search = True

Z
zhaoyingli 已提交
2183 2184 2185 2186 2187 2188 2189 2190
        """
        return self.strategy.auto_search

    @auto_search.setter
    def auto_search(self, flag):
        if isinstance(flag, bool):
            self.strategy.auto_search = flag
        else:
2191
            logger.warning("auto-search should have value of bool type")
Z
zhaoyingli 已提交
2192

2193 2194 2195
    @property
    def split_data(self):
        """
2196

2197 2198
        Indicating whether we split the data. If True, we split the data.
        Default Value: True
2199

2200
        Examples:
2201 2202 2203 2204 2205 2206 2207 2208 2209
            .. code-block:: python

                import paddle

                paddle.enable_static()
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.split_data = True

2210 2211 2212 2213 2214 2215 2216 2217
        """
        return self.strategy.split_data

    @split_data.setter
    def split_data(self, flag):
        if isinstance(flag, bool):
            self.strategy.split_data = flag
        else:
2218
            logger.warning("split_data should have value of bool type")
2219

2220 2221 2222
    @property
    def qat(self):
        """
2223

2224 2225
        Indicating whether we are using quantization training
        Default Value: False
2226

2227 2228 2229 2230 2231 2232 2233 2234
        """
        return self.strategy.qat

    @qat.setter
    def qat(self, flag):
        if isinstance(flag, bool):
            self.strategy.qat = flag
        else:
2235
            logger.warning("qat should have value of bool type")
2236 2237 2238 2239

    @property
    def qat_configs(self):
        """
2240

2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
        Set quantization training configurations. In general, qat has serveral configurable
        settings that can be configured through a dict.

        **Notes**:
            channel_wise_abs_max(bool): Whether to use `per_channel` quantization training. Default is True.

            weight_bits(int): quantization bit number for weight. Default is 8.

            activation_bits(int): quantization bit number for activation. Default is 8.

2251
            not_quant_pattern(list[str]): When the skip pattern is detected in an op's name scope,
2252 2253 2254 2255 2256
                the corresponding op will not be quantized.

            algo(str): Other quantization training algorithm.

        Exampless:
2257
            .. code-block:: python
2258

2259
                import paddle.distributed.fleet as fleet
2260

2261 2262 2263 2264 2265 2266 2267
                strategy = fleet.DistributedStrategy()
                strategy.qat = True
                strategy.qat_configs = {
                    "channel_wise_abs_max": True,
                    "weight_bits": 8,
                    "activation_bits: 8,
                    "not_quant_pattern": ['skip_quant']}
2268 2269 2270 2271 2272 2273 2274 2275 2276

        """
        return get_msg_dict(self.strategy.qat_configs)

    @qat_configs.setter
    def qat_configs(self, configs):
        check_configs_key(self.strategy.qat_configs, configs, "qat_configs")
        assign_configs_value(self.strategy.qat_configs, configs)

K
kuizhiqing 已提交
2277 2278 2279
    @property
    def heter_ccl_mode(self):
        """
2280

K
kuizhiqing 已提交
2281 2282 2283 2284 2285 2286
        Indicating whether we are using heter_ccl_mode for model training.
        This feature is currently an experimental feature. Currently,
        heter_ccl_mode can be used only for dataparallel with dygraph mode.
        Default Value: False

        Examples:
2287
            .. code-block:: python
K
kuizhiqing 已提交
2288

2289 2290
                import paddle
                import paddle.distributed.fleet as fleet
K
kuizhiqing 已提交
2291

2292 2293
                strategy = fleet.DistributedStrategy()
                strategy.heter_ccl_mode = True
K
kuizhiqing 已提交
2294

2295 2296 2297
                # for initialize parallel env, only need to call
                paddle.distributed.init_parallel_env()
                # then the heterogenous context will be created.
K
kuizhiqing 已提交
2298 2299 2300 2301 2302 2303 2304 2305 2306

        """
        return self.strategy.heter_ccl_mode

    @heter_ccl_mode.setter
    def heter_ccl_mode(self, flag):
        if isinstance(flag, bool):
            self.strategy.heter_ccl_mode = flag
        else:
2307
            logger.warning("heter_ccl_mode should have value of bool type")
K
kuizhiqing 已提交
2308

2309 2310
    @property
    def cudnn_exhaustive_search(self):
2311
        """
2312

2313 2314 2315 2316 2317 2318 2319
        Indicating whether to use exhaustive search method to choose convolution algorithms.
        Exhaustive search attempts all cuDNN algorithms to choose the fastest algorithm.
        This method is time-consuming, the choosed algorithm will be cached for the given layer specifications.
        Once the layer specifications (like batch size, feature map size) are changed, it will search again.
        Default Value: True

        Examples:
2320
            .. code-block:: python
1
123malin 已提交
2321

2322 2323 2324
                import paddle
                paddle.enable_static()
                import paddle.distributed.fleet as fleet
2325

2326 2327 2328 2329 2330
                strategy = fleet.DistributedStrategy()
                strategy.cudnn_exhaustive_search = False

                optimizer = paddle.optimizer.SGD(learning_rate=0.01)
                optimizer = fleet.distributed_optimizer(optimizer, strategy)
2331 2332

        """
2333 2334 2335
        return self.strategy.cudnn_exhaustive_search

    @cudnn_exhaustive_search.setter
2336
    @is_strict_auto
2337 2338 2339 2340
    def cudnn_exhaustive_search(self, flag):
        if isinstance(flag, bool):
            self.strategy.cudnn_exhaustive_search = flag
        else:
2341 2342
            logger.warning(
                "cudnn_exhaustive_search should have value of bool type"
2343 2344 2345 2346
            )

    @property
    def conv_workspace_size_limit(self):
2347
        """
2348

2349 2350 2351 2352 2353 2354 2355
        The workspace limit size in MB unit for choosing cuDNN convolution algorithms.
        The inner funciton of cuDNN obtain the fastest suited algorithm that fits within this memory limit.
        Usually, large workspace size may lead to choose faster algorithms,
        but significant increasing memory workspace. Users need to trade-off between memory and speed.
        Default Value: 4000

        Examples:
2356
            .. code-block:: python
1
123malin 已提交
2357

2358 2359 2360
                import paddle
                paddle.enable_static()
                import paddle.distributed.fleet as fleet
2361

2362 2363
                strategy = fleet.DistributedStrategy()
                strategy.conv_workspace_size_limit = 1024
2364

2365 2366
                optimizer = paddle.optimizer.SGD(learning_rate=0.01)
                optimizer = fleet.distributed_optimizer(optimizer, strategy)
1
123malin 已提交
2367

2368
        """
2369 2370 2371
        return self.strategy.conv_workspace_size_limit

    @conv_workspace_size_limit.setter
2372
    @is_strict_auto
2373 2374 2375 2376
    def conv_workspace_size_limit(self, value):
        if isinstance(value, int):
            self.strategy.conv_workspace_size_limit = value
        else:
2377 2378
            logger.warning(
                "conv_workspace_size_limit should have value of int type"
2379 2380 2381 2382
            )

    @property
    def cudnn_batchnorm_spatial_persistent(self):
2383
        """
2384

2385 2386 2387 2388 2389
        Indicates whether to use the mode CUDNN_BATCHNORM_SPATIAL_PERSISTENT function in batchnorm.
        This is only useful in cudnn.
        Default Value: True

        Examples:
2390
            .. code-block:: python
1
123malin 已提交
2391

2392 2393 2394
                import paddle
                paddle.enable_static()
                import paddle.distributed.fleet as fleet
2395

2396 2397
                strategy = fleet.DistributedStrategy()
                strategy.cudnn_batchnorm_spatial_persistent = True
2398

2399 2400
                optimizer = paddle.optimizer.SGD(learning_rate=0.01)
                optimizer = fleet.distributed_optimizer(optimizer, strategy)
2401 2402

        """
2403 2404 2405
        return self.strategy.cudnn_batchnorm_spatial_persistent

    @cudnn_batchnorm_spatial_persistent.setter
2406
    @is_strict_auto
2407 2408 2409 2410
    def cudnn_batchnorm_spatial_persistent(self, flag):
        if isinstance(flag, bool):
            self.strategy.cudnn_batchnorm_spatial_persistent = flag
        else:
2411 2412
            logger.warning(
                "cudnn_batchnorm_spatial_persistent should have value of bool type"
2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434
            )

    def _enable_env(self):
        strategy = self.strategy
        keys = [
            "FLAGS_cudnn_batchnorm_spatial_persistent",
            "FLAGS_conv_workspace_size_limit",
            "FLAGS_cudnn_exhaustive_search",
            "FLAGS_sync_nccl_allreduce",
            "FLAGS_fuse_parameter_memory_size",
            "FLAGS_fuse_parameter_groups_size",
        ]
        values = [
            bool(strategy.cudnn_batchnorm_spatial_persistent),
            int(strategy.conv_workspace_size_limit),
            bool(strategy.cudnn_exhaustive_search),
            bool(strategy.sync_nccl_allreduce),
            int(strategy.fuse_grad_size_in_MB),
            int(strategy.fuse_grad_size_in_TFLOPS),
        ]

        for i, key in enumerate(keys):
2435 2436
            if _global_flags().is_public(key):
                _global_flags()[key] = values[i]
2437

2438 2439 2440 2441 2442 2443
    def _is_strict_auto(self):
        global non_auto_func_called
        if self.strategy.auto and non_auto_func_called:
            return True
        return False

2444
    def __repr__(self):
2445 2446 2447 2448 2449 2450 2451
        spacing = 2
        max_k = 38
        max_v = 38

        length = max_k + max_v + spacing

        h1_format = "    " + "|{{:^{}s}}|\n".format(length)
2452
        h2_format = "    " + "|{{:>{}s}}{}{{:^{}s}}|\n".format(
2453 2454
            max_k, " " * spacing, max_v
        )
2455 2456 2457 2458 2459 2460 2461 2462 2463

        border = "    +" + "".join(["="] * length) + "+"
        line = "    +" + "".join(["-"] * length) + "+"

        draws = border + "\n"
        draws += h1_format.format("")
        draws += h1_format.format("DistributedStrategy Overview")
        draws += h1_format.format("")

D
Dong Daxiang 已提交
2464
        fields = self.strategy.DESCRIPTOR.fields
2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478
        str_res = ""

        env_draws = line + "\n"
        for f in fields:
            if "build_strategy" in f.name or "execution_strategy" in f.name:
                continue
            if "_configs" in f.name:
                continue
            else:
                if isinstance(getattr(self.strategy, f.name), bool):
                    if hasattr(self.strategy, f.name + "_configs"):
                        if getattr(self.strategy, f.name):
                            draws += border + "\n"
                            draws += h1_format.format(
2479 2480
                                "{}=True <-> {}_configs".format(f.name, f.name)
                            )
2481
                            draws += line + "\n"
2482 2483 2484
                            my_configs = getattr(
                                self.strategy, f.name + "_configs"
                            )
2485 2486 2487
                            config_fields = my_configs.DESCRIPTOR.fields
                            for ff in config_fields:
                                if isinstance(
2488 2489 2490
                                    getattr(my_configs, ff.name),
                                    google.protobuf.pyext._message.RepeatedScalarContainer,
                                ):
2491 2492 2493
                                    values = getattr(my_configs, ff.name)
                                    for i, v in enumerate(values):
                                        if i == 0:
2494
                                            draws += h2_format.format(
2495 2496
                                                ff.name, str(v)
                                            )
2497
                                        else:
2498
                                            draws += h2_format.format(
2499 2500
                                                "", str(v)
                                            )
2501 2502 2503
                                else:
                                    draws += h2_format.format(
                                        ff.name,
2504 2505
                                        str(getattr(my_configs, ff.name)),
                                    )
2506 2507
                    else:
                        env_draws += h2_format.format(
2508 2509
                            f.name, str(getattr(self.strategy, f.name))
                        )
2510 2511
                else:
                    env_draws += h2_format.format(
2512 2513 2514 2515 2516 2517 2518 2519 2520
                        f.name, str(getattr(self.strategy, f.name))
                    )

        result_res = (
            draws
            + border
            + "\n"
            + h1_format.format("Environment Flags, Communication Flags")
        )
2521 2522 2523 2524 2525 2526 2527
        result_res += env_draws

        build_strategy_str = border + "\n"
        build_strategy_str += h1_format.format("Build Strategy")
        build_strategy_str += line + "\n"

        fields = self.strategy.build_strategy.DESCRIPTOR.fields
D
Dong Daxiang 已提交
2528
        for f in fields:
2529
            build_strategy_str += h2_format.format(
2530 2531
                f.name, str(getattr(self.strategy.build_strategy, f.name))
            )
2532 2533 2534 2535 2536 2537 2538 2539
        build_strategy_str += border + "\n"

        execution_strategy_str = h1_format.format("Execution Strategy")
        execution_strategy_str += line + "\n"

        fields = self.strategy.execution_strategy.DESCRIPTOR.fields
        for f in fields:
            execution_strategy_str += h2_format.format(
2540 2541
                f.name, str(getattr(self.strategy.execution_strategy, f.name))
            )
2542 2543 2544 2545
        execution_strategy_str += border + "\n"

        result_res += build_strategy_str + execution_strategy_str
        return result_res