Upload 7 files
Browse filesFiles changed (7)
- README.md+119-1
- dataset_infos.jsonAdded+32
- eval.yaml.txtAdded+13
- evaluation_harness.pyAdded+809
- gitattributes.txtAdded+60
- leaderboard.jsonAdded+68
- package.jsonAdded+11
123---license: apache-2.0---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121---language:- enlicense: gpl-3.0pretty_name: GCI-Bench (Glint Clarity Index Bench)task_categories:- text-generation- question-answeringtags:- benchmark- evaluation- context-based- attention---# GCI-Bench: Glint Clarity Index Benchmark## Gradient × Attention Context Importance BenchmarkGCI-Bench is a **5,000-item diagnostic benchmark** designed to measure whether a small language model (1M–100M parameters) uses its **attention × gradient interactions** to prioritize relevant context over distractors.Unlike standard NLP benchmarks, GCI-Bench does **not evaluate answer correctness**. Instead, it analyzes the model’s internal dynamics while it processes the prompt. Specifically, it measures how strongly gradients flow through attention connections tied to causally relevant parts of the input. No reference answer is required for scoring.The goal is to evaluate *how* a model distributes importance across context—not whether it produces the right output.---### Note> Enderchef, the creator of this dataset, has left the org. Permission to this benchmark is given with this credit line: https://huggingface.co/Enderchef## ScoringEach item produces two independent metrics:| Score | Range | What it measures ||-------|--------|-----------------|| **Priority Score** | 0–100 (50 = neutral) | Whether the model assigns more gradient-weighted attention to relevant segments than to distractors || **Linkage Score** | 0–100 (50 = neutral) | Whether the model strengthens attention between causally linked sentence pairs compared to related→distractor pairs || **GCI Score** | 0–100 | Mean of Priority and Linkage |Both metrics are **self-normalized**. Each item contains a balanced 50/50 split of related and unrelated segments, and scores are averaged per token. A model with no systematic preference will converge to ~50 by construction.Scores above 50 indicate structured prioritization. Scores below 50 indicate inverse or noisy allocation.---## Dataset Structure### Item Fields| Field | Type | Description ||--------|------|-------------|| `id` | string | Unique ID (`gci-00001`–`gci-05000`) || `topic` | string | Topic category ID (e.g., `cooking`, `astronomy`) || `topicLabel` | string | Human-readable topic || `templateId` | string | Causal template (`A`–`F`) || `difficulty` | string | `easy` (2 pairs), `medium` (3 pairs), `hard` (4 pairs) || `question` | string | Question about the causal chain || `referenceAnswer` | string | Ground-truth answer (not used for scoring) || `context` | string | Full paragraph with related and distractor segments (shuffled) || `segments` | list | Segment annotations with character offsets and labels || `relatedSegmentIds` | list | IDs of causally relevant segments || `unrelatedSegmentIds` | list | IDs of distractor segments || `keyLinkPairs` | list | Segment ID pairs representing causal links || `meta` | object | Structured fields: subject, driver, mechanism, outcome, threshold, unit |---## Topics (20 Domains)agriculture, archaeology, architecture, astronomy, automotive, aviation, chemistry,cooking, energy, finance, gardening, hardware, marine, music, photography,physiology, sports, textiles, weather, wildlife---## Causal TemplatesSix structured templates (A–F) generate reasoning chains:- Threshold-based change- Comparative experiments- Cumulative exposure- Sudden spike events- Threshold-crossing dynamics- Feedback loopsThese templates enforce consistent causal structure across domains while allowing content variation.---## Evaluation HarnessThe reference evaluation script (`evaluation_harness.py`) supports HuggingFace transformer models that return `output_attentions`.The harness:1. Runs the model in language modeling mode2. Computes standard LM loss3. Backpropagates gradients through attention matrices4. Computes attention × gradient attribution5. Aggregates token-level values into segment-level scores6. Produces Priority, Linkage, and final GCI scoresExample usage:```bash# Evaluate TinyStories-33M on 500 random items(for personal benchmarking)python evaluation_harness.py --model roneneldan/TinyStories-33M --limit 500# Evaluate on the full 5,000-item set(for the full benchmark)python evaluation_harness.py --model roneneldan/TinyStories-8M --limit 0```Some architectures may require minor adjustments to expose attention tensors correctly.---## LicenseGPL 3.0 - see LICENSE
1234567891011121314151617181920212223242526272829303132{ "default": { "description": "GCI-Bench (Glint Clarity Index Bench): a 5,000-item diagnostic benchmark measuring whether small language models (1M\u2013100M parameters) use attention \u00d7 gradient interactions to prioritize relevant context over distractors.", "citation": "", "homepage": "", "license": "MIT", "features": { "id": {"dtype": "string", "_type": "Value"}, "topic": {"dtype": "string", "_type": "Value"}, "topicLabel": {"dtype": "string", "_type": "Value"}, "templateId": {"dtype": "string", "_type": "Value"}, "difficulty": {"dtype": "string", "_type": "Value"}, "question": {"dtype": "string", "_type": "Value"}, "referenceAnswer": {"dtype": "string", "_type": "Value"}, "context": {"dtype": "string", "_type": "Value"}, "segments": {"dtype": "string", "_type": "Value"}, "relatedSegmentIds": {"dtype": "string", "_type": "Value"}, "unrelatedSegmentIds": {"dtype": "string", "_type": "Value"}, "keyLinkPairs": {"dtype": "string", "_type": "Value"}, "meta": {"dtype": "string", "_type": "Value"} }, "splits": { "test": { "name": "test", "num_bytes": 2147483, "num_examples": 5000, "dataset_name": "gci-bench" } }, "version": "1.0.0" }}12345678910111213name: "GCI-Bench"description: >- Glint Clarity Index Bench: measures whether small language models (1M-100M parameters) allocate attention*gradient saliency toward causally-relevant sentences over same-domain distractors, via a white-box internals probe rather than answer-correctness grading.evaluation_framework: "custom"tasks: - id: "gci_bench" config: "default" split: "test" metric: "gciScore" reference_implementation: "https://huggingface.co/datasets/Glint-Research/GCI_Bench/blob/main/evaluation_harness.py"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809#!/usr/bin/env python3"""GCI-Bench harness (robust build)=================================Measures whether a small (1M-100M parameter) HuggingFace transformer'sattention * gradient saliency prioritizes causally-relevant ("related")sentences over same-domain "distractor" sentences mixed into the samecontext, and whether it links causally-connected sentences together.
This benchmark does NOT grade answer correctness. It only inspects internalattention/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 attentionis computed purely inside a fused, non-differentiable-wrt-weights kernel(e.g. some flash-attention-only custom code that never returns/retainsattention *weights* as a tensor with a grad_fn) cannot be introspected bythis 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 argparseimport datetimeimport jsonimport osimport randomimport sysimport urllib.requestfrom dataclasses import dataclassfrom typing import Any, Optional
import numpy as npimport pandas as pd # noqa: F401 (kept for parity / potential future use)import pyarrow.parquet as pqimport torch
try: from tqdm import tqdmexcept ImportError: # pragma: no cover - tqdm is a soft dependency def tqdm(iterable, **kwargs): return iterable
from transformers import ( AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForSeq2SeqLM, AutoTokenizer,)
EPS = 1e-8SCRIPT_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"),]
# Tried in order. `None` means "don't pass attn_implementation at all, let# the library/custom code decide" -- necessary because some architectures# error out on an explicit "eager" string too (rare, but happens with some# trust_remote_code models that only recognize their own custom names).DEFAULT_ATTN_CANDIDATES: list[Optional[str]] = ["eager", None]
# ---------------------------------------------------------------------------# Data loading# ---------------------------------------------------------------------------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()]
# ---------------------------------------------------------------------------# Model loading -- robust to custom architectures / custom attention kernels# ---------------------------------------------------------------------------@dataclassclass LoadedModel: tokenizer: Any model: Any model_type: str # "causal" | "mlm" | "seq2seq" 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 # Multimodal / composite configs (per-backbone attn implementations). 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: # Older transformers / architecture doesn't accept this kwarg at all. kwargs.pop("attn_implementation", None) try: model = model_cls.from_pretrained(model_name, **kwargs) except Exception as e: # noqa: BLE001 last_error = e continue except ValueError as e: # e.g. "<Arch> does not support an attention implementation # through torch.nn.functional.scaled_dot_product_attention yet." last_error = e continue except Exception as e: # noqa: BLE001 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}" )
# ---------------------------------------------------------------------------# Offset mapping (with fallback for slow / custom tokenizers)# ---------------------------------------------------------------------------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 # special token 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
# ---------------------------------------------------------------------------# Generic attention extraction + shape normalization# ---------------------------------------------------------------------------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
# Generic fallback: scan every output field whose name mentions attention, # for custom architectures using nonstandard field names. 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 # can't identify query/key dims with confidence 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) # (seq, seq) saliency += contrib.to(dtype=torch.float32, device="cpu") used += 1 return saliency.numpy(), used, skipped
# ---------------------------------------------------------------------------# Per-item scoring# ---------------------------------------------------------------------------@dataclassclass 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: # Slow / custom tokenizer without fast-tokenizer offset support. 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 # Segments describe the *input* context, so score encoder self-attention. prefer_fields = ("encoder_attentions",) else: # mlm 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: # noqa: BLE001 - never crash the whole run on one item 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: # Architecture computed attentions but they're detached / non-differentiable # w.r.t. the loss (common with some fused / custom kernels). return _skip(item, seq_len, "attentions_not_differentiable")
try: loss.backward() except Exception as e: # noqa: BLE001 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) # per key-token, summed over queries
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, )
# ---------------------------------------------------------------------------# Hub submission (.eval_results/*.yaml PR)# ---------------------------------------------------------------------------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}")
# ---------------------------------------------------------------------------# Main# ---------------------------------------------------------------------------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: # noqa: BLE001 - keep going on isolated failures 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: # noqa: BLE001 print(f"\nFailed to submit to Hub: {e}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.avro filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.lz4 filter=lfs diff=lfs merge=lfs -text*.mds filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text# Audio files - uncompressed*.pcm filter=lfs diff=lfs merge=lfs -text*.sam filter=lfs diff=lfs merge=lfs -text*.raw filter=lfs diff=lfs merge=lfs -text# Audio files - compressed*.aac filter=lfs diff=lfs merge=lfs -text*.flac filter=lfs diff=lfs merge=lfs -text*.mp3 filter=lfs diff=lfs merge=lfs -text*.ogg filter=lfs diff=lfs merge=lfs -text*.wav filter=lfs diff=lfs merge=lfs -text# Image files - uncompressed*.bmp filter=lfs diff=lfs merge=lfs -text*.gif filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.tiff filter=lfs diff=lfs merge=lfs -text# Image files - compressed*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.webp filter=lfs diff=lfs merge=lfs -text# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -text1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768{
"benchmark": "GCI-Bench",
"dataset": "data/test-00000-of-00001.parquet",
"results": [
{
"modelName": "Glint-Research/Glint-1.3",
"numParams": 985344,
"modelType": "causal",
"status": "ok",
"numQuestions": 95,
"numSkipped": 5,
"priorityScore": 47.223,
"linkageScore": 52.426,
"gciScore": 49.824
},
{
"modelName": "Glint-Research/Glint-2",
"numParams": 1512385,
"modelType": "causal",
"status": "ok",
"numQuestions": 100,
"numSkipped": 0,
"priorityScore": 50.501,
"linkageScore": 50.246,
"gciScore": 50.374
},
{
"modelName": "AxiomicLabs/GPT-S-5M",
"numParams": 5158464,
"modelType": "causal",
"status": "ok",
"numQuestions": 100,
"numSkipped": 0,
"priorityScore": 50.535,
"linkageScore": 43.408,
"gciScore": 46.971
},
{
"modelName": "AxiomicLabs/GPT-X2-125M",
"numParams": 125081664,
"modelType": "causal",
"status": "ok",
"numQuestions": 100,
"numSkipped": 0,
"priorityScore": 51.7,
"linkageScore": 56.85,
"gciScore": 54.275
},
{
"modelName": "SupraLabs/Supra-50M-Instruct",
"numParams": 51786240,
"modelType": "causal",
"status": "ok",
"numQuestions": 100,
"numSkipped": 0,
"priorityScore": 53.045,
"linkageScore": 54.019,
"gciScore": 53.532
}
],
"ranking": [
"AxiomicLabs/GPT-X2-125M",
"SupraLabs/Supra-50M-Instruct",
"Glint-Research/Glint-2",
"Glint-Research/Glint-1.3",
"AxiomicLabs/GPT-S-5M"
]
}1234567891011{ "name": "gci-bench", "version": "1.0.0", "private": true, "description": "GCI-Bench: Gradient × attention Context Importance Benchmark", "type": "module", "scripts": { "generate": "node scripts/generate-dataset.mjs" }, "license": "MIT"}README.md+119-1
dataset_infos.jsonAdded+32
eval.yaml.txtAdded+13
evaluation_harness.pyAdded+809
gitattributes.txtAdded+60
leaderboard.jsonAdded+68
package.jsonAdded+11