the_one_ps.py 63.8 KB
Newer Older
Z
ziyoujiyi 已提交
1
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
Z
ziyoujiyi 已提交
2
#
Z
ziyoujiyi 已提交
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
Z
ziyoujiyi 已提交
6
#
Z
ziyoujiyi 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
Z
ziyoujiyi 已提交
8
#
Z
ziyoujiyi 已提交
9 10 11 12 13
# 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.
Z
ziyoujiyi 已提交
14

15
import os
Z
ziyoujiyi 已提交
16 17
import warnings

18 19
from google.protobuf import text_format

W
wangguanqun 已提交
20
import paddle
Z
ziyoujiyi 已提交
21
from paddle.distributed import fleet
22
from paddle.distributed.communicator import Communicator, HeterClient
23 24 25
from paddle.distributed.fleet.base.private_helper_function import (
    wait_server_ready,
)
Z
ziyoujiyi 已提交
26
from paddle.distributed.fleet.proto import the_one_ps_pb2
27
from paddle.distributed.fleet.runtime.runtime_base import RuntimeBase
28
from paddle.distributed.ps.coordinator import Coordinator
29 30 31
from paddle.distributed.ps.utils.public import *  # noqa: F403
from paddle.framework import core
from paddle.static import CompiledProgram, Executor, ParallelExecutor, Program
Z
ziyoujiyi 已提交
32

Z
ziyoujiyi 已提交
33
__all__ = [
34 35 36 37 38 39
    'Table',
    'SparseTable',
    'GeoSparseTable',
    'BarrierTable',
    'TensorTable',
    'DenseTable',
Z
ziyoujiyi 已提交
40
]
Z
ziyoujiyi 已提交
41 42


W
wangguanqun 已提交
43 44 45 46
def get_program_by_id(context, program_id):
    programs = context["origin_main_programs"]
    for i, program in enumerate(programs):
        if id(program) == program_id:
47 48
            return program, context["origin_startup_programs"][i], i
    return None, None, None
W
wangguanqun 已提交
49 50 51


def parse_table_class(varname, program_id, context):
52
    main_program, startup_program, idx = get_program_by_id(context, program_id)
W
wangguanqun 已提交
53
    for op in main_program.global_block().ops:
Z
ziyoujiyi 已提交
54 55 56 57 58
        if not is_distributed_sparse_op(op) and not is_sparse_op(op):
            continue

        param_name = op.input("W")[0]

59 60 61 62 63
        if (
            param_name == varname
            and op.type == "lookup_table"
            or op.type == "lookup_table_v2"
        ):
Z
ziyoujiyi 已提交
64 65 66 67 68 69
            if op.has_attr('table_class') and op.attr("table_class") != "none":
                return op.attr('table_class')
            else:
                return "MemorySparseTable"


Z
ziyoujiyi 已提交
70
def check_embedding_dim(accessor_proto, varname, program_id, context):
71
    main_program, startup_program, idx = get_program_by_id(context, program_id)
Z
ziyoujiyi 已提交
72
    embedding_dim = 0
W
wangguanqun 已提交
73
    for var in main_program.list_vars():
Z
ziyoujiyi 已提交
74 75
        if var.name == varname:
            embedding_dim = var.shape[1]
76 77 78 79 80
            print(
                'new var: {}, {}, {}'.format(
                    var, embedding_dim, accessor_proto.fea_dim
                )
            )
Z
ziyoujiyi 已提交
81
            break
82

Z
ziyoujiyi 已提交
83
    fea_dim = accessor_proto.fea_dim
84 85 86
    if accessor_proto.accessor_class == "SparseAccessor":
        if fea_dim != embedding_dim + 2:
            raise ValueError(
87 88 89 90
                "The fea_dim is wrong, it will be sparse_embedding_dim + 2: {}, but got {}".format(
                    embedding_dim + 2, fea_dim
                )
            )
91 92 93
    else:
        if fea_dim != embedding_dim:
            raise ValueError(
94 95 96 97
                "The fea_dim is wrong, it will be sparse_embedding_dim: {}, but got {}".format(
                    embedding_dim, fea_dim
                )
            )
98

Z
ziyoujiyi 已提交
99
    embedx_dim = accessor_proto.embedx_dim
100 101 102
    if accessor_proto.accessor_class == "SparseAccessor":
        if embedx_dim != embedding_dim - 1:
            raise ValueError(
103 104 105 106
                "The embedx_dim is wrong, it will be sparse_embedding_dim - 1: {}, but got {}".format(
                    embedding_dim - 1, embedx_dim
                )
            )
107 108 109
    else:
        if embedx_dim != embedding_dim - 3:
            raise ValueError(
110 111 112 113
                "The embedx_dim is wrong, it will be sparse_embedding_dim - 3: {}, but got {}".format(
                    embedding_dim - 3, embedx_dim
                )
            )
Z
ziyoujiyi 已提交
114 115


Z
ziyoujiyi 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129
class Service:
    def __init__(self):
        pass

    def _set(self, service_proto):
        service_proto.server_class = "BrpcPsServer"
        service_proto.client_class = "BrpcPsClient"
        service_proto.service_class = "BrpcPsService"
        service_proto.start_server_port = 0
        service_proto.server_thread_num = 12


class GpuService(Service):
    def __init__(self):
130
        super().__init__()
Z
ziyoujiyi 已提交
131 132 133 134 135 136

    def _set(self, service_proto):
        service_proto.server_class = 'PsLocalServer'
        service_proto.client_class = 'PsLocalClient'


Z
ziyoujiyi 已提交
137 138 139 140
class Accessor:
    def __init__(self):
        self.accessor_class = ""
        self.optimizer = None
Z
ziyoujiyi 已提交
141 142
        self.feature_dim = 0
        self.embedding_dim = 0
Z
ziyoujiyi 已提交
143

Z
ziyoujiyi 已提交
144
    # TableAccessorParameter accessor
145 146 147
    def _set(
        self, accessor_proto, varname, program_id, context, common_accessor
    ):
148
        main_program, startup_program, idx = get_program_by_id(
149 150
            context, program_id
        )
Z
ziyoujiyi 已提交
151 152 153 154 155
        embedding_dim = 0
        for var in main_program.list_vars():
            if var.name == varname:
                embedding_dim = var.shape[1]
                break
Z
ziyoujiyi 已提交
156

Z
ziyoujiyi 已提交
157
        if not accessor_proto.HasField("accessor_class"):
158
            # DownpourSparseValueAccessor
159
            if context['use_ps_gpu']:
160
                accessor_proto.accessor_class = "CtrDymfAccessor"
161 162
            else:
                accessor_proto.accessor_class = "SparseAccessor"
Z
ziyoujiyi 已提交
163
        if not accessor_proto.HasField("fea_dim"):
164 165 166 167
            if accessor_proto.accessor_class == "SparseAccessor":
                accessor_proto.fea_dim = embedding_dim + 2
            else:
                accessor_proto.fea_dim = embedding_dim
Z
ziyoujiyi 已提交
168
        if not accessor_proto.HasField("embedx_dim"):
169 170 171 172
            if accessor_proto.accessor_class == "SparseAccessor":
                accessor_proto.embedx_dim = embedding_dim - 1
            else:
                accessor_proto.embedx_dim = embedding_dim - 3
Z
ziyoujiyi 已提交
173 174 175
        if not accessor_proto.HasField("embedx_threshold"):
            accessor_proto.embedx_threshold = 0

D
danleifeng 已提交
176 177 178 179 180 181
        graph_sgd_param = accessor_proto.graph_sgd_param
        if not graph_sgd_param.HasField("nodeid_slot"):
            graph_sgd_param.nodeid_slot = 9008
        if not graph_sgd_param.HasField("feature_learning_rate"):
            graph_sgd_param.feature_learning_rate = 0.05

Z
ziyoujiyi 已提交
182
        ctr_accessor_param = accessor_proto.ctr_accessor_param
183 184
        if accessor_proto.embedx_dim == 0:
            ctr_accessor_param.zero_init = False
Z
ziyoujiyi 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
        if not ctr_accessor_param.HasField("nonclk_coeff"):
            ctr_accessor_param.nonclk_coeff = 0.1
        if not ctr_accessor_param.HasField("click_coeff"):
            ctr_accessor_param.click_coeff = 1.0
        if not ctr_accessor_param.HasField("base_threshold"):
            ctr_accessor_param.base_threshold = 0
        if not ctr_accessor_param.HasField("delta_threshold"):
            ctr_accessor_param.delta_threshold = 0
        if not ctr_accessor_param.HasField("delta_keep_days"):
            ctr_accessor_param.delta_keep_days = 16
        if not ctr_accessor_param.HasField("show_click_decay_rate"):
            ctr_accessor_param.show_click_decay_rate = 1
        if not ctr_accessor_param.HasField("delete_threshold"):
            ctr_accessor_param.delete_threshold = 0
        if not ctr_accessor_param.HasField("delete_after_unseen_days"):
            ctr_accessor_param.delete_after_unseen_days = 30
        if not ctr_accessor_param.HasField("ssd_unseenday_threshold"):
            ctr_accessor_param.ssd_unseenday_threshold = 1

        for sgd_param in [
205 206
            accessor_proto.embed_sgd_param,
            accessor_proto.embedx_sgd_param,
Z
ziyoujiyi 已提交
207 208
        ]:
            if not sgd_param.HasField("name"):
209 210 211 212
                if common_accessor.accessor_class == "sgd":
                    sgd_param.name = "SparseNaiveSGDRule"
                if common_accessor.accessor_class == "adam":
                    sgd_param.name = "SparseAdamSGDRule"
Z
ziyoujiyi 已提交
213 214
                else:  # for fl-ps, because geo accessor is 'sum'
                    sgd_param.name = "SparseAdamSGDRule"
215

216 217 218 219
            if (
                sgd_param.name == "SparseAdaGradSGDRule"
                or sgd_param.name == "StdAdaGradSGDRule"
            ):
Z
ziyoujiyi 已提交
220 221 222 223 224 225 226 227
                if not sgd_param.adagrad.HasField("learning_rate"):
                    sgd_param.adagrad.learning_rate = 0.05
                if not sgd_param.adagrad.HasField("initial_g2sum"):
                    sgd_param.adagrad.initial_g2sum = 3.0
                if not sgd_param.adagrad.HasField("initial_range"):
                    sgd_param.adagrad.initial_range = 0.0001
                if len(sgd_param.adagrad.weight_bounds) == 0:
                    sgd_param.adagrad.weight_bounds.extend([-10.0, 10.0])
228

Z
ziyoujiyi 已提交
229 230
            if sgd_param.name == "SparseNaiveSGDRule":
                if not sgd_param.naive.HasField("learning_rate"):
231 232 233
                    learning_rate = common_accessor.initializers[-1].split("&")[
                        1
                    ]
234
                    sgd_param.naive.learning_rate = float(learning_rate)
Z
ziyoujiyi 已提交
235
                if not sgd_param.naive.HasField("initial_range"):
236 237 238
                    initial_range = common_accessor.initializers[0].split("&")[
                        -1
                    ]
239
                    sgd_param.naive.initial_range = float(initial_range)
Z
ziyoujiyi 已提交
240 241
                if len(sgd_param.naive.weight_bounds) == 0:
                    sgd_param.naive.weight_bounds.extend([-10.0, 10.0])
242

243 244 245 246
            if (
                sgd_param.name == "SparseAdamSGDRule"
                or sgd_param.name == "SparseSharedAdamSGDRule"
            ):
Z
ziyoujiyi 已提交
247
                if not sgd_param.adam.HasField("learning_rate"):
248 249 250
                    learning_rate = common_accessor.initializers[-1].split("&")[
                        1
                    ]
251
                    sgd_param.adam.learning_rate = float(learning_rate)
Z
ziyoujiyi 已提交
252
                if not sgd_param.adam.HasField("initial_range"):
253 254 255
                    initial_range = common_accessor.initializers[0].split("&")[
                        -1
                    ]
256 257 258
                    sgd_param.adam.initial_range = float(initial_range)

                attr_list = [x.split("&") for x in common_accessor.attrs]
259 260 261 262
                if (
                    not sgd_param.adam.HasField("beta1_decay_rate")
                    and common_accessor.accessor_class == "adam"
                ):
263 264
                    sgd_param.adam.beta1_decay_rate = float(attr_list[0][1])
                else:
Z
ziyoujiyi 已提交
265
                    sgd_param.adam.beta1_decay_rate = 0.9
266 267 268 269
                if (
                    not sgd_param.adam.HasField("beta2_decay_rate")
                    and common_accessor.accessor_class == "adam"
                ):
270 271
                    sgd_param.adam.beta2_decay_rate = float(attr_list[1][1])
                else:
Z
ziyoujiyi 已提交
272
                    sgd_param.adam.beta2_decay_rate = 0.999
273 274 275 276
                if (
                    not sgd_param.adam.HasField("ada_epsilon")
                    and common_accessor.accessor_class == "adam"
                ):
277 278
                    sgd_param.adam.ada_epsilon = float(attr_list[2][1])
                else:
Z
ziyoujiyi 已提交
279 280 281 282 283 284
                    sgd_param.adam.ada_epsilon = 1e-08
                if len(sgd_param.adam.weight_bounds) == 0:
                    sgd_param.adam.weight_bounds.extend([-10.0, 10.0])


class CommonAccessor(Accessor):
Z
ziyoujiyi 已提交
285
    def __init__(self):
286
        super().__init__()
Z
ziyoujiyi 已提交
287 288
        self.table_name = ''
        self.entry = 'none'
Z
ziyoujiyi 已提交
289 290 291 292
        self.attrs = []
        self.params = []
        self.dims = []
        self.trainer_num = 0
Z
ziyoujiyi 已提交
293
        self.sync = False
Z
ziyoujiyi 已提交
294 295 296 297 298 299 300 301 302
        self.initializers = []
        self.opt_input_map = {}
        self.opt_attr_map = {}
        self.opt_init_map = {}
        self.define_optimize_map()

    def define_optimize_map(self):
        opt_input_map = {}
        opt_input_map["sgd"] = [("Param", None), ("LearningRate", 1)]
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
        opt_input_map["adam"] = [
            ("Param", None),
            ("Moment1", None),
            ("Moment2", None),
            ("Beta1Pow", 1),
            ("Beta2Pow", 1),
            ("LearningRate", 1),
        ]
        opt_input_map["adam_d2sum"] = [
            ("Param", None),
            ("D2Sum", None),
            ("G2Sum", None),
            ("Moment", None),
            ("MomentDecayRate", 1),
            ("AdaDecayRate", 1),
            ("AdaEpsilon", 1),
            ("LearningRate", 1),
        ]
Z
ziyoujiyi 已提交
321
        opt_input_map["sum"] = [("Param", None)]
322 323 324 325 326
        opt_input_map["naive_adagrad"] = [
            ("Param", None),
            ("G2Sum", 1),
            ("LearningRate", 1),
        ]
W
wangguanqun 已提交
327
        opt_input_map["summary"] = [("Param", None), ("SummaryDecayRate", 1)]
Z
ziyoujiyi 已提交
328 329 330 331 332

        opt_attr_map = {}
        opt_attr_map["sgd"] = []
        opt_attr_map["sum"] = []
        opt_attr_map["naive_adagrad"] = []
333 334 335 336 337 338 339 340 341 342
        opt_attr_map["adam"] = [
            ("beta1", "f"),
            ("beta2", "f"),
            ("epsilon", "f"),
        ]
        opt_attr_map["adam_d2sum"] = [
            ("beta1", "f"),
            ("beta2", "f"),
            ("epsilon", "f"),
        ]
343
        opt_attr_map["summary"] = [("summary_decay_rate", "f")]
Z
ziyoujiyi 已提交
344 345 346 347 348 349 350 351 352 353 354

        opt_init_map = {}
        opt_init_map["gaussian_random"] = ["seed", "mean", "std"]
        opt_init_map["fill_constant"] = ["value"]
        opt_init_map["uniform_random"] = ["seed", "min", "max"]
        opt_init_map["truncated_gaussian_random"] = ["seed", "mean", "std"]

        self.opt_attr_map = opt_attr_map
        self.opt_input_map = opt_input_map
        self.opt_init_map = opt_init_map

W
wangguanqun 已提交
355
    def parse_entry(self, varname, program_id, context):
356
        main_program, startup_program, idx = get_program_by_id(
357 358
            context, program_id
        )
W
wangguanqun 已提交
359
        for op in main_program.global_block().ops:
Z
ziyoujiyi 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
            if not is_distributed_sparse_op(op) and not is_sparse_op(op):
                continue

            param_name = op.input("W")[0]

            if param_name == varname and op.type == "lookup_table":
                self.entry = op.attr('entry')
                break

            if param_name == varname and op.type == "lookup_table_v2":
                self.entry = "none"
                break

    def get_shard(self, total_dim, shard_num, pserver_id):
        blocksize = int(total_dim / shard_num + 1)

        if blocksize * (pserver_id + 1) <= total_dim:
            return blocksize
        else:
            if blocksize * pserver_id < total_dim:
                return total_dim - blocksize * pserver_id
            else:
                return 0

    def get_initializer_attr(self, value_name, o_startup_program):
        l_in = "&"
        attr_str = ""

        origin_var_name = value_name
389
        # print("get_initializer_attr param name:", value_name)
Z
ziyoujiyi 已提交
390
        for op in o_startup_program.global_block().ops:
391 392 393 394
            if (
                op.type in self.opt_init_map.keys()
                and origin_var_name == op.output("Out")[0]
            ):
Z
ziyoujiyi 已提交
395
                init_attr = [op.type]
396
                # print("get_initializer_attr op type:", op.type)
Z
ziyoujiyi 已提交
397
                for attr in self.opt_init_map[op.type]:
398
                    # print("get_initializer_attr opt_init_map attr:", attr)
Z
ziyoujiyi 已提交
399
                    init_attr.append(str(op.attr(attr)))
400
                    # print("get_initializer_attr op attr:", str(op.attr(attr)))
Z
ziyoujiyi 已提交
401 402 403 404
                attr_str = l_in.join(init_attr)
                break
        return attr_str

W
wangguanqun 已提交
405 406 407 408 409 410
    def parse_by_optimizer(self, ctx, context):
        grad_name = ctx.origin_varnames()[0]
        is_sparse = ctx.is_sparse()
        size = ctx.sections()[0]
        single_dim = ctx.sections()[1] if ctx.is_sparse() else 1
        adam_d2sum = context["user_defined_strategy"].adam_d2sum
411 412
        # print("parse_by_optimizer table_id:{} is_datanorm:{}".format(
        #     ctx.table_id(), ctx.is_datanorm_table()))
W
wangguanqun 已提交
413

414
        main_program, startup_program, idx = get_program_by_id(
415 416
            context, ctx.program_id()
        )
Z
ziyoujiyi 已提交
417 418 419
        pserver_id = get_role_id(context['role_maker'])
        pserver_num = len(get_ps_endpoints(context['role_maker']))
        optimizer_ops = get_optimize_ops(main_program)
420 421
        # print("the one ps optimizer_ops:", optimizer_ops)
        # print("the one ps parse_by_optimizer grad_name:", grad_name)
Z
ziyoujiyi 已提交
422 423 424 425
        oop = None

        for op in optimizer_ops:
            if ("Param" in op.input_names) and (
426 427 428
                op.input("Param")[0]
                == context['grad_name_to_param_name'][grad_name]
            ):
Z
ziyoujiyi 已提交
429 430 431 432 433 434 435 436 437 438 439 440
                oop = op
                break

        if oop is None:
            raise ValueError("can not find optimizer for {}".format(grad_name))

        params = []
        dims = []
        attrs = []
        initializers = []

        self.trainer_num = get_trainers(context['role_maker'])
W
wangguanqun 已提交
441 442
        self.table_num = size
        self.table_dim = single_dim
Z
ziyoujiyi 已提交
443

444
        if oop.type != 'adam' and adam_d2sum:
Z
ziyoujiyi 已提交
445 446 447 448 449 450 451 452 453 454 455
            print('optimization algorithm is not adam, set adam_d2sum False')
            adam_d2sum = False
        print("adam_d2sum:", adam_d2sum)
        if context['ps_mode'] == DistributedMode.GEO:
            param_varnames = self.opt_input_map["sum"]
            attr_varnames = self.opt_attr_map["sum"]
            self.accessor_class = "sum"
        elif context['use_ps_gpu'] and is_sparse:
            param_varnames = self.opt_input_map["naive_adagrad"]
            attr_varnames = self.opt_attr_map["naive_adagrad"]
            self.accessor_class = "sgd"
W
wangguanqun 已提交
456 457 458 459 460
        elif ctx.is_datanorm_table():
            param_varnames = self.opt_input_map["summary"]
            attr_varnames = self.opt_attr_map["summary"]
            self.accessor_class = "summary"
        elif adam_d2sum and not is_sparse:
Z
ziyoujiyi 已提交
461 462 463 464
            param_varnames = self.opt_input_map["adam_d2sum"]
            attr_varnames = self.opt_attr_map["adam_d2sum"]
            self.accessor_class = "adam_d2sum"
        else:
465 466
            if oop.type != 'sgd' and oop.type != 'adam':
                raise ValueError(
467 468
                    "The dense optimizer in PS is only supported SGD or Adam!"
                )
Z
ziyoujiyi 已提交
469 470 471 472 473 474 475
            param_varnames = self.opt_input_map[oop.type]
            attr_varnames = self.opt_attr_map[oop.type]
            self.accessor_class = oop.type

        for (formal_name, shape) in param_varnames:
            params.append(formal_name)
            if self.accessor_class == "adam_d2sum":
476
                # for dims
Z
ziyoujiyi 已提交
477 478
                if shape is None:
                    if is_sparse:
W
wangguanqun 已提交
479
                        shape = single_dim
Z
ziyoujiyi 已提交
480
                    else:
W
wangguanqun 已提交
481
                        shape = self.get_shard(size, pserver_num, pserver_id)
Z
ziyoujiyi 已提交
482 483
                dims.append(shape)

484
                # for initializers
Z
ziyoujiyi 已提交
485
                if formal_name == "Param" or formal_name == "LearningRate":
486 487 488 489 490 491 492 493
                    param = main_program.global_block().vars[
                        oop.input(formal_name)[0]
                    ]
                    # TODO: for dense learning_rate, can be different from sparse lr
                    if (
                        formal_name == "LearningRate"
                        and param.name != "learning_rate_" + str(idx)
                    ):
Z
ziyoujiyi 已提交
494 495
                        warnings.warn("will support decay soon")
                        param = main_program.global_block().vars[
496 497
                            "learning_rate_" + str(idx)
                        ]
Z
ziyoujiyi 已提交
498

499
                    initializer = self.get_initializer_attr(
500 501
                        param.name, startup_program
                    )
Z
ziyoujiyi 已提交
502 503 504 505 506 507 508 509 510
                elif formal_name == "MomentDecayRate":
                    initializer = "fill_constant&0.99"
                elif formal_name == "AdaDecayRate":
                    initializer = "fill_constant&0.9999"
                elif formal_name == "AdaEpsilon":
                    initializer = "fill_constant&1.0e-8"
                else:
                    initializer = "fill_constant&0"
                initializers.append(initializer)
W
wangguanqun 已提交
511
            elif self.accessor_class == "summary":
512
                # for dims
W
wangguanqun 已提交
513 514 515 516 517 518 519
                if shape is None:
                    if is_sparse:
                        shape = single_dim
                    else:
                        shape = self.get_shard(size, pserver_num, pserver_id)
                dims.append(shape)

520
                # for initializers
W
wangguanqun 已提交
521
                if formal_name == "Param":
522 523 524
                    param = main_program.global_block().vars[
                        oop.input(formal_name)[0]
                    ]
W
wangguanqun 已提交
525

526
                    initializer = self.get_initializer_attr(
527 528
                        param.name, startup_program
                    )
W
wangguanqun 已提交
529
                elif formal_name == "SummaryDecayRate":
530
                    initializer = "fill_constant&0.999999"
W
wangguanqun 已提交
531 532 533
                else:
                    initializer = "fill_constant&0"
                initializers.append(initializer)
Z
ziyoujiyi 已提交
534 535 536 537 538 539
            else:
                if formal_name == "G2Sum":
                    dims.append(1)
                    initializer = "fill_constant&0"
                    initializers.append(initializer)
                else:
540 541 542 543 544 545 546
                    param = main_program.global_block().vars[
                        oop.input(formal_name)[0]
                    ]
                    if (
                        formal_name == "LearningRate"
                        and param.name != "learning_rate_" + str(idx)
                    ):
Z
ziyoujiyi 已提交
547 548
                        warnings.warn("will support decay soon")
                        param = main_program.global_block().vars[
549 550
                            "learning_rate_" + str(idx)
                        ]
Z
ziyoujiyi 已提交
551 552 553

                    if shape is None:
                        if is_sparse:
W
wangguanqun 已提交
554
                            shape = single_dim
Z
ziyoujiyi 已提交
555
                        else:
556 557 558
                            shape = self.get_shard(
                                size, pserver_num, pserver_id
                            )
Z
ziyoujiyi 已提交
559 560
                    dims.append(shape)

561
                    initializer = self.get_initializer_attr(
562 563
                        param.name, startup_program
                    )
Z
ziyoujiyi 已提交
564 565
                    initializers.append(initializer)

566 567 568 569
        if self.accessor_class == 'summary':
            datanorm_ops = get_datanorm_ops(main_program)
            for op in datanorm_ops:
                if ("BatchSize" in op.input_names) and (
570 571 572
                    op.input("BatchSize")[0]
                    == context['grad_name_to_param_name'][grad_name]
                ):
573 574 575
                    oop = op
                    break

Z
ziyoujiyi 已提交
576 577
        for (attr_varname, type_) in attr_varnames:
            value = oop.attr(attr_varname)
578
            attrs.append("&".join([attr_varname, str(value)]))
Z
ziyoujiyi 已提交
579 580 581 582 583 584

        self.params = params
        self.dims = dims
        self.initializers = initializers
        self.attrs = attrs

Z
ziyoujiyi 已提交
585 586 587 588 589 590 591 592 593 594 595 596
    # CommonAccessorParameter common
    def _set(self, proto):
        proto.name = self.accessor_class
        proto.table_name = self.table_name
        proto.params.extend(self.params)
        proto.dims.extend(self.dims)
        proto.initializers.extend(self.initializers)
        proto.entry = self.entry
        proto.trainer_num = self.trainer_num
        proto.sync = self.sync
        proto.table_num = self.table_num
        proto.table_dim = self.table_dim
597
        proto.attr = "#".join(self.attrs)
Z
ziyoujiyi 已提交
598 599 600


class Tensor:
Z
ziyoujiyi 已提交
601 602 603 604
    def __init__(self, tesnor_dcit):
        self.tensor_dict = tesnor_dcit

    def _set(self, tensor_proto):
605
        tensor_proto.main_program_id = self.tensor_dict.get(
606 607
            "main_program_id", 0
        )
Z
ziyoujiyi 已提交
608
        tensor_proto.startup_program_id = self.tensor_dict.get(
609 610
            "startup_program_id", 0
        )
Z
ziyoujiyi 已提交
611 612 613
        tensor_proto.feed_var_name = self.tensor_dict.get("feed_var_name", '')
        tensor_proto.fetch_var_name = self.tensor_dict.get("fetch_var_name", '')
        tensor_proto.tensor_table_class = self.tensor_dict.get(
614 615
            "tensor_table_class", ''
        )
Z
ziyoujiyi 已提交
616 617 618 619 620 621 622


class Table:
    def __init__(self):
        self.table_class = None
        self.shard_num = -1
        self.type = None
Z
ziyoujiyi 已提交
623 624 625
        self.accessor = Accessor()
        self.shard_num = 256
        self.common = CommonAccessor()
Z
ziyoujiyi 已提交
626 627
        self.tensor = None

Z
ziyoujiyi 已提交
628 629
    def _set(self, table_proto):
        pass
Z
ziyoujiyi 已提交
630 631


Z
ziyoujiyi 已提交
632 633
class BarrierTable(Table):
    def __init__(self, context, idx):
634
        super().__init__()
Z
ziyoujiyi 已提交
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
        self.type = None
        self.shard_num = 256
        self.accessor.accessor_class = 'CommMergeAccessor'
        self.common.attrs = ""
        self.common.dims = []
        self.common.params = []
        self.is_heter_ps_mode = context['is_heter_ps_mode']
        self.role_maker = context['role_maker']
        self.idx = idx
        self.is_sync = context['is_sync']

    def _set(self, table_proto):
        table_proto.table_id = self.idx
        table_proto.table_class = 'BarrierTable'
        table_proto.shard_num = 256
Z
ziyoujiyi 已提交
650
        table_proto.type = the_one_ps_pb2.PS_OTHER_TABLE
Z
ziyoujiyi 已提交
651 652 653 654 655 656 657 658 659 660 661 662 663 664

        table_proto.accessor.accessor_class = "CommMergeAccessor"
        table_proto.accessor.fea_dim = 0
        table_proto.accessor.embedx_dim = 0

        table_proto.common.name = ""
        table_proto.common.table_name = "barrier_table"
        table_proto.common.sync = self.is_sync
        table_proto.common.entry = 'none'

        trainer_num = get_trainers(self.role_maker)
        if self.is_heter_ps_mode:
            trainer_num += len(self.role_maker._get_heter_worker_endpoints())
        table_proto.common.trainer_num = trainer_num
Z
ziyoujiyi 已提交
665 666


Z
ziyoujiyi 已提交
667 668
class TensorTable(Table):
    def __init__(self, idx, tensor_dict, role_maker):
669
        super().__init__()
Z
ziyoujiyi 已提交
670 671 672
        self.idx = idx
        self.tensor_dict = tensor_dict
        self.role_maker = role_maker
Z
ziyoujiyi 已提交
673

Z
ziyoujiyi 已提交
674 675
    def _set(self, table_proto):
        table_proto.table_id = self.idx
Z
ziyoujiyi 已提交
676
        table_proto.type = the_one_ps_pb2.PS_OTHER_TABLE
Z
ziyoujiyi 已提交
677
        table_proto.table_class = self.tensor_dict.get("tensor_table_class", '')
Z
ziyoujiyi 已提交
678

Z
ziyoujiyi 已提交
679
        table_proto.accessor.accessor_class = "CommMergeAccessor"
Z
ziyoujiyi 已提交
680

681
        table_proto.common.table_name = self.tensor_dict.get(
682 683
            "feed_var_name", ''
        )
Z
ziyoujiyi 已提交
684
        table_proto.common.trainer_num = get_trainers(self.role_maker)
Z
ziyoujiyi 已提交
685

Z
ziyoujiyi 已提交
686 687
        tensor = Tensor(self.tensor_dict)
        tensor._set(table_proto.tensor)
Z
ziyoujiyi 已提交
688 689


Z
ziyoujiyi 已提交
690 691
class SparseTable(Table):
    def __init__(self, context, send_ctx):
692
        super().__init__()
Z
ziyoujiyi 已提交
693 694 695 696 697
        self.context = context
        self.ctx = send_ctx
        self.type = None
        self.table_class = 'MemorySparseTable'
        self.accessor = Accessor()
Z
ziyoujiyi 已提交
698

Z
ziyoujiyi 已提交
699 700
    def _set(self, table_proto):
        ctx = self.ctx
701 702 703
        if (
            ctx.is_tensor_table()
            or len(ctx.origin_varnames()) < 1
704
            or (not ctx.is_sparse())
705
        ):
Z
ziyoujiyi 已提交
706 707 708
            return
        table_proto.table_id = ctx.table_id()
        table_proto.table_class = self.table_class
Z
ziyoujiyi 已提交
709
        table_proto.type = the_one_ps_pb2.PS_SPARSE_TABLE
Z
ziyoujiyi 已提交
710
        table_proto.shard_num = self.shard_num
711
        if table_proto.sparse_table_cache_file_num > len(
712 713
            get_ps_endpoints(self.context['role_maker'])
        ):
714
            table_proto.sparse_table_cache_file_num = len(
715 716
                get_ps_endpoints(self.context['role_maker'])
            )
Z
ziyoujiyi 已提交
717 718

        self.common.table_name = self.context['grad_name_to_param_name'][
719 720
            ctx.origin_varnames()[0]
        ]
Z
ziyoujiyi 已提交
721

722
        self.common.parse_by_optimizer(ctx, self.context)
723 724 725
        self.common.parse_entry(
            self.common.table_name, ctx.program_id(), self.context
        )
726 727 728 729
        self.common.sync = True if self.context['is_sync'] else False

        self.common._set(table_proto.common)

Z
ziyoujiyi 已提交
730 731
        print('new table_name: {}'.format(self.common.table_name))
        all_table_proto = self.context[
732 733
            "user_defined_strategy"
        ].sparse_table_configs
Z
ziyoujiyi 已提交
734 735 736 737 738
        usr_table_proto = all_table_proto.add()
        for proto in all_table_proto:
            if proto.table_name == self.common.table_name:
                usr_table_proto = proto
                break
739 740 741 742 743
        if usr_table_proto.HasField("table_class"):
            table_proto.table_class = usr_table_proto.table_class
        else:
            table_proto.table_class = 'MemorySparseTable'
            warnings.warn("The PS mode must use MemorySparseTable.")
Z
ziyoujiyi 已提交
744 745 746
        if usr_table_proto.HasField("shard_num"):
            table_proto.shard_num = usr_table_proto.shard_num
        else:
747 748 749 750 751 752 753 754 755 756
            if self.context['use_ps_gpu']:
                table_proto.shard_num = 37
                warnings.warn(
                    "The shard_num of sparse table is not set, use default value 37 in gpups."
                )
            else:
                table_proto.shard_num = 1000
                warnings.warn(
                    "The shard_num of sparse table is not set, use default value 1000 in cpups."
                )
Z
ziyoujiyi 已提交
757

758
        if usr_table_proto.HasField("enable_sparse_table_cache"):
759 760 761
            table_proto.enable_sparse_table_cache = (
                usr_table_proto.enable_sparse_table_cache
            )
762
        if usr_table_proto.HasField("sparse_table_cache_rate"):
763 764 765
            table_proto.sparse_table_cache_rate = (
                usr_table_proto.sparse_table_cache_rate
            )
766
        if usr_table_proto.HasField("sparse_table_cache_file_num"):
767 768 769
            table_proto.sparse_table_cache_file_num = (
                usr_table_proto.sparse_table_cache_file_num
            )
770 771 772 773 774
        if usr_table_proto.HasField("enable_revert"):
            table_proto.enable_revert = usr_table_proto.enable_revert
        if usr_table_proto.HasField("shard_merge_rate"):
            table_proto.shard_merge_rate = usr_table_proto.shard_merge_rate

Z
ziyoujiyi 已提交
775 776
        if usr_table_proto.accessor.ByteSize() == 0:
            warnings.warn(
777 778
                "The accessor of sparse table is not set, use default value."
            )
Z
ziyoujiyi 已提交
779

Z
ziyoujiyi 已提交
780
        table_proto.accessor.ParseFromString(
781 782 783 784 785 786 787 788 789
            usr_table_proto.accessor.SerializeToString()
        )
        self.accessor._set(
            table_proto.accessor,
            self.common.table_name,
            ctx.program_id(),
            self.context,
            self.common,
        )
Z
ziyoujiyi 已提交
790

791 792 793 794 795 796
        check_embedding_dim(
            table_proto.accessor,
            self.common.table_name,
            ctx.program_id(),
            self.context,
        )
Z
ziyoujiyi 已提交
797 798


Z
ziyoujiyi 已提交
799 800
class GeoSparseTable(SparseTable):
    def __init__(self, context, send_ctx):
801
        super().__init__(context, send_ctx)
802
        self.table_class = "MemorySparseGeoTable"
Z
ziyoujiyi 已提交
803 804 805 806 807
        if self.context['ps_mode'] != DistributedMode.GEO:
            raise ValueError("not geo sparse table!")

    def _set(self, table_proto):
        ctx = self.ctx
808 809 810
        if (
            ctx.is_tensor_table()
            or len(ctx.origin_varnames()) < 1
811
            or (not ctx.is_sparse())
812
        ):
Z
ziyoujiyi 已提交
813 814 815
            return
        table_proto.table_id = ctx.table_id()
        table_proto.table_class = self.table_class
Z
ziyoujiyi 已提交
816
        table_proto.type = the_one_ps_pb2.PS_SPARSE_TABLE
Z
ziyoujiyi 已提交
817 818 819 820 821 822 823
        table_proto.shard_num = self.shard_num

        table_proto.accessor.accessor_class = 'CommMergeAccessor'
        table_proto.accessor.fea_dim = ctx.sections()[0]
        table_proto.accessor.embedx_dim = ctx.sections()[1]

        self.common.table_name = self.context['grad_name_to_param_name'][
824 825
            ctx.origin_varnames()[0]
        ]
Z
ziyoujiyi 已提交
826
        self.common.parse_by_optimizer(ctx, self.context)
827 828 829
        self.common.parse_entry(
            self.common.table_name, ctx.program_id(), self.context
        )
Z
ziyoujiyi 已提交
830 831 832 833 834 835
        self.common.sync = False
        self.common._set(table_proto.common)


class DenseTable(Table):
    def __init__(self, context, send_ctx):
836
        super().__init__()
Z
ziyoujiyi 已提交
837 838 839
        self.context = context
        self.ctx = send_ctx
        self.accessor = Accessor()
Z
ziyoujiyi 已提交
840

Z
ziyoujiyi 已提交
841 842
    def _set(self, table_proto):
        ctx = self.ctx
843 844 845
        if (
            ctx.is_tensor_table()
            or len(ctx.origin_varnames()) < 1
846
            or (ctx.is_sparse())
847
        ):
Z
ziyoujiyi 已提交
848 849 850 851
            return

        table_proto.table_id = ctx.table_id()

Z
ziyoujiyi 已提交
852
        table_proto.type = the_one_ps_pb2.PS_DENSE_TABLE
853
        table_proto.table_class = "MemoryDenseTable"
Z
ziyoujiyi 已提交
854 855 856 857 858 859 860 861
        table_proto.shard_num = 256

        table_proto.accessor.accessor_class = 'CommMergeAccessor'
        table_proto.accessor.fea_dim = ctx.sections()[0]
        table_proto.accessor.embedx_dim = 1

        self.common.table_name = "MergedDense"
        self.common.parse_by_optimizer(ctx, self.context)
862 863 864
        self.common.parse_entry(
            self.common.table_name, ctx.program_id(), self.context
        )
Z
ziyoujiyi 已提交
865 866 867 868 869 870
        self.common.sync = True if self.context['is_sync'] else False

        self.common._set(table_proto.common)


class Server:
Z
ziyoujiyi 已提交
871
    def __init__(self):
Z
ziyoujiyi 已提交
872
        pass
Z
ziyoujiyi 已提交
873

Z
ziyoujiyi 已提交
874 875
    def _set(self):
        pass
Z
ziyoujiyi 已提交
876 877


Z
ziyoujiyi 已提交
878 879
class DownpourServer(Server):
    def __init__(self):
880
        super().__init__()
Z
ziyoujiyi 已提交
881 882 883

    def _set(self):
        pass
Z
ziyoujiyi 已提交
884 885 886 887


class Worker:
    def __init__(self):
Z
ziyoujiyi 已提交
888
        pass
Z
ziyoujiyi 已提交
889

Z
ziyoujiyi 已提交
890 891
    def _set(self):
        pass
Z
ziyoujiyi 已提交
892 893


Z
ziyoujiyi 已提交
894 895
class DownpourWorker(Worker):
    def __init__(self):
896
        super().__init__()
Z
ziyoujiyi 已提交
897 898 899

    def _set(self):
        pass
Z
ziyoujiyi 已提交
900 901 902


class fsClient:
Z
ziyoujiyi 已提交
903 904 905 906 907 908 909 910 911 912 913 914
    def __init__(self, fs_client_param):
        self.fs_client_param = fs_client_param

    def _set(self, proto):
        if not text_format.MessageToString(self.fs_client_param):
            return
        proto.uri = self.fs_client_param.uri
        proto.user = self.fs_client_param.user
        proto.passwd = self.fs_client_param.passwd
        proto.hadoop_bin = self.fs_client_param.hadoop_bin


915
class PsDescBuilder:
Z
ziyoujiyi 已提交
916 917 918 919 920 921
    def __init__(self, context):
        self.context = context
        self.is_sync = context['is_sync']
        self.ps_mode = context['ps_mode']
        self.is_heter_ps_mode = context['is_heter_ps_mode']
        self.use_ps_gpu = context['use_ps_gpu']
922
        self.barrier_table_id = None
923

Z
ziyoujiyi 已提交
924
        self.send_ctx = get_the_one_send_context(
925 926
            self.context, split_dense_table=self.is_heter_ps_mode
        )
Z
ziyoujiyi 已提交
927 928 929 930 931 932 933 934 935

        self.tensor_table_dict = {}  # TODO
        self._server_sub_program = []

        self.tables = self._get_tables()

        self.service = self._get_service()
        self.fs_client = self._get_fs_client()

Z
ziyoujiyi 已提交
936
        self.ps_desc = the_one_ps_pb2.PSParameter()
937
        self.fl_desc = the_one_ps_pb2.FLParameter()
Z
ziyoujiyi 已提交
938 939 940 941 942 943 944

    def _get_tensor_tables(self):
        program_idx = 0
        if not self.tensor_table_dict:
            self._server_sub_program.append(Program().desc)
        tables = []
        for table_name in self.tensor_table_dict:
945 946 947 948 949
            tables.append(
                globals()['TensorTable'](
                    len(tables), tensor_dict, self.context['role_maker']
                )
            )
Z
ziyoujiyi 已提交
950 951 952 953 954 955
            program_idx += 1
        return tables

    def _get_tables(self):
        tables = []
        for idx, (name, ctx) in enumerate(self.send_ctx.items()):
956
            print("idx, name, ctx:", idx, name, ctx)
Z
ziyoujiyi 已提交
957 958
            if ctx.is_sparse():
                if self.ps_mode == DistributedMode.GEO:
959 960 961 962 963 964 965
                    if (
                        self.context['local_sparse']
                        and name[:-5] in self.context['local_sparse']
                    ) or (not self.context['local_sparse']):
                        tables.append(
                            globals()['GeoSparseTable'](self.context, ctx)
                        )
Z
ziyoujiyi 已提交
966
                    else:
967 968 969
                        tables.append(
                            globals()['SparseTable'](self.context, ctx)
                        )
Z
ziyoujiyi 已提交
970 971 972 973 974 975 976 977 978 979 980 981
                else:
                    tables.append(globals()['SparseTable'](self.context, ctx))
            else:
                tables.append(globals()['DenseTable'](self.context, ctx))
        self.tensor_tables = self._get_tensor_tables()
        tables.extend(self.tensor_tables)
        tables.append(globals()['BarrierTable'](self.context, len(tables)))
        return tables

    def _get_service(self):
        if self.use_ps_gpu:
            return GpuService()
Z
ziyoujiyi 已提交
982
        else:
Z
ziyoujiyi 已提交
983 984 985 986 987
            return Service()

    def _get_fs_client(self):
        return fsClient(self.context["user_defined_strategy"].fs_client_param)

988 989 990
    def build_fl_client_desc(self, client_info):
        pass

Z
ziyoujiyi 已提交
991 992
    def build_worker_desc(self):
        for table in self.tables:
993 994
            table_proto = (
                self.ps_desc.worker_param.downpour_worker_param.downpour_table_param.add()
Z
ziyoujiyi 已提交
995 996
            )
            table._set(table_proto)
997 998
            table_proto = (
                self.ps_desc.server_param.downpour_server_param.downpour_table_param.add()
Z
ziyoujiyi 已提交
999 1000
            )
            table._set(table_proto)
1001 1002
            if type(table) == BarrierTable and self.barrier_table_id is None:
                self.barrier_table_id = table.idx
Z
ziyoujiyi 已提交
1003
        self.service._set(
1004 1005
            self.ps_desc.server_param.downpour_server_param.service_param
        )
1006
        self.fs_client._set(self.ps_desc.fs_client_param)
Z
ziyoujiyi 已提交
1007 1008 1009
        return text_format.MessageToString(self.ps_desc)

    def build_server_desc(self):
1010
        self.sparse_table_maps = {}
Z
ziyoujiyi 已提交
1011
        for table in self.tables:
1012 1013
            table_proto = (
                self.ps_desc.server_param.downpour_server_param.downpour_table_param.add()
Z
ziyoujiyi 已提交
1014 1015
            )
            table._set(table_proto)
1016 1017 1018 1019
            if (
                table_proto.type == the_one_ps_pb2.PS_SPARSE_TABLE
                and table_proto.common is not None
            ):
Z
ziyoujiyi 已提交
1020
                self.sparse_table_maps[
1021 1022
                    table_proto.common.table_name
                ] = table_proto.table_id
Z
ziyoujiyi 已提交
1023 1024

        self.service._set(
1025 1026
            self.ps_desc.server_param.downpour_server_param.service_param
        )
Z
ziyoujiyi 已提交
1027 1028
        self.fs_client._set(self.ps_desc.fs_client_param)
        return text_format.MessageToString(self.ps_desc)
Z
ziyoujiyi 已提交
1029 1030 1031 1032


class TheOnePSRuntime(RuntimeBase):
    def __init__(self):
1033
        super().__init__()
Z
ziyoujiyi 已提交
1034 1035
        self._communicator = None
        self._server = None
W
wangguanqun 已提交
1036
        self._worker = core.DistFleetWrapper()
1037
        self._coordinator = None
Z
ziyoujiyi 已提交
1038 1039
        self._server_sub_program = []
        self._heter_client = None
1040
        self._send_ctx = None
Z
ziyoujiyi 已提交
1041 1042 1043 1044

    def _set_basic_info(self, context):
        self.context = context
        self.role_maker = context["role_maker"]
1045 1046
        self.role_id = get_role_id(self.role_maker)
        self.debug = bool(int(os.getenv("PSERVER_DEBUG", "0")))
W
wangguanqun 已提交
1047

Z
ziyoujiyi 已提交
1048
        self.origin_main_program = context["origin_main_program"]
1049 1050 1051
        self.origin_main_programs = context.get(
            "origin_main_programs", [self.origin_main_program]
        )
Z
ziyoujiyi 已提交
1052 1053
        self.context["origin_main_programs"] = self.origin_main_programs
        self.context["origin_startup_programs"] = context.get(
1054 1055
            'origin_startup_programs', [context['origin_startup_program']]
        )
Z
ziyoujiyi 已提交
1056
        self.context[
1057 1058
            'is_heter_ps_mode'
        ] = self.role_maker._is_heter_parameter_server_mode
Z
ziyoujiyi 已提交
1059
        self.is_heter_ps_mode = self.context['is_heter_ps_mode']
1060
        self.context['trainer'] = TrainerRuntimeConfig(
1061 1062
            context['valid_strategy']
        )
Z
ziyoujiyi 已提交
1063
        self.context['ps_mode'] = self.context['trainer'].mode
W
wangguanqun 已提交
1064
        self.context['use_ps_gpu'] = context['valid_strategy'].a_sync_configs[
1065 1066 1067 1068 1069
            'use_ps_gpu'
        ]
        self.context['is_sync'] = (
            True if self.context['ps_mode'] == DistributedMode.SYNC else False
        )
Z
ziyoujiyi 已提交
1070
        self.context['grad_name_to_param_name'] = {}
W
wangguanqun 已提交
1071
        self.context['tensor_table'] = {}
1072 1073
        # FL
        self.context['local_sparse'] = context[
1074 1075
            "user_defined_strategy"
        ].trainer_desc_configs["local_sparse"]
1076
        self.context['remote_sparse'] = context[
1077 1078 1079 1080 1081 1082 1083
            "user_defined_strategy"
        ].trainer_desc_configs["remote_sparse"]
        print(
            "fl-ps > local_sparse: {}, remote_sparse: {}".format(
                self.context['local_sparse'], self.context['remote_sparse']
            )
        )
1084

W
wangguanqun 已提交
1085
        build_var_distributed(self.context)
Z
ziyoujiyi 已提交
1086

1087 1088
        self.trainer_endpoints = get_trainer_endpoints(self.role_maker)

1089
        self.endpoints = get_ps_endpoints(self.role_maker)
Z
ziyoujiyi 已提交
1090
        self.string_hosts = []
1091
        for idx, ep in enumerate(self.endpoints):
Z
ziyoujiyi 已提交
1092
            host, port = ep.split(":")
W
wangguanqun 已提交
1093
            pshost = core.PSHost(host, int(port), idx)
Z
ziyoujiyi 已提交
1094 1095
            self.string_hosts.append(pshost.serialize_to_string())

1096 1097 1098 1099 1100 1101 1102
        self.with_coordinator = self.role_maker._with_coordinator
        self.coordinator_hosts = []
        if self.with_coordinator:
            print("fl-ps > all ps addrs: {}".format(self.string_hosts))
            coordinator_endpoints = self.role_maker._get_coordinator_endpoints()
            for idx, ep in enumerate(coordinator_endpoints):
                ip, port = ep.split(":")
W
wangguanqun 已提交
1103
                pshost = core.PSHost(ip, int(port), idx)
1104 1105
                self.coordinator_hosts.append(pshost.serialize_to_string())

Z
ziyoujiyi 已提交
1106 1107
        self.ps_desc_builder = PsDescBuilder(self.context)

1108
    def _init_all_params(self, scopes, send_ctx, recv_map):
1109
        all_var_names = []
1110 1111 1112 1113 1114 1115 1116
        for name, ctx in send_ctx.items():
            if ctx.is_sparse():
                continue
            _, _, idx = get_program_by_id(self.context, ctx.program_id())
            scope = scopes[idx]
            table_id = ctx.table_id()
            var_names = recv_map[table_id]
1117
            # print("init params:", idx, table_id, var_names)
1118
            self._worker.push_dense_params(scope, table_id, var_names)
1119 1120
            all_var_names.extend(var_names)
        return all_var_names
1121 1122

    def _pull_all_dense(self, scopes, send_ctx, recv_map):
1123
        all_var_names = []
1124 1125 1126 1127 1128 1129 1130
        for name, ctx in send_ctx.items():
            if ctx.is_sparse():
                continue
            _, _, idx = get_program_by_id(self.context, ctx.program_id())
            scope = scopes[idx]
            table_id = ctx.table_id()
            var_names = recv_map[table_id]
1131
            # print("pull all dense:", idx, table_id, var_names)
1132
            self._worker.pull_dense_params(scope, table_id, var_names)
1133 1134
            all_var_names.extend(var_names)
        return all_var_names
1135

1136
    def _init_params(self, program, scope, send_ctx, recv_map):
1137
        all_var_names = []
1138 1139 1140 1141 1142 1143 1144 1145 1146
        for name, ctx in send_ctx.items():
            if ctx.is_sparse():
                continue
            if ctx.program_id() != id(program):
                continue
            table_id = ctx.table_id()
            var_names = recv_map[table_id]
            # print("init params:", table_id, var_names)
            self._worker.push_dense_params(scope, table_id, var_names)
1147 1148
            all_var_names.extend(var_names)
        return all_var_names
1149

1150
    def _pull_dense(self, program, scope, send_ctx, recv_map):
1151
        all_var_names = []
1152 1153 1154 1155 1156 1157 1158 1159 1160
        for name, ctx in send_ctx.items():
            if ctx.is_sparse():
                continue
            if ctx.program_id() != id(program):
                continue
            table_id = ctx.table_id()
            var_names = recv_map[table_id]
            # print("pull dense:", table_id, var_names)
            self._worker.pull_dense_params(scope, table_id, var_names)
1161 1162
            all_var_names.extend(var_names)
        return all_var_names
1163 1164

    def _init_worker(self, scopes=None):
Z
ziyoujiyi 已提交
1165
        worker_desc = self.ps_desc_builder.build_worker_desc()
Z
ziyoujiyi 已提交
1166 1167 1168 1169 1170 1171
        if self.context['use_ps_gpu']:
            main_program = self.context['loss'].block.program
            if not main_program._fleet_opt:
                main_program._fleet_opt = {}
            main_program._fleet_opt["use_ps_gpu"] = True
            gpus_env = os.getenv("FLAGS_selected_gpus")
1172 1173
            gpus_env = [int(s) for s in gpus_env.split(",")]
            main_program._fleet_opt["worker_places"] = gpus_env
W
wangguanqun 已提交
1174
            PSGPU = core.PSGPU()
1175
            PSGPU.init_gpu_ps(gpus_env)
Z
ziyoujiyi 已提交
1176 1177 1178 1179

        def sync_strategy_envs():
            kwargs = {}
            kwargs[
1180 1181
                "pserver_endpoints"
            ] = self.role_maker._get_pserver_endpoints()
Z
ziyoujiyi 已提交
1182 1183 1184 1185
            kwargs["trainer_id"] = self.role_maker._worker_index()
            return kwargs

        dense_map = get_the_one_recv_context(
1186 1187
            self.context, split_dense_table=self.is_heter_ps_mode
        )
Z
ziyoujiyi 已提交
1188 1189 1190
        send_ctx = get_the_one_send_context(
            self.context,
            split_dense_table=self.is_heter_ps_mode,
1191 1192
            ep_list=self.endpoints,
        )
1193
        self._send_ctx = send_ctx
Z
ziyoujiyi 已提交
1194 1195
        trainer_config = self.context['trainer']

1196 1197
        if self.debug:
            print("worker_desc: \n{}".format(worker_desc))
Z
ziyoujiyi 已提交
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
            print("communicator send_ctx:")
            for key in send_ctx:
                print("{}: {}".format(key, send_ctx[key]))
            for key in dense_map:
                print("{}: {}".format(key, dense_map[key]))

        kwargs = {}
        kwargs['need_global_step'] = "0"
        kwargs["trainer_id"] = self.role_maker._role_id()
        kwargs["trainers"] = self.role_maker._worker_num()

1209
        kwargs["barrier_table_id"] = self.ps_desc_builder.barrier_table_id
Z
ziyoujiyi 已提交
1210 1211 1212 1213 1214

        if self.context['ps_mode'] == DistributedMode.SYNC:
            sync_kwargs = sync_strategy_envs()
            kwargs.update(sync_kwargs)

W
wangguanqun 已提交
1215
        print("communicator config:", trainer_config.get_communicator_flags())
Z
ziyoujiyi 已提交
1216

1217
        self._worker.init_worker(worker_desc, self.string_hosts, self.role_id)
Z
ziyoujiyi 已提交
1218 1219 1220
        if not self.is_heter_ps_mode:
            self.trainer_endpoint = get_trainer_endpoint(self.role_maker)
            print("fl-ps > trainer_endpoint: {}".format(self.trainer_endpoint))
1221 1222 1223
        print("fl-ps > with_coordinator? {}".format(self.with_coordinator))
        print("fl-ps > coordinator addr: {}".format(self.coordinator_hosts))
        if self.with_coordinator:
1224 1225 1226
            self._worker.init_fl_worker(
                self.coordinator_hosts, self.role_id, self.trainer_endpoint
            )
1227

1228 1229 1230 1231
        if (
            self.context['ps_mode'] == DistributedMode.GEO
            or self.is_heter_ps_mode
        ):
1232
            self._communicator = Communicator(
1233 1234 1235 1236 1237 1238 1239 1240 1241
                trainer_config.mode,
                kwargs,
                trainer_config.get_communicator_flags(),
            )
            self._communicator.init_with_ctx(
                send_ctx,
                dense_map,
                worker_desc,
                self.string_hosts,
W
wangguanqun 已提交
1242
                paddle.static.global_scope(),
1243
            )
Z
ziyoujiyi 已提交
1244
        fleet.util.barrier()
1245 1246 1247

        # info = self._communicator.get_client_info()
        info = self._worker.get_client_info()
Z
ziyoujiyi 已提交
1248
        if isinstance(info, list) and len(info) > 0:
1249
            all_info = self.role_maker._all_gather(
1250 1251
                info[0]
            )  # 收集其他 client 的 service 地址
Z
ziyoujiyi 已提交
1252 1253 1254 1255
            # for unittest
            if not isinstance(all_info, list):
                warnings.warn("gloo may not initialize correctly")
                all_info = [all_info]
1256 1257 1258 1259 1260

            # self._communicator.set_clients(all_info)
            # self._communicator.create_client_to_client_connection()
            self._worker.set_clients(all_info)
            self._worker.create_client2client_connection()
Z
ziyoujiyi 已提交
1261 1262 1263 1264 1265 1266 1267 1268
            print('create c2c connection done')
        else:
            print('cannot create c2c connection')

        dist_strategy = self.context["valid_strategy"]

        is_test = bool(int(os.getenv("TEST_MODE", "0")))

1269 1270 1271 1272 1273
        if scopes is None:
            if len(self.origin_main_programs) > 1:
                raise ValueError(
                    "You must set the scope list when you have Multiple programs"
                )
W
wangguanqun 已提交
1274
            scopes = [paddle.static.global_scope()]
1275 1276 1277 1278
        if len(self.origin_main_programs) != len(scopes):
            raise VauleError("len(programs) != len(scopes)")

        self.scopes = scopes
Z
ziyoujiyi 已提交
1279
        if not is_test:
1280 1281
            if (
                self.context['ps_mode'] == DistributedMode.GEO
1282
                or self.is_heter_ps_mode
1283
            ):
1284
                self._communicator.init_params(dense_map)
1285
            else:
D
danleifeng 已提交
1286
                if not self.context['use_ps_gpu']:
1287
                    if self.role_id == 0:
1288
                        print("entering self._init_all_params()")
D
danleifeng 已提交
1289
                        self._init_all_params(scopes, send_ctx, dense_map)
1290

1291 1292
            fleet.util.barrier()  # 保证 0 号 worker 参数 push_dense_param over

D
danleifeng 已提交
1293
        if not self.context['use_ps_gpu']:
Z
ziyoujiyi 已提交
1294
            self._pull_all_dense(scopes, send_ctx, dense_map)
Z
ziyoujiyi 已提交
1295 1296
        fleet.util.barrier()

1297 1298
        if (
            self.context['ps_mode'] == DistributedMode.GEO
1299
            or self.is_heter_ps_mode
1300
        ):
1301 1302 1303 1304
            if not self._communicator.is_running():
                self._communicator.start()
            else:
                warnings.warn("communicator has been initialized, skip")
Z
ziyoujiyi 已提交
1305 1306 1307 1308 1309

        launch_barrier = dist_strategy.a_sync_configs["launch_barrier"]
        launch_barrier_flag = int(os.getenv("FLAGS_LAUNCH_BARRIER", "1"))
        if launch_barrier and launch_barrier_flag:
            wait_server_ready(self.role_maker._get_pserver_endpoints())
1310 1311 1312 1313
            if (
                self.is_heter_ps_mode
                and self.role_maker._get_next_trainers() != []
            ):
Z
ziyoujiyi 已提交
1314 1315 1316 1317 1318 1319 1320 1321
                wait_server_ready(self.role_maker._get_next_trainers())
            if self.is_heter_ps_mode:
                previous_trainers = []
                if self.role_maker._get_previous_trainers() != []:
                    previous_trainers = self.role_maker._get_previous_trainers()
                next_trainers = []
                if self.role_maker._get_next_trainers() != []:
                    next_trainers = self.role_maker._get_next_trainers()
1322
                self._heter_client = HeterClient(
1323 1324
                    next_trainers, previous_trainers, self.role_maker._role_id()
                )  # --> HeterClient::GetInstance
Z
ziyoujiyi 已提交
1325

1326
    def _init_coordinator(self, scopes=None):
1327
        if self._coordinator is None:
1328 1329 1330 1331
            self._coordinator = Coordinator(self.string_hosts)

        print(">>> curr node ip: {}".format(self.coordinator_hosts[0]))
        print(">>> all trainer endpoints: {}".format(self.trainer_endpoints))
1332 1333 1334
        self._coordinator.start_coordinator(
            self.coordinator_hosts[0], self.trainer_endpoints
        )
1335 1336

    def _make_fl_strategy(self):
1337
        if self._coordinator is None:
1338
            assert "Coordinator py object is null!"
1339 1340 1341
        else:
            self._coordinator.make_fl_strategy()

Z
ziyoujiyi 已提交
1342
    def _init_server(self, dirname=None, var_names=None, **kwargs):
Z
ziyoujiyi 已提交
1343
        server_desc = self.ps_desc_builder.build_server_desc()
Z
ziyoujiyi 已提交
1344 1345 1346 1347
        trainers = get_trainers(self.role_maker)
        if self.is_heter_ps_mode:
            trainers += len(self.role_maker._get_heter_worker_endpoints())

1348 1349
        if self.debug:
            print("server_desc: \n{}".format(server_desc))
W
wangguanqun 已提交
1350

W
wangguanqun 已提交
1351
        self._server = core.DistFleetWrapper()
1352 1353 1354 1355 1356 1357 1358
        self._server.init_server(
            server_desc,
            self.string_hosts,
            self.role_id,
            trainers,
            self._server_sub_program,
        )
Z
ziyoujiyi 已提交
1359

W
wangguanqun 已提交
1360
        dist_varnames = get_sparse_tablenames(self.origin_main_programs, True)
1361 1362 1363
        sparse_varnames = get_sparse_tablenames(
            self.origin_main_programs, False
        )
Z
ziyoujiyi 已提交
1364 1365 1366 1367 1368 1369 1370 1371 1372

        distributed_varnames = dist_varnames + sparse_varnames

        if var_names is None:
            load_varnames = distributed_varnames
        else:
            for var_name in var_names:
                if var_name not in distributed_varnames:
                    raise ValueError(
1373 1374 1375 1376
                        "fleet.init server can only load sparse variables in {}".format(
                            distributed_varnames
                        )
                    )
Z
ziyoujiyi 已提交
1377 1378 1379 1380 1381
            load_varnames = var_names

        if dirname is None or not load_varnames:
            return

Z
ziyoujiyi 已提交
1382
        sparse_table_maps = self.ps_desc_builder.sparse_table_maps
Z
ziyoujiyi 已提交
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396

        dirname = os.path.normpath(dirname)
        pserver_id = self.role_maker._role_id()

        for var_name in load_varnames:
            table_id = sparse_table_maps[var_name]
            self._server.load_sparse(dirname, "0", table_id)

    def _run_server(self):
        ep = get_ps_endpoint(self.role_maker)
        host, port = ep.split(":")
        self._server.run_server(host, int(port))

    def _stop_worker(self):
1397 1398 1399
        if self.context['ps_mode'] == DistributedMode.GEO:
            self._communicator.stop()
        self._worker.stop_worker()
Z
ziyoujiyi 已提交
1400
        if self.is_heter_ps_mode:
1401
            assert (
1402
                self._heter_client is not None
1403
            ), "heter client should not be None in heterps mode"
Z
ziyoujiyi 已提交
1404 1405 1406 1407 1408 1409 1410 1411
            self._heter_client.stop()

    @staticmethod
    def __exclude_vars(exclude_var_names=[]):
        def is_valid(var):
            if var.name in exclude_var_names:
                return False

W
wangguanqun 已提交
1412
            from .utils.public import _get_varname_parts
1413

Z
ziyoujiyi 已提交
1414 1415 1416 1417
            origin_varname, _, _ = _get_varname_parts(var.name)
            if origin_varname.endswith("@GRAD"):
                return False

1418
            if origin_varname.startswith("learning_rate_"):
Z
ziyoujiyi 已提交
1419 1420
                return False

1421 1422 1423 1424 1425
            if (
                var.desc.type() == core.VarDesc.VarType.FEED_MINIBATCH
                or var.desc.type() == core.VarDesc.VarType.FETCH_LIST
                or var.desc.type() == core.VarDesc.VarType.READER
            ):
Z
ziyoujiyi 已提交
1426 1427 1428 1429 1430
                return False
            return var.persistable

        return is_valid

W
wangguanqun 已提交
1431 1432 1433 1434 1435 1436 1437
    def _get_inference_model_path(self, dirname):
        if dirname.startswith("afs:") or dirname.startswith("hdfs:"):
            model_path = "./dnn_plugin"
        else:
            model_path = os.path.join(dirname, "dnn_plugin")
        return model_path

1438 1439 1440
    def _ps_save_dense_params(
        self, executor, dirname, scope, program, var_names=None
    ):
1441
        dense_map = get_the_one_recv_context(
1442 1443
            self.context, split_dense_table=self.is_heter_ps_mode
        )
1444 1445 1446
        send_ctx = get_the_one_send_context(
            self.context,
            split_dense_table=self.is_heter_ps_mode,
1447 1448
            ep_list=self.endpoints,
        )
1449 1450 1451 1452 1453 1454
        if program is None or len(self.origin_main_programs) == 1:
            program = self.origin_main_programs[0]
        dense_var_names = self._pull_dense(program, scope, send_ctx, dense_map)
        save_var_names = dense_var_names if var_names is None else var_names
        vars = [program.global_block().var(i) for i in save_var_names]
        import paddle
1455

1456
        with paddle.static.scope_guard(scope):
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
            paddle.static.save_vars(
                executor, "./", program, vars=vars, filename=dirname
            )

    def _save_sparse_params(
        self, executor, dirname, context, main_program, mode
    ):
        distributed_varnames = get_sparse_tablenames(
            self.origin_main_programs, True
        )
Z
ziyoujiyi 已提交
1467
        values = []
W
wangguanqun 已提交
1468
        model_path = self._get_inference_model_path(dirname)
Z
ziyoujiyi 已提交
1469 1470 1471 1472
        for id, names in context.items():
            if names[0] not in distributed_varnames:
                # only save sparse param to local
                try:
W
wangguanqun 已提交
1473
                    self._worker.recv_and_save_model(id, model_path)
Z
ziyoujiyi 已提交
1474 1475 1476 1477 1478 1479 1480 1481
                except:
                    pass
            # save sparse & distributed param on server
            self._worker.save_one_model(id, dirname, mode)
            values.extend(names)
        # self._worker.save_all_model(dirname, mode)
        return values

1482 1483 1484
    def _save_distributed_persistables(
        self, executor, dirname, main_program=None, mode=0, **kwargs
    ):
Z
ziyoujiyi 已提交
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
        """
        This function filters out all variables with `persistable==True` from the
        give `main_program` and then saves these variables to the folder `dirname`
        or file `filename`.

        The `dirname` is used to specify the folder where persistable variables
        are going to be saved. If you would like to save variables in separate
        files, set `filename` None; if you would like to save all variables in a
        single file, use `filename` to specify the file name.
        """

        if isinstance(executor, ParallelExecutor):
            raise TypeError(
                "in fleet.save() function, executor must be as Executor type, ParallelExecutor is not allowed"
            )

        if not isinstance(executor, Executor):
            raise TypeError(
1503 1504
                "in fleet.save() function, executor must be as Executor type"
            )
Z
ziyoujiyi 已提交
1505 1506

        if main_program is None:
1507
            main_program = self.context['origin_main_program']
Z
ziyoujiyi 已提交
1508 1509 1510 1511 1512 1513 1514 1515

        if isinstance(main_program, CompiledProgram):
            raise TypeError(
                "in fleet.save() function, main_program must be as Program type, CompiledProgram is not allowed"
            )

        self._worker.save_all_model(dirname, mode)

1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
    def _ps_inference_save_inference_model(
        self,
        executor,
        dirname,
        feeded_var_names,
        target_vars,
        main_program=None,
        export_for_deployment=True,
        mode=0,
    ):
Z
ziyoujiyi 已提交
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
        """
        Prune the given `main_program` to build a new program especially for inference,
        and then save it and all related parameters to given `dirname` by the `executor`.
        """

        if isinstance(executor, ParallelExecutor):
            raise TypeError(
                "in fleet.save() function, executor must be as Executor type, ParallelExecutor is not allowed"
            )

        if not isinstance(executor, Executor):
            raise TypeError(
1538 1539
                "in fleet.save() function, executor must be as Executor type"
            )
Z
ziyoujiyi 已提交
1540 1541

        import paddle
1542 1543 1544 1545 1546 1547

        program = (
            self.origin_main_programs[0]
            if main_program is None
            else main_program
        )
1548 1549 1550
        _, _, idx = get_program_by_id(self.context, id(program))
        scope = self.scopes[idx]
        print("save inference model scope idx:", idx)
Z
ziyoujiyi 已提交
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560

        if isinstance(program, CompiledProgram):
            raise TypeError(
                "in fleet.save() function, main_program must be as Program type, CompiledProgram is not allowed"
            )

        feed_vars = [
            program.global_block().var(name) for name in feeded_var_names
        ]

1561 1562 1563
        infer_program = paddle.static.normalize_program(
            program, feed_vars, target_vars
        )
Z
ziyoujiyi 已提交
1564 1565 1566

        infer_program._copy_dist_param_info_from(program)

W
wangguanqun 已提交
1567
        model_path = self._get_inference_model_path(dirname)
Z
ziyoujiyi 已提交
1568 1569 1570 1571 1572 1573 1574
        model_basename = "__model__"
        model_basename = os.path.join(model_path, model_basename)
        paddle.save(infer_program, model_basename)

        sparses = get_the_one_recv_context(
            self.context,
            is_dense=False,
1575 1576 1577 1578 1579
            split_dense_table=self.is_heter_ps_mode,
        )
        sparse_names = self._save_sparse_params(
            executor, dirname, sparses, main_program, mode
        )
Z
ziyoujiyi 已提交
1580

1581
        dense_map = get_the_one_recv_context(
1582 1583
            self.context, split_dense_table=self.is_heter_ps_mode
        )
1584
        send_ctx = get_the_one_send_context(
Z
ziyoujiyi 已提交
1585 1586
            self.context,
            split_dense_table=self.is_heter_ps_mode,
1587 1588
            ep_list=self.endpoints,
        )
1589
        self._pull_dense(program, scope, send_ctx, dense_map)
Z
ziyoujiyi 已提交
1590 1591

        generate_vars = self.context[
1592 1593
            "user_defined_strategy"
        ].trainer_desc_configs["stat_var_names"]
Z
ziyoujiyi 已提交
1594 1595
        generate_vars = [var for var in generate_vars]
        remaining_vars = list(
1596 1597 1598 1599 1600
            filter(
                TheOnePSRuntime.__exclude_vars(sparse_names),
                infer_program.list_vars(),
            )
        )
Z
ziyoujiyi 已提交
1601 1602

        for var in remaining_vars:
1603
            tensor = var.get_value(scope)
1604 1605 1606 1607 1608
            paddle.save(
                tensor,
                os.path.join(model_path, var.name),
                use_binary_format=True,
            )
Z
ziyoujiyi 已提交
1609

Z
zhaocaibei123 已提交
1610
    def _save_cache_model(self, dirname, **kwargs):
1611
        mode = kwargs.get("mode", 1)
Z
zhaocaibei123 已提交
1612 1613 1614 1615 1616 1617 1618
        table_id = kwargs.get("table_id", 0)
        self._worker.client_flush()
        fleet.util.barrier()
        cache_threshold = 0.0

        if self.role_maker._is_first_worker():
            cache_threshold = self._worker.get_cache_threshold(table_id)
1619
        # check cache threshold right or not
Z
zhaocaibei123 已提交
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
        fleet.util.barrier()

        if self.role_maker._is_first_worker():
            self._worker.cache_shuffle(table_id, dirname, mode, cache_threshold)

        fleet.util.barrier()

        feasign_num = -1
        if self.role_maker._is_first_worker():
            feasign_num = self._worker.save_cache(table_id, dirname, mode)

        fleet.util.barrier()
        return feasign_num

1634 1635 1636 1637 1638 1639
    def _check_save_pre_patch_done(self):
        fleet.util.barrier()
        if self.role_maker._is_first_worker():
            self._worker.check_save_pre_patch_done()
        fleet.util.barrier()

Z
ziyoujiyi 已提交
1640
    def _load_sparse_params(self, dirname, context, main_program, mode):
1641 1642 1643
        distributed_varnames = get_sparse_tablenames(
            self.origin_main_programs, True
        )
Z
ziyoujiyi 已提交
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
        values = []
        for id, names in context.items():
            if names[0] not in distributed_varnames:
                # TODO: only load sparse param from local
                warnings.warn("varname is not in distributed_varnames, pass")
            # load sparse & distributed param on server
            self._worker.load_one_table(id, dirname, mode)
            values.extend(names)
        return values

1654 1655 1656 1657 1658 1659 1660 1661
    def _ps_inference_load_inference_model(
        self, dirname, mode=0, main_program=None
    ):
        main_program = (
            self.origin_main_programs[0]
            if main_program is None
            else main_program
        )
1662 1663 1664
        _, _, idx = get_program_by_id(self.context, id(main_program))
        scope = self.scopes[idx]
        print("load inference model scope idx:", idx)
Z
ziyoujiyi 已提交
1665 1666 1667 1668 1669 1670 1671 1672 1673

        if isinstance(main_program, CompiledProgram):
            raise TypeError(
                "in fleet.save() function, main_program must be as Program type, CompiledProgram is not allowed"
            )

        sparses = get_the_one_recv_context(
            self.context,
            is_dense=False,
1674 1675
            split_dense_table=self.is_heter_ps_mode,
        )
Z
ziyoujiyi 已提交
1676

1677 1678 1679
        sparse_varnames = self._load_sparse_params(
            dirname, sparses, main_program, mode
        )
Z
ziyoujiyi 已提交
1680

1681
        dense_map = get_the_one_recv_context(
1682 1683
            self.context, split_dense_table=self.is_heter_ps_mode
        )
1684 1685 1686
        send_ctx = get_the_one_send_context(
            self.context,
            split_dense_table=self.is_heter_ps_mode,
1687 1688
            ep_list=self.endpoints,
        )
1689

Z
ziyoujiyi 已提交
1690
        recv_dense_varnames = []
1691
        for _, names in dense_map.items():
Z
ziyoujiyi 已提交
1692 1693 1694 1695 1696
            recv_dense_varnames.extend(names)

        loaded_varnames = sparse_varnames

        remaining_vars = list(
1697 1698 1699 1700 1701
            filter(
                TheOnePSRuntime.__exclude_vars(loaded_varnames),
                main_program.list_vars(),
            )
        )
Z
ziyoujiyi 已提交
1702

1703
        model_path = self._get_inference_model_path(dirname)
Z
ziyoujiyi 已提交
1704
        import paddle
1705

Z
ziyoujiyi 已提交
1706 1707 1708 1709
        for var in remaining_vars:
            if var.name not in recv_dense_varnames:
                continue
            tensor = paddle.load(os.path.join(model_path, var.name))
1710
            var.set_value(tensor, scope)
Z
ziyoujiyi 已提交
1711

1712
        self._init_params(main_program, scope, send_ctx, dense_map)
Z
ziyoujiyi 已提交
1713

1714
    def _save_one_table(self, table_id, path, mode):
1715
        fleet.util.barrier()
1716 1717 1718
        if self.role_maker._is_first_worker():
            self._worker.save_one_model(table_id, path, mode)
        fleet.util.barrier()
Z
ziyoujiyi 已提交
1719

1720
    def _save_dense_params(self, *args, **kwargs):
1721
        fleet.util.barrier()
1722 1723 1724 1725 1726
        if self.role_maker._is_first_worker():
            self._ps_save_dense_params(*args, **kwargs)
        fleet.util.barrier()

    def _save_persistables(self, *args, **kwargs):
1727
        fleet.util.barrier()
1728 1729 1730 1731 1732
        if self.role_maker._is_first_worker():
            self._save_distributed_persistables(*args, **kwargs)
        fleet.util.barrier()

    def _save_inference_model(self, *args, **kwargs):
1733
        fleet.util.barrier()
1734 1735 1736 1737 1738
        if self.role_maker._is_first_worker():
            self._ps_inference_save_inference_model(*args, **kwargs)
        fleet.util.barrier()

    def _load_one_table(self, table_id, path, mode):
1739
        fleet.util.barrier()
1740 1741 1742 1743 1744
        if self.role_maker._is_first_worker():
            self._worker.load_one_table(table_id, path, mode)
        fleet.util.barrier()

    def _load_persistables(self, path, mode):
1745
        fleet.util.barrier()
1746 1747 1748 1749 1750
        if self.role_maker._is_first_worker():
            self._worker.load_model(path, mode)
        fleet.util.barrier()

    def _load_inference_model(self, path, mode):
1751
        fleet.util.barrier()
1752
        if self.role_maker._is_first_worker():
Z
ziyoujiyi 已提交
1753
            self._ps_inference_load_inference_model(path, mode)
1754
        fleet.util.barrier()
Z
ziyoujiyi 已提交
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765

    def _shrink(self, threshold=None):
        if threshold is not None:
            warnings.warn(
                "The param threshold is not used in MemorySparseTable, if you need to shrink, please set the config of accessor"
            )
        else:
            threshold = 0

        fleet.util.barrier()
        if self.role_maker._is_first_worker():
Z
ziyoujiyi 已提交
1766
            sparses = get_the_one_recv_context(
Z
ziyoujiyi 已提交
1767 1768
                self.context,
                is_dense=False,
1769 1770
                split_dense_table=self.role_maker._is_heter_parameter_server_mode,
            )
Z
ziyoujiyi 已提交
1771 1772 1773 1774

            for id, names in sparses.items():
                self._worker.shrink_sparse_table(id, threshold)
        fleet.util.barrier()