咱们边玩边学BLIP2

多模态 CLIP/BLIP/BLIP-2论文理论知识总结 CLIP是BLIP的前身,或者说是一个很高水平的基础, 视频听下来最深的印象就是论文团队对于这个大模型的训练用了从网上爬下来的4亿个图像文本对,真是钞能力啊~CLIP通过4亿的数据来学习图像和文本之间的对应关系,实现了扩模态的语义理解,适用于很多扩模态的任务,就比如文生图、利用图像反推其文本tag等,更详细的知识点看视频,我这里就自己总结一下,给自己留个可以快速review的地方。论文的篇幅页数很多,但重要的内容主要就在前面15页左右,再往后都是很多实验的分析啥的。,使用对比损失函数来训练; 阅读详情

理论核心

  1. 冻结视觉编码器,训练Q-former,学习视觉-文本的表征
  2. 冻结LLM,训练视觉到文本的生成

模型架构

Q-Former consists of two transformer submodules that share the same self-attention layers

  1. 带有视觉编码器的image Transformer,来提取视觉特征
  2. a text transformer 同时充当 a text encoder 和 text decoder
  3. 可学习query embedding
    • 首先和shared self- attention交互,可以学习到text信息
    • 然后通过cross attention与image encoder交互,学习图像的信息

Image Transformer输出的是学习到的query embedding 也就是ZZZ,Text Transformer学习到的是文本表征,也就是ttt,就剩【CLS】token的embedding

Since Z contains multiple output embeddings (one from each query), we first compute the
pairwise similarity between each query output and t, and then select the highest one as the image-text similarity

query的具体组成:
在这里插入图片描述


好好好,居然在撩我!!!
在这里插入图片描述

Q-Former核心

Image-text Contrastive

# 将image_feats扩展到所有GPU上,image_feats是图像特征,是一个tensor,维度为[batch_size*num_gpu, num_query_tokens, embed_dim]
image_feats_all = concat_all_gather(image_feats)  

# 将text_feat扩展到所有GPU上,text_feat是文本特征,是一个tensor,维度为[batch_size*num_gpu, embed_dim]
text_feat_all = concat_all_gather(text_feat)  

# 对每个查询标记计算图像到文本的相似度
sim_q2t = torch.matmul(
    image_feats.unsqueeze(1), text_feat_all.unsqueeze(-1)
).squeeze()

# 对image-text相似度进行聚合,取所有查询标记的最大值
sim_i2t, _ = sim_q2t.max(-1)  
sim_i2t = sim_i2t / self.temp  # 对相似度进行缩放

# 对每个查询标记计算文本到图像的相似度
sim_t2q = torch.matmul(
    text_feat.unsqueeze(1).unsqueeze(1), image_feats_all.permute(0, 2, 1)
).squeeze()

# 对text-image相似度进行聚合,取所有查询标记的最大值
sim_t2i, _ = sim_t2q.max(-1)  
sim_t2i = sim_t2i / self.temp  # 对相似度进行缩放

# 获取进程的rank和batch的大小
rank = dist.get_rank()  
bs = image.size(0)  

# 生成targets,用于计算损失
targets = torch.linspace(rank * bs, rank * bs + bs - 1, bs, dtype=int).to(
    image.device
)

# 如果samples中包含image_id,则表示在COCO检索微调训练中
if "image_id" in samples.keys():  
    # 获取image_ids
    image_ids = samples["image_id"].view(-1,1)
    # 将所有图片的image_id扩展到所有GPU上
    image_ids_all = concat_all_gather(image_ids)
    # 计算相似度目标,对匹配的图像进行惩罚
    pos_idx = torch.eq(image_ids, image_ids_all.t()).float()       
    sim_targets = pos_idx / pos_idx.sum(1,keepdim=True)   
    sim_targets = 0.9 * sim_targets + 0.1 * torch.ones_like(sim_targets) / sim_targets.size(1)

    # 计算损失,在COCO检索微调训练中
    loss_t2i = -torch.sum(F.log_softmax(sim_t2i, dim=1)*sim_targets,dim=1).mean()
    loss_i2t = -torch.sum(F.log_softmax(sim_i2t, dim=1)*sim_targets,dim=1).mean()     
    loss_itc = (loss_t2i+loss_i2t)/2  
# 如果不是COCO检索微调训练
else:                     
    # 普通的图像-文本对比损失计算
    loss_itc = (
        F.cross_entropy(sim_i2t, targets, label_smoothing=0.1)
        + F.cross_entropy(sim_t2i, targets, label_smoothing=0.1)
    ) / 2

Text-Image Match

# 将text_tokens中的输入ID和注意力掩码扩展到所有GPU上
text_input_ids_world = concat_all_gather(text_tokens.input_ids)  
text_attention_mask_world = concat_all_gather(text_tokens.attention_mask)

# 将image_embeds扩展到所有GPU上,并且允许梯度传播
image_embeds_world = all_gather_with_grad(image_embeds)  

# 禁止梯度传播,用于下面的操作
with torch.no_grad():
    # 如果samples中包含image_id,则在image_ids与image_ids_all.t()相等的位置填充-10000
    if "image_id" in samples.keys():
        mask = torch.eq(image_ids, image_ids_all.t())
        sim_t2i.masked_fill_(mask, -10000)
        sim_i2t.masked_fill_(mask, -10000)
    else:    
        # 否则在sim_t2i和sim_i2t的对角线位置填充-10000
        sim_t2i[:, rank * bs : rank * bs + bs].fill_diagonal_(-10000)
        sim_i2t[:, rank * bs : rank * bs + bs].fill_diagonal_(-10000)            
        
    # 计算softmax权重,对文本到图像和图像到文本的相似性进行归一化
    weights_t2i = F.softmax(sim_t2i, dim=1)
    weights_i2t = F.softmax(sim_i2t, dim=1)

# 为每个文本选择一个负向图像
image_embeds_neg = []
for b in range(bs):
    neg_idx = torch.multinomial(weights_t2i[b], 1).item()
    image_embeds_neg.append(image_embeds_world[neg_idx])
image_embeds_neg = torch.stack(image_embeds_neg, dim=0)

# 为每个图像选择一个负向文本
text_ids_neg = []
text_atts_neg = []
for b in range(bs):
    neg_idx = torch.multinomial(weights_i2t[b], 1).item()
    text_ids_neg.append(text_input_ids_world[neg_idx])
    text_atts_neg.append(text_attention_mask_world[neg_idx])
text_ids_neg = torch.stack(text_ids_neg, dim=0)
text_atts_neg = torch.stack(text_atts_neg, dim=0)

# 将所有的正向文本和负向文本组合成一个tensor
text_ids_all = torch.cat(
    [text_tokens.input_ids, text_tokens.input_ids, text_ids_neg], dim=0
)  # pos, pos, neg
text_atts_all = torch.cat(
    [text_tokens.attention_mask, text_tokens.attention_mask, text_atts_neg],
    dim=0,
)

# 生成用于查询任务的token和注意力掩码
query_tokens_itm = self.query_tokens.expand(text_ids_all.shape[0], -1, -1)
query_atts_itm = torch.ones(query_tokens_itm.size()[:-1], dtype=torch.long).to(
    image.device
)
attention_mask_all = torch.cat([query_atts_itm, text_atts_all], dim=1)

# 将所有的正向图像和负向图像组合成一个tensor
image_embeds_all = torch.cat(
    [image_embeds, image_embeds_neg, image_embeds], dim=0
)  # pos, neg, pos
image_atts_all = torch.ones(image_embeds_all.size()[:-1], dtype=torch.long).to(
    image.device
)

# 执行查询任务,获取输出
output_itm = self.Qformer.bert(
    text_ids_all,
    query_embeds=query_tokens_itm,
    attention_mask=attention_mask_all,
    encoder_hidden_states=image_embeds_all,
    encoder_attention_mask=image_atts_all,
    return_dict=True,
)

# 提取视觉-语言交互层的输出
vl_embeddings = output_itm.last_hidden_state[:, : query_tokens_itm.size(1), :]

# 对视觉-语言交互层的输出应用itm头
vl_output = self.itm_head(vl_embeddings)
logits = vl_output.mean(dim=1)

# 生成itm标签,对正向样本标记为1,对负向样本标记为0
itm_labels = torch.cat(
    [torch.ones(bs, dtype=torch.long), torch.zeros(2 * bs, dtype=torch.long)],
    dim=0,
).to(image.device)

# 计算itm任务的交叉熵损失
loss_itm = F.cross_entropy(logits, itm_labels)

Image Caption

# 克隆text_tokens的输入ID,并将第一个位置设置为起始符号的ID
decoder_input_ids = text_tokens.input_ids.clone()
decoder_input_ids[:, 0] = self.tokenizer.bos_token_id

# 将要预测的标签设置为decoder_input_ids,并使用-100填充pad位置
labels = decoder_input_ids.masked_fill(
    decoder_input_ids == self.tokenizer.pad_token_id, -100
)

# 生成注意力掩码,用于语言模型的输入
query_atts = torch.ones(query_tokens.size()[:-1], dtype=torch.long).to(
    image.device
)
attention_mask = torch.cat([query_atts, text_tokens.attention_mask], dim=1)

# 执行语言模型的训练,获取LM输出
lm_output = self.Qformer(
    decoder_input_ids,
    attention_mask=attention_mask,
    past_key_values=query_output.past_key_values,
    return_dict=True,
    labels=labels,
)

# 计算语言模型的损失
loss_lm = lm_output.loss

# 返回总的损失和各个部分的损失
return BlipOutput(
    loss=loss_itc + loss_itm + loss_lm,
    loss_itc=loss_itc,
    loss_itm=loss_itm,
    loss_lm=loss_lm,
)

Generate

def generate(
    self,
    samples,
    use_nucleus_sampling=False,
    num_beams=3,
    max_length=30,
    min_length=10,
    top_p=0.9,
    repetition_penalty=1.0,
):
    """
    Args:
    samples (dict): 包含以下键的字典:
        - image (torch.Tensor): 形状为(batch_size, 3, H, W)的张量
    use_nucleus_sampling (bool): 是否使用核采样。如果为False,则使用top-k采样。
    num_beams (int): 用于束搜索的束的数量。1表示不使用束搜索。
    max_length (int): 要生成的序列的最大长度。
    min_length (int): 要生成的序列的最小长度。
    top_p (float): 核采样的累积概率。
    repetition_penalty (float): 重复惩罚的参数。1.0表示没有惩罚。
    num_captions (int): 每个图像要生成的字幕数。
    Returns:
    captions (list): 长度为batch_size * num_captions的字符串列表。
    """
    # 获取图像并将其编码为图像嵌入
    image = samples["image"]
    image_embeds = self.ln_vision(self.visual_encoder(image))

    # 如果不使用核采样,则扩展图像嵌入,用于束搜索
    if not use_nucleus_sampling:
        image_embeds = image_embeds.repeat_interleave(num_beams, dim=0)
    else:
        num_beams = 1
    image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(
        image.device
    )

    # 设置模型参数
    model_kwargs = {
        "encoder_hidden_states": image_embeds,
        "encoder_attention_mask": image_atts,
    }

    # 生成文本描述
    input_ids = (
        torch.LongTensor(image.size(0), 1)
        .fill_(self.tokenizer.bos_token_id)
        .to(image.device)
    )
    # image token编码
    query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
	# 调用Qformer进行生成
    outputs = self.Qformer.generate(
        input_ids=input_ids,
        query_embeds=query_tokens,
        max_length=max_length,
        min_length=min_length,
        num_beams=num_beams,
        do_sample=use_nucleus_sampling,
        top_p=top_p,
        eos_token_id=self.tokenizer.sep_token_id,
        pad_token_id=self.tokenizer.pad_token_id,
        **model_kwargs
    )
    # 解码生成captions
    captions = self.tokenizer.batch_decode(outputs, skip_special_tokens=True)
    return captions

qformer的generate模块好复杂

generate 函数用于模型的条件生成。

首先,generate 函数通过各种参数调用生成。这些参数包括生成配置文件、标记处理列表、停止条件列表、前缀允许令牌 fn、委托人模型、流媒体设备、负提示 ids 和注意力掩码等。这些参数用来进一步控制生成的方式和结果。

generate 函数主要分为以下步骤:

  1. 处理 generation_config 和可能更新它的 kwargs,以及验证 .generate() 调用。

  2. 设置生成参数(如处理?)

  3. 定义模型输入

  4. 定义其他模型kwargs

  5. 准备自回归生成的input_ids

  6. 准备包含其他停止标准的 max_length

  7. 确定生成模式

有了这些步骤,generate 函数可以进入不同的生成模式和执行相应的生成方法,比如贪婪搜索,显示搜索等。

在选择相应的生成模式后,generate 函数根据模型的生成配置、输入和相应的参数调用相应的生成方法,包括模型的贪婪搜索、显示搜索、样本生成等。

接下来,通过选择合适的方法和参数对模型进行生成,并返回生成的输出。
最后,如果选择了与专辑模式,则可以使用 assistant_model 对象来进行助攻生成。在这种情况下,生成方法中的一些参数和逻辑都将有所不同。目的是加速生成。具体来说,在助攻生成过程中,特定的助攻模型将返回模型的生成 output 或torch.FloatTensor。

总的来说,generate 函数负责执行不同的生成方法和逻辑以生成模型的输出。它允许用户根据实际需要执行不同的生成方法,并支持其他参数的进一步控制。这个函数给了人们灵活的选择,以获得满足需求的生成输出。

BLIP2实战

Image2text

from transformers import AutoProcessor, Blip2ForConditionalGeneration
import torch

processor = AutoProcessor.from_pretrained("Salesforce/blip2-opt-2.7b")
model = Blip2ForConditionalGeneration.from_pretrained("Salesforce/blip2-opt-2.7b", torch_dtype=torch.float16, device_map="auto")
device = "cuda:0"
inputs = processor(image, return_tensors="pt").to(device, torch.float16)

generated_ids = model.generate(**inputs, max_new_tokens=20)
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
print(generated_text)

text+img2text

  • 注意:通过提供文本提示来扩展图像字幕生成,模型将在给定图像的情况下接着提示词往下补充
prompt = "this is a cartoon of"

inputs = processor(image, text=prompt, return_tensors="pt").to(device, torch.float16)

generated_ids = model.generate(**inputs, max_new_tokens=20)
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
print(generated_text)

VQA

  • 用于视觉问答时,提示必须遵循特定格式: “Question: {} Answer:”
prompt = "Question: What is a dinosaur holding? Answer:"

inputs = processor(image, text=prompt, return_tensors="pt").to(device, torch.float16)

generated_ids = model.generate(**inputs, max_new_tokens=10)
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
print(generated_text)

contextQA

context = [
   ("What is a dinosaur holding?", "a torch"),
   ("Where are they?", "In the woods.")
]
question = "What for?"
template = "Question: {} Answer: {}."

prompt = " ".join([template.format(context[i][0], context[i][1]) for i in range(len(context))]) + " Question: " + question + " Answer:"

print(prompt)

inputs = processor(image, text=prompt, return_tensors="pt").to(device, torch.float16)

generated_ids = model.generate(**inputs, max_new_tokens=10)
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
print(generated_text)

  • https://huggingface.co/blog/zh/blip-2#%E5%9B%BE%E5%83%8F%E5%AD%97%E5%B9%95%E7%94%9F%E6%88%90
BLIP2中Q-former详解 Querying Transformer,在冻结的视觉模型和大语言模型间进行视觉-语言对齐。为了使Q-Former的学习达到两个目标:学习到和文本最相关的视觉表示。这种表示能够为大语言模型所解释。需要在Q-Former结构设计和训练策略上下功夫。具体来说,Q-Former是一个轻量级的transformer,它使用一个可学习的query向量集,从冻结的视觉模型提取视觉特征。采取两阶段预训练策略。 阅读详情

相关推荐

NLP实践——VQA/Caption生成模型BLIP-2的应用介绍

本文介绍最新的图文生成模型BLIP-2,从下载安装到简单的应用。

weixin_44826203的博客 1万+

BLIP-2:下一代多模态模型的雏形

点击下方卡片,关注“CVer”公众号AI/CV重磅干货,第一时间送达点击进入—>【多模态学习】微信技术交流群作者:竹鼠商人 | (源:知乎)编辑:CVerhttps://zhuanlan.zhihu.com/p/606364639最近ChatGPT风头正劲,但只能理解文字或多或少限制其才华的发挥。得益于Transformer在NLP和CV领域的大放异彩,多模态近几年取得了非常大的进步。但之...

阿木寺的博客 1万+

基于vLLM与QQ协议的AI助手低成本部署实践

大语言模型(LLM)的推理优化是AI工程化的关键技术挑战。vLLM框架通过创新的PagedAttention机制,实现了类似操作系统虚拟内存的显存管理,有效解决了传统推理框架的显存碎片化和并行处理瓶颈问题。结合量化技术和滑动窗口算法,开发者可以在消费级显卡(如RTX 3090)上高效运行70亿参数模型,响应速度可达1秒内。这种技术方案特别适合即时通讯场景的AI助手开发,通过go-cqhttp协议适配层与Redis缓存管理,能够稳定处理20轮以上的长对话。实测表明,采用Llama2-7B-chat模型时,单条

weixin_34210740的博客 381

【论文解读系列】Blip-2:引导语言图像预训练具有冻结图像编码器和大型语言模型

泛化性很强;模型针对中文数据库还可以再优化;文字生成的长度不长(虽然文章中说限制长度更符合人类直接,但是模型很多信息也无法输出更完美)由于大规模模型的端到端训练成本不断增加,视觉和语言预训练的成本已经越来越高。本文提出了BLIP-2,一种通用且高效的预训练策略,它可以从现成的冻结预训练图像编码器和冻结大型语言模型中引导视觉-语言预训练。BLIP-2通过一个轻量级的来弥合模态差距,并在两个阶段进行预训练。第一个阶段从冻结图像编码器引导视觉-语言表示学习。第二个阶段从冻结语言模型中引导视觉-语言生成学习。

JackCrum的博客 7600

VLM 系列——BLIP2——论文解读

BLIP2是一个多模态视觉-文本大语言模型,隶属BLIP系列第二篇,可以完成:图像描述、视觉问答、名画名人等识别(问答、描述)。支持单幅图片输入(作为第一个输入),多轮文本对话。使用冻结的图像编码器、LLM外加一个Q-former,分两阶段来pre-train模型,例图解决训练成本高和模型灾难遗忘的问题。在多个数据集上的zero-shot 和finetune取得很好的效果。

TigerZ*的博客 1592

BLIP2源码阅读-LAVIS/app/__init__.py

可以把使用频率较高的一部分,如你最喜欢的那本或者你平时最常使用的那本,保存到一个触手可及的地方,如身边书架上,这样使用起来就会节省时间。device定义了模型在gpu上运行(如果gpu可用的话,即torch.cuda.is_available()),否则模型在cpu上运行,运行的速度会变慢。综上所述,这行代码的作用是从给定的网址下载图片,并将其转换为RGB模式,以便于进一步处理或显示。对象的一个属性,它提供了原始的响应内容(在这个情况下是图片的数据)。最后返回转换后的demo图片,供后续展示使用。

qq_46805255的博客 1142

【硬件设计】_基于STM32单片机的智能台灯系统

智能台灯系统是一款多功能的智能照明设备,能够自动调节亮度、监测人体活动、感知环境光照,并具备定时和报警功能,极大提升了用户体验与功能的灵活性,主要包括以下功能:系统提供自动和手动两种模式以调节台灯亮度。在自动模式下,台灯会根据周围光强智能调整;而在手动模式下,用户可通过按键自行设置亮度。利用红外光电开关检测台灯与用户之间的距离,若距离过近,系统将发出报警提示。通过时钟模块设置定时提醒,并在OLED显示屏上显示当前时间,当达到设定的定时时间时,蜂鸣器将发出报警音。

2401_85381181的博客 1731

BLIP和BLIP2

文章主要是对BLIP2 (使用冻结图像编码器和大型语言模型的Bootstrapping语言图像预训练)论文的阅读笔记,也对BLIP(用于统一视觉语言理解和生成的Bootstrapping语言图像预训练)算法进行了简单的介绍。

pan的博客 5882

[语义分割]SPP、空洞卷积与ASPP总结

ASPP全称:Atrous Spatial Pyramid Pooling,中文可以理解为空洞空间卷积池化金字塔或者多孔空间金字塔池化。在这其中,要理解两个概念:一个是SPP,池化金字塔结构或者叫空间金字塔池化层,都是一个东西;另一个是Atrous,空洞卷积,两个加在一起就是ASPP。 首先说一下SPP:Spatial Pyramid Pooling。这个结构出自于论文《Spatial Pyramid Pooling in Deep Convolutional Networks for Visual Re

lipengfei0427的博客 2万+

半桥LLC谐振变换器及同步整流MATLAB仿真(一)

LLC工作原理详细解析,工作过程详细拆解

qq_55203246的博客 3万+

BLIP2-图像文本预训练论文解读

BLIP-2,基于现有的图像编码器预训练模型,大规模语言模型进行预训练视觉语言模型;BLIP-2通过轻量级两阶段预训练模型Querying Transformer缩小模态之间gap,第一阶段从冻结图像编码器学习视觉语言表征,第二阶段基于冻结语言模型,进行视觉到语言生成学习;BLIP-2在各种视觉-语言模型达到SOTA。比如在zero-shot VQAv2上超越Flamingo80B 8.7%,也证明该模型可以根据自然语言指引进行zero-shot图像到文本生成;

持续关注并分享目标检测、数据生成、视频驱动、跨模态、分割、关键点等领域前沿技术 2万+

用友T3提示,年度[UFDATA_002_2017]并不存在,导致无法备份迁移。

用友T3提示,年度[UFDATA_002_2017]并不存在,导致无法备份迁移。现在都win11了某个年度账套不存在怎么办?

雨季余静的博客 3563

【多模态】BLIP-2模型技术学习

最近多模态模型特别火,从头开始学习!在前面写的几篇里面学习了MiniCPM-V、ViT、CLIP和BLIP之后,今天学习一下BLIP-2模型,记录学习过程,主要是模型架构、训练方式和相关源代码的理解。欢迎批评指正,一起学习~~

威化饼的一隅 2966

单细胞分析实战:当Seurat的SCTransform遇上Harmony,我的整合流程优化笔记

本文详细介绍了单细胞转录组数据分析中SCTransform与Harmony整合流程的优化策略。通过实战案例展示如何调整SCTransform参数、优化Harmony整合效果,并解决常见问题,帮助研究者获得更可靠的生物学发现。特别适合需要处理批次效应的单细胞数据分析人员。

weixin_42552716的博客 358

Autosar诊断实战系列05-Dcm之0x27加解密服务配置开发详解

UDS 0x27服务实战开发介绍,对解锁尝试次数及delay时间进一步解释。

initiallizer的博客 1993

blip2代码解析

请你作为一个代码翻译解释生成器,下面我会发送一个github链接给你,请你详细解析与介绍这个链接下代码 好的,请发送链接。 https://github.com/huggingface/transformers/blob/main/src/transformers/models/blip_2/ 这是Hugging Face开发的transformers库中的一个模型: “BLiP-2”。 “BL...

CodeInLinXu 2386

Windows 11 - 打开操作安全中心提示 “需要使用新应用以打开此 Windowsdefender 链接“ 解决方案(电脑更新了 Win11 系统版本后,想关闭病毒防护盾牌的时候提示打不开)

Windows 11 - 打开操作安全中心提示 "需要使用新应用以打开此 Windowsdefender 链接" 解决方案(电脑更新了 Win11 系统版本后,想关闭病毒防护盾牌的时候提示打不开),当您点击任务栏上要关闭安全中心防护设置时,这种情况打不开怎么解决,怎么办,Windows安全中心,病毒和威胁保护,账户保护,防火墙和网络保护,设备安全性。

🏆 前端领域优质创作者 1万+

BLIP2

BLIP2的任务是基于已有的固定参数的图像encoder和语言大模型(LLM)搭建一个具有图像理解能力的图文模型,输入是图像和文本,输出是文本。

icylling的专栏 1532

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

BLIP-2: 基于冻结图像编码器和大型语言模型的语言-图像预训练引导

BLIP-2是BLIP-2论文的官方实现,是一种通用且高效的预训练策略,可以轻松地利用预训练视觉模型和大型语言模型(LLMs)进行语言-图像预训练。BLIP-2在零-shot VQAv2上击败了Flamingo(65.0对56.3),在零-shot字幕生成上建立了新的技术水平(在NoCaps上的121.6 CIDEr分数,相对于之前的最佳113.2)。搭载强大的LLMs(如OPT、FlanT5),BLIP-2还为各种有趣的应用解锁了新的零-shot指导的视觉到语言生成能力!

OverlordDuke的博客 2863

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【多模态】6、BLIP-2 | 使用 Q-Former 连接冻结的图像和语言模型 实现高效图文预训练

本文主要介绍 BLIP-2

呆呆的猫的博客 1万+

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

万字长文解读深度学习——多模态模型BLIP2

本文解读BLIP2论文,阐述BLIP2在BLIP基础上的改进。

分享包括但不限于计算机基础知识、数据结构与算法、Golang技术栈。年与时驰,意与日去,遂成枯落,多不接世,悲守穷庐,将复何及! 2660

BLIP-2模型的详解与思考

本文主要讲解了多模态大模型BLIP-2,详细讲解了模型的结构与相关训练的方法。

gz7seven 2745

笔记:BLIP源码之(2)模型是如何定义的

BertEncoder 调用了 BertLayer, BertLayer调用了 BertAttention、BertIntermediate、BertOutput,其中BertAttention 又调用了 BertSelfAttention、BertOutput再回到BertModelBertPooler# 只对第一个token做pooling。

weixin_47505105的博客 1708

BLIP-2

下一代多模态模型的雏形最近ChatGPT风头正劲,但只能理解文字或多或少限制其才华的发挥。得益于Transformer在NLP和CV领域的大放异彩,多模态近几年取得了非常大的进步。但之前的工作大多数局限在几个特定的,比如VQA,ITR,VG等任务上,限制了其应用。最近,Junnan Li大佬挂出了他最新的杰作BLIP2。让我对多模态模型有了一些新的认识,希望通过本文分享一下我的想法。 whaosoft aiot http://143ai.com

whaosoft143ai的博客 1646

【BLIP/BLIP2/InstructBLIP】一篇文章快速了解BLIP系列(附代码讲解说明)

这样的好处在于对于同一张图片,根据不同的instruction,我们可以得到基于instruction偏好更强的视觉特征,同时对于两个不一样的图片,基于instruction内嵌的通用知识,可以使得模型有更好的知识迁移效果。Q-Former的文本输入,保证了Query提取到的特征更加的精炼。使用BLIP-2模型w/ViT-g和FlanT5XXL的指示零样本图像到文本生成的精选示例,其中显示了广泛的功能,包括视觉对话、视觉知识推理、视觉共感推理、故事讲述、个性化图像到文本的生成等。其他与BLIP2基本一样。

零碎@流年絮语 的博客 1万+
上一篇: InterLM代码解析
下一篇: Beam Search学习
银晗
博客等级 码龄6年 1万+粉丝 133原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值