fhyfhy's picture
Add code/
74b7543 verified
Raw History Blame Contribute Delete
9.58 kB
#!/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()