news 2026/7/30 22:19:09

【VLM】——vlm计算ppl损失

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
【VLM】——vlm计算ppl损失

计算vlm模型的ppl损失。

代码:

fromtransformersimportQwen2VLForConditionalGeneration,AutoProcessorimporttorchfromtorch.nnimportCrossEntropyLossfromPILimportImage# 配置DEVICE="cuda:0"MODEL_NAME="/data1/chenjun/huf/Qwen2-VL-2B-Instruct"IMAGE_SIZE=384defresize_image(path,max_side=384):"""调整图片大小,保持宽高比"""image=Image.open(path).convert("RGB")width,height=image.sizeifwidth>height:new_width=max_side new_height=int(height*(max_side/width))else:new_height=max_side new_width=int(width*(max_side/height))return[image.resize((new_width,new_height),Image.Resampling.LANCZOS)]defmain():# 加载模型和处理器model=Qwen2VLForConditionalGeneration.from_pretrained(MODEL_NAME,dtype=torch.float32,device_map=DEVICE)processor=AutoProcessor.from_pretrained(MODEL_NAME)# 构建消息file='outputs/ppl_vlm_qwen3-vl-2b-axera-384/vit/0000.png'messages=[{"role":"user","content":[{"type":"image","image":file},{"type":"text","text":"描述这张图片"},],}]# 应用chat模板text=processor.apply_chat_template(messages,tokenize=False,add_generation_prompt=True)# 处理图片image_inputs=resize_image(file,IMAGE_SIZE)inputs=processor(text=[text],images=image_inputs,return_tensors="pt").to(DEVICE)gen_idx=inputs['input_ids'].shape[1]# 生成文本generated_ids=model.generate(**inputs,max_new_tokens=256)generated_ids_trimmed=[out_ids[len(in_ids):]forin_ids,out_idsinzip(inputs.input_ids,generated_ids)]output_text=processor.batch_decode(generated_ids_trimmed,skip_special_tokens=True,clean_up_tokenization_spaces=False)[0]# 计算PPLtext_with_response=text+output_text image_inputs=resize_image(file,IMAGE_SIZE)inputs2=processor(text=[text_with_response],images=image_inputs,return_tensors="pt").to(DEVICE)withtorch.no_grad():outputs=model(**inputs2,max_new_tokens=1)logits=outputs.logits# 计算交叉熵损失shift_labels=inputs2['input_ids'][...,gen_idx+1:].contiguous().to(DEVICE)shift_logits=logits[...,gen_idx:-1,:].contiguous().to(dtype=torch.float32)loss_fct=CrossEntropyLoss()ce_loss=loss_fct(shift_logits.view(-1,shift_logits.size(-1)),shift_labels.view(-1))print(f"ce_loss:{ce_loss:.3f}, ppl:{ce_loss.exp():.3f}")if__name__=="__main__":main()
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/7/25 9:25:35

【HTML】五子棋AI对战代码

我用夸克网盘给你分享了「五子棋源码」链接:https://pan.quark.cn/s/3590e43e8fa7 通过网盘分享的文件:五子棋代码 链接: https://pan.baidu.com/s/17dmCdrjcuXipFDhuUeaFLw?pwdid8r 提取码: id8r 下面是AI帮我总结的代码描述: 代码结构 1. …

作者头像 李华
网站建设 2026/7/24 19:31:13

CANN图编译器与执行器GE的架构设计与性能优化技术深度解析

CANN图编译器与执行器GE的架构设计与性能优化技术深度解析 cann 组织链接:https://atomgit.com/cann ge仓库解读链接:https://atomgit.com/cann/ge 在深度学习模型的部署和执行过程中,如何将高级神经网络模型高效地映射到底层硬件上&#x…

作者头像 李华
网站建设 2026/7/25 3:24:29

雷达静压水位计

一、设备概述与应用背景 雷达静压水位计是深圳市恒星物联科技有限公司研发的一款采用扩散硅和雷达双元件进行液位测量的液位智能监测仪表,专门为地表或管网水的非接触式液位测量设计。该产品采用微功耗设计,高度集成了毫米波雷达测距、压力传感、RTU数据…

作者头像 李华
网站建设 2026/7/31 1:33:45

【AI开发】—— AI开发基础之LLM、Agent、MCP、Skill

LLM、Agent、MCP、Skill四大核心概念辨析|从基础模型到多智能体落地 随着大模型智能体(Agent)技术的快速迭代,LLM、Agent、MCP、Skill这四个概念频繁出现在技术文档、开发实践和研究论文中。很多开发者和研究者在入门阶段容易混淆…

作者头像 李华
网站建设 2026/7/30 13:04:59

新手也能上手!当红之选的AI论文写作软件 —— 千笔·专业学术智能体

你是否曾在论文写作中感到力不从心?选题无头绪、资料难查找、格式总出错、查重率高得让人焦虑……这些困扰是否让你夜不能寐?作为一位正在经历论文挑战的本科生,你并不孤单。现在,一款专为学生打造的AI论文写作工具——千笔AI&…

作者头像 李华