GomParam-v1 / scripts /eval_gemini_batched.py
Nikame Agent
fix: scrub API keys from evaluation scripts for security
34884b9
Raw
History Blame Contribute Delete
9.63 kB
"""
eval_gemini_batched.py
======================
Evaluate Gemini models on GomParam-v1 via the Gemini API using BATCHING.
This drastically speeds up evaluation and bypasses strict daily quotas
by evaluating multiple items in a single API request.
"""
import argparse
import csv
import json
import os
import re
import time
from pathlib import Path
from google import genai
from google.genai import types
def load_dataset(data_dir: Path):
items = []
for f in sorted(data_dir.glob("*.json")):
module = f.stem
with open(f, encoding="utf-8") as fp:
data = json.load(fp)
for it in data:
it["module"] = module
items.append(it)
return items
def build_batch_prompt(batch: list) -> str:
prompt = (
"You are an expert in Goan Konkani linguistics and culture.\n"
"Evaluate the following multiple-choice questions.\n"
"For each question, select the integer index (0, 1, 2, or 3) of the correct option.\n\n"
"CRITICAL INSTRUCTION:\n"
f"You MUST output your response as a valid JSON list of exactly {len(batch)} integers. "
"Do not include any explanations, markdown formatting, or text outside the JSON list.\n"
"Example output: [1, 0, 3, 2]\n\n"
"---\n\n"
)
for i, item in enumerate(batch):
context = item.get("context", "") or item.get("sentence", "") or item.get("passage", "") or ""
question = item.get("question", "") or ""
candidates = item.get("candidates", [])
prompt += f"[Item {i}]\n"
if context:
prompt += f"Context: {context}\n"
if question:
prompt += f"Question: {question}\n"
else:
prompt += "Complete the sentence or identify the correct relation:\n"
prompt += "Options:\n"
for idx, c in enumerate(candidates):
prompt += f"[{idx}] {c}\n"
prompt += "\n"
return prompt
def parse_batch_prediction(text: str, expected_len: int) -> list:
"""Extracts the JSON list from the response."""
# Strip markdown block if present
text = text.strip()
if text.startswith("```json"):
text = text[7:]
if text.startswith("```"):
text = text[3:]
if text.endswith("```"):
text = text[:-3]
text = text.strip()
try:
preds = json.loads(text)
if isinstance(preds, list) and len(preds) == expected_len:
# Ensure all are valid indices
return [int(p) if int(p) in [0, 1, 2, 3] else -1 for p in preds]
except json.JSONDecodeError:
pass
# Fallback regex extraction if JSON fails
nums = re.findall(r'\b[0123]\b', text)
if len(nums) == expected_len:
return [int(n) for n in nums]
return []
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()}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--model", default="gemini-3.1-flash-lite")
parser.add_argument("--batch_size", type=int, default=15)
parser.add_argument("--delay", type=float, default=4.0)
args = parser.parse_args()
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
print("ERROR: GEMINI_API_KEY environment variable is not set!")
return
print(f"Initializing Gemini Client with {args.model}")
client = genai.Client(api_key=api_key)
config = types.GenerateContentConfig(
temperature=0.0,
response_mime_type="application/json",
)
out_dir = Path("results/gemini/")
out_dir.mkdir(parents=True, exist_ok=True)
items = load_dataset(Path("data/"))
csv_path = out_dir / "predictions.csv"
processed_ids = set()
module_stats = {}
if csv_path.exists():
with open(csv_path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
processed_ids.add(row["id"])
mod = row["module"]
if mod not in module_stats:
module_stats[mod] = {"correct": 0, "total": 0}
module_stats[mod]["total"] += 1
module_stats[mod]["correct"] += int(row["predicted_correct"])
unprocessed_items = [it for i, it in enumerate(items) if it.get("id", f"item_{i}") not in processed_ids]
print(f"Skipping {len(processed_ids)} already processed items. {len(unprocessed_items)} items remaining.")
batches = [unprocessed_items[i:i + args.batch_size] for i in range(0, len(unprocessed_items), args.batch_size)]
print(f"Divided into {len(batches)} batches of up to {args.batch_size} items each.")
mode = "a" if processed_ids else "w"
with open(csv_path, mode, newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["id", "module", "correct", "predicted", "predicted_correct", "raw_response"])
if not processed_ids:
writer.writeheader()
for b_idx, batch in enumerate(batches):
prompt = build_batch_prompt(batch)
max_retries = 5
preds = []
raw_text = ""
for attempt in range(max_retries):
try:
response = client.models.generate_content(
model=args.model,
contents=prompt,
config=config
)
raw_text = response.text.strip()
preds = parse_batch_prediction(raw_text, len(batch))
if preds:
break # Success
else:
print(f" Batch {b_idx+1}: Failed to parse JSON, retrying (Attempt {attempt+1}/{max_retries})")
time.sleep(2)
except Exception as e:
error_msg = str(e)
if "API_KEY_INVALID" in error_msg or "expired" in error_msg:
print(f" API Key INVALID/EXPIRED. Exiting.")
return
if "429" in error_msg or "RESOURCE_EXHAUSTED" in error_msg:
wait_time = 35.0
m = re.search(r"retry in (\d+\.?\d*)s", error_msg)
if m: wait_time = float(m.group(1)) + 2.0
if "GenerateRequestsPerDay" in error_msg or wait_time > 60.0:
print(f" Hit Daily Quota. Exiting.")
return
print(f" Rate limited. Waiting {wait_time:.1f}s (Attempt {attempt+1}/{max_retries})")
time.sleep(wait_time)
else:
print(f" API Error on Batch {b_idx+1}: {e}")
time.sleep(5)
# If all retries failed, log -1 for all items in batch
if not preds:
print(f" Batch {b_idx+1} completely failed! Assigning -1 to all items.")
preds = [-1] * len(batch)
# Write results
for j, item in enumerate(batch):
item_id = item.get("id", f"item_batch_{b_idx}_{j}")
mod = item["module"]
gold = int(item["correct"])
pred = preds[j]
is_correct = int(pred == gold)
writer.writerow({
"id": item_id,
"module": mod,
"correct": gold,
"predicted": pred,
"predicted_correct": is_correct,
"raw_response": f"BATCH_{b_idx+1}"
})
if mod not in module_stats: module_stats[mod] = {"correct": 0, "total": 0}
module_stats[mod]["correct"] += is_correct
module_stats[mod]["total"] += 1
f.flush()
print(f" Processed Batch {b_idx+1}/{len(batches)} ({len(batch)} items)")
time.sleep(args.delay)
print("\nEvaluation Complete! Calculating metrics...")
comp_score, comp_weight = 0.0, 0.0
summary = {"model": args.model, "total_items": sum(s["total"] for s in module_stats.values()), "per_module": {}}
for mod in sorted(module_stats.keys()):
st = module_stats[mod]
acc = st["correct"] / st["total"] if st["total"] > 0 else 0.0
summary["per_module"][mod] = {"accuracy": round(acc, 4), "correct": st["correct"], "total": st["total"]}
if mod in MODULE_WEIGHTS:
comp_score += acc * MODULE_WEIGHTS[mod]
comp_weight += MODULE_WEIGHTS[mod]
final_comp = comp_score / comp_weight if comp_weight > 0 else 0.0
summary["composite_accuracy"] = round(final_comp, 4)
print(f" Composite Accuracy: {final_comp*100:5.1f}%")
summary_path = out_dir / "gemini_summary.json"
with open(summary_path, "w", encoding="utf-8") as f: json.dump(summary, f, indent=2)
if __name__ == "__main__":
main()