Skip to content

Commit 76f3f5f

Browse files
voidstackloopclaude
andcommitted
wgpu: on-device comparisons and where (NaN-correct, no readbacks); memory: page-locked PinnedBuffer
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1 parent 0510fc3 commit 76f3f5f

4 files changed

Lines changed: 259 additions & 0 deletions

File tree

‎crates/oxideon-core/src/backend/mod.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,9 @@ impl Storage {
379379
StorageInner::Cpu(s) => Ok(Self::new_cpu(s.cmp_op(lhs_layout, s, rhs_layout, op)?)),
380380
#[cfg(feature = "wgpu")]
381381
StorageInner::Wgpu(s) => {
382+
if let Some(out) = s.cmp_op(lhs_layout, s, rhs_layout, op)? {
383+
return Ok(Self::new_wgpu(out));
384+
}
382385
let cpu = s.to_cpu()?;
383386
let out = cpu.cmp_op(lhs_layout, &cpu, rhs_layout, op)?;
384387
Ok(Self::new_wgpu(WgpuStorage::from_cpu(&out, s.device())?))
@@ -399,6 +402,9 @@ impl Storage {
399402
}
400403
#[cfg(feature = "wgpu")]
401404
(StorageInner::Wgpu(a), StorageInner::Wgpu(b)) => {
405+
if let Some(out) = a.cmp_op(lhs_layout, b, rhs_layout, op)? {
406+
return Ok(Self::new_wgpu(out));
407+
}
402408
let ca = a.to_cpu()?;
403409
let cb = b.to_cpu()?;
404410
let out = ca.cmp_op(lhs_layout, &cb, rhs_layout, op)?;
@@ -581,6 +587,12 @@ impl Storage {
581587
let n = t_l.shape().iter().product();
582588
return Ok(Self::new_meta(t.dtype(), n));
583589
}
590+
#[cfg(feature = "wgpu")]
591+
if let (StorageInner::Wgpu(c), StorageInner::Wgpu(a), StorageInner::Wgpu(b)) = (&*cond.read(), &*t.read(), &*f.read())
592+
&& let Some(out) = WgpuStorage::where_cond(c, cond_l, a, t_l, b, f_l)?
593+
{
594+
return Ok(Self::new_wgpu(out));
595+
}
584596
let cc = cond.to_cpu_storage()?;
585597
let ct = t.to_cpu_storage()?;
586598
let cf = f.to_cpu_storage()?;

‎crates/oxideon-core/src/backend/wgpu_backend.rs‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ struct WgpuContext {
5050
matmul_pipeline: wgpu::ComputePipeline,
5151
matmul_large_pipeline: wgpu::ComputePipeline,
5252
gather_pipeline: wgpu::ComputePipeline,
53+
where_pipeline: wgpu::ComputePipeline,
5354
reduce_pipeline: wgpu::ComputePipeline,
5455
}
5556

@@ -255,6 +256,7 @@ impl WgpuDevice {
255256
MATMUL_LARGE_WGSL,
256257
),
257258
gather_pipeline: make_pipeline(&device, "oxideon-gather", GATHER_WGSL),
259+
where_pipeline: make_pipeline(&device, "oxideon-where", WHERE_WGSL),
258260
reduce_pipeline: make_pipeline(&device, "oxideon-reduce", REDUCE_WGSL),
259261
device,
260262
queue,
@@ -608,6 +610,58 @@ impl WgpuStorage {
608610
Ok(Self::from_buffer(out, numel, &self.device))
609611
}
610612

613+
/// Elementwise comparison on the device (`f32` operands; the Bool result is stored as 0 / 1 like every non-`f32`
614+
/// device tensor). `None` when the operands are not `f32` or do not fit one dispatch: the caller uses the CPU path.
615+
pub fn cmp_op(&self, lhs_l: &Layout, rhs: &Self, rhs_l: &Layout, op: super::CmpOp) -> Result<Option<Self>> {
616+
let numel = lhs_l.numel();
617+
if self.dtype != DType::F32 || rhs.dtype != DType::F32 || numel == 0 || !self.device.fits_grid(numel, WG) {
618+
return Ok(None);
619+
}
620+
let op_code = match op {
621+
super::CmpOp::Eq => 10,
622+
super::CmpOp::Ne => 11,
623+
super::CmpOp::Lt => 12,
624+
super::CmpOp::Le => 13,
625+
super::CmpOp::Gt => 14,
626+
super::CmpOp::Ge => 15,
627+
};
628+
let a = self.to_contiguous(lhs_l)?;
629+
let b = rhs.to_contiguous(rhs_l)?;
630+
self.device.check_bytes("GPU tensor", numel as u64 * 4)?;
631+
let out = self.device.out_buffer(numel);
632+
let params = BinaryParams { numel: numel as u32, op_code, _pad0: 0, _pad1: 0 };
633+
self.device.run(&self.device.inner.binary_pipeline, &[&a.buffer, &b.buffer, &out], bytemuck::bytes_of(&params), self.device.grid_1d(numel, WG));
634+
let mut s = Self::from_buffer(out, numel, &self.device);
635+
s.dtype = DType::Bool;
636+
Ok(Some(s))
637+
}
638+
639+
/// `cond ? t : f` on the device for a Bool condition and `f32` branches (all three already broadcast to one shape).
640+
/// `None` for other dtypes or sizes beyond one dispatch.
641+
pub fn where_cond(cond: &Self, cond_l: &Layout, t: &Self, t_l: &Layout, f: &Self, f_l: &Layout) -> Result<Option<Self>> {
642+
let numel = t_l.numel();
643+
if cond.dtype != DType::Bool
644+
|| t.dtype != DType::F32
645+
|| f.dtype != DType::F32
646+
|| numel == 0
647+
|| cond_l.numel() != numel
648+
|| f_l.numel() != numel
649+
|| !t.device.fits_grid(numel, WG)
650+
{
651+
return Ok(None);
652+
}
653+
// a Bool tensor's buffer already holds 0 / 1 as f32; gather it like any other layout
654+
let as_f32 = Self { buffer: cond.buffer.clone(), len: cond.len, dtype: DType::F32, device: cond.device.clone() };
655+
let c = as_f32.to_contiguous(cond_l)?;
656+
let a = t.to_contiguous(t_l)?;
657+
let b = f.to_contiguous(f_l)?;
658+
t.device.check_bytes("GPU tensor", numel as u64 * 4)?;
659+
let out = t.device.out_buffer(numel);
660+
let params = BinaryParams { numel: numel as u32, op_code: 0, _pad0: 0, _pad1: 0 };
661+
t.device.run(&t.device.inner.where_pipeline, &[&c.buffer, &a.buffer, &b.buffer, &out], bytemuck::bytes_of(&params), t.device.grid_1d(numel, WG));
662+
Ok(Some(Self::from_buffer(out, numel, &t.device)))
663+
}
664+
611665
pub fn reduce_op(&self, layout: &Layout, axes: &[usize], op: ReduceOp) -> Result<Self> {
612666
if self.dtype == DType::F32 {
613667
if let Some(out) = self.reduce_on_device(layout, axes, op)? {
@@ -928,12 +982,40 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>, @builtin(num_workgroups)
928982
case 7u: { y = a % b; }
929983
case 8u: { let m = a % b; y = select(m, m + b, m != 0.0 && ((m < 0.0) != (b < 0.0))); }
930984
case 9u: { y = floor_div_f(a, b); }
985+
case 10u: { y = f32(a == b); }
986+
case 11u: { y = f32(!(a == b)); }
987+
case 12u: { y = f32(a < b); }
988+
case 13u: { y = f32(a <= b); }
989+
case 14u: { y = f32(a > b); }
990+
case 15u: { y = f32(a >= b); }
931991
default: { y = a; }
932992
}
933993
dst[i] = y;
934994
}
935995
"#;
936996

997+
/// `dst[i] = cond[i] != 0 ? on_true[i] : on_false[i]`.
998+
const WHERE_WGSL: &str = r#"
999+
struct Params {
1000+
numel: u32,
1001+
pad0: u32,
1002+
pad1: u32,
1003+
pad2: u32,
1004+
}
1005+
@group(0) @binding(0) var<storage, read> cond: array<f32>;
1006+
@group(0) @binding(1) var<storage, read> on_true: array<f32>;
1007+
@group(0) @binding(2) var<storage, read> on_false: array<f32>;
1008+
@group(0) @binding(3) var<storage, read_write> dst: array<f32>;
1009+
@group(0) @binding(4) var<uniform> params: Params;
1010+
1011+
@compute @workgroup_size(256)
1012+
fn main(@builtin(global_invocation_id) gid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {
1013+
let i = gid.y * (nwg.x * 256u) + gid.x;
1014+
if (i >= params.numel) { return; }
1015+
dst[i] = select(on_false[i], on_true[i], cond[i] != 0.0);
1016+
}
1017+
"#;
1018+
9371019
/// `dst[i] = src[offset + sum_d coord_d(i) * stride_d]` for the row-major coordinates of `i` in `shape`.
9381020
/// `layout_info` holds the `ndim` sizes followed by the `ndim` strides (strides may be zero or negative).
9391021
const GATHER_WGSL: &str = r#"

‎crates/oxideon-core/src/memory.rs‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,136 @@ pub fn reset_peak() {
4949
PEAK.store(LIVE.load(Relaxed), Relaxed);
5050
}
5151

52+
// ------------------------------------------------------------------------------------------------ pinned memory
53+
54+
#[cfg(windows)]
55+
unsafe extern "system" {
56+
fn VirtualLock(addr: *mut std::ffi::c_void, size: usize) -> i32;
57+
fn VirtualUnlock(addr: *mut std::ffi::c_void, size: usize) -> i32;
58+
}
59+
#[cfg(unix)]
60+
unsafe extern "C" {
61+
fn mlock(addr: *const std::ffi::c_void, len: usize) -> i32;
62+
fn munlock(addr: *const std::ffi::c_void, len: usize) -> i32;
63+
}
64+
65+
const PAGE: usize = 4096;
66+
67+
/// A page-aligned, page-locked (`VirtualLock` / `mlock`) host buffer of `f32`: the OS will not page it out, which keeps
68+
/// uploads to a device and latency-sensitive loops free of page faults (`pin_memory` in other frameworks).
69+
///
70+
/// Locking can be refused (working-set quota on Windows, `RLIMIT_MEMLOCK` on Unix); the buffer then still works and
71+
/// [`is_locked`](Self::is_locked) reports `false`.
72+
pub struct PinnedBuffer {
73+
ptr: std::ptr::NonNull<f32>,
74+
len: usize,
75+
layout: std::alloc::Layout,
76+
locked: bool,
77+
}
78+
79+
// SAFETY: the buffer owns its allocation exclusively, like a `Vec<f32>`.
80+
unsafe impl Send for PinnedBuffer {}
81+
// SAFETY: shared access only hands out `&[f32]`.
82+
unsafe impl Sync for PinnedBuffer {}
83+
84+
impl PinnedBuffer {
85+
/// A zero-filled buffer of `len` values.
86+
pub fn new(len: usize) -> crate::error::Result<Self> {
87+
crate::limits::check_elements("pinned buffer", &[len])?;
88+
let bytes = (len.max(1) * 4).div_ceil(PAGE) * PAGE;
89+
let layout = std::alloc::Layout::from_size_align(bytes, PAGE).map_err(|e| crate::error::Error::Msg(format!("pinned buffer: {e}")))?;
90+
// SAFETY: `layout` has a non-zero size.
91+
let raw = unsafe { std::alloc::alloc_zeroed(layout) };
92+
let ptr = std::ptr::NonNull::new(raw as *mut f32).ok_or_else(|| crate::error::Error::Msg("pinned buffer: allocation failed".into()))?;
93+
// SAFETY: `raw` points to `bytes` bytes owned by this buffer.
94+
#[cfg(windows)]
95+
let locked = unsafe { VirtualLock(raw as *mut std::ffi::c_void, bytes) != 0 };
96+
// SAFETY: as above.
97+
#[cfg(unix)]
98+
let locked = unsafe { mlock(raw as *const std::ffi::c_void, bytes) == 0 };
99+
#[cfg(not(any(windows, unix)))]
100+
let locked = false;
101+
Ok(Self { ptr, len, layout, locked })
102+
}
103+
104+
/// A pinned copy of `data`.
105+
pub fn from_slice(data: &[f32]) -> crate::error::Result<Self> {
106+
let mut b = Self::new(data.len())?;
107+
b.as_mut_slice().copy_from_slice(data);
108+
Ok(b)
109+
}
110+
111+
/// A pinned copy of a tensor's values (converted to `f32`, logical order).
112+
pub fn from_tensor(t: &crate::tensor::Tensor) -> crate::error::Result<Self> {
113+
Self::from_slice(&t.to_dtype(crate::dtype::DType::F32)?.to_vec::<f32>()?)
114+
}
115+
116+
pub fn len(&self) -> usize {
117+
self.len
118+
}
119+
120+
pub fn is_empty(&self) -> bool {
121+
self.len == 0
122+
}
123+
124+
/// Whether the operating system accepted the lock.
125+
pub fn is_locked(&self) -> bool {
126+
self.locked
127+
}
128+
129+
pub fn as_slice(&self) -> &[f32] {
130+
// SAFETY: `ptr` is valid for `len` initialised `f32` values for the life of `self`.
131+
unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
132+
}
133+
134+
pub fn as_mut_slice(&mut self) -> &mut [f32] {
135+
// SAFETY: as above, and `&mut self` gives exclusive access.
136+
unsafe { std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
137+
}
138+
139+
/// A tensor with a copy of the buffer's values in `shape`.
140+
pub fn to_tensor(&self, shape: &[usize]) -> crate::error::Result<crate::tensor::Tensor> {
141+
crate::tensor::Tensor::from_slice(self.as_slice(), shape)
142+
}
143+
}
144+
145+
impl Drop for PinnedBuffer {
146+
fn drop(&mut self) {
147+
let raw = self.ptr.as_ptr() as *mut u8;
148+
// SAFETY: `raw` / `layout` are the allocation made in `new`; it is unlocked (if it was locked) and freed once.
149+
unsafe {
150+
if self.locked {
151+
#[cfg(windows)]
152+
VirtualUnlock(raw as *mut std::ffi::c_void, self.layout.size());
153+
#[cfg(unix)]
154+
munlock(raw as *const std::ffi::c_void, self.layout.size());
155+
}
156+
std::alloc::dealloc(raw, self.layout);
157+
}
158+
}
159+
}
160+
52161
#[cfg(test)]
53162
mod tests {
163+
#[test]
164+
fn pinned_buffers_are_page_aligned_zeroed_writable_and_round_trip_tensors() {
165+
let mut b = super::PinnedBuffer::new(5000).unwrap(); // spans several pages
166+
assert_eq!(b.len(), 5000);
167+
assert_eq!(b.as_slice().as_ptr() as usize % super::PAGE, 0);
168+
assert!(b.as_slice().iter().all(|&v| v == 0.0));
169+
// a small buffer is within every default quota, so the lock itself must succeed on a normal machine
170+
assert!(b.is_locked(), "the OS refused to lock 20 KiB");
171+
for (i, v) in b.as_mut_slice().iter_mut().enumerate() {
172+
*v = i as f32;
173+
}
174+
let t = b.to_tensor(&[50, 100]).unwrap();
175+
assert_eq!(t.to_vec::<f32>().unwrap()[4999], 4999.0);
176+
let back = super::PinnedBuffer::from_tensor(&t.transpose(0, 1).unwrap()).unwrap();
177+
assert_eq!(back.as_slice()[1], 100.0); // logical order of the transposed view
178+
assert!(super::PinnedBuffer::new(0).unwrap().is_empty());
179+
}
180+
181+
54182
use crate::tensor::Tensor;
55183

56184
// global counters: other tests allocate concurrently, so compare with inequalities on a large buffer

‎tests/gpu_kernels.rs‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,3 +412,40 @@ fn division_family_and_nan_semantics_match_the_cpu() -> Result<()> {
412412
assert_eq!(cm[1], gm[1]);
413413
Ok(())
414414
}
415+
416+
#[test]
417+
fn comparisons_and_where_run_on_the_device_and_match_the_cpu() -> Result<()> {
418+
let Some((dev, wd, _lock)) = gpu() else {
419+
return Ok(());
420+
};
421+
let n = 70_000; // more than one workgroup row
422+
let av: Vec<f32> = (0..n).map(|i| ((i * 37 % 101) as f32 - 50.0) * 0.5).collect();
423+
let mut bv: Vec<f32> = (0..n).map(|i| ((i * 53 % 101) as f32 - 50.0) * 0.5).collect();
424+
bv[7] = f32::NAN;
425+
bv[8] = f32::INFINITY;
426+
let (a, b) = (Tensor::from_slice(&av, &[n])?, Tensor::from_slice(&bv, &[n])?);
427+
let (ga, gb) = (a.to_device(&dev)?, b.to_device(&dev)?);
428+
let m2 = Tensor::from_slice(&av[..12], &[3, 4])?;
429+
let g2 = m2.to_device(&dev)?;
430+
let row = Tensor::from_slice(&[0.0f32, -3.0, 5.0], &[3])?;
431+
let grow = row.to_device(&dev)?;
432+
433+
let before = wd.readbacks();
434+
let on_gpu = [ga.eq_tensor(&gb)?, ga.ne_tensor(&gb)?, ga.lt(&gb)?, ga.le(&gb)?, ga.gt(&gb)?, ga.ge(&gb)?];
435+
let w_g = Tensor::where_cond(&ga.gt(&gb)?, &ga, &gb)?;
436+
// a strided condition and broadcast branches
437+
let s_g = Tensor::where_cond(&g2.transpose(0, 1)?.lt(&grow)?, &g2.transpose(0, 1)?, &grow)?;
438+
assert_eq!(wd.readbacks(), before, "comparisons and where must stay on the device");
439+
440+
let on_cpu = [a.eq_tensor(&b)?, a.ne_tensor(&b)?, a.lt(&b)?, a.le(&b)?, a.gt(&b)?, a.ge(&b)?];
441+
for (i, (c, g)) in on_cpu.iter().zip(&on_gpu).enumerate() {
442+
assert_eq!(g.dtype(), DType::Bool);
443+
assert_eq!(c.to_vec::<bool>()?, g.to_device(&Device::Cpu)?.to_vec::<bool>()?, "comparison #{i}");
444+
}
445+
let wc = Tensor::where_cond(&a.gt(&b)?, &a, &b)?.to_vec::<f32>()?;
446+
let wg = w_g.to_device(&Device::Cpu)?.to_vec::<f32>()?;
447+
assert!(wc.iter().zip(&wg).all(|(x, y)| x.to_bits() == y.to_bits() || (x.is_nan() && y.is_nan())), "where");
448+
let s_c = Tensor::where_cond(&m2.transpose(0, 1)?.lt(&row)?, &m2.transpose(0, 1)?, &row)?;
449+
assert_eq!(s_c.to_vec::<f32>()?, s_g.to_device(&Device::Cpu)?.to_vec::<f32>()?);
450+
Ok(())
451+
}

0 commit comments

Comments
 (0)