File size: 24,284 Bytes
265457a
6029afb
 
 
 
 
265457a
 
98d7957
265457a
98d7957
265457a
 
 
 
 
 
 
 
 
d7c7fe4
 
265457a
 
 
 
 
98d7957
 
265457a
 
 
98d7957
265457a
 
 
6029afb
 
 
 
 
 
265457a
98d7957
265457a
6029afb
 
 
265457a
 
98d7957
dc3851d
98d7957
 
265457a
 
98d7957
 
 
dc3851d
98d7957
 
d7c7fe4
98d7957
 
 
 
 
 
 
d7c7fe4
6029afb
 
d7c7fe4
 
 
 
 
98d7957
 
 
265457a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98d7957
 
265457a
 
 
 
 
98d7957
265457a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f497d8b
 
 
265457a
f497d8b
 
 
265457a
 
 
f497d8b
265457a
98d7957
 
 
 
f497d8b
265457a
 
 
 
98d7957
f497d8b
265457a
 
98d7957
f497d8b
265457a
98d7957
 
 
265457a
 
f497d8b
265457a
 
98d7957
265457a
d7c7fe4
 
 
 
98d7957
 
 
 
 
 
 
 
 
 
 
 
 
265457a
 
 
98d7957
265457a
 
98d7957
 
265457a
 
98d7957
 
265457a
 
 
 
 
 
 
 
98d7957
265457a
f497d8b
 
 
 
 
 
 
 
 
 
 
 
265457a
f497d8b
 
 
 
 
98d7957
f497d8b
 
 
7ee8fe0
265457a
 
 
7ee8fe0
265457a
 
7ee8fe0
 
265457a
7ee8fe0
 
 
265457a
 
f497d8b
265457a
 
 
 
 
7ee8fe0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265457a
 
98d7957
265457a
 
 
 
 
 
98d7957
265457a
 
98d7957
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265457a
98d7957
 
 
 
 
265457a
98d7957
 
 
265457a
 
 
 
98d7957
 
 
265457a
 
98d7957
265457a
98d7957
265457a
 
98d7957
230be05
 
 
 
265457a
230be05
98d7957
265457a
 
 
98d7957
 
265457a
 
 
98d7957
 
265457a
98d7957
 
 
 
 
265457a
 
98d7957
 
 
 
 
 
 
7ee8fe0
 
 
 
 
 
 
 
 
 
 
 
98d7957
 
 
 
265457a
 
 
98d7957
 
 
 
 
 
 
 
 
265457a
98d7957
 
265457a
 
 
98d7957
265457a
 
98d7957
265457a
98d7957
 
265457a
 
 
 
98d7957
 
265457a
98d7957
 
265457a
98d7957
265457a
 
 
 
 
 
 
98d7957
 
 
 
 
 
 
 
 
265457a
 
 
98d7957
 
 
 
265457a
 
98d7957
265457a
 
98d7957
 
 
 
265457a
 
 
98d7957
265457a
 
98d7957
 
 
265457a
98d7957
 
 
265457a
98d7957
265457a
 
98d7957
 
 
 
 
 
265457a
 
 
98d7957
265457a
 
98d7957
 
265457a
98d7957
265457a
98d7957
 
 
 
 
 
 
 
 
265457a
 
98d7957
 
 
265457a
98d7957
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
# ================================================================
#  GomParam-v1 Evaluation Suite – v4.1 (Kaggle / Colab Crash-Safe)
#  12 mainstream models, aggressive VRAM and Disk management.
#
#  ▶ IF ON KAGGLE/COLAB, RUN THIS FIRST IN A SEPARATE CELL:
#  !pip -q install -U bitsandbytes accelerate transformers sentencepiece safetensors huggingface_hub
# ================================================================

import json, os, gc, time, math, logging, sys
from pathlib import Path
from typing import Optional

import torch
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import seaborn as sns
from tabulate import tabulate
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForCausalLM, PreTrainedTokenizerFast, BitsAndBytesConfig
import shutil
from huggingface_hub import hf_hub_download, login

logging.basicConfig(level=logging.INFO, format="%(asctime)s  %(levelname)s  %(message)s")
log = logging.getLogger("gomparam")

# ── CONFIG ─────────────────────────────────────────────────────
HF_TOKEN = os.getenv("HF_TOKEN", "")
if HF_TOKEN:
    login(token=HF_TOKEN)
else:
    log.warning("No HF_TOKEN found. Gated models (Gemma, Llama) will fail. Set HF_TOKEN.")

DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
DTYPE  = torch.float16 if DEVICE == "cuda" else torch.float32

# Kaggle / Colab path logic
IS_KAGGLE = Path("/kaggle/working").exists()
BASE_DIR = Path("/kaggle/working") if IS_KAGGLE else Path("/content")

OUTPUT_DIR = BASE_DIR / "gomparam_results"
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
CHECKPOINT_FILE = OUTPUT_DIR / "checkpoint.json"

# Route HF Cache to the larger working directory to avoid disk OOM
os.environ["HF_HOME"] = str(BASE_DIR / "hf_cache")

print(f"Device : {DEVICE}")
if DEVICE == "cuda":
    gpu_name = torch.cuda.get_device_name(0)
    gpu_vram = torch.cuda.get_device_properties(0).total_memory / 1e9
    print(f"GPU    : {gpu_name}")
    print(f"VRAM   : {gpu_vram:.1f} GB")


# ── VRAM Safety ────────────────────────────────────────────────
def vram_gb_free():
    if DEVICE != "cuda": return 999.0
    return (torch.cuda.get_device_properties(0).total_memory - torch.cuda.memory_allocated()) / 1e9

def nuke_gpu():
    """Aggressively free all GPU memory between models and clear disk cache."""
    gc.collect()
    if DEVICE == "cuda":
        torch.cuda.empty_cache()
        torch.cuda.ipc_collect()
        gc.collect()
        torch.cuda.empty_cache()
        time.sleep(2)  # let CUDA reclaim memory
    
    # Clear HuggingFace cache to prevent disk OOM (Kaggle only has 19GB)
    hf_cache = Path(os.environ.get("HF_HOME", os.path.expanduser("~/.cache/huggingface/hub")))
    if hf_cache.exists():
        shutil.rmtree(hf_cache, ignore_errors=True)
        hf_cache.mkdir(parents=True, exist_ok=True)
        
    log.info(f"  Cleanup done. Free VRAM: {vram_gb_free():.1f} GB")


# ── Helper ─────────────────────────────────────────────────────
def safe_str(*args, default=""):
    for v in args:
        if v is not None and str(v).strip():
            return str(v)
    return default


# ── 1. Load all 21 GomParam-v1 modules ────────────────────────
DATASET_REPO = "omdeep22/GomParam-v1"
ALL_MODULES = [
    "cloze","code_switching","coherence","coreference","cross_scripting",
    "cultural_grounding","dialect","entailment","homograph_disambiguation",
    "idioms_proverbs","kinship","medical","mixed_general","morphology",
    "numerical_reasoning","para_qa","perplexity","pragmatics",
    "register_discrimination","sentiment","spatio_temporal",
]

print("Loading GomParam-v1 modules...")
modules = {}
for m in ALL_MODULES:
    try:
        ds = load_dataset(DATASET_REPO, m, split="train", trust_remote_code=False,
                          token=True if HF_TOKEN else None)
        modules[m] = ds
        print(f"  ✓ {m:35s} {len(ds):>4} items")
    except Exception as e:
        print(f"  ✗ {m:35s} FAILED: {e}")

print(f"\nLoaded {len(modules)}/{len(ALL_MODULES)} modules, {sum(len(v) for v in modules.values())} total items")


# ── 2. Schema normalisers (None-safe) ─────────────────────────
def normalise_mcq(item: dict, module: str) -> Optional[dict]:
    item = dict(item)
    candidates = item.get("candidates", [])
    correct    = item.get("correct", -1)
    if not candidates or correct == -1 or len(candidates) < 2:
        return None
    if all(not str(c).strip() for c in candidates):
        return None
    try:
        correct = int(correct)
    except (ValueError, TypeError):
        return None
    if correct < 0 or correct >= len(candidates):
        return None

    if module == "cloze":
        sentence = safe_str(item.get("sentence"), item.get("context"))
        if "___" in sentence:
            prefix = sentence.split("___")[0]
            suffix = sentence.split("___")[1] if len(sentence.split("___")) > 1 else ""
            cands = [str(c).strip() + suffix for c in candidates]
        else:
            prefix = sentence
            cands = [" " + str(c) for c in candidates]
        return {"prefix": prefix, "candidates": cands, "correct": correct}

    if module == "morphology":
        stem = safe_str(item.get("context"), item.get("sentence"))
        return {"prefix": stem, "candidates": [" " + str(c) for c in candidates], "correct": correct}

    if module == "entailment":
        premise    = safe_str(item.get("premise"), item.get("context"))
        hypothesis = safe_str(item.get("hypothesis"), item.get("question"))
        prefix = "पूर्वनिश्चय: " + premise + "\nप्रस्ताव: " + hypothesis
        return {"prefix": prefix, "candidates": ["\n" + str(c) for c in candidates], "correct": correct}

    if module == "idioms_proverbs":
        konkani  = safe_str(item.get("konkani"), item.get("context"), item.get("sentence"))
        question = safe_str(item.get("question"), "ह्या म्हणींचो अर्थ कितें?")
        prefix = konkani + "\n" + question
        return {"prefix": prefix, "candidates": ["\n" + str(c) for c in candidates], "correct": correct}

    if module == "spatio_temporal":
        ctx = safe_str(item.get("context"), item.get("question"), item.get("sentence"))
        return {"prefix": ctx, "candidates": [" " + str(c) for c in candidates], "correct": correct}

    # Generic handler for all other modules
    ctx      = safe_str(item.get("context"), item.get("passage"), item.get("sentence"),
                        item.get("scenario"), item.get("romi"), item.get("sentence_a"))
    question = safe_str(item.get("question"))
    prefix   = ctx + ("\n" + question if question else "")
    return {"prefix": prefix, "candidates": ["\n" + str(c) for c in candidates], "correct": correct}


# ── 3. Model registry (12 mainstream models) ──────────────────
MODELS = [
    # ── Ungated Baselines (no access request needed) ─────────
    {"name":"Phi-2",               "repo":"microsoft/phi-2",                      "size":"2.7B", "type":"Multilingual Small",   "load_8bit":False},
    {"name":"TinyLlama-1.1B-Chat", "repo":"TinyLlama/TinyLlama-1.1B-Chat-v1.0",  "size":"1.1B", "type":"Multilingual Tiny",    "load_8bit":False},
    {"name":"Qwen2.5-3B",          "repo":"Qwen/Qwen2.5-3B",                     "size":"3B",   "type":"Multilingual Small",   "load_8bit":False},
    # ── Qwen Family ────────────────────────────────────────────
    {"name":"Qwen2.5-0.5B",        "repo":"Qwen/Qwen2.5-0.5B",                   "size":"0.5B", "type":"Multilingual Tiny",    "load_8bit":False},
    {"name":"Qwen2.5-1.5B",        "repo":"Qwen/Qwen2.5-1.5B",                   "size":"1.5B", "type":"Multilingual Small",   "load_8bit":False},
    {"name":"Qwen2.5-7B",          "repo":"Qwen/Qwen2.5-7B",                     "size":"7B",   "type":"Multilingual Base",    "load_8bit":True},
    {"name":"Qwen2.5-7B-Instruct", "repo":"Qwen/Qwen2.5-7B-Instruct",            "size":"7B",   "type":"Multilingual Chat",    "load_8bit":True},
    # ── Gemma Family ───────────────────────────────────────────
    {"name":"Gemma-2-2B-It",       "repo":"google/gemma-2-2b-it",                "size":"2B",   "type":"Multilingual Chat",    "load_8bit":False},
    {"name":"Gemma-2-9B-It",       "repo":"google/gemma-2-9b-it",                "size":"9B",   "type":"Multilingual Chat",    "load_8bit":True},
    # ── Indic / Multilingual ───────────────────────────────────
    {"name":"Sarvam-1",            "repo":"sarvamai/sarvam-1",                   "size":"2B",   "type":"Indic Specialist",     "load_8bit":False},
    {"name":"Aya-23-8B",           "repo":"CohereForAI/aya-23-8B",               "size":"8B",   "type":"Massive Multilingual", "load_8bit":True},
    # ── Mistral ────────────────────────────────────────────────
    {"name":"Mistral-7B-v0.3",     "repo":"mistralai/Mistral-7B-v0.3",           "size":"7B",   "type":"Multilingual Base",    "load_8bit":True},
]


# ── 4. Tokenizer loader ───────────────────────────────────────
def load_tokenizer(repo: str) -> AutoTokenizer:
    try:
        tok = AutoTokenizer.from_pretrained(repo, trust_remote_code=True, use_fast=True,
                                            token=True if HF_TOKEN else None)
    except Exception as e:
        if "TokenizersBackend" in str(e) or "does not exist" in str(e).lower():
            tok_json_path = hf_hub_download(repo_id=repo, filename="tokenizer.json",
                                            token=True if HF_TOKEN else None)
            tok = PreTrainedTokenizerFast(tokenizer_file=tok_json_path)
        else:
            raise e
    if tok.pad_token is None:
        tok.pad_token = tok.eos_token
    return tok


# ── 5. Scoring ─────────────────────────────────────────────────
@torch.no_grad()
def sequence_log_prob(model, tokenizer, prefix: str, candidate: str, max_len: int = 512) -> float:
    """Return the average per-token log probability of ONLY the candidate tokens.
    This eliminates repetition bias by mathematically ignoring the prefix/prompt."""
    # Tokenize the full sequence
    enc_full = tokenizer(prefix + candidate, return_tensors="pt", truncation=True, max_length=max_len).to(DEVICE)
    # Tokenize just the prefix to know how many tokens to ignore
    enc_prefix = tokenizer(prefix, return_tensors="pt", truncation=True, max_length=max_len)
    
    ids = enc_full["input_ids"]
    prefix_len = enc_prefix["input_ids"].shape[1]
    
    if ids.shape[1] == 0 or prefix_len >= ids.shape[1]:
        return -1e9
        
    labels = ids.clone()
    # Mask out the prefix tokens by setting their labels to -100
    labels[0, :prefix_len] = -100

    with torch.amp.autocast("cuda", enabled=(DEVICE == "cuda")):
        out = model(ids, labels=labels)
        
    # out.loss is now the mean cross-entropy of ONLY the candidate tokens
    return -float(out.loss.item())


def score_mcq(model, tokenizer, items, module: str) -> dict:
    """Score a module and track accuracy by difficulty level."""
    correct, total = 0, 0
    details = []
    # Track per-difficulty stats
    diff_stats = {}  # {"basic": {"correct": N, "total": N}, ...}
    for raw_item in items:
        raw_dict = dict(raw_item)
        difficulty = str(raw_dict.get("difficulty", "unknown")).lower().strip()
        norm = normalise_mcq(raw_dict, module)
        if norm is None:
            continue
        lps  = [sequence_log_prob(model, tokenizer, norm["prefix"], c) for c in norm["candidates"]]
        pred = int(np.argmax(lps))
        gold = norm["correct"]
        hit  = (pred == gold)
        correct += int(hit)
        total   += 1
        details.append({"gold": gold, "pred": pred, "correct": hit, "difficulty": difficulty})
        # Accumulate per-difficulty
        if difficulty not in diff_stats:
            diff_stats[difficulty] = {"correct": 0, "total": 0}
        diff_stats[difficulty]["total"] += 1
        diff_stats[difficulty]["correct"] += int(hit)
    # Compute per-difficulty accuracy
    diff_accuracy = {}
    for d, s in diff_stats.items():
        diff_accuracy[d] = {
            "accuracy": s["correct"] / s["total"] if s["total"] else 0.0,
            "correct": s["correct"],
            "total": s["total"]
        }
    return {
        "accuracy": correct / total if total else 0.0,
        "correct": correct, "total": total,
        "by_difficulty": diff_accuracy,
        "details": details
    }


# ── 6. Module weights ─────────────────────────────────────────
MODULE_WEIGHTS = {
    "morphology":0.15, "cloze":0.12, "para_qa":0.10, "idioms_proverbs":0.08,
    "pragmatics":0.08, "cultural_grounding":0.07, "homograph_disambiguation":0.07,
    "entailment":0.06, "coreference":0.06, "register_discrimination":0.05,
    "sentiment":0.04, "spatio_temporal":0.04, "kinship":0.04,
    "numerical_reasoning":0.03, "medical":0.03, "coherence":0.03,
    "cross_scripting":0.02, "code_switching":0.02, "dialect":0.02, "perplexity":0.02,
}
_total_w = sum(MODULE_WEIGHTS.values())
MODULE_WEIGHTS = {k: v / _total_w for k, v in MODULE_WEIGHTS.items()}
MCQ_MODULES = [m for m in MODULE_WEIGHTS if m in modules]


# ── 7. Checkpoint helpers ─────────────────────────────────────
def load_checkpoint() -> dict:
    if CHECKPOINT_FILE.exists():
        with open(CHECKPOINT_FILE) as f:
            log.info("Resuming from checkpoint...")
            return json.load(f)
    return {}

def save_checkpoint(results: dict):
    clean = {}
    for mn, r in results.items():
        clean[mn] = {k: ({kk: vv for kk, vv in v.items() if kk != "details"}
                         if isinstance(v, dict) else v) for k, v in r.items()}
    with open(CHECKPOINT_FILE, "w") as f:
        json.dump(clean, f, ensure_ascii=False, indent=2)


# ── 8. Main evaluation loop (crash-safe) ──────────────────────
all_results = load_checkpoint()
completed_models = {k for k, v in all_results.items() if "_error" not in v}

for i, model_cfg in enumerate(MODELS):
    mname = model_cfg["name"]
    repo  = model_cfg["repo"]
    use_8bit = model_cfg["load_8bit"]

    if mname in completed_models:
        log.info(f"SKIP {mname} (already in checkpoint)")
        continue

    print(f"\n{'='*70}")
    print(f"  [{i+1}/{len(MODELS)}] {mname} ({model_cfg['size']})  [{model_cfg['type']}]")
    if DEVICE == "cuda":
        print(f"  Free VRAM before load: {vram_gb_free():.1f} GB")
    print(f"{'='*70}")

    # ── Load tokenizer ─────────────────────────────────────────
    tokenizer = None
    model = None
    try:
        tokenizer = load_tokenizer(repo)
        log.info(f"Tokenizer loaded  vocab={tokenizer.vocab_size}")
    except Exception as e:
        log.error(f"Tokenizer FAILED for {mname}: {e}")
        all_results[mname] = {"_meta": model_cfg, "_error": str(e)}
        save_checkpoint(all_results)
        continue

    # ── Load model ─────────────────────────────────────────────
    try:
        if use_8bit and DEVICE == "cuda":
            import importlib.util
            if importlib.util.find_spec("bitsandbytes") is None:
                raise ImportError("bitsandbytes not installed. Run: pip install bitsandbytes accelerate")
            bnb_config = BitsAndBytesConfig(
                load_in_8bit=True,
                llm_int8_enable_fp32_cpu_offload=True
            )
            model = AutoModelForCausalLM.from_pretrained(
                repo, quantization_config=bnb_config, device_map={"": 0},
                trust_remote_code=True, token=True if HF_TOKEN else None
            )
        else:
            model = AutoModelForCausalLM.from_pretrained(
                repo, torch_dtype=DTYPE,
                device_map="auto" if DEVICE == "cuda" else None,
                trust_remote_code=True, token=True if HF_TOKEN else None
            )
        model.eval()
        n_params = sum(p.numel() for p in model.parameters()) / 1e6
        log.info(f"Model loaded  {n_params:.0f}M params  |  Free VRAM: {vram_gb_free():.1f} GB")
    except Exception as e:
        log.error(f"Model load FAILED for {mname}: {e}")
        all_results[mname] = {"_meta": model_cfg, "_error": str(e)}
        del tokenizer
        nuke_gpu()
        save_checkpoint(all_results)
        continue

    # ── Evaluate all modules ───────────────────────────────────
    model_res = {"_meta": model_cfg}
    try:
        for mod in MCQ_MODULES:
            t0 = time.time()
            sc = score_mcq(model, tokenizer, list(modules[mod]), mod)
            dt = time.time() - t0
            # Build difficulty breakdown string
            diff_parts = []
            for d_name in ["basic", "intermediate", "advanced"]:
                if d_name in sc.get("by_difficulty", {}):
                    ds = sc["by_difficulty"][d_name]
                    diff_parts.append(f"{d_name[:3]}:{ds['accuracy']*100:.0f}%")
            # Include any other difficulty levels not in the standard set
            for d_name, ds in sc.get("by_difficulty", {}).items():
                if d_name not in ["basic", "intermediate", "advanced"]:
                    diff_parts.append(f"{d_name[:3]}:{ds['accuracy']*100:.0f}%")
            diff_str = "  [" + " | ".join(diff_parts) + "]" if diff_parts else ""
            log.info(f"  {mod:35s}  {sc['accuracy']*100:5.1f}%  ({sc['correct']:3d}/{sc['total']:3d})  {dt:.0f}s{diff_str}")
            model_res[mod] = sc
    except Exception as e:
        log.error(f"Evaluation CRASHED on module for {mname}: {e}")
        model_res["_partial_error"] = str(e)

    all_results[mname] = model_res

    # ── AGGRESSIVE CLEANUP (prevents OOM on next model) ────────
    del model, tokenizer
    model = None
    tokenizer = None
    nuke_gpu()

    # ── Save after every model ─────────────────────────────────
    save_checkpoint(all_results)
    log.info(f"✓ Checkpoint saved after {mname}")


# ── 9. Composite scores & leaderboard ─────────────────────────
def composite(res: dict) -> float:
    ws, wt = 0.0, 0.0
    for mod, w in MODULE_WEIGHTS.items():
        if mod in res and isinstance(res[mod], dict) and "accuracy" in res[mod]:
            ws += res[mod]["accuracy"] * w
            wt += w
    return ws / wt if wt else 0.0

def fmt(v):
    return f"{v:.1f}" if isinstance(v, float) and math.isfinite(v) else "—"

rows = []
for mname, res in all_results.items():
    if "_error" in res:
        rows.append({"Model": mname, "Size": res["_meta"]["size"], "Type": res["_meta"]["type"],
                      "Composite": "ERR", **{m: "—" for m in MODULE_WEIGHTS}})
        continue
    row = {"Model": mname, "Size": res["_meta"]["size"], "Type": res["_meta"]["type"],
           "Composite": fmt(composite(res) * 100)}
    for mod in MCQ_MODULES:
        acc = res[mod]["accuracy"] * 100 if mod in res and isinstance(res[mod], dict) else float("nan")
        row[mod] = fmt(acc)
    rows.append(row)

df = pd.DataFrame(rows)
df["_sort"] = pd.to_numeric(df["Composite"], errors="coerce")
df = df.sort_values("_sort", ascending=False).drop(columns=["_sort"])

print("\n" + "=" * 90)
print("GomParam-v1 LEADERBOARD (20 MCQ modules, 12 models)")
print("=" * 90)
DISPLAY_COLS = ["Model", "Size", "Composite",
                "morphology", "cloze", "para_qa", "idioms_proverbs",
                "pragmatics", "cultural_grounding", "homograph_disambiguation",
                "dialect", "perplexity"]
print(tabulate(df[[c for c in DISPLAY_COLS if c in df.columns]],
               headers="keys", tablefmt="rounded_outline", showindex=False))
print(f"\nRandom baseline (4-choice MCQ): 25.0%")


# ── 10. Save final results ────────────────────────────────────
df.to_csv(OUTPUT_DIR / "leaderboard.csv", index=False)
save_checkpoint(all_results)
print(f"Saved: {OUTPUT_DIR}/leaderboard.csv, {CHECKPOINT_FILE}")


# ── 11. Plots ─────────────────────────────────────────────────
sns.set_style("whitegrid")
TYPE_COLORS = {
    "Multilingual Base": "#1d3557",  "Multilingual Chat": "#457b9d",
    "Multilingual Tiny": "#8ecae6",  "Multilingual Small": "#a8dadc",
    "Legacy Baseline": "#6c757d",    "Indic Specialist": "#f4a261",
    "Massive Multilingual": "#e76f51",
}

def plot_composite(df, path):
    d = df[df["Composite"] != "ERR"].copy()
    d["comp_f"] = pd.to_numeric(d["Composite"])
    d = d.sort_values("comp_f")
    colors = [TYPE_COLORS.get(t, "#adb5bd") for t in d["Type"]]
    labels = [f"{r['Model']}\n({r['Size']})" for _, r in d.iterrows()]
    fig, ax = plt.subplots(figsize=(12, max(6, len(d) * 0.55)))
    bars = ax.barh(labels, d["comp_f"], color=colors, edgecolor="white", height=0.55)
    ax.axvline(25.0, color="gray", ls="--", lw=1.2, alpha=0.8)
    for bar, val in zip(bars, d["comp_f"]):
        ax.text(bar.get_width() + 0.5, bar.get_y() + bar.get_height() / 2,
                f"{val:.1f}%", va="center", ha="left", fontsize=9, fontweight="bold")
    patches = [mpatches.Patch(color=c, label=t) for t, c in TYPE_COLORS.items() if t in d["Type"].values]
    ax.legend(handles=patches, fontsize=8, loc="lower right")
    ax.set_xlabel("Composite Accuracy (%)", fontsize=11)
    ax.set_title("GomParam-v1 Leaderboard — Weighted Composite Accuracy", fontsize=13, fontweight="bold")
    ax.set_xlim(0, 105)
    ax.grid(axis="x", alpha=0.25)
    plt.tight_layout()
    plt.savefig(path, dpi=300, bbox_inches="tight")
    plt.show()

def plot_heatmap(df, path):
    heat_cols = [m for m in MCQ_MODULES if m in df.columns]
    d = df[df["Composite"] != "ERR"].set_index("Model")[heat_cols].copy()
    for col in heat_cols:
        d[col] = pd.to_numeric(d[col], errors="coerce")
    d = d.rename(columns={m: m.replace("_", "\n").title() for m in heat_cols})
    fig, ax = plt.subplots(figsize=(max(16, len(heat_cols) * 0.7), max(6, len(d) * 0.6)))
    sns.heatmap(d, annot=True, fmt=".0f", cmap="YlGnBu", vmin=0, vmax=100,
                linewidths=0.5, ax=ax, cbar_kws={"label": "Accuracy (%)"})
    ax.set_title("GomParam-v1 Per-Module Accuracy Heatmap", fontsize=14, fontweight="bold")
    plt.xticks(rotation=45, ha="right", fontsize=9)
    plt.tight_layout()
    plt.savefig(path, dpi=300, bbox_inches="tight")
    plt.show()

try:
    plot_composite(df, OUTPUT_DIR / "leaderboard.png")
except Exception as e:
    log.warning(f"Composite plot failed: {e}")

try:
    plot_heatmap(df, OUTPUT_DIR / "heatmap.png")
except Exception as e:
    log.warning(f"Heatmap plot failed: {e}")

print("\n✅ Done. All results and plots saved in", OUTPUT_DIR)