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
use super::*;
pub struct MaxPool2D {
pub pad: usize,
pub stride: usize,
pub size: usize,
}
pub struct MaxPool2DGrad {
pad: usize,
stride: usize,
size: usize,
}
pub struct MaxPool2DGradGrad {
pad: usize,
stride: usize,
size: usize,
}
macro_rules! impl_max_pool {
($t:ty, $i:ident) => {
unsafe fn $i<T: Float>(
input: *const T,
pad: usize,
xh: usize,
xw: usize,
yh: usize,
yw: usize,
ch: usize,
batch: usize,
size: usize,
stride: usize,
) -> (Vec<T>, Vec<T>) {
let all_len_y = batch * ch * yh * yw;
let mut indices = Vec::with_capacity(all_len_y);
let mut output = Vec::with_capacity(all_len_y);
for b in 0..batch {
for c in 0..ch {
let c_base = xh * (c + b * ch);
for i in 0..yh {
let i_base = yw * (i + yh * (c + b * ch));
let mut h_start = i * stride - pad;
let h_end = if h_start + size > xh {
xh
} else {
h_start + size
};
h_start = h_start * (h_start > 0) as usize;
for j in 0..yw {
let mut max = T::min_value();
let mut max_i = 0;
let mut w_start = j * stride - pad;
let w_end = if w_start + size > xw {
xw
} else {
w_start + size
};
w_start = w_start * (w_start > 0) as usize;
for h in h_start..h_end {
let rows = xw * (h + c_base);
for w in w_start..w_end {
let index = w + rows;
let val = *input.add(index);
if val > max {
max_i = index;
max = val;
}
}
}
let out_index = j + i_base;
*output.get_unchecked_mut(out_index) = max;
*indices.get_unchecked_mut(out_index) =
*(&(max_i as $t) as *const $t as *const T)
}
}
}
}
output.set_len(all_len_y);
indices.set_len(all_len_y);
(output, indices)
}
};
}
impl_max_pool!(f32, max_pool_f32);
impl_max_pool!(f64, max_pool_f64);
#[test]
fn test_max_pool() {
let x = vec![0., 1., 2., 5., 4., 3., 6., 7., 8.];
let (output, argmax) = unsafe {
max_pool_f64(
x.as_ptr(),
0,
3,
3,
2,
2,
1,
1,
2,
1,
)
};
assert_eq!(output, vec![5., 4., 7., 8.]);
assert_eq!(argmax, vec![3., 4., 7., 8.]);
}
macro_rules! impl_max_pool_grad {
($t:ty, $i:ident) => {
fn $i<T: Float>(
batch: usize,
mut gy: *const T,
xh: usize,
xw: usize,
yh: usize,
yw: usize,
c: usize,
mut argmax: *const $t,
) -> Vec<T> {
let mut ret = vec![T::zero(); batch * c * xh * xw];
let gx = ret.as_mut_ptr();
for _ in 0..yh * yw * c * batch {
unsafe {
*gx.offset(*argmax as isize) += *gy;
argmax = argmax.offset(1);
gy = gy.offset(1);
}
}
ret
}
};
}
macro_rules! impl_max_pool_grad_grad {
($t:ty, $i:ident) => {
unsafe fn $i<T: Float>(
ggx: *const T,
yh: usize,
yw: usize,
c: usize,
batch: usize,
mut argmax: *const $t,
) -> Vec<T> {
let len = yh * yw * c * batch;
let mut ret = Vec::with_capacity(len);
let mut ggy = ret.as_mut_ptr();
for _ in 0..len {
*ggy = *ggx.offset(*argmax as isize);
ggy = ggy.offset(1);
argmax = argmax.offset(1);
}
ret.set_len(len);
ret
}
};
}
impl_max_pool_grad!(f32, max_pool_grad_f32);
impl_max_pool_grad!(f64, max_pool_grad_f64);
impl_max_pool_grad_grad!(f32, max_pool_grad_grad_f32);
impl_max_pool_grad_grad!(f64, max_pool_grad_grad_f64);
impl<T: Float> crate::op::Op<T> for MaxPool2D {
fn compute(&self, ctx: &mut crate::op::ComputeContext<T>) -> Result<(), crate::op::OpError> {
let x = &ctx.input(0);
let x_shape = x.shape();
let batch = x_shape[0];
let c = x_shape[1];
let xh = x_shape[2];
let xw = x_shape[3];
let copied_x;
let x = if x.is_standard_layout() {
x.as_ptr()
} else {
copied_x = ndarray_ext::deep_copy(x);
copied_x.as_ptr()
};
let yh = (xh + 2 * self.pad - self.size) / self.stride + 1;
let yw = (xw + 2 * self.pad - self.size) / self.stride + 1;
let (output, indices) = unsafe {
if same_type::<T, f32>() {
max_pool_f32(
x,
self.pad,
xh,
xw,
yh,
yw,
c,
batch,
self.size,
self.stride,
)
} else if same_type::<T, f64>() {
max_pool_f64(
x,
self.pad,
xh,
xw,
yh,
yw,
c,
batch,
self.size,
self.stride,
)
} else {
return Err(op::OpError::TypeUnsupported(
"MaxPool supports only f32 and f64".to_string(),
));
}
};
unsafe {
let output =
NdArray::from_shape_vec_unchecked(ndarray::IxDyn(&[batch, c, yh, yw]), output);
let indices =
NdArray::from_shape_vec_unchecked(ndarray::IxDyn(&[batch, c, yh, yw]), indices);
ctx.append_output(output);
ctx.append_output(indices);
}
Ok(())
}
fn grad(&self, ctx: &mut crate::op::GradientContext<T>) {
let gy = &ctx.output_grad();
let y = &ctx.output();
let indices = nth_tensor(y, 1);
let gx = Tensor::builder(ctx.graph())
.append_input(gy, false)
.append_input(&indices, false)
.build(MaxPool2DGrad {
pad: self.pad,
stride: self.stride,
size: self.size,
});
ctx.append_input_grad(Some(gx));
}
}
impl<T: Float> crate::op::Op<T> for MaxPool2DGrad {
fn compute(&self, ctx: &mut crate::op::ComputeContext<T>) -> Result<(), crate::op::OpError> {
let gy = &ctx.input(0);
let argmax = &ctx.input(1);
let gy_shape = gy.shape();
let batch = gy_shape[0];
let c = gy_shape[1];
let yh = gy_shape[2];
let yw = gy_shape[3];
let copied_gy;
let gy = if gy.is_standard_layout() {
gy.as_ptr()
} else {
copied_gy = ndarray_ext::deep_copy(gy);
copied_gy.as_ptr()
};
let xh = self.stride * (yh - 1) - 2 * self.pad + self.size;
let xw = self.stride * (yw - 1) - 2 * self.pad + self.size;
let gx = if same_type::<T, f32>() {
max_pool_grad_f32(batch, gy, xh, xw, yh, yw, c, argmax.as_ptr() as *const f32)
} else if same_type::<T, f64>() {
max_pool_grad_f64(batch, gy, xh, xw, yh, yw, c, argmax.as_ptr() as *const f64)
} else {
return Err(op::OpError::TypeUnsupported(
"MaxPool2DGrad supports only f32 and f64".to_string(),
));
};
unsafe {
let gx = NdArray::from_shape_vec_unchecked(ndarray::IxDyn(&[batch, c, xh, xw]), gx);
ctx.append_output(gx);
}
Ok(())
}
fn grad(&self, ctx: &mut crate::op::GradientContext<T>) {
let ggx = &ctx.output_grad();
let argmax = &ctx.input(1);
let ggy = Tensor::builder(ctx.graph())
.append_input(&ggx, false)
.append_input(argmax, false)
.build(MaxPool2DGradGrad {
pad: self.pad,
stride: self.stride,
size: self.size,
});
ctx.append_input_grad(Some(ggy));
ctx.append_input_grad(None);
}
}
impl<T: Float> crate::op::Op<T> for MaxPool2DGradGrad {
fn compute(&self, ctx: &mut crate::op::ComputeContext<T>) -> Result<(), crate::op::OpError> {
let ggx = &ctx.input(0);
let x_shape = ggx.shape();
let copied_ggx;
let ggx = if ggx.is_standard_layout() {
ggx.as_ptr()
} else {
copied_ggx = ndarray_ext::deep_copy(ggx);
copied_ggx.as_ptr()
};
let batch = x_shape[0];
let c = x_shape[1];
let xh = x_shape[2];
let xw = x_shape[3];
let yh = (xh + 2 * self.pad - self.size) / self.stride + 1;
let yw = (xw + 2 * self.pad - self.size) / self.stride + 1;
let argmax = &ctx.input(1);
let ggy = unsafe {
let ggy = if same_type::<T, f32>() {
max_pool_grad_grad_f32(ggx, yh, yw, c, batch, argmax.as_ptr() as *const f32)
} else if same_type::<T, f64>() {
max_pool_grad_grad_f64(ggx, yh, yw, c, batch, argmax.as_ptr() as *const f64)
} else {
return Err(op::OpError::TypeUnsupported(
"MaxPool2DGradGrad supports only f32 and f64".to_string(),
));
};
NdArray::from_shape_vec_unchecked(ndarray::IxDyn(&[batch, c, yh, yw]), ggy)
};
ctx.append_output(ggy);
Ok(())
}
fn grad(&self, ctx: &mut crate::op::GradientContext<T>) {
ctx.append_input_grad(None);
ctx.append_input_grad(None);
}
}