Skip to main content

ruxla_ir/
lowering.rs

1//! The interface for lowering primitives to StableHLO.
2//!
3//! Each primitive lowers itself through [`LowerCx`], which emits StableHLO
4//! operations in the MLIR generic form, such as
5//! `%2 = "stablehlo.add"(%0, %1) : (tensor<3xf32>, tensor<3xf32>) -> tensor<3xf32>`.
6//! The `ruxla-stablehlo` crate implements the context and assembles the
7//! operations into functions and modules.
8
9use std::fmt::Write as _;
10
11use crate::error::Result;
12use crate::function::Function;
13use crate::host::HostArray;
14use crate::shape::AVal;
15use ruxla_kernels::{DType, Value};
16
17/// A value in the StableHLO being emitted: an SSA name and its type.
18#[derive(Clone, Debug, PartialEq)]
19pub struct HloValue {
20    /// The SSA name, such as `%3`.
21    pub name: String,
22    /// The abstract value.
23    pub aval: AVal,
24}
25
26/// The body of a region, called with the region's arguments and returning
27/// the values passed to its `stablehlo.return`.
28pub type RegionBody<'a> = dyn FnMut(&mut dyn LowerCx, &[HloValue]) -> Result<Vec<HloValue>> + 'a;
29
30/// A region of an operation such as `stablehlo.reduce` or `stablehlo.while`.
31pub struct Region<'a> {
32    /// The types of the region's block arguments.
33    pub args: Vec<AVal>,
34    /// Emits the region's operations.
35    pub body: &'a mut RegionBody<'a>,
36}
37
38impl std::fmt::Debug for Region<'_> {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.debug_struct("Region")
41            .field("args", &self.args)
42            .finish_non_exhaustive()
43    }
44}
45
46/// Where the emitted StableHLO will be compiled.
47///
48/// The output is the same for both targets except where a PJRT plugin's
49/// defaults differ from the semantics ruxla guarantees.
50#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
51pub enum Target {
52    /// Compiled by a PJRT plugin from Rust (the default).
53    ///
54    /// Some CPU plugins enable XLA's fast min/max, under which `maximum` and
55    /// `minimum` do not propagate NaN, and XLA's debug options cannot be
56    /// overridden one by one. NaN propagation is therefore made explicit.
57    #[default]
58    Pjrt,
59    /// Embedded in a module that JAX compiles. The output follows JAX's own
60    /// lowering, so that the optimized HLO matches a JAX implementation.
61    Jax,
62}
63
64/// The kind of device the StableHLO is compiled for, where JAX lowers a
65/// primitive differently by platform (such as `threefry2x32`, with rolled
66/// loops on CPU and unrolled on GPU).
67#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
68pub enum Platform {
69    /// CPUs (the default).
70    #[default]
71    Cpu,
72    /// GPUs (CUDA or ROCm).
73    Gpu,
74}
75
76/// A context that emits StableHLO operations.
77pub trait LowerCx {
78    /// Returns where the StableHLO will be compiled.
79    fn target(&self) -> Target;
80
81    /// Returns the kind of device the StableHLO is compiled for.
82    fn platform(&self) -> Platform {
83        Platform::Cpu
84    }
85
86    /// Emits an operation and returns its results.
87    ///
88    /// `attributes` is the attribute dictionary without braces, such as
89    /// `broadcast_dimensions = array<i64: 1>`, or empty.
90    fn op(
91        &mut self,
92        name: &str,
93        operands: &[HloValue],
94        attributes: &str,
95        results: &[AVal],
96    ) -> Vec<HloValue>;
97
98    /// Emits an operation with regions and returns its results.
99    ///
100    /// # Errors
101    ///
102    /// Returns an error from lowering a region's body.
103    fn op_with_regions(
104        &mut self,
105        name: &str,
106        operands: &[HloValue],
107        attributes: &str,
108        regions: &mut [Region<'_>],
109        results: &[AVal],
110    ) -> Result<Vec<HloValue>>;
111
112    /// Emits a constant.
113    fn constant(&mut self, value: &HostArray) -> HloValue;
114
115    /// Adds the functions of another StableHLO module (such as one written
116    /// by `jax.export`) to the module, renamed after `name_hint`, and
117    /// returns the new symbol name of its public `main` (without `@`).
118    ///
119    /// # Errors
120    ///
121    /// Returns an error if the module cannot be parsed or has no `main`.
122    fn import(&mut self, module: &str, name_hint: &str) -> Result<String>;
123
124    /// Lowers a function as a private function of the module and returns
125    /// its symbol name (without `@`).
126    ///
127    /// # Errors
128    ///
129    /// Returns an error from lowering the function.
130    fn function(&mut self, f: &Function, name_hint: &str) -> Result<String>;
131}
132
133impl dyn LowerCx + '_ {
134    /// Emits an operation with one result.
135    pub fn op1(
136        &mut self,
137        name: &str,
138        operands: &[HloValue],
139        attributes: &str,
140        result: &AVal,
141    ) -> HloValue {
142        self.op(name, operands, attributes, std::slice::from_ref(result))
143            .pop()
144            .expect("one result")
145    }
146
147    /// Emits `stablehlo.maximum` or `stablehlo.minimum` (given as `op`) with
148    /// NaN propagation, which StableHLO specifies but some PJRT plugins
149    /// disable by default (see [`Target::Pjrt`]).
150    pub fn min_max(&mut self, op: &str, a: &HloValue, b: &HloValue, aval: &AVal) -> HloValue {
151        let result = self.op1(op, &[a.clone(), b.clone()], "", aval);
152        if self.target() == Target::Jax || !aval.dtype.is_float() {
153            return result;
154        }
155        let pred_aval = AVal::new(aval.shape.clone(), DType::Bool);
156        let is_nan = |cx: &mut Self, x: &HloValue| {
157            cx.op1(
158                "stablehlo.compare",
159                &[x.clone(), x.clone()],
160                "comparison_direction = #stablehlo<comparison_direction NE>, \
161                 compare_type = #stablehlo<comparison_type FLOAT>",
162                &pred_aval,
163            )
164        };
165        let a_nan = is_nan(self, a);
166        let result = self.op1("stablehlo.select", &[a_nan, a.clone(), result], "", aval);
167        let b_nan = is_nan(self, b);
168        self.op1("stablehlo.select", &[b_nan, b.clone(), result], "", aval)
169    }
170
171    /// Emits a scalar constant broadcast to `aval`.
172    pub fn splat(&mut self, value: Value, aval: &AVal) -> HloValue {
173        let scalar = self.constant(&HostArray::full(crate::Shape::scalar(), aval.dtype, value));
174        if aval.shape.rank() == 0 {
175            return scalar;
176        }
177        self.op1(
178            "stablehlo.broadcast_in_dim",
179            &[scalar],
180            "broadcast_dimensions = array<i64>",
181            aval,
182        )
183    }
184}
185
186/// Returns the MLIR element type of a dtype, such as `f32` or `ui8`.
187pub fn element_type(dtype: DType) -> &'static str {
188    match dtype {
189        DType::Bool => "i1",
190        DType::I8 => "i8",
191        DType::I16 => "i16",
192        DType::I32 => "i32",
193        DType::I64 => "i64",
194        DType::U8 => "ui8",
195        DType::U16 => "ui16",
196        DType::U32 => "ui32",
197        DType::U64 => "ui64",
198        DType::F16 => "f16",
199        DType::BF16 => "bf16",
200        DType::F32 => "f32",
201        DType::F64 => "f64",
202        DType::C64 => "complex<f32>",
203        DType::C128 => "complex<f64>",
204    }
205}
206
207/// Returns the MLIR tensor type of an abstract value, such as
208/// `tensor<2x3xf32>`.
209pub fn tensor_type(aval: &AVal) -> String {
210    let mut s = String::from("tensor<");
211    for d in aval.shape.iter() {
212        let _ = write!(s, "{d}x");
213    }
214    s.push_str(element_type(aval.dtype));
215    s.push('>');
216    s
217}
218
219/// Formats a list of integers as a dense array attribute, such as
220/// `array<i64: 0, 2>`.
221pub fn i64_array(values: &[usize]) -> String {
222    if values.is_empty() {
223        return String::from("array<i64>");
224    }
225    let items: Vec<String> = values.iter().map(ToString::to_string).collect();
226    format!("array<i64: {}>", items.join(", "))
227}
228
229/// Formats a host array as a dense elements attribute with its type, such
230/// as `dense<"0x0000803F"> : tensor<f32>`.
231///
232/// Elements are written as little-endian hexadecimal bytes, which is exact
233/// for every type; booleans are written as `true` and `false`.
234pub fn dense_attr(value: &HostArray) -> String {
235    let ty = tensor_type(&AVal::new(value.shape().clone(), value.dtype()));
236    if value.size() == 0 {
237        return format!("dense<> : {ty}");
238    }
239    if value.dtype() == DType::Bool {
240        let bytes = value.to_bytes();
241        let bits: Vec<&str> = bytes
242            .iter()
243            .map(|&b| if b != 0 { "true" } else { "false" })
244            .collect();
245        let body = if value.shape().rank() == 0 {
246            bits[0].to_string()
247        } else {
248            nested_list(&bits, value.shape())
249        };
250        return format!("dense<{body}> : {ty}");
251    }
252    let bytes = value.to_bytes();
253    let mut hex = String::with_capacity(2 + bytes.len() * 2);
254    hex.push_str("0x");
255    // Each part of a complex number is a little-endian float.
256    let part = value.dtype().real_dtype().size_in_bytes();
257    for chunk in bytes.chunks_exact(part) {
258        let mut le = chunk.to_vec();
259        if cfg!(target_endian = "big") {
260            le.reverse();
261        }
262        for b in le {
263            let _ = write!(hex, "{b:02X}");
264        }
265    }
266    format!("dense<\"{hex}\"> : {ty}")
267}
268
269/// Formats elements as nested lists, such as `[[true, false], [false, true]]`.
270fn nested_list(items: &[&str], dims: &[usize]) -> String {
271    match dims {
272        [] => items[0].to_string(),
273        [_] => format!("[{}]", items.join(", ")),
274        [d, rest @ ..] => {
275            let step = rest.iter().product::<usize>();
276            let parts: Vec<String> = (0..*d)
277                .map(|i| nested_list(&items[i * step..(i + 1) * step], rest))
278                .collect();
279            format!("[{}]", parts.join(", "))
280        }
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287
288    #[test]
289    fn types() {
290        assert_eq!(
291            tensor_type(&AVal::new([2, 3], DType::F32)),
292            "tensor<2x3xf32>"
293        );
294        assert_eq!(tensor_type(&AVal::scalar(DType::U8)), "tensor<ui8>");
295        assert_eq!(
296            tensor_type(&AVal::new([2], DType::C64)),
297            "tensor<2xcomplex<f32>>"
298        );
299        assert_eq!(i64_array(&[]), "array<i64>");
300        assert_eq!(i64_array(&[1, 0]), "array<i64: 1, 0>");
301    }
302
303    #[test]
304    fn dense_attributes() {
305        assert_eq!(
306            dense_attr(&HostArray::scalar(1.0f32)),
307            "dense<\"0x0000803F\"> : tensor<f32>"
308        );
309        assert_eq!(
310            dense_attr(&HostArray::from_vec(vec![1i32, -1], [2])),
311            "dense<\"0x01000000FFFFFFFF\"> : tensor<2xi32>"
312        );
313        assert_eq!(
314            dense_attr(&HostArray::from_vec(vec![true, false, false, true], [2, 2])),
315            "dense<[[true, false], [false, true]]> : tensor<2x2xi1>"
316        );
317        assert_eq!(
318            dense_attr(&HostArray::scalar(ruxla_kernels::c64::new(1.0, -2.0))),
319            "dense<\"0x0000803F000000C0\"> : tensor<complex<f32>>"
320        );
321        assert_eq!(
322            dense_attr(&HostArray::scalar(true)),
323            "dense<true> : tensor<i1>"
324        );
325        assert_eq!(
326            dense_attr(&HostArray::zeros([0, 2], DType::F32)),
327            "dense<> : tensor<0x2xf32>"
328        );
329    }
330}