{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "251333d5",
   "metadata": {},
   "source": [
    "# Week 5 Practical: Multimodal Large Language Models\n",
    "\n",
    "## Vision-Language Models: From CLIP to Building Your Own VLM\n",
    "\n",
    "### Learning Objectives\n",
    "\n",
    "By the end of this practical session, you will:\n",
    "\n",
    "1. **Understand CLIP embeddings** (Exercise 1)\n",
    "   - Explore how CLIP aligns images and text in a shared space\n",
    "   - Perform zero-shot image classification\n",
    "   - Analyze the embedding space with visualization\n",
    "\n",
    "2. **Build a Vision-Language Model** (Exercise 2)\n",
    "   - Understand how modern VLMs connect vision encoders to LLMs\n",
    "   - Implement a visual projection layer\n",
    "   - Use prompt tuning to improve modality alignment\n",
    "   - Train your model on image captioning\n",
    "   - Generate captions with your trained model"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8a892330",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "The next cell imports the necessary modules – just run it, no need to look at\n",
    "the details!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1dd99d36",
   "metadata": {
    "tags": [
     "colab",
     "pip",
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "# Installing required packages\n",
    "\n",
    "%pip install setuptools==80.9.0\n",
    "\n",
    "# Installing main packages\n",
    "\n",
    "%pip install matplotlib==3.10.8\n",
    "%pip install su-master-mind==2026.1.25.4\n",
    "%pip install torch==2.9.1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67e1e1e9",
   "metadata": {
    "lines_to_next_cell": 0
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import warnings\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import requests\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "from io import BytesIO\n",
    "from typing import List, Optional, Tuple\n",
    "from master_mind.teaching.hf import load_hf_dataset, load_hf_model, load_hf_processor, load_hf_tokenizer\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c9719190",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_best_device():\n",
    "    \"\"\"Returns the best device on this computer\"\"\"\n",
    "\n",
    "    if torch.cuda.is_available():\n",
    "        device = torch.device(\"cuda\")\n",
    "        total_memory = torch.cuda.get_device_properties(device).total_memory\n",
    "        print(f\"GPU Memory: {total_memory / 1e9:.1f} GB\")\n",
    "        print(f\"GPU Name: {torch.cuda.get_device_name(device)}\")\n",
    "    elif torch.backends.mps.is_available():\n",
    "        device = torch.device(\"mps\")\n",
    "    else:\n",
    "        device = torch.device(\"cpu\")\n",
    "    print(f\"Found device: {device}\")\n",
    "    return device\n",
    "\n",
    "\n",
    "device = get_best_device()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d7af727c",
   "metadata": {},
   "outputs": [],
   "source": [
    "warnings.filterwarnings(\"ignore\")\n",
    "os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4711c92d",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Helper Functions\n",
    "\n",
    "We'll use some utility functions to load and display images throughout this practical."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30668853",
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_image_from_url(url: str) -> Image.Image:\n",
    "    \"\"\"Load an image from a URL.\"\"\"\n",
    "    response = requests.get(url, timeout=10)\n",
    "    return Image.open(BytesIO(response.content)).convert(\"RGB\")\n",
    "\n",
    "\n",
    "def load_image(path_or_url: str) -> Image.Image:\n",
    "    \"\"\"Load an image from a local path or URL.\"\"\"\n",
    "    if path_or_url.startswith(\"http\"):\n",
    "        return load_image_from_url(path_or_url)\n",
    "    return Image.open(path_or_url).convert(\"RGB\")\n",
    "\n",
    "\n",
    "def display_images(images: List[Image.Image], titles: List[str] = None, ncols: int = 4):\n",
    "    \"\"\"Display a grid of images with optional titles.\"\"\"\n",
    "    n = len(images)\n",
    "    if n == 0:\n",
    "        return\n",
    "    ncols = min(ncols, n)\n",
    "    nrows = (n + ncols - 1) // ncols\n",
    "    _, axes = plt.subplots(nrows, ncols, figsize=(4 * ncols, 4 * nrows))\n",
    "\n",
    "    # Ensure axes is always a flat list\n",
    "    if nrows == 1 and ncols == 1:\n",
    "        axes = [axes]\n",
    "    else:\n",
    "        axes = np.array(axes).flatten()\n",
    "\n",
    "    for i, (ax, img) in enumerate(zip(axes, images)):\n",
    "        ax.imshow(img)\n",
    "        ax.axis(\"off\")\n",
    "        if titles and i < len(titles):\n",
    "            ax.set_title(titles[i], fontsize=10)\n",
    "\n",
    "    # Hide empty subplots\n",
    "    for ax in axes[n:]:\n",
    "        ax.axis(\"off\")\n",
    "\n",
    "    plt.tight_layout()\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f825bf38",
   "metadata": {},
   "source": [
    "### Loading the Flickr8k Dataset\n",
    "\n",
    "We'll use the Flickr8k dataset throughout this practical. It contains 8,000 images\n",
    "with 5 captions each, making it ideal for learning multimodal alignment.\n",
    "\n",
    "### Loading Flickr8k Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c19ce613",
   "metadata": {},
   "outputs": [],
   "source": [
    "flickr_dataset = load_hf_dataset(\"jxie/flickr8k\")\n",
    "print(f\"Dataset splits: {list(flickr_dataset.keys())}\")\n",
    "print(\n",
    "    f\"Train: {len(flickr_dataset['train'])} | Val: {len(flickr_dataset['validation'])} | Test: {len(flickr_dataset['test'])}\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "540f6fa3",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Select sample images for visualization (use diverse samples from the dataset)\n",
    "n_samples = 16\n",
    "sample_indices = list(range(0, n_samples * 10, 10))  # Spread out samples\n",
    "sample_data = flickr_dataset[\"train\"].select(sample_indices)\n",
    "\n",
    "sample_images = [item[\"image\"] for item in sample_data]\n",
    "sample_captions = [item[\"caption_0\"] for item in sample_data]  # First caption of each\n",
    "\n",
    "# Display some sample images with their captions\n",
    "print(f\"Loaded {len(sample_images)} sample images\")\n",
    "display_images(\n",
    "    sample_images[:8], titles=[c[:40] + \"...\" for c in sample_captions[:8]], ncols=4\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf9f863a",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## Exercise 1: CLIP Embeddings and Zero-Shot Classification\n",
    "\n",
    "[CLIP](https://openai.com/research/clip) (Contrastive Language-Image Pre-training)\n",
    "learns to align images and text in a shared embedding space. This allows for\n",
    "powerful zero-shot capabilities: we can classify images using arbitrary text labels\n",
    "without any task-specific training.\n",
    "\n",
    "### How CLIP Works\n",
    "\n",
    "CLIP consists of two encoders:\n",
    "- **Image encoder**: A Vision Transformer (ViT) that produces image embeddings\n",
    "- **Text encoder**: A Transformer that produces text embeddings\n",
    "\n",
    "During training, CLIP learns to maximize the similarity between matching image-text\n",
    "pairs while minimizing similarity for non-matching pairs (contrastive learning with\n",
    "InfoNCE loss)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80a8a4db",
   "metadata": {},
   "source": [
    "### Load CLIP Model\n",
    "\n",
    "We'll use the base CLIP model (`openai/clip-vit-base-patch32`) which is lightweight\n",
    "enough to run on limited hardware (~600MB).\n",
    "\n",
    "### Loading CLIP Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "33e63cc0",
   "metadata": {},
   "outputs": [],
   "source": [
    "clip_model_name = \"openai/clip-vit-base-patch32\"\n",
    "clip_model = load_hf_model(clip_model_name, CLIPModel).to(device)\n",
    "clip_processor = load_hf_processor(clip_model_name, CLIPProcessor, use_fast=True)\n",
    "\n",
    "print(f\"Model: {clip_model_name}\")\n",
    "print(\n",
    "    f\"Image encoder parameters: {sum(p.numel() for p in clip_model.vision_model.parameters()):,}\"\n",
    ")\n",
    "print(\n",
    "    f\"Text encoder parameters: {sum(p.numel() for p in clip_model.text_model.parameters()):,}\"\n",
    ")\n",
    "print(f\"Embedding dimension: {clip_model.config.projection_dim}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6042a420",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Exercise 1.1: Computing CLIP Embeddings\n",
    "\n",
    "Let's compute embeddings for our sample images and some text descriptions.\n",
    "CLIP embeddings are normalized, so we can use cosine similarity (or just dot product)\n",
    "to measure similarity."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e809feca",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_image_embeddings(images: List[Image.Image], model, processor) -> torch.Tensor:\n",
    "    \"\"\"Compute CLIP embeddings for a list of images.\n",
    "\n",
    "    Args:\n",
    "        images: List of PIL images\n",
    "        model: CLIP model\n",
    "        processor: CLIP processor\n",
    "\n",
    "    Returns:\n",
    "        Normalized image embeddings of shape (n_images, embedding_dim)\n",
    "    \"\"\"\n",
    "    inputs = processor(images=images, return_tensors=\"pt\", padding=True).to(device)\n",
    "    with torch.no_grad():\n",
    "        embeddings = model.get_image_features(**inputs)\n",
    "    # Normalize embeddings\n",
    "    embeddings = F.normalize(embeddings, p=2, dim=-1)\n",
    "    return embeddings\n",
    "\n",
    "\n",
    "def get_text_embeddings(texts: List[str], model, processor) -> torch.Tensor:\n",
    "    \"\"\"Compute CLIP embeddings for a list of texts.\n",
    "\n",
    "    Args:\n",
    "        texts: List of text strings\n",
    "        model: CLIP model\n",
    "        processor: CLIP processor\n",
    "\n",
    "    Returns:\n",
    "        Normalized text embeddings of shape (n_texts, embedding_dim)\n",
    "    \"\"\"\n",
    "    # Compute text embeddings using the CLIP model\n",
    "    inputs = processor(text=texts, return_tensors=\"pt\", padding=True).to(device)\n",
    "    with torch.no_grad():\n",
    "        embeddings = model.get_text_features(**inputs)\n",
    "    embeddings = F.normalize(embeddings, p=2, dim=-1)\n",
    "    return embeddings\n",
    "\n",
    "\n",
    "# Test the functions\n",
    "test_image = sample_images[0]\n",
    "test_texts = [\"a photo of a cat\", \"a photo of a dog\"]\n",
    "\n",
    "img_emb = get_image_embeddings([test_image], clip_model, clip_processor)\n",
    "txt_emb = get_text_embeddings(test_texts, clip_model, clip_processor)\n",
    "\n",
    "print(f\"Image embedding shape: {img_emb.shape}\")\n",
    "print(f\"Text embedding shape: {txt_emb.shape}\")\n",
    "print(f\"Embedding dimension: {img_emb.shape[-1]}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0a1bbc6f",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### Exercise 1.2: Zero-Shot Image Classification\n",
    "\n",
    "With CLIP, we can classify images by computing the similarity between the image\n",
    "embedding and embeddings of candidate text labels. The label with highest similarity\n",
    "\"wins\"."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dd79d9bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "def zero_shot_classify(\n",
    "    image: Image.Image,\n",
    "    labels: List[str],\n",
    "    model,\n",
    "    processor,\n",
    "    prompt_template: str = \"a photo of a {}\",\n",
    ") -> Tuple[str, torch.Tensor]:\n",
    "    \"\"\"Classify an image using CLIP zero-shot classification.\n",
    "\n",
    "    Args:\n",
    "        image: PIL image to classify\n",
    "        labels: List of candidate labels\n",
    "        model: CLIP model\n",
    "        processor: CLIP processor\n",
    "        prompt_template: Template for creating text prompts (use {} for label)\n",
    "\n",
    "    Returns:\n",
    "        Tuple of (predicted label, probabilities for all labels)\n",
    "    \"\"\"\n",
    "    prompts = [prompt_template.format(label) for label in labels]\n",
    "\n",
    "    # Implement zero-shot classification\n",
    "\n",
    "    # 1. Create text prompts from labels using the template\n",
    "    # 2. Get image and text embeddings\n",
    "    # 3. Compute similarities (dot product since embeddings are normalized)\n",
    "    # 4. Convert to probabilities with softmax\n",
    "    # 5. Return the label with highest probability\n",
    "    assert False, 'Not implemented yet'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "813efaa8",
   "metadata": {},
   "source": [
    "### Zero-shot classification results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2ca4f8ab",
   "metadata": {},
   "outputs": [],
   "source": [
    "labels = [\"person\", \"dog\", \"cat\", \"child\", \"water\", \"beach\", \"grass\", \"building\"]\n",
    "\n",
    "for i, img in enumerate(sample_images[:4]):\n",
    "    pred_label, probs = zero_shot_classify(img, labels, clip_model, clip_processor)\n",
    "    caption_short = sample_captions[i][:30] + \"...\"\n",
    "    print(f\"Image {i}: {caption_short:35} -> {pred_label:10} ({probs.max():.2%})\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44c4e5c9",
   "metadata": {},
   "source": [
    "### Exercise 1.3: Prompt Engineering for Zero-Shot Classification\n",
    "\n",
    "The choice of prompt template significantly affects classification accuracy.\n",
    "Let's experiment with different templates.\n",
    "\n",
    "### Effect of prompt templates on classification"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "778bb5c8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Different prompt templates to try\n",
    "prompt_templates = [\n",
    "    \"a photo of a {}\",\n",
    "    \"a {}\",\n",
    "    \"an image of a {}\",\n",
    "    \"a photograph showing a {}\",\n",
    "    \"a picture of a {}\",\n",
    "]\n",
    "\n",
    "# Use first sample image for template comparison\n",
    "test_image = sample_images[0]\n",
    "labels = [\"person\", \"animal\", \"building\", \"nature\"]\n",
    "\n",
    "for template in prompt_templates:\n",
    "    pred_label, probs = zero_shot_classify(\n",
    "        test_image, labels, clip_model, clip_processor, prompt_template=template\n",
    "    )\n",
    "    print(f\"Template: '{template:30}' -> Best: {pred_label:10} ({probs.max():.2%})\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3e2cff3e",
   "metadata": {},
   "source": [
    "### Exercise 1.4: Visualizing the CLIP Embedding Space\n",
    "\n",
    "Let's visualize how images and their corresponding text descriptions are\n",
    "positioned in the CLIP embedding space using PCA."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fcd14922",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compute embeddings for sample images and their captions\n",
    "print(\"Computing embeddings for visualization...\")\n",
    "img_embeddings = get_image_embeddings(sample_images, clip_model, clip_processor)\n",
    "txt_embeddings = get_text_embeddings(sample_captions, clip_model, clip_processor)\n",
    "\n",
    "n_viz = len(sample_images)\n",
    "\n",
    "# Compute cosine similarity matrix between images and texts\n",
    "# This directly shows what CLIP learns: high similarity for matching pairs\n",
    "similarity_matrix = (img_embeddings @ txt_embeddings.T).cpu().numpy()\n",
    "\n",
    "# Plot similarity heatmap\n",
    "plt.figure(figsize=(10, 8))\n",
    "plt.imshow(similarity_matrix, cmap=\"viridis\", aspect=\"auto\")\n",
    "plt.colorbar(label=\"Cosine Similarity\")\n",
    "plt.xlabel(\"Caption Index\")\n",
    "plt.ylabel(\"Image Index\")\n",
    "plt.title(\"CLIP Image-Text Similarity Matrix\\n(Diagonal = matching pairs)\")\n",
    "\n",
    "# Add diagonal line to highlight matching pairs\n",
    "for i in range(n_viz):\n",
    "    plt.plot(i, i, \"rx\", markersize=10, markeredgewidth=2)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "\n",
    "# Print statistics\n",
    "diagonal_sim = np.diag(similarity_matrix)\n",
    "off_diagonal = similarity_matrix[~np.eye(n_viz, dtype=bool)]\n",
    "print(\"\\nSimilarity statistics:\")\n",
    "print(\n",
    "    f\"  Matching pairs (diagonal):     mean={diagonal_sim.mean():.3f}, std={diagonal_sim.std():.3f}\"\n",
    ")\n",
    "print(\n",
    "    f\"  Non-matching pairs:            mean={off_diagonal.mean():.3f}, std={off_diagonal.std():.3f}\"\n",
    ")\n",
    "print(\n",
    "    f\"  Separation (matching - other): {diagonal_sim.mean() - off_diagonal.mean():.3f}\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "53c28772",
   "metadata": {},
   "source": [
    "**Observation**: The similarity matrix shows CLIP's alignment: matching image-caption\n",
    "pairs (on the diagonal, marked with red X) have higher similarity than non-matching\n",
    "pairs. This is exactly what contrastive learning achieves - it brings matching pairs\n",
    "together in the embedding space while pushing non-matching pairs apart."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "68e96edd",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## Exercise 2: Building a Vision-Language Model\n",
    "\n",
    "Now that we understand how CLIP aligns images and text, let's build our own\n",
    "Vision-Language Model (VLM) for image captioning. We'll connect CLIP's vision\n",
    "encoder to a language model and train it to generate captions.\n",
    "\n",
    "### Architecture Overview\n",
    "\n",
    "Modern VLMs like LLaVA, Qwen-VL, and InstructBLIP follow a similar pattern:\n",
    "\n",
    "```\n",
    "┌─────────────────┐     ┌────────────────┐     ┌─────────────────┐\n",
    "│  Vision Encoder │────▶│   Projection   │────▶│      LLM        │\n",
    "│    (frozen)     │     │    + Prompts   │     │    (frozen)     │\n",
    "└─────────────────┘     └────────────────┘     └─────────────────┘\n",
    "     CLIP ViT           Trainable layers         Qwen/Llama/etc.\n",
    "```\n",
    "\n",
    "The key insight is that we only need to train a **projection layer** (and\n",
    "optionally **soft prompts**) to bridge the vision and language modalities.\n",
    "The heavy lifting is done by pre-trained models."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a6582301",
   "metadata": {},
   "source": [
    "### 2.1 Load the Language Model\n",
    "\n",
    "We'll use Qwen2.5-3B-Instruct as our language model. It's modern, capable,\n",
    "and fits comfortably on GPUs with 8-16GB VRAM.\n",
    "\n",
    "### Loading Language Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21ba894f",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm_model_name = \"Qwen/Qwen2.5-3B-Instruct\"\n",
    "\n",
    "\n",
    "# Load tokenizer\n",
    "llm_tokenizer = load_hf_tokenizer(llm_model_name, use_fast=True)\n",
    "if llm_tokenizer.pad_token is None:\n",
    "    llm_tokenizer.pad_token = llm_tokenizer.eos_token\n",
    "\n",
    "# Load model in half precision to save memory\n",
    "llm_model = load_hf_model(\n",
    "    llm_model_name,\n",
    "    AutoModelForCausalLM,\n",
    "    dtype=torch.float16,\n",
    "    device_map=device,\n",
    ")\n",
    "llm_model.eval()\n",
    "\n",
    "print(f\"Model: {llm_model_name}\")\n",
    "print(f\"Parameters: {sum(p.numel() for p in llm_model.parameters()):,}\")\n",
    "print(f\"Embedding dimension: {llm_model.config.hidden_size}\")\n",
    "print(f\"Vocabulary size: {llm_model.config.vocab_size}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ceb1058a",
   "metadata": {},
   "source": [
    "### 2.2 Understanding Visual Features\n",
    "\n",
    "Before building our projection, let's understand what CLIP's vision encoder outputs.\n",
    "The ViT processes images as a sequence of patches, similar to how text is a sequence of tokens."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee6423b9",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Get the hidden states from CLIP's vision encoder\n",
    "test_img = sample_images[0]\n",
    "inputs = clip_processor(images=test_img, return_tensors=\"pt\").to(device)\n",
    "\n",
    "with torch.no_grad():\n",
    "    vision_outputs = clip_model.vision_model(**inputs, output_hidden_states=True)\n",
    "\n",
    "# The output includes:\n",
    "# - last_hidden_state: (batch, num_patches + 1, hidden_dim) - +1 for CLS token\n",
    "# - pooler_output: (batch, hidden_dim) - the CLS token after projection\n",
    "\n",
    "print(\"CLIP Vision Encoder Output:\")\n",
    "print(f\"  Last hidden state shape: {vision_outputs.last_hidden_state.shape}\")\n",
    "print(f\"  Pooler output shape: {vision_outputs.pooler_output.shape}\")\n",
    "print(f\"  Number of patches: {vision_outputs.last_hidden_state.shape[1] - 1}\")\n",
    "print(f\"  CLIP hidden dimension: {vision_outputs.last_hidden_state.shape[-1]}\")\n",
    "print(f\"  LLM hidden dimension: {llm_model.config.hidden_size}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2dbd08ff",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### 2.3 Implement the Vision-Language Model\n",
    "\n",
    "We'll implement a VLM that:\n",
    "1. Extracts visual features using CLIP's vision encoder\n",
    "2. Projects them to the LLM's embedding space\n",
    "3. Adds learnable \"soft prompt\" tokens to help with modality alignment\n",
    "4. Concatenates visual tokens with text tokens for caption generation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "555cc782",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "class VisionLanguageModel(nn.Module):\n",
    "    \"\"\"A simple Vision-Language Model for image captioning.\n",
    "\n",
    "    Architecture:\n",
    "        Image -> CLIP ViT -> Projection MLP -> [Visual Tokens]\n",
    "                                                     |\n",
    "        [Soft Prompts] + [Visual Tokens] + [Text] -> LLM -> Caption\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(\n",
    "        self,\n",
    "        clip_model: CLIPModel,\n",
    "        llm_model: AutoModelForCausalLM,\n",
    "        llm_tokenizer: AutoTokenizer,\n",
    "        num_soft_prompts: int = 8,\n",
    "        projection_hidden_dim: int = None,\n",
    "    ):\n",
    "        super().__init__()\n",
    "\n",
    "        self.clip_vision = clip_model.vision_model\n",
    "        self.llm = llm_model\n",
    "        self.tokenizer = llm_tokenizer\n",
    "\n",
    "        # Implement the projection MLP\n",
    "\n",
    "        # Create a 2-layer MLP that maps from clip_hidden_dim to llm_hidden_dim\n",
    "        # Use GELU activation between layers\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        # Soft prompts: learnable tokens that help bridge modalities\n",
    "        # Initialize learnable soft prompt embeddings\n",
    "\n",
    "        # Create a learnable parameter of shape (num_soft_prompts, llm_hidden_dim)\n",
    "        # Initialize with small random values (std=0.02)\n",
    "        # Don't forget to freeze CLIP and LLM for now\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "    def get_visual_features(self, pixel_values: torch.Tensor) -> torch.Tensor:\n",
    "        \"\"\"Extract and project visual features from images.\n",
    "\n",
    "        Args:\n",
    "            pixel_values: Preprocessed images (batch, channels, height, width)\n",
    "\n",
    "        Returns:\n",
    "            Projected visual features (batch, num_patches, llm_hidden_dim)\n",
    "        \"\"\"\n",
    "        # Get CLIP vision features\n",
    "        with torch.no_grad():\n",
    "            vision_outputs = self.clip_vision(pixel_values)\n",
    "            # Use all patch tokens (exclude CLS token at position 0)\n",
    "            visual_features = vision_outputs.last_hidden_state[:, 1:, :]\n",
    "\n",
    "        # Project to LLM dimension\n",
    "        visual_features = self.projection(\n",
    "            visual_features.to(self.projection[0].weight.dtype)\n",
    "        )\n",
    "        return visual_features\n",
    "\n",
    "    def get_soft_prompts(self, batch_size: int) -> torch.Tensor:\n",
    "        \"\"\"Get soft prompts expanded for batch.\n",
    "\n",
    "        Args:\n",
    "            batch_size: Number of samples in batch\n",
    "\n",
    "        Returns:\n",
    "            Soft prompts (batch, num_soft_prompts, llm_hidden_dim)\n",
    "        \"\"\"\n",
    "        return self.soft_prompts.unsqueeze(0).expand(batch_size, -1, -1)\n",
    "\n",
    "    def forward(\n",
    "        self,\n",
    "        pixel_values: torch.Tensor,\n",
    "        input_ids: torch.Tensor,\n",
    "        attention_mask: torch.Tensor,\n",
    "        labels: Optional[torch.Tensor] = None,\n",
    "    ) -> dict:\n",
    "        \"\"\"Forward pass for training.\n",
    "\n",
    "        Args:\n",
    "            pixel_values: Preprocessed images\n",
    "            input_ids: Tokenized caption (without image tokens)\n",
    "            attention_mask: Attention mask for caption\n",
    "            labels: Labels for language modeling (shifted input_ids)\n",
    "\n",
    "        Returns:\n",
    "            Dictionary with loss and logits\n",
    "        \"\"\"\n",
    "        batch_size = pixel_values.shape[0]\n",
    "\n",
    "        # Get text embeddings from LLM (determines target dtype)\n",
    "        text_embeds = self.llm.get_input_embeddings()(input_ids)\n",
    "        target_dtype = text_embeds.dtype\n",
    "\n",
    "        # Get visual features and soft prompts (cast to match LLM dtype)\n",
    "        visual_features = self.get_visual_features(pixel_values).to(target_dtype)\n",
    "        soft_prompts = self.get_soft_prompts(batch_size).to(target_dtype)\n",
    "\n",
    "        # Concatenate: [soft_prompts, visual_features, text_embeds]\n",
    "        # Concatenate the embeddings in the correct order\n",
    "\n",
    "        # The sequence should be: soft prompts, then visual features, then text\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        return {\n",
    "            \"loss\": outputs.loss,\n",
    "            \"logits\": outputs.logits,\n",
    "        }\n",
    "\n",
    "    @torch.no_grad()\n",
    "    def generate(\n",
    "        self,\n",
    "        pixel_values: torch.Tensor,\n",
    "        max_new_tokens: int = 50,\n",
    "        temperature: float = 0.7,\n",
    "        top_p: float = 0.9,\n",
    "        do_sample: bool = True,\n",
    "    ) -> List[str]:\n",
    "        \"\"\"Generate captions for images.\n",
    "\n",
    "        Args:\n",
    "            pixel_values: Preprocessed images\n",
    "            max_new_tokens: Maximum tokens to generate\n",
    "            temperature: Sampling temperature\n",
    "            top_p: Nucleus sampling threshold\n",
    "            do_sample: Whether to use sampling (vs greedy)\n",
    "\n",
    "        Returns:\n",
    "            List of generated captions\n",
    "        \"\"\"\n",
    "        batch_size = pixel_values.shape[0]\n",
    "\n",
    "        # Add a prompt to guide generation (also determines target dtype)\n",
    "        prompt = \"This image shows\"\n",
    "        prompt_ids = self.tokenizer(prompt, return_tensors=\"pt\").input_ids.to(\n",
    "            pixel_values.device\n",
    "        )\n",
    "        prompt_embeds = self.llm.get_input_embeddings()(prompt_ids)\n",
    "        prompt_embeds = prompt_embeds.expand(batch_size, -1, -1)\n",
    "        target_dtype = prompt_embeds.dtype\n",
    "\n",
    "        # Get visual features and soft prompts (cast to match LLM dtype)\n",
    "        visual_features = self.get_visual_features(pixel_values).to(target_dtype)\n",
    "        soft_prompts = self.get_soft_prompts(batch_size).to(target_dtype)\n",
    "\n",
    "        # Concatenate: [soft_prompts, visual_features, prompt_embeds]\n",
    "        inputs_embeds = torch.cat([soft_prompts, visual_features, prompt_embeds], dim=1)\n",
    "\n",
    "        # Create attention mask\n",
    "        attention_mask = torch.ones(\n",
    "            batch_size, inputs_embeds.shape[1], device=pixel_values.device\n",
    "        )\n",
    "\n",
    "        # Generate\n",
    "        outputs = self.llm.generate(\n",
    "            inputs_embeds=inputs_embeds,\n",
    "            attention_mask=attention_mask,\n",
    "            max_new_tokens=max_new_tokens,\n",
    "            temperature=temperature if do_sample else 1.0,\n",
    "            top_p=top_p if do_sample else 1.0,\n",
    "            do_sample=do_sample,\n",
    "            pad_token_id=self.tokenizer.pad_token_id,\n",
    "            eos_token_id=self.tokenizer.eos_token_id,\n",
    "        )\n",
    "\n",
    "        # Decode (outputs include the prompt, so we take everything)\n",
    "        captions = []\n",
    "        for output in outputs:\n",
    "            caption = self.tokenizer.decode(output, skip_special_tokens=True)\n",
    "            # Prepend our prompt since it was in embeddings\n",
    "            caption = prompt + \" \" + caption\n",
    "            captions.append(caption)\n",
    "\n",
    "        return captions\n",
    "\n",
    "\n",
    "# Sanity checks for VisionLanguageModel implementation\n",
    "def test_vlm_implementation():\n",
    "    \"\"\"Verify student implementation of VisionLanguageModel.\"\"\"\n",
    "    # Create a minimal test instance\n",
    "    _vlm = VisionLanguageModel(\n",
    "        clip_model=clip_model,\n",
    "        llm_model=llm_model,\n",
    "        llm_tokenizer=llm_tokenizer,\n",
    "        num_soft_prompts=4,\n",
    "    )\n",
    "\n",
    "    # Test 1: Projection layer outputs correct dimension\n",
    "    _test_clip_features = torch.randn(2, 10, _vlm.clip_hidden_dim)\n",
    "    _projected = _vlm.projection(_test_clip_features)\n",
    "    assert (\n",
    "        _projected.shape[-1] == _vlm.llm_hidden_dim\n",
    "    ), f\"Projection output dim {_projected.shape[-1]} != LLM hidden dim {_vlm.llm_hidden_dim}\"\n",
    "\n",
    "    # Test 2: Soft prompts have correct shape\n",
    "    assert hasattr(_vlm, \"soft_prompts\"), \"Missing soft_prompts parameter\"\n",
    "    assert (\n",
    "        _vlm.soft_prompts.shape == (4, _vlm.llm_hidden_dim)\n",
    "    ), f\"Soft prompts shape {_vlm.soft_prompts.shape} != expected (4, {_vlm.llm_hidden_dim})\"\n",
    "\n",
    "    # Test 3: CLIP and LLM should be frozen\n",
    "    for param in _vlm.clip_vision.parameters():\n",
    "        assert not param.requires_grad, \"CLIP vision encoder should be frozen\"\n",
    "    for param in _vlm.llm.parameters():\n",
    "        assert not param.requires_grad, \"LLM should be frozen\"\n",
    "\n",
    "    # Test 4: Forward pass produces expected output structure\n",
    "    _test_image = clip_processor(\n",
    "        images=sample_images[0], return_tensors=\"pt\"\n",
    "    ).pixel_values\n",
    "    _test_ids = llm_tokenizer(\n",
    "        \"test caption\", return_tensors=\"pt\", padding=\"max_length\", max_length=10\n",
    "    )\n",
    "    _vlm = _vlm.to(device)\n",
    "    _outputs = _vlm(\n",
    "        pixel_values=_test_image.to(device),\n",
    "        input_ids=_test_ids.input_ids.to(device),\n",
    "        attention_mask=_test_ids.attention_mask.to(device),\n",
    "        labels=_test_ids.input_ids.to(device),\n",
    "    )\n",
    "    assert \"loss\" in _outputs, \"Forward pass must return 'loss'\"\n",
    "    assert \"logits\" in _outputs, \"Forward pass must return 'logits'\"\n",
    "    assert _outputs[\"loss\"] is not None, \"Loss should not be None when labels provided\"\n",
    "\n",
    "    print(\"✓ VisionLanguageModel implementation verified!\")\n",
    "\n",
    "\n",
    "test_vlm_implementation()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2312635a",
   "metadata": {},
   "source": [
    "### 2.4 Create the Model\n",
    "\n",
    "Let's instantiate our VLM and check the number of trainable parameters.\n",
    "\n",
    "### Creating Vision-Language Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42e037cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "vlm = VisionLanguageModel(\n",
    "    clip_model=clip_model,\n",
    "    llm_model=llm_model,\n",
    "    llm_tokenizer=llm_tokenizer,\n",
    "    num_soft_prompts=8,\n",
    ")\n",
    "vlm = vlm.to(device)\n",
    "\n",
    "# Count parameters\n",
    "total_params = sum(p.numel() for p in vlm.parameters())\n",
    "trainable_params = sum(p.numel() for p in vlm.parameters() if p.requires_grad)\n",
    "\n",
    "print(f\"Total parameters: {total_params:,}\")\n",
    "print(f\"Trainable parameters: {trainable_params:,}\")\n",
    "print(f\"Trainable ratio: {trainable_params / total_params:.2%}\")\n",
    "print(\"\\nTrainable components:\")\n",
    "print(f\"  - Projection MLP: {sum(p.numel() for p in vlm.projection.parameters()):,}\")\n",
    "print(f\"  - Soft prompts: {vlm.soft_prompts.numel():,}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dae9d3e6",
   "metadata": {},
   "source": [
    "### 2.5 Prepare Training Data\n",
    "\n",
    "We'll use subsets of the Flickr8k dataset (already loaded earlier) for training.\n",
    "\n",
    "### Preparing Training Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4e3bce69",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# For faster training, we'll use a subset\n",
    "train_size = 800\n",
    "val_size = 200\n",
    "\n",
    "\n",
    "# Use subsets of the official splits (flickr_dataset was loaded earlier)\n",
    "train_dataset = flickr_dataset[\"train\"].shuffle(seed=42).select(range(train_size))\n",
    "val_dataset = flickr_dataset[\"validation\"].shuffle(seed=42).select(range(val_size))\n",
    "\n",
    "print(f\"Training samples: {len(train_dataset)}\")\n",
    "print(f\"Validation samples: {len(val_dataset)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "482de59d",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### 2.6 Create Data Loaders\n",
    "\n",
    "We need to preprocess images with CLIP and tokenize captions for the LLM."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7512908d",
   "metadata": {},
   "outputs": [],
   "source": [
    "class CaptionDataset(torch.utils.data.Dataset):\n",
    "    \"\"\"Dataset for image captioning.\"\"\"\n",
    "\n",
    "    def __init__(self, hf_dataset, clip_processor, llm_tokenizer, max_length=64):\n",
    "        self.dataset = hf_dataset\n",
    "        self.clip_processor = clip_processor\n",
    "        self.llm_tokenizer = llm_tokenizer\n",
    "        self.max_length = max_length\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.dataset)\n",
    "\n",
    "    def __getitem__(self, idx):\n",
    "        sample = self.dataset[idx]\n",
    "\n",
    "        # Get image\n",
    "        image = sample[\"image\"]\n",
    "        if image.mode != \"RGB\":\n",
    "            image = image.convert(\"RGB\")\n",
    "\n",
    "        # Process image for CLIP\n",
    "        pixel_values = self.clip_processor(\n",
    "            images=image, return_tensors=\"pt\"\n",
    "        ).pixel_values.squeeze(0)\n",
    "\n",
    "        # Get caption (use first caption - dataset has caption_0 through caption_4)\n",
    "        caption = sample[\"caption_0\"]\n",
    "\n",
    "        # Tokenize caption\n",
    "        # We add EOS token to mark end of caption\n",
    "        caption_with_eos = caption + self.llm_tokenizer.eos_token\n",
    "        encoding = self.llm_tokenizer(\n",
    "            caption_with_eos,\n",
    "            max_length=self.max_length,\n",
    "            padding=\"max_length\",\n",
    "            truncation=True,\n",
    "            return_tensors=\"pt\",\n",
    "        )\n",
    "\n",
    "        input_ids = encoding.input_ids.squeeze(0)\n",
    "        attention_mask = encoding.attention_mask.squeeze(0)\n",
    "\n",
    "        # Labels are the same as input_ids (causal LM)\n",
    "        # We'll mask padding tokens with -100\n",
    "        labels = input_ids.clone()\n",
    "        labels[attention_mask == 0] = -100\n",
    "\n",
    "        return {\n",
    "            \"pixel_values\": pixel_values,\n",
    "            \"input_ids\": input_ids,\n",
    "            \"attention_mask\": attention_mask,\n",
    "            \"labels\": labels,\n",
    "        }\n",
    "\n",
    "\n",
    "# Create datasets and dataloaders\n",
    "train_caption_dataset = CaptionDataset(\n",
    "    train_dataset, clip_processor, llm_tokenizer, max_length=64\n",
    ")\n",
    "val_caption_dataset = CaptionDataset(\n",
    "    val_dataset, clip_processor, llm_tokenizer, max_length=64\n",
    ")\n",
    "\n",
    "batch_size = 4  # Adjust based on your GPU memory\n",
    "\n",
    "\n",
    "train_loader = DataLoader(\n",
    "    train_caption_dataset,\n",
    "    batch_size=batch_size,\n",
    "    shuffle=True,\n",
    "    num_workers=0,\n",
    ")\n",
    "val_loader = DataLoader(\n",
    "    val_caption_dataset,\n",
    "    batch_size=batch_size,\n",
    "    shuffle=False,\n",
    "    num_workers=0,\n",
    ")\n",
    "\n",
    "print(f\"Training batches: {len(train_loader)}\")\n",
    "print(f\"Validation batches: {len(val_loader)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1cffe646",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "### 2.7 Training Loop\n",
    "\n",
    "Now let's train our model! We'll only update the projection layer and soft prompts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc1b1d46",
   "metadata": {},
   "outputs": [],
   "source": [
    "def train_epoch(model, dataloader, optimizer, device):\n",
    "    \"\"\"Train for one epoch.\"\"\"\n",
    "    model.train()\n",
    "    total_loss = 0\n",
    "    num_batches = 0\n",
    "\n",
    "    pbar = tqdm(dataloader, desc=\"Training\")\n",
    "    for batch in pbar:\n",
    "        # Move batch to device\n",
    "        pixel_values = batch[\"pixel_values\"].to(device)\n",
    "        input_ids = batch[\"input_ids\"].to(device)\n",
    "        attention_mask = batch[\"attention_mask\"].to(device)\n",
    "        labels = batch[\"labels\"].to(device)\n",
    "\n",
    "        # Forward pass\n",
    "        # Implement the forward pass and compute the loss\n",
    "\n",
    "        # Call model() with pixel_values, input_ids, attention_mask, labels\n",
    "        # Extract the loss from the outputs dictionary\n",
    "        assert False, 'Not implemented yet'\n",
    "\n",
    "\n",
    "        # Backward pass\n",
    "        optimizer.zero_grad()\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "\n",
    "        total_loss += loss.item()\n",
    "        num_batches += 1\n",
    "\n",
    "        # Update progress bar with running loss\n",
    "        pbar.set_postfix({\"loss\": f\"{total_loss / num_batches:.4f}\"})\n",
    "\n",
    "    return total_loss / num_batches\n",
    "\n",
    "\n",
    "@torch.no_grad()\n",
    "def evaluate(model, dataloader, device):\n",
    "    \"\"\"Evaluate the model.\"\"\"\n",
    "    model.eval()\n",
    "    total_loss = 0\n",
    "    num_batches = 0\n",
    "\n",
    "    for batch in tqdm(dataloader, desc=\"Evaluating\"):\n",
    "        pixel_values = batch[\"pixel_values\"].to(device)\n",
    "        input_ids = batch[\"input_ids\"].to(device)\n",
    "        attention_mask = batch[\"attention_mask\"].to(device)\n",
    "        labels = batch[\"labels\"].to(device)\n",
    "\n",
    "        outputs = model(\n",
    "            pixel_values=pixel_values,\n",
    "            input_ids=input_ids,\n",
    "            attention_mask=attention_mask,\n",
    "            labels=labels,\n",
    "        )\n",
    "\n",
    "        total_loss += outputs[\"loss\"].item()\n",
    "        num_batches += 1\n",
    "\n",
    "    return total_loss / num_batches"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ad26974",
   "metadata": {},
   "source": [
    "### 2.8 Train the Model\n",
    "\n",
    "Let's train for a few epochs. With our small projection layer and soft prompts,\n",
    "training should be fast even on modest hardware.\n",
    "\n",
    "### Training Vision-Language Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "623693c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Training configuration\n",
    "num_epochs = 3\n",
    "learning_rate = 1e-4\n",
    "\n",
    "\n",
    "# Only optimize trainable parameters\n",
    "optimizer = torch.optim.AdamW(\n",
    "    [p for p in vlm.parameters() if p.requires_grad],\n",
    "    lr=learning_rate,\n",
    ")\n",
    "\n",
    "# Training loop\n",
    "train_losses = []\n",
    "val_losses = []\n",
    "\n",
    "for epoch in range(num_epochs):\n",
    "    print(f\"\\nEpoch {epoch + 1}/{num_epochs}\")\n",
    "\n",
    "    train_loss = train_epoch(vlm, train_loader, optimizer, device)\n",
    "    val_loss = evaluate(vlm, val_loader, device)\n",
    "\n",
    "    train_losses.append(train_loss)\n",
    "    val_losses.append(val_loss)\n",
    "\n",
    "    print(f\"  Train Loss: {train_loss:.4f}\")\n",
    "    print(f\"  Val Loss: {val_loss:.4f}\")\n",
    "\n",
    "# Plot training curves\n",
    "plt.figure(figsize=(8, 5))\n",
    "plt.plot(range(1, num_epochs + 1), train_losses, \"b-o\", label=\"Train Loss\")\n",
    "plt.plot(range(1, num_epochs + 1), val_losses, \"r-o\", label=\"Val Loss\")\n",
    "plt.xlabel(\"Epoch\")\n",
    "plt.ylabel(\"Loss\")\n",
    "plt.title(\"Training Progress\")\n",
    "plt.legend()\n",
    "plt.grid(True, alpha=0.3)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0679a765",
   "metadata": {},
   "source": [
    "### 2.9 Generate Captions\n",
    "\n",
    "Now let's use our trained model to generate captions for images!\n",
    "\n",
    "### Generating Captions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca660c57",
   "metadata": {},
   "outputs": [],
   "source": [
    "def generate_caption_for_image(model, image, clip_processor, device):\n",
    "    \"\"\"Generate a caption for a single image.\"\"\"\n",
    "    # Preprocess image\n",
    "    pixel_values = clip_processor(images=image, return_tensors=\"pt\").pixel_values\n",
    "    pixel_values = pixel_values.to(device)\n",
    "\n",
    "    # Generate\n",
    "    captions = model.generate(\n",
    "        pixel_values,\n",
    "        max_new_tokens=50,\n",
    "        temperature=0.7,\n",
    "        do_sample=True,\n",
    "    )\n",
    "    return captions[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9e585243",
   "metadata": {},
   "source": [
    "### Generated captions for sample images"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0fa2b317",
   "metadata": {},
   "outputs": [],
   "source": [
    "num_samples_to_show = 6\n",
    "\n",
    "\n",
    "for i, img in enumerate(sample_images[:num_samples_to_show]):\n",
    "    caption = generate_caption_for_image(vlm, img, clip_processor, device)\n",
    "    print(f\"\\n[Image {i}] Ground truth: {sample_captions[i][:50]}...\")\n",
    "    print(f\"  Generated: {caption}\")\n",
    "\n",
    "# Display images with their generated captions\n",
    "num_display = 4\n",
    "\n",
    "\n",
    "display_images(\n",
    "    sample_images[:num_display],\n",
    "    titles=[\n",
    "        generate_caption_for_image(vlm, img, clip_processor, device)[:50] + \"...\"\n",
    "        for img in sample_images[:num_display]\n",
    "    ],\n",
    "    ncols=2,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b82f80c1",
   "metadata": {},
   "source": [
    "### 2.10 Compare with Greedy vs Sampling\n",
    "\n",
    "Let's compare different generation strategies.\n",
    "\n",
    "### Comparing generation strategies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "66b1b0cd",
   "metadata": {},
   "outputs": [],
   "source": [
    "test_img = sample_images[5]  # Use a different sample image\n",
    "display_images([test_img], titles=[\"Test image\"])\n",
    "\n",
    "# Greedy decoding\n",
    "pixel_values = clip_processor(images=test_img, return_tensors=\"pt\").pixel_values.to(\n",
    "    device\n",
    ")\n",
    "\n",
    "greedy_caption = vlm.generate(\n",
    "    pixel_values,\n",
    "    max_new_tokens=50,\n",
    "    do_sample=False,\n",
    ")[0]\n",
    "print(f\"\\nGreedy: {greedy_caption}\")\n",
    "\n",
    "# Sampling with different temperatures\n",
    "temperatures = [0.5, 0.7, 1.0]\n",
    "\n",
    "\n",
    "for temp in temperatures:\n",
    "    caption = vlm.generate(\n",
    "        pixel_values,\n",
    "        max_new_tokens=50,\n",
    "        temperature=temp,\n",
    "        do_sample=True,\n",
    "    )[0]\n",
    "    print(f\"Sampling (T={temp}): {caption}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "68e74b4a",
   "metadata": {},
   "source": [
    "### 2.11 Understanding Soft Prompts (Prompt Tuning)\n",
    "\n",
    "Let's visualize what our soft prompts have learned by looking at their similarity\n",
    "to vocabulary tokens.\n",
    "\n",
    "### Analyzing Soft Prompts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "653b49ce",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get the LLM's embedding matrix\n",
    "embedding_matrix = (\n",
    "    llm_model.get_input_embeddings().weight.data\n",
    ")  # (vocab_size, hidden_dim)\n",
    "\n",
    "# Compute similarity between soft prompts and vocabulary embeddings\n",
    "soft_prompt_embeds = vlm.soft_prompts.data  # (num_prompts, hidden_dim)\n",
    "\n",
    "# Normalize for cosine similarity\n",
    "embedding_matrix_norm = F.normalize(embedding_matrix.float(), dim=-1)\n",
    "soft_prompt_norm = F.normalize(soft_prompt_embeds.float(), dim=-1)\n",
    "\n",
    "# Compute similarities\n",
    "similarities = soft_prompt_norm @ embedding_matrix_norm.T  # (num_prompts, vocab_size)\n",
    "\n",
    "# Find the most similar tokens for each soft prompt\n",
    "print(\"Most similar vocabulary tokens to each soft prompt:\")\n",
    "print(\"-\" * 50)\n",
    "\n",
    "for i in range(vlm.num_soft_prompts):\n",
    "    top_k = 5\n",
    "    top_similarities, top_indices = similarities[i].topk(top_k)\n",
    "\n",
    "    tokens = [llm_tokenizer.decode([idx.item()]) for idx in top_indices]\n",
    "    sims = [f\"{s.item():.3f}\" for s in top_similarities]\n",
    "\n",
    "    print(f\"Soft prompt {i}: {list(zip(tokens, sims))}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96cc71fc",
   "metadata": {},
   "source": [
    "**Interpretation**: The soft prompts learn to represent concepts that help bridge\n",
    "the visual and language modalities. They often correspond to words related to\n",
    "visual description, image content, or scene understanding."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48787c63",
   "metadata": {},
   "source": [
    "### Exercise 2.12: Experiment with Different Configurations\n",
    "\n",
    "Try modifying the model configuration and observe the effects:\n",
    "\n",
    "1. **Number of soft prompts**: Try `num_soft_prompts=4` vs `num_soft_prompts=16`\n",
    "2. **Projection architecture**: Try a deeper MLP or a single linear layer\n",
    "3. **Visual tokens**: Currently we use patch tokens. Try using only the CLS token\n",
    "4. **Learning rate**: Experiment with different learning rates"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "notebook_metadata_filter": "metadata"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "metadata": {
   "practical_name": "Multimodal LLMs"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
