adambridge 0.1.2__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.
adambridge/__init__.py ADDED
@@ -0,0 +1,22 @@
1
+ """adambridge: AdamW with host-offloaded state, fused SIMD CPU kernels, and
2
+ layer-wise overlap of optimizer updates with the GPU backward pass."""
3
+
4
+ from . import hardware, native, precision
5
+ from .autotune import AutoTuneConfig
6
+ from .engine import StepStats
7
+ from .optimizer import AdamBridge, OptiComputeAdamW
8
+ from .precision import bytes_per_param
9
+
10
+ __version__ = "0.1.2"
11
+
12
+ __all__ = [
13
+ "AdamBridge",
14
+ "OptiComputeAdamW",
15
+ "AutoTuneConfig",
16
+ "StepStats",
17
+ "bytes_per_param",
18
+ "hardware",
19
+ "native",
20
+ "precision",
21
+ "__version__",
22
+ ]
adambridge/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """``python -m adambridge {build,info}``: build the native kernels or show what will be used."""
2
+
3
+ import sys
4
+
5
+ from .native import _main
6
+
7
+ if __name__ == "__main__":
8
+ raise SystemExit(_main(sys.argv[1:]))
adambridge/autotune.py ADDED
@@ -0,0 +1,144 @@
1
+ """Runtime auto-tuning: moment precision and worker thread count.
2
+
3
+ Precision: after a warm-up, the tuner compares the host update time with the
4
+ GPU backward time (first to last gradient-ready event). While the host is the
5
+ bottleneck it steps the moment precision down one level (fp32 -> bf16 ->
6
+ fp8) and keeps the change only if host time actually drops; otherwise it
7
+ reverts and stops. A lower precision moves fewer bytes but does more
8
+ arithmetic per element (FP8 decodes, rescales and re-encodes every block),
9
+ so the measurement, not the byte count, decides.
10
+
11
+ Threads: a short micro-benchmark of the update kernel per compute pool,
12
+ picking the fastest thread count (memory-bound kernels usually saturate
13
+ DRAM bandwidth before all cores are busy).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ import statistics
20
+ import time
21
+ from dataclasses import dataclass, field
22
+
23
+ import torch
24
+
25
+ from .engine import StepStats, UpdateEngine
26
+ from .kernels import StepCoefficients
27
+ from .precision import PRECISIONS, canonical_precision, make_store
28
+
29
+ __all__ = ["AutoTuneConfig", "AutoTuner", "benchmark_threads"]
30
+
31
+ log = logging.getLogger("adambridge")
32
+
33
+
34
+ @dataclass
35
+ class AutoTuneConfig:
36
+ warmup_steps: int = 3 # steps ignored after start-up or a precision change
37
+ window: int = 5 # steps per measurement (median)
38
+ threshold: float = 1.0 # host is the bottleneck when cpu_update > threshold * gpu_backward
39
+ min_precision: str = "bf16" # lowest precision the tuner may choose
40
+ min_gain: float = 0.05 # keep a downgrade only if host time drops by this fraction
41
+ tune_threads: bool = True
42
+
43
+ def __post_init__(self):
44
+ self.min_precision = canonical_precision(self.min_precision)
45
+
46
+
47
+ @dataclass
48
+ class AutoTuner:
49
+ config: AutoTuneConfig = field(default_factory=AutoTuneConfig)
50
+ done: bool = False
51
+ threads_tuned: bool = False
52
+ decisions: list[str] = field(default_factory=list)
53
+
54
+ def __post_init__(self):
55
+ self._seen = 0
56
+ self._samples: list[StepStats] = []
57
+ self._baseline: tuple[str, float] | None = None # (precision, host time) before the last downgrade
58
+
59
+ def observe(self, stats: StepStats, precision: str) -> str | None:
60
+ """Feed one step's timing; returns a new precision to switch to, or None."""
61
+ if self.done or stats.num_updates == 0:
62
+ return None
63
+ self._seen += 1
64
+ if self._seen <= self.config.warmup_steps:
65
+ return None
66
+ self._samples.append(stats)
67
+ if len(self._samples) < self.config.window:
68
+ return None
69
+
70
+ cpu = statistics.median(s.cpu_update for s in self._samples)
71
+ gpu_vals = [s.gpu_backward for s in self._samples if s.gpu_backward]
72
+ gpu = statistics.median(gpu_vals) if gpu_vals else None
73
+ self._samples.clear()
74
+
75
+ if self._baseline is not None:
76
+ prev_precision, prev_cpu = self._baseline
77
+ self._baseline = None
78
+ if cpu > prev_cpu * (1.0 - self.config.min_gain):
79
+ return self._finish(
80
+ f"{precision} did not reduce host time ({cpu * 1e3:.1f} ms vs "
81
+ f"{prev_cpu * 1e3:.1f} ms); reverting to {prev_precision}",
82
+ prev_precision,
83
+ )
84
+ if gpu is None:
85
+ return self._finish("no GPU backward timing available; keeping " + precision)
86
+ if cpu <= self.config.threshold * gpu:
87
+ return self._finish(f"host update {cpu * 1e3:.1f} ms hidden behind backward {gpu * 1e3:.1f} ms; keeping {precision}")
88
+
89
+ levels = list(PRECISIONS)
90
+ i = levels.index(precision)
91
+ if i + 1 >= len(levels) or i + 1 > levels.index(self.config.min_precision):
92
+ return self._finish(f"host-bound ({cpu * 1e3:.1f} ms vs {gpu * 1e3:.1f} ms) at lowest allowed precision {precision}")
93
+ nxt = levels[i + 1]
94
+ self._baseline = (precision, cpu)
95
+ self._seen = 0
96
+ self.decisions.append(f"host-bound ({cpu * 1e3:.1f} ms vs {gpu * 1e3:.1f} ms): trying {nxt} moments")
97
+ log.info("adambridge autotune: %s", self.decisions[-1])
98
+ return nxt
99
+
100
+ def _finish(self, reason: str, precision: str | None = None) -> str | None:
101
+ self.done = True
102
+ self.decisions.append(reason)
103
+ log.info("adambridge autotune: %s", reason)
104
+ return precision
105
+
106
+
107
+ def benchmark_threads(
108
+ engine: UpdateEngine, device: torch.device, numel: int = 1 << 22, repeats: int = 3
109
+ ) -> dict[int, float]:
110
+ """Time the update kernel for several thread counts; set the fastest. Returns {threads: seconds}."""
111
+ pool = engine.ensure_pool(device)
112
+ out_dtype = torch.bfloat16 if device.type == "cuda" else None
113
+ grad_dtype = torch.bfloat16 if out_dtype else torch.float32
114
+ if not engine.uses_native(grad_dtype, engine.precision, out_dtype):
115
+ return {} # the PyTorch kernel is parallelized by ATen, not by the pool
116
+
117
+ def alloc():
118
+ master = torch.randn(numel)
119
+ grad = torch.randn(numel, dtype=grad_dtype) * 1e-3
120
+ m = make_store(engine.precision, numel, "m")
121
+ v = make_store(engine.precision, numel, "v")
122
+ out = torch.empty(numel, dtype=out_dtype) if out_dtype else None
123
+ return master, grad, m, v, out
124
+
125
+ master, grad, m, v, out = pool.call(alloc)
126
+ c = StepCoefficients.for_step(1e-4, 0.9, 0.999, 1e-8, 0.0, 10)
127
+ candidates = sorted({k for k in (1, 2, 4, 8, 12, 16, 24, 32, 48, 64) if k < pool.max_threads} | {pool.max_threads})
128
+ timings: dict[int, float] = {}
129
+ for k in candidates:
130
+ pool.parallelism = k
131
+ engine.run_kernel(master, grad, m, v, out, c, 0, pool) # warm caches / page in
132
+ samples = []
133
+ for _ in range(repeats):
134
+ t0 = time.perf_counter()
135
+ engine.run_kernel(master, grad, m, v, out, c, 0, pool)
136
+ samples.append(time.perf_counter() - t0)
137
+ timings[k] = min(samples)
138
+ best = min(timings, key=timings.get)
139
+ # Within 3% of the best, prefer fewer threads: leaves cores for the training loop.
140
+ best = min(k for k, t in timings.items() if t <= timings[best] * 1.03)
141
+ pool.parallelism = best
142
+ log.info("adambridge: %d update threads for %s (%s)", best, device,
143
+ ", ".join(f"{k}: {t * 1e3:.2f} ms" for k, t in timings.items()))
144
+ return timings