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