node.py 15.9 KB
Newer Older
D
dongdaxiang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#   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

14
from . import ps_pb2 as pslib
D
dongdaxiang 已提交
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44


class Server(object):
    """
        A Server basic class.
    """

    def __init__(self):
        pass


class Worker(object):
    """
        A Worker basic class.
    """

    def __init__(self):
        pass


class DownpourServer(Server):
    """
        DownpourServer class is used to generate server program_desc
        Args:
            server: it is pslib.ServerParameter() 
        Examples:
            server = DownpourServer()
    """

    def __init__(self):
D
dongdaxiang 已提交
45 46 47 48 49 50
        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 已提交
51

52
    def add_sparse_table(self, table_id, strategy):
D
dongdaxiang 已提交
53 54 55
        """
        Args:
            table_id(int): id of sparse params table
56
            strategy(dict): the config dict.
D
dongdaxiang 已提交
57 58 59
        Returns:
            return None 
        """
60

61 62 63 64 65 66 67
        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" \
                        %(table_id, pslib.PS_SPARSE_TABLE, table.type))
68 69
        if strategy is None:
            strategy = dict()
D
dongdaxiang 已提交
70
        table = self._server.downpour_server_param.downpour_table_param.add()
D
dongdaxiang 已提交
71 72
        table.table_id = table_id
        table.type = pslib.PS_SPARSE_TABLE
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157

        support_sparse_key_list = ['sparse_table_class', 'sparse_compress_in_save', 'sparse_shard_num', \
                    '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_show_click_decay_rate', 'sparse_delete_threshold']

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

        support_table_calss = ['DownpourSparseTable']
        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(
                    "support sparse_table_class: [ 'DownpourSparseTable' ], \
                        but actual %s" % (table_class))
        else:
            table_class = 'DownpourSparseTable'

        table.table_class = table_class

        if table_class == 'DownpourSparseTable':
            table.compress_in_save = strategy.get('sparse_compress_in_save',
                                                  True)
            table.shard_num = strategy.get('sparse_shard_num', 1000)

            support_accessor_class = [
                'DownpourFeatureValueAccessor', 'DownpourCtrAccessor'
            ]
            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(
                        "support sparse_accessor_class: ['DownpourFeatureValueAccessor', 'DownpourCtrAccessor'], \
                            but actual %s" % (accessor_class))
            else:
                accessor_class = 'DownpourCtrAccessor'

            table.accessor.accessor_class = accessor_class

            if accessor_class == 'DownpourFeatureValueAccessor' or accessor_class == 'DownpourCtrAccessor':
                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)
                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)
                table1 = table.accessor.table_accessor_save_param.add()
                table1.param = 1
                table1.converter = "(scripts/xbox_compressor_mf.py | bin/xbox_pb_converter)"
                table1.deconverter = "(bin/xbox_pb_deconverter | scripts/xbox_decompressor_mf.awk)"
                table2 = table.accessor.table_accessor_save_param.add()
                table2.param = 2
                table2.converter = "(scripts/xbox_compressor_mf.py | bin/xbox_pb_converter)"
                table2.deconverter = "(bin/xbox_pb_deconverter | scripts/xbox_decompressor_mf.awk)"

    def add_dense_table(self, table_id, param_var, grad_var, strategy):
D
dongdaxiang 已提交
158 159 160
        """
        Args:
            table_id(int): id of sparse params table
161
            strategy(dict): the dense config dict.
D
dongdaxiang 已提交
162 163 164
        Returns:
            return None 
        """
165 166 167 168 169 170 171 172 173 174 175 176 177
        fea_dim = 0
        for param in filter(lambda x: x.name.find("embedding") == -1,
                            param_var):
            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" \
                        %(table_id, pslib.PS_DENSE_TABLE, table.type))
178 179 180

        if strategy is None:
            strategy = dict()
T
tangwei12 已提交
181
        table = self._server.downpour_server_param.downpour_table_param.add()
D
dongdaxiang 已提交
182
        table.table_id = table_id
183 184 185 186 187 188 189 190 191 192
        support_dense_key_list = ['dense_table_class', 'dense_compress_in_save', 'dense_accessor_class', \
                'dense_optimizer', 'dense_learning_rate', 'dense_avg_decay', 'dense_ada_decay', \
                'dense_ada_epsilon', 'dense_mom_decay', 'dense_naive_lr']

        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 已提交
193
        table.type = pslib.PS_DENSE_TABLE
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
        table.compress_in_save = strategy.get('dense_compress_in_save', True)
        table.accessor.accessor_class = strategy.get(
            'dense_accessor_class', "DownpourDenseValueAccessor")
        table.accessor.dense_sgd_param.name = strategy.get('dense_optimizer',
                                                           "adam")
        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 已提交
211 212
        table.accessor.fea_dim = fea_dim

213 214
    def add_data_norm_table(self, table_id, learning_rate, param_var, grad_var,
                            strategy):
D
dongdaxiang 已提交
215 216
        """
        Args:
217 218
            table_id(int): id of datanorm table
            strategy(dict): the datanorm config dict.
D
dongdaxiang 已提交
219 220 221
        Returns:
            return None 
        """
222 223 224 225 226 227 228 229 230 231 232 233 234
        fea_dim = 0
        for param in filter(lambda x: x.name.find("embedding") == -1,
                            param_var):
            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" \
                        %(table_id, pslib.PS_DENSE_TABLE, table.type))
235 236 237 238 239 240 241 242 243 244
        if strategy is None:
            strategy = dict()

        support_datanorm_key_list = ['datanorm_table_class', 'datanorm_compress_in_save',\
                'datanorm_accessor_class', 'datanorm_operation', 'datanorm_decay_rate']

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

D
dongdaxiang 已提交
245
        table = self._server.downpour_server_param.downpour_table_param.add()
D
dongdaxiang 已提交
246
        table.table_id = table_id
247 248
        table.table_class = strategy.get('datanorm_table_class',
                                         "DownpourDenseDoubleTable")
D
dongdaxiang 已提交
249
        table.type = pslib.PS_DENSE_TABLE
250 251 252 253 254 255 256
        table.compress_in_save = strategy.get('datanorm_compress_in_save', True)
        table.accessor.accessor_class = strategy.get(
            'datanorm_accessor_class', "DownpourDenseValueDoubleAccessor")
        table.accessor.dense_sgd_param.name = strategy.get('datanorm_operation',
                                                           "summarydouble")
        table.accessor.dense_sgd_param.summary.summary_decay_rate = strategy.get(
            'datanorm_decay_rate', 0.999999)
D
dongdaxiang 已提交
257 258 259 260 261 262
        table.accessor.fea_dim = fea_dim

    def get_desc(self):
        """
        Return downpour server program_desc
        """
D
dongdaxiang 已提交
263
        return self._server
D
dongdaxiang 已提交
264 265 266 267 268 269 270 271 272 273 274 275 276 277


class DownpourWorker(Worker):
    """
        DownpourWorker class is used to generate worker program_desc
        Args:
            window (int): push params frequency
            worker: it is pslib.DownpourTrainerParameter 
        Examples:
            worker = DownpourWorker(1)
    """

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

280
    def add_sparse_table(self, table_id, slot_key_vars, slot_value_vars):
D
dongdaxiang 已提交
281 282 283 284 285 286 287 288
        """
        Args:
            table_id(int): id of sparse params table
            slot_key_vars(string): slot key id 
            slot_value_var(string): slot key value after embedding
        Returns:
            return None 
        """
289 290
        for table in self._worker.sparse_table:
            if table.table_id == table_id:
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
                if [var.name for var in slot_key_vars
                    ] == self._worker.sparse_table[table_id].slot_key:
                    if [var.name for var in slot_value_vars
                        ] == self._worker.sparse_table[table_id].slot_value:
                        if [
                                var.name + "@GRAD" for var in slot_value_vars
                        ] == self._worker.sparse_table[table_id].slot_gradient:
                            return
                        else:
                            raise ValueError(
                                "sparse table %s slot_gradient error" %
                                table_id)

                    else:
                        raise ValueError("sparse table %s slot_value error" %
                                         table_id)
                else:
                    raise ValueError("sparse table %s slot_key error" %
                                     table_id)

T
tangwei12 已提交
311
        table = self._worker.sparse_table.add()
D
dongdaxiang 已提交
312 313 314 315 316 317
        table.table_id = table_id
        table.slot_key.extend([var.name for var in slot_key_vars])
        table.slot_value.extend([var.name for var in slot_value_vars])
        table.slot_gradient.extend(
            [var.name + "@GRAD" for var in slot_value_vars])

318 319
    def add_dense_table(self, table_id, learning_rate, param_vars, grad_vars,
                        dense_start_table_id):
D
dongdaxiang 已提交
320 321 322 323 324 325 326 327 328 329
        """
        Args:
            table_id(int): id of sparse params table
            learning_rate(float): the learning rate used to update parameters. \
                Can be a float value
            param_var(list): all dense param. it is a list.
            grad_var(list): all dense grad parm it is a list.
        Returns:
            return None 
        """
330 331
        for table in self._worker.dense_table:
            if table.table_id == table_id:
332 333 334 335 336 337 338 339 340 341 342 343 344
                if filter(lambda x: x.find("embedding") == -1, [p.name for p in param_vars]) ==\
                        self._worker.dense_table[table_id - dense_start_table_id].dense_variable_name:
                    if filter(lambda x: x.find("embedding") == -1, [g.name for g in grad_vars]) ==\
                        self._worker.dense_table[table_id - dense_start_table_id].dense_gradient_variable_name:
                        return
                    else:
                        raise ValueError(
                            "dense table %s dense_gradient_variable_name error"
                            % table_id)
                else:
                    raise ValueError(
                        "dense table %s dense_variable_name error" % table_id)

D
dongdaxiang 已提交
345
        table = self._worker.dense_table.add()
D
dongdaxiang 已提交
346 347 348 349 350 351 352 353 354 355 356 357
        table.table_id = table_id
        table.dense_variable_name.extend(
            filter(lambda x: x.find("embedding") == -1,
                   [p.name for p in param_vars]))
        table.dense_gradient_variable_name.extend(
            filter(lambda x: x.find("embedding") == -1,
                   [g.name for g in grad_vars]))

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