burn_backend/backend/base.rs
1use burn_std::DType;
2pub use burn_std::{ExecutionError, backtrace::BackTrace};
3
4use crate::distributed::DistributedOps;
5pub use crate::element::Element;
6use crate::ops::*;
7use crate::tensor::{BoolTensor, FloatTensor, IntTensor, QuantizedTensor};
8use crate::{TensorData, TensorMetadata};
9use alloc::string::String;
10use alloc::vec::Vec;
11use enumset::{EnumSet, EnumSetType};
12
13use crate::distributed::{DistributedParamId, DistributedParams};
14
15use super::DeviceOps;
16use super::profile::profile_unsupported;
17use super::{MemoryPoolUsage, SlicedPoolReport};
18use super::{ProfileDuration, ProfileOptions, ProfileToken, profile_system_time};
19
20/// The mapping of types used by Backend and traits.
21pub trait BackendTypes: Clone + Send + Sync + core::fmt::Debug + 'static {
22 /// Device type.
23 type Device: DeviceOps;
24
25 /// Tensor primitive to be used for all float operations.
26 type FloatTensorPrimitive: TensorMetadata<Device = Self::Device> + 'static;
27
28 /// Tensor primitive to be used for all int operations.
29 type IntTensorPrimitive: TensorMetadata<Device = Self::Device> + 'static;
30
31 /// Tensor primitive to be used for all bool operations.
32 type BoolTensorPrimitive: TensorMetadata<Device = Self::Device> + 'static;
33
34 /// Tensor primitive to be used for all quantized operations.
35 type QuantizedTensorPrimitive: TensorMetadata<Device = Self::Device> + 'static;
36
37 /// Captured graph primitive returned by [`Backend::graph_stop_capture`] and
38 /// consumed by [`Backend::graph_replay`]: a backend-owned recording of a
39 /// launch sequence that replays as a single dispatch.
40 ///
41 /// Backends without graph-capture support use [`GraphUnsupported`], an
42 /// uninhabited type — their capture methods only ever error, so no value of
43 /// it can exist.
44 type GraphPrimitive: Clone + Send + Sync + core::fmt::Debug + 'static;
45}
46
47/// Captured graph primitive type used by the backend (see
48/// [`BackendTypes::GraphPrimitive`]).
49pub type BackendGraph<B> = <B as BackendTypes>::GraphPrimitive;
50
51/// Placeholder [graph primitive](BackendTypes::GraphPrimitive) for backends
52/// without graph-capture support.
53///
54/// Uninhabited: `graph_stop_capture` on such backends always errors, so a value
55/// of this type can never be constructed (and `graph_replay` can never be called).
56#[derive(Debug, Clone, Copy)]
57pub enum GraphUnsupported {}
58
59/// The error returned by the default (unsupported) graph-capture methods.
60fn graph_unsupported() -> ExecutionError {
61 ExecutionError::Generic {
62 reason: alloc::string::String::from("graph capture is not supported by this backend"),
63 backtrace: BackTrace::capture(),
64 }
65}
66
67/// This trait defines all types and functions needed for a backend to be used with burn.
68///
69/// ## Design
70///
71/// This trait aims to be as unopinionated as possible and allows implementations to define
72/// their own types and patterns. Therefore, there are few pre-defined abstractions baked
73/// into this trait.
74///
75/// Backends must define their own tensor types for each data type: `float`, `int`, and `bool`.
76/// Since we minimize assumptions, we chose to separate these types, as they are used in
77/// different contexts. However, some backends may have a generic tensor type that is used
78/// for all data types.
79///
80/// ### Eager Mode
81///
82/// Because burn supports dynamic graphs, the backend trait is designed around kernel
83/// implementations that can be called without any mutable context or graph. This may not be
84/// ideal for backends that want to configure their computational graphs and execute them
85/// multiple times.
86///
87/// To implement this kind of backend, channels could be used to communicate with a backend
88/// server thread to build the computation graphs and re-execute the ones that are repeated,
89/// with some form of cache. Once that pattern has matured, a graph mode backend trait could
90/// be extracted from it, allowing other backends of the same kind to be quickly integrated
91/// with burn. This pattern could also be used to create an operation fusion trait, which
92/// allows backends to define what kind of graph structures can be fused into one operation.
93///
94/// ### Multi-Threaded
95///
96/// Backend tensor types are all `Clone` + `Send`, which allows them to be safely
97/// sent between threads. It is recommended to wrap tensors with [Arc](alloc::sync::Arc),
98/// which avoids copying the tensor's buffer. Note that it is still possible to mutate and
99/// reuse tensors' buffer without locking; see the next section on the Mutable API.
100///
101/// ### Mutable API
102///
103/// There is no mutable or inplace operation API to implement, but that does not mean that
104/// backends cannot support them. Using [try_unwrap](alloc::sync::Arc::try_unwrap) and
105/// [get_mut](alloc::sync::Arc::get_mut) allows backends to have access to an owned or mutable
106/// reference to their tensor buffer data structure if the tensor is not shared. In that case,
107/// backends can dispatch to their owned inplace operations for better performance.
108///
109/// ## Documentation
110///
111/// Most of the documentation for each function can be found on the user API
112#[cfg_attr(doc, doc = crate::doc_tensor!())]
113#[cfg_attr(not(doc), doc = "`Tensor`")]
114/// struct in the `burn-tensor` crate.
115/// For modules, public functions are often created, which can be used by `burn-core` modules.
116pub trait Backend:
117 BackendTypes
118 + FloatTensorOps<Self>
119 + BoolTensorOps<Self>
120 + IntTensorOps<Self>
121 + ModuleOps<Self>
122 + ActivationOps<Self>
123 + QTensorOps<Self>
124 + TransactionOps<Self>
125 + DistributedOps<Self>
126 + Clone
127 + Default
128 + Sized
129 + Send
130 + Sync
131 + core::fmt::Debug
132 + 'static
133{
134 /// If autodiff is enabled.
135 fn ad_enabled(_device: &Self::Device) -> bool {
136 false
137 }
138
139 /// Sets the current allocation mode to persistent.
140 #[allow(unused_variables)]
141 fn memory_persistent_allocations<
142 Output: Send,
143 Input: Send,
144 Func: Fn(Input) -> Output + Send,
145 >(
146 device: &Self::Device,
147 input: Input,
148 func: Func,
149 ) -> Output {
150 func(input)
151 }
152
153 /// Manually triggers a memory cleanup on the given device.
154 #[allow(unused_variables)]
155 fn memory_cleanup(device: &Self::Device) {}
156
157 /// The dynamic pools' measured state, in the order allocations are routed
158 /// through them. `None` on a backend that does not report one, or whose
159 /// stream has failed.
160 ///
161 /// One entry per pool that carves pages, the pools a growth left behind
162 /// last. Pools of other kinds — an allocation's own page, the metadata
163 /// churn — are left out.
164 #[allow(unused_variables)]
165 fn memory_pool_report(device: &Self::Device) -> Option<Vec<SlicedPoolReport>> {
166 None
167 }
168
169 /// The device allocator's current state. `None` on a backend that does not
170 /// report one, or whose stream has failed.
171 #[allow(unused_variables)]
172 fn memory_pool_usage(device: &Self::Device) -> Option<MemoryPoolUsage> {
173 None
174 }
175
176 /// Name of the backend.
177 fn name(device: &Self::Device) -> String;
178
179 /// Seeds the backend on the specified device.
180 ///
181 /// There is no guarantee that only the specified device will be seeded, but it is guaranteed
182 /// that at least the specified device will be seeded.
183 ///
184 /// In all cases, this should ensure deterministic execution for a single-threaded program.
185 fn seed(device: &Self::Device, seed: u64);
186
187 /// Sync the backend, ensure that all computation are finished.
188 fn sync(_device: &Self::Device) -> Result<(), ExecutionError> {
189 Ok(())
190 }
191
192 /// Measure how long the device spends on the work `func` puts on the
193 /// calling stream, in device time.
194 ///
195 /// The window opens where the stream is when the call is made and closes
196 /// where the stream is when `func` returns: work the stream still owed
197 /// from before falls in, and work a backend queues past the end (a
198 /// batching backend's last operations, unless `options` flush) falls out.
199 /// Nothing is waited on — the [`ProfileDuration`] resolves later, when
200 /// the device has stamped both ends — so windows nest without the inner
201 /// ones being charged to the outer. Work on other streams is not kept
202 /// out, and not counted. A window that nothing ran in reads as no time.
203 ///
204 /// The default is [`profile_system_time`]: wall-clock time between two
205 /// syncs, for a backend with no device clock to read. That one does wait,
206 /// and an inner window's syncs are charged to the outer.
207 ///
208 /// # Errors
209 ///
210 /// The device refused to open or close the window, or work inside it
211 /// failed and took the measurement with it. `func` has run by then — a
212 /// window that could not be opened does not cancel the work it was asked
213 /// to measure — and its output is lost with the error, as it would be on
214 /// the read that the failure surfaces on without a window.
215 ///
216 /// **A failure that the device only reports later is not here.** The
217 /// measurement is resolved after this returns, so anything the device
218 /// learns in between — and everything a *remote* server reports, which
219 /// travels back with the measurement rather than ahead of it — arrives as
220 /// a window that resolves to no measurement, with the reason in the log.
221 /// A caller that must distinguish "nothing ran" from "the server failed"
222 /// cannot do it from the `Result` alone.
223 fn profile<O: Send + 'static>(
224 device: &Self::Device,
225 options: ProfileOptions,
226 func: impl FnOnce() -> O + Send,
227 ) -> Result<(O, ProfileDuration), ExecutionError> {
228 let _ = options;
229 profile_system_time::<Self, O>(device, func)
230 }
231
232 /// Open a [profiling window](Self::profile) at the calling stream's
233 /// current position, to be closed with
234 /// [`profile_end`](Self::profile_end) from the same stream.
235 ///
236 /// For a caller that cannot bracket the work in a closure: a backend that
237 /// forwards operations to be executed on another thread opens and closes
238 /// the window from that thread, in order with the operations.
239 ///
240 /// `None` from a backend that opens no windows and measures only with
241 /// [`profile`](Self::profile) — the default — so the caller can bracket
242 /// with [`profile_system_time`] instead.
243 fn profile_start(_device: &Self::Device) -> Result<Option<ProfileToken>, ExecutionError> {
244 Ok(None)
245 }
246
247 /// Close the window `token` at the calling stream's current position.
248 ///
249 /// When `options` flush, the work the backend still holds queued for the
250 /// stream executes first, so it falls inside the window. A backend that
251 /// forwards the close passes `options` along, so a queue further down
252 /// the chain — a remote server's fusion, say — is flushed too.
253 ///
254 /// Errors on a backend whose [`profile_start`](Self::profile_start) hands
255 /// out no token.
256 fn profile_end(
257 _device: &Self::Device,
258 _token: ProfileToken,
259 _options: ProfileOptions,
260 ) -> Result<ProfileDuration, ExecutionError> {
261 Err(profile_unsupported())
262 }
263
264 /// Drop the window `token` opened without measuring it, for a caller that
265 /// will never reach [`profile_end`](Self::profile_end).
266 ///
267 /// **An open window is not free**, and the cost is not paid once: a
268 /// backend holds a start event, keeps timestamp writes on, or retains
269 /// command buffers for as long as one is open, and on wgpu every later
270 /// pass keeps rewriting the live window's end slot. So a window whose
271 /// caller unwound between the two calls is abandoned rather than left,
272 /// which is what [`profile_with_tokens`](crate::profile_with_tokens) does
273 /// on the panic path.
274 ///
275 /// Cannot fail and answers nothing: it is called while a panic is already
276 /// unwinding, where there is nobody left to tell. The default closes the
277 /// window and discards the measurement, which every backend can already
278 /// do; one that can drop a window without recording an end does that
279 /// instead.
280 fn profile_abandon(device: &Self::Device, token: ProfileToken) {
281 let _ = Self::profile_end(device, token, ProfileOptions::default());
282 }
283
284 /// Prepare `device` for an upcoming graph capture: route allocations into a
285 /// stable pool so every buffer allocated before graph_stop_capture can
286 /// be pinned. Call before the warmup run. No-op by default.
287 ///
288 /// See [`burn_graph`](crate) — the closure-based `capture` helper drives
289 /// this whole sequence.
290 fn graph_prepare(_device: &Self::Device) -> Result<(), ExecutionError> {
291 Ok(())
292 }
293
294 /// Begin recording launches on `device` into a graph (see
295 /// [`graph_stop_capture`](Backend::graph_stop_capture)). Errors on backends
296 /// without hardware graph support, so callers fall back to re-running.
297 fn graph_start_capture(_device: &Self::Device) -> Result<(), ExecutionError> {
298 Err(graph_unsupported())
299 }
300
301 /// Stop recording and return the captured [graph](BackendTypes::GraphPrimitive),
302 /// ready to [`graph_replay`](Backend::graph_replay).
303 fn graph_stop_capture(_device: &Self::Device) -> Result<BackendGraph<Self>, ExecutionError> {
304 Err(graph_unsupported())
305 }
306
307 /// Replay a captured [graph](BackendTypes::GraphPrimitive) — one dispatch
308 /// re-running the recorded launches against their original buffers.
309 ///
310 /// # Safety
311 ///
312 /// The replay dispatches raw device work against the exact buffers recorded
313 /// at capture time, with nothing tracking whether those buffers are still
314 /// valid. The caller must guarantee, for every tensor the captured closure
315 /// read or wrote:
316 ///
317 /// - its buffer is still alive — no tensor referenced by the graph has been
318 /// freed (and its memory possibly reallocated) since capture;
319 /// - it is not concurrently read or written by work on another stream or
320 /// thread while the replay executes;
321 /// - input refreshes and output reads are issued on the stream the graph
322 /// was captured on, so they order correctly against the replay.
323 unsafe fn graph_replay(
324 _device: &Self::Device,
325 _graph: &BackendGraph<Self>,
326 ) -> Result<(), ExecutionError> {
327 Err(graph_unsupported())
328 }
329
330 /// Flush any pending operation of the backend.
331 ///
332 /// # Errors
333 ///
334 /// Returns an [`ExecutionError`] when the pending operations cannot be dispatched, e.g. on
335 /// a device that is poisoned.
336 fn flush(_device: &Self::Device) -> Result<(), ExecutionError>;
337
338 /// Marks the given data as being used as a staging buffer for transfer between CPU and
339 /// accelerators like GPUs.
340 ///
341 /// The given data might be transferred to pinned memory or another format to improve data transfer
342 /// speed.
343 fn staging<'a, Iter>(_data: Iter, _device: &Self::Device)
344 where
345 Iter: Iterator<Item = &'a mut TensorData>,
346 {
347 }
348
349 /// Whether the type is fully supported by the specified device for general operations.
350 ///
351 /// A type is considered supported if it can be used for the full suite of tensor
352 /// operations, including storage, conversion, and basic arithmetic.
353 ///
354 /// Returning `false` does not necessarily mean the device cannot handle the type at all.
355 /// For instance, a device might support a type only for specialized hardware
356 /// acceleration (e.g., matrix multiplication) but lack general arithmetic support. Such
357 /// types should return `false` here as they are not globally supported.
358 fn supports_dtype(device: &Self::Device, dtype: DType) -> bool {
359 Self::dtype_usage(device, dtype).is_superset(DTypeUsage::general())
360 }
361
362 /// Returns the [DTypeUsageSet] for the given [DType] on the specified device.
363 fn dtype_usage(device: &Self::Device, dtype: DType) -> DTypeUsageSet;
364
365 /// Returns the number of devices available on this backend.
366 /// `device` is a reference device used to determine the underlying backend that should be queried.
367 /// A CUDA device will return all devices available to CUDA, a Vulkan device will return all
368 /// devices available to Vulkan, etc.
369 fn device_count(type_id: u16) -> usize;
370}
371
372/// Trait that allows a backend to support autodiff.
373pub trait AutodiffBackend: Backend {
374 /// The inner backend type.
375 type InnerBackend: Backend<Device = Self::Device>;
376
377 /// Gradients type.
378 type Gradients: Send;
379
380 /// Backward pass.
381 ///
382 /// # Arguments
383 ///
384 /// * `tensor` - The tensor is the last node of computational graph where the gradients are computed.
385 ///
386 /// # Returns
387 ///
388 /// The gradients.
389 fn backward(tensor: FloatTensor<Self>) -> Self::Gradients;
390
391 /// Returns the gradients of a tensor.
392 ///
393 /// # Arguments
394 ///
395 /// * `tensor` - The tensor to extract the gradients from.
396 ///
397 /// # Returns
398 ///
399 /// An optional tensor containing the gradient.
400 fn grad(
401 tensor: &FloatTensor<Self>,
402 grads: &Self::Gradients,
403 ) -> Option<FloatTensor<Self::InnerBackend>>;
404
405 /// Pops the gradients of a tensor and returns them.
406 ///
407 /// # Arguments
408 ///
409 /// * `tensor` - The tensor to pop the gradients from.
410 /// * `grads` - The gradients.
411 ///
412 /// # Returns
413 ///
414 /// An optional tensor containing the given gradients.
415 fn grad_remove(
416 tensor: &FloatTensor<Self>,
417 grads: &mut Self::Gradients,
418 ) -> Option<FloatTensor<Self::InnerBackend>>;
419
420 /// Replace the gradients of a tensor with the one provided.
421 ///
422 /// If no gradient existed for the provided tensor, register it.
423 ///
424 /// # Arguments
425 ///
426 /// * `tensor` - The tensor to pop the gradients from.
427 /// * `grads` - The gradients.
428 /// * `grad` - The updated grad tensor.
429 fn grad_replace(
430 tensor: &FloatTensor<Self>,
431 grads: &mut Self::Gradients,
432 grad: FloatTensor<Self::InnerBackend>,
433 );
434
435 /// Returns the tensor with inner backend type.
436 ///
437 /// # Arguments
438 ///
439 /// * `tensor` - The tensor to get the inner backend tensor for.
440 ///
441 /// # Returns
442 ///
443 /// The inner backend tensor.
444 fn inner(tensor: FloatTensor<Self>) -> FloatTensor<Self::InnerBackend>;
445
446 /// Returns the tensor with inner backend type.
447 ///
448 /// # Arguments
449 ///
450 /// * `tensor` - The tensor to get the inner backend tensor for.
451 ///
452 /// # Returns
453 ///
454 /// The inner backend tensor.
455 fn int_inner(tensor: IntTensor<Self>) -> IntTensor<Self::InnerBackend>;
456
457 /// Returns the tensor with inner backend type.
458 ///
459 /// # Arguments
460 ///
461 /// * `tensor` - The tensor to get the inner backend tensor for.
462 ///
463 /// # Returns
464 ///
465 /// The inner backend tensor.
466 fn bool_inner(tensor: BoolTensor<Self>) -> BoolTensor<Self::InnerBackend>;
467
468 /// Returns the tensor with inner backend type.
469 ///
470 /// # Arguments
471 ///
472 /// * `tensor` - The tensor to get the inner backend tensor for.
473 ///
474 /// # Returns
475 ///
476 /// The inner backend tensor.
477 fn q_inner(tensor: QuantizedTensor<Self>) -> QuantizedTensor<Self::InnerBackend>;
478
479 /// Converts the inner backend tensor to the autodiff backend tensor.
480 ///
481 /// # Arguments
482 ///
483 /// * `tensor` - The inner backend tensor to convert.
484 ///
485 ///
486 /// # Returns
487 ///
488 /// The autodiff backend tensor.
489 fn from_inner(tensor: FloatTensor<Self::InnerBackend>) -> FloatTensor<Self>;
490
491 /// Converts the inner backend tensor to the autodiff backend tensor.
492 ///
493 /// # Arguments
494 ///
495 /// * `tensor` - The inner backend tensor to convert.
496 ///
497 ///
498 /// # Returns
499 ///
500 /// The autodiff backend tensor.
501 fn int_from_inner(tensor: IntTensor<Self::InnerBackend>) -> IntTensor<Self>;
502
503 /// Converts the inner backend tensor to the autodiff backend tensor.
504 ///
505 /// # Arguments
506 ///
507 /// * `tensor` - The inner backend tensor to convert.
508 ///
509 ///
510 /// # Returns
511 ///
512 /// The autodiff backend tensor.
513 fn bool_from_inner(tensor: BoolTensor<Self::InnerBackend>) -> BoolTensor<Self>;
514
515 /// Converts the inner backend tensor to the autodiff backend tensor.
516 ///
517 /// # Arguments
518 ///
519 /// * `tensor` - The inner backend tensor to convert.
520 ///
521 ///
522 /// # Returns
523 ///
524 /// The autodiff backend tensor.
525 fn q_from_inner(tensor: QuantizedTensor<Self::InnerBackend>) -> QuantizedTensor<Self>;
526
527 /// Mark the tensor as distributed across multiple devices.
528 /// The gradients will be aggregated during the backward pass.
529 ///
530 /// This function does nothing when distributed training is not available.
531 fn set_distributed_params(
532 tensor: FloatTensor<Self>,
533 _param_id: DistributedParamId,
534 ) -> FloatTensor<Self> {
535 tensor
536 }
537
538 /// Returns the distributed parameters if the tensor was marked as distributed.
539 fn distributed_params(_tensor: &FloatTensor<Self>) -> Option<DistributedParams> {
540 None
541 }
542
543 /// Returns true if the tensor was marked as distributed.
544 fn is_distributed(_tensor: &FloatTensor<Self>) -> bool {
545 false
546 }
547}
548
549/// Describes how a data type can be used on a given device.
550///
551/// A data type may be supported for different classes of operations. Not all
552/// data types that appear in hardware or kernel implementations are suitable
553/// for general-purpose tensor operations.
554#[derive(Debug, EnumSetType)]
555pub enum DTypeUsage {
556 /// The type can be stored in device memory and converted to and from
557 /// other supported data types.
558 Storage,
559 /// The type supports general-purpose arithmetic and common tensor
560 /// operations (e.g. elementwise ops, reductions, etc.).
561 Arithmetic,
562 /// The type is supported by hardware-accelerated execution paths.
563 ///
564 /// This typically indicates support for accelerator-backed compute units (e.g., tensor
565 /// cores executing MMA instructions) for high-performance operations such as matrix
566 /// multiplication and operations that lower to it.
567 ///
568 /// # Notes
569 /// - A type can be both [`Arithmetic`](DTypeUsage::Arithmetic) and
570 /// [`Accelerated`](DTypeUsage::Accelerated) if it supports general-purpose operations
571 /// *and* accelerated paths.
572 /// - If a type is marked as `Accelerated` but not `Arithmetic`, it is not
573 /// suitable for general-purpose tensor operations and may only be used
574 /// in specific accelerated operations.
575 ///
576 /// `Accelerated` is a **flag**, not a detailed descriptor. It does not enumerate which
577 /// operations are accelerated or which accelerator features are available.
578 Accelerated,
579}
580
581/// A set of [DTypeUsage] representing the total capabilities of a data type on a device.
582pub type DTypeUsageSet = EnumSet<DTypeUsage>;
583
584impl DTypeUsage {
585 /// Returns the usage set required for general-purpose tensor support.
586 pub fn general() -> DTypeUsageSet {
587 DTypeUsage::Storage | DTypeUsage::Arithmetic
588 }
589}