| """Phase 1: build the tokenizer and the pretokenized corpus, upload to HF. |
| |
| Steps: |
| 1. stream the source dataset (hy Wikipedia by default) and dump a text sample |
| 2. train a SentencePiece unigram tokenizer on that sample |
| 3. tokenize the FULL corpus into a flat uint16 stream -> train.bin / val.bin |
| 4. upload tokenizer + .bin files to the HF dataset repo |
| |
| Run this on a high-RAM / many-CPU Colab runtime (or a strong local machine). |
| It does NOT need a TPU. Then run launch.py for the TPU training. |
| """ |
| from __future__ import annotations |
|
|
| import os |
| import time |
|
|
| import numpy as np |
|
|
|
|
| def _log(m: str) -> None: |
| print(f"[prepare {time.strftime('%H:%M:%S')}] {m}", flush=True) |
|
|
|
|
| |
| |
| |
| def _default_beat(_m: str) -> None: |
| from pathlib import Path |
| import time as _t |
| try: |
| p = Path("/content/train_logs/heartbeat.txt") |
| p.parent.mkdir(parents=True, exist_ok=True) |
| p.write_text(f"{_t.time():.0f} {_m}\n", encoding="utf-8") |
| except Exception: |
| pass |
|
|
|
|
| def main(beat=_default_beat) -> None: |
| import sentencepiece as spm |
| from datasets import load_dataset |
| from huggingface_hub import HfApi |
|
|
| from config import (MODEL, TOKENIZER, DATA_REPO, SOURCE_DATASET, |
| SOURCE_CONFIG, SOURCE_SPLIT) |
|
|
| hf_token = os.environ["HF_TOKEN"] |
| api = HfApi(token=hf_token) |
|
|
| def text_column(ds) -> str: |
| for c in ("text", "content", "raw_content", "document"): |
| if c in ds.column_names: |
| return c |
| return ds.column_names[0] |
|
|
| |
| _log(f"loading {SOURCE_DATASET}:{SOURCE_CONFIG} (streaming)") |
| beat("prepare: sampling text") |
| stream = load_dataset(SOURCE_DATASET, SOURCE_CONFIG, split=SOURCE_SPLIT, |
| streaming=True, token=hf_token) |
| col = text_column(stream) |
| _log(f"text column: {col}") |
|
|
| sample_path = "tok_sample.txt" |
| n = 0 |
| with open(sample_path, "w", encoding="utf-8") as f: |
| for row in stream: |
| t = (row.get(col) or "").strip() |
| if not t: |
| continue |
| f.write(t[: TOKENIZER.max_chars_per_row].replace("\n", " ") + "\n") |
| n += 1 |
| if n >= TOKENIZER.train_sample_rows: |
| break |
| _log(f"wrote {n:,} rows for tokenizer training") |
|
|
| |
| _log("training SentencePiece tokenizer") |
| beat("prepare: training tokenizer") |
| spm.SentencePieceTrainer.train( |
| input=sample_path, |
| model_prefix="armenian_sp", |
| vocab_size=TOKENIZER.vocab_size, |
| model_type=TOKENIZER.model_type, |
| character_coverage=TOKENIZER.character_coverage, |
| input_sentence_size=n, |
| shuffle_input_sentence=True, |
| bos_id=1, eos_id=2, unk_id=0, pad_id=3, |
| num_threads=os.cpu_count() or 8, |
| ) |
| sp = spm.SentencePieceProcessor(model_file="armenian_sp.model") |
| assert sp.vocab_size() == MODEL.vocab_size, ( |
| f"vocab mismatch: tokenizer {sp.vocab_size()} vs model {MODEL.vocab_size}") |
|
|
| |
| n_proc = max(1, (os.cpu_count() or 8)) |
| _log(f"tokenizing full corpus with num_proc={n_proc}") |
| beat(f"prepare: tokenizing corpus ({n_proc} cores)") |
| |
| full = load_dataset(SOURCE_DATASET, SOURCE_CONFIG, split=SOURCE_SPLIT, token=hf_token) |
|
|
| sp_model_path = os.path.abspath("armenian_sp.model") |
|
|
| def tok_batch(batch): |
| |
| proc = tok_batch._sp |
| if proc is None: |
| proc = spm.SentencePieceProcessor(model_file=sp_model_path) |
| tok_batch._sp = proc |
| eos_id = proc.eos_id() |
| out = [] |
| for t in batch[col]: |
| t = (t or "").strip() |
| if not t: |
| out.append([]) |
| continue |
| ids = proc.encode(t, out_type=int) |
| ids.append(eos_id) |
| out.append(ids) |
| return {"ids": out} |
| tok_batch._sp = None |
|
|
| tokenized = full.map(tok_batch, batched=True, batch_size=1000, |
| num_proc=n_proc, remove_columns=full.column_names, |
| desc="tokenize") |
|
|
| |
| _log("concatenating token stream") |
| parts = [np.asarray(x, dtype=np.uint16) for x in tokenized["ids"] if x] |
| all_ids = np.concatenate(parts) |
| _log(f"total tokens: {len(all_ids):,}") |
|
|
| |
| n_val = max(1, int(len(all_ids) * 0.005)) |
| all_ids[:-n_val].tofile("train.bin") |
| all_ids[-n_val:].tofile("val.bin") |
| _log(f"train.bin {len(all_ids) - n_val:,} | val.bin {n_val:,}") |
|
|
| |
| api.create_repo(DATA_REPO, repo_type="dataset", exist_ok=True) |
| for fn in ("train.bin", "val.bin", "armenian_sp.model", "armenian_sp.vocab"): |
| _log(f"uploading {fn}") |
| api.upload_file(path_or_fileobj=fn, path_in_repo=fn, |
| repo_id=DATA_REPO, repo_type="dataset") |
| _log("done. data ready on HF.") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|