Download scripts/evaluate.py from Infinity08/KAWK50M-Project: direct link, hf CLI and curl.
- Browser
- Download file 6.13 kB
-
https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/evaluate.py
- Command line
-
hf download hf://datasets/Infinity08/KAWK50M-Project/scripts/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/evaluate.py
6.13 kB
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import math | |
| from pathlib import Path | |
| from typing import Any | |
| import torch | |
| from transformers import AutoTokenizer, LlamaForCausalLM | |
| from kawk50m.binary_dataset import PackedTokenDataset | |
| from kawk50m.cli import configure_utf8_stdio | |
| DEFAULT_PROMPTS = [ | |
| "대한민국의 수도는", | |
| "오늘 아침에 일어나서", | |
| "인공지능 언어 모델은", | |
| "비가 내리는 날에는", | |
| ] | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser( | |
| description="Measure validation loss and generate Korean continuations." | |
| ) | |
| parser.add_argument( | |
| "--checkpoint", | |
| required=True, | |
| help="A checkpoint directory containing model/ and tokenizer/.", | |
| ) | |
| parser.add_argument( | |
| "--validation-bin", default="data/tokenized/validation.bin" | |
| ) | |
| parser.add_argument( | |
| "--tokenizer-dir", | |
| default=None, | |
| help="Override the tokenizer stored inside the checkpoint.", | |
| ) | |
| parser.add_argument("--sequence-length", type=int, default=1024) | |
| parser.add_argument("--batch-size", type=int, default=8) | |
| parser.add_argument("--eval-batches", type=int, default=50) | |
| parser.add_argument("--max-new-tokens", type=int, default=80) | |
| parser.add_argument("--temperature", type=float, default=0.8) | |
| parser.add_argument("--top-k", type=int, default=0) | |
| parser.add_argument("--top-p", type=float, default=0.95) | |
| parser.add_argument("--repetition-penalty", type=float, default=1.05) | |
| parser.add_argument("--seed", type=int, default=42) | |
| parser.add_argument("--prompt", action="append", default=None) | |
| parser.add_argument("--cpu", action="store_true") | |
| return parser.parse_args() | |
| def validation_loss( | |
| model: Any, | |
| dataset: PackedTokenDataset, | |
| *, | |
| batches: int, | |
| batch_size: int, | |
| device: torch.device, | |
| use_bf16: bool, | |
| ) -> float: | |
| total = 0.0 | |
| model.eval() | |
| for batch_index in range(batches): | |
| inputs, labels = dataset.evaluation_batch( | |
| batch_index=batch_index, | |
| batch_size=batch_size, | |
| rank=0, | |
| world_size=1, | |
| device=device, | |
| ) | |
| with torch.autocast( | |
| device_type=device.type, | |
| dtype=torch.bfloat16, | |
| enabled=use_bf16, | |
| ): | |
| total += model(input_ids=inputs, labels=labels).loss.item() | |
| return total / batches | |
| def generate_samples( | |
| model: Any, | |
| tokenizer: Any, | |
| prompts: list[str], | |
| *, | |
| device: torch.device, | |
| max_new_tokens: int, | |
| temperature: float, | |
| top_k: int, | |
| top_p: float, | |
| repetition_penalty: float, | |
| ) -> list[dict[str, str]]: | |
| rows = [] | |
| do_sample = temperature > 0 | |
| for prompt in prompts: | |
| encoded = tokenizer(prompt, return_tensors="pt", add_special_tokens=True) | |
| input_ids = encoded["input_ids"].to(device) | |
| available = model.config.max_position_embeddings - input_ids.shape[1] | |
| new_token_limit = min(max_new_tokens, max(available, 1)) | |
| generation_kwargs: dict[str, Any] = { | |
| "input_ids": input_ids, | |
| "max_new_tokens": new_token_limit, | |
| "do_sample": do_sample, | |
| "repetition_penalty": repetition_penalty, | |
| "pad_token_id": tokenizer.pad_token_id, | |
| "eos_token_id": tokenizer.eos_token_id, | |
| } | |
| if do_sample: | |
| generation_kwargs.update( | |
| temperature=temperature, | |
| top_k=top_k, | |
| top_p=top_p, | |
| ) | |
| generated = model.generate(**generation_kwargs) | |
| continuation_ids = generated[0, input_ids.shape[1] :] | |
| continuation = tokenizer.decode( | |
| continuation_ids, | |
| skip_special_tokens=True, | |
| clean_up_tokenization_spaces=False, | |
| ) | |
| rows.append( | |
| { | |
| "prompt": prompt, | |
| "continuation": continuation, | |
| "full_text": prompt + continuation, | |
| } | |
| ) | |
| return rows | |
| def main() -> None: | |
| configure_utf8_stdio() | |
| args = parse_args() | |
| 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 | |
| ) | |
| if args.cpu: | |
| device = torch.device("cpu") | |
| elif torch.cuda.is_available(): | |
| device = torch.device("cuda") | |
| else: | |
| device = torch.device("cpu") | |
| use_bf16 = device.type == "cuda" and torch.cuda.is_bf16_supported() | |
| torch.manual_seed(args.seed) | |
| if device.type == "cuda": | |
| torch.cuda.manual_seed_all(args.seed) | |
| tokenizer = AutoTokenizer.from_pretrained( | |
| tokenizer_dir, use_fast=False, legacy=True | |
| ) | |
| model = LlamaForCausalLM.from_pretrained(model_dir) | |
| model.to(device) | |
| dataset = PackedTokenDataset(args.validation_bin, args.sequence_length) | |
| loss = validation_loss( | |
| model, | |
| dataset, | |
| batches=args.eval_batches, | |
| batch_size=args.batch_size, | |
| device=device, | |
| use_bf16=use_bf16, | |
| ) | |
| samples = generate_samples( | |
| model, | |
| tokenizer, | |
| args.prompt or DEFAULT_PROMPTS, | |
| device=device, | |
| max_new_tokens=args.max_new_tokens, | |
| temperature=args.temperature, | |
| top_k=args.top_k, | |
| top_p=args.top_p, | |
| repetition_penalty=args.repetition_penalty, | |
| ) | |
| result = { | |
| "checkpoint": str(checkpoint.resolve()), | |
| "tokenizer": str(tokenizer_dir.resolve()), | |
| "validation_loss": loss, | |
| "validation_perplexity": math.exp(min(loss, 20.0)), | |
| "evaluated_tokens": ( | |
| args.eval_batches * args.batch_size * args.sequence_length | |
| ), | |
| "samples": samples, | |
| "note": "This is a base-model continuation evaluation, not instruction QA.", | |
| } | |
| print(json.dumps(result, ensure_ascii=False, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |