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,121 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class TorchstackError(Exception):
|
|
7
|
+
"""The base of every error raised on purpose. `context` carries free details for the log."""
|
|
8
|
+
|
|
9
|
+
def __init__(self, message: str, **context: object) -> None:
|
|
10
|
+
super().__init__(message)
|
|
11
|
+
self.message = message
|
|
12
|
+
self.context = dict(context)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class MissingExtraError(TorchstackError, ImportError):
|
|
16
|
+
"""Install an optional dependency: the message names the extra and the pip line."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, module: str, *, extra: str, purpose: str | None = None) -> None:
|
|
19
|
+
needs = f"{purpose} needs" if purpose else "This needs"
|
|
20
|
+
message = (
|
|
21
|
+
f"{needs} the optional dependency {module!r}, which is not installed. "
|
|
22
|
+
f"Install it with: pip install 'torchstack64[{extra}]'"
|
|
23
|
+
)
|
|
24
|
+
if extra == "training":
|
|
25
|
+
message += (
|
|
26
|
+
". For a GPU, install the CUDA build of PyTorch first, from the index that "
|
|
27
|
+
"https://pytorch.org/get-started/locally/ gives for your machine: the default "
|
|
28
|
+
"wheel on Windows only runs on the CPU"
|
|
29
|
+
)
|
|
30
|
+
super().__init__(message, module=module, extra=extra)
|
|
31
|
+
self.name = module
|
|
32
|
+
self.extra = extra
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class DeviceUnavailableError(TorchstackError, RuntimeError):
|
|
36
|
+
"""Choose another device: the one asked for does not exist on this machine."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class NoActiveRunError(TorchstackError, RuntimeError):
|
|
40
|
+
"""Open an MLflow run first (`mlflow.start_run()`), or let the logger stay silent without one."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class CheckpointError(TorchstackError):
|
|
44
|
+
"""A saved training state that cannot resume this trainer: another model, another task."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class BundleError(TorchstackError):
|
|
48
|
+
"""A bundle that cannot be read or written as asked."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class BundleNotFoundError(BundleError, FileNotFoundError):
|
|
52
|
+
"""Point at a folder that holds a `bundle.json`."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class BundleExistsError(BundleError, FileExistsError):
|
|
56
|
+
"""Choose an empty folder, or pass `overwrite=True` to replace the bundle that is there."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class BundleIntegrityError(BundleError):
|
|
60
|
+
"""Download or write the bundle again: its files are not the ones its manifest describes."""
|
|
61
|
+
|
|
62
|
+
def __init__(
|
|
63
|
+
self,
|
|
64
|
+
message: str,
|
|
65
|
+
*,
|
|
66
|
+
missing: Sequence[str] = (),
|
|
67
|
+
changed: Sequence[str] = (),
|
|
68
|
+
unexpected: Sequence[str] = (),
|
|
69
|
+
) -> None:
|
|
70
|
+
super().__init__(message, missing=list(missing), changed=list(changed), unexpected=list(unexpected))
|
|
71
|
+
self.missing = list(missing)
|
|
72
|
+
self.changed = list(changed)
|
|
73
|
+
self.unexpected = list(unexpected)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class TrustRequiredError(BundleError):
|
|
77
|
+
"""This bundle keeps its network and its preparation as Python objects, and reading them runs code: trust
|
|
78
|
+
where it came from (`load_trusted_predictor`), or bring the code yourself through the class that reads it
|
|
79
|
+
(`Class.load(folder, network=..., prepare=...)`)."""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class CodeConflictError(BundleError, ImportError):
|
|
83
|
+
"""Load this bundle in a process of its own: the process already imported another version of a
|
|
84
|
+
module the bundle's code carries, or imported it before its files changed on disk, and one process
|
|
85
|
+
holds one version of each module."""
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class MissingDependencyError(BundleError, ImportError):
|
|
89
|
+
"""Install the packages the bundle's code imports: the message has the `pip` line, with the versions
|
|
90
|
+
that wrote the bundle."""
|
|
91
|
+
|
|
92
|
+
def __init__(self, message: str, *, missing: Sequence[str]) -> None:
|
|
93
|
+
super().__init__(message, missing=list(missing))
|
|
94
|
+
self.missing = list(missing)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class ProofError(BundleError):
|
|
98
|
+
"""Find what differs between the model that was trained and the one the bundle serves: the message
|
|
99
|
+
names the proof that failed, the first example where the two differ, by how much, and the usual causes.
|
|
100
|
+
|
|
101
|
+
`proof` is the name the manifest records it under (`preparation`, `round_trip`, `batch`...), and `example`
|
|
102
|
+
the position of that first example in the bundle's example, or `None` for a proof that needs none.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
def __init__(self, message: str, *, proof: str, example: int | None = None, **context: object) -> None:
|
|
106
|
+
super().__init__(message, proof=proof, example=example, **context)
|
|
107
|
+
self.proof = proof
|
|
108
|
+
self.example = example
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class UnknownArtifactError(BundleError, ValueError):
|
|
112
|
+
"""Fix the logical name: the message lists the names the bundle has."""
|
|
113
|
+
|
|
114
|
+
def __init__(self, name: str, known: Sequence[str], root: object) -> None:
|
|
115
|
+
super().__init__(
|
|
116
|
+
f"The bundle at {root} has no artifact named {name!r}; known artifacts: {sorted(known)}",
|
|
117
|
+
name=name,
|
|
118
|
+
known=sorted(known),
|
|
119
|
+
)
|
|
120
|
+
self.name = name
|
|
121
|
+
self.known = sorted(known)
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""The evaluation seam: a `Metric` is anything with a name and a `compute(y_true, y_pred)`.
|
|
2
|
+
|
|
3
|
+
Nothing here does I/O or talks to a tracking server: compose metrics, compute them, get numbers back
|
|
4
|
+
(`mlflow.log_metrics(result.values)` records them).
|
|
5
|
+
A project's own metric (a domain-specific average precision, say) needs no base class; it only has to
|
|
6
|
+
look like this protocol.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Sequence
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Protocol, runtime_checkable
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@runtime_checkable
|
|
17
|
+
class Metric(Protocol):
|
|
18
|
+
"""A named, scalar evaluation metric."""
|
|
19
|
+
|
|
20
|
+
name: str
|
|
21
|
+
|
|
22
|
+
def compute(self, y_true: Sequence, y_pred: Sequence) -> float:
|
|
23
|
+
"""One number for `y_true` against `y_pred`."""
|
|
24
|
+
...
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(slots=True)
|
|
28
|
+
class EvaluationResult:
|
|
29
|
+
"""A flat bag of named metric values produced by an `Evaluator`."""
|
|
30
|
+
|
|
31
|
+
values: dict[str, float] = field(default_factory=dict)
|
|
32
|
+
|
|
33
|
+
def __getitem__(self, key: str) -> float:
|
|
34
|
+
return self.values[key]
|
|
35
|
+
|
|
36
|
+
def __contains__(self, key: str) -> bool:
|
|
37
|
+
return key in self.values
|
|
38
|
+
|
|
39
|
+
def get(self, key: str, default: float | None = None) -> float | None:
|
|
40
|
+
return self.values.get(key, default)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Evaluator:
|
|
44
|
+
"""Runs a fixed list of metrics over the same `(y_true, y_pred)` pair."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, metrics: Sequence[Metric]) -> None:
|
|
47
|
+
self.metrics = list(metrics)
|
|
48
|
+
|
|
49
|
+
def evaluate(self, y_true: Sequence, y_pred: Sequence) -> EvaluationResult:
|
|
50
|
+
return EvaluationResult(
|
|
51
|
+
values={metric.name: metric.compute(y_true, y_pred) for metric in self.metrics}
|
|
52
|
+
)
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Optional dependencies, imported where they are used and explained when they are missing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
from types import ModuleType
|
|
7
|
+
|
|
8
|
+
from torchstack64.core.errors import MissingExtraError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def require(module: str, *, extra: str, purpose: str | None = None) -> ModuleType:
|
|
12
|
+
"""Imports `module`, or raises `MissingExtraError` naming the extra that installs it.
|
|
13
|
+
|
|
14
|
+
A missing module *inside* an installed package (a broken install) is a different problem, and
|
|
15
|
+
keeps its own `ModuleNotFoundError`.
|
|
16
|
+
"""
|
|
17
|
+
try:
|
|
18
|
+
return importlib.import_module(module)
|
|
19
|
+
except ModuleNotFoundError as error:
|
|
20
|
+
missing_root = (error.name or "").split(".")[0]
|
|
21
|
+
if missing_root and missing_root != module.split(".")[0]:
|
|
22
|
+
raise
|
|
23
|
+
raise MissingExtraError(module.split(".")[0], extra=extra, purpose=purpose) from error
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def is_installed(module: str) -> bool:
|
|
27
|
+
"""Whether `module` can be imported, without importing it."""
|
|
28
|
+
import importlib.util
|
|
29
|
+
import sys
|
|
30
|
+
|
|
31
|
+
if module in sys.modules:
|
|
32
|
+
return sys.modules[module] is not None
|
|
33
|
+
try:
|
|
34
|
+
return importlib.util.find_spec(module) is not None
|
|
35
|
+
except (ImportError, ValueError):
|
|
36
|
+
return False
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""What serving code calls: raw inputs in, one answer per input out.
|
|
2
|
+
|
|
3
|
+
A predictor hides everything its model needs (cleaning, tokenizing, batching, the device), so the
|
|
4
|
+
service only ever sees `predict(inputs)`. The answer's type is a parameter: a classifier answers with
|
|
5
|
+
labels, a scorer with probabilities, a multi-head model with records.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Sequence
|
|
11
|
+
from typing import TYPE_CHECKING, Protocol, runtime_checkable
|
|
12
|
+
|
|
13
|
+
from torchstack64.core.labels import LabelSchema
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from torchstack64.artifacts import ArtifactBundle
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@runtime_checkable
|
|
20
|
+
class Predictor[InputT, OutputT](Protocol):
|
|
21
|
+
"""The serving interface every kind of model implements."""
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def label_schema(self) -> LabelSchema | None:
|
|
25
|
+
"""The classes it answers with, or `None` for a model that does not classify."""
|
|
26
|
+
...
|
|
27
|
+
|
|
28
|
+
def predict(self, inputs: Sequence[InputT]) -> list[OutputT]:
|
|
29
|
+
"""One answer per input, in the same order."""
|
|
30
|
+
...
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def load(cls, bundle: ArtifactBundle, device: str = "cpu") -> Predictor[InputT, OutputT]:
|
|
34
|
+
"""Builds a ready predictor from a bundle."""
|
|
35
|
+
...
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@runtime_checkable
|
|
39
|
+
class ProbabilisticPredictor[InputT, OutputT](Predictor[InputT, OutputT], Protocol):
|
|
40
|
+
"""A predictor that can also say how sure it is: one probability per class, in schema order."""
|
|
41
|
+
|
|
42
|
+
def predict_proba(self, inputs: Sequence[InputT]) -> list[list[float]]: ...
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any, Literal, cast, get_args
|
|
7
|
+
|
|
8
|
+
LabelKind = Literal["binary", "categorical", "ordinal"]
|
|
9
|
+
LABEL_KINDS: tuple[str, ...] = get_args(LabelKind)
|
|
10
|
+
|
|
11
|
+
Label = str | int | float | bool
|
|
12
|
+
"""A class a classifier answers with: a text, a number or a boolean, as JSON holds it."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class LabelSchema:
|
|
17
|
+
"""The classes a classifier answers with, in the order of the columns its model gives.
|
|
18
|
+
|
|
19
|
+
- `binary`: exactly two classes; `classes[1]` is the positive one, the class whose probability the
|
|
20
|
+
`threshold` cuts. The threshold is required: a 0.5 nobody wrote would silently replace one tuned
|
|
21
|
+
for an unbalanced problem.
|
|
22
|
+
- `categorical`: two classes or more; the answer is the most probable one. No threshold.
|
|
23
|
+
- `ordinal`: classes whose order means something (low, medium, high), written by hand. No threshold.
|
|
24
|
+
|
|
25
|
+
`LabelSchema.of(labels)` builds one from the labels of the training data. `encode` turns labels into
|
|
26
|
+
the column indices training should use as targets, so column `k` of the model is `classes[k]` by
|
|
27
|
+
construction; `decode` goes back, and `decide` turns rows of probabilities into answers.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
kind: LabelKind
|
|
31
|
+
classes: tuple[Label, ...]
|
|
32
|
+
threshold: float | None = None
|
|
33
|
+
|
|
34
|
+
def __post_init__(self) -> None:
|
|
35
|
+
if self.kind not in LABEL_KINDS:
|
|
36
|
+
raise ValueError(f"kind must be one of {LABEL_KINDS}; got {self.kind!r}")
|
|
37
|
+
if isinstance(self.classes, str | bytes):
|
|
38
|
+
raise ValueError(f"classes is a sequence of classes, not one text; got {self.classes!r}")
|
|
39
|
+
classes = tuple(_plain_class(value) for value in self.classes)
|
|
40
|
+
object.__setattr__(self, "classes", classes)
|
|
41
|
+
if len(classes) < 2:
|
|
42
|
+
raise ValueError(f"a label schema needs at least two classes; got {classes}")
|
|
43
|
+
families = {_family(value) for value in classes}
|
|
44
|
+
if len(families) > 1:
|
|
45
|
+
raise ValueError(
|
|
46
|
+
f"the classes mix {' and '.join(sorted(families))} ({classes}): a label such as 1 and one "
|
|
47
|
+
"such as '1' would then both be valid answers; write them all one way"
|
|
48
|
+
)
|
|
49
|
+
if len(set(classes)) != len(classes):
|
|
50
|
+
raise ValueError(f"classes must be unique; got {classes}")
|
|
51
|
+
if self.kind == "binary" and len(classes) != 2:
|
|
52
|
+
raise ValueError(f"a binary schema has exactly two classes; got {classes}")
|
|
53
|
+
self._check_threshold()
|
|
54
|
+
|
|
55
|
+
def _check_threshold(self) -> None:
|
|
56
|
+
threshold = self.threshold
|
|
57
|
+
if self.kind != "binary":
|
|
58
|
+
if threshold is not None:
|
|
59
|
+
raise ValueError(
|
|
60
|
+
f"only a binary schema decides by a threshold; a {self.kind} one answers the most "
|
|
61
|
+
f"probable class, so leave threshold out (got {threshold!r})"
|
|
62
|
+
)
|
|
63
|
+
return
|
|
64
|
+
if threshold is None:
|
|
65
|
+
raise ValueError(
|
|
66
|
+
f"a binary schema decides by a threshold on the probability of {self.classes[1]!r}: write "
|
|
67
|
+
"threshold=0.5, or the one you tuned"
|
|
68
|
+
)
|
|
69
|
+
given: Any = threshold
|
|
70
|
+
plain = given.item() if _is_scalar_of_an_array_library(given) else given
|
|
71
|
+
if isinstance(plain, bool) or not isinstance(plain, int | float):
|
|
72
|
+
raise ValueError(f"the threshold is a probability; got {threshold!r}")
|
|
73
|
+
value = float(plain)
|
|
74
|
+
if not 0.0 < value < 1.0:
|
|
75
|
+
raise ValueError(f"the threshold is a probability strictly between 0 and 1; got {threshold!r}")
|
|
76
|
+
object.__setattr__(self, "threshold", value)
|
|
77
|
+
|
|
78
|
+
@classmethod
|
|
79
|
+
def of(cls, labels: Iterable[Any], *, threshold: float | None = None) -> LabelSchema:
|
|
80
|
+
"""The schema of the labels training uses: their distinct values, in increasing order, as plain
|
|
81
|
+
Python values (a NumPy integer becomes an `int`).
|
|
82
|
+
|
|
83
|
+
Two classes make a `binary` schema, which needs the `threshold`; more make a `categorical` one.
|
|
84
|
+
An `ordinal` schema is written by hand, since sorting texts would not keep the order of their
|
|
85
|
+
meaning.
|
|
86
|
+
"""
|
|
87
|
+
if isinstance(labels, str | bytes):
|
|
88
|
+
raise ValueError(f"labels is a sequence of labels, not one text; got {labels!r}")
|
|
89
|
+
distinct = {_plain_class(value) for value in labels}
|
|
90
|
+
families = {_family(value) for value in distinct}
|
|
91
|
+
if len(families) > 1:
|
|
92
|
+
raise ValueError(
|
|
93
|
+
f"the labels mix {' and '.join(sorted(families))}: {sorted(map(repr, distinct))}"
|
|
94
|
+
)
|
|
95
|
+
if len(distinct) < 2:
|
|
96
|
+
raise ValueError(
|
|
97
|
+
f"the labels have {len(distinct)} distinct value{'s' if len(distinct) != 1 else ''} "
|
|
98
|
+
f"({sorted(map(repr, distinct))}): a classifier needs at least two classes"
|
|
99
|
+
)
|
|
100
|
+
ordered = tuple(sorted(distinct)) # type: ignore[type-var]
|
|
101
|
+
return cls("binary" if len(ordered) == 2 else "categorical", ordered, threshold)
|
|
102
|
+
|
|
103
|
+
def encode(self, labels: Iterable[Any]) -> list[int]:
|
|
104
|
+
"""The column of each label: what training should use as its targets. A label that is not one of
|
|
105
|
+
the classes is a `ValueError` that lists them."""
|
|
106
|
+
index = {(_family(value), value): position for position, value in enumerate(self.classes)}
|
|
107
|
+
found: list[int] = []
|
|
108
|
+
for position, label in enumerate(labels):
|
|
109
|
+
plain = _plain_class(label)
|
|
110
|
+
column = index.get((_family(plain), plain))
|
|
111
|
+
if column is None:
|
|
112
|
+
raise ValueError(
|
|
113
|
+
f"label {label!r} (position {position}) is not one of the schema's classes {self.classes}"
|
|
114
|
+
)
|
|
115
|
+
found.append(column)
|
|
116
|
+
return found
|
|
117
|
+
|
|
118
|
+
def decode(self, indices: Iterable[Any]) -> list[Label]:
|
|
119
|
+
"""The class of each column index: the way back from `encode`."""
|
|
120
|
+
found: list[Label] = []
|
|
121
|
+
for position, value in enumerate(indices):
|
|
122
|
+
plain = _plain_class(value)
|
|
123
|
+
if isinstance(plain, bool) or not isinstance(plain, int) or not 0 <= plain < len(self.classes):
|
|
124
|
+
raise ValueError(
|
|
125
|
+
f"index {value!r} (position {position}) is not a column of the {len(self.classes)} "
|
|
126
|
+
f"classes {self.classes}"
|
|
127
|
+
)
|
|
128
|
+
found.append(self.classes[plain])
|
|
129
|
+
return found
|
|
130
|
+
|
|
131
|
+
def decide(self, probabilities: Iterable[Sequence[Any]]) -> list[Label]:
|
|
132
|
+
"""The answer for each row of probabilities, one column per class in this schema's order.
|
|
133
|
+
|
|
134
|
+
A `categorical` schema answers the most probable class (the first one, on a tie); a `binary` one
|
|
135
|
+
answers `classes[1]` when its probability is at least the threshold, and `classes[0]` otherwise.
|
|
136
|
+
An `ordinal` schema has no single rule, so it is refused.
|
|
137
|
+
"""
|
|
138
|
+
if self.kind == "ordinal":
|
|
139
|
+
raise ValueError(
|
|
140
|
+
"an ordinal schema has no single rule to turn probabilities into an answer (cumulative "
|
|
141
|
+
"logits, a plain softmax): write the rule in predict"
|
|
142
|
+
)
|
|
143
|
+
answers: list[Label] = []
|
|
144
|
+
width = len(self.classes)
|
|
145
|
+
for position, row in enumerate(probabilities):
|
|
146
|
+
values = [float(value) for value in row]
|
|
147
|
+
if len(values) != width:
|
|
148
|
+
raise ValueError(
|
|
149
|
+
f"row {position} has {len(values)} probabilities, and the schema has {width} classes "
|
|
150
|
+
f"{self.classes}"
|
|
151
|
+
)
|
|
152
|
+
if self.kind == "binary":
|
|
153
|
+
assert self.threshold is not None # checked when the schema was made
|
|
154
|
+
answers.append(self.classes[1] if values[1] >= self.threshold else self.classes[0])
|
|
155
|
+
else:
|
|
156
|
+
answers.append(self.classes[max(range(width), key=values.__getitem__)])
|
|
157
|
+
return answers
|
|
158
|
+
|
|
159
|
+
def to_json(self) -> dict[str, Any]:
|
|
160
|
+
return {"kind": self.kind, "classes": list(self.classes), "threshold": self.threshold}
|
|
161
|
+
|
|
162
|
+
@classmethod
|
|
163
|
+
def from_json(cls, data: Mapping[str, Any]) -> LabelSchema:
|
|
164
|
+
return cls(
|
|
165
|
+
kind=cast(LabelKind, data["kind"]),
|
|
166
|
+
classes=tuple(data["classes"]),
|
|
167
|
+
threshold=data.get("threshold"),
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _is_scalar_of_an_array_library(value: Any) -> bool:
|
|
172
|
+
"""A NumPy scalar, or an array or tensor of one element, told apart without importing either."""
|
|
173
|
+
if type(value).__module__.split(".")[0] not in {"numpy", "torch"} or not hasattr(value, "item"):
|
|
174
|
+
return False
|
|
175
|
+
size = getattr(value, "size", 1)
|
|
176
|
+
size = size() if callable(size) else size # a tensor's size is a method, an array's a number
|
|
177
|
+
try:
|
|
178
|
+
return int(math.prod(size) if isinstance(size, tuple) else size) == 1
|
|
179
|
+
except (TypeError, ValueError):
|
|
180
|
+
return False
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _plain_class(value: Any) -> Any:
|
|
184
|
+
"""A class as plain Python: a NumPy or PyTorch scalar becomes its Python value. Anything that is not
|
|
185
|
+
a text, a number or a boolean is refused, and so is a number that is not finite."""
|
|
186
|
+
if _is_scalar_of_an_array_library(value):
|
|
187
|
+
value = value.item()
|
|
188
|
+
if not isinstance(value, str | int | float | bool):
|
|
189
|
+
raise ValueError(f"a class is a text, a number or a boolean; got {value!r} ({type(value).__name__})")
|
|
190
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
191
|
+
raise ValueError(f"a class must be a finite number; got {value!r}")
|
|
192
|
+
return value
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _family(value: Any) -> str:
|
|
196
|
+
"""Which kind of class a value is: classes of one schema are all of one kind."""
|
|
197
|
+
if isinstance(value, bool):
|
|
198
|
+
return "booleans"
|
|
199
|
+
if isinstance(value, str):
|
|
200
|
+
return "texts"
|
|
201
|
+
return "numbers"
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""The library's logging policy, in force from `import torchstack64` on.
|
|
2
|
+
|
|
3
|
+
Every module logs to `logging.getLogger(__name__)`, so every record goes through the `torchstack64` logger,
|
|
4
|
+
and everything the library warns about is one of those records: one place decides what is shown.
|
|
5
|
+
|
|
6
|
+
The level is the root logger's (WARNING unless the application changes it), or the one
|
|
7
|
+
`TORCHSTACK64_LOG_LEVEL` names, read when the library is imported. `torchstack64.utils` has the switches
|
|
8
|
+
a notebook uses: `set_verbosity`, `quiet` and `enable_console`.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import logging
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
from typing import Literal, get_args
|
|
17
|
+
|
|
18
|
+
LOGGER_NAME = "torchstack64"
|
|
19
|
+
ENV_VAR = "TORCHSTACK64_LOG_LEVEL"
|
|
20
|
+
DEFAULT_FORMAT = "%(asctime)s %(levelname)-7s %(name)s: %(message)s"
|
|
21
|
+
|
|
22
|
+
LogLevel = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
|
|
23
|
+
|
|
24
|
+
_LEVELS: tuple[str, ...] = get_args(LogLevel)
|
|
25
|
+
_FALLBACK_NAME = "torchstack64.fallback"
|
|
26
|
+
_said: set[tuple[str, str]] = set()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def log_level(value: str | int) -> int:
|
|
30
|
+
"""The number of a level given by its name, in any case, or by its number.
|
|
31
|
+
|
|
32
|
+
The names are the standard library's, the aliases it still accepts (`"WARN"`) and those a program
|
|
33
|
+
registered with `logging.addLevelName` included. An unknown name raises `ValueError` listing the
|
|
34
|
+
valid ones, before anything changes.
|
|
35
|
+
"""
|
|
36
|
+
if isinstance(value, int):
|
|
37
|
+
return value
|
|
38
|
+
if not isinstance(value, str):
|
|
39
|
+
raise TypeError(f"a log level is a name or a number, not {type(value).__name__}")
|
|
40
|
+
number = logging.getLevelNamesMapping().get(value.strip().upper())
|
|
41
|
+
if number is None:
|
|
42
|
+
raise ValueError(f"{value!r} is not a log level; use one of {', '.join(_LEVELS)}, or a number")
|
|
43
|
+
return number
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class _Fallback(logging.Handler):
|
|
47
|
+
"""Writes to stderr the records that no other handler would receive."""
|
|
48
|
+
|
|
49
|
+
def __init__(self) -> None:
|
|
50
|
+
super().__init__()
|
|
51
|
+
self.set_name(_FALLBACK_NAME)
|
|
52
|
+
self.setFormatter(logging.Formatter(DEFAULT_FORMAT))
|
|
53
|
+
|
|
54
|
+
def handle(self, record: logging.LogRecord) -> bool:
|
|
55
|
+
if self._others_receive(record):
|
|
56
|
+
return False
|
|
57
|
+
return bool(super().handle(record))
|
|
58
|
+
|
|
59
|
+
def emit(self, record: logging.LogRecord) -> None:
|
|
60
|
+
stream = sys.stderr # looked up for each record: a notebook replaces it, and pythonw has none
|
|
61
|
+
if stream is None:
|
|
62
|
+
return
|
|
63
|
+
try:
|
|
64
|
+
stream.write(self.format(record) + "\n")
|
|
65
|
+
stream.flush()
|
|
66
|
+
except RecursionError:
|
|
67
|
+
raise
|
|
68
|
+
except Exception:
|
|
69
|
+
self.handleError(record)
|
|
70
|
+
|
|
71
|
+
def _others_receive(self, record: logging.LogRecord) -> bool:
|
|
72
|
+
logger: logging.Logger | None = logging.getLogger(record.name)
|
|
73
|
+
while logger is not None:
|
|
74
|
+
if any(handler is not self for handler in logger.handlers):
|
|
75
|
+
return True
|
|
76
|
+
logger = logger.parent if logger.propagate else None
|
|
77
|
+
return False
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def configure_logging() -> None:
|
|
81
|
+
"""Puts the policy in place. `import torchstack64` calls it; calling it again changes nothing."""
|
|
82
|
+
logger = logging.getLogger(LOGGER_NAME)
|
|
83
|
+
if any(handler.get_name() == _FALLBACK_NAME for handler in logger.handlers):
|
|
84
|
+
return
|
|
85
|
+
logger.addHandler(_Fallback())
|
|
86
|
+
level = os.environ.get(ENV_VAR, "").strip()
|
|
87
|
+
if not level:
|
|
88
|
+
return
|
|
89
|
+
try:
|
|
90
|
+
logger.setLevel(log_level(level))
|
|
91
|
+
except ValueError: # importing the library must not fail over a log level
|
|
92
|
+
logger.warning(
|
|
93
|
+
"%s=%r is not a level, so it is ignored; use one of %s", ENV_VAR, level, ", ".join(_LEVELS)
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def warn_once(logger: logging.Logger, message: str, *args: object) -> None:
|
|
98
|
+
"""Logs `message % args` at WARNING the first time this process meets it.
|
|
99
|
+
|
|
100
|
+
For a warning about the setup, which every fit of a loop would repeat word for word. A warning about
|
|
101
|
+
one event (one bundle written, one fit resumed) goes through `logger.warning` each time. A warning
|
|
102
|
+
hidden by the level (inside `quiet("ERROR")`, say) is not counted as given.
|
|
103
|
+
"""
|
|
104
|
+
if not logger.isEnabledFor(logging.WARNING):
|
|
105
|
+
return
|
|
106
|
+
key = (logger.name, message % args if args else message)
|
|
107
|
+
if key in _said:
|
|
108
|
+
return
|
|
109
|
+
_said.add(key)
|
|
110
|
+
logger.warning(message, *args, stacklevel=2)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# ruff: noqa: E402
|
|
2
|
+
|
|
3
|
+
from torchstack64.core import require
|
|
4
|
+
|
|
5
|
+
require("torch", extra="training", purpose="torchstack64.data")
|
|
6
|
+
|
|
7
|
+
from torchstack64.data.base import PreparedData
|
|
8
|
+
from torchstack64.data.labeled import LabeledData
|
|
9
|
+
|
|
10
|
+
__all__ = ["LabeledData", "PreparedData"]
|