RUST笔记:candle使用基础

2024-02-05 02:10
文章标签 基础 rust 使用 笔记 candle

本文主要是介绍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使用基础的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:https://blog.csdn.net/ResumeProject/article/details/135855626
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/679474

相关文章

Python使用openpyxl读取Excel的操作详解

《Python使用openpyxl读取Excel的操作详解》本文介绍了使用Python的openpyxl库进行Excel文件的创建、读写、数据操作、工作簿与工作表管理,包括创建工作簿、加载工作簿、操作... 目录1 概述1.1 图示1.2 安装第三方库2 工作簿 workbook2.1 创建:Workboo

使用Go实现文件复制的完整流程

《使用Go实现文件复制的完整流程》本案例将实现一个实用的文件操作工具:将一个文件的内容完整复制到另一个文件中,这是文件处理中的常见任务,比如配置文件备份、日志迁移、用户上传文件转存等,文中通过代码示例... 目录案例说明涉及China编程知识点示例代码代码解析示例运行练习扩展小结案例说明我们将通过标准库 os

postgresql使用UUID函数的方法

《postgresql使用UUID函数的方法》本文给大家介绍postgresql使用UUID函数的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录PostgreSQL有两种生成uuid的方法。可以先通过sql查看是否已安装扩展函数,和可以安装的扩展函数

如何使用Lombok进行spring 注入

《如何使用Lombok进行spring注入》本文介绍如何用Lombok简化Spring注入,推荐优先使用setter注入,通过注解自动生成getter/setter及构造器,减少冗余代码,提升开发效... Lombok为了开发环境简化代码,好处不用多说。spring 注入方式为2种,构造器注入和setter

MySQL中比较运算符的具体使用

《MySQL中比较运算符的具体使用》本文介绍了SQL中常用的符号类型和非符号类型运算符,符号类型运算符包括等于(=)、安全等于(=)、不等于(/!=)、大小比较(,=,,=)等,感兴趣的可以了解一下... 目录符号类型运算符1. 等于运算符=2. 安全等于运算符<=>3. 不等于运算符<>或!=4. 小于运

使用zip4j实现Java中的ZIP文件加密压缩的操作方法

《使用zip4j实现Java中的ZIP文件加密压缩的操作方法》本文介绍如何通过Maven集成zip4j1.3.2库创建带密码保护的ZIP文件,涵盖依赖配置、代码示例及加密原理,确保数据安全性,感兴趣的... 目录1. zip4j库介绍和版本1.1 zip4j库概述1.2 zip4j的版本演变1.3 zip4

Python 字典 (Dictionary)使用详解

《Python字典(Dictionary)使用详解》字典是python中最重要,最常用的数据结构之一,它提供了高效的键值对存储和查找能力,:本文主要介绍Python字典(Dictionary)... 目录字典1.基本特性2.创建字典3.访问元素4.修改字典5.删除元素6.字典遍历7.字典的高级特性默认字典

使用Python构建一个高效的日志处理系统

《使用Python构建一个高效的日志处理系统》这篇文章主要为大家详细讲解了如何使用Python开发一个专业的日志分析工具,能够自动化处理、分析和可视化各类日志文件,大幅提升运维效率,需要的可以了解下... 目录环境准备工具功能概述完整代码实现代码深度解析1. 类设计与初始化2. 日志解析核心逻辑3. 文件处

一文详解如何使用Java获取PDF页面信息

《一文详解如何使用Java获取PDF页面信息》了解PDF页面属性是我们在处理文档、内容提取、打印设置或页面重组等任务时不可或缺的一环,下面我们就来看看如何使用Java语言获取这些信息吧... 目录引言一、安装和引入PDF处理库引入依赖二、获取 PDF 页数三、获取页面尺寸(宽高)四、获取页面旋转角度五、判断

C++中assign函数的使用

《C++中assign函数的使用》在C++标准模板库中,std::list等容器都提供了assign成员函数,它比操作符更灵活,支持多种初始化方式,下面就来介绍一下assign的用法,具有一定的参考价... 目录​1.assign的基本功能​​语法​2. 具体用法示例​​​(1) 填充n个相同值​​(2)