strided_perm/copy.rs
1//! Copy/permutation operations on strided views.
2
3use crate::fuse::FusionPlanError;
4use crate::hptt::{build_permute_plan, execute_permute_blocked, ConjStore, PlainStore, Store};
5use strided_view::{ElementOpApply, Result, StridedError, StridedView, StridedViewMut};
6use threadteam::Exec;
7
8/// Map a permutation planning failure onto the shared view error vocabulary.
9///
10/// Rank and shape are validated before planning, so a length mismatch cannot
11/// reach this point; it still maps to a typed error instead of a panic. An
12/// oversized (typically stride-0 broadcast) extent whose fused product cannot
13/// be represented is reported as an offset overflow (issue #263).
14fn plan_error(err: FusionPlanError) -> StridedError {
15 match err {
16 FusionPlanError::LengthMismatch { .. } => StridedError::StrideLengthMismatch,
17 FusionPlanError::DimensionOverflow => StridedError::OffsetOverflow,
18 }
19}
20
21fn total_len(dims: &[usize]) -> usize {
22 dims.iter().product()
23}
24
25/// Check if all strides indicate contiguous column-major or row-major layout.
26fn is_both_contiguous(dims: &[usize], dst_strides: &[isize], src_strides: &[isize]) -> bool {
27 if dims.is_empty() {
28 return true;
29 }
30
31 // Check col-major for both
32 let mut expected = 1isize;
33 let mut col_ok = true;
34 for (&d, (&ds, &ss)) in dims.iter().zip(dst_strides.iter().zip(src_strides.iter())) {
35 if d <= 1 {
36 continue;
37 }
38 if ds != expected || ss != expected {
39 col_ok = false;
40 break;
41 }
42 expected = expected.saturating_mul(d as isize);
43 }
44 if col_ok {
45 return true;
46 }
47
48 // Check row-major for both
49 let mut expected = 1isize;
50 let mut row_ok = true;
51 for (&d, (&ds, &ss)) in dims
52 .iter()
53 .rev()
54 .zip(dst_strides.iter().rev().zip(src_strides.iter().rev()))
55 {
56 if d <= 1 {
57 continue;
58 }
59 if ds != expected || ss != expected {
60 row_ok = false;
61 break;
62 }
63 expected = expected.saturating_mul(d as isize);
64 }
65 row_ok
66}
67
68/// The validated raw geometry of one copy: the shared dims, both stride
69/// runs and the two origins. `U` is the destination element type: `T` for
70/// an initialized destination, `MaybeUninit<T>` for a fresh one.
71struct RawCopy<'a, T, U> {
72 dims: &'a [usize],
73 dst_strides: &'a [isize],
74 src_strides: &'a [isize],
75 dst: *mut U,
76 src: *const T,
77}
78
79/// Validates rank and shape and extracts the raw geometry; `None` for a
80/// zero-sized copy, which has nothing to write.
81///
82/// A zero-sized view validates without its other extents or strides forming
83/// an in-range product, so neither the contiguous fast path nor the
84/// permutation planner may see it.
85fn prepare<'a, T, U>(
86 dest: &'a mut StridedViewMut<U>,
87 src: &'a StridedView<T>,
88) -> Result<Option<RawCopy<'a, T, U>>> {
89 let dst_dims = dest.dims();
90 let src_dims = src.dims();
91 if dst_dims.len() != src_dims.len() {
92 return Err(StridedError::RankMismatch(dst_dims.len(), src_dims.len()));
93 }
94 if dst_dims != src_dims {
95 return Err(StridedError::ShapeMismatch(
96 dst_dims.to_vec(),
97 src_dims.to_vec(),
98 ));
99 }
100 if dst_dims.contains(&0) {
101 return Ok(None);
102 }
103 Ok(Some(RawCopy {
104 dims: dst_dims,
105 dst_strides: dest.strides(),
106 src_strides: src.strides(),
107 dst: dest.as_mut_ptr(),
108 src: src.ptr(),
109 }))
110}
111
112/// The copy over validated raw geometry, run within the budget of `exec`.
113///
114/// # Safety
115///
116/// `raw.dst` must be valid for writes of `T` at every destination offset and
117/// `raw.src` valid for reads of initialized `T` at every source offset; the
118/// two ranges must not overlap. Every store goes through raw pointers, so the
119/// destination may be uninitialized storage.
120unsafe fn copy_raw<T: Copy + Send + Sync + 'static, U, S: Store<T>>(
121 raw: RawCopy<'_, T, U>,
122 exec: Exec<'_>,
123) -> Result<()> {
124 let dst_ptr = raw.dst.cast::<T>();
125 // The width is the token's decision: the serial time of the copy against the
126 // dispatch cost of the one section the engine opens (`for_ranges`).
127 let exec = match raw.dims.iter().try_fold(1usize, |n, &d| n.checked_mul(d)) {
128 Some(n) => {
129 let estimate =
130 std::time::Duration::from_secs_f64(n as f64 * crate::copy_ns_per_element() * 1e-9);
131 let width = exec.width_for(estimate, 1);
132 exec.limit(width)
133 }
134 // An overflowing count is reported by planning below; run it serially.
135 None => exec.limit(std::num::NonZeroUsize::MIN),
136 };
137 // Fast path: both contiguous. A contiguous layout is injective by
138 // construction, so it skips the validation below. A conjugating store must
139 // not `memcpy`: it falls through to the planner, which reduces a contiguous
140 // layout to `ConstStride1` with unit strides and the store's element loop.
141 if S::PLAIN && is_both_contiguous(raw.dims, raw.dst_strides, raw.src_strides) {
142 let len = total_len(raw.dims);
143 if exec.is_serial() {
144 // SAFETY: `prepare` (copy.rs:85) proved `dims`, the strides and the two
145 // origins describe the same shape, and each view's construction proved
146 // that its reachable offsets stay inside its own slice:
147 // `validate_bounds` (strided-view/src/view.rs:187), or for a
148 // `StridedArray` view the dense layout argued at `StridedArray::view`
149 // (strided-view/src/view.rs:1461). A contiguous layout
150 // reaches exactly `total_len(dims)` consecutive elements from that
151 // origin, so both ranges are live for `len` elements; the caller holds
152 // `&mut StridedViewMut` against a shared `&StridedView`, so they do not
153 // overlap.
154 unsafe { std::ptr::copy_nonoverlapping(raw.src, dst_ptr, len) };
155 } else {
156 let src_addr = raw.src as usize;
157 let dst_addr = dst_ptr as usize;
158 exec.for_ranges(len, std::num::NonZeroUsize::MIN, |range| {
159 // SAFETY: the pointers are rebuilt from `as usize` casts of the
160 // live `raw.src`/`dst_ptr`, which expose their provenance, so the
161 // casts back recover it. `range` is a disjoint subrange of
162 // `0..len`, so both
163 // `.add(range.start)` pointers stay within the two live `len`-element
164 // contiguous ranges justified above; the subranges are disjoint, and
165 // raw stores are valid for the uninitialized `U` destination.
166 unsafe {
167 std::ptr::copy_nonoverlapping(
168 (src_addr as *const T).add(range.start),
169 (dst_addr as *mut T).add(range.start),
170 range.len(),
171 );
172 }
173 });
174 }
175 return Ok(());
176 }
177
178 // HPTT-inspired blocked permutation. Planning runs before the injectivity
179 // check so an unrepresentable layout keeps reporting `OffsetOverflow`
180 // (issue #263) even when its destination is also non-injective; planning
181 // only builds metadata and writes nothing.
182 let elem_size = std::mem::size_of::<T>();
183 let plan = build_permute_plan(raw.dims, raw.src_strides, raw.dst_strides, elem_size)
184 .map_err(plan_error)?;
185 // A non-injective destination maps distinct logical elements onto one
186 // offset, so the unsafe write loop would produce overlapping writes (and a
187 // data race when `exec` fans out). This matches the sibling output-writing
188 // APIs (issue #281). The check is global over the destination, so two
189 // worker partitions (disjoint logical positions) can never write one
190 // offset; no extra per-partition separation proof is needed.
191 if !strided_view::is_injective_layout(raw.dims, raw.dst_strides) {
192 return Err(StridedError::NonInjectiveOutputLayout);
193 }
194 // SAFETY: `execute_permute_blocked` (execute.rs:131) needs `src`/`dst` valid at
195 // every offset of the layout `plan` was built from, no overlap, no other
196 // access to the destination, and an injective destination when `exec` fans
197 // out, over a layout with no zero extent. `plan` is `build_permute_plan`
198 // over exactly `raw.dims` and the two stride runs, and `raw` is a
199 // `RawCopy`, which only `prepare` builds and only after returning `None`
200 // for a zero extent (copy.rs:100); validity and non-overlap are this function's `# Safety`
201 // (copy.rs:116); the callers hold `&mut StridedViewMut` for the whole call, so
202 // nothing else touches the destination; injectivity was checked just
203 // above. `dst_ptr` is `raw.dst` cast from `U` to `T`, the same layout for
204 // `U = T` and `U = MaybeUninit<T>`, and the engine only stores through it.
205 execute_permute_blocked::<T, S>(raw.src, dst_ptr, &plan, exec);
206 Ok(())
207}
208
209/// Copy elements from source to destination: `dest[i] = src[i]`.
210///
211/// Uses HPTT-inspired blocked permutation with bilateral dimension fusion,
212/// cache-aware blocking, and optimal loop ordering. The permutation is split
213/// across the budget of `exec`, at the width the token's dispatch cost
214/// justifies for the copy ([`copy_ns_per_element`](crate::copy_ns_per_element)
215/// times its elements); a small copy stays on the calling thread. A caller that wants a large copy on one thread passes
216/// [`Exec::serial`] or narrows the token with [`Exec::limit`].
217/// A contiguous copy uses one `memcpy` per range of the narrowed token, or a
218/// single `memcpy` on the calling thread when that token is serial.
219///
220/// This is a plain copy: no element operation is applied. For a conjugation on
221/// the same engine use [`copy_conj_into`]; for other element operations
222/// (transpose, scale, ...) use the `strided_kernel` element-map entries.
223///
224/// # Errors
225///
226/// Returns [`StridedError::RankMismatch`] or [`StridedError::ShapeMismatch`]
227/// when the views describe different extents,
228/// [`StridedError::OffsetOverflow`] when the layout cannot be expressed in
229/// `isize` stride arithmetic or a fused extent overflows, and
230/// [`StridedError::NonInjectiveOutputLayout`] when two destination elements
231/// map onto the same memory offset, or the layout span is not representable.
232/// Nothing is written unless validation succeeds.
233///
234/// # Examples
235///
236/// ```
237/// use threadteam::Exec;
238/// use strided_perm::copy_into;
239/// use strided_view::StridedArray;
240///
241/// let src = StridedArray::<f64>::from_fn_col_major(&[2, 3], |idx| (idx[0] * 10 + idx[1]) as f64);
242/// let mut dst = StridedArray::<f64>::col_major(&[2, 3]);
243/// copy_into(&mut dst.view_mut(), &src.view(), Exec::serial()).unwrap();
244/// assert_eq!(dst.get(&[1, 2]), 12.0);
245/// ```
246pub fn copy_into<T: Copy + Send + Sync + 'static>(
247 dest: &mut StridedViewMut<T>,
248 src: &StridedView<T>,
249 exec: Exec<'_>,
250) -> Result<()> {
251 match prepare(dest, src)? {
252 // SAFETY: `prepare` (copy.rs:85) rejected a rank or shape mismatch and a
253 // zero-sized copy, and each view's construction proved its reachable
254 // offsets stay inside its slice (`validate_bounds`,
255 // strided-view/src/view.rs:187, or the dense `StridedArray` layout).
256 // `&mut StridedViewMut` excludes any other
257 // borrow of the destination, so the two raw extents cannot overlap.
258 Some(raw) => unsafe { copy_raw::<T, T, PlainStore>(raw, exec) },
259 None => Ok(()),
260 }
261}
262
263/// Copy elements into an uninitialized destination: `dest[i] = src[i]`.
264///
265/// The same permutation engine as [`copy_into`], selected on `T` rather than
266/// on `MaybeUninit<T>`: the engine's native `f32`/`f64` kernels are chosen by
267/// element type, so a destination reinterpreted as `MaybeUninit<T>` would
268/// otherwise fall to the generic element path (about 2.5x slower on a
269/// 4096x4096 `f64` transpose). Every destination element the views describe
270/// is written exactly once; the stores go through raw pointers only, so no
271/// reference to uninitialized storage is formed.
272///
273/// # Errors
274///
275/// Same rejection set as [`copy_into`]: [`StridedError::RankMismatch`],
276/// [`StridedError::ShapeMismatch`], [`StridedError::OffsetOverflow`] and
277/// [`StridedError::NonInjectiveOutputLayout`]. Nothing is written unless
278/// validation succeeds.
279pub fn copy_into_uninit<T: Copy + Send + Sync + 'static>(
280 dest: &mut StridedViewMut<core::mem::MaybeUninit<T>>,
281 src: &StridedView<T>,
282 exec: Exec<'_>,
283) -> Result<()> {
284 match prepare(dest, src)? {
285 // SAFETY: as `copy_into` (copy.rs:243) — `prepare` matched the shapes and
286 // both views proved their bounds at construction. `MaybeUninit<T>` has `T`'s
287 // size and alignment, and the engine only stores into the destination, so
288 // the uninitialized extent is never read.
289 Some(raw) => unsafe { copy_raw::<T, core::mem::MaybeUninit<T>, PlainStore>(raw, exec) },
290 None => Ok(()),
291 }
292}
293
294/// Copy elements with complex conjugation: `dest[i] = conj(src[i])`.
295///
296/// The same HPTT-inspired blocked permutation as [`copy_into`], with the
297/// conjugate applied as each element is stored — HPTT's `conjA`, so conjugation
298/// costs no extra pass over memory. The store is monomorphized, so the engine
299/// keeps its native `f64`/`f32` micro-kernels for a plain copy and its generic
300/// element path for this one. The plan, the width selection
301/// ([`copy_ns_per_element`](crate::copy_ns_per_element) times the elements) and
302/// the error set are those of [`copy_into`].
303///
304/// `T: ElementOpApply` ([`strided_view::ElementOpApply`]) is the bound
305/// `strided_basic::copy_conj_into` uses, so the two entries line up. The
306/// operation is meaningful for the complex element types (`Complex<f32>`,
307/// `Complex<f64>`). An element type whose `conj` is the identity (every real
308/// type) is accepted and copied unchanged through the generic element store,
309/// which is slower than the native kernels: use [`copy_into`] for those.
310///
311/// # Errors
312///
313/// Same rejection set as [`copy_into`]: [`StridedError::RankMismatch`],
314/// [`StridedError::ShapeMismatch`], [`StridedError::OffsetOverflow`] and
315/// [`StridedError::NonInjectiveOutputLayout`]. Nothing is written unless
316/// validation succeeds.
317///
318/// # Examples
319///
320/// ```
321/// use num_complex::Complex64;
322/// use threadteam::Exec;
323/// use strided_perm::copy_conj_into;
324/// use strided_view::StridedArray;
325///
326/// let src = StridedArray::<Complex64>::from_fn_col_major(&[2, 3], |idx| {
327/// Complex64::new(idx[0] as f64, idx[1] as f64)
328/// });
329/// let mut dst = StridedArray::<Complex64>::col_major(&[3, 2]);
330/// let src_t = src.view().permute(&[1, 0]).unwrap();
331/// copy_conj_into(&mut dst.view_mut(), &src_t, Exec::serial()).unwrap();
332/// assert_eq!(dst.get(&[2, 1]), Complex64::new(1.0, -2.0));
333/// ```
334pub fn copy_conj_into<T: ElementOpApply + Send + Sync + 'static>(
335 dest: &mut StridedViewMut<T>,
336 src: &StridedView<T>,
337 exec: Exec<'_>,
338) -> Result<()> {
339 match prepare(dest, src)? {
340 // SAFETY: as `copy_into` (copy.rs:246): `prepare` (copy.rs:85) matched the
341 // shapes and both views proved their bounds at construction. `ConjStore`
342 // only reads an initialized source element and writes a `T` derived from
343 // it.
344 Some(raw) => unsafe { copy_raw::<T, T, ConjStore>(raw, exec) },
345 None => Ok(()),
346 }
347}
348
349/// Conjugating copy into an uninitialized destination: `dest[i] = conj(src[i])`.
350///
351/// The allocation-free sibling of [`copy_conj_into`], selected on `T` for the
352/// same reason as [`copy_into_uninit`]: the engine's dispatch keys off the
353/// source element type, and the destination is only ever written.
354///
355/// # Errors
356///
357/// Same rejection set as [`copy_conj_into`]. Nothing is written unless
358/// validation succeeds.
359pub fn copy_conj_into_uninit<T: ElementOpApply + Send + Sync + 'static>(
360 dest: &mut StridedViewMut<core::mem::MaybeUninit<T>>,
361 src: &StridedView<T>,
362 exec: Exec<'_>,
363) -> Result<()> {
364 match prepare(dest, src)? {
365 // SAFETY: as `copy_conj_into` (copy.rs:334): `MaybeUninit<T>` has `T`'s
366 // size and alignment and the engine only stores into it.
367 Some(raw) => unsafe { copy_raw::<T, core::mem::MaybeUninit<T>, ConjStore>(raw, exec) },
368 None => Ok(()),
369 }
370}
371
372/// Copy elements to a col-major destination.
373///
374/// This delegates to the same HPTT-inspired blocked permutation as
375/// [`copy_into`]. The HPTT planner handles the col-major destination case
376/// optimally.
377///
378/// # Errors
379///
380/// The errors of [`copy_into`]: [`StridedError::RankMismatch`],
381/// [`StridedError::ShapeMismatch`], [`StridedError::OffsetOverflow`] and
382/// [`StridedError::NonInjectiveOutputLayout`].
383pub fn copy_into_col_major<T: Copy + Send + Sync + 'static>(
384 dst: &mut StridedViewMut<T>,
385 src: &StridedView<T>,
386 exec: Exec<'_>,
387) -> Result<()> {
388 copy_into(dst, src, exec)
389}
390
391#[cfg(test)]
392mod tests;