test_dist_transpiler.py 28.2 KB
Newer Older
Y
Yancey 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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
# limitations under the License.

15 16
from __future__ import print_function

T
tangwei12 已提交
17 18
import math

19
import unittest
20
import paddle.fluid as fluid
Y
Yancey 已提交
21
from paddle.fluid.transpiler.distribute_transpiler import delete_ops
W
Wu Yi 已提交
22
import traceback
G
gongweibao 已提交
23
import collections
M
minqiyang 已提交
24
import six
25

Y
Yancey 已提交
26

W
Wu Yi 已提交
27
class TranspilerTest(unittest.TestCase):
Y
Yancey 已提交
28
    def setUp(self):
W
Wu Yi 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
        self.trainer_id = 0
        self.trainers = 2
        self.pservers = 2
        # NOTE: we do not actually bind this port
        self.pserver_eps = "127.0.0.1:6174,127.0.0.1:6175"
        self.pserver1_ep = "127.0.0.1:6174"
        self.pserver2_ep = "127.0.0.1:6175"
        self.sync_mode = True
        self.transpiler = None

    def net_conf(self):
        x = fluid.layers.data(name='x', shape=[1000], dtype='float32')
        y_predict = fluid.layers.fc(input=x,
                                    size=1000,
                                    act=None,
                                    param_attr=fluid.ParamAttr(name='fc_w'),
                                    bias_attr=fluid.ParamAttr(name='fc_b'))
        y = fluid.layers.data(name='y', shape=[1], dtype='float32')
        cost = fluid.layers.square_error_cost(input=y_predict, label=y)
        avg_cost = fluid.layers.mean(cost)
        sgd_optimizer = fluid.optimizer.SGD(learning_rate=0.1)
        sgd_optimizer.minimize(avg_cost)

    def get_main_program(self):
        main = fluid.Program()
54
        main.random_seed = 1
W
Wu Yi 已提交
55 56 57 58 59
        with fluid.program_guard(main):
            self.net_conf()
        self.origin_prog = main.clone()
        return main

G
gongweibao 已提交
60 61 62 63 64
    def get_trainer(self, config=None):
        src = fluid.default_startup_program().clone()

        t = self._transpiler_instance(config)

W
Wu Yi 已提交
65
        trainer_main = t.get_trainer_program(wait_port=False)
G
gongweibao 已提交
66 67 68 69 70 71
        trainer_startup = fluid.default_startup_program()

        assert (src.num_blocks == 1)
        assert (trainer_startup.num_blocks == src.num_blocks)

        return trainer_main, trainer_startup
W
Wu Yi 已提交
72

Q
qiaolongfei 已提交
73 74
    def get_pserver(self, ep, config=None, sync_mode=True):
        t = self._transpiler_instance(config, sync_mode)
W
Wu Yi 已提交
75 76 77 78
        pserver = t.get_pserver_program(ep)
        startup = t.get_startup_program(ep, pserver)
        return pserver, startup

Q
qiaolongfei 已提交
79
    def _transpiler_instance(self, config=None, sync_mode=True):
W
Wu Yi 已提交
80 81
        if not self.transpiler:
            main = self.get_main_program()
G
gongweibao 已提交
82
            self.transpiler = fluid.DistributeTranspiler(config=config)
W
Wu Yi 已提交
83 84 85 86
            self.transpiler.transpile(
                self.trainer_id,
                program=main,
                pservers=self.pserver_eps,
Q
qiaolongfei 已提交
87 88
                trainers=self.trainers,
                sync_mode=sync_mode)
G
gongweibao 已提交
89

W
Wu Yi 已提交
90
        return self.transpiler
Y
Yancey 已提交
91

Q
qiaolongfei 已提交
92 93
    def transpiler_test_impl(self):
        pass
W
Wu Yi 已提交
94

Y
Yancey 已提交
95
    def test_transpiler(self):
Q
qiaolongfei 已提交
96 97
        main = fluid.Program()
        startup = fluid.Program()
T
tangwei12 已提交
98 99 100
        with fluid.unique_name.guard():
            with fluid.program_guard(main, startup):
                self.transpiler_test_impl()
Q
qiaolongfei 已提交
101 102 103 104


class TestBasicModel(TranspilerTest):
    def transpiler_test_impl(self):
W
Wu Yi 已提交
105 106 107
        pserver, startup = self.get_pserver(self.pserver1_ep)
        pserver2, startup2 = self.get_pserver(self.pserver2_ep)

G
gongweibao 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
        trainer, trainer_startup = self.get_trainer()

        # splited var blocks should be in startup program
        self.assertTrue("fc_w.block0" in trainer_startup.global_block().vars)
        self.assertTrue("fc_w.block1" in trainer_startup.global_block().vars)
        self.assertTrue("fc_w" in trainer_startup.global_block().vars)
        self.assertTrue("fc_b" in trainer_startup.global_block().vars)
        self.assertTrue("fc_w@GRAD" not in trainer_startup.global_block().vars)
        self.assertTrue("fc_b@GRAD" not in trainer_startup.global_block().vars)

        src = [op.type for op in trainer_startup.global_block().ops]
        dst = ['fill_constant', 'fill_constant', 'uniform_random', 'recv', 'recv', \
               'fetch_barrier', 'concat']

        self.assertEqual(src, dst)
W
Wu Yi 已提交
123 124 125 126 127 128 129

        self.assertEqual([op.type for op in trainer.global_block().ops], [
            'mul', 'elementwise_add', 'elementwise_sub', 'square', 'mean',
            'fill_constant', 'mean_grad', 'square_grad', 'elementwise_sub_grad',
            'elementwise_add_grad', 'send', 'mul_grad', 'split_byref', 'send',
            'send_barrier', 'recv', 'recv', 'fetch_barrier', 'concat'
        ])
Y
Yancey 已提交
130 131 132 133 134

        self.assertEqual(len(pserver.blocks), 3)
        # block0: listen_and_serv
        self.assertEqual([op.type for op in pserver.blocks[0].ops],
                         ["listen_and_serv"])
W
Wu Yi 已提交
135
        # block1~2: optimize pass
Y
Yancey 已提交
136 137 138
        self.assertEqual([op.type for op in pserver.blocks[1].ops],
                         ["sum", "scale", "sgd"])
        # confirm startup program
W
Wu Yi 已提交
139 140
        self.assertEqual([op.type for op in startup.global_block().ops],
                         ["fill_constant", "fill_constant", "uniform_random"])
Y
Yancey1989 已提交
141
        # the variable #fc_w will be split into two blocks
Y
Yancey 已提交
142 143
        fc_w_var = startup.global_block().var("fc_w.block1")
        self.assertEqual(fc_w_var.shape, (500, 1000))
W
Wu Yi 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
        # all parameters should be optimized on pserver

        pserver_params = []
        for prog in [pserver, pserver2]:
            for blk in prog.blocks:
                for op in blk.ops:
                    if "Param" in op.input_names:
                        param_name = op.input("Param")[0]
                        is_block_idx = param_name.find(".block")
                        if is_block_idx != -1:
                            origin_param_name = param_name[:is_block_idx]
                        else:
                            origin_param_name = param_name
                        pserver_params.append(origin_param_name)
        trainer_params = []
        for op in self.origin_prog.global_block().ops:
            if "Param" in op.input_names:
                trainer_params.append(op.input("Param")[0])
        self.assertEqual(set(pserver_params), set(trainer_params))


G
gongweibao 已提交
165
class TestBasicModelWithLargeBlockSize(TranspilerTest):
Q
qiaolongfei 已提交
166
    def transpiler_test_impl(self):
G
gongweibao 已提交
167 168 169 170 171 172
        config = fluid.DistributeTranspilerConfig()
        config.min_block_size = 1048576

        pserver, startup = self.get_pserver(self.pserver1_ep, config)
        pserver2, startup2 = self.get_pserver(self.pserver2_ep, config)

G
gongweibao 已提交
173
        trainer, _ = self.get_trainer(config)
G
gongweibao 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190

        self.assertEqual([op.type for op in trainer.global_block().ops], [
            'mul', 'elementwise_add', 'elementwise_sub', 'square', 'mean',
            'fill_constant', 'mean_grad', 'square_grad', 'elementwise_sub_grad',
            'elementwise_add_grad', 'send', 'mul_grad', 'send', 'send_barrier',
            'recv', 'recv', 'fetch_barrier'
        ])

        self.assertEqual(len(pserver.blocks), 2)
        # block0: listen_and_serv
        self.assertEqual([op.type for op in pserver.blocks[0].ops],
                         ["listen_and_serv"])
        # block1~2: optimize pass
        self.assertEqual([op.type for op in pserver.blocks[1].ops],
                         ["sum", "scale", "sgd"])
        # confirm startup program
        self.assertEqual([op.type for op in startup.global_block().ops],
Q
qiaolongfei 已提交
191
                         ["fill_constant", "fill_constant"])
G
gongweibao 已提交
192 193
        # the variable #fc_w will be split into two blocks
        fc_w_var = startup2.global_block().var("fc_w")
194
        self.assertEqual(fc_w_var.shape, (1000, 1000))
G
gongweibao 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
        # all parameters should be optimized on pserver

        pserver_params = []
        for prog in [pserver, pserver2]:
            for blk in prog.blocks:
                for op in blk.ops:
                    if "Param" in op.input_names:
                        param_name = op.input("Param")[0]
                        is_block_idx = param_name.find(".block")
                        if is_block_idx != -1:
                            origin_param_name = param_name[:is_block_idx]
                        else:
                            origin_param_name = param_name
                        pserver_params.append(origin_param_name)
        trainer_params = []
        for op in self.origin_prog.global_block().ops:
            if "Param" in op.input_names:
                trainer_params.append(op.input("Param")[0])
        self.assertEqual(set(pserver_params), set(trainer_params))


W
Wu Yi 已提交
216 217 218 219
class TestNoSliceVar(TranspilerTest):
    def setUp(self):
        super(TestNoSliceVar, self).setUp()

Q
qiaolongfei 已提交
220
    def transpiler_test_impl(self):
G
gongweibao 已提交
221 222 223 224 225
        config = fluid.DistributeTranspilerConfig()
        config.slice_var_up = False

        _, startup = self.get_pserver(self.pserver1_ep, config)
        _, startup2 = self.get_pserver(self.pserver2_ep, config)
W
Wu Yi 已提交
226

227
        if "fc_w" in startup.global_block().vars:
W
Wu Yi 已提交
228
            fc_w_var = startup.global_block().vars["fc_w"]
229
        elif "fc_w" in startup2.global_block().vars:
W
Wu Yi 已提交
230 231 232
            fc_w_var = startup2.global_block().vars["fc_w"]

        self.assertEqual(fc_w_var.shape, (1000, 1000))
Y
Yancey 已提交
233 234


W
Wu Yi 已提交
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
class TestLRDecay(TranspilerTest):
    def net_conf(self):
        x = fluid.layers.data(name='x', shape=[1000], dtype='float32')
        y_predict = fluid.layers.fc(input=x,
                                    size=1000,
                                    act=None,
                                    param_attr=fluid.ParamAttr(name='fc_w'),
                                    bias_attr=fluid.ParamAttr(name='fc_b'))
        y = fluid.layers.data(name='y', shape=[1], dtype='float32')
        cost = fluid.layers.square_error_cost(input=y_predict, label=y)
        avg_cost = fluid.layers.mean(cost)
        sgd_optimizer = fluid.optimizer.SGD(
            learning_rate=fluid.layers.exponential_decay(
                learning_rate=1.0,
                decay_steps=2100,
                decay_rate=0.1,
                staircase=True))
        sgd_optimizer.minimize(avg_cost)

Q
qiaolongfei 已提交
254
    def transpiler_test_impl(self):
W
Wu Yi 已提交
255
        pserver, startup = self.get_pserver(self.pserver1_ep)
G
gongweibao 已提交
256
        trainer, _ = self.get_trainer()
W
Wu Yi 已提交
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282

        self.assertEqual(len(pserver.blocks), 4)
        lr_decay_ops = [op.type for op in pserver.blocks[1].ops]
        self.assertEqual(lr_decay_ops, [
            "increment", "cast", "fill_constant", "elementwise_div", "floor",
            "fill_constant", "elementwise_pow", "fill_constant",
            "elementwise_mul"
        ])


class TestLRDecayConditional(TranspilerTest):
    def net_conf(self):
        x = fluid.layers.data(name='x', shape=[1000], dtype='float32')
        y_predict = fluid.layers.fc(input=x,
                                    size=1000,
                                    act=None,
                                    param_attr=fluid.ParamAttr(name='fc_w'),
                                    bias_attr=fluid.ParamAttr(name='fc_b'))
        y = fluid.layers.data(name='y', shape=[1], dtype='float32')
        cost = fluid.layers.square_error_cost(input=y_predict, label=y)
        avg_cost = fluid.layers.mean(cost)
        sgd_optimizer = fluid.optimizer.SGD(
            learning_rate=fluid.layers.piecewise_decay([10000, 20000],
                                                       [1.0, 0.5, 1.0]))
        sgd_optimizer.minimize(avg_cost)

Q
qiaolongfei 已提交
283
    def transpiler_test_impl(self):
W
Wu Yi 已提交
284
        pserver, startup = self.get_pserver(self.pserver1_ep)
G
gongweibao 已提交
285
        trainer, _ = self.get_trainer()
W
Wu Yi 已提交
286 287 288 289

        serv_op = pserver.blocks[0].ops[0]
        sub_blocks = []
        optimize_blocks = []
G
gongweibao 已提交
290
        for b in serv_op.all_attrs()["optimize_blocks"]:
W
Wu Yi 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
            optimize_blocks.append(b.idx)
        for b in pserver.blocks:
            if b.idx not in optimize_blocks:
                sub_blocks.append(b.idx)

        self.assertEqual(len(pserver.blocks), 7)
        lr_decay_ops = [op.type for op in pserver.blocks[1].ops]
        self.assertEqual(lr_decay_ops, [
            "increment", "cast", "fill_constant", "fill_constant", "less_than",
            "logical_not", "conditional_block", "fill_constant",
            "fill_constant", "less_than", "logical_not", "logical_and",
            "logical_and", "conditional_block", "fill_constant",
            "conditional_block"
        ])
        # test the condition blocks
        for b in sub_blocks:
            if b == 0:
                continue
            block = pserver.blocks[b]
            self.assertEqual([op.type for op in block.ops], ["assign"])


class TestL2Decay(TranspilerTest):
    def net_conf(self):
        x = fluid.layers.data(name='x', shape=[1000], dtype='float32')
        y_predict = fluid.layers.fc(
            input=x,
            size=1000,
            act=None,
            param_attr=fluid.ParamAttr(
                name='fc_w',
                regularizer=fluid.regularizer.L2Decay(),
                gradient_clip=fluid.clip.GradientClipByValue(0.1)),
            bias_attr=fluid.ParamAttr(name='fc_b'))
        y = fluid.layers.data(name='y', shape=[1], dtype='float32')
        cost = fluid.layers.square_error_cost(input=y_predict, label=y)
        avg_cost = fluid.layers.mean(cost)
        sgd_optimizer = fluid.optimizer.SGD(learning_rate=0.1)
        sgd_optimizer.minimize(avg_cost)

Q
qiaolongfei 已提交
331
    def transpiler_test_impl(self):
W
Wu Yi 已提交
332
        pserver, startup = self.get_pserver(self.pserver1_ep)
G
gongweibao 已提交
333
        trainer, _ = self.get_trainer()
W
Wu Yi 已提交
334 335 336 337 338 339 340 341 342

        self.assertEqual(len(pserver.blocks), 3)
        self.assertEqual([op.type for op in pserver.blocks[1].ops],
                         ["sum", "scale", "clip", "sgd"])
        self.assertEqual(
            [op.type for op in pserver.blocks[2].ops],
            ["sum", "scale", "clip", "scale", "elementwise_add", "sgd"])
        # TODO(typhoonzero): test clipping and L2Decay ops are removed from trainer

Y
Yancey 已提交
343

T
typhoonzero 已提交
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
class TestL2DecayWithPiecewise(TranspilerTest):
    def net_conf(self):
        x = fluid.layers.data(name='x', shape=[1000], dtype='float32')
        y_predict = fluid.layers.fc(input=x,
                                    size=1000,
                                    act=None,
                                    param_attr=fluid.ParamAttr(name='fc_w'),
                                    bias_attr=fluid.ParamAttr(name='fc_b'))
        y = fluid.layers.data(name='y', shape=[1], dtype='float32')
        cost = fluid.layers.square_error_cost(input=y_predict, label=y)
        avg_cost = fluid.layers.mean(cost)
        base_lr = 1.0
        bd = [1, 10, 20, 30]
        lr = [base_lr * (0.1**i) for i in range(len(bd) + 1)]
        sgd_optimizer = fluid.optimizer.Momentum(
            learning_rate=fluid.layers.piecewise_decay(
                boundaries=bd, values=lr),
            momentum=0.9,
            regularization=fluid.regularizer.L2Decay(1e-4))
        sgd_optimizer.minimize(avg_cost)

Q
qiaolongfei 已提交
365
    def transpiler_test_impl(self):
T
typhoonzero 已提交
366
        pserver, startup = self.get_pserver(self.pserver1_ep)
G
gongweibao 已提交
367
        trainer, _ = self.get_trainer()
T
typhoonzero 已提交
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386

        self.assertEqual(len(pserver.blocks), 9)
        self.assertEqual([op.type for op in pserver.blocks[1].ops], [
            "increment", "cast", "fill_constant", "fill_constant", "less_than",
            "logical_not", "conditional_block", "fill_constant",
            "fill_constant", "less_than", "logical_not", "logical_and",
            "logical_and", "conditional_block", "fill_constant",
            "fill_constant", "less_than", "logical_not", "logical_and",
            "logical_and", "conditional_block", "fill_constant",
            "fill_constant", "less_than", "logical_not", "logical_and",
            "logical_and", "conditional_block", "fill_constant",
            "conditional_block"
        ])
        self.assertEqual(
            [op.type for op in pserver.blocks[7].ops],
            ["sum", "scale", "scale", "elementwise_add", "momentum"])
        self.assertEqual(
            [op.type for op in pserver.blocks[8].ops],
            ["sum", "scale", "scale", "elementwise_add", "momentum"])
Y
Yancey 已提交
387 388


389 390
class TestDistLookupTableBase(TranspilerTest):
    def network_with_table(self, is_sparse, is_distributed):
T
tangwei12 已提交
391 392
        self.table_size = 1000
        self.emb_size = 64
T
tangwei12 已提交
393
        self.lookup_table_name = 'shared_w'
T
tangwei12 已提交
394

395 396 397
        def emb_pool(ids):
            emb = fluid.layers.embedding(
                input=ids,
T
tangwei12 已提交
398
                size=[self.table_size, self.emb_size],
399
                dtype='float32',
T
tangwei12 已提交
400
                param_attr=self.lookup_table_name,  # share parameter
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
                is_sparse=is_sparse,
                is_distributed=is_distributed)
            pool = fluid.layers.sequence_pool(input=emb, pool_type='average')
            return pool

        title_ids = fluid.layers.data(
            name='title_ids', shape=[1], dtype='int64', lod_level=1)
        brand_ids = fluid.layers.data(
            name='brand_ids', shape=[1], dtype='int64', lod_level=1)
        title_emb = emb_pool(title_ids)
        brand_emb = emb_pool(brand_ids)
        fc0 = fluid.layers.concat(input=[title_emb, brand_emb], axis=1)
        predict = fluid.layers.fc(input=fc0,
                                  size=2,
                                  act=None,
                                  param_attr=fluid.ParamAttr(name='fc_w'),
                                  bias_attr=fluid.ParamAttr(name='fc_b'))

        label = fluid.layers.data(name='label', shape=[1], dtype='int64')
        cost = fluid.layers.cross_entropy(input=predict, label=label)
        avg_cost = fluid.layers.mean(cost)
        optimizer = fluid.optimizer.Adam(learning_rate=0.003)
        optimizer.minimize(avg_cost)


Q
qiaolongfei 已提交
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
class TestLocalLookupTable(TestDistLookupTableBase):
    def net_conf(self):
        self.network_with_table(is_sparse=True, is_distributed=False)

    def transpiler_test_impl(self):
        pserver1, startup1 = self.get_pserver(self.pserver1_ep)

        self.assertEqual(len(pserver1.blocks), 3)
        # 0 listen_and_serv
        # 1 optimize for fc_w or fc_b adam
        self.assertEqual([op.type for op in pserver1.blocks[1].ops],
                         ["sum", "scale", "adam", "scale", "scale"])
        # 2 optimize for table adam
        # NOTE: if param is not selected rows, the grad will scaled to grad / trainer_num
        self.assertEqual([op.type for op in pserver1.blocks[2].ops],
Q
qiaolongfei 已提交
441
                         ["sum", "scale", "adam", "scale", "scale"])
Q
qiaolongfei 已提交
442

G
gongweibao 已提交
443
        trainer, _ = self.get_trainer()
Q
qiaolongfei 已提交
444 445 446 447 448 449 450 451 452 453 454 455 456
        self.assertEqual(len(trainer.blocks), 1)
        ops = [
            'lookup_table', 'sequence_pool', 'lookup_table', 'sequence_pool',
            'concat', 'mul', 'elementwise_add', 'cross_entropy', 'mean',
            'fill_constant', 'mean_grad', 'cross_entropy_grad',
            'elementwise_add_grad', 'send', 'mul_grad', 'send', 'concat_grad',
            'sequence_pool_grad', 'lookup_table_grad', 'sequence_pool_grad',
            'lookup_table_grad', 'sum', 'split_selected_rows', 'send',
            'send_barrier', 'recv', 'recv', 'recv', 'fetch_barrier', 'concat'
        ]
        self.assertEqual([op.type for op in trainer.blocks[0].ops], ops)


457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
class TestDistLookupTable(TestDistLookupTableBase):
    def net_conf(self):
        self.network_with_table(is_sparse=True, is_distributed=True)

    def transpiler_test_impl(self):
        pserver1, startup1 = self.get_pserver(self.pserver1_ep)

        self.assertEqual(len(pserver1.blocks), 6)
        # 0 listen_and_serv
        # 1 optimize for fc_w or fc_b adam
        self.assertEqual([op.type for op in pserver1.blocks[1].ops],
                         ["sum", "scale", "adam", "scale", "scale"])
        # 2 optimize for table sgd
        self.assertEqual([op.type for op in pserver1.blocks[2].ops],
                         ["sum", "sgd"])
        # 3 prefetch -> lookup_sparse_table for data0
        self.assertEqual([op.type for op in pserver1.blocks[3].ops],
                         ["lookup_sparse_table"])
        # 4 prefetch -> lookup_sparse_table for data1
        self.assertEqual([op.type for op in pserver1.blocks[4].ops],
                         ["lookup_sparse_table"])
        # 5 save table
        self.assertEqual([op.type for op in pserver1.blocks[5].ops], ["save"])

G
gongweibao 已提交
481
        trainer, _ = self.get_trainer()
482 483 484 485 486 487 488 489 490 491 492 493 494 495
        self.assertEqual(len(trainer.blocks), 1)
        ops = [
            'split_ids', 'prefetch', 'merge_ids', 'sequence_pool', 'split_ids',
            'prefetch', 'merge_ids', 'sequence_pool', 'concat', 'mul',
            'elementwise_add', 'cross_entropy', 'mean', 'fill_constant',
            'mean_grad', 'cross_entropy_grad', 'elementwise_add_grad', 'send',
            'mul_grad', 'send', 'concat_grad', 'sequence_pool_grad',
            'lookup_table_grad', 'sequence_pool_grad', 'lookup_table_grad',
            'sum', 'split_ids', 'send', 'send_barrier', 'recv', 'recv',
            'fetch_barrier'
        ]
        self.assertEqual([op.type for op in trainer.blocks[0].ops], ops)


Q
qiaolongfei 已提交
496 497 498 499 500 501
class TestAsyncLocalLookupTable(TestDistLookupTableBase):
    def net_conf(self):
        self.network_with_table(is_sparse=True, is_distributed=False)

    def transpiler_test_impl(self):
        config = fluid.DistributeTranspilerConfig()
Q
qiaolongfei 已提交
502
        pserver1, startup1 = self.get_pserver(self.pserver1_ep, config, False)
Q
qiaolongfei 已提交
503 504 505 506 507 508 509 510 511 512 513

        self.assertEqual(len(pserver1.blocks), 3)
        # 0 listen_and_serv
        # 1 optimize for fc_w or fc_b adam
        self.assertEqual([op.type for op in pserver1.blocks[1].ops],
                         ["adam", "scale", "scale"])
        # 2 optimize for table adam
        # NOTE: if param is not selected rows, the grad will scaled to grad / trainer_num
        self.assertEqual([op.type for op in pserver1.blocks[2].ops],
                         ["adam", "scale", "scale"])

G
gongweibao 已提交
514
        trainer, _ = self.get_trainer(config)
Q
qiaolongfei 已提交
515 516 517 518 519 520 521 522 523 524 525 526 527
        self.assertEqual(len(trainer.blocks), 1)
        ops = [
            'lookup_table', 'sequence_pool', 'lookup_table', 'sequence_pool',
            'concat', 'mul', 'elementwise_add', 'cross_entropy', 'mean',
            'fill_constant', 'mean_grad', 'cross_entropy_grad',
            'elementwise_add_grad', 'send', 'mul_grad', 'send', 'concat_grad',
            'sequence_pool_grad', 'lookup_table_grad', 'sequence_pool_grad',
            'lookup_table_grad', 'sum', 'split_selected_rows', 'send', 'recv',
            'recv', 'recv', 'concat'
        ]
        self.assertEqual([op.type for op in trainer.blocks[0].ops], ops)


Q
qiaolongfei 已提交
528 529 530 531 532 533 534
class TestAsyncDistLookupTable(TestDistLookupTableBase):
    def net_conf(self):
        self.network_with_table(is_sparse=True, is_distributed=True)

    def transpiler_test_impl(self):
        config = fluid.DistributeTranspilerConfig()

Q
qiaolongfei 已提交
535
        pserver1, startup1 = self.get_pserver(self.pserver1_ep, config, False)
Q
qiaolongfei 已提交
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552

        self.assertEqual(len(pserver1.blocks), 6)
        # 0 listen_and_serv
        # 1 optimize for fc_w or fc_b adam
        self.assertEqual([op.type for op in pserver1.blocks[1].ops],
                         ["adam", "scale", "scale"])
        # 2 optimize for table sgd
        self.assertEqual([op.type for op in pserver1.blocks[2].ops], ["sgd"])
        # 3 prefetch -> lookup_sparse_table for data0
        self.assertEqual([op.type for op in pserver1.blocks[3].ops],
                         ["lookup_sparse_table"])
        # 4 prefetch -> lookup_sparse_table for data1
        self.assertEqual([op.type for op in pserver1.blocks[4].ops],
                         ["lookup_sparse_table"])
        # 5 save table
        self.assertEqual([op.type for op in pserver1.blocks[5].ops], ["save"])

G
gongweibao 已提交
553
        trainer, _ = self.get_trainer(config)
Q
qiaolongfei 已提交
554 555 556 557 558 559 560 561 562 563 564 565 566
        self.assertEqual(len(trainer.blocks), 1)
        ops = [
            'split_ids', 'prefetch', 'merge_ids', 'sequence_pool', 'split_ids',
            'prefetch', 'merge_ids', 'sequence_pool', 'concat', 'mul',
            'elementwise_add', 'cross_entropy', 'mean', 'fill_constant',
            'mean_grad', 'cross_entropy_grad', 'elementwise_add_grad', 'send',
            'mul_grad', 'send', 'concat_grad', 'sequence_pool_grad',
            'lookup_table_grad', 'sequence_pool_grad', 'lookup_table_grad',
            'sum', 'split_ids', 'send', 'recv', 'recv'
        ]
        self.assertEqual([op.type for op in trainer.blocks[0].ops], ops)


T
tangwei12 已提交
567
class TestDistLookupTableSliceSize(TestDistLookupTableBase):
T
tangwei12 已提交
568 569 570 571 572
    def net_conf(self):
        self.network_with_table(is_sparse=True, is_distributed=True)

    def transpiler_test_impl(self):
        config = fluid.DistributeTranspilerConfig()
T
tangwei12 已提交
573
        pserver1, _ = self.get_pserver(self.pserver1_ep, config)
T
tangwei12 已提交
574 575 576 577 578 579 580

        self.assertTrue(self.transpiler.has_distributed_lookup_table)
        lookup_table_var = pserver1.global_block().vars[
            self.transpiler.table_name]
        row_size = lookup_table_var.shape[0]
        calc_row_size = int(math.ceil(self.table_size / self.pservers))
        self.assertEqual(row_size, calc_row_size)
T
tangwei12 已提交
581 582


T
tangwei12 已提交
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
class TestDistArgsInProgram(TestDistLookupTableBase):
    def net_conf(self):
        self.network_with_table(is_sparse=True, is_distributed=True)

    def transpiler_test_impl(self):
        trainer, _ = self.get_trainer()

        self.assertTrue(trainer._is_distributed)
        self.assertTrue(trainer._is_chief)
        self.assertEqual(trainer._distributed_lookup_table,
                         self.lookup_table_name)
        self.assertEqual(trainer._endpoints,
                         [self.pserver1_ep, self.pserver2_ep])


W
Wu Yi 已提交
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 624 625 626
class TestRMSPropOptimizer(TranspilerTest):
    def net_conf(self):
        x = fluid.layers.data(name='x', shape=[1000], dtype='float32')
        y_predict = fluid.layers.fc(input=x,
                                    size=1000,
                                    act=None,
                                    param_attr=fluid.ParamAttr(name='fc_w'),
                                    bias_attr=fluid.ParamAttr(name='fc_b'))
        y = fluid.layers.data(name='y', shape=[1], dtype='float32')
        cost = fluid.layers.square_error_cost(input=y_predict, label=y)
        avg_cost = fluid.layers.mean(cost)
        optimizer = fluid.optimizer.RMSProp(learning_rate=0.1)
        optimizer.minimize(avg_cost)

    def transpiler_test_impl(self):
        pserver, startup = self.get_pserver(self.pserver1_ep)
        pserver2, startup2 = self.get_pserver(self.pserver2_ep)

        self.assertEqual(len(pserver.blocks), 3)
        # block1~2: optimize pass
        self.assertEqual([op.type for op in pserver.blocks[1].ops],
                         ["sum", "scale", "rmsprop"])
        # the variable #fc_w will be split into two blocks
        fc_w_var = startup.global_block().var("fc_w.block1")
        self.assertEqual(fc_w_var.shape, (500, 1000))
        moment_var = startup.global_block().var("momentum_1")
        self.assertEqual(moment_var.shape, (500, 1000))


T
tangwei12 已提交
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
class TestLoadSliceVar(TranspilerTest):
    def net_conf(self):
        x = fluid.layers.data(name='x', shape=[1000], dtype='float32')
        y_predict = fluid.layers.fc(input=x,
                                    size=1000,
                                    act=None,
                                    param_attr=fluid.ParamAttr(name='fc_w'),
                                    bias_attr=fluid.ParamAttr(name='fc_b'))
        y = fluid.layers.data(name='y', shape=[1], dtype='float32')
        cost = fluid.layers.square_error_cost(input=y_predict, label=y)
        avg_cost = fluid.layers.mean(cost)
        optimizer = fluid.optimizer.RMSProp(learning_rate=0.1)
        optimizer.minimize(avg_cost)

    def transpiler_test_impl(self):
        pserver, _ = self.get_pserver(self.pserver1_ep)
        pserver2, _ = self.get_pserver(self.pserver2_ep)

T
tangwei12 已提交
645 646
        self.assertTrue(pserver._slice_vars_and_attrs)
        self.assertTrue(pserver2._slice_vars_and_attrs)
T
tangwei12 已提交
647

M
minqiyang 已提交
648
        for idx in six.moves.xrange(len(pserver._slice_vars_and_attrs)):
T
tangwei12 已提交
649 650
            self.assertEqual(pserver._slice_vars_and_attrs[idx][0],
                             pserver2._slice_vars_and_attrs[idx][0])
T
tangwei12 已提交
651

M
minqiyang 已提交
652 653
            total_numel = six.moves.reduce(
                lambda x, y: x * y, pserver._slice_vars_and_attrs[idx][0].shape)
T
tangwei12 已提交
654 655
            self.assertEqual(
                total_numel,
M
minqiyang 已提交
656 657 658 659
                six.moves.reduce(lambda x, y: x * y,
                                 pserver._slice_vars_and_attrs[idx][2].shape) +
                six.moves.reduce(lambda x, y: x * y,
                                 pserver2._slice_vars_and_attrs[idx][2].shape))
T
tangwei12 已提交
660 661


Y
Yancey 已提交
662 663
if __name__ == "__main__":
    unittest.main()