chimera-ml 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- chimera_ml/__init__.py +11 -0
- chimera_ml/callbacks/__init__.py +19 -0
- chimera_ml/callbacks/_utils.py +64 -0
- chimera_ml/callbacks/base.py +50 -0
- chimera_ml/callbacks/checkpoint_callback.py +112 -0
- chimera_ml/callbacks/collect_predictions_callback.py +181 -0
- chimera_ml/callbacks/early_stopping_callback.py +93 -0
- chimera_ml/callbacks/plot_confusion_matrix_callback.py +257 -0
- chimera_ml/callbacks/snapshot_callback.py +58 -0
- chimera_ml/callbacks/telegram_notifier_callback.py +237 -0
- chimera_ml/cli.py +444 -0
- chimera_ml/core/__init__.py +29 -0
- chimera_ml/core/batch.py +58 -0
- chimera_ml/core/registry.py +53 -0
- chimera_ml/core/types.py +13 -0
- chimera_ml/data/__init__.py +11 -0
- chimera_ml/data/datamodule.py +85 -0
- chimera_ml/data/loader_utils.py +53 -0
- chimera_ml/data/masking_collate.py +241 -0
- chimera_ml/logging/__init__.py +5 -0
- chimera_ml/logging/base.py +38 -0
- chimera_ml/logging/console_file_logger.py +109 -0
- chimera_ml/logging/mlflow_logger.py +98 -0
- chimera_ml/logging/utils.py +57 -0
- chimera_ml/losses/__init__.py +16 -0
- chimera_ml/losses/base.py +12 -0
- chimera_ml/losses/ccc.py +86 -0
- chimera_ml/losses/classification.py +22 -0
- chimera_ml/losses/focal.py +71 -0
- chimera_ml/losses/multilabel.py +22 -0
- chimera_ml/losses/regression.py +37 -0
- chimera_ml/metrics/__init__.py +26 -0
- chimera_ml/metrics/_utils.py +35 -0
- chimera_ml/metrics/base.py +20 -0
- chimera_ml/metrics/confusion_matrix_metric.py +59 -0
- chimera_ml/metrics/prf_metric.py +116 -0
- chimera_ml/metrics/regression_metric.py +178 -0
- chimera_ml/models/__init__.py +13 -0
- chimera_ml/models/base.py +14 -0
- chimera_ml/models/fusion.py +126 -0
- chimera_ml/models/gated_prediction_fusion.py +98 -0
- chimera_ml/models/gating.py +109 -0
- chimera_ml/plugins.py +41 -0
- chimera_ml/training/__init__.py +9 -0
- chimera_ml/training/builders.py +198 -0
- chimera_ml/training/cached_split_outputs.py +39 -0
- chimera_ml/training/config.py +86 -0
- chimera_ml/training/mixed_loader_utils.py +126 -0
- chimera_ml/training/optimizers.py +48 -0
- chimera_ml/training/schedulers.py +33 -0
- chimera_ml/training/trainer.py +643 -0
- chimera_ml/utils/__init__.py +1 -0
- chimera_ml/utils/entrypoints.py +45 -0
- chimera_ml/utils/seed.py +29 -0
- chimera_ml/utils/utils.py +33 -0
- chimera_ml-0.1.0.dist-info/METADATA +410 -0
- chimera_ml-0.1.0.dist-info/RECORD +60 -0
- chimera_ml-0.1.0.dist-info/WHEEL +4 -0
- chimera_ml-0.1.0.dist-info/entry_points.txt +4 -0
- chimera_ml-0.1.0.dist-info/licenses/LICENSE +21 -0
chimera_ml/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from chimera_ml.callbacks.base import BaseCallback
|
|
2
|
+
from chimera_ml.callbacks.checkpoint_callback import checkpoint_callback
|
|
3
|
+
from chimera_ml.callbacks.collect_predictions_callback import collect_predictions_callback
|
|
4
|
+
from chimera_ml.callbacks.early_stopping_callback import early_stopping_callback
|
|
5
|
+
from chimera_ml.callbacks.plot_confusion_matrix_callback import (
|
|
6
|
+
plot_confusion_matrix_callback,
|
|
7
|
+
)
|
|
8
|
+
from chimera_ml.callbacks.snapshot_callback import snapshot_callback
|
|
9
|
+
from chimera_ml.callbacks.telegram_notifier_callback import telegram_notifier_callback
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"BaseCallback",
|
|
13
|
+
"checkpoint_callback",
|
|
14
|
+
"collect_predictions_callback",
|
|
15
|
+
"early_stopping_callback",
|
|
16
|
+
"plot_confusion_matrix_callback",
|
|
17
|
+
"snapshot_callback",
|
|
18
|
+
"telegram_notifier_callback",
|
|
19
|
+
]
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
from collections.abc import Sequence
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from torch.utils.data import DataLoader
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def resolve_splits(
|
|
8
|
+
trainer: Any,
|
|
9
|
+
splits: Sequence[str] | None,
|
|
10
|
+
) -> list[tuple[str, DataLoader | None]]:
|
|
11
|
+
"""Resolve split selectors into concrete `(split_name, loader)` pairs."""
|
|
12
|
+
out: list[tuple[str, DataLoader | None]] = []
|
|
13
|
+
seen: set[str] = set()
|
|
14
|
+
|
|
15
|
+
def add(name: str, loader: DataLoader | None) -> None:
|
|
16
|
+
if name and name not in seen:
|
|
17
|
+
seen.add(name)
|
|
18
|
+
out.append((name, loader))
|
|
19
|
+
|
|
20
|
+
train_loaders = getattr(trainer, "_train_loaders", None)
|
|
21
|
+
val_loaders = getattr(trainer, "_val_loaders", None)
|
|
22
|
+
test_loaders = getattr(trainer, "_test_loaders", None)
|
|
23
|
+
all_loaders = getattr(trainer, "_loaders", None)
|
|
24
|
+
|
|
25
|
+
selectors: list[str] = [splits] if isinstance(splits, str) else list(splits) if splits else ["val"]
|
|
26
|
+
|
|
27
|
+
for split in selectors:
|
|
28
|
+
if split == "train":
|
|
29
|
+
if isinstance(train_loaders, dict) and train_loaders:
|
|
30
|
+
for name, loader in train_loaders.items():
|
|
31
|
+
add(name, loader)
|
|
32
|
+
elif isinstance(all_loaders, dict):
|
|
33
|
+
add("train", all_loaders.get("train"))
|
|
34
|
+
continue
|
|
35
|
+
|
|
36
|
+
if split == "val":
|
|
37
|
+
if isinstance(val_loaders, dict) and val_loaders:
|
|
38
|
+
for name, loader in val_loaders.items():
|
|
39
|
+
add(name, loader)
|
|
40
|
+
elif isinstance(all_loaders, dict):
|
|
41
|
+
add("val", all_loaders.get("val"))
|
|
42
|
+
continue
|
|
43
|
+
|
|
44
|
+
if split == "test":
|
|
45
|
+
if isinstance(test_loaders, dict) and test_loaders:
|
|
46
|
+
for name, loader in test_loaders.items():
|
|
47
|
+
add(name, loader)
|
|
48
|
+
elif isinstance(all_loaders, dict):
|
|
49
|
+
add("test", all_loaders.get("test"))
|
|
50
|
+
continue
|
|
51
|
+
|
|
52
|
+
loader = None
|
|
53
|
+
if isinstance(train_loaders, dict) and split in train_loaders:
|
|
54
|
+
loader = train_loaders[split]
|
|
55
|
+
elif isinstance(val_loaders, dict) and split in val_loaders:
|
|
56
|
+
loader = val_loaders[split]
|
|
57
|
+
elif isinstance(test_loaders, dict) and split in test_loaders:
|
|
58
|
+
loader = test_loaders[split]
|
|
59
|
+
elif isinstance(all_loaders, dict) and split in all_loaders:
|
|
60
|
+
loader = all_loaders[split]
|
|
61
|
+
|
|
62
|
+
add(split, loader)
|
|
63
|
+
|
|
64
|
+
return out
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class BaseCallback:
|
|
5
|
+
"""Base callback interface for the trainer lifecycle."""
|
|
6
|
+
|
|
7
|
+
@classmethod
|
|
8
|
+
def _log(cls, trainer: Any, level: str, message: str) -> None:
|
|
9
|
+
"""Get logger from trainer."""
|
|
10
|
+
logger = getattr(trainer, "logger", None)
|
|
11
|
+
if logger is not None and hasattr(logger, level):
|
|
12
|
+
getattr(logger, level)(message)
|
|
13
|
+
return
|
|
14
|
+
|
|
15
|
+
print(message)
|
|
16
|
+
|
|
17
|
+
@classmethod
|
|
18
|
+
def _info(cls, trainer: Any, message: str) -> None:
|
|
19
|
+
"""Log informational message with fallback to stdout."""
|
|
20
|
+
cls._log(trainer, "info", message)
|
|
21
|
+
|
|
22
|
+
@classmethod
|
|
23
|
+
def _warning(cls, trainer: Any, message: str) -> None:
|
|
24
|
+
"""Log warning message with fallback to stdout."""
|
|
25
|
+
cls._log(trainer, "warning", message)
|
|
26
|
+
|
|
27
|
+
@classmethod
|
|
28
|
+
def _error(cls, trainer: Any, message: str) -> None:
|
|
29
|
+
"""Log error message with fallback to stdout."""
|
|
30
|
+
cls._log(trainer, "error", message)
|
|
31
|
+
|
|
32
|
+
def on_fit_start(self, trainer: Any) -> None:
|
|
33
|
+
"""Called once before the fit/eval loop starts."""
|
|
34
|
+
return
|
|
35
|
+
|
|
36
|
+
def on_epoch_start(self, trainer: Any, epoch: int) -> None:
|
|
37
|
+
"""Called at the beginning of each epoch."""
|
|
38
|
+
return
|
|
39
|
+
|
|
40
|
+
def on_batch_end(self, trainer: Any, global_step: int, logs: dict[str, float]) -> None:
|
|
41
|
+
"""Called after each training batch."""
|
|
42
|
+
return
|
|
43
|
+
|
|
44
|
+
def on_epoch_end(self, trainer: Any, epoch: int, logs: dict[str, float]) -> None:
|
|
45
|
+
"""Called after each epoch with aggregated logs."""
|
|
46
|
+
return
|
|
47
|
+
|
|
48
|
+
def on_fit_end(self, trainer: Any) -> None:
|
|
49
|
+
"""Called once after the fit/eval loop ends."""
|
|
50
|
+
return
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
|
|
7
|
+
from chimera_ml.callbacks.base import BaseCallback
|
|
8
|
+
from chimera_ml.core.registry import CALLBACKS
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class CheckpointCallback(BaseCallback):
|
|
13
|
+
"""Save model checkpoints based on a monitored metric."""
|
|
14
|
+
|
|
15
|
+
log_path: str = "logs"
|
|
16
|
+
experiment_name: str = "chimera"
|
|
17
|
+
run_name: str = "train"
|
|
18
|
+
monitor: str = "val/loss"
|
|
19
|
+
mode: str = "min" # "min" or "max"
|
|
20
|
+
save_top_k: int = 1
|
|
21
|
+
save_last: bool = True
|
|
22
|
+
filename_template: str = "epoch={epoch}_step={step}_{monitor}={value:.4f}.pt"
|
|
23
|
+
|
|
24
|
+
def __post_init__(self) -> None:
|
|
25
|
+
self._best: float | None = None
|
|
26
|
+
self._saved: list[Path] = []
|
|
27
|
+
self._resolved_dirpath: Path | None = None
|
|
28
|
+
|
|
29
|
+
if self.mode not in ("min", "max"):
|
|
30
|
+
raise ValueError("mode must be 'min' or 'max'")
|
|
31
|
+
|
|
32
|
+
def on_fit_start(self, trainer: Any) -> None:
|
|
33
|
+
"""Prepare checkpoint directory before the run starts."""
|
|
34
|
+
dirpath = Path(self.log_path) / self.experiment_name / self.run_name / "checkpoints"
|
|
35
|
+
dirpath.mkdir(parents=True, exist_ok=True)
|
|
36
|
+
self._resolved_dirpath = dirpath
|
|
37
|
+
|
|
38
|
+
def _is_better(self, current: float, best: float) -> bool:
|
|
39
|
+
return current < best if self.mode == "min" else current > best
|
|
40
|
+
|
|
41
|
+
def _sort_key(self, path: Path) -> float:
|
|
42
|
+
return path.stat().st_mtime
|
|
43
|
+
|
|
44
|
+
def _save(self, trainer: Any, epoch: int, step: int, monitor_value: float, is_last: bool = False) -> Path:
|
|
45
|
+
"""Serialize model/optimizer (and scheduler when available) to disk."""
|
|
46
|
+
if self._resolved_dirpath is None:
|
|
47
|
+
self.on_fit_start(trainer)
|
|
48
|
+
|
|
49
|
+
payload = {
|
|
50
|
+
"epoch": epoch,
|
|
51
|
+
"global_step": step,
|
|
52
|
+
"model_state_dict": trainer.model.state_dict(),
|
|
53
|
+
"optimizer_state_dict": trainer.optimizer.state_dict(),
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if trainer.scheduler is not None:
|
|
57
|
+
payload["scheduler_state_dict"] = trainer.scheduler.state_dict()
|
|
58
|
+
|
|
59
|
+
name = (
|
|
60
|
+
"last.pt"
|
|
61
|
+
if is_last
|
|
62
|
+
else self.filename_template.format(
|
|
63
|
+
epoch=epoch,
|
|
64
|
+
step=step,
|
|
65
|
+
monitor=self.monitor.replace("/", "_"),
|
|
66
|
+
value=monitor_value,
|
|
67
|
+
)
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
assert self._resolved_dirpath is not None
|
|
71
|
+
path = self._resolved_dirpath / name
|
|
72
|
+
torch.save(payload, path)
|
|
73
|
+
return path
|
|
74
|
+
|
|
75
|
+
def on_epoch_end(self, trainer: Any, epoch: int, logs: dict[str, float]) -> None:
|
|
76
|
+
"""Optionally save last checkpoint and maintain top-k best checkpoints."""
|
|
77
|
+
step = trainer.global_step
|
|
78
|
+
|
|
79
|
+
if self.save_last:
|
|
80
|
+
self._save(trainer, epoch=epoch, step=step, monitor_value=float("nan"), is_last=True)
|
|
81
|
+
|
|
82
|
+
if self.monitor not in logs:
|
|
83
|
+
available = ", ".join(sorted(logs.keys()))
|
|
84
|
+
self._warning(
|
|
85
|
+
trainer, f"[CheckpointCallback] monitor='{self.monitor}' not found in logs. Available keys: {available}"
|
|
86
|
+
)
|
|
87
|
+
return
|
|
88
|
+
|
|
89
|
+
current = float(logs[self.monitor])
|
|
90
|
+
if self._best is None:
|
|
91
|
+
self._best = current
|
|
92
|
+
p = self._save(trainer, epoch, step, current, is_last=False)
|
|
93
|
+
self._saved.append(p)
|
|
94
|
+
return
|
|
95
|
+
|
|
96
|
+
if self._is_better(current, self._best):
|
|
97
|
+
self._best = current
|
|
98
|
+
p = self._save(trainer, epoch, step, current, is_last=False)
|
|
99
|
+
self._saved.append(p)
|
|
100
|
+
|
|
101
|
+
if self.save_top_k > 0 and len(self._saved) > self.save_top_k:
|
|
102
|
+
self._saved.sort(key=self._sort_key)
|
|
103
|
+
while len(self._saved) > self.save_top_k:
|
|
104
|
+
to_remove = self._saved.pop(0)
|
|
105
|
+
if to_remove.exists() and to_remove.name != "last.pt":
|
|
106
|
+
to_remove.unlink(missing_ok=True)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@CALLBACKS.register("checkpoint_callback")
|
|
110
|
+
def checkpoint_callback(**params):
|
|
111
|
+
"""Registry factory for :class:`CheckpointCallback`."""
|
|
112
|
+
return CheckpointCallback(**params)
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
import io
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Any, Literal
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
from torch.utils.data import DataLoader
|
|
8
|
+
|
|
9
|
+
from chimera_ml.callbacks._utils import resolve_splits
|
|
10
|
+
from chimera_ml.callbacks.base import BaseCallback
|
|
11
|
+
from chimera_ml.core.registry import CALLBACKS
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class CollectPredictionsCallback(BaseCallback):
|
|
16
|
+
"""Log per-sample predictions as CSV artifacts to MLflow.
|
|
17
|
+
|
|
18
|
+
`splits` supports:
|
|
19
|
+
- "val" -> all validation splits (val_loaders dict, else "val")
|
|
20
|
+
- "test" -> all test splits (test_loaders dict, else "test")
|
|
21
|
+
- "train" -> train split
|
|
22
|
+
- any other string -> exact split name (searched in val/test loader dicts)
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
splits: list[str] = field(default_factory=lambda: ["val"])
|
|
26
|
+
artifact_path: str = "predictions"
|
|
27
|
+
filename_template: str = "preds_epoch_{epoch}.csv"
|
|
28
|
+
include_probs: bool = True
|
|
29
|
+
task: Literal["regression", "classification"] = "regression"
|
|
30
|
+
|
|
31
|
+
def on_fit_start(self, trainer: Any) -> None:
|
|
32
|
+
"""Ensure prediction cache collection is enabled for validation/evaluation."""
|
|
33
|
+
trainer.config.collect_cache = True
|
|
34
|
+
|
|
35
|
+
def on_epoch_end(self, trainer: Any, epoch: int, logs: dict[str, float]) -> None:
|
|
36
|
+
"""Export cached predictions to CSV and attach them as MLflow artifacts."""
|
|
37
|
+
logger = getattr(trainer, "mlflow_logger", None)
|
|
38
|
+
if logger is None:
|
|
39
|
+
return
|
|
40
|
+
|
|
41
|
+
for split_name, loader in self._resolve_splits(trainer):
|
|
42
|
+
cached = trainer.get_cached_split_outputs(split_name)
|
|
43
|
+
if cached is None:
|
|
44
|
+
if loader is None:
|
|
45
|
+
continue
|
|
46
|
+
|
|
47
|
+
predict_fn = getattr(trainer, "predict", None)
|
|
48
|
+
if not callable(predict_fn):
|
|
49
|
+
self._warning(
|
|
50
|
+
trainer,
|
|
51
|
+
f"[MLflowPredictionsCallback] No cached predictions for split '{split_name}' "
|
|
52
|
+
"and trainer.predict(...) is not available. Skipping export.",
|
|
53
|
+
)
|
|
54
|
+
continue
|
|
55
|
+
|
|
56
|
+
cached = predict_fn(loader, split=split_name)
|
|
57
|
+
|
|
58
|
+
preds = getattr(cached, "preds", None)
|
|
59
|
+
if preds is None or self._numel(preds) == 0:
|
|
60
|
+
continue
|
|
61
|
+
|
|
62
|
+
targets = getattr(cached, "targets", None)
|
|
63
|
+
metas = getattr(cached, "sample_meta", None)
|
|
64
|
+
|
|
65
|
+
n = self._batch_size(preds)
|
|
66
|
+
ids = self._extract_ids(metas, n)
|
|
67
|
+
|
|
68
|
+
rows = self._build_rows(preds, targets, ids)
|
|
69
|
+
if not rows:
|
|
70
|
+
continue
|
|
71
|
+
|
|
72
|
+
data = self._rows_to_csv_bytes(rows)
|
|
73
|
+
logger.log_artifact_bytes(
|
|
74
|
+
data,
|
|
75
|
+
artifact_path=f"{self.artifact_path}/{split_name}",
|
|
76
|
+
filename=self.filename_template.format(epoch=epoch),
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
def _resolve_splits(self, trainer: Any) -> list[tuple[str, DataLoader | None]]:
|
|
80
|
+
"""Resolve configured split selectors into concrete (name, loader) pairs."""
|
|
81
|
+
return resolve_splits(trainer, self.splits)
|
|
82
|
+
|
|
83
|
+
@staticmethod
|
|
84
|
+
def _numel(x: torch.Tensor | list[torch.Tensor]) -> int:
|
|
85
|
+
"""Return total number of stored elements for tensor or ragged chunks."""
|
|
86
|
+
if torch.is_tensor(x):
|
|
87
|
+
return int(x.numel())
|
|
88
|
+
|
|
89
|
+
return int(sum(int(t.numel()) for t in x))
|
|
90
|
+
|
|
91
|
+
@staticmethod
|
|
92
|
+
def _batch_size(x: torch.Tensor | list[torch.Tensor]) -> int:
|
|
93
|
+
"""Return total batch size across tensor or ragged chunks."""
|
|
94
|
+
if torch.is_tensor(x):
|
|
95
|
+
return int(x.shape[0])
|
|
96
|
+
|
|
97
|
+
return int(sum(int(t.shape[0]) for t in x))
|
|
98
|
+
|
|
99
|
+
@staticmethod
|
|
100
|
+
def _iter_samples(x: torch.Tensor | list[torch.Tensor]) -> list[torch.Tensor]:
|
|
101
|
+
"""Flatten cache container into a list of per-sample tensors."""
|
|
102
|
+
if torch.is_tensor(x):
|
|
103
|
+
return [x[i] for i in range(int(x.shape[0]))]
|
|
104
|
+
|
|
105
|
+
out: list[torch.Tensor] = []
|
|
106
|
+
for chunk in x:
|
|
107
|
+
out.extend(chunk[i] for i in range(int(chunk.shape[0])))
|
|
108
|
+
|
|
109
|
+
return out
|
|
110
|
+
|
|
111
|
+
@staticmethod
|
|
112
|
+
def _extract_ids(metas: Any, n: int) -> list[str | None] | None:
|
|
113
|
+
"""Extract optional sample IDs from cached metadata."""
|
|
114
|
+
if isinstance(metas, list):
|
|
115
|
+
return [m.get("id") if isinstance(m, dict) else None for m in metas[:n]]
|
|
116
|
+
|
|
117
|
+
return None
|
|
118
|
+
|
|
119
|
+
def _build_rows(
|
|
120
|
+
self,
|
|
121
|
+
preds: torch.Tensor | list[torch.Tensor],
|
|
122
|
+
targets: torch.Tensor | list[torch.Tensor] | None,
|
|
123
|
+
ids: list[str | None] | None,
|
|
124
|
+
) -> list[dict[str, object]]:
|
|
125
|
+
"""Build CSV-ready row dictionaries for regression/classification tasks."""
|
|
126
|
+
pred_samples = self._iter_samples(preds)
|
|
127
|
+
target_samples = self._iter_samples(targets) if targets is not None else None
|
|
128
|
+
n = len(pred_samples)
|
|
129
|
+
|
|
130
|
+
if self.task == "classification":
|
|
131
|
+
rows = []
|
|
132
|
+
for i in range(n):
|
|
133
|
+
logits = pred_samples[i].view(-1)
|
|
134
|
+
pred_class = int(torch.argmax(logits).item())
|
|
135
|
+
row = {
|
|
136
|
+
"id": ids[i] if ids else None,
|
|
137
|
+
"pred_class": pred_class,
|
|
138
|
+
"target": int(target_samples[i].item())
|
|
139
|
+
if target_samples is not None and target_samples[i].numel() == 1
|
|
140
|
+
else None,
|
|
141
|
+
}
|
|
142
|
+
if self.include_probs:
|
|
143
|
+
probs = torch.softmax(logits, dim=-1)
|
|
144
|
+
for c in range(int(probs.shape[0])):
|
|
145
|
+
row[f"prob_{c}"] = float(probs[c].item())
|
|
146
|
+
|
|
147
|
+
rows.append(row)
|
|
148
|
+
|
|
149
|
+
return rows
|
|
150
|
+
|
|
151
|
+
rows = []
|
|
152
|
+
for i in range(n):
|
|
153
|
+
pred_flat = pred_samples[i].reshape(-1)
|
|
154
|
+
row = {"id": ids[i] if ids else None}
|
|
155
|
+
for j in range(int(pred_flat.shape[0])):
|
|
156
|
+
row[f"pred_{j}"] = float(pred_flat[j].item())
|
|
157
|
+
|
|
158
|
+
if target_samples is not None:
|
|
159
|
+
targ_flat = target_samples[i].reshape(-1)
|
|
160
|
+
for j in range(int(targ_flat.shape[0])):
|
|
161
|
+
row[f"target_{j}"] = float(targ_flat[j].item())
|
|
162
|
+
|
|
163
|
+
rows.append(row)
|
|
164
|
+
|
|
165
|
+
return rows
|
|
166
|
+
|
|
167
|
+
@staticmethod
|
|
168
|
+
def _rows_to_csv_bytes(rows: list[dict[str, object]]) -> bytes:
|
|
169
|
+
"""Serialize row dictionaries into UTF-8 CSV bytes."""
|
|
170
|
+
buf = io.StringIO()
|
|
171
|
+
fieldnames = sorted({k for row in rows for k in row})
|
|
172
|
+
w = csv.DictWriter(buf, fieldnames=fieldnames)
|
|
173
|
+
w.writeheader()
|
|
174
|
+
w.writerows(rows)
|
|
175
|
+
return buf.getvalue().encode("utf-8")
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@CALLBACKS.register("collect_predictions_callback")
|
|
179
|
+
def collect_predictions_callback(**params):
|
|
180
|
+
"""Registry factory for :class:`CollectPredictionsCallback`."""
|
|
181
|
+
return CollectPredictionsCallback(**params)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from chimera_ml.callbacks.base import BaseCallback
|
|
5
|
+
from chimera_ml.core.registry import CALLBACKS
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass
|
|
9
|
+
class EarlyStoppingCallback(BaseCallback):
|
|
10
|
+
"""Stop training when monitored metric stops improving."""
|
|
11
|
+
|
|
12
|
+
monitor: str = "val/loss"
|
|
13
|
+
mode: str = "min" # "min" or "max"
|
|
14
|
+
patience: int = 10
|
|
15
|
+
min_delta: float = 0.0
|
|
16
|
+
|
|
17
|
+
def __post_init__(self) -> None:
|
|
18
|
+
self._best: float | None = None
|
|
19
|
+
self._bad_epochs = 0
|
|
20
|
+
self._should_stop = False
|
|
21
|
+
self._countdown = self.patience
|
|
22
|
+
|
|
23
|
+
if self.mode not in ("min", "max"):
|
|
24
|
+
raise ValueError("mode must be 'min' or 'max'")
|
|
25
|
+
|
|
26
|
+
if self.patience < 1:
|
|
27
|
+
raise ValueError("patience must be >= 1")
|
|
28
|
+
|
|
29
|
+
def _is_improvement(self, current: float, best: float) -> bool:
|
|
30
|
+
"""Return True if current metric improves beyond `min_delta`."""
|
|
31
|
+
if self.mode == "min":
|
|
32
|
+
return current < (best - self.min_delta)
|
|
33
|
+
|
|
34
|
+
return current > (best + self.min_delta)
|
|
35
|
+
|
|
36
|
+
def on_epoch_end(self, trainer: Any, epoch: int, logs: dict[str, float]) -> None:
|
|
37
|
+
"""Update patience state and request early stop when needed."""
|
|
38
|
+
if self.monitor not in logs:
|
|
39
|
+
available = ", ".join(sorted(logs.keys()))
|
|
40
|
+
self._warning(
|
|
41
|
+
trainer,
|
|
42
|
+
f"[EarlyStoppingCallback] monitor='{self.monitor}' not found in logs. Available keys: {available}",
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
return
|
|
46
|
+
|
|
47
|
+
current = float(logs[self.monitor])
|
|
48
|
+
if self._best is None:
|
|
49
|
+
self._best = current
|
|
50
|
+
self._bad_epochs = 0
|
|
51
|
+
self._countdown = self.patience
|
|
52
|
+
self._info(
|
|
53
|
+
trainer,
|
|
54
|
+
f"[EarlyStoppingCallback] epoch={epoch} {self.monitor}={current:.6f} "
|
|
55
|
+
f"(best init). Countdown: {self._countdown}",
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
return
|
|
59
|
+
|
|
60
|
+
if self._is_improvement(current, self._best):
|
|
61
|
+
self._best = current
|
|
62
|
+
self._bad_epochs = 0
|
|
63
|
+
self._countdown = self.patience
|
|
64
|
+
self._info(
|
|
65
|
+
trainer,
|
|
66
|
+
f"[EarlyStoppingCallback] epoch={epoch} {self.monitor}={current:.6f} "
|
|
67
|
+
f"(improved). Reset countdown to {self._countdown}",
|
|
68
|
+
)
|
|
69
|
+
else:
|
|
70
|
+
self._bad_epochs += 1
|
|
71
|
+
self._countdown = max(0, self.patience - self._bad_epochs)
|
|
72
|
+
|
|
73
|
+
self._info(
|
|
74
|
+
trainer,
|
|
75
|
+
f"[EarlyStoppingCallback] epoch={epoch} {self.monitor}={current:.6f} "
|
|
76
|
+
f"(no improvement). Bad epochs: {self._bad_epochs}/{self.patience}. "
|
|
77
|
+
f"Countdown: {self._countdown}",
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
if self._bad_epochs >= self.patience:
|
|
81
|
+
self._should_stop = True
|
|
82
|
+
trainer.stop_training = True
|
|
83
|
+
self._info(
|
|
84
|
+
trainer,
|
|
85
|
+
f"[EarlyStoppingCallback] Stopping: no improvement in '{self.monitor}' "
|
|
86
|
+
f"for {self.patience} epochs. Best={self._best:.6f}, last={current:.6f}",
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@CALLBACKS.register("early_stopping_callback")
|
|
91
|
+
def early_stopping_callback(**params):
|
|
92
|
+
"""Registry factory for :class:`EarlyStoppingCallback`."""
|
|
93
|
+
return EarlyStoppingCallback(**params)
|