fassabilf commited on
Commit
c68f63e
·
verified ·
1 Parent(s): dfc2427

Upload generate_baselines.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. generate_baselines.py +351 -0
generate_baselines.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ generate_baselines.py — Generate 3 baseline submission CSV files using CLIP.
4
+
5
+ Approach 1: Zero-shot ViT-B/32, template "a photo of a {}"
6
+ Approach 2: Zero-shot ViT-B/32 (prompt ensemble) + LogReg linear probe for LP task
7
+ Approach 3: Zero-shot ViT-L/14@336px, template "a photo of a {}"
8
+
9
+ Outputs: submissions/submission_1_zs_vitb32.csv
10
+ submissions/submission_2_lp_vitb32.csv
11
+ submissions/submission_3_zs_vitl14.csv
12
+ submissions/report.md
13
+ """
14
+
15
+ import re
16
+ import time
17
+ from collections import defaultdict
18
+ from pathlib import Path
19
+
20
+ import clip
21
+ import numpy as np
22
+ import pandas as pd
23
+ import torch
24
+ from PIL import Image
25
+ from sklearn.linear_model import LogisticRegression
26
+ from tqdm import tqdm
27
+
28
+ DATASET_ROOT = Path('./output/clip-pelatnas-p2')
29
+ SUB_DIR = Path('./submissions')
30
+ SUB_DIR.mkdir(exist_ok=True)
31
+
32
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
33
+ print(f"Device: {device}")
34
+ if torch.cuda.is_available():
35
+ print(f"GPU: {torch.cuda.get_device_name(0)} ({torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB)")
36
+
37
+
38
+ # ── Helpers ───────────────────────────────────────────────────────────────────
39
+
40
+ def load_images_as_tensors(img_dir: Path, fnames: list, preprocess, batch_size=128):
41
+ """Load images from disk, preprocess, return (N, D) embedding tensor."""
42
+ imgs = [preprocess(Image.open(img_dir / f).convert('RGB')) for f in tqdm(fnames, desc=' loading')]
43
+ embeddings = []
44
+ for i in range(0, len(imgs), batch_size):
45
+ batch = torch.stack(imgs[i:i + batch_size]).to(device)
46
+ with torch.no_grad():
47
+ emb = model.encode_image(batch)
48
+ emb = emb / emb.norm(dim=-1, keepdim=True)
49
+ embeddings.append(emb.cpu().float().numpy())
50
+ return np.vstack(embeddings)
51
+
52
+
53
+ def encode_texts(texts: list, batch_size=256):
54
+ embeddings = []
55
+ for i in range(0, len(texts), batch_size):
56
+ batch = clip.tokenize(texts[i:i + batch_size], truncate=True).to(device)
57
+ with torch.no_grad():
58
+ emb = model.encode_text(batch)
59
+ emb = emb / emb.norm(dim=-1, keepdim=True)
60
+ embeddings.append(emb.cpu().float().numpy())
61
+ return np.vstack(embeddings)
62
+
63
+
64
+ LETTER_MAP = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'}
65
+
66
+ PROMPT_TEMPLATES = [
67
+ "a photo of a {}",
68
+ "a photograph of a {}",
69
+ "a picture of a {}",
70
+ "an image of a {}",
71
+ "a {} in the wild",
72
+ "a photo of the {}",
73
+ "a {} photo",
74
+ "a {} image",
75
+ ]
76
+
77
+
78
+ # ── Per-task inference ────────────────────────────────────────────────────────
79
+
80
+ def run_zero_shot(class_names, template="a photo of a {}", task='zs'):
81
+ """Zero-shot classification on ZS or LP test set."""
82
+ img_dir = DATASET_ROOT / f'test/{"zero_shot" if task == "zs" else "linear_probing"}/images'
83
+ print(f"\n[Zero-shot task={task}] template: '{template}'")
84
+ fnames = sorted(f.name for f in img_dir.glob('*.png'))
85
+
86
+ embs = load_images_as_tensors(img_dir, fnames, preprocess)
87
+ texts = [template.format(c) for c in class_names]
88
+ text_embs = encode_texts(texts)
89
+
90
+ sim = embs @ text_embs.T # (N, 10)
91
+ preds = np.argmax(sim, axis=1)
92
+ pred_strs = [class_names[i] for i in preds]
93
+
94
+ ids = [f'{task}_{i+1:04d}' for i in range(len(fnames))]
95
+ return ids, pred_strs
96
+
97
+
98
+ def run_zero_shot_ensemble(class_names, templates=PROMPT_TEMPLATES, task='zs'):
99
+ """Zero-shot with ensemble of prompt templates."""
100
+ img_dir = DATASET_ROOT / f'test/{"zero_shot" if task == "zs" else "linear_probing"}/images'
101
+ print(f"\n[Zero-shot ensemble task={task}] {len(templates)} templates")
102
+ fnames = sorted(f.name for f in img_dir.glob('*.png'))
103
+ embs = load_images_as_tensors(img_dir, fnames, preprocess)
104
+
105
+ # Average text embeddings across templates
106
+ all_text_embs = []
107
+ for tmpl in templates:
108
+ texts = [tmpl.format(c) for c in class_names]
109
+ te = encode_texts(texts)
110
+ all_text_embs.append(te)
111
+ text_embs = np.mean(all_text_embs, axis=0)
112
+ text_embs = text_embs / np.linalg.norm(text_embs, axis=-1, keepdims=True)
113
+
114
+ sim = embs @ text_embs.T
115
+ preds = [class_names[i] for i in np.argmax(sim, axis=1)]
116
+
117
+ ids = [f'{task}_{i+1:04d}' for i in range(len(fnames))]
118
+ return ids, preds
119
+
120
+
121
+ def run_linear_probe(class_names, template="a photo of a {}"):
122
+ """Extract LP train embeddings → LogReg → predict LP test."""
123
+ print(f"\n[Linear probe] C=0.316")
124
+
125
+ train_df = pd.read_csv(DATASET_ROOT / 'train/linear_probing/labels.csv')
126
+ train_dir = DATASET_ROOT / 'train/linear_probing/images'
127
+ test_dir = DATASET_ROOT / 'test/linear_probing/images'
128
+ test_fnames = sorted(f.name for f in test_dir.glob('*.png'))
129
+
130
+ print(" Encoding train images...")
131
+ train_embs = load_images_as_tensors(train_dir, train_df['image_path'].tolist(), preprocess)
132
+ train_labels = np.array([class_names.index(l) for l in train_df['label']])
133
+
134
+ print(" Encoding test images...")
135
+ test_embs = load_images_as_tensors(test_dir, test_fnames, preprocess)
136
+
137
+ clf = LogisticRegression(max_iter=1000, C=0.316, random_state=42, n_jobs=-1)
138
+ clf.fit(train_embs, train_labels)
139
+ preds = [class_names[i] for i in clf.predict(test_embs)]
140
+
141
+ ids = [f'lp_{i+1:04d}' for i in range(len(test_fnames))]
142
+ return ids, preds
143
+
144
+
145
+ def run_retrieval():
146
+ """4-way image-to-text retrieval."""
147
+ print("\n[Retrieval]")
148
+ cand_df = pd.read_csv(DATASET_ROOT / 'test/retrieval/candidates.csv')
149
+ query_dir = DATASET_ROOT / 'test/retrieval/queries'
150
+
151
+ ids, preds = [], []
152
+ for _, row in tqdm(cand_df.iterrows(), total=len(cand_df)):
153
+ img_path = query_dir / row['image_path']
154
+ img = preprocess(Image.open(img_path).convert('RGB')).unsqueeze(0).to(device)
155
+
156
+ captions = [row[f'caption_{i}'] for i in range(4)]
157
+ tokens = clip.tokenize(captions, truncate=True).to(device)
158
+
159
+ with torch.no_grad():
160
+ img_emb = model.encode_image(img)
161
+ img_emb = img_emb / img_emb.norm(dim=-1, keepdim=True)
162
+ txt_embs = model.encode_text(tokens)
163
+ txt_embs = txt_embs / txt_embs.norm(dim=-1, keepdim=True)
164
+
165
+ sims = (img_emb @ txt_embs.T).squeeze().cpu().float().numpy()
166
+ ids.append(row['id'])
167
+ preds.append(int(np.argmax(sims)))
168
+
169
+ return ids, preds
170
+
171
+
172
+ def run_mcqa():
173
+ """Multiple choice QA."""
174
+ print("\n[MCQA]")
175
+ test_df = pd.read_csv(DATASET_ROOT / 'test/mcqa/test.csv')
176
+ image_dir = DATASET_ROOT / 'test/mcqa/images'
177
+
178
+ ids, preds = [], []
179
+ for _, row in tqdm(test_df.iterrows(), total=len(test_df)):
180
+ img_path = image_dir / row['image_path']
181
+ n_choices = int(row['num_choices'])
182
+ choices = [row[f'choice_{chr(65+i)}'] for i in range(n_choices)]
183
+ question = row['question']
184
+
185
+ img = preprocess(Image.open(img_path).convert('RGB')).unsqueeze(0).to(device)
186
+ texts = [f"Question: {question} Answer: {c}" for c in choices]
187
+ tokens = clip.tokenize(texts, truncate=True).to(device)
188
+
189
+ with torch.no_grad():
190
+ img_emb = model.encode_image(img)
191
+ img_emb = img_emb / img_emb.norm(dim=-1, keepdim=True)
192
+ txt_embs = model.encode_text(tokens)
193
+ txt_embs = txt_embs / txt_embs.norm(dim=-1, keepdim=True)
194
+
195
+ sims = (img_emb @ txt_embs.T).squeeze().cpu().float().numpy()
196
+ ids.append(row['id'])
197
+ preds.append(LETTER_MAP[int(np.argmax(sims))])
198
+
199
+ return ids, preds
200
+
201
+
202
+ def compute_accuracy(ids, preds, solution_df):
203
+ sol_map = dict(zip(solution_df['Id'], solution_df['prediction'].astype(str)))
204
+ correct = sum(str(p) == sol_map.get(i, '') for i, p in zip(ids, preds))
205
+ return correct / len(ids)
206
+
207
+
208
+ def build_submission(parts):
209
+ """parts = list of (ids, preds) tuples."""
210
+ rows = []
211
+ for ids, preds in parts:
212
+ for i, p in zip(ids, preds):
213
+ rows.append({'id': i, 'prediction': str(p)})
214
+ return pd.DataFrame(rows)
215
+
216
+
217
+ def run_approach(name, fn_zs, fn_lp, class_names):
218
+ """Run all 4 tasks with given functions, return dict of results."""
219
+ t0 = time.time()
220
+ results = {}
221
+ results['zs'] = fn_zs(class_names)
222
+ results['lp'] = fn_lp(class_names)
223
+ results['ret'] = run_retrieval()
224
+ results['mcqa'] = run_mcqa()
225
+ results['elapsed'] = time.time() - t0
226
+ return results
227
+
228
+
229
+ # ── Main ─────────────────────────────────────────────────────────────────────
230
+
231
+ if __name__ == '__main__':
232
+ solution_df = pd.read_csv('./output/solution.csv')
233
+ with open(DATASET_ROOT / 'class_names.txt') as f:
234
+ class_names = [l.strip() for l in f if l.strip()]
235
+ print(f"Classes: {class_names}")
236
+
237
+ # ── APPROACH 1: ViT-B/32 zero-shot (standard) ────────────────────────────
238
+ print("\n" + "=" * 60)
239
+ print("APPROACH 1: Zero-shot ViT-B/32 (standard template)")
240
+ print("=" * 60)
241
+ model, preprocess = clip.load("ViT-B/32", device=device)
242
+ model.eval()
243
+
244
+ r1 = {}
245
+ r1['zs'] = run_zero_shot(class_names, task='zs')
246
+ r1['lp'] = run_zero_shot(class_names, task='lp') # ZS on LP test images
247
+ r1['ret'] = run_retrieval()
248
+ r1['mcqa'] = run_mcqa()
249
+
250
+ sub1 = build_submission([r1['zs'], r1['lp'], r1['ret'], r1['mcqa']])
251
+ sub1.to_csv(SUB_DIR / 'submission_1_zs_vitb32.csv', index=False)
252
+
253
+ # ── APPROACH 2: ViT-B/32 zero-shot ensemble + LogReg LP ──────────────────
254
+ print("\n" + "=" * 60)
255
+ print("APPROACH 2: ViT-B/32 prompt ensemble + LogReg linear probe")
256
+ print("=" * 60)
257
+
258
+ r2 = {}
259
+ r2['zs'] = run_zero_shot_ensemble(class_names)
260
+ r2['lp'] = run_linear_probe(class_names)
261
+ r2['ret'] = run_retrieval() # same model, same result
262
+ r2['mcqa'] = run_mcqa()
263
+
264
+ sub2 = build_submission([r2['zs'], r2['lp'], r2['ret'], r2['mcqa']])
265
+ sub2.to_csv(SUB_DIR / 'submission_2_lp_vitb32.csv', index=False)
266
+
267
+ # ── APPROACH 3: ViT-L/14@336px zero-shot ─────────────────────────────────
268
+ print("\n" + "=" * 60)
269
+ print("APPROACH 3: Zero-shot ViT-L/14@336px (best CLIP model)")
270
+ print("=" * 60)
271
+ del model
272
+ torch.cuda.empty_cache()
273
+ model, preprocess = clip.load("ViT-L/14@336px", device=device)
274
+ model.eval()
275
+
276
+ r3 = {}
277
+ r3['zs'] = run_zero_shot_ensemble(class_names)
278
+ r3['lp'] = run_linear_probe(class_names)
279
+ r3['ret'] = run_retrieval()
280
+ r3['mcqa'] = run_mcqa()
281
+
282
+ sub3 = build_submission([r3['zs'], r3['lp'], r3['ret'], r3['mcqa']])
283
+ sub3.to_csv(SUB_DIR / 'submission_3_zs_vitl14.csv', index=False)
284
+
285
+ # ── Score report ──────────────────────────────────────────────────────────
286
+ print("\n" + "=" * 60)
287
+ print("SCORE REPORT")
288
+ print("=" * 60)
289
+
290
+ approaches = {
291
+ 'Approach 1 — ZS ViT-B/32': r1,
292
+ 'Approach 2 — LP+Ensemble ViT-B/32': r2,
293
+ 'Approach 3 — ZS ViT-L/14@336px': r3,
294
+ }
295
+ tasks = [('zs', 'Zero-shot'), ('lp', 'Linear probe'), ('ret', 'Retrieval'), ('mcqa', 'MCQA')]
296
+
297
+ rows = []
298
+ for approach_name, r in approaches.items():
299
+ row = {'Approach': approach_name}
300
+ total_correct, total_n = 0, 0
301
+ for task_key, task_name in tasks:
302
+ ids, preds = r[task_key]
303
+ acc = compute_accuracy(ids, preds, solution_df)
304
+ row[task_name] = f'{acc*100:.1f}%'
305
+ total_correct += sum(str(p) == dict(zip(solution_df['Id'], solution_df['prediction'].astype(str))).get(i, '') for i, p in zip(ids, preds))
306
+ total_n += len(ids)
307
+ row['Overall (800)'] = f'{total_correct/total_n*100:.1f}%'
308
+ rows.append(row)
309
+
310
+ report_df = pd.DataFrame(rows)
311
+ print(report_df.to_string(index=False))
312
+
313
+ # Save report.md
314
+ report_md = f"""# CLIP Pelatnas P2 — Baseline Score Report
315
+
316
+ **GPU**: {torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'CPU'}
317
+ **Date**: Generated by generate_baselines.py
318
+
319
+ ## Accuracy per Task & Approach
320
+
321
+ {report_df.to_markdown(index=False)}
322
+
323
+ ## Keterangan Approach
324
+
325
+ | Approach | Zero-shot | Linear Probe | Retrieval | MCQA | Model |
326
+ |----------|-----------|--------------|-----------|------|-------|
327
+ | Approach 1 | template standar | zero-shot (no train data) | CLIP similarity | Q+A template | ViT-B/32 |
328
+ | Approach 2 | prompt ensemble (8 template) | LogReg di CLIP features (C=0.316) | CLIP similarity | Q+A template | ViT-B/32 |
329
+ | Approach 3 | prompt ensemble (8 template) | LogReg di CLIP features | CLIP similarity | Q+A template | ViT-L/14@336px |
330
+
331
+ ## Catatan
332
+
333
+ - **Zero-shot**: Task 1 — CLIP langsung predict tanpa training
334
+ - **Linear Probe**: Task 2 — LogReg trained di atas CLIP embeddings (1000 labeled images)
335
+ - **Retrieval**: 4-way image-to-text matching, random baseline = 25%
336
+ - **MCQA**: Visual QA dari ScienceQA, random baseline ≈ 28% (~3.5 avg choices)
337
+
338
+ ## Baseline untuk Peserta
339
+
340
+ Approach 1 adalah baseline yang akan ditunjukkan di tutorial notebook.
341
+ Approach 2 dan 3 adalah referensi untuk mengetahui "ceiling" skor yang realistis.
342
+ """
343
+
344
+ with open(SUB_DIR / 'report.md', 'w') as f:
345
+ f.write(report_md)
346
+
347
+ print(f"\nFiles saved to {SUB_DIR.absolute()}/")
348
+ print(" submission_1_zs_vitb32.csv")
349
+ print(" submission_2_lp_vitb32.csv")
350
+ print(" submission_3_zs_vitl14.csv")
351
+ print(" report.md")