@mailwoman/core 7.2.0 → 7.3.0

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 (150) hide show
  1. package/api/APIClient.ts +175 -0
  2. package/api/headless.ts +23 -0
  3. package/api/index.ts +11 -0
  4. package/api/responses.ts +135 -0
  5. package/coarse-placer/coarse-placer.ts +300 -0
  6. package/coarse-placer/featurize.ts +171 -0
  7. package/coarse-placer/tools/build-dataset.ts +223 -0
  8. package/coarse-placer/tools/build-outlier-exposure.ts +172 -0
  9. package/coarse-placer/tools/build-outlier-latin.ts +200 -0
  10. package/coarse-placer/tools/build-outlier-oa.ts +231 -0
  11. package/coarse-placer/tools/eval-latin-offmap.ts +140 -0
  12. package/coarse-placer/tools/eval-openset.ts +519 -0
  13. package/coarse-placer/tools/eval-quant-compare.ts +151 -0
  14. package/coarse-placer/tools/eval.ts +187 -0
  15. package/coarse-placer/tools/fnv-hash.ts +24 -0
  16. package/coarse-placer/tools/index.ts +23 -0
  17. package/coarse-placer/tools/probe-frontier.ts +216 -0
  18. package/coarse-placer/tools/quantize.ts +116 -0
  19. package/coarse-placer/tools/train.ts +244 -0
  20. package/collections.ts +134 -0
  21. package/db/schema.ts +21 -0
  22. package/decoder/build-tree.ts +228 -0
  23. package/decoder/calibration.ts +101 -0
  24. package/decoder/containment.ts +87 -0
  25. package/decoder/index.ts +17 -0
  26. package/decoder/proposals-to-tree.ts +83 -0
  27. package/decoder/resolve-proposal-overlaps.ts +79 -0
  28. package/decoder/serialize-json.ts +70 -0
  29. package/decoder/serialize-tuples.ts +61 -0
  30. package/decoder/serialize-xml.ts +209 -0
  31. package/decoder/types.ts +159 -0
  32. package/decoder/unknown-spans.ts +103 -0
  33. package/decoder/validate-tree.ts +100 -0
  34. package/env/index.ts +42 -0
  35. package/env/load.ts +14 -0
  36. package/env/paths.ts +40 -0
  37. package/env/schema.ts +125 -0
  38. package/errors/index.ts +9 -0
  39. package/errors/schema.ts +155 -0
  40. package/fs/node.ts +38 -0
  41. package/identifiers.ts +58 -0
  42. package/index.ts +13 -0
  43. package/kysley/adapter.ts +29 -0
  44. package/kysley/client.ts +30 -0
  45. package/kysley/dialect-config.ts +30 -0
  46. package/kysley/dialect.ts +67 -0
  47. package/kysley/driver.ts +175 -0
  48. package/layers/index.ts +12 -0
  49. package/layers/manifest.ts +154 -0
  50. package/layers/schema.ts +105 -0
  51. package/locale/index.ts +9 -0
  52. package/locale/locale.ts +49 -0
  53. package/locale/profiles/en-us.ts +69 -0
  54. package/locale/profiles/fr-fr.ts +75 -0
  55. package/locale/profiles/index.ts +9 -0
  56. package/locale/profiles/ja-jp.ts +33 -0
  57. package/locale/registry.ts +68 -0
  58. package/logging/index.ts +8 -0
  59. package/logging/shared.ts +145 -0
  60. package/logging/utils.ts +46 -0
  61. package/objects.ts +211 -0
  62. package/out/api/APIClient.d.ts.map +1 -1
  63. package/out/api/APIClient.js +2 -2
  64. package/out/api/APIClient.js.map +1 -1
  65. package/out/pipeline/types.d.ts +13 -0
  66. package/out/pipeline/types.d.ts.map +1 -1
  67. package/out/pipeline/types.js.map +1 -1
  68. package/out/scripting/utils/index.d.ts.map +1 -1
  69. package/out/scripting/utils/index.js +3 -5
  70. package/out/scripting/utils/index.js.map +1 -1
  71. package/package.json +190 -107
  72. package/pipeline/index.ts +46 -0
  73. package/pipeline/reconcile-lookups.ts +108 -0
  74. package/pipeline/reconcile.ts +542 -0
  75. package/pipeline/runtime-pipeline.ts +732 -0
  76. package/pipeline/span-logit-aggregation.ts +151 -0
  77. package/pipeline/span-proposer.ts +587 -0
  78. package/pipeline/types.ts +357 -0
  79. package/policy/defaults.ts +35 -0
  80. package/policy/index.ts +10 -0
  81. package/policy/policy.ts +60 -0
  82. package/policy/proposal-collection.ts +64 -0
  83. package/policy/registry.ts +149 -0
  84. package/resolver/index.ts +29 -0
  85. package/resolver/types.ts +584 -0
  86. package/resources/LocaleIndex.ts +124 -0
  87. package/resources/ResourceMapCache.ts +126 -0
  88. package/resources/collections.ts +93 -0
  89. package/resources/debugging.ts +19 -0
  90. package/resources/git.ts +54 -0
  91. package/resources/index.ts +17 -0
  92. package/resources/languages/index.ts +49 -0
  93. package/resources/languages/types.gen.ts +1368 -0
  94. package/resources/libaddressinput.ts +105 -0
  95. package/resources/libpostal.ts +182 -0
  96. package/resources/locale.ts +23 -0
  97. package/resources/set.ts +179 -0
  98. package/resources/whosonfirst/DataSourceCache.ts +72 -0
  99. package/resources/whosonfirst/PlacetypeDataSource.ts +199 -0
  100. package/resources/whosonfirst/index.ts +10 -0
  101. package/resources/whosonfirst/loader.ts +157 -0
  102. package/resources/whosonfirst/placetypes/Placetype.ts +438 -0
  103. package/resources/whosonfirst/placetypes/admin.ts +173 -0
  104. package/resources/whosonfirst/placetypes/definition.ts +135 -0
  105. package/resources/whosonfirst/placetypes/graph.ts +0 -0
  106. package/resources/whosonfirst/placetypes/index.ts +12 -0
  107. package/resources/whosonfirst/placetypes/mermaid.ts +168 -0
  108. package/resources/whosonfirst/placetypes/tree.ts +46 -0
  109. package/routing/index.ts +208 -0
  110. package/scripting/index.ts +40 -0
  111. package/scripting/utils/index.ts +103 -0
  112. package/tokenization/Graph.ts +50 -0
  113. package/tokenization/Span.ts +297 -0
  114. package/tokenization/index.ts +9 -0
  115. package/tokenization/normalizer.ts +123 -0
  116. package/tools/download-libpostal-resources.ts +98 -0
  117. package/tools/download-ssl-address.ts +99 -0
  118. package/tools/generate-language-types.ts +194 -0
  119. package/tools/index.ts +13 -0
  120. package/types/Classification.ts +211 -0
  121. package/types/classifier.ts +133 -0
  122. package/types/component.ts +75 -0
  123. package/types/index.ts +10 -0
  124. package/types/mapping.ts +81 -0
  125. package/utils/data-root.ts +56 -0
  126. package/utils/hash.ts +27 -0
  127. package/utils/index.ts +14 -0
  128. package/utils/jsonl.ts +43 -0
  129. package/utils/python-json.ts +105 -0
  130. package/utils/python-random.ts +90 -0
  131. package/utils/repo.ts +118 -0
  132. package/utils/sealed-db.ts +85 -0
  133. package/utils/stats.ts +32 -0
  134. package/vitest.config.ts +53 -0
  135. package/out/lifecycle/ServiceSymbol.d.ts +0 -57
  136. package/out/lifecycle/ServiceSymbol.d.ts.map +0 -1
  137. package/out/lifecycle/ServiceSymbol.js +0 -60
  138. package/out/lifecycle/ServiceSymbol.js.map +0 -1
  139. package/out/lifecycle/index.d.ts +0 -11
  140. package/out/lifecycle/index.d.ts.map +0 -1
  141. package/out/lifecycle/index.js +0 -11
  142. package/out/lifecycle/index.js.map +0 -1
  143. package/out/lifecycle/lru-cache.d.ts +0 -22
  144. package/out/lifecycle/lru-cache.d.ts.map +0 -1
  145. package/out/lifecycle/lru-cache.js +0 -31
  146. package/out/lifecycle/lru-cache.js.map +0 -1
  147. package/out/lifecycle/services.d.ts +0 -144
  148. package/out/lifecycle/services.d.ts.map +0 -1
  149. package/out/lifecycle/services.js +0 -191
  150. package/out/lifecycle/services.js.map +0 -1
@@ -0,0 +1,519 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * #244 M2 Phase 1 — POST-HOC open-set scoring on the EXISTING (shipped) coarse-placer, NO retrain.
7
+ * The OA-breadth verdict found the 12-way softmax's own max-prob detector tops out at ~88/88 on
8
+ * the leave-one-family-out probe (in-map accuracy vs off-map HELDOUT-family caught). This asks:
9
+ * does a DIFFERENT open-set score, read off the same frozen weights, clear the 90/90 the softmax
10
+ * can't?
11
+ *
12
+ * The 11-way routing (argmax over the in-map classes) is FIXED — the model is unchanged. The only
13
+ * thing each score changes is the REJECT decision (keep the in-map route vs. abstain → OTHER). We
14
+ * sweep each score's threshold and trace its (in-map accuracy, heldout-caught) Pareto.
15
+ *
16
+ * Scores compared (all functions of the frozen 12 logits / 11 in-map logits `z`):
17
+ *
18
+ * - Maxprob : softmax max over the 11 in-map classes (the verdict's baseline detector)
19
+ * - P_inmap : 1 - P(OTHER) (trust the model's own OTHER head)
20
+ * - Energy : logsumexp(z) (free-energy; higher = more in-map)
21
+ * - Maxlogit : max(z)
22
+ * - Maha : -min_c (z-μ_c)ᵀ Σ⁻¹ (z-μ_c), class-conditional Gaussians (tied Σ) fit on in-map TRAIN
23
+ * logits (Lee et al. 2018, in the 11-dim in-map-logit space — the linear model's only dense
24
+ * representation). Higher = closer to the in-map manifold.
25
+ *
26
+ * In-map accuracy = of the 11-country test rows, fraction NOT rejected AND argmax-in-map == truth.
27
+ * heldout caught = of the never-trained off-map families (baltic/oceania/middle-east), fraction
28
+ * rejected. Both move with the threshold; the Pareto is the whole story.
29
+ *
30
+ * Run: `mailwoman placer eval openset [--model <dir>] [--out-md <path>]`
31
+ */
32
+
33
+ import { readFileSync, writeFileSync } from "node:fs"
34
+ import * as path from "node:path"
35
+
36
+ import { dataRootPath } from "../../utils/data-root.ts"
37
+ import { repoRootPath } from "../../utils/repo.ts"
38
+ import type { CoarsePlacerMeta } from "../coarse-placer.ts"
39
+ import { COARSE_CLASSES, featurize } from "../featurize.ts"
40
+
41
+ type ScoreKey = "maxprob" | "p_inmap" | "energy" | "maxlogit" | "maha"
42
+
43
+ interface DataRow {
44
+ raw: string
45
+ country: string
46
+ group?: string
47
+ srcCountry?: string
48
+ family?: string
49
+ }
50
+
51
+ interface ScoredRow {
52
+ correctRoute: boolean
53
+ s: Record<ScoreKey, number>
54
+ }
55
+
56
+ interface ParetoPoint {
57
+ t: number
58
+ inMapAcc: number
59
+ heldCaught: number
60
+ }
61
+
62
+ /** Options for {@linkcode evalOpenSet}. */
63
+ export interface EvalOpenSetOptions {
64
+ /** Model artifact dir. Default `$MAILWOMAN_DATA_ROOT/coarse-placer/model`. */
65
+ model?: string
66
+ /** Dataset dir. Default `<repo>/data/coarse-placer`. */
67
+ data?: string
68
+ /** Mahalanobis fit rows per class. Default 2000. */
69
+ fitPerClass?: number
70
+ /** Also write the markdown report here. */
71
+ outMd?: string
72
+ }
73
+
74
+ /** Result of {@linkcode evalOpenSet}. */
75
+ export interface EvalOpenSetResult {
76
+ /** Best score by the honest dev→test balanced min. */
77
+ winner: ScoreKey
78
+ honestMin: number
79
+ clears90: boolean
80
+ markdown: string
81
+ }
82
+
83
+ function logsumexp(xs: number[]): number {
84
+ let m = -Infinity
85
+
86
+ for (const x of xs)
87
+ if (x > m) {
88
+ m = x
89
+ }
90
+ let s = 0
91
+
92
+ for (const x of xs) {
93
+ s += Math.exp(x - m)
94
+ }
95
+
96
+ return m + Math.log(s)
97
+ }
98
+
99
+ /** Per-class softmax prob over ALL 12 classes. */
100
+ function softmax(z: Float64Array): Float64Array {
101
+ const m = Math.max(...z)
102
+ const e = z.map((x) => Math.exp(x - m))
103
+ const s = e.reduce((a, b) => a + b, 0)
104
+
105
+ return e.map((x) => x / s)
106
+ }
107
+
108
+ /** Invert a symmetric positive-definite matrix via Gauss-Jordan. */
109
+ function inverse(M: Float64Array[]): number[][] {
110
+ const n = M.length
111
+ const A = M.map((row, i) => {
112
+ const r = new Float64Array(2 * n)
113
+
114
+ for (let j = 0; j < n; j++) {
115
+ r[j] = row[j]!
116
+ }
117
+ r[n + i] = 1
118
+
119
+ return r
120
+ })
121
+
122
+ for (let col = 0; col < n; col++) {
123
+ let piv = col
124
+
125
+ for (let r = col + 1; r < n; r++)
126
+ if (Math.abs(A[r]![col]!) > Math.abs(A[piv]![col]!)) {
127
+ piv = r
128
+ }
129
+ ;[A[col], A[piv]] = [A[piv]!, A[col]!]
130
+ const d = A[col]![col]!
131
+
132
+ for (let j = 0; j < 2 * n; j++) {
133
+ A[col]![j] = A[col]![j]! / d
134
+ }
135
+
136
+ for (let r = 0; r < n; r++) {
137
+ if (r === col) continue
138
+ const f = A[r]![col]!
139
+
140
+ for (let j = 0; j < 2 * n; j++) {
141
+ A[r]![j] = A[r]![j]! - f * A[col]![j]!
142
+ }
143
+ }
144
+ }
145
+
146
+ return A.map((r) => Array.from(r.slice(n)))
147
+ }
148
+
149
+ /** Coarse-placer post-hoc open-set score comparison — see the module doc. Emits the markdown report to stdout. */
150
+ export async function evalOpenSet(
151
+ options: EvalOpenSetOptions = {},
152
+ report?: (line: string) => void
153
+ ): Promise<EvalOpenSetResult> {
154
+ const modelDir = options.model || dataRootPath("coarse-placer", "model")
155
+ const dataDir = options.data || repoRootPath("data", "coarse-placer")
156
+ const fitPerClass = options.fitPerClass ?? 2000
157
+
158
+ const meta = JSON.parse(readFileSync(path.join(modelDir, "meta.json"), "utf8")) as CoarsePlacerMeta
159
+ const W = new Float32Array(readFileSync(path.join(modelDir, "weights.bin")).buffer)
160
+ const bias = Float32Array.from(meta.bias)
161
+ const C = meta.classes.length
162
+ const D = meta.featureDim
163
+ const OTHER = meta.classes.indexOf("OTHER")
164
+ const IN = meta.classes.map((_, i) => i).filter((i) => i !== OTHER) // in-map class indices
165
+ const nIn = IN.length
166
+
167
+ if (W.length !== C * D) throw new Error(`weights ${W.length} ≠ ${C}×${D}`)
168
+
169
+ /** Raw logits (PRE-temperature) for the 12 classes. OOD scores use the geometry, not calibration. */
170
+ function logits(raw: string): Float64Array {
171
+ const feats = featurize(raw)
172
+ const z = new Float64Array(C)
173
+
174
+ for (let c = 0; c < C; c++) {
175
+ let s = bias[c]!
176
+ const base = c * D
177
+
178
+ for (const i of feats) {
179
+ s += W[base + i]!
180
+ }
181
+ z[c] = s
182
+ }
183
+
184
+ return z
185
+ }
186
+
187
+ /** In-map logit sub-vector (length nIn), in IN order. */
188
+ const inVec = (z: Float64Array): number[] => IN.map((c) => z[c]!)
189
+
190
+ function load(file: string): DataRow[] {
191
+ return readFileSync(path.join(dataDir, file), "utf8")
192
+ .trim()
193
+ .split("\n")
194
+ .map((l) => JSON.parse(l) as DataRow)
195
+ }
196
+
197
+ // ---------------------------------------------------------------------------
198
+ // Fit the Mahalanobis params on IN-MAP TRAIN logits (no test leak): per-class
199
+ // mean in the nIn-dim in-map-logit space + a tied (shared) covariance.
200
+ // ---------------------------------------------------------------------------
201
+ report?.("fitting Mahalanobis on in-map train logits…")
202
+ const trainRows = load("train.jsonl")
203
+ const byClass = new Map<string, string[]>(COARSE_CLASSES.map((c): [string, string[]] => [c, []]))
204
+
205
+ for (const r of trainRows) {
206
+ if (r.country === "OTHER") continue
207
+ const arr = byClass.get(r.country)
208
+
209
+ if (arr && arr.length < fitPerClass) {
210
+ arr.push(r.raw)
211
+ }
212
+ }
213
+ const means = new Map<string, Float64Array>() // country -> Float64Array(nIn)
214
+ const counts = new Map<string, number>()
215
+
216
+ // Accumulate per-class means.
217
+ for (const [country, raws] of byClass) {
218
+ if (raws.length === 0) continue
219
+ const mu = new Float64Array(nIn)
220
+
221
+ for (const raw of raws) {
222
+ const v = inVec(logits(raw))
223
+
224
+ for (let k = 0; k < nIn; k++) {
225
+ mu[k] = mu[k]! + v[k]!
226
+ }
227
+ }
228
+
229
+ for (let k = 0; k < nIn; k++) {
230
+ mu[k] = mu[k]! / raws.length
231
+ }
232
+ means.set(country, mu)
233
+ counts.set(country, raws.length)
234
+ }
235
+ // Tied covariance over centered in-map train logits.
236
+ const Sigma = Array.from({ length: nIn }, () => new Float64Array(nIn))
237
+ let nTot = 0
238
+
239
+ for (const [country, raws] of byClass) {
240
+ const mu = means.get(country)
241
+
242
+ if (!mu) continue
243
+
244
+ for (const raw of raws) {
245
+ const v = inVec(logits(raw))
246
+ const d = new Float64Array(nIn)
247
+
248
+ for (let k = 0; k < nIn; k++) {
249
+ d[k] = v[k]! - mu[k]!
250
+ }
251
+
252
+ for (let a = 0; a < nIn; a++) {
253
+ for (let b = 0; b < nIn; b++) {
254
+ Sigma[a]![b] = Sigma[a]![b]! + d[a]! * d[b]!
255
+ }
256
+ }
257
+ nTot++
258
+ }
259
+ }
260
+
261
+ for (let a = 0; a < nIn; a++) {
262
+ for (let b = 0; b < nIn; b++) {
263
+ Sigma[a]![b] = Sigma[a]![b]! / nTot
264
+ }
265
+ }
266
+
267
+ // Ridge for invertibility.
268
+ for (let a = 0; a < nIn; a++) {
269
+ Sigma[a]![a] = Sigma[a]![a]! + 1e-3
270
+ }
271
+
272
+ const SigmaInv = inverse(Sigma)
273
+
274
+ /** -min_c Mahalanobis² to any in-map class mean (higher = closer to the in-map manifold). */
275
+ function mahaScore(z: Float64Array): number {
276
+ const v = inVec(z)
277
+ let best = Infinity
278
+
279
+ for (const mu of means.values()) {
280
+ const d = new Float64Array(nIn)
281
+
282
+ for (let k = 0; k < nIn; k++) {
283
+ d[k] = v[k]! - mu[k]!
284
+ }
285
+ let q = 0
286
+
287
+ for (let a = 0; a < nIn; a++) {
288
+ let row = 0
289
+
290
+ for (let b = 0; b < nIn; b++) {
291
+ row += SigmaInv[a]![b]! * d[b]!
292
+ }
293
+ q += d[a]! * row
294
+ }
295
+
296
+ if (q < best) {
297
+ best = q
298
+ }
299
+ }
300
+
301
+ return -best
302
+ }
303
+
304
+ // ---------------------------------------------------------------------------
305
+ // Score the in-map test (11 countries) + the off-map heldout families.
306
+ // ---------------------------------------------------------------------------
307
+ report?.("scoring in-map test + off-map heldout…")
308
+ const SCORES: ScoreKey[] = ["maxprob", "p_inmap", "energy", "maxlogit", "maha"]
309
+
310
+ /** All open-set scores for one raw string + whether argmax-in-map routes to `trueCountry`. */
311
+ function scoreRow(raw: string, trueCountry: string | undefined): ScoredRow {
312
+ const z = logits(raw)
313
+ const probs = softmax(z)
314
+ const zin = inVec(z)
315
+ // argmax over in-map classes (the FIXED routing).
316
+ let amIdx = 0,
317
+ am = -Infinity
318
+
319
+ for (let k = 0; k < nIn; k++)
320
+ if (zin[k]! > am) {
321
+ am = zin[k]!
322
+ amIdx = k
323
+ }
324
+ const routedCountry = COARSE_CLASSES[IN[amIdx]!]!
325
+ const inmapProbMax = Math.max(...IN.map((c) => probs[c]!))
326
+
327
+ return {
328
+ correctRoute: trueCountry !== undefined && routedCountry === trueCountry,
329
+ s: {
330
+ maxprob: inmapProbMax,
331
+ p_inmap: 1 - probs[OTHER]!,
332
+ energy: logsumexp(zin),
333
+ maxlogit: Math.max(...zin),
334
+ maha: mahaScore(z),
335
+ },
336
+ }
337
+ }
338
+
339
+ const inmapTest = load("test.jsonl").filter((r) => r.country !== "OTHER") // the 11 countries only
340
+ const heldout = load("test-latin-offmap.jsonl").filter((r) => r.group === "heldout")
341
+
342
+ const inmapScored = inmapTest.map((r) => scoreRow(r.raw, r.country))
343
+ const heldoutScored = heldout.map((r) => scoreRow(r.raw, undefined))
344
+
345
+ // Honest threshold protocol: split each probe 50/50 (deterministic by index parity) into DEV + TEST.
346
+ // The operating threshold is picked on DEV (maximizing balanced min); the reported point is frozen on
347
+ // TEST — so the number is a generalization estimate, not a threshold fit to the set it's scored on.
348
+ const inDev = inmapScored.filter((_, i) => i % 2 === 0)
349
+ const inTest = inmapScored.filter((_, i) => i % 2 === 1)
350
+ const heldDev = heldoutScored.filter((_, i) => i % 2 === 0)
351
+ const heldTest = heldoutScored.filter((_, i) => i % 2 === 1)
352
+
353
+ /** (inMapAcc, heldCaught) at threshold t over a given in-map/heldout split. */
354
+ function pointAt(scoreKey: ScoreKey, t: number, inSplit: ScoredRow[], heldSplit: ScoredRow[]): ParetoPoint {
355
+ let keepCorrect = 0
356
+
357
+ for (const o of inSplit)
358
+ if (o.s[scoreKey] >= t && o.correctRoute) {
359
+ keepCorrect++
360
+ }
361
+ let caught = 0
362
+
363
+ for (const o of heldSplit)
364
+ if (o.s[scoreKey] < t) {
365
+ caught++
366
+ }
367
+
368
+ return { t, inMapAcc: (100 * keepCorrect) / inSplit.length, heldCaught: (100 * caught) / heldSplit.length }
369
+ }
370
+
371
+ // For each score: KEEP (route in-map) iff score >= threshold; else REJECT (→ OTHER).
372
+ // in-map accuracy = keep & correctRoute. heldout caught = rejected.
373
+ function paretoFor(scoreKey: ScoreKey) {
374
+ const inVals = inmapScored.map((o) => ({ v: o.s[scoreKey], ok: o.correctRoute }))
375
+ const heldVals = heldoutScored.map((o) => o.s[scoreKey])
376
+ // Candidate thresholds: quantiles of the union of scores.
377
+ const all = [...inVals.map((x) => x.v), ...heldVals].sort((a, b) => a - b)
378
+ const ts: number[] = []
379
+
380
+ for (let q = 0; q <= 200; q++) {
381
+ ts.push(all[Math.min(all.length - 1, Math.floor((q / 200) * (all.length - 1)))]!)
382
+ }
383
+ const uniq = [...new Set(ts)]
384
+ const nInVals = inVals.length
385
+ const nHeld = heldVals.length
386
+ const pts: ParetoPoint[] = uniq.map((t) => {
387
+ let keepCorrect = 0
388
+
389
+ for (const x of inVals)
390
+ if (x.v >= t && x.ok) {
391
+ keepCorrect++
392
+ }
393
+ let caught = 0
394
+
395
+ for (const v of heldVals)
396
+ if (v < t) {
397
+ caught++
398
+ }
399
+
400
+ return { t, inMapAcc: (100 * keepCorrect) / nInVals, heldCaught: (100 * caught) / nHeld }
401
+ })
402
+ // Summaries.
403
+ let balanced: { val: number; pt: ParetoPoint | null } = { val: -1, pt: null } // max of min(inMapAcc, heldCaught) on the FULL probe
404
+ let atHeld90: ParetoPoint | null = null // highest inMapAcc with heldCaught >= 90
405
+ let atIn90: ParetoPoint | null = null
406
+
407
+ // highest heldCaught with inMapAcc >= 90
408
+ for (const p of pts) {
409
+ const m = Math.min(p.inMapAcc, p.heldCaught)
410
+
411
+ if (m > balanced.val) {
412
+ balanced = { val: m, pt: p }
413
+ }
414
+
415
+ if (p.heldCaught >= 90 && (!atHeld90 || p.inMapAcc > atHeld90.inMapAcc)) {
416
+ atHeld90 = p
417
+ }
418
+
419
+ if (p.inMapAcc >= 90 && (!atIn90 || p.heldCaught > atIn90.heldCaught)) {
420
+ atIn90 = p
421
+ }
422
+ }
423
+
424
+ // HONEST point: pick t* on DEV (max balanced min), freeze + report on TEST.
425
+ let devBest: { val: number; t: number | null } = { val: -1, t: null }
426
+
427
+ for (const p of pts) {
428
+ const d = pointAt(scoreKey, p.t, inDev, heldDev)
429
+ const m = Math.min(d.inMapAcc, d.heldCaught)
430
+
431
+ if (m > devBest.val) {
432
+ devBest = { val: m, t: p.t }
433
+ }
434
+ }
435
+ const heldoutTestPt = pointAt(scoreKey, devBest.t!, inTest, heldTest)
436
+
437
+ return { balanced, atHeld90, atIn90, devThreshold: devBest.t, honest: heldoutTestPt, pts }
438
+ }
439
+
440
+ type Pareto = ReturnType<typeof paretoFor>
441
+ const results = Object.fromEntries(SCORES.map((k) => [k, paretoFor(k)])) as Record<ScoreKey, Pareto>
442
+
443
+ // ---------------------------------------------------------------------------
444
+ // Report.
445
+ // ---------------------------------------------------------------------------
446
+ const f = (x: number | null | undefined): string => (x == null ? "—" : x.toFixed(1))
447
+ const lines: string[] = []
448
+ lines.push(`# Coarse-placer M2 Phase 1 — post-hoc open-set score comparison (#244)`)
449
+ lines.push("")
450
+ lines.push(
451
+ `_Frozen shipped model (\`${path.basename(modelDir)}\`), NO retrain. In-map test ${inmapTest.length} rows ` +
452
+ `(11 countries); off-map HELDOUT ${heldout.length} rows (never-trained families: baltic/oceania/middle-east). ` +
453
+ `Mahalanobis fit on ≤${fitPerClass}/class in-map train logits. The 11-way routing is fixed; each score only ` +
454
+ `changes the reject decision._`
455
+ )
456
+ lines.push("")
457
+ function atStr(p: ParetoPoint | null): string {
458
+ if (!p) return "— (unreachable)"
459
+
460
+ return `in ${f(p.inMapAcc)} / held ${f(p.heldCaught)}`
461
+ }
462
+
463
+ lines.push(`## Honest dev→test point (threshold picked on dev, frozen on test)`)
464
+ lines.push("")
465
+ lines.push(`| score | TEST in-map | TEST held-caught | min | full-probe balanced |`)
466
+ lines.push(`|---|---:|---:|---:|---:|`)
467
+
468
+ for (const k of SCORES) {
469
+ const r = results[k]
470
+ const h = r.honest
471
+ lines.push(
472
+ `| \`${k}\` | ${f(h.inMapAcc)} | ${f(h.heldCaught)} | **${f(Math.min(h.inMapAcc, h.heldCaught))}** | ${f(r.balanced.val)} |`
473
+ )
474
+ }
475
+ lines.push("")
476
+ lines.push(`## Full-probe corners (the achievable Pareto), per score`)
477
+ lines.push("")
478
+ lines.push(`| score | balanced min(in,held) | in-map @ held≥90 | held @ in-map≥90 |`)
479
+ lines.push(`|---|---:|---:|---:|`)
480
+
481
+ for (const k of SCORES) {
482
+ const r = results[k]
483
+ const bal = r.balanced.pt
484
+ lines.push(
485
+ `| \`${k}\` | **${f(r.balanced.val)}** (in ${f(bal?.inMapAcc)}, held ${f(bal?.heldCaught)}) | ` +
486
+ `${atStr(r.atHeld90)} | ${atStr(r.atIn90)} |`
487
+ )
488
+ }
489
+ lines.push("")
490
+
491
+ // Winner by the HONEST dev→test balanced min (not the full-probe number).
492
+ const ranked = SCORES.map((k) => ({
493
+ k,
494
+ honestMin: Math.min(results[k].honest.inMapAcc, results[k].honest.heldCaught),
495
+ })).sort((a, b) => b.honestMin - a.honestMin)
496
+ const winner = ranked[0]!
497
+ const clears90 = winner.honestMin >= 90
498
+ lines.push(`## Verdict`)
499
+ lines.push("")
500
+ lines.push(
501
+ `Best score (honest dev→test): **\`${winner.k}\`** at min(in-map, heldout) = **${f(winner.honestMin)}** on the frozen test half. ` +
502
+ (clears90
503
+ ? `**Clears 90/90 post-hoc** — wire it into CoarsePlacer as the open-set reject rule; no retrain needed (Phase 2 reject-head unnecessary).`
504
+ : `Below the 90/90 bar — the best post-hoc score reaches ${f(winner.honestMin)}. Escalate to Phase 2 (explicit binary reject head).`)
505
+ )
506
+ lines.push("")
507
+ lines.push(`Ranking (honest dev→test min): ${ranked.map((r) => `\`${r.k}\` ${f(r.honestMin)}`).join(" · ")}`)
508
+ lines.push("")
509
+
510
+ const md = lines.join("\n")
511
+ console.log(md)
512
+
513
+ if (options.outMd) {
514
+ writeFileSync(options.outMd, md)
515
+ report?.(`\n[written] ${options.outMd}`)
516
+ }
517
+
518
+ return { winner: winner.k, honestMin: winner.honestMin, clears90, markdown: md }
519
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Accuracy cost of the #244 coarse-placer int8 quantization (milestone 3). Runs the held-out test
7
+ * split through the fp32 model and the int8 model (dequantized inline) and reports overall + per-
8
+ * class accuracy for each, the delta, prediction-agreement rate, and confidence MAE. Gate: int8
9
+ * within ~1pp of fp32 (the milestone target).
10
+ *
11
+ * Run: `mailwoman placer eval quant-compare [--fp32 <dir>] [--int8 <dir>] [--abstain 0.5]`
12
+ */
13
+
14
+ import { readFileSync } from "node:fs"
15
+ import * as path from "node:path"
16
+
17
+ import { dataRootPath } from "../../utils/data-root.ts"
18
+ import { repoRootPath } from "../../utils/repo.ts"
19
+ import { CoarsePlacer, type CoarsePlacerMeta } from "../coarse-placer.ts"
20
+
21
+ interface TestRow {
22
+ raw: string
23
+ country: string
24
+ }
25
+
26
+ /** Options for {@linkcode evalQuantCompare}. */
27
+ export interface EvalQuantCompareOptions {
28
+ /** Fp32 artifact dir. Default `$MAILWOMAN_DATA_ROOT/coarse-placer/model`. */
29
+ fp32?: string
30
+ /** Int8 artifact dir. Default `$MAILWOMAN_DATA_ROOT/coarse-placer/model-int8`. */
31
+ int8?: string
32
+ /** Abstention threshold. Default 0.5. */
33
+ abstain?: number
34
+ /** Dataset dir (`test.jsonl`). Default `<repo>/data/coarse-placer`. */
35
+ data?: string
36
+ }
37
+
38
+ /** Result of {@linkcode evalQuantCompare}. */
39
+ export interface EvalQuantCompareResult {
40
+ n: number
41
+ /** Fp32 overall accuracy in percent. */
42
+ accFp32: number
43
+ /** Int8 overall accuracy in percent. */
44
+ accInt8: number
45
+ /** Whether int8 is within 1pp of fp32 (the gate). */
46
+ pass: boolean
47
+ }
48
+
49
+ /** Coarse-placer int8-vs-fp32 comparison — see the module doc. Emits the report to stdout. */
50
+ export async function evalQuantCompare(options: EvalQuantCompareOptions = {}): Promise<EvalQuantCompareResult> {
51
+ const fp32Dir = options.fp32 || dataRootPath("coarse-placer", "model")
52
+ const int8Dir = options.int8 || dataRootPath("coarse-placer", "model-int8")
53
+ const abstainBelow = options.abstain ?? 0.5
54
+ const dataDir = options.data || repoRootPath("data", "coarse-placer")
55
+
56
+ function loadFp32(dir: string): CoarsePlacer {
57
+ const meta = JSON.parse(readFileSync(path.join(dir, "meta.json"), "utf8")) as CoarsePlacerMeta
58
+ const buf = readFileSync(path.join(dir, "weights.bin"))
59
+ const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
60
+ const weights = new Float32Array(ab)
61
+
62
+ return new CoarsePlacer({ ...meta, weights }, { abstainBelow })
63
+ }
64
+ function loadInt8(dir: string): CoarsePlacer {
65
+ const meta = JSON.parse(readFileSync(path.join(dir, "meta.json"), "utf8")) as CoarsePlacerMeta
66
+ const buf = readFileSync(path.join(dir, "weights.bin"))
67
+ const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
68
+ const int8 = new Int8Array(ab)
69
+ const C = meta.classes.length
70
+ const dim = meta.featureDim
71
+ const scales = meta.scales!
72
+ const weights = new Float32Array(C * dim)
73
+
74
+ for (let c = 0; c < C; c++) {
75
+ const s = scales[c]!
76
+ const base = c * dim
77
+
78
+ for (let i = 0; i < dim; i++) {
79
+ weights[base + i] = int8[base + i]! * s
80
+ }
81
+ }
82
+
83
+ return new CoarsePlacer({ ...meta, weights }, { abstainBelow })
84
+ }
85
+
86
+ const fp32 = loadFp32(fp32Dir)
87
+ const int8 = loadInt8(int8Dir)
88
+
89
+ const test: TestRow[] = readFileSync(path.join(dataDir, "test.jsonl"), "utf8")
90
+ .trim()
91
+ .split("\n")
92
+ .map((l) => JSON.parse(l) as TestRow)
93
+
94
+ const classes = (JSON.parse(readFileSync(path.join(fp32Dir, "meta.json"), "utf8")) as CoarsePlacerMeta).classes
95
+ let okF = 0
96
+ let okI = 0
97
+ let agree = 0
98
+ let confMae = 0
99
+ const perF: Record<string, { n: number; ok: number }> = {}
100
+ const perI: Record<string, { n: number; ok: number }> = {}
101
+
102
+ for (const r of test) {
103
+ const pf = fp32.predict(r.raw)
104
+ const pi = int8.predict(r.raw)
105
+ const cf = pf.country ?? "(abstain)"
106
+ const ci = pi.country ?? "(abstain)"
107
+ ;(perF[r.country] ??= { n: 0, ok: 0 }).n++
108
+ ;(perI[r.country] ??= { n: 0, ok: 0 }).n++
109
+
110
+ if (cf === r.country) {
111
+ okF++
112
+ perF[r.country]!.ok++
113
+ }
114
+
115
+ if (ci === r.country) {
116
+ okI++
117
+ perI[r.country]!.ok++
118
+ }
119
+
120
+ if (cf === ci) {
121
+ agree++
122
+ }
123
+ confMae += Math.abs(pf.confidence - pi.confidence)
124
+ }
125
+ const N = test.length
126
+ const accF = (100 * okF) / N
127
+ const accI = (100 * okI) / N
128
+ console.log(`coarse-placer int8 vs fp32 — test n=${N} (abstain ${abstainBelow})`)
129
+ console.log(
130
+ ` overall accuracy: fp32 ${accF.toFixed(2)}% int8 ${accI.toFixed(2)}% Δ ${(accI - accF >= 0 ? "+" : "") + (accI - accF).toFixed(2)}pp`
131
+ )
132
+ console.log(` prediction agreement (same top class): ${((100 * agree) / N).toFixed(2)}%`)
133
+ console.log(` confidence MAE: ${(confMae / N).toFixed(4)}`)
134
+ console.log(` per-class recall (fp32 → int8):`)
135
+
136
+ for (const c of classes) {
137
+ const f = perF[c]
138
+ const i = perI[c]!
139
+
140
+ if (!f) continue
141
+ const rf = (100 * f.ok) / f.n
142
+ const ri = (100 * i.ok) / i.n
143
+ console.log(
144
+ ` ${c.padEnd(6)} ${rf.toFixed(1)}% → ${ri.toFixed(1)}% (Δ ${(ri - rf >= 0 ? "+" : "") + (ri - rf).toFixed(1)}pp, n=${f.n})`
145
+ )
146
+ }
147
+ const pass = Math.abs(accI - accF) <= 1.0
148
+ console.log(` gate: ${pass ? "PASS (within 1pp)" : "FAIL (>1pp drop)"}`)
149
+
150
+ return { n: N, accFp32: accF, accInt8: accI, pass }
151
+ }