hybrid_parallel_pp_transformer.py 5.8 KB
Newer Older
1
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# 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
import unittest
17

18
import numpy as np
19 20

import paddle
21 22
import paddle.distributed as dist
import paddle.nn.functional as F
23 24
from paddle import nn
from paddle.distributed import fleet
25
from paddle.distributed.fleet.meta_parallel import LayerDesc, PipelineLayer
26
from paddle.nn import Layer
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46


def set_random_seed(seed, dp_id, rank_id):
    """Set random seed for reproducability."""
    random.seed(seed)
    np.random.seed(seed + dp_id)
    paddle.seed(seed + dp_id)


batch_size = 8
length = 8
micro_batch_size = 2
vocab_size = 128
hidden_size = 16
d_model = hidden_size
dim_feedforward = 4 * d_model


class EmbeddingNet(Layer):
    def __init__(self):
47
        super().__init__()
48 49 50 51
        self.word_embeddings = nn.Embedding(vocab_size, hidden_size)
        self.position_embeddings = nn.Embedding(vocab_size, hidden_size)

    def forward(self, x):
52 53 54
        attention_mask = paddle.tensor.triu(
            (paddle.ones((length, length), dtype="float32") * -1e9), 1
        )
55 56 57

        no_used = paddle.ones((3, 3), dtype="int32")

58 59 60 61
        w_emb = self.word_embeddings(x)
        p_emb = self.position_embeddings(x)
        w_emb = w_emb + p_emb

62 63
        attention_mask.stop_gradient = True
        no_used.stop_gradient = True
64
        # need to fix bug of backward()
65
        return w_emb, attention_mask, no_used, p_emb
66 67 68 69


class TransformerNet(Layer):
    def __init__(self):
70
        super().__init__()
71 72 73 74 75 76 77 78 79 80 81 82 83
        self.linear1 = nn.Linear(d_model, dim_feedforward)
        self.linear2 = nn.Linear(dim_feedforward, d_model)

        self.q_proj = nn.Linear(d_model, d_model)
        self.k_proj = nn.Linear(d_model, d_model)
        self.v_proj = nn.Linear(d_model, d_model)

        self.norm1 = nn.LayerNorm(d_model, epsilon=1e-5)

    def forward(self, x, mask):
        q = self.q_proj(x)
        k = self.k_proj(x)
        v = self.v_proj(x)
K
kangguangli 已提交
84 85
        product = paddle.matmul(x=q, y=k, transpose_y=True)
        product = paddle.scale(product, scale=d_model**-0.5)
86 87

        weights = F.softmax(product + mask)
88 89
        # TODO(shenliang03) For save/load in PipeLineParallel, can’t support dropout temporarily.
        # weights = F.dropout(weights, 0.2)
K
kangguangli 已提交
90
        tgt = paddle.matmul(weights, v)
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
        residual = tgt
        tgt = self.norm1(tgt)
        tgt = residual + tgt

        out = self.linear2(F.gelu(self.linear1(tgt), approximate=True))
        return out


class EmbeddingPipe(EmbeddingNet):
    def forward(self, x):
        return super().forward(x)


class TransformerNetPipe(TransformerNet):
    def forward(self, args):
106
        x, mask, no_used, p_emb = args[0], args[1], args[2], args[3]
107 108

        output = super().forward(x, mask)
109
        output = output + p_emb
110
        mask.stop_gradient = True
111
        return output, mask, no_used, p_emb
112 113 114 115


class CriterionPipe(Layer):
    def __init__(self):
116
        super().__init__()
117 118 119 120 121 122 123

    def forward(self, out, label):
        loss = out.mean()
        return loss


class ModelPipe(PipelineLayer):
124
    def __init__(self, topology, transformer_layer_num: int = 6):
125 126 127
        self.descs = []
        self.descs.append(LayerDesc(EmbeddingPipe))

128
        for x in range(transformer_layer_num):
129 130 131 132
            self.descs.append(LayerDesc(TransformerNetPipe))

        self.descs.append(lambda x: x[0])

133 134 135 136 137 138
        super().__init__(
            layers=self.descs,
            loss_fn=CriterionPipe(),
            topology=topology,
            seg_method="layer:TransformerNetPipe",
        )
139 140


C
co63oc 已提交
141
class TestDistPPTraining(unittest.TestCase):
142 143 144 145 146 147 148 149 150 151 152 153
    def setUp(self):
        strategy = fleet.DistributedStrategy()
        self.model_parallel_size = 1
        self.data_parallel_size = 1
        self.pipeline_parallel_size = 2
        strategy.hybrid_configs = {
            "dp_degree": self.data_parallel_size,
            "mp_degree": self.model_parallel_size,
            "pp_degree": self.pipeline_parallel_size,
        }
        strategy.pipeline_configs = {
            "accumulate_steps": batch_size // micro_batch_size,
154
            "micro_batch_size": micro_batch_size,
155 156 157 158 159 160 161 162 163 164 165 166 167
        }
        fleet.init(is_collective=True, strategy=strategy)

    def test_pp_model(self):
        hcg = fleet.get_hybrid_communicate_group()
        word_size = hcg.get_model_parallel_world_size()
        dp_id = hcg.get_data_parallel_rank()
        pp_id = hcg.get_stage_id()
        rank_id = dist.get_rank()
        topology = hcg.topology()
        set_random_seed(1024, dp_id, rank_id)

        model = ModelPipe(topology)
168 169 170 171 172 173
        scheduler = paddle.optimizer.lr.PiecewiseDecay(
            boundaries=[2], values=[0.001, 0.002], verbose=True
        )
        optimizer = paddle.optimizer.SGD(
            learning_rate=scheduler, parameters=model.parameters()
        )
174 175 176 177 178 179 180 181

        model = fleet.distributed_model(model)
        optimizer = fleet.distributed_optimizer(optimizer)

        for step_id in range(5):
            x_data = np.random.randint(0, vocab_size, size=[batch_size, length])
            x = paddle.to_tensor(x_data)
            x.stop_gradient = True
182 183

            e_loss = model.eval_batch([x, x], True)
184 185
            loss = model.train_batch([x, x], optimizer, scheduler)

186 187 188
            # TODO(shenliang03) add utest for loss
            if pp_id != 0:
                np.testing.assert_allclose(loss.numpy(), e_loss.numpy())
189

190 191 192

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