news 2026/5/7 5:37:56

【llm】——计算llm的ppl损失

作者头像

张小明

前端开发工程师

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

代码:

# 浮点结果计算+ppl计算fromtransformersimportAutoModelForCausalLM,AutoTokenizerimportjsonfromtqdmimporttqdmimporttorchfromtorch.nnimportCrossEntropyLoss model_name="/data1/huf/Qwen3-0.6B"json_file="/data1/05_ax/01_eval/ppl/qnn/gsm8k_17d799.json"out_json_file="/data1/05_ax/01_eval/ppl/qnn/gsm8k_17d799_qwen3_0.6B_pred.json"num_samples=100device="cuda:7"# load the tokenizer and the modeltokenizer=AutoTokenizer.from_pretrained(model_name)model=AutoModelForCausalLM.from_pretrained(model_name,torch_dtype=torch.float32,device_map=device).to(device)deffind_subsequence(tensor,subsequence):len_tensor=len(tensor)len_subsequence=len(subsequence)foriinrange(len_tensor-len_subsequence+1):iftorch.equal(tensor[i:i+len_subsequence],subsequence):returnireturn-1# 如果没有找到子序列,返回 -1withopen(json_file,'r')asf:datas=json.loads(f.read())template="<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"loss=0.0num_batches=0forkey,itemintqdm(datas.items()):withtorch.no_grad():prompt=item['origin_prompt'][0]['prompt']prompt=template.format(prompt)inputs=tokenizer(prompt,return_tensors="pt").to(model.device)## 浮点模型输出generated_ids=model.generate(**inputs,max_new_tokens=128)output_ids=generated_ids[0][len(inputs.input_ids[0]):].tolist()try:index=len(output_ids)-output_ids[::-1].index(151668)exceptValueError:index=0thinking_content=tokenizer.decode(output_ids[:index],skip_special_tokens=True).strip("\n")content=tokenizer.decode(output_ids[index:],skip_special_tokens=True).strip("\n")## 将浮点结果写回jsonitem['prediction']=content# 计算浮点模型的pplnew_prompt=prompt+content new_inputs=tokenizer(new_prompt,return_tensors="pt").to(model.device)input_ids=new_inputs['input_ids']index=find_subsequence(input_ids[0],torch.tensor([151644,77091,198]).to(device))index=index+3+4## 将编码写入jsonitem['input_ids']=input_ids[0].cpu().numpy().tolist()item['gen_index']=index item['origin_prompt'][0]['new_prompt']=new_prompt outputs=model(input_ids)shift_logits=outputs.logits[...,index:-1,:].contiguous().to(dtype=torch.float32)shift_labels=input_ids[...,index+1:].contiguous().to(shift_logits.device)loss_fct=CrossEntropyLoss()ce_loss=loss_fct(shift_logits.view(-1,shift_logits.size(-1)),shift_labels.view(-1)).detach()loss+=ce_lossprint(f"ce_loss:{ce_loss:3f}, ppl:{ce_loss.exp():3f}")num_batches+=1ifnum_batches>=num_samples:breakloss=loss/num_batches ppl=loss.exp()print(f"ppl loss:{ppl:3f}")# 保存jsonwithopen(out_json_file,'w')asf:json.dump(datas,f,indent=4)
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/1 19:30:47

【HTML】五子棋AI对战代码

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

作者头像 李华
网站建设 2026/5/1 22:00:28

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

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

作者头像 李华
网站建设 2026/5/6 22:47:13

雷达静压水位计

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

作者头像 李华
网站建设 2026/4/30 11:03:11

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

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

作者头像 李华
网站建设 2026/5/1 20:52:56

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

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

作者头像 李华