Skip to main content

ruxla_prims/
sort.rs

1//! `sort`, following JAX's `lax.sort_p`.
2
3use ruxla_ir::Atom;
4use ruxla_ir::ad::{AdCx, Tangent};
5use ruxla_ir::batching::{BatchCx, Batched};
6use ruxla_ir::lowering::{HloValue, LowerCx, Region};
7use ruxla_ir::{
8    AVal, DType, DTypeKind, Error, EvalCx, GatherDims, GatherScatterMode, HostArray, Params, Prim,
9    Primitive, Result, Shape, Value,
10};
11use ruxla_kernels::array as k;
12
13use crate::ad::bind1;
14use crate::batching::move_bdim;
15use crate::indexing::GATHER;
16use crate::structural::{BROADCAST_IN_DIM, IOTA};
17use crate::util::wrong_params;
18
19/// `sort`.
20#[derive(Debug)]
21pub(crate) struct Sort;
22
23/// Sorts operands of the same shape along a dimension, lexicographically by
24/// the first `num_keys` of them ([`Params::Sort`]). Floats are ordered as
25/// `-inf < ... < 0 < ... < inf < NaN`, with `-0.0` equal to `0.0` and all
26/// NaNs equal, as in JAX.
27pub static SORT: Prim = Prim::new(&Sort);
28
29fn sort_params(params: &Params) -> Result<(usize, bool, usize)> {
30    match *params {
31        Params::Sort {
32            dimension,
33            is_stable,
34            num_keys,
35        } => Ok((dimension, is_stable, num_keys)),
36        _ => Err(wrong_params("sort")),
37    }
38}
39
40/// `stablehlo.compare` with an explicit comparison type.
41fn compare(
42    cx: &mut dyn LowerCx,
43    direction: &str,
44    compare_type: &str,
45    a: &HloValue,
46    b: &HloValue,
47) -> HloValue {
48    let attrs = format!(
49        "comparison_direction = #stablehlo<comparison_direction {direction}>, \
50         compare_type = #stablehlo<comparison_type {compare_type}>"
51    );
52    cx.op1(
53        "stablehlo.compare",
54        &[a.clone(), b.clone()],
55        &attrs,
56        &AVal::scalar(DType::Bool),
57    )
58}
59
60/// JAX's `_canonicalize_float_for_sort`: `-0.0` becomes `0.0`, and every
61/// NaN becomes the same NaN.
62fn canonicalize_float(cx: &mut dyn LowerCx, x: &HloValue) -> HloValue {
63    let aval = x.aval.clone();
64    let zero = cx.constant(&HostArray::zeros(Shape::scalar(), aval.dtype));
65    let is_zero = compare(cx, "EQ", "FLOAT", x, &zero);
66    let zero = cx.constant(&HostArray::zeros(Shape::scalar(), aval.dtype));
67    let result = cx.op1("stablehlo.select", &[is_zero, zero, x.clone()], "", &aval);
68    let is_nan = compare(cx, "NE", "FLOAT", x, x);
69    let nan = cx.constant(&HostArray::full(
70        Shape::scalar(),
71        aval.dtype,
72        Value::Float(f64::NAN),
73    ));
74    cx.op1("stablehlo.select", &[is_nan, nan, result], "", &aval)
75}
76
77/// The comparison type of keys after canonicalization, as JAX's lowering of
78/// `lt` and `eq` picks it.
79fn key_compare_type(dtype: DType) -> &'static str {
80    match dtype.kind() {
81        DTypeKind::Float | DTypeKind::Complex => "TOTALORDER",
82        DTypeKind::SignedInt => "SIGNED",
83        DTypeKind::UnsignedInt | DTypeKind::Bool => "UNSIGNED",
84    }
85}
86
87impl Primitive for Sort {
88    fn name(&self) -> &'static str {
89        "sort"
90    }
91
92    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
93        let (dimension, _, num_keys) = sort_params(params)?;
94        let Some(first) = inputs.first() else {
95            return Err(Error::type_error(
96                self.name(),
97                "expected at least one operand",
98            ));
99        };
100        if let Some(x) = inputs.iter().find(|x| x.shape != first.shape) {
101            return Err(Error::type_error(
102                self.name(),
103                format!(
104                    "operands must have equal shapes, got [{}] and [{}]",
105                    first.shape, x.shape
106                ),
107            ));
108        }
109        if dimension >= first.shape.rank() {
110            return Err(Error::type_error(
111                self.name(),
112                format!(
113                    "dimension {dimension} is out of bounds for rank {}",
114                    first.shape.rank()
115                ),
116            ));
117        }
118        if num_keys == 0 || num_keys > inputs.len() {
119            return Err(Error::type_error(
120                self.name(),
121                format!(
122                    "num_keys must be between 1 and the number of operands ({}), got {num_keys}",
123                    inputs.len()
124                ),
125            ));
126        }
127        Ok(inputs.to_vec())
128    }
129
130    fn eval(
131        &self,
132        _: &dyn EvalCx,
133        inputs: &[HostArray],
134        params: &Params,
135    ) -> Result<Vec<HostArray>> {
136        let (dimension, _, num_keys) = sort_params(params)?;
137        let shape = inputs[0].shape().clone();
138        let buffers: Vec<_> = inputs.iter().map(HostArray::buffer).collect();
139        Ok(k::sort(&buffers, &shape, dimension, num_keys)
140            .into_iter()
141            .map(|b| HostArray::from_buffer(b, shape.clone()))
142            .collect())
143    }
144
145    /// JAX's `_sort_batch_rule`: every operand gets the batch dimension of
146    /// the first batched operand.
147    fn batch(
148        &'static self,
149        cx: &mut dyn BatchCx,
150        inputs: &[Batched],
151        params: &Params,
152    ) -> Result<Vec<Batched>> {
153        let (dimension, is_stable, num_keys) = sort_params(params)?;
154        let bdim = inputs.iter().find_map(|x| x.bdim).ok_or_else(|| {
155            Error::Malformed(String::from(
156                "the batching rule of sort was called without batched operands",
157            ))
158        })?;
159        let atoms = inputs
160            .iter()
161            .map(|x| move_bdim(cx, x, bdim))
162            .collect::<Result<Vec<_>>>()?;
163        let outs = cx.bind(
164            SORT,
165            &atoms,
166            Params::Sort {
167                dimension: dimension + usize::from(bdim <= dimension),
168                is_stable,
169                num_keys,
170            },
171        )?;
172        Ok(outs.into_iter().map(|a| Batched::mapped(a, bdim)).collect())
173    }
174
175    fn lower(
176        &self,
177        cx: &mut dyn LowerCx,
178        inputs: &[HloValue],
179        params: &Params,
180        outputs: &[AVal],
181    ) -> Result<Vec<HloValue>> {
182        let (dimension, is_stable, num_keys) = sort_params(params)?;
183        let dtypes: Vec<DType> = inputs.iter().map(|x| x.aval.dtype).collect();
184        // JAX's `_sort_lt_comparator`: keys are canonicalized, then compared
185        // from the last key to the first.
186        let mut body = |cx: &mut dyn LowerCx, args: &[HloValue]| {
187            let mut keys = Vec::with_capacity(num_keys);
188            for i in 0..num_keys {
189                let (mut x, mut y) = (args[2 * i].clone(), args[2 * i + 1].clone());
190                if dtypes[i].is_complex() {
191                    // The real and imaginary parts are two float keys.
192                    let part = AVal::scalar(dtypes[i].real_dtype());
193                    for op in ["stablehlo.real", "stablehlo.imag"] {
194                        let xp = cx.op1(op, std::slice::from_ref(&x), "", &part);
195                        let yp = cx.op1(op, std::slice::from_ref(&y), "", &part);
196                        let xp = canonicalize_float(cx, &xp);
197                        let yp = canonicalize_float(cx, &yp);
198                        keys.push((xp, yp, "TOTALORDER"));
199                    }
200                    continue;
201                }
202                if dtypes[i].is_float() {
203                    x = canonicalize_float(cx, &x);
204                    y = canonicalize_float(cx, &y);
205                }
206                keys.push((x, y, key_compare_type(dtypes[i])));
207            }
208            let mut p: Option<HloValue> = None;
209            let bool_aval = AVal::scalar(DType::Bool);
210            for (x, y, ty) in keys.iter().rev() {
211                let lt = compare(cx, "LT", ty, x, y);
212                p = Some(match p {
213                    None => lt,
214                    Some(p) => {
215                        let eq = compare(cx, "EQ", ty, x, y);
216                        let and = cx.op1("stablehlo.and", &[eq, p], "", &bool_aval);
217                        cx.op1("stablehlo.or", &[lt, and], "", &bool_aval)
218                    }
219                });
220            }
221            Ok(vec![p.expect("at least one key")])
222        };
223        let mut regions = [Region {
224            args: dtypes
225                .iter()
226                .flat_map(|&d| [AVal::scalar(d), AVal::scalar(d)])
227                .collect(),
228            body: &mut body,
229        }];
230        let attrs = format!("dimension = {dimension} : i64, is_stable = {is_stable}");
231        cx.op_with_regions("stablehlo.sort", inputs, &attrs, &mut regions, outputs)
232    }
233
234    /// JAX's `_sort_jvp`: sorts an iota along with the operands to get the
235    /// permutation, and gathers the tangents with it.
236    fn jvp(
237        &'static self,
238        cx: &mut dyn AdCx,
239        primals: &[Atom],
240        tangents: &[Tangent],
241        params: &Params,
242    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
243        let (dimension, is_stable, num_keys) = sort_params(params)?;
244        let shape = primals[0].aval().shape;
245        let rank = shape.rank();
246        if shape.size() == 0 {
247            // Nothing to permute (and the gather below would take slices
248            // larger than the operand).
249            let sorted = cx.bind(SORT, primals, params.clone())?;
250            return Ok((sorted, tangents.to_vec()));
251        }
252        let index_dtype = if shape.iter().any(|&d| d as u64 > u64::from(u32::MAX)) {
253            DType::U64
254        } else {
255            DType::U32
256        };
257        let iota = bind1(
258            cx,
259            IOTA,
260            &[],
261            Params::Iota {
262                dtype: index_dtype,
263                shape: shape.clone(),
264                dimension,
265            },
266        )?;
267        let mut operands = primals.to_vec();
268        operands.push(iota);
269        let mut sorted = cx.bind(
270            SORT,
271            &operands,
272            Params::Sort {
273                dimension,
274                is_stable,
275                num_keys,
276            },
277        )?;
278        let perm = sorted.pop().expect("the permutation");
279        let mut idx_shape = shape.dims().to_vec();
280        idx_shape.push(1);
281        let idx = bind1(
282            cx,
283            BROADCAST_IN_DIM,
284            &[perm],
285            Params::BroadcastInDim {
286                shape: idx_shape.into(),
287                broadcast_dimensions: (0..rank).collect(),
288            },
289        )?;
290        let batch_dims: Vec<usize> = (0..rank).filter(|&d| d != dimension).collect();
291        let gather = Params::Gather {
292            dimension_numbers: GatherDims {
293                offset_dims: Vec::new(),
294                collapsed_slice_dims: vec![dimension],
295                start_index_map: vec![dimension],
296                operand_batching_dims: batch_dims.clone(),
297                start_indices_batching_dims: batch_dims,
298            },
299            slice_sizes: vec![1; rank],
300            mode: GatherScatterMode::PromiseInBounds,
301            indices_are_sorted: false,
302            unique_indices: false,
303        };
304        let tangents_out = tangents
305            .iter()
306            .map(|t| match t {
307                None => Ok(None),
308                Some(t) => bind1(cx, GATHER, &[t.clone(), idx.clone()], gather.clone()).map(Some),
309            })
310            .collect::<Result<Vec<_>>>()?;
311        Ok((sorted, tangents_out))
312    }
313}