BLIP2 部署+测试, Lora训练打标

Blip2 部署+测试

本文主要阐述如何在本地部署运行BLIP2, 并使用BLIP2制作Lora训练数据的打标任务。

官网Salesforce/blip2-opt-2.7b | https://huggingface.co/Salesforce/blip2-opt-2.7b

部署环境

conda create -n blip2 python==3.10.14 -y
conda activate clip2
pip3 install torch==2.4.0 torchvision==0.19.0 --index-url https://download.pytorch.org/whl/cu124
pip install -r requirements.txt
transformers
pillow
requests
accelerate>=0.26.0

测试脚本

# vim main.py
# pip install accelerate
import requests
from PIL import Image
from transformers import Blip2Processor, Blip2ForConditionalGeneration

processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
model = Blip2ForConditionalGeneration.from_pretrained("Salesforce/blip2-opt-2.7b", device_map="auto")

img_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg' 
raw_image = Image.open(requests.get(img_url, stream=True).raw).convert('RGB')

inputs = processor(raw_image, return_tensors="pt").to("cuda")

out = model.generate(**inputs)
print(processor.decode(out[0], skip_special_tokens=True).strip())

打标代码,修改图片目录 path/to/your/images

import os
from PIL import Image
from transformers import Blip2Processor, Blip2ForConditionalGeneration

# Configuration for the image directory
config = {
    "image_dir": "path/to/your/images",  # Replace with your image directory
    "model_name": "Salesforce/blip2-opt-2.7b",
}

def load_image(image_path):
    """Load image from the given path."""
    if os.path.exists(image_path):
        return Image.open(image_path).convert('RGB')
    else:
        raise FileNotFoundError(f"Image not found at path: {image_path}")

def process_image(image, model, processor):
    """Process the image and question with the model."""
    inputs = processor(image, return_tensors="pt").to("cuda")
    out = model.generate(**inputs)
    return processor.decode(out[0], skip_special_tokens=True).strip()

def save_result(image_name, result, output_dir):
    """Save the result as a .txt file with the same name as the image."""
    txt_file_path = os.path.join(output_dir, f"{os.path.splitext(image_name)[0]}.txt")
    with open(txt_file_path, 'w') as file:
        file.write(result)

def main():
    # Load the processor and model
    processor = Blip2Processor.from_pretrained(config["model_name"])
    model = Blip2ForConditionalGeneration.from_pretrained(config["model_name"], device_map="auto")

    # Get the list of image files from the directory
    image_dir = config["image_dir"]
    output_dir = image_dir  # Save results in the same directory

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # Process each image in the directory
    for image_name in os.listdir(image_dir):
        if image_name.lower().endswith(('.png', '.jpg', '.jpeg')):
            image_path = os.path.join(image_dir, image_name)

            # Load the image
            try:
                image = load_image(image_path)
            except FileNotFoundError as e:
                print(e)
                continue

            # Process the image and get the result
            result = process_image(image, model, processor)

            # Save the result to a .txt file
            save_result(image_name, result, output_dir)
            print(f"Processed: {image_name} -> {result}")

if __name__ == "__main__":
    main()

### 如何部署BLIP-2模型 #### 准备环境 为了成功部署BLIP-2模型,需先准备好运行环境。这通常涉及安装必要的依赖项和库。对于BLIP及其变体(如BLIP-2),推荐使用Python虚拟环境来管理包版本,确保兼容性和稳定性[^3]。 #### 下载预训练模型 如果打算利用已有的BLIP-2训练成果,则应按照官方指导从指定位置下载对应的权重文件,并妥善存放在`models`目录内以便后续加载时能够顺利找到它们[^1]。 #### 安装LAVIS库 由于BLIP系列属于LAVIS的一部分,因此需要安装LAVIS库作为基础支持框架。可以通过pip命令轻松完成这一操作: ```bash pip install lavis ``` 此步骤简化了与BLIP交互的过程,提供了便捷的方法来进行推理、评估等工作流[^2]。 #### 加载并初始化模型实例 一旦上述准备工作就绪,在实际应用中就可以编写如下代码片段来创建一个BLIP-2对象: ```python from lavis.models import load_model_and_preprocess model, vis_processors, txt_processors = load_model_and_preprocess( name="blip2", model_type="pretrain", is_eval=True, device="cuda" ) ``` 这段脚本不仅会实例化所需的神经网络架构,还会自动应用适当的数据预处理逻辑,使得输入更加贴合预期格式要求。 #### 执行预测任务 最后一步就是向已经构建好的模型传递待分析的内容——无论是图片还是自然语言描述均可被接受。下面给出了一种可能的方式实现这一点: ```python image_path = "path/to/image.jpg" with open(image_path, 'rb') as f: raw_image_bytes = f.read() processed_image = vis_processors["eval"](raw_image_bytes).unsqueeze(0).to("cuda") caption = input("Enter a caption or question about the image:") text_input = txt_processors["eval"](caption) output = model({"image": processed_image, "text_input": text_input}) print(output) ``` 以上过程展示了如何基于给定提示生成相应的响应,或是针对上传的图像执行理解类的任务,比如问答或说明生成等。 #### 使用Docker镜像加速部署流程 考虑到某些场景下的特殊需求,采用容器化技术不失为一种高效途径。特别是当面对资源受限的情况时,预先打包好所有必需组件在内的docker镜像是明智之举。不过需要注意的是,共享此类镜像可能会受到平台政策的影响,具体方式可参照特定社区的规定行事[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

且漫CN

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值