| |
| """ |
| GCI-Bench harness (robust build) |
| ================================= |
| Measures whether a small (1M-100M parameter) HuggingFace transformer's |
| attention * gradient saliency prioritizes causally-relevant ("related") |
| sentences over same-domain "distractor" sentences mixed into the same |
| context, and whether it links causally-connected sentences together. |
| |
| This benchmark does NOT grade answer correctness. It only inspects internal |
| attention/gradient dynamics. |
| |
| Design goals for this build: |
| * Works across CausalLM / MaskedLM / Seq2SeqLM architectures. |
| * Tries multiple attn_implementation values and falls back gracefully when |
| a custom architecture hard-errors on sdpa/flash_attention_2 (many do). |
| * Extracts attention tensors generically -- not just from `.attentions` -- |
| so custom/trust_remote_code architectures with nonstandard output field |
| names still work if they expose *some* attention-shaped tensor. |
| * Normalizes arbitrary attention tensor dim orderings (batch/heads/seq_q/ |
| seq_k in any order) instead of assuming a fixed layout. |
| * Falls back to an approximate char-offset reconstruction for tokenizers |
| that don't support `return_offsets_mapping` (some custom/slow |
| tokenizers). |
| * Never crashes the whole run on a single bad item/layer -- everything |
| that can fail is caught and turned into a clearly-labeled skip reason. |
| |
| Hard limitation that CANNOT be worked around: architectures whose attention |
| is computed purely inside a fused, non-differentiable-wrt-weights kernel |
| (e.g. some flash-attention-only custom code that never returns/retains |
| attention *weights* as a tensor with a grad_fn) cannot be introspected by |
| this technique at all. Those items/models will be skipped with reason |
| "attentions_not_differentiable" or "no_attentions_returned". |
| |
| Usage: |
| python evaluation_harness.py --model roneneldan/TinyStories-33M --limit 500 |
| python evaluation_harness.py --model prajjwal1/bert-tiny --limit 300 |
| python evaluation_harness.py --model distilgpt2 --limit 1000 \ |
| --hub-model-repo distilbert/distilgpt2 --dataset-id your-org/gci-bench |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import datetime |
| import json |
| import os |
| import random |
| import sys |
| import urllib.request |
| from dataclasses import dataclass |
| from typing import Any, Optional |
|
|
| import numpy as np |
| import pandas as pd |
| import pyarrow.parquet as pq |
| import torch |
|
|
| try: |
| from tqdm import tqdm |
| except ImportError: |
| def tqdm(iterable, **kwargs): |
| return iterable |
|
|
| from transformers import ( |
| AutoModelForCausalLM, |
| AutoModelForMaskedLM, |
| AutoModelForSeq2SeqLM, |
| AutoTokenizer, |
| ) |
|
|
| EPS = 1e-8 |
| SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) |
| DEFAULT_DATASET = os.path.join(SCRIPT_DIR, "data", "test-00000-of-00001.parquet") |
|
|
| MODEL_CLASSES: list[tuple[Any, str]] = [ |
| (AutoModelForCausalLM, "causal"), |
| (AutoModelForMaskedLM, "mlm"), |
| (AutoModelForSeq2SeqLM, "seq2seq"), |
| ] |
|
|
| |
| |
| |
| |
| DEFAULT_ATTN_CANDIDATES: list[Optional[str]] = ["eager", None] |
|
|
|
|
| |
| |
| |
| def load_dataset(path: str) -> list[dict]: |
| if path.startswith("http://") or path.startswith("https://"): |
| with urllib.request.urlopen(path) as resp: |
| text = resp.read().decode("utf-8") |
| if path.endswith(".jsonl"): |
| return [json.loads(line) for line in text.splitlines() if line.strip()] |
| return json.loads(text) |
|
|
| if path.endswith(".parquet"): |
| table = pq.read_table(path) |
| df = table.to_pandas() |
| items = [] |
| for _, row in df.iterrows(): |
| item = row.to_dict() |
| for key in ("segments", "relatedSegmentIds", "unrelatedSegmentIds", "keyLinkPairs", "meta"): |
| if isinstance(item.get(key), str): |
| item[key] = json.loads(item[key]) |
| items.append(item) |
| return items |
|
|
| with open(path, "r", encoding="utf-8") as f: |
| return [json.loads(line) for line in f if line.strip()] |
|
|
|
|
| |
| |
| |
| @dataclass |
| class LoadedModel: |
| tokenizer: Any |
| model: Any |
| model_type: str |
| num_params: int |
| device: torch.device |
| attn_implementation: str |
| is_encoder_decoder: bool |
| fast_tokenizer: bool |
|
|
|
|
| def _try_force_eager_post_load(model: Any) -> None: |
| """Best-effort: force a loaded model into eager attention mode even if |
| from_pretrained's attn_implementation kwarg was ignored (this happens |
| with some trust_remote_code custom architectures).""" |
| set_fn = getattr(model, "set_attn_implementation", None) |
| if callable(set_fn): |
| try: |
| set_fn("eager") |
| return |
| except Exception: |
| pass |
|
|
| cfg = getattr(model, "config", None) |
| if cfg is None: |
| return |
| for attr in ("_attn_implementation", "attn_implementation"): |
| try: |
| setattr(cfg, attr, "eager") |
| except Exception: |
| pass |
| |
| for sub_name in getattr(cfg, "sub_configs", {}) or {}: |
| sub_cfg = getattr(cfg, sub_name, None) |
| if sub_cfg is not None: |
| try: |
| setattr(sub_cfg, "_attn_implementation", "eager") |
| except Exception: |
| pass |
| try: |
| cfg.output_attentions = True |
| except Exception: |
| pass |
|
|
|
|
| def load_model( |
| model_name: str, |
| device: torch.device, |
| attn_candidates: list[Optional[str]], |
| dtype: Optional[str] = None, |
| trust_remote_code: bool = False, |
| revision: Optional[str] = None, |
| ) -> LoadedModel: |
| trust_kwargs = {"trust_remote_code": True} if trust_remote_code else {} |
| rev_kwargs = {"revision": revision} if revision else {} |
|
|
| fast_tokenizer = True |
| try: |
| tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True, **trust_kwargs, **rev_kwargs) |
| except Exception: |
| tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False, **trust_kwargs, **rev_kwargs) |
| fast_tokenizer = False |
| if not getattr(tokenizer, "is_fast", False): |
| fast_tokenizer = False |
|
|
| if tokenizer.pad_token is None: |
| if tokenizer.eos_token is not None: |
| tokenizer.pad_token = tokenizer.eos_token |
| else: |
| tokenizer.add_special_tokens({"pad_token": "[PAD]"}) |
|
|
| torch_dtype = getattr(torch, dtype, None) if dtype else None |
|
|
| last_error: Optional[Exception] = None |
| for model_cls, model_type in MODEL_CLASSES: |
| for attn_impl in attn_candidates: |
| kwargs: dict[str, Any] = dict(trust_kwargs) |
| kwargs.update(rev_kwargs) |
| if torch_dtype is not None: |
| kwargs["torch_dtype"] = torch_dtype |
| if attn_impl is not None: |
| kwargs["attn_implementation"] = attn_impl |
| try: |
| model = model_cls.from_pretrained(model_name, **kwargs) |
| except TypeError: |
| |
| kwargs.pop("attn_implementation", None) |
| try: |
| model = model_cls.from_pretrained(model_name, **kwargs) |
| except Exception as e: |
| last_error = e |
| continue |
| except ValueError as e: |
| |
| |
| last_error = e |
| continue |
| except Exception as e: |
| last_error = e |
| continue |
|
|
| _try_force_eager_post_load(model) |
| model.to(device) |
| model.eval() |
| num_params = sum(p.numel() for p in model.parameters()) |
| resolved_impl = str(getattr(model.config, "_attn_implementation", attn_impl or "unknown")) |
| is_enc_dec = bool(getattr(model.config, "is_encoder_decoder", model_type == "seq2seq")) |
| return LoadedModel( |
| tokenizer=tokenizer, |
| model=model, |
| model_type=model_type, |
| num_params=num_params, |
| device=device, |
| attn_implementation=resolved_impl, |
| is_encoder_decoder=is_enc_dec, |
| fast_tokenizer=fast_tokenizer, |
| ) |
|
|
| if not trust_remote_code and last_error and "trust_remote_code" in str(last_error).lower(): |
| return load_model(model_name, device, attn_candidates, dtype, True, revision) |
|
|
| raise RuntimeError( |
| f"Could not load '{model_name}' as CausalLM / MaskedLM / Seq2SeqLM with any of " |
| f"attn_implementation in {attn_candidates}: {last_error}" |
| ) |
|
|
|
|
| |
| |
| |
| def char_span_to_token_indices(offsets: list[tuple[int, int]], char_start: int, char_end: int) -> list[int]: |
| idxs = [] |
| for i, (s, e) in enumerate(offsets): |
| if s == 0 and e == 0: |
| continue |
| if s < char_end and e > char_start: |
| idxs.append(i) |
| return idxs |
|
|
|
|
| def approx_offsets_from_slow_tokenizer( |
| tokenizer: Any, text: str, input_ids: torch.Tensor |
| ) -> list[tuple[int, int]]: |
| """Best-effort char-offset reconstruction for tokenizers that don't |
| support `return_offsets_mapping` (slow / custom tokenizers). Walks |
| through the decoded pieces and locates them in `text` sequentially. |
| This is approximate -- it can misalign on tokenizers with heavy |
| normalization (e.g. lowercasing, accent stripping) -- but degrades |
| gracefully to a (0, 0) "unknown span" per unmatched token rather than |
| crashing. |
| """ |
| offsets: list[tuple[int, int]] = [] |
| cursor = 0 |
| special_ids = set(getattr(tokenizer, "all_special_ids", []) or []) |
| for tok_id in input_ids[0].tolist(): |
| if tok_id in special_ids: |
| offsets.append((0, 0)) |
| continue |
| piece = tokenizer.decode([tok_id], skip_special_tokens=False, clean_up_tokenization_spaces=False) |
| stripped = piece.strip() |
| if not stripped: |
| offsets.append((0, 0)) |
| continue |
| pos = text.find(stripped, cursor) |
| if pos == -1: |
| pos = text.find(stripped) |
| if pos == -1: |
| offsets.append((0, 0)) |
| continue |
| start, end = pos, pos + len(stripped) |
| offsets.append((start, end)) |
| cursor = end |
| return offsets |
|
|
|
|
| |
| |
| |
| def extract_raw_attentions(outputs: Any, prefer_fields: tuple[str, ...] = ()) -> list[torch.Tensor]: |
| """Pull every self-attention weight tensor out of a HF ModelOutput, |
| regardless of model family / custom architecture field naming.""" |
| found: list[torch.Tensor] = [] |
| seen_ids: set[int] = set() |
|
|
| def add(t: Any) -> None: |
| if torch.is_tensor(t) and id(t) not in seen_ids: |
| seen_ids.add(id(t)) |
| found.append(t) |
|
|
| ordered_fields = tuple(prefer_fields) + ("attentions", "decoder_attentions", "encoder_attentions", "cross_attentions") |
| for field_name in ordered_fields: |
| val = getattr(outputs, field_name, None) |
| if val: |
| for t in val: |
| add(t) |
| if found: |
| return found |
|
|
| |
| |
| keys = list(outputs.keys()) if hasattr(outputs, "keys") else [ |
| k for k in vars(outputs) if not k.startswith("_") |
| ] |
| for k in keys: |
| kl = str(k).lower() |
| if "attn" not in kl and "attention" not in kl: |
| continue |
| val = getattr(outputs, k, None) |
| if val is None: |
| continue |
| items = val if isinstance(val, (tuple, list)) else [val] |
| for t in items: |
| add(t) |
| return found |
|
|
|
|
| def normalize_attn_and_grad( |
| attn: torch.Tensor, grad: Optional[torch.Tensor], seq_len: int |
| ) -> tuple[Optional[torch.Tensor], Optional[torch.Tensor]]: |
| """Best-effort reshape of an arbitrarily-ordered attention tensor (and its |
| gradient, if present) into (heads, seq_len, seq_len). Handles models whose |
| attention weights aren't laid out as the conventional |
| (batch, heads, seq_q, seq_k) -- e.g. (batch, seq_q, seq_k, heads), grouped |
| query-attention variants, or single-head models with the head dim |
| squeezed out. Returns (None, None) if the shape can't be safely |
| disambiguated. |
| """ |
| if attn is None or attn.dim() < 2: |
| return None, None |
| shape = list(attn.shape) |
| seq_dims = [i for i, s in enumerate(shape) if s == seq_len] |
| if len(seq_dims) < 2: |
| return None, None |
| key_dim, query_dim = seq_dims[-1], seq_dims[-2] |
| other_dims = [i for i in range(attn.dim()) if i not in (query_dim, key_dim)] |
| batch_dim = next((i for i in other_dims if shape[i] == 1), other_dims[0] if other_dims else None) |
| head_dims = [i for i in other_dims if i != batch_dim] |
| perm = ([batch_dim] if batch_dim is not None else []) + head_dims + [query_dim, key_dim] |
|
|
| def _reshape(t: torch.Tensor) -> torch.Tensor: |
| tp = t.permute(*perm) |
| if batch_dim is not None: |
| tp = tp[0] |
| return tp.reshape(-1, seq_len, seq_len) |
|
|
| try: |
| attn_r = _reshape(attn) |
| grad_r = _reshape(grad) if grad is not None else None |
| except Exception: |
| return None, None |
| return attn_r, grad_r |
|
|
|
|
| def compute_saliency_matrix( |
| grad_capable_attentions: list[torch.Tensor], seq_len: int |
| ) -> tuple[np.ndarray, int, int]: |
| """Sum_layers Sum_heads |A * dL/dA| -> (seq, seq) numpy matrix. |
| Returns (matrix, n_layers_used, n_layers_skipped).""" |
| saliency = torch.zeros((seq_len, seq_len), dtype=torch.float32) |
| used, skipped = 0, 0 |
| for attn in grad_capable_attentions: |
| grad = attn.grad |
| if grad is None: |
| skipped += 1 |
| continue |
| attn_n, grad_n = normalize_attn_and_grad(attn, grad, seq_len) |
| if attn_n is None or grad_n is None: |
| skipped += 1 |
| continue |
| contrib = (attn_n.detach() * grad_n.detach()).abs().sum(dim=0) |
| saliency += contrib.to(dtype=torch.float32, device="cpu") |
| used += 1 |
| return saliency.numpy(), used, skipped |
|
|
|
|
| |
| |
| |
| @dataclass |
| class ItemResult: |
| id: str |
| topic: str |
| difficulty: str |
| num_tokens: int |
| priority_score: float |
| linkage_score: Optional[float] |
| related_mean: float |
| unrelated_mean: float |
| skipped: bool = False |
| reason: str = "" |
|
|
|
|
| def _skip(item: dict, seq_len: int, reason: str) -> ItemResult: |
| return ItemResult(item["id"], item["topic"], item["difficulty"], seq_len, 0.0, None, 0.0, 0.0, True, reason) |
|
|
|
|
| def run_item( |
| loaded: LoadedModel, item: dict, max_length: int, mask_ratio: float, rng: random.Random |
| ) -> ItemResult: |
| tokenizer, model, model_type, device = ( |
| loaded.tokenizer, |
| loaded.model, |
| loaded.model_type, |
| loaded.device, |
| ) |
|
|
| context = item["context"] |
| question = item["question"] |
| full_text = f"{context} {question}" |
|
|
| offsets: Optional[list[tuple[int, int]]] = None |
| try: |
| enc = tokenizer( |
| full_text, |
| return_offsets_mapping=True, |
| return_tensors="pt", |
| truncation=True, |
| max_length=max_length, |
| ) |
| offsets = enc.pop("offset_mapping")[0].tolist() |
| except Exception: |
| |
| enc = tokenizer(full_text, return_tensors="pt", truncation=True, max_length=max_length) |
|
|
| input_ids = enc["input_ids"].to(device) |
| attention_mask = enc.get("attention_mask") |
| if attention_mask is not None: |
| attention_mask = attention_mask.to(device) |
|
|
| if offsets is None: |
| offsets = approx_offsets_from_slow_tokenizer(tokenizer, full_text, enc["input_ids"]) |
|
|
| seq_len = input_ids.shape[1] |
| if seq_len < 4: |
| return _skip(item, seq_len, "too_short") |
|
|
| model.zero_grad(set_to_none=True) |
|
|
| prefer_fields: tuple[str, ...] = () |
| try: |
| if model_type == "causal": |
| outputs = model( |
| input_ids=input_ids, attention_mask=attention_mask, labels=input_ids, output_attentions=True |
| ) |
| loss = outputs.loss |
| elif model_type == "seq2seq": |
| outputs = model( |
| input_ids=input_ids, attention_mask=attention_mask, labels=input_ids, output_attentions=True |
| ) |
| loss = outputs.loss |
| |
| prefer_fields = ("encoder_attentions",) |
| else: |
| mask_token_id = tokenizer.mask_token_id |
| if mask_token_id is None: |
| return _skip(item, seq_len, "no_mask_token") |
| maskable = [i for i, (s, e) in enumerate(offsets) if not (s == 0 and e == 0)] |
| if not maskable: |
| return _skip(item, seq_len, "no_maskable_tokens") |
| n_mask = max(1, int(len(maskable) * mask_ratio)) |
| masked_positions = rng.sample(maskable, min(n_mask, len(maskable))) |
| masked_input_ids = input_ids.clone() |
| labels = torch.full_like(input_ids, -100) |
| for pos in masked_positions: |
| labels[0, pos] = input_ids[0, pos] |
| masked_input_ids[0, pos] = mask_token_id |
| outputs = model( |
| input_ids=masked_input_ids, attention_mask=attention_mask, labels=labels, output_attentions=True |
| ) |
| loss = outputs.loss |
| except Exception as e: |
| return _skip(item, seq_len, f"forward_error:{type(e).__name__}:{e}") |
|
|
| if loss is None or not torch.isfinite(loss): |
| return _skip(item, seq_len, "bad_loss") |
|
|
| raw_attentions = extract_raw_attentions(outputs, prefer_fields=prefer_fields) |
| if not raw_attentions: |
| return _skip(item, seq_len, "no_attentions_returned") |
|
|
| grad_capable: list[torch.Tensor] = [] |
| for attn in raw_attentions: |
| if torch.is_tensor(attn) and attn.requires_grad: |
| try: |
| attn.retain_grad() |
| grad_capable.append(attn) |
| except Exception: |
| pass |
|
|
| if not grad_capable: |
| |
| |
| return _skip(item, seq_len, "attentions_not_differentiable") |
|
|
| try: |
| loss.backward() |
| except Exception as e: |
| return _skip(item, seq_len, f"backward_error:{type(e).__name__}:{e}") |
|
|
| saliency, n_used, n_skipped_layers = compute_saliency_matrix(grad_capable, seq_len) |
| if n_used == 0 or saliency.sum() <= 0: |
| return _skip(item, seq_len, "zero_saliency") |
|
|
| token_importance = saliency.sum(axis=0) |
|
|
| segments = item["segments"] |
| seg_token_idxs: dict[int, list[int]] = {} |
| for seg in segments: |
| idxs = char_span_to_token_indices(offsets, seg["charStart"], seg["charEnd"]) |
| seg_token_idxs[seg["id"]] = idxs |
|
|
| related_ids = item["relatedSegmentIds"] |
| unrelated_ids = item["unrelatedSegmentIds"] |
|
|
| related_tokens = sorted({t for sid in related_ids for t in seg_token_idxs.get(sid, [])}) |
| unrelated_tokens = sorted({t for sid in unrelated_ids for t in seg_token_idxs.get(sid, [])}) |
|
|
| if not related_tokens or not unrelated_tokens: |
| return _skip(item, seq_len, "empty_segment_tokens") |
|
|
| related_mean = float(token_importance[related_tokens].mean()) |
| unrelated_mean = float(token_importance[unrelated_tokens].mean()) |
| priority_score = 100.0 * related_mean / (related_mean + unrelated_mean + EPS) |
|
|
| pair_scores = [] |
| for a, b in item.get("keyLinkPairs", []): |
| idx_a = seg_token_idxs.get(a, []) |
| idx_b = seg_token_idxs.get(b, []) |
| if not idx_a or not idx_b: |
| continue |
| pair_mass = ( |
| saliency[np.ix_(idx_a, idx_b)].sum() + saliency[np.ix_(idx_b, idx_a)].sum() |
| ) / (len(idx_a) * len(idx_b) * 2) |
| combined = sorted(set(idx_a) | set(idx_b)) |
| control_mass = saliency[np.ix_(combined, unrelated_tokens)].sum() / ( |
| len(combined) * len(unrelated_tokens) + EPS |
| ) |
| pair_scores.append(100.0 * pair_mass / (pair_mass + control_mass + EPS)) |
|
|
| linkage_score = float(np.mean(pair_scores)) if pair_scores else None |
|
|
| return ItemResult( |
| id=item["id"], |
| topic=item["topic"], |
| difficulty=item["difficulty"], |
| num_tokens=seq_len, |
| priority_score=priority_score, |
| linkage_score=linkage_score, |
| related_mean=related_mean, |
| unrelated_mean=unrelated_mean, |
| ) |
|
|
|
|
| |
| |
| |
| def submit_to_hub( |
| summary: dict, |
| model_repo: str, |
| dataset_id: str, |
| task_id: str, |
| notes: Optional[str], |
| create_pr: bool, |
| revision: Optional[str], |
| source_url: str, |
| ) -> None: |
| try: |
| from huggingface_hub import HfApi |
| import yaml |
| except ImportError as e: |
| raise RuntimeError( |
| "Submitting to the Hub requires `huggingface_hub` and `pyyaml`. " |
| "Install with: pip install huggingface_hub pyyaml" |
| ) from e |
|
|
| entry = [ |
| { |
| "dataset": {"id": dataset_id, "task_id": task_id}, |
| "value": round(float(summary["gciScore"]), 3), |
| "date": summary["date"], |
| "source": { |
| "url": source_url, |
| "name": "GCI-Bench harness", |
| }, |
| "notes": notes |
| or ( |
| f"priorityScore={summary['priorityScore']}, " |
| f"linkageScore={summary['linkageScore']}, " |
| f"n={summary['numQuestions']}, skipped={summary['numSkipped']}" |
| ), |
| } |
| ] |
| yaml_str = yaml.safe_dump(entry, sort_keys=False) |
|
|
| api = HfApi() |
| result = api.upload_file( |
| path_or_fileobj=yaml_str.encode("utf-8"), |
| path_in_repo=".eval_results/gci-bench.yaml", |
| repo_id=model_repo, |
| repo_type="model", |
| revision=revision, |
| create_pr=create_pr, |
| commit_message="Add GCI-Bench evaluation result", |
| ) |
| print(f"\nSubmitted to Hub: {result}") |
|
|
|
|
| |
| |
| |
| def main(): |
| parser = argparse.ArgumentParser(description="GCI-Bench harness for small HuggingFace transformers.") |
| parser.add_argument("--model", required=True, help="HuggingFace model id or local path (should be <=~100M params).") |
| parser.add_argument("--dataset", default=DEFAULT_DATASET, help="Path or URL to gci-bench .parquet or .jsonl.") |
| parser.add_argument("--limit", type=int, default=500, help="Number of questions to sample (0 = all).") |
| parser.add_argument("--topic", default=None, help="Only evaluate a single topic id (e.g. 'cooking').") |
| parser.add_argument("--max-length", type=int, default=256, help="Max token length per item.") |
| parser.add_argument("--mask-ratio", type=float, default=0.15, help="Mask ratio used for MLM-style models.") |
| parser.add_argument("--seed", type=int, default=42) |
| parser.add_argument("--device", default=None, help="cpu | cuda | mps (default: auto-detect).") |
| parser.add_argument( |
| "--attn-implementation", |
| default="eager,auto", |
| help="Comma-separated list of attn_implementation values to try, in order. " |
| "'auto' means 'let the library decide' (no kwarg passed). Default: 'eager,auto'.", |
| ) |
| parser.add_argument("--dtype", default=None, help="e.g. float32, float16, bfloat16 (default: model default).") |
| parser.add_argument("--trust-remote-code", action="store_true", help="Force trust_remote_code=True.") |
| parser.add_argument("--revision", default=None, help="Model revision (branch/tag/commit) to load.") |
| parser.add_argument("--output", default=None, help="Where to write the full JSON results.") |
| parser.add_argument("--hub-model-repo", default=None, help="Model repo id to submit results to, e.g. 'org/model-name'.") |
| parser.add_argument("--dataset-id", default=None, help="Registered GCI-Bench Benchmark dataset id, e.g. 'your-org/gci-bench'.") |
| parser.add_argument("--task-id", default="default", help="Task id within the benchmark's eval.yaml.") |
| parser.add_argument("--source-url", default="https://github.com/YOUR_ORG/gci-bench", help="Link attached to the submitted result.") |
| parser.add_argument("--no-create-pr", action="store_true", help="Push directly instead of opening a PR (requires write access).") |
| parser.add_argument("--notes", default=None, help="Free-text note to attach to a Hub submission.") |
| args = parser.parse_args() |
|
|
| random.seed(args.seed) |
| np.random.seed(args.seed) |
| torch.manual_seed(args.seed) |
| rng = random.Random(args.seed) |
|
|
| if args.device: |
| device = torch.device(args.device) |
| elif torch.cuda.is_available(): |
| device = torch.device("cuda") |
| elif getattr(torch.backends, "mps", None) is not None and torch.backends.mps.is_available(): |
| device = torch.device("mps") |
| else: |
| device = torch.device("cpu") |
|
|
| attn_candidates: list[Optional[str]] = [ |
| None if tok.strip().lower() == "auto" else tok.strip() |
| for tok in args.attn_implementation.split(",") |
| if tok.strip() |
| ] or DEFAULT_ATTN_CANDIDATES |
|
|
| print(f"Loading dataset from {args.dataset} ...") |
| items = load_dataset(args.dataset) |
| if args.topic: |
| items = [it for it in items if it["topic"] == args.topic] |
| print(f"Loaded {len(items)} items.") |
|
|
| if args.limit and 0 < args.limit < len(items): |
| items = rng.sample(items, args.limit) |
| print(f"Evaluating {len(items)} items.") |
|
|
| print(f"Loading model '{args.model}' on {device} (attn candidates: {attn_candidates}) ...") |
| loaded = load_model( |
| args.model, |
| device, |
| attn_candidates, |
| dtype=args.dtype, |
| trust_remote_code=args.trust_remote_code, |
| revision=args.revision, |
| ) |
| print( |
| f"Model type: {loaded.model_type} | Params: {loaded.num_params:,} | " |
| f"Resolved attn_implementation: {loaded.attn_implementation} | " |
| f"Fast tokenizer: {loaded.fast_tokenizer}" |
| ) |
| if loaded.num_params > 100_000_000: |
| print( |
| f"WARNING: model has {loaded.num_params/1e6:.1f}M parameters, which is above the " |
| "intended <=100M range for GCI-Bench. Results are still computed, but keep this in mind." |
| ) |
| if loaded.attn_implementation not in ("eager",): |
| print( |
| f"NOTE: resolved attn_implementation is '{loaded.attn_implementation}', not 'eager'. " |
| "If this architecture doesn't return real (differentiable) attention weights under " |
| "this implementation, most/all items will be skipped with reason " |
| "'no_attentions_returned' or 'attentions_not_differentiable'." |
| ) |
|
|
| results: list[ItemResult] = [] |
| for item in tqdm(items, desc="Scoring"): |
| try: |
| res = run_item(loaded, item, args.max_length, args.mask_ratio, rng) |
| except Exception as e: |
| res = _skip(item, 0, f"error:{type(e).__name__}:{e}") |
| results.append(res) |
|
|
| valid = [r for r in results if not r.skipped] |
| skipped = len(results) - len(valid) |
|
|
| if skipped: |
| reason_counts: dict[str, int] = {} |
| for r in results: |
| if r.skipped: |
| key = r.reason.split(":")[0] |
| reason_counts[key] = reason_counts.get(key, 0) + 1 |
| print(f"\n{skipped}/{len(results)} items skipped. Breakdown: {json.dumps(reason_counts, indent=2)}") |
| if reason_counts.get("attentions_not_differentiable", 0) + reason_counts.get("no_attentions_returned", 0) > len(results) * 0.5: |
| print( |
| "WARNING: this model/architecture appears to not expose differentiable attention " |
| "weights under any tried attn_implementation. This is an issue of " |
| "some fused/flash-attention-only custom kernels, not a bug in this harness. " |
| "GCI-Bench cannot meaningfully score this model. Please open a community discussion." |
| ) |
|
|
| if not valid: |
| print("No valid items were scored. Aborting.") |
| sys.exit(1) |
|
|
| priority_score = float(np.mean([r.priority_score for r in valid])) |
| linkage_values = [r.linkage_score for r in valid if r.linkage_score is not None] |
| linkage_score = float(np.mean(linkage_values)) if linkage_values else 50.0 |
| gci_score = (priority_score + linkage_score) / 2.0 |
|
|
| by_topic: dict[str, list[float]] = {} |
| for r in valid: |
| by_topic.setdefault(r.topic, []).append(r.priority_score) |
| by_topic_avg = {k: float(np.mean(v)) for k, v in by_topic.items()} |
|
|
| by_difficulty: dict[str, list[float]] = {} |
| for r in valid: |
| by_difficulty.setdefault(r.difficulty, []).append(r.priority_score) |
| by_difficulty_avg = {k: float(np.mean(v)) for k, v in by_difficulty.items()} |
|
|
| summary = { |
| "modelName": args.model, |
| "numParams": int(loaded.num_params), |
| "modelType": loaded.model_type, |
| "attnImplementation": loaded.attn_implementation, |
| "numQuestions": len(valid), |
| "numSkipped": skipped, |
| "priorityScore": round(priority_score, 3), |
| "linkageScore": round(linkage_score, 3), |
| "gciScore": round(gci_score, 3), |
| "priorityByTopic": by_topic_avg, |
| "priorityByDifficulty": by_difficulty_avg, |
| "date": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), |
| "notes": args.notes, |
| } |
|
|
| print("\n=== GCI-Bench summary ===") |
| print(json.dumps({k: v for k, v in summary.items() if k != "priorityByTopic"}, indent=2)) |
|
|
| full_output = { |
| "summary": summary, |
| "items": [r.__dict__ for r in results], |
| } |
|
|
| if args.output: |
| with open(args.output, "w", encoding="utf-8") as f: |
| json.dump(full_output, f, indent=2) |
| print(f"\nWrote full results to {args.output}") |
|
|
| if args.hub_model_repo: |
| if not args.dataset_id: |
| print("\nSkipping Hub submission: --dataset-id is required (the registered GCI-Bench Benchmark dataset id).") |
| else: |
| try: |
| submit_to_hub( |
| summary, |
| model_repo=args.hub_model_repo, |
| dataset_id=args.dataset_id, |
| task_id=args.task_id, |
| notes=args.notes, |
| create_pr=not args.no_create_pr, |
| revision=None, |
| source_url=args.source_url, |
| ) |
| except Exception as e: |
| print(f"\nFailed to submit to Hub: {e}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |