Showing preview only (381K chars total). Download the full file or copy to clipboard to get everything.
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. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
================================================
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).
<img align="center" src="https://github.com/ruinmessi/ASFF/blob/master/doc/asff.png">
### 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
s
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
SYMBOL INDEX (239 symbols across 32 files)
FILE: dataset/cocodataset.py
class COCODataset (line 27) | class COCODataset(Dataset):
method __init__ (line 31) | def __init__(self, data_dir='data/COCO', json_file='instances_train201...
method __len__ (line 63) | def __len__(self):
method pull_item (line 66) | def pull_item(self, index):
method __getitem__ (line 121) | def __getitem__(self, index):
FILE: dataset/data_augment.py
function _crop (line 19) | def _crop(image, boxes, labels, ratios = None):
function _distort (line 86) | def _distort(image):
function _expand (line 116) | def _expand(image, boxes,fill, p):
function _mirror (line 152) | def _mirror(image, boxes):
function _random_affine (line 161) | def _random_affine(img, targets=None, degrees=(-10, 10), translate=(.1, ...
function preproc_for_test (line 228) | def preproc_for_test(image, input_size, mean, std):
class TrainTransform (line 242) | class TrainTransform(object):
method __init__ (line 244) | def __init__(self, p=0.5, rgb_means=None, std = None,max_labels=50):
method __call__ (line 250) | def __call__(self, image, targets, input_dim):
class ValTransform (line 361) | class ValTransform(object):
method __init__ (line 376) | def __init__(self, rgb_means=None, std=None, swap=(2, 0, 1)):
method __call__ (line 382) | def __call__(self, img, res, input_size):
FILE: dataset/dataloading.py
class Dataset (line 14) | class Dataset(torchDataset):
method __init__ (line 21) | def __init__(self, input_dimension):
method input_dim (line 26) | def input_dim(self):
method resize_getitem (line 38) | def resize_getitem(getitem_fn):
class DataLoader (line 75) | class DataLoader(torchDataLoader):
method __init__ (line 114) | def __init__(self, *args, **kwargs):
method change_input_dim (line 157) | def change_input_dim(self, multiple=32, random_range=(10, 19)):
class YoloBatchSampler (line 193) | class YoloBatchSampler(torchBatchSampler):
method __init__ (line 198) | def __init__(self, *args, input_dimension=None, **kwargs):
method __iter__ (line 203) | def __iter__(self):
method __set_input_dim (line 209) | def __set_input_dim(self):
class IterationBasedBatchSampler (line 216) | class IterationBasedBatchSampler(torchBatchSampler):
method __init__ (line 222) | def __init__(self, batch_sampler, num_iterations, start_iter=0):
method __iter__ (line 227) | def __iter__(self):
method __len__ (line 241) | def __len__(self):
function list_collate (line 244) | def list_collate(batch):
FILE: dataset/mixupdetection.py
class MixupDetection (line 9) | class MixupDetection(Dataset):
method __init__ (line 22) | def __init__(self, dataset, mixup=None, preproc=None, *args):
method set_mixup (line 29) | def set_mixup(self, mixup=None, *args):
method __len__ (line 42) | def __len__(self):
method __getitem__ (line 46) | def __getitem__(self, idx):
method pull_item (line 87) | def pull_item(self, idx):
FILE: dataset/voc_eval.py
function parse_rec (line 14) | def parse_rec(filename):
function voc_ap (line 35) | def voc_ap(rec, prec, use_07_metric=False):
function voc_eval (line 68) | def voc_eval(detpath,
FILE: dataset/vocdataset.py
class AnnotationTransform (line 40) | class AnnotationTransform(object):
method __init__ (line 54) | def __init__(self, class_to_ind=None, keep_difficult=True):
method __call__ (line 59) | def __call__(self, target):
class VOCDetection (line 90) | class VOCDetection(Dataset):
method __init__ (line 108) | def __init__(self, root, image_sets, preproc=None, target_transform=An...
method __getitem__ (line 127) | def __getitem__(self, index):
method __len__ (line 147) | def __len__(self):
method pull_image (line 150) | def pull_image(self, index):
method pull_anno (line 164) | def pull_anno(self, index):
method pull_item (line 181) | def pull_item(self, index):
method evaluate_detections (line 204) | def evaluate_detections(self, all_boxes, output_dir=None):
method _get_voc_results_file_template (line 226) | def _get_voc_results_file_template(self):
method _write_voc_results_file (line 235) | def _write_voc_results_file(self, all_boxes):
method _do_python_eval (line 254) | def _do_python_eval(self, output_dir='output', iou = 0.5):
FILE: demo.py
function parse_args (line 24) | def parse_args():
function demo (line 42) | def demo():
FILE: eval.py
function parse_args (line 34) | def parse_args():
function eval (line 66) | def eval():
FILE: main.py
function parse_args (line 37) | def parse_args():
function main (line 86) | def main():
FILE: models/network_blocks.py
function add_conv (line 7) | def add_conv(in_ch, out_ch, ksize, stride, leaky=True):
class upsample (line 31) | class upsample(nn.Module):
method __init__ (line 34) | def __init__(self, size=None, scale_factor=None, mode='nearest', align...
method forward (line 42) | def forward(self, input):
method extra_repr (line 45) | def extra_repr(self):
class SPPLayer (line 53) | class SPPLayer(nn.Module):
method __init__ (line 54) | def __init__(self):
method forward (line 57) | def forward(self, x):
class DropBlock (line 65) | class DropBlock(nn.Module):
method __init__ (line 66) | def __init__(self, block_size=7, keep_prob=0.9):
method reset (line 75) | def reset(self, block_size, keep_prob):
method calculate_gamma (line 83) | def calculate_gamma(self, x):
method forward (line 87) | def forward(self, x):
class resblock (line 109) | class resblock(nn.Module):
method __init__ (line 118) | def __init__(self, ch, nblocks=1, shortcut=True):
method forward (line 129) | def forward(self, x):
class RFBblock (line 138) | class RFBblock(nn.Module):
method __init__ (line 139) | def __init__(self,in_ch,residual=False):
method forward (line 161) | def forward(self,x):
class FeatureAdaption (line 172) | class FeatureAdaption(nn.Module):
method __init__ (line 173) | def __init__(self, in_ch, out_ch, n_anchors, rfb=False, sep=False):
method forward (line 187) | def forward(self, input, wh_pred):
class ASFFmobile (line 199) | class ASFFmobile(nn.Module):
method __init__ (line 200) | def __init__(self, level, rfb=False, vis=False):
method forward (line 228) | def forward(self, x_level_0, x_level_1, x_level_2):
class ASFF (line 267) | class ASFF(nn.Module):
method __init__ (line 268) | def __init__(self, level, rfb=False, vis=False):
method forward (line 295) | def forward(self, x_level_0, x_level_1, x_level_2):
function make_divisible (line 332) | def make_divisible(v, divisor, min_value=None):
class ConvBNReLU (line 352) | class ConvBNReLU(nn.Sequential):
method __init__ (line 353) | def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, gro...
function add_sepconv (line 361) | def add_sepconv(in_ch, out_ch, ksize, stride):
class InvertedResidual (line 375) | class InvertedResidual(nn.Module):
method __init__ (line 376) | def __init__(self, inp, oup, stride, expand_ratio):
method forward (line 397) | def forward(self, x):
class ressepblock (line 403) | class ressepblock(nn.Module):
method __init__ (line 404) | def __init__(self, ch, out_ch, in_ch=None, shortcut=True):
method forward (line 415) | def forward(self, x):
FILE: models/utils_loss.py
class IOUWH_loss (line 7) | class IOUWH_loss(nn.Module): #used for anchor guiding
method __init__ (line 8) | def __init__(self, reduction='none'):
method forward (line 12) | def forward(self, pred, target):
class IOUloss (line 39) | class IOUloss(nn.Module):
method __init__ (line 40) | def __init__(self, reduction='none'):
method forward (line 44) | def forward(self, pred, target):
FILE: models/yolov3_asff.py
function build_yolov3_modules (line 9) | def build_yolov3_modules(num_classes, ignore_thre, label_smooth, rfb):
class YOLOv3 (line 64) | class YOLOv3(nn.Module):
method __init__ (line 70) | def __init__(self, num_classes = 80, ignore_thre=0.7, label_smooth = F...
method forward (line 96) | def forward(self, x, targets=None, epoch=0):
FILE: models/yolov3_baseline.py
function create_yolov3_modules (line 8) | def create_yolov3_modules(num_classes, ignore_thre, label_smooth, rfb):
class YOLOv3 (line 74) | class YOLOv3(nn.Module):
method __init__ (line 80) | def __init__(self, num_classes = 80, ignore_thre=0.7, label_smooth = F...
method forward (line 85) | def forward(self, x, targets=None, epoch=0):
FILE: models/yolov3_head.py
class YOLOv3Head (line 10) | class YOLOv3Head(nn.Module):
method __init__ (line 11) | def __init__(self, anch_mask, n_classes, stride, in_ch=1024, ignore_th...
method forward (line 49) | def forward(self, xin, labels=None):
FILE: models/yolov3_mobilev2.py
function create_yolov3_mobilenet_v2 (line 6) | def create_yolov3_mobilenet_v2(num_classes, width_mult=1.0, inverted_res...
class YOLOv3 (line 85) | class YOLOv3(nn.Module):
method __init__ (line 91) | def __init__(self, num_classes = 80, ignore_thre=0.7, label_smooth = F...
method forward (line 125) | def forward(self, x, targets=None, epoch=0):
FILE: utils/DCN/deform_conv2d_naive.py
class deform_conv2d_naive (line 10) | class deform_conv2d_naive(Module):
method __init__ (line 11) | def __init__(self, in_channels, out_channels,
method reset_parameters (line 32) | def reset_parameters(self):
method forward (line 40) | def forward(self, input, offset):
method compute_mesh_grid (line 68) | def compute_mesh_grid(self, in_h, in_w):
FILE: utils/DCN/functions/deform_conv2d_func.py
class DeformConv2dFunction (line 15) | class DeformConv2dFunction(Function):
method forward (line 18) | def forward(ctx, input, offset, weight, bias,
method backward (line 42) | def backward(ctx, grad_output):
FILE: utils/DCN/functions/modulated_deform_conv2d_func.py
class ModulatedDeformConv2dFunction (line 15) | class ModulatedDeformConv2dFunction(Function):
method forward (line 17) | def forward(ctx, input, offset, mask, weight, bias,
method backward (line 40) | def backward(ctx, grad_output):
FILE: utils/DCN/modules/deform_conv2d.py
class DeformConv2d (line 14) | class DeformConv2d(nn.Module):
method __init__ (line 16) | def __init__(self, in_channels, out_channels,
method reset_parameters (line 44) | def reset_parameters(self):
method forward (line 52) | def forward(self, input, offset):
class DeformConv2dPack (line 67) | class DeformConv2dPack(DeformConv2d):
method __init__ (line 69) | def __init__(self, in_channels, out_channels,
method init_offset (line 86) | def init_offset(self):
method forward (line 90) | def forward(self, input):
class DeformConv2dPackMore (line 103) | class DeformConv2dPackMore(DeformConv2d):
method __init__ (line 105) | def __init__(self, in_channels, out_channels,
method init_offset (line 122) | def init_offset(self):
method forward (line 126) | def forward(self, input):
FILE: utils/DCN/modules/modulated_deform_conv2d.py
class ModulatedDeformConv2d (line 14) | class ModulatedDeformConv2d(nn.Module):
method __init__ (line 16) | def __init__(self, in_channels, out_channels,
method reset_parameters (line 43) | def reset_parameters(self):
method forward (line 51) | def forward(self, input, offset, mask):
class ModulatedDeformConv2dPack (line 68) | class ModulatedDeformConv2dPack(ModulatedDeformConv2d):
method __init__ (line 70) | def __init__(self, in_channels, out_channels,
method init_offset (line 87) | def init_offset(self):
method forward (line 91) | def forward(self, input):
FILE: utils/DCN/setup.py
function get_extensions (line 17) | def get_extensions():
FILE: utils/DCN/src/cpu/deform_conv2d_cpu.cpp
function deform_conv2d_cpu_forward (line 7) | at::Tensor
function deform_conv2d_cpu_backward (line 27) | std::vector<at::Tensor>
FILE: utils/DCN/src/cpu/modulated_deform_conv2d_cpu.cpp
function modulated_deform_conv2d_cpu_forward (line 7) | at::Tensor
function modulated_deform_conv2d_cpu_backward (line 28) | std::vector<at::Tensor>
FILE: utils/DCN/src/vision.cpp
function PYBIND11_MODULE (line 5) | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
FILE: utils/cocoapi_evaluator.py
function _accumulate_predictions_from_multiple_gpus (line 19) | def _accumulate_predictions_from_multiple_gpus(predictions_per_gpu):
class COCOAPIEvaluator (line 31) | class COCOAPIEvaluator():
method __init__ (line 37) | def __init__(self, data_dir, img_size, confthre, nmsthre, testset=Fals...
method evaluate (line 74) | def evaluate(self, model, half=False, distributed=False):
FILE: utils/distributed_util.py
function get_world_size (line 9) | def get_world_size():
function get_rank (line 15) | def get_rank():
function is_main_process (line 21) | def is_main_process():
function synchronize (line 27) | def synchronize():
function _encode (line 53) | def _encode(encoded_data, data):
function _decode (line 67) | def _decode(encoded_data):
function scatter_gather (line 75) | def scatter_gather(data):
function reduce_loss_dict (line 140) | def reduce_loss_dict(loss_dict):
FILE: utils/fp16_utils/fp16_optimizer.py
class FP16_Optimizer (line 11) | class FP16_Optimizer(object):
method __init__ (line 105) | def __init__(self,
method maybe_print (line 177) | def maybe_print(self, msg):
method __getstate__ (line 181) | def __getstate__(self):
method __setstate__ (line 184) | def __setstate__(self, state):
method zero_grad (line 187) | def zero_grad(self, set_grads_to_None=False):
method _check_overflow (line 213) | def _check_overflow(self):
method _update_scale (line 223) | def _update_scale(self, has_overflow=False):
method _master_params_to_model_params (line 226) | def _master_params_to_model_params(self):
method _model_grads_to_master_grads (line 232) | def _model_grads_to_master_grads(self):
method _downscale_master (line 236) | def _downscale_master(self):
method clip_master_grads (line 243) | def clip_master_grads(self, max_norm, norm_type=2):
method state_dict (line 267) | def state_dict(self):
method load_state_dict (line 288) | def load_state_dict(self, state_dict):
method step (line 330) | def step(self, closure=None): # could add clip option.
method _step_with_closure (line 386) | def _step_with_closure(self, closure):
method backward (line 425) | def backward(self, loss, update_master_grads=True, retain_graph=False):
method update_master_grads (line 487) | def update_master_grads(self):
method inspect_master_grad_data (line 500) | def inspect_master_grad_data(self):
method _get_loss_scale (line 535) | def _get_loss_scale(self):
method _set_loss_scale (line 538) | def _set_loss_scale(self, value):
method _get_state (line 544) | def _get_state(self):
method _set_state (line 547) | def _set_state(self, value):
method _get_param_groups (line 554) | def _get_param_groups(self):
method _set_param_groups (line 557) | def _set_param_groups(self, value):
FILE: utils/fp16_utils/fp16util.py
class tofp16 (line 7) | class tofp16(nn.Module):
method __init__ (line 15) | def __init__(self):
method forward (line 18) | def forward(self, input):
function BN_convert_float (line 22) | def BN_convert_float(module):
function network_to_half (line 35) | def network_to_half(network):
function convert_module (line 44) | def convert_module(module, dtype):
function convert_network (line 60) | def convert_network(network, dtype):
class FP16Model (line 71) | class FP16Model(nn.Module):
method __init__ (line 76) | def __init__(self, network):
method forward (line 80) | def forward(self, *inputs):
function backwards_debug_hook (line 85) | def backwards_debug_hook(grad):
function prep_param_lists (line 88) | def prep_param_lists(model, flat_master=False):
function model_grads_to_master_grads (line 134) | def model_grads_to_master_grads(model_params, master_params, flat_master...
function master_params_to_model_params (line 156) | def master_params_to_model_params(model_params, master_params, flat_mast...
function to_python_float (line 174) | def to_python_float(t):
FILE: utils/fp16_utils/loss_scaler.py
function to_python_float (line 4) | def to_python_float(t):
class LossScaler (line 10) | class LossScaler:
method __init__ (line 22) | def __init__(self, scale=1):
method has_overflow (line 26) | def has_overflow(self, params):
method _has_inf_or_nan (line 30) | def _has_inf_or_nan(x):
method update_scale (line 33) | def update_scale(self, overflow):
method loss_scale (line 37) | def loss_scale(self):
method scale_gradient (line 40) | def scale_gradient(self, module, grad_in, grad_out):
method backward (line 43) | def backward(self, loss, retain_graph=False):
class DynamicLossScaler (line 47) | class DynamicLossScaler:
method __init__ (line 73) | def __init__(self,
method has_overflow (line 84) | def has_overflow(self, params):
method _has_inf_or_nan (line 92) | def _has_inf_or_nan(x):
method update_scale (line 113) | def update_scale(self, overflow):
method loss_scale (line 124) | def loss_scale(self):
method scale_gradient (line 127) | def scale_gradient(self, module, grad_in, grad_out):
method backward (line 130) | def backward(self, loss, retain_graph=False):
FILE: utils/utils.py
function postprocess (line 7) | def postprocess(prediction, num_classes, conf_thre=0.7, nms_thre=0.45):
function bboxes_iou (line 72) | def bboxes_iou(bboxes_a, bboxes_b, xyxy=True):
function matrix_iou (line 114) | def matrix_iou(a,b):
function visual (line 126) | def visual(img, boxes, scores):
FILE: utils/vis_utils.py
function make_vis (line 15) | def make_vis(dataset, index, img, fuse_weights, fused_fs):
function make_pred_vis (line 34) | def make_pred_vis(dataset,index, img, class_names, bboxes, cls, scores):
function vis (line 48) | def vis(img, boxes, scores, cls_ids, conf=0.5, class_names=None, color=N...
function add_heat (line 91) | def add_heat(image, heat_map, max_v, min_v, alpha=0.4, save=None, cmap='...
FILE: utils/voc_evaluator.py
function _accumulate_predictions_from_multiple_gpus (line 20) | def _accumulate_predictions_from_multiple_gpus(predictions_per_gpu):
class VOCEvaluator (line 43) | class VOCEvaluator():
method __init__ (line 49) | def __init__(self, data_dir, img_size, confthre, nmsthre,vis=False):
method evaluate (line 75) | def evaluate(self, model, half=False):
Condensed preview — 55 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (385K chars).
[
{
"path": ".gitignore",
"chars": 189,
"preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.pyc\n\n# C extensions\n*.so\n*.o\n\n# Distribution / packaging\n.Python\n"
},
{
"path": "LICENSE",
"chars": 35149,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "README.md",
"chars": 8981,
"preview": "# Learning Spatial Fusion for Single-Shot Object Detection\n\nBy Songtao Liu, Di Huang, Yunhong Wang\n\n### Introduction\nIn "
},
{
"path": "config/yolov3_baseline.cfg",
"chars": 325,
"preview": "MODEL:\n TYPE: YOLOv3\n BACKBONE: darknet53\nTRAIN:\n LR: 0.001\n MOMENTUM: 0.9\n DECAY: 0.0005\n BURN_IN: 5\n MAXEPOCH: "
},
{
"path": "config/yolov3_mobile.cfg",
"chars": 308,
"preview": "MODEL:\n TYPE: YOLOv3\n BACKBONE: mobile\nTRAIN:\n LR: 0.001\n MOMENTUM: 0.9\n DECAY: 0.0005\n BURN_IN: 5\n MAXEPOCH: 300"
},
{
"path": "dataset/__init__.py",
"chars": 26,
"preview": "# -*- coding: utf-8 -*-\n\n\n"
},
{
"path": "dataset/cocodataset.py",
"chars": 5786,
"preview": "import os\nimport numpy as np\n\nimport torch\nfrom .dataloading import Dataset\nimport cv2\nfrom pycocotools.coco import COCO"
},
{
"path": "dataset/data_augment.py",
"chars": 13712,
"preview": "\"\"\"Data augmentation functionality. Passed as callable transformations to\nDataset classes.\n\nThe data augmentation proced"
},
{
"path": "dataset/dataloading.py",
"chars": 9654,
"preview": "import random\nimport logging\nfrom functools import wraps\nimport torch\nfrom torch.utils.data.dataset import Dataset as to"
},
{
"path": "dataset/mixupdetection.py",
"chars": 4918,
"preview": "\"\"\"Mixup detection dataset wrapper.\"\"\"\nfrom __future__ import absolute_import\nimport numpy as np\nimport torch\n#from mxne"
},
{
"path": "dataset/voc_eval.py",
"chars": 7025,
"preview": "# --------------------------------------------------------\n# Fast/er R-CNN\n# Licensed under The MIT License [see LICENSE"
},
{
"path": "dataset/vocdataset.py",
"chars": 11514,
"preview": "\"\"\"VOC Dataset Classes\n\nOriginal author: Francisco Massa\nhttps://github.com/fmassa/vision/blob/voc_dataset/torchvision/d"
},
{
"path": "demo.py",
"chars": 4487,
"preview": "from utils.utils import *\nfrom dataset.vocdataset import VOC_CLASSES\nfrom dataset.cocodataset import COCO_CLASSES\nfrom d"
},
{
"path": "eval.py",
"chars": 6293,
"preview": "from utils.utils import *\nfrom utils.cocoapi_evaluator import COCOAPIEvaluator\nfrom utils.voc_evaluator import VOCEvalua"
},
{
"path": "main.py",
"chars": 18563,
"preview": "from utils.utils import *\nfrom utils.cocoapi_evaluator import COCOAPIEvaluator\nfrom utils.voc_evaluator import VOCEvalua"
},
{
"path": "make.sh",
"chars": 38,
"preview": "cd utils/DCN\n\npython setup.py install\n"
},
{
"path": "models/network_blocks.py",
"chars": 17213,
"preview": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom utils.DCN.mo"
},
{
"path": "models/utils_loss.py",
"chars": 2003,
"preview": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\n\nclass IOUWH_los"
},
{
"path": "models/yolov3_asff.py",
"chars": 7737,
"preview": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom .network_blocks import *\nfrom .yolov3_head impor"
},
{
"path": "models/yolov3_baseline.py",
"chars": 6579,
"preview": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom collections import defaultdict\nfrom .network_blo"
},
{
"path": "models/yolov3_head.py",
"chars": 13416,
"preview": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom utils.utils "
},
{
"path": "models/yolov3_mobilev2.py",
"chars": 8633,
"preview": "from torch import nn\nfrom .network_blocks import *\nfrom .yolov3_head import YOLOv3Head\n\n\ndef create_yolov3_mobilenet_v2("
},
{
"path": "utils/DCN/deform_conv2d_naive.py",
"chars": 4787,
"preview": "import torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport math\nimport numpy as np\nfrom torch.nn.modules.module"
},
{
"path": "utils/DCN/functions/__init__.py",
"chars": 125,
"preview": "from .deform_conv2d_func import DeformConv2dFunction\nfrom .modulated_deform_conv2d_func import ModulatedDeformConv2dFunc"
},
{
"path": "utils/DCN/functions/deform_conv2d_func.py",
"chars": 2472,
"preview": "#!/usr/bin/env python\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ impor"
},
{
"path": "utils/DCN/functions/modulated_deform_conv2d_func.py",
"chars": 2490,
"preview": "#!/usr/bin/env python\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ impor"
},
{
"path": "utils/DCN/make.sh",
"chars": 31,
"preview": "python setup.py build install \n"
},
{
"path": "utils/DCN/modules/__init__.py",
"chars": 205,
"preview": "from .deform_conv2d import DeformConv2d, _DeformConv2d, DeformConv2dPack, DeformConv2dPackMore\nfrom .modulated_deform_co"
},
{
"path": "utils/DCN/modules/deform_conv2d.py",
"chars": 6124,
"preview": "#!/usr/bin/env python\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ impor"
},
{
"path": "utils/DCN/modules/modulated_deform_conv2d.py",
"chars": 4772,
"preview": "#!/usr/bin/env python\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ impor"
},
{
"path": "utils/DCN/setup.py",
"chars": 1862,
"preview": "#!/usr/bin/env python\n\nimport os\nimport glob\n\nimport torch\n\nfrom torch.utils.cpp_extension import CUDA_HOME\nfrom torch.u"
},
{
"path": "utils/DCN/src/cpu/deform_conv2d_cpu.cpp",
"chars": 1707,
"preview": "#include <vector>\n\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n\n\nat::Tensor\ndeform_conv2d_cpu_forward(cons"
},
{
"path": "utils/DCN/src/cpu/deform_conv2d_cpu.h",
"chars": 1590,
"preview": "#pragma once\n#include <torch/extension.h>\n\nat::Tensor\ndeform_conv2d_cpu_forward(const at::Tensor &input,\n "
},
{
"path": "utils/DCN/src/cpu/modulated_deform_conv2d_cpu.cpp",
"chars": 2138,
"preview": "#include <vector>\n\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n\n\nat::Tensor\nmodulated_deform_conv2d_cpu_fo"
},
{
"path": "utils/DCN/src/cpu/modulated_deform_conv2d_cpu.h",
"chars": 2021,
"preview": "#pragma once\n#include <torch/extension.h>\n\nat::Tensor\nmodulated_deform_conv2d_cpu_forward(const at::Tensor &input,\n "
},
{
"path": "utils/DCN/src/cuda/deform_2d_im2col_cuda.cuh",
"chars": 19278,
"preview": "#include <cstdio>\n#include <algorithm>\n#include <cstring>\n\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n\n//"
},
{
"path": "utils/DCN/src/cuda/deform_conv2d_cuda.cu",
"chars": 14926,
"preview": "#include <vector>\n#include \"cuda/deform_2d_im2col_cuda.cuh\"\n\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n#"
},
{
"path": "utils/DCN/src/cuda/deform_conv2d_cuda.h",
"chars": 1620,
"preview": "#pragma once\n#include <torch/extension.h>\n\nat::Tensor\ndeform_conv2d_cuda_forward(const at::Tensor &input,\n "
},
{
"path": "utils/DCN/src/cuda/modulated_deform_2d_im2col_cuda.cuh",
"chars": 22136,
"preview": "#include <cstdio>\n#include <algorithm>\n#include <cstring>\n\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n\n//"
},
{
"path": "utils/DCN/src/cuda/modulated_deform_conv2d_cuda.cu",
"chars": 16032,
"preview": "#include <vector>\n#include \"cuda/modulated_deform_2d_im2col_cuda.cuh\"\n\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDACo"
},
{
"path": "utils/DCN/src/cuda/modulated_deform_conv2d_cuda.h",
"chars": 2053,
"preview": "#pragma once\n#include <torch/extension.h>\n\nat::Tensor\nmodulated_deform_conv2d_cuda_forward(const at::Tensor &input,\n "
},
{
"path": "utils/DCN/src/deform_conv2d.h",
"chars": 2911,
"preview": "#pragma once\n\n#include \"cpu/deform_conv2d_cpu.h\"\n\n#ifdef WITH_CUDA\n#include \"cuda/deform_conv2d_cuda.h\"\n#endif\n\n\nat::Ten"
},
{
"path": "utils/DCN/src/modulated_deform_conv2d.h",
"chars": 3421,
"preview": "#pragma once\n\n#include \"cpu/modulated_deform_conv2d_cpu.h\"\n\n#ifdef WITH_CUDA\n#include \"cuda/modulated_deform_conv2d_cuda"
},
{
"path": "utils/DCN/src/vision.cpp",
"chars": 509,
"preview": "\n#include \"deform_conv2d.h\"\n#include \"modulated_deform_conv2d.h\"\n\nPYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {\n m.def(\"de"
},
{
"path": "utils/__init__.py",
"chars": 26,
"preview": "# -*- coding: utf-8 -*-\n\n\n"
},
{
"path": "utils/cocoapi_evaluator.py",
"chars": 7958,
"preview": "import json\nimport tempfile\nimport sys\nfrom tqdm import tqdm\n\nfrom pycocotools.cocoeval import COCOeval\nfrom torch.autog"
},
{
"path": "utils/distributed_util.py",
"chars": 5368,
"preview": "import os\nimport pickle\nimport tempfile\nimport time\n\nimport torch\n\n\ndef get_world_size():\n if not torch.distributed.i"
},
{
"path": "utils/fp16_utils/README.md",
"chars": 1443,
"preview": "fp16_optimizer.py contains `FP16_Optimizer`, a Python class designed to wrap an existing Pytorch optimizer and automatic"
},
{
"path": "utils/fp16_utils/__init__.py",
"chars": 367,
"preview": "from .fp16util import (\n BN_convert_float,\n network_to_half,\n prep_param_lists,\n model_grads_to_master_grads"
},
{
"path": "utils/fp16_utils/fp16_optimizer.py",
"chars": 29496,
"preview": "import torch\r\nfrom torch import nn\r\nfrom torch.autograd import Variable\r\nfrom torch.nn.parameter import Parameter\r\nfrom "
},
{
"path": "utils/fp16_utils/fp16util.py",
"chars": 7000,
"preview": "import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch._utils import _flatten_dense_tensors, "
},
{
"path": "utils/fp16_utils/loss_scaler.py",
"chars": 7568,
"preview": "import torch\n\n# item() is a recent addition, so this helps with backward compatibility.\ndef to_python_float(t):\n if h"
},
{
"path": "utils/utils.py",
"chars": 5415,
"preview": "from __future__ import division\nimport torch\nimport torchvision\nimport numpy as np\nimport cv2\n\ndef postprocess(predictio"
},
{
"path": "utils/vis_utils.py",
"chars": 3480,
"preview": "# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport os \nimport matplotlib\n\nmatplotlib.use('AGG')\n\nimport matplotlib.pyplo"
},
{
"path": "utils/voc_evaluator.py",
"chars": 7652,
"preview": "import json\nimport tempfile\nimport sys\nfrom tqdm import tqdm\n\nfrom pycocotools.cocoeval import COCOeval\nfrom torch.autog"
}
]
About this extraction
This page contains the full source code of the GOATmessi7/ASFF GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 55 files (362.8 KB), approximately 90.2k tokens, and a symbol index with 239 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.