device_worker.py 26.8 KB
Newer Older
1
#   Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13
#
# 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.
14
"""Defination of device workers."""
15

16
__all__ = [
17 18 19 20 21 22
    'DeviceWorker',
    'Hogwild',
    'DownpourSGD',
    'Section',
    'DownpourSGDOPT',
    'HeterSection',
23
]
24

25

26
class DeviceWorker:
X
xjqbest 已提交
27
    """
28
    DeviceWorker is an abstract class, which generates worker desc.
29 30
    This class is an inner class that we do computation logics within
    the implementation. For example, execution of a program or a graph.
X
xjqbest 已提交
31
    """
32

33
    def __init__(self):
34
        """Init."""
D
dongdaxiang 已提交
35 36
        self._program = None
        self._infer = None
37

38 39 40
    def _set_infer(self, infer=False):
        """
        set inference flag for current device worker
C
Chengmo 已提交
41

42 43 44
        Args:
            infer(bool): whether to do inference
        """
D
dongdaxiang 已提交
45
        self._infer = infer
D
dongdaxiang 已提交
46

47
    def _set_fleet_desc(self, fleet_desc):
X
xjqbest 已提交
48 49 50 51 52 53
        """
        Set fleet desc.

        Args:
            fleet_desc(PSParameter): pslib.PSParameter object
        """
D
dongdaxiang 已提交
54
        self._fleet_desc = fleet_desc
D
dongdaxiang 已提交
55

56
    def _set_program(self, program):
X
xjqbest 已提交
57 58 59 60 61 62
        """
        Set program.

        Args:
            program(Program): a Program object
        """
D
dongdaxiang 已提交
63
        self._program = program
64

65
    def _gen_worker_desc(self, trainer_desc):
X
xjqbest 已提交
66 67 68 69 70 71 72 73
        """
        Generator worker desc.

        Args:
            trainer_desc(TrainerDesc): a TrainerDesc object
        """
        raise NotImplementedError(
            "DeviceWorker does not implement gen_worker_desc, "
74 75
            "please use Hogwild or DownpourSGD, etc."
        )
76 77 78


class Hogwild(DeviceWorker):
X
xjqbest 已提交
79 80 81 82
    """
    Hogwild is a kind of SGD algorithm.

    """
83

84
    def __init__(self):
85
        """Init."""
86
        super().__init__()
87

88
    def _gen_worker_desc(self, trainer_desc):
X
xjqbest 已提交
89 90 91 92 93 94
        """
        Generator worker desc, which device worker is HogwildWorker.

        Args:
            trainer_desc(TrainerDesc): a TrainerDesc object
        """
95
        trainer_desc.device_worker_name = "HogwildWorker"
D
dongdaxiang 已提交
96
        if self._infer:
97
            # just ignore feed op for inference model
98 99 100 101 102 103 104 105 106 107
            trainer_desc.hogwild_param.skip_ops.extend(
                [
                    "feed",
                    "push_sparse",
                    "push_sparse_v2",
                    "push_dense",
                    "distributed_push_sparse",
                    "send",
                ]
            )
108

109 110
        dense_table_set = set()
        program_id = str(id(self._program))
111
        print("device worker program id:", program_id)
112
        if self._program is None:
113 114 115
            print("program of current device worker is not configured")
            exit(-1)
        opt_info = self._program._fleet_opt
116 117
        # when opt_info is None or empty dict, it should return
        if not opt_info:
118
            return
T
Thunderbrook 已提交
119 120 121 122 123 124
        downpour = trainer_desc.downpour_param
        hogwild = trainer_desc.hogwild_param
        if opt_info["stat_var_names"]:
            for i in opt_info["stat_var_names"]:
                hogwild.stat_var_names.extend([i])
                downpour.stat_var_names.extend([i])
125

126 127
        from paddle.fluid.incubate.fleet.parameter_server import version

128 129 130 131 132
        if (
            version.is_transpiler()
            and "fleet_desc" not in opt_info
            and "program_configs" not in opt_info
        ):
C
Chengmo 已提交
133 134
            return

135
        program_configs = opt_info["program_configs"]
136
        print("device worker program_configs:", program_configs)
137 138

        for pid in program_configs:
139
            print("device worker", pid, program_id)
140 141 142
            if pid == program_id:
                pc = downpour.program_config.add()
                pc.program_id = program_id
143 144 145 146
                print(
                    "device worker pull dense:",
                    program_configs[program_id]["pull_dense"],
                )
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
                for i in program_configs[program_id]["push_sparse"]:
                    pc.push_sparse_table_id.extend([i])
                for i in program_configs[program_id]["push_dense"]:
                    pc.push_dense_table_id.extend([i])
                    dense_table_set.add(i)
                for i in program_configs[program_id]["pull_sparse"]:
                    pc.pull_sparse_table_id.extend([i])
                for i in program_configs[program_id]["pull_dense"]:
                    pc.pull_dense_table_id.extend([i])
                    dense_table_set.add(i)
                break

        trainer_desc.device_worker_name = "HogwildWorker"
        pull_thread = trainer_desc.pull_dense_param
        pull_thread.device_num = trainer_desc.thread_num
162 163 164 165
        if (
            opt_info.get("program_id_to_worker") is None
            and opt_info.get("dense_table_config") is None
        ):
166
            raise ValueError(
167 168
                "opt_info must have program_id_to_worker or dense_table_config"
            )
169 170 171
        if opt_info.get("program_id_to_worker") is not None:
            prog_id_to_worker = opt_info["program_id_to_worker"]
            if prog_id_to_worker.get(program_id) is None:
172 173 174
                raise ValueError(
                    "%s not found in program_id_to_worker" % program_id
                )
175 176 177 178 179
            worker = opt_info["program_id_to_worker"][program_id]
            for i in worker.get_desc().dense_table:
                if i.table_id in dense_table_set:
                    dense_table = pull_thread.dense_table.add()
                    dense_table.dense_value_name.extend(i.dense_variable_name)
180
                    dense_table.table_id = i.table_id
181 182 183
            sparse_len = len(worker.get_desc().sparse_table)
            for i in range(sparse_len):
                sparse_table = downpour.sparse_table.add()
184 185 186
                sparse_table.table_id = (
                    worker.get_desc().sparse_table[i].table_id
                )
187
                sparse_table.sparse_key_name.extend(
188 189
                    worker.get_desc().sparse_table[i].slot_key
                )
190
                sparse_table.sparse_value_name.extend(
191 192
                    worker.get_desc().sparse_table[i].slot_value
                )
193
                sparse_table.sparse_grad_name.extend(
194 195 196 197 198
                    worker.get_desc().sparse_table[i].slot_gradient
                )
                sparse_table.fea_dim = self._fleet_desc.server_param.downpour_server_param.downpour_table_param[
                    i
                ].accessor.fea_dim
199 200 201 202 203 204 205 206 207 208 209
                # not use emb_dim
                sparse_table.emb_dim = -1
                # not use hard code click
                sparse_table.label_var_name = ""

            for i in worker.get_desc().dense_table:
                if i.table_id in dense_table_set:
                    dense_table = downpour.dense_table.add()
                    dense_table.table_id = i.table_id
                    dense_table.dense_value_name.extend(i.dense_variable_name)
                    dense_table.dense_grad_name.extend(
210 211
                        i.dense_gradient_variable_name
                    )
212 213 214 215 216
            hogwild.skip_ops.extend(worker.get_desc().skip_op)
        else:
            dense_table_config = opt_info.get("dense_table_config")
            print("device worker dense_table_config:", dense_table_config)
            for table_id, varnames in dense_table_config.items():
217
                dense_table = pull_thread.dense_table.add()
218 219 220
                dense_table.dense_value_name.extend(varnames)
                dense_table.table_id = table_id

221
        if self._infer:
222
            hogwild.skip_ops.extend(
223 224
                ["push_sparse", "push_sparse_v2", "push_dense"]
            )
225 226 227 228 229 230 231 232 233 234


class DownpourLite(DeviceWorker):
    """
    DownpourLite is a kind of SGD algorithm.

    """

    def __init__(self):
        """Init."""
235
        super().__init__()
236 237 238 239 240 241 242 243 244 245 246 247

    def _gen_worker_desc(self, trainer_desc):
        """
        Generator worker desc, which device worker is DownpourLiteWorker.

        Args:
            trainer_desc(TrainerDesc): a TrainerDesc object
        """
        print("create DownpourLiteWorker")
        trainer_desc.device_worker_name = "DownpourLiteWorker"
        if self._infer:
            # just ignore feed op for inference model
248 249 250 251 252 253 254 255 256 257
            trainer_desc.downpour_param.skip_ops.extend(
                [
                    "feed",
                    "push_sparse",
                    "push_sparse_v2",
                    "push_dense",
                    "distributed_push_sparse",
                    "send",
                ]
            )
258 259 260 261

        dense_table_set = set()
        program_id = str(id(self._program))
        print("device worker program id:", program_id)
262
        if self._program is None:
263 264 265 266 267 268 269 270 271 272 273 274 275
            print("program of current device worker is not configured")
            exit(-1)
        opt_info = self._program._fleet_opt
        # when opt_info is None or empty dict, it should return
        if not opt_info:
            return
        downpour = trainer_desc.downpour_param
        if opt_info["stat_var_names"]:
            for i in opt_info["stat_var_names"]:
                downpour.stat_var_names.extend([i])

        from paddle.fluid.incubate.fleet.parameter_server import version

276 277 278 279 280
        if (
            version.is_transpiler()
            and "fleet_desc" not in opt_info
            and "program_configs" not in opt_info
        ):
281 282 283 284 285 286 287 288 289 290
            return

        program_configs = opt_info["program_configs"]
        print("device worker program_configs:", program_configs)

        for pid in program_configs:
            print("device worker", pid, program_id)
            if pid == program_id:
                pc = downpour.program_config.add()
                pc.program_id = program_id
291 292 293 294
                print(
                    "device worker pull dense:",
                    program_configs[program_id]["pull_dense"],
                )
295 296 297 298 299 300 301 302 303 304 305 306 307 308
                for i in program_configs[program_id]["push_sparse"]:
                    pc.push_sparse_table_id.extend([i])
                for i in program_configs[program_id]["push_dense"]:
                    pc.push_dense_table_id.extend([i])
                    dense_table_set.add(i)
                for i in program_configs[program_id]["pull_sparse"]:
                    pc.pull_sparse_table_id.extend([i])
                for i in program_configs[program_id]["pull_dense"]:
                    pc.pull_dense_table_id.extend([i])
                    dense_table_set.add(i)
                break

        pull_thread = trainer_desc.pull_dense_param
        pull_thread.device_num = trainer_desc.thread_num
309 310 311 312
        if (
            opt_info.get("program_id_to_worker") is None
            and opt_info.get("dense_table_config") is None
        ):
313
            raise ValueError(
314 315
                "opt_info must have program_id_to_worker or dense_table_config"
            )
316 317 318
        if opt_info.get("program_id_to_worker") is not None:
            prog_id_to_worker = opt_info["program_id_to_worker"]
            if prog_id_to_worker.get(program_id) is None:
319 320 321
                raise ValueError(
                    "%s not found in program_id_to_worker" % program_id
                )
322 323 324 325 326
            worker = opt_info["program_id_to_worker"][program_id]
            for i in worker.get_desc().dense_table:
                if i.table_id in dense_table_set:
                    dense_table = pull_thread.dense_table.add()
                    dense_table.dense_value_name.extend(i.dense_variable_name)
327
                    dense_table.table_id = i.table_id
328 329 330
            sparse_len = len(worker.get_desc().sparse_table)
            for i in range(sparse_len):
                sparse_table = downpour.sparse_table.add()
331 332 333
                sparse_table.table_id = (
                    worker.get_desc().sparse_table[i].table_id
                )
334
                sparse_table.sparse_key_name.extend(
335 336
                    worker.get_desc().sparse_table[i].slot_key
                )
337
                sparse_table.sparse_value_name.extend(
338 339
                    worker.get_desc().sparse_table[i].slot_value
                )
340
                sparse_table.sparse_grad_name.extend(
341 342 343 344 345
                    worker.get_desc().sparse_table[i].slot_gradient
                )
                sparse_table.fea_dim = self._fleet_desc.server_param.downpour_server_param.downpour_table_param[
                    i
                ].accessor.fea_dim
346 347 348 349 350 351 352 353 354 355 356
                # not use emb_dim
                sparse_table.emb_dim = -1
                # not use hard code click
                sparse_table.label_var_name = ""

            for i in worker.get_desc().dense_table:
                if i.table_id in dense_table_set:
                    dense_table = downpour.dense_table.add()
                    dense_table.table_id = i.table_id
                    dense_table.dense_value_name.extend(i.dense_variable_name)
                    dense_table.dense_grad_name.extend(
357 358
                        i.dense_gradient_variable_name
                    )
359 360 361 362 363 364 365 366 367 368 369
            downpour.skip_ops.extend(worker.get_desc().skip_op)
        else:
            dense_table_config = opt_info.get("dense_table_config")
            print("device worker dense_table_config:", dense_table_config)
            for table_id, varnames in dense_table_config.items():
                dense_table = pull_thread.dense_table.add()
                dense_table.dense_value_name.extend(varnames)
                dense_table.table_id = table_id

        if self._infer:
            downpour.skip_ops.extend(
370 371
                ["push_sparse", "push_sparse_v2", "push_dense"]
            )
372

373

D
dongdaxiang 已提交
374
class DownpourSGD(DeviceWorker):
X
xjqbest 已提交
375 376 377
    """
    DownpourSGD is a kind of distributed SGD algorithm.
    """
378

379
    def __init__(self):
X
xjqbest 已提交
380 381
        """
        Init.
382
        initialize downpourSGD device worker
X
xjqbest 已提交
383
        """
384
        super().__init__()
385

386
    def _gen_worker_desc(self, trainer_desc):
X
xjqbest 已提交
387 388 389 390 391 392
        """
        Generator worker desc, which device worker is DownpourWorker.

        Args:
            trainer_desc(TrainerDesc): a TrainerDesc object
        """
X
fix bug  
xjqbest 已提交
393
        dense_table_set = set()
D
dongdaxiang 已提交
394
        program_id = str(id(self._program))
395
        if self._program is None:
D
dongdaxiang 已提交
396
            print("program of current device worker is not configured")
397
            exit(-1)
D
dongdaxiang 已提交
398
        opt_info = self._program._fleet_opt
D
dongdaxiang 已提交
399
        program_configs = opt_info["program_configs"]
400
        downpour = trainer_desc.downpour_param
D
dongdaxiang 已提交
401

D
dongdaxiang 已提交
402 403
        for pid in program_configs:
            if pid == program_id:
D
dongdaxiang 已提交
404 405 406 407 408 409
                pc = downpour.program_config.add()
                pc.program_id = program_id
                for i in program_configs[program_id]["push_sparse"]:
                    pc.push_sparse_table_id.extend([i])
                for i in program_configs[program_id]["push_dense"]:
                    pc.push_dense_table_id.extend([i])
X
xjqbest 已提交
410
                    dense_table_set.add(i)
D
dongdaxiang 已提交
411 412 413 414
                for i in program_configs[program_id]["pull_sparse"]:
                    pc.pull_sparse_table_id.extend([i])
                for i in program_configs[program_id]["pull_dense"]:
                    pc.pull_dense_table_id.extend([i])
X
fix bug  
xjqbest 已提交
415
                    dense_table_set.add(i)
Z
zhang wenhui 已提交
416 417 418 419 420 421 422
                # code for partial push dense table such as multitask
                if "cond2denseid" in program_configs[program_id]:
                    cond2denseid = program_configs[program_id]["cond2denseid"]
                    for key, value in cond2denseid.items():
                        mc_map = pc.partial_pushdense_condtable_map.add()
                        mc_map.key = key
                        mc_map.value = value
D
dongdaxiang 已提交
423
                break
424

425 426 427
        trainer_desc.device_worker_name = opt_info.get(
            "worker_class", "DownpourWorker"
        )
428 429
        pull_thread = trainer_desc.pull_dense_param
        pull_thread.device_num = trainer_desc.thread_num
430 431 432 433
        if opt_info.get("program_id_to_worker") is None:
            raise ValueError("opt_info must have program_id_to_worker")
        prog_id_to_worker = opt_info["program_id_to_worker"]
        if prog_id_to_worker.get(program_id) is None:
434 435 436
            raise ValueError(
                "%s not found in program_id_to_worker" % program_id
            )
437 438
        worker = opt_info["program_id_to_worker"][program_id]
        for i in worker.get_desc().dense_table:
439 440
            if i.table_id in dense_table_set:
                dense_table = pull_thread.dense_table.add()
441
                dense_table.dense_value_name.extend(i.dense_variable_name)
442
                dense_table.table_id = i.table_id
443
        sparse_len = len(worker.get_desc().sparse_table)
444 445
        for i in range(sparse_len):
            sparse_table = downpour.sparse_table.add()
446
            sparse_table.table_id = worker.get_desc().sparse_table[i].table_id
447
            sparse_table.sparse_key_name.extend(
448 449
                worker.get_desc().sparse_table[i].slot_key
            )
450
            sparse_table.sparse_value_name.extend(
451 452
                worker.get_desc().sparse_table[i].slot_value
            )
453
            sparse_table.sparse_grad_name.extend(
454 455 456 457 458 459 460 461 462 463
                worker.get_desc().sparse_table[i].slot_gradient
            )
            if (
                opt_info["use_cvm"]
                or "no_cvm" in opt_info
                and opt_info["no_cvm"] == True
            ):
                sparse_table.emb_dim = self._fleet_desc.server_param.downpour_server_param.downpour_table_param[
                    i
                ].accessor.fea_dim
464 465
                sparse_table.fea_dim = sparse_table.emb_dim
            else:
466
                sparse_table.emb_dim = (
467
                    self._fleet_desc.server_param.downpour_server_param.downpour_table_param[
468 469 470 471
                        i
                    ].accessor.fea_dim
                    - 2
                )
472 473 474
                sparse_table.fea_dim = sparse_table.emb_dim + 2
            # TODO(guru4elephant): hard code here, need to improve
            sparse_table.label_var_name = "click"
475 476 477
        if opt_info["stat_var_names"]:
            for i in opt_info["stat_var_names"]:
                downpour.stat_var_names.extend([i])
478

479
        for i in worker.get_desc().dense_table:
X
fix bug  
xjqbest 已提交
480 481 482
            if i.table_id in dense_table_set:
                dense_table = downpour.dense_table.add()
                dense_table.table_id = i.table_id
483
                dense_table.dense_value_name.extend(i.dense_variable_name)
X
fix bug  
xjqbest 已提交
484
                dense_table.dense_grad_name.extend(
485 486
                    i.dense_gradient_variable_name
                )
X
xujiaqi01 已提交
487
        downpour.skip_ops.extend(worker.get_desc().skip_op)
D
dongdaxiang 已提交
488
        if self._infer:
489 490
            downpour.push_dense = False
            downpour.push_sparse = False
X
fix bug  
xjqbest 已提交
491

492

493 494 495 496 497 498 499 500 501 502
class DownpourSGDOPT(DeviceWorker):
    """
    DownpourSGDOPT is a kind of distributed SGD algorithm.
    """

    def __init__(self):
        """
        Init.
        initialize downpourSGDOPT device worker
        """
503
        super().__init__()
504 505 506 507 508 509 510 511 512 513

    def _gen_worker_desc(self, trainer_desc):
        """
        Generator worker desc, which device worker is DownpourWorker.

        Args:
            trainer_desc(TrainerDesc): a TrainerDesc object
        """
        dense_table_set = set()
        program_id = str(id(self._program))
514
        if self._program is None:
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
            print("program of current device worker is not configured")
            exit(-1)
        opt_info = self._program._fleet_opt
        program_configs = opt_info["program_configs"]
        downpour = trainer_desc.downpour_param

        for pid in program_configs:
            if pid == program_id:
                pc = downpour.program_config.add()
                pc.program_id = program_id
                for i in program_configs[program_id]["push_sparse"]:
                    pc.push_sparse_table_id.extend([i])
                for i in program_configs[program_id]["push_dense"]:
                    pc.push_dense_table_id.extend([i])
                    dense_table_set.add(i)
                for i in program_configs[program_id]["pull_sparse"]:
                    pc.pull_sparse_table_id.extend([i])
                for i in program_configs[program_id]["pull_dense"]:
                    pc.pull_dense_table_id.extend([i])
                    dense_table_set.add(i)
                break

        trainer_desc.device_worker_name = "DownpourWorkerOpt"
        pull_thread = trainer_desc.pull_dense_param
        pull_thread.device_num = trainer_desc.thread_num
        if opt_info.get("program_id_to_worker") is None:
            raise ValueError("opt_info must have program_id_to_worker")
        prog_id_to_worker = opt_info["program_id_to_worker"]
        if prog_id_to_worker.get(program_id) is None:
544 545 546
            raise ValueError(
                "%s not found in program_id_to_worker" % program_id
            )
547 548 549 550 551
        worker = opt_info["program_id_to_worker"][program_id]
        for i in worker.get_desc().dense_table:
            if i.table_id in dense_table_set:
                dense_table = pull_thread.dense_table.add()
                dense_table.dense_value_name.extend(i.dense_variable_name)
552
                dense_table.table_id = i.table_id
553 554 555 556
        sparse_len = len(worker.get_desc().sparse_table)
        for i in range(sparse_len):
            sparse_table = downpour.sparse_table.add()
            sparse_table.table_id = worker.get_desc().sparse_table[i].table_id
557
            sparse_table.sparse_key_name.extend(
558 559
                worker.get_desc().sparse_table[i].slot_key
            )
560
            sparse_table.sparse_value_name.extend(
561 562
                worker.get_desc().sparse_table[i].slot_value
            )
563
            sparse_table.sparse_grad_name.extend(
564 565 566 567 568 569 570 571 572 573
                worker.get_desc().sparse_table[i].slot_gradient
            )
            if (
                opt_info["use_cvm"]
                or "no_cvm" in opt_info
                and opt_info["no_cvm"] == True
            ):
                sparse_table.emb_dim = self._fleet_desc.server_param.downpour_server_param.downpour_table_param[
                    i
                ].accessor.fea_dim
574 575
                sparse_table.fea_dim = sparse_table.emb_dim
            else:
576
                sparse_table.emb_dim = (
577
                    self._fleet_desc.server_param.downpour_server_param.downpour_table_param[
578 579 580 581
                        i
                    ].accessor.fea_dim
                    - 2
                )
582 583 584
                sparse_table.fea_dim = sparse_table.emb_dim + 2
            # TODO(guru4elephant): hard code here, need to improve
            sparse_table.label_var_name = "click"
585 586 587 588
        if (
            "local_tables" in opt_info
            and sparse_table.table_id in opt_info["local_tables"]
        ):
589
            sparse_table.is_local = True
590 591 592 593
        if (
            "async_tables" in opt_info
            and sparse_table.table_id in opt_info["async_tables"]
        ):
594 595 596 597 598 599 600 601 602 603 604
            sparse_table.is_async = True
        if opt_info["stat_var_names"]:
            for i in opt_info["stat_var_names"]:
                downpour.stat_var_names.extend([i])

        for i in worker.get_desc().dense_table:
            if i.table_id in dense_table_set:
                dense_table = downpour.dense_table.add()
                dense_table.table_id = i.table_id
                dense_table.dense_value_name.extend(i.dense_variable_name)
                dense_table.dense_grad_name.extend(
605 606
                    i.dense_gradient_variable_name
                )
607 608 609 610 611 612
        downpour.skip_ops.extend(worker.get_desc().skip_op)
        if self._infer:
            downpour.push_dense = False
            downpour.push_sparse = False


H
hutuxian 已提交
613
class Section(DeviceWorker):
614
    """SectionWorker."""
H
hutuxian 已提交
615 616

    def __init__(self):
617
        """Init."""
618
        super().__init__()
H
hutuxian 已提交
619 620 621 622 623 624 625 626 627

    def _gen_worker_desc(self, trainer_desc):
        """
        Generator worker desc, which device worker is SectionWorker.
        Args:
            trainer_desc(TrainerDesc): a TrainerDesc object
        """
        from google.protobuf import text_format
        from . import core
628

H
hutuxian 已提交
629 630 631
        trainer_desc.device_worker_name = "SectionWorker"
        pipeline_opt = self._program._pipeline_opt
        section_param = trainer_desc.section_param
L
lilong12 已提交
632
        section_param.num_microbatches = pipeline_opt["num_microbatches"]
H
hutuxian 已提交
633
        section_param.start_cpu_core_id = pipeline_opt["start_cpu_core_id"]
634 635 636 637 638 639 640
        section_param.pipeline_stage = pipeline_opt["pipeline_stage"]
        section_param.num_pipeline_stages = pipeline_opt["num_pipeline_stages"]
        schedule_mode_str = pipeline_opt["schedule_mode"]
        # F-then-B scheduler which runs Forward phase for all microbatches,
        # then runs Backward phase for all microbatches.
        # 1F1B scheduler, which runs forward phase and backward phase altertively
        # after startup phase.
641 642 643
        assert schedule_mode_str in ["F-then-B", "1F1B"], (
            "The schedule mode " "for pipeline must be one of F-then-B or 1F1B"
        )
644 645
        schedule_mode = 0 if schedule_mode_str == "F-then-B" else 1
        section_param.schedule_mode = schedule_mode
646 647
        cfg = section_param.section_config
        program = pipeline_opt["section_program"]
648
        cfg.program_desc.ParseFromString(
649 650
            program._get_desc().serialize_to_string()
        )
651 652 653 654
        # TODO: why does not work
        # cfg.program_desc.CopyFrom(program.program._get_desc())
        place = pipeline_opt["place"]
        place_id = pipeline_opt["place_id"]
655 656 657 658
        if core.is_compiled_with_cuda():
            assert isinstance(place, core.CUDAPlace)
        elif core.is_compiled_with_npu():
            assert isinstance(place, core.NPUPlace)
659 660
        cfg.place = cfg.CUDAPlace
        cfg.place_id = place_id
H
hutuxian 已提交
661 662


663 664 665 666 667
class HeterSection(DeviceWorker):
    """HeterSectionWorker."""

    def __init__(self):
        """Init."""
668
        super().__init__()
669 670 671 672 673 674 675 676 677

    def _gen_worker_desc(self, trainer_desc):
        """
        Generator worker desc, which device worker is HeterSectionWorker.
        Args:
            trainer_desc(TrainerDesc): a TrainerDesc object
        """
        from google.protobuf import text_format
        from . import core
678

679 680 681 682
        trainer_desc.device_worker_name = "HeterSectionWorker"
        heter_pipeline_opt = self._program._heter_pipeline_opt
        heter_section_param = trainer_desc.heter_section_param
        heter_section_param.num_microbatches = heter_pipeline_opt[
683 684
            "num_microbatches"
        ]
685
        heter_section_param.pipeline_stage = heter_pipeline_opt[
686 687
            "pipeline_stage"
        ]
688
        heter_section_param.num_pipeline_stages = heter_pipeline_opt[
689 690
            "num_pipeline_stages"
        ]
691 692
        cfg = heter_section_param.section_config
        program = heter_pipeline_opt["section_program"]
693
        cfg.program_desc.ParseFromString(
694 695
            program._get_desc().serialize_to_string()
        )
696 697


698
class DeviceWorkerFactory:
699
    def _create_device_worker(self, worker_type):
700 701
        classname = worker_type.capitalize()
        return globals()[classname]()