util_factory.py 26.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#   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.
"""Fleet Utils."""
"""distributed operations"""
"""basic collective operations in python"""
"""remote file system"""

19
from ..utils.fs import FS
20 21 22 23 24 25 26 27 28 29
from paddle.fluid.proto import framework_pb2
from paddle.fluid.framework import Program
from paddle.fluid import debugger
from google.protobuf import text_format
import paddle.fluid as fluid
from collections import OrderedDict
from paddle.fluid import core
import subprocess
import os
import numpy as np
30 31

__all__ = []
32

33 34

class UtilFactory(object):
35
    def _create_util(self, context=None):
36
        util = UtilBase()
37 38 39 40
        if context is not None and "valid_strategy" in context:
            util._set_strategy(context["valid_strategy"])
        if context is not None and "role_maker" in context:
            util._set_role_maker(context["role_maker"])
41 42 43
        return util


44
class UtilBase(object):
45 46 47 48 49 50 51 52 53
    def __init__(self):
        self.role_maker = None
        self.dist_strategy = None

    def _set_strategy(self, dist_strategy):
        self.dist_strategy = dist_strategy

    def _set_role_maker(self, role_maker):
        self.role_maker = role_maker
54

55
    def _set_file_system(self, fs_client):
56
        assert isinstance(
57 58
            fs_client, FS
        ), "fs_client must be the instance of paddle.distributed.fleet.utils.FS"
59 60
        self.fs_client = fs_client

61
    def all_reduce(self, input, mode="sum", comm_world="worker"):
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
        """
        All reduce `input` between specified collection. This is a distributed API.

        Args:
            input (list|numpy.array): The input variable to do all_reduce between specified collection.
            mode (str): "sum" or "min" or "max".
            comm_world (str, optional): Collection used to execute all_reduce operation. Supported collections incude `worker` , `server` and `all` . The default is `worker` .

        Returns:
            output(Numpy.array|None): A numpy array with the same shape as the `input` .

        Examples:
            .. code-block:: python

                # Save the following code in `train.py` , and then execute the command `fleetrun --server_num 2 --worker_num 2 train.py` .
                import paddle.distributed.fleet as fleet
                from paddle.distributed.fleet import PaddleCloudRoleMaker
                import sys
                import numpy as np
81 82 83
                import os

                os.environ["PADDLE_WITH_GLOO"] = "2"
84 85 86 87 88 89 90 91 92 93

                def train():
                    role = PaddleCloudRoleMaker(
                        is_collective=False,
                        init_gloo=True,
                        path="./tmp_gloo")
                    fleet.init(role)

                    if fleet.is_server():
                        input = [1, 2]
94
                        output = fleet.util.all_reduce(input, "sum", "server")
95 96 97 98
                        print(output)
                        # [2, 4]
                    elif fleet.is_worker():
                        input = np.array([3, 4])
99
                        output = fleet.util.all_reduce(input, "sum", "worker")
100 101
                        print(output)
                        # [6, 8]
102
                    output = fleet.util.all_reduce(input, "sum", "all")
103 104 105 106 107
                    print(output)
                    # [8, 12]
                if __name__ == "__main__":
                    train()
        """
108
        return self.role_maker._all_reduce(input, mode, comm_world)
109 110

    def barrier(self, comm_world="worker"):
111 112 113 114 115 116 117 118 119
        """
        Barrier between specified collection.

        Args:
            comm_world (str, optional): Collection used to execute barrier operation. Supported collections incude `worker` , `server` and `all` . The default is `worker` .

        Examples:

            .. code-block:: python
120

121 122 123 124 125
                # Save the following code in `train.py` , and then execute the command `fleetrun --server_num 2 --worker_num 2 train.py` .

                import paddle.distributed.fleet as fleet
                from paddle.distributed.fleet import PaddleCloudRoleMaker
                import sys
126 127 128
                import os

                os.environ["PADDLE_WITH_GLOO"] = "2"
129 130 131 132 133 134 135 136 137

                def train():
                    role = PaddleCloudRoleMaker(
                        is_collective=False,
                        init_gloo=True,
                        path="./tmp_gloo")
                    fleet.init(role)

                    if fleet.is_server():
138
                        fleet.util.barrier("server")
139 140
                        print("all server arrive here")
                    elif fleet.is_worker():
141
                        fleet.util.barrier("worker")
142
                        print("all server arrive here")
143
                    fleet.util.barrier("all")
144 145 146 147 148
                    print("all servers and workers arrive here")

                if __name__ == "__main__":
                    train()
        """
149
        self.role_maker._barrier(comm_world)
150 151

    def all_gather(self, input, comm_world="worker"):
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        """
        All gather `input` between specified collection.

        Args:
            input (Int|Float): The input variable to do all_gather between specified collection.
            comm_world (str, optional): Collection used to execute all_reduce operation. Supported collections incude `worker` , `server` and `all` . The default is `worker` .

        Returns:
            output (List): A list of gathered values.

        Examples:

            .. code-block:: python

                # Save the following code in `train.py` , and then execute the command `fleetrun --server_num 2 --worker_num 2 train.py` .
                import paddle.distributed.fleet as fleet
                from paddle.distributed.fleet import PaddleCloudRoleMaker
                import sys
170 171 172
                import os

                os.environ["PADDLE_WITH_GLOO"] = "2"
173 174 175 176 177 178 179 180 181 182

                def train():
                    role = PaddleCloudRoleMaker(
                        is_collective=False,
                        init_gloo=True,
                        path="./tmp_gloo")
                    fleet.init(role)

                    if fleet.is_server():
                        input = fleet.server_index()
183
                        output = fleet.util.all_gather(input, "server")
184 185 186 187
                        print(output)
                        # output = [0, 1]
                    elif fleet.is_worker():
                        input = fleet.worker_index()
188
                        output = fleet.util.all_gather(input, "worker")
189 190
                        # output = [0, 1]
                        print(output)
191
                    output = fleet.util.all_gather(input, "all")
192 193 194 195 196 197
                    print(output)
                    # output = [0, 1, 0, 1]

                if __name__ == "__main__":
                    train()
        """
198 199

        return self.role_maker._all_gather(input, comm_world)
200

201
    def _broadcast(self):
202 203
        pass

204
    def _scatter(self):
205 206
        pass

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    def get_heter_file_shard(self, files):
        if not isinstance(files, list):
            raise TypeError("files should be a list of file need to be read.")
        trainers = self.role_maker._worker_num()
        trainer_id = self.role_maker._worker_index() - trainers
        remainder = len(files) % trainers
        blocksize = int(len(files) / trainers)

        blocks = [blocksize] * trainers
        for i in range(remainder):
            blocks[i] += 1

        trainer_files = [[]] * trainers
        begin = 0
        for i in range(trainers):
222
            trainer_files[i] = files[begin : begin + blocks[i]]
223 224 225 226
            begin += blocks[i]

        return trainer_files[trainer_id]

227
    def get_file_shard(self, files):
228
        """
229 230 231 232 233 234 235 236
        Split files before distributed training, and return filelist assigned to the current trainer.

        .. code-block:: text

            example 1: files is [a, b, c ,d, e]  and trainer_num = 2, then trainer
                    0 gets [a, b, c] and trainer 1 gets [d, e].
            example 2: files is [a, b], and trainer_num = 3, then trainer 0 gets
                    [a], trainer 1 gets [b],  trainer 2 gets []
237

238
        Args:
239
            files(list): File list need to be read.
240

241
        Returns:
242 243 244 245 246 247
            List: Files belong to this worker.

        Examples:

            .. code-block:: python

248 249
                import paddle.distributed.fleet as fleet
                from paddle.distributed.fleet import UserDefinedRoleMaker
250

251
                role = UserDefinedRoleMaker(
252 253 254
                    is_collective=False,
                    init_gloo=False,
                    current_id=0,
255
                    role=fleet.Role.WORKER,
256 257
                    worker_endpoints=["127.0.0.1:6003", "127.0.0.1:6004"],
                    server_endpoints=["127.0.0.1:6001", "127.0.0.1:6002"])
258 259 260 261
                fleet.init(role)

                files = fleet.util.get_file_shard(["file1", "file2", "file3"])
                print(files)
262
                # files = ["file1", "file2"]
263 264 265
        """
        if not isinstance(files, list):
            raise TypeError("files should be a list of file need to be read.")
266

267 268
        trainer_id = self.role_maker._worker_index()
        trainers = self.role_maker._worker_num()
269

270 271
        remainder = len(files) % trainers
        blocksize = int(len(files) / trainers)
272

273 274 275
        blocks = [blocksize] * trainers
        for i in range(remainder):
            blocks[i] += 1
276

277 278 279
        trainer_files = [[]] * trainers
        begin = 0
        for i in range(trainers):
280
            trainer_files[i] = files[begin : begin + blocks[i]]
281 282 283 284 285
            begin += blocks[i]

        return trainer_files[trainer_id]

    def print_on_rank(self, message, rank_id):
286
        """
287
        Woker of rank `rank_id` print some message.
288 289 290 291 292 293 294 295 296

        Args:
            message(str): Log to be printed.
            rank_id(int): trainer id.

        Examples:

            .. code-block:: python

297 298
                import paddle.distributed.fleet as fleet
                from paddle.distributed.fleet import UserDefinedRoleMaker
299

300
                role = UserDefinedRoleMaker(
301 302 303
                    is_collective=False,
                    init_gloo=False,
                    current_id=0,
304
                    role=fleet.Role.WORKER,
305 306
                    worker_endpoints=["127.0.0.1:6003", "127.0.0.1:6004"],
                    server_endpoints=["127.0.0.1:6001", "127.0.0.1:6002"])
307 308 309
                fleet.init(role)

                fleet.util.print_on_rank("I'm worker 0", 0)
310
        """
311
        if self.role_maker._worker_index() != rank_id:
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
            return
        print(message)

    def _save_program(self, program, model_filename='__model__', is_text=False):
        if is_text:
            with open(model_filename, "w") as f:
                f.write(str(program))
        else:
            with open(model_filename, "wb") as f:
                f.write(program.desc.serialize_to_string())

    def _load_program(self, path, is_text):
        def load_program_binary(path):
            """load program from binary string file"""
            with open(path, "rb") as f:
                program_desc_str = f.read()
            return Program.parse_from_string(program_desc_str)

        def load_program_text(path):
            """load program from human-readable text file"""
            with open(path, "r") as f:
                program_desc_text = f.read()

            prog_desc = framework_pb2.ProgramDesc()
            text_format.Merge(program_desc_text, prog_desc)
            return Program.parse_from_string(prog_desc.SerializeToString())

        if is_text:
            return load_program_text(path)
        else:
            return load_program_binary(path)

    def _program_type_trans(self, prog_dir, prog_fn, is_text):
        prog = self._load_program(os.path.join(prog_dir, prog_fn), is_text)
        prog_out_fn = prog_fn + ".bin" if is_text else prog_fn + ".pbtxt"
347 348 349
        self._save_program(
            prog, os.path.join(prog_dir, prog_out_fn), 1 - is_text
        )
350 351 352 353 354 355 356 357
        return prog_out_fn

    def _visualize_graphviz(self, program, output_dir, output_filename):
        block = program.global_block()
        dot_path = os.path.join(output_dir, output_filename + '.dot')
        pdf_path = os.path.join(output_dir, output_filename + '.pdf')
        debugger.draw_block_graphviz(block, path=dot_path)
        cmd = ["dot", "-Tpdf", dot_path, "-o", pdf_path]
358 359 360 361 362 363
        p = subprocess.Popen(
            cmd,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
364 365 366
        p.wait()

    def _proto_check(self, config):
367 368 369 370 371 372
        train_prog = self._load_program(
            config.train_prog_path, config.is_text_train_program
        )
        pruned_prog = self._load_program(
            config.pruned_prog_path, config.is_text_pruned_program
        )
373 374 375

        is_match = True

376 377 378 379 380
        pruned_vars = [
            (v.name, v)
            for v in pruned_prog.list_vars()
            if fluid.io.is_persistable(v)
        ]
381 382 383 384 385 386
        pruned_vars = OrderedDict(pruned_vars)
        pruned_vars_name = [name for name in pruned_vars]
        print("persistable vars in pruned program: {}".format(pruned_vars_name))

        # feed and fetch op is added in pruned program when pruning, not need to be found in train program
        feed_fetch_type_list = [
387 388
            core.VarDesc.VarType.FEED_MINIBATCH,
            core.VarDesc.VarType.FETCH_LIST,
389 390 391 392 393 394 395 396 397 398 399 400
        ]

        for var_name in pruned_vars:
            var = pruned_vars[var_name]
            # feed and fetch op is added in pruned program when pruning, not need to be found in train program
            if var.type in feed_fetch_type_list:
                break
            try:
                train_prog_var = train_prog.global_block().var(var_name)
            except ValueError as e:
                print(
                    "Not find variable '%s' in train program. please check pruning."
401 402
                    % var_name
                )
403 404
                is_match = False
                continue
405 406 407 408
            if (
                var.shape != train_prog_var.shape
                or var.dtype != train_prog_var.dtype
            ):
409
                print(
410 411 412 413 414 415 416 417
                    "variable: {} not match. in pruned program shape: {} dtype:{}, in train program shape: {} dtype: {}".format(
                        var_name,
                        var.shape,
                        var.dtype,
                        train_prog_var.shape,
                        train_prog_var.dtype,
                    )
                )
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
                is_match = False
        return is_match

    def _params_check(self, config):
        def feed_gen(batch_size, feeded_vars_dims, feeded_vars_filelist):
            def reader(batch_size, fn, dim):
                data = []
                if isinstance(dim, list) or isinstance(dim, tuple):
                    shape = list(dim)
                    _temp = 1
                    for x in dim:
                        _temp = _temp * x
                    dim = _temp
                else:
                    shape = [dim]

                shape = [batch_size] + shape
                dim = dim * batch_size

                for line in open(fn, 'r'):
                    fields = line.strip().split(' ')
                    fields = [float(d) for d in fields]
                    while len(fields) >= dim:
                        tmp = fields[:dim]
                        fields = fields[dim:]
                        data.append(np.array(tmp).reshape(shape))
                return data

            batch_feed = []
            for i, fn in enumerate(feeded_vars_filelist):
                batch_feed.append(reader(batch_size, fn, feeded_vars_dims[i]))
            return batch_feed

        prog = self._load_program(
            os.path.join(config.dump_model_dir, config.dump_program_filename),
453 454
            config.is_text_dump_program,
        )
455 456
        if config.is_text_dump_program:
            model_filename = self._program_type_trans(
457 458 459 460
                config.dump_model_dir,
                config.dump_program_filename,
                config.is_text_dump_program,
            )
461 462 463 464

        saved_params = [
            v for v in prog.list_vars() if fluid.io.is_persistable(v)
        ]
465 466 467 468 469
        print(
            "persistable vars in dump program: {}".format(
                [v.name for v in saved_params]
            )
        )
470 471 472 473

        def check_not_expected_ops(prog, not_expected_op_types):
            op_types_set = set()
            for op in prog.global_block().ops:
474 475 476 477
                if (
                    op.type in not_expected_op_types
                    and op.type not in op_types_set
                ):
478 479 480 481 482 483
                    op_types_set.add(op.type)
            return op_types_set

        not_expected_op_types = check_not_expected_ops(prog, ["lookup_table"])
        if len(not_expected_op_types) > 0:
            print(
484 485 486 487
                "find op type '{}' in program, please check if your program is pruned correctly !".format(
                    list(not_expected_op_types)
                )
            )
488 489 490 491 492 493
            return False

        place = fluid.CPUPlace()
        exe = fluid.Executor(place)
        scope = fluid.core.Scope()
        with fluid.scope_guard(scope):
494 495 496 497 498 499 500 501 502 503
            (
                inference_program,
                feed_target_names,
                fetch_targets,
            ) = fluid.io.load_inference_model(
                config.dump_model_dir,
                exe,
                model_filename=model_filename,
                params_filename=config.save_params_filename,
            )
504 505 506 507 508 509 510 511 512 513

            # check program vars and saved vars shape
            orig_para_shape = {
                each_var.name: tuple(each_var.desc.shape())
                for each_var in saved_params
            }
            for each_var in saved_params:
                var_temp = fluid.global_scope().find_var(each_var.name)
                assert var_temp != None, "can't not find var: " + each_var.name
                new_shape = (np.array(var_temp.get_tensor())).shape
514 515 516
                assert each_var.name in orig_para_shape, (
                    each_var.name + "MUST in var list"
                )
517 518 519 520
                orig_shape = orig_para_shape.get(each_var.name)
                if new_shape != orig_shape:
                    raise RuntimeError(
                        "Shape not matching: the Program requires a parameter with a shape of ({}), "
521 522 523 524
                        "while the loaded parameter (namely [ {} ]) has a shape of  ({}).".format(
                            orig_shape, each_var.name, new_shape
                        )
                    )
525 526 527 528 529 530 531 532 533 534 535

            # check feed/fetch vars in program and config
            feed_config = config.feed_config
            fetch_config = config.fetch_config
            fetch_targets_names = [v.name for v in fetch_targets]
            if not feed_target_names:
                print("warning! no feed targets in program.")
            if not fetch_targets_names:
                print("warning! no fetch targets in program.")
            fetch_list = fetch_targets
            feed_name_list = feed_target_names
536 537 538 539
            if (
                feed_config.feeded_vars_names is not None
                and feed_target_names != feed_config.feeded_vars_names
            ):
540
                print(
541 542 543 544
                    "warning! feed vars in program and config are diff: feed in program: {}. feed in config {}.".format(
                        feed_target_names, feed_config.feeded_vars_names
                    )
                )
545 546 547 548 549 550 551 552 553 554
                feed_name_list = feed_config.feeded_vars_names
                # remove feed op in inference_program. new feed op will be added in exe.run
                global_block = inference_program.global_block()
                need_to_remove_op_index = []
                for i, op in enumerate(global_block.ops):
                    op.desc.set_is_target(False)
                    if op.type == "feed":  # only remove feed op here
                        need_to_remove_op_index.append(i)
                for index in need_to_remove_op_index[::-1]:
                    global_block._remove_op(index)
555 556 557 558
            if (
                fetch_config.fetch_vars_names is not None
                and fetch_targets_names != fetch_config.fetch_vars_names
            ):
559
                print(
560 561 562 563
                    "warning! fetch vars in program and config are diff: fetch in program: {}. fetch in config {}.".format(
                        fetch_targets_names, fetch_config.fetch_vars_names
                    )
                )
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
                fetch_list = [
                    inference_program.global_block().var(i)
                    for i in fetch_config.fetch_vars_names
                ]
                # remove fetch op in inference_program. new fetch op will be added in exe.run
                global_block = inference_program.global_block()
                need_to_remove_op_index = []
                for i, op in enumerate(global_block.ops):
                    op.desc.set_is_target(False)
                    if op.type == "fetch":  # only remove fetch op here
                        need_to_remove_op_index.append(i)
                for index in need_to_remove_op_index[::-1]:
                    global_block._remove_op(index)

            # if fetch_list have lod tensor
            return_numpy = all([v.lod_level == 0 for v in fetch_list])

            # try dump fetch_targets
            feed_tensors = []
583 584 585 586 587
            assert (
                len(feed_config.feeded_vars_names)
                == len(feed_config.feeded_vars_dims)
                == len(feed_config.feeded_vars_types)
            )
588 589 590
            # check program vars and feed tensor shape in config
            for i in range(len(feed_config.feeded_vars_names)):
                var = inference_program.global_block().var(
591 592 593 594 595 596
                    feed_config.feeded_vars_names[i]
                )
                if not isinstance(
                    feed_config.feeded_vars_dims[i], (list, tuple)
                ):
                    tensor_shape = (feed_config.feeded_vars_dims[i],)
597 598 599 600 601 602
                else:
                    tensor_shape = tuple(feed_config.feeded_vars_dims[i])
                feed_config.feeded_vars_dims[i] = tensor_shape
                var_shape = var.shape[1:]
                if tensor_shape != var_shape:
                    raise RuntimeError(
603 604 605 606 607 608
                        "feed variable '{}' shape not match. infer program  shape: {}. feed tensor shape: {}".format(
                            feed_config.feeded_vars_names[i],
                            var_shape,
                            tensor_shape,
                        )
                    )
609 610 611 612 613

            if not feed_config.feeded_vars_filelist:
                print("generate random feed vars.")
                for i in range(len(feed_config.feeded_vars_names)):
                    var = inference_program.global_block().var(
614 615
                        feed_config.feeded_vars_names[i]
                    )
616 617 618
                    # create fake feed tensor. if lod_level > 1, should create_lod_tensor()
                    if var.lod_level == 0:
                        feed_tensors.append(
619 620 621 622 623 624 625 626 627 628
                            np.array(
                                np.random.random(
                                    tuple(
                                        [config.batch_size]
                                        + list(feed_config.feeded_vars_dims[i])
                                    )
                                ),
                                dtype=feed_config.feeded_vars_types[i],
                            )
                        )
629
                    elif var.lod_level == 1:
630 631 632 633 634 635 636 637 638
                        t = np.array(
                            np.random.random(
                                tuple(
                                    [config.batch_size]
                                    + list(feed_config.feeded_vars_dims[i])
                                )
                            ),
                            dtype=feed_config.feeded_vars_types[i],
                        )
639
                        feed_tensors.append(
640 641 642 643
                            fluid.create_lod_tensor(
                                t, [[1] * config.batch_size], place
                            )
                        )
644 645 646 647
                    else:
                        raise RuntimeError(
                            "vars with lod_level >= 2 is not supported now in this infer program check tool."
                        )
648 649 650 651 652 653 654 655 656
                results = exe.run(
                    inference_program,
                    feed={
                        name: feed_tensors[i]
                        for i, name in enumerate(feed_name_list)
                    },
                    fetch_list=fetch_list,
                    return_numpy=return_numpy,
                )
657
            else:
658 659 660 661 662
                print(
                    "load feed vars from files: {}.".format(
                        feed_config.feeded_vars_filelist
                    )
                )
663 664
                feed_vars = [
                    inference_program.global_block().var(
665 666
                        feed_config.feeded_vars_names[i]
                    )
667 668 669
                    for i in range(len(feed_config.feeded_vars_names))
                ]
                feeder = fluid.DataFeeder(feed_list=feed_vars, place=place)
670 671 672 673 674
                batch_feed = feed_gen(
                    config.batch_size,
                    feed_config.feeded_vars_dims,
                    feed_config.feeded_vars_filelist,
                )
675
                slots = [batch_feed]
676 677 678 679 680 681
                results = exe.run(
                    inference_program,
                    feed=feeder.feed(slots),
                    fetch_list=fetch_list,
                    return_numpy=return_numpy,
                )
682 683 684 685
            for i, v in enumerate(fetch_list):
                print("fetch_targets name: %s" % v.name)
                print("fetch_targets: {}".format(results[i]))
            return results