webassembly003 MINISIT mnist/convert-h5-to-ggml.py

数据结构

# Convert MNIS h5 transformer model to ggml format
#
# Load the (state_dict) saved model using PyTorch
# Iterate over all variables and write them to a binary file.
#
# For each variable, write the following:
#   - Number of dimensions (int)
#   - Name length (int)
#   - Dimensions (int[n_dims])
#   - Name (char[name_length])
#   - Data (float[n_dims])
#
# At the start of the ggml file we write the model parameters
  • 这个简单的版本没有Name的部分,导出的数据最终如下
ggml-model-f32.bin注释
0x67676d6cmagic
2len(fc1.weight.shape)
784fc1.weight.shape = (500, 784)
500fc1.weight.shape = (500, 784)
datafc1.weight
1len(fc1.bias.shape)
500fc1.bias.shape = (500, )
datafc1.bias
2len(fc2.weight.shape)
500fc1.weight.shape = (10, 500)
10fc1.weight.shape =(10, 500)
datafc2.weight
1len(fc2.bias.shape)
10fc2.bias.shape =(10,)
datafc1.bias

代码注释

import sys
import struct
import json
import numpy as np
import reimport torch
import torch.nn as nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
from torch.autograd import Variable# 检查是否提供了正确数量的命令行参数
if len(sys.argv) != 2:print("Usage: convert-h5-to-ggml.py model\n")sys.exit(1)# 获取输入h5模型和输出ggml模型的文件路径
state_dict_file = sys.argv[1]
fname_out = "models/mnist/ggml-model-f32.bin"# 加载PyTorch保存的state_dict模型
state_dict = torch.load(state_dict_file, map_location=torch.device('cpu'))# 以写入模式打开输出二进制文件
fout = open(fname_out, "wb")# 在文件中写入魔术数字'ggml',以十六进制格式作为文件标识符
# 使用 Python 的 struct 模块将整数 0x67676d6c 打包为二进制数据的操作。在这里,"i" 表示使用整数格式进行打包。
fout.write(struct.pack("i", 0x67676d6c))  # magic: ggml in hex # 迭代state_dict中的所有变量
for name in state_dict.keys():# 从变量中提取数据并将其转换为NumPy数组data = state_dict[name].squeeze().numpy()print("Processing variable: " + name + " with shape: ", data.shape) n_dims = len(data.shape);# 将变量的维度数量写入二进制文件fout.write(struct.pack("i", n_dims))# 将数据转换为float32并将维度写入二进制文件data = data.astype(np.float32)for i in range(n_dims):fout.write(struct.pack("i", data.shape[n_dims - 1 - i]))# 将数据写入二进制文件data.tofile(fout)# 关闭二进制文件
fout.close()print("Done. Output file: " + fname_out)
print("")

tofile()

  • NumPy提供的存数组内容的文件操作函数。读取使用fromfile。

struct.pack

  • 将字节解释为打包的二进制数据。

输出

$:~/ggml/ggml/examples/mnist$ python3 ./convert-h5-to-ggml.py 
./models/mnist/mnist_model.state_dictOrderedDict([('fc1.weight', tensor([[ 0.0130,  0.0034, -0.0287,  ..., -0.0268, -0.0352, -0.0056],[-0.0134,  0.0077, -0.0028,  ...,  0.0356,  0.0143, -0.0107],[-0.0329,  0.0154, -0.0167,  ...,  0.0155,  0.0127, -0.0309],...,[-0.0216, -0.0302,  0.0085,  ...,  0.0301,  0.0073,  0.0153],[ 0.0289,  0.0181,  0.0326,  ...,  0.0107, -0.0314, -0.0349],[ 0.0273,  0.0127,  0.0105,  ...,  0.0090, -0.0007,  0.0190]])), ('fc1.bias', tensor([ 1.9317e-01, -7.4255e-02,  8.3417e-02,  1.1681e-01,  7.5499e-03,8.7627e-02, -7.9260e-03,  6.8504e-02,  2.2217e-02,  9.7918e-02,1.5195e-01,  8.3765e-02,  1.4237e-02,  1.0847e-02,  9.6959e-02,-1.2500e-01,  4.2406e-02, -2.4611e-02,  5.9198e-03,  8.9767e-02,..., 1.3460e-03,  2.9106e-02, -4.0620e-02,  9.7568e-02,  8.5670e-02])), ('fc2.weight', tensor([[-0.0197, -0.0814, -0.3992,  ...,  0.2697,  0.0386, -0.5380],[-0.4174,  0.0572, -0.1331,  ..., -0.2564, -0.3926, -0.0514],...,[-0.2988, -0.1119,  0.0517,  ...,  0.3296,  0.0800,  0.0651]])), ('fc2.bias', tensor([-0.1008, -0.1179, -0.0558, -0.0626,  0.0385, -0.0222,  0.0188, -0.1296,0.1507,  0.0033]))])
Processing variable: fc1.weight with shape:  (500, 784)
Processing variable: fc1.bias with shape:  (500,)
Processing variable: fc2.weight with shape:  (10, 500)
Processing variable: fc2.bias with shape:  (10,)
Done. Output file: models/mnist/ggml-model-f32.bin
————————————————                        
// 原文链接:https://blog.csdn.net/ResumeProject/article/details/131571641

权重读取

// load the model's weights from a file
bool mnist_model_load(const std::string & fname, mnist_model & model) {printf("%s: loading model from '%s'\n", __func__, fname.c_str());auto fin = std::ifstream(fname, std::ios::binary);// std::ifstream用于读文件操作if (!fin) {fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname.c_str());return false;}// verify magic{uint32_t magic;// 32位的无符号整型数 uint32_t i = 0x67676d6c;fin.read((char *) &magic, sizeof(magic));if (magic != GGML_FILE_MAGIC) {fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname.c_str());return false;}}auto & ctx = model.ctx;size_t ctx_size = 0;// compute ctx_size use mnist_hparams{const auto & hparams = model.hparams;const int n_input   = hparams.n_input;const int n_hidden  = hparams.n_hidden;const int n_classes = hparams.n_classes;ctx_size += n_input * n_hidden * ggml_type_sizef(GGML_TYPE_F32); // fc1 weightctx_size +=           n_hidden * ggml_type_sizef(GGML_TYPE_F32); // fc1 biasctx_size += n_hidden * n_classes * ggml_type_sizef(GGML_TYPE_F32); // fc2 weightctx_size +=            n_classes * ggml_type_sizef(GGML_TYPE_F32); // fc2 biasprintf("%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size/(1024.0*1024.0));}// create the ggml context{struct ggml_init_params params = {/*.mem_size   =*/ ctx_size + 1024*1024,/*.mem_buffer =*/ NULL,/*.no_alloc   =*/ false,};model.ctx = ggml_init(params);if (!model.ctx) {fprintf(stderr, "%s: ggml_init() failed\n", __func__);return false;}}// Read FC1 layer 1{// Read dimensions and keep in a signed int// 读取sizeof(n_dims)个字节的数据,并将其存储到n_dims指向的内存空间中。`reinterpret_cast<char *>` 是一个类型转换操作符,它将 `&n_dims` 的地址强制转换为 `char *` 类型的指针,这样可以将 `int32_t` 类型的数据按字节读取。int32_t n_dims; fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));{int32_t ne_weight[2] = { 1, 1 };for (int i = 0; i < n_dims; ++i) {fin.read(reinterpret_cast<char *>(&ne_weight[i]), sizeof(ne_weight[i]));}// FC1 dimensions taken from file, eg. 768x500model.hparams.n_input  = ne_weight[0];model.hparams.n_hidden = ne_weight[1];model.fc1_weight = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, model.hparams.n_input, model.hparams.n_hidden);fin.read(reinterpret_cast<char *>(model.fc1_weight->data), ggml_nbytes(model.fc1_weight));ggml_set_name(model.fc1_weight, "fc1_weight");}{int32_t ne_bias[2] = { 1, 1 };for (int i = 0; i < n_dims; ++i) {fin.read(reinterpret_cast<char *>(&ne_bias[i]), sizeof(ne_bias[i]));}model.fc1_bias = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_hidden);fin.read(reinterpret_cast<char *>(model.fc1_bias->data), ggml_nbytes(model.fc1_bias));ggml_set_name(model.fc1_bias, "fc1_bias");// just for testing purposes, set some parameters to non-zeromodel.fc1_bias->op_params[0] = 0xdeadbeef;}}// Read FC2 layer 2{// Read dimensionsint32_t n_dims;fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));{int32_t ne_weight[2] = { 1, 1 };for (int i = 0; i < n_dims; ++i) {fin.read(reinterpret_cast<char *>(&ne_weight[i]), sizeof(ne_weight[i]));}// FC1 dimensions taken from file, eg. 10x500model.hparams.n_classes = ne_weight[1];model.fc2_weight = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, model.hparams.n_hidden, model.hparams.n_classes);fin.read(reinterpret_cast<char *>(model.fc2_weight->data), ggml_nbytes(model.fc2_weight));ggml_set_name(model.fc2_weight, "fc2_weight");}{int32_t ne_bias[2] = { 1, 1 };for (int i = 0; i < n_dims; ++i) {fin.read(reinterpret_cast<char *>(&ne_bias[i]), sizeof(ne_bias[i]));}model.fc2_bias = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_classes);fin.read(reinterpret_cast<char *>(model.fc2_bias->data), ggml_nbytes(model.fc2_bias));ggml_set_name(model.fc2_bias, "fc2_bias");}}fin.close();return true;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/660011.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

张维迎《博弈与社会》多重均衡与制度和文化(1)多重均衡问题

什么是多重均衡 我曾经在课堂上做过这样一个实验&#xff1a;随机选择男女两位同学参加一个选数字的游戏。游戏的基本规则为&#xff1a;每一个同学随机地从1到10十个数字中任意选择5个。如果两人选择的数字没有任何重复的话&#xff0c;则每人可以得到50元&#xff1b;如果两人…

npm install 安装依赖,为什么有时候会修改项目 package-lock.json,怎么解决?

前端开发时经常会接手一个别人创建的项目已经上线了&#xff0c;后期让我来修复缺陷&#xff0c;或者子新增功能。 上来就使用npm install 安装项目依赖&#xff0c;一看package-lock.json文件被自动修改了&#xff0c;可是我也没有修改package.json文件内容啊&#xff0c;不管…

深入了解协议栈内核源码

三次握手内核源码 深入理解 Linux 的 TCP 三次握手_tcp_v4_conn_request-CSDN博客 socket.c 内核态函数入口 三次状态变化 创建socket入口 ping Breakpoint 7, SyS_socket (family2, type3, protocol1) at net/socket.c:1325 1325 SYSCALL_DEFINE3(socket, int, famil…

Google Gemini Pro 国内版

Google Gemini Pro 国内版&#xff1a;【直达链接】 Google Gemini Pro 国内版 能力分类基准测试描述更高分数更好Gemini UltraGPT-4通用MMLU57个主题&#xff08;包括STEM、人文等&#xff09;的问题表示是90.0%86.4%&#xff08;5-shot, 报告&#xff09;推理Big-Bench Hard…

微信小程序(二十九)交互提示-界面加载框和提示框

注释很详细&#xff0c;直接上代码 上一篇 新增内容&#xff1a; 1.showLoading加载框示范 2.showToast提示框示范 源码&#xff1a; index.wxml <!-- 列表渲染基础写法&#xff0c;不明白的看上一篇 --> <view class"students"><view class"it…

音视频数字化(音乐CD)

上篇文章【音视频数字化(音频数字化)】我们聊了音频数字化原理,其中谈到了音乐CD,结尾也提到了一个小问题:“CD音质是最高吗?为什么?”不知道大家是怎么理解的。 其实CD质量只是“无损”存储,但是数字化标准只是“44.1kHz,16bit”,因此相对于现在,音质不能说最高。 …

故障诊断 | 一文解决,BP神经网络的故障诊断(Matlab)

文章目录 效果一览文章概述专栏介绍模型描述源码设计参考资料效果一览 文章概述 故障诊断 | 一文解决,BP神经网络的故障诊断(Matlab) 专栏介绍 订阅【故障诊断】专栏,不定期更新机器学习和深度学习在故障诊断中的应用;订阅

策略模式+SpringBoot接口,一个接口实现接收的数据自动分流处理

策略模式 定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。策略模式的精髓就在于将经常变化的一点提取出来,单独变成一类,并且各个类别可以相互替换和组合。 1、策略接口 CalculationStrategy //算数 public interface…

dubbo rpc序列化

序列化配置 provider <dubbo:service interface"com.example.DemoService" serialization"hessian2" ref"demoService"/>consumer <dubbo:reference id"demoService" interface"com.example.DemoService" seria…

PyTorch 最新安装教程

以下教程适用于 Windows、Linux 和 macOS 操作系统 1、确保您的计算机上已经安装了 Python。建议使用 Python 3.7 或更高版本。 2、打开终端&#xff08;对于 Windows 用户&#xff0c;请使用命令提示符&#xff09;。 3、在终端中运行以下命令&#xff0c;以安装 PyTorch 的…

解决:IDEA无法下载源码,Cannot download sources, sources not found for: xxxx

原因 Maven版本太高&#xff0c;遇到http协议的镜像网站会阻塞&#xff0c;要改为使用https协议的镜像网站 解决方案 1.打开设置 2. 拿到settings.xml路径 3. 将步骤2里箭头2的User settings file&#xff1a;settings.xml打开&#xff0c;作以下修改 保存即可。如果还不行…

15. 三数之和(力扣LeetCode)

文章目录 15. 三数之和题目描述双指针去重逻辑的思考a的去重b与c的去重 15. 三数之和 题目描述 给你一个整数数组 nums &#xff0c;判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i ! j、i ! k 且 j ! k &#xff0c;同时还满足 nums[i] nums[j] nums[k] 0 。请 …

全志H713红外IR遥控配置方法

篇头 全志H713 Soc是一颗 A53四核心&#xff0c;支持MAX 2GB DDR&#xff0c; 支持1920x1080P LVDS接口&#xff0c; 支持梯形校正功能的芯片&#xff0c;非常适合用于开发投影仪&#xff0c;尤其是低成本的LCD投影。本文详细介绍此平台&#xff0c;配置一个新的红外遥控器的方…

生信学习笔记1:学习如何用OPLS-DA分析代谢组数据(从入门到掌握)

偏最小二乘法(PLS)和正交偏最小二乘法(OPLS)是统计模型,用于寻找两组数据矩阵之间的关系。它们广泛应用于化学计量学、生物信息学、经济预测等领域。 偏最小二乘法(PLS) 偏最小二乘法是一种多变量分析方法,主要用于找到两组数据(通常是预测变量集和响应变量集)之间…

【无刷电机学习】电流采样电路硬件方案

【仅作自学记录&#xff0c;不出于任何商业目的】 目录 AD8210 INA282 INA240 INA199 AD8210 【AD8210数据手册】 在典型应用中&#xff0c;AD8210放大由负载电流通过分流电阻产生的小差分输入电压。AD8210抑制高共模电压(高达65V)&#xff0c;并提供接地参考缓冲输出&…

gtkmm xml ui 例子(from string)

文章目录 前言来看一个从字符串中生成UI的例子 前言 glade生成的xml格式不被gtkmm4支持, 需要作修改 来看一个从字符串中生成UI的例子 #include <gtkmm/application.h> #include <gtkmm.h> #include <iostream> using namespace std;class ExampleWindow :…

51单片机编程应用(C语言):独立按键

目录 1.独立按键介绍 2.独立按键控制LED亮灭 1.1按下时LED亮&#xff0c;松手LED灭&#xff08;按一次执行亮灭&#xff09; 1.2首先按下时无操作&#xff0c;松手时LED亮&#xff08;再按下无操作&#xff0c;所以LED亮&#xff09;&#xff0c;松手LED灭&#xff08;松手时…

高通GAIA V3命令参考手册的研读学习(13):GAIA通知、示例以及制造商命令扩展

如前文《高通GAIA V3命令参考手册的研读学习(四)》所述,PDU一共有四种,前面已经讲了命令、回应以及错误码,现在来看最后一种:通知。 4. QTIL GAIA通知 通知发送的方向,是由设备发送到移动应用。 这些通常是由设备发送到移动应用程序的状态变化。 表4-1列出的事件以…

音频几个相关概念及心理声学模型

系列文章目录 音频格式的介绍文章系列&#xff1a; 音频编解码格式介绍&#xff1a;音频几个相关概念及心理声学模型 https://blog.csdn.net/littlezls/article/details/135499627 音频编解码格式介绍&#xff1a;音频编码格式介绍 https://blog.csdn.net/littlezls/article/d…

RabbitMQ快速上手

首先他的需求实在什么地方。我美哟明显的感受到。 它给我的最大感受就是脱裤子放屁——多此一举&#xff0c;的感觉。 他将信息发送给服务端中间件。在由MQ服务器发送消息。 服务器会监听消息。 但是它不仅仅局限于削峰填谷和稳定发送信息的功能&#xff0c;它还有其他重要…