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.
Files changed (177) hide show
  1. mdb/__init__.py +43 -0
  2. mdb/__main__.py +5 -0
  3. mdb/analysis/__init__.py +34 -0
  4. mdb/analysis/circuits/__init__.py +6 -0
  5. mdb/analysis/circuits/build.py +690 -0
  6. mdb/analysis/circuits/test.py +600 -0
  7. mdb/analysis/features/__init__.py +5 -0
  8. mdb/analysis/features/basis.py +685 -0
  9. mdb/analysis/features/sae.py +374 -0
  10. mdb/analysis/features/watch.py +268 -0
  11. mdb/analysis/measure/__init__.py +7 -0
  12. mdb/analysis/measure/branches.py +806 -0
  13. mdb/analysis/measure/bridge.py +379 -0
  14. mdb/analysis/measure/changes.py +201 -0
  15. mdb/analysis/measure/compare.py +348 -0
  16. mdb/analysis/measure/donors.py +193 -0
  17. mdb/analysis/measure/novelty.py +227 -0
  18. mdb/analysis/measure/paths.py +146 -0
  19. mdb/analysis/measure/pools.py +454 -0
  20. mdb/analysis/measure/readout.py +387 -0
  21. mdb/analysis/measure/reads.py +455 -0
  22. mdb/analysis/measure/sweep.py +215 -0
  23. mdb/analysis/numerics/__init__.py +6 -0
  24. mdb/analysis/numerics/accumulation.py +180 -0
  25. mdb/analysis/numerics/finite.py +1712 -0
  26. mdb/analysis/numerics/labels.py +80 -0
  27. mdb/analysis/numerics/pooling.py +89 -0
  28. mdb/analysis/numerics/stability.py +183 -0
  29. mdb/analysis/numerics/summary.py +306 -0
  30. mdb/analysis/numerics/units.py +86 -0
  31. mdb/analysis/numerics/verdict.py +244 -0
  32. mdb/analysis/numerics/why_frames.py +162 -0
  33. mdb/analysis/predict/__init__.py +7 -0
  34. mdb/analysis/predict/capture.py +265 -0
  35. mdb/analysis/predict/consumers.py +52 -0
  36. mdb/analysis/predict/explain.py +776 -0
  37. mdb/analysis/predict/forecast.py +635 -0
  38. mdb/analysis/predict/plan.py +248 -0
  39. mdb/analysis/predict/propagate.py +596 -0
  40. mdb/analysis/predict/rounding.py +95 -0
  41. mdb/analysis/predict/rowmodel.py +817 -0
  42. mdb/analysis/predict/supplied.py +103 -0
  43. mdb/analysis/predict/verify.py +433 -0
  44. mdb/analysis/predict/whatif.py +840 -0
  45. mdb/analysis/symbols/__init__.py +7 -0
  46. mdb/analysis/symbols/binding.py +138 -0
  47. mdb/analysis/symbols/candidates.py +320 -0
  48. mdb/analysis/symbols/circuit_map.py +592 -0
  49. mdb/analysis/symbols/components.py +436 -0
  50. mdb/analysis/symbols/frame.py +451 -0
  51. mdb/analysis/symbols/hop.py +439 -0
  52. mdb/analysis/symbols/liveness.py +292 -0
  53. mdb/analysis/symbols/probe.py +393 -0
  54. mdb/analysis/symbols/rows.py +400 -0
  55. mdb/analysis/symbols/sealed.py +149 -0
  56. mdb/analysis/symbols/subspace.py +380 -0
  57. mdb/analysis/symbols/symbol_finite.py +417 -0
  58. mdb/analysis/symbols/symbol_runs.py +683 -0
  59. mdb/analysis/symbols/table.py +1110 -0
  60. mdb/cli.py +105 -0
  61. mdb/core/__init__.py +4 -0
  62. mdb/core/address.py +1353 -0
  63. mdb/core/bounded.py +101 -0
  64. mdb/core/checkpoint_schema.py +202 -0
  65. mdb/core/checkpoint_store.py +377 -0
  66. mdb/core/circuit_pages.py +117 -0
  67. mdb/core/custody.py +629 -0
  68. mdb/core/errors.py +51 -0
  69. mdb/core/foreign_names.py +152 -0
  70. mdb/core/graph_seal.py +426 -0
  71. mdb/core/index.py +403 -0
  72. mdb/core/kinds.py +255 -0
  73. mdb/core/locate.py +161 -0
  74. mdb/core/migrate.py +280 -0
  75. mdb/core/neuronpedia.py +116 -0
  76. mdb/core/plugins.py +78 -0
  77. mdb/core/pointers.py +621 -0
  78. mdb/core/project.py +248 -0
  79. mdb/core/project_read.py +1038 -0
  80. mdb/core/recipe.py +457 -0
  81. mdb/core/records.py +1027 -0
  82. mdb/core/resolve.py +296 -0
  83. mdb/core/settings.py +718 -0
  84. mdb/engine/__init__.py +21 -0
  85. mdb/engine/attention_observer.py +53 -0
  86. mdb/engine/attention_port.py +903 -0
  87. mdb/engine/breakpoints.py +1465 -0
  88. mdb/engine/bundle.py +137 -0
  89. mdb/engine/checkpoint.py +1265 -0
  90. mdb/engine/core_file.py +306 -0
  91. mdb/engine/edits.py +323 -0
  92. mdb/engine/holds.py +256 -0
  93. mdb/engine/models.py +172 -0
  94. mdb/engine/ports.py +1424 -0
  95. mdb/engine/refs.py +223 -0
  96. mdb/engine/run.py +2162 -0
  97. mdb/engine/selfcheck.py +347 -0
  98. mdb/engine/trace.py +536 -0
  99. mdb/interop/__init__.py +17 -0
  100. mdb/interop/circuit_tracer_graph.py +253 -0
  101. mdb/interop/circuit_tracer_names.py +44 -0
  102. mdb/interop/clone.py +22 -0
  103. mdb/interop/names.py +295 -0
  104. mdb/interop/nn.py +431 -0
  105. mdb/interop/pyvene_compat.py +40 -0
  106. mdb/interop/pyvene_names.py +82 -0
  107. mdb/interop/tl.py +149 -0
  108. mdb/interop/verify.py +85 -0
  109. mdb/machines/__init__.py +53 -0
  110. mdb/machines/x86/__init__.py +13 -0
  111. mdb/machines/x86/address.py +171 -0
  112. mdb/machines/x86/binary.py +285 -0
  113. mdb/machines/x86/grid.py +188 -0
  114. mdb/machines/x86/index.py +184 -0
  115. mdb/machines/x86/interchange.py +156 -0
  116. mdb/machines/x86/lanes.py +281 -0
  117. mdb/machines/x86/method.py +252 -0
  118. mdb/machines/x86/method_v2.py +105 -0
  119. mdb/machines/x86/mlp.py +430 -0
  120. mdb/machines/x86/records.py +138 -0
  121. mdb/machines/x86/session.py +631 -0
  122. mdb/machines/x86/trace.py +351 -0
  123. mdb/ops/__init__.py +31 -0
  124. mdb/ops/builtin.py +1977 -0
  125. mdb/ops/context.py +60 -0
  126. mdb/ops/debugger.py +926 -0
  127. mdb/ops/errors.py +8 -0
  128. mdb/ops/features.py +513 -0
  129. mdb/ops/graph.py +58 -0
  130. mdb/ops/inspect.py +906 -0
  131. mdb/ops/lines.py +496 -0
  132. mdb/ops/named.py +672 -0
  133. mdb/ops/predict.py +450 -0
  134. mdb/ops/registry.py +332 -0
  135. mdb/ops/sets.py +988 -0
  136. mdb/ops/sweep.py +574 -0
  137. mdb/repl/__init__.py +5 -0
  138. mdb/repl/__main__.py +244 -0
  139. mdb/repl/config.py +213 -0
  140. mdb/repl/remote.py +324 -0
  141. mdb/repl/render.py +1699 -0
  142. mdb/repl/shell.py +409 -0
  143. mdb/serve/__init__.py +17 -0
  144. mdb/serve/__main__.py +180 -0
  145. mdb/serve/_legacy.py +97 -0
  146. mdb/serve/app.py +526 -0
  147. mdb/serve/blobs.py +280 -0
  148. mdb/serve/caps.py +148 -0
  149. mdb/serve/export.py +9 -0
  150. mdb/serve/guard.py +216 -0
  151. mdb/serve/live.py +412 -0
  152. mdb/serve/live_reduce.py +90 -0
  153. mdb/serve/recorded.py +515 -0
  154. mdb/serve/reduce.py +449 -0
  155. mdb/serve/schema.py +969 -0
  156. mdb/serve/states.py +125 -0
  157. mdb/serve/static/assets/index-BJpByNCO.js +58 -0
  158. mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
  159. mdb/serve/static/index.html +14 -0
  160. mdb/serve/static/manifest.json +5 -0
  161. mdb/serve/stored.py +34 -0
  162. mdb/serve/typegen.py +131 -0
  163. mdb/serve/views/__init__.py +1 -0
  164. mdb/serve/views/common.py +201 -0
  165. mdb/serve/views/frame.py +235 -0
  166. mdb/serve/views/graph.py +224 -0
  167. mdb/serve/views/live.py +402 -0
  168. mdb/serve/views/records.py +557 -0
  169. mdb/serve/views/sessions.py +151 -0
  170. mdb/serve/views/symbols.py +185 -0
  171. mdb/serve/views/timeline.py +121 -0
  172. model_debugger-0.4.0.dist-info/METADATA +1516 -0
  173. model_debugger-0.4.0.dist-info/RECORD +177 -0
  174. model_debugger-0.4.0.dist-info/WHEEL +4 -0
  175. model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
  176. model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
  177. 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"]