jay/device/mod.rs
1//! Where a compiled expression runs.
2//!
3//! Placement is deliberately not part of binding. A kernel bound to data is
4//! the same kernel wherever it executes; a [`Device`] says which processor
5//! executes it, and the CPU is one of the answers. `Program::run_on` takes
6//! the device explicitly, and everything a device cannot do falls back to
7//! the CPU path with a reason a caller can read.
8//!
9//! What runs on a GPU this phase is the fused elementwise kernel and nothing
10//! else. [`crate::fuse`] already compiles a chain of scalar verbs into a
11//! postfix program over blocks, with an optional reduction folded in — that
12//! is a kernel description, and `codegen` turns it into WGSL at run time.
13//! Anything outside a fused node, and any fused node the generator declines,
14//! runs where it always ran.
15//!
16//! # Precision
17//!
18//! libjay computes floats in f64. WGSL can express f64, but almost no
19//! adapter implements it: Metal has no double at all, and on Vulkan it is a
20//! feature (`SHADER_F64`) that many drivers leave off. A device that cannot
21//! run f64 therefore **declines** by default rather than quietly computing
22//! in f32 — losing precision is not a performance decision libjay may take
23//! on the caller's behalf. `Precision::F32` is the caller saying, in so many
24//! words, that they want it.
25//!
26//! # Residency
27//!
28//! [`Device::upload`] returns an array that carries its own location: the
29//! buffer it hands back keeps the device allocation alive inside its owner
30//! handle, so passing it to a later run uploads nothing. The array is an
31//! ordinary [`Array`] otherwise, which is what lets a fallback to the CPU
32//! read it without asking anyone.
33
34mod codegen;
35mod gpu;
36
37use std::any::Any;
38use std::sync::Arc;
39
40use crate::array::{Array, Buf, Data, Owner};
41use crate::dtype::DType;
42use crate::fuse::{FusedKernel, Yield};
43
44pub use codegen::Precision;
45
46/// One adapter, as the machine reports it.
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub struct DeviceInfo {
49 /// The adapter's own name, e.g. "AMD Radeon Pro 560".
50 pub name: String,
51 /// The API behind it: Metal, Vulkan, DX12.
52 pub backend: String,
53 /// discrete GPU, integrated GPU, virtual GPU, CPU, or other.
54 pub kind: String,
55 /// Whether shaders on this adapter can compute in f64. Where this is
56 /// false, only an explicit `Precision::F32` reaches the device.
57 pub f64: bool,
58}
59
60/// Every adapter this machine offers, in the order the backend ranks them.
61/// Empty on a machine with no GPU, which is not an error.
62pub fn available() -> Vec<DeviceInfo> {
63 gpu::enumerate()
64}
65
66/// Where a program runs.
67///
68/// Cloning is cheap: the GPU handle is shared, so two clones name the same
69/// adapter and the same uploaded buffers.
70#[derive(Clone)]
71pub struct Device {
72 at: Where,
73 precision: Precision,
74}
75
76#[derive(Clone)]
77enum Where {
78 Cpu,
79 Gpu(Arc<dyn Backend>),
80}
81
82impl std::fmt::Debug for Device {
83 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84 match &self.at {
85 Where::Cpu => write!(f, "Device(cpu)"),
86 Where::Gpu(g) => {
87 write!(f, "Device({}, {:?})", g.info().name, self.precision)
88 }
89 }
90 }
91}
92
93impl Device {
94 /// The processor everything already ran on.
95 pub fn cpu() -> Device {
96 Device { at: Where::Cpu, precision: Precision::F64 }
97 }
98
99 /// The machine's preferred adapter, or None where there is none.
100 ///
101 /// The adapter is opened once per process and shared; asking twice
102 /// costs nothing and hands back the same device.
103 pub fn default_gpu() -> Option<Device> {
104 Some(Device { at: Where::Gpu(gpu::shared()?), precision: Precision::F64 })
105 }
106
107 /// The same device, computing in `p`.
108 ///
109 /// `Precision::F32` is an explicit request to compute a f64 program in
110 /// single precision. It is the only way a machine whose shaders have no
111 /// f64 runs anything at all on its GPU.
112 pub fn with_precision(&self, p: Precision) -> Device {
113 Device { at: self.at.clone(), precision: p }
114 }
115
116 pub fn precision(&self) -> Precision {
117 self.precision
118 }
119
120 pub fn is_gpu(&self) -> bool {
121 matches!(self.at, Where::Gpu(_))
122 }
123
124 /// What this device is, or None for the CPU.
125 pub fn info(&self) -> Option<&DeviceInfo> {
126 match &self.at {
127 Where::Cpu => None,
128 Where::Gpu(g) => Some(g.info()),
129 }
130 }
131
132 fn backend(&self) -> Option<&Arc<dyn Backend>> {
133 match &self.at {
134 Where::Cpu => None,
135 Where::Gpu(g) => Some(g),
136 }
137 }
138
139 /// `y` with its elements resident on this device.
140 ///
141 /// The result is an ordinary array — same shape, same values, readable
142 /// by anything — that additionally holds the device allocation, so a
143 /// run that reaches the device with it uploads nothing. Uploading to
144 /// the CPU is the identity.
145 pub fn upload(&self, y: &Array) -> Result<Array, DeviceError> {
146 let Some(backend) = self.backend() else { return Ok(y.clone()) };
147 // What goes to the device is the elements in row-major order; a
148 // column-major argument is laid out once before it leaves.
149 let laid_out;
150 let y = if y.is_row_major() {
151 y
152 } else {
153 laid_out = y.to_row_major();
154 &laid_out
155 };
156 // A float array is uploaded from its own buffer; anything else is
157 // converted once, and the conversion becomes the host mirror.
158 let host = match &y.data {
159 Data::F64(_) => Host::Same(y.data.clone()),
160 Data::I64(v) => Host::Made(v.iter().map(|&x| x as f64).collect()),
161 Data::Bool(v) => Host::Made(v.iter().map(|&x| x as f64).collect()),
162 _ => {
163 return Err(DeviceError(
164 "only boolean, integer and float arrays can be uploaded".into(),
165 ))
166 }
167 };
168 let handle = backend.upload(host.values(), self.precision)?;
169 let resident = Arc::new(Resident {
170 device: Arc::as_ptr(backend) as *const () as usize,
171 precision: self.precision,
172 elems: host.values().len(),
173 handle,
174 host,
175 });
176 let values = resident.host.values();
177 let (ptr, len) = (values.as_ptr(), values.len());
178 // SAFETY: the elements live inside the `Arc` this owner holds — in
179 // the array's own refcounted buffer or in the vector made for the
180 // upload — so they stay valid and unmutated for as long as the
181 // buffer that borrows them does.
182 let owner: Owner = resident;
183 Ok(Array::new(y.shape.clone(), Data::F64(unsafe { Buf::foreign(ptr, len, owner) })))
184 }
185
186 /// Is this array already resident on this device, at this precision?
187 pub fn holds(&self, y: &Array) -> bool {
188 self.backend().is_some_and(|b| resident_on(y, b, self.precision).is_some())
189 }
190}
191
192/// The elements an uploaded array's buffer borrows: the array's own, when
193/// it was already f64, or the conversion the upload had to make anyway.
194enum Host {
195 Same(Data),
196 Made(Vec<f64>),
197}
198
199impl Host {
200 fn values(&self) -> &[f64] {
201 match self {
202 Host::Same(Data::F64(v)) => v.as_slice(),
203 Host::Same(_) => &[],
204 Host::Made(v) => v,
205 }
206 }
207}
208
209/// A device allocation, and the host mirror an ordinary array reads.
210struct Resident {
211 /// Identifies the backend the allocation belongs to. Two devices that
212 /// share a backend share their uploads; a buffer from another one is
213 /// not usable and is re-uploaded.
214 device: usize,
215 precision: Precision,
216 elems: usize,
217 handle: Handle,
218 host: Host,
219}
220
221/// The device allocation behind this array's buffer, when it has one that
222/// belongs to `backend` at `precision`.
223fn resident_on<'a>(
224 y: &'a Array,
225 backend: &Arc<dyn Backend>,
226 precision: Precision,
227) -> Option<&'a Handle> {
228 let owner = y.data.owner()?;
229 let r: &Resident = owner.downcast_ref()?;
230 let same = r.device == Arc::as_ptr(backend) as *const () as usize
231 && r.precision == precision
232 && r.elems == y.data.len();
233 same.then_some(&r.handle)
234}
235
236/// A device operation that could not be carried out. These are host-side
237/// failures — no adapter, an allocation refused, a shader the driver would
238/// not compile — not language errors, and they never reach a program's
239/// diagnostics: the caller sees them from [`Device::upload`], and a run
240/// turns them into a fallback to the CPU.
241#[derive(Clone, Debug)]
242pub struct DeviceError(pub String);
243
244impl std::fmt::Display for DeviceError {
245 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246 f.write_str(&self.0)
247 }
248}
249
250impl std::error::Error for DeviceError {}
251
252/// An allocation on a device, opaque to everything but the backend that
253/// made it.
254pub(crate) struct Handle(pub Arc<dyn Any + Send + Sync>);
255
256/// One dispatch: a generated shader, the buffers it reads, and the grid.
257pub(crate) struct Plan<'a> {
258 pub source: &'a str,
259 pub entry: &'a str,
260 pub inputs: &'a [&'a Handle],
261 /// Elements the shader writes.
262 pub out_elems: usize,
263 pub elem_size: usize,
264 /// Elements the kernel maps over.
265 pub n: u32,
266 /// Threads in the grid, for the grid-stride loop a reduction runs.
267 pub stride: u32,
268 pub groups: u32,
269}
270
271/// What a device backend must provide for the fused-kernel path.
272///
273/// One implementation, [`gpu`], covers Metal, Vulkan and DX12 through wgpu.
274/// A second — CUDA, say — is another implementation of this trait and
275/// nothing else: the kernel description, the code generator and the
276/// placement rules above it are backend-agnostic.
277pub(crate) trait Backend: Send + Sync + 'static {
278 fn info(&self) -> &DeviceInfo;
279 /// Copy elements into a device buffer, in the device's element type.
280 fn upload(&self, values: &[f64], p: Precision) -> Result<Handle, DeviceError>;
281 /// Compile (or reuse) the plan's shader and run it, returning what it
282 /// wrote.
283 fn dispatch(&self, plan: &Plan<'_>) -> Result<Vec<u8>, DeviceError>;
284}
285
286// --------------------------------------------------------------- placement
287
288/// Why a fused node ran on the CPU although a device was asked for.
289///
290/// Every one of these is a statement about the kernel or its data, decided
291/// before any work happens, except [`Failed`](Refusal::Failed), which is the
292/// device itself refusing at run time. A fallback is always correct and only
293/// ever slower.
294#[derive(Clone, Debug, PartialEq, Eq)]
295pub enum Refusal {
296 /// The kernel's working type is i64. WGSL has no 64-bit integer
297 /// arithmetic on most adapters, so integer chains stay on the CPU.
298 Integer,
299 /// The chain's result is not f64 — a comparison at the root, a tally.
300 /// Narrowing a device result is not worth the risk this phase.
301 NotFloat,
302 /// The adapter has no f64 in shaders and the caller did not ask for
303 /// f32. See the module note on precision.
304 NoF64,
305 /// The generator does not cover one of the chain's operations at this
306 /// precision.
307 Unsupported(&'static str),
308 /// The kernel itself would decline these inputs, device or no device.
309 Declined,
310 /// Too little data to pay for a dispatch.
311 TooSmall,
312 /// The device refused: an allocation, a shader, a queue submission.
313 Failed(String),
314}
315
316impl Refusal {
317 pub fn reason(&self) -> String {
318 match self {
319 Refusal::Integer => "the chain computes in 64-bit integers".into(),
320 Refusal::NotFloat => "the chain's result is not a float array".into(),
321 Refusal::NoF64 => {
322 "this adapter has no f64 in shaders; pass precision=\"f32\" to run anyway".into()
323 }
324 Refusal::Unsupported(op) => format!("`{op}` has no shader form here"),
325 Refusal::Declined => "the fused kernel declined these inputs".into(),
326 Refusal::TooSmall => "there is too little data to pay for a dispatch".into(),
327 Refusal::Failed(e) => format!("the device refused: {e}"),
328 }
329 }
330}
331
332/// Where a fused node's arithmetic happened.
333#[derive(Clone, Debug, PartialEq, Eq)]
334pub enum Placement {
335 /// No device was asked for, so the question did not arise.
336 Default,
337 Gpu,
338 /// The device would not take it, for this reason.
339 Cpu(Refusal),
340}
341
342impl std::fmt::Display for Placement {
343 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
344 match self {
345 Placement::Default => Ok(()),
346 Placement::Gpu => write!(f, "device: gpu"),
347 Placement::Cpu(why) => write!(f, "device: cpu ({})", why.reason()),
348 }
349 }
350}
351
352/// Least elements worth a dispatch.
353///
354/// Below this the round trip — two submissions, a queue wait, a readback —
355/// costs more than the whole pass does on the CPU, whatever the arithmetic
356/// per element is. Measured on a Radeon Pro 560 against the 8-thread CPU
357/// path, the crossover for the simplest chain (`+/ w * x`) is around a
358/// million elements; the threshold is set an octave below that so that a
359/// heavier chain, which crosses over sooner, is not kept off the device.
360pub const MIN_ELEMS: usize = 1 << 19;
361
362/// Run a fused kernel on `device`, or say why it will not.
363pub(crate) fn try_run(
364 device: &Device,
365 k: &FusedKernel,
366 inputs: &[Array],
367) -> Result<Array, Refusal> {
368 let backend = device.backend().ok_or(Refusal::Declined)?;
369 let precision = device.precision;
370 if precision == Precision::F64 && !backend.info().f64 {
371 return Err(Refusal::NoF64);
372 }
373 // A tally never touches values, and a reduction over one item is the
374 // item itself: both are the fused path's own answers, exactly.
375 if k.yields() == Yield::Tally {
376 return Err(Refusal::Declined);
377 }
378 let Some(Some(shape)) = crate::fuse::common_shape(inputs) else {
379 return Err(Refusal::Declined);
380 };
381 let n: usize = shape.iter().product();
382 if n < MIN_ELEMS {
383 return Err(Refusal::TooSmall);
384 }
385 let reducing = k.reduce().is_some();
386 if reducing && shape.len() != 1 {
387 return Err(Refusal::Declined);
388 }
389 let (working, root) = crate::fuse::working_type(k, inputs).ok_or(Refusal::Declined)?;
390 if working != DType::F64 {
391 return Err(Refusal::Integer);
392 }
393 if root != DType::F64 {
394 return Err(Refusal::NotFloat);
395 }
396
397 // Every input either lies on the device already or goes up now. A
398 // rank-0 input becomes a one-element buffer the shader reads at 0.
399 let splat: Vec<bool> = inputs.iter().map(|a| a.rank() == 0).collect();
400 let source = codegen::wgsl(k, &splat, precision).map_err(Refusal::Unsupported)?;
401
402 let mut temporaries: Vec<Handle> = Vec::new();
403 let mut slots: Vec<Option<&Handle>> = Vec::with_capacity(inputs.len());
404 for a in inputs {
405 match resident_on(a, backend, precision) {
406 Some(h) => slots.push(Some(h)),
407 None => {
408 // A float argument goes up from its own buffer; only a
409 // boolean or integer one is converted, and copying tens of
410 // megabytes for nothing is exactly what that would be.
411 let h = match &a.data {
412 Data::F64(v) => backend.upload(v.as_slice(), precision),
413 _ => backend.upload(&as_f64_vec(a), precision),
414 }
415 .map_err(|e| Refusal::Failed(e.0))?;
416 temporaries.push(h);
417 slots.push(None);
418 }
419 }
420 }
421 let mut next = 0usize;
422 let buffers: Vec<&Handle> = slots
423 .iter()
424 .map(|s| match s {
425 Some(h) => *h,
426 None => {
427 let h = &temporaries[next];
428 next += 1;
429 h
430 }
431 })
432 .collect();
433
434 let elem_size = precision.size();
435 let out = if reducing {
436 let groups = codegen::groups_for(n);
437 let plan = Plan {
438 source: &source,
439 entry: codegen::REDUCE,
440 inputs: &buffers,
441 out_elems: groups,
442 elem_size,
443 n: n as u32,
444 stride: (groups * codegen::WORKGROUP) as u32,
445 groups: groups as u32,
446 };
447 let bytes = backend.dispatch(&plan).map_err(|e| Refusal::Failed(e.0))?;
448 let partials = codegen::from_bytes(&bytes, precision, groups);
449 // The partials combine right to left, as the CPU path's chunks do.
450 // Only associative operations are absorbed, so this is the same
451 // regrouping the float contract (§5.9) already allows.
452 let op = k.reduce().expect("reducing");
453 let mut acc = *partials.last().ok_or(Refusal::Declined)?;
454 for &v in partials[..partials.len() - 1].iter().rev() {
455 acc = crate::fuse::step(op, v, acc).ok_or(Refusal::Declined)?;
456 }
457 Array::scalar_f64(acc)
458 } else {
459 let plan = Plan {
460 source: &source,
461 entry: codegen::MAP,
462 inputs: &buffers,
463 out_elems: n,
464 elem_size,
465 n: n as u32,
466 stride: 0,
467 groups: n.div_ceil(codegen::WORKGROUP) as u32,
468 };
469 let bytes = backend.dispatch(&plan).map_err(|e| Refusal::Failed(e.0))?;
470 let values = codegen::from_bytes(&bytes, precision, n);
471 Array::new(shape, Data::F64(values.into()))
472 };
473 Ok(out)
474}
475
476fn as_f64_vec(a: &Array) -> Vec<f64> {
477 match &a.data {
478 Data::F64(v) => v.as_slice().to_vec(),
479 Data::I64(v) => v.iter().map(|&x| x as f64).collect(),
480 Data::Bool(v) => v.iter().map(|&x| x as f64).collect(),
481 _ => Vec::new(),
482 }
483}
484
485#[cfg(test)]
486mod tests {
487 use super::*;
488
489 #[test]
490 fn the_cpu_is_always_a_device() {
491 let d = Device::cpu();
492 assert!(!d.is_gpu());
493 assert!(d.info().is_none());
494 let a = Array::from_f64(vec![1.0, 2.0]);
495 assert_eq!(d.upload(&a).expect("cpu upload"), a);
496 }
497
498 #[test]
499 fn every_refusal_says_something() {
500 for r in [
501 Refusal::Integer,
502 Refusal::NotFloat,
503 Refusal::NoF64,
504 Refusal::Unsupported("^"),
505 Refusal::Declined,
506 Refusal::TooSmall,
507 Refusal::Failed("no adapter".into()),
508 ] {
509 assert!(!r.reason().is_empty());
510 }
511 }
512}