avgpool_layer.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include "avgpool_layer.h"
  2. #include "dark_cuda.h"
  3. #include "utils.h"
  4. #include <stdio.h>
  5. avgpool_layer make_avgpool_layer(int batch, int w, int h, int c)
  6. {
  7. fprintf(stderr, "avg %4d x%4d x%4d -> %4d\n", w, h, c, c);
  8. avgpool_layer l = { (LAYER_TYPE)0 };
  9. l.type = AVGPOOL;
  10. l.batch = batch;
  11. l.h = h;
  12. l.w = w;
  13. l.c = c;
  14. l.out_w = 1;
  15. l.out_h = 1;
  16. l.out_c = c;
  17. l.outputs = l.out_c;
  18. l.inputs = h*w*c;
  19. int output_size = l.outputs * batch;
  20. l.output = (float*)xcalloc(output_size, sizeof(float));
  21. l.delta = (float*)xcalloc(output_size, sizeof(float));
  22. l.forward = forward_avgpool_layer;
  23. l.backward = backward_avgpool_layer;
  24. #ifdef GPU
  25. l.forward_gpu = forward_avgpool_layer_gpu;
  26. l.backward_gpu = backward_avgpool_layer_gpu;
  27. l.output_gpu = cuda_make_array(l.output, output_size);
  28. l.delta_gpu = cuda_make_array(l.delta, output_size);
  29. #endif
  30. return l;
  31. }
  32. void resize_avgpool_layer(avgpool_layer *l, int w, int h)
  33. {
  34. l->w = w;
  35. l->h = h;
  36. l->inputs = h*w*l->c;
  37. }
  38. void forward_avgpool_layer(const avgpool_layer l, network_state state)
  39. {
  40. int b,i,k;
  41. for(b = 0; b < l.batch; ++b){
  42. for(k = 0; k < l.c; ++k){
  43. int out_index = k + b*l.c;
  44. l.output[out_index] = 0;
  45. for(i = 0; i < l.h*l.w; ++i){
  46. int in_index = i + l.h*l.w*(k + b*l.c);
  47. l.output[out_index] += state.input[in_index];
  48. }
  49. l.output[out_index] /= l.h*l.w;
  50. }
  51. }
  52. }
  53. void backward_avgpool_layer(const avgpool_layer l, network_state state)
  54. {
  55. int b,i,k;
  56. for(b = 0; b < l.batch; ++b){
  57. for(k = 0; k < l.c; ++k){
  58. int out_index = k + b*l.c;
  59. for(i = 0; i < l.h*l.w; ++i){
  60. int in_index = i + l.h*l.w*(k + b*l.c);
  61. state.delta[in_index] += l.delta[out_index] / (l.h*l.w);
  62. }
  63. }
  64. }
  65. }