forked from mosaicml/composer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustom_models.py
55 lines (44 loc) · 1.63 KB
/
custom_models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Example for training with an algorithm on a custom model."""
import torch
import torch.utils.data
from torchvision import datasets, transforms
import composer.models
from composer import Trainer
# Example algorithms to train with
from composer.algorithms import CutOut, LabelSmoothing
# Your custom model
class SimpleModel(composer.models.ComposerClassifier):
"""Your custom model."""
def __init__(self, num_hidden: int, num_classes: int):
module = torch.nn.Sequential(
torch.nn.Flatten(start_dim=1),
torch.nn.Linear(28 * 28, num_hidden),
torch.nn.Linear(num_hidden, num_classes),
)
self.num_classes = num_classes
super().__init__(module=module, num_classes=num_classes)
# Your custom train dataloader
train_dataloader = torch.utils.data.DataLoader(
dataset=datasets.MNIST('/datasets/', train=True, transform=transforms.ToTensor(), download=True),
drop_last=False,
shuffle=True,
batch_size=256,
)
# Your custom eval dataloader
eval_dataloader = torch.utils.data.DataLoader(
dataset=datasets.MNIST('/datasets/', train=False, transform=transforms.ToTensor()),
drop_last=False,
shuffle=False,
batch_size=256,
)
# Initialize Trainer with custom model, custom train and eval datasets, and algorithms to train with
trainer = Trainer(
model=SimpleModel(num_hidden=128, num_classes=10),
train_dataloader=train_dataloader,
eval_dataloader=eval_dataloader,
max_duration='3ep',
algorithms=[CutOut(num_holes=1, length=0.5), LabelSmoothing(0.1)],
)
trainer.fit()