File size: 3,799 Bytes
bc3f388
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
"""Generate top-k candidate splits with beam search (guide: Candidate generation).

Output: outputs/<run>/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()