''' Encode the silver corpus once into flat numpy arrays, so that every training run and Optuna trial reads the same cached tensors. python prepare_data.py --out cache/oga-no-norma Steps, matching the original train.py: 1. Read the `macronized` column of the HF dataset (default Urdatorn/oga-macronized-no-norma). 2. Fit the diacritic vocabulary on the first --vocab_fit_lines lines. 3. Shuffle the lines with --data_seed and hold out --val_fraction for validation. The split is fixed independently of the training seed, so every trial and every seed sees the same split. 4. Encode each line and cut it into chunks of at most --max_len characters. Lines and chunks with no label are dropped. Output files in --out: - {train,val}.npz: plane1 (uint8), plane2 (uint8), labels (int8, -100 = ignored) concatenated, plus offsets (int64, one more than the number of examples). - diacritic_vocab.json - meta.json ''' import argparse import glob import json import os import random import time from multiprocessing import Pool import numpy as np import pyarrow.parquet as pq from huggingface_hub import snapshot_download from tokenizer import DiacriticVocab, encode_macronized, LABEL_IGNORE_INDEX _vocab = _max_len = None def _init(vocab, max_len): global _vocab, _max_len _vocab, _max_len = vocab, max_len def _encode(line): enc = encode_macronized(line, _vocab, fit=False) out = [] if not enc["plane1"] or all(l == LABEL_IGNORE_INDEX for l in enc["labels"]): return out for s in range(0, len(enc["plane1"]), _max_len): lab = enc["labels"][s:s + _max_len] if any(l != LABEL_IGNORE_INDEX for l in lab): out.append((np.asarray(enc["plane1"][s:s + _max_len], np.uint8), np.asarray(enc["plane2"][s:s + _max_len], np.uint8), np.asarray(lab, np.int8))) return out def encode_split(lines, vocab, max_len, workers): p1, p2, lab, lens = [], [], [], [] with Pool(workers, initializer=_init, initargs=(vocab, max_len)) as pool: for i, chunks in enumerate(pool.imap(_encode, lines, chunksize=2000)): for a, b, c in chunks: p1.append(a); p2.append(b); lab.append(c); lens.append(len(a)) if (i + 1) % 200_000 == 0: print(f" encoded {i+1:,}/{len(lines):,} lines -> {len(lens):,} examples", flush=True) offsets = np.zeros(len(lens) + 1, np.int64) np.cumsum(lens, out=offsets[1:]) labels = np.concatenate(lab) return dict(plane1=np.concatenate(p1), plane2=np.concatenate(p2), labels=labels, offsets=offsets), labels def main(): ap = argparse.ArgumentParser() ap.add_argument("--dataset", default="Urdatorn/oga-macronized-no-norma") ap.add_argument("--revision", default=None) ap.add_argument("--out", required=True) ap.add_argument("--val_fraction", type=float, default=0.10) ap.add_argument("--data_seed", type=int, default=0) ap.add_argument("--max_len", type=int, default=384) ap.add_argument("--vocab_fit_lines", type=int, default=200_000) ap.add_argument("--max_lines", type=int, default=None, help="for quick tests only") ap.add_argument("--workers", type=int, default=os.cpu_count()) a = ap.parse_args() t0 = time.time() os.makedirs(a.out, exist_ok=True) from huggingface_hub import HfApi a.revision = HfApi().dataset_info(a.dataset, revision=a.revision).sha # pin and record the commit print(f"dataset {a.dataset} @ {a.revision}", flush=True) local = snapshot_download(a.dataset, repo_type="dataset", revision=a.revision, allow_patterns=["data/*.parquet"]) files = sorted(glob.glob(os.path.join(local, "data", "*.parquet"))) lines = [] for f in files: lines.extend(s for s in pq.read_table(f, columns=["macronized"]).column(0).to_pylist() if s and s.strip()) if a.max_lines: lines = lines[: a.max_lines] print(f"{len(lines):,} non-empty lines from {a.dataset} ({len(files)} files)", flush=True) vocab = DiacriticVocab() for line in lines[: a.vocab_fit_lines]: encode_macronized(line, vocab, fit=True) vocab.freeze() print(f"diacritic vocab: {len(vocab)} entries", flush=True) with open(os.path.join(a.out, "diacritic_vocab.json"), "w", encoding="utf-8") as f: json.dump(vocab.to_dict(), f, ensure_ascii=False, indent=2) idx = list(range(len(lines))) random.Random(a.data_seed).shuffle(idx) n_val = max(1, int(len(idx) * a.val_fraction)) splits = {"val": [lines[i] for i in sorted(idx[:n_val])], "train": [lines[i] for i in sorted(idx[n_val:])]} del lines meta = dict(vars(a), n_vocab=len(vocab)) for name, sl in splits.items(): print(f"encoding {name}: {len(sl):,} lines", flush=True) arrays, labels = encode_split(sl, vocab, a.max_len, a.workers) np.savez(os.path.join(a.out, f"{name}.npz"), **arrays) meta[name] = dict(lines=len(sl), examples=len(arrays["offsets"]) - 1, chars=int(len(arrays["plane1"])), labels={k: int((labels == v).sum()) for k, v in (("none", 0), ("short", 1), ("long", 2))}) print(f" {name}: {json.dumps(meta[name])}", flush=True) meta["seconds"] = round(time.time() - t0, 1) with open(os.path.join(a.out, "meta.json"), "w") as f: json.dump(meta, f, indent=2) print(f"done in {meta['seconds']}s -> {a.out}", flush=True) if __name__ == "__main__": main()