大语言模型---Llama不同系列的权重参数文件提取;Llama-7B权重文件提取;Llama-8B权重文件提取;主要代码功能解析

文章目录

  • [1. 概要](#1. 概要)
  • [2. Llama-7B权重文件提取](#2. Llama-7B权重文件提取)
  • [3. Llama-8B权重文件提取](#3. Llama-8B权重文件提取)
  • [4. 主要代码功能解析](#4. 主要代码功能解析)

1. 概要

Llama 系列模型(Meta 发布的大语言模型)在开源社区广受欢迎,不同版本(前文已经介绍过7B和8B的区别,详情请点击链接)在应用场景和硬件需求上各有不同,其权重文件的提取方式也略有差异。本文将通过代码讲解如何获取和提取 Llama 7B 和 8B 的权重参数文件。

2. Llama-7B权重文件提取

python 复制代码
from transformers import AutoTokenizer, AutoModelForCausalLM

def save_weight_int(int_weight: torch.Tensor, path):
    if path[-4:] != '.bin':
        raise ValueError('Path must end with .bin')
    int_weight.cpu().detach().numpy().astype(np.int32).tofile(path)

if __name__ == '__main__':

	tokenizer = AutoTokenizer.from_pretrained(model_card, local_files_only = True, cache_dir = "./model-storage")
    model = AutoModelForSequenceClassification.from_pretrained(model_card, local_files_only = True, cache_dir = "./model-storage")

	for (i, w) in model.model.layers[0].named_parameters():
	    if len(w.shape) == 2:
	        pp_size = w.shape[0]
	        pp_size <<= args.log_off_factor  # 位移操作
	    elif len(w.shape) == 1:
	        (pp_size,) = w.shape
	    else:
	        raise ValueError(f"Unexpected shape {w.shape} for parameter {i}")
        print(f"Layer {i}, Parameter {j}, Shape: {w_orig.shape}")
        save_weight_int(w_orig, f"./zkllm-workdir/Llama-2-{args.model_size}b/layer-{i}-{j}-int.bin")

3. Llama-8B权重文件提取

python 复制代码
from transformers import AutoTokenizer, AutoModelForCausalLM

def save_weight_int(int_weight: torch.Tensor, path):
    if path[-4:] != '.bin':
        raise ValueError('Path must end with .bin')
    int_weight.cpu().detach().numpy().astype(np.int32).tofile(path)

if __name__ == '__main__':
	for i, layer in enumerate(model.model.layers):
	    for j, w in layer.named_parameters():
	        # 中间层参数的处理
	        if len(w.shape) == 2:
	            w_orig = w.float().T
	        else:
	            w_orig = w.float()
	        print(f"Layer {i}, Parameter {j}, Shape: {w_orig.shape}")
	        save_weight_int(w_orig, f"./zkllm-workdir/Llama-2-{args.model_size}b/layer-{i}-{j}-int.bin")
	
	# 处理顶层参数(如输出层的 score.weight)
	for name, param in model.named_parameters():
	    if "score.weight" in name:  # 仅处理输出权重
	        if len(param.shape) == 2:
	            w_orig = param.float().T
	        else:
	            w_orig = param.float()
	        print(f"Processing Output Layer Parameter {name}, Shape: {w_orig.shape}")
	        save_weight_int(w_orig, f"./zkllm-workdir/Llama-2-{args.model_size}b/{name.replace('.', '-')}-int.bin")

4. 主要代码功能解析

  1. save_weight_int(int_weight: torch.Tensor, path) 函数

    作用:将权重量化为 int32 数据,并以 .bin 格式保存到指定路径。

  2. 遍历 model.model.layers 的所有参数

python 复制代码
for i, layer in enumerate(model.model.layers):
    for j, w in layer.named_parameters():
  • 遍历模型的每一层(model.model.layers),i是层索引,layer 是每一层的模块。
  • 使用 named_parameters() 遍历每层中的所有参数(权重和偏置)。
    • j 是参数名称(例如 self_attn.q_proj.weight)。
    • w 是参数张量
  1. 中间参数处理(可以去掉)
python 复制代码
if len(param.shape) == 2:
	w_orig = param.float().T
else:
	w_orig = param.float()
相关推荐
@心都2 分钟前
机器学习数学基础:42.AMOS 结构方程模型(SEM)分析的系统流程
人工智能·算法·机器学习
陆鳐LuLu38 分钟前
深度学习与数据挖掘题库:401-500题精讲
人工智能·深度学习·数据挖掘
子洋40 分钟前
AnythingLLM + SearXNG 实现私有搜索引擎代理
前端·人工智能·后端
紫雾凌寒1 小时前
深度学习|MAE技术全景图:自监督学习的“掩码魔法“如何重塑AI基础
人工智能·深度学习·计算机视觉·自监督学习·vit·视频理解·mae
钡铼技术物联网关1 小时前
Ubuntu工控卫士在制造企业中的应用案例
大数据·人工智能·物联网·边缘计算
数维学长9861 小时前
【Manus资料合集】激活码内测渠道+《Manus Al:Agent应用的ChatGPT时刻》(附资源)
人工智能·chatgpt
施天助1 小时前
开发ai模型最佳的系统是Ubuntu还是linux?
人工智能·ubuntu
邵奈一2 小时前
运行OpenManus项目(使用Conda)
人工智能·大模型·agent·agi
是理不是里_2 小时前
深度学习与普通神经网络有何区别?
人工智能·深度学习·神经网络
曲幽2 小时前
DeepSeek大语言模型下几个常用术语
人工智能·ai·语言模型·自然语言处理·ollama·deepseek