diff --git a/nikud_planes.py b/nikud_planes.py new file mode 100644 index 0000000..af0f039 --- /dev/null +++ b/nikud_planes.py @@ -0,0 +1,77 @@ +"""Hebrew nikud plane decomposition (the haraqat_planes analog). + +Splits labeled Hebrew text into a letter skeleton plus one nikud +cluster per letter. Marks FOLLOW their base letter and close into the +previous letter's class; the cluster is canon-ordered; render is the +byte-exact inverse. The mark set matches rababa.evaluate._NIQQUD_MARKS +minus maqqaf (U+05BE is spacing punctuation — it stays in the +skeleton, and the DER metric treats it as a consonant anyway). + +Teamim (cantillation, U+0591-U+05AF) are not part of the nikud plane: +they do not appear in the v4 corpus targets. +""" + +from __future__ import annotations + +# combining niqqud: sheva, hataf patach/segol/qamats, hiriq, tseri, +# segol, patach, qamats, holam, qubuts, dagesh, meteg, rafe, shin dot, +# sin dot +NIKUD_MARKS = frozenset( + "ְֱֲֳִֵֶַָֹֺֻּֽֿׁׂ" +) + +# Cluster order is PRESERVED AS WRITTEN in the corpus: Hebrew label +# conventions vary per cluster (בְּ is sheva-then-dagesh, שָׁ is +# dot-then-qamats) and the model learns the corpus's own convention. +# Render-exactness beats normalization. + + +def canon_combo(marks: str) -> str: + return marks + + +def split_planes(text: str) -> tuple[str, list[str]]: + """Labeled text -> (skeleton, per-letter nikud classes).""" + skeleton: list[str] = [] + classes: list[str] = [] + current: list[str] = [] + + for ch in text: + if ch in NIKUD_MARKS: + current.append(ch) + continue + if current: + # marks before a letter close into the previous letter + if skeleton: + classes[-1] = canon_combo(classes[-1] + "".join(current)) + else: + # leading marks: bind to a pre-marker so render is exact + skeleton.append("\x00") + classes.append(canon_combo("".join(current))) + current = [] + skeleton.append(ch) + classes.append("") + if current: + if skeleton: + classes[-1] = canon_combo(classes[-1] + "".join(current)) + else: + skeleton.append("\x00") + classes.append(canon_combo("".join(current))) + return "".join(skeleton), classes + + +def render(skeleton: str, classes: list[str]) -> str: + if len(skeleton) != len(classes): + raise ValueError(f"length mismatch: {len(skeleton)} vs {len(classes)}") + return "".join(ch + cls for ch, cls in zip(skeleton, classes)) + + +def plane_classes(texts) -> list[str]: + """Stable inventory of the nikud clusters appearing in texts.""" + seen: set[str] = set() + for t in texts: + _, classes = split_planes(t) + seen.update(c for c in classes if c) + # "" (bare) is always implicitly present; explicit "" first, then + # codepoint-stable ordering + return [""] + sorted(seen) diff --git a/prep_heb_knesset_weak.py b/prep_heb_knesset_weak.py new file mode 100644 index 0000000..d41a0b4 --- /dev/null +++ b/prep_heb_knesset_weak.py @@ -0,0 +1,321 @@ +# /// script +# requires-python = ">=3.11" +# dependencies = [ +# "py7zr>=0.21", +# "huggingface_hub>=0.26", +# ] +# /// +"""WO92 prep — Phonikud knesset_nikud_v6 weak-pretrain corpus builder. + +Builds the stage-1 WEAK-PRETRAIN corpus for the Hebrew plane campaign +(TODO.sota/92): Dicta machine labels, so it is weak supervision ONLY — +never the quality/eval signal (no-teacher-poison rule). + +Pipeline (all inside the job; corpora NEVER touch the laptop): + 1. Fetch knesset_nikud_v6.txt.7z from Phonikud/phonikud-data (MIT, + verified via the dataset card). Record sha256 + size. + 2. Extract with py7zr; stream the single-column v6 lines + (nikud + '|' syllable separators + stress/teamim marks). + 3. Normalize to plane-consumer targets: keep Hebrew letters, the + nikud plane mark set (nikud_planes.NIKUD_MARKS — the trainer's own + definition), ASCII, whitespace; drop '|' / teamim / stress / + phonikud custom marks. src = target minus nikud marks. + 4. Filters (the s45 recipe, VERIFIED 2026-08-20): 10 <= len(src) + <= 300 chars, Hebrew fraction >= 0.6 of non-space, nikud density + >= len(src non-space)/12. + 5. Exact-input dedupe on the normalized skeleton (knesset is + formulaic — the prior pass measured 2.48M of 5.3M exact + duplicates). First occurrence wins; source order preserved. + 6. Decontamination vs the human-verified eval set (hebrew-v4 + test.jsonl): 40-char windows (stride 20) over Hebrew-letter-only + normal forms of BOTH sides. + 7. Emit contiguous shards (source order), manifest.json with every + count, and a SHA256SUMS sidecar for every emitted file. + 8. Upload to hf://datasets/{HEB_WEAK_REPO} (private) + an eval-set + census (re-counted in-job from the mounted hebrew-v4). + +Usage: + hf jobs uv run --flavor cpu-upgrade -d --timeout 4h -s HF_TOKEN \ + -v hf://datasets/Interscript/hebrew-v4:/train_data:ro \ + --name heb-weakprep-data prep_heb_knesset_weak.py +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import shutil +import sys +from datetime import datetime, timezone +from pathlib import Path + +WORK = Path(os.environ.get("HEB_WORK", "/scratch")) +TEST_DATA = Path(os.environ.get("HEB_TEST_DATA", "/train_data")) +REPO_ID = os.environ.get("HEB_WEAK_REPO", "Interscript/he-knesset-v6-weak") +N_SHARDS = int(os.environ.get("HEB_SHARDS", "8")) +ARCHIVE = "knesset_nikud_v6.txt.7z" +UPSTREAM = "Phonikud/phonikud-data" +UPSTREAM_URL = f"https://huggingface.co/datasets/{UPSTREAM}/resolve/main/{ARCHIVE}" + +sys.path.insert(0, "/code") +from nikud_planes import NIKUD_MARKS # noqa: E402 (the trainer's own mark set) + +# s45 mark policy, aligned to the plane set: keep plane nikud marks, +# drop '|' syllable separators, teamim/stress, phonikud custom marks. +# (maqqaf U+05BE stays — nikud_planes keeps it in the skeleton.) +# The v6 separators, per phonikud's own source: PREFIX_CHAR = "|" +# (ASCII U+007C) and HATAMA_CHAR = U+05AB (stress). '|' is inside the +# ASCII-printable band, so it is dropped EXPLICITLY — the s45 comment +# said drop but its ASCII range accidentally kept it. +KEEP_PREDICATE = NIKUD_MARKS +DROP_CHARS = frozenset("|") + + +def _is_hebrew_letter(c: str) -> bool: + return "א" <= c <= "ת" + + +def normalize_line(line: str) -> tuple[str, str] | None: + """Raw v6 line -> (src skeleton, tgt plane target) or None if filtered.""" + tgt_chars = [] + for c in line: + if c in DROP_CHARS: + continue + if c in KEEP_PREDICATE or _is_hebrew_letter(c) or c.isspace() or (33 <= ord(c) <= 126): + tgt_chars.append(c) + # drop: '|' (explicit), teamim/stress, phonikud custom marks, anything else + target = "".join(tgt_chars).strip() + src = "".join(c for c in target if c not in NIKUD_MARKS).strip() + if not (10 <= len(src) <= 300): + return None + letters = sum(1 for c in src if _is_hebrew_letter(c)) + if letters / max(1, len(src.replace(" ", ""))) < 0.6: + return None + nikud = sum(1 for c in target if c in NIKUD_MARKS) + if nikud < len(src.replace(" ", "")) / 12: + return None + return src, target + + +def _letter_norm(text: str) -> str: + """Hebrew letters + single-spaced whitespace — the decontam normal form.""" + return re.sub(r"\s+", " ", "".join(c for c in text if _is_hebrew_letter(c) or c == " ")).strip() + + +def build_test_windows(path: Path) -> set[str]: + """40-char windows (stride 20) over letter-normal forms of the eval set.""" + windows: set[str] = set() + with path.open(encoding="utf-8") as f: + for line in f: + if not line.strip(): + continue + row = json.loads(line) + for side in (row.get("src", ""), row.get("tgt", "")): + norm = _letter_norm(side) + for i in range(0, max(1, len(norm) - 40), 20): + windows.add(norm[i : i + 40]) + return windows + + +def sha256_file(p: Path) -> str: + h = hashlib.sha256() + with p.open("rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + h.update(chunk) + return h.hexdigest() + + +def main() -> None: + from huggingface_hub import HfApi, hf_hub_download + import py7zr + + WORK.mkdir(parents=True, exist_ok=True) + out_dir = WORK / "out" + if out_dir.exists(): + shutil.rmtree(out_dir) + out_dir.mkdir() + + # ---- 1. fetch + pin the upstream archive ---- + archive_path = Path(hf_hub_download(UPSTREAM, ARCHIVE, repo_type="dataset")) + arch_sha = sha256_file(archive_path) + arch_size = archive_path.stat().st_size + print(f"[fetch] {ARCHIVE} size={arch_size} sha256={arch_sha}", flush=True) + KNOWN_SIZE = 142_845_067 # observed 2026-11-19; upstream re-upload changes this + if arch_size != KNOWN_SIZE: + print(f"[warn] archive size {arch_size} != pinned {KNOWN_SIZE} — " + "upstream may have changed; manifest records what we used", flush=True) + + # ---- 2. extract ---- + txt_path = WORK / "knesset_nikud_v6.txt" + if not txt_path.exists(): + print("[extract] ...", flush=True) + with py7zr.SevenZipFile(archive_path, mode="r") as z: + z.extractall(WORK) + + # ---- 3-6. normalize / filter / dedupe / decontam ---- + test_path = TEST_DATA / "test.jsonl" + test_windows = build_test_windows(test_path) + print(f"[decontam] {len(test_windows)} test windows", flush=True) + + seen_src: set[str] = set() + seen_lines: set[str] = set() + survivors: list[tuple[str, str]] = [] + n_lines = n_kept = n_dup = n_rawdup = n_contam = n_filtered = 0 + with txt_path.open(encoding="utf-8") as f: + for line in f: + n_lines += 1 + stripped = line.strip() + if not stripped: + continue + if stripped in seen_lines: + n_rawdup += 1 + else: + seen_lines.add(stripped) + pair = normalize_line(stripped) + if pair is None: + n_filtered += 1 + continue + src, target = pair + if src in seen_src: + n_dup += 1 + continue + norm = _letter_norm(src) + if any(norm[i : i + 40] in test_windows for i in range(0, max(1, len(norm) - 40), 20)): + n_contam += 1 + continue + seen_src.add(src) + survivors.append((src, target)) + n_kept += 1 + if n_kept % 250_000 == 0: + print(f"[prep] kept={n_kept} dup={n_dup} rawdup={n_rawdup} " + f"contam={n_contam} filtered={n_filtered}", flush=True) + + print(f"[prep] lines={n_lines} kept={n_kept} dup={n_dup} rawdup={n_rawdup} " + f"contam={n_contam} filtered={n_filtered}", flush=True) + + # ---- 7. contiguous shards + manifest + sha256 sidecar ---- + shard_names = [] + shard_meta = [] + total = len(survivors) + for s in range(N_SHARDS): + lo = total * s // N_SHARDS + hi = total * (s + 1) // N_SHARDS + name = f"heb-knesset-weak-{s:05d}-of-{N_SHARDS:05d}.jsonl" + p = out_dir / name + with p.open("w", encoding="utf-8") as f: + for src, target in survivors[lo:hi]: + f.write(json.dumps({"src": src, "tgt": target}, ensure_ascii=False) + "\n") + shard_names.append(name) + shard_meta.append({"file": name, "rows": hi - lo, "sha256": sha256_file(p)}) + print(f"[shard] {name} rows={hi - lo}", flush=True) + + # eval-set census, re-counted in-job from the mounted human-verified set + def count_rows(p: Path) -> int: + n = 0 + with p.open(encoding="utf-8") as f: + for line in f: + if line.strip(): + n += 1 + return n + + eval_census = { + "test_rows": count_rows(test_path), + "train_rows": count_rows(TEST_DATA / "train.jsonl"), + "note": "test.jsonl is the held-out HUMAN-VERIFIED eval set " + "(Nakdimon-derived; the crown heb-vocalized-plane-2.0 protocol)", + } + print(f"[census] {eval_census}", flush=True) + + manifest = { + "campaign": "WO92 heb weak-pretrain (TODO.sota/92, interscript-models)", + "built_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "source": { + "dataset": UPSTREAM, + "file": ARCHIVE, + "url": UPSTREAM_URL, + "license": "MIT (dataset card cardData.license, verified 2026-11-19)", + "sha256": arch_sha, + "bytes": arch_size, + "labels": "Dicta machine diacritizer + ~1k manual high-frequency " + "corrections — WEAK supervision only, never eval/quality", + "format": "single-column v6: nikud + '|' syllable separators + " + "stress/teamim marks", + }, + "policy": { + "normalize": "keep Hebrew letters + nikud_planes.NIKUD_MARKS + " + "ASCII + whitespace; drop '|'/teamim/stress/custom marks", + "filters": "10 <= len(src) <= 300 chars; Hebrew fraction >= 0.6 of " + "non-space; nikud density >= len(src non-space)/12 (s45)", + "dedupe": "exact-input (normalized skeleton) dedupe, first " + "occurrence wins, source order preserved", + "decontam": "40-char windows (stride 20) over Hebrew-letter normal " + "forms vs hebrew-v4 test.jsonl both sides", + "sharding": "contiguous source-order slices", + }, + "counts": { + "lines_total": n_lines, + "kept_unique": n_kept, + "skeleton_dup_dropped": n_dup, + "raw_line_dup_seen": n_rawdup, + "contam_dropped": n_contam, + "filter_dropped": n_filtered, + }, + "shards": shard_meta, + "eval_census": eval_census, + } + manifest_path = out_dir / "manifest.json" + manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=1), + encoding="utf-8") + + sums_lines = [f"{m['sha256']} {m['file']}" for m in shard_meta] + sums_lines.append(f"{sha256_file(manifest_path)} manifest.json") + (out_dir / "SHA256SUMS.txt").write_text("\n".join(sums_lines) + "\n", + encoding="utf-8") + + readme = f"""--- +license: mit +task_categories: +- text-classification +language: +- he +--- + +# heb-knesset-v6-weak — WO92 weak-pretrain corpus + +Derived from [{UPSTREAM}]({UPSTREAM_URL}) `knesset_nikud_v6.txt.7z` +(MIT; sha256 `{arch_sha[:16]}…`). Labels are Dicta MACHINE diacritization +(+ ~1k manual high-frequency corrections): **weak supervision only — +never the quality or eval signal** (no-teacher-poison rule). + +Normalization/filters/dedupe/decontam policy and every count are in +`manifest.json`; `SHA256SUMS.txt` pins all files. + +- rows kept (unique skeletons): {n_kept} +- skeleton dups dropped: {n_dup}; raw line dups seen: {n_rawdup} +- decontam drops vs hebrew-v4 test.jsonl: {n_contam} +- eval census: {eval_census["test_rows"]} human-verified test rows + +Consumed by the Hebrew plane trainer (run-093) via HfFileSystem mount. +""" + (out_dir / "README.md").write_text(readme, encoding="utf-8") + + # ---- 8. upload ---- + api = HfApi() + api.create_repo(REPO_ID, repo_type="dataset", private=True, exist_ok=True) + api.upload_folder(repo_id=REPO_ID, repo_type="dataset", folder_path=out_dir) + print(f"[upload] {REPO_ID} done", flush=True) + + summary = {"repo": REPO_ID, "kept": n_kept, "dup": n_dup, + "rawdup": n_rawdup, "contam": n_contam, + "filtered": n_filtered, "lines": n_lines, + "test_rows": eval_census["test_rows"], + "archive_sha256": arch_sha} + print("[summary] " + json.dumps(summary), flush=True) + (out_dir.parent / "PREP_DONE").write_text(json.dumps(summary, indent=1) + "\n", + encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/test_heb_weakprep.py b/test_heb_weakprep.py new file mode 100644 index 0000000..54dbc63 --- /dev/null +++ b/test_heb_weakprep.py @@ -0,0 +1,135 @@ +"""Tests for the WO92 knesset weak-pretrain prep (normalize/filter/dedupe/decontam). + +Real string instances throughout — no doubles, no network, no disk +fixtures beyond a tmp file. +""" + +import json +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import nikud_planes # noqa: F401 (prep imports it via /code in the job) +import prep_heb_knesset_weak as P + + +class TestNormalizeLine(unittest.TestCase): + def test_strips_syllable_and_stress_marks(self): + # '|' syllable separator + teamim/stress + custom marks are dropped; + # nikud plane marks are kept + line = "שָׁ|לוֹ|ם עַ|ל הָ|אָ֗רֶץ" + pair = P.normalize_line(line) + self.assertIsNotNone(pair) + src, tgt = pair + self.assertNotIn("|", tgt) + self.assertNotIn("֗", tgt) # teamim dropped + self.assertNotIn("֫", tgt) # stress (ateh) dropped + self.assertIn("שָׁלוֹם", tgt) + self.assertEqual(src, "".join(c for c in tgt if c not in nikud_planes.NIKUD_MARKS).strip()) + + def test_round_trip_through_plane_split(self): + pair = P.normalize_line("הַ|דְּ|בָרִ|ים הָ|אֵ|לֶּה") + self.assertIsNotNone(pair) + tgt = pair[1] + skel, classes = nikud_planes.split_planes(tgt) + self.assertEqual(nikud_planes.render(skel, classes), tgt) + + def test_short_line_filtered(self): + self.assertIsNone(P.normalize_line("שָׁלוֹם")) + + def test_long_line_filtered(self): + self.assertIsNone(P.normalize_line("שָׁלוֹם " * 65)) + + def test_ascii_pipe_dropped_explicitly(self): + # phonikud PREFIX_CHAR is ASCII U+007C — inside the printable band, + # so the drop must be explicit, not a side effect of the range check + pair = P.normalize_line("שָׁ|לוֹ|ם עַ|ל הָ|אָרֶץ בָּ|אָרֶץ") + self.assertIsNotNone(pair) + self.assertNotIn("|", pair[1]) + self.assertNotIn("|", pair[0]) + + def test_low_hebrew_fraction_filtered(self): + self.assertIsNone(P.normalize_line("hello world 12345 שָׁלוֹם")) + + def test_low_nikud_density_filtered(self): + self.assertIsNone(P.normalize_line("אבגדהוזחטיכלמנסעפצקרשת אבגדהוזחטיכלמנס")) + + def test_ascii_and_whitespace_kept(self): + pair = P.normalize_line("בַּיּוֹם הַהוּא 2026 (והַשָּׁלוֹם)") + self.assertIsNotNone(pair) + self.assertIn("2026", pair[1]) + + +class TestLetterNorm(unittest.TestCase): + def test_drops_nikud_punct_and_marks(self): + norm = P._letter_norm("שָׁלוֹם, עֲלֵיכֶם| — 123") + self.assertEqual(norm, "שלום עליכם") + + def test_collapses_whitespace_runs(self): + self.assertEqual(P._letter_norm("א ב דֶּשֶׁם"), "א ב דשם") + + +class TestBuildTestWindows(unittest.TestCase): + def test_windows_from_both_sides(self): + with tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False, encoding="utf-8") as f: + row = {"src": "וידבר אלהים את כל הדברים האלה לאמר", + "tgt": "וַיְדַבֵּר אֱלֹהִים אֶת כָּל הַדְּבָרִים הָאֵלֶּה לֵאמֹר"} + f.write(json.dumps(row) + "\n") + path = Path(f.name) + try: + windows = P.build_test_windows(path) + self.assertGreater(len(windows), 0) + # a 40-letter slice of the normalized src must be in the window set + norm = P._letter_norm(row["src"]) + self.assertTrue(any(norm[i:i + 40] in windows + for i in range(0, max(1, len(norm) - 40), 20))) + finally: + path.unlink(missing_ok=True) + + def test_contam_window_matches_normalized_variant(self): + # nikud/punct variants of the same text must collide in the window set + with tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False, encoding="utf-8") as f: + f.write(json.dumps({"src": "אבגדהוזחטיכלמנסעפצקרשתאבגדהוזחטיכל", + "tgt": "אבגדהוזחטיכלמנסעפצקרשתאבגדהוזחטיכל"}) + "\n") + path = Path(f.name) + try: + windows = P.build_test_windows(path) + variant = P._letter_norm("אבגדהוזחטיכלמנסעפצקרשתאבגדהוזחטיכל") + hit = any(variant[i:i + 40] in windows + for i in range(0, max(1, len(variant) - 40), 20)) + self.assertTrue(hit) + finally: + path.unlink(missing_ok=True) + + +class TestDedupePolicyContract(unittest.TestCase): + def test_skeleton_dup_is_detected_by_set_semantics(self): + # the policy: exact-input (skeleton) dedupe — same skeleton from + # differently-marked lines is a dup; first occurrence wins + a = P.normalize_line("שָׁלוֹם עֲלֵיכֶם כֹּל יִשְׂרָאֵל עַם אֶחָד בְּאָרְצוֹ") + b = P.normalize_line("שָׁלוֹם עֲלֵיכֶם כֹּל יִשְׂרָאֵל עַם אֶחָד בְּאָרְצוֹ") + self.assertEqual(a[0], b[0]) + seen = set() + self.assertTrue(a[0] not in seen) + seen.add(a[0]) + self.assertTrue(b[0] in seen) + + +class TestSha256File(unittest.TestCase): + def test_known_digest(self): + with tempfile.NamedTemporaryFile("wb", suffix=".txt", delete=False) as f: + f.write(b"heb weak prep\n") + path = Path(f.name) + try: + import hashlib + self.assertEqual(P.sha256_file(path), + hashlib.sha256(b"heb weak prep\n").hexdigest()) + finally: + path.unlink(missing_ok=True) + + +if __name__ == "__main__": + unittest.main() diff --git a/test_nikud_planes.py b/test_nikud_planes.py new file mode 100644 index 0000000..9bc2423 --- /dev/null +++ b/test_nikud_planes.py @@ -0,0 +1,60 @@ +"""Tests for the Hebrew nikud plane decomposition (byte-exact inverse).""" + +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from nikud_planes import NIKUD_MARKS, canon_combo, plane_classes, render, split_planes + + +class TestNikudPlanes(unittest.TestCase): + def test_split_render_round_trip(self): + text = "שָׁלוֹם עֲלֵיכֶם" + skel, classes = split_planes(text) + self.assertEqual(skel, "שלום עליכם") + self.assertEqual(len(classes), len(skel)) + self.assertEqual(render(skel, classes), text) + + def test_marks_close_into_previous_letter(self): + skel, classes = split_planes("בְּרֵאשִׁית") + self.assertEqual(skel, "בראשית") + # dagesh+sheva on bet, tsere on alef... each cluster one class + self.assertTrue(classes[0]) + self.assertEqual(render(skel, classes), "בְּרֵאשִׁית") + + def test_bare_text_is_all_empty_classes(self): + skel, classes = split_planes("שלום עליכם") + self.assertEqual(classes, [""] * len(skel)) + + def test_canon_preserves_written_order(self): + # cluster order is preserved as written (corpus convention) + self.assertEqual(canon_combo("ְּ"), "ְּ") + self.assertEqual(canon_combo("ָּ"), "ָּ") + + def test_maqqaf_stays_in_skeleton(self): + skel, classes = split_planes("וְכָל־הָעָם") + self.assertIn("־", skel) + self.assertEqual(render(skel, classes), "וְכָל־הָעָם") + + def test_plane_classes_is_stable_inventory(self): + self.assertIn("ָ", plane_classes(["שָׁלוֹם", "דָּבָר"])) + + def test_real_corpus_round_trip(self): + path = Path(__file__).resolve().parent / "data/hebrew-distilled/train.txt" + if not path.exists(): + self.skipTest("corpus not present") + n = 0 + for line in path.read_text(encoding="utf-8").splitlines()[:500]: + line = line.strip() + if not line: + continue + skel, classes = split_planes(line) + self.assertEqual(render(skel, classes), line, line[:40]) + n += 1 + self.assertGreater(n, 100) + + +if __name__ == "__main__": + unittest.main() diff --git a/train_hebrew_weakpre_hf.py b/train_hebrew_weakpre_hf.py new file mode 100644 index 0000000..4e8eaa0 --- /dev/null +++ b/train_hebrew_weakpre_hf.py @@ -0,0 +1,380 @@ +# /// script +# requires-python = ">=3.11" +# dependencies = [ +# "torch==2.5.1", +# "transformers==4.46.3", +# "accelerate>=1.1.0", +# ] +# /// +"""run-093 — Hebrew weak-pretrain on HF Jobs (WO92, TODO.sota/92). + +Stage 1 of the s45-style curriculum ported to the plane crown lineage +(heb-vocalized-plane-2.0, DER 8.18): pretrain the ByT5-base plane model +on the DEDUPED Dicta-machine-labeled knesset-v6 corpus +(hf://datasets/Interscript/he-knesset-v6-weak) COMBINED with the full +gold train corpus (hebrew-v4 train.jsonl, 50,433 — the combined-corpus +lesson). Stage 2 (gold SFT with the exact crown recipe from this +checkpoint) is OWNER-GATED on the eval-set decision and never launches +from this run automatically. + +Engineering laws carried (verified on this stack): +- ByT5's internal T5-norm stays AS-PRETRAINED: the crown recipe + (bf16 autocast + fp32 CE logits) is proven stable at run-021/022/026. + No new RMSNorm modules; custom modules (plane_emb, head) are plain + fp32 params. The LayerNorm fix applies to any custom norm module — + the catastrophic RMSNorm+bf16 finding was the custom stack, and this + trainer contains no custom norm. +- ByT5 byte table: ids come from AutoTokenizer ONLY (input_ids[:-1] + strips the trailing EOS id 1); raw text.bytes is silent garbage. +- Decode/eval is single-row GREEDY (K-pass mask-predict argmax) — + beam is counterproductive on flat byte students and is never used + here, matching the shipped crown protocol. + +Resume contract (crown pattern): step-N/ dirs with labels.sha +(sha256[:12] of the inventory bytes) + optim.pt; inventory.json built +once from THIS run's corpus and reused by stage 2 (vocab path +consistency). + +Usage: + hf jobs uv run --flavor a100-large -d --timeout 23h -s HF_TOKEN \ + -v hf://datasets/Interscript/he-knesset-v6-weak:/weak_data:ro \ + -v hf://datasets/Interscript/hebrew-v4:/train_data:ro \ + -v hf://buckets/Interscript/isx-training:/ckpt:rw \ + -v /tmp/heb-weak-code:/code:ro \ + --name run-093-heb-weak-pretrain train_hebrew_weakpre_hf.py + # arms via env: HEB_RUN / HEB_EPOCHS / HEB_BS / HEB_ACCUM / + # HEB_MAX_WEAK / HEB_CKPT_EVERY +""" + +from __future__ import annotations + +import hashlib +import json +import os +import random +import re +import sys +from pathlib import Path + +sys.path.insert(0, "/code") +sys.path.insert(0, "/code/src") + +DATA = Path("/train_data") # hebrew-v4 (gold + human-verified test) +WEAK = Path("/weak_data") # he-knesset-v6-weak (machine labels) +CKPT = Path("/ckpt") +RUN = os.environ.get("HEB_RUN", "run-093-heb-weak-pretrain") +BACKBONE = os.environ.get("HEB_BACKBONE", "google/byt5-base") +EPOCHS = int(os.environ.get("HEB_EPOCHS", "1")) +K_PASSES = int(os.environ.get("HEB_K", "3")) +MICRO_BS = int(os.environ.get("HEB_BS", "8")) +GRAD_ACCUM = int(os.environ.get("HEB_ACCUM", "2")) +MAX_WEAK = int(os.environ.get("HEB_MAX_WEAK", "1_500_000")) +CKPT_EVERY = int(os.environ.get("HEB_CKPT_EVERY", "1000")) +UNIT_BYTES = 1400 +N_VAL = 2_000 + +import torch +import torch.nn as nn +from torch.utils.data import DataLoader, Dataset +from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, get_cosine_schedule_with_warmup + +import nikud_planes as NP +from rababa.evaluate import seq2seq_der + + +def split_windows(text: str, budget: int = UNIT_BYTES) -> list[str]: + if len(text.encode("utf-8")) <= budget: + return [text] + words = text.split() + wins, cur, n = [], [], 0 + for w in words: + c = len(w.encode("utf-8")) + 1 + if cur and n + c > budget: + wins.append(" ".join(cur)) + cur, n = [], 0 + cur.append(w) + n += c + if cur: + wins.append(" ".join(cur)) + return wins + + +def load_jsonl(path: Path) -> list[dict]: + return [json.loads(l) for l in path.read_text(encoding="utf-8").splitlines() if l.strip()] + + +def main() -> None: + run_dir = CKPT / RUN + run_dir.mkdir(parents=True, exist_ok=True) + done_marker = run_dir / "EVAL_DONE" + prog_name = f"eval_progress_{done_marker.name}.jsonl" + + # ---- corpus: deduped weak shards + FULL gold train (combined) ---- + weak_units: list[str] = [] + for shard in sorted(WEAK.glob("heb-knesset-weak-*.jsonl")): + for row in load_jsonl(shard): + t = row["tgt"].strip() + if t and len(t.encode("utf-8")) <= 1450: + weak_units.append(t) + random.Random(42).shuffle(weak_units) + weak_units = weak_units[:MAX_WEAK] + + gold_units = [] + for row in load_jsonl(DATA / "train.jsonl"): + t = row["tgt"].strip() + if t and len(t.encode("utf-8")) <= 1450: + gold_units.append(t) + + units = weak_units + gold_units + random.Random(42).shuffle(units) + print(f"[data] weak={len(weak_units)} gold={len(gold_units)} " + f"combined={len(units)}", flush=True) + + inv_path = run_dir / "inventory.json" + if inv_path.exists(): + classes = json.loads(inv_path.read_text(encoding="utf-8")) + else: + from collections import Counter + + counts: Counter = Counter() + for u in units: + _, cls = NP.split_planes(u) + counts.update(c for c in cls if c) + classes = [""] + sorted(counts) + inv_path.write_text(json.dumps(classes, ensure_ascii=False), encoding="utf-8") + print(f"[inventory] {len(classes)} classes (incl. none)", flush=True) + class_to_id = {c: i for i, c in enumerate(classes)} + n_classes = len(classes) + MASK_ID = n_classes + labels_digest = hashlib.sha256(inv_path.read_bytes()).hexdigest()[:12] + + tok = AutoTokenizer.from_pretrained(BACKBONE) + + def encode_unit(text: str): + skel, labels = NP.split_planes(text) + ids = tok(skel).input_ids[:-1] # ByT5 byte table via tokenizer; drop EOS + label_ids = [0] * len(ids) + pos = 0 + for ch, lab in zip(skel, labels): + n = len(ch.encode("utf-8")) + cid = class_to_id.get(lab, 0) + for t in range(pos, min(pos + n, len(label_ids))): + label_ids[t] = cid + pos += n + return ids, label_ids + + class PlaneDS(Dataset): + def __init__(self, rows): + self.rows = rows + + def __len__(self): + return len(self.rows) + + def __getitem__(self, i): + return encode_unit(self.rows[i]) + + def collate(batch): + mx = max(len(x[0]) for x in batch) + ids = torch.zeros((len(batch), mx), dtype=torch.long) + lab = torch.zeros((len(batch), mx), dtype=torch.long) + am = torch.zeros((len(batch), mx), dtype=torch.long) + for i, (x, y) in enumerate(batch): + ids[i, : len(x)] = torch.tensor(x) + lab[i, : len(y)] = torch.tensor(y) + am[i, : len(x)] = 1 + return ids, am, lab + + val_rows = units[-N_VAL:] + train_units = units[:-N_VAL] + train_loader = DataLoader( + PlaneDS(train_units), batch_size=MICRO_BS, shuffle=True, collate_fn=collate, + num_workers=2, drop_last=True, + ) + total_steps = (len(train_loader) // GRAD_ACCUM) * EPOCHS + print(f"[data] train={len(train_units)} val={len(val_rows)} steps={total_steps} " + f"classes={n_classes}", flush=True) + + backbone = AutoModelForSeq2SeqLM.from_pretrained(BACKBONE) + encoder = backbone.encoder.cuda().train() + d_model = encoder.config.d_model + + plane_emb = nn.Embedding(n_classes + 1, d_model).cuda().train() + nn.init.normal_(plane_emb.weight, std=0.02) + head = nn.Linear(d_model, n_classes).cuda().train() + + params = list(encoder.parameters()) + list(plane_emb.parameters()) + list(head.parameters()) + optimizer = torch.optim.AdamW(params, lr=1e-4, weight_decay=0.01) + scheduler = get_cosine_schedule_with_warmup(optimizer, 500, total_steps) + ce = nn.CrossEntropyLoss() + + def usable(ck: Path) -> bool: + m = ck / "labels.sha" + return m.exists() and m.read_text().strip() == labels_digest + + ckpts = sorted((c for c in run_dir.glob("step-*") if usable(c)), + key=lambda p: int(p.name.split("-")[1])) + step = 0 + if ckpts: + sd = torch.load(ckpts[-1] / "model.pt", map_location="cpu", weights_only=True) + encoder.load_state_dict(sd["encoder"]) + plane_emb.load_state_dict(sd["plane_emb"]) + head.load_state_dict(sd["head"]) + optimizer.load_state_dict(torch.load(ckpts[-1] / "optim.pt", map_location="cpu", weights_only=True)) + step = int(ckpts[-1].name.split("-")[1]) + for _ in range(step): + scheduler.step() + print(f"[resume] step-{step}", flush=True) + + def forward_logits(ids, am, plane_in): + embeds = encoder.embed_tokens(ids) + plane_emb(plane_in) + out = encoder(inputs_embeds=embeds, attention_mask=am) + return head(out.last_hidden_state) + + def save_ckpt(s: int) -> None: + ck = run_dir / f"step-{s}" + ck.mkdir(exist_ok=True) + (ck / "labels.sha").write_text(labels_digest) + torch.save({"encoder": encoder.state_dict(), + "plane_emb": plane_emb.state_dict(), + "head": head.state_dict()}, ck / "model.pt") + torch.save(optimizer.state_dict(), ck / "optim.pt") + print(f"[ckpt] step-{s} saved", flush=True) + + import time + + optimizer.zero_grad() + micro = 0 + t0 = time.time() + for _epoch in range(EPOCHS): + for ids, am, lab in train_loader: + if step >= total_steps: + break + ids, am, lab = ids.cuda(), am.cuda(), lab.cuda() + q = random.random() + keep = (torch.rand_like(lab, dtype=torch.float) >= q).long() * am + plane_in = torch.where(keep == 1, lab, torch.full_like(lab, MASK_ID)) + with torch.autocast("cuda", torch.bfloat16): + logits = forward_logits(ids, am, plane_in) + # fp32 CE over bf16 logits — the crown stability contract + loss = ce(logits.float().reshape(-1, n_classes), lab.reshape(-1)) / GRAD_ACCUM + loss.backward() + micro += 1 + if micro % GRAD_ACCUM == 0: + torch.nn.utils.clip_grad_norm_(params, 1.0) + optimizer.step() + scheduler.step() + optimizer.zero_grad() + step += 1 + if step % 50 == 0: + rate = step / max(1e-9, time.time() - t0) + eta_h = (total_steps - step) / max(1e-9, rate) / 3600.0 + print(f"[{RUN} step {step}/{total_steps}] " + f"ce={float(loss) * GRAD_ACCUM:.4f} q={q:.2f} " + f"eta={eta_h:.1f}h", flush=True) + if step % CKPT_EVERY == 0: + save_ckpt(step) + + best = run_dir / "best" + best.mkdir(exist_ok=True) + torch.save({"encoder": encoder.state_dict(), + "plane_emb": plane_emb.state_dict(), + "head": head.state_dict(), + "classes": classes, + "corpus": {"weak": len(weak_units), "gold": len(gold_units)}}, + best / "model.pt") + print("[ckpt] best saved", flush=True) + + # ---- informational eval: human-verified test (NEVER the weak labels) ---- + # Crown protocol verbatim: 1400-byte windows, K-pass GREEDY mask-predict, + # original-separator stitching, seq2seq_der. + encoder.eval() + plane_emb.eval() + head.eval() + + targets = [r["tgt"] for r in load_jsonl(DATA / "test.jsonl")] + all_windows: list[str] = [] + counts_w: list[int] = [] + for text in targets: + ws = split_windows(text.strip()) + counts_w.append(len(ws)) + all_windows.extend(ws) + print(f"[eval] {len(targets)} examples -> {len(all_windows)} windows", flush=True) + + prog = run_dir / prog_name + saved: dict[int, str] = {} + if prog.exists(): + for line in prog.read_text(encoding="utf-8").splitlines(): + if line.strip(): + row = json.loads(line) + saved[row["i"]] = row["pred"] + print(f"[gen] resuming with {len(saved)} saved windows", flush=True) + + @torch.no_grad() + def predict_window(text: str) -> str: + skel, _ = NP.split_planes(text) + ids = tok(skel).input_ids[:-1] + t_ids = torch.tensor([ids], device="cuda") + am = torch.ones_like(t_ids) + plane = torch.full_like(t_ids, MASK_ID) + preds = None + for _ in range(K_PASSES): + with torch.autocast("cuda", torch.bfloat16): + logits = forward_logits(t_ids, am, plane) + preds = logits.argmax(-1) + plane = preds + pos = 0 + char_preds: list[str] = [] + for ch in skel: + n = len(ch.encode("utf-8")) + votes = preds[0, pos : pos + n].tolist() + cid = max(set(votes), key=votes.count) + char_preds.append(classes[cid] if cid < n_classes else "") + pos += n + return NP.render(skel, char_preds) + + missing = [i for i in range(len(all_windows)) if i not in saved] + with prog.open("a", encoding="utf-8") as prog_out: + for n_done, i in enumerate(missing, 1): + pred = predict_window(all_windows[i]) + prog_out.write(json.dumps({"i": i, "pred": pred}, ensure_ascii=False) + "\n") + saved[i] = pred + if n_done % 200 == 0: + prog_out.flush() + print(f"[gen] {len(saved)}/{len(all_windows)}", flush=True) + + # stitch with ORIGINAL separators (run-021 lesson) + k = 0 + total_wrong = 0.0 + total_positions = 0 + for tgt, c in zip(targets, counts_w): + text = tgt.strip() + words = text.split() + seps = re.findall(r"\s+", text) + sep_for = {i: (seps[i] if i < len(seps) else "") for i in range(len(words))} + rebuilt: list[str] = [] + for _g in range(c): + pred = saved[k]; k += 1 + for w in pred.split(): + wi = sum(len(part.split()) for part in rebuilt) + rebuilt.append(w + sep_for.get(wi, " ")) + pred = "".join(rebuilt) + d, n = seq2seq_der(pred, tgt) + total_wrong += d * n + total_positions += n + + der = total_wrong / max(1, total_positions) + verdict = {"run": RUN, "stage": "weak-pretrain (WO92)", + "corpus": {"weak": len(weak_units), "gold": len(gold_units)}, + "steps": step, "k_passes": K_PASSES, "der": der, + "gate": "INFORMATIONAL — machine labels never gate quality; " + "stage-2 gold SFT is owner-gated (eval-set decision)", + "crown_baseline": 8.18} + (run_dir / "verdict.json").write_text(json.dumps(verdict, indent=1), encoding="utf-8") + print(f"\n===== {RUN} weak-pretrain nakdimon greedy DER: {der:.4f} " + f"(informational; crown heb-vocalized-plane-2.0 = 8.18) =====", flush=True) + done_marker.touch() + print("[done] EVAL_DONE", flush=True) + + +if __name__ == "__main__": + main()