好好学习,天天向上

  • 后端开发
    • Rust
  • 区块链
    • BTC
    • Layer2
  • 经济投资
  • 文学创作
    • 哲学思考
    • 随笔
HhxxTtxs
人生到处知何似,应似飞鸿踏雪泥。
  1. 首页
  2. cuda
  3. 正文

如何使用rust调用cuda代码

18 3 月, 2024 829点热度 5人点赞 1条评论
内容 隐藏
1 基本原理
2 示例
3 总结

基本原理

使用已有rust cuda库 cust 来调用cuda代码。

  1. 将cuda代码编译为.ptx或.fatbin文件
  2. 使用cust读取cuda 编译的 .ptx 或者 .fatbin 文件,然后调用其中对应的cuda函数

示例

环境:ubuntu 22.04(rust和cuda要提前安装)

  1. 书写gpu hello-world代码 hello.cu
#include <stdio.h>
#include <cuda_runtime.h>

extern "C"
__global__ void gpu_hello_world()
{
    printf("Hello world GPU!\n");
}
  1. 编译为.ptx或者.fatbin
nvcc --fatbin hello.cu  //输出 hello.fatbin
nvcc --ptx hello.cu		//输出 hello.ptx
  1. 书写rust代码 main.rs
use cust::{launch, module::Module, stream::{Stream, StreamFlags}};


static TEST_FATBIN: &[u8] = include_bytes!("../../hello.fatbin");
static TEST_PTX: &str = include_str!("../../hello.ptx");

fn main() {
    println!("Hello, world!");
    let _ctx = cust::quick_init().unwrap();
    //let module = Module::from_fatbin(TEST_FATBIN, &[]).unwrap();
    let module = Module::from_ptx(TEST_PTX, &[]).unwrap();
    let stream = Stream::new(StreamFlags::DEFAULT, None).unwrap();
    let kernel = module.get_function("gpu_hello_world").unwrap();
    unsafe {
        launch!(kernel<<<1,1,0,stream>>>()).unwrap();
    }
    stream.synchronize().unwrap();
}

Cargo.toml

[package]
name = "cuda-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
cust = { version = "0.3" }  #引入cust
  1. cargo build 编译运行
>>> cargo build 
>>> ./target/debug/cuda-demo 
Hello, world!
Hello from GPU!

总结

cust库做了一层封装,使rust调用cuda代码变的十分简单,只需要专注于业务代码就好。

上面的cuda nvcc的编译流程也可以通过rust的build.rs来实现,让代码更加完善。

本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: cuda rust
最后更新:23 3 月, 2024

hhxxttxs

五年服务端开发,现专职区块链,偏零知识Layer2工程方向

点赞
下一篇 >

文章评论

  • 可以

    不错哦

    18 3 月, 2024
    回复
  • razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
    取消回复

    Archives

    • 2026 年 2 月
    • 2025 年 9 月
    • 2025 年 8 月
    • 2025 年 7 月
    • 2025 年 1 月
    • 2024 年 9 月
    • 2024 年 8 月
    • 2024 年 7 月
    • 2024 年 6 月
    • 2024 年 5 月
    • 2024 年 4 月
    • 2024 年 3 月

    Categories

    • BTC
    • cuda
    • L2
    • rust
    • 其他
    • 区块链
    • 后端开发
    • 哲学思考
    • 文学创作
    • 算法
    • 经济投资
    • 链开发
    • 零知识

    COPYRIGHT © 2024 好好学习,天天向上. ALL RIGHTS RESERVED.

    Theme Kratos Made By Seaton Jiang