dygraph_hybrid_dpppmp.py 6.6 KB
Newer Older
R
Roc 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2022 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.

import numpy as np
16 17 18 19
from test_collective_multi_nodes import (
    TestCollectiveAPIRunnerBase,
    runtime_main,
)
20 21

import paddle
R
Roc 已提交
22
from paddle import nn
23
from paddle.distributed import fleet
R
Roc 已提交
24 25 26 27 28 29 30 31 32 33


def weight_init(mp, shape, col=True, seed=1024):
    np.random.seed(seed)
    w = np.random.normal(0, 0.02, size=shape)
    if mp is None:
        _w = w
    else:
        if col:
            step = shape[1] // mp.nranks
34
            _w = w[:, mp.rank * step : mp.rank * step + step]
R
Roc 已提交
35 36
        else:
            step = shape[0] // mp.nranks
37
            _w = w[mp.rank * step : mp.rank * step + step, :]
38
    return paddle.nn.initializer.Assign(_w)
R
Roc 已提交
39 40 41 42


class Criterion(nn.Layer):
    def __init__(self):
43
        super().__init__()
R
Roc 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
        self.loss_func = nn.MSELoss(reduction="mean")

    def forward(self, pred, label):
        loss = self.loss_func(pred, label)
        return loss


class ModelPipeline(fleet.meta_parallel.PipelineLayer):
    def __init__(self, hcg):
        paddle.seed(1024)
        dp_linear = nn.Linear(32, 128)
        self.layers_pp = []
        self.topology = hcg.topology()
        self.layers_pp.append(dp_linear)
        mp = hcg.get_model_parallel_group()
        for i in range(6):
            if mp is not None and mp.nranks > 1:
                mp_linear_1 = fleet.meta_parallel.ColumnParallelLinear(
                    128,
                    512,
                    weight_attr=weight_init(mp, (128, 512), True, 1204 + i),
                    has_bias=True,
66 67
                    gather_output=False,
                )
R
Roc 已提交
68 69 70 71 72
                mp_linear_2 = fleet.meta_parallel.RowParallelLinear(
                    512,
                    128,
                    weight_attr=weight_init(mp, (512, 128), False, 2012 + i),
                    has_bias=True,
73 74
                    input_is_parallel=True,
                )
R
Roc 已提交
75
            else:
76 77 78 79 80 81 82 83 84 85
                mp_linear_1 = nn.Linear(
                    128,
                    512,
                    weight_attr=weight_init(None, (128, 512), True, 1204 + i),
                )
                mp_linear_2 = nn.Linear(
                    512,
                    128,
                    weight_attr=weight_init(None, (512, 128), True, 2012 + i),
                )
R
Roc 已提交
86 87 88 89 90 91
            act = nn.ReLU6()
            layer_seq = nn.Sequential(mp_linear_1, mp_linear_2, act)
            self.layers_pp.append(layer_seq)

        out = nn.Linear(128, 32)
        self.layers_pp.append(out)
92
        super().__init__(
93 94
            layers=self.layers_pp, loss_fn=Criterion(), topology=self.topology
        )
R
Roc 已提交
95 96 97 98


class Model(nn.Layer):
    def __init__(self, hcg):
99
        super().__init__()
R
Roc 已提交
100 101 102 103 104 105 106 107 108 109 110 111
        paddle.seed(1024)
        dp_linear = nn.Linear(32, 128)
        self.layers_pp = []
        self.layers_pp.append(dp_linear)
        mp = hcg.get_model_parallel_group() if hcg else None
        for i in range(6):
            if mp is not None and mp.nranks > 1:
                mp_linear_1 = fleet.meta_parallel.ColumnParallelLinear(
                    128,
                    512,
                    weight_attr=weight_init(mp, (128, 512), True, 1204 + i),
                    has_bias=True,
112 113
                    gather_output=False,
                )
R
Roc 已提交
114 115 116 117 118
                mp_linear_2 = fleet.meta_parallel.RowParallelLinear(
                    512,
                    128,
                    weight_attr=weight_init(mp, (512, 128), False, 2012 + i),
                    has_bias=True,
119 120
                    input_is_parallel=True,
                )
R
Roc 已提交
121
            else:
122 123 124 125 126 127 128 129 130 131
                mp_linear_1 = nn.Linear(
                    128,
                    512,
                    weight_attr=weight_init(None, (128, 512), True, 1204 + i),
                )
                mp_linear_2 = nn.Linear(
                    512,
                    128,
                    weight_attr=weight_init(None, (512, 128), True, 2012 + i),
                )
R
Roc 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
            act = nn.ReLU6()
            layer_seq = nn.Sequential(mp_linear_1, mp_linear_2, act)
            self.layers_pp.append(layer_seq)

        out = nn.Linear(128, 32)
        self.layers_pp.append(out)
        self.layers = nn.Sequential(*self.layers_pp)

    def forward(self, x):
        return self.layers(x)


class TestDygrapgHybridDPPPMP(TestCollectiveAPIRunnerBase):
    def __init__(self):
        pass

    def check_pass(self, *args, **kwargs):

        from common import init_parallel_env
151

R
Roc 已提交
152 153
        import paddle
        from paddle.distributed import fleet
154

R
Roc 已提交
155 156 157
        hcg = init_parallel_env("DP4-MP2-PP2-SH1-O1", 64)
        pp_degree = hcg.get_pipe_parallel_world_size()
        import numpy as np
158

R
Roc 已提交
159 160 161 162 163 164 165 166
        crit = Criterion()
        if pp_degree <= 1:
            model = Model(hcg)
        else:
            model = ModelPipeline(hcg)

        model_base = Model(None)

167 168 169
        optimizer = paddle.optimizer.Adam(
            learning_rate=0.01, parameters=model.parameters()
        )
R
Roc 已提交
170
        optimizer_base = paddle.optimizer.Adam(
171 172
            learning_rate=0.01, parameters=model_base.parameters()
        )
R
Roc 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205

        model = fleet.distributed_model(model)
        optimizer = fleet.distributed_optimizer(optimizer)
        loss_hybrid_arr = []
        loss_base_arr = []

        x = paddle.to_tensor(np.random.random((16, 32))).astype("float32")
        y = paddle.to_tensor(np.random.random((16, 32))).astype("float32")

        for _ in range(5):
            if pp_degree > 1:
                loss = model.train_batch([x, y], optimizer=optimizer)
            else:
                output = model(x)
                loss = crit(output, y)
                loss.backward()
                optimizer.step()
                optimizer.clear_grad()

            # baseline loss
            output_base = model_base(x)
            loss_base = crit(output_base, y)
            loss_base.backward()
            optimizer_base.step()
            optimizer_base.clear_grad()

            loss_base_arr.append(loss_base.numpy())
            loss_hybrid_arr.append(loss.numpy())
        assert np.allclose(loss_base_arr, loss_hybrid_arr, rtol=1e-5, atol=1e-5)


if __name__ == "__main__":
    runtime_main(TestDygrapgHybridDPPPMP, "dpppmp")