news 2026/9/3 1:35:36

【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/9/2 16:12:29

打工人上班摸魚小說-第十章 钓鱼邮件、边界测试与“灵感”再现

第十章 钓鱼邮件、边界测试与“灵感”再现 匿名信引发的暗流,在接下来的几天里并未平息,反而有愈演愈烈之势。 OA系统上的安全通告越发密集,措辞也一次比一次严厉。专项审查小组正式成立的消息被高亮置顶,后面附着一长串需要配合…

作者头像 李华
网站建设 2026/9/3 0:21:48

AI 赋能:如何利用大模型自动生成企微外部群高转化率文案?

​QiWe开放平台 个人名片 API驱动企微自动化,让开发更高效 核心能力:API 驱动企微自动化,提升开发效率 官方站点:https://www.qiweapi.com 对接通道:进入官方站点联系客服 团队定位:企微生态深度服务&…

作者头像 李华
网站建设 2026/9/3 0:22:24

CST案例:Interference Task车载GPS天线射频干扰desense仿真.docx

作者 | Zhou Ming 对于射频系统来说,潜在的数字电路干扰源除了时钟CLK信号外,还有可能是来自数据信号,数据信号的产生的频谱通常是宽频带的,如上图所示,我们称为任意噪声谱(Arbitrary Noise Spectrum&#…

作者头像 李华