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,82 @@
1
+ """The names of a search's space: what each one points at, and how a value gets there."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import dataclasses
7
+ import inspect
8
+ from collections.abc import Callable, Mapping
9
+ from typing import TYPE_CHECKING, Any
10
+
11
+ from torchstack64.core import require
12
+ from torchstack64.training.config import FitConfig, SearchConfig, flatten_params
13
+
14
+ if TYPE_CHECKING:
15
+ import optuna
16
+ from optuna.distributions import BaseDistribution
17
+
18
+
19
+ def distributions(search: SearchConfig) -> dict[str, BaseDistribution]:
20
+ """The space as Optuna takes it: a list becomes a categorical distribution."""
21
+ categorical = require("optuna", extra="optuna", purpose="Tuner").distributions.CategoricalDistribution
22
+ return {n: categorical(v) if isinstance(v, list) else v for n, v in search.space.items()}
23
+
24
+
25
+ def suggest(trial: optuna.Trial, name: str, values: BaseDistribution) -> Any:
26
+ """What the study proposes for `name` in this trial."""
27
+ kinds = require("optuna", extra="optuna", purpose="Tuner").distributions
28
+ if isinstance(values, kinds.FloatDistribution):
29
+ return trial.suggest_float(name, values.low, values.high, step=values.step, log=values.log)
30
+ if isinstance(values, kinds.IntDistribution):
31
+ return trial.suggest_int(name, values.low, values.high, step=values.step, log=values.log)
32
+ return trial.suggest_categorical(name, values.choices) # type: ignore[attr-defined]
33
+
34
+
35
+ def place(values: Mapping[str, Any], task: Any, config: FitConfig) -> tuple[dict[str, Any], Any, FitConfig]:
36
+ """The network's arguments, the task and the config with `values` in place. The ones given stay as
37
+ they are: the task is copied, so one that keeps something between epochs starts each fit without it."""
38
+ arguments: dict[str, Any] = {}
39
+ task = copy.deepcopy(task)
40
+ for name, value in values.items():
41
+ part, _, path = name.partition(".")
42
+ if part == "model":
43
+ arguments[path] = value
44
+ elif part == "task":
45
+ task = _replace(task, path, value)
46
+ elif part == "fit":
47
+ config = _replace(config, path, value)
48
+ else:
49
+ raise ValueError(f"{name!r}: a name starts with 'model.', 'task.' or 'fit.'")
50
+ return arguments, task, config
51
+
52
+
53
+ def check_space(
54
+ space: Mapping[str, BaseDistribution], model: Callable[..., Any], task: Any, config: FitConfig
55
+ ) -> None:
56
+ """Refuses a name that points at nothing, and a range whose ends the configuration refuses."""
57
+ arguments = inspect.signature(model).parameters.values()
58
+ any_argument = any(p.kind is p.VAR_KEYWORD for p in arguments)
59
+ known = [f"model.{p.name}" for p in arguments if p.kind not in (p.VAR_KEYWORD, p.VAR_POSITIONAL)]
60
+ known += [*flatten_params(task, "task"), *flatten_params(config, "fit")]
61
+ for name, values in space.items():
62
+ part = name.partition(".")[0]
63
+ if name.startswith("fit.monitor"):
64
+ raise ValueError("the monitor scores the trials, so it cannot change between them")
65
+ if name not in known and not (part == "model" and any_argument):
66
+ here = [n for n in known if n.startswith(f"{part}.") and not n.startswith("fit.monitor")]
67
+ raise ValueError(
68
+ f"nothing is called {name!r}; the names under {part!r} are {', '.join(here) or 'none'}"
69
+ )
70
+ if part != "model":
71
+ choices = getattr(values, "choices", None)
72
+ for value in choices if choices is not None else (values.low, values.high): # type: ignore[attr-defined]
73
+ place({name: value}, task, config)
74
+
75
+
76
+ def _replace(obj: Any, path: str, value: Any) -> Any:
77
+ """A copy of `obj` with the value at `path` changed, through the dataclasses and the mappings on the way:
78
+ the same steps `flatten_params` takes to name it."""
79
+ name, _, rest = path.partition(".")
80
+ if isinstance(obj, Mapping):
81
+ return {**obj, name: _replace(obj[name], rest, value) if rest else value}
82
+ return dataclasses.replace(obj, **{name: _replace(getattr(obj, name), rest, value) if rest else value})
@@ -0,0 +1,137 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from collections.abc import Callable, Iterable, Mapping, Sequence
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from torch import nn
8
+
9
+ from torchstack64.core import require
10
+ from torchstack64.training.config import FitConfig, SearchConfig
11
+ from torchstack64.training.results import FitStatus
12
+ from torchstack64.training.runtime import seed_everything
13
+ from torchstack64.training.trainer import Trainer
14
+ from torchstack64.training.tuner.callback import TrialCallback
15
+ from torchstack64.training.tuner.space import check_space, distributions, place, suggest
16
+
17
+ if TYPE_CHECKING:
18
+ import optuna
19
+
20
+
21
+ class Tuner:
22
+ """Searches for the values that train best: each trial is one fit of a new network, with the values
23
+ the study proposed.
24
+
25
+ It takes what `Trainer` takes, with two differences: `model` is the network's class, or a function
26
+ that builds one, since each trial needs new weights, and `search` says what varies: the arguments of
27
+ that class or function are `model.<argument>` in the space. `callbacks` are given to every trial's
28
+ fit. The names in the space, and the ends of each range, are checked here, before anything trains.
29
+
30
+ After `search(train, val)`, or when it is interrupted, `study` is Optuna's study and `best_trainer` the
31
+ trainer of its best trial. That one is a finished fit: its network has the weights of its best epoch,
32
+ ready to evaluate and to save.
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ model: Callable[..., nn.Module],
38
+ task: Any,
39
+ config: FitConfig,
40
+ search: SearchConfig,
41
+ callbacks: Sequence[Any] = (),
42
+ ) -> None:
43
+ if isinstance(model, nn.Module):
44
+ raise TypeError(
45
+ "Tuner takes the network's class, or a function that builds one, not a network: each trial "
46
+ f"needs new weights. Pass the class, `{type(model).__name__}`, and the search varies its "
47
+ "arguments as `model.<argument>`"
48
+ )
49
+ self.model = model
50
+ self.task = task
51
+ self.config = config
52
+ self.search_config = search
53
+ self.callbacks = list(callbacks)
54
+ self.study: optuna.Study | None = None
55
+ self.best_trainer: Trainer[Any] | None = None
56
+ self._running: Trainer[Any] | None = None # the trial's whose score the study has not seen yet
57
+ self._space = distributions(search)
58
+ check_space(self._space, model, task, config)
59
+
60
+ def build_trainer(self, values: Mapping[str, Any], callbacks: Sequence[Any] = ()) -> Trainer[Any]:
61
+ """A trainer that has not run, with `values` in place: what each trial trains, and how to train
62
+ `study.best_params` again. Any name works, varied or not:
63
+ `build_trainer({**study.best_params, "fit.epochs": 50})`."""
64
+ arguments, task, config = place(values, self.task, self.config)
65
+ if config.seed is not None:
66
+ seed_everything(config.seed) # the weights a network starts with are drawn when it is built
67
+ return Trainer(self.model(**arguments), task, config, callbacks)
68
+
69
+ def search(
70
+ self, train: Iterable[Any], val: Iterable[Any], *, study: optuna.Study | None = None
71
+ ) -> optuna.Study:
72
+ """Runs the trials and returns the study, which stays in `self.study` too. `study` runs them in one
73
+ there is already: an earlier search's, or one of your own (kept on disk, say, or with another
74
+ sampler)."""
75
+ study = self._new_study() if study is None else self._checked(study)
76
+ if study is not self.study:
77
+ self.study, self.best_trainer = study, None
78
+ try:
79
+ study.optimize(
80
+ lambda trial: self._fit(trial, train, val),
81
+ n_trials=self.search_config.n_trials,
82
+ callbacks=[self._keep_the_best],
83
+ )
84
+ finally:
85
+ self._running = None
86
+ return study
87
+
88
+ @property
89
+ def _direction(self) -> str:
90
+ return "maximize" if self.config.monitor.mode == "max" else "minimize"
91
+
92
+ def _new_study(self) -> optuna.Study:
93
+ optuna = require("optuna", extra="optuna", purpose="Tuner")
94
+ sampler = optuna.samplers.TPESampler(seed=self.config.seed)
95
+ return optuna.create_study(
96
+ direction=self._direction, sampler=sampler, pruner=self.search_config.pruner
97
+ )
98
+
99
+ def _checked(self, study: optuna.Study) -> optuna.Study:
100
+ if [direction.name.lower() for direction in study.directions] != [self._direction]:
101
+ raise ValueError(
102
+ f"{self.config.monitor.name} asks for a study with direction={self._direction!r} alone; this "
103
+ f"one has {', '.join(direction.name.lower() for direction in study.directions)}"
104
+ )
105
+ return study
106
+
107
+ def _fit(self, trial: optuna.Trial, train: Iterable[Any], val: Iterable[Any]) -> float:
108
+ """One trial: one fit, whose best score is what the study compares."""
109
+ optuna = require("optuna", extra="optuna", purpose="Tuner")
110
+ values = {name: suggest(trial, name, where) for name, where in self._space.items()}
111
+ self._running = trainer = self.build_trainer(values, [TrialCallback(trial), *self.callbacks])
112
+ try:
113
+ result = trainer.fit(train, val)
114
+ finally:
115
+ trainer.callbacks = list(self.callbacks) # the trial is over: another fit of it is not a trial
116
+ for name, value in _outcome(trainer).items():
117
+ trial.set_user_attr(name, value)
118
+ if result.status is FitStatus.PRUNED:
119
+ raise optuna.TrialPruned(result.stop_reason)
120
+ return result.best_score if result.best_score is not None else math.nan # Optuna's failed trial
121
+
122
+ def _keep_the_best(self, study: optuna.Study, trial: optuna.trial.FrozenTrial) -> None:
123
+ assert self._running is not None
124
+ self._running.model.to("cpu") # off the GPU before the next network; the best one waits there
125
+ if trial.state.name == "COMPLETE" and study.best_trial.number == trial.number:
126
+ self.best_trainer = self._running
127
+
128
+
129
+ def _outcome(trainer: Trainer[Any]) -> dict[str, Any]:
130
+ """How a trial's fit ended, which `study.trials_dataframe()` shows next to its values."""
131
+ state = trainer.state
132
+ return {
133
+ "status": state.status.value,
134
+ "best_epoch": state.best.epoch if state.best is not None else None,
135
+ "epochs_run": len(state.history),
136
+ "stop_reason": state.stop_reason,
137
+ }
@@ -0,0 +1,21 @@
1
+ """Shortcuts for the setup around a fit: the library's log shown in a notebook, an MLflow store, and the runs
2
+ a series of fits leaves in it.
3
+
4
+ Each helper does what a notebook would otherwise write by hand, and returns the outside library's own
5
+ objects (a `logging.Handler`, an MLflow `Experiment` or `Run`), so the code after it is plain `logging` or
6
+ MLflow. None of them is the only way: the callbacks work the same without them. MLflow is imported when a
7
+ helper is called, not when this package is.
8
+ """
9
+
10
+ from torchstack64.utils.logging import disable_console, enable_console, quiet, set_verbosity
11
+ from torchstack64.utils.mlflow import best_run, child_runs, local_experiment
12
+
13
+ __all__ = [
14
+ "best_run",
15
+ "child_runs",
16
+ "disable_console",
17
+ "enable_console",
18
+ "local_experiment",
19
+ "quiet",
20
+ "set_verbosity",
21
+ ]
@@ -0,0 +1,85 @@
1
+ """The switches for the library's log, for a notebook or a script that configures no logging of its own.
2
+
3
+ They change the `torchstack64` logger that `torchstack64.core.logging` sets up, and nothing else: an
4
+ application that configures logging needs none of them.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import sys
11
+ from collections.abc import Iterator
12
+ from contextlib import contextmanager
13
+ from typing import TextIO
14
+
15
+ from torchstack64.core import DEFAULT_FORMAT, LOGGER_NAME, LogLevel, log_level
16
+
17
+ _console: logging.Handler | None = None
18
+ _levels = (logging.NOTSET, logging.NOTSET) # the level enable_console() found, and the one it set
19
+
20
+
21
+ class _CurrentStderr(logging.StreamHandler[TextIO]):
22
+ """Writes each record to the `sys.stderr` of that moment: a notebook replaces it as it goes."""
23
+
24
+ def emit(self, record: logging.LogRecord) -> None:
25
+ self.stream = sys.stderr
26
+ super().emit(record)
27
+
28
+
29
+ def set_verbosity(level: LogLevel | int) -> None:
30
+ """Shows the library's records from `level` up, as `TORCHSTACK64_LOG_LEVEL` does when the library is
31
+ imported: `set_verbosity("INFO")` shows each fit's start and end, `"DEBUG"` every epoch.
32
+ `logging.NOTSET` gives the choice back to the root logger. A name is read in any case."""
33
+ logging.getLogger(LOGGER_NAME).setLevel(log_level(level))
34
+
35
+
36
+ @contextmanager
37
+ def quiet(level: LogLevel | int = logging.WARNING) -> Iterator[None]:
38
+ """Shows only the library's records from `level` up inside the block, then puts the level back:
39
+ a loop of fits without two lines per fit, warnings and errors still shown."""
40
+ number = log_level(level) # a wrong level fails here, before the block changes anything
41
+ logger = logging.getLogger(LOGGER_NAME)
42
+ previous = logger.level
43
+ logger.setLevel(number)
44
+ try:
45
+ yield
46
+ finally:
47
+ logger.setLevel(previous)
48
+
49
+
50
+ def enable_console(
51
+ level: LogLevel | int = logging.INFO, *, stream: TextIO | None = None, fmt: str = DEFAULT_FORMAT
52
+ ) -> logging.Handler:
53
+ """Prints the library's records from `level` up in `fmt`, on stderr unless `stream` is given.
54
+
55
+ `set_verbosity` alone already shows them on stderr; this is for another stream or format. While this
56
+ handler is on, the library's own stderr handler stays silent, so no line is printed twice. Calling
57
+ it again replaces the handler instead of adding a second one, so a notebook cell can run twice.
58
+ Records still propagate to the root logger, so an application's own handlers keep receiving them.
59
+ `disable_console()` undoes it, the level included.
60
+ """
61
+ global _console, _levels
62
+ number = log_level(level) # a wrong level fails here, before the console in use is removed
63
+ logger = logging.getLogger(LOGGER_NAME)
64
+ disable_console()
65
+ handler = logging.StreamHandler(stream) if stream is not None else _CurrentStderr()
66
+ handler.setFormatter(logging.Formatter(fmt))
67
+ logger.addHandler(handler)
68
+ _console, _levels = handler, (logger.level, number)
69
+ logger.setLevel(number)
70
+ return handler
71
+
72
+
73
+ def disable_console() -> None:
74
+ """Undoes `enable_console()`, if it is on: its handler goes, the library's stderr handler takes over
75
+ again, and the level is the one it found. A level chosen since, with `set_verbosity`, stays."""
76
+ global _console
77
+ if _console is None:
78
+ return
79
+ logger = logging.getLogger(LOGGER_NAME)
80
+ logger.removeHandler(_console)
81
+ _console.close()
82
+ _console = None
83
+ found, chosen = _levels
84
+ if logger.level == chosen:
85
+ logger.setLevel(found)
@@ -0,0 +1,127 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import math
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING, Any, Literal
7
+ from urllib.parse import urlsplit
8
+ from urllib.request import url2pathname
9
+
10
+ from torchstack64.core import require
11
+
12
+ if TYPE_CHECKING:
13
+ import pandas as pd
14
+ from mlflow.entities import Experiment, Run
15
+
16
+ from torchstack64.training import Monitor
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ STORE_FILE = "mlflow.db"
21
+ ARTIFACTS_FOLDER = "mlartifacts"
22
+ # Fits a best run is never picked from: they log no bundle, and a search keeps only the trials it finished,
23
+ # as Optuna's `best_trial` does.
24
+ _LEFT_OUT = ("failed", "interrupted", "pruned")
25
+
26
+
27
+ def local_experiment(name: str, folder: str | Path) -> Experiment:
28
+ """Points MLflow at a store kept in `folder` and makes `name` the active experiment, creating both if
29
+ they are missing. Returns the experiment, as `mlflow.set_experiment` does.
30
+
31
+ The store is a SQLite file, `folder/mlflow.db`, with the artifacts beside it in `folder/mlartifacts`,
32
+ so the whole history of a project is one folder. `mlflow ui --backend-store-uri sqlite:///<folder>/mlflow.db`
33
+ opens it. Like `mlflow.set_tracking_uri`, this sets the tracking URI of the whole process: call it once,
34
+ at the top of a notebook. For a tracking server, MLflow's own `set_tracking_uri` and `set_experiment`
35
+ are all it takes.
36
+
37
+ An experiment keeps its artifacts where it was created, for good. When that is not this folder (the folder
38
+ was moved, or the experiment was made by hand before), a warning says where they go.
39
+ """
40
+ mlflow = require("mlflow", extra="mlflow", purpose="local_experiment")
41
+ folder = Path(folder).resolve()
42
+ folder.mkdir(parents=True, exist_ok=True)
43
+ artifacts = folder / ARTIFACTS_FOLDER
44
+ mlflow.set_tracking_uri("sqlite:///" + (folder / STORE_FILE).as_posix())
45
+ experiment = mlflow.get_experiment_by_name(name)
46
+ if experiment is None:
47
+ # Without an artifact location MLflow would put the artifacts in the current directory.
48
+ mlflow.create_experiment(name, artifact_location=artifacts.as_uri())
49
+ elif not _is_folder(experiment.artifact_location, artifacts):
50
+ logger.warning(
51
+ "experiment %r keeps its artifacts in %s, not in %s, and MLflow cannot change that: new runs "
52
+ "write theirs there, and earlier ones look for theirs there. Use another experiment name to keep "
53
+ "everything in one folder",
54
+ name,
55
+ experiment.artifact_location,
56
+ artifacts,
57
+ )
58
+ return mlflow.set_experiment(name)
59
+
60
+
61
+ def _is_folder(location: str, folder: Path) -> bool:
62
+ """Whether an artifact location, a `file:` URI or a path as MLflow writes them, is `folder`."""
63
+ if location == folder.as_uri():
64
+ return True
65
+ parts = urlsplit(location)
66
+ if parts.scheme == "file":
67
+ return Path(url2pathname(parts.path)) == folder
68
+ return len(parts.scheme) < 2 and Path(location) == folder # one letter is a Windows drive, not a scheme
69
+
70
+
71
+ def child_runs(parent: Any) -> pd.DataFrame:
72
+ """The runs nested under `parent`, one row each, as `mlflow.search_runs` returns them: columns such as
73
+ `params.task.optim.lr`, `metrics.best_val_loss` and `tags.torchstack64.status`.
74
+
75
+ `parent` is a run id, a `Run`, or what `with mlflow.start_run() as parent:` gives.
76
+ """
77
+ mlflow = require("mlflow", extra="mlflow", purpose="child_runs")
78
+ return _nested_under(_run_id(parent), mlflow, "pandas")
79
+
80
+
81
+ def best_run(parent: Any, monitor: Monitor) -> Run:
82
+ """The run nested under `parent` with the best score for `monitor`: the `best_<monitor name>` metric
83
+ that `MLflowLogger` logs when a fit ends, the highest or the lowest as the monitor's mode says.
84
+
85
+ Runs whose fit failed, was interrupted or was pruned are left out: they carry no bundle, and a search
86
+ keeps only the trials it finished, so the pick agrees with Optuna's `study.best_trial`. When the logger
87
+ was given a `bundle`, the one of the run that comes back loads with `MLflowRunSource(run.info.run_id)`.
88
+ Raises `LookupError` when no nested run has that metric.
89
+ """
90
+ mlflow = require("mlflow", extra="mlflow", purpose="best_run")
91
+ run_id = _run_id(parent)
92
+ metric = f"best_{monitor.name}"
93
+ runs = _nested_under(run_id, mlflow, "list")
94
+ scored = [
95
+ (run.data.metrics[metric], run)
96
+ for run in runs
97
+ if math.isfinite(run.data.metrics.get(metric, math.nan))
98
+ and run.data.tags.get("torchstack64.status") not in _LEFT_OUT
99
+ ]
100
+ if not scored:
101
+ raise LookupError(
102
+ f"none of the {len(runs)} runs nested under {run_id} has the metric {metric!r} from a fit "
103
+ "that was not failed, interrupted or pruned; MLflowLogger logs it when a fit validates "
104
+ "with that monitor"
105
+ )
106
+ pick = max if monitor.mode == "max" else min
107
+ return pick(scored, key=lambda pair: pair[0])[1]
108
+
109
+
110
+ def _nested_under(run_id: str, mlflow: Any, output_format: Literal["pandas", "list"]) -> Any:
111
+ """The runs nested under `run_id`, looked for in its own experiment, whichever one is active."""
112
+ return mlflow.search_runs(
113
+ experiment_ids=[mlflow.get_run(run_id).info.experiment_id],
114
+ filter_string=f"tags.mlflow.parentRunId = '{run_id}'",
115
+ output_format=output_format,
116
+ )
117
+
118
+
119
+ def _run_id(run: Any) -> str:
120
+ """The id of a run given as an id, a `Run` or an `ActiveRun`."""
121
+ if isinstance(run, str):
122
+ return run
123
+ info = getattr(run, "info", None)
124
+ run_id = getattr(info, "run_id", None)
125
+ if not isinstance(run_id, str):
126
+ raise TypeError(f"expected a run id, a Run or an ActiveRun; got {type(run).__name__}")
127
+ return run_id