Llama3.1 是怎么工作哒?原文翻译版

了解Llama3.1如何工作——深入探讨模型流程

原文标题:Understand How Llama3.1 Works — A Deep Dive Into the Model Flow

原作者:Xiaojian Yu

原文链接:https://medium.com/@yuxiaojian/understand-how-llama3-1-works-a-deep-dive-into-the-model-flow-b149aba04bed

翻译:岁月月宝贝?


目录


像Llama 3.1这样的大型语言模型功能强大,但理解它们的内部工作机制可能很复杂,尤其是当理论脱离实际应用时。在这次深入探讨中,我们将采取一种独特的方法,从反向角度探索模型。通过逆向追溯工作流程,我们将揭示驱动Llama 3.1的复杂过程,提供对这个模型如何运作的深入、实际的理解。

一、模型架构

让我们加载llama3.1模型并仔细查看它。为了减少内存使用,我们对所有线性变换使用了4位量化(Linear4bit)。量化不会影响我们对模型工作原理的理解。

4位量化(4-bit quantization)是一种模型压缩技术,它将模型中的权重和激活值从传统的32位或16位精度降低到4位。这种技术可以显著减少模型在内存中的占用空间,降低计算成本,同时尽可能保持模型的性能。

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
# 定义基础模型的名称
base_model = "meta-llama/Meta-Llama-3.1-8B-Instruct"
# 加载与基础模型相对应的分词器
tokenizer = AutoTokenizer.from_pretrained(base_model)
# 创建量化配置对象
bnb_config = BitsAndBytesConfig(
 load_in_4bit=True, # 模型将被加载为4位量化版本
 bnb_4bit_quant_type="nf4", # 指定4位量化的类型为"nf4",基于分位数的量化方法
 bnb_4bit_compute_dtype=torch.bfloat16 # 设置计算时使用的精度类型为bfloat16
)
# 加载并量化模型
base_model_bnb_4b = AutoModelForCausalLM.from_pretrained(
 base_model, # 基础模型名称
 quantization_config=bnb_config, # 传入量化配置
 device_map='auto' # 设备映射设置为'auto',自动决定在哪个设备上运行模型
)
# 变量base_model_bnb_4b表示加载并量化后的模型

打印 base_model_bnb_4b 将使用模型结构。

LlamaForCausalLM(
 
 (model): LlamaModel( # Llama模型
 
 # 1.1词嵌入层,输入词汇量为128256,嵌入维度为4096 
 (embed_tokens): Embedding(128256, 4096) 
 
 # 多层解码器层 
 (layers): ModuleList( 
 (0-31): 32 x LlamaDecoderLayer( # 包含32层Llama解码器层 
 (self_attn): LlamaSdpaAttention( # 自注意力机制
 (q_proj): Linear4bit(in_features=4096, out_features=4096, bias=False) # 3.1查询投影,4位量化线性层
 (k_proj): Linear4bit(in_features=4096, out_features=1024, bias=False) # 3.