onlyaady commited on
Commit
2360cda
·
verified ·
1 Parent(s): c71ef46

Add FinGuard-Privacy-Benchmark v2 dataset, card, seeds audit and scripts

Browse files
README.md ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ language:
4
+ - en
5
+ pretty_name: FinGuard-Privacy-Benchmark
6
+ size_categories:
7
+ - 1K<n<10K
8
+ task_categories:
9
+ - text-classification
10
+ tags:
11
+ - membership-inference
12
+ - privacy
13
+ - synthetic
14
+ - banking
15
+ - intent-classification
16
+ configs:
17
+ - config_name: default
18
+ default: true
19
+ data_files:
20
+ - split: train
21
+ path: data/train.parquet
22
+ - split: test
23
+ path: data/test.parquet
24
+ - config_name: full
25
+ data_files:
26
+ - split: all
27
+ path: full/dataset_v2.parquet
28
+ - config_name: seeds
29
+ data_files:
30
+ - split: all
31
+ path: seeds/seeds_audited.parquet
32
+ ---
33
+
34
+ # FinGuard-Privacy-Benchmark
35
+
36
+ A synthetic, privacy-flavoured **banking customer-support intent dataset** built to benchmark
37
+ **membership inference attacks (MIA)** such as LiRA against fine-tuned text classifiers.
38
+ It was created for CS684 Assignment 1 (Membership Inference Attacks).
39
+
40
+ - **9,120 messages, 57 intents, exactly 160 per intent.**
41
+ - **Clean labels.** Every row was independently re-labelled by a second LLM; only rows where it agreed with the intended intent are kept. No label noise was injected on purpose.
42
+ - **Fake personal details in ~35% of rows** (names, cities, amounts, dates, reference numbers, card digits, merchants). Everything is generated with Faker / an RNG. No real personal data.
43
+ - **Messy, realistic text**: typos, slang, fragments, run-ons, plus a mix of clean rows.
44
+ - **Pre-defined 1/3 – 2/3 split** for the MIA protocol: the *train* split (3,023 rows) is what a target model is trained on; the *test* split (6,097 rows) is held out and is the pool from which shadow models draw their random halves.
45
+
46
+ ## Why this dataset exists
47
+
48
+ MIA assignments need a text-classification set that (1) is privacy-relevant, (2) has clean labels, and (3) is **provably absent from the pretraining data** of the model being attacked. Banking77 is the natural candidate but has been public since 2020 and is likely inside the pretraining corpora of modern encoders such as ModernBERT (whose pretraining data is undisclosed). So instead of using Banking77 directly we use it only as *grounding*, and train/attack on **freshly generated text**.
49
+
50
+ ## How it was built
51
+
52
+ 1. **Seed pool.** Banking77 (PolyAI, CC BY 4.0), train + test pooled: 13,083 utterances.
53
+ 2. **Duplicate audit.** Strict normalisation (NFKC, casefold, alphanumerics only, so "top-up" = "top up") removes 68 rows in total, including three texts that appeared with conflicting labels (dropped entirely). An independent re-check against a second mirror (`mteb/banking77`) matched. Result: 13,015 unique seeds.
54
+ 3. **Label-noise audit of the seeds.** Three independent detectors (cleanlab confident learning on MiniLM embeddings; logistic regression on bge-small embeddings; kNN voting), plus a model-free check for near-identical texts with different labels. 209 seeds (1.6%) are flagged by at least 2 of 3 detectors. Most flagged rows are genuinely ambiguous intent pairs (e.g. `top_up_reverted` vs `top_up_failed`), not typos. See `seeds/seeds_audited.parquet`.
55
+ 4. **Clean pool and intent pruning.** Rows flagged by any detector or in a conflicting near-duplicate pair were dropped (13,015 → 12,360). Noise was concentrated in confusable intent families (transfers, top-ups, card delivery, identity verification, exchange rates), so 20 hub intents of the confusion graph were dropped, leaving 8,971 real rows over **57 intents** (`in_clean_pool=True` in the seeds file). These real rows are used only as few-shot examples for generation and as a held-out real-text check, and are **not** in the dataset.
56
+ Dropped intents: `balance_not_updated_after_bank_transfer`, `topping_up_by_card`, `card_payment_fee_charged`, `supported_cards_and_currencies`, `transfer_not_received_by_recipient`, `card_arrival`, `card_payment_wrong_exchange_rate`, `card_payment_not_recognised`, `verify_my_identity`, `reverted_card_payment?`, `beneficiary_not_allowed`, `balance_not_updated_after_cheque_or_cash_deposit`, `declined_cash_withdrawal`, `exchange_via_app`, `order_physical_card`, `compromised_card`, `top_up_by_bank_transfer_charge`, `top_up_failed`, `get_disposable_virtual_card`, `getting_spare_card`.
57
+ 5. **Generation.** `deepseek-flash` (DeepSeek-V4.1-Flash), reasoning off, few-shot with 6 real examples of the target intent, plus the names and one example of the 2 most confusable neighbouring intents as "do not write these". Two passes: a clean-style pass (~11k candidates) and a deliberately messy pass (~5k candidates). The model writes personal details only as placeholders (`{NAME}`, `{AMOUNT}`, `{CITY}`, `{DATE}`, `{REF}`, `{LAST4}`, `{MERCHANT}`).
58
+ 6. **Post-processing.** 25% of the clean-pass rows get light typo/slang/punctuation perturbation; PII placeholders are injected (safe patterns only: name greeting, reference number, city, date) until ~32% of rows have some; placeholders are filled with fresh Faker/RNG values.
59
+ 7. **Verification.** `deepseek-v4-pro` classifies every candidate among the 57 intents; a row survives only if it picks the intended one. Agreement on the 16,217 candidates: 99.0% (clean 99.5%, LLM-messy 99.6%, perturbed 96.5%). Calibration: the same verifier scores **93.2% on 400 held-out real Banking77 rows**, i.e. real text is much more ambiguous than the synthetic text.
60
+ 8. **Deduplication and balancing.** Exact and near-duplicate (bge-small cosine ≥ 0.96 within an intent) removal, removal of anything ≥ 0.97 similar to any real Banking77 row, removal of degenerate generations (> 100 words), then balancing to 160 rows per intent (up to 64 messy-LLM rows per intent first, so the mix is ~40% messy).
61
+ 9. **Split.** Stratified 1/3 train, 2/3 test per intent. Clusters of near-duplicates (cosine ≥ 0.95) are kept on the same side, so no near-duplicate pair crosses the split.
62
+
63
+ All generation and verification code is in `scripts/` (API keys are read from the environment, none are stored here).
64
+
65
+ ## Data fields
66
+
67
+ `default` config (`train`, `test`):
68
+
69
+ | field | type | description |
70
+ |---|---|---|
71
+ | `text` | string | the customer message, with fake personal details filled in |
72
+ | `text_template` | string | same message with `{PLACEHOLDER}` slots, as generated |
73
+ | `intent` | string | intent name (57 classes) |
74
+ | `label` | int | integer id of the intent (sorted alphabetically, ASCII order) |
75
+ | `has_pii` | bool | message contains fake personal details |
76
+ | `pii_types` | list[string] | any of `name, amount, location, date, reference, card_digits, merchant` |
77
+ | `noise_type` | string | `clean`, `perturbed` (programmatic typos) or `llm_noisy` (messy LLM pass) |
78
+
79
+ `full` config: the same rows in one file with an extra `split` column (`train` / `test`).
80
+ `seeds` config: the 13,015 deduplicated real Banking77 rows with the detector flags (`suspect_cleanlab`, `suspect_lr_bge`, `suspect_knn_bge`, `votes`, `suspect_consensus`, `in_clean_pool`), included to document the grounding.
81
+
82
+ ## Statistics
83
+
84
+ | | |
85
+ |---|---|
86
+ | rows | 9,120 (train 3,023 / test 6,097) |
87
+ | intents | 57 × 160 rows |
88
+ | `noise_type` | clean 4,043 · llm_noisy 3,637 · perturbed 1,440 |
89
+ | rows with fake PII | 34.7% |
90
+ | words per message | mean 16.3, median 14, p10 6, p90 31, max 80 |
91
+ | bge-small + logistic regression, 5-fold CV accuracy | 97.8% (real Banking77 is about 93%) |
92
+
93
+ ## Intended use
94
+
95
+ Benchmarking membership inference attacks (LOSS, LiRA offline/online, etc.) and their ablations (number of shadow models, over/under-fitting, signal choice) on fine-tuned text classifiers, and studying how memorisation depends on personal-detail content and text noise.
96
+
97
+ ## Limitations and caveats
98
+
99
+ - **Easier than real data.** Confusable intents are cleanly separated in the generated text (verifier agreement 99% vs 93% on real text; simple classifier 97.8% CV accuracy). Expect strong classifiers to score very high, and expect weaker per-example signal for MIA than on natural data.
100
+ - **Same-family bias.** The generator and the verifier are both DeepSeek models, so shared stylistic and semantic biases can pass verification.
101
+ - **Synthetic messiness ≠ real messiness.** Typos and slang are LLM- or rule-generated; some injected personal details read slightly oddly (e.g. a city name in a sentence that does not need one).
102
+ - **Clean labels by design.** Label-noise/mislabelled-record analyses can only use the real seed file, not this dataset.
103
+ - **Not a privacy guarantee.** All personal details are fake, but generated text may resemble real messages. Do not treat the data as a source of real customer behaviour.
104
+ - **Pretraining contamination.** The messages were generated in September 2026 and cannot appear in the pretraining data of models released before that (e.g. ModernBERT, BERT, RoBERTa). Once this dataset is public, models trained afterwards may see it; use models that predate the release when you need the non-contamination property.
105
+
106
+ ## Licence and attribution
107
+
108
+ CC BY 4.0. The seed rows in `seeds/` and the few-shot grounding come from **Banking77** (Casanueva et al., 2020, *Efficient Intent Detection with Dual Sentence Encoders*), released under CC BY 4.0. Synthetic text was produced with DeepSeek models; check the provider's terms for downstream use of generated outputs.
data/test.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c3d4d7f430baf6346c9fe85220b9f79de23da0ced00b1ab78a2524f762798b91
3
+ size 538322
data/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e41f9a07533a221aa4c9d017fc314ac41d16bbda635d0e58750b585010b0b77
3
+ size 276923
full/dataset_v2.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e67543f91b473472150ccf0f83ada820b0282ccbf8aaead85e6e0e0abc01568
3
+ size 790168
scripts/build_dataset.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verified synthetic rows -> deduped, balanced, PII-filled dataset with a stratified 1/3 train / 2/3 test split
2
+ in which near-duplicate clusters never cross the split."""
3
+ import argparse, re, random, unicodedata
4
+ import numpy as np, pandas as pd
5
+ from faker import Faker
6
+ from sentence_transformers import SentenceTransformer
7
+
8
+ TYPES = {"NAME": "name", "AMOUNT": "amount", "LAST4": "card_digits", "MERCHANT": "merchant", "CITY": "location", "DATE": "date", "REF": "reference"}
9
+ MERCHANTS = ["Amazon", "Starbucks", "Tesco", "Uber", "Netflix", "Spotify", "Walmart", "Target", "IKEA", "Zara", "Airbnb", "Apple Store",
10
+ "Best Buy", "Lidl", "Deliveroo", "Ryanair", "Booking.com", "Nike", "eBay", "Shell"]
11
+
12
+ def strict(s):
13
+ return re.sub(r"[\W_]+", "", unicodedata.normalize("NFKC", s).casefold())
14
+
15
+ def fill(t, fk, rng):
16
+ """Fresh fake values per placeholder occurrence (Faker + RNG only; nothing real)."""
17
+ gen = {"NAME": lambda: fk.first_name() if rng.random() < 0.6 else fk.name(),
18
+ "AMOUNT": lambda: rng.choice(["£", "£", "£", "$", "€", ""]) + str(rng.choice([rng.randint(5, 99), rng.randint(100, 999), round(rng.uniform(5, 900), 2)])),
19
+ "LAST4": lambda: f"{rng.randint(0, 9999):04d}", "MERCHANT": lambda: rng.choice(MERCHANTS), "CITY": fk.city,
20
+ "DATE": lambda: rng.choice([fk.date_object().strftime("%d/%m"), fk.date_object().strftime("%-d %B"), f"the {rng.randint(1, 28)}th"]),
21
+ "REF": lambda: rng.choice([f"TXN-{rng.randint(100000, 999999)}", f"{rng.randint(10**7, 10**8 - 1)}", f"REF{rng.randint(1000, 9999)}X"])}
22
+ return re.sub(r"\{(\w+)\}", lambda m: str(gen[m.group(1)]()), t)
23
+
24
+ def components(E, thr):
25
+ """Connected components of the cosine >= thr graph (union-find)."""
26
+ par = list(range(len(E)))
27
+ def f(x):
28
+ while par[x] != x: par[x] = par[par[x]]; x = par[x]
29
+ return x
30
+ S = E @ E.T
31
+ for i, j in zip(*np.where(np.triu(S >= thr, 1))): par[f(i)] = f(j)
32
+ return np.array([f(i) for i in range(len(E))])
33
+
34
+ def main():
35
+ ap = argparse.ArgumentParser()
36
+ ap.add_argument("--inp", default="data/synth_verified.jsonl")
37
+ ap.add_argument("--out", default="data/dataset.parquet")
38
+ ap.add_argument("--per-intent", type=int, default=160)
39
+ ap.add_argument("--noisy-quota", type=int, default=0, help="per intent, take up to this many llm_noisy rows first")
40
+ ap.add_argument("--sim", type=float, default=0.96, help="within-synthetic near-duplicate cosine threshold (bge)")
41
+ ap.add_argument("--real-sim", type=float, default=0.97, help="drop synthetic rows this close to any real seed")
42
+ ap.add_argument("--split-sim", type=float, default=0.95, help="rows this similar are kept on the same side of the split")
43
+ ap.add_argument("--max-words", type=int, default=100, help="drop degenerate generations (e.g. several messages concatenated)")
44
+ ap.add_argument("--seed", type=int, default=0)
45
+ a = ap.parse_args()
46
+ rng, fk = random.Random(a.seed), Faker("en_US"); Faker.seed(a.seed)
47
+ slots = set(TYPES)
48
+
49
+ df = pd.read_json(a.inp, lines=True)
50
+ if "noise_type" not in df: df["noise_type"] = "clean"
51
+ n0 = len(df)
52
+ df = df[df.verified]; n_ver = len(df)
53
+ df = df[df.text.str.split().str.len() <= a.max_words]
54
+ df = df[df.text.map(lambda t: set(re.findall(r"\{(\w+)\}", t)) <= slots)]; n_slot = len(df)
55
+ real = pd.read_parquet("data/seeds_audited.parquet") # ALL real seeds, incl. dropped ones
56
+ df = df[~df.text.map(strict).isin(set(real.text.map(strict)))]
57
+ df = df.assign(k=df.text.map(strict)).drop_duplicates("k").drop(columns="k").sample(frac=1, random_state=a.seed).reset_index(drop=True); n_exact = len(df)
58
+
59
+ m = SentenceTransformer("BAAI/bge-small-en-v1.5")
60
+ E = m.encode(df.text.tolist(), batch_size=256, normalize_embeddings=True)
61
+ R = m.encode(real.text.tolist(), batch_size=256, normalize_embeddings=True)
62
+ keep = np.ones(len(df), bool)
63
+ keep &= (E @ R.T).max(1) < a.real_sim # too close to a real seed
64
+ for i, g in df.groupby("intent").indices.items(): # greedy near-dup removal within intent
65
+ kept = []
66
+ for j in g:
67
+ if not keep[j]: continue
68
+ if kept and (E[kept] @ E[j]).max() >= a.sim: keep[j] = False
69
+ else: kept.append(j)
70
+ df = df[keep].assign(ei=np.where(keep)[0]); n_near = len(df)
71
+
72
+ parts = []
73
+ for _, g in df.groupby("intent"):
74
+ nz = g[g.noise_type == "llm_noisy"].head(a.noisy_quota)
75
+ parts.append(pd.concat([nz, g.drop(nz.index)]).head(a.per_intent))
76
+ df = pd.concat(parts).reset_index(drop=True)
77
+
78
+ df["text_template"] = df.text
79
+ df["pii_types"] = df.text.map(lambda t: sorted({TYPES[s] for s in re.findall(r"\{(\w+)\}", t)}))
80
+ df["has_pii"] = df.pii_types.map(len) > 0
81
+ df["text"] = [fill(t, fk, rng) for t in df.text]
82
+ df["label"] = df.intent.astype("category").cat.codes
83
+
84
+ # stratified 1/3 train / 2/3 test; near-dup clusters (cos >= split-sim) move together
85
+ df["split"] = "test"
86
+ for _, g in df.groupby("intent"):
87
+ comp = components(E[g.ei.values], a.split_sim)
88
+ cids = list(dict.fromkeys(comp)); rng.shuffle(cids)
89
+ want, got = round(len(g) / 3), 0
90
+ for c in cids:
91
+ n = int((comp == c).sum())
92
+ if got >= want: break
93
+ if got + n > want + 2: continue # don't let a big cluster overshoot the quota
94
+ df.loc[g.index[comp == c], "split"] = "train"; got += n
95
+ cross = 0 # audit: any cross-split pair above split-sim?
96
+ for _, g in df.groupby("intent"):
97
+ S = E[g.ei.values] @ E[g.ei.values].T; sp = (g.split == "train").values
98
+ cross += int(((S >= a.split_sim) & (sp[:, None] != sp[None, :])).sum() // 2)
99
+ df[["text", "text_template", "intent", "label", "has_pii", "pii_types", "noise_type", "split"]].to_parquet(a.out)
100
+ print(f"generated {n0} -> verified {n_ver} -> valid slots {n_slot} -> exact-dedup/not-in-real {n_exact} -> near-dedup {n_near} -> balanced {len(df)}")
101
+ print(f"intents={df.intent.nunique()} per-intent min/max={df.intent.value_counts().min()}/{df.intent.value_counts().max()} "
102
+ f"has_pii={df.has_pii.mean():.1%} train={int((df.split=='train').sum())} test={int((df.split=='test').sum())} "
103
+ f"cross-split pairs >= {a.split_sim}: {cross}")
104
+ print("noise_type:", df.noise_type.value_counts().to_dict(), "| pii_types:", df.pii_types.explode().value_counts().to_dict())
105
+
106
+ if __name__ == "__main__":
107
+ main()
scripts/gen_synthetic.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate synthetic banking queries per intent with DeepSeek, seeded with real clean-pool examples."""
2
+ import argparse, json, os, random, threading
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ import numpy as np, pandas as pd
5
+ from llm import chat_json, usage_line
6
+
7
+ SYSTEM = """You write realistic customer messages sent to a retail bank's support chat. Given a target intent, real examples of it, and confusable OTHER intents, write NEW messages that clearly express ONLY the target intent.
8
+ Rules:
9
+ - Every message must be unmistakably about the target intent and must NOT be answerable as any of the confusable other intents.
10
+ - Do not copy or lightly paraphrase the examples; vary wording, structure, length, tone, typos and punctuation as instructed by the style hint.
11
+ - About 1 in 3 messages should include personal details, written ONLY as these placeholders (never real-looking values): {NAME} {AMOUNT} {LAST4} {MERCHANT} {CITY}. The rest must have no personal details and no placeholders.
12
+ - One message per string, no numbering, no quotes inside unless natural.
13
+ Return JSON: {"q": ["...", ...]}"""
14
+
15
+ STYLES = ["very short and terse (3-8 words)", "one casual sentence, lowercase, a typo or two", "polite and formal, 1-2 sentences",
16
+ "frustrated or worried, 2 sentences", "a question phrased indirectly", "detailed, gives the backstory, 2-3 sentences",
17
+ "non-native English speaker phrasing", "mix of short and medium messages"]
18
+
19
+ SYSTEM_NOISY = """You write realistic, MESSY customer messages sent to a retail bank's support chat, typed quickly on a phone. Given a target intent, real examples of it, and confusable OTHER intents, write NEW messages that clearly express ONLY the target intent.
20
+ Rules:
21
+ - Every message must still be unmistakably about the target intent and must NOT be answerable as any confusable other intent.
22
+ - Do NOT write polished, grammatically perfect sentences. Do not copy the examples.
23
+ - Follow the mess hint for the whole batch, but mix in variety: about 30% with typos or misspellings, about 20% very short (under 8 words), about 15% rambling run-ons, some with slang ("pls", "thx", "idk", "gonna", "bc"), some with no punctuation or "!!!" / "???", occasional mixed register.
24
+ - About 1 in 3 messages should include personal details, written ONLY as these placeholders (never real-looking values): {NAME} {AMOUNT} {LAST4} {MERCHANT} {CITY} {DATE} {REF}. Use a placeholder only where it fits the message naturally. The rest must have no placeholders.
25
+ - One message per string, no numbering.
26
+ Return JSON: {"q": ["...", ...]}"""
27
+
28
+ MESS = ["heavy typos and misspellings", "very short fragments, under 8 words", "rambling run-on sentences with backstory",
29
+ "texting slang and abbreviations, no punctuation", "frustrated, caps and !!! and ???", "mixed formal and rude register",
30
+ "odd or unusual word choices, non-native phrasing", "incomplete sentences and trailing off"]
31
+
32
+ def neighbors(intents):
33
+ seeds = pd.read_parquet("data/seeds_audited.parquet")
34
+ emb = np.load("data/seed_emb_bge.npy")
35
+ cent = {i: emb[(seeds.intent == i).values].mean(0) for i in seeds.intent.unique()}
36
+ for k in cent: cent[k] /= np.linalg.norm(cent[k])
37
+ out = {}
38
+ for i in intents:
39
+ sims = sorted(((float(cent[i] @ cent[j]), j) for j in intents if j != i), reverse=True)
40
+ out[i] = [j for _, j in sims[:2]]
41
+ return out
42
+
43
+ def main():
44
+ ap = argparse.ArgumentParser()
45
+ ap.add_argument("--per-intent", type=int, default=195)
46
+ ap.add_argument("--batch", type=int, default=15)
47
+ ap.add_argument("--intents", type=int, default=0, help="pilot: only first N intents")
48
+ ap.add_argument("--workers", type=int, default=12)
49
+ ap.add_argument("--out", default="data/synth_raw.jsonl")
50
+ ap.add_argument("--noisy", action="store_true", help="messy-style prompt with extra PII slots")
51
+ a = ap.parse_args()
52
+
53
+ pool = pd.read_parquet("data/clean_pool.parquet")
54
+ intents = sorted(pool.intent.unique())
55
+ nb = neighbors(intents)
56
+ by = {i: pool[pool.intent == i].text.tolist() for i in intents}
57
+ todo_intents = intents[: a.intents] if a.intents else intents
58
+ have = {i: 0 for i in intents}
59
+ if os.path.exists(a.out):
60
+ for l in open(a.out): have[json.loads(l)["intent"]] += 1
61
+ jobs = []
62
+ for i in todo_intents:
63
+ for _ in range(max(0, -(-(a.per_intent - have[i]) // a.batch))): jobs.append(i)
64
+ print(f"{len(jobs)} calls planned", flush=True)
65
+ lock, f = threading.Lock(), open(a.out, "a")
66
+
67
+ def run(intent):
68
+ rng = random.Random()
69
+ ex = rng.sample(by[intent], min(6, len(by[intent])))
70
+ user = (f"Target intent: {intent}\nReal examples:\n" + "\n".join(f"- {s}" for s in ex) +
71
+ "\nConfusable OTHER intents (do NOT write these):\n" +
72
+ "\n".join(f"- {n}, e.g. \"{rng.choice(by[n])}\"" for n in nb[intent]) +
73
+ f"\n\n{'Mess hint' if a.noisy else 'Style hint'}: {rng.choice(MESS if a.noisy else STYLES)}\nWrite {a.batch} new messages.")
74
+ qs = chat_json("deepseek-flash", SYSTEM_NOISY if a.noisy else SYSTEM, user, max_tokens=1500).get("q", [])
75
+ with lock:
76
+ for q in qs:
77
+ if isinstance(q, str) and q.strip(): f.write(json.dumps({"intent": intent, "text": q.strip()}) + "\n")
78
+ f.flush()
79
+
80
+ with ThreadPoolExecutor(a.workers) as ex: list(ex.map(run, jobs))
81
+ print(usage_line())
82
+
83
+ if __name__ == "__main__":
84
+ main()
scripts/llm.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Minimal DeepSeek chat client: reasoning off, JSON output, retries, token accounting."""
2
+ import json, os, threading, time
3
+ import requests
4
+
5
+ URL = "https://api.deepseek.com/chat/completions"
6
+ _lock = threading.Lock()
7
+ USAGE = {"prompt": 0, "cache_hit": 0, "completion": 0, "calls": 0}
8
+
9
+ def chat_json(model, system, user, max_tokens=1200, temperature=1.0, retries=6):
10
+ body = {"model": model, "temperature": temperature, "max_tokens": max_tokens,
11
+ "thinking": {"type": "disabled"}, "response_format": {"type": "json_object"},
12
+ "messages": [{"role": "system", "content": system}, {"role": "user", "content": user}]}
13
+ for k in range(retries):
14
+ try:
15
+ r = requests.post(URL, headers={"Authorization": "Bearer " + os.environ["DEEPSEEK_API_KEY"]}, json=body, timeout=180)
16
+ if r.status_code == 200:
17
+ j = r.json()
18
+ u = j["usage"]
19
+ with _lock:
20
+ USAGE["prompt"] += u["prompt_tokens"]; USAGE["completion"] += u["completion_tokens"]
21
+ USAGE["cache_hit"] += u.get("prompt_cache_hit_tokens", 0); USAGE["calls"] += 1
22
+ return json.loads(j["choices"][0]["message"]["content"])
23
+ if r.status_code not in (429, 500, 502, 503, 504): raise RuntimeError(f"{r.status_code}: {r.text[:200]}")
24
+ except (requests.RequestException, json.JSONDecodeError):
25
+ pass
26
+ time.sleep(2 ** k)
27
+ raise RuntimeError("LLM call failed after retries")
28
+
29
+ def usage_line():
30
+ u = USAGE
31
+ return f"calls={u['calls']} prompt={u['prompt']} (cached {u['cache_hit']}) completion={u['completion']}"
scripts/make_candidates.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """v2 candidates: clean v1 rows (25% perturbed) + messy LLM rows, then PII injected up to a target rate. Labels are never touched."""
2
+ import argparse, json, random, re
3
+ import pandas as pd
4
+
5
+ SLANG = [("please", "pls"), ("thanks", "thx"), ("because", "bc"), ("going to", "gonna"), ("want to", "wanna"), ("do not", "dont"),
6
+ ("cannot", "cant"), ("i am", "im"), ("you are", "ur"), ("what is", "whats"), ("i have", "ive"), ("my account", "my acct")]
7
+ PREFIX = ["Hi, I'm {NAME}. ", "Hello, this is {NAME}. ", "{NAME} here. ", "hi its {NAME}, ", "Hi, {NAME} speaking. "]
8
+ SUFFIX = [" My ref is {REF}.", " ref {REF}", " (account holder {NAME})", " I'm in {CITY} at the moment.", " This was on {DATE}.", " Ref: {REF}"]
9
+ TYPES = {"NAME": "name", "AMOUNT": "amount", "LAST4": "card_digits", "MERCHANT": "merchant", "CITY": "location", "DATE": "date", "REF": "reference"}
10
+
11
+ def perturb(text, rng):
12
+ """Light input noise: slang, typos, dropped word/punctuation, casing. Placeholders are never touched."""
13
+ for f, s in SLANG:
14
+ if rng.random() < 0.35: text = re.sub(rf"\b{f}\b", s, text, flags=re.I)
15
+ w = text.split()
16
+ for _ in range(rng.choice([1, 1, 2, 3])):
17
+ i = rng.randrange(len(w))
18
+ t = w[i]
19
+ if "{" in t or len(t) < 4: continue
20
+ j = rng.randrange(1, len(t) - 1)
21
+ op = rng.choice(["swap", "drop", "dup"])
22
+ w[i] = t[:j] + t[j + 1] + t[j] + t[j + 2:] if op == "swap" else t[:j] + t[j + 1:] if op == "drop" else t[:j] + t[j] + t[j:]
23
+ k = rng.randrange(1, len(w) - 1) if len(w) > 5 else 0
24
+ if k and rng.random() < 0.3 and "{" not in w[k]: w.pop(k)
25
+ text = " ".join(w)
26
+ if rng.random() < 0.4: text = text.rstrip("?.!")
27
+ if rng.random() < 0.35 and "{" not in text: text = text.lower()
28
+ return text
29
+
30
+ def inject(text, rng):
31
+ if rng.random() < 0.5: return rng.choice(PREFIX) + (text if rng.random() < 0.5 else text[0].lower() + text[1:])
32
+ return text.rstrip() + rng.choice(SUFFIX)
33
+
34
+ def main():
35
+ ap = argparse.ArgumentParser()
36
+ ap.add_argument("--perturb-frac", type=float, default=0.25)
37
+ ap.add_argument("--pii-target", type=float, default=0.32)
38
+ ap.add_argument("--seed", type=int, default=0)
39
+ ap.add_argument("--out", default="data/cand_v2.jsonl")
40
+ a = ap.parse_args()
41
+ rng = random.Random(a.seed)
42
+
43
+ clean = pd.read_json("data/synth_verified.jsonl", lines=True)
44
+ clean = clean[clean.verified][["intent", "text"]].assign(noise_type="clean")
45
+ noisy = pd.read_json("data/synth_raw_v2.jsonl", lines=True).assign(noise_type="llm_noisy")
46
+ pert = clean.sample(frac=a.perturb_frac, random_state=a.seed)
47
+ clean = clean.drop(pert.index)
48
+ pert = pert.assign(text=[perturb(t, rng) for t in pert.text], noise_type="perturbed")
49
+ df = pd.concat([clean, pert, noisy], ignore_index=True)
50
+
51
+ has = df.text.str.contains(r"\{\w+\}")
52
+ need = int(a.pii_target * len(df)) - int(has.sum())
53
+ cand = df.index[~has].tolist()
54
+ rng.shuffle(cand)
55
+ for i in cand[:max(0, need)]: df.at[i, "text"] = inject(df.at[i, "text"], rng)
56
+ after = df.text.str.contains(r"\{\w+\}").mean()
57
+ print(f"rows={len(df)} noise_type={df.noise_type.value_counts().to_dict()} pii_rate {has.mean():.1%} -> {after:.1%}")
58
+ df.to_json(a.out, orient="records", lines=True)
59
+
60
+ if __name__ == "__main__":
61
+ main()
scripts/prep_seeds.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pool Banking77, dedup, and flag likely-mislabeled seeds via cross-validated confident learning."""
2
+ import re
3
+ import unicodedata
4
+ import numpy as np
5
+ import pandas as pd
6
+ from datasets import load_dataset
7
+ from sentence_transformers import SentenceTransformer
8
+ from sklearn.linear_model import LogisticRegression
9
+ from sklearn.model_selection import cross_val_predict, StratifiedKFold
10
+ from cleanlab.filter import find_label_issues
11
+
12
+ def norm(s):
13
+ """NFKC + casefold + keep alphanumerics only (no spaces), so 'top-up' == 'top up' == 'topup'."""
14
+ return re.sub(r"[\W_]+", "", unicodedata.normalize("NFKC", s).casefold())
15
+
16
+ def main():
17
+ ds = load_dataset("legacy-datasets/banking77")
18
+ names = ds["train"].features["label"].names
19
+ df = pd.concat([ds["train"].to_pandas().assign(orig_split="train"),
20
+ ds["test"].to_pandas().assign(orig_split="test")], ignore_index=True)
21
+ df["intent"] = df["label"].map(dict(enumerate(names)))
22
+ df["norm"] = df["text"].map(norm)
23
+ print(f"pooled: {len(df)}")
24
+
25
+ # exact duplicates after normalization; report label conflicts (same text, different intent)
26
+ grp = df.groupby("norm")["label"].nunique()
27
+ print(f"norm-duplicate groups: {(df.duplicated('norm', keep=False)).sum()} rows, "
28
+ f"{(grp > 1).sum()} texts with conflicting labels")
29
+ df = df[~df["norm"].isin(grp[grp > 1].index)] # ambiguous text: drop entirely
30
+ df = df.drop_duplicates("norm", keep="first").reset_index(drop=True)
31
+ print(f"after exact dedup: {len(df)}")
32
+
33
+ emb = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2").encode(
34
+ df["text"].tolist(), batch_size=256, normalize_embeddings=True, show_progress_bar=False)
35
+ probs = cross_val_predict(LogisticRegression(max_iter=2000, C=10), emb, df["label"],
36
+ cv=StratifiedKFold(5, shuffle=True, random_state=0), method="predict_proba")
37
+ issues = find_label_issues(df["label"].values, probs, return_indices_ranked_by="self_confidence")
38
+ df["suspect"] = False
39
+ df.loc[issues, "suspect"] = True
40
+ df["cv_pred"] = probs.argmax(1)
41
+ df["cv_conf_true"] = probs[np.arange(len(df)), df["label"]]
42
+ print(f"suspect seeds: {df.suspect.sum()} ({df.suspect.mean():.1%})")
43
+ print("top intents by suspect rate:\n", df.groupby("intent").suspect.mean().sort_values(ascending=False).head(8).round(2))
44
+ df.drop(columns=["label"]).assign(label=df["label"]).to_parquet("data/seeds.parquet")
45
+ np.save("data/seed_emb.npy", emb)
46
+
47
+
48
+ if __name__ == "__main__":
49
+ main()
scripts/select_clean.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the clean real-seed pool (~9k): drop noisy/conflicting rows, then prune hub intents of the confusion graph."""
2
+ import sys
3
+ from collections import Counter
4
+ import numpy as np, pandas as pd
5
+ from sklearn.feature_extraction.text import TfidfVectorizer
6
+ from sklearn.neighbors import NearestNeighbors
7
+
8
+ TARGET = int(sys.argv[1]) if len(sys.argv) > 1 else 9000
9
+
10
+ def main():
11
+ d = pd.read_parquet("data/seeds_audited.parquet")
12
+ d["votes"] = d.suspect.astype(int) + d.lr_bad.astype(int) + d.knn_bad.astype(int)
13
+ p = np.load("data/seed_cvprob_bge.npy")
14
+ d["cv_pred"] = p.argmax(1)
15
+
16
+ # row-level: any detector flag, or in a near-duplicate pair with a different label
17
+ X = TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 5), sublinear_tf=True).fit_transform(d.text.str.lower())
18
+ dist, idx = NearestNeighbors(n_neighbors=4, metric="cosine").fit(X).kneighbors(X)
19
+ conflict = np.zeros(len(d), bool)
20
+ for i in range(len(d)):
21
+ for dj, j in zip(dist[i, 1:], idx[i, 1:]):
22
+ if 1 - dj >= 0.85 and d.label.values[i] != d.label.values[j]: conflict[i] = conflict[j] = True
23
+ d["conflict_nd"] = conflict
24
+ keep = d[(d.votes == 0) & ~d.conflict_nd].copy()
25
+ print(f"row-level: {len(d)} -> {len(keep)} (flagged {int((d.votes>0).sum())}, conflicting near-dup {int(conflict.sum())})")
26
+
27
+ # intent-level: confusion graph from CV predictions on the rows we kept; drop hub intents greedily
28
+ kk = keep[keep.cv_pred != keep.label]
29
+ mass = Counter()
30
+ edges = Counter()
31
+ for a, b in zip(kk.intent, kk.cv_pred.map(dict(zip(d.label, d.intent)))):
32
+ edges[a] += 1; edges[b] += 1; mass[tuple(sorted((a, b)))] += 1
33
+ dropped = []
34
+ while len(keep) > TARGET:
35
+ deg = Counter()
36
+ for (a, b), n in mass.items(): deg[a] += n; deg[b] += n
37
+ if not deg: break
38
+ worst = deg.most_common(1)[0][0]
39
+ dropped.append((worst, int(deg[worst]), int((keep.intent == worst).sum())))
40
+ keep = keep[keep.intent != worst]
41
+ mass = Counter({k: v for k, v in mass.items() if worst not in k})
42
+ print(f"intent-level: dropped {len(dropped)} intents -> {len(keep)} rows, {keep.intent.nunique()} intents")
43
+ for n, m, r in dropped: print(f" drop {n:45s} confusion={m:3d} rows={r}")
44
+ keep.drop(columns=["cv_pred"]).to_parquet("data/clean_pool.parquet")
45
+ print("per-intent rows: min", keep.intent.value_counts().min(), "max", keep.intent.value_counts().max())
46
+
47
+ if __name__ == "__main__":
48
+ main()
scripts/verify_seeds.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent audit of data/seeds.parquet: different source, normalization, and detectors than prep_seeds.py."""
2
+ import re, unicodedata, itertools
3
+ import numpy as np, pandas as pd
4
+ from huggingface_hub import hf_hub_download
5
+ from sklearn.feature_extraction.text import TfidfVectorizer
6
+ from sklearn.neighbors import NearestNeighbors
7
+ from sklearn.linear_model import LogisticRegression
8
+ from sklearn.model_selection import cross_val_predict, StratifiedKFold
9
+ from sentence_transformers import SentenceTransformer
10
+
11
+ def strict(s): # NFKC + casefold + alnum only (no spaces at all)
12
+ return re.sub(r"[\W_]+", "", unicodedata.normalize("NFKC", s).casefold())
13
+
14
+ def main():
15
+ # ---- independent source: mteb/banking77 jsonl
16
+ raw = pd.concat([pd.read_json(hf_hub_download("mteb/banking77", f"{s}.jsonl", repo_type="dataset"), lines=True).assign(orig_split=s)
17
+ for s in ("train", "test")], ignore_index=True)
18
+ print("mteb columns:", list(raw.columns), "rows:", len(raw))
19
+ raw = raw.rename(columns={c: "intent" for c in raw.columns if c in ("label_text", "intent")})
20
+ saved = pd.read_parquet("data/seeds.parquet")
21
+
22
+ print("\n== 1. SOURCE CROSS-CHECK")
23
+ a, b = set(map(strict, raw["text"])), set(map(strict, saved["text"]))
24
+ print(f"unique(strict) mteb={len(a)} saved={len(b)} only-in-mteb={len(a-b)} only-in-saved={len(b-a)}")
25
+
26
+ print("\n== 2. EXACT DUPLICATES (strict norm, space-free)")
27
+ print("saved rows:", len(saved), " unique strict:", saved["text"].map(strict).nunique())
28
+ print("saved unique bag-of-words (order-insensitive):", saved["text"].map(lambda s: " ".join(sorted(re.findall(r"\w+", s.lower())))).nunique())
29
+ d = raw[raw["text"].map(strict).duplicated(keep=False)]
30
+ print(f"raw dup rows: {len(d)}; spanning train/test: {d.groupby(d['text'].map(strict)).orig_split.nunique().gt(1).sum()} groups; label-conflicting:",
31
+ d.groupby(d['text'].map(strict)).intent.nunique().gt(1).sum())
32
+
33
+ print("\n== 3. NEAR DUPLICATES (char 3-5gram TF-IDF cosine) in saved set")
34
+ X = TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 5), sublinear_tf=True).fit_transform(saved["text"].str.lower())
35
+ nn = NearestNeighbors(n_neighbors=4, metric="cosine").fit(X)
36
+ dist, idx = nn.kneighbors(X)
37
+ pairs = {}
38
+ for i in range(len(saved)):
39
+ for dj, j in zip(dist[i, 1:], idx[i, 1:]):
40
+ sim = 1 - dj
41
+ if sim >= 0.85 and i != j: pairs[tuple(sorted((i, j)))] = sim
42
+ P = pd.DataFrame([(i, j, s) for (i, j), s in pairs.items()], columns=["i", "j", "sim"])
43
+ P["same_label"] = saved.label.values[P.i] == saved.label.values[P.j]
44
+ P["cross_split"] = saved.orig_split.values[P.i] != saved.orig_split.values[P.j]
45
+ for t in (0.85, 0.9, 0.95):
46
+ q = P[P.sim >= t]
47
+ print(f"sim>={t}: {len(q)} pairs | cross orig train/test: {q.cross_split.sum()} | DIFFERENT labels: {(~q.same_label).sum()}")
48
+ diff = P[~P.same_label].sort_values("sim", ascending=False)
49
+ print("\n-- near-identical pairs with DIFFERENT labels (model-free evidence of ambiguity):")
50
+ for _, r in diff.head(15).iterrows():
51
+ print(f" {r.sim:.2f} | {saved.text[r.i]!r} [{saved.intent[r.i]}] <-> {saved.text[r.j]!r} [{saved.intent[r.j]}]")
52
+ print(f"total conflicting near-dup pairs @0.85: {len(diff)}; distinct rows involved: {len(set(diff.i)|set(diff.j))}")
53
+
54
+ print("\n== 4. INDEPENDENT LABEL AUDIT")
55
+ emb = SentenceTransformer("BAAI/bge-small-en-v1.5").encode(saved["text"].tolist(), batch_size=256, normalize_embeddings=True)
56
+ y = saved.label.values
57
+ cv = StratifiedKFold(5, shuffle=True, random_state=123)
58
+ p_lr = cross_val_predict(LogisticRegression(max_iter=3000, C=20), emb, y, cv=cv, method="predict_proba")
59
+ # kNN vote (k=10, leave-self-out) as a second, non-parametric detector
60
+ knn = NearestNeighbors(n_neighbors=11, metric="cosine").fit(emb)
61
+ _, kidx = knn.kneighbors(emb)
62
+ vote_true = np.array([(y[kidx[i, 1:]] == y[i]).mean() for i in range(len(y))])
63
+ lr_bad = p_lr[np.arange(len(y)), y] < 0.1
64
+ knn_bad = vote_true == 0
65
+ both = lr_bad & knn_bad
66
+ prev = saved.suspect.values
67
+ print(f"LR(bge) true-label prob<0.1: {lr_bad.sum()} | kNN 0/10 neighbours agree: {knn_bad.sum()} | both: {both.sum()}")
68
+ print(f"previous flags (cleanlab+MiniLM): {prev.sum()} | overlap with 'both': {(prev & both).sum()} | overlap with either: {(prev & (lr_bad | knn_bad)).sum()}")
69
+ # original protocol check: train on original train, predict original test
70
+ tr, te = (saved.orig_split == "train").values, (saved.orig_split == "test").values
71
+ clf = LogisticRegression(max_iter=3000, C=20).fit(emb[tr], y[tr])
72
+ print(f"train->test accuracy (bge+LR): {(clf.predict(emb[te]) == y[te]).mean():.3f} (a very low value would signal noisy test labels)")
73
+
74
+ print("\n-- 25 random rows flagged by BOTH new detectors (read them yourself):")
75
+ names = saved.intent.values
76
+ cls = dict(zip(saved.label, saved.intent))
77
+ for i in np.random.default_rng(0).permutation(np.where(both)[0])[:25]:
78
+ print(f" {saved.text[i]!r} labeled={names[i]} model says={cls[p_lr[i].argmax()]} prev_flag={prev[i]}")
79
+ print("\n-- 10 random rows flagged by previous pass but NOT by new detectors:")
80
+ for i in np.random.default_rng(1).permutation(np.where(prev & ~(lr_bad | knn_bad))[0])[:10]:
81
+ print(f" {saved.text[i]!r} labeled={names[i]} model says={cls[p_lr[i].argmax()]}")
82
+ out = saved.assign(lr_bad=lr_bad, knn_bad=knn_bad, both_bad=both)
83
+ out.to_parquet("data/seeds_audited.parquet")
84
+
85
+ if __name__ == "__main__":
86
+ main()
scripts/verify_synthetic.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent label check: deepseek-v4-pro classifies each generated query among the intents; keep only agreeing rows.
2
+ Also calibrates the verifier on held-out REAL rows so we know its ceiling."""
3
+ import argparse, json
4
+ from concurrent.futures import ThreadPoolExecutor
5
+ import pandas as pd
6
+ from llm import chat_json, usage_line
7
+
8
+ def build_system(intents, examples):
9
+ listing = "\n".join(f"{k}: {n} | e.g. " + " / ".join(examples[n]) for k, n in enumerate(intents))
10
+ return ("You classify messages sent to a retail bank's support chat into exactly one intent. Intents (id: name | examples):\n"
11
+ f"{listing}\n\nFor each numbered message choose the single best-fitting intent id. Placeholders like {{NAME}} are fake personal details; ignore them. "
12
+ 'Return JSON {"a": [id, id, ...]} with exactly one id per message, in order.')
13
+
14
+ def classify(system, texts, model):
15
+ user = "\n".join(f"{i+1}. {t}" for i, t in enumerate(texts))
16
+ a = chat_json(model, system, user, max_tokens=400, temperature=0.0).get("a", [])
17
+ if len(a) == len(texts): return a
18
+ if len(texts) == 1: return [-1]
19
+ h = len(texts) // 2
20
+ return classify(system, texts[:h], model) + classify(system, texts[h:], model)
21
+
22
+ def run(system, df, model, batch, workers):
23
+ chunks = [df.text.tolist()[i:i + batch] for i in range(0, len(df), batch)]
24
+ with ThreadPoolExecutor(workers) as ex: res = list(ex.map(lambda c: classify(system, c, model), chunks))
25
+ return [x for r in res for x in r]
26
+
27
+ def main():
28
+ ap = argparse.ArgumentParser()
29
+ ap.add_argument("--inp", default="data/synth_raw.jsonl")
30
+ ap.add_argument("--out", default="data/synth_verified.jsonl")
31
+ ap.add_argument("--model", default="deepseek-v4-pro")
32
+ ap.add_argument("--batch", type=int, default=40)
33
+ ap.add_argument("--workers", type=int, default=8)
34
+ ap.add_argument("--calibrate", type=int, default=0, help="only score N held-out real rows, then exit")
35
+ a = ap.parse_args()
36
+
37
+ pool = pd.read_parquet("data/clean_pool.parquet")
38
+ intents = sorted(pool.intent.unique())
39
+ ex_rows = pool.groupby("intent").sample(2, random_state=0) # in-prompt examples
40
+ examples = {i: g.text.tolist() for i, g in ex_rows.groupby("intent")}
41
+ system = build_system(intents, examples)
42
+ idx = {n: k for k, n in enumerate(intents)}
43
+
44
+ if a.calibrate:
45
+ held = pool.drop(ex_rows.index).sample(a.calibrate, random_state=1)
46
+ pred = run(system, held, a.model, a.batch, a.workers)
47
+ acc = (pd.Series(pred).values == held.intent.map(idx).values).mean()
48
+ print(f"verifier accuracy on {len(held)} held-out REAL rows: {acc:.3f}\n{usage_line()}")
49
+ return
50
+
51
+ df = pd.read_json(a.inp, lines=True)
52
+ df["pred"] = run(system, df, a.model, a.batch, a.workers)
53
+ df["verified"] = df.pred == df.intent.map(idx)
54
+ df.to_json(a.out, orient="records", lines=True)
55
+ print(f"verified {df.verified.mean():.1%} of {len(df)}\n{df.groupby('intent').verified.mean().sort_values().head(8).round(2)}\n{usage_line()}")
56
+
57
+ if __name__ == "__main__":
58
+ main()
seeds/seeds_audited.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:54db7fa3e4e6a0efb174863e4116b37a385e150d8d0f29c7a6dd5a25d42f9dcf
3
+ size 383141