Skip to main content

tenferro_runtime/
lib.rs

1//! Traced graph runtime and extension dispatch infrastructure for tenferro.
2//!
3//! This crate owns graph construction, lowering to execution IR, graph
4//! execution, and backend-parametric extension runtime dispatch. Standard
5//! operations are lowered through the runtime's internal operation vocabulary;
6//! tensor storage and backend kernels live in `tenferro-tensor`.
7//!
8//! Use this crate directly when you want concrete tensor helpers or reusable
9//! traced graph execution without depending on `tenferro-ad`. Start with
10//! [`TypedTensor`] when the scalar type is fixed in Rust, [`Tensor`] when dtype
11//! is selected at runtime, and [`TracedTensor`] plus [`GraphCompiler`] and
12//! [`Runtime`] when the same expression should be compiled once and run
13//! repeatedly. Operation-family crates such as `tenferro-einsum`,
14//! `tenferro-linalg`, and `tenferro-fft` register extension runtimes through
15//! runtime engine registrations when compiled execution reaches those
16//! operations.
17//!
18//! User-facing guides live at
19//! <https://tensor4all.org/tenferro-rs/guides/choosing-an-api.html> and
20//! <https://tensor4all.org/tenferro-rs/guides/execution-models.html>.
21//!
22//! # Examples
23//!
24//! ```rust
25//! use tenferro_runtime::{GraphCompiler, Runtime, TracedTensor};
26//! use tenferro_cpu::CpuBackend;
27//!
28//! let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
29//! let y = (&x + &x).unwrap();
30//! let mut compiler = GraphCompiler::new();
31//! let program = compiler.compile(&y).unwrap();
32//! let backend = CpuBackend::default();
33//! let mut builder = Runtime::builder();
34//! builder.register_engine(tenferro_cpu::runtime_engine_registration(&backend).unwrap()).unwrap();
35//! let runtime = builder.build().unwrap();
36//! let out = runtime.run_compiled(&program, &[]).unwrap().pop().unwrap();
37//! assert_eq!(out.as_slice::<f64>().unwrap(), &[2.0, 4.0]);
38//! ```
39
40#[doc(hidden)]
41pub mod ad_support;
42mod checkpoint;
43mod compiler;
44pub mod error;
45mod exec;
46pub mod extension;
47pub mod extension_cache;
48mod extension_execution_context;
49pub mod graph;
50mod metadata;
51pub mod program;
52pub mod runtime;
53#[doc(hidden)]
54pub mod scalar_semantics;
55mod segment;
56mod shape_constraint;
57mod shape_infer;
58mod shape_packing;
59pub mod sym_dim;
60mod tensor;
61mod trace;
62pub mod traced;
63mod typed_tensor;
64
65pub use compiler::{CompilerOptions, OptimizerConfig};
66pub use error::{ContextId, Error, ErrorPhase, Result, ShapeConstraintEvalError};
67pub use extension_cache::{
68    ExtensionCacheKey, ExtensionCacheLimits, ExtensionCacheSelector, ExtensionCacheStore,
69};
70pub use extension_execution_context::ExtensionExecutionContext;
71pub use graph::{CompiledGraph, GraphCompiler};
72pub use runtime::{
73    assemble_executable_engine_registration, assemble_preparation_only_engine_registration,
74    CacheInFlightBehavior, CacheOwnerError, CacheOwnerFailure, CacheOwnerId, CoreCapabilityBundle,
75    CoreCapabilityBundleBuilder, CoreCapabilityKind, CorePrepareContext, Determinism,
76    DotGeneralPreparation, DotGeneralPrepareRequest, ElementwisePrepareRequest, ElementwiseRuntime,
77    EngineExecutionContractError, EngineId, EngineRegistration, EngineRegistrationMetadata,
78    EngineSnapshotView, ErasedExecutionContext, EventDomainDriver, EventDomainError, EventDomainId,
79    EventDomainOperation, EventDomainRun, EventToken, ExecutableEngineRegistrationConfig,
80    ExecutionContextIdentity, ExecutionContextMismatch, ExecutionHandle, ExecutionPolicy,
81    ExecutionPolicyError, ExtensionEngine, ExtensionModule, ExtensionModuleError,
82    ExtensionModuleId, ExtensionModuleRegistrar, ExtensionPlanningConfig, ExtensionPrepareRequest,
83    HardwareClassId, IdentityError, IdentityKind, ImmediateEventDomainDriver,
84    IndexingPrepareRequest, IndexingRuntime, InputIngressContract, InputIngressContractError,
85    InputPlacementContract, InputSignature, InputSignatureContract, InputSignatureEntry,
86    InputSignatureError, InputSpecializationProjection, InputSpecializationRequirements,
87    InputSpecializationRequirementsBuilder, InputSpecializationRequirementsError, LayoutClass,
88    LayoutPrepareRequest, LayoutProjection, LayoutRuntime, LayoutSpecialization,
89    PlacementConstraintError, PlacementProjection, PlacementSpecialization, PreparationKeySummary,
90    PreparationOnlyEngineRegistrationConfig, PrepareCapability, PrepareError, PrepareOptions,
91    PrepareOptionsKey, PreparedCompiledGraph, PreparedOperation, PreparedOperationBinding,
92    PreparedOperationExecutor, PreparedOperationExecutorHandle, PreparedOperationHandle,
93    PreparedOperationPlan, PreparedPlanCacheLimits, PreparedPlanCacheStats,
94    ProgramPlacementConstraint, ProviderContractError, ProviderDeviceIdentity, ProviderId,
95    RankRequirement, ReductionPrepareRequest, ReductionRuntime, RegistrationIdentity,
96    RegistrationKey, ResidentOutputContract, ResolvedPlanningConfig, ResolvedPlanningKey,
97    ResolvedProgramPlacement, Runtime, RuntimeCacheError, RuntimeCacheOwner, RuntimeCacheStats,
98    RuntimeConfigBuilder, RuntimeConfigError, RuntimeConfigSnapshot, RuntimeEpoch, RuntimeId,
99    RuntimeInputContract, RuntimeReconfiguration, RuntimeReconfigureError, RuntimeStateError,
100    SpecializationError, SpecializationProjection, SpecializationRequirements, StorageClass,
101    SubmissionError, TransferEndpoint, TransferError, TransferProvider,
102    TransferProviderContractError, TransferRequest, UnsupportedReason,
103};
104#[doc(hidden)]
105pub use shape_constraint::ShapeGuard;
106pub use shape_packing::TracedSliceBuilder;
107pub use sym_dim::SymDim;
108pub use tenferro_ops::ShapeRelation;
109pub use tenferro_tensor::{
110    BackendSessionHost, CacheStats, CompareDir, DType, DotGeneralConfig, GatherConfig, MemoryKind,
111    PadConfig, ScatterConfig, SliceConfig, Tensor, TensorBackend, TensorRead, TensorScalar,
112    TensorValue, TensorView, TypedTensor, TypedTensorView,
113};
114pub use trace::{TraceContext, TraceValue, TracedGraph};
115
116/// Backend-explicit concrete tensor operations.
117///
118/// `Tensor` is owned by `tenferro-tensor`, so `tenferro-runtime` exposes these
119/// operations as a crate-root extension trait rather than as inherent methods.
120///
121/// # Public API rationale
122///
123/// This trait is intentionally public: it is the supported non-AD concrete
124/// tensor operation surface for downstream users who want to run operations on
125/// an explicit backend. The old public module/free-function surface was
126/// removed; the private `tensor` module now contains implementation helpers
127/// only and must not be treated as a compatibility API.
128///
129/// # Examples
130///
131/// ```rust
132/// use tenferro_cpu::CpuBackend;
133/// use tenferro_runtime::{Tensor, TensorOpsExt};
134///
135/// let mut backend = CpuBackend::new();
136/// let a = Tensor::from_vec_col_major(vec![2, 2], vec![1.0_f64; 4]).unwrap();
137/// let b = Tensor::from_vec_col_major(vec![2, 2], vec![2.0_f64; 4]).unwrap();
138/// let c = a.matmul(&b, &mut backend).unwrap();
139/// assert_eq!(c.shape(), &[2, 2]);
140/// ```
141pub trait TensorOpsExt {
142    /// Convert to a different dtype using the checked conversion lattice.
143    ///
144    /// # Errors
145    ///
146    /// Returns [`tenferro_tensor::Error::UnsupportedDTypeConversion`] when the
147    /// conversion is outside the checked lattice,
148    /// [`tenferro_tensor::Error::Validation`] with `DTypeMismatch` or
149    /// `InvalidArgument` for invalid tensor metadata, or
150    /// [`tenferro_tensor::Error::BackendSource`] when the backend reports a
151    /// typed failure.
152    fn convert<B: TensorBackend>(
153        &self,
154        to: DType,
155        backend: &mut B,
156    ) -> tenferro_tensor::Result<Tensor>;
157    /// Cast to a different dtype using explicit lossy projection.
158    ///
159    /// # Errors
160    ///
161    /// Returns [`tenferro_tensor::Error::UnsupportedDTypeConversion`] when the
162    /// requested cast is unsupported, [`tenferro_tensor::Error::Validation`]
163    /// with `DTypeMismatch` or `InvalidArgument` for invalid tensor metadata,
164    /// or [`tenferro_tensor::Error::BackendSource`] for a typed backend
165    /// failure.
166    fn cast<B: TensorBackend>(&self, to: DType, backend: &mut B)
167        -> tenferro_tensor::Result<Tensor>;
168    /// Elementwise addition with NumPy-style broadcasting.
169    ///
170    /// # Errors
171    ///
172    /// Returns [`tenferro_tensor::Error::Validation`] with a
173    /// [`ShapeMismatch`](tenferro_tensor::ValidationError::ShapeMismatch) or
174    /// `DTypeMismatch` payload when operands are incompatible, or
175    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
176    fn add<B: TensorBackend>(
177        &self,
178        rhs: &Tensor,
179        backend: &mut B,
180    ) -> tenferro_tensor::Result<Tensor>;
181    /// Elementwise subtraction with NumPy-style broadcasting.
182    ///
183    /// # Errors
184    ///
185    /// Returns [`tenferro_tensor::Error::Validation`] with
186    /// `ShapeMismatch` or `DTypeMismatch` for incompatible operands, or
187    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
188    fn sub<B: TensorBackend>(
189        &self,
190        rhs: &Tensor,
191        backend: &mut B,
192    ) -> tenferro_tensor::Result<Tensor>;
193    /// Elementwise multiplication with NumPy-style broadcasting.
194    ///
195    /// # Errors
196    ///
197    /// Returns [`tenferro_tensor::Error::Validation`] with
198    /// `ShapeMismatch` or `DTypeMismatch` for incompatible operands, or
199    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
200    fn mul<B: TensorBackend>(
201        &self,
202        rhs: &Tensor,
203        backend: &mut B,
204    ) -> tenferro_tensor::Result<Tensor>;
205    /// Elementwise division with NumPy-style broadcasting.
206    ///
207    /// # Errors
208    ///
209    /// Returns [`tenferro_tensor::Error::Validation`] with `ShapeMismatch` or
210    /// `DTypeMismatch` for shape/dtype incompatibility,
211    /// [`tenferro_tensor::Error::Extension`] with a numerical classification
212    /// for a detected zero divisor, or
213    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
214    fn div<B: TensorBackend>(
215        &self,
216        rhs: &Tensor,
217        backend: &mut B,
218    ) -> tenferro_tensor::Result<Tensor>;
219    /// Elementwise remainder with NumPy-style broadcasting.
220    ///
221    /// # Errors
222    ///
223    /// Returns [`tenferro_tensor::Error::Validation`] with `ShapeMismatch` or
224    /// `DTypeMismatch` for shape/dtype incompatibility, a numerical
225    /// [`tenferro_tensor::Error::Extension`] for a detected zero divisor, or
226    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
227    fn rem<B: TensorBackend>(
228        &self,
229        rhs: &Tensor,
230        backend: &mut B,
231    ) -> tenferro_tensor::Result<Tensor>;
232    /// Elementwise power with NumPy-style broadcasting.
233    ///
234    /// # Errors
235    ///
236    /// Returns [`tenferro_tensor::Error::Validation`] with `ShapeMismatch` or
237    /// `DTypeMismatch` for incompatible metadata, a numerical
238    /// [`tenferro_tensor::Error::Extension`] for a detected negative integer
239    /// exponent, or [`tenferro_tensor::Error::BackendSource`] for a typed
240    /// backend failure.
241    fn pow<B: TensorBackend>(
242        &self,
243        rhs: &Tensor,
244        backend: &mut B,
245    ) -> tenferro_tensor::Result<Tensor>;
246    /// Elementwise maximum with NumPy-style broadcasting.
247    ///
248    /// # Errors
249    ///
250    /// Returns [`tenferro_tensor::Error::Validation`] with
251    /// `ShapeMismatch` or `DTypeMismatch` for incompatible operands, or
252    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
253    fn maximum<B: TensorBackend>(
254        &self,
255        rhs: &Tensor,
256        backend: &mut B,
257    ) -> tenferro_tensor::Result<Tensor>;
258    /// Elementwise minimum with NumPy-style broadcasting.
259    ///
260    /// # Errors
261    ///
262    /// Returns [`tenferro_tensor::Error::Validation`] with
263    /// `ShapeMismatch` or `DTypeMismatch` for incompatible operands, or
264    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
265    fn minimum<B: TensorBackend>(
266        &self,
267        rhs: &Tensor,
268        backend: &mut B,
269    ) -> tenferro_tensor::Result<Tensor>;
270    /// Elementwise negation.
271    ///
272    /// # Errors
273    ///
274    /// Returns [`tenferro_tensor::Error::Unsupported`] when the dtype is not
275    /// supported by the operation, or [`tenferro_tensor::Error::BackendSource`]
276    /// for a typed backend failure.
277    fn neg<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<Tensor>;
278    /// Elementwise absolute value.
279    ///
280    /// # Errors
281    ///
282    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
283    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
284    /// failure.
285    fn abs<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<Tensor>;
286    /// Elementwise sign.
287    ///
288    /// # Errors
289    ///
290    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
291    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
292    /// failure.
293    fn sign<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<Tensor>;
294    /// Elementwise complex conjugate.
295    ///
296    /// # Errors
297    ///
298    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
299    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
300    /// failure.
301    fn conj<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<Tensor>;
302    /// Elementwise exponential.
303    ///
304    /// # Errors
305    ///
306    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
307    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
308    /// failure.
309    fn exp<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<Tensor>;
310    /// Elementwise natural logarithm.
311    ///
312    /// # Errors
313    ///
314    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
315    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
316    /// failure.
317    fn log<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<Tensor>;
318    /// Elementwise sine.
319    ///
320    /// # Errors
321    ///
322    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
323    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
324    /// failure.
325    fn sin<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<Tensor>;
326    /// Elementwise cosine.
327    ///
328    /// # Errors
329    ///
330    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
331    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
332    /// failure.
333    fn cos<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<Tensor>;
334    /// Elementwise hyperbolic tangent.
335    ///
336    /// # Errors
337    ///
338    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
339    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
340    /// failure.
341    fn tanh<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<Tensor>;
342    /// Elementwise square root.
343    ///
344    /// # Errors
345    ///
346    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
347    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
348    /// failure.
349    fn sqrt<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<Tensor>;
350    /// Elementwise reciprocal square root.
351    ///
352    /// # Errors
353    ///
354    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
355    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
356    /// failure.
357    fn rsqrt<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<Tensor>;
358    /// Elementwise `exp(x) - 1`.
359    ///
360    /// # Errors
361    ///
362    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
363    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
364    /// failure.
365    fn expm1<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<Tensor>;
366    /// Elementwise `log(1 + x)`.
367    ///
368    /// # Errors
369    ///
370    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
371    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
372    /// failure.
373    fn log1p<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<Tensor>;
374    /// Elementwise comparison with NumPy-style broadcasting.
375    ///
376    /// # Errors
377    ///
378    /// Returns [`tenferro_tensor::Error::Validation`] with `ShapeMismatch` or
379    /// `DTypeMismatch` for incompatible shape/dtype metadata, or
380    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
381    fn compare<B: TensorBackend>(
382        &self,
383        rhs: &Tensor,
384        dir: CompareDir,
385        backend: &mut B,
386    ) -> tenferro_tensor::Result<Tensor>;
387    /// Select values from `on_true` or `on_false` using this tensor as condition.
388    ///
389    /// # Errors
390    ///
391    /// Returns [`tenferro_tensor::Error::Validation`] with `ShapeMismatch` or
392    /// `DTypeMismatch` when the condition and branches are incompatible, or
393    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
394    fn where_select<B: TensorBackend>(
395        &self,
396        on_true: &Tensor,
397        on_false: &Tensor,
398        backend: &mut B,
399    ) -> tenferro_tensor::Result<Tensor>;
400    /// Clamp values elementwise between lower and upper bounds.
401    ///
402    /// # Errors
403    ///
404    /// Returns [`tenferro_tensor::Error::Validation`] with `ShapeMismatch` or
405    /// `DTypeMismatch` when bounds are incompatible with the input, or
406    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
407    fn clamp<B: TensorBackend>(
408        &self,
409        lower: &Tensor,
410        upper: &Tensor,
411        backend: &mut B,
412    ) -> tenferro_tensor::Result<Tensor>;
413    /// Rank-2 matrix multiplication.
414    ///
415    /// # Errors
416    ///
417    /// Returns [`tenferro_tensor::Error::Validation`] with `RankMismatch`,
418    /// `ShapeMismatch`, or `DTypeMismatch` for incompatible matrices, or
419    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
420    fn matmul<B: TensorBackend>(
421        &self,
422        rhs: &Tensor,
423        backend: &mut B,
424    ) -> tenferro_tensor::Result<Tensor>;
425    /// Reshape without changing element order.
426    ///
427    /// # Errors
428    ///
429    /// Returns [`tenferro_tensor::Error::Validation`] with
430    /// `ShapeMismatch`, `RankMismatch`, or `InvalidArgument` when element
431    /// counts or ranks are invalid, or
432    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
433    fn reshape<B: TensorBackend>(
434        &self,
435        shape: &[usize],
436        backend: &mut B,
437    ) -> tenferro_tensor::Result<Tensor>;
438    /// Permute axes.
439    ///
440    /// # Errors
441    ///
442    /// Returns [`tenferro_tensor::Error::Validation`] with
443    /// `InvalidPermutationLength`, `AxisOutOfBounds`, or `DuplicateAxis` for
444    /// an invalid permutation, or
445    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
446    fn transpose<B: TensorBackend>(
447        &self,
448        perm: &[usize],
449        backend: &mut B,
450    ) -> tenferro_tensor::Result<Tensor>;
451    /// Sum over one or more axes.
452    ///
453    /// # Errors
454    ///
455    /// Returns [`tenferro_tensor::Error::Validation`] with `AxisOutOfBounds`
456    /// or `DuplicateAxis` for invalid reductions, or
457    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
458    fn reduce_sum<B: TensorBackend>(
459        &self,
460        axes: &[usize],
461        backend: &mut B,
462    ) -> tenferro_tensor::Result<Tensor>;
463}
464
465/// Backend-explicit operations for dynamic-rank typed tensors.
466///
467/// `TypedTensor` is owned by `tenferro-tensor`, so `tenferro-runtime` exposes
468/// these operations as a crate-root extension trait rather than as inherent
469/// methods.
470///
471/// # Public API rationale
472///
473/// This trait is intentionally public for the same reason as [`TensorOpsExt`]:
474/// downstream users need a supported backend-explicit typed tensor surface, and
475/// `tenferro-runtime` cannot add inherent methods to a type owned by
476/// `tenferro-tensor`. The private `typed_tensor` module is implementation
477/// detail, not a retained module/free-function API.
478///
479/// # Examples
480///
481/// ```rust
482/// use tenferro_cpu::CpuBackend;
483/// use tenferro_runtime::{TypedTensor, TypedTensorOpsExt};
484///
485/// let mut backend = CpuBackend::new();
486/// let x = TypedTensor::<f64>::from_vec_col_major(vec![2], vec![1.0, 2.0]).unwrap();
487/// let y = TypedTensor::<f64>::from_vec_col_major(vec![2], vec![3.0, 4.0]).unwrap();
488/// let sum = x.add(&y, &mut backend).unwrap();
489/// assert_eq!(sum.host_data().unwrap(), &[4.0, 6.0]);
490/// ```
491pub trait TypedTensorOpsExt<T: TensorScalar> {
492    /// Elementwise addition with NumPy-style broadcasting.
493    ///
494    /// # Errors
495    ///
496    /// Returns [`tenferro_tensor::Error::Validation`] with `ShapeMismatch` for
497    /// incompatible operands, or [`tenferro_tensor::Error::BackendSource`] for
498    /// a typed backend failure.
499    fn add<B: TensorBackend>(
500        &self,
501        rhs: &TypedTensor<T>,
502        backend: &mut B,
503    ) -> tenferro_tensor::Result<TypedTensor<T>>;
504    /// Elementwise subtraction with NumPy-style broadcasting.
505    ///
506    /// # Errors
507    ///
508    /// Returns [`tenferro_tensor::Error::Validation`] with `ShapeMismatch` for
509    /// incompatible operands, or [`tenferro_tensor::Error::BackendSource`] for
510    /// a typed backend failure.
511    fn sub<B: TensorBackend>(
512        &self,
513        rhs: &TypedTensor<T>,
514        backend: &mut B,
515    ) -> tenferro_tensor::Result<TypedTensor<T>>;
516    /// Elementwise multiplication with NumPy-style broadcasting.
517    ///
518    /// # Errors
519    ///
520    /// Returns [`tenferro_tensor::Error::Validation`] with `ShapeMismatch` for
521    /// incompatible operands, or [`tenferro_tensor::Error::BackendSource`] for
522    /// a typed backend failure.
523    fn mul<B: TensorBackend>(
524        &self,
525        rhs: &TypedTensor<T>,
526        backend: &mut B,
527    ) -> tenferro_tensor::Result<TypedTensor<T>>;
528    /// Elementwise division with NumPy-style broadcasting.
529    ///
530    /// # Errors
531    ///
532    /// Returns [`tenferro_tensor::Error::Validation`] with `ShapeMismatch` for
533    /// incompatible shapes, a numerical [`tenferro_tensor::Error::Extension`]
534    /// for a detected zero divisor, or [`tenferro_tensor::Error::BackendSource`]
535    /// for a typed backend failure.
536    fn div<B: TensorBackend>(
537        &self,
538        rhs: &TypedTensor<T>,
539        backend: &mut B,
540    ) -> tenferro_tensor::Result<TypedTensor<T>>;
541    /// Elementwise remainder with NumPy-style broadcasting.
542    ///
543    /// # Errors
544    ///
545    /// Returns [`tenferro_tensor::Error::Validation`] with `ShapeMismatch` for
546    /// incompatible shapes, a numerical [`tenferro_tensor::Error::Extension`]
547    /// for a detected zero divisor, or [`tenferro_tensor::Error::BackendSource`]
548    /// for a typed backend failure.
549    fn rem<B: TensorBackend>(
550        &self,
551        rhs: &TypedTensor<T>,
552        backend: &mut B,
553    ) -> tenferro_tensor::Result<TypedTensor<T>>;
554    /// Elementwise power with NumPy-style broadcasting.
555    ///
556    /// # Errors
557    ///
558    /// Returns [`tenferro_tensor::Error::Validation`] with `ShapeMismatch` for
559    /// incompatible shapes, a numerical [`tenferro_tensor::Error::Extension`]
560    /// for a detected negative integer exponent, or
561    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
562    fn pow<B: TensorBackend>(
563        &self,
564        rhs: &TypedTensor<T>,
565        backend: &mut B,
566    ) -> tenferro_tensor::Result<TypedTensor<T>>;
567    /// Elementwise maximum with NumPy-style broadcasting.
568    ///
569    /// # Errors
570    ///
571    /// Returns [`tenferro_tensor::Error::Validation`] with `ShapeMismatch` for
572    /// incompatible operands, or [`tenferro_tensor::Error::BackendSource`] for
573    /// a typed backend failure.
574    fn maximum<B: TensorBackend>(
575        &self,
576        rhs: &TypedTensor<T>,
577        backend: &mut B,
578    ) -> tenferro_tensor::Result<TypedTensor<T>>;
579    /// Elementwise minimum with NumPy-style broadcasting.
580    ///
581    /// # Errors
582    ///
583    /// Returns [`tenferro_tensor::Error::Validation`] with `ShapeMismatch` for
584    /// incompatible operands, or [`tenferro_tensor::Error::BackendSource`] for
585    /// a typed backend failure.
586    fn minimum<B: TensorBackend>(
587        &self,
588        rhs: &TypedTensor<T>,
589        backend: &mut B,
590    ) -> tenferro_tensor::Result<TypedTensor<T>>;
591    /// Elementwise negation.
592    ///
593    /// # Errors
594    ///
595    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
596    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
597    /// failure.
598    fn neg<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<TypedTensor<T>>;
599    /// Elementwise absolute value.
600    ///
601    /// # Errors
602    ///
603    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
604    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
605    /// failure.
606    fn abs<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<TypedTensor<T>>;
607    /// Elementwise sign.
608    ///
609    /// # Errors
610    ///
611    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
612    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
613    /// failure.
614    fn sign<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<TypedTensor<T>>;
615    /// Elementwise complex conjugate.
616    ///
617    /// # Errors
618    ///
619    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
620    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
621    /// failure.
622    fn conj<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<TypedTensor<T>>;
623    /// Elementwise exponential.
624    ///
625    /// # Errors
626    ///
627    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
628    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
629    /// failure.
630    fn exp<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<TypedTensor<T>>;
631    /// Elementwise natural logarithm.
632    ///
633    /// # Errors
634    ///
635    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
636    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
637    /// failure.
638    fn log<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<TypedTensor<T>>;
639    /// Elementwise sine.
640    ///
641    /// # Errors
642    ///
643    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
644    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
645    /// failure.
646    fn sin<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<TypedTensor<T>>;
647    /// Elementwise cosine.
648    ///
649    /// # Errors
650    ///
651    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
652    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
653    /// failure.
654    fn cos<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<TypedTensor<T>>;
655    /// Elementwise hyperbolic tangent.
656    ///
657    /// # Errors
658    ///
659    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
660    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
661    /// failure.
662    fn tanh<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<TypedTensor<T>>;
663    /// Elementwise square root.
664    ///
665    /// # Errors
666    ///
667    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
668    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
669    /// failure.
670    fn sqrt<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<TypedTensor<T>>;
671    /// Elementwise reciprocal square root.
672    ///
673    /// # Errors
674    ///
675    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
676    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
677    /// failure.
678    fn rsqrt<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<TypedTensor<T>>;
679    /// Elementwise `exp(x) - 1`.
680    ///
681    /// # Errors
682    ///
683    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
684    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
685    /// failure.
686    fn expm1<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<TypedTensor<T>>;
687    /// Elementwise `log(1 + x)`.
688    ///
689    /// # Errors
690    ///
691    /// Returns [`tenferro_tensor::Error::Unsupported`] for an unsupported
692    /// dtype or [`tenferro_tensor::Error::BackendSource`] for a typed backend
693    /// failure.
694    fn log1p<B: TensorBackend>(&self, backend: &mut B) -> tenferro_tensor::Result<TypedTensor<T>>;
695    /// Elementwise comparison with NumPy-style broadcasting.
696    ///
697    /// # Errors
698    ///
699    /// Returns [`tenferro_tensor::Error::Validation`] with
700    /// `ShapeMismatch::IncompatibleShapes` when broadcasting the operands is
701    /// impossible, or [`tenferro_tensor::Error::BackendSource`] for a typed
702    /// backend failure.
703    fn compare<B: TensorBackend>(
704        &self,
705        rhs: &TypedTensor<T>,
706        dir: CompareDir,
707        backend: &mut B,
708    ) -> tenferro_tensor::Result<TypedTensor<bool>>;
709    /// Clamp values elementwise between lower and upper bounds.
710    ///
711    /// # Errors
712    ///
713    /// Returns [`tenferro_tensor::Error::Validation`] with
714    /// `ShapeMismatch::IncompatibleShapes` when a bound cannot broadcast to
715    /// the input, or [`tenferro_tensor::Error::BackendSource`] for a typed
716    /// backend failure.
717    fn clamp<B: TensorBackend>(
718        &self,
719        lower: &TypedTensor<T>,
720        upper: &TypedTensor<T>,
721        backend: &mut B,
722    ) -> tenferro_tensor::Result<TypedTensor<T>>;
723    /// Rank-2 matrix multiplication.
724    ///
725    /// # Errors
726    ///
727    /// Returns [`tenferro_tensor::Error::Validation`] with `RankMismatch` when
728    /// either operand is not rank two or `ShapeMismatch::ContractedDimensions`
729    /// when the inner dimensions differ, or
730    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
731    fn matmul<B: TensorBackend>(
732        &self,
733        rhs: &TypedTensor<T>,
734        backend: &mut B,
735    ) -> tenferro_tensor::Result<TypedTensor<T>>;
736    /// Sum over one or more axes.
737    ///
738    /// # Errors
739    ///
740    /// Returns [`tenferro_tensor::Error::Validation`] with `AxisOutOfBounds`
741    /// for an axis outside the input rank or `DuplicateAxis` when `axes`
742    /// repeats an axis, or [`tenferro_tensor::Error::BackendSource`] for a
743    /// typed backend failure.
744    fn reduce_sum<B: TensorBackend>(
745        &self,
746        axes: &[usize],
747        backend: &mut B,
748    ) -> tenferro_tensor::Result<TypedTensor<T>>;
749    /// Reshape through the backend structural operation.
750    ///
751    /// # Errors
752    ///
753    /// Returns [`tenferro_tensor::Error::Validation`] with
754    /// `ShapeMismatch::ReshapeElementCount` when the element counts differ,
755    /// `IntegerOverflow` when shape arithmetic overflows, or
756    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
757    fn reshape<B: TensorBackend>(
758        &self,
759        shape: &[usize],
760        backend: &mut B,
761    ) -> tenferro_tensor::Result<TypedTensor<T>>;
762    /// Permute axes through the backend structural operation.
763    ///
764    /// # Errors
765    ///
766    /// Returns [`tenferro_tensor::Error::Validation`] with
767    /// `InvalidPermutationLength` when `perm` has the wrong length,
768    /// `AxisOutOfBounds` for an invalid axis, or `DuplicateAxis` for a
769    /// repeated axis, or [`tenferro_tensor::Error::BackendSource`] for a typed
770    /// backend failure.
771    fn transpose<B: TensorBackend>(
772        &self,
773        perm: &[usize],
774        backend: &mut B,
775    ) -> tenferro_tensor::Result<TypedTensor<T>>;
776    /// Broadcast into a larger shape.
777    ///
778    /// # Errors
779    ///
780    /// Returns [`tenferro_tensor::Error::Validation`] with `RankMismatch` when
781    /// `dims` does not match the input rank, `AxisOutOfBounds` or
782    /// `DuplicateAxis` for an invalid mapping, or
783    /// `ShapeMismatch::IncompatibleShapes` when known dimensions cannot
784    /// broadcast. [`tenferro_tensor::Error::BackendSource`] reports a typed
785    /// backend failure.
786    fn broadcast_in_dim<B: TensorBackend>(
787        &self,
788        shape: &[usize],
789        dims: &[usize],
790        backend: &mut B,
791    ) -> tenferro_tensor::Result<TypedTensor<T>>;
792}
793
794/// Backend-explicit bool-mask operations for typed tensors.
795///
796/// # Public API rationale
797///
798/// This trait keeps `where_select` available as a method on bool
799/// `TypedTensor`s while preserving the crate-root extension-trait surface. It
800/// is public because downstream users call it directly; the implementation
801/// helper in the private `typed_tensor` module is not a compatibility API.
802pub trait TypedTensorMaskOpsExt {
803    /// Select typed values using this bool tensor as condition.
804    ///
805    /// # Errors
806    ///
807    /// Returns [`tenferro_tensor::Error::Validation`] with
808    /// `ShapeMismatch::IncompatibleShapes` when the condition or either branch
809    /// cannot broadcast to the other operands, or
810    /// [`tenferro_tensor::Error::BackendSource`] for a typed backend failure.
811    fn where_select<T: TensorScalar, B: TensorBackend>(
812        &self,
813        on_true: &TypedTensor<T>,
814        on_false: &TypedTensor<T>,
815        backend: &mut B,
816    ) -> tenferro_tensor::Result<TypedTensor<T>>;
817}
818
819pub use traced::TracedTensor;