simple_net.py 1.55 KB
Newer Older
1
2
3
4
5
import torch
import torch.nn as nn
from colossalai.nn import CheckpointModule
from .utils.dummy_data_generator import DummyDataGenerator
from .registry import non_distributed_component_funcs
6
from colossalai.utils.cuda import get_current_device
7
8
9
10
11
12
13
14

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)
15
        self.embed = nn.Embedding(20, 4)
16
        self.proj1 = nn.Linear(4, 8)
17
        self.ln1 = nn.LayerNorm(8)
18
        self.proj2 = nn.Linear(8, 4)
19
        self.ln2 = nn.LayerNorm(4)
20
        self.classifier = nn.Linear(4, 4)
21
22

    def forward(self, x):
23
        x = self.embed(x)
24
        x = self.proj1(x)
25
        x = self.ln1(x)
26
        x = self.proj2(x)
27
        x = self.ln2(x)
28
        x = self.classifier(x)
29
30
31
        return x


32

33
34
35
class DummyDataLoader(DummyDataGenerator):

    def generate(self):
36
37
        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())
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
        return data, label


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

    def model_builder(checkpoint=True):
        return SimpleNet(checkpoint)

    trainloader = DummyDataLoader()
    testloader = DummyDataLoader()

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