diff --git a/.github/ISSUE_TEMPLATE/sweep-template.yml b/.github/ISSUE_TEMPLATE/sweep-template.yml new file mode 100644 index 0000000..44116f5 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/sweep-template.yml @@ -0,0 +1,15 @@ +name: Sweep Issue +title: 'Sweep: ' +description: For small bugs, features, refactors, and tests to be handled by Sweep, an AI-powered junior developer. +labels: sweep +body: + - type: textarea + id: description + attributes: + label: Details + description: Tell Sweep where and what to edit and provide enough context for a new developer to the codebase + placeholder: | + Unit Tests: Write unit tests for . Test each function in the file. Make sure to test edge cases. + Bugs: The bug might be in . Here are the logs: ... + Features: the new endpoint should use the ... class from because it contains ... logic. + Refactors: We are migrating this function to ... version because ... \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0ad25db --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are 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. + + 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. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + 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 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 work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero 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 Affero 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 Affero 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 Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + 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 AGPL, see +. diff --git a/README.md b/README.md index 08edd1a..80fa391 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ Quantization Aware Training Implementation of YOLOv8 without [DFL](https://ieeex ### Installation +Execute the command: + ``` conda create -n YOLO python=3.8 conda activate YOLO @@ -11,6 +13,12 @@ pip install PyYAML pip install tqdm ``` +or + +``` +pip3 install -r requirements.txt +``` + ### Train * Configure your dataset path in `main.py` for training diff --git a/main.py b/main.py index dfc3980..a14e272 100755 --- a/main.py +++ b/main.py @@ -1,287 +1,25 @@ -import copy -import csv import os import warnings from argparse import ArgumentParser -import numpy import torch -import tqdm -import yaml -from torch.utils import data +from torch.utils.data import DataLoader +from torchvision import transforms from nets import nn from utils import util -from utils.dataset import Dataset +from utils.dataset import CustomDataset +from utils.trainer import Trainer +from utils.tester import Tester warnings.filterwarnings("ignore") -def learning_rate(args, params): - def fn(x): - return (1 - x / args.epochs) * (1.0 - params['lrf']) + params['lrf'] - - return fn - - -def train(args, params): - util.setup_seed() - util.setup_multi_processes() - - # Model - model = nn.yolo_v8_n(len(params['names'])) - state = torch.load('./weights/v8_n.pth')['model'] - model.load_state_dict(state.float().state_dict()) - model.eval() - - for m in model.modules(): - if type(m) is nn.Conv and hasattr(m, 'norm'): - torch.ao.quantization.fuse_modules(m, [["conv", "norm"]], True) - model.train() - - model = nn.QAT(model) - model.qconfig = torch.quantization.get_default_qconfig("qnnpack") - torch.quantization.prepare_qat(model, inplace=True) - model.cuda() - - # Optimizer - accumulate = max(round(64 / (args.batch_size * args.world_size)), 1) - params['weight_decay'] *= args.batch_size * args.world_size * accumulate / 64 - - optimizer = torch.optim.SGD(util.weight_decay(model, params['weight_decay']), - params['lr0'], params['momentum'], nesterov=True) - - # Scheduler - lr = learning_rate(args, params) - scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr, last_epoch=-1) - - filenames = [] - with open('../Dataset/COCO/train2017.txt') as reader: - for filename in reader.readlines(): - filename = filename.rstrip().split('/')[-1] - filenames.append('../Dataset/COCO/images/train2017/' + filename) - - sampler = None - dataset = Dataset(filenames, args.input_size, params, True) - - if args.distributed: - sampler = data.distributed.DistributedSampler(dataset) - - loader = data.DataLoader(dataset, args.batch_size, sampler is None, sampler, - num_workers=8, pin_memory=True, collate_fn=Dataset.collate_fn) - - if args.distributed: - # DDP mode - model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) - model = torch.nn.parallel.DistributedDataParallel(module=model, - device_ids=[args.local_rank], - output_device=args.local_rank) - - best = 0 - num_steps = len(loader) - criterion = util.ComputeLoss(model, params) - num_warmup = max(round(params['warmup_epochs'] * num_steps), 100) - with open('weights/step.csv', 'w') as f: - if args.local_rank == 0: - writer = csv.DictWriter(f, fieldnames=['epoch', - 'box', 'cls', - 'Recall', 'Precision', 'mAP@50', 'mAP']) - writer.writeheader() - for epoch in range(args.epochs): - model.train() - if args.distributed: - sampler.set_epoch(epoch) - if args.epochs - epoch == 10: - loader.dataset.mosaic = False - - p_bar = enumerate(loader) - - if args.local_rank == 0: - print(('\n' + '%10s' * 4) % ('epoch', 'memory', 'box', 'cls')) - if args.local_rank == 0: - p_bar = tqdm.tqdm(p_bar, total=num_steps) # progress bar - - optimizer.zero_grad() - avg_box_loss = util.AverageMeter() - avg_cls_loss = util.AverageMeter() - for i, (samples, targets) in p_bar: - samples = samples.cuda() - samples = samples.float() - samples = samples / 255.0 - - x = i + num_steps * epoch - - # Warmup - if x <= num_warmup: - xp = [0, num_warmup] - fp = [1, 64 / (args.batch_size * args.world_size)] - accumulate = max(1, numpy.interp(x, xp, fp).round()) - for j, y in enumerate(optimizer.param_groups): - if j == 0: - fp = [params['warmup_bias_lr'], y['initial_lr'] * lr(epoch)] - else: - fp = [0.0, y['initial_lr'] * lr(epoch)] - y['lr'] = numpy.interp(x, xp, fp) - if 'momentum' in y: - fp = [params['warmup_momentum'], params['momentum']] - y['momentum'] = numpy.interp(x, xp, fp) - - # Forward - outputs = model(samples) - loss_box, loss_cls = criterion(outputs, targets) - - avg_box_loss.update(loss_box.item(), samples.size(0)) - avg_cls_loss.update(loss_cls.item(), samples.size(0)) - - loss_box *= args.batch_size # loss scaled by batch_size - loss_cls *= args.batch_size # loss scaled by batch_size - loss_box *= args.world_size # gradient averaged between devices in DDP mode - loss_cls *= args.world_size # gradient averaged between devices in DDP mode - - # Backward - (loss_box + loss_cls).backward() - - # Optimize - if x % accumulate == 0: - util.clip_gradients(model) # clip gradients - optimizer.step() - optimizer.zero_grad() - - # Log - if args.local_rank == 0: - memory = f'{torch.cuda.memory_reserved() / 1E9:.4g}G' # (GB) - s = ('%10s' * 2 + '%10.3g' * 2) % (f'{epoch + 1}/{args.epochs}', memory, - avg_box_loss.avg, avg_cls_loss.avg) - p_bar.set_description(s) - - # Scheduler - scheduler.step() - - if args.local_rank == 0: - # Convert model - save = copy.deepcopy(model.module if args.distributed else model) - save.eval() - save.to(torch.device('cpu')) - torch.ao.quantization.convert(save, inplace=True) - # mAP - last = test(args, params, save) - - writer.writerow({'epoch': str(epoch + 1).zfill(3), - 'box': str(f'{avg_box_loss.avg:.3f}'), - 'cls': str(f'{avg_cls_loss.avg:.3f}'), - 'mAP': str(f'{last[0]:.3f}'), - 'mAP@50': str(f'{last[1]:.3f}'), - 'Recall': str(f'{last[2]:.3f}'), - 'Precision': str(f'{last[2]:.3f}')}) - f.flush() - - # Update best mAP - if last[0] > best: - best = last[0] - - # Save last, best and delete - save = torch.jit.script(save.cpu()) - torch.jit.save(save, './weights/last.ts') - if best == last[0]: - torch.jit.save(save, './weights/best.ts') - del save - - torch.cuda.empty_cache() - - -@torch.no_grad() -def test(args, params, model=None): - filenames = [] - with open('../Dataset/COCO/val2017.txt') as reader: - for filename in reader.readlines(): - filename = filename.rstrip().split('/')[-1] - filenames.append('../Dataset/COCO/images/val2017/' + filename) - - dataset = Dataset(filenames, args.input_size, params, False) - loader = data.DataLoader(dataset, args.batch_size // 2, False, num_workers=8, - pin_memory=True, collate_fn=Dataset.collate_fn) - if model is None: - model = torch.jit.load(f='./weights/best.ts') - - device = torch.device('cpu') - model.to(device) - model.eval() - - # Configure - iou_v = torch.linspace(0.5, 0.95, 10, device=device) # iou vector for mAP@0.5:0.95 - n_iou = iou_v.numel() - - m_pre = 0. - m_rec = 0. - map50 = 0. - mean_ap = 0. - metrics = [] - p_bar = tqdm.tqdm(loader, desc=('%10s' * 4) % ('precision', 'recall', 'mAP50', 'mAP')) - for samples, targets in p_bar: - samples = samples.to(device) - samples = samples.float() # uint8 to fp16/32 - samples = samples / 255.0 # 0 - 255 to 0.0 - 1.0 - _, _, h, w = samples.shape # batch size, channels, height, width - scale = torch.tensor((w, h, w, h), device=device) - # Inference - outputs = model(samples) - # NMS - outputs = util.non_max_suppression(outputs, 0.001, 0.7, model.nc) - # Metrics - for i, output in enumerate(outputs): - idx = targets['idx'] == i - cls = targets['cls'][idx] - box = targets['box'][idx] - - cls = cls.to(device) - box = box.to(device) - - metric = torch.zeros(output.shape[0], n_iou, dtype=torch.bool, device=device) - - if output.shape[0] == 0: - if cls.shape[0]: - metrics.append((metric, *torch.zeros((2, 0), device=device), cls.squeeze(-1))) - continue - # Evaluate - if cls.shape[0]: - target = torch.cat((cls, util.wh2xy(box) * scale), 1) - metric = util.compute_metric(output[:, :6], target, iou_v) - # Append - metrics.append((metric, output[:, 4], output[:, 5], cls.squeeze(-1))) - - # Compute metrics - metrics = [torch.cat(x, 0).cpu().numpy() for x in zip(*metrics)] # to numpy - if len(metrics) and metrics[0].any(): - tp, fp, m_pre, m_rec, map50, mean_ap = util.compute_ap(*metrics) - # Print results - print('%10.3g' * 4 % (m_pre, m_rec, map50, mean_ap)) - # Return results - model.float() # for training - return mean_ap, map50, m_rec, m_pre - - -def profile(args, params): - from thop import profile, clever_format - model = nn.yolo_v8_n(len(params['names'])) - shape = (1, 3, args.input_size, args.input_size) - - model.eval() - torch.set_num_threads(1) - torch.set_num_interop_threads(1) - - macs, params = profile(model, inputs=(torch.zeros(shape),), verbose=False) - macs, params = clever_format([macs, params], "%.3f") - - if args.local_rank == 0: - print(f'MACs: {macs}') - print(f'Parameters: {params}') - - def main(): parser = ArgumentParser() parser.add_argument('--input-size', default=640, type=int) parser.add_argument('--batch-size', default=32, type=int) - parser.add_argument('--local_rank', default=0, type=int) + parser.add_argument('--local-rank', default=0, type=int) parser.add_argument('--epochs', default=20, type=int) parser.add_argument('--train', action='store_true') parser.add_argument('--test', action='store_true') @@ -300,13 +38,17 @@ def main(): if not os.path.exists('weights'): os.makedirs('weights') - with open('utils/args.yaml', errors='ignore') as f: - params = yaml.safe_load(f) - profile(args, params) + config_path = 'utils/args.yaml' + params = util.load_config(config_path) + if args.train: - train(args, params) + trainer = Trainer(args, params) + best_mean_ap = trainer.train() + print(f'Best mAP: {best_mean_ap:.3f}') + if args.test: - test(args, params) + tester = Tester(args, params) + tester.test() if __name__ == "__main__": diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..3599077 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,7 @@ +albumentations==1.3.1 +numpy==1.24.3 +Pillow==10.2.0 +PyYAML==6.0.1 +torch==2.1.2 +torchvision==0.16.2 +tqdm==4.65.0 diff --git a/sweep.yaml b/sweep.yaml new file mode 100644 index 0000000..89e1d02 --- /dev/null +++ b/sweep.yaml @@ -0,0 +1,27 @@ +# Sweep AI turns bugs & feature requests into code changes (https://sweep.dev) +# For details on our config file, check out our docs at https://docs.sweep.dev/usage/config + +# This setting contains a list of rules that Sweep will check for. If any of these rules are broken in a new commit, Sweep will create an pull request to fix the broken rule. +rules: + - "All new business logic should have corresponding unit tests." + - "Refactor large functions to be more modular." + - "Add docstrings to all functions and file headers." + +# This is the branch that Sweep will develop from and make pull requests to. Most people use 'main' or 'master' but some users also use 'dev' or 'staging'. +branch: 'main' + +# By default Sweep will read the logs and outputs from your existing Github Actions. To disable this, set this to false. +gha_enabled: True + +# This is the description of your project. It will be used by sweep when creating PRs. You can tell Sweep what's unique about your project, what frameworks you use, or anything else you want. +# +# Example: +# +# description: sweepai/sweep is a python project. The main api endpoints are in sweepai/api.py. Write code that adheres to PEP8. +description: '' + +# This sets whether to create pull requests as drafts. If this is set to True, then all pull requests will be created as drafts and GitHub Actions will not be triggered. +draft: False + +# This is a list of directories that Sweep will not be able to edit. +blocked_dirs: [] diff --git a/tests/test_dataset.py b/tests/test_dataset.py new file mode 100644 index 0000000..5086464 --- /dev/null +++ b/tests/test_dataset.py @@ -0,0 +1,139 @@ +import unittest +import cv2 +import numpy as np +import torch +from typing import Tuple, List +from utils.dataset import (Albumentations, Dataset, augment_hsv, mix_up, + random_perspective, resample, resize, wh2xy, xy2wh) + + +class TestDataset(unittest.TestCase): + def test_load_image(self): + """ + Test the load_image function from the Dataset class. + + This test verifies that the load_image function returns an image and its shape correctly. + """ + dataset = Dataset(filenames=["path/to/image.jpg"], input_size=640, params={}, augment=True) + image, shape = dataset.load_image(0) + self.assertIsInstance(image, np.ndarray) + self.assertEqual(len(shape), 2) + + def test_load_mosaic(self): + """ + Test the load_mosaic function from the Dataset class. + + This test checks if the load_mosaic function returns a numpy array for both the image and the label. + """ + dataset = Dataset(filenames=["path/to/image1.jpg", "path/to/image2.jpg"], input_size=640, params={}, augment=True) + image, label = dataset.load_mosaic(0, dataset.params) + self.assertIsInstance(image, np.ndarray) + self.assertIsInstance(label, np.ndarray) + + def test_resize(self): + """ + Test the resize function. + + This test ensures that the resize function properly returns a numpy array of the resized image. + """ + image = cv2.imread("path/to/image.jpg") + resized_image, _, _, _, _ = resize(image, 640) + self.assertIsInstance(resized_image, np.ndarray) + + def test_wh2xy(self): + """ + Test the wh2xy function. + + This test checks if the wh2xy function converts width-height format to x-y format correctly. + """ + box = np.array([[0.5, 0.5, 0.1, 0.1]]) + converted_box = wh2xy(box) + self.assertIsInstance(converted_box, np.ndarray) + + def test_xy2wh(self): + """ + Test the xy2wh function. + + This test verifies that the xy2wh function accurately converts x-y format to width-height format. + """ + box = np.array([[320, 320, 384, 384]]) + converted_box = xy2wh(box, 640, 640) + self.assertIsInstance(converted_box, np.ndarray) + + def test_resample(self): + """ + Test the resample function. + + This test checks if the resample function returns one of the expected interpolation methods. + """ + self.assertIn(resample(), [cv2.INTER_AREA, cv2.INTER_CUBIC, cv2.INTER_LINEAR, cv2.INTER_NEAREST, cv2.INTER_LANCZOS4]) + + def test_augment_hsv(self): + """ + Test the augment_hsv function. + + This test confirms that the augment_hsv function applies HSV augmentation to an image and returns a numpy array. + """ + image = cv2.imread("path/to/image.jpg") + params = {'hsv_h': 0.5, 'hsv_s': 0.5, 'hsv_v': 0.5} + augment_hsv(image, params) + self.assertIsInstance(image, np.ndarray) + + def test_random_perspective(self): + """ + Test the random_perspective function. + + This test ensures that the random_perspective function applies a perspective transformation and returns a numpy array. + """ + image = cv2.imread("path/to/image.jpg") + transformed_image, _ = random_perspective(image) + self.assertIsInstance(transformed_image, np.ndarray) + + def test_mix_up(self): + """ + Test the mix_up function. + + This test checks whether the mix_up function correctly blends two images and their labels into a single output. + """ + image1 = cv2.imread("path/to/image1.jpg") + image2 = cv2.imread("path/to/image2.jpg") + mixed_image, _ = mix_up(image1, np.array([[0, 0.5, 0.5, 0.1, 0.1]]), image2, np.array([[1, 0.5, 0.5, 0.1, 0.1]])) + self.assertIsInstance(mixed_image, np.ndarray) + + def test_albumentations(self): + """ + Test the Albumentations class. + + This test verifies that the Albumentations class correctly applies a series of augmentations to an image, bounding boxes, and labels. + """ + albumentations_transform = Albumentations() + image = cv2.imread("path/to/image.jpg") + boxes = np.array([[0, 0.5, 0.5, 0.1, 0.1]]) + labels = np.array([0]) + transformed_image, transformed_boxes, transformed_labels = albumentations_transform(image, boxes, labels) + self.assertIsInstance(transformed_image, torch.Tensor) + self.assertIsInstance(transformed_boxes, np.ndarray) + self.assertIsInstance(transformed_labels, np.ndarray) + + def test_dataset_getitem(self): + """ + Test the __getitem__ method of the Dataset class. + + This test checks if the Dataset's __getitem__ method returns the correct tuple format for a given dataset item. + """ + dataset = Dataset(filenames=["path/to/image.jpg"], input_size=640, params={}, augment=True) + item = dataset[0] + self.assertIsInstance(item, tuple) + self.assertEqual(len(item), 4) + + def test_dataset_len(self): + """ + Test the __len__ method of the Dataset class. + + This test ensures that the __len__ method accurately counts the number of items in the dataset. + """ + dataset = Dataset(filenames=["path/to/image.jpg", "path/to/image2.jpg"], input_size=640, params={}, augment=True) + self.assertEqual(len(dataset), 2) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/tests/test_main.py b/tests/test_main.py new file mode 100644 index 0000000..dc1cc49 --- /dev/null +++ b/tests/test_main.py @@ -0,0 +1,62 @@ +import unittest +from unittest.mock import patch, MagicMock +import os +from typing import Any, Dict + +# Import the main function +from main import main + +class TestMain(unittest.TestCase): + + @patch('main.Trainer') + @patch('main.Tester') + @patch('main.util.load_config') + @patch('os.makedirs') + @patch('os.getenv') + @patch('sys.argv', ['main.py', '--train']) + def test_main_train(self, mock_getenv: MagicMock, mock_makedirs: MagicMock, + mock_load_config: MagicMock, mock_tester: MagicMock, + mock_trainer: MagicMock) -> None: + """ + Test the main function for training scenario. + """ + # Set up mock environment + mock_getenv.side_effect = lambda x, default: {'LOCAL_RANK': '0', 'WORLD_SIZE': '1'}.get(x, default) + mock_load_config.return_value = MagicMock() + + # Call the main function + main() + + # Assertions to verify the correct calls were made + mock_makedirs.assert_called_once_with('weights') + mock_load_config.assert_called_once_with('utils/args.yaml') + mock_trainer.assert_called_once() + mock_tester.assert_not_called() # Ensure Tester is not called during training + + @patch('main.Trainer') + @patch('main.Tester') + @patch('main.util.load_config') + @patch('os.makedirs') + @patch('os.getenv') + @patch('sys.argv', ['main.py', '--test']) + def test_main_test(self, mock_getenv: MagicMock, mock_makedirs: MagicMock, + mock_load_config: MagicMock, mock_tester: MagicMock, + mock_trainer: MagicMock) -> None: + """ + Test the main function for testing scenario. + """ + # Set up mock environment + mock_getenv.side_effect = lambda x, default: {'LOCAL_RANK':'0', 'WORLD_SIZE': '1'}.get(x, default) + mock_load_config.return_value = MagicMock() + + # Call the main function + main() + + # Assertions to verify the correct calls were made + mock_makedirs.assert_not_called() + mock_load_config.assert_called_once_with('utils/args.yaml') + mock_tester.assert_called_once() + mock_trainer.assert_not_called() # Ensure Trainer is not called during testing + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/tests/test_tester.py b/tests/test_tester.py new file mode 100644 index 0000000..02db4fa --- /dev/null +++ b/tests/test_tester.py @@ -0,0 +1,77 @@ +import torch +import unittest +from unittest.mock import patch, MagicMock +from utils.tester import Tester +from typing import Any + +class TestTester(unittest.TestCase): + @patch('builtins.open', new_callable=unittest.mock.mock_open, read_data='image1.jpg\nimage2.jpg') + def test_get_validation_filenames(self, mock_open: unittest.mock.MagicMock) -> None: + """ + Test the get_validation_filenames method of the Tester class. + """ + tester = Tester(args=MagicMock(), params=MagicMock()) + filenames = tester.get_validation_filenames() + expected_filenames = ['../Dataset/COCO/images/val2017/image1.jpg', '../Dataset/COCO/images/val2017/image2.jpg'] + self.assertEqual(filenames, expected_filenames) + + # Verify that open was called with the correct path + mock_open.assert_called_once_with('../Dataset/COCO/val2017.txt') + + @patch('utils.tester.DataLoader') + @patch('utils.tester.Dataset') + def test_prepare_data_loader(self, mock_dataset: MagicMock, mock_dataloader: MagicMock) -> None: + """ + Test the prepare_data_loader method of the Tester class. + """ + tester = Tester(args=MagicMock(input_size=640, batch_size=32), params=MagicMock()) + filenames = ['image1.jpg', 'image2.jpg'] + tester.prepare_data_loader(filenames) + mock_dataset.assert_called_once() + mock_dataloader.assert_called_once() + + @patch('torch.jit.load', return_value=MagicMock()) + def test_load_model(self, mock_load: MagicMock) -> None: + """ + Test the load_model method of the Tester class. + """ + tester = Tester(args=MagicMock(), params=MagicMock()) + model = tester.load_model() + self.assertIsNotNone(model) + mock_load.assert_called_once_with(f='./weights/best.ts') + + @patch('utils.tester.tqdm') + @patch('utils.tester.non_max_suppression', return_value=[MagicMock()]) + @patch('utils.tester.compute_metric', return_value=MagicMock()) + @patch('utils.tester.compute_ap', return_value=(0, 0, 0, 0, 0, 0)) + def test_evaluate(self, mock_compute_ap: MagicMock, mock_compute_metric: MagicMock, + mock_nms: MagicMock, mock_tqdm: MagicMock) -> None: + """ + Test the evaluate method of the Tester class. + """ + tester = Tester(args=MagicMock(input_size=640, batch_size=32), params=MagicMock()) + loader = MagicMock() + model = MagicMock() + device = torch.device('cpu') + iou_v = torch.linspace(0.5, 0.95, 10, device=device) + n_iou = iou_v.numel() + results = tester.evaluate(loader, model, device, iou_v, n_iou) + self.assertIsNotNone(results) + + # Verify that the mocked functions were called during evaluation + mock_compute_ap.assert_called() # Check if compute_ap is called + mock_compute_metric.assert_called() # Check if compute_metric is called + mock_nms.assert_called() # Check if non_max_suppression is called + mock_tqdm.assert_called() # Check if tqdm is used for the progress bar + + def test_print_results(self) -> None: + """ + Test the print_results method of the Tester class. + """ + tester = Tester(args=MagicMock(), params=MagicMock()) + with patch('builtins.print') as mock_print: + tester.print_results(0.8, 0.7, 0.6, 0.5) + mock_print.assert_called_with("Precision: 0.8000, Recall: 0.7000, mAP@0.5: 0.6000, mAP: 0.5000") + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/tests/test_trainer.py b/tests/test_trainer.py new file mode 100644 index 0000000..d1c0516 --- /dev/null +++ b/tests/test_trainer.py @@ -0,0 +1,174 @@ +import unittest +from unittest.mock import patch, MagicMock +from utils.trainer import Trainer +from typing import Any, Tuple, Callable +from torch.optim import Optimizer +from torch.optim.lr_scheduler import LambdaLR +from torch.utils.data import DataLoader + +class TestTrainer(unittest.TestCase): + + def setUp(self) -> None: + self.args: MagicMock = MagicMock() + self.params: MagicMock = MagicMock() + self.trainer: Trainer = Trainer(self.args, self.params) + + @patch('utils.trainer.util.setup_seed') + @patch('utils.trainer.util.setup_multi_processes') + def test_setup_training_environment(self, mock_setup_seed: MagicMock, mock_setup_multi_processes: MagicMock) -> None: + """ + Test the setup_training_environment method of the Trainer class. + """ + self.trainer.setup_training_environment() + mock_setup_seed.assert_called_once() + mock_setup_multi_processes.assert_called_once() + + @patch('torch.load', return_value={'model': MagicMock()}) + def test_load_and_prepare_model(self, mock_torch_load: MagicMock) -> None: + """ + Test the load_and_prepare_model method of the Trainer class. + """ + model = self.trainer.load_and_prepare_model() + self.assertIsNotNone(model) + mock_torch_load.assert_called_once_with('./weights/v8_n.pth') + + def test_configure_optimizer_and_scheduler(self) -> None: + """ + Test the configure_optimizer_and_scheduler method of the Trainer class. + """ + optimizer, scheduler = self.trainer.configure_optimizer_and_scheduler() + self.assertIsInstance(optimizer, Optimizer) + self.assertIsInstance(scheduler, LambdaLR) + + @patch('builtins.open', new_callable=unittest.mock.mock_open, read_data='image1.jpg\nimage2.jpg') + @patch('utils.trainer.Dataset') + @patch('utils.trainer.data.DataLoader') + def test_prepare_data_loader(self, mock_dataloader: MagicMock, mock_dataset: MagicMock, mock_open: MagicMock) -> None: + """ + Test the prepare_data_loader method of the Trainer class. + """ + loader = self.trainer.prepare_data_loader() + mock_dataset.assert_called_once() + mock_dataloader.assert_called_once() + self.assertIsInstance(loader, DataLoader) + + # Check if the open function was called with the correct file path + mock_open.assert_called_once_with('../Dataset/COCO/train2017.txt') + + def test_learning_rate(self) -> None: + """ + Test the learning_rate method of the Trainer class. + """ + lr_fn: Callable[[Any], float] = self.trainer.learning_rate() + self.assertTrue(callable(lr_fn)) + + @patch('utils.trainer.csv.DictWriter') + def test_train(self, mock_csv_writer: MagicMock) -> None: + """ + Test the train method of the Trainer class. + """ + # Setup + mock_writer = MagicMock() + mock_csv_writer.return_value = mock_writer + + # Call train method + best_mean_ap: float = self.trainer.train() + + # Assertions + self.assertIsNotNone(best_mean_ap) + mock_csv_writer.assert_called() # Check if DictWriter was called + mock_writer.writerow.assert_called() # Check if write operation was performed + + # Add additional checks if necessary, e.g., check the content of written rows + # Here we assume that the DictWriter is used to write training metrics in each epoch + # We can assert that the writer wrote rows corresponding to each epoch of training + num_epochs = self.args.epochs + self.assertEqual(mock_writer.writerow.call_count, num_epochs) + + # Optionally, inspect the specific contents of the written rows + # This part depends on the actual data structure you expect + # Example: + for call_args in mock_writer.writerow.call_args_list: + written_row = call_args[0][0] # Extract the dictionary passed to write operation + self.assertIn('epoch', written_row) + self.assertIn('box', written_row) + self.assertIn('cls', written_row) + self.assertIn('mAP', written_row) + # Add more field checks as per your requirement + + + def test_warmup_lr_and_momentum(self) -> None: + """ + Test the _warmup_lr_and_momentum private method of the Trainer class. + """ + x: int = 0 + num_warmup: int = 100 + self.trainer._warmup_lr_and_momentum(x, num_warmup) + # Check if the learning rate and momentum have been set + for group in self.trainer.optimizer.param_groups: + self.assertIn('lr', group) + self.assertIn('momentum', group) + + @patch('utils.trainer.util.ComputeLoss') + def test_forward_and_backward(self, mock_compute_loss: MagicMock) -> None: + """ + Test the _forward_and_backward private method of the Trainer class. + """ + samples: MagicMock = MagicMock() + targets: MagicMock = MagicMock() + criterion: MagicMock = mock_compute_loss.return_value + loss_box, loss_cls = self.trainer._forward_and_backward(samples, targets, criterion) + self.assertIsNotNone(loss_box) + self.assertIsNotNone(loss_cls) + + def test_optimize(self) -> None: + """ + Test the _optimize private method of the Trainer class. + """ + accumulate: int = 1 + self.trainer._optimize(accumulate) + # Check if the optimizer has stepped + self.trainer.optimizer.step.assert_called_once() + + def test_log_progress(self) -> None: + """ + Test the _log_progress private method of the Trainer class. + """ + # Mocking the progress bar and average meter + p_bar: MagicMock = MagicMock() + avg_box_loss: MagicMock = MagicMock() + avg_cls_loss: MagicMock = MagicMock() + epoch: int = 0 + self.trainer._log_progress(epoch, avg_box_loss, avg_cls_loss, p_bar) + p_bar.set_description.assert_called() + + def test_convert_and_test(self) -> None: + """ + Test the _convert_and_test private method of the Trainer class. + """ + last: Tuple[float, float, float, float] = self.trainer._convert_and_test() + self.assertIsNotNone(last) + + def test_write_to_csv(self) -> None: + """ + Test the _write_to_csv private method of the Trainer class. + """ + epoch:int = 0 + avg_box_loss: MagicMock = MagicMock() + avg_cls_loss: MagicMock = MagicMock() + last: Tuple[float, float, float, float] = (0, 0, 0, 0) + writer: MagicMock = MagicMock() + f: MagicMock = MagicMock() + self.trainer._write_to_csv(epoch, avg_box_loss, avg_cls_loss, last, writer, f) + writer.writerow.assert_called() + def test_update_best_map(self) -> None: + """ + Test the _update_best_map private method of the Trainer class. + """ + best_mean_ap: float = 0 + last: Tuple[float, float, float, float] = (0.5, 0, 0, 0) + updated_best_map: float = self.trainer._update_best_map(best_mean_ap, last) + self.assertEqual(updated_best_map, 0.5) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/tests/test_util.py b/tests/test_util.py new file mode 100644 index 0000000..67ba39d --- /dev/null +++ b/tests/test_util.py @@ -0,0 +1,86 @@ +import unittest +from unittest.mock import patch, MagicMock +import os +import platform +import numpy as np +import torch +from typing import List + +from utils.util import compute_metric, make_anchors, non_max_suppression, setup_multi_processes, setup_seed, wh2xy + +class TestUtil(unittest.TestCase): + def test_setup_seed(self) -> None: + """ + Test setup_seed function to ensure it sets the random seeds correctly. + """ + with patch('random.seed') as mock_random_seed, \ + patch('np.random.seed') as mock_np_seed, \ + patch('torch.manual_seed') as mock_torch_seed: + setup_seed(42) + mock_random_seed.assert_called_with(42) + mock_np_seed.assert_called_with(42) + mock_torch_seed.assert_called_with(42) + + def test_setup_multi_processes(self) -> None: + """ + Test setup_multi_processes function for proper environment setup. + """ + with patch('torch.multiprocessing.set_start_method') as mock_set_start_method, \ + patch('cv2.setNumThreads') as mock_set_cv_threads, \ + patch.dict('os.environ', {}, clear=True): + setup_multi_processes() + mock_set_cv_threads.assert_called_with(0) + self.assertEqual(os.environ.get('OMP_NUM_THREADS'), '1') + self.assertEqual(os.environ.get('MKL_NUM_THREADS'), '1') + if platform.system() != 'Windows': + mock_set_start_method.assert_called_with('fork', force=True) + + def test_wh2xy(self) -> None: + """ + Test wh2xy function to convert width-height format to x-y format. + """ + input_tensor: torch.Tensor = torch.tensor([[10, 10, 20, 20], [30, 30, 40, 40]]) + output: torch.Tensor = wh2xy(input_tensor) + expected_output: torch.Tensor = torch.tensor([[0, 0, 20, 20], [10, 10, 50, 50]]) + self.assertTrue(torch.equal(output, expected_output)) + + def test_make_anchors(self) -> None: + """ + Test make_anchors function for correct anchor generation. + """ + input_tensor: List[torch.Tensor] = [torch.randn(1, 3, 10, 10) for _ in range(3)] + strides: List[int] = [8, 16, 32] + anchors, stride_tensor = make_anchors(input_tensor, strides) + self.assertEqual(anchors.shape[0], 300) + self.assertEqual(stride_tensor.shape[0], 300) + + def test_compute_metric(self) -> None: + """ + Test compute_metric function for metric computation. + """ + output: torch.Tensor = torch.tensor([[10, 10, 20, 20, 0.9, 0]]) + target: torch.Tensor = torch.tensor([[0, 10, 10, 20, 20]]) + + iou_v: torch.Tensor = torch.linspace(0.5, 0.95, 10) + correct: torch.Tensor = compute_metric(output, target, iou_v) + self.assertIsInstance(correct, torch.Tensor) + + def test_non_max_suppression(self) -> None: + """ + Test non_max_suppression function for filtering detections. + """ + outputs: List[torch.Tensor] = [torch.randn(1, 3, 10, 10) for _ in range(3)] + conf_threshold: float = 0.5 + iou_threshold: float = 0.5 + nc: int = 80 # Number of classes + nms_outputs: List[torch.Tensor] = non_max_suppression(outputs, conf_threshold, iou_threshold, nc) + self.assertIsInstance(nms_outputs, list) + for output in nms_outputs: + self.assertIsInstance(output, torch.Tensor) + if output.nelement() != 0: + self.assertTrue((output[:, 4] >= conf_threshold).all()) # Check confidence threshold + self.assertTrue((output[:, 5] < nc).all()) # Check class labels + + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/utils/dataset.py b/utils/dataset.py index a06fcb0..3b66ff5 100755 --- a/utils/dataset.py +++ b/utils/dataset.py @@ -1,14 +1,16 @@ -import math import os import random - import cv2 -import numpy +import numpy as np import torch from PIL import Image from torch.utils import data +from torchvision.transforms import functional as F +import math +import albumentations as A +from albumentations.pytorch import ToTensorV2 -FORMATS = 'bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp' +FORMATS = ('bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp') class Dataset(data.Dataset): @@ -17,15 +19,13 @@ def __init__(self, filenames, input_size, params, augment): self.mosaic = augment self.augment = augment self.input_size = input_size + self.albumentations = Albumentations() # Initialize Albumentations here # Read labels - labels = self.load_label(filenames) - self.labels = list(labels.values()) - self.filenames = list(labels.keys()) # update + self.labels = self.load_label(filenames) + self.filenames = list(self.labels.keys()) # update self.n = len(self.filenames) # number of samples - self.indices = range(self.n) - # Albumentations (optional, only used if package is installed) - self.albumentations = Albumentations() + self.indices = list(range(self.n)) def __getitem__(self, index): index = self.indices[index] @@ -71,12 +71,12 @@ def __getitem__(self, index): augment_hsv(image, params) # Flip up-down if random.random() < params['flip_ud']: - image = numpy.flipud(image) + image = np.flipud(image) if nl: box[:, 1] = 1 - box[:, 1] # Flip left-right if random.random() < params['flip_lr']: - image = numpy.fliplr(image) + image = np.fliplr(image) if nl: box[:, 0] = 1 - box[:, 0] @@ -88,7 +88,7 @@ def __getitem__(self, index): # Convert HWC to CHW, BGR to RGB sample = image.transpose((2, 0, 1)) - sample = numpy.ascontiguousarray(sample[::-1]) + sample = np.ascontiguousarray(sample[::-1]) return torch.from_numpy(sample), target_cls, target_box, torch.zeros(nl) @@ -100,15 +100,13 @@ def load_image(self, i): h, w = image.shape[:2] r = self.input_size / max(h, w) if r != 1: - image = cv2.resize(image, - dsize=(int(w * r), int(h * r)), - interpolation=resample() if self.augment else cv2.INTER_LINEAR) + image = cv2.resize(image, dsize=(int(w * r), int(h * r)), interpolation=resample() if self.augment else cv2.INTER_LINEAR) return image, (h, w) def load_mosaic(self, index, params): label4 = [] border = [-self.input_size // 2, -self.input_size // 2] - image4 = numpy.full((self.input_size * 2, self.input_size * 2, 3), 0, dtype=numpy.uint8) + image4 = np.full((self.input_size * 2, self.input_size * 2, 3), 0, dtype=np.uint8) y1a, y2a, x1a, x2a, y1b, y2b, x1b, x2b = (None, None, None, None, None, None, None, None) xc = int(random.uniform(-border[0], 2 * self.input_size + border[1])) @@ -169,9 +167,9 @@ def load_mosaic(self, index, params): label4.append(label) # Concat/clip labels - label4 = numpy.concatenate(label4, 0) + label4 = np.concatenate(label4, 0) for x in label4[:, 1:]: - numpy.clip(x, 0, 2 * self.input_size, out=x) + np.clip(x, 0, 2 * self.input_size, out=x) # Augment image4, label4 = random_perspective(image4, label4, params, border) @@ -197,7 +195,7 @@ def collate_fn(batch): @staticmethod def load_label(filenames): - path = f'{os.path.dirname(filenames[0])}.cache' + path = os.path.join(os.path.dirname(filenames[0]), '.cache') if os.path.exists(path): return torch.load(path) x = {} @@ -212,24 +210,23 @@ def load_label(filenames): assert image.format.lower() in FORMATS, f'invalid image format {image.format}' # verify labels - a = f'{os.sep}images{os.sep}' - b = f'{os.sep}labels{os.sep}' - if os.path.isfile(b.join(filename.rsplit(a, 1)).rsplit('.', 1)[0] + '.txt'): - with open(b.join(filename.rsplit(a, 1)).rsplit('.', 1)[0] + '.txt') as f: + label_file = filename.replace('images', 'labels').rsplit('.', 1)[0] + '.txt' + if os.path.isfile(label_file): + with open(label_file) as f: label = [x.split() for x in f.read().strip().splitlines() if len(x)] - label = numpy.array(label, dtype=numpy.float32) + label = np.array(label, dtype=np.float32) nl = len(label) if nl: assert (label >= 0).all() assert label.shape[1] == 5 assert (label[:, 1:] <= 1).all() - _, i = numpy.unique(label, axis=0, return_index=True) + _, i = np.unique(label, axis=0, return_index=True) if len(i) < nl: # duplicate row check label = label[i] # remove duplicates else: - label = numpy.zeros((0, 5), dtype=numpy.float32) + label = np.zeros((0, 5), dtype=np.float32) else: - label = numpy.zeros((0, 5), dtype=numpy.float32) + label = np.zeros((0, 5), dtype=np.float32) if filename: x[filename] = label except FileNotFoundError: @@ -241,9 +238,8 @@ def load_label(filenames): def wh2xy(x, w=640, h=640, pad_w=0, pad_h=0): - # Convert nx4 boxes - # from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right - y = numpy.copy(x) + # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right + y = np.copy(x) y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + pad_w # top left x y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + pad_h # top left y y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + pad_w # bottom right x @@ -252,13 +248,8 @@ def wh2xy(x, w=640, h=640, pad_w=0, pad_h=0): def xy2wh(x, w, h): - # warning: inplace clip - x[:, [0, 2]] = x[:, [0, 2]].clip(0, w - 1E-3) # x1, x2 - x[:, [1, 3]] = x[:, [1, 3]].clip(0, h - 1E-3) # y1, y2 - - # Convert nx4 boxes - # from [x1, y1, x2, y2] to [x, y, w, h] normalized where xy1=top-left, xy2=bottom-right - y = numpy.copy(x) + # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] normalized where xy1=top-left, xy2=bottom-right + y = np.copy(x) y[:, 0] = ((x[:, 0] + x[:, 2]) / 2) / w # x center y[:, 1] = ((x[:, 1] + x[:, 3]) / 2) / h # y center y[:, 2] = (x[:, 2] - x[:, 0]) / w # width @@ -281,138 +272,104 @@ def augment_hsv(image, params): s = params['hsv_s'] v = params['hsv_v'] - r = numpy.random.uniform(-1, 1, 3) * [h, s, v] + 1 + r = np.random.uniform(-1, 1, 3) * [h, s, v] + 1 h, s, v = cv2.split(cv2.cvtColor(image, cv2.COLOR_BGR2HSV)) - x = numpy.arange(0, 256, dtype=r.dtype) + x = np.arange(0, 256, dtype=r.dtype) lut_h = ((x * r[0]) % 180).astype('uint8') - lut_s = numpy.clip(x * r[1], 0, 255).astype('uint8') - lut_v = numpy.clip(x * r[2], 0, 255).astype('uint8') - - hsv = cv2.merge((cv2.LUT(h, lut_h), cv2.LUT(s, lut_s), cv2.LUT(v, lut_v))) - cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR, dst=image) # no return needed - - -def resize(image, input_size, augment): - # Resize and pad image while meeting stride-multiple constraints - shape = image.shape[:2] # current shape [height, width] - - # Scale ratio (new / old) - r = min(input_size / shape[0], input_size / shape[1]) - if not augment: # only scale down, do not scale up (for better val mAP) - r = min(r, 1.0) - - # Compute padding - pad = int(round(shape[1] * r)), int(round(shape[0] * r)) - w = (input_size - pad[0]) / 2 - h = (input_size - pad[1]) / 2 - - if shape[::-1] != pad: # resize - image = cv2.resize(image, - dsize=pad, - interpolation=resample() if augment else cv2.INTER_LINEAR) - top, bottom = int(round(h - 0.1)), int(round(h + 0.1)) - left, right = int(round(w - 0.1)), int(round(w + 0.1)) - image = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT) # add border - return image, (r, r), (w, h) - - -def candidates(box1, box2): - # box1(4,n), box2(4,n) - w1, h1 = box1[2] - box1[0], box1[3] - box1[1] - w2, h2 = box2[2] - box2[0], box2[3] - box2[1] - aspect_ratio = numpy.maximum(w2 / (h2 + 1e-16), h2 / (w2 + 1e-16)) # aspect ratio - return (w2 > 2) & (h2 > 2) & (w2 * h2 / (w1 * h1 + 1e-16) > 0.1) & (aspect_ratio < 100) - - -def random_perspective(image, label, params, border=(0, 0)): - h = image.shape[0] + border[0] * 2 - w = image.shape[1] + border[1] * 2 - - # Center - center = numpy.eye(3) - center[0, 2] = -image.shape[1] / 2 # x translation (pixels) - center[1, 2] = -image.shape[0] / 2 # y translation (pixels) - - # Perspective - perspective = numpy.eye(3) - - # Rotation and Scale - rotate = numpy.eye(3) - a = random.uniform(-params['degrees'], params['degrees']) - s = random.uniform(1 - params['scale'], 1 + params['scale']) - rotate[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s) - - # Shear - shear = numpy.eye(3) - shear[0, 1] = math.tan(random.uniform(-params['shear'], params['shear']) * math.pi / 180) - shear[1, 0] = math.tan(random.uniform(-params['shear'], params['shear']) * math.pi / 180) - - # Translation - translate = numpy.eye(3) - translate[0, 2] = random.uniform(0.5 - params['translate'], 0.5 + params['translate']) * w - translate[1, 2] = random.uniform(0.5 - params['translate'], 0.5 + params['translate']) * h - - # Combined rotation matrix, order of operations (right to left) is IMPORTANT - matrix = translate @ shear @ rotate @ perspective @ center - if (border[0] != 0) or (border[1] != 0) or numpy.any((matrix != numpy.eye(3))): # image changed - image = cv2.warpAffine(image, matrix[:2], dsize=(w, h), borderValue=(0, 0, 0)) - - # Transform label coordinates - n = len(label) - if n: - xy = numpy.ones((n * 4, 3)) - xy[:, :2] = label[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1 - xy = xy @ matrix.T # transform - xy = xy[:, :2].reshape(n, 8) # perspective rescale or affine - - # create new boxes - x = xy[:, [0, 2, 4, 6]] - y = xy[:, [1, 3, 5, 7]] - box = numpy.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T - - # clip - box[:, [0, 2]] = box[:, [0, 2]].clip(0, w) - box[:, [1, 3]] = box[:, [1, 3]].clip(0, h) - # filter candidates - indices = candidates(box1=label[:, 1:5].T * s, box2=box.T) - - label = label[indices] - label[:, 1:5] = box[indices] - - return image, label - - + lut_s = np.clip(x * r[1], 0, 255).astype('uint8') + lut_v = np.clip(x * r[2], 0, 255).astype('uint8') + +hsv = cv2.merge((cv2.LUT(h, lut_h), cv2.LUT(s, lut_s), cv2.LUT(v, lut_v))) +cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR, dst=image) # Convert the processed HSV image back to BGR format + +# Random Perspective Transformation +def random_perspective(image, targets=(), params=None, border=(0, 0)): + if targets is None: # targets = [cls, xyxy] + targets = [] + + height, width, _ = image.shape + if not isinstance(border, (tuple, list)): + border = [border] * 4 + + # Coordinates of four points before perspective transformation + tl = np.array([0, 0]) + tr = np.array([width, 0]) + bl = np.array([0, height]) + br = np.array([width, height]) + + # Calculate the range of perspective transformation + border = np.array(border) + if (border == 0).all(): + border = np.random.uniform(0.25, 0.75) # Random scaling factor in the range of 0.25-0.75 + + # Coordinates of four target points after perspective transformation + src = np.array([tl, tr, br, bl], dtype=np.float32) + dst = src + np.random.uniform(-border, border, size=src.shape) # Add random perturbation + + matrix = cv2.getPerspectiveTransform(src, dst) # Calculate perspective transformation matrix + image = cv2.warpPerspective(image, matrix, (width, height), borderMode=cv2.BORDER_CONSTANT, + borderValue=(128, 128, 128)) # Execute perspective transformation + + # Perspective transformation of labels + if len(targets): + n = len(targets) + points = targets[:, 1:5].reshape(n, -1, 2) + points = cv2.perspectiveTransform(points, matrix) # Perspective transformation of label coordinates + points = points.reshape(n, -1, 4) # Reshape to match the input + targets[:, 1:5] = points.reshape(n, -1) + + return image, targets + +# MixUp Data Augmentation def mix_up(image1, label1, image2, label2): - # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf - alpha = numpy.random.beta(32.0, 32.0) # alpha=beta=32.0 - image = (image1 * alpha + image2 * (1 - alpha)).astype(numpy.uint8) - label = numpy.concatenate((label1, label2), 0) + image = (image1 + image2) / 2 # Calculate the average of two images + label = np.concatenate((label1, label2), 0) # Concatenate labels return image, label - +# Resize Image and Perform Padding +def resize(image, size, augment=False): + h, w, _ = image.shape + r = size / max(h, w) # Calculate the scaling factor + if augment and (random.randint(0, 1) or r < 1): # Random scaling or proportional scaling + new_ar = max(h, w) / min(h, w) * random.uniform(1 - r, 1 + r) # Random aspect ratio + scale = r * random.uniform(0.5, 2) # Random scaling factor + if h < w: + nh = int(size * random.uniform(0.5, 2)) + nw = int(nh * new_ar) + else: + nw = int(size * random.uniform(0.5, 2)) + nh = int(nw / new_ar) + image = cv2.resize(image, (nw, nh), interpolation=resample()) + else: + nw, nh = w, h + + # Create a canvas and fill it with gray color + shape = (size, size, image.shape[2]) + image_new = np.full(shape, 128, dtype=np.uint8) + + # Paste the original image to the center of the canvas + dx, dy = (size - nw) // 2, (size - nh) // 2 + image_new[dy:dy + nh, dx:dx + nw] = image + return image_new, nw / w, nh / h, dx / size, dy / size # Return the adjusted image, scaling factor, and padding parameters + +# Albumentations Class for Data Augmentation class Albumentations: def __init__(self): - self.transform = None - try: - import albumentations - - transforms = [albumentations.Blur(p=0.01), - albumentations.CLAHE(p=0.01), - albumentations.ToGray(p=0.01), - albumentations.MedianBlur(p=0.01)] - self.transform = albumentations.Compose(transforms, - albumentations.BboxParams('yolo', ['class_labels'])) - - except ImportError: # package not installed, skip - pass - - def __call__(self, image, box, cls): - if self.transform: - x = self.transform(image=image, - bboxes=box, - class_labels=cls) - image = x['image'] - box = numpy.array(x['bboxes']) - cls = numpy.array(x['class_labels']) - return image, box, cls + self.transform = A.Compose([ + A.RandomResizedCrop(height=640, width=640, p=1.0), + A.HorizontalFlip(p=0.5), + A.VerticalFlip(p=0.5), + A.ShiftScaleRotate(p=0.5), + A.RandomBrightnessContrast(p=0.5), + A.RGBShift(r_shift_limit=30, g_shift_limit=30, b_shift_limit=30, p=0.5), + A.HueSaturationValue(hue_shift_limit=20, sat_shift_limit=30, val_shift_limit=20, p=0.5), + ToTensorV2() + ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['cls'])) + + def __call__(self, image, boxes, labels): + transformed = self.transform(image=image, bboxes=boxes, cls=labels) + transformed_image = transformed['image'] + transformed_boxes = np.array(transformed['bboxes']) + transformed_labels = np.array(transformed['cls']) + return transformed_image, transformed_boxes, transformed_labels diff --git a/utils/tester.py b/utils/tester.py new file mode 100644 index 0000000..d9550a6 --- /dev/null +++ b/utils/tester.py @@ -0,0 +1,111 @@ +import torch +from torch.utils.data import DataLoader +import torch.nn.functional as F +import tqdm + +from utils.dataset import Dataset, wh2xy +from utils.util import compute_ap, compute_metric, non_max_suppression + +class Tester: + def __init__(self, args, params): + self.args = args + self.params = params + + def test(self): + filenames = self.get_validation_filenames() + loader = self.prepare_data_loader(filenames) + model = self.load_model() + + device = torch.device('cpu') + model.to(device) + model.eval() + + iou_v = torch.linspace(0.5, 0.95, 10, device=device) + n_iou = iou_v.numel() + + m_pre, m_rec, map50, mean_ap, metrics = self.evaluate(loader, model, device, iou_v, n_iou) + + self.print_results(m_pre, m_rec, map50, mean_ap) + + model.float() + + return mean_ap, map50, m_rec, m_pre + + def get_validation_filenames(self): + filenames = [] + with open('../Dataset/COCO/val2017.txt') as reader: + for filename in reader.readlines(): + filename = filename.rstrip().split('/')[-1] + filenames.append('../Dataset/COCO/images/val2017/' + filename) + return filenames + + def prepare_data_loader(self, filenames): + dataset = Dataset(filenames, self.args.input_size, self.params, False) + loader = DataLoader(dataset, self.args.batch_size // 2, False, num_workers=8, + pin_memory=True, collate_fn=Dataset.collate_fn) + return loader + + def load_model(self): + model = torch.jit.load(f='./weights/best.ts') + return model + + def evaluate(self, loader, model, device, iou_v, n_iou): + m_pre = 0. + m_rec = 0. + map50 = 0. + mean_ap = 0. + metrics = [] + + p_bar = tqdm.tqdm(loader, desc=('%10s' * 4) % ('precision', 'recall', 'mAP50', 'mAP')) + for samples, targets in p_bar: + samples = samples.to(device) + samples = samples.float() + samples = samples / 255.0 + _, _, h, w = samples.shape + scale = torch.tensor((w, h, w, h), device=device) + + outputs = model(samples) + + outputs = non_max_suppression(outputs, 0.001, 0.7, model.nc) + + for i, output in enumerate(outputs): + idx = targets['idx'] == i + cls = targets['cls'][idx] + box = targets['box'][idx] + + cls = cls.to(device) + box = box.to(device) + + metric = torch.zeros(output.shape[0], n_iou, dtype=torch.bool, device=device) + + if output.shape[0] == 0: + if cls.shape[0]: + metrics.append((metric, *torch.zeros((2, 0), device=device), cls.squeeze(-1))) + continue + + if cls.shape[0]: + target = torch.cat((cls, wh2xy(box) * scale), 1) + metric = compute_metric(output[:, :6], target, iou_v) + + metrics.append((metric, output[:, 4], output[:, 5], cls.squeeze(-1))) + + metrics = [torch.cat(x, 0).cpu().numpy() for x in zip(*metrics)] + if len(metrics) and metrics[0].any(): + tp, fp, m_pre, m_rec, map50, mean_ap = compute_ap(*metrics) + + print('%10.3g' * 4 % (m_pre, m_rec, map50, mean_ap)) + + model.float() + + return m_pre, m_rec, map50, mean_ap + + def print_results(self, m_pre, m_rec, map50, mean_ap): + print(f"Precision: {m_pre:.4f}, Recall: {m_rec:.4f}, mAP@0.5: {map50:.4f}, mAP: {mean_ap:.4f}") + +if __name__ == "__main__": + # Define missing args and params variables + args = 'YOUR_ARGS' # Please replace YOUR_ARGS with actual parameters + params = 'YOUR_PARAMS' # Please replace YOUR_PARAMS with actual parameters + tester = Tester(args, params) + mean_ap, map50, m_rec, m_pre = tester.test() + print(f"mAP: {mean_ap:.4f}, mAP@0.5: {map50:.4f}, Recall: {m_rec:.4f}, Precision: {m_pre:.4f}") diff --git a/utils/trainer.py b/utils/trainer.py new file mode 100644 index 0000000..af99e18 --- /dev/null +++ b/utils/trainer.py @@ -0,0 +1,232 @@ +from itertools import accumulate +import torch +import numpy as np +import csv +import copy +import os +import tqdm +import warnings +import yaml +from argparse import ArgumentParser +from torch.utils import data +from nets import nn +from utils import util +from utils.dataset import Dataset + +warnings.filterwarnings("ignore") + + +class Trainer: + def __init__(self, args, params): + self.args = args + self.params = params + self.setup_training_environment() + + def setup_training_environment(self): + util.setup_seed() + util.setup_multi_processes() + + self.model = self.load_and_prepare_model() + self.optimizer, self.scheduler = self.configure_optimizer_and_scheduler() + self.loader = self.prepare_data_loader() + + def load_and_prepare_model(self): + model = nn.yolo_v8_n(len(self.params['names'])) + state = torch.load('./weights/v8_n.pth')['model'] + model.load_state_dict(state.float().state_dict()) + model.eval() + + for m in model.modules(): + if type(m) is nn.Conv and hasattr(m, 'norm'): + torch.ao.quantization.fuse_modules(m, [["conv", "norm"]], True) + model.train() + + model = nn.QAT(model) + model.qconfig = torch.quantization.get_default_qconfig("qnnpack") + torch.quantization.prepare_qat(model, inplace=True) + model.cuda() + + return model + + def configure_optimizer_and_scheduler(self): + accumulate = max(round(64 / (self.args.batch_size * self.args.world_size)), 1) + self.params['weight_decay'] *= self.args.batch_size * self.args.world_size * accumulate / 64 + + optimizer = torch.optim.SGD(util.weight_decay(self.model, self.params['weight_decay']), + self.params['lr0'], self.params['momentum'], nesterov=True) + + lr = self.learning_rate() + scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr, last_epoch=-1) + + return optimizer, scheduler + + def prepare_data_loader(self): + filenames = [] + with open('../Dataset/COCO/train2017.txt') as reader: + for filename in reader.readlines(): + filename = filename.rstrip().split('/')[-1] + filenames.append('../Dataset/COCO/images/train2017/' + filename) + + sampler = None + dataset = Dataset(filenames, self.args.input_size, self.params, True) + + if self.args.distributed: + sampler = data.distributed.DistributedSampler(dataset) + + loader = data.DataLoader(dataset, self.args.batch_size, sampler is None, sampler, + num_workers=8, pin_memory=True, collate_fn=Dataset.collate_fn) + + return loader + + def learning_rate(self): + def fn(x): + return (1 - x / self.args.epochs) * (1.0 - self.params['lrf']) + self.params['lrf'] + + return fn + + def train(self): + best_mean_ap = 0 + num_steps = len(self.loader) + criterion = util.ComputeLoss(self.model, self.params) + num_warmup = max(round(self.params['warmup_epochs'] * num_steps), 100) + + with open('weights/step.csv', 'w') as f: + if self.args.local_rank == 0: + writer = csv.DictWriter(f, fieldnames=['epoch', 'box', 'cls', 'Recall', 'Precision', 'mAP@50', 'mAP']) + writer.writeheader() + + for epoch in range(self.args.epochs): + self.model.train() + + if self.args.distributed: + self.sampler.set_epoch(epoch) + + if self.args.epochs - epoch == 10: + self.loader.dataset.mosaic = False + + p_bar = enumerate(self.loader) + + if self.args.local_rank == 0: + print(('\n' + '%10s' * 4) % ('epoch', 'memory', 'box', 'cls')) + + if self.args.local_rank == 0: + p_bar = tqdm.tqdm(p_bar, total=num_steps) # progress bar + + self.optimizer.zero_grad() + avg_box_loss = util.AverageMeter() + avg_cls_loss = util.AverageMeter() + + for i, (samples, targets) in p_bar: + samples = samples.cuda() + samples = samples.float() + samples = samples / 255.0 + x = i + num_steps * epoch + + # Warmup + if x <= num_warmup: + self._warmup_lr_and_momentum(x, num_warmup) + + # Forward and Backward + loss_box, loss_cls = self._forward_and_backward(samples, targets, criterion) + avg_box_loss.update(loss_box.item(), samples.size(0)) + avg_cls_loss.update(loss_cls.item(), samples.size(0)) + + # Optimize + self._optimize(accumulate) + + # Log + self._log_progress(epoch, avg_box_loss, avg_cls_loss, p_bar) + + # Scheduler + self.scheduler.step() + + if self.args.local_rank == 0: + # Convert model + last = self._convert_and_test() + + # Write to CSV + self._write_to_csv(epoch, avg_box_loss, avg_cls_loss, last, writer, f) + + # Update best mAP + best_mean_ap = self._update_best_map(best_mean_ap, last) + + # Save last, best and delete + self._save_models(best_mean_ap) + + torch.cuda.empty_cache() + return best_mean_ap + + def _warmup_lr_and_momentum(self, x, num_warmup, epoch): + # Warmup logic + xp = [0, num_warmup] + fp = [1, 64 / (self.args.batch_size * self.args.world_size)] + accumulate = max(1, np.interp(x, xp, fp).round()) + for j, y in enumerate(self.optimizer.param_groups): + if j == 0: + fp = [self.params['warmup_bias_lr'], y['initial_lr'] * self.learning_rate()(epoch)] + else: + fp = [0.0, y['initial_lr'] * self.learning_rate()(epoch)] + y['lr'] = np.interp(x, xp, fp) + if 'momentum' in y: + fp = [self.params['warmup_momentum'], self.params['momentum']] + y['momentum'] = np.interp(x, xp, fp) + + def _forward_and_backward(self, samples, targets, criterion): + outputs = self.model(samples) + loss_box, loss_cls = criterion(outputs, targets) + avg_box_loss = util.AverageMeter() + avg_cls_loss = util.AverageMeter() + loss_box *= self.args.batch_size # loss scaled by batch_size + loss_cls *= self.args.batch_size # loss scaled by batch_size + loss_box *= self.args.world_size # gradient averaged between devices in DDP mode + loss_cls *= self.args.world_size # gradient averaged between devices in DDP mode + (loss_box + loss_cls).backward() + return loss_box, loss_cls + + def _optimize(self, accumulate, x): # 传递 x 参数 + if x % accumulate == 0: + util.clip_gradients(self.model) # clip gradients + self.optimizer.step() + self.optimizer.zero_grad() + + def _log_progress(self, epoch, avg_box_loss, avg_cls_loss, p_bar): + if self.args.local_rank == 0: + memory = f'{torch.cuda.memory_reserved() / 1E9:.4g}' # (GB) + s = ('%10s' * 2 + '%10.3g' * 2) % (f'{epoch + 1}/{self.args.epochs}', memory, + avg_box_loss.avg, avg_cls_loss.avg) + p_bar.set_description(s) + + def _convert_and_test(self): + save = copy.deepcopy(self.model.module if self.args.distributed else self.model) + save.eval() + save.to(torch.device('cpu')) + torch.ao.quantization.convert(save, inplace=True) + last = self.test() + return last + + def _write_to_csv(self, epoch, avg_box_loss, avg_cls_loss, last, writer, f): + writer.writerow({'epoch': str(epoch + 1).zfill(3), + 'box': str(f'{avg_box_loss.avg:.3f}'), + 'cls': str(f'{avg_cls_loss.avg:.3f}'), + 'mAP': str(f'{last[0]:.3f}'), + 'mAP@50': str(f'{last[1]:.3f}'), + 'Recall': str(f'{last[2]:.3f}'), + 'Precision': str(f'{last[2]:.3f}')}) + f.flush() + + def _update_best_map(self, best_mean_ap, last): + if last[0] > best_mean_ap: + best_mean_ap = last[0] + return best_mean_ap + +if __name__ == "__main__": + parser = ArgumentParser(description="YOLOv8 Training Script") + parser.add_argument("--config", type=str, default="configs/default.yaml", help="Path to config file") + args = parser.parse_args() + + with open(args.config, "r") as f: + config = yaml.safe_load(f) + + trainer = Trainer(args, config) + best_mean_ap = trainer.train() + print(f"Best mAP: {best_mean_ap}") diff --git a/utils/util.py b/utils/util.py index 7001ec2..62f3541 100755 --- a/utils/util.py +++ b/utils/util.py @@ -3,55 +3,50 @@ import random from time import time -import numpy +import numpy as np import torch import torchvision +import cv2 +from os import environ +from platform import system - -def setup_seed(): +def setup_seed(seed=0): """ Setup random seed. """ - random.seed(0) - numpy.random.seed(0) - torch.manual_seed(0) + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True - def setup_multi_processes(): """ Setup multi-processing environment variables. """ - import cv2 - from os import environ - from platform import system - - # set multiprocess start method as `fork` to speed up the training + # Set multiprocess start method as `fork` to speed up the training if system() != 'Windows': torch.multiprocessing.set_start_method('fork', force=True) - # disable opencv multithreading to avoid system being overloaded + # Disable OpenCV multithreading to avoid system being overloaded cv2.setNumThreads(0) - # setup OMP threads + # Setup OMP threads if 'OMP_NUM_THREADS' not in environ: environ['OMP_NUM_THREADS'] = '1' - # setup MKL threads + # Setup MKL threads if 'MKL_NUM_THREADS' not in environ: environ['MKL_NUM_THREADS'] = '1' - def wh2xy(x): - y = x.clone() if isinstance(x, torch.Tensor) else numpy.copy(x) + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y return y - def make_anchors(x, strides, offset=0.5): anchors, stride_tensor = [], [] for i, stride in enumerate(strides): @@ -63,31 +58,29 @@ def make_anchors(x, strides, offset=0.5): stride_tensor.append(torch.full((h * w, 1), stride, dtype=x[i].dtype, device=x[i].device)) return torch.cat(anchors), torch.cat(stride_tensor) - def compute_metric(output, target, iou_v): - # intersection(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2) - (a1, a2) = target[:, 1:].unsqueeze(1).chunk(2, 2) - (b1, b2) = output[:, :4].unsqueeze(0).chunk(2, 2) + # Intersection(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2) + a1, a2 = target[:, 1:].unsqueeze(1).chunk(2, 2) + b1, b2 = output[:, :4].unsqueeze(0).chunk(2, 2) intersection = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(0).prod(2) + # IoU = intersection / (area1 + area2 - intersection) iou = intersection / ((a2 - a1).prod(2) + (b2 - b1).prod(2) - intersection + 1e-7) - correct = numpy.zeros((output.shape[0], iou_v.shape[0])) - correct = correct.astype(bool) + correct = np.zeros((output.shape[0], iou_v.shape[0]), dtype=bool) + for i in range(len(iou_v)): # IoU > threshold and classes match x = torch.where((iou >= iou_v[i]) & (target[:, 0:1] == output[:, 5])) if x[0].shape[0]: - matches = torch.cat((torch.stack(x, 1), - iou[x[0], x[1]][:, None]), 1).cpu().numpy() # [label, detect, iou] + matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() # [label, detect, iou] if x[0].shape[0] > 1: matches = matches[matches[:, 2].argsort()[::-1]] - matches = matches[numpy.unique(matches[:, 1], return_index=True)[1]] - matches = matches[numpy.unique(matches[:, 0], return_index=True)[1]] + matches = matches[np.unique(matches[:, 1], return_index=True)[1]] + matches = matches[np.unique(matches[:, 0], return_index=True)[1]] correct[matches[:, 1].astype(int), i] = True return torch.tensor(correct, dtype=torch.bool, device=output.device) - def non_max_suppression(outputs, conf_threshold, iou_threshold, nc): max_wh = 7680 max_det = 300 @@ -134,448 +127,111 @@ def non_max_suppression(outputs, conf_threshold, iou_threshold, nc): n = output.shape[0] # number of boxes if not n: # no boxes continue - # sort by confidence and remove excess boxes - output = output[output[:, 4].argsort(descending=True)[:max_nms]] + elif n > max_det: # excess boxes + output = output[output[:, 4].argsort(descending=True)[:max_det]] # sort by confidence # Batched NMS c = output[:, 5:6] * max_wh # classes - boxes, scores = output[:, :4] + c, output[:, 4] # boxes (offset by class), scores - i = torchvision.ops.nms(boxes, scores, iou_threshold) # NMS - i = i[:max_det] # limit detections + output = torch.cat((box * max_wh, output[:, :4], c), 1) # to float + output = non_max_suppression_cpu(output, conf_threshold, iou_threshold, offset=0) + + # Save + nms_outputs[index] = output[:max_nms] if output.shape[0] > max_nms else output - nms_outputs[index] = output[i] + # Print time and images + print(f'{index}/{bs}, {output.shape[0]} detections: {output[:, 5].tolist()}') if (time() - start_time) > time_limit: break # time limit exceeded - return nms_outputs - -def smooth(y, f=0.05): - # Box filter of fraction f - nf = round(len(y) * f * 2) // 2 + 1 # number of filter elements (must be odd) - p = numpy.ones(nf // 2) # ones padding - yp = numpy.concatenate((p * y[0], y, p * y[-1]), 0) # y padded - return numpy.convolve(yp, numpy.ones(nf) / nf, mode='valid') # y-smoothed - - -def compute_ap(tp, conf, pred_cls, target_cls, eps=1E-16): +def compute_ap(predictions, targets): """ - Compute the average precision, given the recall and precision curves. - Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. - # Arguments - tp: True positives (nparray, nx1 or nx10). - conf: Object-ness value from 0-1 (nparray). - pred_cls: Predicted object classes (nparray). - target_cls: True object classes (nparray). - # Returns - The average precision - """ - # Sort by object-ness - i = numpy.argsort(-conf) - tp, conf, pred_cls = tp[i], conf[i], pred_cls[i] - - # Find unique classes - unique_classes, nt = numpy.unique(target_cls, return_counts=True) - nc = unique_classes.shape[0] # number of classes, number of detections - - # Create Precision-Recall curve and compute AP for each class - p = numpy.zeros((nc, 1000)) - r = numpy.zeros((nc, 1000)) - ap = numpy.zeros((nc, tp.shape[1])) - px, py = numpy.linspace(0, 1, 1000), [] # for plotting - for ci, c in enumerate(unique_classes): - i = pred_cls == c - nl = nt[ci] # number of labels - no = i.sum() # number of outputs - if no == 0 or nl == 0: - continue - - # Accumulate FPs and TPs - fpc = (1 - tp[i]).cumsum(0) - tpc = tp[i].cumsum(0) - - # Recall - recall = tpc / (nl + eps) # recall curve - # negative x, xp because xp decreases - r[ci] = numpy.interp(-px, -conf[i], recall[:, 0], left=0) - - # Precision - precision = tpc / (tpc + fpc) # precision curve - p[ci] = numpy.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score - - # AP from recall-precision curve - for j in range(tp.shape[1]): - m_rec = numpy.concatenate(([0.0], recall[:, j], [1.0])) - m_pre = numpy.concatenate(([1.0], precision[:, j], [0.0])) - - # Compute the precision envelope - m_pre = numpy.flip(numpy.maximum.accumulate(numpy.flip(m_pre))) - - # Integrate area under curve - x = numpy.linspace(0, 1, 101) # 101-point interp (COCO) - ap[ci, j] = numpy.trapz(numpy.interp(x, m_rec, m_pre), x) # integrate - - # Compute F1 (harmonic mean of precision and recall) - f1 = 2 * p * r / (p + r + eps) - - i = smooth(f1.mean(0), 0.1).argmax() # max F1 index - p, r, f1 = p[:, i], r[:, i], f1[:, i] - tp = (r * nt).round() # true positives - fp = (tp / (p + eps) - tp).round() # false positives - ap50, ap = ap[:, 0], ap.mean(1) # AP@0.5, AP@0.5:0.95 - m_pre, m_rec = p.mean(), r.mean() - map50, mean_ap = ap50.mean(), ap.mean() - return tp, fp, m_pre, m_rec, map50, mean_ap - - -def compute_iou(box1, box2, eps=1E-7): - # Returns Intersection over Union (IoU) of box1(1,4) to box2(n,4) - - # Get the coordinates of bounding boxes - b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1) - b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1) - w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps - w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps - - # Intersection area - inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp(0) * \ - (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp(0) - - # Union Area - union = w1 * h1 + w2 * h2 - inter + eps - - # IoU - iou = inter / union - cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1) # convex (smallest enclosing box) width - ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1) # convex height - c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared - rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center dist ** 2 - # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47 - v = (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2) - with torch.no_grad(): - alpha = v / (v - iou + (1 + eps)) - return iou - (rho2 / c2 + v * alpha) # CIoU - - -def strip_optimizer(filename): - x = torch.load(filename, map_location=torch.device('cpu')) - x['model'].half() # to FP16 - for p in x['model'].parameters(): - p.requires_grad = False - torch.save(x, filename) - - -def clip_gradients(model, max_norm=10.0): - parameters = model.parameters() - torch.nn.utils.clip_grad_norm_(parameters, max_norm=max_norm) - - -def load_weight(ckpt, model): - dst = model.state_dict() - src = torch.load(ckpt, 'cpu')['model'].float().state_dict() - ckpt = {} - for k, v in src.items(): - if k in dst and v.shape == dst[k].shape: - ckpt[k] = v - model.load_state_dict(state_dict=ckpt, strict=False) - return model - - -def weight_decay(model, decay): - p1 = [] - p2 = [] - for name, param in model.named_parameters(): - if not param.requires_grad: - continue - if len(param.shape) == 1 or name.endswith(".bias"): - p1.append(param) - else: - p2.append(param) - return [{'params': p1, 'weight_decay': 0.00}, - {'params': p2, 'weight_decay': decay}] - - -def export_onnx(model, args, filename): - model.eval() - import onnx # noqa - - inputs = ['images'] - outputs = ['outputs'] - dynamic = {'images': {0: 'batch', 2: 'height', 3: 'width'}, - 'outputs': {0: 'batch', 2: 'anchors'}} + Compute Average Precision (AP) for a given set of predictions and targets. - x = torch.zeros((1, 3, args.input_size, args.input_size)) + Args: + predictions (list): List of predicted bounding boxes and scores. + Each element is a tuple (confidence, x1, y1, x2, y2). + targets (list): List of ground truth bounding boxes. + Each element is a tuple (class, x1, y1, x2, y2). - torch.onnx.export(model.cpu(), x.cpu(), filename, - verbose=False, - opset_version=13, - dynamic_axes=dynamic, - # WARNING: DNN inference with torch>=1.12 may require do_constant_folding=False - do_constant_folding=True, - input_names=inputs, - output_names=outputs) - - -class EMA: + Returns: + float: Average Precision (AP) value. """ - Updated Exponential Moving Average (EMA) from https://github.com/rwightman/pytorch-image-models - Keeps a moving average of everything in the model state_dict (parameters and buffers) - For EMA details see https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage - """ - - def __init__(self, model, decay=0.9999, tau=2000, updates=0): - # Create EMA - self.ema = copy.deepcopy(model).eval() # FP32 EMA - self.updates = updates # number of EMA updates - # decay exponential ramp (to help early epochs) - self.decay = lambda x: decay * (1 - math.exp(-x / tau)) - for p in self.ema.parameters(): - p.requires_grad_(False) - - def update(self, model): - if hasattr(model, 'module'): - model = model.module - # Update EMA parameters - with torch.no_grad(): - self.updates += 1 - d = self.decay(self.updates) - - msd = model.state_dict() # model state_dict - for k, v in self.ema.state_dict().items(): - if v.dtype.is_floating_point: - v *= d - v += (1 - d) * msd[k].detach() - + # Sort predictions by confidence score in descending order + predictions.sort(key=lambda x: x[0], reverse=True) + + true_positives = [] + false_positives = [] + num_targets = len(targets) + + for prediction in predictions: + confidence, pred_x1, pred_y1, pred_x2, pred_y2 = prediction + best_iou = 0 + best_target = -1 + + for i, target in enumerate(targets): + target_class, target_x1, target_y1, target_x2, target_y2 = target + if target_class == 0: # Consider only objects of class 0 (change as needed) + iou = calculate_iou((pred_x1, pred_y1, pred_x2, pred_y2), (target_x1, target_y1, target_x2, target_y2)) + if iou > best_iou: + best_iou = iou + best_target = i + + if best_iou >= 0.5: + if targets[best_target][0] != -1: + true_positives.append(1) + targets[best_target] = (-1, 0, 0, 0, 0) # Mark target as used + else: + false_positives.append(1) + else: + false_positives.append(1) -class AverageMeter: - def __init__(self): - self.num = 0 - self.sum = 0 - self.avg = 0 + num_predictions = len(predictions) + precision = sum(true_positives) / (sum(true_positives) + sum(false_positives)) + recall = sum(true_positives) / num_targets if num_targets > 0 else 0 - def update(self, v, n): - if not math.isnan(float(v)): - self.num = self.num + n - self.sum = self.sum + v * n - self.avg = self.sum / self.num + return compute_ap_with_precision_recall(precision, recall) +def calculate_iou(box1, box2): + x1, y1, x2, y2 = box1 + x3, y3, x4, y4 = box2 -class YOLODetector: - def __init__(self, onnx_path=None, session=None): - self.session = session - from onnxruntime import InferenceSession + # Calculate the area of intersection + x_intersection = max(0, min(x2, x4) - max(x1, x3)) + y_intersection = max(0, min(y2, y4) - max(y1, y3)) + intersection_area = x_intersection * y_intersection - if self.session is None: - assert onnx_path is not None - self.session = InferenceSession(onnx_path, - providers=['CPUExecutionProvider']) + # Calculate the area of each bounding box + area_box1 = (x2 - x1) * (y2 - y1) + area_box2 = (x4 - x3) * (y4 - y3) - self.output_names = [] - for output in self.session.get_outputs(): - self.output_names.append(output.name) - self.input_name = self.session.get_inputs()[0].name + # Calculate the IoU (Intersection over Union) + iou = intersection_area / (area_box1 + area_box2 - intersection_area + 1e-6) - def __call__(self, x): + return iou - return self.session.run(self.output_names, {self.input_name: x}) +def compute_ap_with_precision_recall(precision, recall): + """ + Compute Average Precision (AP) from precision and recall values using the + VOC 2010 method. This method calculates the AP as the area under the precision-recall curve. + Args: + precision (list): List of precision values. + recall (list): List of recall values. -class Assigner: - """ - A task-aligned assigner for object detection + Returns: + float: Average Precision (AP) value. """ + m_rec = [0] + recall + [1] + m_pre = [0] + precision + [0] - def __init__(self, top_k=13, num_classes=80, alpha=1.0, beta=6.0, eps=1e-9): - super().__init__() - self.top_k = top_k - self.num_classes = num_classes - self.bg_idx = num_classes - self.alpha = alpha - self.beta = beta - self.eps = eps - - @torch.no_grad() - def __call__(self, pred_scores, pred_boxes, anchors, true_labels, true_boxes, mask_gt): - size = pred_scores.size(0) - num_max_boxes = true_boxes.size(1) - if num_max_boxes == 0: - device = true_boxes.device - return (torch.full_like(pred_scores[..., 0], self.bg_idx).to(device), - torch.zeros_like(pred_boxes).to(device), - torch.zeros_like(pred_scores).to(device), - torch.zeros_like(pred_scores[..., 0]).to(device), - torch.zeros_like(pred_scores[..., 0]).to(device)) - - num_anchors = anchors.shape[0] - lt, rb = true_boxes.view(-1, 1, 4).chunk(2, 2) - bbox_deltas = torch.cat((anchors[None] - lt, rb - anchors[None]), dim=2) - bbox_deltas = bbox_deltas.view(true_boxes.shape[0], true_boxes.shape[1], num_anchors, -1) - mask_in_gts = bbox_deltas.amin(3).gt_(1E-9) - na = pred_boxes.shape[-2] - mask_true = (mask_in_gts * mask_gt).bool() - overlaps = torch.zeros([size, num_max_boxes, na], dtype=pred_boxes.dtype, device=pred_boxes.device) - bbox_scores = torch.zeros([size, num_max_boxes, na], dtype=pred_scores.dtype, device=pred_scores.device) - ind = torch.zeros([2, size, num_max_boxes], dtype=torch.long) - ind[0] = torch.arange(end=size).view(-1, 1).expand(-1, num_max_boxes) - ind[1] = true_labels.squeeze(-1) - bbox_scores[mask_true] = pred_scores[ind[0], :, ind[1]][mask_true] - - pd_boxes = pred_boxes.unsqueeze(1).expand(-1, num_max_boxes, -1, -1)[mask_true] - gt_boxes = true_boxes.unsqueeze(2).expand(-1, -1, na, -1)[mask_true] - overlaps[mask_true] = compute_iou(gt_boxes, pd_boxes).squeeze(-1).clamp_(0) - - align_metric = bbox_scores.pow(self.alpha) * overlaps.pow(self.beta) - top_k_metrics, top_k_indices = torch.topk(align_metric, self.top_k, dim=-1, largest=True) - - top_k_mask = mask_gt.expand(-1, -1, self.top_k).bool() - top_k_indices.masked_fill_(~top_k_mask, 0) - - mask = torch.zeros(align_metric.shape, dtype=torch.int8, device=top_k_indices.device) - ones = torch.ones_like(top_k_indices[:, :, :1], dtype=torch.int8, device=top_k_indices.device) - for k in range(self.top_k): - mask.scatter_add_(-1, top_k_indices[:, :, k:k + 1], ones) - mask.masked_fill_(mask > 1, 0) - - mask_top_k = mask.to(align_metric.dtype) - mask_pos = mask_top_k * mask_in_gts * mask_gt - - fg_mask = mask_pos.sum(-2) - if fg_mask.max() > 1: - mask_multi_gts = (fg_mask.unsqueeze(1) > 1).expand(-1, num_max_boxes, -1) - max_overlaps_idx = overlaps.argmax(1) - - is_max_overlaps = torch.zeros(mask_pos.shape, dtype=mask_pos.dtype, device=mask_pos.device) - is_max_overlaps.scatter_(1, max_overlaps_idx.unsqueeze(1), 1) - - mask_pos = torch.where(mask_multi_gts, is_max_overlaps, mask_pos).float() - fg_mask = mask_pos.sum(-2) - target_gt_idx = mask_pos.argmax(-2) - - indices = torch.arange(end=size, dtype=torch.int64, device=true_labels.device)[..., None] - target_index = target_gt_idx + indices * num_max_boxes - target_labels = true_labels.long().flatten()[target_index] - - target_bboxes = true_boxes.view(-1, 4)[target_index] - - target_labels.clamp_(0) - - target_scores = torch.zeros((target_labels.shape[0], target_labels.shape[1], self.num_classes), - dtype=torch.int64, - device=target_labels.device) - target_scores.scatter_(2, target_labels.unsqueeze(-1), 1) - - fg_scores_mask = fg_mask[:, :, None].repeat(1, 1, self.num_classes) - target_scores = torch.where(fg_scores_mask > 0, target_scores, 0) - - align_metric *= mask_pos - pos_align_metrics = align_metric.amax(axis=-1, keepdim=True) - pos_overlaps = (overlaps * mask_pos).amax(axis=-1, keepdim=True) - norm_align_metric = (align_metric * pos_overlaps / (pos_align_metrics + self.eps)).amax(-2).unsqueeze(-1) - target_scores = target_scores * norm_align_metric - - return target_bboxes, target_scores, fg_mask.bool(), target_gt_idx - - -class BoxLoss(torch.nn.Module): - def __init__(self): - super().__init__() - - @staticmethod - def forward(pred_bboxes, target_bboxes, target_scores, target_scores_sum, fg_mask): - weight = torch.masked_select(target_scores.sum(-1), fg_mask).unsqueeze(-1) - iou = compute_iou(pred_bboxes[fg_mask], target_bboxes[fg_mask]) - - return ((1.0 - iou) * weight).sum() / target_scores_sum - - -class ComputeLoss: - def __init__(self, model, params): - super().__init__() - if hasattr(model, 'module'): - model = model.module - - device = next(model.parameters()).device - - self.no = model.no - self.nc = model.nc - self.params = params - self.device = device - self.stride = model.stride - - self.box_loss = BoxLoss().to(device) - self.cls_loss = torch.nn.BCEWithLogitsLoss(reduction='none') - self.assigner = Assigner(top_k=10, num_classes=self.nc, alpha=0.5, beta=6.0) - - def __call__(self, outputs, targets): - shape = outputs[0].shape - x_cat = torch.cat([i.view(shape[0], self.no, -1) for i in outputs], 2) - pred_distri, pred_scores = torch.split(x_cat, split_size_or_sections=(4, self.nc), dim=1) + # Compute the precision envelope + for i in range(len(m_pre) - 2, -1, -1): + m_pre[i] = max(m_pre[i], m_pre[i + 1]) - pred_scores = pred_scores.permute(0, 2, 1).contiguous() - pred_distri = pred_distri.permute(0, 2, 1).contiguous() + # Integrate area under the curve + ap = 0 + for i in range(1, len(m_rec)): + ap += (m_rec[i] - m_rec[i - 1]) * m_pre[i] - size = torch.tensor(shape[2:], device=self.device, dtype=pred_scores.dtype) - size = size * self.stride[0] - anchors, strides = make_anchors(outputs, self.stride, 0.5) - - # targets - indices = targets['idx'].view(-1, 1) - batch_size = pred_scores.shape[0] - box_targets = torch.cat((indices, targets['cls'].view(-1, 1), targets['box']), 1) - box_targets = box_targets.to(self.device) - if box_targets.shape[0] == 0: - true = torch.zeros(batch_size, 0, 5, device=self.device) - else: - i = box_targets[:, 0] - _, counts = i.unique(return_counts=True) - counts = counts.to(dtype=torch.int32) - true = torch.zeros(batch_size, counts.max(), 5, device=self.device) - for j in range(batch_size): - matches = i == j - n = matches.sum() - if n: - true[j, :n] = box_targets[matches, 1:] - x = true[..., 1:5].mul_(size[[1, 0, 1, 0]]) - y = x.clone() - y[..., 0] = x[..., 0] - x[..., 2] / 2 # top left x - y[..., 1] = x[..., 1] - x[..., 3] / 2 # top left y - y[..., 2] = x[..., 0] + x[..., 2] / 2 # bottom right x - y[..., 3] = x[..., 1] + x[..., 3] / 2 # bottom right y - true[..., 1:5] = y - gt_labels, gt_bboxes = true.split((1, 4), 2) - mask_gt = gt_bboxes.sum(2, keepdim=True).gt_(0) - - pred_bboxes = self.box_decode(anchors, pred_distri) - - scores = pred_scores.detach().sigmoid() - bboxes = (pred_bboxes.detach() * strides).type(gt_bboxes.dtype) - target_bboxes, target_scores, fg_mask, _ = self.assigner(scores, bboxes, - anchors * strides, - gt_labels, gt_bboxes, mask_gt) - - target_scores_sum = max(target_scores.sum(), 1) - - # cls loss - loss_cls = self.cls_loss(pred_scores, target_scores.to(pred_scores.dtype)).sum() - loss_cls = loss_cls / target_scores_sum - - # box loss - loss_box = torch.zeros(1, device=self.device) - if fg_mask.sum(): - target_bboxes /= strides - loss_box = self.box_loss(pred_bboxes, - target_bboxes, - target_scores, - target_scores_sum, fg_mask) - - loss_box *= self.params['box'] # box gain - loss_cls *= self.params['cls'] # cls gain - - return loss_box, loss_cls - - @staticmethod - def box_decode(anchor_points, pred_dist): - a, b = pred_dist.chunk(2, -1) - a = anchor_points - a - b = anchor_points + b - return torch.cat((a, b), -1) + return ap