ops.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  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. import paddle
  15. import paddle.nn.functional as F
  16. import paddle.nn as nn
  17. from paddle import ParamAttr
  18. from paddle.regularizer import L2Decay
  19. from paddle import _C_ops
  20. from paddle import in_dynamic_mode
  21. from paddle.common_ops_import import Variable, LayerHelper, check_variable_and_dtype, check_type, check_dtype
  22. __all__ = [
  23. 'roi_pool',
  24. 'roi_align',
  25. 'prior_box',
  26. 'generate_proposals',
  27. 'box_coder',
  28. 'multiclass_nms',
  29. 'distribute_fpn_proposals',
  30. 'matrix_nms',
  31. 'batch_norm',
  32. 'mish',
  33. 'silu',
  34. 'swish',
  35. 'identity',
  36. ]
  37. def identity(x):
  38. return x
  39. def mish(x):
  40. return F.mish(x) if hasattr(F, mish) else x * F.tanh(F.softplus(x))
  41. def silu(x):
  42. return F.silu(x)
  43. def swish(x):
  44. return x * F.sigmoid(x)
  45. TRT_ACT_SPEC = {'swish': swish, 'silu': swish}
  46. ACT_SPEC = {'mish': mish, 'silu': silu}
  47. def get_act_fn(act=None, trt=False):
  48. assert act is None or isinstance(act, (
  49. str, dict)), 'name of activation should be str, dict or None'
  50. if not act:
  51. return identity
  52. if isinstance(act, dict):
  53. name = act['name']
  54. act.pop('name')
  55. kwargs = act
  56. else:
  57. name = act
  58. kwargs = dict()
  59. if trt and name in TRT_ACT_SPEC:
  60. fn = TRT_ACT_SPEC[name]
  61. elif name in ACT_SPEC:
  62. fn = ACT_SPEC[name]
  63. else:
  64. fn = getattr(F, name)
  65. return lambda x: fn(x, **kwargs)
  66. def batch_norm(ch,
  67. norm_type='bn',
  68. norm_decay=0.,
  69. freeze_norm=False,
  70. initializer=None,
  71. data_format='NCHW'):
  72. norm_lr = 0. if freeze_norm else 1.
  73. weight_attr = ParamAttr(
  74. initializer=initializer,
  75. learning_rate=norm_lr,
  76. regularizer=L2Decay(norm_decay),
  77. trainable=False if freeze_norm else True)
  78. bias_attr = ParamAttr(
  79. learning_rate=norm_lr,
  80. regularizer=L2Decay(norm_decay),
  81. trainable=False if freeze_norm else True)
  82. if norm_type in ['sync_bn', 'bn']:
  83. norm_layer = nn.BatchNorm2D(
  84. ch,
  85. weight_attr=weight_attr,
  86. bias_attr=bias_attr,
  87. data_format=data_format)
  88. norm_params = norm_layer.parameters()
  89. if freeze_norm:
  90. for param in norm_params:
  91. param.stop_gradient = True
  92. return norm_layer
  93. @paddle.jit.not_to_static
  94. def roi_pool(input,
  95. rois,
  96. output_size,
  97. spatial_scale=1.0,
  98. rois_num=None,
  99. name=None):
  100. """
  101. This operator implements the roi_pooling layer.
  102. Region of interest pooling (also known as RoI pooling) is to perform max pooling on inputs of nonuniform sizes to obtain fixed-size feature maps (e.g. 7*7).
  103. The operator has three steps:
  104. 1. Dividing each region proposal into equal-sized sections with output_size(h, w);
  105. 2. Finding the largest value in each section;
  106. 3. Copying these max values to the output buffer.
  107. For more information, please refer to https://stackoverflow.com/questions/43430056/what-is-roi-layer-in-fast-rcnn
  108. Args:
  109. input (Tensor): Input feature, 4D-Tensor with the shape of [N,C,H,W],
  110. where N is the batch size, C is the input channel, H is Height, W is weight.
  111. The data type is float32 or float64.
  112. rois (Tensor): ROIs (Regions of Interest) to pool over.
  113. 2D-Tensor or 2D-LoDTensor with the shape of [num_rois,4], the lod level is 1.
  114. Given as [[x1, y1, x2, y2], ...], (x1, y1) is the top left coordinates,
  115. and (x2, y2) is the bottom right coordinates.
  116. output_size (int or tuple[int, int]): The pooled output size(h, w), data type is int32. If int, h and w are both equal to output_size.
  117. spatial_scale (float, optional): Multiplicative spatial scale factor to translate ROI coords from their input scale to the scale used when pooling. Default: 1.0
  118. rois_num (Tensor): The number of RoIs in each image. Default: None
  119. name(str, optional): For detailed information, please refer
  120. to :ref:`api_guide_Name`. Usually name is no need to set and
  121. None by default.
  122. Returns:
  123. Tensor: The pooled feature, 4D-Tensor with the shape of [num_rois, C, output_size[0], output_size[1]].
  124. Examples:
  125. .. code-block:: python
  126. import paddle
  127. from paddlex.ppdet.modeling import ops
  128. paddle.enable_static()
  129. x = paddle.static.data(
  130. name='data', shape=[None, 256, 32, 32], dtype='float32')
  131. rois = paddle.static.data(
  132. name='rois', shape=[None, 4], dtype='float32')
  133. rois_num = paddle.static.data(name='rois_num', shape=[None], dtype='int32')
  134. pool_out = ops.roi_pool(
  135. input=x,
  136. rois=rois,
  137. output_size=(1, 1),
  138. spatial_scale=1.0,
  139. rois_num=rois_num)
  140. """
  141. check_type(output_size, 'output_size', (int, tuple), 'roi_pool')
  142. if isinstance(output_size, int):
  143. output_size = (output_size, output_size)
  144. pooled_height, pooled_width = output_size
  145. if in_dynamic_mode():
  146. assert rois_num is not None, "rois_num should not be None in dygraph mode."
  147. pool_out, argmaxes = _C_ops.roi_pool(
  148. input, rois, rois_num, "pooled_height", pooled_height,
  149. "pooled_width", pooled_width, "spatial_scale", spatial_scale)
  150. return pool_out, argmaxes
  151. else:
  152. check_variable_and_dtype(input, 'input', ['float32'], 'roi_pool')
  153. check_variable_and_dtype(rois, 'rois', ['float32'], 'roi_pool')
  154. helper = LayerHelper('roi_pool', **locals())
  155. dtype = helper.input_dtype()
  156. pool_out = helper.create_variable_for_type_inference(dtype)
  157. argmaxes = helper.create_variable_for_type_inference(dtype='int32')
  158. inputs = {
  159. "X": input,
  160. "ROIs": rois,
  161. }
  162. if rois_num is not None:
  163. inputs['RoisNum'] = rois_num
  164. helper.append_op(
  165. type="roi_pool",
  166. inputs=inputs,
  167. outputs={"Out": pool_out,
  168. "Argmax": argmaxes},
  169. attrs={
  170. "pooled_height": pooled_height,
  171. "pooled_width": pooled_width,
  172. "spatial_scale": spatial_scale
  173. })
  174. return pool_out, argmaxes
  175. @paddle.jit.not_to_static
  176. def roi_align(input,
  177. rois,
  178. output_size,
  179. spatial_scale=1.0,
  180. sampling_ratio=-1,
  181. rois_num=None,
  182. aligned=True,
  183. name=None):
  184. """
  185. Region of interest align (also known as RoI align) is to perform
  186. bilinear interpolation on inputs of nonuniform sizes to obtain
  187. fixed-size feature maps (e.g. 7*7)
  188. Dividing each region proposal into equal-sized sections with
  189. the pooled_width and pooled_height. Location remains the origin
  190. result.
  191. In each ROI bin, the value of the four regularly sampled locations
  192. are computed directly through bilinear interpolation. The output is
  193. the mean of four locations.
  194. Thus avoid the misaligned problem.
  195. Args:
  196. input (Tensor): Input feature, 4D-Tensor with the shape of [N,C,H,W],
  197. where N is the batch size, C is the input channel, H is Height, W is weight.
  198. The data type is float32 or float64.
  199. rois (Tensor): ROIs (Regions of Interest) to pool over.It should be
  200. a 2-D Tensor or 2-D LoDTensor of shape (num_rois, 4), the lod level is 1.
  201. The data type is float32 or float64. Given as [[x1, y1, x2, y2], ...],
  202. (x1, y1) is the top left coordinates, and (x2, y2) is the bottom right coordinates.
  203. output_size (int or tuple[int, int]): The pooled output size(h, w), data type is int32. If int, h and w are both equal to output_size.
  204. spatial_scale (float32, optional): Multiplicative spatial scale factor to translate ROI coords
  205. from their input scale to the scale used when pooling. Default: 1.0
  206. sampling_ratio(int32, optional): number of sampling points in the interpolation grid.
  207. If <=0, then grid points are adaptive to roi_width and pooled_w, likewise for height. Default: -1
  208. rois_num (Tensor): The number of RoIs in each image. Default: None
  209. name(str, optional): For detailed information, please refer
  210. to :ref:`api_guide_Name`. Usually name is no need to set and
  211. None by default.
  212. Returns:
  213. Tensor:
  214. Output: The output of ROIAlignOp is a 4-D tensor with shape (num_rois, channels, pooled_h, pooled_w). The data type is float32 or float64.
  215. Examples:
  216. .. code-block:: python
  217. import paddle
  218. from paddlex.ppdet.modeling import ops
  219. paddle.enable_static()
  220. x = paddle.static.data(
  221. name='data', shape=[None, 256, 32, 32], dtype='float32')
  222. rois = paddle.static.data(
  223. name='rois', shape=[None, 4], dtype='float32')
  224. rois_num = paddle.static.data(name='rois_num', shape=[None], dtype='int32')
  225. align_out = ops.roi_align(input=x,
  226. rois=rois,
  227. output_size=(7, 7),
  228. spatial_scale=0.5,
  229. sampling_ratio=-1,
  230. rois_num=rois_num)
  231. """
  232. check_type(output_size, 'output_size', (int, tuple), 'roi_align')
  233. if isinstance(output_size, int):
  234. output_size = (output_size, output_size)
  235. pooled_height, pooled_width = output_size
  236. if in_dynamic_mode():
  237. assert rois_num is not None, "rois_num should not be None in dygraph mode."
  238. align_out = _C_ops.roi_align(
  239. input, rois, rois_num, "pooled_height", pooled_height,
  240. "pooled_width", pooled_width, "spatial_scale", spatial_scale,
  241. "sampling_ratio", sampling_ratio, "aligned", aligned)
  242. return align_out
  243. else:
  244. check_variable_and_dtype(input, 'input', ['float32', 'float64'],
  245. 'roi_align')
  246. check_variable_and_dtype(rois, 'rois', ['float32', 'float64'],
  247. 'roi_align')
  248. helper = LayerHelper('roi_align', **locals())
  249. dtype = helper.input_dtype()
  250. align_out = helper.create_variable_for_type_inference(dtype)
  251. inputs = {
  252. "X": input,
  253. "ROIs": rois,
  254. }
  255. if rois_num is not None:
  256. inputs['RoisNum'] = rois_num
  257. helper.append_op(
  258. type="roi_align",
  259. inputs=inputs,
  260. outputs={"Out": align_out},
  261. attrs={
  262. "pooled_height": pooled_height,
  263. "pooled_width": pooled_width,
  264. "spatial_scale": spatial_scale,
  265. "sampling_ratio": sampling_ratio,
  266. "aligned": aligned,
  267. })
  268. return align_out
  269. @paddle.jit.not_to_static
  270. def distribute_fpn_proposals(fpn_rois,
  271. min_level,
  272. max_level,
  273. refer_level,
  274. refer_scale,
  275. pixel_offset=False,
  276. rois_num=None,
  277. name=None):
  278. r"""
  279. **This op only takes LoDTensor as input.** In Feature Pyramid Networks
  280. (FPN) models, it is needed to distribute all proposals into different FPN
  281. level, with respect to scale of the proposals, the referring scale and the
  282. referring level. Besides, to restore the order of proposals, we return an
  283. array which indicates the original index of rois in current proposals.
  284. To compute FPN level for each roi, the formula is given as follows:
  285. .. math::
  286. roi\_scale &= \sqrt{BBoxArea(fpn\_roi)}
  287. level = floor(&\log(\\frac{roi\_scale}{refer\_scale}) + refer\_level)
  288. where BBoxArea is a function to compute the area of each roi.
  289. Args:
  290. fpn_rois(Variable): 2-D Tensor with shape [N, 4] and data type is
  291. float32 or float64. The input fpn_rois.
  292. min_level(int32): The lowest level of FPN layer where the proposals come
  293. from.
  294. max_level(int32): The highest level of FPN layer where the proposals
  295. come from.
  296. refer_level(int32): The referring level of FPN layer with specified scale.
  297. refer_scale(int32): The referring scale of FPN layer with specified level.
  298. rois_num(Tensor): 1-D Tensor contains the number of RoIs in each image.
  299. The shape is [B] and data type is int32. B is the number of images.
  300. If it is not None then return a list of 1-D Tensor. Each element
  301. is the output RoIs' number of each image on the corresponding level
  302. and the shape is [B]. None by default.
  303. name(str, optional): For detailed information, please refer
  304. to :ref:`api_guide_Name`. Usually name is no need to set and
  305. None by default.
  306. Returns:
  307. Tuple:
  308. multi_rois(List) : A list of 2-D LoDTensor with shape [M, 4]
  309. and data type of float32 and float64. The length is
  310. max_level-min_level+1. The proposals in each FPN level.
  311. restore_ind(Variable): A 2-D Tensor with shape [N, 1], N is
  312. the number of total rois. The data type is int32. It is
  313. used to restore the order of fpn_rois.
  314. rois_num_per_level(List): A list of 1-D Tensor and each Tensor is
  315. the RoIs' number in each image on the corresponding level. The shape
  316. is [B] and data type of int32. B is the number of images
  317. Examples:
  318. .. code-block:: python
  319. import paddle
  320. from paddlex.ppdet.modeling import ops
  321. paddle.enable_static()
  322. fpn_rois = paddle.static.data(
  323. name='data', shape=[None, 4], dtype='float32', lod_level=1)
  324. multi_rois, restore_ind = ops.distribute_fpn_proposals(
  325. fpn_rois=fpn_rois,
  326. min_level=2,
  327. max_level=5,
  328. refer_level=4,
  329. refer_scale=224)
  330. """
  331. num_lvl = max_level - min_level + 1
  332. if in_dynamic_mode():
  333. assert rois_num is not None, "rois_num should not be None in dygraph mode."
  334. attrs = ('min_level', min_level, 'max_level', max_level, 'refer_level',
  335. refer_level, 'refer_scale', refer_scale, 'pixel_offset',
  336. pixel_offset)
  337. multi_rois, restore_ind, rois_num_per_level = _C_ops.distribute_fpn_proposals(
  338. fpn_rois, rois_num, num_lvl, num_lvl, *attrs)
  339. return multi_rois, restore_ind, rois_num_per_level
  340. else:
  341. check_variable_and_dtype(fpn_rois, 'fpn_rois', ['float32', 'float64'],
  342. 'distribute_fpn_proposals')
  343. helper = LayerHelper('distribute_fpn_proposals', **locals())
  344. dtype = helper.input_dtype('fpn_rois')
  345. multi_rois = [
  346. helper.create_variable_for_type_inference(dtype)
  347. for i in range(num_lvl)
  348. ]
  349. restore_ind = helper.create_variable_for_type_inference(dtype='int32')
  350. inputs = {'FpnRois': fpn_rois}
  351. outputs = {
  352. 'MultiFpnRois': multi_rois,
  353. 'RestoreIndex': restore_ind,
  354. }
  355. if rois_num is not None:
  356. inputs['RoisNum'] = rois_num
  357. rois_num_per_level = [
  358. helper.create_variable_for_type_inference(dtype='int32')
  359. for i in range(num_lvl)
  360. ]
  361. outputs['MultiLevelRoIsNum'] = rois_num_per_level
  362. else:
  363. rois_num_per_level = None
  364. helper.append_op(
  365. type='distribute_fpn_proposals',
  366. inputs=inputs,
  367. outputs=outputs,
  368. attrs={
  369. 'min_level': min_level,
  370. 'max_level': max_level,
  371. 'refer_level': refer_level,
  372. 'refer_scale': refer_scale,
  373. 'pixel_offset': pixel_offset
  374. })
  375. return multi_rois, restore_ind, rois_num_per_level
  376. @paddle.jit.not_to_static
  377. def prior_box(input,
  378. image,
  379. min_sizes,
  380. max_sizes=None,
  381. aspect_ratios=[1.],
  382. variance=[0.1, 0.1, 0.2, 0.2],
  383. flip=False,
  384. clip=False,
  385. steps=[0.0, 0.0],
  386. offset=0.5,
  387. min_max_aspect_ratios_order=False,
  388. name=None):
  389. """
  390. This op generates prior boxes for SSD(Single Shot MultiBox Detector) algorithm.
  391. Each position of the input produce N prior boxes, N is determined by
  392. the count of min_sizes, max_sizes and aspect_ratios, The size of the
  393. box is in range(min_size, max_size) interval, which is generated in
  394. sequence according to the aspect_ratios.
  395. Parameters:
  396. input(Tensor): 4-D tensor(NCHW), the data type should be float32 or float64.
  397. image(Tensor): 4-D tensor(NCHW), the input image data of PriorBoxOp,
  398. the data type should be float32 or float64.
  399. min_sizes(list|tuple|float): the min sizes of generated prior boxes.
  400. max_sizes(list|tuple|None): the max sizes of generated prior boxes.
  401. Default: None.
  402. aspect_ratios(list|tuple|float): the aspect ratios of generated
  403. prior boxes. Default: [1.].
  404. variance(list|tuple): the variances to be encoded in prior boxes.
  405. Default:[0.1, 0.1, 0.2, 0.2].
  406. flip(bool): Whether to flip aspect ratios. Default:False.
  407. clip(bool): Whether to clip out-of-boundary boxes. Default: False.
  408. step(list|tuple): Prior boxes step across width and height, If
  409. step[0] equals to 0.0 or step[1] equals to 0.0, the prior boxes step across
  410. height or weight of the input will be automatically calculated.
  411. Default: [0., 0.]
  412. offset(float): Prior boxes center offset. Default: 0.5
  413. min_max_aspect_ratios_order(bool): If set True, the output prior box is
  414. in order of [min, max, aspect_ratios], which is consistent with
  415. Caffe. Please note, this order affects the weights order of
  416. convolution layer followed by and does not affect the final
  417. detection results. Default: False.
  418. name(str, optional): The default value is None. Normally there is no need for
  419. user to set this property. For more information, please refer to :ref:`api_guide_Name`
  420. Returns:
  421. Tuple: A tuple with two Variable (boxes, variances)
  422. boxes(Tensor): the output prior boxes of PriorBox.
  423. 4-D tensor, the layout is [H, W, num_priors, 4].
  424. H is the height of input, W is the width of input,
  425. num_priors is the total box count of each position of input.
  426. variances(Tensor): the expanded variances of PriorBox.
  427. 4-D tensor, the layput is [H, W, num_priors, 4].
  428. H is the height of input, W is the width of input
  429. num_priors is the total box count of each position of input
  430. Examples:
  431. .. code-block:: python
  432. import paddle
  433. from paddlex.ppdet.modeling import ops
  434. paddle.enable_static()
  435. input = paddle.static.data(name="input", shape=[None,3,6,9])
  436. image = paddle.static.data(name="image", shape=[None,3,9,12])
  437. box, var = ops.prior_box(
  438. input=input,
  439. image=image,
  440. min_sizes=[100.],
  441. clip=True,
  442. flip=True)
  443. """
  444. helper = LayerHelper("prior_box", **locals())
  445. dtype = helper.input_dtype()
  446. check_variable_and_dtype(
  447. input, 'input', ['uint8', 'int8', 'float32', 'float64'], 'prior_box')
  448. def _is_list_or_tuple_(data):
  449. return (isinstance(data, list) or isinstance(data, tuple))
  450. if not _is_list_or_tuple_(min_sizes):
  451. min_sizes = [min_sizes]
  452. if not _is_list_or_tuple_(aspect_ratios):
  453. aspect_ratios = [aspect_ratios]
  454. if not (_is_list_or_tuple_(steps) and len(steps) == 2):
  455. raise ValueError('steps should be a list or tuple ',
  456. 'with length 2, (step_width, step_height).')
  457. min_sizes = list(map(float, min_sizes))
  458. aspect_ratios = list(map(float, aspect_ratios))
  459. steps = list(map(float, steps))
  460. cur_max_sizes = None
  461. if max_sizes is not None and len(max_sizes) > 0 and max_sizes[0] > 0:
  462. if not _is_list_or_tuple_(max_sizes):
  463. max_sizes = [max_sizes]
  464. cur_max_sizes = max_sizes
  465. if in_dynamic_mode():
  466. attrs = ('min_sizes', min_sizes, 'aspect_ratios', aspect_ratios,
  467. 'variances', variance, 'flip', flip, 'clip', clip, 'step_w',
  468. steps[0], 'step_h', steps[1], 'offset', offset,
  469. 'min_max_aspect_ratios_order', min_max_aspect_ratios_order)
  470. if cur_max_sizes is not None:
  471. attrs += ('max_sizes', cur_max_sizes)
  472. box, var = _C_ops.prior_box(input, image, *attrs)
  473. return box, var
  474. else:
  475. attrs = {
  476. 'min_sizes': min_sizes,
  477. 'aspect_ratios': aspect_ratios,
  478. 'variances': variance,
  479. 'flip': flip,
  480. 'clip': clip,
  481. 'step_w': steps[0],
  482. 'step_h': steps[1],
  483. 'offset': offset,
  484. 'min_max_aspect_ratios_order': min_max_aspect_ratios_order
  485. }
  486. if cur_max_sizes is not None:
  487. attrs['max_sizes'] = cur_max_sizes
  488. box = helper.create_variable_for_type_inference(dtype)
  489. var = helper.create_variable_for_type_inference(dtype)
  490. helper.append_op(
  491. type="prior_box",
  492. inputs={"Input": input,
  493. "Image": image},
  494. outputs={"Boxes": box,
  495. "Variances": var},
  496. attrs=attrs, )
  497. box.stop_gradient = True
  498. var.stop_gradient = True
  499. return box, var
  500. @paddle.jit.not_to_static
  501. def multiclass_nms(bboxes,
  502. scores,
  503. score_threshold,
  504. nms_top_k,
  505. keep_top_k,
  506. nms_threshold=0.3,
  507. normalized=True,
  508. nms_eta=1.,
  509. background_label=-1,
  510. return_index=False,
  511. return_rois_num=True,
  512. rois_num=None,
  513. name=None):
  514. """
  515. This operator is to do multi-class non maximum suppression (NMS) on
  516. boxes and scores.
  517. In the NMS step, this operator greedily selects a subset of detection bounding
  518. boxes that have high scores larger than score_threshold, if providing this
  519. threshold, then selects the largest nms_top_k confidences scores if nms_top_k
  520. is larger than -1. Then this operator pruns away boxes that have high IOU
  521. (intersection over union) overlap with already selected boxes by adaptive
  522. threshold NMS based on parameters of nms_threshold and nms_eta.
  523. Aftern NMS step, at most keep_top_k number of total bboxes are to be kept
  524. per image if keep_top_k is larger than -1.
  525. Args:
  526. bboxes (Tensor): Two types of bboxes are supported:
  527. 1. (Tensor) A 3-D Tensor with shape
  528. [N, M, 4 or 8 16 24 32] represents the
  529. predicted locations of M bounding bboxes,
  530. N is the batch size. Each bounding box has four
  531. coordinate values and the layout is
  532. [xmin, ymin, xmax, ymax], when box size equals to 4.
  533. 2. (LoDTensor) A 3-D Tensor with shape [M, C, 4]
  534. M is the number of bounding boxes, C is the
  535. class number
  536. scores (Tensor): Two types of scores are supported:
  537. 1. (Tensor) A 3-D Tensor with shape [N, C, M]
  538. represents the predicted confidence predictions.
  539. N is the batch size, C is the class number, M is
  540. number of bounding boxes. For each category there
  541. are total M scores which corresponding M bounding
  542. boxes. Please note, M is equal to the 2nd dimension
  543. of BBoxes.
  544. 2. (LoDTensor) A 2-D LoDTensor with shape [M, C].
  545. M is the number of bbox, C is the class number.
  546. In this case, input BBoxes should be the second
  547. case with shape [M, C, 4].
  548. background_label (int): The index of background label, the background
  549. label will be ignored. If set to -1, then all
  550. categories will be considered. Default: 0
  551. score_threshold (float): Threshold to filter out bounding boxes with
  552. low confidence score. If not provided,
  553. consider all boxes.
  554. nms_top_k (int): Maximum number of detections to be kept according to
  555. the confidences after the filtering detections based
  556. on score_threshold.
  557. nms_threshold (float): The threshold to be used in NMS. Default: 0.3
  558. nms_eta (float): The threshold to be used in NMS. Default: 1.0
  559. keep_top_k (int): Number of total bboxes to be kept per image after NMS
  560. step. -1 means keeping all bboxes after NMS step.
  561. normalized (bool): Whether detections are normalized. Default: True
  562. return_index(bool): Whether return selected index. Default: False
  563. rois_num(Tensor): 1-D Tensor contains the number of RoIs in each image.
  564. The shape is [B] and data type is int32. B is the number of images.
  565. If it is not None then return a list of 1-D Tensor. Each element
  566. is the output RoIs' number of each image on the corresponding level
  567. and the shape is [B]. None by default.
  568. name(str): Name of the multiclass nms op. Default: None.
  569. Returns:
  570. A tuple with two Variables: (Out, Index) if return_index is True,
  571. otherwise, a tuple with one Variable(Out) is returned.
  572. Out: A 2-D LoDTensor with shape [No, 6] represents the detections.
  573. Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
  574. or A 2-D LoDTensor with shape [No, 10] represents the detections.
  575. Each row has 10 values: [label, confidence, x1, y1, x2, y2, x3, y3,
  576. x4, y4]. No is the total number of detections.
  577. If all images have not detected results, all elements in LoD will be
  578. 0, and output tensor is empty (None).
  579. Index: Only return when return_index is True. A 2-D LoDTensor with
  580. shape [No, 1] represents the selected index which type is Integer.
  581. The index is the absolute value cross batches. No is the same number
  582. as Out. If the index is used to gather other attribute such as age,
  583. one needs to reshape the input(N, M, 1) to (N * M, 1) as first, where
  584. N is the batch size and M is the number of boxes.
  585. Examples:
  586. .. code-block:: python
  587. import paddle
  588. from paddlex.ppdet.modeling import ops
  589. boxes = paddle.static.data(name='bboxes', shape=[81, 4],
  590. dtype='float32', lod_level=1)
  591. scores = paddle.static.data(name='scores', shape=[81],
  592. dtype='float32', lod_level=1)
  593. out, index = ops.multiclass_nms(bboxes=boxes,
  594. scores=scores,
  595. background_label=0,
  596. score_threshold=0.5,
  597. nms_top_k=400,
  598. nms_threshold=0.3,
  599. keep_top_k=200,
  600. normalized=False,
  601. return_index=True)
  602. """
  603. helper = LayerHelper('multiclass_nms3', **locals())
  604. if in_dynamic_mode():
  605. if paddle.__version__ < '2.4.0':
  606. attrs = ('background_label', background_label, 'score_threshold',
  607. score_threshold, 'nms_top_k', nms_top_k, 'nms_threshold',
  608. nms_threshold, 'keep_top_k', keep_top_k, 'nms_eta',
  609. nms_eta, 'normalized', normalized)
  610. else:
  611. attrs = (score_threshold, nms_top_k, keep_top_k, nms_threshold,
  612. normalized, nms_eta, background_label)
  613. output, index, nms_rois_num = _C_ops.multiclass_nms3(bboxes, scores,
  614. rois_num, *attrs)
  615. if not return_index:
  616. index = None
  617. return output, nms_rois_num, index
  618. else:
  619. output = helper.create_variable_for_type_inference(dtype=bboxes.dtype)
  620. index = helper.create_variable_for_type_inference(dtype='int32')
  621. inputs = {'BBoxes': bboxes, 'Scores': scores}
  622. outputs = {'Out': output, 'Index': index}
  623. if rois_num is not None:
  624. inputs['RoisNum'] = rois_num
  625. if return_rois_num:
  626. nms_rois_num = helper.create_variable_for_type_inference(
  627. dtype='int32')
  628. outputs['NmsRoisNum'] = nms_rois_num
  629. helper.append_op(
  630. type="multiclass_nms3",
  631. inputs=inputs,
  632. attrs={
  633. 'background_label': background_label,
  634. 'score_threshold': score_threshold,
  635. 'nms_top_k': nms_top_k,
  636. 'nms_threshold': nms_threshold,
  637. 'keep_top_k': keep_top_k,
  638. 'nms_eta': nms_eta,
  639. 'normalized': normalized
  640. },
  641. outputs=outputs)
  642. output.stop_gradient = True
  643. index.stop_gradient = True
  644. if not return_index:
  645. index = None
  646. if not return_rois_num:
  647. nms_rois_num = None
  648. return output, nms_rois_num, index
  649. @paddle.jit.not_to_static
  650. def matrix_nms(bboxes,
  651. scores,
  652. score_threshold,
  653. post_threshold,
  654. nms_top_k,
  655. keep_top_k,
  656. use_gaussian=False,
  657. gaussian_sigma=2.,
  658. background_label=0,
  659. normalized=True,
  660. return_index=False,
  661. return_rois_num=True,
  662. name=None):
  663. """
  664. **Matrix NMS**
  665. This operator does matrix non maximum suppression (NMS).
  666. First selects a subset of candidate bounding boxes that have higher scores
  667. than score_threshold (if provided), then the top k candidate is selected if
  668. nms_top_k is larger than -1. Score of the remaining candidate are then
  669. decayed according to the Matrix NMS scheme.
  670. Aftern NMS step, at most keep_top_k number of total bboxes are to be kept
  671. per image if keep_top_k is larger than -1.
  672. Args:
  673. bboxes (Tensor): A 3-D Tensor with shape [N, M, 4] represents the
  674. predicted locations of M bounding bboxes,
  675. N is the batch size. Each bounding box has four
  676. coordinate values and the layout is
  677. [xmin, ymin, xmax, ymax], when box size equals to 4.
  678. The data type is float32 or float64.
  679. scores (Tensor): A 3-D Tensor with shape [N, C, M]
  680. represents the predicted confidence predictions.
  681. N is the batch size, C is the class number, M is
  682. number of bounding boxes. For each category there
  683. are total M scores which corresponding M bounding
  684. boxes. Please note, M is equal to the 2nd dimension
  685. of BBoxes. The data type is float32 or float64.
  686. score_threshold (float): Threshold to filter out bounding boxes with
  687. low confidence score.
  688. post_threshold (float): Threshold to filter out bounding boxes with
  689. low confidence score AFTER decaying.
  690. nms_top_k (int): Maximum number of detections to be kept according to
  691. the confidences after the filtering detections based
  692. on score_threshold.
  693. keep_top_k (int): Number of total bboxes to be kept per image after NMS
  694. step. -1 means keeping all bboxes after NMS step.
  695. use_gaussian (bool): Use Gaussian as the decay function. Default: False
  696. gaussian_sigma (float): Sigma for Gaussian decay function. Default: 2.0
  697. background_label (int): The index of background label, the background
  698. label will be ignored. If set to -1, then all
  699. categories will be considered. Default: 0
  700. normalized (bool): Whether detections are normalized. Default: True
  701. return_index(bool): Whether return selected index. Default: False
  702. return_rois_num(bool): whether return rois_num. Default: True
  703. name(str): Name of the matrix nms op. Default: None.
  704. Returns:
  705. A tuple with three Tensor: (Out, Index, RoisNum) if return_index is True,
  706. otherwise, a tuple with two Tensor (Out, RoisNum) is returned.
  707. Out (Tensor): A 2-D Tensor with shape [No, 6] containing the
  708. detection results.
  709. Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
  710. (After version 1.3, when no boxes detected, the lod is changed
  711. from {0} to {1})
  712. Index (Tensor): A 2-D Tensor with shape [No, 1] containing the
  713. selected indices, which are absolute values cross batches.
  714. rois_num (Tensor): A 1-D Tensor with shape [N] containing
  715. the number of detected boxes in each image.
  716. Examples:
  717. .. code-block:: python
  718. import paddle
  719. from paddlex.ppdet.modeling import ops
  720. boxes = paddle.static.data(name='bboxes', shape=[None,81, 4],
  721. dtype='float32', lod_level=1)
  722. scores = paddle.static.data(name='scores', shape=[None,81],
  723. dtype='float32', lod_level=1)
  724. out = ops.matrix_nms(bboxes=boxes, scores=scores, background_label=0,
  725. score_threshold=0.5, post_threshold=0.1,
  726. nms_top_k=400, keep_top_k=200, normalized=False)
  727. """
  728. check_variable_and_dtype(bboxes, 'BBoxes', ['float32', 'float64'],
  729. 'matrix_nms')
  730. check_variable_and_dtype(scores, 'Scores', ['float32', 'float64'],
  731. 'matrix_nms')
  732. check_type(score_threshold, 'score_threshold', float, 'matrix_nms')
  733. check_type(post_threshold, 'post_threshold', float, 'matrix_nms')
  734. check_type(nms_top_k, 'nums_top_k', int, 'matrix_nms')
  735. check_type(keep_top_k, 'keep_top_k', int, 'matrix_nms')
  736. check_type(normalized, 'normalized', bool, 'matrix_nms')
  737. check_type(use_gaussian, 'use_gaussian', bool, 'matrix_nms')
  738. check_type(gaussian_sigma, 'gaussian_sigma', float, 'matrix_nms')
  739. check_type(background_label, 'background_label', int, 'matrix_nms')
  740. if in_dynamic_mode():
  741. attrs = ('background_label', background_label, 'score_threshold',
  742. score_threshold, 'post_threshold', post_threshold,
  743. 'nms_top_k', nms_top_k, 'gaussian_sigma', gaussian_sigma,
  744. 'use_gaussian', use_gaussian, 'keep_top_k', keep_top_k,
  745. 'normalized', normalized)
  746. out, index, rois_num = _C_ops.matrix_nms(bboxes, scores, *attrs)
  747. if not return_index:
  748. index = None
  749. if not return_rois_num:
  750. rois_num = None
  751. return out, rois_num, index
  752. else:
  753. helper = LayerHelper('matrix_nms', **locals())
  754. output = helper.create_variable_for_type_inference(dtype=bboxes.dtype)
  755. index = helper.create_variable_for_type_inference(dtype='int32')
  756. outputs = {'Out': output, 'Index': index}
  757. if return_rois_num:
  758. rois_num = helper.create_variable_for_type_inference(dtype='int32')
  759. outputs['RoisNum'] = rois_num
  760. helper.append_op(
  761. type="matrix_nms",
  762. inputs={'BBoxes': bboxes,
  763. 'Scores': scores},
  764. attrs={
  765. 'background_label': background_label,
  766. 'score_threshold': score_threshold,
  767. 'post_threshold': post_threshold,
  768. 'nms_top_k': nms_top_k,
  769. 'gaussian_sigma': gaussian_sigma,
  770. 'use_gaussian': use_gaussian,
  771. 'keep_top_k': keep_top_k,
  772. 'normalized': normalized
  773. },
  774. outputs=outputs)
  775. output.stop_gradient = True
  776. if not return_index:
  777. index = None
  778. if not return_rois_num:
  779. rois_num = None
  780. return output, rois_num, index
  781. @paddle.jit.not_to_static
  782. def box_coder(prior_box,
  783. prior_box_var,
  784. target_box,
  785. code_type="encode_center_size",
  786. box_normalized=True,
  787. axis=0,
  788. name=None):
  789. r"""
  790. **Box Coder Layer**
  791. Encode/Decode the target bounding box with the priorbox information.
  792. The Encoding schema described below:
  793. .. math::
  794. ox = (tx - px) / pw / pxv
  795. oy = (ty - py) / ph / pyv
  796. ow = \log(\abs(tw / pw)) / pwv
  797. oh = \log(\abs(th / ph)) / phv
  798. The Decoding schema described below:
  799. .. math::
  800. ox = (pw * pxv * tx * + px) - tw / 2
  801. oy = (ph * pyv * ty * + py) - th / 2
  802. ow = \exp(pwv * tw) * pw + tw / 2
  803. oh = \exp(phv * th) * ph + th / 2
  804. where `tx`, `ty`, `tw`, `th` denote the target box's center coordinates,
  805. width and height respectively. Similarly, `px`, `py`, `pw`, `ph` denote
  806. the priorbox's (anchor) center coordinates, width and height. `pxv`,
  807. `pyv`, `pwv`, `phv` denote the variance of the priorbox and `ox`, `oy`,
  808. `ow`, `oh` denote the encoded/decoded coordinates, width and height.
  809. During Box Decoding, two modes for broadcast are supported. Say target
  810. box has shape [N, M, 4], and the shape of prior box can be [N, 4] or
  811. [M, 4]. Then prior box will broadcast to target box along the
  812. assigned axis.
  813. Args:
  814. prior_box(Tensor): Box list prior_box is a 2-D Tensor with shape
  815. [M, 4] holds M boxes and data type is float32 or float64. Each box
  816. is represented as [xmin, ymin, xmax, ymax], [xmin, ymin] is the
  817. left top coordinate of the anchor box, if the input is image feature
  818. map, they are close to the origin of the coordinate system.
  819. [xmax, ymax] is the right bottom coordinate of the anchor box.
  820. prior_box_var(List|Tensor|None): prior_box_var supports three types
  821. of input. One is Tensor with shape [M, 4] which holds M group and
  822. data type is float32 or float64. The second is list consist of
  823. 4 elements shared by all boxes and data type is float32 or float64.
  824. Other is None and not involved in calculation.
  825. target_box(Tensor): This input can be a 2-D LoDTensor with shape
  826. [N, 4] when code_type is 'encode_center_size'. This input also can
  827. be a 3-D Tensor with shape [N, M, 4] when code_type is
  828. 'decode_center_size'. Each box is represented as
  829. [xmin, ymin, xmax, ymax]. The data type is float32 or float64.
  830. code_type(str): The code type used with the target box. It can be
  831. `encode_center_size` or `decode_center_size`. `encode_center_size`
  832. by default.
  833. box_normalized(bool): Whether treat the priorbox as a normalized box.
  834. Set true by default.
  835. axis(int): Which axis in PriorBox to broadcast for box decode,
  836. for example, if axis is 0 and TargetBox has shape [N, M, 4] and
  837. PriorBox has shape [M, 4], then PriorBox will broadcast to [N, M, 4]
  838. for decoding. It is only valid when code type is
  839. `decode_center_size`. Set 0 by default.
  840. name(str, optional): For detailed information, please refer
  841. to :ref:`api_guide_Name`. Usually name is no need to set and
  842. None by default.
  843. Returns:
  844. Tensor:
  845. output_box(Tensor): When code_type is 'encode_center_size', the
  846. output tensor of box_coder_op with shape [N, M, 4] representing the
  847. result of N target boxes encoded with M Prior boxes and variances.
  848. When code_type is 'decode_center_size', N represents the batch size
  849. and M represents the number of decoded boxes.
  850. Examples:
  851. .. code-block:: python
  852. import paddle
  853. from paddlex.ppdet.modeling import ops
  854. paddle.enable_static()
  855. # For encode
  856. prior_box_encode = paddle.static.data(name='prior_box_encode',
  857. shape=[512, 4],
  858. dtype='float32')
  859. target_box_encode = paddle.static.data(name='target_box_encode',
  860. shape=[81, 4],
  861. dtype='float32')
  862. output_encode = ops.box_coder(prior_box=prior_box_encode,
  863. prior_box_var=[0.1,0.1,0.2,0.2],
  864. target_box=target_box_encode,
  865. code_type="encode_center_size")
  866. # For decode
  867. prior_box_decode = paddle.static.data(name='prior_box_decode',
  868. shape=[512, 4],
  869. dtype='float32')
  870. target_box_decode = paddle.static.data(name='target_box_decode',
  871. shape=[512, 81, 4],
  872. dtype='float32')
  873. output_decode = ops.box_coder(prior_box=prior_box_decode,
  874. prior_box_var=[0.1,0.1,0.2,0.2],
  875. target_box=target_box_decode,
  876. code_type="decode_center_size",
  877. box_normalized=False,
  878. axis=1)
  879. """
  880. check_variable_and_dtype(prior_box, 'prior_box', ['float32', 'float64'],
  881. 'box_coder')
  882. check_variable_and_dtype(target_box, 'target_box', ['float32', 'float64'],
  883. 'box_coder')
  884. if in_dynamic_mode():
  885. if isinstance(prior_box_var, Variable):
  886. output_box = _C_ops.box_coder(
  887. prior_box, prior_box_var, target_box, "code_type", code_type,
  888. "box_normalized", box_normalized, "axis", axis)
  889. elif isinstance(prior_box_var, list):
  890. output_box = _C_ops.box_coder(
  891. prior_box, None, target_box, "code_type", code_type,
  892. "box_normalized", box_normalized, "axis", axis, "variance",
  893. prior_box_var)
  894. else:
  895. raise TypeError(
  896. "Input variance of box_coder must be Variable or list")
  897. return output_box
  898. else:
  899. helper = LayerHelper("box_coder", **locals())
  900. output_box = helper.create_variable_for_type_inference(
  901. dtype=prior_box.dtype)
  902. inputs = {"PriorBox": prior_box, "TargetBox": target_box}
  903. attrs = {
  904. "code_type": code_type,
  905. "box_normalized": box_normalized,
  906. "axis": axis
  907. }
  908. if isinstance(prior_box_var, Variable):
  909. inputs['PriorBoxVar'] = prior_box_var
  910. elif isinstance(prior_box_var, list):
  911. attrs['variance'] = prior_box_var
  912. else:
  913. raise TypeError(
  914. "Input variance of box_coder must be Variable or list")
  915. helper.append_op(
  916. type="box_coder",
  917. inputs=inputs,
  918. attrs=attrs,
  919. outputs={"OutputBox": output_box})
  920. return output_box
  921. @paddle.jit.not_to_static
  922. def generate_proposals(scores,
  923. bbox_deltas,
  924. im_shape,
  925. anchors,
  926. variances,
  927. pre_nms_top_n=6000,
  928. post_nms_top_n=1000,
  929. nms_thresh=0.5,
  930. min_size=0.1,
  931. eta=1.0,
  932. pixel_offset=False,
  933. return_rois_num=False,
  934. name=None):
  935. """
  936. **Generate proposal Faster-RCNN**
  937. This operation proposes RoIs according to each box with their
  938. probability to be a foreground object and
  939. the box can be calculated by anchors. Bbox_deltais and scores
  940. to be an object are the output of RPN. Final proposals
  941. could be used to train detection net.
  942. For generating proposals, this operation performs following steps:
  943. 1. Transposes and resizes scores and bbox_deltas in size of
  944. (H*W*A, 1) and (H*W*A, 4)
  945. 2. Calculate box locations as proposals candidates.
  946. 3. Clip boxes to image
  947. 4. Remove predicted boxes with small area.
  948. 5. Apply NMS to get final proposals as output.
  949. Args:
  950. scores(Tensor): A 4-D Tensor with shape [N, A, H, W] represents
  951. the probability for each box to be an object.
  952. N is batch size, A is number of anchors, H and W are height and
  953. width of the feature map. The data type must be float32.
  954. bbox_deltas(Tensor): A 4-D Tensor with shape [N, 4*A, H, W]
  955. represents the difference between predicted box location and
  956. anchor location. The data type must be float32.
  957. im_shape(Tensor): A 2-D Tensor with shape [N, 2] represents H, W, the
  958. origin image size or input size. The data type can be float32 or
  959. float64.
  960. anchors(Tensor): A 4-D Tensor represents the anchors with a layout
  961. of [H, W, A, 4]. H and W are height and width of the feature map,
  962. num_anchors is the box count of each position. Each anchor is
  963. in (xmin, ymin, xmax, ymax) format an unnormalized. The data type must be float32.
  964. variances(Tensor): A 4-D Tensor. The expanded variances of anchors with a layout of
  965. [H, W, num_priors, 4]. Each variance is in
  966. (xcenter, ycenter, w, h) format. The data type must be float32.
  967. pre_nms_top_n(float): Number of total bboxes to be kept per
  968. image before NMS. The data type must be float32. `6000` by default.
  969. post_nms_top_n(float): Number of total bboxes to be kept per
  970. image after NMS. The data type must be float32. `1000` by default.
  971. nms_thresh(float): Threshold in NMS. The data type must be float32. `0.5` by default.
  972. min_size(float): Remove predicted boxes with either height or
  973. width < min_size. The data type must be float32. `0.1` by default.
  974. eta(float): Apply in adaptive NMS, if adaptive `threshold > 0.5`,
  975. `adaptive_threshold = adaptive_threshold * eta` in each iteration.
  976. return_rois_num(bool): When setting True, it will return a 1D Tensor with shape [N, ] that includes Rois's
  977. num of each image in one batch. The N is the image's num. For example, the tensor has values [4,5] that represents
  978. the first image has 4 Rois, the second image has 5 Rois. It only used in rcnn model.
  979. 'False' by default.
  980. name(str, optional): For detailed information, please refer
  981. to :ref:`api_guide_Name`. Usually name is no need to set and
  982. None by default.
  983. Returns:
  984. tuple:
  985. A tuple with format ``(rpn_rois, rpn_roi_probs)``.
  986. - **rpn_rois**: The generated RoIs. 2-D Tensor with shape ``[N, 4]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``.
  987. - **rpn_roi_probs**: The scores of generated RoIs. 2-D Tensor with shape ``[N, 1]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``.
  988. Examples:
  989. .. code-block:: python
  990. import paddle
  991. from paddlex.ppdet.modeling import ops
  992. paddle.enable_static()
  993. scores = paddle.static.data(name='scores', shape=[None, 4, 5, 5], dtype='float32')
  994. bbox_deltas = paddle.static.data(name='bbox_deltas', shape=[None, 16, 5, 5], dtype='float32')
  995. im_shape = paddle.static.data(name='im_shape', shape=[None, 2], dtype='float32')
  996. anchors = paddle.static.data(name='anchors', shape=[None, 5, 4, 4], dtype='float32')
  997. variances = paddle.static.data(name='variances', shape=[None, 5, 10, 4], dtype='float32')
  998. rois, roi_probs = ops.generate_proposals(scores, bbox_deltas,
  999. im_shape, anchors, variances)
  1000. """
  1001. if in_dynamic_mode():
  1002. assert return_rois_num, "return_rois_num should be True in dygraph mode."
  1003. attrs = ('pre_nms_topN', pre_nms_top_n, 'post_nms_topN',
  1004. post_nms_top_n, 'nms_thresh', nms_thresh, 'min_size',
  1005. min_size, 'eta', eta, 'pixel_offset', pixel_offset)
  1006. rpn_rois, rpn_roi_probs, rpn_rois_num = _C_ops.generate_proposals_v2(
  1007. scores, bbox_deltas, im_shape, anchors, variances, *attrs)
  1008. if not return_rois_num:
  1009. rpn_rois_num = None
  1010. return rpn_rois, rpn_roi_probs, rpn_rois_num
  1011. else:
  1012. helper = LayerHelper('generate_proposals_v2', **locals())
  1013. check_variable_and_dtype(scores, 'scores', ['float32'],
  1014. 'generate_proposals_v2')
  1015. check_variable_and_dtype(bbox_deltas, 'bbox_deltas', ['float32'],
  1016. 'generate_proposals_v2')
  1017. check_variable_and_dtype(im_shape, 'im_shape', ['float32', 'float64'],
  1018. 'generate_proposals_v2')
  1019. check_variable_and_dtype(anchors, 'anchors', ['float32'],
  1020. 'generate_proposals_v2')
  1021. check_variable_and_dtype(variances, 'variances', ['float32'],
  1022. 'generate_proposals_v2')
  1023. rpn_rois = helper.create_variable_for_type_inference(
  1024. dtype=bbox_deltas.dtype)
  1025. rpn_roi_probs = helper.create_variable_for_type_inference(
  1026. dtype=scores.dtype)
  1027. outputs = {
  1028. 'RpnRois': rpn_rois,
  1029. 'RpnRoiProbs': rpn_roi_probs,
  1030. }
  1031. if return_rois_num:
  1032. rpn_rois_num = helper.create_variable_for_type_inference(
  1033. dtype='int32')
  1034. rpn_rois_num.stop_gradient = True
  1035. outputs['RpnRoisNum'] = rpn_rois_num
  1036. helper.append_op(
  1037. type="generate_proposals_v2",
  1038. inputs={
  1039. 'Scores': scores,
  1040. 'BboxDeltas': bbox_deltas,
  1041. 'ImShape': im_shape,
  1042. 'Anchors': anchors,
  1043. 'Variances': variances
  1044. },
  1045. attrs={
  1046. 'pre_nms_topN': pre_nms_top_n,
  1047. 'post_nms_topN': post_nms_top_n,
  1048. 'nms_thresh': nms_thresh,
  1049. 'min_size': min_size,
  1050. 'eta': eta,
  1051. 'pixel_offset': pixel_offset
  1052. },
  1053. outputs=outputs)
  1054. rpn_rois.stop_gradient = True
  1055. rpn_roi_probs.stop_gradient = True
  1056. if not return_rois_num:
  1057. rpn_rois_num = None
  1058. return rpn_rois, rpn_roi_probs, rpn_rois_num
  1059. def sigmoid_cross_entropy_with_logits(input,
  1060. label,
  1061. ignore_index=-100,
  1062. normalize=False):
  1063. output = F.binary_cross_entropy_with_logits(input, label, reduction='none')
  1064. mask_tensor = paddle.cast(label != ignore_index, 'float32')
  1065. output = paddle.multiply(output, mask_tensor)
  1066. if normalize:
  1067. sum_valid_mask = paddle.sum(mask_tensor)
  1068. output = output / sum_valid_mask
  1069. return output
  1070. def smooth_l1(input,
  1071. label,
  1072. inside_weight=None,
  1073. outside_weight=None,
  1074. sigma=None):
  1075. input_new = paddle.multiply(input, inside_weight)
  1076. label_new = paddle.multiply(label, inside_weight)
  1077. delta = 1 / (sigma * sigma)
  1078. out = F.smooth_l1_loss(input_new, label_new, reduction='none', delta=delta)
  1079. out = paddle.multiply(out, outside_weight)
  1080. out = out / delta
  1081. out = paddle.reshape(out, shape=[out.shape[0], -1])
  1082. out = paddle.sum(out, axis=1)
  1083. return out
  1084. def channel_shuffle(x, groups):
  1085. batch_size, num_channels, height, width = x.shape[0:4]
  1086. assert num_channels % groups == 0, 'num_channels should be divisible by groups'
  1087. channels_per_group = num_channels // groups
  1088. x = paddle.reshape(
  1089. x=x, shape=[batch_size, groups, channels_per_group, height, width])
  1090. x = paddle.transpose(x=x, perm=[0, 2, 1, 3, 4])
  1091. x = paddle.reshape(x=x, shape=[batch_size, num_channels, height, width])
  1092. return x
  1093. def get_static_shape(tensor):
  1094. shape = paddle.shape(tensor)
  1095. shape.stop_gradient = True
  1096. return shape