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.

convolution.cpp 15 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
Fix warnings on Visual Studio (#1456) * Fix warning C4244 in src/layer/convolution.cpp C4244: '=': conversion from 'double' to 'float', possible loss of data * Fix warning C4244 in src/layer/convolution_sgemm_int8.h C4244: 'initializing': conversion from 'double' to 'int', possible loss of data * Fix warning C4244 in src/layer/deconvolution.cpp C4244: '=': conversion from 'double' to 'float', possible loss of data * Fix warning C4244 in src/layer/elu.cpp C4244: '=': conversion from 'double' to 'float', possible loss of data * Fix warning C4267 in src/layer/embed.cpp C4267: 'initializing': conversion from 'size_t' to 'int', possible loss of data * Fix warning C4244 in src/layer/exp.cpp C4244: '=': conversion from 'double' to 'float', possible loss of data * Fix warning C4244 in src/layer/innerproduct.cpp C4244: '=': conversion from 'double' to 'float', possible loss of data * Fix warning C4244 in src/layer/log.cpp C4244: '=': conversion from 'double' to 'float', possible loss of data C4244: 'initializing': conversion from 'double' to 'float', possible loss of data * Fix warning C4244 in src/layer/lrn.cpp C4244: '=': conversion from 'double' to 'float', possible loss of data * Fix warning C4244 in src/layer/mvn.cp C4244: 'initializing': conversion from 'double' to 'float', possible loss of data * Fix warning C4244 in src/layer/power.cpp C4244: '=': conversion from 'double' to 'float', possible loss of data * Fix warnings C4244 and C4267 in src/layer/proposal.cpp C4244: 'initializing': conversion from 'double' to 'float', possible loss of data C4244: 'initializing': conversion from 'double' to 'int', possible loss of data C4267: 'argument': conversion from 'size_t' to 'int', possible loss of data C4267: 'initializing': conversion from 'size_t' to 'int', possible loss of data * Fix warning C4244 in src/layer/reduction.cpp C4244: 'return': conversion from 'double' to 'T', possible loss of data * Fix warning C4244 in src/layer/tanh.cpp C4244: '=': conversion from 'double' to 'float', possible loss of data * Fix warning C4244 in src/layer/binaryop.cpp C4244: '=': conversion from 'double' to 'float', possible loss of data * Fix warnings C4244 and C4267 in src/layer/unaryop.cpp C4244: 'return': conversion from 'double' to 'T', possible loss of data C4267: 'initializing': conversion from 'size_t' to 'int', possible loss of data * Fix warning C4244 in src/layer/x86/convolutiondepthwise_3x3_int8.h C4244: 'initializing': conversion from 'double' to 'int', possible loss of data
6 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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 "convolution.h"
  15. #include "layer_type.h"
  16. #include <algorithm>
  17. namespace ncnn {
  18. Convolution::Convolution()
  19. {
  20. one_blob_only = true;
  21. support_inplace = false;
  22. use_int8_requantize = false;
  23. }
  24. int Convolution::load_param(const ParamDict& pd)
  25. {
  26. num_output = pd.get(0, 0);
  27. kernel_w = pd.get(1, 0);
  28. kernel_h = pd.get(11, kernel_w);
  29. dilation_w = pd.get(2, 1);
  30. dilation_h = pd.get(12, dilation_w);
  31. stride_w = pd.get(3, 1);
  32. stride_h = pd.get(13, stride_w);
  33. pad_left = pd.get(4, 0);
  34. pad_right = pd.get(15, pad_left);
  35. pad_top = pd.get(14, pad_left);
  36. pad_bottom = pd.get(16, pad_top);
  37. pad_value = pd.get(18, 0.f);
  38. bias_term = pd.get(5, 0);
  39. weight_data_size = pd.get(6, 0);
  40. int8_scale_term = pd.get(8, 0);
  41. activation_type = pd.get(9, 0);
  42. activation_params = pd.get(10, Mat());
  43. impl_type = pd.get(17, 0);
  44. if (int8_scale_term)
  45. {
  46. use_int8_inference = true;
  47. }
  48. return 0;
  49. }
  50. int Convolution::load_model(const ModelBin& mb)
  51. {
  52. weight_data = mb.load(weight_data_size, 0);
  53. if (weight_data.empty())
  54. return -100;
  55. if (bias_term)
  56. {
  57. bias_data = mb.load(num_output, 1);
  58. if (bias_data.empty())
  59. return -100;
  60. }
  61. if (int8_scale_term)
  62. {
  63. weight_data_int8_scales = mb.load(num_output, 1);
  64. bottom_blob_int8_scale = mb.load(1, 1)[0];
  65. }
  66. return 0;
  67. }
  68. int Convolution::create_pipeline(const Option& opt)
  69. {
  70. // runtime quantize the weight data
  71. if (opt.use_int8_inference && weight_data.elemsize == (size_t)4u && int8_scale_term)
  72. {
  73. Mat int8_weight_data(weight_data_size, (size_t)1u);
  74. if (int8_weight_data.empty())
  75. return -100;
  76. const int weight_data_size_output = weight_data_size / num_output;
  77. for (int p = 0; p < num_output; p++)
  78. {
  79. Option opt_q = opt;
  80. opt_q.blob_allocator = int8_weight_data.allocator;
  81. const Mat weight_data_n = weight_data.range(weight_data_size_output * p, weight_data_size_output);
  82. Mat int8_weight_data_n = int8_weight_data.range(weight_data_size_output * p, weight_data_size_output);
  83. quantize_float32_to_int8(weight_data_n, int8_weight_data_n, weight_data_int8_scales[p], opt_q);
  84. }
  85. weight_data = int8_weight_data;
  86. }
  87. return 0;
  88. }
  89. int Convolution::forward(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const
  90. {
  91. // convolv with NxN kernel
  92. // value = value + bias
  93. if (opt.use_int8_inference && weight_data.elemsize == (size_t)1u)
  94. {
  95. return forward_int8(bottom_blob, top_blob, opt);
  96. }
  97. // flattened blob, implement as InnerProduct
  98. if (bottom_blob.dims == 1 && kernel_w == 1 && kernel_h == 1)
  99. {
  100. int num_input = weight_data_size / num_output;
  101. if (bottom_blob.w * bottom_blob.elempack == num_input)
  102. {
  103. // call InnerProduct
  104. ncnn::Layer* op = ncnn::create_layer(ncnn::LayerType::InnerProduct);
  105. // set param
  106. ncnn::ParamDict pd;
  107. pd.set(0, num_output);
  108. pd.set(1, bias_term);
  109. pd.set(2, weight_data_size);
  110. pd.set(8, int8_scale_term);
  111. pd.set(9, activation_type);
  112. pd.set(10, activation_params);
  113. op->load_param(pd);
  114. // set weights
  115. ncnn::Mat weights[4];
  116. weights[0] = weight_data;
  117. weights[1] = bias_data;
  118. if (int8_scale_term)
  119. {
  120. weights[2] = weight_data_int8_scales;
  121. weights[3] = Mat(1, (size_t)4u, (void*)&bottom_blob_int8_scale);
  122. }
  123. op->load_model(ModelBinFromMatArray(weights));
  124. op->create_pipeline(opt);
  125. // forward
  126. op->forward(bottom_blob, top_blob, opt);
  127. op->destroy_pipeline(opt);
  128. delete op;
  129. return 0;
  130. }
  131. }
  132. int w = bottom_blob.w;
  133. int h = bottom_blob.h;
  134. int channels = bottom_blob.c;
  135. size_t elemsize = bottom_blob.elemsize;
  136. // NCNN_LOGE("Convolution input %d x %d pad = %d %d ksize=%d %d stride=%d %d", w, h, pad_w, pad_h, kernel_w, kernel_h, stride_w, stride_h);
  137. const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1;
  138. const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1;
  139. Mat bottom_blob_bordered;
  140. make_padding(bottom_blob, bottom_blob_bordered, opt);
  141. if (bottom_blob_bordered.empty())
  142. return -100;
  143. w = bottom_blob_bordered.w;
  144. h = bottom_blob_bordered.h;
  145. int outw = (w - kernel_extent_w) / stride_w + 1;
  146. int outh = (h - kernel_extent_h) / stride_h + 1;
  147. const int maxk = kernel_w * kernel_h;
  148. // kernel offsets
  149. std::vector<int> _space_ofs(maxk);
  150. int* space_ofs = &_space_ofs[0];
  151. {
  152. int p1 = 0;
  153. int p2 = 0;
  154. int gap = w * dilation_h - kernel_w * dilation_w;
  155. for (int i = 0; i < kernel_h; i++)
  156. {
  157. for (int j = 0; j < kernel_w; j++)
  158. {
  159. space_ofs[p1] = p2;
  160. p1++;
  161. p2 += dilation_w;
  162. }
  163. p2 += gap;
  164. }
  165. }
  166. // float32
  167. top_blob.create(outw, outh, num_output, elemsize, opt.blob_allocator);
  168. if (top_blob.empty())
  169. return -100;
  170. // num_output
  171. #pragma omp parallel for num_threads(opt.num_threads)
  172. for (int p = 0; p < num_output; p++)
  173. {
  174. float* outptr = top_blob.channel(p);
  175. for (int i = 0; i < outh; i++)
  176. {
  177. for (int j = 0; j < outw; j++)
  178. {
  179. float sum = 0.f;
  180. if (bias_term)
  181. sum = bias_data[p];
  182. const float* kptr = (const float*)weight_data + maxk * channels * p;
  183. // channels
  184. for (int q = 0; q < channels; q++)
  185. {
  186. const Mat m = bottom_blob_bordered.channel(q);
  187. const float* sptr = m.row(i * stride_h) + j * stride_w;
  188. for (int k = 0; k < maxk; k++) // 29.23
  189. {
  190. float val = sptr[space_ofs[k]]; // 20.72
  191. float w = kptr[k];
  192. sum += val * w; // 41.45
  193. }
  194. kptr += maxk;
  195. }
  196. if (activation_type == 1)
  197. {
  198. sum = std::max(sum, 0.f);
  199. }
  200. else if (activation_type == 2)
  201. {
  202. float slope = activation_params[0];
  203. sum = sum > 0.f ? sum : sum * slope;
  204. }
  205. else if (activation_type == 3)
  206. {
  207. float min = activation_params[0];
  208. float max = activation_params[1];
  209. if (sum < min)
  210. sum = min;
  211. if (sum > max)
  212. sum = max;
  213. }
  214. else if (activation_type == 4)
  215. {
  216. sum = static_cast<float>(1.f / (1.f + exp(-sum)));
  217. }
  218. else if (activation_type == 5)
  219. {
  220. const float MISH_THRESHOLD = 20;
  221. float x = sum, y;
  222. if (x > MISH_THRESHOLD)
  223. y = x;
  224. else if (x < -MISH_THRESHOLD)
  225. y = expf(x);
  226. else
  227. y = logf(expf(x) + 1);
  228. sum = static_cast<float>(x * tanh(y));
  229. }
  230. outptr[j] = sum;
  231. }
  232. outptr += outw;
  233. }
  234. }
  235. return 0;
  236. }
  237. void Convolution::make_padding(const Mat& bottom_blob, Mat& bottom_blob_bordered, const Option& opt) const
  238. {
  239. int w = bottom_blob.w;
  240. int h = bottom_blob.h;
  241. const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1;
  242. const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1;
  243. bottom_blob_bordered = bottom_blob;
  244. if (pad_left > 0 || pad_right > 0 || pad_top > 0 || pad_bottom > 0)
  245. {
  246. Option opt_b = opt;
  247. opt_b.blob_allocator = opt.workspace_allocator;
  248. copy_make_border(bottom_blob, bottom_blob_bordered, pad_top, pad_bottom, pad_left, pad_right, BORDER_CONSTANT, pad_value, opt_b);
  249. }
  250. else if (pad_left == -233 && pad_right == -233 && pad_top == -233 && pad_bottom == -233)
  251. {
  252. // tensorflow padding=SAME or onnx padding=SAME_UPPER
  253. int wpad = kernel_extent_w + (w - 1) / stride_w * stride_w - w;
  254. int hpad = kernel_extent_h + (h - 1) / stride_h * stride_h - h;
  255. if (wpad > 0 || hpad > 0)
  256. {
  257. Option opt_b = opt;
  258. opt_b.blob_allocator = opt.workspace_allocator;
  259. copy_make_border(bottom_blob, bottom_blob_bordered, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, BORDER_CONSTANT, pad_value, opt_b);
  260. }
  261. }
  262. else if (pad_left == -234 && pad_right == -234 && pad_top == -234 && pad_bottom == -234)
  263. {
  264. // onnx padding=SAME_LOWER
  265. int wpad = kernel_extent_w + (w - 1) / stride_w * stride_w - w;
  266. int hpad = kernel_extent_h + (h - 1) / stride_h * stride_h - h;
  267. if (wpad > 0 || hpad > 0)
  268. {
  269. Option opt_b = opt;
  270. opt_b.blob_allocator = opt.workspace_allocator;
  271. copy_make_border(bottom_blob, bottom_blob_bordered, hpad - hpad / 2, hpad / 2, wpad - wpad / 2, wpad / 2, BORDER_CONSTANT, pad_value, opt_b);
  272. }
  273. }
  274. }
  275. static inline signed char float2int8(float v)
  276. {
  277. int int32 = static_cast<int>(round(v));
  278. if (int32 > 127) return 127;
  279. if (int32 < -127) return -127;
  280. return (signed char)int32;
  281. }
  282. int Convolution::forward_int8(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const
  283. {
  284. int w = bottom_blob.w;
  285. int h = bottom_blob.h;
  286. int channels = bottom_blob.c;
  287. size_t elemsize = bottom_blob.elemsize;
  288. // NCNN_LOGE("Convolution input %d x %d ksize=%d %d stride=%d %d", w, h, kernel_w, kernel_h, stride_w, stride_h);
  289. const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1;
  290. const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1;
  291. Mat bottom_blob_unbordered = bottom_blob;
  292. if (elemsize != 1)
  293. {
  294. Option opt_g = opt;
  295. opt_g.blob_allocator = opt.workspace_allocator;
  296. quantize_float32_to_int8(bottom_blob, bottom_blob_unbordered, bottom_blob_int8_scale, opt_g);
  297. }
  298. Mat bottom_blob_bordered;
  299. make_padding(bottom_blob_unbordered, bottom_blob_bordered, opt);
  300. if (bottom_blob_bordered.empty())
  301. return -100;
  302. w = bottom_blob_bordered.w;
  303. h = bottom_blob_bordered.h;
  304. int outw = (w - kernel_extent_w) / stride_w + 1;
  305. int outh = (h - kernel_extent_h) / stride_h + 1;
  306. const int maxk = kernel_w * kernel_h;
  307. // kernel offsets
  308. std::vector<int> _space_ofs(maxk);
  309. int* space_ofs = &_space_ofs[0];
  310. {
  311. int p1 = 0;
  312. int p2 = 0;
  313. int gap = w * dilation_h - kernel_w * dilation_w;
  314. for (int i = 0; i < kernel_h; i++)
  315. {
  316. for (int j = 0; j < kernel_w; j++)
  317. {
  318. space_ofs[p1] = p2;
  319. p1++;
  320. p2 += dilation_w;
  321. }
  322. p2 += gap;
  323. }
  324. }
  325. // int8
  326. size_t out_elemsize = use_int8_requantize ? 1u : 4u;
  327. top_blob.create(outw, outh, num_output, out_elemsize, opt.blob_allocator);
  328. if (top_blob.empty())
  329. return -100;
  330. // num_output
  331. #pragma omp parallel for num_threads(opt.num_threads)
  332. for (int p = 0; p < num_output; p++)
  333. {
  334. signed char* outptr = top_blob.channel(p);
  335. for (int i = 0; i < outh; i++)
  336. {
  337. for (int j = 0; j < outw; j++)
  338. {
  339. int sum = 0;
  340. const signed char* kptr = (const signed char*)weight_data + maxk * channels * p;
  341. // channels
  342. for (int q = 0; q < channels; q++)
  343. {
  344. const Mat m = bottom_blob_bordered.channel(q);
  345. const signed char* sptr = m.row<signed char>(i * stride_h) + j * stride_w;
  346. for (int k = 0; k < maxk; k++)
  347. {
  348. int val = sptr[space_ofs[k]];
  349. int w = kptr[k];
  350. sum += val * w;
  351. }
  352. kptr += maxk;
  353. }
  354. if (use_int8_requantize)
  355. {
  356. // requantize and relu
  357. float scale_in;
  358. if (weight_data_int8_scales[p] == 0)
  359. scale_in = 0;
  360. else
  361. scale_in = 1.f / (bottom_blob_int8_scale * weight_data_int8_scales[p]);
  362. float sumfp32 = sum * scale_in;
  363. if (bias_term)
  364. sumfp32 += bias_data[p];
  365. float scale_out = top_blob_int8_scale; //FIXME load param
  366. signed char sums8 = float2int8(sumfp32 * scale_out);
  367. if (activation_type == 1)
  368. {
  369. sums8 = std::max(sums8, (signed char)0);
  370. }
  371. outptr[0] = sums8;
  372. outptr += 1;
  373. }
  374. else
  375. {
  376. // dequantize and relu
  377. float scale_in;
  378. if (weight_data_int8_scales[p] == 0)
  379. scale_in = 0;
  380. else
  381. scale_in = 1.f / (bottom_blob_int8_scale * weight_data_int8_scales[p]);
  382. float sumfp32 = sum * scale_in;
  383. if (bias_term)
  384. sumfp32 += bias_data[p];
  385. if (activation_type == 1)
  386. {
  387. sumfp32 = std::max(sumfp32, 0.f);
  388. }
  389. ((float*)outptr)[0] = sumfp32;
  390. outptr += 4;
  391. }
  392. }
  393. }
  394. }
  395. return 0;
  396. }
  397. } // namespace ncnn