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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Corpus'u tokenize edip nanoGPT formatinda .bin olarak kaydet.
|
| 3 |
+
|
| 4 |
+
HIZLANDIRMA:
|
| 5 |
+
- tokenizer.encode_batch (Rust + multi-threaded, single encode'dan ~5-8x hizli)
|
| 6 |
+
- Dosyaya inkremental yazma (RAM'de tum array tutulmuyor)
|
| 7 |
+
- Buyuk batch (5000 satir) — ic icine girmeden ust uste tokenize
|
| 8 |
+
|
| 9 |
+
Cikti:
|
| 10 |
+
data/train.bin (uint16 token id'leri)
|
| 11 |
+
data/val.bin
|
| 12 |
+
data/meta.pkl
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import pickle
|
| 17 |
+
import time
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
from tokenizers import Tokenizer
|
| 22 |
+
from tqdm import tqdm
|
| 23 |
+
|
| 24 |
+
DATA_DIR = Path(__file__).parent / "data"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def encode_file(tokenizer, in_path: Path, out_path: Path, eot_id: int,
|
| 28 |
+
batch_size: int = 5000, dtype=np.uint16):
|
| 29 |
+
print(f"\n{in_path.name} -> {out_path.name}")
|
| 30 |
+
t0 = time.time()
|
| 31 |
+
|
| 32 |
+
# Satir sayisini once say (progress bar icin)
|
| 33 |
+
print(" satir sayiliyor...", end=" ", flush=True)
|
| 34 |
+
n_lines = 0
|
| 35 |
+
with open(in_path, "r", encoding="utf-8") as f:
|
| 36 |
+
for _ in f:
|
| 37 |
+
n_lines += 1
|
| 38 |
+
print(f"{n_lines:,}")
|
| 39 |
+
|
| 40 |
+
total_tokens = 0
|
| 41 |
+
# Append modunda binary yaz — RAM'de tum array tutmuyoruz
|
| 42 |
+
out_path.unlink(missing_ok=True)
|
| 43 |
+
|
| 44 |
+
with open(in_path, "r", encoding="utf-8") as f, \
|
| 45 |
+
open(out_path, "ab", buffering=1024*1024) as out_f:
|
| 46 |
+
|
| 47 |
+
pbar = tqdm(total=n_lines, desc="tokenize", smoothing=0.05)
|
| 48 |
+
batch = []
|
| 49 |
+
|
| 50 |
+
def flush(batch):
|
| 51 |
+
if not batch:
|
| 52 |
+
return 0
|
| 53 |
+
# encode_batch Rust + multi-threaded, ic icine birden fazla cumle alir
|
| 54 |
+
encs = tokenizer.encode_batch(batch)
|
| 55 |
+
# Tum id'leri ve EOT'leri tek bir array'de birlestir
|
| 56 |
+
all_ids = []
|
| 57 |
+
for enc in encs:
|
| 58 |
+
all_ids.extend(enc.ids)
|
| 59 |
+
all_ids.append(eot_id)
|
| 60 |
+
arr = np.array(all_ids, dtype=dtype)
|
| 61 |
+
out_f.write(arr.tobytes())
|
| 62 |
+
return len(arr)
|
| 63 |
+
|
| 64 |
+
for line in f:
|
| 65 |
+
line = line.strip()
|
| 66 |
+
if not line:
|
| 67 |
+
pbar.update(1)
|
| 68 |
+
continue
|
| 69 |
+
batch.append(line)
|
| 70 |
+
if len(batch) >= batch_size:
|
| 71 |
+
total_tokens += flush(batch)
|
| 72 |
+
pbar.update(len(batch))
|
| 73 |
+
pbar.set_postfix(tokens=f"{total_tokens/1e6:.1f}M")
|
| 74 |
+
batch.clear()
|
| 75 |
+
|
| 76 |
+
# Son kalan
|
| 77 |
+
if batch:
|
| 78 |
+
total_tokens += flush(batch)
|
| 79 |
+
pbar.update(len(batch))
|
| 80 |
+
|
| 81 |
+
pbar.close()
|
| 82 |
+
|
| 83 |
+
elapsed = time.time() - t0
|
| 84 |
+
size_mb = out_path.stat().st_size / 1e6
|
| 85 |
+
speed = total_tokens / elapsed / 1e6
|
| 86 |
+
print(f" [OK] {total_tokens:,} token, {size_mb:.1f} MB, "
|
| 87 |
+
f"{elapsed:.1f}s ({speed:.2f}M token/s)")
|
| 88 |
+
return total_tokens
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def main():
|
| 92 |
+
parser = argparse.ArgumentParser()
|
| 93 |
+
parser.add_argument("--tokenizer", type=str,
|
| 94 |
+
default=str(DATA_DIR / "tokenizer-tr-16k.json"))
|
| 95 |
+
parser.add_argument("--train-in", type=str,
|
| 96 |
+
default=str(DATA_DIR / "corpus_train_v3.txt"))
|
| 97 |
+
parser.add_argument("--val-in", type=str, default=None,
|
| 98 |
+
help="Val corpus (yoksa val atlanir)")
|
| 99 |
+
parser.add_argument("--train-out", type=str, default=None,
|
| 100 |
+
help="Train .bin cikti yolu (yoksa data/train.bin)")
|
| 101 |
+
parser.add_argument("--val-out", type=str, default=None,
|
| 102 |
+
help="Val .bin cikti yolu (yoksa data/val.bin)")
|
| 103 |
+
parser.add_argument("--meta-out", type=str, default=None,
|
| 104 |
+
help="Meta pickle yolu (yoksa data/meta.pkl)")
|
| 105 |
+
parser.add_argument("--batch-size", type=int, default=5000)
|
| 106 |
+
args = parser.parse_args()
|
| 107 |
+
|
| 108 |
+
# DATA_DIR yoksa oluştur (Lightning AI fresh env)
|
| 109 |
+
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
| 110 |
+
|
| 111 |
+
train_out = Path(args.train_out) if args.train_out else (DATA_DIR / "train.bin")
|
| 112 |
+
val_out = Path(args.val_out) if args.val_out else (DATA_DIR / "val.bin")
|
| 113 |
+
meta_out = Path(args.meta_out) if args.meta_out else (DATA_DIR / "meta.pkl")
|
| 114 |
+
train_out.parent.mkdir(parents=True, exist_ok=True)
|
| 115 |
+
val_out.parent.mkdir(parents=True, exist_ok=True)
|
| 116 |
+
|
| 117 |
+
tokenizer = Tokenizer.from_file(args.tokenizer)
|
| 118 |
+
vocab_size = tokenizer.get_vocab_size()
|
| 119 |
+
eot_id = tokenizer.token_to_id("<|endoftext|>")
|
| 120 |
+
print(f"Vocab: {vocab_size} EOT id: {eot_id} Batch: {args.batch_size}")
|
| 121 |
+
print(f"Train: {args.train_in} -> {train_out}")
|
| 122 |
+
if args.val_in:
|
| 123 |
+
print(f"Val: {args.val_in} -> {val_out}")
|
| 124 |
+
else:
|
| 125 |
+
print(f"Val: atlandi")
|
| 126 |
+
|
| 127 |
+
if vocab_size > 65535:
|
| 128 |
+
raise ValueError("Vocab 65535'ten buyuk, uint16 yetmez. uint32 kullan.")
|
| 129 |
+
|
| 130 |
+
in_path = Path(args.train_in)
|
| 131 |
+
if not in_path.exists():
|
| 132 |
+
raise FileNotFoundError(f"Train input yok: {in_path}")
|
| 133 |
+
|
| 134 |
+
train_tokens = encode_file(tokenizer, in_path, train_out, eot_id,
|
| 135 |
+
batch_size=args.batch_size)
|
| 136 |
+
|
| 137 |
+
val_tokens = 0
|
| 138 |
+
if args.val_in:
|
| 139 |
+
val_in = Path(args.val_in)
|
| 140 |
+
if not val_in.exists():
|
| 141 |
+
print(f"UYARI: Val input yok ({val_in}), atlandi")
|
| 142 |
+
else:
|
| 143 |
+
val_tokens = encode_file(tokenizer, val_in, val_out, eot_id,
|
| 144 |
+
batch_size=args.batch_size)
|
| 145 |
+
|
| 146 |
+
meta = {
|
| 147 |
+
"vocab_size": vocab_size,
|
| 148 |
+
"eot_id": eot_id,
|
| 149 |
+
"tokenizer_path": args.tokenizer,
|
| 150 |
+
"train_tokens": train_tokens,
|
| 151 |
+
"val_tokens": val_tokens,
|
| 152 |
+
"train_out": str(train_out),
|
| 153 |
+
"val_out": str(val_out) if val_tokens else None,
|
| 154 |
+
}
|
| 155 |
+
with open(meta_out, "wb") as f:
|
| 156 |
+
pickle.dump(meta, f)
|
| 157 |
+
|
| 158 |
+
print(f"\n[OK] Hazir.")
|
| 159 |
+
print(f" Train: {train_tokens:,} token -> {train_out}")
|
| 160 |
+
if val_tokens:
|
| 161 |
+
print(f" Val: {val_tokens:,} token -> {val_out}")
|
| 162 |
+
print(f" Meta: {meta_out}")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
if __name__ == "__main__":
|
| 166 |
+
main()
|