File size: 5,441 Bytes
9b59955
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
936877d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b59955
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
936877d
9b59955
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
936877d
9b59955
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37e9a48
 
 
936877d
37e9a48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b59955
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
"""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)


# Heartbeat so the supervisor sees prepare is progressing across its long,
# blocking phases (SentencePiece training, corpus tokenization). run_all injects
# the real writer; default is a no-op when prepare_data is run standalone.
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]

    # --- 1. sample text for tokenizer training ---
    _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")

    # --- 2. train SentencePiece ---
    _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}")

    # --- 3. tokenize full corpus in parallel across all host cores ---
    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)")
    # Non-streaming so datasets.map can shard across processes (hy wiki is small).
    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):
        # Each worker builds its own processor (SentencePieceProcessor isn't picklable).
        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")

    # Concatenate all id lists into one flat uint16 stream.
    _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):,}")

    # --- 4. split + write .bin ---
    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:,}")

    # --- 5. upload ---
    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()