1use core::mem::MaybeUninit;
9
10use num_complex::{Complex32, Complex64};
11
12use crate::copy_plan::{replay_fused_raw, CopyPlan, OverwriteWriter, ReadModifyWrite};
13use crate::cost::KernelClass;
14use crate::inline::InlineVec;
15use crate::raw_ops::pair_tiles;
16use crate::raw_ops::{fuse_pair_layout, FusedPairLayout};
17use crate::{Exec, RawStridedMut, RawStridedRef, Result, StridedError, RAW_FUSED_RANK_LIMIT};
18
19type AxisVec<T> = InlineVec<T>;
20
21#[derive(Clone, Debug, Eq, PartialEq)]
33pub struct GatherSpec {
34 pub offset_dims: Vec<usize>,
35 pub collapsed_slice_dims: Vec<usize>,
36 pub start_index_map: Vec<usize>,
37 pub index_vector_dim: usize,
38 pub slice_sizes: Vec<usize>,
39}
40
41pub trait GatherIndex: Copy + Send + Sync {
43 fn to_i64(self) -> i64;
44}
45
46impl GatherIndex for i32 {
47 #[inline]
48 fn to_i64(self) -> i64 {
49 i64::from(self)
50 }
51}
52
53impl GatherIndex for i64 {
54 #[inline]
55 fn to_i64(self) -> i64 {
56 self
57 }
58}
59
60mod sealed {
61 pub trait Sealed {}
62}
63
64pub trait ScatterScalar: sealed::Sealed + Copy + Send + Sync {
72 fn wrapping_add(self, rhs: Self) -> Self;
86}
87
88macro_rules! impl_scatter_scalar {
89 (wrapping: $($int:ty),*; ieee: $($float:ty),*) => {
90 $(
91 impl sealed::Sealed for $int {}
92 impl ScatterScalar for $int {
93 #[inline(always)]
94 fn wrapping_add(self, rhs: Self) -> Self {
95 <$int>::wrapping_add(self, rhs)
96 }
97 }
98 )*
99 $(
100 impl sealed::Sealed for $float {}
101 impl ScatterScalar for $float {
102 #[inline(always)]
103 fn wrapping_add(self, rhs: Self) -> Self {
104 self + rhs
105 }
106 }
107 )*
108 };
109}
110
111impl_scatter_scalar!(wrapping: i32, i64; ieee: f32, f64, Complex32, Complex64);
112
113#[derive(Clone, Debug)]
115pub struct GatherPlan {
116 operand_dims: AxisVec<usize>,
117 operand_strides: AxisVec<isize>,
118 index_dims: AxisVec<usize>,
119 index_strides: AxisVec<isize>,
120 dest_dims: AxisVec<usize>,
121 dest_strides: AxisVec<isize>,
122 spec: GatherSpec,
123 replay: GatherReplay,
124 total: usize,
125}
126
127#[derive(Clone, Copy, Debug, Default)]
128struct GatherReplayAxis {
129 dest_step: isize,
130 dest_reset: isize,
131 window_step: isize,
132 window_reset: isize,
133 index_batch_step: isize,
134 index_batch_reset: isize,
135}
136
137#[derive(Clone, Debug)]
138struct GatherReplay {
139 axes: AxisVec<GatherReplayAxis>,
140 index_component_offsets: AxisVec<isize>,
141 index_operand_strides: AxisVec<isize>,
142}
143
144struct GatherReplayState {
145 coords: AxisVec<usize>,
146 dest_offset: isize,
147 window_offset: isize,
148 index_batch_offset: isize,
149}
150
151#[derive(Clone, Copy, Debug, Default)]
152struct WindowReplayAxis {
153 source_step: isize,
154 source_reset: isize,
155 dest_step: isize,
156 dest_reset: isize,
157}
158
159#[derive(Clone, Copy, Debug, Default)]
161struct OffsetSpan {
162 min: isize,
163 max: isize,
164}
165
166impl OffsetSpan {
167 fn covers(&self, base: isize) -> Result<()> {
169 base.checked_add(self.min)
170 .ok_or(StridedError::OffsetOverflow)?;
171 base.checked_add(self.max)
172 .ok_or(StridedError::OffsetOverflow)?;
173 Ok(())
174 }
175}
176
177#[derive(Clone, Debug)]
178struct WindowReplay {
179 shape: AxisVec<usize>,
180 axes: AxisVec<WindowReplayAxis>,
181 source_span: OffsetSpan,
185 dest_span: OffsetSpan,
186}
187
188struct WindowReplayState {
189 coords: CoordScratch,
190 source_offset: isize,
191 dest_offset: isize,
192}
193
194#[derive(Clone, Debug)]
195struct ScatterReplay {
196 batch: WindowReplay,
197 window: WindowReplay,
198 index_component_offsets: AxisVec<isize>,
199}
200
201impl ScatterReplay {
202 #[allow(clippy::too_many_arguments)]
205 fn compile(
206 batch_shape: &[usize],
207 index_dims: &[usize],
208 index_strides: &[isize],
209 index_vector_dim: usize,
210 index_component_count: usize,
211 update_dims: &[usize],
212 update_strides: &[isize],
213 update_window_dims: &[usize],
214 is_update_window_dim: &[bool],
215 window_shape_updates: &[usize],
216 window_dims: &[usize],
217 dest_strides: &[isize],
218 ) -> Result<Self> {
219 let (
220 batch_source_strides,
221 batch_dest_strides,
222 window_source_strides,
223 window_dest_strides,
224 vector_stride,
225 ) = scatter_replay_strides(
226 index_dims,
227 index_strides,
228 index_vector_dim,
229 update_dims,
230 update_strides,
231 update_window_dims,
232 is_update_window_dim,
233 window_dims,
234 dest_strides,
235 );
236 let batch = WindowReplay::compile(batch_shape, &batch_source_strides, &batch_dest_strides)?;
237 let window = WindowReplay::compile(
238 window_shape_updates,
239 &window_source_strides,
240 &window_dest_strides,
241 )?;
242 let mut index_component_offsets = AxisVec::with_capacity(index_component_count);
243 for component in 0..index_component_count {
244 index_component_offsets.push(checked_offset_add(0, vector_stride, component)?);
245 }
246 Ok(Self {
247 batch,
248 window,
249 index_component_offsets,
250 })
251 }
252}
253
254#[allow(clippy::too_many_arguments)]
257fn scatter_replay_strides(
258 index_dims: &[usize],
259 index_strides: &[isize],
260 index_vector_dim: usize,
261 update_dims: &[usize],
262 update_strides: &[isize],
263 update_window_dims: &[usize],
264 is_update_window_dim: &[bool],
265 window_dims: &[usize],
266 dest_strides: &[isize],
267) -> (
268 AxisVec<isize>,
269 AxisVec<isize>,
270 AxisVec<isize>,
271 AxisVec<isize>,
272 isize,
273) {
274 let batch_source_strides = index_dims
275 .iter()
276 .zip(index_strides.iter())
277 .enumerate()
278 .filter_map(|(axis, (_, &stride))| (axis != index_vector_dim).then_some(stride))
279 .collect();
280 let batch_dest_strides = update_dims
281 .iter()
282 .zip(update_strides.iter())
283 .enumerate()
284 .filter_map(|(axis, (_, &stride))| (!is_update_window_dim[axis]).then_some(stride))
285 .collect();
286 let window_source_strides = update_window_dims
287 .iter()
288 .map(|&axis| update_strides[axis])
289 .collect();
290 let window_dest_strides = window_dims.iter().map(|&axis| dest_strides[axis]).collect();
291 let vector_stride = if index_vector_dim < index_dims.len() {
292 index_strides[index_vector_dim]
293 } else {
294 0
295 };
296 (
297 batch_source_strides,
298 batch_dest_strides,
299 window_source_strides,
300 window_dest_strides,
301 vector_stride,
302 )
303}
304
305impl WindowReplay {
306 fn compile(shape: &[usize], source_strides: &[isize], dest_strides: &[isize]) -> Result<Self> {
307 let source_span = validate_layout_span(shape, source_strides)?;
308 let dest_span = validate_layout_span(shape, dest_strides)?;
309 let mut fused_shape: AxisVec<usize> = AxisVec::with_capacity(shape.len());
310 let mut axes: AxisVec<WindowReplayAxis> = AxisVec::with_capacity(shape.len());
311 for (axis, &dim) in shape.iter().enumerate() {
312 let source_step = source_strides[axis];
313 let dest_step = dest_strides[axis];
314 if let Some(previous_axis) = fused_shape.len().checked_sub(1) {
315 let previous_extent = fused_shape[previous_axis];
316 let previous_extent =
317 isize::try_from(previous_extent).map_err(|_| StridedError::OffsetOverflow)?;
318 let expected_source = axes[previous_axis]
319 .source_step
320 .checked_mul(previous_extent)
321 .ok_or(StridedError::OffsetOverflow)?;
322 let expected_dest = axes[previous_axis]
323 .dest_step
324 .checked_mul(previous_extent)
325 .ok_or(StridedError::OffsetOverflow)?;
326 if source_step == expected_source && dest_step == expected_dest {
327 let fused_extent = fused_shape[previous_axis]
328 .checked_mul(dim)
329 .ok_or(StridedError::OffsetOverflow)?;
330 fused_shape[previous_axis] = fused_extent;
331 axes[previous_axis].source_reset =
332 checked_replay_reset(fused_extent, axes[previous_axis].source_step)?;
333 axes[previous_axis].dest_reset =
334 checked_replay_reset(fused_extent, axes[previous_axis].dest_step)?;
335 continue;
336 }
337 }
338 fused_shape.push(dim);
339 axes.push(WindowReplayAxis {
340 source_step,
341 source_reset: checked_replay_reset(dim, source_step)?,
342 dest_step,
343 dest_reset: checked_replay_reset(dim, dest_step)?,
344 });
345 }
346 Ok(Self {
347 shape: fused_shape,
348 axes,
349 source_span,
350 dest_span,
351 })
352 }
353
354 fn start(&self, source_base: isize, dest_base: isize) -> WindowReplayState {
358 WindowReplayState {
359 coords: CoordScratch::new(self.shape.len()),
360 source_offset: source_base,
361 dest_offset: dest_base,
362 }
363 }
364
365 fn decode(
366 &self,
367 mut linear: usize,
368 source_base: isize,
369 dest_base: isize,
370 ) -> Result<WindowReplayState> {
371 let mut coords = CoordScratch::new(self.shape.len());
372 let mut source_offset = source_base;
373 let mut dest_offset = dest_base;
374 for (axis, (&dim, coord)) in self
375 .shape
376 .iter()
377 .zip(coords.as_mut_slice().iter_mut())
378 .enumerate()
379 {
380 *coord = linear % dim;
381 linear /= dim;
382 let replay_axis = self.axes[axis];
383 source_offset = checked_offset_add(source_offset, replay_axis.source_step, *coord)?;
384 dest_offset = checked_offset_add(dest_offset, replay_axis.dest_step, *coord)?;
385 }
386 Ok(WindowReplayState {
387 coords,
388 source_offset,
389 dest_offset,
390 })
391 }
392
393 #[inline]
394 fn advance(&self, state: &mut WindowReplayState) {
395 for ((coord, &dim), replay_axis) in state
396 .coords
397 .as_mut_slice()
398 .iter_mut()
399 .zip(self.shape.iter())
400 .zip(self.axes.iter())
401 {
402 let next = *coord + 1;
403 if next < dim {
404 *coord = next;
405 state.source_offset += replay_axis.source_step;
406 state.dest_offset += replay_axis.dest_step;
407 return;
408 }
409 *coord = 0;
410 state.source_offset += replay_axis.source_reset;
411 state.dest_offset += replay_axis.dest_reset;
412 }
413 }
414}
415
416#[derive(Clone, Debug, Eq, PartialEq)]
422pub struct ScatterSpec {
423 pub update_window_dims: Vec<usize>,
424 pub inserted_window_dims: Vec<usize>,
425 pub scatter_dims_to_operand_dims: Vec<usize>,
426 pub index_vector_dim: usize,
427}
428
429#[derive(Clone, Debug)]
431pub struct DynamicSlicePlan {
432 operand_dims: AxisVec<usize>,
433 operand_strides: AxisVec<isize>,
434 start_dims: AxisVec<usize>,
435 start_strides: AxisVec<isize>,
436 dest_dims: AxisVec<usize>,
437 dest_strides: AxisVec<isize>,
438 slice_sizes: AxisVec<usize>,
439 total: usize,
440 window: Option<FusedPairLayout>,
445 replay: WindowReplay,
446}
447
448#[derive(Clone, Debug)]
454pub struct DynamicUpdateSlicePlan {
455 operand_dims: AxisVec<usize>,
456 operand_strides: AxisVec<isize>,
457 start_dims: AxisVec<usize>,
458 start_strides: AxisVec<isize>,
459 update_dims: AxisVec<usize>,
460 update_strides: AxisVec<isize>,
461 dest_dims: AxisVec<usize>,
462 dest_strides: AxisVec<isize>,
463 total: usize,
464 copy_plan: CopyPlan,
465 window: Option<FusedPairLayout>,
470 replay: WindowReplay,
471}
472
473enum UpdateWindow<'a, T> {
481 Empty,
483 RankOne { update: &'a [T], dest_start: usize },
486 Replay { dest_base: isize },
489}
490
491#[derive(Clone, Debug)]
497pub struct ScatterPlan {
498 operand_dims: AxisVec<usize>,
499 operand_strides: AxisVec<isize>,
500 index_dims: AxisVec<usize>,
501 index_strides: AxisVec<isize>,
502 update_dims: AxisVec<usize>,
503 update_strides: AxisVec<isize>,
504 dest_dims: AxisVec<usize>,
505 dest_strides: AxisVec<isize>,
506 spec: ScatterSpec,
507 window_shape: AxisVec<usize>,
508 batch_elems: usize,
509 window_elems: usize,
510 copy_plan: CopyPlan,
511 replay: ScatterReplay,
512}
513
514impl GatherPlan {
515 pub fn compile(
534 operand_dims: &[usize],
535 operand_strides: &[isize],
536 index_dims: &[usize],
537 index_strides: &[isize],
538 dest_dims: &[usize],
539 dest_strides: &[isize],
540 spec: GatherSpec,
541 ) -> Result<Self> {
542 if operand_dims.len() != operand_strides.len()
543 || index_dims.len() != index_strides.len()
544 || dest_dims.len() != dest_strides.len()
545 {
546 return Err(StridedError::StrideLengthMismatch);
547 }
548 checked_total_len(operand_dims)?;
549 checked_total_len(index_dims)?;
550 let total = checked_total_len(dest_dims)?;
551 validate_layout_span(operand_dims, operand_strides)?;
552 validate_layout_span(index_dims, index_strides)?;
553 validate_layout_span(dest_dims, dest_strides)?;
554 if !crate::layout_check::is_injective_layout(dest_dims, dest_strides) {
555 return Err(StridedError::NonInjectiveOutputLayout);
556 }
557
558 let operand_rank = operand_dims.len();
559 if spec.slice_sizes.len() != operand_rank {
560 return Err(StridedError::RankMismatch(
561 spec.slice_sizes.len(),
562 operand_rank,
563 ));
564 }
565 validate_unique_axes(&spec.collapsed_slice_dims, operand_rank)?;
566 validate_unique_axes(&spec.start_index_map, operand_rank)?;
567 if spec.index_vector_dim > index_dims.len() {
568 return Err(StridedError::InvalidAxis {
569 axis: spec.index_vector_dim,
570 rank: index_dims.len() + 1,
571 });
572 }
573
574 for (axis, (&window, &dim)) in spec.slice_sizes.iter().zip(operand_dims.iter()).enumerate()
575 {
576 if window > dim {
577 return Err(StridedError::InvalidAxis {
578 axis,
579 rank: operand_rank,
580 });
581 }
582 }
583 for &axis in &spec.collapsed_slice_dims {
584 if spec.slice_sizes[axis] != 1 {
585 return Err(StridedError::InvalidAxis {
586 axis,
587 rank: operand_rank,
588 });
589 }
590 }
591
592 let index_vector_size = if spec.index_vector_dim == index_dims.len() {
593 1
594 } else {
595 index_dims[spec.index_vector_dim]
596 };
597 if index_vector_size != spec.start_index_map.len() {
598 return Err(StridedError::RankMismatch(
599 index_vector_size,
600 spec.start_index_map.len(),
601 ));
602 }
603
604 let window_dims = operand_window_dims(operand_rank, &spec.collapsed_slice_dims);
605 if spec.offset_dims.len() != window_dims.len() {
606 return Err(StridedError::RankMismatch(
607 spec.offset_dims.len(),
608 window_dims.len(),
609 ));
610 }
611
612 let batch_shape = index_batch_shape(index_dims, spec.index_vector_dim);
613 let out_rank = batch_shape.len() + spec.offset_dims.len();
614 validate_unique_axes(&spec.offset_dims, out_rank)?;
615
616 let mut out_axis_to_operand_dim: AxisVec<Option<usize>> =
617 (0..out_rank).map(|_| None).collect();
618 for (offset_axis, &out_axis) in spec.offset_dims.iter().enumerate() {
619 out_axis_to_operand_dim[out_axis] = Some(window_dims[offset_axis]);
620 }
621
622 let mut expected_dest_dims: AxisVec<usize> = AxisVec::with_capacity(out_rank);
623 let mut batch_axis = 0usize;
624 for &operand_dim in &out_axis_to_operand_dim {
625 match operand_dim {
626 Some(axis) => expected_dest_dims.push(spec.slice_sizes[axis]),
627 None => {
628 expected_dest_dims.push(batch_shape[batch_axis]);
629 batch_axis += 1;
630 }
631 }
632 }
633 if dest_dims != &expected_dest_dims[..] {
634 return Err(StridedError::ShapeMismatch(
635 dest_dims.to_vec(),
636 expected_dest_dims.to_vec(),
637 ));
638 }
639
640 let batch_index_strides: AxisVec<isize> = index_dims
641 .iter()
642 .zip(index_strides.iter())
643 .enumerate()
644 .filter_map(|(axis, (_, &stride))| (axis != spec.index_vector_dim).then_some(stride))
645 .collect();
646 let mut batch_axis = 0usize;
647 let mut replay_axes = AxisVec::with_capacity(out_rank);
648 for (out_axis, &operand_dim) in out_axis_to_operand_dim.iter().enumerate() {
649 let (window_step, index_batch_step) = match operand_dim {
650 Some(axis) => (operand_strides[axis], 0),
651 None => {
652 let step = batch_index_strides[batch_axis];
653 batch_axis += 1;
654 (0, step)
655 }
656 };
657 replay_axes.push(GatherReplayAxis {
658 dest_step: dest_strides[out_axis],
659 dest_reset: checked_replay_reset(dest_dims[out_axis], dest_strides[out_axis])?,
660 window_step,
661 window_reset: checked_replay_reset(dest_dims[out_axis], window_step)?,
662 index_batch_step,
663 index_batch_reset: checked_replay_reset(dest_dims[out_axis], index_batch_step)?,
664 });
665 }
666
667 let vector_stride = if spec.index_vector_dim < index_dims.len() {
668 index_strides[spec.index_vector_dim]
669 } else {
670 0
671 };
672 let mut index_component_offsets = AxisVec::with_capacity(spec.start_index_map.len());
673 for component in 0..spec.start_index_map.len() {
674 index_component_offsets.push(checked_offset_add(0, vector_stride, component)?);
675 }
676
677 let index_operand_strides: AxisVec<isize> = spec
678 .start_index_map
679 .iter()
680 .map(|&axis| operand_strides[axis])
681 .collect();
682
683 Ok(Self {
684 operand_dims: operand_dims.into(),
685 operand_strides: operand_strides.into(),
686 index_dims: index_dims.into(),
687 index_strides: index_strides.into(),
688 dest_dims: dest_dims.into(),
689 dest_strides: dest_strides.into(),
690 spec,
691 replay: GatherReplay {
692 axes: replay_axes,
693 index_component_offsets,
694 index_operand_strides,
695 },
696 total,
697 })
698 }
699
700 #[inline]
701 pub fn spec(&self) -> &GatherSpec {
702 &self.spec
703 }
704
705 #[inline]
706 pub fn dest_dims(&self) -> &[usize] {
707 &self.dest_dims
708 }
709
710 pub fn execute<T, I>(
724 &self,
725 dest: &mut RawStridedMut<'_, T>,
726 operand: &RawStridedRef<'_, T>,
727 start_indices: &RawStridedRef<'_, I>,
728 exec: Exec<'_>,
729 ) -> Result<()>
730 where
731 T: Copy + Send + Sync,
732 I: GatherIndex,
733 {
734 self.execute_with_writer(dest, operand, start_indices, exec)
735 }
736
737 pub(crate) fn execute_uninit<T, I>(
740 &self,
741 dest: &mut RawStridedMut<'_, MaybeUninit<T>>,
742 operand: &RawStridedRef<'_, T>,
743 start_indices: &RawStridedRef<'_, I>,
744 exec: Exec<'_>,
745 ) -> Result<()>
746 where
747 T: Copy + Send + Sync,
748 I: GatherIndex,
749 {
750 self.execute_with_writer(dest, operand, start_indices, exec)
751 }
752
753 fn execute_with_writer<T, I, W>(
754 &self,
755 dest: &mut W,
756 operand: &RawStridedRef<'_, T>,
757 start_indices: &RawStridedRef<'_, I>,
758 exec: Exec<'_>,
759 ) -> Result<()>
760 where
761 T: Copy + Send + Sync,
762 I: GatherIndex,
763 W: OverwriteWriter<T>,
764 {
765 self.check_call(dest, operand, start_indices)?;
766 if self.total == 0 {
767 return Ok(());
768 }
769 if self.uses_rank_one_scalar_take_path() {
770 let exec = crate::cost::for_len_tree(exec, KernelClass::Copy, self.total);
771 if !exec.is_serial() {
772 return self.execute_rank_one_scalar_take_parallel(
773 dest,
774 operand,
775 start_indices,
776 exec,
777 );
778 }
779 return self.execute_rank_one_scalar_take(dest, operand, start_indices);
780 }
781 let exec = crate::cost::for_len_tree(exec, KernelClass::Copy, self.total);
782 if !exec.is_serial() {
783 return self.execute_parallel(dest, operand, start_indices, exec);
784 }
785
786 let mut state =
787 self.decode_replay_state(0, dest.offset(), operand.offset(), start_indices.offset())?;
788 let operand_data = operand.data();
789 let index_data = start_indices.data();
790
791 for _ in 0..self.total {
795 let mut source_offset = state.window_offset;
800 for ((&index_component_offset, &operand_stride), &operand_dim) in self
801 .replay
802 .index_component_offsets
803 .iter()
804 .zip(self.replay.index_operand_strides.iter())
805 .zip(self.spec.start_index_map.iter())
806 {
807 let index_offset = state.index_batch_offset + index_component_offset;
808 let start = unsafe { *index_data.as_ptr().offset(index_offset) }.to_i64();
811 let clamped = self.clamp_window_start(start, operand_dim);
812 source_offset += operand_stride * clamped as isize;
813 }
814
815 let value = unsafe { *operand_data.as_ptr().offset(source_offset) };
818 unsafe { dest.write_at(state.dest_offset, value) };
819 self.advance_replay_state(&mut state);
820 }
821 Ok(())
822 }
823
824 fn uses_rank_one_scalar_take_path(&self) -> bool {
825 self.operand_dims.len() == 1
826 && self.index_dims.len() == 1
827 && self.dest_dims.len() == 1
828 && self.operand_strides[0] == 1
829 && self.index_strides[0] == 1
830 && self.dest_strides[0] == 1
831 && self.spec.offset_dims.is_empty()
832 && self.spec.collapsed_slice_dims.as_slice() == [0]
833 && self.spec.start_index_map.as_slice() == [0]
834 && self.spec.index_vector_dim == 1
835 && self.spec.slice_sizes.as_slice() == [1]
836 }
837
838 fn execute_rank_one_scalar_take<T, I, W>(
839 &self,
840 dest: &mut W,
841 operand: &RawStridedRef<'_, T>,
842 start_indices: &RawStridedRef<'_, I>,
843 ) -> Result<()>
844 where
845 T: Copy,
846 I: GatherIndex,
847 W: OverwriteWriter<T>,
848 {
849 let mut dest_offset = dest.offset();
850 let mut index_offset = start_indices.offset();
851 let operand_offset = operand.offset();
852 let operand_data = operand.data();
853 let index_data = start_indices.data();
854
855 #[allow(clippy::explicit_counter_loop)]
860 for _ in 0..self.total {
861 unsafe {
863 let start = (*index_data.as_ptr().offset(index_offset)).to_i64();
864 let source_offset = operand_offset + self.clamp_window_start(start, 0) as isize;
865 dest.write_at(dest_offset, *operand_data.as_ptr().offset(source_offset));
866 }
867 dest_offset += 1;
868 index_offset += 1;
869 }
870 Ok(())
871 }
872
873 fn execute_rank_one_scalar_take_parallel<T, I, W>(
874 &self,
875 dest: &mut W,
876 operand: &RawStridedRef<'_, T>,
877 start_indices: &RawStridedRef<'_, I>,
878 exec: Exec<'_>,
879 ) -> Result<()>
880 where
881 T: Copy + Send + Sync,
882 I: GatherIndex,
883 W: OverwriteWriter<T>,
884 {
885 let dest_offset = dest.offset();
886 let operand_offset = operand.offset();
887 let index_offset = start_indices.offset();
888 let dest_ptr = crate::threading::SendPtr(unsafe { dest.data_ptr() });
890 let operand_ptr = crate::threading::SendPtr(operand.data().as_ptr() as *mut T);
891 let index_ptr = crate::threading::SendPtr(start_indices.data().as_ptr() as *mut I);
892
893 crate::threading::parallel_map_reduce(
894 0..self.total,
895 exec,
896 &|range| {
897 let dest_ptr = dest_ptr.as_ptr();
898 let operand_ptr = operand_ptr.as_const();
899 let index_ptr = index_ptr.as_const();
900 for position in range {
903 let position = position as isize;
904 unsafe {
907 let start = (*index_ptr.offset(index_offset + position)).to_i64();
908 let source_offset =
909 operand_offset + self.clamp_window_start(start, 0) as isize;
910 dest_ptr
911 .offset(dest_offset + position)
912 .write(operand_ptr.offset(source_offset).read());
913 }
914 }
915 Ok(())
916 },
917 &|left, right| left.and(right),
918 )
919 }
920
921 fn execute_parallel<T, I, W>(
922 &self,
923 dest: &mut W,
924 operand: &RawStridedRef<'_, T>,
925 start_indices: &RawStridedRef<'_, I>,
926 exec: Exec<'_>,
927 ) -> Result<()>
928 where
929 T: Copy + Send + Sync,
930 I: GatherIndex,
931 W: OverwriteWriter<T>,
932 {
933 let dest_offset_base = dest.offset();
934 let operand_offset_base = operand.offset();
935 let index_offset_base = start_indices.offset();
936 let dest_ptr = crate::threading::SendPtr(unsafe { dest.data_ptr() });
938 let operand_ptr = crate::threading::SendPtr(operand.data().as_ptr() as *mut T);
939 let index_ptr = crate::threading::SendPtr(start_indices.data().as_ptr() as *mut I);
940
941 crate::threading::parallel_map_reduce(
942 0..self.total,
943 exec,
944 &|range| {
945 let mut state = self.decode_replay_state(
946 range.start,
947 dest_offset_base,
948 operand_offset_base,
949 index_offset_base,
950 )?;
951 let dest_ptr = dest_ptr.as_ptr();
952 let operand_ptr = operand_ptr.as_const();
953 let index_ptr = index_ptr.as_const();
954
955 for _ in range {
960 let mut source_offset = state.window_offset;
964 for ((&index_component_offset, &operand_stride), &operand_dim) in self
965 .replay
966 .index_component_offsets
967 .iter()
968 .zip(self.replay.index_operand_strides.iter())
969 .zip(self.spec.start_index_map.iter())
970 {
971 let index_offset = state.index_batch_offset + index_component_offset;
972 let start = unsafe { (*index_ptr.offset(index_offset)).to_i64() };
975 let clamped = self.clamp_window_start(start, operand_dim);
976 source_offset += operand_stride * clamped as isize;
977 }
978
979 unsafe {
982 dest_ptr
983 .offset(state.dest_offset)
984 .write(operand_ptr.offset(source_offset).read());
985 }
986 self.advance_replay_state(&mut state);
987 }
988 Ok(())
989 },
990 &|left, right| left.and(right),
991 )
992 }
993
994 fn check_call<T, I, W>(
995 &self,
996 dest: &W,
997 operand: &RawStridedRef<'_, T>,
998 start_indices: &RawStridedRef<'_, I>,
999 ) -> Result<()>
1000 where
1001 W: OverwriteWriter<T>,
1002 {
1003 if dest.dims() != &self.dest_dims[..]
1004 || dest.strides() != &self.dest_strides[..]
1005 || operand.dims() != &self.operand_dims[..]
1006 || operand.strides() != &self.operand_strides[..]
1007 || start_indices.dims() != &self.index_dims[..]
1008 || start_indices.strides() != &self.index_strides[..]
1009 {
1010 return Err(StridedError::PlanLayoutMismatch);
1011 }
1012 Ok(())
1013 }
1014
1015 fn decode_replay_state(
1016 &self,
1017 mut linear: usize,
1018 dest_offset_base: isize,
1019 operand_offset_base: isize,
1020 index_offset_base: isize,
1021 ) -> Result<GatherReplayState> {
1022 let mut coords = AxisVec::with_capacity(self.dest_dims.len());
1023 let mut dest_offset = dest_offset_base;
1024 let mut window_offset = operand_offset_base;
1025 let mut index_batch_offset = index_offset_base;
1026 for (axis, &dim) in self.dest_dims.iter().enumerate() {
1027 let coord = linear % dim;
1028 linear /= dim;
1029 let replay_axis = self.replay.axes[axis];
1030 coords.push(coord);
1031 dest_offset = checked_offset_add(dest_offset, replay_axis.dest_step, coord)?;
1032 window_offset = checked_offset_add(window_offset, replay_axis.window_step, coord)?;
1033 index_batch_offset =
1034 checked_offset_add(index_batch_offset, replay_axis.index_batch_step, coord)?;
1035 }
1036 Ok(GatherReplayState {
1037 coords,
1038 dest_offset,
1039 window_offset,
1040 index_batch_offset,
1041 })
1042 }
1043
1044 #[inline]
1045 fn advance_replay_state(&self, state: &mut GatherReplayState) {
1046 for (axis, replay_axis) in self.replay.axes.iter().enumerate() {
1047 let coord = state.coords[axis];
1048 if coord + 1 < self.dest_dims[axis] {
1049 state.coords[axis] = coord + 1;
1050 state.dest_offset += replay_axis.dest_step;
1051 state.window_offset += replay_axis.window_step;
1052 state.index_batch_offset += replay_axis.index_batch_step;
1053 return;
1054 }
1055 state.coords[axis] = 0;
1056 state.dest_offset += replay_axis.dest_reset;
1057 state.window_offset += replay_axis.window_reset;
1058 state.index_batch_offset += replay_axis.index_batch_reset;
1059 }
1060 }
1061
1062 #[inline]
1063 fn clamp_window_start(&self, start: i64, operand_dim: usize) -> usize {
1064 let dim_size = self.operand_dims[operand_dim];
1065 let window_size = self.spec.slice_sizes[operand_dim];
1066 let max_start = dim_size.saturating_sub(window_size) as i64;
1067 start.clamp(0, max_start) as usize
1068 }
1069}
1070
1071impl DynamicSlicePlan {
1072 pub fn compile(
1091 operand_dims: &[usize],
1092 operand_strides: &[isize],
1093 start_dims: &[usize],
1094 start_strides: &[isize],
1095 dest_dims: &[usize],
1096 dest_strides: &[isize],
1097 slice_sizes: &[usize],
1098 ) -> Result<Self> {
1099 if operand_dims.len() != operand_strides.len()
1100 || start_dims.len() != start_strides.len()
1101 || dest_dims.len() != dest_strides.len()
1102 {
1103 return Err(StridedError::StrideLengthMismatch);
1104 }
1105 if slice_sizes.len() != operand_dims.len() {
1106 return Err(StridedError::RankMismatch(
1107 slice_sizes.len(),
1108 operand_dims.len(),
1109 ));
1110 }
1111 validate_start_vector(start_dims, operand_dims.len())?;
1112 checked_total_len(operand_dims)?;
1113 checked_total_len(start_dims)?;
1114 let total = checked_total_len(dest_dims)?;
1115 validate_layout_span(operand_dims, operand_strides)?;
1116 validate_layout_span(start_dims, start_strides)?;
1117 validate_layout_span(dest_dims, dest_strides)?;
1118 if dest_dims != slice_sizes {
1119 return Err(StridedError::ShapeMismatch(
1120 dest_dims.to_vec(),
1121 slice_sizes.to_vec(),
1122 ));
1123 }
1124 if !crate::layout_check::is_injective_layout(dest_dims, dest_strides) {
1125 return Err(StridedError::NonInjectiveOutputLayout);
1126 }
1127 validate_window_sizes(operand_dims, slice_sizes)?;
1128 let replay = WindowReplay::compile(slice_sizes, operand_strides, dest_strides)?;
1129
1130 Ok(Self {
1131 operand_dims: operand_dims.into(),
1132 operand_strides: operand_strides.into(),
1133 start_dims: start_dims.into(),
1134 start_strides: start_strides.into(),
1135 dest_dims: dest_dims.into(),
1136 dest_strides: dest_strides.into(),
1137 slice_sizes: slice_sizes.into(),
1138 total,
1139 window: fuse_pair_layout(slice_sizes, dest_strides, operand_strides),
1140 replay,
1141 })
1142 }
1143
1144 pub fn execute<T, I>(
1154 &self,
1155 dest: &mut RawStridedMut<'_, T>,
1156 operand: &RawStridedRef<'_, T>,
1157 starts: &RawStridedRef<'_, I>,
1158 exec: Exec<'_>,
1159 ) -> Result<()>
1160 where
1161 T: Copy + Send + Sync,
1162 I: GatherIndex,
1163 {
1164 self.execute_with_writer(dest, operand, starts, exec)
1165 }
1166
1167 pub(crate) fn execute_uninit<T, I>(
1168 &self,
1169 dest: &mut RawStridedMut<'_, MaybeUninit<T>>,
1170 operand: &RawStridedRef<'_, T>,
1171 starts: &RawStridedRef<'_, I>,
1172 exec: Exec<'_>,
1173 ) -> Result<()>
1174 where
1175 T: Copy + Send + Sync,
1176 I: GatherIndex,
1177 {
1178 self.execute_with_writer(dest, operand, starts, exec)
1179 }
1180
1181 fn execute_with_writer<T, I, W>(
1182 &self,
1183 dest: &mut W,
1184 operand: &RawStridedRef<'_, T>,
1185 starts: &RawStridedRef<'_, I>,
1186 exec: Exec<'_>,
1187 ) -> Result<()>
1188 where
1189 T: Copy + Send + Sync,
1190 I: GatherIndex,
1191 W: OverwriteWriter<T>,
1192 {
1193 self.check_call(dest, operand, starts)?;
1194 if self.total == 0 {
1195 return Ok(());
1196 }
1197 if self.uses_rank_one_contiguous_path() {
1198 return self.execute_rank_one_contiguous(dest, operand, starts, exec);
1199 }
1200 if let Some(window) = &self.window {
1201 return self.execute_fused_window(dest, operand, starts, window, exec);
1202 }
1203 let replay = &self.replay;
1204 let exec = crate::cost::for_len_tree(exec, KernelClass::Copy, self.total);
1205 if !exec.is_serial() {
1206 return self.execute_parallel(dest, operand, starts, exec, replay);
1207 }
1208
1209 let mut starts_storage = CoordScratch::new(self.operand_dims.len());
1210 let clamped_starts = starts_storage.as_mut_slice();
1211 read_clamped_starts(
1212 starts,
1213 &self.operand_dims,
1214 &self.slice_sizes,
1215 clamped_starts,
1216 )?;
1217 let source_base =
1218 checked_strided_offset(operand.offset(), &self.operand_strides, clamped_starts)?;
1219 let mut state = replay.decode(0, source_base, dest.offset())?;
1220 let operand_data = operand.data();
1221
1222 for _ in 0..self.total {
1226 let value = unsafe { *operand_data.as_ptr().offset(state.source_offset) };
1228 unsafe { dest.write_at(state.dest_offset, value) };
1231 replay.advance(&mut state);
1232 }
1233 Ok(())
1234 }
1235
1236 fn execute_fused_window<T, I, W>(
1242 &self,
1243 dest: &mut W,
1244 operand: &RawStridedRef<'_, T>,
1245 starts: &RawStridedRef<'_, I>,
1246 window: &FusedPairLayout,
1247 exec: Exec<'_>,
1248 ) -> Result<()>
1249 where
1250 T: Copy + Send + Sync,
1251 I: GatherIndex,
1252 W: OverwriteWriter<T>,
1253 {
1254 let mut starts_storage = CoordScratch::new(self.operand_dims.len());
1255 let clamped_starts = starts_storage.as_mut_slice();
1256 read_clamped_starts(
1257 starts,
1258 &self.operand_dims,
1259 &self.slice_sizes,
1260 clamped_starts,
1261 )?;
1262 let source_base =
1263 checked_strided_offset(operand.offset(), &self.operand_strides, clamped_starts)?;
1264 let dest_base = dest.offset();
1265 let dest_ptr = unsafe { dest.data_ptr() }.cast::<MaybeUninit<T>>();
1267 let tiles = pair_tiles::<MaybeUninit<T>, T>(window);
1268 unsafe {
1279 replay_fused_raw(
1280 dest_ptr,
1281 dest_base,
1282 operand.data().as_ptr(),
1283 source_base,
1284 window,
1285 tiles.as_ref(),
1286 |slot: &mut MaybeUninit<T>, value: T| *slot = MaybeUninit::new(value),
1287 KernelClass::Copy.ns_per_element(),
1288 exec,
1289 );
1290 }
1291 Ok(())
1292 }
1293
1294 #[inline]
1295 fn uses_rank_one_contiguous_path(&self) -> bool {
1296 self.operand_dims.len() == 1 && self.operand_strides[0] == 1 && self.dest_strides[0] == 1
1297 }
1298
1299 fn execute_rank_one_contiguous<T, I, W>(
1300 &self,
1301 dest: &mut W,
1302 operand: &RawStridedRef<'_, T>,
1303 starts: &RawStridedRef<'_, I>,
1304 exec: Exec<'_>,
1305 ) -> Result<()>
1306 where
1307 T: Copy + Send + Sync,
1308 I: GatherIndex,
1309 W: OverwriteWriter<T>,
1310 {
1311 let mut clamped_starts = [0usize; 1];
1312 read_clamped_starts(
1313 starts,
1314 &self.operand_dims,
1315 &self.slice_sizes,
1316 &mut clamped_starts,
1317 )?;
1318 let source_start = checked_offset_add(operand.offset(), 1, clamped_starts[0])?;
1319 let source_start =
1320 usize::try_from(source_start).map_err(|_| StridedError::OffsetOverflow)?;
1321 let dest_start =
1322 usize::try_from(dest.offset()).map_err(|_| StridedError::OffsetOverflow)?;
1323 let source_end = source_start
1324 .checked_add(self.total)
1325 .ok_or(StridedError::OffsetOverflow)?;
1326 let source = operand
1327 .data()
1328 .get(source_start..source_end)
1329 .ok_or(StridedError::OffsetOverflow)?;
1330 let dest_ptr = unsafe { dest.data_ptr() };
1332 unsafe {
1343 crate::threading::copy_contiguous(
1346 source.as_ptr(),
1347 dest_ptr.add(dest_start),
1348 self.total,
1349 exec,
1350 );
1351 }
1352 Ok(())
1353 }
1354
1355 fn execute_parallel<T, I, W>(
1356 &self,
1357 dest: &mut W,
1358 operand: &RawStridedRef<'_, T>,
1359 starts: &RawStridedRef<'_, I>,
1360 exec: Exec<'_>,
1361 replay: &WindowReplay,
1362 ) -> Result<()>
1363 where
1364 T: Copy + Send + Sync,
1365 I: GatherIndex,
1366 W: OverwriteWriter<T>,
1367 {
1368 let mut clamped_starts: AxisVec<usize> = (0..self.operand_dims.len()).map(|_| 0).collect();
1369 read_clamped_starts(
1370 starts,
1371 &self.operand_dims,
1372 &self.slice_sizes,
1373 &mut clamped_starts,
1374 )?;
1375 let source_base =
1376 checked_strided_offset(operand.offset(), &self.operand_strides, &clamped_starts)?;
1377 let dest_base = dest.offset();
1378 let operand_ptr = crate::threading::SendPtr(operand.data().as_ptr() as *mut T);
1379 let dest_ptr = crate::threading::SendPtr(unsafe { dest.data_ptr() });
1381
1382 crate::threading::parallel_map_reduce(
1383 0..self.total,
1384 exec,
1385 &|range| {
1386 let mut state = replay.decode(range.start, source_base, dest_base)?;
1387 let operand_ptr = operand_ptr.as_const();
1388 let dest_ptr = dest_ptr.as_ptr();
1389
1390 for _ in range {
1394 unsafe {
1397 dest_ptr
1398 .offset(state.dest_offset)
1399 .write(operand_ptr.offset(state.source_offset).read());
1400 }
1401 replay.advance(&mut state);
1402 }
1403 Ok(())
1404 },
1405 &|left, right| left.and(right),
1406 )
1407 }
1408
1409 fn check_call<T, I, W>(
1410 &self,
1411 dest: &W,
1412 operand: &RawStridedRef<'_, T>,
1413 starts: &RawStridedRef<'_, I>,
1414 ) -> Result<()>
1415 where
1416 W: OverwriteWriter<T>,
1417 {
1418 if dest.dims() != &self.dest_dims[..]
1419 || dest.strides() != &self.dest_strides[..]
1420 || operand.dims() != &self.operand_dims[..]
1421 || operand.strides() != &self.operand_strides[..]
1422 || starts.dims() != &self.start_dims[..]
1423 || starts.strides() != &self.start_strides[..]
1424 {
1425 return Err(StridedError::PlanLayoutMismatch);
1426 }
1427 Ok(())
1428 }
1429}
1430
1431impl DynamicUpdateSlicePlan {
1432 #[allow(clippy::too_many_arguments)]
1453 pub fn compile(
1454 operand_dims: &[usize],
1455 operand_strides: &[isize],
1456 start_dims: &[usize],
1457 start_strides: &[isize],
1458 update_dims: &[usize],
1459 update_strides: &[isize],
1460 dest_dims: &[usize],
1461 dest_strides: &[isize],
1462 ) -> Result<Self> {
1463 if operand_dims.len() != operand_strides.len()
1464 || start_dims.len() != start_strides.len()
1465 || update_dims.len() != update_strides.len()
1466 || dest_dims.len() != dest_strides.len()
1467 {
1468 return Err(StridedError::StrideLengthMismatch);
1469 }
1470 if update_dims.len() != operand_dims.len() {
1471 return Err(StridedError::RankMismatch(
1472 update_dims.len(),
1473 operand_dims.len(),
1474 ));
1475 }
1476 validate_start_vector(start_dims, operand_dims.len())?;
1477 checked_total_len(operand_dims)?;
1478 checked_total_len(start_dims)?;
1479 let total = checked_total_len(update_dims)?;
1480 validate_layout_span(operand_dims, operand_strides)?;
1481 validate_layout_span(start_dims, start_strides)?;
1482 validate_layout_span(update_dims, update_strides)?;
1483 validate_layout_span(dest_dims, dest_strides)?;
1484 if dest_dims != operand_dims {
1485 return Err(StridedError::ShapeMismatch(
1486 dest_dims.to_vec(),
1487 operand_dims.to_vec(),
1488 ));
1489 }
1490 if !crate::layout_check::is_injective_layout(dest_dims, dest_strides) {
1491 return Err(StridedError::NonInjectiveOutputLayout);
1492 }
1493 validate_window_sizes(operand_dims, update_dims)?;
1494 let copy_plan = CopyPlan::compile(operand_dims, dest_strides, operand_strides)?;
1495 let replay = WindowReplay::compile(update_dims, update_strides, dest_strides)?;
1496
1497 Ok(Self {
1498 operand_dims: operand_dims.into(),
1499 operand_strides: operand_strides.into(),
1500 start_dims: start_dims.into(),
1501 start_strides: start_strides.into(),
1502 update_dims: update_dims.into(),
1503 update_strides: update_strides.into(),
1504 dest_dims: dest_dims.into(),
1505 dest_strides: dest_strides.into(),
1506 total,
1507 copy_plan,
1508 window: fuse_pair_layout(update_dims, dest_strides, update_strides),
1509 replay,
1510 })
1511 }
1512
1513 pub fn execute<T, I>(
1525 &self,
1526 dest: &mut RawStridedMut<'_, T>,
1527 operand: &RawStridedRef<'_, T>,
1528 update: &RawStridedRef<'_, T>,
1529 starts: &RawStridedRef<'_, I>,
1530 exec: Exec<'_>,
1531 ) -> Result<()>
1532 where
1533 T: Copy + Send + Sync,
1534 I: GatherIndex,
1535 {
1536 let mut exec = exec;
1537 self.check_call(dest, operand, update, starts)?;
1538 let window = self.preflight_update_window(dest, update, starts)?;
1539 self.copy_plan.execute(dest, operand, exec.reborrow())?;
1540 self.execute_update_with_writer(dest, update, &window, exec)
1541 }
1542
1543 pub(crate) fn execute_uninit<'a, T, I>(
1547 &self,
1548 dest: &'a mut RawStridedMut<'a, MaybeUninit<T>>,
1549 operand: &RawStridedRef<'_, T>,
1550 update: &RawStridedRef<'_, T>,
1551 starts: &RawStridedRef<'_, I>,
1552 exec: Exec<'_>,
1553 ) -> Result<()>
1554 where
1555 T: Copy + Send + Sync,
1556 I: GatherIndex,
1557 {
1558 self.check_call(dest, operand, update, starts)?;
1559 let window = self.preflight_update_window(dest, update, starts)?;
1560 self.copy_plan
1561 .execute_uninit_then(dest, operand, exec, |mut receipt, exec| {
1562 self.execute_update_with_writer(&mut receipt, update, &window, exec)
1563 })?
1564 }
1565
1566 fn preflight_update_window<'a, T, I, W>(
1568 &self,
1569 dest: &W,
1570 update: &'a RawStridedRef<'_, T>,
1571 starts: &RawStridedRef<'_, I>,
1572 ) -> Result<UpdateWindow<'a, T>>
1573 where
1574 T: Copy,
1575 I: GatherIndex,
1576 W: OverwriteWriter<T>,
1577 {
1578 if self.total == 0 {
1579 return Ok(UpdateWindow::Empty);
1580 }
1581 let mut starts_storage = CoordScratch::new(self.operand_dims.len());
1582 let clamped_starts = starts_storage.as_mut_slice();
1583 read_clamped_starts(
1584 starts,
1585 &self.operand_dims,
1586 &self.update_dims,
1587 clamped_starts,
1588 )?;
1589 let dest_base = checked_strided_offset(dest.offset(), &self.dest_strides, clamped_starts)?;
1590 self.replay.source_span.covers(update.offset())?;
1593 self.replay.dest_span.covers(dest_base)?;
1594 if self.uses_rank_one_contiguous_path() {
1595 let update_start =
1596 usize::try_from(update.offset()).map_err(|_| StridedError::OffsetOverflow)?;
1597 let dest_start =
1598 usize::try_from(dest_base).map_err(|_| StridedError::OffsetOverflow)?;
1599 let update_end = update_start
1600 .checked_add(self.total)
1601 .ok_or(StridedError::OffsetOverflow)?;
1602 let run = update
1603 .data()
1604 .get(update_start..update_end)
1605 .ok_or(StridedError::OffsetOverflow)?;
1606 return Ok(UpdateWindow::RankOne {
1607 update: run,
1608 dest_start,
1609 });
1610 }
1611 Ok(UpdateWindow::Replay { dest_base })
1612 }
1613
1614 fn execute_update_with_writer<T, W>(
1615 &self,
1616 dest: &mut W,
1617 update: &RawStridedRef<'_, T>,
1618 window: &UpdateWindow<'_, T>,
1619 exec: Exec<'_>,
1620 ) -> Result<()>
1621 where
1622 T: Copy + Send + Sync,
1623 W: OverwriteWriter<T>,
1624 {
1625 let dest_base = match *window {
1626 UpdateWindow::Empty => return Ok(()),
1627 UpdateWindow::RankOne { update, dest_start } => {
1628 return self.execute_rank_one_contiguous(dest, update, dest_start, exec)
1629 }
1630 UpdateWindow::Replay { dest_base } => dest_base,
1631 };
1632 if let Some(fused) = &self.window {
1633 return self.execute_fused_window(dest, update, dest_base, fused, exec);
1634 }
1635 let replay = &self.replay;
1636 let exec = crate::cost::for_len_tree(exec, KernelClass::Copy, self.total);
1637 if !exec.is_serial() {
1638 return self.execute_update_parallel(dest, update, dest_base, exec);
1639 }
1640
1641 let mut state = replay.start(update.offset(), dest_base);
1642 let update_data = update.data();
1643
1644 for _ in 0..self.total {
1648 let value = unsafe { *update_data.as_ptr().offset(state.source_offset) };
1650 unsafe { dest.write_at(state.dest_offset, value) };
1653 replay.advance(&mut state);
1654 }
1655 Ok(())
1656 }
1657
1658 fn execute_fused_window<T, W>(
1661 &self,
1662 dest: &mut W,
1663 update: &RawStridedRef<'_, T>,
1664 dest_base: isize,
1665 window: &FusedPairLayout,
1666 exec: Exec<'_>,
1667 ) -> Result<()>
1668 where
1669 T: Copy + Send + Sync,
1670 W: OverwriteWriter<T>,
1671 {
1672 let dest_ptr = unsafe { dest.data_ptr() }.cast::<MaybeUninit<T>>();
1674 let tiles = pair_tiles::<MaybeUninit<T>, T>(window);
1675 unsafe {
1684 replay_fused_raw(
1685 dest_ptr,
1686 dest_base,
1687 update.data().as_ptr(),
1688 update.offset(),
1689 window,
1690 tiles.as_ref(),
1691 |slot: &mut MaybeUninit<T>, value: T| *slot = MaybeUninit::new(value),
1692 KernelClass::Copy.ns_per_element(),
1693 exec,
1694 );
1695 }
1696 Ok(())
1697 }
1698
1699 #[inline]
1700 fn uses_rank_one_contiguous_path(&self) -> bool {
1701 self.operand_dims.len() == 1
1702 && self.operand_strides[0] == 1
1703 && self.update_strides[0] == 1
1704 && self.dest_strides[0] == 1
1705 }
1706
1707 fn execute_rank_one_contiguous<T, W>(
1708 &self,
1709 dest: &mut W,
1710 update: &[T],
1711 dest_start: usize,
1712 exec: Exec<'_>,
1713 ) -> Result<()>
1714 where
1715 T: Copy + Send + Sync,
1716 W: OverwriteWriter<T>,
1717 {
1718 let dest_ptr = unsafe { dest.data_ptr() };
1720 unsafe {
1735 crate::threading::copy_contiguous(
1738 update.as_ptr(),
1739 dest_ptr.add(dest_start),
1740 self.total,
1741 exec,
1742 );
1743 }
1744 Ok(())
1745 }
1746
1747 fn execute_update_parallel<T, W>(
1748 &self,
1749 dest: &mut W,
1750 update: &RawStridedRef<'_, T>,
1751 dest_base: isize,
1752 exec: Exec<'_>,
1753 ) -> Result<()>
1754 where
1755 T: Copy + Send + Sync,
1756 W: OverwriteWriter<T>,
1757 {
1758 let replay = &self.replay;
1759 let source_base = update.offset();
1760 let update_ptr = crate::threading::SendPtr(update.data().as_ptr() as *mut T);
1761 let dest_ptr = crate::threading::SendPtr(unsafe { dest.data_ptr() });
1763
1764 crate::threading::parallel_map_reduce(
1765 0..self.total,
1766 exec,
1767 &|range| {
1768 let mut state = replay.decode(range.start, source_base, dest_base)?;
1769 let update_ptr = update_ptr.as_const();
1770 let dest_ptr = dest_ptr.as_ptr();
1771
1772 for _ in range {
1777 unsafe {
1780 dest_ptr
1781 .offset(state.dest_offset)
1782 .write(update_ptr.offset(state.source_offset).read());
1783 }
1784 replay.advance(&mut state);
1785 }
1786 Ok(())
1787 },
1788 &|left, right| left.and(right),
1789 )
1790 }
1791
1792 fn check_call<T, I, W>(
1793 &self,
1794 dest: &W,
1795 operand: &RawStridedRef<'_, T>,
1796 update: &RawStridedRef<'_, T>,
1797 starts: &RawStridedRef<'_, I>,
1798 ) -> Result<()>
1799 where
1800 W: OverwriteWriter<T>,
1801 {
1802 if dest.dims() != &self.dest_dims[..]
1803 || dest.strides() != &self.dest_strides[..]
1804 || operand.dims() != &self.operand_dims[..]
1805 || operand.strides() != &self.operand_strides[..]
1806 || update.dims() != &self.update_dims[..]
1807 || update.strides() != &self.update_strides[..]
1808 || starts.dims() != &self.start_dims[..]
1809 || starts.strides() != &self.start_strides[..]
1810 {
1811 return Err(StridedError::PlanLayoutMismatch);
1812 }
1813 Ok(())
1814 }
1815}
1816
1817impl ScatterPlan {
1818 #[allow(clippy::too_many_arguments)]
1841 pub fn compile(
1842 operand_dims: &[usize],
1843 operand_strides: &[isize],
1844 index_dims: &[usize],
1845 index_strides: &[isize],
1846 update_dims: &[usize],
1847 update_strides: &[isize],
1848 dest_dims: &[usize],
1849 dest_strides: &[isize],
1850 spec: ScatterSpec,
1851 ) -> Result<Self> {
1852 if operand_dims.len() != operand_strides.len()
1853 || index_dims.len() != index_strides.len()
1854 || update_dims.len() != update_strides.len()
1855 || dest_dims.len() != dest_strides.len()
1856 {
1857 return Err(StridedError::StrideLengthMismatch);
1858 }
1859 checked_total_len(operand_dims)?;
1860 checked_total_len(index_dims)?;
1861 checked_total_len(update_dims)?;
1862 if dest_dims != operand_dims {
1863 return Err(StridedError::ShapeMismatch(
1864 dest_dims.to_vec(),
1865 operand_dims.to_vec(),
1866 ));
1867 }
1868 if !crate::layout_check::is_injective_layout(dest_dims, dest_strides) {
1869 return Err(StridedError::NonInjectiveOutputLayout);
1870 }
1871
1872 let operand_rank = operand_dims.len();
1873 validate_unique_axes(&spec.inserted_window_dims, operand_rank)?;
1874 validate_unique_axes(&spec.scatter_dims_to_operand_dims, operand_rank)?;
1875 if spec.index_vector_dim > index_dims.len() {
1876 return Err(StridedError::InvalidAxis {
1877 axis: spec.index_vector_dim,
1878 rank: index_dims.len() + 1,
1879 });
1880 }
1881 let index_vector_size = if spec.index_vector_dim == index_dims.len() {
1882 1
1883 } else {
1884 index_dims[spec.index_vector_dim]
1885 };
1886 if index_vector_size != spec.scatter_dims_to_operand_dims.len() {
1887 return Err(StridedError::RankMismatch(
1888 index_vector_size,
1889 spec.scatter_dims_to_operand_dims.len(),
1890 ));
1891 }
1892
1893 let batch_shape = index_batch_shape(index_dims, spec.index_vector_dim);
1894 let window_dims = operand_window_dims(operand_rank, &spec.inserted_window_dims);
1895 if spec.update_window_dims.len() != window_dims.len() {
1896 return Err(StridedError::RankMismatch(
1897 spec.update_window_dims.len(),
1898 window_dims.len(),
1899 ));
1900 }
1901
1902 let update_rank = update_dims.len();
1903 let expected_batch_rank = update_rank
1904 .checked_sub(spec.update_window_dims.len())
1905 .ok_or(StridedError::RankMismatch(
1906 spec.update_window_dims.len(),
1907 update_rank,
1908 ))?;
1909 if expected_batch_rank != batch_shape.len() {
1910 return Err(StridedError::RankMismatch(
1911 expected_batch_rank,
1912 batch_shape.len(),
1913 ));
1914 }
1915 validate_unique_axes(&spec.update_window_dims, update_rank)?;
1916
1917 let mut is_update_window_dim: AxisVec<bool> = (0..update_rank).map(|_| false).collect();
1918 for &axis in &spec.update_window_dims {
1919 is_update_window_dim[axis] = true;
1920 }
1921
1922 let mut batch_axis = 0usize;
1923 for axis in 0..update_rank {
1924 if !is_update_window_dim[axis] {
1925 if update_dims[axis] != batch_shape[batch_axis] {
1926 return Err(StridedError::ShapeMismatch(
1927 update_dims.to_vec(),
1928 expected_scatter_update_shape(&batch_shape, &spec, update_dims).to_vec(),
1929 ));
1930 }
1931 batch_axis += 1;
1932 }
1933 }
1934
1935 let mut window_shape: AxisVec<usize> = (0..operand_rank).map(|_| 1).collect();
1936 let mut window_shape_updates: AxisVec<usize> =
1937 AxisVec::with_capacity(spec.update_window_dims.len());
1938 for (pos, &update_axis) in spec.update_window_dims.iter().enumerate() {
1939 let dim = update_dims[update_axis];
1940 window_shape_updates.push(dim);
1941 window_shape[window_dims[pos]] = dim;
1942 }
1943 validate_window_sizes(operand_dims, &window_shape)?;
1944
1945 let batch_elems = checked_total_len(&batch_shape)?;
1946 let window_elems = checked_total_len(&window_shape_updates)?;
1947 let copy_plan = CopyPlan::compile(operand_dims, dest_strides, operand_strides)?;
1948 let replay = ScatterReplay::compile(
1949 &batch_shape,
1950 index_dims,
1951 index_strides,
1952 spec.index_vector_dim,
1953 spec.scatter_dims_to_operand_dims.len(),
1954 update_dims,
1955 update_strides,
1956 &spec.update_window_dims,
1957 &is_update_window_dim,
1958 &window_shape_updates,
1959 &window_dims,
1960 dest_strides,
1961 )?;
1962
1963 Ok(Self {
1964 operand_dims: operand_dims.into(),
1965 operand_strides: operand_strides.into(),
1966 index_dims: index_dims.into(),
1967 index_strides: index_strides.into(),
1968 update_dims: update_dims.into(),
1969 update_strides: update_strides.into(),
1970 dest_dims: dest_dims.into(),
1971 dest_strides: dest_strides.into(),
1972 spec,
1973 window_shape,
1974 batch_elems,
1975 window_elems,
1976 copy_plan,
1977 replay,
1978 })
1979 }
1980
1981 #[inline(always)]
2019 pub fn execute<T, I>(
2020 &self,
2021 dest: &mut RawStridedMut<'_, T>,
2022 operand: &RawStridedRef<'_, T>,
2023 scatter_indices: &RawStridedRef<'_, I>,
2024 updates: &RawStridedRef<'_, T>,
2025 exec: Exec<'_>,
2026 ) -> Result<()>
2027 where
2028 T: ScatterScalar,
2029 I: GatherIndex,
2030 {
2031 self.execute_with_combine(
2032 dest,
2033 operand,
2034 scatter_indices,
2035 updates,
2036 <T as ScatterScalar>::wrapping_add,
2037 exec,
2038 )
2039 }
2040
2041 pub fn execute_with_combine<T, I>(
2053 &self,
2054 dest: &mut RawStridedMut<'_, T>,
2055 operand: &RawStridedRef<'_, T>,
2056 scatter_indices: &RawStridedRef<'_, I>,
2057 updates: &RawStridedRef<'_, T>,
2058 combine: fn(T, T) -> T,
2059 exec: Exec<'_>,
2060 ) -> Result<()>
2061 where
2062 T: Copy + Send + Sync,
2063 I: GatherIndex,
2064 {
2065 self.check_call(dest, operand, scatter_indices, updates)?;
2066 self.copy_plan.execute(dest, operand, exec)?;
2067 self.execute_updates(dest, scatter_indices, updates, combine)
2068 }
2069
2070 pub(crate) fn execute_uninit<'a, T, I>(
2073 &self,
2074 dest: &'a mut RawStridedMut<'a, MaybeUninit<T>>,
2075 operand: &RawStridedRef<'_, T>,
2076 scatter_indices: &RawStridedRef<'_, I>,
2077 updates: &RawStridedRef<'_, T>,
2078 combine: fn(T, T) -> T,
2079 exec: Exec<'_>,
2080 ) -> Result<()>
2081 where
2082 T: Copy + Send + Sync,
2083 I: GatherIndex,
2084 {
2085 self.check_call(dest, operand, scatter_indices, updates)?;
2086 self.copy_plan
2087 .execute_uninit_then(dest, operand, exec, |mut receipt, _| {
2088 self.execute_updates(&mut receipt, scatter_indices, updates, combine)
2089 })?
2090 }
2091
2092 #[inline(always)]
2093 fn execute_updates<T, I, W, F>(
2094 &self,
2095 dest: &mut W,
2096 scatter_indices: &RawStridedRef<'_, I>,
2097 updates: &RawStridedRef<'_, T>,
2098 combine: F,
2099 ) -> Result<()>
2100 where
2101 T: Copy + Send + Sync,
2102 I: GatherIndex,
2103 W: ReadModifyWrite<T>,
2104 F: Fn(T, T) -> T + Copy,
2105 {
2106 if self.batch_elems == 0 || self.window_elems == 0 {
2107 return Ok(());
2108 }
2109 if self.uses_rank_one_scalar_update_path() {
2110 return self.execute_rank_one_scalar_updates(dest, scatter_indices, updates, combine);
2111 }
2112 self.execute_generic_updates(dest, scatter_indices, updates, combine)
2113 }
2114
2115 #[inline(never)]
2116 fn execute_generic_updates<T, I, W, F>(
2117 &self,
2118 dest: &mut W,
2119 scatter_indices: &RawStridedRef<'_, I>,
2120 updates: &RawStridedRef<'_, T>,
2121 combine: F,
2122 ) -> Result<()>
2123 where
2124 T: Copy + Send + Sync,
2125 I: GatherIndex,
2126 W: ReadModifyWrite<T>,
2127 F: Fn(T, T) -> T + Copy,
2128 {
2129 let replay = &self.replay;
2132
2133 let mut operand_base_storage = CoordScratch::new(self.operand_dims.len());
2134 let operand_base = operand_base_storage.as_mut_slice();
2135 let mut batch_state = replay
2136 .batch
2137 .decode(0, scatter_indices.offset(), updates.offset())?;
2138 let index_data = scatter_indices.data();
2139 let update_data = updates.data();
2140
2141 for _ in 0..self.batch_elems {
2144 operand_base.fill(0);
2145 for (&component_offset, &operand_axis) in replay
2146 .index_component_offsets
2147 .iter()
2148 .zip(self.spec.scatter_dims_to_operand_dims.iter())
2149 {
2150 let index_offset = batch_state
2151 .source_offset
2152 .checked_add(component_offset)
2153 .ok_or(StridedError::OffsetOverflow)?;
2154 let start = unsafe { *index_data.as_ptr().offset(index_offset) }.to_i64();
2157 operand_base[operand_axis] = clamp_window_start(
2158 start,
2159 self.operand_dims[operand_axis],
2160 self.window_shape[operand_axis],
2161 );
2162 }
2163
2164 let dest_base = checked_strided_offset(dest.offset(), dest.strides(), operand_base)?;
2165 let mut window_state = replay
2166 .window
2167 .decode(0, batch_state.dest_offset, dest_base)?;
2168 for _ in 0..self.window_elems {
2169 let value = unsafe { *update_data.as_ptr().offset(window_state.source_offset) };
2172 unsafe { dest.add_at(window_state.dest_offset, value, combine) };
2173 replay.window.advance(&mut window_state);
2174 }
2175 replay.batch.advance(&mut batch_state);
2176 }
2177 Ok(())
2178 }
2179
2180 fn uses_rank_one_scalar_update_path(&self) -> bool {
2181 self.operand_dims.len() == 1
2182 && self.index_dims.len() == 2
2183 && self.update_dims.len() == 1
2184 && self.dest_dims.len() == 1
2185 && self.operand_strides[0] == 1
2186 && self.index_strides[0] == 1
2187 && self.update_strides[0] == 1
2188 && self.dest_strides[0] == 1
2189 && self.index_dims[1] == 1
2190 && self.spec.update_window_dims.is_empty()
2191 && self.spec.inserted_window_dims.as_slice() == [0]
2192 && self.spec.scatter_dims_to_operand_dims.as_slice() == [0]
2193 && self.spec.index_vector_dim == 1
2194 && self.window_elems == 1
2195 }
2196
2197 #[inline(always)]
2198 fn execute_rank_one_scalar_updates<T, I, W, F>(
2199 &self,
2200 dest: &mut W,
2201 scatter_indices: &RawStridedRef<'_, I>,
2202 updates: &RawStridedRef<'_, T>,
2203 combine: F,
2204 ) -> Result<()>
2205 where
2206 T: Copy,
2207 I: GatherIndex,
2208 W: ReadModifyWrite<T>,
2209 F: Fn(T, T) -> T + Copy,
2210 {
2211 let mut index_offset = scatter_indices.offset();
2212 let mut update_offset = updates.offset();
2213 let dest_offset = dest.offset();
2214 let index_data = scatter_indices.data();
2215 let update_data = updates.data();
2216 let dest_ptr = unsafe { dest.data_ptr() };
2218
2219 #[allow(clippy::explicit_counter_loop)]
2223 for _ in 0..self.batch_elems {
2224 unsafe {
2227 let start = (*index_data.as_ptr().offset(index_offset)).to_i64();
2228 let output_offset =
2229 dest_offset + clamp_window_start(start, self.operand_dims[0], 1) as isize;
2230 let output = dest_ptr.offset(output_offset);
2231 output.write(combine(
2232 output.read(),
2233 *update_data.as_ptr().offset(update_offset),
2234 ));
2235 }
2236 index_offset += 1;
2237 update_offset += 1;
2238 }
2239 Ok(())
2240 }
2241
2242 fn check_call<T, I, W>(
2243 &self,
2244 dest: &W,
2245 operand: &RawStridedRef<'_, T>,
2246 scatter_indices: &RawStridedRef<'_, I>,
2247 updates: &RawStridedRef<'_, T>,
2248 ) -> Result<()>
2249 where
2250 W: OverwriteWriter<T>,
2251 {
2252 if dest.dims() != &self.dest_dims[..]
2253 || dest.strides() != &self.dest_strides[..]
2254 || operand.dims() != &self.operand_dims[..]
2255 || operand.strides() != &self.operand_strides[..]
2256 || scatter_indices.dims() != &self.index_dims[..]
2257 || scatter_indices.strides() != &self.index_strides[..]
2258 || updates.dims() != &self.update_dims[..]
2259 || updates.strides() != &self.update_strides[..]
2260 {
2261 return Err(StridedError::PlanLayoutMismatch);
2262 }
2263 Ok(())
2264 }
2265}
2266
2267fn validate_unique_axes(axes: &[usize], rank: usize) -> Result<()> {
2268 let mut seen: InlineVec<bool> = InlineVec::new();
2271 seen.resize(rank, false);
2272 for &axis in axes {
2273 if axis >= rank {
2274 return Err(StridedError::InvalidAxis { axis, rank });
2275 }
2276 if seen[axis] {
2277 return Err(StridedError::InvalidAxis { axis, rank });
2278 }
2279 seen[axis] = true;
2280 }
2281 Ok(())
2282}
2283
2284fn validate_start_vector(start_dims: &[usize], operand_rank: usize) -> Result<()> {
2285 if start_dims.len() != 1 {
2286 return Err(StridedError::RankMismatch(start_dims.len(), 1));
2287 }
2288 if start_dims[0] != operand_rank {
2289 return Err(StridedError::RankMismatch(start_dims[0], operand_rank));
2290 }
2291 Ok(())
2292}
2293
2294fn validate_window_sizes(operand_dims: &[usize], window_sizes: &[usize]) -> Result<()> {
2295 if operand_dims.len() != window_sizes.len() {
2296 return Err(StridedError::RankMismatch(
2297 window_sizes.len(),
2298 operand_dims.len(),
2299 ));
2300 }
2301 for (axis, (&window, &dim)) in window_sizes.iter().zip(operand_dims.iter()).enumerate() {
2302 if window > dim {
2303 return Err(StridedError::InvalidAxis {
2304 axis,
2305 rank: operand_dims.len(),
2306 });
2307 }
2308 }
2309 Ok(())
2310}
2311
2312fn read_clamped_starts<I>(
2313 starts: &RawStridedRef<'_, I>,
2314 operand_dims: &[usize],
2315 window_sizes: &[usize],
2316 out: &mut [usize],
2317) -> Result<()>
2318where
2319 I: GatherIndex,
2320{
2321 debug_assert_eq!(operand_dims.len(), window_sizes.len());
2322 debug_assert_eq!(operand_dims.len(), out.len());
2323 for axis in 0..operand_dims.len() {
2324 let offset = checked_offset_add(starts.offset(), starts.strides()[0], axis)?;
2325 let start = unsafe { *starts.data().as_ptr().offset(offset) }.to_i64();
2326 out[axis] = clamp_window_start(start, operand_dims[axis], window_sizes[axis]);
2327 }
2328 Ok(())
2329}
2330
2331#[inline]
2332fn clamp_window_start(start: i64, dim_size: usize, window_size: usize) -> usize {
2333 let max_start = dim_size.saturating_sub(window_size) as i64;
2334 start.clamp(0, max_start) as usize
2335}
2336
2337fn expected_scatter_update_shape(
2338 batch_shape: &[usize],
2339 spec: &ScatterSpec,
2340 update_dims: &[usize],
2341) -> AxisVec<usize> {
2342 let mut expected: AxisVec<usize> = AxisVec::with_capacity(update_dims.len());
2343 let mut batch_axis = 0usize;
2344 for (axis, &dim) in update_dims.iter().enumerate() {
2345 if spec.update_window_dims.contains(&axis) {
2346 expected.push(dim);
2347 } else {
2348 expected.push(batch_shape[batch_axis]);
2349 batch_axis += 1;
2350 }
2351 }
2352 expected
2353}
2354
2355fn operand_window_dims(rank: usize, collapsed_slice_dims: &[usize]) -> AxisVec<usize> {
2356 (0..rank)
2357 .filter(|axis| !collapsed_slice_dims.contains(axis))
2358 .collect()
2359}
2360
2361fn index_batch_shape(index_dims: &[usize], index_vector_dim: usize) -> AxisVec<usize> {
2362 if index_vector_dim == index_dims.len() {
2363 return index_dims.into();
2364 }
2365 index_dims
2366 .iter()
2367 .enumerate()
2368 .filter_map(|(axis, &dim)| (axis != index_vector_dim).then_some(dim))
2369 .collect()
2370}
2371
2372fn validate_layout_span(dims: &[usize], strides: &[isize]) -> Result<OffsetSpan> {
2374 if dims.len() != strides.len() {
2375 return Err(StridedError::StrideLengthMismatch);
2376 }
2377 let mut span = OffsetSpan::default();
2378 for (&dim, &stride) in dims.iter().zip(strides.iter()) {
2379 let last =
2380 isize::try_from(dim.saturating_sub(1)).map_err(|_| StridedError::OffsetOverflow)?;
2381 let extent = stride
2382 .checked_mul(last)
2383 .ok_or(StridedError::OffsetOverflow)?;
2384 if extent < 0 {
2385 span.min = span
2386 .min
2387 .checked_add(extent)
2388 .ok_or(StridedError::OffsetOverflow)?;
2389 } else {
2390 span.max = span
2391 .max
2392 .checked_add(extent)
2393 .ok_or(StridedError::OffsetOverflow)?;
2394 }
2395 }
2396 Ok(span)
2397}
2398
2399fn checked_replay_reset(dim: usize, step: isize) -> Result<isize> {
2400 if dim == 0 {
2401 return Ok(0);
2402 }
2403 let last = isize::try_from(dim - 1).map_err(|_| StridedError::OffsetOverflow)?;
2404 step.checked_mul(last)
2405 .and_then(isize::checked_neg)
2406 .ok_or(StridedError::OffsetOverflow)
2407}
2408
2409fn checked_total_len(dims: &[usize]) -> Result<usize> {
2410 if dims.is_empty() {
2411 return Ok(1);
2412 }
2413 dims.iter()
2414 .try_fold(1usize, |acc, &dim| acc.checked_mul(dim))
2415 .ok_or(StridedError::OffsetOverflow)
2416}
2417
2418fn checked_strided_offset(base: isize, strides: &[isize], index: &[usize]) -> Result<isize> {
2419 let mut offset = base;
2420 for (&stride, &coord) in strides.iter().zip(index.iter()) {
2421 offset = checked_offset_add(offset, stride, coord)?;
2422 }
2423 Ok(offset)
2424}
2425
2426fn checked_offset_add(base: isize, stride: isize, coord: usize) -> Result<isize> {
2427 let coord = isize::try_from(coord).map_err(|_| StridedError::OffsetOverflow)?;
2428 let scaled = stride
2429 .checked_mul(coord)
2430 .ok_or(StridedError::OffsetOverflow)?;
2431 base.checked_add(scaled).ok_or(StridedError::OffsetOverflow)
2432}
2433
2434struct CoordScratch {
2435 inline: [usize; RAW_FUSED_RANK_LIMIT],
2436 heap: Option<Vec<usize>>,
2437 len: usize,
2438}
2439
2440impl CoordScratch {
2441 fn new(len: usize) -> Self {
2442 if len <= RAW_FUSED_RANK_LIMIT {
2443 Self {
2444 inline: [0; RAW_FUSED_RANK_LIMIT],
2445 heap: None,
2446 len,
2447 }
2448 } else {
2449 Self {
2450 inline: [0; RAW_FUSED_RANK_LIMIT],
2451 heap: Some(vec![0; len]),
2452 len,
2453 }
2454 }
2455 }
2456
2457 fn as_mut_slice(&mut self) -> &mut [usize] {
2458 match &mut self.heap {
2459 Some(heap) => heap,
2460 None => &mut self.inline[..self.len],
2461 }
2462 }
2463}
2464
2465#[cfg(test)]
2466#[path = "gather_plan/tests/tests.rs"]
2467mod tests;
2468
2469#[cfg(test)]
2470#[path = "gather_plan/tests/parallel_tests.rs"]
2471mod parallel_tests;