Skip to main content

burn_dispatch/
tensor.rs

1use crate::{DispatchDevice, backends::*};
2
3#[cfg(feature = "autodiff")]
4use burn_autodiff::checkpoint::strategy::{
5    BalancedCheckpointing, CheckpointStrategy, NoCheckpointing,
6};
7use burn_backend::{Backend, BackendTypes, DType, Shape, TensorMetadata};
8
9use crate::GradientCheckpointingStrategy;
10#[cfg(feature = "autodiff")]
11use alloc::boxed::Box;
12#[cfg(feature = "autodiff")]
13use burn_backend::tensor::FloatTensor;
14
15use alloc::{format, string::String};
16
17// TODO: if we reduce the different associated types for float/int/bool/quantized tensor primitives down to a single
18// `B::TensorPrimitive` we can simplify this.
19
20/// Tensor which points to a backend tensor primitive kind.
21#[derive(Clone, Debug)]
22pub enum BackendTensor<B: BackendTypes> {
23    /// Float tensor handle.
24    Float(B::FloatTensorPrimitive),
25    /// Int tensor handle.
26    Int(B::IntTensorPrimitive),
27    /// Bool tensor handle.
28    Bool(B::BoolTensorPrimitive),
29    /// Quantized tensor handle.
30    Quantized(B::QuantizedTensorPrimitive),
31    #[cfg(feature = "autodiff")]
32    /// Autodiff float tensor handle.
33    Autodiff(FloatTensor<Autodiff<B>>),
34}
35
36impl<B: Backend> BackendTensor<B> {
37    /// Returns the inner float tensor primitive.
38    pub fn float(self) -> B::FloatTensorPrimitive {
39        match self {
40            BackendTensor::Float(tensor) => tensor,
41            BackendTensor::Int(_) => panic!("Should be float, got int"),
42            BackendTensor::Bool(_) => panic!("Should be float, got bool"),
43            BackendTensor::Quantized(_) => panic!("Should be float, got quantized"),
44            #[cfg(feature = "autodiff")]
45            BackendTensor::Autodiff(_) => panic!("Should be float, got autodiff"),
46        }
47    }
48    /// Returns the inner float tensor primitive.
49    pub fn as_float(&self) -> &B::FloatTensorPrimitive {
50        match self {
51            BackendTensor::Float(tensor) => tensor,
52            BackendTensor::Int(_) => panic!("Should be float, got int"),
53            BackendTensor::Bool(_) => panic!("Should be float, got bool"),
54            BackendTensor::Quantized(_) => panic!("Should be float, got quantized"),
55            #[cfg(feature = "autodiff")]
56            BackendTensor::Autodiff(_) => panic!("Should be float, got autodiff"),
57        }
58    }
59
60    /// Returns the inner int tensor primitive.
61    pub fn int(self) -> B::IntTensorPrimitive {
62        match self {
63            BackendTensor::Int(tensor) => tensor,
64            BackendTensor::Float(_) => panic!("Should be int, got float"),
65            BackendTensor::Bool(_) => panic!("Should be int, got bool"),
66            BackendTensor::Quantized(_) => panic!("Should be int, got quantized"),
67            #[cfg(feature = "autodiff")]
68            BackendTensor::Autodiff(_) => panic!("Should be int, got autodiff"),
69        }
70    }
71
72    /// Returns the inner bool tensor primitive.
73    pub fn bool(self) -> B::BoolTensorPrimitive {
74        match self {
75            BackendTensor::Bool(tensor) => tensor,
76            BackendTensor::Float(_) => panic!("Should be bool, got float"),
77            BackendTensor::Int(_) => panic!("Should be bool, got int"),
78            BackendTensor::Quantized(_) => panic!("Should be bool, got quantized"),
79            #[cfg(feature = "autodiff")]
80            BackendTensor::Autodiff(_) => panic!("Should be bool, got autodiff"),
81        }
82    }
83
84    /// Returns the inner quantized tensor primitive.
85    pub fn quantized(self) -> B::QuantizedTensorPrimitive {
86        match self {
87            BackendTensor::Quantized(tensor) => tensor,
88            _ => unreachable!(),
89        }
90    }
91
92    #[cfg(feature = "autodiff")]
93    /// Returns the inner autodiff tensor primitive.
94    pub fn autodiff(self) -> FloatTensor<Autodiff<B>> {
95        match self {
96            BackendTensor::Autodiff(tensor) => tensor,
97            // NOTE: this is the panicking code reached in tensor.rs:74:18:
98            _ => unreachable!(),
99        }
100    }
101
102    #[cfg(feature = "autodiff")]
103    /// Returns the inner autodiff tensor primitive.
104    pub fn as_autodiff(&self) -> &FloatTensor<Autodiff<B>> {
105        match self {
106            BackendTensor::Autodiff(tensor) => tensor,
107            _ => unreachable!(),
108        }
109    }
110
111    #[cfg(feature = "autodiff")]
112    /// Returns the inner autodiff tensor primitive.
113    pub fn autodiff_inner(self) -> B::FloatTensorPrimitive {
114        match self {
115            BackendTensor::Autodiff(tensor) => tensor.into_primitive(),
116            _ => unreachable!(),
117        }
118    }
119
120    /// Lift a handle for backend `B` into the equivalent handle for `Autodiff<B>`.
121    ///
122    /// An already-tracked float (`Autodiff`) becomes the `Float` handle of `Autodiff<B>`; int/bool/
123    /// quantized handles are re-tagged unchanged (those primitives are shared between `B` and
124    /// `Autodiff<B>`). An untracked `Float` handle is invalid here (under autodiff, float tensors
125    /// arrive tracked), so it panics.
126    #[cfg(feature = "autodiff")]
127    pub fn into_autodiff(self) -> BackendTensor<Autodiff<B>> {
128        match self {
129            BackendTensor::Autodiff(tensor) => BackendTensor::Float(tensor),
130            BackendTensor::Int(tensor) => BackendTensor::Int(tensor),
131            BackendTensor::Bool(tensor) => BackendTensor::Bool(tensor),
132            BackendTensor::Quantized(tensor) => BackendTensor::Quantized(tensor),
133            BackendTensor::Float(_) => {
134                unreachable!("an untracked float handle can't be lifted to Autodiff<B>")
135            }
136        }
137    }
138
139    /// Returns the tensor primitive kind name.
140    pub fn name(&self) -> &'static str {
141        match self {
142            BackendTensor::Float(_) => "Float",
143            BackendTensor::Int(_) => "Int",
144            BackendTensor::Bool(_) => "Bool",
145            BackendTensor::Quantized(_) => "Quantized",
146            #[cfg(feature = "autodiff")]
147            BackendTensor::Autodiff(_) => "Autodiff",
148        }
149    }
150}
151
152impl<B: BackendTypes> TensorMetadata for BackendTensor<B> {
153    type Device = B::Device;
154    fn device(&self) -> Self::Device {
155        match self {
156            BackendTensor::Float(tensor) => tensor.device(),
157            BackendTensor::Int(tensor) => tensor.device(),
158            BackendTensor::Bool(tensor) => tensor.device(),
159            BackendTensor::Quantized(tensor) => tensor.device(),
160            #[cfg(feature = "autodiff")]
161            BackendTensor::Autodiff(tensor) => tensor.device(),
162        }
163    }
164    fn dtype(&self) -> DType {
165        match self {
166            BackendTensor::Float(tensor) => tensor.dtype(),
167            BackendTensor::Int(tensor) => tensor.dtype(),
168            BackendTensor::Bool(tensor) => tensor.dtype(),
169            BackendTensor::Quantized(tensor) => tensor.dtype(),
170            #[cfg(feature = "autodiff")]
171            BackendTensor::Autodiff(tensor) => tensor.dtype(),
172        }
173    }
174
175    fn shape(&self) -> Shape {
176        match self {
177            BackendTensor::Float(tensor) => tensor.shape(),
178            BackendTensor::Int(tensor) => tensor.shape(),
179            BackendTensor::Bool(tensor) => tensor.shape(),
180            BackendTensor::Quantized(tensor) => tensor.shape(),
181            #[cfg(feature = "autodiff")]
182            BackendTensor::Autodiff(tensor) => tensor.shape(),
183        }
184    }
185
186    fn can_mut(&self) -> bool {
187        match self {
188            BackendTensor::Float(tensor) => tensor.can_mut(),
189            BackendTensor::Int(tensor) => tensor.can_mut(),
190            BackendTensor::Bool(tensor) => tensor.can_mut(),
191            BackendTensor::Quantized(tensor) => tensor.can_mut(),
192            #[cfg(feature = "autodiff")]
193            BackendTensor::Autodiff(tensor) => tensor.can_mut(),
194        }
195    }
196}
197
198/// The autodiff backend associated with a dispatch tensor.
199///
200/// This is backend metadata, not a statement that a float tensor requires
201/// gradients. Enabled float tensors may be tracked or untracked by autodiff.
202///
203/// Tensor inputs to one backend operation merge their autodiff contexts. A disabled context is
204/// compatible with an enabled one and is treated as a constant for that operation. Two enabled
205/// contexts must use the same gradient-checkpointing strategy.
206#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
207pub enum DispatchAutodiffContext {
208    /// Route the tensor through its concrete backend.
209    #[default]
210    Disabled,
211    /// Associate the tensor with an autodiff backend using the given strategy.
212    Enabled(GradientCheckpointingStrategy),
213}
214
215impl DispatchAutodiffContext {
216    /// Merge two tensor contexts into the context used to execute an operation and wrap its output.
217    ///
218    /// Disabled tensors don't acquire a new context themselves. When combined with an enabled
219    /// tensor, they are treated as constants while the operation and its output use the enabled
220    /// context.
221    ///
222    /// # Panics
223    ///
224    /// Panics when both contexts are enabled with different gradient-checkpointing strategies.
225    #[doc(hidden)]
226    pub fn merge(self, other: Self) -> Self {
227        match (self, other) {
228            (Self::Disabled, context) | (context, Self::Disabled) => context,
229            (Self::Enabled(lhs), Self::Enabled(rhs)) => {
230                assert_eq!(
231                    lhs, rhs,
232                    "Gradient checkpointing strategy mismatch: {lhs:?} vs {rhs:?}. Tensors in the same operation must share a strategy."
233                );
234                Self::Enabled(lhs)
235            }
236        }
237    }
238}
239
240/// A tensor that can dispatch operations to any enabled backend at runtime.
241#[derive(Clone, Debug)]
242pub struct DispatchTensor {
243    /// Tensor kind primitive.
244    pub kind: DispatchTensorKind,
245    /// Autodiff backend association for this tensor.
246    pub autodiff: DispatchAutodiffContext,
247}
248
249/// Internal representation of a [`DispatchTensor`].
250///
251/// This enum contains the concrete backend tensor for each enabled backend.
252/// It is not intended to be used directly; instead, it is manipulated by
253/// the dispatch system to route operations to the correct backend.
254///
255/// Each variant corresponds to a specific backend implementation.
256#[derive(Clone, Debug)]
257// With autodiff and a lone Cube or Remote backend, the only other variant is Autodiff's 8-byte
258// box, so the lint fires. Boxing backend tensors would cost every tensor an allocation.
259#[allow(clippy::large_enum_variant)]
260pub enum DispatchTensorKind {
261    #[cfg(not(backend_enabled))]
262    #[doc(hidden)]
263    Unavailable(crate::NoBackend),
264    /// A tensor on the [cubecl backend](Cube) — its device says which runtime.
265    #[cfg(cube_backend)]
266    Cube(BackendTensor<Cube>),
267
268    /// The [Flex backend](Flex) tensor.
269    #[cfg(feature = "flex")]
270    Flex(BackendTensor<Flex>),
271
272    /// The [Remote backend](Remote) tensor (lives on a remote server).
273    #[cfg(feature = "remote")]
274    Remote(BackendTensor<Remote>),
275    /// A tensor recorded by the capture backend.
276    #[cfg(feature = "capture")]
277    Capture(BackendTensor<Capture>),
278    /// A tensor split over a [device group](Group).
279    #[cfg(feature = "group")]
280    Group(BackendTensor<Group>),
281
282    /// The [autodiff enabled backend](Autodiff) tensor.
283    #[cfg(feature = "autodiff")]
284    Autodiff(Box<DispatchTensorKind>),
285}
286
287impl TensorMetadata for DispatchTensorKind {
288    type Device = DispatchDevice;
289
290    fn dtype(&self) -> DType {
291        match self {
292            #[cfg(not(backend_enabled))]
293            Self::Unavailable(never) => never.unreachable(),
294            #[cfg(cube_backend)]
295            Self::Cube(tensor) => tensor.dtype(),
296            #[cfg(feature = "flex")]
297            Self::Flex(tensor) => tensor.dtype(),
298            #[cfg(feature = "remote")]
299            Self::Remote(tensor) => tensor.dtype(),
300            #[cfg(feature = "group")]
301            Self::Group(tensor) => tensor.dtype(),
302            #[cfg(feature = "capture")]
303            Self::Capture(tensor) => tensor.dtype(),
304            #[cfg(feature = "autodiff")]
305            Self::Autodiff(tensor) => tensor.dtype(),
306        }
307    }
308
309    fn shape(&self) -> Shape {
310        match self {
311            #[cfg(not(backend_enabled))]
312            Self::Unavailable(never) => never.unreachable(),
313            #[cfg(cube_backend)]
314            Self::Cube(tensor) => tensor.shape(),
315            #[cfg(feature = "flex")]
316            Self::Flex(tensor) => tensor.shape(),
317            #[cfg(feature = "remote")]
318            Self::Remote(tensor) => tensor.shape(),
319            #[cfg(feature = "group")]
320            Self::Group(tensor) => tensor.shape(),
321            #[cfg(feature = "capture")]
322            Self::Capture(tensor) => tensor.shape(),
323            #[cfg(feature = "autodiff")]
324            Self::Autodiff(tensor) => tensor.shape(),
325        }
326    }
327
328    fn device(&self) -> DispatchDevice {
329        match self {
330            #[cfg(not(backend_enabled))]
331            Self::Unavailable(never) => never.unreachable(),
332            #[cfg(cube_backend)]
333            DispatchTensorKind::Cube(tensor) => DispatchDevice::Cube(tensor.device()),
334            #[cfg(feature = "flex")]
335            DispatchTensorKind::Flex(tensor) => DispatchDevice::Flex(tensor.device()),
336            #[cfg(feature = "remote")]
337            DispatchTensorKind::Remote(tensor) => DispatchDevice::Remote(tensor.device()),
338            #[cfg(feature = "group")]
339            DispatchTensorKind::Group(tensor) => DispatchDevice::Group(tensor.device()),
340            #[cfg(feature = "capture")]
341            DispatchTensorKind::Capture(tensor) => DispatchDevice::Capture(tensor.device()),
342            #[cfg(feature = "autodiff")]
343            DispatchTensorKind::Autodiff(tensor) => DispatchDevice::autodiff(tensor.device()),
344        }
345    }
346
347    fn can_mut(&self) -> bool {
348        match self {
349            #[cfg(not(backend_enabled))]
350            Self::Unavailable(never) => never.unreachable(),
351            #[cfg(cube_backend)]
352            Self::Cube(tensor) => tensor.can_mut(),
353            #[cfg(feature = "flex")]
354            Self::Flex(tensor) => tensor.can_mut(),
355            #[cfg(feature = "remote")]
356            Self::Remote(tensor) => tensor.can_mut(),
357            #[cfg(feature = "group")]
358            Self::Group(tensor) => tensor.can_mut(),
359            #[cfg(feature = "capture")]
360            Self::Capture(tensor) => tensor.can_mut(),
361            #[cfg(feature = "autodiff")]
362            Self::Autodiff(tensor) => tensor.can_mut(),
363        }
364    }
365}
366
367impl TensorMetadata for DispatchTensor {
368    fn dtype(&self) -> DType {
369        self.kind.dtype()
370    }
371
372    fn shape(&self) -> Shape {
373        self.kind.shape()
374    }
375
376    fn can_mut(&self) -> bool {
377        self.kind.can_mut()
378    }
379
380    type Device = DispatchDevice;
381
382    fn device(&self) -> Self::Device {
383        #[allow(unused_mut)]
384        let mut device = self.kind.device();
385
386        #[cfg(feature = "autodiff")]
387        match (&self.kind, self.autodiff) {
388            (DispatchTensorKind::Autodiff(_), DispatchAutodiffContext::Disabled) => {
389                panic!("an autodiff float primitive must have an enabled autodiff context")
390            }
391            (DispatchTensorKind::Autodiff(_), DispatchAutodiffContext::Enabled(strategy)) => {
392                let DispatchDevice::Autodiff(device) = &mut device else {
393                    unreachable!("autodiff primitive must report an autodiff device")
394                };
395                device.checkpointing = strategy;
396            }
397            (_, DispatchAutodiffContext::Enabled(strategy)) => {
398                if self.dtype().is_float() {
399                    panic!("an enabled float tensor must use an autodiff primitive")
400                }
401                device = DispatchDevice::autodiff(device);
402                let DispatchDevice::Autodiff(device) = &mut device else {
403                    unreachable!()
404                };
405                device.checkpointing = strategy;
406            }
407            (_, DispatchAutodiffContext::Disabled) => {}
408        }
409
410        device
411    }
412}
413
414impl DispatchTensorKind {
415    /// Returns the backend tensor kind name.
416    pub(crate) fn name(&self) -> &'static str {
417        match self {
418            #[cfg(not(backend_enabled))]
419            Self::Unavailable(never) => never.unreachable(),
420            #[cfg(cube_backend)]
421            DispatchTensorKind::Cube(_) => "Cube",
422            #[cfg(feature = "flex")]
423            DispatchTensorKind::Flex(_) => "Flex",
424            #[cfg(feature = "remote")]
425            DispatchTensorKind::Remote(_) => "Remote",
426            #[cfg(feature = "group")]
427            DispatchTensorKind::Group(_) => "Group",
428            #[cfg(feature = "capture")]
429            DispatchTensorKind::Capture(_) => "Capture",
430            #[cfg(feature = "autodiff")]
431            DispatchTensorKind::Autodiff(_) => "Autodiff",
432        }
433    }
434}
435
436#[cfg(feature = "autodiff")]
437trait IntoGradientCheckpointingStrategy {
438    const STRATEGY: GradientCheckpointingStrategy;
439}
440
441#[cfg(feature = "autodiff")]
442impl IntoGradientCheckpointingStrategy for NoCheckpointing {
443    const STRATEGY: GradientCheckpointingStrategy = GradientCheckpointingStrategy::Disabled;
444}
445
446#[cfg(feature = "autodiff")]
447impl IntoGradientCheckpointingStrategy for BalancedCheckpointing {
448    const STRATEGY: GradientCheckpointingStrategy = GradientCheckpointingStrategy::Balanced;
449}
450
451/// Trait to execute runtime routing conversions between the dynamic dispatch layer and specific backends.
452pub trait DispatchKindConversion<B: Backend> {
453    /// Attempts to extract a backend-specific [`BackendTensor`] wrapper from a generic, dynamically-routed [`DispatchTensor`].
454    ///
455    /// # Errors
456    ///
457    /// Returns an error if the dynamic routing state does not match the requested backend `B`.
458    fn try_into_backend(tensor: DispatchTensor) -> Result<BackendTensor<B>, String>;
459
460    /// Encapsulates a backend-specific tensor variant back into a globally routing [`DispatchTensor`].
461    fn from_backend(tensor: BackendTensor<B>) -> DispatchTensor;
462}
463
464macro_rules! impl_dispatch_conversion {
465    ($backend:ident, $cfg:meta) => {
466        #[cfg($cfg)]
467        impl DispatchKindConversion<$backend> for DispatchTensor {
468            fn try_into_backend(tensor: DispatchTensor) -> Result<BackendTensor<$backend>, String> {
469                if tensor.autodiff != DispatchAutodiffContext::Disabled {
470                    return Err(format!(
471                        "Expected concrete {} backend with disabled autodiff context, got {:?}",
472                        stringify!($backend),
473                        tensor.autodiff,
474                    ));
475                }
476                // The catch-all is unreachable in single-backend builds (the enum then has one
477                // variant), but required when several backend features are enabled.
478                #[allow(unreachable_patterns)]
479                match tensor.kind {
480                    DispatchTensorKind::$backend(t) => Ok(t),
481                    other => Err(format!(
482                        "Expected {} tensor, got variant: {}",
483                        stringify!($backend),
484                        other.name()
485                    )),
486                }
487            }
488
489            fn from_backend(tensor: BackendTensor<$backend>) -> DispatchTensor {
490                DispatchTensor {
491                    kind: DispatchTensorKind::$backend(tensor),
492                    autodiff: DispatchAutodiffContext::Disabled,
493                }
494            }
495        }
496
497        #[cfg(all($cfg, feature = "autodiff"))]
498        impl<C: CheckpointStrategy + IntoGradientCheckpointingStrategy>
499            DispatchKindConversion<Autodiff<$backend, C>> for DispatchTensor
500        {
501            fn try_into_backend(
502                tensor: DispatchTensor,
503            ) -> Result<BackendTensor<Autodiff<$backend, C>>, String> {
504                if tensor.autodiff != DispatchAutodiffContext::Enabled(C::STRATEGY) {
505                    return Err(format!(
506                        "Expected {:?} autodiff context, got {:?}",
507                        C::STRATEGY,
508                        tensor.autodiff
509                    ));
510                }
511                match tensor.kind {
512                    DispatchTensorKind::Autodiff(t) => match *t {
513                        DispatchTensorKind::$backend(t) => match t {
514                            // Encode as `BackendTensor::Float` for `Autodiff<B, C>`
515                            BackendTensor::Autodiff(t) => Ok(BackendTensor::Float(t)),
516                            other => Err(format!(
517                                "Expected Autodiff {} float tensor, got Autodiff variant: {}",
518                                stringify!($backend),
519                                other.name()
520                            )),
521                        },
522                        other => Err(format!(
523                            "Expected Autodiff {} tensor, got Autodiff variant: {}",
524                            stringify!($backend),
525                            other.name()
526                        )),
527                    },
528                    DispatchTensorKind::$backend(t) => match t {
529                        BackendTensor::Int(t) => Ok(BackendTensor::Int(t)),
530                        BackendTensor::Bool(t) => Ok(BackendTensor::Bool(t)),
531                        BackendTensor::Quantized(t) => Ok(BackendTensor::Quantized(t)),
532                        BackendTensor::Float(_) => Err(format!(
533                            "Expected Autodiff {} float tensor, got unwrapped float",
534                            stringify!($backend),
535                        )),
536                        BackendTensor::Autodiff(_) => Err(format!(
537                            "Expected Autodiff {} tensor, got invalid inner autodiff variant",
538                            stringify!($backend),
539                        )),
540                    },
541                    #[allow(unreachable_patterns)]
542                    other => Err(format!(
543                        "Expected Autodiff tensor, got backend: {}",
544                        other.name()
545                    )),
546                }
547            }
548
549            fn from_backend(tensor: BackendTensor<Autodiff<$backend, C>>) -> DispatchTensor {
550                // Unwrap the Autodiff backend representation back into the inner hardware representation
551                let kind = match tensor {
552                    // Inverse: Wrap the `Float` variant back into the backend's `Autodiff` primitive variant
553                    BackendTensor::Float(t) => {
554                        let ad_tensor = BackendTensor::Autodiff(t);
555                        // Wrap in the concrete backend's dispatch container
556                        let inner_dispatch = DispatchTensorKind::$backend(ad_tensor);
557                        // Re-apply the outer Autodiff dispatch wrapper
558                        DispatchTensorKind::Autodiff(Box::new(inner_dispatch))
559                    }
560
561                    // Pass-throughs for non-differentiable types
562                    BackendTensor::Int(t) => DispatchTensorKind::$backend(BackendTensor::Int(t)),
563                    BackendTensor::Bool(t) => DispatchTensorKind::$backend(BackendTensor::Bool(t)),
564                    BackendTensor::Quantized(t) => {
565                        DispatchTensorKind::$backend(BackendTensor::Quantized(t))
566                    }
567
568                    BackendTensor::Autodiff(_) => {
569                        panic!("Unexpected Autodiff variant provided to `from_backend`",)
570                    }
571                };
572
573                DispatchTensor {
574                    kind,
575                    autodiff: DispatchAutodiffContext::Enabled(C::STRATEGY),
576                }
577            }
578        }
579    };
580}
581
582// One invocation per dispatch variant. Every cubecl runtime is the same `Cube`
583// backend, so they share the one impl rather than getting seven identical ones.
584impl_dispatch_conversion!(Cube, cube_backend);
585impl_dispatch_conversion!(Flex, feature = "flex");
586impl_dispatch_conversion!(Remote, feature = "remote");
587impl_dispatch_conversion!(Group, feature = "group");
588impl_dispatch_conversion!(Capture, feature = "capture");