You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
2.0 KiB

8 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include <cuda_runtime.h>
  2. #include <curand.h>
  3. #include <cublas_v2.h>
  4. extern "C" {
  5. #include "im2col.h"
  6. #include "dn_cuda.h"
  7. }
  8. using namespace DN;
  9. // src: https://github.com/BVLC/caffe/blob/master/src/caffe/util/im2col.cu
  10. // You may also want to read: https://github.com/BVLC/caffe/blob/master/LICENSE
  11. __global__ void im2col_gpu_kernel(const int n, const float* data_im,
  12. const int height, const int width, const int ksize,
  13. const int pad,
  14. const int stride,
  15. const int height_col, const int width_col,
  16. float *data_col) {
  17. int index = blockIdx.x*blockDim.x + threadIdx.x;
  18. for (; index < n; index += blockDim.x*gridDim.x){
  19. int w_out = index % width_col;
  20. int h_index = index / width_col;
  21. int h_out = h_index % height_col;
  22. int channel_in = h_index / height_col;
  23. int channel_out = channel_in * ksize * ksize;
  24. int h_in = h_out * stride - pad;
  25. int w_in = w_out * stride - pad;
  26. float* data_col_ptr = data_col;
  27. data_col_ptr += (channel_out * height_col + h_out) * width_col + w_out;
  28. const float* data_im_ptr = data_im;
  29. data_im_ptr += (channel_in * height + h_in) * width + w_in;
  30. for (int i = 0; i < ksize; ++i) {
  31. for (int j = 0; j < ksize; ++j) {
  32. int h = h_in + i;
  33. int w = w_in + j;
  34. *data_col_ptr = (h >= 0 && w >= 0 && h < height && w < width) ?
  35. data_im_ptr[i * width + j] : 0;
  36. //*data_col_ptr = data_im_ptr[ii * width + jj];
  37. data_col_ptr += height_col * width_col;
  38. }
  39. }
  40. }
  41. }
  42. void im2col_gpu(float *im,
  43. int channels, int height, int width,
  44. int ksize, int stride, int pad, float *data_col){
  45. // We are going to launch channels * height_col * width_col kernels, each
  46. // kernel responsible for copying a single-channel grid.
  47. int height_col = (height + 2 * pad - ksize) / stride + 1;
  48. int width_col = (width + 2 * pad - ksize) / stride + 1;
  49. int num_kernels = channels * height_col * width_col;
  50. im2col_gpu_kernel <<<(num_kernels + BLOCK - 1) / BLOCK, BLOCK >>>(
  51. num_kernels, im, height, width, ksize, pad,
  52. stride, height_col,
  53. width_col, data_col);
  54. }