[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M74YDMB154SH4TSK3QQK9TA1":3,"skill-same:01M74YDMB154SH4TSK3QQK9TA1":68},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":30,"commitSha":31,"skillDirectory":32,"forksCount":33,"repositoryHtmlUrl":34,"repositoryHomepageUrl":35,"ownerHtmlUrl":36,"ownerBlogUrl":37,"ownerDescription":38,"updatedAt":39,"install":40,"resources":53},"01M74YDMB154SH4TSK3QQK9TA1","blip-2-vision-language",null,"Explains how to use Salesforce BLIP-2 (Q-Former bridging a frozen image encoder and an LLM such as OPT or FlanT5) through HuggingFace Transformers and LAVIS for image captioning, visual question answering, image-text matching, and feature extraction. Use when generating captions for images, building a VQA system, doing zero-shot image-text understanding without task-specific training, matching or retrieving images against text, or fitting a BLIP-2 model into limited GPU memory with INT8\u002FINT4 quantization. Prefer LLaVA or InstructBLIP for instruction-following multimodal chat, and CLIP for plain image-text similarity.","KalarisLabs\u002Fresearch-agent-skills","KalarisLabs","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F300878568?v=4","01M74Y7MT23GXXC56VM6TVSXZY","Kalarislabs","01M74Y7MTQM9REXZX4SNXWX95C",132,"MIT","https:\u002F\u002Fgithub.com\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fblip-2-vision-language\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: blip-2-vision-language\ndescription: Explains how to use Salesforce BLIP-2 (Q-Former bridging a frozen image encoder and an LLM such as OPT or FlanT5) through HuggingFace Transformers and LAVIS for image captioning, visual question answering, image-text matching, and feature extraction. Use when generating captions for images, building a VQA system, doing zero-shot image-text understanding without task-specific training, matching or retrieving images against text, or fitting a BLIP-2 model into limited GPU memory with INT8\u002FINT4 quantization. Prefer LLaVA or InstructBLIP for instruction-following multimodal chat, and CLIP for plain image-text similarity.\nlicense: MIT\nmetadata:\n  version: 1.0.0\n  category: multimodal-and-emerging\n  maintainer: Kalaris Labs\n  tags: Multimodal, Vision-Language, Image Captioning, VQA, Zero-Shot\n  dependencies: transformers>=4.30.0, torch>=1.10.0, Pillow\n---\n\n# BLIP-2: Vision-Language Pre-training\n\nComprehensive guide to using Salesforce's BLIP-2 for vision-language tasks with frozen image encoders and large language models.\n\n## When to use BLIP-2\n\n**Use BLIP-2 when:**\n- Need high-quality image captioning with natural descriptions\n- Building visual question answering (VQA) systems\n- Require zero-shot image-text understanding without task-specific training\n- Want to leverage LLM reasoning for visual tasks\n- Building multimodal conversational AI\n- Need image-text retrieval or matching\n\n**Key features:**\n- **Q-Former architecture**: Lightweight query transformer bridges vision and language\n- **Frozen backbone efficiency**: No need to fine-tune large vision\u002Flanguage models\n- **Multiple LLM backends**: OPT (2.7B, 6.7B) and FlanT5 (XL, XXL)\n- **Zero-shot capabilities**: Strong performance without task-specific training\n- **Efficient training**: Only trains Q-Former (~188M parameters)\n- **State-of-the-art results**: Beats larger models on VQA benchmarks\n\n**Use alternatives instead:**\n- **LLaVA**: For instruction-following multimodal chat\n- **InstructBLIP**: For improved instruction-following (BLIP-2 successor)\n- **GPT-4V\u002FClaude 3**: For production multimodal chat (proprietary)\n- **CLIP**: For simple image-text similarity without generation\n- **Flamingo**: For few-shot visual learning\n\n## Quick start\n\n### Installation\n\n```bash\n# HuggingFace Transformers (recommended)\npip install transformers accelerate torch Pillow\n\n# Or LAVIS library (Salesforce official)\npip install salesforce-lavis\n```\n\n### Basic image captioning\n\n```python\nimport torch\nfrom PIL import Image\nfrom transformers import Blip2Processor, Blip2ForConditionalGeneration\n\n# Load model and processor\nprocessor = Blip2Processor.from_pretrained(\"Salesforce\u002Fblip2-opt-2.7b\")\nmodel = Blip2ForConditionalGeneration.from_pretrained(\n    \"Salesforce\u002Fblip2-opt-2.7b\",\n    torch_dtype=torch.float16,\n    device_map=\"auto\"\n)\n\n# Load image\nimage = Image.open(\"photo.jpg\").convert(\"RGB\")\n\n# Generate caption\ninputs = processor(images=image, return_tensors=\"pt\").to(\"cuda\", torch.float16)\ngenerated_ids = model.generate(**inputs, max_new_tokens=50)\ncaption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]\nprint(caption)\n```\n\n### Visual question answering\n\n```python\n# Ask a question about the image\nquestion = \"What color is the car in this image?\"\n\ninputs = processor(images=image, text=question, return_tensors=\"pt\").to(\"cuda\", torch.float16)\ngenerated_ids = model.generate(**inputs, max_new_tokens=50)\nanswer = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]\nprint(answer)\n```\n\n### Using LAVIS library\n\n```python\nimport torch\nfrom lavis.models import load_model_and_preprocess\nfrom PIL import Image\n\n# Load model\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel, vis_processors, txt_processors = load_model_and_preprocess(\n    name=\"blip2_opt\",\n    model_type=\"pretrain_opt2.7b\",\n    is_eval=True,\n    device=device\n)\n\n# Process image\nimage = Image.open(\"photo.jpg\").convert(\"RGB\")\nimage = vis_processors[\"eval\"](image).unsqueeze(0).to(device)\n\n# Caption\ncaption = model.generate({\"image\": image})\nprint(caption)\n\n# VQA\nquestion = txt_processors[\"eval\"](\"What is in this image?\")\nanswer = model.generate({\"image\": image, \"prompt\": question})\nprint(answer)\n```\n\n## Core concepts\n\n### Architecture overview\n\n```\nBLIP-2 Architecture:\n┌─────────────────────────────────────────────────────────────┐\n│                        Q-Former                              │\n│  ┌─────────────────────────────────────────────────────┐    │\n│  │     Learned Queries (32 queries × 768 dim)          │    │\n│  └────────────────────────┬────────────────────────────┘    │\n│                           │                                  │\n│  ┌────────────────────────▼────────────────────────────┐    │\n│  │    Cross-Attention with Image Features               │    │\n│  └────────────────────────┬────────────────────────────┘    │\n│                           │                                  │\n│  ┌────────────────────────▼────────────────────────────┐    │\n│  │    Self-Attention Layers (Transformer)               │    │\n│  └────────────────────────┬────────────────────────────┘    │\n└───────────────────────────┼─────────────────────────────────┘\n                            │\n┌───────────────────────────▼─────────────────────────────────┐\n│  Frozen Vision Encoder    │      Frozen LLM                  │\n│  (ViT-G\u002F14 from EVA-CLIP) │      (OPT or FlanT5)            │\n└─────────────────────────────────────────────────────────────┘\n```\n\n### Model variants\n\n| Model | LLM Backend | Size | Use Case |\n|-------|-------------|------|----------|\n| `blip2-opt-2.7b` | OPT-2.7B | ~4GB | General captioning, VQA |\n| `blip2-opt-6.7b` | OPT-6.7B | ~8GB | Better reasoning |\n| `blip2-flan-t5-xl` | FlanT5-XL | ~5GB | Instruction following |\n| `blip2-flan-t5-xxl` | FlanT5-XXL | ~13GB | Best quality |\n\n### Q-Former components\n\n| Component | Description | Parameters |\n|-----------|-------------|------------|\n| Learned queries | Fixed set of learnable embeddings | 32 × 768 |\n| Image transformer | Cross-attention to vision features | ~108M |\n| Text transformer | Self-attention for text | ~108M |\n| Linear projection | Maps to LLM dimension | Varies |\n\n## Advanced usage\n\nDetails, code examples and parameter tables: [references\u002Fadvanced-usage-2.md](references\u002Fadvanced-usage-2.md). Read it when this step applies.\n\n## Common workflows\n\n### Workflow 1: Image captioning pipeline\n\n```python\nimport torch\nfrom PIL import Image\nfrom transformers import Blip2Processor, Blip2ForConditionalGeneration\nfrom pathlib import Path\n\nclass ImageCaptioner:\n    def __init__(self, model_name=\"Salesforce\u002Fblip2-opt-2.7b\"):\n        self.processor = Blip2Processor.from_pretrained(model_name)\n        self.model = Blip2ForConditionalGeneration.from_pretrained(\n            model_name,\n            torch_dtype=torch.float16,\n            device_map=\"auto\"\n        )\n\n    def caption(self, image_path: str, prompt: str = None) -> str:\n        image = Image.open(image_path).convert(\"RGB\")\n\n        if prompt:\n            inputs = self.processor(images=image, text=prompt, return_tensors=\"pt\")\n        else:\n            inputs = self.processor(images=image, return_tensors=\"pt\")\n\n        inputs = inputs.to(\"cuda\", torch.float16)\n\n        generated_ids = self.model.generate(\n            **inputs,\n            max_new_tokens=50,\n            num_beams=5\n        )\n\n        return self.processor.decode(generated_ids[0], skip_special_tokens=True)\n\n    def caption_batch(self, image_paths: list, prompt: str = None) -> list:\n        images = [Image.open(p).convert(\"RGB\") for p in image_paths]\n\n        if prompt:\n            inputs = self.processor(\n                images=images,\n                text=[prompt] * len(images),\n                return_tensors=\"pt\",\n                padding=True\n            )\n        else:\n            inputs = self.processor(images=images, return_tensors=\"pt\", padding=True)\n\n        inputs = inputs.to(\"cuda\", torch.float16)\n\n        generated_ids = self.model.generate(**inputs, max_new_tokens=50)\n        return self.processor.batch_decode(generated_ids, skip_special_tokens=True)\n\n# Usage\ncaptioner = ImageCaptioner()\n\n# Single image\ncaption = captioner.caption(\"photo.jpg\")\nprint(f\"Caption: {caption}\")\n\n# With prompt for style\ncaption = captioner.caption(\"photo.jpg\", \"a detailed description of\")\nprint(f\"Detailed: {caption}\")\n\n# Batch processing\ncaptions = captioner.caption_batch([\"img1.jpg\", \"img2.jpg\", \"img3.jpg\"])\nfor i, cap in enumerate(captions):\n    print(f\"Image {i+1}: {cap}\")\n```\n\n### Workflow 2: Visual Q&A system\n\n```python\nclass VisualQA:\n    def __init__(self, model_name=\"Salesforce\u002Fblip2-flan-t5-xl\"):\n        self.processor = Blip2Processor.from_pretrained(model_name)\n        self.model = Blip2ForConditionalGeneration.from_pretrained(\n            model_name,\n            torch_dtype=torch.float16,\n            device_map=\"auto\"\n        )\n        self.current_image = None\n        self.current_inputs = None\n\n    def set_image(self, image_path: str):\n        \"\"\"Load image for multiple questions.\"\"\"\n        self.current_image = Image.open(image_path).convert(\"RGB\")\n\n    def ask(self, question: str) -> str:\n        \"\"\"Ask a question about the current image.\"\"\"\n        if self.current_image is None:\n            raise ValueError(\"No image set. Call set_image() first.\")\n\n        # Format question for FlanT5\n        prompt = f\"Question: {question} Answer:\"\n\n        inputs = self.processor(\n            images=self.current_image,\n            text=prompt,\n            return_tensors=\"pt\"\n        ).to(\"cuda\", torch.float16)\n\n        generated_ids = self.model.generate(\n            **inputs,\n            max_new_tokens=50,\n            num_beams=5\n        )\n\n        return self.processor.decode(generated_ids[0], skip_special_tokens=True)\n\n    def ask_multiple(self, questions: list) -> dict:\n        \"\"\"Ask multiple questions about current image.\"\"\"\n        return {q: self.ask(q) for q in questions}\n\n# Usage\nvqa = VisualQA()\nvqa.set_image(\"scene.jpg\")\n\n# Ask questions\nprint(vqa.ask(\"What objects are in this image?\"))\nprint(vqa.ask(\"What is the weather like?\"))\nprint(vqa.ask(\"How many people are there?\"))\n\n# Batch questions\nresults = vqa.ask_multiple([\n    \"What is the main subject?\",\n    \"What colors are dominant?\",\n    \"Is this indoors or outdoors?\"\n])\n```\n\n### Workflow 3: Image search\u002Fretrieval\n\n```python\nimport torch\nimport numpy as np\nfrom PIL import Image\nfrom lavis.models import load_model_and_preprocess\n\nclass ImageSearchEngine:\n    def __init__(self):\n        self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n        self.model, self.vis_processors, self.txt_processors = load_model_and_preprocess(\n            name=\"blip2_feature_extractor\",\n            model_type=\"pretrain\",\n            is_eval=True,\n            device=self.device\n        )\n        self.image_features = []\n        self.image_paths = []\n\n    def index_images(self, image_paths: list):\n        \"\"\"Build index from images.\"\"\"\n        self.image_paths = image_paths\n\n        for path in image_paths:\n            image = Image.open(path).convert(\"RGB\")\n            image = self.vis_processors[\"eval\"](image).unsqueeze(0).to(self.device)\n\n            with torch.no_grad():\n                features = self.model.extract_features({\"image\": image}, mode=\"image\")\n                # Use projected features for matching\n                self.image_features.append(\n                    features.image_embeds_proj.mean(dim=1).cpu().numpy()\n                )\n\n        self.image_features = np.vstack(self.image_features)\n\n    def search(self, query: str, top_k: int = 5) -> list:\n        \"\"\"Search images by text query.\"\"\"\n        # Get text features\n        text = self.txt_processors[\"eval\"](query)\n        text_input = {\"text_input\": [text]}\n\n        with torch.no_grad():\n            text_features = self.model.extract_features(text_input, mode=\"text\")\n            text_embeds = text_features.text_embeds_proj[:, 0].cpu().numpy()\n\n        # Compute similarities\n        similarities = np.dot(self.image_features, text_embeds.T).squeeze()\n        top_indices = np.argsort(similarities)[::-1][:top_k]\n\n        return [(self.image_paths[i], similarities[i]) for i in top_indices]\n\n# Usage\nengine = ImageSearchEngine()\nengine.index_images([\"img1.jpg\", \"img2.jpg\", \"img3.jpg\", ...])\n\n# Search\nresults = engine.search(\"a sunset over the ocean\", top_k=5)\nfor path, score in results:\n    print(f\"{path}: {score:.3f}\")\n```\n\n## Output format\n\n### Generation output\n\n```python\n# Direct generation returns token IDs\ngenerated_ids = model.generate(**inputs, max_new_tokens=50)\n# Shape: [batch_size, sequence_length]\n\n# Decode to text\ntext = processor.batch_decode(generated_ids, skip_special_tokens=True)\n# Returns: list of strings\n```\n\n### Feature extraction output\n\n```python\n# Q-Former outputs\nfeatures = model.extract_features({\"image\": image}, mode=\"image\")\n\nfeatures.image_embeds          # [B, 32, 768] - Q-Former outputs\nfeatures.image_embeds_proj     # [B, 32, 256] - Projected for matching\nfeatures.text_embeds          # [B, seq_len, 768] - Text features\nfeatures.text_embeds_proj     # [B, 256] - Projected text (CLS)\n```\n\n## Performance optimization\n\n### GPU memory requirements\n\n| Model | FP16 VRAM | INT8 VRAM | INT4 VRAM |\n|-------|-----------|-----------|-----------|\n| blip2-opt-2.7b | ~8GB | ~5GB | ~3GB |\n| blip2-opt-6.7b | ~16GB | ~9GB | ~5GB |\n| blip2-flan-t5-xl | ~10GB | ~6GB | ~4GB |\n| blip2-flan-t5-xxl | ~26GB | ~14GB | ~8GB |\n\n### Speed optimization\n\n```python\n# Use Flash Attention if available\nmodel = Blip2ForConditionalGeneration.from_pretrained(\n    \"Salesforce\u002Fblip2-opt-2.7b\",\n    torch_dtype=torch.float16,\n    attn_implementation=\"flash_attention_2\",  # Requires flash-attn\n    device_map=\"auto\"\n)\n\n# Compile model (PyTorch 2.0+)\nmodel = torch.compile(model)\n\n# Use smaller images (if quality allows)\nprocessor = Blip2Processor.from_pretrained(\"Salesforce\u002Fblip2-opt-2.7b\")\n# Default is 224x224, which is optimal\n```\n\n## Common issues\n\n| Issue | Solution |\n|-------|----------|\n| CUDA OOM | Use INT8\u002FINT4 quantization, smaller model |\n| Slow generation | Use greedy decoding, reduce max_new_tokens |\n| Poor captions | Try FlanT5 variant, use prompts |\n| Hallucinations | Lower temperature, use beam search |\n| Wrong answers | Rephrase question, provide context |\n\n## References\n\n- **[Advanced Usage](references\u002Fadvanced-usage.md)** - Fine-tuning, integration, deployment\n- **[Troubleshooting](references\u002Ftroubleshooting.md)** - Common issues and solutions\n\n## Resources\n\n- **Paper**: https:\u002F\u002Farxiv.org\u002Fabs\u002F2301.12597\n- **GitHub (LAVIS)**: https:\u002F\u002Fgithub.com\u002Fsalesforce\u002FLAVIS\n- **HuggingFace**: https:\u002F\u002Fhuggingface.co\u002FSalesforce\u002Fblip2-opt-2.7b\n- **Demo**: https:\u002F\u002Fhuggingface.co\u002Fspaces\u002FSalesforce\u002FBLIP2\n- **InstructBLIP**: https:\u002F\u002Farxiv.org\u002Fabs\u002F2305.06500 (successor)\n\n## Agent operating procedure\n\n1. **Check the environment.** Confirm GPU memory, model checkpoint and licence, framework versions and input formats.\n2. **Pin down the inputs.** Confirm formats, identifiers and parameters from the data or the user. Ask rather than guess any value that changes the result.\n3. **Run a small version first.** Run inference on a single sample at low resolution or short length first.\n4. **Execute the full task** using the instructions and references above.\n5. **Validate the result.** Inspect outputs qualitatively and with task metrics; check licence restrictions for generated content.\n6. **Report.** State what was run (versions, commands, parameters), what was checked, and what is still uncertain.\n\n| If this happens | Do this |\n|---|---|\n| Out-of-memory on large inputs | Reduce resolution or sequence length, use half precision, or tile the input. |\n| A function, flag or endpoint in these instructions is missing in the installed version | Check the installed version's own documentation (`help()`, `--help`, official docs), adapt, and tell the user. Never invent an API. |\n| A required input, identifier or parameter is ambiguous | Ask the user, or state the assumption explicitly before running. |\n\n**Integrity rules**\n\n- Never fabricate results, parameters, identifiers, citations or statistics. If something cannot be run or verified, say so plainly.\n- Check model and dataset licences before commercial or published use.\n- Treat version-specific details here as possibly outdated: confirm them against the official documentation for the installed version.\n- Ask before actions that cost money, consume shared GPUs or cloud quota, touch personal or patient data, or cannot be undone.\n\n## Related skills\n\n- `clip`: OpenAI's model connecting vision and language.\n- `llava`: Large Language and Vision Assistant.\n- `quantizing-models-bitsandbytes`: Quantizes LLMs to 8-bit or 4-bit for 50-75% memory reduction with minimal accuracy loss.\n","# BLIP-2: Vision-Language Pre-training\n\nComprehensive guide to using Salesforce's BLIP-2 for vision-language tasks with frozen image encoders and large language models.\n\n## When to use BLIP-2\n\n**Use BLIP-2 when:**\n- Need high-quality image captioning with natural descriptions\n- Building visual question answering (VQA) systems\n- Require zero-shot image-text understanding without task-specific training\n- Want to leverage LLM reasoning for visual tasks\n- Building multimodal conversational AI\n- Need image-text retrieval or matching\n\n**Key features:**\n- **Q-Former architecture**: Lightweight query transformer bridges vision and language\n- **Frozen backbone efficiency**: No need to fine-tune large vision\u002Flanguage models\n- **Multiple LLM backends**: OPT (2.7B, 6.7B) and FlanT5 (XL, XXL)\n- **Zero-shot capabilities**: Strong performance without task-specific training\n- **Efficient training**: Only trains Q-Former (~188M parameters)\n- **State-of-the-art results**: Beats larger models on VQA benchmarks\n\n**Use alternatives instead:**\n- **LLaVA**: For instruction-following multimodal chat\n- **InstructBLIP**: For improved instruction-following (BLIP-2 successor)\n- **GPT-4V\u002FClaude 3**: For production multimodal chat (proprietary)\n- **CLIP**: For simple image-text similarity without generation\n- **Flamingo**: For few-shot visual learning\n\n## Quick start\n\n### Installation\n\n```bash\n# HuggingFace Transformers (recommended)\npip install transformers accelerate torch Pillow\n\n# Or LAVIS library (Salesforce official)\npip install salesforce-lavis\n```\n\n### Basic image captioning\n\n```python\nimport torch\nfrom PIL import Image\nfrom transformers import Blip2Processor, Blip2ForConditionalGeneration\n\n# Load model and processor\nprocessor = Blip2Processor.from_pretrained(\"Salesforce\u002Fblip2-opt-2.7b\")\nmodel = Blip2ForConditionalGeneration.from_pretrained(\n    \"Salesforce\u002Fblip2-opt-2.7b\",\n    torch_dtype=torch.float16,\n    device_map=\"auto\"\n)\n\n# Load image\nimage = Image.open(\"photo.jpg\").convert(\"RGB\")\n\n# Generate caption\ninputs = processor(images=image, return_tensors=\"pt\").to(\"cuda\", torch.float16)\ngenerated_ids = model.generate(**inputs, max_new_tokens=50)\ncaption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]\nprint(caption)\n```\n\n### Visual question answering\n\n```python\n# Ask a question about the image\nquestion = \"What color is the car in this image?\"\n\ninputs = processor(images=image, text=question, return_tensors=\"pt\").to(\"cuda\", torch.float16)\ngenerated_ids = model.generate(**inputs, max_new_tokens=50)\nanswer = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]\nprint(answer)\n```\n\n### Using LAVIS library\n\n```python\nimport torch\nfrom lavis.models import load_model_and_preprocess\nfrom PIL import Image\n\n# Load model\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel, vis_processors, txt_processors = load_model_and_preprocess(\n    name=\"blip2_opt\",\n    model_type=\"pretrain_opt2.7b\",\n    is_eval=True,\n    device=device\n)\n\n# Process image\nimage = Image.open(\"photo.jpg\").convert(\"RGB\")\nimage = vis_processors[\"eval\"](image).unsqueeze(0).to(device)\n\n# Caption\ncaption = model.generate({\"image\": image})\nprint(caption)\n\n# VQA\nquestion = txt_processors[\"eval\"](\"What is in this image?\")\nanswer = model.generate({\"image\": image, \"prompt\": question})\nprint(answer)\n```\n\n## Core concepts\n\n### Architecture overview\n\n```\nBLIP-2 Architecture:\n┌─────────────────────────────────────────────────────────────┐\n│                        Q-Former                              │\n│  ┌─────────────────────────────────────────────────────┐    │\n│  │     Learned Queries (32 queries × 768 dim)          │    │\n│  └────────────────────────┬────────────────────────────┘    │\n│                           │                                  │\n│  ┌────────────────────────▼────────────────────────────┐    │\n│  │    Cross-Attention with Image Features               │    │\n│  └────────────────────────┬────────────────────────────┘    │\n│                           │                                  │\n│  ┌────────────────────────▼────────────────────────────┐    │\n│  │    Self-Attention Layers (Transformer)               │    │\n│  └────────────────────────┬────────────────────────────┘    │\n└───────────────────────────┼─────────────────────────────────┘\n                            │\n┌───────────────────────────▼─────────────────────────────────┐\n│  Frozen Vision Encoder    │      Frozen LLM                  │\n│  (ViT-G\u002F14 from EVA-CLIP) │      (OPT or FlanT5)            │\n└─────────────────────────────────────────────────────────────┘\n```\n\n### Model variants\n\n| Model | LLM Backend | Size | Use Case |\n|-------|-------------|------|----------|\n| `blip2-opt-2.7b` | OPT-2.7B | ~4GB | General captioning, VQA |\n| `blip2-opt-6.7b` | OPT-6.7B | ~8GB | Better reasoning |\n| `blip2-flan-t5-xl` | FlanT5-XL | ~5GB | Instruction following |\n| `blip2-flan-t5-xxl` | FlanT5-XXL | ~13GB | Best quality |\n\n### Q-Former components\n\n| Component | Description | Parameters |\n|-----------|-------------|------------|\n| Learned queries | Fixed set of learnable embeddings | 32 × 768 |\n| Image transformer | Cross-attention to vision features | ~108M |\n| Text transformer | Self-attention for text | ~108M |\n| Linear projection | Maps to LLM dimension | Varies |\n\n## Advanced usage\n\nDetails, code examples and parameter tables: [references\u002Fadvanced-usage-2.md](references\u002Fadvanced-usage-2.md). Read it when this step applies.\n\n## Common workflows\n\n### Workflow 1: Image captioning pipeline\n\n```python\nimport torch\nfrom PIL import Image\nfrom transformers import Blip2Processor, Blip2ForConditionalGeneration\nfrom pathlib import Path\n\nclass ImageCaptioner:\n    def __init__(self, model_name=\"Salesforce\u002Fblip2-opt-2.7b\"):\n        self.processor = Blip2Processor.from_pretrained(model_name)\n        self.model = Blip2ForConditionalGeneration.from_pretrained(\n            model_name,\n            torch_dtype=torch.float16,\n            device_map=\"auto\"\n        )\n\n    def caption(self, image_path: str, prompt: str = None) -> str:\n        image = Image.open(image_path).convert(\"RGB\")\n\n        if prompt:\n            inputs = self.processor(images=image, text=prompt, return_tensors=\"pt\")\n        else:\n            inputs = self.processor(images=image, return_tensors=\"pt\")\n\n        inputs = inputs.to(\"cuda\", torch.float16)\n\n        generated_ids = self.model.generate(\n            **inputs,\n            max_new_tokens=50,\n            num_beams=5\n        )\n\n        return self.processor.decode(generated_ids[0], skip_special_tokens=True)\n\n    def caption_batch(self, image_paths: list, prompt: str = None) -> list:\n        images = [Image.open(p).convert(\"RGB\") for p in image_paths]\n\n        if prompt:\n            inputs = self.processor(\n                images=images,\n                text=[prompt] * len(images),\n                return_tensors=\"pt\",\n                padding=True\n            )\n        else:\n            inputs = self.processor(images=images, return_tensors=\"pt\", padding=True)\n\n        inputs = inputs.to(\"cuda\", torch.float16)\n\n        generated_ids = self.model.generate(**inputs, max_new_tokens=50)\n        return self.processor.batch_decode(generated_ids, skip_special_tokens=True)\n\n# Usage\ncaptioner = ImageCaptioner()\n\n# Single image\ncaption = captioner.caption(\"photo.jpg\")\nprint(f\"Caption: {caption}\")\n\n# With prompt for style\ncaption = captioner.caption(\"photo.jpg\", \"a detailed description of\")\nprint(f\"Detailed: {caption}\")\n\n# Batch processing\ncaptions = captioner.caption_batch([\"img1.jpg\", \"img2.jpg\", \"img3.jpg\"])\nfor i, cap in enumerate(captions):\n    print(f\"Image {i+1}: {cap}\")\n```\n\n### Workflow 2: Visual Q&A system\n\n```python\nclass VisualQA:\n    def __init__(self, model_name=\"Salesforce\u002Fblip2-flan-t5-xl\"):\n        self.processor = Blip2Processor.from_pretrained(model_name)\n        self.model = Blip2ForConditionalGeneration.from_pretrained(\n            model_name,\n            torch_dtype=torch.float16,\n            device_map=\"auto\"\n        )\n        self.current_image = None\n        self.current_inputs = None\n\n    def set_image(self, image_path: str):\n        \"\"\"Load image for multiple questions.\"\"\"\n        self.current_image = Image.open(image_path).convert(\"RGB\")\n\n    def ask(self, question: str) -> str:\n        \"\"\"Ask a question about the current image.\"\"\"\n        if self.current_image is None:\n            raise ValueError(\"No image set. Call set_image() first.\")\n\n        # Format question for FlanT5\n        prompt = f\"Question: {question} Answer:\"\n\n        inputs = self.processor(\n            images=self.current_image,\n            text=prompt,\n            return_tensors=\"pt\"\n        ).to(\"cuda\", torch.float16)\n\n        generated_ids = self.model.generate(\n            **inputs,\n            max_new_tokens=50,\n            num_beams=5\n        )\n\n        return self.processor.decode(generated_ids[0], skip_special_tokens=True)\n\n    def ask_multiple(self, questions: list) -> dict:\n        \"\"\"Ask multiple questions about current image.\"\"\"\n        return {q: self.ask(q) for q in questions}\n\n# Usage\nvqa = VisualQA()\nvqa.set_image(\"scene.jpg\")\n\n# Ask questions\nprint(vqa.ask(\"What objects are in this image?\"))\nprint(vqa.ask(\"What is the weather like?\"))\nprint(vqa.ask(\"How many people are there?\"))\n\n# Batch questions\nresults = vqa.ask_multiple([\n    \"What is the main subject?\",\n    \"What colors are dominant?\",\n    \"Is this indoors or outdoors?\"\n])\n```\n\n### Workflow 3: Image search\u002Fretrieval\n\n```python\nimport torch\nimport numpy as np\nfrom PIL import Image\nfrom lavis.models import load_model_and_preprocess\n\nclass ImageSearchEngine:\n    def __init__(self):\n        self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n        self.model, self.vis_processors, self.txt_processors = load_model_and_preprocess(\n            name=\"blip2_feature_extractor\",\n            model_type=\"pretrain\",\n            is_eval=True,\n            device=self.device\n        )\n        self.image_features = []\n        self.image_paths = []\n\n    def index_images(self, image_paths: list):\n        \"\"\"Build index from images.\"\"\"\n        self.image_paths = image_paths\n\n        for path in image_paths:\n            image = Image.open(path).convert(\"RGB\")\n            image = self.vis_processors[\"eval\"](image).unsqueeze(0).to(self.device)\n\n            with torch.no_grad():\n                features = self.model.extract_features({\"image\": image}, mode=\"image\")\n                # Use projected features for matching\n                self.image_features.append(\n                    features.image_embeds_proj.mean(dim=1).cpu().numpy()\n                )\n\n        self.image_features = np.vstack(self.image_features)\n\n    def search(self, query: str, top_k: int = 5) -> list:\n        \"\"\"Search images by text query.\"\"\"\n        # Get text features\n        text = self.txt_processors[\"eval\"](query)\n        text_input = {\"text_input\": [text]}\n\n        with torch.no_grad():\n            text_features = self.model.extract_features(text_input, mode=\"text\")\n            text_embeds = text_features.text_embeds_proj[:, 0].cpu().numpy()\n\n        # Compute similarities\n        similarities = np.dot(self.image_features, text_embeds.T).squeeze()\n        top_indices = np.argsort(similarities)[::-1][:top_k]\n\n        return [(self.image_paths[i], similarities[i]) for i in top_indices]\n\n# Usage\nengine = ImageSearchEngine()\nengine.index_images([\"img1.jpg\", \"img2.jpg\", \"img3.jpg\", ...])\n\n# Search\nresults = engine.search(\"a sunset over the ocean\", top_k=5)\nfor path, score in results:\n    print(f\"{path}: {score:.3f}\")\n```\n\n## Output format\n\n### Generation output\n\n```python\n# Direct generation returns token IDs\ngenerated_ids = model.generate(**inputs, max_new_tokens=50)\n# Shape: [batch_size, sequence_length]\n\n# Decode to text\ntext = processor.batch_decode(generated_ids, skip_special_tokens=True)\n# Returns: list of strings\n```\n\n### Feature extraction output\n\n```python\n# Q-Former outputs\nfeatures = model.extract_features({\"image\": image}, mode=\"image\")\n\nfeatures.image_embeds          # [B, 32, 768] - Q-Former outputs\nfeatures.image_embeds_proj     # [B, 32, 256] - Projected for matching\nfeatures.text_embeds          # [B, seq_len, 768] - Text features\nfeatures.text_embeds_proj     # [B, 256] - Projected text (CLS)\n```\n\n## Performance optimization\n\n### GPU memory requirements\n\n| Model | FP16 VRAM | INT8 VRAM | INT4 VRAM |\n|-------|-----------|-----------|-----------|\n| blip2-opt-2.7b | ~8GB | ~5GB | ~3GB |\n| blip2-opt-6.7b | ~16GB | ~9GB | ~5GB |\n| blip2-flan-t5-xl | ~10GB | ~6GB | ~4GB |\n| blip2-flan-t5-xxl | ~26GB | ~14GB | ~8GB |\n\n### Speed optimization\n\n```python\n# Use Flash Attention if available\nmodel = Blip2ForConditionalGeneration.from_pretrained(\n    \"Salesforce\u002Fblip2-opt-2.7b\",\n    torch_dtype=torch.float16,\n    attn_implementation=\"flash_attention_2\",  # Requires flash-attn\n    device_map=\"auto\"\n)\n\n# Compile model (PyTorch 2.0+)\nmodel = torch.compile(model)\n\n# Use smaller images (if quality allows)\nprocessor = Blip2Processor.from_pretrained(\"Salesforce\u002Fblip2-opt-2.7b\")\n# Default is 224x224, which is optimal\n```\n\n## Common issues\n\n| Issue | Solution |\n|-------|----------|\n| CUDA OOM | Use INT8\u002FINT4 quantization, smaller model |\n| Slow generation | Use greedy decoding, reduce max_new_tokens |\n| Poor captions | Try FlanT5 variant, use prompts |\n| Hallucinations | Lower temperature, use beam search |\n| Wrong answers | Rephrase question, provide context |\n\n## References\n\n- **[Advanced Usage](references\u002Fadvanced-usage.md)** - Fine-tuning, integration, deployment\n- **[Troubleshooting](references\u002Ftroubleshooting.md)** - Common issues and solutions\n\n## Resources\n\n- **Paper**: https:\u002F\u002Farxiv.org\u002Fabs\u002F2301.12597\n- **GitHub (LAVIS)**: https:\u002F\u002Fgithub.com\u002Fsalesforce\u002FLAVIS\n- **HuggingFace**: https:\u002F\u002Fhuggingface.co\u002FSalesforce\u002Fblip2-opt-2.7b\n- **Demo**: https:\u002F\u002Fhuggingface.co\u002Fspaces\u002FSalesforce\u002FBLIP2\n- **InstructBLIP**: https:\u002F\u002Farxiv.org\u002Fabs\u002F2305.06500 (successor)\n\n## Agent operating procedure\n\n1. **Check the environment.** Confirm GPU memory, model checkpoint and licence, framework versions and input formats.\n2. **Pin down the inputs.** Confirm formats, identifiers and parameters from the data or the user. Ask rather than guess any value that changes the result.\n3. **Run a small version first.** Run inference on a single sample at low resolution or short length first.\n4. **Execute the full task** using the instructions and references above.\n5. **Validate the result.** Inspect outputs qualitatively and with task metrics; check licence restrictions for generated content.\n6. **Report.** State what was run (versions, commands, parameters), what was checked, and what is still uncertain.\n\n| If this happens | Do this |\n|---|---|\n| Out-of-memory on large inputs | Reduce resolution or sequence length, use half precision, or tile the input. |\n| A function, flag or endpoint in these instructions is missing in the installed version | Check the installed version's own documentation (`help()`, `--help`, official docs), adapt, and tell the user. Never invent an API. |\n| A required input, identifier or parameter is ambiguous | Ask the user, or state the assumption explicitly before running. |\n\n**Integrity rules**\n\n- Never fabricate results, parameters, identifiers, citations or statistics. If something cannot be run or verified, say so plainly.\n- Check model and dataset licences before commercial or published use.\n- Treat version-specific details here as possibly outdated: confirm them against the official documentation for the installed version.\n- Ask before actions that cost money, consume shared GPUs or cloud quota, touch personal or patient data, or cannot be undone.\n\n## Related skills\n\n- `clip`: OpenAI's model connecting vision and language.\n- `llava`: Large Language and Vision Assistant.\n- `quantizing-models-bitsandbytes`: Quantizes LLMs to 8-bit or 4-bit for 50-75% memory reduction with minimal accuracy loss.\n",{"name":5,"license":15,"metadata":24,"description":7},{"tags":25,"version":26,"category":27,"maintainer":28,"dependencies":29},"Multimodal, Vision-Language, Image Captioning, VQA, Zero-Shot","1.0.0","multimodal-and-emerging","Kalaris Labs","transformers>=4.30.0, torch>=1.10.0, Pillow","main","29fe36d26127205057d5e0ed8425f6b0e9a8c13a","skills\u002Fblip-2-vision-language",16,"https:\u002F\u002Fgithub.com\u002FKalarisLabs\u002Fresearch-agent-skills","https:\u002F\u002Fdocs.kalarislabs.com\u002Fresearch-agent-skills","https:\u002F\u002Fgithub.com\u002FKalarisLabs","kalarislabs.com","Applied AI lab building the infrastructure for the agentic era","2026-11-14 17:49:08",{"source":8,"skillName":5,"commands":41,"prompt":51,"zipAvailable":52},[42,45,48],{"tool":43,"command":44},"npx","npx skills add KalarisLabs\u002Fresearch-agent-skills --skill blip-2-vision-language",{"tool":46,"command":47},"bunx","bunx skills add KalarisLabs\u002Fresearch-agent-skills --skill blip-2-vision-language",{"tool":49,"command":50},"pnpm","pnpm dlx skills add KalarisLabs\u002Fresearch-agent-skills --skill blip-2-vision-language","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fblip-2-vision-language\u002FSKILL.md",true,[54,60,64],{"path":55,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":58,"sourceHtmlUrl":59},"references\u002Fadvanced-usage-2.md","REFERENCE","参考文档",3077,"https:\u002F\u002Fgithub.com\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fblip-2-vision-language\u002Freferences\u002Fadvanced-usage-2.md",{"path":61,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":62,"sourceHtmlUrl":63},"references\u002Fadvanced-usage.md",18889,"https:\u002F\u002Fgithub.com\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fblip-2-vision-language\u002Freferences\u002Fadvanced-usage.md",{"path":65,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":66,"sourceHtmlUrl":67},"references\u002Ftroubleshooting.md",11981,"https:\u002F\u002Fgithub.com\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fblip-2-vision-language\u002Freferences\u002Ftroubleshooting.md",[69,76,83,90,97,104],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M74Z8MGT305R11SNY5G28QH5","plos","Prepare manuscripts for PLOS journals (PLOS ONE, PLOS Biology, PLOS Computational Biology, PLOS Genetics, PLOS Medicine, PLOS Pathogens, PLOS Neglected Tropical Diseases, PLOS Global Public Health and others), covering structure, abstract and author summary, Vancouver-style references, the mandatory data availability policy, ethics and financial disclosure statements, figure requirements (PACE), the PLOS LaTeX template, reporting guidelines and PLOS ONE's publication criteria. Use when targeting any PLOS journal or checking compliance with PLOS policies.","https:\u002F\u002Fgithub.com\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fplos\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M74Z8CCN9APXYHNQ95V1EBGT","pkpd-modeling","Pharmacokinetic and pharmacodynamic modelling and simulation - non-compartmental analysis, compartmental and population PK, PK\u002FPD and exposure-response, TMDD, PBPK orientation, bioequivalence, allometric scaling and first-in-human dose, drug interaction prediction, and Bayesian therapeutic drug monitoring. Use when analysing concentration-time data, deriving exposure metrics, fitting PK or PD models, or evaluating dosing regimens. Triggers include \"pharmacokinetics\", \"pharmacodynamics\", \"PK\u002FPD\", \"NCA\", \"non-compartmental\", \"AUC\", \"Cmax\", \"lambda z\", \"half-life\", \"clearance\", \"volume of distribution\", \"compartmental model\", \"population PK\", \"popPK\", \"NONMEM\", \"nlmixr2\", \"Pharmpy\", \"Monolix\", \"exposure-response\", \"Emax\", \"EC50\", \"indirect response\", \"effect compartment\", \"TMDD\", \"PBPK\", \"bioequivalence\", \"RSABE\", \"ABEL\", \"allometric scaling\", \"first-in-human\", \"MABEL\", \"drug-drug interaction\", \"DDI\", \"ICH M12\", \"concentration-QTc\", \"therapeutic drug monitoring\", \"MIPD\", and \"dosing regimen\".","https:\u002F\u002Fgithub.com\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fpkpd-modeling\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M74Z86YHJJ1FM3X87BHN76KZ","pinecone","Guides use of Pinecone, a managed serverless vector database, through its Python client and the LangChain and LlamaIndex integrations. Covers creating indexes, upserting and querying vectors, metadata filtering, namespaces, hybrid dense and sparse search, index management, and deleting vectors. Use when building a production RAG system on a hosted vector store, adding semantic search or recommendations without running infrastructure, isolating per-user or per-tenant data with namespaces, combining dense and sparse vectors in one query, or filtering results by metadata. Do not use for self-hosted or local stores (Chroma, Weaviate) or offline similarity search (FAISS).","https:\u002F\u002Fgithub.com\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fpinecone\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M74Z80T6E89SAJ8MYDD0767Q","pi-agent","Build with and use Pi, the minimal terminal coding harness. Use for installing Pi, configuring providers\u002Fmodels\u002Fsettings\u002Fenvironment variables, creating Pi skills\u002Fextensions\u002Fpackages\u002Fthemes\u002Fprompt templates, embedding Pi through the SDK, integrating over RPC or JSON event streams, parsing sessions, running local models through the llama.cpp router, developing custom Pi providers and TUI components, or using ecosystem packages such as pi-subagents (delegation\u002Forchestration), pi-mcp-adapter (MCP servers), pi-interview (interactive forms), and pi-web-access (web search, fetching, video understanding).","https:\u002F\u002Fgithub.com\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fpi-agent\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":19},"01M74Z7WF1Y8Q3VFAQPPPRAFMV","phoenix-observability","Open-source AI observability platform for LLM tracing, evaluation, and monitoring. Use when debugging LLM applications with detailed traces, running evaluations on datasets, or monitoring production AI systems with real-time insights.","https:\u002F\u002Fgithub.com\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fphoenix-observability\u002FSKILL.md",[],[],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":19},"01M74Z7HNEH1A2AVYR3G1X2QV6","peft-fine-tuning","Fine-tunes LLMs with Hugging Face PEFT, using LoRA, QLoRA, IA3, AdaLoRA, prefix tuning, and prompt tuning so that under 1% of parameters are trained. Covers rank, alpha, and target module selection, loading and merging adapters, multi-adapter serving, and integration with TRL SFTTrainer, Axolotl, and vLLM. Use when fine-tuning 7B-70B models on limited GPU memory, when running QLoRA on a single 24GB GPU, when choosing LoRA rank and alpha, when merging or swapping adapters on one base model, or when debugging CUDA OOM or an adapter that does not apply. Not for full fine-tuning of small models under 1B parameters or cases needing all weights updated.","https:\u002F\u002Fgithub.com\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fblob\u002Fmain\u002Fskills\u002Fpeft-fine-tuning\u002FSKILL.md",[],[]]