parallelizer_v2.py 13.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   Copyright (c) 2022 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.

import copy
16 17
import time
import logging
18 19 20

from paddle.fluid import program_guard
from paddle.fluid.backward import append_backward
21
from paddle.fluid.framework import unique_name
22 23 24 25
from paddle.distributed.passes import new_pass

from .reshard import Resharder
from .partitioner import Partitioner
26 27 28
from .utils import set_grad_var_shape
from .process_group import get_world_process_group
from ..utils.log_utils import get_logger
29 30 31 32 33 34 35


class Parallelizer:
    def __init__(self, mode, completer, dist_context):
        self._mode = mode
        self._completer = completer
        self._dist_context = dist_context
36
        assert self._dist_context._is_initialized
37 38
        self._pass_context = self._dist_context.pass_context
        self._strategy = self._dist_context.strategy
39
        self._logger = get_logger(logging.INFO)
40 41 42 43 44

    def parallel_all(self):
        world_process_group = get_world_process_group()
        all_ranks = world_process_group.ranks
        for rank in all_ranks:
45
            # self._dist_context._backup(serial=True, dist=True)
46
            self.parallel(rank)
47
            # self._dist_context._restore(serial=True, dist=True)
48 49 50 51 52 53 54

    def parallel(self, rank):
        serial_main_program = self._dist_context.serial_main_program
        serial_startup_program = self._dist_context.serial_startup_program
        serial_optimizer = self._dist_context.serial_optimizer
        if self._mode == "train" and serial_optimizer:
            # Generate backward
55
            serial_loss = self._dist_context.serial_loss
56 57 58
            params_grads = self._generate_backward(
                serial_main_program, serial_startup_program, serial_loss
            )
59
            # Apply pre optimization passes
60
            time0 = time.time()
61 62 63 64 65 66 67 68 69 70 71
            (
                serial_main_program,
                serial_startup_program,
                params_grads,
            ) = self._apply_pre_optimization(
                serial_main_program,
                serial_startup_program,
                serial_loss,
                serial_optimizer,
                params_grads,
            )
72
            self._logger.debug(
73 74 75 76
                "within parallel apply_pre_optimization time: {}, mode {}".format(
                    time.time() - time0, self._mode
                )
            )
77
            # Do logical partition
78
            time0 = time.time()
79
            partitioner = Partitioner(self._dist_context, rank)
80 81 82 83 84 85 86
            (
                dist_main_prog,
                dist_startup_prog,
                dist_params_grads,
            ) = partitioner.partition(
                serial_main_program, serial_startup_program, params_grads
            )
87
            self._logger.debug(
88
                "within parallel partitioner time: {}, mode {}".format(
89 90 91
                    time.time() - time0, self._mode
                )
            )
92
            # Generate optimizer
93
            time0 = time.time()
94 95 96 97 98 99
            self._generate_optimizer(
                dist_main_prog,
                dist_startup_prog,
                serial_optimizer,
                dist_params_grads,
            )
100
            self._logger.debug(
101
                "within parallel optimizer time: {}, mode {}".format(
102 103 104
                    time.time() - time0, self._mode
                )
            )
105
            # Do reshard process
106
            time0 = time.time()
107
            set_grad_var_shape(dist_main_prog, self._dist_context)
108 109 110 111 112 113 114
            resharder = Resharder(
                dist_main_prog,
                dist_startup_prog,
                rank,
                self._dist_context,
                dist_params_grads,
            )
115
            resharder.reshard()
116
            self._logger.debug(
117
                "within parallel reshard time: {}, mode {}".format(
118 119 120
                    time.time() - time0, self._mode
                )
            )
121
            # Apply post optimization passes
122
            time0 = time.time()
123 124 125
            self._apply_post_optimization(
                dist_main_prog, dist_startup_prog, rank, dist_params_grads
            )
126
            self._logger.debug(
127 128 129 130
                "within parallel apply_post_optimization time: {}, mode {}".format(
                    time.time() - time0, self._mode
                )
            )
131 132
        else:
            # Apply pre optimization passes
133
            time0 = time.time()
134 135 136
            self._apply_pre_optimization(
                serial_main_program, serial_startup_program, None, None, None
            )
137
            self._logger.debug(
138 139 140 141
                "within parallel apply_pre_optimization time: {}, mode {}".format(
                    time.time() - time0, self._mode
                )
            )
142
            # Do logical partition
143
            time0 = time.time()
144
            partitioner = Partitioner(self._dist_context, rank)
145 146 147 148 149 150 151
            (
                dist_main_prog,
                dist_startup_prog,
                dist_params_grads,
            ) = partitioner.partition(
                serial_main_program, serial_startup_program, []
            )
152
            # Do reshard process
153
            self._logger.debug(
154
                "within parallel partitioner time: {}, mode {}".format(
155 156 157
                    time.time() - time0, self._mode
                )
            )
158
            time0 = time.time()
159 160 161 162 163 164 165 166
            resharder = Resharder(
                dist_main_prog,
                dist_startup_prog,
                rank,
                self._dist_context,
                [],
                1,
            )
167
            resharder.reshard()
168
            self._logger.debug(
169
                "within parallel reshard time: {}, mode {}".format(
170 171 172 173 174 175 176 177 178 179 180 181 182
                    time.time() - time0, self._mode
                )
            )
            # Apply post optimization passes
            time0 = time.time()
            self._apply_post_optimization(
                dist_main_prog, dist_startup_prog, rank, dist_params_grads
            )
            self._logger.debug(
                "within parallel apply_post_optimization time: {}, mode {}".format(
                    time.time() - time0, self._mode
                )
            )
183 184
        # Clone program for test
        if self._mode != 'train':
185
            pipeline_opt = dist_main_prog._pipeline_opt
186 187
            dist_main_prog = dist_main_prog.clone(for_test=True)
            dist_startup_prog = dist_startup_prog.clone(for_test=True)
188
            dist_main_prog._pipeline_opt = pipeline_opt
189 190 191 192 193 194 195 196

        # Store the distributed programs for further usages
        self._dist_context.dist_main_programs[rank] = dist_main_prog
        self._dist_context.dist_startup_programs[rank] = dist_startup_prog

    def _generate_backward(self, main_program, startup_program, loss):
        with program_guard(main_program, startup_program):
            params_grads = append_backward(
197 198
                loss, distop_context=self._dist_context.dist_op_context
            )
199 200 201 202
        self._completer.complete_backward_annotation(main_program)
        self._dist_context.block_state.parse_backward_blocks(main_program)
        return params_grads

203 204 205
    def _generate_optimizer(
        self, main_program, startup_program, optimizer, params_grads
    ):
206 207
        # NOTE: `apply_gradients` will add an Accumulator for a parameter only once,
        # but optimizer will be called repeatedly in re-launch, so optimizer need to be copied.
208
        optimizer = copy.deepcopy(optimizer)
209
        self._dist_context._serial_optimizer = optimizer
210
        with program_guard(main_program, startup_program):
211 212
            with unique_name.guard("opt_"):
                optimizer_ops = optimizer.apply_gradients(params_grads)
213 214 215
        self._completer.complete_update_annotation(main_program)
        return optimizer_ops

216 217 218
    def _apply_pre_optimization(
        self, main_program, startup_program, loss, optimizer, params_grads
    ):
219 220
        if self._strategy is None:
            return
221 222 223

        # apply quantization pass
        # The pass can be applied when mode must be 'train'
224 225
        if self._mode == 'train' and self._strategy.qat.enable:
            config = copy.deepcopy(self._strategy.qat.to_dict())
226 227 228
            config["dist_context"] = self._dist_context
            config["params_grads"] = params_grads
            auto_parallel_quantization_pass = new_pass(
229 230 231 232 233
                "auto_parallel_quantization", config
            )
            auto_parallel_quantization_pass.apply(
                [main_program], [startup_program], self._pass_context
            )
234 235 236 237
            main_program = self._pass_context.get_attr("main_program")
            startup_program = self._pass_context.get_attr("startup_program")
            params_grads = self._pass_context.get_attr("params_grads")

238
        # apply amp pass on train/eval/predict
239
        if self._strategy.amp.enable:
240
            config = copy.deepcopy(self._strategy.amp.to_dict())
241 242 243
            config["dist_context"] = self._dist_context
            config["params_grads"] = params_grads
            config["loss"] = loss
244 245
            config["input_data"] = (
                self._dist_context.serial_feed_vars["inputs"]
246
                + self._dist_context.serial_feed_vars["labels"]
247
            )
248 249 250
            if config["use_pure_fp16"]:
                config["base_opt"] = optimizer
                auto_parallel_fp16_pass = new_pass("auto_parallel_fp16", config)
251 252 253
                auto_parallel_fp16_pass.apply(
                    [main_program], [startup_program], self._pass_context
                )
254 255
            else:
                auto_parallel_amp_pass = new_pass("auto_parallel_amp", config)
256 257 258
                auto_parallel_amp_pass.apply(
                    [main_program], [startup_program], self._pass_context
                )
259 260

        # apply recompute pass
261
        # recompute is then train-only optimization
262 263
        if self._mode == "train" and self._strategy.recompute.enable:
            config = copy.deepcopy(self._strategy.recompute.to_dict())
264 265 266
            config["dist_context"] = self._dist_context
            config["no_grad_set"] = None
            config["loss"] = loss
267 268 269 270 271 272
            auto_parallel_recompute_pass = new_pass(
                "auto_parallel_recompute", config
            )
            auto_parallel_recompute_pass.apply(
                [main_program], [startup_program], self._pass_context
            )
273

274 275
        return main_program, startup_program, params_grads

276 277 278
    def _apply_post_optimization(
        self, main_program, startup_program, rank, params_grads
    ):
279 280
        if self._strategy is None:
            return
281 282 283 284 285

        # data parallel optimization
        config = {}
        config["dist_context"] = self._dist_context
        config["global_rank"] = rank
286
        config["use_sharding"] = self._strategy.sharding.enable
287 288 289
        dp_pass = new_pass("auto_parallel_data_parallel_optimization", config)
        dp_pass.apply([main_program], [startup_program], self._pass_context)

290 291
        if self._strategy.sharding.enable:
            config = copy.deepcopy(self._strategy.sharding.to_dict())
292 293 294
            config["dist_context"] = self._dist_context
            config["params_grads"] = params_grads
            config["global_rank"] = rank
295 296 297 298 299 300
            auto_parallel_sharding_pass = new_pass(
                "auto_parallel_sharding", config
            )
            auto_parallel_sharding_pass.apply(
                [main_program], [startup_program], self._pass_context
            )
301
            params_grads = self._pass_context.get_attr("params_grads")
302

303 304
        # GradClip is train-only optimization
        if self._mode == "train":
305
            config = copy.deepcopy(self._strategy.sharding.to_dict())
306 307 308
            config["dist_context"] = self._dist_context
            config["params_grads"] = params_grads
            config["rank_id"] = rank
309 310 311 312 313 314 315 316 317 318 319 320 321
            auto_parallel_clip_pass = new_pass(
                "auto_parallel_grad_clip", config
            )
            auto_parallel_clip_pass.apply(
                [main_program], [startup_program], self._pass_context
            )

        if self._strategy.pipeline.enable:
            self._strategy.gradient_merge.enable = True
            self._strategy.gradient_merge.k_steps = (
                self._strategy.pipeline.accumulate_steps
            )
            self._strategy.gradient_merge.avg = True
322 323

        # gradient_merge is then train-only optimization
324 325
        if self._mode == "train" and self._strategy.gradient_merge.enable:
            config = copy.deepcopy(self._strategy.gradient_merge.to_dict())
326 327 328
            config["dist_context"] = self._dist_context
            config["params_grads"] = params_grads
            auto_parallel_gradient_merge_pass = new_pass(
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
                "auto_parallel_gradient_merge_pass", config
            )
            auto_parallel_gradient_merge_pass.apply(
                [main_program], [startup_program], self._pass_context
            )

        if self._strategy.pipeline.enable:
            config = copy.deepcopy(self._strategy.pipeline.to_dict())
            config["dist_context"] = self._dist_context
            auto_parallel_pipeline_pass = new_pass(
                "auto_parallel_pipeline", config
            )
            auto_parallel_pipeline_pass.apply(
                [main_program], [startup_program], self._pass_context
            )