// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * Splits corpus rows into train, val and test by holding out whole places: a random row * split leaks by neighborhood, because the model can memorize a street it saw in train. * * Rows inside a held-out place go to val or test 50/50 by a hash of `source_id`; * every other row goes to train. * Under the evaluation-group policy only the groups the frozen evaluation sets drew from * go to test, a per-country quota of the held-out places' groups goes to val, and the rest * of those places trains (`#utils/evaluation-groups`, `#utils/validation-groups`). * * A holdout change takes effect at the next corpus rebuild. * Each versioned corpus keeps the `SPLIT_MANIFEST.json` it was built with, because adding * a holdout to a built corpus would leak rows the model already trained on. */ import { sha256Buffer } from "@mailwoman/core/crypto/hash" import { openWriteStream } from "@mailwoman/core/fs/streams" import { writeLocalJSONFile, writeLocalTextFile, makeDirectories, removePath } from "@mailwoman/core/fs/writers" import { spawnProcess } from "@mailwoman/core/scripting/process" import { childEnv } from "@mailwoman/core/scripting/utils" import { foldNFKCWhitespace } from "@mailwoman/normalize/fold" import { compactPostcode } from "@mailwoman/postcode/display-form" import { type PathBuilderLike, resolvePathBuilder } from "path-ts" import { JSONSpliterator } from "spliterator" import { recordIDOf } from "#adapters/record-id" import type { CanonicalRow, LabeledRow } from "#types" import { type AddressKeyedRow, evaluationGroupOf, type FrozenGroups, isFrozenRow } from "#utils/evaluation-groups" import { shapeKeyOf, type SplitRetention } from "#utils/retention" import type { ValidationGroups } from "#utils/validation-groups" /** * The name of one corpus split. */ export type SplitName = "train" | "val" | "test" /** * The three splits, in the order a build writes them. */ export const SPLIT_NAMES: readonly SplitName[] = ["train", "val", "test"] /** * The component values that identify the places one country holds out. * * Sources represent a place in different components: `usgov-nad` and `tiger` emit `region`, * but BAN emits none, so a French holdout must also match on postcode. * A row is held out when any declared matcher fires. * A policy with no matchers holds out no entry. */ export interface HoldoutPolicy { regions?: readonly string[] /** * Prefixes matched against `row.components.postcode`; use one only where it identifies * a single place by itself, such as the first two digits of a French postcode. */ postcodePrefixes?: readonly string[] localities?: readonly string[] } /** * One country's holdout as a bare region list or a {@link HoldoutPolicy}. * * Older committed `SPLIT_MANIFEST.json` files use a bare array of region values. */ export type CountryHoldout = readonly string[] | HoldoutPolicy /** * Options for {@link splitRows}. */ export interface SplitOptions { /** * The holdout policy keyed by ISO 3166-1 alpha-2 country code. */ holdouts?: Record /** * The corpus version the manifest records. * * @defaultValue `""` */ corpusVersion?: string /** * The retention table applied to every row, when one was registered. */ retention?: SplitRetention } /** * The `source_id` lists for each split. */ export interface SplitManifest { train: string[] val: string[] test: string[] holdouts: Record /** * The retention table applied, when one was registered. */ retention?: { floor: number; protectedShapes: number } /** * The corpus version the caller supplied. */ corpus_version: string counts: { train: number; val: number; test: number; total: number } } /** * Returns the default holdouts: places below the first-level region in each country, * keyed only by open-vocabulary values, a postcode district or a locality. * A change here takes effect at the next split of the corpus. * * No entry keys on a region. * A region's name is a region span only in rows from that region, so holding a * region out removes it as a label from training, and the model then relabels it * (#2777: v0.8.0 train held 0 region spans for VT, ND, WY, Asturias, Kerala and Cornwall). * * The split holds out places inside regions. * It removes a small share of each affected region and leaves the test split * measuring unseen places under labels the model has seen. * * A selection script chose the district and locality lists below from the v0.8.0 rows of each country: * - Candidates are postcode districts of a fixed length (US 3, AU 3, RO 4, LV and the * French overseas jurisdictions the full postcode), or, where most rows have no postcode, * localities grouped by spelling with accents and punctuation removed. * A locality whose spelling matches a region surface isn't a candidate. * Each candidate accounts for at least 1% of the country's v0.8.0 held-out rows. * - They're walked in the order of `hashBucket(\`${country}|${candidate}\`, 2 ** 32)` * and taken while the country's held-out rows stay at or under its v0.8.0 held-out rows, * because a borderline row goes to training. * A country whose candidates under that bound number fewer than two takes its smallest * candidates up to two, so its held-out set has groups to grade (YT, PF and NC). * Taking also requires that every region with at least {@link HOLDOUT_CAP_MIN_ROWS} * rows loses at most {@link heldOutRegionCap}`(share)` of its rows, and of its rows * with no postcode, where `share` is the country's v0.8.0 held-out share. * - A locality group is held out by every spelling the v0.8.0 rows write. * `held-out-spans.full.test.ts` checks a built corpus against this table. */ export function defaultHoldouts(): Record { return { // DE and GB keep the postcode areas of earlier corpora, so the held-out // rows already verified unseen stay unseen. // Their region names, Saarland, Mecklenburg-Vorpommern and Cornwall, left the table. // FR: districts 200 (Ajaccio) and 206 in Corsica, 231 and 236 in Creuse, and Lozère 48. // A two-digit FR prefix is a whole department, and with all of Creuse and Corsica held out the // region labels Creuse and Corse-du-Sud kept 110 and 73 train rows. The four districts hold out // 60 of Creuse's and 6 of Corsica's region-labeled rows. // DE: area 02, Upper Lusatia in eastern Sachsen. // GB: the Truro and Halifax areas, and ten districts of the Llandudno area. // The whole LL area held 75% of the rendered rows naming Conwy, 74% of Wrecsam's and 67% of // Sir Ddinbych's, so its districts were chosen by the method above, with the cap read for every // region the v0.8.2 GB rows name, these Welsh counties carrying under 100 region rows each. // No prefix is a prefix of another, and no district key is a prefix of another district. FR: { postcodePrefixes: ["200", "206", "231", "236", "48"] }, DE: { postcodePrefixes: ["02"] }, GB: { postcodePrefixes: [ "TR", "HX", "LL15", "LL17", "LL21", "LL26", "LL36", "LL40", "LL41", "LL53", "LL54", "LL55", "LL57", ], }, // Three-digit ZIP areas. US: { postcodePrefixes: [ "084", "156", "171", "172", "223", "317", "364", "450", "664", "683", "716", "734", "759", "763", "808", "881", ], }, AU: { postcodePrefixes: [ "080", "083", "203", "248", "366", "375", "379", "397", "406", "467", "470", "523", "607", "628", "631", "640", "651", "733", ], }, LV: { postcodePrefixes: [ "LV-1004", "LV-1023", "LV-1029", "LV-1057", "LV-2011", "LV-2012", "LV-2016", "LV-2105", "LV-2111", "LV-2119", "LV-2161", "LV-3001", "LV-3007", "LV-3145", "LV-3284", "LV-3456", "LV-3708", "LV-3933", "LV-4033", "LV-4245", "LV-4630", "LV-4838", "LV-5022", "LV-5070", "LV-5120", "LV-5202", "LV-5413", "LV-5414", "LV-5417", "LV-5418", "LV-5422", "LV-5449", "LV-5473", "LV-5481", "LV-5664", "LV-5674", ], }, RO: { postcodePrefixes: [ "0312", "0613", "0751", "1070", "1073", "1153", "1276", "1300", "1470", "2004", "2005", "2173", "2200", "2352", "2477", "3102", "3271", "4000", "4004", "4073", "4173", "4270", "4451", "5004", "5101", "5176", "5356", "5475", "5510", "5571", "6052", "6170", "6271", "7000", "7001", "7005", "7006", "7202", "7251", "7254", "7310", "7370", "7375", "8004", "9003", "9272", ], }, // Each French overseas jurisdiction's BAN rows include a commune postcode, so these hold out communes. // Saint-Barthélemy and Saint-Martin are each one commune under one postcode, // and Saint-Pierre-et-Miquelon's Saint-Pierre holds 2,706 of its 3,084 rows, // so those three are left to the hashed holdout. GP: { postcodePrefixes: ["97113", "97125", "97126", "97128", "97136"] }, MQ: { postcodePrefixes: ["97211", "97216", "97225", "97227", "97233"] }, GF: { postcodePrefixes: ["97313", "97314", "97315", "97316", "97319", "97350", "97360", "97380", "97390"], }, RE: { postcodePrefixes: ["97423", "97427", "97438", "97442", "97450"] }, YT: { postcodePrefixes: ["97625", "97660"] }, PF: { postcodePrefixes: ["98713", "98716"] }, NC: { postcodePrefixes: ["98817", "98820", "98859"] }, // The countries below have a postcode on few rows (ES 13%, IT 6%, RU 20% and under 40% for the rest), // so their holdouts are localities. // ID's `` and NG's `edo state` and `imo`, a placeholder and two state // names written as localities, were dropped from the selection. // One VN commune of Hàm Thuận was dropped too, because the repository spelling // check reads its last word as a typo. // CN and IN are left to the hashed holdout: their locality spans are a // million village and neighborhood names with a median of about ten rows, // so a declared list would need tens of thousands of entries. ES: { localities: [ "adeje", "agaete", "agaetė", "aguimes", "agüimes", "alegría-dulantzi", "amurrio", "arafo", "arico", "arona", "fasnia", "granadilla de abona", "guia de isora", "guía de isora", "hermigua", "melgar de yuso", "mogan", "mogán", "san bartolome de tirajana", "san bartolomé de tirajana", "san miguel de abona", "san sebastián de la gomera", "santiago del teide", "tejeda", "valle gran rey", "vallehermoso", ], }, IT: { localities: [ "arborea", "arbórea", "buggerru", "cabras", "domusnovas", "fluminimaggiore", "gonnesa", "guspini", "gùspini", "marrubiu", "marrùbiu", "perdaxius", "porto torres", "portoscuso", "portotorres", "san giovanni suergiu", "san nicolo d'arcidano", "san nicolo' d'arcidano", "san nicolò d'arcidano", "san nicolò d’arcidano", "sant'anna arresi", "sant'antioco", "santa giusta", "santantioco", "sant’anna arresi", "sant’antioco", "stintino", "terralba", ], }, ID: { localities: [ "balikpapan", "bekasi", "blega", "bogor", "central jakarta", "depok", "east jakarta", "garut", "jakarta utara", "jimbaran", "kabupaten bandung", "karawang", "kel. karang pamulang", "kota bandung", "kota batam", "kota bekasi", "kota malang", "kota tangerang selatan", "kupang", "kuta", "lhokseumawe", "makassar", "mataram", "rancah", "salatiga", "samarinda", "sidoarjo", "sleman", "surakarta", "west jakarta", ], }, PK: { localities: ["faisal town", "gujrat", "multan", "اسلام آباد"], }, VN: { localities: [ "bien hoa", "biên hòa", "buon ma thuot", "buôn ma thuột", "dĩ an - bình dương", "ha giang", "ha long", "hà giang", "hạ long", "long xuyên", "mui ne", "móng cái", "mũi né", "mỹ tho", "phan rang - tháp chàm", "phan rang- tháp chàm", "phan rang-tháp chàm", "phường 13", "phường 15", "phường 16", "phường 2", "phường 22", "phường hiệp bình chánh", "phường hiệp thành", "phường hòa thạnh", "phường thới an", "phường tân quy", "phường tân quý", "phường đại mỗ", "pleiku", "q.cấu giấy", "q.cầu giấy", "sa pa", "saigon", "sapa", "sài gòn", "thành phố huế", "thành phố hải phòng", "thành phố phú quốc", "thành phố thái nguyên", "thành phố thủ dầu một", "thành phố vũng tàu", "tp. hcm", "tp.hồ chí minh", "tuy hoa", "tuy hoà", "tuy hòa", "tân an", "vinh", "việt trì", "vung tau", "vũng tàu", "xã lai vung", "đồng hới", "đồng xoài", ], }, NG: { localities: [ "ibadan", "iiupeju", "ilorin", "isiozi-akah", "kabala", "korongilum", "kosofe", "lekki peninsula ii", "lokoja", "magodo", "makera", "mararaba", "nsukka", "ota", "oyo town", "suncity", "udu", "unec enugu", "zaria", ], }, BD: { localities: [ ", gazipur", ",gazipur", "brahmanbaria", "chandpur", "chattogram", "chattogram (chittagong)", "chittagong", "chittagong.", "dhanmondi", "gazipur", "jamalpur", "jessore", "lalmatia", "magura", "mirpur 10", "mirpur-10", "mohammadpur area", "narsingdi", "paity", "patuakhali", "rajbari", "rajshahi", "ramganj", "rangamati", "sonargaon", "sreemangal", "terokhada khulna", "tongi", "uttara", "uttara.", "ডেমরা", "মোহাম্মদপুর", ], }, NZ: { localities: [ "ashburton", "auckland central", "awarua plains", "bell block", "chartwell", "christchurch", "christchurch central", "conical hills", "dunedin", "east end", "east gore", "east tamaki", "eastern bush", "glengarry", "glenham", "gummies bush", "hamilton east", "hillsborough", "kaeo", "kaitaia", "levin", "lochiel", "manapouri", "masterton", "mataura", "mossburn", "new plymouth", "ngaruawahia", "niagara", "nightcaps", "otapiri gorge", "otautau", "papamoa", "papatoetoe", "pauanui", "queenstown", "riverton", "rolleston", "round hill", "south hillend", "southbridge", "stoke", "strathern", "taupo", "taupō", "the key", "tisbury", "tokoroa", "twizel", "waikiwi", "waipounamu", "waitara", "wallacetown", "wanaka", "waverley", "wellington", "wendon valley", "westport", "whitford", "wyndham", ], }, RU: { localities: ["алатырь", "архангельск", "валевая", "дубенки", "дубёнки", "лукьяновка", "таврово", "шадринск"], }, } } /** * The component tags {@link splitForRow} reads. * * A reader that rebuilds components from spans needs only these. */ export const HOLDOUT_COMPONENT_TAGS: ReadonlySet = new Set(["venue", "region", "postcode", "locality"]) /** * One place in this number is held out in a country without a {@link defaultHoldouts} entry. */ export const HASHED_PLACE_HOLDOUT_DIVISOR = 50 /** * The held-out share the hashed holdout aims at: one place in {@link HASHED_PLACE_HOLDOUT_DIVISOR}. */ export const HASHED_PLACE_HOLDOUT_SHARE = 1 / HASHED_PLACE_HOLDOUT_DIVISOR /** * {@link heldOutRegionCap} applies to a region with at least {@link HOLDOUT_CAP_MIN_ROWS} rows. * * The same minimum applies to a country when its rows have no region. */ export const HOLDOUT_CAP_MIN_ROWS = 100 /** * The largest share of one region's rows a holdout may take, given the country's * held-out share: `min(0.25, max(0.05, 3 × share))`. * * The declared holdouts in {@link defaultHoldouts} were chosen under this bound, and the * hashed holdout trains on a place that exceeds it (see {@link hashedHoldoutTrainedPlaces}). */ export function heldOutRegionCap(share: number): number { return Math.min(0.25, Math.max(0.05, 3 * share)) } /** * The rows one hash-selected place contributes inside one region, or inside its country * when those rows have no region. */ export interface HashedPlaceRegionCount { country: string /** * The key {@link hashedHoldoutPlace} returns. */ place: string /** * The region under `foldNFKCWhitespace`, or null for rows with no region. */ region: string | null rows: number } /** * Returns, per country, the hash-selected places that exceed {@link heldOutRegionCap} * of {@link HASHED_PLACE_HOLDOUT_SHARE} in some region, sorted. * * A place's rows in a region are divided by that region's rows, and its rows with * no region by the country's rows with no region. * A denominator under {@link HOLDOUT_CAP_MIN_ROWS} isn't checked. * * @param denominators Rows per `${country}|${region}`, with an empty region for rows with no region. */ export function hashedPlacesOverCap( counts: Iterable, denominators: ReadonlyMap ): Record { const cap = heldOutRegionCap(HASHED_PLACE_HOLDOUT_SHARE) const over = new Map>() for (const { country, place, region, rows } of counts) { const key = `${country}|${region ?? ""}` const total = denominators.get(key) if (typeof total !== "number") throw new TypeError(`no row count for ${key}, the region of ${country} ${place}`) if (total < HOLDOUT_CAP_MIN_ROWS || rows / total <= cap) continue const places = over.get(country) ?? new Set() places.add(place) over.set(country, places) } return Object.fromEntries([...over.keys()].toSorted().map((country) => [country, [...over.get(country)!].toSorted()])) } /** * The hash-selected places trained on rather than held out, because each one exceeds * {@link heldOutRegionCap} of {@link HASHED_PLACE_HOLDOUT_SHARE} of a region of at least * {@link HOLDOUT_CAP_MIN_ROWS} rows (or of its country's rows with no region). * * {@link hashedPlacesOverCap} chose this table from the v0.8.1 rows. * A place that leaves the holdout isn't replaced by another, so the country's held-out * share falls: a borderline row goes to training, as in {@link defaultHoldouts}. * * The cap bounds a place's share of a region. * It leaves a place that dominates one source's held-out rows in the holdout: v0.8.1's * `IN|locality:new delhi` was 0.036% of IN's rows with no region while holding every osm-in New Delhi row. */ export function hashedHoldoutTrainedPlaces(): Record { return HASHED_HOLDOUT_TRAINED_PLACES } const HASHED_HOLDOUT_TRAINED_PLACES: Record = { CN: ["locality:黄山市", "locality:黄石市"], EG: ["postcode:42", "postcode:46"], HT: ["locality:gonaives"], IM: ["locality:douglas"], MK: ["locality:драчево"], SM: ["locality:città di san marino"], UY: ["locality:vergara"], } const trainedPlaceSetCache = new WeakMap>>() function trainedPlaceSet(table: Record, country: string): ReadonlySet | undefined { let byCountry = trainedPlaceSetCache.get(table) if (!byCountry) { byCountry = new Map(Object.entries(table).map(([cc, places]) => [cc, new Set(places)])) trainedPlaceSetCache.set(table, byCountry) } return byCountry.get(country) } /** * Returns the place the hashed holdout selects for a row of a country without a * {@link defaultHoldouts} entry, before {@link hashedHoldoutTrainedPlaces} is applied, * or null when the hash doesn't select its place. */ export function hashSelectedPlace( country: string, components: Partial> ): string | null { const place = hashedHoldoutPlace(components) return place !== null && hashBucket(`${country}|${place}`, HASHED_PLACE_HOLDOUT_DIVISOR) === 0 ? place : null } /** * The key a row is held out by under the hashed holdout: its venue, else its locality, * else the first two characters of its postcode, else its region. * * A venue name keys before its place because the venue recipes write one name both with a locality and bare. * A locality key would hold out the first form and train on the second. * * Names are compared under {@link foldHoldoutName} and postcodes under `compactPostcode`. * The case, comma and spacing augmentations rewrite a row's components as well as its text, * and an unfolded key sends `La Planada` to a different place than `La Planada`. * * Returns null for a row with none of the four. * That row stays in train. */ export function hashedHoldoutPlace( components: Partial> ): string | null { const venue = components.venue && foldHoldoutName(components.venue) if (venue) return `venue:${venue}` const locality = components.locality && foldHoldoutName(components.locality) if (locality) return `locality:${locality}` const postcode = components.postcode && compactPostcode(components.postcode) if (postcode && postcode.length >= 2) return `postcode:${postcode.slice(0, 2)}` const region = components.region && foldHoldoutName(components.region) return region ? `region:${region}` : null } /** * A place name as the hashed holdout compares it: `foldNFKCWhitespace` with each comma * read as a space, so `drop-commas` leaves `WAL-MART STORES EAST, LP` the same place. */ function foldHoldoutName(name: string): string { return foldNFKCWhitespace(name.replaceAll(",", " ")) } /** * Returns the matchers for one country, reading a bare array as a region list. */ export function holdoutPolicyFor(holdout: CountryHoldout | null): HoldoutPolicy { if (!holdout) return {} return Array.isArray(holdout) ? { regions: holdout } : (holdout as HoldoutPolicy) } /** * Whether a country's declared holdout reads postcode prefixes and no region or locality. * * Under such a policy a row's split reads only its record and its postcode digits. * The corpus augmentations change case, punctuation and abbreviations, and drop a ZIP+4 dash. * None of them changes the compacted postcode digits. * * A variant of a training row therefore trains, and a caller may draw a variant's * training share before making it. */ export function holdoutReadsOnlyPostcode(holdout: CountryHoldout | null | undefined): boolean { const policy = holdoutPolicyFor(holdout ?? null) return Boolean(policy.postcodePrefixes?.length) && !policy.regions?.length && !policy.localities?.length } interface FoldedHoldoutNames { regions: ReadonlySet localities: ReadonlySet /** * The policy's postcode prefixes under `compactPostcode`, so a row's test compacts only its own postcode. */ postcodePrefixes: readonly string[] } const foldedNamesCache = new WeakMap() /** * A policy's region and locality names under `foldNFKCWhitespace`, computed once per policy object. * * Sources write one place in several cases and spacings (`Asturias`, `ASTURIAS`, `Balearic Islands`). * An exact match held out one spelling and trained on the rest. */ function foldedNamesFor(declared: CountryHoldout, policy: HoldoutPolicy): FoldedHoldoutNames { const cached = foldedNamesCache.get(declared) if (cached) return cached const names: FoldedHoldoutNames = { regions: new Set((policy.regions ?? []).map(foldNFKCWhitespace)), localities: new Set((policy.localities ?? []).map(foldNFKCWhitespace)), postcodePrefixes: (policy.postcodePrefixes ?? []).map(compactPostcode), } foldedNamesCache.set(declared, names) return names } type SplitInputRow = Pick & { /** * The row's ordered span tags, when the caller holds a labeled row. * * Retention keys on them. * A caller without them gets no retention lookup. */ span_tags?: readonly string[] | null /** * The id of the base row an augmented row was derived from. * * The evaluation-group policy keys on it, as the overlap audit does. */ base_source_id?: string | null /** * The source, text and spans a keyed source's address key reads (`GROUP_ADDRESS_KEY_SOURCES`). */ address?: AddressKeyedRow | null } /** * Returns the split for one row. * * Both `splitRows` and the streaming `buildCorpus` loop call this, so every * caller assigns a row to the same split. * * A row of a combination the retention table covers below the floor returns `train` * before the holdout is consulted (HOLDOUT_AND_EVALUATION section 5.1: training * retention takes precedence over geographic integrity). * * With `evaluationGroups`, the split is the evaluation-group policy * (HOLDOUT_AND_EVALUATION section 4.6), decided by the row's group and no other field: * a frozen group returns `test`, a validation group `val`, and every other row `train`. * The holdout, the trained places and the retention table are then not consulted, * so no retained shape returns a frozen group's variant to train. * * A row of a keyed source whose address key a frozen row holds is frozen too, * so a re-ingested address under a new record id stays out of train (#3125). * * The overlap audit reads `val` as training data, so `evaluationGroupPolicy` * refuses a validation list that holds a frozen group. */ export function splitForRow( row: Pick, holdouts: Record = defaultHoldouts(), trainedPlaces: Record = hashedHoldoutTrainedPlaces(), retention?: SplitRetention, evaluationGroups?: { frozen: FrozenGroups; validation: Pick } ): SplitName { if (evaluationGroups) { const group = evaluationGroupOf(row) if (isFrozenRow(group, row.address, evaluationGroups.frozen)) return "test" return evaluationGroups.validation.groups.has(group) ? "val" : "train" } if (retention && row.span_tags && retention.protectedShapes.has(shapeKeyOf(row.country, row.span_tags))) { return "train" } const declared = holdouts[row.country] const { region, postcode, locality } = row.components let isHeldOut: boolean if (declared) { const policy = holdoutPolicyFor(declared) const folded = foldedNamesFor(declared, policy) // A compact postcode matches `ll55 1bz` and `LL55 1BZ` to GB's `LL55` as it matches `LL55 1BZ`. const compact = postcode && compactPostcode(postcode) isHeldOut = Boolean( (region && folded.regions.has(foldNFKCWhitespace(region))) || (compact && folded.postcodePrefixes.some((prefix) => compact.startsWith(prefix))) || (locality && folded.localities.has(foldNFKCWhitespace(locality))) ) } else { // A country without a declared holdout holds out whole places chosen by hash, // so every country in the corpus reaches val and test. // A place too large for its region trains. const place = hashSelectedPlace(row.country, row.components) isHeldOut = place !== null && !trainedPlaceSet(trainedPlaces, row.country)?.has(place) } if (!isHeldOut) return "train" // The bucket is the record's, so the rendered rows of one record stay together in val or test. return hashBucket(recordIDOf(row.source_id), 2) === 0 ? "val" : "test" } /** * Builds a `SplitManifest` in memory from labeled or canonical rows. * * Tests and small fixtures use this, while `buildCorpus` uses `splitForRow` * and `writeSplitManifestsFromLabeledFiles` so it never holds every row's split in memory. */ export function splitRows(rows: Iterable, opts: SplitOptions = {}): SplitManifest { const holdouts = opts.holdouts ?? defaultHoldouts() const train: string[] = [] const val: string[] = [] const test: string[] = [] for (const row of rows) { const split = splitForRow(row, holdouts, undefined, opts.retention) if (split === "train") { train.push(row.source_id) } else if (split === "val") { val.push(row.source_id) } else { test.push(row.source_id) } } const total = train.length + val.length + test.length return { train, val, test, holdouts, ...(opts.retention ? { retention: { floor: opts.retention.floor, protectedShapes: opts.retention.protectedShapes.size } } : {}), corpus_version: opts.corpusVersion ?? "", counts: { train: train.length, val: val.length, test: test.length, total }, } } /** * Returns a deterministic bucket in `0..n-1` for an id, from the first four bytes * of the SHA-256 digest read as a big-endian uint32. */ export function hashBucket(id: string, n: number): number { return hashUint32(id) % n } /** * The first four bytes of an id's SHA-256 digest read as a big-endian uint32, * the value {@link hashBucket} reduces and the validation quota orders groups by. */ export function hashUint32(id: string): number { const digest = sha256Buffer(id) return digest[0]! * 0x01_00_00_00 + digest[1]! * 0x01_00_00 + digest[2]! * 0x01_00 + digest[3]! } /** * Writes a `SplitManifest` to `/{train,val,test}.txt` (sorted `source_id` values, one per line) * and `SPLIT_MANIFEST.json` (the corpus version, holdouts and counts). */ export async function writeSplitManifests(manifest: SplitManifest, outputDir: PathBuilderLike): Promise { await makeDirectories(outputDir) for (const name of ["train", "val", "test"] as const) { const sorted = [...manifest[name]].toSorted() await writeLocalTextFile(sorted, outputDir, `${name}.txt`) } const summary = { corpus_version: manifest.corpus_version, holdouts: manifest.holdouts, ...(manifest.retention ? { retention: manifest.retention } : {}), counts: manifest.counts, } await writeLocalJSONFile(summary, outputDir, "SPLIT_MANIFEST.json") } /** * The `LabeledRow` fields that the split functions read. */ export type SplitInputLabeledRow = Pick /** * Writes the same files as `writeSplitManifests` from the rows' `source_id` values. * * `buildCorpus` calls this after its align loop partitions rows with `splitForRow`. * The caller passes the counts to avoid rescanning the files. * `sort(1)` spills to disk, so memory stays constant. * * Each split's ids come from the first of these the caller supplies: * * - `sortedSourceIDPaths`: lists already sorted by byte, merged by `sort -m`. * A build that aligned its sources apart passes each source's sorted list. * - `sourceIDPaths`: one id per line in the order align wrote them, read by `sort` directly. * - `labeledPaths`, the labeled JSONL itself, parsed for each row's `source_id`. * An align phase resumed from a checkpoint written before align recorded ids leaves only this. * * The three write the same bytes from the same rows, because each feeds `sort` the same multiset of ids. */ export async function writeSplitManifestsFromLabeledFiles(opts: { labeledPaths: Record sourceIDPaths?: Record | null sortedSourceIDPaths?: Record | null outputDir: PathBuilderLike corpusVersion: string counts: Record holdouts?: Record retention?: SplitRetention }): Promise { await makeDirectories(opts.outputDir) const holdouts = opts.holdouts ?? defaultHoldouts() for (const split of ["train", "val", "test"] as const) { const outPath = resolvePathBuilder(opts.outputDir, `${split}.txt`) const sorted = opts.sortedSourceIDPaths?.[split] const ids = opts.sourceIDPaths?.[split] if (sorted) { await sortLines(sorted, outPath, { merge: true }) } else if (ids) { await sortLines([ids], outPath) } else { await streamSortedSourceIDs(opts.labeledPaths[split], outPath) } } const total = opts.counts.train + opts.counts.val + opts.counts.test const summary = { corpus_version: opts.corpusVersion, holdouts, ...(opts.retention ? { retention: { floor: opts.retention.floor, protectedShapes: opts.retention.protectedShapes.size } } : {}), counts: { ...opts.counts, total }, } await writeLocalJSONFile(summary, opts.outputDir, "SPLIT_MANIFEST.json") return summary.counts } /** * Writes the sorted `source_id` values from a labeled JSONL file to `outPath`; * an empty input still produces an empty output file. */ async function streamSortedSourceIDs(labeledJsonlPath: PathBuilderLike, outPath: PathBuilderLike): Promise { const unsortedPath = `${outPath}.unsorted` const out = openWriteStream(unsortedPath, { encoding: "utf8" }) const outClosed = new Promise((resolve, reject) => { out.on("close", () => resolve()) out.on("error", reject) }) // A malformed row throws out of the loop. // The `finally` block still closes the write stream. try { for await (const obj of JSONSpliterator.fromAsync<{ source_id?: string }>(labeledJsonlPath)) { if (typeof obj.source_id === "string") { out.write(`${obj.source_id}\n`) } } } finally { out.end() } await outClosed await sortLines([unsortedPath], outPath) await removePath(unsortedPath).catch(() => {}) } /** * Sort the lines of `inputs` by byte into `outPath` with `sort(1)`, which spills to disk. * * With `merge`, each input must already be sorted by byte, and `sort -m` merges them without sorting again. * Duplicate lines are kept either way, and zero inputs write an empty file. */ export async function sortLines( inputs: readonly PathBuilderLike[], outPath: PathBuilderLike, options: { merge?: boolean } = {} ): Promise { if (!inputs.length) { await writeLocalTextFile("", outPath) return } const args = [...(options.merge ? ["-m"] : []), ...inputs.map((input) => input.toString()), "-o", outPath.toString()] await new Promise((resolve, reject) => { // `LC_ALL=C` sorts by byte, so the order is the same on every host. const proc = spawnProcess("sort", args, { env: childEnv({ LC_ALL: "C" }) }) proc.on("error", reject) proc.on("exit", (code) => { if (code === 0) { resolve() } else { reject(new Error(`sort ${args.join(" ")} exited with code ${code}`)) } }) }) }