util_factory.py 26.3 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 20 21 22 23 24 25
import os
import subprocess
from collections import OrderedDict

import numpy as np
from google.protobuf import text_format

W
wangxiaoning 已提交
26
import paddle
27 28
import paddle.framework as framework
from paddle.fluid import core, debugger
29
from paddle.fluid.proto import framework_pb2
W
wangxiaoning 已提交
30
from paddle.static import Program
31 32

from ..utils.fs import FS
33 34

__all__ = []
35

36

37
class UtilFactory:
38
    def _create_util(self, context=None):
39
        util = UtilBase()
40 41 42 43
        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"])
44 45 46
        return util


47
class UtilBase:
48 49 50 51 52 53 54 55 56
    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
57

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

64
    def all_reduce(self, input, mode="sum", comm_world="worker"):
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
        """
        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
84 85 86
                import os

                os.environ["PADDLE_WITH_GLOO"] = "2"
87 88 89 90 91 92 93 94 95 96

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

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

    def barrier(self, comm_world="worker"):
114 115 116 117 118 119 120 121 122
        """
        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
123

124 125 126 127 128
                # 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
129 130 131
                import os

                os.environ["PADDLE_WITH_GLOO"] = "2"
132 133 134 135 136 137 138 139 140

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

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

                if __name__ == "__main__":
                    train()
        """
152
        self.role_maker._barrier(comm_world)
153 154

    def all_gather(self, input, comm_world="worker"):
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
        """
        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
173 174 175
                import os

                os.environ["PADDLE_WITH_GLOO"] = "2"
176 177 178 179 180 181 182 183 184 185

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

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

                if __name__ == "__main__":
                    train()
        """
201 202

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

204
    def _broadcast(self):
205 206
        pass

207
    def _scatter(self):
208 209
        pass

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
    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):
225
            trainer_files[i] = files[begin : begin + blocks[i]]
226 227 228 229
            begin += blocks[i]

        return trainer_files[trainer_id]

230
    def get_file_shard(self, files):
231
        """
232 233 234 235 236 237 238 239
        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 []
240

241
        Args:
242
            files(list): File list need to be read.
243

244
        Returns:
245 246 247 248 249 250
            List: Files belong to this worker.

        Examples:

            .. code-block:: python

251 252
                import paddle.distributed.fleet as fleet
                from paddle.distributed.fleet import UserDefinedRoleMaker
253

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

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

270 271
        trainer_id = self.role_maker._worker_index()
        trainers = self.role_maker._worker_num()
272

273 274
        remainder = len(files) % trainers
        blocksize = int(len(files) / trainers)
275

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

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

        return trainer_files[trainer_id]

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

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

        Examples:

            .. code-block:: python

300 301
                import paddle.distributed.fleet as fleet
                from paddle.distributed.fleet import UserDefinedRoleMaker
302

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

                fleet.util.print_on_rank("I'm worker 0", 0)
313
        """
314
        if self.role_maker._worker_index() != rank_id:
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 347 348 349
            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"
350 351 352
        self._save_program(
            prog, os.path.join(prog_dir, prog_out_fn), 1 - is_text
        )
353 354 355 356 357 358 359 360
        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]
361 362 363 364 365 366
        p = subprocess.Popen(
            cmd,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
367 368 369
        p.wait()

    def _proto_check(self, config):
370 371 372 373 374 375
        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
        )
376 377 378

        is_match = True

379 380 381
        pruned_vars = [
            (v.name, v)
            for v in pruned_prog.list_vars()
W
wangxiaoning 已提交
382
            if paddle.static.io.is_persistable(v)
383
        ]
384 385 386 387 388 389
        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 = [
390 391
            core.VarDesc.VarType.FEED_MINIBATCH,
            core.VarDesc.VarType.FETCH_LIST,
392 393 394 395 396 397 398 399 400 401 402 403
        ]

        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."
404 405
                    % var_name
                )
406 407
                is_match = False
                continue
408 409 410 411
            if (
                var.shape != train_prog_var.shape
                or var.dtype != train_prog_var.dtype
            ):
412
                print(
413 414 415 416 417 418 419 420
                    "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,
                    )
                )
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 453 454 455
                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),
456 457
            config.is_text_dump_program,
        )
458 459
        if config.is_text_dump_program:
            model_filename = self._program_type_trans(
460 461 462 463
                config.dump_model_dir,
                config.dump_program_filename,
                config.is_text_dump_program,
            )
464 465

        saved_params = [
W
wangxiaoning 已提交
466
            v for v in prog.list_vars() if paddle.static.io.is_persistable(v)
467
        ]
468 469 470 471 472
        print(
            "persistable vars in dump program: {}".format(
                [v.name for v in saved_params]
            )
        )
473 474 475 476

        def check_not_expected_ops(prog, not_expected_op_types):
            op_types_set = set()
            for op in prog.global_block().ops:
477 478 479 480
                if (
                    op.type in not_expected_op_types
                    and op.type not in op_types_set
                ):
481 482 483 484 485 486
                    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(
487 488 489 490
                "find op type '{}' in program, please check if your program is pruned correctly !".format(
                    list(not_expected_op_types)
                )
            )
491 492
            return False

W
wangxiaoning 已提交
493 494 495 496
        place = framework.CPUPlace()
        exe = paddle.static.Executor(place)
        scope = paddle.static.Scope()
        with paddle.static.scope_guard(scope):
497 498 499 500
            (
                inference_program,
                feed_target_names,
                fetch_targets,
501
            ) = paddle.distributed.io.load_inference_model_distributed(
502 503 504 505 506
                config.dump_model_dir,
                exe,
                model_filename=model_filename,
                params_filename=config.save_params_filename,
            )
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:
W
wangxiaoning 已提交
514
                var_temp = paddle.static.global_scope().find_var(each_var.name)
515 516 517
                assert var_temp is not None, (
                    "can't not find var: " + each_var.name
                )
518
                new_shape = (np.array(var_temp.get_tensor())).shape
519 520 521
                assert each_var.name in orig_para_shape, (
                    each_var.name + "MUST in var list"
                )
522 523 524 525
                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 ({}), "
526 527 528 529
                        "while the loaded parameter (namely [ {} ]) has a shape of  ({}).".format(
                            orig_shape, each_var.name, new_shape
                        )
                    )
530 531 532 533 534 535 536 537 538 539 540

            # 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
541 542 543 544
            if (
                feed_config.feeded_vars_names is not None
                and feed_target_names != feed_config.feeded_vars_names
            ):
545
                print(
546 547 548 549
                    "warning! feed vars in program and config are diff: feed in program: {}. feed in config {}.".format(
                        feed_target_names, feed_config.feeded_vars_names
                    )
                )
550 551 552 553 554 555 556 557 558 559
                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)
560 561 562 563
            if (
                fetch_config.fetch_vars_names is not None
                and fetch_targets_names != fetch_config.fetch_vars_names
            ):
564
                print(
565 566 567 568
                    "warning! fetch vars in program and config are diff: fetch in program: {}. fetch in config {}.".format(
                        fetch_targets_names, fetch_config.fetch_vars_names
                    )
                )
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
                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 = []
588 589 590 591 592
            assert (
                len(feed_config.feeded_vars_names)
                == len(feed_config.feeded_vars_dims)
                == len(feed_config.feeded_vars_types)
            )
593 594 595
            # 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(
596 597 598 599 600 601
                    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],)
602 603 604 605 606 607
                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(
608 609 610 611 612 613
                        "feed variable '{}' shape not match. infer program  shape: {}. feed tensor shape: {}".format(
                            feed_config.feeded_vars_names[i],
                            var_shape,
                            tensor_shape,
                        )
                    )
614 615 616 617 618

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