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

保定网站制作费用dedecms织梦和wordpress

保定网站制作费用,dedecms织梦和wordpress,在库言库建筑网站,网站维护主要有哪些内容和方法文章目录 前言一、整体源码解读1、完整main源码2、tokenizer加载3、llama3模型加载4、llama3测试数据文本加载5、llama3模型推理模块1、模型推理模块的数据处理2、模型推理模块的model.generate预测3、模型推理模块的预测结果处理6、多轮对话二、llama3推理数据处理1、完整数据…

文章目录

  • 前言
  • 一、整体源码解读
    • 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 
http://www.yayakq.cn/news/209946/

相关文章:

  • 云虚拟主机怎么建设网站网站建设好推荐
  • 钓鱼网站制作开发公司没有资质有什么影响
  • 网站地链接结构在那个网站做任务赚
  • 做cra需要关注的网站网站服务器租用年度价格
  • 做qq动图的网站wordpress文章目录页面
  • 西安企业网站建设价格网站建设评审
  • 企业网站关键字优化尚海整装装修怎么样
  • 如何建设备案网站视频教程宁波网络公司哪家最好
  • 用php做网站需要什么公司的网 网站打不开怎么办
  • 浙江网商银行电话乐陵seo外包
  • 深圳php网站建设网站建设需要什么手续
  • 做网站是不是要域名费放心网络营销定制
  • 莘县做网站网站推广设计方案目标怎么写
  • 给别人网站做跳转Wordpress按钮添加跳转
  • 电脑登录不了建设银行网站做企业网站还有市场吗
  • 中国流量最大的网站排行收益网站制作
  • 网站精简布局免费网站模版
  • 网站开发具体的工作内容手机网站你懂
  • 小说网站如何赚钱网页设计图片滑动代码
  • 广东品牌网站建设多少钱网页版微信官方免费
  • 惠州seo报价seo网站优化网站编辑招聘
  • 移动网站开发做一个简单网页网站后台流程图
  • 网站建设设置背景图片wordpress和iss
  • 西安网站seo价格专门做三国战纪的网站叫什么意思
  • 南昌建站价格东莞饭堂承包东莞网站建设
  • 建设部职称证书查询官方网站北京app开发流程
  • 有哪些学做衣服的网站建筑咨询
  • 效果好的徐州网站建设广告素材网站哪个比较好
  • 开网站 怎么做网上支付书店网站建设需求分析调研表
  • 通过高新区网站建设昆明最新新闻事件今天