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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3 -u
|
| 2 |
+
"""bootstrap_test_set.py — Bootstrap 95% CIs on test set, for Table 5 consistency."""
|
| 3 |
+
|
| 4 |
+
import json, os, sys, csv, gc, warnings
|
| 5 |
+
from dataclasses import dataclass, asdict
|
| 6 |
+
from collections import Counter
|
| 7 |
+
from typing import List
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import regex
|
| 11 |
+
warnings.filterwarnings("ignore")
|
| 12 |
+
|
| 13 |
+
BASE = "/root/oiq_cc_tokenizer/results"
|
| 14 |
+
CORPORA = os.path.join(BASE, "corpora")
|
| 15 |
+
TOK_DIR = os.path.join(BASE, "tokenizers")
|
| 16 |
+
|
| 17 |
+
_WORD_PAT = regex.compile(r"[\p{L}\p{M}\p{N}]+", regex.UNICODE)
|
| 18 |
+
_AR_PAT = regex.compile(r"[\u0600-\u06FF\u0750-\u077F]")
|
| 19 |
+
_SPECIAL = {"<unk>", "<s>", "</s>", "[CLS]", "[SEP]", "[PAD]", "[UNK]", "<pad>", ""}
|
| 20 |
+
|
| 21 |
+
def segment_words(t): return _WORD_PAT.findall(t)
|
| 22 |
+
def count_graphemes(t): return len(regex.findall(r"\X", t))
|
| 23 |
+
def detect_script(t): return "ar" if len(_AR_PAT.findall(t)) > len(t) * 0.3 else "az"
|
| 24 |
+
def filter_sp(tokens): return [t for t in tokens if t not in _SPECIAL]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class RawConcat:
|
| 28 |
+
def __init__(self, ar_j, az_j):
|
| 29 |
+
from tokenizers import Tokenizer
|
| 30 |
+
self.ar = Tokenizer.from_file(ar_j)
|
| 31 |
+
self.az = Tokenizer.from_file(az_j)
|
| 32 |
+
def encode(self, text):
|
| 33 |
+
s = detect_script(text)
|
| 34 |
+
t = self.ar if s == "ar" else self.az
|
| 35 |
+
enc = t.encode(text)
|
| 36 |
+
return enc.tokens, enc.ids, s
|
| 37 |
+
|
| 38 |
+
class RawShared:
|
| 39 |
+
def __init__(self, j):
|
| 40 |
+
from tokenizers import Tokenizer
|
| 41 |
+
self.tok = Tokenizer.from_file(j)
|
| 42 |
+
def encode(self, text):
|
| 43 |
+
enc = self.tok.encode(text)
|
| 44 |
+
return enc.tokens, enc.ids, detect_script(text)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def precompute_metrics(texts):
|
| 48 |
+
"""Compute per-text fertility and CPT for bootstrap resampling."""
|
| 49 |
+
words_per_text = [segment_words(t) for t in texts]
|
| 50 |
+
graphemes_per_text = [count_graphemes(t) for t in texts]
|
| 51 |
+
return words_per_text, graphemes_per_text
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def bootstrap_ci(tok, texts, words_per_text, graphemes_per_text, n_bootstrap=500):
|
| 55 |
+
"""Pre-compute per-text metrics once, then resample."""
|
| 56 |
+
n = len(texts)
|
| 57 |
+
# Pre-compute per-text fertility and CPT
|
| 58 |
+
per_text_fert = []
|
| 59 |
+
per_text_cpt = []
|
| 60 |
+
valid_mask = []
|
| 61 |
+
for i, text in enumerate(texts):
|
| 62 |
+
w = words_per_text[i]
|
| 63 |
+
if not w:
|
| 64 |
+
valid_mask.append(False)
|
| 65 |
+
per_text_fert.append(0)
|
| 66 |
+
per_text_cpt.append(0)
|
| 67 |
+
continue
|
| 68 |
+
try:
|
| 69 |
+
tokens, ids, script = tok.encode(text)
|
| 70 |
+
content = filter_sp(tokens)
|
| 71 |
+
fert = len(content) / len(w)
|
| 72 |
+
cpt = graphemes_per_text[i] / max(len(content), 1)
|
| 73 |
+
valid_mask.append(True)
|
| 74 |
+
per_text_fert.append(fert)
|
| 75 |
+
per_text_cpt.append(cpt)
|
| 76 |
+
except:
|
| 77 |
+
valid_mask.append(False)
|
| 78 |
+
per_text_fert.append(0)
|
| 79 |
+
per_text_cpt.append(0)
|
| 80 |
+
|
| 81 |
+
valid_idx = np.where(valid_mask)[0]
|
| 82 |
+
fert_arr = np.array([per_text_fert[i] for i in valid_idx])
|
| 83 |
+
cpt_arr = np.array([per_text_cpt[i] for i in valid_idx])
|
| 84 |
+
n_valid = len(valid_idx)
|
| 85 |
+
|
| 86 |
+
fert_samples = []
|
| 87 |
+
cpt_samples = []
|
| 88 |
+
rng = np.random.RandomState(42)
|
| 89 |
+
for _ in range(n_bootstrap):
|
| 90 |
+
idx = rng.choice(n_valid, size=n_valid, replace=True)
|
| 91 |
+
fert_samples.append(np.mean(fert_arr[idx]))
|
| 92 |
+
cpt_samples.append(np.mean(cpt_arr[idx]))
|
| 93 |
+
|
| 94 |
+
point_fert = float(np.mean(fert_arr))
|
| 95 |
+
point_cpt = float(np.mean(cpt_arr))
|
| 96 |
+
fert_lo, fert_hi = float(np.percentile(fert_samples, 2.5)), float(np.percentile(fert_samples, 97.5))
|
| 97 |
+
cpt_lo, cpt_hi = float(np.percentile(cpt_samples, 2.5)), float(np.percentile(cpt_samples, 97.5))
|
| 98 |
+
return point_fert, fert_lo, fert_hi, point_cpt, cpt_lo, cpt_hi
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def main():
|
| 102 |
+
texts = []
|
| 103 |
+
for s in ("test_ar", "test_az", "test_mi"):
|
| 104 |
+
p = os.path.join(CORPORA, f"{s}.txt")
|
| 105 |
+
if os.path.exists(p):
|
| 106 |
+
with open(p) as f:
|
| 107 |
+
texts.extend(l.strip() for l in f if l.strip())
|
| 108 |
+
print(f"{len(texts)} test texts", flush=True)
|
| 109 |
+
|
| 110 |
+
words_per_text, graphemes_per_text = precompute_metrics(texts)
|
| 111 |
+
|
| 112 |
+
results = []
|
| 113 |
+
for vsz in (8000, 16000, 32000):
|
| 114 |
+
for algo in ("bpe", "unigram", "wordpiece", "bbpe"):
|
| 115 |
+
jpath = os.path.join(TOK_DIR, f"shared_{algo}_{vsz}.json")
|
| 116 |
+
if os.path.exists(jpath):
|
| 117 |
+
name = f"shared_{algo}_{vsz}"
|
| 118 |
+
print(f"\n{name}", flush=True)
|
| 119 |
+
tok = RawShared(jpath)
|
| 120 |
+
r = bootstrap_ci(tok, texts, words_per_text, graphemes_per_text)
|
| 121 |
+
print(f" F={r[0]:.4f} [{r[1]:.4f}, {r[2]:.4f}] CPT={r[3]:.3f} [{r[4]:.3f}, {r[5]:.3f}]", flush=True)
|
| 122 |
+
results.append({"name": name, **dict(zip(["fert","fert_lo","fert_hi","cpt","cpt_lo","cpt_hi"], r))})
|
| 123 |
+
del tok; gc.collect()
|
| 124 |
+
|
| 125 |
+
ar_j = os.path.join(TOK_DIR, f"concat_ar_{algo}_{vsz//2}.json")
|
| 126 |
+
az_j = os.path.join(TOK_DIR, f"concat_az_{algo}_{vsz//2}.json")
|
| 127 |
+
if os.path.exists(ar_j) and os.path.exists(az_j):
|
| 128 |
+
name = f"concat_{algo}_{vsz}"
|
| 129 |
+
print(f"\n{name}", flush=True)
|
| 130 |
+
tok = RawConcat(ar_j, az_j)
|
| 131 |
+
r = bootstrap_ci(tok, texts, words_per_text, graphemes_per_text)
|
| 132 |
+
print(f" F={r[0]:.4f} [{r[1]:.4f}, {r[2]:.4f}] CPT={r[3]:.3f} [{r[4]:.3f}, {r[5]:.3f}]", flush=True)
|
| 133 |
+
results.append({"name": name, **dict(zip(["fert","fert_lo","fert_hi","cpt","cpt_lo","cpt_hi"], r))})
|
| 134 |
+
del tok; gc.collect()
|
| 135 |
+
|
| 136 |
+
# Verify consistency with test_set_results.csv
|
| 137 |
+
print("\n--- Consistency check ---", flush=True)
|
| 138 |
+
import csv as csv_mod
|
| 139 |
+
test_results = {}
|
| 140 |
+
with open(os.path.join(BASE, "test_set_results.csv")) as f:
|
| 141 |
+
for row in csv_mod.DictReader(f):
|
| 142 |
+
test_results[row["name"]] = row
|
| 143 |
+
|
| 144 |
+
print(f"{'Name':<25} {'Table5_F':>8} {'TestCSV_F':>8} {'Match':>5} {'Table5_CPT':>8} {'TestCSV_CPT':>8} {'Match':>5}", flush=True)
|
| 145 |
+
for r in results:
|
| 146 |
+
csv_r = test_results.get(r["name"])
|
| 147 |
+
if csv_r:
|
| 148 |
+
f_match = abs(float(r["fert"]) - float(csv_r["fertility_overall"])) < 0.001
|
| 149 |
+
c_match = abs(float(r["cpt"]) - float(csv_r["cpt_overall"])) < 0.01
|
| 150 |
+
print(f"{r['name']:<25} {r['fert']:>8.4f} {float(csv_r['fertility_overall']):>8.4f} {'OK' if f_match else 'MISMATCH':>5} {r['cpt']:>8.3f} {float(csv_r['cpt_overall']):>8.3f} {'OK' if c_match else 'MISMATCH':>5}", flush=True)
|
| 151 |
+
|
| 152 |
+
# Save
|
| 153 |
+
out = os.path.join(BASE, "bootstrap_ci_test_set.csv")
|
| 154 |
+
with open(out, "w", newline="") as f:
|
| 155 |
+
w = csv_mod.DictWriter(f, fieldnames=["name","fert","fert_lo","fert_hi","cpt","cpt_lo","cpt_hi"])
|
| 156 |
+
w.writeheader()
|
| 157 |
+
for r in results: w.writerow(r)
|
| 158 |
+
print(f"\nSaved: {out}", flush=True)
|
| 159 |
+
print("DONE!", flush=True)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
if __name__ == "__main__":
|
| 163 |
+
main()
|