Datasets:
Nikame Agent
fix: add smart rate limit handling parsing wait_time from 429 errors for Gemini eval
c0fa15d | # ================================================================ | |
| # GomParam-v1 × Gonyai-TEO2 Evaluation Script | |
| # Kaggle / Colab ready. Mirrors colab_eval.py harness exactly. | |
| # | |
| # Run this first in a separate cell: | |
| # !pip -q install -U bitsandbytes accelerate transformers sentencepiece safetensors huggingface_hub | |
| # | |
| # Usage: | |
| # python eval_gonyai.py | |
| # or paste into a Kaggle notebook cell after the pip install. | |
| # ================================================================ | |
| import json, os, gc, time, math, logging | |
| from pathlib import Path | |
| from typing import Optional | |
| import torch | |
| import numpy as np | |
| import pandas as pd | |
| import matplotlib.pyplot as plt | |
| import seaborn as sns | |
| from datasets import load_dataset | |
| from transformers import AutoTokenizer, AutoModelForCausalLM | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") | |
| log = logging.getLogger("gomparam_gonyai") | |
| # ── CONFIG ───────────────────────────────────────────────────── | |
| HF_TOKEN = os.getenv("HF_TOKEN", "") # set in Kaggle Secrets | |
| GONYAI_REPO = "omdeep22/gonyai-teo2" # HF model repo | |
| DATASET_REPO = "omdeep22/GomParam-v1" # benchmark repo | |
| LOAD_IN_8BIT = False # 251M fits in FP16 easily | |
| IS_KAGGLE = Path("/kaggle/working").exists() | |
| BASE_DIR = Path("/kaggle/working") if IS_KAGGLE else Path(".") | |
| OUTPUT_DIR = BASE_DIR / "gonyai_results" | |
| OUTPUT_DIR.mkdir(parents=True, exist_ok=True) | |
| # Route HF cache to working directory (avoids Kaggle disk OOM) | |
| os.environ["HF_HOME"] = str(BASE_DIR / "hf_cache") | |
| DEVICE = "cuda" if torch.cuda.is_available() else "cpu" | |
| DTYPE = torch.float16 if DEVICE == "cuda" else torch.float32 | |
| print(f"Device : {DEVICE}") | |
| if DEVICE == "cuda": | |
| print(f"GPU : {torch.cuda.get_device_name(0)}") | |
| print(f"VRAM : {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB") | |
| if HF_TOKEN: | |
| from huggingface_hub import login | |
| login(token=HF_TOKEN) | |
| else: | |
| log.warning("No HF_TOKEN found. Set it in Kaggle Secrets if the repo is private.") | |
| # ── 1. Load GomParam-v1 modules ──────────────────────────────── | |
| 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("\nLoading GomParam-v1 from HuggingFace...") | |
| modules = {} | |
| for m in ALL_MODULES: | |
| try: | |
| ds = load_dataset(DATASET_REPO, m, split="train", trust_remote_code=False, | |
| token=HF_TOKEN or None) | |
| modules[m] = list(ds) | |
| print(f" ✓ {m:35s} {len(modules[m]):>4} items") | |
| except Exception as e: | |
| print(f" ✗ {m:35s} FAILED: {e}") | |
| total = sum(len(v) for v in modules.values()) | |
| print(f"\nLoaded {len(modules)}/{len(ALL_MODULES)} modules — {total} total items\n") | |
| # ── 2. Schema normaliser (identical to colab_eval.py) ────────── | |
| def safe_str(*args, default=""): | |
| for v in args: | |
| if v is not None and str(v).strip(): | |
| return str(v) | |
| return default | |
| 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 | |
| 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. Conditional log-probability scorer ────────────────────── | |
| def sequence_log_prob(model, tokenizer, prefix: str, candidate: str, max_len: int = 512) -> float: | |
| """ | |
| Conditional log P(candidate | prefix) per token. | |
| Prompt tokens are masked with -100 so only candidate loss is measured. | |
| Identical implementation to colab_eval.py — ensures directly comparable scores. | |
| """ | |
| enc_full = tokenizer(prefix + candidate, return_tensors="pt", | |
| truncation=True, max_length=max_len).to(DEVICE) | |
| 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() | |
| labels[0, :prefix_len] = -100 # mask prompt tokens | |
| with torch.amp.autocast("cuda", enabled=(DEVICE == "cuda")): | |
| out = model(ids, labels=labels) | |
| return -float(out.loss.item()) | |
| def score_module(model, tokenizer, items, module: str) -> dict: | |
| correct, total = 0, 0 | |
| diff_stats = {} | |
| for raw in items: | |
| raw = dict(raw) | |
| difficulty = str(raw.get("difficulty", "unknown")).lower().strip() | |
| norm = normalise_mcq(raw, 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 = int(pred == gold) | |
| correct += hit | |
| total += 1 | |
| diff_stats.setdefault(difficulty, {"correct": 0, "total": 0}) | |
| diff_stats[difficulty]["total"] += 1 | |
| diff_stats[difficulty]["correct"] += hit | |
| diff_accuracy = {d: {"accuracy": s["correct"]/s["total"] if s["total"] else 0, | |
| "correct": s["correct"], "total": s["total"]} | |
| for d, s in diff_stats.items()} | |
| return { | |
| "accuracy": correct / total if total else 0.0, | |
| "correct": correct, | |
| "total": total, | |
| "by_difficulty": diff_accuracy, | |
| } | |
| # ── 4. Module weights (same as colab_eval.py) ────────────────── | |
| 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] | |
| # ── 5. Load Gonyai-TEO2 ──────────────────────────────────────── | |
| print(f"Loading {GONYAI_REPO} ...") | |
| tokenizer = AutoTokenizer.from_pretrained(GONYAI_REPO, use_fast=True, | |
| token=HF_TOKEN or None) | |
| if tokenizer.pad_token is None: | |
| tokenizer.pad_token = tokenizer.eos_token | |
| model = AutoModelForCausalLM.from_pretrained( | |
| GONYAI_REPO, | |
| torch_dtype=DTYPE, | |
| device_map={"": 0} if DEVICE == "cuda" else None, # pin to cuda:0 — avoids cross-GPU split on Kaggle dual-T4 | |
| trust_remote_code=True, | |
| token=HF_TOKEN or None, | |
| ) | |
| if DEVICE != "cuda": | |
| model = model.to(DEVICE) | |
| model.eval() | |
| n_params = sum(p.numel() for p in model.parameters()) / 1e6 | |
| print(f"Model loaded: {n_params:.0f}M parameters\n") | |
| # ── 6. Evaluate ──────────────────────────────────────────────── | |
| results = {} | |
| for mod in MCQ_MODULES: | |
| t0 = time.time() | |
| sc = score_module(model, tokenizer, modules[mod], mod) | |
| dt = time.time() - t0 | |
| diff_parts = [] | |
| for d in ["basic", "intermediate", "advanced"]: | |
| if d in sc["by_difficulty"]: | |
| ds = sc["by_difficulty"][d] | |
| diff_parts.append(f"{d[:3]}:{ds['accuracy']*100:.0f}%") | |
| diff_str = " [" + " | ".join(diff_parts) + "]" if diff_parts else "" | |
| log.info(f" {mod:35s} {sc['accuracy']*100:5.1f}% " | |
| f"({sc['correct']:3d}/{sc['total']:3d}) {dt:.0f}s{diff_str}") | |
| results[mod] = sc | |
| # ── 7. Composite score ───────────────────────────────────────── | |
| def composite(res): | |
| ws, wt = 0.0, 0.0 | |
| for mod, w in MODULE_WEIGHTS.items(): | |
| if mod in res and "accuracy" in res[mod]: | |
| ws += res[mod]["accuracy"] * w | |
| wt += w | |
| return ws / wt if wt else 0.0 | |
| comp = composite(results) | |
| print(f"\n{'='*60}") | |
| print(f"Gonyai-TEO2 Composite Accuracy: {comp*100:.2f}%") | |
| print(f"Random Baseline: 25.00%") | |
| print(f"{'='*60}\n") | |
| # Module table | |
| print(f"{'Module':<35} {'Acc':>7} {'Correct':>7} {'Total':>7}") | |
| print("-" * 60) | |
| for mod in sorted(results): | |
| sc = results[mod] | |
| print(f"{mod:<35} {sc['accuracy']*100:>6.1f}% {sc['correct']:>7} {sc['total']:>7}") | |
| # ── 8. Save results ──────────────────────────────────────────── | |
| summary = { | |
| "model": GONYAI_REPO, | |
| "composite_accuracy": round(comp, 4), | |
| "random_baseline": 0.25, | |
| "per_module": {m: {"accuracy": round(results[m]["accuracy"], 4), | |
| "correct": results[m]["correct"], | |
| "total": results[m]["total"], | |
| "by_difficulty": results[m]["by_difficulty"]} | |
| for m in results}, | |
| } | |
| summary_path = OUTPUT_DIR / "gonyai_summary.json" | |
| with open(summary_path, "w") as f: | |
| json.dump(summary, f, indent=2) | |
| print(f"\nSummary saved → {summary_path}") | |
| # ── 9. Heatmap plot ──────────────────────────────────────────── | |
| try: | |
| heat_data = {m: results[m]["accuracy"] * 100 for m in MCQ_MODULES} | |
| df_heat = pd.DataFrame([heat_data], index=["Gonyai-TEO2"]) | |
| df_heat = df_heat.rename(columns={m: m.replace("_", "\n").title() for m in MCQ_MODULES}) | |
| fig, ax = plt.subplots(figsize=(18, 3)) | |
| sns.heatmap(df_heat, annot=True, fmt=".0f", cmap="YlGnBu", | |
| vmin=0, vmax=100, linewidths=0.5, ax=ax, | |
| cbar_kws={"label": "Accuracy (%)"}) | |
| ax.set_title("Gonyai-TEO2 — GomParam-v1 Per-Module Accuracy", fontsize=13, fontweight="bold") | |
| plt.xticks(rotation=45, ha="right", fontsize=8) | |
| plt.tight_layout() | |
| heatmap_path = OUTPUT_DIR / "gonyai_heatmap.png" | |
| plt.savefig(heatmap_path, dpi=200, bbox_inches="tight") | |
| plt.show() | |
| print(f"Heatmap saved → {heatmap_path}") | |
| except Exception as e: | |
| log.warning(f"Heatmap plot failed: {e}") | |
| print(f"\n✅ Done. Results in {OUTPUT_DIR}") | |