当前位置: 首页 > news >正文

Ovis1.6-9B视觉大模型环境搭建推理

引子

前阵子,阿里Qwen2-VL刚刚闪亮登场,感兴趣的小伙伴可以移步Qwen2-VL环境搭建&推理测试-CSDN博客。这第一的宝座还没坐多久,自家兄弟Ovis1.6版本就来了,20240919阿里国际AI团队开源多模态大模型Ovis1.6。在多模态权威综合评测基准OpenCompass上,Ovis1.6-Gemma2-9B版本综合得分超越Qwen2VL-7B、InternVL2-26B和MiniCPM-V-2.6等主流开源模型,在300亿以下参数开源模型中位居第一。

一、模型介绍

根据OpenCompass评测基准,Ovis1.6-Gemma2-9B超过了Qwen2-VL-7B、MiniCPM-V-2.6等一众相同参数量级的知名多模态模型。在数学等推理任务中,甚至有媲美70B参数模型的表现。Ovis1.6的幻觉现象和错误率也低于同级别模型,展现了更高的文本质量和准确率。阿里国际AI团队的核心思路是:从结构上对齐视觉和文本嵌入。当前,多数开源多模态大语言模型(MLLM)并非从头训练整个模型,而是通过像多层感知机(MLP)这样的连接器,将预训练的大语言模型(LLM)和视觉Transformer集成起来,给LLM装上“眼睛”。这样一来,就导致了一个问题:MLLM的文本和视觉模块采用不同的嵌入策略,使得视觉和文本信息没办法无缝融合,限制了模型性能的进一步提升。针对这个问题,Ovis采用了视觉tokenizer+视觉嵌入表+大语言模型的架构。

二、环境搭建

1、模型下载

https://huggingface.co/AIDC-AI/Ovis1.6-Gemma2-9B/tree/main

2、环境安装

docker run -it --rm --gpus=all -v /datas/work/zzq:/workspace pytorch/pytorch:2.2.2-cuda12.1-cudnn8-devel bash

git clone https://github.com/AIDC-AI/Ovis.git

cd /workspace/Ovis/Ovis-main

pip install -r requirements.txt -i Simple Index

pip install -e .

三、推理测试

1、修改代码

from dataclasses import field, dataclass
from typing import Optional, Union, Listimport torch
from PIL import Imagefrom ovis.model.modeling_ovis import Ovis
from ovis.util.constants import IMAGE_TOKEN@dataclass
class RunnerArguments:model_path: strmax_new_tokens: int = field(default=512)do_sample: bool = field(default=False)top_p: Optional[float] = field(default=None)top_k: Optional[int] = field(default=None)temperature: Optional[float] = field(default=None)max_partition: int = field(default=9)class OvisRunner:def __init__(self, args: RunnerArguments):self.model_path = args.model_path# self.dtype = torch.bfloat16self.device = torch.cuda.current_device()# self.dtype = torch.bfloat16self.dtype = torch.float16self.model = Ovis.from_pretrained(self.model_path, torch_dtype=self.dtype, multimodal_max_length=8192)self.model = self.model.eval().to(device=self.device)self.eos_token_id = self.model.generation_config.eos_token_idself.text_tokenizer = self.model.get_text_tokenizer()self.pad_token_id = self.text_tokenizer.pad_token_idself.visual_tokenizer = self.model.get_visual_tokenizer()self.conversation_formatter = self.model.get_conversation_formatter()self.image_placeholder = IMAGE_TOKENself.max_partition = args.max_partitionself.gen_kwargs = dict(max_new_tokens=args.max_new_tokens,do_sample=args.do_sample,top_p=args.top_p,top_k=args.top_k,temperature=args.temperature,repetition_penalty=None,eos_token_id=self.eos_token_id,pad_token_id=self.pad_token_id,use_cache=True)def preprocess(self, inputs: List[Union[Image.Image, str]]):# for single image and single text inputs, ensure image aheadif len(inputs) == 2 and isinstance(inputs[0], str) and isinstance(inputs[1], Image.Image):inputs = reversed(inputs)# build queryquery = ''images = []for data in inputs:if isinstance(data, Image.Image):query += self.image_placeholder + '\n'images.append(data)elif isinstance(data, str):query += data.replace(self.image_placeholder, '')elif data is not None:raise RuntimeError(f'Invalid input type, expected `PIL.Image.Image` or `str`, but got {type(data)}')# format conversationprompt, input_ids, pixel_values = self.model.preprocess_inputs(query, images, max_partition=self.max_partition)attention_mask = torch.ne(input_ids, self.text_tokenizer.pad_token_id)input_ids = input_ids.unsqueeze(0).to(device=self.device)attention_mask = attention_mask.unsqueeze(0).to(device=self.device)if pixel_values is not None:pixel_values = [pixel_values.to(device=self.device, dtype=self.dtype)]else:pixel_values = [None]return prompt, input_ids, attention_mask, pixel_valuesdef run(self, inputs: List[Union[Image.Image, str]]):prompt, input_ids, attention_mask, pixel_values = self.preprocess(inputs)output_ids = self.model.generate(input_ids,pixel_values=pixel_values,attention_mask=attention_mask,**self.gen_kwargs)output = self.text_tokenizer.decode(output_ids[0], skip_special_tokens=True)input_token_len = input_ids.shape[1]output_token_len = output_ids.shape[1]response = dict(prompt=prompt,output=output,prompt_tokens=input_token_len,total_tokens=input_token_len + output_token_len)return responseif __name__ == '__main__':# runner_args = RunnerArguments(model_path='<model_path>')runner_args = RunnerArguments(model_path='/workspace/Ovis/Ovis-main/models')runner = OvisRunner(runner_args)# image = Image.open('<image_path>')image = Image.open('/workspace/Ovis/Ovis-main/test.png')# text = '<prompt>'text = 'solve the question in this image'response = runner.run([image, text])print(response['output'])

python ovis/serve/runner.py

好吧,显存不够

相关文章:

  • 实验报告2-前端框架和模板引擎实现视图
  • Kali Linux入门教程(非常详细)从零基础入门到精通,看完这一篇就够了。
  • 【并发】ThreadLocal 为什么会内存泄露
  • WAF,全称Web Application Firewall,好用WAF推荐
  • Ubuntu上安装Git:简单步骤指南
  • 字母象形:十分有趣的单词扩展逻辑
  • 联想电脑怎么开启vt_联想电脑开启vt虚拟化教程(附intel和amd主板开启方法)
  • 等保测评:企业数字安全的坚实盾牌
  • 【2024.9.29练习】R 格式
  • 在Spring项目中使用MD5对数据库加密
  • 【计算机网络】详解HTTP请求和响应格式常见请求方法Header报头响应报文状态码URL
  • C语言-进程控制编程
  • ceph rgw 桶分片之reshard
  • The Sandbox 游戏制作教程第 6 章|如何使用装备制作出色的游戏 —— 避免环境危险
  • 数据库 - python操作MySQL
  • -------------------- 第二讲-------- 第一节------在此给出链表的基本操作
  • android高仿小视频、应用锁、3种存储库、QQ小红点动画、仿支付宝图表等源码...
  • AWS实战 - 利用IAM对S3做访问控制
  • CSS进阶篇--用CSS开启硬件加速来提高网站性能
  • express + mock 让前后台并行开发
  • java概述
  • learning koa2.x
  • 大快搜索数据爬虫技术实例安装教学篇
  • 动态魔术使用DBMS_SQL
  • 飞驰在Mesos的涡轮引擎上
  • 好的网址,关于.net 4.0 ,vs 2010
  • 将 Measurements 和 Units 应用到物理学
  • 普通函数和构造函数的区别
  • 强力优化Rancher k8s中国区的使用体验
  • 入职第二天:使用koa搭建node server是种怎样的体验
  • 设计模式走一遍---观察者模式
  • 视频flv转mp4最快的几种方法(就是不用格式工厂)
  • 手写双向链表LinkedList的几个常用功能
  • UI设计初学者应该如何入门?
  • 移动端高清、多屏适配方案
  • # SpringBoot 如何让指定的Bean先加载
  • #vue3 实现前端下载excel文件模板功能
  • (003)SlickEdit Unity的补全
  • (2024)docker-compose实战 (9)部署多项目环境(LAMP+react+vue+redis+mysql+nginx)
  • (4.10~4.16)
  • (6)STL算法之转换
  • (ctrl.obj) : error LNK2038: 检测到“RuntimeLibrary”的不匹配项: 值“MDd_DynamicDebug”不匹配值“
  • (Forward) Music Player: From UI Proposal to Code
  • (Matlab)基于蝙蝠算法实现电力系统经济调度
  • (php伪随机数生成)[GWCTF 2019]枯燥的抽奖
  • (编译到47%失败)to be deleted
  • (二)fiber的基本认识
  • (二)七种元启发算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划MATLAB
  • (附源码)springboot工单管理系统 毕业设计 964158
  • (每日持续更新)信息系统项目管理(第四版)(高级项目管理)考试重点整理 第13章 项目资源管理(七)
  • (数据结构)顺序表的定义
  • (四)Controller接口控制器详解(三)
  • (一)基于IDEA的JAVA基础12
  • (转)http协议
  • .net core 6 集成和使用 mongodb