Skip to main content

GpuContext

Struct GpuContext 

Source
pub struct GpuContext { /* private fields */ }
Expand description

GPU context for compute operations.

Manages GPU device, queue, and cached compute pipelines for FST operations. Create once and reuse for multiple operations to amortize initialization cost.

§Initialization

GPU context creation is an async operation that:

  1. Enumerates available GPU adapters
  2. Requests a device with required features
  3. Compiles and caches compute shader pipelines

Use pollster::block_on() for synchronous initialization:

use arcweight::gpu::GpuContext;

let ctx = pollster::block_on(GpuContext::new())?;
println!("Using GPU: {}", ctx.adapter_info().name);

§Thread Safety

GpuContext is Send but not Sync. Each thread should have its own context, or use synchronization primitives to share access.

§Resource Management

GPU resources are automatically cleaned up when the context is dropped. Buffers created from this context remain valid as long as the context lives.

Implementations§

Source§

impl GpuContext

Source

pub async fn new() -> Result<Self>

Create a new GPU context.

Initializes the GPU backend by requesting a high-performance adapter, creating a device, and compiling compute shader pipelines.

§Async

This is an async operation. Use pollster::block_on() for synchronous initialization in non-async contexts.

§Errors

Returns an error if:

  • No compatible GPU adapter is found
  • Device creation fails
  • Shader compilation fails
§Examples
use arcweight::gpu::GpuContext;

// Async context
async fn init_gpu() -> arcweight::Result<GpuContext> {
    GpuContext::new().await
}

// Synchronous context
let ctx = pollster::block_on(GpuContext::new())?;
Source

pub fn adapter_info(&self) -> &AdapterInfo

Get information about the GPU adapter.

Returns details about the GPU including name, vendor, and backend.

Source

pub fn device(&self) -> &Device

Get the underlying wgpu device.

Use this for advanced GPU operations not provided by this module.

Source

pub fn queue(&self) -> &Queue

Get the wgpu command queue.

Use this for submitting custom command buffers.

Source

pub fn create_weight_buffer(&self, weights: &[f32]) -> Result<GpuWeightBuffer>

Create a weight buffer on the GPU.

Uploads weight data to GPU memory for use in compute operations. The buffer is created with storage and copy usage flags.

§Arguments
  • weights - Slice of f32 weights to upload
§Complexity
  • Time: O(n) for data transfer
  • Space: O(n) GPU memory
§Examples
use arcweight::gpu::GpuContext;

let ctx = pollster::block_on(GpuContext::new())?;
let weights = vec![1.0f32, 2.0, 3.0, 4.0];
let gpu_buffer = ctx.create_weight_buffer(&weights)?;
assert_eq!(gpu_buffer.len(), 4);
Source

pub fn reduce_min_gpu(&self, weights: &GpuWeightBuffer) -> Result<f32>

Compute minimum value using GPU parallel reduction.

Implements tropical semiring addition (minimum) using a multi-pass parallel reduction algorithm optimized for GPU execution.

§Algorithm

Uses a tree-based parallel reduction:

  1. Each workgroup (256 threads) reduces 256 elements to 1
  2. Results are written to intermediate buffer
  3. Repeat until single value remains
§Complexity
  • Time: O(n / p + log p) where p = number of GPU cores
  • Space: O(n / 256) for intermediate buffers
  • Passes: ceil(log_256(n))
§Examples
use arcweight::gpu::GpuContext;

let ctx = pollster::block_on(GpuContext::new())?;
let weights: Vec<f32> = (0..10000).map(|i| i as f32).collect();
let buffer = ctx.create_weight_buffer(&weights)?;

let min = ctx.reduce_min_gpu(&buffer)?;
assert_eq!(min, 0.0);
Source

pub fn reduce_sum_gpu(&self, weights: &GpuWeightBuffer) -> Result<f32>

Compute sum using GPU parallel reduction.

Implements probability semiring addition (sum) using a multi-pass parallel reduction algorithm.

§Complexity

Same as reduce_min_gpu.

Source

pub fn reduce_min(&self, weights: &GpuWeightBuffer) -> Result<f32>

Compute minimum value in a weight buffer (CPU fallback)

Uses parallel reduction on the GPU for O(log n) depth.

Source

pub fn reduce_sum(&self, weights: &GpuWeightBuffer) -> Result<f32>

Compute sum of values in a weight buffer (CPU fallback)

Source

pub fn read_buffer(&self, buffer: &GpuWeightBuffer) -> Result<Vec<f32>>

Read a buffer back to CPU memory

Source

pub fn elementwise_min_gpu( &self, a: &GpuWeightBuffer, b: &GpuWeightBuffer, ) -> Result<GpuWeightBuffer>

Element-wise minimum of two weight buffers using GPU

Source

pub fn elementwise_min( &self, a: &GpuWeightBuffer, b: &GpuWeightBuffer, ) -> Result<GpuWeightBuffer>

Element-wise minimum of two weight buffers

Source

pub fn elementwise_add_gpu( &self, a: &GpuWeightBuffer, b: &GpuWeightBuffer, ) -> Result<GpuWeightBuffer>

Element-wise addition of two weight buffers using GPU

Source

pub fn elementwise_add( &self, a: &GpuWeightBuffer, b: &GpuWeightBuffer, ) -> Result<GpuWeightBuffer>

Element-wise addition of two weight buffers (for tropical multiplication)

Source

pub fn elementwise_mul_gpu( &self, a: &GpuWeightBuffer, b: &GpuWeightBuffer, ) -> Result<GpuWeightBuffer>

Element-wise multiplication of two weight buffers using GPU

Source

pub fn elementwise_mul( &self, a: &GpuWeightBuffer, b: &GpuWeightBuffer, ) -> Result<GpuWeightBuffer>

Element-wise multiplication (for probability semiring)

Source

pub fn log_sum_exp_gpu(&self, weights: &GpuWeightBuffer) -> Result<f32>

Compute log-sum-exp for log semiring using GPU

This is numerically stable using the max-subtract trick.

Source

pub fn batch_reduce_min(&self, weights_list: &[&[f32]]) -> Result<Vec<f32>>

Batch process multiple weight arrays

Efficiently processes multiple arrays in a single GPU dispatch

Trait Implementations§

Source§

impl Debug for GpuContext

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> ArchivePointee for T

Source§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
Source§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> LayoutRaw for T

Source§

fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>

Returns the layout of the type.
Source§

impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
where T: SharedNiching<N1, N2>, N1: Niching<T>, N2: Niching<T>,

Source§

unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool

Returns whether the given value has been niched. Read more
Source§

fn resolve_niched(out: Place<NichedOption<T, N1>>)

Writes data to out indicating that a T is niched.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Pointee for T

Source§

type Metadata = ()

The metadata type for pointers and references to this type.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,