hybrid_parallel_mp_layers.py 10.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 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.

15
import random
16 17 18
import unittest

import numpy as np
19 20

import paddle
21
import paddle.distributed as dist
22
from paddle.distributed import fleet
23 24 25 26 27 28 29 30 31 32


def set_random_seed(seed):
    """Set random seed for reproducability."""
    random.seed(seed)
    np.random.seed(seed)
    paddle.seed(seed)
    fleet.meta_parallel.model_parallel_random_seed(seed)


33
class ColumnLinearNet(paddle.nn.Layer):
34
    def __init__(self, input_size, output_size, global_dtype):
35
        super().__init__()
36 37 38 39 40 41
        self.parallel_linear = fleet.meta_parallel.ColumnParallelLinear(
            in_features=input_size,
            out_features=output_size,
            weight_attr=None,
            has_bias=True,
            gather_output=True,
42 43
            name="test_column_linear",
        )
44 45 46 47 48 49

    def forward(self, x):
        output = self.parallel_linear(x)
        return output


50
class RowLinearNet(paddle.nn.Layer):
51
    def __init__(self, input_size, output_size):
52
        super().__init__()
53 54 55 56 57
        self.parallel_linear = fleet.meta_parallel.RowParallelLinear(
            in_features=input_size,
            out_features=output_size,
            has_bias=True,
            input_is_parallel=False,
58 59
            name="test_row_linear",
        )
60 61 62 63 64 65

    def forward(self, x):
        output = self.parallel_linear(x)
        return output


66
class EmbeddingNet(paddle.nn.Layer):
67
    def __init__(self, vocab_size, hidden_size):
68
        super().__init__()
69
        self.embedding = fleet.meta_parallel.VocabParallelEmbedding(
70 71
            vocab_size, hidden_size
        )
72 73 74 75 76 77

    def forward(self, x):
        output = self.embedding(x)
        return output


78
class SimpleMatmul(paddle.nn.Layer):
79
    def __init__(self, weight, output_size, global_dtype):
80
        super().__init__()
81 82 83 84
        self.weight = paddle.create_parameter(
            shape=weight.shape,
            dtype=global_dtype,
            attr=paddle.ParamAttr(
85 86 87
                initializer=paddle.nn.initializer.Assign(weight)
            ),
        )
88 89 90 91
        self.bias = self.create_parameter(
            shape=[output_size],
            dtype=global_dtype,
            attr=paddle.ParamAttr(
92 93 94
                initializer=paddle.nn.initializer.Constant(0.0)
            ),
        )
95 96 97 98 99 100

    def forward(self, x):
        output = paddle.matmul(x, self.weight) + self.bias
        return output


101
class SimpleEmbedding(paddle.nn.Layer):
102
    def __init__(self, vocab_size, hidden_size, weight):
103
        super().__init__()
104 105 106 107 108
        self.embedding = paddle.nn.Embedding(
            vocab_size,
            hidden_size,
            weight_attr=paddle.framework.ParamAttr(
                name="origin_embedding",
109 110 111
                initializer=paddle.nn.initializer.Assign(weight),
            ),
        )
112 113 114 115 116 117 118 119 120 121 122 123 124

    def forward(self, x):
        output = self.embedding(x)
        return output


class TestDistTraning(unittest.TestCase):
    def setUp(self):
        strategy = fleet.DistributedStrategy()
        self.model_parallel_size = 2
        strategy.hybrid_configs = {
            "dp_degree": 1,
            "mp_degree": self.model_parallel_size,
125
            "pp_degree": 1,
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
        }
        fleet.init(is_collective=True, strategy=strategy)

    def test_column_parallel_layer(self):
        set_random_seed(1024)
        global_dtype = "float32"

        input_size_per_card = 17
        input_size = input_size_per_card * self.model_parallel_size
        output_size_per_card = 13
        output_size = output_size_per_card * self.model_parallel_size
        batch_size = 4

        model_a = ColumnLinearNet(input_size, output_size, global_dtype)

        # get w
        check_group = dist.new_group(list(range(self.model_parallel_size)))
        integral_w = []
        partial_w = model_a.parallel_linear.weight.clone().detach()
        paddle.distributed.all_gather(integral_w, partial_w, group=check_group)
        integral_w = paddle.concat(integral_w, axis=1)

        model_b = SimpleMatmul(integral_w, output_size, global_dtype)

150 151 152 153 154 155
        optimizer_a = paddle.optimizer.SGD(
            learning_rate=0.001, parameters=model_a.parameters()
        )
        optimizer_b = paddle.optimizer.SGD(
            learning_rate=0.001, parameters=model_b.parameters()
        )
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
        for idx in range(5):
            input = paddle.randn([batch_size, input_size], global_dtype)
            input.stop_gradient = True

            output_a = model_a(input)
            loss_a = output_a.mean()
            loss_a.backward()

            output_b = model_b(input)
            loss_b = output_b.mean()
            loss_b.backward()

            optimizer_a.step()
            optimizer_b.step()

            np.testing.assert_allclose(loss_a.numpy(), loss_b.numpy())

    def test_row_parallel_layer(self):
        global_dtype = "float32"
        paddle.set_default_dtype(global_dtype)
        set_random_seed(1024)

        self.hcg = fleet.get_hybrid_communicate_group()

        self.word_size = self.hcg.get_model_parallel_world_size()
        self.rank_id = self.hcg.get_model_parallel_rank()

183
        input_size_per_card = 11
184
        input_size = input_size_per_card * self.model_parallel_size
185
        output_size_per_card = 10
186 187 188 189 190 191 192 193 194 195 196 197 198 199
        output_size = output_size_per_card * self.model_parallel_size
        batch_size = 4

        model_a = RowLinearNet(input_size, output_size)

        # get w
        check_group = dist.new_group(list(range(self.model_parallel_size)))
        integral_w = []
        partial_w = model_a.parallel_linear.weight.clone().detach()
        paddle.distributed.all_gather(integral_w, partial_w, group=check_group)
        integral_w = paddle.concat(integral_w, axis=0)

        model_b = SimpleMatmul(integral_w, output_size, global_dtype)

200 201 202
        optimizer_a = paddle.optimizer.SGD(
            learning_rate=0.001, parameters=model_a.parameters()
        )
203

204 205 206
        optimizer_b = paddle.optimizer.SGD(
            learning_rate=0.001, parameters=model_b.parameters()
        )
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222

        for idx in range(5):
            input = paddle.randn([batch_size, input_size], global_dtype)
            input.stop_gradient = True

            output_a = model_a(input)
            loss_a = output_a.mean()
            loss_a.backward()

            output_b = model_b(input)
            loss_b = output_b.mean()
            loss_b.backward()

            optimizer_a.step()
            optimizer_b.step()

223 224 225
            np.testing.assert_allclose(
                loss_a.numpy(), loss_b.numpy(), rtol=5e-6
            )
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243

    def test_parallel_embedding(self):
        batch_size = 17
        seq_length = 23
        vocab_size_per_card = 2
        vocab_size = vocab_size_per_card * self.model_parallel_size
        hidden_size = 2
        seed = 1236

        set_random_seed(seed)
        rank_id = dist.get_rank()

        # model_a
        model_a = EmbeddingNet(vocab_size, hidden_size)

        # model_b
        check_group = dist.new_group(list(range(self.model_parallel_size)))
        integral_w = []
244
        partial_w = model_a.embedding.weight.clone().detach()
245 246 247 248 249
        paddle.distributed.all_gather(integral_w, partial_w, group=check_group)
        result_w = []
        for idx in range(len(integral_w)):
            tmp = paddle.gather(
                integral_w[idx],
250 251
                paddle.to_tensor(list(range(vocab_size_per_card))),
            )
252 253 254 255 256
            result_w.append(tmp)
        integral_w = paddle.concat(result_w, axis=0)

        model_b = SimpleEmbedding(vocab_size, hidden_size, integral_w)

257 258 259
        optimizer_a = paddle.optimizer.SGD(
            learning_rate=0.001, parameters=model_a.parameters()
        )
260

261 262 263
        optimizer_b = paddle.optimizer.SGD(
            learning_rate=0.001, parameters=model_b.parameters()
        )
264 265

        for _ in range(5):
266 267 268
            np_input_data = np.random.randint(
                0, vocab_size, (batch_size, seq_length)
            )
269 270 271 272 273 274 275 276 277 278 279 280 281
            input_data = paddle.to_tensor(np_input_data, dtype="int32")

            output_a = model_a(input_data)
            loss_a = output_a.mean()

            output_b = model_b(input_data)
            loss_b = output_b.mean()

            loss_a.backward()
            loss_b.backward()

            optimizer_a.step()
            optimizer_b.step()
282 283 284
            print(loss_a.numpy(), loss_b.numpy())

            np.testing.assert_allclose(loss_a.numpy(), loss_b.numpy())
285

286
    def test_parallel_cross_entropy(self):
287 288
        batch_size = 8
        seq_length = 16
289 290
        class_size_per_card = 2
        vocab_size = class_size_per_card * self.model_parallel_size
291
        seed = 100
292 293 294 295 296 297 298 299 300 301 302 303 304 305

        set_random_seed(seed)
        rank_id = dist.get_rank()

        # model_a
        model_a = fleet.meta_parallel.ParallelCrossEntropy()

        model_b = paddle.nn.CrossEntropyLoss(reduction="none")

        paddle.seed(rank_id * 10)
        random.seed(seed)
        np.random.seed(seed)

        for _ in range(5):
306 307 308
            np_label = np.random.randint(
                0, vocab_size, (batch_size, seq_length)
            )
309 310 311 312
            label = paddle.to_tensor(np_label, dtype="int64")

            data = paddle.randn(
                shape=[batch_size, seq_length, class_size_per_card],
313 314
                dtype='float32',
            )
315 316 317 318 319
            data.stop_gradient = False

            check_group = dist.new_group(list(range(self.model_parallel_size)))
            integral_data = []
            partial_data = data.clone().detach()
320 321 322
            paddle.distributed.all_gather(
                integral_data, partial_data, group=check_group
            )
323 324 325 326 327 328 329 330
            integral_data = paddle.concat(integral_data, axis=-1)
            integral_data = integral_data.detach().clone()
            integral_data.stop_gradient = False

            loss_a = model_a(data, label).sum() / batch_size
            loss_b = model_b(integral_data, label).sum() / batch_size
            print("loss_a: ", loss_a.numpy(), "loss_b: ", loss_b.numpy())

331 332 333
            np.testing.assert_allclose(
                loss_a.numpy(), loss_b.numpy(), rtol=1e-6
            )
334 335 336 337 338 339

            loss_a.backward()
            loss_b.backward()

            integral_grad = []
            partial_grad = data.grad.clone().detach()
340 341 342
            paddle.distributed.all_gather(
                integral_grad, partial_grad, group=check_group
            )
343 344
            integral_grad = paddle.concat(integral_grad, axis=-1)

345 346 347
            np.testing.assert_allclose(
                integral_data.grad.numpy(), integral_grad.numpy(), rtol=1e-6
            )
348

349 350 351

if __name__ == '__main__':
    unittest.main()