@mailwoman/core 8.1.0 → 8.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 (407) hide show
  1. package/api/APIClient.ts +3 -4
  2. package/api/responses.ts +6 -3
  3. package/coarse-placer/coarse-placer.ts +26 -11
  4. package/coarse-placer/featurize.ts +25 -16
  5. package/coarse-placer/tools/build-dataset.ts +42 -18
  6. package/coarse-placer/tools/build-outlier-exposure.ts +51 -18
  7. package/coarse-placer/tools/build-outlier-latin.ts +48 -22
  8. package/coarse-placer/tools/build-outlier-oa.ts +52 -20
  9. package/coarse-placer/tools/eval-latin-offmap.ts +37 -12
  10. package/coarse-placer/tools/eval-openset.ts +104 -37
  11. package/coarse-placer/tools/eval-quant-compare.ts +41 -11
  12. package/coarse-placer/tools/eval.ts +51 -13
  13. package/coarse-placer/tools/fnv-hash.ts +5 -3
  14. package/coarse-placer/tools/probe-frontier.ts +63 -32
  15. package/coarse-placer/tools/quantize.ts +30 -8
  16. package/coarse-placer/tools/train.ts +63 -17
  17. package/collections.ts +2 -2
  18. package/decoder/build-tree.ts +16 -3
  19. package/decoder/calibration.ts +23 -7
  20. package/decoder/containment.ts +3 -1
  21. package/decoder/proposals-to-tree.ts +2 -0
  22. package/decoder/resolve-proposal-overlaps.ts +5 -1
  23. package/decoder/serialize-json.ts +8 -2
  24. package/decoder/serialize-tuples.ts +7 -2
  25. package/decoder/serialize-xml.ts +29 -11
  26. package/decoder/types.ts +34 -12
  27. package/decoder/unknown-spans.ts +14 -5
  28. package/decoder/validate-tree.ts +6 -1
  29. package/env/index.ts +1 -1
  30. package/env/load.ts +1 -1
  31. package/env/paths.ts +1 -1
  32. package/env/schema.ts +12 -4
  33. package/errors/schema.ts +1 -1
  34. package/fs/node.ts +9 -10
  35. package/identifiers.ts +3 -3
  36. package/kysley/adapter.ts +1 -1
  37. package/layers/manifest.ts +22 -8
  38. package/layers/schema.ts +59 -19
  39. package/locale/locale.ts +6 -2
  40. package/locale/profiles/en-us.ts +3 -0
  41. package/locale/profiles/fr-fr.ts +3 -0
  42. package/locale/profiles/ja-jp.ts +6 -0
  43. package/locale/registry.ts +3 -1
  44. package/logging/shared.ts +1 -0
  45. package/logging/utils.ts +1 -1
  46. package/objects.ts +7 -2
  47. package/out/api/APIClient.d.ts +1 -1
  48. package/out/api/APIClient.d.ts.map +1 -1
  49. package/out/api/APIClient.js +3 -2
  50. package/out/api/APIClient.js.map +1 -1
  51. package/out/api/responses.d.ts.map +1 -1
  52. package/out/api/responses.js +3 -3
  53. package/out/api/responses.js.map +1 -1
  54. package/out/coarse-placer/coarse-placer.d.ts +19 -9
  55. package/out/coarse-placer/coarse-placer.d.ts.map +1 -1
  56. package/out/coarse-placer/coarse-placer.js +6 -4
  57. package/out/coarse-placer/coarse-placer.js.map +1 -1
  58. package/out/coarse-placer/featurize.d.ts.map +1 -1
  59. package/out/coarse-placer/featurize.js +20 -16
  60. package/out/coarse-placer/featurize.js.map +1 -1
  61. package/out/coarse-placer/tools/build-dataset.d.ts +15 -5
  62. package/out/coarse-placer/tools/build-dataset.d.ts.map +1 -1
  63. package/out/coarse-placer/tools/build-dataset.js +19 -14
  64. package/out/coarse-placer/tools/build-dataset.js.map +1 -1
  65. package/out/coarse-placer/tools/build-outlier-exposure.d.ts +21 -7
  66. package/out/coarse-placer/tools/build-outlier-exposure.d.ts.map +1 -1
  67. package/out/coarse-placer/tools/build-outlier-exposure.js +24 -12
  68. package/out/coarse-placer/tools/build-outlier-exposure.js.map +1 -1
  69. package/out/coarse-placer/tools/build-outlier-latin.d.ts +18 -6
  70. package/out/coarse-placer/tools/build-outlier-latin.d.ts.map +1 -1
  71. package/out/coarse-placer/tools/build-outlier-latin.js +27 -17
  72. package/out/coarse-placer/tools/build-outlier-latin.js.map +1 -1
  73. package/out/coarse-placer/tools/build-outlier-oa.d.ts +18 -6
  74. package/out/coarse-placer/tools/build-outlier-oa.d.ts.map +1 -1
  75. package/out/coarse-placer/tools/build-outlier-oa.js +29 -15
  76. package/out/coarse-placer/tools/build-outlier-oa.js.map +1 -1
  77. package/out/coarse-placer/tools/eval-latin-offmap.d.ts +18 -6
  78. package/out/coarse-placer/tools/eval-latin-offmap.d.ts.map +1 -1
  79. package/out/coarse-placer/tools/eval-latin-offmap.js +13 -7
  80. package/out/coarse-placer/tools/eval-latin-offmap.js.map +1 -1
  81. package/out/coarse-placer/tools/eval-openset.d.ts +24 -8
  82. package/out/coarse-placer/tools/eval-openset.d.ts.map +1 -1
  83. package/out/coarse-placer/tools/eval-openset.js +52 -31
  84. package/out/coarse-placer/tools/eval-openset.js.map +1 -1
  85. package/out/coarse-placer/tools/eval-quant-compare.d.ts +30 -10
  86. package/out/coarse-placer/tools/eval-quant-compare.d.ts.map +1 -1
  87. package/out/coarse-placer/tools/eval-quant-compare.js +4 -2
  88. package/out/coarse-placer/tools/eval-quant-compare.js.map +1 -1
  89. package/out/coarse-placer/tools/eval.d.ts +24 -8
  90. package/out/coarse-placer/tools/eval.d.ts.map +1 -1
  91. package/out/coarse-placer/tools/eval.js +16 -6
  92. package/out/coarse-placer/tools/eval.js.map +1 -1
  93. package/out/coarse-placer/tools/fnv-hash.d.ts +3 -1
  94. package/out/coarse-placer/tools/fnv-hash.d.ts.map +1 -1
  95. package/out/coarse-placer/tools/fnv-hash.js +5 -3
  96. package/out/coarse-placer/tools/fnv-hash.js.map +1 -1
  97. package/out/coarse-placer/tools/probe-frontier.d.ts +18 -6
  98. package/out/coarse-placer/tools/probe-frontier.d.ts.map +1 -1
  99. package/out/coarse-placer/tools/probe-frontier.js +39 -23
  100. package/out/coarse-placer/tools/probe-frontier.js.map +1 -1
  101. package/out/coarse-placer/tools/quantize.d.ts +15 -5
  102. package/out/coarse-placer/tools/quantize.d.ts.map +1 -1
  103. package/out/coarse-placer/tools/quantize.js +11 -4
  104. package/out/coarse-placer/tools/quantize.js.map +1 -1
  105. package/out/coarse-placer/tools/train.d.ts +24 -8
  106. package/out/coarse-placer/tools/train.d.ts.map +1 -1
  107. package/out/coarse-placer/tools/train.js +24 -10
  108. package/out/coarse-placer/tools/train.js.map +1 -1
  109. package/out/collections.js +2 -2
  110. package/out/collections.js.map +1 -1
  111. package/out/decoder/build-tree.d.ts.map +1 -1
  112. package/out/decoder/build-tree.js +9 -3
  113. package/out/decoder/build-tree.js.map +1 -1
  114. package/out/decoder/calibration.d.ts +17 -3
  115. package/out/decoder/calibration.d.ts.map +1 -1
  116. package/out/decoder/calibration.js +12 -4
  117. package/out/decoder/calibration.js.map +1 -1
  118. package/out/decoder/containment.d.ts +3 -1
  119. package/out/decoder/containment.d.ts.map +1 -1
  120. package/out/decoder/containment.js +3 -1
  121. package/out/decoder/containment.js.map +1 -1
  122. package/out/decoder/proposals-to-tree.d.ts.map +1 -1
  123. package/out/decoder/proposals-to-tree.js.map +1 -1
  124. package/out/decoder/resolve-proposal-overlaps.d.ts.map +1 -1
  125. package/out/decoder/resolve-proposal-overlaps.js +5 -1
  126. package/out/decoder/resolve-proposal-overlaps.js.map +1 -1
  127. package/out/decoder/serialize-json.d.ts +6 -2
  128. package/out/decoder/serialize-json.d.ts.map +1 -1
  129. package/out/decoder/serialize-json.js.map +1 -1
  130. package/out/decoder/serialize-tuples.d.ts +6 -2
  131. package/out/decoder/serialize-tuples.d.ts.map +1 -1
  132. package/out/decoder/serialize-tuples.js.map +1 -1
  133. package/out/decoder/serialize-xml.d.ts +21 -7
  134. package/out/decoder/serialize-xml.d.ts.map +1 -1
  135. package/out/decoder/serialize-xml.js +7 -5
  136. package/out/decoder/serialize-xml.js.map +1 -1
  137. package/out/decoder/types.d.ts +34 -12
  138. package/out/decoder/types.d.ts.map +1 -1
  139. package/out/decoder/types.js +1 -1
  140. package/out/decoder/types.js.map +1 -1
  141. package/out/decoder/unknown-spans.d.ts +9 -3
  142. package/out/decoder/unknown-spans.d.ts.map +1 -1
  143. package/out/decoder/unknown-spans.js +4 -2
  144. package/out/decoder/unknown-spans.js.map +1 -1
  145. package/out/decoder/validate-tree.d.ts +3 -1
  146. package/out/decoder/validate-tree.d.ts.map +1 -1
  147. package/out/decoder/validate-tree.js +3 -1
  148. package/out/decoder/validate-tree.js.map +1 -1
  149. package/out/env/index.js +0 -1
  150. package/out/env/index.js.map +1 -1
  151. package/out/env/load.js +1 -1
  152. package/out/env/load.js.map +1 -1
  153. package/out/env/paths.js +1 -1
  154. package/out/env/paths.js.map +1 -1
  155. package/out/env/schema.d.ts.map +1 -1
  156. package/out/env/schema.js +12 -4
  157. package/out/env/schema.js.map +1 -1
  158. package/out/errors/schema.js +1 -1
  159. package/out/errors/schema.js.map +1 -1
  160. package/out/fs/node.d.ts +1 -2
  161. package/out/fs/node.d.ts.map +1 -1
  162. package/out/fs/node.js +7 -8
  163. package/out/fs/node.js.map +1 -1
  164. package/out/identifiers.js +3 -3
  165. package/out/identifiers.js.map +1 -1
  166. package/out/kysley/adapter.d.ts +1 -1
  167. package/out/kysley/adapter.d.ts.map +1 -1
  168. package/out/kysley/adapter.js +1 -1
  169. package/out/kysley/adapter.js.map +1 -1
  170. package/out/layers/manifest.d.ts +18 -6
  171. package/out/layers/manifest.d.ts.map +1 -1
  172. package/out/layers/manifest.js +8 -4
  173. package/out/layers/manifest.js.map +1 -1
  174. package/out/layers/schema.d.ts +57 -19
  175. package/out/layers/schema.d.ts.map +1 -1
  176. package/out/layers/schema.js +24 -8
  177. package/out/layers/schema.js.map +1 -1
  178. package/out/locale/locale.d.ts +6 -2
  179. package/out/locale/locale.d.ts.map +1 -1
  180. package/out/locale/profiles/en-us.d.ts +3 -0
  181. package/out/locale/profiles/en-us.d.ts.map +1 -1
  182. package/out/locale/profiles/en-us.js +3 -0
  183. package/out/locale/profiles/en-us.js.map +1 -1
  184. package/out/locale/profiles/fr-fr.d.ts +3 -0
  185. package/out/locale/profiles/fr-fr.d.ts.map +1 -1
  186. package/out/locale/profiles/fr-fr.js +3 -0
  187. package/out/locale/profiles/fr-fr.js.map +1 -1
  188. package/out/locale/profiles/ja-jp.d.ts +3 -0
  189. package/out/locale/profiles/ja-jp.d.ts.map +1 -1
  190. package/out/locale/profiles/ja-jp.js +6 -0
  191. package/out/locale/profiles/ja-jp.js.map +1 -1
  192. package/out/locale/registry.d.ts +3 -1
  193. package/out/locale/registry.d.ts.map +1 -1
  194. package/out/locale/registry.js +3 -1
  195. package/out/locale/registry.js.map +1 -1
  196. package/out/logging/shared.d.ts.map +1 -1
  197. package/out/logging/shared.js +1 -0
  198. package/out/logging/shared.js.map +1 -1
  199. package/out/logging/utils.js +1 -1
  200. package/out/logging/utils.js.map +1 -1
  201. package/out/objects.d.ts.map +1 -1
  202. package/out/objects.js +2 -2
  203. package/out/objects.js.map +1 -1
  204. package/out/pipeline/index.d.ts +2 -2
  205. package/out/pipeline/index.d.ts.map +1 -1
  206. package/out/pipeline/index.js +1 -1
  207. package/out/pipeline/index.js.map +1 -1
  208. package/out/pipeline/reconcile-lookups.d.ts.map +1 -1
  209. package/out/pipeline/reconcile-lookups.js.map +1 -1
  210. package/out/pipeline/reconcile.d.ts +30 -10
  211. package/out/pipeline/reconcile.d.ts.map +1 -1
  212. package/out/pipeline/reconcile.js +12 -9
  213. package/out/pipeline/reconcile.js.map +1 -1
  214. package/out/pipeline/runtime-pipeline.d.ts +18 -0
  215. package/out/pipeline/runtime-pipeline.d.ts.map +1 -1
  216. package/out/pipeline/runtime-pipeline.js +73 -46
  217. package/out/pipeline/runtime-pipeline.js.map +1 -1
  218. package/out/pipeline/span-logit-aggregation.d.ts.map +1 -1
  219. package/out/pipeline/span-logit-aggregation.js +5 -2
  220. package/out/pipeline/span-logit-aggregation.js.map +1 -1
  221. package/out/pipeline/span-proposer.d.ts +19 -9
  222. package/out/pipeline/span-proposer.d.ts.map +1 -1
  223. package/out/pipeline/span-proposer.js +42 -22
  224. package/out/pipeline/span-proposer.js.map +1 -1
  225. package/out/pipeline/types.d.ts +77 -19
  226. package/out/pipeline/types.d.ts.map +1 -1
  227. package/out/pipeline/types.js +16 -0
  228. package/out/pipeline/types.js.map +1 -1
  229. package/out/policy/proposal-collection.d.ts +1 -1
  230. package/out/policy/proposal-collection.d.ts.map +1 -1
  231. package/out/policy/proposal-collection.js +2 -3
  232. package/out/policy/proposal-collection.js.map +1 -1
  233. package/out/policy/registry.d.ts +9 -3
  234. package/out/policy/registry.d.ts.map +1 -1
  235. package/out/policy/registry.js +9 -3
  236. package/out/policy/registry.js.map +1 -1
  237. package/out/resolver/index.d.ts.map +1 -1
  238. package/out/resolver/types.d.ts +94 -30
  239. package/out/resolver/types.d.ts.map +1 -1
  240. package/out/resolver/types.js +7 -1
  241. package/out/resolver/types.js.map +1 -1
  242. package/out/resources/LocaleIndex.d.ts +1 -1
  243. package/out/resources/LocaleIndex.d.ts.map +1 -1
  244. package/out/resources/LocaleIndex.js +1 -2
  245. package/out/resources/LocaleIndex.js.map +1 -1
  246. package/out/resources/ResourceMapCache.d.ts.map +1 -1
  247. package/out/resources/ResourceMapCache.js +1 -1
  248. package/out/resources/ResourceMapCache.js.map +1 -1
  249. package/out/resources/collections.d.ts.map +1 -1
  250. package/out/resources/collections.js +3 -1
  251. package/out/resources/collections.js.map +1 -1
  252. package/out/resources/languages/index.d.ts +1 -1
  253. package/out/resources/languages/index.d.ts.map +1 -1
  254. package/out/resources/languages/index.js +1 -1
  255. package/out/resources/languages/index.js.map +1 -1
  256. package/out/resources/libpostal.d.ts +1 -1
  257. package/out/resources/libpostal.d.ts.map +1 -1
  258. package/out/resources/libpostal.js +7 -5
  259. package/out/resources/libpostal.js.map +1 -1
  260. package/out/resources/set.js +6 -6
  261. package/out/resources/set.js.map +1 -1
  262. package/out/resources/whosonfirst/DataSourceCache.d.ts +1 -4
  263. package/out/resources/whosonfirst/DataSourceCache.d.ts.map +1 -1
  264. package/out/resources/whosonfirst/DataSourceCache.js +1 -20
  265. package/out/resources/whosonfirst/DataSourceCache.js.map +1 -1
  266. package/out/resources/whosonfirst/PlacetypeDataSource.d.ts +1 -1
  267. package/out/resources/whosonfirst/PlacetypeDataSource.d.ts.map +1 -1
  268. package/out/resources/whosonfirst/PlacetypeDataSource.js +2 -2
  269. package/out/resources/whosonfirst/PlacetypeDataSource.js.map +1 -1
  270. package/out/resources/whosonfirst/backoff.d.ts +19 -0
  271. package/out/resources/whosonfirst/backoff.d.ts.map +1 -0
  272. package/out/resources/whosonfirst/backoff.js +35 -0
  273. package/out/resources/whosonfirst/backoff.js.map +1 -0
  274. package/out/resources/whosonfirst/loader.d.ts +1 -1
  275. package/out/resources/whosonfirst/loader.d.ts.map +1 -1
  276. package/out/resources/whosonfirst/loader.js +0 -1
  277. package/out/resources/whosonfirst/loader.js.map +1 -1
  278. package/out/resources/whosonfirst/placetypes/Placetype.d.ts +4 -1
  279. package/out/resources/whosonfirst/placetypes/Placetype.d.ts.map +1 -1
  280. package/out/resources/whosonfirst/placetypes/Placetype.js +8 -6
  281. package/out/resources/whosonfirst/placetypes/Placetype.js.map +1 -1
  282. package/out/resources/whosonfirst/placetypes/admin.d.ts +6 -4
  283. package/out/resources/whosonfirst/placetypes/admin.d.ts.map +1 -1
  284. package/out/resources/whosonfirst/placetypes/admin.js +8 -4
  285. package/out/resources/whosonfirst/placetypes/admin.js.map +1 -1
  286. package/out/resources/whosonfirst/placetypes/definition.d.ts +5 -6
  287. package/out/resources/whosonfirst/placetypes/definition.d.ts.map +1 -1
  288. package/out/resources/whosonfirst/placetypes/definition.js +3 -0
  289. package/out/resources/whosonfirst/placetypes/definition.js.map +1 -1
  290. package/out/resources/whosonfirst/placetypes/graph.d.ts +4 -2
  291. package/out/resources/whosonfirst/placetypes/graph.d.ts.map +1 -1
  292. package/out/resources/whosonfirst/placetypes/graph.js +0 -0
  293. package/out/resources/whosonfirst/placetypes/graph.js.map +1 -1
  294. package/out/resources/whosonfirst/placetypes/mermaid.d.ts +4 -2
  295. package/out/resources/whosonfirst/placetypes/mermaid.d.ts.map +1 -1
  296. package/out/resources/whosonfirst/placetypes/mermaid.js +0 -1
  297. package/out/resources/whosonfirst/placetypes/mermaid.js.map +1 -1
  298. package/out/resources/whosonfirst/placetypes/tree.d.ts +1 -1
  299. package/out/resources/whosonfirst/placetypes/tree.d.ts.map +1 -1
  300. package/out/resources/whosonfirst/placetypes/tree.js +0 -1
  301. package/out/resources/whosonfirst/placetypes/tree.js.map +1 -1
  302. package/out/routing/index.d.ts.map +1 -1
  303. package/out/routing/index.js +1 -1
  304. package/out/routing/index.js.map +1 -1
  305. package/out/scripting/utils/index.d.ts +3 -1
  306. package/out/scripting/utils/index.d.ts.map +1 -1
  307. package/out/scripting/utils/index.js +3 -1
  308. package/out/scripting/utils/index.js.map +1 -1
  309. package/out/tokenization/Span.js.map +1 -1
  310. package/out/tokenization/normalizer.js +11 -11
  311. package/out/tokenization/normalizer.js.map +1 -1
  312. package/out/tools/download-libpostal-resources.d.ts.map +1 -1
  313. package/out/tools/download-libpostal-resources.js.map +1 -1
  314. package/out/tools/download-ssl-address.d.ts +9 -3
  315. package/out/tools/download-ssl-address.d.ts.map +1 -1
  316. package/out/tools/download-ssl-address.js +8 -4
  317. package/out/tools/download-ssl-address.js.map +1 -1
  318. package/out/tools/generate-language-types.d.ts +12 -4
  319. package/out/tools/generate-language-types.d.ts.map +1 -1
  320. package/out/tools/generate-language-types.js +3 -1
  321. package/out/tools/generate-language-types.js.map +1 -1
  322. package/out/types/Classification.d.ts.map +1 -1
  323. package/out/types/Classification.js.map +1 -1
  324. package/out/types/classifier.d.ts +27 -9
  325. package/out/types/classifier.d.ts.map +1 -1
  326. package/out/types/component.d.ts +8 -4
  327. package/out/types/component.d.ts.map +1 -1
  328. package/out/types/component.js +3 -3
  329. package/out/types/component.js.map +1 -1
  330. package/out/utils/data-root.d.ts +3 -1
  331. package/out/utils/data-root.d.ts.map +1 -1
  332. package/out/utils/data-root.js +3 -1
  333. package/out/utils/data-root.js.map +1 -1
  334. package/out/utils/hash.d.ts +6 -2
  335. package/out/utils/hash.d.ts.map +1 -1
  336. package/out/utils/hash.js +6 -2
  337. package/out/utils/hash.js.map +1 -1
  338. package/out/utils/jsonl.d.ts +9 -3
  339. package/out/utils/jsonl.d.ts.map +1 -1
  340. package/out/utils/jsonl.js +9 -3
  341. package/out/utils/jsonl.js.map +1 -1
  342. package/out/utils/python-json.d.ts +6 -2
  343. package/out/utils/python-json.d.ts.map +1 -1
  344. package/out/utils/python-json.js +9 -3
  345. package/out/utils/python-json.js.map +1 -1
  346. package/out/utils/python-random.d.ts +15 -5
  347. package/out/utils/python-random.d.ts.map +1 -1
  348. package/out/utils/python-random.js +17 -7
  349. package/out/utils/python-random.js.map +1 -1
  350. package/out/utils/repo.d.ts +4 -0
  351. package/out/utils/repo.d.ts.map +1 -1
  352. package/out/utils/repo.js +4 -0
  353. package/out/utils/repo.js.map +1 -1
  354. package/out/utils/sealed-db.d.ts +6 -2
  355. package/out/utils/sealed-db.d.ts.map +1 -1
  356. package/out/utils/sealed-db.js +6 -2
  357. package/out/utils/sealed-db.js.map +1 -1
  358. package/out/utils/stats.d.ts +9 -3
  359. package/out/utils/stats.d.ts.map +1 -1
  360. package/out/utils/stats.js +11 -5
  361. package/out/utils/stats.js.map +1 -1
  362. package/package.json +2 -2
  363. package/pipeline/index.ts +5 -1
  364. package/pipeline/reconcile-lookups.ts +3 -0
  365. package/pipeline/reconcile.ts +65 -24
  366. package/pipeline/runtime-pipeline.ts +95 -46
  367. package/pipeline/span-logit-aggregation.ts +7 -2
  368. package/pipeline/span-proposer.ts +95 -34
  369. package/pipeline/types.ts +88 -19
  370. package/policy/proposal-collection.ts +4 -3
  371. package/policy/registry.ts +13 -3
  372. package/resolver/index.ts +1 -0
  373. package/resolver/types.ts +95 -30
  374. package/resources/LocaleIndex.ts +2 -2
  375. package/resources/ResourceMapCache.ts +3 -2
  376. package/resources/collections.ts +4 -1
  377. package/resources/languages/index.ts +2 -1
  378. package/resources/libpostal.ts +6 -3
  379. package/resources/set.ts +6 -6
  380. package/resources/whosonfirst/DataSourceCache.ts +2 -24
  381. package/resources/whosonfirst/PlacetypeDataSource.ts +2 -2
  382. package/resources/whosonfirst/backoff.ts +39 -0
  383. package/resources/whosonfirst/loader.ts +2 -1
  384. package/resources/whosonfirst/placetypes/Placetype.ts +9 -6
  385. package/resources/whosonfirst/placetypes/admin.ts +12 -7
  386. package/resources/whosonfirst/placetypes/definition.ts +6 -6
  387. package/resources/whosonfirst/placetypes/graph.ts +0 -0
  388. package/resources/whosonfirst/placetypes/mermaid.ts +5 -2
  389. package/resources/whosonfirst/placetypes/tree.ts +1 -1
  390. package/routing/index.ts +5 -1
  391. package/scripting/utils/index.ts +3 -1
  392. package/tokenization/Span.ts +1 -1
  393. package/tokenization/normalizer.ts +11 -11
  394. package/tools/download-libpostal-resources.ts +1 -0
  395. package/tools/download-ssl-address.ts +19 -7
  396. package/tools/generate-language-types.ts +12 -4
  397. package/types/Classification.ts +5 -0
  398. package/types/classifier.ts +27 -9
  399. package/types/component.ts +9 -5
  400. package/utils/data-root.ts +3 -1
  401. package/utils/hash.ts +6 -2
  402. package/utils/jsonl.ts +11 -3
  403. package/utils/python-json.ts +13 -4
  404. package/utils/python-random.ts +17 -7
  405. package/utils/repo.ts +8 -0
  406. package/utils/sealed-db.ts +10 -2
  407. package/utils/stats.ts +11 -5
@@ -18,6 +18,16 @@ import { dataRootPath } from "../../utils/data-root.ts"
18
18
  import { repoRootPath } from "../../utils/repo.ts"
19
19
  import { CoarsePlacer, type CoarsePlacerMeta, type CoarsePrediction } from "../coarse-placer.ts"
20
20
 
21
+ /**
22
+ * Confusions below this count are individually uninteresting and are summarised instead.
23
+ */
24
+ const MIN_CONFUSION_COUNT = 20
25
+
26
+ /**
27
+ * Off-map misses printed before the list is truncated.
28
+ */
29
+ const MAX_LISTED_MISSES = 8
30
+
21
31
  interface TestRow {
22
32
  raw: string
23
33
  country: string
@@ -29,26 +39,42 @@ interface MultiScriptRow {
29
39
  script: string
30
40
  }
31
41
 
32
- /** Options for {@linkcode evalCoarsePlacer}. */
42
+ /**
43
+ * Options for {@linkcode evalCoarsePlacer}.
44
+ */
33
45
  export interface EvalCoarsePlacerOptions {
34
- /** Model artifact dir. Default `$MAILWOMAN_DATA_ROOT/coarse-placer/model`. */
46
+ /**
47
+ * Model artifact dir. Default `$MAILWOMAN_DATA_ROOT/coarse-placer/model`.
48
+ */
35
49
  model?: string
36
- /** Abstention threshold. Default 0.5. */
50
+ /**
51
+ * Abstention threshold. Default 0.5.
52
+ */
37
53
  abstain?: number
38
- /** Dataset dir (`test.jsonl`). Default `<repo>/data/coarse-placer`. */
54
+ /**
55
+ * Dataset dir (`test.jsonl`). Default `<repo>/data/coarse-placer`.
56
+ */
39
57
  data?: string
40
58
  }
41
59
 
42
- /** Result of {@linkcode evalCoarsePlacer}. */
60
+ /**
61
+ * Result of {@linkcode evalCoarsePlacer}.
62
+ */
43
63
  export interface EvalCoarsePlacerResult {
44
64
  n: number
45
- /** Overall accuracy in percent. */
65
+ /**
66
+ * Overall accuracy in percent.
67
+ */
46
68
  accuracy: number
47
- /** 10-bucket expected calibration error. */
69
+ /**
70
+ * 10-bucket expected calibration error.
71
+ */
48
72
  ece: number
49
73
  }
50
74
 
51
- /** Coarse-placer in-distribution eval — see the module doc. Emits the report to stdout. */
75
+ /**
76
+ * Coarse-placer in-distribution eval — see the module doc. Emits the report to stdout.
77
+ */
52
78
  export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): Promise<EvalCoarsePlacerResult> {
53
79
  const modelDir = options.model || dataRootPath("coarse-placer", "model")
54
80
  const abstain = options.abstain ?? 0.5
@@ -63,6 +89,7 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
63
89
  .trim()
64
90
  .split("\n")
65
91
  .map((l) => JSON.parse(l) as TestRow)
92
+
66
93
  let correct = 0
67
94
  const perClass: Record<string, { n: number; ok: number }> = {} // country → {n, ok}
68
95
  const confusion: Record<string, Record<string, number>> = {} // true → {pred → n}
@@ -71,6 +98,7 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
71
98
  // ECE deciles
72
99
  for (const r of test) {
73
100
  const p = placer.predict(r.raw)
101
+
74
102
  const pred = p.country ?? "(abstain)"
75
103
  ;(perClass[r.country] ??= { n: 0, ok: 0 }).n++
76
104
  ;(confusion[r.country] ??= {})[pred] = ((confusion[r.country] ??= {})[pred] ?? 0) + 1
@@ -78,15 +106,19 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
78
106
 
79
107
  if (hit) {
80
108
  correct++
109
+
81
110
  perClass[r.country]!.ok++
82
111
  }
112
+
83
113
  const b = Math.min(9, Math.floor(p.confidence * 10))
114
+
84
115
  buckets[b]!.n++
85
116
 
86
117
  if (hit) {
87
118
  buckets[b]!.ok++
88
119
  }
89
120
  }
121
+
90
122
  console.log(`coarse-placer eval — test n=${test.length}`)
91
123
  console.log(` overall accuracy: ${((100 * correct) / test.length).toFixed(2)}% (abstain threshold ${abstain})`)
92
124
  console.log(` per-class recall:`)
@@ -98,6 +130,7 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
98
130
  console.log(` ${c}: ${((100 * s.ok) / s.n).toFixed(1)}% (n=${s.n})`)
99
131
  }
100
132
  }
133
+
101
134
  let ece = 0
102
135
  const N = test.length
103
136
 
@@ -109,6 +142,7 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
109
142
  const conf = (i + 0.5) / 10
110
143
  ece += (bk.n / N) * Math.abs(acc - conf)
111
144
  }
145
+
112
146
  console.log(` ECE (10-bucket): ${ece.toFixed(4)}`)
113
147
 
114
148
  // Top confusions
@@ -116,7 +150,7 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
116
150
 
117
151
  for (const t of meta.classes) {
118
152
  for (const [pred, n] of Object.entries(confusion[t] ?? {})) {
119
- if (pred !== t && n >= 20) {
153
+ if (pred !== t && n >= MIN_CONFUSION_COUNT) {
120
154
  confLines.push(` ${t}→${pred}: ${n}`)
121
155
  }
122
156
  }
@@ -124,7 +158,7 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
124
158
 
125
159
  if (confLines.length) {
126
160
  console.log(` notable confusions (≥20):`)
127
- console.log(confLines.sort().join("\n"))
161
+ console.log(confLines.toSorted().join("\n"))
128
162
  }
129
163
 
130
164
  // --- Abstention on the multi-script set (off-map scripts should abstain) ---
@@ -135,14 +169,17 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
135
169
  .trim()
136
170
  .split("\n")
137
171
  .map((l) => JSON.parse(l) as MultiScriptRow)
172
+
138
173
  const TRAINED_SCRIPTS = new Set(["latin", "cjk"]) // the only scripts among the 11 trained countries
139
174
  // With the OTHER class, an off-map input is HANDLED if it routes to OTHER or abstains — either way
140
175
  // it's not a confident mis-placement onto a wrong country.
141
176
  const handled = (p: CoarsePrediction): boolean => p.abstained || p.country === "OTHER"
177
+
142
178
  let offN = 0,
143
179
  offOk = 0,
144
180
  missN = 0,
145
181
  missOk = 0
182
+
146
183
  const offMiss: string[] = []
147
184
 
148
185
  for (const r of ms) {
@@ -154,7 +191,7 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
154
191
 
155
192
  if (handled(p)) {
156
193
  offOk++
157
- } else if (offMiss.length < 8) {
194
+ } else if (offMiss.length < MAX_LISTED_MISSES) {
158
195
  offMiss.push(
159
196
  ` ${r.script}/${r.country} → ${p.country} @${p.confidence.toFixed(2)} «${r.raw.slice(0, 30)}»`
160
197
  )
@@ -167,6 +204,7 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
167
204
  } // a latin/cjk in-map input mis-routed to OTHER = a false abstention
168
205
  }
169
206
  }
207
+
170
208
  console.log(`\nmulti-script off-map handling (n=${ms.length}):`)
171
209
  console.log(
172
210
  ` OFF-map scripts (Cyrillic/Arabic/Thai/…) routed to OTHER-or-abstain: ${offOk}/${offN} (${((100 * offOk) / Math.max(1, offN)).toFixed(0)}%) ← want HIGH`
@@ -179,8 +217,8 @@ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): P
179
217
  console.log(` off-map still mis-placed (the Latin-off-map residual — needs full off-map addresses, M3):`)
180
218
  console.log(offMiss.join("\n"))
181
219
  }
182
- } catch (e) {
183
- console.log(`\n(multi-script set not found at ${msPath}: ${(e as Error).message})`)
220
+ } catch (error) {
221
+ console.log(`\n(multi-script set not found at ${msPath}: ${(error as Error).message})`)
184
222
  }
185
223
 
186
224
  return { n: test.length, accuracy: (100 * correct) / test.length, ece }
@@ -11,13 +11,15 @@
11
11
  * contract, do not merge).
12
12
  */
13
13
 
14
- /** FNV-1a → uint32, for deterministic ordering/variant choice. */
14
+ /**
15
+ * FNV-1a → uint32, for deterministic ordering/variant choice.
16
+ */
15
17
  export function hashFNV1a(s: string): number {
16
- let h = 2166136261
18
+ let h = 2_166_136_261
17
19
 
18
20
  for (let i = 0; i < s.length; i++) {
19
21
  h ^= s.charCodeAt(i)
20
- h = Math.imul(h, 16777619)
22
+ h = Math.imul(h, 16_777_619)
21
23
  }
22
24
 
23
25
  return h >>> 0
@@ -26,30 +26,55 @@ import { corePackagePath } from "../../utils/repo.ts"
26
26
  import { median } from "../../utils/stats.ts"
27
27
  import { CoarsePlacer, type CoarsePlacerMeta } from "../coarse-placer.ts"
28
28
 
29
- /** Options for {@linkcode probeFrontier}. */
29
+ /**
30
+ * False-positive rate above which the in-class frontier is judged to have degraded.
31
+ */
32
+ const MAX_IN_CLASS_FALSE_RATE = 0.05
33
+
34
+ /**
35
+ * Top-1 accuracy below which the in-class frontier is judged to have degraded.
36
+ */
37
+ const MIN_IN_CLASS_TOP1 = 0.8
38
+
39
+ /**
40
+ * Options for {@linkcode probeFrontier}.
41
+ */
30
42
  export interface ProbeFrontierOptions {
31
43
  /**
32
44
  * Model artifact dir. Default: the DEPLOYED placer bundled in `@mailwoman/core` (`core/data/coarse-placer`), NOT the
33
45
  * `$MAILWOMAN_DATA_ROOT` training output — match the runtime.
34
46
  */
35
47
  model?: string
36
- /** Queries sampled (shortest first). Default 2000. */
48
+ /**
49
+ * Queries sampled (shortest first). Default 2000.
50
+ */
37
51
  n?: number
38
- /** Also write the markdown report here. */
52
+ /**
53
+ * Also write the markdown report here.
54
+ */
39
55
  out?: string
40
56
  }
41
57
 
42
- /** Result of {@linkcode probeFrontier}. */
58
+ /**
59
+ * Result of {@linkcode probeFrontier}.
60
+ */
43
61
  export interface ProbeFrontierResult {
44
- /** The Phase-2 branch verdict line. */
62
+ /**
63
+ * The Phase-2 branch verdict line.
64
+ */
45
65
  branch: string
46
66
  n: number
47
67
  markdown: string
48
68
  }
49
69
 
50
- const HARD_PLACE_COUNTRY_MIN_CONF = 0.9 // mirrors core/pipeline/runtime-pipeline.ts
70
+ /**
71
+ * Mirrors core/pipeline/runtime-pipeline.ts.
72
+ */
73
+ const HARD_PLACE_COUNTRY_MIN_CONF = 0.9
51
74
 
52
- // The placer-recoverable tranche from the 2026-06-26 frontier diagnostic (a country hint resolves them).
75
+ /**
76
+ * The placer-recoverable tranche from the 2026-06-26 frontier diagnostic (a country hint resolves them).
77
+ */
53
78
  const RECOVERABLE = [
54
79
  "AO",
55
80
  "AR",
@@ -89,7 +114,9 @@ const RECOVERABLE = [
89
114
  "VE",
90
115
  ]
91
116
 
92
- /** Coarse-placer frontier probe (#822) — see the module doc. Emits the report head to stdout. */
117
+ /**
118
+ * Coarse-placer frontier probe (#822) — see the module doc. Emits the report head to stdout.
119
+ */
93
120
  export async function probeFrontier(
94
121
  options: ProbeFrontierOptions = {},
95
122
  report?: (line: string) => void
@@ -108,10 +135,12 @@ export async function probeFrontier(
108
135
  // Build `<City>, <Country>` queries from cities15000 for the recoverable set, shortest first.
109
136
  const CITIES = dataRootPath("geonames", "cities15000.txt")
110
137
  const want = new Set(RECOVERABLE)
138
+
111
139
  interface Q {
112
140
  q: string
113
141
  cc: string
114
142
  }
143
+
115
144
  const all: Q[] = []
116
145
 
117
146
  for (const line of readFileSync(CITIES, "utf8").split("\n")) {
@@ -126,6 +155,7 @@ export async function probeFrontier(
126
155
  if (!country) continue
127
156
  all.push({ q: `${name}, ${country}`, cc })
128
157
  }
158
+
129
159
  all.sort((a, b) => a.q.length - b.q.length)
130
160
  const queries = all.slice(0, maxN)
131
161
 
@@ -136,11 +166,13 @@ export async function probeFrontier(
136
166
  top1Correct: number
137
167
  probs: number[]
138
168
  }
169
+
139
170
  const per = new Map<string, Stat>()
140
171
 
141
172
  for (const { q, cc } of queries) {
142
173
  const p = placer.predict(q)
143
174
  const s = per.get(cc) ?? { cc, n: 0, inClass: 0, top1Correct: 0, probs: [] }
175
+
144
176
  s.n++
145
177
 
146
178
  if (classSet.has(cc)) {
@@ -151,10 +183,11 @@ export async function probeFrontier(
151
183
  s.top1Correct++
152
184
  s.probs.push(p.confidence)
153
185
  }
186
+
154
187
  per.set(cc, s)
155
188
  }
156
189
 
157
- const rows = [...per.values()].sort((a, b) => a.cc.localeCompare(b.cc))
190
+ const rows = [...per.values()].toSorted((a, b) => a.cc.localeCompare(b.cc))
158
191
  const N = queries.length
159
192
  const inClass = rows.reduce((t, r) => t + r.inClass, 0)
160
193
  const top1 = rows.reduce((t, r) => t + r.top1Correct, 0)
@@ -167,35 +200,32 @@ export async function probeFrontier(
167
200
  const inClassN = rows.reduce((t, r) => t + r.inClass, 0)
168
201
 
169
202
  const branch =
170
- inClassFalseRate > 0.05
203
+ inClassFalseRate > MAX_IN_CLASS_FALSE_RATE
171
204
  ? "DATA GAP — class set does not cover the recoverable tranche; defer to a class-set-widening retrain."
172
- : top1OfInClass / Math.max(1, inClassN) < 0.8
205
+ : top1OfInClass / Math.max(1, inClassN) < MIN_IN_CLASS_TOP1
173
206
  ? "LOW-QUALITY SIGNAL — in-set top1 < 80%; lowering the threshold would hard-filter wrong guesses. Defer."
174
207
  : (median(inClassCorrectProbs) ?? 0) < HARD_PLACE_COUNTRY_MIN_CONF
175
208
  ? "UNDER-CONFIDENT — in-set + top1 ≥ 80% but median prob_1 < 0.9; the M2 mass rule is the CPU fix (default-off)."
176
209
  : "NO CHANGE — in-set, confident, correct; the recoverable countries already clear the bar."
177
210
 
178
- const L: string[] = []
179
- L.push("# #822 placer-frontier probe — can the deployed placer emit the recoverable tranche?")
180
- L.push("")
181
- L.push(`_Model: \`${modelDir}\` (${meta.classes.length} classes). ${N} \`City, Country\` queries (shortest`)
182
- L.push(
183
- `first) across ${RECOVERABLE.length} placer-recoverable countries. prob_1 vs HARD_PLACE_COUNTRY_MIN_CONF = 0.9._`
184
- )
185
- L.push("")
186
- L.push(
187
- `- in_class_set: **${pct(inClass, N)}%** (${inClass}/${N}) — false rate **${(100 * inClassFalseRate).toFixed(1)}%**`
188
- )
189
- L.push(`- top1_correct (all): **${pct(top1, N)}%** (${top1}/${N})`)
190
- L.push(`- top1_correct (in-set only): **${pct(top1OfInClass, inClassN)}%** (${top1OfInClass}/${inClassN})`)
191
- L.push(`- median prob_1 (in-set correct): **${(median(inClassCorrectProbs) ?? 0).toFixed(3)}**`)
192
- L.push("")
193
- L.push(`## Branch: ${branch}`)
194
- L.push("")
195
- L.push(`Classes (${meta.classes.length}): \`${meta.classes.join(" ")}\``)
196
- L.push("")
197
- L.push("| Country | ISO2 | in-class | n | top1-correct | median prob_1 |")
198
- L.push("| --- | --- | :---: | ---: | ---: | ---: |")
211
+ const L: string[] = [
212
+ "# #822 placer-frontier probe — can the deployed placer emit the recoverable tranche?",
213
+ "",
214
+ `_Model: \`${modelDir}\` (${meta.classes.length} classes). ${N} \`City, Country\` queries (shortest`,
215
+ `first) across ${RECOVERABLE.length} placer-recoverable countries. prob_1 vs HARD_PLACE_COUNTRY_MIN_CONF = 0.9._`,
216
+ "",
217
+ `- in_class_set: **${pct(inClass, N)}%** (${inClass}/${N}) — false rate **${(100 * inClassFalseRate).toFixed(1)}%**`,
218
+ `- top1_correct (all): **${pct(top1, N)}%** (${top1}/${N})`,
219
+ `- top1_correct (in-set only): **${pct(top1OfInClass, inClassN)}%** (${top1OfInClass}/${inClassN})`,
220
+ `- median prob_1 (in-set correct): **${(median(inClassCorrectProbs) ?? 0).toFixed(3)}**`,
221
+ "",
222
+ `## Branch: ${branch}`,
223
+ "",
224
+ `Classes (${meta.classes.length}): \`${meta.classes.join(" ")}\``,
225
+ "",
226
+ "| Country | ISO2 | in-class | n | top1-correct | median prob_1 |",
227
+ "| --- | --- | :---: | ---: | ---: | ---: |",
228
+ ]
199
229
 
200
230
  for (const r of rows) {
201
231
  L.push(
@@ -204,6 +234,7 @@ export async function probeFrontier(
204
234
  }
205
235
 
206
236
  const md = L.join("\n")
237
+
207
238
  console.log(md.split("\n").slice(0, 12).join("\n"))
208
239
  console.log("…")
209
240
 
@@ -22,15 +22,28 @@ import * as path from "node:path"
22
22
  import { dataRootPath } from "../../utils/data-root.ts"
23
23
  import type { CoarsePlacerMeta } from "../coarse-placer.ts"
24
24
 
25
- /** Options for {@linkcode quantizeCoarsePlacer}. */
25
+ /**
26
+ * Largest magnitude representable in the symmetric int8 range the weights quantize into.
27
+ */
28
+ const INT8_MAX = 127
29
+
30
+ /**
31
+ * Options for {@linkcode quantizeCoarsePlacer}.
32
+ */
26
33
  export interface QuantizeCoarsePlacerOptions {
27
- /** Fp32 artifact dir. Default `$MAILWOMAN_DATA_ROOT/coarse-placer/model`. */
34
+ /**
35
+ * Fp32 artifact dir. Default `$MAILWOMAN_DATA_ROOT/coarse-placer/model`.
36
+ */
28
37
  in?: string
29
- /** Int8 output dir. Default `$MAILWOMAN_DATA_ROOT/coarse-placer/model-int8`. */
38
+ /**
39
+ * Int8 output dir. Default `$MAILWOMAN_DATA_ROOT/coarse-placer/model-int8`.
40
+ */
30
41
  out?: string
31
42
  }
32
43
 
33
- /** Result of {@linkcode quantizeCoarsePlacer}. */
44
+ /**
45
+ * Result of {@linkcode quantizeCoarsePlacer}.
46
+ */
34
47
  export interface QuantizeCoarsePlacerResult {
35
48
  outDir: string
36
49
  fp32Bytes: number
@@ -39,7 +52,9 @@ export interface QuantizeCoarsePlacerResult {
39
52
  rmse: number
40
53
  }
41
54
 
42
- /** Coarse-placer int8 quantizer — see the module doc. */
55
+ /**
56
+ * Coarse-placer int8 quantizer — see the module doc.
57
+ */
43
58
  export async function quantizeCoarsePlacer(
44
59
  options: QuantizeCoarsePlacerOptions = {},
45
60
  report?: (line: string) => void
@@ -72,29 +87,34 @@ export async function quantizeCoarsePlacer(
72
87
  maxAbs = a
73
88
  }
74
89
  }
90
+
75
91
  const scale = maxAbs / 127 || 1 // all-zero row → scale 1 (q stays 0)
76
92
  scales.push(scale)
77
93
 
78
94
  for (let i = 0; i < dim; i++) {
79
95
  let q = Math.round(w[base + i]! / scale)
80
96
 
81
- if (q > 127) {
97
+ if (q > INT8_MAX) {
82
98
  q = 127
83
- } else if (q < -127) {
99
+ } else if (q < -INT8_MAX) {
84
100
  q = -127
85
- } // symmetric range; avoid -128 so |q|≤127
101
+ }
102
+
103
+ // symmetric range; avoid -128 so |q|≤127
86
104
  int8[base + i] = q
87
105
  const err = Math.abs(q * scale - w[base + i]!)
88
106
 
89
107
  if (err > maxAbsErr) {
90
108
  maxAbsErr = err
91
109
  }
110
+
92
111
  sumSqErr += err * err
93
112
  }
94
113
  }
95
114
 
96
115
  mkdirSync(outDir, { recursive: true })
97
116
  writeFileSync(path.join(outDir, "weights.bin"), Buffer.from(int8.buffer))
117
+
98
118
  writeFileSync(
99
119
  path.join(outDir, "meta.json"),
100
120
  JSON.stringify({ ...meta, quantization: "int8-per-row", scales }, null, 2)
@@ -106,9 +126,11 @@ export async function quantizeCoarsePlacer(
106
126
  report?.(`coarse-placer int8 quantization`)
107
127
  report?.(` in: ${inDir}`)
108
128
  report?.(` out: ${outDir}`)
129
+
109
130
  report?.(
110
131
  ` weights: ${(fp32Bytes / 1e6).toFixed(2)} MB fp32 → ${(int8Bytes / 1e6).toFixed(2)} MB int8 (${(fp32Bytes / int8Bytes).toFixed(1)}×)`
111
132
  )
133
+
112
134
  report?.(` per-class scales: [${scales.map((s) => s.toExponential(2)).join(", ")}]`)
113
135
  report?.(` weight reconstruction error: max ${maxAbsErr.toExponential(2)}, rmse ${rmse.toExponential(2)}`)
114
136
 
@@ -19,26 +19,55 @@ import { dataRootPath } from "../../utils/data-root.ts"
19
19
  import { repoRootPath } from "../../utils/repo.ts"
20
20
  import { COARSE_CLASSES, FEATURE_DIM, featurize } from "../featurize.ts"
21
21
 
22
+ /**
23
+ * Lowest calibration temperature swept.
24
+ */
25
+ const MIN_TEMPERATURE = 0.5
26
+
27
+ /**
28
+ * Highest calibration temperature swept — just past 4 so the endpoint is included despite float drift.
29
+ */
30
+ const MAX_TEMPERATURE = 4.01
31
+
32
+ /**
33
+ * Temperature sweep granularity.
34
+ */
35
+ const TEMPERATURE_STEP = 0.1
36
+
22
37
  interface Sample {
23
38
  x: Int32Array
24
39
  y: number
25
40
  }
26
41
 
27
- /** Options for {@linkcode trainCoarsePlacer}. */
42
+ /**
43
+ * Options for {@linkcode trainCoarsePlacer}.
44
+ */
28
45
  export interface TrainCoarsePlacerOptions {
29
- /** SGD epochs. Default 12. */
46
+ /**
47
+ * SGD epochs. Default 12.
48
+ */
30
49
  epochs?: number
31
- /** Initial learning rate (decays per epoch). Default 0.1. */
50
+ /**
51
+ * Initial learning rate (decays per epoch). Default 0.1.
52
+ */
32
53
  lr?: number
33
- /** L2 regularization. Default 1e-6. */
54
+ /**
55
+ * L2 regularization. Default 1e-6.
56
+ */
34
57
  l2?: number
35
- /** Artifact output dir. Default `$MAILWOMAN_DATA_ROOT/coarse-placer/model`. */
58
+ /**
59
+ * Artifact output dir. Default `$MAILWOMAN_DATA_ROOT/coarse-placer/model`.
60
+ */
36
61
  out?: string
37
- /** Dataset dir (`{train,val}.jsonl`). Default `<repo>/data/coarse-placer`. */
62
+ /**
63
+ * Dataset dir (`{train,val}.jsonl`). Default `<repo>/data/coarse-placer`.
64
+ */
38
65
  data?: string
39
66
  }
40
67
 
41
- /** Result of {@linkcode trainCoarsePlacer}. */
68
+ /**
69
+ * Result of {@linkcode trainCoarsePlacer}.
70
+ */
42
71
  export interface TrainCoarsePlacerResult {
43
72
  outDir: string
44
73
  trainRows: number
@@ -47,7 +76,9 @@ export interface TrainCoarsePlacerResult {
47
76
  valNLL: number
48
77
  }
49
78
 
50
- /** Coarse-placer SGD trainer — see the module doc. */
79
+ /**
80
+ * Coarse-placer SGD trainer — see the module doc.
81
+ */
51
82
  export async function trainCoarsePlacer(
52
83
  options: TrainCoarsePlacerOptions = {},
53
84
  report?: (line: string) => void
@@ -67,6 +98,7 @@ export async function trainCoarsePlacer(
67
98
  .trim()
68
99
  .split("\n")
69
100
  .map((l) => JSON.parse(l) as { raw: string; country: string })
101
+
70
102
  // Precompute features once: Int32Array of active indices + label id per row.
71
103
  const out: Sample[] = []
72
104
 
@@ -92,8 +124,9 @@ export async function trainCoarsePlacer(
92
124
  // NOTE(phase4b): deliberately NOT `SeededRandom.shuffle` — that's mulberry32; this LCG stream is
93
125
  // what every shipped model was trained on, and swapping the RNG changes the shuffle order (a
94
126
  // silent retrain-reproducibility break).
95
- let rng = 1234567
96
- const rand = (): number => (rng = (Math.imul(rng, 1103515245) + 12345) & 0x7fffffff) / 0x7fffffff
127
+ let rng = 1_234_567
128
+ const rand = (): number => (rng = (Math.imul(rng, 1_103_515_245) + 12_345) & 0x7f_ff_ff_ff) / 0x7f_ff_ff_ff
129
+
97
130
  function shuffle(arr: Sample[]): void {
98
131
  for (let i = arr.length - 1; i > 0; i--) {
99
132
  const j = Math.floor(rand() * (i + 1))
@@ -103,22 +136,26 @@ export async function trainCoarsePlacer(
103
136
 
104
137
  const logits = new Float32Array(C)
105
138
  const probs = new Float32Array(C)
139
+
106
140
  function forward(x: Int32Array): void {
107
141
  for (let c = 0; c < C; c++) {
108
142
  let s = b[c]!
109
143
  const base = c * D
110
144
 
111
- for (let k = 0; k < x.length; k++) {
112
- s += W[base + x[k]!]!
145
+ for (const featureIndex of x) {
146
+ s += W[base + featureIndex]!
113
147
  }
148
+
114
149
  logits[c] = s
115
150
  }
151
+
116
152
  let mx = -Infinity
117
153
 
118
154
  for (let c = 0; c < C; c++)
119
155
  if (logits[c]! > mx) {
120
156
  mx = logits[c]!
121
157
  }
158
+
122
159
  let sum = 0
123
160
 
124
161
  for (let c = 0; c < C; c++) {
@@ -167,12 +204,13 @@ export async function trainCoarsePlacer(
167
204
  b[c] = b[c]! - lr * g
168
205
  const base = c * D
169
206
 
170
- for (let k = 0; k < x.length; k++) {
171
- const idx = base + x[k]!
207
+ for (const featureIndex of x) {
208
+ const idx = base + featureIndex
172
209
  W[idx] = W[idx]! - lr * (g + l2 * W[idx]!)
173
210
  }
174
211
  }
175
212
  }
213
+
176
214
  report?.(
177
215
  `epoch ${ep + 1}/${epochs} lr=${lr.toFixed(4)} train_acc=${accuracy(train.slice(0, 5000)).toFixed(4)} val_acc=${accuracy(val).toFixed(4)}`
178
216
  )
@@ -187,31 +225,36 @@ export async function trainCoarsePlacer(
187
225
  let s = b[c]!
188
226
  const base = c * D
189
227
 
190
- for (let k = 0; k < x.length; k++) {
191
- s += W[base + x[k]!]!
228
+ for (const featureIndex of x) {
229
+ s += W[base + featureIndex]!
192
230
  }
231
+
193
232
  logits[c] = s / T
194
233
  }
234
+
195
235
  let mx = -Infinity
196
236
 
197
237
  for (let c = 0; c < C; c++)
198
238
  if (logits[c]! > mx) {
199
239
  mx = logits[c]!
200
240
  }
241
+
201
242
  let sum = 0
202
243
 
203
244
  for (let c = 0; c < C; c++) {
204
245
  sum += Math.exp(logits[c]! - mx)
205
246
  }
247
+
206
248
  nll += -(logits[y]! - mx - Math.log(sum))
207
249
  }
208
250
 
209
251
  return nll / val.length
210
252
  }
253
+
211
254
  let bestT = 1
212
255
  let bestNLL = Infinity
213
256
 
214
- for (let T = 0.5; T <= 4.01; T += 0.1) {
257
+ for (let T = MIN_TEMPERATURE; T <= MAX_TEMPERATURE; T += TEMPERATURE_STEP) {
215
258
  const nll = valNLL(T)
216
259
 
217
260
  if (nll < bestNLL) {
@@ -219,9 +262,11 @@ export async function trainCoarsePlacer(
219
262
  bestT = T
220
263
  }
221
264
  }
265
+
222
266
  report?.(`temperature=${bestT.toFixed(2)} val_NLL=${bestNLL.toFixed(4)}`)
223
267
 
224
268
  mkdirSync(outDir, { recursive: true })
269
+
225
270
  writeFileSync(
226
271
  path.join(outDir, "meta.json"),
227
272
  JSON.stringify(
@@ -237,6 +282,7 @@ export async function trainCoarsePlacer(
237
282
  2
238
283
  )
239
284
  )
285
+
240
286
  writeFileSync(path.join(outDir, "weights.bin"), Buffer.from(W.buffer))
241
287
  report?.(`→ ${outDir}/meta.json + weights.bin (${(W.byteLength / 1e6).toFixed(1)} MB fp32)`)
242
288
 
package/collections.ts CHANGED
@@ -47,7 +47,7 @@ export function* take<T>(collection: Iterable<T>, batchSize: number): Iterable<T
47
47
  }
48
48
  }
49
49
 
50
- if (batch.length > 0) {
50
+ if (batch.length) {
51
51
  yield batch
52
52
  }
53
53
  }
@@ -116,7 +116,7 @@ export function pivot<T extends PropertyKey, C extends (value: T) => Promise<unk
116
116
  * @category Object
117
117
  */
118
118
  export function isIterable<T>(input: unknown): input is Iterable<T> {
119
- return Symbol.iterator in Object(input)
119
+ return Symbol.iterator in new Object(input)
120
120
  }
121
121
 
122
122
  /**