快速入门Safetensors

快速入门Safetensors

    • 什么是Safetensors
    • 架构
    • 常用操作
    • 速度对比
    • 彩蛋

Safetensors官方网址

什么是Safetensors

Safetensors是一种新的简单格式,用于安全存储张量(与pickle相反),而且速度仍然很快(零拷贝)。

架构

在这里插入图片描述

常用操作

# pip install safetensors# Load
from safetensors import safe_opentensors = {}
with safe_open("model.safetensors", framework="pt", device=0) as f:for k in f.keys():tensors[k] = f.get_tensor(k)# Loading only part of the tensors (interesting when running on multiple GPU)
from safetensors import safe_opentensors = {}
with safe_open("model.safetensors", framework="pt", device=0) as f:tensor_slice = f.get_slice("embedding")vocab_size, hidden_dim = tensor_slice.get_shape()tensor = tensor_slice[:, :hidden_dim]# save
import torch
from safetensors.torch import save_filetensors = {"embedding": torch.zeros((2, 2)),"attention": torch.zeros((2, 3))
}
save_file(tensors, "model.safetensors")

速度对比

  • cpu

Loaded safetensors 0:00:00.004015
Loaded pytorch 0:00:00.307460
on CPU, safetensors is faster than pytorch by: 76.6 X

  • gpu

Loaded safetensors 0:00:00.165206
Loaded pytorch 0:00:00.353889
on GPU, safetensors is faster than pytorch by: 2.1 X

彩蛋

Lora的Safetensors格式存储有训练时的元数据信息

代码来自sd-web-ui项目源码

def read_metadata_from_safetensors(filename):import jsonwith open(filename, mode="rb") as file:metadata_len = file.read(8)metadata_len = int.from_bytes(metadata_len, "little")json_start = file.read(2)assert metadata_len > 2 and json_start in (b'{"', b"{'"), f"{filename} is not a safetensors file"json_data = json_start + file.read(metadata_len-2)json_obj = json.loads(json_data)res = {}for k, v in json_obj.get("__metadata__", {}).items():res[k] = vif isinstance(v, str) and v[0:1] == '{':try:res[k] = json.loads(v)except Exception:passreturn res
import sys
print(read_metadata_from_safetensors(sys.argv[1]))
{"ss_sd_model_name": "dream-shaper-5.ckpt","ss_resolution": "(512, 512)","ss_clip_skip": "2","ss_num_train_images": "5000","ss_tag_frequency": {"100_coloredic0n": {"coloredic0n icon a white ambulance with red stripe on it": 1,"coloredic0n icon a brown backpack": 1,"coloredic0n icon a banana peel": 1,"coloredic0n icon a battery with a lightning on it": 1,"coloredic0n icon a bed with a pillow on it": 1,"coloredic0n icon a red book with the words on it": 1,"coloredic0n icon a cabbage with green leaves": 1,"coloredic0n icon a cactus plant in a pot": 1,"coloredic0n icon a cassette tape": 1,"coloredic0n icon a  champagne bottle": 1,"coloredic0n icon a piece of cheese": 1,"coloredic0n icon a squirrel sitting with a nut in its hands": 1,"coloredic0n icon a cookie with a chocolate chip on top": 1,"coloredic0n icon a red price percent symbol on it": 1,"coloredic0n icon a fence": 1,"coloredic0n icon a red fire hydrant": 1,"coloredic0n icon a woman with long hair smiling and wearing a pink shirt": 1,"coloredic0n icon a pair of glasses": 1,"coloredic0n icon a pink jellyfish floating in the air": 1,"coloredic0n icon a ladybug with a black and red pattern on it": 1,"coloredic0n icon a green lawnmower": 1,"coloredic0n icon a carton of milk with a cap on top": 1,"coloredic0n icon a bowl of noodles with peas and tomatoes": 1,"coloredic0n icon a notebook with a pen on top of it": 1,"coloredic0n icon a onion": 1,"coloredic0n icon a padlock": 1,"coloredic0n icon a panda face": 1,"coloredic0n icon a blue pen": 1,"coloredic0n icon a pencil": 1,"coloredic0n icon a black power plug": 1,"coloredic0n icon a rat with a long tail": 1,"coloredic0n icon a raven": 1,"coloredic0n icon a rifle with a bullets": 1,"coloredic0n icon a red and white rocket ship": 1,"coloredic0n icon a red rose with green leaves": 1,"coloredic0n icon a yellow rubber duck": 1,"coloredic0n icon a sneaker with a red and white sole": 1,"coloredic0n icon a green snail with a yellow shell": 1,"coloredic0n icon a pair of socks with a red and white design": 1,"coloredic0n icon a brown couch with pillows and a pillow on it": 1,"coloredic0n icon a grey sofa with pillows and a pillow on it": 1,"coloredic0n icon a sunflower": 1,"coloredic0n icon a yellow ticket with a star on it": 1,"coloredic0n icon a toilet seat with a lid up": 1,"coloredic0n icon a wood log": 1,"coloredic0n icon a red and white target with an arrow in the center": 1,"coloredic0n icon a bucket filled with water": 1,"coloredic0n icon a calendar": 1,"coloredic0n icon a red pencil sharper with a metal blade": 1,"coloredic0n icon a red and white and red megaphone": 1}},"ss_batch_size_per_device": "2","ss_bucket_info": "null","ss_bucket_no_upscale": "False","ss_cache_latents": "True","ss_caption_dropout_every_n_epochs": "0","ss_caption_dropout_rate": "0.0","ss_caption_tag_dropout_rate": "0.0","ss_color_aug": "False","ss_dataset_dirs": {"100_coloredic0n": {"n_repeats": 100,"img_count": 50}},"ss_enable_bucket": "False","ss_epoch": "1","ss_face_crop_aug_range": "None","ss_flip_aug": "False","ss_full_fp16": "False","ss_gradient_accumulation_steps": "1","ss_gradient_checkpointing": "False","ss_keep_tokens": "0","ss_learning_rate": "0.0001","ss_lowram": "False","ss_lr_scheduler": "constant","ss_lr_warmup_steps": "0","ss_max_bucket_reso": "None","ss_max_grad_norm": "1.0","ss_max_token_length": "None","ss_max_train_steps": "2500","ss_min_bucket_reso": "None","ss_min_snr_gamma": "None","ss_mixed_precision": "bf16","ss_network_alpha": "Dynamic","ss_network_dim": "Dynamic","ss_network_module": "networks.lora","ss_new_sd_model_hash": "ffad8f3da766de2a56343e388df43941ee27143a03c596e0b8f06976d4fa52e9","ss_noise_offset": "None","ss_num_batches_per_epoch": "2500","ss_num_epochs": "1","ss_num_reg_images": "0","ss_optimizer": "bitsandbytes.optim.adamw.AdamW8bit","ss_output_name": "Colored_Icons","ss_prior_loss_weight": "1.0","ss_random_crop": "False","ss_reg_dataset_dirs": {},"ss_sd_model_hash": "02a6900f","ss_sd_scripts_commit_hash": "9533285e998c74b0e18d114aea71f7143c8f3fa9","ss_seed": "1234","ss_session_id": "2548637574","ss_shuffle_caption": "False","ss_text_encoder_lr": "5e-05","ss_total_batch_size": "2","ss_training_comment": "Dynamic resize with sv_fro: 0.9 from 128; None","ss_training_finished_at": "1683314416.566944","ss_training_started_at": "1683312438.3090656","ss_unet_lr": "0.0001","ss_v2": "False","sshs_legacy_hash": "a45a7daa","sshs_model_hash": "6a455e4a89e4c0cbb5985bf8ebb96397e61bb4b8431b121281d6ec796daecae1"}

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

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

AI嵌入式K210项目(26)-二维码识别

文章目录 前言一、什么是二维码?二、实验准备三、实验过程四、API接口总结 前言 本章介绍基于机器视觉实现二维码识别,主要包含两个过程,首先检测图像中是否有二维码,如果有则框出并打印二维码信息; 一、什么是二维码…

揭开Markdown的秘籍:标题|文字样式|列表

🌈个人主页:聆风吟 🔥系列专栏:Markdown指南、网络奇遇记 🔖少年有梦不应止于心动,更要付诸行动。 文章目录 📋前言一. ⛳️Markdown 标题二. ⛳️Markdown 文字样式2.1 🔔斜体2.2 &…

MacOS 查AirPods 电量技巧:可实现低电量提醒、自动弹窗

要怎么透过macOS 来查询AirPods 电量呢?当AirPods 和Mac 配对后,有的朋友想通过Mac来查询AirPods有多少电量,这个里有几个技巧,下面我们来介绍一下。 透过Mac 查AirPods 电量技巧 技巧1. 利用状态列上音量功能查询 如要使用此功能…

Spring Boot + 七牛OSS: 简化云存储集成

引言 Spring Boot 是一个非常流行的、快速搭建应用的框架,它无需大量的配置即可运行起来,而七牛云OSS提供了稳定高效的云端对象存储服务。利用两者的优势,可以为应用提供强大的文件存储功能。 为什么选择七牛云OSS? 七牛云OSS提供了高速的…

《Git 简易速速上手小册》第6章:Git 在持续集成/持续部署(CI/CD)中的应用(2024 最新版)

文章目录 6.1 CI/CD基础6.1.1 基础知识讲解6.1.2 重点案例:为 Python Web 应用实现 CI/CD6.1.3 拓展案例 1:自动化部署到云平台6.1.4 拓展案例 2:使用 Docker 容器化部署 6.2 Git 与自动化测试6.2.1 基础知识讲解6.2.2 重点案例:为…

【数据结构】数据结构

本文是基于中国MOOC平台上,华中科技大学的《数据结构》课程和浙江大学的《数据结构》课程所作的一篇课程笔记,便于后期讲行系统性查阅和复习。 从个人感受而言,华中科技大学的课程讲解更适合初学者(缺点在于,从概念到…

2024-01-06-AI 大模型全栈工程师 - 机器学习基础

摘要 2024-01-06 阴 杭州 晴 本节简介: a. 数学模型&算法名词相关概念; b. 学会数学建模相关知识; c. 学会自我思考,提升认知,不要只会模仿; 课程内容 1. Fine-Tuning 有什么作用? a. 什么是模型训练&#xff…

redis的主从配置模拟(一主双从)

目录 先来给大家扩展机道面试官经常会问到关于redis的题 一、redis有哪些好处 二、redis相比memcached有哪些优势 三、redis常见性能问题和解决方案 四、redis集群的工作原理 五、redis主从的原理 redis的主从配置模拟(一主双从) 一、准备环境 …

TCP 传输控制协议——详细

目录 1 TCP 1.1 TCP 最主要的特点 1.2 TCP 的连接 TCP 连接,IP 地址,套接字 1.3 可靠传输的工作原理 1.3.1 停止等待协议 (1)无差错情况 (2)出现差错 (3)确认丢失和确认迟到…

JetpackCompose之状态管理

JetPack Compose系列(13)—状态管理 State 即,状态。官方的解释是: State in an application is any value that can change over time. And ****event can notify a part of a program that something has happened. 可以这样…

113.路径总和 II

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。 叶子节点 是指没有子节点的节点。 示例 1: 输入:root [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum 22 输出&a…

cleanmymacX和腾讯柠檬哪个好用

很多小伙伴在使用Mac时,会遇到硬盘空间不足的情况。遇到这种情况,我们能做的就是清理掉一些不需要的软件或者一些占用磁盘空间较大的文件来腾出空间。我们可以借助一些专门的清理工具,本文中我们来推荐几款好用的Mac知名的清理软件。并且将Cl…

【Git】Windows下通过Docker安装GitLab

私有仓库 前言基本思路拉取镜像创建挂载目录创建容器容器启动成功登录仓库设置中文更改密码人员审核配置邮箱 前言 由于某云存在人数限制,这个其实很好理解,毕竟使用的是云服务器,人家也是要交钱的。把代码完全放在别人的服务器上面&#xf…

百家cms代审

环境搭建 源码链接如下所示 https://gitee.com/openbaijia/baijiacms 安装至本地后 直接解压到phpstudy的www目录下即可 接下来去创建一个数据库用于存储CMS信息。(在Mysql命令行中执行) 接下来访问CMS,会默认跳转至安装界面 数据库名称和…

114.乐理基础-五线谱-快速识别五线谱的谱号

内容参考于:三分钟音乐社 上一个内容:113.乐理基础-五线谱-五线谱的调号(二)-CSDN博客 15个调号,如下图,该怎样才能随便拿出一个来就能快速的知道这是什么调号呢? 一共分为三个要点&#xff1…

单片机学习笔记---DS1302时钟

上一节我们讲了DS1302的工作原理,这一节我们开始代码演示。 新创建一个工程写上框架 我们需要LCD1602进行显示,所以我们要将LCD1602调试工具那一节的LCD1602的模块化代码给添加进来 然后我们开始创建一个DS1302.c和DS1302.h 根据原理图,为了…

牛客网SQL进阶114:更新记录

官网链接: 更新记录(二)_牛客题霸_牛客网现有一张试卷作答记录表exam_record,其中包含多年来的用户作答试卷记录,结构如下表。题目来自【牛客题霸】https://www.nowcoder.com/practice/0c2e81c6b62e4a0f848fa7693291d…

肯尼斯·里科《C和指针》第13章 高级指针话题(2)函数指针

我们不会每天都使用函数指针。但是,它们的确有用武之地,最常见的两个用途是转换表(jump table)和作为参数传递给另一个函数。本节将探索这两方面的一些技巧。但是,首先容我指出一个常见的错误,这是非常重要的。 简单声明一个函数指…

【MATLAB源码-第138期】基于matlab的D2D蜂窝通信仿真,对比启发式算法,最优化算法和随机算法的性能。

操作环境: MATLAB 2022a 1、算法描述 D2D蜂窝通信介绍 D2D蜂窝通信允许在同一蜂窝网络覆盖区域内的终端设备直接相互通信,而无需数据经过基站或网络核心部分转发。这种通信模式具有几个显著优点:首先,它可以显著降低通信延迟&…

铱塔 (iita) 开源 IoT 物联网开发平台,基于 SpringBoot + TDEngine +Vue3

01 铱塔 (iita) 物联网平台 铱塔智联 (open-iita) 基于Java语言的开源物联网基础开发平台,提供了物联网及相关业务开发的常见基础功能, 能帮助你快速搭建自己的物联网相关业务平台。 铱塔智联平台包含了品类、物模型、消息转换、通讯组件(mqtt/EMQX通讯组…