Update evaluation_harness.py
Browse files- evaluation_harness.py +521 -137
evaluation_harness.py
CHANGED
|
@@ -1,39 +1,60 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
GCI-Bench harness
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
|
|
|
|
|
|
| 7 |
|
| 8 |
This benchmark does NOT grade answer correctness. It only inspects internal
|
| 9 |
-
attention/gradient dynamics
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
Usage:
|
| 13 |
-
python
|
| 14 |
-
python
|
| 15 |
-
python
|
| 16 |
-
--
|
| 17 |
-
|
| 18 |
-
See README.md in this folder for a full explanation of the scoring formulas.
|
| 19 |
"""
|
| 20 |
|
| 21 |
from __future__ import annotations
|
| 22 |
|
| 23 |
import argparse
|
|
|
|
| 24 |
import json
|
| 25 |
import os
|
| 26 |
import random
|
| 27 |
import sys
|
| 28 |
import urllib.request
|
| 29 |
-
from dataclasses import dataclass
|
| 30 |
from typing import Any, Optional
|
| 31 |
|
| 32 |
import numpy as np
|
| 33 |
-
import pandas as pd
|
| 34 |
import pyarrow.parquet as pq
|
| 35 |
import torch
|
| 36 |
-
import torch.nn.functional as F # noqa: F401 (kept for clarity / potential extensions)
|
| 37 |
|
| 38 |
try:
|
| 39 |
from tqdm import tqdm
|
|
@@ -41,10 +62,10 @@ except ImportError: # pragma: no cover - tqdm is a soft dependency
|
|
| 41 |
def tqdm(iterable, **kwargs):
|
| 42 |
return iterable
|
| 43 |
|
| 44 |
-
|
| 45 |
from transformers import (
|
| 46 |
AutoModelForCausalLM,
|
| 47 |
AutoModelForMaskedLM,
|
|
|
|
| 48 |
AutoTokenizer,
|
| 49 |
)
|
| 50 |
|
|
@@ -52,6 +73,18 @@ EPS = 1e-8
|
|
| 52 |
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 53 |
DEFAULT_DATASET = os.path.join(SCRIPT_DIR, "data", "test-00000-of-00001.parquet")
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
# ---------------------------------------------------------------------------
|
| 57 |
# Data loading
|
|
@@ -64,93 +97,156 @@ def load_dataset(path: str) -> list[dict]:
|
|
| 64 |
return [json.loads(line) for line in text.splitlines() if line.strip()]
|
| 65 |
return json.loads(text)
|
| 66 |
|
| 67 |
-
# Parquet format (HuggingFace-compatible, preferred)
|
| 68 |
if path.endswith(".parquet"):
|
| 69 |
table = pq.read_table(path)
|
| 70 |
df = table.to_pandas()
|
| 71 |
items = []
|
| 72 |
for _, row in df.iterrows():
|
| 73 |
item = row.to_dict()
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
item[field] = json.loads(item[field])
|
| 78 |
items.append(item)
|
| 79 |
return items
|
| 80 |
|
| 81 |
-
# JSONL format (legacy fallback)
|
| 82 |
with open(path, "r", encoding="utf-8") as f:
|
| 83 |
return [json.loads(line) for line in f if line.strip()]
|
| 84 |
|
| 85 |
|
| 86 |
# ---------------------------------------------------------------------------
|
| 87 |
-
# Model loading
|
| 88 |
# ---------------------------------------------------------------------------
|
| 89 |
@dataclass
|
| 90 |
class LoadedModel:
|
| 91 |
tokenizer: Any
|
| 92 |
model: Any
|
| 93 |
-
model_type: str # "causal" | "mlm"
|
| 94 |
num_params: int
|
| 95 |
device: torch.device
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
|
| 98 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
trust_kwargs = {"trust_remote_code": True} if trust_remote_code else {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
| 102 |
-
model_name, use_fast=True, **trust_kwargs
|
| 103 |
-
)
|
| 104 |
if tokenizer.pad_token is None:
|
| 105 |
if tokenizer.eos_token is not None:
|
| 106 |
tokenizer.pad_token = tokenizer.eos_token
|
| 107 |
else:
|
| 108 |
tokenizer.add_special_tokens({"pad_token": "[PAD]"})
|
| 109 |
|
|
|
|
|
|
|
| 110 |
last_error: Optional[Exception] = None
|
| 111 |
-
for model_cls, model_type in
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
try:
|
| 114 |
-
model = model_cls.from_pretrained(
|
| 115 |
-
model_name, attn_implementation="eager", **trust_kwargs
|
| 116 |
-
)
|
| 117 |
except TypeError:
|
| 118 |
-
# Older transformers
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
model.to(device)
|
| 121 |
model.eval()
|
| 122 |
num_params = sum(p.numel() for p in model.parameters())
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
-
# If trust_remote_code=False failed with custom-code error, retry with trust_remote_code
|
| 129 |
if not trust_remote_code and last_error and "trust_remote_code" in str(last_error).lower():
|
| 130 |
-
return load_model(model_name, device,
|
| 131 |
|
| 132 |
raise RuntimeError(
|
| 133 |
-
f"Could not load '{model_name}' as
|
|
|
|
| 134 |
)
|
| 135 |
|
| 136 |
|
| 137 |
# ---------------------------------------------------------------------------
|
| 138 |
-
#
|
| 139 |
# ---------------------------------------------------------------------------
|
| 140 |
-
@dataclass
|
| 141 |
-
class ItemResult:
|
| 142 |
-
id: str
|
| 143 |
-
topic: str
|
| 144 |
-
difficulty: str
|
| 145 |
-
num_tokens: int
|
| 146 |
-
priority_score: float
|
| 147 |
-
linkage_score: Optional[float]
|
| 148 |
-
related_mean: float
|
| 149 |
-
unrelated_mean: float
|
| 150 |
-
skipped: bool = False
|
| 151 |
-
reason: str = ""
|
| 152 |
-
|
| 153 |
-
|
| 154 |
def char_span_to_token_indices(offsets: list[tuple[int, int]], char_start: int, char_end: int) -> list[int]:
|
| 155 |
idxs = []
|
| 156 |
for i, (s, e) in enumerate(offsets):
|
|
@@ -161,21 +257,165 @@ def char_span_to_token_indices(offsets: list[tuple[int, int]], char_start: int,
|
|
| 161 |
return idxs
|
| 162 |
|
| 163 |
|
| 164 |
-
def
|
| 165 |
-
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
saliency = torch.zeros((seq_len, seq_len), dtype=torch.float32)
|
| 168 |
-
|
|
|
|
| 169 |
grad = attn.grad
|
| 170 |
if grad is None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
continue
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
return saliency.numpy()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
|
| 177 |
|
| 178 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
tokenizer, model, model_type, device = (
|
| 180 |
loaded.tokenizer,
|
| 181 |
loaded.model,
|
|
@@ -187,64 +427,99 @@ def run_item(loaded: LoadedModel, item: dict, max_length: int, mask_ratio: float
|
|
| 187 |
question = item["question"]
|
| 188 |
full_text = f"{context} {question}"
|
| 189 |
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
input_ids = enc["input_ids"].to(device)
|
| 199 |
attention_mask = enc.get("attention_mask")
|
| 200 |
if attention_mask is not None:
|
| 201 |
attention_mask = attention_mask.to(device)
|
| 202 |
|
|
|
|
|
|
|
|
|
|
| 203 |
seq_len = input_ids.shape[1]
|
| 204 |
if seq_len < 4:
|
| 205 |
-
return
|
| 206 |
|
| 207 |
model.zero_grad(set_to_none=True)
|
| 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 |
-
labels=
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
|
| 239 |
if loss is None or not torch.isfinite(loss):
|
| 240 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
-
|
| 243 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
|
| 245 |
-
|
|
|
|
|
|
|
| 246 |
|
| 247 |
-
saliency = compute_saliency_matrix(attentions) # (seq, seq)
|
| 248 |
token_importance = saliency.sum(axis=0) # per key-token, summed over queries
|
| 249 |
|
| 250 |
segments = item["segments"]
|
|
@@ -260,15 +535,12 @@ def run_item(loaded: LoadedModel, item: dict, max_length: int, mask_ratio: float
|
|
| 260 |
unrelated_tokens = sorted({t for sid in unrelated_ids for t in seg_token_idxs.get(sid, [])})
|
| 261 |
|
| 262 |
if not related_tokens or not unrelated_tokens:
|
| 263 |
-
return
|
| 264 |
|
| 265 |
related_mean = float(token_importance[related_tokens].mean())
|
| 266 |
unrelated_mean = float(token_importance[unrelated_tokens].mean())
|
| 267 |
priority_score = 100.0 * related_mean / (related_mean + unrelated_mean + EPS)
|
| 268 |
|
| 269 |
-
# Linkage: for each causally-linked pair of related segments, compare the
|
| 270 |
-
# attention*gradient mass exchanged between them against a control baseline
|
| 271 |
-
# of mass exchanged between related content and unrelated (distractor) content.
|
| 272 |
pair_scores = []
|
| 273 |
for a, b in item.get("keyLinkPairs", []):
|
| 274 |
idx_a = seg_token_idxs.get(a, [])
|
|
@@ -298,6 +570,60 @@ def run_item(loaded: LoadedModel, item: dict, max_length: int, mask_ratio: float
|
|
| 298 |
)
|
| 299 |
|
| 300 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
# ---------------------------------------------------------------------------
|
| 302 |
# Main
|
| 303 |
# ---------------------------------------------------------------------------
|
|
@@ -305,15 +631,28 @@ def main():
|
|
| 305 |
parser = argparse.ArgumentParser(description="GCI-Bench harness for small HuggingFace transformers.")
|
| 306 |
parser.add_argument("--model", required=True, help="HuggingFace model id or local path (should be <=~100M params).")
|
| 307 |
parser.add_argument("--dataset", default=DEFAULT_DATASET, help="Path or URL to gci-bench .parquet or .jsonl.")
|
| 308 |
-
parser.add_argument("--limit", type=int, default=500, help="Number of questions to sample (0 = all
|
| 309 |
parser.add_argument("--topic", default=None, help="Only evaluate a single topic id (e.g. 'cooking').")
|
| 310 |
parser.add_argument("--max-length", type=int, default=256, help="Max token length per item.")
|
| 311 |
parser.add_argument("--mask-ratio", type=float, default=0.15, help="Mask ratio used for MLM-style models.")
|
| 312 |
parser.add_argument("--seed", type=int, default=42)
|
| 313 |
parser.add_argument("--device", default=None, help="cpu | cuda | mps (default: auto-detect).")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
parser.add_argument("--output", default=None, help="Where to write the full JSON results.")
|
| 315 |
-
parser.add_argument("--
|
| 316 |
-
parser.add_argument("--
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
args = parser.parse_args()
|
| 318 |
|
| 319 |
random.seed(args.seed)
|
|
@@ -330,35 +669,75 @@ def main():
|
|
| 330 |
else:
|
| 331 |
device = torch.device("cpu")
|
| 332 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
print(f"Loading dataset from {args.dataset} ...")
|
| 334 |
items = load_dataset(args.dataset)
|
| 335 |
if args.topic:
|
| 336 |
items = [it for it in items if it["topic"] == args.topic]
|
| 337 |
print(f"Loaded {len(items)} items.")
|
| 338 |
|
| 339 |
-
if args.limit and
|
| 340 |
items = rng.sample(items, args.limit)
|
| 341 |
print(f"Evaluating {len(items)} items.")
|
| 342 |
|
| 343 |
-
print(f"Loading model '{args.model}' on {device} ...")
|
| 344 |
-
loaded = load_model(
|
| 345 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
if loaded.num_params > 100_000_000:
|
| 347 |
print(
|
| 348 |
f"WARNING: model has {loaded.num_params/1e6:.1f}M parameters, which is above the "
|
| 349 |
"intended <=100M range for GCI-Bench. Results are still computed, but keep this in mind."
|
| 350 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
|
| 352 |
results: list[ItemResult] = []
|
| 353 |
for item in tqdm(items, desc="Scoring"):
|
| 354 |
try:
|
| 355 |
res = run_item(loaded, item, args.max_length, args.mask_ratio, rng)
|
| 356 |
except Exception as e: # noqa: BLE001 - keep going on isolated failures
|
| 357 |
-
res =
|
| 358 |
results.append(res)
|
| 359 |
|
| 360 |
valid = [r for r in results if not r.skipped]
|
| 361 |
skipped = len(results) - len(valid)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
if not valid:
|
| 363 |
print("No valid items were scored. Aborting.")
|
| 364 |
sys.exit(1)
|
|
@@ -382,6 +761,7 @@ def main():
|
|
| 382 |
"modelName": args.model,
|
| 383 |
"numParams": int(loaded.num_params),
|
| 384 |
"modelType": loaded.model_type,
|
|
|
|
| 385 |
"numQuestions": len(valid),
|
| 386 |
"numSkipped": skipped,
|
| 387 |
"priorityScore": round(priority_score, 3),
|
|
@@ -389,11 +769,12 @@ def main():
|
|
| 389 |
"gciScore": round(gci_score, 3),
|
| 390 |
"priorityByTopic": by_topic_avg,
|
| 391 |
"priorityByDifficulty": by_difficulty_avg,
|
|
|
|
| 392 |
"notes": args.notes,
|
| 393 |
}
|
| 394 |
|
| 395 |
print("\n=== GCI-Bench summary ===")
|
| 396 |
-
print(json.dumps({k: v for k, v in summary.items() if k
|
| 397 |
|
| 398 |
full_output = {
|
| 399 |
"summary": summary,
|
|
@@ -405,21 +786,24 @@ def main():
|
|
| 405 |
json.dump(full_output, f, indent=2)
|
| 406 |
print(f"\nWrote full results to {args.output}")
|
| 407 |
|
| 408 |
-
if args.
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
|
|
|
|
|
|
|
|
|
| 422 |
|
| 423 |
|
| 424 |
if __name__ == "__main__":
|
| 425 |
-
main()
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
GCI-Bench harness (robust build)
|
| 4 |
+
=================================
|
| 5 |
+
Measures whether a small (1M-100M parameter) HuggingFace transformer's
|
| 6 |
+
attention * gradient saliency prioritizes causally-relevant ("related")
|
| 7 |
+
sentences over same-domain "distractor" sentences mixed into the same
|
| 8 |
+
context, and whether it links causally-connected sentences together.
|
| 9 |
|
| 10 |
This benchmark does NOT grade answer correctness. It only inspects internal
|
| 11 |
+
attention/gradient dynamics.
|
| 12 |
+
|
| 13 |
+
Design goals for this build:
|
| 14 |
+
* Works across CausalLM / MaskedLM / Seq2SeqLM architectures.
|
| 15 |
+
* Tries multiple attn_implementation values and falls back gracefully when
|
| 16 |
+
a custom architecture hard-errors on sdpa/flash_attention_2 (many do).
|
| 17 |
+
* Extracts attention tensors generically -- not just from `.attentions` --
|
| 18 |
+
so custom/trust_remote_code architectures with nonstandard output field
|
| 19 |
+
names still work if they expose *some* attention-shaped tensor.
|
| 20 |
+
* Normalizes arbitrary attention tensor dim orderings (batch/heads/seq_q/
|
| 21 |
+
seq_k in any order) instead of assuming a fixed layout.
|
| 22 |
+
* Falls back to an approximate char-offset reconstruction for tokenizers
|
| 23 |
+
that don't support `return_offsets_mapping` (some custom/slow
|
| 24 |
+
tokenizers).
|
| 25 |
+
* Never crashes the whole run on a single bad item/layer -- everything
|
| 26 |
+
that can fail is caught and turned into a clearly-labeled skip reason.
|
| 27 |
+
|
| 28 |
+
Hard limitation that CANNOT be worked around: architectures whose attention
|
| 29 |
+
is computed purely inside a fused, non-differentiable-wrt-weights kernel
|
| 30 |
+
(e.g. some flash-attention-only custom code that never returns/retains
|
| 31 |
+
attention *weights* as a tensor with a grad_fn) cannot be introspected by
|
| 32 |
+
this technique at all. Those items/models will be skipped with reason
|
| 33 |
+
"attentions_not_differentiable" or "no_attentions_returned".
|
| 34 |
|
| 35 |
Usage:
|
| 36 |
+
python evaluation_harness.py --model roneneldan/TinyStories-33M --limit 500
|
| 37 |
+
python evaluation_harness.py --model prajjwal1/bert-tiny --limit 300
|
| 38 |
+
python evaluation_harness.py --model distilgpt2 --limit 1000 \
|
| 39 |
+
--hub-model-repo distilbert/distilgpt2 --dataset-id your-org/gci-bench
|
|
|
|
|
|
|
| 40 |
"""
|
| 41 |
|
| 42 |
from __future__ import annotations
|
| 43 |
|
| 44 |
import argparse
|
| 45 |
+
import datetime
|
| 46 |
import json
|
| 47 |
import os
|
| 48 |
import random
|
| 49 |
import sys
|
| 50 |
import urllib.request
|
| 51 |
+
from dataclasses import dataclass
|
| 52 |
from typing import Any, Optional
|
| 53 |
|
| 54 |
import numpy as np
|
| 55 |
+
import pandas as pd # noqa: F401 (kept for parity / potential future use)
|
| 56 |
import pyarrow.parquet as pq
|
| 57 |
import torch
|
|
|
|
| 58 |
|
| 59 |
try:
|
| 60 |
from tqdm import tqdm
|
|
|
|
| 62 |
def tqdm(iterable, **kwargs):
|
| 63 |
return iterable
|
| 64 |
|
|
|
|
| 65 |
from transformers import (
|
| 66 |
AutoModelForCausalLM,
|
| 67 |
AutoModelForMaskedLM,
|
| 68 |
+
AutoModelForSeq2SeqLM,
|
| 69 |
AutoTokenizer,
|
| 70 |
)
|
| 71 |
|
|
|
|
| 73 |
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 74 |
DEFAULT_DATASET = os.path.join(SCRIPT_DIR, "data", "test-00000-of-00001.parquet")
|
| 75 |
|
| 76 |
+
MODEL_CLASSES: list[tuple[Any, str]] = [
|
| 77 |
+
(AutoModelForCausalLM, "causal"),
|
| 78 |
+
(AutoModelForMaskedLM, "mlm"),
|
| 79 |
+
(AutoModelForSeq2SeqLM, "seq2seq"),
|
| 80 |
+
]
|
| 81 |
+
|
| 82 |
+
# Tried in order. `None` means "don't pass attn_implementation at all, let
|
| 83 |
+
# the library/custom code decide" -- necessary because some architectures
|
| 84 |
+
# error out on an explicit "eager" string too (rare, but happens with some
|
| 85 |
+
# trust_remote_code models that only recognize their own custom names).
|
| 86 |
+
DEFAULT_ATTN_CANDIDATES: list[Optional[str]] = ["eager", None]
|
| 87 |
+
|
| 88 |
|
| 89 |
# ---------------------------------------------------------------------------
|
| 90 |
# Data loading
|
|
|
|
| 97 |
return [json.loads(line) for line in text.splitlines() if line.strip()]
|
| 98 |
return json.loads(text)
|
| 99 |
|
|
|
|
| 100 |
if path.endswith(".parquet"):
|
| 101 |
table = pq.read_table(path)
|
| 102 |
df = table.to_pandas()
|
| 103 |
items = []
|
| 104 |
for _, row in df.iterrows():
|
| 105 |
item = row.to_dict()
|
| 106 |
+
for key in ("segments", "relatedSegmentIds", "unrelatedSegmentIds", "keyLinkPairs", "meta"):
|
| 107 |
+
if isinstance(item.get(key), str):
|
| 108 |
+
item[key] = json.loads(item[key])
|
|
|
|
| 109 |
items.append(item)
|
| 110 |
return items
|
| 111 |
|
|
|
|
| 112 |
with open(path, "r", encoding="utf-8") as f:
|
| 113 |
return [json.loads(line) for line in f if line.strip()]
|
| 114 |
|
| 115 |
|
| 116 |
# ---------------------------------------------------------------------------
|
| 117 |
+
# Model loading -- robust to custom architectures / custom attention kernels
|
| 118 |
# ---------------------------------------------------------------------------
|
| 119 |
@dataclass
|
| 120 |
class LoadedModel:
|
| 121 |
tokenizer: Any
|
| 122 |
model: Any
|
| 123 |
+
model_type: str # "causal" | "mlm" | "seq2seq"
|
| 124 |
num_params: int
|
| 125 |
device: torch.device
|
| 126 |
+
attn_implementation: str
|
| 127 |
+
is_encoder_decoder: bool
|
| 128 |
+
fast_tokenizer: bool
|
| 129 |
|
| 130 |
|
| 131 |
+
def _try_force_eager_post_load(model: Any) -> None:
|
| 132 |
+
"""Best-effort: force a loaded model into eager attention mode even if
|
| 133 |
+
from_pretrained's attn_implementation kwarg was ignored (this happens
|
| 134 |
+
with some trust_remote_code custom architectures)."""
|
| 135 |
+
set_fn = getattr(model, "set_attn_implementation", None)
|
| 136 |
+
if callable(set_fn):
|
| 137 |
+
try:
|
| 138 |
+
set_fn("eager")
|
| 139 |
+
return
|
| 140 |
+
except Exception:
|
| 141 |
+
pass
|
| 142 |
+
|
| 143 |
+
cfg = getattr(model, "config", None)
|
| 144 |
+
if cfg is None:
|
| 145 |
+
return
|
| 146 |
+
for attr in ("_attn_implementation", "attn_implementation"):
|
| 147 |
+
try:
|
| 148 |
+
setattr(cfg, attr, "eager")
|
| 149 |
+
except Exception:
|
| 150 |
+
pass
|
| 151 |
+
# Multimodal / composite configs (per-backbone attn implementations).
|
| 152 |
+
for sub_name in getattr(cfg, "sub_configs", {}) or {}:
|
| 153 |
+
sub_cfg = getattr(cfg, sub_name, None)
|
| 154 |
+
if sub_cfg is not None:
|
| 155 |
+
try:
|
| 156 |
+
setattr(sub_cfg, "_attn_implementation", "eager")
|
| 157 |
+
except Exception:
|
| 158 |
+
pass
|
| 159 |
+
try:
|
| 160 |
+
cfg.output_attentions = True
|
| 161 |
+
except Exception:
|
| 162 |
+
pass
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def load_model(
|
| 166 |
+
model_name: str,
|
| 167 |
+
device: torch.device,
|
| 168 |
+
attn_candidates: list[Optional[str]],
|
| 169 |
+
dtype: Optional[str] = None,
|
| 170 |
+
trust_remote_code: bool = False,
|
| 171 |
+
revision: Optional[str] = None,
|
| 172 |
+
) -> LoadedModel:
|
| 173 |
trust_kwargs = {"trust_remote_code": True} if trust_remote_code else {}
|
| 174 |
+
rev_kwargs = {"revision": revision} if revision else {}
|
| 175 |
+
|
| 176 |
+
fast_tokenizer = True
|
| 177 |
+
try:
|
| 178 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True, **trust_kwargs, **rev_kwargs)
|
| 179 |
+
except Exception:
|
| 180 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False, **trust_kwargs, **rev_kwargs)
|
| 181 |
+
fast_tokenizer = False
|
| 182 |
+
if not getattr(tokenizer, "is_fast", False):
|
| 183 |
+
fast_tokenizer = False
|
| 184 |
|
|
|
|
|
|
|
|
|
|
| 185 |
if tokenizer.pad_token is None:
|
| 186 |
if tokenizer.eos_token is not None:
|
| 187 |
tokenizer.pad_token = tokenizer.eos_token
|
| 188 |
else:
|
| 189 |
tokenizer.add_special_tokens({"pad_token": "[PAD]"})
|
| 190 |
|
| 191 |
+
torch_dtype = getattr(torch, dtype, None) if dtype else None
|
| 192 |
+
|
| 193 |
last_error: Optional[Exception] = None
|
| 194 |
+
for model_cls, model_type in MODEL_CLASSES:
|
| 195 |
+
for attn_impl in attn_candidates:
|
| 196 |
+
kwargs: dict[str, Any] = dict(trust_kwargs)
|
| 197 |
+
kwargs.update(rev_kwargs)
|
| 198 |
+
if torch_dtype is not None:
|
| 199 |
+
kwargs["torch_dtype"] = torch_dtype
|
| 200 |
+
if attn_impl is not None:
|
| 201 |
+
kwargs["attn_implementation"] = attn_impl
|
| 202 |
try:
|
| 203 |
+
model = model_cls.from_pretrained(model_name, **kwargs)
|
|
|
|
|
|
|
| 204 |
except TypeError:
|
| 205 |
+
# Older transformers / architecture doesn't accept this kwarg at all.
|
| 206 |
+
kwargs.pop("attn_implementation", None)
|
| 207 |
+
try:
|
| 208 |
+
model = model_cls.from_pretrained(model_name, **kwargs)
|
| 209 |
+
except Exception as e: # noqa: BLE001
|
| 210 |
+
last_error = e
|
| 211 |
+
continue
|
| 212 |
+
except ValueError as e:
|
| 213 |
+
# e.g. "<Arch> does not support an attention implementation
|
| 214 |
+
# through torch.nn.functional.scaled_dot_product_attention yet."
|
| 215 |
+
last_error = e
|
| 216 |
+
continue
|
| 217 |
+
except Exception as e: # noqa: BLE001
|
| 218 |
+
last_error = e
|
| 219 |
+
continue
|
| 220 |
+
|
| 221 |
+
_try_force_eager_post_load(model)
|
| 222 |
model.to(device)
|
| 223 |
model.eval()
|
| 224 |
num_params = sum(p.numel() for p in model.parameters())
|
| 225 |
+
resolved_impl = str(getattr(model.config, "_attn_implementation", attn_impl or "unknown"))
|
| 226 |
+
is_enc_dec = bool(getattr(model.config, "is_encoder_decoder", model_type == "seq2seq"))
|
| 227 |
+
return LoadedModel(
|
| 228 |
+
tokenizer=tokenizer,
|
| 229 |
+
model=model,
|
| 230 |
+
model_type=model_type,
|
| 231 |
+
num_params=num_params,
|
| 232 |
+
device=device,
|
| 233 |
+
attn_implementation=resolved_impl,
|
| 234 |
+
is_encoder_decoder=is_enc_dec,
|
| 235 |
+
fast_tokenizer=fast_tokenizer,
|
| 236 |
+
)
|
| 237 |
|
|
|
|
| 238 |
if not trust_remote_code and last_error and "trust_remote_code" in str(last_error).lower():
|
| 239 |
+
return load_model(model_name, device, attn_candidates, dtype, True, revision)
|
| 240 |
|
| 241 |
raise RuntimeError(
|
| 242 |
+
f"Could not load '{model_name}' as CausalLM / MaskedLM / Seq2SeqLM with any of "
|
| 243 |
+
f"attn_implementation in {attn_candidates}: {last_error}"
|
| 244 |
)
|
| 245 |
|
| 246 |
|
| 247 |
# ---------------------------------------------------------------------------
|
| 248 |
+
# Offset mapping (with fallback for slow / custom tokenizers)
|
| 249 |
# ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
def char_span_to_token_indices(offsets: list[tuple[int, int]], char_start: int, char_end: int) -> list[int]:
|
| 251 |
idxs = []
|
| 252 |
for i, (s, e) in enumerate(offsets):
|
|
|
|
| 257 |
return idxs
|
| 258 |
|
| 259 |
|
| 260 |
+
def approx_offsets_from_slow_tokenizer(
|
| 261 |
+
tokenizer: Any, text: str, input_ids: torch.Tensor
|
| 262 |
+
) -> list[tuple[int, int]]:
|
| 263 |
+
"""Best-effort char-offset reconstruction for tokenizers that don't
|
| 264 |
+
support `return_offsets_mapping` (slow / custom tokenizers). Walks
|
| 265 |
+
through the decoded pieces and locates them in `text` sequentially.
|
| 266 |
+
This is approximate -- it can misalign on tokenizers with heavy
|
| 267 |
+
normalization (e.g. lowercasing, accent stripping) -- but degrades
|
| 268 |
+
gracefully to a (0, 0) "unknown span" per unmatched token rather than
|
| 269 |
+
crashing.
|
| 270 |
+
"""
|
| 271 |
+
offsets: list[tuple[int, int]] = []
|
| 272 |
+
cursor = 0
|
| 273 |
+
special_ids = set(getattr(tokenizer, "all_special_ids", []) or [])
|
| 274 |
+
for tok_id in input_ids[0].tolist():
|
| 275 |
+
if tok_id in special_ids:
|
| 276 |
+
offsets.append((0, 0))
|
| 277 |
+
continue
|
| 278 |
+
piece = tokenizer.decode([tok_id], skip_special_tokens=False, clean_up_tokenization_spaces=False)
|
| 279 |
+
stripped = piece.strip()
|
| 280 |
+
if not stripped:
|
| 281 |
+
offsets.append((0, 0))
|
| 282 |
+
continue
|
| 283 |
+
pos = text.find(stripped, cursor)
|
| 284 |
+
if pos == -1:
|
| 285 |
+
pos = text.find(stripped)
|
| 286 |
+
if pos == -1:
|
| 287 |
+
offsets.append((0, 0))
|
| 288 |
+
continue
|
| 289 |
+
start, end = pos, pos + len(stripped)
|
| 290 |
+
offsets.append((start, end))
|
| 291 |
+
cursor = end
|
| 292 |
+
return offsets
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
# ---------------------------------------------------------------------------
|
| 296 |
+
# Generic attention extraction + shape normalization
|
| 297 |
+
# ---------------------------------------------------------------------------
|
| 298 |
+
def extract_raw_attentions(outputs: Any, prefer_fields: tuple[str, ...] = ()) -> list[torch.Tensor]:
|
| 299 |
+
"""Pull every self-attention weight tensor out of a HF ModelOutput,
|
| 300 |
+
regardless of model family / custom architecture field naming."""
|
| 301 |
+
found: list[torch.Tensor] = []
|
| 302 |
+
seen_ids: set[int] = set()
|
| 303 |
+
|
| 304 |
+
def add(t: Any) -> None:
|
| 305 |
+
if torch.is_tensor(t) and id(t) not in seen_ids:
|
| 306 |
+
seen_ids.add(id(t))
|
| 307 |
+
found.append(t)
|
| 308 |
+
|
| 309 |
+
ordered_fields = tuple(prefer_fields) + ("attentions", "decoder_attentions", "encoder_attentions", "cross_attentions")
|
| 310 |
+
for field_name in ordered_fields:
|
| 311 |
+
val = getattr(outputs, field_name, None)
|
| 312 |
+
if val:
|
| 313 |
+
for t in val:
|
| 314 |
+
add(t)
|
| 315 |
+
if found:
|
| 316 |
+
return found
|
| 317 |
+
|
| 318 |
+
# Generic fallback: scan every output field whose name mentions attention,
|
| 319 |
+
# for custom architectures using nonstandard field names.
|
| 320 |
+
keys = list(outputs.keys()) if hasattr(outputs, "keys") else [
|
| 321 |
+
k for k in vars(outputs) if not k.startswith("_")
|
| 322 |
+
]
|
| 323 |
+
for k in keys:
|
| 324 |
+
kl = str(k).lower()
|
| 325 |
+
if "attn" not in kl and "attention" not in kl:
|
| 326 |
+
continue
|
| 327 |
+
val = getattr(outputs, k, None)
|
| 328 |
+
if val is None:
|
| 329 |
+
continue
|
| 330 |
+
items = val if isinstance(val, (tuple, list)) else [val]
|
| 331 |
+
for t in items:
|
| 332 |
+
add(t)
|
| 333 |
+
return found
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def normalize_attn_and_grad(
|
| 337 |
+
attn: torch.Tensor, grad: Optional[torch.Tensor], seq_len: int
|
| 338 |
+
) -> tuple[Optional[torch.Tensor], Optional[torch.Tensor]]:
|
| 339 |
+
"""Best-effort reshape of an arbitrarily-ordered attention tensor (and its
|
| 340 |
+
gradient, if present) into (heads, seq_len, seq_len). Handles models whose
|
| 341 |
+
attention weights aren't laid out as the conventional
|
| 342 |
+
(batch, heads, seq_q, seq_k) -- e.g. (batch, seq_q, seq_k, heads), grouped
|
| 343 |
+
query-attention variants, or single-head models with the head dim
|
| 344 |
+
squeezed out. Returns (None, None) if the shape can't be safely
|
| 345 |
+
disambiguated.
|
| 346 |
+
"""
|
| 347 |
+
if attn is None or attn.dim() < 2:
|
| 348 |
+
return None, None
|
| 349 |
+
shape = list(attn.shape)
|
| 350 |
+
seq_dims = [i for i, s in enumerate(shape) if s == seq_len]
|
| 351 |
+
if len(seq_dims) < 2:
|
| 352 |
+
return None, None # can't identify query/key dims with confidence
|
| 353 |
+
key_dim, query_dim = seq_dims[-1], seq_dims[-2]
|
| 354 |
+
other_dims = [i for i in range(attn.dim()) if i not in (query_dim, key_dim)]
|
| 355 |
+
batch_dim = next((i for i in other_dims if shape[i] == 1), other_dims[0] if other_dims else None)
|
| 356 |
+
head_dims = [i for i in other_dims if i != batch_dim]
|
| 357 |
+
perm = ([batch_dim] if batch_dim is not None else []) + head_dims + [query_dim, key_dim]
|
| 358 |
+
|
| 359 |
+
def _reshape(t: torch.Tensor) -> torch.Tensor:
|
| 360 |
+
tp = t.permute(*perm)
|
| 361 |
+
if batch_dim is not None:
|
| 362 |
+
tp = tp[0]
|
| 363 |
+
return tp.reshape(-1, seq_len, seq_len)
|
| 364 |
+
|
| 365 |
+
try:
|
| 366 |
+
attn_r = _reshape(attn)
|
| 367 |
+
grad_r = _reshape(grad) if grad is not None else None
|
| 368 |
+
except Exception:
|
| 369 |
+
return None, None
|
| 370 |
+
return attn_r, grad_r
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def compute_saliency_matrix(
|
| 374 |
+
grad_capable_attentions: list[torch.Tensor], seq_len: int
|
| 375 |
+
) -> tuple[np.ndarray, int, int]:
|
| 376 |
+
"""Sum_layers Sum_heads |A * dL/dA| -> (seq, seq) numpy matrix.
|
| 377 |
+
Returns (matrix, n_layers_used, n_layers_skipped)."""
|
| 378 |
saliency = torch.zeros((seq_len, seq_len), dtype=torch.float32)
|
| 379 |
+
used, skipped = 0, 0
|
| 380 |
+
for attn in grad_capable_attentions:
|
| 381 |
grad = attn.grad
|
| 382 |
if grad is None:
|
| 383 |
+
skipped += 1
|
| 384 |
+
continue
|
| 385 |
+
attn_n, grad_n = normalize_attn_and_grad(attn, grad, seq_len)
|
| 386 |
+
if attn_n is None or grad_n is None:
|
| 387 |
+
skipped += 1
|
| 388 |
continue
|
| 389 |
+
contrib = (attn_n.detach() * grad_n.detach()).abs().sum(dim=0) # (seq, seq)
|
| 390 |
+
saliency += contrib.to(dtype=torch.float32, device="cpu")
|
| 391 |
+
used += 1
|
| 392 |
+
return saliency.numpy(), used, skipped
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
# ---------------------------------------------------------------------------
|
| 396 |
+
# Per-item scoring
|
| 397 |
+
# ---------------------------------------------------------------------------
|
| 398 |
+
@dataclass
|
| 399 |
+
class ItemResult:
|
| 400 |
+
id: str
|
| 401 |
+
topic: str
|
| 402 |
+
difficulty: str
|
| 403 |
+
num_tokens: int
|
| 404 |
+
priority_score: float
|
| 405 |
+
linkage_score: Optional[float]
|
| 406 |
+
related_mean: float
|
| 407 |
+
unrelated_mean: float
|
| 408 |
+
skipped: bool = False
|
| 409 |
+
reason: str = ""
|
| 410 |
|
| 411 |
|
| 412 |
+
def _skip(item: dict, seq_len: int, reason: str) -> ItemResult:
|
| 413 |
+
return ItemResult(item["id"], item["topic"], item["difficulty"], seq_len, 0.0, None, 0.0, 0.0, True, reason)
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def run_item(
|
| 417 |
+
loaded: LoadedModel, item: dict, max_length: int, mask_ratio: float, rng: random.Random
|
| 418 |
+
) -> ItemResult:
|
| 419 |
tokenizer, model, model_type, device = (
|
| 420 |
loaded.tokenizer,
|
| 421 |
loaded.model,
|
|
|
|
| 427 |
question = item["question"]
|
| 428 |
full_text = f"{context} {question}"
|
| 429 |
|
| 430 |
+
offsets: Optional[list[tuple[int, int]]] = None
|
| 431 |
+
try:
|
| 432 |
+
enc = tokenizer(
|
| 433 |
+
full_text,
|
| 434 |
+
return_offsets_mapping=True,
|
| 435 |
+
return_tensors="pt",
|
| 436 |
+
truncation=True,
|
| 437 |
+
max_length=max_length,
|
| 438 |
+
)
|
| 439 |
+
offsets = enc.pop("offset_mapping")[0].tolist()
|
| 440 |
+
except Exception:
|
| 441 |
+
# Slow / custom tokenizer without fast-tokenizer offset support.
|
| 442 |
+
enc = tokenizer(full_text, return_tensors="pt", truncation=True, max_length=max_length)
|
| 443 |
+
|
| 444 |
input_ids = enc["input_ids"].to(device)
|
| 445 |
attention_mask = enc.get("attention_mask")
|
| 446 |
if attention_mask is not None:
|
| 447 |
attention_mask = attention_mask.to(device)
|
| 448 |
|
| 449 |
+
if offsets is None:
|
| 450 |
+
offsets = approx_offsets_from_slow_tokenizer(tokenizer, full_text, enc["input_ids"])
|
| 451 |
+
|
| 452 |
seq_len = input_ids.shape[1]
|
| 453 |
if seq_len < 4:
|
| 454 |
+
return _skip(item, seq_len, "too_short")
|
| 455 |
|
| 456 |
model.zero_grad(set_to_none=True)
|
| 457 |
|
| 458 |
+
prefer_fields: tuple[str, ...] = ()
|
| 459 |
+
try:
|
| 460 |
+
if model_type == "causal":
|
| 461 |
+
outputs = model(
|
| 462 |
+
input_ids=input_ids, attention_mask=attention_mask, labels=input_ids, output_attentions=True
|
| 463 |
+
)
|
| 464 |
+
loss = outputs.loss
|
| 465 |
+
elif model_type == "seq2seq":
|
| 466 |
+
outputs = model(
|
| 467 |
+
input_ids=input_ids, attention_mask=attention_mask, labels=input_ids, output_attentions=True
|
| 468 |
+
)
|
| 469 |
+
loss = outputs.loss
|
| 470 |
+
# Segments describe the *input* context, so score encoder self-attention.
|
| 471 |
+
prefer_fields = ("encoder_attentions",)
|
| 472 |
+
else: # mlm
|
| 473 |
+
mask_token_id = tokenizer.mask_token_id
|
| 474 |
+
if mask_token_id is None:
|
| 475 |
+
return _skip(item, seq_len, "no_mask_token")
|
| 476 |
+
maskable = [i for i, (s, e) in enumerate(offsets) if not (s == 0 and e == 0)]
|
| 477 |
+
if not maskable:
|
| 478 |
+
return _skip(item, seq_len, "no_maskable_tokens")
|
| 479 |
+
n_mask = max(1, int(len(maskable) * mask_ratio))
|
| 480 |
+
masked_positions = rng.sample(maskable, min(n_mask, len(maskable)))
|
| 481 |
+
masked_input_ids = input_ids.clone()
|
| 482 |
+
labels = torch.full_like(input_ids, -100)
|
| 483 |
+
for pos in masked_positions:
|
| 484 |
+
labels[0, pos] = input_ids[0, pos]
|
| 485 |
+
masked_input_ids[0, pos] = mask_token_id
|
| 486 |
+
outputs = model(
|
| 487 |
+
input_ids=masked_input_ids, attention_mask=attention_mask, labels=labels, output_attentions=True
|
| 488 |
+
)
|
| 489 |
+
loss = outputs.loss
|
| 490 |
+
except Exception as e: # noqa: BLE001 - never crash the whole run on one item
|
| 491 |
+
return _skip(item, seq_len, f"forward_error:{type(e).__name__}:{e}")
|
| 492 |
|
| 493 |
if loss is None or not torch.isfinite(loss):
|
| 494 |
+
return _skip(item, seq_len, "bad_loss")
|
| 495 |
+
|
| 496 |
+
raw_attentions = extract_raw_attentions(outputs, prefer_fields=prefer_fields)
|
| 497 |
+
if not raw_attentions:
|
| 498 |
+
return _skip(item, seq_len, "no_attentions_returned")
|
| 499 |
|
| 500 |
+
grad_capable: list[torch.Tensor] = []
|
| 501 |
+
for attn in raw_attentions:
|
| 502 |
+
if torch.is_tensor(attn) and attn.requires_grad:
|
| 503 |
+
try:
|
| 504 |
+
attn.retain_grad()
|
| 505 |
+
grad_capable.append(attn)
|
| 506 |
+
except Exception:
|
| 507 |
+
pass
|
| 508 |
+
|
| 509 |
+
if not grad_capable:
|
| 510 |
+
# Architecture computed attentions but they're detached / non-differentiable
|
| 511 |
+
# w.r.t. the loss (common with some fused / custom kernels).
|
| 512 |
+
return _skip(item, seq_len, "attentions_not_differentiable")
|
| 513 |
+
|
| 514 |
+
try:
|
| 515 |
+
loss.backward()
|
| 516 |
+
except Exception as e: # noqa: BLE001
|
| 517 |
+
return _skip(item, seq_len, f"backward_error:{type(e).__name__}:{e}")
|
| 518 |
|
| 519 |
+
saliency, n_used, n_skipped_layers = compute_saliency_matrix(grad_capable, seq_len)
|
| 520 |
+
if n_used == 0 or saliency.sum() <= 0:
|
| 521 |
+
return _skip(item, seq_len, "zero_saliency")
|
| 522 |
|
|
|
|
| 523 |
token_importance = saliency.sum(axis=0) # per key-token, summed over queries
|
| 524 |
|
| 525 |
segments = item["segments"]
|
|
|
|
| 535 |
unrelated_tokens = sorted({t for sid in unrelated_ids for t in seg_token_idxs.get(sid, [])})
|
| 536 |
|
| 537 |
if not related_tokens or not unrelated_tokens:
|
| 538 |
+
return _skip(item, seq_len, "empty_segment_tokens")
|
| 539 |
|
| 540 |
related_mean = float(token_importance[related_tokens].mean())
|
| 541 |
unrelated_mean = float(token_importance[unrelated_tokens].mean())
|
| 542 |
priority_score = 100.0 * related_mean / (related_mean + unrelated_mean + EPS)
|
| 543 |
|
|
|
|
|
|
|
|
|
|
| 544 |
pair_scores = []
|
| 545 |
for a, b in item.get("keyLinkPairs", []):
|
| 546 |
idx_a = seg_token_idxs.get(a, [])
|
|
|
|
| 570 |
)
|
| 571 |
|
| 572 |
|
| 573 |
+
# ---------------------------------------------------------------------------
|
| 574 |
+
# Hub submission (.eval_results/*.yaml PR)
|
| 575 |
+
# ---------------------------------------------------------------------------
|
| 576 |
+
def submit_to_hub(
|
| 577 |
+
summary: dict,
|
| 578 |
+
model_repo: str,
|
| 579 |
+
dataset_id: str,
|
| 580 |
+
task_id: str,
|
| 581 |
+
notes: Optional[str],
|
| 582 |
+
create_pr: bool,
|
| 583 |
+
revision: Optional[str],
|
| 584 |
+
source_url: str,
|
| 585 |
+
) -> None:
|
| 586 |
+
try:
|
| 587 |
+
from huggingface_hub import HfApi
|
| 588 |
+
import yaml
|
| 589 |
+
except ImportError as e:
|
| 590 |
+
raise RuntimeError(
|
| 591 |
+
"Submitting to the Hub requires `huggingface_hub` and `pyyaml`. "
|
| 592 |
+
"Install with: pip install huggingface_hub pyyaml"
|
| 593 |
+
) from e
|
| 594 |
+
|
| 595 |
+
entry = [
|
| 596 |
+
{
|
| 597 |
+
"dataset": {"id": dataset_id, "task_id": task_id},
|
| 598 |
+
"value": round(float(summary["gciScore"]), 3),
|
| 599 |
+
"date": summary["date"],
|
| 600 |
+
"source": {
|
| 601 |
+
"url": source_url,
|
| 602 |
+
"name": "GCI-Bench harness",
|
| 603 |
+
},
|
| 604 |
+
"notes": notes
|
| 605 |
+
or (
|
| 606 |
+
f"priorityScore={summary['priorityScore']}, "
|
| 607 |
+
f"linkageScore={summary['linkageScore']}, "
|
| 608 |
+
f"n={summary['numQuestions']}, skipped={summary['numSkipped']}"
|
| 609 |
+
),
|
| 610 |
+
}
|
| 611 |
+
]
|
| 612 |
+
yaml_str = yaml.safe_dump(entry, sort_keys=False)
|
| 613 |
+
|
| 614 |
+
api = HfApi()
|
| 615 |
+
result = api.upload_file(
|
| 616 |
+
path_or_fileobj=yaml_str.encode("utf-8"),
|
| 617 |
+
path_in_repo=".eval_results/gci-bench.yaml",
|
| 618 |
+
repo_id=model_repo,
|
| 619 |
+
repo_type="model",
|
| 620 |
+
revision=revision,
|
| 621 |
+
create_pr=create_pr,
|
| 622 |
+
commit_message="Add GCI-Bench evaluation result",
|
| 623 |
+
)
|
| 624 |
+
print(f"\nSubmitted to Hub: {result}")
|
| 625 |
+
|
| 626 |
+
|
| 627 |
# ---------------------------------------------------------------------------
|
| 628 |
# Main
|
| 629 |
# ---------------------------------------------------------------------------
|
|
|
|
| 631 |
parser = argparse.ArgumentParser(description="GCI-Bench harness for small HuggingFace transformers.")
|
| 632 |
parser.add_argument("--model", required=True, help="HuggingFace model id or local path (should be <=~100M params).")
|
| 633 |
parser.add_argument("--dataset", default=DEFAULT_DATASET, help="Path or URL to gci-bench .parquet or .jsonl.")
|
| 634 |
+
parser.add_argument("--limit", type=int, default=500, help="Number of questions to sample (0 = all).")
|
| 635 |
parser.add_argument("--topic", default=None, help="Only evaluate a single topic id (e.g. 'cooking').")
|
| 636 |
parser.add_argument("--max-length", type=int, default=256, help="Max token length per item.")
|
| 637 |
parser.add_argument("--mask-ratio", type=float, default=0.15, help="Mask ratio used for MLM-style models.")
|
| 638 |
parser.add_argument("--seed", type=int, default=42)
|
| 639 |
parser.add_argument("--device", default=None, help="cpu | cuda | mps (default: auto-detect).")
|
| 640 |
+
parser.add_argument(
|
| 641 |
+
"--attn-implementation",
|
| 642 |
+
default="eager,auto",
|
| 643 |
+
help="Comma-separated list of attn_implementation values to try, in order. "
|
| 644 |
+
"'auto' means 'let the library decide' (no kwarg passed). Default: 'eager,auto'.",
|
| 645 |
+
)
|
| 646 |
+
parser.add_argument("--dtype", default=None, help="e.g. float32, float16, bfloat16 (default: model default).")
|
| 647 |
+
parser.add_argument("--trust-remote-code", action="store_true", help="Force trust_remote_code=True.")
|
| 648 |
+
parser.add_argument("--revision", default=None, help="Model revision (branch/tag/commit) to load.")
|
| 649 |
parser.add_argument("--output", default=None, help="Where to write the full JSON results.")
|
| 650 |
+
parser.add_argument("--hub-model-repo", default=None, help="Model repo id to submit results to, e.g. 'org/model-name'.")
|
| 651 |
+
parser.add_argument("--dataset-id", default=None, help="Registered GCI-Bench Benchmark dataset id, e.g. 'your-org/gci-bench'.")
|
| 652 |
+
parser.add_argument("--task-id", default="default", help="Task id within the benchmark's eval.yaml.")
|
| 653 |
+
parser.add_argument("--source-url", default="https://github.com/YOUR_ORG/gci-bench", help="Link attached to the submitted result.")
|
| 654 |
+
parser.add_argument("--no-create-pr", action="store_true", help="Push directly instead of opening a PR (requires write access).")
|
| 655 |
+
parser.add_argument("--notes", default=None, help="Free-text note to attach to a Hub submission.")
|
| 656 |
args = parser.parse_args()
|
| 657 |
|
| 658 |
random.seed(args.seed)
|
|
|
|
| 669 |
else:
|
| 670 |
device = torch.device("cpu")
|
| 671 |
|
| 672 |
+
attn_candidates: list[Optional[str]] = [
|
| 673 |
+
None if tok.strip().lower() == "auto" else tok.strip()
|
| 674 |
+
for tok in args.attn_implementation.split(",")
|
| 675 |
+
if tok.strip()
|
| 676 |
+
] or DEFAULT_ATTN_CANDIDATES
|
| 677 |
+
|
| 678 |
print(f"Loading dataset from {args.dataset} ...")
|
| 679 |
items = load_dataset(args.dataset)
|
| 680 |
if args.topic:
|
| 681 |
items = [it for it in items if it["topic"] == args.topic]
|
| 682 |
print(f"Loaded {len(items)} items.")
|
| 683 |
|
| 684 |
+
if args.limit and 0 < args.limit < len(items):
|
| 685 |
items = rng.sample(items, args.limit)
|
| 686 |
print(f"Evaluating {len(items)} items.")
|
| 687 |
|
| 688 |
+
print(f"Loading model '{args.model}' on {device} (attn candidates: {attn_candidates}) ...")
|
| 689 |
+
loaded = load_model(
|
| 690 |
+
args.model,
|
| 691 |
+
device,
|
| 692 |
+
attn_candidates,
|
| 693 |
+
dtype=args.dtype,
|
| 694 |
+
trust_remote_code=args.trust_remote_code,
|
| 695 |
+
revision=args.revision,
|
| 696 |
+
)
|
| 697 |
+
print(
|
| 698 |
+
f"Model type: {loaded.model_type} | Params: {loaded.num_params:,} | "
|
| 699 |
+
f"Resolved attn_implementation: {loaded.attn_implementation} | "
|
| 700 |
+
f"Fast tokenizer: {loaded.fast_tokenizer}"
|
| 701 |
+
)
|
| 702 |
if loaded.num_params > 100_000_000:
|
| 703 |
print(
|
| 704 |
f"WARNING: model has {loaded.num_params/1e6:.1f}M parameters, which is above the "
|
| 705 |
"intended <=100M range for GCI-Bench. Results are still computed, but keep this in mind."
|
| 706 |
)
|
| 707 |
+
if loaded.attn_implementation not in ("eager",):
|
| 708 |
+
print(
|
| 709 |
+
f"NOTE: resolved attn_implementation is '{loaded.attn_implementation}', not 'eager'. "
|
| 710 |
+
"If this architecture doesn't return real (differentiable) attention weights under "
|
| 711 |
+
"this implementation, most/all items will be skipped with reason "
|
| 712 |
+
"'no_attentions_returned' or 'attentions_not_differentiable'."
|
| 713 |
+
)
|
| 714 |
|
| 715 |
results: list[ItemResult] = []
|
| 716 |
for item in tqdm(items, desc="Scoring"):
|
| 717 |
try:
|
| 718 |
res = run_item(loaded, item, args.max_length, args.mask_ratio, rng)
|
| 719 |
except Exception as e: # noqa: BLE001 - keep going on isolated failures
|
| 720 |
+
res = _skip(item, 0, f"error:{type(e).__name__}:{e}")
|
| 721 |
results.append(res)
|
| 722 |
|
| 723 |
valid = [r for r in results if not r.skipped]
|
| 724 |
skipped = len(results) - len(valid)
|
| 725 |
+
|
| 726 |
+
if skipped:
|
| 727 |
+
reason_counts: dict[str, int] = {}
|
| 728 |
+
for r in results:
|
| 729 |
+
if r.skipped:
|
| 730 |
+
key = r.reason.split(":")[0]
|
| 731 |
+
reason_counts[key] = reason_counts.get(key, 0) + 1
|
| 732 |
+
print(f"\n{skipped}/{len(results)} items skipped. Breakdown: {json.dumps(reason_counts, indent=2)}")
|
| 733 |
+
if reason_counts.get("attentions_not_differentiable", 0) + reason_counts.get("no_attentions_returned", 0) > len(results) * 0.5:
|
| 734 |
+
print(
|
| 735 |
+
"WARNING: this model/architecture appears to not expose differentiable attention "
|
| 736 |
+
"weights under any tried attn_implementation. This is an issue of "
|
| 737 |
+
"some fused/flash-attention-only custom kernels, not a bug in this harness. "
|
| 738 |
+
"GCI-Bench cannot meaningfully score this model. Please open a community discussion."
|
| 739 |
+
)
|
| 740 |
+
|
| 741 |
if not valid:
|
| 742 |
print("No valid items were scored. Aborting.")
|
| 743 |
sys.exit(1)
|
|
|
|
| 761 |
"modelName": args.model,
|
| 762 |
"numParams": int(loaded.num_params),
|
| 763 |
"modelType": loaded.model_type,
|
| 764 |
+
"attnImplementation": loaded.attn_implementation,
|
| 765 |
"numQuestions": len(valid),
|
| 766 |
"numSkipped": skipped,
|
| 767 |
"priorityScore": round(priority_score, 3),
|
|
|
|
| 769 |
"gciScore": round(gci_score, 3),
|
| 770 |
"priorityByTopic": by_topic_avg,
|
| 771 |
"priorityByDifficulty": by_difficulty_avg,
|
| 772 |
+
"date": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
| 773 |
"notes": args.notes,
|
| 774 |
}
|
| 775 |
|
| 776 |
print("\n=== GCI-Bench summary ===")
|
| 777 |
+
print(json.dumps({k: v for k, v in summary.items() if k != "priorityByTopic"}, indent=2))
|
| 778 |
|
| 779 |
full_output = {
|
| 780 |
"summary": summary,
|
|
|
|
| 786 |
json.dump(full_output, f, indent=2)
|
| 787 |
print(f"\nWrote full results to {args.output}")
|
| 788 |
|
| 789 |
+
if args.hub_model_repo:
|
| 790 |
+
if not args.dataset_id:
|
| 791 |
+
print("\nSkipping Hub submission: --dataset-id is required (the registered GCI-Bench Benchmark dataset id).")
|
| 792 |
+
else:
|
| 793 |
+
try:
|
| 794 |
+
submit_to_hub(
|
| 795 |
+
summary,
|
| 796 |
+
model_repo=args.hub_model_repo,
|
| 797 |
+
dataset_id=args.dataset_id,
|
| 798 |
+
task_id=args.task_id,
|
| 799 |
+
notes=args.notes,
|
| 800 |
+
create_pr=not args.no_create_pr,
|
| 801 |
+
revision=None,
|
| 802 |
+
source_url=args.source_url,
|
| 803 |
+
)
|
| 804 |
+
except Exception as e: # noqa: BLE001
|
| 805 |
+
print(f"\nFailed to submit to Hub: {e}")
|
| 806 |
|
| 807 |
|
| 808 |
if __name__ == "__main__":
|
| 809 |
+
main()
|