fleet_util.py 83.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
#   Copyright (c) 2019 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.
14
"""Fleet Utils."""
15 16

import collections
T
Thunderbrook 已提交
17
import copy
18 19 20 21 22 23 24 25
import json
import logging
import math
import numpy as np
import os
import sys
import time
import paddle.fluid as fluid
T
Thunderbrook 已提交
26
from paddle.fluid import core
27
from paddle.fluid.log_helper import get_logger
28
from paddle.distributed.fleet.utils.fs import LocalFS, HDFSClient, AFSClient
29
from . import utils
30

T
Thunderbrook 已提交
31
OpRole = core.op_proto_and_checker_maker.OpRole
32

33
__all__ = ["FleetUtil", "GPUPSUtil"]
34

35 36 37
_logger = get_logger(
    __name__, logging.INFO, fmt='%(asctime)s %(levelname)s: %(message)s'
)
38

T
Thunderbrook 已提交
39
fleet = None
40

41

42
class FleetUtil:
43 44 45 46 47 48 49 50 51 52 53 54
    """
    FleetUtil provides some common functions for users' convenience.

    Examples:
        .. code-block:: python

          from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
          fleet_util = FleetUtil()
          fleet_util.rank0_print("my log")

    """

55 56
    def __init__(self, mode="pslib"):
        global fleet
T
Thunderbrook 已提交
57 58
        op_maker = core.op_proto_and_checker_maker
        self.op_role_key = op_maker.kOpRoleAttrName()
59
        if mode == "pslib":
60
            from paddle.incubate.fleet.parameter_server.pslib import (
61 62 63
                fleet as fleet_pslib,
            )

64 65
            fleet = fleet_pslib
        elif mode == "transpiler":
W
wangzhen38 已提交
66
            from paddle.incubate.fleet.parameter_server.distribute_transpiler import (
67 68 69
                fleet as fleet_transpiler,
            )

70 71 72
            fleet = fleet_transpiler
        else:
            raise ValueError(
73 74
                "Please choose one mode from [\"pslib\", \"transpiler\"]"
            )
75

76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    def rank0_print(self, s):
        """
        Worker of rank 0 print some log.

        Args:
            s(str): string to print

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.rank0_print("my log")

        """
        if fleet.worker_index() != 0:
            return
        print(s)
        sys.stdout.flush()

    def rank0_info(self, s):
        """
        Worker of rank 0 print some log info.

        Args:
            s(str): string to log

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.rank0_info("my log info")

        """
        if fleet.worker_index() != 0:
            return
        _logger.info(s)

    def rank0_error(self, s):
        """
        Worker of rank 0 print some log error.

        Args:
            s(str): string to log

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.rank0_error("my log error")

        """
        if fleet.worker_index() != 0:
            return
        _logger.error(s)

134 135 136 137 138 139 140
    def set_zero(
        self,
        var_name,
        scope=fluid.global_scope(),
        place=fluid.CPUPlace(),
        param_type="int64",
    ):
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
        """
        Set tensor of a Variable to zero.

        Args:
            var_name(str): name of Variable
            scope(Scope): Scope object, default is fluid.global_scope()
            place(Place): Place object, default is fluid.CPUPlace()
            param_type(str): param data type, default is int64

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.set_zero(myvar.name, myscope)

        """
        param = scope.var(var_name).get_tensor()
        param_array = np.zeros(param._get_dims()).astype(param_type)
        param.set(param_array, place)

162 163 164 165 166 167 168
    def print_global_auc(
        self,
        scope=fluid.global_scope(),
        stat_pos="_generated_var_2",
        stat_neg="_generated_var_3",
        print_prefix="",
    ):
169
        r"""
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
        Print global auc of all distributed workers.

        Args:
            scope(Scope): Scope object, default is fluid.global_scope()
            stat_pos(str): name of auc pos bucket Variable
            stat_neg(str): name of auc neg bucket Variable
            print_prefix(str): prefix of print auc

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.print_global_auc(myscope, stat_pos=stat_pos.name,
                                          stat_neg=stat_neg.name)

              # below is part of model
              emb = my_slot_net(slots, label) # emb can be fc layer of size 1
188
              similarity_norm = fluid.layers.sigmoid(paddle.clip(\
189 190
                  emb, min=-15.0, max=15.0), name="similarity_norm")\
              binary_predict = fluid.layers.concat(input=[\
H
HongyuJia 已提交
191
                  paddle.subtract(\
192 193 194
                      fluid.layers.ceil(similarity_norm), similarity_norm),\
                  similarity_norm], axis=1)
              auc, batch_auc, [batch_stat_pos, batch_stat_neg, stat_pos, \
195
                  stat_neg] = paddle.static.auc(input=binary_predict,\
196 197 198 199 200 201 202
                                               label=label, curve='ROC',\
                                               num_thresholds=4096)

        """
        auc_value = self.get_global_auc(scope, stat_pos, stat_neg)
        self.rank0_print(print_prefix + " global auc = %s" % auc_value)

203 204 205 206 207 208
    def get_global_auc(
        self,
        scope=fluid.global_scope(),
        stat_pos="_generated_var_2",
        stat_neg="_generated_var_3",
    ):
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
        """
        Get global auc of all distributed workers.

        Args:
            scope(Scope): Scope object, default is fluid.global_scope()
            stat_pos(str): name of auc pos bucket Variable
            stat_neg(str): name of auc neg bucket Variable

        Returns:
            auc_value(float), total_ins_num(int)

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              auc_value, _ = fleet_util.get_global_auc(myscope,
                                                       stat_pos=stat_pos,
                                                       stat_neg=stat_neg)

        """
        if scope.find_var(stat_pos) is None or scope.find_var(stat_neg) is None:
            self.rank0_print("not found auc bucket")
            return None
        fleet._role_maker._barrier_worker()
        # auc pos bucket
        pos = np.array(scope.find_var(stat_pos).get_tensor())
        # auc pos bucket shape
        old_pos_shape = np.array(pos.shape)
        # reshape to one dim
        pos = pos.reshape(-1)
        global_pos = np.copy(pos) * 0
        # mpi allreduce
X
xujiaqi01 已提交
242
        fleet._role_maker._all_reduce(pos, global_pos)
243 244 245 246 247 248 249 250
        # reshape to its original shape
        global_pos = global_pos.reshape(old_pos_shape)

        # auc neg bucket
        neg = np.array(scope.find_var(stat_neg).get_tensor())
        old_neg_shape = np.array(neg.shape)
        neg = neg.reshape(-1)
        global_neg = np.copy(neg) * 0
X
xujiaqi01 已提交
251
        fleet._role_maker._all_reduce(neg, global_neg)
252 253 254 255 256 257 258 259 260 261
        global_neg = global_neg.reshape(old_neg_shape)

        # calculate auc
        num_bucket = len(global_pos[0])
        area = 0.0
        pos = 0.0
        neg = 0.0
        new_pos = 0.0
        new_neg = 0.0
        total_ins_num = 0
262
        for i in range(num_bucket):
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 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
            index = num_bucket - 1 - i
            new_pos = pos + global_pos[0][index]
            total_ins_num += global_pos[0][index]
            new_neg = neg + global_neg[0][index]
            total_ins_num += global_neg[0][index]
            area += (new_neg - neg) * (pos + new_pos) / 2
            pos = new_pos
            neg = new_neg

        auc_value = None
        if pos * neg == 0 or total_ins_num == 0:
            auc_value = 0.5
        else:
            auc_value = area / (pos * neg)

        fleet._role_maker._barrier_worker()
        return auc_value

    def load_fleet_model_one_table(self, table_id, path):
        """
        load pslib model to one table

        Args:
            table_id(int): load model to one table, default is None, which mean
                           load all table.
            path(str): model path

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.load_fleet_model("hdfs:/my/model/path", table_id=1)
        """
        fleet.load_one_table(table_id, path)

    def load_fleet_model(self, path, mode=0):
        """
        load pslib model

        Args:
            path(str): model path
            mode(str): 0 or 1, which means load checkpoint or delta model,
                       default is 0

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()

              fleet_util.load_fleet_model("hdfs:/my/model/path")

              fleet_util.load_fleet_model("hdfs:/my/model/path", mode=0)

        """
        fleet.init_server(path, mode=mode)

    def save_fleet_model(self, path, mode=0):
        """
        save pslib model

        Args:
            path(str): model path
            mode(str): 0 or 1, which means save checkpoint or delta model,
                       default is 0

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.save_fleet_model("hdfs:/my/model/path")

        """
        fleet.save_persistables(None, path, mode=mode)

340 341 342 343 344 345 346 347 348 349 350
    def _get_xbox_str(
        self,
        output_path,
        day,
        model_path,
        xbox_base_key,
        data_path,
        hadoop_fs_name,
        monitor_data={},
        mode="patch",
    ):
351
        xbox_dict = collections.OrderedDict()
352 353 354 355 356 357 358 359
        if mode == "base":
            xbox_dict["id"] = str(xbox_base_key)
        elif mode == "patch":
            xbox_dict["id"] = str(int(time.time()))
        else:
            print("warning: unknown mode %s, set it to patch" % mode)
            mode = "patch"
            xbox_dict["id"] = str(int(time.time()))
360
        xbox_dict["key"] = str(xbox_base_key)
361
        if model_path.startswith("hdfs:") or model_path.startswith("afs:"):
362
            model_path = model_path[model_path.find(":") + 1 :]
363
        xbox_dict["input"] = hadoop_fs_name + model_path.rstrip("/") + "/000"
364
        xbox_dict["record_count"] = "111111"
365
        xbox_dict["partition_type"] = "2"
366 367 368 369 370 371 372 373 374 375 376 377
        xbox_dict["job_name"] = "default_job_name"
        xbox_dict["ins_tag"] = "feasign"
        xbox_dict["ins_path"] = data_path
        job_id_with_host = os.popen("echo -n ${JOB_ID}").read().strip()
        instance_id = os.popen("echo -n ${INSTANCE_ID}").read().strip()
        start_pos = instance_id.find(job_id_with_host)
        end_pos = instance_id.find("--")
        if start_pos != -1 and end_pos != -1:
            job_id_with_host = instance_id[start_pos:end_pos]
        xbox_dict["job_id"] = job_id_with_host
        # currently hard code here, set monitor_data empty string
        xbox_dict["monitor_data"] = ""
378 379 380
        xbox_dict["monitor_path"] = (
            output_path.rstrip("/") + "/monitor/" + day + ".txt"
        )
381 382 383
        xbox_dict["mpi_size"] = str(fleet.worker_num())
        return json.dumps(xbox_dict)

384 385 386 387 388 389 390 391 392 393 394
    def write_model_donefile(
        self,
        output_path,
        day,
        pass_id,
        xbox_base_key,
        hadoop_fs_name,
        hadoop_fs_ugi,
        hadoop_home="$HADOOP_HOME",
        donefile_name="donefile.txt",
    ):
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
        """
        write donefile when save model

        Args:
            output_path(str): output path
            day(str|int): training day
            pass_id(str|int): training pass id
            xbox_base_key(str|int): xbox base key
            hadoop_fs_name(str): hdfs/afs fs name
            hadoop_fs_ugi(str): hdfs/afs fs ugi
            hadoop_home(str): hadoop home, default is "$HADOOP_HOME"
            donefile_name(str): donefile name, default is "donefile.txt"

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.write_model_donefile(output_path="hdfs:/my/output",
                                              model_path="hdfs:/my/model",
                                              day=20190723,
                                              pass_id=66,
                                              xbox_base_key=int(time.time()),
                                              hadoop_fs_name="hdfs://xxx",
                                              hadoop_fs_ugi="user,passwd")

        """
        day = str(day)
        pass_id = str(pass_id)
        xbox_base_key = int(xbox_base_key)

        if pass_id != "-1":
            suffix_name = "/%s/%s/" % (day, pass_id)
            model_path = output_path.rstrip("/") + suffix_name
        else:
            suffix_name = "/%s/0/" % day
            model_path = output_path.rstrip("/") + suffix_name

        if fleet.worker_index() == 0:
            donefile_path = output_path + "/" + donefile_name
435 436 437 438 439 440 441
            content = "%s\t%lu\t%s\t%s\t%d" % (
                day,
                xbox_base_key,
                model_path,
                pass_id,
                0,
            )
442 443
            configs = {
                "fs.default.name": hadoop_fs_name,
444
                "hadoop.job.ugi": hadoop_fs_ugi,
445 446 447 448 449 450 451 452 453
            }
            client = HDFSClient(hadoop_home, configs)
            if client.is_file(donefile_path):
                pre_content = client.cat(donefile_path)
                pre_content_list = pre_content.split("\n")
                day_list = [i.split("\t")[0] for i in pre_content_list]
                pass_list = [i.split("\t")[3] for i in pre_content_list]
                exist = False
                for i in range(len(day_list)):
454 455 456
                    if int(day) == int(day_list[i]) and int(pass_id) == int(
                        pass_list[i]
                    ):
457 458 459 460 461 462 463
                        exist = True
                        break
                if not exist:
                    with open(donefile_name, "w") as f:
                        f.write(pre_content + "\n")
                        f.write(content + "\n")
                    client.delete(donefile_path)
464
                    client.upload(donefile_name, output_path)
465 466 467
                    self.rank0_error(
                        "write %s/%s %s succeed" % (day, pass_id, donefile_name)
                    )
468
                else:
469 470 471 472
                    self.rank0_error(
                        "not write %s because %s/%s already "
                        "exists" % (donefile_name, day, pass_id)
                    )
473 474 475
            else:
                with open(donefile_name, "w") as f:
                    f.write(content + "\n")
476
                client.upload(donefile_name, output_path)
477 478 479
                self.rank0_error(
                    "write %s/%s %s succeed" % (day, pass_id, donefile_name)
                )
480 481
        fleet._role_maker._barrier_worker()

482 483 484 485 486 487 488 489 490 491 492 493 494
    def write_xbox_donefile(
        self,
        output_path,
        day,
        pass_id,
        xbox_base_key,
        data_path,
        hadoop_fs_name,
        hadoop_fs_ugi,
        monitor_data={},
        hadoop_home="$HADOOP_HOME",
        donefile_name=None,
    ):
495 496 497 498 499 500 501 502 503 504 505 506 507
        """
        write delta donefile or xbox base donefile

        Args:
            output_path(str): output path
            day(str|int): training day of model
            pass_id(str|int): training pass id of model
            xbox_base_key(str|int): xbox base key
            data_path(str|list): training data path
            hadoop_fs_name(str): hdfs/afs fs name
            hadoop_fs_ugi(str): hdfs/afs fs ugi
            monitor_data(dict): metrics
            hadoop_home(str): hadoop home, default is "$HADOOP_HOME"
508
            donefile_name(str): donefile name, default is None"
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.write_xbox_donefile(
                  output_path="hdfs:/my/output/",
                  model_path="hdfs:/my/output/20190722/01",
                  day=20190722,
                  pass_id=1,
                  xbox_base_key=int(time.time()),
                  data_path="hdfs:/my/data/",
                  hadoop_fs_name="hdfs://xxx",
                  hadoop_fs_ugi="user,passwd",
                  monitor_data={}
                  )

        """
        day = str(day)
        pass_id = str(pass_id)
        xbox_base_key = int(xbox_base_key)
531
        mode = None
532 533

        if pass_id != "-1":
534
            mode = "patch"
535 536
            suffix_name = "/%s/delta-%s/" % (day, pass_id)
            model_path = output_path.rstrip("/") + suffix_name
537 538
            if donefile_name is None:
                donefile_name = "xbox_patch_done.txt"
539
        else:
540
            mode = "base"
541 542
            suffix_name = "/%s/base/" % day
            model_path = output_path.rstrip("/") + suffix_name
543 544
            if donefile_name is None:
                donefile_name = "xbox_base_done.txt"
545 546 547 548 549 550

        if isinstance(data_path, list):
            data_path = ",".join(data_path)

        if fleet.worker_index() == 0:
            donefile_path = output_path + "/" + donefile_name
551 552 553 554 555 556 557 558 559 560
            xbox_str = self._get_xbox_str(
                output_path,
                day,
                model_path,
                xbox_base_key,
                data_path,
                hadoop_fs_name,
                monitor_data={},
                mode=mode,
            )
561 562
            configs = {
                "fs.default.name": hadoop_fs_name,
563
                "hadoop.job.ugi": hadoop_fs_ugi,
564 565 566 567 568 569 570 571
            }
            client = HDFSClient(hadoop_home, configs)
            if client.is_file(donefile_path):
                pre_content = client.cat(donefile_path)
                last_dict = json.loads(pre_content.split("\n")[-1])
                last_day = last_dict["input"].split("/")[-3]
                last_pass = last_dict["input"].split("/")[-2].split("-")[-1]
                exist = False
572 573 574 575 576
                if (
                    int(day) < int(last_day)
                    or int(day) == int(last_day)
                    and int(pass_id) <= int(last_pass)
                ):
577 578 579 580 581 582
                    exist = True
                if not exist:
                    with open(donefile_name, "w") as f:
                        f.write(pre_content + "\n")
                        f.write(xbox_str + "\n")
                    client.delete(donefile_path)
583
                    client.upload(donefile_name, output_path)
584 585 586
                    self.rank0_error(
                        "write %s/%s %s succeed" % (day, pass_id, donefile_name)
                    )
587
                else:
588 589 590 591
                    self.rank0_error(
                        "not write %s because %s/%s already "
                        "exists" % (donefile_name, day, pass_id)
                    )
592 593 594
            else:
                with open(donefile_name, "w") as f:
                    f.write(xbox_str + "\n")
595
                client.upload(donefile_name, output_path)
596 597 598
                self.rank0_error(
                    "write %s/%s %s succeed" % (day, pass_id, donefile_name)
                )
599 600
        fleet._role_maker._barrier_worker()

601 602 603 604 605 606 607 608 609 610 611 612
    def write_cache_donefile(
        self,
        output_path,
        day,
        pass_id,
        key_num,
        hadoop_fs_name,
        hadoop_fs_ugi,
        hadoop_home="$HADOOP_HOME",
        donefile_name="sparse_cache.meta",
        **kwargs
    ):
613 614 615 616 617 618 619 620 621 622 623 624
        """
        write cache donefile

        Args:
            output_path(str): output path
            day(str|int): training day of model
            pass_id(str|int): training pass id of model
            key_num(str|int): save cache return value
            hadoop_fs_name(str): hdfs/afs fs name
            hadoop_fs_ugi(str): hdfs/afs fs ugi
            hadoop_home(str): hadoop home, default is "$HADOOP_HOME"
            donefile_name(str): donefile name, default is "sparse_cache.meta"
625 626 627
            kwargs(dict): user defined properties
                          file_num(int): cache file num
                          table_id(int): cache table id
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.write_cache_donefile(
                  output_path="hdfs:/my/output/",
                  day=20190722,
                  pass_id=1,
                  key_num=123456,
                  hadoop_fs_name="hdfs://xxx",
                  hadoop_fs_ugi="user,passwd",
                  )

        """
        day = str(day)
        pass_id = str(pass_id)
        key_num = int(key_num)
647 648
        file_num = kwargs.get("file_num", 16)
        table_id = kwargs.get("table_id", 0)
649 650

        if pass_id != "-1":
651
            suffix_name = "/%s/delta-%s/%03d_cache" % (day, pass_id, table_id)
652 653
            model_path = output_path.rstrip("/") + suffix_name
        else:
654
            suffix_name = "/%s/base/%03d_cache" % (day, table_id)
655 656 657 658 659 660
            model_path = output_path.rstrip("/") + suffix_name

        if fleet.worker_index() == 0:
            donefile_path = model_path + "/" + donefile_name
            configs = {
                "fs.default.name": hadoop_fs_name,
661
                "hadoop.job.ugi": hadoop_fs_ugi,
662 663 664
            }
            client = HDFSClient(hadoop_home, configs)
            if client.is_file(donefile_path):
665 666 667
                self.rank0_error(
                    "not write because %s already exists" % donefile_path
                )
668
            else:
669 670 671 672
                meta_str = "file_prefix:part\npart_num:%s\nkey_num:%d\n" % (
                    file_num,
                    key_num,
                )
673 674
                with open(donefile_name, "w") as f:
                    f.write(meta_str)
675
                client.upload(donefile_name, model_path)
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
                self.rank0_error("write %s succeed" % donefile_path)
        fleet._role_maker._barrier_worker()

    def load_model(self, output_path, day, pass_id):
        """
        load pslib model

        Args:
            output_path(str): output path
            day(str|int): training day
            pass_id(str|int): training pass id

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.load_model("hdfs:/my/path", 20190722, 88)

        """
        day = str(day)
        pass_id = str(pass_id)
        suffix_name = "/%s/%s/" % (day, pass_id)
        load_path = output_path + suffix_name
        self.rank0_error("going to load_model %s" % load_path)
        self.load_fleet_model(load_path)
        self.rank0_error("load_model done")

    def save_model(self, output_path, day, pass_id):
        """
        save pslib model

        Args:
            output_path(str): output path
            day(str|int): training day
            pass_id(str|int): training pass id

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.save_model("hdfs:/my/path", 20190722, 88)

        """
        day = str(day)
        pass_id = str(pass_id)
        suffix_name = "/%s/%s/" % (day, pass_id)
        model_path = output_path + suffix_name
J
jiaqi 已提交
725
        self.rank0_print("going to save_model %s" % model_path)
726
        self.save_fleet_model(model_path)
J
jiaqi 已提交
727
        self.rank0_print("save_model done")
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747

    def save_batch_model(self, output_path, day):
        """
        save batch model

        Args:
            output_path(str): output path
            day(str|int): training day

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.save_batch_model("hdfs:/my/path", 20190722)

        """
        day = str(day)
        suffix_name = "/%s/0/" % day
        model_path = output_path + suffix_name
J
jiaqi 已提交
748
        self.rank0_print("going to save_model %s" % model_path)
749
        fleet.save_persistables(None, model_path, mode=3)
J
jiaqi 已提交
750
        self.rank0_print("save_batch_model done")
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772

    def save_delta_model(self, output_path, day, pass_id):
        """
        save delta model

        Args:
            output_path(str): output path
            day(str|int): training day
            pass_id(str|int): training pass id

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.save_batch_model("hdfs:/my/path", 20190722, 88)

        """
        day = str(day)
        pass_id = str(pass_id)
        suffix_name = "/%s/delta-%s/" % (day, pass_id)
        model_path = output_path + suffix_name
J
jiaqi 已提交
773
        self.rank0_print("going to save_delta_model %s" % model_path)
774
        fleet.save_persistables(None, model_path, mode=1)
J
jiaqi 已提交
775
        self.rank0_print("save_delta_model done")
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795

    def save_xbox_base_model(self, output_path, day):
        """
        save xbox base model

        Args:
            output_path(str): output path
            day(str|int): training day

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.save_xbox_base_model("hdfs:/my/path", 20190722, 88)

        """
        day = str(day)
        suffix_name = "/%s/base/" % day
        model_path = output_path + suffix_name
J
jiaqi 已提交
796
        self.rank0_print("going to save_xbox_base_model " + model_path)
797
        fleet.save_persistables(None, model_path, mode=2)
J
jiaqi 已提交
798
        self.rank0_print("save_xbox_base_model done")
799

800
    def save_cache_model(self, output_path, day, pass_id, mode=1, **kwargs):
801 802 803 804 805 806 807
        """
        save cache model

        Args:
            output_path(str): output path
            day(str|int): training day
            pass_id(str|int): training pass id
808
            mode(str|int): save mode
809 810
            kwargs(dict): user defined properties
                          table_id(int): table id to save cache
811 812 813 814 815 816 817 818 819 820 821 822 823 824

        Returns:
            key_num(int): cache key num

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.save_cache_model("hdfs:/my/path", 20190722, 88)

        """
        day = str(day)
        pass_id = str(pass_id)
825
        mode = int(mode)
826
        table_id = kwargs.get("table_id", 0)
827 828
        suffix_name = "/%s/delta-%s" % (day, pass_id)
        model_path = output_path.rstrip("/") + suffix_name
J
jiaqi 已提交
829
        self.rank0_print("going to save_cache_model %s" % model_path)
830 831 832
        key_num = fleet.save_cache_model(
            None, model_path, mode=mode, table_id=table_id
        )
J
jiaqi 已提交
833
        self.rank0_print("save_cache_model done")
834 835
        return key_num

836
    def save_cache_base_model(self, output_path, day, **kwargs):
837 838 839 840 841 842 843
        """
        save cache model

        Args:
            output_path(str): output path
            day(str|int): training day
            pass_id(str|int): training pass id
844 845
            kwargs(dict): user defined properties
                          table_id(int): table id to save cache
846 847 848 849 850 851 852 853 854 855 856 857 858

        Returns:
            key_num(int): cache key num

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.save_cache_base_model("hdfs:/my/path", 20190722)

        """
        day = str(day)
859
        table_id = kwargs.get("table_id", 0)
860 861
        suffix_name = "/%s/base" % day
        model_path = output_path.rstrip("/") + suffix_name
J
jiaqi 已提交
862
        self.rank0_print("going to save_cache_base_model %s" % model_path)
863 864 865
        key_num = fleet.save_cache_model(
            None, model_path, mode=2, table_id=table_id
        )
J
jiaqi 已提交
866
        self.rank0_print("save_cache_base_model done")
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
        return key_num

    def pull_all_dense_params(self, scope, program):
        """
        pull all dense params in trainer of rank 0

        Args:
            scope(Scope): fluid Scope
            program(Program): fluid Program

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.pull_all_dense_params(my_scope, my_program)

        """
        fleet._role_maker._barrier_worker()
        if fleet._role_maker.is_first_worker():
            prog_id = str(id(program))
888 889 890 891 892
            tables = (
                fleet._opt_info["program_id_to_worker"][prog_id]
                .get_desc()
                .dense_table
            )
893 894 895 896 897 898 899 900 901 902 903 904 905 906
            prog_conf = fleet._opt_info['program_configs'][prog_id]
            prog_tables = {}
            for key in prog_conf:
                if "dense" not in key:
                    continue
                for table_id in prog_conf[key]:
                    prog_tables[int(table_id)] = 0
            for table in tables:
                if int(table.table_id) not in prog_tables:
                    continue
                var_name_list = []
                for i in range(0, len(table.dense_variable_name)):
                    var_name = table.dense_variable_name[i]
                    if scope.find_var(var_name) is None:
907 908 909 910 911 912
                        raise ValueError(
                            "var "
                            + var_name
                            + " not found in scope "
                            + "when pull dense"
                        )
913
                    var_name_list.append(var_name)
914 915 916
                fleet._fleet_ptr.pull_dense(
                    scope, int(table.table_id), var_name_list
                )
917 918
        fleet._role_maker._barrier_worker()

919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
    def save_paddle_inference_model(
        self,
        executor,
        scope,
        program,
        feeded_vars,
        target_vars,
        output_path,
        day,
        pass_id,
        hadoop_fs_name,
        hadoop_fs_ugi,
        hadoop_home="$HADOOP_HOME",
        save_combine=True,
    ):
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
        """
        save paddle inference model, and upload to hdfs dnn_plugin path

        Args:
            executor(Executor): fluid Executor
            scope(Scope): fluid Scope
            program(Program): fluid Program
            feeded_vars(list[Variable]): feed vars
            target_vars(list[variable]): fetch vars
            output_path(str): hdfs/afs output path
            day(str|int): training day
            pass_id(str|int): training pass
            hadoop_fs_name(str): hadoop fs name
            hadoop_fs_ugi(str): hadoop fs ugi
            hadoop_home(str): hadoop home, default is "$HADOOP_HOME"
T
tianshuo78520a 已提交
949
            save_combine(bool): whether to save in a file or separate files,
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
                                default is True

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.save_paddle_inference_model(exe,
                                                     join_scope,
                                                     join_program,
                                                     feeded_vars,
                                                     target_vars,
                                                     "hdfs:/my/output/path/",
                                                     day=20190727,
                                                     pass_id=6,
                                                     hadoop_fs_name="xxx",
                                                     hadoop_fs_ugi="xxx,xxx")
        """
        day = str(day)
        pass_id = str(pass_id)
        feeded_var_names = [i.name for i in feeded_vars]
        model_name = "inference_model"
        # pull dense before save
        self.pull_all_dense_params(scope, program)
        if fleet.worker_index() == 0:
            with fluid.scope_guard(scope):
                if save_combine:
                    fluid.io.save_inference_model(
                        dirname=model_name,
                        feeded_var_names=feeded_var_names,
                        target_vars=target_vars,
X
xujiaqi01 已提交
981
                        executor=executor,
982
                        main_program=program.clone(),
983 984
                        params_filename="params",
                    )
985 986 987 988 989
                else:
                    fluid.io.save_inference_model(
                        dirname=model_name,
                        feeded_var_names=feeded_var_names,
                        target_vars=target_vars,
X
xujiaqi01 已提交
990
                        executor=executor,
991 992
                        main_program=program.clone(),
                    )
993 994 995

            configs = {
                "fs.default.name": hadoop_fs_name,
996
                "hadoop.job.ugi": hadoop_fs_ugi,
997 998 999 1000 1001 1002
            }
            client = HDFSClient(hadoop_home, configs)

            if pass_id == "-1":
                dest = "%s/%s/base/dnn_plugin/" % (output_path, day)
            else:
1003 1004 1005 1006 1007
                dest = "%s/%s/delta-%s/dnn_plugin/" % (
                    output_path,
                    day,
                    pass_id,
                )
1008 1009 1010
            if not client.is_exist(dest):
                client.makedirs(dest)

1011
            client.upload(model_name, dest, multi_processes=5, overwrite=True)
1012 1013 1014

        fleet._role_maker._barrier_worker()

1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
    def save_paddle_params(
        self,
        executor,
        scope,
        program,
        model_name,
        output_path,
        day,
        pass_id,
        hadoop_fs_name,
        hadoop_fs_ugi,
        hadoop_home="$HADOOP_HOME",
        var_names=None,
        save_combine=True,
    ):
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
        """
        save paddle model, and upload to hdfs dnn_plugin path

        Args:
            executor(Executor): fluid Executor
            scope(Scope): fluid Scope
            program(Program): fluid Program
            model_name(str): save model local dir or filename
            output_path(str): hdfs/afs output path
            day(str|int): training day
            pass_id(str|int): training pass
            hadoop_fs_name(str): hadoop fs name
            hadoop_fs_ugi(str): hadoop fs ugi
            hadoop_home(str): hadoop home, default is "$HADOOP_HOME"
            var_names(list): save persistable var names, default is None
T
tianshuo78520a 已提交
1045
            save_combine(bool): whether to save in a file or separate files,
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
                                default is True

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.save_paddle_params(exe,
                                            join_scope,
                                            join_program,
                                            "paddle_dense.model.0",
                                            "hdfs:/my/output/path/",
                                            day=20190727,
                                            pass_id=6,
                                            hadoop_fs_name="xxx",
                                            hadoop_fs_ugi="xxx,xxx",
                                            var_names=join_all_var_names)
              fleet_util.save_paddle_params(exe,
                                            join_scope,
                                            join_program,
                                            "paddle_dense.model.usr.0",
                                            "hdfs:/my/output/path/",
                                            day=20190727,
                                            pass_id=6,
                                            hadoop_fs_name="xxx",
                                            hadoop_fs_ugi="xxx,xxx",
                                            var_names=join_user_var_names)
              fleet_util.save_paddle_params(exe,
                                            join_scope,
                                            join_program,
                                            "paddle_dense.model.item.0",
                                            "hdfs:/my/output/path/",
                                            day=20190727,
                                            pass_id=6,
                                            hadoop_fs_name="xxx",
                                            hadoop_fs_ugi="xxx,xxx",
                                            var_names=join_user_item_names)

        """
        day = str(day)
        pass_id = str(pass_id)
        # pull dense before save
        self.pull_all_dense_params(scope, program)
        if fleet.worker_index() == 0:
            vars = [program.global_block().var(i) for i in var_names]
            with fluid.scope_guard(scope):
                if save_combine:
1093 1094 1095
                    fluid.io.save_vars(
                        executor, "./", program, vars=vars, filename=model_name
                    )
1096 1097 1098 1099 1100
                else:
                    fluid.io.save_vars(executor, model_name, program, vars=vars)

            configs = {
                "fs.default.name": hadoop_fs_name,
1101
                "hadoop.job.ugi": hadoop_fs_ugi,
1102 1103 1104 1105 1106 1107
            }
            client = HDFSClient(hadoop_home, configs)

            if pass_id == "-1":
                dest = "%s/%s/base/dnn_plugin/" % (output_path, day)
            else:
1108 1109 1110 1111 1112
                dest = "%s/%s/delta-%s/dnn_plugin/" % (
                    output_path,
                    day,
                    pass_id,
                )
1113
            if not client.is_exist(dest):
1114 1115
                client.mkdirs(dest)
            client.upload(model_name, dest, multi_processes=5, overwrite=True)
1116 1117 1118

        fleet._role_maker._barrier_worker()

1119 1120 1121 1122 1123 1124 1125
    def get_last_save_xbox_base(
        self,
        output_path,
        hadoop_fs_name,
        hadoop_fs_ugi,
        hadoop_home="$HADOOP_HOME",
    ):
1126
        r"""
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
        get last saved base xbox info from xbox_base_done.txt

        Args:
            output_path(str): output path
            hadoop_fs_name(str): hdfs/afs fs_name
            hadoop_fs_ugi(str): hdfs/afs fs_ugi
            hadoop_home(str): hadoop home, default is "$HADOOP_HOME"

        Returns:
            [last_save_day, last_path, xbox_base_key]
            last_save_day(int): day of saved model
            last_path(str): model path
            xbox_base_key(int): xbox key

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              last_save_day, last_path, xbox_base_key = \
                  fleet_util.get_last_save_xbox_base("hdfs:/my/path", 20190722,
                                                     88)

        """
        donefile_path = output_path + "/xbox_base_done.txt"
        configs = {
            "fs.default.name": hadoop_fs_name,
1154
            "hadoop.job.ugi": hadoop_fs_ugi,
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
        }
        client = HDFSClient(hadoop_home, configs)
        if not client.is_file(donefile_path):
            return [-1, -1, int(time.time())]
        pre_content = client.cat(donefile_path)
        last_dict = json.loads(pre_content.split("\n")[-1])
        last_day = int(last_dict["input"].split("/")[-3])
        last_path = "/".join(last_dict["input"].split("/")[:-1])
        xbox_base_key = int(last_dict["key"])
        return [last_day, last_path, xbox_base_key]

1166 1167 1168 1169 1170 1171 1172
    def get_last_save_xbox(
        self,
        output_path,
        hadoop_fs_name,
        hadoop_fs_ugi,
        hadoop_home="$HADOOP_HOME",
    ):
1173
        r"""
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
        get last saved xbox info from xbox_patch_done.txt

        Args:
            output_path(str): output path
            hadoop_fs_name(str): hdfs/afs fs_name
            hadoop_fs_ugi(str): hdfs/afs fs_ugi
            hadoop_home(str): hadoop home, default is "$HADOOP_HOME"

        Returns:
            [last_save_day, last_save_pass, last_path, xbox_base_key]
            last_save_day(int): day of saved model
            last_save_pass(int): pass id of saved
            last_path(str): model path
            xbox_base_key(int): xbox key

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              last_save_day, last_save_pass, last_path, xbox_base_key = \
                  fleet_util.get_last_save_xbox("hdfs:/my/path", 20190722, 88)

        """
        donefile_path = output_path + "/xbox_patch_done.txt"
        configs = {
            "fs.default.name": hadoop_fs_name,
1201
            "hadoop.job.ugi": hadoop_fs_ugi,
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
        }
        client = HDFSClient(hadoop_home, configs)
        if not client.is_file(donefile_path):
            return [-1, -1, "", int(time.time())]
        pre_content = client.cat(donefile_path)
        last_dict = json.loads(pre_content.split("\n")[-1])
        last_day = int(last_dict["input"].split("/")[-3])
        last_pass = int(last_dict["input"].split("/")[-2].split("-")[-1])
        last_path = "/".join(last_dict["input"].split("/")[:-1])
        xbox_base_key = int(last_dict["key"])
        return [last_day, last_pass, last_path, xbox_base_key]

1214 1215 1216 1217 1218 1219 1220
    def get_last_save_model(
        self,
        output_path,
        hadoop_fs_name,
        hadoop_fs_ugi,
        hadoop_home="$HADOOP_HOME",
    ):
1221
        r"""
1222 1223 1224 1225 1226 1227 1228 1229 1230
        get last saved model info from donefile.txt

        Args:
            output_path(str): output path
            hadoop_fs_name(str): hdfs/afs fs_name
            hadoop_fs_ugi(str): hdfs/afs fs_ugi
            hadoop_home(str): hadoop home, default is "$HADOOP_HOME"

        Returns:
1231
            [last_save_day, last_save_pass, last_path, xbox_base_key]
1232 1233 1234
            last_save_day(int): day of saved model
            last_save_pass(int): pass id of saved
            last_path(str): model path
1235
            xbox_base_key(int): xbox key
1236 1237 1238 1239 1240 1241

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
1242 1243
              last_save_day, last_save_pass, last_path, xbox_base_key = \
                  fleet_util.get_last_save_model("hdfs:/my/path", 20190722, 88)
1244 1245 1246 1247 1248 1249 1250 1251

        """
        last_save_day = -1
        last_save_pass = -1
        last_path = ""
        donefile_path = output_path + "/donefile.txt"
        configs = {
            "fs.default.name": hadoop_fs_name,
1252
            "hadoop.job.ugi": hadoop_fs_ugi,
1253 1254 1255
        }
        client = HDFSClient(hadoop_home, configs)
        if not client.is_file(donefile_path):
1256
            return [-1, -1, "", int(time.time())]
1257 1258 1259 1260 1261
        content = client.cat(donefile_path)
        content = content.split("\n")[-1].split("\t")
        last_save_day = int(content[0])
        last_save_pass = int(content[3])
        last_path = content[2]
1262 1263
        xbox_base_key = int(content[1])
        return [last_save_day, last_save_pass, last_path, xbox_base_key]
1264

1265 1266 1267
    def get_online_pass_interval(
        self, days, hours, split_interval, split_per_pass, is_data_hourly_placed
    ):
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
        """
        get online pass interval

        Args:
            days(str): days to train
            hours(str): hours to train
            split_interval(int|str): split interval
            split_per_pass(int}str): split per pass
            is_data_hourly_placed(bool): is data hourly placed

        Returns:
            online_pass_interval(list)

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              online_pass_interval = fleet_util.get_online_pass_interval(
                  days="{20190720..20190729}",
                  hours="{0..23}",
                  split_interval=5,
                  split_per_pass=2,
                  is_data_hourly_placed=False)

        """
        days = os.popen("echo -n " + days).read().split(" ")
        hours = os.popen("echo -n " + hours).read().split(" ")
        split_interval = int(split_interval)
        split_per_pass = int(split_per_pass)
1298 1299
        splits_per_day = 24 * 60 // split_interval
        pass_per_day = splits_per_day // split_per_pass
1300 1301 1302 1303 1304 1305
        left_train_hour = int(hours[0])
        right_train_hour = int(hours[-1])

        start = 0
        split_path = []
        for i in range(splits_per_day):
1306
            h = start // 60
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
            m = start % 60
            if h < left_train_hour or h > right_train_hour:
                start += split_interval
                continue
            if is_data_hourly_placed:
                split_path.append("%02d" % h)
            else:
                split_path.append("%02d%02d" % (h, m))
            start += split_interval

        start = 0
        online_pass_interval = []
        for i in range(pass_per_day):
            online_pass_interval.append([])
            for j in range(start, start + split_per_pass):
                online_pass_interval[i].append(split_path[j])
            start += split_per_pass

        return online_pass_interval

1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
    def get_global_metrics(
        self,
        scope=fluid.global_scope(),
        stat_pos_name="_generated_var_2",
        stat_neg_name="_generated_var_3",
        sqrerr_name="sqrerr",
        abserr_name="abserr",
        prob_name="prob",
        q_name="q",
        pos_ins_num_name="pos",
        total_ins_num_name="total",
    ):
1339
        r"""
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
        get global metrics, including auc, bucket_error, mae, rmse,
        actual_ctr, predicted_ctr, copc, mean_predict_qvalue, total_ins_num.

        Args:
            scope(Scope): Scope object, default is fluid.global_scope()
            stat_pos_name(str): name of auc pos bucket Variable
            stat_neg_name(str): name of auc neg bucket Variable
            sqrerr_name(str): name of sqrerr Variable
            abserr_name(str): name of abserr Variable
            prob_name(str): name of prob Variable
            q_name(str): name of q Variable
            pos_ins_num_name(str): name of pos ins num Variable
            total_ins_num_name(str): name of total ins num Variable

        Returns:
            [auc, bucket_error, mae, rmse, actual_ctr, predicted_ctr, copc,
             mean_predict_qvalue, total_ins_num]

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              metric_list = fleet_util.get_global_metrics(myscope,
T
tianshuo78520a 已提交
1364
                                                          stat_pos.name,
1365 1366 1367 1368 1369 1370 1371 1372
                                                          stat_neg.name,
                                                          local_sqrerr.name,
                                                          local_abserr.name,
                                                          local_prob.name,
                                                          local_q.name,
                                                          local_pos_ins.name,
                                                          local_total_ins.name)

1373
              # below is part of example model
G
GGBond8488 已提交
1374 1375
              label = paddle.static.data(name="click", shape=[-1, 1],\
                  dtype="int64", lod_level=0)
1376
              emb = my_slot_net(slots, label) # emb can be fc layer of size 1
1377
              similarity_norm = fluid.layers.sigmoid(paddle.clip(\
1378 1379
                  emb, min=-15.0, max=15.0), name="similarity_norm")\
              binary_predict = fluid.layers.concat(input=[\
H
HongyuJia 已提交
1380
                  paddle.subtract(\
1381 1382 1383
                      fluid.layers.ceil(similarity_norm), similarity_norm),\
                  similarity_norm], axis=1)
              auc, batch_auc, [batch_stat_pos, batch_stat_neg, stat_pos, \
1384
                  stat_neg] = paddle.static.auc(input=binary_predict,\
1385 1386 1387 1388 1389 1390 1391
                                               label=label, curve='ROC',\
                                               num_thresholds=4096)
              local_sqrerr, local_abserr, local_prob, local_q, local_pos_ins,\
                  local_total_ins = fluid.contrib.layers.ctr_metric_bundle(\
                      similarity_norm, label)

        """
1392 1393 1394 1395
        if (
            scope.find_var(stat_pos_name) is None
            or scope.find_var(stat_neg_name) is None
        ):
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
            self.rank0_print("not found auc bucket")
            return [None] * 9
        elif scope.find_var(sqrerr_name) is None:
            self.rank0_print("not found sqrerr_name=%s" % sqrerr_name)
            return [None] * 9
        elif scope.find_var(abserr_name) is None:
            self.rank0_print("not found abserr_name=%s" % abserr_name)
            return [None] * 9
        elif scope.find_var(prob_name) is None:
            self.rank0_print("not found prob_name=%s" % prob_name)
            return [None] * 9
        elif scope.find_var(q_name) is None:
            self.rank0_print("not found q_name=%s" % q_name)
            return [None] * 9
        elif scope.find_var(pos_ins_num_name) is None:
            self.rank0_print("not found pos_ins_num_name=%s" % pos_ins_num_name)
            return [None] * 9
        elif scope.find_var(total_ins_num_name) is None:
1414 1415 1416
            self.rank0_print(
                "not found total_ins_num_name=%s" % total_ins_num_name
            )
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
            return [None] * 9

        # barrier worker to ensure all workers finished training
        fleet._role_maker._barrier_worker()

        # get auc
        auc = self.get_global_auc(scope, stat_pos_name, stat_neg_name)
        pos = np.array(scope.find_var(stat_pos_name).get_tensor())
        # auc pos bucket shape
        old_pos_shape = np.array(pos.shape)
        # reshape to one dim
        pos = pos.reshape(-1)
        global_pos = np.copy(pos) * 0
        # mpi allreduce
X
xujiaqi01 已提交
1431
        fleet._role_maker._all_reduce(pos, global_pos)
1432 1433 1434 1435 1436 1437 1438
        # reshape to its original shape
        global_pos = global_pos.reshape(old_pos_shape)
        # auc neg bucket
        neg = np.array(scope.find_var(stat_neg_name).get_tensor())
        old_neg_shape = np.array(neg.shape)
        neg = neg.reshape(-1)
        global_neg = np.copy(neg) * 0
X
xujiaqi01 已提交
1439
        fleet._role_maker._all_reduce(neg, global_neg)
1440 1441 1442 1443 1444 1445 1446 1447 1448
        global_neg = global_neg.reshape(old_neg_shape)

        num_bucket = len(global_pos[0])

        def get_metric(name):
            metric = np.array(scope.find_var(name).get_tensor())
            old_metric_shape = np.array(metric.shape)
            metric = metric.reshape(-1)
            global_metric = np.copy(metric) * 0
X
xujiaqi01 已提交
1449
            fleet._role_maker._all_reduce(metric, global_metric)
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
            global_metric = global_metric.reshape(old_metric_shape)
            return global_metric[0]

        global_sqrerr = get_metric(sqrerr_name)
        global_abserr = get_metric(abserr_name)
        global_prob = get_metric(prob_name)
        global_q_value = get_metric(q_name)
        # note: get ins_num from auc bucket is not actual value,
        # so get it from metric op
        pos_ins_num = get_metric(pos_ins_num_name)
        total_ins_num = get_metric(total_ins_num_name)
        neg_ins_num = total_ins_num - pos_ins_num

        mae = global_abserr / total_ins_num
        rmse = math.sqrt(global_sqrerr / total_ins_num)
1465
        return_actual_ctr = pos_ins_num / total_ins_num
1466 1467 1468 1469
        predicted_ctr = global_prob / total_ins_num
        mean_predict_qvalue = global_q_value / total_ins_num
        copc = 0.0
        if abs(predicted_ctr > 1e-6):
1470
            copc = return_actual_ctr / predicted_ctr
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487

        # calculate bucket error
        last_ctr = -1.0
        impression_sum = 0.0
        ctr_sum = 0.0
        click_sum = 0.0
        error_sum = 0.0
        error_count = 0.0
        click = 0.0
        show = 0.0
        ctr = 0.0
        adjust_ctr = 0.0
        relative_error = 0.0
        actual_ctr = 0.0
        relative_ctr_error = 0.0
        k_max_span = 0.01
        k_relative_error_bound = 0.05
1488
        for i in range(num_bucket):
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
            click = global_pos[0][i]
            show = global_pos[0][i] + global_neg[0][i]
            ctr = float(i) / num_bucket
            if abs(ctr - last_ctr) > k_max_span:
                last_ctr = ctr
                impression_sum = 0.0
                ctr_sum = 0.0
                click_sum = 0.0
            impression_sum += show
            ctr_sum += ctr * show
            click_sum += click
            if impression_sum == 0:
                continue
            adjust_ctr = ctr_sum / impression_sum
            if adjust_ctr == 0:
                continue
1505 1506 1507
            relative_error = math.sqrt(
                (1 - adjust_ctr) / (adjust_ctr * impression_sum)
            )
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
            if relative_error < k_relative_error_bound:
                actual_ctr = click_sum / impression_sum
                relative_ctr_error = abs(actual_ctr / adjust_ctr - 1)
                error_sum += relative_ctr_error * impression_sum
                error_count += impression_sum
                last_ctr = -1

        bucket_error = error_sum / error_count if error_count > 0 else 0.0

        return [
1518 1519 1520 1521 1522 1523 1524 1525 1526
            auc,
            bucket_error,
            mae,
            rmse,
            return_actual_ctr,
            predicted_ctr,
            copc,
            mean_predict_qvalue,
            int(total_ins_num),
1527 1528
        ]

1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
    def print_global_metrics(
        self,
        scope=fluid.global_scope(),
        stat_pos_name="_generated_var_2",
        stat_neg_name="_generated_var_3",
        sqrerr_name="sqrerr",
        abserr_name="abserr",
        prob_name="prob",
        q_name="q",
        pos_ins_num_name="pos",
        total_ins_num_name="total",
        print_prefix="",
    ):
1542
        r"""
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
        print global metrics, including auc, bucket_error, mae, rmse,
        actual_ctr, predicted_ctr, copc, mean_predict_qvalue, total_ins_num.

        Args:
            scope(Scope): Scope object, default is fluid.global_scope()
            stat_pos_name(str): name of auc pos bucket Variable
            stat_neg_name(str): name of auc neg bucket Variable
            sqrerr_name(str): name of sqrerr Variable
            abserr_name(str): name of abserr Variable
            prob_name(str): name of prob Variable
            q_name(str): name of q Variable
            pos_ins_num_name(str): name of pos ins num Variable
            total_ins_num_name(str): name of total ins num Variable
            print_prefix(str): print prefix

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              fleet_util.print_global_metrics(myscope,
T
tianshuo78520a 已提交
1564
                                              stat_pos.name,
1565 1566 1567 1568 1569 1570 1571 1572 1573
                                              stat_neg.name,
                                              local_sqrerr.name,
                                              local_abserr.name,
                                              local_prob.name,
                                              local_q.name,
                                              local_pos_ins.name,
                                              local_total_ins.name)

              # below is part of model
G
GGBond8488 已提交
1574 1575
              label = paddle.static.data(name="click", shape=[-1, 1],\
                  dtype="int64", lod_level=0)
1576
              emb = my_slot_net(slots, label) # emb can be fc layer of size 1
1577
              similarity_norm = fluid.layers.sigmoid(paddle.clip(\
1578 1579
                  emb, min=-15.0, max=15.0), name="similarity_norm")\
              binary_predict = fluid.layers.concat(input=[\
H
HongyuJia 已提交
1580
                  paddle.subtract(\
1581 1582 1583
                      fluid.layers.ceil(similarity_norm), similarity_norm),\
                  similarity_norm], axis=1)
              auc, batch_auc, [batch_stat_pos, batch_stat_neg, stat_pos, \
1584
                  stat_neg] = paddle.static.auc(input=binary_predict,\
1585 1586 1587 1588 1589 1590 1591
                                               label=label, curve='ROC',\
                                               num_thresholds=4096)
              local_sqrerr, local_abserr, local_prob, local_q, local_pos_ins, \
                  local_total_ins = fluid.contrib.layers.ctr_metric_bundle(\
                      similarity_norm, label)

        """
1592 1593 1594 1595
        if (
            scope.find_var(stat_pos_name) is None
            or scope.find_var(stat_neg_name) is None
        ):
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
            self.rank0_print("not found auc bucket")
            return
        elif scope.find_var(sqrerr_name) is None:
            self.rank0_print("not found sqrerr_name=%s" % sqrerr_name)
            return
        elif scope.find_var(abserr_name) is None:
            self.rank0_print("not found abserr_name=%s" % abserr_name)
            return
        elif scope.find_var(prob_name) is None:
            self.rank0_print("not found prob_name=%s" % prob_name)
            return
        elif scope.find_var(q_name) is None:
            self.rank0_print("not found q_name=%s" % q_name)
            return
        elif scope.find_var(pos_ins_num_name) is None:
            self.rank0_print("not found pos_ins_num_name=%s" % pos_ins_num_name)
            return
        elif scope.find_var(total_ins_num_name) is None:
1614 1615 1616
            self.rank0_print(
                "not found total_ins_num_name=%s" % total_ins_num_name
            )
1617 1618
            return

1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
        (
            auc,
            bucket_error,
            mae,
            rmse,
            actual_ctr,
            predicted_ctr,
            copc,
            mean_predict_qvalue,
            total_ins_num,
        ) = self.get_global_metrics(
            scope,
            stat_pos_name,
            stat_neg_name,
            sqrerr_name,
            abserr_name,
            prob_name,
            q_name,
            pos_ins_num_name,
            total_ins_num_name,
        )
1640 1641 1642
        self.rank0_print(
            "%s global AUC=%.6f BUCKET_ERROR=%.6f MAE=%.6f "
            "RMSE=%.6f Actural_CTR=%.6f Predicted_CTR=%.6f "
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
            "COPC=%.6f MEAN Q_VALUE=%.6f Ins number=%s"
            % (
                print_prefix,
                auc,
                bucket_error,
                mae,
                rmse,
                actual_ctr,
                predicted_ctr,
                copc,
                mean_predict_qvalue,
                total_ins_num,
            )
        )
1657 1658 1659 1660

    def program_type_trans(self, prog_dir, prog_fn, is_text):
        return utils.program_type_trans(prog_dir, prog_fn, is_text)

1661 1662 1663
    def draw_from_program_file(
        self, model_filename, is_text, output_dir, output_filename
    ):
1664 1665 1666 1667 1668 1669 1670 1671 1672
        """draw program from file"""
        program = utils.load_program(model_filename, is_text)
        utils.graphviz(program.global_block(), output_dir, output_filename)

    def draw_from_program(self, program, output_dir, output_name):
        """draw Program"""
        utils.graphviz(program.global_block(), output_dir, output_name)

    def check_two_programs(self, config):
1673 1674 1675 1676 1677 1678
        train_prog = utils.load_program(
            config.train_prog_path, config.is_text_train_program
        )
        pruned_prog = utils.load_program(
            config.pruned_prog_path, config.is_text_pruned_program
        )
1679 1680
        if config.draw:
            pruned_dir = os.path.dirname(config.pruned_prog_path)
1681 1682 1683
            self.draw_from_program(
                pruned_prog, pruned_dir, config.draw_out_name
            )
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
        res = utils.check_pruned_program_vars(train_prog, pruned_prog)
        if res:
            _logger.info("check_programs succeed.")
        else:
            _logger.info(
                "check_programs failed. pruned program and train program not match!"
            )
        return res

    def check_vars_and_dump(self, config):
        _logger.info("start check_vars_and_dump.")
        results = utils.check_saved_vars_try_dump(
1696 1697 1698 1699 1700 1701 1702 1703
            config.dump_model_dir,
            config.dump_program_filename,
            config.is_text_dump_program,
            config.feed_config,
            config.fetch_config,
            config.batch_size,
            config.save_params_filename,
        )
1704 1705 1706 1707 1708
        _logger.info("check_vars_and_dump succeed.")
        return results

    def parse_program_proto(self, prog_path, is_text, output_dir):
        """
1709 1710
        Parse program.proto into a more readable format.
        This function will generate three files:
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
        output_dir/vars_all.log,
        output_dir/vars_persistable.log,
        output_dir/ops.log.

        Args:
            prog_path(str): proto file path to be parsed.
            is_text(bool): proto file is human-readale format or not(binary).
            output_dir(str): output dir.

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
              fleet_util = FleetUtil()
              program_path = "./program.pbtxt"
              is_text = True
              output_dir = "/tmp/"
              fleet_util.parse_program_proto(program_path, is_text, output_dir)
        """
        program = utils.load_program(prog_path, is_text)
        utils.parse_program(program, output_dir)
T
Thunderbrook 已提交
1732

T
Thunderbrook 已提交
1733
    def _is_optimizer_op(self, op):
1734 1735 1736
        return self.op_role_key in op.attr_names and int(
            op.all_attrs()[self.op_role_key]
        ) & int(OpRole.Optimize)
T
Thunderbrook 已提交
1737

T
Thunderbrook 已提交
1738 1739 1740 1741 1742 1743
    def split_program_by_device(self, program):
        ops_list = []
        type_list = []
        pre = None
        type_cpu = "cpu"
        for op in program.global_block().ops:
T
Thunderbrook 已提交
1744 1745
            if self._is_optimizer_op(op):
                break
T
Thunderbrook 已提交
1746
            if op.has_attr("op_device"):
1747 1748 1749 1750 1751
                cur_attr = (
                    op.attr("op_device")
                    if op.attr("op_device") != ""
                    else type_cpu
                )
T
Thunderbrook 已提交
1752
                if pre is None or pre != cur_attr:
T
Thunderbrook 已提交
1753
                    ops_list.append([])
T
Thunderbrook 已提交
1754
                    type_list.append(cur_attr)
T
Thunderbrook 已提交
1755
                ops_list[-1].append(op)
T
Thunderbrook 已提交
1756
                pre = cur_attr
T
Thunderbrook 已提交
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
        l = len(type_list)
        i = 0
        type_heter = None
        while i < l:
            while i < l and type_list[i] == type_cpu:
                i += 1
            if i == l:
                break

            type_heter = type_list[i]
            i += 1
            start = i
            valid = True
            while i < l and type_list[i] != type_heter:
                if type_list[i] != type_cpu:
                    valid = False
                    break
                i += 1

            if i == l:
                break
            elif not valid:
                continue

            for j in range(start, i):
                for op in ops_list[j]:
                    op._set_attr("op_device", type_heter)
                type_list[j] = type_heter
                j += 1

        pre = None
        merged_ops_list = []
        merged_type_list = []
        for i in range(l):
            if pre is None or pre != type_list[i]:
                merged_ops_list.append([])
                merged_type_list.append(type_list[i])
            merged_ops_list[-1].extend(ops_list[i])
            pre = type_list[i]

        data_vars = set()
        for k in program.global_block().vars:
            var = program.global_block().var(k)
            if not var.persistable:
                data_vars.add(var.name)

        l = len(merged_ops_list)
        inputs_pre = set()
        outputs_pre = set()
        in_from_pre = [[] for i in range(l)]
        for i in range(l):
            inputs = set()
            outputs = set()
            for op in merged_ops_list[i]:
                for input in op.input_names:
                    for tmp in op.input(input):
                        if tmp not in outputs:
                            inputs.add(tmp)
                for output in op.output_names:
                    for tmp in op.output(output):
                        outputs.add(tmp)
            if i == 0:
                in_from_pre[i] = []
            elif i == 1:
                in_from_pre[i] = (outputs_pre | data_vars) & inputs
            else:
                in_from_pre[i] = outputs_pre & inputs
            inputs_pre = copy.deepcopy(inputs)
            outputs_pre = copy.deepcopy(outputs)

        l = len(in_from_pre)
        start_list = []
        end_list = []
        send_list = [[] for i in range(l)]
        sum = 0
        program_list = []
        for i in range(l):
            start_list.append(sum)
            end_list.append(sum + len(merged_ops_list[i]) - 1)
            sum += len(merged_ops_list[i])
            if i < l - 1:
                send_list[i].extend(list(in_from_pre[i + 1]))
            prog = program.clone()
            if merged_type_list[i] != type_cpu:
1841 1842 1843
                prog = prog._prune_with_input(
                    list(in_from_pre[i]), list(send_list[i])
                )
T
Thunderbrook 已提交
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
                program_list.append(prog)
            else:
                program_list.append(prog)
        recv_list = [list(i) for i in in_from_pre]
        found = False
        heter_index = None
        for i in range(len(merged_type_list)):
            t = merged_type_list[i]
            if t != type_cpu:
                if found:
                    print("only one region of program can be heter")
                found = True
                heter_index = i
        if heter_index is None:
            print("warning: non heter program")
            return None
        else:
1861 1862 1863 1864 1865 1866 1867
            return [
                start_list[heter_index],
                end_list[heter_index],
                send_list[heter_index],
                recv_list[heter_index],
                program_list[heter_index],
            ]
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882


class GPUPSUtil(FleetUtil):
    """
    GPUPSUtil provides some common functions for users' convenience.

    Examples:
        .. code-block:: python

          from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil
          fleet_util = GPUPSUtil()
          fleet_util.rank0_print("my log")
    """

    def __init__(self, fs_client=None):
1883
        super().__init__("pslib")
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057
        self._afs = fs_client
        # self._afs = fs_client._fs

    def init(self, fs_name, fs_user, fs_passwd, fs_conf):
        r"""
        init for fs config

        Args:
            fs_name(str): fs name
            fs_user(str): fs user
            fs_passwd(str): fs password
            fs_conf(str): fs and afs conf path

        Returns:
            None

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil
              fleet_util = GPUPSUtil()
              fleet_util.init(20190722, 88, 88, "./afs.conf")
        """
        self._afs.init(fs_name, fs_user, fs_passwd, fs_conf)

    def set_fsclient(self, fs_client):
        r"""
        set fs_client for fs config

        Args:
            fs_client(AFSClient): fs_client object

        Returns:
            None

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil
              from paddle.distributed.fleet.utils.fs import AFSClient
              hdfs_client = AFSClient()
              fleet_util = GPUPSUtil()
              fleet_util.set_fsclient(hdfs_client)
        """
        self._afs = fs_client

    def get_last_save_xbox_base(self, output_path):
        r"""
        get last saved base xbox info from xbox_base_done.txt

        Args:
            output_path(str): output path

        Returns:
            [last_save_day, last_path, xbox_base_key]
            last_save_day(int): day of saved model
            last_path(str): model path
            xbox_base_key(int): xbox key

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil
              from paddle.distributed.fleet.utils.fs import AFSClient
              hdfs_client = AFSClient()
              fleet_util = GPUPSUtil()
              fleet_util.set_fsclient(hdfs_client)
              last_save_day, last_path, xbox_base_key = \
                  fleet_util.get_last_save_xbox_base("hdfs:/my/path")

        """
        donefile_path = output_path + "/xbox_base_done.txt"

        if not self._afs.is_file(donefile_path):
            return [-1, -1, int(time.time())]
        self._afs.download(donefile_path, "./xbox_base_done.txt")
        # pre_content = self._afs.cat(donefile_path)
        pre_content = ""
        with open("xbox_base_done.txt", "r") as f:
            pre_content = f.read()
        pre_content = pre_content.strip()
        last_dict = json.loads(pre_content.split("\n")[-1])
        last_day = int(last_dict["input"].split("/")[-3])
        last_path = "/".join(last_dict["input"].split("/")[:-1])
        xbox_base_key = int(last_dict["key"])
        return [last_day, last_path, xbox_base_key]

    def get_last_save_xbox(self, output_path):
        r"""
        get last saved xbox info from xbox_patch_done.txt

        Args:
            output_path(str): output path

        Returns:
            [last_save_day, last_save_pass, last_path, xbox_base_key]
            last_save_day(int): day of saved model
            last_save_pass(int): pass id of saved
            last_path(str): model path
            xbox_base_key(int): xbox key

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil
              from paddle.distributed.fleet.utils.fs import AFSClient
              hdfs_client = AFSClient()
              fleet_util = GPUPSUtil()
              fleet_util.set_fsclient(hdfs_client)
              last_save_day, last_save_pass, last_path, xbox_base_key = \
                  fleet_util.get_last_save_xbox("hdfs:/my/path")

        """
        donefile_path = output_path + "/xbox_patch_done.txt"

        if not self._afs.is_file(donefile_path):
            return [-1, -1, "", int(time.time())]
        self._afs.download(donefile_path, "xbox_patch_done.txt")
        pre_content = ""
        with open("xbox_patch_done.txt", "r") as f:
            pre_content = f.read()
        pre_content = pre_content.strip()
        last_dict = json.loads(pre_content.split("\n")[-1])
        last_day = int(last_dict["input"].split("/")[-3])
        last_pass = int(last_dict["input"].split("/")[-2].split("-")[-1])
        last_path = "/".join(last_dict["input"].split("/")[:-1])
        xbox_base_key = int(last_dict["key"])
        os.remove("xbox_patch_done.txt")
        return [last_day, last_pass, last_path, xbox_base_key]

    def get_last_save_model(self, output_path):
        r"""
        get last saved model info from donefile.txt

        Args:
            output_path(str): output path

        Returns:
            [last_save_day, last_save_pass, last_path, xbox_base_key]
            last_save_day(int): day of saved model
            last_save_pass(int): pass id of saved
            last_path(str): model path
            xbox_base_key(int): xbox key

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil
              from paddle.distributed.fleet.utils.fs import AFSClient
              hdfs_client = AFSClient()
              fleet_util = GPUPSUtil()
              fleet_util.set_fsclient(hdfs_client)
              last_save_day, last_save_pass, last_path, xbox_base_key = \
                  fleet_util.get_last_save_model("hdfs:/my/path")

        """
        last_save_day = -1
        last_save_pass = -1
        last_path = ""
        donefile_path = output_path + "/donefile.txt"
        if not self._afs.is_file(donefile_path):
            return [-1, -1, "", int(time.time())]
        self._afs.download(donefile_path, "./donefile.txt")
        content = ""
        with open("donefile.txt", "r") as f:
            content = f.read()
        content = content.strip().split("\n")[-1].split("\t")
        last_save_day = int(content[0])
        last_save_pass = int(content[3])
        last_path = content[2]
        xbox_base_key = int(content[1])
        os.remove("donefile.txt")
        return [last_save_day, last_save_pass, last_path, xbox_base_key]

2058 2059 2060 2061 2062 2063 2064 2065
    def write_model_donefile(
        self,
        output_path,
        day,
        pass_id,
        xbox_base_key,
        donefile_name="donefile.txt",
    ):
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
        """
        write donefile when save model

        Args:
            output_path(str): output path
            day(str|int): training day
            pass_id(str|int): training pass id
            xbox_base_key(str|int): xbox base key
            donefile_name(str): donefile name, default is "donefile.txt"

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil
              from paddle.distributed.fleet.utils.fs import AFSClient
              hdfs_client = AFSClient()
              fleet_util = GPUPSUtil()
              fleet_util.set_fsclient(hdfs_client)
              fleet_util.write_model_donefile(output_path="hdfs:/my/output",
                                              model_path="hdfs:/my/model",
                                              day=20190723,
                                              pass_id=66,
                                              xbox_base_key=int(time.time()))

        """
        day = str(day)
        pass_id = str(pass_id)
        xbox_base_key = int(xbox_base_key)

        if pass_id != "-1":
            suffix_name = "/%s/%s/" % (day, pass_id)
            model_path = output_path.rstrip("/") + suffix_name
        else:
            suffix_name = "/%s/0/" % day
            model_path = output_path.rstrip("/") + suffix_name

        if fleet.worker_index() == 0:
            donefile_path = output_path + "/" + donefile_name
2104 2105 2106 2107 2108 2109 2110
            content = "%s\t%lu\t%s\t%s\t%d" % (
                day,
                xbox_base_key,
                model_path,
                pass_id,
                0,
            )
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
            if self._afs.is_file(donefile_path):
                self._afs.download(donefile_path, donefile_name)
                pre_content = ""
                with open(donefile_name, "r") as f:
                    pre_content = f.read()
                pre_content_list = pre_content.strip().split("\n")
                day_list = [i.split("\t")[0] for i in pre_content_list]
                pass_list = [i.split("\t")[3] for i in pre_content_list]
                os.remove(donefile_name)
                exist = False
                for i in range(len(day_list)):
2122 2123 2124
                    if int(day) == int(day_list[i]) and int(pass_id) == int(
                        pass_list[i]
                    ):
2125 2126 2127 2128 2129 2130 2131 2132
                        exist = True
                        break
                if not exist:
                    with open(donefile_name, "w") as f:
                        f.write(pre_content.strip() + "\n")
                        f.write(content + "\n")
                    self._afs.delete(donefile_path)
                    self._afs.upload(donefile_name, donefile_path)
2133 2134 2135
                    self.rank0_error(
                        "write %s/%s %s succeed" % (day, pass_id, donefile_name)
                    )
2136
                else:
2137 2138 2139 2140
                    self.rank0_error(
                        "not write %s because %s/%s already "
                        "exists" % (donefile_name, day, pass_id)
                    )
2141 2142 2143 2144
            else:
                with open(donefile_name, "w") as f:
                    f.write(content + "\n")
                self._afs.upload(donefile_name, donefile_path)
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161
                self.rank0_error(
                    "write %s/%s %s succeed" % (day, pass_id, donefile_name)
                )

    def write_xbox_donefile(
        self,
        output_path,
        day,
        pass_id,
        xbox_base_key,
        data_path,
        hadoop_fs_name,
        hadoop_fs_ugi,
        monitor_data={},
        hadoop_home="$HADOOP_HOME",
        donefile_name=None,
    ):
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213
        """
        write delta donefile or xbox base donefile

        Args:
            output_path(str): output path
            day(str|int): training day of model
            pass_id(str|int): training pass id of model
            xbox_base_key(str|int): xbox base key
            data_path(str|list): training data path
            monitor_data(dict): metrics
            hadoop_home(str): hadoop home, default is "$HADOOP_HOME"
            donefile_name(str): donefile name, default is None"

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil
              from paddle.distributed.fleet.utils.fs import AFSClient
              hdfs_client = AFSClient()
              fleet_util = GPUPSUtil()
              fleet_util.set_fsclient(hdfs_client)
              fleet_util.write_xbox_donefile(
                  output_path="hdfs:/my/output/",
                  model_path="hdfs:/my/output/20190722/01",
                  day=20190722,
                  pass_id=1,
                  xbox_base_key=int(time.time()),
                  data_path="hdfs:/my/data/",
                  monitor_data={})

        """
        day = str(day)
        pass_id = str(pass_id)
        xbox_base_key = int(xbox_base_key)
        mode = None
        if pass_id != "-1":
            mode = "patch"
            suffix_name = "/%s/delta-%s/" % (day, pass_id)
            model_path = output_path.rstrip("/") + suffix_name
            if donefile_name is None:
                donefile_name = "xbox_patch_done.txt"
        else:
            mode = "base"
            suffix_name = "/%s/base/" % day
            model_path = output_path.rstrip("/") + suffix_name
            if donefile_name is None:
                donefile_name = "xbox_base_done.txt"

        if isinstance(data_path, list):
            data_path = ",".join(data_path)
        if fleet.worker_index() == 0:
            donefile_path = output_path + "/" + donefile_name
2214 2215 2216 2217 2218 2219 2220 2221 2222 2223
            xbox_str = self._get_xbox_str(
                output_path,
                day,
                model_path,
                xbox_base_key,
                data_path,
                hadoop_fs_name,
                monitor_data={},
                mode=mode,
            )
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237

            if self._afs.is_exist(donefile_path):
                self.rank0_info("exist %s succeed" % (donefile_path))
                self._afs.download(donefile_path, donefile_name)
                pre_content = ""
                with open(donefile_name, "r") as f:
                    pre_content = f.read()
                last_dict = json.loads(pre_content.strip().split("\n")[-1])
                last_day = last_dict["input"].split("/")[-3]
                last_pass = last_dict["input"].split("/")[-2].split("-")[-1]

                os.remove(donefile_name)
                self.rank0_info("remove %s succeed" % (donefile_name))
                exist = False
2238 2239 2240 2241 2242
                if (
                    int(day) < int(last_day)
                    or int(day) == int(last_day)
                    and int(pass_id) <= int(last_pass)
                ):
2243 2244 2245 2246 2247 2248 2249
                    exist = True
                if not exist:
                    with open(donefile_name, "w") as f:
                        f.write(pre_content.strip() + "\n")
                        f.write(xbox_str + "\n")
                    self._afs.delete(donefile_path)
                    self._afs.upload(donefile_name, donefile_path)
2250 2251 2252
                    self.rank0_info(
                        "write %s/%s %s succeed" % (day, pass_id, donefile_name)
                    )
2253
                else:
2254 2255 2256 2257
                    self.rank0_info(
                        "not write %s because %s/%s already "
                        "exists" % (donefile_name, day, pass_id)
                    )
2258 2259 2260 2261
            else:
                with open(donefile_name, "w") as f:
                    f.write(xbox_str + "\n")
                self._afs.upload(donefile_name, donefile_path)
2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
                self.rank0_error(
                    "write %s/%s %s succeed" % (day, pass_id, donefile_name)
                )

    def write_cache_donefile(
        self,
        output_path,
        day,
        pass_id,
        key_num,
        donefile_name="sparse_cache.meta",
        **kwargs
    ):
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319
        """
        write cache donefile

        Args:
            output_path(str): output path
            day(str|int): training day of model
            pass_id(str|int): training pass id of model
            key_num(str|int): save cache return value
            donefile_name(str): donefile name, default is "sparse_cache.meta"
            kwargs(dict): user defined properties
                          file_num(int): cache file num
                          table_id(int): cache table id

        Examples:
            .. code-block:: python

              from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil
              from paddle.distributed.fleet.utils.fs import AFSClient
              hdfs_client = AFSClient()
              fleet_util = GPUPSUtil()
              fleet_util.set_fsclient(hdfs_client)
              fleet_util.write_cache_donefile(
                  output_path="hdfs:/my/output/",
                  day=20190722,
                  pass_id=1,
                  key_num=123456)

        """
        day = str(day)
        pass_id = str(pass_id)
        key_num = int(key_num)
        file_num = kwargs.get("file_num", 16)
        table_id = kwargs.get("table_id", 0)

        if pass_id != "-1":
            suffix_name = "/%s/delta-%s/%03d_cache" % (day, pass_id, table_id)
            model_path = output_path.rstrip("/") + suffix_name
        else:
            suffix_name = "/%s/base/%03d_cache" % (day, table_id)
            model_path = output_path.rstrip("/") + suffix_name

        if fleet.worker_index() == 0:
            donefile_path = model_path + "/" + donefile_name

            if self._afs.is_file(donefile_path):
2320 2321 2322
                self.rank0_error(
                    "not write because %s already exists" % donefile_path
                )
2323
            else:
2324 2325 2326 2327
                meta_str = "file_prefix:part\npart_num:%s\nkey_num:%d\n" % (
                    file_num,
                    key_num,
                )
2328 2329 2330 2331 2332
                with open(donefile_name, "w") as f:
                    f.write(meta_str)
                self._afs.upload(donefile_name, donefile_path)
                self.rank0_error("write %s succeed" % donefile_path)

2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343
    def _get_xbox_str(
        self,
        output_path,
        day,
        model_path,
        xbox_base_key,
        data_path,
        hadoop_fs_name,
        monitor_data={},
        mode="patch",
    ):
2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354
        xbox_dict = collections.OrderedDict()
        if mode == "base":
            xbox_dict["id"] = str(xbox_base_key)
        elif mode == "patch":
            xbox_dict["id"] = str(int(time.time()))
        else:
            print("warning: unknown mode %s, set it to patch" % mode)
            mode = "patch"
            xbox_dict["id"] = str(int(time.time()))
        xbox_dict["key"] = str(xbox_base_key)
        if model_path.startswith("hdfs:") or model_path.startswith("afs:"):
2355
            model_path = model_path[model_path.find(":") + 1 :]
2356 2357 2358 2359 2360 2361 2362 2363 2364
        xbox_dict["input"] = hadoop_fs_name + model_path.rstrip("/") + "/000"
        xbox_dict["record_count"] = "111111"
        xbox_dict["partition_type"] = "2"
        xbox_dict["job_name"] = "default_job_name"
        xbox_dict["ins_tag"] = "feasign"
        xbox_dict["ins_path"] = data_path
        xbox_dict["job_id"] = os.environ.get("PADDLE_JOB_ID", "")
        # currently hard code here, set monitor_data empty string
        xbox_dict["monitor_data"] = ""
2365 2366 2367
        xbox_dict["monitor_path"] = (
            output_path.rstrip("/") + "/monitor/" + day + ".txt"
        )
2368 2369
        xbox_dict["mpi_size"] = str(fleet.worker_num())
        return json.dumps(xbox_dict)