Download scripts/evaluate_sft.py from Infinity08/KAWK50M-Project: direct link, hf CLI and curl.
- Browser
- Download file 6.07 kB
-
https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/evaluate_sft.py
- Command line
-
hf download hf://datasets/Infinity08/KAWK50M-Project/scripts/evaluate_sft.py
-
curl -L -o evaluate_sft.py https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/evaluate_sft.py
6.07 kB
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import math | |
| import re | |
| from pathlib import Path | |
| from typing import Any | |
| import torch | |
| from transformers import AutoTokenizer, LlamaForCausalLM | |
| from kawk50m.chat import KOREAN_CHAT_TEMPLATE, format_generation_prompt | |
| from kawk50m.cli import configure_utf8_stdio | |
| from kawk50m.sft_dataset import SFTPackedDataset | |
| from scripts.sft import evaluate_loss | |
| DEFAULT_PROMPTS = [ | |
| "대한민국의 수도는 어디인가요? 한 문장으로 답해주세요.", | |
| "비가 오는 날 외출할 때 준비할 물건 세 가지를 알려주세요.", | |
| "다음 문장을 자연스럽게 고쳐주세요: 나는 어제 학교에 갑니다.", | |
| "한국어로 자기소개를 두 문장으로 해주세요.", | |
| "사용자가 위험한 요청을 하면 어떻게 대응해야 하나요?", | |
| ] | |
| HANGUL_RE = re.compile(r"[가-힣]") | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser( | |
| description="Evaluate assistant-only loss and Korean instruction responses." | |
| ) | |
| parser.add_argument("--checkpoint", required=True) | |
| parser.add_argument("--tokenizer-dir") | |
| parser.add_argument("--validation-prefix", action="append", required=True) | |
| parser.add_argument("--sequence-length", type=int, default=5120) | |
| parser.add_argument("--batch-size", type=int, default=4) | |
| parser.add_argument("--eval-batches", type=int, default=20) | |
| parser.add_argument("--max-new-tokens", type=int, default=160) | |
| parser.add_argument("--temperature", type=float, default=0.3) | |
| parser.add_argument("--top-k", type=int, default=40) | |
| parser.add_argument("--top-p", type=float, default=0.9) | |
| parser.add_argument("--repetition-penalty", type=float, default=1.12) | |
| parser.add_argument("--seed", type=int, default=42) | |
| parser.add_argument("--prompt", action="append") | |
| parser.add_argument("--cpu", action="store_true") | |
| return parser.parse_args() | |
| def response_metrics(text: str) -> dict[str, float | int]: | |
| visible = [character for character in text if not character.isspace()] | |
| words = text.split() | |
| return { | |
| "characters": len(text), | |
| "hangul_visible_ratio": len(HANGUL_RE.findall(text)) / max(len(visible), 1), | |
| "unique_word_ratio": len(set(words)) / max(len(words), 1), | |
| } | |
| 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, Any]]: | |
| model.eval() | |
| rows: list[dict[str, Any]] = [] | |
| for prompt in prompts: | |
| rendered = format_generation_prompt(prompt) | |
| encoded = tokenizer( | |
| rendered, | |
| return_tensors="pt", | |
| add_special_tokens=True, | |
| ) | |
| input_ids = encoded["input_ids"].to(device) | |
| available = model.config.max_position_embeddings - input_ids.shape[1] | |
| generation_kwargs: dict[str, Any] = { | |
| "input_ids": input_ids, | |
| "max_new_tokens": min(max_new_tokens, max(available, 1)), | |
| "do_sample": temperature > 0, | |
| "repetition_penalty": repetition_penalty, | |
| "pad_token_id": tokenizer.pad_token_id, | |
| "eos_token_id": tokenizer.eos_token_id, | |
| } | |
| if temperature > 0: | |
| generation_kwargs.update( | |
| temperature=temperature, | |
| top_k=top_k, | |
| top_p=top_p, | |
| ) | |
| generated = model.generate(**generation_kwargs) | |
| response_ids = generated[0, input_ids.shape[1] :] | |
| response = tokenizer.decode( | |
| response_ids, | |
| skip_special_tokens=True, | |
| clean_up_tokenization_spaces=False, | |
| ).strip() | |
| rows.append( | |
| { | |
| "prompt": prompt, | |
| "response": response, | |
| "metrics": response_metrics(response), | |
| } | |
| ) | |
| 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 | |
| ) | |
| device = ( | |
| torch.device("cpu") | |
| if args.cpu or not torch.cuda.is_available() | |
| else torch.device("cuda") | |
| ) | |
| 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 | |
| ) | |
| tokenizer.chat_template = KOREAN_CHAT_TEMPLATE | |
| model = LlamaForCausalLM.from_pretrained(model_dir).to(device) | |
| dataset = SFTPackedDataset(args.validation_prefix, args.sequence_length) | |
| loss, supervised_tokens = evaluate_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_supervised_tokens": supervised_tokens, | |
| "assistant_only_loss": True, | |
| "samples": samples, | |
| "note": "Korean instruction evaluation; responses are sampled, not facts checked.", | |
| } | |
| print(json.dumps(result, ensure_ascii=False, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |