distributed_strategy.py 52.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15
import paddle
16
from paddle.distributed.fleet.proto import distributed_strategy_pb2
17
from paddle.fluid.framework import Variable, set_flags, core
18
from paddle.fluid.wrapped_decorator import wrap_decorator
19
import google.protobuf.text_format
20
import google.protobuf
21

22 23
__all__ = ["DistributedStrategy"]

24 25 26 27 28 29 30 31 32 33 34 35 36 37
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__)

38

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


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


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


67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
class DistributedJobInfo(object):
    """
    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


class DistributedStrategy(object):
105 106
    __lock_attr = False

107
    def __init__(self):
108 109 110 111 112
        """
        DistributedStrategy is the main configuration entry for distributed training of Paddle.
        All of the distributed training configurations can be configured in DistributedStrategy,
        such as automatic mixed precision (AMP), Layer-wise Adaptive Rate Scaling (LARS), 
        asynchronous update parameter server(ASGD), etc.
1
123malin 已提交
113

114 115 116 117 118 119
        DistributedStrategy can be serialized into protobuf file or deserialized from protobuf file

        Users who run local training usually configure BuildStrategy and ExecutionStrategy, and 
        DistributedStrategy supports configurations from BuildStrategy and ExecutionStrategy

        """
120
        self.strategy = distributed_strategy_pb2.DistributedStrategy()
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

        # Set the default values of the following flags to the ones set by users
        key = 'FLAGS_cudnn_batchnorm_spatial_persistent'
        if core.globals().is_public(key):
            self.strategy.cudnn_batchnorm_spatial_persistent = bool(
                core.globals()[key])
        key = 'FLAGS_conv_workspace_size_limit'
        if core.globals().is_public(key):
            self.strategy.conv_workspace_size_limit = int(core.globals()[key])
        key = 'FLAGS_cudnn_exhaustive_search'
        if core.globals().is_public(key):
            self.strategy.cudnn_exhaustive_search = bool(core.globals()[key])
        key = 'FLAGS_sync_nccl_allreduce'
        if core.globals().is_public(key):
            self.strategy.sync_nccl_allreduce = bool(core.globals()[key])

137 138 139 140 141 142 143
        self.__lock_attr = True

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

145
    def save_to_prototxt(self, output):
146 147 148 149
        """
        Serialize current DistributedStrategy to string and save to output file

        Examples:
1
123malin 已提交
150

151
          .. code-block:: python
1
123malin 已提交
152

153
            import paddle.distributed.fleet as fleet
154 155 156
            strategy = fleet.DistributedStrategy()
            strategy.dgc = True
            strategy.recompute = True
M
mapingshuo 已提交
157
            strategy.recompute_configs = {"checkpoints": ["x"]}
158 159
            strategy.save_to_prototxt("dist_strategy.prototxt")
        """
160 161 162 163
        with open(output, "w") as fout:
            fout.write(str(self.strategy))

    def load_from_prototxt(self, pb_file):
164 165 166 167
        """
        Load from prototxt file for DistributedStrategy initialization

        Examples:
1
123malin 已提交
168

169 170
          .. code-block:: python

171
            import paddle.distributed.fleet as fleet
172
            strategy = fleet.DistributedStrategy()
M
mapingshuo 已提交
173
            strategy.load_from_prototxt("dist_strategy.prototxt")
174 175 176 177 178 179 180 181 182 183 184
        """
        with open(pb_file, 'r') as f:
            self.strategy = google.protobuf.text_format.Merge(
                str(f.read()), self.strategy)

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

        Examples:
1
123malin 已提交
185

186 187
          .. code-block:: python

M
mapingshuo 已提交
188
            import paddle
1
123malin 已提交
189
            exe_strategy = paddle.static.ExecutionStrategy()
190 191 192 193
            exe_strategy.num_threads = 10
            exe_strategy.num_iteration_per_drop_scope = 10
            exe_strategy.num_iteration_per_run = 10

194
            strategy = paddle.distributed.fleet.DistributedStrategy()
195 196 197 198 199 200 201 202 203 204
            strategy.execution_strategy = exe_strategy
        """
        execution_strategy = paddle.fluid.ExecutionStrategy()
        fields = self.strategy.execution_strategy.DESCRIPTOR.fields
        for f in fields:
            setattr(execution_strategy, f.name,
                    getattr(self.strategy.execution_strategy, f.name))
        return execution_strategy

    @execution_strategy.setter
205
    @is_strict_auto
206 207 208 209 210 211 212 213 214 215 216 217 218 219
    def execution_strategy(self, strategy):
        fields = self.strategy.execution_strategy.DESCRIPTOR.fields
        for f in fields:
            setattr(self.strategy.execution_strategy, f.name,
                    getattr(strategy, f.name))

    @property
    def build_strategy(self):
        """
        Configure BuildStrategy for DistributedStrategy
        Note that the properties of BuildStrategy are valid in DistributedStrategy
        only if the property is non-distributed strategy.

        Examples:
1
123malin 已提交
220

221 222
          .. code-block:: python

M
mapingshuo 已提交
223
            import paddle
1
123malin 已提交
224
            build_strategy = paddle.static.BuildStrategy()
225 226 227 228 229 230 231 232
            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
1
123malin 已提交
233

234
            strategy = paddle.distributed.fleet.DistributedStrategy()
235 236 237 238 239 240 241 242 243 244 245
            strategy.build_strategy = build_strategy
        """

        build_strategy = paddle.fluid.BuildStrategy()
        fields = self.strategy.build_strategy.DESCRIPTOR.fields
        for f in fields:
            setattr(build_strategy, f.name,
                    getattr(self.strategy.build_strategy, f.name))
        return build_strategy

    @build_strategy.setter
246
    @is_strict_auto
247 248 249 250 251 252 253 254 255 256 257
    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
                setattr(self.strategy.build_strategy, f.name,
                        getattr(strategy, f.name))
            elif f.label == 3:  # repeated field
                getattr(self.strategy.build_strategy,
                        f.name).extend(getattr(strategy, f.name))

    @property
D
Dong Daxiang 已提交
258
    def a_sync(self):
259 260 261 262 263 264 265
        """
        Indicating whether we are using asynchronous stocastic gradient descent updates
        for training. This property is valid when we are using parameter server training, 
        which is implied by setting approperate RoleMaker
        Default value: True

        Examples:
1
123malin 已提交
266

267 268
          .. code-block:: python

269
            import paddle.distributed.fleet as fleet
270 271 272 273
            role_maker = fleet.PaddleCloudRoleMaker()
            fleet.init(role_maker)

            strategy = fleet.DistributedStrategy()
D
Dong Daxiang 已提交
274
            strategy.a_sync = True  # by default this is True
1
123malin 已提交
275

276 277 278
            # code block for defining loss and local optimizer
            # sgd = fleet.distributed_optimizer(optimizer, strategy)
        """
D
Dong Daxiang 已提交
279
        return self.strategy.a_sync
280

D
Dong Daxiang 已提交
281
    @a_sync.setter
282
    @is_strict_auto
D
Dong Daxiang 已提交
283
    def a_sync(self, flag):
284
        if isinstance(flag, bool):
D
Dong Daxiang 已提交
285
            self.strategy.a_sync = flag
286
            self.a_sync_configs = {"k_steps": 0}
287
        else:
288 289 290
            raise ValueError(
                "The type of `flag` is invalid, expected type is bool, but received %s".
                format(type(flag)))
291 292

    @property
D
Dong Daxiang 已提交
293
    def a_sync_configs(self):
294
        """
D
Dong Daxiang 已提交
295
        Set a_sync update configurations. In general, asynchronous parameter server
296 297
        training has serveral configurable settings that can be configured through
        a dict.
298

299
        **Notes**:
M
mapingshuo 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312
            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
313

314
        Examples:
1
123malin 已提交
315

316
          .. code-block:: python
317

318
            import paddle.distributed.fleet as fleet
319 320
            role_maker = fleet.PaddleCloudRoleMaker()
            fleet.init(role_maker)
321

322
            strategy = fleet.DistributedStrategy()
D
Dong Daxiang 已提交
323
            strategy.a_sync = True  # by default this is True
M
mapingshuo 已提交
324
            configs = {"k_steps": 1024, "send_queue_size": 32}
D
Dong Daxiang 已提交
325
            strategy.a_sync_configs = configs
326

327 328
            # code block for defining loss and local optimizer
            # sgd = fleet.distributed_optimizer(optimizer, strategy)
M
mapingshuo 已提交
329

330
        """
D
Dong Daxiang 已提交
331
        return get_msg_dict(self.strategy.a_sync_configs)
332

D
Dong Daxiang 已提交
333
    @a_sync_configs.setter
334
    @is_strict_auto
D
Dong Daxiang 已提交
335 336 337 338
    def a_sync_configs(self, configs):
        check_configs_key(self.strategy.a_sync_configs, configs,
                          "a_sync_configs")
        assign_configs_value(self.strategy.a_sync_configs, configs)
339

340
    @property
341 342 343 344
    def amp(self):
        """
        Indicating whether we are using automatic mixed precision training
        Default Value: False
345

346
        Examples:
1
123malin 已提交
347

348
          .. code-block:: python
349

350
            import paddle.distributed.fleet as fleet
351 352
            strategy = fleet.DistributedStrategy()
            strategy.amp = True # by default this is false
353

354 355
        """
        return self.strategy.amp
356

357
    @amp.setter
358
    @is_strict_auto
359
    def amp(self, flag):
360
        if isinstance(flag, bool):
361
            self.strategy.amp = flag
362
        else:
363
            print("WARNING: amp should have value of bool type")
364 365

    @property
366
    def amp_configs(self):
367 368 369 370 371
        """
        Set automatic mixed precision training configurations. In general, amp has serveral configurable
        settings that can be configured through a dict.

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

388 389 390 391 392 393 394 395
            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:
1
123malin 已提交
396

397 398 399 400 401 402 403 404
          .. code-block:: python

            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.amp = True
            strategy.amp_configs = {
                "init_loss_scaling": 32768,
                "custom_white_list": ['conv2d']}
405 406 407 408 409 410 411 412 413 414 415 416 417

        Examples 2:

          .. 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
            }
418
        """
419
        return get_msg_dict(self.strategy.amp_configs)
420

421
    @amp_configs.setter
422
    @is_strict_auto
423 424 425
    def amp_configs(self, configs):
        check_configs_key(self.strategy.amp_configs, configs, "amp_configs")
        assign_configs_value(self.strategy.amp_configs, configs)
426 427

    @property
428 429 430 431 432 433
    def recompute(self):
        """
        Indicating whether we are using forward recomputation for memory optimization
        Default value: False

        Examples:
1
123malin 已提交
434

435 436
          .. code-block:: python

437
            import paddle.distributed.fleet as fleet
438 439 440 441 442 443
            strategy = fleet.DistributedStrategy()
            strategy.recompute = True
            # suppose x and y are names of checkpoint tensors for recomputation
            strategy.recompute_configs = {"checkpoints": ["x", "y"]}
        """
        return self.strategy.recompute
444

445 446
    @property
    def sync_nccl_allreduce(self):
447 448 449 450 451
        """
        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:
1
123malin 已提交
452

453 454 455 456 457 458
          .. code-block:: python

            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.sync_nccl_allreduce = True
        """
459 460 461
        return self.strategy.sync_nccl_allreduce

    @sync_nccl_allreduce.setter
462
    @is_strict_auto
463 464 465 466
    def sync_nccl_allreduce(self, flag):
        if isinstance(flag, bool):
            self.strategy.sync_nccl_allreduce = flag
        else:
467
            print("WARNING: sync_nccl_allreduce should have value of bool type")
468

469
    @property
470
    def use_hierarchical_allreduce(self):
471 472 473 474 475 476
        """
        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:
1
123malin 已提交
477

478 479 480 481 482 483
          .. code-block:: python

            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.use_hierarchical_allreduce = True
        """
484
        return self.strategy.use_hierarchical_allreduce
485

486
    @use_hierarchical_allreduce.setter
487
    @is_strict_auto
488
    def use_hierarchical_allreduce(self, flag):
489
        if isinstance(flag, bool):
490
            self.strategy.use_hierarchical_allreduce = flag
491 492
        else:
            print(
493
                "WARNING: use_hierarchical_allreduce should have value of bool type"
494 495 496
            )

    @property
497
    def hierarchical_allreduce_inter_nranks(self):
498 499 500 501 502
        """
        Number of ranks for low level node groups in hierarchical allreduce
        Default value: number of GPU cards on each single GPU machine

        Example:
1
123malin 已提交
503

504 505 506 507 508 509
          .. code-block:: python

            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.hierarchical_allreduce_inter_nranks = 8
        """
510
        return self.strategy.hierarchical_allreduce_inter_nranks
511

512
    @hierarchical_allreduce_inter_nranks.setter
513
    @is_strict_auto
514 515 516
    def hierarchical_allreduce_inter_nranks(self, value):
        if isinstance(value, int):
            self.strategy.hierarchical_allreduce_inter_nranks = value
517 518
        else:
            print(
519
                "WARNING: hierarchical_allreduce_inter_nranks should have value of int type"
520 521
            )

522
    @property
523
    def sync_batch_norm(self):
524 525
        """
        Indicating whether we are using sync_batch_norm to do synchronous batch normalization among all training nodes.
1
123malin 已提交
526

527 528 529
        Default value: False

        Examples:
1
123malin 已提交
530

531 532 533 534 535 536 537
          .. code-block:: python

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

538
        return self.strategy.sync_batch_norm
539

540
    @sync_batch_norm.setter
541
    @is_strict_auto
542
    def sync_batch_norm(self, flag):
543
        if isinstance(flag, bool):
544
            self.strategy.sync_batch_norm = flag
545
        else:
546
            print("WARNING: sync_batch_norm should have value of bool type")
547 548 549

    @property
    def fuse_all_reduce_ops(self):
550 551 552 553 554
        """
        Indicating whether we are using fuse_all_reduce_ops for gradient fusion during backward phase of training
        Default value: True

        Examples:
1
123malin 已提交
555

556 557 558 559 560 561
          .. code-block:: python

            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.fuse_all_reduce_ops = False
        """
562 563 564
        return self.strategy.fuse_all_reduce_ops

    @fuse_all_reduce_ops.setter
565
    @is_strict_auto
566 567 568 569 570 571
    def fuse_all_reduce_ops(self, flag):
        if isinstance(flag, bool):
            self.strategy.fuse_all_reduce_ops = flag
        else:
            print("WARNING: fuse_all_reduce_ops should have value of bool type")

572 573
    @property
    def fuse_grad_size_in_MB(self):
574 575 576 577 578 579
        """
        Specifying the size of gradient to fuse in Mega-Bytes

        Default value: 32

        Examples:
1
123malin 已提交
580

581
          .. code-block:: python
1
123malin 已提交
582

583 584 585 586
            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.fuse_grad_size_in_MB = 50
        """
587 588 589
        return self.strategy.fuse_grad_size_in_MB

    @fuse_grad_size_in_MB.setter
590
    @is_strict_auto
591 592 593 594 595 596
    def fuse_grad_size_in_MB(self, value):
        if isinstance(value, int):
            self.strategy.fuse_grad_size_in_MB = value
        else:
            print("WARNING: fuse_grad_size_in_MB should have value of int type")

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
    @property
    def last_comm_group_size_MB(self):
        """
        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. 

        Default value: 1

        Examples:
          .. code-block:: python
        
            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.last_comm_group_size_MB = 2
        """
        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")

623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
    @property
    def find_unused_parameters(self):
        """
        Indicating whether we are using find_unused_parameters to 
        find unused parameters in DataParallel.

        Default value: True

        Examples:

          .. code-block:: python

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

        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:
            print(
                "WARNING: find_unused_parameters should have value of bool type")

651 652 653 654 655
    @property
    def _fuse_grad_size_in_TFLOPS(self):
        return self.strategy.fuse_grad_size_in_TFLOPS

    @_fuse_grad_size_in_TFLOPS.setter
656
    @is_strict_auto
657 658 659 660 661 662 663 664
    def _fuse_grad_size_in_TFLOPS(self, value):
        if isinstance(value, float):
            self.strategy.fuse_grad_size_in_TFLOPS = value
        else:
            print(
                "WARNING: fuse_grad_size_in_TFLOPS should have value of float type"
            )

665
    @property
666
    def nccl_comm_num(self):
667 668 669 670 671 672
        """
        Specifying the number of NCCL communicator

        Default value: 1

        Examples:
1
123malin 已提交
673

674
          .. code-block:: python
1
123malin 已提交
675

676 677 678 679 680
            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.nccl_comm_num = 2
        """

681
        return self.strategy.nccl_comm_num
682

683
    @nccl_comm_num.setter
684
    @is_strict_auto
685
    def nccl_comm_num(self, value):
686
        if isinstance(value, int):
687
            self.strategy.nccl_comm_num = value
688
        else:
689
            print("WARNING: nccl_comm_num should have value of int type")
690

691
    @recompute.setter
692
    @is_strict_auto
693
    def recompute(self, flag):
694
        if isinstance(flag, bool):
695
            self.strategy.recompute = flag
696
        else:
697
            print("WARNING: recompute should have value of bool type")
698 699

    @property
700 701
    def recompute_configs(self):
        """
J
JZ-LIANG 已提交
702 703 704 705 706 707 708 709 710 711 712 713 714 715
        Set recompute configurations. 
        
        **Note**:
        checkpoints(list): list of string name of checkpoints. In general, the recompute
        strategy of current implementation should have some manually assign checkpoints.

        enable_offload(bool): enable recompute checkpoints offload feature. this feature 
        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
        specific here should be determined ("-1" is not allowed). 
716

717
        Examples:
1
123malin 已提交
718

719
          .. code-block:: python
1
123malin 已提交
720

721
            import paddle.distributed.fleet as fleet
722 723
            strategy = fleet.DistributedStrategy()
            strategy.recompute = True
J
JZ-LIANG 已提交
724 725 726 727
            strategy.recompute_configs = {
                "checkpoints": ["x", "y"],
                "enable_offload": True,
                "checkpoint_shape": [100, 512, 1024] }
728 729 730 731 732

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

    @recompute_configs.setter
733
    @is_strict_auto
734 735 736 737
    def recompute_configs(self, configs):
        check_configs_key(self.strategy.recompute_configs, configs,
                          "checkpoint_configs")
        assign_configs_value(self.strategy.recompute_configs, configs)
738

739 740 741 742
    @property
    def sharding(self):
        """
        Indicating whether we are using sharding Optimizer for memory
J
JZ-LIANG 已提交
743 744 745
        optimization. We implement the sharding optimizer following the ZeRO-DP 
        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.
746 747 748 749

        Default value: False

        Examples:
1
123malin 已提交
750

751
          .. code-block:: python
1
123malin 已提交
752

753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
            import paddle.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.sharding = True
        """
        return self.strategy.sharding

    @sharding.setter
    @is_strict_auto
    def sharding(self, flag):
        if isinstance(flag, bool):
            self.strategy.sharding = flag
        else:
            print("WARNING: sharding should have value of bool type")

    @property
    def sharding_configs(self):
        """
J
JZ-LIANG 已提交
770
        Set sharding configurations. 
771 772

        **Note**:
J
JZ-LIANG 已提交
773 774 775
            fuse_broadcast_MB(float): size of a fused group of broadcasted parameters. 
            This configuration will affect the communication speed in sharding training, 
            and should be an empirical value decided by your model size and network topology.
776

J
JZ-LIANG 已提交
777 778 779 780 781 782 783 784
            hybrid_dp(bool): enable hybrid data parallelism above the sharding parallelism. 
            you are supposed to have at least double the number of gpu you have in normal sharding 
            training to enable this feature.

            sharding_group_size(int): attribute of hybrid_dp. specific the the number of gpus within
            each sharding group; and therefore, the number of hybrid data parallelism ways will be equal
            to (global_size / sharding_group_size).

785
        Examples:
1
123malin 已提交
786

787
          .. code-block:: python
1
123malin 已提交
788

789 790 791
            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.sharding = True
J
JZ-LIANG 已提交
792 793 794 795
            strategy.sharding_configs = {
                "fuse_broadcast_MB": 32,
                "hybrid_dp": True,
                "sharding_group_size": 8}
796 797 798 799 800 801 802 803 804 805
        """
        return get_msg_dict(self.strategy.sharding_configs)

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

806
    @property
807 808 809 810 811 812 813 814
    def pipeline(self):
        """
        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:
1
123malin 已提交
815

816
          .. code-block:: python
1
123malin 已提交
817

818
            import paddle.distributed.fleet as fleet
819 820 821 822 823
            strategy = fleet.DistributedStrategy()
            strategy.pipeline = True

        """
        return self.strategy.pipeline
824

825
    @pipeline.setter
826
    @is_strict_auto
827
    def pipeline(self, flag):
828
        if isinstance(flag, bool):
829
            self.strategy.pipeline = flag
830
        else:
831
            print("WARNING: pipeline should have value of bool type")
832 833

    @property
834 835 836 837 838 839 840 841 842 843
    def pipeline_configs(self):
        """
        Set pipeline parallelism configurations. In pipeline parallelism,
        different parts of neural networks are running on different GPUS.
        There are Tensor queue buffer between each pair of neighborhood GPUS 
        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
        pipeline parallelism is to make the size of Tensor in Tensor queue smaller, 
        so that we will have a faster producer for downstream consumers.
844

845 846
        **Notes**:
            **Detailed arguments for pipeline_configs**
M
mapingshuo 已提交
847

848
            **micro_batch**: the number of small batches in each user defined batch
849

850
        Examples:
1
123malin 已提交
851

852
          .. code-block:: python
1
123malin 已提交
853

854
            import paddle.distributed.fleet as fleet
855 856 857
            strategy = fleet.DistributedStrategy()
            strategy.pipeline = True
            strategy.pipeline_configs = {"micro_batch": 12}
858

859
        """
860

861
        return get_msg_dict(self.strategy.pipeline_configs)
862

863
    @pipeline_configs.setter
864
    @is_strict_auto
865 866 867 868
    def pipeline_configs(self, configs):
        check_configs_key(self.strategy.pipeline_configs, configs,
                          "pipeline_configs")
        assign_configs_value(self.strategy.pipeline_configs, configs)
869 870

    @property
871
    def localsgd(self):
872
        """
M
mapingshuo 已提交
873 874 875
        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>`_.
876 877 878


        Examples:
1
123malin 已提交
879

880 881 882 883 884 885 886
          .. code-block:: python

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

        """
887
        return self.strategy.localsgd
888

889
    @localsgd.setter
890
    @is_strict_auto
891 892 893
    def localsgd(self, flag):
        if isinstance(flag, bool):
            self.strategy.localsgd = flag
894
        else:
895
            print("WARNING: localsgd should have value of bool type")
896 897

    @property
898
    def localsgd_configs(self):
899 900 901 902 903
        """
        Set LocalSGD training configurations. LocalSGD has a configurable
        setting that can be configured through a dict.

        **Notes**:
M
mapingshuo 已提交
904
            k_steps(int) The local steps for training before parameter synchronization. Default 1.
905
            begin_step(int) The step of begining training by localsgd. Default 1.
906 907

        Examples:
1
123malin 已提交
908

909 910 911 912 913
          .. code-block:: python

            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.localsgd = True
914 915
            strategy.localsgd_configs = {"k_steps": 4,
                                         "begin_step": 30}
916 917
        """

918
        return get_msg_dict(self.strategy.localsgd_configs)
919

920
    @localsgd_configs.setter
921
    @is_strict_auto
922 923 924 925
    def localsgd_configs(self, configs):
        check_configs_key(self.strategy.localsgd_configs, configs,
                          "localsgd_configs")
        assign_configs_value(self.strategy.localsgd_configs, configs)
926

927 928 929 930 931 932 933 934 935
    @property
    def adaptive_localsgd(self):
        """
        Indicating whether we are using Adaptive Local SGD training. Default Value: False
        For more details, please refer to `Adaptive Communication Strategies to Achieve 
        the Best Error-Runtime Trade-off in Local-Update SGD <https://arxiv.org/pdf/1810.08313.pdf>`_.


        Examples:
1
123malin 已提交
936

937 938 939 940 941 942 943
          .. code-block:: python

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

        """
944
        return self.strategy.adaptive_localsgd
945 946 947 948 949

    @adaptive_localsgd.setter
    @is_strict_auto
    def adaptive_localsgd(self, flag):
        if isinstance(flag, bool):
950
            self.strategy.adaptive_localsgd = flag
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
        else:
            print("WARNING: adaptive_localsgd should have value of bool type")

    @property
    def adaptive_localsgd_configs(self):
        """
        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.
            begin_step(int) The step of begining training by adaptive localsgd. Default 1.

        Examples:
1
123malin 已提交
967

968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
          .. code-block:: python

            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.adaptive_localsgd = True
            strategy.adaptive_localsgd_configs = {"init_k_steps": 1,
                                                  "begin_step": 30}
        """

        return get_msg_dict(self.strategy.adaptive_localsgd_configs)

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

986
    @property
987
    def dgc(self):
988 989 990 991 992 993 994
        """
        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:
1
123malin 已提交
995

996 997 998 999 1000 1001 1002
          .. code-block:: python

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

        """
1003
        return self.strategy.dgc
1004

1005
    @dgc.setter
1006
    @is_strict_auto
1007 1008 1009
    def dgc(self, flag):
        if isinstance(flag, bool):
            self.strategy.dgc = flag
1010
        else:
1011
            print("WARNING: dgc should have value of bool type")
1012 1013

    @property
1014
    def dgc_configs(self):
1015
        r"""
1016 1017 1018 1019
        Set Deep Gradient Compression training configurations. In general, dgc has serveral configurable
        settings that can be configured through a dict.

        **Notes**:
M
mapingshuo 已提交
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
            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.
1030 1031

        Examples:
1
123malin 已提交
1032

1033 1034 1035 1036 1037 1038 1039
          .. code-block:: python

            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.dgc = True
            strategy.dgc_configs = {"rampup_begin_step": 1252}
        """
1040
        return get_msg_dict(self.strategy.dgc_configs)
1041

1042
    @dgc_configs.setter
1043
    @is_strict_auto
1044 1045 1046
    def dgc_configs(self, configs):
        check_configs_key(self.strategy.dgc_configs, configs, "dgc_configs")
        assign_configs_value(self.strategy.dgc_configs, configs)
1047

1048 1049 1050 1051 1052 1053 1054
    @property
    def fp16_allreduce(self):
        """
        Indicating whether we are using fp16 gradient allreduce training
        Default Value: False

        Examples:
1
123malin 已提交
1055

1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
          .. code-block:: python

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

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

1072
    @property
1073
    def gradient_merge(self):
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
        """
        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:
1
123malin 已提交
1085

M
mapingshuo 已提交
1086 1087
          .. code-block:: python

1088
            import paddle.distributed.fleet as fleet
1089 1090 1091 1092
            strategy = fleet.DistributedStrategy()
            strategy.gradient_merge = True
            strategy.gradient_merge_configs = {"k_steps": 4, "avg": True}
        """
1093
        return self.strategy.gradient_merge
1094

1095
    @gradient_merge.setter
1096
    @is_strict_auto
1097
    def gradient_merge(self, flag):
1098
        if isinstance(flag, bool):
1099
            self.strategy.gradient_merge = flag
1100
        else:
1101 1102 1103 1104
            print("WARNING: gradient_merge should have value of bool type")

    @property
    def gradient_merge_configs(self):
1105 1106
        """
        the key-value configs of distribute_strategy
M
mapingshuo 已提交
1107 1108 1109 1110 1111 1112 1113

        **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:
1
123malin 已提交
1114

M
mapingshuo 已提交
1115 1116
          .. code-block:: python

1117
            import paddle.distributed.fleet as fleet
1118 1119 1120 1121
            strategy = fleet.DistributedStrategy()
            strategy.gradient_merge = True
            strategy.gradient_merge_configs = {"k_steps": 4, "avg": True}
        """
1122 1123 1124
        return get_msg_dict(self.strategy.gradient_merge_configs)

    @gradient_merge_configs.setter
1125
    @is_strict_auto
1126 1127 1128 1129
    def gradient_merge_configs(self, configs):
        check_configs_key(self.strategy.gradient_merge_configs, configs,
                          "gradient_configs")
        assign_configs_value(self.strategy.gradient_merge_configs, configs)
1130 1131

    @property
1132
    def lars(self):
1133 1134 1135 1136 1137 1138 1139 1140
        """
        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 
        [Large Batch Training of Convolutional Networks](https://arxiv.org/abs/1708.03888).

        Default Value: False

        Examples:
1
123malin 已提交
1141

1142 1143 1144 1145 1146 1147
          .. code-block:: python

            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.lars = True # by default this is false
        """
1148
        return self.strategy.lars
1149

1150
    @lars.setter
1151
    @is_strict_auto
1152
    def lars(self, flag):
1153
        if isinstance(flag, bool):
1154
            self.strategy.lars = flag
1155
        else:
1156
            print("WARNING: lars should have value of bool type")
1157

1158 1159
    @property
    def lars_configs(self):
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
        """
        Set Lars training configurations.

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

        Examples:
1
123malin 已提交
1172

1173
          .. code-block:: python
M
mapingshuo 已提交
1174

1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
            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']
                    }
        """
1185 1186 1187
        return get_msg_dict(self.strategy.lars_configs)

    @lars_configs.setter
1188
    @is_strict_auto
1189 1190 1191 1192
    def lars_configs(self, configs):
        check_configs_key(self.strategy.lars_configs, configs, "lars_configs")
        assign_configs_value(self.strategy.lars_configs, configs)

1193
    @property
1194
    def lamb(self):
1195 1196 1197 1198 1199 1200 1201
        """
        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 
        [Large Batch Optimization for Deep Learning: Training BERT in 76 minutes](https://arxiv.org/abs/1904.00962).

        Default Value: False
1
123malin 已提交
1202

1203
        Examples:
1
123malin 已提交
1204

1205 1206 1207 1208 1209 1210 1211
          .. code-block:: python

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

1212
        return self.strategy.lamb
1213

1214
    @lamb.setter
1215
    @is_strict_auto
1216
    def lamb(self, flag):
1217
        if isinstance(flag, bool):
1218
            self.strategy.lamb = flag
1219
        else:
1220
            print("WARNING: lamb should have value of bool type")
1221

1222 1223
    @property
    def lamb_configs(self):
1224 1225 1226 1227 1228 1229 1230 1231 1232
        """
        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:
1
123malin 已提交
1233

1234
          .. code-block:: python
M
mapingshuo 已提交
1235

1236 1237 1238 1239 1240 1241 1242 1243
            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.lamb = True
            strategy.lamb_configs = {
                    'lamb_weight_decay': 0.01,
                    'exclude_from_weight_decay': [],
                }
        """
1244 1245 1246
        return get_msg_dict(self.strategy.lamb_configs)

    @lamb_configs.setter
1247
    @is_strict_auto
1248 1249 1250 1251
    def lamb_configs(self, configs):
        check_configs_key(self.strategy.lamb_configs, configs, "lamb_configs")
        assign_configs_value(self.strategy.lamb_configs, configs)

1252 1253
    @property
    def elastic(self):
1254 1255 1256 1257
        """
        Indicating whether we want to do current distributed training on clusters with elastic resources.
        Currently, this is configuration is not valid.
        """
1258 1259 1260
        return self.strategy.elastic

    @elastic.setter
1261
    @is_strict_auto
1262 1263 1264 1265 1266 1267 1268 1269
    def elastic(self, flag):
        if isinstance(flag, bool):
            self.strategy.elastic = flag
        else:
            print("WARNING: elastic should have value of bool type")

    @property
    def auto(self):
1270 1271 1272 1273 1274 1275 1276 1277 1278
        """
        Indicating whether we are using auto-parallel configuration
        This feature is currently an experimental feature. Currently, 
        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:
1
123malin 已提交
1279

1280 1281 1282
          .. code-block:: python

            import paddle
1283
            paddle.enable_static()
1
123malin 已提交
1284
            import paddle.distributed.fleet as fleet
1285

1286 1287
            strategy = fleet.DistributedStrategy()
            strategy.auto = True
1288 1289
            # if set other strategy at the same time, auto will not apply
            # strategy.amp = True
1290 1291 1292 1293

            optimizer = paddle.optimizer.SGD(learning_rate=0.01)
            optimizer = fleet.distributed_optimizer(optimizer, strategy)
        """
1294 1295 1296 1297 1298 1299 1300 1301 1302
        return self.strategy.auto

    @auto.setter
    def auto(self, flag):
        if isinstance(flag, bool):
            self.strategy.auto = flag
        else:
            print("WARNING: auto should have value of bool type")

1303 1304
    @property
    def cudnn_exhaustive_search(self):
1305 1306 1307 1308 1309 1310 1311 1312
        """
        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:
1
123malin 已提交
1313

1314 1315
          .. code-block:: python

1
123malin 已提交
1316 1317
            import paddle
            paddle.enable_static()
1318 1319 1320 1321 1322 1323 1324
            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.cudnn_exhaustive_search = False

            optimizer = paddle.optimizer.SGD(learning_rate=0.01)
            optimizer = fleet.distributed_optimizer(optimizer, strategy)
        """
1325 1326 1327
        return self.strategy.cudnn_exhaustive_search

    @cudnn_exhaustive_search.setter
1328
    @is_strict_auto
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
    def cudnn_exhaustive_search(self, flag):
        if isinstance(flag, bool):
            self.strategy.cudnn_exhaustive_search = flag
        else:
            print(
                "WARNING: cudnn_exhaustive_search should have value of bool type"
            )

    @property
    def conv_workspace_size_limit(self):
1339 1340 1341 1342 1343 1344 1345 1346
        """
        The workspace limit size in MB unit for choosing cuDNN convolution algorithms.
        The inner funciton of cuDNN obtain the fastest suited algorithm that fits within this memory limit.
        Usually, large workspace size may lead to choose faster algorithms,
        but significant increasing memory workspace. Users need to trade-off between memory and speed.
        Default Value: 4000

        Examples:
1
123malin 已提交
1347

1348 1349
          .. code-block:: python

1
123malin 已提交
1350 1351
            import paddle
            paddle.enable_static()
1352 1353 1354 1355 1356 1357
            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.conv_workspace_size_limit = 1024

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

1359
        """
1360 1361 1362
        return self.strategy.conv_workspace_size_limit

    @conv_workspace_size_limit.setter
1363
    @is_strict_auto
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
    def conv_workspace_size_limit(self, value):
        if isinstance(value, int):
            self.strategy.conv_workspace_size_limit = value
        else:
            print(
                "WARNING: conv_workspace_size_limit should have value of int type"
            )

    @property
    def cudnn_batchnorm_spatial_persistent(self):
1374 1375 1376 1377 1378 1379
        """
        Indicates whether to use the mode CUDNN_BATCHNORM_SPATIAL_PERSISTENT function in batchnorm.
        This is only useful in cudnn.
        Default Value: True

        Examples:
1
123malin 已提交
1380

1381 1382
          .. code-block:: python

1
123malin 已提交
1383 1384
            import paddle
            paddle.enable_static()
1385 1386 1387 1388 1389 1390 1391 1392
            import paddle.distributed.fleet as fleet
            strategy = fleet.DistributedStrategy()
            strategy.cudnn_batchnorm_spatial_persistent = True

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

        """
1393 1394 1395
        return self.strategy.cudnn_batchnorm_spatial_persistent

    @cudnn_batchnorm_spatial_persistent.setter
1396
    @is_strict_auto
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
    def cudnn_batchnorm_spatial_persistent(self, flag):
        if isinstance(flag, bool):
            self.strategy.cudnn_batchnorm_spatial_persistent = flag
        else:
            print(
                "WARNING: cudnn_batchnorm_spatial_persistent should have value of bool type"
            )

    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):
            if core.globals().is_public(key):
                core.globals()[key] = values[i]

1428 1429 1430 1431 1432 1433
    def _is_strict_auto(self):
        global non_auto_func_called
        if self.strategy.auto and non_auto_func_called:
            return True
        return False

1434
    def __repr__(self):
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
        spacing = 2
        max_k = 38
        max_v = 38

        length = max_k + max_v + spacing

        h1_format = "    " + "|{{:^{}s}}|\n".format(length)
        h2_format = "    " + "|{{:>{}s}}{}{{:^{}s}}|\n".format(max_k, " " *
                                                               spacing, max_v)

        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 已提交
1453
        fields = self.strategy.DESCRIPTOR.fields
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
        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(
D
Dong Daxiang 已提交
1468
                                "{}=True <-> {}_configs".format(f.name, f.name))
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
                            draws += line + "\n"
                            my_configs = getattr(self.strategy,
                                                 f.name + "_configs")
                            config_fields = my_configs.DESCRIPTOR.fields
                            for ff in config_fields:
                                if isinstance(
                                        getattr(my_configs, ff.name),
                                        google.protobuf.pyext._message.
                                        RepeatedScalarContainer):
                                    values = getattr(my_configs, ff.name)
                                    for i, v in enumerate(values):
                                        if i == 0:
                                            draws += h2_format.format(ff.name,
                                                                      str(v))
                                        else:
                                            draws += h2_format.format("",
                                                                      str(v))
                                else:
                                    draws += h2_format.format(
                                        ff.name,
                                        str(getattr(my_configs, ff.name)))
                    else:
                        env_draws += h2_format.format(
                            f.name, str(getattr(self.strategy, f.name)))
                else:
                    env_draws += h2_format.format(
                        f.name, str(getattr(self.strategy, f.name)))

        result_res = draws + border + "\n" + h1_format.format(
            "Environment Flags, Communication Flags")
        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 已提交
1506
        for f in fields:
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
            build_strategy_str += h2_format.format(
                f.name, str(getattr(self.strategy.build_strategy, f.name)))
        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(
                f.name, str(getattr(self.strategy.execution_strategy, f.name)))
        execution_strategy_str += border + "\n"

        result_res += build_strategy_str + execution_strategy_str
        return result_res