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