novatensor 0.1.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.
novatensor/__init__.py ADDED
@@ -0,0 +1,46 @@
1
+ """NovaTensor: automatic, verified training-configuration discovery for PyTorch.
2
+
3
+ NovaTensor does not invent new ways to make PyTorch fast. Every optimization it
4
+ applies already ships with PyTorch -- automatic mixed precision, channels_last
5
+ memory format, cuDNN autotuning, torch.compile, DataLoader worker and prefetch
6
+ tuning. What NovaTensor adds is finding the right combination for *your*
7
+ hardware, proving on your machine that each one actually helped, and refusing to
8
+ apply the ones that did not.
9
+
10
+ The decision core (`novatensor.measure`, `novatensor.policy`) deliberately does
11
+ not import torch, so the logic deciding whether to alter someone's training run
12
+ is testable without a GPU.
13
+ """
14
+
15
+ from novatensor.measure import (
16
+ Comparison,
17
+ Summary,
18
+ Verdict,
19
+ WallClockComparison,
20
+ compare,
21
+ compare_wall_clock,
22
+ summarize,
23
+ )
24
+ from novatensor.policy import Decision, EquivalenceCheck, Risk, should_accept
25
+ from novatensor.tune import Trial, TuneResult, tune
26
+
27
+ #: Single source of truth for the version; pyproject.toml reads this.
28
+ __version__ = "0.1.0"
29
+
30
+ __all__ = [
31
+ "Comparison",
32
+ "Decision",
33
+ "EquivalenceCheck",
34
+ "Risk",
35
+ "Summary",
36
+ "Verdict",
37
+ "WallClockComparison",
38
+ "compare",
39
+ "compare_wall_clock",
40
+ "should_accept",
41
+ "summarize",
42
+ "Trial",
43
+ "TuneResult",
44
+ "tune",
45
+ "__version__",
46
+ ]
@@ -0,0 +1,5 @@
1
+ """Thin PyTorch-facing layers: probing, equivalence checking, applying configs.
2
+
3
+ Everything in this subpackage imports torch. The decision logic it feeds lives
4
+ in `novatensor.measure` and `novatensor.policy`, which do not.
5
+ """
@@ -0,0 +1,178 @@
1
+ """Automatic mixed precision: the single largest win available on most GPUs.
2
+
3
+ Why this is first: on tensor-core hardware, running matmuls and convolutions in
4
+ half precision roughly halves the arithmetic cost and the memory traffic, which
5
+ on a memory-bound laptop GPU is usually the dominant term. Nothing else in the
6
+ toolbox offers a comparable return for as little risk.
7
+
8
+ Two half-precision formats exist and the choice is not cosmetic:
9
+
10
+ * **FP16** has 10 mantissa bits and a narrow exponent range. It is the faster
11
+ option on most hardware but gradients can underflow to zero, so it requires a
12
+ GradScaler that multiplies the loss by a large factor before backward and
13
+ divides the gradients afterwards.
14
+ * **BF16** has 8 mantissa bits but the same exponent range as FP32, so
15
+ underflow is not a practical concern and no scaler is needed. It is less
16
+ precise per-value and needs Ampere (sm_80) or newer.
17
+
18
+ BF16 is tried first where available, because a configuration with no loss
19
+ scaling has strictly fewer ways to go wrong.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from dataclasses import dataclass
25
+ from typing import Any, Callable
26
+
27
+ from novatensor.capabilities import Capabilities
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class AmpCandidate:
32
+ """One mixed-precision configuration to evaluate."""
33
+
34
+ name: str
35
+ dtype_name: str # "bfloat16" | "float16"
36
+ needs_scaler: bool
37
+ #: Fixed loss scale used during equivalence checking, in place of the
38
+ #: stateful GradScaler. FP16 needs one or small gradients underflow to zero;
39
+ #: BF16 keeps FP32's exponent range and needs none.
40
+ equiv_scale: float = 1.0
41
+ #: Mantissa bits in this format's significand, excluding the implicit bit.
42
+ #: bf16 has 8, fp16 has 10 -- bf16 buys fp32's exponent range by spending
43
+ #: precision, so it is the coarser of the two despite being the more robust.
44
+ mantissa_bits: int = 23
45
+
46
+ @property
47
+ def deviation_floor(self) -> float:
48
+ """Smallest gradient-direction deviation this format can achieve.
49
+
50
+ One unit in the last place, 2**-mantissa_bits, is the relative
51
+ resolution of a single value, and no correct implementation can do
52
+ better. Judging a format against this rather than a fixed constant is
53
+ what lets one threshold be fair to both bf16 and fp16.
54
+ """
55
+ return 2.0 ** -self.mantissa_bits
56
+
57
+ def dtype(self) -> Any:
58
+ import torch
59
+
60
+ return getattr(torch, self.dtype_name)
61
+
62
+ def make_scaler(self, device_type: str) -> Any | None:
63
+ if not self.needs_scaler:
64
+ return None
65
+ import torch
66
+
67
+ # torch.cuda.amp.GradScaler is deprecated from torch 2.4; the
68
+ # device-generic form is the current API.
69
+ try:
70
+ return torch.amp.GradScaler(device_type)
71
+ except (AttributeError, TypeError): # pragma: no cover - older torch
72
+ return torch.cuda.amp.GradScaler()
73
+
74
+
75
+ BF16 = AmpCandidate(
76
+ "bf16 autocast", "bfloat16", needs_scaler=False, mantissa_bits=8
77
+ )
78
+ FP16 = AmpCandidate(
79
+ "fp16 autocast + GradScaler", "float16", needs_scaler=True,
80
+ equiv_scale=1024.0, mantissa_bits=10,
81
+ )
82
+
83
+
84
+ def candidates_for(caps: Capabilities) -> list[AmpCandidate]:
85
+ """Which AMP configurations are worth trying on this machine.
86
+
87
+ Returns an empty list rather than a guess when the hardware has no
88
+ tensor cores: autocast on such a device adds cast overhead for no
89
+ arithmetic benefit and reliably makes training slower.
90
+ """
91
+ if not caps.is_cuda:
92
+ return []
93
+ out: list[AmpCandidate] = []
94
+ if caps.supports_bf16:
95
+ out.append(BF16)
96
+ if caps.supports_fp16:
97
+ out.append(FP16)
98
+ return out
99
+
100
+
101
+ def make_batch_step(
102
+ model,
103
+ optimizer,
104
+ loss_fn: Callable[[Any, Any], Any],
105
+ device: Any,
106
+ *,
107
+ candidate: AmpCandidate | None = None,
108
+ scaler: Any | None = None,
109
+ backward_only: bool = False,
110
+ manual_scale: float = 1.0,
111
+ ) -> Callable[[Any], Any]:
112
+ """Build a closure performing one training step on a given batch.
113
+
114
+ ``candidate=None`` gives the FP32 baseline. ``backward_only=True`` stops
115
+ before the optimizer step, which is what the equivalence check needs: the
116
+ gradients stay available for inspection and the weights never move.
117
+
118
+ ``manual_scale`` multiplies the loss before backward, replacing GradScaler
119
+ for equivalence checking. GradScaler is stateful: ``unscale_`` may be called
120
+ only once between ``update()`` calls, so a check that does backward without
121
+ stepping raises on its second batch. A fixed scale applied here, and divided
122
+ out by the caller, is the same arithmetic with none of the bookkeeping -- and
123
+ being deterministic, it is what a correctness check should use anyway.
124
+ """
125
+ import torch
126
+
127
+ device_type = device.type if hasattr(device, "type") else str(device)
128
+
129
+ def step(batch: Any) -> Any:
130
+ x, y = batch
131
+ optimizer.zero_grad(set_to_none=True)
132
+
133
+ if candidate is None:
134
+ loss = loss_fn(model(x), y)
135
+ loss.backward()
136
+ if not backward_only:
137
+ optimizer.step()
138
+ return loss
139
+
140
+ with torch.autocast(device_type=device_type, dtype=candidate.dtype()):
141
+ loss = loss_fn(model(x), y)
142
+
143
+ if scaler is None:
144
+ (loss * manual_scale if manual_scale != 1.0 else loss).backward()
145
+ if not backward_only:
146
+ optimizer.step()
147
+ else:
148
+ scaler.scale(loss).backward()
149
+ if not backward_only:
150
+ scaler.step(optimizer)
151
+ scaler.update()
152
+ return loss
153
+
154
+ return step
155
+
156
+
157
+ def make_step_fn(
158
+ model,
159
+ optimizer,
160
+ loss_fn: Callable[[Any, Any], Any],
161
+ batches: list[Any],
162
+ device: Any,
163
+ *,
164
+ candidate: AmpCandidate | None = None,
165
+ scaler: Any | None = None,
166
+ backward_only: bool = False,
167
+ ) -> Callable[[int], Any]:
168
+ """Index-taking form of :func:`make_batch_step`, for `timing.probe_steps`.
169
+
170
+ Cycling by index rather than iterating keeps every trial on exactly the same
171
+ sequence of batches, and avoids identifying a batch by value -- comparing
172
+ tensors for equality raises rather than returning a bool.
173
+ """
174
+ inner = make_batch_step(
175
+ model, optimizer, loss_fn, device,
176
+ candidate=candidate, scaler=scaler, backward_only=backward_only,
177
+ )
178
+ return lambda i: inner(batches[i % len(batches)])
@@ -0,0 +1,170 @@
1
+ """Measuring throughput at different batch sizes.
2
+
3
+ On a 4 GB GPU this search spends most of its time near the out-of-memory edge,
4
+ which makes cleanup the hard part rather than the search strategy. A trial that
5
+ fails and leaves tensors reachable removes that memory from every later trial's
6
+ budget, so subsequent sizes report OOM at values that would in fact have fitted.
7
+ The result is a search that finds a smaller optimum the second time it runs --
8
+ reproducibly wrong rather than obviously broken.
9
+
10
+ So every trial runs inside `timing.released_memory`, which collects and empties
11
+ the caching allocator on the way out, and the search continues past an OOM
12
+ rather than stopping, since a larger size failing says nothing about a smaller
13
+ one.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import Any, Callable
19
+
20
+ from novatensor.adapters.configs import TrainingConfig
21
+ from novatensor.measure.throughput import BatchResult
22
+
23
+
24
+ def rebuild_with_batch_size(loader: Any, batch_size: int) -> Any:
25
+ """A DataLoader like ``loader`` but with a different batch size.
26
+
27
+ The sampler is reused where possible so shuffling behaviour is preserved
28
+ exactly. A batch_sampler encodes its own batch size, so when one is present
29
+ it is replaced rather than reused -- the alternative is silently measuring
30
+ the original batch size and reporting it under a different label.
31
+ """
32
+ from torch.utils.data import BatchSampler, DataLoader
33
+
34
+ kwargs: dict[str, Any] = {
35
+ "dataset": loader.dataset,
36
+ "batch_size": batch_size,
37
+ "collate_fn": loader.collate_fn,
38
+ "drop_last": loader.drop_last,
39
+ "num_workers": loader.num_workers,
40
+ "pin_memory": loader.pin_memory,
41
+ "timeout": loader.timeout,
42
+ "worker_init_fn": loader.worker_init_fn,
43
+ }
44
+ if loader.num_workers > 0:
45
+ kwargs["persistent_workers"] = loader.persistent_workers
46
+ if getattr(loader, "prefetch_factor", None) is not None:
47
+ kwargs["prefetch_factor"] = loader.prefetch_factor
48
+
49
+ if isinstance(loader.batch_sampler, BatchSampler):
50
+ kwargs["sampler"] = loader.batch_sampler.sampler
51
+ else:
52
+ kwargs["sampler"] = loader.sampler
53
+ return DataLoader(**kwargs)
54
+
55
+
56
+ def batches_available(loader: Any, batch_size: int) -> int:
57
+ """How many batches this dataset yields at a given batch size.
58
+
59
+ Worth checking before trusting a large-batch measurement: with few batches
60
+ per epoch, DataLoader prefetching covers a large fraction of them and the
61
+ timing reflects prefetch coverage rather than batch size. Measured on a
62
+ 7,680-sample dataset, a batch of 1024 left only 7 batches per epoch and
63
+ reported higher throughput than batches a quarter its size.
64
+ """
65
+ try:
66
+ return max(0, len(loader.dataset) // batch_size)
67
+ except TypeError: # an iterable-style dataset has no length
68
+ return -1
69
+
70
+
71
+ def trial_batch_size(
72
+ model: Any,
73
+ optimizer: Any,
74
+ loss_fn: Callable[[Any, Any], Any],
75
+ loader: Any,
76
+ device: Any,
77
+ batch_size: int,
78
+ config: TrainingConfig | None = None,
79
+ *,
80
+ # At least as many blocks as `compare` needs samples, or every comparison
81
+ # comes back UNRELIABLE and the search can never recommend anything.
82
+ n_blocks: int = 12,
83
+ block_size: int = 4,
84
+ warmup: int = 6,
85
+ ) -> BatchResult:
86
+ """Time one batch size, surviving out-of-memory.
87
+
88
+ Out-of-memory is an expected outcome here rather than a failure, so it is
89
+ returned as data. Memory is released on every exit path, including the
90
+ failing ones.
91
+ """
92
+ import time
93
+
94
+ import torch
95
+
96
+ from novatensor.adapters import configs as cfg
97
+ from novatensor.adapters import layout
98
+ from novatensor.adapters.timing import preserved, released_memory, synchronize
99
+
100
+ cfg_used = config or TrainingConfig()
101
+ device_type = device.type if hasattr(device, "type") else str(device)
102
+
103
+ with released_memory(device_type), preserved(model, optimizer):
104
+ if cfg_used.channels_last:
105
+ layout.apply_to_model(model)
106
+ cfg.apply_globals(cfg_used)
107
+ if device_type == "cuda":
108
+ torch.cuda.reset_peak_memory_stats()
109
+
110
+ try:
111
+ trial_loader = rebuild_with_batch_size(loader, batch_size)
112
+ step = cfg.make_step(
113
+ model, optimizer, loss_fn, device, cfg_used,
114
+ scaler=cfg_used.make_scaler(device_type),
115
+ )
116
+ it = iter(trial_loader)
117
+ non_blocking = bool(trial_loader.pin_memory)
118
+
119
+ def one_step() -> None:
120
+ nonlocal it
121
+ try:
122
+ batch = next(it)
123
+ except StopIteration:
124
+ it = iter(trial_loader)
125
+ batch = next(it)
126
+ x, y = batch
127
+ x = x.to(device, non_blocking=non_blocking)
128
+ y = y.to(device, non_blocking=non_blocking)
129
+ if cfg_used.channels_last:
130
+ x = layout.apply_to_input(x)
131
+ step((x, y))
132
+
133
+ for _ in range(warmup):
134
+ one_step()
135
+ synchronize(device_type)
136
+
137
+ timings: list[float] = []
138
+ for _ in range(n_blocks):
139
+ synchronize(device_type)
140
+ start = time.perf_counter()
141
+ for _ in range(block_size):
142
+ one_step()
143
+ synchronize(device_type)
144
+ timings.append((time.perf_counter() - start) / block_size)
145
+
146
+ peak = (
147
+ torch.cuda.max_memory_allocated() if device_type == "cuda" else 0
148
+ )
149
+ return BatchResult(
150
+ batch_size=batch_size,
151
+ step_times_s=tuple(timings),
152
+ peak_vram_bytes=peak,
153
+ )
154
+
155
+ except torch.cuda.OutOfMemoryError:
156
+ return BatchResult(
157
+ batch_size=batch_size,
158
+ step_times_s=(),
159
+ peak_vram_bytes=(
160
+ torch.cuda.max_memory_allocated() if device_type == "cuda" else 0
161
+ ),
162
+ out_of_memory=True,
163
+ )
164
+ except Exception as exc:
165
+ return BatchResult(
166
+ batch_size=batch_size,
167
+ step_times_s=(),
168
+ out_of_memory=False,
169
+ error=f"{type(exc).__name__}: {exc}",
170
+ )
@@ -0,0 +1,193 @@
1
+ """Combinations of optimizations, and the training step they produce.
2
+
3
+ Once there is more than one optimization, candidates stop being a list and
4
+ become a lattice: mixed precision and channels_last are not alternatives, they
5
+ compose, and the combination can be worth more than either alone. This module
6
+ represents a point in that lattice and builds the training step it implies.
7
+
8
+ Keeping combination explicit matters for honesty. Measuring A, measuring B, and
9
+ multiplying their speedups is a guess -- optimizations interact, sometimes
10
+ negatively. Enumerating the combinations and measuring each one costs more GPU
11
+ time and tells the truth.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import dataclass
17
+ from typing import Any, Callable
18
+
19
+ from novatensor.adapters import layout
20
+ from novatensor.adapters.amp import AmpCandidate, candidates_for
21
+ from novatensor.capabilities import Capabilities
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class TrainingConfig:
26
+ """One combination of optimizations to evaluate."""
27
+
28
+ amp: AmpCandidate | None = None
29
+ channels_last: bool = False
30
+ #: torch.backends.cudnn.benchmark. Off by default in PyTorch, which means
31
+ #: cuDNN picks a convolution algorithm from a heuristic rather than timing
32
+ #: the candidates. The heuristic can choose badly for unusual
33
+ #: layout/precision combinations, and when it does the cost is large.
34
+ cudnn_benchmark: bool = False
35
+
36
+ @property
37
+ def name(self) -> str:
38
+ parts = []
39
+ if self.amp is not None:
40
+ parts.append(self.amp.name)
41
+ if self.channels_last:
42
+ parts.append("channels_last")
43
+ if self.cudnn_benchmark:
44
+ parts.append("cudnn.benchmark")
45
+ return " + ".join(parts) if parts else "fp32 baseline"
46
+
47
+ @property
48
+ def is_baseline(self) -> bool:
49
+ return (
50
+ self.amp is None
51
+ and not self.channels_last
52
+ and not self.cudnn_benchmark
53
+ )
54
+
55
+ @property
56
+ def equiv_scale(self) -> float:
57
+ return self.amp.equiv_scale if self.amp is not None else 1.0
58
+
59
+ @property
60
+ def deviation_floor(self) -> float:
61
+ """Smallest gradient deviation this combination could achieve.
62
+
63
+ The coarsest component sets the floor: reordering float32 reductions
64
+ contributes round-off at 2**-23, which is swamped by any reduced
65
+ precision, so a combination is judged by whichever is looser.
66
+ """
67
+ # cuDNN autotuning can select a different algorithm, which accumulates
68
+ # in a different order -- float32 round-off, same as a layout change.
69
+ floors = (
70
+ [layout.FP32_REORDER_FLOOR]
71
+ if (self.channels_last or self.cudnn_benchmark)
72
+ else []
73
+ )
74
+ if self.amp is not None:
75
+ floors.append(self.amp.deviation_floor)
76
+ return max(floors) if floors else 0.0
77
+
78
+ def make_scaler(self, device_type: str) -> Any | None:
79
+ return self.amp.make_scaler(device_type) if self.amp is not None else None
80
+
81
+
82
+ def enumerate_configs(
83
+ caps: Capabilities, model: Any, *, include_cudnn_benchmark: bool = True
84
+ ) -> list[TrainingConfig]:
85
+ """Which combinations are worth measuring on this machine and model.
86
+
87
+ Every component is offered alone as well as combined. This is not
88
+ thoroughness for its own sake: measured on an RTX 3050, channels_last alone
89
+ was 0.262x (badly slower) while bf16 + channels_last was 1.894x, the best
90
+ configuration available. Multiplying the separately-measured speedups would
91
+ have predicted 0.42x and discarded the winner. channels_last is not an
92
+ independent speedup but a precondition -- NHWC exists to feed tensor-core
93
+ kernels, and without reduced precision there are none to feed.
94
+
95
+ Interactions like that cannot be inferred, only measured, which is why the
96
+ lattice is enumerated rather than composed.
97
+ """
98
+ amps = candidates_for(caps)
99
+ cl_ok = layout.inspect_model(model).applicable and caps.is_cuda
100
+ bench_options = (
101
+ (False, True) if (include_cudnn_benchmark and caps.cudnn_available)
102
+ else (False,)
103
+ )
104
+
105
+ configs: list[TrainingConfig] = []
106
+ for bench in bench_options:
107
+ if bench:
108
+ configs.append(TrainingConfig(cudnn_benchmark=True))
109
+ if cl_ok:
110
+ configs.append(
111
+ TrainingConfig(channels_last=True, cudnn_benchmark=bench)
112
+ )
113
+ for a in amps:
114
+ configs.append(TrainingConfig(amp=a, cudnn_benchmark=bench))
115
+ if cl_ok:
116
+ configs.append(
117
+ TrainingConfig(
118
+ amp=a, channels_last=True, cudnn_benchmark=bench
119
+ )
120
+ )
121
+ return configs
122
+
123
+
124
+ def apply_globals(config: TrainingConfig) -> None:
125
+ """Set the process-wide flags a config needs.
126
+
127
+ Must be called inside a `timing.preserved` block, which snapshots and
128
+ restores these flags -- they are global, so a leak would silently change
129
+ every later trial and the user's own training afterwards.
130
+ """
131
+ import torch
132
+
133
+ torch.backends.cudnn.benchmark = config.cudnn_benchmark
134
+
135
+
136
+ def make_step(
137
+ model,
138
+ optimizer,
139
+ loss_fn: Callable[[Any, Any], Any],
140
+ device: Any,
141
+ config: TrainingConfig,
142
+ *,
143
+ scaler: Any | None = None,
144
+ backward_only: bool = False,
145
+ manual_scale: float = 1.0,
146
+ ) -> Callable[[Any], Any]:
147
+ """Build a closure performing one training step under ``config``.
148
+
149
+ The model must already have been converted by the caller if
150
+ ``config.channels_last`` is set; this function converts the *inputs* only.
151
+ Separating the two is deliberate: the model conversion is a one-off that
152
+ belongs outside any timed region, while input conversion happens per step
153
+ and must be inside it, since the user's loop would pay that cost too.
154
+ """
155
+ import torch
156
+
157
+ device_type = device.type if hasattr(device, "type") else str(device)
158
+ dtype = config.amp.dtype() if config.amp is not None else None
159
+
160
+ def step(batch: Any) -> Any:
161
+ x, y = batch
162
+ if config.channels_last:
163
+ x = layout.apply_to_input(x)
164
+
165
+ optimizer.zero_grad(set_to_none=True)
166
+
167
+ if dtype is None:
168
+ loss = loss_fn(model(x), y)
169
+ (loss * manual_scale if manual_scale != 1.0 else loss).backward()
170
+ if not backward_only:
171
+ optimizer.step()
172
+ return loss
173
+
174
+ with torch.autocast(device_type=device_type, dtype=dtype):
175
+ loss = loss_fn(model(x), y)
176
+
177
+ if scaler is None:
178
+ (loss * manual_scale if manual_scale != 1.0 else loss).backward()
179
+ if not backward_only:
180
+ optimizer.step()
181
+ else:
182
+ scaler.scale(loss).backward()
183
+ if not backward_only:
184
+ scaler.step(optimizer)
185
+ scaler.update()
186
+ return loss
187
+
188
+ return step
189
+
190
+
191
+ def indexed(step: Callable[[Any], Any], batches: list[Any]) -> Callable[[int], Any]:
192
+ """Adapt a batch-taking step to the index-taking form `probe_steps` wants."""
193
+ return lambda i: step(batches[i % len(batches)])