├── LICENSE ├── README.md ├── parsers └── onnx │ └── builtin_op_importers.cpp ├── plugin ├── maskrcnnRoIAlignPlugin │ ├── CMakeLists.txt │ ├── README.md │ ├── maskrcnnRoIAlignPlugin.cpp │ ├── maskrcnnRoIAlignPlugin.h │ ├── roiAlign.cu │ └── roiAlign.h └── nonMaxSuppressionPlugin │ ├── CMakeLists.txt │ ├── README.md │ ├── gatherNMSOutputs.cu │ ├── gatherNMSOutputs.h │ ├── nonMaxSuppressionInference.cpp │ ├── nonMaxSuppressionInference.h │ ├── nonMaxSuppressionPlugin.cpp │ └── nonMaxSuppressionPlugin.h └── symbolic_opset10.py /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [toc] 2 | # 背景 3 | 4 | 在实际工作当中,训练的模型到实际使用还需要有模型加速过程,比如剪枝,替换backbone,蒸馏等方法。本文主要在硬件级别对模型进行加速。 5 | 6 | TensorRT是NVIDIA专门针对自家显卡做深度学习推理加速的框架,可为深度学习推理应用提供低延迟和高吞吐量。Pytorch是FAIR代言的训练工具,其简单易用的特点使得其成为用户数增长最快的深度学习训练框架,越来越多的学术论文放出来的源码是使用Pytorch训练。 7 | 8 | 转换模型的目的是在对应硬件上达到提速降耗效果。目前各个公司都推出了自己的框架,训练模型常用的如Facebook的Pytorch,Google的TensorFlow,Amazon的Mxnet,只有前向的如Microsoft的ONNX,NVIDIA的TensorRT,Intel的OpenVINO。各个公司的开发速度有快有慢,比如pytorch支持的功能onnx不支持,tensorrt又要与各个版本的onnx做对应开发,本文的作用就是对各个框架的协调一致,达到最终的加速目标。 9 | 10 | 转换过程也是一个学习的过程。首先需要对几个框架有所了解,如果出现问题,可以在对应框架的官方文档、github的issue区或者Google搜索。过程需要耐心和细心,涉及到python、c++、cuda、cmakefile等相关知识,通过这次转换,也可以加深自己对这几种工具的理解程度,对以后的工作也会有帮助作用。 11 | 12 | 本文使用的方法为利用ONNX作为中间框架,先将pytorch模型转为onnx模型,然后再转为tensorrt模型。勇于探索的同学可以尝试直接使用[torch2trt项目](https://github.com/NVIDIA-AI-IOT/torch2trt)。在pytorch和tensorrt的官方文档中对这两步转换的说明以及示例比较清晰,本文主要对文档外的一些特殊情况做些补充说明。 13 | 14 | # 准备工作 15 | 16 | 先介绍一下本文使用到的软件版本,建议使用anaconda3,并升级gcc>=4.9。本文中使用torch===1.4.0,torchvision===0.5.0,cuda===10.0,gcc===5.2.0,onnxruntime。安装tensorrt,参考[文档](https://docs.nvidia.com/deeplearning/tensorrt/install-guide/index.html)。配合CUDA==10.0版本,我使用7.0版本的tensorrt,下载后配置环境变量,并安装对应版本的tensorrt-python和pycuda。 17 | 18 | 在shell界面运行下面命令,可以查看版本号是否与上面一致,第五项输出应该为True。如果使用更高版本pytorch,需搭配的nvidia显卡驱动版本高于发布平台使用的版本。但如果是外部环境可以使用高版本pytorch以及显卡驱动,最新的pytorch中转onnx部分更新速度非常快,对转换过程更加友好。 19 | 20 | ```bash 21 | python --version 22 | nvcc --version 23 | gcc --version 24 | python -c "import torch;print(torch.__version__)" 25 | python -c "import tensorrt as trt;print(trt.__version__)" 26 | python -c "import torch;print(torch.cuda.is_available())" 27 | ``` 28 | 29 | # Pytorch->ONNX 30 | 31 | 主要参考[Pytorch文档](https://pytorch.org/docs/master/onnx.html),分两种转换模式,第一种是trace-based,不支持动态网络,输入维度固定。第二种是script-based,支持动态网络,输入可变维度。 32 | 33 | 很显然第二种更加合理,但改起来相对比较复杂,这里面我们使用trace-based转换模式。另外Torchvision内部所有模型也全部支持转换到ONNX,参考文档见[这里](https://pytorch.org/docs/master/torchvision/models.html#faster-r-cnn)。 34 | 35 | ```python 36 | import torch 37 | import torchvision 38 | import numpy as np 39 | 40 | model = torchvision.models.alexnet(pretrained=True).cuda() 41 | model.eval() 42 | x = torch.rand(1, 3, 224, 224).to("cuda") 43 | with torch.no_grad(): 44 | predictions = model(x) 45 | trace_backbone = torch.jit.trace(model, x, check_trace=False) 46 | torch.onnx.export(trace_backbone, x, "alexnet.onnx", verbose=False, export_params=True, training=False, opset_version=10, example_outputs=predictions) 47 | 48 | # 运行onnx的示例 49 | import onnxruntime as ort 50 | ort_session = ort.InferenceSession('alexnet.onnx') 51 | onnx_outputs = ort_session.run(None, {ort_session.get_inputs()[0].name: x.cpu().numpy().astype(np.float32)}) 52 | 53 | # 校验结果 54 | print(predictions.cpu().numpy() - onnx_outputs) 55 | ``` 56 | 结果输出示例如下,可以看到差异出现在小数点后第七位数字,转换成功。 57 | ```bash 58 | [[[-4.7683716e-07 3.5762787e-07 3.8743019e-07 1.1920929e-07 59 | -9.5367432e-07 -1.0728836e-06 -1.4305115e-06 5.9604645e-08 60 | -7.1525574e-07 3.5762787e-07 5.9604645e-08 7.7486038e-07 61 | 1.1920929e-07 -5.9604645e-07 4.1723251e-07 -3.5762787e-07 62 | 0.0000000e+00 -1.7881393e-07 -1.1920929e-07 1.7881393e-07 63 | ... 64 | 4.7683716e-07 -2.3841858e-07 5.6624413e-07 2.3841858e-07 65 | -9.5367432e-07 -7.1525574e-07 2.3841858e-07 5.9604645e-07]]] 66 | ``` 67 | 68 | # ONNX->TensorRT 69 | 参考[TensorRT文档](https://docs.nvidia.com/deeplearning/sdk/tensorrt-developer-guide/index.html#import_onnx_python),以及一个[SSD例子](https://docs.nvidia.com/deeplearning/sdk/tensorrt-sample-support-guide/index.html#uff_ssd),我们大概可以写个简单的ONNX转换到TensorRT并实际运行的脚本。 70 | 71 | ```python 72 | import os 73 | import numpy as np 74 | import tensorrt as trt 75 | import pycuda.driver as cuda 76 | import pycuda.autoinit 77 | import onnxruntime as ort 78 | 79 | TRT_LOGGER = trt.Logger(trt.Logger.VERBOSE) 80 | EXPLICIT_BATCH = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) 81 | onnx_file_path = "alexnet.onnx" 82 | engine_file_path = "alexnet.trt" 83 | if os.path.exists(engine_file_path): 84 | # If a serialized engine exists, use it instead of building an engine. 85 | print("Reading engine from file {}".format(engine_file_path)) 86 | with open(engine_file_path, "rb") as f, trt.Runtime(TRT_LOGGER) as runtime: 87 | engine = runtime.deserialize_cuda_engine(f.read()) 88 | else: 89 | with trt.Builder(TRT_LOGGER) as builder, \ 90 | builder.create_network(EXPLICIT_BATCH) as network, \ 91 | trt.OnnxParser(network, TRT_LOGGER) as parser: 92 | with open(onnx_file_path, 'rb') as model: 93 | if not parser.parse(model.read()): 94 | print ('ERROR: Failed to parse the ONNX file.') 95 | for error in range(parser.num_errors): 96 | print (parser.get_error(error)) 97 | exit() 98 | print('Building an engine from file temp.pb; this may take a while...') 99 | engine = builder.build_cuda_engine(network) 100 | print("Completed creating Engine") 101 | with open(engine_file_path, "wb") as f: 102 | f.write(engine.serialize()) 103 | 104 | inputs = [] 105 | outputs = [] 106 | bindings = [] 107 | stream = cuda.Stream() 108 | 109 | for binding in engine: 110 | print(binding) 111 | size = trt.volume(engine.get_binding_shape(binding)) * engine.max_batch_size 112 | dtype = trt.nptype(engine.get_binding_dtype(binding)) 113 | 114 | host_mem = cuda.pagelocked_empty(size, dtype) 115 | device_mem = cuda.mem_alloc(host_mem.nbytes) 116 | 117 | bindings.append(int(device_mem)) 118 | 119 | if engine.binding_is_input(binding): 120 | inputs.append((host_mem, device_mem)) 121 | else: 122 | outputs.append((host_mem, device_mem)) 123 | 124 | def do_inference(context, bindings, inputs, outputs, stream, batch_size=1): 125 | [cuda.memcpy_htod_async(inp[1], inp[0], stream) for inp in inputs] 126 | context.execute_async(batch_size=batch_size, bindings=bindings, stream_handle=stream.handle) 127 | [cuda.memcpy_dtoh_async(out[0], out[1],stream) for out in outputs] 128 | stream.synchronize() 129 | return [out[0] for out in outputs] 130 | 131 | # 运行onnx的示例 132 | x = np.random.rand(1, 3, 224, 224).astype(np.float32) 133 | ort_session = ort.InferenceSession(onnx_file_path) 134 | onnx_outputs = ort_session.run(None, {ort_session.get_inputs()[0].name: x}) 135 | 136 | # 校验结果 137 | with engine.create_execution_context() as context: 138 | np.copyto(inputs[0][0], x.reshape(-1)) 139 | output = do_inference(context, bindings=bindings, inputs=inputs, outputs=outputs, stream=stream) 140 | pred = np.array(output) 141 | print(onnx_outputs - pred) 142 | ``` 143 | 144 | 结果也与上面类似,精确到小数点后六位左右。到这里,pytorch模型转为tensorrt模型就转换完成。保存的alexnet.trt文件可以省去再次使用时的转化步骤。可以提供给服务正常使用。 145 | 146 | # 复杂案例 147 | 上面我们转换的是一个非常成熟的Alexnet,但有时我们需要的模型可能稍微复杂一些,有一些自定义的层。接下来我们以一个最常见的FAIR实验室的[maskrcnn-benchmark](https://github.com/facebookresearch/maskrcnn-benchmark)中Faster RCNN模型为例,给大家简单说明一下转换过程中可能遇到的问题以及相关的解决思路。 148 | 149 | ## 编译自定义算子并运行demo 150 | 151 | 进入*maskrcnn-benchmark*目录,执行 152 | ```shell 153 | python setup.py build develop 154 | ``` 155 | 一般此处需要注意输出第一行,是否会出现找不到nvcc的异常,如果出现请把*/usr/local/cuda/bin*目录加入到路径中。执行时间大约5分钟,完毕后会在*maskrcnn_benchmark*目录出现一个*_C.{python-version}.so*的动态链接库。 156 | 157 | 新增如下代码,下载模型[地址](https://download.pytorch.org/models/maskrcnn/e2e_faster_rcnn_R_50_C4_1x.pth)到*models*文件夹,代码中的图片可以自行定义,这里我用了一张ImageNet的测试图像,模型为faster rcnn,使用resnet50作为特征提取模型,使用RoiAlign做特征池化,无FPN。新建脚本*demo/demo.py* 158 | 159 | ```python 160 | import cv2 161 | from maskrcnn_benchmark.config import cfg 162 | from predictor import COCODemo 163 | 164 | if __name__ == "__main__": 165 | image_name = "demo/ILSVRC2012_val_00050000.JPEG" 166 | config_file = "configs/e2e_faster_rcnn_R_50_C4_1x.yaml" 167 | weight_file = "models/e2e_faster_rcnn_R_50_C4_1x.pth" 168 | 169 | # update the config options with the config file 170 | cfg.merge_from_file(config_file) 171 | # manual override some options 172 | cfg.merge_from_list(["MODEL.DEVICE", "cuda", "MODEL.WEIGHT", weight_file]) 173 | 174 | coco_demo = COCODemo( 175 | cfg, 176 | min_image_size=800, 177 | confidence_threshold=0.7, 178 | ) 179 | # load image and then run prediction 180 | image = cv2.imread(image_name) 181 | height, width = image.shape[:2] 182 | predictions = coco_demo.run_on_opencv_image(image) 183 | print(predictions.shape) 184 | 185 | cv2.imwrite("out.jpg", predictions) 186 | ``` 187 | 188 | 修改脚本中的各个文件路径,保存后执行`python demo/demo.py`。如无异常可以查看*demo.jpg*的结果。这样我们就跑通了Resnet50为基础网络的Faster Rcnn模型。 189 | 190 | ## 转换为onnx 191 | 192 | ### 准备步骤 193 | 首先需要修改一下*maskrcnn_benchmark*工程文件,把输出值变成一个tensor,这样onnx才能够正确的读取模型输出。 194 | 195 | 首先在`maskrcnn_benchmark/config/defaults.py`中加一个标志位,表示我们是在进行转换。这个文件保存了所有的默认配置,与*configs*文件夹中yaml文件共同管理代码运行时的参数。 196 | 197 | ```python 198 | _C.MODEL.EXPORT_ON = False 199 | ``` 200 | 修改`maskrcnn_benchmark/modeling/detector/generalized_rcnn.py`文件,在开头加入 201 | 202 | ```python 203 | import torchvision 204 | ``` 205 | 206 | 在`__init__`函数中加入 207 | 208 | ```python 209 | self.cfg = cfg 210 | self.detections_per_img = cfg.MODEL.ROI_HEADS.DETECTIONS_PER_IMG 211 | ``` 212 | 在`forward`函数末尾,修改返回值类型从自定义的BoxList到torch.Tensor。并补齐一下使得返回值为定长。 213 | 214 | ```python 215 | ... 216 | if self.cfg.MODEL.EXPORT_ON: 217 | boxes = torch.stack([x.bbox for x in result], 0) 218 | scores = torch.stack([x.get_field("scores").unsqueeze(1) for x in result], 0) 219 | b = torch.cat((boxes, scores), 2) 220 | if not torchvision._is_tracing(): 221 | b_size = self.detections_per_img - int(b.size(1)) 222 | fill_zeros = torch.zeros((1, b_size, 5), dtype=torch.float, device=boxes.device) 223 | result = torch.cat((b, fill_zeros), 1) 224 | else: 225 | return b 226 | ... 227 | ``` 228 | ### 转换代码 229 | 新建转换onnx文件使用的脚本*tools/export_onnx.py* 230 | ```python 231 | import numpy as np 232 | import cv2 233 | import torch 234 | from maskrcnn_benchmark.config import cfg 235 | from predictor import COCODemo 236 | 237 | if __name__ == "__main__": 238 | config_file = "configs/e2e_faster_rcnn_R_50_C4_1x.yaml" 239 | 240 | # update the config options with the config file 241 | cfg.merge_from_file(config_file) 242 | # manual override some options 243 | cfg.merge_from_list(["MODEL.DEVICE", "cuda", "MODEL.WEIGHT", "models/e2e_faster_rcnn_R_50_C4_1x.pth", "MODEL.EXPORT_ON", True]) 244 | 245 | coco_demo = COCODemo( 246 | cfg, 247 | min_image_size=800, 248 | confidence_threshold=0.7, 249 | ) 250 | # load image and then run prediction 251 | image = cv2.imread("demo/ILSVRC2012_val_00050000.JPEG") 252 | height, width = image.shape[:2] 253 | # predictions = coco_demo.run_on_opencv_image(image) 254 | coco_demo.model.eval() 255 | image = cv2.resize(image, (768, 768)) 256 | image = np.stack([image] * 1, 0) 257 | images = torch.from_numpy(image).to(torch.float).to("cuda").permute(0, 3, 1, 2) 258 | 259 | with torch.no_grad(): 260 | features = coco_demo.model(images) 261 | 262 | trace_backbone = torch.jit.trace(coco_demo.model, images, check_trace=False) 263 | torch.onnx.export(trace_backbone, images, "models/fast_rcnn.onnx", verbose=True, export_params=True, training=False, opset_version=10, example_outputs=features) 264 | ``` 265 | 保存后执行命令`python tools/export_onnx.py`。 266 | 267 | ### 异常解析 268 | 269 | 执行命令后会有较长的输出,此时有两个地方需要注意,第一个是 270 | 271 | >/export/xxx/codes/maskrcnn-benchmark/maskrcnn_benchmark/structures/bounding_box.py:21: TracerWarning: torch.as_tensor results are registered as constants in the trace. You can safely ignore this warning if you use this function to create tensors out of constant variables that would be the same every time you call this function. In any other case, this might cause the trace to be incorrect. 272 | bbox = torch.as_tensor(bbox, dtype=torch.float32, device=device) 273 | 274 | 说明此处代码会使得变量变成一个常量,不会随输入发生改变。如果真的可以不发生变化的话,我们可以不用考虑。此处是输入,应该是一个变量而不是常量,修改`maskrcnn_benchmark/structures/bounding_box.py`文件,第21行修改为 275 | ```python 276 | ... 277 | if not isinstance(bbox, torch.Tensor): 278 | bbox = torch.as_tensor(bbox, dtype=torch.float32, device=device) 279 | ... 280 | ``` 281 | 第二个需要注意的是报错 282 | >Traceback (most recent call last): 283 | File "demo/export_onnx.py", line 33, in 284 | torch.onnx.export(trace_backbone, images, "fast_rcnn.onnx", verbose=True, export_params=True, training=False, opset_version=10, example_outputs=features) 285 | File "/root/xxx/env/anaconda3/lib/python3.6/site-packages/torch/onnx/\_\_init\_\_.py", line 148, in export 286 | strip_doc_string, dynamic_axes, keep_initializers_as_inputs) 287 | File "/root/xxx/env/anaconda3/lib/python3.6/site-packages/torch/onnx/utils.py", line 66, in export 288 | dynamic_axes=dynamic_axes, keep_initializers_as_inputs=keep_initializers_as_inputs) 289 | File "/root/xxx/env/anaconda3/lib/python3.6/site-packages/torch/onnx/utils.py", line 428, in \_export 290 | operator_export_type, strip_doc_string, val_keep_init_as_ip) 291 | RuntimeError: ONNX export failed: Couldn't export Python operator \_ROIAlign 292 | 293 | 说明上节中编译的`_ROIAlign`算子无法从pytorch转换为onnx,需要手动添加自定义层。 294 | ### 自定义算子 295 | 根据报错内容,找到`_ROIAlign`算子所在的文件位置,`maskrcnn_benchmark/layers/roi_align.py`。可以看到`_ROIAlign`层是一个`Function`的子类,在`forward`函数里面有一个`_C.roi_align_forward`命令,就是调用了刚才编译的动态链接库中的函数。我们需要在`_ROIAlign`类中加一个函数,参考[文档](https://pytorch.org/docs/master/onnx.html#custom-operators),让pytorch知道这个自定义的层应该怎么转为onnx。 296 | ```python 297 | @staticmethod 298 | @parse_args('v', 'v', 'is', 'i', 'f') 299 | def symbolic(g, input, roi, output_size, spatial_scale, sampling_ratio): 300 | output_size = g.op('Constant', value_t=torch.tensor([output_size], dtype=torch.int)) 301 | spatial_scale = g.op('Constant', value_t=torch.tensor([spatial_scale], dtype=torch.float)) 302 | sampling_ratio = g.op('Constant', value_t=torch.tensor([sampling_ratio], dtype=torch.float)) 303 | return g.op("MaskRcnnROIAlign", input, roi, output_size, spatial_scale, sampling_ratio) 304 | 305 | ``` 306 | 这里我们告诉pytorch,如果遇到这个自定义算子,前两个输入是tensor类型,后面跟着的分别是int list/int/float类型的三个变量。最终把这个方法转换为onnx中名为`MaskRcnnROIAlign`的算子。这个算子在onnx中并真实不存在,但是因为我们不需要运行onnx程序,所以可以不用在onnx中实现这个算子,只作为一个中间过渡使用。 307 | 308 | 重新运行上面的转换脚本,我们就可以成功得到*fast_rcnn.onnx*文件。此文件由于缺少算子,所以不能用onnxruntime执行。接下来我们把onnx文件转为tensorrt。 309 | 310 | ## 转换为Tensorrt 311 | ### 转换脚本 312 | 313 | 新建*tools/convert_model.py*转换脚本 314 | 315 | ```python 316 | import os 317 | import torch 318 | import tensorrt as trt 319 | import sys 320 | 321 | TRT_LOGGER = trt.Logger(trt.Logger.VERBOSE) 322 | EXPLICIT_BATCH = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) 323 | 324 | def GiB(val): 325 | return val * 1 << 30 326 | 327 | def conver_engine(onnx_file_path, engine_file_path="", max_batch_size=1): 328 | """Attempts to load a serialized engine if available, otherwise builds a new TensorRT engine and saves it.""" 329 | """Takes an ONNX file and creates a TensorRT engine to run inference with""" 330 | with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser(network, TRT_LOGGER) as parser: 331 | builder.max_workspace_size = GiB(max_batch_size) 332 | builder.max_batch_size = max_batch_size 333 | # Parse model file 334 | if not os.path.exists(onnx_file_path): 335 | print('ONNX file {} not found, please run yolov3_to_onnx.py first to generate it.'.format(onnx_file_path)) 336 | exit(0) 337 | print('Loading ONNX file from path {}...'.format(onnx_file_path)) 338 | with open(onnx_file_path, 'rb') as model: 339 | print('Beginning ONNX file parsing') 340 | if not parser.parse(model.read()): 341 | print ('ERROR: Failed to parse the ONNX file.') 342 | for error in range(parser.num_errors): 343 | print (parser.get_error(error)) 344 | return None 345 | # The actual yolov3.onnx is generated with batch size 64. Reshape input to batch size 1 346 | print('Completed parsing of ONNX file') 347 | print('Building an engine from file {}; this may take a while...'.format(onnx_file_path)) 348 | engine = builder.build_cuda_engine(network) 349 | print("Completed creating Engine") 350 | with open(engine_file_path, "wb") as f: 351 | f.write(engine.serialize()) 352 | print("Completed writing Engine. Well done!") 353 | 354 | if __name__ == "__main__": 355 | onnx_file_path = 'models/fast_rcnn.onnx' 356 | engine_file_path = "models/fast_rcnn.trt" 357 | conver_engine(onnx_file_path, engine_file_path) 358 | ``` 359 | 保存后执行`python tools/convert_model.py`。 360 | 361 | ### 异常解析之topK 362 | 363 | 由于是verbose级别的日志输出,会得到比较详细的日志。首先会出现topk异常,开启我们的debug之旅。 364 | 365 | >ERROR: Failed to parse the ONNX file. 366 | In node 669 (importTopK): UNSUPPORTED_NODE: Assertion failed: inputs.at(1).is_weights() 367 | 368 | 这是个问题曾经困扰了我很长时间,一度认为需要把模型拆分为多块转换,中间使用numpy连接。通过查找pytorch源码的issue区以及各个搜索引擎,我感觉修改pytorch源码以及TensorRT源码应该可以解决这个问题。 369 | #### 修改pytorch源码 370 | pytorch源码位置定位方法: 371 | 372 | 1. 使用`which python`找到python所在文件夹,比如 *~/anaconda3/bin/python*。 373 | 2. 使用`find ~/anaconda3 -name "torch"`找到torch所在文件夹 *~/anaconda3/lib/python3.6/site-packages/torch*。 374 | 375 | 进入这个文件夹,在*onnx*文件夹下保存着pytorch转换onnx调用的文件,在上节中我们使用`opset_version=10`,所以python会优先在*symbolic_opset10.py*文件中搜索转换方法,如果未搜寻到,会依次向低版本文件中搜寻。 376 | 377 | 由于10版本`topk`在tensorrt中支持较差,需使用9版本中的`topk`进行模型转换。备份后编辑*symbolic_opset10.py*文件,注释掉`topk`函数。重新转换onnx文件。 378 | 379 | #### 修改tensorrt源码 380 | 381 | 转换后依然有问题,这时需要重新编译TensorRT。首先找到刚才安装TensorRT的文件夹,比如*/absolute_path/env/TensorRT-7.0.0.11*, 382 | 383 | ```bash 384 | cd /absolute_path/env/TensorRT-7.0.0.11 385 | export TRT_RELEASE=`pwd` 386 | 387 | # 返回到env目录 388 | cd .. 389 | 390 | git clone -b master https://github.com/nvidia/TensorRT TensorRT 391 | cd TensorRT 392 | git submodule update --init --recursive 393 | export TRT_SOURCE=`pwd` 394 | 395 | # 重新编译 396 | cd $TRT_SOURCE 397 | mkdir -p build && cd build 398 | export CXX=/usr/local/bin/g++ 399 | cmake .. -DTRT_LIB_DIR=$TRT_RELEASE/lib -DTRT_OUT_DIR=`pwd` -DCUDA_VERISON=10.0 -DCUDNN_VERSION=7.5 -DPROTOBUF_VERSION=3.8.0 -DBUILD_PARSERS=ON -DBUILD_PLUGINS=ON -DBUILD_SAMPLES=OFF 400 | make -j$(nproc) 401 | ``` 402 | 403 | 编译建议使用c++4.x版本,所以会在cmake上一步指定使用系统g++。在执行cmake命令时,酌情根据自己机器环境修改参数。 404 | 405 | 这里有个小tips是make会下载protobuf源码并编译,比较耗时。可以提前下载并跳过校验步骤。 406 | 407 | 1. 可以提前下载[protobuf-cpp-3.8.0.tar.gz](https://github.com/protocolbuffers/protobuf/releases/download/v3.8.0/protobuf-cpp-3.8.0.tar.gz)到*/absolute_path/env*目录, 408 | 2. `ln -sf /absolute_path/env/protobuf-cpp-3.8.0.tar.gz $TRT_SOURCE/build/third_party.protobuf/src`, 409 | 3. 编辑*$TRT_SOURCE/build/third_party.protobuf/src/third_party.protobuf-stamp/download-third_party.protobuf.cmake*文件,在82行加入`return()`。 410 | 411 | 然后将编译出来的动态库替换原tensorrt的库文件。 412 | 413 | ```bash 414 | cd $TRT_RELEASE/lib 415 | ln -sf $TRT_SOURCE/build/libnvinfer_plugin.so.7.0.0.1 libnvinfer_plugin.so.7.0.0 416 | ln -sf $TRT_SOURCE/build/libnvonnxparser.so.7.0.0 libnvonnxparser.so.7.0.0 417 | ``` 418 | 419 | 到这里我们就可以做到在python调用tensorrt库时,使用修改后的tensorrt源码。 420 | 421 | 接下来是修改*$TRT_SOURCE/parsers/onnx/builtin_op_importers.cpp*文件,每一项`DEFINE_BUILTIN_OP_IMPORTER`函数是解析onnx文件算子到tensorrt的映射。搜索topk,修改这个函数里面的 422 | 423 | ```c++ 424 | if (ctx->getOpsetVersion() >= 10) 425 | ``` 426 | 427 | 为 428 | 429 | ```c++ 430 | if (ctx->getOpsetVersion() > 10) 431 | ``` 432 | 433 | 目的是让tensorrt在转换过程中即使发现onnx文件是10版本,也用9版本的方法来解析文件的topk函数,然后到*$TRT_SOURCE/build*文件夹执行`make -j2`后即可。 434 | 435 | #### 重新转换 436 | 437 | 重新转换onnx和tensorrt,还会报topk异常,需要修改maskrcnn-benchmark中*configs/e2e_faster_rcnn_R_50_C4_1x.yaml*文件,将`PRE_NMS_TOP_N_TEST`的值从6000改为1000后解决。 438 | 439 | ### 异常解析之NonZero 440 | 441 | 重新编译后新的报错为 442 | 443 | > ERROR: Failed to parse the ONNX file. 444 | > In node 669 (parseGraph): UNSUPPORTED_NODE: No importer registered for op: NonZero 445 | 446 | 说明在onnx模型文件中存在NonZero算子。此算子的主要功能是提取标量中非零值的索引,它的返回值的长度是可变的。此算子与tensorrt这种预分配固定空间的框架不符,所以在tensorrt中没有相应的转换。我们要找到*maskrcnn_benchmark*项目中哪里用到了NonZero算子,并想办法在onnx模型文件中去掉这个算子。 447 | 448 | 重新转换onnx,在日志中从前向后搜索NonZero,第一处出现的位置日志为 449 | 450 | > %947 : Tensor = onnx::NonZero(%946), scope: \_\_module.rpn/\_\_module.rpn.box_selector_test 451 | > %948 : Tensor = onnx::Transpose\[perm=[1, 0]](%947), scope: \_\_module.rpn/\_\_module.rpn.box_selector_test 452 | > %949 : Tensor = onnx::Squeeze\[axes=[1]](%948), scope: \_\_module.rpn/\_\_module.rpn.box_selector_test 453 | > %950 : Long(1) = onnx::Cast\[to=7](%949), scope: \_\_module.rpn/\_\_module.rpn.box_selector_test # /maskrcnn-benchmark/maskrcnn_benchmark/modeling/rpn/inference.py:98:0 454 | 455 | 表明是在*maskrcnn_benchmark/modeling/rpn/inference.py*文件中第98行使用的,找到这一行发现是个`torch.arange`操作。解决办法修改*symbolic_opset10.py*文件,加入arange算子 456 | 457 | ```python 458 | def arange(g, *args): 459 | from torch.onnx.symbolic_opset11 import arange as arange11 460 | return arange11(g, *args) 461 | ``` 462 | 463 | 另外此函数有个`remove_small_boxes`操作,这里会去除过小的框。在转换时可以直接注释掉,或者 464 | 465 | ```python 466 | ... 467 | if not torchvision._is_tracing(): 468 | boxlist = remove_small_boxes(boxlist, self.min_size) 469 | ... 470 | ``` 471 | 472 | 第三处可以看到是在*maskrcnn_benchmark/modeling/roi_heads/box_head/inference.py*文件中,filter_results函数过滤阈值低于`self.score_thresh`然后进行nms操作。由于nms算子在tensorrt中也不存在,则此处可以在后面与nms自定义层一同处理。 473 | 474 | ### 自定义算子NMS 475 | 476 | 重新执行`python tools/export_onnx.py && python tools/convert_model.py`后,出现报错如下 477 | 478 | > [TensorRT] VERBOSE: /TensorRT/parsers/onnx/ModelImporter.cpp:129: [Slice] inputs: [986 -> (1)], [990 -> (1)], [991 -> (1)], [992 -> (1)], 479 | > ERROR: Failed to parse the ONNX file. 480 | > In node 715 (importSlice): UNSUPPORTED_NODE: Assertion failed: axes.valuesKnown() 481 | 482 | 分析日志找到是在*maskrcnn_benchmark/modeling/rpn/inference.py*文件调用`boxlist_nms`函数时出现的异常。`boxlist_nms`函数会返回一个不定长的nms后的结果,而此nms算子在tensorrt中不存在。我们需要在tensorrt源码中加入这个nms自定义层。 483 | 484 | #### 加入自定义torch层 485 | 486 | 类似前面转换onnx时,我们对自定义`_ROIAlign`层加入虚拟onnx算子,这里我们也建立一个自定义层,并加入虚拟onnx算子。由于不进行真实前向和反向操作,这两处都可以模拟输出值,只关注转换需要用到的`symbolic`函数即可。代码如下 487 | 488 | ```python 489 | import torch 490 | from torch.autograd import Function 491 | from torch.autograd.function import once_differentiable 492 | from torch.onnx.symbolic_opset9 import unsqueeze 493 | from torch.onnx.symbolic_helper import parse_args 494 | 495 | class NonMaxSuppression(Function): 496 | @staticmethod 497 | @parse_args('v', 'v', 'f', 'f', 'i') 498 | def symbolic(g, boxes, scores, iouThreshold, scoreThreshold=0.0, keepTopK=-1): 499 | boxes = unsqueeze(g, boxes, 0) 500 | scores = unsqueeze(g, unsqueeze(g, scores, 0), 0) 501 | if keepTopK == -1: 502 | keepTopK = boxes.size(0) 503 | iouThreshold = g.op('Constant', value_t=torch.tensor([iouThreshold], dtype=torch.float)) 504 | scoreThreshold = g.op('Constant', value_t=torch.tensor([scoreThreshold], dtype=torch.float)) 505 | keepTopK = g.op('Constant', value_t=torch.tensor([keepTopK], dtype=torch.int)) 506 | return g.op("NonMaxSuppression", boxes, scores, iouThreshold, scoreThreshold, keepTopK) 507 | 508 | @staticmethod 509 | def forward(g, boxes, scores, iouThreshold, scoreThreshold=0.0, keepTopK=-1): 510 | if keepTopK == -1: 511 | keepTopK = boxes.size(0) 512 | return torch.ones(keepTopK, device=boxes.device, dtype=torch.long) 513 | 514 | @staticmethod 515 | @once_differentiable 516 | def backward(ctx, grad_output): 517 | pass 518 | ``` 519 | 520 | 保存到*maskrcnn_benchmark/layers/symbolic.py*文件,然后在*maskrcnn_benchmark/layers/\_\_init\_\_.py*文件加入 521 | 522 | ```python 523 | from .symbolic import NonMaxSuppression 524 | ``` 525 | 526 | 在`__all__`变量中加入`"NonMaxSuppression"`。由于nms返回值不定长,这里面我返回了一个定长数组,用`keepTopK`指定。如果nms后的长度小于这个值,返回索引用-1来补齐,使用索引取值时就会取到概率值最低的那个框。 527 | 528 | #### 修改torch调用 529 | 530 | 在*maskrcnn_benchmark/modeling/rpn/inference.py*文件中加入对自定义层`NonMaxSuppression`的引用: 531 | 532 | ```python 533 | from maskrcnn_benchmark.layers import NonMaxSuppression 534 | ``` 535 | 536 | 在`forward_for_single_feature_map`函数内,修改for循环内代码 537 | 538 | ```python 539 | ... 540 | if torchvision._is_tracing(): 541 | keep = NonMaxSuppression.apply(boxlist.bbox, boxlist.get_field("objectness"), self.nms_thresh, 0, self.post_nms_top_n) 542 | boxlist = boxlist[keep] 543 | else: 544 | boxlist = remove_small_boxes(boxlist, self.min_size) 545 | boxlist = boxlist_nms( 546 | boxlist, 547 | self.nms_thresh, 548 | max_proposals=self.post_nms_top_n, 549 | score_field="objectness", 550 | ) 551 | result.append(boxlist) 552 | ... 553 | ``` 554 | 555 | 在*maskrcnn_benchmark/modeling/roi_heads/box_head/inference.py*文件中加入对自定义层`NonMaxSuppression`的引用: 556 | 557 | ```python 558 | import torchvision 559 | from maskrcnn_benchmark.layers import NonMaxSuppression 560 | ``` 561 | 562 | 在`filter_results`函数`result = []`后加入如下代码,由于nms使用-1补齐,这里加入了topk避免输出个数过多。 563 | 564 | ```python 565 | ... 566 | if torchvision._is_tracing(): 567 | scores = torch.split(scores, 1, 1) 568 | for j in range(1, num_classes): 569 | boxes_j = boxes[:, j * 4 : (j + 1) * 4] 570 | scores_j = scores[j].flatten() 571 | idx = NonMaxSuppression.apply(boxes_j, scores_j, self.nms, self.score_thresh, self.detections_per_img) 572 | boxlist_for_class = BoxList(boxes_j[idx, :], boxlist.size, mode="xyxy") 573 | boxlist_for_class.add_field("scores", scores_j[idx]) 574 | result.append(boxlist_for_class) 575 | result = cat_boxlist(result) 576 | objectness = result.get_field("scores") 577 | post_nms_top_n = min(self.detections_per_img, len(objectness)) 578 | _, inds_sorted = torch.topk(objectness, post_nms_top_n, dim=0, sorted=True) 579 | return result[inds_sorted] 580 | ... 581 | ``` 582 | 583 | #### 修改TensorRT源码 584 | 585 | 重新转换onnx后,再转TensorRT时会报找不到刚才自定义的NonMaxSuppression算子 586 | 587 | > ERROR: Failed to parse the ONNX file. 588 | > In node 710 (parseGraph): UNSUPPORTED_NODE: No importer registered for op: NonMaxSuppression 589 | 590 | 此时需要进入`$TRT_SOURCE`文件夹,加入NonMaxSuppression自定义算子的真实实现。参考[项目](https://github.com/TrojanXu/onnxparser-trt-plugin-sample) 591 | 592 | 第一步,修改*parsers/onnx/builtin_op_importers.cpp*文件,加入转换函数,使得onnx的`NonMaxSuppression`算子能够和tensorrt的自定义算子找到对应关系。 593 | 594 | ```c++ 595 | DEFINE_BUILTIN_OP_IMPORTER(NonMaxSuppression) 596 | { 597 | std::vector tensors; 598 | tensors.push_back(&convertToTensor(inputs.at(0), ctx)); 599 | tensors.push_back(&convertToTensor(inputs.at(1), ctx)); 600 | // input[0].shape = [num_boxes, 4] 601 | // input[1].shape = [num_boxes] 602 | 603 | LOG_VERBOSE("call nms plugin: "); 604 | const std::string pluginName = "NonMaxSuppression_TRT"; 605 | const std::string pluginVersion = "1"; 606 | 607 | std::vector f; 608 | bool shareLocation = true; 609 | int backgroundLabelId = -1; 610 | int numClasses = 1; 611 | int topK = tensors[1]->getDimensions().d[2]; 612 | float iouThreshold = static_cast(inputs.at(2).weights().values)[0]; 613 | float scoreThreshold = (node.input().size() > 3) ? static_cast(inputs.at(3).weights().values)[0] : 0.; 614 | int keepTopK = (node.input().size() > 4) ? static_cast(inputs.at(4).weights().values)[0] : tensors[1]->getDimensions().d[2]; 615 | std::cout << "iouThreshold: " << iouThreshold << ", scoreThreshold: " << scoreThreshold << ", keepTopK: " << keepTopK <getPluginCreator(pluginName.c_str(), pluginVersion.c_str()); 630 | 631 | ASSERT(pluginCreator != nullptr, ErrorCode::kINVALID_VALUE); 632 | 633 | nvinfer1::PluginFieldCollection fc; 634 | fc.nbFields = f.size(); 635 | fc.fields = f.data(); 636 | 637 | auto plugin = pluginCreator->createPlugin(node.name().c_str(), &fc); 638 | 639 | ASSERT(plugin != nullptr && "NonMaxSuppression plugin was not found in the plugin registry!", 640 | ErrorCode::kUNSUPPORTED_NODE); 641 | 642 | auto layer = ctx->network()->addPluginV2(&tensors[0], int(tensors.size()), *plugin); 643 | nvinfer1::ITensor* indices = layer->getOutput(0); 644 | 645 | RETURN_FIRST_OUTPUT(layer); 646 | } 647 | ``` 648 | 649 | 注意此处是建立网络时运行的代码,实际做infer的时候不会使用此处代码,所以我们不能获取到那些**标量**的值,但能够获取**常量**的值。代码的一些简单说明: 650 | 651 | - 首行的`NonMaxSuppression`对应onnx算子名称, 652 | - 函数先把前两个输入,整合成为标量数组,注意此处的输入仅仅包含变量的属性信息,获取不到权重。 653 | - 定义了tensorrt中对应算子的名称,`NonMaxSuppression_TRT`,此处后面用到。 654 | - 把其他需要的参数传入到网络,因为前面转onnx时,这些参数都是constant格式,所以此处可以取到他们的值。 655 | - 后面是获取自定义算子以及传参到网络和获取网络返回结果。 656 | 657 | 第二步,加入自定义的非极大值抑制层。在*plugin*文件夹我们看到已经存在了一个*batchedNMSPlugin*文件夹,因为输出与我们定义的后端-1补齐的索引不同,我们不能直接使用,但绝大部分可以复用。拷贝*batchedNMSPlugin*文件夹到新的*nonMaxSuppressionPlugin*文件夹,我们再做一些修改。 658 | 659 | 编辑*plugin/CMakeLists.txt*文件,在`PLUGIN_LISTS`加入我们新建的文件夹名称,nonMaxSuppressionPlugin。 660 | 661 | 参考官方文档见[这里](https://docs.nvidia.com/deeplearning/tensorrt/developer-guide/index.html#add_custom_layer),新增的代码见这里。主要修改点如下: 662 | 663 | - 遵循文档内容,使用`IPluginV2DynamicExt`代替了原来使用的`IPluginV2Ext`父类,修改各个成员函数返回值,如输入输出标量的个数、维度以及类型。 664 | - 返回值改为索引值,长度为固定的`keepTopK`个,不够长时使用-1补齐 665 | 666 | 到*build*文件夹执行`make -j$(nproc)`后生成动态链接库。没有报错后在进入*maskrcnn-benchmark*项目,重新转换tensorrt,此时会发现找不到非极大值抑制的异常消失,取而代之的是找不到`RoiAlign`自定义层。 667 | 668 | ### 自定义算子RoiAlign(略) 669 | 670 | 此部分报错和上节相同, 671 | 672 | > ERROR: Failed to parse the ONNX file. 673 | > In node 718 (parseGraph): UNSUPPORTED_NODE: No importer registered for op: MaskRcnnROIAlign 674 | 675 | 此处也需要在tensorrt中加入自定义层和转换关系,方法逻辑与上节大致相同,不同的是此自定义层需要自行编写cuda核函数,进行并行加速。核函数可以在*maskrcnn-benchmark*项目中找到,稍加修改即可。各位可以尝试自行实现,也可以直接使用工程内我实现的方法。 676 | 677 | 同样在*build*目录`make -j$(nproc)`后可以生成包含RoiAlign算子的动态链接库。在*maskrcnn-benchmark*项目中执行`python tools/convert_model.py`,此时如无报警,需要花费约10分钟至半小时转换,生成最终的tensorrt框架下的模型文件。 678 | 679 | ## 运行tensorrt模型 680 | 681 | ### 运行脚本 682 | 683 | 这里主要考虑保证tensorrt模型与pytorch模型的输入一致,即图像的预处理问题。在maskrcnn-benchmark项目中,图像的预处理为以下步骤: 684 | 685 | 1. 使用opencv读取图像,此时维度是HWC,bgr模式,像素值[0, 255] 686 | 2. 转为pil格式图像, 687 | 3. resize 688 | 4. 转为tensor,并且像素值[0.0, 1.0] 689 | 5. 像素值缩放到[0, 255] 690 | 6. bgr通道减去均值 691 | 692 | 不同项目中预处理不一定相同,但一定要保证模型的输入是一致。所以我们有如下测试脚本。 693 | 694 | ```python 695 | import os 696 | import torch 697 | import tensorrt as trt 698 | from PIL import Image 699 | import numpy as np 700 | import common 701 | from tools.convert_model import conver_engine 702 | import time 703 | import cv2 704 | import glob 705 | 706 | TRT_LOGGER = trt.Logger(trt.Logger.ERROR) 707 | if __name__ == "__main__": 708 | onnx_file_path = 'models/fast_rcnn.onnx' 709 | engine_file_path = "models/fast_rcnn.trt" 710 | threshold = 0.5 711 | image_name = "demo/ILSVRC2012_val_00050000.JPEG" 712 | if not os.path.exists(engine_file_path): 713 | print("no engine file") 714 | # conver_engine(onnx_file_path, engine_file_path) 715 | print(f"Reading engine from file {engine_file_path}") 716 | preprocess_time = 0 717 | process_time = 0 718 | with open(engine_file_path, "rb") as f, trt.Runtime(TRT_LOGGER) as runtime: 719 | with runtime.deserialize_cuda_engine(f.read()) as engine, engine.create_execution_context() as context: 720 | inputs, outputs, bindings, stream = common.allocate_buffers(engine) 721 | image = cv2.imread(image_name) 722 | a = time.time() 723 | image_height, image_width = image.shape[:2] 724 | # image = cv2.resize(image, (768, 768)).transpose((2, 0, 1)) 725 | image = np.array(cv2.resize(image, (768, 768)), dtype=np.float) 726 | image -= np.array([102.9801, 115.9465, 122.7717]) 727 | image = np.transpose(image, (2, 0, 1)).ravel() 728 | # image_batch = np.stack([image], 0).ravel() 729 | np.copyto(inputs[0].host, image) 730 | preprocess_time += time.time() - a 731 | a = time.time() 732 | trt_outputs = common.do_inference_v2(context, bindings=bindings, inputs=inputs, outputs=outputs, stream=stream) 733 | process_time += time.time() - a 734 | x = trt_outputs[0].reshape((100, 5)) 735 | # imshow 736 | image = cv2.imread(image_name) 737 | indices = x[:, -1] > threshold 738 | polygons = x[indices, :-1] 739 | scores = x[indices, -1] 740 | polygons[:, ::2] *= 1. * image.shape[1] / 768 741 | polygons[:, 1::2] *= 1. * image.shape[0] / 768 742 | 743 | for polygon, score in zip(polygons, scores): 744 | print(polygon, score) 745 | cv2.rectangle(image, (int(polygon[0]), int(polygon[1])), (int(polygon[2]), int(polygon[3])), color=(0, 255, 0), thickness=2) 746 | cv2.putText(image, str("%.3f" % score), (int(polygon[0]), int(polygon[1])), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1, False) 747 | cv2.imwrite("tensorrt_demo.jpg", image) 748 | 749 | print("preprocess time: ", preprocess_time, ", inference time: ", process_time) 750 | ``` 751 | 752 | 保存为*demo/tensorrt_demo.py*,执行`python demo/tensorrt_demo.py`即可运行脚本。 753 | 754 | ### 异常解析 755 | 756 | 但此时我们得到的结果是空。首先怀疑是自定义层出现的问题,第一个使用到的自定义层是nms,我们可以在tensorrt中打印一下该层的输入。编辑*plugin/nonMaxSuppressionPlugin/nonMaxSuppressionPlugin.cpp*文件,可以在`enqueue`函数中加入测试代码。 757 | 758 | ```c++ 759 | float* a = (float*)malloc(20 * 4 * sizeof(float)); 760 | cudaMemcpy(a, locData, 20 * 4 * sizeof(float), cudaMemcpyDeviceToHost); 761 | for (int i = 0; i < 20; i ++) { 762 | for (int j = 0; j < 4; j ++) { 763 | std::cout << a[i * 4 + j] << ", "; 764 | } 765 | std::cout << std::endl; 766 | } 767 | std::cout << std::endl; 768 | free(a); 769 | ``` 770 | 771 | 看到输入的bbox坐标都为0,一般这时会在maskrcnn-benchmark项目中加入断点,提前返回中间结果来排查问题。这里我们定位到问题是*maskrcnn_benchmark/modeling/box_coder.py*文件85行以后并没有赋值成功。 772 | 773 | ```python 774 | ... 775 | # pred_boxes = torch.zeros_like(rel_codes) 776 | # # x1 777 | # pred_boxes[:, 0::4] = pred_ctr_x - 0.5 * pred_w 778 | # # y1 779 | # pred_boxes[:, 1::4] = pred_ctr_y - 0.5 * pred_h 780 | # # x2 (note: "- 1" is correct; don't be fooled by the asymmetry) 781 | # pred_boxes[:, 2::4] = pred_ctr_x + 0.5 * pred_w - 1 782 | # # y2 (note: "- 1" is correct; don't be fooled by the asymmetry) 783 | # pred_boxes[:, 3::4] = pred_ctr_y + 0.5 * pred_h - 1 784 | 785 | const_0_5 = torch.tensor(0.5, dtype=pred_ctr_x.dtype) 786 | pred_boxes1 = pred_ctr_x - const_0_5 * pred_w 787 | pred_boxes2 = pred_ctr_y - const_0_5 * pred_h 788 | pred_boxes3 = pred_ctr_x + const_0_5 * pred_w 789 | pred_boxes4 = pred_ctr_y + const_0_5 * pred_h 790 | pred_boxes = torch.stack((pred_boxes1, pred_boxes2, pred_boxes3, pred_boxes4), dim=2).flatten(1) 791 | ... 792 | ``` 793 | 794 | 修改后pytorch->onnx成功,onnx->tensorrt时会出现arange参数是浮点数的异常,修改*maskrcnn_benchmark/modeling/rpn/anchor_generator.py*文件`grid_anchors`函数中,`torch.arange`的参数为`dtype=torch.int64`。 795 | 796 | 重新转换后,nms的输入值非零,但仍与pytorch的不同。*maskrcnn_benchmark/modeling/rpn/inference.py*文件中`boxlist.clip_to_image`函数未起作用导致。于是此for循环需要进行如下改写。 797 | 798 | ```python 799 | ... 800 | for proposal, score, im_shape in zip(proposals, objectness, image_shapes): 801 | if torchvision._is_tracing(): 802 | proposal = torch.stack(( 803 | proposal[:, 0].clamp(min=0, max=im_shape[0] - 1), 804 | proposal[:, 1].clamp(min=0, max=im_shape[1] - 1), 805 | proposal[:, 2].clamp(min=0, max=im_shape[0] - 1), 806 | proposal[:, 3].clamp(min=0, max=im_shape[1] - 1), 807 | ), axis=1) 808 | boxlist = BoxList(proposal, im_shape, mode="xyxy") 809 | boxlist.add_field("objectness", score) 810 | keep = NonMaxSuppression.apply(boxlist.bbox, boxlist.get_field("objectness"), self.nms_thresh, 0, self.post_nms_top_n) 811 | boxlist = boxlist[keep] 812 | else: 813 | boxlist = BoxList(proposal, im_shape, mode="xyxy") 814 | boxlist.add_field("objectness", score) 815 | boxlist = boxlist.clip_to_image(remove_empty=False) 816 | boxlist = remove_small_boxes(boxlist, self.min_size) 817 | boxlist = boxlist_nms( 818 | boxlist, 819 | self.nms_thresh, 820 | max_proposals=self.post_nms_top_n, 821 | score_field="objectness", 822 | ) 823 | result.append(boxlist) 824 | ... 825 | ``` 826 | 827 | 至此结果与pytorch一致。 828 | 829 | 细心的读者可能会发现tensorrt的计算时间会比pytorch时间更长,原因是在box header计算时,pytorch提取box个数是nms后的个数,一般是几十个框。而在tensorrt中由于nms的补齐,是1000个框。修改*configs/e2e_faster_rcnn_R_50_C4_1x.yaml*文件中`POST_NMS_TOP_N_TEST`的值为100后,重新执行`python tools/export_onnx.py && python tools/convert_model.py && python demo/tensorrt_demo.py`,这样就会得到速度比pytorch更加快速的结果了。至此转换成功。 830 | 831 | 832 | # 总结 833 | 834 | - 转换过程中遇到参数问题、或者接口使用的问题推荐搜索官方文档。 835 | - 专用软件的安装可以参考文档或者github页面的说明。 836 | - 转onnx和tensorrt过程中的异常报错,可以试着在github对应的issue区搜索,别人大概率会遇到过类似的情况,会有对应的解决办法。 837 | - 一些编译错误、语法问题或者常用软件的安装可以使用搜索引擎比如谷歌百度。 838 | 839 | 本文也是只针对pytorch->onnx->tensorrt这一种流程做了简单介绍,其他方法也需要继续尝试,比如TensorRT官方出了一个pytorch->tensorrt的版本,也欢迎各位同学勇于尝试新的项目,这样也能加快版本的迭代和技术的进步。 840 | -------------------------------------------------------------------------------- /plugin/maskrcnnRoIAlignPlugin/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | file(GLOB SRCS *.cpp) 17 | set(PLUGIN_SOURCES ${PLUGIN_SOURCES} ${SRCS}) 18 | set(PLUGIN_SOURCES ${PLUGIN_SOURCES} PARENT_SCOPE) 19 | file(GLOB CU_SRCS *.cu) 20 | set(PLUGIN_CU_SOURCES ${PLUGIN_CU_SOURCES} ${CU_SRCS}) 21 | set(PLUGIN_CU_SOURCES ${PLUGIN_CU_SOURCES} PARENT_SCOPE) 22 | 23 | 24 | -------------------------------------------------------------------------------- /plugin/maskrcnnRoIAlignPlugin/README.md: -------------------------------------------------------------------------------- 1 | # batchedNMSPlugin 2 | 3 | **Table Of Contents** 4 | - [Description](#description) 5 | * [Structure](#structure) 6 | - [Parameters](#parameters) 7 | - [Algorithms](#algorithms) 8 | - [Additional resources](#additional-resources) 9 | - [License](#license) 10 | - [Changelog](#changelog) 11 | - [Known issues](#known-issues) 12 | 13 | ## Description 14 | 15 | The `batchedNMSPlugin` implements a non-maximum suppression (NMS) step over boxes for object detection networks. 16 | 17 | Non-maximum suppression is typically the universal step in object detection inference. This plugin is used after you’ve processed the bounding box prediction and object classification to get the final bounding boxes for objects. 18 | 19 | With this plugin, you can incorporate the non-maximum suppression step during TensorRT inference. During inference, the neural network generates a fixed number of bounding boxes with box coordinates, identified class and confidence levels. Not all bounding boxes, but the most representative ones, have to be drawn on the original image. 20 | 21 | Non-maximum suppression is the way to eliminate the boxes which have low confidence or do not have object in and keep the most representative ones. For example, the objects within an image might be covered by many boxes with different levels of confidence. The goal of the non-maximum suppression step is to find the most confident box for the object and remove all the less confident ones. 22 | 23 | This plugin accelerates this non maximum suppression step during TensorRT inference on GPU. 24 | 25 | ### Structure 26 | 27 | The `batchedNMSPlugin` takes two inputs, boxes input and scores input. 28 | 29 | **Boxes input** 30 | The boxes input are of shape `[batch_size, number_boxes, number_classes, number_box_parameters]`. The box location usually consists of four parameters such as `[x_min, y_min, x_max, y_max]`. For example, if your model outputs `8732` bounding boxes given one image, there are `100` candidate classes, the shape of boxes input will be `[8732, 100, 4]`. 31 | 32 | **Scores input** 33 | The scores input are of shape `[batch_size, number_boxes, number_classes]`. Each box has an array of probability for each candidate class. 34 | 35 | The boxes input and scores input generates the following four outputs: 36 | 37 | - `num_detections` 38 | The `num_detections` input are of shape `[batch_size, 1]`. The last dimension of size 1 is an INT32 scalar indicating the number of valid detections per batch item. It can be less than `keepTopK`. Only the top `num_detections[i]` entries in `nmsed_boxes[i]`, `nmsed_scores[i]` and `nmsed_classes[i]` are valid. 39 | 40 | - `nmsed_boxes` 41 | A `[batch_size, keepTopK, 4]` float32 tensor containing the coordinates of non-max suppressed boxes. 42 | 43 | - `nmsed_scores` 44 | A `[batch_size, keepTopK]` float32 tensor containing the scores for the boxes. 45 | 46 | - `nmsed_classes` 47 | A `[batch_size, keepTopK]` float32 tensor containing the classes for the boxes. 48 | 49 | 50 | ## Parameters 51 | 52 | The `batchedNMSPlugin` has plugin creator class `BatchedNMSPluginCreator` and plugin class `BatchedNMSPlugin`. 53 | 54 | The `batchedNMSPlugin` is created using `BatchedNMSPluginCreator` with `NMSParameters` typed parameters. The `NMSParameters` data structure is listed as follows and is defined in the [NvInferPlugin.h header file](https://docs.nvidia.com/deeplearning/sdk/tensorrt-api/c_api/_nv_infer_plugin_8h_source.html). 55 | 56 | | Type | Parameter | Description 57 | |----------|--------------------------|-------------------------------------------------------- 58 | |`bool` |`shareLocation` |If set to `true`, the boxes input are shared across all classes. If set to `false`, the boxes input should account for per-class box data. 59 | |`int` |`backgroundLabelId` |The label ID for the background class. If there is no background class, set it to `-1`. 60 | |`int` |`numClasses` |The number of classes in the network. 61 | |`int` |`topK` |The number of bounding boxes to be fed into the NMS step. 62 | |`int` |`keepTopK` |The number of total bounding boxes to be kept per-image after the NMS step. Should be less than or equal to the `topK` value. 63 | |`float` |`scoreThreshold` |The scalar threshold for score (low scoring boxes are removed). 64 | |`float` |`iouThreshold` |The scalar threshold for IOU (new boxes that have high IOU overlap with previously selected boxes are removed). 65 | |`bool` |`isNormalized` |Set to `false` if the box coordinates are not normalized, meaning they are not in the range `[0,1]`. Defaults to `true`. 66 | 67 | 68 | ## Algorithms 69 | 70 | The NMS algorithm used in this particular plugin first sorts the bounding boxes indices by the score for each class, then sorts the bounding boxes by the updated scores, and finally collects the desired number of bounding boxes with the highest scores. 71 | 72 | It is mainly accelerated using the `nmsInference` kernel defined in the `batchedNMSInference.cu` file. 73 | 74 | Specifically, the NMS algorithm: 75 | - Sorts the bounding box indices by the score for each class. Before sorting, the bounding boxes with a score less than `scoreThreshold` are discarded by setting their indices to `-1` and their scores to `0`. This is using the `sortScoresPerClass` kernel defined in the `sortScoresPerClass.cu` file. 76 | 77 | - Finds the most confident box for the object and removes all the less confident ones using the iterative non-maximum suppression step step for each class. Starting from the bounding box with the highest score in each class, the bounding boxes that has overlap higher than `iouThreshold` is suppressed by setting their indices to `-1` and their scores to `0`. Then all the less confident bounding boxes were suppressed for each class. This is using the `allClassNMS` kernel defined in the `allClassNMS.cu` file. 78 | 79 | - Sorts the bounding boxes per image using the updated scores. At this time, all the classes were mixed before sort. Discarded and suppressed bounding boxes will go to the end of the sorted array since their score is `0`. This is using the `sortScoresPerImage` kernel defined in the `sortScoresPerImage.cu` file. 80 | 81 | - Collects the desired number, `keepTopK`, of bounding box indices with the highest scores from the top of the sorted array, their bounding box coordinates, and their object classification information. This is using the `gatherNMSOutputs` kernel defined in the `gatherNMSOutputs.cu` file. 82 | 83 | 84 | ## Additional resources 85 | 86 | The following resources provide a deeper understanding of the `batchedNMSPlugin` plugin: 87 | 88 | **Networks** 89 | - [SSD: Single Shot MultiBox Detector](https://arxiv.org/abs/1512.02325) 90 | - [Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks](https://arxiv.org/abs/1506.01497) 91 | - [Mask R-CNN](https://arxiv.org/abs/1703.06870) 92 | 93 | 94 | **Documentation** 95 | - [NMSParameter detailed descriptions](https://docs.nvidia.com/deeplearning/sdk/tensorrt-api/c_api/structnvinfer1_1_1plugin_1_1_n_m_s_parameters.html) 96 | - [NMS algorithm](https://www.coursera.org/lecture/convolutional-neural-networks/non-max-suppression-dvrjH) 97 | 98 | 99 | ## License 100 | 101 | For terms and conditions for use, reproduction, and distribution, see the [TensorRT Software License Agreement](https://docs.nvidia.com/deeplearning/sdk/tensorrt-sla/index.html) 102 | documentation. 103 | 104 | 105 | ## Changelog 106 | 107 | May 2019 108 | This is the first release of this `README.md` file. 109 | 110 | 111 | ## Known issues 112 | 113 | - When running `cub::DeviceSegmentedRadixSort::SortPairsDescending` with `cuda-memcheck --tool racecheck`, it will not work correctly. 114 | - BatchedNMS plugin cannot handle greater than 4096 rectangles in the input. 115 | -------------------------------------------------------------------------------- /plugin/maskrcnnRoIAlignPlugin/maskrcnnRoIAlignPlugin.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "maskrcnnRoIAlignPlugin.h" 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | using namespace nvinfer1; 25 | using nvinfer1::plugin::MaskrcnnRoIAlignPlugin; 26 | using nvinfer1::plugin::MaskrcnnRoIAlignPluginCreator; 27 | using nvinfer1::plugin::RoIAlignParameters; 28 | 29 | namespace 30 | { 31 | constexpr const char* ROI_ALIGN_PLUGIN_VERSION{"1"}; 32 | constexpr const char* ROI_ALIGN_PLUGIN_NAME{"MaskrcnnRoIAlign_TRT"}; 33 | } // namespace 34 | REGISTER_TENSORRT_PLUGIN(MaskrcnnRoIAlignPluginCreator); 35 | 36 | PluginFieldCollection MaskrcnnRoIAlignPluginCreator::mFC{}; 37 | std::vector MaskrcnnRoIAlignPluginCreator::mPluginAttributes; 38 | 39 | MaskrcnnRoIAlignPlugin::MaskrcnnRoIAlignPlugin(RoIAlignParameters params) 40 | : param(params) 41 | { 42 | } 43 | 44 | MaskrcnnRoIAlignPlugin::MaskrcnnRoIAlignPlugin(const void* data, size_t length) 45 | { 46 | const char *d = reinterpret_cast(data), *a = d; 47 | param = read(d); 48 | numRoIs = read(d); 49 | ASSERT(d == a + length); 50 | } 51 | 52 | int MaskrcnnRoIAlignPlugin::getNbOutputs() const 53 | { 54 | return 1; 55 | } 56 | 57 | int MaskrcnnRoIAlignPlugin::initialize() 58 | { 59 | return STATUS_SUCCESS; 60 | } 61 | 62 | void MaskrcnnRoIAlignPlugin::terminate() {} 63 | 64 | DimsExprs MaskrcnnRoIAlignPlugin::getOutputDimensions(int outputIndex, const nvinfer1::DimsExprs* inputs, int nbInputs, nvinfer1::IExprBuilder& exprBuilder) 65 | { 66 | ASSERT(nbInputs == 2); 67 | ASSERT(outputIndex >= 0 && outputIndex < this->getNbOutputs()); 68 | ASSERT(inputs[0].nbDims == 4); 69 | ASSERT(inputs[1].nbDims == 2); 70 | 71 | // num_detections 72 | DimsExprs ret; 73 | ret.nbDims = 4; 74 | ret.d[0] = inputs[1].d[0]; 75 | ret.d[1] = inputs[0].d[1]; 76 | ret.d[2] = exprBuilder.constant(param.pooled_height); 77 | ret.d[3] = exprBuilder.constant(param.pooled_width); 78 | return ret; 79 | } 80 | 81 | size_t MaskrcnnRoIAlignPlugin::getWorkspaceSize(const nvinfer1::PluginTensorDesc* inputs, int nbInputs, const nvinfer1::PluginTensorDesc* outputs, int nbOutputs) const 82 | { 83 | return 0; 84 | } 85 | 86 | int MaskrcnnRoIAlignPlugin::enqueue(const nvinfer1::PluginTensorDesc* inputDesc, const nvinfer1::PluginTensorDesc* outputDesc, 87 | const void* const* inputs, void* const* outputs, 88 | void* workspace, 89 | cudaStream_t stream) 90 | { 91 | const float* const feature = (const float* const)(inputs[0]); 92 | const float* const rois = (const float* const)(inputs[1]); 93 | 94 | float* output = (float*)(outputs[0]); 95 | pluginStatus_t status = RoIAlign( 96 | stream, 97 | inputDesc[0].dims.d[0], 98 | inputDesc[0].dims.d[1], 99 | param.pooled_height, 100 | param.pooled_width, 101 | param.sampling_ratio, 102 | feature, 103 | inputDesc[0].dims.d[2], inputDesc[0].dims.d[3], 104 | param.spatial_scale, 105 | rois, inputDesc[1].dims.d[0], 106 | output 107 | ); 108 | // float* a = (float*)malloc(200 * sizeof(float)); 109 | // cudaMemcpy(a, output, 200 * sizeof(float), cudaMemcpyDeviceToHost); 110 | // for (int b = 0; b < 100; b ++) { 111 | // std::cout << ", " << a[b]; 112 | // } 113 | // std::cout << std::endl; 114 | // free(a); 115 | // cudaStreamSynchronize(stream); 116 | // std::cout << "outputDesc[0].dims.d[0]: " << outputDesc[0].dims.d[0] << ", outputDesc[0].dims.d[1]: " << outputDesc[0].dims.d[1] << ", outputDesc[0].dims.d[2]: " << outputDesc[0].dims.d[2] << ", outputDesc[0].dims.d[3]: " << outputDesc[0].dims.d[3] << std::endl; 117 | // float* a = (float*)malloc(800 * 112 * 49 * sizeof(float)); 118 | // cudaMemcpy(a, output, 800 * 112 * 49 * sizeof(float), cudaMemcpyDeviceToHost); 119 | // for (int i = 0; i < 800; i += 400) { 120 | // for (int b = 0; b < 1; b ++) { 121 | // for (int j = 0; j < 1; j ++) { 122 | // for (int k = 0; k < 5; k ++) { 123 | // std::cout << a[i * 112 * 7 * 7 + b * 7 * 7 + j * 7 + k] << ", "; 124 | // } 125 | // } 126 | // std::cout << std::endl; 127 | // } 128 | // } 129 | // std::cout << std::endl; 130 | // free(a); 131 | 132 | ASSERT(status == STATUS_SUCCESS); 133 | return 0; 134 | } 135 | 136 | size_t MaskrcnnRoIAlignPlugin::getSerializationSize() const 137 | { 138 | // RoIAlignParameters, numRoIs 139 | return sizeof(RoIAlignParameters) + sizeof(int); 140 | } 141 | 142 | void MaskrcnnRoIAlignPlugin::serialize(void* buffer) const 143 | { 144 | char *d = reinterpret_cast(buffer), *a = d; 145 | write(d, param); 146 | write(d, numRoIs); 147 | ASSERT(d == a + getSerializationSize()); 148 | } 149 | 150 | void MaskrcnnRoIAlignPlugin::configurePlugin(const nvinfer1::DynamicPluginTensorDesc* in, int nbInputs, 151 | const nvinfer1::DynamicPluginTensorDesc* out, int nbOutputs) 152 | { 153 | ASSERT(nbInputs == 2); 154 | ASSERT(nbOutputs == 1); 155 | ASSERT(in[0].desc.dims.nbDims == 4); 156 | ASSERT(in[1].desc.dims.nbDims == 2); 157 | numRoIs = in[1].desc.dims.d[0]; 158 | ASSERT(in[1].desc.dims.d[1] == 5 || in[1].desc.dims.d[1] == -1); 159 | } 160 | 161 | 162 | bool MaskrcnnRoIAlignPlugin::supportsFormatCombination(int pos, const nvinfer1::PluginTensorDesc* inOut, int nbInputs, int nbOutputs) 163 | { 164 | ASSERT(inOut && pos < (nbInputs + nbOutputs)); 165 | return ((inOut[pos].type == nvinfer1::DataType::kFLOAT || inOut[pos].type == nvinfer1::DataType::kHALF) 166 | && inOut[pos].format == nvinfer1::PluginFormat::kLINEAR && inOut[pos].type == inOut[0].type); 167 | } 168 | 169 | const char* MaskrcnnRoIAlignPlugin::getPluginType() const 170 | { 171 | return ROI_ALIGN_PLUGIN_NAME; 172 | } 173 | 174 | const char* MaskrcnnRoIAlignPlugin::getPluginVersion() const 175 | { 176 | return ROI_ALIGN_PLUGIN_VERSION; 177 | } 178 | 179 | void MaskrcnnRoIAlignPlugin::destroy() 180 | { 181 | delete this; 182 | } 183 | 184 | IPluginV2DynamicExt* MaskrcnnRoIAlignPlugin::clone() const 185 | { 186 | auto* plugin = new MaskrcnnRoIAlignPlugin(param); 187 | plugin->numRoIs = numRoIs; 188 | plugin->setPluginNamespace(mNamespace.c_str()); 189 | return plugin; 190 | } 191 | 192 | void MaskrcnnRoIAlignPlugin::setPluginNamespace(const char* pluginNamespace) 193 | { 194 | mPluginNamespace = pluginNamespace; 195 | } 196 | 197 | const char* MaskrcnnRoIAlignPlugin::getPluginNamespace() const 198 | { 199 | return mPluginNamespace; 200 | } 201 | 202 | nvinfer1::DataType MaskrcnnRoIAlignPlugin::getOutputDataType( 203 | int index, const nvinfer1::DataType* inputTypes, int nbInputs) const 204 | { 205 | ASSERT(index >= 0 && index < this->getNbOutputs()); 206 | return nvinfer1::DataType::kFLOAT; 207 | } 208 | 209 | MaskrcnnRoIAlignPluginCreator::MaskrcnnRoIAlignPluginCreator() 210 | : params{} 211 | { 212 | // Plugin field meta data {name, data, type, length} 213 | mPluginAttributes.emplace_back(PluginField("pooled_height", nullptr, PluginFieldType::kINT32, 1)); 214 | mPluginAttributes.emplace_back(PluginField("pooled_width", nullptr, PluginFieldType::kINT32, 1)); 215 | mPluginAttributes.emplace_back(PluginField("sampling_ratio", nullptr, PluginFieldType::kFLOAT32, 1)); 216 | mPluginAttributes.emplace_back(PluginField("spatial_scale", nullptr, PluginFieldType::kFLOAT32, 1)); 217 | 218 | mFC.nbFields = mPluginAttributes.size(); 219 | mFC.fields = mPluginAttributes.data(); 220 | } 221 | 222 | const char* MaskrcnnRoIAlignPluginCreator::getPluginName() const 223 | { 224 | return ROI_ALIGN_PLUGIN_NAME; 225 | } 226 | 227 | const char* MaskrcnnRoIAlignPluginCreator::getPluginVersion() const 228 | { 229 | return ROI_ALIGN_PLUGIN_VERSION; 230 | } 231 | 232 | const PluginFieldCollection* MaskrcnnRoIAlignPluginCreator::getFieldNames() 233 | { 234 | return &mFC; 235 | } 236 | 237 | IPluginV2DynamicExt* MaskrcnnRoIAlignPluginCreator::createPlugin(const char* name, const PluginFieldCollection* fc) 238 | { 239 | const PluginField* fields = fc->fields; 240 | 241 | for (int i = 0; i < fc->nbFields; ++i) { 242 | const char* attrName = fields[i].name; 243 | if (!strcmp(attrName, "pooled_height")) { 244 | ASSERT(fields[i].type == PluginFieldType::kINT32); 245 | params.pooled_height = *(static_cast(fields[i].data)); 246 | } else if (!strcmp(attrName, "pooled_width")) { 247 | ASSERT(fields[i].type == PluginFieldType::kINT32); 248 | params.pooled_width = *(static_cast(fields[i].data)); 249 | } else if (!strcmp(attrName, "sampling_ratio")) { 250 | ASSERT(fields[i].type == PluginFieldType::kFLOAT32); 251 | params.sampling_ratio = *(static_cast(fields[i].data)); 252 | } else if (!strcmp(attrName, "spatial_scale")) { 253 | ASSERT(fields[i].type == PluginFieldType::kFLOAT32); 254 | params.spatial_scale = *(static_cast(fields[i].data)); 255 | // } else if (!strcmp(attrName, "spatial_scales")) { 256 | // ASSERT(fields[i].type == PluginFieldType::kFLOAT32); 257 | // const int size = fields[i].length; 258 | // const float* o = static_cast(fields[i].data); 259 | // for (int j = 0; j < size; j++) 260 | // { 261 | // params.spatial_scales[j] = *o; 262 | // o++; 263 | // } 264 | } 265 | } 266 | 267 | MaskrcnnRoIAlignPlugin* plugin = new MaskrcnnRoIAlignPlugin(params); 268 | plugin->setPluginNamespace(mNamespace.c_str()); 269 | return plugin; 270 | } 271 | 272 | IPluginV2DynamicExt* MaskrcnnRoIAlignPluginCreator::deserializePlugin(const char* name, const void* serialData, size_t serialLength) 273 | { 274 | // This object will be deleted when the network is destroyed, which will 275 | // call NMS::destroy() 276 | MaskrcnnRoIAlignPlugin* plugin = new MaskrcnnRoIAlignPlugin(serialData, serialLength); 277 | plugin->setPluginNamespace(mNamespace.c_str()); 278 | return plugin; 279 | } 280 | -------------------------------------------------------------------------------- /plugin/maskrcnnRoIAlignPlugin/maskrcnnRoIAlignPlugin.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #ifndef TRT_MASKRCNN_ROI_ALIGN_PLUGIN_H 17 | #define TRT_MASKRCNN_ROI_ALIGN_PLUGIN_H 18 | #include "maskrcnnRoIAlignPlugin/roiAlign.h" 19 | #include "kernel.h" 20 | #include "plugin.h" 21 | #include 22 | #include 23 | #include 24 | 25 | typedef unsigned short half_type; 26 | 27 | using namespace nvinfer1::plugin; 28 | namespace nvinfer1 29 | { 30 | namespace plugin 31 | { 32 | 33 | struct RoIAlignParameters 34 | { 35 | int pooled_height; 36 | int pooled_width; 37 | float sampling_ratio; 38 | float spatial_scale; 39 | }; 40 | 41 | class MaskrcnnRoIAlignPlugin: public IPluginV2DynamicExt 42 | { 43 | public: 44 | MaskrcnnRoIAlignPlugin(RoIAlignParameters param); 45 | 46 | MaskrcnnRoIAlignPlugin(const void* data, size_t length); 47 | 48 | ~MaskrcnnRoIAlignPlugin() override = default; 49 | 50 | int getNbOutputs() const override; 51 | 52 | //DynamicExt plugins returns DimsExprs class instead of Dims 53 | // Dims getOutputDimensions(int index, const Dims* inputs, int nbInputDims) override; 54 | DimsExprs getOutputDimensions(int outputIndex, const nvinfer1::DimsExprs* inputs, int nbInputs, nvinfer1::IExprBuilder& exprBuilder) override; 55 | 56 | // DynamicExt plugin supportsFormat update. 57 | bool supportsFormatCombination(int pos, const nvinfer1::PluginTensorDesc* inOut, int nbInputs, int nbOutputs) override; 58 | 59 | int initialize() override; 60 | 61 | void terminate() override; 62 | 63 | // size_t getWorkspaceSize(int maxBatchSize) const override; 64 | size_t getWorkspaceSize(const nvinfer1::PluginTensorDesc* inputs, int nbInputs, const nvinfer1::PluginTensorDesc* outputs, int nbOutputs) const override; 65 | 66 | 67 | // int enqueue( 68 | // int batchSize, const void* const* inputs, void** outputs, void* workspace, cudaStream_t stream) override; 69 | int enqueue(const nvinfer1::PluginTensorDesc* inputDesc, const nvinfer1::PluginTensorDesc* outputDesc, 70 | const void* const* inputs, void* const* outputs, 71 | void* workspace, 72 | cudaStream_t stream) override; 73 | 74 | size_t getSerializationSize() const override; 75 | 76 | void serialize(void* buffer) const override; 77 | 78 | // void configurePlugin(const Dims* inputDims, int nbInputs, const Dims* outputDims, int nbOutputs, 79 | // const DataType* inputTypes, const DataType* outputTypes, const bool* inputIsBroadcast, 80 | // const bool* outputIsBroadcast, PluginFormat floatFormat, int maxBatchSize) override; 81 | void configurePlugin(const nvinfer1::DynamicPluginTensorDesc* in, int nbInputs, 82 | const nvinfer1::DynamicPluginTensorDesc* out, int nbOutputs) override; 83 | 84 | const char* getPluginType() const override; 85 | 86 | const char* getPluginVersion() const override; 87 | 88 | void destroy() override; 89 | 90 | IPluginV2DynamicExt* clone() const override; 91 | 92 | nvinfer1::DataType getOutputDataType(int index, const nvinfer1::DataType* inputType, int nbInputs) const override; 93 | 94 | void setPluginNamespace(const char* libNamespace) override; 95 | 96 | const char* getPluginNamespace() const override; 97 | 98 | private: 99 | RoIAlignParameters param{}; 100 | int numRoIs{}; 101 | std::string mNamespace; 102 | const char* mPluginNamespace; 103 | }; 104 | 105 | class MaskrcnnRoIAlignPluginCreator : public BaseCreator 106 | { 107 | public: 108 | MaskrcnnRoIAlignPluginCreator(); 109 | 110 | ~MaskrcnnRoIAlignPluginCreator() override = default; 111 | 112 | const char* getPluginName() const override; 113 | 114 | const char* getPluginVersion() const override; 115 | 116 | const PluginFieldCollection* getFieldNames() override; 117 | 118 | IPluginV2DynamicExt* createPlugin(const char* name, const PluginFieldCollection* fc) override; 119 | 120 | IPluginV2DynamicExt* deserializePlugin(const char* name, const void* serialData, size_t serialLength) override; 121 | 122 | private: 123 | static PluginFieldCollection mFC; 124 | RoIAlignParameters params; 125 | static std::vector mPluginAttributes; 126 | }; 127 | } // namespace plugin 128 | } // namespace nvinfer1 129 | 130 | #endif // TRT_MASKRCNN_ROI_ALIGN_PLUGIN_H 131 | -------------------------------------------------------------------------------- /plugin/maskrcnnRoIAlignPlugin/roiAlign.cu: -------------------------------------------------------------------------------- 1 | // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. 2 | #include "roiAlign.h" 3 | #include "cmath" 4 | 5 | // TODO make it in a common file 6 | #define CUDA_1D_KERNEL_LOOP(i, n) \ 7 | for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; \ 8 | i += blockDim.x * gridDim.x) 9 | 10 | 11 | template 12 | __device__ T bilinear_interpolate(const T* bottom_data, 13 | const int height, const int width, 14 | T y, T x, 15 | const int index /* index for debug only*/) { 16 | 17 | // deal with cases that inverse elements are out of feature map boundary 18 | if (y < -1.0 || y > height || x < -1.0 || x > width) { 19 | //empty 20 | return 0; 21 | } 22 | 23 | if (y <= 0) y = 0; 24 | if (x <= 0) x = 0; 25 | 26 | int y_low = (int) y; 27 | int x_low = (int) x; 28 | int y_high; 29 | int x_high; 30 | 31 | if (y_low >= height - 1) { 32 | y_high = y_low = height - 1; 33 | y = (T) y_low; 34 | } else { 35 | y_high = y_low + 1; 36 | } 37 | 38 | if (x_low >= width - 1) { 39 | x_high = x_low = width - 1; 40 | x = (T) x_low; 41 | } else { 42 | x_high = x_low + 1; 43 | } 44 | 45 | T ly = y - y_low; 46 | T lx = x - x_low; 47 | T hy = 1. - ly, hx = 1. - lx; 48 | // do bilinear interpolation 49 | T v1 = bottom_data[y_low * width + x_low]; 50 | T v2 = bottom_data[y_low * width + x_high]; 51 | T v3 = bottom_data[y_high * width + x_low]; 52 | T v4 = bottom_data[y_high * width + x_high]; 53 | T w1 = hy * hx, w2 = hy * lx, w3 = ly * hx, w4 = ly * lx; 54 | 55 | T val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4); 56 | 57 | return val; 58 | } 59 | 60 | template 61 | __global__ void RoIAlign_kernel(const int nthreads, 62 | const int rois_per_image, 63 | const int channels, 64 | const int pooled_height, 65 | const int pooled_width, 66 | const int sampling_ratio, 67 | const T* bottom_data, 68 | const int height, const int width, 69 | const T spatial_scale, 70 | const T* bottom_rois, T* top_data) { 71 | CUDA_1D_KERNEL_LOOP(index, nthreads) { 72 | // (n, c, ph, pw) is an element in the pooled output 73 | int pw = index % pooled_width; 74 | int ph = (index / pooled_width) % pooled_height; 75 | int c = (index / pooled_width / pooled_height) % channels; 76 | int n = index / pooled_width / pooled_height / channels; 77 | 78 | const T* offset_bottom_rois = bottom_rois + n * 5; 79 | int roi_batch_ind = offset_bottom_rois[0]; 80 | 81 | // Do not using rounding; this implementation detail is critical 82 | T roi_start_w = offset_bottom_rois[1] * spatial_scale; 83 | T roi_start_h = offset_bottom_rois[2] * spatial_scale; 84 | T roi_end_w = offset_bottom_rois[3] * spatial_scale; 85 | T roi_end_h = offset_bottom_rois[4] * spatial_scale; 86 | // T roi_start_w = round(offset_bottom_rois[1] * spatial_scale); 87 | // T roi_start_h = round(offset_bottom_rois[2] * spatial_scale); 88 | // T roi_end_w = round(offset_bottom_rois[3] * spatial_scale); 89 | // T roi_end_h = round(offset_bottom_rois[4] * spatial_scale); 90 | 91 | // Force malformed ROIs to be 1x1 92 | T roi_width = max(roi_end_w - roi_start_w, (T)1.); 93 | T roi_height = max(roi_end_h - roi_start_h, (T)1.); 94 | T bin_size_h = static_cast(roi_height) / static_cast(pooled_height); 95 | T bin_size_w = static_cast(roi_width) / static_cast(pooled_width); 96 | 97 | const T* offset_bottom_data = bottom_data + (roi_batch_ind * channels + c) * height * width; 98 | 99 | // We use roi_bin_grid to sample the grid and mimic integral 100 | int roi_bin_grid_h = (sampling_ratio > 0) ? sampling_ratio : ceil(roi_height / pooled_height); // e.g., = 2 101 | int roi_bin_grid_w = (sampling_ratio > 0) ? sampling_ratio : ceil(roi_width / pooled_width); 102 | 103 | // We do average (integral) pooling inside a bin 104 | const T count = roi_bin_grid_h * roi_bin_grid_w; // e.g. = 4 105 | 106 | T output_val = 0.; 107 | for (int iy = 0; iy < roi_bin_grid_h; iy ++) // e.g., iy = 0, 1 108 | { 109 | const T y = roi_start_h + ph * bin_size_h + static_cast(iy + .5f) * bin_size_h / static_cast(roi_bin_grid_h); // e.g., 0.5, 1.5 110 | for (int ix = 0; ix < roi_bin_grid_w; ix ++) 111 | { 112 | const T x = roi_start_w + pw * bin_size_w + static_cast(ix + .5f) * bin_size_w / static_cast(roi_bin_grid_w); 113 | 114 | T val = bilinear_interpolate(offset_bottom_data, height, width, y, x, index); 115 | output_val += val; 116 | } 117 | } 118 | output_val /= count; 119 | 120 | top_data[index] = output_val; 121 | } 122 | } 123 | 124 | pluginStatus_t RoIAlign(cudaStream_t stream, 125 | const int batch_size, 126 | const int channels, 127 | const int pooled_height, 128 | const int pooled_width, 129 | const int sampling_ratio, 130 | const float* feature, 131 | const int feature_height, const int feature_width, 132 | const float spatial_scale, 133 | const float* rois, 134 | const int num_rois, 135 | float* output 136 | ) 137 | { 138 | auto output_size = num_rois * pooled_height * pooled_width * channels; 139 | dim3 grid(std::min((long)(output_size - 1) / 1024 + 1, 4096L)); 140 | dim3 block(1024); 141 | RoIAlign_kernel<<>>( 142 | output_size, 143 | num_rois / batch_size, 144 | channels, 145 | pooled_height, 146 | pooled_width, 147 | sampling_ratio, 148 | feature, 149 | feature_height, feature_width, 150 | spatial_scale, 151 | rois, 152 | output); 153 | return STATUS_SUCCESS; 154 | } 155 | -------------------------------------------------------------------------------- /plugin/maskrcnnRoIAlignPlugin/roiAlign.h: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | > File Name: roiAlign.h 3 | > Author: Stewart 4 | > Mail: tanzhiyu@jd.com 5 | > Created Time: Mon 23 Mar 2020 02:19:25 PM CST 6 | ************************************************************************/ 7 | 8 | #ifndef ROI_ALIGN_H 9 | #define ROI_ALIGN_H 10 | 11 | #include 12 | #include "plugin.h" 13 | #include "cuda_runtime_api.h" 14 | #include "kernel.h" 15 | 16 | using namespace std; 17 | 18 | pluginStatus_t RoIAlign(cudaStream_t stream, 19 | const int rois_per_image, 20 | const int channels, 21 | const int pooled_height, 22 | const int pooled_width, 23 | const int sampling_ratio, 24 | const float* feature, 25 | const int feature_height, const int feature_width, 26 | const float spatial_scale, 27 | const float* rois, 28 | const int num_rois, 29 | float* output 30 | ); 31 | 32 | #endif 33 | -------------------------------------------------------------------------------- /plugin/nonMaxSuppressionPlugin/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | file(GLOB SRCS *.cpp) 17 | set(PLUGIN_SOURCES ${PLUGIN_SOURCES} ${SRCS}) 18 | set(PLUGIN_SOURCES ${PLUGIN_SOURCES} PARENT_SCOPE) 19 | file(GLOB CU_SRCS *.cu) 20 | set(PLUGIN_CU_SOURCES ${PLUGIN_CU_SOURCES} ${CU_SRCS}) 21 | set(PLUGIN_CU_SOURCES ${PLUGIN_CU_SOURCES} PARENT_SCOPE) 22 | 23 | 24 | -------------------------------------------------------------------------------- /plugin/nonMaxSuppressionPlugin/README.md: -------------------------------------------------------------------------------- 1 | # batchedNMSPlugin 2 | 3 | **Table Of Contents** 4 | - [Description](#description) 5 | * [Structure](#structure) 6 | - [Parameters](#parameters) 7 | - [Algorithms](#algorithms) 8 | - [Additional resources](#additional-resources) 9 | - [License](#license) 10 | - [Changelog](#changelog) 11 | - [Known issues](#known-issues) 12 | 13 | ## Description 14 | 15 | The `batchedNMSPlugin` implements a non-maximum suppression (NMS) step over boxes for object detection networks. 16 | 17 | Non-maximum suppression is typically the universal step in object detection inference. This plugin is used after you’ve processed the bounding box prediction and object classification to get the final bounding boxes for objects. 18 | 19 | With this plugin, you can incorporate the non-maximum suppression step during TensorRT inference. During inference, the neural network generates a fixed number of bounding boxes with box coordinates, identified class and confidence levels. Not all bounding boxes, but the most representative ones, have to be drawn on the original image. 20 | 21 | Non-maximum suppression is the way to eliminate the boxes which have low confidence or do not have object in and keep the most representative ones. For example, the objects within an image might be covered by many boxes with different levels of confidence. The goal of the non-maximum suppression step is to find the most confident box for the object and remove all the less confident ones. 22 | 23 | This plugin accelerates this non maximum suppression step during TensorRT inference on GPU. 24 | 25 | ### Structure 26 | 27 | The `batchedNMSPlugin` takes two inputs, boxes input and scores input. 28 | 29 | **Boxes input** 30 | The boxes input are of shape `[batch_size, number_boxes, number_classes, number_box_parameters]`. The box location usually consists of four parameters such as `[x_min, y_min, x_max, y_max]`. For example, if your model outputs `8732` bounding boxes given one image, there are `100` candidate classes, the shape of boxes input will be `[8732, 100, 4]`. 31 | 32 | **Scores input** 33 | The scores input are of shape `[batch_size, number_boxes, number_classes]`. Each box has an array of probability for each candidate class. 34 | 35 | The boxes input and scores input generates the following four outputs: 36 | 37 | - `num_detections` 38 | The `num_detections` input are of shape `[batch_size, 1]`. The last dimension of size 1 is an INT32 scalar indicating the number of valid detections per batch item. It can be less than `keepTopK`. Only the top `num_detections[i]` entries in `nmsed_boxes[i]`, `nmsed_scores[i]` and `nmsed_classes[i]` are valid. 39 | 40 | - `nmsed_boxes` 41 | A `[batch_size, keepTopK, 4]` float32 tensor containing the coordinates of non-max suppressed boxes. 42 | 43 | - `nmsed_scores` 44 | A `[batch_size, keepTopK]` float32 tensor containing the scores for the boxes. 45 | 46 | - `nmsed_classes` 47 | A `[batch_size, keepTopK]` float32 tensor containing the classes for the boxes. 48 | 49 | 50 | ## Parameters 51 | 52 | The `batchedNMSPlugin` has plugin creator class `BatchedNMSPluginCreator` and plugin class `BatchedNMSPlugin`. 53 | 54 | The `batchedNMSPlugin` is created using `BatchedNMSPluginCreator` with `NMSParameters` typed parameters. The `NMSParameters` data structure is listed as follows and is defined in the [NvInferPlugin.h header file](https://docs.nvidia.com/deeplearning/sdk/tensorrt-api/c_api/_nv_infer_plugin_8h_source.html). 55 | 56 | | Type | Parameter | Description 57 | |----------|--------------------------|-------------------------------------------------------- 58 | |`bool` |`shareLocation` |If set to `true`, the boxes input are shared across all classes. If set to `false`, the boxes input should account for per-class box data. 59 | |`int` |`backgroundLabelId` |The label ID for the background class. If there is no background class, set it to `-1`. 60 | |`int` |`numClasses` |The number of classes in the network. 61 | |`int` |`topK` |The number of bounding boxes to be fed into the NMS step. 62 | |`int` |`keepTopK` |The number of total bounding boxes to be kept per-image after the NMS step. Should be less than or equal to the `topK` value. 63 | |`float` |`scoreThreshold` |The scalar threshold for score (low scoring boxes are removed). 64 | |`float` |`iouThreshold` |The scalar threshold for IOU (new boxes that have high IOU overlap with previously selected boxes are removed). 65 | |`bool` |`isNormalized` |Set to `false` if the box coordinates are not normalized, meaning they are not in the range `[0,1]`. Defaults to `true`. 66 | 67 | 68 | ## Algorithms 69 | 70 | The NMS algorithm used in this particular plugin first sorts the bounding boxes indices by the score for each class, then sorts the bounding boxes by the updated scores, and finally collects the desired number of bounding boxes with the highest scores. 71 | 72 | It is mainly accelerated using the `nmsInference` kernel defined in the `batchedNMSInference.cu` file. 73 | 74 | Specifically, the NMS algorithm: 75 | - Sorts the bounding box indices by the score for each class. Before sorting, the bounding boxes with a score less than `scoreThreshold` are discarded by setting their indices to `-1` and their scores to `0`. This is using the `sortScoresPerClass` kernel defined in the `sortScoresPerClass.cu` file. 76 | 77 | - Finds the most confident box for the object and removes all the less confident ones using the iterative non-maximum suppression step step for each class. Starting from the bounding box with the highest score in each class, the bounding boxes that has overlap higher than `iouThreshold` is suppressed by setting their indices to `-1` and their scores to `0`. Then all the less confident bounding boxes were suppressed for each class. This is using the `allClassNMS` kernel defined in the `allClassNMS.cu` file. 78 | 79 | - Sorts the bounding boxes per image using the updated scores. At this time, all the classes were mixed before sort. Discarded and suppressed bounding boxes will go to the end of the sorted array since their score is `0`. This is using the `sortScoresPerImage` kernel defined in the `sortScoresPerImage.cu` file. 80 | 81 | - Collects the desired number, `keepTopK`, of bounding box indices with the highest scores from the top of the sorted array, their bounding box coordinates, and their object classification information. This is using the `gatherNMSOutputs` kernel defined in the `gatherNMSOutputs.cu` file. 82 | 83 | 84 | ## Additional resources 85 | 86 | The following resources provide a deeper understanding of the `batchedNMSPlugin` plugin: 87 | 88 | **Networks** 89 | - [SSD: Single Shot MultiBox Detector](https://arxiv.org/abs/1512.02325) 90 | - [Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks](https://arxiv.org/abs/1506.01497) 91 | - [Mask R-CNN](https://arxiv.org/abs/1703.06870) 92 | 93 | 94 | **Documentation** 95 | - [NMSParameter detailed descriptions](https://docs.nvidia.com/deeplearning/sdk/tensorrt-api/c_api/structnvinfer1_1_1plugin_1_1_n_m_s_parameters.html) 96 | - [NMS algorithm](https://www.coursera.org/lecture/convolutional-neural-networks/non-max-suppression-dvrjH) 97 | 98 | 99 | ## License 100 | 101 | For terms and conditions for use, reproduction, and distribution, see the [TensorRT Software License Agreement](https://docs.nvidia.com/deeplearning/sdk/tensorrt-sla/index.html) 102 | documentation. 103 | 104 | 105 | ## Changelog 106 | 107 | May 2019 108 | This is the first release of this `README.md` file. 109 | 110 | 111 | ## Known issues 112 | 113 | - When running `cub::DeviceSegmentedRadixSort::SortPairsDescending` with `cuda-memcheck --tool racecheck`, it will not work correctly. 114 | - BatchedNMS plugin cannot handle greater than 4096 rectangles in the input. 115 | -------------------------------------------------------------------------------- /plugin/nonMaxSuppressionPlugin/gatherNMSOutputs.cu: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #include "kernel.h" 17 | #include "plugin.h" 18 | #include "gatherNMSOutputs.h" 19 | #include 20 | 21 | template 22 | __launch_bounds__(nthds_per_cta) 23 | __global__ void gatherNMSOutputs_kernel( 24 | const bool shareLocation, 25 | const int numImages, 26 | const int numPredsPerClass, 27 | const int numClasses, 28 | const int topK, 29 | const int keepTopK, 30 | const int* indices, 31 | const T_SCORE* scores, 32 | const T_BBOX* bboxData, 33 | int* nmsedIndices 34 | ) 35 | { 36 | if (keepTopK > topK) 37 | return; 38 | for (int i = blockIdx.x * nthds_per_cta + threadIdx.x; 39 | i < numImages * keepTopK; 40 | i += gridDim.x * nthds_per_cta) 41 | { 42 | const int imgId = i / keepTopK; 43 | const int detId = i % keepTopK; 44 | const int offset = imgId * numClasses * topK; 45 | const int index = indices[offset + detId]; 46 | if (index == -1) { 47 | nmsedIndices[i] = -1; 48 | } else { 49 | const int bboxOffset = imgId * (shareLocation ? numPredsPerClass : (numClasses * numPredsPerClass)); 50 | nmsedIndices[i] = ((shareLocation ? (index % numPredsPerClass) 51 | : index % (numClasses * numPredsPerClass)) + bboxOffset); 52 | } 53 | } 54 | } 55 | 56 | template 57 | pluginStatus_t gatherNMSOutputs_gpu( 58 | cudaStream_t stream, 59 | const bool shareLocation, 60 | const int numImages, 61 | const int numPredsPerClass, 62 | const int numClasses, 63 | const int topK, 64 | const int keepTopK, 65 | const void* indices, 66 | const void* scores, 67 | const void* bboxData, 68 | void* nmsedIndices 69 | ) 70 | { 71 | cudaMemsetAsync(nmsedIndices, -1, keepTopK * sizeof(int), stream); 72 | const int BS = 32; 73 | const int GS = 32; 74 | gatherNMSOutputs_kernel<<>>(shareLocation, numImages, numPredsPerClass, 75 | numClasses, topK, keepTopK, 76 | (int*) indices, (T_SCORE*) scores, (T_BBOX*) bboxData, 77 | (int*) nmsedIndices 78 | ); 79 | 80 | CSC(cudaGetLastError(), STATUS_FAILURE); 81 | return STATUS_SUCCESS; 82 | } 83 | 84 | // gatherNMSOutputs LAUNCH CONFIG {{{ 85 | typedef pluginStatus_t (*nmsOutFunc)(cudaStream_t, 86 | const bool, 87 | const int, 88 | const int, 89 | const int, 90 | const int, 91 | const int, 92 | const void*, 93 | const void*, 94 | const void*, 95 | void* 96 | ); 97 | struct nmsOutLaunchConfig 98 | { 99 | DataType t_bbox; 100 | DataType t_score; 101 | nmsOutFunc function; 102 | 103 | nmsOutLaunchConfig(DataType t_bbox, DataType t_score) 104 | : t_bbox(t_bbox) 105 | , t_score(t_score) 106 | { 107 | } 108 | nmsOutLaunchConfig(DataType t_bbox, DataType t_score, nmsOutFunc function) 109 | : t_bbox(t_bbox) 110 | , t_score(t_score) 111 | , function(function) 112 | { 113 | } 114 | bool operator==(const nmsOutLaunchConfig& other) 115 | { 116 | return t_bbox == other.t_bbox && t_score == other.t_score; 117 | } 118 | }; 119 | 120 | using nvinfer1::DataType; 121 | 122 | static std::vector nmsOutFuncVec; 123 | 124 | bool nonMaxSuppressionOutputInit() 125 | { 126 | nmsOutFuncVec.push_back(nmsOutLaunchConfig(DataType::kFLOAT, DataType::kFLOAT, 127 | gatherNMSOutputs_gpu)); 128 | return true; 129 | } 130 | 131 | static bool initialized = nonMaxSuppressionOutputInit(); 132 | 133 | //}}} 134 | 135 | pluginStatus_t gatherNMSOutputs( 136 | cudaStream_t stream, 137 | const bool shareLocation, 138 | const int numImages, 139 | const int numPredsPerClass, 140 | const int numClasses, 141 | const int topK, 142 | const int keepTopK, 143 | const DataType DT_BBOX, 144 | const DataType DT_SCORE, 145 | const void* indices, 146 | const void* scores, 147 | const void* bboxData, 148 | void* nmsedIndices 149 | ) 150 | { 151 | nmsOutLaunchConfig lc = nmsOutLaunchConfig(DT_BBOX, DT_SCORE); 152 | for (unsigned i = 0; i < nmsOutFuncVec.size(); ++i) 153 | { 154 | if (lc == nmsOutFuncVec[i]) 155 | { 156 | DEBUG_PRINTF("gatherNMSOutputs kernel %d\n", i); return nmsOutFuncVec[i].function(stream, 157 | shareLocation, 158 | numImages, 159 | numPredsPerClass, 160 | numClasses, 161 | topK, 162 | keepTopK, 163 | indices, 164 | scores, 165 | bboxData, 166 | nmsedIndices 167 | ); 168 | } 169 | } 170 | return STATUS_BAD_PARAM; 171 | } 172 | -------------------------------------------------------------------------------- /plugin/nonMaxSuppressionPlugin/gatherNMSOutputs.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #ifndef TRT_NON_MAX_SUPPRESSION_HELPER_H 17 | #define TRT_NON_MAX_SUPPRESSION_HELPER_H 18 | #include "plugin.h" 19 | using namespace nvinfer1; 20 | using namespace nvinfer1::plugin; 21 | 22 | pluginStatus_t gatherNMSOutputs(cudaStream_t stream, bool shareLocation, int numImages, int numPredsPerClass, 23 | int numClasses, int topK, int keepTopK, DataType DT_BBOX, DataType DT_SCORE, const void* indices, 24 | const void* scores, const void* bboxData, void* nmsedIndices); 25 | 26 | #endif 27 | -------------------------------------------------------------------------------- /plugin/nonMaxSuppressionPlugin/nonMaxSuppressionInference.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #include "bboxUtils.h" 17 | #include "cuda_runtime_api.h" 18 | #include "gatherNMSOutputs.h" 19 | #include "kernel.h" 20 | #include "nmsUtils.h" 21 | 22 | pluginStatus_t nonMaxSuppressionInference(cudaStream_t stream, const int N, const int perBatchBoxesSize, const int perBatchScoresSize, 23 | const bool shareLocation, const int backgroundLabelId, const int numPredsPerClass, const int numClasses, 24 | const int topK, const int keepTopK, const float scoreThreshold, const float iouThreshold, const DataType DT_BBOX, 25 | const void* locData, const DataType DT_SCORE, const void* confData, 26 | void* nmsedIndices, void* workspace, bool isNormalized, bool confSigmoid) 27 | { 28 | // locCount = batch_size * number_boxes_per_sample * 4 29 | const int locCount = N * perBatchBoxesSize; 30 | /* 31 | * shareLocation 32 | * Bounding box are shared among all classes, i.e., a bounding box could be classified as any candidate class. 33 | * Otherwise 34 | * Bounding box are designed for specific classes, i.e., a bounding box could be classified as one certain class or 35 | * not (binary classification). 36 | */ 37 | const int numLocClasses = shareLocation ? 1 : numClasses; 38 | 39 | size_t bboxDataSize = detectionForwardBBoxDataSize(N, perBatchBoxesSize, DataType::kFLOAT); 40 | void* bboxDataRaw = workspace; 41 | cudaMemcpyAsync(bboxDataRaw, locData, bboxDataSize, cudaMemcpyDeviceToDevice, stream); 42 | pluginStatus_t status; 43 | 44 | /* 45 | * bboxDataRaw format: 46 | * [batch size, numPriors (per sample), numLocClasses, 4] 47 | */ 48 | // float for now 49 | void* bboxData; 50 | size_t bboxPermuteSize = detectionForwardBBoxPermuteSize(shareLocation, N, perBatchBoxesSize, DataType::kFLOAT); 51 | void* bboxPermute = nextWorkspacePtr((int8_t*) bboxDataRaw, bboxDataSize); 52 | 53 | /* 54 | * After permutation, bboxData format: 55 | * [batch_size, numLocClasses, numPriors (per sample) (numPredsPerClass), 4] 56 | * This is equivalent to swapping axis 57 | */ 58 | if (!shareLocation) 59 | { 60 | status = permuteData( 61 | stream, locCount, numLocClasses, numPredsPerClass, 4, DataType::kFLOAT, false, bboxDataRaw, bboxPermute); 62 | ASSERT_FAILURE(status == STATUS_SUCCESS); 63 | bboxData = bboxPermute; 64 | } 65 | /* 66 | * If shareLocation, numLocClasses = 1 67 | * No need to permute data on linear memory 68 | */ 69 | else 70 | { 71 | bboxData = bboxDataRaw; 72 | } 73 | 74 | /* 75 | * Conf data format 76 | * [batch size, numPriors * param.numClasses, 1, 1] 77 | */ 78 | const int numScores = N * perBatchScoresSize; 79 | size_t totalScoresSize = detectionForwardPreNMSSize(N, perBatchScoresSize); 80 | void* scores = nextWorkspacePtr((int8_t*) bboxPermute, bboxPermuteSize); 81 | 82 | // need a conf_scores 83 | /* 84 | * After permutation, bboxData format: 85 | * [batch_size, numClasses, numPredsPerClass, 1] 86 | */ 87 | status = permuteData( 88 | stream, numScores, numClasses, numPredsPerClass, 1, DataType::kFLOAT, confSigmoid, confData, scores); 89 | ASSERT_FAILURE(status == STATUS_SUCCESS); 90 | 91 | size_t indicesSize = detectionForwardPreNMSSize(N, perBatchScoresSize); 92 | void* indices = nextWorkspacePtr((int8_t*) scores, totalScoresSize); 93 | 94 | size_t postNMSScoresSize = detectionForwardPostNMSSize(N, numClasses, topK); 95 | size_t postNMSIndicesSize = detectionForwardPostNMSSize(N, numClasses, topK); 96 | void* postNMSScores = nextWorkspacePtr((int8_t*) indices, indicesSize); 97 | void* postNMSIndices = nextWorkspacePtr((int8_t*) postNMSScores, postNMSScoresSize); 98 | 99 | void* sortingWorkspace = nextWorkspacePtr((int8_t*) postNMSIndices, postNMSIndicesSize); 100 | // Sort the scores so that the following NMS could be applied. 101 | status = sortScoresPerClass(stream, N, numClasses, numPredsPerClass, backgroundLabelId, scoreThreshold, 102 | DataType::kFLOAT, scores, indices, sortingWorkspace); 103 | 104 | ASSERT_FAILURE(status == STATUS_SUCCESS); 105 | 106 | // This is set to true as the input bounding boxes are of the format [ymin, 107 | // xmin, ymax, xmax]. The default implementation assumes [xmin, ymin, xmax, ymax] 108 | bool flipXY = true; 109 | // NMS 110 | status = allClassNMS(stream, N, numClasses, numPredsPerClass, topK, iouThreshold, shareLocation, isNormalized, 111 | DataType::kFLOAT, DataType::kFLOAT, bboxData, scores, indices, postNMSScores, postNMSIndices, flipXY); 112 | ASSERT_FAILURE(status == STATUS_SUCCESS); 113 | 114 | // Sort the bounding boxes after NMS using scores 115 | status = sortScoresPerImage(stream, N, numClasses * topK, DataType::kFLOAT, postNMSScores, postNMSIndices, scores, 116 | indices, sortingWorkspace); 117 | 118 | // int* a = (int*)malloc(200 * sizeof(int)); 119 | // cudaMemcpy(a, postNMSIndices, 200 * sizeof(int), cudaMemcpyDeviceToHost); 120 | // for (int b = 0; b < 100; b ++) { 121 | // std::cout << ", " << a[b]; 122 | // } 123 | // std::cout << std::endl; 124 | // free(a); 125 | 126 | ASSERT_FAILURE(status == STATUS_SUCCESS); 127 | // Gather data from the sorted bounding boxes after NMS 128 | status = gatherNMSOutputs(stream, shareLocation, N, numPredsPerClass, numClasses, topK, keepTopK, DataType::kFLOAT, 129 | DataType::kFLOAT, indices, scores, bboxData, nmsedIndices); 130 | ASSERT_FAILURE(status == STATUS_SUCCESS); 131 | 132 | return STATUS_SUCCESS; 133 | } 134 | -------------------------------------------------------------------------------- /plugin/nonMaxSuppressionPlugin/nonMaxSuppressionInference.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #ifndef TRT_NON_MAX_SUPPRESSION_INFERENCE_H 17 | #define TRT_NON_MAX_SUPPRESSION_INFERENCE_H 18 | #include "plugin.h" 19 | 20 | using namespace nvinfer1; 21 | using namespace nvinfer1::plugin; 22 | 23 | pluginStatus_t nonMaxSuppressionInference(cudaStream_t stream, int N, int boxesSize, int scoresSize, bool shareLocation, 24 | int backgroundLabelId, int numPredsPerClass, int numClasses, int topK, int keepTopK, float scoreThreshold, 25 | float iouThreshold, DataType DT_BBOX, const void* locData, DataType DT_SCORE, const void* confData, void* nmsedIndices, void* workspace, bool isNormalized, bool confSigmoid = false); 26 | #endif 27 | -------------------------------------------------------------------------------- /plugin/nonMaxSuppressionPlugin/nonMaxSuppressionPlugin.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "nonMaxSuppressionPlugin.h" 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | using namespace nvinfer1; 25 | using nvinfer1::plugin::NonMaxSuppressionPlugin; 26 | using nvinfer1::plugin::NonMaxSuppressionPluginCreator; 27 | using nvinfer1::plugin::NMSParameters; 28 | 29 | namespace 30 | { 31 | constexpr const char* NMS_PLUGIN_VERSION{"1"}; 32 | constexpr const char* NMS_PLUGIN_NAME{"NonMaxSuppression_TRT"}; 33 | } // namespace 34 | REGISTER_TENSORRT_PLUGIN(NonMaxSuppressionPluginCreator); 35 | 36 | PluginFieldCollection NonMaxSuppressionPluginCreator::mFC{}; 37 | std::vector NonMaxSuppressionPluginCreator::mPluginAttributes; 38 | 39 | NonMaxSuppressionPlugin::NonMaxSuppressionPlugin(NMSParameters params) 40 | : param(params) 41 | { 42 | } 43 | 44 | NonMaxSuppressionPlugin::NonMaxSuppressionPlugin(const void* data, size_t length) 45 | { 46 | const char *d = reinterpret_cast(data), *a = d; 47 | param = read(d); 48 | boxesSize = read(d); 49 | scoresSize = read(d); 50 | numPriors = read(d); 51 | mClipBoxes = read(d); 52 | ASSERT(d == a + length); 53 | } 54 | 55 | int NonMaxSuppressionPlugin::getNbOutputs() const 56 | { 57 | return 1; 58 | } 59 | 60 | int NonMaxSuppressionPlugin::initialize() 61 | { 62 | return STATUS_SUCCESS; 63 | } 64 | 65 | void NonMaxSuppressionPlugin::terminate() {} 66 | 67 | // Dims BatchedNMSPlugin::getOutputDimensions(int index, const Dims* inputs, int nbInputDims) 68 | DimsExprs NonMaxSuppressionPlugin::getOutputDimensions(int outputIndex, const nvinfer1::DimsExprs* inputs, int nbInputs, nvinfer1::IExprBuilder& exprBuilder) 69 | { 70 | ASSERT(nbInputs == 2); 71 | ASSERT(outputIndex >= 0 && outputIndex < this->getNbOutputs()); 72 | ASSERT(inputs[0].nbDims == 3); 73 | ASSERT(inputs[1].nbDims == 3); 74 | // scoresSize: number of scores for one sample 75 | scoresSize = inputs[1].d[2]->getConstantValue(); 76 | // boxesSize: number of box coordinates for one sample 77 | boxesSize = scoresSize * 4; 78 | // num_detections 79 | DimsExprs ret; 80 | ret.nbDims = 1; 81 | ret.d[0] = exprBuilder.constant(param.keepTopK); 82 | return ret; 83 | } 84 | 85 | // size_t BatchedNMSPlugin::getWorkspaceSize(int maxBatchSize) const 86 | size_t NonMaxSuppressionPlugin::getWorkspaceSize(const nvinfer1::PluginTensorDesc* inputs, int nbInputs, const nvinfer1::PluginTensorDesc* outputs, int nbOutputs) const 87 | { 88 | return detectionInferenceWorkspaceSize(param.shareLocation, /*maxBatchSize=*/1, boxesSize, scoresSize, param.numClasses, 89 | numPriors, param.topK, DataType::kFLOAT, DataType::kFLOAT); 90 | } 91 | 92 | // int BatchedNMSPlugin::enqueue( 93 | // int batchSize, const void* const* inputs, void** outputs, void* workspace, cudaStream_t stream) 94 | int NonMaxSuppressionPlugin::enqueue(const nvinfer1::PluginTensorDesc* inputDesc, const nvinfer1::PluginTensorDesc* outputDesc, 95 | const void* const* inputs, void* const* outputs, 96 | void* workspace, 97 | cudaStream_t stream) 98 | { 99 | const void* const locData = inputs[0]; 100 | const void* const confData = inputs[1]; 101 | 102 | void* nmsedIndices = outputs[0]; 103 | pluginStatus_t status = nonMaxSuppressionInference(stream, 1, boxesSize, scoresSize, param.shareLocation, 104 | param.backgroundLabelId, numPriors, param.numClasses, param.topK, param.keepTopK, param.scoreThreshold, 105 | param.iouThreshold, DataType::kFLOAT, locData, DataType::kFLOAT, confData, nmsedIndices, 106 | workspace, param.isNormalized, false); 107 | // if (scoresSize > 1000) { 108 | // std::cout << "scoresSize: " << scoresSize << ", topK: " << param.topK << ", numClasses: " << param.numClasses << ", keepTopK: " << param.keepTopK << ", scoreThreshold: " << param.scoreThreshold << ", iouThreshold: " << param.iouThreshold << std::endl; 109 | // float* a = (float*)malloc(20 * 4 * sizeof(float)); 110 | // cudaMemcpy(a, locData, 20 * 4 * sizeof(float), cudaMemcpyDeviceToHost); 111 | // for (int i = 0; i < 20; i ++) { 112 | // for (int j = 0; j < 4; j ++) { 113 | // std::cout << a[i * 4 + j] << ", "; 114 | // } 115 | // std::cout << std::endl; 116 | // } 117 | // std::cout << std::endl; 118 | // free(a); 119 | // } 120 | 121 | ASSERT(status == STATUS_SUCCESS); 122 | return 0; 123 | } 124 | 125 | size_t NonMaxSuppressionPlugin::getSerializationSize() const 126 | { 127 | // NMSParameters, boxesSize,scoresSize,numPriors 128 | return sizeof(NMSParameters) + sizeof(int) * 3 + sizeof(bool); 129 | } 130 | 131 | void NonMaxSuppressionPlugin::serialize(void* buffer) const 132 | { 133 | char *d = reinterpret_cast(buffer), *a = d; 134 | write(d, param); 135 | write(d, boxesSize); 136 | write(d, scoresSize); 137 | write(d, numPriors); 138 | write(d, mClipBoxes); 139 | ASSERT(d == a + getSerializationSize()); 140 | } 141 | 142 | // void BatchedNMSPlugin::configurePlugin(const Dims* inputDims, int nbInputs, const Dims* outputDims, int nbOutputs, 143 | // const DataType* inputTypes, const DataType* outputTypes, const bool* inputIsBroadcast, 144 | // const bool* outputIsBroadcast, nvinfer1::PluginFormat format, int maxBatchSize) 145 | void NonMaxSuppressionPlugin::configurePlugin(const nvinfer1::DynamicPluginTensorDesc* in, int nbInputs, 146 | const nvinfer1::DynamicPluginTensorDesc* out, int nbOutputs) 147 | { 148 | ASSERT(nbInputs == 2); 149 | ASSERT(nbOutputs == 1); 150 | ASSERT(in[0].desc.dims.nbDims == 3); 151 | ASSERT(in[1].desc.dims.nbDims == 3); 152 | 153 | scoresSize = in[1].desc.dims.d[2]; 154 | boxesSize = scoresSize * 4; 155 | // num_boxes 156 | numPriors = in[1].desc.dims.d[2]; 157 | const int numLocClasses = param.shareLocation ? 1 : param.numClasses; 158 | // Third dimension of boxes must be either 1 or num_classes 159 | ASSERT(in[0].desc.dims.d[2] == 4 || in[0].desc.dims.d[2] == -1); 160 | } 161 | 162 | 163 | bool NonMaxSuppressionPlugin::supportsFormatCombination(int pos, const nvinfer1::PluginTensorDesc* inOut, int nbInputs, int nbOutputs) 164 | { 165 | ASSERT(inOut && pos < (nbInputs + nbOutputs)); 166 | if (pos <= 1) { 167 | return ((inOut[pos].type == nvinfer1::DataType::kFLOAT || inOut[pos].type == nvinfer1::DataType::kHALF) 168 | && inOut[pos].format == nvinfer1::PluginFormat::kLINEAR && inOut[pos].type == inOut[0].type); 169 | } else { 170 | return inOut[pos].format == nvinfer1::PluginFormat::kLINEAR && inOut[pos].type == DataType::kINT32; 171 | } 172 | } 173 | 174 | const char* NonMaxSuppressionPlugin::getPluginType() const 175 | { 176 | return NMS_PLUGIN_NAME; 177 | } 178 | 179 | const char* NonMaxSuppressionPlugin::getPluginVersion() const 180 | { 181 | return NMS_PLUGIN_VERSION; 182 | } 183 | 184 | void NonMaxSuppressionPlugin::destroy() 185 | { 186 | delete this; 187 | } 188 | 189 | IPluginV2DynamicExt* NonMaxSuppressionPlugin::clone() const 190 | { 191 | auto* plugin = new NonMaxSuppressionPlugin(param); 192 | plugin->boxesSize = boxesSize; 193 | plugin->scoresSize = scoresSize; 194 | plugin->numPriors = numPriors; 195 | plugin->setPluginNamespace(mNamespace.c_str()); 196 | plugin->setClipParam(mClipBoxes); 197 | return plugin; 198 | } 199 | 200 | void NonMaxSuppressionPlugin::setPluginNamespace(const char* pluginNamespace) 201 | { 202 | mPluginNamespace = pluginNamespace; 203 | } 204 | 205 | const char* NonMaxSuppressionPlugin::getPluginNamespace() const 206 | { 207 | return mPluginNamespace; 208 | } 209 | 210 | nvinfer1::DataType NonMaxSuppressionPlugin::getOutputDataType( 211 | int index, const nvinfer1::DataType* inputTypes, int nbInputs) const 212 | { 213 | ASSERT(index >= 0 && index < this->getNbOutputs()); 214 | return nvinfer1::DataType::kINT32; 215 | } 216 | 217 | void NonMaxSuppressionPlugin::setClipParam(bool clip) 218 | { 219 | mClipBoxes = clip; 220 | } 221 | 222 | NonMaxSuppressionPluginCreator::NonMaxSuppressionPluginCreator() 223 | : params{} 224 | { 225 | mPluginAttributes.emplace_back(PluginField("shareLocation", nullptr, PluginFieldType::kINT32, 1)); 226 | mPluginAttributes.emplace_back(PluginField("backgroundLabelId", nullptr, PluginFieldType::kINT32, 1)); 227 | mPluginAttributes.emplace_back(PluginField("numClasses", nullptr, PluginFieldType::kINT32, 1)); 228 | mPluginAttributes.emplace_back(PluginField("topK", nullptr, PluginFieldType::kINT32, 1)); 229 | mPluginAttributes.emplace_back(PluginField("keepTopK", nullptr, PluginFieldType::kINT32, 1)); 230 | mPluginAttributes.emplace_back(PluginField("scoreThreshold", nullptr, PluginFieldType::kFLOAT32, 1)); 231 | mPluginAttributes.emplace_back(PluginField("iouThreshold", nullptr, PluginFieldType::kFLOAT32, 1)); 232 | mPluginAttributes.emplace_back(PluginField("isNormalized", nullptr, PluginFieldType::kINT32, 1)); 233 | mPluginAttributes.emplace_back(PluginField("clipBoxes", nullptr, PluginFieldType::kINT32, 1)); 234 | 235 | mFC.nbFields = mPluginAttributes.size(); 236 | mFC.fields = mPluginAttributes.data(); 237 | } 238 | 239 | const char* NonMaxSuppressionPluginCreator::getPluginName() const 240 | { 241 | return NMS_PLUGIN_NAME; 242 | } 243 | 244 | const char* NonMaxSuppressionPluginCreator::getPluginVersion() const 245 | { 246 | return NMS_PLUGIN_VERSION; 247 | } 248 | 249 | const PluginFieldCollection* NonMaxSuppressionPluginCreator::getFieldNames() 250 | { 251 | return &mFC; 252 | } 253 | 254 | IPluginV2DynamicExt* NonMaxSuppressionPluginCreator::createPlugin(const char* name, const PluginFieldCollection* fc) 255 | { 256 | const PluginField* fields = fc->fields; 257 | mClipBoxes = true; 258 | 259 | for (int i = 0; i < fc->nbFields; ++i) 260 | { 261 | const char* attrName = fields[i].name; 262 | if (!strcmp(attrName, "shareLocation")) 263 | { 264 | params.shareLocation = *(static_cast(fields[i].data)); 265 | } 266 | else if (!strcmp(attrName, "backgroundLabelId")) 267 | { 268 | ASSERT(fields[i].type == PluginFieldType::kINT32); 269 | params.backgroundLabelId = *(static_cast(fields[i].data)); 270 | } 271 | else if (!strcmp(attrName, "numClasses")) 272 | { 273 | ASSERT(fields[i].type == PluginFieldType::kINT32); 274 | params.numClasses = *(static_cast(fields[i].data)); 275 | } 276 | else if (!strcmp(attrName, "topK")) 277 | { 278 | ASSERT(fields[i].type == PluginFieldType::kINT32); 279 | params.topK = *(static_cast(fields[i].data)); 280 | } 281 | else if (!strcmp(attrName, "keepTopK")) 282 | { 283 | ASSERT(fields[i].type == PluginFieldType::kINT32); 284 | params.keepTopK = *(static_cast(fields[i].data)); 285 | } 286 | else if (!strcmp(attrName, "scoreThreshold")) 287 | { 288 | ASSERT(fields[i].type == PluginFieldType::kFLOAT32); 289 | params.scoreThreshold = *(static_cast(fields[i].data)); 290 | } 291 | else if (!strcmp(attrName, "iouThreshold")) 292 | { 293 | ASSERT(fields[i].type == PluginFieldType::kFLOAT32); 294 | params.iouThreshold = *(static_cast(fields[i].data)); 295 | } 296 | else if (!strcmp(attrName, "isNormalized")) 297 | { 298 | params.isNormalized = *(static_cast(fields[i].data)); 299 | } 300 | else if (!strcmp(attrName, "clipBoxes")) 301 | { 302 | mClipBoxes = *(static_cast(fields[i].data)); 303 | } 304 | } 305 | 306 | NonMaxSuppressionPlugin* plugin = new NonMaxSuppressionPlugin(params); 307 | plugin->setClipParam(mClipBoxes); 308 | plugin->setPluginNamespace(mNamespace.c_str()); 309 | return plugin; 310 | } 311 | 312 | IPluginV2DynamicExt* NonMaxSuppressionPluginCreator::deserializePlugin(const char* name, const void* serialData, size_t serialLength) 313 | { 314 | // This object will be deleted when the network is destroyed, which will 315 | // call NMS::destroy() 316 | NonMaxSuppressionPlugin* plugin = new NonMaxSuppressionPlugin(serialData, serialLength); 317 | plugin->setPluginNamespace(mNamespace.c_str()); 318 | return plugin; 319 | } 320 | -------------------------------------------------------------------------------- /plugin/nonMaxSuppressionPlugin/nonMaxSuppressionPlugin.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #ifndef TRT_NON_MAX_SUPPRESSION_PLUGIN_H 17 | #define TRT_NON_MAX_SUPPRESSION_PLUGIN_H 18 | #include "nonMaxSuppressionPlugin/nonMaxSuppressionInference.h" 19 | #include "nonMaxSuppressionPlugin/gatherNMSOutputs.h" 20 | #include "kernel.h" 21 | #include "nmsUtils.h" 22 | #include "plugin.h" 23 | #include 24 | #include 25 | #include 26 | 27 | typedef unsigned short half_type; 28 | 29 | using namespace nvinfer1::plugin; 30 | namespace nvinfer1 31 | { 32 | namespace plugin 33 | { 34 | 35 | class NonMaxSuppressionPlugin : public IPluginV2DynamicExt 36 | { 37 | public: 38 | NonMaxSuppressionPlugin(NMSParameters param); 39 | 40 | NonMaxSuppressionPlugin(const void* data, size_t length); 41 | 42 | ~NonMaxSuppressionPlugin() override = default; 43 | 44 | int getNbOutputs() const override; 45 | 46 | //DynamicExt plugins returns DimsExprs class instead of Dims 47 | // Dims getOutputDimensions(int index, const Dims* inputs, int nbInputDims) override; 48 | DimsExprs getOutputDimensions(int outputIndex, const nvinfer1::DimsExprs* inputs, int nbInputs, nvinfer1::IExprBuilder& exprBuilder) override; 49 | 50 | // DynamicExt plugin supportsFormat update. 51 | bool supportsFormatCombination(int pos, const nvinfer1::PluginTensorDesc* inOut, int nbInputs, int nbOutputs) override; 52 | 53 | int initialize() override; 54 | 55 | void terminate() override; 56 | 57 | // size_t getWorkspaceSize(int maxBatchSize) const override; 58 | size_t getWorkspaceSize(const nvinfer1::PluginTensorDesc* inputs, int nbInputs, const nvinfer1::PluginTensorDesc* outputs, int nbOutputs) const override; 59 | 60 | 61 | // int enqueue( 62 | // int batchSize, const void* const* inputs, void** outputs, void* workspace, cudaStream_t stream) override; 63 | int enqueue(const nvinfer1::PluginTensorDesc* inputDesc, const nvinfer1::PluginTensorDesc* outputDesc, 64 | const void* const* inputs, void* const* outputs, 65 | void* workspace, 66 | cudaStream_t stream) override; 67 | 68 | size_t getSerializationSize() const override; 69 | 70 | void serialize(void* buffer) const override; 71 | 72 | // void configurePlugin(const Dims* inputDims, int nbInputs, const Dims* outputDims, int nbOutputs, 73 | // const DataType* inputTypes, const DataType* outputTypes, const bool* inputIsBroadcast, 74 | // const bool* outputIsBroadcast, PluginFormat floatFormat, int maxBatchSize) override; 75 | void configurePlugin(const nvinfer1::DynamicPluginTensorDesc* in, int nbInputs, 76 | const nvinfer1::DynamicPluginTensorDesc* out, int nbOutputs) override; 77 | 78 | const char* getPluginType() const override; 79 | 80 | const char* getPluginVersion() const override; 81 | 82 | void destroy() override; 83 | 84 | IPluginV2DynamicExt* clone() const override; 85 | 86 | nvinfer1::DataType getOutputDataType(int index, const nvinfer1::DataType* inputType, int nbInputs) const override; 87 | 88 | void setPluginNamespace(const char* libNamespace) override; 89 | 90 | const char* getPluginNamespace() const override; 91 | 92 | void setClipParam(bool clip); 93 | 94 | private: 95 | NMSParameters param{}; 96 | int boxesSize{}; 97 | int scoresSize{}; 98 | int numPriors{}; 99 | std::string mNamespace; 100 | bool mClipBoxes{}; 101 | const char* mPluginNamespace; 102 | }; 103 | 104 | class NonMaxSuppressionPluginCreator : public BaseCreator 105 | { 106 | public: 107 | NonMaxSuppressionPluginCreator(); 108 | 109 | ~NonMaxSuppressionPluginCreator() override = default; 110 | 111 | const char* getPluginName() const override; 112 | 113 | const char* getPluginVersion() const override; 114 | 115 | const PluginFieldCollection* getFieldNames() override; 116 | 117 | IPluginV2DynamicExt* createPlugin(const char* name, const PluginFieldCollection* fc) override; 118 | 119 | IPluginV2DynamicExt* deserializePlugin(const char* name, const void* serialData, size_t serialLength) override; 120 | 121 | private: 122 | static PluginFieldCollection mFC; 123 | NMSParameters params; 124 | static std::vector mPluginAttributes; 125 | bool mClipBoxes; 126 | }; 127 | } // namespace plugin 128 | } // namespace nvinfer1 129 | 130 | #endif // TRT_NON_MAX_SUPPRESSION_PLUGIN_H 131 | -------------------------------------------------------------------------------- /symbolic_opset10.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, division, print_function, unicode_literals 2 | 3 | import torch 4 | from torch.nn.modules.utils import _single, _pair, _triple 5 | import torch.onnx 6 | # This import monkey-patches graph manipulation methods on Graph, used for the 7 | # ONNX symbolics 8 | import torch.onnx.utils 9 | 10 | import torch.onnx.symbolic_helper as sym_help 11 | from torch.onnx.symbolic_helper import parse_args, _unimplemented 12 | import torch.onnx.symbolic_opset9 13 | 14 | 15 | # EDITING THIS FILE? READ THIS FIRST! 16 | # see Note [Edit Symbolic Files] in symbolic_helper.py 17 | 18 | # This file exports ONNX ops for opset 10 19 | # Opset 10 is supported by ONNX release 1.5.0 20 | # release on 04/24/19 21 | 22 | 23 | @parse_args('v', 'i', 'i', 'none') 24 | def sort(g, self, dim, decending, out=None): 25 | return sym_help._sort_helper(g, self, dim, decending=decending, out=out) 26 | 27 | 28 | # @parse_args('v', 'v', 'i', 'i', 'i', 'none') 29 | # def topk(g, self, k, dim, largest, sorted, out=None): 30 | # return sym_help._topk_helper(g, self, k, dim, largest=largest, sorted=sorted, out=out) 31 | 32 | 33 | def _max_pool(name, tuple_fn, ndims, return_indices): 34 | @parse_args('v', 'is', 'is', 'is', 'is', 'i') 35 | def symbolic_fn(g, input, kernel_size, stride, padding, dilation, ceil_mode): 36 | if not stride: 37 | stride = kernel_size 38 | kwargs = { 39 | 'kernel_shape_i': tuple_fn(kernel_size), 40 | 'pads_i': tuple_fn(padding) * 2, 41 | 'strides_i': tuple_fn(stride), 42 | 'ceil_mode_i': ceil_mode, 43 | } 44 | if set(tuple_fn(dilation)) != {1}: 45 | kwargs['dilations_i'] = tuple_fn(dilation) 46 | # easy but hacky way to get flattened indices values 47 | # to be used to convert the indices values to non-flattened. 48 | # In ONNX the indices are computed as a flatten 1-D tensor, 49 | # so the values in indices are in [0, N x C x D1 x ... x Dn). 50 | # To convert the indices to the same format used by Pytorch, 51 | # we first execute a maxpool with a kernel and stride of 1 on the same input. 52 | # This will result in a tensor of indices in which each index will have it's own value. 53 | # Using this tensor as a reference, we extract the first index of each axis and substract 54 | # it from each index of this axis in the indices to convert. 55 | # This step will result in a tensor were each dimension has values of indices within 56 | # the dimension it is in. 57 | # For more information : 58 | # https://github.com/pytorch/pytorch/pull/16455#issuecomment-460776407 59 | if return_indices: 60 | r, indices = g.op("MaxPool", input, outputs=2, **kwargs) 61 | _, flattened_indices = g.op("MaxPool", input, outputs=2, 62 | kernel_shape_i=[1 for _ in range(ndims)], 63 | strides_i=[1 for _ in range(ndims)]) 64 | # convert indices to have non-flattened indices values 65 | from torch.onnx.symbolic_opset9 import sub 66 | s = sym_help._slice_helper(g, flattened_indices, axes=[2 + i for i in range(ndims)], 67 | starts=tuple_fn(0), ends=tuple_fn(1)) 68 | indices = sub(g, indices, s) 69 | return r, indices 70 | else: 71 | r = g.op("MaxPool", input, outputs=1, **kwargs) 72 | return r 73 | 74 | return symbolic_fn 75 | 76 | 77 | max_pool1d = _max_pool("max_pool1d", _single, 1, return_indices=False) 78 | max_pool2d = _max_pool("max_pool2d", _pair, 2, return_indices=False) 79 | max_pool3d = _max_pool("max_pool3d", _triple, 3, return_indices=False) 80 | max_pool1d_with_indices = _max_pool("max_pool1d_with_indices", _single, 1, return_indices=True) 81 | max_pool2d_with_indices = _max_pool("max_pool2d_with_indices", _pair, 2, return_indices=True) 82 | max_pool3d_with_indices = _max_pool("max_pool3d_with_indices", _triple, 3, return_indices=True) 83 | 84 | 85 | def _avg_pool(name, tuple_fn): 86 | @parse_args('v', 'is', 'is', 'is', 'i', 'i', 'none') 87 | def symbolic_fn(g, input, kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override=None): 88 | padding = sym_help._avgpool_helper(tuple_fn, padding, kernel_size, stride, divisor_override, name) 89 | if count_include_pad: 90 | input = g.op("Pad", input, 91 | pads_i=((0,) * 2 + padding) * 2, 92 | mode_s='constant', 93 | value_f=0.) 94 | padding = (0,) * len(padding) 95 | output = g.op("AveragePool", input, 96 | kernel_shape_i=tuple_fn(kernel_size), 97 | strides_i=tuple_fn(stride), 98 | pads_i=padding * 2, 99 | ceil_mode_i=ceil_mode) 100 | return output 101 | return symbolic_fn 102 | 103 | 104 | avg_pool1d = _avg_pool('avg_pool1d', _single) 105 | avg_pool2d = _avg_pool('avg_pool2d', _pair) 106 | avg_pool3d = _avg_pool('avg_pool3d', _triple) 107 | 108 | 109 | def _interpolate(name, dim, interpolate_mode): 110 | def symbolic_fn(g, input, output_size, align_corners=None): 111 | sym_help._interpolate_warning(interpolate_mode) 112 | align_corners = sym_help._maybe_get_scalar(align_corners) 113 | if align_corners: 114 | return _unimplemented(name, "align_corners == True") 115 | scales = sym_help._interpolate_size_to_scales(g, input, output_size, dim) 116 | return g.op("Resize", input, scales, mode_s=interpolate_mode) 117 | return symbolic_fn 118 | 119 | upsample_nearest1d = _interpolate('upsample_nearest1d', 3, "nearest") 120 | upsample_nearest2d = _interpolate('upsample_nearest2d', 4, "nearest") 121 | upsample_nearest3d = _interpolate('upsample_nearest3d', 5, "nearest") 122 | upsample_linear1d = _interpolate('upsample_linear1d', 3, "linear") 123 | upsample_bilinear2d = _interpolate('upsample_bilinear2d', 4, "linear") 124 | upsample_trilinear3d = _interpolate('upsample_trilinear3d', 5, "linear") 125 | 126 | def arange(g, *args): 127 | from torch.onnx.symbolic_opset11 import arange as arange11 128 | return arange11(g, *args) 129 | 130 | 131 | def __interpolate(g, input, size, scale_factor, mode , align_corners): 132 | scales, mode = sym_help._interpolate_get_scales_and_mode(g, input, size, scale_factor, 133 | mode , align_corners) 134 | return g.op("Resize", input, scales, mode_s=mode) 135 | 136 | 137 | def _slice(g, input, axes, starts, ends, steps=None, dynamic_slice=False): 138 | if dynamic_slice: 139 | starts = g.op("Unsqueeze", starts, axes_i=[0]) 140 | ends = g.op("Unsqueeze", ends, axes_i=[0]) 141 | axes = g.op("Unsqueeze", axes, axes_i=[0]) 142 | else: 143 | assert len(starts) == len(ends) 144 | assert len(starts) == len(axes) 145 | assert steps is None or len(starts) == len(steps) 146 | if len(starts) == 1 and starts[0] == 0 and ends[0] == 9223372036854775807 \ 147 | and (steps is None or (len(steps) == 1 and steps[0] == 1)): 148 | return input 149 | axes = g.op("Constant", value_t=torch.tensor(axes)) 150 | starts = g.op("Constant", value_t=torch.tensor(starts)) 151 | ends = g.op("Constant", value_t=torch.tensor(ends)) 152 | if steps is None: 153 | return g.op("Slice", input, starts, ends, axes) 154 | steps = g.op("Constant", value_t=torch.tensor(steps)) 155 | return g.op("Slice", input, starts, ends, axes, steps) 156 | 157 | 158 | @parse_args('v', 'v', 'v', 'v', 'i') 159 | def slice(g, self, dim, start, end, step): 160 | if (start.node().kind() != 'onnx::Constant' or 161 | end.node().kind() != 'onnx::Constant' or dim.node().kind() != 'onnx::Constant'): 162 | dynamic_slice = True 163 | else: 164 | start = [sym_help._parse_arg(start, 'i')] 165 | end = [sym_help._parse_arg(end, 'i')] 166 | dim = [sym_help._parse_arg(dim, 'i')] 167 | dynamic_slice = False 168 | return sym_help._slice_helper(g, self, axes=dim, starts=start, ends=end, steps=[step], dynamic_slice=dynamic_slice) 169 | 170 | 171 | @parse_args('v', 'is') 172 | def flip(g, input, dims): 173 | return sym_help._slice_helper(g, input, axes=dims, 174 | starts=[-1] * len(dims), 175 | ends=[-9223372036854775807] * len(dims), 176 | steps=[-1] * len(dims)) 177 | 178 | 179 | def fmod(g, input, other): 180 | return g.op("Mod", input, other, fmod_i=1) 181 | --------------------------------------------------------------------------------