GomParam-v1 / scripts /colab_eval.py
Nikame Agent
fix: implement conditional probability scoring
f497d8b
Raw
History Blame Contribute Delete
24.3 kB
# ================================================================
# 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)