coeus-ops 0.14.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
422
423
424
425
426
427
428
429
430
431
//! Dimension-generic coordinate-grid interpolation operations.

use coeus_core::{
    Backend, CpuAddressableStorage, CpuAddressableStorageMut, Float, FloatElement, Scalar,
};
use coeus_tensor::Tensor;

mod private {
    pub trait Sealed {}
}

/// Static boundary behavior for linear interpolation.
pub trait BoundaryPolicy: private::Sealed + Copy + Default {
    /// Returns lower/upper indices and their interpolation weights.
    fn neighbours<T: Float + FloatElement>(coordinate: T, extent: usize) -> (usize, usize, T, T);
}

/// Replicate the nearest border value outside the image extent.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Replicate;

impl private::Sealed for Replicate {}

impl BoundaryPolicy for Replicate {
    fn neighbours<T: Float + FloatElement>(coordinate: T, extent: usize) -> (usize, usize, T, T) {
        let lower_value = Float::floor(coordinate);
        let upper_weight = coordinate - lower_value;
        let upper_bound = T::from_count(extent - 1);
        let lower = clamp_index(lower_value, upper_bound);
        let upper = clamp_index(lower_value + T::ONE, upper_bound);
        (lower, upper, T::ONE - upper_weight, upper_weight)
    }
}

/// Clamp an integer-valued coordinate into `[0, upper]` and return it as an
/// index.
///
/// `Float` exposes no float-to-integer conversion, so the clamped value
/// widens through `NumericElement::to_f64`. The widening is exact — `f64`
/// holds every value of the narrower formats — and a valid input is an
/// integer in `[0, upper]`, so the final cast neither saturates nor
/// truncates. Callers reject non-finite coordinates before reaching here; a
/// NaN compares false against both bounds and saturates to `0`.
fn clamp_index<T: Float>(value: T, upper: T) -> usize {
    let clamped = if value < T::ZERO {
        T::ZERO
    } else if value > upper {
        upper
    } else {
        value
    };
    clamped.to_f64() as usize
}

/// Const-dimension marker restricting interpolation monomorphizations.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Dimension<const D: usize>;

/// Compile-time evidence that an interpolation dimension is implemented.
pub trait SupportedDimension: private::Sealed {}

impl private::Sealed for Dimension<2> {}
impl private::Sealed for Dimension<3> {}
impl SupportedDimension for Dimension<2> {}
impl SupportedDimension for Dimension<3> {}

/// Gradients produced by dimension-generic linear interpolation reverse mode.
pub struct InterpolationGradients<T: Scalar, B: Backend> {
    /// Gradient with respect to image values.
    pub image: Tensor<T, B>,
    /// Gradient with respect to sampling coordinates.
    pub grid: Tensor<T, B>,
}

/// Contract failures for [`linear_interpolation`].
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum InterpolationError {
    /// The image rank differs from `[batch, channel, spatial...]`.
    #[error("{dimension}-D interpolation requires image rank {expected}, got {actual}")]
    ImageRank {
        /// Spatial dimension.
        dimension: usize,
        /// Required rank.
        expected: usize,
        /// Supplied rank.
        actual: usize,
    },
    /// The grid rank differs from `[batch, coordinate, spatial...]`.
    #[error("{dimension}-D interpolation requires grid rank {expected}, got {actual}")]
    GridRank {
        /// Spatial dimension.
        dimension: usize,
        /// Required rank.
        expected: usize,
        /// Supplied rank.
        actual: usize,
    },
    /// The grid batch does not match the image batch.
    #[error("linear interpolation batch mismatch: image {image}, grid {grid}")]
    BatchMismatch {
        /// Image batch extent.
        image: usize,
        /// Grid batch extent.
        grid: usize,
    },
    /// The grid coordinate-channel count differs from the spatial dimension.
    #[error("linear interpolation grid requires {expected} coordinate channels, got {actual}")]
    GridChannels {
        /// Spatial dimension.
        expected: usize,
        /// Supplied channel count.
        actual: usize,
    },
    /// An input spatial axis is empty.
    #[error("linear interpolation image spatial axis {axis} is empty")]
    EmptySpatialAxis {
        /// Zero-based spatial axis.
        axis: usize,
    },
    /// A sampling coordinate is NaN or infinite.
    #[error("linear interpolation coordinate axis {axis} at output point {point} is not finite")]
    NonFiniteCoordinate {
        /// Coordinate axis.
        axis: usize,
        /// Flattened output point.
        point: usize,
    },
    /// A shape product overflowed `usize`.
    #[error("linear interpolation element count overflow")]
    SizeOverflow,
    /// The upstream gradient shape does not match the interpolation output.
    #[error("linear interpolation gradient shape mismatch: expected {expected:?}, got {actual:?}")]
    GradientShape {
        /// Shape implied by the image and sampling grid.
        expected: Vec<usize>,
        /// Supplied upstream-gradient shape.
        actual: Vec<usize>,
    },
}

/// Interpolation contract or storage failure.
#[derive(Debug, thiserror::Error)]
pub enum InterpolationFailure<E> {
    /// The interpolation contract was violated.
    #[error(transparent)]
    Contract(#[from] InterpolationError),
    /// The selected backend rejected a storage operation.
    #[error("interpolation backend failure: {0}")]
    Backend(E),
}

struct Contract {
    batch: usize,
    channels: usize,
    input_spatial: Vec<usize>,
    output_spatial: Vec<usize>,
    input_points: usize,
    output_points: usize,
    output_shape: Vec<usize>,
}

fn checked_product(extents: &[usize]) -> Result<usize, InterpolationError> {
    extents
        .iter()
        .copied()
        .try_fold(1usize, usize::checked_mul)
        .ok_or(InterpolationError::SizeOverflow)
}

fn validate<const D: usize>(image: &[usize], grid: &[usize]) -> Result<Contract, InterpolationError>
where
    Dimension<D>: SupportedDimension,
{
    let rank = D + 2;
    if image.len() != rank {
        return Err(InterpolationError::ImageRank {
            dimension: D,
            expected: rank,
            actual: image.len(),
        });
    }
    if grid.len() != rank {
        return Err(InterpolationError::GridRank {
            dimension: D,
            expected: rank,
            actual: grid.len(),
        });
    }
    if image[0] != grid[0] {
        return Err(InterpolationError::BatchMismatch {
            image: image[0],
            grid: grid[0],
        });
    }
    if grid[1] != D {
        return Err(InterpolationError::GridChannels {
            expected: D,
            actual: grid[1],
        });
    }
    for (axis, &extent) in image[2..].iter().enumerate() {
        if extent == 0 {
            return Err(InterpolationError::EmptySpatialAxis { axis });
        }
    }
    let input_spatial = image[2..].to_vec();
    let output_spatial = grid[2..].to_vec();
    let input_points = checked_product(&input_spatial)?;
    let output_points = checked_product(&output_spatial)?;
    let output_shape = [image[0], image[1]]
        .into_iter()
        .chain(output_spatial.iter().copied())
        .collect::<Vec<_>>();
    checked_product(&output_shape)?;
    Ok(Contract {
        batch: image[0],
        channels: image[1],
        input_spatial,
        output_spatial,
        input_points,
        output_points,
        output_shape,
    })
}

fn spatial_offset(indices: &[usize], extents: &[usize]) -> usize {
    indices
        .iter()
        .zip(extents)
        .fold(0, |offset, (&index, &extent)| offset * extent + index)
}

/// Sample a 2-D or 3-D image at a voxel-coordinate grid.
///
/// `image` has shape `[batch, channel, spatial...]`; `grid` has shape
/// `[batch, D, output_spatial...]`. Coordinate channels follow image spatial
/// axis order. `D` is restricted to 2 or 3, while `P` selects boundary
/// behavior at compile time with zero runtime storage.
///
/// # Errors
///
/// Returns [`InterpolationError`] when ranks, batches, coordinate channels,
/// spatial extents, finite-coordinate requirement, or shape products violate
/// the contract.
pub fn linear_interpolation<T, const D: usize, B, P>(
    image: &Tensor<T, B>,
    grid: &Tensor<T, B>,
    _policy: P,
) -> Result<Tensor<T, B>, InterpolationFailure<B::Error>>
where
    T: Float + FloatElement,
    B: Backend + Default,
    P: BoundaryPolicy,
    Dimension<D>: SupportedDimension,
    B::DeviceBuffer<T>: CpuAddressableStorage<T> + CpuAddressableStorageMut<T>,
{
    let contract = validate::<D>(image.shape(), grid.shape())?;
    let image = image
        .to_contiguous()
        .map_err(InterpolationFailure::Backend)?;
    let grid = grid
        .to_contiguous()
        .map_err(InterpolationFailure::Backend)?;
    let image_values = image.as_slice();
    let grid_values = grid.as_slice();
    let output_len = checked_product(&contract.output_shape)?;
    let mut output = vec![T::ZERO; output_len];
    let corner_count = 1usize << D;

    for batch in 0..contract.batch {
        for point in 0..contract.output_points {
            let mut neighbours = [(0, 0, T::ZERO, T::ZERO); D];
            for (axis, entry) in neighbours.iter_mut().enumerate() {
                let coordinate = grid_values[(batch * D + axis) * contract.output_points + point];
                if !Float::is_finite(coordinate) {
                    return Err(InterpolationError::NonFiniteCoordinate { axis, point }.into());
                }
                *entry = P::neighbours(coordinate, contract.input_spatial[axis]);
            }
            for channel in 0..contract.channels {
                let base = (batch * contract.channels + channel) * contract.input_points;
                let mut value = T::ZERO;
                for corner in 0..corner_count {
                    let mut indices = [0; D];
                    let mut weight = T::ONE;
                    for (axis, &(lower, upper, lower_weight, upper_weight)) in
                        neighbours.iter().enumerate()
                    {
                        let upper_side = corner & (1 << axis) != 0;
                        indices[axis] = if upper_side { upper } else { lower };
                        weight *= if upper_side {
                            upper_weight
                        } else {
                            lower_weight
                        };
                    }
                    value += image_values[base + spatial_offset(&indices, &contract.input_spatial)]
                        * weight;
                }
                output[(batch * contract.channels + channel) * contract.output_points + point] =
                    value;
            }
        }
    }

    Tensor::from_slice_on(contract.output_shape, &output, &B::default())
        .map_err(InterpolationFailure::Backend)
}

/// Backpropagate through [`linear_interpolation`].
///
/// Returns gradients for `(image, grid)`. The image derivative scatters to
/// `2^D` neighbours. Each coordinate derivative differentiates the same
/// multilinear polynomial; replicated axes have zero derivative when both
/// neighbours resolve to one border element.
///
/// # Errors
///
/// Returns [`InterpolationError`] under the forward contract failures or when
/// `grad_output` does not have the implied output shape. Non-finite sampling
/// coordinates are rejected before derivative arithmetic.
pub fn linear_interpolation_backward<T, const D: usize, B, P>(
    image: &Tensor<T, B>,
    grid: &Tensor<T, B>,
    grad_output: &Tensor<T, B>,
    _policy: P,
) -> Result<InterpolationGradients<T, B>, InterpolationFailure<B::Error>>
where
    T: Float + FloatElement,
    B: Backend + Default,
    P: BoundaryPolicy,
    Dimension<D>: SupportedDimension,
    B::DeviceBuffer<T>: CpuAddressableStorage<T> + CpuAddressableStorageMut<T>,
{
    let contract = validate::<D>(image.shape(), grid.shape())?;
    if grad_output.shape() != contract.output_shape {
        return Err(InterpolationError::GradientShape {
            expected: contract.output_shape,
            actual: grad_output.shape().to_vec(),
        }
        .into());
    }
    let image = image
        .to_contiguous()
        .map_err(InterpolationFailure::Backend)?;
    let grid = grid
        .to_contiguous()
        .map_err(InterpolationFailure::Backend)?;
    let grad_output = grad_output
        .to_contiguous()
        .map_err(InterpolationFailure::Backend)?;
    let image_values = image.as_slice();
    let grid_values = grid.as_slice();
    let upstream = grad_output.as_slice();
    let mut image_gradient = vec![T::ZERO; image_values.len()];
    let mut grid_gradient = vec![T::ZERO; grid_values.len()];
    let corner_count = 1usize << D;

    for batch in 0..contract.batch {
        for point in 0..contract.output_points {
            let mut neighbours = [(0, 0, T::ZERO, T::ZERO); D];
            for (axis, entry) in neighbours.iter_mut().enumerate() {
                let coordinate = grid_values[(batch * D + axis) * contract.output_points + point];
                if !Float::is_finite(coordinate) {
                    return Err(InterpolationError::NonFiniteCoordinate { axis, point }.into());
                }
                *entry = P::neighbours(coordinate, contract.input_spatial[axis]);
            }
            for channel in 0..contract.channels {
                let base = (batch * contract.channels + channel) * contract.input_points;
                let output_index =
                    (batch * contract.channels + channel) * contract.output_points + point;
                let grad = upstream[output_index];
                for corner in 0..corner_count {
                    let mut indices = [0; D];
                    let mut weights = [T::ZERO; D];
                    for (axis, &(lower, upper, lower_weight, upper_weight)) in
                        neighbours.iter().enumerate()
                    {
                        let upper_side = corner & (1 << axis) != 0;
                        indices[axis] = if upper_side { upper } else { lower };
                        weights[axis] = if upper_side {
                            upper_weight
                        } else {
                            lower_weight
                        };
                    }
                    let input_index = base + spatial_offset(&indices, &contract.input_spatial);
                    let value = image_values[input_index];
                    let weight = weights.iter().copied().fold(T::ONE, |acc, w| acc * w);
                    image_gradient[input_index] += grad * weight;
                    for axis in 0..D {
                        let (lower, upper, _, _) = neighbours[axis];
                        if lower == upper {
                            continue;
                        }
                        let sign = if corner & (1 << axis) != 0 {
                            T::ONE
                        } else {
                            T::ZERO - T::ONE
                        };
                        let other_weight = weights
                            .iter()
                            .enumerate()
                            .filter(|(candidate, _)| *candidate != axis)
                            .map(|(_, weight)| *weight)
                            .fold(T::ONE, |acc, w| acc * w);
                        grid_gradient[(batch * D + axis) * contract.output_points + point] +=
                            grad * value * sign * other_weight;
                    }
                }
            }
        }
    }

    let backend = B::default();
    let image_shape = [contract.batch, contract.channels]
        .into_iter()
        .chain(contract.input_spatial)
        .collect::<Vec<_>>();
    let grid_shape = [contract.batch, D]
        .into_iter()
        .chain(contract.output_spatial)
        .collect::<Vec<_>>();
    Ok(InterpolationGradients {
        image: Tensor::from_slice_on(image_shape, &image_gradient, &backend)
            .map_err(InterpolationFailure::Backend)?,
        grid: Tensor::from_slice_on(grid_shape, &grid_gradient, &backend)
            .map_err(InterpolationFailure::Backend)?,
    })
}