File size: 3,613 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 | """Evaluate a trained hyper model on a dataset without any further training.
Reads the architecture from the run's hyper_model.pt, loads the newest weights,
and reports stage-wise accuracy on every eval split of --data.
Usage:
python eval_checkpoint.py --run-dir outputs/hyper_run.... \
--data data/twin_2345hop_truood_diff.500.50.10 --max-length 7
# override the loop count the model is unrolled for:
python eval_checkpoint.py --run-dir ... --num-stages 5
"""
import argparse
import json
import types
from pathlib import Path
import torch
import train_twin_hyper as m
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--run-dir", type=str, required=True)
ap.add_argument("--data", type=Path, required=True)
ap.add_argument("--max-length", type=int, required=True)
ap.add_argument("--num-stages", type=int, default=None, help="default: as trained")
ap.add_argument("--batch-size", type=int, default=1024)
ap.add_argument("--device", type=str, default="cuda")
args = ap.parse_args()
cfg_path = Path(args.run_dir) / "stage2_hyper" / "hyper_model.pt"
blob = torch.load(cfg_path, map_location="cpu", weights_only=False)
hc, saved = blob["hyper_config"], blob["args"]
ns = args.num_stages if args.num_stages is not None else hc["num_stages"]
print(f"architecture: {hc['loop_scheme']} m{hc['num_stages']} "
f"gate={hc['gate_mode']} alpha={hc['fixed_alpha']} beta={hc['fixed_beta']}"
+ (f" [unrolled to {ns} stages]" if ns != hc["num_stages"] else ""))
ns_args = types.SimpleNamespace(
model_name=saved["model_name"], from_scratch=True, trust_remote_code=False,
use_small_tokenizer=saved.get("use_small_tokenizer", True),
create_special_token=saved.get("create_special_token", True),
tokenizer_name=saved.get("tokenizer_name"),
data_dir=args.data, init_one_hot=0, freeze_embeddings=0,
)
tokenizer = m.build_tokenizer(ns_args)
base = m.build_base_model(ns_args, tokenizer)
model = m.HyperConnectionGPT2LM(
base_model=base, num_stages=ns, architecture=hc["architecture"],
gate_mode=hc["gate_mode"], fixed_alpha=hc["fixed_alpha"], fixed_beta=hc["fixed_beta"],
norm_type=saved.get("norm_type", "rms"), zero_final_gate=hc["zero_final_gate"],
sg_phi=hc["sg_phi"], use_position_embeddings=hc["use_position_embeddings"],
loop_scheme=hc.get("loop_scheme", "discoloop"),
)
m.load_hyper_weights(model, args.run_dir)
model = model.eval().to(args.device)
train_data = json.loads((args.data / "train.json").read_text())
groups = m.group_by_hops(train_data)
splits = {"train_atom": groups.get(1, [])}
for h in sorted(groups):
if h > 1:
splits[f"train_{h}hop"] = groups[h]
for tag, fn in (("id", "test_id.json"), ("ood", "test_ood.json")):
p = args.data / fn
if p.exists():
for h, recs in sorted(m.group_by_hops(json.loads(p.read_text())).items()):
splits[f"test_{h}hop_{tag}"] = recs
datasets = {k: m.JsonTextDataset(v, tokenizer, args.max_length, "answer") for k, v in splits.items()}
metrics = m.evaluate_named_splits(model, datasets, torch.device(args.device), args.batch_size)
print(f"\n{'split':16s}" + "".join(f"{'s'+str(i):>9s}" for i in range(1, ns + 1)) + f"{'n':>8s}")
for name in datasets:
row = "".join(f"{metrics.get(f'{name}_stage{i}_acc', 0.0):9.4f}" for i in range(1, ns + 1))
print(f"{name:16s}{row}{int(metrics.get(f'{name}_count', 0)):8d}")
if __name__ == "__main__":
main()
|