1use ruxla_ir::ad::{AdCx, Tangent, TransposeInput};
5use ruxla_ir::batching::{BatchCx, Batched};
6use ruxla_ir::lowering::{HloValue, LowerCx};
7use ruxla_ir::{
8 AVal, Atom, DType, Error, EvalCx, HostArray, Params, Prim, Primitive, Result, Value,
9};
10use ruxla_kernels::{Buffer, Element, c64, c128, with_buffer};
11
12use crate::ad::{bind1, full, instantiate, neg_tangent};
13use crate::batching;
14use crate::elementwise::{complex_part, make_complex};
15use crate::util::{arity, no_params, same};
16
17#[derive(Debug)]
19pub(crate) struct Part {
20 imag: bool,
21}
22
23impl Primitive for Part {
24 fn name(&self) -> &'static str {
25 if self.imag { "imag" } else { "real" }
26 }
27
28 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
29 arity(self.name(), inputs, 1)?;
30 no_params(self.name(), params)?;
31 let x = &inputs[0];
32 if !x.dtype.is_complex() {
33 return Err(Error::type_error(
34 self.name(),
35 format!("expected complex numbers, got {x}"),
36 ));
37 }
38 Ok(vec![AVal::new(x.shape.clone(), x.dtype.real_dtype())])
39 }
40
41 fn eval(&self, _: &dyn EvalCx, inputs: &[HostArray], _: &Params) -> Result<Vec<HostArray>> {
42 let x = &inputs[0];
43 let imag = self.imag;
44 let b = with_buffer!(x.buffer(), |v| Buffer::from_vec(
45 v.iter()
46 .map(|&a| if imag { a.im() } else { a.re() })
47 .collect()
48 ));
49 Ok(vec![HostArray::from_buffer(b, x.shape().clone())])
50 }
51
52 fn batch(
53 &'static self,
54 cx: &mut dyn BatchCx,
55 inputs: &[Batched],
56 params: &Params,
57 ) -> Result<Vec<Batched>> {
58 batching::elementwise(cx, Prim::new(self), inputs, params)
59 }
60
61 fn lower(
62 &self,
63 cx: &mut dyn LowerCx,
64 inputs: &[HloValue],
65 _: &Params,
66 _: &[AVal],
67 ) -> Result<Vec<HloValue>> {
68 Ok(vec![complex_part(cx, &inputs[0], self.imag)])
69 }
70
71 fn jvp(
72 &'static self,
73 cx: &mut dyn AdCx,
74 primals: &[Atom],
75 tangents: &[Tangent],
76 params: &Params,
77 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
78 let ans = bind1(cx, Prim::new(self), primals, params.clone())?;
79 let t = tangents[0]
80 .as_ref()
81 .map(|t| bind1(cx, Prim::new(self), std::slice::from_ref(t), Params::None))
82 .transpose()?;
83 Ok((vec![ans], vec![t]))
84 }
85
86 fn transpose(
87 &'static self,
88 cx: &mut dyn AdCx,
89 cotangents: &[Tangent],
90 _: &[TransposeInput],
91 _: &Params,
92 ) -> Result<Vec<Tangent>> {
93 let Some(ct) = &cotangents[0] else {
95 return Ok(vec![None]);
96 };
97 let zero = full(cx, &ct.aval(), Value::Int(0))?;
98 let (re, im) = if self.imag {
99 (
100 zero,
101 neg_tangent(cx, &Some(ct.clone()))?.expect("a cotangent"),
102 )
103 } else {
104 (ct.clone(), zero)
105 };
106 Ok(vec![Some(bind1(cx, COMPLEX, &[re, im], Params::None)?)])
107 }
108}
109
110#[derive(Debug)]
112pub(crate) struct MakeComplex;
113
114impl Primitive for MakeComplex {
115 fn name(&self) -> &'static str {
116 "complex"
117 }
118
119 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
120 arity(self.name(), inputs, 2)?;
121 no_params(self.name(), params)?;
122 same(self.name(), &inputs[0], &inputs[1])?;
123 let x = &inputs[0];
124 if !matches!(x.dtype, DType::F32 | DType::F64) {
125 return Err(Error::type_error(
126 self.name(),
127 format!("expected f32 or f64 parts, got {x}"),
128 ));
129 }
130 let dtype = x.dtype.complex_dtype().expect("f32 or f64");
131 Ok(vec![AVal::new(x.shape.clone(), dtype)])
132 }
133
134 fn eval(&self, _: &dyn EvalCx, inputs: &[HostArray], _: &Params) -> Result<Vec<HostArray>> {
135 let (re, im) = (&inputs[0], &inputs[1]);
136 let b = match re.dtype() {
137 DType::F32 => Buffer::from_vec(zip_parts::<c64>(re, im)?),
138 _ => Buffer::from_vec(zip_parts::<c128>(re, im)?),
139 };
140 Ok(vec![HostArray::from_buffer(b, re.shape().clone())])
141 }
142
143 fn batch(
144 &'static self,
145 cx: &mut dyn BatchCx,
146 inputs: &[Batched],
147 params: &Params,
148 ) -> Result<Vec<Batched>> {
149 batching::elementwise(cx, Prim::new(self), inputs, params)
150 }
151
152 fn lower(
153 &self,
154 cx: &mut dyn LowerCx,
155 inputs: &[HloValue],
156 _: &Params,
157 _: &[AVal],
158 ) -> Result<Vec<HloValue>> {
159 Ok(vec![make_complex(cx, &inputs[0], &inputs[1])])
160 }
161
162 fn jvp(
163 &'static self,
164 cx: &mut dyn AdCx,
165 primals: &[Atom],
166 tangents: &[Tangent],
167 params: &Params,
168 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
169 let ans = bind1(cx, COMPLEX, primals, params.clone())?;
170 if tangents.iter().all(Option::is_none) {
171 return Ok((vec![ans], vec![None]));
172 }
173 let aval = primals[0].aval();
174 let re = instantiate(cx, &tangents[0], &aval)?;
175 let im = instantiate(cx, &tangents[1], &aval)?;
176 let t = bind1(cx, COMPLEX, &[re, im], Params::None)?;
177 Ok((vec![ans], vec![Some(t)]))
178 }
179
180 fn transpose(
181 &'static self,
182 cx: &mut dyn AdCx,
183 cotangents: &[Tangent],
184 inputs: &[TransposeInput],
185 _: &Params,
186 ) -> Result<Vec<Tangent>> {
187 let Some(ct) = &cotangents[0] else {
189 return Ok(vec![None, None]);
190 };
191 let re = if inputs[0].is_linear() {
192 Some(bind1(cx, REAL, std::slice::from_ref(ct), Params::None)?)
193 } else {
194 None
195 };
196 let im = if inputs[1].is_linear() {
197 let n = neg_tangent(cx, &Some(ct.clone()))?.expect("a cotangent");
198 Some(bind1(cx, IMAG, &[n], Params::None)?)
199 } else {
200 None
201 };
202 Ok(vec![re, im])
203 }
204}
205
206fn zip_parts<C: Element>(re: &HostArray, im: &HostArray) -> Result<Vec<C>> {
207 let (a, b) = (re.as_slice::<C::Real>()?, im.as_slice::<C::Real>()?);
208 Ok(a.iter()
209 .zip(b)
210 .map(|(&r, &i)| C::from_parts(r, i))
211 .collect())
212}
213
214#[derive(Debug)]
217pub(crate) struct Conj;
218
219impl Primitive for Conj {
220 fn name(&self) -> &'static str {
221 "conj"
222 }
223
224 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
225 arity(self.name(), inputs, 1)?;
226 no_params(self.name(), params)?;
227 let x = &inputs[0];
228 let Some(dtype) = x.dtype.complex_dtype() else {
229 return Err(Error::type_error(
230 self.name(),
231 format!("expected f32, f64, or complex numbers, got {x}"),
232 ));
233 };
234 Ok(vec![AVal::new(x.shape.clone(), dtype)])
235 }
236
237 fn eval(&self, _: &dyn EvalCx, inputs: &[HostArray], _: &Params) -> Result<Vec<HostArray>> {
238 let x = &inputs[0];
239 let b = match x.buffer() {
240 Buffer::C64(v) => Buffer::from_vec(v.iter().map(|a| a.conj()).collect()),
241 Buffer::C128(v) => Buffer::from_vec(v.iter().map(|a| a.conj()).collect()),
242 Buffer::F32(v) => Buffer::from_vec(v.iter().map(|&a| c64::new(a, 0.0)).collect()),
243 Buffer::F64(v) => Buffer::from_vec(v.iter().map(|&a| c128::new(a, 0.0)).collect()),
244 b => {
245 return Err(Error::type_error(
246 self.name(),
247 format!("unexpected {} operand", b.dtype()),
248 ));
249 }
250 };
251 Ok(vec![HostArray::from_buffer(b, x.shape().clone())])
252 }
253
254 fn batch(
255 &'static self,
256 cx: &mut dyn BatchCx,
257 inputs: &[Batched],
258 params: &Params,
259 ) -> Result<Vec<Batched>> {
260 batching::elementwise(cx, Prim::new(self), inputs, params)
261 }
262
263 fn lower(
264 &self,
265 cx: &mut dyn LowerCx,
266 inputs: &[HloValue],
267 _: &Params,
268 _: &[AVal],
269 ) -> Result<Vec<HloValue>> {
270 let x = &inputs[0];
273 if x.aval.dtype.is_complex() {
274 let re = complex_part(cx, x, false);
275 let im = complex_part(cx, x, true);
276 let im = cx.op1("stablehlo.negate", &[im], "", &re.aval);
277 Ok(vec![make_complex(cx, &re, &im)])
278 } else {
279 let zero = cx.splat(Value::Int(0), &x.aval);
280 Ok(vec![make_complex(cx, x, &zero)])
281 }
282 }
283
284 fn jvp(
285 &'static self,
286 cx: &mut dyn AdCx,
287 primals: &[Atom],
288 tangents: &[Tangent],
289 _: &Params,
290 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
291 let ans = bind1(cx, CONJ, primals, Params::None)?;
292 let t = tangents[0]
293 .as_ref()
294 .map(|t| bind1(cx, CONJ, std::slice::from_ref(t), Params::None))
295 .transpose()?;
296 Ok((vec![ans], vec![t]))
297 }
298
299 fn transpose(
300 &'static self,
301 cx: &mut dyn AdCx,
302 cotangents: &[Tangent],
303 inputs: &[TransposeInput],
304 _: &Params,
305 ) -> Result<Vec<Tangent>> {
306 let Some(ct) = &cotangents[0] else {
309 return Ok(vec![None]);
310 };
311 let prim = if inputs[0].aval().dtype.is_complex() {
312 CONJ
313 } else {
314 REAL
315 };
316 Ok(vec![Some(bind1(
317 cx,
318 prim,
319 std::slice::from_ref(ct),
320 Params::None,
321 )?)])
322 }
323}
324
325pub static REAL: Prim = Prim::new(&Part { imag: false });
327pub static IMAG: Prim = Prim::new(&Part { imag: true });
329pub static COMPLEX: Prim = Prim::new(&MakeComplex);
331pub static CONJ: Prim = Prim::new(&Conj);