/
run-with-skorch.py
67 lines (53 loc) · 1.76 KB
/
run-with-skorch.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
import numpy as np
import torch
from accelerate import Accelerator
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_validate
from torch import nn
from torch.distributed import TCPStore
from skorch import NeuralNetClassifier
from skorch.hf import AccelerateMixin
from skorch.history import DistributedHistory
class MyModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.dense0 = nn.Linear(100, 2)
self.nonlin = nn.LogSoftmax(dim=-1)
def forward(self, X):
X = self.dense0(X)
X = self.nonlin(X)
return X
# make use of accelerate by creating a class with the AccelerateMixin
class AcceleratedNeuralNetClassifier(AccelerateMixin, NeuralNetClassifier):
pass
def main():
X, y = make_classification(10000, n_features=100, n_informative=50, random_state=0)
X = X.astype(np.float32)
accelerator = Accelerator()
# use history class that works in distributed setting
# see https://skorch.readthedocs.io/en/latest/user/history.html#distributed-history
is_master = accelerator.is_main_process
world_size = accelerator.num_processes
rank = accelerator.local_process_index
store = TCPStore(
"127.0.0.1", port=8080, world_size=world_size, is_master=is_master)
dist_history = DistributedHistory(
store=store, rank=rank, world_size=world_size)
model = AcceleratedNeuralNetClassifier(
MyModule,
criterion=nn.CrossEntropyLoss,
accelerator=accelerator,
max_epochs=3,
lr=0.001,
history=dist_history,
)
cross_validate(
model,
X,
y,
cv=2,
scoring="average_precision",
error_score="raise",
)
if __name__ == '__main__':
main()