Reyes:一個(gè)從0到1開始訓(xùn)練的多模態(tài)大模型(技術(shù)報(bào)告) 原創(chuàng)
最近,筆者系統(tǒng)的看了下一些比較經(jīng)典的多模態(tài)大模型實(shí)現(xiàn)思路,本著動(dòng)手實(shí)踐的態(tài)度,從零到一實(shí)現(xiàn)了一個(gè)多模態(tài)大模型,并命名為??Reyes(睿視)?
??,R:睿,eyes:眼。Reyes的參數(shù)量為8B,視覺(jué)編碼器使用的是??InternViT-300M-448px-V2_5?
??,語(yǔ)言模型側(cè)使用的是??Qwen2.5-7B-Instruct?
?,與NVLM-1.0等相關(guān)多模態(tài)大模型一樣,Reyes也通過(guò)一個(gè)兩層MLP投影層連接視覺(jué)編碼器與語(yǔ)言模型。最終,Reyes-8B(0.447分)以更小的參數(shù)量在MMMU-benchmark得分超越llava1.5-13B(0.367分)。
- 模型權(quán)重開源地址:https://modelscope.cn/models/yujunhuinlp/Reyes-8B
- github:https://github.com/yujunhuics/Reyes
Reyes模型大體架構(gòu)
Reyes模型架構(gòu)
- 視覺(jué)編碼器:InternViT-300M-448px-V2_5(https://modelscope.cn/models/OpenGVLab/InternViT-300M-448px-V2_5)
- LLM側(cè):Qwen2.5-7B-Instruct(https://modelscope.cn/models/Qwen/Qwen2.5-7B-Instruct)
模型實(shí)現(xiàn):ReyesModel
class ReyesModel(PreTrainedModel):
config_class = ReyesConfig
main_input_name = 'pixel_values'
_supports_flash_attn_2 = True
_no_split_modules = ['InternVisionModel', 'Qwen2DecoderLayer']
def __init__(self, config: ReyesConfig, vision_model=None, language_model=None, use_flash_attn=True):
super().__init__(config)
assert version_cmp(transformers.__version__, '4.44.2', 'ge')
image_size = config.force_image_size or config.vision_config.image_size
patch_size = config.vision_config.patch_size
self.patch_size = patch_size
self.select_layer = config.select_layer
self.llm_arch_name = config.llm_config.architectures[0]
self.template = config.template
self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
self.downsample_ratio = config.downsample_ratio
self.ps_version = config.ps_version
use_flash_attn = use_flash_attn if has_flash_attn elseFalse
config.vision_config.use_flash_attn = Trueif use_flash_attn elseFalse
config.llm_config._attn_implementation = 'flash_attention_2'if use_flash_attn else'eager'
logger.info(f'num_image_token: {self.num_image_token}')
logger.info(f'ps_version: {self.ps_version}')
if vision_model isnotNone:
self.vision_model = vision_model
else:
self.vision_model = InternVisionModel(config.vision_config)
if language_model isnotNone:
self.language_model = language_model
else:
if config.llm_config.architectures[0] == 'Qwen2ForCausalLM':
self.language_model = Qwen2ForCausalLM(config.llm_config)
# self.language_model = AutoLigerKernelForCausalLM(config.llm_config)
else:
raise NotImplementedError(f'{config.llm_config.architectures[0]} is not implemented.')
vit_hidden_size = config.vision_config.hidden_size
llm_intermediate_size = config.llm_config.intermediate_size
llm_hidden_size = config.llm_config.hidden_size
self.mlp1 = nn.Sequential(
nn.LayerNorm(vit_hidden_size * int(1 / self.downsample_ratio) ** 2),
nn.Linear(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, llm_intermediate_size, bias=False),
nn.GELU(),
nn.Linear(llm_intermediate_size, llm_hidden_size, bias=False)
)
self.img_context_token_id = None
self.conv_template = get_conv_template(self.template)
self.system_message = self.conv_template.system_message
if config.use_backbone_lora:
self.wrap_backbone_lora(r=config.use_backbone_lora, lora_alpha=2 * config.use_backbone_lora)
if config.use_llm_lora:
self.wrap_llm_lora(r=config.use_llm_lora, lora_alpha=2 * config.use_llm_lora)
def wrap_backbone_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
lora_config = LoraConfig(
r=r,
target_modules=['attn.qkv', 'attn.proj', 'mlp.fc1', 'mlp.fc2'],
lora_alpha=lora_alpha,
lora_dropout=lora_dropout,
)
self.vision_model = get_peft_model(self.vision_model, lora_config)
self.vision_model.print_trainable_parameters()
def wrap_llm_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
# Determine the target modules based on the architecture of the language model
if self.llm_arch_name in ['Qwen2ForCausalLM', 'LlamaForCausalLM']:
target_modules = ['self_attn.q_proj', 'self_attn.k_proj', 'self_attn.v_proj', 'self_attn.o_proj',
'mlp.gate_proj', 'mlp.down_proj', 'mlp.up_proj']
else:
raiseNotImplemented
lora_config = LoraConfig(
r=r,
target_modules=target_modules,
lora_alpha=lora_alpha,
lora_dropout=lora_dropout,
task_type='CAUSAL_LM'
)
self.language_model = get_peft_model(self.language_model, lora_config)
self.language_model.enable_input_require_grads()
self.language_model.print_trainable_parameters()
def forward(
self,
pixel_values: torch.FloatTensor,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
image_flags: Optional[torch.LongTensor] = None,
past_key_values: Optional[List[torch.FloatTensor]] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, CausalLMOutputWithPast]:
return_dict = return_dict if return_dict isnotNoneelse self.config.use_return_dict
# image_flags = image_flags.squeeze(-1)
input_embeds = self.language_model.get_input_embeddings()(input_ids)
vit_embeds = self.extract_feature(pixel_values)
# vit_embeds = vit_embeds[image_flags == 1]
vit_batch_size = pixel_values.shape[0]
B, N, C = input_embeds.shape
input_embeds = input_embeds.reshape(B * N, C)
# if torch.distributed.get_rank() == 0:
# print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
input_ids = input_ids.reshape(B * N)
selected = (input_ids == self.img_context_token_id)
try:
input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
except Exception as e:
vit_embeds = vit_embeds.reshape(-1, C)
print(f'warning: {e}, input_embeds[selected].shape={input_embeds[selected].shape}, '
f'vit_embeds.shape={vit_embeds.shape}')
n_token = selected.sum()
input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds[:n_token]
input_embeds = input_embeds.reshape(B, N, C)
outputs = self.language_model(
inputs_embeds=input_embeds,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentinotallow=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
logits = outputs.logits
loss = None
if labels isnotNone:
# Shift so that tokens < n predict n
shift_logits = logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
# Flatten the tokens
loss_fct = CrossEntropyLoss()
shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
shift_labels = shift_labels.view(-1)
# Enable model parallelism
shift_labels = shift_labels.to(shift_logits.device)
loss = loss_fct(shift_logits, shift_labels)
ifnot return_dict:
output = (logits,) + outputs[1:]
return (loss,) + output if loss isnotNoneelse output
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentinotallow=outputs.attentions,
)
數(shù)據(jù)引擎
- 預(yù)訓(xùn)練數(shù)據(jù)(558k):https://huggingface.co/datasets/liuhaotian/LLaVA-Pretrain
- SFT數(shù)據(jù)(665k,其實(shí)筆者沒(méi)使用這么多,大概使用了430K左右):https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_v1_5_mix665k.json
圖片放置方式:
├── coco
│ └── train2017
├── gqa
│ └── images
├── ocr_vqa
│ └── images
├── textvqa
│ └── train_images
└── vg
├── VG_100K
└── VG_100K_2
數(shù)據(jù)格式
- 預(yù)訓(xùn)練數(shù)據(jù)格式:
<Image><image></Image> Give a brief description of the image. A group of airplanes flying through the sky.<|im_end|>
- SFT數(shù)據(jù)格式(chatml格式)
<|im_start|>system
Follow the user's instruction and answer questions.<|im_end|>
<|im_start|>user
<Image><image></lmage>
What activity are the people engaged in on the green field?<|im_end|>
<|im_start|>assistant
The people are engaged in playing a game of frisbee on the lush green field.<|im_end|>
<|im_start|>user
Is there a person wearing a fairy outfit in the image? If so, what are they doing?<|im_end|>
<|im_start|>assistant
Yes, there is a person wearing a fairy outfit in the image. They are walking in the field, likely
participating in the fun activities along with the other people.<|im_end|>
<|im_start|>user
What can you say about the spectator's location in relation to the houses?<|im_end|>
<|im_start|>assistant
The spectators are watching a match being played in a location close to the houses, possibly indicating that the field is within a residential area or park.<|im_end|>
動(dòng)態(tài)高分辨率
在數(shù)據(jù)處理階段,采用動(dòng)態(tài)高分辨率(DHR)方法來(lái)處理不同分辨率的圖像輸入。具體的如下圖,圖像被分割成最多6個(gè)瓦片(tile):
上述兩張圖都是動(dòng)態(tài)DHR的處理過(guò)程,圍繞圖像的預(yù)處理,包括歸一化、縮放、裁剪、根據(jù)寬高比動(dòng)態(tài)處理等操作,構(gòu)建了一套完整的流程,代碼邏輯如下:
import torch
from PIL import Image
import torchvision.transforms as T
from torchvision.transforms.functional import InterpolationMode
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), interpolatinotallow=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=6, image_size=448, use_thumbnail=True):
orig_width, orig_height = image.size
aspect_ratio = orig_width / orig_height
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])
target_aspect_ratio = find_closest_aspect_ratio(
aspect_ratio, target_ratios, orig_width, orig_height, image_size)
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]
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_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=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
loss效果
- 預(yù)訓(xùn)練loss
預(yù)訓(xùn)練loss,epoch=1
- SFT loss
SFT loss,epoch=1
訓(xùn)練配置
為了與llava1.5-13B公平對(duì)比,筆者在訓(xùn)練數(shù)據(jù)上和一些訓(xùn)練參數(shù)上進(jìn)行了對(duì)齊。
- pretrain階段:凍結(jié)視覺(jué)側(cè)和LLM側(cè),只訓(xùn)練MLP對(duì)齊,max-len=2048,gradient_accumulation_steps=4,單卡batch-size=8,8xH100,所有batch-size=8x4x8=256。
- SFT階段:繼續(xù)保持視覺(jué)側(cè)凍結(jié),放開LLM,與MLP一起訓(xùn)練,max-len=2048,gradient_accumulation_steps=2,單卡batch-size=8,8xH100,所有batch-size=8x2x8=128。
推理
import torch
from modelscope import AutoTokenizer, AutoModel
from PIL import Image
import torchvision.transforms as T
from torchvision.transforms.functional import InterpolationMode
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), interpolatinotallow=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
def preprocess_image(file_path, dynamic=True, max_num=6, image_size=448):
try:
if dynamic:
return load_image(file_path, max_num=max_num).to(torch.bfloat16).cuda()
else:
img = Image.open(file_path).convert('RGB')
transform = build_transform(image_size)
pixel_values = transform(img)
return torch.stack([pixel_values]).to(torch.bfloat16).cuda()
except Exception as e:
raise RuntimeError(f"Error processing image: {e}")
path = "Reyes-8B"
model = AutoModel.from_pretrained(
path,
torch_dtype=torch.bfloat16,
trust_remote_code=True,
).eval().cuda()
# print(model)
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
generation_config = dict(max_new_tokens=2048, do_sample=False)
# single-image single-round conversation
file_path = 'tmp.png'
pixel_values = preprocess_image(file_path, dynamic=True)
question = '<image>\nPlease describe the image shortly.'
response = model.chat(tokenizer, pixel_values, question, generation_config)
print(f'User: {question}\nAssistant: {response}')
# 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}')
評(píng)測(cè)
1.MMMU評(píng)測(cè)(MMMU: A Massive Multi-discipline Multimodal Understanding and Reasoning Benchmark for Expert AGI)
簡(jiǎn)介:MMMU 是一種新的基準(zhǔn),旨在評(píng)估多模態(tài)模型在需要大學(xué)水平的學(xué)科知識(shí)和深思熟慮的推理的大規(guī)模多學(xué)科任務(wù)中的表現(xiàn)。MMMU 包含11.5K 個(gè)精心收集的來(lái)自大學(xué)考試、測(cè)驗(yàn)和教科書的多模態(tài)問(wèn)題,涵蓋六個(gè)核心學(xué)科:藝術(shù)與設(shè)計(jì)、商業(yè)、科學(xué)、健康與醫(yī)學(xué)、人文與社會(huì)科學(xué)以及技術(shù)與工程。這些問(wèn)題涵蓋30 個(gè)學(xué)科和183 個(gè)子領(lǐng)域,包含32 種高度異構(gòu)的圖像類型,如圖表、圖解、地圖、表格、樂(lè)譜和化學(xué)結(jié)構(gòu)。與現(xiàn)有基準(zhǔn)不同,MMMU 專注于使用領(lǐng)域特定知識(shí)進(jìn)行高級(jí)感知和推理,挑戰(zhàn)模型執(zhí)行類似于專家面臨的任務(wù)。
評(píng)測(cè)結(jié)果顯示:Reyes-8b比llava1.5-13b取得了更先進(jìn)的結(jié)果。詳細(xì)評(píng)分如下:
- llava1.5-13b得分:0.367
- Reyes-8b得分:0.447
2.一些測(cè)試case
- case1
問(wèn)題: Who painted <image 1>?
選項(xiàng): {'A':'Claude Monet', 'B':'Henri Matisse', 'C':'Andy Warhol','D': "Georgia O'Keefe"]
預(yù)測(cè)的答案: C
正確的答案: C
- case2
問(wèn)題: Each situation below relates to an independent company's Owners' Equity. <image 1> Calculate the missing values of company 2.
選項(xiàng): {'A': '$1,620', 'B': '$12,000', 'C': '$51,180', 'D': '$0'}
預(yù)測(cè)的答案: D
正確的答案: D
- case3
問(wèn)題: A survey line ABC crossing a river at right angles cut its banks at B and C, as shown in Fig. 2.39. To determine the width BC of the river, the following operation was carried out.A 60 m long line BE was set out roughly parallel to the river. Line CE was extended to D and mid-point F of DB was established. Then EF was extended to G such that FG = EF. Line DG was extended to cut the survey line ABC at H. GH and HB were measured and found to be 40 m and 80 m, respectively.Find the width of the river.<image 1>
選項(xiàng): {'A': '120 m', 'B': '122 m', 'C': '123 m', 'D': '121 m'}
預(yù)測(cè)的答案: A
正確的答案: A
總結(jié)
本文記錄了從0到1實(shí)現(xiàn)一個(gè)多模態(tài)大模型的過(guò)程,包括模型結(jié)構(gòu)、數(shù)據(jù)引擎、評(píng)測(cè)全流程。當(dāng)前模型訓(xùn)練數(shù)據(jù)與llava1.5-13b對(duì)齊,并且在MMMU評(píng)測(cè)上以更小的模型參數(shù)量超越了llava1.5-13b,當(dāng)前訓(xùn)練數(shù)據(jù)因?yàn)橹徊捎昧藞D文多模態(tài)數(shù)據(jù),在SFT階段,并未加入text-only數(shù)據(jù),因此,語(yǔ)言模型端會(huì)出現(xiàn)一些退化。將來(lái)若有時(shí)間,會(huì)考慮加入更多的多模態(tài)數(shù)據(jù)及筆者私有數(shù)據(jù)進(jìn)行訓(xùn)練(如:《??【多模態(tài) & 文檔智能】一次多模態(tài)大模型表格識(shí)別解析探索小實(shí)踐記錄??》),打造更強(qiáng)的Reyes模型。
本文轉(zhuǎn)載自公眾號(hào)大模型自然語(yǔ)言處理 作者:余俊暉
