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.
Files changed (92) hide show
  1. torchstack64/__init__.py +101 -0
  2. torchstack64/artifacts/__init__.py +78 -0
  3. torchstack64/artifacts/bundle/__init__.py +50 -0
  4. torchstack64/artifacts/bundle/files.py +106 -0
  5. torchstack64/artifacts/bundle/folder.py +385 -0
  6. torchstack64/artifacts/bundle/tensors.py +75 -0
  7. torchstack64/artifacts/code/__init__.py +103 -0
  8. torchstack64/artifacts/code/copy.py +149 -0
  9. torchstack64/artifacts/code/importing.py +204 -0
  10. torchstack64/artifacts/code/inspection.py +351 -0
  11. torchstack64/artifacts/code/notebook.py +373 -0
  12. torchstack64/artifacts/code/objects.py +401 -0
  13. torchstack64/artifacts/loading.py +117 -0
  14. torchstack64/artifacts/manifest.py +220 -0
  15. torchstack64/artifacts/predictor/__init__.py +45 -0
  16. torchstack64/artifacts/predictor/bundle_predictor.py +193 -0
  17. torchstack64/artifacts/predictor/output_reading.py +96 -0
  18. torchstack64/artifacts/predictor/torch_classifier.py +106 -0
  19. torchstack64/artifacts/predictor/torch_predictor.py +247 -0
  20. torchstack64/artifacts/proofs/__init__.py +83 -0
  21. torchstack64/artifacts/proofs/answers.py +159 -0
  22. torchstack64/artifacts/proofs/example.py +248 -0
  23. torchstack64/artifacts/proofs/modules.py +260 -0
  24. torchstack64/artifacts/proofs/suite.py +560 -0
  25. torchstack64/artifacts/saving.py +461 -0
  26. torchstack64/artifacts/sources.py +166 -0
  27. torchstack64/callbacks/__init__.py +22 -0
  28. torchstack64/callbacks/base.py +43 -0
  29. torchstack64/callbacks/checkpointing.py +40 -0
  30. torchstack64/callbacks/history_plot.py +160 -0
  31. torchstack64/callbacks/mlflow_logger.py +217 -0
  32. torchstack64/callbacks/model_checks.py +295 -0
  33. torchstack64/callbacks/progress.py +132 -0
  34. torchstack64/callbacks/stack.py +85 -0
  35. torchstack64/core/__init__.py +59 -0
  36. torchstack64/core/errors.py +121 -0
  37. torchstack64/core/evaluation.py +52 -0
  38. torchstack64/core/extras.py +36 -0
  39. torchstack64/core/inference.py +42 -0
  40. torchstack64/core/labels.py +201 -0
  41. torchstack64/core/logging.py +110 -0
  42. torchstack64/data/__init__.py +10 -0
  43. torchstack64/data/base.py +256 -0
  44. torchstack64/data/labeled.py +128 -0
  45. torchstack64/devices/__init__.py +38 -0
  46. torchstack64/devices/hardware.py +43 -0
  47. torchstack64/devices/selection.py +82 -0
  48. torchstack64/metrics/__init__.py +21 -0
  49. torchstack64/metrics/classification.py +93 -0
  50. torchstack64/py.typed +0 -0
  51. torchstack64/training/__init__.py +83 -0
  52. torchstack64/training/config/__init__.py +17 -0
  53. torchstack64/training/config/fit.py +60 -0
  54. torchstack64/training/config/monitor.py +63 -0
  55. torchstack64/training/config/optim.py +49 -0
  56. torchstack64/training/config/params.py +55 -0
  57. torchstack64/training/config/search.py +49 -0
  58. torchstack64/training/results/__init__.py +19 -0
  59. torchstack64/training/results/fit.py +37 -0
  60. torchstack64/training/results/history.py +74 -0
  61. torchstack64/training/results/predictions.py +81 -0
  62. torchstack64/training/runtime/__init__.py +18 -0
  63. torchstack64/training/runtime/precision.py +139 -0
  64. torchstack64/training/runtime/randomness.py +142 -0
  65. torchstack64/training/runtime/runtime.py +75 -0
  66. torchstack64/training/runtime/transfer.py +49 -0
  67. torchstack64/training/runtime/weights.py +43 -0
  68. torchstack64/training/task/__init__.py +11 -0
  69. torchstack64/training/task/optim/__init__.py +9 -0
  70. torchstack64/training/task/optim/optimization.py +70 -0
  71. torchstack64/training/task/optim/schedules.py +27 -0
  72. torchstack64/training/task/protocol.py +58 -0
  73. torchstack64/training/task/supervised.py +113 -0
  74. torchstack64/training/trainer/__init__.py +8 -0
  75. torchstack64/training/trainer/adapters.py +122 -0
  76. torchstack64/training/trainer/contracts.py +81 -0
  77. torchstack64/training/trainer/hooks.py +47 -0
  78. torchstack64/training/trainer/meters.py +150 -0
  79. torchstack64/training/trainer/state.py +117 -0
  80. torchstack64/training/trainer/trainer.py +586 -0
  81. torchstack64/training/tuner/__init__.py +3 -0
  82. torchstack64/training/tuner/callback.py +38 -0
  83. torchstack64/training/tuner/space.py +82 -0
  84. torchstack64/training/tuner/tuner.py +137 -0
  85. torchstack64/utils/__init__.py +21 -0
  86. torchstack64/utils/logging.py +85 -0
  87. torchstack64/utils/mlflow.py +127 -0
  88. torchstack64-0.3.0.dist-info/METADATA +622 -0
  89. torchstack64-0.3.0.dist-info/RECORD +92 -0
  90. torchstack64-0.3.0.dist-info/WHEEL +5 -0
  91. torchstack64-0.3.0.dist-info/licenses/LICENSE +21 -0
  92. torchstack64-0.3.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,113 @@
1
+ """`SupervisedTask`: the common case in one line, and the way it reads a batch."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping
6
+ from dataclasses import dataclass
7
+ from typing import Any
8
+
9
+ import torch
10
+ from torch import nn
11
+
12
+ from torchstack64.training.config import OptimConfig
13
+ from torchstack64.training.task.optim import build_optimization
14
+ from torchstack64.training.trainer import FitPlan, Optimization, Step, StepContext
15
+
16
+
17
+ @dataclass(slots=True)
18
+ class SupervisedTask:
19
+ """A common case in one line: batches of `(inputs, targets)` (or `(inputs, targets, ids)`), a model
20
+ that returns what `loss_fn` expects, and one optimizer, which `optim` describes: the learning rate,
21
+ the optimizer, the weight decay and the warm-up.
22
+
23
+ `inputs` is passed to the model as is, or as keyword arguments when it is a dict (a tokenizer's
24
+ output). `to_preds` turns the model's output into what the monitor's metric reads: for a classifier
25
+ and a label metric, `lambda logits: logits.argmax(dim=1)`; for a binary scorer,
26
+ `lambda logits: logits.sigmoid()`. Without it the raw output is kept.
27
+
28
+ A batch is read by position, as a tuple, a list or a named tuple: `(inputs,)`, `(inputs, targets)`
29
+ or `(inputs, targets, ids)`. Two elements are always inputs and targets. Any other shape (a dict
30
+ that carries its labels, ids without targets, extra elements) is described by `unpack`, a function
31
+ from the batch to `(inputs, targets, ids)` with `None` for what the batch lacks. For batches of
32
+ `(inputs, ids)` with no labels: `unpack=lambda batch: (batch[0], None, batch[1])`.
33
+ """
34
+
35
+ loss_fn: Callable[[Any, Any], torch.Tensor]
36
+ optim: OptimConfig = OptimConfig()
37
+ to_preds: Callable[[Any], torch.Tensor] | None = None
38
+ unpack: Callable[[Any], tuple[Any, Any, Any]] | None = None
39
+
40
+ def configure_optimization(self, model: nn.Module, plan: FitPlan) -> Optimization:
41
+ return build_optimization(self.optim, model.parameters(), plan)
42
+
43
+ def training_step(self, model: nn.Module, batch: Any, ctx: StepContext) -> torch.Tensor:
44
+ inputs, targets, _ = self._parts(batch)
45
+ if targets is None:
46
+ raise ValueError(self._no_targets(batch))
47
+ return self.loss_fn(forward(model, inputs), targets)
48
+
49
+ def validation_step(self, model: nn.Module, batch: Any, ctx: StepContext) -> Step:
50
+ inputs, targets, ids = self._parts(batch)
51
+ outputs = forward(model, inputs)
52
+ loss = self.loss_fn(outputs, targets) if targets is not None else None
53
+ return Step(loss=loss, preds=self._preds(outputs), targets=targets, ids=ids)
54
+
55
+ def predict_step(self, model: nn.Module, batch: Any, ctx: StepContext) -> Step:
56
+ inputs, targets, ids = self._parts(batch)
57
+ return Step(preds=self._preds(forward(model, inputs)), targets=targets, ids=ids)
58
+
59
+ def _preds(self, outputs: Any) -> Any:
60
+ return self.to_preds(outputs) if self.to_preds is not None else outputs
61
+
62
+ def _parts(self, batch: Any) -> tuple[Any, Any, Any]:
63
+ if self.unpack is None:
64
+ return split_batch(batch)
65
+ parts = self.unpack(batch)
66
+ if not isinstance(parts, tuple) or len(parts) != 3:
67
+ raise TypeError(
68
+ "unpack must return (inputs, targets, ids), with None for what the batch does not have; "
69
+ f"it returned {describe_batch(parts)}"
70
+ )
71
+ return parts
72
+
73
+ def _no_targets(self, batch: Any) -> str:
74
+ if self.unpack is not None:
75
+ return (
76
+ f"unpack found no targets in this batch ({describe_batch(batch)}); training needs "
77
+ "(inputs, targets, ids) with the targets set"
78
+ )
79
+ return (
80
+ f"SupervisedTask trains on batches with targets, but this batch is {describe_batch(batch)}. "
81
+ "It reads a tuple, list or named tuple of (inputs, targets) or (inputs, targets, ids) by "
82
+ "position; for any other shape, pass unpack= a function from the batch to "
83
+ "(inputs, targets, ids)"
84
+ )
85
+
86
+
87
+ def split_batch(batch: Any) -> tuple[Any, Any, Any]:
88
+ """`(inputs,)`, `(inputs, targets)` or `(inputs, targets, ids)`, as a tuple, a list or a named tuple,
89
+ by position; anything else is the inputs alone."""
90
+ if isinstance(batch, tuple | list):
91
+ if len(batch) == 1:
92
+ return batch[0], None, None
93
+ if len(batch) == 2:
94
+ return batch[0], batch[1], None
95
+ if len(batch) == 3:
96
+ return batch[0], batch[1], batch[2]
97
+ return batch, None, None
98
+
99
+
100
+ def describe_batch(batch: Any) -> str:
101
+ """A batch in a few words, for an error message: its type, and its length or keys."""
102
+ name = type(batch).__name__
103
+ if isinstance(batch, Mapping):
104
+ keys = [str(key) for key in batch]
105
+ shown = ", ".join(repr(key) for key in keys[:8]) + (", ..." if len(keys) > 8 else "")
106
+ return f"a {name} with keys [{shown}]"
107
+ if isinstance(batch, tuple | list):
108
+ return f"a {name} of length {len(batch)}"
109
+ return f"a {name}"
110
+
111
+
112
+ def forward(model: nn.Module, inputs: Any) -> Any:
113
+ return model(**inputs) if isinstance(inputs, Mapping) else model(inputs)
@@ -0,0 +1,8 @@
1
+ """The trainer, which saves and resumes a fit, what it keeps while it runs (the state of the fit, the
2
+ callbacks it calls, the meters of an epoch), and the contracts it trades with a task."""
3
+
4
+ from torchstack64.training.trainer.contracts import FitPlan, Optimization, Step, StepContext
5
+ from torchstack64.training.trainer.state import FitState
6
+ from torchstack64.training.trainer.trainer import Trainer
7
+
8
+ __all__ = ["FitPlan", "FitState", "Optimization", "Step", "StepContext", "Trainer"]
@@ -0,0 +1,122 @@
1
+ """How the loop reads what the user hands it (a task, and callbacks), and what it records of it.
2
+
3
+ A task may return less than the full form: a training step can hand back the loss tensor alone, and
4
+ `configure_optimization` can hand back just an optimizer. The loop turns those into the full `Step` and
5
+ `Optimization` it works with, and says what was wrong when it is given something else.
6
+
7
+ A callback is any object that may keep a state, which is saved with the fit and handed back when the fit
8
+ resumes. The hooks it defines are called from `hooks.py`.
9
+
10
+ The run's parameters say how a fit was set up, flat: what `FitResult.params` keeps and a tracker logs.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import dataclasses
16
+ import logging
17
+ from collections.abc import Iterable, Mapping, Sequence
18
+ from typing import TYPE_CHECKING, Any
19
+
20
+ import torch
21
+
22
+ from torchstack64.core import warn_once
23
+ from torchstack64.training.config import ParamValue, flatten_params
24
+ from torchstack64.training.runtime import Weights
25
+ from torchstack64.training.trainer.contracts import FitPlan, Optimization, Step
26
+
27
+ if TYPE_CHECKING:
28
+ from torchstack64.training.trainer.trainer import Trainer
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ # -- the task ------------------------------------------------------------------------------------------
34
+
35
+
36
+ def plan_for(loader: Iterable[Any], epochs: int, accumulate: int = 1) -> FitPlan:
37
+ """The `FitPlan` of a fit over `loader`: its length is unknown when it has no `len()`."""
38
+ try:
39
+ batches: int | None = len(loader) # type: ignore[arg-type]
40
+ except TypeError:
41
+ batches = None
42
+ return FitPlan(epochs=epochs, batches_per_epoch=batches, accumulate=accumulate)
43
+
44
+
45
+ def as_optimization(value: Optimization | torch.optim.Optimizer) -> Optimization:
46
+ """An `Optimization`, as it is or built around a bare optimizer."""
47
+ if isinstance(value, Optimization):
48
+ return value
49
+ if isinstance(value, torch.optim.Optimizer):
50
+ return Optimization(value)
51
+ raise TypeError(
52
+ f"configure_optimization must return an Optimization or an optimizer; got {type(value).__name__}"
53
+ )
54
+
55
+
56
+ def as_step(value: Step | torch.Tensor) -> Step:
57
+ """A `Step`, as it is or built around a bare loss tensor."""
58
+ if isinstance(value, Step):
59
+ return value
60
+ if isinstance(value, torch.Tensor):
61
+ return Step(loss=value)
62
+ raise TypeError(f"a step must return a Step or a loss tensor; got {type(value).__name__}")
63
+
64
+
65
+ # -- the callbacks' state ------------------------------------------------------------------------------
66
+
67
+
68
+ def capture_callback_states(trainer: Trainer[Any]) -> dict[str, Any]:
69
+ """The state of each callback that has a `state_dict`, under its key, for `restore_callback_states`."""
70
+ return {
71
+ key: callback.state_dict()
72
+ for key, callback in callback_keys(trainer.callbacks)
73
+ if callable(getattr(callback, "state_dict", None))
74
+ }
75
+
76
+
77
+ def restore_callback_states(trainer: Trainer[Any], states: Mapping[str, Any]) -> None:
78
+ """Hands each callback that has a `load_state_dict` the state it saved."""
79
+ for key, callback in callback_keys(trainer.callbacks):
80
+ if key in states and callable(getattr(callback, "load_state_dict", None)):
81
+ callback.load_state_dict(states[key])
82
+
83
+
84
+ def callback_keys(callbacks: Sequence[Any]) -> list[tuple[str, Any]]:
85
+ """A stable key per callback, to save and restore their state: its place and its class."""
86
+ return [(f"{index}:{type(callback).__qualname__}", callback) for index, callback in enumerate(callbacks)]
87
+
88
+
89
+ # -- the run's parameters ------------------------------------------------------------------------------
90
+
91
+
92
+ def run_params(trainer: Trainer[Any]) -> dict[str, ParamValue]:
93
+ """How the fit that is starting was set up: the `FitConfig` under `fit.`, the task's fields under
94
+ `task.`, the device and precision in use, the plan, the model's class and parameter counts, and the
95
+ callbacks. They describe the setup, not the model's weights.
96
+
97
+ A task that is not a dataclass is recorded by its class name alone, with a warning (once per process
98
+ and class): its settings cannot be read.
99
+ """
100
+ task = trainer.task
101
+ params = flatten_params(trainer.config, "fit")
102
+ params["task"] = type(task).__qualname__
103
+ if dataclasses.is_dataclass(task) and not isinstance(task, type):
104
+ params.update(flatten_params(task, "task"))
105
+ else:
106
+ warn_once(
107
+ logger,
108
+ "%s is not a dataclass, so its hyperparameters are not recorded in FitResult.params nor logged "
109
+ "by a tracker; write it as a dataclass whose fields are its settings",
110
+ type(task).__name__,
111
+ )
112
+ if trainer.runtime is not None:
113
+ params["runtime.device"] = str(trainer.runtime.device)
114
+ params["runtime.precision"] = trainer.runtime.precision
115
+ if trainer.plan is not None:
116
+ params["plan.steps_per_epoch"] = str(trainer.plan.optimization_steps_per_epoch)
117
+ total, trainable = Weights(trainer.model).count()
118
+ params["model.class"] = type(trainer.model).__qualname__
119
+ params["model.parameters"] = total
120
+ params["model.trainable_parameters"] = trainable
121
+ params["callbacks"] = ",".join(type(callback).__name__ for callback in trainer.callbacks)
122
+ return params
@@ -0,0 +1,81 @@
1
+ """What the trainer and a task trade: two values the trainer tells a task (`FitPlan`, `StepContext`) and
2
+ two a task hands back (`Optimization`, `Step`).
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import math
8
+ from collections.abc import Mapping, Sequence
9
+ from dataclasses import dataclass, field
10
+ from typing import Any, Literal
11
+
12
+ import torch
13
+
14
+
15
+ @dataclass(frozen=True, slots=True)
16
+ class FitPlan:
17
+ """What the loop knows before the first batch: everything a learning-rate schedule needs."""
18
+
19
+ epochs: int
20
+ batches_per_epoch: int | None # None when the loader has no len()
21
+ accumulate: int = 1
22
+
23
+ @property
24
+ def optimization_steps_per_epoch(self) -> int | None:
25
+ """Optimization steps per epoch: batches over `accumulate`, rounded up."""
26
+ if self.batches_per_epoch is None:
27
+ return None
28
+ return math.ceil(self.batches_per_epoch / self.accumulate)
29
+
30
+ @property
31
+ def total_optimization_steps(self) -> int | None:
32
+ steps = self.optimization_steps_per_epoch
33
+ return None if steps is None else steps * self.epochs
34
+
35
+
36
+ @dataclass(frozen=True, slots=True)
37
+ class StepContext:
38
+ """Where a batch is processed: the epoch, the optimization steps taken so far, the batch
39
+ within the epoch, whether it is training, the device, and the plan.
40
+
41
+ With gradient accumulation several batches share the same `optimization_step`; `batch_index` tells
42
+ them apart.
43
+ """
44
+
45
+ epoch: int
46
+ optimization_step: int
47
+ batch_index: int
48
+ training: bool
49
+ device: torch.device
50
+ plan: FitPlan | None = None
51
+
52
+
53
+ @dataclass(frozen=True, slots=True)
54
+ class Optimization:
55
+ """The optimizer, an optional scheduler, and whether the scheduler steps per optimization step
56
+ (`"step"`) or per epoch."""
57
+
58
+ optimizer: torch.optim.Optimizer
59
+ scheduler: Any = None # an LRScheduler, or ReduceLROnPlateau (stepped with the monitored value)
60
+ interval: Literal["step", "epoch"] = "step"
61
+
62
+ def __post_init__(self) -> None:
63
+ if self.interval not in ("step", "epoch"):
64
+ raise ValueError(f"interval must be 'step' or 'epoch'; got {self.interval!r}")
65
+
66
+
67
+ @dataclass(slots=True)
68
+ class Step:
69
+ """What a task hands back for one batch (not for an optimization step). While training only `loss` is
70
+ needed; while validating, `preds` and `targets` feed the monitor, and `ids` keep each prediction tied
71
+ to its example.
72
+
73
+ `preds` may be one tensor or a dict of named outputs. `logs` are extra values (each part of a
74
+ composite loss, say) that the trainer averages per epoch and writes in the history.
75
+ """
76
+
77
+ loss: torch.Tensor | None = None
78
+ preds: torch.Tensor | Mapping[str, torch.Tensor] | None = None
79
+ targets: torch.Tensor | None = None
80
+ ids: torch.Tensor | Sequence[Any] | None = None
81
+ logs: Mapping[str, torch.Tensor | float] = field(default_factory=dict)
@@ -0,0 +1,47 @@
1
+ """The hooks of a fit: the moments a callback can hear about, and how the trainer calls them.
2
+
3
+ A callback is any object. For each hook it defines, a method of that name is called with the trainer
4
+ (and what the moment produced), in the order the callbacks were given; a hook it does not define is
5
+ skipped. The trainer knows the hooks by name only and imports no callback.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from enum import StrEnum
11
+ from typing import TYPE_CHECKING, Any
12
+
13
+ if TYPE_CHECKING:
14
+ from torchstack64.training.trainer.trainer import Trainer
15
+
16
+
17
+ class Hook(StrEnum):
18
+ TRAIN_BEGIN = "on_train_begin"
19
+ EPOCH_BEGIN = "on_epoch_begin"
20
+ TRAIN_BATCH_BEGIN = "on_train_batch_begin"
21
+ OPTIMIZATION_STEP_END = "on_optimization_step_end"
22
+ VALIDATION_BEGIN = "on_validation_begin"
23
+ VALIDATION_END = "on_validation_end"
24
+ EPOCH_END = "on_epoch_end"
25
+ TRAIN_END = "on_train_end"
26
+
27
+
28
+ def emit(trainer: Trainer[Any], hook: Hook, *args: Any) -> None:
29
+ """Calls `hook` on every callback that defines it. The first one to raise ends the fit."""
30
+ for callback in trainer.callbacks:
31
+ method = getattr(callback, hook, None)
32
+ if method is not None:
33
+ method(trainer, *args)
34
+
35
+
36
+ def emit_all(trainer: Trainer[Any], hook: Hook, *args: Any) -> list[BaseException]:
37
+ """Calls every callback even when one fails, and returns the errors."""
38
+ errors: list[BaseException] = []
39
+ for callback in trainer.callbacks:
40
+ method = getattr(callback, hook, None)
41
+ if method is None:
42
+ continue
43
+ try:
44
+ method(trainer, *args)
45
+ except Exception as error:
46
+ errors.append(error)
47
+ return errors
@@ -0,0 +1,150 @@
1
+ """What the loop gathers while it runs: the means of the logged values, the predictions of a
2
+ validation pass, and how many examples a batch had.
3
+
4
+ An epoch is hundreds of batches, and the task returns only a little for each: a loss, some predictions,
5
+ some targets (a `Step`). The rest of the system (the history plot, the progress bar, the monitor that
6
+ picks the best checkpoint, the metrics) wants one result per epoch. These pieces turn what each batch
7
+ returns into it:
8
+
9
+ - `RunningMeans`: the mean of each logged number over the epoch (the loss, a learning rate, ...).
10
+ - `PredictionCollector`: every prediction and target of a validation pass, kept together so a metric
11
+ can be computed over the whole set.
12
+ - `batch_size_of`: how many examples a batch had, so that a smaller last batch does not weigh as much
13
+ as a full one.
14
+
15
+ Everything here counts batches, not optimization steps: with gradient accumulation several batches make
16
+ one optimization step, and these pieces still see each of them. They only do the bookkeeping (add, join,
17
+ count). What to gather, and when, is up to the trainer.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from collections.abc import Mapping, Sequence
23
+ from typing import Any
24
+
25
+ import torch
26
+
27
+ from torchstack64.training.results import Predictions
28
+
29
+
30
+ class RunningMeans:
31
+ """Means of named values over an epoch, summed on the device: one GPU wait per name, at the end.
32
+
33
+ Each call to `add` is one batch, and every batch counts the same: this is the plain mean of the
34
+ per-batch values, not weighted by the number of examples in each. (The validation loss is weighted,
35
+ by the trainer, with `batch_size_of`.)
36
+
37
+ The sums stay on the device because calling `.item()` after every batch would make the CPU wait for
38
+ the GPU each time. Here that wait happens once per name, in `means`, when the epoch is over.
39
+ """
40
+
41
+ def __init__(self) -> None:
42
+ self._sums: dict[str, torch.Tensor | float] = {}
43
+ self._counts: dict[str, int] = {}
44
+
45
+ def add(self, values: Mapping[str, torch.Tensor | float]) -> None:
46
+ """Count one batch: fold each value into the running sum of its name.
47
+
48
+ A tensor becomes a scalar mean first and stays on the device; a number is added as it is.
49
+ """
50
+ for name, value in values.items():
51
+ if isinstance(value, torch.Tensor):
52
+ value = value.detach().float().mean()
53
+ current = self._sums.get(name)
54
+ self._sums[name] = value if current is None else current + value
55
+ self._counts[name] = self._counts.get(name, 0) + 1
56
+
57
+ def means(self) -> dict[str, float]:
58
+ """The mean of every name so far, as plain floats. This is where the GPU wait happens."""
59
+ result: dict[str, float] = {}
60
+ for name, total in self._sums.items():
61
+ value = total.item() if isinstance(total, torch.Tensor) else float(total)
62
+ result[name] = value / self._counts[name]
63
+ return result
64
+
65
+
66
+ class PredictionCollector:
67
+ """Gathers the `Step`s of a validation or prediction pass into one `Predictions`, on the CPU.
68
+
69
+ Metrics such as accuracy, F1 or AUC cannot be computed batch by batch and then averaged: they need
70
+ the whole set of predictions and targets. So the outputs of each batch are kept as they come, and
71
+ `result` joins them at the end.
72
+
73
+ Floating outputs are kept as float32: a bf16 tensor cannot become a NumPy array, and the metrics
74
+ downstream (scikit-learn, a project's own) expect ordinary floats.
75
+
76
+ Every batch must return the same named outputs. Otherwise there would be nothing to join, and `add`
77
+ says so at once instead of letting `torch.cat` fail later.
78
+ """
79
+
80
+ def __init__(self) -> None:
81
+ self._outputs: dict[str, list[torch.Tensor]] = {}
82
+ self._targets: list[torch.Tensor] = []
83
+ self._ids: list[Any] = []
84
+ self._has_ids = False
85
+
86
+ def add(
87
+ self,
88
+ preds: torch.Tensor | Mapping[str, torch.Tensor] | None,
89
+ targets: torch.Tensor | None,
90
+ ids: torch.Tensor | Sequence[Any] | None,
91
+ ) -> None:
92
+ """Keep the outputs of one batch.
93
+
94
+ A single tensor is stored under `Predictions.SINGLE`; a mapping keeps its names. Targets and ids
95
+ are optional: a batch that has none adds nothing.
96
+ """
97
+ if preds is not None:
98
+ named = {Predictions.SINGLE: preds} if isinstance(preds, torch.Tensor) else dict(preds)
99
+ if self._outputs and set(named) != set(self._outputs):
100
+ raise ValueError(
101
+ f"every batch must return the same outputs:{sorted(self._outputs)} vs {sorted(named)}"
102
+ )
103
+ for name, tensor in named.items():
104
+ self._outputs.setdefault(name, []).append(self._to_cpu(tensor))
105
+ if targets is not None:
106
+ self._targets.append(self._to_cpu(targets))
107
+ if ids is not None:
108
+ self._has_ids = True
109
+ self._ids.extend(ids.tolist() if isinstance(ids, torch.Tensor) else list(ids))
110
+
111
+ def result(self) -> Predictions:
112
+ """Join every batch into one `Predictions`. `targets` and `ids` are None if no batch gave any."""
113
+ return Predictions(
114
+ outputs={name: torch.cat(parts) for name, parts in self._outputs.items()},
115
+ targets=torch.cat(self._targets) if self._targets else None,
116
+ ids=self._ids if self._has_ids else None,
117
+ )
118
+
119
+ @staticmethod
120
+ def _to_cpu(tensor: torch.Tensor) -> torch.Tensor:
121
+ """Detached, at least 1-d (so a scalar can be joined with `torch.cat`), floats as float32, and on
122
+ the CPU."""
123
+ tensor = torch.atleast_1d(tensor.detach())
124
+ if tensor.is_floating_point():
125
+ tensor = tensor.float()
126
+ return tensor.to("cpu")
127
+
128
+
129
+ def batch_size_of(
130
+ targets: torch.Tensor | None, preds: torch.Tensor | Mapping[str, torch.Tensor] | None
131
+ ) -> int:
132
+ """How many examples a batch had, to weight its loss in the epoch's mean.
133
+
134
+ The last batch of a loader is often smaller than the rest: 1000 examples in batches of 64 leave one
135
+ of 40. The loss of a batch is a mean over its own examples, so a plain mean of the losses would count
136
+ that small batch as much as a full one. Weighting each loss by this count gives the mean over the
137
+ examples.
138
+
139
+ The size is the first dimension of the targets, else of the predictions (a tensor, or the first
140
+ tensor of a mapping) that the task returned for the batch. With neither, the batch counts as one.
141
+ """
142
+ if isinstance(targets, torch.Tensor) and targets.dim() > 0:
143
+ return int(targets.shape[0])
144
+ if isinstance(preds, torch.Tensor) and preds.dim() > 0:
145
+ return int(preds.shape[0])
146
+ if isinstance(preds, Mapping):
147
+ for tensor in preds.values():
148
+ if isinstance(tensor, torch.Tensor) and tensor.dim() > 0:
149
+ return int(tensor.shape[0])
150
+ return 1
@@ -0,0 +1,117 @@
1
+ """Where a fit is: what callbacks read, and what is saved to resume it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass, field
7
+ from typing import Any
8
+
9
+ import torch
10
+
11
+ from torchstack64.training.config import ParamValue
12
+ from torchstack64.training.results import BestCheckpoint, FitResult, FitStatus, Predictions, TrainingHistory
13
+
14
+
15
+ @dataclass(slots=True)
16
+ class FitState:
17
+ """Where the fit is: what callbacks read, and what `Trainer.save_state` writes to resume it."""
18
+
19
+ epoch: int = 0
20
+ optimization_step: int = 0
21
+ history: TrainingHistory = field(default_factory=TrainingHistory)
22
+ best: BestCheckpoint | None = None
23
+ patience: int = 0
24
+ should_stop: bool = False
25
+ stop_reason: str | None = None
26
+ status: FitStatus = FitStatus.RUNNING
27
+ error: BaseException | None = None
28
+ seconds: float = 0.0 # spent in earlier sessions of a resumed fit
29
+
30
+ def request_stop(self, reason: str, status: FitStatus = FitStatus.STOPPED) -> None:
31
+ if not self.should_stop:
32
+ self.should_stop = True
33
+ self.stop_reason = reason
34
+ self.status = status
35
+
36
+ def fail(self, error: BaseException) -> None:
37
+ self.error = error
38
+ if isinstance(error, KeyboardInterrupt):
39
+ self.status = FitStatus.INTERRUPTED
40
+ self.stop_reason = self.stop_reason or "interrupted"
41
+ else:
42
+ self.status = FitStatus.FAILED
43
+ self.stop_reason = f"{type(error).__name__}: {error}"
44
+
45
+ def result(self, monitor: str, seconds: float, params: Mapping[str, ParamValue]) -> FitResult:
46
+ return FitResult(
47
+ history=self.history,
48
+ status=self.status,
49
+ monitor=monitor,
50
+ best_epoch=self.best.epoch if self.best else None,
51
+ best_score=self.best.score if self.best else None,
52
+ best_predictions=self.best.predictions if self.best else None,
53
+ stop_reason=self.stop_reason,
54
+ epochs_run=len(self.history),
55
+ optimization_steps=self.optimization_step,
56
+ seconds=seconds,
57
+ error=None if self.error is None else f"{type(self.error).__name__}: {self.error}",
58
+ params=dict(params),
59
+ )
60
+
61
+ def state_dict(self, elapsed: float = 0.0) -> dict[str, Any]:
62
+ """Where the fit is, its history and the best epoch so far: what a resumed fit needs from here.
63
+
64
+ `elapsed` is the running session's time, added to what the earlier sessions spent. A stop request
65
+ and an error are not kept: a resumed fit starts running.
66
+ """
67
+ best = self.best
68
+ best_state = None
69
+ if best is not None:
70
+ predictions = best.predictions
71
+ best_state = {
72
+ "epoch": best.epoch,
73
+ "score": best.score,
74
+ "state": {
75
+ k: v.to("cpu") if isinstance(v, torch.Tensor) else v for k, v in best.state.items()
76
+ },
77
+ "predictions": None
78
+ if predictions is None
79
+ else {
80
+ "outputs": dict(predictions.outputs),
81
+ "targets": predictions.targets,
82
+ "ids": predictions.ids,
83
+ },
84
+ }
85
+ return {
86
+ "epoch": self.epoch,
87
+ "optimization_step": self.optimization_step,
88
+ "patience": self.patience,
89
+ "seconds": self.seconds + elapsed,
90
+ "history": [dict(entry) for entry in self.history.entries],
91
+ "best": best_state,
92
+ }
93
+
94
+ def load_state_dict(self, state: Mapping[str, Any], *, device: torch.device | str | None = None) -> None:
95
+ """Restores what `state_dict` wrote."""
96
+ self.epoch = int(state["epoch"])
97
+ self.optimization_step = int(state["optimization_step"])
98
+ self.patience = int(state["patience"])
99
+ self.seconds = float(state["seconds"])
100
+ self.history = TrainingHistory([dict(entry) for entry in state["history"]])
101
+ self.status = FitStatus.RUNNING
102
+ best = state["best"]
103
+ if best is not None:
104
+ weights = best["state"]
105
+ if device is not None:
106
+ weights = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in weights.items()}
107
+ payload = best["predictions"]
108
+ self.best = BestCheckpoint(
109
+ epoch=int(best["epoch"]),
110
+ score=float(best["score"]),
111
+ state=weights,
112
+ predictions=None
113
+ if payload is None
114
+ else Predictions(
115
+ outputs=dict(payload["outputs"]), targets=payload["targets"], ids=payload["ids"]
116
+ ),
117
+ )