Skip to main content

ruxla_stablehlo/
lib.rs

1//! Lowering of the ruxla IR to StableHLO.
2//!
3//! [`lower`] turns a [`Function`] into a StableHLO module in the MLIR text
4//! format, with the function as the public `@main`. Each primitive emits its
5//! own operations through [`LowerCx`]; this crate provides the context,
6//! assigns SSA names, emits constants, and places nested functions (such as
7//! the bodies of `jit`) in the same module.
8//!
9//! The text is consumed in two places: the PJRT runtime compiles it with
10//! XLA, and the Python package embeds it in the modules JAX compiles. The
11//! [`link`] module merges modules exported from JAX into ruxla's modules.
12//!
13//! # Examples
14//!
15//! ```
16//! use ruxla_ir::{AVal, Atom, DType, Eqn, Function, Params, Var};
17//!
18//! let x = Var::new(AVal::new([2], DType::F32));
19//! let y = Var::new(AVal::new([2], DType::F32));
20//! let eqn = Eqn {
21//!     prim: ruxla_prims::MUL,
22//!     inputs: vec![Atom::Var(x.clone()), Atom::Var(x.clone())],
23//!     params: Params::None,
24//!     outputs: vec![y.clone()],
25//!     loc: None,
26//! };
27//! let f = Function { invars: vec![x], eqns: vec![eqn], outvars: vec![y.into()], ..Function::default() };
28//! let module = ruxla_stablehlo::lower(&f, ruxla_ir::lowering::Target::Pjrt).unwrap();
29//! assert!(module.contains("func.func public @main(%arg0: tensor<2xf32>) -> (tensor<2xf32>)"));
30//! assert!(module.contains("\"stablehlo.multiply\"(%arg0, %arg0)"));
31//! ```
32
33pub mod link;
34
35use std::collections::{HashMap, HashSet};
36use std::fmt::Write as _;
37
38use ruxla_ir::lowering::{HloValue, LowerCx, Platform, Region, Target, dense_attr, tensor_type};
39use ruxla_ir::{AVal, Atom, Function, HostArray, Result};
40
41/// Lowers a function to a StableHLO module whose public `@main` is the
42/// function, for the given target.
43///
44/// # Errors
45///
46/// Returns an error if a primitive cannot be lowered.
47pub fn lower(f: &Function, target: Target) -> Result<String> {
48    lower_with(
49        f,
50        &LowerOptions {
51            target,
52            ..LowerOptions::default()
53        },
54    )
55}
56
57/// How [`lower_with`] lowers a function.
58#[derive(Clone, Debug, Default)]
59pub struct LowerOptions {
60    /// Where the StableHLO will be compiled.
61    pub target: Target,
62    /// The kind of device it is compiled for.
63    pub platform: Platform,
64    /// The inputs given to the program for reuse as outputs, as JAX's
65    /// `donate_argnums` does: an input is aliased with the first unused
66    /// output of the same type (`tf.aliasing_output`), or else marked as a
67    /// buffer donor (`jax.buffer_donor`). Empty donates nothing.
68    pub donated: Vec<bool>,
69}
70
71/// [`lower`] with options (the platform and donated inputs).
72///
73/// # Errors
74///
75/// Returns an error if a primitive cannot be lowered.
76pub fn lower_with(f: &Function, options: &LowerOptions) -> Result<String> {
77    let (target, donated) = (options.target, &options.donated[..]);
78    let mut main_arg_attrs = vec![String::new(); f.invars.len()];
79    let outs = f.out_avals();
80    let mut used = vec![false; outs.len()];
81    for (i, v) in f.invars.iter().enumerate() {
82        if !donated.get(i).copied().unwrap_or(false) {
83            continue;
84        }
85        let aval = v.aval();
86        main_arg_attrs[i] = match (0..outs.len()).find(|&j| !used[j] && outs[j] == *aval) {
87            Some(j) => {
88                used[j] = true;
89                format!(" {{tf.aliasing_output = {j} : i32}}")
90            }
91            None => String::from(" {jax.buffer_donor = true}"),
92        };
93    }
94    let mut module = ModuleState {
95        target,
96        functions: Vec::new(),
97        symbols: HashSet::new(),
98        lowered: HashMap::new(),
99        imports: Vec::new(),
100        main_arg_attrs,
101        platform: options.platform,
102    };
103    module.symbols.insert(String::from("main"));
104    module.lower_function(f, "main", true)?;
105    if !module.imports.is_empty() {
106        let imports: Vec<link::Imported> = module.imports.into_iter().map(|(_, i, _)| i).collect();
107        return Ok(link::link(&module.functions.concat(), &imports));
108    }
109    let mut out = String::from("module @ruxla {\n");
110    for func in &module.functions {
111        out.push_str(func);
112    }
113    out.push_str("}\n");
114    Ok(out)
115}
116
117/// The functions of the module being built.
118struct ModuleState {
119    target: Target,
120    /// Function definitions, in the order they were finished.
121    functions: Vec<String>,
122    /// Symbol names in use.
123    symbols: HashSet<String>,
124    /// Functions already lowered, by address, so that a function called from
125    /// several places is emitted once.
126    lowered: HashMap<usize, String>,
127    /// Imported modules: the text, the renamed functions, and the symbol of
128    /// their `main`.
129    imports: Vec<(String, link::Imported, String)>,
130    /// The attributes of the parameters of `main` (donation).
131    main_arg_attrs: Vec<String>,
132    /// The kind of device the module is compiled for.
133    platform: Platform,
134}
135
136impl ModuleState {
137    /// Returns a fresh symbol name based on `hint`.
138    fn fresh_symbol(&mut self, hint: &str) -> String {
139        let base: String = hint
140            .chars()
141            .map(|c| {
142                if c.is_ascii_alphanumeric() || c == '_' {
143                    c
144                } else {
145                    '_'
146                }
147            })
148            .collect::<String>()
149            .trim_matches('_')
150            .to_string();
151        let base = if base.is_empty() {
152            String::from("fn")
153        } else {
154            base
155        };
156        let mut name = base.clone();
157        let mut i = 1;
158        while !self.symbols.insert(name.clone()) {
159            name = format!("{base}_{i}");
160            i += 1;
161        }
162        name
163    }
164
165    fn lower_function(&mut self, f: &Function, symbol: &str, public: bool) -> Result<()> {
166        let mut emitter = FnEmitter {
167            module: self,
168            body: String::new(),
169            indent: 2,
170            next_value: 0,
171        };
172        let mut env: HashMap<u64, HloValue> = HashMap::new();
173
174        let params: Vec<String> = f
175            .invars
176            .iter()
177            .enumerate()
178            .map(|(i, v)| {
179                let value = HloValue {
180                    name: format!("%arg{i}"),
181                    aval: v.aval().clone(),
182                };
183                let attrs = if public && symbol == "main" {
184                    emitter
185                        .module
186                        .main_arg_attrs
187                        .get(i)
188                        .cloned()
189                        .unwrap_or_default()
190                } else {
191                    String::new()
192                };
193                let param = format!("{}: {}{attrs}", value.name, tensor_type(&value.aval));
194                env.insert(v.id(), value);
195                param
196            })
197            .collect();
198        for (v, value) in &f.constvars {
199            let c = emitter.constant(value);
200            env.insert(v.id(), c);
201        }
202
203        for eqn in &f.eqns {
204            let inputs: Vec<HloValue> = eqn
205                .inputs
206                .iter()
207                .map(|a| emitter.atom(&env, a))
208                .collect::<Result<_>>()?;
209            let out_avals: Vec<AVal> = eqn.outputs.iter().map(|v| v.aval().clone()).collect();
210            let outputs = eqn
211                .prim
212                .lower(&mut emitter, &inputs, &eqn.params, &out_avals)?;
213            for (v, value) in eqn.outputs.iter().zip(outputs) {
214                env.insert(v.id(), value);
215            }
216        }
217
218        let results: Vec<HloValue> = f
219            .outvars
220            .iter()
221            .map(|a| emitter.atom(&env, a))
222            .collect::<Result<_>>()?;
223        let names: Vec<&str> = results.iter().map(|r| r.name.as_str()).collect();
224        let types: Vec<String> = results.iter().map(|r| tensor_type(&r.aval)).collect();
225        let _ = writeln!(
226            emitter.body,
227            "    \"func.return\"({}) : ({}) -> ()",
228            names.join(", "),
229            types.join(", ")
230        );
231        let body = emitter.body;
232
233        let visibility = if public { "public" } else { "private" };
234        let mut text = format!(
235            "  func.func {visibility} @{symbol}({}) -> ({}) {{\n",
236            params.join(", "),
237            types.join(", ")
238        );
239        text.push_str(&body);
240        text.push_str("  }\n");
241        self.functions.push(text);
242        Ok(())
243    }
244}
245
246/// Emits the operations of one function.
247struct FnEmitter<'m> {
248    module: &'m mut ModuleState,
249    body: String,
250    /// The indentation of the current block, in units of two spaces.
251    indent: usize,
252    next_value: usize,
253}
254
255impl FnEmitter<'_> {
256    fn fresh(&mut self) -> String {
257        let name = format!("%{}", self.next_value);
258        self.next_value += 1;
259        name
260    }
261
262    fn line(&mut self, text: &str) {
263        let _ = writeln!(self.body, "{:width$}{text}", "", width = self.indent * 2);
264    }
265
266    fn atom(&mut self, env: &HashMap<u64, HloValue>, atom: &Atom) -> Result<HloValue> {
267        match atom {
268            Atom::Var(v) => env
269                .get(&v.id())
270                .cloned()
271                .ok_or_else(|| ruxla_ir::Error::Malformed(format!("{v:?} is not defined"))),
272            Atom::Lit(l) => Ok(self.constant(l.value())),
273        }
274    }
275
276    /// Names the results of an operation and returns the left-hand side.
277    fn results(&mut self, results: &[AVal]) -> (String, Vec<HloValue>) {
278        match results.len() {
279            0 => (String::new(), Vec::new()),
280            1 => {
281                let name = self.fresh();
282                (
283                    format!("{name} = "),
284                    vec![HloValue {
285                        name,
286                        aval: results[0].clone(),
287                    }],
288                )
289            }
290            n => {
291                let name = self.fresh();
292                let values = results
293                    .iter()
294                    .enumerate()
295                    .map(|(i, aval)| HloValue {
296                        name: format!("{name}#{i}"),
297                        aval: aval.clone(),
298                    })
299                    .collect();
300                (format!("{name}:{n} = "), values)
301            }
302        }
303    }
304}
305
306/// Formats the operands and the function type of an operation.
307fn signature(operands: &[HloValue], results: &[AVal]) -> (String, String) {
308    let names: Vec<&str> = operands.iter().map(|o| o.name.as_str()).collect();
309    let in_types: Vec<String> = operands.iter().map(|o| tensor_type(&o.aval)).collect();
310    let out_types: Vec<String> = results.iter().map(tensor_type).collect();
311    let out = if out_types.len() == 1 {
312        out_types[0].clone()
313    } else {
314        format!("({})", out_types.join(", "))
315    };
316    (
317        names.join(", "),
318        format!("({}) -> {out}", in_types.join(", ")),
319    )
320}
321
322fn attribute_dict(attributes: &str) -> String {
323    if attributes.is_empty() {
324        String::new()
325    } else {
326        format!(" {{{attributes}}}")
327    }
328}
329
330impl LowerCx for FnEmitter<'_> {
331    fn platform(&self) -> Platform {
332        self.module.platform
333    }
334    fn target(&self) -> Target {
335        self.module.target
336    }
337
338    fn op(
339        &mut self,
340        name: &str,
341        operands: &[HloValue],
342        attributes: &str,
343        results: &[AVal],
344    ) -> Vec<HloValue> {
345        let (lhs, values) = self.results(results);
346        let (args, ty) = signature(operands, results);
347        let line = format!(
348            "{lhs}\"{name}\"({args}){} : {ty}",
349            attribute_dict(attributes)
350        );
351        self.line(&line);
352        values
353    }
354
355    fn op_with_regions(
356        &mut self,
357        name: &str,
358        operands: &[HloValue],
359        attributes: &str,
360        regions: &mut [Region<'_>],
361        results: &[AVal],
362    ) -> Result<Vec<HloValue>> {
363        // Emit each region into its own buffer, then the operation around them.
364        let saved = std::mem::take(&mut self.body);
365        let saved_indent = self.indent;
366        let mut region_texts = Vec::new();
367        for region in regions.iter_mut() {
368            self.indent = saved_indent + 1;
369            let args: Vec<HloValue> = region
370                .args
371                .iter()
372                .map(|aval| HloValue {
373                    name: self.fresh(),
374                    aval: aval.clone(),
375                })
376                .collect();
377            let header: Vec<String> = args
378                .iter()
379                .map(|a| format!("{}: {}", a.name, tensor_type(&a.aval)))
380                .collect();
381            if !header.is_empty() {
382                let _ = writeln!(
383                    self.body,
384                    "{:width$}^bb0({}):",
385                    "",
386                    header.join(", "),
387                    width = saved_indent * 2
388                );
389            }
390            let returned = (region.body)(self, &args)?;
391            let names: Vec<&str> = returned.iter().map(|r| r.name.as_str()).collect();
392            let types: Vec<String> = returned.iter().map(|r| tensor_type(&r.aval)).collect();
393            let ret = format!(
394                "\"stablehlo.return\"({}) : ({}) -> ()",
395                names.join(", "),
396                types.join(", ")
397            );
398            self.line(&ret);
399            region_texts.push(std::mem::take(&mut self.body));
400        }
401        self.body = saved;
402        self.indent = saved_indent;
403
404        let (lhs, values) = self.results(results);
405        let (args, ty) = signature(operands, results);
406        let pad = " ".repeat(saved_indent * 2);
407        let regions_text: Vec<String> = region_texts
408            .iter()
409            .map(|body| format!("{{\n{body}{pad}}}"))
410            .collect();
411        let line = format!(
412            "{lhs}\"{name}\"({args}) ({}){} : {ty}",
413            regions_text.join(", "),
414            attribute_dict(attributes)
415        );
416        self.line(&line);
417        Ok(values)
418    }
419
420    fn constant(&mut self, value: &HostArray) -> HloValue {
421        let aval = AVal::new(value.shape().clone(), value.dtype());
422        let attrs = format!("value = {}", dense_attr(value));
423        self.op(
424            "stablehlo.constant",
425            &[],
426            &attrs,
427            std::slice::from_ref(&aval),
428        )
429        .pop()
430        .expect("one result")
431    }
432
433    fn import(&mut self, module: &str, name_hint: &str) -> Result<String> {
434        if let Some((_, _, symbol)) = self.module.imports.iter().find(|(m, _, _)| m == module) {
435            return Ok(symbol.clone());
436        }
437        let prefix = self.module.fresh_symbol(name_hint);
438        let imported = link::import(module, &prefix)
439            .map_err(|e| ruxla_ir::Error::Malformed(format!("cannot import `{name_hint}`: {e}")))?;
440        let symbol = imported
441            .symbol("main")
442            .ok_or_else(|| ruxla_ir::Error::Malformed(format!("`{name_hint}` has no `main`")))?
443            .to_string();
444        self.module.symbols.insert(symbol.clone());
445        self.module
446            .imports
447            .push((module.to_string(), imported, symbol.clone()));
448        Ok(symbol)
449    }
450
451    fn function(&mut self, f: &Function, name_hint: &str) -> Result<String> {
452        let key = std::ptr::from_ref(f).addr();
453        if let Some(symbol) = self.module.lowered.get(&key) {
454            return Ok(symbol.clone());
455        }
456        let symbol = self.module.fresh_symbol(name_hint);
457        self.module.lower_function(f, &symbol, false)?;
458        self.module.lowered.insert(key, symbol.clone());
459        Ok(symbol)
460    }
461}
462
463#[cfg(test)]
464mod tests {
465    #[test]
466    fn donated_inputs_alias_outputs_of_the_same_type() {
467        use ruxla_ir::{AVal, Atom, DType, Var};
468        let x = Var::new(AVal::new([3], DType::F32));
469        let y = Var::new(AVal::scalar(DType::I32));
470        let f = Function {
471            invars: vec![x.clone(), y],
472            outvars: vec![Atom::Var(x)],
473            ..Function::default()
474        };
475        let options = LowerOptions {
476            target: Target::Pjrt,
477            donated: vec![true, true],
478            ..LowerOptions::default()
479        };
480        let text = lower_with(&f, &options).unwrap();
481        assert!(
482            text.contains("%arg0: tensor<3xf32> {tf.aliasing_output = 0 : i32}"),
483            "{text}"
484        );
485        assert!(
486            text.contains("%arg1: tensor<i32> {jax.buffer_donor = true}"),
487            "{text}"
488        );
489        let plain = lower(&f, Target::Pjrt).unwrap();
490        assert!(
491            !plain.contains("aliasing") && !plain.contains("donor"),
492            "{plain}"
493        );
494    }
495
496    use super::*;
497
498    #[test]
499    fn symbols_are_sanitized_and_unique() {
500        let mut m = ModuleState {
501            target: Target::Pjrt,
502            functions: Vec::new(),
503            symbols: HashSet::new(),
504            lowered: HashMap::new(),
505            imports: Vec::new(),
506            main_arg_attrs: Vec::new(),
507            platform: Platform::Cpu,
508        };
509        assert_eq!(m.fresh_symbol("<lambda>"), "lambda");
510        assert_eq!(m.fresh_symbol("<lambda>"), "lambda_1");
511        assert_eq!(m.fresh_symbol("!!!"), "fn");
512    }
513}