""" ClipCap — Image Captioning with CLIP Prefix + frozen GPT-2 Large. Gradio app for Hugging Face Spaces. Model definition and inference logic are taken verbatim from the project's clipcap-test.ipynb so behaviour exactly matches the notebook. Only the mapping network is loaded from the checkpoint; CLIP (ViT-B/32) and GPT-2 Large download from their hubs on first run. """ import torch import torch.nn as nn import clip import gradio as gr from PIL import Image from transformers import GPT2LMHeadModel, GPT2Tokenizer from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware import uvicorn device = torch.device("cuda" if torch.cuda.is_available() else "cpu") CHECKPOINT_PATH = "best_model_slim.pt" # ────────────────────────────────────────────────────────────────────────── # Mapping network (verbatim from clipcap-test.ipynb) # ────────────────────────────────────────────────────────────────────────── class TransformerMappingNetwork(nn.Module): """Maps CLIP embeddings to GPT-2 prefix embeddings using a Transformer.""" def __init__(self, clip_dim: int, gpt_dim: int, prefix_length: int, num_heads: int = 8, num_layers: int = 8): super().__init__() self.prefix_length = prefix_length self.clip_projection = nn.Linear(clip_dim, gpt_dim) self.constant_input = nn.Parameter(torch.randn(prefix_length, gpt_dim)) encoder_layer = nn.TransformerEncoderLayer( d_model=gpt_dim, nhead=num_heads, dim_feedforward=gpt_dim * 4, dropout=0.1, activation='gelu', batch_first=True ) self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers) self.norm = nn.LayerNorm(gpt_dim) def forward(self, clip_embedding: torch.Tensor) -> torch.Tensor: batch_size = clip_embedding.shape[0] clip_projected = self.clip_projection(clip_embedding).unsqueeze(1) constant = self.constant_input.unsqueeze(0).expand(batch_size, -1, -1) x = torch.cat([clip_projected, constant], dim=1) x = self.transformer(x) x = self.norm(x) prefix = x[:, 1:, :] return prefix # ────────────────────────────────────────────────────────────────────────── # Full model (verbatim from clipcap-test.ipynb) # ────────────────────────────────────────────────────────────────────────── class CLIPPrefixCaptioning(nn.Module): """Full CLIP Prefix Captioning model with frozen LM.""" def __init__(self, prefix_length: int = 10, clip_model_name: str = "ViT-B/32", num_heads: int = 8, num_layers: int = 8): super().__init__() self.prefix_length = prefix_length self.clip_model, self.clip_preprocess = clip.load(clip_model_name, device="cpu") for param in self.clip_model.parameters(): param.requires_grad = False clip_dim = self.clip_model.visual.output_dim self.gpt2 = GPT2LMHeadModel.from_pretrained("gpt2-large") for param in self.gpt2.parameters(): param.requires_grad = False gpt_dim = self.gpt2.config.n_embd self.mapping_network = TransformerMappingNetwork( clip_dim=clip_dim, gpt_dim=gpt_dim, prefix_length=prefix_length, num_heads=num_heads, num_layers=num_layers ) self.tokenizer = GPT2Tokenizer.from_pretrained("gpt2-large") self.tokenizer.pad_token = self.tokenizer.eos_token def get_clip_embedding(self, images: torch.Tensor) -> torch.Tensor: with torch.no_grad(): clip_features = self.clip_model.encode_image(images).float() return clip_features @torch.no_grad() def generate(self, images: torch.Tensor, max_length: int = 50, beam_size: int = 5, temperature: float = 1.0): clip_embedding = self.get_clip_embedding(images) prefix = self.mapping_network(clip_embedding) batch_size = prefix.shape[0] captions = [] for i in range(batch_size): single_prefix = prefix[i].unsqueeze(0) if beam_size <= 1: caption = self._greedy_decode(single_prefix, max_length, temperature) else: caption = self._beam_search(single_prefix, max_length, beam_size) captions.append(caption) return captions def _greedy_decode(self, prefix, max_length, temperature): generated = prefix tokens = [] for _ in range(max_length): outputs = self.gpt2(inputs_embeds=generated) logits = outputs.logits[:, -1, :] / temperature next_token = logits.argmax(dim=-1) if next_token.item() == self.tokenizer.eos_token_id: break tokens.append(next_token.item()) next_embedding = self.gpt2.transformer.wte(next_token).unsqueeze(1) generated = torch.cat([generated, next_embedding], dim=1) return self.tokenizer.decode(tokens, skip_special_tokens=True) def _beam_search(self, prefix, max_length, beam_size): beams = [(0.0, [], prefix)] completed = [] for _ in range(max_length): candidates = [] for log_prob, tokens, embeds in beams: outputs = self.gpt2(inputs_embeds=embeds) logits = outputs.logits[:, -1, :] log_probs = torch.log_softmax(logits, dim=-1).squeeze(0) top_log_probs, top_indices = log_probs.topk(beam_size) for j in range(beam_size): token_id = top_indices[j].item() new_log_prob = log_prob + top_log_probs[j].item() new_tokens = tokens + [token_id] if token_id == self.tokenizer.eos_token_id: completed.append((new_log_prob, new_tokens[:-1])) else: next_emb = self.gpt2.transformer.wte( top_indices[j].unsqueeze(0).unsqueeze(0) ) new_embeds = torch.cat([embeds, next_emb], dim=1) candidates.append((new_log_prob, new_tokens, new_embeds)) if not candidates: break candidates.sort(key=lambda x: x[0], reverse=True) beams = candidates[:beam_size] for log_prob, tokens, _ in beams: completed.append((log_prob, tokens)) best = max(completed, key=lambda x: x[0] / max(len(x[1]), 1)) return self.tokenizer.decode(best[1], skip_special_tokens=True) # ────────────────────────────────────────────────────────────────────────── # Load model once at startup # ────────────────────────────────────────────────────────────────────────── print("Loading model — this downloads CLIP + GPT-2 Large on first run...") model = CLIPPrefixCaptioning(prefix_length=10).to(device) checkpoint = torch.load(CHECKPOINT_PATH, map_location=device) model.mapping_network.load_state_dict(checkpoint["mapping_network_state_dict"]) model.eval() print(f"Loaded checkpoint (epoch {checkpoint.get('epoch', '?')}, " f"val_loss {checkpoint.get('val_loss', float('nan')):.4f})") # ────────────────────────────────────────────────────────────────────────── # Inference function for Gradio # ────────────────────────────────────────────────────────────────────────── def caption_image(pil_img, beam_size): if pil_img is None: return "Please upload an image." image = pil_img.convert("RGB") image_tensor = model.clip_preprocess(image).unsqueeze(0).to(device) captions = model.generate(image_tensor, beam_size=int(beam_size)) return captions[0] # ────────────────────────────────────────────────────────────────────────── # Gradio UI # ────────────────────────────────────────────────────────────────────────── demo = gr.Interface( fn=caption_image, inputs=[ gr.Image(type="pil", label="Upload an image"), gr.Slider(1, 5, value=3, step=1, label="Beam size (1 = greedy/fastest, 5 = best quality)"), ], outputs=gr.Textbox(label="Generated caption"), title="ClipCap — Image Captioning", description=( "Upload an image to generate a caption. Uses a CLIP visual encoder, a " "trained Transformer mapping network, and a frozen GPT-2 Large language model. " "Trained on Flickr8k — note it tends to describe scenes in terms of people/actions." ), examples=None, api_name="caption", # stable endpoint name → /caption ) # ────────────────────────────────────────────────────────────────────────── # Mount Gradio inside FastAPI so we can allow our site's origin (with credentials) # ────────────────────────────────────────────────────────────────────────── ALLOWED_ORIGINS = [ "https://YOUR-SITE.vercel.app", # ← your real deployed domain (add when you have it) "http://localhost:3000", # npm run dev "http://localhost:8000", # local python3 -m http.server test ] if __name__ == "__main__": demo.launch()