model-debugger 0.4.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.
- mdb/__init__.py +43 -0
- mdb/__main__.py +5 -0
- mdb/analysis/__init__.py +34 -0
- mdb/analysis/circuits/__init__.py +6 -0
- mdb/analysis/circuits/build.py +690 -0
- mdb/analysis/circuits/test.py +600 -0
- mdb/analysis/features/__init__.py +5 -0
- mdb/analysis/features/basis.py +685 -0
- mdb/analysis/features/sae.py +374 -0
- mdb/analysis/features/watch.py +268 -0
- mdb/analysis/measure/__init__.py +7 -0
- mdb/analysis/measure/branches.py +806 -0
- mdb/analysis/measure/bridge.py +379 -0
- mdb/analysis/measure/changes.py +201 -0
- mdb/analysis/measure/compare.py +348 -0
- mdb/analysis/measure/donors.py +193 -0
- mdb/analysis/measure/novelty.py +227 -0
- mdb/analysis/measure/paths.py +146 -0
- mdb/analysis/measure/pools.py +454 -0
- mdb/analysis/measure/readout.py +387 -0
- mdb/analysis/measure/reads.py +455 -0
- mdb/analysis/measure/sweep.py +215 -0
- mdb/analysis/numerics/__init__.py +6 -0
- mdb/analysis/numerics/accumulation.py +180 -0
- mdb/analysis/numerics/finite.py +1712 -0
- mdb/analysis/numerics/labels.py +80 -0
- mdb/analysis/numerics/pooling.py +89 -0
- mdb/analysis/numerics/stability.py +183 -0
- mdb/analysis/numerics/summary.py +306 -0
- mdb/analysis/numerics/units.py +86 -0
- mdb/analysis/numerics/verdict.py +244 -0
- mdb/analysis/numerics/why_frames.py +162 -0
- mdb/analysis/predict/__init__.py +7 -0
- mdb/analysis/predict/capture.py +265 -0
- mdb/analysis/predict/consumers.py +52 -0
- mdb/analysis/predict/explain.py +776 -0
- mdb/analysis/predict/forecast.py +635 -0
- mdb/analysis/predict/plan.py +248 -0
- mdb/analysis/predict/propagate.py +596 -0
- mdb/analysis/predict/rounding.py +95 -0
- mdb/analysis/predict/rowmodel.py +817 -0
- mdb/analysis/predict/supplied.py +103 -0
- mdb/analysis/predict/verify.py +433 -0
- mdb/analysis/predict/whatif.py +840 -0
- mdb/analysis/symbols/__init__.py +7 -0
- mdb/analysis/symbols/binding.py +138 -0
- mdb/analysis/symbols/candidates.py +320 -0
- mdb/analysis/symbols/circuit_map.py +592 -0
- mdb/analysis/symbols/components.py +436 -0
- mdb/analysis/symbols/frame.py +451 -0
- mdb/analysis/symbols/hop.py +439 -0
- mdb/analysis/symbols/liveness.py +292 -0
- mdb/analysis/symbols/probe.py +393 -0
- mdb/analysis/symbols/rows.py +400 -0
- mdb/analysis/symbols/sealed.py +149 -0
- mdb/analysis/symbols/subspace.py +380 -0
- mdb/analysis/symbols/symbol_finite.py +417 -0
- mdb/analysis/symbols/symbol_runs.py +683 -0
- mdb/analysis/symbols/table.py +1110 -0
- mdb/cli.py +105 -0
- mdb/core/__init__.py +4 -0
- mdb/core/address.py +1353 -0
- mdb/core/bounded.py +101 -0
- mdb/core/checkpoint_schema.py +202 -0
- mdb/core/checkpoint_store.py +377 -0
- mdb/core/circuit_pages.py +117 -0
- mdb/core/custody.py +629 -0
- mdb/core/errors.py +51 -0
- mdb/core/foreign_names.py +152 -0
- mdb/core/graph_seal.py +426 -0
- mdb/core/index.py +403 -0
- mdb/core/kinds.py +255 -0
- mdb/core/locate.py +161 -0
- mdb/core/migrate.py +280 -0
- mdb/core/neuronpedia.py +116 -0
- mdb/core/plugins.py +78 -0
- mdb/core/pointers.py +621 -0
- mdb/core/project.py +248 -0
- mdb/core/project_read.py +1038 -0
- mdb/core/recipe.py +457 -0
- mdb/core/records.py +1027 -0
- mdb/core/resolve.py +296 -0
- mdb/core/settings.py +718 -0
- mdb/engine/__init__.py +21 -0
- mdb/engine/attention_observer.py +53 -0
- mdb/engine/attention_port.py +903 -0
- mdb/engine/breakpoints.py +1465 -0
- mdb/engine/bundle.py +137 -0
- mdb/engine/checkpoint.py +1265 -0
- mdb/engine/core_file.py +306 -0
- mdb/engine/edits.py +323 -0
- mdb/engine/holds.py +256 -0
- mdb/engine/models.py +172 -0
- mdb/engine/ports.py +1424 -0
- mdb/engine/refs.py +223 -0
- mdb/engine/run.py +2162 -0
- mdb/engine/selfcheck.py +347 -0
- mdb/engine/trace.py +536 -0
- mdb/interop/__init__.py +17 -0
- mdb/interop/circuit_tracer_graph.py +253 -0
- mdb/interop/circuit_tracer_names.py +44 -0
- mdb/interop/clone.py +22 -0
- mdb/interop/names.py +295 -0
- mdb/interop/nn.py +431 -0
- mdb/interop/pyvene_compat.py +40 -0
- mdb/interop/pyvene_names.py +82 -0
- mdb/interop/tl.py +149 -0
- mdb/interop/verify.py +85 -0
- mdb/machines/__init__.py +53 -0
- mdb/machines/x86/__init__.py +13 -0
- mdb/machines/x86/address.py +171 -0
- mdb/machines/x86/binary.py +285 -0
- mdb/machines/x86/grid.py +188 -0
- mdb/machines/x86/index.py +184 -0
- mdb/machines/x86/interchange.py +156 -0
- mdb/machines/x86/lanes.py +281 -0
- mdb/machines/x86/method.py +252 -0
- mdb/machines/x86/method_v2.py +105 -0
- mdb/machines/x86/mlp.py +430 -0
- mdb/machines/x86/records.py +138 -0
- mdb/machines/x86/session.py +631 -0
- mdb/machines/x86/trace.py +351 -0
- mdb/ops/__init__.py +31 -0
- mdb/ops/builtin.py +1977 -0
- mdb/ops/context.py +60 -0
- mdb/ops/debugger.py +926 -0
- mdb/ops/errors.py +8 -0
- mdb/ops/features.py +513 -0
- mdb/ops/graph.py +58 -0
- mdb/ops/inspect.py +906 -0
- mdb/ops/lines.py +496 -0
- mdb/ops/named.py +672 -0
- mdb/ops/predict.py +450 -0
- mdb/ops/registry.py +332 -0
- mdb/ops/sets.py +988 -0
- mdb/ops/sweep.py +574 -0
- mdb/repl/__init__.py +5 -0
- mdb/repl/__main__.py +244 -0
- mdb/repl/config.py +213 -0
- mdb/repl/remote.py +324 -0
- mdb/repl/render.py +1699 -0
- mdb/repl/shell.py +409 -0
- mdb/serve/__init__.py +17 -0
- mdb/serve/__main__.py +180 -0
- mdb/serve/_legacy.py +97 -0
- mdb/serve/app.py +526 -0
- mdb/serve/blobs.py +280 -0
- mdb/serve/caps.py +148 -0
- mdb/serve/export.py +9 -0
- mdb/serve/guard.py +216 -0
- mdb/serve/live.py +412 -0
- mdb/serve/live_reduce.py +90 -0
- mdb/serve/recorded.py +515 -0
- mdb/serve/reduce.py +449 -0
- mdb/serve/schema.py +969 -0
- mdb/serve/states.py +125 -0
- mdb/serve/static/assets/index-BJpByNCO.js +58 -0
- mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
- mdb/serve/static/index.html +14 -0
- mdb/serve/static/manifest.json +5 -0
- mdb/serve/stored.py +34 -0
- mdb/serve/typegen.py +131 -0
- mdb/serve/views/__init__.py +1 -0
- mdb/serve/views/common.py +201 -0
- mdb/serve/views/frame.py +235 -0
- mdb/serve/views/graph.py +224 -0
- mdb/serve/views/live.py +402 -0
- mdb/serve/views/records.py +557 -0
- mdb/serve/views/sessions.py +151 -0
- mdb/serve/views/symbols.py +185 -0
- mdb/serve/views/timeline.py +121 -0
- model_debugger-0.4.0.dist-info/METADATA +1516 -0
- model_debugger-0.4.0.dist-info/RECORD +177 -0
- model_debugger-0.4.0.dist-info/WHEEL +4 -0
- model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
- model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
- model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
mdb/serve/reduce.py
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
"""Server-side reductions of one recorded tensor (numpy only). The browser never gets a tensor.
|
|
2
|
+
|
|
3
|
+
Ops: ``stats``; ``topk {axis, k<=64, by: abs|signed}``; ``slice {selector}`` (<= 4096 values,
|
|
4
|
+
float32 little-endian base64); ``histogram {bins<=256, range?}``; ``tile {axes, fixed, x0, y0,
|
|
5
|
+
level}`` (one 64 x 64 u8 tile, mean of 2^level x 2^level blocks, with its domain and scale);
|
|
6
|
+
``project {direction: pointer}`` (inner products over the last axis). Unknown parameter names
|
|
7
|
+
are refused (422 ``bad_params``). Results are cached by (session, pointer digest, op, sha256 of
|
|
8
|
+
the canonical known params), bounded by entry count and by total bytes of cached results.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import base64
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
import math
|
|
16
|
+
import threading
|
|
17
|
+
from collections import OrderedDict
|
|
18
|
+
|
|
19
|
+
from ..core.address import AddressError, format_address
|
|
20
|
+
from ..core.address import parse as parse_address
|
|
21
|
+
from . import blobs
|
|
22
|
+
from .schema import (
|
|
23
|
+
HistogramResult,
|
|
24
|
+
NumList,
|
|
25
|
+
ProjectResult,
|
|
26
|
+
SliceResult,
|
|
27
|
+
StatsResult,
|
|
28
|
+
TileResult,
|
|
29
|
+
TopkEntry,
|
|
30
|
+
TopkResult,
|
|
31
|
+
num,
|
|
32
|
+
unresolved,
|
|
33
|
+
)
|
|
34
|
+
from .views.common import occurrence_row, spec_digest
|
|
35
|
+
|
|
36
|
+
MAX_TOPK, MAX_SLICE, MAX_BINS, TILE = 64, 4096, 256, 64
|
|
37
|
+
CACHE_BYTES = 16 * 1024 * 1024
|
|
38
|
+
PARAMS = {"stats": (), "topk": ("k", "by", "axis"), "slice": ("selector",),
|
|
39
|
+
"histogram": ("bins", "range"), "tile": ("axes", "fixed", "x0", "y0", "level"),
|
|
40
|
+
"project": ("direction",)}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class ReduceError(ValueError):
|
|
44
|
+
def __init__(self, reason, detail, status=422):
|
|
45
|
+
super().__init__(detail)
|
|
46
|
+
self.reason, self.detail, self.status = reason, detail, status
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def resolve(model, spec: dict):
|
|
50
|
+
"""``(array, info)`` for a pointer spec; raises ``ReduceError`` (unresolved or refused)."""
|
|
51
|
+
import numpy as np
|
|
52
|
+
|
|
53
|
+
store = model.store_root
|
|
54
|
+
try:
|
|
55
|
+
if spec["kind"] == "slot":
|
|
56
|
+
array, info = model.cut_slot(spec["cut"], spec["slot"], spec.get("item"))
|
|
57
|
+
for index in spec.get("select") or []:
|
|
58
|
+
if array.ndim == 0 or not 0 <= index < array.shape[0]:
|
|
59
|
+
raise ReduceError("bad_selector", "select index is outside the slot tensor")
|
|
60
|
+
array = array[index]
|
|
61
|
+
return np.asarray(array), info
|
|
62
|
+
if spec["kind"] == "blob":
|
|
63
|
+
return blobs.tensor_blob(store, spec["ref"])
|
|
64
|
+
if spec["kind"] == "occurrence":
|
|
65
|
+
try:
|
|
66
|
+
address = format_address(parse_address(spec["address"]))
|
|
67
|
+
except AddressError as error:
|
|
68
|
+
raise ReduceError("bad_address", str(error)) from error
|
|
69
|
+
row = occurrence_row(model, address)
|
|
70
|
+
if row is None:
|
|
71
|
+
raise ReduceError("unresolved", f"{address} is not materialised in this project "
|
|
72
|
+
"(no occurrence index row); producing it needs the engine")
|
|
73
|
+
if not row.get("blob_id"):
|
|
74
|
+
raise ReduceError("unresolved", f"{address} is indexed without a stored blob; "
|
|
75
|
+
"rebuilding it needs recipe replay in the engine")
|
|
76
|
+
array, info = blobs.tensor_blob(store, row["blob_id"])
|
|
77
|
+
return array, {**info, "via": ["occurrence index", *info["via"]]}
|
|
78
|
+
except blobs.BlobError as error:
|
|
79
|
+
raise ReduceError("over_limit" if error.limit else
|
|
80
|
+
"verification_failed" if error.refused else "unresolved",
|
|
81
|
+
error.reason) from error
|
|
82
|
+
raise ReduceError("bad_pointer", f"unknown pointer kind {spec.get('kind')!r}")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _f(value):
|
|
86
|
+
return float(value)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _encode_f32(array):
|
|
90
|
+
import numpy as np
|
|
91
|
+
|
|
92
|
+
return base64.b64encode(np.ascontiguousarray(array, dtype="<f4").tobytes()).decode()
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _int(params, key, default, lo, hi):
|
|
96
|
+
value = params.get(key, default)
|
|
97
|
+
if value is None and default is None:
|
|
98
|
+
return None
|
|
99
|
+
if isinstance(value, bool) or not isinstance(value, int) or not lo <= value <= hi:
|
|
100
|
+
raise ReduceError("bad_params", f"{key} must be an integer in {lo}..{hi}")
|
|
101
|
+
return value
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _stat(value, **kw):
|
|
105
|
+
"""A measured statistic, or ``unresolved`` when it overflows float64."""
|
|
106
|
+
value = float(value)
|
|
107
|
+
if not math.isfinite(value):
|
|
108
|
+
return unresolved("overflows float64 (the exact value is not finite in double precision)",
|
|
109
|
+
**kw)
|
|
110
|
+
return num(value, "measured", **kw)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def stats(array, base):
|
|
114
|
+
import numpy as np
|
|
115
|
+
|
|
116
|
+
values = np.asarray(array, dtype=np.float64).reshape(-1)
|
|
117
|
+
finite = values[np.isfinite(values)]
|
|
118
|
+
count = num(values.size, "measured", unit="values")
|
|
119
|
+
if finite.size == 0:
|
|
120
|
+
none = unresolved("no finite values")
|
|
121
|
+
return StatsResult(**base, count=count, finite=num(0, "measured", unit="values"),
|
|
122
|
+
min=none, max=none, mean=none, std=none, absmax=none, l2=none)
|
|
123
|
+
m = dict(ptr=base["pointer"])
|
|
124
|
+
top = float(np.abs(finite).max())
|
|
125
|
+
with np.errstate(all="ignore"):
|
|
126
|
+
mean = finite.mean()
|
|
127
|
+
std = finite.std()
|
|
128
|
+
l2 = top * np.sqrt(((finite / top) ** 2).sum()) if top > 0 else 0.0
|
|
129
|
+
return StatsResult(**base, count=count, finite=num(finite.size, "measured", unit="values"),
|
|
130
|
+
min=_stat(finite.min(), **m), max=_stat(finite.max(), **m),
|
|
131
|
+
mean=_stat(mean, **m), std=_stat(std, **m), absmax=_stat(top, **m),
|
|
132
|
+
l2=_stat(l2, **m))
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _top_indices(score, k):
|
|
136
|
+
"""Indices of the ``k`` largest scores, ties broken by the lower index: exactly the first
|
|
137
|
+
``k`` of a stable descending full sort, without sorting everything (argpartition, then a sort
|
|
138
|
+
of only the winners and the boundary ties)."""
|
|
139
|
+
import numpy as np
|
|
140
|
+
|
|
141
|
+
n = score.size
|
|
142
|
+
if n <= k:
|
|
143
|
+
return np.argsort(-score, kind="stable")
|
|
144
|
+
top = np.argpartition(score, n - k)[n - k:]
|
|
145
|
+
threshold = score[top].min()
|
|
146
|
+
above = np.flatnonzero(score > threshold)
|
|
147
|
+
ties = np.flatnonzero(score == threshold)[:k - above.size]
|
|
148
|
+
keep = np.concatenate([above, ties])
|
|
149
|
+
return keep[np.lexsort((keep, -score[keep]))]
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def topk(array, params, base):
|
|
153
|
+
import numpy as np
|
|
154
|
+
|
|
155
|
+
k = _int(params, "k", 8, 1, MAX_TOPK)
|
|
156
|
+
by = params.get("by", "abs")
|
|
157
|
+
if by not in ("abs", "signed"):
|
|
158
|
+
raise ReduceError("bad_params", "by is 'abs' or 'signed'")
|
|
159
|
+
values = np.asarray(array, dtype=np.float64)
|
|
160
|
+
axis = params.get("axis")
|
|
161
|
+
if axis is not None:
|
|
162
|
+
if values.ndim == 0:
|
|
163
|
+
raise ReduceError("bad_params", "axis needs a tensor with at least one axis")
|
|
164
|
+
axis = _int(params, "axis", None, -values.ndim, values.ndim - 1)
|
|
165
|
+
if values.size == 0:
|
|
166
|
+
what = "element value" if axis is None else f"sum over the other axes ({by})"
|
|
167
|
+
return TopkResult(**base, axis=axis, by=by, k=k, entries=[], score=what)
|
|
168
|
+
if axis is None:
|
|
169
|
+
flat = values.reshape(-1)
|
|
170
|
+
score = np.abs(flat) if by == "abs" else flat.copy()
|
|
171
|
+
ev, what = "measured", "element value"
|
|
172
|
+
else:
|
|
173
|
+
moved = np.moveaxis(values, axis, 0).reshape(values.shape[axis], -1)
|
|
174
|
+
with np.errstate(all="ignore"):
|
|
175
|
+
flat = (np.abs(moved) if by == "abs" else moved).sum(axis=1)
|
|
176
|
+
score = flat.copy()
|
|
177
|
+
ev, what = "derived-exact", f"sum over the other axes ({by})"
|
|
178
|
+
score[~np.isfinite(score)] = -np.inf
|
|
179
|
+
entries = []
|
|
180
|
+
for i in _top_indices(score, k):
|
|
181
|
+
if not np.isfinite(flat[i]):
|
|
182
|
+
continue
|
|
183
|
+
index = ([int(j) for j in np.unravel_index(int(i), values.shape)] if axis is None
|
|
184
|
+
else [int(i)])
|
|
185
|
+
entries.append(TopkEntry(index=index, v=num(flat[i], ev, ptr=base["pointer"])))
|
|
186
|
+
return TopkResult(**base, axis=axis, by=by, k=k, entries=entries, score=what)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _selector(array, selector):
|
|
190
|
+
if not isinstance(selector, list) or len(selector) > array.ndim:
|
|
191
|
+
raise ReduceError("bad_params", "selector is a list of at most ndim entries")
|
|
192
|
+
index = []
|
|
193
|
+
for dim, item in zip(array.shape, selector):
|
|
194
|
+
if item is None:
|
|
195
|
+
index.append(slice(None))
|
|
196
|
+
elif isinstance(item, int) and not isinstance(item, bool) and -dim <= item < dim:
|
|
197
|
+
index.append(item)
|
|
198
|
+
elif (isinstance(item, list) and len(item) == 2
|
|
199
|
+
and all(isinstance(v, int) and not isinstance(v, bool) for v in item)
|
|
200
|
+
and 0 <= item[0] <= item[1] <= dim):
|
|
201
|
+
index.append(slice(item[0], item[1]))
|
|
202
|
+
else:
|
|
203
|
+
raise ReduceError("bad_params", f"selector entry {item!r} is not an index, a "
|
|
204
|
+
f"[start, stop] range or null within size {dim}")
|
|
205
|
+
return tuple(index)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def slice_(array, params, base):
|
|
209
|
+
import numpy as np
|
|
210
|
+
|
|
211
|
+
selector = params.get("selector", [])
|
|
212
|
+
view = array[_selector(array, selector)] # a view: nothing is copied before the size check
|
|
213
|
+
if view.size > MAX_SLICE:
|
|
214
|
+
raise ReduceError("over_limit", f"slice has {view.size} values (> {MAX_SLICE}); "
|
|
215
|
+
"narrow the selector or use tile/histogram")
|
|
216
|
+
part = np.asarray(view, dtype=np.float64)
|
|
217
|
+
note = None if base["dtype"] == "float32" else f"{base['dtype']} values sent as float32"
|
|
218
|
+
return SliceResult(**{**base, "note": note}, selector=selector, outShape=list(part.shape),
|
|
219
|
+
encoding="f32-le-base64", data=_encode_f32(part),
|
|
220
|
+
nonfinite=int((~np.isfinite(part)).sum()), ev="measured")
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def histogram(array, params, base):
|
|
224
|
+
import numpy as np
|
|
225
|
+
|
|
226
|
+
bins = _int(params, "bins", 32, 1, MAX_BINS)
|
|
227
|
+
values = np.asarray(array, dtype=np.float64).reshape(-1)
|
|
228
|
+
finite = values[np.isfinite(values)]
|
|
229
|
+
rng = params.get("range")
|
|
230
|
+
if rng is not None:
|
|
231
|
+
real = (isinstance(rng, list) and len(rng) == 2 and all(
|
|
232
|
+
isinstance(v, (int, float)) and not isinstance(v, bool) for v in rng))
|
|
233
|
+
if not real or not all(math.isfinite(v) for v in rng) or not rng[0] < rng[1] or \
|
|
234
|
+
not math.isfinite(float(rng[1]) - float(rng[0])):
|
|
235
|
+
raise ReduceError("bad_params", "range is [lo, hi]: two finite reals with lo < hi and "
|
|
236
|
+
"a finite hi - lo")
|
|
237
|
+
if finite.size == 0:
|
|
238
|
+
counts, edges = np.zeros(bins, dtype=int), np.linspace(0.0, 1.0, bins + 1)
|
|
239
|
+
else:
|
|
240
|
+
counts, edges = np.histogram(finite, bins=bins, range=None if rng is None
|
|
241
|
+
else (float(rng[0]), float(rng[1])))
|
|
242
|
+
edge_list = NumList(vs=[_f(e) for e in edges], ev="derived-exact", unit="bin edge",
|
|
243
|
+
proof="numpy.histogram edges over the finite values"
|
|
244
|
+
if rng is None else "requested range split into equal bins")
|
|
245
|
+
return HistogramResult(**base, bins=bins, edges=edge_list,
|
|
246
|
+
counts=[int(c) for c in counts],
|
|
247
|
+
nonfinite=int(values.size - finite.size), ev="measured")
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def tile(array, params, base):
|
|
251
|
+
import numpy as np
|
|
252
|
+
|
|
253
|
+
values = np.asarray(array, dtype=np.float64)
|
|
254
|
+
if values.ndim == 0:
|
|
255
|
+
values = values.reshape(1, 1)
|
|
256
|
+
if values.ndim == 1:
|
|
257
|
+
values = values.reshape(1, -1)
|
|
258
|
+
axes = params.get("axes", [values.ndim - 2, values.ndim - 1])
|
|
259
|
+
if (not isinstance(axes, list) or len(axes) != 2 or len(set(axes)) != 2
|
|
260
|
+
or any(not isinstance(a, int) or not 0 <= a < values.ndim for a in axes)):
|
|
261
|
+
raise ReduceError("bad_params", "axes is two distinct axis indices")
|
|
262
|
+
others = [d for d in range(values.ndim) if d not in axes]
|
|
263
|
+
level = _int(params, "level", 0, 0, 16)
|
|
264
|
+
x0 = _int(params, "x0", 0, 0, 1 << 30)
|
|
265
|
+
y0 = _int(params, "y0", 0, 0, 1 << 30)
|
|
266
|
+
if values.size == 0: # nothing recorded to draw: a resolved empty tile, not an error
|
|
267
|
+
return TileResult(**base, axes=axes, fixed=[0] * len(others), x0=x0, y0=y0, level=level,
|
|
268
|
+
w=0, h=0, full=[values.shape[axes[0]], values.shape[axes[1]]],
|
|
269
|
+
encoding="u8-base64", data="",
|
|
270
|
+
domain=NumList(vs=[0.0, 0.0], ev="derived-exact",
|
|
271
|
+
proof="empty tensor: no block means"),
|
|
272
|
+
scale="linear", agg=f"mean of {1 << level}x{1 << level} blocks of "
|
|
273
|
+
"finite values (no values)", nonfinite=0, ev="measured")
|
|
274
|
+
fixed = params.get("fixed", [0] * len(others))
|
|
275
|
+
if (not isinstance(fixed, list) or len(fixed) != len(others)
|
|
276
|
+
or any(not isinstance(f, int) or not 0 <= f < values.shape[d]
|
|
277
|
+
for f, d in zip(fixed, others))):
|
|
278
|
+
raise ReduceError("bad_params", f"fixed gives one index for each of axes {others}")
|
|
279
|
+
plane = values[tuple(fixed[others.index(d)] if d in others else slice(None)
|
|
280
|
+
for d in range(values.ndim))]
|
|
281
|
+
if axes[0] > axes[1]:
|
|
282
|
+
plane = plane.T
|
|
283
|
+
s = 1 << level
|
|
284
|
+
rows, cols = plane.shape
|
|
285
|
+
h = max(0, min(TILE, -(-(rows - y0) // s)))
|
|
286
|
+
w = max(0, min(TILE, -(-(cols - x0) // s)))
|
|
287
|
+
out = np.full((h, w), np.nan)
|
|
288
|
+
for i in range(h):
|
|
289
|
+
block_rows = plane[y0 + i * s:y0 + (i + 1) * s]
|
|
290
|
+
for j in range(w):
|
|
291
|
+
block = block_rows[:, x0 + j * s:x0 + (j + 1) * s]
|
|
292
|
+
good = block[np.isfinite(block)]
|
|
293
|
+
if good.size:
|
|
294
|
+
out[i, j] = good.mean()
|
|
295
|
+
finite = out[np.isfinite(out)]
|
|
296
|
+
lo, hi = (float(finite.min()), float(finite.max())) if finite.size else (0.0, 0.0)
|
|
297
|
+
# Byte 0 = no finite value in the block (drawn empty); 1..255 span the domain. Scaled by
|
|
298
|
+
# halves so a domain near the float64 limit does not overflow.
|
|
299
|
+
if lo < 0 < hi:
|
|
300
|
+
m = max(-lo, hi)
|
|
301
|
+
domain, scale = [-m, m], "diverging"
|
|
302
|
+
proof = ("diverging: symmetric about 0, [-m, m] with m = max(|min|, |max|) of the "
|
|
303
|
+
"block means")
|
|
304
|
+
q = 1 + np.round((out + m) / (2 * m) * 254 if math.isfinite(2 * m)
|
|
305
|
+
else (out / 2 / m + 0.5) * 254)
|
|
306
|
+
else:
|
|
307
|
+
domain, scale = [lo, hi], "linear"
|
|
308
|
+
proof = "linear: [min, max] of the block means"
|
|
309
|
+
if not hi > lo:
|
|
310
|
+
q = np.full(out.shape, 128.0)
|
|
311
|
+
elif math.isfinite(hi - lo):
|
|
312
|
+
q = 1 + np.round((out - lo) / (hi - lo) * 254)
|
|
313
|
+
else:
|
|
314
|
+
q = 1 + np.round((out / 2 - lo / 2) / (hi / 2 - lo / 2) * 254)
|
|
315
|
+
q[~np.isfinite(out)] = 0
|
|
316
|
+
q = np.clip(q, 0, 255)
|
|
317
|
+
data = base64.b64encode(q.astype(np.uint8).tobytes()).decode()
|
|
318
|
+
return TileResult(**base, axes=axes, fixed=fixed, x0=x0, y0=y0, level=level, w=w, h=h,
|
|
319
|
+
full=[rows, cols], encoding="u8-base64", data=data,
|
|
320
|
+
domain=NumList(vs=domain, ev="derived-exact", proof=proof),
|
|
321
|
+
scale=scale, agg=f"mean of {s}x{s} blocks of finite values",
|
|
322
|
+
nonfinite=int((~np.isfinite(out)).sum()), ev="measured")
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def project(array, params, base, direction_of):
|
|
326
|
+
"""``direction_of(spec)`` reads the direction pointer (the same tier as the tensor's)."""
|
|
327
|
+
import numpy as np
|
|
328
|
+
|
|
329
|
+
spec = params.get("direction")
|
|
330
|
+
if not isinstance(spec, dict):
|
|
331
|
+
raise ReduceError("bad_params", "direction is a pointer spec")
|
|
332
|
+
direction = direction_of(spec)
|
|
333
|
+
direction = np.asarray(direction, dtype=np.float64).reshape(-1)
|
|
334
|
+
values = np.asarray(array, dtype=np.float64)
|
|
335
|
+
if values.ndim == 0 or values.shape[-1] != direction.size:
|
|
336
|
+
raise ReduceError("bad_params", f"direction has {direction.size} values; the tensor's "
|
|
337
|
+
f"last axis has {values.shape[-1] if values.ndim else 0}")
|
|
338
|
+
out = values @ direction
|
|
339
|
+
out = np.asarray(out).reshape(values.shape[:-1])
|
|
340
|
+
if out.size > MAX_SLICE:
|
|
341
|
+
raise ReduceError("over_limit", f"projection has {out.size} values (> {MAX_SLICE})")
|
|
342
|
+
return ProjectResult(**base, direction=spec_digest(spec),
|
|
343
|
+
directionNorm=_stat(np.linalg.norm(direction)),
|
|
344
|
+
outShape=list(out.shape), encoding="f32-le-base64",
|
|
345
|
+
data=_encode_f32(out), ev="derived-exact")
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _check_params(op, params):
|
|
349
|
+
known = PARAMS.get(op)
|
|
350
|
+
if known is None:
|
|
351
|
+
raise ReduceError("bad_op", f"unknown reduce op {op!r}")
|
|
352
|
+
unknown = sorted(str(k) for k in params if k not in known)
|
|
353
|
+
if unknown:
|
|
354
|
+
shown = ", ".join(repr(k[:40]) for k in unknown[:8]) + (
|
|
355
|
+
f" (+{len(unknown) - 8} more)" if len(unknown) > 8 else "")
|
|
356
|
+
raise ReduceError("bad_params", f"unknown parameter(s) for {op}: {shown}; "
|
|
357
|
+
f"{op} takes {', '.join(known) if known else 'no parameters'}")
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def params_digest(params):
|
|
361
|
+
"""sha256 of the canonical params (known names only, so it is the whole key)."""
|
|
362
|
+
try:
|
|
363
|
+
raw = json.dumps(params, sort_keys=True, separators=(",", ":"), allow_nan=False)
|
|
364
|
+
except (RecursionError, ValueError, TypeError) as error:
|
|
365
|
+
raise ReduceError("bad_params", "params are not plain JSON of bounded depth") from error
|
|
366
|
+
return hashlib.sha256(raw.encode()).hexdigest()
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
class Reducer:
|
|
370
|
+
"""Runs reductions and caches results by (session, pointer, op, params digest).
|
|
371
|
+
|
|
372
|
+
The cache is bounded by entry count (``size``) and by the summed size of the cached results
|
|
373
|
+
(``max_bytes``); a result larger than a quarter of the byte budget is not cached."""
|
|
374
|
+
|
|
375
|
+
def __init__(self, size=256, max_bytes=CACHE_BYTES):
|
|
376
|
+
self.size, self.max_bytes = size, max_bytes
|
|
377
|
+
self._cache, self._lock, self.bytes = OrderedDict(), threading.Lock(), 0
|
|
378
|
+
|
|
379
|
+
def _store(self, key, result):
|
|
380
|
+
weight = len(result.model_dump_json())
|
|
381
|
+
if weight > self.max_bytes // 4:
|
|
382
|
+
return
|
|
383
|
+
with self._lock:
|
|
384
|
+
if key in self._cache:
|
|
385
|
+
self.bytes -= self._cache.pop(key)[1]
|
|
386
|
+
self._cache[key] = (result, weight)
|
|
387
|
+
self.bytes += weight
|
|
388
|
+
while len(self._cache) > self.size or self.bytes > self.max_bytes:
|
|
389
|
+
self.bytes -= self._cache.popitem(last=False)[1][1]
|
|
390
|
+
|
|
391
|
+
@staticmethod
|
|
392
|
+
def _pointer_key(model, spec: dict) -> str:
|
|
393
|
+
"""The cache key of a pointer: an occurrence pointer is keyed on the blob its index row
|
|
394
|
+
names now (so a re-indexed address never serves a stale result), the rest on the spec."""
|
|
395
|
+
if isinstance(spec, dict) and spec.get("kind") == "occurrence":
|
|
396
|
+
try:
|
|
397
|
+
address = format_address(parse_address(spec["address"]))
|
|
398
|
+
row = occurrence_row(model, address)
|
|
399
|
+
except (AddressError, KeyError, TypeError, ValueError):
|
|
400
|
+
row = None
|
|
401
|
+
blob = row.get("blob_id") if isinstance(row, dict) else None
|
|
402
|
+
return spec_digest({"kind": "occurrence-blob", "blob": blob if isinstance(
|
|
403
|
+
blob, str) else None, "address": None if isinstance(blob, str) else spec.get(
|
|
404
|
+
"address")})
|
|
405
|
+
return spec_digest(spec)
|
|
406
|
+
|
|
407
|
+
def run(self, model, spec: dict, op: str, params: dict):
|
|
408
|
+
_check_params(op, params)
|
|
409
|
+
key = (model.sid, self._pointer_key(model, spec), op, params_digest(params))
|
|
410
|
+
with self._lock:
|
|
411
|
+
if key in self._cache:
|
|
412
|
+
self._cache.move_to_end(key)
|
|
413
|
+
return self._cache[key][0]
|
|
414
|
+
array, info = resolve(model, spec)
|
|
415
|
+
result = reduce_array(array, info, spec, op, params,
|
|
416
|
+
direction_of=lambda d: resolve(model, d)[0])
|
|
417
|
+
self._store(key, result)
|
|
418
|
+
return result
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def reduce_array(array, info, spec: dict, op: str, params: dict, *, direction_of):
|
|
422
|
+
"""One reduction of an array already read through ``spec`` (``info``: shape, dtype).
|
|
423
|
+
``direction_of(spec)`` reads the ``project`` direction. Every value statistic is labelled
|
|
424
|
+
``measured``; a caller whose tensor carries another authority relabels the result."""
|
|
425
|
+
_check_params(op, params)
|
|
426
|
+
base = {"op": op, "pointer": spec_digest(spec), "shape": list(info["shape"]),
|
|
427
|
+
"dtype": info["dtype"], "note": None}
|
|
428
|
+
try:
|
|
429
|
+
if op == "stats":
|
|
430
|
+
return stats(array, base)
|
|
431
|
+
if op == "topk":
|
|
432
|
+
return topk(array, params, base)
|
|
433
|
+
if op == "slice":
|
|
434
|
+
return slice_(array, params, base)
|
|
435
|
+
if op == "histogram":
|
|
436
|
+
return histogram(array, params, base)
|
|
437
|
+
if op == "tile":
|
|
438
|
+
return tile(array, params, base)
|
|
439
|
+
return project(array, params, base, direction_of)
|
|
440
|
+
except ReduceError:
|
|
441
|
+
raise
|
|
442
|
+
except (ValueError, ArithmeticError, TypeError, IndexError) as error:
|
|
443
|
+
# numpy rejected a well-formed request (bad axis, bad range, ...): the caller's
|
|
444
|
+
# parameters, not a server fault.
|
|
445
|
+
raise ReduceError("bad_params", f"{op}: {type(error).__name__}: "
|
|
446
|
+
f"{str(error)[:300]}") from error
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
__all__ = ["Reducer", "ReduceError", "reduce_array", "resolve"]
|