@mailwoman/corpus 11.5.0 → 12.0.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 (144) hide show
  1. package/data/builds/v0.8.22-wofrank-overlay/OVERLAY_PLAN.json +51 -0
  2. package/data/builds/v0.8.24-everyplace/inputs.json +35 -0
  3. package/data/training-configs/v8.17.0-stage1-gazetteer-v0822-s42.yaml +557 -0
  4. package/data/training-configs/v8.17.0-stage2-corpus-v0822-s42.yaml +1008 -0
  5. package/data/training-configs/v8.18.0-gazetteer-then-mixture-v0822-s42.yaml +1225 -0
  6. package/data/training-configs/v8.20.0-wofrank-v0822-s42.yaml +863 -0
  7. package/data/training-configs/v8.21.0-outcomes-v0822-s42.yaml +873 -0
  8. package/data/training-configs/v8.22.0-stage1-everyplace-v0824-s42.yaml +374 -0
  9. package/data/training-configs/v8.22.0-stage2-corpus-v0824-s42.yaml +808 -0
  10. package/data/training-configs/v8.22.1-stage1-everyplace-v0824-s42.yaml +376 -0
  11. package/data/training-configs/v8.22.1-stage2-corpus-v0824-s42.yaml +793 -0
  12. package/data/training-configs/v9.0.0-bytestem-v090-s42.yaml +665 -0
  13. package/data/training-manifests/v0.8.22-wofrank-overlay.json +9000 -0
  14. package/data/training-manifests/v0.8.24-everyplace-overlay.json +9000 -0
  15. package/data/training-manifests/v0.9.0-compact.effective.json +2556 -0
  16. package/data/training-manifests/v0.9.0-compact.json +9000 -0
  17. package/lib/adapters/wof/admin/json/adapter.ts +38 -3
  18. package/lib/adapters/wof/json-rows.ts +84 -5
  19. package/lib/adapters/wof/sample.ts +42 -6
  20. package/lib/build/code-hash.ts +1 -1
  21. package/lib/cjk/foreign-places.ts +1 -1
  22. package/lib/kr/adapters/localdata/permit-rows.ts +1 -1
  23. package/lib/parquet/schema.ts +7 -0
  24. package/lib/tools/anthropic/batches.ts +221 -0
  25. package/lib/tools/anthropic/labeling.ts +263 -0
  26. package/lib/tools/compact-v9.ts +872 -0
  27. package/lib/tools/fetch/wikidata/vital-places/entities.ts +20 -2
  28. package/lib/tools/fetch/wikidata/vital-places/qrank.ts +5 -4
  29. package/lib/tools/fragment-assay.run.ts +2 -1
  30. package/lib/tools/name-roles/name-roles.run.ts +296 -0
  31. package/lib/tools/name-roles/prompt.ts +253 -0
  32. package/lib/tools/overlay/deletions.ts +1 -1
  33. package/lib/tools/overlay/draw-weight.ts +275 -0
  34. package/lib/tools/place-twins/place-twins.run.ts +528 -0
  35. package/lib/tools/place-twins/prompt.ts +276 -0
  36. package/lib/tools/prominent-shapes/prominent-shapes.run.ts +420 -0
  37. package/lib/tools/prominent-shapes/prompt.ts +189 -0
  38. package/lib/tools/prominent-shapes/read-seeds.ts +286 -0
  39. package/lib/tools/prominent-shapes/seeds.ts +281 -0
  40. package/lib/tools/prominent-shapes/validate.ts +563 -0
  41. package/lib/training/config/admission.ts +9 -2
  42. package/lib/training/config/schema.ts +68 -1
  43. package/lib/types.ts +23 -0
  44. package/lib/utils/split.ts +1 -1
  45. package/out/adapters/wof/admin/json/adapter.d.ts +7 -0
  46. package/out/adapters/wof/admin/json/adapter.d.ts.map +1 -1
  47. package/out/adapters/wof/admin/json/adapter.js +28 -3
  48. package/out/adapters/wof/admin/json/adapter.js.map +1 -1
  49. package/out/adapters/wof/json-rows.d.ts +8 -0
  50. package/out/adapters/wof/json-rows.d.ts.map +1 -1
  51. package/out/adapters/wof/json-rows.js +56 -4
  52. package/out/adapters/wof/json-rows.js.map +1 -1
  53. package/out/adapters/wof/sample.d.ts +12 -0
  54. package/out/adapters/wof/sample.d.ts.map +1 -1
  55. package/out/adapters/wof/sample.js +37 -6
  56. package/out/adapters/wof/sample.js.map +1 -1
  57. package/out/build/code-hash.js +1 -1
  58. package/out/build/code-hash.js.map +1 -1
  59. package/out/cjk/foreign-places.js +1 -1
  60. package/out/cjk/foreign-places.js.map +1 -1
  61. package/out/kr/adapters/localdata/permit-rows.js +1 -1
  62. package/out/kr/adapters/localdata/permit-rows.js.map +1 -1
  63. package/out/parquet/schema.d.ts +6 -0
  64. package/out/parquet/schema.d.ts.map +1 -1
  65. package/out/parquet/schema.js +6 -0
  66. package/out/parquet/schema.js.map +1 -1
  67. package/out/tools/anthropic/batches.d.ts +117 -0
  68. package/out/tools/anthropic/batches.d.ts.map +1 -0
  69. package/out/tools/anthropic/batches.js +141 -0
  70. package/out/tools/anthropic/batches.js.map +1 -0
  71. package/out/tools/anthropic/labeling.d.ts +97 -0
  72. package/out/tools/anthropic/labeling.d.ts.map +1 -0
  73. package/out/tools/anthropic/labeling.js +146 -0
  74. package/out/tools/anthropic/labeling.js.map +1 -0
  75. package/out/tools/compact-v9.d.ts +117 -0
  76. package/out/tools/compact-v9.d.ts.map +1 -0
  77. package/out/tools/compact-v9.js +494 -0
  78. package/out/tools/compact-v9.js.map +1 -0
  79. package/out/tools/fetch/wikidata/vital-places/entities.d.ts +3 -0
  80. package/out/tools/fetch/wikidata/vital-places/entities.d.ts.map +1 -1
  81. package/out/tools/fetch/wikidata/vital-places/entities.js +19 -1
  82. package/out/tools/fetch/wikidata/vital-places/entities.js.map +1 -1
  83. package/out/tools/fetch/wikidata/vital-places/qrank.d.ts.map +1 -1
  84. package/out/tools/fetch/wikidata/vital-places/qrank.js +4 -4
  85. package/out/tools/fetch/wikidata/vital-places/qrank.js.map +1 -1
  86. package/out/tools/fragment-assay.run.js +1 -1
  87. package/out/tools/fragment-assay.run.js.map +1 -1
  88. package/out/tools/name-roles/name-roles.run.d.ts +2 -0
  89. package/out/tools/name-roles/name-roles.run.d.ts.map +1 -0
  90. package/out/tools/name-roles/name-roles.run.js +230 -0
  91. package/out/tools/name-roles/name-roles.run.js.map +1 -0
  92. package/out/tools/name-roles/prompt.d.ts +166 -0
  93. package/out/tools/name-roles/prompt.d.ts.map +1 -0
  94. package/out/tools/name-roles/prompt.js +176 -0
  95. package/out/tools/name-roles/prompt.js.map +1 -0
  96. package/out/tools/overlay/deletions.js +1 -1
  97. package/out/tools/overlay/deletions.js.map +1 -1
  98. package/out/tools/overlay/draw-weight.d.ts +86 -0
  99. package/out/tools/overlay/draw-weight.d.ts.map +1 -0
  100. package/out/tools/overlay/draw-weight.js +131 -0
  101. package/out/tools/overlay/draw-weight.js.map +1 -0
  102. package/out/tools/place-twins/place-twins.run.d.ts +2 -0
  103. package/out/tools/place-twins/place-twins.run.d.ts.map +1 -0
  104. package/out/tools/place-twins/place-twins.run.js +385 -0
  105. package/out/tools/place-twins/place-twins.run.js.map +1 -0
  106. package/out/tools/place-twins/prompt.d.ts +169 -0
  107. package/out/tools/place-twins/prompt.d.ts.map +1 -0
  108. package/out/tools/place-twins/prompt.js +183 -0
  109. package/out/tools/place-twins/prompt.js.map +1 -0
  110. package/out/tools/prominent-shapes/prominent-shapes.run.d.ts +2 -0
  111. package/out/tools/prominent-shapes/prominent-shapes.run.d.ts.map +1 -0
  112. package/out/tools/prominent-shapes/prominent-shapes.run.js +302 -0
  113. package/out/tools/prominent-shapes/prominent-shapes.run.js.map +1 -0
  114. package/out/tools/prominent-shapes/prompt.d.ts +74 -0
  115. package/out/tools/prominent-shapes/prompt.d.ts.map +1 -0
  116. package/out/tools/prominent-shapes/prompt.js +156 -0
  117. package/out/tools/prominent-shapes/prompt.js.map +1 -0
  118. package/out/tools/prominent-shapes/read-seeds.d.ts +23 -0
  119. package/out/tools/prominent-shapes/read-seeds.d.ts.map +1 -0
  120. package/out/tools/prominent-shapes/read-seeds.js +219 -0
  121. package/out/tools/prominent-shapes/read-seeds.js.map +1 -0
  122. package/out/tools/prominent-shapes/seeds.d.ts +132 -0
  123. package/out/tools/prominent-shapes/seeds.d.ts.map +1 -0
  124. package/out/tools/prominent-shapes/seeds.js +178 -0
  125. package/out/tools/prominent-shapes/seeds.js.map +1 -0
  126. package/out/tools/prominent-shapes/validate.d.ts +152 -0
  127. package/out/tools/prominent-shapes/validate.d.ts.map +1 -0
  128. package/out/tools/prominent-shapes/validate.js +389 -0
  129. package/out/tools/prominent-shapes/validate.js.map +1 -0
  130. package/out/training/config/admission.d.ts +2 -1
  131. package/out/training/config/admission.d.ts.map +1 -1
  132. package/out/training/config/admission.js +9 -2
  133. package/out/training/config/admission.js.map +1 -1
  134. package/out/training/config/schema.d.ts +276 -1
  135. package/out/training/config/schema.d.ts.map +1 -1
  136. package/out/training/config/schema.js +64 -1
  137. package/out/training/config/schema.js.map +1 -1
  138. package/out/types.d.ts +21 -0
  139. package/out/types.d.ts.map +1 -1
  140. package/out/types.js +13 -0
  141. package/out/types.js.map +1 -1
  142. package/out/utils/split.js +1 -1
  143. package/out/utils/split.js.map +1 -1
  144. package/package.json +24 -24
@@ -0,0 +1,563 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * @file Checks the query forms a language model wrote for a prominent place against the place's seed.
6
+ *
7
+ * A form is kept only when it cites surfaces the seed supplied, each cited surface is found in the
8
+ * form's text under the case and whitespace fold, and the text outside those spans is separators.
9
+ * A form that cites a slot letter in place of a numbered key is kept when one key of that slot passes.
10
+ * The last rule is what refuses a name the seed didn't supply: an alias, an exonym or a typo
11
+ * leaves letters outside every span.
12
+ * A refused form is dropped and counted under its reason.
13
+ */
14
+
15
+ import { tryParsingJSON } from "@mailwoman/core/values/json"
16
+
17
+ import { type SeedSurface, type ShapeSeed, SurfaceSlot } from "#tools/prominent-shapes/seeds"
18
+
19
+ /**
20
+ * One form as the model returns it: the text and the keys of the surfaces it contains.
21
+ */
22
+ export interface ReturnedForm {
23
+ raw: string
24
+ uses: string[]
25
+ }
26
+
27
+ /**
28
+ * The forms the model returned for one place.
29
+ */
30
+ export interface ReturnedPlace {
31
+ id: string
32
+ forms: ReturnedForm[]
33
+ }
34
+
35
+ /**
36
+ * The reasons a returned form is dropped.
37
+ */
38
+ export const FormDrop = {
39
+ /**
40
+ * The form cites a key the seed doesn't hold.
41
+ */
42
+ UnknownSurface: "unknown_surface_key",
43
+ /**
44
+ * The form cites a bare slot letter, and no choice of that slot's keys passes every other rule.
45
+ */
46
+ LetterUnresolved: "slot_letter_without_passing_key",
47
+ /**
48
+ * The form cites a bare slot letter, and more than one choice of that slot's keys passes every other rule.
49
+ */
50
+ LetterAmbiguous: "slot_letter_with_several_passing_keys",
51
+ /**
52
+ * The cited slots are a combination the label policy doesn't write.
53
+ */
54
+ SlotsNotAllowed: "slots_not_allowed",
55
+ /**
56
+ * A cited surface isn't in the text, so its span has no offsets.
57
+ */
58
+ UnresolvableSpan: "unresolvable_span",
59
+ /**
60
+ * The text holds letters or digits outside every cited surface.
61
+ */
62
+ UnsuppliedText: "text_outside_supplied_surfaces",
63
+ /**
64
+ * Two spans touch without a separator in a script that separates words.
65
+ */
66
+ UnseparatedSpans: "unseparated_spans",
67
+ /**
68
+ * The form writes one surface in Latin script beside another in a different script.
69
+ */
70
+ MixedScript: "mixed_script",
71
+ /**
72
+ * The text is empty or longer than a search-box query.
73
+ */
74
+ Length: "raw_length",
75
+ /**
76
+ * The same text was already kept for this place.
77
+ */
78
+ Duplicate: "duplicate_raw",
79
+ } as const
80
+
81
+ /**
82
+ * One drop reason.
83
+ */
84
+ export type FormDrop = (typeof FormDrop)[keyof typeof FormDrop]
85
+
86
+ /**
87
+ * One labeled span of a kept form.
88
+ */
89
+ export interface CandidateSpan {
90
+ tag: "locality" | "dependent_locality" | "region" | "country"
91
+ /**
92
+ * The span's text as the form writes it.
93
+ */
94
+ value: string
95
+ /**
96
+ * UTF-16 offsets into `raw`, `end` exclusive.
97
+ */
98
+ start: number
99
+ end: number
100
+ /**
101
+ * The supplied surface the span writes, and the record it came from.
102
+ */
103
+ surface: string
104
+ origin: string
105
+ }
106
+
107
+ /**
108
+ * A kept form before the run's model and batch are added to it.
109
+ */
110
+ export interface ValidatedForm {
111
+ wof_id: number
112
+ country: string
113
+ band: ShapeSeed["band"]
114
+ shape: string
115
+ raw: string
116
+ spans: CandidateSpan[]
117
+ /**
118
+ * Whether the form cited a bare slot letter (`n`) rather than a key (`n2`),
119
+ * and the letter was resolved to the one key of that slot the text passes with.
120
+ */
121
+ keys_from_letters: boolean
122
+ }
123
+
124
+ /**
125
+ * The longest text kept, in UTF-16 units.
126
+ */
127
+ const MAX_RAW_LENGTH = 120
128
+
129
+ /**
130
+ * The characters a form may hold outside its spans.
131
+ */
132
+ const SEPARATORS = /^[\s,.;/()\-–·、,]*$/u
133
+
134
+ /**
135
+ * A character of a script written without spaces between words, where two spans may touch.
136
+ */
137
+ const UNSPACED_SCRIPT =
138
+ /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u
139
+
140
+ /**
141
+ * A text folded for comparison, with each folded unit's offsets in the source.
142
+ */
143
+ interface OffsetFold {
144
+ text: string
145
+ starts: number[]
146
+ ends: number[]
147
+ }
148
+
149
+ /**
150
+ * Folds case and whitespace as `foldCaseWhitespace` does, keeping where each folded unit came from.
151
+ *
152
+ * Each code point is lower-cased on its own, so a final sigma folds as a medial one does
153
+ * and `ΠΑΦΟΣ` matches `Πάφος`'s letters where the context-sensitive mapping wouldn't.
154
+ */
155
+ function foldWithOffsets(input: string): OffsetFold {
156
+ const fold: OffsetFold = { text: "", starts: [], ends: [] }
157
+ let offset = 0
158
+ // The source offsets of a whitespace run not yet written, or -1 outside one.
159
+ let spaceStart = -1
160
+ let spaceEnd = -1
161
+
162
+ for (const char of input) {
163
+ const start = offset
164
+
165
+ offset += char.length
166
+
167
+ if (/\s/u.test(char)) {
168
+ if (fold.text !== "") {
169
+ spaceStart = spaceStart < 0 ? start : spaceStart
170
+ spaceEnd = offset
171
+ }
172
+
173
+ continue
174
+ }
175
+
176
+ if (spaceStart >= 0) {
177
+ fold.text += " "
178
+ fold.starts.push(spaceStart)
179
+ fold.ends.push(spaceEnd)
180
+ spaceStart = -1
181
+ }
182
+
183
+ const lowered = char.toLowerCase().replaceAll("ς", "σ")
184
+
185
+ fold.text += lowered
186
+ // One offset pair per UTF-16 unit, so an index into the folded text reads its source offsets.
187
+ fold.starts.push(...Array.from<number>({ length: lowered.length }).fill(start))
188
+ fold.ends.push(...Array.from<number>({ length: lowered.length }).fill(offset))
189
+ }
190
+
191
+ return fold
192
+ }
193
+
194
+ /**
195
+ * The tag a surface takes in a form of `seed`.
196
+ */
197
+ function surfaceTag(seed: ShapeSeed, surface: SeedSurface): CandidateSpan["tag"] {
198
+ switch (surface.slot) {
199
+ case SurfaceSlot.Name:
200
+ return seed.place_tag
201
+ case SurfaceSlot.Parent:
202
+ return seed.parent_tag ?? "locality"
203
+ case SurfaceSlot.Region:
204
+ case SurfaceSlot.RegionAbbreviation:
205
+ return "region"
206
+ case SurfaceSlot.Country:
207
+ return "country"
208
+ }
209
+ }
210
+
211
+ /**
212
+ * The shape id of a set of cited slots: the second segments in a fixed order,
213
+ * or `bare` for a form that cites only the name.
214
+ */
215
+ export function shapeOfSlots(slots: ReadonlySet<SurfaceSlot>): string {
216
+ const parts = [
217
+ slots.has(SurfaceSlot.Parent) ? "parent" : null,
218
+ slots.has(SurfaceSlot.Region) ? "region" : null,
219
+ slots.has(SurfaceSlot.RegionAbbreviation) ? "region_abbr" : null,
220
+ slots.has(SurfaceSlot.Country) ? "country" : null,
221
+ ].filter((part) => part != null)
222
+
223
+ return parts.length ? parts.join("+") : "bare"
224
+ }
225
+
226
+ /**
227
+ * Whether the label policy writes a form with these slots for `seed`: one name, at most one surface per
228
+ * other slot, a region written once, and a parent beside every place the seed has a parent slot for.
229
+ */
230
+ function slotsAllowed(seed: ShapeSeed, surfaces: readonly SeedSurface[]): boolean {
231
+ const count = (slot: SurfaceSlot) => surfaces.filter((surface) => surface.slot === slot).length
232
+
233
+ if (count(SurfaceSlot.Name) !== 1) return false
234
+
235
+ if (Object.values(SurfaceSlot).some((slot) => count(slot) > 1)) return false
236
+
237
+ if (count(SurfaceSlot.Region) + count(SurfaceSlot.RegionAbbreviation) > 1) return false
238
+
239
+ // A postal pair's parent is its region, so an abbreviation replaces the parent rather than joining it.
240
+ if (seed.parent_tag === "region") {
241
+ return count(SurfaceSlot.Parent) + count(SurfaceSlot.RegionAbbreviation) === 1
242
+ }
243
+
244
+ return seed.parent_tag === "locality" ? count(SurfaceSlot.Parent) === 1 : count(SurfaceSlot.Parent) === 0
245
+ }
246
+
247
+ function isLatin(text: string): boolean {
248
+ return /\p{Script=Latin}/u.test(text)
249
+ }
250
+
251
+ function hasOtherScript(text: string): boolean {
252
+ return /[^\p{Script=Latin}\p{Script=Common}\p{Script=Inherited}]/u.test(text)
253
+ }
254
+
255
+ /**
256
+ * Every order of `items`, the given order first.
257
+ */
258
+ function* orderings<T>(items: readonly T[]): Generator<T[]> {
259
+ if (items.length <= 1) {
260
+ yield [...items]
261
+
262
+ return
263
+ }
264
+
265
+ for (let index = 0; index < items.length; index++) {
266
+ for (const rest of orderings([...items.slice(0, index), ...items.slice(index + 1)])) {
267
+ yield [items[index]!, ...rest]
268
+ }
269
+ }
270
+ }
271
+
272
+ /**
273
+ * Finds each surface in `fold` from left to right in the order given, or `null` when one is absent.
274
+ */
275
+ function locateInOrder(
276
+ fold: OffsetFold,
277
+ surfaces: readonly SeedSurface[]
278
+ ): Array<{ surface: SeedSurface; start: number; end: number }> | null {
279
+ const located: Array<{ surface: SeedSurface; start: number; end: number }> = []
280
+ let from = 0
281
+
282
+ for (const surface of surfaces) {
283
+ const needle = foldWithOffsets(surface.text).text
284
+ const at = needle === "" ? -1 : fold.text.indexOf(needle, from)
285
+
286
+ if (at < 0) return null
287
+
288
+ from = at + needle.length
289
+ located.push({ surface, start: fold.starts[at]!, end: fold.ends[from - 1]! })
290
+ }
291
+
292
+ return located
293
+ }
294
+
295
+ /**
296
+ * Every choice of one item from each list, in the lists' order.
297
+ * A list without an item leaves no choice.
298
+ */
299
+ function* choices<T>(lists: ReadonlyArray<readonly T[]>): Generator<T[]> {
300
+ const [head, ...rest] = lists
301
+
302
+ if (!head) {
303
+ yield []
304
+
305
+ return
306
+ }
307
+
308
+ for (const item of head) {
309
+ for (const tail of choices(rest)) {
310
+ yield [item, ...tail]
311
+ }
312
+ }
313
+ }
314
+
315
+ function isSurfaceSlot(key: string): key is SurfaceSlot {
316
+ return (Object.values(SurfaceSlot) as string[]).includes(key)
317
+ }
318
+
319
+ /**
320
+ * Checks one returned form against its seed.
321
+ *
322
+ * A bare slot letter cited as a key stands for a key of that slot.
323
+ * Each choice of keys is checked under the rules a numbered citation passes.
324
+ *
325
+ * The form is kept only when exactly one choice passes, so a letter never decides
326
+ * between two surfaces the text could both be.
327
+ */
328
+ export function validateForm(seed: ShapeSeed, form: ReturnedForm): ValidatedForm | FormDrop {
329
+ const raw = form.raw.trim()
330
+
331
+ if (raw === "" || raw.length > MAX_RAW_LENGTH || /[\n\r\t]/u.test(raw)) return FormDrop.Length
332
+
333
+ const byKey = new Map(seed.surfaces.map((surface) => [surface.key, surface]))
334
+ const options: SeedSurface[][] = []
335
+ let fromLetters = false
336
+
337
+ for (const key of form.uses) {
338
+ const surface = byKey.get(key)
339
+
340
+ if (surface) {
341
+ options.push([surface])
342
+ } else if (isSurfaceSlot(key)) {
343
+ fromLetters = true
344
+ options.push(seed.surfaces.filter((candidate) => candidate.slot === key))
345
+ } else {
346
+ return FormDrop.UnknownSurface
347
+ }
348
+ }
349
+
350
+ if (!options.length) return FormDrop.UnknownSurface
351
+
352
+ if (!fromLetters) return validateCitedSurfaces(seed, raw, options.flat(), false)
353
+
354
+ let passing: ValidatedForm | null = null
355
+
356
+ for (const surfaces of choices(options)) {
357
+ const result = validateCitedSurfaces(seed, raw, surfaces, true)
358
+
359
+ if (typeof result === "string") continue
360
+
361
+ if (passing) return FormDrop.LetterAmbiguous
362
+
363
+ passing = result
364
+ }
365
+
366
+ return passing ?? FormDrop.LetterUnresolved
367
+ }
368
+
369
+ /**
370
+ * Checks a form's text against the surfaces it cites.
371
+ *
372
+ * The surfaces are located in the cited order first and then in every other order,
373
+ * and the first order that leaves only separators outside the spans is kept.
374
+ */
375
+ function validateCitedSurfaces(
376
+ seed: ShapeSeed,
377
+ raw: string,
378
+ surfaces: readonly SeedSurface[],
379
+ fromLetters: boolean
380
+ ): ValidatedForm | FormDrop {
381
+ if (!slotsAllowed(seed, surfaces)) return FormDrop.SlotsNotAllowed
382
+
383
+ if (
384
+ surfaces.some((surface) => hasOtherScript(surface.text)) &&
385
+ surfaces.some((surface) => !hasOtherScript(surface.text) && isLatin(surface.text))
386
+ ) {
387
+ return FormDrop.MixedScript
388
+ }
389
+
390
+ const fold = foldWithOffsets(raw)
391
+ let failure: FormDrop = FormDrop.UnresolvableSpan
392
+
393
+ for (const order of orderings(surfaces)) {
394
+ const located = locateInOrder(fold, order)
395
+
396
+ if (!located) continue
397
+
398
+ const gaps = located.map((span, index) => raw.slice(index === 0 ? 0 : located[index - 1]!.end, span.start))
399
+ const tail = raw.slice(located.at(-1)!.end)
400
+
401
+ if (gaps[0] !== "" || ![...gaps, tail].every((gap) => SEPARATORS.test(gap)) || !/^[).]?$/u.test(tail)) {
402
+ failure = FormDrop.UnsuppliedText
403
+
404
+ continue
405
+ }
406
+
407
+ const touching = gaps.some(
408
+ (gap, index) =>
409
+ index > 0 &&
410
+ gap === "" &&
411
+ !(UNSPACED_SCRIPT.test(raw[located[index]!.start]!) || UNSPACED_SCRIPT.test(raw[located[index]!.start - 1]!))
412
+ )
413
+
414
+ if (touching) {
415
+ failure = FormDrop.UnseparatedSpans
416
+
417
+ continue
418
+ }
419
+
420
+ return {
421
+ wof_id: seed.wof_id,
422
+ country: seed.country,
423
+ band: seed.band,
424
+ shape: shapeOfSlots(new Set(surfaces.map((surface) => surface.slot))),
425
+ raw,
426
+ spans: located.map(({ surface, start, end }) => ({
427
+ tag: surfaceTag(seed, surface),
428
+ value: raw.slice(start, end),
429
+ start,
430
+ end,
431
+ surface: surface.text,
432
+ origin: surface.origin,
433
+ })),
434
+ keys_from_letters: fromLetters,
435
+ }
436
+ }
437
+
438
+ return failure
439
+ }
440
+
441
+ /**
442
+ * The kept forms of one place and its drops by reason, with a repeated text kept once.
443
+ */
444
+ export function validatePlaceForms(
445
+ seed: ShapeSeed,
446
+ forms: readonly ReturnedForm[]
447
+ ): { kept: ValidatedForm[]; drops: Partial<Record<FormDrop, number>> } {
448
+ const kept: ValidatedForm[] = []
449
+ const drops: Partial<Record<FormDrop, number>> = {}
450
+ const seen = new Set<string>()
451
+
452
+ for (const form of forms) {
453
+ const result = validateForm(seed, form)
454
+ const drop = typeof result === "string" ? result : seen.has(result.raw) ? FormDrop.Duplicate : null
455
+
456
+ if (drop || typeof result === "string") {
457
+ drops[drop!] = (drops[drop!] ?? 0) + 1
458
+
459
+ continue
460
+ }
461
+
462
+ seen.add(result.raw)
463
+ kept.push(result)
464
+ }
465
+
466
+ return { kept, drops }
467
+ }
468
+
469
+ /**
470
+ * What one request's response held: the kept forms, the drops by reason,
471
+ * the forms returned and the places answered.
472
+ */
473
+ export interface ValidatedResponse {
474
+ kept: ValidatedForm[]
475
+ drops: Partial<Record<string, number>>
476
+ returned: number
477
+ answered: Set<number>
478
+ }
479
+
480
+ /**
481
+ * Validates the response text of one request against the request's seeds,
482
+ * or returns `null` when the text isn't the schema's shape.
483
+ */
484
+ export function validateResponse(text: string, seeds: readonly ShapeSeed[]): ValidatedResponse | null {
485
+ const places = parseShapeResponse(text)
486
+
487
+ if (!places) return null
488
+
489
+ const byID = new Map(seeds.map((seed) => [String(seed.wof_id), seed]))
490
+ const kept: ValidatedForm[] = []
491
+ const drops: Partial<Record<string, number>> = {}
492
+ const answered = new Set<number>()
493
+ let returned = 0
494
+
495
+ for (const place of places) {
496
+ const seed = byID.get(place.id)
497
+
498
+ returned += place.forms.length
499
+
500
+ if (!seed || answered.has(seed.wof_id)) {
501
+ const reason = seed ? "repeated_place" : "place_not_in_request"
502
+
503
+ drops[reason] = (drops[reason] ?? 0) + place.forms.length
504
+
505
+ continue
506
+ }
507
+
508
+ answered.add(seed.wof_id)
509
+
510
+ const result = validatePlaceForms(seed, place.forms)
511
+
512
+ kept.push(...result.kept)
513
+
514
+ for (const [reason, n] of Object.entries(result.drops)) {
515
+ drops[reason] = (drops[reason] ?? 0) + n
516
+ }
517
+ }
518
+
519
+ return { kept, drops, returned, answered }
520
+ }
521
+
522
+ /**
523
+ * The reason every form of a response dropped under, or `null` when a form was kept,
524
+ * the response held no form, or its forms dropped under more than one reason.
525
+ *
526
+ * One reason taking a whole response is a fault of the request or of the validator rather than of a form.
527
+ */
528
+ export function wholeResponseDropReason(response: ValidatedResponse): string | null {
529
+ const reasons = Object.entries(response.drops).filter(([, n]) => (n ?? 0) > 0)
530
+
531
+ if (response.kept.length || response.returned === 0 || reasons.length !== 1) return null
532
+
533
+ return reasons[0]![0]
534
+ }
535
+
536
+ /**
537
+ * Parses a response's text into its places, or returns `null` when the text isn't the schema's shape.
538
+ *
539
+ * A place or form of another shape makes the whole response unreadable rather than a
540
+ * shorter list, so a caller never counts a partly read response as a complete one.
541
+ */
542
+ export function parseShapeResponse(text: string): ReturnedPlace[] | null {
543
+ const parsed = tryParsingJSON(text) as { places?: unknown } | null
544
+
545
+ if (!parsed || !Array.isArray(parsed.places)) return null
546
+
547
+ const places: ReturnedPlace[] = []
548
+
549
+ for (const place of parsed.places as Array<Partial<ReturnedPlace> | null>) {
550
+ if (typeof place?.id !== "string" || !Array.isArray(place.forms)) return null
551
+
552
+ for (const form of place.forms as Array<Partial<ReturnedForm> | null>) {
553
+ const readable =
554
+ typeof form?.raw === "string" && Array.isArray(form.uses) && form.uses.every((key) => typeof key === "string")
555
+
556
+ if (!readable) return null
557
+ }
558
+
559
+ places.push({ id: place.id, forms: place.forms })
560
+ }
561
+
562
+ return places
563
+ }
@@ -21,7 +21,8 @@ import { trainingCorpusVersion } from "#training/config/load"
21
21
  import type { TrainingConfig } from "#training/config/schema"
22
22
 
23
23
  /**
24
- * The corpus sources a config admits: every positive `source_weights` or `source_reps` key, sorted.
24
+ * The corpus sources a config admits: every positive `source_weights` or `source_reps` key,
25
+ * plus any source listed in `tier1_sources`, sorted.
25
26
  *
26
27
  * A config without `source_weights` admits every source its corpus holds and lists none of them.
27
28
  */
@@ -31,7 +32,13 @@ export function admittedTrainingSources(config: TrainingConfig): string[] {
31
32
  .filter(([, weight]) => weight > 0)
32
33
  .map(([source]) => source)
33
34
 
34
- return [...new Set([...positive(config.data.source_weights), ...positive(config.data.source_reps)])].toSorted()
35
+ return [
36
+ ...new Set([
37
+ ...positive(config.data.source_weights),
38
+ ...positive(config.data.source_reps),
39
+ ...config.data.tier1_sources,
40
+ ]),
41
+ ].toSorted()
35
42
  }
36
43
 
37
44
  /**
@@ -67,13 +67,32 @@ const optionalInt = (value: bigint | null = null) => ({
67
67
  * `mixture` draws each row's source from the weights and shuffles.
68
68
  * `stored` reads each positively weighted source's rows once, in the order `source_weights`
69
69
  * lists the sources and the corpus stores the rows, and ends the run when the files end.
70
+ *
71
+ * `stratified` mixes exact shuffled passes over `tier1_sources` at `tier1_share`
72
+ * with temperature-smoothed sampling over Tier-2 sources.
70
73
  */
71
- export const READ_ORDERS = ["mixture", "stored"] as const
74
+ export const READ_ORDERS = ["mixture", "stored", "stratified"] as const
72
75
 
73
76
  export type ReadOrder = (typeof READ_ORDERS)[number]
74
77
 
75
78
  const readOrder = () => ({ annotation: "str", default: (): PythonValue => "mixture", output: z.enum(READ_ORDERS) })
76
79
 
80
+ /**
81
+ * How runtime augmentations are emitted by `mtf-sampler`.
82
+ *
83
+ * `legacy_copy` emits augmented rows beside the original row, preserving v8 parity.
84
+ * `in_place` transforms each popped row 1-to-1 after the shuffle buffer with an isolated PRNG.
85
+ */
86
+ export const AUGMENT_MODES = ["legacy_copy", "in_place"] as const
87
+
88
+ export type AugmentMode = (typeof AUGMENT_MODES)[number]
89
+
90
+ const augmentMode = () => ({
91
+ annotation: "str",
92
+ default: (): PythonValue => "legacy_copy",
93
+ output: z.enum(AUGMENT_MODES),
94
+ })
95
+
77
96
  const optionalFloat = () => ({ annotation: "float | None", default: () => null, output: z.number().nullable() })
78
97
  const strList = () => ({ annotation: "list[str]", default: (): PythonValue => [], output: z.array(z.string()) })
79
98
 
@@ -169,6 +188,10 @@ export const LABEL_SUPPORT_SECTION = {
169
188
  * Its `PLACES.json` sits beside it.
170
189
  *
171
190
  * A config that sets it runs the `prominent_place_coverage` receipt in the launch preflight (#3156).
191
+ *
192
+ * `required_place_coverage` is the least share of the WOF places the `wof-admin`
193
+ * adapter renders that must hold a `wof-admin` train row.
194
+ * A config that sets it runs the `place_coverage` receipt in the launch preflight.
172
195
  */
173
196
  export const DATA_SECTION = {
174
197
  className: "DataConfig",
@@ -188,6 +211,7 @@ export const DATA_SECTION = {
188
211
  required_validation_coverage: sectionList(VALIDATION_COVERAGE_SECTION),
189
212
  required_validation_label_support: sectionList(LABEL_SUPPORT_SECTION),
190
213
  prominent_place_coverage: optionalStr(),
214
+ required_place_coverage: optionalFloat(),
191
215
  train_rows_per_epoch: optionalInt(),
192
216
  read_order: readOrder(),
193
217
  val_rows: optionalInt(4096n),
@@ -219,6 +243,29 @@ export const DATA_SECTION = {
219
243
  anchor_paint_mode: str("gold"),
220
244
  anchor_value_mode: str("posterior_latlon"),
221
245
  region_centroids_path: optionalStr(),
246
+ /**
247
+ * The corpus's outcome mask file, relative to the checkout.
248
+ *
249
+ * A model with the outcome hint or head reads it (`packages/trainer/crates/trainer-loop/src/outcomes.rs`).
250
+ */
251
+ outcome_masks_path: optionalStr(),
252
+ byte_window: int(32n),
253
+ augment_mode: augmentMode(),
254
+ augment_drop_commas_prob: float(0),
255
+ augment_double_space_prob: float(0),
256
+ augment_line_breaks_prob: float(0),
257
+ augment_accent_strip_prob: float(0),
258
+ tier1_sources: strList(),
259
+ tier1_share: float(0.5),
260
+ temperature_alpha: float(0.4),
261
+ spread_visit_rows: optionalInt(),
262
+ use_alias_draw_weights: bool(false),
263
+ /**
264
+ * The grammar-family partition table, relative to the checkout.
265
+ *
266
+ * Defaults to `packages/trainer/data/grammar_families.json` when configured for v9.
267
+ */
268
+ grammar_families_path: optionalStr(),
222
269
  },
223
270
  } as const satisfies ConfigSectionSpec
224
271
 
@@ -251,6 +298,10 @@ export const MODEL_SECTION = {
251
298
  use_locale_hint: bool(false),
252
299
  locale_hint_drop_prob: float(0.5),
253
300
  locale_hint_noise_prob: float(0.05),
301
+ use_outcome_hint: bool(false),
302
+ outcome_hint_prob: float(0),
303
+ use_outcome_head: bool(false),
304
+ outcome_loss_weight: float(0),
254
305
  use_postcode_anchor: bool(false),
255
306
  use_gazetteer_anchor: bool(false),
256
307
  use_conventions_loss_mask: bool(false),
@@ -273,6 +324,22 @@ export const MODEL_SECTION = {
273
324
  use_char_embed: bool(false),
274
325
  char_embed_dim: int(64n),
275
326
  char_kernel_sizes: intList([3n, 4n, 5n]),
327
+ use_byte_stem: bool(false),
328
+ byte_embed_dim: int(64n),
329
+ byte_kernel_sizes: intList([1n, 3n, 5n]),
330
+ use_rel_pos_bias: bool(false),
331
+ rel_pos_max_dist: int(32n),
332
+ use_grammar_smear: bool(false),
333
+ grammar_layer: int(2n),
334
+ num_grammar_families: int(10n),
335
+ smear_rank: int(12n),
336
+ smear_start_layer: int(4n),
337
+ grammar_loss_weight: float(0),
338
+ use_outcome_attn_pool: bool(false),
339
+ outcome_hint_noise_prob: float(0),
340
+ outcome_hint_parent_only: bool(false),
341
+ outcome_mask_loss_on_hint: bool(false),
342
+ outcome_class_weights: optionalFloatMap(),
276
343
  },
277
344
  } as const satisfies ConfigSectionSpec
278
345