File size: 14,572 Bytes
5b1ff4d | 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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | """
๋ฐ๋ณต ํดํ ๋ฌธ์ ํด๊ฒฐ์ ์ํ ์์ฑ ํ๋ผ๋ฏธํฐ ๊ทธ๋ฆฌ๋ ์์น.
๋ค์ํ ๋์ฝ๋ฉ ์ ๋ต์ ํ
์คํธํ๊ณ ๋ฐ๋ณต๋ฅ ์ ์ธก์ ํ๋ค.
- Sampling (temperature, top_p, top_k, repetition_penalty)
- no_repeat_ngram_size
- Contrastive Search
- Stop sequence (### ๋ต๋ณ:, ### ์ง๋ฌธ:)
Usage:
cd /PROJECT/0325120031_A/ghong/taketimes/llm-bang
python eval/test_generation_params.py \
--checkpoint checkpoints/korean_1b_sft/checkpoint-0005000 \
--device cuda:0
"""
from __future__ import annotations
import argparse
import json
import sys
import time
from pathlib import Path
from collections import Counter
import torch
import torch.nn.functional as F
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(_PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(_PROJECT_ROOT))
from model.transformer import LLM
from tokenizers import Tokenizer
# ---------------------------------------------------------------------------
# Prompts (using the CORRECT SFT template format)
# ---------------------------------------------------------------------------
SFT_PROMPTS = [
"<|user|>\nํ๊ตญ์ ์๋๋ ์ด๋์ธ๊ฐ์?\n<|assistant|>\n",
"<|user|>\nํ์ด์ฌ์์ ๋ฆฌ์คํธ๋ฅผ ์ ๋ ฌํ๋ ๋ฐฉ๋ฒ์ ์ค๋ช
ํด์ฃผ์ธ์.\n<|assistant|>\n",
"<|user|>\n์ง๊ตฌ์จ๋ํ์ ์ฃผ์ ์์ธ์ ์ค๋ช
ํ์ธ์.\n<|assistant|>\n",
"<|user|>\n์ข์ ์๋ฉด ์ต๊ด์ ๋ง๋ค๊ธฐ ์ํ ํ์ ์๋ ค์ฃผ์ธ์.\n<|assistant|>\n",
"<|user|>\nํ๊ตญ ์ ํต ์์ ์ค ๊น์น์ ๋ํด ์ค๋ช
ํด์ฃผ์ธ์.\n<|assistant|>\n",
]
# Also test with the WRONG format (### ์ง๋ฌธ/๋ต๋ณ) to compare
WRONG_FORMAT_PROMPTS = [
"### ์ง๋ฌธ: ํ๊ตญ์ ์๋๋ ์ด๋์ธ๊ฐ์?\n### ๋ต๋ณ:",
"### ์ง๋ฌธ: ํ์ด์ฌ์์ ๋ฆฌ์คํธ๋ฅผ ์ ๋ ฌํ๋ ๋ฐฉ๋ฒ์ ์ค๋ช
ํด์ฃผ์ธ์.\n### ๋ต๋ณ:",
"### ์ง๋ฌธ: ์ง๊ตฌ์จ๋ํ์ ์ฃผ์ ์์ธ์ ์ค๋ช
ํ์ธ์.\n### ๋ต๋ณ:",
]
# ---------------------------------------------------------------------------
# Stop sequence utilities
# ---------------------------------------------------------------------------
def find_stop_token_ids(tokenizer: Tokenizer, stop_strings: list[str]) -> list[list[int]]:
"""Find token IDs for stop sequences."""
results = []
for s in stop_strings:
ids = tokenizer.encode(s).ids
results.append(ids)
print(f" Stop sequence '{s}' โ token IDs: {ids}")
return results
def check_stop_sequences(generated_ids: list[int], stop_sequences: list[list[int]]) -> int | None:
"""Check if generated_ids ends with any stop sequence. Returns index to truncate at, or None."""
for seq in stop_sequences:
seq_len = len(seq)
if len(generated_ids) >= seq_len:
if generated_ids[-seq_len:] == seq:
return len(generated_ids) - seq_len
return None
# ---------------------------------------------------------------------------
# Repetition metrics
# ---------------------------------------------------------------------------
def compute_ngram_repetition(text: str, n: int) -> float:
tokens = text.split()
if len(tokens) < n:
return 0.0
ngrams = [tuple(tokens[i:i + n]) for i in range(len(tokens) - n + 1)]
if not ngrams:
return 0.0
return 1.0 - len(set(ngrams)) / len(ngrams)
def compute_all_repetition_metrics(text: str) -> dict:
return {
f"{n}gram_rep": compute_ngram_repetition(text, n)
for n in [1, 2, 3, 4]
}
# ---------------------------------------------------------------------------
# Generation with all parameter options
# ---------------------------------------------------------------------------
def top_p_filtering(logits, top_p=0.9, top_k=0):
if logits.dim() == 1:
logits = logits.unsqueeze(0)
squeeze = True
else:
squeeze = False
if top_k > 0:
k = min(top_k, logits.size(-1))
kth = torch.topk(logits, k, dim=-1).values[:, -1, None]
logits = logits.masked_fill(logits < kth, float("-inf"))
if 0.0 < top_p < 1.0:
sorted_logits, sorted_idx = torch.sort(logits, dim=-1, descending=True)
cum_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
remove = cum_probs - F.softmax(sorted_logits, dim=-1) >= top_p
sorted_logits[remove] = float("-inf")
logits = torch.zeros_like(logits).scatter_(-1, sorted_idx, sorted_logits)
if squeeze:
logits = logits.squeeze(0)
return logits
@torch.inference_mode()
def generate_with_params(
model, tokenizer, prompt, params, device="cuda:0", max_new_tokens=200
):
"""Generate with flexible parameter set."""
model.eval()
input_ids = torch.tensor([tokenizer.encode(prompt).ids], dtype=torch.long, device=device)
eos_id = tokenizer.token_to_id("</s>")
# Parse params
temperature = params.get("temperature", 0.8)
top_p = params.get("top_p", 0.9)
top_k = params.get("top_k", 50)
repetition_penalty = params.get("repetition_penalty", 1.0)
no_repeat_ngram = params.get("no_repeat_ngram_size", 0)
use_contrastive = params.get("contrastive_search", False)
penalty_alpha = params.get("penalty_alpha", 0.6)
contrastive_k = params.get("contrastive_k", 4)
# Stop sequences
stop_strings = params.get("stop_strings", [])
stop_seqs = []
for s in stop_strings:
stop_seqs.append(tokenizer.encode(s).ids)
generated_ids = input_ids
new_token_ids = []
for step in range(max_new_tokens):
logits_all, _ = model(generated_ids)
logits = logits_all[:, -1, :].clone() # [1, V]
# --- Repetition penalty ---
if repetition_penalty != 1.0:
for token_id in set(generated_ids[0].tolist()):
if logits[0, token_id] > 0:
logits[0, token_id] /= repetition_penalty
else:
logits[0, token_id] *= repetition_penalty
# --- No-repeat n-gram blocking ---
if no_repeat_ngram > 0 and len(new_token_ids) >= no_repeat_ngram - 1:
all_ids = generated_ids[0].tolist()
for i in range(len(all_ids) - no_repeat_ngram + 1):
ngram = tuple(all_ids[i:i + no_repeat_ngram - 1])
last_ngram = tuple(all_ids[-(no_repeat_ngram - 1):])
if ngram == last_ngram:
logits[0, all_ids[i + no_repeat_ngram - 1]] = float("-inf")
if use_contrastive:
# Contrastive Search (Yang & Klein 2022)
# Score = (1 - alpha) * model_confidence - alpha * max_cosine_sim
# Simplified: pick top_k candidates, then select one with best contrastive score
top_k_logits, top_k_ids = torch.topk(logits[0], contrastive_k)
probs = F.softmax(top_k_logits, dim=-1)
if step > 0:
# Get hidden states for context (use logits as proxy)
# For true contrastive search we'd need hidden states,
# but as approximation we use logit distribution similarity
best_idx = 0
best_score = float("-inf")
for ki in range(contrastive_k):
confidence = probs[ki].item()
# Degeneration penalty: penalize tokens already generated
token = top_k_ids[ki].item()
penalty = 1.0 if token in set(new_token_ids[-20:]) else 0.0
score = (1 - penalty_alpha) * confidence - penalty_alpha * penalty
if score > best_score:
best_score = score
best_idx = ki
next_token_id = top_k_ids[best_idx].unsqueeze(0).unsqueeze(0)
else:
next_token_id = top_k_ids[0].unsqueeze(0).unsqueeze(0)
else:
# Standard sampling
if temperature == 0.0:
next_token_id = logits.argmax(dim=-1, keepdim=True)
else:
logits = logits / max(temperature, 1e-8)
logits = top_p_filtering(logits, top_p=top_p, top_k=top_k)
probs = F.softmax(logits, dim=-1)
next_token_id = torch.multinomial(probs, num_samples=1)
generated_ids = torch.cat([generated_ids, next_token_id], dim=-1)
new_token_ids.append(next_token_id.item())
# EOS check
if eos_id is not None and next_token_id.item() == eos_id:
break
# Stop sequence check
for seq in stop_seqs:
if len(new_token_ids) >= len(seq) and new_token_ids[-len(seq):] == seq:
new_token_ids = new_token_ids[:-len(seq)]
return tokenizer.decode(new_token_ids)
return tokenizer.decode(new_token_ids)
# ---------------------------------------------------------------------------
# Parameter grid
# ---------------------------------------------------------------------------
PARAM_GRID = [
# Baseline (current settings)
{"name": "baseline", "temperature": 0.8, "top_p": 0.9, "top_k": 50},
# Repetition penalty variants
{"name": "rep_1.1", "temperature": 0.8, "top_p": 0.9, "top_k": 50, "repetition_penalty": 1.1},
{"name": "rep_1.2", "temperature": 0.8, "top_p": 0.9, "top_k": 50, "repetition_penalty": 1.2},
{"name": "rep_1.3", "temperature": 0.8, "top_p": 0.9, "top_k": 50, "repetition_penalty": 1.3},
{"name": "rep_1.5", "temperature": 0.8, "top_p": 0.9, "top_k": 50, "repetition_penalty": 1.5},
# No-repeat n-gram
{"name": "no_rep_3gram", "temperature": 0.8, "top_p": 0.9, "top_k": 50, "no_repeat_ngram_size": 3},
{"name": "no_rep_4gram", "temperature": 0.8, "top_p": 0.9, "top_k": 50, "no_repeat_ngram_size": 4},
# Combined: rep penalty + no-repeat
{"name": "rep1.2+no3gram", "temperature": 0.8, "top_p": 0.9, "top_k": 50,
"repetition_penalty": 1.2, "no_repeat_ngram_size": 3},
# Temperature variants
{"name": "temp_0.5", "temperature": 0.5, "top_p": 0.9, "top_k": 50},
{"name": "temp_0.7", "temperature": 0.7, "top_p": 0.9, "top_k": 50},
{"name": "temp_1.0", "temperature": 1.0, "top_p": 0.9, "top_k": 50},
# Contrastive search
{"name": "contrastive_a0.6_k4", "contrastive_search": True, "penalty_alpha": 0.6, "contrastive_k": 4},
{"name": "contrastive_a0.4_k6", "contrastive_search": True, "penalty_alpha": 0.4, "contrastive_k": 6},
# Stop sequences (most important fix!)
{"name": "stop_seq", "temperature": 0.8, "top_p": 0.9, "top_k": 50,
"stop_strings": ["### ๋ต๋ณ:", "### ์ง๋ฌธ:", "\n\n###"]},
{"name": "rep1.2+stop", "temperature": 0.8, "top_p": 0.9, "top_k": 50,
"repetition_penalty": 1.2, "stop_strings": ["### ๋ต๋ณ:", "### ์ง๋ฌธ:", "\n\n###"]},
# Best combo (predicted)
{"name": "best_combo", "temperature": 0.7, "top_p": 0.9, "top_k": 50,
"repetition_penalty": 1.2, "no_repeat_ngram_size": 3,
"stop_strings": ["### ๋ต๋ณ:", "### ์ง๋ฌธ:", "\n\n###", "<|user|>"]},
# With correct SFT format stop
{"name": "sft_format_stop", "temperature": 0.7, "top_p": 0.9, "top_k": 50,
"repetition_penalty": 1.2, "no_repeat_ngram_size": 3,
"stop_strings": ["<|user|>", "</s>"]},
]
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint", default="checkpoints/korean_1b_sft/checkpoint-0005000")
parser.add_argument("--device", default="cuda:0")
parser.add_argument("--max_new_tokens", type=int, default=200)
parser.add_argument("--output", default="eval/repetition_param_search_results.json")
args = parser.parse_args()
ckpt = Path(args.checkpoint)
if not ckpt.is_absolute():
ckpt = _PROJECT_ROOT / ckpt
print(f"Loading model from {ckpt}...")
model = LLM.from_pretrained(str(ckpt)).to(device=args.device, dtype=torch.bfloat16)
model.eval()
tok_path = ckpt / "tokenizer.json"
if not tok_path.exists():
tok_path = _PROJECT_ROOT / "tokenizer" / "korean_sp" / "tokenizer.json"
tokenizer = Tokenizer.from_file(str(tok_path))
print(f"Model loaded. Params: {sum(p.numel() for p in model.parameters())/1e6:.1f}M")
# Show stop sequence token IDs
print("\n=== Stop Sequence Token IDs ===")
for s in ["### ๋ต๋ณ:", "### ์ง๋ฌธ:", "<|user|>", "<|assistant|>", "</s>", "\n\n###"]:
ids = tokenizer.encode(s).ids
print(f" '{s}' โ {ids}")
# Test both prompt formats
all_results = {}
for format_name, prompts in [("sft_format", SFT_PROMPTS), ("wrong_format", WRONG_FORMAT_PROMPTS)]:
print(f"\n{'='*70}")
print(f" Testing with {format_name}")
print(f"{'='*70}")
for params in PARAM_GRID:
name = params["name"]
key = f"{format_name}/{name}"
print(f"\n--- {key} ---")
rep_scores = []
generations = []
for prompt in prompts:
t0 = time.time()
text = generate_with_params(
model, tokenizer, prompt, params,
device=args.device, max_new_tokens=args.max_new_tokens,
)
elapsed = time.time() - t0
metrics = compute_all_repetition_metrics(text)
rep_scores.append(metrics["3gram_rep"])
generations.append({
"prompt": prompt[:50] + "...",
"generation": text[:200],
"3gram_rep": metrics["3gram_rep"],
"time": round(elapsed, 2),
})
avg_rep = sum(rep_scores) / len(rep_scores) if rep_scores else 0
print(f" Avg 3-gram repetition: {avg_rep*100:.1f}%")
all_results[key] = {
"params": {k: v for k, v in params.items() if k != "name"},
"avg_3gram_rep": round(avg_rep, 4),
"generations": generations,
}
# Sort by avg repetition
print(f"\n{'='*70}")
print(" RESULTS RANKED BY REPETITION RATE")
print(f"{'='*70}")
print(f" {'Config':<35} {'Avg 3gram Rep':>15}")
print(f" {'-'*35} {'-'*15}")
for key, res in sorted(all_results.items(), key=lambda x: x[1]["avg_3gram_rep"]):
print(f" {key:<35} {res['avg_3gram_rep']*100:>14.1f}%")
# Save
out_path = _PROJECT_ROOT / args.output
out_path.parent.mkdir(parents=True, exist_ok=True)
with open(out_path, "w", encoding="utf-8") as f:
json.dump(all_results, f, ensure_ascii=False, indent=2)
print(f"\nResults saved to {out_path}")
if __name__ == "__main__":
main()
|