Skip to main content

tensor4all_tensorbackend/
lib.rs

1#![warn(missing_docs)]
2//! Tensor storage and linear algebra backend for tensor4all.
3//!
4//! [`CpuExecutionContext`] is the canonical CPU integration path. It requires a
5//! caller-supplied [`CpuBackend`] and owns plain, graph, and eager-AD runtime state.
6//!
7//! ## Feature flags
8//!
9//! - `explicit-context`: explicit CPU execution and logical tensor transfer.
10//! - `global-defaults`: legacy process-global tensor operations.
11//! - `backend-tenferro` (default): compatibility alias for `global-defaults`.
12
13#[cfg(feature = "global-defaults")]
14/// Dynamic scalar types supporting f32, f64, Complex32, and Complex64.
15mod any_scalar;
16#[cfg(feature = "global-defaults")]
17/// Backend dispatch for dense linear algebra operations.
18mod backend;
19#[cfg(feature = "explicit-context")]
20/// Explicit and optional process-global tenferro execution helpers.
21mod context;
22#[cfg(feature = "tenferro-cuda")]
23/// Explicit visible-ordinal-0 CUDA execution and transfer boundaries.
24mod cuda;
25#[cfg(feature = "explicit-context")]
26/// Einsum label helpers shared by both frontends.
27mod einsum_ids;
28#[cfg(feature = "explicit-context")]
29/// Opt-in explicit/concrete execution frontend (issue #859 B1).
30pub mod explicit;
31#[cfg(feature = "global-defaults")]
32/// Incremental QR state for successive randomized compression.
33mod incremental_qr;
34#[cfg(feature = "explicit-context")]
35/// Backend-free tensor snapshots for execution-domain transfer.
36mod logical_tensor;
37#[cfg(feature = "global-defaults")]
38/// Dense column-major matrix type and backend-backed matrix utilities.
39mod matrix;
40#[cfg(feature = "global-defaults")]
41/// Process-level memory pressure helpers.
42mod memory;
43#[cfg(feature = "global-defaults")]
44/// Tensor snapshot storage types and low-level dense/diagonal kernels.
45mod storage;
46#[cfg(feature = "global-defaults")]
47pub(crate) mod tenferro_bridge;
48#[cfg(feature = "global-defaults")]
49/// Supported public tensor element types and native constructor hooks.
50mod tensor_element;
51
52#[cfg(feature = "global-defaults")]
53pub use any_scalar::BackendScalar;
54#[cfg(feature = "global-defaults")]
55pub use backend::{
56    full_piv_lu_backend, full_piv_lu_matrix, full_piv_lu_matrix_in, full_piv_lu_matrix_owned,
57    qr_backend, qr_backend_in, solve_backend, solve_matrix, solve_matrix_in, solve_matrix_owned,
58    src_error_estimate, src_error_estimate_general, svd_backend, svd_backend_in,
59    triangular_solve_backend, triangular_solve_matrix, triangular_solve_matrix_in,
60    triangular_solve_matrix_owned, BackendLinalgError, BackendLinalgScalar, FullPivLuMatrixResult,
61    FullPivLuResult, FullPivLuScalar, MatrixSolveScalar, MatrixTriangularSolveScalar,
62    SrcErrorEstimate, SvdResult,
63};
64#[cfg(feature = "global-defaults")]
65pub use context::{
66    default_cpu_execution_context, default_eager_ctx, with_default_backend, with_runtime_engine,
67    EagerContextError, ExecutionContextEntryError,
68};
69#[cfg(feature = "explicit-context")]
70pub use context::{
71    set_default_cpu_threads, AlreadyInitialized, CpuBackend, CpuExecutionContext,
72    CpuExecutionContextError, CpuThreadError, ExecutionContext,
73};
74#[cfg(feature = "tenferro-cuda")]
75pub use cuda::{
76    CudaExecutionContext, CudaExecutionContextError, CudaPinnedBuffer, PendingCudaDownload,
77    PendingCudaUpload, CUDA_ORDINAL,
78};
79#[cfg(feature = "global-defaults")]
80pub use incremental_qr::{IncrementalQr, IncrementalQrScalar};
81#[cfg(feature = "explicit-context")]
82pub use logical_tensor::{LogicalTensor, LogicalTensorData, LogicalTensorError};
83#[cfg(feature = "global-defaults")]
84pub use matrix::{
85    batched_mat_mul_same_shape, batched_mat_mul_same_shape_owned, from_vec2d,
86    hermitian_eigendecomposition, hermitian_exponential_first_column, lowest_hermitian_eigenpair,
87    mat_mul, mat_mul_in, mat_mul_owned, submatrix, submatrix_argmax, swap_cols, swap_rows,
88    transpose, try_from_vec2d, BlasMul, HermitianEigenError, HermitianEigenScalar,
89    HermitianEigendecomposition, HermitianEigenpair, Matrix, MatrixMulError, MatrixScalar,
90    MatrixShapeError, MatrixTensorConversionError,
91};
92#[cfg(feature = "global-defaults")]
93pub use memory::{release_process_allocator_cached_memory, AllocatorPressureRelief};
94#[cfg(feature = "global-defaults")]
95pub use storage::{
96    contract_storage, make_mut_storage, min_dim, scale_target_dtype, NonfiniteFlags, Storage,
97    StorageError, StorageKind, StorageResult, StorageScalar, StructuredStorage, SumFromStorage,
98};
99#[cfg(feature = "global-defaults")]
100pub use tenferro_bridge::{
101    axpby_native_tensor, axpby_storage_native, conj_native_tensor, contract_native_tensor,
102    contract_storage_native, dense_native_tensor_from_col_major,
103    dense_native_tensor_from_col_major_owned, dense_native_tensor_read_input_from_col_major,
104    diag_native_tensor_from_col_major, einsum_native_subscripts, einsum_native_tensor_reads,
105    einsum_native_tensors, einsum_native_tensors_owned, native_tensor_primal_to_dense_col_major,
106    native_tensor_primal_to_diag, native_tensor_primal_to_storage, outer_product_native_tensor,
107    outer_product_storage_native, permute_native_tensor, permute_storage_native,
108    print_and_reset_native_einsum_profile, qr_native_tensor, reset_native_einsum_profile,
109    reshape_col_major_native_tensor, scale_native_tensor, scale_storage_native,
110    storage_from_payload_native, storage_payload_native, storage_payload_native_read_input,
111    storage_to_native_tensor, sum_native_tensor, svd_native_tensor, tangent_native_tensor,
112    BridgeError, NativeTensorReadInput,
113};
114#[cfg(feature = "global-defaults")]
115pub use tensor_element::TensorElement;
116
117/// Report a violated internal invariant that no public input can reach.
118///
119/// This is the only sanctioned `panic!` in production code. Use it only for
120/// (a) an internal invariant — a state no public input can reach — or (b) the
121/// documented `# Panics` precondition of an infallible standard-trait
122/// implementation that cannot return `Result`, such as an out-of-range
123/// [`Index`](std::ops::Index)/[`IndexMut`](std::ops::IndexMut). Never use it
124/// for user-reachable invalid input of a function that can return `Result`;
125/// return a crate-local typed error instead.
126///
127/// `context` names the invariant and `error` carries the underlying
128/// diagnostic, so the panic message is `"{context}: {error}"`. The library
129/// panic audit allowlists this single `panic!` and reports every call site, so
130/// invariant panics stay visible.
131///
132/// # Panics
133///
134/// Always panics and never returns.
135///
136/// # Examples
137///
138/// ```
139/// use tensor4all_tensorbackend::invariant_violated;
140///
141/// let payload = std::panic::catch_unwind(|| {
142///     invariant_violated("rank mismatch", "expected 2 rows");
143/// })
144/// .unwrap_err();
145/// let message = payload
146///     .downcast_ref::<String>()
147///     .expect("panic payload is a formatted string");
148/// assert_eq!(message, "rank mismatch: expected 2 rows");
149/// ```
150#[doc(hidden)]
151#[track_caller]
152pub fn invariant_violated(context: &str, error: impl std::fmt::Display) -> ! {
153    panic!("{context}: {error}")
154}
155
156#[cfg(all(test, feature = "global-defaults"))]
157mod tests;