coeus-ops 0.13.0

Numerical tensor operators for Coeus.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use crate::fuse::expr_node::CpuExprNode;
use crate::ptr::MutPtr;
use crate::CpuBackend;
use coeus_core::{
    BackendError, ClosedReduction, CpuAddressableStorageMut, FloatElement, Layout, Scalar,
};
use coeus_tensor::Tensor;

#[repr(transparent)]
#[derive(Clone, Copy)]
struct ScopedExpression(*const ());

// SAFETY: the wrapper exposes no safe dereference operation. Its only use in
// this module is bounded by Backend::parallel_for, which joins all invocations
// before returning and therefore before the borrowed expression is dropped.
unsafe impl Send for ScopedExpression {}
// SAFETY: expression reads are shared and ExprNode requires Sync; callers of
// read additionally uphold the pointee type and lifetime contract.
unsafe impl Sync for ScopedExpression {}

impl ScopedExpression {
    fn new<E>(expression: &E) -> Self {
        Self(std::ptr::from_ref(expression).cast())
    }

    unsafe fn read<E: Copy>(self) -> E {
        // SAFETY: callers provide the original pointee type and keep it alive
        // until the synchronous parallel_for invocation has joined.
        unsafe { self.0.cast::<E>().read() }
    }
}

#[inline(always)]
fn logical_to_coords(mut temp: usize, ndim: usize, out_strides: &[usize], coords: &mut [usize]) {
    match ndim {
        0 => {}
        1 => {
            coords[0] = temp;
        }
        2 => {
            let s0 = out_strides[0];
            coords[0] = temp / s0;
            coords[1] = temp % s0;
        }
        3 => {
            let s0 = out_strides[0];
            let s1 = out_strides[1];
            coords[0] = temp / s0;
            let rem0 = temp % s0;
            coords[1] = rem0 / s1;
            coords[2] = rem0 % s1;
        }
        4 => {
            let s0 = out_strides[0];
            let s1 = out_strides[1];
            let s2 = out_strides[2];
            coords[0] = temp / s0;
            let rem0 = temp % s0;
            coords[1] = rem0 / s1;
            let rem1 = rem0 % s1;
            coords[2] = rem1 / s2;
            coords[3] = rem1 % s2;
        }
        _ => {
            for d in 0..ndim {
                coords[d] = temp / out_strides[d];
                temp %= out_strides[d];
            }
        }
    }
}

fn write_fused_values<E, T, B>(
    expr: E,
    out_ptr: MutPtr<T>,
    out_numel: usize,
    out_layout: &Layout,
    contiguous_fast_path: bool,
    backend: &B,
) where
    E: CpuExprNode<T, B> + Copy + Send,
    T: Scalar,
    B: CpuBackend,
{
    let ndim = out_layout.ndim();
    let out_strides = out_layout.strides_cloned();
    let expression = ScopedExpression::new(&expr);

    if contiguous_fast_path {
        backend.parallel_for(0, out_numel, move |idx| unsafe {
            let expr = expression.read::<E>();
            let val = expr.eval_cpu_flat(idx);
            out_ptr.write(idx, val);
        });
    } else {
        backend.parallel_for(0, out_numel, move |idx| {
            // SAFETY: parallel_for joins before write_fused_values returns,
            // keeping the borrowed expression alive for every invocation.
            let expr = unsafe { expression.read::<E>() };
            if ndim <= 8 {
                let mut coords = [0usize; 8];
                logical_to_coords(idx, ndim, &out_strides, &mut coords[..ndim]);
                unsafe {
                    let val = expr.eval_cpu(&coords[..ndim]);
                    out_ptr.write(idx, val);
                }
            } else {
                let mut coords = smallvec::SmallVec::<[usize; 16]>::from_elem(0, ndim);
                logical_to_coords(idx, ndim, &out_strides, &mut coords);
                unsafe {
                    let val = expr.eval_cpu(&coords);
                    out_ptr.write(idx, val);
                }
            }
        });
    }
}

/// How a fused reduction folds its axis and finishes.
#[derive(Clone, Copy)]
enum FusedFold<T> {
    /// Sum, product, maximum, or minimum: the folded value is the result.
    Closed(ClosedReduction),
    /// Arithmetic mean: the folded sum divided by `divisor`, the axis length
    /// in the element type.
    Mean { divisor: T },
}

impl<T: Scalar> FusedFold<T> {
    /// The reduction tag this fold evaluates.
    fn op(self) -> crate::ReductionOp {
        match self {
            Self::Closed(reduction) => reduction.into(),
            Self::Mean { .. } => crate::ReductionOp::Mean,
        }
    }

    #[inline(always)]
    fn combine(self, acc: T, val: T) -> T {
        match self {
            Self::Closed(ClosedReduction::Sum) | Self::Mean { .. } => acc + val,
            Self::Closed(ClosedReduction::Prod) => acc * val,
            Self::Closed(ClosedReduction::Max) => {
                if val > acc {
                    val
                } else {
                    acc
                }
            }
            Self::Closed(ClosedReduction::Min) => {
                if val < acc {
                    val
                } else {
                    acc
                }
            }
        }
    }

    #[inline(always)]
    fn finish(self, acc: T) -> T {
        match self {
            Self::Closed(_) => acc,
            Self::Mean { divisor } => acc / divisor,
        }
    }
}

#[derive(Clone, Copy)]
struct FusedReductionPlan<'a, T> {
    out_layout: &'a Layout,
    axis: usize,
    axis_len: usize,
    fold: FusedFold<T>,
}

unsafe fn eval_reduction_at<E, T, B>(
    expr: E,
    coords: &mut [usize],
    axis: usize,
    axis_len: usize,
    fold: FusedFold<T>,
) -> T
where
    E: CpuExprNode<T, B> + Copy,
    T: Scalar,
    B: CpuBackend,
{
    coords[axis] = 0;
    let mut acc = expr.eval_cpu(coords);

    for k in 1..axis_len {
        coords[axis] = k;
        let val = expr.eval_cpu(coords);
        acc = fold.combine(acc, val);
    }

    fold.finish(acc)
}

fn write_fused_reductions<E, T, B>(
    expr: E,
    out_ptr: MutPtr<T>,
    out_numel: usize,
    plan: FusedReductionPlan<'_, T>,
    backend: &B,
) where
    E: CpuExprNode<T, B> + Copy + Send,
    T: Scalar,
    B: CpuBackend,
{
    let ndim = plan.out_layout.ndim();
    let out_strides = plan.out_layout.strides_cloned();
    let expression = ScopedExpression::new(&expr);

    backend.parallel_for(0, out_numel, move |idx| {
        // SAFETY: parallel_for joins before write_fused_reductions returns,
        // keeping the borrowed expression alive for every invocation.
        let expr = unsafe { expression.read::<E>() };
        if ndim <= 8 {
            let mut coords = [0usize; 8];
            logical_to_coords(idx, ndim, &out_strides, &mut coords[..ndim]);
            unsafe {
                let acc = eval_reduction_at(
                    expr,
                    &mut coords[..ndim],
                    plan.axis,
                    plan.axis_len,
                    plan.fold,
                );
                out_ptr.write(idx, acc);
            }
        } else {
            let mut coords = smallvec::SmallVec::<[usize; 16]>::from_elem(0, ndim);
            logical_to_coords(idx, ndim, &out_strides, &mut coords);
            unsafe {
                let acc = eval_reduction_at(expr, &mut coords, plan.axis, plan.axis_len, plan.fold);
                out_ptr.write(idx, acc);
            }
        }
    });
}

/// Validate the shared empty-axis contract for fused reductions.
///
/// Sum and product retain their additive and multiplicative identities. Mean,
/// maximum, and minimum require at least one input value.
///
/// # Errors
///
/// Returns [`BackendError::EmptyReduction`] when `axis_len` is zero and `op`
/// has no identity.
pub fn validate_fused_reduction_axis(
    op: crate::ReductionOp,
    axis_len: usize,
) -> Result<(), BackendError> {
    if axis_len == 0
        && matches!(
            op,
            crate::ReductionOp::Mean | crate::ReductionOp::Max | crate::ReductionOp::Min
        )
    {
        return Err(BackendError::EmptyReduction {
            operation: "fused reduction",
            reduction: op,
        });
    }
    Ok(())
}

/// Evaluate a fused expression DAG on the CPU, returning a new tensor with the result.
///
/// # Errors
///
/// Returns [`BackendError`] when the expression has no tensor input or its
/// child shapes cannot be broadcast.
pub fn evaluate_fused_cpu<E, T, B>(expr: &E, backend: &B) -> Result<Tensor<T, B>, BackendError>
where
    E: CpuExprNode<T, B> + Copy + Send,
    T: Scalar,
    B: CpuBackend,
    B::DeviceBuffer<T>: CpuAddressableStorageMut<T>,
{
    let out_shape = expr.shape()?.ok_or_else(|| BackendError::Storage {
        operation: "fused expression",
        reason: "expression has no tensor input from which to derive its shape".to_string(),
    })?;
    let out_layout = Layout::new(out_shape.clone());
    // SAFETY: The following operation writes every output element before it is read.
    let mut out = unsafe { Tensor::alloc_on(out_shape, backend) }?;

    let out_numel = out.numel();
    let contiguous_fast_path = expr.is_contiguous_and_same_shape(out_layout.shape());
    let out_ptr = MutPtr(out.storage_mut()?.as_mut_slice()?.as_mut_ptr());
    write_fused_values(
        *expr,
        out_ptr,
        out_numel,
        &out_layout,
        contiguous_fast_path,
        backend,
    );

    Ok(out)
}

/// Evaluate a fused expression DAG with a reduction along `axis` on the CPU.
///
/// Mean is float-only and evaluates through [`evaluate_fused_mean_cpu`].
///
/// # Errors
///
/// Returns [`BackendError::FloatOnlyReduction`] for
/// [`ReductionOp::Mean`](crate::ReductionOp::Mean), and [`BackendError`] when
/// the expression has no tensor input, child shapes cannot be broadcast,
/// `axis` is outside the expression rank, or an empty axis is used with
/// maximum or minimum.
pub fn evaluate_fused_reduce_cpu<E, T, B>(
    expr: &E,
    op: crate::ReductionOp,
    axis: usize,
    backend: &B,
) -> Result<Tensor<T, B>, BackendError>
where
    E: CpuExprNode<T, B> + Copy + Send,
    T: Scalar,
    B: CpuBackend,
    B::DeviceBuffer<T>: CpuAddressableStorageMut<T>,
{
    let reduction = ClosedReduction::from_op("fused reduction", op)?;
    fused_reduction(expr, axis, backend, |_| FusedFold::Closed(reduction))
}

/// Evaluate a fused expression DAG with an arithmetic mean along `axis` on
/// the CPU.
///
/// The `FloatElement` bound makes integer mean unrepresentable: integer
/// division would truncate the quotient.
///
/// # Errors
///
/// Returns [`BackendError`] when the expression has no tensor input, child
/// shapes cannot be broadcast, `axis` is outside the expression rank, or the
/// axis is empty.
pub fn evaluate_fused_mean_cpu<E, T, B>(
    expr: &E,
    axis: usize,
    backend: &B,
) -> Result<Tensor<T, B>, BackendError>
where
    E: CpuExprNode<T, B> + Copy + Send,
    T: Scalar + FloatElement,
    B: CpuBackend,
    B::DeviceBuffer<T>: CpuAddressableStorageMut<T>,
{
    fused_reduction(expr, axis, backend, |axis_len| FusedFold::Mean {
        divisor: T::from_count(axis_len),
    })
}

/// Shared fused reduction body. `fold_for` builds the fold from the reduced
/// axis length once the axis is validated.
fn fused_reduction<E, T, B>(
    expr: &E,
    axis: usize,
    backend: &B,
    fold_for: impl FnOnce(usize) -> FusedFold<T>,
) -> Result<Tensor<T, B>, BackendError>
where
    E: CpuExprNode<T, B> + Copy + Send,
    T: Scalar,
    B: CpuBackend,
    B::DeviceBuffer<T>: CpuAddressableStorageMut<T>,
{
    let expr_shape = expr.shape()?.ok_or_else(|| BackendError::Storage {
        operation: "fused reduction",
        reason: "expression has no tensor input from which to derive its shape".to_string(),
    })?;
    if axis >= expr_shape.len() {
        return Err(BackendError::AxisOutOfRange {
            operation: "fused reduction",
            axis,
            rank: expr_shape.len(),
        });
    }

    let mut out_shape = expr_shape.clone();
    out_shape[axis] = 1;
    let out_layout = Layout::new(out_shape.clone());
    // SAFETY: The following operation writes every output element before it is read.
    let mut out = unsafe { Tensor::alloc_on(out_shape, backend) }?;

    let out_numel = out.numel();
    let axis_len = expr_shape[axis];
    let fold = fold_for(axis_len);
    validate_fused_reduction_axis(fold.op(), axis_len)?;

    if axis_len == 0 {
        let identity = match fold {
            FusedFold::Closed(ClosedReduction::Sum) => T::ZERO,
            FusedFold::Closed(ClosedReduction::Prod) => T::ONE,
            FusedFold::Closed(ClosedReduction::Max | ClosedReduction::Min)
            | FusedFold::Mean { .. } => {
                unreachable!("invariant: undefined empty reductions were rejected")
            }
        };
        backend.fill(out.storage_mut()?, identity)?;
        return Ok(out);
    }

    let plan = FusedReductionPlan {
        out_layout: &out_layout,
        axis,
        axis_len,
        fold,
    };
    let out_ptr = MutPtr(out.storage_mut()?.as_mut_slice()?.as_mut_ptr());
    write_fused_reductions(*expr, out_ptr, out_numel, plan, backend);

    Ok(out)
}