code-switch-mtp / scripts /phase5_prepare_iast.py
Anupam-Rawat-IITB's picture
Refresh to the current main: code, results, logs and the final deck (part 3)
3ef3d94 verified
Raw History Blame Contribute Delete
3.65 kB
"""Build an IAST copy of the existing Llama Devanagari L4 split, fully offline.
No downloads: decode the existing Llama-tokenised Devanagari ids back to text, transliterate
Devanagari -> IAST with the already-installed aksharamukha, and re-tokenise with the same
Llama tokenizer. Guards: abort unless the Devanagari decode->encode round-trip is lossless on
a sample (so the decoded text we transliterate really is the training text).
Inputs : <in-dir>/L4_train_ids.npy (flat Llama token ids, Devanagari)
<in-dir>/L4_heldout.jsonl (per-doc text, Devanagari)
Outputs: <out-dir>/L4_train_ids.npy (flat Llama token ids, IAST)
<out-dir>/L4_heldout.jsonl (per-doc text, IAST)
"""
import argparse
import json
import sys
from pathlib import Path
import numpy as np
def main() -> None:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--in-dir", required=True)
p.add_argument("--out-dir", required=True)
p.add_argument("--backbone", default="meta-llama/Llama-3.2-1B")
p.add_argument("--chunk", type=int, default=20000, help="tokens per decode/transliterate chunk")
p.add_argument("--src", default="Devanagari")
p.add_argument("--tgt", default="IAST")
args = p.parse_args()
from transformers import AutoTokenizer
from aksharamukha import transliterate as T
tok = AutoTokenizer.from_pretrained(args.backbone)
indir, outdir = Path(args.in_dir), Path(args.out_dir)
outdir.mkdir(parents=True, exist_ok=True)
def xlit(s: str) -> str:
return T.process(args.src, args.tgt, s)
# --- round-trip guard: the decoded Devanagari must survive re-encoding losslessly ---
ids = np.load(indir / "L4_train_ids.npy")
sample = [int(x) for x in ids[:5000]]
dec = tok.decode(sample)
reenc = tok(dec, add_special_tokens=False).input_ids
redec = tok.decode(reenc)
if redec != dec:
print("FATAL: Devanagari decode->encode->decode is NOT lossless on the sample; aborting IAST build.")
print(f" len(dec)={len(dec)} len(redec)={len(redec)}")
sys.exit(2)
print(f"round-trip OK on 5000-token sample (text len {len(dec)})")
# --- train ids: decode -> IAST -> re-encode, chunked ---
n = len(ids)
out_ids = []
iast_text_len = deva_text_len = 0
for s in range(0, n, args.chunk):
chunk = [int(x) for x in ids[s : s + args.chunk]]
deva = tok.decode(chunk)
iast = xlit(deva)
deva_text_len += len(deva); iast_text_len += len(iast)
out_ids.extend(tok(iast, add_special_tokens=False).input_ids)
if (s // args.chunk) % 50 == 0:
print(f" train chunk {s}/{n} -> cumulative IAST ids {len(out_ids)}", flush=True)
out_ids = np.array(out_ids, dtype=ids.dtype)
np.save(outdir / "L4_train_ids.npy", out_ids)
print(f"train: {n} Deva ids ({deva_text_len} chars) -> {len(out_ids)} IAST ids ({iast_text_len} chars); "
f"fertility ratio {len(out_ids)/max(n,1):.3f}")
# --- heldout: transliterate each doc's text (keep the same doc set / order) ---
src_held = (indir / "L4_heldout.jsonl").read_text().splitlines()
kept = 0
with (outdir / "L4_heldout.jsonl").open("w") as f:
for line in src_held:
if not line.strip():
continue
d = json.loads(line)
key = "text" if "text" in d else next((k for k in d if isinstance(d[k], str)), None)
d[key] = xlit(d[key])
f.write(json.dumps(d, ensure_ascii=False) + "\n")
kept += 1
print(f"heldout: transliterated {kept} docs")
print("DONE prepare_iast")
if __name__ == "__main__":
main()