File size: 9,584 Bytes
74b7543 | 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 | #!/usr/bin/env python3
"""
Evaluate a trained model on test.json and store outputs + accuracy.
Two modes:
- generate (default): greedy generation from input_text until </a> or max_new_tokens
- teacher: argmax next-token predictions on the full target_text (teacher-forced)
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
from typing import Dict, List, Optional
import torch
from transformers import GPT2LMHeadModel, GPT2TokenizerFast
def load_json(path: Path):
with path.open() as f:
return json.load(f)
def tokenize_no_pad(tokenizer: GPT2TokenizerFast, text: str) -> List[int]:
return tokenizer(text, add_special_tokens=False)["input_ids"]
def decode_ids(tokenizer: GPT2TokenizerFast, ids: List[int]) -> str:
return tokenizer.decode(ids, skip_special_tokens=False)
def compute_metrics(items: List[Dict]) -> Dict[str, Dict[str, float]]:
by_type: Dict[str, Dict[str, float]] = {}
for item in items:
key = item.get("type", "ALL")
by_type.setdefault(key, {"total": 0, "correct": 0})
by_type[key]["total"] += 1
by_type[key]["correct"] += 1 if item["correct"] else 0
metrics = {}
for k, v in by_type.items():
total = v["total"]
correct = v["correct"]
acc = correct / total if total else 0.0
metrics[k] = {"total": total, "correct": correct, "accuracy": acc}
return metrics
def add_train_split_metrics(outputs: List[Dict]) -> Dict[str, Dict[str, float]]:
# Derive 1-hop vs 2-hop from token count in target_text.
groups: Dict[str, Dict[str, float]] = {
"Train-OneHop": {"total": 0, "correct": 0},
"Train-TwoHop": {"total": 0, "correct": 0},
}
for item in outputs:
if item.get("_split") != "train":
continue
token_count = len(item["target_text"].replace("</a>", "").strip("<>").split("><"))
if token_count == 3:
key = "Train-OneHop"
elif token_count == 4:
key = "Train-TwoHop"
else:
continue
groups[key]["total"] += 1
groups[key]["correct"] += 1 if item["correct"] else 0
results = {}
for k, v in groups.items():
total = v["total"]
correct = v["correct"]
acc = correct / total if total else 0.0
results[k] = {"total": total, "correct": correct, "accuracy": acc}
return results
def eval_generate(
model: GPT2LMHeadModel,
tokenizer: GPT2TokenizerFast,
data: List[Dict],
device: torch.device,
batch_size: int,
eos_token: str,
max_new_tokens: Optional[int],
):
eos_id = tokenizer.convert_tokens_to_ids(eos_token)
if eos_id is None or eos_id < 0:
eos_id = tokenizer.eos_token_id
pad_id = tokenizer.pad_token_id or tokenizer.eos_token_id
outputs: List[Dict] = []
for i in range(0, len(data), batch_size):
batch = data[i : i + batch_size]
inputs = [item["input_text"] for item in batch]
targets = [item["target_text"] for item in batch]
enc = tokenizer(inputs, return_tensors="pt", padding=True).to(device)
input_ids = enc["input_ids"]
attention_mask = enc["attention_mask"]
target_ids = [tokenize_no_pad(tokenizer, t) for t in targets]
input_ids_list = [tokenize_no_pad(tokenizer, t) for t in inputs]
max_needed = max(len(t) - len(p) for t, p in zip(target_ids, input_ids_list))
cur_max_new = max_new_tokens if max_new_tokens is not None else max_needed
cur_max_new = max(cur_max_new, 1)
with torch.no_grad():
gen = model.generate(
input_ids=input_ids,
attention_mask=attention_mask,
max_new_tokens=cur_max_new,
do_sample=False,
eos_token_id=eos_id,
pad_token_id=pad_id,
)
gen = gen.cpu().tolist()
for item, pred_ids, tgt_ids in zip(batch, gen, target_ids):
# compare the tail of generated sequence to target length (handles left padding)
pred_tail = pred_ids[-len(tgt_ids) :]
correct = pred_tail == tgt_ids
pred_text = decode_ids(tokenizer, pred_tail)
out = {
"input_text": item["input_text"],
"target_text": item["target_text"],
"model_output": pred_text,
"correct": bool(correct),
}
if "type" in item:
out["type"] = item["type"]
outputs.append(out)
return outputs
def eval_teacher(
model: GPT2LMHeadModel,
tokenizer: GPT2TokenizerFast,
data: List[Dict],
device: torch.device,
batch_size: int,
):
outputs: List[Dict] = []
for i in range(0, len(data), batch_size):
batch = data[i : i + batch_size]
targets = [item["target_text"] for item in batch]
enc = tokenizer(targets, return_tensors="pt", padding=True).to(device)
input_ids = enc["input_ids"]
attention_mask = enc["attention_mask"]
with torch.no_grad():
logits = model(input_ids=input_ids, attention_mask=attention_mask).logits
pred_ids = torch.argmax(logits, dim=-1)
for item, pred, tgt, mask in zip(batch, pred_ids, input_ids, attention_mask):
length = int(mask.sum().item())
# next-token prediction: compare pred[:-1] to tgt[1:]
pred_slice = pred[: length - 1].cpu().tolist()
tgt_slice = tgt[1:length].cpu().tolist()
correct = pred_slice == tgt_slice
# reconstruct predicted sequence by shifting left and appending last token
pred_text = decode_ids(tokenizer, pred[:length].cpu().tolist())
out = {
"input_text": item["input_text"],
"target_text": item["target_text"],
"model_output": pred_text,
"correct": bool(correct),
}
if "type" in item:
out["type"] = item["type"]
outputs.append(out)
return outputs
def parse_args():
ap = argparse.ArgumentParser(description="Evaluate a trained model on test.json.")
ap.add_argument("--model-dir", type=Path, required=True, help="Path to trained model directory.")
ap.add_argument("--data-dir", type=Path, required=True, help="Dataset directory containing train.json/test.json.")
ap.add_argument("--output", type=Path, default=Path("test_outputs.json"), help="Where to write outputs.")
ap.add_argument("--metrics", type=Path, default=Path("test_metrics.json"), help="Where to write summary metrics.")
ap.add_argument("--batch-size", type=int, default=16, help="Batch size for evaluation.")
ap.add_argument("--mode", choices=["generate", "teacher"], default="generate", help="Evaluation mode.")
ap.add_argument("--eos-token", type=str, default="</a>", help="Token string to treat as eos for generation.")
ap.add_argument("--max-new-tokens", type=int, default=None, help="Max new tokens for generation.")
ap.add_argument("--device", type=str, default=None, help="Device (e.g., cuda, cuda:0, cpu).")
return ap.parse_args()
def main():
args = parse_args()
test_path = args.data_dir / "test.json"
train_path = args.data_dir / "train.json"
if not test_path.exists():
raise FileNotFoundError(f"Missing test.json at {test_path}")
if not train_path.exists():
raise FileNotFoundError(f"Missing train.json at {train_path}")
device = torch.device(args.device or ("cuda" if torch.cuda.is_available() else "cpu"))
tokenizer = GPT2TokenizerFast.from_pretrained(args.model_dir)
tokenizer.pad_token = tokenizer.eos_token
tokenizer.padding_side = "left"
model = GPT2LMHeadModel.from_pretrained(args.model_dir).to(device)
model.eval()
test_data = load_json(test_path)
train_data = load_json(train_path)
if args.mode == "generate":
test_outputs = eval_generate(
model,
tokenizer,
test_data,
device=device,
batch_size=args.batch_size,
eos_token=args.eos_token,
max_new_tokens=args.max_new_tokens,
)
train_outputs = eval_generate(
model,
tokenizer,
train_data,
device=device,
batch_size=args.batch_size,
eos_token=args.eos_token,
max_new_tokens=args.max_new_tokens,
)
else:
test_outputs = eval_teacher(
model,
tokenizer,
test_data,
device=device,
batch_size=args.batch_size,
)
train_outputs = eval_teacher(
model,
tokenizer,
train_data,
device=device,
batch_size=args.batch_size,
)
# Tag splits for later metrics.
for item in test_outputs:
item["_split"] = "test"
for item in train_outputs:
item["_split"] = "train"
outputs = test_outputs + train_outputs
args.output.parent.mkdir(parents=True, exist_ok=True)
with args.output.open("w", encoding="utf-8") as f:
json.dump(outputs, f)
metrics = compute_metrics(outputs)
metrics.update(add_train_split_metrics(outputs))
args.metrics.parent.mkdir(parents=True, exist_ok=True)
with args.metrics.open("w", encoding="utf-8") as f:
json.dump(metrics, f)
print(f"Wrote outputs to {args.output}")
print(f"Wrote metrics to {args.metrics}")
if __name__ == "__main__":
main()
|