从零开始打造多模态大模型:预训练全攻略,新手到专家的完整指南,一篇收藏走天下!

本文参考官方教程[1]介绍如何训练 LLaVA v1.5 多模态模型。LLaVA 训练包括特征对齐阶段(feature alignment stage)和视觉指令微调阶段(visual instruction tuning stage),其中特征对齐阶段使用 LAION-CC-SBU 数据集的 558K 子集(记为 LLaVA-Pretrain),目的是训练 MLP connector(或称为 projector),而视觉指令微调阶段使用 GPT-4 生成的 150K 条多模态指令跟随数据和来自学术任务的 515K 条 VQA 数据引导 LLaVA 模型遵从多模态指令。

官方给出的 LLaVA v1.5 使用了 8 个 A100 GPU(80G)进行训练,如果我们没有 8 个 GPU 或者足够的显存(80G),可以减小per_device_train_batch_size的值并增大gradient_accumulation_steps,始终保证全局 batch size 不变,其中 batch size 的大小等于 per_device_train_batch_sizexgradient_accumulation_stepsxnum_gpus 。

下面以 LLaVA-v1.5-13B 为例介绍 LLaVA 模型的训练。

特征对齐阶段

准备数据
下载 LLaVA-Pretrain[2] 数据集
# 将数据下载到 ./playground/data/LLaVA-Pretrain,否则需要修改启动脚本的 data_path 参数   huggingface-cli download --repo-type dataset liuhaotian/LLaVA-Pretrain --local-dir ./playground/data/LLaVA-Pretrain

LLaVA-Pretrain 包含 3 个文件:

  • • blip_laion_cc_sbu_558k.json:此数据的构造过程是将 image-caption 数据添加随机选择的指令(例如:“Describe this image”)转换成多模态对话,下面是数据示例:
{       'id': '004539375',       'image': '00453/004539375.jpg',       'conversations': [         {           'from': 'human',           'value': 'Render a clear and concise summary of the photo.\n<image>'         },         {           'from': 'gpt',           'value': 'select luxury furniture 3 - inch gel memory foam mattress topper'         }       ]     },

  • • blip_laion_cc_sbu_558k_meta.json:包含 3 种元数据,分别是图像路径、图像 URL 和 blip_caption
{       'id': '004539375',       'image': '00453/004539375.jpg',       'blip_caption': 'select luxury furniture 3 - inch gel memory foam mattress topper',       'url': 'http://ec1.ostkcdn.com/images/products/8111140/P15459545.jpg'     }

  • • images.zip:LAION/CC/SBU 筛选后的子集
解压images.zip
# 解压到 ./playground/data/LLaVA-Pretrain/images,否则需要修改启动脚本的 image_folder 参数   unzip ./playground/data/LLaVA-Pretrain/images.zip -d ./playground/data/LLaVA-Pretrain/images

启动训练

在这个阶段,使用 8 个 A100(80G)训练 LLaVA-v1.5-13B 大约需要 5.5 小时。

启动的脚本是scripts/v1_5/pretrain.sh,它的内容如下:

#!/bin/bash   deepspeed llava/train/train_mem.py \       --deepspeed ./scripts/zero2.json \  # 使用 DeepSpeed ZeRO-2       --model_name_or_path lmsys/vicuna-13b-v1.5 \  # 语言模型是 lmsys/vicuna-13b-v1.5       --version plain \       --data_path ./playground/data/LLaVA-Pretrain/blip_laion_cc_sbu_558k.json \  # 训练样本文件       --image_folder ./playground/data/LLaVA-Pretrain/images \  # 存放图像的目录       --vision_tower openai/clip-vit-large-patch14-336 \  # 视觉编码器       --mm_projector_type mlp2x_gelu \  # projector 的类型       --tune_mm_mlp_adapter True \  # 是否训练 projector       --mm_vision_select_layer -2 \       --mm_use_im_start_end False \       --mm_use_im_patch_token False \       --bf16 True \       --output_dir ./checkpoints/llava-v1.5-13b-pretrain \  # 保存的路径       --num_train_epochs 1 \       --per_device_train_batch_size 32 \       --per_device_eval_batch_size 4 \       --gradient_accumulation_steps 1 \       --evaluation_strategy 'no' \       --save_strategy 'steps' \       --save_steps 24000 \       --save_total_limit 1 \       --learning_rate 1e-3 \       --weight_decay 0. \       --warmup_ratio 0.03 \       --lr_scheduler_type 'cosine' \       --logging_steps 1 \       --tf32 True \       --model_max_length 2048 \       --gradient_checkpointing True \       --dataloader_num_workers 4 \       --lazy_preprocess True \       --report_to wandb

启动脚本:

sh ./scripts/v1_5/pretrain.sh

启动训练后,会自动下载语言模型视觉编码器的权重,完成权重的下载后会提示是否需要使用 wandb 可视化结果,这里按需选择即可。

接下来就开始了训练,下面是 loss 的部分日志:

训练完成后,权重会保存在./checkpoints/llava-v1.5-13b-pretrain目录。

视觉指令微调阶段

完成特征对齐阶段的训练后,我们进入视觉指令微调阶段。注意:如果我们跳过特征对齐阶段的训练,则需要将对应的 projector 下载到./checkpoints目录,下载的命令如下:

huggingface-cli download liuhaotian/llava-v1.5-mlp2x-336px-pretrain-vicuna-13b-v1.5 --local-dir ./checkpoints/llava-v1.5-13b-pretrain

准备数据
下载数据集
  • • 下载 llava_v1_5_mix665k.json[3]
# 将数据下载到 ./playground/data/LLaVA-Instruct-150K   huggingface-cli download --repo-type dataset liuhaotian/LLaVA-Instruct-150K --local-dir ./playground/data/LLaVA-Instruct-150K   cp ./playground/data/LLaVA-Instruct-150K/llava_v1_5_mix665k.json ./playground/data/llava_v1_5_mix665k.json

下面是 llava_v1_5_mix665k.json 的示例:

{       'id': '000000033471',  // 样本的唯一 id       'image': 'coco/train2017/000000033471.jpg',  // 可以是绝对路径,也可以是相对于 image_folder 的路径       'conversations': [         {           'from': 'human',           'value': '<image>\nWhat are the colors of the bus in the image?'         },         {           'from': 'gpt',           'value': 'The bus in the image is white and red.'         },         {           'from': 'human',           'value': 'What feature can be seen on the back of the bus?'         },         {           'from': 'gpt',           'value': 'The back of the bus features an advertisement.'         },         {           'from': 'human',           'value': 'Is the bus driving down the street or pulled off to the side?'         },         {           'from': 'gpt',           'value': 'The bus is driving down the street, which is crowded with people and other vehicles.'         }       ]     },

  • • 下载 COCO train2017[4]
wget http://images.cocodataset.org/zips/train2017.zip -P ./playground/data/coco   unzip ./playground/data/coco/train2017.zip -d ./playground/data/coco

  • • 下载 GQA images[5]
wget https://downloads.cs.stanford.edu/nlp/data/gqa/images.zip -P ./playground/data/gqa   unzip ./playground/data/gqa/images.zip -d ./playground/data/gqa

  • • 下载 OCR-VQA[6] 将 OCR-VQA 中的 dataset.json 和 loadDataset.py 文件下载到 ./playground/data/ocr_vqa 目录。注释 loadDataset.py 中的 pdb.set_trace()后执行下面的命令:
cd ./playground/data/ocr_vqa   python loadDataset.py   # 回到 LLaVA 目录   cd ../../../

使用下面的代码处理 OCR-VQA 图像的后缀问题[7]:

import json   import os      with open('./playground/data/llava_v1_5_mix665k.json') as f:       samples = json.load(f)      for sample in samples:       if 'image' not in sample:           continue          img_path = os.path.join('./playground/data', sample['image'])       if not os.path.exists(img_path):           # 处理 OCR-VQA 图像后缀和 llava_v1_5_mix665k.json 中的后缀不一致问题           img_path_wo_ext = os.path.splitext(img_path)[0]           for ext in ['.png', '.gif']:               real_path = img_path_wo_ext + ext               if os.path.exists(real_path):                   # 重命名                   os.replace(real_path, img_path)                   break

也可以参考 https://github.com/haotian-liu/LLaVA/pull/1458 给出的路径下载 ORC-VQA 数据。

  • • 下载 TextVQA[8]
wget https://dl.fbaipublicfiles.com/textvqa/images/train_val_images.zip -P ./playground/data/textvqa   unzip ./playground/data/textvqa/train_val_images.zip -d ./playground/data/textvqa

  • • 下载 VisualGenome part1[9] 和 part2[10]
wget https://cs.stanford.edu/people/rak248/VG_100K_2/images.zip -P ./playground/data/vg   wget https://cs.stanford.edu/people/rak248/VG_100K_2/images2.zip -P ./playground/data/vg   unzip ./playground/data/vg/images.zip -d ./playground/data/vg   unzip ./playground/data/vg/images2.zip -d ./playground/data/vg

数据集结构

完成数据集的下载后,检查数据集的目录结构是否和下面的一致:

├── coco   │   ├── train2017   │   │   ├── xxx.jpg   ├── gqa   │   ├── images   │   │   ├── xxx.jpg   ├── llava_v1_5_mix665k.json   ├── ocr_vqa   │   ├── dataset.json   │   ├── images   │   │   ├── xxx.jpg   │   └── loadDataset.py   ├── textvqa   │   ├── train_images   │   │   ├── xxx.jpg   │── vg   ├── └── VG_100K   │   │   ├── xxx.jpg   ├── │── VG_100K_2   │   │   ├── xxx.jpg

使用下面的代码检查数据目录结构:

import json   import os      with open('./playground/data/llava_v1_5_mix665k.json') as f:       samples = json.load(f)      missing_cnt = 0  # 记录图像路径不存在的个数   for sample in samples:       if 'image' not in sample:           continue          img_path = os.path.join('./playground/data', sample['image'])       if not os.path.exists(img_path):           missing_cnt += 1      print(missing_cnt)

如果 missing_cnt 为 0,则说明数据的目录结构是正确的。

启动训练

在启动训练前,请查看 https://github.com/haotian-liu/LLaVA/issues/1144 以避免训练结束后权重保存出错。

在这个阶段,使用 8 个 A100(80G)训练 LLaVA-v1.5-13B 大约需要 20 小时。启动的脚本是scripts/v1_5/finetune.sh,它的内容如下:

#!/bin/bash      deepspeed llava/train/train_mem.py \       --deepspeed ./scripts/zero3.json \  # 使用 DeepSpeed ZeRO-3       --model_name_or_path lmsys/vicuna-13b-v1.5 \       --version v1 \       --data_path ./playground/data/llava_v1_5_mix665k.json \  # 训练样本       --image_folder ./playground/data \  # 存放图像的目录       --vision_tower openai/clip-vit-large-patch14-336 \       --pretrain_mm_mlp_adapter ./checkpoints/llava-v1.5-13b-pretrain/mm_projector.bin \       --mm_projector_type mlp2x_gelu \  # projector 的类型       --mm_vision_select_layer -2 \       --mm_use_im_start_end False \       --mm_use_im_patch_token False \       --image_aspect_ratio pad \       --group_by_modality_length True \       --bf16 True \       --output_dir ./checkpoints/llava-v1.5-13b \       --num_train_epochs 1 \       --per_device_train_batch_size 16 \       --per_device_eval_batch_size 4 \       --gradient_accumulation_steps 1 \       --evaluation_strategy 'no' \       --save_strategy 'steps' \       --save_steps 50000 \       --save_total_limit 1 \       --learning_rate 2e-5 \       --weight_decay 0. \       --warmup_ratio 0.03 \       --lr_scheduler_type 'cosine' \       --logging_steps 1 \       --tf32 True \       --model_max_length 2048 \       --gradient_checkpointing True \       --dataloader_num_workers 4 \       --lazy_preprocess True \       --report_to wandb

启动脚本:

sh ./scripts/v1_5/finetune.sh

启动训练后,会询问是否需要使用 wandb 可视化结果,这里按需选择即可。

接下来就开始了训练,下面是 loss 的部分日志:

训练完成后,权重会保存在./checkpoints/llava-v1.5-13b目录。注意:如果单卡显存不足 80G,可以使用 LoRA 微调脚本 finetune_lora.sh[11]。完成训练后,可以参考 LLaVA 评测[12]对模型的性能进行评测。

微调自定义数据集

参考 Finetune LLaVA on Custom Datasets[13]

将训练样本以列表的形式保存到 json 文件,其中每一个样本是一个字典,它至少包含三个字段:

  • • id:全局唯一的字符串

  • • image:图片的路径,可以是绝对路径,也可以是相对于image_folder的相对路径

  • • conversations:人类和语言模型的对话

下面是一个示例:

[     {       'id': '997bb945-628d-4724-b370-b84de974a19f',       'image': 'part-000001/997bb945-628d-4724-b370-b84de974a19f.jpg',       'conversations': [         {           'from': 'human',           'value': '<image>\nWrite a prompt for Stable Diffusion to generate this image.'         },         {           'from': 'gpt',           'value': 'a beautiful painting of chernobyl by nekro, pascal blanche, john harris, greg rutkowski, sin jong hun, moebius, simon stalenhag. in style of cg art. ray tracing. cel shading. hyper detailed. realistic. ue 5. maya. octane render. '         },       ]     },     ...   ]

完成数据的处理后,修改 finetune.sh[14] 中的 data_path 参数(必须)以及其他想要调整的参数(可选,例如学习率)。

修改完成后,即可启动训练:

sh ./scripts/v1_5/finetune.sh

以上就是 LLaVA 的训练流程。

零基础如何学习大模型 AI

领取方式在文末

为什么要学习大模型?

学习大模型课程的重要性在于它能够极大地促进个人在人工智能领域的专业发展。大模型技术,如自然语言处理和图像识别,正在推动着人工智能的新发展阶段。通过学习大模型课程,可以掌握设计和实现基于大模型的应用系统所需的基本原理和技术,从而提升自己在数据处理、分析和决策制定方面的能力。此外,大模型技术在多个行业中的应用日益增加,掌握这一技术将有助于提高就业竞争力,并为未来的创新创业提供坚实的基础。

大模型实际应用案例分享

①智能客服:某科技公司员工在学习了大模型课程后,成功开发了一套基于自然语言处理的大模型智能客服系统。该系统不仅提高了客户服务效率,还显著降低了人工成本。
②医疗影像分析:一位医学研究人员通过学习大模型课程,掌握了深度学习技术在医疗影像分析中的应用。他开发的算法能够准确识别肿瘤等病变,为医生提供了有力的诊断辅助。
③金融风险管理:一位金融分析师利用大模型课程中学到的知识,开发了一套信用评分模型。该模型帮助银行更准确地评估贷款申请者的信用风险,降低了不良贷款率。
④智能推荐系统:一位电商平台的工程师在学习大模型课程后,优化了平台的商品推荐算法。新算法提高了用户满意度和购买转化率,为公司带来了显著的增长。

这些案例表明,学习大模型课程不仅能够提升个人技能,还能为企业带来实际效益,推动行业创新发展。

学习资料领取

如果你对大模型感兴趣,可以看看我整合并且整理成了一份AI大模型资料包,需要的小伙伴文末免费领取哦,无偿分享!!!
vx扫描下方二维码即可
加上后会一个个给大家发

在这里插入图片描述

部分资料展示

一、 AI大模型学习路线图

整个学习分为7个阶段
在这里插入图片描述

二、AI大模型实战案例

涵盖AI大模型的理论研究、技术实现、行业应用等多个方面。无论您是科研人员、工程师,还是对AI大模型感兴趣的爱好者,皆可用。
在这里插入图片描述

三、视频和书籍PDF合集

从入门到进阶这里都有,跟着老师学习事半功倍。
在这里插入图片描述

在这里插入图片描述

如果二维码失效,可以点击下方链接,一样的哦
【CSDN大礼包】最新AI大模型资源包,这里全都有!无偿分享!!!

😝朋友们如果有需要的话,可以V扫描下方二维码联系领取~
在这里插入图片描述

  • 14
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值