[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.pyc\n\n# C extensions\n*.so\n*.o\n\n# Distribution / packaging\n.Python\nbuild/\n\n*.swp\n\nweights/\nlog/\nsave/\ntrained_model/\ndist/\n*.egg-info/\n\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Learning Spatial Fusion for Single-Shot Object Detection\n\nBy Songtao Liu, Di Huang, Yunhong Wang\n\n### Introduction\nIn this work, we propose a novel and data driven strategy for pyramidal feature fusion, referred to as adaptively spatial feature fusion (ASFF). It learns the way to spatially filter conflictive information to suppress the inconsistency, thus improving the scale-invariance of features, and introduces nearly free inference overhead. For more details, please refer to our [arXiv paper](https://arxiv.org/abs/1911.09516).\n\n<img align=\"center\" src=\"https://github.com/ruinmessi/ASFF/blob/master/doc/asff.png\">\n\n### Updates:\n- YOLOX is [here!](https://github.com/Megvii-BaseDetection/YOLOX), come and use the stronger YOLO!\n- Add MobileNet V2!\n    * The previous models actually are all trained with the wrong anchor setting, we fix the error on mobileNet model.\n    * We currently not support rfb, dropblock and Feature Adaption for mobileNet V2.\n    * FP16 training for mobileNet is not working now. I didn't figure it out. \n    * FP16 testing for mobileNet drops about 0.2 mAP. \n\n- Add a demo.py file\n\n- Faster NMS (adopt official implementation)\n\n### COCO \n\n| System |  *test-dev mAP* | **Time** (V100) | **Time** (2080ti)|\n|:-------|:-----:|:-------:|:-------:|\n| [YOLOv3 608](http://pjreddie.com/darknet/yolo/) | 33.0 | 20ms| 26ms|\n| YOLOv3 608+ [BoFs](https://arxiv.org/abs/1902.04103) | 37.0 | 20ms | 26ms|\n| YOLOv3 608 (our baseline) | **38.8** | 20ms | 26ms|\n| YOLOv3 608+ ASFF | **40.6** | 22ms | 30ms| \n| YOLOv3 608+ ASFF\\* | **42.4** | 22ms | 30ms| \n| YOLOv3 800+ ASFF\\* | **43.9** | 34ms | 38ms| \n| YOLOv3 MobileNetV1 416 + [BoFs](https://arxiv.org/abs/1902.04103)| 28.6 | - | 22 ms| \n| YOLOv3 MobileNetV2 416 (our baseline) | 29.0 | - | 22 ms| \n| YOLOv3 MobileNetV2 416 +ASFF | **30.6** | - | 24 ms| \n\n\n### Citing \nPlease cite our paper in your publications if it helps your research:\n\n    @article{liu2019asff,\n        title = {Learning Spatial Fusion for Single-Shot Object Detection},\n        author = {Songtao Liu, Di Huang and Yunhong Wang},\n        booktitle = {arxiv preprint arXiv:1911.09516},\n        year = {2019}\n    }\n\n### Contents\n1. [Installation](#installation)\n2. [Datasets](#datasets)\n3. [Training](#training)\n4. [Evaluation](#evaluation)\n5. [Models](#models)\n\n## Installation\n- Install [PyTorch-1.3.1](http://pytorch.org/) by selecting your environment on the website and running the appropriate command.\n- Clone this repository. \n    * Note: We currently only support PyTorch-1.0.0+ and Python 3+.\n- Compile the DCN layer (ported from [DCNv2 implementation](https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0)):\n```Shell\n./make.sh\n```\n\n### Prerequisites\n- We also use [apex](https://github.com/NVIDIA/apex), numpy, opencv, tqdm, pyyaml, matplotlib, scikit-image...\n    * Note: We use apex for distributed training and synchronized batch normalization. For FP16 training, since the current apex version have some [issues](https://github.com/NVIDIA/apex/issues/318), we use the old version of FP16_Optimizer, and split the code in ./utils/fp_utils.\n\n- We also support tensorboard if you have installed it.   \n\n### Demo\n\n```Shell\npython demo.py -i /path/to/your/image \\\n--cfg config/yolov3_baseline.cfg -d COCO \\\n--checkpoint /path/to/you/weights --half --asff --rfb -s 608\n```\n- Note:\n  * -i, --img: image path.\n  * --cfg: config files.\n  * -d: choose datasets, COCO or VOC.\n  * -c, --checkpoint: pretrained weights.\n  * --half: FP16 testing.\n  * -s: evaluation image size, from 320 to 608 as in YOLOv3.\n\n\n## Datasets\nNote: We currently only support [COCO](http://mscoco.org/) and [VOC](http://host.robots.ox.ac.uk/pascal/VOC/).  \nTo make things easy, we provide simple COCO and VOC dataset loader that inherits `torch.utils.data.Dataset` making it fully compatible with the `torchvision.datasets` [API](http://pytorch.org/docs/torchvision/datasets.html).\n\nMoreover, we also implement the Mix-up strategy in [BoFs](https://arxiv.org/abs/1902.04103) and distributed random resizing in YOLov3.\n### COCO Dataset\nInstall the MS COCO dataset at /path/to/coco from [official website](http://mscoco.org/), default is ./data/COCO, and a soft-link is recommended. \n```\nln -s /path/to/coco ./data/COCO\n```\n\nIt should have this basic structure\n```Shell\n$COCO/\n$COCO/annotations/\n$COCO/images/\n$COCO/images/test2017/\n$COCO/images/train2017/\n$COCO/images/val2017/\n```\nThe current COCO dataset has released new *train2017* and *val2017* sets, and we defaultly train our model on *train2017* and evaluate on *val2017*. \n\n### VOC Dataset\nInstall the VOC dataset as ./data/VOC. We also recommend a soft-link:\n```\nln -s /path/to/VOCdevkit ./data/VOC\n```\n\n## Training\n\n- First download the mix-up pretrained [Darknet-53](https://arxiv.org/abs/1902.04103) PyTorch base network weights at: https://drive.google.com/open?id=1phqyYhV1K9KZLQZH1kENTAPprLBmymfP  \n  or from our [BaiduYun Driver](https://pan.baidu.com/s/19PaXl6p9vXHG2ZuGqtfLOg) \n\n- For MobileNetV2, we use the pytorch official [weights](https://drive.google.com/open?id=1LwMd9lK6YqGM8Yjf_ClBT2MG1-PHgUGa) (change the key name to fit our code), or from our [BaiduYun Driver](https://pan.baidu.com/s/12eScI6YNBvkVX0286cMEZA)\n\n- By default, we assume you have downloaded the file in the `ASFF/weights` dir:\n\n- Since random resizing consumes much more GPU memory, we implement FP16 training with an old version of apex. \n\n- We currently **ONLY** test the code with distributed training on multiple GPUs (10 2080ti or 4 Tesla V100).\n\n- To train YOLOv3 baseline (ours) using the train script simply specify the parameters listed in `main.py` as a flag or manually change them on config/yolov3_baseline.cfg:\n```Shell\npython -m torch.distributed.launch --nproc_per_node=10 --master_port=${RANDOM+10000} main.py \\\n--cfg config/yolov3_baseline.cfg -d COCO --tfboard --distributed --ngpu 10 \\\n--checkpoint weights/darknet53_feature_mx.pth --start_epoch 0 --half --log_dir log/COCO -s 608 \n```\n- Note:\n  * --cfg: config files.\n  * --tfboard: use tensorboard.\n  * --distributed: distributed training (we only test the code with distributed training)\n  * -d: choose datasets, COCO or VOC.\n  * --ngpu: number of GPUs.\n  * -c, --checkpoint: pretrained weights or resume weights. You can pick-up training from a checkpoint by specifying the path as one of the training parameters (again, see `main.py` for options)\n \n  * --start_epoch: used for resume training.\n  * --half: FP16 training.\n  * --log_dir: log dir for tensorboard.\n  * -s: evaluation image size, from 320 to 608 as in YOLOv3.\n\n- To train YOLOv3 with ASFF or ASFF\\*, you only need add some addional flags:\n```Shell\npython -m torch.distributed.launch --nproc_per_node=10 --master_port=${RANDOM+10000} main.py \\\n--cfg config/yolov3_baseline.cfg -d COCO --tfboard --distributed --ngpu 10 \\\n--checkpoint weights/darknet53_feature_mx.pth --start_epoch 0 --half --asff --rfb --dropblock \\\n--log_dir log/COCO_ASFF -s 608 \n```\n- Note:\n  * --asff: add ASFF module on YOLOv3.\n  * --rfb: use [RFB](https://github.com/ruinmessi/RFBNet) moduel on ASFF.\n  * --dropblock: use [DropBlock](https://arxiv.org/abs/1810.12890).\n  \n## Evaluation\nTo evaluate a trained network, you can use the following command:\n\n```Shell\npython -m torch.distributed.launch --nproc_per_node=10 --master_port=${RANDOM+10000} eval.py \\\n--cfg config/yolov3_baseline.cfg -d COCO --distributed --ngpu 10 \\\n--checkpoint /path/to/you/weights --half --asff --rfb -s 608\n```\n- Note:\n  * --vis: Visualization of ASFF.\n  * --testset: evaluate on COCO *test-dev*.\n  * -s: evaluation image size.\n\nBy default, it will directly output the mAP results on COCO *val2017* or VOC *test 2007*. \n\n## Models\n* yolov3 mobilenetv2 (ours)[weights](https://drive.google.com/open?id=1XGXJPXHIroimEuW8oujbInNapuEDALOB) [baiduYun](https://pan.baidu.com/s/100TivomBLDTRZSA1pkGiNA) [training tfboard log](https://pan.baidu.com/s/1P_00LAUvV-VOzxqoIxC_Yw)\n\n* yolov3 mobilenetv2 +asff [weights](https://drive.google.com/open?id=1cC-xGoaw3Wu5hYd3iXEq6xrAn4U_dW-w) [baiduYun](https://pan.baidu.com/s/1JxX8mYkljk1ap2s4zpLrSg) [training tfboard log](https://pan.baidu.com/s/1R2YL9uZ9baQWR6aht0qVlQ)\n\n* yolov3_baseline (ours) [weights](https://drive.google.com/open?id=1RbjUQbNxl4cEbk-6jFkFnOHRukJY5EQk) [baiduYun](https://pan.baidu.com/s/131JhlaOBbeL9l4tqiJO9yA) [training tfboard log](https://pan.baidu.com/s/1GcpVnq7mhIsrk8zrJ9FF2g)\n\n* yolov3_asff [weights](https://drive.google.com/open?id=1Dyf8ZEga_VT2O3_c5nrFJA5uON1aSJK-) [baiduYun](https://pan.baidu.com/s/1a-eQZ0kDpsnUooD4RtRdxg) [training tfboard log](https://pan.baidu.com/s/1MeMkAWwv1SFsVbvsTpj_xQ)\n\n* yolov3_asff\\* (320-608) [weights](https://drive.google.com/open?id=1N668Za8OBbJbUStYde0ml9SZdM7tabXy) [baiduYun](https://pan.baidu.com/s/1d9hOQBj20HCy51qWbonxMQ)\n\n* yolov3_asff\\* (480-800) [weights](https://drive.google.com/open?id=18N4_nNVqYbjawerEHQnwJGPcRvcLOe06) [baiduYun](https://pan.baidu.com/s/1HERhiP4vmUekxxm5KQrX8g)\n\n\n"
  },
  {
    "path": "config/yolov3_baseline.cfg",
    "content": "MODEL:\n  TYPE: YOLOv3\n  BACKBONE: darknet53\nTRAIN:\n  LR: 0.001\n  MOMENTUM: 0.9\n  DECAY: 0.0005\n  BURN_IN: 5\n  MAXEPOCH: 300\n  COS: True\n  SYBN: True\n  MIX: True\n  NO_MIXUP_EPOCHS: 30\n  LABAL_SMOOTH: True\n  BATCHSIZE: 5\n  IMGSIZE: 608\n  IGNORETHRE: 0.7\n  RANDRESIZE: True\nTEST:\n  CONFTHRE: 0.01\n  NMSTHRE: 0.65\n  IMGSIZE: 608\n"
  },
  {
    "path": "config/yolov3_mobile.cfg",
    "content": "MODEL:\n  TYPE: YOLOv3\n  BACKBONE: mobile\nTRAIN:\n  LR: 0.001\n  MOMENTUM: 0.9\n  DECAY: 0.0005\n  BURN_IN: 5\n  MAXEPOCH: 300\n  COS: True\n  SYBN: True\n  MIX: True\n  NO_MIXUP_EPOCHS: 30\n  LABAL_SMOOTH: True\n  BATCHSIZE: 8\n  IMGSIZE: 416\n  IGNORETHRE: 0.7\n  RANDRESIZE: True\nTEST:\n  CONFTHRE: 0.001\n  NMSTHRE: 0.65\n"
  },
  {
    "path": "dataset/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n\n\n"
  },
  {
    "path": "dataset/cocodataset.py",
    "content": "import os\nimport numpy as np\n\nimport torch\nfrom .dataloading import Dataset\nimport cv2\nfrom pycocotools.coco import COCO\n\nfrom utils.utils import *\n\nCOCO_CLASSES=(\n'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck',\n'boat', 'traffic light', 'fire hydrant', 'street sign', 'stop sign',\n'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',\n'elephant', 'bear', 'zebra', 'giraffe', 'hat', 'backpack', 'umbrella',\n'shoe', 'eye glasses', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis',\n'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove',\n'skateboard', 'surfboard', 'tennis racket', 'bottle', 'plate', 'wine glass',\n'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich',\n'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair',\n'couch', 'potted plant', 'bed', 'mirror', 'dining table', 'window', 'desk',\n'toilet', 'door', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',\n'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'blender', 'book',\n'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush')\n\n\nclass COCODataset(Dataset):\n    \"\"\"\n    COCO dataset class.\n    \"\"\"\n    def __init__(self, data_dir='data/COCO', json_file='instances_train2017.json',\n                 name='train2017', img_size=(416,416), preproc=None, debug=False, voc=False):\n        \"\"\"\n        COCO dataset initialization. Annotation data are read into memory by COCO API.\n        Args:\n            data_dir (str): dataset root directory\n            json_file (str): COCO json file name\n            name (str): COCO data name (e.g. 'train2017' or 'val2017')\n            img_size (int): target image size after pre-processing\n            preproc: data augmentation strategy\n            debug (bool): if True, only one data id is selected from the dataset\n        \"\"\"\n        super().__init__(img_size)\n        self.data_dir = data_dir\n        self.json_file = json_file\n        self.voc = voc\n        if voc:\n            self.coco = COCO(self.data_dir+'VOC2007/Annotations/'+self.json_file)\n        else:\n            self.coco = COCO(self.data_dir+'annotations/'+self.json_file)\n        self.ids = self.coco.getImgIds()\n        if debug:\n            self.ids = self.ids[1:2]\n            print(\"debug mode...\", self.ids)\n        self.class_ids = sorted(self.coco.getCatIds())\n        cats = self.coco.loadCats(self.coco.getCatIds())\n        self._classes = tuple([c['name'] for c in cats])\n        self.name = name\n        self.max_labels = 50\n        self.img_size = img_size\n        self.preproc = preproc\n\n    def __len__(self):\n        return len(self.ids)\n\n    def pull_item(self, index):\n\n        id_ = self.ids[index]\n\n        im_ann = self.coco.loadImgs(id_)[0]\n        width = im_ann['width']\n        height = im_ann['height']\n        anno_ids = self.coco.getAnnIds(imgIds=[int(id_)], iscrowd=None)\n        annotations = self.coco.loadAnns(anno_ids)\n\n        # load image and preprocess\n        img_file = os.path.join(self.data_dir, 'images', self.name,\n                                #'COCO_'+self.name+'_'+'{:012}'.format(id_) + '.jpg')\n                                '{:012}'.format(id_) + '.jpg')\n\n        if self.voc:\n            file_name = im_ann['file_name']\n            img_file = os.path.join(self.data_dir, 'VOC2007', 'JPEGImages',\n                                file_name)\n\n        img = cv2.imread(img_file)\n\n        if self.json_file == 'instances_val5k.json' and img is None:\n            img_file = os.path.join(self.data_dir, 'images', 'train2017',\n                                    '{:012}'.format(id_) + '.jpg')\n            img = cv2.imread(img_file)\n        assert img is not None\n\n        #img, info_img = preprocess(img, self.input_dim[0])\n\n        # load labels\n        valid_objs = []\n        for obj in annotations:\n            x1 = np.max((0, obj['bbox'][0]))\n            y1 = np.max((0, obj['bbox'][1]))\n            x2 = np.min((width - 1, x1 + np.max((0, obj['bbox'][2] - 1))))\n            y2 = np.min((height - 1, y1 + np.max((0, obj['bbox'][3] - 1))))\n            if obj['area'] > 0 and x2 >= x1 and y2 >= y1:\n                obj['clean_bbox'] = [x1, y1, x2, y2]\n                valid_objs.append(obj)\n        objs = valid_objs\n        num_objs = len(objs)\n\n        res = np.zeros((num_objs, 5))\n\n        for ix, obj in enumerate(objs):\n            cls = self.class_ids.index(obj['category_id'])\n            res[ix, 0:4] = obj['clean_bbox']\n            res[ix, 4] = cls\n\n        img_info = (width, height)\n\n        return img, res, img_info, id_\n\n    @Dataset.resize_getitem\n    def __getitem__(self, index):\n        \"\"\"\n        One image / label pair for the given index is picked up \\\n        and pre-processed.\n        Args:\n            index (int): data index\n        Returns:\n            img (numpy.ndarray): pre-processed image\n            padded_labels (torch.Tensor): pre-processed label data. \\\n                The shape is :math:`[self.max_labels, 5]`. \\\n                each label consists of [class, xc, yc, w, h]:\n                    class (float): class index.\n                    xc, yc (float) : center of bbox whose values range from 0 to 1.\n                    w, h (float) : size of bbox whose values range from 0 to 1.\n            info_img : tuple of h, w, nh, nw, dx, dy.\n                h, w (int): original shape of the image\n                nh, nw (int): shape of the resized image without padding\n                dx, dy (int): pad size\n            id_ (int): same as the input index. Used for evaluation.\n        \"\"\"\n        img, res, img_info, id_ = self.pull_item(index)\n\n        if self.preproc is not None:\n            img, target = self.preproc(img, res, self.input_dim)\n\n\n        return img, target, img_info, id_\n"
  },
  {
    "path": "dataset/data_augment.py",
    "content": "\"\"\"Data augmentation functionality. Passed as callable transformations to\nDataset classes.\n\nThe data augmentation procedures were interpreted from @weiliu89's SSD paper\nhttp://arxiv.org/abs/1512.02325\n\"\"\"\n\nimport torch\nfrom torchvision import transforms\nimport cv2\nimport numpy as np\nimport random\nimport math\nfrom utils.utils import matrix_iou, visual\n\n#DEBUG = True\nDEBUG = False\n\ndef _crop(image, boxes, labels, ratios = None):\n    height, width, _ = image.shape\n\n    if len(boxes)== 0:\n        return image, boxes, labels, ratios\n\n    while True:\n        mode = random.choice((\n            None,\n            (0.1, None),\n            (0.3, None),\n            (0.5, None),\n            (0.7, None),\n            (0.9, None),\n            (None, None),\n        ))\n\n        if mode is None:\n            return image, boxes, labels, ratios\n\n        min_iou, max_iou = mode\n        if min_iou is None:\n            min_iou = float('-inf')\n        if max_iou is None:\n            max_iou = float('inf')\n\n        for _ in range(50):\n            scale = random.uniform(0.3,1.)\n            min_ratio = max(0.5, scale*scale)\n            max_ratio = min(2, 1. / scale / scale)\n            ratio = math.sqrt(random.uniform(min_ratio, max_ratio))\n            w = int(scale * ratio * width)\n            h = int((scale / ratio) * height)\n\n\n            l = random.randrange(width - w)\n            t = random.randrange(height - h)\n            roi = np.array((l, t, l + w, t + h))\n\n            iou = matrix_iou(boxes, roi[np.newaxis])\n\n            if not (min_iou <= iou.min() and iou.max() <= max_iou):\n                continue\n\n            image_t = image[roi[1]:roi[3], roi[0]:roi[2]]\n\n            centers = (boxes[:, :2] + boxes[:, 2:]) / 2\n            mask = np.logical_and(roi[:2] < centers, centers < roi[2:]) \\\n                     .all(axis=1)\n            boxes_t = boxes[mask].copy()\n            labels_t = labels[mask].copy()\n            if ratios is not None:\n                ratios_t = ratios[mask].copy()\n            else:\n                ratios_t=None\n\n            if len(boxes_t) == 0:\n                continue\n\n            boxes_t[:, :2] = np.maximum(boxes_t[:, :2], roi[:2])\n            boxes_t[:, :2] -= roi[:2]\n            boxes_t[:, 2:] = np.minimum(boxes_t[:, 2:], roi[2:])\n            boxes_t[:, 2:] -= roi[:2]\n\n            return image_t, boxes_t,labels_t, ratios_t\n\n\ndef _distort(image):\n    def _convert(image, alpha=1, beta=0):\n        tmp = image.astype(float) * alpha + beta\n        tmp[tmp < 0] = 0\n        tmp[tmp > 255] = 255\n        image[:] = tmp\n\n    image = image.copy()\n\n    if random.randrange(2):\n        _convert(image, beta=random.uniform(-32, 32))\n\n    if random.randrange(2):\n        _convert(image, alpha=random.uniform(0.5, 1.5))\n\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n\n    if random.randrange(2):\n        tmp = image[:, :, 0].astype(int) + random.randint(-18, 18)\n        tmp %= 180\n        image[:, :, 0] = tmp\n\n    if random.randrange(2):\n        _convert(image[:, :, 1], alpha=random.uniform(0.5, 1.5))\n\n    image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)\n\n    return image\n\n\ndef _expand(image, boxes,fill, p):\n    if random.random() > p:\n        return image, boxes\n\n    height, width, depth = image.shape\n    for _ in range(50):\n        scale = random.uniform(1,4)\n\n        min_ratio = max(0.5, 1./scale/scale)\n        max_ratio = min(2, scale*scale)\n        ratio = math.sqrt(random.uniform(min_ratio, max_ratio))\n        ws = scale*ratio\n        hs = scale/ratio\n        if ws < 1 or hs < 1:\n            continue\n        w = int(ws * width)\n        h = int(hs * height)\n\n        left = random.randint(0, w - width)\n        top = random.randint(0, h - height)\n\n        boxes_t = boxes.copy()\n        boxes_t[:, :2] += (left, top)\n        boxes_t[:, 2:] += (left, top)\n\n\n        expand_image = np.empty(\n            (h, w, depth),\n            dtype=image.dtype)\n        expand_image[:, :] = fill\n        expand_image[top:top + height, left:left + width] = image\n        image = expand_image\n\n        return image, boxes_t\n\n\ndef _mirror(image, boxes):\n    _, width, _ = image.shape\n    if random.randrange(2):\n        image = image[:, ::-1]\n        boxes = boxes.copy()\n        boxes[:, 0::2] = width - boxes[:, 2::-2]\n    return image, boxes\n\n\ndef _random_affine(img, targets=None, degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-2, 2),\n                  borderValue=(127.5, 127.5, 127.5)):\n    # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))\n    # https://medium.com/uruvideo/dataset-augmentation-with-random-homographies-a8f4b44830d4\n\n    border = 0  # width of added border (optional)\n    #height = max(img.shape[0], img.shape[1]) + border * 2\n    height, width, _ = img.shape \n\n    # Rotation and Scale\n    R = np.eye(3)\n    a = random.random() * (degrees[1] - degrees[0]) + degrees[0]\n    # a += random.choice([-180, -90, 0, 90])  # 90deg rotations added to small rotations\n    s = random.random() * (scale[1] - scale[0]) + scale[0]\n    R[:2] = cv2.getRotationMatrix2D(angle=a, center=(img.shape[1] / 2, img.shape[0] / 2), scale=s)\n\n    # Translation\n    T = np.eye(3)\n    T[0, 2] = (random.random() * 2 - 1) * translate[0] * img.shape[0] + border  # x translation (pixels)\n    T[1, 2] = (random.random() * 2 - 1) * translate[1] * img.shape[1] + border  # y translation (pixels)\n\n    # Shear\n    S = np.eye(3)\n    S[0, 1] = math.tan((random.random() * (shear[1] - shear[0]) + shear[0]) * math.pi / 180)  # x shear (deg)\n    S[1, 0] = math.tan((random.random() * (shear[1] - shear[0]) + shear[0]) * math.pi / 180)  # y shear (deg)\n\n    M = S @ T @ R  # Combined rotation matrix. ORDER IS IMPORTANT HERE!!\n    imw = cv2.warpPerspective(img, M, dsize=(width, height), flags=cv2.INTER_LINEAR,\n                              borderValue=borderValue)  # BGR order borderValue\n\n    # Return warped points also\n    if targets is not None:\n        if len(targets) > 0:\n            n = targets.shape[0]\n            points = targets[:, 0:4].copy()\n            area0 = (points[:, 2] - points[:, 0]) * (points[:, 3] - points[:, 1])\n\n            # warp points\n            xy = np.ones((n * 4, 3))\n            xy[:, :2] = points[:, [0, 1, 2, 3, 0, 3, 2, 1]].reshape(n * 4, 2)  # x1y1, x2y2, x1y2, x2y1\n            xy = (xy @ M.T)[:, :2].reshape(n, 8)\n\n            # create new boxes\n            x = xy[:, [0, 2, 4, 6]]\n            y = xy[:, [1, 3, 5, 7]]\n            xy = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T\n\n            # apply angle-based reduction\n            radians = a * math.pi / 180\n            reduction = max(abs(math.sin(radians)), abs(math.cos(radians))) ** 0.5\n            x = (xy[:, 2] + xy[:, 0]) / 2\n            y = (xy[:, 3] + xy[:, 1]) / 2\n            w = (xy[:, 2] - xy[:, 0]) * reduction\n            h = (xy[:, 3] - xy[:, 1]) * reduction\n            xy = np.concatenate((x - w / 2, y - h / 2, x + w / 2, y + h / 2)).reshape(4, n).T\n\n            # reject warped points outside of image\n            x1 = np.clip(xy[:,0], 0, width)\n            y1 = np.clip(xy[:,1], 0, height)\n            x2 = np.clip(xy[:,2], 0, width)\n            y2 = np.clip(xy[:,3], 0, height)\n            boxes = np.concatenate((x1, y1, x2, y2)).reshape(4, n).T\n\n        return imw, boxes, M\n    else:\n        return imw\n\ndef preproc_for_test(image, input_size, mean, std):\n    interp_methods = [cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_NEAREST, cv2.INTER_LANCZOS4]\n    interp_method = interp_methods[random.randrange(5)]\n    image = cv2.resize(image, input_size,interpolation=interp_method)\n    image = image.astype(np.float32)\n    image = image[:,:,::-1]\n    image /= 255.\n    if mean is not None:\n        image -= mean\n    if std is not None:\n        image /= std\n    return image.transpose(2, 0, 1)\n\n\nclass TrainTransform(object):\n\n    def __init__(self, p=0.5, rgb_means=None, std = None,max_labels=50):\n        self.means = rgb_means\n        self.std = std\n        self.p = p\n        self.max_labels=max_labels\n\n    def __call__(self, image, targets, input_dim):\n        boxes = targets[:,:4].copy()\n        labels = targets[:,4].copy()\n        if targets.shape[1] > 5:\n            mixup=True\n            ratios = targets[:,-1].copy()\n            ratios_o = targets[:,-1].copy()\n        else:\n            mixup=False\n            ratios = None\n            ratios_o = None\n        lshape = 6 if mixup else 5\n        if len(boxes) == 0:\n            targets = np.zeros((self.max_labels,lshape),dtype=np.float32)\n            image = preproc_for_test(image, input_dim, self.means, self.std)\n            image = np.ascontiguousarray(image, dtype=np.float32)\n            return torch.from_numpy(image), torch.from_numpy(targets)\n\n        image_o = image.copy()\n        targets_o = targets.copy()\n        height_o, width_o, _ = image_o.shape\n        boxes_o = targets_o[:,:4]\n        labels_o = targets_o[:,4]\n        b_x_o = (boxes_o[:, 2] + boxes_o[:, 0])*.5\n        b_y_o = (boxes_o[:, 3] + boxes_o[:, 1])*.5\n        b_w_o = (boxes_o[:, 2] - boxes_o[:, 0])*1.\n        b_h_o = (boxes_o[:, 3] - boxes_o[:, 1])*1.\n        boxes_o[:,0] = b_x_o\n        boxes_o[:,1] = b_y_o\n        boxes_o[:,2] = b_w_o\n        boxes_o[:,3] = b_h_o\n        boxes_o[:, 0::2] /= width_o\n        boxes_o[:, 1::2] /= height_o\n        boxes_o[:, 0::2] *= input_dim[0]\n        boxes_o[:, 1::2] *= input_dim[1]\n        #labels_o = np.expand_dims(labels_o,1)\n        #targets_o = np.hstack((boxes_o,labels_o))\n        #targets_o = np.hstack((labels_o,boxes_o))\n\n        image_t = _distort(image)\n        if self.means is not None:\n            fill = [m * 255 for m in self.means]\n            fill = fill[::-1]\n        else:\n            fill = (127.5,127.5,127.5)\n        image_t, boxes = _expand(image_t, boxes, fill, self.p)\n        image_t, boxes, labels, ratios = _crop(image_t, boxes, labels, ratios)\n        image_t, boxes = _mirror(image_t, boxes)\n\n        if random.randrange(2):\n            image_t, boxes, _ = _random_affine(image_t, boxes, borderValue=fill)\n\n        height, width, _ = image_t.shape\n\n        if DEBUG:\n            image_t = np.ascontiguousarray(image_t, dtype=np.uint8)\n            img = visual(image_t, boxes,labels) \n            cv2.imshow('DEBUG', img)\n            cv2.waitKey(0)\n\n        image_t = preproc_for_test(image_t, input_dim, self.means, self.std)\n        boxes  = boxes.copy()\n        b_x = (boxes[:, 2] + boxes[:, 0])*.5\n        b_y = (boxes[:, 3] + boxes[:, 1])*.5\n        b_w = (boxes[:, 2] - boxes[:, 0])*1.\n        b_h = (boxes[:, 3] - boxes[:, 1])*1.\n        boxes[:,0] = b_x\n        boxes[:,1] = b_y\n        boxes[:,2] = b_w\n        boxes[:,3] = b_h\n        boxes[:, 0::2] /= width\n        boxes[:, 1::2] /= height\n        boxes[:, 0::2] *= input_dim[0]\n        boxes[:, 1::2] *= input_dim[1]\n        mask_b= np.minimum(boxes[:,2], boxes[:,3]) > 6\n        #mask_b= (boxes[:,2]*boxes[:,3]) > 32**2\n        #mask_b= (boxes[:,2]*boxes[:,3]) > 48**2\n        boxes_t = boxes[mask_b]\n        labels_t = labels[mask_b].copy()\n        if mixup:\n            ratios_t = ratios[mask_b].copy()\n\n        '''\n        if len(boxes_t)==0:\n            targets = np.zeros((self.max_labels,lshape),dtype=np.float32)\n            image = preproc_for_test(image_o, input_dim, self.means, self.std)\n            image = np.ascontiguousarray(image, dtype=np.float32)\n            return torch.from_numpy(image), torch.from_numpy(targets)\n        '''\n        #if len(boxes_t)==0 or random.random() > 0.97:\n        if len(boxes_t)==0:\n            image_t = preproc_for_test(image_o, input_dim, self.means, self.std)\n            boxes_t = boxes_o\n            labels_t = labels_o\n            ratios_t = ratios_o\n\n        labels_t = np.expand_dims(labels_t,1)\n        if mixup:\n            ratios_t = np.expand_dims(ratios_t,1)\n            targets_t = np.hstack((labels_t,boxes_t,ratios_t))\n        else:\n            targets_t = np.hstack((labels_t,boxes_t))\n        padded_labels = np.zeros((self.max_labels,lshape))\n        padded_labels[range(len(targets_t))[:self.max_labels]] = targets_t[:self.max_labels]\n        padded_labels = np.ascontiguousarray(padded_labels, dtype=np.float32)\n        image_t = np.ascontiguousarray(image_t, dtype=np.float32)\n\n        return torch.from_numpy(image_t), torch.from_numpy(padded_labels)\n\n\n\nclass ValTransform(object):\n    \"\"\"Defines the transformations that should be applied to test PIL image\n        for input into the network\n\n    dimension -> tensorize -> color adj\n\n    Arguments:\n        resize (int): input dimension to SSD\n        rgb_means ((int,int,int)): average RGB of the dataset\n            (104,117,123)\n        swap ((int,int,int)): final order of channels\n    Returns:\n        transform (transform) : callable transform to be applied to test/val\n        data\n    \"\"\"\n    def __init__(self, rgb_means=None, std=None, swap=(2, 0, 1)):\n        self.means = rgb_means\n        self.swap = swap\n        self.std=std\n\n    # assume input is cv2 img for now\n    def __call__(self, img, res, input_size):\n\n        interp_methods = [cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_NEAREST, cv2.INTER_LANCZOS4]\n        interp_method = interp_methods[0]\n        img = cv2.resize(np.array(img), input_size,\n                        interpolation = interp_method).astype(np.float32)\n        img = img[:,:,::-1]\n        img /= 255.\n        if self.means is not None:\n            img -= self.means\n        if self.std is not None:\n            img /= self.std\n        img = img.transpose(self.swap)\n        img = np.ascontiguousarray(img, dtype=np.float32)\n        return torch.from_numpy(img), torch.zeros(1,5)\n"
  },
  {
    "path": "dataset/dataloading.py",
    "content": "import random\nimport logging\nfrom functools import wraps\nimport torch\nfrom torch.utils.data.dataset import Dataset as torchDataset\nfrom torch.utils.data.sampler import BatchSampler as torchBatchSampler\nfrom torch.utils.data.dataloader import DataLoader as torchDataLoader\nfrom torch.utils.data.dataloader import default_collate\n\n\nlog = logging.getLogger(__name__)\n\n\nclass Dataset(torchDataset):\n    \"\"\" This class is a subclass of the base :class:`torch.utils.data.Dataset`,\n    that enables on the fly resizing of the ``input_dim`` with a :class:`lightnet.data.DataLoader`.\n\n    Args:\n        input_dimension (tuple): (width,height) tuple with default dimensions of the network\n    \"\"\"\n    def __init__(self, input_dimension):\n        super().__init__()\n        self.__input_dim = input_dimension[:2]\n\n    @property\n    def input_dim(self):\n        \"\"\" Dimension that can be used by transforms to set the correct image size, etc.\n        This allows transforms to have a single source of truth for the input dimension of the network.\n\n        Return:\n            list: Tuple containing the current width,height\n        \"\"\"\n        if hasattr(self, '_input_dim'):\n            return self._input_dim\n        return self.__input_dim\n\n    @staticmethod\n    def resize_getitem(getitem_fn):\n        \"\"\" Decorator method that needs to be used around the ``__getitem__`` method. |br|\n        This decorator enables the on the fly resizing  of the ``input_dim`` with our :class:`~lightnet.data.DataLoader` class.\n\n        Example:\n            >>> class CustomSet(ln.data.Dataset):\n            ...     def __len__(self):\n            ...         return 10\n            ...     @ln.data.Dataset.resize_getitem\n            ...     def __getitem__(self, index):\n            ...         # Should return (image, anno) but here we return input_dim\n            ...         return self.input_dim\n            >>> data = CustomSet((200,200))\n            >>> data[0]\n            (200, 200)\n            >>> data[(480,320), 0]\n            (480, 320)\n        \"\"\"\n        @wraps(getitem_fn)\n        def wrapper(self, index):\n            if not isinstance(index, int):\n                has_dim = True\n                self._input_dim = index[0]\n                index = index[1]\n            else:\n                has_dim = False\n\n            ret_val = getitem_fn(self, index)\n\n            if has_dim:\n                del self._input_dim\n\n            return ret_val\n\n        return wrapper\n\n\nclass DataLoader(torchDataLoader):\n    \"\"\" Lightnet dataloader that enables on the fly resizing of the images.\n    See :class:`torch.utils.data.DataLoader` for more information on the arguments.\n\n    Note:\n        This dataloader only works with :class:`lightnet.data.Dataset` based datasets.\n\n    Example:\n        >>> class CustomSet(ln.data.Dataset):\n        ...     def __len__(self):\n        ...         return 4\n        ...     @ln.data.Dataset.resize_getitem\n        ...     def __getitem__(self, index):\n        ...         # Should return (image, anno) but here we return (input_dim,)\n        ...         return (self.input_dim,)\n        >>> dl = ln.data.DataLoader(\n        ...     CustomSet((200,200)),\n        ...     batch_size = 2,\n        ...     collate_fn = ln.data.list_collate   # We want the data to be grouped as a list\n        ... )\n        >>> dl.dataset.input_dim    # Default input_dim\n        (200, 200)\n        >>> for d in dl:\n        ...     d\n        [[(200, 200), (200, 200)]]\n        [[(200, 200), (200, 200)]]\n        >>> dl.change_input_dim(320, random_range=None)\n        (320, 320)\n        >>> for d in dl:\n        ...     d\n        [[(320, 320), (320, 320)]]\n        [[(320, 320), (320, 320)]]\n        >>> dl.change_input_dim((480, 320), random_range=None)\n        (480, 320)\n        >>> for d in dl:\n        ...     d\n        [[(480, 320), (480, 320)]]\n        [[(480, 320), (480, 320)]]\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.__initialized = False\n        shuffle = False\n        batch_sampler = None\n        if len(args) > 5:\n            shuffle = args[2]\n            sampler = args[3]\n            batch_sampler = args[4]\n        elif len(args) > 4:\n            shuffle = args[2]\n            sampler = args[3]\n            if 'batch_sampler' in kwargs:\n                batch_sampler = kwargs['batch_sampler']\n        elif len(args) > 3:\n            shuffle = args[2]\n            if 'sampler' in kwargs:\n                sampler = kwargs['sampler']\n            if 'batch_sampler' in kwargs:\n                batch_sampler = kwargs['batch_sampler']\n        else:\n            if 'shuffle' in kwargs:\n                shuffle = kwargs['shuffle']\n            if 'sampler' in kwargs:\n                sampler = kwargs['sampler']\n            if 'batch_sampler' in kwargs:\n                batch_sampler = kwargs['batch_sampler']\n\n        # Use custom BatchSampler\n        if batch_sampler is None:\n            if sampler is None:\n                if shuffle:\n                    sampler = torch.utils.data.sampler.RandomSampler(self.dataset)\n                    #sampler = torch.utils.data.DistributedSampler(self.dataset)\n                else:\n                    sampler = torch.utils.data.sampler.SequentialSampler(self.dataset)\n            batch_sampler = YoloBatchSampler(sampler, self.batch_size, self.drop_last, input_dimension=self.dataset.input_dim)\n            #batch_sampler = IterationBasedBatchSampler(batch_sampler, num_iterations = \n\n        self.batch_sampler = batch_sampler\n\n        self.__initialized = True\n\n    def change_input_dim(self, multiple=32, random_range=(10, 19)):\n        \"\"\" This function will compute a new size and update it on the next mini_batch.\n\n        Args:\n            multiple (int or tuple, optional): value (or values) to multiply the randomly generated range by; Default **32**\n            random_range (tuple, optional): This (min, max) tuple sets the range for the randomisation; Default **(10, 19)**\n\n        Return:\n            tuple: width, height tuple with new dimension\n\n        Note:\n            The new size is generated as follows: |br|\n            First we compute a random integer inside ``[random_range]``.\n            We then multiply that number with the ``multiple`` argument, which gives our final new input size. |br|\n            If ``multiple`` is an integer we generate a square size. If you give a tuple of **(width, height)**,\n            the size is computed as :math:`rng * multiple[0], rng * multiple[1]`.\n\n        Note:\n            You can set the ``random_range`` argument to **None** to set an exact size of multiply. |br|\n            See the example above for how this works.\n        \"\"\"\n        if random_range is None:\n            size = 1\n        else:\n            size = random.randint(*random_range)\n\n        if isinstance(multiple, int):\n            size = (size * multiple, size * multiple)\n        else:\n            size = (size * multiple[0], size * multiple[1])\n\n        self.batch_sampler.new_input_dim = size\n\n        return size\n\n\nclass YoloBatchSampler(torchBatchSampler):\n    \"\"\" This batch sampler will generate mini-batches of (dim, index) tuples from another sampler.\n    It works just like the :class:`torch.utils.data.sampler.BatchSampler`, but it will prepend a dimension,\n    whilst ensuring it stays the same across one mini-batch.\n    \"\"\"\n    def __init__(self, *args, input_dimension=None, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.input_dim = input_dimension\n        self.new_input_dim = None\n\n    def __iter__(self):\n        self.__set_input_dim()\n        for batch in super().__iter__():\n            yield [(self.input_dim, idx) for idx in batch]\n            self.__set_input_dim()\n\n    def __set_input_dim(self):\n        \"\"\" This function randomly changes the the input dimension of the dataset. \"\"\"\n        if self.new_input_dim is not None:\n            log.info(f'Resizing network {self.new_input_dim[:2]}')\n            self.input_dim = (self.new_input_dim[0], self.new_input_dim[1])\n            self.new_input_dim = None\n\nclass IterationBasedBatchSampler(torchBatchSampler):\n    \"\"\"\n    Wraps a BatchSampler, resampling from it until\n    a specified number of iterations have been sampled\n    \"\"\"\n\n    def __init__(self, batch_sampler, num_iterations, start_iter=0):\n        self.batch_sampler = batch_sampler\n        self.num_iterations = num_iterations\n        self.start_iter = start_iter\n\n    def __iter__(self):\n        iteration = self.start_iter\n        while iteration <= self.num_iterations:\n            # if the underlying sampler has a set_epoch method, like\n            # DistributedSampler, used for making each process see\n            # a different split of the dataset, then set it\n            if hasattr(self.batch_sampler.sampler, \"set_epoch\"):\n                self.batch_sampler.sampler.set_epoch(iteration)\n            for batch in self.batch_sampler:\n                iteration += 1\n                if iteration > self.num_iterations:\n                    break\n                yield batch\n\n    def __len__(self):\n        return self.num_iterations\n\ndef list_collate(batch):\n    \"\"\" Function that collates lists or tuples together into one list (of lists/tuples).\n    Use this as the collate function in a Dataloader, if you want to have a list of items as an output, as opposed to tensors (eg. Brambox.boxes).\n    \"\"\"\n    items = list(zip(*batch))\n\n    for i in range(len(items)):\n        if isinstance(items[i][0], (list, tuple)):\n            items[i] = list(items[i])\n        else:\n            items[i] = default_collate(items[i])\n\n    return items\n\n"
  },
  {
    "path": "dataset/mixupdetection.py",
    "content": "\"\"\"Mixup detection dataset wrapper.\"\"\"\nfrom __future__ import absolute_import\nimport numpy as np\nimport torch\n#from mxnet.gluon.data import Dataset\nfrom .dataloading import Dataset\n\n\nclass MixupDetection(Dataset):\n    \"\"\"Detection dataset wrapper that performs mixup for normal dataset.\n    Parameters\n    ----------\n    dataset : mx.gluon.data.Dataset\n        Gluon dataset object.\n    mixup : callable random generator, e.g. np.random.uniform\n        A random mixup ratio sampler, preferably a random generator from numpy.random\n        A random float will be sampled each time with mixup(*args).\n        Use None to disable.\n    *args : list\n        Additional arguments for mixup random sampler.\n    \"\"\"\n    def __init__(self, dataset, mixup=None, preproc=None, *args):\n        super().__init__(dataset.input_dim)\n        self._dataset = dataset\n        self.preproc = preproc\n        self._mixup = mixup\n        self._mixup_args = args\n\n    def set_mixup(self, mixup=None, *args):\n        \"\"\"Set mixup random sampler, use None to disable.\n        Parameters\n        ----------\n        mixup : callable random generator, e.g. np.random.uniform\n            A random mixup ratio sampler, preferably a random generator from numpy.random\n            A random float will be sampled each time with mixup(*args)\n        *args : list\n            Additional arguments for mixup random sampler.\n        \"\"\"\n        self._mixup = mixup\n        self._mixup_args = args\n\n    def __len__(self):\n        return len(self._dataset)\n\n    @Dataset.resize_getitem\n    def __getitem__(self, idx):\n        self._dataset._input_dim = self.input_dim\n        # first image\n        img1, label1, _, _= self._dataset.pull_item(idx)\n        lambd = 1\n\n        # draw a random lambda ratio from distribution\n        if self._mixup is not None:\n            lambd = max(0, min(1, self._mixup(*self._mixup_args)))\n\n        if lambd >= 1:\n            weights1 = np.ones((label1.shape[0], 1))\n            label1 = np.hstack((label1, weights1))\n            height, width, _ = img1.shape\n            img_info = (width, height)\n            if self.preproc is not None:\n                img_o, target_o = self.preproc(img1, label1, self.input_dim)\n            return img_o, target_o, img_info, idx\n\n        # second image\n        idx2 = int(np.random.choice(np.delete(np.arange(len(self)), idx)))\n        img2, label2, _, _ = self._dataset.pull_item(idx2)\n\n        # mixup two images\n        height = max(img1.shape[0], img2.shape[0])\n        width = max(img1.shape[1], img2.shape[1])\n        mix_img = np.zeros((height, width, 3),dtype=np.float32)\n        mix_img[:img1.shape[0], :img1.shape[1], :] = img1.astype(np.float32) * lambd\n        mix_img[:img2.shape[0], :img2.shape[1], :] += img2.astype(np.float32) * (1. - lambd)\n        mix_img = mix_img.astype(np.uint8)\n\n        y1 = np.hstack((label1, np.full((label1.shape[0], 1), lambd)))\n        y2 = np.hstack((label2, np.full((label2.shape[0], 1), 1. - lambd)))\n        mix_label = np.vstack((y1, y2))\n        if self.preproc is not None:\n            mix_img, padded_labels = self.preproc(mix_img, mix_label, self.input_dim)\n\n        img_info = (width, height)\n\n        return mix_img, padded_labels, img_info , idx\n\n    def pull_item(self, idx):\n        self._dataset._input_dim = self.input_dim\n        # first image\n        img1, label1, _, _= self._dataset.pull_item(idx)\n        lambd = 1\n\n        # draw a random lambda ratio from distribution\n        if self._mixup is not None:\n            lambd = max(0, min(1, self._mixup(*self._mixup_args)))\n\n        if lambd >= 1:\n            weights1 = np.ones((label1.shape[0], 1))\n            label1 = np.hstack((label1, weights1))\n            height, width, _ = img1.shape\n            img_info = (width, height)\n            if self.preproc is not None:\n                img_o, target_o = self.preproc(img1, label1, self.input_dim)\n            return img_o, target_o, img_info, idx\n\n        # second image\n        idx2 = int(np.random.choice(np.delete(np.arange(len(self)), idx)))\n        img2, label2 = self._dataset.pull_item(idx2)\n\n        # mixup two images\n        height = max(img1.shape[0], img2.shape[0])\n        width = max(img1.shape[1], img2.shape[1])\n        mix_img = np.zeros((height, width, 3),dtype=np.float32)\n        mix_img[:img1.shape[0], :img1.shape[1], :] = img1.astype(np.float32) * lambd\n        mix_img[:img2.shape[0], :img2.shape[1], :] += img2.astype(np.float32) * (1. - lambd)\n        mix_img = mix_img.astype(np.uint8)\n\n        y1 = np.hstack((label1, np.full((label1.shape[0], 1), lambd)))\n        y2 = np.hstack((label2, np.full((label2.shape[0], 1), 1. - lambd)))\n        mix_label = np.vstack((y1, y2))\n        if self.preproc is not None:\n            mix_img, padded_labels = self.preproc(mix_img, mix_label, self.input_dim)\n\n        img_info = (width, height)\n        return mix_img, padded_labels, img_info , idx\n"
  },
  {
    "path": "dataset/voc_eval.py",
    "content": "# --------------------------------------------------------\n# Fast/er R-CNN\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Bharath Hariharan\n# --------------------------------------------------------\n\nimport xml.etree.ElementTree as ET\nimport os\nimport pickle\nimport numpy as np\nimport pdb\n\n\ndef parse_rec(filename):\n    \"\"\" Parse a PASCAL VOC xml file \"\"\"\n    tree = ET.parse(filename)\n    objects = []\n    for obj in tree.findall('object'):\n        obj_struct = {}\n        obj_struct['name'] = obj.find('name').text\n        obj_struct['pose'] = obj.find('pose').text\n        obj_struct['truncated'] = int(obj.find('truncated').text)\n        obj_struct['difficult'] = int(obj.find('difficult').text)\n        bbox = obj.find('bndbox')\n        obj_struct['bbox'] = [int(bbox.find('xmin').text),\n                              int(bbox.find('ymin').text),\n                              int(bbox.find('xmax').text),\n                              int(bbox.find('ymax').text)]\n        objects.append(obj_struct)\n\n    return objects\n\n\n\ndef voc_ap(rec, prec, use_07_metric=False):\n    \"\"\" ap = voc_ap(rec, prec, [use_07_metric])\n    Compute VOC AP given precision and recall.\n    If use_07_metric is true, uses the\n    VOC 07 11 point method (default:False).\n    \"\"\"\n    if use_07_metric:\n        # 11 point metric\n        ap = 0.\n        for t in np.arange(0., 1.1, 0.1):\n            if np.sum(rec >= t) == 0:\n                p = 0\n            else:\n                p = np.max(prec[rec >= t])\n            ap = ap + p / 11.\n    else:\n        # correct AP calculation\n        # first append sentinel values at the end\n        mrec = np.concatenate(([0.], rec, [1.]))\n        mpre = np.concatenate(([0.], prec, [0.]))\n\n        # compute the precision envelope\n        for i in range(mpre.size - 1, 0, -1):\n            mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n        # to calculate area under PR curve, look for points\n        # where X axis (recall) changes value\n        i = np.where(mrec[1:] != mrec[:-1])[0]\n\n        # and sum (\\Delta recall) * prec\n        ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n    return ap\n\ndef voc_eval(detpath,\n             annopath,\n             imagesetfile,\n             classname,\n             cachedir,\n             ovthresh=0.5,\n             use_07_metric=False):\n    \"\"\"rec, prec, ap = voc_eval(detpath,\n                                annopath,\n                                imagesetfile,\n                                classname,\n                                [ovthresh],\n                                [use_07_metric])\n\n    Top level function that does the PASCAL VOC evaluation.\n\n    detpath: Path to detections\n        detpath.format(classname) should produce the detection results file.\n    annopath: Path to annotations\n        annopath.format(imagename) should be the xml annotations file.\n    imagesetfile: Text file containing the list of images, one image per line.\n    classname: Category name (duh)\n    cachedir: Directory for caching the annotations\n    [ovthresh]: Overlap threshold (default = 0.5)\n    [use_07_metric]: Whether to use VOC07's 11 point AP computation\n        (default False)\n    \"\"\"\n    # assumes detections are in detpath.format(classname)\n    # assumes annotations are in annopath.format(imagename)\n    # assumes imagesetfile is a text file with each line an image name\n    # cachedir caches the annotations in a pickle file\n\n    # first load gt\n    if not os.path.isdir(cachedir):\n        os.mkdir(cachedir)\n    cachefile = os.path.join(cachedir, 'annots.pkl')\n    # read list of images\n    with open(imagesetfile, 'r') as f:\n        lines = f.readlines()\n    imagenames = [x.strip() for x in lines]\n\n    if not os.path.isfile(cachefile):\n        # load annots\n        recs = {}\n        for i, imagename in enumerate(imagenames):\n            recs[imagename] = parse_rec(annopath.format(imagename))\n            if i % 100 == 0:\n                print('Reading annotation for {:d}/{:d}'.format(\n                    i + 1, len(imagenames)))\n        # save\n        print('Saving cached annotations to {:s}'.format(cachefile))\n        with open(cachefile, 'wb') as f:\n            pickle.dump(recs, f)\n    else:\n        # load\n        with open(cachefile, 'rb') as f:\n            recs = pickle.load(f)\n\n    # extract gt objects for this class\n    class_recs = {}\n    npos = 0\n    for imagename in imagenames:\n        R = [obj for obj in recs[imagename] if obj['name'] == classname]\n        bbox = np.array([x['bbox'] for x in R])\n        difficult = np.array([x['difficult'] for x in R]).astype(np.bool)\n        det = [False] * len(R)\n        npos = npos + sum(~difficult)\n        class_recs[imagename] = {'bbox': bbox,\n                                 'difficult': difficult,\n                                 'det': det}\n\n    # read dets\n    detfile = detpath.format(classname)\n    with open(detfile, 'r') as f:\n        lines = f.readlines()\n\n    if len(lines) == 0:\n        return 0, 0, 0\n\n    splitlines = [x.strip().split(' ') for x in lines]\n    image_ids = [x[0] for x in splitlines]\n    confidence = np.array([float(x[1]) for x in splitlines])\n    BB = np.array([[float(z) for z in x[2:]] for x in splitlines])\n\n        # sort by confidence\n    sorted_ind = np.argsort(-confidence)\n    sorted_scores = np.sort(-confidence)\n    BB = BB[sorted_ind, :]\n    image_ids = [image_ids[x] for x in sorted_ind]\n\n        # go down dets and mark TPs and FPs\n    nd = len(image_ids)\n    tp = np.zeros(nd)\n    fp = np.zeros(nd)\n    for d in range(nd):\n        R = class_recs[image_ids[d]]\n        bb = BB[d, :].astype(float)\n        ovmax = -np.inf\n        BBGT = R['bbox'].astype(float)\n\n        if BBGT.size > 0:\n            # compute overlaps\n            # intersection\n            ixmin = np.maximum(BBGT[:, 0], bb[0])\n            iymin = np.maximum(BBGT[:, 1], bb[1])\n            ixmax = np.minimum(BBGT[:, 2], bb[2])\n            iymax = np.minimum(BBGT[:, 3], bb[3])\n            iw = np.maximum(ixmax - ixmin + 1., 0.)\n            ih = np.maximum(iymax - iymin + 1., 0.)\n            inters = iw * ih\n\n                # union\n            uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) +\n                   (BBGT[:, 2] - BBGT[:, 0] + 1.) *\n                   (BBGT[:, 3] - BBGT[:, 1] + 1.) - inters)\n\n            overlaps = inters / uni\n            ovmax = np.max(overlaps)\n            jmax = np.argmax(overlaps)\n\n        if ovmax > ovthresh:\n            if not R['difficult'][jmax]:\n                if not R['det'][jmax]:\n                    tp[d] = 1.\n                    R['det'][jmax] = 1\n                else:\n                    fp[d] = 1.\n        else:\n            fp[d] = 1.\n\n        # compute precision recall\n    fp = np.cumsum(fp)\n    tp = np.cumsum(tp)\n    rec = tp / float(npos)\n        # avoid divide by zero in case the first detection matches a difficult\n        # ground truth\n    prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)\n    ap = voc_ap(rec, prec, use_07_metric)\n\n    return rec, prec, ap\n"
  },
  {
    "path": "dataset/vocdataset.py",
    "content": "\"\"\"VOC Dataset Classes\n\nOriginal author: Francisco Massa\nhttps://github.com/fmassa/vision/blob/voc_dataset/torchvision/datasets/voc.py\n\nUpdated by: Ellis Brown, Max deGroot\n\"\"\"\n\nimport os\nimport pickle\nimport os.path\nimport sys\nimport torch\nimport torch.utils.data as data\nimport torchvision.transforms as transforms\nimport cv2\nimport numpy as np\nfrom .voc_eval import voc_eval\nfrom .dataloading import Dataset\nif sys.version_info[0] == 2:\n    import xml.etree.cElementTree as ET\nelse:\n    import xml.etree.ElementTree as ET\n\n\n#VOC_CLASSES = ( '__background__', # always index 0\nVOC_CLASSES = ( \n    'aeroplane', 'bicycle', 'bird', 'boat',\n    'bottle', 'bus', 'car', 'cat', 'chair',\n    'cow', 'diningtable', 'dog', 'horse',\n    'motorbike', 'person', 'pottedplant',\n    'sheep', 'sofa', 'train', 'tvmonitor')\n\n# for making bounding boxes pretty\nCOLORS = ((255, 0, 0, 128), (0, 255, 0, 128), (0, 0, 255, 128),\n          (0, 255, 255, 128), (255, 0, 255, 128), (255, 255, 0, 128))\n\n\n\nclass AnnotationTransform(object):\n\n    \"\"\"Transforms a VOC annotation into a Tensor of bbox coords and label index\n    Initilized with a dictionary lookup of classnames to indexes\n\n    Arguments:\n        class_to_ind (dict, optional): dictionary lookup of classnames -> indexes\n            (default: alphabetic indexing of VOC's 20 classes)\n        keep_difficult (bool, optional): keep difficult instances or not\n            (default: False)\n        height (int): height\n        width (int): width\n    \"\"\"\n\n    def __init__(self, class_to_ind=None, keep_difficult=True):\n        self.class_to_ind = class_to_ind or dict(\n            zip(VOC_CLASSES, range(len(VOC_CLASSES))))\n        self.keep_difficult = keep_difficult\n\n    def __call__(self, target):\n        \"\"\"\n        Arguments:\n            target (annotation) : the target annotation to be made usable\n                will be an ET.Element\n        Returns:\n            a list containing lists of bounding boxes  [bbox coords, class name]\n        \"\"\"\n        res = np.empty((0,5)) \n        for obj in target.iter('object'):\n            difficult = int(obj.find('difficult').text) == 1\n            if not self.keep_difficult and difficult:\n                continue\n            name = obj.find('name').text.lower().strip()\n            bbox = obj.find('bndbox')\n\n            pts = ['xmin', 'ymin', 'xmax', 'ymax']\n            bndbox = []\n            for i, pt in enumerate(pts):\n                cur_pt = int(bbox.find(pt).text) - 1\n                # scale height or width\n                #cur_pt = cur_pt / width if i % 2 == 0 else cur_pt / height\n                bndbox.append(cur_pt)\n            label_idx = self.class_to_ind[name]\n            bndbox.append(label_idx)\n            res = np.vstack((res,bndbox))  # [xmin, ymin, xmax, ymax, label_ind]\n            # img_id = target.find('filename').text[:-4]\n\n        return res  # [[xmin, ymin, xmax, ymax, label_ind], ... ]\n\n\nclass VOCDetection(Dataset):\n\n    \"\"\"VOC Detection Dataset Object\n\n    input is image, target is annotation\n\n    Arguments:\n        root (string): filepath to VOCdevkit folder.\n        image_set (string): imageset to use (eg. 'train', 'val', 'test')\n        transform (callable, optional): transformation to perform on the\n            input image\n        target_transform (callable, optional): transformation to perform on the\n            target `annotation`\n            (eg: take in caption string, return tensor of word indices)\n        dataset_name (string, optional): which dataset to load\n            (default: 'VOC2007')\n    \"\"\"\n\n    def __init__(self, root, image_sets, preproc=None, target_transform=AnnotationTransform(), input_dim=(416,416),\n                 dataset_name='VOC0712'):\n        super().__init__(input_dim)\n        self.root = root\n        self.image_set = image_sets\n        self.preproc = preproc\n        self.target_transform = target_transform\n        self.name = dataset_name\n        self._annopath = os.path.join('%s', 'Annotations', '%s.xml')\n        self._imgpath = os.path.join('%s', 'JPEGImages', '%s.jpg')\n        self._classes=VOC_CLASSES\n        self.ids = list()\n        for (year, name) in image_sets:\n            self._year = year\n            rootpath = os.path.join(self.root, 'VOC' + year)\n            for line in open(os.path.join(rootpath, 'ImageSets', 'Main', name + '.txt')):\n                self.ids.append((rootpath, line.strip()))\n\n    @Dataset.resize_getitem\n    def __getitem__(self, index):\n        img_id = self.ids[index]\n        target = ET.parse(self._annopath % img_id).getroot()\n        img = cv2.imread(self._imgpath % img_id, cv2.IMREAD_COLOR)\n        #img = Image.open(self._imgpath % img_id).convert('RGB')\n\n        height, width, _ = img.shape\n\n        if self.target_transform is not None:\n            target = self.target_transform(target)\n\n\n        if self.preproc is not None:\n            img, target = self.preproc(img, target, self.input_dim)\n            #print(img.size())\n\n        img_info = (width, height)\n\n        return img, target, img_info, img_id\n\n    def __len__(self):\n        return len(self.ids)\n\n    def pull_image(self, index):\n        '''Returns the original image object at index in PIL form\n\n        Note: not using self.__getitem__(), as any transformations passed in\n        could mess up this functionality.\n\n        Argument:\n            index (int): index of img to show\n        Return:\n            PIL img\n        '''\n        img_id = self.ids[index]\n        return cv2.imread(self._imgpath % img_id, cv2.IMREAD_COLOR)\n\n    def pull_anno(self, index):\n        '''Returns the original annotation of image at index\n\n        Note: not using self.__getitem__(), as any transformations passed in\n        could mess up this functionality.\n\n        Argument:\n            index (int): index of img to get annotation of\n        Return:\n            list:  [img_id, [(label, bbox coords),...]]\n                eg: ('001718', [('dog', (96, 13, 438, 332))])\n        '''\n        img_id = self.ids[index]\n        anno = ET.parse(self._annopath % img_id).getroot()\n        gt = self.target_transform(anno, 1, 1)\n        return img_id[1], gt\n\n    def pull_item(self, index):\n        '''Returns the original image and target at an index for mixup\n\n        Note: not using self.__getitem__(), as any transformations passed in\n        could mess up this functionality.\n\n        Argument:\n            index (int): index of img to show\n        Return:\n            img, target\n        '''\n        img_id = self.ids[index]\n        target = ET.parse(self._annopath % img_id).getroot()\n        img = cv2.imread(self._imgpath % img_id, cv2.IMREAD_COLOR)\n\n        height, width, _ = img.shape\n\n        img_info = (width, height)\n        if self.target_transform is not None:\n            target = self.target_transform(target)\n\n        return img, target, img_info, img_id\n\n    def evaluate_detections(self, all_boxes, output_dir=None):\n        \"\"\"\n        all_boxes is a list of length number-of-classes.\n        Each list element is a list of length number-of-images.\n        Each of those list elements is either an empty list []\n        or a numpy array of detection.\n\n        all_boxes[class][image] = [] or np.array of shape #dets x 5\n        \"\"\"\n        self._write_voc_results_file(all_boxes)\n        IouTh = np.linspace(.5, 0.95, np.round((0.95 - .5) / .05) + 1, endpoint=True)\n        mAPs = []\n        for iou in IouTh:\n            mAP = self._do_python_eval(output_dir,iou)\n            mAPs.append(mAP)\n\n        print('--------------------------------------------------------------')\n        print('map_5095:', np.mean(mAPs))\n        print('map_50:', mAPs[0])\n        print('--------------------------------------------------------------')\n        return np.mean(mAPs), mAPs[0]\n\n    def _get_voc_results_file_template(self):\n        filename = 'comp4_det_test' + '_{:s}.txt'\n        filedir = os.path.join(\n            self.root, 'results', 'VOC' + self._year, 'Main')\n        if not os.path.exists(filedir):\n            os.makedirs(filedir)\n        path = os.path.join(filedir, filename)\n        return path\n\n    def _write_voc_results_file(self, all_boxes):\n        for cls_ind, cls in enumerate(VOC_CLASSES):\n            cls_ind = cls_ind \n            if cls == '__background__':\n                continue\n            print('Writing {} VOC results file'.format(cls))\n            filename = self._get_voc_results_file_template().format(cls)\n            with open(filename, 'wt') as f:\n                for im_ind, index in enumerate(self.ids):\n                    index = index[1]\n                    dets = all_boxes[cls_ind][im_ind]\n                    if dets == []:\n                        continue\n                    for k in range(dets.shape[0]):\n                        f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\\n'.\n                                format(index, dets[k, -1],\n                                dets[k, 0] + 1, dets[k, 1] + 1,\n                                dets[k, 2] + 1, dets[k, 3] + 1))\n\n    def _do_python_eval(self, output_dir='output', iou = 0.5):\n        rootpath = os.path.join(self.root, 'VOC' + self._year)\n        name = self.image_set[0][1]\n        annopath = os.path.join(\n                                rootpath,\n                                'Annotations',\n                                '{:s}.xml')\n        imagesetfile = os.path.join(\n                                rootpath,\n                                'ImageSets',\n                                'Main',\n                                name+'.txt')\n        cachedir = os.path.join(self.root, 'annotations_cache', 'VOC'+self._year, name)\n        if not os.path.exists(cachedir):\n            os.makedirs(cachedir)\n        aps = []\n        # The PASCAL VOC metric changed in 2010\n        use_07_metric = True if int(self._year) < 2010 else False\n        print('VOC07 metric? ' + ('Yes' if use_07_metric else 'No'))\n        if output_dir is not None and not os.path.isdir(output_dir):\n            os.mkdir(output_dir)\n        for i, cls in enumerate(VOC_CLASSES):\n\n            if cls == '__background__':\n                continue\n\n            filename = self._get_voc_results_file_template().format(cls)\n            rec, prec, ap = voc_eval(\n                                    filename, annopath, imagesetfile, cls, cachedir, ovthresh=iou,\n                                    use_07_metric=use_07_metric)\n            aps += [ap]\n            if iou == 0.5:\n                print('AP for {} = {:.4f}'.format(cls, ap))\n            if output_dir is not None:\n                with open(os.path.join(output_dir, cls + '_pr.pkl'), 'wb') as f:\n                    pickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f)\n        if iou ==0.5:\n            print('Mean AP = {:.4f}'.format(np.mean(aps)))\n            print('~~~~~~~~')\n            print('Results:')\n            for ap in aps:\n                print('{:.3f}'.format(ap))\n            print('{:.3f}'.format(np.mean(aps)))\n            print('~~~~~~~~')\n            print('')\n            print('--------------------------------------------------------------')\n            print('Results computed with the **unofficial** Python eval code.')\n            print('Results should be very close to the official MATLAB eval code.')\n            print('Recompute with `./tools/reval.py --matlab ...` for your paper.')\n            print('-- Thanks, The Management')\n            print('--------------------------------------------------------------')\n    \n        return np.mean(aps)\n"
  },
  {
    "path": "demo.py",
    "content": "from utils.utils import *\nfrom dataset.vocdataset import VOC_CLASSES\nfrom dataset.cocodataset import COCO_CLASSES\nfrom dataset.data_augment import ValTransform\nfrom utils.vis_utils import vis\n\nimport os\nimport sys\nimport argparse\nimport yaml\nimport cv2\ncv2.setNumThreads(0)\n\nimport torch\nfrom torch.autograd import Variable\nimport time\n\n######## unlimit the resource in some dockers or cloud machines ####### \n#import resource\n#rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)\n#resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1]))\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--cfg', type=str, default='config/yolov3_baseline.cfg',\n                        help='config file. see readme')\n    parser.add_argument('-d', '--dataset', type=str, default='COCO')\n    parser.add_argument('-i', '--img', type=str, default='example/test.jpg',)\n    parser.add_argument('-c', '--checkpoint', type=str,\n                        help='pytorch checkpoint file path')\n    parser.add_argument('-s', '--test_size', type=int, default=416)\n    parser.add_argument('--half', dest='half', action='store_true', default=False,\n                        help='FP16 training')\n    parser.add_argument('--rfb', dest='rfb', action='store_true', default=False,\n                        help='Use rfb block')\n    parser.add_argument('--asff', dest='asff', action='store_true', default=False,\n                        help='Use ASFF module for yolov3')\n    parser.add_argument('--use_cuda', type=bool, default=True)\n    return parser.parse_args()\n\ndef demo():\n    \"\"\"\n    YOLOv3 demo. See README for details.\n    \"\"\"\n    args = parse_args()\n    print(\"Setting Arguments.. : \", args)\n\n    cuda = torch.cuda.is_available() and args.use_cuda\n\n    # Parse config settings\n    with open(args.cfg, 'r') as f:\n        cfg = yaml.safe_load(f)\n\n    print(\"successfully loaded config file: \", cfg)\n\n    backbone=cfg['MODEL']['BACKBONE']\n    test_size = (args.test_size,args.test_size)\n\n    if args.dataset == 'COCO':\n        class_names = COCO_CLASSES\n        num_class=80\n    elif args.dataset == 'VOC':\n        class_names = VOC_CLASSES\n        num_class=20\n    else:\n        raise Exception(\"Only support COCO or VOC model now!\")\n\n    # Initiate model\n    if args.asff:\n        if backbone == 'mobile':\n            from models.yolov3_mobilev2 import YOLOv3\n            print(\"For mobilenet, we currently don't support dropblock, rfb and FeatureAdaption\")\n        else:\n            from models.yolov3_asff import YOLOv3\n        print('Training YOLOv3 with ASFF!')\n        model = YOLOv3(num_classes = num_class, rfb=args.rfb, asff=args.asff)\n    else:\n        if backbone == 'mobile':\n            from models.yolov3_mobilev2 import YOLOv3\n        else:\n            from models.yolov3_baseline import YOLOv3\n        print('Training YOLOv3 strong baseline!')\n        model = YOLOv3(num_classes = num_class, rfb=args.rfb)\n\n\n    if args.checkpoint:\n        print(\"loading pytorch ckpt...\", args.checkpoint)\n        cpu_device = torch.device(\"cpu\")\n        ckpt = torch.load(args.checkpoint, map_location=cpu_device)\n        #model.load_state_dict(ckpt,strict=False)\n        model.load_state_dict(ckpt)\n    if cuda:\n        print(\"using cuda\")\n        torch.backends.cudnn.benchmark = True\n        device = torch.device(\"cuda\")\n        model = model.to(device)\n\n    if args.half:\n        model = model.half()\n\n    model = model.eval()\n    dtype = torch.float16 if args.half else torch.float32\n\n    #load img\n    transform = ValTransform(rgb_means=(0.485, 0.456, 0.406), std=(0.229,0.224,0.225))\n    im = cv2.imread(args.img)\n    height, width, _ = im.shape\n    ori_im = im.copy()\n    im_input, _ = transform(im, None, test_size)\n    if cuda:\n        im_input = im_input.to(device)\n\n    im_input = Variable(im_input.type(dtype).unsqueeze(0))\n    outputs= model(im_input)\n    outputs = postprocess(outputs, num_class, 0.01, 0.65)\n\n    outputs = outputs[0].cpu().data\n    bboxes = outputs[:, 0:4]\n    bboxes[:, 0::2] *= width / test_size[0]\n    bboxes[:, 1::2] *= height / test_size[1]\n    bboxes[:, 2] = bboxes[:,2] - bboxes[:,0]\n    bboxes[:, 3] = bboxes[:,3] - bboxes[:,1]\n    cls = outputs[:, 6]\n    scores = outputs[:, 4]* outputs[:,5]\n\n    pred_im=vis(ori_im, bboxes.numpy(), scores.numpy(), cls.numpy(), conf=0.6, class_names=class_names)\n    cv2.imshow('Detection', pred_im)\n    cv2.waitKey(0)\n    cv2.destroyAllWindows()\n\n    sys.exit(0)\n\n\nif __name__ == '__main__':\n    demo()\n"
  },
  {
    "path": "eval.py",
    "content": "from utils.utils import *\nfrom utils.cocoapi_evaluator import COCOAPIEvaluator\nfrom utils.voc_evaluator import VOCEvaluator\nfrom utils import distributed_util\nfrom utils.distributed_util import reduce_loss_dict\nfrom dataset.cocodataset import *\nfrom dataset.vocdataset import *\nfrom dataset.data_augment import TrainTransform\nfrom dataset.dataloading import *\n\nimport os\nimport sys\nimport argparse\nimport yaml\nimport random\nimport math\nimport cv2\ncv2.setNumThreads(0)\n\nimport torch\nimport torch.nn.init as init\nfrom torch.autograd import Variable\nimport torch.distributed as dist\nimport time\n\nimport apex\n\n######## unlimit the resource in some dockers or cloud machines ####### \n#import resource\n#rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)\n#resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1]))\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--cfg', type=str, default='config/yolov3_baseline.cfg',\n                        help='config file. see readme')\n    parser.add_argument('-d', '--dataset', type=str,\n                        default='COCO', help='COCO or VOC dataset')\n    parser.add_argument('--n_cpu', type=int, default=4,\n                        help='number of workers')\n    parser.add_argument('--distributed', dest='distributed', action='store_true', default=False,\n                        help='distributed training')\n    parser.add_argument('--local_rank', type=int,\n                            default=0, help='local_rank')\n    parser.add_argument('--ngpu', type=int, default=10,\n                        help='number of gpu')\n    parser.add_argument('-c', '--checkpoint', type=str,\n                        help='pytorch checkpoint file path')\n    parser.add_argument('-s', '--test_size', type=int, default=416)\n    parser.add_argument('--testset', dest='testset', action='store_true', default=False,\n                        help='test set evaluation')\n    parser.add_argument('--half', dest='half', action='store_true', default=False,\n                        help='FP16 training')\n    parser.add_argument('--rfb', dest='rfb', action='store_true', default=False,\n                        help='Use rfb block')\n    parser.add_argument('--asff', dest='asff', action='store_true', default=False,\n                        help='Use ASFF module for yolov3')\n    parser.add_argument('--vis', dest='vis', action='store_true', default=False,\n                        help='visualize fusion weight and detection results')\n    parser.add_argument('--use_cuda', type=bool, default=True)\n    parser.add_argument('--debug', action='store_true', default=False,\n                        help='debug mode where only one image is trained')\n    return parser.parse_args()\n\ndef eval():\n    \"\"\"\n    YOLOv3 evaler. See README for details.\n    \"\"\"\n    args = parse_args()\n    print(\"Setting Arguments.. : \", args)\n\n    cuda = torch.cuda.is_available() and args.use_cuda\n\n    if args.distributed:\n        torch.cuda.set_device(args.local_rank)\n        torch.distributed.init_process_group(backend=\"nccl\", init_method=\"env://\")\n\n\n    # Parse config settings\n    with open(args.cfg, 'r') as f:\n        cfg = yaml.safe_load(f)\n\n    print(\"successfully loaded config file: \", cfg)\n\n    backbone=cfg['MODEL']['BACKBONE']\n    test_size = (args.test_size,args.test_size)\n\n    if args.dataset == 'COCO':\n        evaluator = COCOAPIEvaluator(\n                    data_dir='data/COCO/',\n                    img_size=test_size,\n                    confthre=0.001,\n                    nmsthre=0.65,\n                    testset=args.testset,\n                    vis=args.vis)\n\n        num_class=80\n\n    elif args.dataset == 'VOC':\n        '''\n        # COCO style evaluation, you have to convert xml annotation files into a json file.\n        evaluator = COCOAPIEvaluator(\n                    data_dir='data/VOC/',\n                    img_size=test_size,\n                    confthre=cfg['TEST']['CONFTHRE'],\n                    nmsthre=cfg['TEST']['NMSTHRE'],\n                    testset=args.testset,\n                    voc = True)\n        '''\n        evaluator = VOCEvaluator(\n                    data_dir='data/VOC/',\n                    img_size=test_size,\n                    confthre=0.001,\n                    nmsthre=0.65,\n                    vis=args.vis)\n        num_class=20\n    # Initiate model\n    if args.asff:\n        if backbone == 'mobile':\n            from models.yolov3_mobilev2 import YOLOv3\n            print(\"For mobilenet, we currently don't support dropblock, rfb and FeatureAdaption\")\n        else:\n            from models.yolov3_asff import YOLOv3\n        print('Training YOLOv3 with ASFF!')\n        model = YOLOv3(num_classes = num_class, rfb=args.rfb, vis=args.vis, asff=args.asff)\n    else:\n        if backbone == 'mobile':\n            from models.yolov3_mobilev2 import YOLOv3\n        else:\n            from models.yolov3_baseline import YOLOv3\n        print('Training YOLOv3 strong baseline!')\n        if args.vis:\n            print('Visualization is not supported for YOLOv3 baseline model')\n            args.vis = False\n        model = YOLOv3(num_classes = num_class, rfb=args.rfb)\n\n    save_to_disk = (not args.distributed) or distributed_util.get_rank() == 0\n\n    if args.checkpoint:\n        print(\"loading pytorch ckpt...\", args.checkpoint)\n        cpu_device = torch.device(\"cpu\")\n        ckpt = torch.load(args.checkpoint, map_location=cpu_device)\n        #model.load_state_dict(ckpt,strict=False)\n        model.load_state_dict(ckpt)\n    if cuda:\n        print(\"using cuda\")\n        torch.backends.cudnn.benchmark = True\n        device = torch.device(\"cuda\")\n        model = model.to(device)\n\n    if args.half:\n        model = model.half()\n\n    if args.ngpu > 1:\n        if args.distributed:\n            model = apex.parallel.DistributedDataParallel(model, delay_allreduce=True)\n            #model = apex.parallel.DistributedDataParallel(model)\n        else:\n            model = nn.DataParallel(model) \n\n    dtype = torch.float16 if args.half else torch.float32\n\n    if args.distributed:\n        distributed_util.synchronize()\n\n    ap50_95, ap50 = evaluator.evaluate(model, args.half, args.distributed)\n\n    if args.distributed:\n        distributed_util.synchronize()\n    sys.exit(0) \n\n\nif __name__ == '__main__':\n    eval()\n"
  },
  {
    "path": "main.py",
    "content": "from utils.utils import *\nfrom utils.cocoapi_evaluator import COCOAPIEvaluator\nfrom utils.voc_evaluator import VOCEvaluator\nfrom utils import distributed_util\nfrom utils.distributed_util import reduce_loss_dict\nfrom dataset.cocodataset import *\nfrom dataset.vocdataset import *\nfrom dataset.data_augment import TrainTransform\nfrom dataset.dataloading import *\n\nimport os\nimport sys\nimport argparse\nimport yaml\nimport random\nimport math\nimport cv2\ncv2.setNumThreads(0)\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.init as init\nfrom torch.autograd import Variable\nimport torch.distributed as dist\nimport torch.optim as optim\nimport time\n\nimport apex\nfrom utils.fp16_utils import FP16_Optimizer\n\n######## unlimit the resource in some dockers or cloud machines ####### \n#import resource\n#rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)\n#resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1]))\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--cfg', type=str, default='config/yolov3_baseline.cfg',\n                        help='config file. see readme')\n    parser.add_argument('-d', '--dataset', type=str,\n                        default='COCO', help='COCO or VOC dataset')\n    parser.add_argument('--n_cpu', type=int, default=4,\n                        help='number of workers')\n    parser.add_argument('--distributed', dest='distributed', action='store_true', default=False,\n                        help='distributed training')\n    parser.add_argument('--local_rank', type=int,\n                            default=0, help='local_rank')\n    parser.add_argument('--ngpu', type=int, default=10,\n                        help='number of gpu')\n    parser.add_argument('--start_epoch', type=int,\n                            default=0, help='start epoch')\n    parser.add_argument('--eval_interval', type=int,\n                            default=10, help='interval epoch between evaluations')\n    parser.add_argument('-c', '--checkpoint', type=str,\n                        help='pytorch checkpoint file path')\n    parser.add_argument('--save_dir', type=str,\n                        default='save',\n                        help='directory where model are saved')\n    parser.add_argument('--test', dest='test', action='store_true', default=False,\n                        help='test model')\n    parser.add_argument('-s', '--test_size', type=int, default=416)\n    parser.add_argument('--testset', dest='testset', action='store_true', default=False,\n                        help='test set evaluation')\n    parser.add_argument('--half', dest='half', action='store_true', default=False,\n                        help='FP16 training')\n    parser.add_argument('--rfb', dest='rfb', action='store_true', default=False,\n                        help='Use rfb block')\n    parser.add_argument('--asff', dest='asff', action='store_true', default=False,\n                        help='Use ASFF module for yolov3')\n    parser.add_argument('--dropblock', dest='dropblock', action='store_true', default=False,\n                        help='Use dropblock')\n    parser.add_argument('--nowd', dest='no_wd', action='store_true', default=False,\n                        help='no weight decay for bias')\n    parser.add_argument('--vis', dest='vis', action='store_true', default=False,\n                        help='visualize fusion weight and detection results')\n    parser.add_argument('--use_cuda', type=bool, default=True)\n    parser.add_argument('--debug', action='store_true', default=False,\n                        help='debug mode where only one image is trained')\n    parser.add_argument('--tfboard', action='store_true', help='tensorboard path for logging', default=False)\n    parser.add_argument('--log_dir', type=str,\n                        default='log/',\n                        help='directory where tf log are saved')\n    return parser.parse_args()\n\ndef main():\n    \"\"\"\n    YOLOv3 trainer. See README for details.\n    \"\"\"\n    args = parse_args()\n    print(\"Setting Arguments.. : \", args)\n\n    cuda = torch.cuda.is_available() and args.use_cuda\n    os.makedirs(args.log_dir, exist_ok=True)\n    os.makedirs(args.save_dir, exist_ok=True)\n\n    if args.distributed:\n        torch.cuda.set_device(args.local_rank)\n        torch.distributed.init_process_group(backend=\"nccl\", init_method=\"env://\")\n\n    save_prefix = 'yolov3'\n\n    # Parse config settings\n    with open(args.cfg, 'r') as f:\n        cfg = yaml.safe_load(f)\n\n    print(\"successfully loaded config file: \", cfg)\n\n    backbone = cfg['MODEL']['BACKBONE']\n    lr = cfg['TRAIN']['LR']\n    epochs = cfg['TRAIN']['MAXEPOCH']\n    cos = cfg['TRAIN']['COS']\n    sybn = cfg['TRAIN']['SYBN']\n    mixup = cfg['TRAIN']['MIX']\n    no_mixup_epochs= cfg['TRAIN']['NO_MIXUP_EPOCHS']\n    label_smooth = cfg['TRAIN']['LABAL_SMOOTH']\n    momentum = cfg['TRAIN']['MOMENTUM']\n    burn_in = cfg['TRAIN']['BURN_IN']\n    batch_size = cfg['TRAIN']['BATCHSIZE']\n    decay = cfg['TRAIN']['DECAY']\n    ignore_thre = cfg['TRAIN']['IGNORETHRE']\n    random_resize = cfg['TRAIN']['RANDRESIZE']\n    input_size = (cfg['TRAIN']['IMGSIZE'],cfg['TRAIN']['IMGSIZE'])\n    test_size = (args.test_size,args.test_size)\n    steps = (180, 240) # for no cos lr shedule training\n\n\n    # Learning rate setup\n    base_lr = lr\n\n    if args.dataset == 'COCO':\n        dataset = COCODataset(\n                  data_dir='data/COCO/',\n                  img_size=input_size,\n                  preproc=TrainTransform(rgb_means=(0.485, 0.456, 0.406),std=(0.229, 0.224, 0.225),max_labels=50),\n                  debug=args.debug)\n        num_class = 80\n    elif args.dataset == 'VOC':\n        train_sets = [('2007', 'trainval'), ('2012', 'trainval')]\n        dataset = VOCDetection(root='data/VOC',\n                 image_sets = train_sets,\n                 input_dim = input_size,\n                 preproc=TrainTransform(rgb_means=(0.485, 0.456, 0.406),std=(0.229, 0.224, 0.225),max_labels=30))\n        num_class = 20\n    else:\n        print('Only COCO and VOC datasets are supported!')\n        return\n\n    save_prefix += ('_'+args.dataset)\n\n    if label_smooth:\n        save_prefix += '_label_smooth'\n\n    # Initiate model\n    if args.asff:\n        save_prefix += '_asff'\n        if backbone == 'mobile':\n            from models.yolov3_mobilev2 import YOLOv3\n            save_prefix += '_mobilev2'\n            print(\"For mobilenet, we currently don't support dropblock, rfb and FeatureAdaption\")\n        else:\n            from models.yolov3_asff import YOLOv3\n        print('Training YOLOv3 with ASFF!')\n        model = YOLOv3(num_classes = num_class, ignore_thre=ignore_thre, label_smooth = label_smooth, rfb=args.rfb, vis=args.vis, asff=args.asff)\n    else:\n        save_prefix += '_baseline'\n        if backbone == 'mobile':\n            from models.yolov3_mobilev2 import YOLOv3\n            save_prefix += '_mobilev2'\n        else:\n            from models.yolov3_baseline import YOLOv3\n        print('Training YOLOv3 strong baseline!')\n        if args.vis:\n            print('Visualization is not supported for YOLOv3 baseline model')\n            args.vis = False\n        model = YOLOv3(num_classes = num_class, ignore_thre=ignore_thre, label_smooth = label_smooth, rfb=args.rfb)\n\n\n    save_to_disk = (not args.distributed) or distributed_util.get_rank() == 0\n\n    def init_yolo(M):\n        for m in M.modules():\n            if isinstance(m, nn.Conv2d):\n                if backbone == 'mobile':\n                    init.kaiming_normal_(m.weight, mode='fan_in')\n                else:\n                    init.kaiming_normal_(m.weight, a=0.1, mode='fan_in')\n                if m.bias is not None:\n                    init.zeros_(m.bias)\n            elif isinstance(m, nn.BatchNorm2d):\n                init.ones_(m.weight)\n                init.zeros_(m.bias)\n            elif isinstance(m, nn.Linear):\n                init.normal_(m.weight, 0, 0.01)\n                init.zeros_(m.bias)\n                m.state_dict()[key][...] = 0\n\n    model.apply(init_yolo)\n\n    if sybn:\n        model = apex.parallel.convert_syncbn_model(model)\n\n    if args.checkpoint:\n        print(\"loading pytorch ckpt...\", args.checkpoint)\n        cpu_device = torch.device(\"cpu\")\n        ckpt = torch.load(args.checkpoint, map_location=cpu_device)\n        model.load_state_dict(ckpt,strict=False)\n        #model.load_state_dict(ckpt)\n    if cuda:\n        print(\"using cuda\")\n        torch.backends.cudnn.benchmark = True\n        device = torch.device(\"cuda\")\n        model = model.to(device)\n\n    if args.half:\n        model = model.half()\n\n    if args.ngpu > 1:\n        if args.distributed:\n            model = apex.parallel.DistributedDataParallel(model, delay_allreduce=True)\n            #model = apex.parallel.DistributedDataParallel(model)\n        else:\n            model = nn.DataParallel(model) \n\n    if args.tfboard and save_to_disk:\n        print(\"using tfboard\")\n        from torch.utils.tensorboard import SummaryWriter\n        tblogger = SummaryWriter(args.log_dir)\n\n    model.train()\n    if mixup:\n        from dataset.mixupdetection import MixupDetection\n        dataset = MixupDetection(dataset,\n                  preproc=TrainTransform(rgb_means=(0.485, 0.456, 0.406),std=(0.229, 0.224, 0.225),max_labels=50),\n                  )\n        dataset.set_mixup(np.random.beta, 1.5,1.5)\n\n        save_prefix += '_mixup'\n\n    if args.distributed:\n        sampler = torch.utils.data.DistributedSampler(dataset)\n    else:\n        sampler = torch.utils.data.RandomSampler(dataset)\n\n    batch_sampler = YoloBatchSampler(sampler=sampler, batch_size=batch_size,drop_last=False,input_dimension=input_size)\n    dataloader = DataLoader(\n        dataset, batch_sampler=batch_sampler, num_workers=args.n_cpu, pin_memory=True)\n\n    dataiterator = iter(dataloader)\n\n    if args.dataset == 'COCO':\n        evaluator = COCOAPIEvaluator(\n                    data_dir='data/COCO/',\n                    img_size=test_size,\n                    confthre=cfg['TEST']['CONFTHRE'],\n                    nmsthre=cfg['TEST']['NMSTHRE'],\n                    testset=args.testset,\n                    vis=args.vis)\n\n    elif args.dataset == 'VOC':\n        '''\n        # COCO style evaluation, you have to convert xml annotation files into a json file.\n        evaluator = COCOAPIEvaluator(\n                    data_dir='data/VOC/',\n                    img_size=test_size,\n                    confthre=cfg['TEST']['CONFTHRE'],\n                    nmsthre=cfg['TEST']['NMSTHRE'],\n                    testset=args.testset,\n                    voc = True)\n        '''\n        evaluator = VOCEvaluator(\n                    data_dir='data/VOC/',\n                    img_size=test_size,\n                    confthre=cfg['TEST']['CONFTHRE'],\n                    nmsthre=cfg['TEST']['NMSTHRE'],\n                    vis=args.vis)\n\n\n    dtype = torch.float16 if args.half else torch.float32\n\n    # optimizer setup\n    # set weight decay only on conv.weight\n    if args.no_wd:\n        params_dict = dict(model.named_parameters())\n        params = []\n        for key, value in params_dict.items():\n            if 'conv.weight' in key:\n                params += [{'params':value, 'weight_decay':decay }]\n            else:\n                params += [{'params':value, 'weight_decay':0.0}]\n\n        save_prefix += '_no_wd'\n    else:\n        params = model.parameters()\n\n    optimizer = optim.SGD(params, lr=base_lr, momentum=momentum,\n                          dampening=0, weight_decay=decay)\n\n    if args.half:\n        optimizer = FP16_Optimizer(optimizer,verbose=False)\n\n    if cos:\n        save_prefix += '_cos'\n\n    tmp_lr = base_lr\n\n    def set_lr(tmp_lr):\n        for param_group in optimizer.param_groups:\n            param_group['lr'] = tmp_lr\n\n    # start training loop\n    start = time.time()\n    epoch = args.start_epoch\n    epoch_size = len(dataset) // (batch_size*args.ngpu)\n    while epoch < epochs+1:\n        if args.distributed:\n            batch_sampler.sampler.set_epoch(epoch)\n\n        if epoch > epochs-no_mixup_epochs+1:\n            args.eval_interval = 1\n            if mixup:\n                print('Disable mix up now!')\n                mixup=False\n                dataset.set_mixup(None)\n                if args.distributed:\n                    sampler = torch.utils.data.DistributedSampler(dataset)\n                else:\n                    sampler = torch.utils.data.RandomSampler(dataset)\n                batch_sampler = YoloBatchSampler(sampler=sampler, batch_size=batch_size,drop_last=False,input_dimension=input_size)\n                dataloader = DataLoader(\n                        dataset, batch_sampler=batch_sampler, num_workers=args.n_cpu, pin_memory=True)\n\n        #### DropBlock Shedule #####\n        Drop_layer = [16, 24, 33]\n        if args.asff:\n            Drop_layer = [16, 22, 29]\n        if (epoch == 5 or (epoch == args.start_epoch and args.start_epoch > 5)) and (args.dropblock) and backbone!='mobile':\n            block_size = [1, 3, 5]\n            keep_p = [0.9, 0.9, 0.9]\n            for i in range(len(Drop_layer)):\n                model.module.module_list[Drop_layer[i]].reset(block_size[i], keep_p[i])\n\n        if (epoch == 80 or (epoch == args.start_epoch and args.start_epoch > 80) ) and (args.dropblock) and backbone!='mobile':\n            block_size = [3, 5, 7]\n            keep_p = [0.9, 0.9, 0.9]\n            for i in range(len(Drop_layer)):\n                model.module.module_list[Drop_layer[i]].reset(block_size[i], keep_p[i])\n\n        if (epoch == 150 or (epoch == args.start_epoch and args.start_epoch > 150)) and (args.dropblock) and backbone!='mobile':\n            block_size = [7, 7, 7]\n            keep_p = [0.9, 0.9, 0.9]\n            for i in range(len(Drop_layer)):\n                model.module.module_list[Drop_layer[i]].reset(block_size[i], keep_p[i])\n\n\n        for iter_i,  (imgs, targets,img_info,idx) in enumerate(dataloader):\n            #evaluation\n            if ((epoch % args.eval_interval == 0)and epoch > args.start_epoch and iter_i == 0) or args.test:\n                if not args.test and save_to_disk:\n                    torch.save(model.module.state_dict(), os.path.join(args.save_dir,\n                            save_prefix+'_'+repr(epoch)+'.pth'))\n\n                if args.distributed:\n                    distributed_util.synchronize()\n                ap50_95, ap50 = evaluator.evaluate(model, args.half,args.distributed)\n                if args.distributed:\n                    distributed_util.synchronize()\n                if args.test:\n                    sys.exit(0) \n                model.train()\n                if args.tfboard and save_to_disk:\n                    tblogger.add_scalar('val/COCOAP50', ap50, epoch)\n                    tblogger.add_scalar('val/COCOAP50_95', ap50_95, epoch)\n\n        # learning rate scheduling (cos or step)\n            if epoch < burn_in:\n                tmp_lr = base_lr * pow((iter_i+epoch*epoch_size)*1. / (burn_in*epoch_size), 4)\n                set_lr(tmp_lr)\n            elif cos:\n                if epoch <= epochs-no_mixup_epochs and epoch > 20:\n                    min_lr = 0.00001\n                    tmp_lr = min_lr + 0.5*(base_lr-min_lr)*(1+math.cos(math.pi*(epoch-20)*1./\\\n                        (epochs-no_mixup_epochs-20)))\n                elif epoch > epochs-no_mixup_epochs:\n                    tmp_lr = 0.00001\n                set_lr(tmp_lr)\n\n            elif epoch == burn_in:\n                tmp_lr = base_lr\n                set_lr(tmp_lr)\n            elif epoch in steps and iter_i == 0:\n                tmp_lr = tmp_lr * 0.1\n                set_lr(tmp_lr)\n\n\n            optimizer.zero_grad()\n\n            imgs = Variable(imgs.to(device).to(dtype))\n            targets = Variable(targets.to(device).to(dtype), requires_grad=False)\n            loss_dict = model(imgs, targets, epoch)\n            loss_dict_reduced = reduce_loss_dict(loss_dict)\n            loss = sum(loss for loss in loss_dict['losses'])\n            if args.half:\n                optimizer.backward(loss)\n            else:\n                loss.backward()\n\n            #torch.nn.utils.clip_grad_norm_(model.parameters(), 10)\n\n            optimizer.step()\n\n\n            if iter_i % 10 == 0 and save_to_disk:\n            # logging\n                end = time.time()\n                print('[Epoch %d/%d][Iter %d/%d][lr %.6f]'\n                    '[Loss: anchor %.2f, iou %.2f, l1 %.2f, conf %.2f, cls %.2f, imgsize %d, time: %.2f]'\n                % (epoch, epochs, iter_i, epoch_size, tmp_lr,\n                 sum(anchor_loss for anchor_loss in loss_dict_reduced['anchor_losses']).item(),\n                 sum(iou_loss for iou_loss in loss_dict_reduced['iou_losses']).item(),\n                 sum(l1_loss for l1_loss in loss_dict_reduced['l1_losses']).item(),\n                 sum(conf_loss for conf_loss in loss_dict_reduced['conf_losses']).item(),\n                 sum(cls_loss for cls_loss in loss_dict_reduced['cls_losses']).item(),\n                 input_size[0], end-start),\n                flush=True)\n\n                start = time.time()\n                if args.tfboard and save_to_disk:\n                    tblogger.add_scalar('train/total_loss',\n                            sum(loss for loss in loss_dict_reduced['losses']).item(),\n                            epoch*epoch_size+iter_i)\n\n            # random resizing\n            if random_resize and iter_i %10 == 0 and iter_i > 0:\n                tensor = torch.LongTensor(1).to(device)\n                if args.distributed:\n                    distributed_util.synchronize()\n\n                if save_to_disk:\n                    if epoch > epochs-10:\n                        size = 416 if args.dataset=='VOC' else 608\n                    else:\n                        size = random.randint(*(10,19))\n                        size = int(32 * size)\n                    tensor.fill_(size)\n\n                if args.distributed:\n                    distributed_util.synchronize()\n                    dist.broadcast(tensor, 0)\n\n                input_size = dataloader.change_input_dim(multiple=tensor.item(), random_range=None)\n\n                if args.distributed:\n                    distributed_util.synchronize()\n\n        epoch +=1\n    if not args.test and save_to_disk:\n        torch.save(model.module.state_dict(), os.path.join(args.save_dir,\n            \"yolov3_\"+args.dataset+'_Final.pth'))\n    \n    if args.distributed:\n        distributed_util.synchronize()\n    ap50_95, ap50 = evaluator.evaluate(model, args.half)\n\n    if args.tfboard and save_to_disk:\n        tblogger.close()\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "make.sh",
    "content": "cd utils/DCN\n\npython setup.py install\n"
  },
  {
    "path": "models/network_blocks.py",
    "content": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom utils.DCN.modules.deform_conv2d import DeformConv2d\n\ndef add_conv(in_ch, out_ch, ksize, stride, leaky=True):\n    \"\"\"\n    Add a conv2d / batchnorm / leaky ReLU block.\n    Args:\n        in_ch (int): number of input channels of the convolution layer.\n        out_ch (int): number of output channels of the convolution layer.\n        ksize (int): kernel size of the convolution layer.\n        stride (int): stride of the convolution layer.\n    Returns:\n        stage (Sequential) : Sequential layers composing a convolution block.\n    \"\"\"\n    stage = nn.Sequential()\n    pad = (ksize - 1) // 2\n    stage.add_module('conv', nn.Conv2d(in_channels=in_ch,\n                                       out_channels=out_ch, kernel_size=ksize, stride=stride,\n                                       padding=pad, bias=False))\n    stage.add_module('batch_norm', nn.BatchNorm2d(out_ch))\n    if leaky:\n        stage.add_module('leaky', nn.LeakyReLU(0.1))\n    else:\n        stage.add_module('relu6', nn.ReLU6(inplace=True))\n    return stage\n\n\nclass upsample(nn.Module):\n    __constants__ = ['size', 'scale_factor', 'mode', 'align_corners', 'name']\n\n    def __init__(self, size=None, scale_factor=None, mode='nearest', align_corners=None):\n        super(upsample, self).__init__()\n        self.name = type(self).__name__\n        self.size = size\n        self.scale_factor = scale_factor\n        self.mode = mode\n        self.align_corners = align_corners\n\n    def forward(self, input):\n        return F.interpolate(input, self.size, self.scale_factor, self.mode, self.align_corners)\n\n    def extra_repr(self):\n        if self.scale_factor is not None:\n            info = 'scale_factor=' + str(self.scale_factor) \n        else:\n            info = 'size=' + str(self.size)\n        info += ', mode=' + self.mode\n        return info\n\nclass SPPLayer(nn.Module):\n    def __init__(self):\n        super(SPPLayer, self).__init__()\n\n    def forward(self, x):\n        x_1 = x\n        x_2 = F.max_pool2d(x, 5, stride=1, padding=2)\n        x_3 = F.max_pool2d(x, 9, stride=1, padding=4)\n        x_4 = F.max_pool2d(x, 13, stride=1, padding=6)\n        out = torch.cat((x_1, x_2, x_3, x_4),dim=1)\n        return out\n\nclass DropBlock(nn.Module):\n    def __init__(self, block_size=7, keep_prob=0.9):\n        super(DropBlock, self).__init__()\n        self.block_size = block_size\n        self.keep_prob = keep_prob\n        self.gamma = None\n        self.kernel_size = (block_size, block_size)\n        self.stride = (1, 1)\n        self.padding = (block_size//2, block_size//2)\n    \n    def reset(self, block_size, keep_prob):\n        self.block_size = block_size\n        self.keep_prob = keep_prob\n        self.gamma = None\n        self.kernel_size = (block_size, block_size)\n        self.stride = (1, 1)\n        self.padding = (block_size//2, block_size//2)\n\n    def calculate_gamma(self, x):\n        return  (1-self.keep_prob) * x.shape[-1]**2/\\\n                (self.block_size**2 * (x.shape[-1] - self.block_size + 1)**2) \n\n    def forward(self, x):\n        if (not self.training or self.keep_prob==1): #set keep_prob=1 to turn off dropblock\n            return x\n        if self.gamma is None:\n            self.gamma = self.calculate_gamma(x)\n        if x.type() == 'torch.cuda.HalfTensor': #TODO: not fully support for FP16 now \n            FP16 = True\n            x = x.float()\n        else:\n            FP16 = False\n        p = torch.ones_like(x) * (self.gamma)\n        mask = 1 - torch.nn.functional.max_pool2d(torch.bernoulli(p),\n                                                  self.kernel_size,\n                                                  self.stride,\n                                                  self.padding)\n\n        out =  mask * x * (mask.numel()/mask.sum())\n\n        if FP16:\n            out = out.half()\n        return out\n\nclass resblock(nn.Module):\n    \"\"\"\n    Sequential residual blocks each of which consists of \\\n    two convolution layers.\n    Args:\n        ch (int): number of input and output channels.\n        nblocks (int): number of residual blocks.\n        shortcut (bool): if True, residual tensor addition is enabled.\n    \"\"\"\n    def __init__(self, ch, nblocks=1, shortcut=True):\n\n        super().__init__()\n        self.shortcut = shortcut\n        self.module_list = nn.ModuleList()\n        for i in range(nblocks):\n            resblock_one = nn.ModuleList()\n            resblock_one.append(add_conv(ch, ch//2, 1, 1))\n            resblock_one.append(add_conv(ch//2, ch, 3, 1))\n            self.module_list.append(resblock_one)\n\n    def forward(self, x):\n        for module in self.module_list:\n            h = x\n            for res in module:\n                h = res(h)\n            x = x + h if self.shortcut else h\n        return x\n\n\nclass RFBblock(nn.Module):\n    def __init__(self,in_ch,residual=False):\n        super(RFBblock, self).__init__()\n        inter_c = in_ch // 4\n        self.branch_0 = nn.Sequential(\n                    nn.Conv2d(in_channels=in_ch, out_channels=inter_c, kernel_size=1, stride=1, padding=0),\n                    )\n        self.branch_1 = nn.Sequential(\n                    nn.Conv2d(in_channels=in_ch, out_channels=inter_c, kernel_size=1, stride=1, padding=0),\n                    nn.Conv2d(in_channels=inter_c, out_channels=inter_c, kernel_size=3, stride=1, padding=1)\n                    )\n        self.branch_2 = nn.Sequential(\n                    nn.Conv2d(in_channels=in_ch, out_channels=inter_c, kernel_size=1, stride=1, padding=0),\n                    nn.Conv2d(in_channels=inter_c, out_channels=inter_c, kernel_size=3, stride=1, padding=1),\n                    nn.Conv2d(in_channels=inter_c, out_channels=inter_c, kernel_size=3, stride=1, dilation=2, padding=2)\n                    )\n        self.branch_3 = nn.Sequential(\n                    nn.Conv2d(in_channels=in_ch, out_channels=inter_c, kernel_size=1, stride=1, padding=0),\n                    nn.Conv2d(in_channels=inter_c, out_channels=inter_c, kernel_size=5, stride=1, padding=2),\n                    nn.Conv2d(in_channels=inter_c, out_channels=inter_c, kernel_size=3, stride=1, dilation=3, padding=3)\n                    )\n        self.residual= residual\n\n    def forward(self,x):\n        x_0 = self.branch_0(x)\n        x_1 = self.branch_1(x)\n        x_2 = self.branch_2(x)\n        x_3 = self.branch_3(x)  \n        out = torch.cat((x_0,x_1,x_2,x_3),1)\n        if self.residual:\n            out +=x \n        return out\n\n\nclass FeatureAdaption(nn.Module):\n    def __init__(self, in_ch, out_ch, n_anchors, rfb=False, sep=False):\n        super(FeatureAdaption, self).__init__()\n        if sep:\n            self.sep=True\n        else:\n            self.sep=False\n            self.conv_offset = nn.Conv2d(in_channels=2*n_anchors, \n                    out_channels=2*9*n_anchors, groups = n_anchors, kernel_size=1,stride=1,padding=0)\n            self.dconv = DeformConv2d(in_channels=in_ch, out_channels=out_ch, kernel_size=3, stride=1,\n                    padding=1, deformable_groups=n_anchors)\n            self.rfb=None\n            if rfb:\n                self.rfb = RFBblock(out_ch)\n\n    def forward(self, input, wh_pred):\n        #The RFB block is added behind FeatureAdaption\n        #For mobilenet, we currently don't support rfb and FeatureAdaption\n        if self.sep:\n            return input\n        if self.rfb is not None:\n            input = self.rfb(input)\n        wh_pred_new = wh_pred.detach()\n        offset = self.conv_offset(wh_pred_new)\n        out = self.dconv(input, offset)\n        return out\n\nclass ASFFmobile(nn.Module):\n    def __init__(self, level, rfb=False, vis=False):\n        super(ASFFmobile, self).__init__()\n        self.level = level\n        self.dim = [512, 256, 128]\n        self.inter_dim = self.dim[self.level]\n        if level==0:\n            self.stride_level_1 = add_conv(256, self.inter_dim, 3, 2, leaky=False)\n            self.stride_level_2 = add_conv(128, self.inter_dim, 3, 2, leaky=False)\n            self.expand = add_conv(self.inter_dim, 1024, 3, 1, leaky=False)\n        elif level==1:\n            self.compress_level_0 = add_conv(512, self.inter_dim, 1, 1, leaky=False)\n            self.stride_level_2 = add_conv(128, self.inter_dim, 3, 2, leaky=False)\n            self.expand = add_conv(self.inter_dim, 512, 3, 1, leaky=False)\n        elif level==2:\n            self.compress_level_0 = add_conv(512, self.inter_dim, 1, 1, leaky=False)\n            self.compress_level_1 = add_conv(256, self.inter_dim, 1, 1, leaky=False)\n            self.expand = add_conv(self.inter_dim, 256, 3, 1,leaky=False)\n\n        compress_c = 8 if rfb else 16  #when adding rfb, we use half number of channels to save memory\n\n        self.weight_level_0 = add_conv(self.inter_dim, compress_c, 1, 1, leaky=False)\n        self.weight_level_1 = add_conv(self.inter_dim, compress_c, 1, 1, leaky=False)\n        self.weight_level_2 = add_conv(self.inter_dim, compress_c, 1, 1, leaky=False)\n\n        self.weight_levels = nn.Conv2d(compress_c*3, 3, kernel_size=1, stride=1, padding=0)\n        self.vis= vis\n\n\n    def forward(self, x_level_0, x_level_1, x_level_2):\n        if self.level==0:\n            level_0_resized = x_level_0\n            level_1_resized = self.stride_level_1(x_level_1)\n\n            level_2_downsampled_inter =F.max_pool2d(x_level_2, 3, stride=2, padding=1)\n            level_2_resized = self.stride_level_2(level_2_downsampled_inter)\n\n        elif self.level==1:\n            level_0_compressed = self.compress_level_0(x_level_0)\n            level_0_resized =F.interpolate(level_0_compressed, scale_factor=2, mode='nearest')\n            level_1_resized =x_level_1\n            level_2_resized =self.stride_level_2(x_level_2)\n        elif self.level==2:\n            level_0_compressed = self.compress_level_0(x_level_0)\n            level_0_resized =F.interpolate(level_0_compressed, scale_factor=4, mode='nearest')\n            level_1_compressed = self.compress_level_1(x_level_1)\n            level_1_resized =F.interpolate(level_1_compressed, scale_factor=2, mode='nearest')\n            level_2_resized =x_level_2\n\n        level_0_weight_v = self.weight_level_0(level_0_resized)\n        level_1_weight_v = self.weight_level_1(level_1_resized)\n        level_2_weight_v = self.weight_level_2(level_2_resized)\n        levels_weight_v = torch.cat((level_0_weight_v, level_1_weight_v, level_2_weight_v),1)\n        levels_weight = self.weight_levels(levels_weight_v)\n        levels_weight = F.softmax(levels_weight, dim=1)\n\n        fused_out_reduced = level_0_resized * levels_weight[:,0:1,:,:]+\\\n                            level_1_resized * levels_weight[:,1:2,:,:]+\\\n                            level_2_resized * levels_weight[:,2:,:,:]\n\n        out = self.expand(fused_out_reduced)\n\n        if self.vis:\n            return out, levels_weight, fused_out_reduced.sum(dim=1)\n        else:\n            return out\n\n\nclass ASFF(nn.Module):\n    def __init__(self, level, rfb=False, vis=False):\n        super(ASFF, self).__init__()\n        self.level = level\n        self.dim = [512, 256, 256]\n        self.inter_dim = self.dim[self.level]\n        if level==0:\n            self.stride_level_1 = add_conv(256, self.inter_dim, 3, 2)\n            self.stride_level_2 = add_conv(256, self.inter_dim, 3, 2)\n            self.expand = add_conv(self.inter_dim, 1024, 3, 1)\n        elif level==1:\n            self.compress_level_0 = add_conv(512, self.inter_dim, 1, 1)\n            self.stride_level_2 = add_conv(256, self.inter_dim, 3, 2)\n            self.expand = add_conv(self.inter_dim, 512, 3, 1)\n        elif level==2:\n            self.compress_level_0 = add_conv(512, self.inter_dim, 1, 1)\n            self.expand = add_conv(self.inter_dim, 256, 3, 1)\n\n        compress_c = 8 if rfb else 16  #when adding rfb, we use half number of channels to save memory\n\n        self.weight_level_0 = add_conv(self.inter_dim, compress_c, 1, 1)\n        self.weight_level_1 = add_conv(self.inter_dim, compress_c, 1, 1)\n        self.weight_level_2 = add_conv(self.inter_dim, compress_c, 1, 1)\n\n        self.weight_levels = nn.Conv2d(compress_c*3, 3, kernel_size=1, stride=1, padding=0)\n        self.vis= vis\n\n\n    def forward(self, x_level_0, x_level_1, x_level_2):\n        if self.level==0:\n            level_0_resized = x_level_0\n            level_1_resized = self.stride_level_1(x_level_1)\n\n            level_2_downsampled_inter =F.max_pool2d(x_level_2, 3, stride=2, padding=1)\n            level_2_resized = self.stride_level_2(level_2_downsampled_inter)\n\n        elif self.level==1:\n            level_0_compressed = self.compress_level_0(x_level_0)\n            level_0_resized =F.interpolate(level_0_compressed, scale_factor=2, mode='nearest')\n            level_1_resized =x_level_1\n            level_2_resized =self.stride_level_2(x_level_2)\n        elif self.level==2:\n            level_0_compressed = self.compress_level_0(x_level_0)\n            level_0_resized =F.interpolate(level_0_compressed, scale_factor=4, mode='nearest')\n            level_1_resized =F.interpolate(x_level_1, scale_factor=2, mode='nearest')\n            level_2_resized =x_level_2\n\n        level_0_weight_v = self.weight_level_0(level_0_resized)\n        level_1_weight_v = self.weight_level_1(level_1_resized)\n        level_2_weight_v = self.weight_level_2(level_2_resized)\n        levels_weight_v = torch.cat((level_0_weight_v, level_1_weight_v, level_2_weight_v),1)\n        levels_weight = self.weight_levels(levels_weight_v)\n        levels_weight = F.softmax(levels_weight, dim=1)\n\n        fused_out_reduced = level_0_resized * levels_weight[:,0:1,:,:]+\\\n                            level_1_resized * levels_weight[:,1:2,:,:]+\\\n                            level_2_resized * levels_weight[:,2:,:,:]\n\n        out = self.expand(fused_out_reduced)\n\n        if self.vis:\n            return out, levels_weight, fused_out_reduced.sum(dim=1)\n        else:\n            return out\n\ndef make_divisible(v, divisor, min_value=None):\n    \"\"\"\n    This function is taken from the original tf repo.\n    It ensures that all layers have a channel number that is divisible by 8\n    It can be seen here:\n    https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py\n    :param v:\n    :param divisor:\n    :param min_value:\n    :return:\n    \"\"\"\n    if min_value is None:\n        min_value = divisor\n    new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)\n    # Make sure that round down does not go down by more than 10%.\n    if new_v < 0.9 * v:\n        new_v += divisor\n    return new_v\n\n\nclass ConvBNReLU(nn.Sequential):\n    def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1):\n        padding = (kernel_size - 1) // 2\n        super(ConvBNReLU, self).__init__(\n            nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False),\n            nn.BatchNorm2d(out_planes),\n            nn.ReLU6(inplace=True)\n        )\n\ndef add_sepconv(in_ch, out_ch, ksize, stride):\n\n    stage = nn.Sequential()\n    pad = (ksize - 1) // 2\n    stage.add_module('sepconv', nn.Conv2d(in_channels=in_ch,\n                                       out_channels=in_ch, kernel_size=ksize, stride=stride,\n                                       padding=pad, groups=in_ch, bias=False))\n    stage.add_module('sepbn', nn.BatchNorm2d(in_ch))\n    stage.add_module('seprelu6', nn.ReLU6(inplace=True))\n    stage.add_module('ptconv', nn.Conv2d(in_ch, out_ch, 1, 1, 0, bias=False))\n    stage.add_module('ptbn', nn.BatchNorm2d(out_ch))\n    stage.add_module('ptrelu6', nn.ReLU6(inplace=True))\n    return stage\n\nclass InvertedResidual(nn.Module):\n    def __init__(self, inp, oup, stride, expand_ratio):\n        super(InvertedResidual, self).__init__()\n        self.stride = stride\n        assert stride in [1, 2]\n\n        hidden_dim = int(round(inp * expand_ratio))\n        self.use_res_connect = self.stride == 1 and inp == oup\n\n        layers = []\n        if expand_ratio != 1:\n            # pw\n            layers.append(ConvBNReLU(inp, hidden_dim, kernel_size=1))\n        layers.extend([\n            # dw\n            ConvBNReLU(hidden_dim, hidden_dim, stride=stride, groups=hidden_dim),\n            # pw-linear\n            nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),\n            nn.BatchNorm2d(oup),\n        ])\n        self.conv = nn.Sequential(*layers)\n\n    def forward(self, x):\n        if self.use_res_connect:\n            return x + self.conv(x)\n        else:\n            return self.conv(x)\n\nclass ressepblock(nn.Module):\n    def __init__(self, ch, out_ch, in_ch=None, shortcut=True):\n\n        super().__init__()\n        self.shortcut = shortcut\n        self.module_list = nn.ModuleList()\n        in_ch = ch//2 if in_ch==None else in_ch\n        resblock_one = nn.ModuleList()\n        resblock_one.append(add_conv(ch, in_ch, 1, 1, leaky=False))\n        resblock_one.append(add_conv(in_ch, out_ch, 3, 1,leaky=False))\n        self.module_list.append(resblock_one)\n\n    def forward(self, x):\n        for module in self.module_list:\n            h = x\n            for res in module:\n                h = res(h)\n            x = x + h if self.shortcut else h\n        return x\n\n"
  },
  {
    "path": "models/utils_loss.py",
    "content": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\n\nclass IOUWH_loss(nn.Module): #used for anchor guiding\n    def __init__(self, reduction='none'):\n        super(IOUWH_loss, self).__init__()\n        self.reduction = reduction\n\n    def forward(self, pred, target):\n        orig_shape = pred.shape\n        pred = pred.view(-1,4)\n        target = target.view(-1,4)\n        target[:,:2] = 0\n        tl = torch.max((target[:, :2]-pred[:,2:]/2),\n                      (target[:, :2] - target[:, 2:]/2))\n\n        br = torch.min((target[:, :2]+pred[:,2:]/2),\n                      (target[:, :2] + target[:, 2:]/2))\n\n        area_p = torch.prod(pred[:,2:], 1)\n        area_g = torch.prod(target[:,2:], 1)\n\n        en = (tl< br).type(tl.type()).prod(dim=1)\n        area_i = torch.prod(br-tl, 1) * en\n        U = area_p+area_g-area_i+ 1e-16\n        iou= area_i / U\n\n        loss = 1-iou**2\n        if self.reduction =='mean':\n            loss = loss.mean()\n        elif self.reduction == 'sum':\n            loss = loss.sum()\n\n        return loss\n\nclass IOUloss(nn.Module):\n    def __init__(self, reduction='none'):\n        super(IOUloss, self).__init__()\n        self.reduction = reduction\n\n    def forward(self, pred, target):\n        orig_shape = pred.shape\n        pred = pred.view(-1,4)\n        target = target.view(-1,4)\n        tl = torch.max((pred[:, :2]-pred[:,2:]/2),\n                      (target[:, :2] - target[:, 2:]/2))\n        br = torch.min((pred[:, :2]+pred[:,2:]/2),\n                      (target[:, :2] + target[:, 2:]/2))\n\n        area_p = torch.prod(pred[:,2:], 1)\n        area_g = torch.prod(target[:,2:], 1)\n\n        en = (tl< br).type(tl.type()).prod(dim=1)\n        area_i = torch.prod(br-tl, 1) * en\n        iou= (area_i) / (area_p+area_g-area_i+ 1e-16)\n\n        loss = 1-iou**2\n        if self.reduction =='mean':\n            loss = loss.mean()\n        elif self.reduction == 'sum':\n            loss = loss.sum()\n\n        return loss\n"
  },
  {
    "path": "models/yolov3_asff.py",
    "content": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom .network_blocks import *\nfrom .yolov3_head import YOLOv3Head\n\nfrom collections import defaultdict\n\ndef build_yolov3_modules(num_classes, ignore_thre, label_smooth, rfb):\n    \"\"\"\n    Build yolov3 layer modules.\n    Args:\n        ignore_thre (float): used in YOLOLayer.\n    Returns:\n        mlist (ModuleList): YOLOv3 module list.\n    \"\"\"\n    # DarkNet53\n    mlist = nn.ModuleList()\n    mlist.append(add_conv(in_ch=3, out_ch=32, ksize=3, stride=1))           #0\n    mlist.append(add_conv(in_ch=32, out_ch=64, ksize=3, stride=2))          #1\n    mlist.append(resblock(ch=64))                                           #2\n    mlist.append(add_conv(in_ch=64, out_ch=128, ksize=3, stride=2))         #3\n    mlist.append(resblock(ch=128, nblocks=2))                               #4\n    mlist.append(add_conv(in_ch=128, out_ch=256, ksize=3, stride=2))        #5\n    mlist.append(resblock(ch=256, nblocks=8))    # shortcut 1 from here     #6\n    mlist.append(add_conv(in_ch=256, out_ch=512, ksize=3, stride=2))        #7\n    mlist.append(resblock(ch=512, nblocks=8))    # shortcut 2 from here     #8\n    mlist.append(add_conv(in_ch=512, out_ch=1024, ksize=3, stride=2))       #9\n    mlist.append(resblock(ch=1024, nblocks=4))                              #10\n\n    # YOLOv3\n    mlist.append(resblock(ch=1024, nblocks=1, shortcut=False))              #11\n    mlist.append(add_conv(in_ch=1024, out_ch=512, ksize=1, stride=1))       #12\n    #SPP Layer\n    mlist.append(SPPLayer())                                                #13\n\n    mlist.append(add_conv(in_ch=2048, out_ch=512, ksize=1, stride=1))       #14\n    mlist.append(add_conv(in_ch=512, out_ch=1024, ksize=3, stride=1))       #15\n    mlist.append(DropBlock(block_size=1, keep_prob=1))                    #16\n    mlist.append(add_conv(in_ch=1024, out_ch=512, ksize=1, stride=1))       #17\n\n    # 1st yolo branch\n    mlist.append(add_conv(in_ch=512, out_ch=256, ksize=1, stride=1))        #18\n    mlist.append(upsample(scale_factor=2, mode='nearest'))                  #19\n    mlist.append(add_conv(in_ch=768, out_ch=256, ksize=1, stride=1))        #20\n    mlist.append(add_conv(in_ch=256, out_ch=512, ksize=3, stride=1))        #21\n    mlist.append(DropBlock(block_size=1, keep_prob=1))                    #22\n    mlist.append(resblock(ch=512, nblocks=1, shortcut=False))               #23\n    mlist.append(add_conv(in_ch=512, out_ch=256, ksize=1, stride=1))        #24\n    # 2nd yolo branch\n\n    mlist.append(add_conv(in_ch=256, out_ch=128, ksize=1, stride=1))        #25\n    mlist.append(upsample(scale_factor=2, mode='nearest'))                  #26\n    mlist.append(add_conv(in_ch=384, out_ch=128, ksize=1, stride=1))        #27\n    mlist.append(add_conv(in_ch=128, out_ch=256, ksize=3, stride=1))        #28\n    mlist.append(DropBlock(block_size=1, keep_prob=1))                    #29\n    mlist.append(resblock(ch=256, nblocks=1, shortcut=False))               #30\n    mlist.append(add_conv(in_ch=256, out_ch=128, ksize=1, stride=1))        #31\n    mlist.append(add_conv(in_ch=128, out_ch=256, ksize=3, stride=1))        #32\n\n    return mlist\n\n\nclass YOLOv3(nn.Module):\n    \"\"\"\n    YOLOv3 model module. The module list is defined by create_yolov3_modules function. \\\n    The network returns loss values from three YOLO layers during training \\\n    and detection results during test.\n    \"\"\"\n    def __init__(self, num_classes = 80, ignore_thre=0.7, label_smooth = False, rfb=False, vis=False, asff=False):\n        \"\"\"\n        Initialization of YOLOv3 class.\n        Args:\n            ignore_thre (float): used in YOLOLayer.\n        \"\"\"\n        super(YOLOv3, self).__init__()\n        self.module_list = build_yolov3_modules(num_classes, ignore_thre, label_smooth, rfb)\n\n\n        self.level_0_fusion = ASFF(level=0,rfb=rfb,vis=vis)\n\n        self.level_0_header = YOLOv3Head(anch_mask=[6, 7, 8], n_classes=num_classes, stride=32, in_ch=1024,\n                              ignore_thre=ignore_thre,label_smooth = label_smooth, rfb=rfb)\n\n        self.level_1_fusion = ASFF(level=1,rfb=rfb,vis=vis)\n\n        self.level_1_header = YOLOv3Head(anch_mask=[3, 4, 5], n_classes=num_classes, stride=16, in_ch=512,\n                              ignore_thre=ignore_thre, label_smooth = label_smooth, rfb=rfb)\n\n        self.level_2_fusion = ASFF(level=2,rfb=rfb,vis=vis)\n\n        self.level_2_header = YOLOv3Head(anch_mask=[0, 1, 2], n_classes=num_classes, stride=8, in_ch=256,\n                              ignore_thre=ignore_thre, label_smooth = label_smooth, rfb=rfb)\n        self.vis=vis\n\n    def forward(self, x, targets=None, epoch=0):\n        \"\"\"\n        Forward path of YOLOv3.\n        Args:\n            x (torch.Tensor) : input data whose shape is :math:`(N, C, H, W)`, \\\n                where N, C are batchsize and num. of channels.\n            targets (torch.Tensor) : label array whose shape is :math:`(N, 50, 5)`\n\n        Returns:\n            training:\n                output (torch.Tensor): loss tensor for backpropagation.\n            test:\n                output (torch.Tensor): concatenated detection results.\n        \"\"\"\n\n        train = targets is not None\n        output = []\n        anchor_losses= []\n        iou_losses = []\n        l1_losses = []\n        conf_losses = []\n        cls_losses = []\n        route_layers = []\n        if self.vis:\n            fuse_wegihts = []\n            fuse_fs = []\n\n        for i, module in enumerate(self.module_list):\n\n            # yolo layers\n            x = module(x)\n\n            # route layers\n            if i in [6, 8, 17, 24, 32]:\n                route_layers.append(x)\n            if i == 19:\n                x = torch.cat((x, route_layers[1]), 1)\n            if i == 26:\n                x = torch.cat((x, route_layers[0]), 1)\n        \n\n        for l in range(3):\n            fusion = getattr(self, 'level_{}_fusion'.format(l))\n            header = getattr(self, 'level_{}_header'.format(l))\n\n            if self.vis:\n                fused, weight, fuse_f = fusion(route_layers[2],route_layers[3],route_layers[4])\n                fuse_wegihts.append(weight)\n                fuse_fs.append(fuse_f)\n            else:\n                fused = fusion(route_layers[2],route_layers[3],route_layers[4])\n\n            if train:\n                x, anchor_loss, iou_loss, l1_loss, conf_loss, cls_loss = header(fused, targets)\n                anchor_losses.append(anchor_loss)\n                iou_losses.append(iou_loss)\n                l1_losses.append(l1_loss)\n                conf_losses.append(conf_loss)\n                cls_losses.append(cls_loss)\n            else:\n                x = header(fused)\n\n            output.append(x)\n\n        if train:\n            losses = torch.stack(output, 0).unsqueeze(0).sum(1,keepdim=True)\n            anchor_losses = torch.stack(anchor_losses, 0).unsqueeze(0).sum(1,keepdim=True)\n            iou_losses = torch.stack(iou_losses, 0).unsqueeze(0).sum(1,keepdim=True)\n            l1_losses = torch.stack(l1_losses, 0).unsqueeze(0).sum(1,keepdim=True)\n            conf_losses = torch.stack(conf_losses, 0).unsqueeze(0).sum(1,keepdim=True)\n            cls_losses = torch.stack(cls_losses, 0).unsqueeze(0).sum(1,keepdim=True)\n            loss_dict = dict(\n                    losses = losses,\n                    anchor_losses = anchor_losses,\n                    iou_losses = iou_losses,\n                    l1_losses = l1_losses,\n                    conf_losses = conf_losses,\n                    cls_losses = cls_losses,\n            )\n            return loss_dict\n        else:\n            if self.vis:\n                return torch.cat(output, 1), fuse_wegihts, fuse_fs\n            else:\n                return torch.cat(output, 1)\n\n"
  },
  {
    "path": "models/yolov3_baseline.py",
    "content": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom collections import defaultdict\nfrom .network_blocks import *\nfrom .yolov3_head import YOLOv3Head\n\ndef create_yolov3_modules(num_classes, ignore_thre, label_smooth, rfb):\n    \"\"\"\n    Build yolov3 layer modules.\n    Args:\n        ignore_thre (float): used in YOLOLayer.\n    Returns:\n        mlist (ModuleList): YOLOv3 module list.\n    \"\"\"\n    # DarkNet53\n    mlist = nn.ModuleList()\n    mlist.append(add_conv(in_ch=3, out_ch=32, ksize=3, stride=1))           #0\n    mlist.append(add_conv(in_ch=32, out_ch=64, ksize=3, stride=2))          #1\n    mlist.append(resblock(ch=64))                                           #2\n    mlist.append(add_conv(in_ch=64, out_ch=128, ksize=3, stride=2))         #3\n    mlist.append(resblock(ch=128, nblocks=2))                               #4\n    mlist.append(add_conv(in_ch=128, out_ch=256, ksize=3, stride=2))        #5\n    mlist.append(resblock(ch=256, nblocks=8))    # shortcut 1 from here     #6\n    mlist.append(add_conv(in_ch=256, out_ch=512, ksize=3, stride=2))        #7\n    mlist.append(resblock(ch=512, nblocks=8))    # shortcut 2 from here     #8\n    mlist.append(add_conv(in_ch=512, out_ch=1024, ksize=3, stride=2))       #9\n    mlist.append(resblock(ch=1024, nblocks=4))                              #10\n\n    # YOLOv3\n    mlist.append(resblock(ch=1024, nblocks=1, shortcut=False))              #11\n    mlist.append(add_conv(in_ch=1024, out_ch=512, ksize=1, stride=1))       #12\n    #SPP Layer\n    mlist.append(SPPLayer())                                                #13\n\n    mlist.append(add_conv(in_ch=2048, out_ch=512, ksize=1, stride=1))       #14\n    mlist.append(add_conv(in_ch=512, out_ch=1024, ksize=3, stride=1))       #15\n    mlist.append(DropBlock(block_size=1, keep_prob=1.0))                    #16\n    mlist.append(add_conv(in_ch=1024, out_ch=512, ksize=1, stride=1))       #17\n    # 1st yolo branch\n    mlist.append(add_conv(in_ch=512, out_ch=1024, ksize=3, stride=1))       #18\n    mlist.append(\n        YOLOv3Head(anch_mask=[6, 7, 8], n_classes=num_classes, stride=32, in_ch=1024,\n            ignore_thre=ignore_thre,label_smooth = label_smooth, rfb=rfb))           #19\n\n    mlist.append(add_conv(in_ch=512, out_ch=256, ksize=1, stride=1))        #20\n    mlist.append(upsample(scale_factor=2, mode='nearest'))                  #21\n    mlist.append(add_conv(in_ch=768, out_ch=256, ksize=1, stride=1))        #22\n    mlist.append(add_conv(in_ch=256, out_ch=512, ksize=3, stride=1))        #23\n    mlist.append(DropBlock(block_size=1, keep_prob=1.0))                    #24\n    mlist.append(resblock(ch=512, nblocks=1, shortcut=False))               #25\n    mlist.append(add_conv(in_ch=512, out_ch=256, ksize=1, stride=1))        #26\n    # 2nd yolo branch\n    mlist.append(add_conv(in_ch=256, out_ch=512, ksize=3, stride=1))        #27\n    mlist.append(\n        YOLOv3Head(anch_mask=[3, 4, 5], n_classes=num_classes, stride=16, in_ch=512,\n             ignore_thre=ignore_thre, label_smooth = label_smooth, rfb=rfb))         #28\n\n    mlist.append(add_conv(in_ch=256, out_ch=128, ksize=1, stride=1))        #29\n    mlist.append(upsample(scale_factor=2, mode='nearest'))                  #30\n    mlist.append(add_conv(in_ch=384, out_ch=128, ksize=1, stride=1))        #31\n    mlist.append(add_conv(in_ch=128, out_ch=256, ksize=3, stride=1))        #32\n    mlist.append(DropBlock(block_size=1, keep_prob=1.0))                    #33\n    mlist.append(resblock(ch=256, nblocks=1, shortcut=False))               #34\n    mlist.append(add_conv(in_ch=256, out_ch=128, ksize=1, stride=1))        #35\n    mlist.append(add_conv(in_ch=128, out_ch=256, ksize=3, stride=1))        #36\n    mlist.append(\n        YOLOv3Head(anch_mask=[0, 1, 2], n_classes=num_classes, stride=8, in_ch=256,\n             ignore_thre=ignore_thre, label_smooth = label_smooth, rfb=rfb))         #37\n\n    return mlist\n\n\nclass YOLOv3(nn.Module):\n    \"\"\"\n    YOLOv3 model module. The module list is defined by create_yolov3_modules function. \\\n    The network returns loss values from three YOLO layers during training \\\n    and detection results during test.\n    \"\"\"\n    def __init__(self, num_classes = 80, ignore_thre=0.7, label_smooth = False, rfb=False):\n\n        super(YOLOv3, self).__init__()\n        self.module_list = create_yolov3_modules(num_classes, ignore_thre, label_smooth, rfb)\n\n    def forward(self, x, targets=None, epoch=0):\n\n        train = targets is not None\n        output = []\n        anchor_losses= []\n        iou_losses = []\n        l1_losses = []\n        conf_losses = []\n        cls_losses = []\n        route_layers = []\n        for i, module in enumerate(self.module_list):\n\n            # yolo layers\n            if i in [19, 28, 37]:\n                if train:\n                    x, anchor_loss, iou_loss, l1_loss, conf_loss, cls_loss = module(x, targets)\n                    anchor_losses.append(anchor_loss)\n                    iou_losses.append(iou_loss)\n                    l1_losses.append(l1_loss)\n                    conf_losses.append(conf_loss)\n                    cls_losses.append(cls_loss)\n                else:\n                    x = module(x)\n\n                output.append(x)\n            else:\n                x = module(x)\n\n            # route layers\n            if i in [6, 8, 17, 26]:\n                route_layers.append(x)\n            if i == 19:\n                x = route_layers[2]\n            if i == 28:  # yolo 2nd\n                x = route_layers[3]\n            if i == 21:\n                x = torch.cat((x, route_layers[1]), 1)\n            if i == 30:\n                x = torch.cat((x, route_layers[0]), 1)\n\n        if train:\n            losses = torch.stack(output, 0).unsqueeze(0).sum(1,keepdim=True)\n            anchor_losses = torch.stack(anchor_losses, 0).unsqueeze(0).sum(1,keepdim=True)\n            iou_losses = torch.stack(iou_losses, 0).unsqueeze(0).sum(1,keepdim=True)\n            l1_losses = torch.stack(l1_losses, 0).unsqueeze(0).sum(1,keepdim=True)\n            conf_losses = torch.stack(conf_losses, 0).unsqueeze(0).sum(1,keepdim=True)\n            cls_losses = torch.stack(cls_losses, 0).unsqueeze(0).sum(1,keepdim=True)\n            loss_dict = dict(\n                    losses = losses,\n                    anchor_losses = anchor_losses,\n                    iou_losses = iou_losses,\n                    l1_losses = l1_losses,\n                    conf_losses = conf_losses,\n                    cls_losses = cls_losses,\n            )\n            return loss_dict\n        else:\n            return torch.cat(output, 1)\n\n"
  },
  {
    "path": "models/yolov3_head.py",
    "content": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom utils.utils import bboxes_iou\nimport numpy as np\nfrom .utils_loss import *\nfrom .network_blocks import *\n\nclass YOLOv3Head(nn.Module):\n    def __init__(self, anch_mask, n_classes, stride, in_ch=1024, ignore_thre=0.7, label_smooth = False, rfb=False, sep=False):\n        super(YOLOv3Head, self).__init__()\n        self.anchors = [\n            (10, 13), (16, 30), (33, 23), \n            (30, 61), (62, 45), (42, 119),\n            (116, 90), (156, 198), (121, 240) ]\n        if sep:\n            self.anchors = [\n                (10, 13), (16, 30), (33, 23), \n                (30, 61), (62, 45), (42, 119),\n                (116, 90), (156, 198), (373, 326)]\n\n        self.anch_mask = anch_mask\n        self.n_anchors = 4\n        self.n_classes = n_classes\n        self.guide_wh = nn.Conv2d(in_channels=in_ch,\n                              out_channels=2*self.n_anchors, kernel_size=1, stride=1, padding=0)\n        self.Feature_adaption=FeatureAdaption(in_ch, in_ch, self.n_anchors, rfb, sep)\n\n        self.conv = nn.Conv2d(in_channels=in_ch,\n                              out_channels=self.n_anchors*(self.n_classes+5), kernel_size=1, stride=1, padding=0)\n        self.ignore_thre = ignore_thre\n        self.l1_loss = nn.L1Loss(reduction='none')\n        #self.smooth_l1_loss = nn.SmoothL1Loss(reduction='none')\n        self.bcewithlog_loss = nn.BCEWithLogitsLoss(reduction='none')\n        self.bce_loss = nn.BCELoss(reduction='none')\n        self.iou_loss = IOUloss(reduction='none')\n        self.iou_wh_loss = IOUWH_loss(reduction='none')\n        self.stride = stride\n        self._label_smooth = label_smooth\n\n        self.all_anchors_grid = self.anchors\n        self.masked_anchors = [self.all_anchors_grid[i]\n                               for i in self.anch_mask]\n        self.ref_anchors = np.zeros((len(self.all_anchors_grid), 4))\n        self.ref_anchors[:, 2:] = np.array(self.all_anchors_grid)\n        self.ref_anchors = torch.FloatTensor(self.ref_anchors)\n\n    def forward(self, xin, labels=None):\n        \"\"\"\n        In this\n        Args:\n            xin (torch.Tensor): input feature map whose size is :math:`(N, C, H, W)`, \\\n                where N, C, H, W denote batchsize, channel width, height, width respectively.\n            labels (torch.Tensor): label data whose size is :math:`(N, K, 5)`. \\\n                N and K denote batchsize and number of labels.\n                Each label consists of [class, xc, yc, w, h]:\n                    class (float): class index.\n                    xc, yc (float) : center of bbox whose values range from 0 to 1.\n                    w, h (float) : size of bbox whose values range from 0 to 1.\n        Returns:\n            loss (torch.Tensor): total loss - the target of backprop.\n            loss_xy (torch.Tensor): x, y loss - calculated by binary cross entropy (BCE) \\\n                with boxsize-dependent weights.\n            loss_wh (torch.Tensor): w, h loss - calculated by l2 without size averaging and \\\n                with boxsize-dependent weights.\n            loss_obj (torch.Tensor): objectness loss - calculated by BCE.\n            loss_cls (torch.Tensor): classification loss - calculated by BCE for each class.\n            loss_l2 (torch.Tensor): total l2 loss - only for logging.\n        \"\"\"\n\n        wh_pred = self.guide_wh(xin) #Anchor guiding\n\n        if xin.type() == 'torch.cuda.HalfTensor': #As DCN only support FP32 now, change the feature to float.\n            wh_pred = wh_pred.float()\n            if labels is not None:\n                labels = labels.float()\n            self.Feature_adaption = self.Feature_adaption.float()\n            self.conv = self.conv.float()\n            xin = xin.float()\n\n        feature_adapted = self.Feature_adaption(xin, wh_pred)\n\n        output = self.conv(feature_adapted)\n        wh_pred = torch.exp(wh_pred)\n\n        batchsize = output.shape[0]\n        fsize = output.shape[2]\n        image_size = fsize * self.stride\n        n_ch = 5 + self.n_classes\n        dtype = torch.cuda.FloatTensor if xin.is_cuda else torch.FloatTensor\n\n        wh_pred = wh_pred.view(batchsize, self.n_anchors, 2 , fsize, fsize)\n        wh_pred = wh_pred.permute(0, 1, 3, 4, 2).contiguous()\n\n        output = output.view(batchsize, self.n_anchors, n_ch, fsize, fsize)\n        output = output.permute(0,1,3,4,2).contiguous()\n\n        x_shift = dtype(np.broadcast_to(\n            np.arange(fsize, dtype=np.float32), output.shape[:4]))\n        y_shift = dtype(np.broadcast_to(\n            np.arange(fsize, dtype=np.float32).reshape(fsize, 1), output.shape[:4]))\n\n        masked_anchors = np.array(self.masked_anchors)\n\n        w_anchors = dtype(np.broadcast_to(np.reshape(\n            masked_anchors[:, 0], (1, self.n_anchors-1, 1, 1)), [batchsize, self.n_anchors-1, fsize, fsize]))\n        h_anchors = dtype(np.broadcast_to(np.reshape(\n            masked_anchors[:, 1], (1, self.n_anchors-1, 1, 1)), [batchsize, self.n_anchors-1, fsize, fsize]))\n\n        default_center = torch.zeros(batchsize, self.n_anchors, fsize, fsize, 2).type(dtype)\n\n        pred_anchors = torch.cat((default_center, wh_pred), dim=-1).contiguous()\n\n        anchors_based = pred_anchors[:, :self.n_anchors-1, :, :, :]   #anchor branch\n        anchors_free = pred_anchors[:, self.n_anchors-1, :, :, :]     #anchor free branch\n        anchors_based[...,2] *= w_anchors\n        anchors_based[...,3] *= h_anchors\n        anchors_free[...,2] *= self.stride*4\n        anchors_free[...,3] *= self.stride*4\n        pred_anchors[...,:2] = pred_anchors[...,:2].detach()\n\n        if not self.training:\n\n            pred = output.clone()\n            pred[..., np.r_[:2, 4:n_ch]] = torch.sigmoid(\n                    pred[...,np.r_[:2, 4:n_ch]])\n            pred[...,0] += x_shift\n            pred[...,1] += y_shift\n            pred[...,:2] *= self.stride\n            pred[...,2] = torch.exp(pred[...,2])*(pred_anchors[...,2])\n            pred[...,3] = torch.exp(pred[...,3])*(pred_anchors[...,3])\n            refined_pred = pred.view(batchsize, -1, n_ch)\n            return refined_pred.data\n\n        #training for anchor prediction\n        if self.training:\n\n            target = torch.zeros(batchsize, self.n_anchors,\n                                fsize, fsize, n_ch).type(dtype)\n            l1_target = torch.zeros(batchsize, self.n_anchors,\n                                fsize, fsize, 4).type(dtype)\n            tgt_scale = torch.zeros(batchsize, self.n_anchors,\n                                fsize, fsize, 4).type(dtype)\n            obj_mask = torch.ones(batchsize, self.n_anchors, fsize, fsize).type(dtype)\n\n            cls_mask = torch.zeros(batchsize, self.n_anchors, fsize, fsize, self.n_classes).type(dtype)\n            coord_mask = torch.zeros(batchsize, self.n_anchors, fsize, fsize).type(dtype)\n            anchor_mask = torch.zeros(batchsize, self.n_anchors, fsize, fsize).type(dtype)\n\n            labels = labels.data\n            mixup = labels.shape[2]>5\n            if mixup:\n                label_cut = labels[...,:5]\n            else:\n                label_cut = labels\n            nlabel = (label_cut.sum(dim=2) > 0).sum(dim=1)  # number of objects\n\n            truth_x_all = labels[:, :, 1] * 1.\n            truth_y_all = labels[:, :, 2] * 1.\n            truth_w_all = labels[:, :, 3] * 1.\n            truth_h_all = labels[:, :, 4] * 1.\n            truth_i_all = (truth_x_all/image_size*fsize).to(torch.int16).cpu().numpy()\n            truth_j_all = (truth_y_all/image_size*fsize).to(torch.int16).cpu().numpy()\n\n            pred = output.clone()\n            pred[..., np.r_[:2, 4:n_ch]] = torch.sigmoid(\n                    pred[...,np.r_[:2, 4:n_ch]])\n            pred[...,0] += x_shift\n            pred[...,1] += y_shift\n            pred[...,2] = torch.exp(pred[...,2])*(pred_anchors[...,2])\n            pred[...,3] = torch.exp(pred[...,3])*(pred_anchors[...,3])\n            pred[...,:2] *= self.stride\n\n            pred_boxes = pred[...,:4].data\n            for b in range(batchsize):\n                n = int(nlabel[b])\n                if n == 0:\n                    continue\n\n                truth_box = dtype(np.zeros((n, 4)))\n                truth_box[:n, 2] = truth_w_all[b, :n]\n                truth_box[:n, 3] = truth_h_all[b, :n]\n                truth_i = truth_i_all[b, :n]\n                truth_j = truth_j_all[b, :n]\n\n                # calculate iou between truth and reference anchors\n                anchor_ious_all = bboxes_iou(truth_box.cpu(), self.ref_anchors, xyxy=False)\n                best_n_all = np.argmax(anchor_ious_all, axis=1)\n                best_anchor_iou = anchor_ious_all[np.arange(anchor_ious_all.shape[0]),best_n_all]\n                best_n = best_n_all % 3\n                best_n_mask = ((best_n_all == self.anch_mask[0]) | (\n                    best_n_all == self.anch_mask[1]) | (best_n_all == self.anch_mask[2]))\n\n                truth_box[:n, 0] = truth_x_all[b, :n]\n                truth_box[:n, 1] = truth_y_all[b, :n]\n                pred_box = pred_boxes[b]\n                pred_ious = bboxes_iou(pred_box.view(-1,4),\n                        truth_box, xyxy=False)\n                pred_best_iou, _= pred_ious.max(dim=1)\n                pred_best_iou = (pred_best_iou > self.ignore_thre)\n                pred_best_iou = pred_best_iou.view(pred_box.shape[:3])\n                obj_mask[b]= ~pred_best_iou\n                truth_box[:n, 0] = 0\n                truth_box[:n, 1] = 0\n\n                if sum(best_n_mask) == 0:\n                    continue\n                for ti in range(best_n.shape[0]):\n                    if best_n_mask[ti] == 1:\n                        i, j = truth_i[ti], truth_j[ti]\n                        a = best_n[ti]\n                        free_iou = bboxes_iou(truth_box[ti].cpu().view(-1,4),\n                                pred_anchors[b, self.n_anchors-1, j, i, :4].data.cpu().view(-1,4),xyxy=False)  #iou of pred anchor \n\n                        #choose the best anchor\n                        if free_iou > best_anchor_iou[ti]:\n                            aa = self.n_anchors-1\n                        else:\n                            aa = a\n\n                        cls_mask[b, aa, j, i, :] = 1\n                        coord_mask[b, aa, j, i] = 1\n\n                        anchor_mask[b, self.n_anchors-1, j, i] = 1\n                        anchor_mask[b, a, j, i] = 1\n\n                        obj_mask[b, aa, j, i]= 1 if not mixup else labels[b, ti, 5]\n\n                        target[b, a, j, i, 0] = truth_x_all[b, ti]\n                        target[b, a, j, i, 1] = truth_y_all[b, ti]\n                        target[b, a, j, i, 2] = truth_w_all[b, ti]\n                        target[b, a, j, i, 3] = truth_h_all[b, ti]\n\n                        target[b, self.n_anchors-1, j, i, 0] = truth_x_all[b, ti]\n                        target[b, self.n_anchors-1, j, i, 1] = truth_y_all[b, ti]\n                        target[b, self.n_anchors-1, j, i, 2] = truth_w_all[b, ti]\n                        target[b, self.n_anchors-1, j, i, 3] = truth_h_all[b, ti]\n\n                        l1_target[b, aa, j, i, 0] = truth_x_all[b, ti]/image_size *fsize - i*1.0\n                        l1_target[b, aa, j, i, 1] = truth_y_all[b, ti]/image_size *fsize - j*1.0\n                        l1_target[b, aa, j, i, 2] = torch.log(truth_w_all[b, ti]/\\\n                            (pred_anchors[b, aa, j, i, 2])+ 1e-12)\n                        l1_target[b, aa, j, i, 3] = torch.log(truth_h_all[b, ti]/\\\n                            (pred_anchors[b, aa, j, i, 3]) + 1e-12)\n                        target[b, aa, j, i, 4] = 1\n                        if self._label_smooth:\n                            smooth_delta = 1\n                            smooth_weight = 1. / self.n_classes\n                            target[b, aa, j, i, 5:]= smooth_weight* smooth_delta\n\n                            target[b, aa, j, i, 5 + labels[b, ti,\n                                0].to(torch.int16)] = 1 - smooth_delta*smooth_weight\n                        else:\n                            target[b,aa, j, i, 5 + labels[b, ti,\n                                0].to(torch.int16)] = 1\n\n                        tgt_scale[b, aa,j, i, :] = 2.0 - truth_w_all[b, ti]*truth_h_all[b, ti] / image_size/image_size\n\n\n            # Anchor loss\n            anchorcoord_mask = anchor_mask>0\n            loss_anchor = self.iou_wh_loss(pred_anchors[...,:4][anchorcoord_mask], target[...,:4][anchorcoord_mask]).sum()/batchsize\n\n            #Prediction loss\n            coord_mask = coord_mask>0\n            loss_iou = (tgt_scale[coord_mask][...,0]*\\\n                    self.iou_loss(pred[..., :4][coord_mask], target[..., :4][coord_mask])).sum() / batchsize\n            tgt_scale = tgt_scale[...,:2]\n            loss_xy = (tgt_scale*self.bcewithlog_loss(output[...,:2], l1_target[...,:2])).sum() / batchsize\n            loss_wh = (tgt_scale*self.l1_loss(output[...,2:4], l1_target[...,2:4])).sum() / batchsize\n            loss_l1 = loss_xy + loss_wh\n            loss_obj = (obj_mask*(self.bcewithlog_loss(output[..., 4], target[..., 4]))).sum() / batchsize\n            loss_cls = (cls_mask*(self.bcewithlog_loss(output[..., 5:], target[..., 5:]))).sum()/ batchsize\n\n            loss = loss_anchor + loss_iou + loss_l1+ loss_obj + loss_cls\n\n            return loss, loss_anchor, loss_iou, loss_l1, loss_obj, loss_cls\n\n"
  },
  {
    "path": "models/yolov3_mobilev2.py",
    "content": "from torch import nn\nfrom .network_blocks import *\nfrom .yolov3_head import YOLOv3Head\n\n\ndef create_yolov3_mobilenet_v2(num_classes, width_mult=1.0, inverted_residual_setting=None, round_nearest=8):\n    \"\"\"\n    MobileNet V2 main class\n\n    Args:\n        num_classes (int): Number of classes\n        width_mult (float): Width multiplier - adjusts number of channels in each layer by this amount\n        inverted_residual_setting: Network structure\n        round_nearest (int): Round the number of channels in each layer to be a multiple of this number\n        Set to 1 to turn off rounding\n    \"\"\"\n    block = InvertedResidual\n    input_channel = 32\n    last_channel = 1280\n\n    if inverted_residual_setting is None:\n        inverted_residual_setting = [\n            # t, c, n, s\n            [1, 16, 1, 1],\n            [6, 24, 2, 2],\n            [6, 32, 3, 2],\n            [6, 64, 4, 2],\n            [6, 96, 3, 1],\n            [6, 160, 3, 2],\n            [6, 320, 1, 1],\n        ]\n\n    # only check the first element, assuming user knows t,c,n,s are required\n    if len(inverted_residual_setting) == 0 or len(inverted_residual_setting[0]) != 4:\n        raise ValueError(\"inverted_residual_setting should be non-empty \"\n                         \"or a 4-element list, got {}\".format(inverted_residual_setting))\n\n    # building first layer\n    input_channel = make_divisible(input_channel * width_mult, round_nearest)\n    last_channel = make_divisible(last_channel * max(1.0, width_mult), round_nearest)\n    mlist = nn.ModuleList()\n    mlist.append(ConvBNReLU(3, input_channel, stride=2))\n    # building inverted residual blocks\n    for t, c, n, s in inverted_residual_setting:\n        output_channel =make_divisible(c * width_mult, round_nearest)\n        for i in range(n):\n            stride = s if i == 0 else 1\n            mlist.append(block(input_channel, output_channel, stride, expand_ratio=t))\n            input_channel = output_channel\n    # building last several layers\n    mlist.append(ConvBNReLU(input_channel, last_channel, kernel_size=1))   #18\n\n    # YOLOv3\n    mlist.append(ressepblock(last_channel, 1024, in_ch=512, shortcut=False))               #19\n    mlist.append(add_conv(in_ch=1024, out_ch=512, ksize=1, stride=1,leaky=False))      #20\n    # SPP Layer\n    mlist.append(SPPLayer())                                               #21\n\n    mlist.append(add_conv(in_ch=2048, out_ch=512, ksize=1, stride=1, leaky=False))      #22\n    mlist.append(add_conv(in_ch=512, out_ch=1024, ksize=3, stride=1,leaky=False))   #23\n    mlist.append(DropBlock(block_size=1, keep_prob=1))                     #24\n    mlist.append(add_conv(in_ch=1024, out_ch=512, ksize=1, stride=1, leaky=False))      #25 (17)\n\n    # 1st yolo branch\n    mlist.append(add_conv(in_ch=512, out_ch=256, ksize=1, stride=1, leaky=False))        #26\n    mlist.append(upsample(scale_factor=2, mode='nearest'))                  #27\n    mlist.append(add_conv(in_ch=352, out_ch=256, ksize=1, stride=1,leaky=False))        #28\n    mlist.append(add_conv(in_ch=256, out_ch=512, ksize=3, stride=1,leaky=False))     #29\n    mlist.append(DropBlock(block_size=1, keep_prob=1))                      #30\n    mlist.append(ressepblock(512, 512, in_ch=256,shortcut=False))        #31\n    mlist.append(add_conv(in_ch=512, out_ch=256, ksize=1, stride=1,leaky=False))        #32\n    # 2nd yolo branch\n\n    mlist.append(add_conv(in_ch=256, out_ch=128, ksize=1, stride=1,leaky=False))        #33\n    mlist.append(upsample(scale_factor=2, mode='nearest'))                  #34\n    mlist.append(add_conv(in_ch=160, out_ch=128, ksize=1, stride=1,leaky=False))        #35\n    mlist.append(add_conv(in_ch=128, out_ch=256, ksize=3, stride=1,leaky=False))     #36\n    mlist.append(DropBlock(block_size=1, keep_prob=1))                      #37\n    mlist.append(ressepblock(256, 256, in_ch=128,shortcut=False))        #38\n    mlist.append(add_conv(in_ch=256, out_ch=128, ksize=1, stride=1,leaky=False))        #39\n\n    return mlist\n\n\nclass YOLOv3(nn.Module):\n    \"\"\"\n    YOLOv3 model module. The module list is defined by create_yolov3_modules function. \\\n    The network returns loss values from three YOLO layers during training \\\n    and detection results during test.\n    \"\"\"\n    def __init__(self, num_classes = 80, ignore_thre=0.7, label_smooth = False, rfb=False, vis=False, asff=False):\n        \"\"\"\n        Initialization of YOLOv3 class.\n        Args:\n            ignore_thre (float): used in YOLOLayer.\n        \"\"\"\n        super(YOLOv3, self).__init__()\n        self.module_list = create_yolov3_mobilenet_v2(num_classes)\n\n        if asff:\n            self.level_0_conv =ASFFmobile(level=0,rfb=rfb,vis=vis)\n        else:\n            self.level_0_conv =add_conv(in_ch=512, out_ch=1024, ksize=3, stride=1,leaky=False)  \n\n        self.level_0_header = YOLOv3Head(anch_mask=[6, 7, 8], n_classes=num_classes, stride=32, in_ch=1024,\n                              ignore_thre=ignore_thre,label_smooth = label_smooth, rfb=rfb, sep=True)\n\n        if asff:\n            self.level_1_conv =ASFFmobile(level=1,rfb=rfb,vis=vis)\n        else:\n            self.level_1_conv =add_conv(in_ch=256, out_ch=512, ksize=3, stride=1,leaky=False)  \n\n        self.level_1_header = YOLOv3Head(anch_mask=[3, 4, 5], n_classes=num_classes, stride=16, in_ch=512,\n                              ignore_thre=ignore_thre, label_smooth = label_smooth, rfb=rfb, sep=True)\n\n        if asff:\n            self.level_2_conv =ASFFmobile(level=2,rfb=rfb,vis=vis)\n        else:\n            self.level_2_conv =add_conv(in_ch=128, out_ch=256, ksize=3, stride=1,leaky=False)  \n\n        self.level_2_header = YOLOv3Head(anch_mask=[0, 1, 2], n_classes=num_classes, stride=8, in_ch=256,\n                              ignore_thre=ignore_thre, label_smooth = label_smooth, rfb=rfb, sep=True)\n        self.asff = asff\n\n    def forward(self, x, targets=None, epoch=0):\n        \"\"\"\n        Forward path of YOLOv3.\n        Args:\n            x (torch.Tensor) : input data whose shape is :math:`(N, C, H, W)`, \\\n                where N, C are batchsize and num. of channels.\n            targets (torch.Tensor) : label array whose shape is :math:`(N, 50, 5)`\n\n        Returns:\n            training:\n                output (torch.Tensor): loss tensor for backpropagation.\n            test:\n                output (torch.Tensor): concatenated detection results.\n        \"\"\"\n\n        train = targets is not None\n        output = []\n        anchor_losses= []\n        iou_losses = []\n        l1_losses = []\n        conf_losses = []\n        cls_losses = []\n        route_layers = []\n\n        for i, module in enumerate(self.module_list):\n\n            # yolo layers\n            x = module(x)\n\n            # route layers\n            if i in [6, 13, 25, 32, 39]:\n                route_layers.append(x)\n            if i == 27:\n                x = torch.cat((x, route_layers[1]), 1)\n            if i == 34:\n                x = torch.cat((x, route_layers[0]), 1)\n        \n\n        for l in range(3):\n            conver = getattr(self, 'level_{}_conv'.format(l))\n            header = getattr(self, 'level_{}_header'.format(l))\n            if self.asff:\n                f_conv= conver(route_layers[2],route_layers[3],route_layers[4])\n            else:\n                f_conv = conver(route_layers[l+2])\n            if train:\n                x, anchor_loss, iou_loss, l1_loss, conf_loss, cls_loss = header(f_conv, targets)\n                anchor_losses.append(anchor_loss)\n                iou_losses.append(iou_loss)\n                l1_losses.append(l1_loss)\n                conf_losses.append(conf_loss)\n                cls_losses.append(cls_loss)\n            else:\n                x = header(f_conv)\n\n            output.append(x)\n\n        if train:\n            losses = torch.stack(output, 0).unsqueeze(0).sum(1,keepdim=True)\n            anchor_losses = torch.stack(anchor_losses, 0).unsqueeze(0).sum(1,keepdim=True)\n            iou_losses = torch.stack(iou_losses, 0).unsqueeze(0).sum(1,keepdim=True)\n            l1_losses = torch.stack(l1_losses, 0).unsqueeze(0).sum(1,keepdim=True)\n            conf_losses = torch.stack(conf_losses, 0).unsqueeze(0).sum(1,keepdim=True)\n            cls_losses = torch.stack(cls_losses, 0).unsqueeze(0).sum(1,keepdim=True)\n            loss_dict = dict(\n                    losses = losses,\n                    anchor_losses = anchor_losses,\n                    iou_losses = iou_losses,\n                    l1_losses = l1_losses,\n                    conf_losses = conf_losses,\n                    cls_losses = cls_losses,\n            )\n            return loss_dict\n        else:\n            return torch.cat(output, 1)\n"
  },
  {
    "path": "utils/DCN/deform_conv2d_naive.py",
    "content": "import torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport math\nimport numpy as np\nfrom torch.nn.modules.module import Module\nimport torch.nn.functional as F\nfrom torch.nn.modules.utils import _pair\n\nclass deform_conv2d_naive(Module):\n    def __init__(self, in_channels, out_channels,\n                 kernel_size, stride, padding, dilation=1, groups=1, deformable_groups=1, bias=True):\n        super(deform_conv2d_naive, self).__init__()\n        self.in_channels = in_channels\n        self.out_channels = out_channels\n        self.kernel_size = _pair(kernel_size)\n        self.stride = _pair(stride)\n        self.padding = _pair(padding)\n        self.dilation = _pair(dilation)\n        self.groups = groups\n        self.deformable_groups = deformable_groups\n        self.use_bias = bias\n        \n        self.weight = nn.Parameter(torch.Tensor(\n            out_channels, in_channels//groups, *self.kernel_size))\n        self.bias = nn.Parameter(torch.Tensor(out_channels))\n        self.reset_parameters()\n        if not self.use_bias:\n            self.bias.requires_grad = False\n            self.bias.data.zero_()\n\n    def reset_parameters(self):\n        n = self.in_channels\n        init.kaiming_uniform_(self.weight, a=math.sqrt(5))\n        if self.bias is not None:\n            fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)\n            bound = 1 / math.sqrt(fan_in)\n            init.uniform_(self.bias, -bound, bound)\n\n    def forward(self, input, offset):\n        N = input.size(0)\n        in_channels = self.in_channels\n        out_channels = self.out_channels\n        in_h = input.size(2)\n        in_w = input.size(3)\n        out_h = offset.size(2)\n        out_w = offset.size(3)\n        kernel_h = self.kernel_size[0]\n        kernel_w = self.kernel_size[1]\n        # [1, kernel_h * kernel_w, out_h, out_w, 2]\n        mesh = self.compute_mesh_grid(in_h, in_w).cuda(input.get_device())\n        offset = offset.view(N, self.deformable_groups, kernel_h, kernel_w, 2, out_h, out_w)\n        # [N * dg * kernel_h * kernel_w, out_h, out_w, 2]\n        offset = offset.permute(0, 1, 2, 3, 5, 6, 4).contiguous().view(N * self.deformable_groups * kernel_h * kernel_w, out_h, out_w, 2)\n        offset_x_normalize = (offset[:, :, :, 1]) / ((in_w - 1) * 1.0 / 2)\n        offset_y_normalize = (offset[:, :, :, 0]) / ((in_h - 1) * 1.0 / 2)\n        # [N * dg * kernel_h * kernel_w, out_h, out_w, 2]\n        offset = torch.cat([offset_x_normalize[..., None], offset_y_normalize[..., None]], dim=3)\n        # [N * dg * kernel_h * kernel_w, out_h, out_w, 2]\n        grid = mesh.expand(N * self.deformable_groups, -1, -1, -1, -1).contiguous().view(-1, out_h, out_w, 2) + offset\n        # [N * kernel_h * kernel_w * dg, in_channels/dg, in_h, in_w]\n        input = input[:, None, ...].expand(-1, kernel_h * kernel_w, -1, -1, -1).contiguous().view(\n            N * kernel_h * kernel_w * self.deformable_groups, in_channels // self.deformable_groups,  in_h, in_w)\n        sampled_feat = F.grid_sample(input, grid).view(N, kernel_h * kernel_w, in_channels, out_h, out_w).permute(2, 1, 0, 3, 4).contiguous().view(in_channels * kernel_h * kernel_w, -1)\n        output_feat = torch.matmul(self.weight.view(self.weight.size(0), -1), sampled_feat).view(out_channels, N, out_h, out_w).permute(1,0,2,3)\n        return output_feat\n        \n    def compute_mesh_grid(self, in_h, in_w):\n        kernel_h, kernel_w = self.kernel_size\n        stride_h, stride_w = self.stride\n        dilation_h, dilation_w = self.dilation\n        padding_h, padding_w = self.padding\n        out_h = (in_h + 2 * padding_h - (dilation_h * (kernel_h - 1) + 1)) // stride_h + 1\n        out_w = (in_w + 2 * padding_w - (dilation_w * (kernel_w - 1) + 1)) // stride_w + 1\n        # [out_h, out_w]\n        mesh_y, mesh_x = torch.meshgrid(torch.arange(out_h), torch.arange(out_w))\n        mesh_y = mesh_y * stride_h - padding_h\n        mesh_x = mesh_x * stride_w - padding_w\n        # [1, out_h, out_w]\n        mesh_y = mesh_y.unsqueeze(0).float()\n        mesh_x = mesh_x.unsqueeze(0).float()\n        # [kernel_h, kernel_w]\n        kernel_offset_y, kernel_offset_x = torch.meshgrid(torch.arange(kernel_h), torch.arange(kernel_w))\n        # [kernel_h * kernel_w, 1, 1]\n        kernel_offset_y = kernel_offset_y.float().view(kernel_h * kernel_w, 1, 1) * dilation_h\n        kernel_offset_x = kernel_offset_x.float().view(kernel_h * kernel_w, 1, 1) * dilation_w\n        # [kernel_h * kernel_w, out_h, out_w]\n        mesh_y = mesh_y + kernel_offset_y\n        mesh_x = mesh_x + kernel_offset_x\n        mesh_y = (mesh_y - (in_h - 1) / 2.) / ((in_h - 1) / 2.)\n        mesh_x = (mesh_x - (in_w - 1) / 2.) / ((in_w - 1) / 2.)\n        mesh = torch.cat([mesh_x[None, ..., None], mesh_y[None, ..., None]], dim=4)\n        return mesh\n"
  },
  {
    "path": "utils/DCN/functions/__init__.py",
    "content": "from .deform_conv2d_func import DeformConv2dFunction\nfrom .modulated_deform_conv2d_func import ModulatedDeformConv2dFunction\n"
  },
  {
    "path": "utils/DCN/functions/deform_conv2d_func.py",
    "content": "#!/usr/bin/env python\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport math\nimport torch\nfrom torch import nn\nfrom torch.autograd import Function\nfrom torch.nn.modules.utils import _pair\nfrom torch.autograd.function import once_differentiable\nfrom apex import amp\nimport DCN\n\nclass DeformConv2dFunction(Function):\n    @staticmethod\n    @amp.float_function\n    def forward(ctx, input, offset, weight, bias,\n                stride, padding, dilation, group, deformable_groups, im2col_step):\n        ctx.stride = _pair(stride)\n        ctx.padding = _pair(padding)\n        ctx.dilation = _pair(dilation)\n        ctx.kernel_size = _pair(weight.shape[2:4])\n        ctx.group = group\n        ctx.deformable_groups = deformable_groups\n        ctx.im2col_step = im2col_step\n        output = DCN.deform_conv2d_forward(input, weight, bias,\n                                         offset,\n                                         ctx.kernel_size[0], ctx.kernel_size[1],\n                                         ctx.stride[0], ctx.stride[1],\n                                         ctx.padding[0], ctx.padding[1],\n                                         ctx.dilation[0], ctx.dilation[1],\n                                         ctx.group,\n                                         ctx.deformable_groups,\n                                         ctx.im2col_step)\n        ctx.save_for_backward(input, offset, weight, bias)\n        return output\n\n    @staticmethod\n    @once_differentiable\n    @amp.float_function\n    def backward(ctx, grad_output):\n        input, offset, weight, bias = ctx.saved_tensors\n        grad_input, grad_offset, grad_weight, grad_bias = \\\n            DCN.deform_conv2d_backward(input, weight,\n                                     bias,\n                                     offset,\n                                     grad_output,\n                                     ctx.kernel_size[0], ctx.kernel_size[1],\n                                     ctx.stride[0], ctx.stride[1],\n                                     ctx.padding[0], ctx.padding[1],\n                                     ctx.dilation[0], ctx.dilation[1],\n                                     ctx.group,\n                                     ctx.deformable_groups,\n                                     ctx.im2col_step)\n\n        return grad_input, grad_offset, grad_weight, grad_bias,\\\n            None, None, None, None, None, None\n"
  },
  {
    "path": "utils/DCN/functions/modulated_deform_conv2d_func.py",
    "content": "#!/usr/bin/env python\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport math\nimport torch\nfrom torch import nn\nfrom torch.autograd import Function\nfrom torch.nn.modules.utils import _pair\nfrom torch.autograd.function import once_differentiable\n\nimport DCN\n\nclass ModulatedDeformConv2dFunction(Function):\n    @staticmethod\n    def forward(ctx, input, offset, mask, weight, bias,\n                stride, padding, dilation, groups, deformable_groups, im2col_step):\n        ctx.stride = _pair(stride)\n        ctx.padding = _pair(padding)\n        ctx.dilation = _pair(dilation)\n        ctx.kernel_size = _pair(weight.shape[2:4])\n        ctx.groups = groups\n        ctx.deformable_groups = deformable_groups\n        ctx.im2col_step = im2col_step\n        output = DCN.modulated_deform_conv2d_forward(input, weight, bias,\n                                         offset, mask,\n                                         ctx.kernel_size[0], ctx.kernel_size[1],\n                                         ctx.stride[0], ctx.stride[1],\n                                         ctx.padding[0], ctx.padding[1],\n                                         ctx.dilation[0], ctx.dilation[1],\n                                         ctx.groups,\n                                         ctx.deformable_groups,\n                                         ctx.im2col_step)\n        ctx.save_for_backward(input, offset, mask, weight, bias)\n        return output\n\n    @staticmethod\n    @once_differentiable\n    def backward(ctx, grad_output):\n        input, offset, mask, weight, bias = ctx.saved_tensors\n        grad_input, grad_offset, grad_mask, grad_weight, grad_bias = \\\n            DCN.modulated_deform_conv2d_backward(input, weight,\n                                     bias,\n                                     offset, mask,\n                                     grad_output,\n                                     ctx.kernel_size[0], ctx.kernel_size[1],\n                                     ctx.stride[0], ctx.stride[1],\n                                     ctx.padding[0], ctx.padding[1],\n                                     ctx.dilation[0], ctx.dilation[1],\n                                     ctx.groups,\n                                     ctx.deformable_groups,\n                                     ctx.im2col_step)\n\n        return grad_input, grad_offset, grad_mask, grad_weight, grad_bias,\\\n            None, None, None, None, None, None\n"
  },
  {
    "path": "utils/DCN/make.sh",
    "content": "python setup.py build install \n"
  },
  {
    "path": "utils/DCN/modules/__init__.py",
    "content": "from .deform_conv2d import DeformConv2d, _DeformConv2d, DeformConv2dPack, DeformConv2dPackMore\nfrom .modulated_deform_conv2d import ModulatedDeformConv2d, _ModulatedDeformConv2d, ModulatedDeformConv2dPack\n"
  },
  {
    "path": "utils/DCN/modules/deform_conv2d.py",
    "content": "#!/usr/bin/env python\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport torch\nimport math\nfrom torch import nn\nfrom torch.nn import init\nfrom torch.nn.modules.utils import _pair\n\nfrom ..functions.deform_conv2d_func import DeformConv2dFunction\n\nclass DeformConv2d(nn.Module):\n\n    def __init__(self, in_channels, out_channels,\n                 kernel_size, stride, padding, dilation=1, groups=1, deformable_groups=1, im2col_step=64, bias=True):\n        super(DeformConv2d, self).__init__()\n\n        if in_channels % groups != 0:\n            raise ValueError('in_channels {} must be divisible by groups {}'.format(in_channels, groups))\n        if out_channels % groups != 0:\n            raise ValueError('out_channels {} must be divisible by groups {}'.format(out_channels, groups))\n\n        self.in_channels = in_channels\n        self.out_channels = out_channels\n        self.kernel_size = _pair(kernel_size)\n        self.stride = _pair(stride)\n        self.padding = _pair(padding)\n        self.dilation = _pair(dilation)\n        self.groups = groups\n        self.deformable_groups = deformable_groups\n        self.im2col_step = im2col_step\n        self.use_bias = bias\n        \n        self.weight = nn.Parameter(torch.Tensor(\n            out_channels, in_channels//groups, *self.kernel_size))\n        self.bias = nn.Parameter(torch.Tensor(out_channels))\n        self.reset_parameters()\n        if not self.use_bias:\n            self.bias.requires_grad = False\n            self.bias.data.zero_()\n\n    def reset_parameters(self):\n        n = self.in_channels\n        init.kaiming_uniform_(self.weight, a=math.sqrt(5))\n        if self.bias is not None:\n            fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)\n            bound = 1 / math.sqrt(fan_in)\n            init.uniform_(self.bias, -bound, bound)\n\n    def forward(self, input, offset):\n        assert 2 * self.deformable_groups * self.kernel_size[0] * self.kernel_size[1] == \\\n            offset.shape[1]\n        return DeformConv2dFunction.apply(input, offset,\n                                                   self.weight,\n                                                   self.bias,\n                                                   self.stride,\n                                                   self.padding,\n                                                   self.dilation,\n                                                   self.groups,\n                                                   self.deformable_groups,\n                                                   self.im2col_step)\n\n_DeformConv2d = DeformConv2dFunction.apply\n\nclass DeformConv2dPack(DeformConv2d):\n\n    def __init__(self, in_channels, out_channels,\n                 kernel_size, stride, padding,\n                 dilation=1, groups=1, deformable_groups=1, im2col_step=64, bias=True, lr_mult=0.1):\n        super(DeformConv2dPack, self).__init__(in_channels, out_channels,\n                                  kernel_size, stride, padding, dilation, groups, deformable_groups, im2col_step, bias)\n\n        out_channels = self.deformable_groups * 2 * self.kernel_size[0] * self.kernel_size[1]\n        self.conv_offset = nn.Conv2d(self.in_channels,\n                                          out_channels,\n                                          kernel_size=self.kernel_size,\n                                          stride=self.stride,\n                                          padding=self.padding,\n                                          bias=True)\n        self.conv_offset.lr_mult = lr_mult\n        self.conv_offset.inited = True\n        self.init_offset()\n\n    def init_offset(self):\n        self.conv_offset.weight.data.zero_()\n        self.conv_offset.bias.data.zero_()\n\n    def forward(self, input):\n        offset = self.conv_offset(input)\n        return DeformConv2dFunction.apply(input, offset, \n                                          self.weight, \n                                          self.bias, \n                                          self.stride, \n                                          self.padding, \n                                          self.dilation, \n                                          self.groups,\n                                          self.deformable_groups,\n                                          self.im2col_step)\n\n\nclass DeformConv2dPackMore(DeformConv2d):\n\n    def __init__(self, in_channels, out_channels,\n                 kernel_size, stride, padding,\n                 dilation=1, groups=1, deformable_groups=1, im2col_step=64, bias=True, lr_mult=0.1):\n        super(DeformConv2dPackMore, self).__init__(in_channels, out_channels,\n                                                   kernel_size, stride, padding, dilation, groups, deformable_groups, im2col_step, bias)\n\n        out_channels = self.deformable_groups * 2 * self.kernel_size[0] * self.kernel_size[1]\n        self.conv_offset = nn.Sequential(\n            nn.Conv2d(self.in_channels, self.in_channels//4, kernel_size=1, bias=False),\n            nn.BatchNorm2d(self.in_channels//4),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(self.in_channels//4, out_channels, kernel_size=self.kernel_size, stride=self.stride, padding=self.padding, bias=True)\n        )\n        self.conv_offset[-1].lr_mult = lr_mult\n        self.conv_offset[-1].inited = True\n        self.init_offset()\n\n    def init_offset(self):\n        self.conv_offset[-1].weight.data.zero_()\n        self.conv_offset[-1].bias.data.zero_()\n\n    def forward(self, input):\n        offset = self.conv_offset(input)\n        return DeformConv2dFunction.apply(input, offset,\n                                          self.weight,\n                                          self.bias,\n                                          self.stride,\n                                          self.padding,\n                                          self.dilation,\n                                          self.groups,\n                                          self.deformable_groups,\n                                          self.im2col_step)\n"
  },
  {
    "path": "utils/DCN/modules/modulated_deform_conv2d.py",
    "content": "#!/usr/bin/env python\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport torch\nimport math\nfrom torch import nn\nfrom torch.nn import init\nfrom torch.nn.modules.utils import _pair\n\nfrom ..functions.modulated_deform_conv2d_func import ModulatedDeformConv2dFunction\n\nclass ModulatedDeformConv2d(nn.Module):\n\n    def __init__(self, in_channels, out_channels,\n                 kernel_size, stride, padding, dilation=1, groups=1, deformable_groups=1, im2col_step=64, bias=True):\n        super(ModulatedDeformConv2d, self).__init__()\n\n        if in_channels % groups != 0:\n            raise ValueError('in_channels {} must be divisible by groups {}'.format(in_channels, groups))\n        if out_channels % groups != 0:\n            raise ValueError('out_channels {} must be divisible by groups {}'.format(out_channels, groups))\n\n        self.in_channels = in_channels\n        self.out_channels = out_channels\n        self.kernel_size = _pair(kernel_size)\n        self.stride = _pair(stride)\n        self.padding = _pair(padding)\n        self.dilation = _pair(dilation)\n        self.groups = groups\n        self.deformable_groups = deformable_groups\n        self.im2col_step = im2col_step\n        self.use_bias = bias\n\n        self.weight = nn.Parameter(torch.Tensor(\n            out_channels, in_channels//groups, *self.kernel_size))\n        self.bias = nn.Parameter(torch.Tensor(out_channels))\n        self.reset_parameters()\n        if not self.use_bias:\n            self.bias.requires_grad = False\n\n    def reset_parameters(self):\n        n = self.in_channels\n        init.kaiming_uniform_(self.weight, a=math.sqrt(5))\n        if self.bias is not None:\n            fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)\n            bound = 1 / math.sqrt(fan_in)\n            init.uniform_(self.bias, -bound, bound)\n\n    def forward(self, input, offset, mask):\n        assert 2 * self.deformable_groups * self.kernel_size[0] * self.kernel_size[1] == \\\n            offset.shape[1]\n        assert self.deformable_groups * self.kernel_size[0] * self.kernel_size[1] == \\\n            mask.shape[1]\n        return ModulatedDeformConv2dFunction.apply(input, offset, mask,\n                                                   self.weight,\n                                                   self.bias,\n                                                   self.stride,\n                                                   self.padding,\n                                                   self.dilation,\n                                                   self.groups,\n                                                   self.deformable_groups,\n                                                   self.im2col_step)\n\n_ModulatedDeformConv2d = ModulatedDeformConv2dFunction.apply\n\nclass ModulatedDeformConv2dPack(ModulatedDeformConv2d):\n\n    def __init__(self, in_channels, out_channels,\n                 kernel_size, stride, padding,\n                 dilation=1, groups=1, deformable_groups=1, im2col_step=64, bias=True, lr_mult=0.1):\n        super(ModulatedDeformConv2dPack, self).__init__(in_channels, out_channels,\n                                  kernel_size, stride, padding, dilation, groups, deformable_groups, im2col_step, bias)\n\n        out_channels = self.deformable_groups * 3 * self.kernel_size[0] * self.kernel_size[1]\n        self.conv_offset_mask = nn.Conv2d(self.in_channels,\n                                          out_channels,\n                                          kernel_size=self.kernel_size,\n                                          stride=self.stride,\n                                          padding=self.padding,\n                                          bias=True)\n        self.conv_offset_mask.lr_mult = lr_mult\n        self.conv_offset_mask.inited = True\n        self.init_offset()\n\n    def init_offset(self):\n        self.conv_offset_mask.weight.data.zero_()\n        self.conv_offset_mask.bias.data.zero_()\n\n    def forward(self, input):\n        out = self.conv_offset_mask(input)\n        o1, o2, mask = torch.chunk(out, 3, dim=1)\n        offset = torch.cat((o1, o2), dim=1)\n        mask = torch.sigmoid(mask)\n        return ModulatedDeformConv2dFunction.apply(input, offset, mask, \n                                                self.weight, \n                                                self.bias, \n                                                self.stride, \n                                                self.padding, \n                                                self.dilation, \n                                                self.groups,\n                                                self.deformable_groups,\n                                                self.im2col_step)\n\n"
  },
  {
    "path": "utils/DCN/setup.py",
    "content": "#!/usr/bin/env python\n\nimport os\nimport glob\n\nimport torch\n\nfrom torch.utils.cpp_extension import CUDA_HOME\nfrom torch.utils.cpp_extension import CppExtension\nfrom torch.utils.cpp_extension import CUDAExtension\n\nfrom setuptools import find_packages\nfrom setuptools import setup\n\nrequirements = [\"torch\", \"torchvision\"]\n\ndef get_extensions():\n    this_dir = os.path.dirname(os.path.abspath(__file__))\n    extensions_dir = os.path.join(this_dir, \"src\")\n\n    main_file = glob.glob(os.path.join(extensions_dir, \"*.cpp\"))\n    source_cpu = glob.glob(os.path.join(extensions_dir, \"cpu\", \"*.cpp\"))\n    source_cuda = glob.glob(os.path.join(extensions_dir, \"cuda\", \"*.cu\"))\n\n    sources = main_file + source_cpu\n    extension = CppExtension\n    extra_compile_args = {\"cxx\": []}\n    define_macros = []\n\n    if torch.cuda.is_available() and CUDA_HOME is not None:\n        extension = CUDAExtension\n        sources += source_cuda\n        define_macros += [(\"WITH_CUDA\", None)]\n        extra_compile_args[\"nvcc\"] = [\n            \"-DCUDA_HAS_FP16=1\",\n            \"-D__CUDA_NO_HALF_OPERATORS__\",\n            \"-D__CUDA_NO_HALF_CONVERSIONS__\",\n            \"-D__CUDA_NO_HALF2_OPERATORS__\",\n        ]\n    else:\n        raise NotImplementedError('Cuda is not availabel')\n\n    sources = [os.path.join(extensions_dir, s) for s in sources]\n    include_dirs = [extensions_dir]\n    ext_modules = [\n        extension(\n            \"DCN\",\n            sources,\n            include_dirs=include_dirs,\n            define_macros=define_macros,\n            extra_compile_args=extra_compile_args,\n        )\n    ]\n    return ext_modules\n\nsetup(\n    name=\"DCN\",\n    version=\"1.0\",\n    description=\"deformable convolutional networks\",\n    packages=find_packages(exclude=(\"configs\", \"tests\",)),\n    ext_modules=get_extensions(),\n    cmdclass={\"build_ext\": torch.utils.cpp_extension.BuildExtension},\n)\n"
  },
  {
    "path": "utils/DCN/src/cpu/deform_conv2d_cpu.cpp",
    "content": "#include <vector>\n\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n\n\nat::Tensor\ndeform_conv2d_cpu_forward(const at::Tensor &input,\n                          const at::Tensor &weight,\n                          const at::Tensor &bias,\n                          const at::Tensor &offset,\n                          const int kernel_h,\n                          const int kernel_w,\n                          const int stride_h,\n                          const int stride_w,\n                          const int pad_h,\n                          const int pad_w,\n                          const int dilation_h,\n                          const int dilation_w,\n                          const int group,\n                          const int deformable_group,\n                          const int im2col_step)\n{\n    AT_ERROR(\"Not implement on cpu\");\n}\n\nstd::vector<at::Tensor>\ndeform_conv2d_cpu_backward(const at::Tensor &input,\n                           const at::Tensor &weight,\n                           const at::Tensor &bias,\n                           const at::Tensor &offset,\n                           const at::Tensor &grad_output,\n                           const int kernel_h,\n                           const int kernel_w,\n                           const int stride_h,\n                           const int stride_w,\n                           const int pad_h,\n                           const int pad_w,\n                           const int dilation_h,\n                           const int dilation_w,\n                           const int group,\n                           const int deformable_group,\n                           const int im2col_step)\n{\n    AT_ERROR(\"Not implement on cpu\");\n}\n\n"
  },
  {
    "path": "utils/DCN/src/cpu/deform_conv2d_cpu.h",
    "content": "#pragma once\n#include <torch/extension.h>\n\nat::Tensor\ndeform_conv2d_cpu_forward(const at::Tensor &input,\n                          const at::Tensor &weight,\n                          const at::Tensor &bias,\n                          const at::Tensor &offset,\n                          const int kernel_h,\n                          const int kernel_w,\n                          const int stride_h,\n                          const int stride_w,\n                          const int pad_h,\n                          const int pad_w,\n                          const int dilation_h,\n                          const int dilation_w,\n                          const int group,\n                          const int deformable_group,\n                          const int im2col_step);\n\nstd::vector<at::Tensor>\ndeform_conv2d_cpu_backward(const at::Tensor &input,\n                           const at::Tensor &weight,\n                           const at::Tensor &bias,\n                           const at::Tensor &offset,\n                           const at::Tensor &grad_output,\n                           const int kernel_h,\n                           const int kernel_w,\n                           const int stride_h,\n                           const int stride_w,\n                           const int pad_h,\n                           const int pad_w,\n                           const int dilation_h,\n                           const int dilation_w,\n                           const int group,\n                           const int deformable_group,\n                           const int im2col_step);\n\n\n"
  },
  {
    "path": "utils/DCN/src/cpu/modulated_deform_conv2d_cpu.cpp",
    "content": "#include <vector>\n\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n\n\nat::Tensor\nmodulated_deform_conv2d_cpu_forward(const at::Tensor &input,\n                                    const at::Tensor &weight,\n                                    const at::Tensor &bias,\n                                    const at::Tensor &offset,\n                                    const at::Tensor &mask,\n                                    const int kernel_h,\n                                    const int kernel_w,\n                                    const int stride_h,\n                                    const int stride_w,\n                                    const int pad_h,\n                                    const int pad_w,\n                                    const int dilation_h,\n                                    const int dilation_w,\n                                    const int group,\n                                    const int deformable_group,\n                                    const int im2col_step)\n{\n    AT_ERROR(\"Not implement on cpu\");\n}\n\nstd::vector<at::Tensor>\nmodulated_deform_conv2d_cpu_backward(const at::Tensor &input,\n                                     const at::Tensor &weight,\n                                     const at::Tensor &bias,\n                                     const at::Tensor &offset,\n                                     const at::Tensor &mask,\n                                     const at::Tensor &grad_output,\n                                     const int kernel_h,\n                                     const int kernel_w,\n                                     const int stride_h,\n                                     const int stride_w,\n                                     const int pad_h,\n                                     const int pad_w,\n                                     const int dilation_h,\n                                     const int dilation_w,\n                                     const int group,\n                                     const int deformable_group,\n                                     const int im2col_step)\n{\n    AT_ERROR(\"Not implement on cpu\");\n}\n\n"
  },
  {
    "path": "utils/DCN/src/cpu/modulated_deform_conv2d_cpu.h",
    "content": "#pragma once\n#include <torch/extension.h>\n\nat::Tensor\nmodulated_deform_conv2d_cpu_forward(const at::Tensor &input,\n                                    const at::Tensor &weight,\n                                    const at::Tensor &bias,\n                                    const at::Tensor &offset,\n                                    const at::Tensor &mask,\n                                    const int kernel_h,\n                                    const int kernel_w,\n                                    const int stride_h,\n                                    const int stride_w,\n                                    const int pad_h,\n                                    const int pad_w,\n                                    const int dilation_h,\n                                    const int dilation_w,\n                                    const int group,\n                                    const int deformable_group,\n                                    const int im2col_step);\n\nstd::vector<at::Tensor>\nmodulated_deform_conv2d_cpu_backward(const at::Tensor &input,\n                                     const at::Tensor &weight,\n                                     const at::Tensor &bias,\n                                     const at::Tensor &offset,\n                                     const at::Tensor &mask,\n                                     const at::Tensor &grad_output,\n                                     const int kernel_h,\n                                     const int kernel_w,\n                                     const int stride_h,\n                                     const int stride_w,\n                                     const int pad_h,\n                                     const int pad_w,\n                                     const int dilation_h,\n                                     const int dilation_w,\n                                     const int group,\n                                     const int deformable_group,\n                                     const int im2col_step);\n\n\n"
  },
  {
    "path": "utils/DCN/src/cuda/deform_2d_im2col_cuda.cuh",
    "content": "#include <cstdio>\n#include <algorithm>\n#include <cstring>\n\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n\n// #include <THC/THC.h>\n#include <THC/THCAtomics.cuh>\n// #include <THC/THCDeviceUtils.cuh>\n\n#define CUDA_KERNEL_LOOP(i, n)                          \\\n  for (int i = blockIdx.x * blockDim.x + threadIdx.x;   \\\n      i < (n);                                          \\\n      i += blockDim.x * gridDim.x)\n\nconst int CUDA_NUM_THREADS = 1024;\ninline int GET_BLOCKS(const int N)\n{\n  return (N + CUDA_NUM_THREADS - 1) / CUDA_NUM_THREADS;\n}\n\ntemplate <typename scalar_t>\n__device__ scalar_t dmcn_2d_im2col_bilinear(const scalar_t *bottom_data, const int data_width,\n                                            const int height, const int width, scalar_t h, scalar_t w)\n{\n  int h_low = floor(h);\n  int w_low = floor(w);\n  int h_high = h_low + 1;\n  int w_high = w_low + 1;\n\n  scalar_t lh = h - h_low;\n  scalar_t lw = w - w_low;\n  scalar_t hh = 1 - lh, hw = 1 - lw;\n\n  scalar_t v1 = 0;\n  if (h_low >= 0 && w_low >= 0)\n    v1 = bottom_data[h_low * data_width + w_low];\n  scalar_t v2 = 0;\n  if (h_low >= 0 && w_high <= width - 1)\n    v2 = bottom_data[h_low * data_width + w_high];\n  scalar_t v3 = 0;\n  if (h_high <= height - 1 && w_low >= 0)\n    v3 = bottom_data[h_high * data_width + w_low];\n  scalar_t v4 = 0;\n  if (h_high <= height - 1 && w_high <= width - 1)\n    v4 = bottom_data[h_high * data_width + w_high];\n\n  scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;\n\n  scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);\n  return val;\n}\n\ntemplate <typename scalar_t>\n__device__ scalar_t dmcn_2d_get_gradient_weight(scalar_t argmax_h, scalar_t argmax_w,\n                                          const int h, const int w, const int height, const int width)\n{\n  if (argmax_h <= -1 || argmax_h >= height || argmax_w <= -1 || argmax_w >= width)\n  {\n    //empty\n    return 0;\n  }\n\n  int argmax_h_low = floor(argmax_h);\n  int argmax_w_low = floor(argmax_w);\n  int argmax_h_high = argmax_h_low + 1;\n  int argmax_w_high = argmax_w_low + 1;\n\n  scalar_t weight = 0;\n  if (h == argmax_h_low && w == argmax_w_low)\n    weight = (h + 1 - argmax_h) * (w + 1 - argmax_w);\n  if (h == argmax_h_low && w == argmax_w_high)\n    weight = (h + 1 - argmax_h) * (argmax_w + 1 - w);\n  if (h == argmax_h_high && w == argmax_w_low)\n    weight = (argmax_h + 1 - h) * (w + 1 - argmax_w);\n  if (h == argmax_h_high && w == argmax_w_high)\n    weight = (argmax_h + 1 - h) * (argmax_w + 1 - w);\n  return weight;\n}\n\ntemplate <typename scalar_t>\n__device__ scalar_t dmcn_2d_get_coordinate_weight(scalar_t argmax_h, scalar_t argmax_w,\n                                            const int height, const int width, const scalar_t *im_data,\n                                            const int data_width, const int bp_dir)\n{\n  if (argmax_h <= -1 || argmax_h >= height || argmax_w <= -1 || argmax_w >= width)\n  {\n    //empty\n    return 0;\n  }\n\n  int argmax_h_low = floor(argmax_h);\n  int argmax_w_low = floor(argmax_w);\n  int argmax_h_high = argmax_h_low + 1;\n  int argmax_w_high = argmax_w_low + 1;\n\n  scalar_t weight = 0;\n\n  if (bp_dir == 0)\n  {\n    if (argmax_h_low >= 0 && argmax_w_low >= 0)\n      weight += -1 * (argmax_w_low + 1 - argmax_w) * im_data[argmax_h_low * data_width + argmax_w_low];\n    if (argmax_h_low >= 0 && argmax_w_high <= width - 1)\n      weight += -1 * (argmax_w - argmax_w_low) * im_data[argmax_h_low * data_width + argmax_w_high];\n    if (argmax_h_high <= height - 1 && argmax_w_low >= 0)\n      weight += (argmax_w_low + 1 - argmax_w) * im_data[argmax_h_high * data_width + argmax_w_low];\n    if (argmax_h_high <= height - 1 && argmax_w_high <= width - 1)\n      weight += (argmax_w - argmax_w_low) * im_data[argmax_h_high * data_width + argmax_w_high];\n  }\n  else if (bp_dir == 1)\n  {\n    if (argmax_h_low >= 0 && argmax_w_low >= 0)\n      weight += -1 * (argmax_h_low + 1 - argmax_h) * im_data[argmax_h_low * data_width + argmax_w_low];\n    if (argmax_h_low >= 0 && argmax_w_high <= width - 1)\n      weight += (argmax_h_low + 1 - argmax_h) * im_data[argmax_h_low * data_width + argmax_w_high];\n    if (argmax_h_high <= height - 1 && argmax_w_low >= 0)\n      weight += -1 * (argmax_h - argmax_h_low) * im_data[argmax_h_high * data_width + argmax_w_low];\n    if (argmax_h_high <= height - 1 && argmax_w_high <= width - 1)\n      weight += (argmax_h - argmax_h_low) * im_data[argmax_h_high * data_width + argmax_w_high];\n  }\n\n  return weight;\n}\n\ntemplate <typename scalar_t>\n__global__ void deformable_2d_im2col_gpu_kernel(const int n,\n                                                const scalar_t *data_im, const scalar_t *data_offset,\n                                                const int height, const int width, const int kernel_h,\n                                                const int kernel_w,\n                                                const int pad_h, const int pad_w,\n                                                const int stride_h, const int stride_w,\n                                                const int dilation_h, const int dilation_w,\n                                                const int channel_per_deformable_group,\n                                                const int batch_size, const int num_channels,\n                                                const int deformable_group,\n                                                const int height_col, const int width_col,\n                                                scalar_t *data_col)\n{\n  // launch channels * batch_size * height_col * width_col cores\n  CUDA_KERNEL_LOOP(index, n)\n  {\n    // NOTE(CharlesShang): different from Dai Jifeng's MXNet implementation, col_buffer is of shape (c*kw*kh, N, oh, ow)\n    // here columns is of shape (N, c*kw*kh, oh * ow), need to adapt axis\n    // NOTE(Jiarui XU): different from CharlesShang's implementation, col_buffer is of shape (N, c*kw*kh, oh * ow)\n    // here columns is of shape (c*kw*kh, N, oh, ow), need to adapt axis\n\n    // index index of output matrix\n    const int w_col = index % width_col;\n    const int h_col = (index / width_col) % height_col;\n    const int b_col = (index / width_col / height_col) % batch_size;\n    const int c_im = (index / width_col / height_col) / batch_size;\n    const int c_col = c_im * kernel_h * kernel_w;\n\n    // compute deformable group index\n    const int deformable_group_index = c_im / channel_per_deformable_group;\n\n    const int h_in = h_col * stride_h - pad_h;\n    const int w_in = w_col * stride_w - pad_w;\n\n     scalar_t *data_col_ptr = data_col + ((c_col * batch_size + b_col) * height_col + h_col) * width_col + w_col;\n    // const scalar_t* data_im_ptr = data_im + ((b_col * num_channels + c_im) * height + h_in) * width + w_in;\n    const scalar_t *data_im_ptr = data_im + (b_col * num_channels + c_im) * height * width;\n    const scalar_t *data_offset_ptr = data_offset + (b_col * deformable_group + deformable_group_index) * 2 * kernel_h * kernel_w * height_col * width_col;\n\n    for (int i = 0; i < kernel_h; ++i)\n    {\n      for (int j = 0; j < kernel_w; ++j)\n      {\n        const int data_offset_h_ptr = ((2 * (i * kernel_w + j)) * height_col + h_col) * width_col + w_col;\n        const int data_offset_w_ptr = ((2 * (i * kernel_w + j) + 1) * height_col + h_col) * width_col + w_col;\n        const scalar_t offset_h = data_offset_ptr[data_offset_h_ptr];\n        const scalar_t offset_w = data_offset_ptr[data_offset_w_ptr];\n        scalar_t val = static_cast<scalar_t>(0);\n        const scalar_t h_im = h_in + i * dilation_h + offset_h;\n        const scalar_t w_im = w_in + j * dilation_w + offset_w;\n        if (h_im > -1 && w_im > -1 && h_im < height && w_im < width)\n        {\n          //const scalar_t map_h = i * dilation_h + offset_h;\n          //const scalar_t map_w = j * dilation_w + offset_w;\n          //const int cur_height = height - h_in;\n          //const int cur_width = width - w_in;\n          //val = dmcn_im2col_bilinear(data_im_ptr, width, cur_height, cur_width, map_h, map_w);\n          val = dmcn_2d_im2col_bilinear(data_im_ptr, width, height, width, h_im, w_im);\n        }\n        *data_col_ptr = val;\n        data_col_ptr += batch_size * height_col * width_col;\n      }\n    }\n  }\n}\n\ntemplate <typename scalar_t>\n__global__ void deformable_2d_col2im_gpu_kernel(const int n,\n                                                const scalar_t *data_col, const scalar_t *data_offset,\n                                                const int channels, const int height, const int width,\n                                                const int kernel_h, const int kernel_w,\n                                                const int pad_h, const int pad_w,\n                                                const int stride_h, const int stride_w,\n                                                const int dilation_h, const int dilation_w,\n                                                const int channel_per_deformable_group,\n                                                const int batch_size, const int deformable_group,\n                                                const int height_col, const int width_col,\n                                                scalar_t *grad_im)\n{\n  CUDA_KERNEL_LOOP(index, n)\n  {\n    const int j = (index / width_col / height_col / batch_size) % kernel_w;\n    const int i = (index / width_col / height_col / batch_size / kernel_w) % kernel_h;\n    const int c = index / width_col / height_col / batch_size / kernel_w / kernel_h;\n    // compute the start and end of the output\n\n    const int deformable_group_index = c / channel_per_deformable_group;\n\n    int w_out = index % width_col;\n    int h_out = (index / width_col) % height_col;\n    int b = (index / width_col / height_col) % batch_size;\n    int w_in = w_out * stride_w - pad_w;\n    int h_in = h_out * stride_h - pad_h;\n\n    const scalar_t *data_offset_ptr = data_offset + (b * deformable_group + deformable_group_index) * 2 * kernel_h * kernel_w * height_col * width_col;\n    const int data_offset_h_ptr = ((2 * (i * kernel_w + j)) * height_col + h_out) * width_col + w_out;\n    const int data_offset_w_ptr = ((2 * (i * kernel_w + j) + 1) * height_col + h_out) * width_col + w_out;\n    const scalar_t offset_h = data_offset_ptr[data_offset_h_ptr];\n    const scalar_t offset_w = data_offset_ptr[data_offset_w_ptr];\n    const scalar_t cur_inv_h_data = h_in + i * dilation_h + offset_h;\n    const scalar_t cur_inv_w_data = w_in + j * dilation_w + offset_w;\n\n    const scalar_t cur_top_grad = data_col[index];\n    const int cur_h = (int)cur_inv_h_data;\n    const int cur_w = (int)cur_inv_w_data;\n    for (int dy = -2; dy <= 2; dy++)\n    {\n      for (int dx = -2; dx <= 2; dx++)\n      {\n        if (cur_h + dy >= 0 && cur_h + dy < height &&\n            cur_w + dx >= 0 && cur_w + dx < width &&\n            abs(cur_inv_h_data - (cur_h + dy)) < 1 &&\n            abs(cur_inv_w_data - (cur_w + dx)) < 1)\n        {\n          int cur_bottom_grad_pos = ((b * channels + c) * height + cur_h + dy) * width + cur_w + dx;\n          scalar_t weight = dmcn_2d_get_gradient_weight(cur_inv_h_data, cur_inv_w_data, cur_h + dy, cur_w + dx, height, width);\n          atomicAdd(grad_im + cur_bottom_grad_pos, weight * cur_top_grad);\n        }\n      }\n    }\n  }\n}\n\ntemplate <typename scalar_t>\n__global__ void deformable_2d_col2im_coord_gpu_kernel(const int n,\n                                                      const scalar_t *data_col, const scalar_t *data_im,\n                                                      const scalar_t *data_offset,\n                                                      const int channels, const int height, const int width,\n                                                      const int kernel_h, const int kernel_w,\n                                                      const int pad_h, const int pad_w,\n                                                      const int stride_h, const int stride_w,\n                                                      const int dilation_h, const int dilation_w,\n                                                      const int channel_per_deformable_group,\n                                                      const int batch_size, const int offset_channels,\n                                                      const int deformable_group,\n                                                      const int height_col, const int width_col,\n                                                      scalar_t *grad_offset)\n{\n  CUDA_KERNEL_LOOP(index, n)\n  {\n    scalar_t val = 0;\n    int w = index % width_col;\n    int h = (index / width_col) % height_col;\n    int c = (index / width_col / height_col) % offset_channels;\n    int b = (index / width_col / height_col) / offset_channels;\n    // compute the start and end of the output\n\n    const int deformable_group_index = c / (2 * kernel_h * kernel_w);\n    const int col_step = kernel_h * kernel_w;\n    int cnt = 0;\n    const scalar_t *data_col_ptr = data_col + deformable_group_index * channel_per_deformable_group * batch_size * width_col * height_col;\n    const scalar_t *data_im_ptr = data_im + (b * deformable_group + deformable_group_index) * channel_per_deformable_group / kernel_h / kernel_w * height * width;\n    const scalar_t *data_offset_ptr = data_offset + (b * deformable_group + deformable_group_index) * 2 * kernel_h * kernel_w * height_col * width_col;\n\n    const int offset_c = c - deformable_group_index * 2 * kernel_h * kernel_w;\n\n    for (int col_c = (offset_c / 2); col_c < channel_per_deformable_group; col_c += col_step)\n    {\n      const int col_pos = (((col_c * batch_size + b) * height_col) + h) * width_col + w;\n      const int bp_dir = offset_c % 2;\n\n      int j = (col_pos / width_col / height_col / batch_size) % kernel_w;\n      int i = (col_pos / width_col / height_col / batch_size / kernel_w) % kernel_h;\n      int w_out = col_pos % width_col;\n      int h_out = (col_pos / width_col) % height_col;\n      int w_in = w_out * stride_w - pad_w;\n      int h_in = h_out * stride_h - pad_h;\n      const int data_offset_h_ptr = (((2 * (i * kernel_w + j)) * height_col + h_out) * width_col + w_out);\n      const int data_offset_w_ptr = (((2 * (i * kernel_w + j) + 1) * height_col + h_out) * width_col + w_out);\n      const scalar_t offset_h = data_offset_ptr[data_offset_h_ptr];\n      const scalar_t offset_w = data_offset_ptr[data_offset_w_ptr];\n      scalar_t inv_h = h_in + i * dilation_h + offset_h;\n      scalar_t inv_w = w_in + j * dilation_w + offset_w;\n      if (inv_h <= -1 || inv_w <= -1 || inv_h >= height || inv_w >= width)\n      {\n        inv_h = inv_w = -2;\n      }\n      const scalar_t weight = dmcn_2d_get_coordinate_weight(\n          inv_h, inv_w,\n          height, width, data_im_ptr + cnt * height * width, width, bp_dir);\n      val += weight * data_col_ptr[col_pos];\n      cnt += 1;\n    }\n    // KERNEL_ASSIGN(grad_offset[index], offset_req, val);\n    grad_offset[index] = val;\n  }\n}\n\ntemplate <typename scalar_t>\nvoid deformable_2d_im2col_cuda(cudaStream_t stream,\n                               const scalar_t *data_im, const scalar_t *data_offset,\n                               const int batch_size, const int channels, const int height_im, const int width_im,\n                               const int height_col, const int width_col, const int kernel_h, const int kernel_w,\n                               const int pad_h, const int pad_w, const int stride_h, const int stride_w,\n                               const int dilation_h, const int dilation_w,\n                               const int deformable_group, scalar_t *data_col) {\n  // num_axes should be smaller than block size\n  const int channel_per_deformable_group = channels / deformable_group;\n  const int num_kernels = channels * batch_size * height_col * width_col;\n  deformable_2d_im2col_gpu_kernel<scalar_t>\n      <<<GET_BLOCKS(num_kernels), CUDA_NUM_THREADS,\n          0, stream>>>(\n      num_kernels, data_im, data_offset, height_im, width_im, kernel_h, kernel_w,\n      pad_h, pad_w, stride_h, stride_w, dilation_h, dilation_w, channel_per_deformable_group,\n      batch_size, channels, deformable_group, height_col, width_col, data_col);\n  \n  cudaError_t err = cudaGetLastError();\n  if (err != cudaSuccess)\n  {\n    printf(\"error in deformable_im2col_cuda: %s\\n\", cudaGetErrorString(err));\n  }\n\n}\n\ntemplate <typename scalar_t>\nvoid deformable_2d_col2im_cuda(cudaStream_t stream,\n                               const scalar_t *data_col, const scalar_t *data_offset,\n                               const int batch_size, const int channels, const int height_im, const int width_im,\n                               const int height_col, const int width_col, const int kernel_h, const int kernel_w,\n                               const int pad_h, const int pad_w, const int stride_h, const int stride_w,\n                               const int dilation_h, const int dilation_w,\n                               const int deformable_group, scalar_t *grad_im){\n\n  const int channel_per_deformable_group = channels / deformable_group;\n  const int num_kernels = channels * kernel_h * kernel_w * batch_size * height_col * width_col;\n  deformable_2d_col2im_gpu_kernel<scalar_t>\n      <<<GET_BLOCKS(num_kernels), CUDA_NUM_THREADS,\n          0, stream>>>(\n        num_kernels, data_col, data_offset, channels, height_im, width_im,\n        kernel_h, kernel_w, pad_h, pad_h, stride_h, stride_w,\n        dilation_h, dilation_w, channel_per_deformable_group,\n        batch_size, deformable_group, height_col, width_col, grad_im);\n  cudaError_t err = cudaGetLastError();\n  if (err != cudaSuccess)\n  {\n    printf(\"error in deformable_col2im_cuda: %s\\n\", cudaGetErrorString(err));\n  }\n\n}\n\ntemplate <typename scalar_t>\nvoid deformable_2d_col2im_coord_cuda(cudaStream_t stream,\n                                     const scalar_t *data_col, const scalar_t *data_im, const scalar_t *data_offset,\n                                     const int batch_size, const int channels, const int height_im, const int width_im,\n                                     const int height_col, const int width_col, const int kernel_h, const int kernel_w,\n                                     const int pad_h, const int pad_w, const int stride_h, const int stride_w,\n                                     const int dilation_h, const int dilation_w,\n                                     const int deformable_group,\n                                     scalar_t *grad_offset) {\n  const int num_kernels = batch_size * height_col * width_col * 2 * kernel_h * kernel_w * deformable_group;\n  const int channel_per_deformable_group = channels * kernel_h * kernel_w / deformable_group;\n  deformable_2d_col2im_coord_gpu_kernel<scalar_t>\n      <<<GET_BLOCKS(num_kernels), CUDA_NUM_THREADS,\n        0, stream>>>(\n        num_kernels, data_col, data_im, data_offset, channels, height_im, width_im,\n        kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w,\n        dilation_h, dilation_w, channel_per_deformable_group,\n        batch_size, 2 * kernel_h * kernel_w * deformable_group, deformable_group, height_col, width_col, \n        grad_offset);\n  cudaError_t err = cudaGetLastError();\n  if (err != cudaSuccess)\n  {\n    printf(\"error in deformable_col2im_coord_cuda: %s\\n\", cudaGetErrorString(err));\n  }\n}"
  },
  {
    "path": "utils/DCN/src/cuda/deform_conv2d_cuda.cu",
    "content": "#include <vector>\n#include \"cuda/deform_2d_im2col_cuda.cuh\"\n\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n// #include <THC/THC.h>\n// #include <THC/THCAtomics.cuh>\n// #include <THC/THCDeviceUtils.cuh>\n\n// extern THCState *state;\n\n// author: Charles Shang\n// https://github.com/torch/cunn/blob/master/lib/THCUNN/generic/SpatialConvolutionMM.cu\n\n\nat::Tensor\ndeform_conv2d_cuda_forward(const at::Tensor &input,\n                           const at::Tensor &weight,\n                           const at::Tensor &bias,\n                           const at::Tensor &offset,\n                           const int kernel_h,\n                           const int kernel_w,\n                           const int stride_h,\n                           const int stride_w,\n                           const int pad_h,\n                           const int pad_w,\n                           const int dilation_h,\n                           const int dilation_w,\n                           const int group,\n                           const int deformable_group,\n                           const int im2col_step)\n{\n    // THCAssertSameGPU(THCudaTensor_checkGPU(state, 5, input, weight, bias, offset, mask));\n\n    AT_ASSERTM(input.is_contiguous(), \"input tensor has to be contiguous\");\n    AT_ASSERTM(weight.is_contiguous(), \"weight tensor has to be contiguous\");\n\n    AT_ASSERTM(input.type().is_cuda(), \"input must be a CUDA tensor\");\n    AT_ASSERTM(weight.type().is_cuda(), \"weight must be a CUDA tensor\");\n    AT_ASSERTM(bias.type().is_cuda(), \"bias must be a CUDA tensor\");\n    AT_ASSERTM(offset.type().is_cuda(), \"offset must be a CUDA tensor\");\n\n    const int batch = input.size(0);\n    const int channels = input.size(1);\n    const int height = input.size(2);\n    const int width = input.size(3);\n\n    const int channels_out = weight.size(0);\n    const int channels_kernel = weight.size(1);\n    const int kernel_h_ = weight.size(2);\n    const int kernel_w_ = weight.size(3);\n\n    const int im2col_step_ = std::min(batch, im2col_step);\n\n    AT_ASSERTM(batch % im2col_step_ == 0, \"batch(%d) must divide im2col_step(%d)\", batch, im2col_step_);\n\n    AT_ASSERTM((channels % group == 0) && (channels_out % group == 0), \n        \"channels(%d) and channels_out(%d) must divide group(%d)\", channels, channels_out, group);\n\n    // printf(\"Kernels: %d %d %d %d\\n\", kernel_h_, kernel_w_, kernel_w, kernel_h);\n    // printf(\"Channels: %d %d\\n\", channels, channels_kernel);\n    // printf(\"Channels: %d %d\\n\", channels_out, channels_kernel);\n\n    AT_ASSERTM(kernel_h_ == kernel_h && kernel_w_ == kernel_w,\n               \"Input shape and kernel shape wont match: (%d x %d vs %d x %d).\", kernel_h_, kernel_w, kernel_h_, kernel_w_);\n\n    AT_ASSERTM(channels == (channels_kernel * group),\n               \"Input shape and kernel channels wont match: (%d vs %d).\", channels, channels_kernel * group);\n\n    const int height_out = (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1;\n    const int width_out = (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1;\n\n    auto output = at::empty({batch * height_out * width_out, channels_out}, input.options());\n\n    // prepare group weight and bias\n    auto weight_g = weight.view({group, channels_out/group, channels_kernel, kernel_h, kernel_w});\n    auto bias_g = bias.view({group, channels_out/group});\n\n    // define alias for easy use\n    const int batch_n = im2col_step_;\n    const int per_input_size = channels * height * width;\n    const int per_offset_size = offset.size(1) * offset.size(2) * offset.size(3);\n    auto output_n = output.view({batch/im2col_step_, batch_n * height_out * width_out, channels_out});\n    for (int n = 0; n < batch/im2col_step_; ++n)\n    {\n        auto columns = at::empty({channels * kernel_h * kernel_w, batch_n * height_out * width_out}, input.options());\n        AT_DISPATCH_FLOATING_TYPES(input.type(), \"deform_conv_forward_cuda\", ([&] {\n            deformable_2d_im2col_cuda(at::cuda::getCurrentCUDAStream(),\n                                             input.data<scalar_t>() + n * im2col_step_ * per_input_size,\n                                             offset.data<scalar_t>() + n * im2col_step_ * per_offset_size,\n                                             batch_n, channels, height, width,\n                                             height_out, width_out, kernel_h, kernel_w,\n                                             pad_h, pad_w, stride_h, stride_w, dilation_h, dilation_w,\n                                             deformable_group,\n                                             columns.data<scalar_t>());\n\n        }));\n\n        // auto columns_m = columns.t();\n        // auto weight_m = weight.view({channels_out, channels_kernel * kernel_h * kernel_w}).t();\n        // output = at::addmm(bias, columns_m, weight_m);\n        auto columns_g = columns.view({group, channels/group * kernel_h * kernel_w, batch_n * height_out * width_out});\n        auto output_g = output_n.select(0, n).view({batch_n * height_out * width_out, group, channels_out/group});\n        for (int g = 0; g < group; ++g)\n        {\n            auto columns_gm = columns_g.select(0, g).t();\n            auto weight_gm = weight_g.select(0, g).view({channels_out/group, channels_kernel * kernel_h * kernel_w}).t();\n            auto output_m = at::addmm(bias_g.select(0, g), columns_gm, weight_gm);\n            output_g.select(1, g) = output_m.view({batch_n * height_out * width_out, channels_out/group});\n        }\n\n    }\n\n    output = output.view({batch, height_out, width_out, channels_out}).permute({0, 3, 1, 2}).contiguous();\n\n    return output;\n}\n\nstd::vector<at::Tensor> deform_conv2d_cuda_backward(const at::Tensor &input,\n                                                    const at::Tensor &weight,\n                                                    const at::Tensor &bias,\n                                                    const at::Tensor &offset,\n                                                    const at::Tensor &grad_output,\n                                                    const int kernel_h,\n                                                    const int kernel_w,\n                                                    const int stride_h,\n                                                    const int stride_w,\n                                                    const int pad_h,\n                                                    const int pad_w,\n                                                    const int dilation_h,\n                                                    const int dilation_w,\n                                                    const int group,\n                                                    const int deformable_group,\n                                                    const int im2col_step)\n{\n\n    AT_ASSERTM(input.is_contiguous(), \"input tensor has to be contiguous\");\n    AT_ASSERTM(weight.is_contiguous(), \"weight tensor has to be contiguous\");\n\n    AT_ASSERTM(input.type().is_cuda(), \"input must be a CUDA tensor\");\n    AT_ASSERTM(weight.type().is_cuda(), \"weight must be a CUDA tensor\");\n    AT_ASSERTM(bias.type().is_cuda(), \"bias must be a CUDA tensor\");\n    AT_ASSERTM(offset.type().is_cuda(), \"offset must be a CUDA tensor\");\n\n    const int batch = input.size(0);\n    const int channels = input.size(1);\n    const int height = input.size(2);\n    const int width = input.size(3);\n\n    const int channels_out = weight.size(0);\n    const int channels_kernel = weight.size(1);\n    const int kernel_h_ = weight.size(2);\n    const int kernel_w_ = weight.size(3);\n\n    const int batch_ = grad_output.size(0);\n    const int channels_out_ = grad_output.size(1);\n    const int height_out_ = grad_output.size(2);\n    const int width_out_ = grad_output.size(3);\n\n    const int im2col_step_ = std::min(im2col_step, batch);\n\n    AT_ASSERTM(batch % im2col_step_ == 0, \"batch(%d) must divide im2col_step(%d)\", batch, im2col_step_);\n\n    AT_ASSERTM((channels % group == 0) && (channels_out % group == 0), \n        \"channels(%d) and channels_out(%d) must divide group(%d)\", channels, channels_out, group);\n\n    AT_ASSERTM(kernel_h_ == kernel_h && kernel_w_ == kernel_w,\n               \"Input shape and kernel shape wont match: (%d x %d vs %d x %d).\", kernel_h_, kernel_w, kernel_h_, kernel_w_);\n\n    AT_ASSERTM(channels == (channels_kernel * group),\n               \"Input shape and kernel channels wont match: (%d vs %d).\", channels, channels_kernel * group);\n\n    const int height_out = (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1;\n    const int width_out = (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1;\n\n    AT_ASSERTM(batch == batch_,\n               \"Input shape and grad_out batch wont match: (%d vs %d).\", batch, batch_);\n\n    AT_ASSERTM(channels_out == channels_out_,\n               \"Input shape and grad_out channels_out wont match: (%d vs %d).\", channels_out, channels_out_);\n\n    AT_ASSERTM(height_out == height_out_ && width_out == width_out_,\n               \"Input shape and grad_out shape wont match: (%d x %d vs %d x %d).\", height_out, height_out_, width_out, width_out_);\n\n    auto grad_input = at::zeros_like(input);\n    auto grad_offset = at::zeros_like(offset);\n    auto grad_weight = at::zeros_like(weight);\n    auto grad_bias = at::zeros_like(bias);\n\n    // auto grad_output_m = grad_output.permute({1, 0, 2, 3}).contiguous().view({channels_out, batch * height_out * width_out});\n    // auto weight_m = weight.view({channels_out, channels_kernel * kernel_h * kernel_w}).t();\n    // columns = at::mm(weight_m, grad_output_m);\n\n    // prepare group weight and bias\n    auto weight_g = weight.view({group, channels_out/group, channels_kernel, kernel_h, kernel_w});\n    auto grad_weight_g = grad_weight.view({group, channels_out/group, channels_kernel, kernel_h, kernel_w});\n    auto grad_bias_g = grad_bias.view({group, channels_out/group});\n\n    const int batch_n = im2col_step_;\n    const int per_input_size = channels * height * width;\n    const int per_offset_size = offset.size(1) * offset.size(2) * offset.size(3);\n    auto grad_output_n = grad_output.view({batch/im2col_step_, batch_n, channels_out, height_out, width_out});\n    for (int n = 0; n < batch/im2col_step_; ++n)\n    {\n        auto grad_output_g = grad_output_n.select(0, n).view({batch_n, group, channels_out/group, height_out, width_out});\n        auto ones = at::ones({batch_n * height_out * width_out}, input.options());\n        auto columns = at::empty({channels * kernel_h * kernel_w, batch_n * 1 * height_out * width_out}, input.options());\n        auto columns_g = columns.view({group, channels/group * kernel_h * kernel_w, batch_n * height_out * width_out});\n        for (int g = 0; g < group; ++g)\n        {\n            auto grad_output_gm = grad_output_g.select(1, g).permute({1, 0, 2, 3}).contiguous().view({channels_out/group, batch_n * height_out * width_out});\n            auto weight_gm = weight_g.select(0, g).view({channels_out/group, channels_kernel * kernel_h * kernel_w}).t();\n            columns_g.select(0, g) = at::mm(weight_gm, grad_output_gm);\n        }\n\n        AT_DISPATCH_FLOATING_TYPES(input.type(), \"deform_conv_backward_cuda\", ([&] {\n            deformable_2d_col2im_coord_cuda(at::cuda::getCurrentCUDAStream(),\n                                                   columns.data<scalar_t>(),\n                                                   input.data<scalar_t>() + n * im2col_step_ * per_input_size,\n                                                   offset.data<scalar_t>() + n * im2col_step_ * per_offset_size,\n                                                   batch_n, channels, height, width,\n                                                   height_out, width_out, kernel_h, kernel_w,\n                                                   pad_h, pad_w, stride_h, stride_w,\n                                                   dilation_h, dilation_w, deformable_group,\n                                                   grad_offset.data<scalar_t>() + n * im2col_step_ * per_offset_size);\n            // gradient w.r.t. input data\n            deformable_2d_col2im_cuda(at::cuda::getCurrentCUDAStream(),\n                                             columns.data<scalar_t>(),\n                                             offset.data<scalar_t>() + n * im2col_step_ * per_offset_size,\n                                             batch_n, channels, height, width,\n                                             height_out, width_out, kernel_h, kernel_w,\n                                             pad_h, pad_w, stride_h, stride_w,\n                                             dilation_h, dilation_w, deformable_group,\n                                             grad_input.data<scalar_t>() + n * im2col_step_ * per_input_size);\n\n            // gradient w.r.t. weight, dWeight should accumulate across the batch and group\n            deformable_2d_im2col_cuda(at::cuda::getCurrentCUDAStream(),\n                                             input.data<scalar_t>() + n * im2col_step_ * per_input_size,\n                                             offset.data<scalar_t>() + n * im2col_step_ * per_offset_size,\n                                             batch_n, channels, height, width,\n                                             height_out, width_out, kernel_h, kernel_w,\n                                             pad_h, pad_w, stride_h, stride_w,\n                                             dilation_h, dilation_w, deformable_group,\n                                             columns.data<scalar_t>());\n\n        }));\n\n        // auto grad_output_m = grad_output.permute({1, 0, 2, 3}).contiguous().view({channels_out, batch * height_out * width_out});\n        // grad_weight = at::mm(grad_output_m, columns.t()).view_as(weight);\n        // grad_bias = at::mv(grad_output_m, ones);\n        // auto grad_output_g = grad_output.view({batch, group, channels_out/group, height_out, width_out});\n        // auto columns_g = columns.view({group, channels/group * kernel_h * kernel_w, batch * height_out * width_out});\n        for (int g = 0; g < group; ++g)\n        {\n            auto grad_output_gm = grad_output_g.select(1, g).permute({1, 0, 2, 3}).contiguous().view({channels_out/group, batch_n * height_out * width_out});\n            auto columns_gm = columns_g.select(0, g).t();\n            auto grad_weight_gm = grad_weight_g.select(0, g).view({channels_out/group, channels_kernel * kernel_h * kernel_w});\n            auto grad_bias_gm = grad_bias_g.select(0, g);\n            grad_weight_g.select(0, g) = at::addmm(grad_weight_gm, grad_output_gm, columns_gm).view_as(grad_weight_g.select(0, g));\n            grad_bias_g.select(0, g) = at::addmv(grad_bias_gm, grad_output_gm, ones);\n        }\n\n    }\n\n    return {\n        grad_input, grad_offset, grad_weight, grad_bias\n    };\n}\n"
  },
  {
    "path": "utils/DCN/src/cuda/deform_conv2d_cuda.h",
    "content": "#pragma once\n#include <torch/extension.h>\n\nat::Tensor\ndeform_conv2d_cuda_forward(const at::Tensor &input,\n                           const at::Tensor &weight,\n                           const at::Tensor &bias,\n                           const at::Tensor &offset,\n                           const int kernel_h,\n                           const int kernel_w,\n                           const int stride_h,\n                           const int stride_w,\n                           const int pad_h,\n                           const int pad_w,\n                           const int dilation_h,\n                           const int dilation_w,\n                           const int group,\n                           const int deformable_group,\n                           const int im2col_step);\n\nstd::vector<at::Tensor>\ndeform_conv2d_cuda_backward(const at::Tensor &input,\n                            const at::Tensor &weight,\n                            const at::Tensor &bias,\n                            const at::Tensor &offset,\n                            const at::Tensor &grad_output,\n                            const int kernel_h,\n                            const int kernel_w,\n                            const int stride_h,\n                            const int stride_w,\n                            const int pad_h,\n                            const int pad_w,\n                            const int dilation_h,\n                            const int dilation_w,\n                            const int group,\n                            const int deformable_group,\n                            const int im2col_step);\n\n"
  },
  {
    "path": "utils/DCN/src/cuda/modulated_deform_2d_im2col_cuda.cuh",
    "content": "#include <cstdio>\n#include <algorithm>\n#include <cstring>\n\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n\n// #include <THC/THC.h>\n#include <THC/THCAtomics.cuh>\n// #include <THC/THCDeviceUtils.cuh>\n\n#define CUDA_KERNEL_LOOP(i, n)                          \\\n  for (int i = blockIdx.x * blockDim.x + threadIdx.x;   \\\n      i < (n);                                          \\\n      i += blockDim.x * gridDim.x)\n\nconst int CUDA_NUM_THREADS = 1024;\ninline int GET_BLOCKS(const int N)\n{\n  return (N + CUDA_NUM_THREADS - 1) / CUDA_NUM_THREADS;\n}\n\n\ntemplate <typename scalar_t>\n__device__ scalar_t mdmcn_2d_im2col_bilinear(const scalar_t *bottom_data, const int data_width,\n                                             const int height, const int width, scalar_t h, scalar_t w)\n{\n  int h_low = floor(h);\n  int w_low = floor(w);\n  int h_high = h_low + 1;\n  int w_high = w_low + 1;\n\n  scalar_t lh = h - h_low;\n  scalar_t lw = w - w_low;\n  scalar_t hh = 1 - lh, hw = 1 - lw;\n\n  scalar_t v1 = 0;\n  if (h_low >= 0 && w_low >= 0)\n    v1 = bottom_data[h_low * data_width + w_low];\n  scalar_t v2 = 0;\n  if (h_low >= 0 && w_high <= width - 1)\n    v2 = bottom_data[h_low * data_width + w_high];\n  scalar_t v3 = 0;\n  if (h_high <= height - 1 && w_low >= 0)\n    v3 = bottom_data[h_high * data_width + w_low];\n  scalar_t v4 = 0;\n  if (h_high <= height - 1 && w_high <= width - 1)\n    v4 = bottom_data[h_high * data_width + w_high];\n\n  scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;\n\n  scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);\n  return val;\n}\n\ntemplate <typename scalar_t>\n__device__ scalar_t mdmcn_2d_get_gradient_weight(scalar_t argmax_h, scalar_t argmax_w,\n                                          const int h, const int w, const int height, const int width)\n{\n  if (argmax_h <= -1 || argmax_h >= height || argmax_w <= -1 || argmax_w >= width)\n  {\n    //empty\n    return 0;\n  }\n\n  int argmax_h_low = floor(argmax_h);\n  int argmax_w_low = floor(argmax_w);\n  int argmax_h_high = argmax_h_low + 1;\n  int argmax_w_high = argmax_w_low + 1;\n\n  scalar_t weight = 0;\n  if (h == argmax_h_low && w == argmax_w_low)\n    weight = (h + 1 - argmax_h) * (w + 1 - argmax_w);\n  if (h == argmax_h_low && w == argmax_w_high)\n    weight = (h + 1 - argmax_h) * (argmax_w + 1 - w);\n  if (h == argmax_h_high && w == argmax_w_low)\n    weight = (argmax_h + 1 - h) * (w + 1 - argmax_w);\n  if (h == argmax_h_high && w == argmax_w_high)\n    weight = (argmax_h + 1 - h) * (argmax_w + 1 - w);\n  return weight;\n}\n\ntemplate <typename scalar_t>\n__device__ scalar_t mdmcn_2d_get_coordinate_weight(scalar_t argmax_h, scalar_t argmax_w,\n                                            const int height, const int width, const scalar_t *im_data,\n                                            const int data_width, const int bp_dir)\n{\n  if (argmax_h <= -1 || argmax_h >= height || argmax_w <= -1 || argmax_w >= width)\n  {\n    //empty\n    return 0;\n  }\n\n  int argmax_h_low = floor(argmax_h);\n  int argmax_w_low = floor(argmax_w);\n  int argmax_h_high = argmax_h_low + 1;\n  int argmax_w_high = argmax_w_low + 1;\n\n  scalar_t weight = 0;\n\n  if (bp_dir == 0)\n  {\n    if (argmax_h_low >= 0 && argmax_w_low >= 0)\n      weight += -1 * (argmax_w_low + 1 - argmax_w) * im_data[argmax_h_low * data_width + argmax_w_low];\n    if (argmax_h_low >= 0 && argmax_w_high <= width - 1)\n      weight += -1 * (argmax_w - argmax_w_low) * im_data[argmax_h_low * data_width + argmax_w_high];\n    if (argmax_h_high <= height - 1 && argmax_w_low >= 0)\n      weight += (argmax_w_low + 1 - argmax_w) * im_data[argmax_h_high * data_width + argmax_w_low];\n    if (argmax_h_high <= height - 1 && argmax_w_high <= width - 1)\n      weight += (argmax_w - argmax_w_low) * im_data[argmax_h_high * data_width + argmax_w_high];\n  }\n  else if (bp_dir == 1)\n  {\n    if (argmax_h_low >= 0 && argmax_w_low >= 0)\n      weight += -1 * (argmax_h_low + 1 - argmax_h) * im_data[argmax_h_low * data_width + argmax_w_low];\n    if (argmax_h_low >= 0 && argmax_w_high <= width - 1)\n      weight += (argmax_h_low + 1 - argmax_h) * im_data[argmax_h_low * data_width + argmax_w_high];\n    if (argmax_h_high <= height - 1 && argmax_w_low >= 0)\n      weight += -1 * (argmax_h - argmax_h_low) * im_data[argmax_h_high * data_width + argmax_w_low];\n    if (argmax_h_high <= height - 1 && argmax_w_high <= width - 1)\n      weight += (argmax_h - argmax_h_low) * im_data[argmax_h_high * data_width + argmax_w_high];\n  }\n\n  return weight;\n}\n\ntemplate <typename scalar_t>\n__global__ void modulated_deformable_2d_im2col_gpu_kernel(const int n,\n                                                          const scalar_t *data_im, const scalar_t *data_offset,\n                                                          const scalar_t *data_mask,\n                                                          const int height, const int width, const int kernel_h,\n                                                          const int kernel_w,\n                                                          const int pad_h, const int pad_w,\n                                                          const int stride_h, const int stride_w,\n                                                          const int dilation_h, const int dilation_w,\n                                                          const int channel_per_deformable_group,\n                                                          const int batch_size, const int num_channels,\n                                                          const int deformable_group,\n                                                          const int height_col, const int width_col,\n                                                          scalar_t *data_col)\n{\n  // launch channels * batch_size * height_col * width_col cores\n  CUDA_KERNEL_LOOP(index, n)\n  {\n    // NOTE(CharlesShang): different from Dai Jifeng's MXNet implementation, col_buffer is of shape (c*kw*kh, N, oh, ow)\n    // here columns is of shape (N, c*kw*kh, oh * ow), need to adapt axis\n    // NOTE(Jiarui XU): different from CharlesShang's implementation, col_buffer is of shape (N, c*kw*kh, oh * ow)\n    // here columns is of shape (c*kw*kh, N, oh, ow), need to adapt axis\n\n    // index index of output matrix\n    const int w_col = index % width_col;\n    const int h_col = (index / width_col) % height_col;\n    const int b_col = (index / width_col / height_col) % batch_size;\n    const int c_im = (index / width_col / height_col) / batch_size;\n    const int c_col = c_im * kernel_h * kernel_w;\n\n    // compute deformable group index\n    const int deformable_group_index = c_im / channel_per_deformable_group;\n\n    const int h_in = h_col * stride_h - pad_h;\n    const int w_in = w_col * stride_w - pad_w;\n\n     scalar_t *data_col_ptr = data_col + ((c_col * batch_size + b_col) * height_col + h_col) * width_col + w_col;\n    //const scalar_t* data_im_ptr = data_im + ((b_col * num_channels + c_im) * height + h_in) * width + w_in;\n    const scalar_t *data_im_ptr = data_im + (b_col * num_channels + c_im) * height * width;\n    const scalar_t *data_offset_ptr = data_offset + (b_col * deformable_group + deformable_group_index) * 2 * kernel_h * kernel_w * height_col * width_col;\n\n    const scalar_t *data_mask_ptr = data_mask + (b_col * deformable_group + deformable_group_index) * kernel_h * kernel_w * height_col * width_col;\n\n    for (int i = 0; i < kernel_h; ++i)\n    {\n      for (int j = 0; j < kernel_w; ++j)\n      {\n        const int data_offset_h_ptr = ((2 * (i * kernel_w + j)) * height_col + h_col) * width_col + w_col;\n        const int data_offset_w_ptr = ((2 * (i * kernel_w + j) + 1) * height_col + h_col) * width_col + w_col;\n        const int data_mask_hw_ptr = ((i * kernel_w + j) * height_col + h_col) * width_col + w_col;\n        const scalar_t offset_h = data_offset_ptr[data_offset_h_ptr];\n        const scalar_t offset_w = data_offset_ptr[data_offset_w_ptr];\n        const scalar_t mask = data_mask_ptr[data_mask_hw_ptr];\n        scalar_t val = static_cast<scalar_t>(0);\n        const scalar_t h_im = h_in + i * dilation_h + offset_h;\n        const scalar_t w_im = w_in + j * dilation_w + offset_w;\n        if (h_im > -1 && w_im > -1 && h_im < height && w_im < width)\n        {\n          //const scalar_t map_h = i * dilation_h + offset_h;\n          //const scalar_t map_w = j * dilation_w + offset_w;\n          //const int cur_height = height - h_in;\n          //const int cur_width = width - w_in;\n          //val = dmcn_im2col_bilinear(data_im_ptr, width, cur_height, cur_width, map_h, map_w);\n          val = mdmcn_2d_im2col_bilinear(data_im_ptr, width, height, width, h_im, w_im);\n        }\n        *data_col_ptr = val * mask;\n        data_col_ptr += batch_size * height_col * width_col;\n      }\n    }\n  }\n}\n\ntemplate <typename scalar_t>\n__global__ void modulated_deformable_2d_col2im_gpu_kernel(const int n,\n                                                          const scalar_t *data_col, const scalar_t *data_offset,\n                                                          const scalar_t *data_mask,\n                                                          const int channels, const int height, const int width,\n                                                          const int kernel_h, const int kernel_w,\n                                                          const int pad_h, const int pad_w,\n                                                          const int stride_h, const int stride_w,\n                                                          const int dilation_h, const int dilation_w,\n                                                          const int channel_per_deformable_group,\n                                                          const int batch_size, const int deformable_group,\n                                                          const int height_col, const int width_col,\n                                                          scalar_t *grad_im)\n{\n  CUDA_KERNEL_LOOP(index, n)\n  {\n    const int j = (index / width_col / height_col / batch_size) % kernel_w;\n    const int i = (index / width_col / height_col / batch_size / kernel_w) % kernel_h;\n    const int c = index / width_col / height_col / batch_size / kernel_w / kernel_h;\n    // compute the start and end of the output\n\n    const int deformable_group_index = c / channel_per_deformable_group;\n\n    int w_out = index % width_col;\n    int h_out = (index / width_col) % height_col;\n    int b = (index / width_col / height_col) % batch_size;\n    int w_in = w_out * stride_w - pad_w;\n    int h_in = h_out * stride_h - pad_h;\n\n    const scalar_t *data_offset_ptr = data_offset + (b * deformable_group + deformable_group_index) * 2 * kernel_h * kernel_w * height_col * width_col;\n    const scalar_t *data_mask_ptr = data_mask + (b * deformable_group + deformable_group_index) * kernel_h * kernel_w * height_col * width_col;\n    const int data_offset_h_ptr = ((2 * (i * kernel_w + j)) * height_col + h_out) * width_col + w_out;\n    const int data_offset_w_ptr = ((2 * (i * kernel_w + j) + 1) * height_col + h_out) * width_col + w_out;\n    const int data_mask_hw_ptr = ((i * kernel_w + j) * height_col + h_out) * width_col + w_out;\n    const scalar_t offset_h = data_offset_ptr[data_offset_h_ptr];\n    const scalar_t offset_w = data_offset_ptr[data_offset_w_ptr];\n    const scalar_t mask = data_mask_ptr[data_mask_hw_ptr];\n    const scalar_t cur_inv_h_data = h_in + i * dilation_h + offset_h;\n    const scalar_t cur_inv_w_data = w_in + j * dilation_w + offset_w;\n\n    const scalar_t cur_top_grad = data_col[index] * mask;\n    const int cur_h = (int)cur_inv_h_data;\n    const int cur_w = (int)cur_inv_w_data;\n    for (int dy = -2; dy <= 2; dy++)\n    {\n      for (int dx = -2; dx <= 2; dx++)\n      {\n        if (cur_h + dy >= 0 && cur_h + dy < height &&\n            cur_w + dx >= 0 && cur_w + dx < width &&\n            abs(cur_inv_h_data - (cur_h + dy)) < 1 &&\n            abs(cur_inv_w_data - (cur_w + dx)) < 1)\n        {\n          int cur_bottom_grad_pos = ((b * channels + c) * height + cur_h + dy) * width + cur_w + dx;\n          scalar_t weight = mdmcn_2d_get_gradient_weight(cur_inv_h_data, cur_inv_w_data, cur_h + dy, cur_w + dx, height, width);\n          atomicAdd(grad_im + cur_bottom_grad_pos, weight * cur_top_grad);\n        }\n      }\n    }\n  }\n}\n\ntemplate <typename scalar_t>\n__global__ void modulated_deformable_2d_col2im_coord_gpu_kernel(const int n,\n                                                                const scalar_t *data_col, const scalar_t *data_im,\n                                                                const scalar_t *data_offset, const scalar_t *data_mask,\n                                                                const int channels, const int height, const int width,\n                                                                const int kernel_h, const int kernel_w,\n                                                                const int pad_h, const int pad_w,\n                                                                const int stride_h, const int stride_w,\n                                                                const int dilation_h, const int dilation_w,\n                                                                const int channel_per_deformable_group,\n                                                                const int batch_size, const int offset_channels,\n                                                                const int deformable_group,\n                                                                const int height_col, const int width_col,\n                                                                scalar_t *grad_offset, scalar_t *grad_mask)\n{\n  CUDA_KERNEL_LOOP(index, n)\n  {\n    scalar_t val = 0, mval = 0;\n    int w = index % width_col;\n    int h = (index / width_col) % height_col;\n    int c = (index / width_col / height_col) % offset_channels;\n    int b = (index / width_col / height_col) / offset_channels;\n    // compute the start and end of the output\n\n    const int deformable_group_index = c / (2 * kernel_h * kernel_w);\n    const int col_step = kernel_h * kernel_w;\n    int cnt = 0;\n    const scalar_t *data_col_ptr = data_col + deformable_group_index * channel_per_deformable_group * batch_size * width_col * height_col;\n    const scalar_t *data_im_ptr = data_im + (b * deformable_group + deformable_group_index) * channel_per_deformable_group / kernel_h / kernel_w * height * width;\n    const scalar_t *data_offset_ptr = data_offset + (b * deformable_group + deformable_group_index) * 2 * kernel_h * kernel_w * height_col * width_col;\n    const scalar_t *data_mask_ptr = data_mask + (b * deformable_group + deformable_group_index) * kernel_h * kernel_w * height_col * width_col;\n\n    const int offset_c = c - deformable_group_index * 2 * kernel_h * kernel_w;\n\n    for (int col_c = (offset_c / 2); col_c < channel_per_deformable_group; col_c += col_step)\n    {\n      const int col_pos = (((col_c * batch_size + b) * height_col) + h) * width_col + w;\n      const int bp_dir = offset_c % 2;\n\n      int j = (col_pos / width_col / height_col / batch_size) % kernel_w;\n      int i = (col_pos / width_col / height_col / batch_size / kernel_w) % kernel_h;\n      int w_out = col_pos % width_col;\n      int h_out = (col_pos / width_col) % height_col;\n      int w_in = w_out * stride_w - pad_w;\n      int h_in = h_out * stride_h - pad_h;\n      const int data_offset_h_ptr = (((2 * (i * kernel_w + j)) * height_col + h_out) * width_col + w_out);\n      const int data_offset_w_ptr = (((2 * (i * kernel_w + j) + 1) * height_col + h_out) * width_col + w_out);\n      const int data_mask_hw_ptr = (((i * kernel_w + j) * height_col + h_out) * width_col + w_out);\n      const scalar_t offset_h = data_offset_ptr[data_offset_h_ptr];\n      const scalar_t offset_w = data_offset_ptr[data_offset_w_ptr];\n      const scalar_t mask = data_mask_ptr[data_mask_hw_ptr];\n      scalar_t inv_h = h_in + i * dilation_h + offset_h;\n      scalar_t inv_w = w_in + j * dilation_w + offset_w;\n      if (inv_h <= -1 || inv_w <= -1 || inv_h >= height || inv_w >= width)\n      {\n        inv_h = inv_w = -2;\n      }\n      else\n      {\n        mval += data_col_ptr[col_pos] * mdmcn_2d_im2col_bilinear(data_im_ptr + cnt * height * width, width, height, width, inv_h, inv_w);\n      }\n      const scalar_t weight = mdmcn_2d_get_coordinate_weight(\n          inv_h, inv_w,\n          height, width, data_im_ptr + cnt * height * width, width, bp_dir);\n      val += weight * data_col_ptr[col_pos] * mask;\n      cnt += 1;\n    }\n    // KERNEL_ASSIGN(grad_offset[index], offset_req, val);\n    grad_offset[index] = val;\n    if (offset_c % 2 == 0)\n      // KERNEL_ASSIGN(grad_mask[(((b * deformable_group + deformable_group_index) * kernel_h * kernel_w + offset_c / 2) * height_col + h) * width_col + w], mask_req, mval);\n      grad_mask[(((b * deformable_group + deformable_group_index) * kernel_h * kernel_w + offset_c / 2) * height_col + h) * width_col + w] = mval;\n  }\n}\n\ntemplate <typename scalar_t>\nvoid modulated_deformable_2d_im2col_cuda(cudaStream_t stream,\n                                         const scalar_t *data_im, const scalar_t *data_offset,\n                                         const scalar_t *data_mask,\n                                         const int batch_size, const int channels, const int height_im,\n                                         const int width_im,\n                                         const int height_col, const int width_col, const int kernel_h,\n                                         const int kernel_w,\n                                         const int pad_h, const int pad_w, const int stride_h, const int stride_w,\n                                         const int dilation_h, const int dilation_w,\n                                         const int deformable_group, scalar_t *data_col) {\n  // num_axes should be smaller than block size\n  const int channel_per_deformable_group = channels / deformable_group;\n  const int num_kernels = channels * batch_size * height_col * width_col;\n  modulated_deformable_2d_im2col_gpu_kernel<scalar_t>\n      <<<GET_BLOCKS(num_kernels), CUDA_NUM_THREADS,\n          0, stream>>>(\n      num_kernels, data_im, data_offset, data_mask, height_im, width_im, kernel_h, kernel_w,\n      pad_h, pad_w, stride_h, stride_w, dilation_h, dilation_w, channel_per_deformable_group,\n      batch_size, channels, deformable_group, height_col, width_col, data_col);\n  \n  cudaError_t err = cudaGetLastError();\n  if (err != cudaSuccess)\n  {\n    printf(\"error in modulated_deformable_im2col_cuda: %s\\n\", cudaGetErrorString(err));\n  }\n\n}\n\ntemplate <typename scalar_t>\nvoid modulated_deformable_2d_col2im_cuda(cudaStream_t stream,\n                                         const scalar_t *data_col, const scalar_t *data_offset,\n                                         const scalar_t *data_mask,\n                                         const int batch_size, const int channels, const int height_im,\n                                         const int width_im,\n                                         const int height_col, const int width_col, const int kernel_h,\n                                         const int kernel_w,\n                                         const int pad_h, const int pad_w, const int stride_h, const int stride_w,\n                                         const int dilation_h, const int dilation_w,\n                                         const int deformable_group, scalar_t *grad_im){\n\n  const int channel_per_deformable_group = channels / deformable_group;\n  const int num_kernels = channels * kernel_h * kernel_w * batch_size * height_col * width_col;\n  modulated_deformable_2d_col2im_gpu_kernel<scalar_t>\n      <<<GET_BLOCKS(num_kernels), CUDA_NUM_THREADS,\n          0, stream>>>(\n        num_kernels, data_col, data_offset, data_mask, channels, height_im, width_im,\n        kernel_h, kernel_w, pad_h, pad_h, stride_h, stride_w,\n        dilation_h, dilation_w, channel_per_deformable_group,\n        batch_size, deformable_group, height_col, width_col, grad_im);\n  cudaError_t err = cudaGetLastError();\n  if (err != cudaSuccess)\n  {\n    printf(\"error in modulated_deformable_col2im_cuda: %s\\n\", cudaGetErrorString(err));\n  }\n\n}\n\ntemplate <typename scalar_t>\nvoid modulated_deformable_2d_col2im_coord_cuda(cudaStream_t stream,\n                                               const scalar_t *data_col, const scalar_t *data_im,\n                                               const scalar_t *data_offset, const scalar_t *data_mask,\n                                               const int batch_size, const int channels, const int height_im,\n                                               const int width_im,\n                                               const int height_col, const int width_col, const int kernel_h,\n                                               const int kernel_w,\n                                               const int pad_h, const int pad_w, const int stride_h, const int stride_w,\n                                               const int dilation_h, const int dilation_w,\n                                               const int deformable_group,\n                                               scalar_t *grad_offset, scalar_t *grad_mask) {\n  const int num_kernels = batch_size * height_col * width_col * 2 * kernel_h * kernel_w * deformable_group;\n  const int channel_per_deformable_group = channels * kernel_h * kernel_w / deformable_group;\n  modulated_deformable_2d_col2im_coord_gpu_kernel<scalar_t>\n      <<<GET_BLOCKS(num_kernels), CUDA_NUM_THREADS,\n        0, stream>>>(\n        num_kernels, data_col, data_im, data_offset, data_mask, channels, height_im, width_im,\n        kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w,\n        dilation_h, dilation_w, channel_per_deformable_group,\n        batch_size, 2 * kernel_h * kernel_w * deformable_group, deformable_group, height_col, width_col, \n        grad_offset, grad_mask);\n  cudaError_t err = cudaGetLastError();\n  if (err != cudaSuccess)\n  {\n    printf(\"error in modulated_deformable_col2im_coord_cuda: %s\\n\", cudaGetErrorString(err));\n  }\n}"
  },
  {
    "path": "utils/DCN/src/cuda/modulated_deform_conv2d_cuda.cu",
    "content": "#include <vector>\n#include \"cuda/modulated_deform_2d_im2col_cuda.cuh\"\n\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n// #include <THC/THC.h>\n// #include <THC/THCAtomics.cuh>\n// #include <THC/THCDeviceUtils.cuh>\n\n// extern THCState *state;\n\n// author: Charles Shang\n// https://github.com/torch/cunn/blob/master/lib/THCUNN/generic/SpatialConvolutionMM.cu\n\n\nat::Tensor\nmodulated_deform_conv2d_cuda_forward(const at::Tensor &input,\n                                     const at::Tensor &weight,\n                                     const at::Tensor &bias,\n                                     const at::Tensor &offset,\n                                     const at::Tensor &mask,\n                                     const int kernel_h,\n                                     const int kernel_w,\n                                     const int stride_h,\n                                     const int stride_w,\n                                     const int pad_h,\n                                     const int pad_w,\n                                     const int dilation_h,\n                                     const int dilation_w,\n                                     const int group,\n                                     const int deformable_group,\n                                     const int im2col_step)\n{\n    // THCAssertSameGPU(THCudaTensor_checkGPU(state, 5, input, weight, bias, offset, mask));\n\n    AT_ASSERTM(input.is_contiguous(), \"input tensor has to be contiguous\");\n    AT_ASSERTM(weight.is_contiguous(), \"weight tensor has to be contiguous\");\n\n    AT_ASSERTM(input.type().is_cuda(), \"input must be a CUDA tensor\");\n    AT_ASSERTM(weight.type().is_cuda(), \"weight must be a CUDA tensor\");\n    AT_ASSERTM(bias.type().is_cuda(), \"bias must be a CUDA tensor\");\n    AT_ASSERTM(offset.type().is_cuda(), \"offset must be a CUDA tensor\");\n    AT_ASSERTM(mask.type().is_cuda(), \"mask must be a CUDA tensor\");\n\n    const int batch = input.size(0);\n    const int channels = input.size(1);\n    const int height = input.size(2);\n    const int width = input.size(3);\n\n    const int channels_out = weight.size(0);\n    const int channels_kernel = weight.size(1);\n    const int kernel_h_ = weight.size(2);\n    const int kernel_w_ = weight.size(3);\n\n    const int im2col_step_ = std::min(batch, im2col_step);\n\n    AT_ASSERTM(batch % im2col_step_ == 0, \"batch(%d) must divide im2col_step(%d)\", batch, im2col_step_);\n\n    AT_ASSERTM((channels % group == 0) && (channels_out % group == 0), \n        \"channels(%d) and channels_out(%d) must divide group(%d)\", channels, channels_out, group);\n\n    // printf(\"Kernels: %d %d %d %d\\n\", kernel_h_, kernel_w_, kernel_w, kernel_h);\n    // printf(\"Channels: %d %d\\n\", channels, channels_kernel);\n    // printf(\"Channels: %d %d\\n\", channels_out, channels_kernel);\n\n    AT_ASSERTM(kernel_h_ == kernel_h && kernel_w_ == kernel_w,\n               \"Input shape and kernel shape wont match: (%d x %d vs %d x %d).\", kernel_h_, kernel_w, kernel_h_, kernel_w_);\n\n    AT_ASSERTM(channels == (channels_kernel * group),\n               \"Input shape and kernel channels wont match: (%d vs %d).\", channels, channels_kernel * group);\n\n    const int height_out = (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1;\n    const int width_out = (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1;\n    \n    auto output = at::empty({batch * height_out * width_out, channels_out}, input.options());\n\n    // prepare group weight and bias\n    auto weight_g = weight.view({group, channels_out/group, channels_kernel, kernel_h, kernel_w});\n    auto bias_g = bias.view({group, channels_out/group});\n\n    // define alias for easy use\n    const int batch_n = im2col_step_;\n    const int per_input_size = channels * height * width;\n    const int per_offset_size = offset.size(1) * offset.size(2) * offset.size(3);\n    const int per_mask_size = mask.size(1) * mask.size(2) * mask.size(3);\n    auto output_n = output.view({batch/im2col_step_, batch_n * height_out * width_out, channels_out});\n    for (int n = 0; n < batch/im2col_step_; ++n)\n    {\n        auto columns = at::empty({channels * kernel_h * kernel_w, batch_n * height_out * width_out}, input.options());\n        AT_DISPATCH_FLOATING_TYPES(input.type(), \"deform_conv_forward_cuda\", ([&] {\n            modulated_deformable_2d_im2col_cuda(at::cuda::getCurrentCUDAStream(),\n                                             input.data<scalar_t>() + n * im2col_step_ * per_input_size,\n                                             offset.data<scalar_t>() + n * im2col_step_ * per_offset_size,\n                                             mask.data<scalar_t>() + n * im2col_step_ * per_mask_size,\n                                             batch_n, channels, height, width,\n                                             height_out, width_out, kernel_h, kernel_w,\n                                             pad_h, pad_w, stride_h, stride_w, dilation_h, dilation_w,\n                                             deformable_group,\n                                             columns.data<scalar_t>());\n\n        }));\n\n        auto columns_g = columns.view({group, channels/group * kernel_h * kernel_w, batch_n * height_out * width_out});\n        auto output_g = output_n.select(0, n).view({batch_n * height_out * width_out, group, channels_out/group});\n        for (int g = 0; g < group; ++g)\n        {\n            auto columns_gm = columns_g.select(0, g).t();\n            auto weight_gm = weight_g.select(0, g).view({channels_out/group, channels_kernel * kernel_h * kernel_w}).t();\n            auto output_m = at::addmm(bias_g.select(0, g), columns_gm, weight_gm);\n            output_g.select(1, g) = output_m.view({batch_n * height_out * width_out, channels_out/group});\n        }\n\n    }\n\n    output = output.view({batch, height_out, width_out, channels_out}).permute({0, 3, 1, 2}).contiguous();\n\n    return output;\n}\n\n\nstd::vector<at::Tensor> modulated_deform_conv2d_cuda_backward(const at::Tensor &input,\n                                                              const at::Tensor &weight,\n                                                              const at::Tensor &bias,\n                                                              const at::Tensor &offset,\n                                                              const at::Tensor &mask,\n                                                              const at::Tensor &grad_output,\n                                                              const int kernel_h,\n                                                              const int kernel_w,\n                                                              const int stride_h,\n                                                              const int stride_w,\n                                                              const int pad_h,\n                                                              const int pad_w,\n                                                              const int dilation_h,\n                                                              const int dilation_w,\n                                                              const int group,\n                                                              const int deformable_group,\n                                                              const int im2col_step)\n{\n\n    AT_ASSERTM(input.is_contiguous(), \"input tensor has to be contiguous\");\n    AT_ASSERTM(weight.is_contiguous(), \"weight tensor has to be contiguous\");\n\n    AT_ASSERTM(input.type().is_cuda(), \"input must be a CUDA tensor\");\n    AT_ASSERTM(weight.type().is_cuda(), \"weight must be a CUDA tensor\");\n    AT_ASSERTM(bias.type().is_cuda(), \"bias must be a CUDA tensor\");\n    AT_ASSERTM(offset.type().is_cuda(), \"offset must be a CUDA tensor\");\n    AT_ASSERTM(mask.type().is_cuda(), \"mask must be a CUDA tensor\");\n\n    const int batch = input.size(0);\n    const int channels = input.size(1);\n    const int height = input.size(2);\n    const int width = input.size(3);\n\n    const int channels_out = weight.size(0);\n    const int channels_kernel = weight.size(1);\n    const int kernel_h_ = weight.size(2);\n    const int kernel_w_ = weight.size(3);\n\n    const int batch_ = grad_output.size(0);\n    const int channels_out_ = grad_output.size(1);\n    const int height_out_ = grad_output.size(2);\n    const int width_out_ = grad_output.size(3);\n\n    const int im2col_step_ = std::min(im2col_step, batch);\n\n    AT_ASSERTM(batch % im2col_step_ == 0, \"batch(%d) must divide im2col_step(%d)\", batch, im2col_step_);\n\n    AT_ASSERTM((channels % group == 0) && (channels_out % group == 0), \n        \"channels(%d) and channels_out(%d) must divide group(%d)\", channels, channels_out, group);\n\n    AT_ASSERTM(kernel_h_ == kernel_h && kernel_w_ == kernel_w,\n               \"Input shape and kernel shape wont match: (%d x %d vs %d x %d).\", kernel_h_, kernel_w, kernel_h_, kernel_w_);\n\n    AT_ASSERTM(channels == (channels_kernel * group),\n               \"Input shape and kernel channels wont match: (%d vs %d).\", channels, channels_kernel * group);\n\n    const int height_out = (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1;\n    const int width_out = (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1;\n\n    AT_ASSERTM(batch == batch_,\n               \"Input shape and grad_out batch wont match: (%d vs %d).\", batch, batch_);\n\n    AT_ASSERTM(channels_out == channels_out_,\n               \"Input shape and grad_out channels_out wont match: (%d vs %d).\", channels_out, channels_out_);\n\n    AT_ASSERTM(height_out == height_out_ && width_out == width_out_,\n               \"Input shape and grad_out shape wont match: (%d x %d vs %d x %d).\", height_out, height_out_, width_out, width_out_);\n\n    auto ones = at::ones({batch * height_out * width_out}, input.options());\n    auto columns = at::empty({channels * kernel_h * kernel_w, batch * 1 * height_out * width_out}, input.options());\n\n    auto grad_input = at::zeros_like(input);\n    auto grad_weight = at::zeros_like(weight);\n    auto grad_bias = at::zeros_like(bias);\n    auto grad_offset = at::zeros_like(offset);\n    auto grad_mask = at::zeros_like(mask);\n\n    // prepare group weight and bias\n    auto weight_g = weight.view({group, channels_out/group, channels_kernel, kernel_h, kernel_w});\n    auto grad_weight_g = grad_weight.view({group, channels_out/group, channels_kernel, kernel_h, kernel_w});\n    auto grad_bias_g = grad_bias.view({group, channels_out/group});\n\n    const int batch_n = im2col_step_;\n    const int per_input_size = channels * height * width;\n    const int per_offset_size = offset.size(1) * offset.size(2) * offset.size(3);\n    const int per_mask_size = mask.size(1) * mask.size(2) * mask.size(3);\n    auto grad_output_n = grad_output.view({batch/im2col_step_, batch_n, channels_out, height_out, width_out});\n    for (int n = 0; n < batch/im2col_step_; ++n)\n    {\n        auto grad_output_g = grad_output_n.select(0, n).view({batch_n, group, channels_out/group, height_out, width_out});\n        auto ones = at::ones({batch_n * height_out * width_out}, input.options());\n        auto columns = at::empty({channels * kernel_h * kernel_w, batch_n * 1 * height_out * width_out}, input.options());\n        auto columns_g = columns.view({group, channels/group * kernel_h * kernel_w, batch_n * height_out * width_out});\n        for (int g = 0; g < group; ++g)\n        {\n            auto grad_output_gm = grad_output_g.select(1, g).permute({1, 0, 2, 3}).contiguous().view({channels_out/group, batch_n * height_out * width_out});\n            auto weight_gm = weight_g.select(0, g).view({channels_out/group, channels_kernel * kernel_h * kernel_w}).t();\n            columns_g.select(0, g) = at::mm(weight_gm, grad_output_gm);\n        }\n\n        AT_DISPATCH_FLOATING_TYPES(input.type(), \"deform_conv_backward_cuda\", ([&] {\n            modulated_deformable_2d_col2im_coord_cuda(at::cuda::getCurrentCUDAStream(),\n                                                   columns.data<scalar_t>(),\n                                                   input.data<scalar_t>() + n * im2col_step_ * per_input_size,\n                                                   offset.data<scalar_t>() + n * im2col_step_ * per_offset_size,\n                                                   mask.data<scalar_t>() + n * im2col_step_ * per_mask_size,\n                                                   batch_n, channels, height, width,\n                                                   height_out, width_out, kernel_h, kernel_w,\n                                                   pad_h, pad_w, stride_h, stride_w,\n                                                   dilation_h, dilation_w, deformable_group,\n                                                   grad_offset.data<scalar_t>() + n * im2col_step_ * per_offset_size,\n                                                   grad_mask.data<scalar_t>() + n * im2col_step_ * per_mask_size);\n            // gradient w.r.t. input data\n            modulated_deformable_2d_col2im_cuda(at::cuda::getCurrentCUDAStream(),\n                                             columns.data<scalar_t>(),\n                                             offset.data<scalar_t>() + n * im2col_step_ * per_offset_size,\n                                             mask.data<scalar_t>() + n * im2col_step_ * per_mask_size,\n                                             batch_n, channels, height, width,\n                                             height_out, width_out, kernel_h, kernel_w,\n                                             pad_h, pad_w, stride_h, stride_w,\n                                             dilation_h, dilation_w, deformable_group,\n                                             grad_input.data<scalar_t>() + n * im2col_step_ * per_input_size);\n\n            // gradient w.r.t. weight, dWeight should accumulate across the batch and group\n            modulated_deformable_2d_im2col_cuda(at::cuda::getCurrentCUDAStream(),\n                                             input.data<scalar_t>() + n * im2col_step_ * per_input_size,\n                                             offset.data<scalar_t>() + n * im2col_step_ * per_offset_size,\n                                             mask.data<scalar_t>() + n * im2col_step_ * per_mask_size,\n                                             batch_n, channels, height, width,\n                                             height_out, width_out, kernel_h, kernel_w,\n                                             pad_h, pad_w, stride_h, stride_w,\n                                             dilation_h, dilation_w, deformable_group,\n                                             columns.data<scalar_t>());\n\n        }));\n\n        // auto grad_output_m = grad_output.permute({1, 0, 2, 3}).contiguous().view({channels_out, batch * height_out * width_out});\n        // grad_weight = at::mm(grad_output_m, columns.t()).view_as(weight);\n        // grad_bias = at::mv(grad_output_m, ones);\n        // auto grad_output_g = grad_output.view({batch, group, channels_out/group, height_out, width_out});\n        // auto columns_g = columns.view({group, channels/group * kernel_h * kernel_w, batch * height_out * width_out});\n        for (int g = 0; g < group; ++g)\n        {\n            auto grad_output_gm = grad_output_g.select(1, g).permute({1, 0, 2, 3}).contiguous().view({channels_out/group, batch_n * height_out * width_out});\n            auto columns_gm = columns_g.select(0, g).t();\n            auto grad_weight_gm = grad_weight_g.select(0, g).view({channels_out/group, channels_kernel * kernel_h * kernel_w});\n            auto grad_bias_gm = grad_bias_g.select(0, g);\n            grad_weight_g.select(0, g) = at::addmm(grad_weight_gm, grad_output_gm, columns_gm).view_as(grad_weight_g.select(0, g));\n            grad_bias_g.select(0, g) = at::addmv(grad_bias_gm, grad_output_gm, ones);\n        }\n\n    }\n\n    return {\n        grad_input, grad_offset, grad_mask, grad_weight, grad_bias\n    };\n}\n"
  },
  {
    "path": "utils/DCN/src/cuda/modulated_deform_conv2d_cuda.h",
    "content": "#pragma once\n#include <torch/extension.h>\n\nat::Tensor\nmodulated_deform_conv2d_cuda_forward(const at::Tensor &input,\n                                     const at::Tensor &weight,\n                                     const at::Tensor &bias,\n                                     const at::Tensor &offset,\n                                     const at::Tensor &mask,\n                                     const int kernel_h,\n                                     const int kernel_w,\n                                     const int stride_h,\n                                     const int stride_w,\n                                     const int pad_h,\n                                     const int pad_w,\n                                     const int dilation_h,\n                                     const int dilation_w,\n                                     const int group,\n                                     const int deformable_group,\n                                     const int im2col_step);\n\nstd::vector<at::Tensor>\nmodulated_deform_conv2d_cuda_backward(const at::Tensor &input,\n                                      const at::Tensor &weight,\n                                      const at::Tensor &bias,\n                                      const at::Tensor &offset,\n                                      const at::Tensor &mask,\n                                      const at::Tensor &grad_output,\n                                      const int kernel_h,\n                                      const int kernel_w,\n                                      const int stride_h,\n                                      const int stride_w,\n                                      const int pad_h,\n                                      const int pad_w,\n                                      const int dilation_h,\n                                      const int dilation_w,\n                                      const int group,\n                                      const int deformable_group,\n                                      const int im2col_step);\n\n"
  },
  {
    "path": "utils/DCN/src/deform_conv2d.h",
    "content": "#pragma once\n\n#include \"cpu/deform_conv2d_cpu.h\"\n\n#ifdef WITH_CUDA\n#include \"cuda/deform_conv2d_cuda.h\"\n#endif\n\n\nat::Tensor\ndeform_conv2d_forward(const at::Tensor &input,\n                      const at::Tensor &weight,\n                      const at::Tensor &bias,\n                      const at::Tensor &offset,\n                      const int kernel_h,\n                      const int kernel_w,\n                      const int stride_h,\n                      const int stride_w,\n                      const int pad_h,\n                      const int pad_w,\n                      const int dilation_h,\n                      const int dilation_w,\n                      const int group,\n                      const int deformable_group,\n                      const int im2col_step)\n{\n    if (input.type().is_cuda())\n    {\n#ifdef WITH_CUDA\n        return deform_conv2d_cuda_forward(input, weight, bias, offset,\n                                   kernel_h, kernel_w,\n                                   stride_h, stride_w,\n                                   pad_h, pad_w,\n                                   dilation_h, dilation_w,\n                                   group,\n                                   deformable_group, \n                                   im2col_step);\n#else\n        AT_ERROR(\"Not compiled with GPU support\");\n#endif\n    }\n    AT_ERROR(\"Not implemented on the CPU\");\n}\n\nstd::vector<at::Tensor>\ndeform_conv2d_backward(const at::Tensor &input,\n                       const at::Tensor &weight,\n                       const at::Tensor &bias,\n                       const at::Tensor &offset,\n                       const at::Tensor &grad_output,\n                       const int kernel_h,\n                       const int kernel_w,\n                       const int stride_h,\n                       const int stride_w,\n                       const int pad_h,\n                       const int pad_w,\n                       const int dilation_h,\n                       const int dilation_w,\n                       const int group,\n                       const int deformable_group,\n                       const int im2col_step)\n{\n    if (input.type().is_cuda())\n    {\n#ifdef WITH_CUDA\n        return deform_conv2d_cuda_backward(input,\n                                    weight,\n                                    bias,\n                                    offset,\n                                    grad_output,\n                                    kernel_h, kernel_w,\n                                    stride_h, stride_w,\n                                    pad_h, pad_w,\n                                    dilation_h, dilation_w,\n                                    group,\n                                    deformable_group,\n                                    im2col_step);\n#else\n        AT_ERROR(\"Not compiled with GPU support\");\n#endif\n    }\n    AT_ERROR(\"Not implemented on the CPU\");\n}\n\n"
  },
  {
    "path": "utils/DCN/src/modulated_deform_conv2d.h",
    "content": "#pragma once\n\n#include \"cpu/modulated_deform_conv2d_cpu.h\"\n\n#ifdef WITH_CUDA\n#include \"cuda/modulated_deform_conv2d_cuda.h\"\n#endif\n\n\nat::Tensor\nmodulated_deform_conv2d_forward(const at::Tensor &input,\n                                const at::Tensor &weight,\n                                const at::Tensor &bias,\n                                const at::Tensor &offset,\n                                const at::Tensor &mask,\n                                const int kernel_h,\n                                const int kernel_w,\n                                const int stride_h,\n                                const int stride_w,\n                                const int pad_h,\n                                const int pad_w,\n                                const int dilation_h,\n                                const int dilation_w,\n                                const int group,\n                                const int deformable_group,\n                                const int im2col_step)\n{\n    if (input.type().is_cuda())\n    {\n#ifdef WITH_CUDA\n        return modulated_deform_conv2d_cuda_forward(input, weight, bias, offset, mask,\n                                   kernel_h, kernel_w,\n                                   stride_h, stride_w,\n                                   pad_h, pad_w,\n                                   dilation_h, dilation_w,\n                                   group,\n                                   deformable_group,\n                                   im2col_step);\n#else\n        AT_ERROR(\"Not compiled with GPU support\");\n#endif\n    }\n    AT_ERROR(\"Not implemented on the CPU\");\n}\n\nstd::vector<at::Tensor>\nmodulated_deform_conv2d_backward(const at::Tensor &input,\n                                 const at::Tensor &weight,\n                                 const at::Tensor &bias,\n                                 const at::Tensor &offset,\n                                 const at::Tensor &mask,\n                                 const at::Tensor &grad_output,\n                                 const int kernel_h,\n                                 const int kernel_w,\n                                 const int stride_h,\n                                 const int stride_w,\n                                 const int pad_h,\n                                 const int pad_w,\n                                 const int dilation_h,\n                                 const int dilation_w,\n                                 const int group,\n                                 const int deformable_group,\n                                 const int im2col_step)\n{\n    if (input.type().is_cuda())\n    {\n#ifdef WITH_CUDA\n        return modulated_deform_conv2d_cuda_backward(input,\n                                    weight,\n                                    bias,\n                                    offset,\n                                    mask,\n                                    grad_output,\n                                    kernel_h, kernel_w,\n                                    stride_h, stride_w,\n                                    pad_h, pad_w,\n                                    dilation_h, dilation_w,\n                                    group,\n                                    deformable_group,\n                                    im2col_step);\n#else\n        AT_ERROR(\"Not compiled with GPU support\");\n#endif\n    }\n    AT_ERROR(\"Not implemented on the CPU\");\n}\n\n"
  },
  {
    "path": "utils/DCN/src/vision.cpp",
    "content": "\n#include \"deform_conv2d.h\"\n#include \"modulated_deform_conv2d.h\"\n\nPYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {\n  m.def(\"deform_conv2d_forward\", &deform_conv2d_forward, \"deform_conv2d_forward\");\n  m.def(\"deform_conv2d_backward\", &deform_conv2d_backward, \"deform_conv2d_backward\");\n  m.def(\"modulated_deform_conv2d_forward\", &modulated_deform_conv2d_forward, \"modulated_deform_conv2d_forward\");\n  m.def(\"modulated_deform_conv2d_backward\", &modulated_deform_conv2d_backward, \"modulated_deform_conv2d_backward\");\n}\n"
  },
  {
    "path": "utils/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n\n\n"
  },
  {
    "path": "utils/cocoapi_evaluator.py",
    "content": "import json\nimport tempfile\nimport sys\nfrom tqdm import tqdm\n\nfrom pycocotools.cocoeval import COCOeval\nfrom torch.autograd import Variable\n\nfrom dataset.cocodataset import *\nfrom dataset.data_augment import ValTransform\nfrom utils.utils import *\nfrom utils import distributed_util\nfrom utils.vis_utils import make_vis, make_pred_vis\nimport time\nimport apex\n\nDEBUG =False\n\ndef _accumulate_predictions_from_multiple_gpus(predictions_per_gpu):\n    all_predictions = distributed_util.scatter_gather(predictions_per_gpu)\n    if not distributed_util.is_main_process():\n        return\n    # merge the list of dicts\n    predictions = []\n    for p in all_predictions:\n        for a in p:\n            predictions.append(a)\n\n    return predictions\n\nclass COCOAPIEvaluator():\n    \"\"\"\n    COCO AP Evaluation class.\n    All the data in the val2017 dataset are processed \\\n    and evaluated by COCO API.\n    \"\"\"\n    def __init__(self, data_dir, img_size, confthre, nmsthre, testset=False, voc=False, vis=False):\n        \"\"\"\n        Args:\n            data_dir (str): dataset root directory\n            img_size (int): image size after preprocess. images are resized \\\n                to squares whose shape is (img_size, img_size).\n            confthre (float):\n                confidence threshold ranging from 0 to 1, \\\n                which is defined in the config file.\n            nmsthre (float):\n                IoU threshold of non-max supression ranging from 0 to 1.\n        \"\"\"\n        json_f = 'instances_val2017.json'\n        name='val2017'\n        if testset:\n            json_f = 'image_info_test-dev2017.json'\n            name='test2017'\n        if voc:\n            json_f = 'pascal_test2007.json'\n\n        self.testset= testset\n        self.dataset = COCODataset(data_dir=data_dir,\n                                   img_size=img_size,\n                                   json_file=json_f,\n                                   preproc = ValTransform(rgb_means=(0.485, 0.456, 0.406),std=(0.229, 0.224, 0.225)),\n                                   name=name,\n                                   voc = voc)\n\n        self.num_images = len(self.dataset)\n        self.dataloader = torch.utils.data.DataLoader(\n            self.dataset, batch_size=1, shuffle=False, num_workers=0)\n        self.img_size = img_size\n        self.confthre = confthre\n        self.nmsthre = nmsthre\n        self.voc = voc\n        self.vis = vis\n\n    def evaluate(self, model, half=False, distributed=False):\n        \"\"\"\n        COCO average precision (AP) Evaluation. Iterate inference on the test dataset\n        and the results are evaluated by COCO API.\n        Args:\n            model : model object\n        Returns:\n            ap50_95 (float) : calculated COCO AP for IoU=50:95\n            ap50 (float) : calculated COCO AP for IoU=50\n        \"\"\"\n        if isinstance(model, apex.parallel.DistributedDataParallel):\n            model = model.module\n            distributed=True\n\n        model=model.eval()\n        cuda = torch.cuda.is_available()\n        if half:\n            Tensor = torch.cuda.HalfTensor if cuda else torch.HalfTensor\n        else:\n            Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor\n        ids = []\n        data_dict = []\n        img_num = 0\n\n        indices = list(range(self.num_images))\n        if distributed:\n            dis_indices = indices[distributed_util.get_rank()::distributed_util.get_world_size()]\n        else:\n            dis_indices = indices\n        progress_bar = tqdm if distributed_util.is_main_process() else iter\n        num_classes = 80 if not self.voc else 20\n\n        inference_time=0\n        nms_time=0\n        n_samples=len(dis_indices)-10\n\n        for k, i in enumerate(progress_bar(dis_indices)):\n            img, _, info_img, id_ = self.dataset[i]  # load a batch\n            info_img = [float(info) for info in info_img]\n            id_ = int(id_)\n            ids.append(id_)\n            with torch.no_grad():\n                img = Variable(img.type(Tensor).unsqueeze(0))\n                if k > 9:\n                    start=time.time()\n\n                if self.vis:\n                    outputs,fuse_weights,fused_f = model(img)\n                else:\n                    outputs = model(img)\n\n                if k > 9:\n                    infer_end=time.time()\n                    inference_time += (infer_end-start)\n\n                outputs = postprocess(\n                    outputs, num_classes, self.confthre, self.nmsthre)\n\n                if k > 9:\n                    nms_end=time.time()\n                    nms_time +=(nms_end-infer_end)\n\n                if outputs[0] is None:\n                    continue\n                outputs = outputs[0].cpu().data\n\n            bboxes = outputs[:, 0:4]\n            bboxes[:, 0::2] *= info_img[0] / self.img_size[0]\n            bboxes[:, 1::2] *= info_img[1] / self.img_size[1]\n            bboxes[:, 2] = bboxes[:,2] - bboxes[:,0]\n            bboxes[:, 3] = bboxes[:,3] - bboxes[:,1]\n            cls = outputs[:, 6]\n            scores = outputs[:, 4]* outputs[:,5]\n            for ind in range(bboxes.shape[0]):\n                label = self.dataset.class_ids[int(cls[ind])]\n                A = {\"image_id\": id_, \"category_id\": label, \"bbox\": bboxes[ind].numpy().tolist(),\n                 \"score\": scores[ind].numpy().item(), \"segmentation\": []} # COCO json format\n                data_dict.append(A)\n            \n            if self.vis:\n                o_img,_,_,_  = self.dataset.pull_item(i)\n                make_vis('COCO', i, o_img, fuse_weights, fused_f)\n                class_names = self.dataset._classes\n                make_pred_vis('COCO', i, o_img, class_names, bboxes, cls, scores)\n\n            if DEBUG and distributed_util.is_main_process():\n                o_img,_  = self.dataset.pull_item(i)\n                class_names = self.dataset._classes\n                make_pred_vis('COCO', i, o_img, class_names, bboxes, cls, scores)\n\n        if distributed:\n            distributed_util.synchronize()\n            data_dict = _accumulate_predictions_from_multiple_gpus(data_dict)\n            inference_time = torch.FloatTensor(1).type(Tensor).fill_(inference_time)\n            nms_time = torch.FloatTensor(1).type(Tensor).fill_(nms_time)\n            n_samples = torch.LongTensor(1).type(Tensor).fill_(n_samples)\n            distributed_util.synchronize()\n            torch.distributed.reduce(inference_time, dst=0)\n            torch.distributed.reduce(nms_time, dst=0)\n            torch.distributed.reduce(n_samples, dst=0)\n            inference_time = inference_time.item()\n            nms_time = nms_time.item()\n            n_samples = n_samples.item()\n\n        if not distributed_util.is_main_process():\n            return 0, 0\n\n\n        print('Main process Evaluating...')\n\n        annType = ['segm', 'bbox', 'keypoints']\n        a_infer_time = 1000*inference_time / (n_samples)\n        a_nms_time= 1000*nms_time / (n_samples)\n\n        print('Average forward time: %.2f ms, Average NMS time: %.2f ms, Average inference time: %.2f ms' %(a_infer_time, \\\n                a_nms_time, (a_infer_time+a_nms_time)))\n\n        # Evaluate the Dt (detection) json comparing with the ground truth\n        if len(data_dict) > 0:\n            cocoGt = self.dataset.coco\n            # workaround: temporarily write data to json file because pycocotools can't process dict in py36.\n            if self.testset:\n                json.dump(data_dict, open('yolov3_2017.json', 'w'))\n                cocoDt = cocoGt.loadRes('yolov3_2017.json')\n            else:\n                _, tmp = tempfile.mkstemp()\n                json.dump(data_dict, open(tmp, 'w'))\n                cocoDt = cocoGt.loadRes(tmp)\n            cocoEval = COCOeval(self.dataset.coco, cocoDt, annType[1])\n            cocoEval.evaluate()\n            cocoEval.accumulate()\n            cocoEval.summarize()\n            return cocoEval.stats[0], cocoEval.stats[1]\n        else:\n            return 0, 0\n\n"
  },
  {
    "path": "utils/distributed_util.py",
    "content": "import os\nimport pickle\nimport tempfile\nimport time\n\nimport torch\n\n\ndef get_world_size():\n    if not torch.distributed.is_initialized():\n        return 1\n    return torch.distributed.get_world_size()\n\n\ndef get_rank():\n    if not torch.distributed.is_initialized():\n        return 0\n    return torch.distributed.get_rank()\n\n\ndef is_main_process():\n    if not torch.distributed.is_initialized():\n        return True\n    return torch.distributed.get_rank() == 0\n\n\ndef synchronize():\n    \"\"\"\n    Helper function to synchronize between multiple processes when\n    using distributed training\n    \"\"\"\n    if not torch.distributed.is_initialized():\n        return\n    world_size = torch.distributed.get_world_size()\n    rank = torch.distributed.get_rank()\n    if world_size == 1:\n        return\n\n    def _send_and_wait(r):\n        if rank == r:\n            tensor = torch.tensor(0, device=\"cuda\")\n        else:\n            tensor = torch.tensor(1, device=\"cuda\")\n        torch.distributed.broadcast(tensor, r)\n        while tensor.item() == 1:\n            time.sleep(1)\n\n    _send_and_wait(0)\n    # now sync on the main process\n    _send_and_wait(1)\n\n\ndef _encode(encoded_data, data):\n    # gets a byte representation for the data\n    encoded_bytes = pickle.dumps(data)\n    # convert this byte string into a byte tensor\n    storage = torch.ByteStorage.from_buffer(encoded_bytes)\n    tensor = torch.ByteTensor(storage).to(\"cuda\")\n    # encoding: first byte is the size and then rest is the data\n    s = tensor.numel()\n    assert s <= 255, \"Can't encode data greater than 255 bytes\"\n    # put the encoded data in encoded_data\n    encoded_data[0] = s\n    encoded_data[1: (s + 1)] = tensor\n\n\ndef _decode(encoded_data):\n    size = encoded_data[0]\n    encoded_tensor = encoded_data[1: (size + 1)].to(\"cpu\")\n    return pickle.loads(bytearray(encoded_tensor.tolist()))\n\n\n# TODO try to use tensor in shared-memory instead of serializing to disk\n# this involves getting the all_gather to work\ndef scatter_gather(data):\n    \"\"\"\n    This function gathers data from multiple processes, and returns them\n    in a list, as they were obtained from each process.\n    This function is useful for retrieving data from multiple processes,\n    when launching the code with torch.distributed.launch\n    Note: this function is slow and should not be used in tight loops, i.e.,\n    do not use it in the training loop.\n    Arguments:\n        data: the object to be gathered from multiple processes.\n            It must be serializable\n    Returns:\n        result (list): a list with as many elements as there are processes,\n            where each element i in the list corresponds to the data that was\n            gathered from the process of rank i.\n    \"\"\"\n    # strategy: the main process creates a temporary directory, and communicates\n    # the location of the temporary directory to all other processes.\n    # each process will then serialize the data to the folder defined by\n    # the main process, and then the main process reads all of the serialized\n    # files and returns them in a list\n    if not torch.distributed.is_initialized():\n        return [data]\n    synchronize()\n    # get rank of the current process\n    rank = torch.distributed.get_rank()\n\n    # the data to communicate should be small\n    data_to_communicate = torch.empty(256, dtype=torch.uint8, device=\"cuda\")\n    if rank == 0:\n        # manually creates a temporary directory, that needs to be cleaned\n        # afterwards\n        tmp_dir = tempfile.mkdtemp()\n        _encode(data_to_communicate, tmp_dir)\n\n    synchronize()\n    # the main process (rank=0) communicates the data to all processes\n    torch.distributed.broadcast(data_to_communicate, 0)\n\n    # get the data that was communicated\n    tmp_dir = _decode(data_to_communicate)\n\n    # each process serializes to a different file\n    file_template = \"file{}.pth\"\n    tmp_file = os.path.join(tmp_dir, file_template.format(rank))\n    torch.save(data, tmp_file)\n\n    # synchronize before loading the data\n    synchronize()\n\n    # only the master process returns the data\n    if rank == 0:\n        data_list = []\n        world_size = torch.distributed.get_world_size()\n        for r in range(world_size):\n            file_path = os.path.join(tmp_dir, file_template.format(r))\n            d = torch.load(file_path)\n            data_list.append(d)\n            # cleanup\n            os.remove(file_path)\n        # cleanup\n        os.rmdir(tmp_dir)\n        return data_list\n\n\ndef reduce_loss_dict(loss_dict):\n    \"\"\"\n    Reduce the loss dictionary from all processes so that process with rank\n    0 has the averaged results. Returns a dict with the same fields as\n    loss_dict, after reduction.\n    \"\"\"\n    world_size = get_world_size()\n    if world_size < 2:\n        return loss_dict\n    with torch.no_grad():\n        loss_names = []\n        all_losses = []\n        for k in sorted(loss_dict.keys()):\n            loss_names.append(k)\n            all_losses.append(loss_dict[k])\n        all_losses = torch.stack(all_losses, dim=0)\n        torch.distributed.reduce(all_losses, dst=0)\n        if torch.distributed.get_rank() == 0:\n            # only main process gets accumulated, so only divide by\n            # world_size in this case\n            all_losses /= world_size\n        reduced_losses = {k: v for k, v in zip(loss_names, all_losses)}\n    return reduced_losses\n"
  },
  {
    "path": "utils/fp16_utils/README.md",
    "content": "fp16_optimizer.py contains `FP16_Optimizer`, a Python class designed to wrap an existing Pytorch optimizer and automatically enable master parameters and loss scaling in a manner transparent to the user.  To use `FP16_Optimizer`, only two lines of one's Python model need to change.\n\n#### [FP16_Optimizer API documentation](https://nvidia.github.io/apex/fp16_utils.html#automatic-management-of-master-params-loss-scaling)\n\n#### [Simple examples with FP16_Optimizer](https://github.com/NVIDIA/apex/tree/master/examples/FP16_Optimizer_simple)\n\n#### [Imagenet with FP16_Optimizer](https://github.com/NVIDIA/apex/tree/master/examples/imagenet)\n\n#### [word_language_model with FP16_Optimizer](https://github.com/NVIDIA/apex/tree/master/examples/word_language_model)\n\n\nfp16_util.py contains a number of utilities to manually manage master parameters and loss scaling, if the user chooses.  \n\n#### [Manual management documentation](https://nvidia.github.io/apex/fp16_utils.html#manual-master-parameter-management)\n\nThe [Imagenet with FP16_Optimizer](https://github.com/NVIDIA/apex/tree/master/examples/imagenet) and [word_language_model with FP16_Optimizer](https://github.com/NVIDIA/apex/tree/master/examples/word_language_model) directories also contain `main.py` files that demonstrate manual management of master parameters and static loss scaling.  These examples illustrate what sort of operations `FP16_Optimizer` is performing automatically.\n"
  },
  {
    "path": "utils/fp16_utils/__init__.py",
    "content": "from .fp16util import (\n    BN_convert_float,\n    network_to_half,\n    prep_param_lists,\n    model_grads_to_master_grads,\n    master_params_to_model_params,\n    tofp16,\n    to_python_float,\n    clip_grad_norm,\n    convert_module,\n    convert_network,\n    FP16Model,\n)\n\nfrom .fp16_optimizer import FP16_Optimizer\nfrom .loss_scaler import LossScaler, DynamicLossScaler\n"
  },
  {
    "path": "utils/fp16_utils/fp16_optimizer.py",
    "content": "import torch\r\nfrom torch import nn\r\nfrom torch.autograd import Variable\r\nfrom torch.nn.parameter import Parameter\r\nfrom torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors\r\n\r\nfrom .loss_scaler import DynamicLossScaler, LossScaler\r\nfrom .fp16util import model_grads_to_master_grads, master_params_to_model_params, clip_grad_norm\r\n\r\n# TODO:  Update overflow check + downscale to use Carl's fused kernel.\r\nclass FP16_Optimizer(object):\r\n    \"\"\"\r\n    :class:`FP16_Optimizer` is designed to wrap an existing PyTorch optimizer, \r\n    and manage static or dynamic loss scaling and master weights in a manner transparent to the user.\r\n    For standard use, only two lines must be changed:  creating the :class:`FP16_Optimizer` instance,\r\n    and changing the call to ``backward``.\r\n\r\n    Example::\r\n\r\n        model = torch.nn.Linear(D_in, D_out).cuda().half()\r\n        optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)\r\n        # Name the FP16_Optimizer instance to replace the existing optimizer\r\n        # (recommended but not required):\r\n        optimizer = FP16_Optimizer(optimizer, static_loss_scale = 128.0)\r\n        ...\r\n        # loss.backward() becomes:\r\n        optimizer.backward(loss)\r\n        ...\r\n\r\n    Example with dynamic loss scaling::\r\n\r\n        ...\r\n        optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)\r\n                                   # optional arg to control dynamic loss scaling behavior\r\n                                   # dynamic_loss_args={'scale_window' : 500})\r\n                                   # Usually, dynamic_loss_args is not necessary. \r\n\r\n    Args:\r\n        init_optimizer (torch.optim.optimizer):  Existing optimizer created with the parameters to optimize.  Internally, :class:`FP16_Optimizer` replaces the passed optimizer's fp16 parameters, if any, with fp32 master parameters copied from the original ones.  :class:`FP16_Optimizer` also stores references to the original fp16 parameters, and updates these fp16 parameters from the master fp32 copy at the end of each :attr:`step`.  \r\n        static_loss_scale (float, optional, default=1.0):  Loss scale used internally to scale gradients computed by the model.  Any fp16 gradients will be copied to fp32, then downscaled before being applied to the fp32 master params, so ``static_loss_scale`` should not affect learning rate.\r\n        dynamic_loss_scale (bool, optional, default=False):  Use dynamic loss scaling.  If True, this will override any ``static_loss_scale`` option.\r\n        dynamic_loss_args (dict, optional, default=None):  Dict of kwargs that will be forwarded to the internal :class:`DynamicLossScaler` instance's constructor.  Keys of this dict must match kwargs accepted by :class:`DynamicLossScaler`'s constructor.  If ``dynamic_loss_args`` is unspecified, :class:`DynamicLossScaler`'s defaults will be used.\r\n        verbose (bool, optional, default=True):  By default, FP16_Optimizer's constructor prints out the parameters and parameter groups it is ingesting, as a sanity check.  If this becomes annoying (e.g. for large models), it can be disabled by passing ``verbose=False``.  ``verbose=False`` will not disable printing when the loss scale is readjusted during dynamic loss scaling.\r\n\r\n    ``init_optimizer`` is expected to have been constructed in the ordinary way.  \r\n    It is recommended (although not required) that the newly constructed :class:`FP16_Optimizer` instance be \r\n    named to replace ``init_optimizer``, for two reasons:  \r\n    First, it means that references to the same name\r\n    later in the file will not have to change.  \r\n    Second, :class:`FP16_Optimizer` reserves the right (as an implementation detail) to \r\n    modify ``init_optimizer``.  If you do choose a unique name for the new\r\n    :class:`FP16_Optimizer` instance, you should only work with this new instance,\r\n    because the preexisting optimizer might no longer behave as expected.\r\n\r\n    ``init_optimizer`` may be any Pytorch optimizer. \r\n    It may contain a mixture of fp16 and fp32 parameters organized into any number of \r\n    ``param_groups`` with different hyperparameters.  The :class:`FP16_Optimizer` constructor will \r\n    ingest these ``param_groups`` and remember them. \r\n\r\n    Calls to ::\r\n\r\n        loss.backward() \r\n\r\n    must be replaced with ::\r\n\r\n        optimizer.backward(loss)  \r\n\r\n    because :class:`FP16_Optimizer` requires ownership of the backward pass to implement \r\n    loss scaling and copies to master gradients.\r\n\r\n    .. note::\r\n        Loss scaling, either static or dynamic, is orthogonal to learning rate, because gradients\r\n        are downscaled before being applied.  This means that adjusting the loss scale, or using\r\n        dynamic loss scaling, should not require retuning the learning rate or any other \r\n        hyperparameters.\r\n\r\n\r\n    **Advanced options**\r\n\r\n    **Closures**:  :class:`FP16_Optimizer` can wrap a Pytorch optimizer that receives a closure.\r\n    See docstring for :attr:`step`.\r\n\r\n    **Gradient clipping**:  Use :attr:`clip_master_grads`.\r\n    \r\n    **Multiple losses**:  If your model accumulates gradients from multiple losses,\r\n    this can be made more efficient by supplying ``update_master_grads=False``\r\n    to :attr:`backward`.  See docstring for :attr:`backward`.\r\n\r\n    **Manually adjusting loss scale**:  The current loss scale can be retrieved or set via ::\r\n\r\n        print(optimizer.loss_scale)\r\n        optimizer.loss_scale = new_loss_scale\r\n\r\n    For static loss scaling, manually adjusting the loss scale over time is a reasonable\r\n    thing to do.  During later epochs, gradients may become smaller, and a \r\n    higher loss scale may be required, analogous to scheduling the learning rate.  Dynamic loss\r\n    scaling is more subtle (see :class:`DynamicLossScaler`) and in this case, manually adjusting \r\n    the loss scale is not recommended.\r\n\r\n    **Multi_GPU training**:  If the wrapped ``init_optimizer`` was created from a model wrapped in\r\n    Pytorch DistributedDataParallel or Apex DistributedDataParallel, :class:`FP16_Optimizer` \r\n    should still work as intended.\r\n    \"\"\"\r\n\r\n    def __init__(self, \r\n                 init_optimizer, \r\n                 static_loss_scale=1.0, \r\n                 dynamic_loss_scale=False,\r\n                 dynamic_loss_args=None,\r\n                 verbose=True):\r\n        if not torch.cuda.is_available:\r\n            raise SystemError(\"Cannot use fp16 without CUDA.\")\r\n\r\n        self.verbose = verbose\r\n\r\n        self.optimizer = init_optimizer\r\n        # init_state_dict sets up an alternative way to cast per-param state tensors.\r\n        # Stashing here in case https://github.com/pytorch/pytorch/issues/7733 makes it necessary.\r\n        # init_state_dict = init_optimizer.state_dict()\r\n\r\n        self.fp16_groups = []\r\n        self.fp32_from_fp16_groups = []\r\n        self.fp32_from_fp32_groups = []\r\n        for i, param_group in enumerate(self.optimizer.param_groups):\r\n            self.maybe_print(\"FP16_Optimizer processing param group {}:\".format(i))\r\n            fp16_params_this_group = []\r\n            fp32_params_this_group = []\r\n            fp32_from_fp16_params_this_group = []\r\n            for i, param in enumerate(param_group['params']):\r\n                if param.requires_grad:\r\n                    if param.type() == 'torch.cuda.HalfTensor':\r\n                        self.maybe_print(\"FP16_Optimizer received torch.cuda.HalfTensor with {}\"\r\n                                         .format(param.size()))\r\n                        fp16_params_this_group.append(param)\r\n                        master_param = param.detach().clone().float()\r\n                        master_param.requires_grad = True\r\n                        param_group['params'][i] = master_param\r\n                        fp32_from_fp16_params_this_group.append(master_param)\r\n                        # Reset existing state dict key to the new master param.\r\n                        # We still need to recast per-param state tensors, if any, to FP32.\r\n                        if param in self.optimizer.state:\r\n                           self.optimizer.state[master_param] = self.optimizer.state.pop(param) \r\n                    elif param.type() == 'torch.cuda.FloatTensor':\r\n                        self.maybe_print(\"FP16_Optimizer received torch.cuda.FloatTensor with {}\"\r\n                                         .format(param.size()))\r\n                        fp32_params_this_group.append(param)\r\n                        param_group['params'][i] = param\r\n                    else:\r\n                        raise TypeError(\"Wrapped parameters must be either \"\r\n                                        \"torch.cuda.FloatTensor or torch.cuda.HalfTensor. \"  \r\n                                        \"Received {}\".format(param.type()))\r\n            \r\n            self.fp16_groups.append(fp16_params_this_group)\r\n            self.fp32_from_fp16_groups.append(fp32_from_fp16_params_this_group)\r\n            self.fp32_from_fp32_groups.append(fp32_params_this_group)\r\n\r\n        # Leverage state_dict() and load_state_dict() to recast preexisting per-param state tensors\r\n        self.optimizer.load_state_dict(self.optimizer.state_dict())\r\n        # alternative way to cast per-param state tensors:\r\n        # self.optimizer.load_state_dict(init_state_dict)\r\n\r\n        if dynamic_loss_scale:\r\n            self.dynamic_loss_scale = True\r\n            if dynamic_loss_args is not None:\r\n                self.loss_scaler = DynamicLossScaler(**dynamic_loss_args)\r\n            else:\r\n                self.loss_scaler = DynamicLossScaler()\r\n        else:\r\n            self.dynamic_loss_scale = False\r\n            self.loss_scaler = LossScaler(static_loss_scale)\r\n\r\n        self.overflow = False\r\n        self.first_closure_call_this_step = True\r\n\r\n        self.clip_grad_norm = clip_grad_norm\r\n\r\n    def maybe_print(self, msg):\r\n        if self.verbose:\r\n            print(msg)\r\n            \r\n    def __getstate__(self):\r\n        raise RuntimeError(\"FP16_Optimizer should be serialized using state_dict().\")\r\n\r\n    def __setstate__(self, state):\r\n        raise RuntimeError(\"FP16_Optimizer should be deserialized using load_state_dict().\")\r\n\r\n    def zero_grad(self, set_grads_to_None=False):\r\n        \"\"\"\r\n        Zero fp32 and fp16 parameter grads.\r\n        \"\"\"\r\n        # In principle, only the .grad attributes of the model params need to be zeroed,\r\n        # because gradients are copied into the FP32 master params.  However, we zero\r\n        # all gradients owned by the optimizer, just to be safe:\r\n        for group in self.optimizer.param_groups:\r\n             for p in group['params']:\r\n                 if set_grads_to_None:\r\n                     p.grad = None\r\n                 else:\r\n                     if p.grad is not None:\r\n                         p.grad.detach_()\r\n                         p.grad.zero_()\r\n\r\n        # Zero fp16 gradients owned by the model:\r\n        for fp16_group in self.fp16_groups:\r\n            for param in fp16_group:\r\n                if set_grads_to_None:\r\n                    param.grad = None\r\n                else:\r\n                    if param.grad is not None:\r\n                        param.grad.detach_() # as in torch.optim.optimizer.zero_grad()\r\n                        param.grad.zero_()\r\n\r\n    def _check_overflow(self):\r\n        params = [] \r\n        for group in self.fp16_groups:\r\n            for param in group:\r\n                params.append(param)\r\n        for group in self.fp32_from_fp32_groups:\r\n            for param in group:\r\n                params.append(param)\r\n        self.overflow = self.loss_scaler.has_overflow(params)\r\n\r\n    def _update_scale(self, has_overflow=False):\r\n        self.loss_scaler.update_scale(has_overflow)\r\n\r\n    def _master_params_to_model_params(self):\r\n        for fp16_group, fp32_from_fp16_group in zip(self.fp16_groups, self.fp32_from_fp16_groups):\r\n            master_params_to_model_params(fp16_group, fp32_from_fp16_group)\r\n\r\n    # To consider:  Integrate distributed with this wrapper by registering a hook on each variable \r\n    # that does the overflow check, gradient copy + downscale, and fp32 allreduce in a different stream.\r\n    def _model_grads_to_master_grads(self):\r\n        for fp16_group, fp32_from_fp16_group in zip(self.fp16_groups, self.fp32_from_fp16_groups):\r\n            model_grads_to_master_grads(fp16_group, fp32_from_fp16_group)\r\n\r\n    def _downscale_master(self):\r\n        if self.loss_scale != 1.0: \r\n            for group in self.optimizer.param_groups:\r\n                for param in group['params']:\r\n                    if param.grad is not None:\r\n                        param.grad.data.mul_(1./self.loss_scale)\r\n\r\n    def clip_master_grads(self, max_norm, norm_type=2):\r\n        \"\"\"\r\n        Clips fp32 master gradients via ``torch.nn.utils.clip_grad_norm``.\r\n\r\n        Args:\r\n            max_norm (float or int): max norm of the gradients\r\n            norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for\r\n                infinity norm.\r\n\r\n        Returns:\r\n            Total norm of the current fp32 gradients (viewed as a single vector).\r\n\r\n        .. warning::\r\n            Returns -1 if the most recently computed fp16 gradients overflowed (that is, if ``self.overflow`` is ``True``).\r\n        \"\"\"\r\n        if not self.overflow:\r\n            fp32_params = []\r\n            for param_group in self.optimizer.param_groups:\r\n                for param in param_group['params']:\r\n                    fp32_params.append(param)\r\n            return self.clip_grad_norm(fp32_params, max_norm, norm_type)\r\n        else:\r\n            return -1\r\n\r\n    def state_dict(self):\r\n        \"\"\"\r\n        Returns a dict containing the current state of this :class:`FP16_Optimizer` instance.\r\n        This dict contains attributes of :class:`FP16_Optimizer`, as well as the state_dict\r\n        of the contained Pytorch optimizer.\r\n        Example::\r\n\r\n            checkpoint = {}\r\n            checkpoint['model'] = model.state_dict()\r\n            checkpoint['optimizer'] = optimizer.state_dict()\r\n            torch.save(checkpoint, \"saved.pth\")\r\n        \"\"\"\r\n        state_dict = {}\r\n        state_dict['loss_scaler'] = self.loss_scaler\r\n        state_dict['dynamic_loss_scale'] = self.dynamic_loss_scale\r\n        state_dict['overflow'] = self.overflow\r\n        state_dict['first_closure_call_this_step'] = self.first_closure_call_this_step\r\n        state_dict['optimizer_state_dict'] = self.optimizer.state_dict()\r\n        state_dict['fp32_from_fp16'] = self.fp32_from_fp16_groups\r\n        return state_dict\r\n\r\n    def load_state_dict(self, state_dict):\r\n        \"\"\"\r\n        Loads a state_dict created by an earlier call to state_dict(). \r\n        If ``fp16_optimizer_instance`` was constructed from some ``init_optimizer``, \r\n        whose parameters in turn came from ``model``, it is expected that the user \r\n        will call ``model.load_state_dict()`` before\r\n        ``fp16_optimizer_instance.load_state_dict()`` is called.\r\n\r\n        Example::\r\n\r\n            model = torch.nn.Linear(D_in, D_out).cuda().half()\r\n            optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)\r\n            optimizer = FP16_Optimizer(optimizer, static_loss_scale = 128.0)\r\n            ...\r\n            checkpoint = torch.load(\"saved.pth\")\r\n            model.load_state_dict(checkpoint['model'])\r\n            optimizer.load_state_dict(checkpoint['optimizer'])\r\n        \"\"\"\r\n        # I think it should actually be ok to reload the optimizer before the model.\r\n        self.loss_scaler = state_dict['loss_scaler']\r\n        self.dynamic_loss_scale = state_dict['dynamic_loss_scale']\r\n        self.overflow = state_dict['overflow']\r\n        self.first_closure_call_this_step = state_dict['first_closure_call_this_step']\r\n        self.optimizer.load_state_dict(state_dict['optimizer_state_dict'])\r\n        # At this point, the optimizer's references to the model's fp32 parameters are up to date.\r\n        # The optimizer's hyperparameters and internal buffers are also up to date.  \r\n        # However, the fp32 master copies of the model's fp16 params stored by the optimizer are still\r\n        # out of date.  There are two options.  \r\n        # 1:  Refresh the master params from the model's fp16 params.  \r\n        # This requires less storage but incurs precision loss.\r\n        # 2:  Save and restore the fp32 master copies separately.\r\n        # We choose option 2.\r\n        # \r\n        # Pytorch Optimizer.load_state_dict casts saved buffers (e.g. momentum) to the type and device \r\n        # of their associated parameters, because it's possible those buffers might not exist yet in \r\n        # the current optimizer instance.  In our case, as long as the current FP16_Optimizer has been \r\n        # constructed in the same way as the one whose state_dict we are loading, the same master params\r\n        # are guaranteed to exist, so we can just copy_() from the saved master params.\r\n        for current_group, saved_group in zip(self.fp32_from_fp16_groups, state_dict['fp32_from_fp16']):\r\n            for current, saved in zip(current_group, saved_group):\r\n                current.data.copy_(saved.data)\r\n\r\n    def step(self, closure=None): # could add clip option.\r\n        \"\"\"\r\n        If no closure is supplied, :attr:`step` should be called after \r\n        ``fp16_optimizer_obj.backward(loss)``.\r\n        :attr:`step` updates the fp32 master copy of parameters using the optimizer supplied to\r\n        :class:`FP16_Optimizer`'s constructor, then copies the updated fp32 params into the fp16 params\r\n        originally referenced by :class:`FP16_Optimizer`'s constructor, so the user may immediately run\r\n        another forward pass using their model.\r\n\r\n        If a closure is supplied, :attr:`step` may be called without a prior call to \r\n        :attr:`backward(loss)`.\r\n        This control flow is identical to `ordinary Pytorch optimizer use`_ with closures.\r\n        However, the user should take care that any ``loss.backward()`` call within the closure\r\n        has been replaced by ``fp16_optimizer_obj.backward(loss)``.\r\n\r\n        Args:\r\n           closure (optional):  Closure that will be supplied to the underlying optimizer originally passed to :class:`FP16_Optimizer`'s constructor.  closure should call :attr:`zero_grad()` on the :class:`FP16_Optimizer` object, compute the loss, call :attr:`backward(loss)`, and return the loss.\r\n\r\n        Example with closure::\r\n\r\n            # optimizer is assumed to be an FP16_Optimizer object, previously constructed from an \r\n            # existing pytorch optimizer.\r\n            for input, target in dataset:\r\n                def closure():\r\n                    optimizer.zero_grad()\r\n                    output = model(input)\r\n                    loss = loss_fn(output, target)\r\n                    # loss.backward() becomes:\r\n                    optimizer.backward(loss)\r\n                    return loss\r\n                optimizer.step(closure)\r\n\r\n        .. warning::\r\n            Currently, calling :attr:`step` with a closure is not compatible with dynamic loss scaling.\r\n\r\n        .. _`ordinary Pytorch optimizer use`:\r\n            http://pytorch.org/docs/master/optim.html#optimizer-step-closure\r\n        \"\"\"\r\n\r\n        scale = self.loss_scaler.loss_scale\r\n        self._update_scale(self.overflow)\r\n\r\n        if self.overflow:\r\n            print(\"OVERFLOW! Skipping step. Attempted loss scale: {}, reducing to {}\"\r\n                .format(scale, self.loss_scale))\r\n            return\r\n        \r\n        if closure is not None:\r\n            retval = self._step_with_closure(closure)\r\n        else:\r\n            retval = self.optimizer.step()\r\n\r\n        self._master_params_to_model_params()\r\n\r\n        return retval\r\n\r\n    def _step_with_closure(self, closure):\r\n        def wrapped_closure():\r\n            # helpful for debugging\r\n            # print(\"Calling wrapped_closure, first_closure_call_this_step = {}\"\r\n            #       .format(self.first_closure_call_this_step))\r\n            if self.first_closure_call_this_step:\r\n                # We expect that the fp16 params are initially fresh on entering self.step(),\r\n                # so _master_params_to_model_params() is unnecessary the first time wrapped_closure()\r\n                # is called within self.optimizer.step().\r\n                self.first_closure_call_this_step = False\r\n            else:\r\n                # If self.optimizer.step() internally calls wrapped_closure more than once,\r\n                # it may update the fp32 params after each call.  However, self.optimizer \r\n                # doesn't know about the fp16 params at all.  If the fp32 params get updated,\r\n                # we can't rely on self.optimizer to refresh the fp16 params.  We need\r\n                # to handle that manually:\r\n                self._master_params_to_model_params()\r\n            # Our API expects the user to give us ownership of the backward() call by\r\n            # replacing all calls to loss.backward() with optimizer.backward(loss).\r\n            # This requirement holds whether or not the call to backward() is made within a closure.\r\n            # If the user is properly calling optimizer.backward(loss) within \"closure,\" \r\n            # calling closure() here will give the fp32 master params fresh gradients\r\n            # for the optimizer to play with, so all wrapped_closure needs to do is call \r\n            # closure() and return the loss.\r\n            temp_loss = closure() \r\n            while(self.overflow):\r\n                scale = self.loss_scaler.loss_scale\r\n                self._update_scale(self.overflow)\r\n                print(\"OVERFLOW within closure! Skipping step. Attempted loss scale: {}, \"\r\n                      \"reducing to {}\".format(scale, self.loss_scale))\r\n                temp_loss = closure()\r\n            return temp_loss\r\n\r\n        retval = self.optimizer.step(wrapped_closure)\r\n\r\n        self.first_closure_call_this_step = True\r\n\r\n        return retval\r\n\r\n    def backward(self, loss, update_master_grads=True, retain_graph=False):\r\n        \"\"\" \r\n        :attr:`backward` performs the following conceptual steps:\r\n\r\n        1. fp32_loss = loss.float() (see first Note below)\r\n        2. scaled_loss = fp32_loss*loss_scale\r\n        3. scaled_loss.backward(), which accumulates scaled gradients into the ``.grad`` attributes of the model's leaves (which may be fp16, fp32, or a mixture, depending how your model was defined).\r\n        4. fp16 grads are then copied to the master params' ``.grad`` attributes (see second Note), which are guaranteed to be fp32.\r\n        5. Finally, master grads are divided by loss_scale.\r\n\r\n        In this way, after :attr:`backward`, the master params have fresh gradients,\r\n        and :attr:`step` may be called.\r\n\r\n        .. note::\r\n            :attr:`backward` internally converts the loss to fp32 before applying the loss scale.\r\n            This provides some additional safety against overflow if the user has supplied an \r\n            fp16 loss value.  \r\n            However, for maximum overflow safety, the user should\r\n            compute the loss criterion (MSE, cross entropy, etc) in fp32 before supplying it to \r\n            :attr:`backward`.\r\n\r\n        .. warning::\r\n            The gradients found in a model's leaves after the call to \r\n            :attr:`backward` should not be regarded as valid in general, \r\n            because it's possible \r\n            they have been scaled (and in the case of dynamic loss scaling, \r\n            the scale factor may change over time).  \r\n            If the user wants to inspect gradients after a call to :attr:`backward`,  \r\n            only the master gradients should be regarded as valid.  These can be retrieved via\r\n            :attr:`inspect_master_grad_data()`.\r\n\r\n        Args:\r\n            loss:  The loss output by the user's model.  loss may be either float or half (but see first Note above).\r\n            update_master_grads (bool, optional, default=True):  Option to copy fp16 grads to fp32 grads on this call.  By setting this to False, the user can delay the copy, which is useful to eliminate redundant fp16->fp32 grad copies if :attr:`backward` is being called on multiple losses in one iteration.  If set to False, the user becomes responsible for calling :attr:`update_master_grads` before calling :attr:`step`.\r\n            retain_graph (bool, optional, default=False):  Forwards the usual ``retain_graph=True`` option to the internal call to ``loss.backward``.  If ``retain_graph`` is being used to accumulate gradient values from multiple backward passes before calling ``optimizer.step``, passing ``update_master_grads=False`` is also recommended (see Example below).\r\n\r\n        Example::\r\n\r\n            # Ordinary operation:\r\n            optimizer.backward(loss)\r\n\r\n            # Naive operation with multiple losses (technically valid, but less efficient):\r\n            # fp32 grads will be correct after the second call,  but \r\n            # the first call incurs an unnecessary fp16->fp32 grad copy.\r\n            optimizer.backward(loss1)\r\n            optimizer.backward(loss2)\r\n\r\n            # More efficient way to handle multiple losses:\r\n            # The fp16->fp32 grad copy is delayed until fp16 grads from all \r\n            # losses have been accumulated.\r\n            optimizer.backward(loss1, update_master_grads=False)\r\n            optimizer.backward(loss2, update_master_grads=False)\r\n            optimizer.update_master_grads()\r\n        \"\"\" \r\n        # To consider:  try multiple backward passes using retain_grad=True to find \r\n        # a loss scale that works.  After you find a loss scale that works, do a final dummy\r\n        # backward pass with retain_graph=False to tear down the graph.  Doing this would avoid \r\n        # discarding the iteration,  but probably wouldn't improve overall efficiency.  \r\n        self.loss_scaler.backward(loss.float(), retain_graph=retain_graph)\r\n        if update_master_grads:\r\n            self.update_master_grads()\r\n\r\n    def update_master_grads(self):\r\n        \"\"\"\r\n        Copy the ``.grad`` attribute from stored references to fp16 parameters to \r\n        the ``.grad`` attribute of the fp32 master parameters that are directly \r\n        updated by the optimizer.  :attr:`update_master_grads` only needs to be called if\r\n        ``fp16_optimizer_obj.backward`` was called with ``update_master_grads=False``.\r\n        \"\"\"\r\n        if self.dynamic_loss_scale:\r\n            self._check_overflow()\r\n            if self.overflow: return\r\n        self._model_grads_to_master_grads()\r\n        self._downscale_master()\r\n\r\n    def inspect_master_grad_data(self):\r\n        \"\"\"\r\n        When running with :class:`FP16_Optimizer`, \r\n        ``.grad`` attributes of a model's fp16 leaves should not be\r\n        regarded as truthful, because they might be scaled.  \r\n        After a call to :attr:`fp16_optimizer_obj.backward(loss)`, if no overflow was encountered,\r\n        the fp32 master params' ``.grad``\r\n        attributes will contain valid gradients properly divided by the loss scale.  However, \r\n        because :class:`FP16_Optimizer` flattens some parameters, accessing them may be \r\n        nonintuitive.  :attr:`inspect_master_grad_data`\r\n        allows those gradients to be viewed with shapes corresponding to their associated model leaves.\r\n\r\n        Returns:\r\n            List of lists (one list for each parameter group).  The list for each parameter group\r\n            is a list of the ``.grad.data`` attributes of the fp32 master params belonging to that group.                 \r\n        \"\"\"\r\n        if self.overflow:\r\n            print(\"Warning:  calling FP16_Optimizer.inspect_master_grad_data while in an overflow state.  \"\r\n                  \"Gradients are currently invalid (may be inf, nan, or stale).  Returning None.\")\r\n            return None\r\n        else:\r\n            # The optimizer owns only references to master params.\r\n            master_grads_data = []\r\n            for param_group in self.optimizer.param_groups:\r\n                master_grads_this_group = []\r\n                for param in param_group['params']:\r\n                    if param.grad is not None:\r\n                        master_grads_this_group.append(param.grad.data)\r\n                    else:\r\n                        master_grads_this_group.append(None)\r\n                master_grads_data.append(master_grads_this_group)\r\n            return master_grads_data\r\n\r\n\r\n    # Promote loss scale so it can be retrieved or set via \"fp16_optimizer_instance.loss_scale\"\r\n    def _get_loss_scale(self):\r\n        return self.loss_scaler.loss_scale\r\n\r\n    def _set_loss_scale(self, value):\r\n        self.loss_scaler.cur_scale = value\r\n\r\n    loss_scale = property(_get_loss_scale, _set_loss_scale)\r\n\r\n    # Promote state so it can be retrieved or set via \"fp16_optimizer_instance.state\"\r\n    def _get_state(self):\r\n        return self.optimizer.state\r\n\r\n    def _set_state(self, value):\r\n        self.optimizer.state = value\r\n\r\n    state = property(_get_state, _set_state)\r\n\r\n    # Promote param_groups so it can be retrieved or set via \"fp16_optimizer_instance.param_groups\"\r\n    # (for example, to adjust the learning rate)\r\n    def _get_param_groups(self):\r\n        return self.optimizer.param_groups\r\n\r\n    def _set_param_groups(self, value):\r\n        self.optimizer.param_groups = value\r\n\r\n    param_groups = property(_get_param_groups, _set_param_groups)\r\n\r\n"
  },
  {
    "path": "utils/fp16_utils/fp16util.py",
    "content": "import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors\n\n\nclass tofp16(nn.Module):\n    \"\"\"\n    Utility module that implements::\n\n        def forward(self, input):\n            return input.half()\n    \"\"\"\n\n    def __init__(self):\n        super(tofp16, self).__init__()\n\n    def forward(self, input):\n        return input.half()\n\n\ndef BN_convert_float(module):\n    \"\"\"\n    Utility function for network_to_half().\n\n    Retained for legacy purposes.\n    \"\"\"\n    if isinstance(module, torch.nn.modules.batchnorm._BatchNorm) and module.affine is True:\n        module.float()\n    for child in module.children():\n        BN_convert_float(child)\n    return module\n\n\ndef network_to_half(network):\n    \"\"\"\n    Convert model to half precision in a batchnorm-safe way.\n\n    Retained for legacy purposes. It is recommended to use FP16Model.\n    \"\"\"\n    return nn.Sequential(tofp16(), BN_convert_float(network.half()))\n\n\ndef convert_module(module, dtype):\n    \"\"\"\n    Converts a module's immediate parameters and buffers to dtype.\n    \"\"\"\n    for param in module.parameters(recurse=False):\n        if param is not None:\n            if param.data.dtype.is_floating_point:\n                param.data = param.data.to(dtype=dtype)\n            if param._grad is not None and param._grad.data.dtype.is_floating_point:\n                param._grad.data = param._grad.data.to(dtype=dtype)\n\n    for buf in module.buffers(recurse=False):\n        if buf is not None and buf.data.dtype.is_floating_point:\n            buf.data = buf.data.to(dtype=dtype)\n\n\ndef convert_network(network, dtype):\n    \"\"\"\n    Converts a network's parameters and buffers to dtype.\n    \"\"\"\n    for module in network.modules():\n        if isinstance(module, torch.nn.modules.batchnorm._BatchNorm) and module.affine is True:\n            continue\n        convert_module(module, dtype)\n    return network\n\n\nclass FP16Model(nn.Module):\n    \"\"\"\n    Convert model to half precision in a batchnorm-safe way.\n    \"\"\"\n\n    def __init__(self, network):\n        super(FP16Model, self).__init__()\n        self.network = convert_network(network, dtype=torch.half)\n\n    def forward(self, *inputs):\n        inputs = tuple(t.half() for t in inputs)\n        return self.network(*inputs)\n\n\ndef backwards_debug_hook(grad):\n    raise RuntimeError(\"master_params recieved a gradient in the backward pass!\")\n\ndef prep_param_lists(model, flat_master=False):\n    \"\"\"\n    Creates a list of FP32 master parameters for a given model, as in\n    `Training Neural Networks with Mixed Precision:  Real Examples`_.\n\n    Args:\n        model (torch.nn.Module): Existing Pytorch model\n        flat_master (bool, optional, default=False):  Flatten the master parameters into a single tensor, as a performance optimization.\n    Returns:\n        A tuple (``model_params``, ``master_params``). ``model_params`` is a list of the model's parameters for later use with :func:`model_grads_to_master_grads` and :func:`master_params_to_model_params`.  ``master_params`` is a list of FP32 master gradients.  If ``flat_master=True``, ``master_params`` will be a list with one element.\n\n    Example::\n\n        model_params, master_params = prep_param_lists(model)\n\n    .. warning::\n        Currently, if ``flat_master=True``, all the model's parameters must be the same type.  If the model has parameters of different types, use ``flat_master=False``, or use :class:`FP16_Optimizer`.\n\n    .. _`Training Neural Networks with Mixed Precision:  Real Examples`:\n        http://on-demand.gputechconf.com/gtc/2018/video/S81012/\n    \"\"\"\n    model_params = [param for param in model.parameters() if param.requires_grad]\n\n    if flat_master:\n        # Give the user some more useful error messages\n        try:\n            # flatten_dense_tensors returns a contiguous flat array.\n            # http://pytorch.org/docs/master/_modules/torch/_utils.html\n            master_params = _flatten_dense_tensors([param.data for param in model_params]).float()\n        except:\n            print(\"Error in prep_param_lists:  model may contain a mixture of parameters \"\n                      \"of different types.  Use flat_master=False, or use F16_Optimizer.\")\n            raise\n        master_params = torch.nn.Parameter(master_params)\n        master_params.requires_grad = True\n        # master_params.register_hook(backwards_debug_hook)\n        if master_params.grad is None:\n            master_params.grad = master_params.new(*master_params.size())\n        return model_params, [master_params]\n    else:\n        master_params = [param.clone().float().detach() for param in model_params]\n        for param in master_params:\n            param.requires_grad = True\n        return model_params, master_params\n\n\ndef model_grads_to_master_grads(model_params, master_params, flat_master=False):\n    \"\"\"\n    Copy model gradients to master gradients.  \n\n    Args:\n        model_params:  List of model parameters created by :func:`prep_param_lists`.\n        master_params:  List of FP32 master parameters created by :func:`prep_param_lists`.  If ``master_params`` was created with ``flat_master=True``, ``flat_master=True`` should also be supplied to :func:`model_grads_to_master_grads`.\n    \"\"\"\n    if flat_master:\n        # The flattening may incur one more deep copy than is necessary.\n        master_params[0].grad.data.copy_(\n            _flatten_dense_tensors([p.grad.data for p in model_params]))\n    else:\n        for model, master in zip(model_params, master_params):\n            if model.grad is not None:\n                if master.grad is None:\n                    master.grad = Variable(master.data.new(*master.data.size()))\n                master.grad.data.copy_(model.grad.data)\n            else:\n                master.grad = None\n\n\ndef master_params_to_model_params(model_params, master_params, flat_master=False):\n    \"\"\"\n    Copy master parameters to model parameters.\n\n    Args:\n        model_params:  List of model parameters created by :func:`prep_param_lists`.\n        master_params:  List of FP32 master parameters created by :func:`prep_param_lists`.  If ``master_params`` was created with ``flat_master=True``, ``flat_master=True`` should also be supplied to :func:`master_params_to_model_params`.\n    \"\"\"\n    if flat_master:\n        for model, master in zip(model_params, \n                                 _unflatten_dense_tensors(master_params[0].data, model_params)):\n            model.data.copy_(master)\n    else:\n        for model, master in zip(model_params, master_params):\n            model.data.copy_(master.data)\n\n# Backward compatibility fixes\n\ndef to_python_float(t):\n    if hasattr(t, 'item'):\n        return t.item()\n    else:\n        return t[0]\n\nTORCH_MAJOR = int(torch.__version__.split('.')[0])\nTORCH_MINOR = int(torch.__version__.split('.')[1])\nif TORCH_MAJOR == 0 and TORCH_MINOR <= 4:\n    clip_grad_norm = torch.nn.utils.clip_grad_norm\nelse:\n    clip_grad_norm = torch.nn.utils.clip_grad_norm_\n"
  },
  {
    "path": "utils/fp16_utils/loss_scaler.py",
    "content": "import torch\n\n# item() is a recent addition, so this helps with backward compatibility.\ndef to_python_float(t):\n    if hasattr(t, 'item'):\n        return t.item()\n    else:\n        return t[0]\n\nclass LossScaler:\n    \"\"\"\n    Class that manages a static loss scale.  This class is intended to interact with\n    :class:`FP16_Optimizer`, and should not be directly manipulated by the user.\n\n    Use of :class:`LossScaler` is enabled via the ``static_loss_scale`` argument to \n    :class:`FP16_Optimizer`'s constructor.\n\n    Args:\n        scale (float, optional, default=1.0):  The loss scale.\n    \"\"\"\n\n    def __init__(self, scale=1):\n        self.cur_scale = scale\n\n    # `params` is a list / generator of torch.Variable\n    def has_overflow(self, params):\n        return False\n\n    # `x` is a torch.Tensor\n    def _has_inf_or_nan(x):\n        return False\n\n    def update_scale(self, overflow):\n        pass\n\n    @property\n    def loss_scale(self):\n        return self.cur_scale\n\n    def scale_gradient(self, module, grad_in, grad_out):\n        return tuple(self.loss_scale * g for g in grad_in)\n\n    def backward(self, loss, retain_graph=False):\n        scaled_loss = loss*self.loss_scale\n        scaled_loss.backward(retain_graph=retain_graph)\n\nclass DynamicLossScaler:\n    \"\"\"\n    Class that manages dynamic loss scaling.  It is recommended to use :class:`DynamicLossScaler`\n    indirectly, by supplying ``dynamic_loss_scale=True`` to the constructor of \n    :class:`FP16_Optimizer`.  However, it's important to understand how :class:`DynamicLossScaler`\n    operates, because the default options can be changed using the\n    the ``dynamic_loss_args`` argument to :class:`FP16_Optimizer`'s constructor.\n\n    Loss scaling is designed to combat the problem of underflowing gradients encountered at long\n    times when training fp16 networks.  Dynamic loss scaling begins by attempting a very high loss\n    scale.  Ironically, this may result in OVERflowing gradients.  If overflowing gradients are\n    encountered, :class:`DynamicLossScaler` informs :class:`FP16_Optimizer` that an overflow has \n    occurred.\n    :class:`FP16_Optimizer` then skips the update step for this particular iteration/minibatch,\n    and :class:`DynamicLossScaler` adjusts the loss scale to a lower value.  \n    If a certain number of iterations occur without overflowing gradients detected,\n    :class:`DynamicLossScaler` increases the loss scale once more.\n    In this way :class:`DynamicLossScaler` attempts to \"ride the edge\" of \n    always using the highest loss scale possible without incurring overflow.\n\n    Args:\n        init_scale (float, optional, default=2**32):  Initial loss scale attempted by :class:`DynamicLossScaler.`\n        scale_factor (float, optional, default=2.0):  Factor used when adjusting the loss scale. If an overflow is encountered, the loss scale is readjusted to loss scale/``scale_factor``.  If ``scale_window`` consecutive iterations take place without an overflow, the loss scale is readjusted to loss_scale*``scale_factor``. \n        scale_window (int, optional, default=1000):  Number of consecutive iterations without an overflow to wait before increasing the loss scale.\n    \"\"\"\n\n    def __init__(self,\n                 init_scale=2**32,\n                 scale_factor=2.,\n                 scale_window=1000):\n        self.cur_scale = init_scale\n        self.cur_iter = 0\n        self.last_overflow_iter = -1\n        self.scale_factor = scale_factor\n        self.scale_window = scale_window\n\n    # `params` is a list / generator of torch.Variable\n    def has_overflow(self, params):\n        for p in params:\n            if p.grad is not None and DynamicLossScaler._has_inf_or_nan(p.grad.data):\n                return True\n\n        return False\n\n    # `x` is a torch.Tensor\n    def _has_inf_or_nan(x):\n        try:\n            # if x is half, the .float() incurs an additional deep copy, but it's necessary if \n            # Pytorch's .sum() creates a one-element tensor of the same type as x \n            # (which is true for some recent version of pytorch).\n            cpu_sum = float(x.float().sum())\n            # More efficient version that can be used if .sum() returns a Python scalar\n            # cpu_sum = float(x.sum())\n        except RuntimeError as instance:\n            # We want to check if inst is actually an overflow exception.\n            # RuntimeError could come from a different error.\n            # If so, we still want the exception to propagate.\n            if \"value cannot be converted\" not in instance.args[0]:\n                raise\n            return True\n        else:\n            if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum:\n                return True\n            return False\n\n    # `overflow` is boolean indicating whether the gradient overflowed\n    def update_scale(self, overflow):\n        if overflow:\n            # self.cur_scale /= self.scale_factor\n            self.cur_scale = max(self.cur_scale/self.scale_factor, 1)\n            self.last_overflow_iter = self.cur_iter\n        else:\n            if (self.cur_iter - self.last_overflow_iter) % self.scale_window == 0:\n                self.cur_scale *= self.scale_factor\n        self.cur_iter += 1\n\n    @property\n    def loss_scale(self):\n        return self.cur_scale\n\n    def scale_gradient(self, module, grad_in, grad_out):\n        return tuple(self.loss_scale * g for g in grad_in)\n\n    def backward(self, loss, retain_graph=False):\n        scaled_loss = loss*self.loss_scale\n        scaled_loss.backward(retain_graph=retain_graph)\n        \n##############################################################        \n# Example usage below here -- assuming it's in a separate file\n##############################################################\n\"\"\"\nTO-DO separate out into an example.\nif __name__ == \"__main__\":\n    import torch\n    from torch.autograd import Variable\n    from dynamic_loss_scaler import DynamicLossScaler\n\n    # N is batch size; D_in is input dimension;\n    # H is hidden dimension; D_out is output dimension.\n    N, D_in, H, D_out = 64, 1000, 100, 10\n\n    # Create random Tensors to hold inputs and outputs, and wrap them in Variables.\n    x = Variable(torch.randn(N, D_in), requires_grad=False)\n    y = Variable(torch.randn(N, D_out), requires_grad=False)\n\n    w1 = Variable(torch.randn(D_in, H), requires_grad=True)\n    w2 = Variable(torch.randn(H, D_out), requires_grad=True)\n    parameters = [w1, w2]\n\n    learning_rate = 1e-6\n    optimizer = torch.optim.SGD(parameters, lr=learning_rate)\n    loss_scaler = DynamicLossScaler()\n\n    for t in range(500):\n        y_pred = x.mm(w1).clamp(min=0).mm(w2)\n        loss = (y_pred - y).pow(2).sum() * loss_scaler.loss_scale\n        print('Iter {} loss scale: {}'.format(t, loss_scaler.loss_scale))\n        print('Iter {} scaled loss: {}'.format(t, loss.data[0]))\n        print('Iter {} unscaled loss: {}'.format(t, loss.data[0] / loss_scaler.loss_scale))\n\n        # Run backprop\n        optimizer.zero_grad()\n        loss.backward()\n        \n        # Check for overflow\n        has_overflow = DynamicLossScaler.has_overflow(parameters)\n        \n        # If no overflow, unscale grad and update as usual\n        if not has_overflow:\n            for param in parameters:\n                param.grad.data.mul_(1. / loss_scaler.loss_scale)\n            optimizer.step()\n        # Otherwise, don't do anything -- ie, skip iteration\n        else:\n            print('OVERFLOW!')\n\n        # Update loss scale for next iteration\n        loss_scaler.update_scale(has_overflow)\n\n\"\"\"\n"
  },
  {
    "path": "utils/utils.py",
    "content": "from __future__ import division\nimport torch\nimport torchvision\nimport numpy as np\nimport cv2\n\ndef postprocess(prediction, num_classes, conf_thre=0.7, nms_thre=0.45):\n    \"\"\"\n    Postprocess for the output of YOLO model\n    perform box transformation, specify the class for each detection,\n    and perform class-wise non-maximum suppression.\n    Args:\n        prediction (torch tensor): The shape is :math:`(N, B, 4)`.\n            :math:`N` is the number of predictions,\n            :math:`B` the number of boxes. The last axis consists of\n            :math:`xc, yc, w, h` where `xc` and `yc` represent a center\n            of a bounding box.\n        num_classes (int):\n            number of dataset classes.\n        conf_thre (float):\n            confidence threshold ranging from 0 to 1,\n            which is defined in the config file.\n        nms_thre (float):\n            IoU threshold of non-max suppression ranging from 0 to 1.\n\n    Returns:\n        output (list of torch tensor):\n\n    \"\"\"\n    box_corner = prediction.new(prediction.shape)\n    box_corner[:, :, 0] = prediction[:, :, 0] - prediction[:, :, 2] / 2\n    box_corner[:, :, 1] = prediction[:, :, 1] - prediction[:, :, 3] / 2\n    box_corner[:, :, 2] = prediction[:, :, 0] + prediction[:, :, 2] / 2\n    box_corner[:, :, 3] = prediction[:, :, 1] + prediction[:, :, 3] / 2\n    prediction[:, :, :4] = box_corner[:, :, :4]\n\n    output = [None for _ in range(len(prediction))]\n    for i, image_pred in enumerate(prediction):\n\n        # If none are remaining => process next image\n        if not image_pred.size(0):\n            continue\n        # Get score and class with highest confidence\n        class_conf, class_pred = torch.max(\n            image_pred[:, 5:5 + num_classes], 1,  keepdim=True)\n\n        conf_mask = (image_pred[:, 4] * class_conf.squeeze() >= conf_thre).squeeze()\n        # Detections ordered as (x1, y1, x2, y2, obj_conf, class_conf, class_pred)\n        detections = torch.cat(\n            (image_pred[:, :5], class_conf, class_pred.float()), 1)\n        detections = detections[conf_mask]\n        if not detections.size(0):\n            continue\n\n        # Iterate through all predicted classes\n        unique_labels = detections[:, -1].unique()\n\n        for c in unique_labels:\n            # Get the detections with the particular class\n            detections_class = detections[detections[:, -1] == c]\n            nms_out_index = torchvision.ops.nms(\n                detections_class[:, :4], detections_class[:, 4]*detections_class[:, 5], nms_thre)\n            detections_class = detections_class[nms_out_index]\n            if output[i] is None:\n                output[i] = detections_class\n            else:\n                output[i] = torch.cat((output[i], detections_class))\n\n    return output\n\n\ndef bboxes_iou(bboxes_a, bboxes_b, xyxy=True):\n    \"\"\"Calculate the Intersection of Unions (IoUs) between bounding boxes.\n    IoU is calculated as a ratio of area of the intersection\n    and area of the union.\n\n    Args:\n        bbox_a (array): An array whose shape is :math:`(N, 4)`.\n            :math:`N` is the number of bounding boxes.\n            The dtype should be :obj:`numpy.float32`.\n        bbox_b (array): An array similar to :obj:`bbox_a`,\n            whose shape is :math:`(K, 4)`.\n            The dtype should be :obj:`numpy.float32`.\n    Returns:\n        array:\n        An array whose shape is :math:`(N, K)`. \\\n        An element at index :math:`(n, k)` contains IoUs between \\\n        :math:`n` th bounding box in :obj:`bbox_a` and :math:`k` th bounding \\\n        box in :obj:`bbox_b`.\n\n    from: https://github.com/chainer/chainercv\n    \"\"\"\n    if bboxes_a.shape[1] != 4 or bboxes_b.shape[1] != 4:\n        raise IndexError\n\n    if xyxy:\n        tl = torch.max(bboxes_a[:, None, :2], bboxes_b[:, :2])\n        br = torch.min(bboxes_a[:, None, 2:], bboxes_b[:, 2:])\n        area_a = torch.prod(bboxes_a[:, 2:] - bboxes_a[:, :2], 1)\n        area_b = torch.prod(bboxes_b[:, 2:] - bboxes_b[:, :2], 1)\n    else:\n        tl = torch.max((bboxes_a[:, None, :2] - bboxes_a[:, None, 2:] / 2),\n                        (bboxes_b[:, :2] - bboxes_b[:, 2:] / 2))\n        br = torch.min((bboxes_a[:, None, :2] + bboxes_a[:, None, 2:] / 2),\n                        (bboxes_b[:, :2] + bboxes_b[:, 2:] / 2))\n\n        area_a = torch.prod(bboxes_a[:, 2:], 1)\n        area_b = torch.prod(bboxes_b[:, 2:], 1)\n    en = (tl < br).type(tl.type()).prod(dim=2)\n    area_i = torch.prod(br - tl, 2) * en  # * ((tl < br).all())\n    return area_i / (area_a[:, None] + area_b - area_i)\n\n\ndef matrix_iou(a,b):\n    \"\"\"\n    return iou of a and b, numpy version for data augenmentation\n    \"\"\"\n    lt = np.maximum(a[:, np.newaxis, :2], b[:, :2])\n    rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])\n\n    area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2)\n    area_a = np.prod(a[:, 2:] - a[:, :2], axis=1)\n    area_b = np.prod(b[:, 2:] - b[:, :2], axis=1)\n    return area_i / (area_a[:, np.newaxis] + area_b - area_i+1e-12)\n\ndef visual(img, boxes, scores):\n\n    COLORS = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]\n    FONT = cv2.FONT_HERSHEY_SIMPLEX\n    for i in range(boxes.shape[0]):\n\n        cv2.rectangle(img, (int(boxes[i][0]),int(boxes[i][1])),(int(boxes[i][2]),int(boxes[i][3])),COLORS[i%3],2)\n        cv2.putText(img, 'Object: %.2f'%scores[i],(int(boxes[i][0])-3,int(boxes[i][1])-5), FONT,\n                     0.4, (0,0,0),2)\n\n    return img\n\n\n"
  },
  {
    "path": "utils/vis_utils.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport os \nimport matplotlib\n\nmatplotlib.use('AGG')\n\nimport matplotlib.pyplot as plt\nimport torch\nimport cv2\nimport math\nfrom skimage import transform\n\ndef make_vis(dataset, index, img, fuse_weights, fused_fs):\n    save_dir = 'vis_output/{}/{}'.format(dataset,index)\n    os.makedirs(save_dir, exist_ok=True)\n\n    for i in range(len(fuse_weights)):\n        weights = fuse_weights[i].float().cpu().squeeze().numpy()\n        max_v = weights.max()\n        min_v = weights.min()\n        for j in range(3):\n            v = weights[j,:,:]\n            save_name = os.path.join(save_dir, 'level_{}_weight_{}.png'.format(i+1,j+1))\n            add_heat(img, v, max_v, min_v, save=save_name)\n\n        fused_f = fused_fs[i].float().cpu().squeeze().numpy()\n        max_f = fused_f.max()\n        min_f = fused_f.min()\n        save_f_name = os.path.join(save_dir, 'fused_feature_level_{}.png'.format(i+1))\n        add_heat(img, fused_f, max_f, min_f, save=save_f_name)\n\ndef make_pred_vis(dataset,index, img, class_names, bboxes, cls, scores):\n    save_preddir = 'vis_output/{}/pred/'.format(dataset)\n    os.makedirs(save_preddir, exist_ok=True)\n\n    save_pred_name = os.path.join(save_preddir,'{}.png'.format(index))\n\n    bboxes = bboxes.numpy()\n    scores = scores.numpy()\n    cls_ids = cls.numpy()\n\n    im = vis(img, bboxes, scores, cls_ids, class_names)\n    \n    cv2.imwrite(save_pred_name, im)\n\ndef vis(img, boxes, scores, cls_ids, conf=0.5, class_names=None, color=None):\n\n    colors = torch.FloatTensor([[1,0,1],[0,0,1],[0,1,1],[0,1,0],[1,1,0],[1,0,0]]);\n    def get_color(c, x, max_val):\n        ratio = float(x)/max_val * 5\n        i = int(math.floor(ratio))\n        j = int(math.ceil(ratio))\n        ratio = ratio - i\n        r = (1-ratio) * colors[i][c] + ratio*colors[j][c]\n        return int(r*255)\n\n    width = img.shape[1]\n    height = img.shape[0]\n    for i in range(len(boxes)):\n        box = boxes[i]\n        cls_conf = scores[i]\n        if cls_conf < conf:\n            continue\n        x1 = int(box[0])\n        y1 = int(box[1])\n        x2 = int(box[0]+box[2])\n        y2 = int(box[1]+box[3])\n\n\n        if color:\n            rgb = color\n        else:\n            rgb = (255, 0, 0)\n        if class_names is not None:\n            cls_conf = scores[i]\n            cls_id = int(cls_ids[i])\n            class_name = class_names[cls_id]\n            classes = len(class_names)\n            offset = cls_id * 123456 % classes\n            red   = get_color(2, offset, classes)\n            green = get_color(1, offset, classes)\n            blue  = get_color(0, offset, classes)\n            if color is None:\n                rgb = (red, green, blue)\n            img = cv2.putText(img, '%s: %.2f'%(class_name,cls_conf), (x1,y1-5), cv2.FONT_HERSHEY_SIMPLEX, 0.3, rgb, 1)\n        img = cv2.rectangle(img, (x1,y1), (x2,y2), rgb, 1)\n    return img\n\ndef add_heat(image, heat_map, max_v, min_v, alpha=0.4, save=None, cmap='jet', axis='off'):\n    height = image.shape[0]\n    width = image.shape[1]\n\n    # resize heat map\n    heat_map_resized = transform.resize(heat_map, (height, width))\n\n    # normalize heat map\n    max_value = max_v\n    min_value = min_v\n    normalized_heat_map = (heat_map_resized - min_value) / (max_value - min_value)\n\n    # display\n    plt.imshow(image)\n    plt.imshow(255 * normalized_heat_map, alpha=alpha, cmap=cmap)\n    plt.axis(axis)\n\n    if save is not None:\n        plt.savefig(save, bbox_inches='tight', pad_inches=0)\n\n\n\n\n"
  },
  {
    "path": "utils/voc_evaluator.py",
    "content": "import json\nimport tempfile\nimport sys\nfrom tqdm import tqdm\n\nfrom pycocotools.cocoeval import COCOeval\nfrom torch.autograd import Variable\n\nfrom dataset.vocdataset import *\nfrom dataset.data_augment import ValTransform\nfrom utils.utils import *\nfrom utils import distributed_util\nfrom utils.vis_utils import make_vis, make_pred_vis\n\nimport time\n\n#DEBUG = True\nDEBUG = False\n\ndef _accumulate_predictions_from_multiple_gpus(predictions_per_gpu):\n    all_predictions = distributed_util.scatter_gather(predictions_per_gpu)\n    if not distributed_util.is_main_process():\n        return\n    # merge the list of dicts\n    predictions = {}\n    for p in all_predictions:\n        predictions.update(p)\n    # convert a dict where the key is the index in a list\n    image_ids = list(sorted(predictions.keys()))\n    if len(image_ids) != image_ids[-1] + 1:\n        print('num_imgs: ',len(image_ids))\n        print('last img_id: ',image_ids[-1])\n        print(\n            \"Number of images that were gathered from multiple processes is not \"\n            \"a contiguous set. Some images might be missing from the evaluation\"\n        )\n\n    # convert to a list\n    predictions = [predictions[i] for i in image_ids]\n    return predictions\n\n\nclass VOCEvaluator():\n    \"\"\"\n    COCO AP Evaluation class.\n    All the data in the val2017 dataset are processed \\\n    and evaluated by COCO API.\n    \"\"\"\n    def __init__(self, data_dir, img_size, confthre, nmsthre,vis=False):\n        \"\"\"\n        Args:\n            data_dir (str): dataset root directory\n            img_size (int): image size after preprocess. images are resized \\\n                to squares whose shape is (img_size, img_size).\n            confthre (float):\n                confidence threshold ranging from 0 to 1, \\\n                which is defined in the config file.\n            nmsthre (float):\n                IoU threshold of non-max supression ranging from 0 to 1.\n        \"\"\"\n        test_sets = [('2007', 'test'),]\n        self.dataset = VOCDetection(\n                                   root=data_dir,\n                                   image_sets = test_sets,\n                                   input_dim=img_size,\n                                   preproc = ValTransform(rgb_means=(0.485, 0.456, 0.406),std=(0.229, 0.224, 0.225)),)\n        self.num_images = len(self.dataset)\n        self.dataloader = torch.utils.data.DataLoader(\n            self.dataset, batch_size=1, shuffle=False, num_workers=0)\n        self.img_size = img_size\n        self.confthre = confthre\n        self.nmsthre = nmsthre\n        self.vis=vis\n\n    def evaluate(self, model, half=False):\n        \"\"\"\n        COCO average precision (AP) Evaluation. Iterate inference on the test dataset\n        and the results are evaluated by COCO API.\n        Args:\n            model : model object\n        Returns:\n            ap50_95 (float) : calculated COCO AP for IoU=50:95\n            ap50 (float) : calculated COCO AP for IoU=50\n        \"\"\"\n        if isinstance(model, torch.nn.parallel.DistributedDataParallel):\n            model = model.module\n        model.eval()\n        cuda = torch.cuda.is_available()\n        if half:\n            Tensor = torch.cuda.HalfTensor if cuda else torch.HalfTensor\n        else:\n            Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor\n        \n        ids = []\n        data_dict = []\n        dataiterator = iter(self.dataloader)\n        img_num = 0\n        indices = list(range(self.num_images))\n        dis_indices = indices[distributed_util.get_rank()::distributed_util.get_world_size()]\n        progress_bar = tqdm if distributed_util.is_main_process() else iter\n        num_classes = 20\n        predictions = {}\n\n        if distributed_util.is_main_process():\n            inference_time=0\n            nms_time=0\n            n_samples=len(dis_indices)\n\n        for i in progress_bar(dis_indices):\n            img, _, info_img, id_ = self.dataset[i]  # load a batch\n            info_img = [float(info) for info in info_img]\n            ids.append(id_)\n            with torch.no_grad():\n                img = Variable(img.type(Tensor).unsqueeze(0))\n\n                if distributed_util.is_main_process() and i > 9:\n                    start=time.time()\n\n                if self.vis:\n                    outputs,fuse_weights,fused_f = model(img)\n                else:\n                    outputs = model(img)\n\n                if distributed_util.is_main_process() and i > 9:\n                    infer_end=time.time()\n                    inference_time += (infer_end-start)\n\n                outputs = postprocess(\n                    outputs, 20, self.confthre, self.nmsthre)\n\n\n                if distributed_util.is_main_process() and i > 9:\n                    nms_end=time.time()\n                    nms_time +=(nms_end-infer_end)\n\n                if outputs[0] is None:\n                    predictions[i] = (None, None, None)\n                    continue\n                outputs = outputs[0].cpu().data\n\n            bboxes = outputs[:, 0:4]\n            bboxes[:, 0::2] *= info_img[0] / self.img_size[0]\n            bboxes[:, 1::2] *= info_img[1] / self.img_size[1]\n            cls = outputs[:, 6]\n            scores = outputs[:, 4]* outputs[:,5]\n            predictions[i] = (bboxes, cls, scores)\n\n            if self.vis:\n                o_img,_,_,_  = self.dataset.pull_item(i)\n                make_vis('VOC', i, o_img, fuse_weights, fused_f)\n                class_names = self.dataset._classes\n\n                bbox = bboxes.clone()\n                bbox[:, 2] = bbox[:,2] - bbox[:,0]\n                bbox[:, 3] = bbox[:,3] - bbox[:,1]\n\n                make_pred_vis('VOC', i, o_img, class_names, bbox, cls, scores)\n\n            if DEBUG and distributed_util.is_main_process():\n                o_img,_,_,_  = self.dataset.pull_item(i)\n                class_names = self.dataset._classes\n                bbox = bboxes.clone()\n                bbox[:, 2] = bbox[:,2] - bbox[:,0]\n                bbox[:, 3] = bbox[:,3] - bbox[:,1]\n                make_pred_vis('VOC', i, o_img, class_names, bbox, cls, scores)\n\n        distributed_util.synchronize()\n        predictions = _accumulate_predictions_from_multiple_gpus(predictions)\n        if not distributed_util.is_main_process():\n            return 0, 0\n\n\n        print('Main process Evaluating...')\n\n        a_infer_time = 1000*inference_time / (n_samples-10)\n        a_nms_time= 1000*nms_time / (n_samples-10)\n\n        print('Average forward time: %.2f ms, Average NMS time: %.2f ms, Average inference time: %.2f ms' %(a_infer_time, \\\n                a_nms_time, (a_infer_time+a_nms_time)))\n\n        all_boxes = [[[] for _ in range(self.num_images)]\n                     for _ in range(num_classes)]\n        for img_num in range(self.num_images):\n            bboxes, cls, scores = predictions[img_num]\n            if bboxes is None:\n                for j in range(num_classes):\n                    all_boxes[j][img_num] = np.empty([0,5],dtype=np.float32)\n                continue\n            for j in range(num_classes):\n                mask_c = (cls == j)\n                if sum(mask_c) ==0:\n                    all_boxes[j][img_num] = np.empty([0,5],dtype=np.float32)\n                    continue\n\n                c_dets = torch.cat((bboxes, scores.unsqueeze(1)),dim=1)\n                all_boxes[j][img_num] = c_dets[mask_c].numpy()\n\n            sys.stdout.write('im_eval: {:d}/{:d} \\r'.format(img_num+1, self.num_images))\n            sys.stdout.flush()\n\n        with tempfile.TemporaryDirectory() as tempdir:\n            mAP50, mAP70 = self.dataset.evaluate_detections(all_boxes, tempdir)\n            return mAP50,mAP70\n\n"
  }
]