File size: 6,130 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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
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()


@torch.no_grad()
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


@torch.no_grad()
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()