forked from pfnet/pytorch-pfn-extras
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ignite-mnist.py
173 lines (155 loc) · 4.83 KB
/
ignite-mnist.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
from argparse import ArgumentParser
import pytorch_pfn_extras as ppe
import pytorch_pfn_extras.training.extensions as extensions
import torch
import torch.nn.functional as F
from ignite.engine import (
Events,
create_supervised_evaluator,
create_supervised_trainer,
)
from ignite.metrics import Accuracy, Loss
from torch import nn
from torch.optim import SGD
from torch.utils.data import DataLoader
from torchvision.datasets import MNIST
from torchvision.transforms import Compose, Normalize, ToTensor
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.flatten(start_dim=1)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
return F.log_softmax(x, dim=-1)
def get_data_loaders(train_batch_size, val_batch_size):
data_transform = Compose([ToTensor(), Normalize((0.1307,), (0.3081,))])
train_loader = DataLoader(
MNIST(
download=True, root="../data", transform=data_transform, train=True
),
batch_size=train_batch_size,
shuffle=True,
)
val_loader = DataLoader(
MNIST(
download=False,
root="../data",
transform=data_transform,
train=False,
),
batch_size=val_batch_size,
shuffle=False,
)
return train_loader, val_loader
def run(train_batch_size, val_batch_size, epochs, lr, momentum, log_interval):
train_loader, val_loader = get_data_loaders(
train_batch_size, val_batch_size
)
model = Net()
device = "cpu"
if torch.cuda.is_available():
device = "cuda:0"
model = model.to(device)
optimizer = SGD(model.parameters(), lr=lr, momentum=momentum)
optimizer.step()
trainer = create_supervised_trainer(
model, optimizer, F.nll_loss, device=device
)
evaluator = create_supervised_evaluator(
model,
metrics={"acc": Accuracy(), "loss": Loss(F.nll_loss)},
device=device,
)
# manager.extend(...) also works
my_extensions = [
extensions.LogReport(),
extensions.ProgressBar(),
extensions.observe_lr(optimizer=optimizer),
extensions.ParameterStatistics(model, prefix="model"),
extensions.VariableStatisticsPlot(model),
extensions.snapshot(),
extensions.IgniteEvaluator(
evaluator, val_loader, model, progress_bar=True
),
extensions.PlotReport(["train/loss"], "epoch", filename="loss.png"),
extensions.PrintReport(
[
"epoch",
"iteration",
"train/loss",
"lr",
"model/fc2.bias/grad/min",
"val/loss",
"val/acc",
]
),
]
models = {"main": model}
optimizers = {"main": optimizer}
manager = ppe.training.IgniteExtensionsManager(
trainer, models, optimizers, args.epochs, extensions=my_extensions
)
# Lets load the snapshot
if args.snapshot is not None:
state = torch.load(args.snapshot)
manager.load_state_dict(state)
@trainer.on(Events.ITERATION_COMPLETED)
def report_loss(engine):
ppe.reporting.report({"train/loss": engine.state.output})
trainer.run(train_loader, max_epochs=epochs)
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument(
"--batch_size",
type=int,
default=64,
help="input batch size for training (default: 64)",
)
parser.add_argument(
"--val_batch_size",
type=int,
default=1000,
help="input batch size for validation (default: 1000)",
)
parser.add_argument(
"--epochs",
type=int,
default=10,
help="number of epochs to train (default: 10)",
)
parser.add_argument(
"--lr", type=float, default=0.01, help="learning rate (default: 0.01)"
)
parser.add_argument(
"--momentum",
type=float,
default=0.5,
help="SGD momentum (default: 0.5)",
)
parser.add_argument(
"--log_interval",
type=int,
default=10,
help="how many batches to wait before logging " "training status",
)
parser.add_argument(
"--snapshot", type=str, default=None, help="path to snapshot file"
)
args = parser.parse_args()
run(
args.batch_size,
args.val_batch_size,
args.epochs,
args.lr,
args.momentum,
args.log_interval,
)