Download scripts/tokenize_corpus.py from Infinity08/KAWK50M-Project: direct link, hf CLI and curl.
- Browser
- Download file 5.4 kB
-
https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/tokenize_corpus.py
- Command line
-
hf download hf://datasets/Infinity08/KAWK50M-Project/scripts/tokenize_corpus.py
-
curl -L -o tokenize_corpus.py https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/tokenize_corpus.py
5.4 kB
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| from tqdm import tqdm | |
| from transformers import AutoTokenizer | |
| from kawk50m.cli import configure_utf8_stdio | |
| from kawk50m.io import discover_paths, iter_documents | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser( | |
| description="Tokenize clean JSONL shards into flat uint16 streams." | |
| ) | |
| parser.add_argument("--input-dir", default="data/clean") | |
| parser.add_argument("--tokenizer-dir", default="artifacts/tokenizer-20k") | |
| parser.add_argument("--output-dir", default="data/tokenized") | |
| parser.add_argument("--batch-size", type=int, default=64) | |
| parser.add_argument("--max-train-tokens", type=int, default=None) | |
| parser.add_argument("--max-validation-tokens", type=int, default=None) | |
| parser.add_argument("--max-test-tokens", type=int, default=None) | |
| return parser.parse_args() | |
| def tokenize_split( | |
| *, | |
| split: str, | |
| paths: list[Path], | |
| tokenizer: Any, | |
| output_path: Path, | |
| batch_size: int, | |
| max_tokens: int | None, | |
| ) -> dict[str, Any]: | |
| documents_seen = 0 | |
| documents_written = 0 | |
| token_count = 0 | |
| text_batch: list[str] = [] | |
| def flush(handle: Any) -> bool: | |
| nonlocal documents_written, token_count | |
| if not text_batch: | |
| return False | |
| encoded_batch = tokenizer( | |
| text_batch, | |
| add_special_tokens=False, | |
| return_attention_mask=False, | |
| return_token_type_ids=False, | |
| )["input_ids"] | |
| reached_limit = False | |
| for token_ids in encoded_batch: | |
| tokens = list(token_ids) | |
| if not tokens or tokens[-1] != tokenizer.eos_token_id: | |
| tokens.append(tokenizer.eos_token_id) | |
| if max_tokens is not None: | |
| remaining = max_tokens - token_count | |
| if remaining <= 0: | |
| reached_limit = True | |
| break | |
| if len(tokens) > remaining: | |
| tokens = tokens[:remaining] | |
| reached_limit = True | |
| if tokens: | |
| np.asarray(tokens, dtype=np.uint16).tofile(handle) | |
| token_count += len(tokens) | |
| documents_written += 1 | |
| if reached_limit: | |
| break | |
| text_batch.clear() | |
| return reached_limit | |
| with output_path.open("wb") as handle: | |
| progress = tqdm(iter_documents(paths), desc=split, unit="docs") | |
| for document in progress: | |
| documents_seen += 1 | |
| text_batch.append(document["text"]) | |
| if len(text_batch) >= batch_size and flush(handle): | |
| break | |
| else: | |
| flush(handle) | |
| return { | |
| "split": split, | |
| "output": str(output_path), | |
| "input_files": len(paths), | |
| "documents_seen": documents_seen, | |
| "documents_written": documents_written, | |
| "tokens": token_count, | |
| "bytes": output_path.stat().st_size, | |
| "dtype": "uint16", | |
| } | |
| def main() -> None: | |
| configure_utf8_stdio() | |
| args = parse_args() | |
| if args.batch_size <= 0: | |
| raise ValueError("--batch-size must be positive") | |
| output_dir = Path(args.output_dir) | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| existing = [ | |
| *(output_dir / f"{split}.bin" for split in ("train", "validation", "test")), | |
| output_dir / "metadata.json", | |
| ] | |
| existing = [path for path in existing if path.exists()] | |
| if existing: | |
| raise FileExistsError( | |
| f"{existing[0]} already exists. Choose a new output directory." | |
| ) | |
| tokenizer = AutoTokenizer.from_pretrained( | |
| args.tokenizer_dir, use_fast=False, legacy=True | |
| ) | |
| tokenizer.model_max_length = int(1e30) | |
| if len(tokenizer) > np.iinfo(np.uint16).max: | |
| raise ValueError("uint16 output requires a vocabulary no larger than 65,535") | |
| if tokenizer.eos_token_id is None: | |
| raise ValueError("Tokenizer must define eos_token_id") | |
| input_dir = Path(args.input_dir) | |
| limits = { | |
| "train": args.max_train_tokens, | |
| "validation": args.max_validation_tokens, | |
| "test": args.max_test_tokens, | |
| } | |
| summaries: dict[str, Any] = { | |
| "tokenizer": str(Path(args.tokenizer_dir).resolve()), | |
| "vocab_size": len(tokenizer), | |
| "eos_token_id": tokenizer.eos_token_id, | |
| "splits": {}, | |
| } | |
| for split in ("train", "validation", "test"): | |
| paths = discover_paths([str(input_dir / f"{split}-*.jsonl")]) | |
| if not paths: | |
| print(f"Skipping {split}: no input shards") | |
| continue | |
| summary = tokenize_split( | |
| split=split, | |
| paths=paths, | |
| tokenizer=tokenizer, | |
| output_path=output_dir / f"{split}.bin", | |
| batch_size=args.batch_size, | |
| max_tokens=limits[split], | |
| ) | |
| summaries["splits"][split] = summary | |
| if "train" not in summaries["splits"]: | |
| raise FileNotFoundError("No train shards were found") | |
| metadata_path = output_dir / "metadata.json" | |
| with metadata_path.open("w", encoding="utf-8") as handle: | |
| json.dump(summaries, handle, ensure_ascii=False, indent=2) | |
| handle.write("\n") | |
| print(json.dumps(summaries, ensure_ascii=False, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |