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
mod depth_wise;
mod im2col;
#[cfg(test)]
pub mod proptest;
#[cfg(test)]
mod proptest_q;
mod q_sum_b;
mod unary;

use crate::internal::*;

pub use self::im2col::Im2Col;
pub(crate) use self::q_sum_b::QSumB;
pub use self::unary::ConvUnary;

#[derive(Debug, Copy, Clone, PartialEq, Hash)]
pub enum KernelFormat {
    OIHW,
    HWIO,
}

impl Default for KernelFormat {
    fn default() -> KernelFormat {
        KernelFormat::OIHW
    }
}

impl KernelFormat {
    pub fn h_axis(&self) -> usize {
        match self {
            KernelFormat::OIHW => 2,
            KernelFormat::HWIO => 0,
        }
    }

    pub fn spatial_shape<'a, D: DimLike>(&self, full_shape: &'a [D]) -> &'a [D] {
        &full_shape[self.h_axis()..][..full_shape.len() - 2]
    }

    pub fn i<'a, D: DimLike>(&self, full_shape: &'a [D]) -> &'a D {
        match self {
            KernelFormat::OIHW => &full_shape[1],
            KernelFormat::HWIO => &full_shape[full_shape.len() - 2],
        }
    }

    pub fn o<'a, D: DimLike>(&self, full_shape: &'a [D]) -> &'a D {
        match self {
            KernelFormat::OIHW => &full_shape[0],
            KernelFormat::HWIO => &full_shape[full_shape.len() - 1],
        }
    }

    pub fn kernel_as_group_o_ihw(
        &self,
        kernel: &Tensor,
        group: usize,
        input_channels: usize,
        output_channels: usize,
    ) -> TractResult<Arc<Tensor>> {
        let final_shape = [group, output_channels / group, kernel.len() / output_channels];
        trace!("kernel shape (group, output, rest) = {:?}", final_shape);
        let hw_rank = kernel.rank() - 2;
        match self {
            KernelFormat::HWIO => {
                let mut shape = kernel.shape().to_vec();
                shape.insert(hw_rank + 1, group); // HWIGO
                shape[kernel.rank() - 2] = input_channels / group;
                let mut kernel = kernel.clone();
                kernel.set_shape(&shape)?;
                let mut permutation: Vec<usize> = vec![hw_rank + 1, hw_rank + 2, hw_rank];
                permutation.extend(0..hw_rank);
                let mut kernel = kernel.permute_axes(&permutation)?;
                kernel.set_shape(&final_shape)?;
                Ok(kernel.into_arc_tensor())
            }
            KernelFormat::OIHW => {
                Ok(kernel.clone().into_shape(&final_shape)?.into_arc_tensor())
            }
        }
    }
}