gpu-rng is a Rust project that leverages GPU compute shaders via wgpu to generate random numbers efficiently. It uses a Linear Congruential Generator (LCG) implemented in a compute shader written in WGSL.
This project was made purely as a learning endeavor to try and get more familiar with wgpu, WGSL shaders, random number generation processes, and rust.
- GPU-Accelerated Random Number Generation: Generates random numbers in parallel using a compute shader.
- Linear Congruential Generator (LCG): Implements a simple yet effective algorithm for generating pseudorandom numbers.
- Scalable Workload: Configurable number of random numbers to generate, divided into GPU workgroups.
- Cross-Platform: Built on wgpu, ensuring support across Vulkan, Metal, DirectX, and WebGPU.
Before building and running this project, ensure the following are installed:
- Rust: Install via rustup.
- ... tbh, i think that is all you need?
.
├── Cargo.lock
├── Cargo.toml
├── README.md
└── src
├── main.rs # Main Rust program
└── rng.wgsl # Compute shader
main.rs
: Contains the Rust code to set up the GPU, load the shader, and retrieve random numbers.rng.wgsl
: Defines the compute shader for random number generation.
git clone https://github.com/evanwmart/gpu-rng.git
cd gpu-rng
cargo build
cargo run
-
Compute Shader: The shader (rng.wgsl) is executed on the GPU. It uses the global invocation ID to seed a Linear Congruential Generator (LCG), generating one random number per thread.
-
Buffers:
- An output buffer stores the random numbers generated by the shader.
- A staging buffer is used to transfer data back from the GPU to the CPU.
-
Workgroups: The shader divides work into groups of 64 threads. The number of threads is determined by the NUM_RANDOMS constant in main.rs.
-
Data Transfer:
- The GPU writes random numbers to the output buffer.
- The output is copied to a staging buffer and mapped back to the CPU for reading.
-
Rust and wgpu: The Rust code initializes wgpu, compiles the shader, and handles buffer mapping for GPU-CPU communication.
You can configure the number of random numbers to generate by modifying NUM_RANDOMS in main.rs:
const NUM_RANDOMS: u32 = 1024; // Adjust as needed
When you run the program, it generates and prints a list of random numbers:
$ cargo run
Random Numbers: [2891336453, 3639132858, 91961967, 839758372, ...]
This project uses the following crates:
- wgpu: Safe and portable GPU abstraction.
- bytemuck: Utilities for zero-cost casting of slices and arrays.
- pollster: Blocking executor for async functions.
gpu-rng is a great project for exploring:
- GPU compute shaders.
- Parallel programming concepts.
- Rust's ecosystem for GPU programming.
Contributions are welcome! Feel free to:
- Report issues.
- Suggest improvements.
- Submit pull requests.
This project is licensed under the MIT License.
Shoutout wgpu and Rust for making cool stuff.