tenferro_runtime/traced.rs
1use std::collections::HashMap;
2use std::error::Error as StdError;
3use std::fmt;
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::sync::Arc;
6
7use computegraph::graph::{Graph, GraphBuilder};
8use computegraph::types::{OperationRole, ValueKey, ValueRef};
9use computegraph::LocalValueId;
10use num_complex::{Complex32, Complex64};
11use tenferro_ops::ad::context::GlobalMetadataScope;
12use tenferro_ops::broadcast::{
13 broadcast_error_to_validation, broadcast_in_dim_extent_error, broadcast_input_plan,
14 broadcast_shape, broadcast_shapes, BroadcastError,
15};
16use tenferro_ops::dim_expr::DimExpr;
17use tenferro_ops::input_key::TensorInputKey;
18use tenferro_ops::std_tensor_op::StdTensorOp;
19use tenferro_ops::TensorMeta;
20use tenferro_tensor::{
21 CompareDir, DType, DotGeneralConfig, Error as TensorError, GatherConfig, IntoShapeVec,
22 PadConfig, ScatterConfig, ShapeMismatch, SliceConfig, Tensor, TensorScalar, TensorValue,
23 ValidationError,
24};
25
26use super::error::{Error, ErrorPhase, Result};
27use super::sym_dim::SymDim;
28use crate::checkpoint::{CheckpointNode, RetainedInputMap, RetainedValue};
29use crate::metadata::{
30 concrete_tensor_meta, register_scoped_graph_metadata, register_scoped_value_metadata,
31 symbolic_input_meta, tensor_meta, MetadataScopeChain,
32};
33use crate::scalar_semantics::{bool_from_real_for_op, round_real_to_i32_for_op, round_real_to_i64};
34use crate::shape_constraint::ConstraintScopeChain;
35
36static NEXT_INPUT_ID: AtomicU64 = AtomicU64::new(0);
37static NEXT_TRACED_ID: AtomicU64 = AtomicU64::new(0);
38
39pub type TracedTensorId = u64;
40
41pub(crate) fn next_input_key() -> TensorInputKey {
42 TensorInputKey::User {
43 id: NEXT_INPUT_ID.fetch_add(1, Ordering::Relaxed),
44 }
45}
46
47pub(crate) fn next_traced_id() -> TracedTensorId {
48 NEXT_TRACED_ID.fetch_add(1, Ordering::Relaxed)
49}
50
51type TracedInputMap = RetainedInputMap;
52
53#[derive(Clone)]
54pub struct TracedTensor {
55 pub id: TracedTensorId,
56 pub rank: usize,
57 pub dtype: DType,
58 pub(crate) graph: Arc<Graph<StdTensorOp>>,
59 pub val: LocalValueId,
60 pub(crate) data: Option<Arc<RetainedValue>>,
61 pub(crate) shape_hint: Option<Vec<SymDim>>,
62 pub(crate) inputs_map: Arc<TracedInputMap>,
63 /// Retained construction-time metadata per bound leaf input key.
64 ///
65 /// Populated by data-attached leaf constructors with the exact
66 /// `TensorMeta` they register (symbolic `tensor_axis` extents for
67 /// [`TracedTensor::from_shared_tensor_value_symbolic_shape`]), so the
68 /// deferred eager-AD analysis can seed symbolic leaf metadata without
69 /// deriving concrete extents from the bound values.
70 pub(crate) leaf_metas: Arc<HashMap<TensorInputKey, TensorMeta>>,
71 pub(crate) extra_roots: Vec<Arc<Graph<StdTensorOp>>>,
72 pub(crate) checkpoint_chain: Option<Arc<CheckpointNode>>,
73 pub(crate) metadata_scopes: MetadataScopeChain,
74 pub(crate) constraint_scopes: ConstraintScopeChain,
75}
76
77impl fmt::Debug for TracedTensor {
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 f.debug_struct("TracedTensor")
80 .field("id", &self.id)
81 .field("rank", &self.rank)
82 .field("dtype", &self.dtype)
83 .field("val", &self.val)
84 .field("shape_hint", &self.shape_hint)
85 .field("has_data", &self.data.is_some())
86 .finish_non_exhaustive()
87 }
88}
89
90pub(crate) fn merge_traced_inputs_map<'a>(
91 inputs: impl IntoIterator<Item = &'a TracedTensor>,
92) -> Arc<TracedInputMap> {
93 let maps: Vec<_> = inputs
94 .into_iter()
95 .map(|input| &input.inputs_map)
96 .filter(|map| !map.is_empty())
97 .collect();
98 match maps.as_slice() {
99 [] => return Arc::new(HashMap::new()),
100 [single] => return Arc::clone(*single),
101 _ => {}
102 }
103
104 for &candidate in &maps {
105 if input_map_matches_ordered_merge(candidate.as_ref(), &maps) {
106 return Arc::clone(candidate);
107 }
108 }
109
110 let mut merged = (**maps[0]).clone();
111 for map in maps.iter().skip(1) {
112 merged.extend(
113 map.iter()
114 .map(|(key, tensor)| (key.clone(), tensor.clone())),
115 );
116 }
117 Arc::new(merged)
118}
119
120fn input_map_matches_ordered_merge(
121 candidate: &TracedInputMap,
122 maps: &[&Arc<TracedInputMap>],
123) -> bool {
124 merged_map_matches_ordered(candidate, maps, Arc::ptr_eq)
125}
126
127/// Merge the retained leaf-metadata maps of several traced tensors into one.
128///
129/// Sibling of [`merge_traced_inputs_map`]: the merged map covers exactly the
130/// same leaf keys as the merged bindings map, mapping each to the
131/// construction-time `TensorMeta` its leaf registered (symbolic for symbolic
132/// leaves).
133pub(crate) fn merge_traced_leaf_metas<'a>(
134 inputs: impl IntoIterator<Item = &'a TracedTensor>,
135) -> Arc<HashMap<TensorInputKey, TensorMeta>> {
136 let maps: Vec<_> = inputs
137 .into_iter()
138 .map(|input| &input.leaf_metas)
139 .filter(|map| !map.is_empty())
140 .collect();
141 match maps.as_slice() {
142 [] => return Arc::new(HashMap::new()),
143 [single] => return Arc::clone(*single),
144 _ => {}
145 }
146
147 for &candidate in &maps {
148 if merged_map_matches_ordered(candidate.as_ref(), &maps, |a, b| a == b) {
149 return Arc::clone(candidate);
150 }
151 }
152
153 let mut merged = (**maps[0]).clone();
154 for map in maps.iter().skip(1) {
155 merged.extend(map.iter().map(|(key, meta)| (key.clone(), meta.clone())));
156 }
157 Arc::new(merged)
158}
159
160fn merged_map_matches_ordered<V>(
161 candidate: &HashMap<TensorInputKey, V>,
162 maps: &[&Arc<HashMap<TensorInputKey, V>>],
163 matches: impl Fn(&V, &V) -> bool,
164) -> bool {
165 for map in maps {
166 for key in map.keys() {
167 let Some(final_value) = maps.iter().rev().find_map(|source| source.get(key)) else {
168 return false;
169 };
170 let Some(candidate_value) = candidate.get(key) else {
171 return false;
172 };
173 if !matches(candidate_value, final_value) {
174 return false;
175 }
176 }
177 }
178 true
179}
180
181pub(crate) fn try_concrete_shape(tensor: &TracedTensor) -> Option<Vec<usize>> {
182 tensor
183 .shape_hint
184 .as_ref()?
185 .iter()
186 .map(SymDim::constant_value)
187 .collect()
188}
189
190fn graph_validation(op: &'static str, source: impl Into<ValidationError>) -> Error {
191 Error::validation(op, ErrorPhase::GraphBuild, source.into())
192}
193
194fn graph_invalid_argument(
195 op: &'static str,
196 argument: &'static str,
197 message: impl Into<String>,
198) -> Error {
199 graph_validation(
200 op,
201 ValidationError::InvalidArgument {
202 argument,
203 message: message.into(),
204 },
205 )
206}
207
208fn graph_broadcast_error(op: &'static str, error: BroadcastError) -> Error {
209 graph_validation(op, broadcast_error_to_validation(error))
210}
211
212fn graph_tensor_error(op: &'static str, error: TensorError) -> Error {
213 match error {
214 TensorError::Validation { source, .. } => graph_validation(op, source),
215 other => Error::TensorRuntime(other),
216 }
217}
218
219fn graph_error_with_context(op: &'static str, error: Error) -> Error {
220 match error {
221 Error::Validation { source, .. } => graph_validation(op, source),
222 other => other,
223 }
224}
225
226pub(crate) fn concrete_shape(tensor: &TracedTensor) -> Result<Vec<usize>> {
227 tensor
228 .shape_hint
229 .as_ref()
230 .ok_or_else(|| {
231 graph_invalid_argument(
232 "TracedTensor::concrete_shape",
233 "shape",
234 format!("missing shape hint for traced tensor {}", tensor.id),
235 )
236 })?
237 .iter()
238 .map(|dim| {
239 dim.constant_value().ok_or_else(|| {
240 graph_invalid_argument(
241 "TracedTensor::concrete_shape",
242 "shape",
243 format!("symbolic dimension in shape hint for tensor {}", tensor.id),
244 )
245 })
246 })
247 .collect()
248}
249
250/// Broadcast a traced tensor to `target_shape`.
251///
252/// Expanding singleton axes are first reshaped away so the existing
253/// `BroadcastInDim` transpose rule reduces them correctly during VJP.
254pub(crate) fn broadcast_to(tensor: &TracedTensor, target_shape: &[usize]) -> Result<TracedTensor> {
255 let tensor_shape = concrete_shape(tensor)?;
256 if tensor_shape == target_shape {
257 return Ok(tensor.clone());
258 }
259
260 let plan = broadcast_input_plan(&tensor_shape, target_shape)
261 .map_err(|err| graph_broadcast_error("broadcast_to", err))?;
262
263 let source = if plan.source_shape == tensor_shape {
264 tensor.clone()
265 } else {
266 tensor.reshape(&plan.source_shape)?
267 };
268 source.broadcast_in_dim(target_shape, &plan.dims)
269}
270
271/// Broadcast two tensors to a common shape.
272pub(crate) fn broadcast_binary(
273 a: &TracedTensor,
274 b: &TracedTensor,
275) -> Result<(TracedTensor, TracedTensor)> {
276 if a.shape_hint == b.shape_hint && a.rank == b.rank {
277 return Ok((a.clone(), b.clone()));
278 }
279 if (try_concrete_shape(a).is_none() || try_concrete_shape(b).is_none()) && a.rank == b.rank {
280 return Ok((a.clone(), b.clone()));
281 }
282 let a_shape = concrete_shape(a)?;
283 let b_shape = concrete_shape(b)?;
284 let target = broadcast_shape(&a_shape, &b_shape)
285 .map_err(|err| graph_broadcast_error("broadcast_binary", err))?;
286 Ok((broadcast_to(a, &target)?, broadcast_to(b, &target)?))
287}
288
289pub(crate) fn broadcast_ternary(
290 a: &TracedTensor,
291 b: &TracedTensor,
292 c: &TracedTensor,
293) -> Result<(TracedTensor, TracedTensor, TracedTensor)> {
294 let a_shape = concrete_shape(a)?;
295 let b_shape = concrete_shape(b)?;
296 let c_shape = concrete_shape(c)?;
297 let target = broadcast_shapes([a_shape.as_slice(), b_shape.as_slice(), c_shape.as_slice()])
298 .map_err(|err| graph_broadcast_error("broadcast_ternary", err))?;
299 Ok((
300 broadcast_to(a, &target)?,
301 broadcast_to(b, &target)?,
302 broadcast_to(c, &target)?,
303 ))
304}
305
306fn scale_with_constant(input: &TracedTensor, op: StdTensorOp) -> Result<TracedTensor> {
307 let scalar = apply_nullary(op, 0, input.dtype, Some(vec![]))?;
308 apply_binary(
309 StdTensorOp::Mul,
310 input,
311 &scalar,
312 input.rank,
313 input.shape_hint.clone(),
314 )
315}
316
317fn try_inferred_output_dtype(
318 op: &StdTensorOp,
319 inputs: &[DType],
320 context: &'static str,
321) -> Result<DType> {
322 crate::shape_infer::infer_output_dtype_at(op, inputs, ErrorPhase::GraphBuild)
323 .map_err(|err| graph_error_with_context(context, err))
324}
325
326fn checked_shape_product_for_graph_build(
327 shape: &[usize],
328 context: &'static str,
329 _role: &'static str,
330) -> Result<usize> {
331 shape.iter().copied().try_fold(1usize, |acc, dim| {
332 acc.checked_mul(dim)
333 .ok_or_else(|| graph_validation(context, ValidationError::IntegerOverflow))
334 })
335}
336
337fn validate_concrete_reshape_shape(input: &TracedTensor, shape: &[usize]) -> Result<()> {
338 let to = checked_shape_product_for_graph_build(shape, "TracedTensor::reshape", "target")?;
339 let Some(input_shape) = try_concrete_shape(input) else {
340 return Ok(());
341 };
342 let from =
343 checked_shape_product_for_graph_build(&input_shape, "TracedTensor::reshape", "input")?;
344 if from != to {
345 return Err(graph_validation(
346 "TracedTensor::reshape",
347 ShapeMismatch::ReshapeElementCount { from, to },
348 ));
349 }
350 Ok(())
351}
352
353fn traced_input_shape_exprs(input_idx: usize, tensor: &TracedTensor) -> Vec<DimExpr> {
354 match tensor.shape_hint.as_ref() {
355 Some(shape) => shape
356 .iter()
357 .enumerate()
358 .map(|(axis, dim)| {
359 dim.constant_value()
360 .map_or(DimExpr::InputDim { input_idx, axis }, DimExpr::Const)
361 })
362 .collect(),
363 None => (0..tensor.rank)
364 .map(|axis| DimExpr::InputDim { input_idx, axis })
365 .collect(),
366 }
367}
368
369fn traced_input_sym_shape(tensor: &TracedTensor) -> Vec<SymDim> {
370 tensor.shape_hint.clone().unwrap_or_else(|| {
371 (0..tensor.rank)
372 .map(|axis| SymDim::tensor_axis(tensor.id, axis))
373 .collect()
374 })
375}
376
377pub(crate) fn infer_traced_single_output_shape(
378 op_name: &'static str,
379 op: &StdTensorOp,
380 inputs: &[&TracedTensor],
381) -> Result<(usize, Option<Vec<SymDim>>)> {
382 let input_shape_exprs: Vec<Vec<DimExpr>> = inputs
383 .iter()
384 .enumerate()
385 .map(|(input_idx, tensor)| traced_input_shape_exprs(input_idx, tensor))
386 .collect();
387 let input_shape_refs: Vec<&[DimExpr]> = input_shape_exprs.iter().map(Vec::as_slice).collect();
388 let output_shapes = crate::shape_infer::infer_output_shapes(op, &input_shape_refs)
389 .map_err(|err| graph_error_with_context(op_name, err))?;
390 let output_shape = output_shapes.first().ok_or_else(|| {
391 Error::Internal(format!("{op_name}: shape inference returned no outputs"))
392 })?;
393 if output_shapes.len() != 1 {
394 return Err(Error::Internal(format!(
395 "{op_name}: expected single-output shape inference, got {} outputs",
396 output_shapes.len()
397 )));
398 }
399
400 let input_sym_shapes: Vec<Vec<SymDim>> = inputs
401 .iter()
402 .map(|tensor| traced_input_sym_shape(tensor))
403 .collect();
404 let input_sym_refs: Vec<&[SymDim]> = input_sym_shapes.iter().map(Vec::as_slice).collect();
405 let out_shape_hint = output_shape
406 .iter()
407 .map(|dim| SymDim::from_dim_expr(dim, &input_sym_refs))
408 .collect();
409 Ok((output_shape.len(), Some(out_shape_hint)))
410}
411
412pub(crate) fn register_metadata_or_runtime_state<E>(
413 result: std::result::Result<GlobalMetadataScope, E>,
414) -> Result<GlobalMetadataScope>
415where
416 E: StdError + Send + Sync + 'static,
417{
418 result.map_err(|err| Error::runtime_state_source("metadata", ErrorPhase::Compile, err))
419}
420
421fn reduction_output_meta(
422 tensor: &TracedTensor,
423 axes: &[usize],
424 op: &'static str,
425) -> Result<(usize, Option<Vec<SymDim>>)> {
426 let mut seen = vec![false; tensor.rank];
427 for &axis in axes {
428 if axis >= tensor.rank {
429 return Err(graph_validation(
430 op,
431 ValidationError::AxisOutOfBounds {
432 axis,
433 rank: tensor.rank,
434 },
435 ));
436 }
437 if seen[axis] {
438 return Err(graph_validation(
439 op,
440 ValidationError::DuplicateAxis {
441 axis,
442 role: "reduction",
443 },
444 ));
445 }
446 seen[axis] = true;
447 }
448
449 let out_shape_hint = tensor.shape_hint.as_ref().map(|shape| {
450 (0..shape.len())
451 .filter(|d| !axes.contains(d))
452 .map(|d| shape[d].clone())
453 .collect()
454 });
455 Ok((tensor.rank - axes.len(), out_shape_hint))
456}
457
458fn validate_traced_axis(tensor: &TracedTensor, axis: usize, op: &'static str) -> Result<()> {
459 if axis >= tensor.rank {
460 return Err(graph_validation(
461 op,
462 ValidationError::AxisOutOfBounds {
463 axis,
464 rank: tensor.rank,
465 },
466 ));
467 }
468 Ok(())
469}
470
471fn validate_traced_axes(rank: usize, axes: &[usize], op: &'static str) -> Result<()> {
472 let mut seen = vec![false; rank];
473 for &axis in axes {
474 if axis >= rank {
475 return Err(graph_validation(
476 op,
477 ValidationError::AxisOutOfBounds { axis, rank },
478 ));
479 }
480 if seen[axis] {
481 return Err(graph_validation(
482 op,
483 ValidationError::DuplicateAxis { axis, role: "axis" },
484 ));
485 }
486 seen[axis] = true;
487 }
488 Ok(())
489}
490
491fn validate_traced_insert_axis(rank: usize, axis: usize, op: &'static str) -> Result<()> {
492 if axis > rank {
493 return Err(graph_invalid_argument(
494 op,
495 "axis",
496 format!("axis {axis} out of bounds for rank {rank} insertion"),
497 ));
498 }
499 Ok(())
500}
501
502fn validate_traced_perm(rank: usize, perm: &[usize], op: &'static str) -> Result<()> {
503 if perm.len() != rank {
504 return Err(graph_validation(
505 op,
506 ValidationError::InvalidPermutationLength {
507 expected: rank,
508 actual: perm.len(),
509 },
510 ));
511 }
512 let mut seen = vec![false; rank];
513 for &axis in perm {
514 if axis >= rank {
515 return Err(graph_validation(
516 op,
517 ValidationError::AxisOutOfBounds { axis, rank },
518 ));
519 }
520 if seen[axis] {
521 return Err(graph_validation(
522 op,
523 ValidationError::DuplicateAxis {
524 axis,
525 role: "permutation",
526 },
527 ));
528 }
529 seen[axis] = true;
530 }
531 Ok(())
532}
533
534fn validate_broadcast_in_dim_args(
535 input: &TracedTensor,
536 output_shape: &[SymDim],
537 dims: &[usize],
538 op: &'static str,
539) -> Result<()> {
540 if dims.len() != input.rank {
541 return Err(graph_validation(
542 op,
543 ValidationError::RankMismatch {
544 expected: input.rank,
545 actual: dims.len(),
546 },
547 ));
548 }
549
550 let concrete_input_shape: Option<Vec<usize>> = input
551 .shape_hint
552 .as_ref()
553 .and_then(|shape| shape.iter().map(SymDim::constant_value).collect());
554 let concrete_output_shape = output_shape
555 .iter()
556 .map(SymDim::constant_value)
557 .collect::<Option<Vec<_>>>();
558 if let (Some(input_shape), Some(output_shape)) = (
559 concrete_input_shape.as_deref(),
560 concrete_output_shape.as_deref(),
561 ) && let Some(error) = broadcast_in_dim_extent_error(input_shape, output_shape, dims)
562 {
563 return Err(graph_broadcast_error(op, error));
564 }
565
566 let mut seen = vec![false; output_shape.len()];
567 for &dim in dims {
568 if dim >= output_shape.len() {
569 return Err(graph_validation(
570 op,
571 ValidationError::AxisOutOfBounds {
572 axis: dim,
573 rank: output_shape.len(),
574 },
575 ));
576 }
577 if seen[dim] {
578 return Err(graph_validation(
579 op,
580 ValidationError::DuplicateAxis {
581 axis: dim,
582 role: "broadcast",
583 },
584 ));
585 }
586 seen[dim] = true;
587 }
588
589 Ok(())
590}
591
592impl std::ops::Add for &TracedTensor {
593 type Output = Result<TracedTensor>;
594
595 fn add(self, rhs: &TracedTensor) -> Result<TracedTensor> {
596 TracedTensor::add(self, rhs)
597 }
598}
599
600impl std::ops::Sub for &TracedTensor {
601 type Output = Result<TracedTensor>;
602
603 fn sub(self, rhs: &TracedTensor) -> Result<TracedTensor> {
604 TracedTensor::sub(self, rhs)
605 }
606}
607
608impl std::ops::Mul for &TracedTensor {
609 type Output = Result<TracedTensor>;
610
611 fn mul(self, rhs: &TracedTensor) -> Result<TracedTensor> {
612 TracedTensor::mul(self, rhs)
613 }
614}
615
616impl std::ops::Mul<f64> for &TracedTensor {
617 type Output = Result<TracedTensor>;
618
619 fn mul(self, rhs: f64) -> Result<TracedTensor> {
620 self.scale_real(rhs)
621 }
622}
623
624impl std::ops::Mul<&TracedTensor> for f64 {
625 type Output = Result<TracedTensor>;
626
627 fn mul(self, rhs: &TracedTensor) -> Result<TracedTensor> {
628 rhs.scale_real(self)
629 }
630}
631
632impl std::ops::Neg for &TracedTensor {
633 type Output = Result<TracedTensor>;
634
635 fn neg(self) -> Self::Output {
636 TracedTensor::neg(self)
637 }
638}
639
640impl std::ops::Div for &TracedTensor {
641 type Output = Result<TracedTensor>;
642
643 fn div(self, rhs: &TracedTensor) -> Result<TracedTensor> {
644 TracedTensor::div(self, rhs)
645 }
646}
647
648impl std::ops::Rem for &TracedTensor {
649 type Output = Result<TracedTensor>;
650
651 fn rem(self, rhs: &TracedTensor) -> Result<TracedTensor> {
652 TracedTensor::rem(self, rhs)
653 }
654}
655
656impl TracedTensor {
657 /// Return the graph that owns this traced tensor's current value.
658 ///
659 /// # Examples
660 ///
661 /// ```
662 /// use tenferro_runtime::TracedTensor;
663 ///
664 /// let x = TracedTensor::from_vec_col_major(vec![1], vec![1.0_f64]).unwrap();
665 /// let _graph = x.graph();
666 /// ```
667 pub fn graph(&self) -> &Arc<Graph<StdTensorOp>> {
668 &self.graph
669 }
670
671 /// Return the concrete tensor data attached to this traced value, if any.
672 ///
673 /// Placeholder tensors created with `input_concrete_shape` or
674 /// `input_symbolic_shape` have no attached data until execution bindings
675 /// provide it.
676 ///
677 /// # Examples
678 ///
679 /// ```
680 /// use tenferro_runtime::{DType, TracedTensor};
681 ///
682 /// let concrete = TracedTensor::from_vec_col_major(vec![1], vec![1.0_f64]).unwrap();
683 /// assert!(concrete.attached_value().is_some());
684 ///
685 /// let placeholder = TracedTensor::input_symbolic_shape(DType::F64, 1).unwrap();
686 /// assert!(placeholder.attached_value().is_none());
687 /// ```
688 pub fn attached_value(&self) -> Option<&Arc<RetainedValue>> {
689 self.data.as_ref()
690 }
691
692 /// Build a [`TracedTensor`] leaf from a concrete [`Tensor`], keeping its
693 /// shape as a concrete `shape_hint`.
694 ///
695 /// This is the common constructor when you have concrete tensor data that
696 /// you want to use both for graph building and for evaluation. The
697 /// resulting tensor is treated as a concrete-shape leaf by downstream
698 /// passes (binary einsum decomposition, build-time reshape folding, etc.).
699 ///
700 /// # Examples
701 ///
702 /// ```
703 /// use tenferro_runtime::{Tensor, TracedTensor};
704 ///
705 /// let a = TracedTensor::from_tensor_concrete_shape(
706 /// Tensor::from_vec_col_major(vec![2, 3], vec![1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap(),
707 /// )
708 /// .unwrap();
709 /// assert_eq!(a.rank, 2);
710 /// assert!(a.is_concrete_shape());
711 /// ```
712 ///
713 /// # Errors
714 ///
715 /// Returns [`Error::RuntimeStateSource`] when graph metadata registration
716 /// cannot retain the concrete tensor's shape or dtype.
717 pub fn from_tensor_concrete_shape(tensor: Tensor) -> Result<Self> {
718 Self::from_tensor_concrete_shape_with_identity(tensor, None)
719 }
720
721 /// Build a [`TracedTensor`] leaf from a concrete tensor that declares the
722 /// canonical identity of its externally defined scalar.
723 ///
724 /// # Examples
725 ///
726 /// ```rust
727 /// use tenferro_runtime::TracedTensor;
728 /// use tenferro_tensor::DType;
729 ///
730 /// let dtype = DType::External(std::any::TypeId::of::<f64>());
731 /// let leaf = TracedTensor::input_concrete_shape_declaring_scalar(dtype, &[2], "example.scalar.v1")?;
732 /// assert!(leaf.is_concrete_shape());
733 /// # Ok::<(), tenferro_runtime::Error>(())
734 /// ```
735 ///
736 /// # Errors
737 ///
738 /// Returns [`Error::RuntimeStateSource`] when graph metadata registration
739 /// cannot retain the concrete tensor's shape or dtype.
740 pub fn from_tensor_concrete_shape_declaring_scalar(
741 tensor: Tensor,
742 identity: &'static str,
743 ) -> Result<Self> {
744 Self::from_tensor_concrete_shape_with_identity(tensor, Some(identity))
745 }
746
747 fn from_tensor_concrete_shape_with_identity(
748 tensor: Tensor,
749 identity: Option<&'static str>,
750 ) -> Result<Self> {
751 let shape = tensor.shape().to_vec();
752 let rank = shape.len();
753 let dtype = tensor.dtype();
754 let key = next_input_key();
755 let id = next_traced_id();
756 let data = Arc::new(RetainedValue::from_tensor(tensor));
757 let meta = concrete_tensor_meta(dtype, &shape);
758 let meta = match identity {
759 Some(identity) => meta.with_scalar_identity(identity),
760 None => meta,
761 };
762
763 let mut builder = GraphBuilder::new();
764 let val = builder.add_input(key.clone());
765 builder.set_outputs(vec![val]);
766 let graph = Arc::new(builder.build());
767 let metadata_scope = register_metadata_or_runtime_state(register_scoped_value_metadata(
768 graph.values()[val].key.clone(),
769 meta.clone(),
770 ))?;
771
772 let mut map = HashMap::new();
773 map.insert(key.clone(), Arc::clone(&data));
774 let mut leaf_metas = HashMap::new();
775 leaf_metas.insert(key, meta);
776
777 Ok(Self {
778 id,
779 rank,
780 dtype,
781 graph,
782 val,
783 data: Some(data),
784 shape_hint: Some(shape.into_iter().map(SymDim::from).collect()),
785 inputs_map: Arc::new(map),
786 leaf_metas: Arc::new(leaf_metas),
787 extra_roots: Vec::new(),
788 checkpoint_chain: None,
789 metadata_scopes: MetadataScopeChain::from_scope(metadata_scope),
790 constraint_scopes: ConstraintScopeChain::empty(),
791 })
792 }
793
794 /// Build a [`TracedTensor`] leaf from a concrete [`Tensor`] but advertise
795 /// a symbolic shape during graph construction.
796 ///
797 /// The tensor data is still attached (so plain `eval` works without
798 /// bindings), but graph passes see the leaf as shape-symbolic. This is
799 /// useful for building a single traced program that should not bake in
800 /// shape-specific optimizations.
801 ///
802 /// # Examples
803 ///
804 /// ```
805 /// use tenferro_runtime::{Tensor, TracedTensor};
806 ///
807 /// let t = TracedTensor::from_tensor_symbolic_shape(
808 /// Tensor::from_vec_col_major(vec![2, 3], vec![1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap(),
809 /// )
810 /// .unwrap();
811 /// assert_eq!(t.rank, 2);
812 /// assert!(!t.is_concrete_shape());
813 /// ```
814 ///
815 /// # Errors
816 ///
817 /// Returns [`Error::RuntimeStateSource`] when symbolic graph metadata
818 /// registration is unavailable or its registry state is poisoned.
819 pub fn from_tensor_symbolic_shape(tensor: Tensor) -> Result<Self> {
820 Self::from_tensor_value_symbolic_shape(TensorValue::from_tensor(tensor))
821 }
822
823 /// Build a data-attached symbolic-shape traced leaf from shared tensor data.
824 ///
825 /// This is an internal crate-boundary helper for eager AD recording. It
826 /// preserves the same tensor allocation used by the eager value while graph
827 /// passes see symbolic input extents.
828 ///
829 /// # Examples
830 ///
831 /// ```
832 /// use std::sync::Arc;
833 /// use tenferro_runtime::{Tensor, TracedTensor};
834 ///
835 /// let tensor = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
836 /// let traced = TracedTensor::from_tensor_symbolic_shape(tensor)?;
837 /// assert_eq!(traced.rank, 1);
838 /// assert!(!traced.is_concrete_shape());
839 /// # Ok::<(), tenferro_runtime::Error>(())
840 /// ```
841 ///
842 /// # Errors
843 ///
844 /// Returns [`Error::RuntimeStateSource`] when symbolic graph metadata
845 /// registration is unavailable or its registry state is poisoned.
846 #[doc(hidden)]
847 pub fn from_tensor_value_symbolic_shape(value: TensorValue) -> Result<Self> {
848 let data = Arc::new(RetainedValue::from_tensor_value(value)?);
849 Self::from_shared_tensor_value_symbolic_shape(data)
850 }
851
852 #[doc(hidden)]
853 pub fn from_shared_tensor_value_symbolic_shape(data: Arc<RetainedValue>) -> Result<Self> {
854 let rank = data.shape().len();
855 let dtype = data.dtype();
856 let key = next_input_key();
857 let id = next_traced_id();
858 let meta = symbolic_input_meta(dtype, id, rank);
859
860 let mut builder = GraphBuilder::new();
861 let val = builder.add_input(key.clone());
862 builder.set_outputs(vec![val]);
863 let graph = Arc::new(builder.build());
864 let metadata_scope = register_metadata_or_runtime_state(register_scoped_value_metadata(
865 graph.values()[val].key.clone(),
866 meta.clone(),
867 ))?;
868
869 let mut map = HashMap::new();
870 map.insert(key.clone(), Arc::clone(&data));
871 let mut leaf_metas = HashMap::new();
872 leaf_metas.insert(key, meta);
873
874 Ok(Self {
875 id,
876 rank,
877 dtype,
878 graph,
879 val,
880 data: Some(data),
881 shape_hint: None,
882 inputs_map: Arc::new(map),
883 leaf_metas: Arc::new(leaf_metas),
884 extra_roots: Vec::new(),
885 checkpoint_chain: None,
886 metadata_scopes: MetadataScopeChain::from_scope(metadata_scope),
887 constraint_scopes: ConstraintScopeChain::empty(),
888 })
889 }
890
891 /// Build a data-less placeholder leaf with a fixed (concrete) shape.
892 ///
893 /// Must be passed as an input to [`crate::Runtime::run_compiled`] before evaluation.
894 /// Use this when you know the exact shape of the input but want to build
895 /// the graph once and feed different concrete tensors at execution time.
896 ///
897 /// # Examples
898 ///
899 /// ```
900 /// use tenferro_tensor::DType;
901 /// use tenferro_runtime::TracedTensor;
902 ///
903 /// let x = TracedTensor::input_concrete_shape(DType::F64, &[2, 3]).unwrap();
904 /// assert_eq!(x.rank, 2);
905 /// assert!(x.is_concrete_shape());
906 /// ```
907 ///
908 /// # Errors
909 ///
910 /// Returns [`Error::RuntimeStateSource`] when graph metadata registration
911 /// fails or the registry state is poisoned. `dtype` and `shape` are
912 /// metadata values and are not revalidated by this constructor.
913 pub fn input_concrete_shape(dtype: DType, shape: &[usize]) -> Result<Self> {
914 Self::input_concrete_shape_with_identity(dtype, shape, None)
915 }
916
917 /// Build a data-less placeholder leaf of a concrete shape that declares the
918 /// canonical identity of its externally defined scalar.
919 ///
920 /// A semantic program's identity must be reproducible across processes, while an
921 /// externally defined scalar's tag is a process-local `TypeId`, so an input whose
922 /// dtype is external must declare the stable name its contribution owns.
923 ///
924 /// # Examples
925 ///
926 /// ```rust
927 /// use tenferro_runtime::TracedTensor;
928 /// use tenferro_tensor::DType;
929 ///
930 /// let dtype = DType::External(std::any::TypeId::of::<f64>());
931 /// let x = TracedTensor::input_concrete_shape_declaring_scalar(dtype, &[2], "example.scalar.v1")?;
932 /// assert_eq!(x.rank, 1);
933 /// assert!(x.is_concrete_shape());
934 /// # Ok::<(), tenferro_runtime::Error>(())
935 /// ```
936 ///
937 /// # Errors
938 ///
939 /// Returns [`Error::RuntimeStateSource`] when graph metadata registration fails
940 /// or the registry state is poisoned.
941 pub fn input_concrete_shape_declaring_scalar(
942 dtype: DType,
943 shape: &[usize],
944 identity: &'static str,
945 ) -> Result<Self> {
946 Self::input_concrete_shape_with_identity(dtype, shape, Some(identity))
947 }
948
949 fn input_concrete_shape_with_identity(
950 dtype: DType,
951 shape: &[usize],
952 identity: Option<&'static str>,
953 ) -> Result<Self> {
954 let shape = shape.to_vec();
955 let rank = shape.len();
956 let key = next_input_key();
957 let id = next_traced_id();
958
959 let mut builder = GraphBuilder::new();
960 let val = builder.add_input(key.clone());
961 builder.set_outputs(vec![val]);
962 let graph = Arc::new(builder.build());
963 let meta = concrete_tensor_meta(dtype, &shape);
964 let meta = match identity {
965 Some(identity) => meta.with_scalar_identity(identity),
966 None => meta,
967 };
968 let metadata_scope = register_metadata_or_runtime_state(register_scoped_value_metadata(
969 graph.values()[val].key.clone(),
970 meta,
971 ))?;
972
973 Ok(Self {
974 id,
975 rank,
976 dtype,
977 graph,
978 val,
979 data: None,
980 shape_hint: Some(shape.into_iter().map(SymDim::from).collect()),
981 inputs_map: Arc::new(HashMap::new()),
982 leaf_metas: Arc::new(HashMap::new()),
983 extra_roots: Vec::new(),
984 checkpoint_chain: None,
985 metadata_scopes: MetadataScopeChain::from_scope(metadata_scope),
986 constraint_scopes: ConstraintScopeChain::empty(),
987 })
988 }
989
990 /// Build a data-less placeholder leaf with the given rank but fully
991 /// symbolic shape (every dim is a distinct `SymDim::TensorAxis`).
992 ///
993 /// Must be passed as an input to [`crate::Runtime::run_compiled`] before
994 /// evaluation. Use this to build shape-agnostic graphs.
995 ///
996 /// # Examples
997 ///
998 /// ```
999 /// use tenferro_tensor::DType;
1000 /// use tenferro_runtime::TracedTensor;
1001 ///
1002 /// let x = TracedTensor::input_symbolic_shape(DType::F64, 2).unwrap();
1003 /// assert_eq!(x.rank, 2);
1004 /// assert!(!x.is_concrete_shape());
1005 /// ```
1006 ///
1007 /// # Errors
1008 ///
1009 /// Returns [`Error::RuntimeStateSource`] when graph metadata registration
1010 /// fails or the registry state is poisoned. `rank` is recorded as the
1011 /// symbolic placeholder rank and is not otherwise rejected here.
1012 pub fn input_symbolic_shape(dtype: DType, rank: usize) -> Result<Self> {
1013 let key = next_input_key();
1014 let id = next_traced_id();
1015
1016 let mut builder = GraphBuilder::new();
1017 let val = builder.add_input(key.clone());
1018 builder.set_outputs(vec![val]);
1019 let graph = Arc::new(builder.build());
1020 let metadata_scope = register_metadata_or_runtime_state(register_scoped_value_metadata(
1021 graph.values()[val].key.clone(),
1022 symbolic_input_meta(dtype, id, rank),
1023 ))?;
1024
1025 Ok(Self {
1026 id,
1027 rank,
1028 dtype,
1029 graph,
1030 val,
1031 data: None,
1032 shape_hint: None,
1033 inputs_map: Arc::new(HashMap::new()),
1034 leaf_metas: Arc::new(HashMap::new()),
1035 extra_roots: Vec::new(),
1036 checkpoint_chain: None,
1037 metadata_scopes: MetadataScopeChain::from_scope(metadata_scope),
1038 constraint_scopes: ConstraintScopeChain::empty(),
1039 })
1040 }
1041
1042 /// Build a concrete-shape [`TracedTensor`] leaf from column-major typed
1043 /// `Vec<T>` data.
1044 ///
1045 /// The data must already be in tenferro's physical column-major order.
1046 ///
1047 /// # Examples
1048 ///
1049 /// ```
1050 /// use tenferro_runtime::TracedTensor;
1051 ///
1052 /// let a = TracedTensor::from_vec_col_major(
1053 /// vec![2, 3],
1054 /// vec![1.0_f64, 4.0, 2.0, 5.0, 3.0, 6.0],
1055 /// )?;
1056 /// assert_eq!(a.rank, 2);
1057 /// # Ok::<(), tenferro_runtime::Error>(())
1058 /// ```
1059 ///
1060 /// # Errors
1061 ///
1062 /// Returns [`Error::TensorRuntime`] containing
1063 /// `ValidationError::ShapeDataLengthMismatch` when the shape product does
1064 /// not equal `data.len()`, or `ValidationError::IntegerOverflow` when the
1065 /// shape product cannot be represented by `usize`.
1066 pub fn from_vec_col_major<T: TensorScalar>(
1067 shape: impl IntoShapeVec,
1068 data: Vec<T>,
1069 ) -> Result<Self> {
1070 Self::from_tensor_concrete_shape(Tensor::from_vec_col_major(shape, data)?)
1071 }
1072
1073 /// Return the tensor element dtype recorded for this traced value.
1074 pub fn dtype(&self) -> DType {
1075 self.dtype
1076 }
1077
1078 /// Returns `true` iff every dim of this tensor's `shape_hint` is a
1079 /// constant `SymDim` (i.e. the shape is fully known at graph-build time).
1080 ///
1081 /// # Examples
1082 ///
1083 /// ```
1084 /// use tenferro_tensor::DType;
1085 /// use tenferro_runtime::TracedTensor;
1086 ///
1087 /// let a = TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64; 6]).unwrap();
1088 /// let b = TracedTensor::input_symbolic_shape(DType::F64, 2).unwrap();
1089 /// assert!(a.is_concrete_shape());
1090 /// assert!(!b.is_concrete_shape());
1091 /// ```
1092 pub fn is_concrete_shape(&self) -> bool {
1093 try_concrete_shape(self).is_some()
1094 }
1095
1096 /// Return the fully-concrete shape of this tensor, if every dim of
1097 /// its shape-hint is a constant `SymDim`. Returns `None` if any
1098 /// dimension is symbolic.
1099 ///
1100 /// This is the counterpart to [`Self::is_concrete_shape`] for callers
1101 /// that need to *use* the concrete shape (e.g. external composition
1102 /// wrappers building `broadcast_in_dim` payloads from known shapes).
1103 ///
1104 /// # Examples
1105 ///
1106 /// ```
1107 /// use tenferro_tensor::DType;
1108 /// use tenferro_runtime::TracedTensor;
1109 ///
1110 /// let a = TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64; 6]).unwrap();
1111 /// assert_eq!(a.try_concrete_shape(), Some(vec![2, 3]));
1112 ///
1113 /// let b = TracedTensor::input_symbolic_shape(DType::F64, 2).unwrap();
1114 /// assert!(b.try_concrete_shape().is_none());
1115 /// ```
1116 pub fn try_concrete_shape(&self) -> Option<Vec<usize>> {
1117 try_concrete_shape(self)
1118 }
1119
1120 /// Return the concrete tensor shape.
1121 ///
1122 /// Returns an error when a shape hint is missing or any dimension is
1123 /// symbolic. Composite traced ops that require concrete sizes should
1124 /// propagate this error instead of panicking.
1125 ///
1126 /// # Errors
1127 ///
1128 /// Returns [`Error::Validation`] with `InvalidArgument` when this tensor
1129 /// has no shape hint or any dimension is symbolic.
1130 pub fn concrete_shape(&self) -> Result<Vec<usize>> {
1131 concrete_shape(self)
1132 }
1133
1134 /// If this `TracedTensor` is a leaf (single-node input graph),
1135 /// return its input key. Computed tensors return `None`.
1136 pub fn input_key(&self) -> Option<TensorInputKey> {
1137 match &self.graph.values()[self.val].key {
1138 ValueKey::Input(key) => Some(key.clone()),
1139 _ => None,
1140 }
1141 }
1142
1143 /// Return whether this traced graph carries default data for `key`.
1144 #[doc(hidden)]
1145 pub fn has_attached_input_key(&self, key: &TensorInputKey) -> bool {
1146 self.inputs_map.contains_key(key)
1147 }
1148
1149 /// Elementwise addition with NumPy-style broadcasting.
1150 ///
1151 /// Prefer using the `+` operator when it reads naturally.
1152 ///
1153 /// A longer expression such as `a + b + c` does not compose because the
1154 /// first `+` returns `Result<TracedTensor, Error>`, so the second `+`
1155 /// would receive a result rather than a tensor. Use `?` at each step or
1156 /// the explicit fallible method chain shown below when the operation
1157 /// sequence is more important than notation:
1158 ///
1159 /// # Examples
1160 ///
1161 /// ```rust
1162 /// # use tenferro_runtime::{Error, TracedTensor};
1163 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
1164 /// # let z = TracedTensor::from_vec_col_major(vec![2], vec![3.0_f64, 4.0]).unwrap();
1165 /// let y = x.add(&z);
1166 /// let y2 = &x + &z;
1167 /// # fn add_three(
1168 /// # a: &TracedTensor,
1169 /// # b: &TracedTensor,
1170 /// # c: &TracedTensor,
1171 /// # ) -> Result<TracedTensor, Error> {
1172 /// let ab = (a + b)?;
1173 /// let sum = (&ab + c)?;
1174 /// let method_chain = a.add(b)?.add(c)?;
1175 /// let _ = method_chain;
1176 /// # Ok(sum)
1177 /// # }
1178 /// ```
1179 ///
1180 /// Tenferro prioritizes robust error handling over the conciseness of
1181 /// chained operator notation; the explicit fallible methods are the
1182 /// canonical form for longer sequences.
1183 ///
1184 /// # Errors
1185 ///
1186 /// Returns [`Error::Validation`] with `ShapeMismatch` when operand shapes
1187 /// cannot be broadcast, or [`Error::RuntimeStateSource`] when graph
1188 /// metadata registration fails.
1189 ///
1190 /// # Deferred errors
1191 ///
1192 /// If symbolic dimensions prevent shape comparison during graph
1193 /// construction, the same `ShapeMismatch` can be reported during
1194 /// compilation or execution, with the corresponding [`ErrorPhase`].
1195 pub fn add(&self, other: &TracedTensor) -> Result<TracedTensor> {
1196 let (lhs, rhs) = broadcast_binary(self, other)?;
1197 apply_binary(
1198 StdTensorOp::Add,
1199 &lhs,
1200 &rhs,
1201 lhs.rank,
1202 lhs.shape_hint.clone(),
1203 )
1204 }
1205
1206 /// Elementwise subtraction with NumPy-style broadcasting.
1207 ///
1208 /// Prefer using the `-` operator when it reads naturally.
1209 ///
1210 /// # Errors
1211 ///
1212 /// Returns [`Error::Validation`] with `ShapeMismatch` when operand shapes
1213 /// cannot be broadcast, or [`Error::RuntimeStateSource`] when graph
1214 /// metadata registration fails.
1215 ///
1216 /// # Deferred errors
1217 ///
1218 /// If symbolic dimensions prevent shape comparison during graph
1219 /// construction, the same `ShapeMismatch` can be reported during
1220 /// compilation or execution, with the corresponding [`ErrorPhase`].
1221 pub fn sub(&self, other: &TracedTensor) -> Result<TracedTensor> {
1222 let (lhs, rhs) = broadcast_binary(self, other)?;
1223 apply_binary(
1224 StdTensorOp::Sub,
1225 &lhs,
1226 &rhs,
1227 lhs.rank,
1228 lhs.shape_hint.clone(),
1229 )
1230 }
1231
1232 /// Elementwise multiplication with NumPy-style broadcasting.
1233 ///
1234 /// Prefer using the `*` operator when it reads naturally.
1235 ///
1236 /// # Examples
1237 ///
1238 /// ```rust
1239 /// # use tenferro_runtime::TracedTensor;
1240 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
1241 /// # let z = TracedTensor::from_vec_col_major(vec![2], vec![3.0_f64, 4.0]).unwrap();
1242 /// let y = x.mul(&z);
1243 /// let y2 = &x * &z;
1244 /// ```
1245 ///
1246 /// # Errors
1247 ///
1248 /// Returns [`Error::Validation`] with `ShapeMismatch` when operand shapes
1249 /// cannot be broadcast, or [`Error::RuntimeStateSource`] when graph
1250 /// metadata registration fails.
1251 ///
1252 /// # Deferred errors
1253 ///
1254 /// If symbolic ranks prevent shape comparison during graph construction,
1255 /// the same `ShapeMismatch` can be reported during compilation or
1256 /// execution, with the corresponding [`ErrorPhase`].
1257 pub fn mul(&self, other: &TracedTensor) -> Result<TracedTensor> {
1258 let (lhs, rhs) = broadcast_binary(self, other)?;
1259 apply_binary(
1260 StdTensorOp::Mul,
1261 &lhs,
1262 &rhs,
1263 lhs.rank,
1264 lhs.shape_hint.clone(),
1265 )
1266 }
1267
1268 /// Elementwise division with NumPy-style broadcasting.
1269 ///
1270 /// Prefer using the `/` operator when it reads naturally.
1271 ///
1272 /// # Examples
1273 ///
1274 /// ```rust
1275 /// # use tenferro_runtime::TracedTensor;
1276 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
1277 /// # let z = TracedTensor::from_vec_col_major(vec![2], vec![3.0_f64, 4.0]).unwrap();
1278 /// let y = x.div(&z);
1279 /// let y2 = &x / &z;
1280 /// ```
1281 ///
1282 /// # Errors
1283 ///
1284 /// Returns [`Error::Validation`] with `ShapeMismatch` when operand shapes
1285 /// cannot be broadcast, or [`Error::RuntimeStateSource`] when graph
1286 /// metadata registration fails.
1287 ///
1288 /// # Deferred errors
1289 ///
1290 /// If symbolic ranks prevent shape comparison during graph construction,
1291 /// the same `ShapeMismatch` can be reported during compilation or
1292 /// execution, with the corresponding [`ErrorPhase`]. For integer inputs,
1293 /// a zero divisor is reported during execution as
1294 /// [`Error::TensorRuntime`] containing a
1295 /// [`tenferro_tensor::Error::Extension`] classified as
1296 /// `tenferro_tensor::ErrorKind::NumericalFailure` and retaining the typed
1297 /// backend source; floating-point and complex zero divisors follow their
1298 /// numeric semantics instead.
1299 pub fn div(&self, other: &TracedTensor) -> Result<TracedTensor> {
1300 let (lhs, rhs) = broadcast_binary(self, other)?;
1301 apply_binary(
1302 StdTensorOp::Div,
1303 &lhs,
1304 &rhs,
1305 lhs.rank,
1306 lhs.shape_hint.clone(),
1307 )
1308 }
1309
1310 /// Elementwise remainder with NumPy-style broadcasting.
1311 ///
1312 /// Prefer using the `%` operator when it reads naturally.
1313 ///
1314 /// # Errors
1315 ///
1316 /// Returns [`Error::Validation`] with `ShapeMismatch` when operand shapes
1317 /// cannot be broadcast, [`Error::Unsupported`] at
1318 /// [`ErrorPhase::GraphBuild`] when either operand has a complex dtype, or
1319 /// [`Error::RuntimeStateSource`] when graph metadata registration fails.
1320 ///
1321 /// # Deferred errors
1322 ///
1323 /// If symbolic ranks prevent shape comparison during graph construction,
1324 /// the same `ShapeMismatch` can be reported during compilation or
1325 /// execution, with the corresponding [`ErrorPhase`]. For integer inputs,
1326 /// a zero divisor is reported during execution as
1327 /// [`Error::TensorRuntime`] containing a
1328 /// [`tenferro_tensor::Error::Extension`] classified as
1329 /// `tenferro_tensor::ErrorKind::NumericalFailure` and retaining the typed
1330 /// backend source; floating-point zero divisors follow their numeric
1331 /// semantics.
1332 pub fn rem(&self, other: &TracedTensor) -> Result<TracedTensor> {
1333 let (lhs, rhs) = broadcast_binary(self, other)?;
1334 apply_binary(
1335 StdTensorOp::Rem,
1336 &lhs,
1337 &rhs,
1338 lhs.rank,
1339 lhs.shape_hint.clone(),
1340 )
1341 }
1342
1343 /// Elementwise comparison with NumPy-style broadcasting.
1344 ///
1345 /// # Errors
1346 ///
1347 /// Returns [`Error::Validation`] with `ShapeMismatch` when the concrete
1348 /// operands cannot be broadcast, [`Error::Unsupported`] when ordered
1349 /// comparison rejects a complex dtype, or [`Error::RuntimeStateSource`]
1350 /// when result metadata cannot be registered.
1351 ///
1352 /// # Deferred errors
1353 ///
1354 /// With same-rank symbolic operands, shape compatibility is retained as a
1355 /// graph constraint. A concrete mismatch is reported later as
1356 /// [`Error::TensorRuntime`] containing a typed validation source, with the
1357 /// failure phase identifying compilation or execution.
1358 pub fn compare(&self, other: &TracedTensor, dir: CompareDir) -> Result<TracedTensor> {
1359 apply_broadcast_binary_op(StdTensorOp::Compare(dir), self, other)
1360 }
1361
1362 /// Elementwise maximum with NumPy-style broadcasting.
1363 ///
1364 /// # Errors
1365 ///
1366 /// Returns [`Error::Validation`] with `ShapeMismatch` when the concrete
1367 /// operands cannot be broadcast, [`Error::Unsupported`] when ordered
1368 /// maximum rejects a complex dtype, or [`Error::RuntimeStateSource`] when
1369 /// result metadata cannot be registered.
1370 ///
1371 /// # Deferred errors
1372 ///
1373 /// With same-rank symbolic operands, the broadcast constraint may fail at
1374 /// compile or execution and is returned as [`Error::TensorRuntime`] with
1375 /// its typed validation source.
1376 pub fn maximum(&self, other: &TracedTensor) -> Result<TracedTensor> {
1377 apply_broadcast_binary_op(StdTensorOp::Maximum, self, other)
1378 }
1379
1380 /// Elementwise minimum with NumPy-style broadcasting.
1381 ///
1382 /// # Errors
1383 ///
1384 /// Returns [`Error::Validation`] with `ShapeMismatch` when the concrete
1385 /// operands cannot be broadcast, [`Error::Unsupported`] when ordered
1386 /// minimum rejects a complex dtype, or [`Error::RuntimeStateSource`] when
1387 /// result metadata cannot be registered.
1388 ///
1389 /// # Deferred errors
1390 ///
1391 /// With same-rank symbolic operands, the broadcast constraint may fail at
1392 /// compile or execution and is returned as [`Error::TensorRuntime`] with
1393 /// its typed validation source.
1394 pub fn minimum(&self, other: &TracedTensor) -> Result<TracedTensor> {
1395 apply_broadcast_binary_op(StdTensorOp::Minimum, self, other)
1396 }
1397
1398 /// Select values from `on_true` or `on_false` using `condition`.
1399 ///
1400 /// # Errors
1401 ///
1402 /// Returns [`Error::Validation`] with `InvalidArgument` when an operand
1403 /// lacks concrete shape metadata, or `ShapeMismatch` when the concrete
1404 /// condition and branches cannot share a broadcast shape. Dtype promotion
1405 /// failures are returned as [`Error::TensorRuntime`] with the typed
1406 /// `UnsupportedDTypeConversion` source; metadata failures retain
1407 /// [`Error::RuntimeStateSource`].
1408 pub fn where_select(
1409 condition: &TracedTensor,
1410 on_true: &TracedTensor,
1411 on_false: &TracedTensor,
1412 ) -> Result<TracedTensor> {
1413 apply_broadcast_ternary_op(StdTensorOp::Select, condition, on_true, on_false)
1414 }
1415
1416 /// Alias for [`Self::where_select`].
1417 ///
1418 /// # Errors
1419 ///
1420 /// Returns the same concrete failures as [`Self::where_select`]:
1421 /// [`Error::Validation`] with `InvalidArgument`/`ShapeMismatch` for shape
1422 /// metadata or broadcasting, [`Error::TensorRuntime`] with
1423 /// `UnsupportedDTypeConversion` for failed promotion, and
1424 /// [`Error::RuntimeStateSource`] for metadata registration.
1425 pub fn select(
1426 condition: &TracedTensor,
1427 on_true: &TracedTensor,
1428 on_false: &TracedTensor,
1429 ) -> Result<TracedTensor> {
1430 Self::where_select(condition, on_true, on_false)
1431 }
1432
1433 /// Clamp values elementwise between lower and upper bounds.
1434 ///
1435 /// # Errors
1436 ///
1437 /// Returns [`Error::Validation`] with `InvalidArgument` when an operand
1438 /// lacks concrete shape metadata, `ShapeMismatch` when bounds cannot be
1439 /// broadcast with the input, [`Error::Unsupported`] for an ordered
1440 /// complex dtype, or [`Error::RuntimeStateSource`] when metadata cannot be
1441 /// registered.
1442 pub fn clamp(&self, lower: &TracedTensor, upper: &TracedTensor) -> Result<TracedTensor> {
1443 apply_broadcast_ternary_op(StdTensorOp::Clamp, self, lower, upper)
1444 }
1445
1446 fn apply_same_shape_unary(&self, op: StdTensorOp) -> Result<TracedTensor> {
1447 apply_unary(op, self, self.rank, self.shape_hint.clone())
1448 }
1449
1450 /// Elementwise negation.
1451 ///
1452 /// Prefer using the unary `-` operator when it reads naturally.
1453 ///
1454 /// # Examples
1455 ///
1456 /// ```rust
1457 /// # use tenferro_runtime::TracedTensor;
1458 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
1459 /// let y = x.neg().unwrap();
1460 /// let y2 = (-&x).unwrap();
1461 /// ```
1462 ///
1463 /// # Errors
1464 ///
1465 /// Returns [`Error::RuntimeStateSource`] when the graph metadata registry
1466 /// is unavailable or poisoned while recording the unary result.
1467 pub fn neg(&self) -> Result<TracedTensor> {
1468 self.apply_same_shape_unary(StdTensorOp::Neg)
1469 }
1470
1471 /// Elementwise complex conjugate.
1472 ///
1473 /// # Examples
1474 ///
1475 /// ```rust
1476 /// # use num_complex::Complex64;
1477 /// # use tenferro_runtime::TracedTensor;
1478 /// # let x = TracedTensor::from_vec_col_major(
1479 /// # vec![2],
1480 /// # vec![Complex64::new(1.0, 2.0), Complex64::new(3.0, 4.0)],
1481 /// # )
1482 /// # .unwrap();
1483 /// let y = x.conj().unwrap();
1484 /// ```
1485 ///
1486 /// # Errors
1487 ///
1488 /// Returns [`Error::RuntimeStateSource`] when the graph metadata registry
1489 /// is unavailable or poisoned while recording the unary result.
1490 pub fn conj(&self) -> Result<TracedTensor> {
1491 self.apply_same_shape_unary(StdTensorOp::Conj)
1492 }
1493
1494 /// Elementwise absolute value.
1495 ///
1496 /// Complex inputs return real magnitudes (`C32 -> F32`, `C64 -> F64`).
1497 ///
1498 /// # Examples
1499 ///
1500 /// ```rust
1501 /// # use tenferro_runtime::TracedTensor;
1502 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![-1.0_f64, 2.0]).unwrap();
1503 /// let y = x.abs().unwrap();
1504 /// ```
1505 ///
1506 /// # Errors
1507 ///
1508 /// Returns [`Error::RuntimeStateSource`] when the graph metadata registry
1509 /// is unavailable or poisoned while recording the unary result.
1510 pub fn abs(&self) -> Result<TracedTensor> {
1511 self.apply_same_shape_unary(StdTensorOp::Abs)
1512 }
1513
1514 /// Elementwise sign.
1515 ///
1516 /// # Examples
1517 ///
1518 /// ```rust
1519 /// # use tenferro_runtime::TracedTensor;
1520 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![-1.0_f64, 2.0]).unwrap();
1521 /// let y = x.sign().unwrap();
1522 /// ```
1523 ///
1524 /// # Errors
1525 ///
1526 /// Returns [`Error::RuntimeStateSource`] when the graph metadata registry
1527 /// is unavailable or poisoned while recording the unary result.
1528 pub fn sign(&self) -> Result<TracedTensor> {
1529 self.apply_same_shape_unary(StdTensorOp::Sign)
1530 }
1531
1532 /// Scale by a real scalar: `y = factor * x`.
1533 ///
1534 /// # Examples
1535 ///
1536 /// ```rust
1537 /// # use tenferro_runtime::TracedTensor;
1538 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
1539 /// let y = x.scale_real(2.0)?;
1540 /// # Ok::<(), tenferro_runtime::Error>(())
1541 /// ```
1542 ///
1543 /// # Errors
1544 ///
1545 /// Returns [`Error::Validation`] with `InvalidArgument` when an integer or
1546 /// boolean factor is non-finite or out of range for the input dtype, or
1547 /// [`Error::RuntimeStateSource`] when output metadata registration fails.
1548 pub fn scale_real(&self, factor: f64) -> Result<TracedTensor> {
1549 let op = match self.dtype {
1550 DType::F64 => StdTensorOp::constant(factor),
1551 DType::F32 => StdTensorOp::constant(factor as f32),
1552 DType::I32 => StdTensorOp::constant(round_real_to_i32_for_op("scale_real", factor)?),
1553 DType::I64 => StdTensorOp::constant(round_real_to_i64(factor)?),
1554 DType::Bool => StdTensorOp::constant(bool_from_real_for_op("scale_real", factor)?),
1555 DType::C64 => StdTensorOp::constant(Complex64::new(factor, 0.0)),
1556 DType::C32 => StdTensorOp::constant(Complex32::new(factor as f32, 0.0)),
1557 // An externally defined scalar has no traced constant, so the closure
1558 // rejects it instead of guessing one.
1559 DType::External(_) => {
1560 return Err(graph_invalid_argument(
1561 "scale_real",
1562 "dtype",
1563 format!("requires a preset tensor dtype, got {:?}", self.dtype),
1564 ));
1565 }
1566 };
1567 scale_with_constant(self, op)
1568 }
1569
1570 /// Scale by a complex scalar: `y = factor * x`.
1571 ///
1572 /// Only complex tensors support complex scaling. For a real scalar factor
1573 /// that should preserve the input dtype, prefer [`scale_real`](Self::scale_real).
1574 ///
1575 /// # Examples
1576 ///
1577 /// ```rust
1578 /// use num_complex::Complex64;
1579 /// # use tenferro_runtime::TracedTensor;
1580 /// # let x = TracedTensor::from_vec_col_major(
1581 /// # vec![2],
1582 /// # vec![Complex64::new(1.0, 0.0), Complex64::new(2.0, 0.0)],
1583 /// # )
1584 /// # .unwrap();
1585 /// let y = x.scale_complex(Complex64::new(0.0, 1.0)).unwrap(); // multiply by i
1586 /// ```
1587 ///
1588 /// # Errors
1589 ///
1590 /// Returns [`Error::Validation`] with `InvalidArgument` when a complex
1591 /// factor is applied to a non-complex dtype, or
1592 /// [`Error::RuntimeStateSource`] when output metadata registration fails.
1593 pub fn scale_complex(&self, factor: Complex64) -> Result<TracedTensor> {
1594 match self.dtype {
1595 DType::C64 => scale_with_constant(self, StdTensorOp::constant(factor)),
1596 DType::C32 => scale_with_constant(
1597 self,
1598 StdTensorOp::constant(Complex32::new(factor.re as f32, factor.im as f32)),
1599 ),
1600 DType::F32
1601 | DType::F64
1602 | DType::I32
1603 | DType::I64
1604 | DType::Bool
1605 | DType::External(_) => Err(graph_invalid_argument(
1606 "scale_complex",
1607 "dtype",
1608 format!("requires complex tensor dtype, got {:?}", self.dtype),
1609 )),
1610 }
1611 }
1612
1613 /// Elementwise exponential.
1614 ///
1615 /// # Examples
1616 ///
1617 /// ```rust
1618 /// # use tenferro_runtime::TracedTensor;
1619 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
1620 /// let y = x.exp().unwrap();
1621 /// ```
1622 ///
1623 /// # Errors
1624 ///
1625 /// Returns [`Error::RuntimeStateSource`] when the graph metadata registry
1626 /// is unavailable or poisoned while recording the unary result.
1627 pub fn exp(&self) -> Result<TracedTensor> {
1628 self.apply_same_shape_unary(StdTensorOp::Exp)
1629 }
1630
1631 /// Elementwise natural logarithm.
1632 ///
1633 /// # Examples
1634 ///
1635 /// ```rust
1636 /// # use tenferro_runtime::TracedTensor;
1637 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
1638 /// let y = x.log().unwrap();
1639 /// ```
1640 ///
1641 /// # Errors
1642 ///
1643 /// Returns [`Error::RuntimeStateSource`] when the graph metadata registry
1644 /// is unavailable or poisoned while recording the unary result.
1645 pub fn log(&self) -> Result<TracedTensor> {
1646 self.apply_same_shape_unary(StdTensorOp::Log)
1647 }
1648
1649 /// Elementwise sine.
1650 ///
1651 /// # Examples
1652 ///
1653 /// ```rust
1654 /// # use tenferro_runtime::TracedTensor;
1655 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
1656 /// let y = x.sin().unwrap();
1657 /// ```
1658 ///
1659 /// # Errors
1660 ///
1661 /// Returns [`Error::RuntimeStateSource`] when the graph metadata registry
1662 /// is unavailable or poisoned while recording the unary result.
1663 pub fn sin(&self) -> Result<TracedTensor> {
1664 self.apply_same_shape_unary(StdTensorOp::Sin)
1665 }
1666
1667 /// Elementwise cosine.
1668 ///
1669 /// # Examples
1670 ///
1671 /// ```rust
1672 /// # use tenferro_runtime::TracedTensor;
1673 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
1674 /// let y = x.cos().unwrap();
1675 /// ```
1676 ///
1677 /// # Errors
1678 ///
1679 /// Returns [`Error::RuntimeStateSource`] when the graph metadata registry
1680 /// is unavailable or poisoned while recording the unary result.
1681 pub fn cos(&self) -> Result<TracedTensor> {
1682 self.apply_same_shape_unary(StdTensorOp::Cos)
1683 }
1684
1685 /// Elementwise hyperbolic tangent.
1686 ///
1687 /// # Examples
1688 ///
1689 /// ```rust
1690 /// # use tenferro_runtime::TracedTensor;
1691 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
1692 /// let y = x.tanh().unwrap();
1693 /// ```
1694 ///
1695 /// # Errors
1696 ///
1697 /// Returns [`Error::RuntimeStateSource`] when the graph metadata registry
1698 /// is unavailable or poisoned while recording the unary result.
1699 pub fn tanh(&self) -> Result<TracedTensor> {
1700 self.apply_same_shape_unary(StdTensorOp::Tanh)
1701 }
1702
1703 /// Elementwise square root.
1704 ///
1705 /// # Examples
1706 ///
1707 /// ```rust
1708 /// # use tenferro_runtime::TracedTensor;
1709 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 4.0]).unwrap();
1710 /// let y = x.sqrt().unwrap();
1711 /// ```
1712 ///
1713 /// # Errors
1714 ///
1715 /// Returns [`Error::RuntimeStateSource`] when the graph metadata registry
1716 /// is unavailable or poisoned while recording the unary result.
1717 pub fn sqrt(&self) -> Result<TracedTensor> {
1718 self.apply_same_shape_unary(StdTensorOp::Sqrt)
1719 }
1720
1721 /// Elementwise reciprocal square root.
1722 ///
1723 /// # Examples
1724 ///
1725 /// ```rust
1726 /// # use tenferro_runtime::TracedTensor;
1727 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 4.0]).unwrap();
1728 /// let y = x.rsqrt().unwrap();
1729 /// ```
1730 ///
1731 /// # Errors
1732 ///
1733 /// Returns [`Error::RuntimeStateSource`] when the graph metadata registry
1734 /// is unavailable or poisoned while recording the unary result.
1735 pub fn rsqrt(&self) -> Result<TracedTensor> {
1736 self.apply_same_shape_unary(StdTensorOp::Rsqrt)
1737 }
1738
1739 /// Elementwise power with NumPy-style broadcasting.
1740 ///
1741 /// # Examples
1742 ///
1743 /// ```rust
1744 /// # use tenferro_runtime::TracedTensor;
1745 /// # let base = TracedTensor::from_vec_col_major(vec![2], vec![2.0_f64, 3.0]).unwrap();
1746 /// # let exp = TracedTensor::from_vec_col_major(vec![2], vec![3.0_f64, 2.0]).unwrap();
1747 /// let y = base.pow(&exp);
1748 /// ```
1749 ///
1750 /// # Errors
1751 ///
1752 /// Returns [`Error::Validation`] with `ShapeMismatch` when the concrete
1753 /// operands cannot be broadcast, or [`Error::RuntimeStateSource`] when
1754 /// result metadata cannot be registered.
1755 ///
1756 /// # Deferred errors
1757 ///
1758 /// A symbolic broadcast mismatch or integer negative exponent is
1759 /// discovered at compile or execution and is returned as
1760 /// [`Error::TensorRuntime`] with a typed `ShapeMismatch` or
1761 /// `NegativeIntegerExponent` numerical source and the corresponding
1762 /// [`ErrorPhase`].
1763 pub fn pow(&self, other: &TracedTensor) -> Result<TracedTensor> {
1764 let (lhs, rhs) = broadcast_binary(self, other)?;
1765 apply_binary(
1766 StdTensorOp::Pow,
1767 &lhs,
1768 &rhs,
1769 lhs.rank,
1770 lhs.shape_hint.clone(),
1771 )
1772 }
1773
1774 /// Elementwise `exp(x) - 1`.
1775 ///
1776 /// # Examples
1777 ///
1778 /// ```rust
1779 /// # use tenferro_runtime::TracedTensor;
1780 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
1781 /// let y = x.expm1().unwrap();
1782 /// ```
1783 ///
1784 /// # Errors
1785 ///
1786 /// Returns [`Error::RuntimeStateSource`] when the graph metadata registry
1787 /// is unavailable or poisoned while recording the unary result.
1788 pub fn expm1(&self) -> Result<TracedTensor> {
1789 self.apply_same_shape_unary(StdTensorOp::Expm1)
1790 }
1791
1792 /// Elementwise `log(1 + x)`.
1793 ///
1794 /// # Examples
1795 ///
1796 /// ```rust
1797 /// # use tenferro_runtime::TracedTensor;
1798 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
1799 /// let y = x.log1p().unwrap();
1800 /// ```
1801 ///
1802 /// # Errors
1803 ///
1804 /// Returns [`Error::RuntimeStateSource`] when the graph metadata registry
1805 /// is unavailable or poisoned while recording the unary result.
1806 pub fn log1p(&self) -> Result<TracedTensor> {
1807 self.apply_same_shape_unary(StdTensorOp::Log1p)
1808 }
1809
1810 /// Convert the tensor to a different dtype using checked conversion.
1811 ///
1812 /// Use [`cast`](Self::cast) when a lossy dtype projection is intended.
1813 ///
1814 /// # Examples
1815 ///
1816 /// ```rust
1817 /// use tenferro_runtime::DType;
1818 /// # use tenferro_runtime::TracedTensor;
1819 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
1820 ///
1821 /// let y = x.convert(DType::C64)?;
1822 /// # Ok::<(), tenferro_runtime::Error>(())
1823 /// ```
1824 ///
1825 /// # Errors
1826 ///
1827 /// Returns [`tenferro_tensor::Error::UnsupportedDTypeConversion`] when the
1828 /// requested pair is outside tenferro's checked dtype-promotion lattice,
1829 /// or [`Error::Validation`] when graph metadata rejects the conversion.
1830 /// Use [`cast`](Self::cast) for explicit lossy dtype projection.
1831 pub fn convert(&self, to: DType) -> Result<TracedTensor> {
1832 tenferro_tensor::validate::validate_convert_dtype("TracedTensor::convert", self.dtype, to)?;
1833 self.cast(to)
1834 }
1835
1836 /// Cast the tensor to a different dtype using explicit dtype projection.
1837 ///
1838 /// `cast` may truncate, narrow precision, project complex values to their
1839 /// real component, or use boolean truthiness where the backend supports the
1840 /// requested projection.
1841 ///
1842 /// # Examples
1843 ///
1844 /// ```rust
1845 /// use tenferro_runtime::DType;
1846 /// # use tenferro_runtime::TracedTensor;
1847 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![1.2_f64, -2.8]).unwrap();
1848 ///
1849 /// let y = x.cast(DType::I32).unwrap();
1850 /// ```
1851 ///
1852 /// # Errors
1853 ///
1854 /// Returns [`Error::TensorRuntime`] containing
1855 /// `UnsupportedDTypeConversion` when the requested input-to-target
1856 /// projection is not supported, or [`Error::RuntimeStateSource`] when
1857 /// converted-output metadata cannot be registered.
1858 pub fn cast(&self, to: DType) -> Result<TracedTensor> {
1859 if self.dtype == to {
1860 return Ok(self.clone());
1861 }
1862
1863 apply_unary_with_dtype(
1864 StdTensorOp::Convert {
1865 from: self.dtype,
1866 to,
1867 },
1868 self,
1869 self.rank,
1870 self.shape_hint.clone(),
1871 to,
1872 )
1873 }
1874
1875 /// Generalized tensor contraction.
1876 ///
1877 /// # Examples
1878 ///
1879 /// ```rust
1880 /// # use tenferro_runtime::{DotGeneralConfig, TracedTensor};
1881 /// # let a = TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64; 6]).unwrap();
1882 /// # let b = TracedTensor::from_vec_col_major(vec![3, 4], vec![1.0_f64; 12]).unwrap();
1883 /// # let config = DotGeneralConfig {
1884 /// # lhs_contracting_dims: vec![1],
1885 /// # rhs_contracting_dims: vec![0],
1886 /// # lhs_batch_dims: vec![],
1887 /// # rhs_batch_dims: vec![],
1888 /// # };
1889 /// let y = a.dot_general(&b, config)?;
1890 /// # Ok::<(), tenferro_runtime::Error>(())
1891 /// ```
1892 ///
1893 /// # Errors
1894 ///
1895 /// Returns [`Error::Validation`] with `RankMismatch`, `AxisOutOfBounds`,
1896 /// `DuplicateAxis`, or `AxisRoleConflict` when dimension numbers are
1897 /// invalid for the operand ranks, and [`Error::RuntimeStateSource`] when
1898 /// output metadata cannot be registered.
1899 ///
1900 /// # Deferred errors
1901 ///
1902 /// Contracting or batch dimensions whose sizes are symbolic are checked
1903 /// when concrete inputs reach compilation or execution. A mismatch is
1904 /// returned as [`Error::TensorRuntime`] with a typed `ShapeMismatch`
1905 /// source and its corresponding [`ErrorPhase`].
1906 pub fn dot_general(
1907 &self,
1908 other: &TracedTensor,
1909 config: DotGeneralConfig,
1910 ) -> Result<TracedTensor> {
1911 config
1912 .validate_dims_with_ranks(self.rank, other.rank)
1913 .map_err(|err| graph_tensor_error("dot_general", err))?;
1914 let lhs_free: Vec<usize> = (0..self.rank)
1915 .filter(|d| {
1916 !config.lhs_contracting_dims.contains(d) && !config.lhs_batch_dims.contains(d)
1917 })
1918 .collect();
1919 let rhs_free: Vec<usize> = (0..other.rank)
1920 .filter(|d| {
1921 !config.rhs_contracting_dims.contains(d) && !config.rhs_batch_dims.contains(d)
1922 })
1923 .collect();
1924 let out_rank = config.lhs_batch_dims.len() + lhs_free.len() + rhs_free.len();
1925 let out_shape_hint = match (&self.shape_hint, &other.shape_hint) {
1926 (Some(lhs_shape), Some(rhs_shape)) => {
1927 let mut out_shape = Vec::with_capacity(out_rank);
1928 for &d in &lhs_free {
1929 out_shape.push(lhs_shape[d].clone());
1930 }
1931 for &d in &rhs_free {
1932 out_shape.push(rhs_shape[d].clone());
1933 }
1934 for &d in &config.lhs_batch_dims {
1935 out_shape.push(lhs_shape[d].clone());
1936 }
1937 Some(out_shape)
1938 }
1939 _ => None,
1940 };
1941
1942 apply_binary(
1943 StdTensorOp::DotGeneral { config },
1944 self,
1945 other,
1946 out_rank,
1947 out_shape_hint,
1948 )
1949 }
1950
1951 /// Matrix multiplication for rank-2 tensors.
1952 ///
1953 /// # Errors
1954 ///
1955 /// Returns [`Error::Validation`] with `RankMismatch` when either operand is
1956 /// not rank 2, `ShapeMismatch::ContractedDimensions` when known matrix
1957 /// dimensions differ, or [`Error::RuntimeStateSource`] when output
1958 /// metadata cannot be registered.
1959 ///
1960 /// # Deferred errors
1961 ///
1962 /// If either contracted dimension is symbolic, the mismatch is discovered
1963 /// at compilation or execution and returned as [`Error::TensorRuntime`]
1964 /// with its typed `ShapeMismatch` source.
1965 pub fn matmul(&self, other: &TracedTensor) -> Result<TracedTensor> {
1966 if self.rank != 2 {
1967 return Err(graph_validation(
1968 "TracedTensor::matmul",
1969 ValidationError::RankMismatch {
1970 expected: 2,
1971 actual: self.rank,
1972 },
1973 ));
1974 }
1975 if other.rank != 2 {
1976 return Err(graph_validation(
1977 "TracedTensor::matmul",
1978 ValidationError::RankMismatch {
1979 expected: 2,
1980 actual: other.rank,
1981 },
1982 ));
1983 }
1984 if let (Some(lhs_shape), Some(rhs_shape)) = (&self.shape_hint, &other.shape_hint)
1985 && let (Some(lhs_cols), Some(rhs_rows)) =
1986 (lhs_shape[1].constant_value(), rhs_shape[0].constant_value())
1987 && lhs_cols != rhs_rows
1988 {
1989 return Err(graph_validation(
1990 "TracedTensor::matmul",
1991 ShapeMismatch::ContractedDimensions {
1992 lhs_axis: 1,
1993 lhs_size: lhs_cols,
1994 rhs_axis: 0,
1995 rhs_size: rhs_rows,
1996 },
1997 ));
1998 }
1999 self.dot_general(
2000 other,
2001 DotGeneralConfig {
2002 lhs_contracting_dims: vec![1],
2003 rhs_contracting_dims: vec![0],
2004 lhs_batch_dims: vec![],
2005 rhs_batch_dims: vec![],
2006 },
2007 )
2008 }
2009
2010 /// Sum over the given axes.
2011 ///
2012 /// # Examples
2013 ///
2014 /// ```rust
2015 /// # use tenferro_runtime::TracedTensor;
2016 /// # let x = TracedTensor::from_vec_col_major(vec![2, 2], vec![1.0_f64; 4]).unwrap();
2017 /// let total = x.reduce_sum(None)?;
2018 /// let rows = x.reduce_sum(Some(&[1]))?;
2019 /// let identity = x.reduce_sum(Some(&[]))?;
2020 /// assert_eq!(total.rank, 0);
2021 /// assert_eq!(rows.rank, 1);
2022 /// assert_eq!(identity.rank, 2);
2023 /// # Ok::<(), tenferro_runtime::Error>(())
2024 /// ```
2025 ///
2026 /// # Errors
2027 ///
2028 /// Returns [`Error::Validation`] with `AxisOutOfBounds` when an axis is
2029 /// outside the input rank or `DuplicateAxis` when `axes` repeats an axis,
2030 /// or [`Error::RuntimeStateSource`] when output metadata cannot be
2031 /// registered.
2032 pub fn reduce_sum(&self, axes: Option<&[usize]>) -> Result<TracedTensor> {
2033 let axes = axes.map_or_else(|| (0..self.rank).collect(), <[usize]>::to_vec);
2034 let (out_rank, out_shape_hint) =
2035 reduction_output_meta(self, &axes, "TracedTensor::reduce_sum")?;
2036 apply_unary(
2037 StdTensorOp::ReduceSum { axes },
2038 self,
2039 out_rank,
2040 out_shape_hint,
2041 )
2042 }
2043
2044 /// Sum elementwise squares over the requested axes.
2045 ///
2046 /// Each value is squared in its input dtype before reduction. The initial
2047 /// supported dtypes are `f32` and `f64`; other dtypes return a typed
2048 /// unsupported error during execution. Passing an empty axis slice returns
2049 /// the elementwise square without reducing rank.
2050 ///
2051 /// This operation is useful when the squared sum is needed directly. Use
2052 /// the linalg norm APIs when a square root or complex magnitude semantics
2053 /// are required.
2054 ///
2055 /// # Errors
2056 ///
2057 /// Returns a typed validation error for invalid axes or a typed
2058 /// runtime-state error while registering output metadata.
2059 ///
2060 /// # Deferred errors
2061 ///
2062 /// Unsupported dtypes and backend execution failures are reported when the
2063 /// compiled graph is executed.
2064 /// # Examples
2065 ///
2066 /// ```rust
2067 /// # use tenferro_runtime::TracedTensor;
2068 /// # let x = TracedTensor::from_vec_col_major(
2069 /// # vec![2, 2],
2070 /// # vec![1.0_f64, 2.0, 3.0, 4.0],
2071 /// # )?;
2072 /// let squares = x.reduce_sum_squares(&[1])?;
2073 /// assert_eq!(squares.rank, 1);
2074 /// # Ok::<(), tenferro_runtime::Error>(())
2075 /// ```
2076 pub fn reduce_sum_squares(&self, axes: &[usize]) -> Result<TracedTensor> {
2077 let (out_rank, out_shape_hint) =
2078 reduction_output_meta(self, axes, "TracedTensor::reduce_sum_squares")?;
2079 apply_unary(
2080 StdTensorOp::ReduceSumSquares {
2081 axes: axes.to_vec(),
2082 },
2083 self,
2084 out_rank,
2085 out_shape_hint,
2086 )
2087 }
2088
2089 /// Reduce by taking the maximum along the given axes.
2090 ///
2091 /// Used by tropical (max-plus) compositions: a max-plus reduction over
2092 /// an axis is `ReduceMax` on that axis.
2093 ///
2094 /// # Examples
2095 ///
2096 /// ```rust
2097 /// # use tenferro_runtime::TracedTensor;
2098 /// # let x = TracedTensor::from_vec_col_major(vec![2, 2], vec![1.0_f64; 4]).unwrap();
2099 /// let y = x.reduce_max(Some(&[0]))?;
2100 /// # Ok::<(), tenferro_runtime::Error>(())
2101 /// ```
2102 ///
2103 /// # Errors
2104 ///
2105 /// Returns [`Error::Validation`] with `AxisOutOfBounds` when an axis is
2106 /// outside the input rank or `DuplicateAxis` when `axes` repeats an axis,
2107 /// [`Error::Unsupported`] when a non-empty maximum reduction receives a
2108 /// complex dtype, or [`Error::RuntimeStateSource`] when output metadata
2109 /// cannot be registered.
2110 pub fn reduce_max(&self, axes: Option<&[usize]>) -> Result<TracedTensor> {
2111 let axes = axes.map_or_else(|| (0..self.rank).collect(), <[usize]>::to_vec);
2112 let (out_rank, out_shape_hint) =
2113 reduction_output_meta(self, &axes, "TracedTensor::reduce_max")?;
2114 try_apply_unary(
2115 StdTensorOp::ReduceMax { axes },
2116 self,
2117 out_rank,
2118 out_shape_hint,
2119 "TracedTensor::reduce_max",
2120 )
2121 }
2122
2123 /// Reduce by taking the minimum along the given axes.
2124 ///
2125 /// Used by tropical (min-plus) compositions: a min-plus reduction over
2126 /// an axis is `ReduceMin` on that axis.
2127 ///
2128 /// # Examples
2129 ///
2130 /// ```rust
2131 /// # use tenferro_runtime::TracedTensor;
2132 /// # let x = TracedTensor::from_vec_col_major(vec![2, 2], vec![1.0_f64; 4]).unwrap();
2133 /// let y = x.reduce_min(Some(&[0]))?;
2134 /// # Ok::<(), tenferro_runtime::Error>(())
2135 /// ```
2136 ///
2137 /// # Errors
2138 ///
2139 /// Returns [`Error::Validation`] with `AxisOutOfBounds` when an axis is
2140 /// outside the input rank or `DuplicateAxis` when `axes` repeats an axis,
2141 /// [`Error::Unsupported`] when a non-empty minimum reduction receives a
2142 /// complex dtype, or [`Error::RuntimeStateSource`] when output metadata
2143 /// cannot be registered.
2144 pub fn reduce_min(&self, axes: Option<&[usize]>) -> Result<TracedTensor> {
2145 let axes = axes.map_or_else(|| (0..self.rank).collect(), <[usize]>::to_vec);
2146 let (out_rank, out_shape_hint) =
2147 reduction_output_meta(self, &axes, "TracedTensor::reduce_min")?;
2148 try_apply_unary(
2149 StdTensorOp::ReduceMin { axes },
2150 self,
2151 out_rank,
2152 out_shape_hint,
2153 "TracedTensor::reduce_min",
2154 )
2155 }
2156
2157 /// Reduce by taking the product along the given axes.
2158 ///
2159 /// # Examples
2160 ///
2161 /// ```rust
2162 /// # use tenferro_runtime::TracedTensor;
2163 /// # let x = TracedTensor::from_vec_col_major(vec![2, 2], vec![1.0_f64; 4]).unwrap();
2164 /// let y = x.reduce_prod(Some(&[0]))?;
2165 /// # Ok::<(), tenferro_runtime::Error>(())
2166 /// ```
2167 ///
2168 /// # Errors
2169 ///
2170 /// Returns [`Error::Validation`] with `AxisOutOfBounds` when an axis is
2171 /// outside the input rank or `DuplicateAxis` when `axes` repeats an axis,
2172 /// or [`Error::RuntimeStateSource`] when output metadata cannot be
2173 /// registered.
2174 pub fn reduce_prod(&self, axes: Option<&[usize]>) -> Result<TracedTensor> {
2175 let axes = axes.map_or_else(|| (0..self.rank).collect(), <[usize]>::to_vec);
2176 let (out_rank, out_shape_hint) =
2177 reduction_output_meta(self, &axes, "TracedTensor::reduce_prod")?;
2178 apply_unary(
2179 StdTensorOp::ReduceProd { axes },
2180 self,
2181 out_rank,
2182 out_shape_hint,
2183 )
2184 }
2185
2186 /// Reshape without changing element order.
2187 ///
2188 /// # Examples
2189 ///
2190 /// ```rust
2191 /// # use tenferro_runtime::TracedTensor;
2192 /// # let x = TracedTensor::from_vec_col_major(vec![4], vec![1.0_f64; 4]).unwrap();
2193 /// for y in [x.reshape([2, 2])?, x.reshape(vec![2, 2])?, x.reshape(&[2, 2][..])?] {
2194 /// assert_eq!(y.try_concrete_shape(), Some(vec![2, 2]));
2195 /// }
2196 /// assert!(x.reshape([3]).is_err());
2197 /// # Ok::<(), tenferro_runtime::Error>(())
2198 /// ```
2199 ///
2200 /// # Errors
2201 ///
2202 /// Returns [`Error::Validation`] with `ShapeMismatch::ReshapeElementCount`
2203 /// when a concrete input has a different element count, or
2204 /// `IntegerOverflow` when the target shape product overflows `usize`.
2205 pub fn reshape(&self, shape: impl IntoShapeVec) -> Result<TracedTensor> {
2206 let shape = shape.into_shape_vec();
2207 validate_concrete_reshape_shape(self, &shape)?;
2208 apply_unary_with_dtype(
2209 StdTensorOp::Reshape {
2210 to_shape: DimExpr::from_concrete(&shape),
2211 },
2212 self,
2213 shape.len(),
2214 Some(shape.iter().copied().map(SymDim::from).collect()),
2215 self.dtype,
2216 )
2217 }
2218
2219 /// Return a symbolic expression for the size of one axis, suitable as
2220 /// an `InputDim`-style reference when composing with
2221 /// [`TracedTensor::reshape_sym`].
2222 ///
2223 /// Semantics: if this tensor's `shape_hint` has a symbolic
2224 /// (non-constant) entry for `axis`, that entry is returned
2225 /// verbatim. Otherwise — including when `shape_hint[axis]` is a
2226 /// concrete `SymDim::Concrete(n)` — a
2227 /// `SymDim::tensor_axis(self.id, axis)` reference is returned so the
2228 /// resulting graph remains shape-polymorphic if the same graph is
2229 /// later evaluated against a differently-shaped binding.
2230 ///
2231 /// For a canonical "what is the size of this axis?" query that
2232 /// reports the concrete size when it is known, prefer
2233 /// [`Self::axis_sym_dim`].
2234 ///
2235 /// # Examples
2236 ///
2237 /// ```rust
2238 /// # use tenferro_runtime::TracedTensor;
2239 /// # let x = TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64; 6]).unwrap();
2240 /// let rows = x.sym_size(0)?;
2241 /// let cols = x.sym_size(1)?;
2242 /// let y = x.reshape_sym(&[rows * cols]).unwrap();
2243 /// # Ok::<(), tenferro_runtime::Error>(())
2244 /// ```
2245 ///
2246 /// # Errors
2247 ///
2248 /// Returns [`Error::Validation`] with `AxisOutOfBounds` when `axis` is
2249 /// outside this tensor's rank.
2250 pub fn sym_size(&self, axis: usize) -> Result<SymDim> {
2251 validate_traced_axis(self, axis, "TracedTensor::sym_size")?;
2252 Ok(self
2253 .shape_hint
2254 .as_ref()
2255 .and_then(|shape| shape.get(axis))
2256 .filter(|dim| dim.constant_value().is_none())
2257 .cloned()
2258 .unwrap_or_else(|| SymDim::tensor_axis(self.id, axis)))
2259 }
2260
2261 /// Return the canonical `SymDim` for `axis` — the concrete
2262 /// `SymDim::Concrete(n)` when the size is known, otherwise a symbolic
2263 /// expression identifying this tensor's axis.
2264 ///
2265 /// Unlike [`Self::sym_size`], this method does **not** rewrite
2266 /// concrete axes into `TensorAxis` references. It is the accessor
2267 /// external composition wrappers should use when building mixed
2268 /// concrete/symbolic target shapes for operations like
2269 /// [`Self::broadcast_in_dim_sym`].
2270 ///
2271 /// # Examples
2272 ///
2273 /// ```
2274 /// use tenferro_tensor::DType;
2275 /// use tenferro_runtime::TracedTensor;
2276 ///
2277 /// let a = TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64; 6]).unwrap();
2278 /// // Concrete axis: reports the constant size.
2279 /// assert_eq!(a.axis_sym_dim(0).unwrap().constant_value(), Some(2));
2280 ///
2281 /// let b = TracedTensor::input_symbolic_shape(DType::F64, 2).unwrap();
2282 /// // Fully symbolic leaf: reports a TensorAxis reference.
2283 /// assert!(b.axis_sym_dim(0).unwrap().constant_value().is_none());
2284 /// ```
2285 ///
2286 /// # Errors
2287 ///
2288 /// Returns [`Error::Validation`] with `AxisOutOfBounds` when `axis` is
2289 /// outside this tensor's rank.
2290 pub fn axis_sym_dim(&self, axis: usize) -> Result<SymDim> {
2291 validate_traced_axis(self, axis, "TracedTensor::axis_sym_dim")?;
2292 match self.shape_hint.as_ref().and_then(|shape| shape.get(axis)) {
2293 Some(dim) => Ok(dim.clone()),
2294 None => Ok(SymDim::tensor_axis(self.id, axis)),
2295 }
2296 }
2297
2298 /// Return the full symbolic shape of this tensor when a `shape_hint`
2299 /// is present.
2300 ///
2301 /// Returns `None` for fully-symbolic placeholders produced via
2302 /// [`Self::input_symbolic_shape`] (where `shape_hint` is intentionally
2303 /// absent). For those, build the shape axis-by-axis via
2304 /// [`Self::axis_sym_dim`].
2305 ///
2306 /// # Examples
2307 ///
2308 /// ```
2309 /// use tenferro_tensor::DType;
2310 /// use tenferro_runtime::TracedTensor;
2311 ///
2312 /// let a = TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64; 6]).unwrap();
2313 /// assert!(a.sym_shape().is_some());
2314 /// assert_eq!(a.sym_shape().unwrap().len(), 2);
2315 ///
2316 /// let b = TracedTensor::input_symbolic_shape(DType::F64, 2).unwrap();
2317 /// assert!(b.sym_shape().is_none());
2318 /// ```
2319 pub fn sym_shape(&self) -> Option<&[SymDim]> {
2320 self.shape_hint.as_deref()
2321 }
2322
2323 /// Reshape using symbolic dimensions derived from traced tensor axes.
2324 ///
2325 /// # Examples
2326 ///
2327 /// ```rust
2328 /// # use tenferro_runtime::TracedTensor;
2329 /// # let x = TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64; 6]).unwrap();
2330 /// let rows = x.sym_size(0)?;
2331 /// let cols = x.sym_size(1)?;
2332 /// let y = x.reshape_sym(&[rows * cols]).unwrap();
2333 /// # Ok::<(), tenferro_runtime::Error>(())
2334 /// ```
2335 ///
2336 /// # Errors
2337 ///
2338 /// Returns [`Error::SymbolicShapeConversion`] when a supplied symbolic
2339 /// dimension cannot be mapped to this graph, or [`Error::RuntimeStateSource`]
2340 /// when result metadata cannot be registered.
2341 ///
2342 /// # Deferred errors
2343 ///
2344 /// Element-count compatibility for symbolic dimensions is checked when
2345 /// concrete inputs reach compilation or execution. A mismatch is returned
2346 /// as [`Error::TensorRuntime`] with a typed `ShapeMismatch` source.
2347 pub fn reshape_sym(&self, shape: &[SymDim]) -> Result<TracedTensor> {
2348 let tensor_map = [(self.id, 0usize)];
2349 let to_shape = shape
2350 .iter()
2351 .map(|dim| {
2352 dim.to_dim_expr(&tensor_map)
2353 .map_err(|source| Error::SymbolicShapeConversion {
2354 op: "TracedTensor::reshape_sym",
2355 phase: ErrorPhase::GraphBuild,
2356 source,
2357 })
2358 })
2359 .collect::<Result<Vec<_>>>()?;
2360 let out_shape_hint = Some(shape.to_vec());
2361 apply_unary(
2362 StdTensorOp::Reshape { to_shape },
2363 self,
2364 shape.len(),
2365 out_shape_hint,
2366 )
2367 }
2368
2369 /// Broadcast into a larger shape with explicit dimension placement.
2370 ///
2371 /// # Examples
2372 ///
2373 /// ```rust
2374 /// # use tenferro_runtime::TracedTensor;
2375 /// # let x = TracedTensor::from_vec_col_major(vec![3], vec![1.0_f64; 3]).unwrap();
2376 /// let y = x.broadcast_in_dim(&[2, 3], &[1])?;
2377 /// # Ok::<(), tenferro_runtime::Error>(())
2378 /// ```
2379 ///
2380 /// # Errors
2381 ///
2382 /// Returns [`Error::Validation`] with `RankMismatch` when `dims` does not
2383 /// have one entry per input axis, `AxisOutOfBounds` or `DuplicateAxis` for
2384 /// an invalid output mapping, or `InvalidArgument` when known dimensions
2385 /// cannot broadcast. [`Error::RuntimeStateSource`] reports failure to
2386 /// register the result metadata.
2387 pub fn broadcast_in_dim(&self, shape: &[usize], dims: &[usize]) -> Result<TracedTensor> {
2388 let out_shape_hint: Vec<SymDim> = shape.iter().copied().map(SymDim::from).collect();
2389 validate_broadcast_in_dim_args(
2390 self,
2391 &out_shape_hint,
2392 dims,
2393 "TracedTensor::broadcast_in_dim",
2394 )?;
2395 apply_unary(
2396 StdTensorOp::BroadcastInDim {
2397 shape: DimExpr::from_concrete(shape),
2398 dims: dims.to_vec(),
2399 },
2400 self,
2401 shape.len(),
2402 Some(out_shape_hint),
2403 )
2404 }
2405
2406 /// Broadcast into a symbolic target shape with explicit dimension
2407 /// placement.
2408 ///
2409 /// Unlike [`Self::broadcast_in_dim`], each axis of `shape` is a
2410 /// [`SymDim`], so the target shape can mix concrete sizes (via
2411 /// `SymDim::from(n)`) with symbolic references to this tensor's axes
2412 /// (via [`Self::axis_sym_dim`]) or to axes of other traced tensors.
2413 ///
2414 /// When `shape` contains a `SymDim` that references a traced tensor
2415 /// other than `self`, the referenced tensor(s) must be supplied in
2416 /// `shape_refs`. They are wired into the built op as auxiliary
2417 /// shape-reference inputs — the op does not read their data, only
2418 /// their runtime shape. `shape_refs` must be listed in the same order
2419 /// in which their tensor IDs first appear when walking `shape` after
2420 /// any references to `self`. Usually the simplest correct thing is to
2421 /// pass each unique non-self reference tensor once.
2422 ///
2423 /// # Examples
2424 ///
2425 /// ```
2426 /// use tenferro_runtime::TracedTensor;
2427 ///
2428 /// let a = TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64; 6]).unwrap();
2429 /// let b = TracedTensor::from_vec_col_major(vec![3, 4], vec![1.0_f64; 12]).unwrap();
2430 /// let m = a.axis_sym_dim(0)?;
2431 /// let k = a.axis_sym_dim(1)?;
2432 /// let n = b.axis_sym_dim(1)?;
2433 /// // Broadcast `a[m, k]` to `[m, k, n]`, placing `a`'s axes at 0, 1
2434 /// // and taking `n` from `b` as an auxiliary shape reference.
2435 /// let a_b = a.broadcast_in_dim_sym(&[m, k, n], &[0, 1], &[&b])?;
2436 /// assert_eq!(a_b.rank, 3);
2437 /// # Ok::<(), tenferro_runtime::Error>(())
2438 /// ```
2439 ///
2440 /// # Errors
2441 ///
2442 /// Returns [`Error::Validation`] with `RankMismatch`, `AxisOutOfBounds`,
2443 /// `DuplicateAxis`, or `InvalidArgument` when the output mapping or shape
2444 /// references are invalid, [`Error::SymbolicShapeConversion`] for an
2445 /// unmappable symbolic dimension, or [`Error::RuntimeStateSource`] when
2446 /// metadata cannot be registered.
2447 ///
2448 /// # Deferred errors
2449 ///
2450 /// If a symbolic output dimension is smaller than a non-unit input axis,
2451 /// the concrete broadcast check is deferred to compilation or execution
2452 /// and is returned as [`Error::TensorRuntime`] with a typed validation
2453 /// source.
2454 pub fn broadcast_in_dim_sym(
2455 &self,
2456 shape: &[SymDim],
2457 dims: &[usize],
2458 shape_refs: &[&TracedTensor],
2459 ) -> Result<TracedTensor> {
2460 validate_broadcast_in_dim_args(self, shape, dims, "TracedTensor::broadcast_in_dim_sym")?;
2461
2462 // Build a dedup'd list of shape-reference tensors (first occurrence
2463 // wins) and index them starting at 1 — the primary input `self`
2464 // is at 0.
2465 let mut dedup_refs: Vec<&TracedTensor> = Vec::with_capacity(shape_refs.len());
2466 let mut tensor_map: Vec<(u64, usize)> = vec![(self.id, 0)];
2467 for &t in shape_refs {
2468 if !tensor_map.iter().any(|(id, _)| *id == t.id) {
2469 let idx = tensor_map.len();
2470 tensor_map.push((t.id, idx));
2471 dedup_refs.push(t);
2472 }
2473 }
2474
2475 let to_shape: Vec<DimExpr> = shape
2476 .iter()
2477 .map(|dim| {
2478 dim.to_dim_expr(&tensor_map)
2479 .map_err(|source| Error::SymbolicShapeConversion {
2480 op: "broadcast_in_dim_sym",
2481 phase: ErrorPhase::GraphBuild,
2482 source,
2483 })
2484 })
2485 .collect::<Result<Vec<_>>>()?;
2486
2487 // Trim auxiliary shape-reference inputs down to those actually
2488 // used by the generated `DimExpr`s. If the target shape resolved
2489 // to all constants (the concrete-shape case) the op is a plain
2490 // unary broadcast with no extra parents. Otherwise the op needs
2491 // a contiguous prefix of shape-ref inputs covering every
2492 // referenced `input_idx`.
2493 let max_used_idx = DimExpr::max_input_idx_all(&to_shape).unwrap_or(0);
2494 let used_refs: Vec<&TracedTensor> = dedup_refs.into_iter().take(max_used_idx).collect();
2495
2496 let out_shape_hint = Some(shape.to_vec());
2497 apply_unary_with_shape_refs(
2498 StdTensorOp::BroadcastInDim {
2499 shape: to_shape,
2500 dims: dims.to_vec(),
2501 },
2502 self,
2503 &used_refs,
2504 shape.len(),
2505 out_shape_hint,
2506 )
2507 }
2508
2509 /// Slice with explicit start, limit, and stride per axis.
2510 ///
2511 /// # Errors
2512 ///
2513 /// Returns [`Error::Validation`] with `RankMismatch` when the start/limit/
2514 /// stride vectors do not match the input rank, `InvalidSliceStep` when a
2515 /// stride is zero, `InvalidSliceBounds` when a limit precedes its start,
2516 /// or [`Error::RuntimeStateSource`] when output metadata cannot be
2517 /// registered.
2518 pub fn slice(&self, config: SliceConfig) -> Result<TracedTensor> {
2519 let op = StdTensorOp::Slice(config);
2520 let (out_rank, out_shape_hint) =
2521 infer_traced_single_output_shape("TracedTensor::slice", &op, &[self])?;
2522 apply_unary(op, self, out_rank, out_shape_hint)
2523 }
2524
2525 /// Pad with zeros using StableHLO-style edge and interior padding.
2526 ///
2527 /// # Errors
2528 ///
2529 /// Returns [`Error::Validation`] with `RankMismatch` when padding vectors
2530 /// do not match the input rank, `InvalidArgument` for negative interior
2531 /// padding, or `IntegerOverflow` when the padded extent exceeds `usize`.
2532 /// [`Error::RuntimeStateSource`] is returned when output metadata cannot be
2533 /// registered.
2534 pub fn pad(&self, config: PadConfig) -> Result<TracedTensor> {
2535 let op = StdTensorOp::Pad(config);
2536 let (out_rank, out_shape_hint) =
2537 infer_traced_single_output_shape("TracedTensor::pad", &op, &[self])?;
2538 apply_unary(op, self, out_rank, out_shape_hint)
2539 }
2540
2541 /// Reverse the order of elements along the requested axes.
2542 ///
2543 /// # Errors
2544 ///
2545 /// Returns [`Error::Validation`] with `AxisOutOfBounds` when an axis is
2546 /// outside the input rank or `DuplicateAxis` when `axes` repeats one, or
2547 /// [`Error::RuntimeStateSource`] when result metadata cannot be
2548 /// registered.
2549 pub fn reverse(&self, axes: &[usize]) -> Result<TracedTensor> {
2550 validate_traced_axes(self.rank, axes, "TracedTensor::reverse")?;
2551 apply_unary(
2552 StdTensorOp::Reverse {
2553 axes: axes.to_vec(),
2554 },
2555 self,
2556 self.rank,
2557 self.shape_hint.clone(),
2558 )
2559 }
2560
2561 /// Gather slices from `self` using integer start indices.
2562 ///
2563 /// # Errors
2564 ///
2565 /// Returns [`Error::Validation`] with `RankMismatch`, `AxisOutOfBounds`,
2566 /// `DuplicateAxis`, or `ShapeMismatch` when indices or the gather
2567 /// configuration is incompatible with the input, and
2568 /// [`Error::RuntimeStateSource`] when output metadata cannot be
2569 /// registered.
2570 ///
2571 /// # Deferred errors
2572 ///
2573 /// Runtime index values are checked after binding. An out-of-range index
2574 /// is returned as [`Error::TensorRuntime`] with the backend's typed
2575 /// validation source and [`ErrorPhase::Execution`].
2576 pub fn gather(&self, indices: &TracedTensor, config: GatherConfig) -> Result<TracedTensor> {
2577 let op = StdTensorOp::Gather(config);
2578 let (out_rank, out_shape_hint) =
2579 infer_traced_single_output_shape("TracedTensor::gather", &op, &[self, indices])?;
2580 apply_binary_preserve_input_dtypes(op, self, indices, out_rank, out_shape_hint, self.dtype)
2581 }
2582
2583 /// Scatter updates into `self` using StableHLO scatter semantics.
2584 ///
2585 /// # Errors
2586 ///
2587 /// Returns [`Error::Validation`] with `RankMismatch`, `AxisOutOfBounds`,
2588 /// `DuplicateAxis`, or `ShapeMismatch` when indices, updates, or the
2589 /// scatter configuration is incompatible, [`Error::TensorRuntime`] with
2590 /// `UnsupportedDTypeConversion` when dtype promotion cannot be
2591 /// represented, or [`Error::RuntimeStateSource`] when output metadata
2592 /// cannot be registered.
2593 ///
2594 /// # Deferred errors
2595 ///
2596 /// Runtime index/update values are checked after binding. An invalid
2597 /// index or update shape is returned as [`Error::TensorRuntime`] with its
2598 /// typed validation source and [`ErrorPhase::Execution`].
2599 pub fn scatter(
2600 &self,
2601 indices: &TracedTensor,
2602 updates: &TracedTensor,
2603 config: ScatterConfig,
2604 ) -> Result<TracedTensor> {
2605 let op = StdTensorOp::Scatter(config);
2606 let (out_rank, out_shape_hint) = infer_traced_single_output_shape(
2607 "TracedTensor::scatter",
2608 &op,
2609 &[self, indices, updates],
2610 )?;
2611 let out_dtype = crate::shape_infer::promote_dtype(self.dtype, updates.dtype);
2612 let operand = if self.dtype != out_dtype {
2613 self.cast(out_dtype)?
2614 } else {
2615 self.clone()
2616 };
2617 let updates = if updates.dtype != out_dtype {
2618 updates.cast(out_dtype)?
2619 } else {
2620 updates.clone()
2621 };
2622 apply_ternary_with_output_dtype(
2623 op,
2624 &operand,
2625 indices,
2626 &updates,
2627 out_rank,
2628 out_shape_hint,
2629 out_dtype,
2630 )
2631 }
2632
2633 /// Slice using runtime start indices.
2634 ///
2635 /// # Errors
2636 ///
2637 /// Returns [`Error::Validation`] with `RankMismatch`, `AxisOutOfBounds`,
2638 /// or `InvalidArgument` when `starts` or `sizes` has an incompatible rank
2639 /// or extent, and [`Error::RuntimeStateSource`] when output metadata cannot
2640 /// be registered.
2641 ///
2642 /// # Deferred errors
2643 ///
2644 /// Runtime start values are checked after binding. An out-of-range start
2645 /// is returned as [`Error::TensorRuntime`] with the backend's typed
2646 /// validation source and [`ErrorPhase::Execution`].
2647 pub fn dynamic_slice(&self, starts: &TracedTensor, sizes: &[usize]) -> Result<TracedTensor> {
2648 let op = StdTensorOp::DynamicSlice {
2649 slice_sizes: sizes.to_vec(),
2650 };
2651 let (out_rank, out_shape_hint) =
2652 infer_traced_single_output_shape("TracedTensor::dynamic_slice", &op, &[self, starts])?;
2653 apply_binary_preserve_input_dtypes(op, self, starts, out_rank, out_shape_hint, self.dtype)
2654 }
2655
2656 /// Keep the lower triangle and zero the rest.
2657 ///
2658 /// # Examples
2659 ///
2660 /// ```rust
2661 /// # use tenferro_runtime::TracedTensor;
2662 /// let matrix = TracedTensor::from_vec_col_major(vec![2, 2], vec![1.0_f64; 4])?;
2663 /// let lower = matrix.tril(0)?;
2664 /// assert_eq!(lower.rank, 2);
2665 /// # Ok::<(), tenferro_runtime::Error>(())
2666 /// ```
2667 ///
2668 /// # Errors
2669 ///
2670 /// Returns [`Error::RuntimeStateSource`] when traced output metadata
2671 /// registration is unavailable or inconsistent with the graph.
2672 pub fn tril(&self, k: i64) -> Result<TracedTensor> {
2673 apply_unary(
2674 StdTensorOp::Tril { k },
2675 self,
2676 self.rank,
2677 self.shape_hint.clone(),
2678 )
2679 }
2680
2681 /// Keep the upper triangle and zero the rest.
2682 ///
2683 /// # Examples
2684 ///
2685 /// ```rust
2686 /// # use tenferro_runtime::TracedTensor;
2687 /// let matrix = TracedTensor::from_vec_col_major(vec![2, 2], vec![1.0_f64; 4])?;
2688 /// let upper = matrix.triu(0)?;
2689 /// assert_eq!(upper.rank, 2);
2690 /// # Ok::<(), tenferro_runtime::Error>(())
2691 /// ```
2692 ///
2693 /// # Errors
2694 ///
2695 /// Returns [`Error::RuntimeStateSource`] when traced output metadata
2696 /// registration is unavailable or inconsistent with the graph.
2697 pub fn triu(&self, k: i64) -> Result<TracedTensor> {
2698 apply_unary(
2699 StdTensorOp::Triu { k },
2700 self,
2701 self.rank,
2702 self.shape_hint.clone(),
2703 )
2704 }
2705
2706 /// Permute tensor axes.
2707 ///
2708 /// # Examples
2709 ///
2710 /// ```rust
2711 /// # use tenferro_runtime::TracedTensor;
2712 /// # let x = TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64; 6]).unwrap();
2713 /// let y = x.transpose(&[1, 0])?;
2714 /// # Ok::<(), tenferro_runtime::Error>(())
2715 /// ```
2716 ///
2717 /// # Errors
2718 ///
2719 /// Returns [`Error::Validation`] with `InvalidPermutationLength`,
2720 /// `AxisOutOfBounds`, or `DuplicateAxis` when `perm` is not a valid
2721 /// permutation of the tensor axes, or [`Error::RuntimeStateSource`] when
2722 /// output metadata registration fails.
2723 pub fn transpose(&self, perm: &[usize]) -> Result<TracedTensor> {
2724 validate_traced_perm(self.rank, perm, "TracedTensor::transpose")?;
2725 let out_shape_hint = self
2726 .shape_hint
2727 .as_ref()
2728 .map(|shape| perm.iter().map(|&p| shape[p].clone()).collect());
2729 apply_unary(
2730 StdTensorOp::Transpose {
2731 perm: perm.to_vec(),
2732 },
2733 self,
2734 self.rank,
2735 out_shape_hint,
2736 )
2737 }
2738
2739 /// Extract the diagonal along two axes.
2740 ///
2741 /// # Examples
2742 ///
2743 /// ```rust
2744 /// # use tenferro_runtime::TracedTensor;
2745 /// # let x = TracedTensor::from_vec_col_major(vec![2, 2], vec![1.0_f64; 4]).unwrap();
2746 /// let y = x.extract_diag(0, 1)?;
2747 /// # Ok::<(), tenferro_runtime::Error>(())
2748 /// ```
2749 ///
2750 /// # Errors
2751 ///
2752 /// Returns [`Error::Validation`] with `AxisOutOfBounds` when either axis
2753 /// is outside the input rank or `InvalidArgument` when `axis_a == axis_b`.
2754 pub fn extract_diag(&self, axis_a: usize, axis_b: usize) -> Result<TracedTensor> {
2755 validate_traced_axis(self, axis_a, "TracedTensor::extract_diag")?;
2756 validate_traced_axis(self, axis_b, "TracedTensor::extract_diag")?;
2757 if axis_a == axis_b {
2758 return Err(graph_invalid_argument(
2759 "TracedTensor::extract_diag",
2760 "axes",
2761 "diagonal axes must be distinct",
2762 ));
2763 }
2764 let op = StdTensorOp::ExtractDiag { axis_a, axis_b };
2765 let (out_rank, out_shape_hint) =
2766 infer_traced_single_output_shape("TracedTensor::extract_diag", &op, &[self])?;
2767 apply_unary(op, self, out_rank, out_shape_hint)
2768 }
2769
2770 /// Embed a vector or lower-rank tensor along a diagonal.
2771 ///
2772 /// # Examples
2773 ///
2774 /// ```rust
2775 /// # use tenferro_runtime::TracedTensor;
2776 /// # let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64; 2]).unwrap();
2777 /// let y = x.embed_diag(0, 1)?;
2778 /// # Ok::<(), tenferro_runtime::Error>(())
2779 /// ```
2780 ///
2781 /// # Errors
2782 ///
2783 /// Returns [`Error::Validation`] with `AxisOutOfBounds` when `axis_a` is
2784 /// outside the input rank or `InvalidArgument` when `axis_b` is not a
2785 /// valid insertion axis.
2786 pub fn embed_diag(&self, axis_a: usize, axis_b: usize) -> Result<TracedTensor> {
2787 validate_traced_axis(self, axis_a, "TracedTensor::embed_diag")?;
2788 validate_traced_insert_axis(self.rank, axis_b, "TracedTensor::embed_diag")?;
2789 let out_shape_hint = self.shape_hint.as_ref().map(|shape| {
2790 let mut out_shape = shape.clone();
2791 out_shape.insert(axis_b, shape[axis_a].clone());
2792 out_shape
2793 });
2794 apply_unary(
2795 StdTensorOp::EmbedDiag { axis_a, axis_b },
2796 self,
2797 self.rank + 1,
2798 out_shape_hint,
2799 )
2800 }
2801
2802 /// Return the runtime size of one axis as a scalar `f64` tensor.
2803 ///
2804 /// The result is metadata-derived and therefore has no gradient.
2805 ///
2806 /// # Examples
2807 ///
2808 /// ```
2809 /// use tenferro_cpu::CpuBackend;
2810 /// use tenferro_runtime::{GraphCompiler, Runtime, TracedTensor};
2811 ///
2812 /// let x = TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap();
2813 /// let cols = x.shape_of(1)?;
2814 /// let mut compiler = GraphCompiler::new();
2815 /// let program = compiler.compile(&cols).unwrap();
2816 /// let backend = CpuBackend::new();
2817 /// let mut builder = Runtime::builder();
2818 /// builder
2819 /// .register_engine(tenferro_cpu::runtime_engine_registration(&backend).unwrap())
2820 /// .unwrap();
2821 /// let runtime = builder.build().unwrap();
2822 /// let outputs = runtime.run_compiled(&program, &[]).unwrap();
2823 /// let out = &outputs[0];
2824 /// assert_eq!(out.shape(), &[] as &[usize]);
2825 /// # Ok::<(), tenferro_runtime::Error>(())
2826 /// ```
2827 ///
2828 /// # Errors
2829 ///
2830 /// Returns [`Error::Validation`] with `AxisOutOfBounds` when `axis` is
2831 /// outside the input rank, or [`Error::RuntimeStateSource`] when scalar
2832 /// output metadata cannot be registered.
2833 pub fn shape_of(&self, axis: usize) -> Result<TracedTensor> {
2834 validate_traced_axis(self, axis, "TracedTensor::shape_of")?;
2835 apply_unary_with_dtype(
2836 StdTensorOp::ShapeOf { axis },
2837 self,
2838 0,
2839 Some(vec![]),
2840 DType::F64,
2841 )
2842 }
2843
2844 /// Truncate this tensor along `axis` to the first `size` elements.
2845 ///
2846 /// `size` is read at runtime from a scalar traced tensor. Values are
2847 /// rounded to the nearest integer, clamped to `[0, self.shape[axis]]`,
2848 /// and the output keeps the same element dtype as the input.
2849 ///
2850 /// # Examples
2851 ///
2852 /// ```
2853 /// use tenferro_cpu::CpuBackend;
2854 /// use tenferro_runtime::{GraphCompiler, Runtime, TracedTensor};
2855 ///
2856 /// let x = TracedTensor::from_vec_col_major(vec![4], vec![1.0_f64, 2.0, 3.0, 4.0]).unwrap();
2857 /// let size = TracedTensor::from_vec_col_major(vec![], vec![2.0_f64]).unwrap();
2858 /// let y = x.dynamic_truncate(&size, 0)?;
2859 /// let mut compiler = GraphCompiler::new();
2860 /// let program = compiler.compile(&y).unwrap();
2861 /// let backend = CpuBackend::new();
2862 /// let mut builder = Runtime::builder();
2863 /// builder
2864 /// .register_engine(tenferro_cpu::runtime_engine_registration(&backend).unwrap())
2865 /// .unwrap();
2866 /// let runtime = builder.build().unwrap();
2867 /// let outputs = runtime.run_compiled(&program, &[]).unwrap();
2868 /// let out = &outputs[0];
2869 /// assert_eq!(out.shape(), &[2]);
2870 /// # Ok::<(), tenferro_runtime::Error>(())
2871 /// ```
2872 ///
2873 /// # Errors
2874 ///
2875 /// Returns [`Error::Validation`] with `AxisOutOfBounds` when `axis` is
2876 /// outside the input rank or `RankMismatch` when `size` is not scalar.
2877 ///
2878 /// # Deferred errors
2879 ///
2880 /// At execution, non-`f32`/`f64`/`i64` size dtypes return
2881 /// [`Error::TensorRuntime`] with `Unsupported`, non-finite size values
2882 /// return a typed `InvalidArgument`, and an empty scalar buffer returns a
2883 /// typed runtime-state source.
2884 pub fn dynamic_truncate(&self, size: &TracedTensor, axis: usize) -> Result<TracedTensor> {
2885 validate_traced_axis(self, axis, "TracedTensor::dynamic_truncate")?;
2886 if size.rank != 0 {
2887 return Err(graph_validation(
2888 "TracedTensor::dynamic_truncate",
2889 ValidationError::RankMismatch {
2890 expected: 0,
2891 actual: size.rank,
2892 },
2893 ));
2894 }
2895 apply_binary_preserve_input_dtypes(
2896 StdTensorOp::DynamicTruncate { axis },
2897 self,
2898 size,
2899 self.rank,
2900 None,
2901 self.dtype,
2902 )
2903 }
2904
2905 /// Pad this tensor with zeros along `axis` to match `reference.shape[axis]`.
2906 ///
2907 /// If `reference` is smaller along that axis, this is a no-op.
2908 ///
2909 /// # Examples
2910 ///
2911 /// ```
2912 /// use tenferro_cpu::CpuBackend;
2913 /// use tenferro_runtime::{GraphCompiler, Runtime, TracedTensor};
2914 ///
2915 /// let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
2916 /// let reference = TracedTensor::from_vec_col_major(vec![4], vec![0.0_f64, 0.0, 0.0, 0.0]).unwrap();
2917 /// let y = x.pad_to_match(&reference, 0)?;
2918 /// let mut compiler = GraphCompiler::new();
2919 /// let program = compiler.compile(&y).unwrap();
2920 /// let backend = CpuBackend::new();
2921 /// let mut builder = Runtime::builder();
2922 /// builder
2923 /// .register_engine(tenferro_cpu::runtime_engine_registration(&backend).unwrap())
2924 /// .unwrap();
2925 /// let runtime = builder.build().unwrap();
2926 /// let outputs = runtime.run_compiled(&program, &[]).unwrap();
2927 /// let out = &outputs[0];
2928 /// assert_eq!(out.shape(), &[4]);
2929 /// # Ok::<(), tenferro_runtime::Error>(())
2930 /// ```
2931 ///
2932 /// # Errors
2933 ///
2934 /// Returns [`Error::Validation`] with `AxisOutOfBounds` when `axis` is
2935 /// outside either tensor's rank, or [`Error::RuntimeStateSource`] when
2936 /// output metadata cannot be registered.
2937 pub fn pad_to_match(&self, reference: &TracedTensor, axis: usize) -> Result<TracedTensor> {
2938 validate_traced_axis(self, axis, "TracedTensor::pad_to_match")?;
2939 validate_traced_axis(reference, axis, "TracedTensor::pad_to_match")?;
2940 let op = StdTensorOp::PadToMatch { axis };
2941 let (out_rank, out_shape_hint) = infer_traced_single_output_shape(
2942 "TracedTensor::pad_to_match",
2943 &op,
2944 &[self, reference],
2945 )?;
2946 apply_binary_preserve_input_dtypes(
2947 op,
2948 self,
2949 reference,
2950 out_rank,
2951 out_shape_hint,
2952 self.dtype,
2953 )
2954 }
2955}
2956
2957pub(crate) fn apply_unary(
2958 op: StdTensorOp,
2959 input: &TracedTensor,
2960 out_rank: usize,
2961 out_shape_hint: Option<Vec<SymDim>>,
2962) -> Result<TracedTensor> {
2963 let out_dtype = try_inferred_output_dtype(&op, &[input.dtype], "apply_unary")?;
2964 apply_unary_with_dtype(op, input, out_rank, out_shape_hint, out_dtype)
2965}
2966
2967fn try_apply_unary(
2968 op: StdTensorOp,
2969 input: &TracedTensor,
2970 out_rank: usize,
2971 out_shape_hint: Option<Vec<SymDim>>,
2972 context: &'static str,
2973) -> Result<TracedTensor> {
2974 let out_dtype = try_inferred_output_dtype(&op, &[input.dtype], context)?;
2975 apply_unary_with_dtype(op, input, out_rank, out_shape_hint, out_dtype)
2976}
2977
2978pub(crate) fn apply_unary_with_dtype(
2979 op: StdTensorOp,
2980 input: &TracedTensor,
2981 out_rank: usize,
2982 out_shape_hint: Option<Vec<SymDim>>,
2983 out_dtype: DType,
2984) -> Result<TracedTensor> {
2985 let mut builder = GraphBuilder::new();
2986 builder.add_parent(input.graph.clone());
2987 let input_ref = ValueRef::External(input.graph.values()[input.val].key.clone());
2988 let outputs = builder.add_operation(op, vec![input_ref], OperationRole::Primary);
2989 builder.set_outputs(outputs.clone());
2990 let graph = Arc::new(builder.build());
2991 let metadata_scope =
2992 register_single_output_metadata(graph.as_ref(), outputs[0], out_dtype, &out_shape_hint)?;
2993
2994 Ok(TracedTensor {
2995 id: next_traced_id(),
2996 rank: out_rank,
2997 dtype: out_dtype,
2998 graph,
2999 val: outputs[0],
3000 data: None,
3001 shape_hint: out_shape_hint,
3002 inputs_map: input.inputs_map.clone(),
3003 leaf_metas: input.leaf_metas.clone(),
3004 extra_roots: input.extra_roots.clone(),
3005 checkpoint_chain: input.checkpoint_chain.clone(),
3006 metadata_scopes: MetadataScopeChain::with_new(metadata_scope, [&input.metadata_scopes]),
3007 constraint_scopes: input.constraint_scopes.clone(),
3008 })
3009}
3010
3011/// Apply a unary-primary op that additionally references one or more
3012/// tensors for shape resolution only.
3013///
3014/// The primary `input` becomes op input 0; each tensor in `shape_refs`
3015/// becomes op input 1, 2, … in order. Used by
3016/// [`TracedTensor::broadcast_in_dim_sym`] when the target shape
3017/// references axes of tensors other than the primary input; the op
3018/// reads only their runtime shape, not their data.
3019pub(crate) fn apply_unary_with_shape_refs(
3020 op: StdTensorOp,
3021 input: &TracedTensor,
3022 shape_refs: &[&TracedTensor],
3023 out_rank: usize,
3024 out_shape_hint: Option<Vec<SymDim>>,
3025) -> Result<TracedTensor> {
3026 let mut builder = GraphBuilder::new();
3027 builder.add_parent(input.graph.clone());
3028 for t in shape_refs {
3029 builder.add_parent(t.graph.clone());
3030 }
3031 let mut op_inputs: Vec<ValueRef<StdTensorOp>> = Vec::with_capacity(1 + shape_refs.len());
3032 op_inputs.push(ValueRef::External(
3033 input.graph.values()[input.val].key.clone(),
3034 ));
3035 for t in shape_refs {
3036 op_inputs.push(ValueRef::External(t.graph.values()[t.val].key.clone()));
3037 }
3038 let outputs = builder.add_operation(op, op_inputs, OperationRole::Primary);
3039 builder.set_outputs(outputs.clone());
3040 let graph = Arc::new(builder.build());
3041 let metadata_scope =
3042 register_single_output_metadata(graph.as_ref(), outputs[0], input.dtype, &out_shape_hint)?;
3043
3044 let inputs_map =
3045 merge_traced_inputs_map(std::iter::once(input).chain(shape_refs.iter().copied()));
3046 let leaf_metas =
3047 merge_traced_leaf_metas(std::iter::once(input).chain(shape_refs.iter().copied()));
3048
3049 let mut extra_roots = input.extra_roots.clone();
3050 for t in shape_refs {
3051 extra_roots.extend(t.extra_roots.iter().cloned());
3052 }
3053
3054 let mut checkpoint_chain = input.checkpoint_chain.clone();
3055 for t in shape_refs {
3056 checkpoint_chain =
3057 CheckpointNode::merge_chains(checkpoint_chain, t.checkpoint_chain.clone());
3058 }
3059
3060 Ok(TracedTensor {
3061 id: next_traced_id(),
3062 rank: out_rank,
3063 dtype: input.dtype,
3064 graph,
3065 val: outputs[0],
3066 data: None,
3067 shape_hint: out_shape_hint,
3068 inputs_map,
3069 leaf_metas,
3070 extra_roots,
3071 checkpoint_chain,
3072 metadata_scopes: MetadataScopeChain::with_new(
3073 metadata_scope,
3074 std::iter::once(&input.metadata_scopes)
3075 .chain(shape_refs.iter().map(|tensor| &tensor.metadata_scopes)),
3076 ),
3077 constraint_scopes: ConstraintScopeChain::merge(
3078 std::iter::once(&input.constraint_scopes)
3079 .chain(shape_refs.iter().map(|tensor| &tensor.constraint_scopes)),
3080 ),
3081 })
3082}
3083
3084pub(crate) fn apply_nullary(
3085 op: StdTensorOp,
3086 rank: usize,
3087 dtype: DType,
3088 shape_hint: Option<Vec<SymDim>>,
3089) -> Result<TracedTensor> {
3090 let mut builder = GraphBuilder::new();
3091 let outputs = builder.add_operation(op, vec![], OperationRole::Primary);
3092 builder.set_outputs(outputs.clone());
3093 let graph = Arc::new(builder.build());
3094 let metadata_scope =
3095 register_single_output_metadata(graph.as_ref(), outputs[0], dtype, &shape_hint)?;
3096
3097 Ok(TracedTensor {
3098 id: next_traced_id(),
3099 rank,
3100 dtype,
3101 graph,
3102 val: outputs[0],
3103 data: None,
3104 shape_hint,
3105 inputs_map: Arc::new(HashMap::new()),
3106 leaf_metas: Arc::new(HashMap::new()),
3107 extra_roots: Vec::new(),
3108 checkpoint_chain: None,
3109 metadata_scopes: MetadataScopeChain::from_scope(metadata_scope),
3110 constraint_scopes: ConstraintScopeChain::empty(),
3111 })
3112}
3113
3114pub(crate) fn apply_binary(
3115 op: StdTensorOp,
3116 lhs: &TracedTensor,
3117 rhs: &TracedTensor,
3118 out_rank: usize,
3119 out_shape_hint: Option<Vec<SymDim>>,
3120) -> Result<TracedTensor> {
3121 let input_dtype = crate::shape_infer::promote_dtype_for_binary_op(&op, lhs.dtype, rhs.dtype);
3122 let out_dtype = try_inferred_output_dtype(&op, &[lhs.dtype, rhs.dtype], "apply_binary")?;
3123
3124 // Insert Convert ops when an input dtype differs from the primitive input dtype.
3125 let lhs = if lhs.dtype != input_dtype {
3126 lhs.cast(input_dtype)?
3127 } else {
3128 lhs.clone()
3129 };
3130 let rhs = if rhs.dtype != input_dtype {
3131 rhs.cast(input_dtype)?
3132 } else {
3133 rhs.clone()
3134 };
3135
3136 apply_binary_with_output_dtype(op, &lhs, &rhs, out_rank, out_shape_hint, out_dtype)
3137}
3138
3139fn try_apply_binary(
3140 op: StdTensorOp,
3141 lhs: &TracedTensor,
3142 rhs: &TracedTensor,
3143 out_rank: usize,
3144 out_shape_hint: Option<Vec<SymDim>>,
3145 context: &'static str,
3146) -> Result<TracedTensor> {
3147 let input_dtype = crate::shape_infer::promote_dtype_for_binary_op(&op, lhs.dtype, rhs.dtype);
3148 let out_dtype = try_inferred_output_dtype(&op, &[lhs.dtype, rhs.dtype], context)?;
3149
3150 let lhs = if lhs.dtype != input_dtype {
3151 lhs.cast(input_dtype)?
3152 } else {
3153 lhs.clone()
3154 };
3155 let rhs = if rhs.dtype != input_dtype {
3156 rhs.cast(input_dtype)?
3157 } else {
3158 rhs.clone()
3159 };
3160
3161 apply_binary_with_output_dtype(op, &lhs, &rhs, out_rank, out_shape_hint, out_dtype)
3162}
3163
3164pub(crate) fn apply_binary_preserve_input_dtypes(
3165 op: StdTensorOp,
3166 lhs: &TracedTensor,
3167 rhs: &TracedTensor,
3168 out_rank: usize,
3169 out_shape_hint: Option<Vec<SymDim>>,
3170 out_dtype: DType,
3171) -> Result<TracedTensor> {
3172 apply_binary_with_output_dtype(op, lhs, rhs, out_rank, out_shape_hint, out_dtype)
3173}
3174
3175pub(crate) fn apply_broadcast_binary_op(
3176 op: StdTensorOp,
3177 lhs: &TracedTensor,
3178 rhs: &TracedTensor,
3179) -> Result<TracedTensor> {
3180 let (lhs, rhs) = broadcast_binary(lhs, rhs)?;
3181 try_apply_binary(
3182 op,
3183 &lhs,
3184 &rhs,
3185 lhs.rank,
3186 lhs.shape_hint.clone(),
3187 "broadcast_binary",
3188 )
3189}
3190
3191pub(crate) fn apply_broadcast_ternary_op(
3192 op: StdTensorOp,
3193 first: &TracedTensor,
3194 second: &TracedTensor,
3195 third: &TracedTensor,
3196) -> Result<TracedTensor> {
3197 let (first, second, third) = broadcast_ternary(first, second, third)?;
3198 try_apply_ternary(
3199 op,
3200 &first,
3201 &second,
3202 &third,
3203 first.rank,
3204 first.shape_hint.clone(),
3205 "broadcast_ternary",
3206 )
3207}
3208
3209fn try_apply_ternary(
3210 op: StdTensorOp,
3211 first: &TracedTensor,
3212 second: &TracedTensor,
3213 third: &TracedTensor,
3214 out_rank: usize,
3215 out_shape_hint: Option<Vec<SymDim>>,
3216 context: &'static str,
3217) -> Result<TracedTensor> {
3218 let out_dtype =
3219 try_inferred_output_dtype(&op, &[first.dtype, second.dtype, third.dtype], context)?;
3220 let (first, second, third) = match op {
3221 StdTensorOp::Select => {
3222 let value_dtype = crate::shape_infer::promote_dtype(second.dtype, third.dtype);
3223 let second = if second.dtype != value_dtype {
3224 second.cast(value_dtype)?
3225 } else {
3226 second.clone()
3227 };
3228 let third = if third.dtype != value_dtype {
3229 third.cast(value_dtype)?
3230 } else {
3231 third.clone()
3232 };
3233 (first.clone(), second, third)
3234 }
3235 _ => {
3236 let input_dtype =
3237 crate::shape_infer::promote_dtypes([first.dtype, second.dtype, third.dtype]);
3238 let first = if first.dtype != input_dtype {
3239 first.cast(input_dtype)?
3240 } else {
3241 first.clone()
3242 };
3243 let second = if second.dtype != input_dtype {
3244 second.cast(input_dtype)?
3245 } else {
3246 second.clone()
3247 };
3248 let third = if third.dtype != input_dtype {
3249 third.cast(input_dtype)?
3250 } else {
3251 third.clone()
3252 };
3253 (first, second, third)
3254 }
3255 };
3256 apply_ternary_with_output_dtype(
3257 op,
3258 &first,
3259 &second,
3260 &third,
3261 out_rank,
3262 out_shape_hint,
3263 out_dtype,
3264 )
3265}
3266
3267fn apply_binary_with_output_dtype(
3268 op: StdTensorOp,
3269 lhs: &TracedTensor,
3270 rhs: &TracedTensor,
3271 out_rank: usize,
3272 out_shape_hint: Option<Vec<SymDim>>,
3273 out_dtype: DType,
3274) -> Result<TracedTensor> {
3275 let lhs_ref = ValueRef::External(lhs.graph.values()[lhs.val].key.clone());
3276 let rhs_ref = ValueRef::External(rhs.graph.values()[rhs.val].key.clone());
3277
3278 let mut builder = GraphBuilder::new();
3279 builder.add_parent(lhs.graph.clone());
3280 builder.add_parent(rhs.graph.clone());
3281 let outputs = builder.add_operation(op, vec![lhs_ref, rhs_ref], OperationRole::Primary);
3282 builder.set_outputs(outputs.clone());
3283 let graph = Arc::new(builder.build());
3284 let metadata_scope =
3285 register_single_output_metadata(graph.as_ref(), outputs[0], out_dtype, &out_shape_hint)?;
3286
3287 let mut extra_roots = lhs.extra_roots.clone();
3288 extra_roots.extend(rhs.extra_roots.iter().cloned());
3289
3290 Ok(TracedTensor {
3291 id: next_traced_id(),
3292 rank: out_rank,
3293 dtype: out_dtype,
3294 graph,
3295 val: outputs[0],
3296 data: None,
3297 shape_hint: out_shape_hint,
3298 inputs_map: merge_traced_inputs_map([lhs, rhs]),
3299 leaf_metas: merge_traced_leaf_metas([lhs, rhs]),
3300 extra_roots,
3301 checkpoint_chain: CheckpointNode::merge_chains(
3302 lhs.checkpoint_chain.clone(),
3303 rhs.checkpoint_chain.clone(),
3304 ),
3305 metadata_scopes: MetadataScopeChain::with_new(
3306 metadata_scope,
3307 [&lhs.metadata_scopes, &rhs.metadata_scopes],
3308 ),
3309 constraint_scopes: ConstraintScopeChain::merge([
3310 &lhs.constraint_scopes,
3311 &rhs.constraint_scopes,
3312 ]),
3313 })
3314}
3315
3316fn apply_ternary_with_output_dtype(
3317 op: StdTensorOp,
3318 first: &TracedTensor,
3319 second: &TracedTensor,
3320 third: &TracedTensor,
3321 out_rank: usize,
3322 out_shape_hint: Option<Vec<SymDim>>,
3323 out_dtype: DType,
3324) -> Result<TracedTensor> {
3325 let first_ref = ValueRef::External(first.graph.values()[first.val].key.clone());
3326 let second_ref = ValueRef::External(second.graph.values()[second.val].key.clone());
3327 let third_ref = ValueRef::External(third.graph.values()[third.val].key.clone());
3328
3329 let mut builder = GraphBuilder::new();
3330 builder.add_parent(first.graph.clone());
3331 builder.add_parent(second.graph.clone());
3332 builder.add_parent(third.graph.clone());
3333 let outputs = builder.add_operation(
3334 op,
3335 vec![first_ref, second_ref, third_ref],
3336 OperationRole::Primary,
3337 );
3338 builder.set_outputs(outputs.clone());
3339 let graph = Arc::new(builder.build());
3340 let metadata_scope =
3341 register_single_output_metadata(graph.as_ref(), outputs[0], out_dtype, &out_shape_hint)?;
3342
3343 let mut extra_roots = first.extra_roots.clone();
3344 extra_roots.extend(second.extra_roots.iter().cloned());
3345 extra_roots.extend(third.extra_roots.iter().cloned());
3346
3347 let checkpoint_chain = CheckpointNode::merge_chains(
3348 CheckpointNode::merge_chains(
3349 first.checkpoint_chain.clone(),
3350 second.checkpoint_chain.clone(),
3351 ),
3352 third.checkpoint_chain.clone(),
3353 );
3354
3355 Ok(TracedTensor {
3356 id: next_traced_id(),
3357 rank: out_rank,
3358 dtype: out_dtype,
3359 graph,
3360 val: outputs[0],
3361 data: None,
3362 shape_hint: out_shape_hint,
3363 inputs_map: merge_traced_inputs_map([first, second, third]),
3364 leaf_metas: merge_traced_leaf_metas([first, second, third]),
3365 extra_roots,
3366 checkpoint_chain,
3367 metadata_scopes: MetadataScopeChain::with_new(
3368 metadata_scope,
3369 [
3370 &first.metadata_scopes,
3371 &second.metadata_scopes,
3372 &third.metadata_scopes,
3373 ],
3374 ),
3375 constraint_scopes: ConstraintScopeChain::merge([
3376 &first.constraint_scopes,
3377 &second.constraint_scopes,
3378 &third.constraint_scopes,
3379 ]),
3380 })
3381}
3382
3383fn register_single_output_metadata(
3384 graph: &Graph<StdTensorOp>,
3385 output: LocalValueId,
3386 dtype: DType,
3387 shape_hint: &Option<Vec<SymDim>>,
3388) -> Result<GlobalMetadataScope> {
3389 if let Some(shape) = shape_hint {
3390 // Fresh graph output keys are generated in this builder, so metadata
3391 // registration failure would indicate a global metadata invariant bug.
3392 register_metadata_or_runtime_state(register_scoped_value_metadata(
3393 graph.values()[output].key.clone(),
3394 tensor_meta(dtype, shape.clone()),
3395 ))
3396 } else {
3397 // Fresh graph output keys are generated in this builder, so metadata
3398 // registration failure would indicate a global metadata invariant bug.
3399 register_metadata_or_runtime_state(register_scoped_graph_metadata(
3400 graph,
3401 std::iter::empty(),
3402 ))
3403 }
3404}
3405
3406impl TracedTensor {
3407 pub(crate) fn resolve_roots(&self) -> Vec<Arc<Graph<StdTensorOp>>> {
3408 let mut roots = Vec::with_capacity(1 + self.extra_roots.len());
3409 roots.push(self.graph.clone());
3410 roots.extend(self.extra_roots.iter().cloned());
3411 roots
3412 }
3413}
3414
3415#[cfg(test)]
3416mod tests;