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.

conv_layer.py 22 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. import te.lang.cce
  16. from te import tvm
  17. from te.platform import CUBE_MKN
  18. from topi import generic
  19. from topi.cce import util
  20. from topi.cce.util import is_v200_version
  21. # pylint: disable=R0912,R0913,R0914,R0915,E1101
  22. # the dim of shape in conv must be 4
  23. PAD_SHAPE_DIM = 2
  24. NONETYPE = type(None)
  25. @util.check_input_type((list, tuple), (list, tuple), str, str, str, (list, int), (list, int),
  26. int, int,(list, tuple), (list, tuple),
  27. str, str, str,
  28. str, str, str,
  29. str, bool, str)
  30. def conv_layer_cce_para_check(shape_in, shape_w, in_dtype, w_dtype, res_dtype, padh, padw,
  31. strideh, stridew, quantize_config, scale_sqrt,
  32. scale_q_dtype, offset_q_dtype, scale_dq_dtype,
  33. scale_rq_dtype, offset_rq_dtype, offset_w_dtype,
  34. offset_pad_dtype, bias, kernel_name):
  35. # conv shape check
  36. util.check_kernel_name(kernel_name)
  37. # conv data type check
  38. util.check_dtype_rule(in_dtype, ['float16', 'int8', 'uint8'])
  39. util.check_dtype_rule(w_dtype, ['float16', 'int8', 'uint8'])
  40. res_dtype_list = ['float16', 'int8', 'uint8']
  41. if is_v200_version():
  42. res_dtype_list.append('int32')
  43. util.check_dtype_rule(res_dtype, res_dtype_list)
  44. util.check_dtype_rule(scale_q_dtype, ['float16'])
  45. util.check_dtype_rule(offset_q_dtype, ['float16'])
  46. util.check_dtype_rule(scale_dq_dtype, ['float16'])
  47. util.check_dtype_rule(scale_rq_dtype, ['float16'])
  48. util.check_dtype_rule(offset_rq_dtype, ['float16'])
  49. util.check_dtype_rule(offset_w_dtype, ['int32'])
  50. util.check_dtype_rule(offset_pad_dtype, ['uint8'])
  51. if not isinstance(bias, bool):
  52. raise RuntimeError("bias dtype should be bool.")
  53. if quantize_config[0] == 0:
  54. if is_v200_version():
  55. util.check_dtype_rule(in_dtype, ('int8', ))
  56. util.check_dtype_rule(w_dtype, ('int8', ))
  57. util.check_dtype_rule(res_dtype, ('int32', ))
  58. else:
  59. util.check_dtype_rule(in_dtype, ['float16'])
  60. util.check_dtype_rule(w_dtype, ['float16'])
  61. util.check_dtype_rule(res_dtype, ['float16'])
  62. if quantize_config[0] == 1:
  63. util.check_dtype_rule(w_dtype, ['int8'])
  64. if quantize_config[1] == 0:
  65. util.check_dtype_rule(in_dtype, ['int8', 'float16'])
  66. util.check_dtype_rule(res_dtype, ['int8', 'float16'])
  67. elif quantize_config[1] == 1:
  68. util.check_dtype_rule(in_dtype, ['uint8', 'float16'])
  69. util.check_dtype_rule(res_dtype, ['uint8', 'float16'])
  70. elif quantize_config[1] == 2:
  71. raise RuntimeError("All Offset mode quantize not support.")
  72. else:
  73. raise RuntimeError("Invalid quantize algorithm.")
  74. # quantize switch on
  75. if quantize_config[0] == 1:
  76. quantize_turn_on = True
  77. # quantize -> DeQuantize dataflow
  78. if in_dtype == 'float16' and w_dtype == 'int8' and res_dtype == 'float16':
  79. pass
  80. # DeQuantize dataflow
  81. elif (in_dtype in ['int8', 'uint8'] and w_dtype == 'int8' and
  82. res_dtype == 'float16'):
  83. pass
  84. # quantize -> ReQuantize dataflow
  85. elif (in_dtype == 'float16' and w_dtype == 'int8' and res_dtype in
  86. ['int8', 'uint8']):
  87. pass
  88. # ReQuantize dataflow
  89. elif (in_dtype in ['int8', 'uint8'] and w_dtype == 'int8' and res_dtype in
  90. ['int8', 'uint8']):
  91. pass
  92. else:
  93. raise RuntimeError("Not support in/out data type for quantize.")
  94. if quantize_config not in ([1, 0, 0], [1, 1, 0], [1, 0, 1], [1, 1, 1]):
  95. raise RuntimeError("Invalid Quantize Config.")
  96. if scale_sqrt not in ([0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1],
  97. [1, 0, 1], [0, 1, 1], [1, 1, 1]):
  98. raise RuntimeError("Invalid Quantize Config.")
  99. # quantize switch off
  100. elif quantize_config[0] == 0:
  101. if quantize_config != [0, 0, 0]:
  102. raise RuntimeError("Invalid Quantize Config.")
  103. if scale_sqrt != [0, 0, 0]:
  104. raise RuntimeError("Invalid Quantize Config.")
  105. else:
  106. raise RuntimeError("Invalid Quantize Config.")
  107. if isinstance(padh, list):
  108. if len(padh) != PAD_SHAPE_DIM:
  109. raise RuntimeError("Dimension must be %d when padh is a list."%PAD_SHAPE_DIM)
  110. pad_top = padh[0]
  111. pad_bottom = padh[1]
  112. else:
  113. pad_top = padh
  114. pad_bottom = padh
  115. if isinstance(padw, list):
  116. if len(padw) != PAD_SHAPE_DIM:
  117. raise RuntimeError("Dimension must be %d when padw is a list."%PAD_SHAPE_DIM)
  118. pad_left = padw[0]
  119. pad_right = padw[1]
  120. else:
  121. pad_left = padw
  122. pad_right = padw
  123. shape_in, shape_w = te.lang.cce.check_conv_shape(shape_in, shape_w, pad_top, pad_bottom, \
  124. pad_left, pad_right, strideh, \
  125. stridew, in_dtype, w_dtype, res_dtype)
  126. return shape_in, shape_w
  127. @util.check_input_type((list, tuple), (list, tuple), str, str, str, \
  128. (list, int), (list, int), int, int,
  129. (list, NONETYPE), (list, NONETYPE),
  130. str, str, str,
  131. str, str, str, str,
  132. bool, str, bool, bool)
  133. def conv_layer_cce(shape_in, shape_w, in_dtype, w_dtype, res_dtype, padh, padw, strideh, stridew,
  134. quantize_config=None, scale_sqrt=None,
  135. scale_q_dtype='float16', offset_q_dtype='float16', scale_dq_dtype='float16',
  136. scale_rq_dtype='float16', offset_rq_dtype='float16', offset_w_dtype='int32',
  137. offset_pad_dtype='uint8', bias=False, kernel_name="cce_conv", need_build=False,
  138. need_print=False):
  139. """
  140. Parameters
  141. ----------
  142. shape_in : shape of data_in
  143. shape_w : shape of filter
  144. in_dtype : the feature map data type
  145. w_dtype : the weight data type
  146. res_dtype : the result data type
  147. padh: the padding shape in H
  148. padw: the padding shape in weight
  149. strideh: the stride value in H
  150. stridew: the stride value in weight
  151. quantize_config: quantize config table, default [0, 0, 0]
  152. quantize_config[0] - quantize function switch
  153. 0: quantize off
  154. 1: quantize on
  155. quantize_config[1] - quantize_algorithm
  156. 0: non offset
  157. 1: half offset
  158. 2: all offset ( Not supported now )
  159. quantize_config[2] - QuantizeScaleType (for Dequantize/Requantize, quantize always scalar)
  160. 0: scalar
  161. 1: vector
  162. scale_sqrt: scale mode
  163. scale_sqrt[0] - Quantize scale mode
  164. 0: non sqrt
  165. 1: sqrt
  166. scale_sqrt[1] - DeQuantize scale mode
  167. 0: non sqrt
  168. 1: sqrt
  169. scale_sqrt[2] - ReQuantize scale mode
  170. 0: non sqrt
  171. 1: sqrt
  172. scale_q_dtype: Quantize scale data type, default 'float16'
  173. offset_q_dtype: Quantize offset data type, default 'float16'
  174. scale_dq_dtype: DeQuantize scale data type, default 'float16'
  175. scale_rq_dtype: ReQuantize scale data type, default 'float16'
  176. offset_rq_dtype: ReQuantize offset data type, default 'float16'
  177. offset_w_dtype: weight offset data type, default 'int32'
  178. offset_pad_dtype: Quantize Cube offset data type, default 'uint8'
  179. bias: the tag for bias or not
  180. kernel_name : cce kernel name, default value is "cce_conv"
  181. need_build : if need to build CCEC kernel, default value is False
  182. need_print : if need to print the ir, default value is False
  183. Returns
  184. -------
  185. wrapped_tensor
  186. """
  187. # for pylint, otherwise "Dangerous default value [] as argument"
  188. if quantize_config is None:
  189. quantize_config = [0, 0, 0]
  190. if scale_sqrt is None:
  191. scale_sqrt = [0, 0, 0]
  192. in_dtype = in_dtype.lower()
  193. w_dtype = w_dtype.lower()
  194. res_dtype = res_dtype.lower()
  195. scale_q_dtype = scale_q_dtype.lower()
  196. offset_q_dtype = offset_q_dtype.lower()
  197. scale_dq_dtype = scale_dq_dtype.lower()
  198. scale_rq_dtype = scale_rq_dtype.lower()
  199. offset_rq_dtype = offset_rq_dtype.lower()
  200. offset_w_dtype = offset_w_dtype.lower()
  201. offset_pad_dtype = offset_pad_dtype.lower()
  202. mad_dtype = 'float32'
  203. if w_dtype == 'int8':
  204. mad_dtype = 'int32'
  205. shape_in = list(shape_in)
  206. shape_w = list(shape_w)
  207. shape_in, shape_w = conv_layer_cce_para_check(shape_in, shape_w, in_dtype, w_dtype, res_dtype, padh, padw, strideh, stridew,
  208. quantize_config, scale_sqrt, scale_q_dtype, offset_q_dtype, scale_dq_dtype,
  209. scale_rq_dtype, offset_rq_dtype, offset_w_dtype, offset_pad_dtype, bias, kernel_name)
  210. # quantize switch on
  211. if quantize_config[0] == 1:
  212. quantize_turn_on = True
  213. # quantize -> DeQuantize dataflow
  214. if in_dtype == 'float16' and w_dtype == 'int8' and res_dtype == 'float16':
  215. is_quantize = True
  216. is_dequantize = True
  217. is_requantize = False
  218. # DeQuantize dataflow
  219. elif (in_dtype in ['int8', 'uint8'] and w_dtype == 'int8' and
  220. res_dtype == 'float16'):
  221. is_quantize = False
  222. is_dequantize = True
  223. is_requantize = False
  224. # quantize -> ReQuantize dataflow
  225. elif (in_dtype == 'float16' and w_dtype == 'int8' and res_dtype in
  226. ['int8', 'uint8']):
  227. is_quantize = True
  228. is_dequantize = False
  229. is_requantize = True
  230. # ReQuantize dataflow
  231. elif (in_dtype in ['int8', 'uint8'] and w_dtype == 'int8' and res_dtype in
  232. ['int8', 'uint8']):
  233. is_quantize = False
  234. is_dequantize = False
  235. is_requantize = True
  236. else:
  237. raise RuntimeError("Not support in/out data type for quantize.")
  238. # quantize switch off
  239. elif quantize_config[0] == 0:
  240. quantize_turn_on = False
  241. is_quantize = False
  242. is_dequantize = False
  243. is_requantize = False
  244. if quantize_config != [0, 0, 0]:
  245. raise RuntimeError("Invalid Quantize Config.")
  246. if scale_sqrt != [0, 0, 0]:
  247. raise RuntimeError("Invalid Quantize Config.")
  248. else:
  249. raise RuntimeError("Invalid Quantize Config.")
  250. batch_size = shape_in[0]
  251. in_channel = shape_in[1]
  252. feature_map_h = shape_in[2]
  253. feature_map_w = shape_in[3]
  254. block_size_k = CUBE_MKN[in_dtype]['mac'][1]
  255. fmap_shape_nc1hwc0 = (batch_size, (in_channel + block_size_k - 1) // block_size_k,
  256. feature_map_h, feature_map_w, block_size_k)
  257. out_channel = shape_w[0]
  258. in_channel_weight = shape_w[1]
  259. filter_h = shape_w[2]
  260. filter_w = shape_w[3]
  261. block_size_k = CUBE_MKN[w_dtype]['mac'][1]
  262. block_size_n = CUBE_MKN[w_dtype]['mac'][2]
  263. filter_shape_frac_z = (in_channel_weight * filter_h * filter_w // block_size_k,
  264. out_channel // block_size_n, block_size_n, block_size_k)
  265. with tvm.target.cce():
  266. data = tvm.placeholder(
  267. fmap_shape_nc1hwc0, name='Fmap', dtype=in_dtype)
  268. weight = tvm.placeholder(
  269. filter_shape_frac_z, name='Filter', dtype=w_dtype)
  270. bias_tensor = None
  271. scale_q = None
  272. scale_dq = None
  273. scale_rq = None
  274. offset_pad = None
  275. offset_rq = None
  276. offset_q = None
  277. scale_drq = None
  278. # bias or fusion_bias(half offset)
  279. if bias or (quantize_config[1] == 1 and quantize_turn_on):
  280. bias_tensor = tvm.placeholder(
  281. (out_channel,), name='bias_tensor', \
  282. dtype="int32" if quantize_turn_on else res_dtype)
  283. # quantize on
  284. if quantize_turn_on:
  285. quantize_algorithm = quantize_config[1]
  286. if is_quantize:
  287. scale_q = tvm.placeholder(
  288. (CUBE_MKN[scale_q_dtype]['mac'][1],), name='scaleQ', dtype=scale_q_dtype)
  289. if quantize_algorithm ==1:
  290. offset_q = tvm.placeholder(
  291. (CUBE_MKN[offset_q_dtype]['mac'][1],), name='offsetQ', dtype=offset_q_dtype)
  292. if is_dequantize:
  293. scale_dq_shape = (CUBE_MKN[scale_dq_dtype]['mac'][1],) if quantize_config[2] == 0 \
  294. else (out_channel,)
  295. scale_dq = tvm.placeholder(
  296. scale_dq_shape, name='scaleDq', dtype=scale_dq_dtype)
  297. if is_requantize:
  298. scale_rq_shape = (CUBE_MKN[scale_rq_dtype]['mac'][1],) if quantize_config[2] == 0 \
  299. else (out_channel,)
  300. scale_rq = tvm.placeholder(
  301. scale_rq_shape, name='scaleRq', dtype=scale_rq_dtype)
  302. if quantize_algorithm ==1:
  303. offset_rq_shape = (CUBE_MKN[offset_rq_dtype]['mac'][1],)
  304. offset_rq = tvm.placeholder(
  305. offset_rq_shape, name='offsetRq', dtype=offset_rq_dtype)
  306. # need offset_pad , for half offset
  307. if quantize_algorithm ==1:
  308. offset_pad = tvm.placeholder(
  309. (CUBE_MKN[offset_pad_dtype]['mac'][1],), name='offset_pad',
  310. dtype=offset_pad_dtype)
  311. if quantize_algorithm == 0:
  312. if is_quantize:
  313. if is_dequantize:
  314. scale_drq = scale_dq
  315. else:
  316. scale_drq = scale_rq
  317. conv_res = te.lang.cce.conv(
  318. data, weight, {"bias_tensor": bias_tensor,
  319. "scale_q": scale_q,
  320. "offset_q": offset_q,
  321. "scale_drq": scale_drq,
  322. "offset_pad": offset_pad,
  323. "offset_rq": offset_rq,
  324. "quantize_config": quantize_config,
  325. "is_quantize": is_quantize,
  326. "is_dequantize": is_dequantize,
  327. "is_requantize": is_requantize,
  328. "scale_sqrt": scale_sqrt,
  329. "pad_h": padh, "pad_w": padw,
  330. "stride_h": strideh, "stride_w": stridew,
  331. "filter_h": filter_h, "filter_w": filter_w,
  332. "res_dtype": res_dtype, "mad_dtype": mad_dtype},
  333. dsl_flag=False)
  334. if bias:
  335. tensor_list = [data, weight, bias_tensor, scale_q,
  336. scale_drq, conv_res]
  337. else:
  338. tensor_list = [data, weight, scale_q,
  339. scale_drq, conv_res]
  340. else:
  341. if is_dequantize:
  342. scale_drq = scale_dq
  343. else:
  344. scale_drq = scale_rq
  345. conv_res = te.lang.cce.conv(
  346. data, weight, {"bias_tensor": bias_tensor,
  347. "scale_q": scale_q,
  348. "offset_q": offset_q,
  349. "scale_drq": scale_drq,
  350. "offset_pad": offset_pad,
  351. "offset_rq": offset_rq,
  352. "quantize_config": quantize_config,
  353. "is_quantize": is_quantize,
  354. "is_dequantize": is_dequantize,
  355. "is_requantize": is_requantize,
  356. "scale_sqrt": scale_sqrt,
  357. "pad_h": padh, "pad_w": padw,
  358. "stride_h": strideh, "stride_w": stridew,
  359. "filter_h": filter_h, "filter_w": filter_w,
  360. "res_dtype": res_dtype, "mad_dtype": mad_dtype},
  361. dsl_flag=False)
  362. if bias:
  363. tensor_list = [data, weight, bias_tensor,
  364. scale_drq, conv_res]
  365. else:
  366. tensor_list = [data, weight,
  367. scale_drq, conv_res]
  368. # half offset
  369. else:
  370. if is_quantize:
  371. if is_dequantize:
  372. scale_drq = scale_dq
  373. else:
  374. scale_drq = scale_rq
  375. conv_res = te.lang.cce.conv(
  376. data, weight, {"bias_tensor": bias_tensor,
  377. "scale_q": scale_q,
  378. "offset_q": offset_q,
  379. "scale_drq": scale_drq,
  380. "offset_pad": offset_pad,
  381. "offset_rq": offset_rq,
  382. "quantize_config": quantize_config,
  383. "is_quantize": is_quantize,
  384. "is_dequantize": is_dequantize,
  385. "is_requantize": is_requantize,
  386. "scale_sqrt": scale_sqrt,
  387. "pad_h": padh, "pad_w": padw,
  388. "stride_h": strideh, "stride_w": stridew,
  389. "filter_h": filter_h, "filter_w": filter_w,
  390. "res_dtype": res_dtype, "mad_dtype": mad_dtype},
  391. dsl_flag=False)
  392. if is_dequantize:
  393. tensor_list = [data, weight, bias_tensor, scale_q, offset_q,
  394. scale_drq, offset_pad, conv_res]
  395. else:
  396. tensor_list = [data, weight, bias_tensor, scale_q, offset_q,
  397. scale_drq, offset_rq, offset_pad, conv_res]
  398. else:
  399. if is_dequantize:
  400. scale_drq = scale_dq
  401. else:
  402. scale_drq = scale_rq
  403. conv_res = te.lang.cce.conv(
  404. data, weight, {"bias_tensor": bias_tensor,
  405. "scale_q": scale_q,
  406. "offset_q": offset_q,
  407. "scale_drq": scale_drq,
  408. "offset_pad": offset_pad,
  409. "offset_rq": offset_rq,
  410. "quantize_config": quantize_config,
  411. "is_quantize": is_quantize,
  412. "is_dequantize": is_dequantize,
  413. "is_requantize": is_requantize,
  414. "scale_sqrt": scale_sqrt,
  415. "pad_h": padh, "pad_w": padw,
  416. "stride_h": strideh, "stride_w": stridew,
  417. "filter_h": filter_h, "filter_w": filter_w,
  418. "res_dtype": res_dtype, "mad_dtype": mad_dtype},
  419. dsl_flag=False)
  420. if is_dequantize:
  421. tensor_list = [data, weight, bias_tensor,
  422. scale_drq, offset_pad, conv_res]
  423. else:
  424. tensor_list = [data, weight, bias_tensor,
  425. scale_drq, offset_rq, offset_pad, conv_res]
  426. else:
  427. conv_res = te.lang.cce.conv(
  428. data, weight, {"bias_tensor": bias_tensor,
  429. "scale_q": scale_q,
  430. "offset_q": offset_q,
  431. "scale_drq": scale_drq,
  432. "offset_pad": offset_pad,
  433. "offset_rq": offset_rq,
  434. "quantize_config": quantize_config,
  435. "is_quantize": is_quantize,
  436. "is_dequantize": is_dequantize,
  437. "is_requantize": is_requantize,
  438. "scale_sqrt": scale_sqrt,
  439. "pad_h": padh, "pad_w": padw,
  440. "stride_h": strideh, "stride_w": stridew,
  441. "filter_h": filter_h, "filter_w": filter_w,
  442. "res_dtype": res_dtype, "mad_dtype": mad_dtype},
  443. dsl_flag=False)
  444. if bias:
  445. tensor_list = [data, weight, bias_tensor, conv_res]
  446. else:
  447. tensor_list = [data, weight, conv_res]
  448. sch = generic.auto_schedule(conv_res)
  449. config = {
  450. "print_ir": need_print,
  451. "need_build": need_build,
  452. "name": kernel_name,
  453. "tensor_list": tensor_list
  454. }
  455. te.lang.cce.cce_build_code(sch, config)