Download code/scripts/ft_prep_triplets.py from Arushhh/amlc-work: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/datasets/Arushhh/amlc-work/resolve/main/code/scripts/ft_prep_triplets.py
- Command line
-
hf download hf://datasets/Arushhh/amlc-work/code/scripts/ft_prep_triplets.py
-
curl -L -o ft_prep_triplets.py https://huggingface.co/datasets/Arushhh/amlc-work/resolve/main/code/scripts/ft_prep_triplets.py
10.4 kB
| """Build contrastive fine-tuning triplets for multilingual-e5-large (AMLC 2026). | |
| Runs on the on-demand CPU box: /data/venv/bin/python ft_prep_triplets.py | |
| Inputs : /data/amlc/norm/{s1,s2,s3}.parquet (entity_id, country, raw_name, raw_address) | |
| /data/amlc/parquet/pairs.parquet (a = S1 id, b = S2/S3 id) | |
| /data/amlc/dense/train_cands.parquet (s1_id, cand_id, sim_e5_full, ...) zero-shot e5 top-30 full + top-10 name | |
| /data/amlc/ft/eval/embed_eval_set.parquet (role=='query' S1 ids are excluded) | |
| Text : "query: " + raw_name.strip() + " | " + raw_address.strip() (name only when the address is empty) | |
| Sample : S1 entities with >=1 labelled match, not an eval query; <= MAX_POS positives per S1 (random); | |
| S1 entities are taken in a seeded-hash order: the first ~VAL_N triplets form the validation split, the next | |
| TRAIN_N triplets the training split (splits are disjoint by S1 entity). | |
| Hard negative (one per S1): the non-matching (vs ALL labelled pairs of that S1) candidate with the highest sim_e5_full, | |
| skipping candidates whose text is identical (case-insensitive) to the anchor or to any labelled match of that S1; | |
| fallback: a seeded-random same-country S2/S3 record that is not a match. | |
| Output : /data/amlc/ft/out/train_triplets.parquet (anchor_text, positive_text, negative_text, s1_id, pos_id, neg_id, | |
| neg_type, neg_sim_e5_full, pos_sim_e5_full, country, split), /data/amlc/ft/out/train_s1_ids.parquet | |
| (s1_id, country, split, n_triplets), /data/amlc/ft/out/prep_stats.json | |
| """ | |
| import os, time, json | |
| import duckdb, numpy as np, pandas as pd, pyarrow as pa, pyarrow.parquet as pq | |
| R = '/data/amlc'; O = f'{R}/ft'; OUT = f'{O}/out' | |
| TRAIN_N = int(os.environ.get('TRAIN_N', 1_500_000)); VAL_N = int(os.environ.get('VAL_N', 20_000)) | |
| MAX_POS = int(os.environ.get('MAX_POS', 2)); SEED = os.environ.get('SEED', 'ft2026') | |
| T0 = time.time() | |
| def log(*a): print(f"[{time.strftime('%H:%M:%S')} +{time.time() - T0:5.0f}s]", *a, flush=True) | |
| os.makedirs(OUT, exist_ok=True); os.makedirs(f'{O}/duck_tmp', exist_ok=True) | |
| con = duckdb.connect() | |
| con.execute(f"SET threads={os.environ.get('THREADS', 4)}; SET memory_limit='{os.environ.get('MEM', '28GB')}'; " | |
| f"SET temp_directory='{O}/duck_tmp'; SET preserve_insertion_order=false") | |
| log('duckdb', duckdb.__version__) | |
| S = {} | |
| con.execute(f"CREATE TABLE evq AS SELECT DISTINCT entity_id FROM read_parquet('{O}/eval/embed_eval_set.parquet') WHERE role='query'") | |
| S['eval_query_s1'] = con.execute("SELECT count(*) FROM evq").fetchone()[0] | |
| con.execute(f"CREATE TABLE s1 AS SELECT entity_id, country, raw_name, raw_address FROM read_parquet('{R}/norm/s1.parquet')") | |
| con.execute(f"CREATE TABLE v AS SELECT entity_id, country, raw_name, raw_address FROM read_parquet(['{R}/norm/s2.parquet','{R}/norm/s3.parquet'])") | |
| con.execute(f"CREATE TABLE pairs AS SELECT a, b FROM read_parquet('{R}/parquet/pairs.parquet')") | |
| S['s1_rows'], S['vendor_rows'], S['pairs'] = [con.execute(f"SELECT count(*) FROM {t}").fetchone()[0] for t in ('s1', 'v', 'pairs')] | |
| log('loaded', S) | |
| # comparison key for the identical-text guard (python-strip-like trim on ASCII whitespace, lower-cased) | |
| KEY = lambda t: (f"lower(CASE WHEN trim(coalesce({t}.raw_address,''))<>'' THEN trim(coalesce({t}.raw_name,''))||' | '||" | |
| f"trim(coalesce({t}.raw_address,'')) ELSE trim(coalesce({t}.raw_name,'')) END)") | |
| # ---- eligible pairs, <= MAX_POS per S1 | |
| con.execute(f"""CREATE TABLE pc AS SELECT p.a, p.b, s1.country, | |
| row_number() OVER (PARTITION BY p.a ORDER BY hash(p.b || '{SEED}p')) AS k | |
| FROM pairs p JOIN s1 ON s1.entity_id = p.a ANTI JOIN evq ON evq.entity_id = p.a | |
| QUALIFY k <= {MAX_POS}""") | |
| con.execute(f"""CREATE TABLE s1r AS SELECT a, country, count(*) AS np, hash(a || '{SEED}s') AS h FROM pc GROUP BY a, country""") | |
| con.execute("CREATE TABLE s1c AS SELECT a, country, np, sum(np) OVER (ORDER BY h, a ROWS UNBOUNDED PRECEDING) AS cum FROM s1r") | |
| S['eligible_s1'] = con.execute("SELECT count(*) FROM s1c").fetchone()[0] | |
| S['eligible_pairs_capped'] = con.execute("SELECT count(*) FROM pc").fetchone()[0] | |
| vmax = con.execute(f"SELECT max(cum) FROM s1c WHERE cum <= {VAL_N}").fetchone()[0] | |
| con.execute(f"""CREATE TABLE sel AS SELECT a, country, np, CASE WHEN cum <= {vmax} THEN 'val' ELSE 'train' END AS split | |
| FROM s1c WHERE cum <= {vmax + TRAIN_N}""") | |
| log('eligible S1', S['eligible_s1'], 'capped pairs', S['eligible_pairs_capped'], 'val cum', vmax) | |
| # ---- mined hard negatives: top-5 non-matching candidates per selected S1 by sim_e5_full | |
| con.execute(f"""CREATE TABLE neg5 AS SELECT c.s1_id, c.cand_id, c.sim_e5_full, | |
| row_number() OVER (PARTITION BY c.s1_id ORDER BY c.sim_e5_full DESC, c.cand_id) AS r | |
| FROM read_parquet('{R}/dense/train_cands.parquet') c | |
| SEMI JOIN sel ON sel.a = c.s1_id | |
| ANTI JOIN pairs p ON p.a = c.s1_id AND p.b = c.cand_id | |
| QUALIFY r <= 5""") | |
| log('neg5 rows', con.execute("SELECT count(*) FROM neg5").fetchone()[0]) | |
| # identical-text guard: drop candidates whose text equals the anchor's or any labelled match's text | |
| con.execute(f"""CREATE TABLE badtxt AS | |
| SELECT sel.a, {KEY('s1')} AS key FROM sel JOIN s1 ON s1.entity_id = sel.a | |
| UNION SELECT p.a, {KEY('v')} AS key FROM pairs p SEMI JOIN sel ON sel.a = p.a JOIN v ON v.entity_id = p.b""") | |
| con.execute(f"""CREATE TABLE neg5k AS SELECT n.*, {KEY('v')} AS key FROM neg5 n JOIN v ON v.entity_id = n.cand_id""") | |
| con.execute("""CREATE TABLE negok AS SELECT n.s1_id, n.cand_id, n.sim_e5_full, n.r FROM neg5k n | |
| ANTI JOIN badtxt b ON b.a = n.s1_id AND b.key = n.key""") | |
| con.execute("""CREATE TABLE neg AS SELECT s1_id, cand_id AS neg_id, sim_e5_full AS neg_sim, r AS neg_rank, 'mined' AS neg_type | |
| FROM negok QUALIFY row_number() OVER (PARTITION BY s1_id ORDER BY r) = 1""") | |
| S['mined_top1_skipped_identical_text'] = con.execute("SELECT count(*) FROM neg WHERE neg_rank > 1").fetchone()[0] | |
| S['s1_with_candidates_but_all_top5_identical'] = con.execute( | |
| "SELECT count(DISTINCT s1_id) FROM neg5 ANTI JOIN neg ON neg.s1_id = neg5.s1_id").fetchone()[0] | |
| # ---- fallback: seeded-random same-country vendor record | |
| con.execute("""CREATE TABLE vpool AS SELECT entity_id, country, | |
| row_number() OVER (PARTITION BY country ORDER BY hash(entity_id || 'vp')) AS rn, count(*) OVER (PARTITION BY country) AS nc FROM v""") | |
| con.execute("CREATE TABLE needy AS SELECT sel.a, sel.country FROM sel ANTI JOIN neg ON neg.s1_id = sel.a") | |
| S['fallback_random_s1'] = con.execute("SELECT count(*) FROM needy").fetchone()[0] | |
| con.execute(f"""INSERT INTO neg SELECT needy.a, vp.entity_id, NULL, NULL, 'random' | |
| FROM needy JOIN (SELECT DISTINCT country, nc FROM vpool) c ON c.country = needy.country | |
| JOIN vpool vp ON vp.country = needy.country AND vp.rn = 1 + (hash(needy.a || '{SEED}fb') % c.nc)""") | |
| S['fallback_collisions_with_matches'] = con.execute( | |
| "SELECT count(*) FROM neg JOIN pairs p ON p.a = neg.s1_id AND p.b = neg.neg_id").fetchone()[0] | |
| log('negatives', con.execute("SELECT neg_type, count(*), avg(neg_sim), avg(neg_rank) FROM neg GROUP BY 1").fetchall(), S) | |
| # ---- assemble triplets (ids + raw fields; text is built in pandas with python str.strip like encode_e5.py) | |
| df = con.execute(f"""SELECT pc.a AS s1_id, pc.b AS pos_id, neg.neg_id, neg.neg_type, neg.neg_sim AS neg_sim_e5_full, | |
| tc.sim_e5_full AS pos_sim_e5_full, sel.country, sel.split, | |
| s1.raw_name AS an, s1.raw_address AS aa, vp.raw_name AS pn, vp.raw_address AS pa, vn.raw_name AS nn, vn.raw_address AS na | |
| FROM sel JOIN pc ON pc.a = sel.a JOIN neg ON neg.s1_id = sel.a | |
| JOIN s1 ON s1.entity_id = sel.a JOIN v vp ON vp.entity_id = pc.b JOIN v vn ON vn.entity_id = neg.neg_id | |
| LEFT JOIN read_parquet('{R}/dense/train_cands.parquet') tc ON tc.s1_id = pc.a AND tc.cand_id = pc.b | |
| ORDER BY hash(pc.a || pc.b || '{SEED}o')""").df() | |
| log('assembled', len(df)) | |
| def txt(n, a): | |
| n = n.fillna('').astype(str).str.strip(); a = a.fillna('').astype(str).str.strip() | |
| return 'query: ' + pd.Series(np.where(a.str.len() > 0, n + ' | ' + a, n), index=n.index) | |
| df['anchor_text'] = txt(df.an, df.aa); df['positive_text'] = txt(df.pn, df.pa); df['negative_text'] = txt(df.nn, df.na) | |
| df = df[['anchor_text', 'positive_text', 'negative_text', 's1_id', 'pos_id', 'neg_id', 'neg_type', 'neg_sim_e5_full', | |
| 'pos_sim_e5_full', 'country', 'split']] | |
| df['neg_sim_e5_full'] = df.neg_sim_e5_full.astype('float32'); df['pos_sim_e5_full'] = df.pos_sim_e5_full.astype('float32') | |
| assert not df.s1_id.isin(set(con.execute("SELECT entity_id FROM evq").df().entity_id)).any(), 'eval query leaked' | |
| assert df.groupby('s1_id').split.nunique().max() == 1, 'S1 in both splits' | |
| pq.write_table(pa.Table.from_pandas(df, preserve_index=False), f'{OUT}/train_triplets.parquet', compression='zstd', row_group_size=100_000) | |
| ids = df.groupby(['s1_id', 'country', 'split']).size().rename('n_triplets').reset_index() | |
| pq.write_table(pa.Table.from_pandas(ids, preserve_index=False), f'{OUT}/train_s1_ids.parquet', compression='zstd') | |
| # ---- stats | |
| S['triplets'] = df.split.value_counts().to_dict(); S['s1_entities'] = ids.split.value_counts().to_dict() | |
| S['triplets_by_country'] = df[df.split == 'train'].country.value_counts().to_dict() | |
| S['neg_type'] = df.groupby('split').neg_type.value_counts().unstack().fillna(0).astype(int).to_dict('index') | |
| m = df[df.neg_type == 'mined'] | |
| S['neg_sim_e5_full'] = {q: float(m.neg_sim_e5_full.quantile(q)) for q in (0.05, 0.25, 0.5, 0.75, 0.95)} | |
| hp = df.pos_sim_e5_full.notna() | |
| S['pos_in_train_cands_share'] = float(hp.mean()) | |
| S['pos_sim_e5_full'] = {q: float(df.pos_sim_e5_full[hp].quantile(q)) for q in (0.05, 0.25, 0.5, 0.75, 0.95)} | |
| b = hp & (df.neg_type == 'mined') | |
| S['share_neg_sim_gt_pos_sim'] = float((df.neg_sim_e5_full[b] > df.pos_sim_e5_full[b]).mean()) | |
| S['text_len_chars_p50_p95'] = {c: [float(df[c].str.len().quantile(0.5)), float(df[c].str.len().quantile(0.95))] | |
| for c in ('anchor_text', 'positive_text', 'negative_text')} | |
| S['params'] = dict(TRAIN_N=TRAIN_N, VAL_N=VAL_N, MAX_POS=MAX_POS, SEED=SEED) | |
| S['examples'] = df.head(3)[['anchor_text', 'positive_text', 'negative_text', 'neg_type']].to_dict('records') | |
| S['seconds'] = round(time.time() - T0, 1) | |
| json.dump(S, open(f'{OUT}/prep_stats.json', 'w'), indent=1, default=str, ensure_ascii=False) | |
| log('STATS', json.dumps(S, indent=1, default=str, ensure_ascii=False)) | |
| log('PREP_DONE') | |