torchstack64 0.3.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.
- torchstack64/__init__.py +101 -0
- torchstack64/artifacts/__init__.py +78 -0
- torchstack64/artifacts/bundle/__init__.py +50 -0
- torchstack64/artifacts/bundle/files.py +106 -0
- torchstack64/artifacts/bundle/folder.py +385 -0
- torchstack64/artifacts/bundle/tensors.py +75 -0
- torchstack64/artifacts/code/__init__.py +103 -0
- torchstack64/artifacts/code/copy.py +149 -0
- torchstack64/artifacts/code/importing.py +204 -0
- torchstack64/artifacts/code/inspection.py +351 -0
- torchstack64/artifacts/code/notebook.py +373 -0
- torchstack64/artifacts/code/objects.py +401 -0
- torchstack64/artifacts/loading.py +117 -0
- torchstack64/artifacts/manifest.py +220 -0
- torchstack64/artifacts/predictor/__init__.py +45 -0
- torchstack64/artifacts/predictor/bundle_predictor.py +193 -0
- torchstack64/artifacts/predictor/output_reading.py +96 -0
- torchstack64/artifacts/predictor/torch_classifier.py +106 -0
- torchstack64/artifacts/predictor/torch_predictor.py +247 -0
- torchstack64/artifacts/proofs/__init__.py +83 -0
- torchstack64/artifacts/proofs/answers.py +159 -0
- torchstack64/artifacts/proofs/example.py +248 -0
- torchstack64/artifacts/proofs/modules.py +260 -0
- torchstack64/artifacts/proofs/suite.py +560 -0
- torchstack64/artifacts/saving.py +461 -0
- torchstack64/artifacts/sources.py +166 -0
- torchstack64/callbacks/__init__.py +22 -0
- torchstack64/callbacks/base.py +43 -0
- torchstack64/callbacks/checkpointing.py +40 -0
- torchstack64/callbacks/history_plot.py +160 -0
- torchstack64/callbacks/mlflow_logger.py +217 -0
- torchstack64/callbacks/model_checks.py +295 -0
- torchstack64/callbacks/progress.py +132 -0
- torchstack64/callbacks/stack.py +85 -0
- torchstack64/core/__init__.py +59 -0
- torchstack64/core/errors.py +121 -0
- torchstack64/core/evaluation.py +52 -0
- torchstack64/core/extras.py +36 -0
- torchstack64/core/inference.py +42 -0
- torchstack64/core/labels.py +201 -0
- torchstack64/core/logging.py +110 -0
- torchstack64/data/__init__.py +10 -0
- torchstack64/data/base.py +256 -0
- torchstack64/data/labeled.py +128 -0
- torchstack64/devices/__init__.py +38 -0
- torchstack64/devices/hardware.py +43 -0
- torchstack64/devices/selection.py +82 -0
- torchstack64/metrics/__init__.py +21 -0
- torchstack64/metrics/classification.py +93 -0
- torchstack64/py.typed +0 -0
- torchstack64/training/__init__.py +83 -0
- torchstack64/training/config/__init__.py +17 -0
- torchstack64/training/config/fit.py +60 -0
- torchstack64/training/config/monitor.py +63 -0
- torchstack64/training/config/optim.py +49 -0
- torchstack64/training/config/params.py +55 -0
- torchstack64/training/config/search.py +49 -0
- torchstack64/training/results/__init__.py +19 -0
- torchstack64/training/results/fit.py +37 -0
- torchstack64/training/results/history.py +74 -0
- torchstack64/training/results/predictions.py +81 -0
- torchstack64/training/runtime/__init__.py +18 -0
- torchstack64/training/runtime/precision.py +139 -0
- torchstack64/training/runtime/randomness.py +142 -0
- torchstack64/training/runtime/runtime.py +75 -0
- torchstack64/training/runtime/transfer.py +49 -0
- torchstack64/training/runtime/weights.py +43 -0
- torchstack64/training/task/__init__.py +11 -0
- torchstack64/training/task/optim/__init__.py +9 -0
- torchstack64/training/task/optim/optimization.py +70 -0
- torchstack64/training/task/optim/schedules.py +27 -0
- torchstack64/training/task/protocol.py +58 -0
- torchstack64/training/task/supervised.py +113 -0
- torchstack64/training/trainer/__init__.py +8 -0
- torchstack64/training/trainer/adapters.py +122 -0
- torchstack64/training/trainer/contracts.py +81 -0
- torchstack64/training/trainer/hooks.py +47 -0
- torchstack64/training/trainer/meters.py +150 -0
- torchstack64/training/trainer/state.py +117 -0
- torchstack64/training/trainer/trainer.py +586 -0
- torchstack64/training/tuner/__init__.py +3 -0
- torchstack64/training/tuner/callback.py +38 -0
- torchstack64/training/tuner/space.py +82 -0
- torchstack64/training/tuner/tuner.py +137 -0
- torchstack64/utils/__init__.py +21 -0
- torchstack64/utils/logging.py +85 -0
- torchstack64/utils/mlflow.py +127 -0
- torchstack64-0.3.0.dist-info/METADATA +622 -0
- torchstack64-0.3.0.dist-info/RECORD +92 -0
- torchstack64-0.3.0.dist-info/WHEEL +5 -0
- torchstack64-0.3.0.dist-info/licenses/LICENSE +21 -0
- torchstack64-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# ruff: noqa: E402 (the imports below come after the check on purpose)
|
|
2
|
+
|
|
3
|
+
from torchstack64.core import require
|
|
4
|
+
|
|
5
|
+
require("torch", extra="training", purpose="torchstack64.training")
|
|
6
|
+
|
|
7
|
+
from torchstack64.training.config import (
|
|
8
|
+
FitConfig,
|
|
9
|
+
Monitor,
|
|
10
|
+
OptimConfig,
|
|
11
|
+
OptimizerType,
|
|
12
|
+
ParamValue,
|
|
13
|
+
Precision,
|
|
14
|
+
SearchConfig,
|
|
15
|
+
flatten_params,
|
|
16
|
+
)
|
|
17
|
+
from torchstack64.training.results import (
|
|
18
|
+
BestCheckpoint,
|
|
19
|
+
EpochResult,
|
|
20
|
+
Evaluation,
|
|
21
|
+
FitResult,
|
|
22
|
+
FitStatus,
|
|
23
|
+
OptimizationStepRecord,
|
|
24
|
+
Predictions,
|
|
25
|
+
TrainingHistory,
|
|
26
|
+
)
|
|
27
|
+
from torchstack64.training.runtime import (
|
|
28
|
+
Runtime,
|
|
29
|
+
Weights,
|
|
30
|
+
seed_everything,
|
|
31
|
+
to_device,
|
|
32
|
+
)
|
|
33
|
+
from torchstack64.training.task import (
|
|
34
|
+
EpochTask,
|
|
35
|
+
SupervisedTask,
|
|
36
|
+
Task,
|
|
37
|
+
build_optimization,
|
|
38
|
+
linear_warmup,
|
|
39
|
+
)
|
|
40
|
+
from torchstack64.training.trainer import (
|
|
41
|
+
FitPlan,
|
|
42
|
+
FitState,
|
|
43
|
+
Optimization,
|
|
44
|
+
Step,
|
|
45
|
+
StepContext,
|
|
46
|
+
Trainer,
|
|
47
|
+
)
|
|
48
|
+
from torchstack64.training.tuner import Tuner
|
|
49
|
+
|
|
50
|
+
__all__ = [
|
|
51
|
+
"BestCheckpoint",
|
|
52
|
+
"EpochResult",
|
|
53
|
+
"EpochTask",
|
|
54
|
+
"Evaluation",
|
|
55
|
+
"FitConfig",
|
|
56
|
+
"FitPlan",
|
|
57
|
+
"FitResult",
|
|
58
|
+
"FitState",
|
|
59
|
+
"FitStatus",
|
|
60
|
+
"Monitor",
|
|
61
|
+
"OptimConfig",
|
|
62
|
+
"Optimization",
|
|
63
|
+
"OptimizationStepRecord",
|
|
64
|
+
"OptimizerType",
|
|
65
|
+
"ParamValue",
|
|
66
|
+
"Precision",
|
|
67
|
+
"Predictions",
|
|
68
|
+
"Runtime",
|
|
69
|
+
"SearchConfig",
|
|
70
|
+
"Step",
|
|
71
|
+
"StepContext",
|
|
72
|
+
"SupervisedTask",
|
|
73
|
+
"Task",
|
|
74
|
+
"Trainer",
|
|
75
|
+
"TrainingHistory",
|
|
76
|
+
"Tuner",
|
|
77
|
+
"Weights",
|
|
78
|
+
"build_optimization",
|
|
79
|
+
"flatten_params",
|
|
80
|
+
"linear_warmup",
|
|
81
|
+
"seed_everything",
|
|
82
|
+
"to_device",
|
|
83
|
+
]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from torchstack64.training.config.fit import PRECISIONS, FitConfig, Precision
|
|
2
|
+
from torchstack64.training.config.monitor import Monitor
|
|
3
|
+
from torchstack64.training.config.optim import OptimConfig, OptimizerType
|
|
4
|
+
from torchstack64.training.config.params import ParamValue, flatten_params
|
|
5
|
+
from torchstack64.training.config.search import SearchConfig
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"PRECISIONS",
|
|
9
|
+
"FitConfig",
|
|
10
|
+
"Monitor",
|
|
11
|
+
"OptimConfig",
|
|
12
|
+
"OptimizerType",
|
|
13
|
+
"ParamValue",
|
|
14
|
+
"Precision",
|
|
15
|
+
"SearchConfig",
|
|
16
|
+
"flatten_params",
|
|
17
|
+
]
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
from torchstack64.devices import validate_device_name
|
|
8
|
+
from torchstack64.training.config.monitor import Monitor
|
|
9
|
+
|
|
10
|
+
Precision = Literal["fp32", "bf16", "fp16"]
|
|
11
|
+
PRECISIONS: tuple[str, ...] = ("fp32", "bf16", "fp16")
|
|
12
|
+
KeepBest = Literal["cpu", "device"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
16
|
+
class FitConfig:
|
|
17
|
+
"""How to run the loop.
|
|
18
|
+
|
|
19
|
+
- `epochs`: how many passes over the training data, at most.
|
|
20
|
+
- `monitor`: what picks the best epoch and decides early stopping (the validation loss by default).
|
|
21
|
+
- `early_stopping_patience`: epochs without improvement before stopping; `None` runs every epoch.
|
|
22
|
+
- `precision`: `"fp32"`, or mixed precision with `"bf16"` (no scaler needed) or `"fp16"` (with a
|
|
23
|
+
gradient scaler).
|
|
24
|
+
- `accumulate`: micro-batches whose gradients add up before each optimization step.
|
|
25
|
+
- `clip_grad_norm`: the largest gradient norm allowed before each optimization step; `None` does not clip.
|
|
26
|
+
- `device`: `None` uses the library's default device (`torchstack64.set_device`, `"auto"`).
|
|
27
|
+
- `seed`: seeds Python, NumPy and PyTorch at the start of the fit; `None` leaves them alone.
|
|
28
|
+
- `keep_best`: where the best epoch's weights wait for the end of the fit. `"cpu"` costs no GPU
|
|
29
|
+
memory; `"device"` keeps a second copy of the model on the GPU.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
epochs: int = 30
|
|
33
|
+
monitor: Monitor = field(default_factory=Monitor.val_loss)
|
|
34
|
+
early_stopping_patience: int | None = 5
|
|
35
|
+
precision: Precision = "fp32"
|
|
36
|
+
accumulate: int = 1
|
|
37
|
+
clip_grad_norm: float | None = None
|
|
38
|
+
device: str | None = None
|
|
39
|
+
seed: int | None = None
|
|
40
|
+
keep_best: KeepBest = "cpu"
|
|
41
|
+
|
|
42
|
+
def __post_init__(self) -> None:
|
|
43
|
+
if self.epochs < 1:
|
|
44
|
+
raise ValueError(f"epochs must be at least 1; got {self.epochs}")
|
|
45
|
+
if not isinstance(self.monitor, Monitor):
|
|
46
|
+
raise ValueError(f"monitor must be a Monitor; got {type(self.monitor).__name__}")
|
|
47
|
+
if self.early_stopping_patience is not None and self.early_stopping_patience < 1:
|
|
48
|
+
raise ValueError("early_stopping_patience must be at least 1, or None to never stop early")
|
|
49
|
+
if self.precision not in PRECISIONS:
|
|
50
|
+
raise ValueError(f"precision must be one of {PRECISIONS}; got {self.precision!r}")
|
|
51
|
+
if self.accumulate < 1:
|
|
52
|
+
raise ValueError(f"accumulate must be at least 1; got {self.accumulate}")
|
|
53
|
+
if self.clip_grad_norm is not None and not (
|
|
54
|
+
self.clip_grad_norm > 0 and math.isfinite(self.clip_grad_norm)
|
|
55
|
+
):
|
|
56
|
+
raise ValueError(f"clip_grad_norm must be a positive number, or None; got {self.clip_grad_norm}")
|
|
57
|
+
if self.device is not None:
|
|
58
|
+
validate_device_name(self.device)
|
|
59
|
+
if self.keep_best not in ("cpu", "device"):
|
|
60
|
+
raise ValueError(f"keep_best must be 'cpu' or 'device'; got {self.keep_best!r}")
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
from torchstack64.core import Metric
|
|
9
|
+
|
|
10
|
+
Mode = Literal["min", "max"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True, slots=True)
|
|
14
|
+
class Monitor:
|
|
15
|
+
"""The value watched at the end of each validation: the validation loss (`metric=None`) or a metric.
|
|
16
|
+
|
|
17
|
+
`output` picks which prediction feeds the metric when the model has several (a main score and an
|
|
18
|
+
auxiliary head). `min_delta` is the smallest gain that counts as an improvement: on a small
|
|
19
|
+
validation set, a gain below the noise should not reset the patience.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
metric: Metric | None = None
|
|
23
|
+
mode: Mode = "min"
|
|
24
|
+
output: str | None = None
|
|
25
|
+
min_delta: float = 0.0
|
|
26
|
+
|
|
27
|
+
def __post_init__(self) -> None:
|
|
28
|
+
if self.mode not in ("min", "max"):
|
|
29
|
+
raise ValueError(f"mode must be 'min' or 'max'; got {self.mode!r}")
|
|
30
|
+
if self.metric is None and self.mode == "max":
|
|
31
|
+
raise ValueError("the validation loss is minimized: use mode='min', or give a metric to maximize")
|
|
32
|
+
if not (self.min_delta >= 0 and math.isfinite(self.min_delta)):
|
|
33
|
+
raise ValueError(f"min_delta must be a finite number >= 0; got {self.min_delta}")
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
def val_loss(cls, *, min_delta: float = 0.0) -> Monitor:
|
|
37
|
+
"""Watches the validation loss, lower is better."""
|
|
38
|
+
return cls(metric=None, mode="min", min_delta=min_delta)
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def name(self) -> str:
|
|
42
|
+
"""The column it writes in the history: `"val_loss"` or `"val_<metric name>"`."""
|
|
43
|
+
return "val_loss" if self.metric is None else f"val_{self.metric.name}"
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def watches_loss(self) -> bool:
|
|
47
|
+
return self.metric is None
|
|
48
|
+
|
|
49
|
+
def score(self, val_loss: float | None, y_true: Sequence, y_pred: Sequence) -> float | None:
|
|
50
|
+
if self.metric is None:
|
|
51
|
+
return val_loss
|
|
52
|
+
return float(self.metric.compute(y_true, y_pred))
|
|
53
|
+
|
|
54
|
+
def improved(self, current: float | None, best: float | None) -> bool:
|
|
55
|
+
"""Whether `current` beats `best` by more than `min_delta`. A value that is not a finite number
|
|
56
|
+
never counts as an improvement, not even the first one."""
|
|
57
|
+
if current is None or not math.isfinite(current):
|
|
58
|
+
return False
|
|
59
|
+
if best is None:
|
|
60
|
+
return True
|
|
61
|
+
if self.mode == "max":
|
|
62
|
+
return current > best + self.min_delta
|
|
63
|
+
return current < best - self.min_delta
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""How the weights learn: the optimizer's settings a task holds, and the optimizers known by name."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from enum import StrEnum
|
|
8
|
+
from typing import TYPE_CHECKING
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
import torch
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class OptimizerType(StrEnum):
|
|
15
|
+
"""Currently supported optimizers"""
|
|
16
|
+
|
|
17
|
+
ADAM = "adam"
|
|
18
|
+
ADAMW = "adamw"
|
|
19
|
+
SGD = "sgd"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
23
|
+
class OptimConfig:
|
|
24
|
+
"""How the weights learn, for a task with one optimizer: what `build_optimization` turns into the
|
|
25
|
+
`Optimization` that `configure_optimization` returns.
|
|
26
|
+
|
|
27
|
+
- `lr`: the learning rate; with param groups, the rate of a group that sets none.
|
|
28
|
+
- `optimizer`: `"adamw"`, `"adam"`, `"sgd"`, an `OptimizerType`, or any optimizer class or factory,
|
|
29
|
+
called as `factory(params, lr=..., weight_decay=...)`. `"sgd"` is SGD with momentum 0.9; for
|
|
30
|
+
another momentum, `functools.partial(torch.optim.SGD, momentum=0.5)`.
|
|
31
|
+
- `weight_decay`: the weight decay of a group that sets none.
|
|
32
|
+
- `warmup`: the share of all optimization steps spent rising linearly to `lr`, after which the rate
|
|
33
|
+
falls linearly to zero; `None` keeps the rate constant.
|
|
34
|
+
|
|
35
|
+
A task holds it as a field, so these settings are recorded with the task's other fields. A task whose
|
|
36
|
+
optimization does not fit here (another schedule, another optimizer per head) writes its own
|
|
37
|
+
`configure_optimization`, from fields of its own.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
lr: float = 1e-3
|
|
41
|
+
optimizer: OptimizerType | str | Callable[..., torch.optim.Optimizer] = OptimizerType.ADAMW
|
|
42
|
+
weight_decay: float = 0.0
|
|
43
|
+
warmup: float | None = None
|
|
44
|
+
|
|
45
|
+
def __post_init__(self) -> None:
|
|
46
|
+
if self.lr <= 0:
|
|
47
|
+
raise ValueError(f"lr must be positive; got {self.lr}")
|
|
48
|
+
if self.warmup is not None and not 0 <= self.warmup <= 1:
|
|
49
|
+
raise ValueError(f"warmup is a share of all optimization steps, in [0, 1]; got {self.warmup}")
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""A configuration as flat parameters: what a fit records of the dataclasses that set it up."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import enum
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from pathlib import PurePath
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
ParamValue = str | int | float | bool
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def flatten_params(obj: Any, prefix: str = "") -> dict[str, ParamValue]:
|
|
15
|
+
"""Turns a configuration (dataclasses, mappings, enums, plain values) into flat parameters.
|
|
16
|
+
|
|
17
|
+
`FitConfig(monitor=Monitor(F1Metric("macro"), "max"))` becomes `{"epochs": 30, "monitor.mode":
|
|
18
|
+
"max", "monitor.metric.average": "macro", ...}`. The dataclass is the only description of the
|
|
19
|
+
configuration: there is no second list of parameters to keep in sync by hand.
|
|
20
|
+
"""
|
|
21
|
+
flat: dict[str, ParamValue] = {}
|
|
22
|
+
_flatten(obj, prefix, flat)
|
|
23
|
+
return flat
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _flatten(obj: Any, key: str, flat: dict[str, ParamValue]) -> None:
|
|
27
|
+
if dataclasses.is_dataclass(obj) and not isinstance(obj, type):
|
|
28
|
+
for field in dataclasses.fields(obj):
|
|
29
|
+
_flatten(getattr(obj, field.name), _join(key, field.name), flat)
|
|
30
|
+
return
|
|
31
|
+
if isinstance(obj, Mapping):
|
|
32
|
+
for name, value in obj.items():
|
|
33
|
+
_flatten(value, _join(key, str(name)), flat)
|
|
34
|
+
return
|
|
35
|
+
flat[key or "value"] = _scalar(obj)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _join(prefix: str, name: str) -> str:
|
|
39
|
+
return f"{prefix}.{name}" if prefix else name
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _scalar(value: Any) -> ParamValue:
|
|
43
|
+
if isinstance(value, enum.Enum):
|
|
44
|
+
value = value.value
|
|
45
|
+
if isinstance(value, bool | int | float | str):
|
|
46
|
+
return value
|
|
47
|
+
if value is None:
|
|
48
|
+
return "None"
|
|
49
|
+
if isinstance(value, PurePath):
|
|
50
|
+
return str(value)
|
|
51
|
+
if isinstance(value, type) or callable(value) and hasattr(value, "__qualname__"):
|
|
52
|
+
return f"{getattr(value, '__module__', '')}.{value.__qualname__}".lstrip(".")
|
|
53
|
+
if isinstance(value, list | tuple | set | frozenset):
|
|
54
|
+
return repr(list(value) if isinstance(value, set | frozenset) else value)
|
|
55
|
+
return type(value).__name__
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
6
|
+
|
|
7
|
+
from torchstack64.core import require
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from optuna.distributions import BaseDistribution
|
|
11
|
+
from optuna.pruners import BasePruner
|
|
12
|
+
|
|
13
|
+
PARTS = ("model", "task", "fit") # what a name of the space starts with
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
17
|
+
class SearchConfig:
|
|
18
|
+
"""What a search varies, and in how many fits.
|
|
19
|
+
|
|
20
|
+
- `space`: the name of each value to vary, and where it may go: a list of options, or an Optuna
|
|
21
|
+
distribution for a range (`FloatDistribution(1e-4, 1e-2, log=True)`). The names are the ones a fit
|
|
22
|
+
records, `task.optim.lr` or `fit.clip_grad_norm`, and `model.<argument>` for an argument of the
|
|
23
|
+
network's class, or of the function that builds it.
|
|
24
|
+
- `n_trials`: how many fits a search runs.
|
|
25
|
+
- `pruner`: what gives a trial up early; `None` is Optuna's default, the median rule.
|
|
26
|
+
|
|
27
|
+
Score the trials by a metric, not by the loss, when the search varies the loss itself: the scores of
|
|
28
|
+
two losses are not comparable.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
space: Mapping[str, list[Any] | BaseDistribution]
|
|
32
|
+
n_trials: int = 20
|
|
33
|
+
pruner: BasePruner | None = None
|
|
34
|
+
|
|
35
|
+
def __post_init__(self) -> None:
|
|
36
|
+
distributions = require("optuna.distributions", extra="optuna", purpose="SearchConfig")
|
|
37
|
+
if not self.space:
|
|
38
|
+
raise ValueError("space is empty: name at least one value to vary")
|
|
39
|
+
if self.n_trials < 1:
|
|
40
|
+
raise ValueError(f"n_trials must be at least 1; got {self.n_trials}")
|
|
41
|
+
for name, values in self.space.items():
|
|
42
|
+
part, _, path = name.partition(".")
|
|
43
|
+
if part not in PARTS or not path:
|
|
44
|
+
raise ValueError(f"{name!r}: a name starts with 'model.', 'task.' or 'fit.'")
|
|
45
|
+
if not isinstance(values, list | distributions.BaseDistribution):
|
|
46
|
+
raise ValueError(
|
|
47
|
+
f"{name}: give a list of options, or a distribution for a range, such as "
|
|
48
|
+
f"FloatDistribution(1e-4, 1e-2, log=True); got {values!r}"
|
|
49
|
+
)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from torchstack64.training.results.fit import FitResult, FitStatus
|
|
2
|
+
from torchstack64.training.results.history import (
|
|
3
|
+
BestCheckpoint,
|
|
4
|
+
EpochResult,
|
|
5
|
+
OptimizationStepRecord,
|
|
6
|
+
TrainingHistory,
|
|
7
|
+
)
|
|
8
|
+
from torchstack64.training.results.predictions import Evaluation, Predictions
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"BestCheckpoint",
|
|
12
|
+
"EpochResult",
|
|
13
|
+
"Evaluation",
|
|
14
|
+
"FitResult",
|
|
15
|
+
"FitStatus",
|
|
16
|
+
"OptimizationStepRecord",
|
|
17
|
+
"Predictions",
|
|
18
|
+
"TrainingHistory",
|
|
19
|
+
]
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from enum import StrEnum
|
|
6
|
+
|
|
7
|
+
from torchstack64.training.results.history import TrainingHistory
|
|
8
|
+
from torchstack64.training.results.predictions import Predictions
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class FitStatus(StrEnum):
|
|
12
|
+
RUNNING = "running"
|
|
13
|
+
COMPLETED = "completed" # every epoch ran
|
|
14
|
+
STOPPED_EARLY = "stopped_early" # the patience ran out
|
|
15
|
+
STOPPED = "stopped" # a callback asked, or the monitored value stopped being a number
|
|
16
|
+
PRUNED = "pruned" # a hyperparameter search abandoned the trial
|
|
17
|
+
INTERRUPTED = "interrupted" # KeyboardInterrupt
|
|
18
|
+
FAILED = "failed" # an exception
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(slots=True, frozen=True)
|
|
22
|
+
class FitResult:
|
|
23
|
+
"""How a fit ended, its history and best epoch, and `params`: how it was set up (the `FitConfig`, the
|
|
24
|
+
task's fields, the device, the model's size), flat, recorded whether or not a tracker runs."""
|
|
25
|
+
|
|
26
|
+
history: TrainingHistory
|
|
27
|
+
status: FitStatus
|
|
28
|
+
monitor: str
|
|
29
|
+
best_epoch: int | None
|
|
30
|
+
best_score: float | None
|
|
31
|
+
best_predictions: Predictions | None
|
|
32
|
+
stop_reason: str | None
|
|
33
|
+
epochs_run: int
|
|
34
|
+
optimization_steps: int
|
|
35
|
+
seconds: float
|
|
36
|
+
error: str | None = None
|
|
37
|
+
params: Mapping[str, str | int | float | bool] = field(default_factory=dict)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import math
|
|
5
|
+
from collections.abc import Iterator, Mapping
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import torch
|
|
11
|
+
|
|
12
|
+
from torchstack64.training.results.predictions import Predictions
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(slots=True, frozen=True)
|
|
16
|
+
class OptimizationStepRecord:
|
|
17
|
+
optimization_step: int
|
|
18
|
+
epoch: int
|
|
19
|
+
batch_index: int
|
|
20
|
+
loss: torch.Tensor
|
|
21
|
+
lr: float
|
|
22
|
+
grad_norm: torch.Tensor | None = None
|
|
23
|
+
skipped: bool = False # the fp16 scaler found inf/NaN gradients and skipped the update
|
|
24
|
+
logs: Mapping[str, torch.Tensor | float] = field(default_factory=dict)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(slots=True)
|
|
28
|
+
class BestCheckpoint:
|
|
29
|
+
epoch: int
|
|
30
|
+
score: float
|
|
31
|
+
state: dict[str, Any]
|
|
32
|
+
predictions: Predictions | None = None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(slots=True, frozen=True)
|
|
36
|
+
class EpochResult:
|
|
37
|
+
epoch: int
|
|
38
|
+
metrics: dict[str, float]
|
|
39
|
+
improved: bool
|
|
40
|
+
patience: int
|
|
41
|
+
best: BestCheckpoint | None
|
|
42
|
+
seconds: float
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(slots=True)
|
|
46
|
+
class TrainingHistory:
|
|
47
|
+
entries: list[dict[str, float]] = field(default_factory=list)
|
|
48
|
+
|
|
49
|
+
def __len__(self) -> int:
|
|
50
|
+
return len(self.entries)
|
|
51
|
+
|
|
52
|
+
def __iter__(self) -> Iterator[dict[str, float]]:
|
|
53
|
+
return iter(self.entries)
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def columns(self) -> list[str]:
|
|
57
|
+
names: dict[str, None] = {}
|
|
58
|
+
for entry in self.entries:
|
|
59
|
+
names.update(dict.fromkeys(entry))
|
|
60
|
+
return list(names)
|
|
61
|
+
|
|
62
|
+
def column(self, name: str) -> list[float]:
|
|
63
|
+
"""The values of one column, epoch by epoch (NaN where an epoch did not record it)."""
|
|
64
|
+
if self.entries and not any(name in entry for entry in self.entries):
|
|
65
|
+
raise KeyError(f"no column {name!r} in the history; columns: {self.columns}")
|
|
66
|
+
return [float(entry.get(name, math.nan)) for entry in self.entries]
|
|
67
|
+
|
|
68
|
+
def to_csv(self, path: str | Path) -> Path:
|
|
69
|
+
path = Path(path)
|
|
70
|
+
with path.open("w", newline="", encoding="utf-8") as handle:
|
|
71
|
+
writer = csv.DictWriter(handle, fieldnames=self.columns)
|
|
72
|
+
writer.writeheader()
|
|
73
|
+
writer.writerows(self.entries)
|
|
74
|
+
return path
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(slots=True)
|
|
12
|
+
class Predictions:
|
|
13
|
+
outputs: dict[str, torch.Tensor]
|
|
14
|
+
targets: torch.Tensor | None = None
|
|
15
|
+
ids: list[Any] | None = None
|
|
16
|
+
|
|
17
|
+
SINGLE = "preds"
|
|
18
|
+
|
|
19
|
+
def __len__(self) -> int:
|
|
20
|
+
for tensor in self.outputs.values():
|
|
21
|
+
return int(tensor.shape[0])
|
|
22
|
+
if self.targets is not None:
|
|
23
|
+
return int(self.targets.shape[0])
|
|
24
|
+
return len(self.ids or [])
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def names(self) -> list[str]:
|
|
28
|
+
return list(self.outputs)
|
|
29
|
+
|
|
30
|
+
def select(self, output: str | None = None) -> torch.Tensor:
|
|
31
|
+
"""One output: the only one when `output` is None, or the one named."""
|
|
32
|
+
if output is None:
|
|
33
|
+
if len(self.outputs) == 1:
|
|
34
|
+
return next(iter(self.outputs.values()))
|
|
35
|
+
raise ValueError(
|
|
36
|
+
f"these predictions have several outputs {self.names}: name one (Monitor(output=...))"
|
|
37
|
+
)
|
|
38
|
+
try:
|
|
39
|
+
return self.outputs[output]
|
|
40
|
+
except KeyError:
|
|
41
|
+
raise ValueError(f"no output named {output!r}; outputs: {self.names}") from None
|
|
42
|
+
|
|
43
|
+
def columns(self) -> dict[str, list[Any]]:
|
|
44
|
+
"""A table, one column per field: `id`, `target`, and each output (a 2-D output becomes one
|
|
45
|
+
column per class, `score_0`, `score_1`...). Ready for a CSV, a DataFrame or `mlflow.log_table`."""
|
|
46
|
+
table: dict[str, list[Any]] = {}
|
|
47
|
+
if self.ids is not None:
|
|
48
|
+
table["id"] = list(self.ids)
|
|
49
|
+
if self.targets is not None:
|
|
50
|
+
table.update(self._columns_of("target", self.targets))
|
|
51
|
+
for name, tensor in self.outputs.items():
|
|
52
|
+
table.update(self._columns_of(name, tensor))
|
|
53
|
+
return table
|
|
54
|
+
|
|
55
|
+
@staticmethod
|
|
56
|
+
def _columns_of(name: str, tensor: torch.Tensor) -> dict[str, list[Any]]:
|
|
57
|
+
"""The column or columns of one tensor: one for a 1-D tensor, one per class (`name_0`, `name_1`...)
|
|
58
|
+
for a 2-D one, and a column of lists for more dimensions."""
|
|
59
|
+
if tensor.dim() <= 1:
|
|
60
|
+
return {name: tensor.reshape(-1).tolist()}
|
|
61
|
+
if tensor.dim() == 2:
|
|
62
|
+
return {f"{name}_{index}": tensor[:, index].tolist() for index in range(tensor.shape[1])}
|
|
63
|
+
return {name: [row.tolist() for row in tensor]}
|
|
64
|
+
|
|
65
|
+
def to_csv(self, path: str | Path) -> Path:
|
|
66
|
+
path = Path(path)
|
|
67
|
+
table = self.columns()
|
|
68
|
+
names = list(table)
|
|
69
|
+
with path.open("w", newline="", encoding="utf-8") as handle:
|
|
70
|
+
writer = csv.writer(handle)
|
|
71
|
+
writer.writerow(names)
|
|
72
|
+
writer.writerows(zip(*(table[n] for n in names), strict=True))
|
|
73
|
+
return path
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(slots=True, frozen=True)
|
|
77
|
+
class Evaluation:
|
|
78
|
+
loss: float | None
|
|
79
|
+
predictions: Predictions
|
|
80
|
+
score: float | None
|
|
81
|
+
logs: dict[str, float] = field(default_factory=dict)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""What a loop runs on and with: the device and precision (`Runtime`), moving a batch to the device, the
|
|
2
|
+
random generators, and copies of a model's weights.
|
|
3
|
+
|
|
4
|
+
The trainer runs on these, and a hand-written loop can use them directly.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from torchstack64.training.runtime.randomness import Randomness, seed_everything
|
|
8
|
+
from torchstack64.training.runtime.runtime import Runtime
|
|
9
|
+
from torchstack64.training.runtime.transfer import to_device
|
|
10
|
+
from torchstack64.training.runtime.weights import Weights
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"Randomness",
|
|
14
|
+
"Runtime",
|
|
15
|
+
"Weights",
|
|
16
|
+
"seed_everything",
|
|
17
|
+
"to_device",
|
|
18
|
+
]
|