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