{ "cells": [ { "cell_type": "markdown", "id": "35ed4e8a", "metadata": {}, "source": [ "# CLIP Tutorial — Pelatnas IOAI 2026 P2\n", "\n", "**Topik:** Multimodal Learning — CLIP (Contrastive Language-Image Pretraining)\n", "\n", "Notebook ini memandu kalian dari nol — memahami arsitektur CLIP, mengimplementasikannya dari scratch,\n", "sampai menggunakannya untuk menyelesaikan 4 task kompetisi ARIA.\n", "\n", "| Section | Topik |\n", "|---------|-------|\n", "| 1 | CLIP: Arsitektur dan Motivasi |\n", "| 2 | Mini CLIP dari Scratch (CIFAR-10) |\n", "| 3 | Load Pretrained CLIP + Eksplorasi Embedding Space |\n", "| 4 | Zero-Shot Classification |\n", "| 5 | Linear Probing |\n", "| 6 | Image-Text Retrieval |\n", "| 7 | MCQA dengan CLIP |\n", "| 8 | Baseline Submission |\n" ] }, { "cell_type": "markdown", "id": "e61a5ba3", "metadata": {}, "source": [ "---\n", "## Section 1 — CLIP: Arsitektur dan Motivasi\n", "\n", "### Mengapa CLIP?\n", "\n", "Model vision konvensional (ResNet, ViT) ditraining untuk memprediksi label dari\n", "dataset yang fixed (ImageNet → 1000 kelas). Masalahnya:\n", "- Tidak bisa generalize ke kelas baru tanpa retraining\n", "- Label harus predefined, tidak bisa deskripsi bebas\n", "\n", "**CLIP** (Contrastive Language-Image Pretraining, Radford et al. 2021) menyelesaikan\n", "ini dengan cara berbeda: instead of predicting labels, CLIP belajar *alignment*\n", "antara gambar dan teks.\n", "\n", "### Dual-Stream Architecture\n", "\n", "CLIP terdiri dari dua encoder yang ditraining bersama:\n", "1. **Image Encoder**: ViT atau ResNet → menghasilkan image embedding (vektor)\n", "2. **Text Encoder**: Transformer → menghasilkan text embedding (vektor)\n", "\n", "Kedua encoder memproyeksikan input ke *shared embedding space* dengan dimensi\n", "yang sama (e.g., 512 untuk ViT-B/32).\n", "\n", "### Training Objective\n", "\n", "CLIP ditraining dengan dataset **400 juta** pasang (image, caption) dari internet.\n", "Objective-nya sederhana:\n", "- image dan caption yang **matching** → cosine similarity **TINGGI**\n", "- image dan caption yang **tidak matching** → cosine similarity **RENDAH**\n", "\n", "Ini adalah *contrastive learning*: model belajar \"mendekatkan\" pasangan yang benar\n", "dan \"menjauhkan\" pasangan yang salah.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "25a6d7c7", "metadata": {}, "outputs": [], "source": [ "# ── Cell 1.1: Visualisasi konsep similarity matrix ──────────────────────────\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "labels = ['cat', 'dog', 'car', 'ship', 'bird', 'horse']\n", "N = len(labels)\n", "\n", "# Similarity matrix ideal: diagonal tinggi, off-diagonal rendah\n", "np.random.seed(42)\n", "sim_matrix = np.random.uniform(0.1, 0.4, (N, N))\n", "np.fill_diagonal(sim_matrix, np.random.uniform(0.8, 0.95, N))\n", "\n", "fig, ax = plt.subplots(figsize=(7, 6))\n", "im = ax.imshow(sim_matrix, cmap='Blues', vmin=0, vmax=1)\n", "ax.set_xticks(range(N))\n", "ax.set_yticks(range(N))\n", "ax.set_xticklabels([f'\"{l}\"' for l in labels], rotation=45, ha='right')\n", "ax.set_yticklabels([f'[IMG {l}]' for l in labels])\n", "ax.set_xlabel('Text Embeddings')\n", "ax.set_ylabel('Image Embeddings')\n", "ax.set_title('CLIP Similarity Matrix\\n(diagonal = matching pairs)')\n", "plt.colorbar(im)\n", "\n", "for i in range(N):\n", " for j in range(N):\n", " ax.text(j, i, f'{sim_matrix[i, j]:.2f}',\n", " ha='center', va='center',\n", " color='white' if sim_matrix[i, j] > 0.6 else 'black', fontsize=9)\n", "plt.tight_layout()\n", "plt.show()\n" ] }, { "cell_type": "markdown", "id": "7d21742a", "metadata": {}, "source": [ "---\n", "## Section 2 — Mini CLIP dari Scratch\n", "\n", "### Implementasi CLIP dari Nol\n", "\n", "Kita akan membuat versi miniatur CLIP untuk memahami mekanismenya.\n", "Ini **BUKAN** untuk performa — hanya untuk intuisi.\n", "\n", "Dataset toy: CIFAR-10 subset (1.000 images, 10 classes).\n", "Template caption: `\"a photo of a {class_name}\"`.\n", "\n", "Komponen yang diperlukan:\n", "1. `TinyImageEncoder`: CNN sederhana → embedding\n", "2. `TinyTextEncoder`: word embedding → pooling → linear\n", "3. `InfoNCE Loss`: fungsi loss contrastive\n", "4. Training loop + visualisasi\n" ] }, { "cell_type": "code", "execution_count": null, "id": "1e24cd2b", "metadata": {}, "outputs": [], "source": [ "# ── Cell 2.1: Setup dan download CIFAR-10 ───────────────────────────────────\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "from torchvision import datasets, transforms\n", "from torch.utils.data import DataLoader, Subset\n", "import numpy as np\n", "\n", "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", "print(f\"Using device: {device}\")\n", "\n", "CIFAR10_CLASSES = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n", " 'dog', 'frog', 'horse', 'ship', 'truck']\n", "\n", "transform = transforms.Compose([\n", " transforms.ToTensor(),\n", " transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n", "])\n", "\n", "full_train = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)\n", "\n", "# Ambil 100 images per class = 1000 total\n", "indices_per_class = {c: [] for c in range(10)}\n", "for idx, (_, label) in enumerate(full_train):\n", " if len(indices_per_class[label]) < 100:\n", " indices_per_class[label].append(idx)\n", " if all(len(v) == 100 for v in indices_per_class.values()):\n", " break\n", "\n", "all_indices = [idx for idxs in indices_per_class.values() for idx in idxs]\n", "toy_labels = [full_train.targets[i] for i in all_indices]\n", "toy_dataset = Subset(full_train, all_indices)\n", "\n", "print(f\"Toy dataset size: {len(toy_dataset)} images\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "48df6b98", "metadata": {}, "outputs": [], "source": [ "# ── Cell 2.2: Tiny Image Encoder ────────────────────────────────────────────\n", "class TinyImageEncoder(nn.Module):\n", " \"\"\"\n", " CNN sederhana: Conv → ReLU → MaxPool (×2) → GAP → Linear projection\n", " Input: (B, 3, 32, 32)\n", " Output: (B, EMBED_DIM) — normalized embedding\n", " \"\"\"\n", " def __init__(self, embed_dim=128):\n", " super().__init__()\n", " self.conv = nn.Sequential(\n", " nn.Conv2d(3, 32, kernel_size=3, padding=1), # → (B, 32, 32, 32)\n", " nn.ReLU(),\n", " nn.MaxPool2d(2), # → (B, 32, 16, 16)\n", " nn.Conv2d(32, 64, kernel_size=3, padding=1), # → (B, 64, 16, 16)\n", " nn.ReLU(),\n", " nn.MaxPool2d(2), # → (B, 64, 8, 8)\n", " )\n", " self.projection = nn.Linear(64, embed_dim)\n", "\n", " def forward(self, x):\n", " x = self.conv(x)\n", " x = x.mean(dim=[2, 3]) # Global Average Pooling → (B, 64)\n", " x = self.projection(x) # (B, embed_dim)\n", " return F.normalize(x, dim=-1) # L2-normalize → unit sphere\n", "\n", "\n", "# ── Cell 2.3: Tiny Text Encoder ─────────────────────────────────────────────\n", "class TinyTextEncoder(nn.Module):\n", " \"\"\"\n", " Word embedding → mean pooling → Linear projection\n", " Input: token ids (B, seq_len)\n", " Output: (B, EMBED_DIM) — normalized embedding\n", " \"\"\"\n", " def __init__(self, vocab_size, embed_dim=128, hidden_dim=64):\n", " super().__init__()\n", " self.embedding = nn.Embedding(vocab_size, hidden_dim, padding_idx=0)\n", " self.projection = nn.Linear(hidden_dim, embed_dim)\n", "\n", " def forward(self, x):\n", " emb = self.embedding(x) # (B, seq_len, hidden_dim)\n", " pooled = emb.mean(dim=1) # mean pooling → (B, hidden_dim)\n", " out = self.projection(pooled)\n", " return F.normalize(out, dim=-1)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "0bd8a6ea", "metadata": {}, "outputs": [], "source": [ "# ── Cell 2.4: Simple Tokenizer ───────────────────────────────────────────────\n", "templates = [f\"a photo of a {c}\" for c in CIFAR10_CLASSES]\n", "all_words = set()\n", "for t in templates:\n", " all_words.update(t.split())\n", "vocab = {word: idx + 1 for idx, word in enumerate(sorted(all_words))}\n", "vocab[''] = 0\n", "\n", "\n", "def tokenize(text, max_len=8):\n", " tokens = [vocab.get(w, 0) for w in text.split()]\n", " tokens = tokens[:max_len]\n", " tokens += [0] * (max_len - len(tokens))\n", " return tokens\n", "\n", "\n", "text_tokens = torch.tensor([tokenize(t) for t in templates]).to(device) # (10, 8)\n", "vocab_size = len(vocab) + 1\n", "\n", "print(\"Vocabulary:\", vocab)\n", "print(\"Template tokens shape:\", text_tokens.shape)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "6d6dce03", "metadata": {}, "outputs": [], "source": [ "# ── Cell 2.5: InfoNCE Loss ───────────────────────────────────────────────────\n", "def info_nce_loss(image_emb, text_emb, temperature=0.07):\n", " \"\"\"\n", " Contrastive loss untuk batch of N image-text pairs.\n", "\n", " Intuisi:\n", " - Hitung similarity matrix N×N\n", " - Untuk setiap image, correct text-nya adalah di posisi diagonal\n", " - Cross-entropy: dorong diagonal jadi paling tinggi\n", " - Loss = rata-rata dua arah (image→text + text→image)\n", " \"\"\"\n", " logits = (image_emb @ text_emb.T) / temperature # (N, N)\n", " labels = torch.arange(len(image_emb)).to(image_emb.device)\n", "\n", " loss_i2t = F.cross_entropy(logits, labels)\n", " loss_t2i = F.cross_entropy(logits.T, labels)\n", "\n", " return (loss_i2t + loss_t2i) / 2\n" ] }, { "cell_type": "code", "execution_count": null, "id": "45e059f3", "metadata": {}, "outputs": [], "source": [ "# ── Cell 2.6: TinyCLIP model ────────────────────────────────────────────────\n", "class TinyCLIP(nn.Module):\n", " def __init__(self, vocab_size, embed_dim=128):\n", " super().__init__()\n", " self.image_encoder = TinyImageEncoder(embed_dim)\n", " self.text_encoder = TinyTextEncoder(vocab_size, embed_dim)\n", "\n", " def encode_image(self, images):\n", " return self.image_encoder(images)\n", "\n", " def encode_text(self, tokens):\n", " return self.text_encoder(tokens)\n", "\n", "\n", "model = TinyCLIP(vocab_size=vocab_size, embed_dim=128).to(device)\n", "print(f\"TinyCLIP parameters: {sum(p.numel() for p in model.parameters()):,}\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "f360ddba", "metadata": {}, "outputs": [], "source": [ "# ── Cell 2.7: Training loop ──────────────────────────────────────────────────\n", "optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)\n", "\n", "images_tensor = torch.stack([toy_dataset[i][0] for i in range(len(toy_dataset))])\n", "loader = DataLoader(\n", " list(zip(images_tensor, toy_labels)),\n", " batch_size=64, shuffle=True\n", ")\n", "\n", "loss_history = []\n", "NUM_EPOCHS = 10\n", "\n", "for epoch in range(NUM_EPOCHS):\n", " model.train()\n", " epoch_losses = []\n", "\n", " for images, labels in loader:\n", " images = images.to(device)\n", " labels_list = labels.tolist() if isinstance(labels, torch.Tensor) else labels\n", "\n", " batch_text = text_tokens[labels_list] # (B, 8)\n", " image_emb = model.encode_image(images) # (B, 128)\n", " text_emb = model.encode_text(batch_text) # (B, 128)\n", "\n", " loss = info_nce_loss(image_emb, text_emb)\n", "\n", " optimizer.zero_grad()\n", " loss.backward()\n", " optimizer.step()\n", "\n", " epoch_losses.append(loss.item())\n", "\n", " mean_loss = np.mean(epoch_losses)\n", " loss_history.append(mean_loss)\n", " print(f\"Epoch {epoch+1:2d}/{NUM_EPOCHS} | Loss: {mean_loss:.4f}\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "cb49c0e2", "metadata": {}, "outputs": [], "source": [ "# ── Cell 2.8: Plot loss curve ────────────────────────────────────────────────\n", "import matplotlib.pyplot as plt\n", "\n", "plt.figure(figsize=(8, 4))\n", "plt.plot(range(1, NUM_EPOCHS + 1), loss_history, marker='o', linewidth=2, color='steelblue')\n", "plt.xlabel('Epoch')\n", "plt.ylabel('InfoNCE Loss')\n", "plt.title('TinyCLIP Training Loss')\n", "plt.grid(True, alpha=0.3)\n", "plt.tight_layout()\n", "plt.show()\n" ] }, { "cell_type": "code", "execution_count": null, "id": "7e920a81", "metadata": {}, "outputs": [], "source": [ "# ── Cell 2.9: Visualisasi embedding space (t-SNE) ───────────────────────────\n", "from sklearn.manifold import TSNE\n", "\n", "model.eval()\n", "with torch.no_grad():\n", " all_images = torch.stack([toy_dataset[i][0] for i in range(len(toy_dataset))]).to(device)\n", " image_embs = model.encode_image(all_images).cpu().numpy()\n", " text_embs = model.encode_text(text_tokens).cpu().numpy()\n", "\n", "all_embs = np.vstack([image_embs, text_embs]) # (1010, 128)\n", "tsne = TSNE(n_components=2, random_state=42, perplexity=30)\n", "embs_2d = tsne.fit_transform(all_embs)\n", "\n", "img_2d = embs_2d[:1000]\n", "txt_2d = embs_2d[1000:]\n", "\n", "colors = plt.cm.tab10(np.linspace(0, 1, 10))\n", "fig, ax = plt.subplots(figsize=(10, 8))\n", "\n", "for c in range(10):\n", " mask = np.array(toy_labels) == c\n", " ax.scatter(img_2d[mask, 0], img_2d[mask, 1],\n", " c=[colors[c]], alpha=0.4, s=20, label=CIFAR10_CLASSES[c])\n", " ax.scatter(txt_2d[c, 0], txt_2d[c, 1],\n", " c=[colors[c]], marker='*', s=300, edgecolors='black', linewidths=1)\n", "\n", "ax.legend(loc='upper right', fontsize=8)\n", "ax.set_title('t-SNE: TinyCLIP Embedding Space\\n'\n", " '(dots = images, stars = text templates)')\n", "ax.axis('off')\n", "plt.tight_layout()\n", "plt.show()\n" ] }, { "cell_type": "markdown", "id": "a61dee70", "metadata": {}, "source": [ "---\n", "## Section 3 — Load Pretrained CLIP + Eksplorasi Embedding Space\n", "\n", "### Dari Scratch ke Pretrained\n", "\n", "TinyCLIP kita ditraining di 1.000 gambar selama beberapa menit.\n", "CLIP asli ditraining di **400 juta** pasang selama berbulan-bulan di ratusan GPU.\n", "\n", "Hasilnya sangat berbeda. Mari kita load pretrained CLIP dan lihat embedding space-nya.\n", "\n", "**`openai/clip-vit-b-32`:**\n", "- Image encoder: Vision Transformer ViT-B/32\n", "- Text encoder: Transformer 12 layers\n", "- Embedding dim: 512\n", "- Total parameters: ~150M\n" ] }, { "cell_type": "code", "execution_count": null, "id": "1cde344f", "metadata": {}, "outputs": [], "source": [ "# ── Cell 3.1: Install dan load CLIP ─────────────────────────────────────────\n", "# !pip install git+https://github.com/openai/CLIP.git # jalankan sekali jika belum\n", "\n", "import clip\n", "from PIL import Image\n", "import torch\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", "model_clip, preprocess = clip.load(\"ViT-B/32\", device=device)\n", "model_clip.eval()\n", "\n", "print(f\"Model loaded. Input resolution: {model_clip.visual.input_resolution}\")\n", "print(f\"Embedding dimension: {model_clip.visual.output_dim}\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "51eb6f2e", "metadata": {}, "outputs": [], "source": [ "# ── Cell 3.2: Load STL-10 test images ───────────────────────────────────────\n", "from torchvision import datasets\n", "from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize\n", "\n", "clip_preprocess = Compose([\n", " Resize(224),\n", " CenterCrop(224),\n", " ToTensor(),\n", " Normalize((0.48145466, 0.4578275, 0.40821073),\n", " (0.26862954, 0.26130258, 0.27577711))\n", "])\n", "\n", "stl10_test = datasets.STL10(root='./data', split='test', download=True,\n", " transform=clip_preprocess)\n", "\n", "STL10_CLASSES = stl10_test.classes\n", "print(f\"STL-10 classes: {STL10_CLASSES}\")\n", "\n", "# Ambil 20/class untuk zero-shot (200 total) dan 20/class untuk linear probing (200 total)\n", "from collections import defaultdict\n", "zs_imgs, zs_labels = [], []\n", "lp_imgs, lp_labels = [], []\n", "zs_count = defaultdict(int)\n", "lp_count = defaultdict(int)\n", "\n", "for idx in range(len(stl10_test)):\n", " img, label = stl10_test[idx]\n", " if zs_count[label] < 20:\n", " zs_imgs.append(img)\n", " zs_labels.append(label)\n", " zs_count[label] += 1\n", " elif lp_count[label] < 20:\n", " lp_imgs.append(img)\n", " lp_labels.append(label)\n", " lp_count[label] += 1\n", " if sum(zs_count.values()) == 200 and sum(lp_count.values()) == 200:\n", " break\n", "\n", "zs_labels_arr = np.array(zs_labels)\n", "lp_test_labels = np.array(lp_labels)\n", "print(f\"ZS set: {len(zs_imgs)} | LP test set: {len(lp_imgs)}\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "0c99135b", "metadata": {}, "outputs": [], "source": [ "# ── Cell 3.3: Extract CLIP image embeddings ──────────────────────────────────\n", "from torch.utils.data import DataLoader, TensorDataset\n", "\n", "\n", "def extract_embeddings(img_list, batch_size=64):\n", " \"\"\"Extract CLIP image embeddings dari list of tensors.\"\"\"\n", " all_embs = []\n", " for i in range(0, len(img_list), batch_size):\n", " batch = torch.stack(img_list[i:i + batch_size]).to(device)\n", " with torch.no_grad():\n", " emb = model_clip.encode_image(batch)\n", " emb = emb / emb.norm(dim=-1, keepdim=True)\n", " all_embs.append(emb.cpu())\n", " return torch.cat(all_embs).numpy()\n", "\n", "\n", "print(\"Extracting embeddings...\")\n", "zs_embeddings = extract_embeddings(zs_imgs)\n", "lp_test_embeddings = extract_embeddings(lp_imgs)\n", "\n", "print(f\"Zero-shot embeddings: {zs_embeddings.shape}\")\n", "print(f\"Linear probing test embeddings: {lp_test_embeddings.shape}\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "61608dde", "metadata": {}, "outputs": [], "source": [ "# ── Cell 3.4: Extract text embeddings untuk 10 kelas ────────────────────────\n", "def get_text_embeddings(class_names, template=\"a photo of a {}\"):\n", " \"\"\"Encode class names dengan text encoder CLIP.\"\"\"\n", " prompts = [template.format(c) for c in class_names]\n", " tokens = clip.tokenize(prompts).to(device)\n", " with torch.no_grad():\n", " text_emb = model_clip.encode_text(tokens)\n", " text_emb = text_emb / text_emb.norm(dim=-1, keepdim=True)\n", " return text_emb.cpu().numpy()\n", "\n", "\n", "text_embeddings = get_text_embeddings(STL10_CLASSES)\n", "print(f\"Text embeddings: {text_embeddings.shape}\") # (10, 512)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "5a113a9e", "metadata": {}, "outputs": [], "source": [ "# ── Cell 3.5: Visualisasi t-SNE ─────────────────────────────────────────────\n", "from sklearn.manifold import TSNE\n", "\n", "all_embs = np.vstack([zs_embeddings, text_embeddings]) # (210, 512)\n", "tsne = TSNE(n_components=2, random_state=42, perplexity=30)\n", "embs_2d = tsne.fit_transform(all_embs)\n", "\n", "img_2d = embs_2d[:200]\n", "txt_2d = embs_2d[200:]\n", "\n", "colors = plt.cm.tab10(np.linspace(0, 1, 10))\n", "fig, ax = plt.subplots(figsize=(12, 9))\n", "\n", "for c in range(10):\n", " mask = zs_labels_arr == c\n", " ax.scatter(img_2d[mask, 0], img_2d[mask, 1],\n", " c=[colors[c]], alpha=0.5, s=30, label=STL10_CLASSES[c])\n", " ax.scatter(txt_2d[c, 0], txt_2d[c, 1],\n", " c=[colors[c]], marker='*', s=500, edgecolors='black', linewidths=1.5)\n", "\n", "ax.legend(loc='upper right', fontsize=9)\n", "ax.set_title('Pretrained CLIP — Embedding Space (STL-10)\\n'\n", " 'Dots = image embeddings | Stars = text template embeddings', fontsize=12)\n", "ax.axis('off')\n", "plt.tight_layout()\n", "plt.show()\n" ] }, { "cell_type": "markdown", "id": "3fe1881a", "metadata": {}, "source": [ "---\n", "## Section 4 — Zero-Shot Classification\n", "\n", "### Cara Kerja Zero-Shot dengan CLIP\n", "\n", "1. Encode setiap class name menjadi text embedding\n", "2. Encode query image menjadi image embedding\n", "3. Hitung cosine similarity antara image dan semua class embeddings\n", "4. Prediksi = class dengan similarity tertinggi\n", "\n", "**Prompt engineering penting!**\n", "`\"dog\"` ≠ `\"a photo of a dog\"` ≠ `\"a high-quality photo of a dog, DSLR\"`\n" ] }, { "cell_type": "code", "execution_count": null, "id": "6d54f9b1", "metadata": {}, "outputs": [], "source": [ "# ── Cell 4.1: Zero-shot prediction ──────────────────────────────────────────\n", "# zs_embeddings dan text_embeddings sudah dihitung di Section 3\n", "\n", "similarity = zs_embeddings @ text_embeddings.T # (200, 10)\n", "predictions_idx = np.argmax(similarity, axis=1)\n", "predictions_str = [STL10_CLASSES[i] for i in predictions_idx]\n", "\n", "accuracy = np.mean(predictions_idx == zs_labels_arr)\n", "print(f\"Zero-shot accuracy: {accuracy:.4f} ({accuracy*100:.1f}%)\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "bfb07706", "metadata": {}, "outputs": [], "source": [ "# ── Cell 4.2: Pengaruh prompt engineering ────────────────────────────────────\n", "templates_to_compare = [\n", " \"{}\",\n", " \"a photo of a {}\",\n", " \"a photo of a {}, high quality\",\n", " \"a {} in the wild\",\n", "]\n", "\n", "print(\"\\nPrompt engineering comparison:\")\n", "print(\"-\" * 50)\n", "for template in templates_to_compare:\n", " text_emb = get_text_embeddings(STL10_CLASSES, template)\n", " sim = zs_embeddings @ text_emb.T\n", " preds = np.argmax(sim, axis=1)\n", " acc = np.mean(preds == zs_labels_arr)\n", " print(f\" {template:<40} → {acc*100:.1f}%\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "aa9db826", "metadata": {}, "outputs": [], "source": [ "# ── Cell 4.3: Confusion matrix ───────────────────────────────────────────────\n", "from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay\n", "\n", "cm = confusion_matrix(zs_labels_arr, predictions_idx)\n", "disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=STL10_CLASSES)\n", "\n", "fig, ax = plt.subplots(figsize=(10, 8))\n", "disp.plot(ax=ax, colorbar=False, cmap='Blues')\n", "ax.set_title('Zero-Shot Classification — Confusion Matrix')\n", "plt.xticks(rotation=45, ha='right')\n", "plt.tight_layout()\n", "plt.show()\n" ] }, { "cell_type": "code", "execution_count": null, "id": "eb5c282d", "metadata": {}, "outputs": [], "source": [ "# ── Cell 4.4: Per-class accuracy ─────────────────────────────────────────────\n", "per_class_acc = {}\n", "for c in range(10):\n", " mask = zs_labels_arr == c\n", " per_class_acc[STL10_CLASSES[c]] = np.mean(predictions_idx[mask] == c)\n", "\n", "print(\"\\nPer-class accuracy:\")\n", "for cls, acc in sorted(per_class_acc.items(), key=lambda x: -x[1]):\n", " bar = '█' * int(acc * 20)\n", " print(f\" {cls:<10} {acc*100:5.1f}% {bar}\")\n" ] }, { "cell_type": "markdown", "id": "0aca5a63", "metadata": {}, "source": [ "---\n", "## Section 5 — Linear Probing\n", "\n", "### Perbedaan dari Zero-Shot\n", "\n", "| Metode | Data berlabel? | Cara prediksi |\n", "|--------|---------------|---------------|\n", "| Zero-shot | Tidak | Text prompts |\n", "| Linear probing | Ya (sedikit) | Classifier di atas frozen embeddings |\n", "\n", "**Kenapa tidak fine-tune semua layer?**\n", "- Linear probing murah secara komputasi\n", "- Menguji seberapa \"baik\" embeddings CLIP tanpa tambahan supervision\n", "- Fine-tuning bisa overfit ke domain kecil\n" ] }, { "cell_type": "code", "execution_count": null, "id": "c57f46c5", "metadata": {}, "outputs": [], "source": [ "# ── Cell 5.1: Extract train embeddings untuk linear probing ─────────────────\n", "stl10_train = datasets.STL10(root='./data', split='train', download=True,\n", " transform=clip_preprocess)\n", "\n", "# Ambil 100/class = 1000 images untuk training\n", "train_imgs, train_labels = [], []\n", "count = defaultdict(int)\n", "\n", "for idx in range(len(stl10_train)):\n", " img, label = stl10_train[idx]\n", " if count[label] < 100:\n", " train_imgs.append(img)\n", " train_labels.append(label)\n", " count[label] += 1\n", " if sum(count.values()) == 1000:\n", " break\n", "\n", "train_labels_arr = np.array(train_labels)\n", "print(\"Extracting train embeddings...\")\n", "lp_train_embeddings = extract_embeddings(train_imgs)\n", "print(f\"Train embeddings: {lp_train_embeddings.shape}\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "1dc5eed7", "metadata": {}, "outputs": [], "source": [ "# ── Cell 5.2: Train classifier ───────────────────────────────────────────────\n", "from sklearn.linear_model import LogisticRegression\n", "\n", "clf = LogisticRegression(max_iter=1000, C=0.316, random_state=42)\n", "clf.fit(lp_train_embeddings, train_labels_arr)\n", "\n", "lp_predictions = clf.predict(lp_test_embeddings)\n", "lp_accuracy = np.mean(lp_predictions == lp_test_labels)\n", "print(f\"Linear probing accuracy: {lp_accuracy:.4f} ({lp_accuracy*100:.1f}%)\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "9832535f", "metadata": {}, "outputs": [], "source": [ "# ── Cell 5.3: Perbandingan zero-shot vs linear probing ───────────────────────\n", "print(\"\\n\" + \"=\"*50)\n", "print(\" Perbandingan: Zero-Shot vs Linear Probing\")\n", "print(\"=\"*50)\n", "print(f\" Zero-shot (0 training images) : {accuracy*100:5.1f}%\")\n", "print(f\" Linear probe (1.000 labeled imgs) : {lp_accuracy*100:5.1f}%\")\n", "print(f\" Gap: +{(lp_accuracy - accuracy)*100:.1f}%\")\n", "print(\"=\"*50)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "69fafdc6", "metadata": {}, "outputs": [], "source": [ "# ── Cell 5.4: Bar chart per-class comparison ─────────────────────────────────\n", "per_class_lp = {}\n", "for c in range(10):\n", " mask = lp_test_labels == c\n", " per_class_lp[STL10_CLASSES[c]] = np.mean(lp_predictions[mask] == c)\n", "\n", "fig, ax = plt.subplots(figsize=(12, 5))\n", "x = np.arange(10)\n", "w = 0.35\n", "zs_vals = [per_class_acc[c] for c in STL10_CLASSES]\n", "lp_vals = [per_class_lp[c] for c in STL10_CLASSES]\n", "\n", "ax.bar(x - w/2, zs_vals, w, label='Zero-shot', color='steelblue', alpha=0.8)\n", "ax.bar(x + w/2, lp_vals, w, label='Linear probe', color='coral', alpha=0.8)\n", "ax.set_xticks(x)\n", "ax.set_xticklabels(STL10_CLASSES, rotation=45, ha='right')\n", "ax.set_ylabel('Accuracy')\n", "ax.set_title('Per-Class Accuracy: Zero-Shot vs Linear Probing')\n", "ax.legend()\n", "ax.set_ylim(0, 1.05)\n", "ax.grid(True, axis='y', alpha=0.3)\n", "plt.tight_layout()\n", "plt.show()\n" ] }, { "cell_type": "markdown", "id": "b1d910ed", "metadata": {}, "source": [ "---\n", "## Section 6 — Image-Text Retrieval\n", "\n", "### Retrieval sebagai Task Matching\n", "\n", "CLIP sangat natural untuk retrieval:\n", "1. Encode query image → image embedding\n", "2. Encode semua candidate captions → text embeddings\n", "3. Similarity = cosine similarity\n", "4. Predict = candidate dengan similarity tertinggi\n", "\n", "Dalam competition: **4 candidates per query**, predict index 0–3.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "4eac3bd2", "metadata": {}, "outputs": [], "source": [ "# ── Cell 6.1: Load Flickr8k test data ────────────────────────────────────────\n", "import pandas as pd\n", "from PIL import Image as PILImage\n", "\n", "DATASET_ROOT = '/kaggle/input/clip-pelatnas-p2'\n", "candidates_df = pd.read_csv(f'{DATASET_ROOT}/test/retrieval/candidates.csv')\n", "print(f\"Retrieval test: {len(candidates_df)} queries\")\n", "print(candidates_df.head(2))\n" ] }, { "cell_type": "code", "execution_count": null, "id": "876b6c60", "metadata": {}, "outputs": [], "source": [ "# ── Cell 6.2: CLIP retrieval pipeline ────────────────────────────────────────\n", "def clip_retrieval(image_path, captions, model, preprocess, device):\n", " \"\"\"\n", " Predict correct caption index untuk satu query.\n", " Returns: (predicted_idx, similarities_array)\n", " \"\"\"\n", " image = preprocess(PILImage.open(image_path)).unsqueeze(0).to(device)\n", " with torch.no_grad():\n", " img_emb = model.encode_image(image)\n", " img_emb = img_emb / img_emb.norm(dim=-1, keepdim=True)\n", "\n", " tokens = clip.tokenize(captions, truncate=True).to(device)\n", " with torch.no_grad():\n", " txt_emb = model.encode_text(tokens)\n", " txt_emb = txt_emb / txt_emb.norm(dim=-1, keepdim=True)\n", "\n", " similarities = (img_emb @ txt_emb.T).squeeze().cpu().numpy()\n", " predicted_idx = int(np.argmax(similarities))\n", " return predicted_idx, similarities\n" ] }, { "cell_type": "code", "execution_count": null, "id": "70ca735c", "metadata": {}, "outputs": [], "source": [ "# ── Cell 6.3: Batch evaluation ────────────────────────────────────────────────\n", "base_path = f'{DATASET_ROOT}/test/retrieval/queries/'\n", "predictions_ret = []\n", "\n", "for _, row in candidates_df.iterrows():\n", " captions = [row[f'caption_{i}'] for i in range(4)]\n", " pred_idx, _ = clip_retrieval(\n", " base_path + row['image_path'], captions, model_clip, preprocess, device\n", " )\n", " predictions_ret.append(pred_idx)\n", "\n", "predictions_ret = np.array(predictions_ret)\n", "correct_idx = candidates_df['correct_idx'].values\n", "\n", "ret_accuracy = np.mean(predictions_ret == correct_idx)\n", "print(f\"Retrieval accuracy (4-way): {ret_accuracy:.4f} ({ret_accuracy*100:.1f}%)\")\n", "print(f\"Random baseline: 25.0%\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "0c01f0d0", "metadata": {}, "outputs": [], "source": [ "# ── Cell 6.4: Qualitative examples ───────────────────────────────────────────\n", "fig, axes = plt.subplots(2, 4, figsize=(16, 7))\n", "correct_mask = predictions_ret == correct_idx\n", "correct_examples = np.where(correct_mask)[0][:2]\n", "wrong_examples = np.where(~correct_mask)[0][:2]\n", "examples = list(correct_examples) + list(wrong_examples)\n", "\n", "for col, idx in enumerate(examples):\n", " row_data = candidates_df.iloc[idx]\n", " captions = [row_data[f'caption_{i}'] for i in range(4)]\n", " _, sims = clip_retrieval(\n", " base_path + row_data['image_path'], captions, model_clip, preprocess, device\n", " )\n", "\n", " img = PILImage.open(base_path + row_data['image_path'])\n", " axes[0, col].imshow(img)\n", " axes[0, col].set_title('Benar' if col < 2 else 'Salah',\n", " color='green' if col < 2 else 'red', fontsize=12)\n", " axes[0, col].axis('off')\n", "\n", " for i, (cap, sim) in enumerate(zip(captions, sims)):\n", " is_correct = (i == row_data['correct_idx'])\n", " is_wrong = (i == predictions_ret[idx] and not is_correct)\n", " color = 'green' if is_correct else ('red' if is_wrong else 'black')\n", " marker = '★' if is_correct else ('✗' if is_wrong else ' ')\n", " axes[1, col].text(0.02, 0.88 - i * 0.23,\n", " f\"{marker} [{sim:.2f}] {cap[:55]}...\",\n", " transform=axes[1, col].transAxes,\n", " fontsize=7, color=color)\n", " axes[1, col].axis('off')\n", "\n", "plt.suptitle('Retrieval Examples (★ = correct answer, ✗ = wrong prediction)', fontsize=12)\n", "plt.tight_layout()\n", "plt.show()\n" ] }, { "cell_type": "markdown", "id": "97f98be0", "metadata": {}, "source": [ "---\n", "## Section 7 — MCQA dengan CLIP\n", "\n", "### Keterbatasan CLIP untuk Reasoning\n", "\n", "Cara naive dengan CLIP:\n", "- Encode image\n", "- Untuk setiap pilihan jawaban: encode `\"Question: {q} Answer: {choice}\"`\n", "- Predict = pilihan dengan similarity tertinggi terhadap image\n", "\n", "**Limitation**: CLIP tidak didesain untuk reasoning bertahap.\n", "CLIP bagus di *\"apa yang ada di gambar ini?\"* tapi terbatas untuk\n", "*\"kenapa hal ini terjadi?\"* atau soal sains yang butuh domain knowledge.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "bd004ef7", "metadata": {}, "outputs": [], "source": [ "# ── Cell 7.1: Load ScienceQA test data ──────────────────────────────────────\n", "mcqa_df = pd.read_csv(f'{DATASET_ROOT}/test/mcqa/test.csv')\n", "print(f\"MCQA test: {len(mcqa_df)} questions\")\n", "print(mcqa_df.head(2))\n" ] }, { "cell_type": "code", "execution_count": null, "id": "3fedf9ce", "metadata": {}, "outputs": [], "source": [ "# ── Cell 7.2: CLIP MCQA pipeline ─────────────────────────────────────────────\n", "def clip_mcqa(image_path, question, choices, model, preprocess, device):\n", " \"\"\"\n", " Predict correct answer untuk MCQA.\n", " Strategi: encode image, bandingkan dengan \"Question: {q} Answer: {choice}\".\n", " \"\"\"\n", " image = preprocess(PILImage.open(image_path)).unsqueeze(0).to(device)\n", " with torch.no_grad():\n", " img_emb = model.encode_image(image)\n", " img_emb = img_emb / img_emb.norm(dim=-1, keepdim=True)\n", "\n", " texts = [f\"Question: {question} Answer: {c}\" for c in choices]\n", " tokens = clip.tokenize(texts, truncate=True).to(device)\n", " with torch.no_grad():\n", " txt_emb = model.encode_text(tokens)\n", " txt_emb = txt_emb / txt_emb.norm(dim=-1, keepdim=True)\n", "\n", " similarities = (img_emb @ txt_emb.T).squeeze().cpu().numpy()\n", " predicted_idx = int(np.argmax(similarities))\n", "\n", " letter_map = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'}\n", " return letter_map[predicted_idx], similarities\n" ] }, { "cell_type": "code", "execution_count": null, "id": "80755731", "metadata": {}, "outputs": [], "source": [ "# ── Cell 7.3: Batch evaluation ────────────────────────────────────────────────\n", "base_path_mcqa = f'{DATASET_ROOT}/test/mcqa/images/'\n", "predictions_mcqa = []\n", "\n", "for _, row in mcqa_df.iterrows():\n", " n_choices = int(row['num_choices'])\n", " choices = [row[f'choice_{chr(65+i)}'] for i in range(n_choices)]\n", "\n", " pred_letter, _ = clip_mcqa(\n", " base_path_mcqa + row['image_path'],\n", " row['question'], choices, model_clip, preprocess, device\n", " )\n", " predictions_mcqa.append(pred_letter)\n", "\n", "mcqa_accuracy = np.mean(np.array(predictions_mcqa) == mcqa_df.get('answer', pd.Series([])).values) if 'answer' in mcqa_df.columns else float('nan')\n", "\n", "print(f\"MCQA accuracy: {mcqa_accuracy:.4f} ({mcqa_accuracy*100:.1f}%)\" if not np.isnan(mcqa_accuracy)\n", " else \"MCQA predictions done (answer column not available in test set)\")\n", "print(f\"Random baseline (~3.5 choices avg): ~{100/3.5:.1f}%\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "0b34a2f3", "metadata": {}, "outputs": [], "source": [ "# ── Cell 7.4: Analysis per subject ───────────────────────────────────────────\n", "mcqa_df_copy = mcqa_df.copy()\n", "mcqa_df_copy['predicted'] = predictions_mcqa\n", "\n", "if 'subject' in mcqa_df_copy.columns and 'answer' in mcqa_df_copy.columns:\n", " mcqa_df_copy['correct'] = mcqa_df_copy['predicted'] == mcqa_df_copy['answer']\n", " subject_acc = mcqa_df_copy.groupby('subject')['correct'].mean().sort_values(ascending=False)\n", "\n", " print(\"Accuracy per subject:\")\n", " for subj, acc in subject_acc.items():\n", " bar = '█' * int(acc * 20)\n", " print(f\" {subj:<25} {acc*100:5.1f}% {bar}\")\n", "else:\n", " subj_counts = mcqa_df_copy.groupby('subject')['predicted'].count()\n", " print(\"Question count per subject:\")\n", " for subj, cnt in subj_counts.items():\n", " print(f\" {subj:<25} {cnt} questions\")\n" ] }, { "cell_type": "markdown", "id": "6ce1248a", "metadata": {}, "source": [ "---\n", "## Section 8 — Baseline Submission\n", "\n", "### Membuat Submission\n", "\n", "Kode berikut menggabungkan prediksi dari semua 4 task ke dalam satu CSV.\n", "Ini adalah baseline paling sederhana: semua task menggunakan zero-shot CLIP.\n", "\n", "**Estimasi skor baseline: ~70–80% overall accuracy.**\n", "\n", "Cara improve:\n", "- Prompt engineering yang lebih baik\n", "- Gunakan model CLIP yang lebih besar (ViT-L/14)\n", "- Fine-tuning CLIP untuk task tertentu\n", "- Ensemble dengan model multimodal lain (BLIP, SigLIP)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "98109b5f", "metadata": {}, "outputs": [], "source": [ "# ── Cell 8.1: Compile semua prediksi ─────────────────────────────────────────\n", "import pandas as pd\n", "\n", "sample_sub = pd.read_csv(f'{DATASET_ROOT}/sample_submission.csv')\n", "pred_map = {}\n", "\n", "# Zero-shot predictions (dari Section 4)\n", "zs_ids = [f'zs_{i:04d}' for i in range(1, 201)]\n", "for id_, pred in zip(zs_ids, predictions_str):\n", " pred_map[id_] = pred\n", "\n", "# Linear probing predictions (dari Section 5)\n", "lp_ids = [f'lp_{i:04d}' for i in range(1, 201)]\n", "lp_cls_str = [STL10_CLASSES[p] for p in lp_predictions]\n", "for id_, pred in zip(lp_ids, lp_cls_str):\n", " pred_map[id_] = pred\n", "\n", "# Retrieval predictions (dari Section 6)\n", "for id_, pred in zip(candidates_df['id'].values, predictions_ret.tolist()):\n", " pred_map[id_] = int(pred)\n", "\n", "# MCQA predictions (dari Section 7)\n", "for id_, pred in zip(mcqa_df['id'].values, predictions_mcqa):\n", " pred_map[id_] = pred\n" ] }, { "cell_type": "code", "execution_count": null, "id": "0675c9b8", "metadata": {}, "outputs": [], "source": [ "# ── Cell 8.2: Generate submission ────────────────────────────────────────────\n", "submission = sample_sub.copy()\n", "submission['prediction'] = submission['id'].map(pred_map)\n", "\n", "assert len(submission) == 800, f\"Expected 800 rows, got {len(submission)}\"\n", "assert submission['prediction'].isna().sum() == 0, \"Ada id yang tidak terprediksi!\"\n", "\n", "print(\"Submission preview (2 per task):\")\n", "for prefix in ['zs', 'lp', 'ret', 'mcqa']:\n", " mask = submission['id'].str.startswith(prefix)\n", " print(submission[mask].head(2).to_string(index=False))\n", " print()\n", "\n", "submission.to_csv('submission.csv', index=False)\n", "print(f\"Saved: submission.csv ({len(submission)} rows)\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "9fcd617f", "metadata": {}, "outputs": [], "source": [ "# ── Cell 8.3: Sanity check ────────────────────────────────────────────────────\n", "print(\"Distribusi prediksi per task:\\n\")\n", "for prefix, name in [('zs', 'Zero-shot'), ('lp', 'Linear probe'),\n", " ('ret', 'Retrieval'), ('mcqa', 'MCQA')]:\n", " mask = submission['id'].str.startswith(prefix)\n", " subset = submission[mask]\n", " counts = subset['prediction'].value_counts().to_dict()\n", " print(f\" {name} ({mask.sum()} items): {counts}\")\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.10.0" } }, "nbformat": 4, "nbformat_minor": 5 }