simple_model.py 10.4 KB
Newer Older
aiss's avatar
aiss committed
1
2
3
4
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: Apache-2.0

# DeepSpeed Team
aiss's avatar
aiss committed
5

6
7
8
9
10
import os
import json
import argparse
import torch

11
from deepspeed.pipe import PipelineModule, LayerSpec
aiss's avatar
aiss committed
12
from deepspeed.moe.layer import MoE
aiss's avatar
aiss committed
13
14
15
from deepspeed.accelerator import get_accelerator

import deepspeed.comm as dist
16

17
18

class SimpleModel(torch.nn.Module):
aiss's avatar
aiss committed
19

aiss's avatar
aiss committed
20
    def __init__(self, hidden_dim, empty_grad=False, nlayers=1):
21
        super(SimpleModel, self).__init__()
aiss's avatar
aiss committed
22
        self.linears = torch.nn.ModuleList([torch.nn.Linear(hidden_dim, hidden_dim) for i in range(nlayers)])
23
        if empty_grad:
Jeff Rasley's avatar
Jeff Rasley committed
24
            self.linear2 = torch.nn.Linear(hidden_dim, hidden_dim)
25
        self.cross_entropy_loss = torch.nn.CrossEntropyLoss()
Jeff Rasley's avatar
Jeff Rasley committed
26
        self.empty_grad = empty_grad
27
28

    def forward(self, x, y):
aiss's avatar
aiss committed
29
30
        if len(self.linears) == 1:
            x = self.linears[0](x)
Jeff Rasley's avatar
Jeff Rasley committed
31
        else:
aiss's avatar
aiss committed
32
33
34
35
36
            for i, l in enumerate(self.linears):
                x = self.linears[i // 2](x) + l(x)
        return self.cross_entropy_loss(x, y)


aiss's avatar
aiss committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class SimpleFrozenModel(torch.nn.Module):

    def __init__(self, hidden_dim, empty_grad=False):
        super(SimpleFrozenModel, self).__init__()
        self.linears = torch.nn.ModuleList([torch.nn.Linear(hidden_dim, hidden_dim) for i in range(2)])
        if empty_grad:
            self.linear2 = torch.nn.Linear(hidden_dim, hidden_dim)
        self.cross_entropy_loss = torch.nn.CrossEntropyLoss()
        self.empty_grad = empty_grad
        # Freeze first layer
        self.linears[0].weight.requires_grad = False
        self.linears[0].bias.requires_grad = False

    def forward(self, x, y):
        if len(self.linears) == 1:
            x = self.linears[0](x)
        else:
            for i, l in enumerate(self.linears):
                x = self.linears[i // 2](x) + l(x)
        return self.cross_entropy_loss(x, y)


aiss's avatar
aiss committed
59
class Curriculum_SimpleModel(SimpleModel):
aiss's avatar
aiss committed
60

aiss's avatar
aiss committed
61
62
63
64
65
66
67
68
69
70
    def __init__(self, hidden_dim, empty_grad=False):
        super(Curriculum_SimpleModel, self).__init__(hidden_dim, empty_grad)

    def forward(self, x, y, **kwargs):
        seqlen = kwargs.get('curriculum_seqlen', None)
        loss = super(Curriculum_SimpleModel, self).forward(x, y)
        return loss, seqlen


class SimpleMoEModel(torch.nn.Module):
aiss's avatar
aiss committed
71

aiss's avatar
aiss committed
72
73
74
    def __init__(self, hidden_dim, num_experts=4, ep_size=1, use_residual=False):
        super(SimpleMoEModel, self).__init__()
        self.linear = torch.nn.Linear(hidden_dim, hidden_dim)
aiss's avatar
aiss committed
75
76
        expert = torch.nn.Linear(hidden_dim, hidden_dim)
        # using two MoE layers to check implications of sharing a single storage
aiss's avatar
aiss committed
77
        self.linear2 = MoE(hidden_size=hidden_dim,
aiss's avatar
aiss committed
78
79
80
81
82
83
84
                           expert=expert,
                           ep_size=ep_size,
                           use_residual=use_residual,
                           num_experts=num_experts,
                           k=1)
        self.linear3 = MoE(hidden_size=hidden_dim,
                           expert=expert,
aiss's avatar
aiss committed
85
86
87
88
89
90
91
                           ep_size=ep_size,
                           use_residual=use_residual,
                           num_experts=num_experts,
                           k=1)
        self.cross_entropy_loss = torch.nn.CrossEntropyLoss()

    def forward(self, x, y):
aiss's avatar
aiss committed
92
        hidden_dim = self.linear(x)
aiss's avatar
aiss committed
93
        output, _, _ = self.linear2(hidden_dim)
aiss's avatar
aiss committed
94
        output, _, _ = self.linear3(output)
aiss's avatar
aiss committed
95
96
97
98
99
100
        hidden_dim = hidden_dim + output
        sentence_embed = hidden_dim.mean(1)
        return self.cross_entropy_loss(sentence_embed, y)


class SimplePRMoEModel(torch.nn.Module):
aiss's avatar
aiss committed
101

aiss's avatar
aiss committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    def __init__(self, hidden_dim, num_experts=2, ep_size=1, use_residual=False):
        super(SimplePRMoEModel, self).__init__()
        self.linear = torch.nn.Linear(hidden_dim, hidden_dim)
        linear2 = torch.nn.Linear(hidden_dim, hidden_dim)
        self.linear2 = MoE(hidden_size=hidden_dim,
                           expert=linear2,
                           ep_size=ep_size,
                           use_residual=use_residual,
                           num_experts=num_experts,
                           k=1)
        linear3 = torch.nn.Linear(hidden_dim, hidden_dim)
        self.linear3 = MoE(hidden_size=hidden_dim,
                           expert=linear3,
                           ep_size=ep_size,
                           use_residual=use_residual,
                           num_experts=int(2 * num_experts),
                           k=1)
        self.cross_entropy_loss = torch.nn.CrossEntropyLoss()

    def forward(self, x, y):
        hidden_dim = x
        hidden_dim = self.linear(hidden_dim)
        output, _, _ = self.linear2(hidden_dim)
        output, _, _ = self.linear3(output)
        hidden_dim = hidden_dim + output
        sentence_embed = hidden_dim.mean(1)
        return self.cross_entropy_loss(sentence_embed, y)


class UnusedParametersModel(SimpleModel):
aiss's avatar
aiss committed
132

aiss's avatar
aiss committed
133
134
135
136
    def __init__(self, hidden_dim, empty_grad=False):
        super().__init__(hidden_dim, empty_grad)

        self.unused_linear = torch.nn.Linear(hidden_dim, hidden_dim)
137
138


139
class LinearStack(torch.nn.Module):
aiss's avatar
aiss committed
140

141
142
143
144
145
146
    def __init__(self, input_dim=128, hidden_dim=128, output_dim=128, num_layers=4):
        super().__init__()
        self.input_dim = input_dim
        self.output_dim = output_dim
        self.hidden_dim = hidden_dim

aiss's avatar
aiss committed
147
        self.input_layer = torch.nn.Linear(in_features=self.input_dim, out_features=self.hidden_dim)
148
        self.layers = torch.nn.ModuleList([
aiss's avatar
aiss committed
149
150
            torch.nn.Linear(in_features=self.hidden_dim, out_features=self.hidden_dim, bias=False)
            for x in range(num_layers)
151
        ])
aiss's avatar
aiss committed
152
        self.output_layer = torch.nn.Linear(in_features=self.hidden_dim, out_features=self.output_dim)
153
154
155
156
157
158
159
160
161
162
163
164

        self.cross_entropy_loss = torch.nn.CrossEntropyLoss()

    def forward(self, x, y):
        x = self.input_layer(x)
        for layer in self.layers:
            x = layer(x)
        x = self.output_layer(x)
        return x


class LinearStackPipe(PipelineModule):
aiss's avatar
aiss committed
165
166

    def __init__(self, input_dim=128, hidden_dim=128, output_dim=128, num_layers=4, **kwargs):
167
168
169
170
171
172
173
174
        self.input_dim = input_dim
        self.output_dim = output_dim
        self.hidden_dim = hidden_dim
        self.num_layers = num_layers

        layers = []
        layers.append(LayerSpec(torch.nn.Linear, self.input_dim, self.hidden_dim))
        for x in range(self.num_layers):
aiss's avatar
aiss committed
175
            layers.append(LayerSpec(torch.nn.Linear, self.hidden_dim, self.hidden_dim, bias=False))
176
177
178
179
180
181
            layers.append(lambda x: x)
        layers.append(LayerSpec(torch.nn.Linear, self.hidden_dim, self.output_dim))

        super().__init__(layers=layers, loss_fn=torch.nn.CrossEntropyLoss(), **kwargs)


182
class SimpleOptimizer(torch.optim.Optimizer):
aiss's avatar
aiss committed
183

184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
    def __init__(self, params, lr=0.11072018):
        defaults = dict(lr=lr)
        super(SimpleOptimizer, self).__init__(params, defaults)

    def __setstate__(self, state):
        super(SimpleOptimizer, self).__setstate__(state)

    def step(self, closure=None):
        loss = None
        if closure is not None:
            loss = closure()

        for group in self.param_groups:
            for p in group['params']:
                if p.grad is None:
                    continue
                d_p = p.grad.data
                p.data.add_(-group['lr'], d_p)

        return loss


206
class HybridStateOptimizer(torch.optim.Optimizer):
aiss's avatar
aiss committed
207

208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
    def __init__(self, params, lr=0.11072018):
        defaults = dict(lr=lr)
        super(HybridStateOptimizer, self).__init__(params, defaults)

    def __setstate__(self, state):
        super(HybridStateOptimizer, self).__setstate__(state)

    def step(self, closure=None):
        loss = None
        if closure is not None:
            loss = closure()

        for group in self.param_groups:
            for p in group['params']:
                if p.grad is None:
                    continue

                state = self.state[p]
                if len(state) == 0:
                    state['integer_step'] = 0
aiss's avatar
aiss committed
228
                    state['tensor_step'] = torch.zeros(1, device=p.device)
229
230
231
232
233
234
235
236
237

                d_p = p.grad.data
                p.data.add_(-group['lr'], d_p)
                state['integer_step'] += 1
                state['tensor_step'] += 1

        return loss


Olatunji Ruwase's avatar
Olatunji Ruwase committed
238
class PLD_SimpleModel(SimpleModel):
aiss's avatar
aiss committed
239

240
241
    def __init__(self, hidden_dim, empty_grad=False):
        super(PLD_SimpleModel, self).__init__(hidden_dim, empty_grad)
Olatunji Ruwase's avatar
Olatunji Ruwase committed
242
243
244
245
246
247
248
249

    def forward(self, x, y, **kwargs):
        pld = kwargs.get('progressive_layer_drop', False)
        theta = kwargs.get('pld_theta', 1.0)
        hidden_dim = super(PLD_SimpleModel, self).forward(x, y)
        return hidden_dim


aiss's avatar
aiss committed
250
251
def random_dataset(total_samples, hidden_dim, device, dtype=torch.half):
    train_data = torch.randn(total_samples, hidden_dim, device=device, dtype=dtype)
aiss's avatar
aiss committed
252
    train_label = torch.empty(total_samples, dtype=torch.long, device=device).random_(hidden_dim)
aiss's avatar
aiss committed
253
254
255
256
    train_dataset = torch.utils.data.TensorDataset(train_data, train_label)
    return train_dataset


257
def random_dataloader(model, total_samples, hidden_dim, device, dtype=torch.half):
258
    batch_size = model.train_micro_batch_size_per_gpu()
aiss's avatar
aiss committed
259
260
261
262
263
    train_dataset = random_dataset(total_samples, hidden_dim, device, dtype=dtype)
    train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size)
    return train_loader


aiss's avatar
aiss committed
264
def sequence_dataloader(model, total_samples, hidden_dim, device, seq_len: int = 32, dtype=torch.half):
aiss's avatar
aiss committed
265
    batch_size = model.train_micro_batch_size_per_gpu()
aiss's avatar
aiss committed
266
267
    train_data = torch.randn(total_samples, seq_len, hidden_dim, device=device, dtype=dtype)
    train_label = torch.empty(total_samples, dtype=torch.long, device=device).random_(hidden_dim)
268
269
270
271
272
273
274
275
276
277
278
279
    train_dataset = torch.utils.data.TensorDataset(train_data, train_label)
    train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size)
    return train_loader


def create_config_from_dict(tmpdir, config_dict):
    config_path = os.path.join(tmpdir, 'temp_config.json')
    with open(config_path, 'w') as fd:
        json.dump(config_dict, fd)
    return config_path


280
def create_deepspeed_args():
281
282
283
    parser = argparse.ArgumentParser()
    args = parser.parse_args(args='')
    args.deepspeed = True
aiss's avatar
aiss committed
284
    if dist.is_initialized():
285
        # We assume up to one full node executing unit tests
aiss's avatar
aiss committed
286
287
        assert dist.get_world_size() <= get_accelerator().device_count()
        args.local_rank = dist.get_rank()
288
    return args
289
290
291
292
293
294
295


def args_from_dict(tmpdir, config_dict):
    args = create_deepspeed_args()
    config_path = create_config_from_dict(tmpdir, config_dict)
    args.deepspeed_config = config_path
    return args