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)]
257#[allow(clippy::large_enum_variant)]
260pub enum DispatchTensorKind {
261 #[cfg(not(backend_enabled))]
262 #[doc(hidden)]
263 Unavailable(crate::NoBackend),
264 #[cfg(cube_backend)]
266 Cube(BackendTensor<Cube>),
267
268 #[cfg(feature = "flex")]
270 Flex(BackendTensor<Flex>),
271
272 #[cfg(feature = "remote")]
274 Remote(BackendTensor<Remote>),
275 #[cfg(feature = "capture")]
277 Capture(BackendTensor<Capture>),
278 #[cfg(feature = "group")]
280 Group(BackendTensor<Group>),
281
282 #[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 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
451pub trait DispatchKindConversion<B: Backend> {
453 fn try_into_backend(tensor: DispatchTensor) -> Result<BackendTensor<B>, String>;
459
460 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 #[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 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 let kind = match tensor {
552 BackendTensor::Float(t) => {
554 let ad_tensor = BackendTensor::Autodiff(t);
555 let inner_dispatch = DispatchTensorKind::$backend(ad_tensor);
557 DispatchTensorKind::Autodiff(Box::new(inner_dispatch))
559 }
560
561 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
582impl_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");