1use ruxla_ir::ad::{AdCx, Tangent};
8use ruxla_ir::{AVal, Atom, DType, Error, HostArray, Literal, Params, Prim, Result, Shape, Value};
9
10use crate::elementwise::{ADD, CONVERT_ELEMENT_TYPE, MUL, NEG, SUB};
11use crate::structural::BROADCAST_IN_DIM;
12
13pub fn bind1(cx: &mut dyn AdCx, prim: Prim, inputs: &[Atom], params: Params) -> Result<Atom> {
15 let mut outputs = cx.bind(prim, inputs, params)?;
16 if outputs.len() != 1 {
17 return Err(Error::Malformed(format!(
18 "{} returned {} outputs, expected one",
19 prim.name(),
20 outputs.len()
21 )));
22 }
23 Ok(outputs.remove(0))
24}
25
26pub fn scalar(dtype: DType, value: Value) -> Atom {
28 Atom::Lit(Literal::new(HostArray::full(Shape::scalar(), dtype, value)))
29}
30
31pub fn full(cx: &mut dyn AdCx, aval: &AVal, value: Value) -> Result<Atom> {
37 let s = scalar(aval.dtype, value);
38 if aval.shape.rank() == 0 {
39 return Ok(s);
40 }
41 bind1(
42 cx,
43 BROADCAST_IN_DIM,
44 &[s],
45 Params::BroadcastInDim {
46 shape: aval.shape.clone(),
47 broadcast_dimensions: Vec::new(),
48 },
49 )
50}
51
52pub fn zeros(cx: &mut dyn AdCx, aval: &AVal) -> Result<Atom> {
58 full(cx, aval, Value::Int(0))
59}
60
61pub fn instantiate(cx: &mut dyn AdCx, t: &Tangent, aval: &AVal) -> Result<Atom> {
67 match t {
68 Some(a) => Ok(a.clone()),
69 None => zeros(cx, aval),
70 }
71}
72
73pub fn add_tangents(cx: &mut dyn AdCx, a: Tangent, b: Tangent) -> Result<Tangent> {
79 Ok(match (a, b) {
80 (None, t) | (t, None) => t,
81 (Some(a), Some(b)) => Some(bind1(cx, ADD, &[a, b], Params::None)?),
82 })
83}
84
85pub fn mul_tangent(cx: &mut dyn AdCx, t: &Tangent, by: &Atom) -> Result<Tangent> {
91 t.as_ref()
92 .map(|t| bind1(cx, MUL, &[t.clone(), by.clone()], Params::None))
93 .transpose()
94}
95
96pub fn neg_tangent(cx: &mut dyn AdCx, t: &Tangent) -> Result<Tangent> {
102 t.as_ref()
103 .map(|t| bind1(cx, NEG, std::slice::from_ref(t), Params::None))
104 .transpose()
105}
106
107pub fn sub_tangents(cx: &mut dyn AdCx, a: Tangent, b: Tangent) -> Result<Tangent> {
113 Ok(match (a, b) {
114 (t, None) => t,
115 (None, Some(b)) => Some(bind1(cx, NEG, &[b], Params::None)?),
116 (Some(a), Some(b)) => Some(bind1(cx, SUB, &[a, b], Params::None)?),
117 })
118}
119
120pub fn convert(cx: &mut dyn AdCx, x: &Atom, dtype: DType) -> Result<Atom> {
126 if x.aval().dtype == dtype {
127 return Ok(x.clone());
128 }
129 bind1(
130 cx,
131 CONVERT_ELEMENT_TYPE,
132 std::slice::from_ref(x),
133 Params::Convert { new_dtype: dtype },
134 )
135}
136
137pub fn differentiable(aval: &AVal) -> bool {
139 ruxla_ir::ad::is_differentiable(aval)
140}