Skip to main content

ruxla_ir/
primitive.rs

1//! The interface of primitives.
2
3use std::fmt;
4
5use crate::Atom;
6use crate::ad::{AdCx, Tangent, TransposeInput};
7use crate::batching::{BatchCx, Batched};
8use crate::error::Error;
9use crate::error::Result;
10use crate::function::{Function, Params};
11use crate::host::HostArray;
12use crate::lowering::{HloValue, LowerCx};
13use crate::shape::AVal;
14
15/// Evaluates nested functions, for primitives that contain functions.
16pub trait EvalCx {
17    /// Evaluates `f` on `args`.
18    ///
19    /// # Errors
20    ///
21    /// Returns an error from a primitive of `f`.
22    fn eval_function(&self, f: &Function, args: &[HostArray]) -> Result<Vec<HostArray>>;
23}
24
25/// A primitive: the smallest unit that carries rules for every
26/// transformation and backend.
27///
28/// It has the rules for shape inference, evaluation, lowering to StableHLO,
29/// batching (`vmap`), and differentiation (`jvp` and `transpose`).
30pub trait Primitive: Send + Sync + 'static {
31    /// The name, as in JAX (`add`, `reduce_sum`, ...).
32    fn name(&self) -> &'static str;
33
34    /// Returns the abstract values of the outputs.
35    ///
36    /// # Errors
37    ///
38    /// Returns an error if the inputs or parameters are not accepted.
39    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>>;
40
41    /// Evaluates the primitive on host arrays, with `ruxla-kernels`.
42    ///
43    /// # Errors
44    ///
45    /// Returns an error if the inputs are not accepted.
46    fn eval(
47        &self,
48        cx: &dyn EvalCx,
49        inputs: &[HostArray],
50        params: &Params,
51    ) -> Result<Vec<HostArray>>;
52
53    /// Emits the StableHLO operations of the primitive.
54    ///
55    /// # Errors
56    ///
57    /// Returns an error if the primitive cannot be lowered for these inputs.
58    fn lower(
59        &self,
60        cx: &mut dyn LowerCx,
61        inputs: &[HloValue],
62        params: &Params,
63        outputs: &[AVal],
64    ) -> Result<Vec<HloValue>> {
65        let _ = (cx, inputs, params, outputs);
66        Err(Error::unsupported(self.name(), "no lowering to StableHLO"))
67    }
68
69    /// Emits the batched version of the primitive (`vmap`).
70    ///
71    /// `inputs` carry their batch dimensions, at least one of which is not
72    /// `None`. The rule returns the outputs with their batch dimensions. It
73    /// follows JAX's batching rule of the primitive, so that the batched IR
74    /// has the same form as JAX's (see [`crate::batching`]).
75    ///
76    /// # Errors
77    ///
78    /// Returns an error if the primitive cannot be batched for these inputs.
79    fn batch(
80        &'static self,
81        cx: &mut dyn BatchCx,
82        inputs: &[Batched],
83        params: &Params,
84    ) -> Result<Vec<Batched>> {
85        let _ = (cx, inputs, params);
86        Err(Error::unsupported(self.name(), "no batching rule"))
87    }
88
89    /// The JVP rule: returns the outputs for `primals` and their tangents
90    /// for the input `tangents` (`None` for symbolic zeros; not all are
91    /// zero), computed with operations linear in the tangents.
92    ///
93    /// # Errors
94    ///
95    /// Returns an error if the primitive cannot be differentiated.
96    fn jvp(
97        &'static self,
98        cx: &mut dyn AdCx,
99        primals: &[Atom],
100        tangents: &[Tangent],
101        params: &Params,
102    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
103        let _ = (cx, primals, tangents, params);
104        Err(Error::unsupported(self.name(), "no differentiation rule"))
105    }
106
107    /// The transpose rule of a primitive that is linear in its
108    /// [`TransposeInput::Linear`] inputs: returns the cotangent of each
109    /// input (`None` for constant inputs and symbolic zeros) for the output
110    /// `cotangents` (not all zero).
111    ///
112    /// # Errors
113    ///
114    /// Returns an error if the primitive is not linear in those inputs.
115    fn transpose(
116        &'static self,
117        cx: &mut dyn AdCx,
118        cotangents: &[Tangent],
119        inputs: &[TransposeInput],
120        params: &Params,
121    ) -> Result<Vec<Tangent>> {
122        let _ = (cx, cotangents, inputs, params);
123        Err(Error::unsupported(self.name(), "no transpose rule"))
124    }
125}
126
127/// A handle to a primitive, compared by name.
128#[derive(Clone, Copy)]
129pub struct Prim(&'static dyn Primitive);
130
131impl Prim {
132    /// Creates a handle.
133    pub const fn new(p: &'static dyn Primitive) -> Self {
134        Self(p)
135    }
136
137    /// Returns the name.
138    pub fn name(self) -> &'static str {
139        self.0.name()
140    }
141
142    /// Calls [`Primitive::abstract_eval`].
143    ///
144    /// # Errors
145    ///
146    /// See [`Primitive::abstract_eval`].
147    pub fn abstract_eval(self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
148        self.0.abstract_eval(inputs, params)
149    }
150
151    /// Calls [`Primitive::eval`].
152    ///
153    /// # Errors
154    ///
155    /// See [`Primitive::eval`].
156    pub fn eval(
157        self,
158        cx: &dyn EvalCx,
159        inputs: &[HostArray],
160        params: &Params,
161    ) -> Result<Vec<HostArray>> {
162        self.0.eval(cx, inputs, params)
163    }
164}
165
166impl Prim {
167    /// Calls [`Primitive::lower`].
168    ///
169    /// # Errors
170    ///
171    /// See [`Primitive::lower`].
172    pub fn lower(
173        self,
174        cx: &mut dyn LowerCx,
175        inputs: &[HloValue],
176        params: &Params,
177        outputs: &[AVal],
178    ) -> Result<Vec<HloValue>> {
179        self.0.lower(cx, inputs, params, outputs)
180    }
181
182    /// Calls [`Primitive::batch`].
183    ///
184    /// # Errors
185    ///
186    /// See [`Primitive::batch`].
187    pub fn batch(
188        self,
189        cx: &mut dyn BatchCx,
190        inputs: &[Batched],
191        params: &Params,
192    ) -> Result<Vec<Batched>> {
193        self.0.batch(cx, inputs, params)
194    }
195
196    /// Applies the JVP rule.
197    ///
198    /// # Errors
199    ///
200    /// See [`Primitive::jvp`].
201    pub fn jvp(
202        self,
203        cx: &mut dyn AdCx,
204        primals: &[Atom],
205        tangents: &[Tangent],
206        params: &Params,
207    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
208        self.0.jvp(cx, primals, tangents, params)
209    }
210
211    /// Applies the transpose rule.
212    ///
213    /// # Errors
214    ///
215    /// See [`Primitive::transpose`].
216    pub fn transpose(
217        self,
218        cx: &mut dyn AdCx,
219        cotangents: &[Tangent],
220        inputs: &[TransposeInput],
221        params: &Params,
222    ) -> Result<Vec<Tangent>> {
223        self.0.transpose(cx, cotangents, inputs, params)
224    }
225}
226
227impl PartialEq for Prim {
228    fn eq(&self, other: &Self) -> bool {
229        self.name() == other.name()
230    }
231}
232
233impl Eq for Prim {}
234
235impl fmt::Debug for Prim {
236    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
237        f.write_str(self.name())
238    }
239}
240
241impl fmt::Display for Prim {
242    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243        f.write_str(self.name())
244    }
245}