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
//! N-dimensional convolution layers.
use super::Path;
use crate::{TchError, Tensor};
use std::borrow::Borrow;

/// How padding is performed by convolution operations
/// on the edge of the input tensor.
#[derive(Debug, Clone, Copy)]
pub enum PaddingMode {
    Zeros,
    Reflect,
    Replicate,
    Circular,
}

impl PaddingMode {
    fn to_string(self) -> &'static str {
        // This has to match the internal representation used on the C++
        // side.
        match self {
            // The default value when using constant is zero.
            PaddingMode::Zeros => "constant",
            PaddingMode::Reflect => "reflect",
            PaddingMode::Replicate => "replicate",
            PaddingMode::Circular => "circular",
        }
    }

    pub fn f_pad(
        self,
        xs: &Tensor,
        reversed_padding_repeated_twice: &[i64],
    ) -> Result<Tensor, TchError> {
        xs.f_pad(reversed_padding_repeated_twice, self.to_string(), None)
    }

    pub fn pad(self, xs: &Tensor, reversed_padding_repeated_twice: &[i64]) -> Tensor {
        xs.pad(reversed_padding_repeated_twice, self.to_string(), None)
    }
}

/// Generic convolution config.
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, Clone, Copy)]
pub struct ConvConfigND<ND> {
    pub stride: ND,
    pub padding: ND,
    pub dilation: ND,
    pub groups: i64,
    pub bias: bool,
    pub ws_init: super::Init,
    pub bs_init: super::Init,
    pub padding_mode: PaddingMode,
}

/// Convolution config using the same parameters on all dimensions.
pub type ConvConfig = ConvConfigND<i64>;

impl Default for ConvConfig {
    fn default() -> Self {
        ConvConfig {
            stride: 1,
            padding: 0,
            dilation: 1,
            groups: 1,
            bias: true,
            ws_init: super::init::DEFAULT_KAIMING_UNIFORM,
            bs_init: super::Init::Const(0.),
            padding_mode: PaddingMode::Zeros,
        }
    }
}

impl Default for ConvConfigND<[i64; 2]> {
    fn default() -> Self {
        ConvConfigND::<[i64; 2]> {
            stride: [1, 1],
            padding: [0, 0],
            dilation: [1, 1],
            groups: 1,
            bias: true,
            ws_init: super::init::DEFAULT_KAIMING_UNIFORM,
            bs_init: super::Init::Const(0.),
            padding_mode: PaddingMode::Zeros,
        }
    }
}

/// The default convolution config without bias.
pub fn no_bias() -> ConvConfig {
    ConvConfig { bias: false, ..Default::default() }
}

// Use const generics when they have landed in stable rust.
/// A N-dimensional convolution layer.
#[derive(Debug)]
pub struct Conv<ND> {
    pub ws: Tensor,
    pub bs: Option<Tensor>,
    reversed_padding_repeated_twice: Vec<i64>,
    config: ConvConfigND<ND>,
}

/// One dimension convolution layer.
pub type Conv1D = Conv<[i64; 1]>;

/// Two dimensions convolution layer.
pub type Conv2D = Conv<[i64; 2]>;

/// Three dimensions convolution layer.
pub type Conv3D = Conv<[i64; 3]>;

/// Creates a new convolution layer for any number of dimensions.
pub fn conv<'a, ND: std::convert::AsRef<[i64]>, T: Borrow<super::Path<'a>>>(
    vs: T,
    in_dim: i64,
    out_dim: i64,
    ksizes: ND,
    config: ConvConfigND<ND>,
) -> Conv<ND> {
    let vs = vs.borrow();
    let bs = if config.bias { Some(vs.var("bias", &[out_dim], config.bs_init)) } else { None };
    let mut weight_size = vec![out_dim, in_dim / config.groups];
    weight_size.extend(ksizes.as_ref().iter());
    let ws = vs.var("weight", weight_size.as_slice(), config.ws_init);
    let mut reversed_padding_repeated_twice = vec![];
    for &v in config.padding.as_ref().iter().rev() {
        reversed_padding_repeated_twice.push(v)
    }
    for &v in config.padding.as_ref().iter().rev() {
        reversed_padding_repeated_twice.push(v)
    }
    Conv { ws, bs, config, reversed_padding_repeated_twice }
}

trait Create: std::convert::AsRef<[i64]> + std::marker::Sized {
    fn make_array(i: i64) -> Self;

    fn conv<'a, T: Borrow<super::Path<'a>>>(
        vs: T,
        in_dim: i64,
        out_dim: i64,
        ksize: i64,
        config: ConvConfig,
    ) -> Conv<Self> {
        let config = ConvConfigND::<Self> {
            stride: Self::make_array(config.stride),
            padding: Self::make_array(config.padding),
            dilation: Self::make_array(config.dilation),
            groups: config.groups,
            bias: config.bias,
            ws_init: config.ws_init,
            bs_init: config.bs_init,
            padding_mode: config.padding_mode,
        };
        conv(vs, in_dim, out_dim, Self::make_array(ksize), config)
    }
}

impl Create for [i64; 1] {
    fn make_array(i: i64) -> Self {
        [i]
    }
}

impl Create for [i64; 2] {
    fn make_array(i: i64) -> Self {
        [i, i]
    }
}

impl Create for [i64; 3] {
    fn make_array(i: i64) -> Self {
        [i, i, i]
    }
}

/// Creates a new one dimension convolution layer.
pub fn conv1d<'a, T: Borrow<Path<'a>>>(vs: T, i: i64, o: i64, k: i64, c: ConvConfig) -> Conv1D {
    <[i64; 1]>::conv(vs, i, o, k, c)
}

/// Creates a new two dimension convolution layer.
pub fn conv2d<'a, T: Borrow<Path<'a>>>(vs: T, i: i64, o: i64, k: i64, c: ConvConfig) -> Conv2D {
    <[i64; 2]>::conv(vs, i, o, k, c)
}

/// Creates a new three dimension convolution layer.
pub fn conv3d<'a, T: Borrow<Path<'a>>>(vs: T, i: i64, o: i64, k: i64, c: ConvConfig) -> Conv3D {
    <[i64; 3]>::conv(vs, i, o, k, c)
}

impl super::module::Module for Conv1D {
    fn forward(&self, xs: &Tensor) -> Tensor {
        let (xs, padding) = match self.config.padding_mode {
            PaddingMode::Zeros => (xs.shallow_clone(), self.config.padding),
            p => (p.pad(xs, &self.reversed_padding_repeated_twice), [0]),
        };
        xs.conv1d(
            &self.ws,
            self.bs.as_ref(),
            self.config.stride,
            padding,
            self.config.dilation,
            self.config.groups,
        )
    }
}

impl super::module::Module for Conv2D {
    fn forward(&self, xs: &Tensor) -> Tensor {
        let (xs, padding) = match self.config.padding_mode {
            PaddingMode::Zeros => (xs.shallow_clone(), self.config.padding),
            p => (p.pad(xs, &self.reversed_padding_repeated_twice), [0, 0]),
        };
        xs.conv2d(
            &self.ws,
            self.bs.as_ref(),
            self.config.stride,
            padding,
            self.config.dilation,
            self.config.groups,
        )
    }
}

impl super::module::Module for Conv3D {
    fn forward(&self, xs: &Tensor) -> Tensor {
        let (xs, padding) = match self.config.padding_mode {
            PaddingMode::Zeros => (xs.shallow_clone(), self.config.padding),
            p => (p.pad(xs, &self.reversed_padding_repeated_twice), [0, 0, 0]),
        };
        xs.conv3d(
            &self.ws,
            self.bs.as_ref(),
            self.config.stride,
            padding,
            self.config.dilation,
            self.config.groups,
        )
    }
}