"""Generate top-k candidate splits with beam search (guide: Candidate generation). Output: outputs//candidates.jsonl, one line per verse: {"id", "candidates": [{"split", "logprob"}], "gold", "english"} Candidates differing only in whitespace are deduplicated, keeping the highest log-probability. Log-probabilities are returned per sequence and also normalised per word, since the combined score mixes them with a per-word translation score. Usage: python -I src/splitter/topk.py --config configs/topk_dev.yaml --seed 13 """ from __future__ import annotations import argparse import json import os import sys sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) import torch # noqa: E402 import yaml # noqa: E402 from transformers import AutoTokenizer, T5ForConditionalGeneration # noqa: E402 PREFIX = "S " def dedup(cands): """Collapse candidates identical up to whitespace, keep best logprob.""" best = {} for split, lp in cands: key = " ".join(split.split()) if key not in best or lp > best[key]: best[key] = lp return sorted(((s, lp) for s, lp in best.items()), key=lambda t: -t[1]) @torch.no_grad() def run(cfg, seed): dev = "cuda" if torch.cuda.is_available() else "cpu" tok = AutoTokenizer.from_pretrained(cfg["model"]) model = T5ForConditionalGeneration.from_pretrained(cfg["model"]).to(dev).eval() if dev == "cuda": model = model.to(torch.bfloat16) k = int(cfg["k"]) max_len = int(cfg.get("max_length", 512)) bs = int(cfg.get("batch_size", 8)) rows = [json.loads(l) for l in open(cfg["paths"]["input"], encoding="utf-8")] if cfg.get("limit"): rows = rows[: int(cfg["limit"])] print(f"{len(rows)} verses, k={k}, device={dev}") out_path = cfg["paths"]["output"] os.makedirs(os.path.dirname(out_path), exist_ok=True) n = 0 with open(out_path, "w", encoding="utf-8") as fh: for i in range(0, len(rows), bs): batch = rows[i: i + bs] enc = tok([PREFIX + r["sanskrit_raw"] for r in batch], return_tensors="pt", padding=True, truncation=True, max_length=max_len).to(dev) gen = model.generate( **enc, num_beams=k, num_return_sequences=k, max_length=max_len, early_stopping=True, output_scores=True, return_dict_in_generate=True, ) seqs = tok.batch_decode(gen.sequences, skip_special_tokens=True) scores = gen.sequences_scores.tolist() # length-normalised logprob for j, r in enumerate(batch): cands = [(seqs[j * k + m], scores[j * k + m]) for m in range(k)] cands = dedup(cands) rec = { "id": r["id"], "gold": r.get("sanskrit_gold", ""), "sanskrit_raw": r["sanskrit_raw"], "candidates": [ {"split": s, "logprob": lp, "logprob_per_word": lp / max(len(s.split()), 1)} for s, lp in cands ], } if "english" in r: rec["english"] = r["english"] fh.write(json.dumps(rec, ensure_ascii=False) + "\n") n += 1 if (i // bs) % 20 == 0: print(f" {n}/{len(rows)}", flush=True) print(f"wrote {n} -> {out_path}") def main(): ap = argparse.ArgumentParser() ap.add_argument("--config", required=True) ap.add_argument("--seed", type=int, required=True) a = ap.parse_args() run(yaml.safe_load(open(a.config, encoding="utf-8")), a.seed) if __name__ == "__main__": main()