Download scripts/evaluate_text.py from Infinity08/KAWK50M-Project: direct link, hf CLI and curl.
- Browser
- Download file 5.83 kB
-
https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/evaluate_text.py
- Command line
-
hf download hf://datasets/Infinity08/KAWK50M-Project/scripts/evaluate_text.py
-
curl -L -o evaluate_text.py https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/evaluate_text.py
5.83 kB
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import math | |
| from pathlib import Path | |
| from typing import Any | |
| import torch | |
| import torch.nn.functional as F | |
| from transformers import AutoTokenizer, LlamaForCausalLM | |
| from kawk50m.cli import configure_utf8_stdio | |
| from kawk50m.io import discover_paths, iter_documents | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser( | |
| description=( | |
| "Evaluate a checkpoint on raw text with tokenizer-independent " | |
| "UTF-8 byte-normalized negative log-likelihood." | |
| ) | |
| ) | |
| parser.add_argument( | |
| "--checkpoint", | |
| required=True, | |
| help="Checkpoint directory containing model/ and tokenizer/.", | |
| ) | |
| parser.add_argument( | |
| "--input", | |
| nargs="+", | |
| required=True, | |
| help="Validation JSONL/TXT files or glob patterns.", | |
| ) | |
| parser.add_argument( | |
| "--tokenizer-dir", | |
| default=None, | |
| help="Override the tokenizer stored inside the checkpoint.", | |
| ) | |
| parser.add_argument("--max-documents", type=int, default=1_000) | |
| parser.add_argument("--max-characters-per-document", type=int, default=20_000) | |
| parser.add_argument("--context-length", type=int, default=None) | |
| parser.add_argument("--cpu", action="store_true") | |
| return parser.parse_args() | |
| def document_nll( | |
| model: Any, | |
| tokenizer: Any, | |
| text: str, | |
| *, | |
| context_length: int, | |
| device: torch.device, | |
| use_bf16: bool, | |
| ) -> tuple[float, int]: | |
| token_ids = tokenizer.encode(text, add_special_tokens=False) | |
| if not token_ids: | |
| return 0.0, 0 | |
| prefix_id = tokenizer.bos_token_id | |
| if prefix_id is None: | |
| prefix_id = tokenizer.eos_token_id | |
| if prefix_id is None: | |
| raise ValueError("Tokenizer must define bos_token_id or eos_token_id") | |
| stream = [prefix_id, *token_ids] | |
| total_nll = 0.0 | |
| predicted_tokens = 0 | |
| for start in range(0, len(stream) - 1, context_length): | |
| stop = min(start + context_length, len(stream) - 1) | |
| input_ids = torch.tensor( | |
| stream[start:stop], dtype=torch.long, device=device | |
| ).unsqueeze(0) | |
| targets = torch.tensor( | |
| stream[start + 1 : stop + 1], dtype=torch.long, device=device | |
| ) | |
| with torch.autocast( | |
| device_type=device.type, | |
| dtype=torch.bfloat16, | |
| enabled=use_bf16, | |
| ): | |
| logits = model(input_ids=input_ids, use_cache=False).logits[0] | |
| total_nll += F.cross_entropy( | |
| logits.float(), targets, reduction="sum" | |
| ).item() | |
| predicted_tokens += targets.numel() | |
| return total_nll, predicted_tokens | |
| def main() -> None: | |
| configure_utf8_stdio() | |
| args = parse_args() | |
| if args.max_documents <= 0: | |
| raise ValueError("--max-documents must be positive") | |
| if args.max_characters_per_document <= 0: | |
| raise ValueError("--max-characters-per-document must be positive") | |
| checkpoint = Path(args.checkpoint) | |
| model_dir = checkpoint / "model" if (checkpoint / "model").is_dir() else checkpoint | |
| tokenizer_dir = Path(args.tokenizer_dir) if args.tokenizer_dir else ( | |
| checkpoint / "tokenizer" | |
| if (checkpoint / "tokenizer").is_dir() | |
| else checkpoint | |
| ) | |
| device = torch.device( | |
| "cpu" if args.cpu or not torch.cuda.is_available() else "cuda" | |
| ) | |
| use_bf16 = device.type == "cuda" and torch.cuda.is_bf16_supported() | |
| tokenizer = AutoTokenizer.from_pretrained( | |
| tokenizer_dir, use_fast=False, legacy=True | |
| ) | |
| tokenizer.model_max_length = int(1e30) | |
| model = LlamaForCausalLM.from_pretrained(model_dir).to(device).eval() | |
| context_length = args.context_length or int( | |
| model.config.max_position_embeddings | |
| ) | |
| if context_length <= 0: | |
| raise ValueError("--context-length must be positive") | |
| context_length = min(context_length, int(model.config.max_position_embeddings)) | |
| paths = discover_paths(args.input) | |
| if not paths: | |
| raise FileNotFoundError("No evaluation inputs were found") | |
| total_nll = 0.0 | |
| total_tokens = 0 | |
| total_characters = 0 | |
| total_utf8_bytes = 0 | |
| documents = 0 | |
| for document in iter_documents(paths): | |
| text = document["text"][: args.max_characters_per_document] | |
| if not text: | |
| continue | |
| nll, tokens = document_nll( | |
| model, | |
| tokenizer, | |
| text, | |
| context_length=context_length, | |
| device=device, | |
| use_bf16=use_bf16, | |
| ) | |
| total_nll += nll | |
| total_tokens += tokens | |
| total_characters += len(text) | |
| total_utf8_bytes += len(text.encode("utf-8")) | |
| documents += 1 | |
| if documents >= args.max_documents: | |
| break | |
| if documents == 0 or total_tokens == 0 or total_utf8_bytes == 0: | |
| raise RuntimeError("Evaluation set contained no usable text") | |
| result = { | |
| "checkpoint": str(checkpoint.resolve()), | |
| "tokenizer": str(tokenizer_dir.resolve()), | |
| "inputs": [str(path) for path in paths], | |
| "documents": documents, | |
| "characters": total_characters, | |
| "utf8_bytes": total_utf8_bytes, | |
| "predicted_tokens": total_tokens, | |
| "context_length": context_length, | |
| "token_nll": total_nll / total_tokens, | |
| "token_perplexity": math.exp(min(total_nll / total_tokens, 20.0)), | |
| "nats_per_character": total_nll / total_characters, | |
| "bits_per_utf8_byte": total_nll / total_utf8_bytes / math.log(2.0), | |
| "note": ( | |
| "Compare bits_per_utf8_byte only when checkpoints are evaluated " | |
| "on the exact same ordered raw-text documents." | |
| ), | |
| } | |
| print(json.dumps(result, ensure_ascii=False, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |