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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364 | class ResearchTrackerCallback(Callback):
"""Create and maintain a research-tracker run for a Lightning fit.
Names, configuration paths, logger metadata, and checkpoints are resolved
from standard Lightning interfaces. Explicit constructor values always take
precedence over inferred values.
"""
def __init__(
self,
store_root: str | Path | None = None,
model: str | None = None,
dataset: str | None = None,
dataset_version: str | None = None,
*,
config_path: str | Path | None = None,
config_filename: str = "config.yaml",
checkpoint_policy: CheckpointPolicy = "best_or_last",
logger_index: int = 0,
loader: str | None = None,
parent_run_id: str | None = None,
resume_mode: ResumeMode = "continue",
track_fast_dev_runs: bool = False,
) -> None:
super().__init__()
if Path(config_filename).name != config_filename:
raise ValueError("config_filename must be a filename, not a path")
if checkpoint_policy not in {"best", "last", "best_or_last", "none"}:
raise ValueError(f"Unknown checkpoint policy: {checkpoint_policy}")
if logger_index < 0:
raise ValueError("logger_index must be non-negative")
if resume_mode not in {"continue", "fork"}:
raise ValueError(f"Unknown resume mode: {resume_mode}")
self.store_root = Path(store_root) if store_root is not None else None
self.model = model
self.dataset = dataset
self.dataset_version = dataset_version
self.config_path = Path(config_path) if config_path is not None else None
self.config_filename = config_filename
self.checkpoint_policy = checkpoint_policy
self.logger_index = logger_index
self.loader = loader
self.parent_run_id = parent_run_id
self.resume_mode = resume_mode
self.track_fast_dev_runs = track_fast_dev_runs
self._store: ExperimentStore | None = None
self._run_id: str | None = None
self._checkpoint_run_id: str | None = None
self._tracking = False
@property
def store(self) -> ExperimentStore:
if self._store is None:
if self.store_root is None:
raise RuntimeError("Store root has not been resolved yet")
self._store = ExperimentStore(self.store_root)
return self._store
@property
def run_id(self) -> str:
if self._run_id is None:
raise RuntimeError("Run has not been created yet")
return self._run_id
def on_load_checkpoint(
self,
trainer: Trainer,
pl_module: LightningModule,
checkpoint: dict[str, Any],
) -> None:
metadata = checkpoint.get("research_tracker", {})
self._checkpoint_run_id = _text(metadata.get("run_id"))
def on_fit_start(self, trainer: Trainer, pl_module: LightningModule) -> None:
self._tracking = self.track_fast_dev_runs or not trainer.fast_dev_run
if not self._tracking:
return
run_id = None
if trainer.is_global_zero:
self._resolve_store_root(trainer)
run_id = self._start_or_resume_run(trainer, pl_module)
self._log_run_id(trainer, run_id)
self._run_id = self._broadcast(trainer, run_id)
def on_fit_end(self, trainer: Trainer, pl_module: LightningModule) -> None:
if not self._should_write(trainer):
return
checkpoint_path = self._resolve_checkpoint_path(trainer)
if checkpoint_path is not None:
self.store.add_checkpoint(checkpoint_path, self.run_id)
self.store.set_status(Status.COMPLETED, self.run_id)
def on_save_checkpoint(
self,
trainer: Trainer,
pl_module: LightningModule,
checkpoint: dict[str, Any],
) -> None:
if not self._tracking or self._run_id is None:
return
metadata = {
"run_id": self.run_id,
"model_class": _class_path(pl_module),
}
if trainer.datamodule is not None:
metadata["datamodule_class"] = _class_path(trainer.datamodule)
checkpoint["research_tracker"] = metadata
def on_exception(
self,
trainer: Trainer,
pl_module: LightningModule,
exception: BaseException,
) -> None:
if self._should_write(trainer):
self.store.set_status(Status.FAILED, self.run_id)
def _start_or_resume_run(
self,
trainer: Trainer,
pl_module: LightningModule,
) -> str:
if (
self.resume_mode == "continue"
and self._checkpoint_run_id is not None
and self._store_contains_run(self._checkpoint_run_id)
):
self.store.set_status(Status.RUNNING, self._checkpoint_run_id)
return self._checkpoint_run_id
datamodule = trainer.datamodule
logger = self._selected_logger(trainer)
tracking_backend, tracking_id, tracking_project = self._logger_metadata(logger)
config_path = self._resolve_config_path(trainer)
model_name = self.model or _text(getattr(pl_module, "model_name", None))
dataset_name = self.dataset
dataset_version = self.dataset_version
if datamodule is not None:
dataset_name = dataset_name or _text(
getattr(datamodule, "dataset_name", None)
)
dataset_version = dataset_version or _text(
getattr(datamodule, "dataset_version", None)
)
run = self.store.create_run(
model=model_name or pl_module.__class__.__name__,
model_class=_class_path(pl_module),
dataset=dataset_name
or (datamodule.__class__.__name__ if datamodule is not None else "unknown"),
config=config_path,
status=Status.RUNNING,
seed=self._resolve_seed(),
tracking_backend=tracking_backend,
tracking_id=tracking_id,
tracking_project=tracking_project,
loader=self.loader,
dataset_version=dataset_version,
datamodule_class=(
_class_path(datamodule) if datamodule is not None else None
),
parent_run_id=self.parent_run_id or self._checkpoint_run_id,
)
return run.run_id
def _resolve_store_root(self, trainer: Trainer) -> None:
if self.store_root is not None:
return
default_root = getattr(trainer, "default_root_dir", None)
if not isinstance(default_root, (str, PathLike)):
raise RuntimeError(
"Could not infer the store root from trainer.default_root_dir"
)
self.store_root = Path(default_root)
def _resolve_config_path(self, trainer: Trainer) -> Path:
if self.config_path is not None:
if not self.config_path.is_file():
raise FileNotFoundError(self.config_path)
return self.config_path
candidates: list[Path] = []
for logger in self._loggers(trainer):
experiment = getattr(logger, "experiment", None)
self._add_config_candidate(candidates, experiment, "dir")
self._add_config_candidate(candidates, logger, "log_dir")
self._add_config_candidate(candidates, logger, "save_dir")
self._add_config_candidate(candidates, trainer, "default_root_dir")
for candidate in candidates:
if candidate.is_file():
return candidate
searched = ", ".join(str(path) for path in candidates) or "<none>"
raise FileNotFoundError(
f"Could not find {self.config_filename}. Searched: {searched}. "
"Pass config_path explicitly when the configuration is stored elsewhere."
)
def _add_config_candidate(
self,
candidates: list[Path],
owner: object | None,
attribute: str,
) -> None:
if owner is None:
return
value = getattr(owner, attribute, None)
if callable(value):
value = value()
if not isinstance(value, (str, PathLike)):
return
candidate = Path(value) / self.config_filename
if candidate not in candidates:
candidates.append(candidate)
def _loggers(self, trainer: Trainer) -> list[Any]:
loggers = getattr(trainer, "loggers", None)
if loggers:
return list(loggers)
logger = getattr(trainer, "logger", None)
return [] if logger is None or logger is False else [logger]
def _selected_logger(self, trainer: Trainer) -> Any | None:
loggers = self._loggers(trainer)
if not loggers:
return None
if self.logger_index >= len(loggers):
raise IndexError(
f"logger_index={self.logger_index} but Trainer has "
f"{len(loggers)} logger(s)"
)
return loggers[self.logger_index]
def _logger_metadata(
self,
logger: Any | None,
) -> tuple[str | None, str | None, str | None]:
if logger is None:
return None, None, None
experiment = getattr(logger, "experiment", None)
tracking_id = _text(getattr(experiment, "id", None)) or _text(
getattr(logger, "version", None)
)
tracking_project = _text(getattr(experiment, "project", None)) or _text(
getattr(logger, "name", None)
)
return logger.__class__.__qualname__, tracking_id, tracking_project
def _log_run_id(self, trainer: Trainer, run_id: str) -> None:
logger = self._selected_logger(trainer)
if logger is None:
return
log_hyperparams = getattr(logger, "log_hyperparams", None)
if not callable(log_hyperparams):
return
try:
log_hyperparams({"research_run_id": run_id})
except Exception as error:
warnings.warn(
f"Could not add research_run_id to the logger: {error}",
RuntimeWarning,
stacklevel=2,
)
def _resolve_checkpoint_path(self, trainer: Trainer) -> Path | None:
if self.checkpoint_policy == "none":
return None
checkpoints = [
callback
for callback in trainer.callbacks
if isinstance(callback, ModelCheckpoint)
]
best = [
Path(callback.best_model_path)
for callback in checkpoints
if callback.best_model_path
]
last = [
Path(callback.last_model_path)
for callback in checkpoints
if callback.last_model_path
]
if self.checkpoint_policy == "best":
return best[0] if best else None
if self.checkpoint_policy == "last":
return last[0] if last else None
return (best or last or [None])[0]
def _store_contains_run(self, run_id: str) -> bool:
return self.store.has_run(run_id)
def _should_write(self, trainer: Trainer) -> bool:
return self._tracking and trainer.is_global_zero and self._run_id is not None
@staticmethod
def _resolve_seed() -> int | None:
seed = os.environ.get("PL_GLOBAL_SEED")
if seed is None:
return None
try:
return int(seed)
except ValueError:
warnings.warn(
f"Ignoring invalid PL_GLOBAL_SEED value: {seed!r}",
RuntimeWarning,
stacklevel=2,
)
return None
@staticmethod
def _broadcast(trainer: Trainer, run_id: str | None) -> str | None:
broadcast = getattr(getattr(trainer, "strategy", None), "broadcast", None)
return broadcast(run_id) if callable(broadcast) else run_id
|