distributed_strategy.py 92.5 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 17
import copy

18 19 20
import google.protobuf
import google.protobuf.text_format

21
import paddle
22
from paddle.distributed.fleet.proto import distributed_strategy_pb2
23
from paddle.distributed.fleet.utils.log_util import logger
24
from paddle.fluid.framework import _global_flags
25
from paddle.fluid.wrapped_decorator import wrap_decorator
26

27
__all__ = []
28

29 30 31 32 33 34 35 36 37 38 39 40 41 42
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__)

43

44 45 46 47
def get_msg_dict(msg):
    res_dict = {}
    fields = msg.DESCRIPTOR.fields
    for f in fields:
48 49 50 51 52 53 54 55 56
        v = getattr(msg, f.name)
        # NOTE(zhiqiu): convert repeated filed to list to
        # avoid segment fault when the process exit?
        # WHY?
        # I guess the type or value of protobuf item is NULL when
        # dealloc.
        if f.label == google.protobuf.descriptor.FieldDescriptor.LABEL_REPEATED:
            v = list(v)
        res_dict[f.name] = v
57 58 59 60 61 62 63 64
    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:
65 66 67
                # LABEL_OPTIONAL = 1
                # LABEL_REPEATED = 3
                # LABEL_REQUIRED = 2
68
                if f.label == 3:
S
sneaxiy 已提交
69 70
                    if config[f.name] is not None:
                        getattr(msg, f.name).extend(config[f.name])
71 72 73 74 75 76 77
                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:
78
        assert key in key_list, f"key:{key} not in {field_name}"
79 80


81
class DistributedJobInfo:
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    """
    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


118 119 120
ReduceStrategyFleet = int


121
class DistributedStrategy:
122 123
    __lock_attr = False

124
    def __init__(self):
125
        """
126

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

132 133
        DistributedStrategy can be serialized into protobuf file or deserialized from protobuf file

134
        Users who run local training usually configure BuildStrategy and ExecutionStrategy, and
135 136 137
        DistributedStrategy supports configurations from BuildStrategy and ExecutionStrategy

        """
138
        self.strategy = distributed_strategy_pb2.DistributedStrategy()
139 140 141

        # Set the default values of the following flags to the ones set by users
        key = 'FLAGS_cudnn_batchnorm_spatial_persistent'
142
        if _global_flags().is_public(key):
143
            self.strategy.cudnn_batchnorm_spatial_persistent = bool(
144 145
                _global_flags()[key]
            )
146
        key = 'FLAGS_conv_workspace_size_limit'
147 148
        if _global_flags().is_public(key):
            self.strategy.conv_workspace_size_limit = int(_global_flags()[key])
149
        key = 'FLAGS_cudnn_exhaustive_search'
150 151
        if _global_flags().is_public(key):
            self.strategy.cudnn_exhaustive_search = bool(_global_flags()[key])
152
        key = 'FLAGS_sync_nccl_allreduce'
153 154
        if _global_flags().is_public(key):
            self.strategy.sync_nccl_allreduce = bool(_global_flags()[key])
155

zhenhailiu's avatar
zhenhailiu 已提交
156
        self.hybrid_parallel_order = ['dp', 'pp', 'sharding', 'sep', 'mp']
W
wuhuachaocoding 已提交
157 158
        self.sync_param_name = ["embedding", "layer_norm", ".b_"]

159
        self.__lock_attr = True
160
        logger.info("distributed strategy initialized")
161 162 163

    def __setattr__(self, key, value):
        if self.__lock_attr and not hasattr(self, key):
164
            raise TypeError(
165
                f"{key} is not a attribute of {self.__class__.__name__}"
166
            )
167
        object.__setattr__(self, key, value)
168

169
    def save_to_prototxt(self, output):
170
        """
171

172 173 174
        Serialize current DistributedStrategy to string and save to output file

        Examples:
175
            .. code-block:: python
1
123malin 已提交
176

177 178 179 180 181 182
                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 已提交
183

184
        """
185 186 187 188
        with open(output, "w") as fout:
            fout.write(str(self.strategy))

    def load_from_prototxt(self, pb_file):
189
        """
190

191 192 193
        Load from prototxt file for DistributedStrategy initialization

        Examples:
194
            .. code-block:: python
1
123malin 已提交
195

196 197 198
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.load_from_prototxt("dist_strategy.prototxt")
199 200 201 202

        """
        with open(pb_file, 'r') as f:
            self.strategy = google.protobuf.text_format.Merge(
203 204
                str(f.read()), self.strategy
            )
205 206 207 208 209 210 211

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

        Examples:
212
            .. code-block:: python
1
123malin 已提交
213

214 215 216 217 218
                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
219

220 221
                strategy = paddle.distributed.fleet.DistributedStrategy()
                strategy.execution_strategy = exe_strategy
222 223

        """
W
wangxiaoning 已提交
224
        execution_strategy = paddle.static.ExecutionStrategy()
225 226
        fields = self.strategy.execution_strategy.DESCRIPTOR.fields
        for f in fields:
227 228 229 230 231
            setattr(
                execution_strategy,
                f.name,
                getattr(self.strategy.execution_strategy, f.name),
            )
232 233 234
        return execution_strategy

    @execution_strategy.setter
235
    @is_strict_auto
236 237 238
    def execution_strategy(self, strategy):
        fields = self.strategy.execution_strategy.DESCRIPTOR.fields
        for f in fields:
239 240 241 242 243
            setattr(
                self.strategy.execution_strategy,
                f.name,
                getattr(strategy, f.name),
            )
244 245 246 247

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

249 250 251 252 253
        Configure BuildStrategy for DistributedStrategy
        Note that the properties of BuildStrategy are valid in DistributedStrategy
        only if the property is non-distributed strategy.

        Examples:
254
            .. code-block:: python
1
123malin 已提交
255

256 257 258 259 260 261 262 263 264 265
                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
266

267 268
                strategy = paddle.distributed.fleet.DistributedStrategy()
                strategy.build_strategy = build_strategy
1
123malin 已提交
269

270 271
        """

W
wangxiaoning 已提交
272
        build_strategy = paddle.static.BuildStrategy()
273 274
        fields = self.strategy.build_strategy.DESCRIPTOR.fields
        for f in fields:
275 276
            value = getattr(self.strategy.build_strategy, f.name)
            if f.name == 'reduce_strategy':
277
                value = paddle.static.BuildStrategy.ReduceStrategy(value)
278
            setattr(build_strategy, f.name, value)
279 280 281
        return build_strategy

    @build_strategy.setter
282
    @is_strict_auto
283 284 285 286
    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
287 288 289 290
                value = getattr(strategy, f.name)
                if f.name == 'reduce_strategy':
                    value = ReduceStrategyFleet(value)
                setattr(self.strategy.build_strategy, f.name, value)
291
            elif f.label == 3:  # repeated field
292 293 294
                getattr(self.strategy.build_strategy, f.name).extend(
                    getattr(strategy, f.name)
                )
295 296

    @property
Y
Yuang Liu 已提交
297 298
    def gradient_scale_configs(self):
        """
299

Y
Yuang Liu 已提交
300
        Set the strategy of gradient scale
301

Y
Yuang Liu 已提交
302
        Examples:
303
            .. code-block:: python
Y
Yuang Liu 已提交
304

305 306 307
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.gradient_scale_configs = {'scale_strategy': 'avg'}
Y
Yuang Liu 已提交
308 309

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

Y
Yuang Liu 已提交
311 312 313 314 315 316
        """
        return get_msg_dict(self.strategy.gradient_scale_configs)

    @gradient_scale_configs.setter
    @is_strict_auto
    def gradient_scale_configs(self, config):
317 318 319 320 321
        check_configs_key(
            self.strategy.gradient_scale_configs,
            config,
            'gradient_scale_configs',
        )
Y
Yuang Liu 已提交
322 323 324
        assign_configs_value(self.strategy.gradient_scale_configs, config)

    @property
D
Dong Daxiang 已提交
325
    def a_sync(self):
326
        """
327

328
        Indicating whether we are using asynchronous stocastic gradient descent updates
329
        for training. This property is valid when we are using parameter server training,
330 331 332 333
        which is implied by setting approperate RoleMaker
        Default value: True

        Examples:
334
            .. code-block:: python
1
123malin 已提交
335

336 337 338
                import paddle.distributed.fleet as fleet
                role_maker = fleet.PaddleCloudRoleMaker()
                fleet.init(role_maker)
339

340 341
                strategy = fleet.DistributedStrategy()
                strategy.a_sync = True  # by default this is True
342

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

346
        """
D
Dong Daxiang 已提交
347
        return self.strategy.a_sync
348

D
Dong Daxiang 已提交
349
    @a_sync.setter
350
    @is_strict_auto
D
Dong Daxiang 已提交
351
    def a_sync(self, flag):
352
        if isinstance(flag, bool):
D
Dong Daxiang 已提交
353
            self.strategy.a_sync = flag
354
            self.a_sync_configs = {"k_steps": 0}
355
        else:
356
            raise ValueError(
357 358 359 360
                "The type of `flag` is invalid, expected type is bool, but received {}".format(
                    type(flag)
                )
            )
361 362

    @property
D
Dong Daxiang 已提交
363
    def a_sync_configs(self):
364
        """
365

D
Dong Daxiang 已提交
366
        Set a_sync update configurations. In general, asynchronous parameter server
367 368
        training has serveral configurable settings that can be configured through
        a dict.
369

370
        **Notes**:
M
mapingshuo 已提交
371 372 373 374 375 376 377 378 379 380 381 382 383
            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
384

385
        Examples:
386
            .. code-block:: python
1
123malin 已提交
387

388 389 390
                import paddle.distributed.fleet as fleet
                role_maker = fleet.PaddleCloudRoleMaker()
                fleet.init(role_maker)
391

392 393 394 395
                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
396

397 398
                # code block for defining loss and local optimizer
                # sgd = fleet.distributed_optimizer(optimizer, strategy)
M
mapingshuo 已提交
399

400
        """
D
Dong Daxiang 已提交
401
        return get_msg_dict(self.strategy.a_sync_configs)
402

D
Dong Daxiang 已提交
403
    @a_sync_configs.setter
404
    @is_strict_auto
D
Dong Daxiang 已提交
405
    def a_sync_configs(self, configs):
406 407 408
        check_configs_key(
            self.strategy.a_sync_configs, configs, "a_sync_configs"
        )
D
Dong Daxiang 已提交
409
        assign_configs_value(self.strategy.a_sync_configs, configs)
410

411 412 413
    @property
    def trainer_desc_configs(self):
        """
414

415
        Set trainer desc configurations.
416 417 418 419 420 421 422 423

        **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

424
            stat_var_names(list(str)):
425 426

        Examples:
427
            .. code-block:: python
428

429 430 431
                import paddle.distributed.fleet as fleet
                role_maker = fleet.PaddleCloudRoleMaker()
                fleet.init(role_maker)
432

433 434 435
                strategy = fleet.DistributedStrategy()
                configs = {"dump_fields_path": "./dump_data", "dump_fields": ["xxx", "yyy"]}
                strategy.trainer_desc_configs = configs
436

437 438
                # code block for defining loss and local optimizer
                # sgd = fleet.distributed_optimizer(optimizer, strategy)
439 440 441 442

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

443 444 445
    @property
    def adam_d2sum(self):
        """
446

447
        set adam_d2sum
W
wangguanqun 已提交
448
        Default value: False
449 450

        Examples:
451
            .. code-block:: python
452

453 454 455
                import paddle.distributed.fleet as fleet
                role_maker = fleet.PaddleCloudRoleMaker()
                fleet.init(role_maker)
456

457 458
                strategy = fleet.DistributedStrategy()
                strategy.adam_d2sum = True  # by default this is False
459

460 461
                # code block for defining loss and local optimizer
                # sgd = fleet.distributed_optimizer(optimizer, strategy)
462 463 464 465 466 467 468 469 470 471 472

        """
        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(
473 474 475 476
                "The type of `flag` is invalid, expected type is bool, but received {}".format(
                    type(flag)
                )
            )
477

478 479 480
    @trainer_desc_configs.setter
    @is_strict_auto
    def trainer_desc_configs(self, configs):
481 482 483
        check_configs_key(
            self.strategy.trainer_desc_configs, configs, "trainer_desc_configs"
        )
484 485
        assign_configs_value(self.strategy.trainer_desc_configs, configs)

486 487 488
    @property
    def fs_client_param(self):
        """
489

490
        Set fs client configurations.
491 492

        Note:
493
            uri(str): the uri of fs client
494

495
            user(str): the user_name of fs client
496

497
            passwd(str): the passwd of fs client
498

499
            hadoop_bin(str):
500

501
        Examples:
502 503 504 505 506 507 508 509 510 511 512
            .. 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)

513 514 515 516 517 518
        """
        return self.strategy.fs_client_param

    @fs_client_param.setter
    @is_strict_auto
    def fs_client_param(self, configs):
519 520 521
        check_configs_key(
            self.strategy.fs_client_param, configs, "fs_client_param"
        )
522 523 524 525 526 527 528 529 530 531
        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
532

533 534
        table_param = self.strategy.downpour_table_param

535
        def set_table_config(msg, config_name, configs, index=0):
536 537 538
            for field in msg.DESCRIPTOR.fields:
                name = config_name + "." + field.name
                if field.type == FieldDescriptor.TYPE_MESSAGE:
539
                    logger.debug(f"message: {name}")
540 541 542 543
                    if field.label == FieldDescriptor.LABEL_REPEATED:
                        if name + ".num" not in configs:
                            continue
                        num = configs[name + ".num"]
544
                        logger.debug(f"message num: {name} {num}")
545 546 547 548
                        for i in range(num):
                            data = getattr(msg, field.name).add()
                            set_table_config(data, name, configs, i)
                    else:
549 550 551
                        set_table_config(
                            getattr(msg, field.name), name, configs
                        )
552
                else:
553
                    logger.debug("not message: %s", name)
554 555 556 557 558
                    if name not in configs:
                        continue
                    if field.label == FieldDescriptor.LABEL_REPEATED:
                        getattr(msg, field.name).extend(configs[name])
                    else:
559 560 561 562
                        if type(configs[name]) == list:
                            setattr(msg, field.name, configs[name][index])
                        else:
                            setattr(msg, field.name, configs[name])
563

564
        if not configs:
565
            logger.info("table configs is empty")
566
        else:
567 568 569
            for table_name in configs:
                table_data = table_param.add()
                table_data.table_name = table_name
570 571 572 573 574
                set_table_config(
                    table_data,
                    "table_parameters." + table_name,
                    configs[table_name],
                )
575

576 577
    @sparse_table_configs.setter
    def fleet_desc_configs(self, configs):
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 611 612 613 614 615 616 617 618 619 620 621 622 623
        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',
L
lxsbupt 已提交
624 625 626 627 628
            'sparse_load_filter_slots',
        ]
        support_sparse_table_class = [
            'DownpourSparseTable',
            'DownpourSparseSSDTable',
629
        ]
630
        support_sparse_accessor_class = [
631 632 633 634 635 636
            'DownpourSparseValueAccessor',
            'DownpourCtrAccessor',
            'DownpourCtrDoubleAccessor',
            'DownpourUnitAccessor',
            'DownpourDoubleUnitAccessor',
            'DownpourCtrDymfAccessor',
637 638 639
        ]
        table_param = self.strategy.downpour_table_param

D
danleifeng 已提交
640
        def add_graph_config(graph, strategy):
641 642 643
            graph.feature_learning_rate = strategy.get(
                'feature_learning_rate', 0.05
            )
D
danleifeng 已提交
644 645
            graph.nodeid_slot = strategy.get('nodeid_slot', 9008)

646
        def sparse_optimizer_config(sgd, strategy, prefix):
647 648 649
            optimizer_name = strategy.get(
                prefix + "sparse_optimizer", "adagrad"
            )
650 651 652 653
            sgd.name = optimizer_name
            if optimizer_name == "naive":
                sgd.name = "SparseNaiveSGDRule"
                sgd.naive.learning_rate = strategy.get(
654 655
                    prefix + 'sparse_learning_rate', 0.05
                )
656
                sgd.naive.initial_range = strategy.get(
657 658 659 660 661
                    prefix + 'sparse_initial_range', 1e-4
                )
                bounds = strategy.get(
                    prefix + 'sparse_weight_bounds', [-10, 10]
                )
662 663 664 665
                sgd.naive.weight_bounds.extend(bounds)
            elif optimizer_name == "adagrad":
                sgd.name = 'SparseAdaGradSGDRule'
                sgd.adagrad.learning_rate = strategy.get(
666 667
                    prefix + 'sparse_learning_rate', 0.05
                )
668
                sgd.adagrad.initial_range = strategy.get(
669 670
                    prefix + 'sparse_initial_range', 1e-4
                )
671 672 673
                if prefix == "embed_":
                    sgd.adagrad.initial_range = 0
                sgd.adagrad.initial_g2sum = strategy.get(
674 675 676 677 678
                    prefix + 'sparse_initial_g2sum', 3
                )
                bounds = strategy.get(
                    prefix + 'sparse_weight_bounds', [-10, 10]
                )
679 680 681 682
                sgd.adagrad.weight_bounds.extend(bounds)
            elif optimizer_name == "std_adagrad":
                sgd.name = 'StdAdaGradSGDRule'
                sgd.adagrad.learning_rate = strategy.get(
683 684
                    prefix + 'sparse_learning_rate', 0.05
                )
685
                sgd.adagrad.initial_range = strategy.get(
686 687
                    prefix + 'sparse_initial_range', 1e-4
                )
688 689 690
                if prefix == "embed_":
                    sgd.adagrad.initial_range = 0
                sgd.adagrad.initial_g2sum = strategy.get(
691 692 693 694 695
                    prefix + 'sparse_initial_g2sum', 3
                )
                bounds = strategy.get(
                    prefix + 'sparse_weight_bounds', [-10, 10]
                )
696 697 698
                sgd.adagrad.weight_bounds.extend(bounds)
            elif optimizer_name == "adam":
                sgd.name = 'SparseAdamSGDRule'
D
danleifeng 已提交
699
                sgd.adam.learning_rate = strategy.get(
700 701
                    prefix + 'sparse_learning_rate', 0.001
                )
D
danleifeng 已提交
702
                sgd.adam.initial_range = strategy.get(
703 704
                    prefix + 'sparse_initial_range', 1e-4
                )
D
danleifeng 已提交
705
                sgd.adam.beta1_decay_rate = strategy.get(
706 707
                    prefix + 'sparse_beta1_decay_rate', 0.9
                )
D
danleifeng 已提交
708
                sgd.adam.beta2_decay_rate = strategy.get(
709 710
                    prefix + 'sparse_beta2_decay_rate', 0.999
                )
D
danleifeng 已提交
711
                sgd.adam.ada_epsilon = strategy.get(
712 713 714 715 716
                    prefix + 'sparse_ada_epsilon', 1e-8
                )
                bounds = strategy.get(
                    prefix + 'sparse_weight_bounds', [-10, 10]
                )
D
danleifeng 已提交
717 718 719
                sgd.adam.weight_bounds.extend(bounds)
            elif optimizer_name == "shared_adam":
                sgd.name = 'SparseSharedAdamSGDRule'
720
                sgd.adam.learning_rate = strategy.get(
721 722
                    prefix + 'sparse_learning_rate', 0.001
                )
723
                sgd.adam.initial_range = strategy.get(
724 725
                    prefix + 'sparse_initial_range', 1e-4
                )
726
                sgd.adam.beta1_decay_rate = strategy.get(
727 728
                    prefix + 'sparse_beta1_decay_rate', 0.9
                )
729
                sgd.adam.beta2_decay_rate = strategy.get(
730 731
                    prefix + 'sparse_beta2_decay_rate', 0.999
                )
732
                sgd.adam.ada_epsilon = strategy.get(
733 734 735 736 737
                    prefix + 'sparse_ada_epsilon', 1e-8
                )
                bounds = strategy.get(
                    prefix + 'sparse_weight_bounds', [-10, 10]
                )
738 739 740 741 742 743
                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))
744 745 746
            table_class = config.get(
                "sparse_table_class", "DownpourSparseTable"
            )
747 748
            if table_class not in support_sparse_table_class:
                raise ValueError(
L
lxsbupt 已提交
749
                    "support sparse_table_class: ['DownpourSparseTable, DownpourSparseSSDTable'], but actual %s"
750 751
                    % (table_class)
                )
L
lxsbupt 已提交
752 753 754 755
            if table_class == "DownpourSparseSSDTable":
                table_data.table_class = 'SSDSparseTable'
            else:
                table_data.table_class = 'MemorySparseTable'
756
            table_data.shard_num = config.get('sparse_shard_num', 1000)
757
            table_data.enable_sparse_table_cache = config.get(
758 759
                'sparse_enable_cache', True
            )
760
            table_data.sparse_table_cache_rate = config.get(
761 762
                'sparse_cache_rate', 0.00055
            )
763
            table_data.sparse_table_cache_file_num = config.get(
764 765
                'sparse_cache_file_num', 16
            )
766

767 768 769
            accessor_class = config.get(
                "sparse_accessor_class", "DownpourCtrAccessor"
            )
770 771
            if accessor_class not in support_sparse_accessor_class:
                raise ValueError(
772
                    "support sparse_accessor_class: ['DownpourSparseValueAccessor', 'DownpourCtrAccessor', 'DownpourCtrDoubleAccessor', 'DownpourUnitAccessor', 'DownpourDoubleUnitAccessor'], but actual %s"
773 774
                    % (accessor_class)
                )
775

776 777
            if accessor_class.find("Double") >= 0:
                table_data.accessor.accessor_class = 'CtrDoubleAccessor'
778 779
            elif accessor_class.find("Dymf") >= 0:
                table_data.accessor.accessor_class = 'CtrDymfAccessor'
780
            else:
781 782 783
                table_data.accessor.accessor_class = 'CtrCommonAccessor'

            if not configs.get("use_cvm", True):
784 785 786 787 788
                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(
789 790
                'sparse_embedx_threshold', 10
            )
791

792 793 794 795 796
            if accessor_class == 'DownpourUnitAccessor':
                table_data.accessor.ctr_accessor_param.show_scale = False
            else:
                table_data.accessor.ctr_accessor_param.show_scale = True

797
            table_data.accessor.ctr_accessor_param.nonclk_coeff = config.get(
798 799
                'sparse_nonclk_coeff', 0.1
            )
800
            table_data.accessor.ctr_accessor_param.click_coeff = config.get(
801 802
                'sparse_click_coeff', 1
            )
803
            table_data.accessor.ctr_accessor_param.base_threshold = config.get(
804 805
                'sparse_base_threshold', 1.5
            )
806
            table_data.accessor.ctr_accessor_param.delta_threshold = config.get(
807 808
                'sparse_delta_threshold', 0.25
            )
809
            table_data.accessor.ctr_accessor_param.delta_keep_days = config.get(
810 811 812 813 814 815 816 817 818 819 820 821 822 823
                '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)
            )
L
lxsbupt 已提交
824 825 826 827
            load_filter_slots = config.get('sparse_load_filter_slots', [])
            table_data.accessor.ctr_accessor_param.load_filter_slots.extend(
                load_filter_slots
            )
828 829 830 831 832 833 834 835 836 837 838 839 840
            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

841 842 843 844 845 846 847 848 849 850
            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, ''
                )
851
            else:
852 853 854 855 856 857
                sparse_optimizer_config(
                    table_data.accessor.embed_sgd_param, config, 'embed_'
                )
                sparse_optimizer_config(
                    table_data.accessor.embedx_sgd_param, config, 'embedx_'
                )
D
danleifeng 已提交
858
            add_graph_config(table_data.accessor.graph_sgd_param, config)
859 860

        if not configs:
861
            logger.info("fleet desc config is empty")
862 863
        else:
            for table_name in configs:
864 865 866 867
                if (
                    table_name == 'dense_table'
                    or table_name == 'datanorm_table'
                ):
868 869 870 871 872 873 874
                    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])

875
    @property
876 877 878 879
    def amp(self):
        """
        Indicating whether we are using automatic mixed precision training
        Default Value: False
880

881
        Examples:
1
123malin 已提交
882

883
          .. code-block:: python
884

885
            import paddle.distributed.fleet as fleet
886 887
            strategy = fleet.DistributedStrategy()
            strategy.amp = True # by default this is false
888

889 890
        """
        return self.strategy.amp
891

892
    @amp.setter
893
    @is_strict_auto
894
    def amp(self, flag):
895
        if isinstance(flag, bool):
896
            self.strategy.amp = flag
897
        else:
898
            logger.warning("amp should have value of bool type")
899 900

    @property
901
    def amp_configs(self):
902
        """
903

904 905 906 907
        Set automatic mixed precision training configurations. In general, amp has serveral configurable
        settings that can be configured through a dict.

        **Notes**:
M
mapingshuo 已提交
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
            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.
923

924 925 926 927 928 929 930 931
            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:
932
            .. code-block:: python
1
123malin 已提交
933

934 935 936 937 938 939
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.amp = True
                strategy.amp_configs = {
                    "init_loss_scaling": 32768,
                    "custom_white_list": ['conv2d']}
940 941

        Examples 2:
942 943 944 945 946 947 948 949 950 951
            .. 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
                }
952

953
        """
954
        return get_msg_dict(self.strategy.amp_configs)
955

956
    @amp_configs.setter
957
    @is_strict_auto
958 959 960
    def amp_configs(self, configs):
        check_configs_key(self.strategy.amp_configs, configs, "amp_configs")
        assign_configs_value(self.strategy.amp_configs, configs)
961

962 963 964
    @property
    def asp(self):
        """
965

966 967 968 969
        Indicating whether we are using automatic sparsity training
        Default Value: False

        Examples:
970
            .. code-block:: python
971

972 973 974
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.asp = True # by default this is false
975 976 977 978 979 980 981 982 983 984

        """
        return self.strategy.asp

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

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
    @property
    def qat(self):
        """
        Indicating whether we are using quantization aware training
        Default Value: False

        Examples:

          .. code-block:: python

            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.qat = True # by default this is false

        """
        return self.strategy.qat

    @qat.setter
    @is_strict_auto
    def qat(self, flag):
        assert isinstance(flag, bool), "qat should have value of bool type"
        self.strategy.qat = flag

    @property
    def qat_configs(self):
        """
        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.
            not_quant_pattern(list[str]): When the skip pattern is detected in an op's name scope,
                the corresponding op will not be quantized.
            algo(str): Other quantization training algorithm.
        Exampless:
          .. code-block:: python
            import paddle.distributed.fleet as fleet
            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']}
        """
        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)

1040
    @property
1041 1042 1043 1044 1045 1046
    def recompute(self):
        """
        Indicating whether we are using forward recomputation for memory optimization
        Default value: False

        Examples:
1047
            .. code-block:: python
1
123malin 已提交
1048

1049 1050 1051 1052 1053
                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"]}
1054 1055 1056

        """
        return self.strategy.recompute
1057

1058 1059
    @property
    def sync_nccl_allreduce(self):
1060
        """
1061

1062 1063 1064 1065
        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:
1066
            .. code-block:: python
1
123malin 已提交
1067

1068 1069 1070
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.sync_nccl_allreduce = True
1071 1072

        """
1073 1074 1075
        return self.strategy.sync_nccl_allreduce

    @sync_nccl_allreduce.setter
1076
    @is_strict_auto
1077 1078 1079 1080
    def sync_nccl_allreduce(self, flag):
        if isinstance(flag, bool):
            self.strategy.sync_nccl_allreduce = flag
        else:
1081
            logger.warning("sync_nccl_allreduce should have value of bool type")
1082

1083
    @property
1084
    def use_hierarchical_allreduce(self):
1085
        """
1086

1087 1088 1089 1090 1091
        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:
1092
            .. code-block:: python
1
123malin 已提交
1093

1094 1095 1096
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.use_hierarchical_allreduce = True
1097 1098

        """
1099
        return self.strategy.use_hierarchical_allreduce
1100

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

    @property
1112
    def hierarchical_allreduce_inter_nranks(self):
1113
        """
1114

1115 1116 1117 1118
        Number of ranks for low level node groups in hierarchical allreduce
        Default value: number of GPU cards on each single GPU machine

        Example:
1119
            .. code-block:: python
1
123malin 已提交
1120

1121 1122 1123
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.hierarchical_allreduce_inter_nranks = 8
1124 1125

        """
1126
        return self.strategy.hierarchical_allreduce_inter_nranks
1127

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

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

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

1144 1145 1146
        Default value: False

        Examples:
1147
            .. code-block:: python
1
123malin 已提交
1148

1149 1150 1151
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.sync_batch_norm = True
1152 1153 1154

        """

1155
        return self.strategy.sync_batch_norm
1156

1157
    @sync_batch_norm.setter
1158
    @is_strict_auto
1159
    def sync_batch_norm(self, flag):
1160
        if isinstance(flag, bool):
1161
            self.strategy.sync_batch_norm = flag
1162
        else:
1163
            logger.warning("sync_batch_norm should have value of bool type")
1164 1165 1166

    @property
    def fuse_all_reduce_ops(self):
1167
        """
1168

1169 1170 1171 1172
        Indicating whether we are using fuse_all_reduce_ops for gradient fusion during backward phase of training
        Default value: True

        Examples:
1173
            .. code-block:: python
1
123malin 已提交
1174

1175 1176 1177
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.fuse_all_reduce_ops = False
1178 1179

        """
1180 1181 1182
        return self.strategy.fuse_all_reduce_ops

    @fuse_all_reduce_ops.setter
1183
    @is_strict_auto
1184 1185 1186 1187
    def fuse_all_reduce_ops(self, flag):
        if isinstance(flag, bool):
            self.strategy.fuse_all_reduce_ops = flag
        else:
1188
            logger.warning("fuse_all_reduce_ops should have value of bool type")
1189

1190 1191
    @property
    def fuse_grad_size_in_MB(self):
1192
        """
1193

1194 1195 1196 1197 1198
        Specifying the size of gradient to fuse in Mega-Bytes

        Default value: 32

        Examples:
1199
            .. code-block:: python
1
123malin 已提交
1200

1201 1202 1203
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.fuse_grad_size_in_MB = 50
1
123malin 已提交
1204

1205
        """
1206 1207 1208
        return self.strategy.fuse_grad_size_in_MB

    @fuse_grad_size_in_MB.setter
1209
    @is_strict_auto
1210 1211 1212 1213
    def fuse_grad_size_in_MB(self, value):
        if isinstance(value, int):
            self.strategy.fuse_grad_size_in_MB = value
        else:
1214
            logger.warning("fuse_grad_size_in_MB should have value of int type")
1215

1216 1217 1218
    @property
    def last_comm_group_size_MB(self):
        """
1219

1220 1221 1222
        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.
1223 1224 1225 1226

        Default value: 1

        Examples:
1227 1228 1229 1230 1231
            .. code-block:: python

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

1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
        """
        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")

1244 1245 1246
    @property
    def find_unused_parameters(self):
        """
1247

1248
        Indicating whether we are using find_unused_parameters to
1249 1250
        find unused parameters in DataParallel.

1251
        Default value: False
1252 1253

        Examples:
1254
            .. code-block:: python
1255

1256 1257 1258
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.find_unused_parameters = True
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269

        """

        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:
1270 1271
            logger.warning(
                "find_unused_parameters should have value of bool type"
1272
            )
1273

1274 1275 1276 1277 1278
    @property
    def _fuse_grad_size_in_TFLOPS(self):
        return self.strategy.fuse_grad_size_in_TFLOPS

    @_fuse_grad_size_in_TFLOPS.setter
1279
    @is_strict_auto
1280 1281 1282 1283
    def _fuse_grad_size_in_TFLOPS(self, value):
        if isinstance(value, float):
            self.strategy.fuse_grad_size_in_TFLOPS = value
        else:
1284 1285
            logger.warning(
                "fuse_grad_size_in_TFLOPS should have value of float type"
1286 1287
            )

1288
    @property
1289
    def nccl_comm_num(self):
1290
        """
1291

1292 1293 1294 1295 1296
        Specifying the number of NCCL communicator

        Default value: 1

        Examples:
1297
            .. code-block:: python
1
123malin 已提交
1298

1299 1300 1301
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.nccl_comm_num = 2
1
123malin 已提交
1302

1303 1304
        """

1305
        return self.strategy.nccl_comm_num
1306

1307
    @nccl_comm_num.setter
1308
    @is_strict_auto
1309
    def nccl_comm_num(self, value):
1310
        if isinstance(value, int):
1311
            self.strategy.nccl_comm_num = value
1312
        else:
1313
            logger.warning("nccl_comm_num should have value of int type")
1314

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

    @property
1324 1325
    def recompute_configs(self):
        """
1326

1327 1328
        Set recompute configurations.

J
JZ-LIANG 已提交
1329 1330 1331 1332
        **Note**:
        checkpoints(list): list of string name of checkpoints. In general, the recompute
        strategy of current implementation should have some manually assign checkpoints.

1333
        enable_offload(bool): enable recompute checkpoints offload feature. this feature
J
JZ-LIANG 已提交
1334 1335 1336 1337 1338 1339
        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
1340
        specific here should be determined ("-1" is not allowed).
1341

1342
        Examples:
1343
            .. code-block:: python
1
123malin 已提交
1344

1345 1346 1347 1348 1349 1350 1351
                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] }
1352 1353 1354 1355 1356

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

    @recompute_configs.setter
1357
    @is_strict_auto
1358
    def recompute_configs(self, configs):
1359 1360 1361
        check_configs_key(
            self.strategy.recompute_configs, configs, "checkpoint_configs"
        )
1362
        assign_configs_value(self.strategy.recompute_configs, configs)
1363

1364 1365 1366
    @property
    def sharding(self):
        """
1367

1368
        Indicating whether we are using sharding Optimizer for memory
1369
        optimization. We implement the sharding optimizer following the ZeRO-DP
J
JZ-LIANG 已提交
1370 1371
        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.
1372

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

1375 1376 1377
        Default value: False

        Examples:
1378
            .. code-block:: python
1
123malin 已提交
1379

1380 1381 1382
                import paddle.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.sharding = True
1
123malin 已提交
1383

1384 1385 1386 1387 1388 1389 1390 1391 1392
        """
        return self.strategy.sharding

    @sharding.setter
    @is_strict_auto
    def sharding(self, flag):
        if isinstance(flag, bool):
            self.strategy.sharding = flag
        else:
1393
            logger.warning("sharding should have value of bool type")
1394 1395 1396 1397

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

1399
        Set sharding configurations.
1400 1401

        **Note**:
1402 1403
            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
1404 1405
            communication. Default is segment_broadcast_MB.

1406
            segment_broadcast_MB(float, optional): segment by the parameters broadcast volume. sharding will introduce parameter broadcast operations into program, and
1407 1408 1409 1410
            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 .

1411
            segment_anchors(list): list of anchors used to segment the program, which allows a finner control of program segmentation.
1412 1413 1414 1415 1416 1417
            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.

1418
            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.
1419 1420 1421 1422 1423
            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.

1424
            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.
1425

1426
            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.
1427

1428
            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.
1429
            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 已提交
1430

1431 1432 1433
            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 已提交
1434

1435
        Examples:
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
            .. 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 已提交
1449

1450 1451 1452 1453 1454 1455
        """
        return get_msg_dict(self.strategy.sharding_configs)

    @sharding_configs.setter
    @is_strict_auto
    def sharding_configs(self, configs):
1456 1457 1458
        check_configs_key(
            self.strategy.sharding_configs, configs, "sharding_configs"
        )
1459 1460
        assign_configs_value(self.strategy.sharding_configs, configs)

1461 1462 1463
    @property
    def without_graph_optimization(self):
        """
1464

1465 1466 1467
        Run program using Executor other than ParallelExecutor.

        Examples:
1468
            .. code-block:: python
1469

1470 1471 1472
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.without_graph_optimization = True
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482

        """
        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:
1483 1484
            logger.warning(
                "without_graph_optimization should have value of bool type"
1485 1486
            )

1487 1488 1489
    @property
    def _calc_comm_same_stream(self):
        """
1490

1491 1492 1493
        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
1494

1495
        Examples:
1496 1497 1498 1499 1500 1501
            .. code-block:: python

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

1502 1503 1504 1505 1506 1507 1508 1509 1510
        """
        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:
1511 1512
            logger.warning(
                "calc_comm_same_stream should have value of boolean type"
1513 1514
            )

1515 1516 1517
    @property
    def fuse_grad_merge(self):
        """
1518

1519 1520 1521
        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
1522

1523
        Examples:
1524 1525 1526 1527 1528 1529
            .. code-block:: python

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

1530 1531 1532 1533 1534 1535 1536 1537 1538
        """
        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:
1539
            logger.warning("fuse_grad_merge should have value of boolean type")
1540

1541 1542 1543
    @property
    def fuse_grad_size_in_num(self):
        """
1544

1545
        This based on raw_program_optimizer program and allreduce the num of the fused op
1546

1547
        Examples:
1548 1549 1550 1551 1552 1553 1554
            .. code-block:: python

                import paddle.distributed.fleet as fleet

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

1555 1556 1557 1558 1559 1560 1561 1562 1563
        """
        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:
1564 1565
            logger.warning(
                "fuse_grad_size_in_num should have value of int32 type"
1566
            )
1567

1568
    @property
1569 1570
    def pipeline(self):
        """
1571

1572 1573 1574 1575 1576 1577
        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:
1578
            .. code-block:: python
1
123malin 已提交
1579

1580 1581 1582
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.pipeline = True
1583 1584 1585

        """
        return self.strategy.pipeline
1586

1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
    @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:
1597
            logger.warning("is_fl_ps_mode should have value of bool type")
1598

1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
    @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:
1609
            logger.warning("with_coordinator should have value of bool type")
1610

1611
    @pipeline.setter
1612
    @is_strict_auto
1613
    def pipeline(self, flag):
1614
        if isinstance(flag, bool):
1615
            self.strategy.pipeline = flag
1616
        else:
1617
            logger.warning("pipeline should have value of bool type")
1618 1619

    @property
1620 1621
    def pipeline_configs(self):
        """
1622

1623 1624
        Set pipeline parallelism configurations. In pipeline parallelism,
        different parts of neural networks are running on different GPUS.
1625
        There are Tensor queue buffer between each pair of neighborhood GPUS
1626 1627 1628
        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
1629
        pipeline parallelism is to make the size of Tensor in Tensor queue smaller,
1630
        so that we will have a faster producer for downstream consumers.
1631

1632 1633
        **Notes**:
            **Detailed arguments for pipeline_configs**
M
mapingshuo 已提交
1634

1635
            **micro_batch_size**: the number of small batches in each user defined batch
1636

1637
        Examples:
1638
            .. code-block:: python
1
123malin 已提交
1639

1640 1641 1642 1643
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.pipeline = True
                strategy.pipeline_configs = {"micro_batch_size": 12}
1644

1645
        """
1646

1647
        return get_msg_dict(self.strategy.pipeline_configs)
1648

1649
    @pipeline_configs.setter
1650
    @is_strict_auto
1651
    def pipeline_configs(self, configs):
1652 1653 1654
        check_configs_key(
            self.strategy.pipeline_configs, configs, "pipeline_configs"
        )
1655
        assign_configs_value(self.strategy.pipeline_configs, configs)
1656

L
lilong12 已提交
1657 1658 1659
    @property
    def tensor_parallel(self):
        """
1660

L
lilong12 已提交
1661 1662 1663
        Indicating whether we are using tensor parallel for distributed training.

        Examples:
1664
            .. code-block:: python
L
lilong12 已提交
1665

1666 1667 1668
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.tensor_parallel = True
L
lilong12 已提交
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678

        """
        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:
1679
            logger.warning("tensor_parallel should have value of bool type")
L
lilong12 已提交
1680 1681 1682 1683

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

L
lilong12 已提交
1685 1686 1687 1688
        Set tensor_parallel configurations.

        **Notes**:
            **Detailed arguments for tensor_parallel_configs**
1689

L
lilong12 已提交
1690
            **tensor_parallel_degree**: degree of tensor parallel
1691

1692 1693
            **tensor_init_seed**: parameter initialization random seed

L
lilong12 已提交
1694 1695

        Examples:
1696
            .. code-block:: python
L
lilong12 已提交
1697

1698 1699 1700 1701 1702
                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 已提交
1703 1704 1705 1706 1707 1708 1709

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

    @tensor_parallel_configs.setter
    @is_strict_auto
    def tensor_parallel_configs(self, configs):
1710 1711 1712 1713 1714
        check_configs_key(
            self.strategy.tensor_parallel_configs,
            configs,
            "tensor_parallel_configs",
        )
L
lilong12 已提交
1715 1716
        assign_configs_value(self.strategy.tensor_parallel_configs, configs)

1717 1718 1719
    @property
    def hybrid_configs(self):
        """
1720

zhenhailiu's avatar
zhenhailiu 已提交
1721
        Dynamic graph hybrid parallel strategy configuration. Five-way hybrid parallelism
1722 1723
        needs to meet the following relationships

zhenhailiu's avatar
zhenhailiu 已提交
1724
        total_number_GPUs = dp_degree * mp_degree * pp_degree * sharding_degree * sep_degree
1725 1726

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

1732 1733 1734
            **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
zhenhailiu's avatar
zhenhailiu 已提交
1735 1736 1737
            **sep_degree(int)**: set number of GPUs in a sep parallel group. Default 1
            **sharding_degree(int)**: set number of GPUs in a sharding parallel group. Default 1
            **order(list(string))**: set hybrid parallel dimensions, the order is from outside to inside. Default ['dp','pp','sharding','sep', 'mp']
1738

1739
        Examples:
1740 1741 1742 1743 1744 1745 1746
            .. code-block:: python

                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.hybrid_configs = {
                    "dp_degree": 1,
                    "mp_degree": 2,
1747
                    "pp_degree": 1,
zhenhailiu's avatar
zhenhailiu 已提交
1748
                    "order":['dp','pp','sharding', 'sep', 'mp']}
1749

1750 1751 1752 1753 1754
        """
        return get_msg_dict(self.strategy.hybrid_configs)

    @hybrid_configs.setter
    def hybrid_configs(self, configs):
1755 1756 1757 1758 1759
        hybrid_config = copy.deepcopy(configs)
        if "order" in hybrid_config:
            self.hybrid_parallel_order = hybrid_config["order"]
            hybrid_config.pop('order')

1760
        check_configs_key(
1761
            self.strategy.hybrid_configs, hybrid_config, "hybrid_configs"
1762
        )
1763 1764

        if "mp_configs" in configs:
W
wuhuachaocoding 已提交
1765 1766 1767 1768
            if "sync_param_name" in configs["mp_configs"]:
                self.sync_param_name = configs["mp_configs"]["sync_param_name"]
                configs["mp_configs"].pop("sync_param_name")

1769 1770 1771 1772
            assign_configs_value(
                self.strategy.hybrid_configs.mp_configs, configs["mp_configs"]
            )
            configs.pop("mp_configs")
1773 1774 1775 1776 1777 1778
        if "pp_configs" in configs:
            assign_configs_value(
                self.strategy.hybrid_configs.pp_configs, configs["pp_configs"]
            )
            configs.pop("pp_configs")

1779 1780
        assign_configs_value(self.strategy.hybrid_configs, configs)

1781
    @property
1782
    def localsgd(self):
1783
        """
1784

M
mapingshuo 已提交
1785 1786 1787
        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>`_.
1788 1789 1790


        Examples:
1791
            .. code-block:: python
1
123malin 已提交
1792

1793 1794 1795
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.localsgd = True # by default this is false
1796 1797

        """
1798
        return self.strategy.localsgd
1799

1800
    @localsgd.setter
1801
    @is_strict_auto
1802 1803 1804
    def localsgd(self, flag):
        if isinstance(flag, bool):
            self.strategy.localsgd = flag
1805
        else:
1806
            logger.warning("localsgd should have value of bool type")
1807 1808

    @property
1809
    def localsgd_configs(self):
1810
        """
1811

1812 1813 1814 1815
        Set LocalSGD training configurations. LocalSGD has a configurable
        setting that can be configured through a dict.

        **Notes**:
M
mapingshuo 已提交
1816
            k_steps(int) The local steps for training before parameter synchronization. Default 1.
1817
            begin_step(int) The step of beginning training by localsgd. Default 1.
1818 1819

        Examples:
1820
            .. code-block:: python
1
123malin 已提交
1821

1822 1823 1824 1825 1826
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.localsgd = True
                strategy.localsgd_configs = {"k_steps": 4,
                                            "begin_step": 30}
1827 1828 1829

        """

1830
        return get_msg_dict(self.strategy.localsgd_configs)
1831

1832
    @localsgd_configs.setter
1833
    @is_strict_auto
1834
    def localsgd_configs(self, configs):
1835 1836 1837
        check_configs_key(
            self.strategy.localsgd_configs, configs, "localsgd_configs"
        )
1838
        assign_configs_value(self.strategy.localsgd_configs, configs)
1839

1840 1841 1842
    @property
    def adaptive_localsgd(self):
        """
1843

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

        Examples:
1849
            .. code-block:: python
1
123malin 已提交
1850

1851 1852 1853
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.adaptive_localsgd = True # by default this is false
1854 1855

        """
1856
        return self.strategy.adaptive_localsgd
1857 1858 1859 1860 1861

    @adaptive_localsgd.setter
    @is_strict_auto
    def adaptive_localsgd(self, flag):
        if isinstance(flag, bool):
1862
            self.strategy.adaptive_localsgd = flag
1863
        else:
1864
            logger.warning("adaptive_localsgd should have value of bool type")
1865 1866 1867 1868

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

1870 1871 1872 1873 1874 1875 1876
        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.
1877

1878
            begin_step(int) The step of beginning training by adaptive localsgd. Default 1.
1879 1880

        Examples:
1881
            .. code-block:: python
1
123malin 已提交
1882

1883 1884 1885 1886 1887
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.adaptive_localsgd = True
                strategy.adaptive_localsgd_configs = {"init_k_steps": 1,
                                                    "begin_step": 30}
1888 1889 1890 1891 1892 1893 1894 1895

        """

        return get_msg_dict(self.strategy.adaptive_localsgd_configs)

    @adaptive_localsgd_configs.setter
    @is_strict_auto
    def adaptive_localsgd_configs(self, configs):
1896 1897 1898 1899 1900
        check_configs_key(
            self.strategy.adaptive_localsgd_configs,
            configs,
            "adaptive_localsgd_configs",
        )
1901 1902
        assign_configs_value(self.strategy.adaptive_localsgd_configs, configs)

1903
    @property
1904
    def dgc(self):
1905
        """
1906

1907 1908 1909 1910 1911 1912
        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:
1913
            .. code-block:: python
1
123malin 已提交
1914

1915 1916 1917
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.dgc = True # by default this is false
1918 1919

        """
1920
        return self.strategy.dgc
1921

1922
    @dgc.setter
1923
    @is_strict_auto
1924 1925 1926
    def dgc(self, flag):
        if isinstance(flag, bool):
            self.strategy.dgc = flag
1927
        else:
1928
            logger.warning("dgc should have value of bool type")
1929 1930

    @property
1931
    def dgc_configs(self):
1932
        r"""
1933

1934 1935 1936 1937
        Set Deep Gradient Compression training configurations. In general, dgc has serveral configurable
        settings that can be configured through a dict.

        **Notes**:
M
mapingshuo 已提交
1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
            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.
1948 1949

        Examples:
1950
            .. code-block:: python
1
123malin 已提交
1951

1952 1953 1954 1955
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.dgc = True
                strategy.dgc_configs = {"rampup_begin_step": 1252}
1956 1957

        """
1958
        return get_msg_dict(self.strategy.dgc_configs)
1959

1960
    @dgc_configs.setter
1961
    @is_strict_auto
1962 1963 1964
    def dgc_configs(self, configs):
        check_configs_key(self.strategy.dgc_configs, configs, "dgc_configs")
        assign_configs_value(self.strategy.dgc_configs, configs)
1965

1966 1967 1968
    @property
    def fp16_allreduce(self):
        """
1969

1970 1971 1972 1973
        Indicating whether we are using fp16 gradient allreduce training
        Default Value: False

        Examples:
1974
            .. code-block:: python
1
123malin 已提交
1975

1976
                import paddle.distributed.fleet as fleet
1977

1978 1979
                strategy = fleet.DistributedStrategy()
                strategy.fp16_allreduce = True # by default this is false
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990

        """
        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

1991
    @property
1992
    def gradient_merge(self):
1993
        """
1994

1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
        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:
2005
            .. code-block:: python
1
123malin 已提交
2006

2007 2008 2009 2010
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.gradient_merge = True
                strategy.gradient_merge_configs = {"k_steps": 4, "avg": True}
M
mapingshuo 已提交
2011

2012
        """
2013
        return self.strategy.gradient_merge
2014

2015
    @gradient_merge.setter
2016
    @is_strict_auto
2017
    def gradient_merge(self, flag):
2018
        if isinstance(flag, bool):
2019
            self.strategy.gradient_merge = flag
2020
        else:
2021
            logger.warning("gradient_merge should have value of bool type")
2022 2023 2024

    @property
    def gradient_merge_configs(self):
2025
        """
2026

2027
        the key-value configs of distribute_strategy
M
mapingshuo 已提交
2028 2029 2030 2031 2032 2033 2034

        **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:
2035
            .. code-block:: python
1
123malin 已提交
2036

2037 2038 2039 2040
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.gradient_merge = True
                strategy.gradient_merge_configs = {"k_steps": 4, "avg": True}
M
mapingshuo 已提交
2041

2042
        """
2043 2044 2045
        return get_msg_dict(self.strategy.gradient_merge_configs)

    @gradient_merge_configs.setter
2046
    @is_strict_auto
2047
    def gradient_merge_configs(self, configs):
2048 2049 2050
        check_configs_key(
            self.strategy.gradient_merge_configs, configs, "gradient_configs"
        )
2051
        assign_configs_value(self.strategy.gradient_merge_configs, configs)
2052 2053

    @property
2054
    def lars(self):
2055
        """
2056

2057 2058
        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
2059 2060 2061 2062 2063
        [Large Batch Training of Convolutional Networks](https://arxiv.org/abs/1708.03888).

        Default Value: False

        Examples:
2064
            .. code-block:: python
1
123malin 已提交
2065

2066 2067 2068
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.lars = True # by default this is false
2069 2070

        """
2071
        return self.strategy.lars
2072

2073
    @lars.setter
2074
    @is_strict_auto
2075
    def lars(self, flag):
2076
        if isinstance(flag, bool):
2077
            self.strategy.lars = flag
2078
        else:
2079
            logger.warning("lars should have value of bool type")
2080

2081 2082
    @property
    def lars_configs(self):
2083
        """
2084

2085 2086 2087 2088 2089
        Set Lars training configurations.

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

        Examples:
2096
            .. code-block:: python
1
123malin 已提交
2097

2098 2099 2100 2101 2102 2103 2104 2105 2106
                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 已提交
2107

2108
        """
2109 2110 2111
        return get_msg_dict(self.strategy.lars_configs)

    @lars_configs.setter
2112
    @is_strict_auto
2113 2114 2115 2116
    def lars_configs(self, configs):
        check_configs_key(self.strategy.lars_configs, configs, "lars_configs")
        assign_configs_value(self.strategy.lars_configs, configs)

2117
    @property
2118
    def lamb(self):
2119
        """
2120

2121 2122 2123
        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
2124 2125 2126
        [Large Batch Optimization for Deep Learning: Training BERT in 76 minutes](https://arxiv.org/abs/1904.00962).

        Default Value: False
1
123malin 已提交
2127

2128
        Examples:
2129
            .. code-block:: python
1
123malin 已提交
2130

2131 2132 2133
                import paddle.distributed.fleet as fleet
                strategy = fleet.DistributedStrategy()
                strategy.lamb = True # by default this is false
2134 2135 2136

        """

2137
        return self.strategy.lamb
2138

2139
    @lamb.setter
2140
    @is_strict_auto
2141
    def lamb(self, flag):
2142
        if isinstance(flag, bool):
2143
            self.strategy.lamb = flag
2144
        else:
2145
            logger.warning("lamb should have value of bool type")
2146

2147 2148
    @property
    def lamb_configs(self):
2149
        """
2150

2151 2152 2153 2154 2155 2156 2157 2158
        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:
2159 2160 2161 2162 2163 2164 2165 2166 2167
            .. 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 已提交
2168

2169
        """
2170 2171 2172
        return get_msg_dict(self.strategy.lamb_configs)

    @lamb_configs.setter
2173
    @is_strict_auto
2174 2175 2176 2177
    def lamb_configs(self, configs):
        check_configs_key(self.strategy.lamb_configs, configs, "lamb_configs")
        assign_configs_value(self.strategy.lamb_configs, configs)

2178 2179
    @property
    def elastic(self):
2180
        """
2181

2182 2183
        Indicating whether we want to do current distributed training on clusters with elastic resources.
        Currently, this is configuration is not valid.
2184

2185
        """
2186 2187 2188
        return self.strategy.elastic

    @elastic.setter
2189
    @is_strict_auto
2190 2191 2192 2193
    def elastic(self, flag):
        if isinstance(flag, bool):
            self.strategy.elastic = flag
        else:
2194
            logger.warning("elastic should have value of bool type")
2195 2196 2197

    @property
    def auto(self):
2198
        """
2199

2200
        Indicating whether we are using auto-parallel configuration
2201
        This feature is currently an experimental feature. Currently,
2202 2203 2204 2205 2206 2207
        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:
2208
            .. code-block:: python
1
123malin 已提交
2209

2210 2211 2212
                import paddle
                paddle.enable_static()
                import paddle.distributed.fleet as fleet
2213

2214 2215 2216 2217
                strategy = fleet.DistributedStrategy()
                strategy.auto = True
                # if set other strategy at the same time, auto will not apply
                # strategy.amp = True
2218

2219 2220
                optimizer = paddle.optimizer.SGD(learning_rate=0.01)
                optimizer = fleet.distributed_optimizer(optimizer, strategy)
2221 2222

        """
2223 2224 2225 2226 2227 2228 2229
        return self.strategy.auto

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

2232 2233 2234
    @property
    def semi_auto(self):
        """
2235

2236
        Indicating whether we are using semi-auto parallel function
2237
        This feature is currently an experimental feature. Currently,
2238 2239 2240 2241 2242 2243
        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:
2244
            .. code-block:: python
2245

2246 2247 2248
                import paddle
                paddle.enable_static()
                import paddle.distributed.fleet as fleet
2249

2250 2251 2252 2253
                strategy = fleet.DistributedStrategy()
                strategy.semi_auto = True
                # if set other strategy at the same time, auto will not apply
                # strategy.amp = True
2254

2255 2256
                optimizer = paddle.optimizer.SGD(learning_rate=0.01)
                optimizer = fleet.distributed_optimizer(optimizer, strategy)
2257 2258 2259 2260 2261 2262 2263 2264 2265

        """
        return self.strategy.semi_auto

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

Z
zhaoyingli 已提交
2268 2269 2270
    @property
    def auto_search(self):
        """
2271

Z
zhaoyingli 已提交
2272 2273 2274
        Indicating whether we are using auto-search parallel function
        For details, please reference the following code example
        Default Value: False
2275

Z
zhaoyingli 已提交
2276
        Examples:
2277 2278 2279 2280 2281 2282 2283 2284 2285
            .. code-block:: python

                import paddle

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

Z
zhaoyingli 已提交
2286 2287 2288 2289 2290 2291 2292 2293
        """
        return self.strategy.auto_search

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

2296 2297 2298
    @property
    def split_data(self):
        """
2299

2300 2301
        Indicating whether we split the data. If True, we split the data.
        Default Value: True
2302

2303
        Examples:
2304 2305 2306 2307 2308 2309 2310 2311 2312
            .. code-block:: python

                import paddle

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

2313 2314 2315 2316 2317 2318 2319 2320
        """
        return self.strategy.split_data

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

2323 2324 2325
    @property
    def qat(self):
        """
2326

2327 2328
        Indicating whether we are using quantization training
        Default Value: False
2329

2330 2331 2332 2333 2334 2335 2336 2337
        """
        return self.strategy.qat

    @qat.setter
    def qat(self, flag):
        if isinstance(flag, bool):
            self.strategy.qat = flag
        else:
2338
            logger.warning("qat should have value of bool type")
2339 2340 2341 2342

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

2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
        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.

2354
            not_quant_pattern(list[str]): When the skip pattern is detected in an op's name scope,
2355 2356 2357 2358 2359
                the corresponding op will not be quantized.

            algo(str): Other quantization training algorithm.

        Exampless:
2360
            .. code-block:: python
2361

2362
                import paddle.distributed.fleet as fleet
2363

2364 2365 2366 2367 2368 2369 2370
                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']}
2371 2372 2373 2374 2375 2376 2377 2378 2379

        """
        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 已提交
2380 2381 2382
    @property
    def heter_ccl_mode(self):
        """
2383

K
kuizhiqing 已提交
2384 2385 2386 2387 2388 2389
        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:
2390
            .. code-block:: python
K
kuizhiqing 已提交
2391

2392 2393
                import paddle
                import paddle.distributed.fleet as fleet
K
kuizhiqing 已提交
2394

2395 2396
                strategy = fleet.DistributedStrategy()
                strategy.heter_ccl_mode = True
K
kuizhiqing 已提交
2397

2398 2399 2400
                # for initialize parallel env, only need to call
                paddle.distributed.init_parallel_env()
                # then the heterogenous context will be created.
K
kuizhiqing 已提交
2401 2402 2403 2404 2405 2406 2407 2408 2409

        """
        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:
2410
            logger.warning("heter_ccl_mode should have value of bool type")
K
kuizhiqing 已提交
2411

2412 2413
    @property
    def cudnn_exhaustive_search(self):
2414
        """
2415

2416 2417 2418 2419 2420 2421 2422
        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:
2423
            .. code-block:: python
1
123malin 已提交
2424

2425 2426 2427
                import paddle
                paddle.enable_static()
                import paddle.distributed.fleet as fleet
2428

2429 2430 2431 2432 2433
                strategy = fleet.DistributedStrategy()
                strategy.cudnn_exhaustive_search = False

                optimizer = paddle.optimizer.SGD(learning_rate=0.01)
                optimizer = fleet.distributed_optimizer(optimizer, strategy)
2434 2435

        """
2436 2437 2438
        return self.strategy.cudnn_exhaustive_search

    @cudnn_exhaustive_search.setter
2439
    @is_strict_auto
2440 2441 2442 2443
    def cudnn_exhaustive_search(self, flag):
        if isinstance(flag, bool):
            self.strategy.cudnn_exhaustive_search = flag
        else:
2444 2445
            logger.warning(
                "cudnn_exhaustive_search should have value of bool type"
2446 2447 2448 2449
            )

    @property
    def conv_workspace_size_limit(self):
2450
        """
2451

2452
        The workspace limit size in MB unit for choosing cuDNN convolution algorithms.
C
co63oc 已提交
2453
        The inner function of cuDNN obtain the fastest suited algorithm that fits within this memory limit.
2454 2455 2456 2457 2458
        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:
2459
            .. code-block:: python
1
123malin 已提交
2460

2461 2462 2463
                import paddle
                paddle.enable_static()
                import paddle.distributed.fleet as fleet
2464

2465 2466
                strategy = fleet.DistributedStrategy()
                strategy.conv_workspace_size_limit = 1024
2467

2468 2469
                optimizer = paddle.optimizer.SGD(learning_rate=0.01)
                optimizer = fleet.distributed_optimizer(optimizer, strategy)
1
123malin 已提交
2470

2471
        """
2472 2473 2474
        return self.strategy.conv_workspace_size_limit

    @conv_workspace_size_limit.setter
2475
    @is_strict_auto
2476 2477 2478 2479
    def conv_workspace_size_limit(self, value):
        if isinstance(value, int):
            self.strategy.conv_workspace_size_limit = value
        else:
2480 2481
            logger.warning(
                "conv_workspace_size_limit should have value of int type"
2482 2483 2484 2485
            )

    @property
    def cudnn_batchnorm_spatial_persistent(self):
2486
        """
2487

2488 2489 2490 2491 2492
        Indicates whether to use the mode CUDNN_BATCHNORM_SPATIAL_PERSISTENT function in batchnorm.
        This is only useful in cudnn.
        Default Value: True

        Examples:
2493
            .. code-block:: python
1
123malin 已提交
2494

2495 2496 2497
                import paddle
                paddle.enable_static()
                import paddle.distributed.fleet as fleet
2498

2499 2500
                strategy = fleet.DistributedStrategy()
                strategy.cudnn_batchnorm_spatial_persistent = True
2501

2502 2503
                optimizer = paddle.optimizer.SGD(learning_rate=0.01)
                optimizer = fleet.distributed_optimizer(optimizer, strategy)
2504 2505

        """
2506 2507 2508
        return self.strategy.cudnn_batchnorm_spatial_persistent

    @cudnn_batchnorm_spatial_persistent.setter
2509
    @is_strict_auto
2510 2511 2512 2513
    def cudnn_batchnorm_spatial_persistent(self, flag):
        if isinstance(flag, bool):
            self.strategy.cudnn_batchnorm_spatial_persistent = flag
        else:
2514 2515
            logger.warning(
                "cudnn_batchnorm_spatial_persistent should have value of bool type"
2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537
            )

    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):
2538 2539
            if _global_flags().is_public(key):
                _global_flags()[key] = values[i]
2540

2541 2542 2543 2544 2545 2546
    def _is_strict_auto(self):
        global non_auto_func_called
        if self.strategy.auto and non_auto_func_called:
            return True
        return False

2547
    def __repr__(self):
2548 2549 2550 2551 2552 2553
        spacing = 2
        max_k = 38
        max_v = 38

        length = max_k + max_v + spacing

2554
        h1_format = "    " + f"|{{:^{length}s}}|\n"
2555
        h2_format = "    " + "|{{:>{}s}}{}{{:^{}s}}|\n".format(
2556 2557
            max_k, " " * spacing, max_v
        )
2558 2559 2560 2561 2562 2563 2564 2565 2566

        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 已提交
2567
        fields = self.strategy.DESCRIPTOR.fields
2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581
        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(
2582
                                f"{f.name}=True <-> {f.name}_configs"
2583
                            )
2584
                            draws += line + "\n"
2585 2586 2587
                            my_configs = getattr(
                                self.strategy, f.name + "_configs"
                            )
2588
                            config_fields = my_configs.DESCRIPTOR.fields
R
risemeup1 已提交
2589 2590 2591 2592 2593 2594
                            protobuf_version = google.protobuf.__version__
                            if protobuf_version >= "4.21.0":
                                RepeatedScalarContainer = (
                                    google._upb._message.RepeatedScalarContainer
                                )
                            else:
R
risemeup1 已提交
2595 2596
                                from google.protobuf.pyext import _message

R
risemeup1 已提交
2597
                                RepeatedScalarContainer = (
R
risemeup1 已提交
2598
                                    _message.RepeatedScalarContainer
R
risemeup1 已提交
2599
                                )
2600 2601
                            for ff in config_fields:
                                if isinstance(
2602
                                    getattr(my_configs, ff.name),
R
risemeup1 已提交
2603
                                    RepeatedScalarContainer,
2604
                                ):
2605 2606 2607
                                    values = getattr(my_configs, ff.name)
                                    for i, v in enumerate(values):
                                        if i == 0:
2608
                                            draws += h2_format.format(
2609 2610
                                                ff.name, str(v)
                                            )
2611
                                        else:
2612
                                            draws += h2_format.format(
2613 2614
                                                "", str(v)
                                            )
2615 2616 2617
                                else:
                                    draws += h2_format.format(
                                        ff.name,
2618 2619
                                        str(getattr(my_configs, ff.name)),
                                    )
2620 2621
                    else:
                        env_draws += h2_format.format(
2622 2623
                            f.name, str(getattr(self.strategy, f.name))
                        )
2624 2625
                else:
                    env_draws += h2_format.format(
2626 2627 2628 2629 2630 2631 2632 2633 2634
                        f.name, str(getattr(self.strategy, f.name))
                    )

        result_res = (
            draws
            + border
            + "\n"
            + h1_format.format("Environment Flags, Communication Flags")
        )
2635 2636 2637 2638 2639 2640 2641
        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 已提交
2642
        for f in fields:
2643
            build_strategy_str += h2_format.format(
2644 2645
                f.name, str(getattr(self.strategy.build_strategy, f.name))
            )
2646 2647 2648 2649 2650 2651 2652 2653
        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(
2654 2655
                f.name, str(getattr(self.strategy.execution_strategy, f.name))
            )
2656 2657 2658 2659
        execution_strategy_str += border + "\n"

        result_res += build_strategy_str + execution_strategy_str
        return result_res