vox-tier2-backup / scripts /assemble_pilot.py
addyo07's picture
Tier-2 parking snapshot 2026-10-04
46e27b5 verified
Raw History Blame Contribute Delete
12.3 kB
#!/usr/bin/env python3
"""Assemble the Vox Tier-2 pilot dataset with an audited stratum mixture.
Replaces the first-N sampler that produced the degenerate v1 pilot. Every defect
that made v1 solvable by `len(text) >= 15` is closed here:
1. LENGTH MATCHING - CLEAN negatives are drawn per word-count bucket to match the
DISFLUENCY length histogram. v1 had CLEAN median 8 words vs DISFLUENCY 22,
which handed the label to a one-line rule (91.9% accuracy, no model).
2. RANDOM, DOMAIN-BALANCED SAMPLING - v1 took the first N lines of clean_50k,
which is 100% MultiWOZ. CLEAN is now drawn across two domains.
3. HARD NEGATIVES - a quota of CLEAN examples must contain filler words in KEEP
positions ("works well", "so the cache stays warm"). Without these the model
never practises the delete-vs-keep decision that actually matters.
4. GOLD STRATUM QUOTAS - DISFLUENCY is drawn by gold annotation provenance
(self-correction / disfluency region / edit region) so no single class
dominates, per the taxonomy contract.
5. TIER-1 PARITY - Tier-1-duplicate spans are rejected upstream in the harvester;
this script re-checks via dedup.deterministic_reject.
Usage:
venv/bin/python sandbox/scripts/assemble_pilot.py \
--dis corpus/harvest_dis.jsonl --clean corpus/harvest_clean.jsonl \
--extra-clean corpus/clean_50k.jsonl \
--out corpus/pilot_v2.jsonl --train-out corpus/pilot_v2_train.jsonl \
--val-out corpus/pilot_v2_val.jsonl --total-dis 2000 --total-clean 2000
"""
import argparse
import json
import random
import re
import sys
from collections import Counter, defaultdict
sys.path.insert(0, "/opt/vox/sandbox/scripts")
from dedup import NearDup, norm_tokens
from schema import DatasetExample, Span
FILLER_WORD = re.compile(
r"\b(well|like|so|just|actually|anyway|really|pretty|okay|right|sort of|kind of)\b", re.I)
# The two features the DISFLUENCY half over-represents. CLEAN must be drawn to
# MATCH these rates, otherwise "starts with Well" or "contains you know" becomes a
# free classifier (measured at 63.9% and 67.4% accuracy on pilot_v1).
OPENER = re.compile(r"^\W*(well|yeah|oh|so|okay|ok|right|alright|now)\b", re.I)
CUE_PHRASE = re.compile(r"\b(you know|i mean|you see|i guess|sort of|kind of)\b", re.I)
# Gold stratum quotas as a fraction of the DISFLUENCY half. Tuned so that the
# spoken self-correction class the taxonomy calls out is well represented instead
# of being swamped by filler (v1: 0.6% corrections, 37.6% filler).
QUOTAS = {"correction": 0.40, "region:D": 0.35, "region:E": 0.10}
HARD_NEGATIVE_QUOTA = 0.40 # fraction of CLEAN that must contain a filler word
# --------------------------------------------------------------------------- #
# Fast exact near-duplicate rejection
# --------------------------------------------------------------------------- #
# --------------------------------------------------------------------------- #
# Loading
# --------------------------------------------------------------------------- #
def load(path, limit=None):
out = []
with open(path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
d = json.loads(line)
out.append(DatasetExample(**{k: v for k, v in d.items()
if k in DatasetExample.model_fields}))
except Exception:
continue
if limit and len(out) >= limit:
break
return out
def stratum_of(ex: DatasetExample) -> str:
"""Dominant gold stratum of an example."""
origins = {s.origin for s in ex.spans if s.origin}
if "correction" in origins:
return "correction"
if origins == {"region:E"}:
return "region:E"
return "region:D"
def bucket_of(ex: DatasetExample) -> int:
return len(ex.raw_text.split()) // 5 * 5
# --------------------------------------------------------------------------- #
# Sampling
# --------------------------------------------------------------------------- #
def draw_disfluency(items, total, rng, dup):
"""Quota-driven draw across gold strata, then top up from the remainder."""
pools = defaultdict(list)
for ex in items:
pools[stratum_of(ex)].append(ex)
for v in pools.values():
rng.shuffle(v)
chosen, taken = [], set()
for name, frac in QUOTAS.items():
want = int(total * frac)
picked = 0
for ex in pools.get(name, []):
if picked >= want:
break
fp = norm_tokens(ex.raw_text)
if dup.seen(fp):
continue
dup.add(fp)
chosen.append(ex)
taken.add(id(ex))
picked += 1
print(f" stratum {name:12s} quota {frac:.0%} -> {picked} (pool {len(pools.get(name, []))})")
leftover = [ex for pool in pools.values() for ex in pool if id(ex) not in taken]
rng.shuffle(leftover)
for ex in leftover:
if len(chosen) >= total:
break
fp = norm_tokens(ex.raw_text)
if dup.seen(fp):
continue
dup.add(fp)
chosen.append(ex)
print(f" stratum {'top-up':12s} quota n/a -> {len(chosen)} (total {len(chosen)}/{total})")
return chosen[:total]
def match_rates(dis):
"""Surface-feature rates of the DISFLUENCY half; CLEAN must mirror them."""
n = max(len(dis), 1)
return {
"opener": sum(1 for ex in dis if OPENER.match(ex.raw_text)) / n,
"cue": sum(1 for ex in dis if CUE_PHRASE.search(ex.raw_text)) / n,
"filler": sum(1 for ex in dis if FILLER_WORD.search(ex.raw_text)) / n,
}
def draw_clean(indomain, extra, dis_lut, total, rng, dup, rates):
"""Length-matched, domain-balanced CLEAN draw with a hard-negative quota.
`dis_lut` maps word-count bucket -> how many DISFLUENCY examples fall in it.
Each domain may contribute at most `domain_cap`, so one pool cannot swamp the
other (v1 was 100% MultiWOZ because the sampler took the first N lines).
"""
target = Counter(dis_lut)
domain_cap = total // 2 + total % 2
# Hard-negative quotas are derived from the DISFLUENCY half, not hardcoded, so
# the two strata stay balanced automatically when the source mix changes.
need_opener = int(round(total * rates["opener"]))
need_cue = int(round(total * rates["cue"]))
need_filler = max(int(total * HARD_NEGATIVE_QUOTA), int(round(total * rates["filler"])))
picked = []
stats = Counter()
per_source = Counter()
seen_keys = set()
def take(ex, source):
key = ex.raw_text.strip().lower()
if key in seen_keys:
return False
fp = norm_tokens(ex.raw_text)
if dup.seen(fp):
return False
dup.add(fp)
seen_keys.add(key)
picked.append(ex)
per_source[source] += 1
t = ex.raw_text
if OPENER.match(t):
stats["opener"] += 1
if CUE_PHRASE.search(t):
stats["cue"] += 1
if FILLER_WORD.search(t):
stats["filler"] += 1
return True
# Bucket both pools, then merge each bucket with a domain-aware interleave so
# that neither domain can dominate inside a length bucket.
pool = defaultdict(list)
for source, items in (("in_domain", indomain), ("technical_business", extra)):
for ex in items:
pool[bucket_of(ex)].append((ex, source))
for v in pool.values():
rng.shuffle(v)
def sweep(predicate, cap, label):
"""Fill from the length-matched pools until `cap` items pass `predicate`."""
# Single pass per predicate. An earlier version re-scanned the whole pool on
# every iteration, which is O(n^2) and took minutes on the 55k clean pool.
for bucket in sorted(target, reverse=True):
if len(picked) >= cap:
return
survivors = []
for ex, source in pool[bucket]:
if per_source[source] >= domain_cap:
continue
if not predicate(ex.raw_text):
survivors.append((ex, source))
continue
if take(ex, source):
target[bucket] -= 1
if target[bucket] <= 0:
break
else:
survivors.append((ex, source))
pool[bucket] = survivors
# Hardest negatives first: opener-initial, then cue phrases, then any filler,
# then plain clean so the model also sees ordinary sentences.
sweep(lambda t: bool(OPENER.match(t)), need_opener, "opener")
sweep(lambda t: bool(CUE_PHRASE.search(t)), need_cue, "cue")
sweep(lambda t: bool(FILLER_WORD.search(t)), need_filler, "filler")
sweep(lambda t: True, total, "any")
print(f" opener-initial CLEAN : {stats['opener']}/{len(picked)}"
f" (target {need_opener}, DISFLUENCY rate {round(100 * rates['opener'], 1)}%)")
print(f" cue-phrase CLEAN : {stats['cue']}/{len(picked)}"
f" (target {need_cue}, DISFLUENCY rate {round(100 * rates['cue'], 1)}%)")
print(f" any-filler CLEAN : {stats['filler']}/{len(picked)} (target {need_filler})")
print(f" domain balance: {dict(per_source)} (cap {domain_cap} each)")
return picked[:total]
# --------------------------------------------------------------------------- #
# Main
# --------------------------------------------------------------------------- #
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--dis", default="/opt/vox/sandbox/corpus/harvest_dis.jsonl")
ap.add_argument("--clean", default="/opt/vox/sandbox/corpus/harvest_clean.jsonl")
ap.add_argument("--extra-clean", default="/opt/vox/sandbox/corpus/clean_50k.jsonl")
ap.add_argument("--out", default="/opt/vox/sandbox/corpus/pilot_v2.jsonl")
ap.add_argument("--train-out", default="/opt/vox/sandbox/corpus/pilot_v2_train.jsonl")
ap.add_argument("--val-out", default="/opt/vox/sandbox/corpus/pilot_v2_val.jsonl")
ap.add_argument("--total-dis", type=int, default=2000)
ap.add_argument("--total-clean", type=int, default=2000)
ap.add_argument("--near-dup", type=float, default=0.85)
ap.add_argument("--seed", type=int, default=42)
args = ap.parse_args()
rng = random.Random(args.seed)
dup = NearDup(args.near_dup)
print("Loading DISFLUENCY (gold-annotated, single-sentence)...")
dis_items = load(args.dis)
print(f" {len(dis_items)} available")
print("Drawing DISFLUENCY by gold stratum quota...")
dis = draw_disfluency(dis_items, args.total_dis, rng, dup)
print("Loading CLEAN pools...")
indomain = load(args.clean)
extra = load(args.extra_clean)
rng.shuffle(indomain)
rng.shuffle(extra)
print(f" in-domain {len(indomain)}, technical/business {len(extra)}")
dis_lut = Counter(bucket_of(ex) for ex in dis)
rates = match_rates(dis)
print("Drawing length-matched CLEAN with DISFLUENCY-matched hard negatives...")
print(f" DISFLUENCY rates: opener {round(100 * rates['opener'], 1)}%, "
f"cue {round(100 * rates['cue'], 1)}%, filler {round(100 * rates['filler'], 1)}%")
clean = draw_clean(indomain, extra, dis_lut, args.total_clean, rng, dup, rates)
rows = dis + clean
rng.shuffle(rows)
for i, ex in enumerate(rows, 1):
ex.id = f"vxb_v2_{i:05d}"
# Deterministic 80/20 split by position; stratification holds because the
# shuffle above mixes categories and both pools were drawn independently.
train = [ex for i, ex in enumerate(rows) if i % 5 != 0]
val = [ex for i, ex in enumerate(rows) if i % 5 == 0]
cats = Counter(ex.category for ex in rows)
strata = Counter(stratum_of(ex) for ex in dis)
print(f"\nTOTAL {len(rows)} categories {dict(cats)}")
print(f"DISFLUENCY strata: {dict(strata)}")
for path, data in ((args.out, rows), (args.train_out, train), (args.val_out, val)):
with open(path, "w", encoding="utf-8") as f:
for ex in data:
f.write(json.dumps(ex.model_dump(), ensure_ascii=False) + "\n")
print(f" wrote {len(data):5d} -> {path}")
if __name__ == "__main__":
main()