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

llama3源码解读之推理-infer

文章目录

  • 前言
  • 一、整体源码解读
    • 1、完整main源码
    • 2、tokenizer加载
    • 3、llama3模型加载
    • 4、llama3测试数据文本加载
    • 5、llama3模型推理模块
      • 1、模型推理模块的数据处理
      • 2、模型推理模块的model.generate预测
      • 3、模型推理模块的预测结果处理
    • 6、多轮对话
  • 二、llama3推理数据处理
    • 1、完整数据处理源码
    • 2、使用prompt方式询问数据加载
    • 3、推理处理数据
  • 三、llama3推理generate调用_sample方法
    • 1、GenerationMode.SAMPLE方法源码
    • 2、huggingface的_sample源码
    • 3、_sample的初始化与准备
    • 4、_sample的初始化(attention / hidden states / scores)
    • 5、encoder-decoder模式模型处理
    • 6、保持相应变量内容
    • 7、进入while循环模块
    • 8、结果返回处理
  • 四、_sample的while循环模块内容
    • 1、模型输入加工
      • 1、首次迭代数据加工
      • 2、再次迭代数据加工
    • 2、模型推理
      • 1、首次迭代数据加工
      • 2、再次迭代数据加工
    • 3、预测结果取值
    • 4、预测logits惩罚处理
    • 5、预测softmax处理
    • 6、预测token选择处理
    • 7、停止条件更新处理
    • 8、再次循环迭代input_ids与attention_mask处理(生成式预测)
    • 8、停止条件再次更新与处理
  • 五、模型推理(self)
    • 1、模型预测输入参数
    • 2、进入包装选择调用方法
    • 3、进入forward函数--class LlamaForCausalLM(LlamaPreTrainedModel)
    • 4、llama3推理forward的前提说明
    • 5、llama3推理forward的设置参数
    • 6、llama3推理forward的推理(十分重要)
    • 7、llama3推理forward的的lm_head转换
    • 8、llama3推理forward的结果包装(CausalLMOutputWithPast)
  • 六、llama3模型forward的self.model方法
    • 1、模型输入内容
      • 1、self.model模型初次输入内容
      • 2、self.model模型再次输入内容
    • 2、进入包装选择调用方法
    • 3、进入forward函数--class LlamaModel(LlamaPreTrainedModel)
    • 4、llama3模型forward的源码
    • 5、llama3模型forward的输入准备与embedding
      • 1、初次输入llama3模型内容
      • 2、再此输入llama3模型内容
      • 3、说明
    • 6、llama3模型forward的cache
      • 1、DynamicCache.from_legacy_cache(past_key_values)函数
      • 2、cache = cls()类方法
        • 该类位置
        • 该类方法
      • 2、cache.update的更新
    • 7、llama3模型decoder_layer方法
      • 1、decoder_layer调用源码
      • 2、decoder_layer源码方法与调用self.self_attn方法
      • 3、self.self_attn源码方法
    • 8、hidden_states的LlamaRMSNorm
    • 9、next_cache保存与输出结果
  • 七、llama3模型atten方法
    • 1、模型位置
    • 2、llama3推理模型初始化
    • 3、llama3推理的forward方法
    • 4、llama3模型结构图


前言

本项目是解读开源github的代码,该项目基于Meta最新发布的新一代开源大模型Llama-3开发,是Chinese-LLaMA-Alpaca开源大模型相关系列项目(一期、二期)的第三期。而本项目开源了中文Llama-3基座模型和中文Llama-3-Instruct指令精调大模型。这些模型在原版Llama-3的基础上使用了大规模中文数据进行增量预训练,并且使用精选指令数据进行精调,进一步提升了中文基础语义和指令理解能力,相比二代相关模型获得了显著性能提升。因此,我是基于该项目解读训练与推理相关原理与内容,并以代码形式带领读者一步一步解读,理解其大语言模型运行机理。而该博客首先给出llama3推理源码相关内容解读,我将按照源码流程给出解读。


一、整体源码解读

1、完整main源码

我先给出完整的源码,后面推理使用哪些部分代码,我在深度解读。而一些较为简单内容我不在解读了。

if __name__ == '__main__':load_type = torch.float16# Move the model to the MPS device if availableif torch.backends.mps.is_available():device = torch.device("mps")else:if torch.cuda.is_available():device = torch.device(0)else:device = torch.device('cpu')print(f"Using device: {device}")if args.tokenizer_path is None:args.tokenizer_path = args.base_modeltokenizer = AutoTokenizer.from_pretrained(args.tokenizer_path)terminators = [tokenizer.eos_token_id,tokenizer.convert_tokens_to_ids("<|eot_id|>")]if args.use_vllm:model = LLM(model=args.base_model,tokenizer=args.tokenizer_path,tensor_parallel_size=len(args.gpus.split(',')),dtype=load_type)generation_config["stop_token_ids"] = terminatorsgeneration_config["stop"] = ["<|eot_id|>", "<|end_of_text|>"]else:if args.load_in_4bit or args.load_in_8bit:quantization_config = BitsAndBytesConfig(load_in_4bit=args.load_in_4bit,load_in_8bit=args.load_in_8bit,bnb_4bit_compute_dtype=load_type,bnb_4bit_use_double_quant=True,bnb_4bit_quant_type="nf4")model = AutoModelForCausalLM.from_pretrained(args.base_model,torch_dtype=load_type,low_cpu_mem_usage=True,device_map='auto',quantization_config=quantization_config if (args.load_in_4bit or args.load_in_8bit) else None,attn_implementation="flash_attention_2" if args.use_flash_attention_2 else "sdpa")if device==torch.device('cpu'):model.float()model.eval()# test dataif args.data_file is None:examples = sample_dataelse:with open(args.data_file, 'r') as f:examples = [line.strip() for line in f.readlines()]print("first 10 examples:")for example in examples[:10]:print(example)with torch.no_grad():if args.interactive:print("Start inference with instruction mode.")print('='*85)print("+ 该模式下仅支持单轮问答,无多轮对话能力。\n""+ 如要进行多轮对话,请使用llama.cpp")print('-'*85)print("+ This mode only supports single-turn QA.\n""+ If you want to experience multi-turn dialogue, please use llama.cpp")print('='*85)while True:raw_input_text = input("Input:")if len(raw_input_text.strip())==0:breakif args.with_prompt:input_text = generate_prompt(instruction=raw_input_text)else:input_text = raw_input_textif args.use_vllm:output = model.generate([input_text], SamplingParams(**generation_config), use_tqdm=False)response = output[0].outputs[0].textelse:inputs = tokenizer(input_text,return_tensors="pt")  #add_special_tokens=False ?generation_output = model.generate(input_ids = inputs["input_ids"].to(device),attention_mask = inputs['attention_mask'].to(device),eos_token_id=terminators,pad_token_id=tokenizer.eos_token_id,generation_config = generation_config)s = generation_output[0]output = tokenizer.decode(s, skip_special_tokens=True)if args.with_prompt:response = output.split("assistant\n\n")[-1].strip()else:response = outputprint("Response: ",response)print("\n")else:print("Start inference.")results = []if args.use_vllm:if args.with_prompt is True:inputs = [generate_prompt(example) for example in examples]else:inputs = examplesoutputs = model.generate(inputs, SamplingParams(**generation_config))for index, (example, output) in enumerate(zip(examples, outputs)):response = output.outputs[0].textprint(f"======={index}=======")print(f"Input: {example}\n")print(f"Output: {response}\n")results.append({"Input":example,"Output":response})else:for index, example in enumerate(examples):if args.with_prompt:input_text = generate_prompt(instruction=example)else:input_text = exampleinputs = tokenizer(input_text,return_tensors="pt")  #add_special_tokens=False ?generation_output = model.generate(input_ids = inputs["input_ids"].to(device),attention_mask = inputs['attention_mask'].to(device),eos_token_id=terminators,pad_token_id=tokenizer.eos_token_id,generation_config = generation_config)s = generation_output[0]output = tokenizer.decode(s,skip_special_tokens=True)if args.with_prompt:response = output.split("assistant\n\n")[1].strip()else:response = outputprint(f"======={index}=======")print(f"Input: {example}\n")print(f"Output: {response}\n")results.append({"Input":input_text,"Output":response})dirname = os.path.dirname(args.predictions_file)os.makedirs(dirname,exist_ok=True)with open(args.predictions_file,'w') as f:json.dump(results,f,ensure_ascii=False,indent=2)if args.use_vllm:with open(dirname+'/generation_config.json','w') as f:json.dump(generation_config,f,ensure_ascii=False,indent=2)else:generation_config.save_pretrained('./')

2、tokenizer加载

有关tokenzier相关加载可参考博客这里。这里,我直接给出其源码,如下:

tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_path)
terminators = [tokenizer.eos_token_id,tokenizer.convert_tokens_to_ids("<|eot_id|>")]

tokenizer.eos_token_id=128009,而terminators=[128009,128009]。

3、llama3模型加载

huggingface模型加载可参考博客这里。这里,llama3的模型加载不在介绍,如下源码:

model = AutoModelForCausalLM.from_pretrained(args.base_model,  # 权重路径文件夹torch_dtype=load_type,low_cpu_mem_usage=True,device_map='auto',quantization_config=quantization_config if (args.load_in_4bit or args.load_in_8bit) else None,attn_implementation="flash_attention_2" if args.use_flash_attention_2 else "sdpa"
)
if device==torch.device('cpu'):model.float()
model.eval()

注意:model.eval()为固定权重方式,这是pytorch评估类似。

4、llama3测试数据文本加载

 # test dataif args.data_file is None:examples = sample_data  #  ["为什么要减少污染,保护环境?","你有什么建议?"]else:with open(args.data_file, 'r') as f:examples 

相关文章:

llama3源码解读之推理-infer

文章目录 前言一、整体源码解读1、完整main源码2、tokenizer加载3、llama3模型加载4、llama3测试数据文本加载5、llama3模型推理模块1、模型推理模块的数据处理2、模型推理模块的model.generate预测3、模型推理模块的预测结果处理6、多轮对话二、llama3推理数据处理1、完整数据…...

【教程】Linux安装Redis步骤记录

下载地址 Index of /releases/ Downloads - Redis 安装redis-7.4.0.tar.gz 1.下载安装包 wget https://download.redis.io/releases/redis-7.4.0.tar.gz 2.解压 tar -zxvf redis-7.4.0.tar.gz 3.进入目录 cd redis-7.4.0/ 4.编译 make 5.安装 make install PREFIX/u…...

全球汽车线控制动系统市场规模预测:未来六年CAGR为17.3%

引言&#xff1a; 随着汽车行业的持续发展和对安全性能需求的增加&#xff0c;汽车线控制动系统作为提升车辆安全性和操控性的关键组件&#xff0c;正逐渐受到市场的广泛关注。本文旨在通过深度分析汽车线控制动系统行业的各个维度&#xff0c;揭示行业发展趋势和潜在机会。 【…...

Ubuntu运行深度学习代码,代码随机epoch中断没有任何报错

深度学习运行代码直接中断 文章目录 深度学习运行代码直接中断问题描述设备信息问题补充解决思路问题发现及正确解决思路新问题出现最终问题&#xff1a;ubuntu系统&#xff0c;4090显卡安装英伟达驱动535.x外的驱动会导致开机无法进入桌面问题记录 问题描述 运行深度学习代码…...

只有4%知道的Linux,看了你也能上手Ubuntu桌面系统,Ubuntu简易设置,源更新,root密码,远程服务...

创作不易 只因热爱!! 热衷分享&#xff0c;一起成长! “你的鼓励就是我努力付出的动力” 最近常提的一句话&#xff0c;那就是“但行好事&#xff0c;莫问前程"! 与辉同行的董工说​&#xff1a;​守正出奇。坚持分享&#xff0c;坚持付出&#xff0c;坚持奉献&#xff0c…...

Tomcat部署——个人笔记

Tomcat部署——个人笔记 文章目录 [toc]简介安装配置文件WEB项目的标准结构WEB项目部署IDEA中开发并部署运行WEB项目 本学习笔记参考尚硅谷等教程。 简介 Apache Tomcat 官网 Tomcat是Apache 软件基金会&#xff08;Apache Software Foundation&#xff09;的Jakarta 项目中…...

常见且重要的用户体验原则

以下是一些常见且重要的用户体验原则&#xff1a; 1. 以用户为中心 - 深入了解用户的需求、期望、目标和行为习惯。通过用户研究、调查、访谈等方法获取真实的用户反馈&#xff0c;以此来设计产品或服务。 - 例如&#xff0c;在设计一款老年手机时&#xff0c;充分考虑老年…...

web基础及nginx搭建

第四周 上午 静态资源 根据开发者保存在项目资源目录中的路径访问静态资源 html 图片 js css 音乐 视频 f12 &#xff0c;开发者工具&#xff0c;网络 1 、 web 基本概念 web 服务器&#xff08; web server &#xff09;&#xff1a;也称 HTTP 服务器&#xff08; HTTP …...

C++ 布隆过滤器

1. 布隆过滤器提出 我们在使用新闻客户端看新闻时&#xff0c;它会给我们不停地推荐新的内容&#xff0c;它每次推荐时要去重&#xff0c;去掉 那些已经看过的内容。问题来了&#xff0c;新闻客户端推荐系统如何实现推送去重的&#xff1f; 用服务器记录了用 户看过的所有历史…...

使用HTML创建用户注册表单

在当今数字化时代&#xff0c;网页表单对于收集用户信息和促进网站交互至关重要。无论您设计简单的注册表单还是复杂的调查表&#xff0c;了解HTML的基础知识可以帮助您构建有效的用户界面。在本教程中&#xff0c;我们将详细介绍如何使用HTML创建基本的用户注册表单。 第一步…...

Python零基础入门教程

Python零基础详细入门教程可以从以下几个方面进行学习和掌握&#xff1a; 一、Python基础认知 1. Python简介 由来与发展&#xff1a;Python是一种广泛使用的高级编程语言&#xff0c;由Guido van Rossum&#xff08;吉多范罗苏姆&#xff09;于1991年首次发布。Python以其简…...

成为git砖家(10): 根据文件内容生成SHA-1

文章目录 1. .git/objects 目录2. git cat-file 命令3. 根据文件内容生成 sha-14. 结语5. References 1. .git/objects 目录 git 是一个根据文件内容进行检索的系统。 当创建 hello.py, 填入 print("hello, world")的内容&#xff0c; 并执行 git add hello.py gi…...

园区导航小程序:一站式解决园区导航问题,释放存储,优化访客体验

随着园区的规模不断扩大&#xff0c;功能区划分日益复杂&#xff0c;导致访客和新员工在没有有效导航的情况下容易迷路。传统APP导航虽能解决部分问题&#xff0c;但其下载安装繁琐、占用手机内存大、且非高频使用导致的闲置&#xff0c;让许多用户望而却步。园区导航小程序的出…...

对于n进制转十进制的解法及代码(干货!)

对于p进制转十进制&#xff0c;我们有&#xff1a;(x)pa[0]*p^0a[1]*p^1a[2]*p^2...a[n]*p^n 举个例子&#xff1a;&#xff08;11001&#xff09;21*10*20*41*81*1625 &#xff08;9FA&#xff09;1610*16^015*16^19*16^22554 据此&#xff0c;我们可以编出c代码来解决问题 …...

当代互联网打工人的生存现状,看完泪流满面!

欢迎私信小编&#xff0c;了解更多产品信息呦~...

花几千上万学习Java,真没必要!(三十八)

测试代码1&#xff1a; package iotest.com; import java.nio.charset.StandardCharsets; import java.io.UnsupportedEncodingException; public class StringByteConversion { public static void main(String[] args) throws UnsupportedEncodingException { // 原始字…...

Zilliz 2025届校园招聘正式启动,寻找向量数据库内核开发工程师

为了解决非结构化数据处理问题&#xff0c;我们构建了向量数据库-Milvus! Milvus 数据库不仅是顶级开源基金会 LF AI&Data 的毕业项目&#xff0c;还曾登上数据库顶会SIGMOD、VLDB&#xff0c;在全球首届向量检索比赛中夺冠。目前&#xff0c;Milvus 项目已获得超过 2.8w s…...

TwinCAT3 新建项目教程

文章目录 打开TwinCAT 新建项目&#xff08;通过TcXaeShell&#xff09; 新建项目&#xff08;通过VS 2019&#xff09;...

大模型算法面试题(十九)

本系列收纳各种大模型面试题及答案。 1、SFT&#xff08;有监督微调&#xff09;、RM&#xff08;奖励模型&#xff09;、PPO&#xff08;强化学习&#xff09;的数据集格式&#xff1f; SFT&#xff08;有监督微调&#xff09;、RM&#xff08;奖励模型&#xff09;、PPO&…...

应用地址信息获取新技巧:Xinstall来助力

在移动互联网时代&#xff0c;应用获取用户地址信息的需求越来越普遍。无论是为了提供个性化服务&#xff0c;还是进行精准营销&#xff0c;地址信息都扮演着至关重要的角色。然而&#xff0c;如何合规、准确地获取这一信息&#xff0c;却是许多开发者面临的挑战。今天&#xf…...

RestClient

什么是RestClient RestClient 是 Elasticsearch 官方提供的 Java 低级 REST 客户端&#xff0c;它允许HTTP与Elasticsearch 集群通信&#xff0c;而无需处理 JSON 序列化/反序列化等底层细节。它是 Elasticsearch Java API 客户端的基础。 RestClient 主要特点 轻量级&#xff…...

Appium+python自动化(十六)- ADB命令

简介 Android 调试桥(adb)是多种用途的工具&#xff0c;该工具可以帮助你你管理设备或模拟器 的状态。 adb ( Android Debug Bridge)是一个通用命令行工具&#xff0c;其允许您与模拟器实例或连接的 Android 设备进行通信。它可为各种设备操作提供便利&#xff0c;如安装和调试…...

vulnyx Blogger writeup

信息收集 arp-scan nmap 获取userFlag 上web看看 一个默认的页面&#xff0c;gobuster扫一下目录 可以看到扫出的目录中得到了一个有价值的目录/wordpress&#xff0c;说明目标所使用的cms是wordpress&#xff0c;访问http://192.168.43.213/wordpress/然后查看源码能看到 这…...

群晖NAS如何在虚拟机创建飞牛NAS

套件中心下载安装Virtual Machine Manager 创建虚拟机 配置虚拟机 飞牛官网下载 https://iso.liveupdate.fnnas.com/x86_64/trim/fnos-0.9.2-863.iso 群晖NAS如何在虚拟机创建飞牛NAS - 个人信息分享...

基于PHP的连锁酒店管理系统

有需要请加文章底部Q哦 可远程调试 基于PHP的连锁酒店管理系统 一 介绍 连锁酒店管理系统基于原生PHP开发&#xff0c;数据库mysql&#xff0c;前端bootstrap。系统角色分为用户和管理员。 技术栈 phpmysqlbootstrapphpstudyvscode 二 功能 用户 1 注册/登录/注销 2 个人中…...

BLEU评分:机器翻译质量评估的黄金标准

BLEU评分&#xff1a;机器翻译质量评估的黄金标准 1. 引言 在自然语言处理(NLP)领域&#xff0c;衡量一个机器翻译模型的性能至关重要。BLEU (Bilingual Evaluation Understudy) 作为一种自动化评估指标&#xff0c;自2002年由IBM的Kishore Papineni等人提出以来&#xff0c;…...

PHP 8.5 即将发布:管道操作符、强力调试

前不久&#xff0c;PHP宣布了即将在 2025 年 11 月 20 日 正式发布的 PHP 8.5&#xff01;作为 PHP 语言的又一次重要迭代&#xff0c;PHP 8.5 承诺带来一系列旨在提升代码可读性、健壮性以及开发者效率的改进。而更令人兴奋的是&#xff0c;借助强大的本地开发环境 ServBay&am…...

libfmt: 现代C++的格式化工具库介绍与酷炫功能

libfmt: 现代C的格式化工具库介绍与酷炫功能 libfmt 是一个开源的C格式化库&#xff0c;提供了高效、安全的文本格式化功能&#xff0c;是C20中引入的std::format的基础实现。它比传统的printf和iostream更安全、更灵活、性能更好。 基本介绍 主要特点 类型安全&#xff1a…...

深度剖析 DeepSeek 开源模型部署与应用:策略、权衡与未来走向

在人工智能技术呈指数级发展的当下&#xff0c;大模型已然成为推动各行业变革的核心驱动力。DeepSeek 开源模型以其卓越的性能和灵活的开源特性&#xff0c;吸引了众多企业与开发者的目光。如何高效且合理地部署与运用 DeepSeek 模型&#xff0c;成为释放其巨大潜力的关键所在&…...

嵌入式学习之系统编程(九)OSI模型、TCP/IP模型、UDP协议网络相关编程(6.3)

目录 一、网络编程--OSI模型 二、网络编程--TCP/IP模型 三、网络接口 四、UDP网络相关编程及主要函数 ​编辑​编辑 UDP的特征 socke函数 bind函数 recvfrom函数&#xff08;接收函数&#xff09; sendto函数&#xff08;发送函数&#xff09; 五、网络编程之 UDP 用…...