Qiita Conference 2025

Qiita史上最多!豪華12名のゲストが登壇

特別講演ゲスト(敬称略)

ymrl、成瀬允宣、鹿野壮、伊藤淳一、uhyo、徳丸浩、ミノ駆動、みのるん、桜庭洋之、tenntenn、けんちょん、こにふぁー

37
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GPUからHello World!

Posted at

GPUからHello World!

by termoshtt
1 / 6

先行研究


Accel: GPGPU Framework for Rust


CUDAのprintf / PTX system call

# include <stdio.h>

__global__ void test() {
    printf("Hello world from %d of %d\n", threadIdx.x, blockDim.x);
}

この printf はCPUの方に命令を投げないといけないので、CUDAのコンパイル時にはPTX system callにある vprintf の呼び出しに変換されて、実行時にはドライバによって管理されます。システムコールには以下の4つがあり、それぞれ core::arch::nvptx に対応する命令がある

  • vprintf
  • malloc
  • free
  • __assert_fail

print! macro

  • Rustのprint!などは内部でメモリ確保を行うのでlibcoreにはない
  • 最近stdからメモリ確保だけを必要とする部分を分離したalloc crateというのがある
    • Global Allocatorさえあれば動く
      • malloc/freeがPTX system callにあるので動く
    • format!マクロはあるので文字列には出来る
    • しかし標準出力はstdにしか無い
      • なので vprintf system callに文字列を上げる
# [macro_export]
macro_rules! print {
    ($($arg:tt)*) => {
        let msg = ::alloc::format!($($arg)*);
        unsafe {
            ::core::arch::nvptx::vprintf(msg.as_ptr(), ::core::ptr::null_mut());
        }
    }
}

Hello World!

use accel::*;
use accel_derive::kernel;

# [kernel]
pub fn print() {
    let i = accel_core::index();
    accel_core::println!("Hello from {}", i);
}

fn main() -> anyhow::Result<()> {
    let grid = Grid::x(1);
    let block = Block::x(4);
    let device = driver::Device::nth(0)?;
    let _ctx = device.create_context_auto()?;
    print(grid, block)?;
    Ok(())
}
37
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
37
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?