simple_net.py 1.55 KB
Newer Older
1
2
import torch
import torch.nn as nn
HELSON's avatar
HELSON committed
3

4
from colossalai.nn import CheckpointModule
5
from colossalai.utils.cuda import get_current_device
6

HELSON's avatar
HELSON committed
7
8
9
10
from .registry import non_distributed_component_funcs
from .utils.dummy_data_generator import DummyDataGenerator


11
12
13
14
15
16
17
class SimpleNet(CheckpointModule):
    """
    In this no-leaf module, it has subordinate nn.modules and a nn.Parameter.
    """

    def __init__(self, checkpoint=False) -> None:
        super().__init__(checkpoint=checkpoint)
18
        self.embed = nn.Embedding(20, 4)
19
        self.proj1 = nn.Linear(4, 8)
20
        self.ln1 = nn.LayerNorm(8)
21
        self.proj2 = nn.Linear(8, 4)
22
        self.ln2 = nn.LayerNorm(4)
23
        self.classifier = nn.Linear(4, 4)
24
25

    def forward(self, x):
26
        x = self.embed(x)
27
        x = self.proj1(x)
28
        x = self.ln1(x)
29
        x = self.proj2(x)
30
        x = self.ln2(x)
31
        x = self.classifier(x)
32
33
34
35
36
37
        return x


class DummyDataLoader(DummyDataGenerator):

    def generate(self):
38
39
        data = torch.randint(low=0, high=20, size=(16,), device=get_current_device())
        label = torch.randint(low=0, high=2, size=(16,), device=get_current_device())
40
41
42
43
44
45
        return data, label


@non_distributed_component_funcs.register(name='simple_net')
def get_training_components():

HELSON's avatar
HELSON committed
46
    def model_builder(checkpoint=False):
47
48
49
50
51
52
53
54
        return SimpleNet(checkpoint)

    trainloader = DummyDataLoader()
    testloader = DummyDataLoader()

    criterion = torch.nn.CrossEntropyLoss()
    from colossalai.nn.optimizer import HybridAdam
    return model_builder, trainloader, testloader, HybridAdam, criterion