forked from optuna/optuna-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pytorch_lightning_distributed.py
141 lines (111 loc) · 3.9 KB
/
pytorch_lightning_distributed.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
import os
import optuna
from optuna.integration.mlflow import MLflowCallback
import pytorch_lightning as pl
from pytorch_lightning import Callback
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import Adam
import torch.utils.data
from torchvision import datasets
from torchvision import transforms
PERCENT_VALID_EXAMPLES = 0.1
BATCHSIZE = 128
CLASSES = 10
EPOCHS = 5
DIR = os.getcwd()
MODEL_DIR = os.path.join(DIR, "result")
class MetricsCallback(Callback):
def __init__(self):
super().__init__()
self.metrics = []
def on_validation_end(self, trainer, pl_module):
self.metrics.append(trainer.callback_metrics)
def create_model(trial):
n_layers = trial.suggest_int("n_layers", 1, 3)
dropout = trial.suggest_float("dropout", 0.2, 0.5)
input_dim = 28 * 28
layers = []
for i in range(n_layers):
output_dim = int(trial.suggest_float("n_units_l{}".format(i), 4, 128))
layers.append(nn.Linear(input_dim, output_dim))
layers.append(nn.ReLU())
layers.append(nn.Dropout(dropout))
input_dim = output_dim
layers.append(nn.Linear(input_dim, CLASSES))
layers.append(nn.LogSoftmax(dim=1))
model = nn.Sequential(*layers)
return model
class LightningNet(pl.LightningModule):
def __init__(self, trial):
super().__init__()
self.model = create_model(trial)
def forward(self, data):
return self.model(data.view(-1, 28 * 28))
def training_step(self, batch, batch_nb):
data, target = batch
output = self.forward(data)
return {"loss": F.nll_loss(output, target)}
def validation_step(self, batch, batch_nb):
data, target = batch
output = self.forward(data)
pred = output.argmax(dim=1, keepdim=True)
accuracy = pred.eq(target.view_as(pred)).float().mean().item()
return {"batch_val_acc": accuracy}
def validation_epoch_end(self, outputs):
accuracy = sum(x["batch_val_acc"] for x in outputs) / len(outputs)
# Pass the accuracy to the `DictLogger` via the `'log'` key.
self.log("val_acc", accuracy)
def configure_optimizers(self):
return Adam(self.model.parameters())
def train_dataloader(self):
return torch.utils.data.DataLoader(
datasets.FashionMNIST(DIR, train=True, download=True, transform=transforms.ToTensor()),
batch_size=BATCHSIZE,
shuffle=True,
)
def val_dataloader(self):
return torch.utils.data.DataLoader(
datasets.FashionMNIST(
DIR, train=False, download=True, transform=transforms.ToTensor()
),
batch_size=BATCHSIZE,
shuffle=False,
)
def objective(trial):
# Clear clutter from previous Keras session graphs.
metrics_callback = MetricsCallback()
trainer = pl.Trainer(
logger=False,
limit_val_batches=PERCENT_VALID_EXAMPLES,
checkpoint_callback=False,
max_epochs=EPOCHS,
gpus=None,
callbacks=[metrics_callback],
)
model = LightningNet(trial)
trainer.fit(model)
return metrics_callback.metrics[-1]["val_acc"]
if __name__ == "__main__":
study = optuna.load_study(
study_name="k8s_mlflow",
storage="postgresql://{}:{}@postgres:5432/{}".format(
os.environ["POSTGRES_USER"],
os.environ["POSTGRES_PASSWORD"],
os.environ["POSTGRES_DB"],
),
)
study.optimize(
objective,
n_trials=100,
timeout=600,
callbacks=[MLflowCallback(tracking_uri="http://mlflow:5000/", metric_name="val_accuracy")],
)
print("Number of finished trials: {}".format(len(study.trials)))
print("Best trial:")
trial = study.best_trial
print(" Value: {}".format(trial.value))
print(" Params: ")
for key, value in trial.params.items():
print(" {}: {}".format(key, value))