amlc-work / code /src /predict.py
Arushhh's picture
code snapshot
0dd5490 verified
Raw History Blame Contribute Delete
9.67 kB
"""Score the test candidates and write the submission files.
python -m src.predict --cands cands_test.parquet --norm-dir ROOT/norm --model-dir ROOT/models/m1 \
--s1 ROOT/parquet/t1.parquet --out-dir ROOT/output \
[--validator student_resource/utils/validate_submission.py --test-dir ROOT/raw/dataset/test]
features (src.features, S1 IDF from the test S1 table) -> model(s) from features.json (fold
models are averaged) -> isotonic calibrator -> expected-F0.5 decode -> one-parent rule ->
out-dir/matching_results.tsv (one row per S1 id of --s1, in file order, empty when no match) and
out-dir/candidate_pairs.tsv (src.make_candidate_tsv over the same --cands, i.e. exactly the set
the model scored). --s1 may be a parquet (entity_id [+ rn for file order]) or the TSV.
--save-probs writes out-dir/pair_probs.parquet (s1_id, cand_id, raw, cal, selected).
"""
from __future__ import annotations
import argparse
import json
import os
import pickle
import subprocess
import sys
import time
import numpy as np
import polars as pl
if __package__ in (None, ""): # allow `python src/predict.py`
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from src.decode import decode_arrays # noqa: E402
from src.features import build_features, build_idf_tables, log # noqa: E402
from src.metric import write_id_list_tsv # noqa: E402
from src.train_matcher import (_as_arrow, add_missing_features, load_tables, one_parent, # noqa: E402
predict_raw, read_cands, selected_pred)
def read_s1_ids(path: str) -> list:
"""S1 ids in file order from a parquet (entity_id, optional rn) or a challenge TSV."""
if path.endswith(".parquet"):
import pyarrow.parquet as pq
names = pq.ParquetFile(path).schema_arrow.names
col = "entity_id" if "entity_id" in names else ("source1_entity_id" if "source1_entity_id" in names else names[0])
df = pl.read_parquet(path, columns=[col] + (["rn"] if "rn" in names else []))
if "rn" in df.columns:
df = df.sort("rn")
ids = df.get_column(col)
else:
df = pl.read_csv(path, separator="\t", quote_char=None, infer_schema_length=0, truncate_ragged_lines=True)
col = "entity_id" if "entity_id" in df.columns else df.columns[0]
ids = df.get_column(col)
ids = ids.cast(pl.Utf8).str.strip_chars()
seen, out, dup = set(), [], 0
for x in ids.to_list():
if x in seen:
dup += 1
continue
seen.add(x)
out.append(x)
if dup:
print(f"WARNING: {dup} duplicate ids in {path}; kept the first", file=sys.stderr)
return out
def run(a) -> dict:
t_all = time.time()
os.makedirs(a.out_dir, exist_ok=True)
with open(os.path.join(a.model_dir, "features.json")) as fh:
meta = json.load(fh)
import lightgbm as lgb
boosters = [lgb.Booster(model_file=os.path.join(a.model_dir, m)) for m in meta["models"]]
with open(os.path.join(a.model_dir, meta.get("calibrator", "calibrator.pkl")), "rb") as fh:
iso = pickle.load(fh)
dec = meta.get("decode", {})
min_prob = a.min_prob if a.min_prob is not None else float(dec.get("min_prob") or 0.0)
max_k = a.max_k if a.max_k is not None else dec.get("max_k")
feat_cols = meta["features"]
log(f"model: {len(boosters)} booster(s) {meta['models']}, {len(feat_cols)} features, decode min_prob={min_prob} max_k={max_k}")
s1_order = read_s1_ids(a.s1)
cands = read_cands(a.cands)
s1_tab, pool_tab = load_tables(a.norm_dir, a.s1_table, a.pool_tables)
log(f"loaded: {len(s1_order):,} S1 ids from {a.s1}; cands {cands.height:,}; S1 table {s1_tab.num_rows:,}; "
f"pool {pool_tab.num_rows:,}")
idf = build_idf_tables(s1_tab)
t = time.time()
feats = build_features(cands, s1_tab, pool_tab, idf, n_jobs=a.workers, task_rows=a.task_rows)
t_feat = time.time() - t
del cands, s1_tab, pool_tab, idf
missing = add_missing_features(feats, feat_cols)
if missing:
print(f"WARNING: features missing from this candidate table, filled with NaN: {missing}", file=sys.stderr)
t = time.time()
raw = predict_raw(boosters, feats, feat_cols, chunk_rows=a.chunk_rows, num_threads=a.workers)
cal = iso.predict(raw)
log(f"scored {len(raw):,} pairs in {time.time() - t:.0f}s; mean raw {raw.mean() if len(raw) else 0:.4f}, "
f"mean cal {cal.mean() if len(cal) else 0:.4f}")
s1_rows = feats["s1_row"].to_numpy()
pool_rows = feats["pool_row"].to_numpy()
s1_ids, cand_ids = _as_arrow(feats["s1_id"]), _as_arrow(feats["cand_id"])
if "country" in feats.columns:
ccodes = feats["country"].cat.codes.to_numpy()
ccats = list(feats["country"].cat.categories)
else:
ccodes = None
del feats
t = time.time()
if len(cal):
r = decode_arrays(s1_rows, cal, method="expected_f", min_prob=min_prob, max_k=max_k, n_jobs=a.workers)
sel0 = r.selected
else:
sel0 = np.zeros(0, dtype=bool)
sel = one_parent(sel0, pool_rows, cal)
log(f"decoded in {time.time() - t:.0f}s: {int(sel0.sum()):,} pairs selected, {int(sel0.sum() - sel.sum()):,} "
f"dropped by the one-parent rule")
pred = selected_pred(sel, cal, s1_rows, s1_ids, cand_ids)
pred = {k: [c for c in v if c.startswith(("S2-", "S3-"))] for k, v in pred.items()}
order_set = set(s1_order)
extra = sum(1 for k in pred if k not in order_set)
if extra:
print(f"WARNING: {extra:,} S1 ids with predictions are not in {a.s1}; not written", file=sys.stderr)
out_match = os.path.join(a.out_dir, "matching_results.tsv")
write_id_list_tsv(pred, out_match, all_ids=s1_order)
n_nonempty = sum(1 for k in s1_order if pred.get(k))
n_pairs = sum(len(pred.get(k, ())) for k in s1_order)
log(f"wrote {out_match}: {len(s1_order):,} rows, {n_nonempty:,} non-empty ({n_nonempty / max(len(s1_order), 1):.1%}), "
f"{n_pairs:,} matched ids, {n_pairs / max(len(s1_order), 1):.2f} per S1")
if ccodes is not None and len(sel):
cnt = np.bincount(ccodes[sel][ccodes[sel] >= 0], minlength=len(ccats))
log(" selected pairs by country: " + ", ".join(f"{c}={n:,}" for c, n in zip(ccats, cnt)))
if a.save_probs:
import pyarrow as pa
import pyarrow.parquet as pq
pq.write_table(pa.table({"s1_id": s1_ids, "cand_id": cand_ids, "raw": pa.array(raw.astype(np.float32)),
"cal": pa.array(cal.astype(np.float32)), "selected": pa.array(sel)}),
os.path.join(a.out_dir, "pair_probs.parquet"), compression="zstd")
# candidate_pairs.tsv: exactly the candidate set the model scored
out_cand = os.path.join(a.out_dir, "candidate_pairs.tsv")
tmp_s1 = os.path.join(a.out_dir, "_s1_ids.tsv")
with open(tmp_s1, "w", encoding="utf-8") as fh:
fh.write("entity_id\n")
fh.writelines(f"{x}\n" for x in s1_order)
from src import make_candidate_tsv
try:
make_candidate_tsv.main(["--candidates", a.cands, "--s1", tmp_s1, "--out", out_cand])
finally:
os.remove(tmp_s1)
summary = {"n_s1": len(s1_order), "n_nonempty": n_nonempty, "n_matched_ids": n_pairs,
"n_pairs_scored": int(len(raw)), "features_s": round(t_feat, 1),
"total_s": round(time.time() - t_all, 1), "validator_rc": None}
if a.validator:
test_dir = a.test_dir
if not test_dir and os.path.basename(a.s1) == "test_source1.tsv":
test_dir = os.path.dirname(os.path.abspath(a.s1))
if not test_dir:
print("WARNING: --validator given without --test-dir (dir holding test_source1.tsv); skipped",
file=sys.stderr)
else:
cmd = [sys.executable, a.validator, "--matching", out_match, "--candidate", out_cand, "--test-dir", test_dir]
log("running validator: " + " ".join(cmd))
rc = subprocess.run(cmd).returncode
summary["validator_rc"] = rc
log(f"validator exit code {rc}")
with open(os.path.join(a.out_dir, "predict_summary.json"), "w") as fh:
json.dump(summary, fh, indent=1)
log(f"done in {time.time() - t_all:.0f}s")
return summary
def build_parser() -> argparse.ArgumentParser:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--cands", required=True)
ap.add_argument("--norm-dir", required=True)
ap.add_argument("--model-dir", required=True)
ap.add_argument("--s1", required=True, help="test S1 parquet or TSV: the full id list, in file order")
ap.add_argument("--out-dir", required=True)
ap.add_argument("--s1-table", default="t1")
ap.add_argument("--pool-tables", default="t2,t3")
ap.add_argument("--workers", type=int, default=os.cpu_count())
ap.add_argument("--task-rows", type=int, default=50_000)
ap.add_argument("--chunk-rows", type=int, default=2_000_000, help="rows per LightGBM predict call")
ap.add_argument("--min-prob", type=float, default=None, help="override the decode setting in features.json")
ap.add_argument("--max-k", type=int, default=None)
ap.add_argument("--save-probs", action="store_true")
ap.add_argument("--validator", default=None, help="path to student_resource/utils/validate_submission.py")
ap.add_argument("--test-dir", default=None, help="dir with test_source1.tsv for the validator")
return ap
def main(argv=None) -> int:
s = run(build_parser().parse_args(argv))
return 0 if s.get("validator_rc") in (None, 0) else 1
if __name__ == "__main__":
raise SystemExit(main())