Ouaill commited on
Commit
c38fbd3
·
verified ·
1 Parent(s): b2bb309

Add code-switching eval script and results

Browse files
Files changed (1) hide show
  1. eval_codeswitch_and_new_baselines.py +369 -0
eval_codeswitch_and_new_baselines.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3 -u
2
+ """
3
+ eval_codeswitch_and_new_baselines.py
4
+ 1) Evaluate mixed-script texts SEPARATELY (not forced into ar/az binary)
5
+ 2) Add atlasia/darija_bpe_tokenizer baseline
6
+ 3) Evaluate on independent DODa dataset (Arabic-only)
7
+ """
8
+
9
+ import json, os, sys, time, csv, gc, warnings
10
+ from collections import Counter
11
+ from dataclasses import dataclass, asdict
12
+ from typing import List
13
+
14
+ import numpy as np
15
+ import regex
16
+ warnings.filterwarnings("ignore")
17
+
18
+ BASE = "/root/oiq_cc_tokenizer/results"
19
+ CORPORA = os.path.join(BASE, "corpora")
20
+ TOK_DIR = os.path.join(BASE, "tokenizers")
21
+ PLOTS_DIR = os.path.join(BASE, "plots")
22
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
23
+
24
+ _WORD_PAT = regex.compile(r"[\p{L}\p{M}\p{N}]+", regex.UNICODE)
25
+ _AR_PAT = regex.compile(r"[\u0600-\u06FF\u0750-\u077F]")
26
+ _LAT_PAT = regex.compile(r"[a-zA-Z]")
27
+ _SPECIAL = {"<unk>", "<s>", "</s>", "[CLS]", "[SEP]", "[PAD]", "[UNK]", "<pad>", "",
28
+ "<|im_start|>", "<|im_end|>"}
29
+
30
+ def segment_words(t): return _WORD_PAT.findall(t)
31
+ def count_graphemes(t): return len(regex.findall(r"\X", t))
32
+ def filter_sp(tokens): return [t for t in tokens if t not in _SPECIAL]
33
+
34
+ def classify_script_detailed(t):
35
+ """Classify as 'ar', 'az', or 'mi' (mixed)."""
36
+ ar_chars = len(_AR_PAT.findall(t))
37
+ lat_chars = len(_LAT_PAT.findall(t))
38
+ total_alpha = ar_chars + lat_chars
39
+ if total_alpha == 0:
40
+ return "ar"
41
+ ar_ratio = ar_chars / total_alpha
42
+ lat_ratio = lat_chars / total_alpha
43
+ # Pure = >90% one script, mixed = both scripts present with >10% each
44
+ if ar_ratio > 0.9 and lat_ratio < 0.1:
45
+ return "ar"
46
+ elif lat_ratio > 0.9 and ar_ratio < 0.1:
47
+ return "az"
48
+ else:
49
+ return "mi"
50
+
51
+ def detect_script(t): return "ar" if len(_AR_PAT.findall(t)) > len(t) * 0.3 else "az"
52
+
53
+
54
+ @dataclass
55
+ class M:
56
+ name: str = ""
57
+ source: str = ""
58
+ algorithm: str = ""
59
+ architecture: str = ""
60
+ vocab_size: int = 0
61
+ fertility_ar: float = 0.0
62
+ fertility_az: float = 0.0
63
+ fertility_mi: float = 0.0
64
+ fertility_overall: float = 0.0
65
+ disparity: float = 0.0
66
+ cpt_ar: float = 0.0
67
+ cpt_az: float = 0.0
68
+ cpt_mi: float = 0.0
69
+ exact_match_ar: float = 0.0
70
+ exact_match_az: float = 0.0
71
+ exact_match_mi: float = 0.0
72
+
73
+
74
+ class RawConcat:
75
+ def __init__(self, ar_j, az_j):
76
+ from tokenizers import Tokenizer
77
+ self.ar = Tokenizer.from_file(ar_j)
78
+ self.az = Tokenizer.from_file(az_j)
79
+
80
+ def encode(self, text):
81
+ s = detect_script(text)
82
+ t = self.ar if s == "ar" else self.az
83
+ enc = t.encode(text)
84
+ return enc.tokens, enc.ids, s
85
+
86
+ def decode(self, ids, script):
87
+ t = self.ar if script == "ar" else self.az
88
+ return t.decode(ids, skip_special_tokens=True)
89
+
90
+
91
+ class HFTok:
92
+ def __init__(self, repo, use_token=False):
93
+ from transformers import AutoTokenizer
94
+ kwargs = {"trust_remote_code": True}
95
+ if use_token:
96
+ kwargs["token"] = HF_TOKEN
97
+ self.tok = AutoTokenizer.from_pretrained(repo, **kwargs)
98
+
99
+ def encode(self, text):
100
+ ids = self.tok.encode(text, add_special_tokens=False)
101
+ return self.tok.convert_ids_to_tokens(ids), ids, detect_script(text)
102
+
103
+ def decode(self, ids, script):
104
+ return self.tok.decode(ids, skip_special_tokens=True)
105
+
106
+
107
+ def evaluate_with_mixed(tok, name, source, algo, arch, vsz, texts):
108
+ """Evaluate with separate mi bucket for code-switched texts."""
109
+ m = M(name=name, source=source, algorithm=algo, architecture=arch, vocab_size=vsz)
110
+ buckets = {"ar": [], "az": [], "mi": []}
111
+ cpt_buckets = {"ar": [], "az": [], "mi": []}
112
+ em_buckets = {"ar": {"ok": 0, "n": 0}, "az": {"ok": 0, "n": 0}, "mi": {"ok": 0, "n": 0}}
113
+ all_f = []
114
+
115
+ for i, text in enumerate(texts):
116
+ if (i + 1) % 5000 == 0:
117
+ print(f" [{i+1}/{len(texts)}] {name}", flush=True)
118
+ try:
119
+ tokens, ids, script = tok.encode(text)
120
+ content = filter_sp(tokens)
121
+ words = segment_words(text)
122
+ if not words:
123
+ continue
124
+ fert = len(content) / len(words)
125
+ all_f.append(fert)
126
+ cpt = count_graphemes(text) / max(len(content), 1)
127
+
128
+ # Use DETAILED classification for separate mi bucket
129
+ sc = classify_script_detailed(text)
130
+
131
+ buckets[sc].append(fert)
132
+ cpt_buckets[sc].append(cpt)
133
+ em_buckets[sc]["n"] += 1
134
+
135
+ try:
136
+ dec = tok.decode(ids, script)
137
+ if dec.strip() == text.strip():
138
+ em_buckets[sc]["ok"] += 1
139
+ except:
140
+ pass
141
+ except:
142
+ pass
143
+
144
+ for sc in ("ar", "az", "mi"):
145
+ setattr(m, f"fertility_{sc}", float(np.mean(buckets[sc])) if buckets[sc] else 0)
146
+ setattr(m, f"cpt_{sc}", float(np.mean(cpt_buckets[sc])) if cpt_buckets[sc] else 0)
147
+ b = em_buckets[sc]
148
+ setattr(m, f"exact_match_{sc}", b["ok"] / max(b["n"], 1))
149
+
150
+ m.fertility_overall = float(np.mean(all_f)) if all_f else 0
151
+ mx = max(m.fertility_ar, m.fertility_az, 1e-9)
152
+ m.disparity = abs(m.fertility_ar - m.fertility_az) / mx
153
+ return m
154
+
155
+
156
+ def evaluate_on_doda(tok, name, source, algo, arch, vsz, texts):
157
+ """Evaluate on independent DODa data (Arabic only, no ar/az split)."""
158
+ all_f, all_c = [], []
159
+ em_ok, em_n = 0, 0
160
+
161
+ for i, text in enumerate(texts):
162
+ if (i + 1) % 5000 == 0:
163
+ print(f" [{i+1}/{len(texts)}] {name} (doda)", flush=True)
164
+ try:
165
+ tokens, ids, script = tok.encode(text)
166
+ content = filter_sp(tokens)
167
+ words = segment_words(text)
168
+ if not words:
169
+ continue
170
+ fert = len(content) / len(words)
171
+ all_f.append(fert)
172
+ cpt = count_graphemes(text) / max(len(content), 1)
173
+ all_c.append(cpt)
174
+ try:
175
+ dec = tok.decode(ids, script)
176
+ if dec.strip() == text.strip():
177
+ em_ok += 1
178
+ except:
179
+ pass
180
+ em_n += 1
181
+ except:
182
+ pass
183
+
184
+ return {
185
+ "name": name, "source": source, "algorithm": algo,
186
+ "architecture": arch, "vocab_size": vsz,
187
+ "n_texts": em_n,
188
+ "fertility": float(np.mean(all_f)) if all_f else 0,
189
+ "cpt": float(np.mean(all_c)) if all_c else 0,
190
+ "exact_match": em_ok / max(em_n, 1),
191
+ }
192
+
193
+
194
+ def main():
195
+ # Load test texts
196
+ test_ar, test_az, test_mi = [], [], []
197
+ for s, lst in [("test_ar", test_ar), ("test_az", test_az), ("test_mi", test_mi)]:
198
+ p = os.path.join(CORPORA, f"{s}.txt")
199
+ if os.path.exists(p):
200
+ with open(p) as f:
201
+ lst.extend(l.strip() for l in f if l.strip())
202
+
203
+ # Check script distribution with DETAILED classification
204
+ print("=== Script distribution (detailed) ===", flush=True)
205
+ from collections import Counter
206
+ dist = Counter()
207
+ for f in [test_ar, test_az, test_mi]:
208
+ for t in f:
209
+ dist[classify_script_detailed(t)] += 1
210
+ total = sum(dist.values())
211
+ for sc in ("ar", "az", "mi"):
212
+ print(f" {sc}: {dist[sc]} ({dist[sc]/total*100:.1f}%)", flush=True)
213
+ print(f" Total: {total}", flush=True)
214
+
215
+ all_texts = test_ar + test_az + test_mi
216
+ mi_texts = test_mi # Only mixed-script texts for dedicated eval
217
+
218
+ print(f"\n=== 1. Code-switching evaluation (3 best ours + key externals) ===", flush=True)
219
+ cs_results = []
220
+
221
+ ours_cfg = [
222
+ ("concat_bpe_8000", "concat_ar_bpe_4000", "concat_az_bpe_4000", "bpe", "concatenated", 8000),
223
+ ("concat_wordpiece_16000", "concat_ar_wordpiece_8000", "concat_az_wordpiece_8000", "wordpiece", "concatenated", 16000),
224
+ ("concat_bpe_32000", "concat_ar_bpe_16000", "concat_az_bpe_16000", "bpe", "concatenated", 32000),
225
+ ]
226
+ for name, ar_sub, az_sub, algo, arch, vsz in ours_cfg:
227
+ ar_j = os.path.join(TOK_DIR, f"{ar_sub}.json")
228
+ az_j = os.path.join(TOK_DIR, f"{az_sub}.json")
229
+ if os.path.exists(ar_j) and os.path.exists(az_j):
230
+ print(f"\n{name}", flush=True)
231
+ tok = RawConcat(ar_j, az_j)
232
+ r = evaluate_with_mixed(tok, name, "ours", algo, arch, vsz, all_texts)
233
+ cs_results.append(r)
234
+ print(f" F_ar={r.fertility_ar:.3f} F_az={r.fertility_az:.3f} F_mi={r.fertility_mi:.3f} EM_mi={r.exact_match_mi:.2%}", flush=True)
235
+ del tok; gc.collect()
236
+
237
+ # Key externals for code-switching
238
+ externals_cs = [
239
+ ("DarijaBERT-ar", "external_darija", "WordPiece", "shared", 80000,
240
+ "SI2M-Lab/DarijaBERT", False),
241
+ ("Qwen2.5-Darija", "external_darija", "SentencePiece", "shared", 151643,
242
+ "GemMaroc/Qwen2.5-7B-Instruct-darija", False),
243
+ ]
244
+ for name, src, algo, arch, vsz, repo, gated in externals_cs:
245
+ print(f"\n{name} ({repo})", flush=True)
246
+ try:
247
+ tok = HFTok(repo, use_token=gated)
248
+ r = evaluate_with_mixed(tok, name, src, algo, arch, vsz, all_texts)
249
+ cs_results.append(r)
250
+ print(f" F_ar={r.fertility_ar:.3f} F_az={r.fertility_az:.3f} F_mi={r.fertility_mi:.3f} EM_mi={r.exact_match_mi:.2%}", flush=True)
251
+ del tok; gc.collect()
252
+ except Exception as e:
253
+ print(f" FAILED: {e}", flush=True)
254
+
255
+ # Save code-switching results
256
+ cs_csv = os.path.join(BASE, "codeswitch_results.csv")
257
+ cs_json = os.path.join(BASE, "codeswitch_results.json")
258
+ with open(cs_csv, "w", newline="") as f:
259
+ w = csv.DictWriter(f, fieldnames=list(asdict(cs_results[0]).keys()))
260
+ w.writeheader()
261
+ for r in cs_results:
262
+ w.writerow(asdict(r))
263
+ with open(cs_json, "w") as f:
264
+ json.dump([asdict(r) for r in cs_results], f, indent=2)
265
+ print(f"\nCode-switching results saved to {cs_csv}", flush=True)
266
+
267
+ # Print code-switching table
268
+ print("\n" + "=" * 130, flush=True)
269
+ hdr = f"{'Name':<30} {'F_ar':>7} {'F_az':>7} {'F_mi':>7} {'CPT_ar':>7} {'CPT_az':>7} {'CPT_mi':>7} {'EM_ar':>7} {'EM_az':>7} {'EM_mi':>7}"
270
+ print(hdr, flush=True)
271
+ print("-" * 130, flush=True)
272
+ for r in cs_results:
273
+ print(f"{r.name:<30} {r.fertility_ar:>7.3f} {r.fertility_az:>7.3f} {r.fertility_mi:>7.3f} {r.cpt_ar:>7.3f} {r.cpt_az:>7.3f} {r.cpt_mi:>7.3f} {r.exact_match_ar:>7.2%} {r.exact_match_az:>7.2%} {r.exact_match_mi:>7.2%}", flush=True)
274
+ print("=" * 130, flush=True)
275
+
276
+ # ========== 2. atlasia/darija_bpe_tokenizer ==========
277
+ print("\n=== 2. Evaluating atlasia/darija_bpe_tokenizer ===", flush=True)
278
+ try:
279
+ tok = HFTok("atlasia/darija_bpe_tokenizer", use_token=True)
280
+ r = evaluate_with_mixed(tok, "atlasia_darija_bpe", "external_darija", "BPE", "shared", 0, all_texts)
281
+ # Also need vocab size
282
+ r.vocab_size = tok.tok.vocab_size
283
+ print(f" Vocab size: {r.vocab_size}", flush=True)
284
+ print(f" F={r.fertility_overall:.3f} F_ar={r.fertility_ar:.3f} F_az={r.fertility_az:.3f} ΔF={r.disparity:.3f}", flush=True)
285
+ cs_results.append(r)
286
+ del tok; gc.collect()
287
+ print(" atlasia/darija_bpe_tokenizer evaluated successfully", flush=True)
288
+ except Exception as e:
289
+ print(f" atlasia/darija_bpe_tokenizer FAILED: {e}", flush=True)
290
+ import traceback; traceback.print_exc()
291
+
292
+ # ========== 3. Independent DODa evaluation ==========
293
+ print("\n=== 3. Independent dataset evaluation (DODa) ===", flush=True)
294
+
295
+ # Try to load DODa from HF
296
+ doda_texts = []
297
+ try:
298
+ from datasets import load_dataset
299
+ print(" Loading DODa from HuggingFace...", flush=True)
300
+ ds = load_dataset("OussamaElbaz/DODa", split="train", token=HF_TOKEN, trust_remote_code=True)
301
+ if ds is not None:
302
+ # Extract Arabic text
303
+ for row in ds:
304
+ t = row.get("text", "") or row.get("arabic", "") or row.get("word", "") or row.get("sentence", "")
305
+ if t and len(t.strip()) > 5:
306
+ doda_texts.append(t.strip())
307
+ print(f" Loaded {len(doda_texts)} DODa entries", flush=True)
308
+ except Exception as e:
309
+ print(f" DODa load failed: {e}", flush=True)
310
+ import traceback; traceback.print_exc()
311
+
312
+ # Try alternative DODa repos
313
+ if not doda_texts:
314
+ for repo in ["OussamaElbaz/DODa", "DODa"]:
315
+ try:
316
+ from datasets import load_dataset
317
+ ds = load_dataset(repo, split="train", token=HF_TOKEN, trust_remote_code=True)
318
+ for row in ds:
319
+ for k, v in row.items():
320
+ if isinstance(v, str) and len(v.strip()) > 5 and any(c in v for c in "ابتثج"):
321
+ doda_texts.append(v.strip())
322
+ break
323
+ if doda_texts:
324
+ print(f" Loaded {len(doda_texts)} from {repo}", flush=True)
325
+ break
326
+ except:
327
+ continue
328
+
329
+ if not doda_texts:
330
+ print(" No DODa data available locally. Skipping independent evaluation.", flush=True)
331
+ print(" (Would need to download DODa separately)", flush=True)
332
+ else:
333
+ print(f" Evaluating {len(doda_texts)} DODa texts...", flush=True)
334
+ doda_results = []
335
+ for name, ar_sub, az_sub, algo, arch, vsz in ours_cfg:
336
+ ar_j = os.path.join(TOK_DIR, f"{ar_sub}.json")
337
+ az_j = os.path.join(TOK_DIR, f"{az_sub}.json")
338
+ if os.path.exists(ar_j) and os.path.exists(az_j):
339
+ tok = RawConcat(ar_j, az_j)
340
+ r = evaluate_on_doda(tok, name, "ours", algo, arch, vsz, doda_texts)
341
+ doda_results.append(r)
342
+ print(f" {name}: F={r['fertility']:.3f} CPT={r['cpt']:.3f} EM={r['exact_match']:.2%}", flush=True)
343
+ del tok; gc.collect()
344
+
345
+ # Key externals
346
+ for name, repo in [("CaMeLBERT-MSA", "CAMeL-Lab/bert-base-arabic-camelbert-msa"),
347
+ ("Qwen2.5-Darija", "GemMaroc/Qwen2.5-7B-Instruct-darija")]:
348
+ try:
349
+ tok = HFTok(repo, use_token=False)
350
+ r = evaluate_on_doda(tok, name, "external", "WordPiece", "shared", 0, doda_texts)
351
+ doda_results.append(r)
352
+ print(f" {name}: F={r['fertility']:.3f} CPT={r['cpt']:.3f} EM={r['exact_match']:.2%}", flush=True)
353
+ del tok; gc.collect()
354
+ except Exception as e:
355
+ print(f" {name} FAILED: {e}", flush=True)
356
+
357
+ doda_csv = os.path.join(BASE, "doda_independent_results.csv")
358
+ with open(doda_csv, "w", newline="") as f:
359
+ w = csv.DictWriter(f, fieldnames=list(doda_results[0].keys()))
360
+ w.writeheader()
361
+ for r in doda_results:
362
+ w.writerow(r)
363
+ print(f"\nDODa results saved to {doda_csv}", flush=True)
364
+
365
+ print("\n=== ALL DONE ===", flush=True)
366
+
367
+
368
+ if __name__ == "__main__":
369
+ main()