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

pooling.cpp 9.7 kB

[WIP] vulkan compute (#618) * vulkan infrastructure * vkallocator and vkmat * layer interface for vulkan compute * wip... * default vulkan device, command wrapper, upload model weight in load_model to simplify layer interface * simplify command api, vkmat holds staging buffer, relu works * initialize specialization constant, simplify command dispatch, fix staging buffer copy with different shape, convolution works * init extension functions * dynamic local size and group count * group count=1 is invalid * regard device max workgroup size limit * fix relu oooops * decouple command record and staging allocation * create result blob * add pooling shader * buffer is faster than image :) * fix pooling shader * add innerproduct shader * readonly writeonly decoration * simplify buffer creation * decouple command and layer, VK_KHR_descriptor_update_template extension makes descriptor binding update easy :D * fix vulkan building issues in visual studio (#1) * fix building issues on visual studio * ignore benchmark * cancel changes * ... ... * decouple paramdict and vulkandevice * fix staging buffer destroy in model loading * remove vkdev member in option * add padding shader * simplify vulkan layer creation, simplify convolution and pooling shader for no padding, less debug output * add convolutiondepthwise and softmax shader * specialization float type, add leakyrelu * add dropout shader * add batchnorm shader * split vulkan forward * add scale shader * push constant type can be int or float * set_optimal_local_size_xyz * add eltwise shader * concat vulkan forward * fix convolution without bias * add dummy shader for concat and split, more fix ... * optional VK_KHR_descriptor_update_template and VK_KHR_push_descriptor * check VK_KHR_push_descriptor for vkCmdPushDescriptorSetWithTemplateKHR * binaryop and unaryop shader * hide raw command buffer * simple vkbenchncnn benchmark * create device with transfer queue * rename command to vkcompute, add vktransfer and layer upload_model interface * external VkMat, copy and map wrt buffer offset * command copy respect offset and size * decouple weight upload and load, simplify upload weight api, use one big staging buffer for uploading weights * fix build on android * binding count can not vary :( * barrier check state, fix sub-op destruction * declare local_size_xyz constant, fix crash on radv * fix local_size_xyz, second try * more barrier and state fix * fix softmax * reconstruct buffer memory allocator, reuse blob buffer, less verbose output * find unified memory type index * weight staging buffer allocator and weight buffer allocator, respect descriptor buffer offset alignment * use VK_KHR_descriptor_update_template for faster descriptor update if available, multithread pipeline creation * find more useful vulkan extensions and enable them * fix msvc build * respect VK_KHR_dedicated_allocation for weight buffer allocation * fix android build * fix bias name conflicts with metal * decouple pipeline and layer, building shader sources into shader module, dedicated create_pipeline api, simplify pipeline recording * drop dummy shader, inplace softmax, multiple shader module works * fix unique queue family index error * flatten support vulkan * mnasnet run * find shader module by name, each entry point per shader module, fix attribute/id conflict on moltenvk * some minor changes * add some high level api * use dedicated transfer queue to upload weight model * prefer mappable buffer on unified memory * global pooling and convolution fc, reuse staging buffer * implement ring-buffer style blob allocator, add VkBufferMemory capacity * use blob allocator for workspace blob, it works fine :) * vulkan option off * Update layer.cpp * fix build with vulkan off * less verbose output, fix crash on vulkan_compute off * merge benchncnn tool * allocator clear api, use new weight buffer allocator per net * add default locked allocator * mapped mat ptr api, persistent mapped memory works generally :) * travis ci linux vulkan * travis ci vulkan wip ... * more gpu wip ... * more gpu wip ... * wip... * wip... * wip... ... * wip... ios vulkan build... * find glslangValidator on ios build * use dynamic moltenvk library * travis ci wip ... * ios simulator does not support metal at all * fix cpu only extractor * optimize workgroup size, first try * optimize workgroup size, second try * conv1x1s1d1 vec4 * revert build system * fix ncnn2mem build * fix ncnn2mem build
7 years ago
7 years ago
[WIP] vulkan compute (#618) * vulkan infrastructure * vkallocator and vkmat * layer interface for vulkan compute * wip... * default vulkan device, command wrapper, upload model weight in load_model to simplify layer interface * simplify command api, vkmat holds staging buffer, relu works * initialize specialization constant, simplify command dispatch, fix staging buffer copy with different shape, convolution works * init extension functions * dynamic local size and group count * group count=1 is invalid * regard device max workgroup size limit * fix relu oooops * decouple command record and staging allocation * create result blob * add pooling shader * buffer is faster than image :) * fix pooling shader * add innerproduct shader * readonly writeonly decoration * simplify buffer creation * decouple command and layer, VK_KHR_descriptor_update_template extension makes descriptor binding update easy :D * fix vulkan building issues in visual studio (#1) * fix building issues on visual studio * ignore benchmark * cancel changes * ... ... * decouple paramdict and vulkandevice * fix staging buffer destroy in model loading * remove vkdev member in option * add padding shader * simplify vulkan layer creation, simplify convolution and pooling shader for no padding, less debug output * add convolutiondepthwise and softmax shader * specialization float type, add leakyrelu * add dropout shader * add batchnorm shader * split vulkan forward * add scale shader * push constant type can be int or float * set_optimal_local_size_xyz * add eltwise shader * concat vulkan forward * fix convolution without bias * add dummy shader for concat and split, more fix ... * optional VK_KHR_descriptor_update_template and VK_KHR_push_descriptor * check VK_KHR_push_descriptor for vkCmdPushDescriptorSetWithTemplateKHR * binaryop and unaryop shader * hide raw command buffer * simple vkbenchncnn benchmark * create device with transfer queue * rename command to vkcompute, add vktransfer and layer upload_model interface * external VkMat, copy and map wrt buffer offset * command copy respect offset and size * decouple weight upload and load, simplify upload weight api, use one big staging buffer for uploading weights * fix build on android * binding count can not vary :( * barrier check state, fix sub-op destruction * declare local_size_xyz constant, fix crash on radv * fix local_size_xyz, second try * more barrier and state fix * fix softmax * reconstruct buffer memory allocator, reuse blob buffer, less verbose output * find unified memory type index * weight staging buffer allocator and weight buffer allocator, respect descriptor buffer offset alignment * use VK_KHR_descriptor_update_template for faster descriptor update if available, multithread pipeline creation * find more useful vulkan extensions and enable them * fix msvc build * respect VK_KHR_dedicated_allocation for weight buffer allocation * fix android build * fix bias name conflicts with metal * decouple pipeline and layer, building shader sources into shader module, dedicated create_pipeline api, simplify pipeline recording * drop dummy shader, inplace softmax, multiple shader module works * fix unique queue family index error * flatten support vulkan * mnasnet run * find shader module by name, each entry point per shader module, fix attribute/id conflict on moltenvk * some minor changes * add some high level api * use dedicated transfer queue to upload weight model * prefer mappable buffer on unified memory * global pooling and convolution fc, reuse staging buffer * implement ring-buffer style blob allocator, add VkBufferMemory capacity * use blob allocator for workspace blob, it works fine :) * vulkan option off * Update layer.cpp * fix build with vulkan off * less verbose output, fix crash on vulkan_compute off * merge benchncnn tool * allocator clear api, use new weight buffer allocator per net * add default locked allocator * mapped mat ptr api, persistent mapped memory works generally :) * travis ci linux vulkan * travis ci vulkan wip ... * more gpu wip ... * more gpu wip ... * wip... * wip... * wip... ... * wip... ios vulkan build... * find glslangValidator on ios build * use dynamic moltenvk library * travis ci wip ... * ios simulator does not support metal at all * fix cpu only extractor * optimize workgroup size, first try * optimize workgroup size, second try * conv1x1s1d1 vec4 * revert build system * fix ncnn2mem build * fix ncnn2mem build
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. // Tencent is pleased to support the open source community by making ncnn available.
  2. //
  3. // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
  4. //
  5. // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // https://opensource.org/licenses/BSD-3-Clause
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #include "pooling.h"
  15. #include <float.h>
  16. #include <algorithm>
  17. #include "layer_type.h"
  18. namespace ncnn {
  19. DEFINE_LAYER_CREATOR(Pooling)
  20. Pooling::Pooling()
  21. {
  22. one_blob_only = true;
  23. support_inplace = false;
  24. }
  25. int Pooling::load_param(const ParamDict& pd)
  26. {
  27. pooling_type = pd.get(0, 0);
  28. kernel_w = pd.get(1, 0);
  29. kernel_h = pd.get(11, kernel_w);
  30. stride_w = pd.get(2, 1);
  31. stride_h = pd.get(12, stride_w);
  32. pad_left = pd.get(3, 0);
  33. pad_right = pd.get(14, pad_left);
  34. pad_top = pd.get(13, pad_left);
  35. pad_bottom = pd.get(15, pad_top);
  36. global_pooling = pd.get(4, 0);
  37. pad_mode = pd.get(5, 0);
  38. avgpool_count_include_pad = pd.get(6, 0);
  39. return 0;
  40. }
  41. int Pooling::forward(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const
  42. {
  43. // max value in NxN window
  44. // avg value in NxN window
  45. int w = bottom_blob.w;
  46. int h = bottom_blob.h;
  47. int channels = bottom_blob.c;
  48. size_t elemsize = bottom_blob.elemsize;
  49. // fprintf(stderr, "Pooling input %d x %d pad = %d %d %d %d ksize=%d %d stride=%d %d\n", w, h, pad_left, pad_right, pad_top, pad_bottom, kernel_w, kernel_h, stride_w, stride_h);
  50. if (global_pooling)
  51. {
  52. top_blob.create(channels, elemsize, opt.blob_allocator);
  53. if (top_blob.empty())
  54. return -100;
  55. int size = w * h;
  56. if (pooling_type == PoolMethod_MAX)
  57. {
  58. #pragma omp parallel for num_threads(opt.num_threads)
  59. for (int q=0; q<channels; q++)
  60. {
  61. const float* ptr = bottom_blob.channel(q);
  62. float max = ptr[0];
  63. for (int i=0; i<size; i++)
  64. {
  65. max = std::max(max, ptr[i]);
  66. }
  67. top_blob[q] = max;
  68. }
  69. }
  70. else if (pooling_type == PoolMethod_AVE)
  71. {
  72. #pragma omp parallel for num_threads(opt.num_threads)
  73. for (int q=0; q<channels; q++)
  74. {
  75. const float* ptr = bottom_blob.channel(q);
  76. float sum = 0.f;
  77. for (int i=0; i<size; i++)
  78. {
  79. sum += ptr[i];
  80. }
  81. top_blob[q] = sum / size;
  82. }
  83. }
  84. return 0;
  85. }
  86. Mat bottom_blob_bordered = bottom_blob;
  87. float pad_value = 0.f;
  88. if (pooling_type == PoolMethod_MAX)
  89. {
  90. pad_value = -FLT_MAX;
  91. }
  92. else if (pooling_type == PoolMethod_AVE)
  93. {
  94. pad_value = 0.f;
  95. }
  96. int wtailpad = 0;
  97. int htailpad = 0;
  98. if (pad_mode == 0) // full padding
  99. {
  100. int wtail = (w + pad_left + pad_right - kernel_w) % stride_w;
  101. int htail = (h + pad_top + pad_bottom - kernel_h) % stride_h;
  102. if (wtail != 0)
  103. wtailpad = stride_w - wtail;
  104. if (htail != 0)
  105. htailpad = stride_h - htail;
  106. Option opt_b = opt;
  107. opt_b.blob_allocator = opt.workspace_allocator;
  108. copy_make_border(bottom_blob, bottom_blob_bordered, pad_top, pad_bottom + htailpad, pad_left, pad_right + wtailpad, BORDER_CONSTANT, pad_value, opt_b);
  109. if (bottom_blob_bordered.empty())
  110. return -100;
  111. w = bottom_blob_bordered.w;
  112. h = bottom_blob_bordered.h;
  113. }
  114. else if (pad_mode == 1) // valid padding
  115. {
  116. Option opt_b = opt;
  117. opt_b.blob_allocator = opt.workspace_allocator;
  118. copy_make_border(bottom_blob, bottom_blob_bordered, pad_top, pad_bottom, pad_left, pad_right, BORDER_CONSTANT, pad_value, opt_b);
  119. if (bottom_blob_bordered.empty())
  120. return -100;
  121. w = bottom_blob_bordered.w;
  122. h = bottom_blob_bordered.h;
  123. }
  124. else if (pad_mode == 2) // tensorflow padding=SAME or onnx padding=SAME_UPPER
  125. {
  126. int wpad = kernel_w + (w - 1) / stride_w * stride_w - w;
  127. int hpad = kernel_h + (h - 1) / stride_h * stride_h - h;
  128. if (wpad > 0 || hpad > 0)
  129. {
  130. Option opt_b = opt;
  131. opt_b.blob_allocator = opt.workspace_allocator;
  132. copy_make_border(bottom_blob, bottom_blob_bordered, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, BORDER_CONSTANT, pad_value, opt_b);
  133. if (bottom_blob_bordered.empty())
  134. return -100;
  135. }
  136. w = bottom_blob_bordered.w;
  137. h = bottom_blob_bordered.h;
  138. }
  139. else if (pad_mode == 3) // onnx padding=SAME_LOWER
  140. {
  141. int wpad = kernel_w + (w - 1) / stride_w * stride_w - w;
  142. int hpad = kernel_h + (h - 1) / stride_h * stride_h - h;
  143. if (wpad > 0 || hpad > 0)
  144. {
  145. Option opt_b = opt;
  146. opt_b.blob_allocator = opt.workspace_allocator;
  147. copy_make_border(bottom_blob, bottom_blob_bordered, hpad - hpad / 2, hpad / 2, wpad - wpad / 2, wpad / 2, BORDER_CONSTANT, pad_value, opt_b);
  148. if (bottom_blob_bordered.empty())
  149. return -100;
  150. }
  151. w = bottom_blob_bordered.w;
  152. h = bottom_blob_bordered.h;
  153. }
  154. int outw = (w - kernel_w) / stride_w + 1;
  155. int outh = (h - kernel_h) / stride_h + 1;
  156. top_blob.create(outw, outh, channels, elemsize, opt.blob_allocator);
  157. if (top_blob.empty())
  158. return -100;
  159. const int maxk = kernel_w * kernel_h;
  160. // kernel offsets
  161. std::vector<int> _space_ofs(maxk);
  162. int* space_ofs = &_space_ofs[0];
  163. {
  164. int p1 = 0;
  165. int p2 = 0;
  166. int gap = w - kernel_w;
  167. for (int i = 0; i < kernel_h; i++)
  168. {
  169. for (int j = 0; j < kernel_w; j++)
  170. {
  171. space_ofs[p1] = p2;
  172. p1++;
  173. p2++;
  174. }
  175. p2 += gap;
  176. }
  177. }
  178. if (pooling_type == PoolMethod_MAX)
  179. {
  180. #pragma omp parallel for num_threads(opt.num_threads)
  181. for (int q=0; q<channels; q++)
  182. {
  183. const Mat m = bottom_blob_bordered.channel(q);
  184. float* outptr = top_blob.channel(q);
  185. for (int i = 0; i < outh; i++)
  186. {
  187. for (int j = 0; j < outw; j++)
  188. {
  189. const float* sptr = m.row(i*stride_h) + j*stride_w;
  190. float max = sptr[0];
  191. for (int k = 0; k < maxk; k++)
  192. {
  193. float val = sptr[ space_ofs[k] ];
  194. max = std::max(max, val);
  195. }
  196. outptr[j] = max;
  197. }
  198. outptr += outw;
  199. }
  200. }
  201. }
  202. else if (pooling_type == PoolMethod_AVE)
  203. {
  204. #pragma omp parallel for num_threads(opt.num_threads)
  205. for (int q=0; q<channels; q++)
  206. {
  207. const Mat m = bottom_blob_bordered.channel(q);
  208. float* outptr = top_blob.channel(q);
  209. for (int i = 0; i < outh; i++)
  210. {
  211. for (int j = 0; j < outw; j++)
  212. {
  213. const float* sptr = m.row(i*stride_h) + j*stride_w;
  214. float sum = 0;
  215. for (int k = 0; k < maxk; k++)
  216. {
  217. float val = sptr[ space_ofs[k] ];
  218. sum += val;
  219. }
  220. outptr[j] = sum / maxk;
  221. }
  222. outptr += outw;
  223. }
  224. if (avgpool_count_include_pad == 0)
  225. {
  226. // fix pad
  227. if (pad_top != 0)
  228. {
  229. const float scale = (float)kernel_h / (kernel_h - pad_top);
  230. outptr = top_blob.channel(q).row(0);
  231. for (int i = 0; i < outw; i++)
  232. {
  233. outptr[i] *= scale;
  234. }
  235. }
  236. if (pad_bottom + htailpad != 0)
  237. {
  238. const float scale = (float)kernel_h / (kernel_h - pad_bottom - htailpad);
  239. outptr = top_blob.channel(q).row(outh - 1);
  240. for (int i = 0; i < outw; i++)
  241. {
  242. outptr[i] *= scale;
  243. }
  244. }
  245. if (pad_left != 0)
  246. {
  247. const float scale = (float)kernel_w / (kernel_w - pad_left);
  248. outptr = top_blob.channel(q);
  249. for (int i = 0; i < outh; i++)
  250. {
  251. *outptr *= scale;
  252. outptr += outw;
  253. }
  254. }
  255. if (pad_right + wtailpad != 0)
  256. {
  257. const float scale = (float)kernel_w / (kernel_w - pad_right - wtailpad);
  258. outptr = top_blob.channel(q);
  259. outptr += outw - 1;
  260. for (int i = 0; i < outh; i++)
  261. {
  262. *outptr *= scale;
  263. outptr += outw;
  264. }
  265. }
  266. }
  267. }
  268. }
  269. return 0;
  270. }
  271. } // namespace ncnn