Repository: wenhui0206/NeuroGPT Branch: main Commit: 230571d45ca4 Files: 23 Total size: 194.8 KB Directory structure: gitextract_e8qms5uv/ ├── .gitignore ├── LICENSE ├── README.md ├── requirements.txt ├── scripts/ │ ├── finetune.sh │ └── train.sh └── src/ ├── batcher/ │ ├── base.py │ ├── downstream_dataset.py │ └── make.py ├── decoder/ │ ├── gpt.py │ ├── make_decoder.py │ └── unembedder.py ├── embedder/ │ ├── base.py │ ├── csm.py │ ├── csm_causal.py │ └── make.py ├── encoder/ │ ├── base.py │ └── conformer_braindecode.py ├── model.py ├── train_gpt.py ├── trainer/ │ ├── base.py │ └── make.py └── utils.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class slurm* *.npy *.out *.csv *.pt *.bin *.json *.pyc # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ pip-wheel-metadata/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ data/ result/ ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # NeuroGPT ### Neuro-GPT: Towards a Foundation Model for EEG [paper](https://arxiv.org/abs/2311.03764) #### Published on IEEE - ISBI 2024 We propose Neuro-GPT, a foundation model consisting of an EEG encoder and a GPT model. The foundation model is pre-trained on a large-scale data set using a self-supervised task that learns how to reconstruct masked EEG segments. We then fine-tune the model on a Motor Imagery Classification task to validate its performance in a low-data regime (9 subjects). Our experiments demonstrate that applying a foundation model can significantly improve classification performance compared to a model trained from scratch. ### Pre-trained foundation model available [here](https://huggingface.co/wenhuic/Neuro-GPT/tree/main) ![Neuro-GPT Pipeline](./figures/pipeline.png) ## Installation ```console git clone git@github.com:wenhui0206/NeuroGPT.git pip install -r requirements.txt cd NeuroGPT/scripts ./train.sh ``` ## Requirements pip install -r requirements.txt ## Datasets - [TUH EEG Corpus](https://isip.piconepress.com/projects/tuh_eeg/html/downloads.shtml#c_tueg) - [BCI Competition IV 2a Dataset](https://www.bbci.de/competition/iv/#datasets) ## Acknowledgments This project is developed based on the following open-source repositories: - [Self-supervised learning of brain dynamics from broad neuroimaging data](https://github.com/athms/learning-from-brains) - [EEG-Conformer](https://github.com/eeyhsong/EEG-Conformer) ================================================ FILE: requirements.txt ================================================ einops==0.7.0 h5py==3.10.0 numpy==1.26.4 pandas==2.2.1 scikit_learn==1.4.0 scipy==1.12.0 torch==2.2.0 torchinfo==1.8.0 tqdm==4.66.2 transformers==4.38.1 ================================================ FILE: scripts/finetune.sh ================================================ python3 ../src/train_gpt.py --training-style='decoding' --num-decoding-classes=4 --training-steps=10000 --eval_every_n_steps=500 --log-every-n-steps=1000 --num_chunks=2 --per-device-training-batch-size=32 --per-device-validation-batch-size=32 --chunk_len=500 --chunk_ovlp=0 --run-name='dst' --ft-only-encoder='True' --fold_i=0 --num-encoder-layers=6 --num-hidden-layers=6 --learning-rate=1e-4 --use-encoder='True' --embedding-dim=1024 --pretrained-model='../pretrained_model/pytorch_model.bin' --dst-data-path="../../bci2a_egg_npz/" ================================================ FILE: scripts/train.sh ================================================ python3 ../src/train_gpt.py --training-steps=50000 --eval_every_n_steps=1000 --log-every-n-steps=3000 --per-device-training-batch-size=32 --per-device-validation-batch-size=32 --num-workers=16 --num_chunks=32 --chunk_len=500 --chunk_ovlp=50 --num-hidden-layers=6 --num-encoder-layers=6 --run-name='32clen2_embed1024' --training-style='CSM_causal' --embedding-dim=1024 --train-data-path='../../tuh_tensors' ================================================ FILE: src/batcher/base.py ================================================ #!/usr/bin/env python3 from typing import Dict import numpy as np # import webdataset as wds import torch # import gzip # import pickle import h5py import os # import webdataset as wds from torch.utils.data import Dataset def _pad_seq_right_to_n( seq: np.ndarray, n: int, pad_value: float = 0. ) -> np.ndarray: if n == seq.shape[0]: return seq return np.concatenate( [ seq, np.ones( ( n-seq.shape[0], *seq.shape[1:] ) ) * pad_value, ], axis=0, ) class EEGDataset(Dataset): def __init__(self, filenames, sample_keys, chunk_len=500, num_chunks=10, ovlp=50, root_path="", population_mean=0, population_std=1, gpt_only=False, normalization=True, start_samp_pnt=-1): if root_path == "": self.filenames = filenames else: self.filenames = [root_path + fn for fn in filenames if os.path.isfile(root_path+fn)] self.root_path = root_path print("Number of subjects loaded: ", len(self.filenames)) # self.data = data_all self.chunk_len = chunk_len self.num_chunks = num_chunks self.ovlp = ovlp self.sample_keys = sample_keys self.mean = population_mean self.std = population_std self.do_normalization = normalization self.gpt_only=gpt_only self.start_samp_pnt = start_samp_pnt def __len__(self): return len(self.filenames) def __getitem__(self, idx): data = self.load_tensor(self.filenames[idx]) #===reorder channels==== data = self.reorder_channels(data) return self.preprocess_sample(data, seq_len=self.num_chunks) @staticmethod def _pad_seq_right_to_n( seq: np.ndarray, n: int, pad_value: float = 0 ) -> np.ndarray: return _pad_seq_right_to_n( seq=seq, n=n, pad_value=pad_value ) def load_single_file(self, filename): with h5py.File(filename, 'r') as file: data_dict = file['Result'] data = [] for i in range(data_dict['data'].shape[0]): ref = data_dict['data'][i][0] time_series = data_dict[ref] if len(data) > 0 and time_series.shape[0] < data[0].shape[0]: time_series = np.zeros_like(data[0]) data.append(np.array(time_series).squeeze()) return data def load_tensor(self, filename): # tensor_fn = filename[:-3] + 'pt' tensor_data = torch.load(filename) return tensor_data.numpy() def reorder_channels(self, data): chann_labels = {'FP1': 0, 'FP2': 1, 'F3': 2, 'F4': 3, 'C3': 4, 'C4': 5, 'P3': 6, 'P4': 7, 'O1': 8, 'O2': 9, 'F7': 10, 'F8': 11, 'T3': 12, 'T4': 13, 'T5': 14, 'T6': 15, 'FZ': 16, 'CZ': 17, 'PZ': 18, 'OZ': 19, 'T1': 20, 'T2': 21} reorder_labels = {'FP1': 0, 'FP2': 1, 'F7': 2, 'F3': 3, 'FZ': 4, 'F4': 5, 'F8': 6, 'T1': 7, 'T3': 8, 'C3': 9, 'CZ': 10, 'C4': 11, 'T4': 12, 'T2': 13, 'T5': 14, 'P3': 15, 'PZ': 16, 'P4': 17, 'T6': 18, 'O1': 19, 'OZ': 20, 'O2': 21} reordered = np.zeros_like(data) for label, target_idx in reorder_labels.items(): mapped_idx = chann_labels[label] reordered[target_idx, :] = data[mapped_idx, :] return reordered def split_chunks(self, data, length=500, ovlp=50, num_chunks=10, start_point=-1): '''2 seconds, 0.2 seconds overlap''' all_chunks = [] total_len = data.shape[1] actual_num_chunks = num_chunks if start_point == -1: if num_chunks * length > total_len - 1: start_point = 0 actual_num_chunks = total_len // length else: start_point = np.random.randint(0, total_len - num_chunks * length) for i in range(actual_num_chunks): chunk = data[:, start_point: start_point + length] all_chunks.append(np.array(chunk)) start_point = start_point + length - ovlp return np.array(all_chunks), start_point def normalize(self, data): mean = np.mean(data, axis=-1, keepdims=True) std = np.std(data, axis=-1, keepdims=True) # Ensure std is not zero to avoid division by zero. # If std is zero, normalization doesn't make sense, # so you might set std to a small positive value or handle it in another way. # std = np.where(std == 0, 1e-23, std) return (data - mean) / (std + 1e-25) def preprocess_sample( self, sample, seq_len, labels=None ) -> Dict[str, torch.Tensor]: out = {} if self.do_normalization: sample = self.normalize(sample) chunks, seq_on = self.split_chunks(sample, self.chunk_len, self.ovlp, seq_len, self.start_samp_pnt) attention_mask = np.ones(seq_len) chunks = self._pad_seq_right_to_n( seq=chunks, n=seq_len, pad_value=0 ) attention_mask = self._pad_seq_right_to_n( seq=attention_mask, n=seq_len, pad_value=0 ) if self.gpt_only == True: chunks = np.reshape(chunks, (seq_len, chunks.shape[1]*chunks.shape[2])) out["inputs"] = torch.from_numpy(chunks).to(torch.float) out["attention_mask"] = torch.from_numpy(attention_mask).to(torch.long) out['seq_on'] = seq_on out['seq_len'] = seq_len if self.sample_keys is not None: out = { key: out[key] for key in self.sample_keys if key in out } if labels is not None: out['labels'] = torch.from_numpy(np.array(labels)).to(torch.long) return out ================================================ FILE: src/batcher/downstream_dataset.py ================================================ import os import pdb import numpy as np from batcher.base import EEGDataset from scipy.io import loadmat from scipy.signal import butter, filtfilt class MotorImageryDataset(EEGDataset): def __init__(self, filenames, sample_keys, chunk_len=500, num_chunks=10, ovlp=50, root_path="", gpt_only=True): super().__init__(filenames, sample_keys, chunk_len, num_chunks, ovlp, root_path=root_path, gpt_only=gpt_only) self.data_all = [] for fn in self.filenames: self.data_all.append(np.load(fn)) self.mi_types = {769: 'left', 770: 'right', 771: 'foot', 772: 'tongue', 1023: 'rejected'} # , 783: 'unknown', 1023: 'rejected' # Types of motor imagery self.labels_string2int = {'left': 0, 'right': 1, 'foot': 2, 'tongue':3 } #, 'unknown': -1 self.Fs = 250 # 250Hz from original paper self.P = np.load("../inputs/tMatrix_value.npy") self.trials, self.labels, self.num_trials_per_sub = self.get_trials_all() # keys of data ['s', 'etyp', 'epos', 'edur', 'artifacts'] def __len__(self): return sum(self.num_trials_per_sub) def __getitem__(self, idx): return self.preprocess_sample(self.trials[idx], self.num_chunks, self.labels[idx]) def map2pret(self, data): return np.matmul(self.P, data) # 22x22, 22xTime def get_trials_from_single_subj(self, sub_id): raw = self.data_all[sub_id]['s'].T events_type = self.data_all[sub_id]['etyp'].T events_position = self.data_all[sub_id]['epos'].T events_duration = self.data_all[sub_id]['edur'].T artifacts = self.data_all[sub_id]['artifacts'].T # Channel default is C3 startrial_code = 768 starttrial_events = events_type == startrial_code idxs = [i for i, x in enumerate(starttrial_events[0]) if x] trial_labels = self.get_labels(sub_id) trials = [] classes = [] for j, index in enumerate(idxs): try: # print(index) # type_e = events_type[0, index+1] # class_e = self.mi_types[type_e] # if type_e == 1023: # continue # classes.append(self.labels_string2int[class_e]) classes.append(trial_labels[j]) start = events_position[0, index] stop = start + events_duration[0, index] trial = raw[:22, start+500 : stop-375] #add band-pass filter # self.bandpass_filter(trial, lowcut=4, highcut=40, fs=250, order=5) trials.append(trial) except: # print("Cannot load trial") continue return trials, classes def get_labels(self, sub_id): label_path = self.root_path + "true_labels/" base_name = os.path.basename(self.filenames[sub_id]) sub_name = os.path.splitext(base_name)[0] labels = loadmat(label_path + sub_name +".mat")["classlabel"] return labels.squeeze() - 1 def get_trials_all(self): trials_all = [] labels_all = [] total_num = [] for sub_id in range(len(self.data_all)): trials, labels = self.get_trials_from_single_subj(sub_id) total_num.append(len(trials)) trials_all.append(np.array(trials)) labels_all.append(np.array(labels)) # reordered_data = self.reorder_channels(np.vstack(trials_all)) trials_all_arr = np.vstack(trials_all) # map to same channel configuration as pretraining trials_all_arr = self.map2pret(trials_all_arr) return self.normalize(trials_all_arr), np.array(labels_all).flatten(), total_num # def normalize(self, data): # return (data - np.mean(data)) / np.std(data) def bandpass_filter(self, data, lowcut, highcut, fs, order=5): """ Apply a bandpass filter to the data. Parameters: - data: The EEG signal - lowcut: Low cut-off frequency - highcut: High cut-off frequency - fs: Sampling rate (frequency) - order: Order of the filter Returns: - Filtered data """ nyq = 0.5 * fs low = lowcut / nyq high = highcut / nyq b, a = butter(order, [low, high], btype='band') filtered_data = filtfilt(b, a, data) return filtered_data ================================================ FILE: src/batcher/make.py ================================================ #!/usr/bin/env python3 from batcher.base import BaseBatcher def make_batcher( training_style: str='CSM', tr: float=2.0, chunk_len:int=500, num_chunks: int=10, seq_min: int=10, seq_max: int=50, bert_seq_gap_min: int=1, bert_seq_gap_max: int=5, decoding_target: str=None, sample_random_seq: bool=True, seed: int=None, bold_dummy_mode: bool=False, ) -> BaseBatcher: """ Make a batcher object. The batcher is used to generate batches of input data for training and evaluation. Args: ----- training_style: str The used training style (ie., framework). One of: 'BERT', 'CSM', 'NetBERT', 'autoencoder', 'decoding'. seq_min: int The minimum sequence length (in sequence elements) used for the random sampling of input sequences. seq_max: int The maximum sequence length (in sequence elements) used for the random sampling of input sequences. bert_seq_gap_min: int The minimum gap (in sequence elements) between two consecutive sequences for BERT-style training, if they are sampled from the same data run file. bert_seq_gap_max: int The maximum gap (in sequence elements) between two consecutive sequences for BERT-style training, if they are sampled from the same data run file. decoding_target: str Key of decoding target variable in data run files. sample_random_seq: bool If True, the sequences are sampled randomly from the data run files, given the spefied sequence length (seq_min and seq_max) and the specified gap consecutive sequences (bert_seq_gap_min, bert_seq_gap_max) for BERT-style training. seed: int The seed for the random number generator. bold_dummy_mode: bool If True, the BOLD data are replaced with simple dummy data (for internal testing purposed only). Core methods: ----- dataset(tarfiles: list) Returns a Pytorch dataset that can be used for training, given the specified list of data run file paths (tarfiles). """ kwargs = { "tr": tr, "chunk_len": chunk_len, "num_chunks": num_chunks, "seq_min": seq_min, "seq_max": seq_max, "gap_min": bert_seq_gap_min, "gap_max": bert_seq_gap_max, "decoding_target": decoding_target, "sample_random_seq": sample_random_seq, "seed": seed, "bold_dummy_mode": bold_dummy_mode } sample_keys = [ 'inputs', 'attention_mask', 't_rs' ] if training_style in {'CSM', 'MSM', 'MNM', 'autoencoder'}: from batcher.base import BaseBatcher return BaseBatcher(**{**kwargs, **{'sample_keys': sample_keys}}) elif training_style == 'decoding': sample_keys.append('labels') from batcher.base import BaseBatcher return BaseBatcher(**{**kwargs, **{'sample_keys': sample_keys}}) else: raise ValueError('unknown training style.') ================================================ FILE: src/decoder/gpt.py ================================================ #!/usr/bin/env python3 from typing import Dict import warnings import torch from transformers import GPT2Config, GPT2Model import torch.nn as nn class GPTModel(torch.nn.Module): def __init__( self, num_hidden_layers: int = 6, num_attention_heads: int = 12, embed_dim: int = 768, intermediate_dim_factor: int = 4, n_positions: int = 512, hidden_activation: str = 'gelu', dropout: float = 0.1, **kwargs ) -> None: super().__init__() self.name = 'GPT' self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.embed_dim = embed_dim self.intermediate_dim_factor = intermediate_dim_factor self.n_positions = n_positions self.hidden_activation = hidden_activation self.dropout_resid = dropout self.dropout_attn = dropout self.dropout_embd = dropout self.mse_loss = torch.nn.MSELoss() self.bxe_loss = torch.nn.BCEWithLogitsLoss() self.config = GPT2Config( vocab_size=1, n_positions=self.n_positions, n_embd=self.embed_dim, n_layer=self.num_hidden_layers, n_head=self.num_attention_heads, n_inner=self.embed_dim * self.intermediate_dim_factor, resid_pdrop=self.dropout_resid, attn_pdrop=self.dropout_attn, embd_pdrop=self.dropout_embd, activation_function=self.hidden_activation ) self.transformer = GPT2Model(config=self.config) self.is_decoding_mode = False self.decoding_head = None self.num_decoding_classes = None self.pooler_layer = None self.add_pooler_layer() def switch_decoding_mode( self, is_decoding_mode: bool=False, num_decoding_classes: int=None ) -> None: self.is_decoding_mode = is_decoding_mode if self.is_decoding_mode: if self.pooler_layer is None: self.add_pooler_layer() self.add_decoding_head(num_decoding_classes=num_decoding_classes) else: self.decoding_head = None def add_pooler_layer(self): if self.pooler_layer is not None: warnings.warn( 'Warning: overwriting existing pooler layer' ) self.pooler_layer = torch.nn.Sequential( torch.nn.Linear( in_features=self.embed_dim, out_features=self.embed_dim ), torch.nn.Tanh(), torch.nn.Dropout(self.dropout_resid) ) def add_decoding_head( self, num_decoding_classes: int ) -> None: if self.decoding_head is not None: if self.num_decoding_classes == num_decoding_classes: warnings.warn( 'Warning: not overwriting decoding head, as ' f'{num_decoding_classes}-class decoding head exists.' ) return None else: warnings.warn( f'Warning: overwriting existing {num_decoding_classes}-class decoding head.' ) self.num_decoding_classes = num_decoding_classes # self.decoding_head = torch.nn.Sequential( # torch.nn.Linear( # in_features=self.embed_dim, # out_features=self.num_decoding_classes # ) # ) self.decoding_head = nn.Sequential( nn.Linear(self.embed_dim, 256), nn.ELU(), nn.Dropout(0.5), nn.Linear(256, 32), nn.ELU(), nn.Dropout(0.3), nn.Linear(32, self.num_decoding_classes) ) return None def decode( self, outputs: torch.tensor, attention_mask: torch.tensor, ) -> Dict[str, torch.tensor]: assert self.is_decoding_mode, 'GPTModel must be in decoding_mode.' assert self.pooler_layer is not None, 'pooler_layer head must be added.' assert self.decoding_head is not None, 'decoding head must be added.' batch_size = outputs.size()[0] sequence_lengths = attention_mask.sum(dim=1)-1 decoding_outputs = { 'pooler_outputs': self.pooler_layer( outputs[torch.arange(batch_size, device=outputs.device), sequence_lengths] ) } decoding_outputs['decoding_logits'] = self.decoding_head(decoding_outputs['pooler_outputs']) return decoding_outputs def forward( self, batch: Dict[str, torch.tensor] ) -> Dict[str, torch.tensor]: transformer_outputs = self.transformer.forward( inputs_embeds=batch['inputs_embeds'], attention_mask=batch['attention_mask'], token_type_ids=batch.get('token_type_ids', None), return_dict=True ) outputs = {'outputs': transformer_outputs['last_hidden_state']} if not self.is_decoding_mode: return outputs outputs.update( self.decode( outputs=outputs['outputs'], attention_mask=batch['attention_mask'] ) ) return outputs class PretrainedGPT2(GPTModel): def __init__( self, **kwargs ): super().__init__(**kwargs) self.name = 'PretrainedGPT2' self.config = GPT2Config() self.n_positions = self.config.n_positions self.embed_dim = self.config.n_embd self.num_hidden_layers = self.config.n_layer self.num_attention_heads = self.config.n_head self.intermediate_dim_factor = 4 self.dropout_resid = self.config.resid_pdrop self.dropout_attn = self.config.attn_pdrop self.dropout_embd = self.config.embd_pdrop self.hidden_activation = self.config.activation_function self.transformer = GPT2Model.from_pretrained("gpt2") ================================================ FILE: src/decoder/make_decoder.py ================================================ #!/usr/bin/env python3 import torch def make_decoder( architecture: str='GPT', num_hidden_layers: int = 4, embed_dim: int = 768, output_dim: int = 1024, num_attention_heads: int = 12, intermediate_dim_factor: int=4, n_positions: int = 512, hidden_activation: str='gelu_new', dropout: float = 0.1 ) -> torch.nn.Module: """ Make a decoder object. The decoder contains the core model architecture used for learning. Args: ----- architecture: str The model architecture to use. One of: 'GPT', 'BERT', 'NetBERT', autoencoder', 'PretrainedGPT', 'PretrainedBERT', 'LinearBaseline'. num_hidden_layers: int The number of hidden layers of the model. Does not apply to 'PretrainedGPT', 'PretrainedBERT', 'LinearBaseline'. For 'autoencoder', num_hidden_layers represents the number of hidden layers of the encoder and decoder model. embed_dim: int The dimension of the used embedding space (see src.embedder). output_dim: int The dimension of the output projection (needs to match in_dim of src.embedder for upstream learning). num_attention_heads: int The number of attention heads of transformer models. Does not apply to any other model architecture as well as the 'PretrainedGPT' and 'PretrainedBERT' architectures. intermediate_dim_factor: int Scales feed-forward transformer layer dimension relative to ' embed_dim: intermediate_dim_factor * embed_dim n_positions: int The maximum number of sequence elements that the model can handle (in sequence elements). hidden_activation: str Type of hidden activation of transformer layers One of 'gelu', 'gelu_new', 'relu', 'silu'. Does not apply to non-transformer models. dropout: float Dropout ratio for attendion heads and residual layers of transofmer models and between LSTM layers of encoder / decoder parts of autoencoder models. Core methods: ----- forward(batch: Dict): Forward pass of the model, generates Dict containing predicted output seqeuences, given input batch (as generated by src.embedder.prep_batch). decode(outputs: Dict): Make decoding prediction, given outputs generated by caling forward(). switch_decoding_mode(is_decoding_mode: bool): Switch model to decoding mode (is_decoding_mode=True). Relevant for adaptation of pre-trained models to downstream decoding tasks. """ kwargs = { "num_hidden_layers": num_hidden_layers, "embed_dim": embed_dim, "output_dim": output_dim, "num_attention_heads": num_attention_heads, "intermediate_dim_factor": intermediate_dim_factor, "n_positions": n_positions, "hidden_activation": hidden_activation, "dropout": dropout } if architecture == 'GPT': from decoder.gpt import GPTModel return GPTModel(**kwargs) elif architecture == 'PretrainedGPT2': from decoder.gpt import PretrainedGPT2 return PretrainedGPT2(**kwargs) else: raise ValueError(f'{architecture}-architecture unkown.') ================================================ FILE: src/decoder/unembedder.py ================================================ #!/usr/bin/env python3 import torch from einops import rearrange import torch.nn as nn from einops.layers.torch import Rearrange class DeconvNet(nn.Module): def __init__(self, n_filters_time=40, n_channels=22, filter_time_length=25, stride_avg_pool=15, pool_time_length=75): super(DeconvNet, self).__init__() # To reverse AvgPool2d self.depool = nn.Sequential(Rearrange("b seq d_model -> b d_model 1 seq"), nn.Upsample(size=(1, 476), mode='nearest')) #nn.ConvTranspose2d(n_filters_time, n_filters_time, kernel_size=(1, pool_time_length), stride=(1, stride_avg_pool)) self.deconv1 = nn.ConvTranspose2d(n_filters_time, n_filters_time, (n_channels, 1), (1, 1)) self.deconv2 = nn.ConvTranspose2d(n_filters_time, 1, (1, filter_time_length), (1, 1)) def forward(self, x): x = self.depool(x) x = self.deconv1(x) x = nn.ELU()(x) # We're keeping ELU activation. x = self.deconv2(x) return {'outputs': x.squeeze()} class UnEmbedder(torch.nn.Module): """ Unmebedding model; used to project predicted output sequences of src.decoder back to input space during upstream learning. Args ---- embed_dim: int Dimension of the embedding space. out_dim: int Dimension of the output space. num_hidden_layers: int Number of hidden layers of projection model. If >1, all hidden layers except for the last are activated with Gelu activation. dropout: float Dropout ratio for the projection model. Core methods ---- forward(inputs, **kwargs) Projection of input to output space. """ def __init__( self, embed_dim: int = 768, out_dim: int = 1024, num_hidden_layers: int = 1, dropout: int = 0.1, ) -> None: super().__init__() self.embed_dim = embed_dim self.out_dim = out_dim self.num_hidden_layers = num_hidden_layers self.dropout = dropout layer_stack = [] for _ in range(self.num_hidden_layers-1): layer_stack.extend( [ torch.nn.Linear( in_features=self.embed_dim, out_features=self.embed_dim ), torch.nn.LayerNorm(self.embed_dim), torch.nn.GELU(), torch.nn.Dropout(p=self.dropout) ] ) layer_stack.extend( [ torch.nn.Linear( in_features=self.embed_dim, out_features=self.out_dim ) ] ) self.model = torch.nn.Sequential(*layer_stack) def stack_inputs( self, tensor ) -> torch.tensor: return rearrange( tensor=tensor, pattern='b s e -> (b s) e' ) def unstack_inputs( self, tensor, b ) -> torch.tensor: return rearrange( tensor=tensor, pattern='(b s) e -> b s e', b=b ) def forward( self, inputs, **kwargs ) -> torch.tensor: inputs_stacked = self.stack_inputs(tensor=inputs) return { 'outputs': self.unstack_inputs( tensor=self.model(inputs_stacked), b=inputs.size()[0] ) } def make_unembedder( embed_dim: int = 768, out_dim: int = 1024, num_hidden_layers: int = 1, dropout: int = 0.1 ) -> torch.nn.Module: """ Creates a UnEmbedder object. Args ---- embed_dim: int Dimension of the embedding space. out_dim: int Dimension of the output space. num_hidden_layers: int Number of hidden layers of projection model. If >1, all hidden layers except for the last are activated with Gelu activation. dropout: float Dropout ratio for the projection model. Core methods ---- forward(inputs, **kwargs) Projection of input to output space. """ return UnEmbedder( embed_dim=embed_dim, out_dim=out_dim, num_hidden_layers=num_hidden_layers, dropout=dropout ) ================================================ FILE: src/embedder/base.py ================================================ #/usr/bin/env python3 import pdb import torch from typing import Dict from einops import rearrange class EmbeddingModel(torch.nn.Module): def __init__( self, in_dim: int = 1024, embed_dim: int = 768, num_hidden_layers: int = 1, dropout: int = 0.1, ) -> None: super().__init__() self.in_dim = in_dim self.embed_dim = embed_dim self.num_hidden_layers = num_hidden_layers self.dropout = dropout layer_stack = [] for _ in range(self.num_hidden_layers-1): layer_stack.extend( [ torch.nn.Linear( in_features=self.in_dim, out_features=self.embed_dim ), torch.nn.LayerNorm(self.embed_dim), torch.nn.GELU(), torch.nn.Dropout(p=self.dropout) ] ) layer_stack.extend( [ torch.nn.Linear( in_features=self.embed_dim if self.num_hidden_layers>1 else self.in_dim, out_features=self.embed_dim ), torch.nn.LayerNorm(self.embed_dim), torch.nn.Dropout(p=self.dropout) ] ) self.model = torch.nn.Sequential(*layer_stack) def _stack_inputs( self, tensor ) -> torch.tensor: return rearrange( tensor=tensor, pattern='b s e -> (b s) e' ) def _unstack_inputs( self, tensor, b ) -> torch.tensor: return rearrange( tensor=tensor, pattern='(b s) e -> b s e', b=b ) def forward( self, inputs, **kwargs ) -> torch.tensor: inputs_stacked = self._stack_inputs(tensor=inputs) return self._unstack_inputs( tensor=self.model(inputs_stacked), b=inputs.size()[0] ) class BaseEmbedder(torch.nn.Module): def __init__(self, in_dim: int = 1024, embed_dim: int = 768, num_hidden_layers: int = 1, dropout: float = 0.1, **kwargs ) -> None: super().__init__() self.name = 'BaseEmbedder' self.training_style = 'base' self._root_training_style = 'base' self.in_dim = in_dim self.embed_dim = embed_dim self.num_hidden_layers = num_hidden_layers self.dropout = dropout self.xe_loss = torch.nn.CrossEntropyLoss(reduction='mean') self.bxe_loss = torch.nn.BCEWithLogitsLoss(reduction='mean') self.l1_loss = torch.nn.L1Loss(reduction='mean') self.l2_loss = torch.nn.MSELoss(reduction='mean') # for L2 loss # self.huber_loss = torch.nn.HuberLoss(reduction='mean', delta=1.0) # for Huber loss self.embed_model = EmbeddingModel( in_dim=self.in_dim, embed_dim=self.embed_dim, num_hidden_layers=self.num_hidden_layers, dropout=self.dropout ) self.is_decoding_mode = False def switch_decoding_mode(self, is_decoding_mode: bool=False) -> None: self.is_decoding_mode = is_decoding_mode if self.is_decoding_mode: self.training_style = 'decoding' else: self.training_style = self._root_training_style @staticmethod def _pad_tensor_left_by_n( tensor, n, pad_value ) -> torch.tensor: filling = torch.ones( ( tensor.size()[0], n, *tensor.size()[2:] ), device=tensor.device ) * pad_value return torch.cat( [ filling, tensor ], dim=1 ).to(torch.long) @staticmethod def _round_to_precision( x: torch.tensor, precision: float, ) -> torch.tensor: return torch.round(x / precision) * precision def embed_inputs( self, inputs: torch.tensor ) -> torch.tensor: return self.embed_model(inputs) def forward( self, batch: Dict[str, torch.tensor] ) -> torch.tensor: inputs_key = 'inputs' if 'inputs_embeds' not in batch else 'inputs_embeds' if self.in_dim == self.embed_dim: inputs_embeds = batch[inputs_key] else: inputs_embeds = self.embed_inputs(inputs=batch[inputs_key]) return inputs_embeds def decoding_loss( self, decoding_logits, labels, **kwargs ) -> Dict[str, torch.tensor]: # pdb.set_trace() return { 'decoding_loss': self.xe_loss( input=decoding_logits, target=labels.to(dtype=torch.long) ) } def reconstruction_loss( self, input, target, **kwargs ) -> Dict[str, torch.tensor]: return { 'reconstruction_loss': self.l2_loss( input=input, target=target ) } def prep_batch( self, batch: Dict[str, torch.tensor] ) -> Dict: batch_out = {} for key in batch: if ( torch.is_tensor(batch[key]) and key != 'labels' ): batch_out[key] = batch[key].to(torch.float) elif key == 'labels': batch_out[key] = batch['labels'].to(torch.int) else: batch_out[key] = torch.clone(batch[key]) # dummy copy of inputs to be used in forward pass batch_out['inputs_embeds'] = torch.clone(batch_out['inputs']) return batch_out def _root_loss( self, inputs, outputs, attention_mask, **kwargs ) -> Dict[str, torch.tensor]: attention_mask = torch.unsqueeze(attention_mask, -1).repeat(1,1,self.in_dim) return self.reconstruction_loss( input=torch.masked_select(outputs, attention_mask.to(torch.bool)), target=torch.masked_select(inputs, attention_mask.to(torch.bool)) ) def loss( self, batch, outputs ) -> Dict[str, torch.tensor]: if self.is_decoding_mode: losses = self.decoding_loss( **batch, **outputs ) else: losses = self._root_loss( **batch, **outputs ) if 'loss' not in losses: losses['loss'] = sum(losses.values()) return losses ================================================ FILE: src/embedder/csm.py ================================================ #/usr/bin/env python3 import pdb from typing import Dict import torch from embedder.base import BaseEmbedder class CSMEmbedder(BaseEmbedder): def __init__( self, **kwargs ) -> None: super().__init__(**kwargs) self.name = 'CSMEmbedder' self.training_style = 'CSM' assert self.training_style in {'CSM', 'decoding'}, f'{self.training_style} not supported' self._root_training_style = 'CSM' ##========= self.in_dim_for_mask = self.in_dim self.msk_embed = torch.nn.Parameter( torch.empty( size=(1, 1, self.in_dim_for_mask) ) ) self.cls_embed = torch.nn.Parameter( torch.empty( size=(1, 1, self.in_dim_for_mask) ) ) self._embeds = [ self.msk_embed, self.cls_embed ] self._init_embeds() def _init_embeds(self): for embed in self._embeds: torch.nn.init.normal_( tensor=embed, mean=0.0, std=1.0, ) def prep_batch( self, batch: Dict[str, torch.tensor], ) -> Dict[str, torch.tensor]: batch_out = dict(batch) labels = torch.clone(batch['labels']) if 'labels' in batch else None if self.training_style != 'decoding': return self.mask_inputs(batch=batch_out) batch_out = self.add_cls_embed(batch=batch_out) if labels is not None: batch_out['labels'] = labels return batch_out def mask_inputs( self, batch: Dict[str, torch.tensor], ) -> Dict[str, torch.tensor]: inputs_key = 'inputs' if 'inputs_embeds' not in batch else 'inputs_embeds' assert inputs_key in batch, f'{inputs_key} not found in batch' input_shape = batch[inputs_key].size() device = batch[inputs_key].device masking_i = torch.cat( [ torch.randint( low=1, # at least one seq value before mask! high=sum(batch['attention_mask'][i]==1), # high is exclusive, so this accounts for 0-indexing size=(1,), device=device ) for i in range(input_shape[0]) ], dim=0 ) print("masking id", masking_i) modelling_mask = torch.zeros_like( batch[inputs_key], device=device ) modelling_mask[torch.arange(input_shape[0]), masking_i] = 1 batch['modelling_mask'] = modelling_mask.to(torch.long) batch['masked_inputs'] = torch.masked_select( input=batch[inputs_key], mask=batch['modelling_mask'].to(torch.bool) ).detach().clone() batch['inputs_embeds'] = torch.where( batch['modelling_mask']==1, self.msk_embed.repeat( input_shape[0], input_shape[1], 1 ), batch[inputs_key].to(torch.float) ) batch['attention_mask'] = torch.cat( [ torch.cat( ( torch.ones( ( 1, i+1 # to account for 0-indexing in python ), device=device ), torch.zeros( ( 1, input_shape[1]-i-1 # to account for 0-indexing in python ), device=device ) ), dim = 1 ) for i in masking_i ], dim = 0 ).to(torch.long) # re-mask inputs attention_mask_expanded = torch.unsqueeze( batch['attention_mask'], dim=2 ).repeat( 1, 1, self.in_dim_for_mask ) batch["inputs_embeds"] = torch.where( attention_mask_expanded == 1, batch['inputs_embeds'], torch.zeros_like(batch['inputs_embeds']) ) return batch def add_cls_embed( self, batch: Dict[str, torch.tensor] ) -> Dict[str, torch.tensor]: inputs_key = 'inputs' if 'inputs_embeds' not in batch else 'inputs_embeds' assert inputs_key in batch, f'{inputs_key} not found in batch' batch_size = batch[inputs_key].size()[0] sequence_lengths = batch['attention_mask'].sum(dim=1) inputs_embeds = [] if 't_rs' in batch: t_rs = [] for i in range(len(sequence_lengths)): inputs_embeds.append( torch.cat( [ batch[inputs_key][i, :sequence_lengths[i], :], self.cls_embed[0], batch[inputs_key][i, sequence_lengths[i]:, :] ], dim=0 ) ) if 't_rs' in batch: t_rs.append( torch.cat( [ batch['t_rs'][i, :sequence_lengths[i]], torch.ones(1, device=batch['t_rs'].device) * -1, batch['t_rs'][i, sequence_lengths[i]:] ], dim=0 ) ) batch['inputs_embeds'] = torch.stack( inputs_embeds, dim=0 ) if 't_rs' in batch: batch['t_rs'] = torch.stack( t_rs, dim=0 ) if 'token_type_ids' in batch: batch['token_type_ids'] = self._pad_tensor_left_by_n( tensor=batch['token_type_ids'], n=1, pad_value=0 ) if 'modelling_mask' in batch: batch['modelling_mask'] = self._pad_tensor_left_by_n( tensor=batch['modelling_mask'], n=1, pad_value=0 ) if 'attention_mask' in batch: batch['attention_mask'] = self._pad_tensor_left_by_n( tensor=batch['attention_mask'], n=1, pad_value=1 ) return batch def masking_loss( self, masked_inputs, outputs, modelling_mask ) -> Dict[str, torch.tensor]: return { 'masking_loss': self.reconstruction_loss( input=torch.masked_select(outputs, modelling_mask.to(torch.bool)), target=masked_inputs )['reconstruction_loss'] } def _root_loss( self, masked_inputs, outputs, modelling_mask, **kwargs ) -> Dict[str, torch.tensor]: return self.masking_loss( masked_inputs=masked_inputs, outputs=outputs, modelling_mask=modelling_mask ) ================================================ FILE: src/embedder/csm_causal.py ================================================ #/usr/bin/env python3 import pdb from typing import Dict, Tuple import torch from embedder.base import BaseEmbedder import numpy as np class CSMEmbedder(BaseEmbedder): def __init__( self, **kwargs ) -> None: super().__init__(**kwargs) self.name = 'CSMEmbedder' self.training_style = 'CSM' assert self.training_style in {'CSM', 'decoding'}, f'{self.training_style} not supported' self._root_training_style = 'CSM' ##========= self.in_dim_for_mask = self.in_dim self.msk_embed = torch.nn.Parameter( torch.empty( size=(1, 1, self.in_dim_for_mask) ) ) self.cls_embed = torch.nn.Parameter( torch.empty( size=(1, 1, self.in_dim_for_mask) ) ) self._embeds = [ self.msk_embed, self.cls_embed ] self._init_embeds() def _init_embeds(self): for embed in self._embeds: torch.nn.init.normal_( tensor=embed, mean=0.0, std=1.0, ) def duplicate_batch(self, batch: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: duplicated_batch = {} batch_size = batch['inputs'].size()[0] times = [sum(batch['attention_mask'][i]==1) - 1 for i in range(batch_size)] for key, tensor in batch.items(): new_tensors = [] for idx in range(batch_size): rest_dims = tensor[idx].size() duplicated_tensor = tensor[idx].unsqueeze(0).expand(times[idx], *rest_dims) new_tensors.append(duplicated_tensor) duplicated_batch[key] = torch.cat(new_tensors, dim=0) return duplicated_batch, times def prep_batch( self, batch: Dict[str, torch.tensor], ) -> Dict[str, torch.tensor]: batch_out = dict(batch) labels = torch.clone(batch['labels']) if 'labels' in batch else None if self.training_style != 'decoding': duplicated_batch, duplicate_times = self.duplicate_batch(batch_out) masking_pos = [torch.arange(1, max_mask_pos_in_seq + 1) for max_mask_pos_in_seq in duplicate_times] batch_out = self.mask_inputs(batch=duplicated_batch, masking_pos=masking_pos) return batch_out batch_out = self.add_cls_embed(batch=batch_out) if labels is not None: batch_out['labels'] = labels return batch_out def mask_inputs( self, batch: Dict[str, torch.tensor], masking_pos = None ) -> Dict[str, torch.tensor]: inputs_key = 'inputs' if 'inputs_embeds' not in batch else 'inputs_embeds' assert inputs_key in batch, f'{inputs_key} not found in batch' input_shape = batch[inputs_key].size() device = batch[inputs_key].device if masking_pos is not None: masking_i = torch.cat(masking_pos, dim=0) # pdb.set_trace() else: masking_i = torch.cat( [ torch.randint( low=1, # at least one seq value before mask! high=sum(batch['attention_mask'][i]==1), # high is exclusive, so this accounts for 0-indexing size=(1,), device=device ) for i in range(input_shape[0]) ], dim=0 ) # print("masking id", masking_i) modelling_mask = torch.zeros_like( batch[inputs_key], device=device ) modelling_mask[torch.arange(input_shape[0]), masking_i] = 1 batch['modelling_mask'] = modelling_mask.to(torch.long) batch['masked_inputs'] = torch.masked_select( input=batch[inputs_key], mask=batch['modelling_mask'].to(torch.bool) ).detach().clone() # this is the actual label, masked_inputs batch['inputs_embeds'] = torch.where( batch['modelling_mask']==1, self.msk_embed.repeat( input_shape[0], input_shape[1], 1 ), batch[inputs_key].to(torch.float) ) batch['attention_mask'] = torch.cat( [ torch.cat( ( torch.ones( ( 1, i+1 # to account for 0-indexing in python ), device=device ), torch.zeros( ( 1, input_shape[1]-i-1 # to account for 0-indexing in python ), device=device ) ), dim = 1 ) for i in masking_i ], dim = 0 ).to(torch.long) # re-mask inputs attention_mask_expanded = torch.unsqueeze( batch['attention_mask'], dim=2 ).repeat( 1, 1, self.in_dim_for_mask ) batch["inputs_embeds"] = torch.where( attention_mask_expanded == 1, batch['inputs_embeds'], torch.zeros_like(batch['inputs_embeds']) ) return batch def add_cls_embed( self, batch: Dict[str, torch.tensor] ) -> Dict[str, torch.tensor]: inputs_key = 'inputs' if 'inputs_embeds' not in batch else 'inputs_embeds' assert inputs_key in batch, f'{inputs_key} not found in batch' batch_size = batch[inputs_key].size()[0] sequence_lengths = batch['attention_mask'].sum(dim=1) inputs_embeds = [] if 't_rs' in batch: t_rs = [] for i in range(len(sequence_lengths)): inputs_embeds.append( torch.cat( [ batch[inputs_key][i, :sequence_lengths[i], :], self.cls_embed[0], batch[inputs_key][i, sequence_lengths[i]:, :] ], dim=0 ) ) if 't_rs' in batch: t_rs.append( torch.cat( [ batch['t_rs'][i, :sequence_lengths[i]], torch.ones(1, device=batch['t_rs'].device) * -1, batch['t_rs'][i, sequence_lengths[i]:] ], dim=0 ) ) batch['inputs_embeds'] = torch.stack( inputs_embeds, dim=0 ) if 't_rs' in batch: batch['t_rs'] = torch.stack( t_rs, dim=0 ) if 'token_type_ids' in batch: batch['token_type_ids'] = self._pad_tensor_left_by_n( tensor=batch['token_type_ids'], n=1, pad_value=0 ) if 'modelling_mask' in batch: batch['modelling_mask'] = self._pad_tensor_left_by_n( tensor=batch['modelling_mask'], n=1, pad_value=0 ) if 'attention_mask' in batch: batch['attention_mask'] = self._pad_tensor_left_by_n( tensor=batch['attention_mask'], n=1, pad_value=1 ) return batch def masking_loss( self, masked_inputs, outputs, modelling_mask ) -> Dict[str, torch.tensor]: return { 'masking_loss': self.reconstruction_loss( input=torch.masked_select(outputs, modelling_mask.to(torch.bool)), target=masked_inputs )['reconstruction_loss'] } def _root_loss( self, masked_inputs, outputs, modelling_mask, **kwargs ) -> Dict[str, torch.tensor]: return self.masking_loss( masked_inputs=masked_inputs, outputs=outputs, modelling_mask=modelling_mask ) ================================================ FILE: src/embedder/make.py ================================================ #!/usr/bin/env python3 import torch def make_embedder( architecture: str='GPT', training_style: str='CSM', in_dim: int=1024, embed_dim: int=768, num_hidden_layers: int=1, dropout: float=0.1, n_positions: int=512 ) -> torch.nn.Module: """ Make an embedder object. The embedder is used to prepare an input batch (as generated by src.batcher) for training and compute the model's training loss, given the specified training style. Args: ----- architecture: str The model architecture to use. One of: 'GPT', 'BERT', 'NetBERT', autoencoder', 'PretrainedGPT', 'PretrainedBERT', 'LinearBaseline'. training_style: str The used training style (ie., framework). One of: 'BERT', 'CSM', 'NetBERT', 'autoencoder', 'decoding'. in_dim: int The input dimension (ie., # networks) of the parcelated BOLD data. embed_dim: int The dimension of the used embedding space. num_hidden_layers: int The number of hidden layers of the embedding model. If more than one layers are used, all layers except the last one are activated through Gelu activation (see src.base.EmbeddingModel). dropout: float Dropout rate used emebdding model. n_positions: int The maximum number of sequence elements that the model can handle (in sequence elements). Core methods: ----- prep_batch(batch): Makes all training-style specific edits of input batch (as generated by src.batcher); i.e., projection of input BOLD sequences into an embedding space (as defined by embed_dim) and addition of all training-style specific tokens to the input data loss(batch, outputs): Compute the training-style specific loss, given batch (as generated by prep_batch) and the the full model's (see src.model) output (as generated by model.forward) switch_decoding_mode(is_decoding_mode): Switch the embedder to decoding mode (is_decoding_mode=True). This function is needed to adapt a pre-trained model to a downstream decoding task. """ kwargs = { "in_dim": in_dim, "embed_dim": embed_dim, "num_hidden_layers": num_hidden_layers, "dropout": dropout, "n_positions": n_positions } if training_style == 'CSM_causal': from embedder.csm_causal import CSMEmbedder embedder = CSMEmbedder(**kwargs) elif training_style == 'CSM': from embedder.csm import CSMEmbedder embedder = CSMEmbedder(**kwargs) elif training_style == 'decoding': if architecture in {'GPT', 'PretrainedGPT2'}: from embedder.csm import CSMEmbedder embedder = CSMEmbedder(**kwargs) else: raise ValueError('unkown architecture') else: raise ValueError('unknown training style.') return embedder ================================================ FILE: src/encoder/base.py ================================================ # Authors: Pierre Guetschel # Maciej Sliwowski # # License: BSD-3 import warnings from typing import Dict, Iterable, List, Optional, Tuple from collections import OrderedDict import numpy as np import torch from torchinfo import ModelStatistics, summary def deprecated_args(obj, *old_new_args): out_args = [] for old_name, new_name, old_val, new_val in old_new_args: if old_val is None: out_args.append(new_val) else: warnings.warn( f'{obj.__class__.__name__}: {old_name!r} is depreciated. Use {new_name!r} instead.' ) if new_val is not None: raise ValueError( f'{obj.__class__.__name__}: Both {old_name!r} and {new_name!r} were specified.' ) out_args.append(old_val) return out_args class EEGModuleMixin(): """ Mixin class for all EEG models in braindecode. Parameters ---------- n_outputs : int Number of outputs of the model. This is the number of classes in the case of classification. n_chans : int Number of EEG channels. chs_info : list of dict Information about each individual EEG channel. This should be filled with ``info["chs"]``. Refer to :class:`mne.Info` for more details. n_times : int Number of time samples of the input window. input_window_seconds : float Length of the input window in seconds. sfreq : float Sampling frequency of the EEG recordings. add_log_softmax: bool Whether to use log-softmax non-linearity as the output function. LogSoftmax final layer will be removed in the future. Please adjust your loss function accordingly (e.g. CrossEntropyLoss)! Check the documentation of the torch.nn loss functions: https://pytorch.org/docs/stable/nn.html#loss-functions. Raises ------ ValueError: If some input signal-related parameters are not specified and can not be inferred. FutureWarning: If add_log_softmax is True, since LogSoftmax final layer will be removed in the future. Notes ----- If some input signal-related parameters are not specified, there will be an attempt to infer them from the other parameters. """ def __init__( self, n_outputs: Optional[int] = None, n_chans: Optional[int] = None, chs_info: Optional[List[Dict]] = None, n_times: Optional[int] = None, input_window_seconds: Optional[float] = None, sfreq: Optional[float] = None, add_log_softmax: Optional[bool] = False, ): if ( n_chans is not None and chs_info is not None and len(chs_info) != n_chans ): raise ValueError(f'{n_chans} different from {chs_info} length') if ( n_times is not None and input_window_seconds is not None and sfreq is not None and n_times != int(input_window_seconds * sfreq) ): raise ValueError( f'{n_times} different from ' f'{input_window_seconds} * {sfreq}' ) self._n_outputs = n_outputs self._n_chans = n_chans self._chs_info = chs_info self._n_times = n_times self._input_window_seconds = input_window_seconds self._sfreq = sfreq self._add_log_softmax = add_log_softmax super().__init__() @property def n_outputs(self): if self._n_outputs is None: raise ValueError('n_outputs not specified.') return self._n_outputs @property def n_chans(self): if self._n_chans is None and self._chs_info is not None: return len(self._chs_info) elif self._n_chans is None: raise ValueError( 'n_chans could not be inferred. Either specify n_chans or chs_info.' ) return self._n_chans @property def chs_info(self): if self._chs_info is None: raise ValueError('chs_info not specified.') return self._chs_info @property def n_times(self): if ( self._n_times is None and self._input_window_seconds is not None and self._sfreq is not None ): return int(self._input_window_seconds * self._sfreq) elif self._n_times is None: raise ValueError( 'n_times could not be inferred. ' 'Either specify n_times or input_window_seconds and sfreq.' ) return self._n_times @property def input_window_seconds(self): if ( self._input_window_seconds is None and self._n_times is not None and self._sfreq is not None ): return self._n_times / self._sfreq elif self._input_window_seconds is None: raise ValueError( 'input_window_seconds could not be inferred. ' 'Either specify input_window_seconds or n_times and sfreq.' ) return self._input_window_seconds @property def sfreq(self): if ( self._sfreq is None and self._input_window_seconds is not None and self._n_times is not None ): return self._n_times / self._input_window_seconds elif self._sfreq is None: raise ValueError( 'sfreq could not be inferred. ' 'Either specify sfreq or input_window_seconds and n_times.' ) return self._sfreq @property def add_log_softmax(self): if self._add_log_softmax: warnings.warn("LogSoftmax final layer will be removed! " + "Please adjust your loss function accordingly (e.g. CrossEntropyLoss)!") return self._add_log_softmax @property def input_shape(self) -> Tuple[int]: """Input data shape.""" return (1, self.n_chans, self.n_times) def get_output_shape(self) -> Tuple[int]: """Returns shape of neural network output for batch size equal 1. Returns ------- output_shape: Tuple[int] shape of the network output for `batch_size==1` (1, ...) """ with torch.inference_mode(): try: return tuple(self.forward( torch.zeros( self.input_shape, dtype=next(self.parameters()).dtype, device=next(self.parameters()).device )).shape) except RuntimeError as exc: if str(exc).endswith( ("Output size is too small", "Kernel size can't be greater than actual input size") ): msg = ( "During model prediction RuntimeError was thrown showing that at some " f"layer `{str(exc).split('.')[-1]}` (see above in the stacktrace). This " "could be caused by providing too small `n_times`/`input_window_seconds`. " "Model may require longer chunks of signal in the input than " f"{self.input_shape}." ) raise ValueError(msg) from exc raise exc mapping = None def load_state_dict(self, state_dict, *args, **kwargs): mapping = self.mapping if self.mapping else {} new_state_dict = OrderedDict() for k, v in state_dict.items(): if k in mapping: new_state_dict[mapping[k]] = v else: new_state_dict[k] = v return super().load_state_dict(new_state_dict, *args, **kwargs) def to_dense_prediction_model(self, axis: Tuple[int] = (2, 3)) -> None: """ Transform a sequential model with strides to a model that outputs dense predictions by removing the strides and instead inserting dilations. Modifies model in-place. Parameters ---------- axis: int or (int,int) Axis to transform (in terms of intermediate output axes) can either be 2, 3, or (2,3). Notes ----- Does not yet work correctly for average pooling. Prior to version 0.1.7, there had been a bug that could move strides backwards one layer. """ if not hasattr(axis, "__len__"): axis = [axis] assert all([ax in [2, 3] for ax in axis]), "Only 2 and 3 allowed for axis" axis = np.array(axis) - 2 stride_so_far = np.array([1, 1]) for module in self.modules(): if hasattr(module, "dilation"): assert module.dilation == 1 or (module.dilation == (1, 1)), ( "Dilation should equal 1 before conversion, maybe the model is " "already converted?" ) new_dilation = [1, 1] for ax in axis: new_dilation[ax] = int(stride_so_far[ax]) module.dilation = tuple(new_dilation) if hasattr(module, "stride"): if not hasattr(module.stride, "__len__"): module.stride = (module.stride, module.stride) stride_so_far *= np.array(module.stride) new_stride = list(module.stride) for ax in axis: new_stride[ax] = 1 module.stride = tuple(new_stride) def get_torchinfo_statistics( self, col_names: Optional[Iterable[str]] = ( "input_size", "output_size", "num_params", "kernel_size", ), row_settings: Optional[Iterable[str]] = ("var_names", "depth"), ) -> ModelStatistics: """Generate table describing the model using torchinfo.summary. Parameters ---------- col_names : tuple, optional Specify which columns to show in the output, see torchinfo for details, by default ("input_size", "output_size", "num_params", "kernel_size") row_settings : tuple, optional Specify which features to show in a row, see torchinfo for details, by default ("var_names", "depth") Returns ------- torchinfo.ModelStatistics ModelStatistics generated by torchinfo.summary. """ return summary( self, input_size=(1, self.n_chans, self.n_times), col_names=col_names, row_settings=row_settings, verbose=0, ) def __str__(self) -> str: return str(self.get_torchinfo_statistics()) ================================================ FILE: src/encoder/conformer_braindecode.py ================================================ # Authors: Yonghao Song # # License: BSD (3-clause) import torch import torch.nn.functional as F from einops import rearrange from einops.layers.torch import Rearrange from torch import nn, Tensor import warnings from encoder.base import EEGModuleMixin, deprecated_args class EEGConformer(EEGModuleMixin, nn.Module): """EEG Conformer. This neural network architecture recieves a traditional braindecode input. The input shape should be three-dimensional matrix representing the EEG signals. `(batch_size, n_channels, n_timesteps)`. The EEG Conformer architecture is composed of three modules: - PatchEmbedding - TransformerEncoder - ClassificationHead Notes ----- The authors recommend using data augmentation before using Conformer, e.g. sementation and recombination, Please refer to the original paper and code for more details. The model was initially tuned on 4 seconds of 250 Hz data. Please adjust the scale of the temporal convolutional layer, and the pooling layer for better performance. .. versionadded:: 0.8 We aggregate the parameters based on the parts of the models, or when the parameters were used first, e.g. n_filters_time. Parameters ---------- n_filters_time: int Number of temporal filters, defines also embedding size. filter_time_length: int Length of the temporal filter. pool_time_length: int Length of temporal pooling filter. pool_time_stride: int Length of stride between temporal pooling filters. drop_prob: float Dropout rate of the convolutional layer. att_depth: int Number of self-attention layers. att_heads: int Number of attention heads. att_drop_prob: float Dropout rate of the self-attention layer. final_fc_length: int | str The dimension of the fully connected layer. return_features: bool If True, the forward method returns the features before the last classification layer. Defaults to False. n_classes : Alias for n_outputs. n_channels : Alias for n_chans. input_window_samples : Alias for n_times. References --------------- .. [ConformerCode] Song, Y., Zheng, Q., Liu, B. and Gao, X., 2022. EEG conformer: Convolutional transformer for EEG decoding and visualization. https://github.com/eeyhsong/EEG-Conformer. """ def __init__( self, n_outputs=4, n_chans=None, n_filters_time=40, filter_time_length=25, pool_time_length=75, pool_time_stride=15, drop_prob=0.5, att_depth=6, att_heads=10, att_drop_prob=0.5, final_fc_length="auto", return_features=False, n_times=None, chs_info=None, input_window_seconds=None, sfreq=None, n_classes=None, n_channels=None, input_window_samples=None, add_log_softmax=True, ch_pos=None, is_decoding_mode=False, ): n_outputs, n_chans, n_times = deprecated_args( self, ('n_classes', 'n_outputs', n_classes, n_outputs), ('n_channels', 'n_chans', n_channels, n_chans), ('input_window_samples', 'n_times', input_window_samples, n_times) ) super().__init__( n_outputs=n_outputs, n_chans=n_chans, chs_info=chs_info, n_times=n_times, input_window_seconds=input_window_seconds, sfreq=sfreq, add_log_softmax=add_log_softmax, ) self.mapping = { 'classification_head.fc.6.weight': 'final_layer.final_layer.0.weight', 'classification_head.fc.6.bias': 'final_layer.final_layer.0.bias' } del n_outputs, n_chans, chs_info, n_times, input_window_seconds, sfreq del n_classes, n_channels, input_window_samples if not (self.n_chans <= 64): warnings.warn("This model has only been tested on no more " + "than 64 channels. no guarantee to work with " + "more channels.", UserWarning) self.patch_embedding = _PatchEmbedding( n_filters_time=n_filters_time, filter_time_length=filter_time_length, n_channels=self.n_chans, pool_time_length=pool_time_length, stride_avg_pool=pool_time_stride, drop_prob=drop_prob) if final_fc_length == "auto": assert self.n_times is not None final_fc_length = self.get_fc_size() self.transformer = _TransformerEncoder( att_depth=att_depth, emb_size=n_filters_time, att_heads=att_heads, att_drop=att_drop_prob) self.ch_pos = ch_pos self.is_decoding_mode = is_decoding_mode if self.is_decoding_mode: print("FC Layer for Classification created.") self.fc = _FullyConnected( final_fc_length=final_fc_length) self.final_layer = _FinalLayer(n_classes=self.n_outputs, return_features=return_features, add_log_softmax=self.add_log_softmax) def forward(self, x: Tensor) -> Tensor: batch, chunks, chann, time = x.size() x = x.contiguous().view(batch*chunks, chann, time) # x = x.permute(0, 2, 1, 3).contiguous().view(batch, chann, -1) x = torch.unsqueeze(x, dim=1) # add one extra dimension x = self.patch_embedding(x) x = self.transformer(x) if self.is_decoding_mode: # pdb.set_trace() x = self.fc(x) x = self.final_layer(x) return x def get_fc_size(self): out = self.patch_embedding(torch.ones((1, 1, self.n_chans, self.n_times))) size_embedding_1 = out.cpu().data.numpy().shape[1] size_embedding_2 = out.cpu().data.numpy().shape[2] return size_embedding_1 * size_embedding_2 class _PatchEmbedding(nn.Module): """Patch Embedding. The authors used a convolution module to capture local features, instead of position embedding. Parameters ---------- n_filters_time: int Number of temporal filters, defines also embedding size. filter_time_length: int Length of the temporal filter. n_channels: int Number of channels to be used as number of spatial filters. pool_time_length: int Length of temporal pooling filter. stride_avg_pool: int Length of stride between temporal pooling filters. drop_prob: float Dropout rate of the convolutional layer. Returns ------- x: torch.Tensor The output tensor of the patch embedding layer. """ def __init__( self, n_filters_time, filter_time_length, n_channels, pool_time_length, stride_avg_pool, drop_prob, ): super().__init__() self.shallownet = nn.Sequential( nn.Conv2d(1, n_filters_time, (1, filter_time_length), (1, 1)), nn.Conv2d(n_filters_time, n_filters_time, (n_channels, 1), (1, 1)), nn.BatchNorm2d(num_features=n_filters_time), nn.ELU(), nn.AvgPool2d( kernel_size=(1, pool_time_length), stride=(1, stride_avg_pool) ), # pooling acts as slicing to obtain 'patch' along the # time dimension as in ViT nn.Dropout(p=drop_prob), ) self.projection = nn.Sequential( nn.Conv2d( n_filters_time, n_filters_time, (1, 1), stride=(1, 1) ), # transpose, conv could enhance fiting ability slightly Rearrange("b d_model 1 seq -> b seq d_model"), # no need, because it will be flattened ) def forward(self, x: Tensor) -> Tensor: x = self.shallownet(x) x = self.projection(x) return x class _MultiHeadAttention(nn.Module): def __init__(self, emb_size, num_heads, dropout): super().__init__() self.emb_size = emb_size self.num_heads = num_heads self.keys = nn.Linear(emb_size, emb_size) self.queries = nn.Linear(emb_size, emb_size) self.values = nn.Linear(emb_size, emb_size) self.att_drop = nn.Dropout(dropout) self.projection = nn.Linear(emb_size, emb_size) def forward(self, x: Tensor, mask: Tensor = None) -> Tensor: queries = rearrange( self.queries(x), "b n (h d) -> b h n d", h=self.num_heads ) keys = rearrange( self.keys(x), "b n (h d) -> b h n d", h=self.num_heads ) values = rearrange( self.values(x), "b n (h d) -> b h n d", h=self.num_heads ) energy = torch.einsum("bhqd, bhkd -> bhqk", queries, keys) if mask is not None: fill_value = torch.finfo(torch.float32).min energy.mask_fill(~mask, fill_value) scaling = self.emb_size ** (1 / 2) att = F.softmax(energy / scaling, dim=-1) att = self.att_drop(att) out = torch.einsum("bhal, bhlv -> bhav ", att, values) out = rearrange(out, "b h n d -> b n (h d)") out = self.projection(out) return out class _ResidualAdd(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn def forward(self, x, **kwargs): res = x x = self.fn(x, **kwargs) x += res return x class _FeedForwardBlock(nn.Sequential): def __init__(self, emb_size, expansion, drop_p): super().__init__( nn.Linear(emb_size, expansion * emb_size), nn.GELU(), nn.Dropout(drop_p), nn.Linear(expansion * emb_size, emb_size), ) class _TransformerEncoderBlock(nn.Sequential): def __init__(self, emb_size, att_heads, att_drop, forward_expansion=4): super().__init__( _ResidualAdd( nn.Sequential( nn.LayerNorm(emb_size), _MultiHeadAttention(emb_size, att_heads, att_drop), nn.Dropout(att_drop), ) ), _ResidualAdd( nn.Sequential( nn.LayerNorm(emb_size), _FeedForwardBlock( emb_size, expansion=forward_expansion, drop_p=att_drop ), nn.Dropout(att_drop), ) ), ) class _TransformerEncoder(nn.Sequential): """Transformer encoder module for the transformer encoder. Similar to the layers used in ViT. Parameters ---------- att_depth : int Number of transformer encoder blocks. emb_size : int Embedding size of the transformer encoder. att_heads : int Number of attention heads. att_drop : float Dropout probability for the attention layers. """ def __init__(self, att_depth, emb_size, att_heads, att_drop): super().__init__( *[ _TransformerEncoderBlock(emb_size, att_heads, att_drop) for _ in range(att_depth) ] ) class _FullyConnected(nn.Module): def __init__(self, final_fc_length, drop_prob_1=0.5, drop_prob_2=0.3, out_channels=256, hidden_channels=32): """Fully-connected layer for the transformer encoder. Parameters ---------- final_fc_length : int Length of the final fully connected layer. n_classes : int Number of classes for classification. drop_prob_1 : float Dropout probability for the first dropout layer. drop_prob_2 : float Dropout probability for the second dropout layer. out_channels : int Number of output channels for the first linear layer. hidden_channels : int Number of output channels for the second linear layer. return_features : bool Whether to return input features. add_log_softmax: bool Whether to add LogSoftmax non-linearity as the final layer. """ super().__init__() self.fc = nn.Sequential( nn.Linear(final_fc_length*2, out_channels), nn.ELU(), nn.Dropout(drop_prob_1), nn.Linear(out_channels, hidden_channels), nn.ELU(), # nn.Dropout(drop_prob_2), ) def forward(self, x): x = x.contiguous().view(x.size(0)//2, -1) out = self.fc(x) return out class _FinalLayer(nn.Module): def __init__(self, n_classes, hidden_channels=32, return_features=False, add_log_softmax=True): """Classification head for the transformer encoder. Parameters ---------- n_classes : int Number of classes for classification. hidden_channels : int Number of output channels for the second linear layer. return_features : bool Whether to return input features. add_log_softmax : bool Adding LogSoftmax or not. """ super().__init__() self.final_layer = nn.Sequential( nn.Linear(hidden_channels, n_classes), ) self.return_features = return_features if add_log_softmax: classification = nn.LogSoftmax(dim=1) else: classification = nn.Identity() if not self.return_features: self.final_layer.add_module("classification", classification) def forward(self, x): if self.return_features: out = self.final_layer(x) return out, x else: out = self.final_layer(x) return out ================================================ FILE: src/model.py ================================================ #!/usr/bin/env python3 import torch from typing import Dict import warnings class Model(torch.nn.Module): """ Create Model object from embedder, decoder, and unembedder (if not None). Args ---- embedder: src.embedder.make_embedder Instance of embedder class. decoder: src.decoder.make_decoder Instance of decoder class. unembedder: src.unembedder.make_unembedder Instance of unembedder class. Only added to model if not None. Methods ---- forward(batch: Dict[str, torch.tensor]) Forward pass of model. prep_batch(batch: Dict[str, torch.tensor]) Prepare batch for forward pass. compute_loss(batch: Dict[str, torch.tensor]) Compute training loss. from_pretrained(pretrained_path: str) Load pretrained model from pretrained_path. Needs to point to pytorch_model.bin file """ def __init__( self, encoder: torch.nn.Module, embedder: torch.nn.Module, decoder: torch.nn.Module, unembedder: torch.nn.Module = None ) -> torch.nn.Module: super().__init__() self.name = f'Embedder-{embedder.name}_Decoder-{decoder.name}' self.encoder = encoder self.embedder = embedder self.decoder = decoder self.unembedder = unembedder self.is_decoding_mode = False self.ft_only_encoder = False def from_pretrained( self, pretrained_path: str ) -> None: """Load pretrained model from pretrained_path. Needs to point to pytorch_model.bin file. """ print( f'Loading pretrained model from {pretrained_path}' ) if next(self.parameters()).is_cuda: pretrained = torch.load(pretrained_path) else: pretrained = torch.load(pretrained_path, map_location=torch.device('cpu')) for k in self.state_dict(): if k in pretrained: assert pretrained[k].shape == self.state_dict()[k].shape,\ f'{k} shape mismatch between pretrained model and current model '+\ f'{pretrained[k].shape} vs {self.state_dict()[k].shape}' for k in pretrained: if k not in self.state_dict(): warnings.warn( f'Warning: /!\ Skipping {k} from {pretrained_path} '\ 'because it is not part of the current model' ) # we set strict=False, because we can be sure # that all relevant keys are in pretrained self.load_state_dict(pretrained, strict=False) def switch_ft_mode(self, ft_encoder_only=False): self.ft_only_encoder = ft_encoder_only def switch_decoding_mode( self, is_decoding_mode: bool = False, num_decoding_classes: int = None ) -> None: """Switch model to decoding model or back to training mode. Necessary to adapt pre-trained models to downstream decoding tasks. Args ---- is_decoding_mode: bool Whether to switch to decoding mode or not. num_decoding_classes: int Number of classes to use for decoding. """ self.is_decoding_mode = is_decoding_mode self.embedder.switch_decoding_mode(is_decoding_mode=is_decoding_mode) self.decoder.switch_decoding_mode( is_decoding_mode=is_decoding_mode, num_decoding_classes=num_decoding_classes ) def compute_loss( self, batch: Dict[str, torch.tensor], return_outputs: bool = False ) -> Dict[str, torch.tensor]: """ Compute training loss, based on embedder's training-style. Args ---- batch: Dict[str, torch.tensor] Input batch (as generated by src.batcher) return_outputs: bool Whether to return outputs of forward pass or not. If False, only loss is returned. Returns ---- losses: Dict[str, torch.tensor] Training losses. outputs: torch.tensor Outputs of forward pass. """ (outputs, batch) = self.forward( batch=batch, return_batch=True ) losses = self.embedder.loss( batch=batch, outputs=outputs ) return (losses, outputs) if return_outputs else losses def prep_batch( self, batch: Dict[str, torch.tensor] ) -> Dict[str, torch.tensor]: """Prepare input batch for forward pass. Calls src.embedder.prep_batch. Args ---- batch: Dict[str, torch.tensor] Input batch (as generated by src.batcher) """ return self.embedder.prep_batch(batch=dict(batch)) def forward( self, batch: Dict[str, torch.tensor], prep_batch: bool = True, return_batch: bool = False ) -> torch.tensor: """ Forward pass of model. Args ---- batch: Dict[str, torch.tensor] Input batch (as generated by src.batcher) prep_batch: bool Whether to prep batch for forward pass by calling self.embedder.prep_batch return_batch: bool Whether to return batch after forward pass or not. If False, only outputs of forward pass are returned. Returns ---- outputs: torch.tensor Outputs of forward pass. batch: Dict[str, torch.tensor] Input batch (as returned by prep_batch, if prep_batch is True) """ if self.encoder is not None: #before prep_batch masking and things, we need to first let the splitted chunks of raw input through the encoder features = self.encoder(batch['inputs']) #attempt for trying fine-tune only the encoder, but the encoder cannot combine information across chunks. if self.is_decoding_mode and self.ft_only_encoder: outputs={'outputs': features, 'decoding_logits': features} return (outputs, batch) if return_batch else outputs b, f1, f2 = features.size() nchunks = batch['inputs'].size()[1] batch['inputs'] = features.view(b//nchunks, nchunks, f1*f2) if prep_batch: if len(batch['inputs'].size()) > 3: bsize, chunk, chann, time = batch['inputs'].size() batch['inputs'] = batch['inputs'].view(bsize, chunk, chann*time) batch = self.prep_batch(batch=batch) # batch['inputs_embeds'] = batch['inputs_embeds'].view(bsize, chunk, chann, time) # print("preparing batch") else: assert 'inputs_embeds' in batch, 'inputs_embeds not in batch' # pdb.set_trace() batch['inputs_embeds'] = self.embedder(batch=batch) outputs = self.decoder(batch=batch) if self.unembedder is not None and not self.is_decoding_mode: outputs['outputs'] = self.unembedder(inputs=outputs['outputs'])['outputs'] return (outputs, batch) if return_batch else outputs ================================================ FILE: src/train_gpt.py ================================================ #!/usr/bin/env python3 """ train.py Training of models on given data. See get_args() for details on command line arguments. To train a model, multiple core components from ..src/ are invoked: src/batcher: Building PyTorch dataloaders for given data. src/embedder: Embedding of inputs into embedding space, training-style specific addition of training tokens and masking, and computation of training-style specific losses. Valid training styles: - CSM (Causal Sequence Modeling) - decoding src/decoder: Model architecture used for decoding / sequence modeling. One of the following: - GPT - PretrainedBERT (as provided by HuggingFace) src/unembedder: Projecting sequence output of decoder back to input space. src/trainer: Trainer for model; invokes instance of Hugging Face's Trainer object. src/model: Build full model from components (ie., embedder, decoder, unembedder). See make_model() below for details. """ from batcher.downstream_dataset import MotorImageryDataset import torch import os import argparse import pdb from typing import Dict import json from datetime import datetime from numpy import random import pandas as pd import numpy as np from encoder.conformer_braindecode import EEGConformer from torch import manual_seed import sys from utils import cv_split_bci, read_threshold_sub script_path = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(script_path, '../')) # from batcher.make import make_batcher from batcher.base import EEGDataset from decoder.make_decoder import make_decoder from embedder.make import make_embedder from trainer.make import make_trainer from trainer.base import Trainer from decoder.unembedder import make_unembedder os.environ["WANDB_DISABLED"] = "true" def train(config: Dict=None) -> Trainer: """Model training according to config. -> see get_args() below for all command line arguments. """ if config is None: config = get_config() if config['do_train']: os.makedirs( config["log_dir"], exist_ok=True ) resume_path = str(config["resume_from"]) if config["resume_from"] is not None else None if resume_path is not None: config_filepath = os.path.join( config["resume_from"], 'train_config.json' ) if os.path.isfile(config_filepath): print( f'Loading training config from {config_filepath}' ) with open(config_filepath, 'r') as f: config = json.load(f) else: with open(config_filepath, 'w') as f: json.dump(config, f, indent=2) checkpoints = [ int(p.split('checkpoint-')[1]) for p in os.listdir(resume_path) if 'checkpoint-' in p and os.path.isdir(os.path.join(resume_path, p)) ] last_checkpoint = max(checkpoints) print( f'Resuming training from checkpoint-{last_checkpoint} in {resume_path}' ) config["resume_from"] = os.path.join( resume_path, f'checkpoint-{last_checkpoint}' ) else: config_filepath = os.path.join( config["log_dir"], 'train_config.json' ) with open(config_filepath, 'w') as f: json.dump(config, f, indent=2) config["resume_from"] = None assert config["training_style"] in { 'CSM', 'CSM_causal', 'decoding' }, f'{config["training_style"]} is not supported.' assert config["architecture"] in { 'GPT', 'PretrainedGPT2' }, f'{config["architecture"]} is not supported.' if config['set_seed']: random.seed(config["seed"]) manual_seed(config["seed"]) #handles the input part, which are the output from encoder. if config["training_style"] == 'decoding': downstream_path = config["dst_data_path"] train_folds, test_folds = cv_split_bci(sorted(os.listdir(downstream_path))[:18]) train_files = train_folds[config['fold_i']] test_files = test_folds[config['fold_i']] train_dataset = MotorImageryDataset(train_files, sample_keys=[ 'inputs', 'attention_mask' ], chunk_len=config["chunk_len"], num_chunks=config["num_chunks"], ovlp=config["chunk_ovlp"], root_path=downstream_path, gpt_only= not config["use_encoder"]) # pdb.set_trace() test_dataset = MotorImageryDataset(test_files, sample_keys=[ 'inputs', 'attention_mask' ], chunk_len=config["chunk_len"], num_chunks=config["num_chunks"], ovlp=config["chunk_ovlp"], root_path=downstream_path, gpt_only= not config["use_encoder"]) validation_dataset = test_dataset test_dataset = train_dataset else: root_path = config["train_data_path"] files = read_threshold_sub('../inputs/sub_list2.csv', lower_bound=1000, upper_bound=1000000)# time len random.shuffle(files) train_dataset = EEGDataset(files[1000:], sample_keys=[ 'inputs', 'attention_mask' ], chunk_len=config["chunk_len"], num_chunks=config["num_chunks"], ovlp=config["chunk_ovlp"], root_path=root_path, gpt_only= not config["use_encoder"], normalization=config["do_normalization"]) validation_dataset = EEGDataset(files[:1000], sample_keys=[ 'inputs', 'attention_mask' ], chunk_len=config["chunk_len"], num_chunks=config["num_chunks"], ovlp=config["chunk_ovlp"], root_path=root_path, gpt_only= not config["use_encoder"], normalization=config["do_normalization"]) test_dataset = None def model_init(params: Dict=None): model_config = dict(config) if params is not None: model_config |= params return make_model(model_config) if config["training_style"] == "decoding": model_save_steps = config["training_steps"]*2 else: model_save_steps = config["log_every_n_steps"] trainer = make_trainer( model_init=model_init, training_style=config["training_style"], run_name=config["run_name"], output_dir=config["log_dir"], train_dataset=train_dataset, validation_dataset=validation_dataset, per_device_train_batch_size=config["per_device_training_batch_size"], per_device_eval_batch_size=config["per_device_validation_batch_size"], dataloader_num_workers=config["num_workers"], optim=config["optim"], learning_rate=config["learning_rate"], weight_decay=config["weight_decay"], adam_beta1=config["adam_beta_1"], adam_beta2=config["adam_beta_1"], adam_epsilon=config["adam_epsilon"], max_grad_norm=config["max_grad_norm"], lr_scheduler_type=config["lr_scheduler"], warmup_ratio=config["warmup_ratio"], max_steps=config["training_steps"], # num_train_epochs=5, save_steps=model_save_steps, logging_steps=config["log_every_n_steps"], eval_steps=config["eval_every_n_steps"], seed=config["seed"] if config['set_seed'] else np.random.choice(range(1, 100000)), fp16=config["fp16"], deepspeed=config["deepspeed"], ) if config['do_train']: trainer.train(resume_from_checkpoint=config["resume_from"]) trainer.save_model( os.path.join( config["log_dir"], 'model_final' ) ) if test_dataset is not None: test_prediction = trainer.predict(test_dataset) pd.DataFrame( test_prediction.metrics, index=[0] ).to_csv( os.path.join( config["log_dir"], 'test_metrics.csv' ), index=False ) np.save( os.path.join( config["log_dir"], 'test_predictions.npy' ), test_prediction.predictions ) np.save( os.path.join( config["log_dir"], 'test_label_ids.npy' ), test_prediction.label_ids ) return trainer def make_model(model_config: Dict=None): """Make model from model_config (as generated by get_config()). """ if model_config["use_encoder"] == True: chann_coords = None encoder = EEGConformer(n_outputs=model_config["num_decoding_classes"], n_chans=22, n_times=model_config['chunk_len'], ch_pos=chann_coords, is_decoding_mode=model_config["ft_only_encoder"]) #calculates the output dimension of the encoder, which is the output of transformer layer. model_config["parcellation_dim"] = ((model_config['chunk_len'] - model_config['filter_time_length'] + 1 - model_config['pool_time_length']) // model_config['stride_avg_pool'] + 1) * model_config['n_filters_time'] else: encoder = None model_config["parcellation_dim"] = model_config["chunk_len"] * 22 embedder = make_embedder( training_style=model_config["training_style"], architecture=model_config["architecture"], in_dim=model_config["parcellation_dim"], # flattened, channel x chunk length embed_dim=model_config["embedding_dim"], num_hidden_layers=model_config["num_hidden_layers_embedding_model"], dropout=model_config["dropout"], n_positions=model_config["n_positions"] ) decoder = make_decoder( architecture=model_config["architecture"], num_hidden_layers=model_config["num_hidden_layers"], embed_dim=model_config["embedding_dim"], num_attention_heads=model_config["num_attention_heads"], n_positions=model_config["n_positions"], intermediate_dim_factor=model_config["intermediate_dim_factor"], hidden_activation=model_config["hidden_activation"], dropout=model_config["dropout"] ) if model_config["embedding_dim"] != model_config["parcellation_dim"]: unembedder = make_unembedder( embed_dim=model_config["embedding_dim"], num_hidden_layers=model_config["num_hidden_layers_unembedding_model"], out_dim=model_config["parcellation_dim"], dropout=model_config["dropout"], ) else: print("No Embedder and Unembedder!") unembedder = None from model import Model model = Model( encoder=encoder, embedder=embedder, decoder=decoder, unembedder=unembedder ) if model_config["ft_only_encoder"]: model.switch_ft_mode(ft_encoder_only=True) if model_config["training_style"] == 'decoding': model.switch_decoding_mode( is_decoding_mode=True, num_decoding_classes=model_config["num_decoding_classes"] ) if model_config["pretrained_model"] is not None: model.from_pretrained(model_config["pretrained_model"]) if model_config["freeze_embedder"]: for param in model.embedder.parameters(): param.requires_grad = False if model_config["freeze_decoder"]: for param in model.decoder.parameters(): param.requires_grad = False if model_config["freeze_encoder"]: for name, param in model.encoder.named_parameters(): if 'fc.' in name \ or 'final_layer' in name: continue else: param.requires_grad = False if 'freeze_decoder_without_pooler_heads' in model_config \ and model_config["freeze_decoder_without_pooler_heads"]: for name, param in model.decoder.named_parameters(): if 'pooler_layer' in name \ or 'decoding_head' in name \ or 'is_next_head' in name: continue else: param.requires_grad = False if model_config["freeze_unembedder"] and unembedder is not None: for param in model.unembedder.parameters(): param.requires_grad = False return model def get_config(args: argparse.Namespace=None) -> Dict: """ Make config from command line arguments (as created by get_args()). Performs additional formating of args required for calling train(). """ if args is None: args = get_args().parse_args() if args.smoke_test == "True": args.per_device_training_batch_size = 2 args.per_device_validation_batch_size = 2 args.training_steps = 2 args.validation_steps = 2 args.test_steps = 2 args.log_every_n_steps = 1 if args.num_attention_heads == -1: assert ( args.embedding_dim%64 ) == 0, f'embedding-dim needs be be multiple of 64 (currently: {args.embedding_dim})' args.num_attention_heads = args.embedding_dim//64 if args.run_name == 'none': args.run_name = f'{args.architecture}' if args.architecture != 'LinearBaseline': if 'Pretrained' not in args.architecture: args.run_name += f'_lrs-{args.num_hidden_layers}' args.run_name += f'_hds-{args.num_attention_heads}' # args.run_name += f'_embd-{args.embedding_dim}' # args.run_name += f'_train-{args.training_style}' # args.run_name += f'_lr-{str(args.learning_rate).replace(".", "")[1:]}' # args.run_name += f'_bs-{args.per_device_training_batch_size}' # args.run_name += f'_drp-{str(args.dropout).replace(".", "")}' args.run_name += f'_ChunkLen-{args.chunk_len}' args.run_name += f'_NumChunks-{args.num_chunks}' args.run_name += f'_ovlp-{args.chunk_ovlp}' else: args.run_name += f'_train-{args.training_style}' args.run_name += f"_{datetime.now().strftime('%Y-%m-%d_%H')}" if args.training_style == "decoding": args.run_name += '-' + str(args.fold_i) if args.smoke_test == "True": args.run_name = f'smoke-test_{args.run_name}' args.log_dir = os.path.join(args.log_dir, args.run_name) args.wandb_mode = args.wandb_mode if args.wandb_mode in {'online', 'offline'} and args.local_rank in {-1, 0} else "disabled" config = vars(args) for arg in config: if config[arg] in {'True', 'False'}: config[arg] = config[arg] == 'True' elif config[arg] == 'none': config[arg] = None elif 'subjects_per_dataset' in arg: config[arg] = None if config[arg] == -1 else config[arg] return config def get_args() -> argparse.ArgumentParser: """Get command line arguments""" parser = argparse.ArgumentParser( description='run model training' ) # Data pipeline settings: parser.add_argument( '--train-data-path', metavar='DIR', default='../../tuh_tensors/', type=str, help='path to training data directory ' '(default: data/upstream)' ) parser.add_argument( '--dst-data-path', metavar='DIR', default="../../bci2a_egg_npz/", type=str, help='path to training data directory ' '(default: data/upstream)' ) parser.add_argument( '--parcellation-dim', metavar='INT', default=1024, type=int, help='dimension of input data parcellation (default: 1024). ' '! This is fixed for the current up-/downstream data.' ) parser.add_argument( '--pretrained-model', metavar='DIR', type=str, default='none', help='checkpoint used to initialize model weights ' '(default: none)' ) # Embedder settings: parser.add_argument( '--embedding-dim', metavar='INT', default=1024, type=int, help='dimension of input embedding ' '(default: 1024)' ) parser.add_argument( '--num-hidden-layers-embedding-model', metavar='INT', default=1, type=int, help='numer of layers of linear embedding model ' '(default: 1)' ) parser.add_argument( '--freeze-embedder', metavar='BOOL', default='False', choices=('True', 'False'), type=str, help='whether or not to freeze embedder weights during training ' '(default: False) ' ) # UnEmbedder settings: parser.add_argument( '--num-hidden-layers-unembedding-model', metavar='INT', default=1, type=int, help='numer of hidden layers for linear unembedding model ' '(default: 1)' ) parser.add_argument( '--freeze-unembedder', metavar='BOOL', default='False', choices=('True', 'False'), type=str, help='whether or not to freeze unembedder weights during training ' '(default: False) ' ) # Decoder settings: parser.add_argument( '--architecture', metavar='STR', default='GPT', choices=( 'GPT', 'PretrainedGPT2' ), type=str, help='Model architecture used for sequence modeling / decoding. ' '(default: GPT) ' ) parser.add_argument( '--num-hidden-layers', metavar='INT', default=4, type=int, help='number of hidden model layers in --architecture ' '(default: 4). ' '! Does not apply to LinearBaseline; ' '! Same number of hidden layers is used for decoder / encoder ' 'parts of autoencoder (ie., default creates encoder and decoder ' 'with 4 hidden layers each)' ) parser.add_argument( '--num-attention-heads', metavar='INT', default=-1, type=int, help='number of attention heads per transformer layer ' '(default: embedding-dim // 64). ' '! Does not apply to non-transformer models' ) parser.add_argument( '--intermediate-dim-factor', metavar='INT', default=4, type=int, help='scales feed-forward transformer layer dimension relative to ' 'embedding-dim: intermediate-dim-factor * embedding-dim ' '(default: 4)' ) parser.add_argument( '--hidden-activation', metavar='STR', default='gelu_new', choices=( 'gelu', 'gelu_new', 'relu', 'silu' ), type=str, help='type of hidden activation of transformer layers ' '(default: gelu_new); ' 'one of {"gelu", "gelu_new", "relu", "silu"}. ' '! Does not apply to non-transformer models' ) parser.add_argument( '--freeze-decoder', metavar='BOOL', default='False', choices=('True', 'False'), type=str, help='whether or not to freeze decoder model weights during training ' 'as specified by --architecture ' '(default: False) ' ) parser.add_argument( '--freeze-decoder-without-pooler-heads', metavar='BOOL', default='False', choices=('True', 'False'), type=str, help='whether or not to freeze decoder model weights during training ' 'as specified by --architecture, without pooler layer and ' ' is-next-pred / decoding heads ' '(default: False) ' ) # Trainer settings: parser.add_argument( '--resume-from', metavar='DIR', type=str, default='none', help='continue training from specified checkpoint ' '(default: none)' ) parser.add_argument( '--training-style', metavar='STR', default='CSM_causal', choices=( 'CSM', 'CSM_causal', 'decoding' ), type=str, help='training framework / style (default: CSM); ' 'one of CSM, decoding' ) parser.add_argument( '--decoding-target', metavar='STR', default='none', type=str, help='key for decoding target variable in .tar-files in --data' '(default: none). ' '! Must be specified when setting --training-style to "decoding"' ) parser.add_argument( '--num-decoding-classes', metavar='INT', default=4, type=int, help='number of decoding classes (ie., mental states) in --data ' '(default: 0). ' '! Must be specified when setting --training-style to "decoding"' ) parser.add_argument( '--training-steps', metavar='INT', default=60000, type=int, help='number of training steps to perform ' '(default: 400000)' ) parser.add_argument( '--validation-steps', metavar='INT', default=1000, type=int, help='number of validation steps to perform at evaluation time ' '(default: 1000)' ) parser.add_argument( '--test-steps', metavar='INT', default=1000, type=int, help='number of test steps to perform at test time' '(default: 2000). ' '! Test evaluation only performed if test set created by ' 'setting --n-test-subjects-per-dataset != -1' ) parser.add_argument( '--per-device-training-batch-size', metavar='INT', default=16, type=int, help='batch size during training per training device ' '(default: 64)' ) parser.add_argument( '--per-device-validation-batch-size', metavar='INT', default=16, type=int, help='batch size during evaluation per training device ' '(default: 64)' ) parser.add_argument( '--optim', metavar='STR', default='adamw_hf', type=str, help='optimizer to use for training ' '(default: adamw_hf) -> adamw from HuggingFrace transformer library. ' 'For other options see Huggingface TrainerArgs.' ) parser.add_argument( '--learning-rate', metavar='FLOAT', default=1e-4, type=float, help='maximum learning rate during training ' '(default: 1e-4)' ) parser.add_argument( '--warmup-ratio', metavar='FLOAT', default=0.01, type=float, help='warm-up steps for linear learning rate scheduler ' 'specified as fraction of --training-steps ' '(default: 0.01)' ) parser.add_argument( '--weight-decay', metavar='FLOAT', default=0.1, type=float, help='weight decay strength (indicating l2-regularisation strength) ' '(default: 0.1)' ) parser.add_argument( '--adam-beta-1', metavar='FLOAT', default=0.9, type=float, help='adam beta 1 (default: 0.9)' ) parser.add_argument( '--adam-beta-2', metavar='FLOAT', default=0.999, type=float, help='adam beta 2 (default: 0.999)' ) parser.add_argument( '--adam-epsilon', metavar='FLOAT', default=1e-8, type=float, help='adam beta 2 (default: 1e-8)' ) parser.add_argument( '--max-grad-norm', metavar='FLOAT', default=1.0, type=float, help='maximum gradient clipping norm (default: 1.0)' ) parser.add_argument( '--lr-scheduler', metavar='STR', default='linear', choices=( 'linear', 'constant_with_warmup', 'none' ), type=str, help='learning rate scheduler; ' 'one of {linear, constant_with_warmup, none} ' '(default: linear)' ) parser.add_argument( '--dropout', metavar='FLOAT', default=0.1, type=float, help='dropout ratio for hidden layers of embedder and decoder model parts ' '(default: 0.1)' ) # Logging settings: parser.add_argument( '--log-dir', metavar='DIR', type=str, default='results/models/upstream', help='path where training is logged ' '(default: results/models/upstream)' ) parser.add_argument( '--log-every-n-steps', metavar='INT', default=1000, type=int, help='frequence of logging in training steps ' '(default: 10000)' ) parser.add_argument( '--run-name', metavar='STR', type=str, default='none', help='descriptor of the training run used for logging and wandb; ' '! if set to "none", a unique identifier is automatically created' ) parser.add_argument( '--wandb-mode', metavar='STR', choices=( 'online', 'offline', 'disabled' ), default='disabled', help='track training w/ wandb online or offline or not at all ' '(default: disabled) ' '! requires setting up weights-and-bias for this machine; ' 'see: https://docs.wandb.ai/' ) parser.add_argument( '--wandb-project-name', metavar='STR', type=str, default='learning-from-brains', help='name of wandb project where data is logged ' '(default: learning-from-brains)' ) # Other settings: parser.add_argument( '--seed', metavar='INT', default=1234, type=int, help='random seed (default: 1234)' ) parser.add_argument( '--set-seed', metavar='BOOL', choices=('True', 'False'), default='True', type=str, help='whether or not to set random seed (default: True)' ) parser.add_argument( '--fp16', metavar='BOOL', choices=('True', 'False'), default='True', help='whether or not to use 16-bit precision GPU training ' '(default: True)' ) parser.add_argument( '--deepspeed', metavar='DIR', default="none", type=str, help='location of deepspeed configuration file; ' 'automatically adds deepspeed functionality to training if specified ' '(default: none)' ) parser.add_argument( '--local_rank', metavar='INT', default=-1, type=int, help='Rank of the process during distributed training ' '(default: -1)' ) parser.add_argument( '--num-workers', metavar='INT', default=8, type=int, help='number of data loading workers ' '(default: 0 -> load in main process)' ) parser.add_argument( '--plot-model-graph', metavar='BOOL', default="False", type=str, choices=('True', 'False'), help='whether or not to save an image of the model graph to log-dir ' '(default: False)' ) parser.add_argument( '--smoke-test', metavar='BOOL', default="False", type=str, choices=("True", "False"), help='whetehr or not to run training in smoke test-mode ' '(default: False)' 'If set to "True", training is restricted by setting: ' '--per-device-training_batch_size 2 ' '--per-device-validation_batch_size 2 ' '--training-steps 2 ' '--validation-steps 2 ' '--test-steps 2 ' '--log-every-n-steps 1' ) parser.add_argument( '--bold-dummy-mode', metavar='BOOL', default='False', type=str, choices=('True', 'False'), help='whether or not to replace BOLD with dummy during training; ' 'for internal testing purposes only! ' '(default: False)' ) parser.add_argument( '--do-train', metavar='BOOL', default='True', type=str, choices=('True', 'False'), help='whether or not to run training ' '(default: True). ' 'If "False", train() still returns trainer' ) parser.add_argument( '--n-positions', metavar='INT', default=512, type=int, help='maximum sequence length that transformer model might ever be used with ' '(default: 512)' ) ## EEG settings parser.add_argument( '--chunk_len', default=500, type=int) parser.add_argument( '--num_chunks', default=8, type=int) parser.add_argument( '--chunk_ovlp', default=50, type=int) parser.add_argument( '--sampling_rate', default=250, type=int) parser.add_argument( '--fold_i', default=0, type=int) parser.add_argument( '--use-encoder', metavar='BOOL', default='True', type=str, choices=('True', 'False'), help='whether to use encoder or not' ) parser.add_argument( '--do-normalization', metavar='BOOL', default='True', type=str, choices=('True', 'False'), help='whether to use encoder or not' ) parser.add_argument('--filter-time-length', metavar='INT', default=25, type=int, help='length of the temporal filter (default: 25)') parser.add_argument('--pool-time-length', metavar='INT', default=75, type=int, help='length of temporal pooling filter (default: 75)') parser.add_argument('--stride-avg-pool', metavar='INT', default=15, type=int, help='length of stride between temporal pooling filters (default: 15)') parser.add_argument('--n-filters-time', metavar='INT', default=40, type=int, help='number of temporal filters (default: 40)') parser.add_argument('--num-encoder-layers', metavar='INT', default=6, type=int, help='number of transformer layers in encoder') parser.add_argument('--eval_every_n_steps', default=200, type=int) parser.add_argument('--freeze-encoder', metavar='BOOL', default='False', choices=('True', 'False'), type=str, help='whether or not to freeze encoder weights during training ' '(default: False) ' ) parser.add_argument('--ft-only-encoder', metavar='BOOL', default='False', choices=('True', 'False'), type=str, help='finetune with only encoder or not ' '(default: False) ' ) return parser if __name__ == '__main__': trainer = train() ================================================ FILE: src/trainer/base.py ================================================ #!/usr/bin/env python3 from typing import Dict, List, Optional, Tuple from collections.abc import Mapping from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union # from apex import amp from tqdm.auto import tqdm import torch from torch import nn from transformers import Trainer from torch.utils.data import DataLoader, Dataset, RandomSampler, SequentialSampler from torch.utils.data.distributed import DistributedSampler import torch.distributed as dist from transformers.integrations import ( # isort: split hp_params, ) from transformers import PretrainedConfig from transformers.data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator from transformers.deepspeed import deepspeed_init, is_deepspeed_zero3_enabled from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_callback import ( TrainerState, ) from transformers.trainer_pt_utils import ( IterableDatasetShard, ) from transformers.trainer_utils import ( seed_worker ) from transformers.training_args import OptimizerNames, ParallelMode, TrainingArguments from transformers.utils import ( is_sagemaker_mp_enabled, is_torch_tensorrt_fx_available, is_datasets_available, is_torch_tpu_available, is_torchdynamo_available, logging, ) from transformers.utils.generic import ContextManagers logger = logging.get_logger(__name__) TRAINING_ARGS_NAME = "training_args.bin" TRAINER_STATE_NAME = "trainer_state.json" OPTIMIZER_NAME = "optimizer.pt" SCHEDULER_NAME = "scheduler.pt" SCALER_NAME = "scaler.pt" class Trainer(Trainer): def __init__( self, is_deepspeed: bool = False, **kwargs ) -> None: super().__init__(**kwargs) self.name = "Trainer" self.is_deepspeed = is_deepspeed def get_train_dataloader(self) -> DataLoader: """ Returns the training [`~torch.utils.data.DataLoader`]. Will use no sampler if `train_dataset` does not implement `__len__`, a random sampler (adapted to distributed training if necessary) otherwise. Subclass and override this method if you want to inject some custom behavior. """ if self.train_dataset is None: raise ValueError("Trainer: training requires a train_dataset.") train_dataset = self.train_dataset data_collator = self.data_collator # if is_datasets_available() and isinstance(train_dataset, datasets.Dataset): # train_dataset = self._remove_unused_columns(train_dataset, description="training") # else: # data_collator = self._get_collator_with_removed_columns(data_collator, description="training") # pdb.set_trace() if isinstance(train_dataset, torch.utils.data.IterableDataset): # if self.args.world_size > 1: # train_dataset = IterableDatasetShard( # train_dataset, # batch_size=self._train_batch_size, # drop_last=self.args.dataloader_drop_last, # num_processes=self.args.world_size, # process_index=self.args.process_index, # ) print("iterable dataset") # pdb.set_trace() return DataLoader( train_dataset, batch_size=self.args.per_device_train_batch_size, # collate_fn=data_collator, num_workers=self.args.dataloader_num_workers, pin_memory=True, ) train_sampler = self._get_train_sampler() train_loader = DataLoader( train_dataset, batch_size=self._train_batch_size, sampler=train_sampler, # collate_fn=data_collator, drop_last=self.args.dataloader_drop_last, num_workers=self.args.dataloader_num_workers, pin_memory=True, worker_init_fn=seed_worker, ) return train_loader def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader: """ Returns the evaluation [`~torch.utils.data.DataLoader`]. Subclass and override this method if you want to inject some custom behavior. Args: eval_dataset (`torch.utils.data.Dataset`, *optional*): If provided, will override `self.eval_dataset`. If it is a [`~datasets.Dataset`], columns not accepted by the `model.forward()` method are automatically removed. It must implement `__len__`. """ if eval_dataset is None and self.eval_dataset is None: raise ValueError("Trainer: evaluation requires an eval_dataset.") eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset data_collator = self.data_collator # if is_datasets_available() and isinstance(eval_dataset, datasets.Dataset): # eval_dataset = self._remove_unused_columns(eval_dataset, description="evaluation") # else: # data_collator = self._get_collator_with_removed_columns(data_collator, description="evaluation") if isinstance(eval_dataset, torch.utils.data.IterableDataset): if self.args.world_size > 1: eval_dataset = IterableDatasetShard( eval_dataset, batch_size=self.args.per_device_eval_batch_size, drop_last=self.args.dataloader_drop_last, num_processes=self.args.world_size, process_index=self.args.process_index, ) return DataLoader( eval_dataset, batch_size=self.args.eval_batch_size, # collate_fn=data_collator, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) eval_sampler = self._get_eval_sampler(eval_dataset) return DataLoader( eval_dataset, sampler=eval_sampler, batch_size=self.args.eval_batch_size, # collate_fn=data_collator, drop_last=self.args.dataloader_drop_last, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) def get_test_dataloader(self, test_dataset: Dataset) -> DataLoader: """ Returns the test [`~torch.utils.data.DataLoader`]. Subclass and override this method if you want to inject some custom behavior. Args: test_dataset (`torch.utils.data.Dataset`, *optional*): The test dataset to use. If it is a [`~datasets.Dataset`], columns not accepted by the `model.forward()` method are automatically removed. It must implement `__len__`. """ # data_collator = self.data_collator if isinstance(test_dataset, torch.utils.data.IterableDataset): if self.args.world_size > 1: test_dataset = IterableDatasetShard( test_dataset, batch_size=self.args.eval_batch_size, drop_last=self.args.dataloader_drop_last, num_processes=self.args.world_size, process_index=self.args.process_index, ) return DataLoader( test_dataset, batch_size=self.args.eval_batch_size, # collate_fn=data_collator, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) test_sampler = self._get_eval_sampler(test_dataset) # We use the same batch_size as for eval. return DataLoader( test_dataset, sampler=test_sampler, batch_size=self.args.eval_batch_size, # collate_fn=data_collator, drop_last=self.args.dataloader_drop_last, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, ) # def _inner_training_loop( # self, batch_size=None, args=None, resume_from_checkpoint=None, trial=None, ignore_keys_for_eval=None # ): # self._train_batch_size = batch_size # # Data loader and number of training steps # train_dataloader = self.get_train_dataloader() # # Setting up training control variables: # # number of training epochs: num_train_epochs # # number of training steps per epoch: num_update_steps_per_epoch # # total number of training steps to execute: max_steps # total_train_batch_size = args.train_batch_size * args.gradient_accumulation_steps * args.world_size # len_dataloader = None # if len(train_dataloader) > 0: # len_dataloader = len(train_dataloader) # num_update_steps_per_epoch = len_dataloader // args.gradient_accumulation_steps # num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1) # num_examples = self.num_examples(train_dataloader) # if args.max_steps > 0: # max_steps = args.max_steps # num_train_epochs = args.max_steps // num_update_steps_per_epoch + int( # args.max_steps % num_update_steps_per_epoch > 0 # ) # # May be slightly incorrect if the last batch in the training dataloader has a smaller size but it's # # the best we can do. # num_train_samples = args.max_steps * total_train_batch_size # else: # max_steps = math.ceil(args.num_train_epochs * num_update_steps_per_epoch) # num_train_epochs = math.ceil(args.num_train_epochs) # num_train_samples = self.num_examples(train_dataloader) * args.num_train_epochs # elif args.max_steps > 0: # Rely on max_steps when dataloader does not have a working size # max_steps = args.max_steps # # Setting a very large number of epochs so we go as many times as necessary over the iterator. # num_train_epochs = sys.maxsize # num_update_steps_per_epoch = max_steps # num_examples = total_train_batch_size * args.max_steps # num_train_samples = args.max_steps * total_train_batch_size # else: # raise ValueError( # "args.max_steps must be set to a positive value if dataloader does not have a length, was" # f" {args.max_steps}" # ) # delay_optimizer_creation = ( # self.sharded_ddp is not None # and self.sharded_ddp != ShardedDDPOption.SIMPLE # or is_sagemaker_mp_enabled() # or self.fsdp is not None # ) # if args.deepspeed: # deepspeed_engine, optimizer, lr_scheduler = deepspeed_init( # self, num_training_steps=max_steps, resume_from_checkpoint=resume_from_checkpoint # ) # self.model = deepspeed_engine.module # self.model_wrapped = deepspeed_engine # self.deepspeed = deepspeed_engine # self.optimizer = optimizer # self.lr_scheduler = lr_scheduler # elif not delay_optimizer_creation: # self.create_optimizer_and_scheduler(num_training_steps=max_steps) # self.state = TrainerState() # self.state.is_hyper_param_search = trial is not None # # Activate gradient checkpointing if needed # if args.gradient_checkpointing: # self.model.gradient_checkpointing_enable() # model = self._wrap_model(self.model_wrapped) # if is_sagemaker_mp_enabled() and resume_from_checkpoint is not None: # self._load_from_checkpoint(resume_from_checkpoint, model) # # for the rest of this function `model` is the outside model, whether it was wrapped or not # if model is not self.model: # self.model_wrapped = model # if delay_optimizer_creation: # self.create_optimizer_and_scheduler(num_training_steps=max_steps) # # Check if saved optimizer or scheduler states exist # self._load_optimizer_and_scheduler(resume_from_checkpoint) # # important: at this point: # # self.model is the Transformers Model # # self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model), etc. # # Train! # logger.info("***** Running training *****") # logger.info(f" Num examples = {num_examples}") # logger.info(f" Num Epochs = {num_train_epochs}") # logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}") # logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}") # logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}") # logger.info(f" Total optimization steps = {max_steps}") # logger.info( # f" Number of trainable parameters = {sum(p.numel() for p in model.parameters() if p.requires_grad)}" # ) # self.state.epoch = 0 # start_time = time.time() # epochs_trained = 0 # steps_trained_in_current_epoch = 0 # steps_trained_progress_bar = None # # Check if continuing training from a checkpoint # if resume_from_checkpoint is not None and os.path.isfile( # os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME) # ): # self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME)) # epochs_trained = self.state.global_step // num_update_steps_per_epoch # if not args.ignore_data_skip: # steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch) # steps_trained_in_current_epoch *= args.gradient_accumulation_steps # else: # steps_trained_in_current_epoch = 0 # logger.info(" Continuing training from checkpoint, will skip to saved global_step") # logger.info(f" Continuing training from epoch {epochs_trained}") # logger.info(f" Continuing training from global step {self.state.global_step}") # if not args.ignore_data_skip: # logger.info( # f" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} " # "batches in the first epoch. If this takes a lot of time, you can add the `--ignore_data_skip` " # "flag to your launch command, but you will resume the training on data already seen by your model." # ) # if self.is_local_process_zero() and not args.disable_tqdm: # steps_trained_progress_bar = tqdm(total=steps_trained_in_current_epoch) # steps_trained_progress_bar.set_description("Skipping the first batches") # # Update the references # self.callback_handler.model = self.model # self.callback_handler.optimizer = self.optimizer # self.callback_handler.lr_scheduler = self.lr_scheduler # self.callback_handler.train_dataloader = train_dataloader # if self.hp_name is not None and self._trial is not None: # # use self._trial because the SigOpt/Optuna hpo only call `_hp_search_setup(trial)` instead of passing trial # # parameter to Train when using DDP. # self.state.trial_name = self.hp_name(self._trial) # if trial is not None: # assignments = trial.assignments if self.hp_search_backend == HPSearchBackend.SIGOPT else trial # self.state.trial_params = hp_params(assignments) # else: # self.state.trial_params = None # # This should be the same if the state has been saved but in case the training arguments changed, it's safer # # to set this after the load. # self.state.max_steps = max_steps # self.state.num_train_epochs = num_train_epochs # self.state.is_local_process_zero = self.is_local_process_zero() # self.state.is_world_process_zero = self.is_world_process_zero() # # tr_loss is a tensor to avoid synchronization of TPUs through .item() # tr_loss = torch.tensor(0.0).to(args.device) # # _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses # self._total_loss_scalar = 0.0 # self._globalstep_last_logged = self.state.global_step # model.zero_grad() # self.control = self.callback_handler.on_train_begin(args, self.state, self.control) # # Skip the first epochs_trained epochs to get the random state of the dataloader at the right point. # if not args.ignore_data_skip: # for epoch in range(epochs_trained): # is_random_sampler = hasattr(train_dataloader, "sampler") and isinstance( # train_dataloader.sampler, RandomSampler # ) # if is_torch_less_than_1_11 or not is_random_sampler: # # We just need to begin an iteration to create the randomization of the sampler. # # That was before PyTorch 1.11 however... # for _ in train_dataloader: # break # else: # # Otherwise we need to call the whooooole sampler cause there is some random operation added # # AT THE VERY END! # _ = list(train_dataloader.sampler) # for epoch in range(epochs_trained, num_train_epochs): # if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler): # train_dataloader.sampler.set_epoch(epoch) # elif hasattr(train_dataloader, "dataset") and isinstance(train_dataloader.dataset, IterableDatasetShard): # train_dataloader.dataset.set_epoch(epoch) # epoch_iterator = train_dataloader # # Reset the past mems state at the beginning of each epoch if necessary. # if args.past_index >= 0: # self._past = None # steps_in_epoch = ( # len(epoch_iterator) # if len_dataloader is not None # else args.max_steps * args.gradient_accumulation_steps # ) # self.control = self.callback_handler.on_epoch_begin(args, self.state, self.control) # if epoch == epochs_trained and resume_from_checkpoint is not None and steps_trained_in_current_epoch == 0: # self._load_rng_state(resume_from_checkpoint) # step = -1 # for step, inputs in enumerate(epoch_iterator): # # Skip past any already trained steps if resuming training # pdb.set_trace() # if steps_trained_in_current_epoch > 0: # steps_trained_in_current_epoch -= 1 # if steps_trained_progress_bar is not None: # steps_trained_progress_bar.update(1) # if steps_trained_in_current_epoch == 0: # self._load_rng_state(resume_from_checkpoint) # continue # elif steps_trained_progress_bar is not None: # steps_trained_progress_bar.close() # steps_trained_progress_bar = None # if step % args.gradient_accumulation_steps == 0: # self.control = self.callback_handler.on_step_begin(args, self.state, self.control) # if ( # ((step + 1) % args.gradient_accumulation_steps != 0) # and args.local_rank != -1 # and args._no_sync_in_gradient_accumulation # ): # # Avoid unnecessary DDP synchronization since there will be no backward pass on this example. # with model.no_sync(): # tr_loss_step = self.training_step(model, inputs) # else: # tr_loss_step = self.training_step(model, inputs) # if ( # args.logging_nan_inf_filter # and not is_torch_tpu_available() # and (torch.isnan(tr_loss_step) or torch.isinf(tr_loss_step)) # ): # # if loss is nan or inf simply add the average of previous logged losses # tr_loss += tr_loss / (1 + self.state.global_step - self._globalstep_last_logged) # else: # tr_loss += tr_loss_step # self.current_flos += float(self.floating_point_ops(inputs)) # # Optimizer step for deepspeed must be called on every step regardless of the value of gradient_accumulation_steps # if self.deepspeed: # self.deepspeed.step() # if (step + 1) % args.gradient_accumulation_steps == 0 or ( # # last step in epoch but step is always smaller than gradient_accumulation_steps # steps_in_epoch <= args.gradient_accumulation_steps # and (step + 1) == steps_in_epoch # ): # # Gradient clipping # if args.max_grad_norm is not None and args.max_grad_norm > 0 and not self.deepspeed: # # deepspeed does its own clipping # if self.do_grad_scaling: # # Reduce gradients first for XLA # # if is_torch_tpu_available(): # # gradients = xm._fetch_gradients(self.optimizer) # # xm.all_reduce("sum", gradients, scale=1.0 / xm.xrt_world_size()) # # AMP: gradients need unscaling # self.scaler.unscale_(self.optimizer) # if is_sagemaker_mp_enabled() and args.fp16: # self.optimizer.clip_master_grads(args.max_grad_norm) # elif hasattr(self.optimizer, "clip_grad_norm"): # # Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping # self.optimizer.clip_grad_norm(args.max_grad_norm) # elif hasattr(model, "clip_grad_norm_"): # # Some models (like FullyShardedDDP) have a specific way to do gradient clipping # model.clip_grad_norm_(args.max_grad_norm) # else: # # Revert to normal clipping otherwise, handling Apex or full precision # # if is_apex_available(): # # nn.utils.clip_grad_norm_( # # amp.master_params(self.optimizer) if self.use_apex else model.parameters(), # # args.max_grad_norm, # # ) # continue # # Optimizer step # optimizer_was_run = True # if self.deepspeed: # pass # called outside the loop # elif self.do_grad_scaling: # scale_before = self.scaler.get_scale() # self.scaler.step(self.optimizer) # self.scaler.update() # scale_after = self.scaler.get_scale() # optimizer_was_run = scale_before <= scale_after # else: # self.optimizer.step() # if optimizer_was_run and not self.deepspeed: # self.lr_scheduler.step() # model.zero_grad() # self.state.global_step += 1 # self.state.epoch = epoch + (step + 1) / steps_in_epoch # self.control = self.callback_handler.on_step_end(args, self.state, self.control) # print(self.state.epoch) # pdb.set_trace() # self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval) # else: # self.control = self.callback_handler.on_substep_end(args, self.state, self.control) # pdb.set_trace() # if self.control.should_epoch_stop or self.control.should_training_stop: # print('should stop') # pdb.set_trace() # break # if step < 0: # logger.warning( # "There seems to be not a single sample in your epoch_iterator, stopping training at step" # f" {self.state.global_step}! This is expected if you're using an IterableDataset and set" # f" num_steps ({max_steps}) higher than the number of available samples." # ) # self.control.should_training_stop = True # self.control = self.callback_handler.on_epoch_end(args, self.state, self.control) # self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval) # if self.control.should_training_stop: # break # if args.past_index and hasattr(self, "_past"): # # Clean the state at the end of training # delattr(self, "_past") # logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n") # if args.load_best_model_at_end and self.state.best_model_checkpoint is not None: # # Wait for everyone to get here so we are sur the model has been saved by process 0. # # if is_torch_tpu_available(): # # xm.rendezvous("load_best_model_at_end") # if args.local_rank != -1: # dist.barrier() # # elif is_sagemaker_mp_enabled(): # # smp.barrier() # self._load_best_model() # # add remaining tr_loss # self._total_loss_scalar += tr_loss.item() # train_loss = self._total_loss_scalar / self.state.global_step # metrics = speed_metrics("train", start_time, num_samples=num_train_samples, num_steps=self.state.max_steps) # self.store_flos() # metrics["total_flos"] = self.state.total_flos # metrics["train_loss"] = train_loss # self.is_in_train = False # self._memory_tracker.stop_and_update_metrics(metrics) # self.log(metrics) # run_dir = self._get_output_dir(trial) # checkpoints_sorted = self._sorted_checkpoints(use_mtime=False, output_dir=run_dir) # # Delete the last checkpoint when save_total_limit=1 if it's different from the best checkpoint. # if self.state.best_model_checkpoint is not None and self.args.save_total_limit == 1: # for checkpoint in checkpoints_sorted: # if checkpoint != self.state.best_model_checkpoint: # logger.info(f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit") # shutil.rmtree(checkpoint) # self.control = self.callback_handler.on_train_end(args, self.state, self.control) # return TrainOutput(self.state.global_step, train_loss, metrics) # def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor: # """ # Perform a training step on a batch of inputs. # Subclass and override to inject custom behavior. # Args: # model (`nn.Module`): # The model to train. # inputs (`Dict[str, Union[torch.Tensor, Any]]`): # The inputs and targets of the model. # The dictionary will be unpacked before being fed to the model. Most models expect the targets under the # argument `labels`. Check your model's documentation for all accepted arguments. # Return: # `torch.Tensor`: The tensor with training loss on this batch. # """ # model.train() # inputs = self._prepare_inputs(inputs) # # if is_sagemaker_mp_enabled(): # # loss_mb = smp_forward_backward(model, inputs, self.args.gradient_accumulation_steps) # # return loss_mb.reduce_mean().detach().to(self.args.device) # with self.compute_loss_context_manager(): # loss = self.compute_loss(model, inputs) # if self.args.n_gpu > 1: # loss = loss.mean() # mean() to average on multi-gpu parallel training # if self.args.gradient_accumulation_steps > 1 and not self.deepspeed: # # deepspeed handles loss scaling by gradient_accumulation_steps in its `backward` # loss = loss / self.args.gradient_accumulation_steps # if self.do_grad_scaling: # self.scaler.scale(loss).backward() # # elif self.use_apex: # # with amp.scale_loss(loss, self.optimizer) as scaled_loss: # # scaled_loss.backward() # elif self.deepspeed: # # loss gets scaled under gradient_accumulation_steps in deepspeed # loss = self.deepspeed.backward(loss) # else: # loss.backward() # return loss.detach() def prediction_step( self, model, batch, prediction_loss_only: bool = False, ignore_keys: Optional[List[str]] = None ) -> Tuple[torch.tensor, torch.tensor, torch.tensor]: batch = self._move_batch_to_device(batch=batch) with torch.no_grad(): (loss, outputs) = self.compute_loss( model=model, batch=batch, return_outputs=True ) if not prediction_loss_only and 'labels' in batch: return (loss, outputs['decoding_logits'], batch['labels']) else: return (loss, outputs, None) def compute_loss( self, model, batch, return_outputs=False, **kwargs ): batch = self._move_batch_to_device(batch=batch) if isinstance( model, ( torch.nn.DataParallel, torch.nn.parallel.DistributedDataParallel ) ) or self.is_deepspeed: (losses, outputs) = model.module.compute_loss( batch=batch, return_outputs=True ) else: (losses, outputs) = model.compute_loss( batch=batch, return_outputs=True ) loss = losses['loss'] if 'loss' in losses.keys() else sum(losses.values()) return (loss, outputs) if return_outputs else loss def _move_batch_to_device( self, batch ) -> Dict[str, torch.tensor]: batch = self._prepare_inputs(batch) if "labels" in batch: batch["labels"] = batch["labels"].to(torch.long).to(batch["inputs"].device) return self._prepare_inputs(batch) ================================================ FILE: src/trainer/make.py ================================================ #!/usr/bin/env python3 import os from typing import Dict, List, Tuple import numpy as np from sklearn.metrics import accuracy_score import torch from transformers import TrainingArguments,TrainerCallback from trainer.base import Trainer class CSVLogCallback(TrainerCallback): def __init__(self): super().__init__() self.train_log_filepath = None self.eval_log_filepath = None def on_log( self, args, state, control, model, **kwargs ) -> None: if args.local_rank not in {-1, 0}: return if self.train_log_filepath is None: self.train_log_filepath = os.path.join( args.output_dir, 'train_history.csv' ) with open(self.train_log_filepath, 'a') as f: f.write('step,loss,lr\n') if self.eval_log_filepath is None: self.eval_log_filepath = os.path.join( args.output_dir, 'eval_history.csv' ) with open(self.eval_log_filepath, 'a') as f: f.write('step,loss,accuracy\n') is_eval = any('eval' in k for k in state.log_history[-1].keys()) if is_eval: with open(self.eval_log_filepath, 'a') as f: f.write('{},{},{}\n'.format( state.global_step, state.log_history[-1]['eval_loss'], state.log_history[-1]['eval_accuracy'] if 'eval_accuracy' in state.log_history[-1] else np.nan ) ) else: with open(self.train_log_filepath, 'a') as f: f.write('{},{},{}\n'.format( state.global_step, state.log_history[-1]['loss'] if 'loss' in state.log_history[-1] else state.log_history[-1]['train_loss'], state.log_history[-1]['learning_rate'] if 'learning_rate' in state.log_history[-1] else None ) ) def _cat_data_collator(features: List) -> Dict[str, torch.tensor]: if not isinstance(features[0], dict): features = [vars(f) for f in features] return { k: torch.cat( [ f[k] for f in features ] ) for k in features[0].keys() if not k.startswith('__') } def decoding_accuracy_metrics(eval_preds): preds, labels = eval_preds preds = preds.argmax(axis=-1) accuracy = accuracy_score(labels, preds) return { "accuracy": round(accuracy, 3) } def make_trainer( model_init, training_style, train_dataset, validation_dataset, do_train: bool = True, do_eval: bool = True, run_name: str = None, output_dir: str = None, overwrite_output_dir: bool = True, optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), optim: str='adamw_hf', learning_rate: float = 1e-4, weight_decay: float = 0.1, adam_beta1: float=0.9, adam_beta2: float=0.999, adam_epsilon: float=1e-8, max_grad_norm: float=1.0, per_device_train_batch_size: int = 64, per_device_eval_batch_size: int = 64, dataloader_num_workers: int = 0, max_steps: int = 400000, num_train_epochs: int = 1, lr_scheduler_type: str = 'linear', warmup_ratio: float = 0.01, evaluation_strategy: str = 'steps', prediction_loss_only: bool = False, logging_strategy: str = 'steps', save_strategy: str = 'steps', save_total_limit: int = 5, save_steps: int = 10000, logging_steps: int = 10000, eval_steps: int = None, logging_first_step: bool = True, greater_is_better: bool = True, seed: int = 1, fp16: bool = True, deepspeed: str = None, compute_metrics = None, **kwargs ) -> Trainer: """ Make a Trainer object for training a model. Returns an instance of transformers.Trainer. See the HuggingFace transformers documentation for more details on input arguments: https://huggingface.co/transformers/main_classes/trainer.html Custom arguments: --- model_init: callable A callable that does not require any arguments and returns model that is to be trained (see scripts.train.model_init) training_style: str The training style (ie., framework) to use. One of: 'BERT', 'CSM', 'NetBERT', 'autoencoder', 'decoding'. train_dataset: src.batcher.dataset The training dataset, as generated by src.batcher.dataset validation_dataset: src.batcher.dataset The validation dataset, as generated by src.batcher.dataset Returns ---- trainer: transformers.Trainer """ trainer_args = TrainingArguments( output_dir=output_dir, run_name=run_name, do_train=do_train, do_eval=do_eval, overwrite_output_dir=overwrite_output_dir, prediction_loss_only=prediction_loss_only, per_device_train_batch_size=per_device_train_batch_size, per_device_eval_batch_size=per_device_eval_batch_size, dataloader_num_workers=dataloader_num_workers, optim=optim, learning_rate=learning_rate, warmup_ratio=warmup_ratio, max_steps=max_steps, num_train_epochs=num_train_epochs, weight_decay=weight_decay, adam_beta1=adam_beta1, adam_beta2=adam_beta2, adam_epsilon=adam_epsilon, lr_scheduler_type=lr_scheduler_type, save_strategy=save_strategy, save_total_limit=save_total_limit, greater_is_better=greater_is_better, save_steps=save_steps, logging_strategy=logging_strategy, logging_first_step=logging_first_step, logging_steps=logging_steps, evaluation_strategy=evaluation_strategy, eval_steps=eval_steps if eval_steps is not None else logging_steps, seed=seed, fp16=fp16, max_grad_norm=max_grad_norm, deepspeed=deepspeed, **kwargs ) data_collator = _cat_data_collator is_deepspeed = deepspeed is not None # TODO: custom compute_metrics so far not working in multi-gpu setting compute_metrics = decoding_accuracy_metrics if training_style=='decoding' and compute_metrics is None else compute_metrics trainer = Trainer( args=trainer_args, model_init=model_init, train_dataset=train_dataset, eval_dataset=validation_dataset, data_collator=data_collator, compute_metrics=compute_metrics, optimizers=optimizers, is_deepspeed=is_deepspeed ) trainer.add_callback(CSVLogCallback) return trainer ================================================ FILE: src/utils.py ================================================ import os import pdb import shutil import h5py import numpy as np import gzip import pickle import time import pandas as pd def load_tuh_all(path): # files = os.listdir(path) filepath = [] file="" # for file in files: groups = os.listdir(path) for group in groups: if os.path.isdir(os.path.join(path, group)): subs = os.listdir(os.path.join(path, file, group)) else: continue for sub in subs: sessions = os.listdir(os.path.join(path, file, group, sub)) for sess in sessions: montages = os.listdir(os.path.join(path, file, group, sub, sess)) for mont in montages: edf_files = os.listdir(os.path.join(path, file, group, sub, sess, mont)) for edf in edf_files: full_path = os.path.join(path, file, group, sub, sess, mont, edf) filepath.append(full_path) # pdb.set_trace() shutil.move(full_path, os.path.join(path, group, sess + "_" + mont + "_" + edf)) # pdb.set_trace() # load_eeg(filepath[-1]) return filepath def load_pickle(filename): start_time = time.time() with gzip.open(filename, "rb") as file: data = pickle.load(file) print(data) end_time = time.time() print("Compressed Elapsed time:", end_time - start_time, "seconds") return data['data'], np.array(data['channel']) def read_threshold_sub(csv_file, lower_bound=2599, upper_bound=1000000): df_read = pd.read_csv(csv_file) # Access the list of filenames and time_len filenames = df_read['filename'].tolist() time_lens = df_read['time_len'].tolist() filtered_files = [] for fn, tlen in zip(filenames, time_lens): if (tlen > lower_bound) and (tlen < upper_bound): filtered_files.append(fn) return filtered_files def get_epi_files(path, epi_csv, nonepi_csv, lower_bound=2599, upper_bound=1000000): epi_full_path = [] nonepi_full_path = [] if epi_csv is not None: epi_filtered_files = read_threshold_sub(epi_csv, lower_bound, upper_bound) epi_full_path = [path + "/epilepsy_edf/" + fn for fn in epi_filtered_files] if nonepi_csv is not None: nonepi_filtered_files = read_threshold_sub(nonepi_csv, lower_bound, upper_bound) nonepi_full_path = [path + "/no_epilepsy_edf/" + fn for fn in nonepi_filtered_files] return epi_full_path + nonepi_full_path def read_sub_list(epi_list): with open(epi_list, 'r') as file: items = file.readlines() # Remove newline characters epi_subs = [item.strip() for item in items] return epi_subs def exclude_epi_subs(csv_file, epi_list, lower_bound=2599, upper_bound=1000000, files_all=None): epi_subs = read_sub_list(epi_list) group_epi_subs = epi_subs if files_all is None: all_files = read_threshold_sub(csv_file, lower_bound, upper_bound) else: all_files = files_all filtered_files = [f for f in all_files if not any(sub_id in f for sub_id in group_epi_subs)] # pdb.set_trace() return filtered_files def exclude_sz_subs(csv_file, lower_bound=2599, upper_bound=1000000, files_all=None): if files_all is None: all_files = read_threshold_sub(csv_file, lower_bound, upper_bound) else: all_files = files_all with open('sz_subs.txt', 'r') as f: sz_subs = f.readlines() filtered_files = [f for f in all_files if not any(sub_id in f for sub_id in sz_subs)] # pdb.set_trace() return filtered_files def cv_split_bci(filenames): train_folds = [] val_folds = [] for i in range(9): train_files = filenames[0:i*2] + filenames[i*2+2:] validation_files = filenames[i*2 : i*2+2] train_folds.append(train_files) val_folds.append(validation_files) return train_folds, val_folds