Download data/tokenize_data.py from scs09/zenex-ai-project: direct link, hf CLI and curl.
- Browser
- Download file 3.33 kB
-
https://huggingface.co/datasets/scs09/zenex-ai-project/resolve/main/data/tokenize_data.py
- Command line
-
hf download hf://datasets/scs09/zenex-ai-project/data/tokenize_data.py
-
curl -L -o tokenize_data.py https://huggingface.co/datasets/scs09/zenex-ai-project/resolve/main/data/tokenize_data.py
3.33 kB
| """Tokenize cleaned corpora and emit binary shards for pretraining.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import logging | |
| from pathlib import Path | |
| import numpy as np | |
| import sentencepiece as spm | |
| LOGGER = logging.getLogger(__name__) | |
| def stream_records(path: Path): | |
| """Yield text records from JSONL.""" | |
| with path.open("r", encoding="utf-8") as f: | |
| for line in f: | |
| if line.strip(): | |
| record = json.loads(line) | |
| yield record.get("text", ""), record.get("kind", "general") | |
| def shard_tokens(token_ids: list[int], shard_size: int, out_dir: Path, prefix: str) -> int: | |
| """Write token ids into uint32 binary shard files.""" | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| count = 0 | |
| for i in range(0, len(token_ids), shard_size): | |
| shard = np.array(token_ids[i : i + shard_size], dtype=np.uint32) | |
| out_file = out_dir / f"{prefix}_{count:06d}.bin" | |
| shard.tofile(out_file) | |
| count += 1 | |
| return count | |
| def tokenize_corpus( | |
| input_jsonl: Path, | |
| tokenizer_model: Path, | |
| out_dir: Path, | |
| shard_size: int, | |
| general_ratio: float, | |
| code_ratio: float, | |
| ) -> dict[str, int]: | |
| """Tokenize and split according to configured data mix.""" | |
| sp = spm.SentencePieceProcessor(model_file=str(tokenizer_model)) | |
| general_tokens: list[int] = [] | |
| code_tokens: list[int] = [] | |
| for text, kind in stream_records(input_jsonl): | |
| ids = sp.encode(text, out_type=int) | |
| if kind == "code": | |
| code_tokens.extend(ids) | |
| else: | |
| general_tokens.extend(ids) | |
| total = len(general_tokens) + len(code_tokens) | |
| if total == 0: | |
| raise ValueError("No tokens produced from dataset") | |
| target_general = int(total * general_ratio) | |
| target_code = int(total * code_ratio) | |
| mixed = general_tokens[:target_general] + code_tokens[:target_code] | |
| mixed_shards = shard_tokens(mixed, shard_size, out_dir / "pretrain", "mix") | |
| return { | |
| "total_tokens": len(mixed), | |
| "general_tokens_used": min(target_general, len(general_tokens)), | |
| "code_tokens_used": min(target_code, len(code_tokens)), | |
| "shards": mixed_shards, | |
| } | |
| def parse_args() -> argparse.Namespace: | |
| """Parse CLI arguments.""" | |
| parser = argparse.ArgumentParser(description="Tokenize cleaned data to binary shards") | |
| parser.add_argument("--input", type=Path, required=True) | |
| parser.add_argument("--tokenizer-model", type=Path, required=True) | |
| parser.add_argument("--out-dir", type=Path, required=True) | |
| parser.add_argument("--shard-size", type=int, default=4_000_000) | |
| parser.add_argument("--general-ratio", type=float, default=0.87) | |
| parser.add_argument("--code-ratio", type=float, default=0.13) | |
| return parser.parse_args() | |
| def main() -> None: | |
| """CLI entrypoint.""" | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") | |
| args = parse_args() | |
| stats = tokenize_corpus( | |
| input_jsonl=args.input, | |
| tokenizer_model=args.tokenizer_model, | |
| out_dir=args.out_dir, | |
| shard_size=args.shard_size, | |
| general_ratio=args.general_ratio, | |
| code_ratio=args.code_ratio, | |
| ) | |
| LOGGER.info("Tokenization complete: %s", stats) | |
| if __name__ == "__main__": | |
| main() | |