strided_fused/erased.rs
1use crate::*;
2use core::mem::MaybeUninit;
3use num_complex::{Complex32, Complex64};
4use strided_basic::execution::{
5 check_dtype, ensure_same_shape, erased_view, validate_destination_layout_without_alloc,
6 validate_uninit_no_overlap, ValidatedDestinationLayout,
7};
8const ERASED_FUSED_INPUT_LIMIT: usize = 4;
9
10/// Dtype-erased wrapper around [`FusedPlan`].
11///
12/// This is the erased replay boundary for unary map and zip-map elementwise
13/// families. It supports the same runtime op-code vocabulary as [`FusedPlan`],
14/// but only for the scalar dtypes currently implementing [`FusedScalar`]. A
15/// plan may name one or more outputs; [`ErasedFusedPlan::execute_outputs`] and
16/// [`ErasedFusedPlan::execute_outputs_uninit`] write them all in one replay.
17#[derive(Clone, Debug)]
18pub struct ErasedFusedPlan {
19 dtype: KernelDType,
20 plan: FusedPlan,
21}
22
23impl ErasedFusedPlan {
24 /// Validate and store a fused elementwise plan for one dtype.
25 ///
26 /// The plan must name at least one output; repeated output value ids are
27 /// allowed and write the same value to each named destination.
28 ///
29 /// # Errors
30 ///
31 /// Returns [`StridedError::UnsupportedArity`] when `plan.input_count` is
32 /// outside `1..=4`,
33 /// [`StridedError::RankMismatch`] when the plan names no output or an
34 /// instruction is given a different operand count than it consumes,
35 /// [`StridedError::InvalidAxis`] when an instruction input or a named
36 /// output is not a value id defined before it, and
37 /// [`StridedError::UnsupportedOp`] when the dtype cannot evaluate a
38 /// planned operation.
39 pub fn compile(dtype: KernelDType, plan: FusedPlan) -> Result<Self> {
40 check_fused_dtype(dtype)?;
41 if plan.input_count == 0 || plan.input_count > ERASED_FUSED_INPUT_LIMIT {
42 return Err(StridedError::UnsupportedArity {
43 arity: plan.input_count,
44 max: ERASED_FUSED_INPUT_LIMIT,
45 });
46 }
47 validate_fused_plan_for_dtype(dtype, &plan)?;
48 Ok(Self { dtype, plan })
49 }
50
51 #[inline]
52 pub fn dtype(&self) -> KernelDType {
53 self.dtype
54 }
55
56 #[inline]
57 pub fn plan(&self) -> &FusedPlan {
58 &self.plan
59 }
60
61 /// Execute a single-output fused elementwise plan through erased descriptors.
62 ///
63 /// Forwarding front end for [`Self::execute_outputs`]; the plan must name
64 /// exactly one output.
65 ///
66 /// # Errors
67 ///
68 /// Returns [`StridedError::RankMismatch`] when the input count or the
69 /// output count disagrees with the plan or the plan does not name exactly
70 /// one output, [`StridedError::DTypeMismatch`] when a descriptor does not
71 /// carry the plan dtype, [`StridedError::ShapeMismatch`] or
72 /// [`StridedError::RankMismatch`] when a destination or input does not
73 /// have the shape of `dests[0]`, and
74 /// [`StridedError::NonInjectiveOutputLayout`] when a destination layout
75 /// maps two logical elements onto one offset. Nothing is written unless
76 /// every check succeeds.
77 pub fn execute(
78 &self,
79 dest: &mut ErasedRawStridedMut<'_>,
80 inputs: &[ErasedRawStridedRef<'_>],
81 exec: Exec<'_>,
82 ) -> Result<()> {
83 self.execute_outputs(std::slice::from_mut(dest), inputs, exec)
84 }
85
86 /// Execute a plan into one or more destinations in a single replay.
87 ///
88 /// `plan.outputs` are written to `dests` in order. Every destination is
89 /// validated before any write: dtype, shape against the inputs, and output
90 /// injectivity. Overlapping initialized input/output memory is not
91 /// supported; the mutable destination slices are exclusive, so only
92 /// destination-versus-input overlap is a caller concern.
93 ///
94 /// # Errors
95 ///
96 /// Returns [`StridedError::RankMismatch`] when `inputs.len()` or
97 /// `dests.len()` disagrees with the plan,
98 /// [`StridedError::DTypeMismatch`] when a descriptor does not carry the
99 /// plan dtype, [`StridedError::ShapeMismatch`] or
100 /// [`StridedError::RankMismatch`] when a destination or input does not
101 /// have the shape of `dests[0]`, and
102 /// [`StridedError::NonInjectiveOutputLayout`] when a destination layout
103 /// maps two logical elements onto one offset. Every check runs before any
104 /// destination is written.
105 ///
106 /// # Examples
107 ///
108 /// ```
109 /// use strided_basic::{
110 /// ErasedRawStridedMut, ErasedRawStridedRef, Exec, KernelDType,
111 /// };
112 /// use strided_fused::{ErasedFusedPlan, FusedInst, FusedOp, FusedPlan};
113 ///
114 /// let plan = ErasedFusedPlan::compile(
115 /// KernelDType::F64,
116 /// FusedPlan::new(
117 /// 1,
118 /// vec![0, 1],
119 /// vec![FusedInst::new(FusedOp::Negate, vec![0])],
120 /// ),
121 /// )
122 /// .unwrap();
123 /// let input = [1.0_f64, -2.0];
124 /// let dims = [2];
125 /// let strides = [1];
126 /// let inputs = [ErasedRawStridedRef::from_slice(&input, &dims, &strides, 0).unwrap()];
127 /// let mut pass_through = [0.0_f64; 2];
128 /// let mut negated = [0.0_f64; 2];
129 /// {
130 /// let mut dests = [
131 /// ErasedRawStridedMut::from_slice_mut(&mut pass_through, &dims, &strides, 0).unwrap(),
132 /// ErasedRawStridedMut::from_slice_mut(&mut negated, &dims, &strides, 0).unwrap(),
133 /// ];
134 /// plan.execute_outputs(&mut dests, &inputs, Exec::serial())
135 /// .unwrap();
136 /// }
137 /// assert_eq!(pass_through, [1.0, -2.0]);
138 /// assert_eq!(negated, [-1.0, 2.0]);
139 /// ```
140 pub fn execute_outputs(
141 &self,
142 dests: &mut [ErasedRawStridedMut<'_>],
143 inputs: &[ErasedRawStridedRef<'_>],
144 exec: Exec<'_>,
145 ) -> Result<()> {
146 if inputs.len() != self.plan.input_count {
147 return Err(StridedError::RankMismatch(
148 inputs.len(),
149 self.plan.input_count,
150 ));
151 }
152 if dests.len() != self.plan.outputs.len() {
153 return Err(StridedError::RankMismatch(
154 dests.len(),
155 self.plan.outputs.len(),
156 ));
157 }
158 for dest in dests.iter() {
159 check_dtype(self.dtype, dest.dtype())?;
160 }
161 for input in inputs {
162 check_dtype(self.dtype, input.dtype())?;
163 }
164 let dims = dests[0].dims();
165 for dest in &dests[1..] {
166 ensure_same_shape(dims, dest.dims())?;
167 }
168 for input in inputs {
169 ensure_same_shape(dims, input.dims())?;
170 }
171
172 match self.dtype {
173 KernelDType::F32 => execute_fused_multi::<f32>(&self.plan, dests, inputs, exec),
174 KernelDType::F64 => execute_fused_multi::<f64>(&self.plan, dests, inputs, exec),
175 KernelDType::I32 => execute_fused_multi::<i32>(&self.plan, dests, inputs, exec),
176 KernelDType::I64 => execute_fused_multi::<i64>(&self.plan, dests, inputs, exec),
177 KernelDType::Bool => execute_fused_multi::<bool>(&self.plan, dests, inputs, exec),
178 KernelDType::C32 => execute_fused_multi::<Complex32>(&self.plan, dests, inputs, exec),
179 KernelDType::C64 => execute_fused_multi::<Complex64>(&self.plan, dests, inputs, exec),
180 _ => Err(StridedError::UnsupportedDType {
181 dtype: self.dtype.label(),
182 }),
183 }
184 }
185
186 /// Execute a single-output fused plan into fully overwritten uninitialized
187 /// storage.
188 ///
189 /// Forwarding front end for [`Self::execute_outputs_uninit`]; the plan must
190 /// name exactly one output.
191 ///
192 /// # Errors
193 ///
194 /// Returns [`StridedError::RankMismatch`] when the input count or the
195 /// output count disagrees with the plan or the plan does not name exactly
196 /// one output, [`StridedError::DTypeMismatch`] when a descriptor does not
197 /// carry the plan dtype, [`StridedError::ShapeMismatch`] or
198 /// [`StridedError::RankMismatch`] when a destination or input does not
199 /// have the shape of `dests[0]`,
200 /// [`StridedError::NonInjectiveOutputLayout`] when a destination layout
201 /// maps two logical elements onto one offset,
202 /// [`StridedError::OverlappingInputOutput`] when an input allocation
203 /// overlaps a destination, and [`StridedError::InvalidBoolByte`] when a
204 /// `bool` input holds a byte other than 0 or 1. Every rejection is
205 /// returned before any destination is written.
206 pub fn execute_uninit(
207 &self,
208 dest: &mut ErasedRawStridedUninitMut<'_>,
209 inputs: &[ErasedRawStridedPtr<'_>],
210 exec: Exec<'_>,
211 ) -> Result<()> {
212 self.execute_outputs_uninit(std::slice::from_mut(dest), inputs, exec)
213 }
214
215 /// Execute a plan into one or more fully overwritten uninitialized
216 /// destinations in a single replay.
217 ///
218 /// Dtype, shape, destination injectivity, bounds, and input/output overlap
219 /// are validated for every destination before any shared typed input
220 /// descriptor is formed or any destination byte is written. On `Ok(())`,
221 /// every logical destination element is initialized. An error leaves every
222 /// destination untouched; a panic during execution may leave partial
223 /// initialization, but the backing `MaybeUninit` storage remains safe to
224 /// drop.
225 ///
226 /// # Errors
227 ///
228 /// Returns [`StridedError::RankMismatch`] when `inputs.len()` or
229 /// `dests.len()` disagrees with the plan,
230 /// [`StridedError::DTypeMismatch`] when a descriptor does not carry the
231 /// plan dtype, [`StridedError::ShapeMismatch`] or
232 /// [`StridedError::RankMismatch`] when a destination or input does not
233 /// have the shape of `dests[0]`,
234 /// [`StridedError::NonInjectiveOutputLayout`] when a destination layout
235 /// maps two logical elements onto one offset,
236 /// [`StridedError::OverlappingInputOutput`] when an input allocation
237 /// overlaps a destination, and [`StridedError::InvalidBoolByte`] when a
238 /// `bool` input holds a byte other than 0 or 1. All error-producing
239 /// validation completes before execution starts.
240 ///
241 /// # Examples
242 ///
243 /// ```
244 /// use core::mem::MaybeUninit;
245 /// use strided_basic::{
246 /// ErasedRawStridedPtr, ErasedRawStridedRef, ErasedRawStridedUninitMut,
247 /// Exec, KernelDType,
248 /// };
249 /// use strided_fused::{ErasedFusedPlan, FusedInst, FusedOp, FusedPlan};
250 ///
251 /// let plan = ErasedFusedPlan::compile(
252 /// KernelDType::F32,
253 /// FusedPlan::new(
254 /// 1,
255 /// vec![0, 1],
256 /// vec![FusedInst::new(FusedOp::Negate, vec![0])],
257 /// ),
258 /// )
259 /// .unwrap();
260 /// let input = [1.0_f32, -2.0];
261 /// let dims = [2];
262 /// let strides = [1];
263 /// let input = ErasedRawStridedRef::from_slice(&input, &dims, &strides, 0).unwrap();
264 /// let pointers = [ErasedRawStridedPtr::from_ref(&input)];
265 /// let mut pass_through = [MaybeUninit::<f32>::uninit(); 2];
266 /// let mut negated = [MaybeUninit::<f32>::uninit(); 2];
267 /// {
268 /// let mut dests = [
269 /// ErasedRawStridedUninitMut::from_uninit_slice(
270 /// &mut pass_through,
271 /// &dims,
272 /// &strides,
273 /// 0,
274 /// )
275 /// .unwrap(),
276 /// ErasedRawStridedUninitMut::from_uninit_slice(&mut negated, &dims, &strides, 0).unwrap(),
277 /// ];
278 /// plan.execute_outputs_uninit(&mut dests, &pointers, Exec::serial())
279 /// .unwrap();
280 /// }
281 /// // SAFETY: `execute_outputs_uninit` overwrites every reachable element.
282 /// assert_eq!(unsafe { pass_through[1].assume_init() }, -2.0);
283 /// // SAFETY: as above.
284 /// assert_eq!(unsafe { negated[1].assume_init() }, 2.0);
285 /// ```
286 pub fn execute_outputs_uninit(
287 &self,
288 dests: &mut [ErasedRawStridedUninitMut<'_>],
289 inputs: &[ErasedRawStridedPtr<'_>],
290 exec: Exec<'_>,
291 ) -> Result<()> {
292 if inputs.len() != self.plan.input_count {
293 return Err(StridedError::RankMismatch(
294 inputs.len(),
295 self.plan.input_count,
296 ));
297 }
298 if dests.len() != self.plan.outputs.len() {
299 return Err(StridedError::RankMismatch(
300 dests.len(),
301 self.plan.outputs.len(),
302 ));
303 }
304 for dest in dests.iter() {
305 check_dtype(self.dtype, dest.dtype())?;
306 }
307 for input in inputs {
308 check_dtype(self.dtype, input.dtype())?;
309 }
310 let dims = dests[0].dims();
311 for dest in &dests[1..] {
312 ensure_same_shape(dims, dest.dims())?;
313 }
314 for input in inputs {
315 ensure_same_shape(dims, input.dims())?;
316 }
317 for (index, input) in inputs.iter().enumerate() {
318 for dest in dests.iter() {
319 validate_uninit_no_overlap(dest, input, index)?;
320 }
321 }
322 // Store the validation tokens inline: the destination-count bound is
323 // the five-stream operand bound, so two outputs plus one input allocate
324 // nothing. Above the bound the vector spills by contract.
325 let mut validated: strided_basic::OperandVec<ValidatedDestinationLayout> =
326 strided_basic::OperandVec::with_capacity(dests.len());
327 for dest in dests.iter() {
328 validated.push(validate_destination_layout_without_alloc(
329 dest.dims(),
330 dest.strides(),
331 )?);
332 }
333 self.dispatch_uninit(dests, inputs, validated.as_slice(), exec)
334 }
335
336 fn dispatch_uninit(
337 &self,
338 dests: &mut [ErasedRawStridedUninitMut<'_>],
339 inputs: &[ErasedRawStridedPtr<'_>],
340 validated: &[ValidatedDestinationLayout],
341 exec: Exec<'_>,
342 ) -> Result<()> {
343 match self.dtype {
344 KernelDType::F32 => {
345 execute_fused_uninit_multi::<f32>(&self.plan, dests, inputs, validated, exec)
346 }
347 KernelDType::F64 => {
348 execute_fused_uninit_multi::<f64>(&self.plan, dests, inputs, validated, exec)
349 }
350 KernelDType::I32 => {
351 execute_fused_uninit_multi::<i32>(&self.plan, dests, inputs, validated, exec)
352 }
353 KernelDType::I64 => {
354 execute_fused_uninit_multi::<i64>(&self.plan, dests, inputs, validated, exec)
355 }
356 KernelDType::Bool => {
357 execute_fused_uninit_multi::<bool>(&self.plan, dests, inputs, validated, exec)
358 }
359 KernelDType::C32 => {
360 execute_fused_uninit_multi::<Complex32>(&self.plan, dests, inputs, validated, exec)
361 }
362 KernelDType::C64 => {
363 execute_fused_uninit_multi::<Complex64>(&self.plan, dests, inputs, validated, exec)
364 }
365 _ => Err(StridedError::UnsupportedDType {
366 dtype: self.dtype.label(),
367 }),
368 }
369 }
370}
371
372fn check_fused_dtype(dtype: KernelDType) -> Result<()> {
373 match dtype {
374 KernelDType::F32
375 | KernelDType::F64
376 | KernelDType::I32
377 | KernelDType::I64
378 | KernelDType::Bool
379 | KernelDType::C32
380 | KernelDType::C64 => Ok(()),
381 _ => Err(StridedError::UnsupportedDType {
382 dtype: dtype.label(),
383 }),
384 }
385}
386
387fn validate_fused_plan_for_dtype(dtype: KernelDType, plan: &FusedPlan) -> Result<()> {
388 let output_count = plan.outputs.len();
389 match dtype {
390 KernelDType::F32 => {
391 crate::fused::validate_plan_for_scalar::<f32>(plan, plan.input_count, output_count)
392 }
393 KernelDType::F64 => {
394 crate::fused::validate_plan_for_scalar::<f64>(plan, plan.input_count, output_count)
395 }
396 KernelDType::I32 => {
397 crate::fused::validate_plan_for_scalar::<i32>(plan, plan.input_count, output_count)
398 }
399 KernelDType::I64 => {
400 crate::fused::validate_plan_for_scalar::<i64>(plan, plan.input_count, output_count)
401 }
402 KernelDType::Bool => {
403 crate::fused::validate_plan_for_scalar::<bool>(plan, plan.input_count, output_count)
404 }
405 KernelDType::C32 => crate::fused::validate_plan_for_scalar::<Complex32>(
406 plan,
407 plan.input_count,
408 output_count,
409 ),
410 KernelDType::C64 => crate::fused::validate_plan_for_scalar::<Complex64>(
411 plan,
412 plan.input_count,
413 output_count,
414 ),
415 _ => Err(StridedError::UnsupportedDType {
416 dtype: dtype.label(),
417 }),
418 }
419}
420
421fn execute_fused_multi<T>(
422 plan: &FusedPlan,
423 dests: &mut [ErasedRawStridedMut<'_>],
424 inputs: &[ErasedRawStridedRef<'_>],
425 exec: Exec<'_>,
426) -> Result<()>
427where
428 T: FusedScalar + KernelStorageElement,
429{
430 // The single-output case uses stack storage so the hot path allocates
431 // nothing; several destinations stay inline up to the operand bound and
432 // spill above it.
433 if dests.len() == 1 {
434 let dims = dests[0].dims();
435 let strides = dests[0].strides();
436 let offset = dests[0].offset();
437 let data = dests[0].data_as_mut::<T>()?;
438 let mut dest_views =
439 // SAFETY: `StridedViewMut::new_unchecked` (strided-view/src/view.rs:957) needs every
440 // index combination in bounds. This descriptor checked exactly these dims, strides
441 // and offset against its element count when it was built (`validate_bounds`,
442 // strided-view/src/view.rs:187), and `data_as_mut` (strided-view/src/raw.rs:710)
443 // returned that count after checking the dtype. The `&mut` slice carries exclusivity.
444 [unsafe { StridedViewMut::new_unchecked(data, dims, strides, offset) }];
445 return execute_fused_inputs(&mut dest_views, inputs, plan, exec);
446 }
447
448 if dests.len() <= strided_basic::OPERAND_CAP {
449 let mut storage =
450 [const { MaybeUninit::<StridedViewMut<'_, T>>::uninit() }; strided_basic::OPERAND_CAP];
451 // SAFETY: `InitializedViewsMut::new` (fused.rs:38) needs `OPERAND_CAP` writable slots
452 // that outlive the guard: `storage` is an `OPERAND_CAP` array declared before `views`, so
453 // it is dropped after it, and this branch holds only when `dests.len() <= OPERAND_CAP`
454 // (erased.rs:448), which bounds the pushes.
455 let mut views = unsafe { crate::fused::InitializedViewsMut::new(storage.as_mut_ptr()) };
456 for dest in dests.iter_mut() {
457 let dims = dest.dims();
458 let strides = dest.strides();
459 let offset = dest.offset();
460 let data = dest.data_as_mut::<T>()?;
461 // SAFETY: as for the single-destination view above (erased.rs:439): the descriptor's
462 // construction-time `validate_bounds` (strided-view/src/view.rs:187) covers these
463 // dims, strides and offset, and `data_as_mut` (strided-view/src/raw.rs:710) the count.
464 views.push(unsafe { StridedViewMut::new_unchecked(data, dims, strides, offset) });
465 }
466 return execute_fused_inputs(views.as_mut_slice(), inputs, plan, exec);
467 }
468
469 let mut dest_views = Vec::with_capacity(dests.len());
470 for dest in dests.iter_mut() {
471 let dims = dest.dims();
472 let strides = dest.strides();
473 let offset = dest.offset();
474 let data = dest.data_as_mut::<T>()?;
475 // SAFETY: as for the single-destination view above (erased.rs:439): the descriptor's
476 // construction-time `validate_bounds` (strided-view/src/view.rs:187) covers these dims,
477 // strides and offset, and `data_as_mut` (strided-view/src/raw.rs:710) returned the count.
478 dest_views.push(unsafe { StridedViewMut::new_unchecked(data, dims, strides, offset) });
479 }
480 execute_fused_inputs(&mut dest_views, inputs, plan, exec)
481}
482
483fn execute_fused_inputs<T>(
484 dests: &mut [StridedViewMut<'_, T>],
485 inputs: &[ErasedRawStridedRef<'_>],
486 plan: &FusedPlan,
487 exec: Exec<'_>,
488) -> Result<()>
489where
490 T: FusedScalar + KernelStorageElement,
491{
492 match inputs {
493 [a] => {
494 let views = [erased_view::<T>(a)?];
495 execute_fused_views(dests, &views, plan, exec)
496 }
497 [a, b] => {
498 let views = [erased_view::<T>(a)?, erased_view::<T>(b)?];
499 execute_fused_views(dests, &views, plan, exec)
500 }
501 [a, b, c] => {
502 let views = [
503 erased_view::<T>(a)?,
504 erased_view::<T>(b)?,
505 erased_view::<T>(c)?,
506 ];
507 execute_fused_views(dests, &views, plan, exec)
508 }
509 [a, b, c, d] => {
510 let views = [
511 erased_view::<T>(a)?,
512 erased_view::<T>(b)?,
513 erased_view::<T>(c)?,
514 erased_view::<T>(d)?,
515 ];
516 execute_fused_views(dests, &views, plan, exec)
517 }
518 _ => Err(StridedError::UnsupportedArity {
519 arity: inputs.len(),
520 max: ERASED_FUSED_INPUT_LIMIT,
521 }),
522 }
523}
524
525fn execute_fused_uninit_multi<T>(
526 plan: &FusedPlan,
527 dests: &mut [ErasedRawStridedUninitMut<'_>],
528 inputs: &[ErasedRawStridedPtr<'_>],
529 validated: &[ValidatedDestinationLayout],
530 exec: Exec<'_>,
531) -> Result<()>
532where
533 T: FusedScalar + KernelStorageElement,
534{
535 if dests.len() == 1 {
536 let dims = dests[0].dims();
537 let strides = dests[0].strides();
538 let offset = dests[0].offset();
539 let data = dests[0].data_as_uninit_mut::<T>()?;
540 let mut dest_views =
541 // SAFETY: `StridedViewMut::new_unchecked` (strided-view/src/view.rs:957) needs every
542 // index combination in bounds. This descriptor checked exactly these dims, strides
543 // and offset against its element count when it was built (`validate_bounds`,
544 // strided-view/src/view.rs:187), and `data_as_uninit_mut`
545 // (strided-view/src/raw.rs:882) returned that count after checking the dtype. The
546 // `&mut` slice carries exclusivity.
547 [unsafe { StridedViewMut::new_unchecked(data, dims, strides, offset) }];
548 return execute_fused_uninit_inputs(plan, &mut dest_views, inputs, validated, exec);
549 }
550
551 if dests.len() <= strided_basic::OPERAND_CAP {
552 let mut storage = [const { MaybeUninit::<StridedViewMut<'_, MaybeUninit<T>>>::uninit() };
553 strided_basic::OPERAND_CAP];
554 // SAFETY: `InitializedViewsMut::new` (fused.rs:38) needs `OPERAND_CAP` writable slots
555 // that outlive the guard: `storage` is an `OPERAND_CAP` array declared before `views`, so
556 // it is dropped after it, and this branch holds only when `dests.len() <= OPERAND_CAP`
557 // (erased.rs:551), which bounds the pushes.
558 let mut views = unsafe { crate::fused::InitializedViewsMut::new(storage.as_mut_ptr()) };
559 for dest in dests.iter_mut() {
560 let dims = dest.dims();
561 let strides = dest.strides();
562 let offset = dest.offset();
563 let data = dest.data_as_uninit_mut::<T>()?;
564 // SAFETY: as for the single-destination view above (erased.rs:541): the descriptor's
565 // construction-time `validate_bounds` (strided-view/src/view.rs:187) covers these
566 // dims, strides and offset, and `data_as_uninit_mut` (strided-view/src/raw.rs:882)
567 // returned the count.
568 views.push(unsafe { StridedViewMut::new_unchecked(data, dims, strides, offset) });
569 }
570 return execute_fused_uninit_inputs(plan, views.as_mut_slice(), inputs, validated, exec);
571 }
572
573 let mut dest_views = Vec::with_capacity(dests.len());
574 for dest in dests.iter_mut() {
575 let dims = dest.dims();
576 let strides = dest.strides();
577 let offset = dest.offset();
578 let data = dest.data_as_uninit_mut::<T>()?;
579 // SAFETY: as for the single-destination view above (erased.rs:541): the descriptor's
580 // construction-time `validate_bounds` (strided-view/src/view.rs:187) covers these dims,
581 // strides and offset, and `data_as_uninit_mut` (strided-view/src/raw.rs:882) returned
582 // the count.
583 dest_views.push(unsafe { StridedViewMut::new_unchecked(data, dims, strides, offset) });
584 }
585 execute_fused_uninit_inputs(plan, &mut dest_views, inputs, validated, exec)
586}
587
588fn execute_fused_uninit_inputs<T>(
589 plan: &FusedPlan,
590 dests: &mut [StridedViewMut<'_, MaybeUninit<T>>],
591 inputs: &[ErasedRawStridedPtr<'_>],
592 validated: &[ValidatedDestinationLayout],
593 exec: Exec<'_>,
594) -> Result<()>
595where
596 T: FusedScalar + KernelStorageElement,
597{
598 match inputs {
599 // SAFETY: `ErasedFusedPlan::execute_outputs_uninit` checked every input
600 // against every destination before this helper.
601 [a] => {
602 // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs no
603 // mutable allocation overlapping `a`, its allocation contract still in force
604 // (strided-view/src/raw.rs:204), and no conflicting access while the result is used.
605 // This helper's only caller is `execute_fused_uninit_multi`, reached only from
606 // `ErasedFusedPlan::execute_outputs_uninit`, which checked every input against every
607 // destination with `validate_uninit_no_overlap` (erased.rs:319) before dispatching.
608 // The destinations stay borrowed `&mut` for the call.
609 let refs = [unsafe { a.try_as_ref_after_no_overlap()? }];
610 let views = [erased_view::<T>(&refs[0])?];
611 crate::fused::fused_elementwise_into_uninit_multi(dests, &views, plan, validated, exec)
612 }
613 [a, b] => {
614 let refs = [
615 // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs no
616 // mutable allocation overlapping `a`, its allocation contract still in force
617 // (strided-view/src/raw.rs:204), and no conflicting access while the result is
618 // used. This helper's only caller is `execute_fused_uninit_multi`, reached only
619 // from `ErasedFusedPlan::execute_outputs_uninit`, which checked every input
620 // against every destination with `validate_uninit_no_overlap` (erased.rs:319)
621 // before dispatching. The destinations stay borrowed `&mut` for the call.
622 unsafe { a.try_as_ref_after_no_overlap()? },
623 // SAFETY: as for `a`: the same `validate_uninit_no_overlap` check covered `b`
624 // (erased.rs:319).
625 unsafe { b.try_as_ref_after_no_overlap()? },
626 ];
627 let views = [erased_view::<T>(&refs[0])?, erased_view::<T>(&refs[1])?];
628 crate::fused::fused_elementwise_into_uninit_multi(dests, &views, plan, validated, exec)
629 }
630 [a, b, c] => {
631 let refs = [
632 // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs no
633 // mutable allocation overlapping `a`, its allocation contract still in force
634 // (strided-view/src/raw.rs:204), and no conflicting access while the result is
635 // used. This helper's only caller is `execute_fused_uninit_multi`, reached only
636 // from `ErasedFusedPlan::execute_outputs_uninit`, which checked every input
637 // against every destination with `validate_uninit_no_overlap` (erased.rs:319)
638 // before dispatching. The destinations stay borrowed `&mut` for the call.
639 unsafe { a.try_as_ref_after_no_overlap()? },
640 // SAFETY: as for `a`: the same `validate_uninit_no_overlap` check covered `b`
641 // (erased.rs:319).
642 unsafe { b.try_as_ref_after_no_overlap()? },
643 // SAFETY: as for `a`: the same `validate_uninit_no_overlap` check covered `c`
644 // (erased.rs:319).
645 unsafe { c.try_as_ref_after_no_overlap()? },
646 ];
647 let views = [
648 erased_view::<T>(&refs[0])?,
649 erased_view::<T>(&refs[1])?,
650 erased_view::<T>(&refs[2])?,
651 ];
652 crate::fused::fused_elementwise_into_uninit_multi(dests, &views, plan, validated, exec)
653 }
654 [a, b, c, d] => {
655 let refs = [
656 // SAFETY: `try_as_ref_after_no_overlap` (strided-view/src/raw.rs:288) needs no
657 // mutable allocation overlapping `a`, its allocation contract still in force
658 // (strided-view/src/raw.rs:204), and no conflicting access while the result is
659 // used. This helper's only caller is `execute_fused_uninit_multi`, reached only
660 // from `ErasedFusedPlan::execute_outputs_uninit`, which checked every input
661 // against every destination with `validate_uninit_no_overlap` (erased.rs:319)
662 // before dispatching. The destinations stay borrowed `&mut` for the call.
663 unsafe { a.try_as_ref_after_no_overlap()? },
664 // SAFETY: as for `a`: the same `validate_uninit_no_overlap` check covered `b`
665 // (erased.rs:319).
666 unsafe { b.try_as_ref_after_no_overlap()? },
667 // SAFETY: as for `a`: the same `validate_uninit_no_overlap` check covered `c`
668 // (erased.rs:319).
669 unsafe { c.try_as_ref_after_no_overlap()? },
670 // SAFETY: as for `a`: the same `validate_uninit_no_overlap` check covered `d`
671 // (erased.rs:319).
672 unsafe { d.try_as_ref_after_no_overlap()? },
673 ];
674 let views = [
675 erased_view::<T>(&refs[0])?,
676 erased_view::<T>(&refs[1])?,
677 erased_view::<T>(&refs[2])?,
678 erased_view::<T>(&refs[3])?,
679 ];
680 crate::fused::fused_elementwise_into_uninit_multi(dests, &views, plan, validated, exec)
681 }
682 _ => Err(StridedError::UnsupportedArity {
683 arity: inputs.len(),
684 max: ERASED_FUSED_INPUT_LIMIT,
685 }),
686 }
687}
688
689fn execute_fused_views<T>(
690 dests: &mut [StridedViewMut<'_, T>],
691 inputs: &[StridedView<'_, T>],
692 plan: &FusedPlan,
693 exec: Exec<'_>,
694) -> Result<()>
695where
696 T: FusedScalar + KernelStorageElement,
697{
698 fused_elementwise_into(dests, inputs, plan, exec)
699}