prolearn 0.1.0.dev0__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.
- prolearn/__init__.py +10 -0
- prolearn/py.typed +0 -0
- prolearn/resources.py +711 -0
- prolearn/result.schema.json +396 -0
- prolearn/results.py +118 -0
- prolearn-0.1.0.dev0.dist-info/METADATA +63 -0
- prolearn-0.1.0.dev0.dist-info/RECORD +9 -0
- prolearn-0.1.0.dev0.dist-info/WHEEL +4 -0
- prolearn-0.1.0.dev0.dist-info/licenses/LICENSE +32 -0
prolearn/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""prolearn: prospective learning in Python.
|
|
2
|
+
|
|
3
|
+
Prospective learning studies learners whose data come from a process that
|
|
4
|
+
changes over time, and whose goal is low risk on the future rather than on
|
|
5
|
+
the past.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__version__ = "0.1.0.dev0"
|
|
9
|
+
|
|
10
|
+
__all__ = ["__version__"]
|
prolearn/py.typed
ADDED
|
File without changes
|
prolearn/resources.py
ADDED
|
@@ -0,0 +1,711 @@
|
|
|
1
|
+
"""Meter the computation a learner spends, step by step and over time.
|
|
2
|
+
|
|
3
|
+
A :class:`ResourceMeter` records each call a learner makes under a step name,
|
|
4
|
+
``"perceive"``, ``"learn"`` or ``"predict"``. The caller opens and closes every
|
|
5
|
+
call::
|
|
6
|
+
|
|
7
|
+
meter = ResourceMeter()
|
|
8
|
+
with meter.measure("learn"):
|
|
9
|
+
learner.partial_fit(X, y)
|
|
10
|
+
meter.add_updates(1)
|
|
11
|
+
with meter.measure("predict", n_samples=len(X_future)):
|
|
12
|
+
learner.predict(X_future)
|
|
13
|
+
record = meter.snapshot(learner)
|
|
14
|
+
|
|
15
|
+
Every reading is a dictionary ``{"value": ..., "status": ...}``. The status is
|
|
16
|
+
``"measured"``, ``"estimated"`` or ``"absent"``. An absent reading has a null
|
|
17
|
+
value, so a missing measure is never recorded as zero.
|
|
18
|
+
|
|
19
|
+
Training readings cover the ``"perceive"`` and ``"learn"`` calls and are
|
|
20
|
+
cumulative from the first call. Inference readings cover the ``"predict"``
|
|
21
|
+
calls since the previous snapshot, as means per predicted sample.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import contextlib
|
|
27
|
+
import functools
|
|
28
|
+
import importlib
|
|
29
|
+
import importlib.metadata
|
|
30
|
+
import math
|
|
31
|
+
import os
|
|
32
|
+
import pickle
|
|
33
|
+
import platform
|
|
34
|
+
import resource
|
|
35
|
+
import shutil
|
|
36
|
+
import subprocess
|
|
37
|
+
import sys
|
|
38
|
+
import time
|
|
39
|
+
import warnings
|
|
40
|
+
from collections.abc import Generator
|
|
41
|
+
from dataclasses import dataclass
|
|
42
|
+
from pathlib import Path
|
|
43
|
+
from typing import Any, Literal
|
|
44
|
+
|
|
45
|
+
__all__ = ["ResourceMeter"]
|
|
46
|
+
|
|
47
|
+
Status = Literal["measured", "estimated", "absent"]
|
|
48
|
+
Reading = dict[str, Any]
|
|
49
|
+
|
|
50
|
+
STEPS = ("perceive", "learn", "predict")
|
|
51
|
+
TRAIN_STEPS = ("perceive", "learn")
|
|
52
|
+
VERSION_PACKAGES = (
|
|
53
|
+
"prolearn",
|
|
54
|
+
"numpy",
|
|
55
|
+
"scikit-learn",
|
|
56
|
+
"torch",
|
|
57
|
+
"jsonschema",
|
|
58
|
+
"zeus",
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _is_count(n: object, *, minimum: int) -> bool:
|
|
63
|
+
"""Whether ``n`` is an integer of at least ``minimum``, and not a bool."""
|
|
64
|
+
return isinstance(n, int) and not isinstance(n, bool) and n >= minimum
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _reading(value: float | None, status: Status) -> Reading:
|
|
68
|
+
if status == "absent":
|
|
69
|
+
return {"value": None, "status": "absent"}
|
|
70
|
+
return {"value": value, "status": status}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class _Call:
|
|
75
|
+
"""One metered call."""
|
|
76
|
+
|
|
77
|
+
step: str
|
|
78
|
+
start: float
|
|
79
|
+
end: float = 0.0
|
|
80
|
+
n_samples: int | None = None
|
|
81
|
+
flops: float | None = None
|
|
82
|
+
flops_status: Status = "absent"
|
|
83
|
+
updates: int | None = None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass
|
|
87
|
+
class _Totals:
|
|
88
|
+
"""Sums over a set of calls, with the status each sum earns."""
|
|
89
|
+
|
|
90
|
+
seconds: float = 0.0
|
|
91
|
+
flops: float = 0.0
|
|
92
|
+
flops_status: Status = "measured"
|
|
93
|
+
joules: float = 0.0
|
|
94
|
+
joules_status: Status = "measured"
|
|
95
|
+
n_samples: int = 0
|
|
96
|
+
n_calls: int = 0
|
|
97
|
+
updates: int = 0
|
|
98
|
+
counted_updates: bool = False
|
|
99
|
+
|
|
100
|
+
def add(self, call: _Call) -> None:
|
|
101
|
+
self.n_calls += 1
|
|
102
|
+
self.seconds += call.end - call.start
|
|
103
|
+
self.n_samples += call.n_samples or 0
|
|
104
|
+
self.flops_status = _combine(self.flops_status, call.flops_status)
|
|
105
|
+
if call.flops is not None:
|
|
106
|
+
self.flops += call.flops
|
|
107
|
+
if call.updates is not None:
|
|
108
|
+
self.updates += call.updates
|
|
109
|
+
self.counted_updates = True
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _combine(total: Status, part: Status) -> Status:
|
|
113
|
+
"""Label a sum: any absent part makes it absent, any estimate an estimate."""
|
|
114
|
+
if "absent" in (total, part):
|
|
115
|
+
return "absent"
|
|
116
|
+
if "estimated" in (total, part):
|
|
117
|
+
return "estimated"
|
|
118
|
+
return "measured"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class _ZeusEnergy:
|
|
122
|
+
"""Read energy counters through Zeus over one window per call.
|
|
123
|
+
|
|
124
|
+
NVML GPU counters and RAPL CPU and DRAM counters are labeled measured.
|
|
125
|
+
Apple silicon readings come from IOReport, which Zeus describes as
|
|
126
|
+
model-based estimates, so they are labeled estimated.
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
key = "prolearn"
|
|
130
|
+
|
|
131
|
+
def __init__(self, monitor: Any) -> None:
|
|
132
|
+
self.monitor = monitor
|
|
133
|
+
parts = []
|
|
134
|
+
if monitor.gpu_indices:
|
|
135
|
+
parts.append("zeus-gpu")
|
|
136
|
+
if monitor.cpu_indices:
|
|
137
|
+
parts.append("zeus-rapl")
|
|
138
|
+
if monitor.soc_is_present:
|
|
139
|
+
parts.append("zeus-apple")
|
|
140
|
+
self.name = "+".join(parts)
|
|
141
|
+
self.window_status: Status = (
|
|
142
|
+
"estimated" if monitor.soc_is_present else "measured"
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
# The meter synchronizes the device itself (decision 168).
|
|
146
|
+
def begin(self) -> None:
|
|
147
|
+
self.monitor.begin_window(self.key, sync_execution=False)
|
|
148
|
+
|
|
149
|
+
def end(self) -> tuple[float, Status]:
|
|
150
|
+
"""Close the window, and return its joules and their label.
|
|
151
|
+
|
|
152
|
+
A GPU reading of 0 J means the window was shorter than the counter's
|
|
153
|
+
update. It is replaced by instant power times the window's length,
|
|
154
|
+
the rule of Zeus's ``approx_instant_energy``, and labeled estimated
|
|
155
|
+
(decision 171).
|
|
156
|
+
"""
|
|
157
|
+
with warnings.catch_warnings():
|
|
158
|
+
warnings.filterwarnings("ignore", message=".*measured as zero.*")
|
|
159
|
+
measurement = self.monitor.end_window(self.key, sync_execution=False)
|
|
160
|
+
status = self.window_status
|
|
161
|
+
for gpu, joules in measurement.gpu_energy.items():
|
|
162
|
+
if joules == 0.0:
|
|
163
|
+
watts = self.monitor.gpus.get_instant_power_usage(gpu) / 1000
|
|
164
|
+
measurement.gpu_energy[gpu] = watts * measurement.time
|
|
165
|
+
status = "estimated"
|
|
166
|
+
return _zeus_joules(measurement), status
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _zeus_joules(measurement: Any) -> float:
|
|
170
|
+
"""Sum every rail of a Zeus measurement, in joules."""
|
|
171
|
+
total = sum(measurement.gpu_energy.values())
|
|
172
|
+
total += sum((measurement.cpu_energy or {}).values())
|
|
173
|
+
total += sum((measurement.dram_energy or {}).values())
|
|
174
|
+
soc = measurement.soc_energy
|
|
175
|
+
if soc is not None:
|
|
176
|
+
# Zeus gives None for a rail this chip does not report.
|
|
177
|
+
rails = (soc.cpu_total_mj, soc.gpu_mj, soc.gpu_sram_mj, soc.ane_mj, soc.dram_mj)
|
|
178
|
+
total += sum(rail or 0 for rail in rails) / 1000
|
|
179
|
+
return float(total)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _start_zeus(gpu: int | None = None) -> _ZeusEnergy | None:
|
|
183
|
+
"""Start a Zeus monitor, or return None if Zeus is missing or finds nothing.
|
|
184
|
+
|
|
185
|
+
``gpu`` is the one CUDA device to read (decision 169). Without it, Zeus
|
|
186
|
+
reads no GPU.
|
|
187
|
+
"""
|
|
188
|
+
try:
|
|
189
|
+
monitor_module = importlib.import_module("zeus.monitor")
|
|
190
|
+
except ImportError:
|
|
191
|
+
return None
|
|
192
|
+
try:
|
|
193
|
+
monitor = monitor_module.ZeusMonitor(gpu_indices=[] if gpu is None else [gpu])
|
|
194
|
+
except Exception: # Zeus raises its own errors for missing hardware.
|
|
195
|
+
return None
|
|
196
|
+
if not (monitor.gpu_indices or monitor.cpu_indices or monitor.soc_is_present):
|
|
197
|
+
return None
|
|
198
|
+
return _ZeusEnergy(monitor)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _other_load(device: str, torch: Any) -> bool | None:
|
|
202
|
+
"""Whether other work loads the machine, by IPW's bounds.
|
|
203
|
+
|
|
204
|
+
The CPU counts as loaded when the one-minute load average exceeds 10% of
|
|
205
|
+
the cores, and a CUDA GPU when its utilization exceeds 5%. Null if neither
|
|
206
|
+
can be read.
|
|
207
|
+
"""
|
|
208
|
+
checks: list[bool] = []
|
|
209
|
+
with contextlib.suppress(OSError, AttributeError):
|
|
210
|
+
checks.append(os.getloadavg()[0] / (os.cpu_count() or 1) > 0.10)
|
|
211
|
+
if device == "cuda" and torch is not None:
|
|
212
|
+
with contextlib.suppress(Exception):
|
|
213
|
+
checks.append(float(torch.cuda.utilization()) > 5)
|
|
214
|
+
return any(checks) if checks else None
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _mv_flops(a_shape: Any, b_shape: Any, *_args: Any, **_kwargs: Any) -> int:
|
|
218
|
+
"""A matrix-vector product: 2 FLOPs per multiply-add, as torch counts mm."""
|
|
219
|
+
m, k = a_shape
|
|
220
|
+
return 2 * m * k
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _dot_flops(a_shape: Any, b_shape: Any, *_args: Any, **_kwargs: Any) -> int:
|
|
224
|
+
"""A dot product of two length-k vectors."""
|
|
225
|
+
return 2 * a_shape[0]
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _addmv_flops(
|
|
229
|
+
self_shape: Any, a_shape: Any, b_shape: Any, *_args: Any, **_kwargs: Any
|
|
230
|
+
) -> int:
|
|
231
|
+
"""``self + A @ v``: the product's FLOPs, as torch counts addmm."""
|
|
232
|
+
return _mv_flops(a_shape, b_shape)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _addmm_activation_flops(
|
|
236
|
+
self_shape: Any, a_shape: Any, b_shape: Any, *_args: Any, **_kwargs: Any
|
|
237
|
+
) -> int:
|
|
238
|
+
"""``act(self + A @ B)``: the product's FLOPs, as torch counts addmm."""
|
|
239
|
+
m, k = a_shape
|
|
240
|
+
return 2 * m * k * b_shape[1]
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _flop_formulas(torch: Any) -> dict[Any, Any]:
|
|
244
|
+
"""Formulas for products torch's FLOP counter has none for (decision 167)."""
|
|
245
|
+
aten = torch.ops.aten
|
|
246
|
+
return {
|
|
247
|
+
aten.mv: _mv_flops,
|
|
248
|
+
aten.dot: _dot_flops,
|
|
249
|
+
aten.addmv: _addmv_flops,
|
|
250
|
+
aten._addmm_activation: _addmm_activation_flops,
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _peak_rss_bytes() -> int:
|
|
255
|
+
"""The process's peak resident set size since it started."""
|
|
256
|
+
peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
|
257
|
+
# macOS reports bytes, Linux kibibytes.
|
|
258
|
+
return peak if sys.platform == "darwin" else peak * 1024
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
class ResourceMeter:
|
|
262
|
+
"""Record the time, FLOPs, energy, memory and updates of a learner's calls.
|
|
263
|
+
|
|
264
|
+
Parameters
|
|
265
|
+
----------
|
|
266
|
+
torch_flops : bool, default=False
|
|
267
|
+
Count the FLOPs of torch operations inside each call with
|
|
268
|
+
``torch.utils.flop_counter.FlopCounterMode``, labeled measured. That
|
|
269
|
+
counter covers the operators it has formulas for, such as matrix
|
|
270
|
+
products and convolutions, plus the meter's own formulas for
|
|
271
|
+
matrix-vector and dot products. Ops without a formula, such as elementwise
|
|
272
|
+
ops, add nothing. Code outside torch, such as an optimizer's update
|
|
273
|
+
written in Python, is not seen. Needs ``prolearn[torch]``.
|
|
274
|
+
energy : bool, default=False
|
|
275
|
+
Read energy over each call. With ``prolearn[energy]`` installed, Zeus
|
|
276
|
+
reads NVML counters on a CUDA GPU, RAPL counters on a Linux CPU, and
|
|
277
|
+
IOReport on Apple silicon without sudo. Counter readings are labeled
|
|
278
|
+
measured and Apple readings estimated. Without Zeus, or where it
|
|
279
|
+
finds no counters, energy is absent. Idle power is measured for
|
|
280
|
+
``idle_seconds`` when the meter starts and recorded, not subtracted.
|
|
281
|
+
device : {"cpu", "cuda", "mps"}, default="cpu"
|
|
282
|
+
The device whose allocator peak is recorded as
|
|
283
|
+
``device_peak_memory_bytes``. For CUDA this is
|
|
284
|
+
``torch.cuda.max_memory_allocated`` on the current device, reset when
|
|
285
|
+
the meter starts. For MPS it is the largest
|
|
286
|
+
``torch.mps.driver_allocated_memory`` read at the end of each call,
|
|
287
|
+
which is a lower bound on the true peak. On CPU it is absent.
|
|
288
|
+
trace_python_memory : bool, default=False
|
|
289
|
+
Trace Python allocations with :mod:`tracemalloc` and record their peak
|
|
290
|
+
as ``python_peak_memory_bytes``, reset when the meter starts. Tracing
|
|
291
|
+
slows every allocation, so it is off by default, and the reading is
|
|
292
|
+
then absent. A meter that starts tracing stops it on :meth:`close`.
|
|
293
|
+
|
|
294
|
+
Notes
|
|
295
|
+
-----
|
|
296
|
+
Calls cannot nest. A call that raises still counts toward the totals,
|
|
297
|
+
and its error reaches the caller. On CUDA and MPS, the meter waits for
|
|
298
|
+
the device's queued work at each call's start and end, so a call's time
|
|
299
|
+
and energy include the GPU work it queued. FLOPs declared with
|
|
300
|
+
:meth:`add_flops` are labeled estimated. A sum that mixes measured and
|
|
301
|
+
estimated parts is estimated, and a sum with any absent part is absent.
|
|
302
|
+
"""
|
|
303
|
+
|
|
304
|
+
idle_seconds = 3.0
|
|
305
|
+
|
|
306
|
+
def __init__(
|
|
307
|
+
self,
|
|
308
|
+
*,
|
|
309
|
+
torch_flops: bool = False,
|
|
310
|
+
energy: bool = False,
|
|
311
|
+
device: Literal["cpu", "cuda", "mps"] = "cpu",
|
|
312
|
+
trace_python_memory: bool = False,
|
|
313
|
+
) -> None:
|
|
314
|
+
if device not in ("cpu", "cuda", "mps"):
|
|
315
|
+
raise ValueError(f"device must be 'cpu', 'cuda' or 'mps', not {device!r}")
|
|
316
|
+
self.torch_flops = torch_flops
|
|
317
|
+
self.device = device
|
|
318
|
+
self.trace_python_memory = trace_python_memory
|
|
319
|
+
self._torch: Any = None
|
|
320
|
+
self._flop_counter: Any = None
|
|
321
|
+
if torch_flops or device != "cpu":
|
|
322
|
+
self._torch = _import_torch()
|
|
323
|
+
if torch_flops:
|
|
324
|
+
module = importlib.import_module("torch.utils.flop_counter")
|
|
325
|
+
self._flop_counter = functools.partial(
|
|
326
|
+
module.FlopCounterMode,
|
|
327
|
+
display=False,
|
|
328
|
+
custom_mapping=_flop_formulas(self._torch),
|
|
329
|
+
)
|
|
330
|
+
self._current: _Call | None = None
|
|
331
|
+
self._train = _Totals()
|
|
332
|
+
self._infer = _Totals()
|
|
333
|
+
self._device_peak: int | None = None
|
|
334
|
+
self._zeus: _ZeusEnergy | None = None
|
|
335
|
+
self._other_load = _other_load(device, self._torch)
|
|
336
|
+
self._idle_watts = _reading(None, "absent")
|
|
337
|
+
if energy:
|
|
338
|
+
self._start_energy()
|
|
339
|
+
# Each meter's peaks are its own, except RSS (decision 170).
|
|
340
|
+
if device == "cuda" and self._torch is not None:
|
|
341
|
+
self._torch.cuda.reset_peak_memory_stats()
|
|
342
|
+
self._started_tracing = False
|
|
343
|
+
if trace_python_memory:
|
|
344
|
+
import tracemalloc
|
|
345
|
+
|
|
346
|
+
if tracemalloc.is_tracing():
|
|
347
|
+
tracemalloc.reset_peak()
|
|
348
|
+
else:
|
|
349
|
+
tracemalloc.start()
|
|
350
|
+
self._started_tracing = True
|
|
351
|
+
|
|
352
|
+
def _start_energy(self) -> None:
|
|
353
|
+
gpu = self._torch.cuda.current_device() if self.device == "cuda" else None
|
|
354
|
+
self._zeus = _start_zeus(gpu)
|
|
355
|
+
self._idle_watts = self._measure_idle()
|
|
356
|
+
|
|
357
|
+
def _measure_idle(self) -> Reading:
|
|
358
|
+
if self.idle_seconds <= 0 or self._zeus is None:
|
|
359
|
+
return _reading(None, "absent")
|
|
360
|
+
self._zeus.begin()
|
|
361
|
+
start = time.perf_counter()
|
|
362
|
+
time.sleep(self.idle_seconds)
|
|
363
|
+
seconds = time.perf_counter() - start
|
|
364
|
+
joules, status = self._zeus.end()
|
|
365
|
+
return _reading(joules / seconds, status)
|
|
366
|
+
|
|
367
|
+
@property
|
|
368
|
+
def _joules_status(self) -> Status:
|
|
369
|
+
"""Every call's energy comes from one source, so it carries one label."""
|
|
370
|
+
return self._zeus.window_status if self._zeus is not None else "absent"
|
|
371
|
+
|
|
372
|
+
@contextlib.contextmanager
|
|
373
|
+
def measure(self, step: str, *, n_samples: int | None = None) -> Generator[None]:
|
|
374
|
+
"""Record one call under ``step``.
|
|
375
|
+
|
|
376
|
+
Parameters
|
|
377
|
+
----------
|
|
378
|
+
step : {"perceive", "learn", "predict"}
|
|
379
|
+
The step the call belongs to.
|
|
380
|
+
n_samples : int, optional
|
|
381
|
+
The number of samples the call predicts. Required for
|
|
382
|
+
``"predict"``, so that inference readings are means per sample.
|
|
383
|
+
|
|
384
|
+
Yields
|
|
385
|
+
------
|
|
386
|
+
None
|
|
387
|
+
The block to meter.
|
|
388
|
+
"""
|
|
389
|
+
if step not in STEPS:
|
|
390
|
+
raise ValueError(f"step must be one of {STEPS}, not {step!r}")
|
|
391
|
+
if self._current is not None:
|
|
392
|
+
raise RuntimeError("meter calls cannot nest")
|
|
393
|
+
if step == "predict" and not _is_count(n_samples, minimum=1):
|
|
394
|
+
raise ValueError(
|
|
395
|
+
"a 'predict' call needs an integer n_samples of at least 1"
|
|
396
|
+
)
|
|
397
|
+
call = _Call(step=step, start=0.0, n_samples=n_samples)
|
|
398
|
+
counter = self._flop_counter() if self.torch_flops else None
|
|
399
|
+
zeus_joules, zeus_status = 0.0, self._joules_status
|
|
400
|
+
window_open = started = False
|
|
401
|
+
self._current = call
|
|
402
|
+
try:
|
|
403
|
+
# Queued GPU work belongs to the call that queued it (decision 168).
|
|
404
|
+
self._sync()
|
|
405
|
+
if self._zeus is not None:
|
|
406
|
+
self._zeus.begin()
|
|
407
|
+
window_open = True
|
|
408
|
+
with counter if counter is not None else contextlib.nullcontext():
|
|
409
|
+
call.start = time.perf_counter()
|
|
410
|
+
started = True
|
|
411
|
+
try:
|
|
412
|
+
yield
|
|
413
|
+
finally:
|
|
414
|
+
try:
|
|
415
|
+
self._sync()
|
|
416
|
+
finally:
|
|
417
|
+
call.end = time.perf_counter()
|
|
418
|
+
finally:
|
|
419
|
+
# A call that raises still spent its resources (decision 166).
|
|
420
|
+
# A call that failed before its clock started spent none.
|
|
421
|
+
self._current = None
|
|
422
|
+
try:
|
|
423
|
+
if window_open and self._zeus is not None:
|
|
424
|
+
zeus_status = "absent" # until the window closes
|
|
425
|
+
zeus_joules, zeus_status = self._zeus.end()
|
|
426
|
+
finally:
|
|
427
|
+
if started:
|
|
428
|
+
self._record(call, counter, zeus_joules, zeus_status)
|
|
429
|
+
|
|
430
|
+
def _sync(self) -> None:
|
|
431
|
+
"""Wait for the device's queued work."""
|
|
432
|
+
if self.device == "cuda":
|
|
433
|
+
self._torch.cuda.synchronize()
|
|
434
|
+
elif self.device == "mps":
|
|
435
|
+
self._torch.mps.synchronize()
|
|
436
|
+
|
|
437
|
+
def _record(
|
|
438
|
+
self, call: _Call, counter: Any, joules: float, joules_status: Status
|
|
439
|
+
) -> None:
|
|
440
|
+
"""Add a finished call to its step's totals.
|
|
441
|
+
|
|
442
|
+
The call is added even when reading its FLOPs or the device peak
|
|
443
|
+
raises (decision 166). A FLOP count that could not be read is absent.
|
|
444
|
+
"""
|
|
445
|
+
totals = self._train if call.step in TRAIN_STEPS else self._infer
|
|
446
|
+
try:
|
|
447
|
+
if counter is not None:
|
|
448
|
+
declared = call.flops_status == "estimated"
|
|
449
|
+
call.flops_status = "absent" # until the count is read
|
|
450
|
+
measured = float(counter.get_total_flops())
|
|
451
|
+
if declared:
|
|
452
|
+
call.flops = (call.flops or 0.0) + measured
|
|
453
|
+
call.flops_status = "estimated"
|
|
454
|
+
else:
|
|
455
|
+
call.flops, call.flops_status = measured, "measured"
|
|
456
|
+
self._read_device_peak()
|
|
457
|
+
finally:
|
|
458
|
+
totals.add(call)
|
|
459
|
+
totals.joules += joules
|
|
460
|
+
totals.joules_status = _combine(totals.joules_status, joules_status)
|
|
461
|
+
|
|
462
|
+
def add_flops(self, n: float) -> None:
|
|
463
|
+
"""Declare ``n`` FLOPs for the current call, labeled estimated.
|
|
464
|
+
|
|
465
|
+
Parameters
|
|
466
|
+
----------
|
|
467
|
+
n : float
|
|
468
|
+
The FLOPs that the caller's formula gives for this call.
|
|
469
|
+
"""
|
|
470
|
+
call = self._require_call("add_flops")
|
|
471
|
+
if not math.isfinite(n) or n < 0:
|
|
472
|
+
raise ValueError("FLOPs must be finite and not negative")
|
|
473
|
+
call.flops = (call.flops or 0.0) + n
|
|
474
|
+
call.flops_status = "estimated"
|
|
475
|
+
|
|
476
|
+
def add_updates(self, n: int = 1) -> None:
|
|
477
|
+
"""Count ``n`` parameter updates in the current call.
|
|
478
|
+
|
|
479
|
+
Parameters
|
|
480
|
+
----------
|
|
481
|
+
n : int, default=1
|
|
482
|
+
The number of updates.
|
|
483
|
+
"""
|
|
484
|
+
call = self._require_call("add_updates")
|
|
485
|
+
if not _is_count(n, minimum=0):
|
|
486
|
+
raise ValueError("updates must be an integer that is not negative")
|
|
487
|
+
call.updates = (call.updates or 0) + n
|
|
488
|
+
|
|
489
|
+
def _require_call(self, name: str) -> _Call:
|
|
490
|
+
if self._current is None:
|
|
491
|
+
raise RuntimeError(f"{name} must be called inside meter.measure(...)")
|
|
492
|
+
return self._current
|
|
493
|
+
|
|
494
|
+
def _read_device_peak(self) -> None:
|
|
495
|
+
if self.device == "mps":
|
|
496
|
+
now = int(self._torch.mps.driver_allocated_memory())
|
|
497
|
+
self._device_peak = max(self._device_peak or 0, now)
|
|
498
|
+
elif self.device == "cuda":
|
|
499
|
+
self._device_peak = int(self._torch.cuda.max_memory_allocated())
|
|
500
|
+
|
|
501
|
+
def snapshot(self, learner: object | None = None) -> dict[str, Reading]:
|
|
502
|
+
"""Return the readings at this checkpoint.
|
|
503
|
+
|
|
504
|
+
Parameters
|
|
505
|
+
----------
|
|
506
|
+
learner : object, optional
|
|
507
|
+
The learner whose state size to record, as the byte length of its
|
|
508
|
+
pickle. That covers its parameters, its retained data and any
|
|
509
|
+
optimizer state. Without it, ``state_bytes`` is absent.
|
|
510
|
+
|
|
511
|
+
Returns
|
|
512
|
+
-------
|
|
513
|
+
dict
|
|
514
|
+
One reading for each of ``train_flops``, ``train_seconds``,
|
|
515
|
+
``train_joules``, ``updates``, ``inference_flops``,
|
|
516
|
+
``inference_seconds``, ``inference_joules``,
|
|
517
|
+
``peak_memory_bytes``, ``device_peak_memory_bytes``,
|
|
518
|
+
``python_peak_memory_bytes`` and ``state_bytes``.
|
|
519
|
+
"""
|
|
520
|
+
train, infer = self._train, self._infer
|
|
521
|
+
self._infer = _Totals()
|
|
522
|
+
readings: dict[str, Reading] = {
|
|
523
|
+
"train_flops": _reading(train.flops, _empty_ok(train.flops_status, train)),
|
|
524
|
+
"train_seconds": _reading(train.seconds, "measured"),
|
|
525
|
+
"train_joules": _reading(
|
|
526
|
+
train.joules, _combine(self._joules_status, train.joules_status)
|
|
527
|
+
),
|
|
528
|
+
"updates": _reading(
|
|
529
|
+
train.updates, "measured" if train.counted_updates else "absent"
|
|
530
|
+
),
|
|
531
|
+
}
|
|
532
|
+
readings.update(_per_sample(infer, self._joules_status))
|
|
533
|
+
readings["peak_memory_bytes"] = _reading(_peak_rss_bytes(), "measured")
|
|
534
|
+
readings["device_peak_memory_bytes"] = _reading(
|
|
535
|
+
self._device_peak, "absent" if self._device_peak is None else "measured"
|
|
536
|
+
)
|
|
537
|
+
readings["python_peak_memory_bytes"] = self._python_peak()
|
|
538
|
+
readings["state_bytes"] = (
|
|
539
|
+
_reading(len(pickle.dumps(learner)), "measured")
|
|
540
|
+
if learner is not None
|
|
541
|
+
else _reading(None, "absent")
|
|
542
|
+
)
|
|
543
|
+
return readings
|
|
544
|
+
|
|
545
|
+
def _python_peak(self) -> Reading:
|
|
546
|
+
import tracemalloc
|
|
547
|
+
|
|
548
|
+
if not (self.trace_python_memory and tracemalloc.is_tracing()):
|
|
549
|
+
return _reading(None, "absent")
|
|
550
|
+
return _reading(tracemalloc.get_traced_memory()[1], "measured")
|
|
551
|
+
|
|
552
|
+
def resources(self) -> dict[str, Any]:
|
|
553
|
+
"""Return the ``resources`` block of a result file.
|
|
554
|
+
|
|
555
|
+
Returns
|
|
556
|
+
-------
|
|
557
|
+
dict
|
|
558
|
+
``energy``, ``hardware``, ``versions`` and ``git``.
|
|
559
|
+
``energy`` gives the energy source, the idle power and whether
|
|
560
|
+
other work loaded the machine when the meter started.
|
|
561
|
+
|
|
562
|
+
"""
|
|
563
|
+
return {
|
|
564
|
+
"energy": {
|
|
565
|
+
"source": self._zeus.name if self._zeus is not None else None,
|
|
566
|
+
"idle_watts": dict(self._idle_watts),
|
|
567
|
+
"other_load": self._other_load,
|
|
568
|
+
},
|
|
569
|
+
"hardware": _hardware(self.device, self._torch),
|
|
570
|
+
"versions": _versions(),
|
|
571
|
+
"git": _git_state(),
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
def close(self) -> None:
|
|
575
|
+
"""Stop :mod:`tracemalloc` if this meter started it (decision 172)."""
|
|
576
|
+
if self._started_tracing:
|
|
577
|
+
import tracemalloc
|
|
578
|
+
|
|
579
|
+
tracemalloc.stop()
|
|
580
|
+
self._started_tracing = False
|
|
581
|
+
|
|
582
|
+
def __enter__(self) -> ResourceMeter:
|
|
583
|
+
"""Return the meter, to be closed on exit."""
|
|
584
|
+
return self
|
|
585
|
+
|
|
586
|
+
def __exit__(self, *exc: object) -> None:
|
|
587
|
+
"""Close the meter, even when the block raised."""
|
|
588
|
+
self.close()
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def _empty_ok(status: Status, totals: _Totals) -> Status:
|
|
592
|
+
"""FLOPs over no calls are zero, measured."""
|
|
593
|
+
return "measured" if totals.n_calls == 0 else status
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def _per_sample(totals: _Totals, joules_status: Status) -> dict[str, Reading]:
|
|
597
|
+
if totals.n_samples == 0:
|
|
598
|
+
absent = _reading(None, "absent")
|
|
599
|
+
return {
|
|
600
|
+
"inference_flops": absent,
|
|
601
|
+
"inference_seconds": dict(absent),
|
|
602
|
+
"inference_joules": dict(absent),
|
|
603
|
+
}
|
|
604
|
+
n = totals.n_samples
|
|
605
|
+
return {
|
|
606
|
+
"inference_flops": _reading(totals.flops / n, totals.flops_status),
|
|
607
|
+
"inference_seconds": _reading(totals.seconds / n, "measured"),
|
|
608
|
+
"inference_joules": _reading(
|
|
609
|
+
totals.joules / n, _combine(joules_status, totals.joules_status)
|
|
610
|
+
),
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def _import_torch() -> Any:
|
|
615
|
+
try:
|
|
616
|
+
return importlib.import_module("torch")
|
|
617
|
+
except ImportError as error:
|
|
618
|
+
raise ImportError(
|
|
619
|
+
"torch FLOPs and device memory need torch: pip install 'prolearn[torch]'"
|
|
620
|
+
) from error
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def _run(command: list[str], cwd: Path | None = None) -> str | None:
|
|
624
|
+
try:
|
|
625
|
+
result = subprocess.run(
|
|
626
|
+
command, cwd=cwd, capture_output=True, text=True, timeout=10, check=False
|
|
627
|
+
)
|
|
628
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
629
|
+
return None
|
|
630
|
+
return result.stdout.strip() if result.returncode == 0 else None
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def _hardware(device: str = "cpu", torch: Any = None) -> dict[str, Any]:
|
|
634
|
+
"""Describe the machine.
|
|
635
|
+
|
|
636
|
+
Parameters
|
|
637
|
+
----------
|
|
638
|
+
device : str, default="cpu"
|
|
639
|
+
The device the run used, to name its GPU.
|
|
640
|
+
torch : module, optional
|
|
641
|
+
The torch module, when the run uses it.
|
|
642
|
+
|
|
643
|
+
Returns
|
|
644
|
+
-------
|
|
645
|
+
dict
|
|
646
|
+
``chip``, ``gpu``, ``memory_bytes`` and ``os``. A field that cannot be
|
|
647
|
+
read is null.
|
|
648
|
+
"""
|
|
649
|
+
chip = None
|
|
650
|
+
if sys.platform == "darwin":
|
|
651
|
+
chip = _run(["sysctl", "-n", "machdep.cpu.brand_string"])
|
|
652
|
+
elif Path("/proc/cpuinfo").exists():
|
|
653
|
+
for line in Path("/proc/cpuinfo").read_text().splitlines():
|
|
654
|
+
if line.startswith("model name"):
|
|
655
|
+
chip = line.split(":", 1)[1].strip()
|
|
656
|
+
break
|
|
657
|
+
chip = chip or platform.processor() or None
|
|
658
|
+
gpu = None
|
|
659
|
+
if device == "cuda" and torch is not None:
|
|
660
|
+
gpu = str(torch.cuda.get_device_name())
|
|
661
|
+
elif device == "mps":
|
|
662
|
+
gpu = f"{chip} GPU (MPS)" if chip else "Apple GPU (MPS)"
|
|
663
|
+
try:
|
|
664
|
+
memory = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES")
|
|
665
|
+
except (ValueError, OSError, AttributeError):
|
|
666
|
+
memory = None
|
|
667
|
+
return {"chip": chip, "gpu": gpu, "memory_bytes": memory, "os": platform.platform()}
|
|
668
|
+
|
|
669
|
+
|
|
670
|
+
def _versions() -> dict[str, str | None]:
|
|
671
|
+
"""Return the versions of Python and the libraries a run may use.
|
|
672
|
+
|
|
673
|
+
Returns
|
|
674
|
+
-------
|
|
675
|
+
dict
|
|
676
|
+
``python``, then ``prolearn``, ``numpy``, ``scikit-learn``, ``torch``,
|
|
677
|
+
``jsonschema`` and ``zeus``, each null if not installed.
|
|
678
|
+
"""
|
|
679
|
+
found: dict[str, str | None] = {"python": platform.python_version()}
|
|
680
|
+
for name in VERSION_PACKAGES:
|
|
681
|
+
try:
|
|
682
|
+
found[name] = importlib.metadata.version(name)
|
|
683
|
+
except importlib.metadata.PackageNotFoundError:
|
|
684
|
+
found[name] = None
|
|
685
|
+
return found
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
def _git_state() -> dict[str, Any]:
|
|
689
|
+
"""Return the commit of the checkout that holds the imported package.
|
|
690
|
+
|
|
691
|
+
Returns
|
|
692
|
+
-------
|
|
693
|
+
dict
|
|
694
|
+
``sha`` and ``dirty``. Both are null when the package is not imported
|
|
695
|
+
from a git checkout, as for an installed wheel, whose version
|
|
696
|
+
the versions block records.
|
|
697
|
+
"""
|
|
698
|
+
source = Path(__file__).resolve()
|
|
699
|
+
absent: dict[str, Any] = {"sha": None, "dirty": None}
|
|
700
|
+
if shutil.which("git") is None:
|
|
701
|
+
return absent
|
|
702
|
+
# A wheel installed in a virtual environment inside a checkout is not
|
|
703
|
+
# tracked by that checkout, so require the package's own files to be.
|
|
704
|
+
tracked = _run(["git", "ls-files", "--error-unmatch", "__init__.py"], source.parent)
|
|
705
|
+
if tracked is None:
|
|
706
|
+
return absent
|
|
707
|
+
sha = _run(["git", "rev-parse", "HEAD"], source.parent)
|
|
708
|
+
status = _run(["git", "status", "--porcelain"], source.parent)
|
|
709
|
+
if sha is None or status is None:
|
|
710
|
+
return absent
|
|
711
|
+
return {"sha": sha, "dirty": bool(status)}
|
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "https://neurodata.github.io/prolearn/result.schema.json",
|
|
4
|
+
"title": "prolearn result file",
|
|
5
|
+
"description": "One run of one learner on one setting, scored over time.",
|
|
6
|
+
"type": "object",
|
|
7
|
+
"required": [
|
|
8
|
+
"schema_version",
|
|
9
|
+
"run",
|
|
10
|
+
"series",
|
|
11
|
+
"reference",
|
|
12
|
+
"resources"
|
|
13
|
+
],
|
|
14
|
+
"additionalProperties": false,
|
|
15
|
+
"properties": {
|
|
16
|
+
"schema_version": {
|
|
17
|
+
"const": 1
|
|
18
|
+
},
|
|
19
|
+
"run": {
|
|
20
|
+
"type": "object",
|
|
21
|
+
"required": [
|
|
22
|
+
"setting",
|
|
23
|
+
"algorithm",
|
|
24
|
+
"family",
|
|
25
|
+
"time_features",
|
|
26
|
+
"mode",
|
|
27
|
+
"seed",
|
|
28
|
+
"checkpoints"
|
|
29
|
+
],
|
|
30
|
+
"properties": {
|
|
31
|
+
"setting": {
|
|
32
|
+
"type": "object",
|
|
33
|
+
"required": [
|
|
34
|
+
"name",
|
|
35
|
+
"params"
|
|
36
|
+
],
|
|
37
|
+
"additionalProperties": false,
|
|
38
|
+
"properties": {
|
|
39
|
+
"name": {
|
|
40
|
+
"type": "string",
|
|
41
|
+
"minLength": 1
|
|
42
|
+
},
|
|
43
|
+
"params": {
|
|
44
|
+
"type": "object"
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
"algorithm": {
|
|
49
|
+
"type": "string",
|
|
50
|
+
"minLength": 1
|
|
51
|
+
},
|
|
52
|
+
"family": {
|
|
53
|
+
"type": "string",
|
|
54
|
+
"minLength": 1
|
|
55
|
+
},
|
|
56
|
+
"time_features": {
|
|
57
|
+
"type": [
|
|
58
|
+
"string",
|
|
59
|
+
"null"
|
|
60
|
+
]
|
|
61
|
+
},
|
|
62
|
+
"mode": {
|
|
63
|
+
"enum": [
|
|
64
|
+
"batch",
|
|
65
|
+
"online",
|
|
66
|
+
"frozen"
|
|
67
|
+
]
|
|
68
|
+
},
|
|
69
|
+
"seed": {
|
|
70
|
+
"type": "integer"
|
|
71
|
+
},
|
|
72
|
+
"checkpoints": {
|
|
73
|
+
"type": "array",
|
|
74
|
+
"minItems": 1,
|
|
75
|
+
"items": {
|
|
76
|
+
"type": "integer",
|
|
77
|
+
"minimum": 1
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
"warm_up": {
|
|
81
|
+
"type": "integer",
|
|
82
|
+
"minimum": 0
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
"series": {
|
|
87
|
+
"type": "array",
|
|
88
|
+
"minItems": 1,
|
|
89
|
+
"items": {
|
|
90
|
+
"$ref": "#/$defs/record"
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
"reference": {
|
|
94
|
+
"type": "object",
|
|
95
|
+
"required": [
|
|
96
|
+
"bayes",
|
|
97
|
+
"chance"
|
|
98
|
+
],
|
|
99
|
+
"additionalProperties": false,
|
|
100
|
+
"properties": {
|
|
101
|
+
"bayes": {
|
|
102
|
+
"$ref": "#/$defs/level"
|
|
103
|
+
},
|
|
104
|
+
"chance": {
|
|
105
|
+
"$ref": "#/$defs/level"
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
"resources": {
|
|
110
|
+
"type": "object",
|
|
111
|
+
"required": [
|
|
112
|
+
"energy",
|
|
113
|
+
"hardware",
|
|
114
|
+
"versions",
|
|
115
|
+
"git"
|
|
116
|
+
],
|
|
117
|
+
"additionalProperties": false,
|
|
118
|
+
"properties": {
|
|
119
|
+
"energy": {
|
|
120
|
+
"type": "object",
|
|
121
|
+
"required": [
|
|
122
|
+
"source",
|
|
123
|
+
"idle_watts",
|
|
124
|
+
"other_load"
|
|
125
|
+
],
|
|
126
|
+
"additionalProperties": false,
|
|
127
|
+
"properties": {
|
|
128
|
+
"source": {
|
|
129
|
+
"type": [
|
|
130
|
+
"string",
|
|
131
|
+
"null"
|
|
132
|
+
],
|
|
133
|
+
"minLength": 1
|
|
134
|
+
},
|
|
135
|
+
"idle_watts": {
|
|
136
|
+
"$ref": "#/$defs/reading"
|
|
137
|
+
},
|
|
138
|
+
"other_load": {
|
|
139
|
+
"type": [
|
|
140
|
+
"boolean",
|
|
141
|
+
"null"
|
|
142
|
+
]
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
"hardware": {
|
|
147
|
+
"type": "object",
|
|
148
|
+
"required": [
|
|
149
|
+
"chip",
|
|
150
|
+
"gpu",
|
|
151
|
+
"memory_bytes",
|
|
152
|
+
"os"
|
|
153
|
+
],
|
|
154
|
+
"additionalProperties": false,
|
|
155
|
+
"properties": {
|
|
156
|
+
"chip": {
|
|
157
|
+
"type": [
|
|
158
|
+
"string",
|
|
159
|
+
"null"
|
|
160
|
+
]
|
|
161
|
+
},
|
|
162
|
+
"gpu": {
|
|
163
|
+
"type": [
|
|
164
|
+
"string",
|
|
165
|
+
"null"
|
|
166
|
+
]
|
|
167
|
+
},
|
|
168
|
+
"memory_bytes": {
|
|
169
|
+
"type": [
|
|
170
|
+
"integer",
|
|
171
|
+
"null"
|
|
172
|
+
],
|
|
173
|
+
"minimum": 0
|
|
174
|
+
},
|
|
175
|
+
"os": {
|
|
176
|
+
"type": [
|
|
177
|
+
"string",
|
|
178
|
+
"null"
|
|
179
|
+
]
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
},
|
|
183
|
+
"versions": {
|
|
184
|
+
"type": "object",
|
|
185
|
+
"required": [
|
|
186
|
+
"python",
|
|
187
|
+
"prolearn",
|
|
188
|
+
"numpy",
|
|
189
|
+
"scikit-learn",
|
|
190
|
+
"torch",
|
|
191
|
+
"jsonschema",
|
|
192
|
+
"zeus"
|
|
193
|
+
],
|
|
194
|
+
"additionalProperties": {
|
|
195
|
+
"type": [
|
|
196
|
+
"string",
|
|
197
|
+
"null"
|
|
198
|
+
]
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
"git": {
|
|
202
|
+
"type": "object",
|
|
203
|
+
"required": [
|
|
204
|
+
"sha",
|
|
205
|
+
"dirty"
|
|
206
|
+
],
|
|
207
|
+
"additionalProperties": false,
|
|
208
|
+
"properties": {
|
|
209
|
+
"sha": {
|
|
210
|
+
"type": [
|
|
211
|
+
"string",
|
|
212
|
+
"null"
|
|
213
|
+
],
|
|
214
|
+
"pattern": "^[0-9a-f]{40,64}$"
|
|
215
|
+
},
|
|
216
|
+
"dirty": {
|
|
217
|
+
"type": [
|
|
218
|
+
"boolean",
|
|
219
|
+
"null"
|
|
220
|
+
]
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
},
|
|
227
|
+
"$defs": {
|
|
228
|
+
"risk": {
|
|
229
|
+
"type": "number",
|
|
230
|
+
"minimum": 0,
|
|
231
|
+
"maximum": 1
|
|
232
|
+
},
|
|
233
|
+
"reading": {
|
|
234
|
+
"type": "object",
|
|
235
|
+
"required": [
|
|
236
|
+
"value",
|
|
237
|
+
"status"
|
|
238
|
+
],
|
|
239
|
+
"additionalProperties": false,
|
|
240
|
+
"properties": {
|
|
241
|
+
"value": {
|
|
242
|
+
"type": [
|
|
243
|
+
"number",
|
|
244
|
+
"null"
|
|
245
|
+
],
|
|
246
|
+
"minimum": 0
|
|
247
|
+
},
|
|
248
|
+
"status": {
|
|
249
|
+
"enum": [
|
|
250
|
+
"measured",
|
|
251
|
+
"estimated",
|
|
252
|
+
"absent"
|
|
253
|
+
]
|
|
254
|
+
}
|
|
255
|
+
},
|
|
256
|
+
"if": {
|
|
257
|
+
"properties": {
|
|
258
|
+
"status": {
|
|
259
|
+
"const": "absent"
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
},
|
|
263
|
+
"then": {
|
|
264
|
+
"properties": {
|
|
265
|
+
"value": {
|
|
266
|
+
"type": "null"
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
},
|
|
270
|
+
"else": {
|
|
271
|
+
"properties": {
|
|
272
|
+
"value": {
|
|
273
|
+
"type": "number"
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
},
|
|
278
|
+
"readings": {
|
|
279
|
+
"type": "object",
|
|
280
|
+
"required": [
|
|
281
|
+
"train_flops",
|
|
282
|
+
"train_seconds",
|
|
283
|
+
"train_joules",
|
|
284
|
+
"updates",
|
|
285
|
+
"inference_flops",
|
|
286
|
+
"inference_seconds",
|
|
287
|
+
"inference_joules",
|
|
288
|
+
"peak_memory_bytes",
|
|
289
|
+
"device_peak_memory_bytes",
|
|
290
|
+
"python_peak_memory_bytes",
|
|
291
|
+
"state_bytes"
|
|
292
|
+
],
|
|
293
|
+
"properties": {
|
|
294
|
+
"train_flops": {
|
|
295
|
+
"$ref": "#/$defs/reading"
|
|
296
|
+
},
|
|
297
|
+
"train_seconds": {
|
|
298
|
+
"$ref": "#/$defs/reading"
|
|
299
|
+
},
|
|
300
|
+
"train_joules": {
|
|
301
|
+
"$ref": "#/$defs/reading"
|
|
302
|
+
},
|
|
303
|
+
"updates": {
|
|
304
|
+
"$ref": "#/$defs/reading"
|
|
305
|
+
},
|
|
306
|
+
"inference_flops": {
|
|
307
|
+
"$ref": "#/$defs/reading"
|
|
308
|
+
},
|
|
309
|
+
"inference_seconds": {
|
|
310
|
+
"$ref": "#/$defs/reading"
|
|
311
|
+
},
|
|
312
|
+
"inference_joules": {
|
|
313
|
+
"$ref": "#/$defs/reading"
|
|
314
|
+
},
|
|
315
|
+
"peak_memory_bytes": {
|
|
316
|
+
"$ref": "#/$defs/reading"
|
|
317
|
+
},
|
|
318
|
+
"device_peak_memory_bytes": {
|
|
319
|
+
"$ref": "#/$defs/reading"
|
|
320
|
+
},
|
|
321
|
+
"python_peak_memory_bytes": {
|
|
322
|
+
"$ref": "#/$defs/reading"
|
|
323
|
+
},
|
|
324
|
+
"state_bytes": {
|
|
325
|
+
"$ref": "#/$defs/reading"
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
},
|
|
329
|
+
"record": {
|
|
330
|
+
"type": "object",
|
|
331
|
+
"required": [
|
|
332
|
+
"t",
|
|
333
|
+
"prospective_risk",
|
|
334
|
+
"instantaneous_risk"
|
|
335
|
+
],
|
|
336
|
+
"unevaluatedProperties": false,
|
|
337
|
+
"allOf": [
|
|
338
|
+
{
|
|
339
|
+
"$ref": "#/$defs/readings"
|
|
340
|
+
}
|
|
341
|
+
],
|
|
342
|
+
"properties": {
|
|
343
|
+
"t": {
|
|
344
|
+
"type": "integer",
|
|
345
|
+
"minimum": 1
|
|
346
|
+
},
|
|
347
|
+
"prospective_risk": {
|
|
348
|
+
"$ref": "#/$defs/risk"
|
|
349
|
+
},
|
|
350
|
+
"instantaneous_risk": {
|
|
351
|
+
"oneOf": [
|
|
352
|
+
{
|
|
353
|
+
"$ref": "#/$defs/risk"
|
|
354
|
+
},
|
|
355
|
+
{
|
|
356
|
+
"type": "null"
|
|
357
|
+
}
|
|
358
|
+
]
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
},
|
|
362
|
+
"level": {
|
|
363
|
+
"oneOf": [
|
|
364
|
+
{
|
|
365
|
+
"type": "object",
|
|
366
|
+
"required": [
|
|
367
|
+
"value"
|
|
368
|
+
],
|
|
369
|
+
"additionalProperties": false,
|
|
370
|
+
"properties": {
|
|
371
|
+
"value": {
|
|
372
|
+
"$ref": "#/$defs/risk"
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
},
|
|
376
|
+
{
|
|
377
|
+
"type": "object",
|
|
378
|
+
"required": [
|
|
379
|
+
"value",
|
|
380
|
+
"reason"
|
|
381
|
+
],
|
|
382
|
+
"additionalProperties": false,
|
|
383
|
+
"properties": {
|
|
384
|
+
"value": {
|
|
385
|
+
"type": "null"
|
|
386
|
+
},
|
|
387
|
+
"reason": {
|
|
388
|
+
"type": "string",
|
|
389
|
+
"minLength": 1
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
]
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
}
|
prolearn/results.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Save and load result files.
|
|
2
|
+
|
|
3
|
+
A result file is JSON that records one run of one learner on one setting:
|
|
4
|
+
``run`` describes it, ``series`` holds one record per checkpoint,
|
|
5
|
+
``reference`` gives the Bayes and chance levels or why they are missing, and
|
|
6
|
+
``resources`` holds the energy source, the hardware, library versions and git
|
|
7
|
+
commit. The JSON Schema ``result.schema.json``, shipped with the package,
|
|
8
|
+
fixes the fields.
|
|
9
|
+
|
|
10
|
+
:func:`write_result` validates before it writes, so no invalid file is saved.
|
|
11
|
+
:func:`read_result` validates what it reads.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import itertools
|
|
17
|
+
import json
|
|
18
|
+
from functools import cache
|
|
19
|
+
from importlib.resources import files
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
import jsonschema
|
|
24
|
+
|
|
25
|
+
__all__ = ["read_result", "write_result"]
|
|
26
|
+
|
|
27
|
+
SCHEMA_FILE = "result.schema.json"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@cache
|
|
31
|
+
def _validator() -> jsonschema.Draft202012Validator:
|
|
32
|
+
schema = json.loads(files("prolearn").joinpath(SCHEMA_FILE).read_text())
|
|
33
|
+
jsonschema.Draft202012Validator.check_schema(schema)
|
|
34
|
+
return jsonschema.Draft202012Validator(schema)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _validate(result: dict[str, Any]) -> None:
|
|
38
|
+
"""Check ``result`` against the schema and the rules it cannot express.
|
|
39
|
+
|
|
40
|
+
Raises
|
|
41
|
+
------
|
|
42
|
+
ValueError
|
|
43
|
+
If the result is invalid. The message lists every error found.
|
|
44
|
+
"""
|
|
45
|
+
errors = [
|
|
46
|
+
f"{'/'.join(map(str, error.absolute_path)) or '(top)'}: {error.message}"
|
|
47
|
+
for error in sorted(_validator().iter_errors(result), key=str)
|
|
48
|
+
]
|
|
49
|
+
if not errors:
|
|
50
|
+
times = [record["t"] for record in result["series"]]
|
|
51
|
+
if times != result["run"]["checkpoints"]:
|
|
52
|
+
errors.append("series: the records' t must equal run/checkpoints")
|
|
53
|
+
if any(later <= earlier for earlier, later in itertools.pairwise(times)):
|
|
54
|
+
errors.append("run/checkpoints: must increase strictly")
|
|
55
|
+
if errors:
|
|
56
|
+
raise ValueError("invalid result:\n" + "\n".join(errors))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _refuse_constant(name: str) -> None:
|
|
60
|
+
"""Refuse NaN and Infinity, which JSON does not allow."""
|
|
61
|
+
raise ValueError(f"invalid result:\n(top): {name} is not JSON compliant")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def write_result(path: str | Path, result: dict[str, Any]) -> Path:
|
|
65
|
+
"""Validate a result and save it as JSON.
|
|
66
|
+
|
|
67
|
+
Parameters
|
|
68
|
+
----------
|
|
69
|
+
path : str or Path
|
|
70
|
+
Where to save it. Missing parent folders are created.
|
|
71
|
+
result : dict
|
|
72
|
+
The result, with ``schema_version``, ``run``, ``series``,
|
|
73
|
+
``reference`` and ``resources``.
|
|
74
|
+
|
|
75
|
+
Returns
|
|
76
|
+
-------
|
|
77
|
+
Path
|
|
78
|
+
The path written.
|
|
79
|
+
|
|
80
|
+
Raises
|
|
81
|
+
------
|
|
82
|
+
ValueError
|
|
83
|
+
If the result is invalid. Nothing is written.
|
|
84
|
+
"""
|
|
85
|
+
_validate(result)
|
|
86
|
+
try:
|
|
87
|
+
text = json.dumps(result, indent=2, allow_nan=False) + "\n"
|
|
88
|
+
except TypeError as error:
|
|
89
|
+
raise ValueError(f"invalid result:\n(top): {error}") from error
|
|
90
|
+
path = Path(path)
|
|
91
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
path.write_text(text)
|
|
93
|
+
return path
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def read_result(path: str | Path) -> dict[str, Any]:
|
|
97
|
+
"""Load a result file and validate it.
|
|
98
|
+
|
|
99
|
+
Parameters
|
|
100
|
+
----------
|
|
101
|
+
path : str or Path
|
|
102
|
+
The file to read.
|
|
103
|
+
|
|
104
|
+
Returns
|
|
105
|
+
-------
|
|
106
|
+
dict
|
|
107
|
+
The result.
|
|
108
|
+
|
|
109
|
+
Raises
|
|
110
|
+
------
|
|
111
|
+
ValueError
|
|
112
|
+
If the file holds an invalid result.
|
|
113
|
+
"""
|
|
114
|
+
result = json.loads(Path(path).read_text(), parse_constant=_refuse_constant)
|
|
115
|
+
if not isinstance(result, dict):
|
|
116
|
+
raise ValueError("invalid result:\n(top): must be a JSON object")
|
|
117
|
+
_validate(result)
|
|
118
|
+
return result
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: prolearn
|
|
3
|
+
Version: 0.1.0.dev0
|
|
4
|
+
Summary: Prospective learning in Python
|
|
5
|
+
Project-URL: Homepage, https://github.com/neurodata/prolearn
|
|
6
|
+
Project-URL: Documentation, https://neurodata.github.io/prolearn/
|
|
7
|
+
Project-URL: Source, https://github.com/neurodata/prolearn
|
|
8
|
+
Project-URL: Issues, https://github.com/neurodata/prolearn/issues
|
|
9
|
+
Author: Joshua T. Vogelstein
|
|
10
|
+
License-Expression: BSD-3-Clause
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Requires-Dist: jsonschema>=4.18
|
|
23
|
+
Provides-Extra: energy
|
|
24
|
+
Requires-Dist: zeus>=0.17; (sys_platform != 'darwin') and extra == 'energy'
|
|
25
|
+
Requires-Dist: zeus[apple]>=0.17; (sys_platform == 'darwin') and extra == 'energy'
|
|
26
|
+
Provides-Extra: torch
|
|
27
|
+
Requires-Dist: torch>=2.6; extra == 'torch'
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# prolearn
|
|
31
|
+
|
|
32
|
+
The code for the NeurIPS 2024 paper "Prospective Learning: Learning for a Dynamic Future" is in [neurodata/prolearn0](https://github.com/neurodata/prolearn0).
|
|
33
|
+
|
|
34
|
+
`prolearn` is a Python package for prospective learning. It is in early development, and it has no public API yet.
|
|
35
|
+
|
|
36
|
+
## Install
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install prolearn
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
For development, clone the repo and run `uv sync`. See [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
43
|
+
|
|
44
|
+
## Papers
|
|
45
|
+
|
|
46
|
+
- Kording, Vogelstein, Chaudhari and Verstynen. "Toward a science of prospective learning." *Neuron* 113(24):4103–4106, 2025. [doi:10.1016/j.neuron.2025.11.010](https://doi.org/10.1016/j.neuron.2025.11.010)
|
|
47
|
+
- De Silva et al. "Prospective Learning: Principled Extrapolation to the Future." *Proceedings of the 2nd Conference on Lifelong Learning Agents*, PMLR 232:347–357, 2023. [proceedings.mlr.press/v232/de-silva23a](https://proceedings.mlr.press/v232/de-silva23a.html)
|
|
48
|
+
- De Silva, Ramesh, Yang, Yu, Vogelstein and Chaudhari. "Prospective learning: Learning for a dynamic future." *Advances in Neural Information Processing Systems 37*, 2024. [doi:10.52202/079017-3911](https://doi.org/10.52202/079017-3911)
|
|
49
|
+
- Bai, Shuai, De Silva, Yu, Chaudhari and Vogelstein. "Prospective learning in retrospect." *Lecture Notes in Computer Science*, 17–29, 2026. [doi:10.1007/978-3-032-00686-8_3](https://doi.org/10.1007/978-3-032-00686-8_3)
|
|
50
|
+
- Bai, Acharyya, De Silva, Shen, Hassett and Vogelstein. "Optimal control of the future via prospective learning with control." *Proceedings of the 8th Annual Learning for Dynamics and Control Conference*, PMLR 331:1157–1180, 2026. [proceedings.mlr.press/v331/bai26a](https://proceedings.mlr.press/v331/bai26a.html)
|
|
51
|
+
|
|
52
|
+
## Earlier code
|
|
53
|
+
|
|
54
|
+
- [neurodata/prolearn0](https://github.com/neurodata/prolearn0)
|
|
55
|
+
- [neurodata/prolearn2](https://github.com/neurodata/prolearn2)
|
|
56
|
+
- [neurodata/procontrol](https://github.com/neurodata/procontrol)
|
|
57
|
+
- [neurodata/ProspectiveLearningwithControl](https://github.com/neurodata/ProspectiveLearningwithControl)
|
|
58
|
+
- [neurodata/ProspectiveForaging](https://github.com/neurodata/ProspectiveForaging)
|
|
59
|
+
- [YuxinB/ProL](https://github.com/YuxinB/ProL)
|
|
60
|
+
|
|
61
|
+
## License
|
|
62
|
+
|
|
63
|
+
BSD-3-Clause. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
prolearn/__init__.py,sha256=yDWscU73LxYu3XiU6oyvMy_1Mcix_4DwKitBqj81SWk,264
|
|
2
|
+
prolearn/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
prolearn/resources.py,sha256=svKOjSe2ZTnCeylTaKZdH7bIRCL_J00SKRVTYZNRrIs,26304
|
|
4
|
+
prolearn/result.schema.json,sha256=enPq7tIjd-IS72ZN9JKmCiaIEcC5of6OxCm00uGLzv0,8249
|
|
5
|
+
prolearn/results.py,sha256=ySxcC5vfD7bfxt7waILfvsOHgWMvZs91VM9pPD_AI6o,3500
|
|
6
|
+
prolearn-0.1.0.dev0.dist-info/METADATA,sha256=xK9MDgRkuwgIoWTC7PFGNP5skXwUWnwxALnQm11QvTQ,3439
|
|
7
|
+
prolearn-0.1.0.dev0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
prolearn-0.1.0.dev0.dist-info/licenses/LICENSE,sha256=0gKRKKvyq2Cs8VMtruKfhxWkNqYO7-nmWup9neB3CDk,1761
|
|
9
|
+
prolearn-0.1.0.dev0.dist-info/RECORD,,
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026, The prolearn developers.
|
|
4
|
+
The developers are the commit authors in the git history, which governs.
|
|
5
|
+
To list them, run `git shortlog -sne` in a clone. GitHub's contributors
|
|
6
|
+
page, https://github.com/neurodata/prolearn/graphs/contributors, is a
|
|
7
|
+
convenience and may be incomplete.
|
|
8
|
+
|
|
9
|
+
Redistribution and use in source and binary forms, with or without
|
|
10
|
+
modification, are permitted provided that the following conditions are met:
|
|
11
|
+
|
|
12
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
13
|
+
list of conditions and the following disclaimer.
|
|
14
|
+
|
|
15
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
16
|
+
this list of conditions and the following disclaimer in the documentation
|
|
17
|
+
and/or other materials provided with the distribution.
|
|
18
|
+
|
|
19
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
20
|
+
contributors may be used to endorse or promote products derived from
|
|
21
|
+
this software without specific prior written permission.
|
|
22
|
+
|
|
23
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
24
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
25
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
26
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
27
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
28
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
29
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
30
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
31
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
32
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|