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#[derive(Clone, Debug)]
22pub enum BackendTensor<B: BackendTypes> {
23 Float(B::FloatTensorPrimitive),
25 Int(B::IntTensorPrimitive),
27 Bool(B::BoolTensorPrimitive),
29 Quantized(B::QuantizedTensorPrimitive),
31 #[cfg(feature = "autodiff")]
32 Autodiff(FloatTensor<Autodiff<B>>),
34}
35
36impl<B: Backend> BackendTensor<B> {
37 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 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 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 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 pub fn quantized(self) -> B::QuantizedTensorPrimitive {
86 match self {
87 BackendTensor::Quantized(tensor) => tensor,
88 _ => unreachable!(),
89 }
90 }
91
92 #[cfg(feature = "autodiff")]
93 pub fn autodiff(self) -> FloatTensor<Autodiff<B>> {
95 match self {
96 BackendTensor::Autodiff(tensor) => tensor,
97 _ => unreachable!(),
99 }
100 }
101
102 #[cfg(feature = "autodiff")]
103 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 pub fn autodiff_inner(self) -> B::FloatTensorPrimitive {
114 match self {
115 BackendTensor::Autodiff(tensor) => tensor.into_primitive(),
116 _ => unreachable!(),
117 }
118 }
119
120 #[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 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
207pub enum DispatchAutodiffContext {
208 #[default]
210 Disabled,
211 Enabled(GradientCheckpointingStrategy),
213}
214
215impl DispatchAutodiffContext {
216 #[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#[derive(Clone, Debug)]
242pub struct DispatchTensor {
243 pub kind: DispatchTensorKind,
245 pub autodiff: DispatchAutodiffContext,
247}
248
249#[derive(Clone, Debug)]
257pub enum DispatchTensorKind {
258 #[cfg(not(backend_enabled))]
259 #[doc(hidden)]
260 Unavailable(crate::NoBackend),
261 #[cfg(cube_backend)]
263 Cube(BackendTensor<Cube>),
264
265 #[cfg(feature = "flex")]
267 Flex(BackendTensor<Flex>),
268
269 #[cfg(feature = "ndarray")]
271 NdArray(BackendTensor<NdArray>),
272
273 #[cfg(feature = "tch")]
275 LibTorch(BackendTensor<LibTorch>),
276
277 #[cfg(feature = "remote")]
279 Remote(BackendTensor<Remote>),
280 #[cfg(feature = "capture")]
282 Capture(BackendTensor<Capture>),
283
284 #[cfg(feature = "autodiff")]
286 Autodiff(Box<DispatchTensorKind>),
287}
288
289impl TensorMetadata for DispatchTensorKind {
290 type Device = DispatchDevice;
291
292 fn dtype(&self) -> DType {
293 match self {
294 #[cfg(not(backend_enabled))]
295 Self::Unavailable(never) => never.unreachable(),
296 #[cfg(cube_backend)]
297 Self::Cube(tensor) => tensor.dtype(),
298 #[cfg(feature = "flex")]
299 Self::Flex(tensor) => tensor.dtype(),
300 #[cfg(feature = "ndarray")]
301 Self::NdArray(tensor) => tensor.dtype(),
302 #[cfg(feature = "tch")]
303 Self::LibTorch(tensor) => tensor.dtype(),
304 #[cfg(feature = "remote")]
305 Self::Remote(tensor) => tensor.dtype(),
306 #[cfg(feature = "capture")]
307 Self::Capture(tensor) => tensor.dtype(),
308 #[cfg(feature = "autodiff")]
309 Self::Autodiff(tensor) => tensor.dtype(),
310 }
311 }
312
313 fn shape(&self) -> Shape {
314 match self {
315 #[cfg(not(backend_enabled))]
316 Self::Unavailable(never) => never.unreachable(),
317 #[cfg(cube_backend)]
318 Self::Cube(tensor) => tensor.shape(),
319 #[cfg(feature = "flex")]
320 Self::Flex(tensor) => tensor.shape(),
321 #[cfg(feature = "ndarray")]
322 Self::NdArray(tensor) => tensor.shape(),
323 #[cfg(feature = "tch")]
324 Self::LibTorch(tensor) => tensor.shape(),
325 #[cfg(feature = "remote")]
326 Self::Remote(tensor) => tensor.shape(),
327 #[cfg(feature = "capture")]
328 Self::Capture(tensor) => tensor.shape(),
329 #[cfg(feature = "autodiff")]
330 Self::Autodiff(tensor) => tensor.shape(),
331 }
332 }
333
334 fn device(&self) -> DispatchDevice {
335 match self {
336 #[cfg(not(backend_enabled))]
337 Self::Unavailable(never) => never.unreachable(),
338 #[cfg(cube_backend)]
339 DispatchTensorKind::Cube(tensor) => DispatchDevice::Cube(tensor.device()),
340 #[cfg(feature = "flex")]
341 DispatchTensorKind::Flex(tensor) => DispatchDevice::Flex(tensor.device()),
342 #[cfg(feature = "ndarray")]
343 DispatchTensorKind::NdArray(tensor) => DispatchDevice::NdArray(tensor.device()),
344 #[cfg(feature = "tch")]
345 DispatchTensorKind::LibTorch(tensor) => DispatchDevice::LibTorch(tensor.device()),
346 #[cfg(feature = "remote")]
347 DispatchTensorKind::Remote(tensor) => DispatchDevice::Remote(tensor.device()),
348 #[cfg(feature = "capture")]
349 DispatchTensorKind::Capture(tensor) => DispatchDevice::Capture(tensor.device()),
350 #[cfg(feature = "autodiff")]
351 DispatchTensorKind::Autodiff(tensor) => DispatchDevice::autodiff(tensor.device()),
352 }
353 }
354
355 fn can_mut(&self) -> bool {
356 match self {
357 #[cfg(not(backend_enabled))]
358 Self::Unavailable(never) => never.unreachable(),
359 #[cfg(cube_backend)]
360 Self::Cube(tensor) => tensor.can_mut(),
361 #[cfg(feature = "flex")]
362 Self::Flex(tensor) => tensor.can_mut(),
363 #[cfg(feature = "ndarray")]
364 Self::NdArray(tensor) => tensor.can_mut(),
365 #[cfg(feature = "tch")]
366 Self::LibTorch(tensor) => tensor.can_mut(),
367 #[cfg(feature = "remote")]
368 Self::Remote(tensor) => tensor.can_mut(),
369 #[cfg(feature = "capture")]
370 Self::Capture(tensor) => tensor.can_mut(),
371 #[cfg(feature = "autodiff")]
372 Self::Autodiff(tensor) => tensor.can_mut(),
373 }
374 }
375}
376
377impl TensorMetadata for DispatchTensor {
378 fn dtype(&self) -> DType {
379 self.kind.dtype()
380 }
381
382 fn shape(&self) -> Shape {
383 self.kind.shape()
384 }
385
386 fn can_mut(&self) -> bool {
387 self.kind.can_mut()
388 }
389
390 type Device = DispatchDevice;
391
392 fn device(&self) -> Self::Device {
393 #[allow(unused_mut)]
394 let mut device = self.kind.device();
395
396 #[cfg(feature = "autodiff")]
397 match (&self.kind, self.autodiff) {
398 (DispatchTensorKind::Autodiff(_), DispatchAutodiffContext::Disabled) => {
399 panic!("an autodiff float primitive must have an enabled autodiff context")
400 }
401 (DispatchTensorKind::Autodiff(_), DispatchAutodiffContext::Enabled(strategy)) => {
402 let DispatchDevice::Autodiff(device) = &mut device else {
403 unreachable!("autodiff primitive must report an autodiff device")
404 };
405 device.checkpointing = strategy;
406 }
407 (_, DispatchAutodiffContext::Enabled(strategy)) => {
408 if self.dtype().is_float() {
409 panic!("an enabled float tensor must use an autodiff primitive")
410 }
411 device = DispatchDevice::autodiff(device);
412 let DispatchDevice::Autodiff(device) = &mut device else {
413 unreachable!()
414 };
415 device.checkpointing = strategy;
416 }
417 (_, DispatchAutodiffContext::Disabled) => {}
418 }
419
420 device
421 }
422}
423
424impl DispatchTensorKind {
425 pub(crate) fn name(&self) -> &'static str {
427 match self {
428 #[cfg(not(backend_enabled))]
429 Self::Unavailable(never) => never.unreachable(),
430 #[cfg(cube_backend)]
431 DispatchTensorKind::Cube(_) => "Cube",
432 #[cfg(feature = "flex")]
433 DispatchTensorKind::Flex(_) => "Flex",
434 #[cfg(feature = "ndarray")]
435 DispatchTensorKind::NdArray(_) => "NdArray",
436 #[cfg(feature = "tch")]
437 DispatchTensorKind::LibTorch(_) => "LibTorch",
438 #[cfg(feature = "remote")]
439 DispatchTensorKind::Remote(_) => "Remote",
440 #[cfg(feature = "capture")]
441 DispatchTensorKind::Capture(_) => "Capture",
442 #[cfg(feature = "autodiff")]
443 DispatchTensorKind::Autodiff(_) => "Autodiff",
444 }
445 }
446}
447
448#[cfg(feature = "autodiff")]
449trait IntoGradientCheckpointingStrategy {
450 const STRATEGY: GradientCheckpointingStrategy;
451}
452
453#[cfg(feature = "autodiff")]
454impl IntoGradientCheckpointingStrategy for NoCheckpointing {
455 const STRATEGY: GradientCheckpointingStrategy = GradientCheckpointingStrategy::Disabled;
456}
457
458#[cfg(feature = "autodiff")]
459impl IntoGradientCheckpointingStrategy for BalancedCheckpointing {
460 const STRATEGY: GradientCheckpointingStrategy = GradientCheckpointingStrategy::Balanced;
461}
462
463pub trait DispatchKindConversion<B: Backend> {
465 fn try_into_backend(tensor: DispatchTensor) -> Result<BackendTensor<B>, String>;
471
472 fn from_backend(tensor: BackendTensor<B>) -> DispatchTensor;
474}
475
476macro_rules! impl_dispatch_conversion {
477 ($backend:ident, $cfg:meta) => {
478 #[cfg($cfg)]
479 impl DispatchKindConversion<$backend> for DispatchTensor {
480 fn try_into_backend(tensor: DispatchTensor) -> Result<BackendTensor<$backend>, String> {
481 if tensor.autodiff != DispatchAutodiffContext::Disabled {
482 return Err(format!(
483 "Expected concrete {} backend with disabled autodiff context, got {:?}",
484 stringify!($backend),
485 tensor.autodiff,
486 ));
487 }
488 #[allow(unreachable_patterns)]
491 match tensor.kind {
492 DispatchTensorKind::$backend(t) => Ok(t),
493 other => Err(format!(
494 "Expected {} tensor, got variant: {}",
495 stringify!($backend),
496 other.name()
497 )),
498 }
499 }
500
501 fn from_backend(tensor: BackendTensor<$backend>) -> DispatchTensor {
502 DispatchTensor {
503 kind: DispatchTensorKind::$backend(tensor),
504 autodiff: DispatchAutodiffContext::Disabled,
505 }
506 }
507 }
508
509 #[cfg(all($cfg, feature = "autodiff"))]
510 impl<C: CheckpointStrategy + IntoGradientCheckpointingStrategy>
511 DispatchKindConversion<Autodiff<$backend, C>> for DispatchTensor
512 {
513 fn try_into_backend(
514 tensor: DispatchTensor,
515 ) -> Result<BackendTensor<Autodiff<$backend, C>>, String> {
516 if tensor.autodiff != DispatchAutodiffContext::Enabled(C::STRATEGY) {
517 return Err(format!(
518 "Expected {:?} autodiff context, got {:?}",
519 C::STRATEGY,
520 tensor.autodiff
521 ));
522 }
523 match tensor.kind {
524 DispatchTensorKind::Autodiff(t) => match *t {
525 DispatchTensorKind::$backend(t) => match t {
526 BackendTensor::Autodiff(t) => Ok(BackendTensor::Float(t)),
528 other => Err(format!(
529 "Expected Autodiff {} float tensor, got Autodiff variant: {}",
530 stringify!($backend),
531 other.name()
532 )),
533 },
534 other => Err(format!(
535 "Expected Autodiff {} tensor, got Autodiff variant: {}",
536 stringify!($backend),
537 other.name()
538 )),
539 },
540 DispatchTensorKind::$backend(t) => match t {
541 BackendTensor::Int(t) => Ok(BackendTensor::Int(t)),
542 BackendTensor::Bool(t) => Ok(BackendTensor::Bool(t)),
543 BackendTensor::Quantized(t) => Ok(BackendTensor::Quantized(t)),
544 BackendTensor::Float(_) => Err(format!(
545 "Expected Autodiff {} float tensor, got unwrapped float",
546 stringify!($backend),
547 )),
548 BackendTensor::Autodiff(_) => Err(format!(
549 "Expected Autodiff {} tensor, got invalid inner autodiff variant",
550 stringify!($backend),
551 )),
552 },
553 #[allow(unreachable_patterns)]
554 other => Err(format!(
555 "Expected Autodiff tensor, got backend: {}",
556 other.name()
557 )),
558 }
559 }
560
561 fn from_backend(tensor: BackendTensor<Autodiff<$backend, C>>) -> DispatchTensor {
562 let kind = match tensor {
564 BackendTensor::Float(t) => {
566 let ad_tensor = BackendTensor::Autodiff(t);
567 let inner_dispatch = DispatchTensorKind::$backend(ad_tensor);
569 DispatchTensorKind::Autodiff(Box::new(inner_dispatch))
571 }
572
573 BackendTensor::Int(t) => DispatchTensorKind::$backend(BackendTensor::Int(t)),
575 BackendTensor::Bool(t) => DispatchTensorKind::$backend(BackendTensor::Bool(t)),
576 BackendTensor::Quantized(t) => {
577 DispatchTensorKind::$backend(BackendTensor::Quantized(t))
578 }
579
580 BackendTensor::Autodiff(_) => {
581 panic!("Unexpected Autodiff variant provided to `from_backend`",)
582 }
583 };
584
585 DispatchTensor {
586 kind,
587 autodiff: DispatchAutodiffContext::Enabled(C::STRATEGY),
588 }
589 }
590 }
591 };
592}
593
594impl_dispatch_conversion!(Cube, cube_backend);
597impl_dispatch_conversion!(Flex, feature = "flex");
598impl_dispatch_conversion!(Remote, feature = "remote");
599impl_dispatch_conversion!(Capture, feature = "capture");
600impl_dispatch_conversion!(NdArray, feature = "ndarray");
601impl_dispatch_conversion!(LibTorch, feature = "tch");