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作为一个整体,目前没办法拆开来看其内部的中间值。

相关推荐
码云之上8 小时前
项目团队从 5 人扩到 15 人,我写了个 CLI 让 IDE 共享 AI 规则
前端·人工智能·后端
2601_956865778 小时前
# 2026年AI API中转平台选型指南:高并发能力、协议兼容与白盒计费体系深度解析
人工智能·api
格子软件8 小时前
GEO系统深度实战:多引擎自适应算法与去中心化流控
人工智能·算法·去中心化·区块链
触底反弹8 小时前
面试被问 RAG 只能说出六个字?这篇用 100 行 Node.js 代码帮你彻底搞懂
javascript·人工智能·面试
小白跃升坊8 小时前
1Panel企业版+AI门户|从零构建企业专属AI门户
人工智能·ai·1panel·skills·ai运维·ai门户
可以飞的话8 小时前
五、数据处理1
python
鱼毓屿御8 小时前
Python 装饰器与函数调用机制(复习笔记 · 2026-07-07)
开发语言·python
写代码像蔡徐抻8 小时前
三年了,为什么 AI 应用还没爆发?
人工智能
宝贝儿好8 小时前
【LLM】第三章:BERT讲解+情感分析案例
人工智能·深度学习·神经网络·算法·自然语言处理·bert
-cywen-8 小时前
BLIP:Bootstrapping Language-Image Pre-training
人工智能