Skip to main content

ruxla_prims/
top_k.rs

1//! `top_k`, following JAX's `lax.top_k_p`.
2
3use ruxla_ir::Atom;
4use ruxla_ir::ad::{AdCx, Tangent};
5use ruxla_ir::batching::{BatchCx, Batched};
6use ruxla_ir::lowering::{HloValue, LowerCx, i64_array};
7use ruxla_ir::{
8    AVal, DType, Error, EvalCx, GatherDims, GatherScatterMode, HostArray, Params, Prim, Primitive,
9    Result, Shape,
10};
11use ruxla_kernels::array as k;
12use ruxla_kernels::{Buffer, with_buffer};
13
14use crate::ad::bind1;
15use crate::batching::{self, batched_operand};
16use crate::indexing::GATHER;
17use crate::structural::RESHAPE;
18use crate::util::{arity, wrong_params};
19
20/// `top_k`.
21#[derive(Debug)]
22pub(crate) struct TopK;
23
24/// The `k` largest elements along an axis in descending order, and their
25/// indices as `i32` ([`Params::TopK`]). Floats are ordered by XLA's total
26/// order `-NaN < -inf < ... < -0.0 < 0.0 < ... < inf < NaN`; equal elements
27/// keep their order.
28pub static TOP_K: Prim = Prim::new(&TopK);
29
30fn top_k_params(params: &Params) -> Result<(usize, usize, bool)> {
31    match *params {
32        Params::TopK { k, axis, is_stable } => Ok((k, axis, is_stable)),
33        _ => Err(wrong_params("top_k")),
34    }
35}
36
37/// The permutation that swaps `axis` with the last dimension.
38fn swap_last(rank: usize, axis: usize) -> Vec<usize> {
39    let mut perm: Vec<usize> = (0..rank).collect();
40    perm.swap(axis, rank - 1);
41    perm
42}
43
44impl Primitive for TopK {
45    fn name(&self) -> &'static str {
46        "top_k"
47    }
48
49    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
50        arity(self.name(), inputs, 1)?;
51        let (k, axis, _) = top_k_params(params)?;
52        let x = &inputs[0];
53        if x.dtype.is_complex() {
54            return Err(Error::type_error(
55                self.name(),
56                format!("does not accept {} operands", x.dtype),
57            ));
58        }
59        if x.shape.rank() == 0 {
60            return Err(Error::type_error(
61                self.name(),
62                "the operand must have at least one dimension",
63            ));
64        }
65        if axis >= x.shape.rank() {
66            return Err(Error::type_error(
67                self.name(),
68                format!("axis {axis} is out of bounds for {x}"),
69            ));
70        }
71        let n = x.shape[axis];
72        if k > n {
73            return Err(Error::type_error(
74                self.name(),
75                format!("k ({k}) must be no larger than the size along the axis ({n})"),
76            ));
77        }
78        if n as u64 > 1 << 31 {
79            return Err(Error::type_error(
80                self.name(),
81                format!("the size along the axis ({n}) overflows i32 indices"),
82            ));
83        }
84        let mut shape = x.shape.dims().to_vec();
85        shape[axis] = k;
86        let shape = Shape::from(shape);
87        Ok(vec![
88            AVal::new(shape.clone(), x.dtype),
89            AVal::new(shape, DType::I32),
90        ])
91    }
92
93    fn eval(
94        &self,
95        _: &dyn EvalCx,
96        inputs: &[HostArray],
97        params: &Params,
98    ) -> Result<Vec<HostArray>> {
99        let (k, axis, _) = top_k_params(params)?;
100        let x = &inputs[0];
101        let shape = x.shape().dims();
102        let (values, indices) = with_buffer!(x.buffer(), |v| {
103            let (values, indices) = k::top_k(v, shape, k, axis);
104            (Buffer::from_vec(values), indices)
105        });
106        let mut out_shape = shape.to_vec();
107        out_shape[axis] = k;
108        Ok(vec![
109            HostArray::from_buffer(values, out_shape.clone()),
110            HostArray::from_vec(indices, out_shape),
111        ])
112    }
113
114    /// JAX's `_top_k_batch_rule`.
115    fn batch(
116        &'static self,
117        cx: &mut dyn BatchCx,
118        inputs: &[Batched],
119        params: &Params,
120    ) -> Result<Vec<Batched>> {
121        let (k, axis, is_stable) = top_k_params(params)?;
122        let x = &inputs[0];
123        let b = batched_operand(self.name(), x)?;
124        let outs = cx.bind(
125            TOP_K,
126            std::slice::from_ref(&x.atom),
127            Params::TopK {
128                k,
129                axis: batching::batched_dim(axis, b),
130                is_stable,
131            },
132        )?;
133        Ok(outs.into_iter().map(|a| Batched::mapped(a, b)).collect())
134    }
135
136    /// JAX's `_top_k_lower`: `chlo.top_k` along the last dimension, with
137    /// transposes around it for other axes.
138    fn lower(
139        &self,
140        cx: &mut dyn LowerCx,
141        inputs: &[HloValue],
142        params: &Params,
143        outputs: &[AVal],
144    ) -> Result<Vec<HloValue>> {
145        let (k, axis, is_stable) = top_k_params(params)?;
146        let mut x = inputs[0].clone();
147        let rank = x.aval.shape.rank();
148        let perm = (axis + 1 != rank).then(|| swap_last(rank, axis));
149        let permute = |aval: &AVal, perm: &[usize]| {
150            let dims: Vec<usize> = perm.iter().map(|&d| aval.shape[d]).collect();
151            AVal::new(dims, aval.dtype)
152        };
153        if let Some(perm) = &perm {
154            let aval = permute(&x.aval, perm);
155            x = cx.op1(
156                "stablehlo.transpose",
157                &[x],
158                &format!("permutation = {}", i64_array(perm)),
159                &aval,
160            );
161        }
162        let results: Vec<AVal> = match &perm {
163            Some(perm) => outputs.iter().map(|a| permute(a, perm)).collect(),
164            None => outputs.to_vec(),
165        };
166        // `is_stable` defaults to true, which JAX's printed modules leave
167        // out.
168        let mut attrs = format!("k = {k} : i64");
169        if !is_stable {
170            attrs.push_str(", is_stable = false");
171        }
172        let outs = cx.op("chlo.top_k", &[x], &attrs, &results);
173        Ok(match &perm {
174            Some(perm) => outs
175                .into_iter()
176                .zip(outputs)
177                .map(|(r, aval)| {
178                    cx.op1(
179                        "stablehlo.transpose",
180                        &[r],
181                        &format!("permutation = {}", i64_array(perm)),
182                        aval,
183                    )
184                })
185                .collect(),
186            None => outs,
187        })
188    }
189
190    /// JAX's `_top_k_jvp`: gathers the tangent at the indices. JAX's gather
191    /// has the default mode (`FILL_OR_DROP`), which ruxla does not have; the
192    /// indices are in bounds, so promising it computes the same.
193    fn jvp(
194        &'static self,
195        cx: &mut dyn AdCx,
196        primals: &[Atom],
197        tangents: &[Tangent],
198        params: &Params,
199    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
200        let (_, axis, _) = top_k_params(params)?;
201        let outs = cx.bind(TOP_K, primals, params.clone())?;
202        let Some(t) = &tangents[0] else {
203            return Ok((outs, vec![None, None]));
204        };
205        if t.aval().shape.size() == 0 {
206            // Nothing to gather (and the gather would take slices larger
207            // than the operand).
208            let zeros = crate::ad::zeros(cx, &outs[0].aval())?;
209            return Ok((outs, vec![Some(zeros), None]));
210        }
211        let idx_shape = outs[1].aval().shape;
212        let rank = idx_shape.rank();
213        let mut gather_shape = idx_shape.dims().to_vec();
214        gather_shape.push(1);
215        let idx = bind1(
216            cx,
217            RESHAPE,
218            std::slice::from_ref(&outs[1]),
219            Params::Reshape {
220                new_sizes: gather_shape.into(),
221            },
222        )?;
223        let batch_dims: Vec<usize> = (0..rank).filter(|&d| d != axis).collect();
224        let tangent = bind1(
225            cx,
226            GATHER,
227            &[t.clone(), idx],
228            Params::Gather {
229                dimension_numbers: GatherDims {
230                    offset_dims: Vec::new(),
231                    collapsed_slice_dims: vec![axis],
232                    start_index_map: vec![axis],
233                    operand_batching_dims: batch_dims.clone(),
234                    start_indices_batching_dims: batch_dims,
235                },
236                slice_sizes: vec![1; rank],
237                mode: GatherScatterMode::PromiseInBounds,
238                indices_are_sorted: false,
239                unique_indices: false,
240            },
241        )?;
242        Ok((outs, vec![Some(tangent), None]))
243    }
244}