Showing preview only (281K chars total). Download the full file or copy to clipboard to get everything.
Repository: uzh-rpg/dagr
Branch: master
Commit: 0b1d3170bb47
Files: 62
Total size: 263.1 KB
Directory structure:
gitextract_6_j6wcbc/
├── .gitignore
├── LICENSE
├── config/
│ ├── dagr-l-dsec.yaml
│ ├── dagr-l-ncaltech.yaml
│ ├── dagr-m-dsec.yaml
│ ├── dagr-n-dsec.yaml
│ └── dagr-s-dsec.yaml
├── download_and_install_dependencies.sh
├── download_example_data.sh
├── install_env.sh
├── readme.md
├── scripts/
│ ├── check_dataset.py
│ ├── count_flops.py
│ ├── downsample_all_events.sh
│ ├── downsample_events.py
│ ├── run_test.py
│ ├── run_test_interframe.py
│ ├── train_dsec.py
│ ├── train_ncaltech101.py
│ └── visualize_detections.py
├── setup.py
└── src/
└── dagr/
├── asynchronous/
│ ├── __init__.py
│ ├── asy_tools/
│ │ └── main.cu
│ ├── base/
│ │ ├── __init__.py
│ │ ├── base.py
│ │ └── utils.py
│ ├── batch_norm.py
│ ├── cartesian.py
│ ├── conv.py
│ ├── evaluate_flops.py
│ ├── flops/
│ │ ├── __init__.py
│ │ └── conv.py
│ ├── linear.py
│ └── max_pool.py
├── data/
│ ├── augment.py
│ ├── dsec_data.py
│ ├── dsec_split.yaml
│ ├── dsec_utils.py
│ ├── ncaltech101_data.py
│ └── utils.py
├── graph/
│ ├── ev_graph.cu
│ ├── ev_graph.py
│ ├── spiral.h
│ └── utils.py
├── model/
│ ├── layers/
│ │ ├── components.py
│ │ ├── conv.py
│ │ ├── ev_tgn.py
│ │ ├── pooling.py
│ │ └── spline_conv.py
│ ├── networks/
│ │ ├── dagr.py
│ │ ├── ema.py
│ │ ├── net.py
│ │ └── net_img.py
│ └── utils.py
├── utils/
│ ├── args.py
│ ├── buffers.py
│ ├── coco_eval.py
│ ├── learning_rate_scheduler.py
│ ├── logging.py
│ └── testing.py
└── visualization/
├── bbox_viz.py
└── event_viz.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
*.so
*.egg-info/
*.pyc
build/
libs/
.idea/
================================================
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: config/dagr-l-dsec.yaml
================================================
dataset_directory: "/data/storage/daniel/aegnn/"
output_directory: "/data/storage/daniel/aegnn/logs"
task: detection
dataset: dsec
# network
radius: 0.01
time_window_us: 1000000
max_neighbors: 16
n_nodes: 50000
batch_size: 64
activation: relu
edge_attr_dim: 2
aggr: sum
kernel_size: 5
pooling_aggr: max
base_width: 0.5
after_pool_width: 1
net_stem_width: 1
yolo_stem_width: 1
num_scales: 2
# learning
weight_decay: 0.00001
clip: 0.1
pooling_dim_at_output: 5x7
aug_trans: 0.1
aug_zoom: 1.5
aug_p_flip: 0.5
img_net: resnet18
l_r: 0.0002
tot_num_epochs: 801
================================================
FILE: config/dagr-l-ncaltech.yaml
================================================
path: "/data/storage/daniel/aegnn"
output_directory: "/data/storage/daniel/aegnn/logs"
pooling_dim_at_output: 5x7
task: detection
dataset: ncaltech101
# network
radius: 0.01
time_window_us: 1000000
max_neighbors: 16
n_nodes: 50000
batch_size: 64
activation: relu
edge_attr_dim: 2
aggr: sum
kernel_size: 5
pooling_aggr: max
base_width: 0.5
after_pool_width: 1
net_stem_width: 1
yolo_stem_width: 1
num_scales: 1
# learning
weight_decay: 0.00001
clip: 0.1
aug_trans: 0.1
aug_p_flip: 0
aug_zoom: 1
l_r: 0.001
tot_num_epochs: 801
================================================
FILE: config/dagr-m-dsec.yaml
================================================
dataset_directory: "/data/storage/daniel/aegnn/"
output_directory: "/data/storage/daniel/aegnn/logs"
task: detection
dataset: dsec
# network
radius: 0.01
time_window_us: 1000000
max_neighbors: 16
n_nodes: 50000
batch_size: 64
activation: relu
edge_attr_dim: 2
aggr: sum
kernel_size: 5
pooling_aggr: max
base_width: 0.5
after_pool_width: 1
net_stem_width: 0.75
yolo_stem_width: 0.75
num_scales: 2
# learning
weight_decay: 0.00001
clip: 0.1
pooling_dim_at_output: 5x7
aug_trans: 0.1
aug_zoom: 1.5
aug_p_flip: 0.5
img_net: resnet18
l_r: 0.0002
tot_num_epochs: 801
================================================
FILE: config/dagr-n-dsec.yaml
================================================
dataset_directory: "/data/storage/daniel/aegnn/"
output_directory: "/data/storage/daniel/aegnn/logs"
task: detection
dataset: dsec
# network
radius: 0.01
time_window_us: 1000000
max_neighbors: 16
n_nodes: 50000
batch_size: 64
activation: relu
edge_attr_dim: 2
aggr: sum
kernel_size: 5
pooling_aggr: max
base_width: 0.5
after_pool_width: 1
net_stem_width: 0.25
yolo_stem_width: 0.25
num_scales: 2
# learning
weight_decay: 0.00001
clip: 0.1
pooling_dim_at_output: 5x7
aug_trans: 0.1
aug_zoom: 1.5
aug_p_flip: 0.5
img_net: resnet18
l_r: 0.0002
tot_num_epochs: 801
================================================
FILE: config/dagr-s-dsec.yaml
================================================
dataset_directory: "/data/storage/daniel/aegnn/"
output_directory: "/data/storage/daniel/aegnn/logs"
task: detection
dataset: dsec
# network
radius: 0.01
time_window_us: 1000000
max_neighbors: 16
n_nodes: 50000
batch_size: 64
activation: relu
edge_attr_dim: 2
aggr: sum
kernel_size: 5
pooling_aggr: max
base_width: 0.5
after_pool_width: 1
net_stem_width: 0.5
yolo_stem_width: 0.5
num_scales: 2
# learning
weight_decay: 0.00001
clip: 0.1
pooling_dim_at_output: 5x7
aug_trans: 0.1
aug_zoom: 1.5
aug_p_flip: 0.5
img_net: resnet18
l_r: 0.0002
tot_num_epochs: 801
================================================
FILE: download_and_install_dependencies.sh
================================================
#! /usr/bin/env bash
DAGR_DIR=$(pwd)
# Download detectron2 for its fast mAP calculation function
mkdir $DAGR_DIR/libs
cd $DAGR_DIR/libs
git clone --no-checkout git@github.com:facebookresearch/detectron2.git
cd $DAGR_DIR/libs/detectron2/
git checkout 32bd159d7263683e39bf4e87e5c4ac88bad2fd73
# Download YOLOX
cd $DAGR_DIR/libs
git clone --no-checkout git@github.com:Megvii-BaseDetection/YOLOX.git
cd $DAGR_DIR/libs/YOLOX
git checkout 618fd8c08b2bc5fac9ffbb19a3b7e039ea0d5b9a
# Download dsec-det
cd $DAGR_DIR/libs
git clone git@github.com:uzh-rpg/dsec-det.git
cd $DAGR_DIR/libs/dsec-det
git checkout 81e381dc0fc1b1a540a604a970a37de038abb83b
pip install -e $DAGR_DIR/libs/dsec-det
pip install -e $DAGR_DIR/libs/detectron2
pip install -e $DAGR_DIR/libs/YOLOX
pip install seaborn
================================================
FILE: download_example_data.sh
================================================
#! /usr/bin/env bash
DAGR_DIR=$(pwd)
DATA_DIR=$DAGR_DIR/data
mkdir $DATA_DIR
wget https://download.ifi.uzh.ch/rpg/dagr/data/dagr_s_50.pth -O $DATA_DIR/dagr_s_50.pth
wget https://download.ifi.uzh.ch/rpg/dagr/data/DSEC_fragment.zip -O $DATA_DIR/DSEC_fragment.zip
unzip $DATA_DIR/DSEC_fragment.zip -d $DATA_DIR
rm -rf $DATA_DIR/DSEC_fragment.zip
================================================
FILE: install_env.sh
================================================
#! /usr/bin/env bash
TORCH=$(python -c "import torch; print(torch.__version__)")
CUDA=$(python -c "import torch; print(torch.version.cuda)")
URL=https://data.pyg.org/whl/torch-${TORCH}+${CUDA}.html
pip install --no-cache-dir torch-scatter -f $URL;
pip install --no-cache-dir torch-cluster -f $URL;
pip install --no-cache-dir torch-spline-conv -f $URL;
pip install --no-cache-dir torch-sparse -f $URL;
pip install torch-geometric;
pip install wandb numba hdf5plugin plotly matplotlib pycocotools opencv-python scikit-video pandas ruamel.yaml
================================================
FILE: readme.md
================================================
# Low Latency Automotive Vision with Event Cameras
<p align="center">
<a href="https://youtu.be/dwzGhMQCc4Y">
<img src="assets/Nature_Gehrig_YouTube_cover_yt.jpg" alt="DAGR" width="500"/>
</a>
</p>
This repository contains code from our 2024 Nature paper which can be accessed for free here [PDF Open Access](https://www.nature.com/articles/s41586-024-07409-w).
**_Low Latency Automotive Vision with Event Cameras_** by [Daniel Gehrig](https://danielgehrig18.github.io/) and [Davide Scaramuzza](http://rpg.ifi.uzh.ch/people_scaramuzza.html).
If you use our code or refer to this project, please cite it using
```bibtex
@Article{Gehrig24nature,
author = {Gehrig, Daniel and Scaramuzza, Davide},
title = {Low Latency Automotive Vision with Event Cameras},
booktitle = {Nature},
year = {2024}
}
```
## Updates
* Training code for N-Caltech101 and DSEC-DET have been open sourced. To train your model jump to the [training section](#training)
## Installation
First, download the github repository and its dependencies
```bash
WORK_DIR=/path/to/work/directory/
cd $WORK_DIR
git clone git@github.com:uzh-rpg/dagr.git
DAGR_DIR=$WORK_DIR/dagr
cd $DAGR_DIR
```
Then start by installing the main libraries. Make sure Anaconda (or better Mamba), PyTorch, and CUDA is installed.
```bash
cd $DAGR_DIR
conda create -y -n dagr python=3.8
conda activate dagr
conda install -y setuptools==69.5.1 mkl==2024.0 pytorch==1.11.0 torchvision==0.12.0 torchaudio==0.11.0 cudatoolkit=11.3 -c pytorch
```
Then install the pytorch-geometric libraries. This may take a while.
```bash
bash install_env.sh
```
The above bash file will figure out the CUDA and Torch version, and install the appropriate pytorch-geometric packages.
Then, download and install additional dependencies locally
```bash
bash download_and_install_dependencies.sh
conda install -y h5py blosc-hdf5-plugin
```
Finally, install the dagr package
```bash
pip install -e .
```
## Run Example
After installing, you can download a data fragment, and checkpoint with
```bash
bash download_example_data.sh
```
This will download a checkpoint and data fragment of DSEC-Detection on which you can test the code.
Once downloaded, run the following command
```bash
LOG_DIR=/path/to/log
DEVICE=1
CUDA_VISIBLE_DEVICES=$DEVICE python scripts/run_test_interframe.py --config config/dagr-s-dsec.yaml \
--use_image \
--img_net resnet50 \
--checkpoint data/dagr_s_50.pth \
--batch_size 8 \
--dataset_directory data/DSEC_fragment \
--no_eval \
--output_directory $LOG_DIR
```
note the wandb directory as `$WANDB_DIR` and then visualize the detections with
```bash
python scripts/visualize_detections.py --detections_folder $LOG_DIR/$WANDB_DIR \
--dataset_directory data/DSEC_fragment/test \
--vis_time_step_us 1000 \
--event_time_window_us 5000 \
--sequence zurich_city_13_b
```
## Test on DSEC
Start by downloading the DSEC dataset and the additional labelled data introduced in this work.
To do so, follow [these instructions](https://github.com/uzh-rpg/dsec-det?tab=readme-ov-file#download-dsec). They are based on the scripts
of [dsec-det](https://github.com/uzh-rpg/dsec-det), which can be found in `libs/dsec-det/scripts`.
To continue, complete sections [Download DSEC](https://github.com/uzh-rpg/dsec-det?tab=readme-ov-file#download-dsec) until [Test Alignment](https://github.com/uzh-rpg/dsec-det?tab=readme-ov-file#test-alignment).
If you already downloaded DSEC, make sure `$DSEC_ROOT` points to it, and instead start at section [Download DSEC-extra
](https://github.com/uzh-rpg/dsec-det?tab=readme-ov-file#download-dsec-extra).
After downloading all the data, change back to $DAGR_DIR, and start by downsampling the events
```bash
cd $DAGR_DIR
bash scripts/downsample_all_events.sh $DSEC_ROOT
```
### Running Evaluation
This repository implements three scripts for running evaluation of the model on DSEC-Det.
The first, evaluates the detection performance of the model after seeing one image, and the subsequent 50 milliseconds of events.
To run it, specify a device, and logging directory with type
```bash
LOG_DIR=/path/to/log
DEVICE=1
CUDA_VISIBLE_DEVICES=$DEVICE python scripts/run_test.py --config config/dagr-s-dsec.yaml \
--use_image \
--img_net resnet50 \
--checkpoint data/dagr_s_50.pth \
--batch_size 8 \
--dataset_directory $DSEC_ROOT \
--output_directory $LOG_DIR
```
Then, to evaluate the number of FLOPS generated in asynchronous mode, run
```bash
LOG_DIR=/path/to/log
DEVICE=1
CUDA_VISIBLE_DEVICES=$DEVICE python scripts/count_flops.py --config config/eagr-s-dsec.yaml \
--use_image \
--img_net resnet50 \
--checkpoint data/dagr_s_50.pth \
--batch_size 8 \
--dataset_directory $DSEC_ROOT \
--output_directory $LOG_DIR
```
Finally, to evaluate the interframe detection performance of our method run
```bash
LOG_DIR=/path/to/log
DEVICE=1
CUDA_VISIBLE_DEVICES=$DEVICE python scripts/run_test_interframe.py --config config/eagr-s-dsec.yaml \
--use_image \
--img_net resnet50 \
--checkpoint data/dagr_s_50.pth \
--batch_size 8 \
--dataset_directory $DSEC_ROOT \
--output_directory $LOG_DIR \
--num_interframe_steps 10
```
This last script will write the high-rate detections from our method into the folder `$LOG_DIR/$WANDB_DIR`,
where `$WANDB_DIR` is the automatically generated folder created by wandb.
To visualize the detections, use the following script:
```bash
python scripts/visualize_detections.py --detections_folder $LOG_DIR/$WANDB_DIR \
--dataset_directory $DSEC_ROOT/test/ \
--vis_time_step_us 1000 \
--event_time_window_us 5000 \
--sequence zurich_city_13_b
```
This will start a visualization window showing the detections over a given sequence. If you want to save the detections
to a video, use the `--write_to_output` flag, which will create a video in the folder `$LOG_DIR/$WANDB_DIR/visualization}`.
## Training
To train on N-Caltech101, download the files with
```bash
wget https://download.ifi.uzh.ch/rpg/dagr/data/ncaltech101.zip -P $DAGR_DIR/data/
cd $DAGR_DIR/data/
unzip ncaltech101.zip
rm -rf ncaltech101.zip
```
Then run training with
```bash
python scripts/train_ncaltech101.py --config config/dagr-l-ncaltech.yaml \
--exp_name ncaltech_l \
--dataset_directory $DAGR_DIR/data/ \
--output_directory $DAGR_DIR/logs/
```
To train on DSEC, make a symlink to the data directory via
```bash
ln -s $DSEC_ROOT $DAGR_DIR/data/dsec
```
Then run training with
```bash
python scripts/train_dsec.py --config config/dagr-s-dsec.yaml \
--exp_name dsec_s_50 \
--dataset_directory $DAGR_DIR/data/ \
--output_directory $DAGR_DIR/logs/ \
--use_image --img_net resnet50 --batch_size 32
```
================================================
FILE: scripts/check_dataset.py
================================================
================================================
FILE: scripts/count_flops.py
================================================
import os
import tqdm
import torch
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
from torch_geometric.data import DataLoader
from dagr.utils.args import FLOPS_FLAGS
from dagr.utils.buffers import DictBuffer, format_data
from dagr.data.augment import Augmentations
from dagr.data.dsec_data import DSEC
from dagr.model.networks.dagr import DAGR
from dagr.asynchronous.evaluate_flops import evaluate_flops
if __name__ == '__main__':
import torch_geometric
seed = 42
torch_geometric.seed.seed_everything(seed)
args = FLOPS_FLAGS()
assert "checkpoint" in args
project = f"flops-{args.dataset}-{args.task}"
pbar = tqdm.tqdm(total=4)
pbar.set_description("Loading dataset")
dataset_path = args.dataset_directory / args.dataset
print("init datasets")
dataset = DSEC(args.dataset_directory, "test", Augmentations.transform_testing, debug=True, min_bbox_diag=15, min_bbox_height=10)
loader = DataLoader(dataset, follow_batch=['bbox', "bbox0"], batch_size=args.batch_size, shuffle=False, num_workers=16)
pbar.update(1)
pbar.set_description("Initializing net")
model = DAGR(args, height=dataset.height, width=dataset.width)
model = model.cuda()
model.eval()
pbar.update(1)
assert "checkpoint" in args
checkpoint = torch.load(args.checkpoint)
model.load_state_dict(checkpoint['ema'])
pbar.update(1)
model.cache_luts(radius=args.radius, height=dataset.height, width=dataset.width)
pbar.set_description("Computing FLOPS")
buffer = DictBuffer()
args.output_directory.mkdir(parents=True, exist_ok=True)
pbar_flops = tqdm.tqdm(total=len(loader.dataset), desc="Computing FLOPS")
for i, data in enumerate(loader):
data = data.cuda(non_blocking=True)
data = format_data(data)
flops_evaluation = evaluate_flops(model, data,
check_consistency=args.check_consistency,
return_all_samples=True, dense=args.dense)
if flops_evaluation is None:
continue
buffer.update(flops_evaluation['flops_per_layer'])
buffer.save(args.output_directory / "flops_per_layer.pth")
tot_flops = sum(buffer.compute().values())
pbar_flops.set_description(f"Total FLOPS {tot_flops}")
pbar_flops.update(1)
print(sum(buffer.compute().values()))
pbar.update(1)
================================================
FILE: scripts/downsample_all_events.sh
================================================
#!/bin/bash
DSEC_ROOT=$1
for split in train test; do
for sequence in $DSEC_ROOT/$split/*/; do
infile=$sequence/events/left/events.h5
outfile=$sequence/events/left/events_2x.h5
python scripts/downsample_events.py --input_path $infile --output_path $outfile
done
done
================================================
FILE: scripts/downsample_events.py
================================================
import argparse
import tqdm
import hdf5plugin
import h5py
import weakref
import numba
import numpy as np
from pathlib import Path
from dsec_det.io import extract_from_h5_by_index, get_num_events
def _compression_opts():
compression_level = 1 # {0, ..., 9}
shuffle = 2 # {0: none, 1: byte, 2: bit}
# From https://github.com/Blosc/c-blosc/blob/7435f28dd08606bd51ab42b49b0e654547becac4/blosc/blosc.h#L66-L71
# define BLOSC_BLOSCLZ 0
# define BLOSC_LZ4 1
# define BLOSC_LZ4HC 2
# define BLOSC_SNAPPY 3
# define BLOSC_ZLIB 4
# define BLOSC_ZSTD 5
compressor_type = 5
compression_opts = (0, 0, 0, 0, compression_level, shuffle, compressor_type)
return compression_opts
H5_BLOSC_COMPRESSION_FLAGS = dict(
compression=32001,
compression_opts=_compression_opts(), # Blosc
chunks=True
)
def create_ms_to_idx(t_us):
t_ms = t_us // 1000
x, counts = np.unique(t_ms, return_counts=True)
ms_to_idx = np.zeros(shape=(t_ms[-1] + 2,), dtype="uint64")
ms_to_idx[x + 1] = counts
ms_to_idx = ms_to_idx[:-1].cumsum()
return ms_to_idx
class H5Writer:
def __init__(self, outfile):
assert not outfile.exists()
self.h5f = h5py.File(outfile, 'a')
self._finalizer = weakref.finalize(self, self.close_callback, self.h5f)
self.t_offset = None
self.num_events = 0
# create hdf5 datasets
shape = (2 ** 16,)
maxshape = (None,)
self.h5f.create_dataset(f'events/x', shape=shape, dtype='u2', maxshape=maxshape, **H5_BLOSC_COMPRESSION_FLAGS)
self.h5f.create_dataset(f'events/y', shape=shape, dtype='u2', maxshape=maxshape, **H5_BLOSC_COMPRESSION_FLAGS)
self.h5f.create_dataset(f'events/p', shape=shape, dtype='u1', maxshape=maxshape, **H5_BLOSC_COMPRESSION_FLAGS)
self.h5f.create_dataset(f'events/t', shape=shape, dtype='u4', maxshape=maxshape, **H5_BLOSC_COMPRESSION_FLAGS)
def create_ms_to_idx(self):
t_us = self.h5f['events/t'][()]
self.h5f.create_dataset(f'ms_to_idx', data=create_ms_to_idx(t_us), dtype='u8', **H5_BLOSC_COMPRESSION_FLAGS)
@staticmethod
def close_callback(h5f: h5py.File):
h5f.close()
def add_data(self, events):
if self.t_offset is None:
self.t_offset = events['t'][0]
self.h5f.create_dataset(f't_offset', data=self.t_offset, dtype='i8')
events['t'] -= self.t_offset
size = len(events['t'])
self.num_events += size
self.h5f[f'events/x'].resize(self.num_events, axis=0)
self.h5f[f'events/y'].resize(self.num_events, axis=0)
self.h5f[f'events/p'].resize(self.num_events, axis=0)
self.h5f[f'events/t'].resize(self.num_events, axis=0)
self.h5f[f'events/x'][self.num_events-size:self.num_events] = events['x']
self.h5f[f'events/y'][self.num_events-size:self.num_events] = events['y']
self.h5f[f'events/p'][self.num_events-size:self.num_events] = events['p']
self.h5f[f'events/t'][self.num_events-size:self.num_events] = events['t']
def downsample_events(events, input_height, input_width, output_height, output_width, change_map=None):
# this subsamples events if they were generated with cv2.INTER_AREA
if change_map is None:
change_map = np.zeros((output_height, output_width), dtype="float32")
fx = int(input_width / output_width)
fy = int(input_height / output_height)
mask = np.zeros(shape=(len(events['t']),), dtype="bool")
mask, change_map = _filter_events_resize(events['x'], events['y'], events['p'], mask, change_map, fx, fy)
events = {k: v[mask] for k, v in events.items()}
events['x'] = (events['x'] / fx).astype("uint16")
events['y'] = (events['y'] / fy).astype("uint16")
return events, change_map
@numba.jit(nopython=True, cache=True)
def _filter_events_resize(x, y, p, mask, change_map, fx, fy):
# iterates through x,y,p of events, and increments cells of size fx x fy by 1/(fx*fy)
# if one of these cells reaches +-1, then reset the cell, and pass through that event.
# for memory reasons, this only returns the True/False for every event, indicating if
# the event was skipped or passed through.
for i in range(len(x)):
x_l = x[i] // fx
y_l = y[i] // fy
change_map[y_l, x_l] += p[i] * 1.0 / (fx * fy)
if np.abs(change_map[y_l, x_l]) >= 1:
mask[i] = True
change_map[y_l, x_l] -= p[i]
return mask, change_map
if __name__ == '__main__':
parser = argparse.ArgumentParser("""Downsample events""")
parser.add_argument("--input_path", type=Path, required=True, help="Path to input events.h5. ")
parser.add_argument("--output_path", type=Path, required=True, help="Path where output events.h5 will be written.")
parser.add_argument("--input_height", type=int, default=480, help="Height of the input events resolution.")
parser.add_argument("--input_width", type=int, default=640, help="Width of the input events resolution")
parser.add_argument("--output_height", type=int, default=240, help="Height of the output events resolution.")
parser.add_argument("--output_width", type=int, default=320, help="Width of the output events resolution.")
args = parser.parse_args()
num_events = get_num_events(args.input_path)
num_events_per_chunk = 100000
num_iterations = num_events // num_events_per_chunk
writer = H5Writer(args.output_path)
change_map = None
pbar = tqdm.tqdm(total=num_iterations+1)
for i in range(num_iterations):
events = extract_from_h5_by_index(args.input_path, i * num_events_per_chunk, (i+1) * num_events_per_chunk)
events['p'] = 2 * events['p'].astype("int8") - 1
downsampled_events, change_map = downsample_events(events, change_map=change_map, input_height=args.input_height, input_width=args.input_width,
output_height=args.output_height, output_width=args.output_width)
events['p'] = ((events['p'] + 1)//2).astype("int8")
writer.add_data(downsampled_events)
pbar.update(1)
events = extract_from_h5_by_index(args.input_path, num_iterations * num_events_per_chunk, num_events)
downsampled_events, change_map = downsample_events(events, change_map=change_map, input_height=args.input_height,
input_width=args.input_width,
output_height=args.output_height, output_width=args.output_width)
writer.add_data(downsampled_events)
pbar.update(1)
writer.create_ms_to_idx()
================================================
FILE: scripts/run_test.py
================================================
# avoid matlab error on server
import os
import torch
import wandb
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
from torch_geometric.data import DataLoader
from dagr.utils.args import FLAGS
from dagr.data.dsec_data import DSEC
from dagr.data.augment import Augmentations
from dagr.model.networks.dagr import DAGR
from dagr.model.networks.ema import ModelEMA
from dagr.utils.logging import set_up_logging_directory, log_hparams
from dagr.utils.testing import run_test_with_visualization
if __name__ == '__main__':
import torch_geometric
import random
import numpy as np
seed = 42
torch_geometric.seed.seed_everything(seed)
torch.random.manual_seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
args = FLAGS()
output_directory = set_up_logging_directory(args.dataset, args.task, args.output_directory)
project = f"low_latency-{args.dataset}-{args.task}"
print(f"PROJECT: {project}")
log_hparams(args)
print("init datasets")
dataset_path = args.dataset_directory.parent / args.dataset
test_dataset = DSEC(args.dataset_directory, "test", Augmentations.transform_testing, debug=False, min_bbox_diag=15, min_bbox_height=10)
num_iters_per_epoch = 1
sampler = np.random.permutation(np.arange(len(test_dataset)))
test_loader = DataLoader(test_dataset, sampler=sampler, follow_batch=['bbox', 'bbox0'], batch_size=args.batch_size, shuffle=False, num_workers=4, drop_last=True)
print("init net")
# load a dummy sample to get height, width
model = DAGR(args, height=test_dataset.height, width=test_dataset.width)
model = model.cuda()
ema = ModelEMA(model)
assert "checkpoint" in args
checkpoint = torch.load(args.checkpoint)
ema.ema.load_state_dict(checkpoint['ema'])
ema.ema.cache_luts(radius=args.radius, height=test_dataset.height, width=test_dataset.width)
with torch.no_grad():
metrics = run_test_with_visualization(test_loader, ema.ema, dataset=args.dataset)
log_data = {f"testing/metric/{k}": v for k, v in metrics.items()}
wandb.log(log_data)
print(metrics['mAP'])
================================================
FILE: scripts/run_test_interframe.py
================================================
import torch
import tqdm
import wandb
import os
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
from torch_geometric.data import DataLoader
from pprint import pprint
from dagr.utils.logging import set_up_logging_directory, log_hparams
from dagr.utils.args import FLAGS
from dagr.utils.testing import run_test_with_visualization
from dagr.data.augment import Augmentations
from dagr.data.dsec_data import DSEC
from dagr.model.networks.dagr import DAGR
from dagr.model.networks.ema import ModelEMA
def to_npy(detections):
n_boxes = len(detections['boxes'])
dtype = np.dtype([('t', '<u8'), ('x', '<f4'), ('y', '<f4'), ('w', '<f4'), ('h', '<f4'), ('class_id', 'u1'), ('class_confidence', '<f4')])
data = np.zeros(shape=(n_boxes,), dtype=dtype)
data['t'] = detections['t']
data['x'] = detections['boxes'][:,0]
data['y'] = detections['boxes'][:,1]
data['w'] = detections['boxes'][:,2] - data['x']
data['h'] = detections['boxes'][:,3] - data['y']
data['class_id'] = detections['labels']
data['class_confidence'] = detections['scores']
return data
def save_detections(directory, detections):
sequence_detections_map = dict()
for d in tqdm.tqdm(detections, desc="compiling detections for saving..."):
s = d['sequence']
if s not in sequence_detections_map:
sequence_detections_map[s] = to_npy(d)
else:
sequence_detections_map[s] = np.concatenate([sequence_detections_map[s], to_npy(d)])
for s, detections in sequence_detections_map.items():
detections = detections[detections['t'].argsort()]
np.save(directory / f"detections_{s}.npy", detections)
if __name__ == '__main__':
import torch_geometric
import random
import numpy as np
seed = 42
torch_geometric.seed.seed_everything(seed)
torch.random.manual_seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
args = FLAGS()
output_directory = set_up_logging_directory(args.dataset, args.task, args.output_directory)
log_hparams(args)
print("init datasets")
test_dataset = DSEC(root=args.dataset_directory, split="test", transform=Augmentations.transform_testing,
debug=False, min_bbox_diag=15, min_bbox_height=10, only_perfect_tracks=True,
no_eval=args.no_eval)
test_loader = DataLoader(test_dataset, follow_batch=['bbox', "bbox0"], batch_size=args.batch_size, shuffle=False, num_workers=0, drop_last=True)
print("init net")
model = DAGR(args, height=test_dataset.height, width=test_dataset.width)
model = model.cuda()
ema = ModelEMA(model)
assert "checkpoint" in args
checkpoint = torch.load(args.checkpoint)
ema.ema.load_state_dict(checkpoint['ema'])
ema.ema.cache_luts(radius=args.radius, height=test_dataset.height, width=test_dataset.width)
detections = []
with torch.no_grad():
for n_us in np.linspace(0, 50000, args.num_interframe_steps):
test_loader.dataset.set_num_us(int(n_us))
metrics, detections_one_offset = run_test_with_visualization(test_loader, ema.ema, dataset=args.dataset, name=wandb.run.name, compile_detections=True,
no_eval=args.no_eval)
detections.extend(detections_one_offset)
if metrics is not None:
pprint(f"Time Window: {int(n_us)} ms \t mAP: {metrics['mAP']}")
save_detections(output_directory, detections)
================================================
FILE: scripts/train_dsec.py
================================================
# avoid matlab error on server
import os
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
import torch
import tqdm
import wandb
from pathlib import Path
import argparse
from torch_geometric.data import DataLoader
from dagr.utils.logging import Checkpointer, set_up_logging_directory, log_hparams
from dagr.utils.buffers import DetectionBuffer
from dagr.utils.args import FLAGS
from dagr.utils.learning_rate_scheduler import LRSchedule
from dagr.data.augment import Augmentations
from dagr.utils.buffers import format_data
from dagr.data.dsec_data import DSEC
from dagr.model.networks.dagr import DAGR
from dagr.model.networks.ema import ModelEMA
def gradients_broken(model):
valid_gradients = True
for name, param in model.named_parameters():
if param.grad is not None:
# valid_gradients = not (torch.isnan(param.grad).any() or torch.isinf(param.grad).any())
valid_gradients = not (torch.isnan(param.grad).any())
if not valid_gradients:
break
return not valid_gradients
def fix_gradients(model):
for name, param in model.named_parameters():
if param.grad is not None:
param.grad = torch.nan_to_num(param.grad, nan=0.0)
def train(loader: DataLoader,
model: torch.nn.Module,
ema: ModelEMA,
scheduler: torch.optim.lr_scheduler.LambdaLR,
optimizer: torch.optim.Optimizer,
args: argparse.ArgumentParser,
run_name=""):
model.train()
for i, data in enumerate(tqdm.tqdm(loader, desc=f"Training {run_name}")):
data = data.cuda(non_blocking=True)
data = format_data(data)
optimizer.zero_grad(set_to_none=True)
model_outputs = model(data)
loss_dict = {k: v for k, v in model_outputs.items() if "loss" in k}
loss = loss_dict.pop("total_loss")
loss.backward()
torch.nn.utils.clip_grad_value_(model.parameters(), args.clip)
fix_gradients(model)
optimizer.step()
scheduler.step()
ema.update(model)
training_logs = {f"training/loss/{k}": v for k, v in loss_dict.items()}
wandb.log({"training/loss": loss.item(), "training/lr": scheduler.get_last_lr()[-1], **training_logs})
def run_test(loader: DataLoader,
model: torch.nn.Module,
dry_run_steps: int=-1,
dataset="gen1"):
model.eval()
mapcalc = DetectionBuffer(height=loader.dataset.height, width=loader.dataset.width, classes=loader.dataset.classes)
for i, data in enumerate(tqdm.tqdm(loader)):
data = data.cuda()
data = format_data(data)
detections, targets = model(data)
if i % 10 == 0:
torch.cuda.empty_cache()
mapcalc.update(detections, targets, dataset, data.height[0], data.width[0])
if dry_run_steps > 0 and i == dry_run_steps:
break
torch.cuda.empty_cache()
return mapcalc
if __name__ == '__main__':
import torch_geometric
import random
import numpy as np
seed = 42
torch_geometric.seed.seed_everything(seed)
torch.random.manual_seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
args = FLAGS()
output_directory = set_up_logging_directory(args.dataset, args.task, args.output_directory, exp_name=args.exp_name)
log_hparams(args)
augmentations = Augmentations(args)
print("init datasets")
dataset_path = args.dataset_directory / args.dataset
train_dataset = DSEC(root=dataset_path, split="train", transform=augmentations.transform_training, debug=False,
min_bbox_diag=15, min_bbox_height=10)
test_dataset = DSEC(root=dataset_path, split="val", transform=augmentations.transform_testing, debug=False,
min_bbox_diag=15, min_bbox_height=10)
train_loader = DataLoader(train_dataset, follow_batch=['bbox', 'bbox0'], batch_size=args.batch_size, shuffle=True, num_workers=4, drop_last=True)
num_iters_per_epoch = len(train_loader)
sampler = np.random.permutation(np.arange(len(test_dataset)))
test_loader = DataLoader(test_dataset, sampler=sampler, follow_batch=['bbox', 'bbox0'], batch_size=args.batch_size, shuffle=False, num_workers=4, drop_last=True)
print("init net")
# load a dummy sample to get height, width
model = DAGR(args, height=test_dataset.height, width=test_dataset.width)
num_params = sum([np.prod(p.size()) for p in model.parameters()])
print(f"Training with {num_params} number of parameters.")
model = model.cuda()
ema = ModelEMA(model)
nominal_batch_size = 64
lr = args.l_r * np.sqrt(args.batch_size) / np.sqrt(nominal_batch_size)
optimizer = torch.optim.AdamW(list(model.parameters()), lr=lr, weight_decay=args.weight_decay)
lr_func = LRSchedule(warmup_epochs=.3,
num_iters_per_epoch=num_iters_per_epoch,
tot_num_epochs=args.tot_num_epochs)
lr_scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer=optimizer, lr_lambda=lr_func)
checkpointer = Checkpointer(output_directory=output_directory,
model=model, optimizer=optimizer,
scheduler=lr_scheduler, ema=ema,
args=args)
start_epoch = checkpointer.restore_if_existing(output_directory, resume_from_best=False)
start_epoch = 0
if "resume_checkpoint" in args:
start_epoch = checkpointer.restore_checkpoint(args.resume_checkpoint, best=False)
print(f"Resume from checkpoint at epoch {start_epoch}")
with torch.no_grad():
mapcalc = run_test(test_loader, ema.ema, dry_run_steps=2, dataset=args.dataset)
mapcalc.compute()
print("starting to train")
for epoch in range(start_epoch, args.tot_num_epochs):
train(train_loader, model, ema, lr_scheduler, optimizer, args, run_name=wandb.run.name)
checkpointer.checkpoint(epoch, name=f"last_model")
if epoch % 3 > 0:
continue
with torch.no_grad():
mapcalc = run_test(test_loader, ema.ema, dataset=args.dataset)
metrics = mapcalc.compute()
checkpointer.process(metrics, epoch)
================================================
FILE: scripts/train_ncaltech101.py
================================================
# avoid matlab error on server
import os
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
import torch
import tqdm
import wandb
from pathlib import Path
import argparse
from torch_geometric.data import DataLoader
from dagr.utils.logging import Checkpointer, set_up_logging_directory, log_hparams
from dagr.utils.buffers import DetectionBuffer
from dagr.utils.args import FLAGS
from dagr.utils.learning_rate_scheduler import LRSchedule
from dagr.data.augment import Augmentations
from dagr.utils.buffers import format_data
from dagr.data.ncaltech101_data import NCaltech101
from dagr.model.networks.dagr import DAGR
from dagr.model.networks.ema import ModelEMA
def gradients_broken(model):
valid_gradients = True
for name, param in model.named_parameters():
if param.grad is not None:
# valid_gradients = not (torch.isnan(param.grad).any() or torch.isinf(param.grad).any())
valid_gradients = not (torch.isnan(param.grad).any())
if not valid_gradients:
break
return not valid_gradients
def fix_gradients(model):
for name, param in model.named_parameters():
if param.grad is not None:
param.grad = torch.nan_to_num(param.grad, nan=0.0)
def train(loader: DataLoader,
model: torch.nn.Module,
ema: ModelEMA,
scheduler: torch.optim.lr_scheduler.LambdaLR,
optimizer: torch.optim.Optimizer,
args: argparse.ArgumentParser,
run_name=""):
model.train()
for i, data in enumerate(tqdm.tqdm(loader, desc=f"Training {run_name}")):
data = data.cuda(non_blocking=True)
data = format_data(data)
optimizer.zero_grad(set_to_none=True)
model_outputs = model(data)
loss_dict = {k: v for k, v in model_outputs.items() if "loss" in k}
loss = loss_dict.pop("total_loss")
loss.backward()
torch.nn.utils.clip_grad_value_(model.parameters(), args.clip)
fix_gradients(model)
optimizer.step()
scheduler.step()
ema.update(model)
training_logs = {f"training/loss/{k}": v for k, v in loss_dict.items()}
wandb.log({"training/loss": loss.item(), "training/lr": scheduler.get_last_lr()[-1], **training_logs})
def run_test(loader: DataLoader,
model: torch.nn.Module,
dry_run_steps: int=-1,
dataset="gen1"):
model.eval()
mapcalc = DetectionBuffer(height=loader.dataset.height, width=loader.dataset.width, classes=loader.dataset.classes)
for i, data in enumerate(tqdm.tqdm(loader)):
data = data.cuda()
data = format_data(data)
detections, targets = model(data)
if i % 10 == 0:
torch.cuda.empty_cache()
mapcalc.update(detections, targets, dataset, data.height[0], data.width[0])
if dry_run_steps > 0 and i == dry_run_steps:
break
torch.cuda.empty_cache()
return mapcalc
if __name__ == '__main__':
import torch_geometric
import random
import numpy as np
seed = 42
torch_geometric.seed.seed_everything(seed)
torch.random.manual_seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
args = FLAGS()
output_directory = set_up_logging_directory(args.dataset, args.task, args.output_directory, exp_name=args.exp_name)
log_hparams(args)
augmentations = Augmentations(args)
print("init datasets")
dataset_path = args.dataset_directory / args.dataset
train_dataset = NCaltech101(dataset_path, "training", augmentations.transform_training, num_events=args.n_nodes)
test_dataset = NCaltech101(dataset_path, "validation", augmentations.transform_testing, num_events=args.n_nodes)
train_loader = DataLoader(train_dataset, follow_batch=['bbox', 'bbox0'], batch_size=args.batch_size, shuffle=True, num_workers=4, drop_last=True)
num_iters_per_epoch = len(train_loader)
sampler = np.random.permutation(np.arange(len(test_dataset)))
test_loader = DataLoader(test_dataset, sampler=sampler, follow_batch=['bbox', 'bbox0'], batch_size=args.batch_size, shuffle=False, num_workers=4, drop_last=True)
print("init net")
# load a dummy sample to get height, width
model = DAGR(args, height=test_dataset.height, width=test_dataset.width)
num_params = sum([np.prod(p.size()) for p in model.parameters()])
print(f"Training with {num_params} number of parameters.")
model = model.cuda()
ema = ModelEMA(model)
nominal_batch_size = 64
lr = args.l_r * np.sqrt(args.batch_size) / np.sqrt(nominal_batch_size)
optimizer = torch.optim.AdamW(list(model.parameters()), lr=lr, weight_decay=args.weight_decay)
lr_func = LRSchedule(warmup_epochs=.3,
num_iters_per_epoch=num_iters_per_epoch,
tot_num_epochs=args.tot_num_epochs)
lr_scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer=optimizer, lr_lambda=lr_func)
checkpointer = Checkpointer(output_directory=output_directory,
model=model, optimizer=optimizer,
scheduler=lr_scheduler, ema=ema,
args=args)
start_epoch = checkpointer.restore_if_existing(output_directory, resume_from_best=False)
start_epoch = 0
if "resume_checkpoint" in args:
start_epoch = checkpointer.restore_checkpoint(args.resume_checkpoint, best=False)
print(f"Resume from checkpoint at epoch {start_epoch}")
with torch.no_grad():
mapcalc = run_test(test_loader, ema.ema, dry_run_steps=2, dataset=args.dataset)
mapcalc.compute()
print("starting to train")
for epoch in range(start_epoch, args.tot_num_epochs):
train(train_loader, model, ema, lr_scheduler, optimizer, args, run_name=wandb.run.name)
checkpointer.checkpoint(epoch, name=f"last_model")
if epoch % 3 > 0:
continue
with torch.no_grad():
mapcalc = run_test(test_loader, ema.ema, dataset=args.dataset)
metrics = mapcalc.compute()
checkpointer.process(metrics, epoch)
================================================
FILE: scripts/visualize_detections.py
================================================
import cv2
import argparse
from pathlib import Path
import numpy as np
from dsec_det.directory import DSECDirectory
from dsec_det.io import extract_from_h5_by_timewindow, extract_image_by_index, load_start_and_end_time
from dsec_det.preprocessing import compute_index
from dagr.visualization.bbox_viz import draw_bbox_on_img
from dagr.visualization.event_viz import draw_events_on_image
if __name__ == '__main__':
parser = argparse.ArgumentParser("""Visualization script to show bounding boxes""")
parser.add_argument("--detections_folder", help="Path to folder with detections.", type=Path)
parser.add_argument("--dataset_directory", help="Path to DSEC folder including which split.", type=Path, default="/data/scratch1/daniel/datasets/DSEC_fragment/test")
parser.add_argument("--vis_time_step_us", help="Number of microseconds to step each iteration.", type=int, default=1000)
parser.add_argument("--event_time_window_us", help="Length of sliding event time window for visualization.", type=int, default=5000)
parser.add_argument("--sequence", help="Sequence to visualize. Must be an official DSEC sequence e.g. zurich_city_13_b", default="zurich_city_13_b", type=str)
parser.add_argument("--write_to_output", help="Whether to save images in folder ${detections_folder}/visualization. Otherwise, just cv2.imshow is used.", action="store_true")
args = parser.parse_args()
assert args.dataset_directory.exists()
assert args.vis_time_step_us > 0
assert args.event_time_window_us > 0
if args.write_to_output:
assert (args.detections_folder / f"detections_{args.sequence}.npy").exists()
assert args.detections_folder.exists()
output_path = args.detections_folder / "visualization"
output_path.mkdir(parents=True, exist_ok=True)
dsec_directory = DSECDirectory(args.dataset_directory / args.sequence)
t0, t1 = load_start_and_end_time(dsec_directory)
vis_timestamps = np.arange(t0, t1, step=args.vis_time_step_us)
step_index_to_image_index = compute_index(dsec_directory.images.timestamps, vis_timestamps)
show_detections = args.detections_folder is not None
if not show_detections:
print("Did not specifiy detections. Just showing events and images.")
if show_detections:
detections_file = args.detections_folder / f"detections_{args.sequence}.npy"
detections = np.load(detections_file)
detection_timestamps = np.unique(detections['t'])
step_index_to_boxes_index = compute_index(detection_timestamps, vis_timestamps)
scale = 2
for step, t in enumerate(vis_timestamps):
# find most recent image
image_index = step_index_to_image_index[step]
image = extract_image_by_index(dsec_directory.images.image_files_distorted, image_index)
# find events within time window [image_timestamps, t]
events = extract_from_h5_by_timewindow(dsec_directory.events.event_file, t-args.event_time_window_us, t)
image = draw_events_on_image(image, events['x'], events['y'], events['p'])
if show_detections:
# find most recent bounding boxes
boxes_index = step_index_to_boxes_index[step]
boxes_timestamp = detection_timestamps[boxes_index]
boxes = detections[detections['t'] == boxes_timestamp]
# draw them on one image
scale = 2
image = draw_bbox_on_img(image, scale*boxes['x'], scale*boxes['y'], scale*boxes['w'], scale*boxes["h"],
boxes["class_id"], boxes['class_confidence'], conf=0.3, nms=0.65)
if args.write_to_output:
cv2.imwrite(str(output_path / ("%06d.png" % step)), image)
else:
cv2.imshow("DSEC Det: Visualization", image)
cv2.waitKey(3)
================================================
FILE: setup.py
================================================
from distutils.core import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
setup(
name='dagr',
packages=['dagr'],
package_dir={'':'src'},
ext_modules=[
CUDAExtension(name='asy_tools',
sources=['src/dagr/asynchronous/asy_tools/main.cu']),
CUDAExtension(name="ev_graph_cuda",
sources=['src/dagr/graph/ev_graph.cu'])
],
cmdclass={
'build_ext': BuildExtension
}
)
================================================
FILE: src/dagr/asynchronous/__init__.py
================================================
import logging
import torch.nn
import torch_geometric
import inspect
from torch.nn import ModuleList
from .conv import make_conv_asynchronous
from .batch_norm import make_batch_norm_asynchronous
from .linear import make_linear_asynchronous
from .max_pool import make_max_pool_asynchronous
from .cartesian import make_cartesian_asynchronous
from .flops import compute_flops_from_module
from dagr.model.layers.spline_conv import MySplineConv
from dagr.model.layers.pooling import Pooling
from dagr.model.layers.components import BatchNormData, Cartesian, Linear
from torch_geometric.data import Data, Batch
from typing import List
def is_data_or_data_list(ann):
return ann is Data or ann is Batch or ann is List[Data]
def make_model_synchronous(module: torch.nn.Module):
module.forward = module.sync_forward
module.asy_flops_log = []
for key, nn in module.named_modules():
if hasattr(nn, "sync_forward"):
nn.forward = nn.sync_forward
nn.asy_flops_log = []
return module
def make_model_asynchronous(module, log_flops: bool = False):
"""Module converter from synchronous to asynchronous & sparse processing for graph convolutional layers.
By overwriting parts of the module asynchronous processing can be enabled without the need of re-learning
and moving its weights and configuration. So, a convolutional layer can be converted by, for example:
```
module = GCNConv(1, 2)
module = make_conv_asynchronous(module)
```
:param module: convolutional module to transform.
:param grid_size: grid size (grid starting at 0, spanning to `grid_size`), >= `size` for pooling operations,
e.g. the image size.
:param r: update radius around new events.
:param edge_attributes: function for computing edge attributes (default = None), assumed to be the same over
all convolutional layers.
:param log_flops: log flops of asynchronous update.
"""
assert isinstance(module, torch.nn.Module), "module must be a `torch.nn.Module`"
model_forward = module.forward
module.sync_forward = module.forward
module.asy_flops_log = [] if log_flops else None
# Make all layers asynchronous that have an implemented asynchronous function. Otherwise use
# the synchronous forward function.
for key, nn in module._modules.items():
nn_class_name = nn.__class__.__name__
logging.debug(f"Making layer {key} of type {nn_class_name} asynchronous")
if isinstance(nn, MySplineConv):
module._modules[key] = make_conv_asynchronous(nn, log_flops=log_flops)
elif isinstance(nn, Pooling):
module._modules[key] = make_max_pool_asynchronous(nn, log_flops=log_flops)
elif isinstance(nn, BatchNormData):
module._modules[key] = make_batch_norm_asynchronous(nn, log_flops=log_flops)
elif isinstance(nn, Cartesian):
module._modules[key] = make_cartesian_asynchronous(nn, log_flops=log_flops)
elif isinstance(nn, Linear):
module._modules[key] = make_linear_asynchronous(nn, log_flops=log_flops)
elif isinstance(nn, ModuleList):
module._modules[key] = make_model_asynchronous(nn, log_flops=log_flops)
else:
sign = inspect.signature(nn.forward)
first_arg = list(sign.parameters.values())[0]
if not is_data_or_data_list(first_arg.annotation):
continue
module._modules[key] = make_model_asynchronous(nn, log_flops=log_flops)
logging.debug(f"Asynchronous module for {nn_class_name} is being made asynchronous recursively.")
def async_forward(data: torch_geometric.data.Data, *args, **kwargs):
out = model_forward(data, *args, **kwargs)
if module.asy_flops_log is not None:
flops_count = [compute_flops_from_module(layer) for layer in module._modules.values()]
module.asy_flops_log.append(sum(flops_count))
logging.debug(f"Model's modules update with overall {sum(flops_count)} flops")
return out
module.forward = async_forward
return module
__all__ = [
"make_conv_asynchronous",
"make_linear_asynchronous",
"make_max_pool_asynchronous",
"make_model_asynchronous"
]
================================================
FILE: src/dagr/asynchronous/asy_tools/main.cu
================================================
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <vector>
#define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor")
#define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous")
#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)
#define CHECK_DEVICE(x, y) AT_ASSERTM(x.device().index() == y.device().index(), #x " and " #y " must be in same CUDA device")
template <typename scalar_t>
__global__ void masked_isdiff_kernel(
int64_t* __restrict__ indices,
const scalar_t* __restrict__ x_old,
const scalar_t* __restrict__ x_new,
int K, int C, float atol, float rtol
)
{
// linear index
const int lin_idx = blockIdx.x * blockDim.x + threadIdx.x;
// check that thread is not out of valid range
if (lin_idx >= K)
return;
// find out how many events to write, and what is the offset
int64_t temp = indices[lin_idx];
indices[lin_idx] = -1;
int offset = temp*C;
for (int i=0; i<C; i++) {
float input = x_old[offset + i];
float other = x_new[offset + i];
if (std::abs(input - other) > atol + rtol * other) {
indices[lin_idx] = temp;
break;
}
}
}
template <typename scalar_t>
__global__ void masked_inplace_BN_kernel(
const int64_t* __restrict__ indices,
const scalar_t* __restrict__ x,
scalar_t* __restrict__ x_out,
const scalar_t* __restrict__ running_mean,
const scalar_t* __restrict__ running_var,
const scalar_t* __restrict__ weight,
const scalar_t* __restrict__ bias,
int K, int C, float eps
)
{
// linear index
const int lin_idx = blockIdx.x * blockDim.x + threadIdx.x;
// check that thread is not out of valid range
if (lin_idx >= K*C)
return;
int i = lin_idx / C;
int c = lin_idx % C;
int x_lin_idx = C * indices[i] + c;
x_out[x_lin_idx] = (x[x_lin_idx] - running_mean[c]) / (sqrt(running_var[c] + eps)) * weight[c] + bias[c];
}
void masked_inplace_BN(
const torch::Tensor& indices,
const torch::Tensor& x,
torch::Tensor& x_out,
const torch::Tensor& running_mean,
const torch::Tensor& running_var,
const torch::Tensor& weight,
const torch::Tensor& bias,
float eps
)
{
unsigned K = indices.size(0);
unsigned C = x.size(1);
unsigned threads = 256;
dim3 blocks((K*C + threads - 1) / threads, 1);
masked_inplace_BN_kernel<float><<<blocks, threads>>>(
indices.data<int64_t>(),
x.data<float>(),
x_out.data<float>(),
running_mean.data<float>(),
running_var.data<float>(),
weight.data<float>(),
bias.data<float>(), K, C, eps
);
}
torch::Tensor masked_isdiff(
const torch::Tensor& indices, // N -> num events
const torch::Tensor& x_old, // K -> num active pixels
const torch::Tensor& x_new, // K -> num active pixels
float atol, float rtol
)
{
CHECK_INPUT(indices);
CHECK_INPUT(x_old);
CHECK_INPUT(x_new);
CHECK_DEVICE(indices, x_old);
CHECK_DEVICE(indices, x_new);
unsigned K = indices.size(0);
unsigned C = x_old.size(1);
unsigned threads = 256;
dim3 blocks((K + threads - 1) / threads, 1);
masked_isdiff_kernel<float><<<blocks, threads>>>(
indices.data<int64_t>(),
x_old.data<float>(),
x_new.data<float>(),
K, C, atol, rtol
);
return indices.index({indices > -1});
}
template <typename scalar_t>
__global__ void masked_lin_kernel(
int64_t* __restrict__ indices,
const scalar_t* __restrict__ x_in,
scalar_t* __restrict__ x_out,
const scalar_t* __restrict__ weight,
const scalar_t* __restrict__ bias,
int K, int Cin, int Cout, bool add
)
{
// linear index
const int lin_idx = blockIdx.x * blockDim.x + threadIdx.x;
// check that thread is not out of valid range
if (lin_idx >= K*Cout)
return;
int i = lin_idx / Cout;
int cout = lin_idx % Cout;
int x_out_lin_idx = Cout * indices[i] + cout;
int x_int_lin_idx = Cin * indices[i];
if (!add)
x_out[x_out_lin_idx] = 0;
for (int cin=0; cin<Cin; cin++) {
x_out[x_out_lin_idx] += x_in[x_int_lin_idx + cin] * weight[cout*Cin + cin];
}
x_out[x_out_lin_idx] += bias[cout];
}
template <typename scalar_t>
__global__ void masked_lin_no_bias_kernel(
int64_t* __restrict__ indices,
const scalar_t* __restrict__ x_in,
scalar_t* __restrict__ x_out,
const scalar_t* __restrict__ weight,
int K, int Cin, int Cout, bool add
)
{
// linear index
const int lin_idx = blockIdx.x * blockDim.x + threadIdx.x;
// check that thread is not out of valid range
if (lin_idx >= K*Cout)
return;
int i = lin_idx / Cout;
int cout = lin_idx % Cout;
int x_out_lin_idx = Cout * indices[i] + cout;
int x_int_lin_idx = Cin * indices[i];
if (!add)
x_out[x_out_lin_idx] = 0;
for (int cin=0; cin<Cin; cin++) {
x_out[x_out_lin_idx] += x_in[x_int_lin_idx + cin] * weight[cout*Cin + cin];
}
}
void masked_lin_no_bias(
const torch::Tensor& indices,
const torch::Tensor& x_in,
torch::Tensor& x_out,
const torch::Tensor& weight,
bool add
)
{
unsigned K = indices.size(0);
unsigned Cin = weight.size(1);
unsigned Cout = weight.size(0);
unsigned threads = 256;
dim3 blocks((K*Cout + threads - 1) / threads, 1);
masked_lin_no_bias_kernel<float><<<blocks, threads>>>(
indices.data<int64_t>(),
x_in.data<float>(),
x_out.data<float>(),
weight.data<float>(),
K, Cin, Cout, add);
}
void masked_lin(
const torch::Tensor& indices,
const torch::Tensor& x_in,
torch::Tensor& x_out,
const torch::Tensor& weight,
const torch::Tensor& bias,
bool add
)
{
unsigned K = indices.size(0);
unsigned Cin = weight.size(1);
unsigned Cout = weight.size(0);
unsigned threads = 256;
dim3 blocks((K*Cout + threads - 1) / threads, 1);
masked_lin_kernel<float><<<blocks, threads>>>(
indices.data<int64_t>(),
x_in.data<float>(),
x_out.data<float>(),
weight.data<float>(),
bias.data<float>(), K, Cin, Cout, add);
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("masked_lin", &masked_lin, "Find edges from a queue of events.");
m.def("masked_lin_no_bias", &masked_lin_no_bias, "Find edges from a queue of events.");
m.def("masked_isdiff", &masked_isdiff, "Find edges from a queue of events.");
m.def("masked_inplace_BN", &masked_inplace_BN, "Find edges from a queue of events.");
}
================================================
FILE: src/dagr/asynchronous/base/__init__.py
================================================
================================================
FILE: src/dagr/asynchronous/base/base.py
================================================
from contextlib import contextmanager
import logging
def add_async_graph(module, log_flops: bool = False):
module.asy_graph = None
module.asy_flops_log = [] if log_flops else None
return module
def make_asynchronous(module, initialization_func, processing_func):
module.sync_forward = module.forward
def async_forward(*args, **kwargs):
with async_context(module, initialization_func, processing_func) as func:
output = func(module, *args, **kwargs)
return output
module.forward = async_forward
return module
@contextmanager
def async_context(module, initialization_func, processing_func):
if module.asy_graph is None:
logging.debug(f"Graph initialization of module {module}")
yield initialization_func
else:
logging.debug(f"Calling processing of module {module}")
yield processing_func
================================================
FILE: src/dagr/asynchronous/base/utils.py
================================================
import torch
from typing import Tuple
import asy_tools
def _efficient_cat(data_list):
data_list = [d for d in data_list if len(d) > 0]
if len(data_list) == 1:
return data_list[0]
return torch.cat(data_list)
def _efficient_cat_unique(data_list):
# first only keep elements that have len > 0
data_list_filt = [data for data in data_list if data.shape[0] > 0]
if len(data_list_filt) == 1:
return data_list_filt[0]
elif len(data_list_filt) == 0:
return data_list[0]
else:
return torch.cat(data_list_filt).unique()
def _to_hom(x, ones=None):
if ones is None or len(ones) < len(x):
ones = torch.ones_like(x[:,-1:])
else:
ones = ones[:len(x)]
return torch.cat([x, ones], dim=-1)
def _from_hom(x):
return x[:,:-1] / (x[:,-1:] + 1e-9)
def graph_new_nodes(old_data, new_data):
return torch.arange(old_data.x.shape[0], new_data.x.shape[0], device=new_data.x.device, dtype=torch.long)
def graph_changed_nodes(old_data, new_data) -> Tuple[torch.Tensor, torch.Tensor]:
len_x_old = old_data.x.shape[0]
len_pos_old = old_data.pos.shape[0]
x_new = new_data.x[:len_x_old] if len_x_old < new_data.x.shape[0] else new_data.x
pos_new = new_data.pos[:len_pos_old] if len_pos_old < new_data.pos.shape[0] else new_data.pos
diff_idx = asy_tools.masked_isdiff(new_data.diff_idx, x_new, old_data.x, 1e-8, 1e-5) if new_data.diff_idx.numel() > 0 else new_data.diff_idx
diff_pos_idx = asy_tools.masked_isdiff(new_data.diff_pos_idx, pos_new, old_data.pos, 1e-8, 1e-5) if new_data.diff_pos_idx.numel() > 0 else new_data.diff_pos_idx
return diff_idx, diff_pos_idx
def torch_isin(query, database):
if hasattr(torch, "isin"):
return torch.isin(query, database)
else:
return (query.view(1, -1) == database.view(-1, 1)).any(0)
def __remove_duplicate_from_A(a, b):
a_in_b = (a.view(2,1,-1) == b.view(2,-1,1)).all(0).any(0)
return a[:,~a_in_b]
================================================
FILE: src/dagr/asynchronous/batch_norm.py
================================================
import torch
import asy_tools
from torch_geometric.nn.norm import BatchNorm
import torch.nn.functional as F
from .base.base import make_asynchronous, add_async_graph
from .base.utils import graph_changed_nodes, graph_new_nodes
def __sync_forward(m, x):
return F.batch_norm(x, m.running_mean, m.running_var, m.weight, m.bias, False, m.momentum, m.eps)
def __graph_initialization(module: BatchNorm, data) -> torch.Tensor:
module.asy_graph = data.clone()
module.graph_out = data.clone()
module.graph_out.x = __sync_forward(module.module, data.x)
# flops are not counted since BN can be fused with previous conv operator.
if module.asy_flops_log is not None:
flops = 0
module.asy_flops_log.append(flops)
return module.graph_out.clone()
def __graph_processing(module: BatchNorm, data) -> torch.Tensor:
"""Batch norms only execute simple normalization operation, which already is very efficient. The overhead
for looking for diff nodes would be much larger than computing the dense update.
However, a new node slightly changes the feature distribution and therefore all activations, when calling
the dense implementation. Therefore, we approximate the distribution with the initial distribution as
num_new_events << num_initial_events.
"""
if len(module.asy_graph.x) < len(data.x):
diff_idx = graph_new_nodes(module.asy_graph, data)
module.graph_out.x = torch.cat([module.graph_out.x, torch.zeros_like(data.x[:len(diff_idx)])])
else:
diff_idx, _ = graph_changed_nodes(module.asy_graph, data)
if data.diff_idx.numel()>0:
asy_tools.masked_inplace_BN(data.diff_idx, data.x,
module.graph_out.x,
module.module.running_mean,
module.module.running_var,
module.module.weight,
module.module.bias,
module.module.eps)
# If required, compute the flops of the asynchronous update operation.
if module.asy_flops_log is not None:
flops = 0
module.asy_flops_log.append(flops)
data.x = module.graph_out.x
return data
def __check_support(module):
return True
def make_batch_norm_asynchronous(module: BatchNorm, log_flops: bool = False):
"""Module converter from synchronous to asynchronous & sparse processing for batch norm (1d) layers.
By overwriting parts of the module asynchronous processing can be enabled without the need of re-learning
and moving its weights and configuration. So, a layer can be converted by, for example:
```
module = BatchNorm(4)
module = make_batch_norm_asynchronous(module)
```
:param module: batch norm module to transform.
:param log_flops: log flops of asynchronous update.
"""
assert __check_support(module)
module = add_async_graph(module, log_flops=log_flops)
return make_asynchronous(module, __graph_initialization, __graph_processing)
================================================
FILE: src/dagr/asynchronous/cartesian.py
================================================
import torch
from torch_geometric.nn.norm import BatchNorm
from .base.base import make_asynchronous, add_async_graph
def __edge_attr(pos, edge_index, norm, max):
(row, col), pos = edge_index, pos
cart = pos[row] - pos[col]
cart = cart.view(-1, 1) if cart.dim() == 1 else cart
if norm and cart.numel() > 0:
max_value = cart.abs().max() if max is None else max
cart = cart / (2 * max_value) + 0.5
return cart
def __graph_initialization(module: BatchNorm, data) -> torch.Tensor:
module.asy_graph = data.clone()
module.graph_out = data.clone()
module.graph_out.edge_attr = __edge_attr(data.pos, data.edge_index, module.norm, module.max)
# flops are not counted since BN can be fused with previous conv operator.
if module.asy_flops_log is not None:
flops = 2 * len(module.graph_out.edge_attr)
module.asy_flops_log.append(flops)
return module.graph_out.clone()
def __graph_processing(module: BatchNorm, data) -> torch.Tensor:
"""Batch norms only execute simple normalization operation, which already is very efficient. The overhead
for looking for diff nodes would be much larger than computing the dense update.
However, a new node slightly changes the feature distribution and therefore all activations, when calling
the dense implementation. Therefore, we approximate the distribution with the initial distribution as
num_new_events << num_initial_events.
"""
module.graph_out.pos = torch.cat([module.asy_graph.pos, data.pos])
module.graph_out.x = torch.cat([module.asy_graph.x, data.x])
module.graph_out.edge_attr = __edge_attr(module.graph_out.pos, data.edge_index, module.norm, module.max)
module.graph_out.edge_index = data.edge_index
# flops are not counted since BN can be fused with previous conv operator.
if module.asy_flops_log is not None:
flops = 2 * len(module.graph_out.edge_attr)
module.asy_flops_log.append(flops)
if hasattr(data, "diff_idx"):
module.graph_out.diff_idx = data.diff_idx
module.graph_out.diff_pos_idx = data.diff_pos_idx
return module.graph_out
def __check_support(module):
return True
def make_cartesian_asynchronous(module: BatchNorm, log_flops: bool = False):
"""Module converter from synchronous to asynchronous & sparse processing for cartesian layers.
By overwriting parts of the module asynchronous processing can be enabled without the need of re-learning
and moving its weights and configuration. So, a layer can be converted by, for example:
```
module = Cartesian()
module = make_cartesian_asynchronous(module)
```
:param module: cartesian module to transform.
:param log_flops: log flops of asynchronous update.
"""
assert __check_support(module)
module = add_async_graph(module, log_flops=log_flops)
return make_asynchronous(module, __graph_initialization, __graph_processing)
================================================
FILE: src/dagr/asynchronous/conv.py
================================================
import asy_tools
import torch
import torch_geometric.nn.conv
from .base.base import make_asynchronous, add_async_graph
from .base.utils import graph_new_nodes, graph_changed_nodes, _efficient_cat_unique, torch_isin
from .flops import compute_flops_conv, compute_flops_cat
from torch_scatter import scatter_sum
def __conv(x, edge_index, edge_attr, mask, nn):
if edge_index.numel() > 0:
x_j = x[edge_index[0, :], :]
phi = nn.message(x_j, edge_attr=edge_attr[:, :nn.dim])
y = nn.aggregate(phi, index=edge_index[1, :], ptr=None, dim_size=x.size()[0])
else:
y = torch.zeros(size=(x.shape[0], nn.out_channels), dtype=x.dtype, device=x.device)
if hasattr(nn, "root_weight") and nn.root_weight:
nn.lin_act = nn.lin(x)
y[mask] += nn.lin_act[mask]
if hasattr(nn, "bias") and nn.bias is not None:
y[mask] += nn.bias
return y
def __graph_initialization(module, data, *args, **kwargs):
module.asy_graph = data.clone()
module.graph_out = data.clone()
# Concat old and updated feature for output feature vector.
if hasattr(module.asy_graph, "active_clusters"):
mask = module.asy_graph.active_clusters
num_updated_elements = len(mask)
else:
mask = slice(None)
num_updated_elements = len(data.x)
module.graph_out.x = __conv(data.x, data.edge_index, data.edge_attr, mask, module)
# If required, compute the flops of the asynchronous update operation. Therefore, sum the flops for each node
# update, as they highly depend on the number of neighbors of this node.
if module.asy_flops_log is not None:
flops = compute_flops_conv(module, num_times_apply_bias_and_root=num_updated_elements, num_edges=data.edge_index.shape[1])
module.asy_flops_log.append(flops)
if hasattr(module, "to_dense"):
mask = module.graph_out.active_clusters
batch = module.graph_out.batch if module.graph_out.batch is None else module.graph_out.batch[mask]
if batch is None:
batch = torch.zeros(len(module.graph_out.pos[mask]), dtype=torch.long, device=data.x.device)
return module.to_dense(module.graph_out.x[mask],
module.graph_out.pos[mask],
module.graph_out.pooling,
batch)
return module.graph_out.clone()
def __edges_with_src_node(node_idx, edge_index, edge_attr=None, node_idx_type="src", return_changed_edges=False, return_mask=False):
if node_idx.numel() == 0:
outputs = [torch.empty(size=(2,0), dtype=torch.long, device=node_idx.device)]
if edge_attr is not None:
outputs.append(torch.empty(size=(0,3), dtype=edge_attr.dtype, device=edge_attr.device))
if return_mask:
outputs.append(torch.empty(size=(0,), dtype=torch.bool, device=node_idx.device))
if len(outputs) == 1:
outputs = outputs[0]
return outputs
if node_idx_type == "src":
mask = torch_isin(edge_index[0], node_idx)
elif node_idx_type == "dst":
mask = torch_isin(edge_index[1], node_idx)
elif node_idx_type == "both":
mask = torch_isin(edge_index[0], node_idx) | torch_isin(edge_index[1], node_idx)
else:
raise ValueError
output = [edge_index[:,mask]]
if edge_attr is not None:
output.append(edge_attr[mask])
if return_changed_edges:
output.append(mask.nonzero().ravel())
if return_mask:
output.append(mask.nonzero().ravel())
if len(output) == 1:
output = output[0]
return output
def find_only_x(idx_new_comp, idx_diff, pos_idx_diff, edge):
return idx_new_comp[torch_isin(idx_new_comp, idx_diff) & ~torch_isin(idx_new_comp, pos_idx_diff) & ~torch_isin(idx_new_comp, edge)]
def __graph_processing(module, data, *args, **kwargs):
"""Asynchronous graph update for graph convolutional layer.
After the initialization of the graph, only the nodes (and their receptive field) have to updated which either
have changed (different features) or have been added. Therefore, for updating the graph we have to first
compute the set of "diff" and "new" nodes to then do the convolutional message passing on this subgraph,
and add the resulting residuals to the graph.
:param x: graph nodes features.
"""
num_edges_image_feat = 0
num_edges = 0
num_times_apply_bias_and_root = 0
new_nodes = len(data.x) > len(module.asy_graph.x)
# first update the input graph
if new_nodes:
idx_new = graph_new_nodes(module.asy_graph, data)
module.asy_graph.x = torch.cat([module.asy_graph.x, data.x[idx_new]])
idx_new_comp = idx_new
# when new edges are added through added events, make sure to add them, otherwise only update the edge attributes
module.asy_graph.edge_index = torch.cat([module.asy_graph.edge_index, data.edge_index], dim=-1)
module.asy_graph.edge_attr = torch.cat([module.asy_graph.edge_attr, data.edge_attr], dim=0)
zero_row = torch.zeros(len(idx_new), module.out_channels, device=data.x.device)
module.graph_out.x = torch.cat([module.graph_out.x, zero_row])
data.diff_idx = idx_new_comp
pos_idx_diff = torch.zeros(size=(0,), dtype=torch.long, device=data.x.device)
if idx_new_comp.numel() > 0:
edge_index_new, edge_attr_new = data.edge_index, data.edge_attr
num_edges += edge_index_new.shape[1]
else:
idx_diff, pos_idx_diff = graph_changed_nodes(module.asy_graph, data)
idx_new_comp = _efficient_cat_unique([pos_idx_diff, idx_diff, data.edge_index[1].unique()])
data.diff_idx = idx_new_comp
if idx_new_comp.numel() > 0:
# find out dests of idx new, idx diff and pos_idx_diff
edge_index_update_message, mask = __edges_with_src_node(idx_new_comp, module.asy_graph.edge_index, return_mask=True)
edge_attr_update_message = module.asy_graph.edge_attr[mask]
num_edges += edge_index_update_message.shape[1]
if hasattr(module.asy_graph, "active_clusters") and hasattr(data, "_changed_attr"):
module.asy_graph.edge_attr[data._changed_attr_indices] = data._changed_attr
edge_attr_update_message_new = module.asy_graph.edge_attr[mask]
else:
edge_attr_update_message_new = edge_attr_update_message
# when new edges are added through added events, make sure to add them, otherwise only update the edge attributes
if data.edge_index.numel() > 0:
module.asy_graph.edge_index = torch.cat([module.asy_graph.edge_index, data.edge_index], dim=-1)
module.asy_graph.edge_attr = torch.cat([module.asy_graph.edge_attr, data.edge_attr], dim=0)
if idx_new_comp.numel() > 0 and edge_index_update_message.numel() > 0:
# first compute update to y
x_old = module.asy_graph.x[edge_index_update_message[0], :]
phi_old = module.message(x_old, edge_attr=edge_attr_update_message)
# new messages
x_new = data.x[edge_index_update_message[0], :]
phi_new = module.message(x_new, edge_attr=edge_attr_update_message_new)
scatter_sum(phi_new-phi_old, index=edge_index_update_message[1],out=module.graph_out.x, dim=0, dim_size=len(module.graph_out.x))
data.diff_idx = _efficient_cat_unique([data.diff_idx, edge_index_update_message[1]])
num_edges += edge_index_update_message.shape[1]
only_x = find_only_x(idx_new_comp, idx_diff, pos_idx_diff, data.edge_index[1])
if only_x is not None and len(only_x) > 0:
idx_new_comp = idx_new_comp[~torch_isin(idx_new_comp, only_x)]
generalized_lin(module, data.x - module.asy_graph.x, module.graph_out.x, only_x)
num_times_apply_bias_and_root += len(only_x)
if idx_new_comp.numel() > 0:
# edge and attrs for newly computed
edge_index_new, edge_attr_new = __edges_with_src_node(idx_new_comp, edge_index=module.asy_graph.edge_index,
edge_attr=module.asy_graph.edge_attr,
node_idx_type="dst")
edge_index_pos, _ = __edges_with_src_node(pos_idx_diff, edge_index=module.asy_graph.edge_index,
edge_attr=module.asy_graph.edge_attr,
node_idx_type="dst")
num_edges_image_feat = edge_index_pos.shape[1]
num_edges += edge_index_new.shape[1]
module.graph_out.x[idx_new_comp] = 0
if idx_new_comp.numel() > 0:
if edge_index_new.shape[1] > 0:
num_edges += edge_index_new.shape[1]
# next compute all messages for computing new index
x_j = data.x[edge_index_new[0, :], :]
phi = module.message(x_j, edge_attr=edge_attr_new[:,:module.dim])
scatter_sum(phi, out=module.graph_out.x, index=edge_index_new[1], dim=0, dim_size=len(module.graph_out.x))
num_times_apply_bias_and_root += len(idx_new_comp)
generalized_lin(module, data.x, module.graph_out.x, idx_new_comp)
data.x = module.graph_out.x
data.diff_pos_idx = pos_idx_diff
# If required, compute the flops of the asynchronous update operation. Therefore, sum the flops for each node
# update, as they highly depend on the number of neighbors of this node.
if module.asy_flops_log is not None:
cat = hasattr(data, "skipped") and data.skipped
data.skipped = False
flops = compute_flops_conv(module, num_times_apply_bias_and_root=len(idx_new_comp), num_edges=num_edges,
concatenation=cat, num_image_channels=getattr(data, "num_image_channels", -1))
if cat:
flops += compute_flops_cat(module, num_edges=num_edges_image_feat,
num_times_apply_bias_and_root=num_times_apply_bias_and_root, num_image_channels=getattr(data, "num_image_channels", -1))
module.asy_flops_log.append(flops)
if hasattr(module, "to_dense"):
if pos_idx_diff.numel() > 0 or idx_new_comp.numel() > 0:
mask = data.active_clusters
batch = data.batch if data.batch is None else data.batch[mask]
if batch is None:
batch = torch.zeros(len(module.graph_out.pos[mask]), dtype=torch.long, device=data.x.device)
return module.to_dense(data.x[mask],
data.pos[mask],
data.pooling,
batch)
else:
return module.dense[:1]
return data
def generalized_lin(module, input, output, idx):
uses_bias = hasattr(module, "bias") and module.bias is not None
uses_weight = hasattr(module, "root_weight") and module.root_weight
if not uses_weight:
return
if uses_bias:
asy_tools.masked_lin(idx, input, output, module.lin.weight.data, module.bias.data, True)
else:
asy_tools.masked_lin_no_bias(idx, input, output, module.lin.weight.data, True)
def __check_support(module) -> bool:
if isinstance(module, torch_geometric.nn.conv.GCNConv):
if module.normalize is True:
raise NotImplementedError("GCNConvs with normalization are not yet supported!")
return True
def make_conv_asynchronous(module, log_flops: bool = False):
"""Module converter from synchronous to asynchronous & sparse processing for graph convolutional layers.
By overwriting parts of the module asynchronous processing can be enabled without the need of re-learning
and moving its weights and configuration. So, a convolutional layer can be converted by, for example:
```
module = GCNConv(1, 2)
module = make_conv_asynchronous(module)
```
:param module: convolutional module to transform.
:param r: update radius around new events.
:param edge_attributes: function for computing edge attributes (default = None).
:param is_initial: layer initial layer of sequential or deeper (default = False).
:param log_flops: log flops of asynchronous update.
"""
assert __check_support(module)
module = add_async_graph(module, log_flops=log_flops)
return make_asynchronous(module, __graph_initialization, __graph_processing)
================================================
FILE: src/dagr/asynchronous/evaluate_flops.py
================================================
import torch
from torch_geometric.data import Batch, Data
from typing import List, Tuple
from collections import OrderedDict
from . import make_model_asynchronous, make_model_synchronous
def split_data(data: Data, index: int)->Tuple[Data, Data]:
kwargs = dict(time_window=data.time_window, width=data.width, height=data.height)
if hasattr(data, "image"):
kwargs['image'] = data.image
data1 = Data(pos=data.pos[:index], x=data.x[:index], **kwargs)
data2 = Data(pos=data.pos[index:], x=data.x[index:], **kwargs)
if hasattr(data, "pos_denorm"):
data1.pos_denorm = data.pos_denorm[:index]
data2.pos_denorm = data.pos_denorm[index:]
return data1, data2
def forward_hook(inst, inp, out):
inp = inp[0]
if type(inp) is list:
inp = inp[0].clone()
elif type(inp) is tuple or type(inp) is dict:
return
else:
inp = inp.clone()
if type(out) is list:
out = out[0].clone()
elif type(out) is tuple or type(out) is dict:
return
else:
out = out.clone()
if not hasattr(inst, "activations"):
inst.activations = []
if type(inp) is torch.Tensor:
inp = inp if len(inp.shape) == 2 else inp[0]
inp = Data(x=inp)
if type(out) is torch.Tensor:
out = out if len(out.shape) == 2 else out[0]
out = Data(x=out)
if hasattr(inp, "active_clusters") and not hasattr(out, "active_clusters"):
out.active_clusters = inp.active_clusters
elif hasattr(out, "active_clusters") and not hasattr(inp, "active_clusters"):
inp.active_clusters = out.active_clusters
inp = _mask_if_possible(inp)
out = _mask_if_possible(out)
inst.activations.append((inp, out))
def _mask_if_possible(data):
mask = slice(None, None, None)
if hasattr(data,"active_clusters") and len(data.x) > data.active_clusters.max():
mask = data.active_clusters
masked = Data()
if hasattr(data, "x"):
masked.x = data.x[mask]
if hasattr(data, "pos") and data.pos is not None:
masked.pos = data.pos[mask]
if hasattr(data, "edge_index"):
masked.edge_index = data.edge_index
masked.edge_attr = data.edge_attr
return masked
def denorm(data):
denorm = torch.tensor([int(data.width), int(data.height), int(data.time_window)], device=data.pos.device)
data.pos_denorm = (denorm.view(1,-1) * data.pos + 1e-3).int()
data.batch = data.batch.int()
return data
def evaluate_flops(model: torch.nn.Module, batch: Data, dense=False,
check_consistency=False,
return_all_samples=False) -> OrderedDict:
flops_per_layer_batch = []
# for loop over batch
for i, data in enumerate(batch.to_data_list()):
events_initial, events_new = split_data(data, -1)
events_initial = Batch.from_data_list([events_initial])
events_new = Batch.from_data_list([events_new])
data = Batch.from_data_list([data])
# prepare data for fast inference
data = denorm(data)
events_new = denorm(events_new)
events_initial = denorm(events_initial)
# make a deep copy asynchronous version
handles = []
if check_consistency:
for m in model.modules():
handle = m.register_forward_hook(forward_hook)
handles.append(handle)
with torch.no_grad():
model.forward(data, reset=True, return_targets=False)
model = make_model_asynchronous(model, log_flops=True)
try:
with torch.no_grad():
model.forward(events_initial, reset=True, return_targets=False)
model.forward(events_new, reset=False, return_targets=False)
except Exception as e:
print(f"Crashed at index {i} with message {e}")
raise e
index = 0 if dense else 1
flops_per_layer = OrderedDict(
[
(name, module.asy_flops_log[index]) for name, module in model.named_modules() \
if hasattr(module, "asy_flops_log") and module.asy_flops_log is not None and len(
module.asy_flops_log) > 0
]
)
flops_per_layer = _filter_non_leaf_nodes(flops_per_layer)
flops_per_layer = _merge_to_level_flops(flops_per_layer, level=3)
if not check_consistency:
flops_per_layer_batch.append(flops_per_layer)
model = make_model_synchronous(model)
if check_consistency:
# tests if outputs from 0th and 2nd run are equal
max_mistake_x_layer, max_mistake_pos_layer, global_summary = test_and_compare_activations(model, runs=[0,2])
if max_mistake_x_layer[0] > 1e-3 or max_mistake_pos_layer[1] > 1e-3:
print(global_summary)
print(f"AssertionError(Failed at index {i}.)")
else:
flops_per_layer_batch.append(flops_per_layer)
print(global_summary)
for handle in handles:
handle.remove()
for m in model.modules():
if hasattr(m, "activations"):
del m.activations
if len(flops_per_layer_batch) == 0:
return None
# global average
flops_per_layer = _merge_list_flops(flops_per_layer_batch)
output = {"flops_per_layer": flops_per_layer, "total_flops": sum(flops_per_layer.values())}
if return_all_samples:
output['flops_per_layer_batch'] = flops_per_layer_batch
return output
def _filter_non_leaf_nodes(flops_per_layer: OrderedDict)->OrderedDict:
filter_keys = []
for q_name in flops_per_layer:
for name in flops_per_layer:
if q_name in name and q_name != name:
filter_keys.append(q_name)
break
for f in filter_keys:
flops_per_layer.pop(f)
return flops_per_layer
def _merge_to_level_flops(flops_per_layer: OrderedDict, level=2)->OrderedDict:
known_flops = []
known_keys = []
for name, flops in flops_per_layer.items():
layers = name.split(".")
layers_up_to_level = ".".join(layers[:level])
if layers_up_to_level not in known_keys:
known_keys.append(layers_up_to_level)
known_flops.append(0)
index = known_keys.index(layers_up_to_level)
known_flops[index] += flops
return OrderedDict(zip(known_keys, known_flops))
def _merge_list_flops(flops_per_layer_batch: List[OrderedDict])->OrderedDict:
return OrderedDict([(key, sum([f[key] for f in flops_per_layer_batch]) / len(flops_per_layer_batch)) for key in flops_per_layer_batch[0]])
def _summary(est, gt, prefix):
if len(est) != len(gt):
return "\tCannot compare since x do not have same length\n", None
max_diff, max_rel_diff, ind, max_ind = max_abs_diff(gt, est, threshold=1e-6)
summary = f"\t{prefix} MAX DIFF: {max_diff} MAX REL DIFF: {max_rel_diff}\n"
if ind.numel() > 0:
summary += f"\t{prefix} IND: {max_ind.cpu().numpy().ravel().tolist()}\n"
return summary, max_diff
def max_rel_diff(x, y, threshold=None):
return error_above_threshold((x-y).abs() / (x.abs()+1e-6), threshold)
def error_above_threshold(error, mag, threshold):
if threshold is None:
return error.max()
else:
error_ravel = error.ravel()
arg = error_ravel.argmax()
return error_ravel[arg], error_ravel[arg] / mag.ravel()[arg], (error > threshold).nonzero()[:,0].unique(), error.max(-1).values.argmax()
def max_abs_diff(x, y, threshold=None, alpha=0):
error = (x-y).abs()-x.abs()*alpha
return error_above_threshold(error, x.abs(), threshold)
def _print_summary_for_one(target, estimate, prefix=""):
max_diff_pos = None
if type(target) is torch.Tensor:
summary, max_diff_x = _summary(target, estimate, prefix)
else:
summary = ""
if target.pos is not None and estimate.pos is not None:
sub_summary, max_diff_pos = _summary(target.pos[:,:2], estimate.pos[:,:2], f"{prefix} POS")
summary += sub_summary
sub_summary, max_diff_x = _summary(target.x, estimate.x, prefix=f"{prefix} X")
summary += sub_summary
return summary, max_diff_x, max_diff_pos
def print_summary_of_module(activations, runs=[0,2]):
target, estimate = [activations[i][1] for i in runs]
return _print_summary_for_one(target, estimate, "OUT")
def test_and_compare_activations(model, runs=[0,2]):
num_mistakes = []
global_summary = ""
for name, module in model.named_modules():
if not hasattr(module, "activations"):
continue
else:
if len(module.activations) <= max(runs):
continue
summary, max_diff_x, max_diff_pos = print_summary_of_module(module.activations, runs)
if max_diff_x is not None and max_diff_pos is not None:
num_mistakes.append([max_diff_x, max_diff_pos, name])
global_summary += f"Inspecting {name}\n{summary}\n\n"
max_mistake_x_layer = max(num_mistakes, key=lambda x: x[0])
max_mistake_pos_layer = max(num_mistakes, key=lambda x: x[1])
global_summary += f"Maximum mistakes: \n" \
f"\t{max_mistake_x_layer}\n" \
f"\t{max_mistake_pos_layer}"
return max_mistake_x_layer, max_mistake_pos_layer, global_summary
================================================
FILE: src/dagr/asynchronous/flops/__init__.py
================================================
import logging
from torch.nn import ModuleList
from .conv import compute_flops_conv, compute_flops_cat
def compute_flops_from_module(module) -> int:
"""Compute flops from a GNN module (after the forward pass).
Generally, there are two cases. Either the module is an asynchronous module, then it should
have an `flops_log`, which contains the flops used for the last forward pass. Otherwise, the
layer's flops are computed from to the synchronous, dense update.
:param module: module to infer the flops from.
"""
module_name = module.__class__.__name__
if hasattr(module, "asy_flops_log") and module.asy_flops_log is not None:
assert type(module.asy_flops_log) == list, "asyc. flops log must be a list"
if type(module) is ModuleList:
flops = sum([compute_flops_from_module(layer) for layer in module._modules.values()])
else:
assert len(module.asy_flops_log) > 0, f"asynchronous flops log is empty for module {module.__class__.__name__}"
flops = module.asy_flops_log[-1]
else:
logging.debug(f"Module {module_name} is not asynchronous, using flops = 0")
return 0
logging.debug(f"Module {module_name} adds {flops} flops")
return flops
__all__ = [
"compute_flops_conv",
"compute_flops_from_module"
]
================================================
FILE: src/dagr/asynchronous/flops/conv.py
================================================
import torch
def compute_flops_conv(module: torch.nn.Module, num_times_apply_bias_and_root: int, num_edges: int, concatenation=False, num_image_channels=-1) -> int:
# Iterate over every different and every new node, and add the number of flops introduced
# by the node to the overall flops count of the layer.
ni = num_edges
m_in = module.in_channels
if concatenation:
m_in -= num_image_channels
m_out = module.out_channels
flops = ni * (2*m_in-1) * m_out
if hasattr(module, "root_weight") and module.root_weight:
flops += num_times_apply_bias_and_root * module.lin.weight.shape[0] * (2*module.lin.weight.shape[1]-1)
if hasattr(module, "bias") and module.bias is not None:
flops += num_times_apply_bias_and_root * module.lin.weight.shape[0]
return flops
def compute_flops_cat(module, num_edges, num_times_apply_bias_and_root, num_image_channels):
ni = num_edges
m_in = num_image_channels
m_out = module.out_channels
flops = ni * (2 * m_in - 1) * m_out
if hasattr(module, "root_weight") and module.root_weight:
flops += num_times_apply_bias_and_root * module.lin.weight.shape[0] * (2*m_in-1)
return flops
================================================
FILE: src/dagr/asynchronous/linear.py
================================================
import numpy as np
import torch
import torch_geometric
import asy_tools
from torch.nn import Linear
import torch.nn.functional as F
from .base.base import make_asynchronous, add_async_graph
from .base.utils import graph_new_nodes, graph_changed_nodes
def __graph_initialization(module: Linear, data) -> torch.Tensor:
mask = data.active_clusters if hasattr(data, "active_clusters") else slice(None, None, None)
x = data.x[mask]
weight = module.mlp.weight
bias = module.mlp.bias
y = torch.zeros(size=(len(data.x), weight.shape[0]), dtype=torch.float32, device=data.pos.device)
y[mask] = F.linear(x, weight, bias)
module.asy_graph = data.clone()
module.graph_out = torch_geometric.data.Data(x=y, pos=data.pos)
if hasattr(data, "active_clusters"):
module.graph_out.active_clusters = data.active_clusters
if module.asy_flops_log is not None:
flops = int(np.prod(x.size()) * y.size()[-1])
module.asy_flops_log.append(flops)
return module.graph_out.clone()
def __graph_processing(module: Linear, data) -> torch.Tensor:
if len(module.asy_graph.x) < len(data.x):
diff_idx = graph_new_nodes(module.asy_graph, data)
diff_pos_idx = diff_idx.clone()
module.graph_out.x = torch.cat([module.graph_out.x, torch.zeros_like(module.graph_out.x[:len(diff_idx)])])
else:
diff_idx, diff_pos_idx = graph_changed_nodes(module.asy_graph, data)
weight = module.mlp.weight
bias = module.mlp.bias
# Update the graph with the new values (only there where it has changed).
if diff_idx.numel() > 0:
if bias is not None:
asy_tools.masked_lin(diff_idx, data.x, module.graph_out.x, weight.data, bias.data, False)
else:
asy_tools.masked_lin_no_bias(diff_idx, data.x, module.graph_out.x, weight.data, False)
# If required, compute the flops of the asynchronous update operation.
if module.asy_flops_log is not None:
cin = weight.shape[1]
cat = hasattr(data, "skipped") and data.skipped
data.skipped = False
if cat:
cin -= data.num_image_channels
flops = diff_idx.numel() * int(weight.shape[0] * (2*cin-1))
flops += diff_idx.numel() * weight.shape[0]
module.asy_flops_log.append(flops)
data.diff_idx = diff_idx
data.diff_pos_idx = diff_pos_idx
data.x = module.graph_out.x
return data
def __check_support(module: Linear):
return True
def make_linear_asynchronous(module: Linear, log_flops: bool = False):
"""Module converter from synchronous to asynchronous & sparse processing for linear layers.
By overwriting parts of the module asynchronous processing can be enabled without the need of re-learning
and moving its weights and configuration. So, a linear layer can be converted by, for example:
```
module = Linear(4, 2)
module = make_linear_asynchronous(module)
```
:param module: linear module to transform.
:param log_flops: log flops of asynchronous update.
"""
assert __check_support(module)
module = add_async_graph(module, log_flops=log_flops)
return make_asynchronous(module, __graph_initialization, __graph_processing)
================================================
FILE: src/dagr/asynchronous/max_pool.py
================================================
import logging
import torch
from torch_geometric.data import Data
from torch_scatter import scatter_max, scatter_sum
from .base.base import add_async_graph, make_asynchronous
from .base.utils import graph_changed_nodes, graph_new_nodes, _efficient_cat_unique, torch_isin, _efficient_cat
from .conv import __edges_with_src_node
from .base.utils import _to_hom, _from_hom, __remove_duplicate_from_A
def pool_edge(cluster, edge_index, self_loop):
edge_index = cluster[edge_index]
if self_loop:
edge_index = edge_index.unique(dim=-1)
else:
edge_index = edge_index[:,edge_index[0]!=edge_index[1]].unique(dim=-1)
if len(edge_index) > 0:
return edge_index
return torch.zeros((2,0), dtype=torch.long, device=cluster.device)
def compute_attrs(transform, edge_index, pos):
return (pos[edge_index[0]] - pos[edge_index[1]]) / (2 * transform.max) + 0.5
def __dense_process(module, data: Data, *args, **kwargs) -> Data:
# compute the cache to compute the output graph. This contains
# 1. the cluster assignment for each input feature -> dim num_input_nodes
# 2. the sum of positions for each feature in each cluster -> max_num_clusters
# 3. the count of positions for each feature -> max_num_clusters
# 4. which input nodes went to the computation of which output_node -> max_num_clusters x num_output
cluster_index = __get_global_cluster_index(module, pos=data.pos[:,:module.dim])
x, pos = data.x, data.pos
edge_index = pool_edge(cluster_index, data.edge_index, module.self_loop)
if hasattr(module.asy_graph, "active_clusters"):
active_cluster_index = cluster_index[module.asy_graph.active_clusters]
new_cluster_index = torch.full_like(cluster_index, fill_value=-1)
new_cluster_index[module.asy_graph.active_clusters] = active_cluster_index
cluster_index = new_cluster_index
x = x[module.asy_graph.active_clusters]
pos = pos[module.asy_graph.active_clusters]
else:
active_cluster_index = cluster_index
pos_hom = scatter_sum(_to_hom(pos[:,:module.dim]), active_cluster_index, dim=0, dim_size=module.num_grid_cells)
output_pos = _from_hom(pos_hom)
module.wh_inv = 1/ torch.Tensor([data.width[0], data.height[0]]).to(output_pos.device).view(1,-1)
output_pos[:,:2] = module.round_to_pixel(output_pos[:,:2], wh_inv=module.wh_inv)
active_clusters = torch.unique(active_cluster_index)
cache = Data(cluster_index=cluster_index, pos_hom=pos_hom)
if module.aggr == 'max':
output_x = torch.full(size=(module.num_grid_cells, x.shape[1]), fill_value=-torch.inf, device=x.device)
_, output_argmax = scatter_max(x, active_cluster_index, dim=0, out=output_x, dim_size=module.num_grid_cells)
cache.output_argmax = output_argmax
else:
x_hom = _to_hom(x)
cache.output_x_hom = scatter_sum(x_hom, active_cluster_index, dim=0, dim_size=module.num_grid_cells)
output_x = _from_hom(cache.output_x_hom)
module.ones = torch.ones_like(output_x[:,:1])
# construct output. This contains:
# the output graph -> has num_unique_clusters nodes
if module.keep_temporal_ordering:
t = pos[:, -1] if pos.shape[-1] > 2 else data.t_max[active_cluster_index]
output_t = torch.full(size=(module.num_grid_cells,), fill_value=-torch.inf, device=x.device)
t_max, _ = scatter_max(t, active_cluster_index, dim=0, out=output_t, dim_size=module.num_grid_cells)
if edge_index.shape[1] > 0:
t_src, t_dst = t_max[edge_index]
edge_index = edge_index[:, t_dst > t_src]
output_graph = Data(x=output_x,
pos=output_pos,
edge_index=edge_index,
active_clusters=active_clusters,
width=data.width,
height=data.height)
if module.keep_temporal_ordering:
output_graph.t_max = output_t
if module.transform is not None:
output_graph = module.transform(output_graph)
return output_graph, cache
def __graph_initialization(module, data: Data, *args, **kwargs) -> Data:
"""Graph initialization for asynchronous update.
Both the input as well as the output graph have to be stored, in order to avoid repeated computation. The
input graph is used for spotting changed or new nodes (as for other asyn. layers), while the output graph
is compared to the set of diff & new nodes, in order to be updated. Depending on the type of pooling (max, mean,
average, etc) not only the output voxel feature have to be stored but also aggregations over all nodes in
one output voxel such as the sum or count.
Next to the features the node positions are averaged over all nodes in the voxel, as well. To do so,
position aggregations (count, sum) are stored and updated, too.
"""
module.asy_graph = data.clone()
module.graph_out, module.cache = __dense_process(module, data)
module.graph_out.pooling = module.voxel_size
logging.debug(f"Resulting in coarse graph {module.graph_out}")
# Compute number of floating point operations (no cat, flatten, etc.).
if module.asy_flops_log is not None:
unique_clusters = len(module.graph_out.active_clusters)
flops = 6 * unique_clusters # pos and scatter with index
flops += module.graph_out.x.shape[1] * unique_clusters + module.graph_out.edge_index.numel() # every edge has to be re-assigned
module.asy_flops_log.append(flops)
return module.graph_out.clone()
#@profile
def __graph_process(module, data, *args, **kwargs) -> Data:
new_nodes = len(data.x) > len(module.asy_graph.x)
if new_nodes:
new_idx = graph_new_nodes(module.asy_graph, data)
module.asy_graph.x = torch.cat([module.asy_graph.x, data.x[new_idx]])
module.asy_graph.pos = torch.cat([module.asy_graph.pos, data.pos[new_idx]])
new_cluster_idx = __get_global_cluster_index(module, data.pos[new_idx, :module.dim])
# add to active clusters
if new_idx.numel() > 0:
module.graph_out.active_clusters = torch.cat([new_cluster_idx, module.graph_out.active_clusters]).sort().values.unique()
module.cache.cluster_index = torch.cat([module.cache.cluster_index, new_cluster_idx])
diff_pos_idx = new_idx
new_pos_hom = _to_hom(data.pos[new_idx, :module.dim], module.ones)
recomp_pos_new = new_cluster_idx
recomp_x_new = new_cluster_idx
if recomp_x_new.numel() > 0:
recomp_x_new = recomp_x_new#.clone()
num_diff_x = 0#len(diff_idx)
num_new = len(new_idx)
scatter_sum(new_pos_hom, new_cluster_idx, out=module.cache.pos_hom, dim=0)
if recomp_x_new.numel() > 0:
if module.aggr == "max":
mask = torch.cat([module.cache.output_argmax[recomp_x_new].ravel(), new_idx]).unique()
else:
mask = torch_isin(module.cache.cluster_index, recomp_x_new)
else:
num_new = 0
diff_idx, diff_pos_idx = graph_changed_nodes(module.asy_graph, data)
num_diff_x = len(diff_idx)
recomp_x_new = None
recomp_pos_new = None
if diff_pos_idx.numel()> 0:
inactive = torch_isin(diff_pos_idx, module.asy_graph.active_clusters)
old_pos = module.asy_graph.pos[diff_pos_idx[inactive], :module.dim]
module.asy_graph.pos[diff_pos_idx] = data.pos[diff_pos_idx]
old_pos_hom = _to_hom(old_pos, module.ones)
old_cluster_idx_pos = __get_global_cluster_index(module, old_pos)
new_pos_hom = _to_hom(data.pos[diff_pos_idx, :module.dim], module.ones)
all_pos = torch.cat([-old_pos_hom, new_pos_hom])
new_cluster_idx_pos = __get_global_cluster_index(module, data.pos[diff_pos_idx, :module.dim])
module.cache.cluster_index[diff_pos_idx] = new_cluster_idx_pos
recomp_x_new = new_cluster_idx_pos
recomp_pos_new = _efficient_cat([old_cluster_idx_pos, new_cluster_idx_pos])
# todo stupid bug, shallow copy could occur
if recomp_pos_new.numel()>0 and recomp_pos_new.data_ptr() == recomp_x_new.data_ptr():
recomp_pos_new = recomp_pos_new#.clone()
scatter_sum(all_pos, recomp_pos_new, out=module.cache.pos_hom, dim=0)
if diff_idx.numel() > 0:
cluster_idx_x = __get_global_cluster_index(module, module.asy_graph.pos[diff_idx, :module.dim])
recomp_x_new = cluster_idx_x if recomp_x_new is None else _efficient_cat_unique([recomp_x_new, cluster_idx_x])
if recomp_x_new is not None and recomp_x_new.numel() > 0:
mask = torch_isin(module.cache.cluster_index, recomp_x_new)
if module.aggr == "max":
module.graph_out.x[recomp_x_new] = -torch.inf
if recomp_x_new is not None and recomp_x_new.numel() > 0:
if module.aggr == "max":
scatter_max(data.x[mask], module.cache.cluster_index[mask], out=module.graph_out.x, dim=0)
else:
delta_x_hom = _to_hom(data.x[mask], module.ones) #
valid = ~torch.isinf(module.asy_graph.x[mask][:,0])
delta_x_hom[valid] -= _to_hom(module.asy_graph.x[mask][valid], module.ones)
scatter_sum(delta_x_hom, module.cache.cluster_index[mask], out=module.cache.output_x_hom, dim=0)
module.graph_out.x[recomp_x_new] = _from_hom(module.cache.output_x_hom[recomp_x_new])
# find the edges which are associated with changed positions since these need their attrs updated
# however, here we can only look at the x,y values. If only the third attr changes, then we don't need to do anything
if recomp_pos_new is not None and recomp_pos_new.numel() > 0:
# update pos with the updated positions
new_pos = _from_hom(module.cache.pos_hom[recomp_pos_new])
new_pos[:,:2] = module.round_to_pixel(new_pos[:,:2], wh_inv=module.wh_inv)
module.graph_out.pos[recomp_pos_new,:module.dim] = new_pos
update_edge_index, changed_edges = __edges_with_src_node(recomp_pos_new, module.graph_out.edge_index, node_idx_type="both", return_changed_edges=True)
if module.transform is not None:
module.graph_out._changed_attr = compute_attrs(module.transform, update_edge_index, module.graph_out.pos)
module.graph_out._changed_attr_indices = changed_edges
# also handle edges which come from new connections at the input. These first need to be pooled
# then check if they are actually new.
if data.edge_index.numel() > 0:
coarse_edge_index = pool_edge(module.cache.cluster_index, data.edge_index, module.self_loop)
module.graph_out.edge_index = __remove_duplicate_from_A(coarse_edge_index, module.graph_out.edge_index)
else:
module.graph_out.edge_index = data.edge_index#torch.empty((2, 0), dtype=torch.long, device=data.x.device)
if module.transform is not None:
if module.graph_out.edge_index.numel() > 0:
module.graph_out.edge_attr = compute_attrs(module.transform, module.graph_out.edge_index, module.graph_out.pos)
else:
module.graph_out.edge_attr = data.edge_attr
module.graph_out.diff_idx = recomp_x_new.unique() if recomp_x_new is not None else diff_idx
module.graph_out.diff_pos_idx = recomp_pos_new.unique() if recomp_pos_new is not None else diff_pos_idx
if module.asy_flops_log is not None:
num_recomp_x = 0 if recomp_x_new is None else len(recomp_x_new)
num_recomp_pos = 0 if recomp_pos_new is None else len(recomp_pos_new)
flops = 0
flops += num_recomp_x * module.graph_out.x.shape[1] # perform max
flops += num_recomp_pos # recompute pos
flops += 4 * len(diff_pos_idx) # subtract and add pos twice
flops += len(diff_pos_idx) + num_diff_x # get cluster center for each index
flops += num_new * 2 # add twice, also compute cluster center
module.asy_flops_log.append(flops)
return module.graph_out
def __get_global_cluster_index(module, pos) -> torch.LongTensor:
n_pos_dim = 2#pos.shape[1]
voxel_size = module.voxel_size[:n_pos_dim]#, device=pos.device)
pos_vertex = (pos[:,:2] / voxel_size).long()
x_v, y_v = pos_vertex.t()
grid_size = (1 / voxel_size + 1e-3).long()
cluster_idx = x_v + grid_size[0] * y_v
return cluster_idx
def make_max_pool_asynchronous(module, log_flops: bool = False):
"""Module converter from synchronous to asynchronous & sparse processing for graph max pooling layer.
By overwriting parts of the module asynchronous processing can be enabled without the need re-creating the
object. So, a max pooling layer can be converted by, for example:
```
module = MaxPool([4, 4])
module = make_max_pool_asynchronous(module)
```
:param module: standard max pooling module.
:param grid_size: grid size (grid starting at 0, spanning to `grid_size`), >= `size`.
:param r: update radius around new events.
:param log_flops: log flops of asynchronous update.
"""
module = add_async_graph(module, log_flops=log_flops)
module = make_asynchronous(module, __graph_initialization, __graph_process)
return module
================================================
FILE: src/dagr/data/augment.py
================================================
import torch
from torch_geometric.transforms import BaseTransform
from torch_geometric.data import Data
from typing import List
import cv2
import numpy as np
import numba
import torch_geometric.transforms as T
@numba.njit
def _add_event(x, y, xlim, ylim, p, i, count, pos, mask, threshold=1):
count[ylim, xlim] += float(p * (1 - abs(x - xlim)) * (1 - abs(y - ylim)))
pol = 1 if count[ylim, xlim] > 0 else -1
if pol * count[ylim, xlim] > threshold:
count[ylim, xlim] -= pol * threshold
mask[i] = True
pos[i, 0] = xlim
pos[i, 1] = ylim
@numba.njit
def _subsample(pos: np.ndarray, polarity: np.ndarray, mask: np.ndarray, count: np.ndarray, threshold=1):
for i in range(len(pos)):
x, y = pos[i]
x0, x1 = int(x), int(x+1)
y0, y1 = int(y), int(y+1)
_add_event(x, y, x0, y0, polarity[i,0], i=i, count=count, pos=pos, mask=mask, threshold=threshold)
_add_event(x, y, x1, y0, polarity[i,0], i=i, count=count, pos=pos, mask=mask, threshold=threshold)
_add_event(x, y, x0, y1, polarity[i,0], i=i, count=count, pos=pos, mask=mask, threshold=threshold)
_add_event(x, y, x1, y1, polarity[i,0], i=i, count=count, pos=pos, mask=mask, threshold=threshold)
def _crop_events(data, left, right, not_crop_idx=None):
if not_crop_idx is None:
not_crop_idx = torch.all((data.pos >= left) & (data.pos <= right), dim=1)
data.x = data.x[not_crop_idx]
data.pos = data.pos[not_crop_idx]
if hasattr(data, "t"):
data.t = data.t[not_crop_idx]
return data
def _crop_image(image, left, right):
xmin, ymin = left
xmax, ymax = right
image[:ymin, :] = 0
image[ymax:, :] = 0
image[:, :xmin] = 0
image[:, xmax:] = 0
return image
def _resize_image(image, height, width, bg=None):
image = image[0].permute(1, 2, 0).numpy()
new_image = cv2.resize(image, (width, height), interpolation=cv2.INTER_NEAREST)
px = (new_image.shape[1] - image.shape[1])//2
py = (new_image.shape[0] - image.shape[0])//2
if px >= 0:
bg = new_image[py:py+image.shape[0], px:px+image.shape[1]]
else:
assert bg is not None
bg[-py:-py+new_image.shape[0], -px:-px+new_image.shape[1]] = new_image
bg = torch.from_numpy(bg).permute(2, 0, 1)[None]
return bg
def _crop_bbox(bbox: torch.Tensor, left: torch.Tensor, right: torch.Tensor):
bbox = bbox.clone()
bbox[:,2:4] += bbox[:,:2]
bbox[:,:2] = torch.clamp(bbox[:,:2], min=left, max=right)
bbox[:,2:4] = torch.clamp(bbox[:,2:4], min=left, max=right)
bbox[:,2:4] -= bbox[:,:2]
return bbox
def _scale_and_clip(x, scale):
return int(torch.clamp(x * scale, min=0, max=scale-1))
class RandomHFlip(BaseTransform):
def __init__(self, p: float):
self.p = p
def __call__(self, data: Data):
if torch.rand(1) > self.p:
return data
data.pos[:,0] = data.width - 1 - data.pos[:,0]
if hasattr(data, "image"):
image = data.image[0].permute(1,2,0).numpy()
image = np.ascontiguousarray(image[:,::-1])
image = torch.from_numpy(image).permute(2, 0, 1)[None]
data.image = image
if hasattr(data, "bbox"):
data.bbox[:, 0] = data.width - 1 - (data.bbox[:, 0] + data.bbox[:, 2])
if hasattr(data, "bbox0"):
data.bbox0[:, 0] = data.width - 1 - (data.bbox0[:, 0] + data.bbox0[:, 2])
return data
class Crop(BaseTransform):
r"""Crop with max and min values, has to be called before a graph is generated.
Args:
min (List[float]): min value per dimension
max (List[float]): max value per dimension
"""
def __init__(self, min: List[float], max: List[float]):
self.min = torch.as_tensor(min)
self.max = torch.as_tensor(max)
def init(self, height, width):
size = [width, height]
self.max = torch.IntTensor([_scale_and_clip(m, s) for m, s in zip(self.max, size)])
self.min = torch.IntTensor([_scale_and_clip(m, s) for m, s in zip(self.min, size)])
def __call__(self, data: Data):
data = _crop_events(data, self.min, self.max)
if hasattr(data, "image"):
data.image = _crop_image(data.image, self.min, self.max)
# crop bbox to dimension
if hasattr(data, "bbox"):
data.bbox = _crop_bbox(data.bbox, self.min, self.max)
if hasattr(data, "bbox0"):
data.bbox0 = _crop_bbox(data.bbox0, self.min, self.max)
return data
class RandomZoom(BaseTransform):
def __init__(self, zoom, subsample=False):
self.zoom = zoom
self.subsample = subsample
self.image = None
if subsample:
self._count = None
def _subsample(self, data, zoom, count):
pos_zoom = data.pos.numpy()
mask = np.zeros(len(data.pos), dtype="bool")
_subsample(pos_zoom, data.x.numpy(), mask, count, threshold=1/(float(zoom)**2))
data.pos = torch.from_numpy(pos_zoom[mask].astype("int16")) # implicit cast to int
data.x = data.x[mask]
if hasattr(data, "t"):
data.t = data.t[mask]
return data
def init(self, height, width):
self.image = np.zeros((height, width, 3), dtype="uint8")
self._count = np.zeros((height + 1, width + 1), dtype="float32")
def __call__(self, data):
zoom = torch.rand(1) * (self.zoom[1] - self.zoom[0]) + self.zoom[0]
width, height = int(np.ceil(data.width * zoom)), int(np.ceil(data.height * zoom))
H, W = self.image.shape[:2]
data.pos[:, 0] = ((data.pos[:, 0] - W // 2) * zoom + W // 2).to(torch.int16)
data.pos[:, 1] = ((data.pos[:, 1] - H // 2) * zoom + H // 2).to(torch.int16)
if self.subsample and zoom < 1:
data = self._subsample(data, float(zoom), count=self._count.copy())
if hasattr(data, "image"):
data.image = _resize_image(data.image, width=width, height=height, bg=self.image.copy() if zoom < 1 else None)
if hasattr(data, "bbox"):
data.bbox[:,2:4] *= zoom
data.bbox[:,0] = ((data.bbox[:,0] - W//2) * zoom + W//2)
data.bbox[:,1] = ((data.bbox[:,1] - H//2) * zoom + H//2)
if hasattr(data, "bbox0"):
data.bbox0[:,2:4] *= zoom
data.bbox0[:,0] = ((data.bbox0[:,0] - W//2) * zoom + W//2)
data.bbox0[:,1] = ((data.bbox0[:,1] - H//2) * zoom + H//2)
return data
class RandomCrop(BaseTransform):
r"""Random crop, assumes all pos values are in [0,1]
Args:
size (List[float]): crop size per dimension
dim (List[int]): dimension of the crop, default = [0,1]
p float: only to random crop with a probability of p
"""
def __init__(self, size: List[float] = [0.75, 0.75], dim: List[int]=[0,1], p=0.5):
self.size = torch.as_tensor(size)
self.dim = dim
self.p = p
def init(self, height, width):
size = torch.IntTensor([width, height])
self.size = torch.IntTensor([_scale_and_clip(s, ss) for s, ss in zip(self.size, size)])
self.left_max = size - self.size
def __call__(self, data: Data):
if torch.rand(1) > self.p:
return data
left = (torch.rand(len(self.dim)) * self.left_max).to(torch.int16)
right = left + self.size
data = _crop_events(data, left, right)
if hasattr(data, "image"):
data.image = _crop_image(data.image, left, right)
# crop bbox to new crop dimension
if hasattr(data, "bbox"):
data.bbox = _crop_bbox(data.bbox, left, right)
if hasattr(data, "bbox0"):
data.bbox0 = _crop_bbox(data.bbox0, left, right)
return data
class RandomTranslate(BaseTransform):
r"""Random crop, assumes all pos values are in [0,1]
Args:
size (float): crop size per dimension
dim (int): dimension of the crop, default = [0,1]
"""
def __init__(self, size: List[float]):
self.size = torch.as_tensor(size).float()
self.image = None
def init(self, height, width):
size = [width, height]
self.size = torch.IntTensor([_scale_and_clip(s, ss) for s, ss in zip(self.size, size)])
self.image = np.zeros((height + 2 * self.size[1], width + 2 * self.size[0], 3), dtype="uint8")
def pad(self, image, bg):
px = (bg.shape[1] - image.shape[1])//2
py = (bg.shape[0] - image.shape[0])//2
bg[py:py + image.shape[0], px:px + image.shape[1]] = image
return bg
def __call__(self, data: Data):
move_px = (self.size * (torch.rand(len(self.size)) * 2 - 1)).to(torch.int16)
data.pos = data.pos + move_px
if hasattr(data, "image"):
image = data.image[0].permute(1, 2, 0).numpy()
image = self.pad(image, self.image.copy())
image = image[self.size[1]-move_px[1]:self.size[1]-move_px[1]+data.height, \
self.size[0]-move_px[0]:self.size[0]-move_px[0]+data.width]
data.image = torch.from_numpy(image).permute(2, 0, 1)[None]
if hasattr(data, "bbox"):
data.bbox[:,:2] += move_px
if hasattr(data, "bbox0"):
data.bbox0[:,:2] += move_px
return data
class Augmentations:
transform_testing = T.Compose([
Crop([0, 0], [1, 1]),
])
def __init__(self, args):
self.transform_training = T.Compose([
RandomHFlip(p=args.aug_p_flip),
RandomCrop([0.75, 0.75], p=0.2),
RandomZoom(zoom=[1, args.aug_zoom], subsample=True),
RandomTranslate([args.aug_trans, args.aug_trans, 0]),
Crop([0, 0], [1, 1]),
])
def init_transforms(transforms, height, width):
for t in transforms:
if hasattr(t, "init"):
t.init(height=height, width=width)
================================================
FILE: src/dagr/data/dsec_data.py
================================================
from pathlib import Path
from typing import Optional, Callable
from torch_geometric.data import Dataset
import numpy as np
import cv2
import torch
from functools import lru_cache
from dsec_det.dataset import DSECDet
from dsec_det.io import yaml_file_to_dict
from dagr.data.dsec_utils import filter_tracks, crop_tracks, rescale_tracks, compute_class_mapping, map_classes, filter_small_bboxes
from dsec_det.directory import BaseDirectory
from dagr.data.augment import init_transforms
from dagr.data.utils import to_data
from dagr.visualization.bbox_viz import draw_bbox_on_img
from dagr.visualization.event_viz import draw_events_on_image
def tracks_to_array(tracks):
return np.stack([tracks['x'], tracks['y'], tracks['w'], tracks['h'], tracks['class_id']], axis=1)
def interpolate_tracks(detections_0, detections_1, t):
assert len(detections_1) == len(detections_0)
if len(detections_0) == 0:
return detections_1
t0 = detections_0['t'][0]
t1 = detections_1['t'][0]
assert t0 < t1
# need to sort detections
detections_0 = detections_0[detections_0['track_id'].argsort()]
detections_1 = detections_1[detections_1['track_id'].argsort()]
r = ( t - t0 ) / ( t1 - t0 )
detections_out = detections_0.copy()
for k in 'xywh':
detections_out[k] = detections_0[k] * (1 - r) + detections_1[k] * r
return detections_out
class EventDirectory(BaseDirectory):
@property
@lru_cache
def event_file(self):
return self.root / "left/events_2x.h5"
class DSEC(Dataset):
MAPPING = dict(pedestrian="pedestrian", rider=None, car="car", bus="car", truck="car", bicycle=None,
motorcycle=None, train=None)
def __init__(self,
root: Path,
split: str,
transform: Optional[Callable]=None,
debug=False,
min_bbox_diag=0,
min_bbox_height=0,
scale=2,
cropped_height=430,
only_perfect_tracks=False,
demo=False,
no_eval=False):
Dataset.__init__(self)
split_config = None
if not demo:
split_config = yaml_file_to_dict(Path(__file__).parent / "dsec_split.yaml")
assert split in split_config.keys(), f"'{split}' not in {list(split_config.keys())}"
self.dataset = DSECDet(root=root, split=split, sync="back", debug=debug, split_config=split_config)
for directory in self.dataset.directories.values():
directory.events = EventDirectory(directory.events.root)
self.scale = scale
self.width = self.dataset.width // scale
self.height = cropped_height // scale
self.classes = ("car", "pedestrian")
self.time_window = 1000000
self.min_bbox_height = min_bbox_height
self.min_bbox_diag = min_bbox_diag
self.debug = debug
self.num_us = -1
self.class_remapping = compute_class_mapping(self.classes, self.dataset.classes, self.MAPPING)
if transform is not None and hasattr(transform, "transforms"):
init_transforms(transform.transforms, self.height, self.width)
self.transform = transform
self.no_eval = no_eval
if self.no_eval:
only_perfect_tracks = False
self.image_index_pairs, self.track_masks = filter_tracks(dataset=self.dataset, image_width=self.width,
image_height=self.height,
class_remapping=self.class_remapping,
min_bbox_height=min_bbox_height,
min_bbox_diag=min_bbox_diag,
only_perfect_tracks=only_perfect_tracks,
scale=scale)
def set_num_us(self, num_us):
self.num_us = num_us
def visualize_debug(self, index):
data = self.__getitem__(index)
image = data.image[0].permute(1,2,0).numpy()
p = data.x[:,0].numpy()
x, y = data.pos.t().numpy()
b_x, b_y, b_w, b_h, b_c = data.bbox.t().numpy()
image = draw_events_on_image(image, x, y, p)
image = draw_bbox_on_img(image, b_x, b_y, b_w, b_h,
b_c, np.ones_like(b_c), conf=0.3, nms=0.65)
cv2.imshow(f"Debug {index}", image)
cv2.waitKey(0)
def __len__(self):
return sum(len(d) for d in self.image_index_pairs.values())
def preprocess_detections(self, detections):
detections = rescale_tracks(detections, self.scale)
detections = crop_tracks(detections, self.width, self.height)
detections['class_id'], _ = map_classes(detections['class_id'], self.class_remapping)
return detections
def preprocess_events(self, events):
mask = events['y'] < self.height
events = {k: v[mask] for k, v in events.items()}
if len(events['t']) > 0:
events['t'] = self.time_window + events['t'] - events['t'][-1]
events['p'] = 2 * events['p'].reshape((-1,1)).astype("int8") - 1
return events
def preprocess_image(self, image):
image = image[:self.scale * self.height]
image = cv2.resize(image, (self.width, self.height), interpolation=cv2.INTER_CUBIC)
image = torch.from_numpy(image).permute(2, 0, 1)
image = image.unsqueeze(0)
return image
def __getitem__(self, idx):
dataset, image_index_pairs, track_masks, idx = self.rel_index(idx)
image_index_0, image_index_1 = image_index_pairs[idx]
image_ts_0, image_ts_1 = dataset.images.timestamps[[image_index_0, image_index_1]]
detections_0 = self.dataset.get_tracks(image_index_0, mask=track_masks, directory_name=dataset.root.name)
detections_1 = self.dataset.get_tracks(image_index_1, mask=track_masks, directory_name=dataset.root.name)
detections_0 = self.preprocess_detections(detections_0)
detections_1 = self.preprocess_detections(detections_1)
image_0 = self.dataset.get_image(image_index_0, directory_name=dataset.root.name)
image_0 = self.preprocess_image(image_0)
events = self.dataset.get_events(image_index_0, directory_name=dataset.root.name)
if self.num_us >= 0:
image_ts_1 = image_ts_0 + self.num_us
events = {k: v[events['t'] < image_ts_1] for k, v in events.items()}
if not self.no_eval:
detections_1 = interpolate_tracks(detections_0, detections_1, image_ts_1)
# here, the timestamp of the events is no longer absolute
events = self.preprocess_events(events)
# convert to torch geometric data
data = to_data(**events, bbox=tracks_to_array(detections_1), bbox0=tracks_to_array(detections_0), t0=image_ts_0, t1=image_ts_1,
width=self.width, height=self.height, time_window=self.time_window,
image=image_0, sequence=str(dataset.root.name))
if self.transform is not None:
data = self.transform(data)
# remove bboxes if they have 0 width or height
mask = filter_small_bboxes(data.bbox[:, 2], data.bbox[:, 3], self.min_bbox_height, self.min_bbox_diag)
data.bbox = data.bbox[mask]
mask = filter_small_bboxes(data.bbox0[:, 2], data.bbox0[:, 3], self.min_bbox_height, self.min_bbox_diag)
data.bbox0 = data.bbox0[mask]
return data
def rel_index(self, idx):
for folder in self.dataset.subsequence_directories:
name = folder.name
image_index_pairs = self.image_index_pairs[name]
directory = self.dataset.directories[name]
track_mask = self.track_masks[name]
if idx < len(image_index_pairs):
return directory, image_index_pairs, track_mask, idx
idx -= len(image_index_pairs)
raise IndexError
================================================
FILE: src/dagr/data/dsec_split.yaml
================================================
train:
- thun_00_a
- interlaken_00_c
- interlaken_00_d
- interlaken_00_e
- interlaken_00_f
- interlaken_00_g
- zurich_city_00_a
- zurich_city_00_b
- zurich_city_01_a
- zurich_city_01_b
- zurich_city_01_c
- zurich_city_01_d
- zurich_city_01_e
- zurich_city_01_f
- zurich_city_02_a
- zurich_city_02_b
- zurich_city_02_c
- zurich_city_02_d
- zurich_city_02_e
- zurich_city_03_a
- zurich_city_04_a
- zurich_city_04_b
- zurich_city_04_c
- zurich_city_04_d
- zurich_city_04_e
- zurich_city_04_f
- zurich_city_05_a
- zurich_city_05_b
- zurich_city_06_a
- zurich_city_07_a
- zurich_city_08_a
- zurich_city_09_a
- zurich_city_09_b
- zurich_city_09_c
- zurich_city_09_d
- zurich_city_09_e
- zurich_city_10_a
- zurich_city_10_b
- zurich_city_11_a
- zurich_city_11_b
- zurich_city_11_c
val:
- zurich_city_16_a
- zurich_city_17_a
- zurich_city_18_a
- zurich_city_19_a
- zurich_city_20_a
- zurich_city_21_a
test:
- thun_01_a
- thun_01_b
- thun_02_a
- interlaken_00_a
- interlaken_00_b
- interlaken_01_a
- zurich_city_12_a
- zurich_city_13_a
- zurich_city_13_b
- zurich_city_14_a
- zurich_city_14_b
- zurich_city_14_c
- zurich_city_15_a
================================================
FILE: src/dagr/data/dsec_utils.py
================================================
import numpy as np
import h5py
def construct_pairs(indices, n=2):
indices = np.sort(indices)
indices = np.stack([indices[i:i+1-n] for i in range(n-1)] + [indices[n-1:]])
mask = np.ones_like(indices[0]) > 0
for i, row in enumerate(indices):
mask = mask & (indices[0] + i == row)
indices = indices[...,mask].T
return indices
def rescale_tracks(tracks, scale):
tracks = tracks.copy()
for k in "xywh":
tracks[k] /= scale
return tracks
def crop_tracks(tracks, width, height):
tracks = tracks.copy()
x1, y1 = tracks['x'], tracks['y']
x2, y2 = x1 + tracks['w'], y1 + tracks['h']
x1 = np.clip(x1, 0, width-1)
x2 = np.clip(x2, 0, width-1)
y1 = np.clip(y1, 0, height-1)
y2 = np.clip(y2, 0, height-1)
tracks['x'] = x1
tracks['y'] = y1
tracks['w'] = x2-x1
tracks['h'] = y2-y1
return tracks
def map_classes(class_ids, old_to_new_mapping):
new_class_ids = old_to_new_mapping[class_ids]
mask = new_class_ids > -1
return new_class_ids, mask
def filter_small_bboxes(w, h, bbox_height=20, bbox_diag=30):
"""
Filter out tracks that are too small.
"""
diag = np.sqrt(h ** 2 + w ** 2)
return (diag > bbox_diag) & (w > bbox_height) & (h > bbox_height)
def filter_tracks(dataset, image_width, image_height, class_remapping, min_bbox_height=0, min_bbox_diag=0, scale=1, only_perfect_tracks=False):
image_index_pairs = {}
track_masks = {}
for directory_path in dataset.subsequence_directories:
tracks = dataset.directories[directory_path.name].tracks.tracks
image_timestamps = dataset.directories[directory_path.name].images.timestamps
tracks_rescaled = rescale_tracks(tracks, scale)
tracks_rescaled = crop_tracks(tracks_rescaled, image_width, image_height)
_, class_mask = map_classes(tracks_rescaled['class_id'], class_remapping)
size_mask = filter_small_bboxes(tracks_rescaled['w'], tracks_rescaled['h'], min_bbox_height, min_bbox_diag)
final_mask = size_mask & class_mask
# 1. stores indices of images which are valid, i.e. survived all filters above
valid_image_indices = np.unique(np.nonzero(np.isin(image_timestamps, tracks_rescaled[final_mask]['t']))[0])
valid_image_index_pairs = construct_pairs(valid_image_indices, 2)
if only_perfect_tracks:
valid_image_timestamp_brackets = image_timestamps[valid_image_index_pairs]
img_idx_to_track_idx = compute_img_idx_to_track_idx(tracks['t'], valid_image_timestamp_brackets)
mask = filter_by_only_perfect_tracks(tracks_rescaled, img_idx_to_track_idx, tracks_mask=final_mask)
valid_image_index_pairs = valid_image_index_pairs[mask]
image_index_pairs[directory_path.name] = valid_image_index_pairs
track_masks[directory_path.name] = final_mask
return image_index_pairs, track_masks
def _load_events(file, t0, num_events=None, num_us=None, height=None, time_window=None):
with h5py.File(file, 'r') as f:
ms = int((t0 - f['t_offset'][()]) / 1e3)
idx0 = int(f['ms_to_idx'][ms])
if num_events is not None:
idx1 = idx0 + num_events
if num_us is not None:
idx1 = int(f['ms_to_idx'][ms + int(num_us / 1e3)])
idx0, idx1 = sorted([idx0, idx1])
idx0 = idx0 if idx0 >= 0 else 0
idx1 = idx1 if idx1 >= 0 else 0
# load all events
events = {k: f[f'events/{k}'][idx0:idx1] for k in "xytp"}
tq = events['t'][-1] if idx1 > idx0 else f[f'events/t'][max([idx1 - 1, idx0])]
# cast to desired types
p = 2 * events["p"][..., None].astype("int8") - 1
t_ev = events['t'][..., None]
xy = np.stack([events['x'], events['y']], axis=-1).astype("int16")
if time_window is not None:
t = (time_window - tq + t_ev).astype('int32')
else:
t = tq.copy()
# we have to add the offset here
tq += f['t_offset'][()]
tq = tq.astype("int64")
# crop events to crop height
mask = (t[:, 0] > 0)
if height is not None:
mask &= (xy[:, 1] < height)
events = (xy[mask], t[mask], p[mask])
return events, tq
def filter_by_only_perfect_tracks(tracks, img_idx_to_track_idx, tracks_mask=None):
i0, i1 = img_idx_to_track_idx
mask = np.ones_like(i0[0]) > 0
for i in range(i0.shape[1]):
track = [tracks[i0[j][i]:i1[j][i]] for j in range(len(i0))]
if tracks_mask is not None:
track_mask = [tracks_mask[i0[j][i]:i1[j][i]] for j in range(len(i0))]
track = [t[m] for t, m in zip(track, track_mask)]
mask[i] = not is_invalid_track(track)
return mask
def is_invalid_track(track):
track = [tr[tr['track_id'].argsort()] for tr in track]
i_tr = track[0]
for c_tr in track[1:]:
if len(i_tr) != len(c_tr):
return True
if not (c_tr['track_id'] == i_tr['track_id']).all():
return True
iou = compute_iou(i_tr, c_tr)
min_iou = np.min(iou)
if min_iou < 0.10:
return True
else:
return False
def compute_iou(track0, track1):
x1, x2 = track0['x'], track0['x'] + track0['w']
y1, y2 = track0['y'], track0['y'] + track0['h']
x1g, x2g = track1['x'], track1['x'] + track1['w']
y1g, y2g = track1['y'], track1['y'] + track1['h']
# Intersection keypoints
xkis1 = np.max(np.stack([x1, x1g]), axis=0)
ykis1 = np.max(np.stack([y1, y1g]), axis=0)
xkis2 = np.min(np.stack([x2, x2g]), axis=0)
ykis2 = np.min(np.stack([y2, y2g]), axis=0)
intsct = np.zeros_like(x1)
mask = (ykis2 > ykis1) & (xkis2 > xkis1)
intsct[mask] = (xkis2[mask] - xkis1[mask]) * (ykis2[mask] - ykis1[mask])
union = (x2 - x1) * (y2 - y1) + (x2g - x1g) * (y2g - y1g) - intsct + 1e-9
iou = intsct / union
return iou
def compute_indices_for_contiguous_parts(x):
x, counts = np.unique(x, return_counts=True)
idx = np.concatenate([np.array([0]), counts]).cumsum()
return np.stack([idx[:-1], idx[1:]], axis=-1)
def _compute_img_idx_to_track_idx(t, t_query):
new_img_idx = compute_indices_for_contiguous_parts(t)
mask = np.isin(np.unique(t), t_query)
new_img_idx = new_img_idx[mask].T
return new_img_idx
def compute_img_idx_to_track_idx(t, t_query):
return np.stack([_compute_img_idx_to_track_idx(t, t_q) for t_q in t_query.T])
def compute_class_mapping(classes, all_classes, mapping):
output_mapping = []
for i, c in enumerate(all_classes):
mapped_class = mapping[c]
output_mapping.append(classes.index(mapped_class) if mapped_class in classes else -1)
return np.array(output_mapping)
================================================
FILE: src/dagr/data/ncaltech101_data.py
================================================
import numpy as np
import torch
import hdf5plugin
import h5py
from pathlib import Path
from typing import Optional, Callable
from torch.utils.data import Dataset
from torch_geometric.data import Data
from dagr.data.augment import init_transforms
from dagr.data.utils import to_data
class NCaltech101(Dataset):
def __init__(self, root: Path, split, transform=Optional[Callable[[Data,], Data]], num_events: int=50000):
super().__init__()
self.load_dir = root / split
self.classes = sorted([d.name for d in self.load_dir.glob("*")])
self.num_classes = len(self.classes)
self.files = sorted(list(self.load_dir.rglob("*.h5")))
self.height = 180
self.width = 240
if transform is not None and hasattr(transform, "transforms"):
init_transforms(transform.transforms, self.height, self.width)
self.transform = transform
self.time_window = 1000000
self.num_events = num_events
def __len__(self):
return len(self.files)
def preprocess(self, data):
data.t -= (data.t[-1] - self.time_window + 1)
return data
def load_events(self, f_path):
return _load_events(f_path, self.num_events)
def __getitem__(self, idx):
f_path = self.files[idx]
target = self.classes.index(str(f_path.parent.name))
events = self.load_events(f_path)
data = to_data(**events, bbox=self.load_bboxes(f_path, target),
t0=events['t'][0], t1=events['t'], width=self.width, height=self.height,
time_window=self.time_window)
data = self.preprocess(data)
data = self.transform(data) if self.transform is not None else data
if not hasattr(data, "t"):
data.t = data.pos[:, -1:]
data.pos = data.pos[:, :2].type(torch.int16)
return data
def load_bboxes(self, raw_file: Path, class_id):
rel_path = str(raw_file.relative_to(self.load_dir))
rel_path = rel_path.replace("image_", "annotation_").replace(".h5", ".bin")
annotation_file = self.load_dir / "../annotations" / rel_path
with annotation_file.open() as fh:
annotations = np.fromfile(fh, dtype=np.int16)
annotations = np.array(annotations[2:10])
return np.array([
annotations[0], annotations[1], # upper-left corner
annotations[2] - annotations[0], # width
annotations[5] - annotations[1], # height
class_id,
1
]).astype("float32").reshape((1,-1))
def _load_events(f_path, num_events):
with h5py.File(str(f_path)) as fh:
fh = fh['events']
x = fh["x"][-num_events:]
y = fh["y"][-num_events:]
t = fh["t"][-num_events:]
p = fh["p"][-num_events:]
return dict(x=x, y=y, t=t, p=p)
================================================
FILE: src/dagr/data/utils.py
================================================
import numpy as np
import torch
from torch_geometric.data import Data
def to_data(**kwargs):
# convert all tracks to correct format
for k, v in kwargs.items():
if k.startswith("bbox"):
kwargs[k] = torch.from_numpy(v)
xy = np.stack([kwargs['x'], kwargs['y']], axis=-1).astype("int16")
t = kwargs['t'].astype("int32")
p = kwargs['p'].reshape((-1,1))
kwargs['x'] = torch.from_numpy(p)
kwargs['pos'] = torch.from_numpy(xy)
kwargs['t'] = torch.from_numpy(t)
return Data(**kwargs)
================================================
FILE: src/dagr/graph/ev_graph.cu
================================================
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include "spiral.h"
#include <vector>
#define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor")
#define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous")
#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)
#define CHECK_DEVICE(x, y) AT_ASSERTM(x.device().index() == y.device().index(), #x " and " #y " must be in same CUDA device")
__global__ void fill_edges_cuda_kernel(
const int32_t* __restrict__ batch,
const int32_t* __restrict__ pos,
const int32_t* __restrict__ all_timestamps,
const int32_t* __restrict__ indices,
const int32_t* __restrict__ event_queue,
int64_t* __restrict__ edges,
// int64_t* __restrict__ num_neighbors_array,
int B, int Q, int H, int W, int N, int K, float radius, float delta_t_us, int max_num_neighbors, int min_index
)
{
// linear index
const int event_idx = blockIdx.x * blockDim.x + threadIdx.x;
// check that thread is not out of valid range
if (event_idx >= N)
return;
int radius_int = radius;
int num_neighbors = 0;
int offset = event_idx * max_num_neighbors;
int b = batch[event_idx];
int x = pos[3 * event_idx + 0];
int y = pos[3 * event_idx + 1];
int ts_event = pos[3 * event_idx + 2];
// first add self edge
edges[offset + num_neighbors + K * 0] = indices[event_idx]-min_index;
edges[offset + num_neighbors + K * 1] = indices[event_idx]-min_index;
num_neighbors++;
SpiralOut spiral;
for (int i=0; i<std::pow(2*radius_int+1, 2); i++) {
if (num_neighbors >= max_num_neighbors) break;
for (int q=0; q<Q; q++) {
int x_neighbor = x + spiral.x;
int y_neighbor = y + spiral.y;
// break if out of fov
if (!((x_neighbor >= 0) && (y_neighbor >= 0) && (x_neighbor < W) && (y_neighbor < H))) break;
int64_t queue_idx = x_neighbor + W * y_neighbor + H * W * q + H * W * Q * b;
int idx = event_queue[queue_idx];
// break if exceeded max num neighbors or no more events in queue
if (idx < min_index) break;
if (indices[event_idx] > idx) {
int32_t ts_neighbor = all_timestamps[idx-min_index];
int32_t dt_us = ts_event - ts_neighbor;
// if delta t is too large, no edge is added
if (dt_us > delta_t_us) continue;
edges[offset + num_neighbors + K * 0] = idx-min_index;
edges[offset + num_neighbors + K * 1] = indices[event_idx]-min_index;
num_neighbors++;
if (num_neighbors >= max_num_neighbors) break;
}
}
spiral.goNext();
}
//num_neighbors_array[event_idx] = num_neighbors;
}
void fill_edges_cuda(
const torch::Tensor& batch, // N
const torch::Tensor& pos, // N x 3
const torch::Tensor& all_timestamps, // N
const torch::Tensor& event_queue, // B x Q x H x W
const torch::Tensor& indices, // N
const int max_num_neighbors,
const float radius,
const float delta_t_us,
torch::Tensor& edges, // 2 x E
const int min_index
)
{
CHECK_INPUT(batch);
CHECK_INPUT(pos);
CHECK_INPUT(event_queue);
CHECK_INPUT(all_timestamps);
CHECK_INPUT(edges);
CHECK_INPUT(indices);
CHECK_DEVICE(batch, event_queue);
CHECK_DEVICE(batch, pos);
CHECK_DEVICE(batch, edges);
CHECK_DEVICE(batch, indices);
CHECK_DEVICE(batch, all_timestamps);
unsigned N = batch.size(0);
unsigned B = event_queue.size(0);
unsigned Q = event_queue.size(1);
unsigned H = event_queue.size(2);
unsigned W = event_queue.size(3);
unsigned K = edges.size(1);
unsigned threads = 256;
dim3 blocks((N + threads - 1) / threads, 1);
fill_edges_cuda_kernel<<<blocks, threads>>>(
batch.data<int32_t>(),
pos.data<int32_t>(),
all_timestamps.data<int32_t>(),
indices.data<int32_t>(),
event_queue.data<int32_t>(),
edges.data<int64_t>(),
//num_neighbors.data<int64_t>(),
B, Q, H, W, N, K, radius, delta_t_us, max_num_neighbors, min_index
);
}
template <typename scalar_t>
__global__ void insert_in_queue_single_cuda_kernel(
const scalar_t* __restrict__ indices,
const scalar_t* __restrict__ events,
scalar_t* __restrict__ queue,
int B, int Q, int H, int W, int K
)
{
// linear index
const int lin_idx = blockIdx.x * blockDim.x + threadIdx.x;
// check that thread is not out of valid range
if (lin_idx >= K)
return;
// find out how many events to write, and what is the offset
int counts = 1;
int offset = 0;
// find out the x, y coords where to write the indices
int x = events[0];
int y = events[1];
int b = 0;
// write indices. break if queue size or counter is exceeded
for (int q=Q-1; q>=0; q--) {
int index = b * H * W * Q + q * H * W + y * W + x;
// for the current position, get the one at q - shift.
// if q - shift goes in the negative, take from indices instead
if (q >= counts) {
int shifted_index = b * H * W * Q + (q-counts) * H * W + y * W + x;
queue[index] = queue[shifted_index];
} else {
queue[index] = indices[offset + counts - 1 - q];
}
}
}
template <typename scalar_t>
__global__ void insert_in_queue_cuda_kernel(
const scalar_t* __restrict__ indices,
const scalar_t* __restrict__ unique_coords,
const scalar_t* __restrict__ cumsum_counts,
scalar_t* __restrict__ queue,
int B, int Q, int H, int W, int K
)
{
// linear index
const int lin_idx = blockIdx.x * blockDim.x + threadIdx.x;
// check that thread is not out of valid range
if (lin_idx >= K)
return;
// find out how many events to write, and what is the offset
int counts, offset;
if (lin_idx > 0) {
offset = cumsum_counts[lin_idx-1];
counts = cumsum_counts[lin_idx] - offset;
} else {
offset = 0;
counts = cumsum_counts[lin_idx];
}
// find out the x, y coords where to write the indices
int x = unique_coords[lin_idx] % W;
int y = ((unique_coords[lin_idx] - x)/ W) % H;
int b = unique_coords[lin_idx] / (W*H);
// write indices. break if queue size or counter is exceeded
for (int q=Q-1; q>=0; q--) {
int index = b * H * W * Q + q * H * W + y * W + x;
// for the current position, get the one at q - shift.
// if q - shift goes in the negative, take from indices instead
if (q >= counts) {
int shifted_index = b * H * W * Q + (q-counts) * H * W + y * W + x;
queue[index] = queue[shifted_index];
} else {
queue[index] = indices[offset + counts - 1 - q];
}
}
}
torch::Tensor insert_in_queue_single_cuda(
const torch::Tensor& indices, // 1
const torch::Tensor& events, // 4 x 1
const torch::Tensor& queue // B x Q x H x W
)
{
unsigned W = queue.size(3);
unsigned H = queue.size(2);
unsigned Q = queue.size(1);
unsigned B = queue.size(0);
unsigned K = 1;
unsigned threads = 256;
dim3 blocks((K + threads - 1) / threads, 1);
insert_in_queue_single_cuda_kernel<int32_t><<<blocks, threads>>>(
indices.data<int32_t>(),
events.data<int32_t>(),
queue.data<int32_t>(),
B, Q, H, W, K
);
return queue;
}
torch::Tensor insert_in_queue_cuda(
const torch::Tensor& indices, // N -> num events
const torch::Tensor& unique_coords, // K -> num active pixels
const torch::Tensor& cumsum_counts, // K -> num active pixels
const torch::Tensor& queue // B x Q x H x W
)
{
CHECK_INPUT(indices);
CHECK_INPUT(unique_coords);
CHECK_INPUT(cumsum_counts);
CHECK_INPUT(queue);
CHECK_DEVICE(indices, queue);
CHECK_DEVICE(indices, unique_coords);
CHECK_DEVICE(indices, cumsum_counts);
CHECK_DEVICE(indices, queue);
unsigned W = queue.size(3);
unsigned H = queue.size(2);
unsigned Q = queue.size(1);
unsigned B = queue.size(0);
unsigned K = unique_coords.size(0);
unsigned threads = 256;
dim3 blocks((K + threads - 1) / threads, 1);
insert_in_queue_cuda_kernel<int32_t><<<blocks, threads>>>(
indices.data<int32_t>(),
unique_coords.data<int32_t>(),
cumsum_counts.data<int32_t>(),
queue.data<int32_t>(),
B, Q, H, W, K
);
return queue;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("fill_edges_cuda", &fill_edges_cuda, "Find edges from a queue of events.");
m.def("insert_in_queue_cuda", &insert_in_queue_cuda, "Insert events into queue.");
m.def("insert_in_queue_single_cuda", &insert_in_queue_single_cuda, "Insert single events into queue.");
}
================================================
FILE: src/dagr/graph/ev_graph.py
================================================
import torch
from .utils import _insert_events_into_queue, _search_for_edges
def move_to_cuda(func):
def wrapper(self, x, *args, **kwargs):
device = x.device
on_cpu = device == "cpu"
if on_cpu:
x = x.to("cuda")
ret = func(self, x, *args, **kwargs)
if on_cpu:
ret = ret.cpu()
return ret
return wrapper
class AsyncGraph:
def __init__(self, width=640,
height=480,
batch_size=1,
max_num_neighbors=16,
max_queue_size=512,
radius=7,
delta_t_us=600000):
self.radius = radius
self.delta_t_us = delta_t_us
self.event_queue = None
self.max_index = 0
self.min_index = 0
self.max_queue_size = max_queue_size
self.max_num_neighbors = max_num_neighbors
self.width = width
self.height = height
self.batch_size = batch_size
self.device = None
self.edges = torch.zeros((2,0), dtype=torch.long)
self.all_timestamps = torch.zeros((0,), dtype=torch.int32)
self.new_indices = None
self.edge_buffer = None
self.event_queue = None
def initialize(self, n_ev, device):
self.edges = torch.zeros((2,0), dtype=torch.long, device=device)
self.all_timestamps = torch.zeros((0,), dtype=torch.int32, device=device)
self.new_indices = torch.arange(n_ev, dtype=torch.int32, device=device)
self.edge_buffer = torch.full((2, self.max_num_neighbors * n_ev), dtype=torch.int64, fill_value=-1, device=device)
self.event_queue = torch.full((self.batch_size, self.max_queue_size, self.height, self.width), fill_value=-1, device=device, dtype=torch.int32)
def reset(self):
self.edges = torch.zeros((2,0), dtype=torch.long, device=self.device)
self.all_timestamps = torch.zeros((0,), dtype=torch.int32, device=self.device)
self.max_index = 0
self.min_index = 0
if self.edge_buffer is not None:
self.edge_buffer.fill_(-1)
if self.event_queue is not None:
self.event_queue.fill_(-1)
@move_to_cuda
def forward(self, batch, pos, collect_edges=True):
n_ev = len(batch)
if self.device is None:
self.device = batch.device
self.initialize(n_ev, self.device)
if len(batch) == 0:
return torch.zeros((2,0), device=self.device, dtype=torch.int32)
assert type(batch) is torch.Tensor and batch.dtype == torch.int32, [type(batch), batch.dtype]
self.all_timestamps = torch.cat([self.all_timestamps, pos[:,2]])
# insert events into queue, they have an ever growing index
if n_ev > len(self.new_indices):
self.new_indices = torch.arange(0, n_ev, dtype=torch.int32, device=self.device)
self.edge_buffer = torch.full((2, self.max_num_neighbors * n_ev), dtype=torch.int64, fill_value=-1, device=self.device)
indices = self.max_index + self.new_indices[:n_ev]
self.max_index += n_ev
self.event_queue = _insert_events_into_queue(batch, pos, indices=indices, queue=self.event_queue)
# read out edges from event queue, they need to correspond to indices
# from the current nodes
self.edge_buffer.fill_(-1)
edge_indices = _search_for_edges(batch, pos,
all_timestamps=self.all_timestamps.contiguous(),
indices=indices,
queue=self.event_queue,
max_num_neighbors=self.max_num_neighbors,
radius=self.radius,
delta_t_us=self.delta_t_us,
edges=self.edge_buffer,
min_index=self.min_index)
if collect_edges:
self.edges = torch.cat([self.edges, edge_indices], dim=-1)
return edge_indices
class SlidingWindowGraph(AsyncGraph):
def __init__(self, width=640,
height=480,
batch_size=1,
max_num_neighbors=16,
max_queue_size=1024,
radius=7,
delta_t_us=600000):
AsyncGraph.__init__(self, width, height, batch_size, max_num_neighbors,
max_queue_size, radius, delta_t_us)
@property
def init(self):
return len(self.all_timestamps) > 0
def delete_nodes(self, n_delete, delete_edges=True, return_edges=True):
# delete nodes
self.all_timestamps = self.all_timestamps[n_delete:]
self.min_index += n_delete
# the current edges do not correspond to
# the nodes anymore, so they need to be decremented
if delete_edges:
mask = (self.edges[0] < n_delete) | (self.edges[1] < n_delete)
deleted_edges = self.edges[:,mask].clone()
self.edges = self.edges[:,~mask]
self.edges.add_(-n_delete)
if delete_edges and return_edges:
return deleted_edges
@move_to_cuda
def forward(self, batch, pos, return_node_counts=False, return_total_edges=False, delete_nodes=True, collect_edges=True):
n_delete = len(batch) if self.init else 0
# first find the interactions
edges = AsyncGraph.forward(self, batch, pos, collect_edges=collect_edges)
if return_total_edges:
total_edges = self.edges.clone()
if return_node_counts:
tot_nodes = len(self.all_timestamps)
ret = [edges]
if delete_nodes:
deleted_edges = self.delete_nodes(n_delete)
ret.append(deleted_edges)
if return_total_edges:
ret.append(total_edges)
if return_node_counts:
ret.append([n_delete, len(batch), tot_nodes])
if len(ret) == 1:
ret = ret[0]
return ret
================================================
FILE: src/dagr/graph/spiral.h
================================================
class SpiralOut{
protected:
unsigned layer;
unsigned leg;
public:
int x, y; //read these as output from next, do not modify.
__device__ SpiralOut():layer(1),leg(0),x(0),y(0){}
__device__ void goNext(){
switch(leg){
case 0: ++x; if(x == layer) ++leg; break;
case 1: ++y; if(y == layer) ++leg; break;
case 2: --x; if(-x == layer) ++leg; break;
case 3: --y; if(-y == layer){ leg = 0; ++layer; } break;
}
}
};
================================================
FILE: src/dagr/graph/utils.py
================================================
import torch
import ev_graph_cuda
from typing import Union
def _insert_events_into_queue(batch, pos, indices, queue: torch.LongTensor):
if len(batch) > 1:
height, width = queue.shape[-2:]
lin_coords = pos[:,0] + width * pos[:,1] + width*height*batch
sorted_lin_coords, sort_index = torch.sort(lin_coords, stable=True, descending=False)
sorted_indices = indices[sort_index].int()
unique_coords, unique_counter = torch.unique_consecutive(sorted_lin_coords, return_counts=True)
cumsum_counter = torch.cumsum(unique_counter, dim=0).int()
queue = ev_graph_cuda.insert_in_queue_cuda(sorted_indices, unique_coords, cumsum_counter, queue)
else:
queue = ev_graph_cuda.insert_in_queue_single_cuda(indices, pos, queue)
return queue
def _search_for_edges(batch, pos, all_timestamps, queue, indices, max_num_neighbors, radius, delta_t_us, edges, min_index):
ev_graph_cuda.fill_edges_cuda(batch, pos, all_timestamps, queue, indices, max_num_neighbors, radius, delta_t_us, edges, min_index)
edges = edges[:,(edges[1]>=0)]
return edges
================================================
FILE: src/dagr/model/layers/components.py
================================================
import torch
from torch_geometric.nn import BatchNorm
from torch_geometric.data import Data
import torch_geometric.transforms as T
class BatchNormData(BatchNorm):
def forward(self, data: Data):
data.x = BatchNorm.forward(self, data.x)
return data
class Linear(torch.nn.Module):
def __init__(self, ic, oc, bias=True):
torch.nn.Module.__init__(self)
self.mlp = torch.nn.Linear(ic, oc, bias=bias)
def forward(self, data: Data):
data.x = self.mlp(data.x)
return data
class Cartesian(torch.nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
T.Cartesian.__init__(self, *args, **kwargs)
def forward(self, data):
if data.edge_index.shape[1] > 0:
return T.Cartesian.__call__(self, data)
else:
data.edge_attr = torch.zeros((0, 3), dtype=data.x.dtype, device=data.x.device)
return data
================================================
FILE: src/dagr/model/layers/conv.py
================================================
import torch
from torch_geometric.data import Data
from dagr.model.layers.components import BatchNormData, Linear
from dagr.model.layers.spline_conv import MySplineConv
from dagr.model.utils import shallow_copy
class ConvBlock(torch.nn.Module):
def __init__(self, in_channels: int, out_channels: int, args, degree=1) -> None:
super(ConvBlock, self).__init__()
self.dim = args.edge_attr_dim
self.activation = getattr(torch.nn.functional, args.activation, torch.nn.functional.elu)
self.conv = MySplineConv(in_channels=in_channels,
out_channels=out_channels,
args=args,
bias=False,
degree=degree)
self.norm = BatchNormData(in_channels=out_channels)
def forward(self, data: Data) -> torch.Tensor:
data = self.conv(data)
data = self.norm(data)
data.x = self.activation(data.x)
return data
class ConvBlockWithSkip(torch.nn.Module):
def __init__(self, in_channel: int, out_channel: int, skip_in_channel: int, args) -> None:
super(ConvBlockWithSkip, self).__init__()
self.dim = args.edge_attr_dim
self.conv = MySplineConv(in_channels=in_channel,
out_channels=out_channel,
args=args,
bias=False)
self.activation = getattr(torch.nn.functional, args.activation, torch.nn.functional.elu)
self.norm = BatchNormData(in_channels=out_channel)
self.lin = Linear(skip_in_channel, out_channel, bias=False)
self.norm_skip = BatchNormData(in_channels=out_channel)
def forward(self, data: Data, data_skip: Data):
data = self.conv(data)
data_skip = self.lin(data_skip)
data_skip = self.norm_skip(data_skip)
data = self.norm(data)
data.x = self.activation(data.x + data_skip.x)
return data
class Layer(torch.nn.Module):
def __init__(self, in_channels: int, out_channels: int, args) -> None:
super(Layer, self).__init__()
self.in_channel = in_channels
self.out_channel = out_channels
self.conv_block1 = ConvBlock(in_channels, out_channels, args)
self.conv_block2 = ConvBlockWithSkip(out_channels, out_channels, in_channels, args=args)
def forward(self, data: Data) -> torch.Tensor:
data_skip = shallow_copy(data)
data = self.conv_block1(data)
output = self.conv_block2(data, data_skip)
return output
================================================
FILE: src/dagr/model/layers/ev_tgn.py
================================================
import torch
from torch_geometric.data import Batch, Data
from dagr.graph.ev_graph import SlidingWindowGraph
def _get_value_as_int(obj, key):
val = getattr(obj, key)
return val if type(val) is int else val[0]
def denormalize_pos(events):
if hasattr(events, "pos_denorm"):
return events.pos_denorm
denorm = torch.tensor([int(events.width[0]), int(events.height[0]), int(events.time_window[0])], device=events.pos.device)
return (denorm.view(1,-1) * events.pos + 1e-3).int()
class EV_TGN(torch.nn.Module):
def __init__(self, args):
torch.nn.Module.__init__(self)
self.radius = args.radius
self.max_neighbors = args.max_neighbors
self.max_queue_size = 128
self.graph_creators = None
def init_graph_creator(self, data):
delta_t_us = int(self.radius * _get_value_as_int(data, "time_window"))
radius = int(self.radius * _get_value_as_int(data, "width")+1)
batch_size = data.num_graphs
width = int(_get_value_as_int(data, "width"))
height = int(_get_value_as_int(data, "height"))
self.graph_creators = SlidingWindowGraph(width=width, height=height,
max_num_neighbors=self.max_neighbors,
max_queue_size=self.max_queue_size,
batch_size=batch_size,
radius=radius, delta_t_us=delta_t_us)
def forward(self, events: Data, reset=True):
if events.batch is None:
events = Batch.from_data_list([events])
# before we start, are the new events used to generate the graph, or are the new nodes attached to the network?
# if the first, then don't delete old events, if the second, delete as many events as are coming in.
if self.graph_creators is None:
self.init_graph_creator(events)
else:
if reset:
self.graph_creators.reset()
pos = denormalize_pos(events)
#pos = torch.cat([events.batch.view(-1,1), pos, events.x.int()], dim=1).int()
# properties of the edges
# src_i <= dst_i
# dst_i <= dst_j if i<j
events.edge_index = self.graph_creators.forward(events.batch.int(), pos, delete_nodes=False, collect_edges=reset)
events.edge_index = events.edge_index.long()
return events
================================================
FILE: src/dagr/model/layers/pooling.py
================================================
import torch
import torch_scatter
from torch_cluster import grid_cluster
from torch_geometric.nn.pool.avg_pool import _avg_pool_x
from torch_geometric.nn.pool.pool import pool_pos
from torch_geometric.data import Data, Batch
from dagr.model.layers.components import BatchNormData
from typing import List, Callable
def consecutive_cluster(src):
unique, inv, counts = torch.unique(src, sorted=True, return_inverse=True, return_counts=True)
perm = torch.arange(inv.size(0), dtype=inv.dtype, device=inv.device)
perm = inv.new_empty(unique.size(0)).scatter_(0, inv, perm)
return unique, inv, perm, counts
class Pooling(torch.nn.Module):
def __init__(self, si
gitextract_6_j6wcbc/
├── .gitignore
├── LICENSE
├── config/
│ ├── dagr-l-dsec.yaml
│ ├── dagr-l-ncaltech.yaml
│ ├── dagr-m-dsec.yaml
│ ├── dagr-n-dsec.yaml
│ └── dagr-s-dsec.yaml
├── download_and_install_dependencies.sh
├── download_example_data.sh
├── install_env.sh
├── readme.md
├── scripts/
│ ├── check_dataset.py
│ ├── count_flops.py
│ ├── downsample_all_events.sh
│ ├── downsample_events.py
│ ├── run_test.py
│ ├── run_test_interframe.py
│ ├── train_dsec.py
│ ├── train_ncaltech101.py
│ └── visualize_detections.py
├── setup.py
└── src/
└── dagr/
├── asynchronous/
│ ├── __init__.py
│ ├── asy_tools/
│ │ └── main.cu
│ ├── base/
│ │ ├── __init__.py
│ │ ├── base.py
│ │ └── utils.py
│ ├── batch_norm.py
│ ├── cartesian.py
│ ├── conv.py
│ ├── evaluate_flops.py
│ ├── flops/
│ │ ├── __init__.py
│ │ └── conv.py
│ ├── linear.py
│ └── max_pool.py
├── data/
│ ├── augment.py
│ ├── dsec_data.py
│ ├── dsec_split.yaml
│ ├── dsec_utils.py
│ ├── ncaltech101_data.py
│ └── utils.py
├── graph/
│ ├── ev_graph.cu
│ ├── ev_graph.py
│ ├── spiral.h
│ └── utils.py
├── model/
│ ├── layers/
│ │ ├── components.py
│ │ ├── conv.py
│ │ ├── ev_tgn.py
│ │ ├── pooling.py
│ │ └── spline_conv.py
│ ├── networks/
│ │ ├── dagr.py
│ │ ├── ema.py
│ │ ├── net.py
│ │ └── net_img.py
│ └── utils.py
├── utils/
│ ├── args.py
│ ├── buffers.py
│ ├── coco_eval.py
│ ├── learning_rate_scheduler.py
│ ├── logging.py
│ └── testing.py
└── visualization/
├── bbox_viz.py
└── event_viz.py
SYMBOL INDEX (306 symbols across 41 files)
FILE: scripts/downsample_events.py
function _compression_opts (line 15) | def _compression_opts():
function create_ms_to_idx (line 36) | def create_ms_to_idx(t_us):
class H5Writer (line 44) | class H5Writer:
method __init__ (line 45) | def __init__(self, outfile):
method create_ms_to_idx (line 63) | def create_ms_to_idx(self):
method close_callback (line 68) | def close_callback(h5f: h5py.File):
method add_data (line 71) | def add_data(self, events):
function downsample_events (line 91) | def downsample_events(events, input_height, input_width, output_height, ...
function _filter_events_resize (line 110) | def _filter_events_resize(x, y, p, mask, change_map, fx, fy):
FILE: scripts/run_test_interframe.py
function to_npy (line 21) | def to_npy(detections):
function save_detections (line 34) | def save_detections(directory, detections):
FILE: scripts/train_dsec.py
function gradients_broken (line 26) | def gradients_broken(model):
function fix_gradients (line 36) | def fix_gradients(model):
function train (line 42) | def train(loader: DataLoader,
function run_test (line 77) | def run_test(loader: DataLoader,
FILE: scripts/train_ncaltech101.py
function gradients_broken (line 25) | def gradients_broken(model):
function fix_gradients (line 35) | def fix_gradients(model):
function train (line 41) | def train(loader: DataLoader,
function run_test (line 76) | def run_test(loader: DataLoader,
FILE: src/dagr/asynchronous/__init__.py
function is_data_or_data_list (line 27) | def is_data_or_data_list(ann):
function make_model_synchronous (line 30) | def make_model_synchronous(module: torch.nn.Module):
function make_model_asynchronous (line 41) | def make_model_asynchronous(module, log_flops: bool = False):
FILE: src/dagr/asynchronous/base/base.py
function add_async_graph (line 5) | def add_async_graph(module, log_flops: bool = False):
function make_asynchronous (line 11) | def make_asynchronous(module, initialization_func, processing_func):
function async_context (line 22) | def async_context(module, initialization_func, processing_func):
FILE: src/dagr/asynchronous/base/utils.py
function _efficient_cat (line 7) | def _efficient_cat(data_list):
function _efficient_cat_unique (line 13) | def _efficient_cat_unique(data_list):
function _to_hom (line 23) | def _to_hom(x, ones=None):
function _from_hom (line 30) | def _from_hom(x):
function graph_new_nodes (line 33) | def graph_new_nodes(old_data, new_data):
function graph_changed_nodes (line 36) | def graph_changed_nodes(old_data, new_data) -> Tuple[torch.Tensor, torch...
function torch_isin (line 47) | def torch_isin(query, database):
function __remove_duplicate_from_A (line 53) | def __remove_duplicate_from_A(a, b):
FILE: src/dagr/asynchronous/batch_norm.py
function __sync_forward (line 9) | def __sync_forward(m, x):
function __graph_initialization (line 13) | def __graph_initialization(module: BatchNorm, data) -> torch.Tensor:
function __graph_processing (line 25) | def __graph_processing(module: BatchNorm, data) -> torch.Tensor:
function __check_support (line 58) | def __check_support(module):
function make_batch_norm_asynchronous (line 62) | def make_batch_norm_asynchronous(module: BatchNorm, log_flops: bool = Fa...
FILE: src/dagr/asynchronous/cartesian.py
function __edge_attr (line 6) | def __edge_attr(pos, edge_index, norm, max):
function __graph_initialization (line 19) | def __graph_initialization(module: BatchNorm, data) -> torch.Tensor:
function __graph_processing (line 32) | def __graph_processing(module: BatchNorm, data) -> torch.Tensor:
function __check_support (line 57) | def __check_support(module):
function make_cartesian_asynchronous (line 61) | def make_cartesian_asynchronous(module: BatchNorm, log_flops: bool = Fal...
FILE: src/dagr/asynchronous/conv.py
function __conv (line 11) | def __conv(x, edge_index, edge_attr, mask, nn):
function __graph_initialization (line 28) | def __graph_initialization(module, data, *args, **kwargs):
function __edges_with_src_node (line 60) | def __edges_with_src_node(node_idx, edge_index, edge_attr=None, node_idx...
function find_only_x (line 91) | def find_only_x(idx_new_comp, idx_diff, pos_idx_diff, edge):
function __graph_processing (line 94) | def __graph_processing(module, data, *args, **kwargs):
function generalized_lin (line 229) | def generalized_lin(module, input, output, idx):
function __check_support (line 240) | def __check_support(module) -> bool:
function make_conv_asynchronous (line 247) | def make_conv_asynchronous(module, log_flops: bool = False):
FILE: src/dagr/asynchronous/evaluate_flops.py
function split_data (line 10) | def split_data(data: Data, index: int)->Tuple[Data, Data]:
function forward_hook (line 25) | def forward_hook(inst, inp, out):
function _mask_if_possible (line 62) | def _mask_if_possible(data):
function denorm (line 76) | def denorm(data):
function evaluate_flops (line 82) | def evaluate_flops(model: torch.nn.Module, batch: Data, dense=False,
function _filter_non_leaf_nodes (line 167) | def _filter_non_leaf_nodes(flops_per_layer: OrderedDict)->OrderedDict:
function _merge_to_level_flops (line 178) | def _merge_to_level_flops(flops_per_layer: OrderedDict, level=2)->Ordere...
function _merge_list_flops (line 192) | def _merge_list_flops(flops_per_layer_batch: List[OrderedDict])->Ordered...
function _summary (line 195) | def _summary(est, gt, prefix):
function max_rel_diff (line 206) | def max_rel_diff(x, y, threshold=None):
function error_above_threshold (line 209) | def error_above_threshold(error, mag, threshold):
function max_abs_diff (line 217) | def max_abs_diff(x, y, threshold=None, alpha=0):
function _print_summary_for_one (line 221) | def _print_summary_for_one(target, estimate, prefix=""):
function print_summary_of_module (line 236) | def print_summary_of_module(activations, runs=[0,2]):
function test_and_compare_activations (line 240) | def test_and_compare_activations(model, runs=[0,2]):
FILE: src/dagr/asynchronous/flops/__init__.py
function compute_flops_from_module (line 7) | def compute_flops_from_module(module) -> int:
FILE: src/dagr/asynchronous/flops/conv.py
function compute_flops_conv (line 4) | def compute_flops_conv(module: torch.nn.Module, num_times_apply_bias_and...
function compute_flops_cat (line 27) | def compute_flops_cat(module, num_edges, num_times_apply_bias_and_root, ...
FILE: src/dagr/asynchronous/linear.py
function __graph_initialization (line 12) | def __graph_initialization(module: Linear, data) -> torch.Tensor:
function __graph_processing (line 32) | def __graph_processing(module: Linear, data) -> torch.Tensor:
function __check_support (line 69) | def __check_support(module: Linear):
function make_linear_asynchronous (line 73) | def make_linear_asynchronous(module: Linear, log_flops: bool = False):
FILE: src/dagr/asynchronous/max_pool.py
function pool_edge (line 13) | def pool_edge(cluster, edge_index, self_loop):
function compute_attrs (line 25) | def compute_attrs(transform, edge_index, pos):
function __dense_process (line 29) | def __dense_process(module, data: Data, *args, **kwargs) -> Data:
function __graph_initialization (line 95) | def __graph_initialization(module, data: Data, *args, **kwargs) -> Data:
function __graph_process (line 123) | def __graph_process(module, data, *args, **kwargs) -> Data:
function __get_global_cluster_index (line 245) | def __get_global_cluster_index(module, pos) -> torch.LongTensor:
function make_max_pool_asynchronous (line 255) | def make_max_pool_asynchronous(module, log_flops: bool = False):
FILE: src/dagr/data/augment.py
function _add_event (line 14) | def _add_event(x, y, xlim, ylim, p, i, count, pos, mask, threshold=1):
function _subsample (line 27) | def _subsample(pos: np.ndarray, polarity: np.ndarray, mask: np.ndarray, ...
function _crop_events (line 39) | def _crop_events(data, left, right, not_crop_idx=None):
function _crop_image (line 51) | def _crop_image(image, left, right):
function _resize_image (line 60) | def _resize_image(image, height, width, bg=None):
function _crop_bbox (line 78) | def _crop_bbox(bbox: torch.Tensor, left: torch.Tensor, right: torch.Tens...
function _scale_and_clip (line 86) | def _scale_and_clip(x, scale):
class RandomHFlip (line 90) | class RandomHFlip(BaseTransform):
method __init__ (line 91) | def __init__(self, p: float):
method __call__ (line 94) | def __call__(self, data: Data):
class Crop (line 115) | class Crop(BaseTransform):
method __init__ (line 122) | def __init__(self, min: List[float], max: List[float]):
method init (line 126) | def init(self, height, width):
method __call__ (line 131) | def __call__(self, data: Data):
class RandomZoom (line 147) | class RandomZoom(BaseTransform):
method __init__ (line 148) | def __init__(self, zoom, subsample=False):
method _subsample (line 156) | def _subsample(self, data, zoom, count):
method init (line 169) | def init(self, height, width):
method __call__ (line 173) | def __call__(self, data):
class RandomCrop (line 200) | class RandomCrop(BaseTransform):
method __init__ (line 208) | def __init__(self, size: List[float] = [0.75, 0.75], dim: List[int]=[0...
method init (line 213) | def init(self, height, width):
method __call__ (line 218) | def __call__(self, data: Data):
class RandomTranslate (line 240) | class RandomTranslate(BaseTransform):
method __init__ (line 247) | def __init__(self, size: List[float]):
method init (line 251) | def init(self, height, width):
method pad (line 256) | def pad(self, image, bg):
method __call__ (line 262) | def __call__(self, data: Data):
class Augmentations (line 282) | class Augmentations:
method __init__ (line 287) | def __init__(self, args):
function init_transforms (line 296) | def init_transforms(transforms, height, width):
FILE: src/dagr/data/dsec_data.py
function tracks_to_array (line 24) | def tracks_to_array(tracks):
function interpolate_tracks (line 29) | def interpolate_tracks(detections_0, detections_1, t):
class EventDirectory (line 50) | class EventDirectory(BaseDirectory):
method event_file (line 53) | def event_file(self):
class DSEC (line 57) | class DSEC(Dataset):
method __init__ (line 60) | def __init__(self,
method set_num_us (line 114) | def set_num_us(self, num_us):
method visualize_debug (line 117) | def visualize_debug(self, index):
method __len__ (line 132) | def __len__(self):
method preprocess_detections (line 135) | def preprocess_detections(self, detections):
method preprocess_events (line 141) | def preprocess_events(self, events):
method preprocess_image (line 149) | def preprocess_image(self, image):
method __getitem__ (line 156) | def __getitem__(self, idx):
method rel_index (line 197) | def rel_index(self, idx):
FILE: src/dagr/data/dsec_utils.py
function construct_pairs (line 5) | def construct_pairs(indices, n=2):
function rescale_tracks (line 14) | def rescale_tracks(tracks, scale):
function crop_tracks (line 20) | def crop_tracks(tracks, width, height):
function map_classes (line 38) | def map_classes(class_ids, old_to_new_mapping):
function filter_small_bboxes (line 43) | def filter_small_bboxes(w, h, bbox_height=20, bbox_diag=30):
function filter_tracks (line 50) | def filter_tracks(dataset, image_width, image_height, class_remapping, m...
function _load_events (line 80) | def _load_events(file, t0, num_events=None, num_us=None, height=None, ti...
function filter_by_only_perfect_tracks (line 123) | def filter_by_only_perfect_tracks(tracks, img_idx_to_track_idx, tracks_m...
function is_invalid_track (line 134) | def is_invalid_track(track):
function compute_iou (line 150) | def compute_iou(track0, track1):
function compute_indices_for_contiguous_parts (line 172) | def compute_indices_for_contiguous_parts(x):
function _compute_img_idx_to_track_idx (line 177) | def _compute_img_idx_to_track_idx(t, t_query):
function compute_img_idx_to_track_idx (line 183) | def compute_img_idx_to_track_idx(t, t_query):
function compute_class_mapping (line 186) | def compute_class_mapping(classes, all_classes, mapping):
FILE: src/dagr/data/ncaltech101_data.py
class NCaltech101 (line 14) | class NCaltech101(Dataset):
method __init__ (line 16) | def __init__(self, root: Path, split, transform=Optional[Callable[[Dat...
method __len__ (line 30) | def __len__(self):
method preprocess (line 33) | def preprocess(self, data):
method load_events (line 37) | def load_events(self, f_path):
method __getitem__ (line 40) | def __getitem__(self, idx):
method load_bboxes (line 59) | def load_bboxes(self, raw_file: Path, class_id):
function _load_events (line 75) | def _load_events(f_path, num_events):
FILE: src/dagr/data/utils.py
function to_data (line 6) | def to_data(**kwargs):
FILE: src/dagr/graph/ev_graph.py
function move_to_cuda (line 5) | def move_to_cuda(func):
class AsyncGraph (line 18) | class AsyncGraph:
method __init__ (line 19) | def __init__(self, width=640,
method initialize (line 45) | def initialize(self, n_ev, device):
method reset (line 52) | def reset(self):
method forward (line 63) | def forward(self, batch, pos, collect_edges=True):
class SlidingWindowGraph (line 106) | class SlidingWindowGraph(AsyncGraph):
method __init__ (line 107) | def __init__(self, width=640,
method init (line 118) | def init(self):
method delete_nodes (line 121) | def delete_nodes(self, n_delete, delete_edges=True, return_edges=True):
method forward (line 139) | def forward(self, batch, pos, return_node_counts=False, return_total_e...
FILE: src/dagr/graph/spiral.h
function class (line 1) | class SpiralOut{
FILE: src/dagr/graph/utils.py
function _insert_events_into_queue (line 6) | def _insert_events_into_queue(batch, pos, indices, queue: torch.LongTens...
function _search_for_edges (line 20) | def _search_for_edges(batch, pos, all_timestamps, queue, indices, max_nu...
FILE: src/dagr/model/layers/components.py
class BatchNormData (line 9) | class BatchNormData(BatchNorm):
method forward (line 10) | def forward(self, data: Data):
class Linear (line 15) | class Linear(torch.nn.Module):
method __init__ (line 16) | def __init__(self, ic, oc, bias=True):
method forward (line 20) | def forward(self, data: Data):
class Cartesian (line 25) | class Cartesian(torch.nn.Module):
method __init__ (line 26) | def __init__(self, *args, **kwargs):
method forward (line 30) | def forward(self, data):
FILE: src/dagr/model/layers/conv.py
class ConvBlock (line 10) | class ConvBlock(torch.nn.Module):
method __init__ (line 11) | def __init__(self, in_channels: int, out_channels: int, args, degree=1...
method forward (line 23) | def forward(self, data: Data) -> torch.Tensor:
class ConvBlockWithSkip (line 31) | class ConvBlockWithSkip(torch.nn.Module):
method __init__ (line 32) | def __init__(self, in_channel: int, out_channel: int, skip_in_channel:...
method forward (line 47) | def forward(self, data: Data, data_skip: Data):
class Layer (line 59) | class Layer(torch.nn.Module):
method __init__ (line 60) | def __init__(self, in_channels: int, out_channels: int, args) -> None:
method forward (line 68) | def forward(self, data: Data) -> torch.Tensor:
FILE: src/dagr/model/layers/ev_tgn.py
function _get_value_as_int (line 7) | def _get_value_as_int(obj, key):
function denormalize_pos (line 11) | def denormalize_pos(events):
class EV_TGN (line 19) | class EV_TGN(torch.nn.Module):
method __init__ (line 20) | def __init__(self, args):
method init_graph_creator (line 27) | def init_graph_creator(self, data):
method forward (line 39) | def forward(self, events: Data, reset=True):
FILE: src/dagr/model/layers/pooling.py
function consecutive_cluster (line 12) | def consecutive_cluster(src):
class Pooling (line 19) | class Pooling(torch.nn.Module):
method __init__ (line 20) | def __init__(self, size: List[float], width, height, batch_size, trans...
method num_grid_cells (line 44) | def num_grid_cells(self):
method round_to_pixel (line 47) | def round_to_pixel(self, pos, wh_inv):
method forward (line 51) | def forward(self, data: Data):
FILE: src/dagr/model/layers/spline_conv.py
class MySplineConv (line 9) | class MySplineConv(SplineConv):
method __init__ (line 10) | def __init__(self, in_channels, out_channels, args, bias=False, degree...
method init_lut (line 16) | def init_lut(self, height, width, rx=None, Mx=None, ry=None, My=None):
method message_lut (line 39) | def message_lut(self, x_j, edge_attr):
method forward (line 49) | def forward(self, data: Data)->Data:
method _forward (line 64) | def _forward(self, x, edge_index, edge_attr=None, size=None):
function to_dense (line 80) | def to_dense(self, x, pos, pooling, batch=None, batch_size=None):
class SplineConvToDense (line 110) | class SplineConvToDense(MySplineConv):
method forward (line 111) | def forward(self, data: Data, batch_size: int=None)->torch.Tensor:
method to_dense (line 117) | def to_dense(self, x, pos, pooling, batch=None, batch_size=None):
FILE: src/dagr/model/networks/dagr.py
class DAGR (line 14) | class DAGR(YOLOX):
method __init__ (line 15) | def __init__(self, args, height, width):
method cache_luts (line 37) | def cache_luts(self, width, height, radius):
method forward (line 74) | def forward(self, x: Data, reset=True, return_targets=True, filtering=...
class CNNHead (line 106) | class CNNHead(YOLOXHead):
method forward (line 107) | def forward(self, xin):
class GNNHead (line 125) | class GNNHead(YOLOXHead):
method __init__ (line 126) | def __init__(
method process_feature (line 179) | def process_feature(self, x, stem, cls_conv, reg_conv, cls_pred, reg_p...
method forward (line 192) | def forward(self, xin: Data, labels=None, imgs=None):
method collect_outputs (line 292) | def collect_outputs(self, cls_output, reg_output, obj_output, k, strid...
method decode_outputs (line 306) | def decode_outputs(self, outputs, dtype):
FILE: src/dagr/model/networks/ema.py
class ModelEMA (line 6) | class ModelEMA:
method __init__ (line 17) | def __init__(self, model, decay=0.9999, updates=0):
method update (line 41) | def update(self, model):
FILE: src/dagr/model/networks/net.py
function sampling_skip (line 15) | def sampling_skip(data, image_feat):
function compute_pooling_at_each_layer (line 19) | def compute_pooling_at_each_layer(pooling_dim_at_output, num_layers):
class Net (line 31) | class Net(torch.nn.Module):
method __init__ (line 32) | def __init__(self, args, height, width):
method get_output_sizes (line 103) | def get_output_sizes(self):
method forward (line 108) | def forward(self, data: Data, reset=True):
function sample_features (line 193) | def sample_features(data, image_feat, image_sample_mode="bilinear"):
function _sample_features (line 204) | def _sample_features(x, y, b, image_feat, width, height, batch_size, ima...
FILE: src/dagr/model/networks/net_img.py
class Layer (line 4) | class Layer(torch.nn.Module):
method __init__ (line 5) | def __init__(self, input_channels, output_channels):
method forward (line 17) | def forward(self, x):
class ConvBlockDense (line 25) | class ConvBlockDense(torch.nn.Module):
method __init__ (line 26) | def __init__(self, in_channels, out_channels, bias=False, act=torch.nn...
method forward (line 33) | def forward(self, x):
class HookModule (line 42) | class HookModule(torch.nn.Module):
method __init__ (line 48) | def __init__(self, module, height, width, input_channels=3, feature_la...
method extract_layer (line 92) | def extract_layer(self, module, layer):
method compute_channels_with_dummy (line 98) | def compute_channels_with_dummy(self, shape):
method remove_hooks (line 106) | def remove_hooks(self):
method register_hooks (line 110) | def register_hooks(self):
method forward (line 122) | def forward(self, x):
FILE: src/dagr/model/utils.py
function init_subnetwork (line 9) | def init_subnetwork(net, state_dict, name="backbone.net.", freeze=False):
function batched_nms_coordinate_trick (line 25) | def batched_nms_coordinate_trick(boxes, scores, idxs, iou_threshold, wid...
function convert_to_evaluation_format (line 35) | def convert_to_evaluation_format(data):
function convert_to_training_format (line 46) | def convert_to_training_format(bbox, batch, batch_size):
function postprocess_network_output (line 61) | def postprocess_network_output(prediction, num_classes, conf_thre=0.01, ...
function voxel_size_to_params (line 112) | def voxel_size_to_params(pooling_layer, height, width):
function init_grid_and_stride (line 119) | def init_grid_and_stride(hw, strides, dtype):
function _sequential_counter (line 134) | def _sequential_counter(counts: torch.LongTensor):
function shallow_copy (line 158) | def shallow_copy(data):
FILE: src/dagr/utils/args.py
function BASE_FLAGS (line 7) | def BASE_FLAGS():
function FLAGS (line 54) | def FLAGS():
function FLOPS_FLAGS (line 82) | def FLOPS_FLAGS():
function parse_config (line 104) | def parse_config(args: argparse.ArgumentParser, config: Path):
FILE: src/dagr/utils/buffers.py
function diag_filter (line 10) | def diag_filter(bbox, height: int, width: int, min_box_diagonal: int = 3...
function filter_bboxes (line 19) | def filter_bboxes(detections: List[Dict[str, torch.Tensor]], height: int...
function format_data (line 33) | def format_data(data, normalizer=None):
function bbox_t_to_ndarray (line 46) | def bbox_t_to_ndarray(bbox, t):
function compile (line 68) | def compile(detections, sequences, timestamps):
function to_cpu (line 80) | def to_cpu(data_list: List[Dict[str, torch.Tensor]]):
class Buffer (line 83) | class Buffer:
method __init__ (line 84) | def __init__(self):
method extend (line 87) | def extend(self, elements: List[Dict[str, torch.Tensor]]):
method clear (line 90) | def clear(self):
method __iter__ (line 93) | def __iter__(self):
method __next__ (line 96) | def __next__(self):
class DetectionBuffer (line 101) | class DetectionBuffer:
method __init__ (line 102) | def __init__(self, height: int, width: int, classes: List[str]):
method compile (line 109) | def compile(self, sequences, timestamps):
method update (line 114) | def update(self, detections: List[Dict[str, torch.Tensor]], groundtrut...
method compute (line 118) | def compute(self)->Dict[str, float]:
class DictBuffer (line 126) | class DictBuffer:
method __init__ (line 127) | def __init__(self):
method __recursive_mean (line 131) | def __recursive_mean(self, mn: float, s: float):
method update (line 134) | def update(self, dictionary: Dict[str, float]):
method save (line 141) | def save(self, path):
method compute (line 144) | def compute(self)->Dict[str, float]:
FILE: src/dagr/utils/coco_eval.py
function _convert_to_coco_format (line 17) | def _convert_to_coco_format(gt_boxes_list: List[Dict[str, Tensor]],
function evaluate_detection (line 64) | def evaluate_detection(gt_boxes_list: List[Dict[str, Tensor]],
function _to_prophesee (line 96) | def _to_prophesee(det: Dict[str, Tensor]):
function _match_times (line 109) | def _match_times(all_ts, gt_boxes, dt_boxes, time_tol):
function _coco_eval (line 147) | def _coco_eval(dataset, results, num_gts):
function _to_coco_format (line 181) | def _to_coco_format(gts, detections, categories, height=240, width=304):
FILE: src/dagr/utils/learning_rate_scheduler.py
class LRSchedule (line 8) | class LRSchedule:
method __init__ (line 9) | def __init__(self,
method __call__ (line 23) | def __call__(self, *args, **kwargs)->float:
function _yolox_warm_cos_lr (line 27) | def _yolox_warm_cos_lr(
FILE: src/dagr/utils/logging.py
class Checkpointer (line 14) | class Checkpointer:
method __init__ (line 15) | def __init__(self, output_directory: Optional[Path] = None, args=None,...
method restore_if_existing (line 25) | def restore_if_existing(self, folder, resume_from_best=False):
method mAP_from_checkpoint_name (line 31) | def mAP_from_checkpoint_name(self, checkpoint_name: Path):
method search_for_checkpoint (line 34) | def search_for_checkpoint(self, resume_checkpoint: Path, best=False):
method restore_if_not_none (line 51) | def restore_if_not_none(self, target, source):
method restore_checkpoint (line 55) | def restore_checkpoint(self, checkpoint_directory, best=False):
method fix_checkpoint (line 72) | def fix_checkpoint(self, state_dict):
method checkpoint (line 75) | def checkpoint(self, epoch: int, name: str=""):
method process (line 90) | def process(self, data: Dict[str, float], epoch: int):
function set_up_logging_directory (line 101) | def set_up_logging_directory(dataset, task, output_directory, exp_name="...
function log_hparams (line 114) | def log_hparams(args):
function log_bboxes (line 119) | def log_bboxes(data: Batch,
function visualize_events (line 169) | def visualize_events(data: Data)->torch.Tensor:
function __convert_to_wandb_data (line 184) | def __convert_to_wandb_data(image: torch.Tensor, gt: torch.Tensor, p: to...
function __parse_bboxes (line 190) | def __parse_bboxes(bboxes: torch.Tensor, class_names: List[str], suffix:...
function __parse_bbox (line 197) | def __parse_bbox(bbox: torch.Tensor, class_names: List[str], suffix: str...
FILE: src/dagr/utils/testing.py
function to_npy (line 6) | def to_npy(detections):
function format_detections (line 9) | def format_detections(sequences, t, detections):
function run_test_with_visualization (line 16) | def run_test_with_visualization(loader, model, dataset: str, log_every_n...
FILE: src/dagr/visualization/bbox_viz.py
function draw_bbox_on_img (line 11) | def draw_bbox_on_img(img, x, y, w, h, labels, scores=None, conf=0.5, nms...
function filter_boxes (line 56) | def filter_boxes(x, y, w, h, labels, scores, conf, nms):
FILE: src/dagr/visualization/event_viz.py
function draw_events_on_image (line 4) | def draw_events_on_image(img, x, y, p, alpha=0.5):
Condensed preview — 62 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (281K chars).
[
{
"path": ".gitignore",
"chars": 43,
"preview": "*.so\n*.egg-info/\n*.pyc\nbuild/\nlibs/\n.idea/\n"
},
{
"path": "LICENSE",
"chars": 35149,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "config/dagr-l-dsec.yaml",
"chars": 598,
"preview": "dataset_directory: \"/data/storage/daniel/aegnn/\"\noutput_directory: \"/data/storage/daniel/aegnn/logs\"\n\ntask: detection\nda"
},
{
"path": "config/dagr-l-ncaltech.yaml",
"chars": 531,
"preview": "path: \"/data/storage/daniel/aegnn\"\noutput_directory: \"/data/storage/daniel/aegnn/logs\"\npooling_dim_at_output: 5x7\n\ntask:"
},
{
"path": "config/dagr-m-dsec.yaml",
"chars": 604,
"preview": "dataset_directory: \"/data/storage/daniel/aegnn/\"\noutput_directory: \"/data/storage/daniel/aegnn/logs\"\n\ntask: detection\nda"
},
{
"path": "config/dagr-n-dsec.yaml",
"chars": 604,
"preview": "dataset_directory: \"/data/storage/daniel/aegnn/\"\noutput_directory: \"/data/storage/daniel/aegnn/logs\"\n\ntask: detection\nda"
},
{
"path": "config/dagr-s-dsec.yaml",
"chars": 601,
"preview": "dataset_directory: \"/data/storage/daniel/aegnn/\"\noutput_directory: \"/data/storage/daniel/aegnn/logs\"\n\ntask: detection\nda"
},
{
"path": "download_and_install_dependencies.sh",
"chars": 779,
"preview": "#! /usr/bin/env bash\nDAGR_DIR=$(pwd)\n\n# Download detectron2 for its fast mAP calculation function\nmkdir $DAGR_DIR/libs\nc"
},
{
"path": "download_example_data.sh",
"chars": 344,
"preview": "#! /usr/bin/env bash\nDAGR_DIR=$(pwd)\nDATA_DIR=$DAGR_DIR/data\n\nmkdir $DATA_DIR\nwget https://download.ifi.uzh.ch/rpg/dagr/"
},
{
"path": "install_env.sh",
"chars": 543,
"preview": "#! /usr/bin/env bash\n\nTORCH=$(python -c \"import torch; print(torch.__version__)\")\nCUDA=$(python -c \"import torch; print("
},
{
"path": "readme.md",
"chars": 8879,
"preview": "# Low Latency Automotive Vision with Event Cameras\n\n<p align=\"center\">\n<a href=\"https://youtu.be/dwzGhMQCc4Y\">\n <img sr"
},
{
"path": "scripts/check_dataset.py",
"chars": 0,
"preview": ""
},
{
"path": "scripts/count_flops.py",
"chars": 2417,
"preview": "import os\nimport tqdm\nimport torch\nos.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\n\nfrom torch_geometric.data import Data"
},
{
"path": "scripts/downsample_all_events.sh",
"chars": 298,
"preview": "#!/bin/bash\n\nDSEC_ROOT=$1\nfor split in train test; do\n for sequence in $DSEC_ROOT/$split/*/; do\n infile=$seque"
},
{
"path": "scripts/downsample_events.py",
"chars": 6713,
"preview": "import argparse\nimport tqdm\nimport hdf5plugin\nimport h5py\nimport weakref\nimport numba\n\nimport numpy as np\n\nfrom pathlib "
},
{
"path": "scripts/run_test.py",
"chars": 2155,
"preview": "# avoid matlab error on server\nimport os\nimport torch\nimport wandb\nos.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\n\nfrom "
},
{
"path": "scripts/run_test_interframe.py",
"chars": 3533,
"preview": "import torch\nimport tqdm\nimport wandb\nimport os\nos.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\n\nfrom torch_geometric.dat"
},
{
"path": "scripts/train_dsec.py",
"chars": 6255,
"preview": "# avoid matlab error on server\nimport os\nos.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\n\nimport torch\nimport tqdm\nimport"
},
{
"path": "scripts/train_ncaltech101.py",
"chars": 6150,
"preview": "# avoid matlab error on server\nimport os\nos.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\n\nimport torch\nimport tqdm\nimport"
},
{
"path": "scripts/visualize_detections.py",
"chars": 3827,
"preview": "import cv2\nimport argparse\n\nfrom pathlib import Path\nimport numpy as np\n\nfrom dsec_det.directory import DSECDirectory\nfr"
},
{
"path": "setup.py",
"chars": 483,
"preview": "from distutils.core import setup\nfrom torch.utils.cpp_extension import BuildExtension, CUDAExtension\n\nsetup(\n name='d"
},
{
"path": "src/dagr/asynchronous/__init__.py",
"chars": 4327,
"preview": "import logging\n\nimport torch.nn\nimport torch_geometric\nimport inspect\n\nfrom torch.nn import ModuleList\n\nfrom .conv impor"
},
{
"path": "src/dagr/asynchronous/asy_tools/main.cu",
"chars": 6330,
"preview": "#include <torch/extension.h>\n\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <vector>\n\n\n#define CHECK_CUDA(x) AT_A"
},
{
"path": "src/dagr/asynchronous/base/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "src/dagr/asynchronous/base/base.py",
"chars": 888,
"preview": "from contextlib import contextmanager\nimport logging\n\n\ndef add_async_graph(module, log_flops: bool = False):\n module."
},
{
"path": "src/dagr/asynchronous/base/utils.py",
"chars": 1976,
"preview": "import torch\n\nfrom typing import Tuple\nimport asy_tools\n\n\ndef _efficient_cat(data_list):\n data_list = [d for d in dat"
},
{
"path": "src/dagr/asynchronous/batch_norm.py",
"chars": 3083,
"preview": "import torch\nimport asy_tools\nfrom torch_geometric.nn.norm import BatchNorm\nimport torch.nn.functional as F\nfrom .base.b"
},
{
"path": "src/dagr/asynchronous/cartesian.py",
"chars": 2959,
"preview": "import torch\n\nfrom torch_geometric.nn.norm import BatchNorm\nfrom .base.base import make_asynchronous, add_async_graph\n\nd"
},
{
"path": "src/dagr/asynchronous/conv.py",
"chars": 12525,
"preview": "import asy_tools\nimport torch\nimport torch_geometric.nn.conv\n\nfrom .base.base import make_asynchronous, add_async_graph\n"
},
{
"path": "src/dagr/asynchronous/evaluate_flops.py",
"chars": 9420,
"preview": "import torch\n\nfrom torch_geometric.data import Batch, Data\nfrom typing import List, Tuple\nfrom collections import Ordere"
},
{
"path": "src/dagr/asynchronous/flops/__init__.py",
"chars": 1333,
"preview": "import logging\nfrom torch.nn import ModuleList\n\nfrom .conv import compute_flops_conv, compute_flops_cat\n\n\ndef compute_fl"
},
{
"path": "src/dagr/asynchronous/flops/conv.py",
"chars": 1214,
"preview": "import torch\n\n\ndef compute_flops_conv(module: torch.nn.Module, num_times_apply_bias_and_root: int, num_edges: int, conca"
},
{
"path": "src/dagr/asynchronous/linear.py",
"chars": 3223,
"preview": "import numpy as np\nimport torch\nimport torch_geometric\nimport asy_tools\n\nfrom torch.nn import Linear\nimport torch.nn.fun"
},
{
"path": "src/dagr/asynchronous/max_pool.py",
"chars": 13392,
"preview": "import logging\nimport torch\n\nfrom torch_geometric.data import Data\nfrom torch_scatter import scatter_max, scatter_sum\n\nf"
},
{
"path": "src/dagr/data/augment.py",
"chars": 9928,
"preview": "import torch\n\nfrom torch_geometric.transforms import BaseTransform\nfrom torch_geometric.data import Data\nfrom typing imp"
},
{
"path": "src/dagr/data/dsec_data.py",
"chars": 8145,
"preview": "from pathlib import Path\nfrom typing import Optional, Callable\n\nfrom torch_geometric.data import Dataset\n\nimport numpy a"
},
{
"path": "src/dagr/data/dsec_split.yaml",
"chars": 1241,
"preview": "train:\n - thun_00_a\n - interlaken_00_c\n - interlaken_00_d\n - interlaken_00_e\n - interlaken_00_f\n - interlaken_00_g"
},
{
"path": "src/dagr/data/dsec_utils.py",
"chars": 6766,
"preview": "import numpy as np\nimport h5py\n\n\ndef construct_pairs(indices, n=2):\n indices = np.sort(indices)\n indices = np.stac"
},
{
"path": "src/dagr/data/ncaltech101_data.py",
"chars": 2865,
"preview": "import numpy as np\nimport torch\nimport hdf5plugin\nimport h5py\n\nfrom pathlib import Path\nfrom typing import Optional, Cal"
},
{
"path": "src/dagr/data/utils.py",
"chars": 535,
"preview": "import numpy as np\nimport torch\nfrom torch_geometric.data import Data\n\n\ndef to_data(**kwargs):\n # convert all tracks "
},
{
"path": "src/dagr/graph/ev_graph.cu",
"chars": 8501,
"preview": "#include <torch/extension.h>\n\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include \"spiral.h\"\n#include <vector>\n\n\n#defin"
},
{
"path": "src/dagr/graph/ev_graph.py",
"chars": 6105,
"preview": "import torch\nfrom .utils import _insert_events_into_queue, _search_for_edges\n\n\ndef move_to_cuda(func):\n def wrapper(s"
},
{
"path": "src/dagr/graph/spiral.h",
"chars": 529,
"preview": "class SpiralOut{\nprotected:\n unsigned layer;\n unsigned leg;\npublic:\n int x, y; //read these as output from next"
},
{
"path": "src/dagr/graph/utils.py",
"chars": 1112,
"preview": "import torch\nimport ev_graph_cuda\nfrom typing import Union\n\n\ndef _insert_events_into_queue(batch, pos, indices, queue: t"
},
{
"path": "src/dagr/model/layers/components.py",
"chars": 938,
"preview": "import torch\n\nfrom torch_geometric.nn import BatchNorm\nfrom torch_geometric.data import Data\n\nimport torch_geometric.tra"
},
{
"path": "src/dagr/model/layers/conv.py",
"chars": 2598,
"preview": "import torch\n\nfrom torch_geometric.data import Data\n\nfrom dagr.model.layers.components import BatchNormData, Linear\nfrom"
},
{
"path": "src/dagr/model/layers/ev_tgn.py",
"chars": 2447,
"preview": "import torch\n\nfrom torch_geometric.data import Batch, Data\nfrom dagr.graph.ev_graph import SlidingWindowGraph\n\n\ndef _get"
},
{
"path": "src/dagr/model/layers/pooling.py",
"chars": 3879,
"preview": "import torch\nimport torch_scatter\n\nfrom torch_cluster import grid_cluster\nfrom torch_geometric.nn.pool.avg_pool import _"
},
{
"path": "src/dagr/model/layers/spline_conv.py",
"chars": 4943,
"preview": "import torch\n\nfrom torch_geometric.nn.conv import SplineConv\nfrom torch_geometric.data import Data\nfrom torch_geometric."
},
{
"path": "src/dagr/model/networks/dagr.py",
"chars": 14575,
"preview": "import torch\n\nimport torch.nn.functional as F\n\nfrom torch_geometric.data import Data\nfrom yolox.models import YOLOX, YOL"
},
{
"path": "src/dagr/model/networks/ema.py",
"chars": 1839,
"preview": "import torch\nimport math\nfrom copy import deepcopy\n\n\nclass ModelEMA:\n \"\"\"\n Model Exponential Moving Average from h"
},
{
"path": "src/dagr/model/networks/net.py",
"chars": 8805,
"preview": "import torch\n\nimport torch_geometric.transforms as T\n\nfrom torch_geometric.data import Data\nfrom dagr.model.layers.ev_tg"
},
{
"path": "src/dagr/model/networks/net_img.py",
"chars": 5281,
"preview": "import torch\n\n\nclass Layer(torch.nn.Module):\n def __init__(self, input_channels, output_channels):\n super(Laye"
},
{
"path": "src/dagr/model/utils.py",
"chars": 6077,
"preview": "import torchvision\nimport torch\n\nimport numpy as np\n\nfrom torch_geometric.data import Data\n\n\ndef init_subnetwork(net, st"
},
{
"path": "src/dagr/utils/args.py",
"chars": 4614,
"preview": "import argparse\nimport yaml\n\nfrom pathlib import Path\n\n\ndef BASE_FLAGS():\n parser = argparse.ArgumentParser(\"\")\n p"
},
{
"path": "src/dagr/utils/buffers.py",
"chars": 4592,
"preview": "import numpy as np\nimport torch\n\nfrom typing import List, Dict\nfrom pathlib import Path\n\nfrom .coco_eval import evaluate"
},
{
"path": "src/dagr/utils/coco_eval.py",
"chars": 8497,
"preview": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n"
},
{
"path": "src/dagr/utils/learning_rate_scheduler.py",
"chars": 1643,
"preview": "from functools import partial\nimport math\nfrom typing import List\n\nimport numpy as np\n\n\nclass LRSchedule:\n def __init"
},
{
"path": "src/dagr/utils/logging.py",
"chars": 7579,
"preview": "import torch\nimport wandb\nimport os\n\nfrom typing import List, Dict, Optional\nfrom torch_geometric.data import Batch\nfrom"
},
{
"path": "src/dagr/utils/testing.py",
"chars": 1879,
"preview": "import torch\nfrom dagr.utils.logging import log_bboxes\nfrom dagr.utils.buffers import DetectionBuffer, format_data\nimpor"
},
{
"path": "src/dagr/visualization/bbox_viz.py",
"chars": 2050,
"preview": "import numpy as np\nimport cv2\nimport torchvision\nimport torch\n\n\n_COLORS = np.array([[0.000, 0.8, 0.1], [1, 0.67, 0.00]])"
},
{
"path": "src/dagr/visualization/event_viz.py",
"chars": 312,
"preview": "import numba\n\n@numba.jit(nopython=True)\ndef draw_events_on_image(img, x, y, p, alpha=0.5):\n img_copy = img.copy()\n "
}
]
About this extraction
This page contains the full source code of the uzh-rpg/dagr GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 62 files (263.1 KB), approximately 67.9k tokens, and a symbol index with 306 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.