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,139 @@
|
|
|
1
|
+
"""How a fit trades numeric precision for speed: one small class per precision.
|
|
2
|
+
|
|
3
|
+
`Fp32` is full precision and does nothing special. `Bf16` runs the forward pass in bfloat16. `Fp16` does
|
|
4
|
+
the same in float16 and adds a gradient scaler, because float16 gradients can be too small to exist and
|
|
5
|
+
underflow to zero. A `Runtime` holds one of these and never asks which it is.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from contextlib import AbstractContextManager, nullcontext
|
|
12
|
+
from typing import Any, Protocol
|
|
13
|
+
|
|
14
|
+
import torch
|
|
15
|
+
|
|
16
|
+
from torchstack64.training.config import PRECISIONS, Precision
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class PrecisionPolicy(Protocol):
|
|
20
|
+
"""What a `Runtime` asks of a precision."""
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def scaler(self) -> torch.amp.GradScaler | None:
|
|
24
|
+
"""The gradient scaler, for the precisions that have one."""
|
|
25
|
+
...
|
|
26
|
+
|
|
27
|
+
def autocast(self) -> AbstractContextManager[Any]:
|
|
28
|
+
"""Runs the forward pass in this precision."""
|
|
29
|
+
...
|
|
30
|
+
|
|
31
|
+
def backward(self, loss: torch.Tensor) -> None:
|
|
32
|
+
"""Back-propagates `loss`, scaled first when the precision needs it."""
|
|
33
|
+
...
|
|
34
|
+
|
|
35
|
+
def unscale(self, optimizer: torch.optim.Optimizer) -> None:
|
|
36
|
+
"""Brings the gradients back to their true size, which clipping needs and a scaled gradient is not."""
|
|
37
|
+
...
|
|
38
|
+
|
|
39
|
+
def step(self, optimizer: torch.optim.Optimizer) -> bool:
|
|
40
|
+
"""Applies the gradients. Returns False when the update was skipped."""
|
|
41
|
+
...
|
|
42
|
+
|
|
43
|
+
def state_dict(self) -> dict[str, Any] | None:
|
|
44
|
+
"""What a resumed fit needs from this precision, or `None` when it needs nothing."""
|
|
45
|
+
...
|
|
46
|
+
|
|
47
|
+
def load_state_dict(self, state: Mapping[str, Any] | None) -> None: ...
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Fp32:
|
|
51
|
+
"""Full precision: the forward pass runs as written, and there is nothing to scale."""
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def scaler(self) -> torch.amp.GradScaler | None:
|
|
55
|
+
return None
|
|
56
|
+
|
|
57
|
+
def autocast(self) -> AbstractContextManager[Any]:
|
|
58
|
+
return nullcontext()
|
|
59
|
+
|
|
60
|
+
def backward(self, loss: torch.Tensor) -> None:
|
|
61
|
+
loss.backward()
|
|
62
|
+
|
|
63
|
+
def unscale(self, optimizer: torch.optim.Optimizer) -> None:
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
def step(self, optimizer: torch.optim.Optimizer) -> bool:
|
|
67
|
+
optimizer.step()
|
|
68
|
+
return True
|
|
69
|
+
|
|
70
|
+
def state_dict(self) -> dict[str, Any] | None:
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
def load_state_dict(self, state: Mapping[str, Any] | None) -> None:
|
|
74
|
+
pass
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class Bf16(Fp32):
|
|
78
|
+
"""The forward pass in bfloat16. It has float32's range, so gradients do not underflow and no scaler
|
|
79
|
+
is needed."""
|
|
80
|
+
|
|
81
|
+
def __init__(self, device: torch.device) -> None:
|
|
82
|
+
if device.type == "cuda" and not torch.cuda.is_bf16_supported(including_emulation=False):
|
|
83
|
+
raise ValueError("this GPU has no native bf16; use precision='fp16' (with its gradient scaler)")
|
|
84
|
+
self._device_type = device.type
|
|
85
|
+
|
|
86
|
+
def autocast(self) -> AbstractContextManager[Any]:
|
|
87
|
+
return torch.autocast(self._device_type, dtype=torch.bfloat16)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class Fp16(Fp32):
|
|
91
|
+
"""The forward pass in float16, with a gradient scaler.
|
|
92
|
+
|
|
93
|
+
The loss is scaled up before the backward pass, so small gradients survive, and the gradients are
|
|
94
|
+
scaled back down before they are clipped or applied. A gradient that overflows to inf or NaN makes
|
|
95
|
+
the scaler skip that update and lower its scale.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
def __init__(self, device: torch.device) -> None:
|
|
99
|
+
self._device_type = device.type
|
|
100
|
+
self._scaler = torch.amp.GradScaler(device.type)
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def scaler(self) -> torch.amp.GradScaler:
|
|
104
|
+
return self._scaler
|
|
105
|
+
|
|
106
|
+
def autocast(self) -> AbstractContextManager[Any]:
|
|
107
|
+
return torch.autocast(self._device_type, dtype=torch.float16)
|
|
108
|
+
|
|
109
|
+
def backward(self, loss: torch.Tensor) -> None:
|
|
110
|
+
self._scaler.scale(loss).backward()
|
|
111
|
+
|
|
112
|
+
def unscale(self, optimizer: torch.optim.Optimizer) -> None:
|
|
113
|
+
self._scaler.unscale_(optimizer)
|
|
114
|
+
|
|
115
|
+
def step(self, optimizer: torch.optim.Optimizer) -> bool:
|
|
116
|
+
"""Returns False when the scaler skipped the update because a gradient was inf or NaN (it then
|
|
117
|
+
lowers the scale and tries again on the next step)."""
|
|
118
|
+
scale_before = self._scaler.get_scale()
|
|
119
|
+
self._scaler.step(optimizer)
|
|
120
|
+
self._scaler.update()
|
|
121
|
+
return self._scaler.get_scale() >= scale_before
|
|
122
|
+
|
|
123
|
+
def state_dict(self) -> dict[str, Any] | None:
|
|
124
|
+
return self._scaler.state_dict()
|
|
125
|
+
|
|
126
|
+
def load_state_dict(self, state: Mapping[str, Any] | None) -> None:
|
|
127
|
+
if state:
|
|
128
|
+
self._scaler.load_state_dict(dict(state))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def policy_for(precision: Precision, device: torch.device) -> PrecisionPolicy:
|
|
132
|
+
"""The policy of `precision` on `device`; `ValueError` for a name that is not one of the three."""
|
|
133
|
+
if precision == "fp32":
|
|
134
|
+
return Fp32()
|
|
135
|
+
if precision == "bf16":
|
|
136
|
+
return Bf16(device)
|
|
137
|
+
if precision == "fp16":
|
|
138
|
+
return Fp16(device)
|
|
139
|
+
raise ValueError(f"precision must be one of {PRECISIONS}; got {precision!r}")
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""The random generators a run depends on, in one place: seeding them, and saving and restoring them.
|
|
2
|
+
|
|
3
|
+
They are Python's `random`, NumPy's (when it is installed) and PyTorch's, on the CPU and on every
|
|
4
|
+
accelerator the machine has (CUDA, XPU, MPS), plus the generator a data loader was given of its own
|
|
5
|
+
(`DataLoader(generator=...)`)
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import random
|
|
11
|
+
from collections.abc import Callable, Mapping
|
|
12
|
+
from functools import partial
|
|
13
|
+
from types import ModuleType
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
import torch
|
|
17
|
+
|
|
18
|
+
from torchstack64.core import is_installed
|
|
19
|
+
|
|
20
|
+
_Generator = tuple[
|
|
21
|
+
Callable[[], Any], Callable[[Any], object]
|
|
22
|
+
] # how to read a generator's state, and put it back
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _numpy() -> ModuleType | None:
|
|
26
|
+
if not is_installed("numpy"):
|
|
27
|
+
return None
|
|
28
|
+
import numpy
|
|
29
|
+
|
|
30
|
+
return numpy
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def seed_everything(seed: int) -> torch.Generator:
|
|
34
|
+
"""Seeds Python's `random`, NumPy (if installed) and PyTorch on every device, and returns a
|
|
35
|
+
`torch.Generator` seeded the same way, for `DataLoader(generator=...)`.
|
|
36
|
+
"""
|
|
37
|
+
random.seed(seed)
|
|
38
|
+
if (numpy := _numpy()) is not None:
|
|
39
|
+
numpy.random.seed(seed % 2**32)
|
|
40
|
+
torch.manual_seed(seed)
|
|
41
|
+
generator = torch.Generator()
|
|
42
|
+
generator.manual_seed(seed)
|
|
43
|
+
return generator
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Randomness:
|
|
47
|
+
"""The random generators of a fit, saved and put back together.
|
|
48
|
+
|
|
49
|
+
`loaders` are the fit's data loaders by name. Those that were given a generator of their own
|
|
50
|
+
(`DataLoader(generator=...)`) have it saved too; one without draws from PyTorch's global generator,
|
|
51
|
+
which is saved anyway.
|
|
52
|
+
|
|
53
|
+
The state is made of tensors and plain Python values, so it survives `torch.save` and loading with
|
|
54
|
+
`weights_only=True`.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def __init__(self, loaders: Mapping[str, object] | None = None) -> None:
|
|
58
|
+
self.loaders = dict(loaders or {})
|
|
59
|
+
|
|
60
|
+
def state_dict(self) -> dict[str, Any]:
|
|
61
|
+
"""Every random generator the next epoch reads, by name."""
|
|
62
|
+
return {name: read() for name, (read, _) in self._sources().items()}
|
|
63
|
+
|
|
64
|
+
def load_state_dict(self, state: Mapping[str, Any]) -> None:
|
|
65
|
+
"""Puts back what `state_dict` took. A generator in the state that this machine or this fit does
|
|
66
|
+
not have (an accelerator, a loader's) is skipped, so a fit can resume on another machine."""
|
|
67
|
+
for name, (_, put) in self._sources().items():
|
|
68
|
+
if name in state:
|
|
69
|
+
put(state[name])
|
|
70
|
+
|
|
71
|
+
def _sources(self) -> dict[str, _Generator]:
|
|
72
|
+
"""How to read and put back each generator that this machine and this fit have, by name."""
|
|
73
|
+
sources: dict[str, _Generator] = {
|
|
74
|
+
"python": (random.getstate, self._set_python_state),
|
|
75
|
+
"torch": (torch.get_rng_state, torch.set_rng_state),
|
|
76
|
+
}
|
|
77
|
+
sources.update(self._accelerator_generators())
|
|
78
|
+
if (numpy := _numpy()) is not None:
|
|
79
|
+
sources["numpy"] = (partial(self._numpy_state, numpy), partial(self._set_numpy_state, numpy))
|
|
80
|
+
for name, loader in self.loaders.items():
|
|
81
|
+
if (generator := self._own_generator(loader)) is not None:
|
|
82
|
+
sources[f"loader:{name}"] = (generator.get_state, generator.set_state)
|
|
83
|
+
return sources
|
|
84
|
+
|
|
85
|
+
@staticmethod
|
|
86
|
+
def _accelerator_generators() -> dict[str, _Generator]:
|
|
87
|
+
"""The generator of each accelerator this machine has, by name.
|
|
88
|
+
|
|
89
|
+
`torch.manual_seed` already seeds every accelerator; it is saving and restoring that has to ask
|
|
90
|
+
each one, because each has its own functions for it.
|
|
91
|
+
"""
|
|
92
|
+
found: dict[str, _Generator] = {}
|
|
93
|
+
if torch.cuda.is_available():
|
|
94
|
+
found["cuda"] = (torch.cuda.get_rng_state_all, torch.cuda.set_rng_state_all)
|
|
95
|
+
if hasattr(torch, "xpu") and torch.xpu.is_available():
|
|
96
|
+
found["xpu"] = (torch.xpu.get_rng_state_all, torch.xpu.set_rng_state_all)
|
|
97
|
+
if torch.backends.mps.is_available():
|
|
98
|
+
found["mps"] = (torch.mps.get_rng_state, torch.mps.set_rng_state)
|
|
99
|
+
return found
|
|
100
|
+
|
|
101
|
+
@staticmethod
|
|
102
|
+
def _own_generator(loader: object) -> torch.Generator | None:
|
|
103
|
+
"""The generator a data loader was given (`DataLoader(generator=...)`), if any.
|
|
104
|
+
|
|
105
|
+
A loader without one draws from PyTorch's global generator, which is saved already.
|
|
106
|
+
"""
|
|
107
|
+
generator = getattr(loader, "generator", None)
|
|
108
|
+
return generator if isinstance(generator, torch.Generator) else None
|
|
109
|
+
|
|
110
|
+
@staticmethod
|
|
111
|
+
def _set_python_state(state: Any) -> None:
|
|
112
|
+
random.setstate(Randomness._as_tuple(state))
|
|
113
|
+
|
|
114
|
+
@staticmethod
|
|
115
|
+
def _as_tuple(value: Any) -> Any:
|
|
116
|
+
"""`random.setstate` wants tuples, and a saved state comes back from disk as lists."""
|
|
117
|
+
if isinstance(value, list | tuple):
|
|
118
|
+
return tuple(Randomness._as_tuple(item) for item in value)
|
|
119
|
+
return value
|
|
120
|
+
|
|
121
|
+
@staticmethod
|
|
122
|
+
def _numpy_state(numpy: ModuleType) -> dict[str, Any]:
|
|
123
|
+
kind, keys, position, has_gauss, cached = numpy.random.get_state()
|
|
124
|
+
return {
|
|
125
|
+
"kind": str(kind),
|
|
126
|
+
"keys": torch.from_numpy(numpy.asarray(keys, dtype=numpy.int64)),
|
|
127
|
+
"position": int(position),
|
|
128
|
+
"has_gauss": int(has_gauss),
|
|
129
|
+
"cached": float(cached),
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
@staticmethod
|
|
133
|
+
def _set_numpy_state(numpy: ModuleType, saved: Mapping[str, Any]) -> None:
|
|
134
|
+
numpy.random.set_state(
|
|
135
|
+
(
|
|
136
|
+
saved["kind"],
|
|
137
|
+
saved["keys"].numpy().astype(numpy.uint32),
|
|
138
|
+
saved["position"],
|
|
139
|
+
saved["has_gauss"],
|
|
140
|
+
saved["cached"],
|
|
141
|
+
)
|
|
142
|
+
)
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""The device and the precision of a loop, behind one object.
|
|
2
|
+
|
|
3
|
+
The trainer runs on a `Runtime`, and a hand-written loop can use one directly. It is the one place that
|
|
4
|
+
knows where tensors go and in which precision the passes run; a distributed backend would plug in here,
|
|
5
|
+
without touching any task.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
from collections.abc import Iterable, Mapping
|
|
12
|
+
from contextlib import AbstractContextManager
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import torch
|
|
16
|
+
|
|
17
|
+
from torchstack64.devices import resolve_torch_device
|
|
18
|
+
from torchstack64.training.config import Precision
|
|
19
|
+
from torchstack64.training.runtime.precision import policy_for
|
|
20
|
+
from torchstack64.training.runtime.transfer import to_device
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Runtime:
|
|
26
|
+
"""The device and the precision of a loop."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, device: str | torch.device | None = None, precision: Precision = "fp32") -> None:
|
|
29
|
+
self.device = resolve_torch_device(device)
|
|
30
|
+
self.precision = precision
|
|
31
|
+
self._policy = policy_for(precision, self.device)
|
|
32
|
+
logger.debug("runtime on %s with %s", self.device, precision)
|
|
33
|
+
|
|
34
|
+
def __repr__(self) -> str:
|
|
35
|
+
return f"Runtime(device={str(self.device)!r}, precision={self.precision!r})"
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def scaler(self) -> torch.amp.GradScaler | None:
|
|
39
|
+
"""The gradient scaler: only fp16 has one."""
|
|
40
|
+
return self._policy.scaler
|
|
41
|
+
|
|
42
|
+
def autocast(self) -> AbstractContextManager[Any]:
|
|
43
|
+
"""Runs the forward pass in the chosen precision; a no-op in fp32."""
|
|
44
|
+
return self._policy.autocast()
|
|
45
|
+
|
|
46
|
+
def to_device(self, obj: Any) -> Any:
|
|
47
|
+
return to_device(obj, self.device)
|
|
48
|
+
|
|
49
|
+
def backward(self, loss: torch.Tensor) -> None:
|
|
50
|
+
"""Back-propagates `loss`, scaled first in fp16 so small gradients do not underflow to zero."""
|
|
51
|
+
self._policy.backward(loss)
|
|
52
|
+
|
|
53
|
+
def clip(
|
|
54
|
+
self, parameters: Iterable[torch.Tensor], max_norm: float | None, optimizer: torch.optim.Optimizer
|
|
55
|
+
) -> torch.Tensor | None:
|
|
56
|
+
"""Clips the gradients to `max_norm` and returns their norm before clipping (`None` when not
|
|
57
|
+
clipping). In fp16 the gradients are unscaled first, so the true gradients are clipped."""
|
|
58
|
+
if max_norm is None:
|
|
59
|
+
return None
|
|
60
|
+
self._policy.unscale(optimizer)
|
|
61
|
+
return torch.nn.utils.clip_grad_norm_(list(parameters), max_norm)
|
|
62
|
+
|
|
63
|
+
def step(self, optimizer: torch.optim.Optimizer) -> bool:
|
|
64
|
+
"""Applies the gradients. Returns False when fp16's scaler skipped the update because a gradient
|
|
65
|
+
was inf or NaN."""
|
|
66
|
+
return self._policy.step(optimizer)
|
|
67
|
+
|
|
68
|
+
def state_dict(self) -> dict[str, Any]:
|
|
69
|
+
return {"precision": self.precision, "scaler": self._policy.state_dict()}
|
|
70
|
+
|
|
71
|
+
def load_state_dict(self, state: Mapping[str, Any]) -> None:
|
|
72
|
+
saved = state.get("precision")
|
|
73
|
+
if saved is not None and saved != self.precision:
|
|
74
|
+
logger.warning("resuming a fit saved with precision %r under precision %r", saved, self.precision)
|
|
75
|
+
self._policy.load_state_dict(state.get("scaler"))
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Moving a batch to the device, whatever shape the batch has."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def to_device(obj: Any, device: torch.device | str, *, non_blocking: bool | None = None) -> Any:
|
|
13
|
+
"""Moves every tensor inside `obj` to `device`, and leaves everything else as it is.
|
|
14
|
+
|
|
15
|
+
It walks dicts, lists, tuples (named ones too) and dataclasses, and calls `.to(device)` on any other
|
|
16
|
+
object that has it (a tokenizer's `BatchEncoding`). Identifiers, strings and numbers pass through.
|
|
17
|
+
"""
|
|
18
|
+
device = torch.device(device)
|
|
19
|
+
if non_blocking is None:
|
|
20
|
+
non_blocking = device.type in ("cuda", "xpu")
|
|
21
|
+
return _move(obj, device, non_blocking)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _move(obj: Any, device: torch.device, non_blocking: bool) -> Any:
|
|
25
|
+
if isinstance(obj, torch.Tensor):
|
|
26
|
+
return obj.to(device, non_blocking=non_blocking)
|
|
27
|
+
if dataclasses.is_dataclass(obj) and not isinstance(obj, type):
|
|
28
|
+
changes = {
|
|
29
|
+
f.name: _move(getattr(obj, f.name), device, non_blocking)
|
|
30
|
+
for f in dataclasses.fields(obj)
|
|
31
|
+
if f.init
|
|
32
|
+
}
|
|
33
|
+
return dataclasses.replace(obj, **changes)
|
|
34
|
+
if isinstance(obj, tuple):
|
|
35
|
+
moved = [_move(item, device, non_blocking) for item in obj]
|
|
36
|
+
return type(obj)(*moved) if hasattr(obj, "_fields") else tuple(moved)
|
|
37
|
+
if isinstance(obj, list):
|
|
38
|
+
return [_move(item, device, non_blocking) for item in obj]
|
|
39
|
+
# An object that moves itself is moved by its own `.to`, so this comes before the plain mappings:
|
|
40
|
+
# a tokenizer's BatchEncoding is a mapping too.
|
|
41
|
+
if not isinstance(obj, dict | str | bytes) and callable(getattr(obj, "to", None)):
|
|
42
|
+
return obj.to(device)
|
|
43
|
+
if isinstance(obj, Mapping):
|
|
44
|
+
moved_items = {key: _move(value, device, non_blocking) for key, value in obj.items()}
|
|
45
|
+
try:
|
|
46
|
+
return type(obj)(moved_items) # type: ignore[call-arg] # a dict subclass keeps its type
|
|
47
|
+
except TypeError:
|
|
48
|
+
return moved_items
|
|
49
|
+
return obj
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""A model's weights: independent copies of them, and the size of the model."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import torch
|
|
8
|
+
from torch import nn
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Weights:
|
|
12
|
+
"""The weights of `model`.
|
|
13
|
+
|
|
14
|
+
A copy is independent of the model: training on does not change it. `model.state_dict()` alone is not
|
|
15
|
+
a copy, it holds the very tensors the model trains.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
def __init__(self, model: nn.Module) -> None:
|
|
19
|
+
self.model = model
|
|
20
|
+
|
|
21
|
+
def cpu_copy(self) -> dict[str, Any]:
|
|
22
|
+
"""A copy in CPU memory: it costs no GPU memory while it waits."""
|
|
23
|
+
return {
|
|
24
|
+
# `copy=True` matters: a tensor already on the CPU comes back from `.to("cpu")` as itself
|
|
25
|
+
name: value.detach().to("cpu", copy=True) if isinstance(value, torch.Tensor) else value
|
|
26
|
+
for name, value in self.model.state_dict().items()
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
def device_copy(self) -> dict[str, Any]:
|
|
30
|
+
"""A copy where the weights are (the GPU, usually)."""
|
|
31
|
+
return {
|
|
32
|
+
name: value.detach().clone() if isinstance(value, torch.Tensor) else value
|
|
33
|
+
for name, value in self.model.state_dict().items()
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
def count(self) -> tuple[int, int]:
|
|
37
|
+
"""(all parameters, trainable parameters)."""
|
|
38
|
+
total = trainable = 0
|
|
39
|
+
for parameter in self.model.parameters():
|
|
40
|
+
total += parameter.numel()
|
|
41
|
+
if parameter.requires_grad:
|
|
42
|
+
trainable += parameter.numel()
|
|
43
|
+
return total, trainable
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
from torchstack64.training.task.optim import build_optimization, linear_warmup
|
|
2
|
+
from torchstack64.training.task.protocol import EpochTask, Task
|
|
3
|
+
from torchstack64.training.task.supervised import SupervisedTask
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"EpochTask",
|
|
7
|
+
"SupervisedTask",
|
|
8
|
+
"Task",
|
|
9
|
+
"build_optimization",
|
|
10
|
+
"linear_warmup",
|
|
11
|
+
]
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Everything a task needs to set up learning, one question per module."""
|
|
2
|
+
|
|
3
|
+
from torchstack64.training.task.optim.optimization import build_optimization
|
|
4
|
+
from torchstack64.training.task.optim.schedules import linear_warmup
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"build_optimization",
|
|
8
|
+
"linear_warmup",
|
|
9
|
+
]
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""The common case: an `OptimConfig` made into the `Optimization` a task returns, the optimizer named
|
|
2
|
+
in it included."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import logging
|
|
7
|
+
from collections.abc import Callable, Iterable
|
|
8
|
+
from typing import TYPE_CHECKING, Any, assert_never
|
|
9
|
+
|
|
10
|
+
import torch
|
|
11
|
+
|
|
12
|
+
from torchstack64.core import warn_once
|
|
13
|
+
from torchstack64.training.config import OptimizerType
|
|
14
|
+
from torchstack64.training.task.optim.schedules import linear_warmup
|
|
15
|
+
from torchstack64.training.trainer import Optimization
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from torchstack64.training.config import OptimConfig
|
|
19
|
+
from torchstack64.training.trainer import FitPlan
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def build_optimization(optim: OptimConfig, params: Iterable[Any], plan: FitPlan) -> Optimization:
|
|
25
|
+
"""The optimizer that `optim` names over `params`, with its warm-up when it has one.
|
|
26
|
+
|
|
27
|
+
`params` is the model's parameters, or param groups (dicts with `params` and any settings of their
|
|
28
|
+
own, such as a different `lr` for the head); a group's own `lr` and `weight_decay` win over `optim`'s.
|
|
29
|
+
The warm-up needs the fit's total of optimization steps: when the training loader has no `len()`, the
|
|
30
|
+
rate stays constant, with a warning (once per process).
|
|
31
|
+
"""
|
|
32
|
+
optimizer = _optimizer(optim.optimizer, params, lr=optim.lr, weight_decay=optim.weight_decay)
|
|
33
|
+
if optim.warmup is None:
|
|
34
|
+
return Optimization(optimizer)
|
|
35
|
+
total = plan.total_optimization_steps
|
|
36
|
+
if total is None:
|
|
37
|
+
warn_once(
|
|
38
|
+
logger,
|
|
39
|
+
"the training loader has no len(), so the warm-up has no total number of steps; "
|
|
40
|
+
"the learning rate stays constant",
|
|
41
|
+
)
|
|
42
|
+
return Optimization(optimizer)
|
|
43
|
+
warmup_steps = round(optim.warmup * total)
|
|
44
|
+
return Optimization(optimizer, linear_warmup(optimizer, warmup_steps=warmup_steps, total_steps=total))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _optimizer(
|
|
48
|
+
kind: OptimizerType | str | Callable[..., torch.optim.Optimizer],
|
|
49
|
+
params: Iterable[Any],
|
|
50
|
+
*,
|
|
51
|
+
lr: float,
|
|
52
|
+
weight_decay: float,
|
|
53
|
+
) -> torch.optim.Optimizer:
|
|
54
|
+
"""The optimizer `kind` names, or the one a class or factory of yours builds, over `params`."""
|
|
55
|
+
if not isinstance(kind, str):
|
|
56
|
+
return kind(params, lr=lr, weight_decay=weight_decay)
|
|
57
|
+
try:
|
|
58
|
+
name = OptimizerType(kind)
|
|
59
|
+
except ValueError:
|
|
60
|
+
known = [member.value for member in OptimizerType]
|
|
61
|
+
raise ValueError(f"unknown optimizer {kind!r}; known: {known}, or pass an optimizer class") from None
|
|
62
|
+
match name:
|
|
63
|
+
case OptimizerType.ADAM:
|
|
64
|
+
return torch.optim.Adam(params, lr=lr, weight_decay=weight_decay)
|
|
65
|
+
case OptimizerType.ADAMW:
|
|
66
|
+
return torch.optim.AdamW(params, lr=lr, weight_decay=weight_decay)
|
|
67
|
+
case OptimizerType.SGD:
|
|
68
|
+
return torch.optim.SGD(params, lr=lr, weight_decay=weight_decay, momentum=0.9)
|
|
69
|
+
case _:
|
|
70
|
+
assert_never(name)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Schedules: how the learning rate moves over the course of a fit."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
from torch.optim.lr_scheduler import LambdaLR
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def linear_warmup(optimizer: torch.optim.Optimizer, *, warmup_steps: int, total_steps: int) -> LambdaLR:
|
|
10
|
+
"""The rate rises linearly from 0 over `warmup_steps`, then falls linearly to 0 at `total_steps`.
|
|
11
|
+
|
|
12
|
+
The same curve as `transformers.get_linear_schedule_with_warmup`, for any model and without the
|
|
13
|
+
dependency. Step it after every optimization step (the trainer does, with `interval="step"`).
|
|
14
|
+
"""
|
|
15
|
+
if total_steps < 1:
|
|
16
|
+
raise ValueError(f"total_steps must be at least 1; got {total_steps}")
|
|
17
|
+
if not 0 <= warmup_steps <= total_steps:
|
|
18
|
+
raise ValueError(
|
|
19
|
+
f"warmup_steps must be between 0 and total_steps ({total_steps}); got {warmup_steps}"
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
def factor(step: int) -> float:
|
|
23
|
+
if step < warmup_steps:
|
|
24
|
+
return step / max(1, warmup_steps)
|
|
25
|
+
return max(0.0, (total_steps - step) / max(1, total_steps - warmup_steps))
|
|
26
|
+
|
|
27
|
+
return LambdaLR(optimizer, factor)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""The two shapes a task can have: `Task`, whose steps the trainer drives one batch at a time, and
|
|
2
|
+
`EpochTask`, which runs the whole training epoch itself.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from collections.abc import Iterable
|
|
8
|
+
from typing import TYPE_CHECKING, Protocol, runtime_checkable
|
|
9
|
+
|
|
10
|
+
import torch
|
|
11
|
+
from torch import nn
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from torchstack64.training.trainer import FitPlan, Optimization, Step, StepContext, Trainer
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@runtime_checkable
|
|
18
|
+
class Task[BatchT](Protocol):
|
|
19
|
+
"""The three things that differ between models. Any object with these methods is a task.
|
|
20
|
+
|
|
21
|
+
Write it as a dataclass whose fields are its hyperparameters (an `OptimConfig` for the optimizer,
|
|
22
|
+
the weights of a loss, the rates), with no numeric constant in its methods: the trainer records those
|
|
23
|
+
fields in `FitResult.params`, a tracker logs them, and `dataclasses.replace` makes an arm of an
|
|
24
|
+
experiment. A task that is not a dataclass still runs, with a warning that its settings go unrecorded.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def configure_optimization(self, model: nn.Module, plan: FitPlan) -> Optimization | torch.optim.Optimizer:
|
|
28
|
+
"""Builds the optimizer (and scheduler) for `model`. Called at the start of every fit."""
|
|
29
|
+
...
|
|
30
|
+
|
|
31
|
+
def training_step(self, model: nn.Module, batch: BatchT, ctx: StepContext) -> Step | torch.Tensor:
|
|
32
|
+
"""The loss of one batch (the trainer does the backward pass and the optimization step)."""
|
|
33
|
+
...
|
|
34
|
+
|
|
35
|
+
def validation_step(self, model: nn.Module, batch: BatchT, ctx: StepContext) -> Step:
|
|
36
|
+
"""The loss and predictions of one validation batch (gradients are off)."""
|
|
37
|
+
...
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@runtime_checkable
|
|
41
|
+
class EpochTask[BatchT](Protocol):
|
|
42
|
+
"""A task that runs the whole training epoch itself, as a hand-written loop would.
|
|
43
|
+
|
|
44
|
+
The trainer still validates, keeps the best epoch, stops early and calls the callbacks. Inside
|
|
45
|
+
`train_epoch`, `trainer.runtime` has `autocast()`, `backward()` and `to_device()`, and
|
|
46
|
+
`trainer.optimization_step(loss)` clips, steps, schedules and calls
|
|
47
|
+
`on_optimization_step_end`.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def configure_optimization(
|
|
51
|
+
self, model: nn.Module, plan: FitPlan
|
|
52
|
+
) -> Optimization | torch.optim.Optimizer: ...
|
|
53
|
+
|
|
54
|
+
def train_epoch(self, trainer: Trainer[BatchT], loader: Iterable[BatchT]) -> float:
|
|
55
|
+
"""Runs one training epoch and returns its mean training loss."""
|
|
56
|
+
...
|
|
57
|
+
|
|
58
|
+
def validation_step(self, model: nn.Module, batch: BatchT, ctx: StepContext) -> Step: ...
|