AI知识库

53AI知识库

学习大模型的前沿技术与行业应用场景


InternVL2-4B微调记录
发布日期:2024-08-13 07:41:01 浏览次数: 1991



来源:single430 | 编辑:DeepLearning笔记

InternVL 2.0 超越了大多数开源模型。它在各种能力上表现出与闭源商业模型相媲美的竞争力,包括文档和图表理解、信息图表问答、场景文本理解和 OCR 任务、科学和数学问题解决,以及文化理解和综合多模态能力。

具体细节可以看这两篇文章:

InternVL系列:通过开源套件缩小与商业多模态模型的差距—成为GPT-4o的开创性开源替代方案

InternVL 2.0:多模态大模型新标杆

InternVL发布了多个版本,如下:

各位可以根据自己机器配置选择合适的版本做微调,此微调方法可切换任意版本模型。

首先下载模型到本地,各位可以从mdoelscope(需要注册)和HF下载(HF需要翻墙),不过也可以使用HF的镜像网站:https://hf-mirror.com/,具体下载命令如下:

pip install -U huggingface_hubLinux: export HF_ENDPOINT=https://hf-mirror.comWindows: $env:HF_ENDPOINT = "https://hf-mirror.com"
huggingface-cli download --local-dir-use-symlinks False --resume-download OpenGVLab/InternVL2-4B --local-dir OpenGVLab/InternVL2-4B

② 使用ms-swift进行微调,ms-swift已接入Internvl2系列模型,包括:Internvl2-2B, Internvl2-4B,Internvl2-8B,Internvl2-26B。命令安装:

# 设置pip全局镜像 (加速下载)pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/# 安装ms-swiftgit clone https://github.com/modelscope/swift.gitcd swiftpip install -e '.[llm]'

③ 数据集准备,这里可以替换自己的数据集,具体格式如下,保存为 jsonl,支持纯文本和视频,多图(后两个还没做测试)。
{"images": ["path/to/xxx.jpg"], "query": "描述图片内容", "response": "根据图片,里面xxx...", "history": [["query0", "response0"]]}{"query": "2+2等于多大", "response": "4", "history": [["query0", "response0"]]}{"images": ["path/to/xxx.jpg"], "query": "在以下图像中进行目标检测,并标出所有汽车。", "response": "<ref>汽车</ref><box>[[31, 530, 389, 944], [574, 533, 797, 875]]</box>", "history": []}

④ 微调命令如下,以下参数可以根据实际情况修改(CUDA_VISIBLE_DEVICES,batch_size,max_length等, model_type可以设置其它模型):

#!/bin/bash
export CUDA_VISIBLE_DEVICES=0,1
swift sft --model_type internvl2-4b \--model_id_or_path /path/to/InternVL2-4B \--gradient_checkpointing true \--custom_train_dataset_path /path/to/all_finetune_data_train_swift.jsonl \--custom_val_dataset_path /path/to/all_finetune_data_val_swift.jsonl \--batch_size 4 \--eval_batch_size 2 \--gradient_accumulation_steps 1 \--max_steps 20000 \--eval_steps 1000 \--save_steps 1000 \--learning_rate 1e-4 \--max_length 2048 \    --sft_type lora


⑤ 微调后推理:
# 直接推理CUDA_VISIBLE_DEVICES=0 swift infer \    --ckpt_dir output/internvl2-4b/vx-xxx/checkpoint-xxx \    --custom_val_dataset_path /path/to/all_finetune_data_val_swift.jsonl    # 合并后推理CUDA_VISIBLE_DEVICES=0 swift export \    --ckpt_dir output/internvl2-4b/vx-xxx/checkpoint-xxx \--merge_lora true
CUDA_VISIBLE_DEVICES=0 swift infer \    --ckpt_dir output/internvl2-4b/vx-xxx/checkpoint-xxx-merged \---custom_val_dataset_path /path/to/all_finetune_data_val_swift.jsonl

⑥ 快速调用
import numpy as npimport torchimport torchvision.transforms as Tfrom decord import VideoReader, cpufrom PIL import Imagefrom torchvision.transforms.functional import InterpolationModefrom 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_STDtransform = 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 * heightfor 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_diffbest_ratio = ratioelif ratio_diff == best_ratio_diff:if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:best_ratio = ratioreturn best_ratio

def dynamic_preprocess(image, min_num=1, max_num=6, image_size=448, use_thumbnail=False):orig_width, orig_height = image.sizeaspect_ratio = orig_width / orig_height
# calculate the existing image aspect ratiotarget_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) ifi * 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 targettarget_aspect_ratio = find_closest_aspect_ratio(aspect_ratio, target_ratios, orig_width, orig_height, image_size)
# calculate the target width and heighttarget_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 imageresized_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 imagesplit_img = resized_img.crop(box)processed_images.append(split_img)assert len(processed_images) == blocksif 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=6):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

path = 'output/internvl2-4b/vx-xxx/checkpoint-xxx-merged'model = AutoModel.from_pretrained(path,torch_dtype=torch.bfloat16,low_cpu_mem_usage=True,trust_remote_code=True).eval().cuda()
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)# set the max number of tiles in `max_num`pixel_values = load_image('./examples/image1.jpg', max_num=6).to(torch.bfloat16).cuda()
generation_config = dict(num_beams=1,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}')print(f'Assistant: {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}')print(f'Assistant: {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}')print(f'Assistant: {response}')
# single-image multi-round conversation (单图多轮对话)question = '<image>\n描述图片中的详细内容.'response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)print(f'User: {question}')print(f'Assistant: {response}')


⑦ 对于微调后部署问题,官方采用的时lmdeploy可以很友好的支持openai接口调用
1) 使用lmdeploy v0.5.0, 需要先设置chat template. 创建如下json文件chat_template.json{"model_name":"internlm2","meta_instruction":"你是由上海人工智能实验室开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。","stop_words":["<|im_start|>", "<|im_end|>"]}
2) 使用lmdeploy部署internvl的api服务lmdeploy serve api_server output/internvl2-4b/vx-xxx/checkpoint-xxx-merged --model-name InternVL2-4B --server-port 9433 --chat-template chat_template.json
3) 使用OpenAI样式接口需要安装OpenAIpip install openai
4) 接口调用from openai import OpenAI
client = OpenAI(api_key='可不填', base_url='http://0.0.0.0:9433/v1')model_name = client.models.list().data[0].idresponse = client.chat.completions.create(    model="InternVL2-4B",    messages=[{'role': 'user',    'content': [{    'type': 'text','text': '描述这幅画',        }, {'type': 'image_url','image_url': {'url':'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',            },}],    }],     temperature=0.8,top_p=0.8)print(response)


* 这里列举下InternVL训练时使用的数据集:

* 以及我对一些数据集的整理,各位可自行下载

* 部分标签文件这里下载

https://huggingface.co/OpenGVLab/InternVL/resolve/main/playground.zip
一:AI2D: ai2d_images (provided by InternLM-XComposer) -- 1.3GBhttps://drive.google.com/file/d/1dqqa3MnrxMXaU_K9JA6C83je32ibwdOY/view?usp=sharing
二:ChartQA: ChartQA Dataset800+MBhttps://huggingface.co/datasets/ahmed-masry/ChartQA/resolve/main/ChartQA%20Dataset.zip
三:COCO: train2017 18GBhttp://images.cocodataset.org/zips/train2017.zip
四:DocVQA: train 6.6GB, val 825MB, test 879MBhttps://datasets.cvc.uab.es/rrc/DocVQA/train.tar.gzhttps://datasets.cvc.uab.es/rrc/DocVQA/val.tar.gzhttps://datasets.cvc.uab.es/rrc/DocVQA/test.tar.gz
五:DVQA: images 5GBhttps://drive.google.com/file/d/1iKH2lTi1-QxtNUVRxTUWFvUvRHq6HAsZ/view
六:GQA: images 20.3GBhttps://downloads.cs.stanford.edu/nlp/data/gqa/images.zip
七:LLaVA-Pretrain: images 25.5GBhttps://huggingface.co/datasets/liuhaotian/LLaVA-Pretrain/resolve/main/images.zip
八:OCR-VQA(图像问答,书籍封面): download script. We save all files as .jpg 20GBhttps://drive.google.com/drive/folders/1_GYPY5UkUy7HIcR0zq3ZCFgeZN7BAfm_?usp=sharing
九:SAM: We only use 000000~000050.tar for now. You can quickly download 9K images from here. 8GBhttps://drive.google.com/file/d/1dKumdOKSXtV7lIXdrG7jsIK_z2vZv2gs/view?usp=drive_link
十:TextVQA: trainvalimages 6.6GBhttps://dl.fbaipublicfiles.com/textvqa/images/train_val_images.zip
十一:SynthDoG-EN(OCR数据集): We only use 00000~00004 parquet files for now, with a total of 30K images. We provide the converted images. 2.2GBhttps://huggingface.co/OpenGVLab/InternVL/resolve/main/synthdog-en-images.zip
十二:VisualGenome: part1 9.1GB, part2 5.1GBhttps://cs.stanford.edu/people/rak248/VG_100K_2/images.ziphttps://cs.stanford.edu/people/rak248/VG_100K_2/images2.zip
十三:WebData: images. Only for academic usage. 9GBhttps://drive.google.com/drive/folders/1tCUQ-sq6vdshZVkF0ZeF3K4eztkXJgax?usp=sharing
十四:GeoQA+(几何数学题): GeoQA+ images20MBhttps://drive.google.com/file/d/1KL4_wIzr3p8XSKMkkLgYcYwCbb0TzZ9O/viewhttps://huggingface.co/OpenGVLab/InternVL/resolve/main/geoqa%2B_images.zip


参考:

1. https://github.com/OpenGVLab/InternVL2. https://github.com/modelscope/swift3. https://mp.weixin.qq.com/s/OUaVLkxlk1zhFb1cvMCFjg


53AI,企业落地应用大模型首选服务商

产品:大模型应用平台+智能体定制开发+落地咨询服务

承诺:先做场景POC验证,看到效果再签署服务协议。零风险落地应用大模型,已交付160+中大型企业

联系我们

售前咨询
186 6662 7370
预约演示
185 8882 0121

微信扫码

与创始人交个朋友

回到顶部

 
扫码咨询