ferrotensor 0.7.1

GPU-accelerated machine learning library for training and inference in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
//! Device abstraction for GPU/CPU computation.
//!
//! A [`Device`] is either the CPU or a wgpu GPU (Metal, Vulkan, DX12). Every
//! tensor op runs on both: the GPU path dispatches WGSL kernels, the CPU path
//! runs the reference implementation in `tensor::cpu`. Tensors on the CPU
//! device need no GPU at all, which is what the test suite and CI use.

use std::collections::HashMap;
use std::num::NonZeroU64;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, TryRecvError};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, Instant};
use wgpu::{
    Adapter, BindingResource, Buffer, BufferBinding, BufferUsages, CommandEncoder,
    Device as WgpuDevice, Queue,
};

use crate::backend::{ComputeEngine, Dispatch, FUSED_STORAGE_BINDINGS};
use crate::tensor::Storage;

/// Ops recorded before the pending commands are submitted anyway, so the GPU
/// starts on long op sequences that never read back to the host.
const MAX_PENDING_OPS: usize = 256;

/// Size of the buffer holding the small per-op arguments ([`Arg::Params`],
/// [`Arg::Meta`]) of one batch.
const ARGS_BYTES: usize = 256 * 1024;

/// How long a wait busy-polls the GPU before sleeping between polls.
/// Sleeping costs up to its length on every read back of a short batch.
const SPIN_WAIT: Duration = Duration::from_millis(10);
/// Sleep between polls once [`SPIN_WAIT`] has passed.
const POLL_SLEEP: Duration = Duration::from_micros(50);

/// Largest total size of freed tensor buffers kept for reuse.
const POOL_BYTES: u64 = 128 << 20;

/// Tensor buffers one `fused` dispatch binds (its last binding is the program).
const FUSED_SLOTS: usize = (FUSED_STORAGE_BINDINGS - 1) as usize;

/// One element-wise op for [`GpuContext::elementwise`].
pub(crate) struct ElementwiseStep {
    /// 0 for a `unary_op`, 1 for a `binary_op`.
    pub(crate) kind: u32,
    pub(crate) op: u32,
    /// Scalars of a unary op.
    pub(crate) a: f32,
    pub(crate) b: f32,
    /// One input for a unary op, two for a binary op, each with `n` elements.
    pub(crate) inputs: Vec<Arc<Storage>>,
    /// A new buffer of `n` elements.
    pub(crate) output: Arc<Storage>,
    pub(crate) n: usize,
}

/// Element-wise steps over the same element count, recorded as one `fused`
/// dispatch when the group closes. Holding each slot's storage keeps its
/// buffer out of the pool until then.
struct FusionGroup {
    n: usize,
    /// The storage bound to each slot, in slot order.
    slots: Vec<Arc<Storage>>,
    /// Eight words per step; see the `fused` kernel.
    program: Vec<u32>,
}

impl FusionGroup {
    fn position(&self, storage: &Arc<Storage>) -> Option<usize> {
        self.slots.iter().position(|s| Arc::ptr_eq(s, storage))
    }

    /// Number of slots the group would use with `step` added.
    fn slots_with(&self, step: &ElementwiseStep) -> usize {
        let mut added: Vec<&Arc<Storage>> = Vec::new();
        for s in step.inputs.iter().chain(std::iter::once(&step.output)) {
            if self.position(s).is_none() && !added.iter().any(|a| Arc::ptr_eq(a, s)) {
                added.push(s);
            }
        }
        self.slots.len() + added.len()
    }

    fn slot(&mut self, storage: &Arc<Storage>) -> u32 {
        let index = match self.position(storage) {
            Some(index) => index,
            None => {
                self.slots.push(Arc::clone(storage));
                self.slots.len() - 1
            }
        };
        index as u32
    }

    fn push(&mut self, step: &ElementwiseStep) {
        let src0 = self.slot(&step.inputs[0]);
        let src1 = match step.inputs.get(1) {
            Some(s) => self.slot(s),
            None => 0,
        };
        let dst = self.slot(&step.output);
        self.program.extend_from_slice(&[
            step.kind,
            step.op,
            src0,
            src1,
            dst,
            step.a.to_bits(),
            step.b.to_bits(),
            0,
        ]);
    }
}

/// Freed tensor buffers by size, reused by later ops.
///
/// Reuse needs no synchronisation: the queue runs the new owner's ops after
/// every op of the old one that was recorded before it.
#[derive(Default)]
pub(crate) struct BufferPool {
    free: HashMap<u64, Vec<Buffer>>,
    bytes: u64,
}

/// A tensor's storage buffer; it goes back to its device's pool when dropped.
pub(crate) struct GpuBuffer {
    buffer: Option<Buffer>,
    pool: Arc<Mutex<BufferPool>>,
}

impl std::ops::Deref for GpuBuffer {
    type Target = Buffer;

    #[expect(clippy::expect_used, reason = "the buffer is taken out only in drop")]
    fn deref(&self) -> &Buffer {
        self.buffer.as_ref().expect("buffer used after drop")
    }
}

impl Drop for GpuBuffer {
    fn drop(&mut self) {
        let Some(buffer) = self.buffer.take() else {
            return;
        };
        let Ok(mut pool) = self.pool.lock() else {
            return;
        };
        let size = buffer.size();
        if pool.bytes + size <= POOL_BYTES {
            pool.bytes += size;
            pool.free.entry(size).or_default().push(buffer);
        }
    }
}

/// One binding of a kernel dispatch.
pub(crate) enum Arg<'a> {
    /// A storage buffer, bound whole.
    Buffer(&'a Buffer),
    /// A 16-byte uniform.
    Params([u32; 4]),
    /// A read-only `u32` storage array.
    Meta(&'a [u32]),
}

/// GPU resources shared by every tensor on one GPU device.
///
/// Ops are recorded and submitted together at the next sync point (a read
/// back, a host write, or every [`MAX_PENDING_OPS`] ops) instead of one
/// submission per op. Consecutive dispatches share one compute pass, and
/// their uniforms and shape metadata share one buffer that is written once
/// per batch. The queue runs everything in recording order, so results are
/// the same as submitting each op on its own.
pub(crate) struct GpuContext {
    pub(crate) adapter: Adapter,
    pub(crate) device: WgpuDevice,
    pub(crate) queue: Queue,
    pub(crate) engine: ComputeEngine,
    /// Holds [`Pending::args`] while the batch runs.
    args: Buffer,
    /// Offset alignment of uniform and storage bindings.
    align: usize,
    pending: Mutex<Pending>,
    pool: Arc<Mutex<BufferPool>>,
    /// Whether element-wise ops are fused (`FERROTENSOR_FUSION=1`).
    fusion: AtomicBool,
    /// Placeholders for the unused slots of a `fused` dispatch: one each, so
    /// no buffer is bound twice as read-write.
    fused_dummies: Vec<Buffer>,
}

/// Work recorded since the last submission.
#[derive(Default)]
struct Pending {
    encoder: Option<CommandEncoder>,
    /// Dispatches not yet encoded; they go into one compute pass.
    dispatches: Vec<Dispatch>,
    /// Contents of [`GpuContext::args`] for this batch.
    args: Vec<u8>,
    ops: usize,
    /// Element-wise steps not yet recorded as a `fused` dispatch.
    group: Option<FusionGroup>,
}

impl GpuContext {
    fn new(adapter: Adapter, device: WgpuDevice, queue: Queue) -> Self {
        let engine = ComputeEngine::new(&device);
        let limits = device.limits();
        let align = limits
            .min_uniform_buffer_offset_alignment
            .max(limits.min_storage_buffer_offset_alignment)
            .max(4) as usize;
        let args = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Op arguments"),
            size: ARGS_BYTES as u64,
            usage: BufferUsages::UNIFORM | BufferUsages::STORAGE | BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let fused_dummies = (0..FUSED_SLOTS)
            .map(|_| {
                device.create_buffer(&wgpu::BufferDescriptor {
                    label: Some("Fused slot placeholder"),
                    size: 4,
                    usage: BufferUsages::STORAGE,
                    mapped_at_creation: false,
                })
            })
            .collect();
        let fusion =
            engine.has("fused") && std::env::var("FERROTENSOR_FUSION").as_deref() == Ok("1");
        Self {
            adapter,
            device,
            queue,
            engine,
            args,
            align,
            pending: Mutex::default(),
            pool: Arc::default(),
            fusion: AtomicBool::new(fusion),
            fused_dummies,
        }
    }

    /// Whether element-wise ops go through [`GpuContext::elementwise`].
    pub(crate) fn fusion(&self) -> bool {
        self.fusion.load(Ordering::Relaxed)
    }

    /// Turn fusion on or off (on only where the `fused` kernel compiled).
    /// Tests use it to compare fused and unfused runs on one device.
    #[cfg(test)]
    pub(crate) fn set_fusion(&self, on: bool) {
        self.fusion
            .store(on && self.engine.has("fused"), Ordering::Relaxed);
    }

    /// Record an element-wise op, joining the open fusion group when it has
    /// the same element count and room for the op's buffers.
    pub(crate) fn elementwise(&self, step: ElementwiseStep) {
        let mut pending = self.lock();
        let joins = pending
            .group
            .as_ref()
            .is_some_and(|g| g.n == step.n && g.slots_with(&step) <= FUSED_SLOTS);
        if !joins {
            self.close_group(&mut pending);
            pending.group = Some(FusionGroup {
                n: step.n,
                slots: Vec::new(),
                program: Vec::new(),
            });
        }
        if let Some(group) = pending.group.as_mut() {
            group.push(&step);
        }
        self.count_op(&mut pending);
    }

    /// Record the open fusion group, if any, as one `fused` dispatch.
    fn close_group(&self, pending: &mut Pending) {
        let Some(group) = pending.group.take() else {
            return;
        };
        let buffers: Vec<&Buffer> = group
            .slots
            .iter()
            .map(|s| match &**s {
                Storage::Gpu(buffer) => &**buffer,
                Storage::Cpu(_) => unreachable!("fused step on a CPU tensor"),
            })
            .collect();
        let mut args: Vec<Arg<'_>> = (0..FUSED_SLOTS)
            .map(|i| Arg::Buffer(buffers.get(i).copied().unwrap_or(&self.fused_dummies[i])))
            .collect();
        args.push(Arg::Meta(&group.program));
        args.push(Arg::Params([
            group.n as u32,
            (group.program.len() / 8) as u32,
            0,
            0,
        ]));
        self.stage(
            pending,
            "fused",
            &args,
            ComputeEngine::workgroups_1d(group.n),
        );
    }

    /// A tensor buffer of `bytes` bytes: a freed one when available, else a
    /// new one made by `create`.
    #[expect(
        clippy::expect_used,
        reason = "lock poisoning means another thread panicked while holding the lock"
    )]
    pub(crate) fn buffer(&self, bytes: u64, create: impl FnOnce() -> Buffer) -> GpuBuffer {
        let reused = {
            let mut pool = self.pool.lock().expect("buffer pool lock poisoned");
            let buffer = pool.free.get_mut(&bytes).and_then(Vec::pop);
            if buffer.is_some() {
                pool.bytes -= bytes;
            }
            buffer
        };
        self.adopt(reused.unwrap_or_else(create))
    }

    /// Wrap a new tensor buffer so it goes to the pool when dropped.
    pub(crate) fn adopt(&self, buffer: Buffer) -> GpuBuffer {
        GpuBuffer {
            buffer: Some(buffer),
            pool: Arc::clone(&self.pool),
        }
    }

    #[expect(
        clippy::expect_used,
        reason = "lock poisoning means another thread panicked while holding the lock"
    )]
    fn lock(&self) -> MutexGuard<'_, Pending> {
        self.pending.lock().expect("GPU command lock poisoned")
    }

    /// Record a dispatch of `kernel` with `args[i]` bound to `@binding(i)`.
    pub(crate) fn dispatch(
        &self,
        kernel: &'static str,
        args: &[Arg<'_>],
        workgroups: (u32, u32, u32),
    ) {
        let mut pending = self.lock();
        self.close_group(&mut pending);
        self.stage(&mut pending, kernel, args, workgroups);
        self.count_op(&mut pending);
    }

    /// Stage `args` in the batch's argument buffer and queue the dispatch.
    fn stage(
        &self,
        pending: &mut Pending,
        kernel: &'static str,
        args: &[Arg<'_>],
        workgroups: (u32, u32, u32),
    ) {
        let padded = |bytes: usize| bytes.div_ceil(self.align) * self.align;
        let needed: usize = args
            .iter()
            .map(|arg| match arg {
                Arg::Buffer(_) => 0,
                Arg::Params(_) => padded(16),
                Arg::Meta(words) => padded(words.len().max(1) * 4),
            })
            .sum();
        assert!(
            needed <= ARGS_BYTES,
            "kernel arguments exceed {ARGS_BYTES} bytes"
        );

        if pending.args.len() + needed > ARGS_BYTES {
            self.submit(pending);
        }
        let staged = &mut pending.args;
        let resources = args
            .iter()
            .map(|arg| {
                let bytes: &[u8] = match arg {
                    Arg::Buffer(buffer) => return buffer.as_entire_binding(),
                    Arg::Params(words) => bytemuck::cast_slice(words),
                    Arg::Meta([]) => &[0; 4],
                    Arg::Meta(words) => bytemuck::cast_slice(words),
                };
                let offset = staged.len();
                staged.extend_from_slice(bytes);
                staged.resize(padded(staged.len()), 0);
                BindingResource::Buffer(BufferBinding {
                    buffer: &self.args,
                    offset: offset as u64,
                    size: NonZeroU64::new(bytes.len() as u64),
                })
            })
            .collect();
        let dispatch = self
            .engine
            .dispatch(&self.device, kernel, resources, workgroups);
        pending.dispatches.push(dispatch);
    }

    /// Record a copy of the first `bytes` bytes of `src` into `dst`.
    pub(crate) fn copy(&self, src: &Buffer, dst: &Buffer, bytes: u64) {
        let mut pending = self.lock();
        self.encoder(&mut pending)
            .copy_buffer_to_buffer(src, 0, dst, 0, bytes);
        self.count_op(&mut pending);
    }

    /// Submit every recorded op.
    pub(crate) fn flush(&self) {
        self.submit(&mut self.lock());
    }

    /// Overwrite the start of `buffer` with `data`.
    ///
    /// The queue applies writes before the next submission's commands, so
    /// the ops recorded so far are submitted first.
    pub(crate) fn write_buffer(&self, buffer: &Buffer, data: &[u8]) {
        let mut pending = self.lock();
        self.submit(&mut pending);
        self.queue.write_buffer(buffer, 0, data);
    }

    /// Poll the device until a GPU callback sends on `rx`: busy-polling for
    /// up to [`SPIN_WAIT`], then sleeping [`POLL_SLEEP`] between polls.
    ///
    /// Never blocks in `Maintain::Wait`: wgpu-core 0.19 gives up waiting
    /// there after 5 s and then frees the still-running submission's
    /// resources as if it had finished, which crashes drivers that are still
    /// reading them.
    #[expect(
        clippy::panic,
        reason = "the callback sender lives until wgpu fires it, so a dropped one means the device is lost"
    )]
    pub(crate) fn wait_for<T>(&self, rx: &Receiver<T>) -> T {
        let start = Instant::now();
        loop {
            self.device.poll(wgpu::Maintain::Poll);
            match rx.try_recv() {
                Ok(value) => return value,
                Err(TryRecvError::Empty) if start.elapsed() < SPIN_WAIT => std::thread::yield_now(),
                Err(TryRecvError::Empty) => std::thread::sleep(POLL_SLEEP),
                Err(TryRecvError::Disconnected) => panic!("GPU callback dropped"),
            }
        }
    }

    fn count_op(&self, pending: &mut Pending) {
        pending.ops += 1;
        if pending.ops >= MAX_PENDING_OPS {
            self.submit(pending);
        }
    }

    /// The batch's encoder, with the pending dispatches (and the open
    /// fusion group) encoded into it.
    fn encoder<'p>(&self, pending: &'p mut Pending) -> &'p mut CommandEncoder {
        self.close_group(pending);
        let encoder = pending.encoder.get_or_insert_with(|| {
            self.device
                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                    label: Some("Ferrotensor ops"),
                })
        });
        if !pending.dispatches.is_empty() {
            self.engine.encode(encoder, &pending.dispatches);
            pending.dispatches.clear();
        }
        encoder
    }

    fn submit(&self, pending: &mut Pending) {
        if pending.ops == 0 {
            return;
        }
        self.encoder(pending);
        if !pending.args.is_empty() {
            self.queue.write_buffer(&self.args, 0, &pending.args);
            pending.args.clear();
        }
        if let Some(encoder) = pending.encoder.take() {
            self.queue.submit(std::iter::once(encoder.finish()));
        }
        pending.ops = 0;
    }
}

#[derive(Clone)]
enum Kind {
    Cpu,
    Gpu(Arc<GpuContext>),
}

/// A compute device: the CPU or a GPU.
///
/// Cloning is cheap; clones refer to the same GPU context.
///
/// # Example
/// ```rust,no_run
/// use ferrotensor::Device;
///
/// // A GPU if one is available, else the CPU.
/// let device = Device::best();
/// println!("Using: {} ({})", device.name(), device.backend());
///
/// // Always available, no GPU needed.
/// let cpu = Device::cpu();
/// assert!(cpu.is_cpu());
/// ```
#[derive(Clone)]
pub struct Device {
    kind: Kind,
}

impl Device {
    /// Create a GPU device with the best available backend.
    ///
    /// On macOS this is Metal; on Windows/Linux, Vulkan or DX12. Set the
    /// `WGPU_BACKEND` environment variable (e.g. `vulkan`) to restrict the
    /// choice.
    ///
    /// # Panics
    /// Panics when no GPU adapter is available. Use [`Device::gpu`] to get an
    /// `Option`, or [`Device::best`] to fall back to the CPU.
    #[expect(
        clippy::expect_used,
        reason = "documented panic; Device::gpu and Device::best are the fallible constructors"
    )]
    pub fn new() -> Self {
        Self::gpu().expect("no GPU adapter available; use Device::best() or Device::cpu()")
    }

    /// The CPU device.
    pub fn cpu() -> Self {
        Self { kind: Kind::Cpu }
    }

    /// A GPU device, or `None` when no adapter or device can be created.
    pub fn gpu() -> Option<Self> {
        pollster::block_on(Self::gpu_async())
    }

    /// Async version of [`Device::gpu`].
    pub async fn gpu_async() -> Option<Self> {
        // WGPU_BACKEND (e.g. "vulkan", "metal", "dx12", "gl") restricts the backends tried.
        // WGPU_DX12_COMPILER ("dxc" or "fxc") picks the DX12 shader compiler.
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
            backends: wgpu::util::backend_bits_from_env().unwrap_or(wgpu::Backends::all()),
            dx12_shader_compiler: wgpu::util::dx12_shader_compiler_from_env().unwrap_or_default(),
            ..Default::default()
        });
        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::HighPerformance,
                compatible_surface: None,
                force_fallback_adapter: false,
            })
            .await?;
        let (device, queue) = adapter
            .request_device(
                &wgpu::DeviceDescriptor {
                    label: Some("Ferrotensor Device"),
                    required_features: wgpu::Features::empty(),
                    required_limits: adapter.limits(),
                },
                None,
            )
            .await
            .ok()?;
        Some(Self {
            kind: Kind::Gpu(Arc::new(GpuContext::new(adapter, device, queue))),
        })
    }

    /// Async version of [`Device::new`].
    ///
    /// # Panics
    /// Panics when no GPU is available.
    #[expect(
        clippy::expect_used,
        reason = "documented panic; Device::gpu_async is the fallible constructor"
    )]
    pub async fn new_async() -> Self {
        Self::gpu_async()
            .await
            .expect("no GPU adapter available; use Device::best() or Device::cpu()")
    }

    /// A GPU if one is available, otherwise the CPU.
    pub fn best() -> Self {
        Self::gpu().unwrap_or_else(Self::cpu)
    }

    /// True for the CPU device.
    pub fn is_cpu(&self) -> bool {
        matches!(self.kind, Kind::Cpu)
    }

    /// True for a GPU device.
    pub fn is_gpu(&self) -> bool {
        !self.is_cpu()
    }

    /// Name of the device ("CPU" or the GPU adapter name).
    pub fn name(&self) -> String {
        match &self.kind {
            Kind::Cpu => "CPU".to_string(),
            Kind::Gpu(ctx) => ctx.adapter.get_info().name,
        }
    }

    /// Backend name: "Cpu", or the wgpu backend (Metal, Vulkan, Dx12, ...).
    pub fn backend(&self) -> String {
        match &self.kind {
            Kind::Cpu => "Cpu".to_string(),
            Kind::Gpu(ctx) => format!("{:?}", ctx.adapter.get_info().backend),
        }
    }

    /// Whether the device can run training (every device can).
    pub fn supports_training(&self) -> bool {
        true
    }

    /// True when both handles refer to the same device.
    pub fn same_as(&self, other: &Device) -> bool {
        match (&self.kind, &other.kind) {
            (Kind::Cpu, Kind::Cpu) => true,
            (Kind::Gpu(a), Kind::Gpu(b)) => Arc::ptr_eq(a, b),
            _ => false,
        }
    }

    /// Wait until every op issued on this device has finished.
    ///
    /// GPU ops are queued and run asynchronously; reading a tensor's values
    /// waits for the ops it depends on, so this is only needed for timing.
    /// Does nothing on the CPU.
    pub fn synchronize(&self) {
        if let Some(ctx) = self.gpu_ctx() {
            ctx.flush();
            let (tx, rx) = std::sync::mpsc::channel();
            ctx.queue.on_submitted_work_done(move || {
                let _ = tx.send(());
            });
            ctx.wait_for(&rx);
        }
    }

    /// The GPU context, or `None` on the CPU.
    pub(crate) fn gpu_ctx(&self) -> Option<&GpuContext> {
        match &self.kind {
            Kind::Cpu => None,
            Kind::Gpu(ctx) => Some(ctx),
        }
    }
}

impl Default for Device {
    /// Same as [`Device::best`].
    fn default() -> Self {
        Self::best()
    }
}

impl std::fmt::Debug for Device {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Device")
            .field("name", &self.name())
            .field("backend", &self.backend())
            .finish()
    }
}