3
0

ops.py 53 KB

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