coeus-nn 0.14.0

Neural-network layers and 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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
// ── Adaptive Pooling NN modules ──
//
// AdaptiveAvgPool1d / AdaptiveAvgPool2d / AdaptiveMaxPool1d / AdaptiveMaxPool2d:
//   Stateless modules where the user specifies the output spatial size rather
//   than the kernel/stride.  The pooling regions are computed dynamically to
//   evenly cover the input spatial extent.
//
//   Matches PyTorch `nn.AdaptiveAvgPool1d(output_size)` etc.
//
// ZST phantom markers provide zero-overhead type safety without any allocation.

use crate::module::{Module, ModuleError};
use coeus_autograd::Var;
use coeus_core::{CpuAddressableStorage, CpuAddressableStorageMut, Float, MoiraiBackend, Scalar};
use coeus_tensor::Tensor;
use std::marker::PhantomData;

/// Transposed averaging matrix `P_T` `[in_len, out_len]` for adaptive average
/// pooling along one axis. Output column `o` carries `1/region` in the rows of
/// its input region `[floor(o*in/out), ceil((o+1)*in/out))` — PyTorch's adaptive
/// region convention — and zero elsewhere. `input @ P_T` then averages each
/// region; being a constant matmul it is differentiable (the backward scatters
/// the per-region-averaged gradient back to every input position in the region).
fn avg_pool_matrix_t<T: Float + coeus_core::FloatElement, B: coeus_ops::BackendOps<T> + Default>(
    in_len: usize,
    out_len: usize,
    backend: &B,
) -> Result<Var<T, B>, B::Error>
where
    B::DeviceBuffer<T>: CpuAddressableStorage<T> + CpuAddressableStorageMut<T>,
{
    let mut pt = vec![T::ZERO; in_len * out_len];
    for o in 0..out_len {
        let start = o * in_len / out_len;
        let end = ((o + 1) * in_len).div_ceil(out_len);
        let inv = <T as coeus_core::FloatElement>::from_count_reciprocal(end - start);
        // Column `o`, rows `start..end`: flat index `l * out_len + o`.
        for slot in pt
            .iter_mut()
            .skip(start * out_len + o)
            .step_by(out_len)
            .take(end - start)
        {
            *slot = inv;
        }
    }
    Var::new(
        Tensor::from_slice_on([in_len, out_len], &pt, backend)?,
        false,
    )
}

/// Adaptive **max** pool over the last axis of a 2D view `[rows, in_len]` →
/// `[rows, out_len]`. Each output takes the max over its adaptive input region
/// (PyTorch's region convention). Differentiable: non-region positions are
/// filled with `-inf` and `max_axis` routes the gradient to each region's
/// argmax. The transient `[rows, out_len, in_len]` mask is `out_len`× the slice
/// — modest for typical pools; an argmax-scatter kernel would avoid it.
fn masked_adaptive_max<
    T: Float + coeus_core::FloatElement + coeus_cpu::RealScalar,
    B: coeus_ops::BackendOps<T> + Default,
>(
    x2: &Var<T, B>,
    rows: usize,
    in_len: usize,
    out_len: usize,
    backend: &B,
) -> Result<Var<T, B>, B::Error>
where
    B::DeviceBuffer<T>: CpuAddressableStorage<T> + CpuAddressableStorageMut<T>,
{
    // outside[o, l] = 1 where l is NOT in region o → filled with -inf below.
    let mut outside = vec![T::ONE; out_len * in_len];
    for o in 0..out_len {
        let start = o * in_len / out_len;
        let end = ((o + 1) * in_len).div_ceil(out_len);
        outside[o * in_len + start..o * in_len + end].fill(T::ZERO);
    }
    let outside_var = Var::new(
        Tensor::from_slice_on([1, out_len, in_len], &outside, backend)?,
        false,
    )?;
    let xb = coeus_autograd::broadcast_to(
        &coeus_autograd::reshape(x2, [rows, 1, in_len])?,
        vec![rows, out_len, in_len],
    )?;
    let ob = coeus_autograd::broadcast_to(&outside_var, vec![rows, out_len, in_len])?;
    let masked = coeus_autograd::masked_fill(
        &xb,
        &ob,
        <T as coeus_core::FloatElement>::from_f64(f64::NEG_INFINITY),
    )?;
    coeus_autograd::max_axis(&masked, 2)
}

// ── AdaptiveAvgPool1d ─────────────────────────────────────────────────────────

/// Adaptive average pooling for `[N, C, L]` → `[N, C, output_size]`.
///
/// Matches PyTorch `nn.AdaptiveAvgPool1d(output_size)`.  Each output position
/// pools over a region of the input whose size is determined by the ratio
/// `L / output_size`, with ceiling/floor arithmetic for non-divisible sizes.
///
/// # Examples
///
/// ```
/// use coeus_nn::{AdaptiveAvgPool1d, Module};
/// use coeus_autograd::Var;
/// use coeus_tensor::Tensor;
/// use coeus_core::SequentialBackend;
///
/// let m = AdaptiveAvgPool1d::<f32, SequentialBackend>::new(2);
/// let x = Var::new(
///     Tensor::<f32, SequentialBackend>::ones([1, 3, 8])
///         .expect("invariant: example shape allocation succeeds"),
///     false,
/// ).expect("invariant: constant example variable needs no gradient buffer");
/// let y = m.forward(&x).expect("valid AdaptiveAvgPool1d input");
/// assert_eq!(y.tensor.shape(), &[1, 3, 2]);
/// ```
#[derive(Clone, Debug)]
pub struct AdaptiveAvgPool1d<T: Scalar, B: coeus_ops::BackendOps<T> + Default = MoiraiBackend> {
    /// Target spatial output length.
    output_size: usize,
    _marker: PhantomData<(T, B)>,
}

impl<T: coeus_core::FloatElement + Scalar, B: coeus_ops::BackendOps<T> + Default>
    AdaptiveAvgPool1d<T, B>
{
    /// Create an `AdaptiveAvgPool1d` with the given output size.
    pub const fn new(output_size: usize) -> Self {
        Self {
            output_size,
            _marker: PhantomData,
        }
    }
}

impl<
        T: coeus_core::FloatElement + Float + coeus_cpu::RealScalar,
        B: coeus_ops::BackendOps<T> + Default,
    > Module<T, B> for AdaptiveAvgPool1d<T, B>
where
    B::DeviceBuffer<T>: CpuAddressableStorage<T> + CpuAddressableStorageMut<T>,
{
    fn parameters(&self) -> Vec<Var<T, B>> {
        vec![]
    }

    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
        // Differentiable: average each adaptive region via a constant averaging
        // matmul over the length axis.  [N, C, L] -> [N*C, L] @ P_T[L, O].
        let shape = input.tensor.shape_cloned();
        if shape.len() != 3 {
            return Err(ModuleError::InvalidRank {
                module: "AdaptiveAvgPool1d",
                expected: "3",
                actual: shape.len(),
            });
        }
        let (n, c, l) = (shape[0], shape[1], shape[2]);
        let o = self.output_size;
        if l == 0 || o == 0 {
            return Err(ModuleError::ShapeMismatch {
                module: "AdaptiveAvgPool1d",
                parameter: "spatial input and output dimensions",
                expected: vec![1, 1],
                actual: vec![l, o],
            });
        }
        let backend = B::default();
        let p_t = avg_pool_matrix_t::<T, B>(l, o, &backend)?;
        let x2 = coeus_autograd::reshape(input, [n * c, l])?;
        let out2 = coeus_autograd::matmul(&x2, &p_t)?;
        Ok(coeus_autograd::reshape(&out2, [n, c, o])?)
    }
}

// ── AdaptiveAvgPool2d ─────────────────────────────────────────────────────────

/// Adaptive average pooling for `[N, C, H, W]` → `[N, C, out_h, out_w]`.
///
/// Matches PyTorch `nn.AdaptiveAvgPool2d((out_h, out_w))`.  Commonly used as
/// the final spatial pooling stage in CNN classifiers (e.g., ResNet).
///
/// # Examples
///
/// ```
/// use coeus_nn::{AdaptiveAvgPool2d, Module};
/// use coeus_autograd::Var;
/// use coeus_tensor::Tensor;
/// use coeus_core::SequentialBackend;
///
/// let m = AdaptiveAvgPool2d::<f32, SequentialBackend>::new(1, 1);
/// let x = Var::new(
///     Tensor::<f32, SequentialBackend>::ones([2, 4, 8, 8])
///         .expect("invariant: example shape allocation succeeds"),
///     false,
/// ).expect("invariant: constant example variable needs no gradient buffer");
/// let y = m.forward(&x).expect("valid AdaptiveAvgPool2d input");
/// assert_eq!(y.tensor.shape(), &[2, 4, 1, 1]);
/// ```
#[derive(Clone, Debug)]
pub struct AdaptiveAvgPool2d<T: Scalar, B: coeus_ops::BackendOps<T> + Default = MoiraiBackend> {
    /// Target output height.
    out_h: usize,
    /// Target output width.
    out_w: usize,
    _marker: PhantomData<(T, B)>,
}

impl<T: coeus_core::FloatElement + Scalar, B: coeus_ops::BackendOps<T> + Default>
    AdaptiveAvgPool2d<T, B>
{
    /// Create an `AdaptiveAvgPool2d` pooling to `(out_h, out_w)` output size.
    pub const fn new(out_h: usize, out_w: usize) -> Self {
        Self {
            out_h,
            out_w,
            _marker: PhantomData,
        }
    }

    /// Create an `AdaptiveAvgPool2d` pooling to a square `(size, size)` output.
    pub const fn square(size: usize) -> Self {
        Self::new(size, size)
    }
}

impl<
        T: coeus_core::FloatElement + Float + coeus_cpu::RealScalar,
        B: coeus_ops::BackendOps<T> + Default,
    > Module<T, B> for AdaptiveAvgPool2d<T, B>
where
    B::DeviceBuffer<T>: CpuAddressableStorage<T> + CpuAddressableStorageMut<T>,
{
    fn parameters(&self) -> Vec<Var<T, B>> {
        vec![]
    }

    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
        // Differentiable separable pooling: average over W, then over H, each a
        // constant averaging matmul. Averaging is separable so this equals the
        // joint 2D adaptive average.
        let shape = input.tensor.shape_cloned();
        if shape.len() != 4 {
            return Err(ModuleError::InvalidRank {
                module: "AdaptiveAvgPool2d",
                expected: "4",
                actual: shape.len(),
            });
        }
        let (n, c, h, w) = (shape[0], shape[1], shape[2], shape[3]);
        let (oh, ow) = (self.out_h, self.out_w);
        if h == 0 || w == 0 || oh == 0 || ow == 0 {
            return Err(ModuleError::ShapeMismatch {
                module: "AdaptiveAvgPool2d",
                parameter: "spatial input and output dimensions",
                expected: vec![1; 4],
                actual: vec![h, w, oh, ow],
            });
        }
        let backend = B::default();

        // Fast path for global (1×1) pooling: sequential mean_axis reductions
        // avoid allocating the O(H*W) averaging matrix.
        if oh == 1 && ow == 1 {
            let after_h = coeus_autograd::mean_axis(input, 2)?; // [N, C, 1, W]
            return Ok(coeus_autograd::mean_axis(&after_h, 3)?); // [N, C, 1, 1]
        }

        // Pool W: [N, C, H, W] -> [N*C*H, W] @ PW_T[W, OW] -> [N, C, H, OW].
        let pw_t = avg_pool_matrix_t::<T, B>(w, ow, &backend)?;
        let yw = coeus_autograd::matmul(&coeus_autograd::reshape(input, [n * c * h, w])?, &pw_t)?;
        let yw = coeus_autograd::reshape(&yw, [n, c, h, ow])?;

        // Pool H: bring H last, [N, C, OW, H] -> [N*C*OW, H] @ PH_T[H, OH].
        let ph_t = avg_pool_matrix_t::<T, B>(h, oh, &backend)?;
        let yw_p = coeus_autograd::permute(&yw, &[0, 1, 3, 2])?;
        let yh = coeus_autograd::matmul(&coeus_autograd::reshape(&yw_p, [n * c * ow, h])?, &ph_t)?;
        let yh = coeus_autograd::reshape(&yh, [n, c, ow, oh])?;
        // Final transpose to [N, C, OH, OW]; reshape materializes it contiguous.
        let out = coeus_autograd::permute(&yh, &[0, 1, 3, 2])?;
        Ok(coeus_autograd::reshape(&out, [n, c, oh, ow])?)
    }
}

// ── AdaptiveMaxPool1d ─────────────────────────────────────────────────────────

/// Adaptive max pooling for `[N, C, L]` → `[N, C, output_size]`.
///
/// Matches PyTorch `nn.AdaptiveMaxPool1d(output_size)`.
#[derive(Clone, Debug)]
pub struct AdaptiveMaxPool1d<T: Scalar, B: coeus_ops::BackendOps<T> + Default = MoiraiBackend> {
    /// Target spatial output length.
    output_size: usize,
    _marker: PhantomData<(T, B)>,
}

impl<T: coeus_core::FloatElement + Scalar, B: coeus_ops::BackendOps<T> + Default>
    AdaptiveMaxPool1d<T, B>
{
    /// Create an `AdaptiveMaxPool1d` with the given output size.
    pub const fn new(output_size: usize) -> Self {
        Self {
            output_size,
            _marker: PhantomData,
        }
    }
}

impl<
        T: coeus_core::FloatElement + Float + coeus_cpu::RealScalar,
        B: coeus_ops::BackendOps<T> + Default,
    > Module<T, B> for AdaptiveMaxPool1d<T, B>
where
    B::DeviceBuffer<T>: CpuAddressableStorage<T> + CpuAddressableStorageMut<T>,
{
    fn parameters(&self) -> Vec<Var<T, B>> {
        vec![]
    }

    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
        // Direct region-maximum loop: one strided pass over the input with no
        // [rows, out_len, in_len] broadcast intermediate (previously ~20ms on
        // the standard fixture; COEUS-ADAPTIVE-MAX-POOL1D-PERF). Region maxima
        // use strict `>`, so the first maximum wins; a NaN wins only when it
        // is the first element of its region.
        let shape = input.tensor.shape_cloned();
        if shape.len() != 3 {
            return Err(ModuleError::InvalidRank {
                module: "AdaptiveMaxPool1d",
                expected: "3",
                actual: shape.len(),
            });
        }
        let (n, c, l) = (shape[0], shape[1], shape[2]);
        let o = self.output_size;
        if l == 0 || o == 0 {
            return Err(ModuleError::ShapeMismatch {
                module: "AdaptiveMaxPool1d",
                parameter: "spatial input and output dimensions",
                expected: vec![1, 1],
                actual: vec![l, o],
            });
        }
        let backend = B::default();
        // SAFETY: every output element is written by the loop below before the
        // tensor is read.
        let mut out_tensor = unsafe { Tensor::alloc_on([n, c, o], &backend) }?;
        let (out_storage, out_layout) = out_tensor.storage_mut_and_layout()?;
        let out_buf = out_storage.as_mut_slice()?;
        let (out_off, out_st) = (out_layout.offset(), out_layout.strides());
        let in_buf = input.tensor.storage().as_slice();
        let in_layout = input.tensor.layout();
        let (in_off, in_st) = (in_layout.offset(), in_layout.strides());
        for n_i in 0..n {
            for c_i in 0..c {
                let in_base = in_off + n_i * in_st[0] + c_i * in_st[1];
                let out_base = out_off + n_i * out_st[0] + c_i * out_st[1];
                for o_i in 0..o {
                    let (start, end) = coeus_autograd::ops::nn::pool::adaptive_region(o_i, l, o);
                    let mut best = in_buf[in_base + start * in_st[2]];
                    for i in (start + 1)..end {
                        let v = in_buf[in_base + i * in_st[2]];
                        if v > best {
                            best = v;
                        }
                    }
                    out_buf[out_base + o_i * out_st[2]] = best;
                }
            }
        }
        Ok(coeus_autograd::adaptive_max_pool1d(
            input, out_tensor, l, o,
        )?)
    }
}

// ── AdaptiveMaxPool2d ─────────────────────────────────────────────────────────

/// Adaptive max pooling for `[N, C, H, W]` → `[N, C, out_h, out_w]`.
///
/// Matches PyTorch `nn.AdaptiveMaxPool2d((out_h, out_w))`.
#[derive(Clone, Debug)]
pub struct AdaptiveMaxPool2d<T: Scalar, B: coeus_ops::BackendOps<T> + Default = MoiraiBackend> {
    /// Target output height.
    out_h: usize,
    /// Target output width.
    out_w: usize,
    _marker: PhantomData<(T, B)>,
}

impl<T: coeus_core::FloatElement + Scalar, B: coeus_ops::BackendOps<T> + Default>
    AdaptiveMaxPool2d<T, B>
{
    /// Create an `AdaptiveMaxPool2d` pooling to `(out_h, out_w)` output size.
    pub const fn new(out_h: usize, out_w: usize) -> Self {
        Self {
            out_h,
            out_w,
            _marker: PhantomData,
        }
    }

    /// Create an `AdaptiveMaxPool2d` pooling to a square `(size, size)` output.
    pub const fn square(size: usize) -> Self {
        Self::new(size, size)
    }
}

impl<
        T: coeus_core::FloatElement + Float + coeus_cpu::RealScalar,
        B: coeus_ops::BackendOps<T> + Default,
    > Module<T, B> for AdaptiveMaxPool2d<T, B>
where
    B::DeviceBuffer<T>: CpuAddressableStorage<T> + CpuAddressableStorageMut<T>,
{
    fn parameters(&self) -> Vec<Var<T, B>> {
        vec![]
    }

    fn forward(&self, input: &Var<T, B>) -> Result<Var<T, B>, ModuleError<B::Error>> {
        // Differentiable separable max pooling: max over W, then over H (max of a
        // 2D region equals the max of per-axis maxes), each a masked max_axis.
        let shape = input.tensor.shape_cloned();
        if shape.len() != 4 {
            return Err(ModuleError::InvalidRank {
                module: "AdaptiveMaxPool2d",
                expected: "4",
                actual: shape.len(),
            });
        }
        let (n, c, h, w) = (shape[0], shape[1], shape[2], shape[3]);
        let (oh, ow) = (self.out_h, self.out_w);
        if h == 0 || w == 0 || oh == 0 || ow == 0 {
            return Err(ModuleError::ShapeMismatch {
                module: "AdaptiveMaxPool2d",
                parameter: "spatial input and output dimensions",
                expected: vec![1; 4],
                actual: vec![h, w, oh, ow],
            });
        }
        let backend = B::default();

        // Fast path for global (1×1) max pooling: sequential max_axis reductions.
        if oh == 1 && ow == 1 {
            let after_h = coeus_autograd::max_axis(input, 2)?; // [N, C, 1, W]
            return Ok(coeus_autograd::max_axis(&after_h, 3)?); // [N, C, 1, 1]
        }

        // Pool W: [N, C, H, W] -> [N*C*H, W] -> [N*C*H, OW] -> [N, C, H, OW].
        let xw = coeus_autograd::reshape(input, [n * c * h, w])?;
        let pw = masked_adaptive_max::<T, B>(&xw, n * c * h, w, ow, &backend)?;
        let yw = coeus_autograd::reshape(&pw, [n, c, h, ow])?;

        // Pool H: bring H last, [N, C, OW, H] -> [N*C*OW, H] -> [N*C*OW, OH].
        let yw_p = coeus_autograd::permute(&yw, &[0, 1, 3, 2])?;
        let ph = masked_adaptive_max::<T, B>(
            &coeus_autograd::reshape(&yw_p, [n * c * ow, h])?,
            n * c * ow,
            h,
            oh,
            &backend,
        )?;
        let yh = coeus_autograd::reshape(&ph, [n, c, ow, oh])?;
        let out = coeus_autograd::permute(&yh, &[0, 1, 3, 2])?;
        Ok(coeus_autograd::reshape(&out, [n, c, oh, ow])?)
    }
}