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ab50eae
 
 
 
 
 
 
 
 
 
 
ea6cb4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab50eae
 
 
ea6cb4e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
#!/usr/bin/env python3
"""
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  # noqa: F401  (kept for parity / potential future use)
import pyarrow.parquet as pq
import torch

try:
    from tqdm import tqdm
except ImportError:  # pragma: no cover - tqdm is a soft dependency
    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"),
]

# 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
# ---------------------------------------------------------------------------
@dataclass
class 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
# ---------------------------------------------------------------------------
@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:
        # 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()