File size: 8,952 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
"""Combine the within-model fertility sweep into results/phase4_fertility_sweep.csv.

Four spellings of the same Hindi on the same frozen Llama-3.2-1B:
Devanagari and ITRANS (Phase 3, two runs each) and IAST and ISO 15919
(this phase). Three ways to read the MTP cost D = BPB(MTP) - BPB(NTP):

  bits per byte   as trained and reported in Phase 3; NOT comparable across
                  scripts, since a Devanagari character is 3 UTF-8 bytes and
                  most romanized characters are 1.
  relative        D / BPB(NTP) = extra held-out loss as a fraction of the
                  baseline's; the byte count cancels, so it is comparable.
  bits per word   D x bytes-per-word of exactly the text evaluate_stack
                  scored; the words are the same content in every script,
                  so this is the cost per unit of content.

CPU-only.
"""

import argparse
import csv
import statistics
import sys
from pathlib import Path

import yaml

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from transformers import AutoTokenizer

from src.train.data import load_heldout_texts

SCRIPTS = ("Devanagari", "ITRANS", "IAST", "ISO")
N_HEADS = 4
PHASE3_LABEL = {"Devanagari": "L4", "ITRANS": "L2"}


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--config", default="configs/phase4_fertility.yaml")
    p.add_argument("--phase3-csv", default="results/phase3_measurements.csv")
    p.add_argument("--itrans-seed1-csv", default="/data/cs769_mtp/scratch/runs/phase3_seed1/L2.csv")
    p.add_argument("--tokens-per-word-csv", default="results/phase4_fertility_tokens_per_word.csv")
    p.add_argument("--out", default="results/phase4_fertility_sweep.csv")
    return p.parse_args()


def read_metrics(path: str, key_column: str = "condition") -> dict:
    """{(key, metric): value} from a (key, metric, value, n) CSV."""
    with open(path, encoding="utf-8") as f:
        return {(row[key_column], row["metric"]): row["value"] for row in csv.DictReader(f)}


def covered_bytes_and_words(tokenizer, texts: list, max_tokens: int) -> tuple:
    """Bytes and whitespace words of exactly the spans evaluate_stack scores (tokens 1..n-1 of each doc)."""
    total_bytes = total_words = 0
    for text in texts:
        enc = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True, truncation=True, max_length=max_tokens)
        if len(enc.input_ids) < N_HEADS + 2:
            continue
        span = text[enc.offset_mapping[1][0] : enc.offset_mapping[len(enc.input_ids) - 1][1]]
        total_bytes += len(span.encode("utf-8"))
        total_words += len(span.split())
    return total_bytes, total_words


def main() -> None:
    args = parse_args()
    with open(args.config, encoding="utf-8") as f:
        cfg = yaml.safe_load(f)
    tokenizer = AutoTokenizer.from_pretrained(cfg["backbone"]["hf_id"])
    run_dir = Path(cfg["run_out_dir"])

    tpw = read_metrics(args.tokens_per_word_csv, key_column="scheme")
    phase3 = read_metrics(args.phase3_csv)
    itrans_seed1 = read_metrics(args.itrans_seed1_csv)

    # (script, run) -> {bpb_mtp, bpb_ntp, n_bytes}
    runs = {
        ("Devanagari", "run1"): (phase3[("L4", "bpb_mtp")], phase3[("L4", "bpb_ntp")]),
        ("Devanagari", "run2"): (phase3[("L4_seed1", "bpb_mtp")], phase3[("L4_seed1", "bpb_ntp")]),
        ("ITRANS", "run1"): (phase3[("L2", "bpb_mtp")], phase3[("L2", "bpb_ntp")]),
        ("ITRANS", "run2"): (itrans_seed1[("L2", "bpb_mtp")], itrans_seed1[("L2", "bpb_ntp")]),
    }
    new_runs = {}
    for script in ("IAST", "ISO"):
        for run, seed in (("run1", "seed0"), ("run2", "seed1")):
            path = run_dir / f"{script}_{seed}.csv"
            if not path.exists():
                continue
            metrics = read_metrics(str(path))
            runs[(script, run)] = (metrics[(script, "bpb_mtp")], metrics[(script, "bpb_ntp")])
            if run == "run1":
                new_runs[script] = metrics
            elif (script, "verified_tokens_per_verification_pass") in metrics:
                new_runs[f"{script}_run2"] = metrics

    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"),
    }

    rows = [["script", "metric", "value", "n"]]
    summary = {}
    for script in SCRIPTS:
        rows.append([script, "tokens_per_word_paired_sentences", tpw[(script, "paired_tokens_per_word")], 2000])
        rows.append([script, "tokens_per_word_heldout_docs", tpw[(script, "heldout_docs_tokens_per_word")], 512])

        covered_bytes, covered_words = covered_bytes_and_words(tokenizer, load_heldout_texts(heldout_paths[script]), cfg["eval_max_tokens_per_doc"])
        bytes_per_word = covered_bytes / covered_words
        rows.append([script, "evaluated_bytes", covered_bytes, 1])
        rows.append([script, "evaluated_words", covered_words, 1])

        relative, per_word = [], []
        for run in ("run1", "run2"):
            if (script, run) not in runs:
                continue
            bpb_mtp, bpb_ntp = (float(v) for v in runs[(script, run)])
            d = bpb_mtp - bpb_ntp
            relative.append(d / bpb_ntp)
            per_word.append(d * bytes_per_word)
            rows.append([script, f"{run}_bpb_mtp", f"{bpb_mtp:.6f}", covered_bytes])
            rows.append([script, f"{run}_bpb_ntp", f"{bpb_ntp:.6f}", covered_bytes])
            rows.append([script, f"{run}_d_bits_per_byte", f"{d:.6f}", covered_bytes])
            rows.append([script, f"{run}_d_relative", f"{d / bpb_ntp:.6f}", covered_bytes])
            rows.append([script, f"{run}_d_bits_per_word", f"{d * bytes_per_word:.6f}", covered_words])
            rows.append([script, f"{run}_ntp_bits_per_word", f"{bpb_ntp * bytes_per_word:.6f}", covered_words])
        rows.append([script, "n_runs", len(relative), 1])
        if not relative:
            continue
        rows.append([script, "mean_d_relative", f"{statistics.mean(relative):.6f}", len(relative)])
        rows.append([script, "mean_d_bits_per_word", f"{statistics.mean(per_word):.6f}", len(per_word)])
        summary[script] = (float(tpw[(script, "paired_tokens_per_word")]), statistics.mean(relative), statistics.mean(per_word))

        # per-predictor accuracy inside words vs at word starts, first run
        source = {"Devanagari": (phase3, "L4"), "ITRANS": (phase3, "L2")}.get(script) or (new_runs.get(script), script)
        metrics, key = source
        if metrics:
            for k in range(1, N_HEADS + 1):
                for kind in ("intraword", "boundary"):
                    rows.append([script, f"head{k}_accuracy_{kind}", metrics[(key, f"head{k}_accuracy_{kind}")], 1])

        # acceptance with the corrected decoder
        if script in ("IAST", "ISO") and script in new_runs:
            acceptance = {m: v for (c, m), v in new_runs[script].items() if c == script}
        else:
            path = run_dir / f"{script}_seed0_acceptance.csv"
            acceptance = {m: v for (c, m), v in read_metrics(str(path), key_column="arm").items()} if path.exists() else {}
        acceptance_metrics = ("verified_tokens_per_verification_pass", "verified_boundary_completion_rate",
                              "draft2_acceptance_word_start", "draft2_acceptance_inside_word")
        for metric in acceptance_metrics:
            if metric in acceptance:
                rows.append([script, metric, acceptance[metric], 1])
        second = new_runs.get(f"{script}_run2")
        if second:
            for metric in acceptance_metrics:
                rows.append([script, f"run2_{metric}", second[(script, metric)], 1])

    # does the relative cost move with tokens-per-word across the scripts measured so far?
    measured = [s for s in SCRIPTS if s in summary]
    xs = [summary[s][0] for s in measured]
    for label, idx in (("d_relative", 1), ("d_bits_per_word", 2)):
        ys = [summary[s][idx] for s in measured]
        mx, my = statistics.mean(xs), statistics.mean(ys)
        sxx = sum((x - mx) ** 2 for x in xs)
        slope = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sxx
        r = slope * (sxx ** 0.5) / (sum((y - my) ** 2 for y in ys) ** 0.5)
        rows.append(["all", f"slope_{label}_per_token_per_word", f"{slope:.6f}", len(measured)])
        rows.append(["all", f"pearson_r_{label}_vs_tokens_per_word", f"{r:.4f}", len(measured)])

    Path(args.out).parent.mkdir(parents=True, exist_ok=True)
    with open(args.out, "w", newline="", encoding="utf-8") as f:
        csv.writer(f).writerows(rows)
    for s in measured:
        print(f"{s:11s} tokens/word {summary[s][0]:.3f}  relative D {100 * summary[s][1]:.2f}%  D {summary[s][2]:.4f} bits/word")
    print(f"wrote {args.out}")


if __name__ == "__main__":
    main()