-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.py
213 lines (187 loc) · 7.06 KB
/
config.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
from dataclasses import dataclass, asdict, field
import optuna
import yaml
import importlib
@dataclass
class EarlyStoppingConfig:
enabled: bool = False
patience: int = 10
mode: str = "min" # "min" or "max"
min_delta: float = 0.0001
@dataclass
class RunConfig:
project: str
device: str
seeds: list[int]
net: str
optimizer: str
scheduler: str
epochs: int
batch_size: int
net_config: dict[str, int]
optimizer_config: dict[str, int | float]
scheduler_config: dict[str, int | float]
early_stopping_config: EarlyStoppingConfig = field(
default_factory=lambda: EarlyStoppingConfig()
)
def __post_init__(self):
if isinstance(self.early_stopping_config, dict):
self.early_stopping_config = EarlyStoppingConfig(
**self.early_stopping_config
)
@classmethod
def from_yaml(cls, path: str):
with open(path, "r") as file:
config = yaml.safe_load(file)
return cls(**config)
def to_yaml(self, path: str):
with open(path, "w") as file:
yaml.dump(asdict(self), file, sort_keys=False)
def create_model(self):
module_name, class_name = self.net.rsplit(".", 1)
module = importlib.import_module(module_name)
model_class = getattr(module, class_name)
return model_class(self.net_config, device=self.device)
def create_optimizer(self, model):
module_name, class_name = self.optimizer.rsplit(".", 1)
module = importlib.import_module(module_name)
optimizer_class = getattr(module, class_name)
return optimizer_class(model.parameters(), **self.optimizer_config)
def create_scheduler(self, optimizer):
scheduler_module, scheduler_class = self.scheduler.rsplit(".", 1)
scheduler_module = importlib.import_module(scheduler_module)
scheduler_class = getattr(scheduler_module, scheduler_class)
return scheduler_class(optimizer, **self.scheduler_config)
def gen_group_name(self):
name = f"{self.net.split('.')[-1]}"
for k, v in self.net_config.items():
name += f"_{k[0]}_{v}"
name += f"_{abbreviate(self.optimizer.split('.')[-1])}"
for k, v in self.optimizer_config.items():
name += f"_{k[0]}_{v:.4e}" if isinstance(v, float) else f"_{k[0]}_{v}"
name += f"_{abbreviate(self.scheduler.split('.')[-1])}"
for k, v in self.scheduler_config.items():
name += f"_{k[0]}_{v:.4e}" if isinstance(v, float) else f"_{k[0]}_{v}"
return name
def gen_tags(self):
return [
self.net.split(".")[-1],
*[f"{k[0]}={v}" for k, v in self.net_config.items()],
self.optimizer.split(".")[-1],
self.scheduler.split(".")[-1],
]
def gen_config(self):
return asdict(self)
def default_run_config():
return RunConfig(
project="PyTorch_Template",
device="cpu",
seeds=[42],
net="MLP",
optimizer="torch.optim.adamw.AdamW",
scheduler="torch.optim.lr_scheduler.CosineAnnealingLR",
epochs=50,
batch_size=256,
net_config={
"nodes": 128,
"layers": 4,
},
optimizer_config={
"lr": 1e-3,
},
scheduler_config={
"T_max": 50,
"eta_min": 1e-5,
},
)
@dataclass
class OptimizeConfig:
study_name: str
trials: int
seed: int
metric: str
direction: str
sampler: dict = field(default_factory=dict)
pruner: dict = field(default_factory=dict)
search_space: dict = field(default_factory=dict)
@classmethod
def from_yaml(cls, path):
with open(path, "r") as file:
config = yaml.safe_load(file)
return cls(**config)
def to_yaml(self, path):
with open(path, "w") as file:
yaml.dump(asdict(self), file, sort_keys=False)
def _create_sampler(self):
module_name, class_name = self.sampler["name"].rsplit(".", 1)
module = importlib.import_module(module_name)
sampler_class = getattr(module, class_name)
sampler_kwargs = self.sampler.get("kwargs", {})
if class_name == "GridSampler":
sampler_kwargs["search_space"] = self.grid_search_space()
return sampler_class(**sampler_kwargs)
def _create_pruner(self):
if not self.pruner:
return None
module_name, class_name = self.pruner["name"].rsplit(".", 1)
module = importlib.import_module(module_name)
pruner_class = getattr(module, class_name)
pruner_kwargs = self.pruner.get("kwargs", {})
return pruner_class(**pruner_kwargs)
def create_study(self, project):
sampler = self._create_sampler()
study = {
"study_name": self.study_name,
"storage": f"sqlite:///{project}.db",
"sampler": sampler,
"direction": self.direction,
"load_if_exists": True,
}
pruner = self._create_pruner()
if pruner:
study["pruner"] = pruner
return optuna.create_study(**study)
def suggest_params(self, trial):
params = {}
for category, config in self.search_space.items():
params[category] = {}
for param, param_config in config.items():
if param_config["type"] == "int":
params[category][param] = trial.suggest_int(
f"{category}_{param}",
param_config["min"],
param_config["max"],
step=param_config.get("step", 1),
)
elif param_config["type"] == "float":
if param_config.get("log", False):
params[category][param] = trial.suggest_float(
f"{category}_{param}",
param_config["min"],
param_config["max"],
log=True,
)
else:
params[category][param] = trial.suggest_float(
f"{category}_{param}",
param_config["min"],
param_config["max"],
)
elif param_config["type"] == "categorical":
params[category][param] = trial.suggest_categorical(
f"{category}_{param}", param_config["choices"]
)
return params
def grid_search_space(self):
params = {}
for category, config in self.search_space.items():
for param, param_config in config.items():
if param_config["type"] == "categorical":
params[f"{category}_{param}"] = param_config["choices"]
else:
raise ValueError(
f"Unsupported grid search space type: {param_config['type']}"
)
return params
def abbreviate(s: str):
return "".join([w for w in s if w.isupper()])