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

RUST笔记:candle使用基础

candle介绍

  • candle是huggingface开源的Rust的极简 ML 框架。

candle-矩阵乘法示例

cargo new myapp
cd myapp
cargo add --git https://github.com/huggingface/candle.git candle-core
cargo build # 测试,或执行 cargo ckeck
  • main.rs
use candle_core::{Device, Tensor};fn main() -> Result<(), Box<dyn std::error::Error>> {let device = Device::Cpu;let a = Tensor::randn(0f32, 1., (2, 3), &device)?;let b = Tensor::randn(0f32, 1., (3, 4), &device)?;let c = a.matmul(&b)?;println!("{c}");Ok(())
}
  • 项目输出
~/myrust$ cargo new myappCreated binary (application) `myapp` package
~/myrust$ cd myapp
~/myrust/myapp$ cargo add --git https://github.com/huggingface/candle.git candle-coreUpdating git repository `https://github.com/huggingface/candle.git`Updating git submodule `https://github.com/NVIDIA/cutlass.git`Adding candle-core (git) to dependencies.Features:- accelerate- cuda- cudarc- cudnn- metal- mklUpdating git repository `https://github.com/huggingface/candle.git`Updating crates.io index
~/myrust/myapp$ cargo buildDownloaded serde_derive v1.0.195Downloaded either v1.9.0Downloaded autocfg v1.1.0Downloaded zerofrom v0.1.3Downloaded zerofrom-derive v0.1.3Downloaded synstructure v0.13.0Downloaded crossbeam-deque v0.8.5Downloaded yoke-derive v0.7.3Downloaded half v2.3.1Downloaded bytemuck v1.14.1Downloaded rand_core v0.6.4Downloaded paste v1.0.14Downloaded proc-macro2 v1.0.78Downloaded itoa v1.0.10Downloaded memmap2 v0.9.4Downloaded syn v2.0.48Downloaded crossbeam-epoch v0.9.18Downloaded cfg-if v1.0.0Downloaded bitflags v1.3.2Downloaded num_cpus v1.16.0Downloaded gemm-f32 v0.17.0Downloaded reborrow v0.5.5Downloaded stable_deref_trait v1.2.0Downloaded rayon-core v1.12.1Downloaded seq-macro v0.3.5Downloaded thiserror-impl v1.0.56Downloaded dyn-stack v0.10.0Downloaded thiserror v1.0.56Downloaded unicode-xid v0.2.4Downloaded rand_chacha v0.3.1Downloaded ppv-lite86 v0.2.17Downloaded bytemuck_derive v1.5.0Downloaded getrandom v0.2.12Downloaded once_cell v1.19.0Downloaded unicode-ident v1.0.12Downloaded byteorder v1.5.0Downloaded crc32fast v1.3.2Downloaded num-complex v0.4.4Downloaded gemm-common v0.17.0Downloaded crossbeam-utils v0.8.19Downloaded quote v1.0.35Downloaded ryu v1.0.16Downloaded num-traits v0.2.17Downloaded zip v0.6.6Downloaded rand_distr v0.4.3Downloaded serde v1.0.195Downloaded rand v0.8.5Downloaded raw-cpuid v10.7.0Downloaded libm v0.2.8Downloaded serde_json v1.0.111Downloaded rayon v1.8.1Downloaded libc v0.2.152Downloaded gemm-c64 v0.17.0Downloaded gemm-c32 v0.17.0Downloaded safetensors v0.4.2Downloaded gemm-f64 v0.17.0Downloaded gemm v0.17.0Downloaded gemm-f16 v0.17.0Downloaded yoke v0.7.3Downloaded pulp v0.18.6Downloaded 60 crates (3.1 MB) in 14.91sCompiling proc-macro2 v1.0.78Compiling unicode-ident v1.0.12Compiling libc v0.2.152Compiling cfg-if v1.0.0Compiling libm v0.2.8Compiling autocfg v1.1.0Compiling crossbeam-utils v0.8.19Compiling ppv-lite86 v0.2.17Compiling rayon-core v1.12.1Compiling reborrow v0.5.5Compiling paste v1.0.14Compiling either v1.9.0Compiling bitflags v1.3.2Compiling seq-macro v0.3.5Compiling once_cell v1.19.0Compiling unicode-xid v0.2.4Compiling raw-cpuid v10.7.0Compiling serde v1.0.195Compiling crc32fast v1.3.2Compiling serde_json v1.0.111Compiling stable_deref_trait v1.2.0Compiling itoa v1.0.10Compiling ryu v1.0.16Compiling thiserror v1.0.56Compiling byteorder v1.5.0Compiling num-traits v0.2.17Compiling zip v0.6.6Compiling crossbeam-epoch v0.9.18Compiling quote v1.0.35Compiling syn v2.0.48Compiling crossbeam-deque v0.8.5Compiling getrandom v0.2.12Compiling memmap2 v0.9.4Compiling num_cpus v1.16.0Compiling rand_core v0.6.4Compiling rand_chacha v0.3.1Compiling rayon v1.8.1Compiling rand v0.8.5Compiling rand_distr v0.4.3Compiling synstructure v0.13.0Compiling bytemuck_derive v1.5.0Compiling serde_derive v1.0.195Compiling zerofrom-derive v0.1.3Compiling thiserror-impl v1.0.56Compiling yoke-derive v0.7.3Compiling bytemuck v1.14.1Compiling num-complex v0.4.4Compiling dyn-stack v0.10.0Compiling half v2.3.1Compiling zerofrom v0.1.3Compiling yoke v0.7.3Compiling pulp v0.18.6Compiling gemm-common v0.17.0Compiling gemm-f32 v0.17.0Compiling gemm-c64 v0.17.0Compiling gemm-f64 v0.17.0Compiling gemm-c32 v0.17.0Compiling gemm-f16 v0.17.0Compiling gemm v0.17.0Compiling safetensors v0.4.2Compiling candle-core v0.3.3 (https://github.com/huggingface/candle.git#fd7c8565)Compiling myapp v0.1.0 (/home/pdd/myrust/myapp)Finished dev [unoptimized + debuginfo] target(s) in 32.90s

candle_test的简单测试项目

  • https://github.com/RileySeaburg/candle_test

  • git clone https://github.com/RileySeaburg/candle_test.git

Cargo.toml 文件

[package]
name = "candle_test"
version = "0.1.0"
edition = "2021" #  Rust 版本# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html[dependencies]
candle-core = { git = "https://github.com/huggingface/candle.git", version = "0.2.1", features = ["cuda"] }
# `candle-core`:项目依赖的包的名称。`git` 字段指定了包的源代码仓库地址。`version` 字段指定了使用的包的版本。`features` 字段是一个数组,指定了启用的功能。在这里,启用了 "cuda" 功能。
# 可以通过以下命令添加,取消可注释掉"cuda",再cargo build
# cargo add --git https://github.com/huggingface/candle.git candle-core
# cargo add candle-core --features cuda

main.rs

use candle_core::{DType, Device, Result, Tensor};// 定义一个模型结构体
struct Model {first: Tensor,second: Tensor,
}impl Model {// 定义模型的前向传播方法fn forward(&self, image: &Tensor) -> Result<Tensor> {let x = image.matmul(&self.first)?; // 输入乘以第一层权重let x = x.relu()?; // 使用 ReLU 激活函数x.matmul(&self.second) // 结果乘以第二层权重}
}fn main() -> Result<()> {// 初始化设备,如果 GPU 可用则使用 GPU,否则使用 CPUlet device = match Device::new_cuda(0) {Ok(device) => device,Err(_) => Device::Cpu,};// 创建模型的第一层和第二层权重张量let first = Tensor::zeros((784, 100), DType::F32, &device).unwrap().contiguous()?;let second = Tensor::zeros((100, 10), DType::F32, &device).unwrap().contiguous()?;// 初始化模型let model = Model { first, second };// 创建一个用于测试的虚拟图像张量let dummy_image = Tensor::zeros((1, 784), DType::F32, &device).unwrap().contiguous()?;// 调用模型的前向传播方法获取预测结果let digit = model.forward(&dummy_image)?;// 打印预测结果println!("Digit {digit:?} digit");Ok(())
}

知识点总结

candle_core:: Result

在这里插入图片描述

// Result定义在/home/pdd/.cargo/git/checkouts/candle-0c2b4fa9e5801351/e8e3375/candle-core/src/error.rs
pub type Result<T> = std::result::Result<T, Error>; // 定义了一个 `Result` 类型,这是一个 `Result<T, Error>` 类型的别名。其中 `T` 是成功时的返回类型,而 `Error` 是失败时的错误类型。
// Ok(()) 定义在 /home/pdd/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/result.rs
// 这是 Rust 标准库中的 `Result` 公共的枚举类型,它有两个泛型参数 `T` 和 `E`。`T` 代表成功时返回的值的类型,`E` 代表错误时返回的错误类型。
// #[]是属性(attribute),提供额外信息
pub enum Result<T, E> {/// Contains the success value#[lang = "Ok"]#[stable(feature = "rust1", since = "1.0.0")]Ok(#[stable(feature = "rust1", since = "1.0.0")] T),// `Ok(T)`: 这是 `Result` 枚举的一个变体,用于表示成功的情况// (): 是 Rust 中的单元类型(unit type),类似于其他语言中的 void。/// Contains the error value#[lang = "Err"]#[stable(feature = "rust1", since = "1.0.0")]Err(#[stable(feature = "rust1", since = "1.0.0")] E),// `Err(E)`: 这是 `Result` 枚举的另一个变体,用于表示错误的情况。
}

?符号

  • 在 Rust 中,? 符号用于处理 ResultOption 类型的返回值。这个符号的作用是将可能的错误或 None 值快速传播到调用链的最上层,使得代码更加简洁和易读。
fn forward(&self, image: &Tensor) -> Result<Tensor> {let x = image.matmul(&self.first)?; // 如果matmul返回Err,则整个forward函数返回Errlet x = x.relu()?; // 如果relu返回Err,则整个forward函数返回Errx.matmul(&self.second) // 如果matmul返回Err,则整个forward函数返回Err;否则返回Ok(Tensor)
}

语句和表达式:语句以分号结尾,而表达式通常不需要分号。

  • 函数体:函数体是一个块表达式,其值是最后一个表达式的值。

    fn add(x: i32, y: i32) -> i32 {x + y // 表达式
    }
    

CG

  • Burn is a new comprehensive dynamic Deep Learning Framework built using Rust with extreme flexibility, compute efficiency and portability as its primary goals.
  • resnet for caddle: https://github.com/iFREEGROUP/candle-models
  • Using candle to build a transformers for Rust.
  • https://github.com/joker3212/candle-clip
  • https://github.com/jonysugianto/candle_fastformer
  • Candle Silu inplace
  • https://github.com/ansleliu/PortableTelemedicineMonitoringSystem
  • https://mobile-aloha.github.io/
  • Learning Fine-Grained Bimanual Manipulation with Low-Cost Hardwarehttps://arxiv.org/pdf/2304.13705.pdf
  • A flexible, high-performance 3D simulator for Embodied AI research.
  • https://github.com/huggingface/huggingface.js
  • https://www.zhihu.com/people/wasmedge
  • https://wasmedge.org/docs/start/install/

相关文章:

RUST笔记:candle使用基础

candle介绍 candle是huggingface开源的Rust的极简 ML 框架。 candle-矩阵乘法示例 cargo new myapp cd myapp cargo add --git https://github.com/huggingface/candle.git candle-core cargo build # 测试&#xff0c;或执行 cargo ckeckmain.rs use candle_core::{Device…...

Python算法题集_接雨水

本文为Python算法题集之一的代码示例 题目42&#xff1a;接雨水 说明&#xff1a;给定 n 个非负整数表示每个宽度为 1 的柱子的高度图&#xff0c;计算按此排列的柱子&#xff0c;下雨之后能接多少雨水 示例 1&#xff1a; 输入&#xff1a;height [0,1,0,2,1,0,1,3,2,1,2,1]…...

FIND_IN_SET的使用:mysql表数据多角色、多用户查询

MySQL 函数 FIND_IN_SET 是用于在逗号分隔的字符串中查找特定值的函数。它的语法如下&#xff1a; FIND_IN_SET(search_value, comma_separated_string)search_value 是要查找的值。 comma_separated_string 是逗号分隔的字符串&#xff0c;在这个字符串中查找指定的值。FIND_…...

JVM篇----第十一篇

系列文章目录 文章目录 系列文章目录前言一、在新生代-复制算法二、在老年代-标记整理算法三、分区收集算法四、GC 垃圾收集器前言 前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这篇文章男女通用,看懂了就去分享给你…...

鸿蒙HarmonyOS获取GPS精确位置信息

参考官方文档 #1.初始化时获取经纬度信息 aboutToAppear() {this.getLocation() } async getLocation () {try {const result await geoLocationManager.getCurrentLocation()AlertDialog.show({message: JSON.stringify(result)})}catch (error) {AlertDialog.show({message…...

java正则校验,手机号,邮箱,日期格式,时间格式,数字金额两位小数

java正则校验&#xff0c;手机号&#xff0c;邮箱&#xff0c;日期格式&#xff0c;时间格式&#xff0c;数字金额两位小数 3.58是否为金额&#xff1a;true 3.582是否为金额&#xff1a;false 1284789qq.com是否为email&#xff1a;true 1284789qq.com是否为email&#xff1…...

php下curl发送cookie

目录 一&#xff1a;使用 CURLOPT_COOKIE 选项 二&#xff1a;CURLOPT_COOKIEFILE 三&#xff1a;CURLOPT_HTTPHEADER php curl发送cookie的几种方式,下面来介绍下 一&#xff1a;使用 CURLOPT_COOKIE 选项 通过设置 CURLOPT_COOKIE 选项&#xff0c;你可以将 cookie 字符…...

stable diffusion学习笔记——文生图(一)

模型设置 基本模型 基本模型也就是常说的checkpoint&#xff08;大模型&#xff09;&#xff0c;基本模型决定了生成图片的主体风格。 如上图所示&#xff0c;基本模型的后缀为.safetensors。需要存放在特定的文件夹下。 如果用的是启动器&#xff0c;可以在启动器内直接下载。…...

Linux下安装openresty

Linux下安装openresty 十一、Linux下安装openresty11.1.概述11.2.下载OpenResty并安装相关依赖&#xff1a;11.3.使用wget下载:11.4.解压缩:11.5.进入OpenResty目录:11.6.编译和安装11.7.进入OpenResty的目录&#xff0c;找到nginx&#xff1a;11.8.在conf目录下的nginx.conf添…...

【IM】如何保证消息可用性(一)

目录 1. 基本概念1.1 长连接 和 短连接1.2 PUSH模式和PULL模式 2. 背景介绍2.1 理解端到端的思想 3. 方案选型3.1 技术挑战3.2 技术目标 1. 基本概念 在讲解消息可用性之前&#xff0c;需要理解几个通信领域的基本概念。 1.1 长连接 和 短连接 什么是长连接&#xff0c;短连接…...

js直接下载附件和通过blob数据类型下载文件

js下载文件方式有使用a标签的&#xff0c;也有直接用window.open的&#xff0c;还有用form表单的&#xff1b;这里采用的是a标签的下载方式&#xff0c;一种是url直接下载&#xff0c;另一种是文件的blob数据类型进行下载。 文件blob数据类型的获取一般是后端返回文件的二进制流…...

第2章-神经网络的数学基础——python深度学习

第2章 神经网络的数学基础 2.1 初识神经网络 我们来看一个具体的神经网络示例&#xff0c;使用 Python 的 Keras 库 来学习手写数字分类。 我们这里要解决的问题是&#xff0c; 将手写数字的灰度图像&#xff08;28 像素28 像素&#xff09;划分到 10 个类别 中&#xff08;0…...

【Docker】Docker学习⑧ - Docker仓库之分布式Harbor

【Docker】Docker学习⑧ - Docker仓库之分布式Harbor 一、Docker简介二、Docker安装及基础命令介绍三、Docker镜像管理四、Docker镜像与制作五、Docker数据管理六、网络部分七、Docker仓库之单机Dokcer Registry八、 Docker仓库之分布式Harbor1 Harbor功能官方介绍2 安装Harbor…...

一行命令在 wsl-ubuntu 中使用 Docker 启动 Windows

在 wsl-ubuntu 中使用 Docker 启动 Windows 0. 背景1. 验证我的系统是否支持 KVM&#xff1f;2. 使用 Docker 启动 Windows3. 访问 Docker 启动的 Windows4. Docker Hub 地址5. Github 地址 0. 背景 我们可以在 Windows 系统使用安装 wsl-ubuntu&#xff0c;今天玩玩在 wsl-ub…...

Datawhale 组队学习之大模型理论基础 Task7 分布式训练

第8章 分布式训练 8.1 为什么分布式训练越来越流行 近年来&#xff0c;模型规模越来越大&#xff0c;对硬件&#xff08;算力、内存&#xff09;的发展提出要求。因为内存墙的存在&#xff0c;单一设持续提高芯片的集成越来越困难&#xff0c;难以跟上模型扩大的需求。 为了…...

05-使用结构体构建相关数据

上一篇&#xff1a; 04-了解所有权 结构体&#xff08;struct&#xff09;是一种自定义数据类型&#xff0c;可以将多个相关值打包命名&#xff0c;组成一个有意义的组。如果你熟悉面向对象的语言&#xff0c;那么结构体就像是对象的数据属性。在本章中&#xff0c;我们将对元组…...

【Android】Android中的系统镜像由什么组成?

文章目录 总览Boot Loader 的加锁与解锁Boot 镜像内核RAM diskARM 中的设备树 (Device Tree) /System 和/Data 分区镜像参考 总览 各种Android设备都只能刷专门为相应型号的设备定制的镜像。 厂商会提供一套系统镜像把它作为“出厂默认”的 Android 系统刷在设备上。 一个完…...

仿真机器人-深度学习CV和激光雷达感知(项目2)day7【ROS关键组件】

文章目录 前言Launch 文件了解 XML 文件Launch 文件作用Launch 文件常用标签实例--作业1的 Launch 文件TF Tree介绍发布坐标变换--海龟例程获取坐标变换--海龟自动跟随例程rqt_工作箱前言 💫你好,我是辰chen,本文旨在准备考研复试或就业 💫本文内容是我为复试准备的第二个…...

解锁一些SQL注入的姿势

昨天课堂上布置了要去看一些sql注入的案例&#xff0c;以下是我的心得&#xff1a; ​​​​​​​ ​​​​​​​ ​​​​​​​ 1.新方法 打了sqli的前十关&#xff0c;我发现一般都是联合查询&#xff0c;但是有没有不是联合查询的方法呢&#xf…...

Qt 拖拽事件示例

一、引子 拖拽这个动作,在桌面应用程序中是非常实用和具有很友好的交互体验的。我们常见的譬如有,将文件拖拽到某个窗口打开,或者拖拽文件到指定位置上传;在绘图软件中,选中某个模板、并拖拽到画布上,画布上变回绘制该模板的图像… 诸如此类,数不胜数。 那么,在Qt中我…...

TVA在齿轮箱零部件及其装配质检中的应用(六)

前沿技术背景介绍&#xff1a;AI 智能体视觉检测系统&#xff08;TVA&#xff0c;全称为 Transformer-based Vision Agent&#xff09;&#xff0c;是基于 Transformer 架构与 “因式智能体” 范式构建的高精度视觉智能体。它区别于传统机器视觉软件及早期 AI 视觉技术&#xf…...

iOS开发避坑指南:IDFA、IDFV、UUID到底怎么选?别再混淆了!

iOS设备标识符深度解析&#xff1a;IDFA、IDFV与UUID的实战选择策略 每次在iOS项目中遇到设备标识需求时&#xff0c;面对IDFA、IDFV和UUID这三个选项&#xff0c;你是否也曾在深夜调试时对着文档陷入选择困难&#xff1f;作为经历过无数坑的老司机&#xff0c;我想分享一些实战…...

别再只调亮度了!用STM32的PWM和外部中断,给你的台灯加上“防近视”和“小夜灯”模式

用STM32打造智能护眼台灯&#xff1a;从PWM调光到健康感知系统 1. 重新定义台灯&#xff1a;从照明工具到健康伙伴 传统台灯的核心功能是提供光源&#xff0c;但现代人对健康用眼的需求远不止于此。想象一下&#xff0c;当孩子写作业时身体不自觉前倾&#xff0c;台灯能主动提醒…...

Perfetto上下文切换分析终极指南:快速定位进程调度开销问题

Perfetto上下文切换分析终极指南&#xff1a;快速定位进程调度开销问题 【免费下载链接】perfetto Production-grade client-side tracing, profiling, and analysis for complex software systems. 项目地址: https://gitcode.com/GitHub_Trending/pe/perfetto Perfett…...

为什么92%的“智慧交通”项目三年后停摆?AGI时代城市治理的3大认知断层与破局公式(内部推演纪要)

第一章&#xff1a;AGI驱动的城市交通治理范式革命 2026奇点智能技术大会(https://ml-summit.org) 传统交通治理长期受限于静态模型、滞后响应与孤岛式数据协同&#xff0c;而具备自主推理、多源语义理解与跨域决策能力的通用人工智能&#xff08;AGI&#xff09;正从根本上重…...

天赐范式第16天:【硬核物理】哥本哈根学派沉默了:用纯经典混沌模拟出量子双缝干涉,量子力学统计特性可能是高维相空间混沌投影的观点(附源码)

摘要&#xff1a;不需要波函数&#xff0c;不需要概率云&#xff0c;甚至不需要“上帝掷骰子”。本文基于受驱摆高斯势垒的混沌系统&#xff0c;利用 RK45 高精度积分器&#xff0c;在 2000 个粒子的系综模拟中&#xff0c;成功复现了双缝干涉的统计包络特征&#xff0c;分布重…...

艾可瑞妥单抗EPKINLY真实世界经验:缓解率数据与中性粒细胞减少、发热等副作用的预防及处理

艾可瑞妥单抗&#xff08;EPKINLY&#xff09;作为一种创新型的双特异性T细胞衔接剂&#xff0c;在复发或难治性弥漫性大B细胞淋巴瘤&#xff08;DLBCL&#xff09;的治疗中展现出显著的疗效。缓解率数据多项真实世界研究数据支持了EPKINLY在治疗DLBCL中的显著疗效。例如&#…...

Laravel Blade 中高效筛选并限制关联分类数据的实践指南

本文讲解如何在 Laravel 中避免在 Blade 模板中嵌套循环与字符串解析&#xff0c;转而使用数据库层的 WHERE FIND_IN_SET() 配合 limit() 实现精准、高效的数据筛选与分页控制。 本文讲解如何在 laravel 中避免在 blade 模板中嵌套循环与字符串解析&#xff0c;转而使用数…...

Redis怎样设计企业级备份策略_结合全量RDB与增量AOF实现多级数据保护

全量备份应选RDB&#xff1b;因其文件小、恢复快&#xff0c;适合作为每日基线备份&#xff0c;而AOF仅宜作为增量补丁&#xff0c;不可替代RDB承担全量角色。全量备份选 RDB 还是 AOF&#xff1f;得看恢复速度和磁盘压力RDB 是快照式备份&#xff0c;save 或 bgsave 生成的 du…...

层次分析法(AHP)翻车实录:我踩过的3个大坑和避坑指南

层次分析法实战避坑指南&#xff1a;从理论到落地的关键挑战 去年数学建模竞赛中&#xff0c;我们团队在决策分析环节选择了层次分析法&#xff08;AHP&#xff09;&#xff0c;结果却因为几个隐蔽的陷阱导致最终结果与实际情况严重偏离。这次经历让我深刻认识到——掌握AHP的基…...