File size: 5,825 Bytes
91ac3cc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | 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()
@torch.no_grad()
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()
|