大语言模型---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()
相关推荐
ModelWhale1 小时前
喜报!和鲸科技获张江国家自主创新示范区专项发展资金支持
大数据·人工智能·科研
飞哥数智坊1 小时前
AI 编程时代,你得学会“狠心”删代码
人工智能·ai编程
stbomei1 小时前
静默期的跃迁:2025 年 AI 技术落地与产业重构路径
人工智能·重构
可触的未来,发芽的智生1 小时前
新奇特:神经网络烘焙坊(下),万能配方的甜蜜奥义
人工智能·python·神经网络·算法·架构
RoboWizard1 小时前
移动固态硬盘无法被电脑识别怎么办?
大数据·人工智能·缓存·电脑·金士顿
zero13_小葵司2 小时前
基于多Agent构建AI驱动的智能化软件开发协作平台
人工智能·aigc·软件工程·团队开发·ai编程
jllllyuz2 小时前
matlab裂纹检测与延展分析系统
人工智能·计算机视觉·matlab
伊织code2 小时前
Cybersecurity AI (CAI) - 轻量级网络安全AI框架
人工智能·安全·web安全·cybersecurity·cai
JiaWen技术圈2 小时前
关于机器人的物理结构(连杆、关节、执行器)的快速入门介绍
人工智能·单片机·嵌入式硬件·机器人·硬件架构
科技峰行者2 小时前
阿里云瓴羊发布企业级AI智能体服务平台AgentOne,成就AI时代的“超级公司”
人工智能·阿里云·ai·云计算·羚羊