Download scripts/estimate_corpus_tokens.py from Infinity08/KAWK50M-Project: direct link, hf CLI and curl.
- Browser
- Download file 3.75 kB
-
https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/estimate_corpus_tokens.py
- Command line
-
hf download hf://datasets/Infinity08/KAWK50M-Project/scripts/estimate_corpus_tokens.py
-
curl -L -o estimate_corpus_tokens.py https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/estimate_corpus_tokens.py
3.75 kB
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| from typing import Any | |
| 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="Estimate total corpus tokens from a deterministic document sample." | |
| ) | |
| parser.add_argument("--input", nargs="+", required=True) | |
| parser.add_argument("--tokenizer-dir", required=True) | |
| parser.add_argument("--prepare-stats", default=None) | |
| parser.add_argument("--max-documents", type=int, default=50_000) | |
| parser.add_argument("--batch-size", type=int, default=64) | |
| return parser.parse_args() | |
| def accepted_counts(stats: dict[str, Any]) -> tuple[int, int]: | |
| counts = stats.get("counts", {}) | |
| documents = sum( | |
| int(counts.get(f"accepted_{split}", 0)) | |
| for split in ("train", "validation", "test") | |
| ) | |
| characters = int(counts.get("accepted_characters", 0)) | |
| return documents, characters | |
| def main() -> None: | |
| configure_utf8_stdio() | |
| args = parse_args() | |
| if args.max_documents <= 0 or args.batch_size <= 0: | |
| raise ValueError("--max-documents and --batch-size must be positive") | |
| paths = discover_paths(args.input) | |
| if not paths: | |
| raise FileNotFoundError("No corpus inputs were found") | |
| tokenizer = AutoTokenizer.from_pretrained( | |
| args.tokenizer_dir, use_fast=False, legacy=True | |
| ) | |
| tokenizer.model_max_length = int(1e30) | |
| sampled_documents = 0 | |
| sampled_characters = 0 | |
| sampled_tokens = 0 | |
| batch: list[str] = [] | |
| def flush() -> None: | |
| nonlocal sampled_documents, sampled_characters, sampled_tokens | |
| if not batch: | |
| return | |
| encoded = tokenizer( | |
| batch, | |
| add_special_tokens=False, | |
| return_attention_mask=False, | |
| return_token_type_ids=False, | |
| )["input_ids"] | |
| for text, token_ids in zip(batch, encoded, strict=True): | |
| sampled_documents += 1 | |
| sampled_characters += len(text) | |
| sampled_tokens += len(token_ids) + 1 | |
| batch.clear() | |
| for document in iter_documents(paths): | |
| batch.append(document["text"]) | |
| if sampled_documents + len(batch) >= args.max_documents: | |
| flush() | |
| break | |
| if len(batch) >= args.batch_size: | |
| flush() | |
| else: | |
| flush() | |
| if sampled_documents == 0 or sampled_characters == 0: | |
| raise RuntimeError("Corpus sample contained no usable text") | |
| content_tokens = sampled_tokens - sampled_documents | |
| content_tokens_per_character = content_tokens / sampled_characters | |
| result: dict[str, Any] = { | |
| "tokenizer": str(Path(args.tokenizer_dir).resolve()), | |
| "sampled_documents": sampled_documents, | |
| "sampled_characters": sampled_characters, | |
| "sampled_tokens_including_eos": sampled_tokens, | |
| "content_tokens_per_character": content_tokens_per_character, | |
| "characters_per_content_token": sampled_characters / content_tokens, | |
| } | |
| if args.prepare_stats is not None: | |
| stats_path = Path(args.prepare_stats) | |
| stats = json.loads(stats_path.read_text(encoding="utf-8")) | |
| documents, characters = accepted_counts(stats) | |
| result.update( | |
| prepare_stats=str(stats_path.resolve()), | |
| accepted_documents=documents, | |
| accepted_characters=characters, | |
| estimated_total_tokens=round( | |
| characters * content_tokens_per_character + documents | |
| ), | |
| ) | |
| print(json.dumps(result, ensure_ascii=False, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |