fleet_executor_utils.py 18.1 KB
Newer Older
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2
#
3 4 5
# 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
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9 10 11 12 13 14
# 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
from paddle.distributed.fleet.meta_optimizers.common import OP_ROLE_KEY, OpRole
16
from paddle.framework import core
17
from paddle.static import Program
18 19


20 21 22 23 24
class TaskNode:
    """
    Python side TaskNode, connection to the c++ side TaskNode
    """

25 26 27 28 29 30 31 32 33 34 35
    def __init__(
        self,
        rank,
        max_run_times,
        max_slot_times,
        role=None,
        node_type=None,
        task_id=0,
        ops=None,
        program=None,
        lazy_initialize=False,
L
LiYuRio 已提交
36
        cond_var_name=None,
37
    ):
38
        """
39
        :param rank (int): Current rank of the task node.
40 41
        :param max_run_times (int): The max run times of the task node.
        :param max_slot_times (int): The mas slot times of the task node.
42 43 44
        :param role (int): The role of the task node. (Will be removed in the future)
        :param node_type (str): The type of the task node.
        :param task_id (int): The id of task node.
45
        :param ops (list): A list of op.desc to init the task node. (Will be removed in the future)
46
        :param program (Program): An instance of Program to init the task node.
47
        :param lazy_initialize (bool): In user-defined task, the program may change adding feed/fetch op. As efficient consideration, the task node will have the C++ object later.
L
LiYuRio 已提交
48
        :param cond_var_name (string): Indicate the cond var name of while.
49
        """
50 51 52 53 54 55
        assert (ops is not None) ^ (
            program is not None
        ), "Should provide only one of ops or program to task node."
        assert not (
            (ops is not None) and lazy_initialize
        ), "Lazy initialization doesn't support with ops list"
56 57 58 59 60 61 62
        self.id = int(task_id)
        self.rank = rank
        self.max_run_times = max_run_times
        self.max_slot_times = max_slot_times
        self.node_type = node_type
        self.program = program
        self.lazy_initialize = lazy_initialize
L
LiYuRio 已提交
63
        self.cond_var_name = cond_var_name
64 65 66 67 68 69 70
        self.run_pre_steps = None
        self.run_at_offset = None
        self.node = None
        self.upstreams = []
        self.downstreams = []
        if not lazy_initialize:
            if ops is not None:
71 72 73 74 75 76
                assert (
                    role is not None and task_id is not None
                ), "If init task node with ops, should provide `role` and `task_id`."
                self.node = core.TaskNode(
                    role, ops, rank, task_id, max_run_times, max_slot_times
                )
77
            else:
78 79 80
                self.node = core.TaskNode(
                    program.desc, rank, self.id, max_run_times, max_slot_times
                )
81 82
            if self.node_type:
                self.node.set_type(self.node_type)
83 84

    def task_node(self):
85
        if self.lazy_initialize:
86 87 88 89 90 91 92
            self.node = core.TaskNode(
                self.program.desc,
                self.rank,
                self.id,
                self.max_run_times,
                self.max_slot_times,
            )
93 94 95 96 97 98
            if self.node_type:
                self.node.set_type(self.node_type)
            if self.run_pre_steps:
                self.node.set_run_pre_steps(self.run_pre_steps)
            if self.run_at_offset:
                self.node.set_run_at_offset(self.run_at_offset)
L
LiYuRio 已提交
99 100
            if self.cond_var_name:
                self.node.set_cond_var_name(self.cond_var_name)
101
            for up in self.upstreams:
L
LiYuRio 已提交
102
                self.node.add_upstream_task(up[0], up[1], up[2])
103
            for down in self.downstreams:
L
LiYuRio 已提交
104
                self.node.add_downstream_task(down[0], down[1], down[2])
105
            self.lazy_initialize = False
106 107 108
        return self.node

    def set_program(self, program):
109 110 111
        assert (
            self.lazy_initialize
        ), "Inside program is unchangable for immediate initialized task node. Set the lazy_initialize to be true if the inside program need to be update. Remember to do all your change before eval node.task_node()."
112 113 114
        self.program = program

    def get_program(self):
115 116 117
        assert (
            self.program is not None
        ), "The task node is not initialized using program"
118 119 120
        return self.program

    def set_run_pre_steps(self, steps):
121 122 123 124
        if self.lazy_initialize:
            self.run_pre_steps = steps
        else:
            self.node.set_run_pre_steps(steps)
125 126

    def set_run_at_offset(self, offset):
127 128 129 130
        if self.lazy_initialize:
            self.run_at_offset = offset
        else:
            self.node.set_run_at_offset(offset)
131

L
LiYuRio 已提交
132 133 134
    def add_upstream_task(
        self, upstream, buffer_size=2, depend_type=core.DependType.NORMAL
    ):
135
        if self.lazy_initialize:
L
LiYuRio 已提交
136
            self.upstreams.append((upstream, buffer_size, depend_type))
137
        else:
L
LiYuRio 已提交
138
            self.node.add_upstream_task(upstream, buffer_size, depend_type)
139

L
LiYuRio 已提交
140 141 142
    def add_downstream_task(
        self, downstream, buffer_size=2, depend_type=core.DependType.NORMAL
    ):
143
        if self.lazy_initialize:
L
LiYuRio 已提交
144
            self.downstreams.append((downstream, buffer_size, depend_type))
145
        else:
L
LiYuRio 已提交
146
            self.node.add_downstream_task(downstream, buffer_size, depend_type)
147 148

    def task_id(self):
149
        return self.id
150 151


152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
class CoordSys:
    """
    This class is used to mapping rank to (mp rank, sharding rank, pp rank, dp rank).
    """

    def __init__(self, dist_opt):
        self.dp_degree = dist_opt.get('dp_degree', 1)
        self.pp_degree = dist_opt.get('pp_degree', 1)
        self.sharding_degree = dist_opt.get('sharding_degree', 1)
        self.mp_degree = dist_opt.get('mp_degree', 1)

    def _invalide_coord(self, coord):
        """
        Test the input coord is valid or not.
        :param coord: The coord to be tested
        :return: False if valid, True if invalid.
        """
169 170 171 172 173 174 175 176 177 178
        return (
            coord['mp_idx'] < 0
            or coord['mp_idx'] >= self.mp_degree
            or coord['sharding_idx'] < 0
            or coord['sharding_idx'] >= self.sharding_degree
            or coord['pp_idx'] < 0
            or coord['pp_idx'] >= self.pp_degree
            or coord['dp_idx'] < 0
            or coord['dp_idx'] >= self.dp_degree
        )
179 180 181 182 183 184 185 186 187

    def coord_to_rank(self, coord):
        """
        Map the input coord to it's corresponding rank.
        :param coord:  The coord to be converted
        :return: The rank corresponding with the coord
        """
        if self._invalide_coord(coord):
            return -1
188 189 190 191 192 193 194 195 196
        return int(
            coord['dp_idx']
            * self.pp_degree
            * self.sharding_degree
            * self.mp_degree
            + coord['pp_idx'] * self.sharding_degree * self.mp_degree
            + coord['sharding_idx'] * self.mp_degree
            + coord['mp_idx']
        )
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214

    def rank_to_coord(self, rank):
        """
        Map the input rank to it's corresponding coord
        :param rank: The rank to be converted
        :return: The coord corresponding with the rank
        """
        mp_idx = rank % self.mp_degree
        rank //= self.mp_degree
        sharding_idx = rank % self.sharding_degree
        rank //= self.sharding_degree
        pp_idx = rank % self.pp_degree
        rank //= self.pp_degree
        dp_idx = rank % self.dp_degree
        return {
            'mp_idx': int(mp_idx),
            'sharding_idx': int(sharding_idx),
            'pp_idx': int(pp_idx),
215
            'dp_idx': int(dp_idx),
216 217 218
        }


219
class FleetExecutorUtils:
220 221 222
    def __init__(
        self, dist_strategy=None, rank=None, nrank=None, max_run_times=None
    ):
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
        self.dist_strategy = dist_strategy
        self.rank = rank
        self.nrank = nrank
        self.max_run_times = max_run_times
        self.is_auto_parallel = True if dist_strategy is None else False
        self.num_of_functionality = 4
        self.coord_sys = None
        self.coord = None
        if dist_strategy:
            self.coord_sys = CoordSys(dist_strategy)
            self.coord = self.coord_sys.rank_to_coord(rank)

    def is_optimizer_op(self, op_role):
        return op_role == int(OpRole.Optimize)

    def is_lr_sched_op(self, op_role):
        return op_role == int(OpRole.Optimize.LRSched)

    def is_forward_op(self, op_role):
242 243 244
        return (op_role == int(OpRole.Forward)) or (
            op_role == (int(OpRole.Forward) | int(OpRole.Loss))
        )
245 246

    def is_backward_op(self, op_role):
247 248 249
        return (op_role == int(OpRole.Backward)) or (
            op_role == (int(OpRole.Backward) | int(OpRole.Loss))
        )
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270

    def split_program_to_op_list(self, program):
        op_list_map = {"lr": [], "fwd": [], "bwd": [], "opt": []}
        for op in program.block(0).ops:
            # split the program based on the op_role
            op_role = int(op.all_attrs()[OP_ROLE_KEY])
            if self.is_lr_sched_op(op_role):
                op_list_map["lr"].append(op)
            elif self.is_forward_op(op_role):
                op_list_map["fwd"].append(op)
            elif self.is_backward_op(op_role):
                op_list_map["bwd"].append(op)
            elif self.is_optimizer_op(op_role):
                op_list_map["opt"].append(op)
            else:
                raise "The op role: " + str(
                    op_role
                ) + " isn't one of LRSched, Forward, Backward or Optimizer."
        return op_list_map

    def convert_op_list_to_program(self, op_list, complete_program):
271
        # TODO(liyurui): Complete this convert logic
272 273 274 275
        program_map = {
            "lr": Program(),
            "fwd": Program(),
            "bwd": Program(),
276
            "opt": Program(),
277 278 279 280
        }
        return program_map

    def build_1f1b_dependency(self, task_node_map):
281 282 283
        assert (
            not self.is_auto_parallel
        ), "Handly add dependency should not be invoked in auto parallel mode"
284 285 286 287 288 289 290 291 292
        # Generated the dependency based on this graph:
        # lr(1:m) -> forward -> backward -> (m:1)optimize
        #               ↑          ↓
        # lr(1:m) -> forward -> backward -> (m:1)optimize
        #               ↑          ↓
        # lr(1:m) -> forward -> backward -> (m:1)optimize

        # add dependency intra stage
        cur_start_id = self.rank * self.num_of_functionality
293 294 295
        pp_buff_size = int(
            self.dist_strategy['pp_degree'] - self.coord['pp_idx']
        )
296 297 298 299 300 301 302 303 304 305 306 307
        task_node_map["lr"].add_downstream_task(cur_start_id + 1)
        task_node_map["fwd"].add_upstream_task(cur_start_id)
        task_node_map["fwd"].add_downstream_task(cur_start_id + 2, pp_buff_size)
        task_node_map["bwd"].add_upstream_task(cur_start_id + 1, pp_buff_size)
        task_node_map["bwd"].add_downstream_task(cur_start_id + 3)
        task_node_map["opt"].add_upstream_task(cur_start_id + 2)
        # add dependency inter stage
        upstream_coord, downstream_coord = self.coord.copy(), self.coord.copy()
        upstream_coord['pp_idx'] = upstream_coord['pp_idx'] - 1
        downstream_coord['pp_idx'] = downstream_coord['pp_idx'] + 1
        pp_upstream = self.coord_sys.coord_to_rank(upstream_coord)
        pp_downstream = self.coord_sys.coord_to_rank(downstream_coord)
308 309
        first_stage = pp_upstream == -1
        last_stage = pp_downstream == -1
310 311 312 313 314 315 316 317 318 319 320 321 322
        prev_pp_start_id = pp_upstream * self.num_of_functionality
        next_pp_start_id = pp_downstream * self.num_of_functionality
        if not first_stage:
            task_node_map["fwd"].add_upstream_task(prev_pp_start_id + 1)
            task_node_map["bwd"].add_downstream_task(prev_pp_start_id + 2)
        if not last_stage:
            task_node_map["fwd"].add_downstream_task(next_pp_start_id + 1)
            task_node_map["bwd"].add_upstream_task(next_pp_start_id + 2)
        return task_node_map

    def construct_task_nodes_1f1b(self, program_map):
        max_slot_times = int(self.max_run_times - self.coord['pp_idx'])
        cur_start_id = int(self.rank * self.num_of_functionality)
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
        lr_task_node = TaskNode(
            rank=self.rank,
            max_run_times=self.max_run_times,
            max_slot_times=max_slot_times,
            program=program_map["lr"],
            task_id=cur_start_id,
        )
        fwd_task_node = TaskNode(
            rank=self.rank,
            max_run_times=self.max_run_times,
            max_slot_times=max_slot_times,
            program=program_map["fwd"],
            task_id=cur_start_id + 1,
        )
        bwd_task_node = TaskNode(
            rank=self.rank,
            max_run_times=self.max_run_times,
            max_slot_times=max_slot_times,
            program=program_map["bwd"],
            task_id=cur_start_id + 2,
        )
        opt_task_node = TaskNode(
            rank=self.rank,
            max_run_times=self.max_run_times,
            max_slot_times=max_slot_times,
            program=program_map["opt"],
            task_id=cur_start_id + 3,
        )
351 352 353 354
        return {
            "lr": lr_task_node,
            "fwd": fwd_task_node,
            "bwd": bwd_task_node,
355
            "opt": opt_task_node,
356
        }
357

358 359 360 361 362 363 364 365 366 367
    def task_id_to_rank(self):
        task_id_to_rank = {}
        for i in range(self.nrank):
            for j in range(self.num_of_functionality):
                task_id_to_rank[int(i * self.num_of_functionality + j)] = i
        return task_id_to_rank

    def construct_task_nodes_1f1b_op_list(self, op_list_map):
        max_slot_times = int(self.max_run_times - self.coord['pp_idx'])
        cur_start_id = int(self.rank * self.num_of_functionality)
368 369 370 371 372 373 374 375 376
        lr_task_node = TaskNode(
            rank=self.rank,
            max_run_times=self.max_run_times,
            max_slot_times=max_slot_times,
            role=int(OpRole.Optimize.LRSched),
            ops=op_list_map["lr"],
            task_id=cur_start_id,
            node_type="Amplifier",
        )
377
        lr_task_node.set_run_pre_steps(self.max_run_times)
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
        fwd_task_node = TaskNode(
            rank=self.rank,
            max_run_times=self.max_run_times,
            max_slot_times=max_slot_times,
            role=int(OpRole.Forward),
            ops=op_list_map["fwd"],
            task_id=cur_start_id + 1,
            node_type="Compute",
        )
        bwd_task_node = TaskNode(
            rank=self.rank,
            max_run_times=self.max_run_times,
            max_slot_times=max_slot_times,
            role=int(OpRole.Backward),
            ops=op_list_map["bwd"],
            task_id=cur_start_id + 2,
            node_type="Compute",
        )
        opt_task_node = TaskNode(
            rank=self.rank,
            max_run_times=self.max_run_times,
            max_slot_times=max_slot_times,
            role=int(OpRole.Optimize),
            ops=op_list_map["opt"],
            task_id=cur_start_id + 3,
            node_type="Amplifier",
        )
405 406 407 408 409 410
        opt_task_node.set_run_pre_steps(self.max_run_times)
        opt_task_node.set_run_at_offset(self.max_run_times - 1)
        return {
            "lr": lr_task_node,
            "fwd": fwd_task_node,
            "bwd": bwd_task_node,
411
            "opt": opt_task_node,
412
        }
413 414


415 416 417 418 419 420 421 422
def run1f1b(
    program,
    rank,
    max_run_times,
    dist_opt,
    nrank,
    with_standalone_executor=False,
):
423 424 425 426 427 428
    """
    Split the program to support 1f1b pipeline scheduler.
    This funct will split the program based on the op_role.
    The program will be split into four parts: lr_sched, fwd, bwd, opt.
    And will create task nodes based on the four parts of the program.
    :param program: The origin program.
429
    :param rank: Current rank (can be got from fleet.worker_index()).
430 431 432
    :param max_run_times: Max run times for a micro batch. AKA number of micro steps.
    :param dist_opt: The fleet_opt configured by user.
    :param nrank: Number of workers (can be got from fleet.worker_num()).
433
    :param with_standalone_executor: Experiment feature, use fleet executor with standalone executor.
434 435 436 437 438
    :return:
        task_nodes (list): four task nodes for current rank
        task_id_to_rank (dict): task nodes' ids to it's corresponding rank
    """
    print("fleet executor will use python side 1f1b scheduler.")
439 440 441 442 443 444
    fleet_executor_utils = FleetExecutorUtils(
        dist_strategy=dist_opt,
        rank=rank,
        nrank=nrank,
        max_run_times=max_run_times,
    )
445 446 447 448
    op_list_map = fleet_executor_utils.split_program_to_op_list(program)
    task_node_map = None
    if with_standalone_executor:
        program_map = fleet_executor_utils.convert_op_list_to_program(
449 450
            op_list_map, program
        )
451
        task_node_map = fleet_executor_utils.construct_task_nodes_1f1b(
452 453
            program_map
        )
454 455 456 457 458 459
    else:
        op_desc_list_map = {"lr": [], "fwd": [], "bwd": [], "opt": []}
        for key in op_list_map:
            for op in op_list_map[key]:
                op_desc_list_map[key].append(op.desc)
        task_node_map = fleet_executor_utils.construct_task_nodes_1f1b_op_list(
460 461
            op_desc_list_map
        )
462 463 464 465 466 467 468
    task_node_map = fleet_executor_utils.build_1f1b_dependency(task_node_map)
    task_id_to_rank = fleet_executor_utils.task_id_to_rank()
    task_node_list = [task_node_map[key].task_node() for key in task_node_map]
    return task_node_list, task_id_to_rank


def origin(program, rank):
469 470 471
    """
    Origin scheduler for fleet executor, supports non-pp mode
    :param program: The origin program.
472
    :param rank: Current rank (can be got from fleet.worker_index()).
473 474 475 476 477
    :return:
        task_nodes (list): four task nodes for current rank
        task_id_to_rank (dict): a fake dict, since there is no upstream or downstream, this dict won't be used
    """
    print("fleet executor will use python side origin scheduler.")
478 479 480 481 482 483 484
    task_node = TaskNode(
        program=program,
        rank=rank,
        node_type="Compute",
        max_run_times=1,
        max_slot_times=1,
    )
485
    task_id_to_rank = {task_node.task_id(): rank}
486
    return [task_node.task_node()], task_id_to_rank