| 339 | |
| 340 | template <typename ctype, typename IdxGetter> |
| 341 | void pooling_backward_max_impl( |
| 342 | const ctype* __restrict src, const ctype* __restrict dst, |
| 343 | const ctype* __restrict diff, ctype* __restrict grad, size_t N, size_t C, |
| 344 | size_t IH, size_t IW, size_t OH, size_t OW, size_t PH, size_t PW, size_t SH, |
| 345 | size_t SW, size_t FH, size_t FW) { |
| 346 | std::memset(grad, 0, sizeof(ctype) * (N * C * IH * IW)); |
| 347 | rep(n, N) rep(c, C) rep(oh, OH) rep(ow, OW) { |
| 348 | size_t count = 0u; |
| 349 | rep(fh, FH) rep(fw, FW) { |
| 350 | size_t ih = -PH + oh * SH + fh; |
| 351 | size_t iw = -PW + ow * SW + fw; |
| 352 | if (ih < IH && iw < IW) |
| 353 | ++count; |
| 354 | } |
| 355 | if (count == 0u) { |
| 356 | megdnn_throw("The pooling window lies outside completely"); |
| 357 | } |
| 358 | rep(fh, FH) rep(fw, FW) { |
| 359 | size_t ih = -PH + oh * SH + fh; |
| 360 | size_t iw = -PW + ow * SW + fw; |
| 361 | if (ih < IH && iw < IW) { |
| 362 | size_t si = IdxGetter::get_idx(n, c, ih, iw, N, C, IH, IW); |
| 363 | size_t di = IdxGetter::get_idx(n, c, oh, ow, N, C, OH, OW); |
| 364 | auto sval = src[si]; |
| 365 | auto& gval = grad[si]; |
| 366 | auto dst_val = dst[di]; |
| 367 | auto diff_val = diff[di]; |
| 368 | if (sval == dst_val) |
| 369 | gval += diff_val; |
| 370 | } |
| 371 | } |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | } // namespace |
| 376 | |