Skip to main content

ruxla_prims/
elementwise.rs

1//! Elementwise primitives.
2
3use ruxla_ir::ad::{AdCx, Tangent, TransposeInput};
4use ruxla_ir::batching::{BatchCx, Batched};
5use ruxla_ir::lowering::{HloValue, LowerCx, Target};
6use ruxla_ir::{
7    AVal, Atom, DType, DTypeKind, Error, EvalCx, HostArray, Params, Prim, Primitive, Result,
8    RoundingMethod, Shape, Value,
9};
10use ruxla_kernels::{BinaryOp, Buffer, CompareOp, Ops, TernaryOp, UnaryOp, with_buffer};
11
12use crate::batching;
13use crate::elementwise_ad as ad;
14use crate::special;
15use crate::structural::BROADCAST_IN_DIM;
16use crate::util::{arity, no_params, same, wrong_params};
17
18/// A unary primitive defined by a [`UnaryOp`].
19#[derive(Debug)]
20pub(crate) struct Unary(pub(crate) UnaryOp);
21
22impl Primitive for Unary {
23    fn name(&self) -> &'static str {
24        self.0.name()
25    }
26
27    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
28        arity(self.name(), inputs, 1)?;
29        no_params(self.name(), params)?;
30        if !self.0.supports(inputs[0].dtype) {
31            return Err(Error::type_error(
32                self.name(),
33                format!("does not accept {} operands", inputs[0].dtype),
34            ));
35        }
36        let mut out = inputs[0].clone();
37        if self.0 == UnaryOp::Abs {
38            // The magnitude of a complex number is real.
39            out.dtype = out.dtype.real_dtype();
40        }
41        Ok(vec![out])
42    }
43
44    fn eval(&self, _: &dyn EvalCx, inputs: &[HostArray], _: &Params) -> Result<Vec<HostArray>> {
45        let op = self.0;
46        let x = &inputs[0];
47        let b = with_buffer!(x.buffer(), |v| Buffer::from_vec(
48            v.iter().map(|&a| Ops::unary(op, a)).collect()
49        ));
50        let out = HostArray::from_buffer(b, x.shape().clone());
51        if op == UnaryOp::Abs && x.dtype().is_complex() {
52            // The real part, which holds the magnitude.
53            return Ok(vec![out.convert(x.dtype().real_dtype())]);
54        }
55        Ok(vec![out])
56    }
57
58    fn batch(
59        &'static self,
60        cx: &mut dyn BatchCx,
61        inputs: &[Batched],
62        params: &Params,
63    ) -> Result<Vec<Batched>> {
64        batching::elementwise(cx, Prim::new(self), inputs, params)
65    }
66
67    fn lower(
68        &self,
69        cx: &mut dyn LowerCx,
70        inputs: &[HloValue],
71        _: &Params,
72        outputs: &[AVal],
73    ) -> Result<Vec<HloValue>> {
74        let out = &outputs[0];
75        let x = inputs[0].clone();
76        if self.0 == UnaryOp::BesselI0e {
77            // JAX lowers bessel_i0e by tracing its implementation.
78            return special::lower_traced(cx, self.name(), inputs, out, |b, a| {
79                ruxla_kernels::special::bessel_i0e(b, &a[0])
80            });
81        }
82        if inputs[0].aval.dtype.is_complex() {
83            match self.0 {
84                UnaryOp::Abs => return Ok(vec![lower_complex_abs(cx, &x, out)]),
85                UnaryOp::Sin | UnaryOp::Cos => {
86                    return Ok(vec![lower_complex_sin_cos(cx, &x, self.0 == UnaryOp::Cos)]);
87                }
88                _ => {}
89            }
90        }
91        Ok(vec![match self.0 {
92            // As JAX lowers `square`.
93            UnaryOp::Square => cx.op1("stablehlo.multiply", &[x.clone(), x], "", out),
94            // CHLO's erf_inv, which XLA expands, as in JAX.
95            UnaryOp::ErfInv => cx.op1("chlo.erf_inv", &[x], "", out),
96            // StableHLO's sign does not accept unsigned integers; JAX lowers
97            // it as `x != 0`.
98            UnaryOp::Sign if out.dtype.kind() == DTypeKind::UnsignedInt => {
99                let zero = cx.splat(Value::Int(0), out);
100                let one = cx.splat(Value::Int(1), out);
101                let pred_aval = AVal::new(out.shape.clone(), DType::Bool);
102                let nonzero = compare(cx, "NE", &x, &zero, &pred_aval);
103                cx.op1("stablehlo.select", &[nonzero, one, zero], "", out)
104            }
105            op => cx.op1(unary_hlo(op), &[x], "", out),
106        }])
107    }
108
109    fn jvp(
110        &'static self,
111        cx: &mut dyn AdCx,
112        primals: &[Atom],
113        tangents: &[Tangent],
114        _: &Params,
115    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
116        let (a, t) = ad::unary_jvp(cx, self.0, &primals[0], &tangents[0])?;
117        Ok((vec![a], vec![t]))
118    }
119
120    fn transpose(
121        &'static self,
122        cx: &mut dyn AdCx,
123        cotangents: &[Tangent],
124        inputs: &[TransposeInput],
125        _: &Params,
126    ) -> Result<Vec<Tangent>> {
127        let _ = inputs;
128        ad::unary_transpose(cx, self.0, &cotangents[0])
129    }
130}
131
132/// A binary primitive defined by a [`BinaryOp`]. Operands have the same
133/// shape and type.
134#[derive(Debug)]
135pub(crate) struct Binary(pub(crate) BinaryOp);
136
137impl Primitive for Binary {
138    fn name(&self) -> &'static str {
139        self.0.name()
140    }
141
142    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
143        arity(self.name(), inputs, 2)?;
144        no_params(self.name(), params)?;
145        same(self.name(), &inputs[0], &inputs[1])?;
146        if !self.0.supports(inputs[0].dtype) {
147            return Err(Error::type_error(
148                self.name(),
149                format!("does not accept {} operands", inputs[0].dtype),
150            ));
151        }
152        Ok(vec![inputs[0].clone()])
153    }
154
155    fn eval(&self, _: &dyn EvalCx, inputs: &[HostArray], _: &Params) -> Result<Vec<HostArray>> {
156        let op = self.0;
157        let (x, y) = (&inputs[0], &inputs[1]);
158        let b = with_buffer!(x.buffer(), |a| {
159            let b = y.as_slice().expect("same types");
160            Buffer::from_vec(
161                a.iter()
162                    .zip(b)
163                    .map(|(&p, &q)| Ops::binary(op, p, q))
164                    .collect(),
165            )
166        });
167        Ok(vec![HostArray::from_buffer(b, x.shape().clone())])
168    }
169
170    fn batch(
171        &'static self,
172        cx: &mut dyn BatchCx,
173        inputs: &[Batched],
174        params: &Params,
175    ) -> Result<Vec<Batched>> {
176        batching::elementwise(cx, Prim::new(self), inputs, params)
177    }
178
179    fn lower(
180        &self,
181        cx: &mut dyn LowerCx,
182        inputs: &[HloValue],
183        _: &Params,
184        outputs: &[AVal],
185    ) -> Result<Vec<HloValue>> {
186        let out = &outputs[0];
187        if matches!(
188            self.0,
189            BinaryOp::Igamma
190                | BinaryOp::Igammac
191                | BinaryOp::IgammaGradA
192                | BinaryOp::RandomGammaGrad
193        ) {
194            // JAX lowers these by tracing their implementations.
195            let op = self.0;
196            return special::lower_traced(cx, self.name(), inputs, out, |b, a| {
197                ruxla_kernels::special::eval_binary(b, op, &a[0], &a[1])
198            });
199        }
200        Ok(vec![match self.0 {
201            BinaryOp::Max | BinaryOp::Min if out.dtype.is_complex() => {
202                lower_complex_min_max(cx, self.0 == BinaryOp::Max, &inputs[0], &inputs[1])
203            }
204            BinaryOp::Max => cx.min_max("stablehlo.maximum", &inputs[0], &inputs[1], out),
205            BinaryOp::Min => cx.min_max("stablehlo.minimum", &inputs[0], &inputs[1], out),
206            op => cx.op1(binary_hlo(op), inputs, "", out),
207        }])
208    }
209
210    fn jvp(
211        &'static self,
212        cx: &mut dyn AdCx,
213        primals: &[Atom],
214        tangents: &[Tangent],
215        _: &Params,
216    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
217        let (a, t) = ad::binary_jvp(
218            cx,
219            self.0,
220            &primals[0],
221            &primals[1],
222            &tangents[0],
223            &tangents[1],
224        )?;
225        Ok((vec![a], vec![t]))
226    }
227
228    fn transpose(
229        &'static self,
230        cx: &mut dyn AdCx,
231        cotangents: &[Tangent],
232        inputs: &[TransposeInput],
233        _: &Params,
234    ) -> Result<Vec<Tangent>> {
235        ad::binary_transpose(cx, self.0, &cotangents[0], inputs)
236    }
237}
238
239/// A comparison primitive.
240#[derive(Debug)]
241pub(crate) struct Compare(pub(crate) CompareOp);
242
243impl Primitive for Compare {
244    fn name(&self) -> &'static str {
245        self.0.name()
246    }
247
248    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
249        arity(self.name(), inputs, 2)?;
250        no_params(self.name(), params)?;
251        same(self.name(), &inputs[0], &inputs[1])?;
252        if !self.0.supports(inputs[0].dtype) {
253            return Err(Error::type_error(
254                self.name(),
255                format!("does not accept {} operands", inputs[0].dtype),
256            ));
257        }
258        Ok(vec![AVal::new(inputs[0].shape.clone(), DType::Bool)])
259    }
260
261    fn eval(&self, _: &dyn EvalCx, inputs: &[HostArray], _: &Params) -> Result<Vec<HostArray>> {
262        let op = self.0;
263        let (x, y) = (&inputs[0], &inputs[1]);
264        let out: Vec<bool> = with_buffer!(x.buffer(), |a| {
265            let b = y.as_slice().expect("same types");
266            a.iter()
267                .zip(b)
268                .map(|(&p, &q)| ruxla_kernels::compare(op, p, q))
269                .collect()
270        });
271        Ok(vec![HostArray::from_vec(out, x.shape().clone())])
272    }
273
274    fn batch(
275        &'static self,
276        cx: &mut dyn BatchCx,
277        inputs: &[Batched],
278        params: &Params,
279    ) -> Result<Vec<Batched>> {
280        batching::elementwise(cx, Prim::new(self), inputs, params)
281    }
282
283    fn lower(
284        &self,
285        cx: &mut dyn LowerCx,
286        inputs: &[HloValue],
287        _: &Params,
288        outputs: &[AVal],
289    ) -> Result<Vec<HloValue>> {
290        let direction = match self.0 {
291            CompareOp::Eq => "EQ",
292            CompareOp::Ne => "NE",
293            CompareOp::Lt => "LT",
294            CompareOp::Le => "LE",
295            CompareOp::Gt => "GT",
296            CompareOp::Ge => "GE",
297        };
298        Ok(vec![compare(
299            cx,
300            direction,
301            &inputs[0],
302            &inputs[1],
303            &outputs[0],
304        )])
305    }
306
307    fn jvp(
308        &'static self,
309        cx: &mut dyn AdCx,
310        primals: &[Atom],
311        tangents: &[Tangent],
312        params: &Params,
313    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
314        let _ = tangents;
315        let outs = cx.bind(Prim::new(self), primals, params.clone())?;
316        let n = outs.len();
317        Ok((outs, vec![None; n]))
318    }
319}
320
321/// A ternary primitive defined by a [`TernaryOp`]. Operands have the same
322/// shape and type.
323#[derive(Debug)]
324pub(crate) struct Ternary(pub(crate) TernaryOp);
325
326impl Primitive for Ternary {
327    fn name(&self) -> &'static str {
328        self.0.name()
329    }
330
331    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
332        arity(self.name(), inputs, 3)?;
333        no_params(self.name(), params)?;
334        same(self.name(), &inputs[0], &inputs[1])?;
335        same(self.name(), &inputs[0], &inputs[2])?;
336        if !self.0.supports(inputs[0].dtype) {
337            return Err(Error::type_error(
338                self.name(),
339                format!("does not accept {} operands", inputs[0].dtype),
340            ));
341        }
342        Ok(vec![inputs[0].clone()])
343    }
344
345    fn eval(&self, _: &dyn EvalCx, inputs: &[HostArray], _: &Params) -> Result<Vec<HostArray>> {
346        let op = self.0;
347        let (x, y, z) = (&inputs[0], &inputs[1], &inputs[2]);
348        let b = with_buffer!(x.buffer(), |a| {
349            let b = y.as_slice().expect("same types");
350            let c = z.as_slice().expect("same types");
351            Buffer::from_vec(
352                a.iter()
353                    .zip(b)
354                    .zip(c)
355                    .map(|((&p, &q), &r)| Ops::ternary(op, p, q, r))
356                    .collect(),
357            )
358        });
359        Ok(vec![HostArray::from_buffer(b, x.shape().clone())])
360    }
361
362    fn batch(
363        &'static self,
364        cx: &mut dyn BatchCx,
365        inputs: &[Batched],
366        params: &Params,
367    ) -> Result<Vec<Batched>> {
368        batching::elementwise(cx, Prim::new(self), inputs, params)
369    }
370
371    fn lower(
372        &self,
373        cx: &mut dyn LowerCx,
374        inputs: &[HloValue],
375        _: &Params,
376        outputs: &[AVal],
377    ) -> Result<Vec<HloValue>> {
378        // JAX lowers it by tracing its implementation.
379        special::lower_traced(cx, self.name(), inputs, &outputs[0], |b, a| {
380            ruxla_kernels::special::regularized_incomplete_beta(b, &a[0], &a[1], &a[2])
381        })
382    }
383
384    fn jvp(
385        &'static self,
386        cx: &mut dyn AdCx,
387        primals: &[Atom],
388        tangents: &[Tangent],
389        _: &Params,
390    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
391        let (a, t) = ad::ternary_jvp(cx, self.0, primals, tangents)?;
392        Ok((vec![a], vec![t]))
393    }
394}
395
396/// `is_finite`.
397#[derive(Debug)]
398pub(crate) struct IsFinite;
399
400impl Primitive for IsFinite {
401    fn name(&self) -> &'static str {
402        "is_finite"
403    }
404
405    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
406        arity(self.name(), inputs, 1)?;
407        no_params(self.name(), params)?;
408        if !inputs[0].dtype.is_float() {
409            return Err(Error::type_error(
410                self.name(),
411                format!("expected floats, got {}", inputs[0]),
412            ));
413        }
414        Ok(vec![AVal::new(inputs[0].shape.clone(), DType::Bool)])
415    }
416
417    fn eval(&self, _: &dyn EvalCx, inputs: &[HostArray], _: &Params) -> Result<Vec<HostArray>> {
418        let x = &inputs[0];
419        let out: Vec<bool> = with_buffer!(x.buffer(), |v| v
420            .iter()
421            .map(|&a| Ops::is_finite(a))
422            .collect());
423        Ok(vec![HostArray::from_vec(out, x.shape().clone())])
424    }
425
426    fn batch(
427        &'static self,
428        cx: &mut dyn BatchCx,
429        inputs: &[Batched],
430        params: &Params,
431    ) -> Result<Vec<Batched>> {
432        batching::elementwise(cx, Prim::new(self), inputs, params)
433    }
434
435    fn lower(
436        &self,
437        cx: &mut dyn LowerCx,
438        inputs: &[HloValue],
439        _: &Params,
440        outputs: &[AVal],
441    ) -> Result<Vec<HloValue>> {
442        Ok(vec![cx.op1("stablehlo.is_finite", inputs, "", &outputs[0])])
443    }
444
445    fn jvp(
446        &'static self,
447        cx: &mut dyn AdCx,
448        primals: &[Atom],
449        tangents: &[Tangent],
450        params: &Params,
451    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
452        let _ = tangents;
453        let outs = cx.bind(Prim::new(self), primals, params.clone())?;
454        let n = outs.len();
455        Ok((outs, vec![None; n]))
456    }
457}
458
459/// `round`, with a rounding method.
460#[derive(Debug)]
461pub(crate) struct Round;
462
463impl Primitive for Round {
464    fn name(&self) -> &'static str {
465        "round"
466    }
467
468    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
469        arity(self.name(), inputs, 1)?;
470        let Params::Round { .. } = params else {
471            return Err(wrong_params(self.name()));
472        };
473        if !inputs[0].dtype.is_float() {
474            return Err(Error::type_error(
475                self.name(),
476                format!("expected floats, got {}", inputs[0]),
477            ));
478        }
479        Ok(vec![inputs[0].clone()])
480    }
481
482    fn eval(
483        &self,
484        _: &dyn EvalCx,
485        inputs: &[HostArray],
486        params: &Params,
487    ) -> Result<Vec<HostArray>> {
488        let Params::Round { method } = params else {
489            return Err(wrong_params(self.name()));
490        };
491        let op = match method {
492            RoundingMethod::AwayFromZero => UnaryOp::Round,
493            RoundingMethod::ToNearestEven => UnaryOp::RoundEven,
494        };
495        Unary(op).eval(&NoCx, inputs, &Params::None)
496    }
497
498    fn batch(
499        &'static self,
500        cx: &mut dyn BatchCx,
501        inputs: &[Batched],
502        params: &Params,
503    ) -> Result<Vec<Batched>> {
504        batching::elementwise(cx, Prim::new(self), inputs, params)
505    }
506
507    fn lower(
508        &self,
509        cx: &mut dyn LowerCx,
510        inputs: &[HloValue],
511        params: &Params,
512        outputs: &[AVal],
513    ) -> Result<Vec<HloValue>> {
514        let Params::Round { method } = params else {
515            return Err(wrong_params(self.name()));
516        };
517        let op = match method {
518            RoundingMethod::AwayFromZero => "stablehlo.round_nearest_afz",
519            RoundingMethod::ToNearestEven => "stablehlo.round_nearest_even",
520        };
521        Ok(vec![cx.op1(op, inputs, "", &outputs[0])])
522    }
523
524    fn jvp(
525        &'static self,
526        cx: &mut dyn AdCx,
527        primals: &[Atom],
528        tangents: &[Tangent],
529        params: &Params,
530    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
531        let _ = tangents;
532        let Params::Round { method } = *params else {
533            return Err(wrong_params(self.name()));
534        };
535        let (a, t) = ad::round_jvp(cx, &primals[0], method)?;
536        Ok((vec![a], vec![t]))
537    }
538}
539
540/// `integer_pow`.
541#[derive(Debug)]
542pub(crate) struct IntegerPow;
543
544impl Primitive for IntegerPow {
545    fn name(&self) -> &'static str {
546        "integer_pow"
547    }
548
549    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
550        arity(self.name(), inputs, 1)?;
551        let Params::IntegerPow { y } = params else {
552            return Err(wrong_params(self.name()));
553        };
554        let d = inputs[0].dtype;
555        if d == DType::Bool || (*y < 0 && !d.is_inexact()) {
556            return Err(Error::type_error(
557                self.name(),
558                format!("cannot raise {} to the power {y}", inputs[0]),
559            ));
560        }
561        Ok(vec![inputs[0].clone()])
562    }
563
564    fn eval(
565        &self,
566        _: &dyn EvalCx,
567        inputs: &[HostArray],
568        params: &Params,
569    ) -> Result<Vec<HostArray>> {
570        let Params::IntegerPow { y } = params else {
571            return Err(wrong_params(self.name()));
572        };
573        let x = &inputs[0];
574        let b = with_buffer!(x.buffer(), |v| Buffer::from_vec(
575            v.iter()
576                .map(|&a| ruxla_kernels::integer_pow(a, *y))
577                .collect()
578        ));
579        Ok(vec![HostArray::from_buffer(b, x.shape().clone())])
580    }
581
582    fn batch(
583        &'static self,
584        cx: &mut dyn BatchCx,
585        inputs: &[Batched],
586        params: &Params,
587    ) -> Result<Vec<Batched>> {
588        batching::elementwise(cx, Prim::new(self), inputs, params)
589    }
590
591    fn lower(
592        &self,
593        cx: &mut dyn LowerCx,
594        inputs: &[HloValue],
595        params: &Params,
596        outputs: &[AVal],
597    ) -> Result<Vec<HloValue>> {
598        let Params::IntegerPow { y } = *params else {
599            return Err(wrong_params(self.name()));
600        };
601        let out = &outputs[0];
602        // Exponentiation by squaring, as JAX lowers integer_pow.
603        let mut acc: Option<HloValue> = None;
604        let mut base = inputs[0].clone();
605        let mut n = y.unsigned_abs();
606        while n > 0 {
607            if n & 1 == 1 {
608                acc = Some(match acc {
609                    None => base.clone(),
610                    Some(a) => cx.op1("stablehlo.multiply", &[a, base.clone()], "", out),
611                });
612            }
613            n >>= 1;
614            if n > 0 {
615                base = cx.op1("stablehlo.multiply", &[base.clone(), base], "", out);
616            }
617        }
618        let positive = match acc {
619            Some(a) => a,
620            None => cx.splat(Value::Int(1), out),
621        };
622        if y >= 0 {
623            return Ok(vec![positive]);
624        }
625        let one = cx.splat(Value::Int(1), out);
626        Ok(vec![cx.op1("stablehlo.divide", &[one, positive], "", out)])
627    }
628
629    fn jvp(
630        &'static self,
631        cx: &mut dyn AdCx,
632        primals: &[Atom],
633        tangents: &[Tangent],
634        params: &Params,
635    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
636        let Params::IntegerPow { y } = *params else {
637            return Err(wrong_params(self.name()));
638        };
639        let (a, t) = ad::integer_pow_jvp(cx, &primals[0], &tangents[0], y)?;
640        Ok((vec![a], vec![t]))
641    }
642}
643
644/// `convert_element_type`.
645#[derive(Debug)]
646pub(crate) struct ConvertElementType;
647
648impl Primitive for ConvertElementType {
649    fn name(&self) -> &'static str {
650        "convert_element_type"
651    }
652
653    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
654        arity(self.name(), inputs, 1)?;
655        let Params::Convert { new_dtype } = params else {
656            return Err(wrong_params(self.name()));
657        };
658        Ok(vec![AVal::new(inputs[0].shape.clone(), *new_dtype)])
659    }
660
661    fn eval(
662        &self,
663        _: &dyn EvalCx,
664        inputs: &[HostArray],
665        params: &Params,
666    ) -> Result<Vec<HostArray>> {
667        let Params::Convert { new_dtype } = params else {
668            return Err(wrong_params(self.name()));
669        };
670        Ok(vec![inputs[0].convert(*new_dtype)])
671    }
672
673    fn batch(
674        &'static self,
675        cx: &mut dyn BatchCx,
676        inputs: &[Batched],
677        params: &Params,
678    ) -> Result<Vec<Batched>> {
679        batching::elementwise(cx, Prim::new(self), inputs, params)
680    }
681
682    fn lower(
683        &self,
684        cx: &mut dyn LowerCx,
685        inputs: &[HloValue],
686        _: &Params,
687        outputs: &[AVal],
688    ) -> Result<Vec<HloValue>> {
689        let out = &outputs[0];
690        let mut x = inputs[0].clone();
691        if x.aval.dtype.is_complex() && !out.dtype.is_complex() {
692            // As JAX lowers it: the real part is converted.
693            x = complex_part(cx, &x, false);
694            if out.dtype == DType::Bool {
695                // As JAX's `convert_hlo`: `x != 0`.
696                let zero = cx.splat(Value::Int(0), &x.aval);
697                return Ok(vec![compare(cx, "NE", &x, &zero, out)]);
698            }
699        }
700        Ok(vec![cx.op1("stablehlo.convert", &[x], "", out)])
701    }
702
703    fn jvp(
704        &'static self,
705        cx: &mut dyn AdCx,
706        primals: &[Atom],
707        tangents: &[Tangent],
708        params: &Params,
709    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
710        let Params::Convert { new_dtype } = *params else {
711            return Err(wrong_params(self.name()));
712        };
713        let (a, t) = ad::convert_jvp(cx, &primals[0], &tangents[0], new_dtype)?;
714        Ok((vec![a], vec![t]))
715    }
716
717    fn transpose(
718        &'static self,
719        cx: &mut dyn AdCx,
720        cotangents: &[Tangent],
721        inputs: &[TransposeInput],
722        _: &Params,
723    ) -> Result<Vec<Tangent>> {
724        ad::convert_transpose(cx, &cotangents[0], &inputs[0])
725    }
726}
727
728/// `bitcast_convert_type`: reinterprets the bits as a type of the same size.
729#[derive(Debug)]
730pub(crate) struct BitcastConvertType;
731
732impl Primitive for BitcastConvertType {
733    fn name(&self) -> &'static str {
734        "bitcast_convert_type"
735    }
736
737    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
738        arity(self.name(), inputs, 1)?;
739        let Params::Convert { new_dtype } = params else {
740            return Err(wrong_params(self.name()));
741        };
742        let d = inputs[0].dtype;
743        if d.size_in_bytes() != new_dtype.size_in_bytes()
744            || d == DType::Bool
745            || *new_dtype == DType::Bool
746            || d.is_complex()
747            || new_dtype.is_complex()
748        {
749            return Err(Error::type_error(
750                self.name(),
751                format!("cannot reinterpret {d} as {new_dtype}"),
752            ));
753        }
754        Ok(vec![AVal::new(inputs[0].shape.clone(), *new_dtype)])
755    }
756
757    fn eval(
758        &self,
759        _: &dyn EvalCx,
760        inputs: &[HostArray],
761        params: &Params,
762    ) -> Result<Vec<HostArray>> {
763        let Params::Convert { new_dtype } = params else {
764            return Err(wrong_params(self.name()));
765        };
766        let x = &inputs[0];
767        Ok(vec![HostArray::from_bytes(
768            &x.to_bytes(),
769            x.shape().clone(),
770            *new_dtype,
771        )?])
772    }
773
774    fn batch(
775        &'static self,
776        cx: &mut dyn BatchCx,
777        inputs: &[Batched],
778        params: &Params,
779    ) -> Result<Vec<Batched>> {
780        batching::elementwise(cx, Prim::new(self), inputs, params)
781    }
782
783    fn lower(
784        &self,
785        cx: &mut dyn LowerCx,
786        inputs: &[HloValue],
787        _: &Params,
788        outputs: &[AVal],
789    ) -> Result<Vec<HloValue>> {
790        Ok(vec![cx.op1(
791            "stablehlo.bitcast_convert",
792            inputs,
793            "",
794            &outputs[0],
795        )])
796    }
797
798    fn jvp(
799        &'static self,
800        cx: &mut dyn AdCx,
801        primals: &[Atom],
802        tangents: &[Tangent],
803        params: &Params,
804    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
805        let _ = tangents;
806        let outs = cx.bind(Prim::new(self), primals, params.clone())?;
807        let n = outs.len();
808        Ok((outs, vec![None; n]))
809    }
810}
811
812/// `select_n(which, *cases)`: element `i` comes from `cases[which[i]]`.
813/// `which` is a bool (two cases at most) or `i32`, and is a scalar or has
814/// the shape of the cases.
815#[derive(Debug)]
816pub(crate) struct SelectN;
817
818impl Primitive for SelectN {
819    fn name(&self) -> &'static str {
820        "select_n"
821    }
822
823    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
824        let name = self.name();
825        no_params(name, params)?;
826        let [which, cases @ ..] = inputs else {
827            return Err(Error::type_error(name, "expected operands"));
828        };
829        let Some(first) = cases.first() else {
830            return Err(Error::type_error(name, "expected a case"));
831        };
832        for c in cases {
833            same(name, first, c)?;
834        }
835        match which.dtype {
836            DType::Bool if cases.len() <= 2 => {}
837            DType::I32 => {}
838            _ => {
839                return Err(Error::type_error(
840                    name,
841                    format!("invalid predicate {which} for {} cases", cases.len()),
842                ));
843            }
844        }
845        if which.shape.rank() != 0 && which.shape != first.shape {
846            return Err(Error::type_error(
847                name,
848                format!("the predicate {which} must be a scalar or match {first}"),
849            ));
850        }
851        Ok(vec![first.clone()])
852    }
853
854    fn eval(&self, _: &dyn EvalCx, inputs: &[HostArray], _: &Params) -> Result<Vec<HostArray>> {
855        let which: Vec<usize> = crate::util::indices(&inputs[0].convert(DType::I64))
856            .into_iter()
857            .map(|i| i.max(0) as usize)
858            .collect();
859        let cases = &inputs[1..];
860        let b = with_buffer!(cases[0].buffer(), |first| {
861            let slices: Vec<&[_]> = std::iter::once(first.as_slice())
862                .chain(cases[1..].iter().map(|c| c.as_slice().expect("same types")))
863                .collect();
864            Buffer::from_vec(ruxla_kernels::array::select_n(&which, &slices))
865        });
866        Ok(vec![HostArray::from_buffer(b, cases[0].shape().clone())])
867    }
868
869    fn batch(
870        &'static self,
871        cx: &mut dyn BatchCx,
872        inputs: &[Batched],
873        params: &Params,
874    ) -> Result<Vec<Batched>> {
875        let (which, cases) = (&inputs[0], &inputs[1..]);
876        let example = cases[0].example_aval();
877        if which.example_aval().shape.rank() == example.shape.rank() {
878            return batching::elementwise(cx, SELECT_N, inputs, params);
879        }
880        // A scalar predicate per example selects whole cases.
881        let (which, bdim) = match which.bdim {
882            // The cases are elementwise among themselves.
883            None => {
884                let first = cases.iter().find_map(|c| c.bdim).unwrap_or(0);
885                let bdim = if cases.iter().all(|c| c.bdim == Some(first)) {
886                    first
887                } else {
888                    0
889                };
890                (which.atom.clone(), bdim)
891            }
892            // The predicate (shape `[n]`) is broadcast to the cases.
893            Some(_) => (
894                batching::broadcast_example_scalar(cx, &which.atom, &example.shape)?,
895                0,
896            ),
897        };
898        let mut atoms = vec![which];
899        for c in cases {
900            atoms.push(batching::move_bdim(cx, c, bdim)?);
901        }
902        let out = batching::bind1(cx, SELECT_N, &atoms, params.clone())?;
903        Ok(vec![Batched::mapped(out, bdim)])
904    }
905
906    fn lower(
907        &self,
908        cx: &mut dyn LowerCx,
909        inputs: &[HloValue],
910        _: &Params,
911        outputs: &[AVal],
912    ) -> Result<Vec<HloValue>> {
913        let (which, cases) = (&inputs[0], &inputs[1..]);
914        let out = &outputs[0];
915        if cases.len() == 1 {
916            return Ok(vec![cases[0].clone()]);
917        }
918        if which.aval.dtype == DType::Bool {
919            // select(pred, on_true, on_false): `true` picks the second case.
920            let operands = [which.clone(), cases[1].clone(), cases[0].clone()];
921            return Ok(vec![cx.op1("stablehlo.select", &operands, "", out)]);
922        }
923        // An i32 predicate picks case k where k is the largest index with
924        // which >= k, which also clamps out-of-range indices.
925        let pred_aval = AVal::new(which.aval.shape.clone(), DType::Bool);
926        let mut result = cases[0].clone();
927        for (k, case) in cases.iter().enumerate().skip(1) {
928            let k = cx.splat(Value::Int(k as i64), &which.aval);
929            let pred = compare(cx, "GE", which, &k, &pred_aval);
930            result = cx.op1("stablehlo.select", &[pred, case.clone(), result], "", out);
931        }
932        Ok(vec![result])
933    }
934
935    fn jvp(
936        &'static self,
937        cx: &mut dyn AdCx,
938        primals: &[Atom],
939        tangents: &[Tangent],
940        _: &Params,
941    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
942        let (a, t) = ad::select_n_jvp(cx, primals, tangents)?;
943        Ok((vec![a], vec![t]))
944    }
945
946    fn transpose(
947        &'static self,
948        cx: &mut dyn AdCx,
949        cotangents: &[Tangent],
950        inputs: &[TransposeInput],
951        _: &Params,
952    ) -> Result<Vec<Tangent>> {
953        ad::select_n_transpose(cx, &cotangents[0], inputs)
954    }
955}
956
957/// `clamp(lo, x, hi)`; `lo` and `hi` are scalars or have the shape of `x`.
958#[derive(Debug)]
959pub(crate) struct Clamp;
960
961impl Primitive for Clamp {
962    fn name(&self) -> &'static str {
963        "clamp"
964    }
965
966    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
967        arity(self.name(), inputs, 3)?;
968        no_params(self.name(), params)?;
969        let x = &inputs[1];
970        if x.dtype == DType::Bool || x.dtype.is_complex() {
971            return Err(Error::type_error(
972                self.name(),
973                format!("does not accept {} operands", x.dtype),
974            ));
975        }
976        for b in [&inputs[0], &inputs[2]] {
977            if b.dtype != x.dtype || (b.shape.rank() != 0 && b.shape != x.shape) {
978                return Err(Error::type_error(
979                    self.name(),
980                    format!("bounds must be scalars or match {x}, got {b}"),
981                ));
982            }
983        }
984        Ok(vec![x.clone()])
985    }
986
987    fn eval(&self, _: &dyn EvalCx, inputs: &[HostArray], _: &Params) -> Result<Vec<HostArray>> {
988        let x = &inputs[1];
989        let b = with_buffer!(x.buffer(), |v| {
990            let lo = inputs[0].as_slice().expect("same types");
991            let hi = inputs[2].as_slice().expect("same types");
992            Buffer::from_vec(ruxla_kernels::array::clamp(lo, v, hi))
993        });
994        Ok(vec![HostArray::from_buffer(b, x.shape().clone())])
995    }
996
997    fn batch(
998        &'static self,
999        cx: &mut dyn BatchCx,
1000        inputs: &[Batched],
1001        params: &Params,
1002    ) -> Result<Vec<Batched>> {
1003        // As JAX's `_clamp_batch_rule`.
1004        let (lo, x, hi) = (&inputs[0], &inputs[1], &inputs[2]);
1005        let (lo_aval, x_aval, hi_aval) = (lo.atom.aval(), x.atom.aval(), hi.atom.aval());
1006        let rank = |a: &Atom| a.aval().shape.rank();
1007        let broadcast = |cx: &mut dyn BatchCx, a: Atom, shape: &Shape, dims: Vec<usize>| {
1008            batching::bind1(
1009                cx,
1010                BROADCAST_IN_DIM,
1011                &[a],
1012                Params::BroadcastInDim {
1013                    shape: shape.clone(),
1014                    broadcast_dimensions: dims,
1015                },
1016            )
1017        };
1018        let clamp = |cx: &mut dyn BatchCx, lo: Atom, x: Atom, hi: Atom| {
1019            batching::bind1(cx, CLAMP, &[lo, x, hi], params.clone())
1020        };
1021        // Special cases without transposes.
1022        if let (Some(b), true) = (x.bdim, lo.bdim == x.bdim && hi.bdim == x.bdim) {
1023            if lo_aval.shape == x_aval.shape && hi_aval.shape == x_aval.shape {
1024                let out = clamp(cx, lo.atom.clone(), x.atom.clone(), hi.atom.clone())?;
1025                return Ok(vec![Batched::mapped(out, b)]);
1026            }
1027            if lo_aval.shape.rank() == 1 && hi_aval.shape.rank() == 1 {
1028                let lo = broadcast(cx, lo.atom.clone(), &x_aval.shape, vec![b])?;
1029                let hi = broadcast(cx, hi.atom.clone(), &x_aval.shape, vec![b])?;
1030                let out = clamp(cx, lo, x.atom.clone(), hi)?;
1031                return Ok(vec![Batched::mapped(out, b)]);
1032            }
1033        } else if let Some(b) = x.bdim
1034            && lo_aval.shape.rank() == 0
1035            && hi_aval.shape.rank() == 0
1036        {
1037            let out = clamp(cx, lo.atom.clone(), x.atom.clone(), hi.atom.clone())?;
1038            return Ok(vec![Batched::mapped(out, b)]);
1039        }
1040        // Otherwise the batch dimensions move to the front, and bounds are
1041        // broadcast to the operand.
1042        let front = |cx: &mut dyn BatchCx, v: &Batched| {
1043            if v.atom.aval().shape.rank() > 0 {
1044                batching::bdim_at_front(cx, v)
1045            } else {
1046                Ok(v.atom.clone())
1047            }
1048        };
1049        let mut lo = front(cx, lo)?;
1050        let mut hi = front(cx, hi)?;
1051        let mut x = front(cx, x)?;
1052        let shape = x.aval().shape;
1053        for bound in [&mut lo, &mut hi] {
1054            let r = rank(bound);
1055            if r == 0 && shape.rank() > 0 {
1056                *bound = broadcast(cx, bound.clone(), &shape, vec![])?;
1057            } else if 0 < r && r < shape.rank() {
1058                *bound = broadcast(cx, bound.clone(), &shape, vec![0])?;
1059            }
1060        }
1061        if shape.rank() == 0
1062            && let Some(b) = [&lo, &hi].into_iter().find(|b| rank(b) > 0)
1063        {
1064            let target = b.aval().shape;
1065            x = broadcast(cx, x, &target, vec![])?;
1066        }
1067        let out = clamp(cx, lo, x, hi)?;
1068        Ok(vec![Batched::mapped(out, 0)])
1069    }
1070
1071    fn lower(
1072        &self,
1073        cx: &mut dyn LowerCx,
1074        inputs: &[HloValue],
1075        _: &Params,
1076        outputs: &[AVal],
1077    ) -> Result<Vec<HloValue>> {
1078        let aval = &outputs[0];
1079        if cx.target() == Target::Jax || !aval.dtype.is_float() {
1080            return Ok(vec![cx.op1("stablehlo.clamp", inputs, "", aval)]);
1081        }
1082        // Clamping with NaN propagation (see `Target::Pjrt`).
1083        let bound = |cx: &mut dyn LowerCx, b: &HloValue| {
1084            if b.aval.shape == aval.shape {
1085                b.clone()
1086            } else {
1087                cx.op1(
1088                    "stablehlo.broadcast_in_dim",
1089                    std::slice::from_ref(b),
1090                    "broadcast_dimensions = array<i64>",
1091                    aval,
1092                )
1093            }
1094        };
1095        let lo = bound(cx, &inputs[0]);
1096        let hi = bound(cx, &inputs[2]);
1097        let x = cx.min_max("stablehlo.maximum", &inputs[1], &lo, aval);
1098        Ok(vec![cx.min_max("stablehlo.minimum", &x, &hi, aval)])
1099    }
1100
1101    fn jvp(
1102        &'static self,
1103        cx: &mut dyn AdCx,
1104        primals: &[Atom],
1105        tangents: &[Tangent],
1106        _: &Params,
1107    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
1108        let (a, t) = ad::clamp_jvp(cx, primals, tangents)?;
1109        Ok((vec![a], vec![t]))
1110    }
1111}
1112
1113/// Returns the StableHLO operation of a unary operation lowered one to one.
1114fn unary_hlo(op: UnaryOp) -> &'static str {
1115    match op {
1116        UnaryOp::Neg => "stablehlo.negate",
1117        UnaryOp::Abs => "stablehlo.abs",
1118        UnaryOp::Sign => "stablehlo.sign",
1119        UnaryOp::Not => "stablehlo.not",
1120        UnaryOp::Floor => "stablehlo.floor",
1121        UnaryOp::Ceil => "stablehlo.ceil",
1122        UnaryOp::Round => "stablehlo.round_nearest_afz",
1123        UnaryOp::RoundEven => "stablehlo.round_nearest_even",
1124        UnaryOp::Exp => "stablehlo.exponential",
1125        UnaryOp::Expm1 => "stablehlo.exponential_minus_one",
1126        UnaryOp::Log => "stablehlo.log",
1127        UnaryOp::Log1p => "stablehlo.log_plus_one",
1128        UnaryOp::Sqrt => "stablehlo.sqrt",
1129        UnaryOp::Rsqrt => "stablehlo.rsqrt",
1130        UnaryOp::Cbrt => "stablehlo.cbrt",
1131        UnaryOp::Sin => "stablehlo.sine",
1132        UnaryOp::Cos => "stablehlo.cosine",
1133        UnaryOp::Tan => "stablehlo.tan",
1134        UnaryOp::Tanh => "stablehlo.tanh",
1135        UnaryOp::Logistic => "stablehlo.logistic",
1136        UnaryOp::Square => "stablehlo.multiply",
1137        UnaryOp::ErfInv => "chlo.erf_inv",
1138        // CHLO's operations, which XLA expands, as in JAX (which lowers
1139        // `lgamma` of `f32` with its own implementation instead).
1140        UnaryOp::Lgamma => "chlo.lgamma",
1141        UnaryOp::Digamma => "chlo.digamma",
1142        UnaryOp::Erf => "chlo.erf",
1143        UnaryOp::Erfc => "chlo.erfc",
1144        UnaryOp::BesselI1e => "chlo.bessel_i1e",
1145        UnaryOp::BesselI0e => unreachable!("lowered by tracing"),
1146    }
1147}
1148
1149/// Returns the StableHLO operation of a binary operation.
1150fn binary_hlo(op: BinaryOp) -> &'static str {
1151    match op {
1152        BinaryOp::Add => "stablehlo.add",
1153        BinaryOp::Sub => "stablehlo.subtract",
1154        BinaryOp::Mul => "stablehlo.multiply",
1155        BinaryOp::Div => "stablehlo.divide",
1156        BinaryOp::Rem => "stablehlo.remainder",
1157        BinaryOp::Pow => "stablehlo.power",
1158        BinaryOp::Max => "stablehlo.maximum",
1159        BinaryOp::Min => "stablehlo.minimum",
1160        BinaryOp::Atan2 => "stablehlo.atan2",
1161        BinaryOp::And => "stablehlo.and",
1162        BinaryOp::Or => "stablehlo.or",
1163        BinaryOp::Xor => "stablehlo.xor",
1164        BinaryOp::ShiftLeft => "stablehlo.shift_left",
1165        BinaryOp::ShiftRightLogical => "stablehlo.shift_right_logical",
1166        BinaryOp::ShiftRightArithmetic => "stablehlo.shift_right_arithmetic",
1167        BinaryOp::Polygamma => "chlo.polygamma",
1168        BinaryOp::Zeta => "chlo.zeta",
1169        BinaryOp::Igamma
1170        | BinaryOp::Igammac
1171        | BinaryOp::IgammaGradA
1172        | BinaryOp::RandomGammaGrad => {
1173            unreachable!("lowered by tracing")
1174        }
1175    }
1176}
1177
1178/// Emits `stablehlo.real` or `stablehlo.imag` of a complex value.
1179pub(crate) fn complex_part(cx: &mut dyn LowerCx, x: &HloValue, imag: bool) -> HloValue {
1180    let part = AVal::new(x.aval.shape.clone(), x.aval.dtype.real_dtype());
1181    let op = if imag {
1182        "stablehlo.imag"
1183    } else {
1184        "stablehlo.real"
1185    };
1186    cx.op1(op, std::slice::from_ref(x), "", &part)
1187}
1188
1189/// Emits `stablehlo.complex` of real and imaginary parts.
1190pub(crate) fn make_complex(cx: &mut dyn LowerCx, re: &HloValue, im: &HloValue) -> HloValue {
1191    let dtype = re.aval.dtype.complex_dtype().expect("f32 or f64 parts");
1192    let out = AVal::new(re.aval.shape.clone(), dtype);
1193    cx.op1("stablehlo.complex", &[re.clone(), im.clone()], "", &out)
1194}
1195
1196/// The `abs` of complex numbers as JAX lowers it: `lax.hypot` of the real
1197/// and imaginary parts (see [`ruxla_kernels::Complex::abs`]).
1198fn lower_complex_abs(cx: &mut dyn LowerCx, x: &HloValue, out: &AVal) -> HloValue {
1199    let (k, e_hi) = if out.dtype == DType::F32 {
1200        (75, 63)
1201    } else {
1202        (537, 511)
1203    };
1204    let pred = AVal::new(out.shape.clone(), DType::Bool);
1205    let x1 = complex_part(cx, x, false);
1206    let x2 = complex_part(cx, x, true);
1207    let a1 = cx.op1("stablehlo.abs", std::slice::from_ref(&x1), "", out);
1208    let a2 = cx.op1("stablehlo.abs", std::slice::from_ref(&x2), "", out);
1209    let m = cx.min_max("stablehlo.maximum", &a1, &a2, out);
1210    let pow2 = |cx: &mut dyn LowerCx, e: i32| cx.splat(Value::Float(2f64.powi(e)), out);
1211    let big = pow2(cx, e_hi);
1212    let hi = compare(cx, "GE", &m, &big, &pred);
1213    let small = pow2(cx, e_hi - k);
1214    let lo = compare(cx, "LE", &m, &small, &pred);
1215    let s_down = pow2(cx, -k);
1216    let s_up = pow2(cx, k);
1217    let one = cx.splat(Value::Float(1.0), out);
1218    let select = |cx: &mut dyn LowerCx, p: &HloValue, a: &HloValue, b: &HloValue| {
1219        cx.op1(
1220            "stablehlo.select",
1221            &[p.clone(), a.clone(), b.clone()],
1222            "",
1223            out,
1224        )
1225    };
1226    let mul = |cx: &mut dyn LowerCx, a: &HloValue, b: &HloValue| {
1227        cx.op1("stablehlo.multiply", &[a.clone(), b.clone()], "", out)
1228    };
1229    let mut scaled = Vec::new();
1230    for xi in [&x1, &x2] {
1231        let down = mul(cx, xi, &s_down);
1232        let up = mul(cx, xi, &s_up);
1233        let inner = select(cx, &lo, &up, xi);
1234        scaled.push(select(cx, &hi, &down, &inner));
1235    }
1236    let inner = select(cx, &lo, &s_down, &one);
1237    let inv_scale = select(cx, &hi, &s_up, &inner);
1238    let sq1 = mul(cx, &scaled[0], &scaled[0]);
1239    let sq2 = mul(cx, &scaled[1], &scaled[1]);
1240    let sum = cx.op1("stablehlo.add", &[sq1, sq2], "", out);
1241    let r_scaled = cx.op1("stablehlo.sqrt", &[sum], "", out);
1242    let r = mul(cx, &r_scaled, &inv_scale);
1243    let inf = cx.splat(Value::Float(f64::INFINITY), out);
1244    let i1 = compare(cx, "EQ", &a1, &inf, &pred);
1245    let i2 = compare(cx, "EQ", &a2, &inf, &pred);
1246    let either = cx.op1("stablehlo.or", &[i1, i2], "", &pred);
1247    select(cx, &either, &inf, &r)
1248}
1249
1250/// `sin` and `cos` of complex numbers as JAX lowers them (`_sin_complex`
1251/// and `_cos_complex`, with `expm1` against cancellation).
1252fn lower_complex_sin_cos(cx: &mut dyn LowerCx, x: &HloValue, cos: bool) -> HloValue {
1253    let a = complex_part(cx, x, false);
1254    let b = complex_part(cx, x, true);
1255    let part = a.aval.clone();
1256    let pred = AVal::new(part.shape.clone(), DType::Bool);
1257    let zero = cx.splat(Value::Float(0.0), &part);
1258    let two = cx.splat(Value::Float(2.0), &part);
1259    let a_is_zero = compare(cx, "EQ", &a, &zero, &pred);
1260    let sn = cx.op1("stablehlo.sine", std::slice::from_ref(&a), "", &part);
1261    let cs = cx.op1("stablehlo.cosine", std::slice::from_ref(&a), "", &part);
1262    let e1m = cx.op1(
1263        "stablehlo.exponential_minus_one",
1264        std::slice::from_ref(&b),
1265        "",
1266        &part,
1267    );
1268    let nb = cx.op1("stablehlo.negate", &[b], "", &part);
1269    let e2m = cx.op1("stablehlo.exponential_minus_one", &[nb], "", &part);
1270    let d = cx.op1("stablehlo.subtract", &[e1m.clone(), e2m.clone()], "", &part);
1271    let snh = cx.op1("stablehlo.divide", &[d, two.clone()], "", &part);
1272    let s = cx.op1("stablehlo.add", &[e1m, e2m], "", &part);
1273    let s = cx.op1("stablehlo.add", &[s, two.clone()], "", &part);
1274    let csh = cx.op1("stablehlo.divide", &[s, two], "", &part);
1275    let (re, im) = if cos {
1276        let re = cx.op1("stablehlo.multiply", &[cs, csh], "", &part);
1277        let nsn = cx.op1("stablehlo.negate", &[sn], "", &part);
1278        let im = cx.op1("stablehlo.multiply", &[nsn, snh], "", &part);
1279        (re, im)
1280    } else {
1281        let re = cx.op1("stablehlo.multiply", &[sn, csh], "", &part);
1282        let im = cx.op1("stablehlo.multiply", &[cs, snh], "", &part);
1283        (re, im)
1284    };
1285    let special = if cos {
1286        make_complex(cx, &re, &zero)
1287    } else {
1288        make_complex(cx, &zero, &im)
1289    };
1290    let general = make_complex(cx, &re, &im);
1291    cx.op1(
1292        "stablehlo.select",
1293        &[a_is_zero, special, general],
1294        "",
1295        &x.aval,
1296    )
1297}
1298
1299/// `max` and `min` of complex numbers as JAX lowers them: lexicographic
1300/// comparisons of the parts select `x` or `y`.
1301fn lower_complex_min_max(cx: &mut dyn LowerCx, max: bool, x: &HloValue, y: &HloValue) -> HloValue {
1302    let direction = if max { "GT" } else { "LT" };
1303    let pred = AVal::new(x.aval.shape.clone(), DType::Bool);
1304    let (rx, ry) = (complex_part(cx, x, false), complex_part(cx, y, false));
1305    let real_eq = compare(cx, "EQ", &rx, &ry, &pred);
1306    let real_cmp = compare(cx, direction, &rx, &ry, &pred);
1307    let (ix, iy) = (complex_part(cx, x, true), complex_part(cx, y, true));
1308    let imag_cmp = compare(cx, direction, &ix, &iy, &pred);
1309    let which = cx.op1(
1310        "stablehlo.select",
1311        &[real_eq, imag_cmp, real_cmp],
1312        "",
1313        &pred,
1314    );
1315    cx.op1(
1316        "stablehlo.select",
1317        &[which, x.clone(), y.clone()],
1318        "",
1319        &x.aval,
1320    )
1321}
1322
1323/// Emits `stablehlo.compare` with the comparison type of the operands.
1324pub(crate) fn compare(
1325    cx: &mut dyn LowerCx,
1326    direction: &str,
1327    a: &HloValue,
1328    b: &HloValue,
1329    out: &AVal,
1330) -> HloValue {
1331    let compare_type = match a.aval.dtype.kind() {
1332        DTypeKind::Float | DTypeKind::Complex => "FLOAT",
1333        DTypeKind::SignedInt => "SIGNED",
1334        DTypeKind::UnsignedInt | DTypeKind::Bool => "UNSIGNED",
1335    };
1336    let attrs = format!(
1337        "comparison_direction = #stablehlo<comparison_direction {direction}>, \
1338         compare_type = #stablehlo<comparison_type {compare_type}>"
1339    );
1340    cx.op1("stablehlo.compare", &[a.clone(), b.clone()], &attrs, out)
1341}
1342
1343/// An evaluation context for primitives without nested functions.
1344struct NoCx;
1345
1346impl EvalCx for NoCx {
1347    fn eval_function(&self, _: &ruxla_ir::Function, _: &[HostArray]) -> Result<Vec<HostArray>> {
1348        Err(Error::Malformed(String::from("no nested functions here")))
1349    }
1350}
1351
1352macro_rules! unary {
1353    ($($(#[$m:meta])* $name:ident => $op:ident;)*) => {$(
1354        $(#[$m])*
1355        pub static $name: Prim = Prim::new(&Unary(UnaryOp::$op));
1356    )*};
1357}
1358
1359macro_rules! binary {
1360    ($($(#[$m:meta])* $name:ident => $op:ident;)*) => {$(
1361        $(#[$m])*
1362        pub static $name: Prim = Prim::new(&Binary(BinaryOp::$op));
1363    )*};
1364}
1365
1366macro_rules! compare {
1367    ($($(#[$m:meta])* $name:ident => $op:ident;)*) => {$(
1368        $(#[$m])*
1369        pub static $name: Prim = Prim::new(&Compare(CompareOp::$op));
1370    )*};
1371}
1372
1373unary! {
1374    /// `-x`.
1375    NEG => Neg;
1376    /// `|x|`.
1377    ABS => Abs;
1378    /// The sign.
1379    SIGN => Sign;
1380    /// Logical or bitwise not.
1381    NOT => Not;
1382    /// Round down.
1383    FLOOR => Floor;
1384    /// Round up.
1385    CEIL => Ceil;
1386    /// `e^x`.
1387    EXP => Exp;
1388    /// `e^x - 1`.
1389    EXPM1 => Expm1;
1390    /// Natural logarithm.
1391    LOG => Log;
1392    /// `log(1 + x)`.
1393    LOG1P => Log1p;
1394    /// Square root.
1395    SQRT => Sqrt;
1396    /// `1 / sqrt(x)`.
1397    RSQRT => Rsqrt;
1398    /// Cube root.
1399    CBRT => Cbrt;
1400    /// Sine.
1401    SIN => Sin;
1402    /// Cosine.
1403    COS => Cos;
1404    /// Tangent.
1405    TAN => Tan;
1406    /// Hyperbolic tangent.
1407    TANH => Tanh;
1408    /// The logistic sigmoid.
1409    LOGISTIC => Logistic;
1410    /// `x * x`.
1411    SQUARE => Square;
1412    /// The inverse error function.
1413    ERF_INV => ErfInv;
1414    /// The logarithm of the absolute value of the gamma function.
1415    LGAMMA => Lgamma;
1416    /// The digamma function.
1417    DIGAMMA => Digamma;
1418    /// The error function.
1419    ERF => Erf;
1420    /// The complementary error function.
1421    ERFC => Erfc;
1422    /// `exp(-|x|) I0(x)`.
1423    BESSEL_I0E => BesselI0e;
1424    /// `exp(-|x|) I1(x)`.
1425    BESSEL_I1E => BesselI1e;
1426}
1427
1428binary! {
1429    /// `x + y`.
1430    ADD => Add;
1431    /// `x - y`.
1432    SUB => Sub;
1433    /// `x * y`.
1434    MUL => Mul;
1435    /// `x / y`.
1436    DIV => Div;
1437    /// Remainder.
1438    REM => Rem;
1439    /// `x^y`.
1440    POW => Pow;
1441    /// Maximum.
1442    MAX => Max;
1443    /// Minimum.
1444    MIN => Min;
1445    /// `atan2(x, y)`.
1446    ATAN2 => Atan2;
1447    /// Logical or bitwise and.
1448    AND => And;
1449    /// Logical or bitwise or.
1450    OR => Or;
1451    /// Logical or bitwise exclusive or.
1452    XOR => Xor;
1453    /// `x << y`.
1454    SHIFT_LEFT => ShiftLeft;
1455    /// `x >> y`, filling with zeros.
1456    SHIFT_RIGHT_LOGICAL => ShiftRightLogical;
1457    /// `x >> y`, filling with the sign bit.
1458    SHIFT_RIGHT_ARITHMETIC => ShiftRightArithmetic;
1459    /// The regularized lower incomplete gamma function.
1460    IGAMMA => Igamma;
1461    /// The regularized upper incomplete gamma function.
1462    IGAMMAC => Igammac;
1463    /// The derivative of `igamma` with respect to its first operand.
1464    IGAMMA_GRAD_A => IgammaGradA;
1465    /// The derivative of a sample of `Gamma(a, 1)` with respect to `a`.
1466    RANDOM_GAMMA_GRAD => RandomGammaGrad;
1467    /// The polygamma function.
1468    POLYGAMMA => Polygamma;
1469    /// The Hurwitz zeta function.
1470    ZETA => Zeta;
1471}
1472
1473compare! {
1474    /// `x == y`.
1475    EQ => Eq;
1476    /// `x != y`.
1477    NE => Ne;
1478    /// `x < y`.
1479    LT => Lt;
1480    /// `x <= y`.
1481    LE => Le;
1482    /// `x > y`.
1483    GT => Gt;
1484    /// `x >= y`.
1485    GE => Ge;
1486}
1487
1488/// The regularized incomplete beta function `I_x(a, b)` of `(a, b, x)`.
1489pub static REGULARIZED_INCOMPLETE_BETA: Prim =
1490    Prim::new(&Ternary(TernaryOp::RegularizedIncompleteBeta));
1491/// Whether each element is finite.
1492pub static IS_FINITE: Prim = Prim::new(&IsFinite);
1493/// Round to an integer ([`Params::Round`]).
1494pub static ROUND: Prim = Prim::new(&Round);
1495/// `x^y` for a static integer `y` ([`Params::IntegerPow`]).
1496pub static INTEGER_POW: Prim = Prim::new(&IntegerPow);
1497/// Convert to another element type ([`Params::Convert`]).
1498pub static CONVERT_ELEMENT_TYPE: Prim = Prim::new(&ConvertElementType);
1499/// Reinterpret the bits as another type of the same size.
1500pub static BITCAST_CONVERT_TYPE: Prim = Prim::new(&BitcastConvertType);
1501/// Select elements from cases.
1502pub static SELECT_N: Prim = Prim::new(&SelectN);
1503/// Clamp to bounds.
1504pub static CLAMP: Prim = Prim::new(&Clamp);
1505
1506/// Returns the primitive of a [`UnaryOp`] (`round` and `round_even` map to
1507/// the `round` primitive with a method).
1508pub fn unary_prim(op: UnaryOp) -> (Prim, Params) {
1509    let p = match op {
1510        UnaryOp::Round => {
1511            return (
1512                ROUND,
1513                Params::Round {
1514                    method: RoundingMethod::AwayFromZero,
1515                },
1516            );
1517        }
1518        UnaryOp::RoundEven => {
1519            return (
1520                ROUND,
1521                Params::Round {
1522                    method: RoundingMethod::ToNearestEven,
1523                },
1524            );
1525        }
1526        UnaryOp::Neg => NEG,
1527        UnaryOp::Abs => ABS,
1528        UnaryOp::Sign => SIGN,
1529        UnaryOp::Not => NOT,
1530        UnaryOp::Floor => FLOOR,
1531        UnaryOp::Ceil => CEIL,
1532        UnaryOp::Exp => EXP,
1533        UnaryOp::Expm1 => EXPM1,
1534        UnaryOp::Log => LOG,
1535        UnaryOp::Log1p => LOG1P,
1536        UnaryOp::Sqrt => SQRT,
1537        UnaryOp::Rsqrt => RSQRT,
1538        UnaryOp::Cbrt => CBRT,
1539        UnaryOp::Sin => SIN,
1540        UnaryOp::Cos => COS,
1541        UnaryOp::Tan => TAN,
1542        UnaryOp::Tanh => TANH,
1543        UnaryOp::Logistic => LOGISTIC,
1544        UnaryOp::Square => SQUARE,
1545        UnaryOp::ErfInv => ERF_INV,
1546        UnaryOp::Lgamma => LGAMMA,
1547        UnaryOp::Digamma => DIGAMMA,
1548        UnaryOp::Erf => ERF,
1549        UnaryOp::Erfc => ERFC,
1550        UnaryOp::BesselI0e => BESSEL_I0E,
1551        UnaryOp::BesselI1e => BESSEL_I1E,
1552    };
1553    (p, Params::None)
1554}
1555
1556/// Returns the primitive of a [`BinaryOp`].
1557pub fn binary_prim(op: BinaryOp) -> Prim {
1558    match op {
1559        BinaryOp::Add => ADD,
1560        BinaryOp::Sub => SUB,
1561        BinaryOp::Mul => MUL,
1562        BinaryOp::Div => DIV,
1563        BinaryOp::Rem => REM,
1564        BinaryOp::Pow => POW,
1565        BinaryOp::Max => MAX,
1566        BinaryOp::Min => MIN,
1567        BinaryOp::Atan2 => ATAN2,
1568        BinaryOp::And => AND,
1569        BinaryOp::Or => OR,
1570        BinaryOp::Xor => XOR,
1571        BinaryOp::ShiftLeft => SHIFT_LEFT,
1572        BinaryOp::ShiftRightLogical => SHIFT_RIGHT_LOGICAL,
1573        BinaryOp::ShiftRightArithmetic => SHIFT_RIGHT_ARITHMETIC,
1574        BinaryOp::Igamma => IGAMMA,
1575        BinaryOp::Igammac => IGAMMAC,
1576        BinaryOp::IgammaGradA => IGAMMA_GRAD_A,
1577        BinaryOp::RandomGammaGrad => RANDOM_GAMMA_GRAD,
1578        BinaryOp::Polygamma => POLYGAMMA,
1579        BinaryOp::Zeta => ZETA,
1580    }
1581}
1582
1583/// Returns the primitive of a [`TernaryOp`].
1584pub fn ternary_prim(op: TernaryOp) -> Prim {
1585    match op {
1586        TernaryOp::RegularizedIncompleteBeta => REGULARIZED_INCOMPLETE_BETA,
1587    }
1588}
1589
1590/// Returns the primitive of a [`CompareOp`].
1591pub fn compare_prim(op: CompareOp) -> Prim {
1592    match op {
1593        CompareOp::Eq => EQ,
1594        CompareOp::Ne => NE,
1595        CompareOp::Lt => LT,
1596        CompareOp::Le => LE,
1597        CompareOp::Gt => GT,
1598        CompareOp::Ge => GE,
1599    }
1600}