1use ruxla_ir::Atom;
7use ruxla_ir::ad::{AdCx, Tangent, TransposeInput};
8use ruxla_ir::batching::{BatchCx, Batched};
9use ruxla_ir::lowering::{HloValue, LowerCx, Region, i64_array};
10use ruxla_ir::{
11 AVal, DType, Error, EvalCx, HostArray, Params, Prim, Primitive, Result, SelectPrim, Shape,
12};
13use ruxla_kernels::array::ReduceOp;
14use ruxla_kernels::window::{self as w, Window};
15use ruxla_kernels::{Buffer, Element, Ops, Value, with_buffer, with_dtype};
16
17use crate::ad::{bind1, scalar};
18use crate::batching::{self, batched_operand, bdim_at_front};
19use crate::conv::{padding_attr, vjp_lhs_padding};
20use crate::elementwise::compare;
21use crate::structural::{PAD, SLICE};
22use crate::structural_ad as sad;
23use crate::util::{arity, wrong_params};
24
25#[derive(Clone, Copy)]
27struct Win<'a> {
28 dimensions: &'a [usize],
29 strides: &'a [usize],
30 padding: &'a [(i64, i64)],
31 base_dilation: &'a [usize],
32 window_dilation: &'a [usize],
33}
34
35impl Win<'_> {
36 fn kernel(&self) -> Window<'_> {
37 Window {
38 dimensions: self.dimensions,
39 strides: self.strides,
40 padding: self.padding,
41 base_dilation: self.base_dilation,
42 window_dilation: self.window_dilation,
43 }
44 }
45
46 fn insert(&self, at: usize) -> OwnedWin {
49 let ins = |v: &[usize], x: usize| {
50 let mut v = v.to_vec();
51 v.insert(at, x);
52 v
53 };
54 let mut padding = self.padding.to_vec();
55 padding.insert(at, (0, 0));
56 OwnedWin {
57 dimensions: ins(self.dimensions, 1),
58 strides: ins(self.strides, 1),
59 padding,
60 base_dilation: ins(self.base_dilation, 1),
61 window_dilation: ins(self.window_dilation, 1),
62 }
63 }
64}
65
66struct OwnedWin {
68 dimensions: Vec<usize>,
69 strides: Vec<usize>,
70 padding: Vec<(i64, i64)>,
71 base_dilation: Vec<usize>,
72 window_dilation: Vec<usize>,
73}
74
75impl OwnedWin {
76 fn reduce_window(self) -> Params {
77 Params::ReduceWindow {
78 window_dimensions: self.dimensions,
79 window_strides: self.strides,
80 padding: self.padding,
81 base_dilation: self.base_dilation,
82 window_dilation: self.window_dilation,
83 }
84 }
85
86 fn select_and_scatter_add(self, select_prim: SelectPrim) -> Params {
87 Params::SelectAndScatterAdd {
88 select_prim,
89 window_dimensions: self.dimensions,
90 window_strides: self.strides,
91 padding: self.padding,
92 }
93 }
94
95 fn select_and_gather_add(self, select_prim: SelectPrim) -> Params {
96 Params::SelectAndGatherAdd {
97 select_prim,
98 window_dimensions: self.dimensions,
99 window_strides: self.strides,
100 padding: self.padding,
101 base_dilation: self.base_dilation,
102 window_dilation: self.window_dilation,
103 }
104 }
105}
106
107const ONES: [usize; 16] = [1; 16];
109
110fn ones(n: usize) -> Vec<usize> {
111 vec![1; n]
112}
113
114fn window_of<'a>(name: &'static str, params: &'a Params) -> Result<(Win<'a>, Option<SelectPrim>)> {
118 match params {
119 Params::ReduceWindow {
120 window_dimensions,
121 window_strides,
122 padding,
123 base_dilation,
124 window_dilation,
125 } => Ok((
126 Win {
127 dimensions: window_dimensions,
128 strides: window_strides,
129 padding,
130 base_dilation,
131 window_dilation,
132 },
133 None,
134 )),
135 Params::SelectAndGatherAdd {
136 select_prim,
137 window_dimensions,
138 window_strides,
139 padding,
140 base_dilation,
141 window_dilation,
142 } => Ok((
143 Win {
144 dimensions: window_dimensions,
145 strides: window_strides,
146 padding,
147 base_dilation,
148 window_dilation,
149 },
150 Some(*select_prim),
151 )),
152 Params::SelectAndScatterAdd {
153 select_prim,
154 window_dimensions,
155 window_strides,
156 padding,
157 } => {
158 let n = window_dimensions.len();
159 if n > ONES.len() {
160 return Err(Error::unsupported(name, "more than 16 dimensions"));
161 }
162 Ok((
163 Win {
164 dimensions: window_dimensions,
165 strides: window_strides,
166 padding,
167 base_dilation: &ONES[..n],
168 window_dilation: &ONES[..n],
169 },
170 Some(*select_prim),
171 ))
172 }
173 _ => Err(wrong_params(name)),
174 }
175}
176
177fn window_shape(name: &'static str, shape: &Shape, win: &Win<'_>) -> Result<Vec<usize>> {
180 let rank = shape.rank();
181 let lens = [
182 win.dimensions.len(),
183 win.strides.len(),
184 win.padding.len(),
185 win.base_dilation.len(),
186 win.window_dilation.len(),
187 ];
188 if lens.iter().any(|&n| n != rank) {
189 return Err(Error::type_error(
190 name,
191 format!("the window needs {rank} entries for an operand of shape [{shape}]"),
192 ));
193 }
194 if win
195 .dimensions
196 .iter()
197 .chain(win.strides)
198 .chain(win.base_dilation)
199 .chain(win.window_dilation)
200 .any(|&d| d == 0)
201 {
202 return Err(Error::type_error(
203 name,
204 "window dimensions, strides, and dilations must be positive",
205 ));
206 }
207 if win.padding.iter().any(|&(lo, hi)| lo < 0 || hi < 0) {
208 return Err(Error::type_error(
209 name,
210 format!("padding must not be negative, got {:?}", win.padding),
211 ));
212 }
213 Ok(w::reduce_window_shape(shape, &win.kernel()))
214}
215
216fn reduce_window_attrs(win: &Win<'_>) -> String {
218 format!(
219 "base_dilations = {}, padding = {}, window_dilations = {}, window_dimensions = {}, \
220 window_strides = {}",
221 i64_array(win.base_dilation),
222 padding_attr(win.padding),
223 i64_array(win.window_dilation),
224 i64_array(win.dimensions),
225 i64_array(win.strides),
226 )
227}
228
229fn identity(op: ReduceOp, dtype: DType) -> HostArray {
232 with_dtype!(dtype, |T| HostArray::from_vec(
233 vec![match op {
234 ReduceOp::Sum => T::from_value(Value::Int(0)),
235 ReduceOp::Max => <T as Ops>::lowest(),
236 ReduceOp::Min => <T as Ops>::highest(),
237 }],
238 Shape::scalar()
239 ))
240}
241
242fn chooser(select_prim: SelectPrim) -> ReduceOp {
244 match select_prim {
245 SelectPrim::Ge => ReduceOp::Max,
246 SelectPrim::Le => ReduceOp::Min,
247 }
248}
249
250fn direction(select_prim: SelectPrim) -> &'static str {
251 match select_prim {
252 SelectPrim::Ge => "GE",
253 SelectPrim::Le => "LE",
254 }
255}
256
257#[derive(Debug)]
259pub(crate) struct ReduceWindow {
260 name: &'static str,
261 op: ReduceOp,
262}
263
264pub static REDUCE_WINDOW_SUM: Prim = Prim::new(&ReduceWindow {
266 name: "reduce_window_sum",
267 op: ReduceOp::Sum,
268});
269pub static REDUCE_WINDOW_MAX: Prim = Prim::new(&ReduceWindow {
271 name: "reduce_window_max",
272 op: ReduceOp::Max,
273});
274pub static REDUCE_WINDOW_MIN: Prim = Prim::new(&ReduceWindow {
276 name: "reduce_window_min",
277 op: ReduceOp::Min,
278});
279
280impl Primitive for ReduceWindow {
281 fn name(&self) -> &'static str {
282 self.name
283 }
284
285 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
286 arity(self.name, inputs, 1)?;
287 let Params::ReduceWindow { .. } = params else {
288 return Err(wrong_params(self.name));
289 };
290 let (win, _) = window_of(self.name, params)?;
291 let x = &inputs[0];
292 let unordered = x.dtype.is_complex() && self.op != ReduceOp::Sum;
295 if x.dtype == DType::Bool || unordered || !self.op.binary().supports(x.dtype) {
296 return Err(Error::type_error(
297 self.name,
298 format!("does not accept {} operands", x.dtype),
299 ));
300 }
301 Ok(vec![AVal::new(
302 window_shape(self.name, &x.shape, &win)?,
303 x.dtype,
304 )])
305 }
306
307 fn eval(
308 &self,
309 _: &dyn EvalCx,
310 inputs: &[HostArray],
311 params: &Params,
312 ) -> Result<Vec<HostArray>> {
313 let (win, _) = window_of(self.name, params)?;
314 let x = &inputs[0];
315 let shape = window_shape(self.name, x.shape(), &win)?;
316 let b = with_buffer!(x.buffer(), |v| Buffer::from_vec(w::reduce_window(
317 v,
318 x.shape(),
319 &win.kernel(),
320 self.op
321 )));
322 Ok(vec![HostArray::from_buffer(b, shape)])
323 }
324
325 fn batch(
328 &'static self,
329 cx: &mut dyn BatchCx,
330 inputs: &[Batched],
331 params: &Params,
332 ) -> Result<Vec<Batched>> {
333 let (win, _) = window_of(self.name, params)?;
334 let x = &inputs[0];
335 let b = batched_operand(self.name, x)?;
336 let out = batching::bind1(
337 cx,
338 Prim::new(self),
339 std::slice::from_ref(&x.atom),
340 win.insert(b).reduce_window(),
341 )?;
342 Ok(vec![Batched::mapped(out, b)])
343 }
344
345 fn lower(
346 &self,
347 cx: &mut dyn LowerCx,
348 inputs: &[HloValue],
349 params: &Params,
350 outputs: &[AVal],
351 ) -> Result<Vec<HloValue>> {
352 let (win, _) = window_of(self.name, params)?;
353 let dtype = inputs[0].aval.dtype;
354 let init = cx.constant(&identity(self.op, dtype));
355 let scalar = AVal::scalar(dtype);
356 let op = self.op;
357 let mut body = |cx: &mut dyn LowerCx, args: &[HloValue]| {
358 let (a, b) = (&args[0], &args[1]);
359 Ok(vec![match op {
360 ReduceOp::Sum => cx.op1("stablehlo.add", args, "", &scalar),
361 ReduceOp::Max => cx.min_max("stablehlo.maximum", a, b, &scalar),
362 ReduceOp::Min => cx.min_max("stablehlo.minimum", a, b, &scalar),
363 }])
364 };
365 let mut regions = [Region {
366 args: vec![AVal::scalar(dtype), AVal::scalar(dtype)],
367 body: &mut body,
368 }];
369 cx.op_with_regions(
370 "stablehlo.reduce_window",
371 &[inputs[0].clone(), init],
372 &reduce_window_attrs(&win),
373 &mut regions,
374 outputs,
375 )
376 }
377
378 fn jvp(
382 &'static self,
383 cx: &mut dyn AdCx,
384 primals: &[Atom],
385 tangents: &[Tangent],
386 params: &Params,
387 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
388 let (win, _) = window_of(self.name, params)?;
389 let select_prim = match self.op {
390 ReduceOp::Sum => {
391 return sad::linear_jvp(cx, Prim::new(self), primals, tangents, params);
392 }
393 ReduceOp::Max => SelectPrim::Ge,
394 ReduceOp::Min => SelectPrim::Le,
395 };
396 let ans = bind1(cx, Prim::new(self), primals, params.clone())?;
397 let t = tangents[0]
398 .as_ref()
399 .map(|t| {
400 bind1(
401 cx,
402 SELECT_AND_GATHER_ADD,
403 &[t.clone(), primals[0].clone()],
404 win.insert_none().select_and_gather_add(select_prim),
405 )
406 })
407 .transpose()?;
408 Ok((vec![ans], vec![t]))
409 }
410
411 fn transpose(
415 &'static self,
416 cx: &mut dyn AdCx,
417 cotangents: &[Tangent],
418 inputs: &[TransposeInput],
419 params: &Params,
420 ) -> Result<Vec<Tangent>> {
421 if self.op != ReduceOp::Sum {
422 return Err(Error::unsupported(
423 self.name,
424 "only reduce_window_sum is linear",
425 ));
426 }
427 let (win, _) = window_of(self.name, params)?;
428 let Some(ct) = &cotangents[0] else {
429 return Ok(vec![None]);
430 };
431 let operand = inputs[0].aval();
432 let rank = operand.shape.rank();
433 let pads = vjp_lhs_padding(
434 &operand.shape,
435 win.dimensions,
436 win.strides,
437 &ct.aval().shape,
438 win.padding,
439 win.base_dilation,
440 win.window_dilation,
441 );
442 let padding_config = pads
443 .iter()
444 .zip(win.strides)
445 .map(|(&(lo, hi), &s)| (lo, hi, s - 1))
446 .collect();
447 let padded = bind1(
448 cx,
449 PAD,
450 &[ct.clone(), scalar(ct.aval().dtype, Value::Int(0))],
451 Params::Pad { padding_config },
452 )?;
453 let result = bind1(
454 cx,
455 REDUCE_WINDOW_SUM,
456 &[padded],
457 Params::ReduceWindow {
458 window_dimensions: win.dimensions.to_vec(),
459 window_strides: win.base_dilation.to_vec(),
460 padding: vec![(0, 0); rank],
461 base_dilation: ones(rank),
462 window_dilation: win.window_dilation.to_vec(),
463 },
464 )?;
465 Ok(vec![Some(result)])
466 }
467}
468
469impl Win<'_> {
470 fn insert_none(&self) -> OwnedWin {
472 OwnedWin {
473 dimensions: self.dimensions.to_vec(),
474 strides: self.strides.to_vec(),
475 padding: self.padding.to_vec(),
476 base_dilation: self.base_dilation.to_vec(),
477 window_dilation: self.window_dilation.to_vec(),
478 }
479 }
480}
481
482fn check_pair(name: &'static str, a: &AVal, b: &AVal, floats_only: bool) -> Result<()> {
485 if a.dtype != b.dtype
486 || a.dtype == DType::Bool
487 || a.dtype.is_complex()
488 || (floats_only && !a.dtype.is_float())
489 {
490 return Err(Error::type_error(
491 name,
492 format!("does not accept operands {a} and {b}"),
493 ));
494 }
495 Ok(())
496}
497
498#[derive(Debug)]
500pub(crate) struct SelectAndScatterAdd;
501
502pub static SELECT_AND_SCATTER_ADD: Prim = Prim::new(&SelectAndScatterAdd);
506
507impl Primitive for SelectAndScatterAdd {
508 fn name(&self) -> &'static str {
509 "select_and_scatter_add"
510 }
511
512 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
513 let name = self.name();
514 arity(name, inputs, 2)?;
515 let Params::SelectAndScatterAdd { .. } = params else {
516 return Err(wrong_params(name));
517 };
518 let (win, _) = window_of(name, params)?;
519 let (source, operand) = (&inputs[0], &inputs[1]);
520 check_pair(name, source, operand, false)?;
521 let windows = window_shape(name, &operand.shape, &win)?;
522 if source.shape.dims() != windows.as_slice() {
523 return Err(Error::type_error(
524 name,
525 format!("the source must have the shape of the windows {windows:?}, got {source}"),
526 ));
527 }
528 Ok(vec![operand.clone()])
529 }
530
531 fn eval(
532 &self,
533 _: &dyn EvalCx,
534 inputs: &[HostArray],
535 params: &Params,
536 ) -> Result<Vec<HostArray>> {
537 let (win, select_prim) = window_of(self.name(), params)?;
538 let ge = select_prim == Some(SelectPrim::Ge);
539 let (source, operand) = (&inputs[0], &inputs[1]);
540 let b = with_buffer!(source.buffer(), |s| Buffer::from_vec(
541 w::select_and_scatter_add(
542 s,
543 operand.as_slice().expect("same types"),
544 operand.shape(),
545 win.dimensions,
546 win.strides,
547 win.padding,
548 ge,
549 )
550 ));
551 Ok(vec![HostArray::from_buffer(b, operand.shape().clone())])
552 }
553
554 fn batch(
556 &'static self,
557 cx: &mut dyn BatchCx,
558 inputs: &[Batched],
559 params: &Params,
560 ) -> Result<Vec<Batched>> {
561 let (win, select_prim) = window_of(self.name(), params)?;
562 let source = bdim_at_front(cx, &inputs[0])?;
563 let operand = bdim_at_front(cx, &inputs[1])?;
564 let out = batching::bind1(
565 cx,
566 SELECT_AND_SCATTER_ADD,
567 &[source, operand],
568 win.insert(0)
569 .select_and_scatter_add(select_prim.expect("select_prim")),
570 )?;
571 Ok(vec![Batched::mapped(out, 0)])
572 }
573
574 fn lower(
577 &self,
578 cx: &mut dyn LowerCx,
579 inputs: &[HloValue],
580 params: &Params,
581 outputs: &[AVal],
582 ) -> Result<Vec<HloValue>> {
583 let (win, select_prim) = window_of(self.name(), params)?;
584 let select_prim = select_prim.expect("select_prim");
585 let (source, mut operand) = (inputs[0].clone(), inputs[1].clone());
586 let aval = operand.aval.clone();
587 let dtype = aval.dtype;
588 let rank = aval.shape.rank();
589 let padded = win.padding.iter().any(|&p| p != (0, 0));
590 if padded {
591 let pad_value = cx.constant(&identity(chooser(select_prim), dtype));
592 let shape: Vec<usize> = (0..rank)
593 .map(|i| (aval.shape[i] as i64 + win.padding[i].0 + win.padding[i].1) as usize)
594 .collect();
595 let lows: Vec<i64> = win.padding.iter().map(|p| p.0).collect();
596 let highs: Vec<i64> = win.padding.iter().map(|p| p.1).collect();
597 let list = |v: &[i64]| {
598 if v.is_empty() {
599 String::from("array<i64>")
600 } else {
601 let items: Vec<String> = v.iter().map(ToString::to_string).collect();
602 format!("array<i64: {}>", items.join(", "))
603 }
604 };
605 let attrs = format!(
606 "edge_padding_high = {}, edge_padding_low = {}, interior_padding = {}",
607 list(&highs),
608 list(&lows),
609 i64_array(&vec![0; rank]),
610 );
611 operand = cx.op1(
612 "stablehlo.pad",
613 &[operand, pad_value],
614 &attrs,
615 &AVal::new(shape, dtype),
616 );
617 }
618 let zero = cx.constant(&identity(ReduceOp::Sum, dtype));
619 let scalar = AVal::scalar(dtype);
620 let pred = AVal::scalar(DType::Bool);
621 let dir = direction(select_prim);
622 let mut select = |cx: &mut dyn LowerCx, args: &[HloValue]| {
623 Ok(vec![compare(cx, dir, &args[0], &args[1], &pred)])
624 };
625 let mut scatter = |cx: &mut dyn LowerCx, args: &[HloValue]| {
626 Ok(vec![cx.op1("stablehlo.add", args, "", &scalar)])
627 };
628 let mut regions = [
629 Region {
630 args: vec![scalar.clone(), scalar.clone()],
631 body: &mut select,
632 },
633 Region {
634 args: vec![scalar.clone(), scalar.clone()],
635 body: &mut scatter,
636 },
637 ];
638 let attrs = format!(
639 "padding = {}, window_dimensions = {}, window_strides = {}",
640 padding_attr(&vec![(0, 0); rank]),
641 i64_array(win.dimensions),
642 i64_array(win.strides),
643 );
644 let out_aval = operand.aval.clone();
645 let out = cx.op_with_regions(
646 "stablehlo.select_and_scatter",
647 &[operand, source, zero],
648 &attrs,
649 &mut regions,
650 std::slice::from_ref(&out_aval),
651 )?;
652 if !padded {
653 return Ok(out);
654 }
655 let starts: Vec<usize> = win.padding.iter().map(|p| p.0 as usize).collect();
656 let limits: Vec<usize> = (0..rank).map(|i| starts[i] + aval.shape[i]).collect();
657 let attrs = format!(
658 "limit_indices = {}, start_indices = {}, strides = {}",
659 i64_array(&limits),
660 i64_array(&starts),
661 i64_array(&ones(rank)),
662 );
663 Ok(vec![cx.op1("stablehlo.slice", &out, &attrs, &outputs[0])])
664 }
665
666 fn jvp(
668 &'static self,
669 cx: &mut dyn AdCx,
670 primals: &[Atom],
671 tangents: &[Tangent],
672 params: &Params,
673 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
674 let ans = bind1(cx, SELECT_AND_SCATTER_ADD, primals, params.clone())?;
675 let t = tangents[0]
676 .as_ref()
677 .map(|t| {
678 bind1(
679 cx,
680 SELECT_AND_SCATTER_ADD,
681 &[t.clone(), primals[1].clone()],
682 params.clone(),
683 )
684 })
685 .transpose()?;
686 Ok((vec![ans], vec![t]))
687 }
688
689 fn transpose(
691 &'static self,
692 cx: &mut dyn AdCx,
693 cotangents: &[Tangent],
694 inputs: &[TransposeInput],
695 params: &Params,
696 ) -> Result<Vec<Tangent>> {
697 if !inputs[0].is_linear() || inputs[1].is_linear() {
698 return Err(Error::unsupported(self.name(), "linear only in the source"));
699 }
700 let (win, select_prim) = window_of(self.name(), params)?;
701 let Some(t) = &cotangents[0] else {
702 return Ok(vec![None, None]);
703 };
704 let source_t = bind1(
705 cx,
706 SELECT_AND_GATHER_ADD,
707 &[t.clone(), inputs[1].constant().clone()],
708 win.insert_none()
709 .select_and_gather_add(select_prim.expect("select_prim")),
710 )?;
711 Ok(vec![Some(source_t), None])
712 }
713}
714
715#[derive(Debug)]
717pub(crate) struct SelectAndGatherAdd;
718
719pub static SELECT_AND_GATHER_ADD: Prim = Prim::new(&SelectAndGatherAdd);
723
724impl Primitive for SelectAndGatherAdd {
725 fn name(&self) -> &'static str {
726 "select_and_gather_add"
727 }
728
729 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
730 let name = self.name();
731 arity(name, inputs, 2)?;
732 let Params::SelectAndGatherAdd { .. } = params else {
733 return Err(wrong_params(name));
734 };
735 let (win, _) = window_of(name, params)?;
736 let (tangents, operand) = (&inputs[0], &inputs[1]);
737 check_pair(name, tangents, operand, true)?;
738 if tangents.shape != operand.shape {
739 return Err(Error::type_error(
740 name,
741 format!("tangents and operand shapes must match, got {tangents} and {operand}"),
742 ));
743 }
744 Ok(vec![AVal::new(
745 window_shape(name, &operand.shape, &win)?,
746 operand.dtype,
747 )])
748 }
749
750 fn eval(
751 &self,
752 _: &dyn EvalCx,
753 inputs: &[HostArray],
754 params: &Params,
755 ) -> Result<Vec<HostArray>> {
756 let (win, select_prim) = window_of(self.name(), params)?;
757 let ge = select_prim == Some(SelectPrim::Ge);
758 let (tangents, operand) = (&inputs[0], &inputs[1]);
759 let shape = window_shape(self.name(), operand.shape(), &win)?;
760 let b = with_buffer!(tangents.buffer(), |t| Buffer::from_vec(
761 w::select_and_gather_add(
762 t,
763 operand.as_slice().expect("same types"),
764 operand.shape(),
765 &win.kernel(),
766 ge,
767 )
768 ));
769 Ok(vec![HostArray::from_buffer(b, shape)])
770 }
771
772 fn batch(
774 &'static self,
775 cx: &mut dyn BatchCx,
776 inputs: &[Batched],
777 params: &Params,
778 ) -> Result<Vec<Batched>> {
779 let (win, select_prim) = window_of(self.name(), params)?;
780 let t = bdim_at_front(cx, &inputs[0])?;
781 let x = bdim_at_front(cx, &inputs[1])?;
782 let out = batching::bind1(
783 cx,
784 SELECT_AND_GATHER_ADD,
785 &[t, x],
786 win.insert(0)
787 .select_and_gather_add(select_prim.expect("select_prim")),
788 )?;
789 Ok(vec![Batched::mapped(out, 0)])
790 }
791
792 fn lower(
794 &self,
795 cx: &mut dyn LowerCx,
796 inputs: &[HloValue],
797 params: &Params,
798 outputs: &[AVal],
799 ) -> Result<Vec<HloValue>> {
800 let (win, select_prim) = window_of(self.name(), params)?;
801 let select_prim = select_prim.expect("select_prim");
802 let dtype = inputs[1].aval.dtype;
803 let init = cx.constant(&identity(chooser(select_prim), dtype));
804 let zero = cx.constant(&identity(ReduceOp::Sum, dtype));
805 let scalar = AVal::scalar(dtype);
806 let pred = AVal::scalar(DType::Bool);
807 let dir = direction(select_prim);
808 let mut body = |cx: &mut dyn LowerCx, args: &[HloValue]| {
809 let (kx, vx, ky, vy) = (&args[0], &args[1], &args[2], &args[3]);
810 let which = compare(cx, dir, kx, ky, &pred);
811 let k = cx.op1(
812 "stablehlo.select",
813 &[which.clone(), kx.clone(), ky.clone()],
814 "",
815 &scalar,
816 );
817 let v = cx.op1(
818 "stablehlo.select",
819 &[which, vx.clone(), vy.clone()],
820 "",
821 &scalar,
822 );
823 Ok(vec![k, v])
824 };
825 let mut regions = [Region {
826 args: vec![scalar.clone(); 4],
827 body: &mut body,
828 }];
829 let results = [outputs[0].clone(), outputs[0].clone()];
830 let mut out = cx.op_with_regions(
831 "stablehlo.reduce_window",
832 &[inputs[1].clone(), inputs[0].clone(), init, zero],
833 &reduce_window_attrs(&win),
834 &mut regions,
835 &results,
836 )?;
837 Ok(vec![out.remove(1)])
838 }
839
840 fn jvp(
842 &'static self,
843 cx: &mut dyn AdCx,
844 primals: &[Atom],
845 tangents: &[Tangent],
846 params: &Params,
847 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
848 let ans = bind1(cx, SELECT_AND_GATHER_ADD, primals, params.clone())?;
849 let t = tangents[0]
850 .as_ref()
851 .map(|t| {
852 bind1(
853 cx,
854 SELECT_AND_GATHER_ADD,
855 &[t.clone(), primals[1].clone()],
856 params.clone(),
857 )
858 })
859 .transpose()?;
860 Ok((vec![ans], vec![t]))
861 }
862
863 fn transpose(
867 &'static self,
868 cx: &mut dyn AdCx,
869 cotangents: &[Tangent],
870 inputs: &[TransposeInput],
871 params: &Params,
872 ) -> Result<Vec<Tangent>> {
873 let name = self.name();
874 if !inputs[0].is_linear() || inputs[1].is_linear() {
875 return Err(Error::unsupported(name, "linear only in the tangents"));
876 }
877 let (win, select_prim) = window_of(name, params)?;
878 let select_prim = select_prim.expect("select_prim");
879 if win.window_dilation.iter().any(|&d| d != 1) {
880 return Err(Error::unsupported(
881 name,
882 format!(
883 "VJP not implemented for select_and_gather (MaxPool) with window dilation, \
884 got window_dilation={:?}",
885 win.window_dilation
886 ),
887 ));
888 }
889 let Some(t) = &cotangents[0] else {
890 return Ok(vec![None, None]);
891 };
892 let mut operand = inputs[1].constant().clone();
893 let rank = operand.aval().shape.rank();
894 let dilated = win.base_dilation.iter().any(|&d| d != 1);
895 if dilated {
896 let dtype = operand.aval().dtype;
897 let pad_value = identity(chooser(select_prim), dtype).get(0);
898 operand = bind1(
899 cx,
900 PAD,
901 &[operand, scalar(dtype, pad_value)],
902 Params::Pad {
903 padding_config: win.base_dilation.iter().map(|&d| (0, 0, d - 1)).collect(),
904 },
905 )?;
906 }
907 let mut result = bind1(
908 cx,
909 SELECT_AND_SCATTER_ADD,
910 &[t.clone(), operand],
911 Params::SelectAndScatterAdd {
912 select_prim,
913 window_dimensions: win.dimensions.to_vec(),
914 window_strides: win.strides.to_vec(),
915 padding: win.padding.to_vec(),
916 },
917 )?;
918 if dilated {
919 let shape = result.aval().shape;
920 result = bind1(
921 cx,
922 SLICE,
923 &[result],
924 Params::Slice {
925 start_indices: vec![0; rank],
926 limit_indices: shape.dims().to_vec(),
927 strides: win.base_dilation.to_vec(),
928 },
929 )?;
930 }
931 Ok(vec![Some(result), None])
932 }
933}