#!/usr/bin/env python3 """ generate_baselines.py — Generate 3 baseline submission CSV files using CLIP. Approach 1: Zero-shot ViT-B/32, template "a photo of a {}" Approach 2: Zero-shot ViT-B/32 (prompt ensemble) + LogReg linear probe for LP task Approach 3: Zero-shot ViT-L/14@336px, template "a photo of a {}" Outputs: submissions/submission_1_zs_vitb32.csv submissions/submission_2_lp_vitb32.csv submissions/submission_3_zs_vitl14.csv submissions/report.md """ import re import time from collections import defaultdict from pathlib import Path import clip import numpy as np import pandas as pd import torch from PIL import Image from sklearn.linear_model import LogisticRegression from tqdm import tqdm DATASET_ROOT = Path('./output/clip-pelatnas-p2') SUB_DIR = Path('./submissions') SUB_DIR.mkdir(exist_ok=True) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print(f"Device: {device}") if torch.cuda.is_available(): print(f"GPU: {torch.cuda.get_device_name(0)} ({torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB)") # ── Helpers ─────────────────────────────────────────────────────────────────── def load_images_as_tensors(img_dir: Path, fnames: list, preprocess, batch_size=128): """Load images from disk, preprocess, return (N, D) embedding tensor.""" imgs = [preprocess(Image.open(img_dir / f).convert('RGB')) for f in tqdm(fnames, desc=' loading')] embeddings = [] for i in range(0, len(imgs), batch_size): batch = torch.stack(imgs[i:i + batch_size]).to(device) with torch.no_grad(): emb = model.encode_image(batch) emb = emb / emb.norm(dim=-1, keepdim=True) embeddings.append(emb.cpu().float().numpy()) return np.vstack(embeddings) def encode_texts(texts: list, batch_size=256): embeddings = [] for i in range(0, len(texts), batch_size): batch = clip.tokenize(texts[i:i + batch_size], truncate=True).to(device) with torch.no_grad(): emb = model.encode_text(batch) emb = emb / emb.norm(dim=-1, keepdim=True) embeddings.append(emb.cpu().float().numpy()) return np.vstack(embeddings) LETTER_MAP = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'} PROMPT_TEMPLATES = [ "a photo of a {}", "a photograph of a {}", "a picture of a {}", "an image of a {}", "a {} in the wild", "a photo of the {}", "a {} photo", "a {} image", ] # ── Per-task inference ──────────────────────────────────────────────────────── def run_zero_shot(class_names, template="a photo of a {}", task='zs'): """Zero-shot classification on ZS or LP test set.""" img_dir = DATASET_ROOT / f'test/{"zero_shot" if task == "zs" else "linear_probing"}/images' print(f"\n[Zero-shot task={task}] template: '{template}'") fnames = sorted(f.name for f in img_dir.glob('*.png')) embs = load_images_as_tensors(img_dir, fnames, preprocess) texts = [template.format(c) for c in class_names] text_embs = encode_texts(texts) sim = embs @ text_embs.T # (N, 10) preds = np.argmax(sim, axis=1) pred_strs = [class_names[i] for i in preds] ids = [f'{task}_{i+1:04d}' for i in range(len(fnames))] return ids, pred_strs def run_zero_shot_ensemble(class_names, templates=PROMPT_TEMPLATES, task='zs'): """Zero-shot with ensemble of prompt templates.""" img_dir = DATASET_ROOT / f'test/{"zero_shot" if task == "zs" else "linear_probing"}/images' print(f"\n[Zero-shot ensemble task={task}] {len(templates)} templates") fnames = sorted(f.name for f in img_dir.glob('*.png')) embs = load_images_as_tensors(img_dir, fnames, preprocess) # Average text embeddings across templates all_text_embs = [] for tmpl in templates: texts = [tmpl.format(c) for c in class_names] te = encode_texts(texts) all_text_embs.append(te) text_embs = np.mean(all_text_embs, axis=0) text_embs = text_embs / np.linalg.norm(text_embs, axis=-1, keepdims=True) sim = embs @ text_embs.T preds = [class_names[i] for i in np.argmax(sim, axis=1)] ids = [f'{task}_{i+1:04d}' for i in range(len(fnames))] return ids, preds def run_linear_probe(class_names, template="a photo of a {}"): """Extract LP train embeddings → LogReg → predict LP test.""" print(f"\n[Linear probe] C=0.316") train_df = pd.read_csv(DATASET_ROOT / 'train/linear_probing/labels.csv') train_dir = DATASET_ROOT / 'train/linear_probing/images' test_dir = DATASET_ROOT / 'test/linear_probing/images' test_fnames = sorted(f.name for f in test_dir.glob('*.png')) print(" Encoding train images...") train_embs = load_images_as_tensors(train_dir, train_df['image_path'].tolist(), preprocess) train_labels = np.array([class_names.index(l) for l in train_df['label']]) print(" Encoding test images...") test_embs = load_images_as_tensors(test_dir, test_fnames, preprocess) clf = LogisticRegression(max_iter=1000, C=0.316, random_state=42, n_jobs=-1) clf.fit(train_embs, train_labels) preds = [class_names[i] for i in clf.predict(test_embs)] ids = [f'lp_{i+1:04d}' for i in range(len(test_fnames))] return ids, preds def run_retrieval(): """4-way image-to-text retrieval.""" print("\n[Retrieval]") cand_df = pd.read_csv(DATASET_ROOT / 'test/retrieval/candidates.csv') query_dir = DATASET_ROOT / 'test/retrieval/queries' ids, preds = [], [] for _, row in tqdm(cand_df.iterrows(), total=len(cand_df)): img_path = query_dir / row['image_path'] img = preprocess(Image.open(img_path).convert('RGB')).unsqueeze(0).to(device) captions = [row[f'caption_{i}'] for i in range(4)] tokens = clip.tokenize(captions, truncate=True).to(device) with torch.no_grad(): img_emb = model.encode_image(img) img_emb = img_emb / img_emb.norm(dim=-1, keepdim=True) txt_embs = model.encode_text(tokens) txt_embs = txt_embs / txt_embs.norm(dim=-1, keepdim=True) sims = (img_emb @ txt_embs.T).squeeze().cpu().float().numpy() ids.append(row['id']) preds.append(int(np.argmax(sims))) return ids, preds def run_mcqa(): """Multiple choice QA.""" print("\n[MCQA]") test_df = pd.read_csv(DATASET_ROOT / 'test/mcqa/test.csv') image_dir = DATASET_ROOT / 'test/mcqa/images' ids, preds = [], [] for _, row in tqdm(test_df.iterrows(), total=len(test_df)): img_path = image_dir / row['image_path'] n_choices = int(row['num_choices']) choices = [row[f'choice_{chr(65+i)}'] for i in range(n_choices)] question = row['question'] img = preprocess(Image.open(img_path).convert('RGB')).unsqueeze(0).to(device) texts = [f"Question: {question} Answer: {c}" for c in choices] tokens = clip.tokenize(texts, truncate=True).to(device) with torch.no_grad(): img_emb = model.encode_image(img) img_emb = img_emb / img_emb.norm(dim=-1, keepdim=True) txt_embs = model.encode_text(tokens) txt_embs = txt_embs / txt_embs.norm(dim=-1, keepdim=True) sims = (img_emb @ txt_embs.T).squeeze().cpu().float().numpy() ids.append(row['id']) preds.append(LETTER_MAP[int(np.argmax(sims))]) return ids, preds def compute_accuracy(ids, preds, solution_df): sol_map = dict(zip(solution_df['Id'], solution_df['prediction'].astype(str))) correct = sum(str(p) == sol_map.get(i, '') for i, p in zip(ids, preds)) return correct / len(ids) def build_submission(parts): """parts = list of (ids, preds) tuples.""" rows = [] for ids, preds in parts: for i, p in zip(ids, preds): rows.append({'id': i, 'prediction': str(p)}) return pd.DataFrame(rows) def run_approach(name, fn_zs, fn_lp, class_names): """Run all 4 tasks with given functions, return dict of results.""" t0 = time.time() results = {} results['zs'] = fn_zs(class_names) results['lp'] = fn_lp(class_names) results['ret'] = run_retrieval() results['mcqa'] = run_mcqa() results['elapsed'] = time.time() - t0 return results # ── Main ───────────────────────────────────────────────────────────────────── if __name__ == '__main__': solution_df = pd.read_csv('./output/solution.csv') with open(DATASET_ROOT / 'class_names.txt') as f: class_names = [l.strip() for l in f if l.strip()] print(f"Classes: {class_names}") # ── APPROACH 1: ViT-B/32 zero-shot (standard) ──────────────────────────── print("\n" + "=" * 60) print("APPROACH 1: Zero-shot ViT-B/32 (standard template)") print("=" * 60) model, preprocess = clip.load("ViT-B/32", device=device) model.eval() r1 = {} r1['zs'] = run_zero_shot(class_names, task='zs') r1['lp'] = run_zero_shot(class_names, task='lp') # ZS on LP test images r1['ret'] = run_retrieval() r1['mcqa'] = run_mcqa() sub1 = build_submission([r1['zs'], r1['lp'], r1['ret'], r1['mcqa']]) sub1.to_csv(SUB_DIR / 'submission_1_zs_vitb32.csv', index=False) # ── APPROACH 2: ViT-B/32 zero-shot ensemble + LogReg LP ────────────────── print("\n" + "=" * 60) print("APPROACH 2: ViT-B/32 prompt ensemble + LogReg linear probe") print("=" * 60) r2 = {} r2['zs'] = run_zero_shot_ensemble(class_names) r2['lp'] = run_linear_probe(class_names) r2['ret'] = run_retrieval() # same model, same result r2['mcqa'] = run_mcqa() sub2 = build_submission([r2['zs'], r2['lp'], r2['ret'], r2['mcqa']]) sub2.to_csv(SUB_DIR / 'submission_2_lp_vitb32.csv', index=False) # ── APPROACH 3: ViT-L/14@336px zero-shot ───────────────────────────────── print("\n" + "=" * 60) print("APPROACH 3: Zero-shot ViT-L/14@336px (best CLIP model)") print("=" * 60) del model torch.cuda.empty_cache() model, preprocess = clip.load("ViT-L/14@336px", device=device) model.eval() r3 = {} r3['zs'] = run_zero_shot_ensemble(class_names) r3['lp'] = run_linear_probe(class_names) r3['ret'] = run_retrieval() r3['mcqa'] = run_mcqa() sub3 = build_submission([r3['zs'], r3['lp'], r3['ret'], r3['mcqa']]) sub3.to_csv(SUB_DIR / 'submission_3_zs_vitl14.csv', index=False) # ── Score report ────────────────────────────────────────────────────────── print("\n" + "=" * 60) print("SCORE REPORT") print("=" * 60) approaches = { 'Approach 1 — ZS ViT-B/32': r1, 'Approach 2 — LP+Ensemble ViT-B/32': r2, 'Approach 3 — ZS ViT-L/14@336px': r3, } tasks = [('zs', 'Zero-shot'), ('lp', 'Linear probe'), ('ret', 'Retrieval'), ('mcqa', 'MCQA')] rows = [] for approach_name, r in approaches.items(): row = {'Approach': approach_name} total_correct, total_n = 0, 0 for task_key, task_name in tasks: ids, preds = r[task_key] acc = compute_accuracy(ids, preds, solution_df) row[task_name] = f'{acc*100:.1f}%' total_correct += sum(str(p) == dict(zip(solution_df['Id'], solution_df['prediction'].astype(str))).get(i, '') for i, p in zip(ids, preds)) total_n += len(ids) row['Overall (800)'] = f'{total_correct/total_n*100:.1f}%' rows.append(row) report_df = pd.DataFrame(rows) print(report_df.to_string(index=False)) # Save report.md report_md = f"""# CLIP Pelatnas P2 — Baseline Score Report **GPU**: {torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'CPU'} **Date**: Generated by generate_baselines.py ## Accuracy per Task & Approach {report_df.to_markdown(index=False)} ## Keterangan Approach | Approach | Zero-shot | Linear Probe | Retrieval | MCQA | Model | |----------|-----------|--------------|-----------|------|-------| | Approach 1 | template standar | zero-shot (no train data) | CLIP similarity | Q+A template | ViT-B/32 | | Approach 2 | prompt ensemble (8 template) | LogReg di CLIP features (C=0.316) | CLIP similarity | Q+A template | ViT-B/32 | | Approach 3 | prompt ensemble (8 template) | LogReg di CLIP features | CLIP similarity | Q+A template | ViT-L/14@336px | ## Catatan - **Zero-shot**: Task 1 — CLIP langsung predict tanpa training - **Linear Probe**: Task 2 — LogReg trained di atas CLIP embeddings (1000 labeled images) - **Retrieval**: 4-way image-to-text matching, random baseline = 25% - **MCQA**: Visual QA dari ScienceQA, random baseline ≈ 28% (~3.5 avg choices) ## Baseline untuk Peserta Approach 1 adalah baseline yang akan ditunjukkan di tutorial notebook. Approach 2 dan 3 adalah referensi untuk mengetahui "ceiling" skor yang realistis. """ with open(SUB_DIR / 'report.md', 'w') as f: f.write(report_md) print(f"\nFiles saved to {SUB_DIR.absolute()}/") print(" submission_1_zs_vitb32.csv") print(" submission_2_lp_vitb32.csv") print(" submission_3_zs_vitl14.csv") print(" report.md")