1use ruxla_ir::Atom;
4use ruxla_ir::ad::{AdCx, Tangent, TransposeInput};
5use ruxla_ir::batching::{BatchCx, Batched};
6use ruxla_ir::lowering::{HloValue, LowerCx, i64_array};
7use ruxla_ir::{
8 AVal, DType, Error, EvalCx, HostArray, Params, Prim, Primitive, Result, Shape, Value,
9};
10use ruxla_kernels::array as k;
11use ruxla_kernels::{Buffer, with_buffer, with_dtype};
12
13use crate::batching::{self, batched_operand};
14use crate::structural_ad as sad;
15use crate::util::{arity, check_axes, indices, integer, wrong_params};
16
17macro_rules! prim {
18 ($ty:ident, $name:literal, $static:ident, $doc:literal) => {
19 #[derive(Debug)]
20 pub(crate) struct $ty;
21 #[doc = $doc]
22 pub static $static: Prim = Prim::new(&$ty);
23 };
24}
25
26prim!(
27 BroadcastInDim,
28 "broadcast_in_dim",
29 BROADCAST_IN_DIM,
30 "Broadcasts to a larger shape ([`Params::BroadcastInDim`])."
31);
32prim!(
33 Reshape,
34 "reshape",
35 RESHAPE,
36 "Changes the shape, keeping the elements in row-major order."
37);
38prim!(
39 Transpose,
40 "transpose",
41 TRANSPOSE,
42 "Permutes the dimensions."
43);
44prim!(Slice, "slice", SLICE, "A static slice, with strides.");
45prim!(
46 DynamicSlice,
47 "dynamic_slice",
48 DYNAMIC_SLICE,
49 "A slice at run-time start indices (one integer scalar per dimension), clamped to stay in bounds."
50);
51prim!(
52 DynamicUpdateSlice,
53 "dynamic_update_slice",
54 DYNAMIC_UPDATE_SLICE,
55 "Writes an update at run-time start indices, clamped to stay in bounds."
56);
57prim!(
58 Concatenate,
59 "concatenate",
60 CONCATENATE,
61 "Joins arrays along a dimension."
62);
63prim!(
64 Pad,
65 "pad",
66 PAD,
67 "Pads with a scalar value; negative padding removes elements."
68);
69prim!(Rev, "rev", REV, "Reverses dimensions.");
70prim!(Iota, "iota", IOTA, "The indices along a dimension.");
71
72fn out(x: &HostArray, b: Buffer, shape: impl Into<Shape>) -> Vec<HostArray> {
73 let _ = x;
74 vec![HostArray::from_buffer(b, shape)]
75}
76
77impl Primitive for BroadcastInDim {
78 fn name(&self) -> &'static str {
79 "broadcast_in_dim"
80 }
81 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
82 arity(self.name(), inputs, 1)?;
83 let Params::BroadcastInDim {
84 shape,
85 broadcast_dimensions: dims,
86 } = params
87 else {
88 return Err(wrong_params(self.name()));
89 };
90 let x = &inputs[0];
91 let ok = dims.len() == x.shape.rank()
92 && dims.windows(2).all(|w| w[0] < w[1])
93 && dims
94 .iter()
95 .enumerate()
96 .all(|(i, &d)| d < shape.rank() && (x.shape[i] == 1 || x.shape[i] == shape[d]));
97 if !ok {
98 return Err(Error::type_error(
99 self.name(),
100 format!("cannot broadcast {x} to [{shape}] with {dims:?}"),
101 ));
102 }
103 Ok(vec![AVal::new(shape.clone(), x.dtype)])
104 }
105 fn eval(
106 &self,
107 _: &dyn EvalCx,
108 inputs: &[HostArray],
109 params: &Params,
110 ) -> Result<Vec<HostArray>> {
111 let Params::BroadcastInDim {
112 shape,
113 broadcast_dimensions,
114 } = params
115 else {
116 return Err(wrong_params(self.name()));
117 };
118 let x = &inputs[0];
119 let b = with_buffer!(x.buffer(), |v| Buffer::from_vec(k::broadcast_in_dim(
120 v,
121 x.shape(),
122 shape,
123 broadcast_dimensions
124 )));
125 Ok(out(x, b, shape.clone()))
126 }
127
128 fn batch(
129 &'static self,
130 cx: &mut dyn BatchCx,
131 inputs: &[Batched],
132 params: &Params,
133 ) -> Result<Vec<Batched>> {
134 let Params::BroadcastInDim {
135 shape,
136 broadcast_dimensions,
137 } = params
138 else {
139 return Err(wrong_params(self.name()));
140 };
141 let x = batching::bdim_at_front(cx, &inputs[0])?;
144 let mut dims = vec![0];
145 dims.extend(broadcast_dimensions.iter().map(|&d| d + 1));
146 let n = cx.axis_size();
147 let out = batching::bind1(
148 cx,
149 BROADCAST_IN_DIM,
150 &[x],
151 Params::BroadcastInDim {
152 shape: batching::insert_dim(shape.dims(), 0, n).into(),
153 broadcast_dimensions: dims,
154 },
155 )?;
156 Ok(vec![Batched::mapped(out, 0)])
157 }
158
159 fn lower(
160 &self,
161 cx: &mut dyn LowerCx,
162 inputs: &[HloValue],
163 params: &Params,
164 outputs: &[AVal],
165 ) -> Result<Vec<HloValue>> {
166 let Params::BroadcastInDim {
167 broadcast_dimensions: dims,
168 ..
169 } = params
170 else {
171 return Err(wrong_params(self.name()));
172 };
173 let attrs = format!("broadcast_dimensions = {}", i64_array(dims));
174 Ok(vec![cx.op1(
175 "stablehlo.broadcast_in_dim",
176 inputs,
177 &attrs,
178 &outputs[0],
179 )])
180 }
181
182 fn jvp(
183 &'static self,
184 cx: &mut dyn AdCx,
185 primals: &[Atom],
186 tangents: &[Tangent],
187 params: &Params,
188 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
189 sad::linear_jvp(cx, Prim::new(self), primals, tangents, params)
190 }
191
192 fn transpose(
193 &'static self,
194 cx: &mut dyn AdCx,
195 cotangents: &[Tangent],
196 inputs: &[TransposeInput],
197 params: &Params,
198 ) -> Result<Vec<Tangent>> {
199 sad::broadcast_in_dim_transpose(cx, &cotangents[0], &inputs[0], params)
200 }
201}
202
203impl Primitive for Reshape {
204 fn name(&self) -> &'static str {
205 "reshape"
206 }
207 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
208 arity(self.name(), inputs, 1)?;
209 let Params::Reshape { new_sizes } = params else {
210 return Err(wrong_params(self.name()));
211 };
212 if new_sizes.checked_size() != Some(inputs[0].shape.size()) {
213 return Err(Error::type_error(
214 self.name(),
215 format!("cannot reshape {} to [{new_sizes}]", inputs[0]),
216 ));
217 }
218 Ok(vec![AVal::new(new_sizes.clone(), inputs[0].dtype)])
219 }
220 fn eval(
221 &self,
222 _: &dyn EvalCx,
223 inputs: &[HostArray],
224 params: &Params,
225 ) -> Result<Vec<HostArray>> {
226 let Params::Reshape { new_sizes } = params else {
227 return Err(wrong_params(self.name()));
228 };
229 Ok(vec![inputs[0].clone().reshape(new_sizes.clone())])
230 }
231
232 fn batch(
233 &'static self,
234 cx: &mut dyn BatchCx,
235 inputs: &[Batched],
236 params: &Params,
237 ) -> Result<Vec<Batched>> {
238 let Params::Reshape { new_sizes } = params else {
239 return Err(wrong_params(self.name()));
240 };
241 let x = batching::bdim_at_front(cx, &inputs[0])?;
242 let n = cx.axis_size();
243 let out = batching::bind1(
244 cx,
245 RESHAPE,
246 &[x],
247 Params::Reshape {
248 new_sizes: batching::insert_dim(new_sizes.dims(), 0, n).into(),
249 },
250 )?;
251 Ok(vec![Batched::mapped(out, 0)])
252 }
253
254 fn lower(
255 &self,
256 cx: &mut dyn LowerCx,
257 inputs: &[HloValue],
258 _: &Params,
259 outputs: &[AVal],
260 ) -> Result<Vec<HloValue>> {
261 Ok(vec![cx.op1("stablehlo.reshape", inputs, "", &outputs[0])])
262 }
263
264 fn jvp(
265 &'static self,
266 cx: &mut dyn AdCx,
267 primals: &[Atom],
268 tangents: &[Tangent],
269 params: &Params,
270 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
271 sad::linear_jvp(cx, Prim::new(self), primals, tangents, params)
272 }
273
274 fn transpose(
275 &'static self,
276 cx: &mut dyn AdCx,
277 cotangents: &[Tangent],
278 inputs: &[TransposeInput],
279 params: &Params,
280 ) -> Result<Vec<Tangent>> {
281 let _ = params;
282 sad::reshape_transpose(cx, &cotangents[0], &inputs[0])
283 }
284}
285
286impl Primitive for Transpose {
287 fn name(&self) -> &'static str {
288 "transpose"
289 }
290 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
291 arity(self.name(), inputs, 1)?;
292 let Params::Transpose { permutation } = params else {
293 return Err(wrong_params(self.name()));
294 };
295 let x = &inputs[0];
296 if permutation.len() != x.shape.rank() {
297 return Err(Error::type_error(
298 self.name(),
299 format!("{permutation:?} is not a permutation for {x}"),
300 ));
301 }
302 check_axes(self.name(), permutation, x.shape.rank())?;
303 Ok(vec![AVal::new(
304 permutation.iter().map(|&p| x.shape[p]).collect::<Vec<_>>(),
305 x.dtype,
306 )])
307 }
308 fn eval(
309 &self,
310 _: &dyn EvalCx,
311 inputs: &[HostArray],
312 params: &Params,
313 ) -> Result<Vec<HostArray>> {
314 let Params::Transpose { permutation } = params else {
315 return Err(wrong_params(self.name()));
316 };
317 let x = &inputs[0];
318 let shape: Vec<usize> = permutation.iter().map(|&p| x.shape()[p]).collect();
319 let b = with_buffer!(x.buffer(), |v| Buffer::from_vec(k::transpose(
320 v,
321 x.shape(),
322 permutation
323 )));
324 Ok(out(x, b, shape))
325 }
326
327 fn batch(
328 &'static self,
329 cx: &mut dyn BatchCx,
330 inputs: &[Batched],
331 params: &Params,
332 ) -> Result<Vec<Batched>> {
333 let Params::Transpose { permutation } = params else {
334 return Err(wrong_params(self.name()));
335 };
336 let x = &inputs[0];
337 let b = batched_operand(self.name(), x)?;
338 let mut perm = vec![b];
339 perm.extend(permutation.iter().map(|&p| batching::batched_dim(p, b)));
340 let out = batching::bind1(
341 cx,
342 TRANSPOSE,
343 std::slice::from_ref(&x.atom),
344 Params::Transpose { permutation: perm },
345 )?;
346 Ok(vec![Batched::mapped(out, 0)])
347 }
348
349 fn lower(
350 &self,
351 cx: &mut dyn LowerCx,
352 inputs: &[HloValue],
353 params: &Params,
354 outputs: &[AVal],
355 ) -> Result<Vec<HloValue>> {
356 let Params::Transpose { permutation } = params else {
357 return Err(wrong_params(self.name()));
358 };
359 let attrs = format!("permutation = {}", i64_array(permutation));
360 Ok(vec![cx.op1(
361 "stablehlo.transpose",
362 inputs,
363 &attrs,
364 &outputs[0],
365 )])
366 }
367
368 fn jvp(
369 &'static self,
370 cx: &mut dyn AdCx,
371 primals: &[Atom],
372 tangents: &[Tangent],
373 params: &Params,
374 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
375 sad::linear_jvp(cx, Prim::new(self), primals, tangents, params)
376 }
377
378 fn transpose(
379 &'static self,
380 cx: &mut dyn AdCx,
381 cotangents: &[Tangent],
382 inputs: &[TransposeInput],
383 params: &Params,
384 ) -> Result<Vec<Tangent>> {
385 let _ = inputs;
386 sad::transpose_transpose(cx, &cotangents[0], params)
387 }
388}
389
390fn slice_shape(
391 name: &'static str,
392 x: &AVal,
393 start: &[usize],
394 limit: &[usize],
395 step: &[usize],
396) -> Result<Vec<usize>> {
397 let r = x.shape.rank();
398 if start.len() != r || limit.len() != r || step.len() != r {
399 return Err(Error::type_error(
400 name,
401 format!("slice bounds must have one entry per dimension of {x}"),
402 ));
403 }
404 (0..r)
405 .map(|i| {
406 if start[i] > limit[i] || limit[i] > x.shape[i] || step[i] == 0 {
407 Err(Error::type_error(
408 name,
409 format!(
410 "invalid slice {}..{} step {} of {x}",
411 start[i], limit[i], step[i]
412 ),
413 ))
414 } else {
415 Ok((limit[i] - start[i]).div_ceil(step[i]))
416 }
417 })
418 .collect()
419}
420
421impl Primitive for Slice {
422 fn name(&self) -> &'static str {
423 "slice"
424 }
425 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
426 arity(self.name(), inputs, 1)?;
427 let Params::Slice {
428 start_indices,
429 limit_indices,
430 strides,
431 } = params
432 else {
433 return Err(wrong_params(self.name()));
434 };
435 let shape = slice_shape(
436 self.name(),
437 &inputs[0],
438 start_indices,
439 limit_indices,
440 strides,
441 )?;
442 Ok(vec![AVal::new(shape, inputs[0].dtype)])
443 }
444 fn eval(
445 &self,
446 _: &dyn EvalCx,
447 inputs: &[HostArray],
448 params: &Params,
449 ) -> Result<Vec<HostArray>> {
450 let Params::Slice {
451 start_indices,
452 limit_indices,
453 strides,
454 } = params
455 else {
456 return Err(wrong_params(self.name()));
457 };
458 let x = &inputs[0];
459 let shape = slice_shape(
460 self.name(),
461 &x.aval(),
462 start_indices,
463 limit_indices,
464 strides,
465 )?;
466 let b = with_buffer!(x.buffer(), |v| Buffer::from_vec(k::slice(
467 v,
468 x.shape(),
469 start_indices,
470 limit_indices,
471 strides
472 )));
473 Ok(out(x, b, shape))
474 }
475
476 fn batch(
477 &'static self,
478 cx: &mut dyn BatchCx,
479 inputs: &[Batched],
480 params: &Params,
481 ) -> Result<Vec<Batched>> {
482 let Params::Slice {
483 start_indices,
484 limit_indices,
485 strides,
486 } = params
487 else {
488 return Err(wrong_params(self.name()));
489 };
490 let x = &inputs[0];
491 let b = batched_operand(self.name(), x)?;
492 let n = cx.axis_size();
493 let out = batching::bind1(
494 cx,
495 SLICE,
496 std::slice::from_ref(&x.atom),
497 Params::Slice {
498 start_indices: batching::insert_dim(start_indices, b, 0),
499 limit_indices: batching::insert_dim(limit_indices, b, n),
500 strides: batching::insert_dim(strides, b, 1),
501 },
502 )?;
503 Ok(vec![Batched::mapped(out, b)])
504 }
505
506 fn lower(
507 &self,
508 cx: &mut dyn LowerCx,
509 inputs: &[HloValue],
510 params: &Params,
511 outputs: &[AVal],
512 ) -> Result<Vec<HloValue>> {
513 let Params::Slice {
514 start_indices,
515 limit_indices,
516 strides,
517 } = params
518 else {
519 return Err(wrong_params(self.name()));
520 };
521 let attrs = format!(
522 "start_indices = {}, limit_indices = {}, strides = {}",
523 i64_array(start_indices),
524 i64_array(limit_indices),
525 i64_array(strides)
526 );
527 Ok(vec![cx.op1("stablehlo.slice", inputs, &attrs, &outputs[0])])
528 }
529
530 fn jvp(
531 &'static self,
532 cx: &mut dyn AdCx,
533 primals: &[Atom],
534 tangents: &[Tangent],
535 params: &Params,
536 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
537 sad::linear_jvp(cx, SLICE, primals, tangents, params)
538 }
539
540 fn transpose(
541 &'static self,
542 cx: &mut dyn AdCx,
543 cotangents: &[Tangent],
544 inputs: &[TransposeInput],
545 params: &Params,
546 ) -> Result<Vec<Tangent>> {
547 sad::slice_transpose(cx, &cotangents[0], &inputs[0], params)
548 }
549}
550
551fn check_starts(name: &'static str, x: &AVal, starts: &[AVal]) -> Result<()> {
554 if starts.len() != x.shape.rank() {
555 return Err(Error::type_error(
556 name,
557 format!("expected {} start indices for {x}", x.shape.rank()),
558 ));
559 }
560 for s in starts {
561 integer(name, s)?;
562 if s.shape.rank() != 0 || s.dtype != starts[0].dtype {
563 return Err(Error::type_error(
564 name,
565 format!("start indices must be scalars of one type, got {s}"),
566 ));
567 }
568 }
569 Ok(())
570}
571
572fn starts(inputs: &[HostArray]) -> Vec<i64> {
573 inputs.iter().map(|s| indices(s)[0]).collect()
574}
575
576impl Primitive for DynamicSlice {
577 fn name(&self) -> &'static str {
578 "dynamic_slice"
579 }
580 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
581 let Params::DynamicSlice { slice_sizes } = params else {
582 return Err(wrong_params(self.name()));
583 };
584 let Some((x, rest)) = inputs.split_first() else {
585 return Err(Error::type_error(self.name(), "expected an operand"));
586 };
587 check_starts(self.name(), x, rest)?;
588 if slice_sizes.len() != x.shape.rank()
589 || slice_sizes.iter().zip(x.shape.dims()).any(|(s, n)| s > n)
590 {
591 return Err(Error::type_error(
592 self.name(),
593 format!("invalid slice sizes {slice_sizes:?} for {x}"),
594 ));
595 }
596 Ok(vec![AVal::new(slice_sizes.clone(), x.dtype)])
597 }
598 fn eval(
599 &self,
600 _: &dyn EvalCx,
601 inputs: &[HostArray],
602 params: &Params,
603 ) -> Result<Vec<HostArray>> {
604 let Params::DynamicSlice { slice_sizes } = params else {
605 return Err(wrong_params(self.name()));
606 };
607 let x = &inputs[0];
608 let s = starts(&inputs[1..]);
609 let b = with_buffer!(x.buffer(), |v| Buffer::from_vec(k::dynamic_slice(
610 v,
611 x.shape(),
612 &s,
613 slice_sizes
614 )));
615 Ok(out(x, b, slice_sizes.clone()))
616 }
617
618 fn batch(
619 &'static self,
620 cx: &mut dyn BatchCx,
621 inputs: &[Batched],
622 params: &Params,
623 ) -> Result<Vec<Batched>> {
624 let Params::DynamicSlice { slice_sizes } = params else {
625 return Err(wrong_params(self.name()));
626 };
627 crate::indexing::batch_dynamic_slice(cx, &inputs[0], &inputs[1..], slice_sizes)
629 }
630
631 fn lower(
632 &self,
633 cx: &mut dyn LowerCx,
634 inputs: &[HloValue],
635 params: &Params,
636 outputs: &[AVal],
637 ) -> Result<Vec<HloValue>> {
638 let Params::DynamicSlice { slice_sizes } = params else {
639 return Err(wrong_params(self.name()));
640 };
641 let attrs = format!("slice_sizes = {}", i64_array(slice_sizes));
642 Ok(vec![cx.op1(
643 "stablehlo.dynamic_slice",
644 inputs,
645 &attrs,
646 &outputs[0],
647 )])
648 }
649
650 fn jvp(
651 &'static self,
652 cx: &mut dyn AdCx,
653 primals: &[Atom],
654 tangents: &[Tangent],
655 params: &Params,
656 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
657 sad::linear_jvp(cx, DYNAMIC_SLICE, primals, tangents, params)
659 }
660
661 fn transpose(
662 &'static self,
663 cx: &mut dyn AdCx,
664 cotangents: &[Tangent],
665 inputs: &[TransposeInput],
666 _: &Params,
667 ) -> Result<Vec<Tangent>> {
668 sad::dynamic_slice_transpose(cx, &cotangents[0], inputs)
669 }
670}
671
672impl Primitive for DynamicUpdateSlice {
673 fn name(&self) -> &'static str {
674 "dynamic_update_slice"
675 }
676 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
677 if *params != Params::None {
678 return Err(wrong_params(self.name()));
679 }
680 if inputs.len() < 2 {
681 return Err(Error::type_error(
682 self.name(),
683 "expected an operand and an update",
684 ));
685 }
686 let (x, u) = (&inputs[0], &inputs[1]);
687 check_starts(self.name(), x, &inputs[2..])?;
688 let fits = u.shape.rank() == x.shape.rank()
689 && u.shape.iter().zip(x.shape.dims()).all(|(a, b)| a <= b);
690 if u.dtype != x.dtype || !fits {
691 return Err(Error::type_error(
692 self.name(),
693 format!("update {u} does not fit {x}"),
694 ));
695 }
696 Ok(vec![x.clone()])
697 }
698 fn eval(&self, _: &dyn EvalCx, inputs: &[HostArray], _: &Params) -> Result<Vec<HostArray>> {
699 let (x, u) = (&inputs[0], &inputs[1]);
700 let s = starts(&inputs[2..]);
701 let b = with_buffer!(x.buffer(), |v| Buffer::from_vec(k::dynamic_update_slice(
702 v,
703 x.shape(),
704 u.as_slice().expect("same types"),
705 u.shape(),
706 &s
707 )));
708 Ok(out(x, b, x.shape().clone()))
709 }
710
711 fn batch(
712 &'static self,
713 cx: &mut dyn BatchCx,
714 inputs: &[Batched],
715 params: &Params,
716 ) -> Result<Vec<Batched>> {
717 if *params != Params::None {
718 return Err(wrong_params(self.name()));
719 }
720 crate::indexing::batch_dynamic_update_slice(cx, &inputs[0], &inputs[1], &inputs[2..])
722 }
723
724 fn lower(
725 &self,
726 cx: &mut dyn LowerCx,
727 inputs: &[HloValue],
728 _: &Params,
729 outputs: &[AVal],
730 ) -> Result<Vec<HloValue>> {
731 Ok(vec![cx.op1(
732 "stablehlo.dynamic_update_slice",
733 inputs,
734 "",
735 &outputs[0],
736 )])
737 }
738
739 fn jvp(
740 &'static self,
741 cx: &mut dyn AdCx,
742 primals: &[Atom],
743 tangents: &[Tangent],
744 _: &Params,
745 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
746 sad::dynamic_update_slice_jvp(cx, primals, tangents)
747 }
748
749 fn transpose(
750 &'static self,
751 cx: &mut dyn AdCx,
752 cotangents: &[Tangent],
753 inputs: &[TransposeInput],
754 _: &Params,
755 ) -> Result<Vec<Tangent>> {
756 sad::dynamic_update_slice_transpose(cx, &cotangents[0], inputs)
757 }
758}
759
760impl Primitive for Concatenate {
761 fn name(&self) -> &'static str {
762 "concatenate"
763 }
764 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
765 let Params::Concatenate { dimension } = params else {
766 return Err(wrong_params(self.name()));
767 };
768 let Some(first) = inputs.first() else {
769 return Err(Error::type_error(self.name(), "expected operands"));
770 };
771 if *dimension >= first.shape.rank() {
772 return Err(Error::type_error(
773 self.name(),
774 format!("dimension {dimension} is out of bounds for {first}"),
775 ));
776 }
777 let mut shape = first.shape.dims().to_vec();
778 shape[*dimension] = 0;
779 for x in inputs {
780 let compatible = x.dtype == first.dtype
781 && x.shape.rank() == first.shape.rank()
782 && (0..shape.len()).all(|i| i == *dimension || x.shape[i] == first.shape[i]);
783 if !compatible {
784 return Err(Error::type_error(
785 self.name(),
786 format!("cannot join {x} with {first}"),
787 ));
788 }
789 shape[*dimension] += x.shape[*dimension];
790 }
791 Ok(vec![AVal::new(shape, first.dtype)])
792 }
793 fn eval(
794 &self,
795 _: &dyn EvalCx,
796 inputs: &[HostArray],
797 params: &Params,
798 ) -> Result<Vec<HostArray>> {
799 let Params::Concatenate { dimension } = params else {
800 return Err(wrong_params(self.name()));
801 };
802 let avals: Vec<AVal> = inputs.iter().map(HostArray::aval).collect();
803 let shape = self.abstract_eval(&avals, params)?.remove(0).shape;
804 let b = with_buffer!(inputs[0].buffer(), |first| {
805 let parts: Vec<(&[_], &[usize])> =
806 std::iter::once((first.as_slice(), inputs[0].shape().dims()))
807 .chain(
808 inputs[1..]
809 .iter()
810 .map(|x| (x.as_slice().expect("same types"), x.shape().dims())),
811 )
812 .collect();
813 Buffer::from_vec(k::concatenate(&parts, *dimension))
814 });
815 Ok(vec![HostArray::from_buffer(b, shape)])
816 }
817
818 fn batch(
819 &'static self,
820 cx: &mut dyn BatchCx,
821 inputs: &[Batched],
822 params: &Params,
823 ) -> Result<Vec<Batched>> {
824 let Params::Concatenate { dimension } = params else {
825 return Err(wrong_params(self.name()));
826 };
827 let atoms = inputs
829 .iter()
830 .map(|x| batching::bdim_at_front(cx, x))
831 .collect::<Result<Vec<_>>>()?;
832 let out = batching::bind1(
833 cx,
834 CONCATENATE,
835 &atoms,
836 Params::Concatenate {
837 dimension: dimension + 1,
838 },
839 )?;
840 Ok(vec![Batched::mapped(out, 0)])
841 }
842
843 fn lower(
844 &self,
845 cx: &mut dyn LowerCx,
846 inputs: &[HloValue],
847 params: &Params,
848 outputs: &[AVal],
849 ) -> Result<Vec<HloValue>> {
850 let Params::Concatenate { dimension } = *params else {
851 return Err(wrong_params(self.name()));
852 };
853 let attrs = format!("dimension = {dimension} : i64");
854 Ok(vec![cx.op1(
855 "stablehlo.concatenate",
856 inputs,
857 &attrs,
858 &outputs[0],
859 )])
860 }
861
862 fn jvp(
863 &'static self,
864 cx: &mut dyn AdCx,
865 primals: &[Atom],
866 tangents: &[Tangent],
867 params: &Params,
868 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
869 sad::linear_jvp_all(cx, CONCATENATE, primals, tangents, params)
870 }
871
872 fn transpose(
873 &'static self,
874 cx: &mut dyn AdCx,
875 cotangents: &[Tangent],
876 inputs: &[TransposeInput],
877 params: &Params,
878 ) -> Result<Vec<Tangent>> {
879 sad::concatenate_transpose(cx, &cotangents[0], inputs, params)
880 }
881}
882
883fn padded_shape(x: &AVal, config: &[(i64, i64, usize)]) -> Option<Vec<usize>> {
884 if config.len() != x.shape.rank() {
885 return None;
886 }
887 let dims = x
888 .shape
889 .iter()
890 .zip(config)
891 .map(|(&n, &(lo, hi, int))| {
892 let (n, int) = (n as i128, int as i128);
893 let inner = if n == 0 { 0 } else { n + (n - 1) * int };
894 usize::try_from(i128::from(lo) + i128::from(hi) + inner).ok()
895 })
896 .collect::<Option<Vec<usize>>>()?;
897 Shape::new(&dims).checked_size().map(|_| dims)
898}
899
900impl Primitive for Pad {
901 fn name(&self) -> &'static str {
902 "pad"
903 }
904 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
905 arity(self.name(), inputs, 2)?;
906 let Params::Pad { padding_config } = params else {
907 return Err(wrong_params(self.name()));
908 };
909 let (x, v) = (&inputs[0], &inputs[1]);
910 if v.shape.rank() != 0 || v.dtype != x.dtype {
911 return Err(Error::type_error(
912 self.name(),
913 format!("the padding value must be a scalar like {x}, got {v}"),
914 ));
915 }
916 let shape = padded_shape(x, padding_config).ok_or_else(|| {
917 Error::type_error(
918 self.name(),
919 format!("invalid padding {padding_config:?} of {x}"),
920 )
921 })?;
922 Ok(vec![AVal::new(shape, x.dtype)])
923 }
924 fn eval(
925 &self,
926 _: &dyn EvalCx,
927 inputs: &[HostArray],
928 params: &Params,
929 ) -> Result<Vec<HostArray>> {
930 let Params::Pad { padding_config } = params else {
931 return Err(wrong_params(self.name()));
932 };
933 let x = &inputs[0];
934 let shape = padded_shape(&x.aval(), padding_config).expect("checked");
935 let b = with_buffer!(x.buffer(), |v| {
936 let value = inputs[1].as_slice().expect("same types")[0];
937 Buffer::from_vec(k::pad(v, x.shape(), value, padding_config))
938 });
939 Ok(out(x, b, shape))
940 }
941
942 fn batch(
943 &'static self,
944 cx: &mut dyn BatchCx,
945 inputs: &[Batched],
946 params: &Params,
947 ) -> Result<Vec<Batched>> {
948 let Params::Pad { padding_config } = params else {
949 return Err(wrong_params(self.name()));
950 };
951 let (x, value) = (&inputs[0], &inputs[1]);
952 let (operand, b) = match x.bdim {
955 Some(b) => (x.atom.clone(), b),
956 None => (batching::bdim_at_front(cx, x)?, 0),
957 };
958 let mut config = padding_config.clone();
959 config.insert(b, (0, 0, 0));
960 let params = Params::Pad {
961 padding_config: config,
962 };
963 if value.bdim.is_none() {
964 let out = batching::bind1(cx, PAD, &[operand, value.atom.clone()], params)?;
965 return Ok(vec![Batched::mapped(out, b)]);
966 }
967 let aval = operand.aval();
970 let zero = batching::literal(aval.dtype, Value::Int(0));
971 let padded = batching::bind1(cx, PAD, &[operand, zero], params.clone())?;
972 let ones = batching::bind1(
973 cx,
974 BROADCAST_IN_DIM,
975 &[batching::literal(DType::Bool, Value::Bool(true))],
976 Params::BroadcastInDim {
977 shape: aval.shape.clone(),
978 broadcast_dimensions: vec![],
979 },
980 )?;
981 let no = batching::literal(DType::Bool, Value::Bool(false));
982 let mask = batching::bind1(cx, PAD, &[ones, no], params)?;
983 let value = batching::bind1(
984 cx,
985 BROADCAST_IN_DIM,
986 std::slice::from_ref(&value.atom),
987 Params::BroadcastInDim {
988 shape: padded.aval().shape,
989 broadcast_dimensions: vec![b],
990 },
991 )?;
992 let out = batching::bind1(
993 cx,
994 crate::elementwise::SELECT_N,
995 &[mask, value, padded],
996 Params::None,
997 )?;
998 Ok(vec![Batched::mapped(out, b)])
999 }
1000
1001 fn lower(
1002 &self,
1003 cx: &mut dyn LowerCx,
1004 inputs: &[HloValue],
1005 params: &Params,
1006 outputs: &[AVal],
1007 ) -> Result<Vec<HloValue>> {
1008 let Params::Pad { padding_config } = params else {
1009 return Err(wrong_params(self.name()));
1010 };
1011 let list = |f: fn(&(i64, i64, usize)) -> i64| {
1012 let items: Vec<String> = padding_config.iter().map(|c| f(c).to_string()).collect();
1013 if items.is_empty() {
1014 String::from("array<i64>")
1015 } else {
1016 format!("array<i64: {}>", items.join(", "))
1017 }
1018 };
1019 let attrs = format!(
1020 "edge_padding_low = {}, edge_padding_high = {}, interior_padding = {}",
1021 list(|c| c.0),
1022 list(|c| c.1),
1023 list(|c| c.2 as i64)
1024 );
1025 Ok(vec![cx.op1("stablehlo.pad", inputs, &attrs, &outputs[0])])
1026 }
1027
1028 fn jvp(
1029 &'static self,
1030 cx: &mut dyn AdCx,
1031 primals: &[Atom],
1032 tangents: &[Tangent],
1033 params: &Params,
1034 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
1035 sad::linear_jvp_all(cx, PAD, primals, tangents, params)
1036 }
1037
1038 fn transpose(
1039 &'static self,
1040 cx: &mut dyn AdCx,
1041 cotangents: &[Tangent],
1042 inputs: &[TransposeInput],
1043 params: &Params,
1044 ) -> Result<Vec<Tangent>> {
1045 sad::pad_transpose(cx, &cotangents[0], inputs, params)
1046 }
1047}
1048
1049impl Primitive for Rev {
1050 fn name(&self) -> &'static str {
1051 "rev"
1052 }
1053 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
1054 arity(self.name(), inputs, 1)?;
1055 let Params::Rev { dimensions } = params else {
1056 return Err(wrong_params(self.name()));
1057 };
1058 check_axes(self.name(), dimensions, inputs[0].shape.rank())?;
1059 Ok(vec![inputs[0].clone()])
1060 }
1061 fn eval(
1062 &self,
1063 _: &dyn EvalCx,
1064 inputs: &[HostArray],
1065 params: &Params,
1066 ) -> Result<Vec<HostArray>> {
1067 let Params::Rev { dimensions } = params else {
1068 return Err(wrong_params(self.name()));
1069 };
1070 let x = &inputs[0];
1071 let b = with_buffer!(x.buffer(), |v| Buffer::from_vec(k::rev(
1072 v,
1073 x.shape(),
1074 dimensions
1075 )));
1076 Ok(out(x, b, x.shape().clone()))
1077 }
1078
1079 fn batch(
1080 &'static self,
1081 cx: &mut dyn BatchCx,
1082 inputs: &[Batched],
1083 params: &Params,
1084 ) -> Result<Vec<Batched>> {
1085 let Params::Rev { dimensions } = params else {
1086 return Err(wrong_params(self.name()));
1087 };
1088 let x = &inputs[0];
1089 let b = batched_operand(self.name(), x)?;
1090 let out = batching::bind1(
1091 cx,
1092 REV,
1093 std::slice::from_ref(&x.atom),
1094 Params::Rev {
1095 dimensions: dimensions
1096 .iter()
1097 .map(|&d| batching::batched_dim(d, b))
1098 .collect(),
1099 },
1100 )?;
1101 Ok(vec![Batched::mapped(out, b)])
1102 }
1103
1104 fn lower(
1105 &self,
1106 cx: &mut dyn LowerCx,
1107 inputs: &[HloValue],
1108 params: &Params,
1109 outputs: &[AVal],
1110 ) -> Result<Vec<HloValue>> {
1111 let Params::Rev { dimensions } = params else {
1112 return Err(wrong_params(self.name()));
1113 };
1114 let attrs = format!("dimensions = {}", i64_array(dimensions));
1115 Ok(vec![cx.op1(
1116 "stablehlo.reverse",
1117 inputs,
1118 &attrs,
1119 &outputs[0],
1120 )])
1121 }
1122
1123 fn jvp(
1124 &'static self,
1125 cx: &mut dyn AdCx,
1126 primals: &[Atom],
1127 tangents: &[Tangent],
1128 params: &Params,
1129 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
1130 sad::linear_jvp(cx, REV, primals, tangents, params)
1131 }
1132
1133 fn transpose(
1134 &'static self,
1135 cx: &mut dyn AdCx,
1136 cotangents: &[Tangent],
1137 _: &[TransposeInput],
1138 params: &Params,
1139 ) -> Result<Vec<Tangent>> {
1140 sad::rev_transpose(cx, &cotangents[0], params)
1141 }
1142}
1143
1144impl Primitive for Iota {
1145 fn name(&self) -> &'static str {
1146 "iota"
1147 }
1148 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
1149 arity(self.name(), inputs, 0)?;
1150 let Params::Iota {
1151 dtype,
1152 shape,
1153 dimension,
1154 } = params
1155 else {
1156 return Err(wrong_params(self.name()));
1157 };
1158 if *dimension >= shape.rank() || *dtype == DType::Bool {
1159 return Err(Error::type_error(
1160 self.name(),
1161 format!("invalid iota of {dtype}[{shape}] along {dimension}"),
1162 ));
1163 }
1164 Ok(vec![AVal::new(shape.clone(), *dtype)])
1165 }
1166 fn eval(&self, _: &dyn EvalCx, _: &[HostArray], params: &Params) -> Result<Vec<HostArray>> {
1167 let Params::Iota {
1168 dtype,
1169 shape,
1170 dimension,
1171 } = params
1172 else {
1173 return Err(wrong_params(self.name()));
1174 };
1175 let b = with_dtype!(*dtype, |T| Buffer::from_vec(k::iota::<T>(
1176 shape, *dimension
1177 )));
1178 Ok(vec![HostArray::from_buffer(b, shape.clone())])
1179 }
1180
1181 fn batch(
1182 &'static self,
1183 cx: &mut dyn BatchCx,
1184 inputs: &[Batched],
1185 params: &Params,
1186 ) -> Result<Vec<Batched>> {
1187 let _ = (cx, inputs, params);
1188 Err(Error::Malformed(String::from(
1189 "iota has no operands and is never batched",
1190 )))
1191 }
1192
1193 fn lower(
1194 &self,
1195 cx: &mut dyn LowerCx,
1196 inputs: &[HloValue],
1197 params: &Params,
1198 outputs: &[AVal],
1199 ) -> Result<Vec<HloValue>> {
1200 let Params::Iota { dimension, .. } = params else {
1201 return Err(wrong_params(self.name()));
1202 };
1203 let attrs = format!("iota_dimension = {dimension} : i64");
1204 Ok(vec![cx.op1("stablehlo.iota", inputs, &attrs, &outputs[0])])
1205 }
1206}