| 2434 | } |
| 2435 | |
| 2436 | void reorg_gradient( |
| 2437 | bool add_to, |
| 2438 | tensor& grad, |
| 2439 | const int row_stride, |
| 2440 | const int col_stride, |
| 2441 | const tensor& gradient_input |
| 2442 | ) |
| 2443 | { |
| 2444 | DLIB_CASSERT(!is_same_object(grad, gradient_input), "Grad and gradient_input must be distinct objects."); |
| 2445 | DLIB_CASSERT(grad.nr() % row_stride == 0, "The number of rows in grad must be divisible by row_stride."); |
| 2446 | DLIB_CASSERT(grad.nc() % col_stride == 0, "The number of columns in grad must be divisible by col_stride."); |
| 2447 | DLIB_CASSERT(grad.num_samples() == gradient_input.num_samples(), "The number of samples in grad and gradient_input must match."); |
| 2448 | DLIB_CASSERT(grad.k() == gradient_input.k() / row_stride / col_stride, "The number of channels in grad must be gradient_input.k() divided by row_stride and col_stride."); |
| 2449 | DLIB_CASSERT(grad.nr() == gradient_input.nr() * row_stride, "The number of rows in grad must be gradient_input.nr() multiplied by row_stride."); |
| 2450 | DLIB_CASSERT(grad.nc() == gradient_input.nc() * col_stride, "The number of columns in grad must be gradient_input.nc() multiplied by col_stride."); |
| 2451 | |
| 2452 | const float* gi = gradient_input.host(); |
| 2453 | float* g = grad.host(); |
| 2454 | |
| 2455 | parallel_for(0, gradient_input.num_samples(), [&](long n) |
| 2456 | { |
| 2457 | for (long k = 0; k < gradient_input.k(); ++k) |
| 2458 | { |
| 2459 | for (long r = 0; r < gradient_input.nr(); ++r) |
| 2460 | { |
| 2461 | for (long c = 0; c < gradient_input.nc(); ++c) |
| 2462 | { |
| 2463 | const auto in_idx = tensor_index(gradient_input, n, k, r, c); |
| 2464 | const auto out_idx = tensor_index(grad, |
| 2465 | n, |
| 2466 | k % grad.k(), |
| 2467 | r * row_stride + (k / grad.k()) / col_stride, |
| 2468 | c * col_stride + (k / grad.k()) % col_stride); |
| 2469 | |
| 2470 | if (add_to) g[out_idx] += gi[in_idx]; |
| 2471 | else g[out_idx] = gi[in_idx]; |
| 2472 | } |
| 2473 | } |
| 2474 | } |
| 2475 | }); |
| 2476 | } |
| 2477 | |
| 2478 | // ------------------------------------------------------------------------------------ |
| 2479 | |