node.py 30.0 KB
Newer Older
D
dongdaxiang 已提交
1 2 3 4 5 6 7 8 9 10 11 12
#   Copyright (c) 2018 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
13
"""Defination of Server and Worker."""
D
dongdaxiang 已提交
14

15
from . import ps_pb2 as pslib
16 17
# NOTE: reduce removed in fuctools in python3
from functools import reduce
D
dongdaxiang 已提交
18 19 20 21


class Server(object):
    """
22 23
        A Server basic class
        it's a base class, does not have implementation
D
dongdaxiang 已提交
24 25 26 27 28 29 30 31 32
    """

    def __init__(self):
        pass


class Worker(object):
    """
        A Worker basic class.
33
        it's a base class, does not have implementation
D
dongdaxiang 已提交
34 35 36 37 38 39 40 41 42 43
    """

    def __init__(self):
        pass


class DownpourServer(Server):
    """
        DownpourServer class is used to generate server program_desc
        Args:
44
            server: it is pslib.ServerParameter()
D
dongdaxiang 已提交
45 46 47 48 49
        Examples:
            server = DownpourServer()
    """

    def __init__(self):
D
dongdaxiang 已提交
50 51 52 53 54 55
        self._server = pslib.ServerParameter()
        self._server.downpour_server_param.service_param.server_class = "DownpourBrpcPsServer"
        self._server.downpour_server_param.service_param.client_class = "DownpourBrpcPsClient"
        self._server.downpour_server_param.service_param.service_class = "DownpourPsService"
        self._server.downpour_server_param.service_param.start_server_port = 0
        self._server.downpour_server_param.service_param.server_thread_num = 12
D
dongdaxiang 已提交
56

57
    def add_sparse_table(self, table_id, strategy):
D
dongdaxiang 已提交
58 59 60
        """
        Args:
            table_id(int): id of sparse params table
61
            strategy(dict): the config dict.
D
dongdaxiang 已提交
62
        Returns:
63
            return None
D
dongdaxiang 已提交
64
        """
65

66 67 68 69 70 71
        for table in self._server.downpour_server_param.downpour_table_param:
            if table.table_id == table_id:
                if table.type == pslib.PS_SPARSE_TABLE:
                    return
                else:
                    raise ValueError("expect table %s type=%s, but actual type=%s" \
72
                                     %(table_id, pslib.PS_SPARSE_TABLE, table.type))
73 74
        if strategy is None:
            strategy = dict()
D
dongdaxiang 已提交
75
        table = self._server.downpour_server_param.downpour_table_param.add()
D
dongdaxiang 已提交
76 77
        table.table_id = table_id
        table.type = pslib.PS_SPARSE_TABLE
78 79

        support_sparse_key_list = ['sparse_table_class', 'sparse_compress_in_save', 'sparse_shard_num', \
80 81 82 83 84 85 86 87 88 89 90 91
                                   'sparse_accessor_class', 'sparse_learning_rate', 'sparse_initial_g2sum', 'sparse_initial_range', \
                                   'sparse_weight_bounds', 'sparse_embedx_dim', 'sparse_embedx_threshold', 'sparse_nonclk_coeff', \
                                   'sparse_click_coeff', 'sparse_base_threshold', 'sparse_delta_threshold', 'sparse_delta_keep_days', \
                                   'sparse_delete_after_unseen_days', 'sparse_show_click_decay_rate', 'sparse_delete_threshold', \
                                   'sparse_converter', 'sparse_deconverter', 'sparse_enable_cache', 'sparse_cache_rate', \
                                   'sparse_cache_file_num', 'sparse_beta1_decay_rate', 'sparse_beta2_decay_rate', \
                                   'sparse_ada_epsilon', 'sparse_optimizer', 'sparse_ssd_unseenday_threshold', \
                                   'embed_sparse_optimizer', 'embed_sparse_learning_rate', 'embed_sparse_weight_bounds', \
                                   'embed_sparse_initial_range', 'embed_sparse_initial_g2sum', 'embed_sparse_beta1_decay_rate', \
                                   'embed_sparse_beta2_decay_rate', 'embedx_sparse_optimizer', 'embedx_sparse_learning_rate', \
                                   'embedx_sparse_weight_bounds', 'embedx_sparse_initial_range', 'embedx_sparse_initial_g2sum', \
                                   'embedx_sparse_beta1_decay_rate', 'embedx_sparse_beta2_decay_rate']
92 93 94 95 96

        for key in strategy:
            if key not in support_sparse_key_list:
                raise ValueError("strategy key '%s' not support" % (key))

97
        support_table_calss = ['DownpourSparseTable', 'DownpourSparseSSDTable']
98 99 100 101
        if strategy.get('sparse_table_class') is not None:
            table_class = strategy.get('sparse_table_class')
            if table_class not in support_table_calss:
                raise ValueError(
102
                    "support sparse_table_class: [ 'DownpourSparseTable', 'DownpourSparseSSDTable'], \
103 104 105 106 107 108
                        but actual %s" % (table_class))
        else:
            table_class = 'DownpourSparseTable'

        table.table_class = table_class

109
        if table_class == 'DownpourSparseTable' or table_class == 'DownpourSparseSSDTable':
110 111
            table.enable_sparse_table_cache = strategy.get(
                'sparse_enable_cache', True)
112 113
            table.sparse_table_cache_rate = strategy.get(
                'sparse_cache_rate', 0.00055)
114 115
            table.sparse_table_cache_file_num = strategy.get(
                'sparse_cache_file_num', 16)
116 117 118
            table.compress_in_save = strategy.get('sparse_compress_in_save',
                                                  True)
            table.shard_num = strategy.get('sparse_shard_num', 1000)
119 120 121
            # DownpourFeatureValueAccessor: for ctr task, has cvm, embedding and sgd info
            # DownpourCtrAccessor         : for ctr task, has cvm, slot, embedding and sgd info
            # DownpourSparseValueAccessor : for general task, has embedding and sgd info
122
            # DownpourCtrDoubleAccessor   : for ctr task, which show clk are in double
X
xujiaqi01 已提交
123
            # DownpourUnitAccessor        : for ctr task, has cvm, slot, embedding and sgd info
124 125

            support_accessor_class = [
126
                'DownpourFeatureValueAccessor', 'DownpourCtrAccessor',
Y
yaoxuefeng 已提交
127 128 129
                'DownpourCtrDymfAccessor', 'DownpourSparseValueAccessor',
                'DownpourCtrDoubleAccessor', 'DownpourUnitAccessor',
                'DownpourDoubleUnitAccessor'
130 131 132 133 134
            ]
            if strategy.get('sparse_accessor_class') is not None:
                accessor_class = strategy.get('sparse_accessor_class')
                if accessor_class not in support_accessor_class:
                    raise ValueError(
Y
yaoxuefeng 已提交
135
                        "support sparse_accessor_class: ['DownpourFeatureValueAccessor', 'DownpourCtrAccessor', 'DownpourCtrDymfAccessor', \
136
                        'DownpourSparseValueAccessor', 'DownpourCtrDoubleAccessor'], \
137 138 139 140 141 142
                            but actual %s" % (accessor_class))
            else:
                accessor_class = 'DownpourCtrAccessor'

            table.accessor.accessor_class = accessor_class

X
xujiaqi01 已提交
143 144
            if accessor_class == 'DownpourFeatureValueAccessor' \
                    or accessor_class == 'DownpourCtrAccessor' \
Y
yaoxuefeng 已提交
145
                    or accessor_class == 'DownpourCtrDymfAccessor' \
X
xujiaqi01 已提交
146
                    or accessor_class == 'DownpourCtrDoubleAccessor':
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
                table.accessor.sparse_sgd_param.learning_rate = strategy.get(
                    'sparse_learning_rate', 0.05)
                table.accessor.sparse_sgd_param.initial_g2sum = strategy.get(
                    'sparse_initial_g2sum', 3)
                table.accessor.sparse_sgd_param.initial_range = strategy.get(
                    'sparse_initial_range', 1e-4)
                if strategy.get('sparse_weight_bounds') is None:
                    table.accessor.sparse_sgd_param.weight_bounds.extend(
                        [-10, 10])
                else:
                    table.accessor.sparse_sgd_param.weight_bounds.extend(
                        strategy.get('sparse_weight_bounds'))
                table.accessor.embedx_dim = strategy.get('sparse_embedx_dim', 8)
                table.accessor.embedx_threshold = strategy.get(
                    'sparse_embedx_threshold', 10)
                table.accessor.fea_dim = int(table.accessor.embedx_dim) + 3
                table.accessor.downpour_accessor_param.nonclk_coeff = strategy.get(
                    'sparse_nonclk_coeff', 0.1)
                table.accessor.downpour_accessor_param.click_coeff = strategy.get(
                    'sparse_click_coeff', 1)
                table.accessor.downpour_accessor_param.base_threshold = strategy.get(
                    'sparse_base_threshold', 1.5)
                table.accessor.downpour_accessor_param.delta_threshold = strategy.get(
                    'sparse_delta_threshold', 0.25)
                table.accessor.downpour_accessor_param.delta_keep_days = strategy.get(
                    'sparse_delta_keep_days', 16)
                table.accessor.downpour_accessor_param.delete_after_unseen_days = strategy.get(
                    'sparse_delete_after_unseen_days', 30)
175 176
                table.accessor.downpour_accessor_param.ssd_unseenday_threshold = strategy.get(
                    'sparse_ssd_unseenday_threshold', 1)
177 178 179 180
                table.accessor.downpour_accessor_param.show_click_decay_rate = strategy.get(
                    'sparse_show_click_decay_rate', 0.98)
                table.accessor.downpour_accessor_param.delete_threshold = strategy.get(
                    'sparse_delete_threshold', 0.8)
181 182 183 184
                converter = strategy.get(
                    'sparse_converter',
                    "(scripts/xbox_compressor_mf.py | bin/xbox_pb_converter)")
                deconverter = strategy.get(
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 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 242 243 244 245 246 247
                    'sparse_deconverter',
                    "(bin/xbox_pb_deconverter | scripts/xbox_decompressor_mf.awk)"
                )

                table1 = table.accessor.table_accessor_save_param.add()
                table1.param = 1
                table1.converter = converter
                table1.deconverter = deconverter

                table2 = table.accessor.table_accessor_save_param.add()
                table2.param = 2
                table2.converter = converter
                table2.deconverter = deconverter
            elif accessor_class == 'DownpourSparseValueAccessor':
                optimizer_name = strategy.get("sparse_optimizer", "adam")
                table.accessor.sparse_commonsgd_param.name = optimizer_name
                table.accessor.embedx_dim = strategy.get('sparse_embedx_dim', 8)
                table.accessor.fea_dim = int(table.accessor.embedx_dim)
                if optimizer_name == "naive":
                    table.accessor.sparse_commonsgd_param.naive.learning_rate = \
                        strategy.get('sparse_learning_rate', 0.05)
                    table.accessor.sparse_commonsgd_param.naive.initial_range = \
                        strategy.get('sparse_initial_range', 1e-4)
                    if strategy.get('sparse_weight_bounds') is None:
                        table.accessor.sparse_commonsgd_param.naive.weight_bounds.extend(
                            [-10, 10])
                    else:
                        table.accessor.sparse_commonsgd_param.naive.weight_bounds.extend(
                            strategy.get('sparse_weight_bounds'))
                elif optimizer_name == "adagrad":
                    table.accessor.sparse_commonsgd_param.adagrad.learning_rate = \
                        strategy.get('sparse_learning_rate', 0.05)
                    table.accessor.sparse_commonsgd_param.adagrad.initial_range = \
                        strategy.get('sparse_initial_range', 1e-4)
                    table.accessor.sparse_commonsgd_param.adagrad.initial_g2sum = strategy.get(
                        'sparse_initial_g2sum', 3)
                    if strategy.get('sparse_weight_bounds') is None:
                        table.accessor.sparse_commonsgd_param.adagrad.weight_bounds.extend(
                            [-10, 10])
                    else:
                        table.accessor.sparse_commonsgd_param.adagrad.weight_bounds.extend(
                            strategy.get('sparse_weight_bounds'))
                elif optimizer_name == "adam":
                    table.accessor.sparse_commonsgd_param.adam.learning_rate = \
                        strategy.get('sparse_learning_rate', 0.001)
                    table.accessor.sparse_commonsgd_param.adam.initial_range = \
                        strategy.get('sparse_initial_range', 1e-4)
                    table.accessor.sparse_commonsgd_param.adam.beta1_decay_rate = strategy.get(
                        'sparse_beta1_decay_rate', 0.9)
                    table.accessor.sparse_commonsgd_param.adam.beta2_decay_rate = strategy.get(
                        'sparse_beta2_decay_rate', 0.999)
                    table.accessor.sparse_commonsgd_param.adam.ada_epsilon = strategy.get(
                        'sparse_ada_epsilon', 1e-8)
                    if strategy.get('sparse_weight_bounds') is None:
                        table.accessor.sparse_commonsgd_param.adam.weight_bounds.extend(
                            [-10, 10])
                    else:
                        table.accessor.sparse_commonsgd_param.adam.weight_bounds.extend(
                            strategy.get('sparse_weight_bounds'))
                converter = strategy.get(
                    'sparse_converter',
                    "(scripts/xbox_compressor_mf.py | bin/xbox_pb_converter)")
                deconverter = strategy.get(
248 249 250 251
                    'sparse_deconverter',
                    "(bin/xbox_pb_deconverter | scripts/xbox_decompressor_mf.awk)"
                )

252 253
                table1 = table.accessor.table_accessor_save_param.add()
                table1.param = 1
254 255 256
                table1.converter = converter
                table1.deconverter = deconverter

257 258
                table2 = table.accessor.table_accessor_save_param.add()
                table2.param = 2
259 260
                table2.converter = converter
                table2.deconverter = deconverter
T
Thunderbrook 已提交
261
            elif accessor_class == 'DownpourUnitAccessor' or accessor_class == 'DownpourDoubleUnitAccessor':
X
xujiaqi01 已提交
262 263 264 265 266
                self.add_sparse_table_common_config(table, strategy)
                self.add_sparse_optimizer(table.accessor.embed_sgd_param,
                                          strategy, "embed_")
                self.add_sparse_optimizer(table.accessor.embedx_sgd_param,
                                          strategy, "embedx_")
267

268
    def add_dense_table(self, table_id, param_var, grad_var, strategy,
269
                        sparse_table_names):
D
dongdaxiang 已提交
270 271 272
        """
        Args:
            table_id(int): id of sparse params table
273 274 275 276
            param_var(list): param vars
            grad_var(list): param grad vars
            strategy(dict): the dense config dict
            sparse_table_names(list): sparse table names
D
dongdaxiang 已提交
277
        Returns:
278
            return None
D
dongdaxiang 已提交
279
        """
280
        fea_dim = 0
281 282
        dense_param_vars = []
        for p in param_var:
283
            if p.name not in sparse_table_names:
284 285 286
                dense_param_vars.append(p)

        for param in dense_param_vars:
287 288 289 290 291 292 293 294 295
            fea_dim += reduce(lambda x, y: x * y, param.shape, 1)

        for table in self._server.downpour_server_param.downpour_table_param:
            if table.table_id == table_id:
                if table.type == pslib.PS_DENSE_TABLE:
                    table.accessor.fea_dim = fea_dim
                    return
                else:
                    raise ValueError("expect table %s type=%s, but actual type=%s" \
296
                                     %(table_id, pslib.PS_DENSE_TABLE, table.type))
297 298 299

        if strategy is None:
            strategy = dict()
T
tangwei12 已提交
300
        table = self._server.downpour_server_param.downpour_table_param.add()
D
dongdaxiang 已提交
301
        table.table_id = table_id
302
        support_dense_key_list = ['dense_table_class', 'dense_compress_in_save', 'dense_accessor_class', \
303 304
                                  'dense_optimizer', 'dense_learning_rate', 'dense_avg_decay', 'dense_ada_decay', \
                                  'dense_ada_epsilon', 'dense_mom_decay', 'dense_naive_lr']
305 306 307 308 309 310 311

        for key in strategy:
            if key not in support_dense_key_list:
                raise ValueError("strategy key '%s' not support" % (key))

        table.table_class = strategy.get('dense_table_class',
                                         "DownpourDenseTable")
D
dongdaxiang 已提交
312
        table.type = pslib.PS_DENSE_TABLE
313 314 315
        table.compress_in_save = strategy.get('dense_compress_in_save', True)
        table.accessor.accessor_class = strategy.get(
            'dense_accessor_class', "DownpourDenseValueAccessor")
316 317
        table.accessor.dense_sgd_param.name = strategy.get(
            'dense_optimizer', "adam")
318 319 320 321 322 323 324 325 326 327 328 329
        table.accessor.dense_sgd_param.adam.learning_rate = strategy.get(
            'dense_learning_rate', 5e-06)
        table.accessor.dense_sgd_param.adam.avg_decay_rate = strategy.get(
            'dense_avg_decay', 0.999993)
        table.accessor.dense_sgd_param.adam.ada_decay_rate = strategy.get(
            'dense_ada_decay', 0.9999)
        table.accessor.dense_sgd_param.adam.ada_epsilon = strategy.get(
            'dense_ada_epsilon', 1e-8)
        table.accessor.dense_sgd_param.adam.mom_decay_rate = strategy.get(
            'dense_mom_decay', 0.99)
        table.accessor.dense_sgd_param.naive.learning_rate = strategy.get(
            'dense_naive_lr', 0.0002)
D
dongdaxiang 已提交
330 331
        table.accessor.fea_dim = fea_dim

332
    def add_data_norm_table(self, table_id, learning_rate, param_var, grad_var,
333
                            strategy, sparse_table_names):
D
dongdaxiang 已提交
334 335
        """
        Args:
336
            table_id(int): id of datanorm table
337 338 339 340 341
            learning_rate(float): the learning rate used to update parameters
            param_var(list): param vars
            grad_var(list): param grad vars
            strategy(dict): the datanorm config dict
            sparse_table_names(list): sparse table names
D
dongdaxiang 已提交
342
        Returns:
343
            return None
D
dongdaxiang 已提交
344
        """
345
        fea_dim = 0
346 347
        dense_param_vars = []
        for p in param_var:
348
            if p.name not in sparse_table_names:
349 350 351
                dense_param_vars.append(p)

        for param in dense_param_vars:
352 353 354 355 356 357 358 359 360
            fea_dim += reduce(lambda x, y: x * y, param.shape, 1)

        for table in self._server.downpour_server_param.downpour_table_param:
            if table.table_id == table_id:
                if table.type == pslib.PS_DENSE_TABLE:
                    table.accessor.fea_dim = fea_dim
                    return
                else:
                    raise ValueError("expect table %s type=%s, but actual type=%s" \
361
                                     %(table_id, pslib.PS_DENSE_TABLE, table.type))
362 363 364
        if strategy is None:
            strategy = dict()

365 366
        support_datanorm_key_list = ['datanorm_table_class', 'datanorm_compress_in_save', \
                                     'datanorm_accessor_class', 'datanorm_operation', 'datanorm_decay_rate']
367 368 369 370 371

        for key in strategy:
            if key not in support_datanorm_key_list:
                raise ValueError("strategy key '%s' not support" % (key))

D
dongdaxiang 已提交
372
        table = self._server.downpour_server_param.downpour_table_param.add()
D
dongdaxiang 已提交
373
        table.table_id = table_id
374
        table.table_class = strategy.get('datanorm_table_class',
375
                                         'DownpourDenseTable')
D
dongdaxiang 已提交
376
        table.type = pslib.PS_DENSE_TABLE
377 378
        table.compress_in_save = strategy.get('datanorm_compress_in_save', True)
        table.accessor.accessor_class = strategy.get(
379
            'datanorm_accessor_class', 'DownpourDenseValueAccessor')
380 381
        table.accessor.dense_sgd_param.name = strategy.get(
            'datanorm_operation', 'summary')
382 383
        table.accessor.dense_sgd_param.summary.summary_decay_rate = strategy.get(
            'datanorm_decay_rate', 0.999999)
D
dongdaxiang 已提交
384 385
        table.accessor.fea_dim = fea_dim

X
xujiaqi01 已提交
386
    def add_sparse_optimizer(self, sgd, strategy, prefix):
T
Thunderbrook 已提交
387
        optimizer_name = strategy.get(prefix + "sparse_optimizer", "adagrad")
X
xujiaqi01 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400
        sgd.name = optimizer_name
        if optimizer_name == "naive":
            sgd.naive.learning_rate = \
                strategy.get(prefix + 'sparse_learning_rate', 0.05)
            sgd.naive.initial_range = \
                strategy.get(prefix + 'sparse_initial_range', 1e-4)
            bounds = strategy.get(prefix + 'sparse_weight_bounds', [-10, 10])
            sgd.naive.weight_bounds.extend(bounds)
        elif optimizer_name == "adagrad":
            sgd.adagrad.learning_rate = \
                strategy.get(prefix + 'sparse_learning_rate', 0.05)
            sgd.adagrad.initial_range = \
                strategy.get(prefix + 'sparse_initial_range', 1e-4)
T
Thunderbrook 已提交
401 402 403 404 405 406 407 408 409 410 411 412 413
            if prefix == "embed_":
                sgd.adagrad.initial_range = 0
            sgd.adagrad.initial_g2sum = strategy.get(
                prefix + 'sparse_initial_g2sum', 3)
            bounds = strategy.get(prefix + 'sparse_weight_bounds', [-10, 10])
            sgd.adagrad.weight_bounds.extend(bounds)
        elif optimizer_name == "std_adagrad":
            sgd.adagrad.learning_rate = \
                strategy.get(prefix + 'sparse_learning_rate', 0.05)
            sgd.adagrad.initial_range = \
                strategy.get(prefix + 'sparse_initial_range', 1e-4)
            if prefix == "embed_":
                sgd.adagrad.initial_range = 0
X
xujiaqi01 已提交
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
            sgd.adagrad.initial_g2sum = strategy.get(
                prefix + 'sparse_initial_g2sum', 3)
            bounds = strategy.get(prefix + 'sparse_weight_bounds', [-10, 10])
            sgd.adagrad.weight_bounds.extend(bounds)
        elif optimizer_name == "adam":
            sgd.adam.learning_rate = \
                strategy.get(prefix + 'sparse_learning_rate', 0.001)
            sgd.adam.initial_range = \
                strategy.get(prefix + 'sparse_initial_range', 1e-4)
            sgd.adam.beta1_decay_rate = strategy.get(
                prefix + 'sparse_beta1_decay_rate', 0.9)
            sgd.adam.beta2_decay_rate = strategy.get(
                prefix + 'sparse_beta2_decay_rate', 0.999)
            sgd.adam.ada_epsilon = strategy.get(prefix + 'sparse_ada_epsilon',
                                                1e-8)
            bounds = strategy.get(prefix + 'sparse_weight_bounds', [-10, 10])
            sgd.adam.weight_bounds.extend(bounds)

    def add_sparse_table_common_config(self, table, strategy):
        table.accessor.embedx_dim = strategy.get('sparse_embedx_dim', 8)
        table.accessor.embedx_threshold = strategy.get(
            'sparse_embedx_threshold', 10)
        table.accessor.fea_dim = int(table.accessor.embedx_dim) + 3
        table.accessor.downpour_accessor_param.nonclk_coeff = strategy.get(
            'sparse_nonclk_coeff', 0.1)
        table.accessor.downpour_accessor_param.click_coeff = strategy.get(
            'sparse_click_coeff', 1)
        table.accessor.downpour_accessor_param.base_threshold = strategy.get(
            'sparse_base_threshold', 1.5)
        table.accessor.downpour_accessor_param.delta_threshold = strategy.get(
            'sparse_delta_threshold', 0.25)
        table.accessor.downpour_accessor_param.delta_keep_days = strategy.get(
            'sparse_delta_keep_days', 16)
        table.accessor.downpour_accessor_param.delete_after_unseen_days = strategy.get(
            'sparse_delete_after_unseen_days', 30)
        table.accessor.downpour_accessor_param.show_click_decay_rate = strategy.get(
            'sparse_show_click_decay_rate', 0.98)
        table.accessor.downpour_accessor_param.delete_threshold = strategy.get(
            'sparse_delete_threshold', 0.8)
        converter = strategy.get(
            'sparse_converter',
            "(scripts/xbox_compressor_mf.py | bin/xbox_pb_converter)")
        deconverter = strategy.get(
            'sparse_deconverter',
            "(bin/xbox_pb_deconverter | scripts/xbox_decompressor_mf.awk)")

        table1 = table.accessor.table_accessor_save_param.add()
        table1.param = 1
        table1.converter = converter
        table1.deconverter = deconverter

        table2 = table.accessor.table_accessor_save_param.add()
        table2.param = 2
        table2.converter = converter
        table2.deconverter = deconverter

D
dongdaxiang 已提交
470 471 472 473
    def get_desc(self):
        """
        Return downpour server program_desc
        """
D
dongdaxiang 已提交
474
        return self._server
D
dongdaxiang 已提交
475 476 477 478 479 480 481


class DownpourWorker(Worker):
    """
        DownpourWorker class is used to generate worker program_desc
        Args:
            window (int): push params frequency
482
            worker: it is pslib.DownpourTrainerParameter
D
dongdaxiang 已提交
483 484 485 486 487 488
        Examples:
            worker = DownpourWorker(1)
    """

    def __init__(self, window):
        self.window = window
D
dongdaxiang 已提交
489
        self._worker = pslib.DownpourTrainerParameter()
D
dongdaxiang 已提交
490

491 492 493 494 495
    def add_sparse_table(self,
                         table_id,
                         slot_key_vars,
                         slot_value_vars,
                         slot_value_grads=None):
D
dongdaxiang 已提交
496 497 498
        """
        Args:
            table_id(int): id of sparse params table
499 500 501
            slot_key_vars(list): slot key id
            slot_value_vars(list): slot key value after embedding
            slot_value_grads(list): grad of all params, default is None
D
dongdaxiang 已提交
502
        Returns:
503
            return None
D
dongdaxiang 已提交
504
        """
505 506 507 508 509 510 511 512 513 514 515 516 517
        if slot_value_grads is None:
            slot_value_grad_names = \
                [var.name + "@GRAD" for var in slot_value_vars]
        else:
            value_to_key = {}
            for i in range(len(slot_key_vars)):
                value_to_key[slot_value_vars[i].name] = slot_key_vars[i]
            slot_value_grad_names = []
            all_grad_names = [var.name for var in slot_value_grads]
            for var in slot_value_vars:
                if var.name + "@GRAD" in all_grad_names:
                    slot_value_grad_names.append(var.name + "@GRAD")
            sorted_slot_value_vars = [i for i in slot_value_vars if \
518
                                      i.name + "@GRAD" in slot_value_grad_names]
519
            sorted_slot_value_vars += [i for i in slot_value_vars if \
520
                                       i.name + "@GRAD" not in slot_value_grad_names]
521 522 523 524
            sorted_slot_key_vars = \
                [value_to_key[v.name] for v in sorted_slot_value_vars]

        target_table = None
525 526
        for table in self._worker.sparse_table:
            if table.table_id == table_id:
X
xujiaqi01 已提交
527
                keys = table.slot_key
528 529 530 531
                key_names = [var.name for var in sorted_slot_key_vars]
                for key_name in key_names:
                    if key_name not in keys:
                        raise ValueError("sparse table %s slot_key error" %
532
                                         table_id)
533 534
                target_table = table
                break
535

536 537 538
        table = target_table
        if table is not None:
            self._worker.sparse_table.remove(table)
T
tangwei12 已提交
539
        table = self._worker.sparse_table.add()
D
dongdaxiang 已提交
540
        table.table_id = table_id
541 542 543
        table.slot_key.extend([var.name for var in sorted_slot_key_vars])
        table.slot_value.extend([var.name for var in sorted_slot_value_vars])
        table.slot_gradient.extend(slot_value_grad_names)
D
dongdaxiang 已提交
544

545
    def add_dense_table(self, table_id, learning_rate, param_vars, grad_vars,
546
                        dense_start_table_id, sparse_table_names):
547
        r"""
D
dongdaxiang 已提交
548 549 550 551
        Args:
            table_id(int): id of sparse params table
            learning_rate(float): the learning rate used to update parameters. \
                Can be a float value
552 553 554 555
            param_vars(list): all dense param. it is a list.
            grad_vars(list): all dense grad parm it is a list.
            dense_start_table_id(int): dense table start index
            sparse_table_names(list): sparse table names
D
dongdaxiang 已提交
556
        Returns:
557
            return None
D
dongdaxiang 已提交
558
        """
559
        sparse_table_name_grad = []
560
        for name in sparse_table_names:
561 562 563 564
            sparse_table_name_grad.append(name + "@GRAD")

        dense_param_name = []
        for p in param_vars:
565
            if p.name not in sparse_table_names:
566 567 568 569 570 571 572 573 574
                dense_param_name.append(p.name)

        dense_grad_name = []
        for g in grad_vars:
            if g.name not in sparse_table_name_grad:
                dense_grad_name.append(g.name)

        dense_param_name.sort()
        dense_grad_name.sort()
575

576 577
        for table in self._worker.dense_table:
            if table.table_id == table_id:
578
                desc_dense_param_name = list(table.dense_variable_name)
579 580 581
                desc_dense_param_name.sort()

                if dense_param_name == desc_dense_param_name:
582 583
                    desc_dense_grad_name = list(
                        table.dense_gradient_variable_name)
584 585
                    desc_dense_grad_name.sort()
                    if dense_grad_name == desc_dense_grad_name:
586 587 588
                        return
                    else:
                        raise ValueError(
589 590
                            "dense table %s dense_gradient_variable_name "
                            "error" % table_id)
591 592 593 594
                else:
                    raise ValueError(
                        "dense table %s dense_variable_name error" % table_id)

D
dongdaxiang 已提交
595
        table = self._worker.dense_table.add()
D
dongdaxiang 已提交
596
        table.table_id = table_id
597

598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
        #def cmp_fc(x, y):
        #    if x.startswith("fc_") and y.startswith("fc_"):
        #        index_x = x.find('.')
        #        index_y = y.find('.')
        #        if index_x > 0 and index_y > 0:
        #            num_x = x[3:index_x]
        #            num_y = y[3:index_y]
        #            if num_x.isdigit() and num_y.isdigit():
        #                if int(num_x) < int(num_y):
        #                    return -1
        #                if int(num_x) > int(num_y):
        #                    return 1
        #                if x[index_x + 1] == 'w' and y[index_y + 1] == 'b':
        #                    return -1
        #                if x[index_x + 1] == 'b' and y[index_y + 1] == 'w':
        #                    return 1
        #    if x < y:
        #        return -1
        #    else:
        #        return 1

        #table.dense_variable_name.extend(sorted(dense_param_name, cmp_fc))
        #table.dense_gradient_variable_name.extend(
        #    sorted(dense_grad_name, cmp_fc))
        table.dense_variable_name.extend(dense_param_name)
        table.dense_gradient_variable_name.extend(dense_grad_name)
D
dongdaxiang 已提交
624 625 626 627 628

    def get_desc(self):
        """
        Return downpour worker program_desc
        """
D
dongdaxiang 已提交
629
        return self._worker