当前位置: 首页 > news >正文

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;
}

CG

  • GGUF 文件格式规范

相关文章:

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) # …...

fetch和axios的区别

概念不同 Fetch是一种新的获取资源的接口方式&#xff0c;可以直接使用Axios是一个基于XMLHttpRequest封装的工具包&#xff0c;需要引入才可以使用 传递数据的方式不同 Fetch则是需要放在body属性中&#xff0c;以字符串的方式进行传递Axios是放到data属性里&#xff0c;以对象…...

【unity小技巧】FPS简单的射击换挡瞄准动画控制

文章目录 射击动画控制换弹动画瞄准动画完结 射击动画控制 换弹动画 调用 瞄准动画 问题&#xff1a;瞄准时&#xff0c;但是动画会卡住&#xff0c;不会播放瞄准的待机动画 修改 调用 动画如果太快可以去修改播放速度 播放速度变慢了&#xff0c;可能导致切换待机动画也…...

如何获取时间戳

在JavaScript中&#xff0c;你可以使用Date对象来获取时间戳。以下是一个例子&#xff1a; javascriptvar timestamp new Date().getTime(); console.log(timestamp); 在这个例子中&#xff0c;new Date()创建了一个新的日期对象&#xff0c;.getTime()方法则返回自1970年1月…...

VSCode 设置代理

Open Visual Studio Code, click the settings icon in the lower left corner, and click Settings....

保姆级教程: 零门槛制作AI微信红包封面之入门篇

写在前面 本文旨在低门槛制作微信红包教程&#xff0c;人人均可上手! 操作步骤 AI红包制作平台: https://cover.fdfs.site 第一步: 先登录 alt text 可以使用谷歌&#xff0c;github直接登录&#xff0c;也可以用自己的邮箱注册 第二步: 设置自己的apiKey API-Key可以从平台 ht…...

Redis核心技术与实战【学习笔记】 - 17.Redis 缓存异常:缓存雪崩、击穿、穿透

概述 Redis 的缓存异常问题&#xff0c;除了数据不一致问题外&#xff0c;还会面临其他三个问题&#xff0c;分别是缓存雪崩、缓存击穿、缓存穿透。这三个问题&#xff0c;一旦发生&#xff0c;会导致大量的请求积压到数据库。若并发量很大&#xff0c;就会导致数据库宕机或故…...

Leetcode—2670. 找出不同元素数目差数组【简单】

2024每日刷题&#xff08;一零七&#xff09; Leetcode—2670. 找出不同元素数目差数组 哈希表实现代码 class Solution { public:vector<int> distinctDifferenceArray(vector<int>& nums) {unordered_set<int> s;int n nums.size();vector<int&g…...

App ICP备案获取iOS和Android的公钥和证书指纹

依照《工业和信息化部关于开展移动互联网应用程序备案工作的通知》&#xff0c;向iOS和安卓平台提交App时需要先提交ICP备案信息。 iOS平台&#xff1a; 1、下载appuploader工具&#xff1a;Appuploader home -- A tool improve ios develop efficiency such as submit ipa to…...

猿创征文 | 项目整合KafkaStream实现文章热度实时计算

个人简介&#xff1a; > &#x1f4e6;个人主页&#xff1a;赵四司机 > &#x1f3c6;学习方向&#xff1a;JAVA后端开发 > ⏰往期文章&#xff1a;SpringBoot项目整合微信支付 > &#x1f514;博主推荐网站&#xff1a;牛客网 刷题|面试|找工作神器 > &#…...

状态压缩 笔记

棋盘式的f[i][j]中表示状态的j可以是状态本身也可以是在合法状态state中的下标 用状态本身比较方便&#xff0c;用下标比较省空间 用下标的话可以开id[M]数组记录一下 蒙德里安的梦想 求把 NM的棋盘分割成若干个 12的长方形&#xff0c;有多少种方案。 例如当 N2&#xff0…...

Java 数据结构篇-实现二叉搜索树的核心方法

&#x1f525;博客主页&#xff1a; 【小扳_-CSDN博客】 ❤感谢大家点赞&#x1f44d;收藏⭐评论✍ 文章目录 1.0 二叉搜索树的概述 2.0 二叉搜索树的成员变量及其构造方法 3.0 实现二叉树的核心接口 3.1 实现二叉搜索树 - 获取值 get(int key) 3.2 实现二叉搜索树 - 获取最小…...

go语言(二十一)---- channel的关闭

channel不像文件一样需要经常去关闭&#xff0c;只有当你确实没有任何发送数据了&#xff0c;或者你想显示的结束range循环之类的&#xff0c;才去关闭channel。关闭channel后&#xff0c;无法向channel再发送数据&#xff0c;&#xff08;引发pannic错误后&#xff0c;导致接收…...

【PyQt】01-PyQt下载

文章目录 前言静态库 一、PyQt是什么&#xff1f;二、安装1.Windows环境下安装安装PyQt5Designer 2.Liunx环境下安装 总结 前言 拜吾师 PyQt5 快速入门 静态库 补充一点知识&#xff1a; Windows&#xff1a; .lib Linux: .a .so(动态库) 简单描述PyQt就是python调用C的Qt文…...

不一样的味觉体验:精酿啤酒与烤肉的绝妙搭配

在繁华的都市生活中&#xff0c;人们总是在寻找那份与众不同的味觉享受。当夏日的微风轻轻拂过&#xff0c;你是否想过&#xff0c;与三五好友围坐在一起&#xff0c;拿着Fendi Club啤酒与烤肉的绝妙搭配&#xff0c;畅谈生活点滴&#xff0c;感受那份惬意与自在&#xff1f; F…...

linux系统ansible的jiaja2的语法和简单剧本编写

jianja2语法和简单剧本 jinja2语法Jinja default()设定if语句for语句 ansiblejiaja2的使用ansible目录结构&#xff1a;tasks目录下文件内容&#xff1a;nginx模板文件ansible变量文件ansible主playbook文件测试并执行&#xff1a;查看检测执行结果 剧本编写安装apache安装mysq…...

Three.js PBR 物理渲染

详解 Three.js PBR 物理渲染 Three.js 是一个流行的基于 WebGL 的 JavaScript 库&#xff0c;专门用于创建和运行三维动画和游戏。其中很关键的一部分是物理渲染&#xff08;PBR&#xff09;。本文将深入探讨 Three.js 的 PBR 渲染&#xff0c;并为初学者提供实用的指导。 什…...

POSIX(包含程序的可移植性) -- 详解

1. 什么是 POSIX 参考链接–知乎 POSIX 标准包含了进程管理、文件管理、网络通信、线程和同步、信号处理等方面的功能。 这些接口定义了函数、数据类型和常量等&#xff0c;为开发者提供了一个可移植的方法来与操作系统进行交互。 2. 谁遵守这个标准 遵守 POSIX 标准的主要是…...

Jmeter学习系列之五:基础线程组(Thread Group)

前言 线程组是一系列线程的集合,每一个线程代表着一个正在使用应用程序的用户。在 jmeter 中,每个线程意味着模拟一个真实用户向服务器发起请求。 在 jmeter 中,线程组组件运行用户设置线程数量、初始化方式等等配置。 例如,如果你设置线程数为 100,那么 jmeter 将创建…...

Android 双卡适配 subId 相关方法

业务场景 双卡设备进行网络等业务时&#xff0c;需要正确操作对应的卡。 执行卡业务和主要是使用subId和 PhoneId/SlotId进行区分隔离。 代码举例 初始化subId //初始化subId private int mSubId SubscriptionManager.INVALID_SUBSCRIPTION_ID;//1、通过intent传值&#x…...

vscode里如何用git

打开vs终端执行如下&#xff1a; 1 初始化 Git 仓库&#xff08;如果尚未初始化&#xff09; git init 2 添加文件到 Git 仓库 git add . 3 使用 git commit 命令来提交你的更改。确保在提交时加上一个有用的消息。 git commit -m "备注信息" 4 …...

【Python】 -- 趣味代码 - 小恐龙游戏

文章目录 文章目录 00 小恐龙游戏程序设计框架代码结构和功能游戏流程总结01 小恐龙游戏程序设计02 百度网盘地址00 小恐龙游戏程序设计框架 这段代码是一个基于 Pygame 的简易跑酷游戏的完整实现,玩家控制一个角色(龙)躲避障碍物(仙人掌和乌鸦)。以下是代码的详细介绍:…...

linux之kylin系统nginx的安装

一、nginx的作用 1.可做高性能的web服务器 直接处理静态资源&#xff08;HTML/CSS/图片等&#xff09;&#xff0c;响应速度远超传统服务器类似apache支持高并发连接 2.反向代理服务器 隐藏后端服务器IP地址&#xff0c;提高安全性 3.负载均衡服务器 支持多种策略分发流量…...

RocketMQ延迟消息机制

两种延迟消息 RocketMQ中提供了两种延迟消息机制 指定固定的延迟级别 通过在Message中设定一个MessageDelayLevel参数&#xff0c;对应18个预设的延迟级别指定时间点的延迟级别 通过在Message中设定一个DeliverTimeMS指定一个Long类型表示的具体时间点。到了时间点后&#xf…...

java_网络服务相关_gateway_nacos_feign区别联系

1. spring-cloud-starter-gateway 作用&#xff1a;作为微服务架构的网关&#xff0c;统一入口&#xff0c;处理所有外部请求。 核心能力&#xff1a; 路由转发&#xff08;基于路径、服务名等&#xff09;过滤器&#xff08;鉴权、限流、日志、Header 处理&#xff09;支持负…...

树莓派超全系列教程文档--(62)使用rpicam-app通过网络流式传输视频

使用rpicam-app通过网络流式传输视频 使用 rpicam-app 通过网络流式传输视频UDPTCPRTSPlibavGStreamerRTPlibcamerasrc GStreamer 元素 文章来源&#xff1a; http://raspberry.dns8844.cn/documentation 原文网址 使用 rpicam-app 通过网络流式传输视频 本节介绍来自 rpica…...

IGP(Interior Gateway Protocol,内部网关协议)

IGP&#xff08;Interior Gateway Protocol&#xff0c;内部网关协议&#xff09; 是一种用于在一个自治系统&#xff08;AS&#xff09;内部传递路由信息的路由协议&#xff0c;主要用于在一个组织或机构的内部网络中决定数据包的最佳路径。与用于自治系统之间通信的 EGP&…...

iPhone密码忘记了办?iPhoneUnlocker,iPhone解锁工具Aiseesoft iPhone Unlocker 高级注册版​分享

平时用 iPhone 的时候&#xff0c;难免会碰到解锁的麻烦事。比如密码忘了、人脸识别 / 指纹识别突然不灵&#xff0c;或者买了二手 iPhone 却被原来的 iCloud 账号锁住&#xff0c;这时候就需要靠谱的解锁工具来帮忙了。Aiseesoft iPhone Unlocker 就是专门解决这些问题的软件&…...

【ROS】Nav2源码之nav2_behavior_tree-行为树节点列表

1、行为树节点分类 在 Nav2(Navigation2)的行为树框架中,行为树节点插件按照功能分为 Action(动作节点)、Condition(条件节点)、Control(控制节点) 和 Decorator(装饰节点) 四类。 1.1 动作节点 Action 执行具体的机器人操作或任务,直接与硬件、传感器或外部系统…...

零基础设计模式——行为型模式 - 责任链模式

第四部分&#xff1a;行为型模式 - 责任链模式 (Chain of Responsibility Pattern) 欢迎来到行为型模式的学习&#xff01;行为型模式关注对象之间的职责分配、算法封装和对象间的交互。我们将学习的第一个行为型模式是责任链模式。 核心思想&#xff1a;使多个对象都有机会处…...