File size: 9,187 Bytes
3bbd5dd | 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 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | """Prepare the within-model fertility sweep: reversibility gate, tokens-per-word, corpora.
CPU-only. Three steps, run in order:
gate round-trip reversibility of ITRANS / IAST / ISO on Phase 1's
1,000-sentence Dakshina sample and on 1,000 sentences from the
held-out sangraha documents; a scheme below the Phase 1 bar is
reported and must not be trained on.
fertility Llama-3.2 tokens-per-word of the same 2,000 paired sentences
Phase 2b used, for Devanagari, ITRANS, IAST and ISO, plus the
same quantity over each condition's held-out documents.
corpus the packed training stream and held-out documents for one
scheme, built from the same sangraha documents in the same
order as Phase 3, so the held-out split is shared across all
four scripts by construction.
"""
import argparse
import csv
import json
import logging
import random
import re
import statistics
import sys
import unicodedata
from pathlib import Path
import yaml
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from transformers import AutoTokenizer
from scripts.phase2b_blocker_a import load_texts, paired_sentence_indices
from scripts.phase4_fertility_romanize import check_reversibility_scheme, iter_romanized, romanize_scheme
from src.data.dakshina import load_native_sentences
from src.train.data import iter_sangraha_docs, load_heldout_texts, prepare_corpus, save_corpus
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("huggingface_hub").setLevel(logging.WARNING)
logger = logging.getLogger("phase4_fertility_prepare")
GATE_SCHEMES = ("ITRANS", "IAST", "ISO")
SENTENCE_SPLIT = re.compile(r"(?<=[।॥.!?])\s+|\n+")
MIN_SENTENCE_WORDS = 3
# Phase 2b's paired values (results/phase2b_blockers.csv, llama_dev / llama_rom);
# reproducing them first shows this script measures the same quantity.
PHASE2B_REFERENCE = {"Devanagari": 3.051233, "ITRANS": 3.064673}
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--config", default="configs/phase4_fertility.yaml")
p.add_argument("--step", required=True, choices=["gate", "fertility", "corpus"])
p.add_argument("--scheme", choices=["IAST", "ISO"], help="corpus step only")
p.add_argument("--out", help="CSV path for the gate and fertility steps")
return p.parse_args()
def heldout_sentences(cfg: dict, n: int, seed: int) -> list:
"""Sample sentences from the held-out sangraha documents shared by every condition."""
docs = []
for text in iter_sangraha_docs(cfg["sangraha_jsonl"]):
docs.append(text)
if len(docs) >= cfg["heldout_docs"]:
break
sentences = [s.strip() for d in docs for s in SENTENCE_SPLIT.split(d) if len(s.split()) >= MIN_SENTENCE_WORDS]
rng = random.Random(seed)
return sentences if len(sentences) <= n else rng.sample(sentences, n)
def step_gate(cfg: dict, out_path: str) -> None:
dakshina = load_native_sentences(cfg["dakshina_root"])
sangraha = heldout_sentences(cfg, cfg["reversibility_sample_size"], cfg["seed"])
rows = [["scheme", "sample", "metric", "value", "n"]]
failures = {}
for scheme in GATE_SCHEMES:
for sample_name, sentences in (("dakshina_phase1_sample", dakshina), ("sangraha_heldout_sentences", sangraha)):
result = check_reversibility_scheme(sentences, scheme, cfg["reversibility_sample_size"], cfg["seed"])
logger.info("%s on %s: %d/%d exact, rate=%.4f", scheme, sample_name, result.exact_matches, result.n, result.rate)
rows.append([scheme, sample_name, "reversibility_rate", f"{result.rate:.4f}", result.n])
rows.append([scheme, sample_name, "passes_gate", int(result.rate >= cfg["reversibility_min_rate"]), result.n])
failures[f"{scheme}/{sample_name}"] = result.failures[:10]
write_rows(out_path, rows)
failures_path = Path(cfg["data_dir"]) / "reversibility_failures.json"
failures_path.parent.mkdir(parents=True, exist_ok=True)
failures_path.write_text(json.dumps(failures, ensure_ascii=False, indent=1), encoding="utf-8")
logger.info("wrote %s and %s", out_path, failures_path)
def tokens_per_word(tokenizer, texts: list, add_special_tokens: bool) -> list:
"""Per-sentence tokens per whitespace word, exactly as Phase 2b computed it."""
values = []
for text in texts:
n_words = len(text.split())
if n_words == 0:
continue
ids = tokenizer(unicodedata.normalize("NFC", text), add_special_tokens=add_special_tokens).input_ids
values.append(len(ids) / n_words)
return values
def step_fertility(cfg: dict, out_path: str) -> None:
tokenizer = AutoTokenizer.from_pretrained(cfg["backbone"]["hf_id"])
indices = paired_sentence_indices(cfg["fertility_triples_csv"], cfg["fertility_sentences"], cfg["seed"])
devanagari = load_texts(cfg["fertility_triples_csv"], "devanagari", indices)
paired = {
"Devanagari": devanagari,
"ITRANS": load_texts(cfg["fertility_triples_csv"], "itrans_roman", indices),
"IAST": [romanize_scheme(s, "IAST") for s in devanagari],
"ISO": [romanize_scheme(s, "ISO") for s in devanagari],
}
rows = [["scheme", "metric", "value", "n"]]
for scheme, texts in paired.items():
with_bos = tokens_per_word(tokenizer, texts, add_special_tokens=True)
content = tokens_per_word(tokenizer, texts, add_special_tokens=False)
mean = statistics.mean(with_bos)
logger.info("%s: %.4f tokens/word (content-only %.4f) over %d paired sentences", scheme, mean, statistics.mean(content), len(with_bos))
if scheme in PHASE2B_REFERENCE and abs(mean - PHASE2B_REFERENCE[scheme]) > 1e-4:
raise RuntimeError(f"{scheme} gives {mean:.6f}, Phase 2b measured {PHASE2B_REFERENCE[scheme]:.6f}: not the same quantity")
rows.append([scheme, "paired_tokens_per_word", f"{mean:.6f}", len(with_bos)])
rows.append([scheme, "paired_tokens_per_word_content_only", f"{statistics.mean(content):.6f}", len(content)])
heldout_paths = {
"Devanagari": cfg["existing"]["Devanagari"]["heldout"],
"ITRANS": cfg["existing"]["ITRANS"]["heldout"],
"IAST": str(Path(cfg["data_dir"]) / "IAST_heldout.jsonl"),
"ISO": str(Path(cfg["data_dir"]) / "ISO_heldout.jsonl"),
}
for scheme, path in heldout_paths.items():
if not Path(path).exists():
logger.info("%s held-out documents not built yet; skipping document-level tokens/word", scheme)
continue
docs = load_heldout_texts(path)
n_tokens = sum(len(tokenizer(unicodedata.normalize("NFC", d), add_special_tokens=False).input_ids) for d in docs)
n_words = sum(len(d.split()) for d in docs)
rows.append([scheme, "heldout_docs_tokens_per_word", f"{n_tokens / n_words:.6f}", len(docs)])
logger.info("%s held-out documents: %.4f tokens/word over %d docs", scheme, n_tokens / n_words, len(docs))
write_rows(out_path, rows)
logger.info("wrote %s", out_path)
def step_corpus(cfg: dict, scheme: str) -> None:
tokenizer = AutoTokenizer.from_pretrained(cfg["backbone"]["hf_id"])
docs = iter_romanized(iter_sangraha_docs(cfg["sangraha_jsonl"]), scheme)
prepared = prepare_corpus(
docs=docs,
tokenizer=tokenizer,
target_tokens=cfg["target_train_tokens"],
n_heldout_docs=cfg["heldout_docs"],
transform=None,
)
paths = save_corpus(prepared, cfg["data_dir"], scheme)
logger.info(
"%s: %d train tokens from %d docs, %d held-out docs -> %s",
scheme, prepared.n_train_tokens, prepared.n_docs_consumed, len(prepared.heldout_texts), paths,
)
# the held-out split must be Phase 3's, document for document
devanagari_heldout = load_heldout_texts(cfg["existing"]["Devanagari"]["heldout"])
mismatched = sum(romanize_scheme(d, scheme) != r for d, r in zip(devanagari_heldout, prepared.heldout_texts))
if len(devanagari_heldout) != len(prepared.heldout_texts) or mismatched:
raise RuntimeError(f"{scheme} held-out documents differ from Phase 3's ({mismatched} mismatched)")
logger.info("%s held-out documents match Phase 3's split document for document", scheme)
def write_rows(path: str, rows: list) -> None:
Path(path).parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", newline="", encoding="utf-8") as f:
csv.writer(f).writerows(rows)
def main() -> None:
args = parse_args()
with open(args.config, encoding="utf-8") as f:
cfg = yaml.safe_load(f)
if args.step == "gate":
step_gate(cfg, args.out or "results/phase4_fertility_reversibility.csv")
elif args.step == "fertility":
step_fertility(cfg, args.out or "results/phase4_fertility_tokens_per_word.csv")
else:
if not args.scheme:
raise SystemExit("--scheme is required for the corpus step")
step_corpus(cfg, args.scheme)
if __name__ == "__main__":
main()
|