robustrep 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
robustrep/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """robustrep: robust, transport-agnostic reputation scoring for AI agents."""
2
+ from .config import Config
3
+ from .pipeline import score
4
+
5
+ __all__ = ["Config", "score"]
6
+ __version__ = "0.1.0"
robustrep/aggregate.py ADDED
@@ -0,0 +1,262 @@
1
+ """Aggregators turn (values, weights) into (score, ci_low, ci_high).
2
+
3
+ The arithmetic mean has breakdown point zero: a single extreme rating can move
4
+ it arbitrarily far. The weighted median has breakdown point ~0.5 (roughly half
5
+ the total weight must be adversarial to move it), so it is the default
6
+ aggregator here. `Aggregator` is an abstract base so Bayesian and graph-based
7
+ aggregators can be added later behind the same interface.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from abc import ABC, abstractmethod
12
+
13
+ import numpy as np
14
+
15
+ from .config import Config
16
+
17
+ # Half-weight threshold is nudged down by this relative fraction so that
18
+ # float64 cumsum drift at an exact tie doesn't step one element too far
19
+ # (which would break scale invariance and bias the result upward).
20
+ _TIE_EPS = 1e-9
21
+
22
+ # Minimum fraction of bootstrap resamples that must carry non-zero total
23
+ # weight for the CI to be considered meaningful.
24
+ MIN_VALID_BOOT_FRACTION = 0.1
25
+
26
+ # Cap on the number of (resample x vote) float64 cells materialized at once
27
+ # by `bootstrap_ci`'s chunked multinomial draw, so peak memory stays bounded
28
+ # even for a ratee with thousands of votes: a chunk holds at most this many
29
+ # cells regardless of how large `n_boot` is.
30
+ _MAX_BOOT_CHUNK_CELLS = 2_000_000
31
+
32
+
33
+ def _validate(values: np.ndarray, weights: np.ndarray, name: str) -> tuple[np.ndarray, np.ndarray]:
34
+ """Shared input validation for `weighted_median` and `bootstrap_ci`.
35
+
36
+ Coerces both to 1-D float64 arrays and validates: 1-D, non-empty, equal
37
+ length, all-finite (no NaN/+/-inf), weights non-negative, and weights
38
+ summing to > 0. Returns the coerced `(values, weights)`. Raises
39
+ ValueError (messages prefixed with `name`, the caller's own name) on any
40
+ violation.
41
+ """
42
+ values = np.asarray(values, dtype=float)
43
+ weights = np.asarray(weights, dtype=float)
44
+ if values.ndim != 1 or weights.ndim != 1:
45
+ raise ValueError(f"{name}: values/weights must be 1-D")
46
+ if values.shape[0] == 0:
47
+ raise ValueError(f"{name}: values/weights must not be empty")
48
+ if values.shape != weights.shape:
49
+ raise ValueError(f"{name}: values and weights must have the same length")
50
+ if not np.isfinite(values).all() or not np.isfinite(weights).all():
51
+ raise ValueError(f"{name}: values/weights must not contain non-finite entries (NaN/inf)")
52
+ if (weights < 0).any():
53
+ raise ValueError(f"{name}: weights must be non-negative")
54
+ if weights.sum() <= 0:
55
+ raise ValueError(f"{name}: weights must sum to > 0")
56
+ return values, weights
57
+
58
+
59
+ def _weighted_median_pos(cum: np.ndarray) -> int:
60
+ """Position in an ascending cumulative-weight array selected by the lower-weighted-
61
+ median convention: the first index at which cumulative weight reaches >= half the
62
+ total (`np.searchsorted(..., side="left")`), with the half-weight threshold nudged
63
+ down by `_TIE_EPS` to absorb float64 cumsum drift at exact ties. Shared by
64
+ `_weighted_median_sorted` and `weighted_median_index` so this tie-tolerance logic
65
+ lives in exactly one place. `cum` must be non-empty and non-decreasing (a cumsum).
66
+ """
67
+ half = 0.5 * cum[-1]
68
+ return int(np.searchsorted(cum, half * (1 - _TIE_EPS), side="left"))
69
+
70
+
71
+ def _weighted_median_sorted(v: np.ndarray, w: np.ndarray) -> float:
72
+ """Weighted median of already-sorted, already-validated inputs.
73
+
74
+ Assumes `v` is sorted ascending and `w` is finite, non-negative, and sums
75
+ to > 0. Not for external use (no validation) — see `weighted_median`.
76
+ """
77
+ return float(v[_weighted_median_pos(np.cumsum(w))])
78
+
79
+
80
+ def weighted_median(values: np.ndarray, weights: np.ndarray) -> float:
81
+ """Return the weighted median of `values` under `weights`.
82
+
83
+ Tie/even-count convention: this is the *lower* weighted median. Sorting
84
+ values ascending and walking cumulative weight, the returned value is the
85
+ first one at which cumulative weight reaches >= half the total weight
86
+ (`np.searchsorted(..., side="left")`, with the half-weight threshold
87
+ nudged down by a small epsilon to absorb float64 cumsum drift at exact
88
+ ties). For an even count with equal weights this picks the smaller of the
89
+ two middle values (e.g. [0.2, 0.8] with equal weights returns 0.2),
90
+ matching a robust, deterministic, order-independent convention rather
91
+ than numpy's mean-of-two-middles.
92
+
93
+ Raises ValueError if `values`/`weights` are not 1-D, are empty,
94
+ mismatched in length, contain NaN or +/-inf, or if any weight is
95
+ negative or all weights are zero (see `_validate`).
96
+ """
97
+ values, weights = _validate(values, weights, "weighted_median")
98
+ order = np.argsort(values, kind="stable")
99
+ return _weighted_median_sorted(values[order], weights[order])
100
+
101
+
102
+ def weighted_median_index(values: np.ndarray, weights: np.ndarray) -> int:
103
+ """Return the *original* index of the element `weighted_median` would return.
104
+
105
+ Same validation, stable sort, and tie tolerance as `weighted_median` (see
106
+ `_validate` and `_weighted_median_sorted`) -- `values[weighted_median_index(values,
107
+ weights)] == weighted_median(values, weights)` always holds. Useful when a caller
108
+ needs to know *which* input element was selected (e.g. `explain()` marking the
109
+ vote/tag chosen by the weighted-median chain), not just its value.
110
+ """
111
+ values, weights = _validate(values, weights, "weighted_median_index")
112
+ order = np.argsort(values, kind="stable")
113
+ cum = np.cumsum(weights[order])
114
+ return int(order[_weighted_median_pos(cum)])
115
+
116
+
117
+ def _bootstrap_draws(
118
+ v_sorted: np.ndarray,
119
+ w_sorted: np.ndarray,
120
+ n_boot: int,
121
+ rng: np.random.Generator,
122
+ chunk_size: int,
123
+ ) -> np.ndarray:
124
+ """The array of valid weighted-median bootstrap draws (length <= n_boot).
125
+
126
+ `v_sorted`/`w_sorted` must already be sorted ascending by value. Draws
127
+ are generated `chunk_size` resamples at a time via
128
+ `rng.multinomial(n, [1/n]*n, size=chunk_size)` (see `bootstrap_ci` for
129
+ why a multinomial count draw is equivalent to classic index resampling
130
+ with replacement) and accumulated, so peak memory is bounded by
131
+ `chunk_size * n` regardless of `n_boot`. A resample whose weights sum to
132
+ zero has an undefined weighted median and is dropped from the result
133
+ rather than counted.
134
+ """
135
+ n = len(v_sorted)
136
+ pvals = np.full(n, 1.0 / n)
137
+ boots = []
138
+ remaining = n_boot
139
+ while remaining > 0:
140
+ take = min(chunk_size, remaining)
141
+ remaining -= take
142
+ counts = rng.multinomial(n, pvals, size=take)
143
+ cum = np.cumsum(counts * w_sorted, axis=1)
144
+ valid = cum[:, -1] > 0
145
+ cum_valid = cum[valid]
146
+ half = 0.5 * cum_valid[:, -1:]
147
+ idx = (cum_valid >= half * (1 - _TIE_EPS)).argmax(axis=1)
148
+ boots.append(v_sorted[idx])
149
+ return np.concatenate(boots) if boots else np.array([], dtype=float)
150
+
151
+
152
+ def bootstrap_ci(
153
+ values: np.ndarray,
154
+ weights: np.ndarray,
155
+ n_boot: int,
156
+ rng: np.random.Generator,
157
+ ci_level: float,
158
+ ) -> tuple[float, float]:
159
+ """Vectorized bootstrap (lo, hi) quantiles of the weighted median.
160
+
161
+ Equivalent to resampling n `(value, weight)` pairs with replacement
162
+ `n_boot` times and taking the weighted median of each resample, but
163
+ without a Python-level loop over resamples. A resample's weighted
164
+ median depends only on how many times each *position* was drawn (its
165
+ resample count), not on the order of the draws, so after sorting
166
+ `values` once (stable), `rng.multinomial(n, [1/n]*n, size=chunk)`
167
+ produces a batch of resamples' per-position counts in a single call --
168
+ equivalent to drawing n indices with replacement, once per resample --
169
+ and the cumulative sum of `counts * sorted_weights` along each row gives
170
+ every resample's weighted median in one vectorized pass (see
171
+ `_bootstrap_draws`). Processed in chunks of at most
172
+ `max(1, 2_000_000 // n)` resamples so peak memory stays bounded even for
173
+ a ratee with thousands of votes; this is what keeps the per-ratee
174
+ bootstrap affordable at ~28k ratees.
175
+
176
+ Inputs are validated exactly like `weighted_median` (see `_validate`).
177
+ A resample whose weights sum to zero has an undefined weighted median
178
+ and is skipped rather than counted. If fewer than `max(2, n_boot // 10)`
179
+ resamples remain valid, raises ValueError instead of silently reporting
180
+ a CI built from too few (or zero) samples. Skipping all-zero resamples
181
+ conditions the CI on non-zero weight; unreachable in-pipeline since
182
+ Config forbids zero weights.
183
+ """
184
+ values, weights = _validate(values, weights, "bootstrap_ci")
185
+ n = len(values)
186
+ order = np.argsort(values, kind="stable")
187
+ v_sorted, w_sorted = values[order], weights[order]
188
+
189
+ chunk_size = max(1, _MAX_BOOT_CHUNK_CELLS // n)
190
+ boots = _bootstrap_draws(v_sorted, w_sorted, n_boot, rng, chunk_size)
191
+
192
+ min_valid = max(2, int(n_boot * MIN_VALID_BOOT_FRACTION))
193
+ if boots.size < min_valid:
194
+ raise ValueError("bootstrap degenerate: too many zero-weight resamples")
195
+
196
+ alpha = (1 - ci_level) / 2
197
+ lo, hi = np.quantile(boots, [alpha, 1 - alpha])
198
+ return float(lo), float(hi)
199
+
200
+
201
+ def _bootstrap_ci(
202
+ values: np.ndarray,
203
+ weights: np.ndarray,
204
+ n_boot: int,
205
+ seed: int,
206
+ ci_level: float,
207
+ ) -> tuple[float, float]:
208
+ """Bootstrap (lo, hi) quantiles of the weighted median, seeded by a plain
209
+ integer `seed`. Thin wrapper around `bootstrap_ci` (the one bootstrap
210
+ implementation) for callers that don't manage their own
211
+ `numpy.random.Generator`.
212
+ """
213
+ return bootstrap_ci(values, weights, n_boot, np.random.default_rng(seed), ci_level)
214
+
215
+
216
+ class Aggregator(ABC):
217
+ """Abstract base for turning per-ratee (values, weights) into a score with a CI.
218
+
219
+ Concrete implementations (e.g. `WeightedMedian`, and future Bayesian or
220
+ graph-based aggregators) all expose the same `aggregate` interface so the
221
+ pipeline can swap aggregation strategies without changing callers.
222
+ """
223
+
224
+ @abstractmethod
225
+ def aggregate(self, values: np.ndarray, weights: np.ndarray) -> tuple[float, float, float]:
226
+ """Return (score, ci_low, ci_high)."""
227
+
228
+
229
+ class WeightedMedian(Aggregator):
230
+ """Weighted-median aggregator with a bootstrap confidence interval.
231
+
232
+ `aggregate` resamples (values, weights) pairs with replacement `n_boot`
233
+ times, computes the weighted median of each resample, and reports the
234
+ `ci_level` central interval of the bootstrap distribution (widened if
235
+ needed so it always contains the point estimate). Note: with tied or
236
+ coarse-grained values the percentile bootstrap can legitimately return a
237
+ zero-width interval (every resample lands on the same value) — consumers
238
+ should read the CI together with the underlying vote count rather than
239
+ treating a narrow interval alone as high confidence.
240
+ """
241
+
242
+ def __init__(self, n_boot: int = 1000, seed: int = 0, ci_level: float = 0.95):
243
+ if n_boot < 0:
244
+ raise ValueError("WeightedMedian: n_boot must be >= 0")
245
+ if not 0 < ci_level < 1:
246
+ raise ValueError("WeightedMedian: ci_level must be in (0, 1)")
247
+ self.n_boot, self.seed, self.ci_level = n_boot, seed, ci_level
248
+
249
+ @classmethod
250
+ def from_config(cls, cfg: Config) -> "WeightedMedian":
251
+ """Build a WeightedMedian aggregator from a pipeline Config."""
252
+ return cls(n_boot=cfg.bootstrap_n, seed=cfg.bootstrap_seed, ci_level=cfg.ci_level)
253
+
254
+ def aggregate(self, values: np.ndarray, weights: np.ndarray) -> tuple[float, float, float]:
255
+ values = np.asarray(values, dtype=float)
256
+ weights = np.asarray(weights, dtype=float)
257
+ point = weighted_median(values, weights)
258
+ if len(values) == 1 or self.n_boot == 0:
259
+ return point, point, point
260
+ lo, hi = _bootstrap_ci(values, weights, self.n_boot, self.seed, self.ci_level)
261
+ # defensive; not expected to fire
262
+ return point, float(min(lo, point)), float(max(hi, point))