1use 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#[derive(Clone, Debug, PartialEq)]
19pub struct HloValue {
20 pub name: String,
22 pub aval: AVal,
24}
25
26pub type RegionBody<'a> = dyn FnMut(&mut dyn LowerCx, &[HloValue]) -> Result<Vec<HloValue>> + 'a;
29
30pub struct Region<'a> {
32 pub args: Vec<AVal>,
34 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
51pub enum Target {
52 #[default]
58 Pjrt,
59 Jax,
62}
63
64#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
68pub enum Platform {
69 #[default]
71 Cpu,
72 Gpu,
74}
75
76pub trait LowerCx {
78 fn target(&self) -> Target;
80
81 fn platform(&self) -> Platform {
83 Platform::Cpu
84 }
85
86 fn op(
91 &mut self,
92 name: &str,
93 operands: &[HloValue],
94 attributes: &str,
95 results: &[AVal],
96 ) -> Vec<HloValue>;
97
98 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 fn constant(&mut self, value: &HostArray) -> HloValue;
114
115 fn import(&mut self, module: &str, name_hint: &str) -> Result<String>;
123
124 fn function(&mut self, f: &Function, name_hint: &str) -> Result<String>;
131}
132
133impl dyn LowerCx + '_ {
134 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 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 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
186pub 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
207pub 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
219pub 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
229pub 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 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
269fn 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}