PyTorch神经网络打印存储所有权重+激活值(运行时中间值)

很多时候嵌入式或者新硬件需要纯净的权重模型和激活值(运行时中间值),本文提供一种最简洁的方法。

假设已经有模型model和pt文件了,在当前目录下新建weights文件夹,运行这段代码,就可以得到模型的权重(文本形式和二进制形式)

python 复制代码
model.load_state_dict(state_dict)

global_index = 0
for name, param in model.named_parameters():
    print(name, param.size())
    print(param.data.numpy(),file=open(f"weights/{global_index}-{name}.txt", "w"))
    param.data.numpy().tofile(f"weights/{global_index}-{name}.bin")
    global_index += 1

对于二进制形式的文件,可以通过od -t f4 <binary file name> 查看其对应的浮点数值。f4表示fp32.

打印forward的中间值:(这么复杂是必要的)

python3 复制代码
global_index = 0
def hook_fn(module, input, output):
    global global_index
    module_name = str(module)
    module_name=module_name.replace(" ", "")
    module_name=module_name.replace("\n", "")
    # print(name)
    intermediate_outputs = {}
    # input is a tuple, output is a tensor
    for i, inp in enumerate(input):
        intermediate_outputs[f"{global_index}-{module_name}-input-{i}"] = inp
    intermediate_outputs[f"{global_index}-{module_name}-output"] = output
    module_name = module_name[0:200]  # make sure full path <= 255
    print(intermediate_outputs)
    print(f"Size input:",end=" ")
    if(type(input) == tuple):
        for i, inp in enumerate(input):
            if type(inp) == torch.Tensor:
                print(f"{i}-th Size: {inp.size()}", end=", ")
                inp.numpy().tofile(f"activations/{global_index}-{module_name}-input-{i}.bin")
            else:
                print(f"{i}-th : {inp}", end=", ")
    elif type(input) == torch.Tensor:
        print(f"Size: {input.size()}")
        input.numpy().tofile(f"activations/{global_index}-{module_name}-input.bin")
    print(f"Size output: {output.size()}")
    global_index += 1
    output.numpy().tofile(f"activations/{global_index}-{module_name}-output.bin")

def register_hooks(model):
    for name, layer in model.named_children():
        # print(name, layer) # dump all layers, > layers.txt
        # Register the hook to the current layer
        layer.register_forward_hook(hook_fn)
        # Recursively apply the same to all submodules
        register_hooks(layer)

register_hooks(model)

其中regster_hooks和以下等价(不需要recursive了)

python3 复制代码
def register_hooks(model):
    for name, layer in model.named_modules():
        # print(name, layer) # dump all layers
        layer.register_forward_hook(hook_fn)

其中nn.sequential作为一个整体,目前没办法拆开来看其内部的中间值。

相关推荐
Yoshizawa-Violet20 小时前
模板方法模式实战:重构Agent工具审批,告别重复代码
python·agent·模板方法
weixin_4280053020 小时前
C#调用 AI学习从0开始-第1阶段(基础与工具)-第7天多轮对话记忆
人工智能·学习·c#·多轮对话·千问api调用
机器之心20 小时前
Speech LLM 的下一个突破口:你的语音大模型可以是个「带韵律的文本模型」
人工智能·openai
久菜盒子工作室20 小时前
艾华集团 经营分析
人工智能
HjhIron20 小时前
Python列表与LLM接口实战:从切片到DeepSeek调用
python
SLD_Allen20 小时前
企业级 AI Agent: MCP、CLI、Skills,如何定位、该怎么选、最佳实践。
大数据·人工智能·elasticsearch·企业级 ai agent
搬砖的小码农_Sky20 小时前
macOS Sequoia上如何安装Python开发环境?
开发语言·python·macos
跨境卫士-小汪20 小时前
经营变量持续增多之下跨境卖家如何建立更稳的单品测算框架
大数据·人工智能·产品运营·跨境电商·亚马逊
AI服务老曹20 小时前
深度解析:基于 Docker 部署与 GB28181/RTSP 统一接入的跨平台 AI 视频管理系统(附源码交付与边缘计算架构设计)
人工智能·docker·音视频
Rauser Mack20 小时前
编程纯小白,五分钟用AI做了个小游戏(附Prompt)
人工智能·python·html·prompt·ai编程