InternVL-2B尝试

news2024/9/27 9:28:30

以最新的官方文档为准:https://internvl.readthedocs.io/en/latest/get_started/installation.html

一、环境配置

a. 下载InternVL完整的repo(无权重,空间占的不大)

git clone https://github.com/OpenGVLab/InternVL.git

b. 配置相关环境

cd InternVL

pip install -r requirements.txt

这一步大概率会下载到不匹配的torch和torchvision,自己按照cuda和显卡、py版本来。

我这边A100用的torch2.0.1+cuda118、torchvision0.15.2+cu118

pip install flash-attn==2.3.6 --no-build-isolation

c. 下载InternVL-2B的repo(4G+ 包含权重和代码和example)

mkdir pretrained
cd pretrained/
# pip install -U huggingface_hub

# Download OpenGVLab/InternVL2-2B
huggingface-cli download --resume-download --local-dir-use-symlinks False OpenGVLab/InternVL2-2B --local-dir InternVL2-2B

如果hf-cli不会用or安装失败 可以自行去hugging face搜索InternVL-2B安装或者上hf-mirror.com镜像站安装,这里不做阐述。有问题可以评论。

然后再InternVL大目录下应该是这样的:(我这里只下载了2B)

d. 安装InternVL-2B的相关环境

正常只需要安装这个transformers库

pip install transformers==4.37.2 

二、准备demo

利用这个脚本测试,注意修改path = 'OpenGVLab/InternVL2-8B'为InternVL-2B的路径。

这个脚本最好放在InternVL-2B目录下,这样输入的图像都在相对路径./examples中,否则也需要相应修改。

import numpy as np
import torch
import torchvision.transforms as T
from decord import VideoReader, cpu
from PIL import Image
from torchvision.transforms.functional import InterpolationMode
from transformers import AutoModel, AutoTokenizer

IMAGENET_MEAN = (0.485, 0.456, 0.406)
IMAGENET_STD = (0.229, 0.224, 0.225)

def build_transform(input_size):
    MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
    transform = T.Compose([
        T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
        T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
        T.ToTensor(),
        T.Normalize(mean=MEAN, std=STD)
    ])
    return transform

def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
    best_ratio_diff = float('inf')
    best_ratio = (1, 1)
    area = width * height
    for ratio in target_ratios:
        target_aspect_ratio = ratio[0] / ratio[1]
        ratio_diff = abs(aspect_ratio - target_aspect_ratio)
        if ratio_diff < best_ratio_diff:
            best_ratio_diff = ratio_diff
            best_ratio = ratio
        elif ratio_diff == best_ratio_diff:
            if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
                best_ratio = ratio
    return best_ratio

def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
    orig_width, orig_height = image.size
    aspect_ratio = orig_width / orig_height

    # calculate the existing image aspect ratio
    target_ratios = set(
        (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
        i * j <= max_num and i * j >= min_num)
    target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])

    # find the closest aspect ratio to the target
    target_aspect_ratio = find_closest_aspect_ratio(
        aspect_ratio, target_ratios, orig_width, orig_height, image_size)

    # calculate the target width and height
    target_width = image_size * target_aspect_ratio[0]
    target_height = image_size * target_aspect_ratio[1]
    blocks = target_aspect_ratio[0] * target_aspect_ratio[1]

    # resize the image
    resized_img = image.resize((target_width, target_height))
    processed_images = []
    for i in range(blocks):
        box = (
            (i % (target_width // image_size)) * image_size,
            (i // (target_width // image_size)) * image_size,
            ((i % (target_width // image_size)) + 1) * image_size,
            ((i // (target_width // image_size)) + 1) * image_size
        )
        # split the image
        split_img = resized_img.crop(box)
        processed_images.append(split_img)
    assert len(processed_images) == blocks
    if use_thumbnail and len(processed_images) != 1:
        thumbnail_img = image.resize((image_size, image_size))
        processed_images.append(thumbnail_img)
    return processed_images

def load_image(image_file, input_size=448, max_num=12):
    image = Image.open(image_file).convert('RGB')
    transform = build_transform(input_size=input_size)
    images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
    pixel_values = [transform(image) for image in images]
    pixel_values = torch.stack(pixel_values)
    return pixel_values

# If you have an 80G A100 GPU, you can put the entire model on a single GPU.
# Otherwise, you need to load a model using multiple GPUs, please refer to the `Multiple GPUs` section.
path = 'OpenGVLab/InternVL2-8B'
model = AutoModel.from_pretrained(
    path,
    torch_dtype=torch.bfloat16,
    low_cpu_mem_usage=True,
    use_flash_attn=True,
    trust_remote_code=True).eval().cuda()
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)

# set the max number of tiles in `max_num`
pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
generation_config = dict(max_new_tokens=1024, do_sample=False)

# pure-text conversation (纯文本对话)
question = 'Hello, who are you?'
response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
print(f'User: {question}\nAssistant: {response}')

question = 'Can you tell me a story?'
response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
print(f'User: {question}\nAssistant: {response}')

# single-image single-round conversation (单图单轮对话)
question = '<image>\nPlease describe the image shortly.'
response = model.chat(tokenizer, pixel_values, question, generation_config)
print(f'User: {question}\nAssistant: {response}')

# single-image multi-round conversation (单图多轮对话)
question = '<image>\nPlease describe the image in detail.'
response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
print(f'User: {question}\nAssistant: {response}')

question = 'Please write a poem according to the image.'
response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
print(f'User: {question}\nAssistant: {response}')

# multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)
pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)

question = '<image>\nDescribe the two images in detail.'
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
                               history=None, return_history=True)
print(f'User: {question}\nAssistant: {response}')

question = 'What are the similarities and differences between these two images.'
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
                               history=history, return_history=True)
print(f'User: {question}\nAssistant: {response}')

# multi-image multi-round conversation, separate images (多图多轮对话,独立图像)
pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]

question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
                               num_patches_list=num_patches_list,
                               history=None, return_history=True)
print(f'User: {question}\nAssistant: {response}')

question = 'What are the similarities and differences between these two images.'
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
                               num_patches_list=num_patches_list,
                               history=history, return_history=True)
print(f'User: {question}\nAssistant: {response}')

# batch inference, single image per sample (单图批处理)
pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)

questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
responses = model.batch_chat(tokenizer, pixel_values,
                             num_patches_list=num_patches_list,
                             questions=questions,
                             generation_config=generation_config)
for question, response in zip(questions, responses):
    print(f'User: {question}\nAssistant: {response}')

# video multi-round conversation (视频多轮对话)
def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
    if bound:
        start, end = bound[0], bound[1]
    else:
        start, end = -100000, 100000
    start_idx = max(first_idx, round(start * fps))
    end_idx = min(round(end * fps), max_frame)
    seg_size = float(end_idx - start_idx) / num_segments
    frame_indices = np.array([
        int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
        for idx in range(num_segments)
    ])
    return frame_indices

def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
    vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
    max_frame = len(vr) - 1
    fps = float(vr.get_avg_fps())

    pixel_values_list, num_patches_list = [], []
    transform = build_transform(input_size=input_size)
    frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
    for frame_index in frame_indices:
        img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')
        img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
        pixel_values = [transform(tile) for tile in img]
        pixel_values = torch.stack(pixel_values)
        num_patches_list.append(pixel_values.shape[0])
        pixel_values_list.append(pixel_values)
    pixel_values = torch.cat(pixel_values_list)
    return pixel_values, num_patches_list

video_path = './examples/red-panda.mp4'
pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)
pixel_values = pixel_values.to(torch.bfloat16).cuda()
video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
question = video_prefix + 'What is the red panda doing?'
# Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
                               num_patches_list=num_patches_list, history=None, return_history=True)
print(f'User: {question}\nAssistant: {response}')

question = 'Describe this video in detail. Don\'t repeat.'
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
                               num_patches_list=num_patches_list, history=history, return_history=True)
print(f'User: {question}\nAssistant: {response}')

这个demo有纯文本对话、输入单图单轮对话、输入单图多轮对话、输入多图多轮对话、输入视频对话等等。

正常运行后的效果:

显存占用20G不到。

三、finetune

提前准备好一些finetune的数据集,可以下载coco_caption数据集用。

## 到internvl_chat目录下
cd /InternVL/internvl_chat
## 官方给出了3个finetune的脚本参考 其中full finetune需要更多的资源和时间
## lora需要的资源和时间少 但是效果一般差一点
# Using 8 GPUs, fine-tune the full LLM, cost about 30G per GPU
GPUS=8 PER_DEVICE_BATCH_SIZE=1 sh shell/internvl2.0/2nd_finetune/internvl2_2b_internlm2_1_8b_dynamic_res_2nd_finetune_full.sh
# Using 2 GPUs, fine-tune the LoRA, cost about 27G per GPU
GPUS=2 PER_DEVICE_BATCH_SIZE=1 sh shell/internvl2.0/2nd_finetune/internvl2_2b_internlm2_1_8b_dynamic_res_2nd_finetune_lora.sh
# Using 8 GPUs, fine-tune the LoRA, cost about 27G per GPU
GPUS=8 PER_DEVICE_BATCH_SIZE=1 sh shell/internvl2.0/2nd_finetune/internvl2_2b_internlm2_1_8b_dynamic_res_2nd_finetune_lora.sh

记得修改.sh脚本里的一些路径。

todo

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2109850.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Shopee 9.9大促活动定档,下半年首个大促你报名了吗?

官方数据显示&#xff0c;2023年9.9大促期间&#xff0c;仅活动开始后的两个小时内&#xff0c;Shopee的跨境订单量就同比增长了12倍。而去年12.12大促期间&#xff0c;活动开始两小时内&#xff0c;Shopee的跨境订单量增长到了平时的17倍&#xff0c;Shopee Mall的订单量激增了…

iOS——方法交换Method Swizzing

什么是方法交换 Method Swizzing是发生在运行时的&#xff0c;主要用于在运行时将两个Method进行交换&#xff0c;我们可以将Method Swizzling代码写到任何地方&#xff0c;但是只有在这段Method Swilzzling代码执行完毕之后互换才起作用。 利用Objective-C Runtimee的动态绑定…

游戏录屏掉帧怎么办?有什么录屏软件推荐吗?

对于广大游戏爱好者来说&#xff0c;录制游戏精彩瞬间、分享攻略或制作教程已经成为一种常态。然而&#xff0c;在录屏过程中&#xff0c;不少玩家都会遇到掉帧的问题&#xff0c;这不仅影响了视频的流畅度&#xff0c;也大大降低了观看体验。那么&#xff0c;面对游戏录屏掉帧…

Linux学习之路 -- 信号的处理

前面介绍了信号的保存与产生的基本原理&#xff0c;下面介绍一下信号处理的相关知识。 1、信号何时被处理&#xff1f; 前面我们提到&#xff0c;信号在被进程接受后&#xff0c;不一定会被马上处理&#xff0c;而是要等到合适的时机才会被进程处理。而这个合适的时机其实就是…

Ubuntu22.04版本左右,开机自动启动脚本

Ubuntu22.04版本左右&#xff0c;开机自动启动脚本 1. 新增/lib/systemd/system/rc-local.service中[Install]内容 vim /lib/systemd/system/rc-local.service 按 i 进入插入模式后&#xff0c;新增内容如下&#xff1a; [Install] WantedBymulti-user.target Aliasrc-local.…

【LeetCode】01.两数之和

题目要求 做题链接&#xff1a;1.两数之和 解题思路 我们这道题是在nums数组中找到两个两个数使得他们的和为target&#xff0c;最简单的方法就是暴力枚举一遍即可&#xff0c;时间复杂度为O&#xff08;N&#xff09;&#xff0c;空间复杂度为O&#xff08;1&#xff09;。…

苹果qq文件过期了怎么恢复?简单4招,拯救你的过期文件

相较于微信而言&#xff0c;qq可以一次性发送数量较多且所占内存较大的文件。因此&#xff0c;较多用户都会选择使用qq来传输文件。但不可避免的是&#xff0c;我们有时也会遇到忘记下载文件&#xff0c;导致qq文件过期的情况&#xff0c;对此&#xff0c;该如何解决qq文件过期…

在NAS上打造AI加持的云端个人开发环境

作为一个有追求程序员&#xff0c;在工作之余有时也需要搞点开发&#xff0c;这时开发环境就成为一个有点棘手的问题。每个程序员都希望有一个长期的、稳定的开发环境&#xff0c;这样用起来才顺手。用工作电脑毕竟有不方便的方面&#xff0c;各种全家桶、监控、访问限制……总…

HTML 基本语法以及结构标签

1. HTML 基本语法 2. 标签关系 3. 基本结构标签 演示&#xff1a;打开页面&#xff0c;右击“打开源代码”&#xff08;CTRLU&#xff09;可以查看源代码; 4. VSCode 工具生成骨架标签 4.1 文档声明类型标签 注意&#xff1a; 4.2 lang 语言种类 4.3 字符集 4.4 总结

maven-helper插件解决jar包冲突实战

经常遇到jar包冲突问题&#xff0c;今天梳理一下&#xff1a; 1、打开idea 2、安装后 打开pom文件 点击 3、 4、 5、 6、 7、 8、 9、 可参考的类似文章

计数dp+组合数学,CF 213B - Numbers

目录 一、题目 1、题目描述 2、输入输出 2.1输入 2.2输出 3、原题链接 二、解题报告 1、思路分析 2、复杂度 3、代码详解 一、题目 1、题目描述 2、输入输出 2.1输入 2.2输出 3、原题链接 213B - Numbers 二、解题报告 1、思路分析 从0~9依次填写 对于0&#x…

[UVM]5.config机制 report 消息管理

1.config机制 &#xff08;1&#xff09;概述 SV只能例化后通过句柄访问&#xff0c;配置前必例化。 &#xff08;2&#xff09;uvm_config_db uvm_congfig_db就是关联数组&#xff0c;path和value组成。 传递配置对象&#xff08;config object&#xff09;就是传递句柄。 …

Ps:颜色模型、色彩空间及配置文件

颜色模型、色彩空间和配置文件是处理颜色的核心概念。它们虽然互相关联&#xff0c;但各自有不同的功能和作用。 通过理解这些概念及其关系&#xff0c;Photoshop 用户可以更好地管理和优化图像处理流程&#xff0c;确保颜色在不同设备和应用中的一致性和准确性。 颜色模型 Col…

ERP系统在IC设计行业的必要性

在当今这个科技日新月异的时代&#xff0c;集成电路(IC)设计行业作为信息技术发展的核心驱动力之一&#xff0c;正面临着前所未有的挑战与机遇。随着产品复杂度的提升、市场需求的快速变化以及全球供应链的紧密交织&#xff0c;如何高效管理设计资源、优化生产流程、提升响应速…

【Netty】实战:基于Http的Web服务器

目录 一、实现ChannelHandler 二、实现ChannelInitializer 三、实现服务器启动程序 四、测试 本文来实现一个简单的Web服务器&#xff0c;当用户在浏览器访问Web服务器时&#xff0c;可以返回响应的内容给用户。很简单&#xff0c;就三步。 一、实现ChannelHandler pack…

Spring之拦截器(HandlerInterceptor)

前言 在web开发中&#xff0c;拦截器是经常用到的功能&#xff0c;用于拦截请求进行预处理和后处理&#xff0c;一般用于以下场景&#xff1a; 日志记录&#xff0c;可以记录请求信息的日志&#xff0c;以便进行信息监控、信息统计、计算PV&#xff08;Page View&#xff09;等…

C++ 继承(二)

目录 1. 实现一个不能被继承的类 2. 友元与继承 3.继承与静态成员 4.多继承及其菱形继承问题 (1). 继承模型 (2). 虚继承 (2.1)虚继承解决数据冗余和二义性的原理 (3). 多继承中指针偏移问题 (4). IO库中的菱形虚拟继承 5. 继承和组合 1. 实现一个不能被继承的类 方法1…

内蒙古众壹集团:引领蒙东财税服务行业,成就企业发展新高度

内蒙古众壹企业管理集团有限公司自2019年成立以来&#xff0c;凭借卓越的服务和专业的团队&#xff0c;迅速成长为蒙东地区财税服务行业的先锋企业。 公司在成立初期&#xff0c;通过加盟慧算账平台&#xff0c;快速进入市场&#xff0c;并设立了多个分公司&#xff0c;逐步扩展…

Daily2:字体描边

有一个小的需求,需要对字体进行描边,一开始理解错了需求,以为要对字体镂空处理,然后尝试了许多做错了许多 后来发现是一个简单的描边处理,直接chatgpt就可以得出来一个简单的实现代码, class BorderTextView JvmOverloads constructor(context: Context, attrs: AttributeSet?…

读懂以太坊源码(3)-详细解析genesis.json

要想搞懂以太坊的源代码逻辑&#xff0c;必须要了解以太坊创世区块配置文件(genesis.json)的结构&#xff0c;以及每个配置参数的意义&#xff0c;创世配置文件&#xff0c;主要作用是设置链的ID&#xff0c;指定以太坊网络中硬分叉发生的区块高度&#xff0c;以及初始ETH数量的…