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,40 @@
1
+ """Saves the training state every few epochs, so a long fit can be resumed after a crash or a restart."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ from torchstack64.callbacks.base import Callback
9
+
10
+ if TYPE_CHECKING:
11
+ from torchstack64.training.results import EpochResult
12
+ from torchstack64.training.trainer import Trainer
13
+
14
+
15
+ class Checkpointing(Callback):
16
+ """Writes `directory/last.pt` every `every_n_epochs` epochs and when the fit stops early.
17
+
18
+ Resume with `trainer.fit(train, val, resume_from=Checkpointing.latest(directory))`: when there is no
19
+ file yet, `latest` returns `None` and the fit starts from the beginning.
20
+ """
21
+
22
+ def __init__(self, directory: str | Path, *, every_n_epochs: int = 1, filename: str = "last.pt") -> None:
23
+ if every_n_epochs < 1:
24
+ raise ValueError("every_n_epochs must be at least 1")
25
+ self.directory = Path(directory)
26
+ self.every_n_epochs = every_n_epochs
27
+ self.filename = filename
28
+
29
+ @property
30
+ def path(self) -> Path:
31
+ return self.directory / self.filename
32
+
33
+ @staticmethod
34
+ def latest(directory: str | Path, filename: str = "last.pt") -> Path | None:
35
+ path = Path(directory) / filename
36
+ return path if path.is_file() else None
37
+
38
+ def on_epoch_end(self, trainer: Trainer[Any], result: EpochResult) -> None:
39
+ if result.epoch % self.every_n_epochs == 0 or trainer.state.should_stop:
40
+ trainer.save_state(self.path)
@@ -0,0 +1,160 @@
1
+ """The training curves of a fit: `training_curves` draws them as a matplotlib `Figure` without `pyplot`,
2
+ and `HistoryPlot` draws them when a fit ends."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import logging
7
+ import sys
8
+ import tempfile
9
+ from collections.abc import Callable, Mapping, Sequence
10
+ from pathlib import Path
11
+ from typing import TYPE_CHECKING, Any, Literal
12
+
13
+ from torchstack64.callbacks.base import Callback
14
+ from torchstack64.core import require, warn_once
15
+
16
+ if TYPE_CHECKING:
17
+ from matplotlib.figure import Figure
18
+
19
+ from torchstack64.training.results import FitResult
20
+ from torchstack64.training.trainer import Trainer
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ class HistoryPlot(Callback):
26
+ """Draws the training and validation losses and the monitored metric, epoch by epoch."""
27
+
28
+ def __init__(
29
+ self,
30
+ *,
31
+ save_dir: str | Path | None = None,
32
+ metrics: Sequence[str] | None = None,
33
+ log_to_mlflow: bool | Literal["auto"] = "auto",
34
+ on_figure: Callable[[Figure], None] | None = None,
35
+ display: bool = False,
36
+ title: str = "Training History",
37
+ dpi: int = 150,
38
+ ) -> None:
39
+ require("matplotlib", extra="plots", purpose="HistoryPlot")
40
+ self.save_dir = Path(save_dir) if save_dir is not None else None
41
+ self.metrics = list(metrics) if metrics is not None else None
42
+ self.log_to_mlflow = log_to_mlflow
43
+ self.on_figure = on_figure
44
+ self.display = display
45
+ self.title = title
46
+ self.dpi = dpi
47
+ self.figure: Figure | None = None
48
+
49
+ def on_train_end(self, trainer: Trainer[Any], result: FitResult) -> None:
50
+ history = result.history
51
+ if not len(history):
52
+ return
53
+ metrics = self.metrics
54
+ if metrics is None:
55
+ name = trainer.config.monitor.name
56
+ metrics = [name] if name != "val_loss" and name in history.columns else []
57
+ figure = training_curves(history, metrics, title=self.title)
58
+ self.figure = figure
59
+ if self.on_figure is not None:
60
+ self.on_figure(figure)
61
+ if self.display:
62
+ _show(figure)
63
+ if self.save_dir is not None:
64
+ self.save_dir.mkdir(parents=True, exist_ok=True)
65
+ figure.savefig(self.save_dir / "training_curves.png", dpi=self.dpi, bbox_inches="tight")
66
+ history.to_csv(self.save_dir / "history.csv")
67
+ if self._should_log():
68
+ self._log(figure, result)
69
+
70
+ def _should_log(self) -> bool:
71
+ if self.log_to_mlflow is False:
72
+ return False
73
+ if self.log_to_mlflow == "auto":
74
+ mlflow = sys.modules.get("mlflow")
75
+ if mlflow is None:
76
+ return False
77
+ else:
78
+ mlflow = require("mlflow", extra="mlflow", purpose="HistoryPlot(log_to_mlflow=True)")
79
+ try:
80
+ active = mlflow.active_run() is not None
81
+ except Exception:
82
+ active = False
83
+ if not active and self.log_to_mlflow is True:
84
+ warn_once(logger, "HistoryPlot was asked to log to MLflow, but no run is active")
85
+ return active
86
+
87
+ def _log(self, figure: Figure, result: FitResult) -> None:
88
+ mlflow = sys.modules["mlflow"]
89
+ with tempfile.TemporaryDirectory(prefix="torchstack64-plot-", ignore_cleanup_errors=True) as folder:
90
+ figure.savefig(Path(folder) / "training_curves.png", dpi=self.dpi, bbox_inches="tight")
91
+ result.history.to_csv(Path(folder) / "history.csv")
92
+ mlflow.log_artifacts(folder, artifact_path="plots")
93
+
94
+
95
+ def _show(figure: Figure) -> None:
96
+ try:
97
+ from IPython.display import display
98
+ except ImportError:
99
+ warn_once(logger, "HistoryPlot(display=True) needs IPython (a notebook); the figure is in .figure")
100
+ return
101
+ display(figure)
102
+
103
+
104
+ def training_curves(
105
+ history: Any,
106
+ metrics: Sequence[str] | None = None,
107
+ *,
108
+ title: str = "Training History",
109
+ figsize: tuple[float, float] | None = None,
110
+ ) -> Figure:
111
+ """The training and validation loss per epoch on the left axis, and each of `metrics` on the right.
112
+
113
+ `history` is a `TrainingHistory` (or a list of per-epoch dicts). Without `metrics`, every validation
114
+ column other than the loss is drawn. The figure is built with `matplotlib.figure.Figure`, so it never
115
+ changes pyplot's backend or list of open figures; in a notebook, a cell that ends with it shows it.
116
+ """
117
+ require("matplotlib", extra="plots", purpose="training_curves")
118
+ from matplotlib.figure import Figure
119
+ from matplotlib.ticker import MaxNLocator
120
+
121
+ entries: list[Mapping[str, float]] = list(getattr(history, "entries", history))
122
+ columns: dict[str, None] = {}
123
+ for entry in entries:
124
+ columns.update(dict.fromkeys(entry))
125
+ if metrics is None:
126
+ metrics = [name for name in columns if name.startswith("val_") and name != "val_loss"]
127
+ epochs = [int(entry.get("epoch", index + 1)) for index, entry in enumerate(entries)]
128
+
129
+ width = min(max(8.0, len(entries) * 0.25), 20.0)
130
+ figure = Figure(figsize=figsize or (width, 4.0), layout="tight")
131
+ loss_axis = figure.add_subplot()
132
+ style: dict[str, Any] = {"linewidth": 2, "marker": "o", "markersize": 3}
133
+ for name, label, color in (
134
+ ("train_loss", "Train loss", "tab:blue"),
135
+ ("val_loss", "Validation loss", "tab:cyan"),
136
+ ):
137
+ if name in columns:
138
+ loss_axis.plot(
139
+ epochs,
140
+ [entry.get(name, float("nan")) for entry in entries],
141
+ label=label,
142
+ color=color,
143
+ **style,
144
+ )
145
+ loss_axis.set(title=title, xlabel="Epoch", ylabel="Loss")
146
+ loss_axis.xaxis.set_major_locator(MaxNLocator(integer=True))
147
+ loss_axis.grid(True, alpha=0.4)
148
+ lines = list(loss_axis.get_lines())
149
+ present = [name for name in metrics if name in columns]
150
+ if present:
151
+ metric_axis = loss_axis.twinx()
152
+ palette = ["tab:orange", "tab:green", "tab:red", "tab:purple", "tab:brown"]
153
+ for index, name in enumerate(present):
154
+ values = [entry.get(name, float("nan")) for entry in entries]
155
+ metric_axis.plot(epochs, values, label=name, color=palette[index % len(palette)], **style)
156
+ metric_axis.set_ylabel(present[0] if len(present) == 1 else "Metric")
157
+ lines += list(metric_axis.get_lines())
158
+ if lines:
159
+ loss_axis.legend(lines, [str(line.get_label()) for line in lines], loc="best")
160
+ return figure
@@ -0,0 +1,217 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import math
5
+ import sys
6
+ import tempfile
7
+ import time
8
+ from collections.abc import Callable, Mapping
9
+ from pathlib import Path
10
+ from typing import TYPE_CHECKING, Any
11
+
12
+ from torchstack64.callbacks.base import Callback
13
+ from torchstack64.core import NoActiveRunError, require
14
+
15
+ if TYPE_CHECKING:
16
+ from torch import nn
17
+
18
+ from torchstack64.artifacts import ArtifactBundle
19
+ from torchstack64.training.results import EpochResult, FitResult, OptimizationStepRecord
20
+ from torchstack64.training.trainer import Trainer
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ BundleWriter = Callable[["nn.Module", Path], "ArtifactBundle | None"]
25
+ ParamValue = str | int | float | bool
26
+
27
+
28
+ class MLflowLogger(Callback):
29
+ """Logs a fit to the MLflow run that is already active. The notebook decides how runs are organized (one
30
+ per arm, nested under a parent), and this logger fills whichever run is active when the fit begins.
31
+
32
+ The trials of a `Tuner` are the one exception: the tuner starts those fits, so the notebook cannot open
33
+ a run for each. The logger opens it, `trial-<number>`, nested under the active one, and closes it when the
34
+ fit ends. Put the logger after the callbacks that log to MLflow themselves, such as `HistoryPlot`, as
35
+ `default_stack` does, or what they log at the end of a trial goes to the outer run.
36
+
37
+ What it logs:
38
+
39
+ - parameters: the fit's own (`trainer.params`, the same as `FitResult.params`: the `FitConfig`, the
40
+ task's fields, the device and precision actually used, the model's class and parameter counts),
41
+ and `params` (a dict or a dataclass of yours);
42
+ - tags: `tags`, the torchstack64 version, and at the end the fit's status and why it stopped;
43
+ - metrics: every column of each epoch (step = epoch), and every `log_every_n_steps` optimization steps
44
+ the training loss, the learning rate and the gradient norm (step = optimization step);
45
+ - at the end: the fit's duration, the best epoch and its score, the best epoch's validation
46
+ predictions as a table, and, if `bundle` is given, the bundle it writes from the final model (not for
47
+ a fit that failed, was interrupted or was pruned). Without `bundle`, no weights are kept.
48
+
49
+ `bundle(model, folder)` writes the bundle in a temporary folder, which is uploaded and then deleted:
50
+ nothing is written in the current directory. `save_bundle` with the validation data and the predictor
51
+ class is such a function
52
+ (`MLflowLogger(bundle=functools.partial(save_bundle, data=val, predictor=TorchClassifier))`), and its
53
+ bundle loads back with `load_trusted_predictor(f"runs:/{run_id}/model")`. A `save_bundle` given
54
+ without what it needs to prove the bundle is refused when the fit begins, not after its last epoch.
55
+ Without an active run, `required=True` (the default when you add it yourself) raises;
56
+ `required=False` makes it silent.
57
+ """
58
+
59
+ MAX_PARAM_LENGTH = 500 # a longer parameter value is cut, with "..." at its end
60
+
61
+ def __init__(
62
+ self,
63
+ *,
64
+ params: Mapping[str, Any] | Any = None,
65
+ tags: Mapping[str, str] | None = None,
66
+ log_every_n_steps: int | None = None,
67
+ bundle: BundleWriter | None = None,
68
+ artifact_path: str = "model",
69
+ log_predictions: bool = True,
70
+ predictions_file: str = "predictions/best_validation.json",
71
+ required: bool = True,
72
+ ) -> None:
73
+ if log_every_n_steps is not None and log_every_n_steps < 1:
74
+ raise ValueError("log_every_n_steps must be at least 1, or None")
75
+ self._module = require("mlflow", extra="mlflow", purpose="MLflowLogger") if required else None
76
+ self.params = params
77
+ self.tags = dict(tags or {})
78
+ self.log_every_n_steps = log_every_n_steps
79
+ self.bundle = bundle
80
+ self.artifact_path = artifact_path
81
+ self.log_predictions = log_predictions
82
+ self.predictions_file = predictions_file
83
+ self.required = required
84
+ self.active = False
85
+ self.run_id: str | None = None
86
+ self._opened = False # the active run is one this logger opened, for a trial
87
+
88
+ @property
89
+ def _mlflow(self) -> Any:
90
+ return self._module if self._module is not None else sys.modules.get("mlflow")
91
+
92
+ def _active_run(self) -> Any:
93
+ if self._mlflow is None:
94
+ return None
95
+ try:
96
+ return self._mlflow.active_run()
97
+ except Exception: # a tracking store that cannot be reached counts as no run
98
+ logger.debug("could not ask MLflow for the active run", exc_info=True)
99
+ return None
100
+
101
+ def on_train_begin(self, trainer: Trainer[Any]) -> None:
102
+ self._refuse_a_bundle_it_cannot_prove()
103
+ run = self._active_run()
104
+ self.active = run is not None
105
+ if not self.active:
106
+ if self.required:
107
+ raise NoActiveRunError(
108
+ "MLflowLogger needs an active MLflow run: open one with `with mlflow.start_run():`, "
109
+ "or pass required=False to log nothing without one"
110
+ )
111
+ logger.debug("no active MLflow run: nothing is logged for this fit")
112
+ return
113
+ trial = trainer.params.get("trial.number") # the tuner says so in the parameters of its fits
114
+ self._opened = trial is not None
115
+ if self._opened:
116
+ run = self._mlflow.start_run(run_name=f"trial-{trial}", nested=True)
117
+ self.run_id = getattr(getattr(run, "info", None), "run_id", None)
118
+ self._log_params(self._collect_params(trainer))
119
+ from torchstack64 import __version__
120
+
121
+ self._mlflow.set_tags({"torchstack64.version": __version__, **self.tags})
122
+
123
+ def _refuse_a_bundle_it_cannot_prove(self) -> None:
124
+ """A `save_bundle` without the validation data would fail after the whole fit, at its end; it is
125
+ refused here instead, before the first epoch. A writer of a project's own is not checked."""
126
+ if self.bundle is None:
127
+ return
128
+ from torchstack64.artifacts import missing_evidence # here: callbacks import without it
129
+
130
+ problem = missing_evidence(self.bundle)
131
+ if problem is not None:
132
+ raise ValueError(problem)
133
+
134
+ def _collect_params(self, trainer: Trainer[Any]) -> dict[str, ParamValue]:
135
+ """The fit's parameters, as the trainer recorded them, and `params`, each cut to MLflow's limit."""
136
+ params = dict(trainer.params)
137
+ if self.params is not None:
138
+ from torchstack64.training.config import flatten_params # here: callbacks import without torch
139
+
140
+ params.update(flatten_params(self.params))
141
+ return {name: self._cut(value) for name, value in params.items()}
142
+
143
+ @classmethod
144
+ def _cut(cls, value: ParamValue) -> ParamValue:
145
+ """MLflow refuses a parameter longer than its limit: a longer one is cut, ending with "..."."""
146
+ limit = cls.MAX_PARAM_LENGTH
147
+ if isinstance(value, str) and len(value) > limit:
148
+ return value[: limit - 3] + "..."
149
+ return value
150
+
151
+ def _log_params(self, params: Mapping[str, Any]) -> None:
152
+ try:
153
+ self._mlflow.log_params(dict(params))
154
+ except Exception as error: # e.g. a second fit in the same run with other values
155
+ logger.warning("MLflow refused the fit's parameters (%s); metrics are still logged", error)
156
+
157
+ def on_optimization_step_end(self, trainer: Trainer[Any], record: OptimizationStepRecord) -> None:
158
+ number = record.optimization_step
159
+ if not self.active or self.log_every_n_steps is None or number % self.log_every_n_steps:
160
+ return
161
+ metrics = {"step_train_loss": float(record.loss.item()), "step_lr": record.lr}
162
+ if record.grad_norm is not None:
163
+ metrics["step_grad_norm"] = float(record.grad_norm.item())
164
+ self._mlflow.log_metrics(_finite(metrics), step=number)
165
+
166
+ def on_epoch_end(self, trainer: Trainer[Any], result: EpochResult) -> None:
167
+ if not self.active:
168
+ return
169
+ metrics = dict(result.metrics)
170
+ metrics["epoch_seconds"] = result.seconds
171
+ self._mlflow.log_metrics(_finite(metrics), step=result.epoch)
172
+
173
+ def on_train_end(self, trainer: Trainer[Any], result: FitResult) -> None:
174
+ if not self.active:
175
+ return
176
+ self.active = False
177
+ try:
178
+ self._log_end(trainer, result)
179
+ finally:
180
+ if self._opened: # a pruned trial is how a search goes, not a failure
181
+ status = {"failed": "FAILED", "interrupted": "KILLED"}.get(result.status.value, "FINISHED")
182
+ self._mlflow.end_run(status)
183
+
184
+ def _log_end(self, trainer: Trainer[Any], result: FitResult) -> None:
185
+ from torchstack64.training.results import FitStatus
186
+
187
+ mlflow = self._mlflow
188
+ mlflow.set_tags(
189
+ {"torchstack64.status": result.status.value, "torchstack64.stop_reason": result.stop_reason or ""}
190
+ )
191
+ summary = {"fit_seconds": result.seconds, "epochs_run": float(result.epochs_run)}
192
+ if result.best_epoch is not None and result.best_score is not None:
193
+ summary["best_epoch"] = float(result.best_epoch)
194
+ summary[f"best_{result.monitor}"] = result.best_score
195
+ mlflow.log_metrics(_finite(summary))
196
+ if self.log_predictions and result.best_predictions is not None and len(result.best_predictions):
197
+ mlflow.log_table(data=result.best_predictions.columns(), artifact_file=self.predictions_file)
198
+ unserved = (FitStatus.FAILED, FitStatus.INTERRUPTED, FitStatus.PRUNED)
199
+ if self.bundle is not None and result.status not in unserved:
200
+ self._log_bundle(trainer)
201
+
202
+ def _log_bundle(self, trainer: Trainer[Any]) -> None:
203
+ assert self.bundle is not None
204
+ with tempfile.TemporaryDirectory(prefix="torchstack64-bundle-", ignore_cleanup_errors=True) as folder:
205
+ target = Path(folder) / "bundle"
206
+ started = time.perf_counter()
207
+ written = self.bundle(trainer.model, target)
208
+ root = written.root if written is not None and hasattr(written, "root") else target
209
+ self._mlflow.log_artifacts(str(root), artifact_path=self.artifact_path)
210
+ logger.info(
211
+ "bundle logged to MLflow under %r in %.1fs", self.artifact_path, time.perf_counter() - started
212
+ )
213
+
214
+
215
+ def _finite(metrics: Mapping[str, float]) -> dict[str, float]:
216
+ """MLflow stores NaN, but a NaN column only hides the rest of a chart: those values are left out."""
217
+ return {name: float(value) for name, value in metrics.items() if math.isfinite(float(value))}