dist_methods / code /train_fineweb_bpe.py
Ilikemechuri's picture
Add distributed training experiment code and results
bbf3a52 verified
Raw History Blame Contribute Delete
4.27 kB
#!/usr/bin/env python3
"""Train a 4,096-entry byte-level BPE tokenizer from the cached FineWeb text."""
from __future__ import annotations
import hashlib
import json
from datetime import datetime, timezone
from pathlib import Path
from tokenizers import AddedToken, Tokenizer, decoders, models, pre_tokenizers, trainers
from transformers import PreTrainedTokenizerFast
CORPUS_DIR = Path("/workspace/data/fineweb_text")
OUTPUT_DIR = Path("/workspace/tokenizers/fineweb_bpe_4096")
VOCAB_SIZE = 4096
EOS_TOKEN = "<|endoftext|>"
PAD_TOKEN = "<|pad|>"
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def main() -> None:
train_path = CORPUS_DIR / "train.txt"
if not train_path.is_file():
raise SystemExit(f"Training text not found: {train_path}")
if OUTPUT_DIR.exists():
raise SystemExit(f"Refusing to overwrite existing tokenizer: {OUTPUT_DIR}")
OUTPUT_DIR.mkdir(parents=True)
backend = Tokenizer(models.BPE(unk_token=None))
byte_level = pre_tokenizers.ByteLevel(add_prefix_space=False, use_regex=True)
backend.pre_tokenizer = byte_level
backend.decoder = decoders.ByteLevel()
special_tokens = [
AddedToken(EOS_TOKEN, special=True),
AddedToken(PAD_TOKEN, special=True),
]
trainer = trainers.BpeTrainer(
vocab_size=VOCAB_SIZE,
min_frequency=2,
special_tokens=special_tokens,
initial_alphabet=byte_level.alphabet(),
show_progress=True,
)
backend.train(files=[str(train_path)], trainer=trainer)
actual_vocab_size = backend.get_vocab_size(with_added_tokens=True)
if actual_vocab_size != VOCAB_SIZE:
raise RuntimeError(
f"Expected vocab size {VOCAB_SIZE}, got {actual_vocab_size}"
)
eos_id = backend.token_to_id(EOS_TOKEN)
pad_id = backend.token_to_id(PAD_TOKEN)
if eos_id is None or pad_id is None:
raise RuntimeError("Trainer did not retain the requested special tokens")
backend.save(str(OUTPUT_DIR / "tokenizer.json"), pretty=True)
backend.model.save(str(OUTPUT_DIR))
hf_tokenizer = PreTrainedTokenizerFast(
tokenizer_object=backend,
eos_token=EOS_TOKEN,
pad_token=PAD_TOKEN,
clean_up_tokenization_spaces=False,
model_max_length=2048,
)
hf_tokenizer.save_pretrained(str(OUTPUT_DIR))
manifest = {
"created_utc": datetime.now(timezone.utc).isoformat(),
"algorithm": "ByteLevel BPE",
"target_vocab_size": VOCAB_SIZE,
"actual_vocab_size": actual_vocab_size,
"min_frequency": 2,
"initial_alphabet": "all 256 byte-level symbols",
"normalizer": None,
"pre_tokenizer": "ByteLevel(add_prefix_space=false, use_regex=true)",
"decoder": "ByteLevel",
"special_tokens": {
"eos_token": EOS_TOKEN,
"eos_token_id": eos_id,
"pad_token": PAD_TOKEN,
"pad_token_id": pad_id,
},
"bos_token": None,
"training_files": {
"train.txt": {
"bytes": train_path.stat().st_size,
"sha256": sha256_file(train_path),
}
},
"validation_and_test_used_for_training": False,
}
(OUTPUT_DIR / "manifest.json").write_text(
json.dumps(manifest, indent=2, ensure_ascii=False) + "\n",
encoding="utf-8",
)
(OUTPUT_DIR / "README.md").write_text(
"# FineWeb custom tokenizer\n\n"
"A 4,096-entry byte-level BPE tokenizer trained only on the cached FineWeb "
"`train.txt`. `val.txt` and `test.txt` were kept out of tokenizer training. "
"The vocabulary includes `<|endoftext|>` and `<|pad|>`; append EOS between "
"documents when preparing language-model sequences. No BOS token is defined.\n\n"
"Load with `transformers.AutoTokenizer.from_pretrained(this_directory)`.\n",
encoding="utf-8",
)
print(json.dumps(manifest, indent=2, ensure_ascii=False), flush=True)
print(f"tokenizer_ready={OUTPUT_DIR}", flush=True)
if __name__ == "__main__":
main()