static_model_parallel_embedding.py 3.8 KB
Newer Older
L
lilong12 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 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 45 46 47 48 49 50 51 52 53 54 55 56 57
#   Copyright (c) 2021 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.

from __future__ import print_function

import numpy as np
import argparse
import time
import math

import paddle
import paddle.fluid as fluid
import paddle.fluid.profiler as profiler
from paddle.fluid import core
import unittest
from multiprocessing import Process
import os
import signal
from functools import reduce
from test_dist_base import TestDistRunnerBase, runtime_main
import paddle.distributed.fleet as fleet

paddle.enable_static()

DTYPE = "float32"
MODEL_PARALLEL_SIZE = 2
IN_SIZE = 2 * MODEL_PARALLEL_SIZE
OUT_SIZE = 2 * MODEL_PARALLEL_SIZE

# Fix seed for test
#fluid.default_startup_program().random_seed = 1
#fluid.default_main_program().random_seed = 1


def create_model(data, rank):
    np.random.seed(2021)
    np_weight = np.random.uniform(-1, 1, size=(IN_SIZE, OUT_SIZE)).astype(DTYPE)
    if rank is not None:
        start_row = 0 if rank == 0 else IN_SIZE // 2
        np_weight_part = np_weight[start_row:start_row + IN_SIZE // 2, :]
        result = paddle.distributed.split(
            data,
            size=(IN_SIZE, OUT_SIZE),
            operation='linear',
            axis=0,
            num_partitions=MODEL_PARALLEL_SIZE,
58 59 60 61
            weight_attr=paddle.ParamAttr(initializer=fluid.initializer.
                                         NumpyArrayInitializer(np_weight_part)),
            bias_attr=False,
        )
L
lilong12 已提交
62 63 64 65 66 67
    else:
        result = fluid.layers.fc(
            data,
            size=OUT_SIZE,
            param_attr=paddle.ParamAttr(
                initializer=fluid.initializer.NumpyArrayInitializer(np_weight)),
68 69
            bias_attr=False,
        )
L
lilong12 已提交
70 71 72 73 74 75

    predict = paddle.sum(result)
    return predict


class TestModelParallel(TestDistRunnerBase):
76

L
lilong12 已提交
77 78
    def get_model(self, batch_size=2, use_dgc=False, dist_strategy=None):
        # Input data
79 80 81
        data_in = fluid.data(name='data_in',
                             shape=[batch_size, IN_SIZE],
                             dtype=DTYPE)
L
lilong12 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

        if dist_strategy:
            data_loader = fluid.io.DataLoader.from_generator(
                feed_list=[data_in],
                capacity=64,
                use_double_buffer=False,
                iterable=False)

        if dist_strategy:
            fleet.init(is_collective=True)
            strategy = fleet.DistributedStrategy()
            strategy.tensor_parallel = True
            strategy.tensor_parallel_configs = {'tensor_parallel_degree': 2}

        rank = fleet.worker_index() if dist_strategy else None
        avg_cost = create_model(data_in, rank)
        opt = fluid.optimizer.SGD(0.1)

        if dist_strategy:
101 102
            dist_opt = fleet.distributed_optimizer(optimizer=opt,
                                                   strategy=strategy)
L
lilong12 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
            dist_opt.minimize(avg_cost)
        else:
            opt.minimize(avg_cost)

        def gen_data():
            np.random.seed(2021)
            while True:
                data = [np.random.random([IN_SIZE]).astype(DTYPE)]
                yield data

        train_reader = paddle.batch(gen_data, batch_size=batch_size)

        if dist_strategy:
            return None, avg_cost, train_reader, None, None, None, data_loader
        else:
            return None, avg_cost, train_reader, None, None, None


if __name__ == "__main__":
    runtime_main(TestModelParallel)