diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..8fcfee75 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +*.pyd +*.pt +MANIFEST.in +build/ +!docs/build/ +data/ +dist/ +MemTorch.egg-info/ +MemTorch_cpu.egg-info/ +**/__pycache__/ +.ipynb_checkpoints +memtorch/examples/reproduce/*.csv +tmp/ diff --git a/.readthedocs.yml b/.readthedocs.yml new file mode 100644 index 00000000..1742030e --- /dev/null +++ b/.readthedocs.yml @@ -0,0 +1,19 @@ +# Required +version: 2 + +# Build documentation in the docs/ directory with Sphinx +sphinx: + configuration: docs/conf.py + +# Optionally build your docs in additional formats such as PDF and ePub +formats: all + +# Optionally set the version of Python and requirements required to build your docs +python: + version: 3.6 + install: + - requirements: docs/requirements.txt + - method: pip + path: . + extra_requirements: + - memtorch diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..e729f086 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,22 @@ +language: python +matrix: + include: + - os: linux + sudo: required + python: 3.6 + dist: xenial + - os: linux + sudo: required + python: 3.7 + dist: xenial + - os: linux + sudo: required + python: 3.8 + dist: xenial +install: + - sudo apt-get install -y ninja-build + - python -m pip install --upgrade pip + - python -m pip install numpy pandas torch torchvision matplotlib seaborn sklearn + - python setup.py install +script: + - echo pass diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 00000000..2d105bf2 --- /dev/null +++ b/README.md @@ -0,0 +1,49 @@ +# MemTorch +![](https://img.shields.io/badge/license-GPL-blue.svg) +![DOI](https://img.shields.io/badge/DOI-TBD-brightgreen.svg) +[![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/memtorch/community) +![](https://readthedocs.org/projects/pip/badge/?version=latest) +![](https://api.travis-ci.org/coreylammie/MemTorch.svg) + +MemTorch is a *Simulation Framework for Memristive Deep Learning Systems* which integrates directly with the well-known *PyTorch* Machine Learning (ML) library, which is presented in *MemTorch: An Open-source Simulation Framework for Memristive Deep Learning Systems*. + +## Installation + To install MemTorch from source: + +``` +git clone https://github.com/coreylammie/MemTorch +cd MemTorch +python setup.py install +``` + +*If CUDA is True in setup.py, CUDA Toolkit 10.1 and Microsoft Visual C++ Build Tools are required. If CUDA is False in setup.py, Microsoft Visual C++ Build Tools are required.* + +Alternatively, MemTorch can be installed using the *pip* package-management system: + +``` +pip install memtorch # Supports CUDA and normal operation +pip install memtorch-cpu # Supports normal operation +``` + +## API & Example Usage +A complete API is avaliable [here](https://memtorch.readthedocs.io/). To learn how to use MemTorch, and to reproduce results of ‘*MemTorch: An Open-source Simulation Framework for Memristive Deep Learning Systems*’, we provide numerous Jupyter notebooks [here](memtorch/examples). + +## Current Issues and Feature Requests +Current issues, feature requests and improvements are welcome, and are tracked using: https://github.com/coreylammie/MemTorch/projects/1. + +These should be reported [here](https://github.com/coreylammie/MemTorch/issues). + +## Contributing +Please follow the "fork-and-pull" Git workflow: + 1. **Fork** the repo on GitHub + 2. **Clone** the project to your own machine + 3. **Commit** changes to your own branch + 4. **Push** your work back up to your fork + 5. Submit a **Pull request** so that we can review your changes + +*Be sure to merge the latest from 'upstream' before making a pull request*. + +## License +All code is licensed under the GNU General Public License v3.0. Details pertaining to this are available at: https://www.gnu.org/licenses/gpl-3.0.en.html. + +[![HitCount](http://hits.dwyl.io/coreylammie/MemTorch.svg)](http://hits.dwyl.io/coreylammie/MemTorch) diff --git a/docs/CaseStudy.ipynb b/docs/CaseStudy.ipynb new file mode 100644 index 00000000..9ba6f977 --- /dev/null +++ b/docs/CaseStudy.ipynb @@ -0,0 +1,513 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# A Case Study - Seizure Detection" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 1. Seizure detection dataset" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import torch\n", + "from torch.utils.data import Dataset\n", + "import torch.nn.functional as F\n", + "import torch.nn as nn\n", + "import pandas as pd\n", + "import numpy as np\n", + "import sklearn\n", + "from sklearn import preprocessing\n", + "\n", + "\n", + "class SeizureDataset(Dataset):\n", + "\n", + " def __init__(self, path_to_csv):\n", + " self.features = pd.read_csv(path_to_csv)\n", + " self.labels = self.features.pop('y')\n", + " self.features = preprocessing.scale(self.features.iloc[:, 1:], axis=0)\n", + "\n", + " def __len__(self):\n", + " return len(self.labels)\n", + "\n", + " def __getitem__(self, i):\n", + " if self.labels[i] == 1:\n", + " label = 1\n", + " else:\n", + " label = 0\n", + "\n", + " return np.asarray(self.features[i, :]).astype(np.float), label\n", + "\n", + "csv_path = 'http://archive.ics.uci.edu/ml/machine-learning-databases/00388/data.csv'\n", + "dataset = SeizureDataset(path_to_csv=csv_path)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Network architecture" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class EEGNet(nn.Module):\n", + " def __init__(self):\n", + " super(EEGNet, self).__init__()\n", + " self.fc1 = nn.Linear(178, 200)\n", + " self.batchnorm1 = nn.BatchNorm1d(200)\n", + " self.fc2 = nn.Linear(200, 200)\n", + " self.batchnorm2 = nn.BatchNorm1d(200)\n", + " self.fc3 = nn.Linear(200, 200)\n", + " self.batchnorm3 = nn.BatchNorm1d(200)\n", + " self.fc4 = nn.Linear(200, 2)\n", + " self.batchnorm4 = nn.BatchNorm1d(2)\n", + "\n", + " def forward(self, x):\n", + " x = self.batchnorm1(F.relu(self.fc1(x)))\n", + " x = self.batchnorm2(F.relu(self.fc2(x)))\n", + " x = self.batchnorm3(F.relu(self.fc3(x)))\n", + " x = self.batchnorm4(self.fc4(x))\n", + " return F.log_softmax(x, dim=1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Training methodology" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import sklearn\n", + "from sklearn.model_selection import KFold\n", + "\n", + "\n", + "init_lr = 1e-1\n", + "batch_size = 1024\n", + "\n", + "def get_device():\n", + " if torch.cuda.is_available():\n", + " device = 'cuda:0'\n", + " else:\n", + " device = 'cpu'\n", + " return device\n", + "\n", + "def adjust_lr(optimizer, epoch):\n", + " lr = init_lr * (0.1 ** (epoch // 20))\n", + " for param_group in optimizer.param_groups:\n", + " param_group['lr'] = lr\n", + "\n", + " return lr\n", + "\n", + "def train(net, train_loader, test_loader, epochs=10, fold=0):\n", + " print('fold %d' % fold)\n", + " best_f1_score = 0\n", + " for epoch in range(epochs):\n", + " lr = adjust_lr(optimizer, epoch)\n", + " running_loss = 0\n", + " for data in train_loader:\n", + " inputs, labels = data\n", + " inputs = inputs.float()\n", + " if device == 'cuda:0':\n", + " inputs = inputs.cuda()\n", + " labels = labels.cuda()\n", + "\n", + " optimizer.zero_grad()\n", + " outputs = net(inputs)\n", + " loss = criterion(outputs, labels)\n", + " loss.backward()\n", + " optimizer.step()\n", + " running_loss += loss.item()\n", + "\n", + " f1_score = test(net, test_loader)\n", + " if f1_score > best_f1_score:\n", + " torch.save(net.state_dict(), 'trained_net_fold_%d.pt' % fold)\n", + " best_f1_score = f1_score\n", + "\n", + " print('[Epoch %d] lr: %.4f f1_score: %.4f\\ttraining loss: %.4f' % (epoch + 1, lr, f1_score, running_loss / len(train_loader)))\n", + "\n", + "def test(net, test_loader):\n", + " confusion_matrix = torch.zeros(2, 2)\n", + " correct = 0\n", + " total = 0\n", + " with torch.no_grad():\n", + " for data in test_loader:\n", + " inputs, labels = data\n", + " inputs = inputs.float()\n", + " if device == 'cuda:0':\n", + " inputs = inputs.cuda()\n", + " labels = labels.cuda()\n", + "\n", + " outputs = net(inputs)\n", + " _, predicted = torch.max(outputs.data, 1)\n", + " for t, p in zip(labels.view(-1), predicted.view(-1)):\n", + " confusion_matrix[t.long(), p.long()] += 1\n", + "\n", + " total += labels.size(0)\n", + " correct += (predicted == labels).sum().item()\n", + "\n", + " f1_score = 2 * confusion_matrix[0][0] / (2 * confusion_matrix[0][0] + confusion_matrix[0][1] + confusion_matrix[1][0])\n", + " return f1_score.item()\n", + "\n", + "device = get_device()\n", + "dataset = SeizureDataset(csv_path)\n", + "torch.manual_seed(0)\n", + "kf = KFold(n_splits=5, shuffle=True)\n", + "train_loaders = []\n", + "test_loaders = []\n", + "for i, (train_index, test_index) in enumerate(kf.split(dataset)):\n", + " train_ = torch.utils.data.Subset(dataset, train_index)\n", + " test_ = torch.utils.data.Subset(dataset, test_index)\n", + " train_loaders.append(torch.utils.data.DataLoader(train_, batch_size=batch_size, shuffle=True))\n", + " test_loaders.append(torch.utils.data.DataLoader(test_, batch_size=batch_size, shuffle=False))\n", + "\n", + "torch.manual_seed(torch.initial_seed())\n", + "torch.save(test_loaders, 'test_loaders.pth')\n", + "assert(len(train_loaders) == len(test_loaders))\n", + "\n", + "# Determine the baseline F1 score\n", + "df = pd.DataFrame(columns=['indentifier', 'fold', 'f1_score'])\n", + "for indentifier in range(100):\n", + " test_loaders = torch.load('test_loaders.pth')\n", + " for fold in range(len(test_loaders)):\n", + " net = EEGNet()\n", + " if torch.cuda.is_available():\n", + " net = torch.nn.DataParallel(net)\n", + "\n", + " f1_score = test(net, test_loaders[fold])\n", + " df = df.append({'indentifier': indentifier, 'fold': fold, 'f1_score': f1_score}, ignore_index=True)\n", + "\n", + " df.to_csv('baseline.csv', index=False)\n", + "\n", + "# Determine the F1 score\n", + "for fold in range(len(train_loaders)):\n", + " net = EEGNet().to(device)\n", + " criterion = torch.nn.CrossEntropyLoss()\n", + " optimizer = torch.optim.Adam(net.parameters(), lr=init_lr)\n", + " train(net, train_loaders[fold], test_loaders[fold], epochs=50, fold=fold)\n", + "\n", + "fold_f1_scores = []\n", + "for fold in range(len(train_loaders)):\n", + " net = EEGNet().to(device)\n", + " net.load_state_dict(torch.load('trained_net_fold_%d.pt' % fold), strict=True)\n", + " fold_f1_scores.append(test(net, test_loaders[fold]))\n", + " print('f1_score of fold %d: %0.4f' % (fold, fold_f1_scores[fold]))\n", + "\n", + "print('baseline -> mean: %0.4f\\tstddev: %0.4f' % (np.mean(df['f1_score'].values), np.std(df['f1_score'].values)))\n", + "print('trained -> mean: %0.4f\\tstddev: %0.4f' % (np.mean(fold_f1_scores), np.std(fold_f1_scores)))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. Network conversion" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import memtorch\n", + "from memtorch.mn.Module import patch_model\n", + "from memtorch.map.Parameter import naive_map\n", + "from memtorch.bh.crossbar.Program import naive_program\n", + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "import copy\n", + "\n", + "\n", + "test_loaders = torch.load('test_loaders.pth')\n", + "\n", + "# Determine the first baseline F1 score\n", + "df = pd.DataFrame(columns=['indentifier', 'fold', 'f1_score'])\n", + "for indentifier in range(100):\n", + " for fold in range(len(test_loaders)):\n", + " net = EEGNet()\n", + " net.load_state_dict(torch.load('trained_net_fold_%d.pt' % fold), strict=True)\n", + " if torch.cuda.is_available():\n", + " net = torch.nn.DataParallel(net)\n", + "\n", + " patched_net = patch_model(copy.deepcopy(net),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None,\n", + " scheme=memtorch.bh.Scheme.DoubleColumn)\n", + "\n", + " for i, (name, m) in enumerate(list(patched_net.named_modules())):\n", + " if isinstance(m, memtorch.mn.Linear):\n", + " m.crossbars[0].conductance_matrix = m.crossbars[0].conductance_matrix.uniform_(1 / 2.5e3, 1 / 100)\n", + " m.crossbars[1].conductance_matrix = m.crossbars[1].conductance_matrix.uniform_(1 / 2.5e3, 1 / 100)\n", + "\n", + " patched_net.tune_()\n", + " f1_score = test(patched_net, test_loaders[fold])\n", + " df = df.append({'indentifier': indentifier, 'fold': fold, 'f1_score': f1_score}, ignore_index=True)\n", + "\n", + " df.to_csv('baseline_variability.csv', index=False)\n", + "\n", + "# Determine the second baseline F1 score\n", + "df_2 = pd.DataFrame(columns=['indentifier', 'fold', 'f1_score'])\n", + "for indentifier in range(100):\n", + " for fold in range(len(test_loaders)):\n", + " net = EEGNet()\n", + " if torch.cuda.is_available():\n", + " net = torch.nn.DataParallel(net)\n", + "\n", + " patched_net = patch_model(copy.deepcopy(net),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None,\n", + " scheme=memtorch.bh.Scheme.DoubleColumn)\n", + "\n", + " for i, (name, m) in enumerate(list(patched_net.named_modules())):\n", + " if isinstance(m, memtorch.mn.Linear):\n", + " m.crossbars[0].conductance_matrix = m.crossbars[0].conductance_matrix.uniform_(1 / 2.5e3, 1 / 100)\n", + " m.crossbars[1].conductance_matrix = m.crossbars[1].conductance_matrix.uniform_(1 / 2.5e3, 1 / 100)\n", + "\n", + " f1_score = test(patched_net, test_loaders[fold])\n", + " df_2 = df_2.append({'indentifier': indentifier, 'fold': fold, 'f1_score': f1_score}, ignore_index=True)\n", + "\n", + " df_2.to_csv('baseline_variability_no_tune.csv', index=False)\n", + "\n", + "# Determine the F1 score\n", + "fold_f1_scores = []\n", + "for fold in range(len(test_loaders)):\n", + " net = EEGNet()\n", + " net.load_state_dict(torch.load('trained_net_fold_%d.pt' % fold), strict=False)\n", + " if torch.cuda.is_available():\n", + " net = torch.nn.DataParallel(net)\n", + "\n", + " reference_memristor = memtorch.bh.memristor.VTEAM\n", + " reference_memristor_params = {'time_series_resolution': 1e-6,\n", + " 'alpha_off': 1,\n", + " 'alpha_on': 3,\n", + " 'v_off': 0.5,\n", + " 'v_on': -0.53,\n", + " 'r_off': 2.5e3,\n", + " 'r_on': 100,\n", + " 'k_off': 4.03e-8,\n", + " 'k_on': -80,\n", + " 'd': 10e-9,\n", + " 'x_on': 0,\n", + " 'x_off': 10e-9}\n", + "\n", + " patched_net = patch_model(net,\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None,\n", + " scheme=memtorch.bh.Scheme.DoubleColumn)\n", + "\n", + " patched_net.tune_()\n", + " f1_score = test(patched_net, test_loaders[fold])\n", + " fold_f1_scores.append(f1_score)\n", + "\n", + "tuned_baseline = np.mean(df['f1_score'].values)\n", + "print('baseline -> mean: %0.4f\\tstddev: %0.4f' % (np.mean(df_2['f1_score'].values), np.std(df_2['f1_score'].values))) \n", + "print('tuned baseline -> mean: %0.4f\\tstddev: %0.4f' % (np.mean(df['f1_score'].values), np.std(df['f1_score'].values)))\n", + "print('trained and tuned -> mean: %0.4f\\tstddev: %0.4f' % (np.mean(fold_f1_scores), np.std(fold_f1_scores)))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "# Plot the hysteresis loop\n", + "palette = [\"#DA4453\", \"#8CC152\", \"#4A89DC\", \"#F6BB42\", \"#B600B0\", \"#535353\"]\n", + "f = plt.figure(figsize=(16/3, 4))\n", + "plt.title('Hysteresis Loop')\n", + "plt.xlabel('Voltage (V)')\n", + "plt.ylabel('Current (A)')\n", + "j = 0\n", + "for i in range(10):\n", + " j = j + 1\n", + " if j == 6:\n", + " j = 0\n", + "\n", + " memristor = reference_memristor(**reference_memristor_params)\n", + " voltage_signal, current_signal = memristor.plot_hysteresis_loop(duration=2, voltage_signal_amplitude=1, voltage_signal_frequency = 0.5, return_result=True)\n", + " plt.plot(voltage_signal, current_signal, color=palette[j])\n", + "\n", + "plt.grid()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 5. Device-to-device variability investigation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Determine the F1 score\n", + "df = pd.DataFrame(columns=['sigma', 'mean', 'std'])\n", + "sigma_values = np.linspace(0, 500, 21)\n", + "for sigma in sigma_values:\n", + " f1_scores = []\n", + " for fold in range(len(test_loaders)):\n", + " net = EEGNet()\n", + " net.load_state_dict(torch.load('trained_net_fold_%d.pt' % fold), strict=True)\n", + " if torch.cuda.is_available():\n", + " net = torch.nn.DataParallel(net)\n", + "\n", + " non_linear_reference_memristor_params = {'time_series_resolution': 1e-6,\n", + " 'alpha_off': 1,\n", + " 'alpha_on': 3,\n", + " 'v_off': 0.5,\n", + " 'v_on': -0.53,\n", + " 'r_off': memtorch.bh.StochasticParameter(2.5e3, std=sigma*2, min=1),\n", + " 'r_on': memtorch.bh.StochasticParameter(100, std=sigma, min=1),\n", + " 'k_off': 4.03e-8,\n", + " 'k_on': -80,\n", + " 'd': 10e-9,\n", + " 'x_on': 0,\n", + " 'x_off': 10e-9}\n", + " \n", + " patched_net = patch_model(copy.deepcopy(net),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=non_linear_reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None,\n", + " scheme=memtorch.bh.Scheme.DoubleColumn)\n", + "\n", + " patched_net.tune_()\n", + " f1_score = test(patched_net, test_loaders[fold])\n", + " f1_scores.append(f1_score)\n", + "\n", + " df = df.append({'sigma': sigma, 'mean': np.mean(f1_scores), 'std': np.std(f1_scores)}, ignore_index=True)\n", + "\n", + "df.to_csv('variability.csv', index=False)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "f = plt.figure(figsize=(16/3, 4))\n", + "plt.axhline(y=tuned_baseline, color='k', linestyle='--', zorder=1)\n", + "b = plt.bar(df['sigma'], df['mean'], width=12.5, zorder=2)\n", + "plt.xlabel('$\\sigma$')\n", + "plt.ylabel('F1 Score')\n", + "for bar in b:\n", + " bar.set_edgecolor('black')\n", + " bar.set_facecolor(palette[0])\n", + " bar.set_linewidth(1)\n", + "\n", + "f.tight_layout()\n", + "plt.grid()\n", + "plt.ylim([0.9, 1.0])\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 6. Non-linear IV characteristics investigation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Determine the F1 score\n", + "df = pd.DataFrame(columns=['sigma', 'mean', 'std'])\n", + "sigma_values = np.linspace(0, 500, 11)\n", + "f1_scores = []\n", + "for fold in range(len(test_loaders)):\n", + " net = EEGNet()\n", + " net.load_state_dict(torch.load('trained_net_fold_%d.pt' % fold), strict=False)\n", + " if torch.cuda.is_available():\n", + " net = torch.nn.DataParallel(net)\n", + "\n", + " patched_net = patch_model(net,\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None,\n", + " scheme=memtorch.bh.Scheme.DoubleColumn)\n", + "\n", + " patched_net = apply_nonidealities(patched_net,\n", + " non_idealities=[memtorch.bh.nonideality.NonIdeality.NonLinear],\n", + " sweep_duration=2,\n", + " sweep_voltage_signal_amplitude=1,\n", + " sweep_voltage_signal_frequency=0.5)\n", + "\n", + " patched_net.tune_()\n", + " f1_score = test(patched_net, test_loaders[fold])\n", + " f1_scores.append(f1_score)\n", + "\n", + "print('mean: %0.4f\\tstddev: %0.4f' % (np.mean(f1_scores), np.std(f1_scores))) " + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 00000000..d0c3cbf1 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = source +BUILDDIR = build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/NovelSimulations.ipynb b/docs/NovelSimulations.ipynb new file mode 100644 index 00000000..1d9f7e58 --- /dev/null +++ b/docs/NovelSimulations.ipynb @@ -0,0 +1,687 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Novel Simulations" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 1. Define and train a VGG Convolutional Neural Network (CNN) using CIFAR-10" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch.optim as optim\n", + "from torch.autograd import Variable\n", + "import memtorch\n", + "from memtorch.utils import LoadCIFAR10\n", + "\n", + "\n", + "class Net(nn.Module):\n", + " def __init__(self, inflation_ratio=1):\n", + " super(Net, self).__init__()\n", + " self.conv0 = nn.Conv2d(in_channels=3, out_channels=128*inflation_ratio, kernel_size=3, stride=1, padding=1)\n", + " self.bn0 = nn.BatchNorm2d(num_features=128*inflation_ratio)\n", + " self.act0 = nn.ReLU()\n", + " self.conv1 = nn.Conv2d(in_channels=128*inflation_ratio, out_channels=128*inflation_ratio, kernel_size=3, padding=1)\n", + " self.bn1 = nn.BatchNorm2d(num_features=128*inflation_ratio)\n", + " self.act1 = nn.ReLU()\n", + " self.conv2 = nn.Conv2d(in_channels=128*inflation_ratio, out_channels=256*inflation_ratio, kernel_size=3, padding=1)\n", + " self.bn2 = nn.BatchNorm2d(num_features=256*inflation_ratio)\n", + " self.act2 = nn.ReLU()\n", + " self.conv3 = nn.Conv2d(in_channels=256*inflation_ratio, out_channels=256*inflation_ratio, kernel_size=3, padding=1)\n", + " self.bn3 = nn.BatchNorm2d(num_features=256*inflation_ratio)\n", + " self.act3 = nn.ReLU()\n", + " self.conv4 = nn.Conv2d(in_channels=256*inflation_ratio, out_channels=512*inflation_ratio, kernel_size=3, padding=1)\n", + " self.bn4 = nn.BatchNorm2d(num_features=512*inflation_ratio)\n", + " self.act4 = nn.ReLU()\n", + " self.conv5 = nn.Conv2d(in_channels=512*inflation_ratio, out_channels=512, kernel_size=3, padding=1)\n", + " self.bn5 = nn.BatchNorm2d(num_features=512)\n", + " self.act5 = nn.ReLU()\n", + " self.fc6 = nn.Linear(in_features=512*4*4, out_features=1024)\n", + " self.bn6 = nn.BatchNorm1d(num_features=1024)\n", + " self.act6 = nn.ReLU()\n", + " self.fc7 = nn.Linear(in_features=1024, out_features=1024)\n", + " self.bn7 = nn.BatchNorm1d(num_features=1024)\n", + " self.act7 = nn.ReLU()\n", + " self.fc8 = nn.Linear(in_features=1024, out_features=10)\n", + "\n", + " def forward(self, input):\n", + " x = self.act0(self.bn0(self.conv0(input)))\n", + " x = self.act1(self.bn1(F.max_pool2d(self.conv1(x), 2)))\n", + " x = self.act2(self.bn2(self.conv2(x)))\n", + " x = self.act3(self.bn3(F.max_pool2d(self.conv3(x), 2)))\n", + " x = self.act4(self.bn4(self.conv4(x)))\n", + " x = self.act5(self.bn5(F.max_pool2d(self.conv5(x), 2)))\n", + " x = x.view(x.size(0), -1)\n", + " x = self.act6(self.bn6(self.fc6(x)))\n", + " x = self.act7(self.bn7(self.fc7(x)))\n", + " return self.fc8(x)\n", + " \n", + " \n", + "def test(model, test_loader):\n", + " correct = 0\n", + " for batch_idx, (data, target) in enumerate(test_loader): \n", + " output = model(data.to(device))\n", + " pred = output.data.max(1)[1]\n", + " correct += pred.eq(target.to(device).data.view_as(pred)).cpu().sum()\n", + "\n", + " return 100. * float(correct) / float(len(test_loader.dataset))\n", + "\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "epochs = 50\n", + "train_loader, validation_loader, test_loader = LoadCIFAR10(batch_size=256, validation=False)\n", + "model = Net().to(device)\n", + "if device == 'cuda':\n", + " model = torch.nn.DataParallel(model)\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "learning_rate = 1e-2\n", + "optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n", + "best_accuracy = 0\n", + "for epoch in range(0, epochs):\n", + " print('Epoch: [%d]\\t\\t' % (epoch + 1), end='')\n", + " if epoch % 20 == 0:\n", + " learning_rate = learning_rate * 0.1\n", + " for param_group in optimizer.param_groups:\n", + " param_group['lr'] = learning_rate\n", + "\n", + " model.train()\n", + " for batch_idx, (data, target) in enumerate(train_loader):\n", + " optimizer.zero_grad()\n", + " output = model(data.to(device))\n", + " loss = criterion(output, target.to(device))\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " accuracy = test(model, test_loader)\n", + " print('%2.2f%%' % accuracy)\n", + " if accuracy > best_accuracy:\n", + " torch.save(model.state_dict(), 'trained_model.pt')\n", + " best_accuracy = accuracy" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Load and test the network" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import copy\n", + "import pandas as pd\n", + "import matplotlib\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "\n", + "model = Net().to(device)\n", + "try:\n", + " model.load_state_dict(torch.load('trained_model.pt'), strict=False)\n", + "except:\n", + " raise Exception('trained_model.pt has not been found.')\n", + " \n", + "print('Test Set Accuracy: \\t%2.2f%%' % test(model, test_loader))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Import seaborn and define an appropriate color-palette" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "\n", + "\n", + "palette = [\"#DA4453\", \"#8CC152\", \"#4A89DC\", \"#F6BB42\", \"#B600B0\", \"#535353\"]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. Device-device variability investigation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from memtorch.mn.Module import patch_model\n", + "from memtorch.map.Parameter import naive_map\n", + "from memtorch.bh.crossbar.Program import naive_program\n", + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "\n", + "\n", + "def trial(r_on, r_off, sigma):\n", + " model_ = copy.deepcopy(model)\n", + " reference_memristor = memtorch.bh.memristor.VTEAM\n", + " reference_memristor_params = {'time_series_resolution': 1e-10,\n", + " 'r_off': memtorch.bh.StochasticParameter(r_off, std=sigma*2, min=1),\n", + " 'r_on': memtorch.bh.StochasticParameter(r_on, std=sigma, min=1)}\n", + "\n", + " patched_model = patch_model(copy.deepcopy(model_),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear, torch.nn.Conv2d],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None)\n", + " \n", + " patched_model.tune_()\n", + " return test(patched_model, test_loader)\n", + "\n", + "df = pd.DataFrame(columns=['sigma', 'test_set_accuracy'])\n", + "r_on = 200\n", + "r_off = 500\n", + "sigma_values = np.linspace(0, 100, 21)\n", + "for sigma in sigma_values:\n", + " df = df.append({'sigma': sigma, 'test_set_accuracy': trial(r_on, r_off, sigma)}, ignore_index=True)\n", + " \n", + "df.to_csv('variability.csv', index=False)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "df = pd.read_csv('variability.csv')\n", + "f = plt.figure()\n", + "plt.axhline(y=10, color='k', linestyle='--', zorder=1)\n", + "b = plt.bar(df['sigma'], df['test_set_accuracy'], width=2.5, zorder=2)\n", + "plt.xlabel('$\\sigma$')\n", + "plt.ylabel('CIFAR-10 Test-set Accuracy (%)')\n", + "for bar in b:\n", + " bar.set_edgecolor('black')\n", + " bar.set_facecolor(palette[0])\n", + " bar.set_linewidth(1)\n", + " \n", + "f.tight_layout()\n", + "plt.grid()\n", + "plt.savefig(\"P1.svg\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 5. Finite conductance states investigation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from memtorch.mn.Module import patch_model\n", + "from memtorch.map.Parameter import naive_map\n", + "from memtorch.bh.crossbar.Program import naive_program\n", + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "\n", + "\n", + "def trial(r_on, r_off, finite_states):\n", + " model_ = copy.deepcopy(model)\n", + " reference_memristor = memtorch.bh.memristor.VTEAM\n", + " reference_memristor_params = {'time_series_resolution': 1e-10,\n", + " 'r_off': r_off,\n", + " 'r_on': r_on}\n", + "\n", + " patched_model = patch_model(copy.deepcopy(model_),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear, torch.nn.Conv2d],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None)\n", + " \n", + " patched_model = apply_nonidealities(patched_model,\n", + " non_idealities=[memtorch.bh.nonideality.NonIdeality.FiniteConductanceStates],\n", + " conductance_states = int(finite_states))\n", + " \n", + " patched_model.tune_()\n", + " return test(patched_model, test_loader)\n", + "\n", + "df = pd.DataFrame(columns=['finite_states', 'test_set_accuracy'])\n", + "r_on = 200\n", + "r_off = 500\n", + "finite_state_values = np.linspace(1, 10, 10)\n", + "for finite_states in finite_state_values:\n", + " df = df.append({'finite_states': finite_states, 'test_set_accuracy': trial(r_on, r_off, finite_states)}, ignore_index=True)\n", + " \n", + "df.to_csv('finite_states.csv', index=False)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "df = pd.read_csv('finite_states.csv')\n", + "f = plt.figure()\n", + "plt.axhline(y=10, color='k', linestyle='--', zorder=1)\n", + "b = plt.bar(df['finite_states'], df['test_set_accuracy'], width=0.5, zorder=2)\n", + "plt.xlabel('Number of Finite States')\n", + "plt.ylabel('CIFAR-10 Test-set Accuracy (%)')\n", + "plt.xticks(df['finite_states'])\n", + "for bar in b:\n", + " bar.set_edgecolor('black')\n", + " bar.set_facecolor(palette[0])\n", + " bar.set_linewidth(1)\n", + " \n", + "f.tight_layout()\n", + "plt.grid()\n", + "plt.savefig(\"P2.svg\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 6. Device failure investigation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from memtorch.mn.Module import patch_model\n", + "from memtorch.map.Parameter import naive_map\n", + "from memtorch.bh.crossbar.Program import naive_program\n", + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "\n", + "\n", + "def trial(r_on, r_off, lrs_proportion, hrs_proportion):\n", + " model_ = copy.deepcopy(model)\n", + " reference_memristor = memtorch.bh.memristor.VTEAM\n", + " reference_memristor_params = {'time_series_resolution': 1e-10,\n", + " 'r_off': r_off,\n", + " 'r_on': r_on}\n", + "\n", + " patched_model = patch_model(copy.deepcopy(model_),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear, torch.nn.Conv2d],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None)\n", + " \n", + " patched_model = apply_nonidealities(patched_model,\n", + " non_idealities=[memtorch.bh.nonideality.NonIdeality.DeviceFaults],\n", + " lrs_proportion=lrs_proportion,\n", + " hrs_proportion=hrs_proportion,\n", + " electroform_proportion=0)\n", + " \n", + " patched_model.tune_()\n", + " return test(patched_model, test_loader)\n", + "\n", + "df_lrs_hrs = pd.DataFrame(columns=['failure_percentage', 'test_set_accuracy'])\n", + "df_lrs = pd.DataFrame(columns=['failure_percentage', 'test_set_accuracy'])\n", + "df_hrs = pd.DataFrame(columns=['failure_percentage', 'test_set_accuracy'])\n", + "r_on = 200\n", + "r_off = 500\n", + "failures = np.linspace(0, 0.25, 11)\n", + "\n", + "for failure in failures:\n", + " df_lrs_hrs = df_lrs_hrs.append({'failure_percentage': failure, 'test_set_accuracy': trial(r_on, r_off, failure, failure)}, ignore_index=True)\n", + " df_lrs = df_lrs.append({'failure_percentage': failure, 'test_set_accuracy': trial(r_on, r_off, failure, 0)}, ignore_index=True) \n", + " df_hrs = df_hrs.append({'failure_percentage': failure, 'test_set_accuracy': trial(r_on, r_off, 0, failure)}, ignore_index=True) \n", + " \n", + "df_lrs_hrs.to_csv('failure_lrs_hrs.csv', index=False)\n", + "df_lrs.to_csv('failure_lrs.csv', index=False)\n", + "df_hrs.to_csv('failure_hrs.csv', index=False)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "from matplotlib.ticker import FormatStrFormatter\n", + "\n", + "\n", + "df_lrs_hrs = pd.read_csv('failure_lrs_hrs.csv')\n", + "df_lrs = pd.read_csv('failure_lrs.csv')\n", + "df_hrs = pd.read_csv('failure_hrs.csv')\n", + "f = plt.figure()\n", + "plt.axhline(y=10, color='k', linestyle='--', zorder=1)\n", + "concat = pd.concat([df_lrs_hrs['failure_percentage'], \n", + " df_lrs_hrs['test_set_accuracy'], \n", + " df_lrs['test_set_accuracy'], \n", + " df_hrs['test_set_accuracy']], \n", + " axis=1)\n", + "concat.columns = ['failure_percentage', 'lrs_hrs', 'lrs', 'hrs']\n", + "data = pd.DataFrame(columns=['failure_percentage', 'state', 'test_set_accuracy'])\n", + "for index, row in concat.iterrows():\n", + " data = data.append({'failure_percentage': row['failure_percentage'] * 100, 'state': 'lrs_hrs', 'test_set_accuracy': row['lrs_hrs']}, ignore_index=True)\n", + " data = data.append({'failure_percentage': row['failure_percentage'] * 100, 'state': 'lrs', 'test_set_accuracy': row['lrs']}, ignore_index=True)\n", + " data = data.append({'failure_percentage': row['failure_percentage'] * 100, 'state': 'hrs', 'test_set_accuracy': row['hrs']}, ignore_index=True)\n", + " \n", + "data['state'] = data['state'].map({'lrs_hrs': '$R_{ON}$ and $R_{OFF}$', 'lrs': '$R_{ON}$', 'hrs': '$R_{OFF}$'})\n", + "h = sns.barplot(x=\"failure_percentage\", hue=\"state\", y=\"test_set_accuracy\", data=data, zorder=2, edgecolor='black', linewidth='1', palette=sns.color_palette(palette), saturation=1)\n", + "plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%1.1f'))\n", + "plt.xticks(np.arange(11), np.arange(0, 25 + 2.5, step=2.5))\n", + "h.legend(loc=1)\n", + "plt.xlabel('Device Failure (%)')\n", + "plt.ylabel('CIFAR-10 Test-set Accuracy (%)') \n", + "f.tight_layout()\n", + "plt.grid()\n", + "plt.savefig(\"P3.svg\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 7. First novel simulation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from memtorch.mn.Module import patch_model\n", + "from memtorch.map.Parameter import naive_map\n", + "from memtorch.bh.crossbar.Program import naive_program\n", + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "\n", + "\n", + "def trial(num_conductance_states, g_ratio, sigma):\n", + " model_ = copy.deepcopy(model)\n", + " r_on = 200\n", + " reference_memristor = memtorch.bh.memristor.VTEAM\n", + " reference_memristor_params = {'time_series_resolution': 1e-10,\n", + " 'r_off': memtorch.bh.StochasticParameter(r_on * g_ratio, std=sigma*2, min=1),\n", + " 'r_on': memtorch.bh.StochasticParameter(r_on, std=sigma, min=1)}\n", + " patched_model = patch_model(copy.deepcopy(model_),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear, torch.nn.Conv2d],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None)\n", + " patched_model = apply_nonidealities(patched_model,\n", + " non_idealities=[memtorch.bh.nonideality.NonIdeality.FiniteConductanceStates],\n", + " conductance_states=int(num_conductance_states))\n", + " patched_model.tune_()\n", + " return test(patched_model, test_loader)\n", + "\n", + "std_devs = [0, 20, 100]\n", + "g_ratios = [2 ** n for n in range(6)]\n", + "conductance_states = np.linspace(2, 10, 9)\n", + "for std_dev in std_devs:\n", + " df = pd.DataFrame(columns=['conductance_states', 'g_ratio', 'test_set_accuracy'])\n", + " for g_ratio in g_ratios:\n", + " for num_conductance_states in conductance_states:\n", + " test_set_accuracy = trial(num_conductance_states, g_ratio, std_dev)\n", + " df = df.append({'conductance_states': num_conductance_states, \n", + " 'g_ratio': g_ratio, \n", + " 'test_set_accuracy': test_set_accuracy}, ignore_index=True)\n", + " \n", + " df.to_csv('S1_std_dev_%d.csv' % std_dev, index=False)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "scrolled": false + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "from matplotlib.ticker import FormatStrFormatter\n", + "\n", + "f = plt.figure(figsize=(16, 4))\n", + "plt.subplot(1, len(std_devs), 1)\n", + "for plot_index, std_dev in enumerate(std_devs):\n", + " plt.subplot(1, len(std_devs), plot_index + 1)\n", + " plt.axhline(y=10, color='k', linestyle='--', zorder=1)\n", + " data = pd.read_csv('S1_std_dev_%d.csv' % std_dev)\n", + " h = sns.barplot(x=\"conductance_states\", hue=\"g_ratio\", y=\"test_set_accuracy\", data=data, zorder=2, edgecolor='black', linewidth='1', palette=sns.color_palette(palette), saturation=1)\n", + " plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%1.0f'))\n", + " plt.xticks(np.arange(0, len(conductance_states)), map(lambda n: \"%d\" % n, conductance_states))\n", + " leg = h.axes.get_legend()\n", + " leg.set_title('RON/ROFF Ratio')\n", + " h.legend(loc=1)\n", + " plt.title('$\\sigma$ = %d' % std_dev)\n", + " if plot_index == 0:\n", + " plt.xlabel('Number of Finite States')\n", + " plt.ylabel('CIFAR-10 Test-set Accuracy (%)')\n", + " else:\n", + " plt.xlabel('')\n", + " plt.ylabel('')\n", + " \n", + " plt.grid()\n", + " \n", + "f.tight_layout()\n", + "plt.savefig(\"S1.svg\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 8. Second novel simulation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from memtorch.mn.Module import patch_model\n", + "from memtorch.map.Parameter import naive_map\n", + "from memtorch.bh.crossbar.Program import naive_program\n", + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "\n", + "\n", + "def trial(num_conductance_states, lrs_failure_rate, hrs_failure_rate, sigma):\n", + " model_ = copy.deepcopy(model)\n", + " r_on = 200\n", + " r_off = 500\n", + " reference_memristor = memtorch.bh.memristor.VTEAM\n", + " reference_memristor_params = {'time_series_resolution': 1e-10,\n", + " 'r_off': memtorch.bh.StochasticParameter(r_on * g_ratio, std=sigma*2, min=1),\n", + " 'r_on': memtorch.bh.StochasticParameter(r_off, std=sigma, min=1)}\n", + " patched_model = patch_model(copy.deepcopy(model_),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear, torch.nn.Conv2d],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None)\n", + " patched_model = apply_nonidealities(patched_model,\n", + " non_idealities=[memtorch.bh.nonideality.NonIdeality.FiniteConductanceStates,\n", + " memtorch.bh.nonideality.NonIdeality.DeviceFaults],\n", + " conductance_states=int(num_conductance_states),\n", + " lrs_proportion=lrs_failure_rate,\n", + " hrs_proportion=hrs_failure_rate,\n", + " electroform_proportion=0)\n", + " patched_model.tune_()\n", + " return test(patched_model, test_loader)\n", + "\n", + "std_devs = [0, 20, 100]\n", + "failure_rates = np.linspace(0, 0.25, 6)\n", + "conductance_states = np.linspace(2, 10, 9)\n", + "\n", + "# LRS\n", + "for std_dev in std_devs:\n", + " df = pd.DataFrame(columns=['conductance_states', 'failure_rate', 'test_set_accuracy'])\n", + " for failure_rate in failure_rates:\n", + " for num_conductance_states in conductance_states:\n", + " test_set_accuracy = trial(num_conductance_states, failure_rate, 0, std_dev)\n", + " df = df.append({'conductance_states': num_conductance_states, \n", + " 'failure_rate': failure_rate, \n", + " 'test_set_accuracy': test_set_accuracy}, ignore_index=True)\n", + " \n", + " df.to_csv('S2_LRS_std_dev_%d.csv' % std_dev, index=False)\n", + " \n", + "# HRS\n", + "for std_dev in std_devs:\n", + " df = pd.DataFrame(columns=['conductance_states', 'failure_rate', 'test_set_accuracy'])\n", + " for failure_rate in failure_rates:\n", + " for num_conductance_states in conductance_states:\n", + " test_set_accuracy = trial(num_conductance_states, 0, failure_rate, std_dev)\n", + " df = df.append({'conductance_states': num_conductance_states, \n", + " 'failure_rate': failure_rate, \n", + " 'test_set_accuracy': test_set_accuracy}, ignore_index=True)\n", + " \n", + " df.to_csv('S2_HRS_std_dev_%d.csv' % std_dev, index=False)\n", + " \n", + "# LRS and HRS\n", + "for std_dev in std_devs:\n", + " df = pd.DataFrame(columns=['conductance_states', 'failure_rate', 'test_set_accuracy'])\n", + " for failure_rate in failure_rates:\n", + " for num_conductance_states in conductance_states:\n", + " test_set_accuracy = trial(num_conductance_states, failure_rate, failure_rate, std_dev)\n", + " df = df.append({'conductance_states': num_conductance_states, \n", + " 'failure_rate': failure_rate, \n", + " 'test_set_accuracy': test_set_accuracy}, ignore_index=True)\n", + " \n", + " df.to_csv('S2_LRS_HRS_std_dev_%d.csv' % std_dev, index=False)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "from matplotlib.ticker import FormatStrFormatter\n", + "\n", + "f = plt.figure(figsize=(16, 12))\n", + "plt.subplot(3, len(std_devs), 1)\n", + "# LRS\n", + "for plot_index, std_dev in enumerate(std_devs):\n", + " plt.subplot(3, len(std_devs), plot_index + 1)\n", + " plt.axhline(y=10, color='k', linestyle='--', zorder=1)\n", + " data = pd.read_csv('S2_LRS_std_dev_%d.csv' % std_dev)\n", + " h = sns.barplot(x=\"conductance_states\", hue=\"failure_rate\", y=\"test_set_accuracy\", data=data, zorder=2, edgecolor='black', linewidth='1', palette=sns.color_palette(palette), saturation=1)\n", + " plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%1.0f'))\n", + " plt.xticks(np.arange(0, len(conductance_states)), map(lambda n: \"%d\" % n, conductance_states))\n", + " leg = h.axes.get_legend()\n", + " leg.set_title('Device Failure (%)')\n", + " h.legend(loc=1)\n", + " plt.title('$\\sigma$ = %d' % std_dev)\n", + " if plot_index == 0:\n", + " plt.xlabel('Number of Finite States')\n", + " plt.ylabel('[LRS] CIFAR-10 Test-set Accuracy (%)')\n", + " else:\n", + " plt.xlabel('')\n", + " plt.ylabel('')\n", + " \n", + " plt.grid()\n", + " \n", + "# HRS\n", + "for plot_index, std_dev in enumerate(std_devs):\n", + " plt.subplot(3, len(std_devs), plot_index + 1 + len(std_devs))\n", + " plt.axhline(y=10, color='k', linestyle='--', zorder=1)\n", + " data = pd.read_csv('S2_HRS_std_dev_%d.csv' % std_dev)\n", + " h = sns.barplot(x=\"conductance_states\", hue=\"failure_rate\", y=\"test_set_accuracy\", data=data, zorder=2, edgecolor='black', linewidth='1', palette=sns.color_palette(palette), saturation=1)\n", + " plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%1.0f'))\n", + " plt.xticks(np.arange(0, len(conductance_states)), map(lambda n: \"%d\" % n, conductance_states))\n", + " leg = h.axes.get_legend()\n", + " leg.set_title('Device Failure (%)')\n", + " h.legend(loc=1)\n", + " plt.title('$\\sigma$ = %d' % std_dev)\n", + " if plot_index == 0:\n", + " plt.xlabel('Number of Finite States')\n", + " plt.ylabel('[HRS] CIFAR-10 Test-set Accuracy (%)')\n", + " else:\n", + " plt.xlabel('')\n", + " plt.ylabel('')\n", + " \n", + " plt.grid()\n", + " \n", + "# LRS and HRS\n", + "for plot_index, std_dev in enumerate(std_devs):\n", + " plt.subplot(3, len(std_devs), plot_index + 1 + 2 * len(std_devs))\n", + " plt.axhline(y=10, color='k', linestyle='--', zorder=1)\n", + " data = pd.read_csv('S2_LRS_HRS_std_dev_%d.csv' % std_dev)\n", + " h = sns.barplot(x=\"conductance_states\", hue=\"failure_rate\", y=\"test_set_accuracy\", data=data, zorder=2, edgecolor='black', linewidth='1', palette=sns.color_palette(palette), saturation=1)\n", + " plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%1.0f'))\n", + " plt.xticks(np.arange(0, len(conductance_states)), map(lambda n: \"%d\" % n, conductance_states))\n", + " leg = h.axes.get_legend()\n", + " leg.set_title('Device Failure (%)')\n", + " h.legend(loc=1)\n", + " plt.title('$\\sigma$ = %d' % std_dev)\n", + " if plot_index == 0:\n", + " plt.xlabel('Number of Finite States')\n", + " plt.ylabel('[LRS and HRS] CIFAR-10 Test-set Accuracy (%)')\n", + " else:\n", + " plt.xlabel('')\n", + " plt.ylabel('')\n", + " \n", + " plt.grid()\n", + " \n", + "f.tight_layout()\n", + "plt.savefig(\"S2.svg\")\n", + "plt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/docs/Tutorial.ipynb b/docs/Tutorial.ipynb new file mode 100644 index 00000000..1d960ebc --- /dev/null +++ b/docs/Tutorial.ipynb @@ -0,0 +1,562 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# MemTorch Tutorial" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "qBYEsnSav5E1" + }, + "source": [ + "## 1. Training and benchmarking a DNN using CIFAR-10" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "HCy9QqPHv5E3" + }, + "source": [ + "The VGG-16 DNN architecture is trained and tested using the CIFAR-10 data set. The CIFAR-10 data set consists of 60,000 32x32 color images in 10 classes, with 6,000 images per class. There are 50,000 training images and 10,000 test images. The network is trained for 50 epochs with a batch size, $\\Im=256$. The initial learning rate is $\\eta = 1e-2$, which is decayed by an order of magnitude every 20 training epochs. Adam is used to optimize network parameters and Cross Entropy (CE) is used to determine network losses. *memtorch.utils.LoadCIFAR10* is used to load the CIFAR-10 training and test sets. After each epoch the model is bench-marked using the CIFAR-10 test set. The model that achieves the highest test set accuracy is saved as *trained_model.pt*." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "jVH_tu3tv5E4" + }, + "outputs": [], + "source": [ + "import torch\n", + "from torch.autograd import Variable\n", + "import memtorch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch.optim as optim\n", + "from memtorch.utils import LoadCIFAR10\n", + "import numpy as np\n", + "\n", + "\n", + "class Net(nn.Module):\n", + " def __init__(self, inflation_ratio=1):\n", + " super(Net, self).__init__()\n", + " self.conv0 = nn.Conv2d(in_channels=3, out_channels=128*inflation_ratio, kernel_size=3, stride=1, padding=1)\n", + " self.bn0 = nn.BatchNorm2d(num_features=128*inflation_ratio)\n", + " self.act0 = nn.ReLU()\n", + " self.conv1 = nn.Conv2d(in_channels=128*inflation_ratio, out_channels=128*inflation_ratio, kernel_size=3, padding=1)\n", + " self.bn1 = nn.BatchNorm2d(num_features=128*inflation_ratio)\n", + " self.act1 = nn.ReLU()\n", + " self.conv2 = nn.Conv2d(in_channels=128*inflation_ratio, out_channels=256*inflation_ratio, kernel_size=3, padding=1)\n", + " self.bn2 = nn.BatchNorm2d(num_features=256*inflation_ratio)\n", + " self.act2 = nn.ReLU()\n", + " self.conv3 = nn.Conv2d(in_channels=256*inflation_ratio, out_channels=256*inflation_ratio, kernel_size=3, padding=1)\n", + " self.bn3 = nn.BatchNorm2d(num_features=256*inflation_ratio)\n", + " self.act3 = nn.ReLU()\n", + " self.conv4 = nn.Conv2d(in_channels=256*inflation_ratio, out_channels=512*inflation_ratio, kernel_size=3, padding=1)\n", + " self.bn4 = nn.BatchNorm2d(num_features=512*inflation_ratio)\n", + " self.act4 = nn.ReLU()\n", + " self.conv5 = nn.Conv2d(in_channels=512*inflation_ratio, out_channels=512, kernel_size=3, padding=1)\n", + " self.bn5 = nn.BatchNorm2d(num_features=512)\n", + " self.act5 = nn.ReLU()\n", + " self.fc6 = nn.Linear(in_features=512*4*4, out_features=1024)\n", + " self.bn6 = nn.BatchNorm1d(num_features=1024)\n", + " self.act6 = nn.ReLU()\n", + " self.fc7 = nn.Linear(in_features=1024, out_features=1024)\n", + " self.bn7 = nn.BatchNorm1d(num_features=1024)\n", + " self.act7 = nn.ReLU()\n", + " self.fc8 = nn.Linear(in_features=1024, out_features=10)\n", + "\n", + " def forward(self, input):\n", + " x = self.act0(self.bn0(self.conv0(input)))\n", + " x = self.act1(self.bn1(F.max_pool2d(self.conv1(x), 2)))\n", + " x = self.act2(self.bn2(self.conv2(x)))\n", + " x = self.act3(self.bn3(F.max_pool2d(self.conv3(x), 2)))\n", + " x = self.act4(self.bn4(self.conv4(x)))\n", + " x = self.act5(self.bn5(F.max_pool2d(self.conv5(x), 2)))\n", + " x = x.view(x.size(0), -1)\n", + " x = self.act6(self.bn6(self.fc6(x)))\n", + " x = self.act7(self.bn7(self.fc7(x)))\n", + " return self.fc8(x)\n", + "\n", + "def test(model, test_loader):\n", + " correct = 0\n", + " for batch_idx, (data, target) in enumerate(test_loader): \n", + " output = model(data.to(device))\n", + " pred = output.data.max(1)[1]\n", + " correct += pred.eq(target.to(device).data.view_as(pred)).cpu().sum()\n", + "\n", + " return 100. * float(correct) / float(len(test_loader.dataset))\n", + "\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "epochs = 50\n", + "train_loader, validation_loader, test_loader = LoadCIFAR10(batch_size=256, validation=False)\n", + "model = Net().to(device)\n", + "if device == 'cuda':\n", + " model = torch.nn.DataParallel(model)\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "learning_rate = 1e-2\n", + "optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n", + "best_accuracy = 0\n", + "for epoch in range(0, epochs):\n", + " print('Epoch: [%d]\\t\\t' % (epoch + 1), end='')\n", + " if epoch % 20 == 0:\n", + " learning_rate = learning_rate * 0.1\n", + " for param_group in optimizer.param_groups:\n", + " param_group['lr'] = learning_rate\n", + "\n", + " model.train()\n", + " for batch_idx, (data, target) in enumerate(train_loader):\n", + " optimizer.zero_grad()\n", + " output = model(data.to(device))\n", + " loss = criterion(output, target.to(device))\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " accuracy = test(model, test_loader)\n", + " print('%2.2f%%' % accuracy)\n", + " if accuracy > best_accuracy:\n", + " torch.save(model.state_dict(), 'trained_model.pt')\n", + " best_accuracy = accuracy" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "Ag8Z6Rn_v5E8" + }, + "source": [ + "## 2. Conversion of a DNN to a MDNN " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "lyt9qHvAv5E9" + }, + "source": [ + "We use MemTorch to demonstrate the conversion of a DNN to MDNN. A memristive device model is defined and characterized below, which is used to replace all *torch.nn.Linear* layers within the DNN, trained in Step 1, with equivalent crossbar architectures using *memtorch.mn.Module.patch_model*." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 295 + }, + "colab_type": "code", + "id": "dRMGKP-lv5E-", + "outputId": "f22a800e-3eae-4060-a874-23d7a218f3cf" + }, + "outputs": [], + "source": [ + "reference_memristor = memtorch.bh.memristor.VTEAM\n", + "reference_memristor_params = {'time_series_resolution': 1e-10}\n", + "memristor = reference_memristor(**reference_memristor_params)\n", + "memristor.plot_hysteresis_loop()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "b0kLErl0v5FC" + }, + "source": [ + "*memtorch.bh.map.Parameter.naive_map* is used to convert the weights within all *torch.nn.Linear* layers to equivalent conductance values, to be programmed to the two memristive devices used to represent each weight (positive and negative) using Eq. (13). \n", + "\n", + "*transistor* is *True*, so a 1T1R arrangement is simulated. *programming_routine* is set to *None* to skip device-level simulation of the programming routine. We note if *transistor* is *False* *programming_routine* must not be *None*. In which case, device-level simulation is performed for each device using *memtorch.bh.crossbar.gen_programming_signal* and *memtorch.bh.memristor.Memristor.simulate*, which uses finite differences to model internal device dynamics. As *scheme* is not defined, a double-column parameter representation scheme is adopted.\n", + "\n", + "All patched *torch.nn.Linear* layers are tuned using linear regression. A randomly generated tensor of size (8, *self.in_features*) is propagated through each memristive layer and each legacy layer (accessible using *layer.forward_legacy*). *sklearn.linear_model.LinearRegression* is used to determine the coefficient and intercept between the linear relationship of each set of outputs, which is used to define the *transform_output* lamdba function, that maps the output of each layer to their equivalent representations.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "oJWSTW5Qv5FD" + }, + "outputs": [], + "source": [ + "import copy\n", + "from memtorch.mn.Module import patch_model\n", + "from memtorch.map.Parameter import naive_map\n", + "from memtorch.bh.crossbar.Program import naive_program\n", + "\n", + "\n", + "model = Net()\n", + "if torch.cuda.is_available():\n", + " model = torch.nn.DataParallel(model)\n", + "\n", + "model.load_state_dict(torch.load('trained_model.pt'), strict=False)\n", + "patched_model = patch_model(copy.deepcopy(model),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "Mam3ggffv5FG" + }, + "outputs": [], + "source": [ + "patched_model.tune_()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "U5F0muXPv5FK" + }, + "outputs": [], + "source": [ + "print(test(patched_model, test_loader))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "eV8IJSH6v5FN" + }, + "source": [ + "## 3. Modeling non-ideal device characteristics" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "R4H9f4d248V7" + }, + "source": [ + "We use a simple prototype model to demonstrate modeling non-ideal device characteristics." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 50 + }, + "colab_type": "code", + "id": "x0mghWrdv5FO", + "outputId": "fb7d0542-7839-438e-94fb-029d05f0bbc1" + }, + "outputs": [], + "source": [ + "from memtorch.mn.Module import patch_model\n", + "import copy\n", + "from memtorch.map.Parameter import naive_map\n", + "\n", + "class Model(torch.nn.Module):\n", + "\n", + " def __init__(self):\n", + " super(Model, self).__init__()\n", + " self.convolutional_layer = torch.nn.Conv2d(in_channels=3, out_channels=1, kernel_size=5)\n", + " self.linear_layer = torch.nn.Linear(in_features=16, out_features=4)\n", + "\n", + " def forward(self, input):\n", + " x = self.convolutional_layer(input)\n", + " x = x.view(x.size(0), -1)\n", + " return self.linear_layer(x)\n", + " \n", + "torch.manual_seed(0)\n", + "model = Model()\n", + "if torch.cuda.is_available():\n", + " model = torch.nn.DataParallel(model)\n", + "\n", + "reference_memristor_params = {'time_series_resolution': 1e-10, 'r_off': 200, 'r_on': 100}\n", + "patched_model = patch_model(copy.deepcopy(model),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear, torch.nn.Conv2d],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "D2Vcpuuw5D_S" + }, + "source": [ + "Device-device variability is introduced to the VTEAM reference memristor model using *memtorch.bh.StochasticParameter*, by sampling $R_{\\text{OFF}}$ for each device from a normal distribution with $\\sigma = 20$ and $x = 200$, and $R_{\\text{ON}}$ for each device from a normal distribution with $\\sigma = 10$ and $x = 100$. Using *np.vectorize*, the $R_{\\text{OFF}}$ and $R_{\\text{ON}}$ values for each memristive device are compared." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 276 + }, + "colab_type": "code", + "id": "4thsaVDEv5FS", + "outputId": "e46021ed-b57f-4be7-f29e-15bd17ec2473" + }, + "outputs": [], + "source": [ + "from memtorch.mn.Module import patch_model\n", + "import copy\n", + "from memtorch.map.Parameter import naive_map\n", + "from memtorch.bh.crossbar.Program import naive_program\n", + "import matplotlib.pyplot as plt\n", + "from mpl_toolkits.axes_grid1 import make_axes_locatable\n", + "\n", + "reference_memristor_params = {'time_series_resolution': 1e-10, \n", + " 'r_off': memtorch.bh.StochasticParameter(200, std=20, min=2),\n", + " 'r_on': memtorch.bh.StochasticParameter(100, std=10, min=1)}\n", + "\n", + "patched_model_ = patch_model(copy.deepcopy(model),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear, torch.nn.Conv2d],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None)\n", + "\n", + "A = torch.Tensor(np.vectorize(lambda x: x.r_off)(patched_model_.linear_layer.crossbars[0].devices))\n", + "B = torch.Tensor(np.vectorize(lambda x: x.r_on)(patched_model_.linear_layer.crossbars[0].devices))\n", + "C = torch.cat((A, B), 0)\n", + "\n", + "\n", + "plt.subplot(2, 1, 1)\n", + "plt.imshow(A.transpose(0, 1), interpolation='nearest', aspect=1, vmin=C.min(), vmax=C.max(), cmap='seismic')\n", + "plt.xticks([])\n", + "plt.yticks([])\n", + "plt.xlabel('Dimension 1')\n", + "plt.ylabel('Dimension 0')\n", + "divider = make_axes_locatable(plt.gca())\n", + "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n", + "plt.colorbar(cax=cax)\n", + "\n", + "plt.subplot(2, 1, 2)\n", + "plt.imshow(B.transpose(0, 1), interpolation='nearest', aspect=1, vmin=C.min(), vmax=C.max(), cmap='seismic')\n", + "plt.xticks([])\n", + "plt.yticks([])\n", + "plt.xlabel('Dimension 1')\n", + "plt.ylabel('Dimension 0')\n", + "divider = make_axes_locatable(plt.gca())\n", + "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n", + "plt.colorbar(cax=cax)\n", + "plt.savefig('var.svg')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "3okdYrSZ7dJh" + }, + "source": [ + "We model a number (5) of finite discrete conductance states using $memtorch.bh.nonideality.NonIdeality.FiniteConductanceStates$. The conductance levels within the positive crossbar were compared before and after a finite discrete conductance states are modeled." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 246 + }, + "colab_type": "code", + "id": "bpIOctS5v5FV", + "outputId": "feefbf64-f8fe-4da2-8212-afa17dade373" + }, + "outputs": [], + "source": [ + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "\n", + "A = 1 / patched_model.linear_layer.crossbars[0].conductance_matrix\n", + "model = apply_nonidealities(copy.deepcopy(patched_model),\n", + " non_idealities=[memtorch.bh.nonideality.NonIdeality.FiniteConductanceStates],\n", + " conductance_states = 5)\n", + "B = 1 / model.linear_layer.crossbars[0].conductance_matrix\n", + "C = torch.cat((A, B), 0)\n", + "\n", + "plt.subplot(2, 1, 1)\n", + "plt.imshow(A.transpose(0, 1), interpolation='nearest', aspect=1, vmin=C.min(), vmax=C.max(), cmap='seismic')\n", + "plt.xticks([])\n", + "plt.yticks([])\n", + "plt.xlabel('Dimension 1')\n", + "plt.ylabel('Dimension 0')\n", + "divider = make_axes_locatable(plt.gca())\n", + "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n", + "plt.colorbar(cax=cax)\n", + "\n", + "plt.subplot(2, 1, 2)\n", + "plt.imshow(B.transpose(0, 1), interpolation='nearest', aspect=1, vmin=C.min(), vmax=C.max(), cmap='seismic')\n", + "plt.xticks([])\n", + "plt.yticks([])\n", + "plt.xlabel('Dimension 1')\n", + "plt.ylabel('Dimension 0')\n", + "divider = make_axes_locatable(plt.gca())\n", + "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n", + "plt.colorbar(cax=cax)\n", + "plt.savefig('finite.svg')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "rfyXHayL70HP" + }, + "source": [ + "We model device failure using $memtorch.bh.nonideality.NonIdeality.DeviceFaults$. The conductance levels within the positive crossbar are once again compared, before and after 50\\% of devices are stuck at $R_{\\text{LRS}}$ and 50\\% of devices are stuck at $R_{\\text{HRS}}$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 246 + }, + "colab_type": "code", + "id": "E6Xi7FUxv5FZ", + "outputId": "a074acc6-3e0b-4d39-89cf-90fb2ad05bdd" + }, + "outputs": [], + "source": [ + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "\n", + "A = 1 / patched_model.linear_layer.crossbars[0].conductance_matrix\n", + "model = apply_nonidealities(copy.deepcopy(patched_model),\n", + " non_idealities=[memtorch.bh.nonideality.NonIdeality.DeviceFaults],\n", + " lrs_proportion=0.5,\n", + " hrs_proportion=0.5,\n", + " electroform_proportion=0)\n", + "B = 1 / model.linear_layer.crossbars[0].conductance_matrix\n", + "C = torch.cat((A, B), 0)\n", + "\n", + "plt.subplot(2, 1, 1)\n", + "plt.imshow(A.transpose(0, 1), interpolation='nearest', aspect=1, vmin=C.min(), vmax=C.max(), cmap='seismic')\n", + "plt.xticks([])\n", + "plt.yticks([])\n", + "plt.xlabel('Dimension 1')\n", + "plt.ylabel('Dimension 0')\n", + "divider = make_axes_locatable(plt.gca())\n", + "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n", + "plt.colorbar(cax=cax)\n", + "\n", + "plt.subplot(2, 1, 2)\n", + "plt.imshow(B.transpose(0, 1), interpolation='nearest', aspect=1, vmin=C.min(), vmax=C.max(), cmap='seismic')\n", + "plt.xticks([])\n", + "plt.yticks([])\n", + "plt.xlabel('Dimension 1')\n", + "plt.ylabel('Dimension 0')\n", + "divider = make_axes_locatable(plt.gca())\n", + "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n", + "plt.colorbar(cax=cax)\n", + "plt.savefig('fault.svg')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "WWX0f_Wz8U1L" + }, + "source": [ + "We model non-linear I/V characteristics using $memtorch.bh.nonideality.NonIdeality.NonLinear$ during inference. The output of the single *torch.nn.Linear* layer are compared when devices were simulated during inference with linear and non-linear I/V characteristics. Non-linear I/V characteristics were determined by applying a half-voltage sweep, using a sinusoidal cosine voltage signal with a duration of 5ns, amplitude of 1V, and a frequency of 50 MHz to each device. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 34 + }, + "colab_type": "code", + "id": "xIbVHttJv5Fb", + "outputId": "559d9c25-25f0-4f6c-fbeb-75defceb9048" + }, + "outputs": [], + "source": [ + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "from sklearn.metrics.pairwise import cosine_similarity\n", + "\n", + "A = torch.tensor(np.zeros((100, 4)))\n", + "B = torch.tensor(np.zeros((100, 4)))\n", + "for i in range(100):\n", + " input = torch.zeros((1,3,8,8)).uniform_(-1, 1)\n", + " A[i, :] = patched_model(input)\n", + " model = apply_nonidealities(copy.deepcopy(patched_model),\n", + " non_idealities=[memtorch.bh.nonideality.NonIdeality.NonLinear],\n", + " sweep_duration=5e-9,\n", + " sweep_voltage_signal_amplitude=1,\n", + " sweep_voltage_signal_frequency=50e6)\n", + " B[i, :] = model(input)\n", + "\n", + "print(cosine_similarity([A.view(-1).numpy()], [B.view(-1).numpy()]))" + ] + } + ], + "metadata": { + "colab": { + "collapsed_sections": [], + "name": "Tutorial.ipynb", + "provenance": [] + }, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 00000000..70a3c6cc --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,66 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import torch +import memtorch + +# -- Project information ----------------------------------------------------- + +project = 'MemTorch' +copyright = '2020, Corey Lammie' +author = 'Corey Lammie' + +# The full version, including alpha/beta/rc tags +release = '1.0.1' +autodoc_inherit_docstrings = False + +# -- General configuration --------------------------------------------------- +master_doc = 'index' +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.napoleon', + 'sphinx.ext.viewcode', + 'sphinx.ext.doctest', + 'sphinx.ext.intersphinx', + 'nbsphinx' +] + +nbsphinx_execute = 'never' + +intersphinx_mapping = {'torch': ('https://pytorch.org/docs/stable/', None), + 'python': ('https://docs.python.org/3', None)} + +autodoc_inherit_docstrings = True + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = [] + + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'sphinx_rtd_theme' + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 00000000..6b4c6153 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,17 @@ +.. MemTorch documentation master file, created by + sphinx-quickstart on Fri Jan 3 15:51:39 2020. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +:github_url: https://github.com/coreylammie/MemTorch + +MemTorch documentation +==================================== +`MemTorch `_ is a simulation framework for memristive deep learning systems that integrates directly with the well-known PyTorch Machine Learning (ML) library. + +.. toctree:: + :maxdepth: 4 + + memtorch + tutorials + Discuss MemTorch on Gitter diff --git a/docs/memtorch.bh.memristor.rst b/docs/memtorch.bh.memristor.rst new file mode 100644 index 00000000..b01bd523 --- /dev/null +++ b/docs/memtorch.bh.memristor.rst @@ -0,0 +1,21 @@ +memtorch.bh.memristor +============================= +Submodule containing various behavioural memristor models, which extend :ref:`base-class-label`. + +.. _base-class-label: + +memtorch.bh.memristor.Memristor +-------------------------------------- + +.. automodule:: memtorch.bh.memristor.Memristor + :members: + :undoc-members: + :show-inheritance: + +memtorch.bh.memristor.LinearIonDrift +------------------------------------------- + +.. automodule:: memtorch.bh.memristor.LinearIonDrift + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/memtorch.bh.nonideality.rst b/docs/memtorch.bh.nonideality.rst new file mode 100644 index 00000000..11177805 --- /dev/null +++ b/docs/memtorch.bh.nonideality.rst @@ -0,0 +1,29 @@ +memtorch.bh.nonideality +=============================== +Submodule containing various models, which can be used to introduce non-idealities. + +memtorch.bh.nonideality.NonIdeality +------------------------------------------ + +.. automodule:: memtorch.bh.nonideality.NonIdeality + :members: + :undoc-members: + :show-inheritance: + +memtorch.bh.nonideality.FiniteConductanceStates +------------------------------------------------------ +Used to model a finite number of conductance states. + +.. automodule:: memtorch.bh.nonideality.FiniteConductanceStates + :members: + :undoc-members: + :show-inheritance: + +memtorch.bh.nonideality.Variability +------------------------------------------ +Used to model device-device variability. + +.. automodule:: memtorch.bh.nonideality.Variability + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/memtorch.bh.rst b/docs/memtorch.bh.rst new file mode 100644 index 00000000..a418c7ae --- /dev/null +++ b/docs/memtorch.bh.rst @@ -0,0 +1,16 @@ +memtorch.bh +=================== +Submodule containing various behavioural models. + +.. toctree:: + + memtorch.bh.memristor + memtorch.bh.nonideality + +memtorch.bh.Crossbar +--------------------------- + +.. automodule:: memtorch.bh.Crossbar + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/memtorch.map.rst b/docs/memtorch.map.rst new file mode 100644 index 00000000..07d3f3d4 --- /dev/null +++ b/docs/memtorch.map.rst @@ -0,0 +1,19 @@ +memtorch.map +==================== +Submodule containing various mapping algorithms. + +memtorch.map.Module +----------------------------- + +.. automodule:: memtorch.map.Module + :members: + :undoc-members: + :show-inheritance: + +memtorch.map.Parameter +----------------------------- + +.. automodule:: memtorch.map.Parameter + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/memtorch.mn.rst b/docs/memtorch.mn.rst new file mode 100644 index 00000000..a0727bd0 --- /dev/null +++ b/docs/memtorch.mn.rst @@ -0,0 +1,26 @@ +memtorch.mn +=================== +torch.nn equivalent submodule. + +memtorch.mn.Module +------------------------- + +.. automodule:: memtorch.mn.Module + :members: + :undoc-members: + :show-inheritance: + +memtorch.mn.Conv2d +------------------------- +.. automodule:: memtorch.mn.Conv2d + :members: + :undoc-members: + :show-inheritance: + +memtorch.mn.Linear +------------------------- + +.. automodule:: memtorch.mn.Linear + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/memtorch.rst b/docs/memtorch.rst new file mode 100644 index 00000000..f43a9ab8 --- /dev/null +++ b/docs/memtorch.rst @@ -0,0 +1,7 @@ +Python API +================ +.. toctree:: + + memtorch.bh + memtorch.map + memtorch.mn diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 00000000..d06bcb53 --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,8 @@ +numpy +pandas +torch>=1.2.0 +torchvision +matplotlib +seaborn +sklearn +nbsphinx diff --git a/docs/test_loaders.pth b/docs/test_loaders.pth new file mode 100644 index 00000000..49775682 Binary files /dev/null and b/docs/test_loaders.pth differ diff --git a/docs/tutorials.rst b/docs/tutorials.rst new file mode 100644 index 00000000..a084b8f4 --- /dev/null +++ b/docs/tutorials.rst @@ -0,0 +1,22 @@ +Tutorials +==================================== + +To learn how to use MemTorch, and to reproduce results of 'MemTorch: An Open-source Simulation Framework for Memristive Deep Learning Systems', we provide numerous Jupyter notebooks. + +:doc:`Tutorial.ipynb ` details example usage of MemTorch to: + +1. Train and benchmark a DNN model using the CIFAR-10 dataset. +2. Convert a pretrained DNN to a Memristive-DNN (MDNN). +3. Patch a converted Memristive-CNN. +4. Introduce non-ideal device characteristics to a generic memristive model. + +:doc:`CaseStudy.ipynb ` can be used to reproduce the results from the case study presented in 'MemTorch: An Open-source Simulation Framework for Memristive Deep Learning Systems'. + +:doc:`NovelSimulations.ipynb ` can be used to reproduce the results from the novel simulations presented in 'MemTorch: An Open-source Simulation Framework for Memristive Deep Learning Systems'. + +.. toctree:: + :maxdepth: 2 + + Tutorial.ipynb + CaseStudy.ipynb + NovelSimulations.ipynb diff --git a/memtorch/__init__.py b/memtorch/__init__.py new file mode 100644 index 00000000..25a146ad --- /dev/null +++ b/memtorch/__init__.py @@ -0,0 +1,6 @@ +import torch +from memtorch.bh import * +from memtorch.bh.nonideality import * +from memtorch.mn import * +from memtorch.utils import * +from memtorch.map import * diff --git a/memtorch/bh/StochasticParameter.py b/memtorch/bh/StochasticParameter.py new file mode 100644 index 00000000..0bf72950 --- /dev/null +++ b/memtorch/bh/StochasticParameter.py @@ -0,0 +1,83 @@ +import torch +import memtorch + + +def StochasticParameter(mean, distribution=torch.distributions.normal.Normal, min=0, max=float('Inf'), function=True, **kwargs): + """Method to model a stochatic parameter. + + Parameters + ---------- + mean : float + Mean value of the stochatic parameter. + distribution : torch.distributions + torch distribution. + min : float + Minimum value to sample. + max: float + Maximum value to sample. + function : bool + A sampled value is returned (True). A function to return a sampled value or mean is returned (False). + + Returns + ------- + float or function + A sampled value of the stochatic parameter, or a sample-value generator. + """ + assert distribution == torch.distributions.normal.Normal, 'Currently, only torch.distributions.normal.Normal is supported.' + assert kwargs['std'] is not None, 'std must be defined when distribution=torch.distributions.normal.Normal.' + m = distribution(mean, kwargs['std']) + def f(return_mean=False): + """Method to return a sampled value or the mean of the stochatic parameters. + + Parameters + ---------- + return_mean : bool + Return the mean value of the stochatic parameter (True). Return a sampled value of the stochatic parameter (False). + + Returns + ------- + float + The mean value, or a sampled value of the stochatic parameter. + """ + if return_mean: + return mean + else: + return m.sample().clamp(min, max).item() + + if function: + return f + else: + return f() + +def unpack_parameters(local_args): + """Method to sample from stochastic sample-value generators + + Parameters + ---------- + local_args : locals() + Local arguments with stochastic sample-value generators from which to sample from. + + Returns + ------- + ** + locals() with sampled stochastic parameters. + + """ + if 'reference' in local_args: + return_mean = True + else: + return_mean = False + + for arg in local_args: + if callable(local_args[arg]) and '__' not in str(arg): + local_args[arg] = local_args[arg](return_mean=return_mean) + + return Dict2Obj(local_args) + + +class Dict2Obj(object): + """Class used to instantiate a object given a dictionary.""" + + def __init__(self, dictionary): + for key in dictionary: + setattr(self, key, dictionary[key]) diff --git a/memtorch/bh/__init__.py b/memtorch/bh/__init__.py new file mode 100644 index 00000000..a08f62cd --- /dev/null +++ b/memtorch/bh/__init__.py @@ -0,0 +1,3 @@ +from .memristor import * +from .crossbar import * +from .StochasticParameter import * diff --git a/memtorch/bh/crossbar/Crossbar.py b/memtorch/bh/crossbar/Crossbar.py new file mode 100644 index 00000000..cc10d783 --- /dev/null +++ b/memtorch/bh/crossbar/Crossbar.py @@ -0,0 +1,213 @@ +import memtorch +import torch +import torch.nn as nn +import numpy as np +import pandas as pd +import math +from enum import Enum, auto, unique +import multiprocessing as mp +import itertools + + +@unique +class Scheme(Enum): + """Scheme enumeration.""" + SingleColumn = auto() + DoubleColumn = auto() + + +class Crossbar(): + """Class used to model memristor crossbars. + + Parameters + ---------- + memristor_model : memtorch.bh.memristor.Memristor.Memristor + Memristor model. + memristor_model_params: **kwargs + **kwargs to instantiate the memristor model with. + shape : tuple + Shape of the crossbar. + """ + + def __init__(self, memristor_model, memristor_model_params, shape): + self.time_series_resolution = memristor_model_params.get('time_series_resolution') + self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + if len(shape) == 4: # memtorch.mn.Conv2d + self.rows = shape[0] + self.columns = shape[1] * shape[2] * shape[3] + elif len(shape) == 2: # memtorch.mn.Linear + self.columns, self.rows = shape + else: + raise('Unsupported crossbar shape.') + + self.rows = int(self.rows) + self.columns = int(self.columns) + self.devices = np.empty((self.rows, self.columns), dtype=object) + self.devices.flat = [memristor_model(**memristor_model_params) for _ in self.devices.flat] + self.conductance_matrix = torch.zeros((self.rows, self.columns)).to(self.device) + self.g_np = np.vectorize(lambda x: x.g) + self.update(from_devices=True) + + def update(self, from_devices=True, parallelize=True): + """Method to update either the layers conductance_matrix or each devices conductance state. + + Parameters + ---------- + from_devices : bool + The conductance matrix can either be updated from all devices (True), or each device can be updated from the conductance matrix (False). + parallelize : bool + The operation is parallelized (True). + """ + if from_devices: + self.conductance_matrix = torch.tensor(self.g_np(self.devices)).to(self.device) + else: + if parallelize: + def write_conductance(device, conductance): + device.g = conductance + + np.frompyfunc(write_conductance, 2, 0)(self.devices, self.conductance_matrix.detach().cpu()) + else: + for i in range(0, self.rows): + for j in range(0, self.columns): + self.devices[i][j].g = self.conductance_matrix[i][j].item() + + def write_conductance_matrix(self, conductance_matrix, transistor=True, programming_routine=None): + """Method to directly program (alter) the conductance of all devices within the crossbar. + + Parameters + ---------- + conductance_matrix : torch.FloatTensor + Conductance matrix to write. + transistor : bool + Used to determine if a 1T1R (True) or 1R arrangement (False) is simulated. + programming_routine + Programming routine (method) to use. + """ + if transistor: + if len(conductance_matrix.shape) == 4: # memtorch.mn.Conv2d + self.conductance_matrix = conductance_matrix.reshape(self.rows, self.columns) + elif len(conductance_matrix.shape) == 2: # memtorch.mn.Linear + conductance_matrix = conductance_matrix.T.clone().detach().to(self.device) + assert(conductance_matrix.shape[0] == self.rows and conductance_matrix.shape[1] == self.columns) + min = torch.tensor(1 / np.vectorize(lambda x: x.r_off)(self.devices)).to(self.device).float() + max = torch.tensor(1 / np.vectorize(lambda x: x.r_on)(self.devices)).to(self.device).float() + self.conductance_matrix = torch.max(torch.min(conductance_matrix, max), min).to(self.device) + else: + raise('Unsupported crossbar shape.') + + self.update(from_devices=False) + else: + assert programming_routine is not None, 'programming_routine must be defined if transistor is False.' + for i in range(0, self.rows): + for j in range(0, self.columns): + self.devices[i][j] = programming_routine(self, (i, j), conductance_matrix[i][j]) + + self.update(from_devices=True) + + +def init_crossbar(weights, memristor_model, memristor_model_params, transistor, mapping_routine, programming_routine, scheme=Scheme.DoubleColumn): + """Method to initialise and construct memristive crossbars. + + Parameters + ---------- + weights : torch.tensor + Weights to map. + memristor_model : memtorch.bh.memristor.Memristor.Memristor + Memristor model. + memristor_model_params: **kwargs + **kwargs to instantiate the memristor model with. + transistor : bool + Used to determine if a 1T1R (True) or 1R arrangement (False) is simulated. + mapping_routine : function + Mapping routine to use. + programming_routine : function + Programming routine to use. + scheme : memtorch.bh.Scheme + Scheme enum. + + Returns + ------- + tuple + The constructed crossbars and forward() function. + """ + assert scheme in Scheme, 'scheme must be a Scheme Enum.' + weights_ = weights.data.detach().clone() + crossbars = [] + reference_memristor_model_params = {**memristor_model_params, **{'reference': True}} + reference_memristor_model = memristor_model(**reference_memristor_model_params) + if scheme == Scheme.DoubleColumn: + crossbars.append(memtorch.bh.crossbar.Crossbar(memristor_model, memristor_model_params, weights.shape)) + crossbars.append(memtorch.bh.crossbar.Crossbar(memristor_model, memristor_model_params, weights.shape)) + pos_conductance_matrix, neg_conductance_matrix = mapping_routine(weights_, + reference_memristor_model.r_on, + reference_memristor_model.r_off, + scheme) + + crossbars[0].write_conductance_matrix(pos_conductance_matrix, transistor=transistor, programming_routine=programming_routine) + crossbars[1].write_conductance_matrix(neg_conductance_matrix, transistor=transistor, programming_routine=programming_routine) + def out(crossbars, operation, *args): + return operation(crossbars[0], *args) - operation(crossbars[1], *args) + + elif scheme == Scheme.SingleColumn: + crossbars.append(memtorch.bh.crossbar.Crossbar(memristor_model, memristor_model_params, weights.shape)) + conductance_matrix = mapping_routine(weights_, + reference_memristor_model.r_on, + reference_memristor_model.r_off, + scheme) + crossbars[0].write_conductance_matrix(conductance_matrix, transistor=transistor, programming_routine=programming_routine) + g_m = ((1 / reference_memristor_model.r_on) + (1 / reference_memristor_model.r_off)) / 2 + def out(crossbars, operation, *args): + return operation(crossbars[0], *args) - g_m + + else: + raise('%s is not currently supported.' % scheme) + + return crossbars, out + +def simulate(input, devices, parallelize=False, nl=True): + """Method to simulate non-linear IV device characterisitcs for a 2-D crossbar architecture given scaled inputs. + + Parameters + ---------- + input : tensor + Scaled input tensor. + devices : numpy.ndarray + Devices to simulate. + parallelize : bool + The operation is parallelized (True). + nl : bool + Use lookup tables rather than simulating each device (True). + + Returns + ------- + numpy.ndarray + Output ndarray. + """ + input_rows, input_columns = input.shape + devices_rows, devices_columns = devices.shape + mat_res = np.zeros((input_rows, devices_columns)) + if parallelize: + def pool_nl(i, j, k): + mat_res[i][j] += devices[k][j].det_current(input[i][k].item()) + + def pool_simulate(i, j, k): + mat_res[i][j] += devices[k][j].simulate(torch.Tensor[input[i][k]], return_current=True).item() + + pool = mp.Pool() + if nl: + pool.map(pool_nl, itertools.product(range(input_rows), range(devices_columns), range(input_columns))) + else: + pool.map(pool_simulate, itertools.product(range(input_rows), range(devices_columns), range(input_columns))) + else: + if nl: + for i in range(input_rows): + for j in range(devices_columns): + for k in range(input_columns): + mat_res[i][j] += devices[k][j].det_current(input[i][k].item()) + else: + for i in range(input_rows): + for j in range(devices_columns): + for k in range(input_columns): + mat_res[i][j] += devices[k][j].simulate(torch.Tensor([input[i][k]]).cpu(), return_current=True).item() + + return mat_res diff --git a/memtorch/bh/crossbar/Program.py b/memtorch/bh/crossbar/Program.py new file mode 100644 index 00000000..5a7e13a4 --- /dev/null +++ b/memtorch/bh/crossbar/Program.py @@ -0,0 +1,84 @@ +import torch +import memtorch +import numpy as np + + +def naive_program(crossbar, point, conductance, pulse_duration=1e-3, refactory_period=0, pos_voltage_level=1, neg_voltage_level=-1): + """Method to program (alter) the conductance of a given device within a crossbar. + + Parameters + ---------- + crossbar : memtorch.bh.crossbar.Crossbar + Crossbar containing the device to program. + pulse_duration : float + Duration of the programming pulse (s). + refactory_period : float + Duration of the refactory period (s). + pos_voltage_level : float + Positive voltage level (V). + neg_voltage_level : float + Negative voltage level (V). + + Returns + ------- + memtorch.bh.memristor.Memristor.Memristor + Programmed device. + """ + row, column = point + assert (1 / conductance) >= crossbar.devices[row][column].r_on and conductance <= crossbar.devices[row][column].r_off, 'Conductance to program must be between g_off and g_on.' + if conductance > crossbar.devices[row][column].g: + time_signal, voltage_signal = gen_programming_signal(1, pulse_duration, refactory_period, pos_voltage_level, crossbar.devices[row][column].time_series_resolution) + while conductance >= crossbar.devices[row][column].g: + crossbar.devices[row][column].simulate(voltage_signal) + for row_ in range(0, crossbar.rows): + if row_ != row: + crossbar.devices[row_, column].simulate(voltage_signal / 2) + + for column_ in range(0, crossbar.columns): + if column_ != column: + crossbar.devices[row, column_].simulate(voltage_signal / 2) + elif conductance < crossbar.devices[row][column].g: + time_signal, voltage_signal = gen_programming_signal(1, pulse_duration, refactory_period, neg_voltage_level, crossbar.devices[row][column].time_series_resolution) + while conductance <= crossbar.devices[row][column].g: + crossbar.devices[row][column].simulate(voltage_signal) + for row_ in range(0, crossbar.rows): + if row_ != row: + crossbar.devices[row_, column].simulate(voltage_signal / 2) + + for column_ in range(0, crossbar.columns): + if column_ != column: + crossbar.devices[row, column_].simulate(voltage_signal / 2) + + return crossbar.devices[row][column] + +def gen_programming_signal(number_of_pulses, pulse_duration, refactory_period, voltage_level, time_series_resolution): + """Method to generate a programming signal using a sequence of pulses. + + Parameters + ---------- + number_of_pulses : int + Number of pulses. + pulse_duration : float + Duration of the programming pulse (s). + refactory_period : float + Duration of the refactory period (s). + voltage_level : float + Voltage level (V). + time_series_resolution : float + Time series resolution (s). + + Returns + ------- + tuple + Tuple containing the generated time and voltage signals. + """ + period = pulse_duration + refactory_period + duration = number_of_pulses * period + assert_tol = 1e-9 + assert abs(pulse_duration/time_series_resolution - round(pulse_duration/time_series_resolution)) <= assert_tol, 'pulse_duration must be divisible by time_series_resolution.' + assert abs(refactory_period/time_series_resolution - round(refactory_period/time_series_resolution)) <= assert_tol, 'refactory_period must be divisible by time_series_resolution.' + time_signal = np.arange(0, duration, step=time_series_resolution) + period = np.zeros(round(period / time_series_resolution)) + period[0:round(pulse_duration / time_series_resolution)] = voltage_level + voltage_signal = np.tile(period, number_of_pulses) + return time_signal, voltage_signal diff --git a/memtorch/bh/crossbar/__init__.py b/memtorch/bh/crossbar/__init__.py new file mode 100644 index 00000000..81aeaf57 --- /dev/null +++ b/memtorch/bh/crossbar/__init__.py @@ -0,0 +1,2 @@ +from .Crossbar import * +from .Program import * diff --git a/memtorch/bh/memristor/LinearIonDrift.py b/memtorch/bh/memristor/LinearIonDrift.py new file mode 100644 index 00000000..fc55c683 --- /dev/null +++ b/memtorch/bh/memristor/LinearIonDrift.py @@ -0,0 +1,107 @@ +import memtorch +from .Memristor import Memristor as Memristor +from memtorch.utils import convert_range +import numpy as np +import torch +import math + + +class LinearIonDrift(Memristor): + """Linear Ion behvaioural drift model. + + Parameters + ---------- + time_series_resolution : float + Time series resolution (s). + u_v : float + Dopant drift mobility of the device material. + d : float + Device length (m). + r_on : float + On (minimum) resistance of the device (ohms). + r_off : float + Off (maximum) resistance of the device (ohms). + pos_write_threshold: float + Positive write threshold voltage (V). + neg_write_threshold : float + Negative write threshold voltage (V). + p : int + Joglekar window p constant. + """ + def __init__(self, + time_series_resolution=1e-4, + u_v=1e-14, + d=10e-9, + r_on=100, + r_off=16e3, + pos_write_threshold=0.55, + neg_write_threshold=-0.55, + p=1, + **kwargs): + + args = memtorch.bh.unpack_parameters(locals()) + super(LinearIonDrift, self).__init__(args.time_series_resolution, args.pos_write_threshold, args.neg_write_threshold) + self.u_v = args.u_v + self.d = args.d + self.r_on = args.r_on + self.r_off = args.r_off + self.r_i = args.r_off + self.p = args.p + self.g = 1 / self.r_i + self.x = convert_range(self.r_i, self.r_off, self.r_on, 0, 1) + + def simulate(self, voltage_signal, return_current=False): + if return_current: + current = np.zeros(len(voltage_signal)) + + for t in range(0, len(voltage_signal)): + current_ = self.current(voltage_signal[t]) + if voltage_signal[t] >= self.pos_write_threshold or voltage_signal[t] <= self.neg_write_threshold: + self.x = self.x + self.dxdt(current_) * self.time_series_resolution + + self.g = current_ / voltage_signal[t] + if self.g > (1 / self.r_on): + self.g = 1 / self.r_on + elif self.g < (1 / self.r_off): + self.g = 1 / self.r_off + + if return_current: + current[t] = current_ + + if return_current: + return current + else: + return + + def current(self, voltage): + """Method to determine the current of the model given an applied voltage. + + Parameters + ---------- + voltage : float + The current applied voltage (V). + + Returns + ------- + float + The observed current (A). + """ + return voltage / (((self.r_on * self.x) + (self.r_off * (1 - self.x)))) + + def dxdt(self, current): + """Method to determine the derivative of the state variable, dx/dt. + + Parameters + ---------- + current : float + The observed current (A). + + Returns + ------- + float + The derivative of the state variable, dx/dt. + """ + return self.u_v * (self.r_on / (self.d ** 2)) * current * memtorch.bh.memristor.window.Jogelkar(self.x, self.p) + + def plot_hysteresis_loop(self, duration=4, voltage_signal_amplitude=5, voltage_signal_frequency=2.5, return_result=False): + return super().plot_hysteresis_loop(self, duration=duration, voltage_signal_amplitude=voltage_signal_amplitude, voltage_signal_frequency=voltage_signal_frequency, return_result=return_result) diff --git a/memtorch/bh/memristor/Memristor.py b/memtorch/bh/memristor/Memristor.py new file mode 100644 index 00000000..7845097e --- /dev/null +++ b/memtorch/bh/memristor/Memristor.py @@ -0,0 +1,107 @@ +from abc import ABC, abstractmethod +import torch +import memtorch +import numpy as np +import math +import matplotlib.pyplot as plt + + +class Memristor(ABC): + """ + Parameters + ---------- + time_series_resolution : float + Time series resolution (s). + pos_write_threshold : float + Positive write threshold voltage (V). + neg_write_threshold : float + Negative write threshold voltage (V). + """ + + def __init__(self, time_series_resolution, pos_write_threshold=0, neg_write_threshold=0): + self.time_series_resolution = time_series_resolution + self.pos_write_threshold = pos_write_threshold + self.neg_write_threshold = neg_write_threshold + self.g = None + self.finite_states = None + + @abstractmethod + def simulate(self, voltage_signal): + """Method to determine the equivalent conductance of a memristive device when a given voltage signal is applied. + + Parameters + ---------- + voltage_signal : torch.Tensor + A discrete voltage signal with resolution time_series_resolution. + + Returns + ------- + torch.Tensor + A tensor containing the equivalent device conductance for each simulated timestep. + """ + return + + def get_resistance(self): + """ + Method to determine the resistance of a memristive device. + + Returns + ------- + float + The devices resistance (ohms). + """ + return 1 / self.g + + def plot_hysteresis_loop(self, memristor, duration, voltage_signal_amplitude, voltage_signal_frequency, return_result=False): + """Method to plot the hysteresis loop of a given device. + + Parameters + ---------- + memristor_model : memtorch.bh.memristor.Memristor.Memristor + Memristor model. + duration : float + Duration (s). + voltage_signal_amplitude: float + Voltage signal amplitude (V). + voltage_signal_frequency : float + Voltage signal frequency (Hz) + return_result: bool + Voltage and current signals are returned (True). + """ + return plot_hysteresis_loop(memristor, duration, voltage_signal_amplitude, voltage_signal_frequency, return_result) + + +def plot_hysteresis_loop(memristor_model, duration, voltage_signal_amplitude, voltage_signal_frequency, return_result=False): + """Method to plot the hysteresis loop of a given device. + + Parameters + ---------- + memristor_model : memtorch.bh.memristor.Memristor.Memristor + Memristor model. + duration : float + Duration (s). + voltage_signal_amplitude: float + Voltage signal amplitude (V). + voltage_signal_frequency : float + Voltage signal frequency (Hz) + return_result: bool + Voltage and current signals are returned (True). + + Returns + ------- + tuple + Voltage and current signals. + """ + time_signal = np.arange(0, duration + memristor_model.time_series_resolution, step=memristor_model.time_series_resolution) + voltage_signal = voltage_signal_amplitude * np.sin(2 * math.pi * voltage_signal_frequency * time_signal) + current_signal = memristor_model.simulate(voltage_signal, return_current=True) + if return_result: + return voltage_signal, current_signal + else: + plt.figure() + plt.title('Hysteresis Loop') + plt.xlabel('Voltage (V)') + plt.ylabel('Current (A)') + plt.plot(voltage_signal, current_signal) + plt.show() + return diff --git a/memtorch/bh/memristor/VTEAM.py b/memtorch/bh/memristor/VTEAM.py new file mode 100644 index 00000000..a34f6b64 --- /dev/null +++ b/memtorch/bh/memristor/VTEAM.py @@ -0,0 +1,131 @@ +import memtorch +from .Memristor import Memristor as Memristor +import numpy as np +import torch +import math + + +class VTEAM(Memristor): + """VTEAM memristor model. + + Parameters + ---------- + time_series_resolution : float + Time series resolution (s). + r_off : float + Off (maximum) resistance of the device (ohms). + r_on : float + On (minimum) resistance of the device (ohms). + d : float + Device length (m). + k_on : float + k_on model parameter. + k_off: float + k_off model parameter. + alpha_on : float + alpha_on model parameter. + alpha_off : float + alpha_off model parameter. + v_on : float + Positive write threshold voltage (V). + v_off : float + Negative write threshold voltage (V). + x_on : float + x_on model parameter. + x_off : float + x_off model parameter. + """ + def __init__(self, + time_series_resolution=1e-10, + r_off=1000, + r_on=50, + d=3e-9, + k_on=-10, + k_off=5e-4, + alpha_on=3, + alpha_off=1, + v_on=-0.2, + v_off=0.02, + x_on=0, + x_off=3e-9, + **kwargs): + + args = memtorch.bh.unpack_parameters(locals()) + super(VTEAM, self).__init__(args.time_series_resolution, args.v_off, args.v_on) + self.r_off = args.r_off + self.r_on = args.r_on + self.d = args.d + self.k_on = args.k_on + self.k_off = args.k_off + self.alpha_on = args.alpha_on + self.alpha_off = args.alpha_off + self.v_on = args.v_on + self.v_off = args.v_off + self.x_on = args.x_on + self.x_off = args.x_off + self.g = 1 / self.r_on + self.x = self.x_on + self.lamda = np.log(self.r_off / self.r_on) + + def dxdt(self, voltage): + """ Method to determine the derivative of the state variable. + + Parameters + ---------- + voltage : float + The current applied voltage (V). + + Returns + ------- + float + The derivative of the state variable. + """ + if voltage >= self.v_off: + return self.k_off * (((voltage / self.v_off) - 1) ** self.alpha_off) + elif voltage <= self.v_on: + return self.k_on * (((voltage / self.v_on) - 1) ** self.alpha_on) + else: + return 0 + + def current(self, voltage): + """Method to determine the current of the model given an applied voltage. + + Parameters + ---------- + voltage : float + The current applied voltage (V). + + Returns + ------- + float + The observed current (A). + """ + return voltage / (self.r_off * self.x / self.d + self.r_on * (1 - self.x / self.d)) + + def simulate(self, voltage_signal, return_current=False): + if return_current: + current = np.zeros(len(voltage_signal)) + + x = np.zeros(len(voltage_signal)) + for t in range(0, len(voltage_signal)): + self.x = self.x + (self.dxdt(voltage_signal[t]) * self.time_series_resolution) + if self.x >= self.d or self.x <= 0: + if self.x >= self.d: + self.x = self.d + else: + self.x = 0 + + current_ = self.current(voltage_signal[t]) + if voltage_signal[t] != 0: + self.g = current_ / voltage_signal[t] + + if return_current: + current[t] = current_ + + if return_current: + return current + else: + return + + def plot_hysteresis_loop(self, duration=200e-9, voltage_signal_amplitude=1, voltage_signal_frequency=50e6, return_result=False): + return super(VTEAM, self).plot_hysteresis_loop(self, duration=duration, voltage_signal_amplitude=voltage_signal_amplitude, voltage_signal_frequency=voltage_signal_frequency, return_result=return_result) diff --git a/memtorch/bh/memristor/__init__.py b/memtorch/bh/memristor/__init__.py new file mode 100644 index 00000000..61b194e9 --- /dev/null +++ b/memtorch/bh/memristor/__init__.py @@ -0,0 +1,4 @@ +from .Memristor import * +from .window import * +from .LinearIonDrift import * +from .VTEAM import * diff --git a/memtorch/bh/memristor/window/Biolek.py b/memtorch/bh/memristor/window/Biolek.py new file mode 100644 index 00000000..73a0a93b --- /dev/null +++ b/memtorch/bh/memristor/window/Biolek.py @@ -0,0 +1,22 @@ +import torch +import memtorch +import numpy as np +import math + + +def Biolek(voltage, x, p): + """Biolek window function. + + Parameters + ---------- + voltage : float + Input voltage (V). + x : float + State variable. + p : int + p constant. + """ + def step(x): + return 1 * (x > 0) + + return (1 - (1 - x - step(voltage)) ** (2 * p)) diff --git a/memtorch/bh/memristor/window/Jogelkar.py b/memtorch/bh/memristor/window/Jogelkar.py new file mode 100644 index 00000000..997ed7c7 --- /dev/null +++ b/memtorch/bh/memristor/window/Jogelkar.py @@ -0,0 +1,17 @@ +import torch +import memtorch +import numpy as np +import math + + +def Jogelkar(x, p): + """Jogelkar window function. + + Parameters + ---------- + x : float + State variable. + p : int + p constant. + """ + return (1 - (2 * x - 1)) ** (2 * p) diff --git a/memtorch/bh/memristor/window/Prodromakis.py b/memtorch/bh/memristor/window/Prodromakis.py new file mode 100644 index 00000000..cb3ffc60 --- /dev/null +++ b/memtorch/bh/memristor/window/Prodromakis.py @@ -0,0 +1,19 @@ +import torch +import memtorch +import numpy as np +import math + + +def Prodromakis(x, p, j): + """Prodromakis window function. + + Parameters + ---------- + x : float + State variable. + p : int + p constant. + j : float + j constant. + """ + return j * ((1 - (x - 0.5) ** 2 + 0.75) ** p) diff --git a/memtorch/bh/memristor/window/__init__.py b/memtorch/bh/memristor/window/__init__.py new file mode 100644 index 00000000..4d7b7c47 --- /dev/null +++ b/memtorch/bh/memristor/window/__init__.py @@ -0,0 +1,3 @@ +from .Biolek import * +from .Jogelkar import * +from .Prodromakis import * diff --git a/memtorch/bh/nonideality/DeviceFaults.py b/memtorch/bh/nonideality/DeviceFaults.py new file mode 100644 index 00000000..0ecf76b6 --- /dev/null +++ b/memtorch/bh/nonideality/DeviceFaults.py @@ -0,0 +1,46 @@ +import torch +import memtorch +import numpy as np + + +def apply_device_faults(layer, lrs_proportion, hrs_proportion, electroform_proportion): + """Method to model device failure within a memristive layer. + + Parameters + ---------- + layer : memtorch.mn + A memrstive layer. + lrs_proportion : float + Proportion of devices which become stuck at a low resistance state. + hrs_proportion : float + Proportion of devices which become stuck at a high resistance state. + electroform_proportion : float + Proportion of devices which fail to electroform. + + Returns + ------- + memtorch.mn + The patched memristive layer. + """ + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + def apply_device_faults_to_crossbar(crossbar, lrs_proportion, hrs_proportion): + crossbar_min = torch.tensor(1 / (np.vectorize(lambda x: x.r_off)(crossbar.devices))).view(-1).to(device) + crossbar_max = torch.tensor(1 / (np.vectorize(lambda x: x.r_on)(crossbar.devices))).view(-1).to(device) + crossbar_min_indices = np.random.choice(np.arange(torch.numel(crossbar_min)), replace=False, size=int(torch.numel(crossbar_min) * hrs_proportion)) + crossbar_shape = crossbar.conductance_matrix.shape + crossbar.conductance_matrix = crossbar.conductance_matrix.view(-1) + for index in crossbar_min_indices: + crossbar.conductance_matrix[index] = crossbar_min[index] + + crossbar_max_indices = np.random.choice(np.arange(torch.numel(crossbar_max)), replace=False, size=int(torch.numel(crossbar_max) * lrs_proportion)) + for index in crossbar_max_indices: + crossbar.conductance_matrix[index] = crossbar_max[index] + + crossbar.conductance_matrix = crossbar.conductance_matrix.view(crossbar_shape) + return crossbar + + hrs_proportion = hrs_proportion + electroform_proportion + for i in range(len(layer.crossbars)): + layer.crossbars[i] = apply_device_faults_to_crossbar(layer.crossbars[i], lrs_proportion, hrs_proportion) + + return layer diff --git a/memtorch/bh/nonideality/FiniteConductanceStates.py b/memtorch/bh/nonideality/FiniteConductanceStates.py new file mode 100644 index 00000000..50ecb116 --- /dev/null +++ b/memtorch/bh/nonideality/FiniteConductanceStates.py @@ -0,0 +1,36 @@ +import torch +import memtorch +import numpy as np +if torch.cuda.is_available(): + import cuda_quantization as quantization +else: + import quantization + + +def apply_finite_conductance_states(layer, num_conductance_states): + """Method to model a finite number of conductance states for devices within a memristive layer. + + Parameters + ---------- + layer : memtorch.mn + A memrstive layer. + num_conductance_states : int + Number of finite conductance states to model. + + Returns + ------- + memtorch.mn + The patched memristive layer. + """ + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + assert int(num_conductance_states) == num_conductance_states, 'num_conductance_states must be a whole number.' + def apply_finite_conductance_states_to_crossbar(crossbar, num_conductance_states): + crossbar_min = torch.tensor(1 / (np.vectorize(lambda x: x.r_off)(crossbar.devices))).view(-1).to(device).float() + crossbar_max = torch.tensor(1 / (np.vectorize(lambda x: x.r_on)(crossbar.devices))).view(-1).to(device).float() + quantization.quantize(crossbar.conductance_matrix, num_conductance_states, crossbar_min, crossbar_max) + return crossbar + + for i in range(len(layer.crossbars)): + layer.crossbars[i] = apply_finite_conductance_states_to_crossbar(layer.crossbars[i], num_conductance_states) + + return layer diff --git a/memtorch/bh/nonideality/NonIdeality.py b/memtorch/bh/nonideality/NonIdeality.py new file mode 100644 index 00000000..0ac9642e --- /dev/null +++ b/memtorch/bh/nonideality/NonIdeality.py @@ -0,0 +1,91 @@ +import memtorch +import memtorch.mn +from memtorch.bh.nonideality.FiniteConductanceStates import apply_finite_conductance_states +from memtorch.bh.nonideality.DeviceFaults import apply_device_faults +from memtorch.bh.nonideality.NonLinear import apply_non_linear +from memtorch.mn.Module import supported_module_parameters +import numpy as np +import torch +import math +from enum import Enum, auto, unique + + +@unique +class NonIdeality(Enum): + """NonIdeality enumeration.""" + FiniteConductanceStates = auto() + DeviceFaults = auto() + NonLinear = auto() + + +def apply_nonidealities(model, non_idealities, **kwargs): + """Method to apply non-idealities to a torch.nn.Module instance with memristive layers. + + Parameters + ---------- + model : torch.nn.Module + torch.nn.Module instance. + nonidealities : memtorch.bh.nonideality.NonIdeality.NonIdeality, tuple + Non-linearitites to model. + + Returns + ------- + torch.nn.Module + Patched instance. + """ + for i, (name, m) in enumerate(list(model.named_modules())): + if type(m) in supported_module_parameters.values(): + if torch.cuda.is_available() and len(name.split('.')) > 1: + name = name.split('.')[1] + + for non_ideality in non_idealities: + if non_ideality == NonIdeality.FiniteConductanceStates: + required(kwargs, ['conductance_states'], 'memtorch.bh.nonideality.NonIdeality.FiniteConductanceStates') + if hasattr(model, 'module'): + setattr(model.module, name, apply_finite_conductance_states(m, kwargs['conductance_states'])) + else: + setattr(model, name, apply_finite_conductance_states(m, kwargs['conductance_states'])) + + if non_ideality == NonIdeality.DeviceFaults: + required(kwargs, ['lrs_proportion', 'hrs_proportion', 'electroform_proportion'], 'memtorch.bh.nonideality.NonIdeality.DeviceFaults') + if hasattr(model, 'module'): + setattr(model.module, name, apply_device_faults(m, kwargs['lrs_proportion'], kwargs['hrs_proportion'], kwargs['electroform_proportion'])) + else: + setattr(model, name, apply_device_faults(m, kwargs['lrs_proportion'], kwargs['hrs_proportion'], kwargs['electroform_proportion'])) + + if non_ideality == NonIdeality.NonLinear: + if 'simulate' in kwargs: + if kwargs['simulate'] == True: + if hasattr(model, 'module'): + setattr(model.module, name, apply_non_linear(m, simulate=True)) + else: + setattr(model, name, apply_non_linear(m, simulate=True)) + else: + required(kwargs, ['sweep_duration', 'sweep_voltage_signal_amplitude', 'sweep_voltage_signal_frequency'], 'memtorch.bh.nonideality.NonIdeality.NonLinear') + if hasattr(model, 'module'): + setattr(model.module, name, apply_non_linear(m, kwargs['sweep_duration'], kwargs['sweep_voltage_signal_amplitude'], kwargs['sweep_voltage_signal_frequency'])) + else: + setattr(model, name, apply_non_linear(m, kwargs['sweep_duration'], kwargs['sweep_voltage_signal_amplitude'], kwargs['sweep_voltage_signal_frequency'])) + else: + required(kwargs, ['sweep_duration', 'sweep_voltage_signal_amplitude', 'sweep_voltage_signal_frequency'], 'memtorch.bh.nonideality.NonIdeality.NonLinear') + if hasattr(model, 'module'): + setattr(model.module, name, apply_non_linear(m, kwargs['sweep_duration'], kwargs['sweep_voltage_signal_amplitude'], kwargs['sweep_voltage_signal_frequency'])) + else: + setattr(model, name, apply_non_linear(m, kwargs['sweep_duration'], kwargs['sweep_voltage_signal_amplitude'], kwargs['sweep_voltage_signal_frequency'])) + + return model + +def required(kwargs, arguments, call): + """Method to check is required arguments in **kwargs are present. + + Parameters + ---------- + kwargs : **kwargs + Keyword-arguments. + arguments : list of str + Arguments which are required to be present. + call : str + Function to call. + """ + for argument in arguments: + assert kwargs[argument] is not None, '%s is required when calling %s' % (argument, call) diff --git a/memtorch/bh/nonideality/NonLinear.py b/memtorch/bh/nonideality/NonLinear.py new file mode 100644 index 00000000..a7745c1d --- /dev/null +++ b/memtorch/bh/nonideality/NonLinear.py @@ -0,0 +1,64 @@ +import torch +import memtorch +import numpy as np +import math +import copy +import matplotlib.pyplot as plt + + +def apply_non_linear(layer, sweep_duration=1, sweep_voltage_signal_amplitude=1, sweep_voltage_signal_frequency=1, num_conductance_states=None, simulate=False): + """Method to model non_linear iv characteristics for devices within a memristive layer. + + Parameters + ---------- + layer : memtorch.mn + A memrstive layer. + sweep_duration : float + Voltage sweep duration (s). + sweep_voltage_signal_amplitude : float + Voltage sweep amplitude (v). + sweep_voltage_signal_frequency : float + Voltage sweep frequency (Hz). + num_conductance_states : int + Number of finite conductance states to model. None indicates finite states are not to be modeled. + simulate : bool + Each device is simulated during inference (True). + + Returns + ------- + memtorch.mn + The patched memristive layer. + """ + def apply_non_linear_to_device(device, sweep_duration, sweep_voltage_signal_amplitude, sweep_voltage_signal_frequency): + time_signal = np.arange(0, sweep_duration + device.time_series_resolution, step=device.time_series_resolution) + voltage_signal = np.cos(2 * math.pi * sweep_voltage_signal_frequency * time_signal) + current_signal = copy.deepcopy(device).simulate(voltage_signal, return_current=True) + + def det_current(voltage): + if np.isnan(voltage): + return 0 + + assert abs(voltage) <= sweep_voltage_signal_amplitude, 'voltage must be between -sweep_voltage_signal_amplitude and sweep_voltage_signal_amplitude.' + if voltage < 0: + return -1 * current_signal[::-1][np.searchsorted(voltage_signal[::-1], -1 * voltage, side="left")] + else: + return current_signal[::-1][np.searchsorted(voltage_signal[::-1], voltage, side="left")] + + device.det_current = det_current + return device + + def apply_non_linear_to_crossbar(crossbar, sweep_duration, sweep_voltage_signal_amplitude, sweep_voltage_signal_frequency): + crossbar.devices.flat = [apply_non_linear_to_device(device, sweep_duration, sweep_voltage_signal_amplitude, sweep_voltage_signal_frequency) for device in crossbar.devices.flat] + return crossbar + + layer.non_linear = True + if simulate: + layer.simulate = True + else: + if num_conductance_states is None: + for i in range(len(layer.crossbars)): + layer.crossbars[i] = apply_non_linear_to_crossbar(layer.crossbars[i], sweep_duration, sweep_voltage_signal_amplitude, sweep_voltage_signal_frequency) + else: + raise('To be implemented.') + + return layer diff --git a/memtorch/bh/nonideality/__init__.py b/memtorch/bh/nonideality/__init__.py new file mode 100644 index 00000000..ed3aae15 --- /dev/null +++ b/memtorch/bh/nonideality/__init__.py @@ -0,0 +1,2 @@ +from .NonIdeality import * +from .FiniteConductanceStates import * diff --git a/memtorch/cpp/quantize/quant.cpp b/memtorch/cpp/quantize/quant.cpp new file mode 100644 index 00000000..4884c106 --- /dev/null +++ b/memtorch/cpp/quantize/quant.cpp @@ -0,0 +1,44 @@ +#include +#include + +void quantize_element(float* tensor, int index, float* quant_levels, int num_quant_levels) { + int middle_point; // Middle point + int optimal_point = 0; // Optimal point + int l = 0; // Lower bound + int h = num_quant_levels; // Higher bound + float difference = 1.0f; // Difference between a given point and the current middle point + while (l <= h) { + middle_point = l + (h - l) / 2; + if (abs(tensor[index] - quant_levels[middle_point]) < difference) { + difference = abs(tensor[index] - quant_levels[middle_point]); + optimal_point = middle_point; + } + if (quant_levels[middle_point] < tensor[index]) { + l = middle_point + 1; + } else { + h = middle_point - 1; + } + } + tensor[index] = quant_levels[optimal_point]; +} + +void quant(at::Tensor tensor, int num_quant_levels, float min_value, float max_value) { + torch::Tensor quant_levels = at::linspace(min_value, max_value, num_quant_levels); + for (int i = 0; i < tensor.numel(); i += 1) { + quantize_element(tensor.data(), i, quant_levels.data(), num_quant_levels); + } +} + +void quant(at::Tensor tensor, int num_quant_levels, at::Tensor min_values, at::Tensor max_values) { + float* min_values_ = min_values.data(); + float* max_values_ = max_values.data(); + for (int i = 0; i < tensor.numel(); i += 1) { + torch::Tensor quant_levels = at::linspace(min_values_[i], max_values_[i], num_quant_levels); + quantize_element(tensor.data(), i, quant_levels.data(), num_quant_levels); + } +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("quantize", (void (*)(at::Tensor, int, float, float)) &quant, "tbd"); + m.def("quantize", (void (*)(at::Tensor, int, at::Tensor, at::Tensor)) &quant, "tbd"); +} diff --git a/memtorch/cu/quantize/gpu.cuh b/memtorch/cu/quantize/gpu.cuh new file mode 100644 index 00000000..35356610 --- /dev/null +++ b/memtorch/cu/quantize/gpu.cuh @@ -0,0 +1,7 @@ +#include +constexpr int CUDA_NUM_THREADS = 128; +constexpr int MAXIMUM_NUM_BLOCKS = 4096; + +inline int GET_BLOCKS(const int N) { + return std::max(std::min((N + CUDA_NUM_THREADS - 1) / CUDA_NUM_THREADS, MAXIMUM_NUM_BLOCKS), 1); +} diff --git a/memtorch/cu/quantize/quant.cu b/memtorch/cu/quantize/quant.cu new file mode 100644 index 00000000..85dd2aeb --- /dev/null +++ b/memtorch/cu/quantize/quant.cu @@ -0,0 +1,80 @@ +#include +#include +#include +#include +#include "cuda_runtime.h" +#include "gpu.cuh" +#include + +__device__ float quantize_element(float element, float* quant_levels, int num_quant_levels) { + int middle_point; // Middle point + int optimal_point = 0; // Optimal point + int l = 0; // Lower bound + int h = num_quant_levels; // Higher bound + float difference = 1.0f; // Difference between a given point and the current middle point + while (l <= h) { + middle_point = l + (h - l) / 2; + if (abs(element - quant_levels[middle_point]) < difference) { + difference = abs(element - quant_levels[middle_point]); + optimal_point = middle_point; + } + if (quant_levels[middle_point] < element) { + l = middle_point + 1; + } else { + h = middle_point - 1; + } + } + return quant_levels[optimal_point]; +} + +__global__ void quantize(int num_quant_levels, + float* quant_levels, + int num_elements, + float* tensor) { + + int index = blockIdx.x * blockDim.x + threadIdx.x; + int stride = blockDim.x * gridDim.x; + + for (int i = index; i < num_elements; i += stride) { + tensor[i] = quantize_element(tensor[i], quant_levels, num_quant_levels); + } +} + +__global__ void quantize_(int num_quant_levels, + float* min_values, + float* max_values, + int num_elements, + float* tensor) { + + int index = blockIdx.x * blockDim.x + threadIdx.x; + int stride = blockDim.x * gridDim.x; + + float* quant_levels = new float[num_quant_levels]; + for (int i = index; i < num_elements; i += stride) { + // Manually generate linspace vectors + float step_size = (max_values[i] - min_values[i]) / (num_quant_levels - 1); + for (int j = 0; j < num_quant_levels; ++j) { + quant_levels[j] = min_values[i] + j * step_size; + } + quant_levels[num_quant_levels - 1] = max_values[i]; + tensor[i] = quantize_element(tensor[i], quant_levels, num_quant_levels); + } + free(quant_levels); +} + +void quant_cuda(at::Tensor tensor, int num_quant_levels, float min_value, float max_value) { + torch::Tensor quant_levels = at::linspace(min_value, max_value, num_quant_levels); + float *quant_levels_gpu; + cudaMalloc(&quant_levels_gpu, sizeof(float) * quant_levels.numel()); + cudaMemcpy(quant_levels_gpu, quant_levels.data(), sizeof(float) * quant_levels.numel(), cudaMemcpyHostToDevice); + quantize<<>>(num_quant_levels, quant_levels_gpu, tensor.numel(), tensor.data()); + cudaDeviceSynchronize(); + cudaStreamSynchronize(at::cuda::getCurrentCUDAStream()); + cudaFree(quant_levels_gpu); +} + +void quant_cuda(at::Tensor tensor, int num_quant_levels, at::Tensor min_values, at::Tensor max_values) { + quantize_<<>>(num_quant_levels, min_values.data(), max_values.data(), tensor.numel(), tensor.data()); + cudaDeviceSynchronize(); + cudaStreamSynchronize(at::cuda::getCurrentCUDAStream()); +} diff --git a/memtorch/cu/quantize/quant_cuda.cpp b/memtorch/cu/quantize/quant_cuda.cpp new file mode 100644 index 00000000..15f44de8 --- /dev/null +++ b/memtorch/cu/quantize/quant_cuda.cpp @@ -0,0 +1,33 @@ +#include +#include +#include + +// CUDA kernels +void quant_cuda(at::Tensor tensor, int num_quant_levels, float min_value, float max_value); +void quant_cuda(at::Tensor tensor, int num_quant_levels, at::Tensor min_values, at::Tensor max_values); + +void quant(at::Tensor tensor, int num_quant_levels, float min_value, float max_value) { + if (at::cuda::is_available()) { + tensor.to(torch::Device("cuda:0")); + quant_cuda(tensor, num_quant_levels, min_value, max_value); + } else { + printf("To be supported.\n"); + } +} + +void quant(at::Tensor tensor, int num_quant_levels, at::Tensor min_values, at::Tensor max_values) { + if (at::cuda::is_available()) { + assert(tensor.numel() == min_values.numel() == max_values.numel()); + tensor.to(torch::Device("cuda:0")); + min_values.to(torch::Device("cuda:0")); + max_values.to(torch::Device("cuda:0")); + quant_cuda(tensor, num_quant_levels, min_values, max_values); + } else { + printf("To be supported.\n"); + } +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("quantize", (void (*)(at::Tensor, int, float, float)) &quant, "tbd"); + m.def("quantize", (void (*)(at::Tensor, int, at::Tensor, at::Tensor)) &quant, "tbd"); +} diff --git a/memtorch/examples/CaseStudy.ipynb b/memtorch/examples/CaseStudy.ipynb new file mode 100644 index 00000000..9ba6f977 --- /dev/null +++ b/memtorch/examples/CaseStudy.ipynb @@ -0,0 +1,513 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# A Case Study - Seizure Detection" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 1. Seizure detection dataset" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import torch\n", + "from torch.utils.data import Dataset\n", + "import torch.nn.functional as F\n", + "import torch.nn as nn\n", + "import pandas as pd\n", + "import numpy as np\n", + "import sklearn\n", + "from sklearn import preprocessing\n", + "\n", + "\n", + "class SeizureDataset(Dataset):\n", + "\n", + " def __init__(self, path_to_csv):\n", + " self.features = pd.read_csv(path_to_csv)\n", + " self.labels = self.features.pop('y')\n", + " self.features = preprocessing.scale(self.features.iloc[:, 1:], axis=0)\n", + "\n", + " def __len__(self):\n", + " return len(self.labels)\n", + "\n", + " def __getitem__(self, i):\n", + " if self.labels[i] == 1:\n", + " label = 1\n", + " else:\n", + " label = 0\n", + "\n", + " return np.asarray(self.features[i, :]).astype(np.float), label\n", + "\n", + "csv_path = 'http://archive.ics.uci.edu/ml/machine-learning-databases/00388/data.csv'\n", + "dataset = SeizureDataset(path_to_csv=csv_path)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Network architecture" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class EEGNet(nn.Module):\n", + " def __init__(self):\n", + " super(EEGNet, self).__init__()\n", + " self.fc1 = nn.Linear(178, 200)\n", + " self.batchnorm1 = nn.BatchNorm1d(200)\n", + " self.fc2 = nn.Linear(200, 200)\n", + " self.batchnorm2 = nn.BatchNorm1d(200)\n", + " self.fc3 = nn.Linear(200, 200)\n", + " self.batchnorm3 = nn.BatchNorm1d(200)\n", + " self.fc4 = nn.Linear(200, 2)\n", + " self.batchnorm4 = nn.BatchNorm1d(2)\n", + "\n", + " def forward(self, x):\n", + " x = self.batchnorm1(F.relu(self.fc1(x)))\n", + " x = self.batchnorm2(F.relu(self.fc2(x)))\n", + " x = self.batchnorm3(F.relu(self.fc3(x)))\n", + " x = self.batchnorm4(self.fc4(x))\n", + " return F.log_softmax(x, dim=1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Training methodology" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import sklearn\n", + "from sklearn.model_selection import KFold\n", + "\n", + "\n", + "init_lr = 1e-1\n", + "batch_size = 1024\n", + "\n", + "def get_device():\n", + " if torch.cuda.is_available():\n", + " device = 'cuda:0'\n", + " else:\n", + " device = 'cpu'\n", + " return device\n", + "\n", + "def adjust_lr(optimizer, epoch):\n", + " lr = init_lr * (0.1 ** (epoch // 20))\n", + " for param_group in optimizer.param_groups:\n", + " param_group['lr'] = lr\n", + "\n", + " return lr\n", + "\n", + "def train(net, train_loader, test_loader, epochs=10, fold=0):\n", + " print('fold %d' % fold)\n", + " best_f1_score = 0\n", + " for epoch in range(epochs):\n", + " lr = adjust_lr(optimizer, epoch)\n", + " running_loss = 0\n", + " for data in train_loader:\n", + " inputs, labels = data\n", + " inputs = inputs.float()\n", + " if device == 'cuda:0':\n", + " inputs = inputs.cuda()\n", + " labels = labels.cuda()\n", + "\n", + " optimizer.zero_grad()\n", + " outputs = net(inputs)\n", + " loss = criterion(outputs, labels)\n", + " loss.backward()\n", + " optimizer.step()\n", + " running_loss += loss.item()\n", + "\n", + " f1_score = test(net, test_loader)\n", + " if f1_score > best_f1_score:\n", + " torch.save(net.state_dict(), 'trained_net_fold_%d.pt' % fold)\n", + " best_f1_score = f1_score\n", + "\n", + " print('[Epoch %d] lr: %.4f f1_score: %.4f\\ttraining loss: %.4f' % (epoch + 1, lr, f1_score, running_loss / len(train_loader)))\n", + "\n", + "def test(net, test_loader):\n", + " confusion_matrix = torch.zeros(2, 2)\n", + " correct = 0\n", + " total = 0\n", + " with torch.no_grad():\n", + " for data in test_loader:\n", + " inputs, labels = data\n", + " inputs = inputs.float()\n", + " if device == 'cuda:0':\n", + " inputs = inputs.cuda()\n", + " labels = labels.cuda()\n", + "\n", + " outputs = net(inputs)\n", + " _, predicted = torch.max(outputs.data, 1)\n", + " for t, p in zip(labels.view(-1), predicted.view(-1)):\n", + " confusion_matrix[t.long(), p.long()] += 1\n", + "\n", + " total += labels.size(0)\n", + " correct += (predicted == labels).sum().item()\n", + "\n", + " f1_score = 2 * confusion_matrix[0][0] / (2 * confusion_matrix[0][0] + confusion_matrix[0][1] + confusion_matrix[1][0])\n", + " return f1_score.item()\n", + "\n", + "device = get_device()\n", + "dataset = SeizureDataset(csv_path)\n", + "torch.manual_seed(0)\n", + "kf = KFold(n_splits=5, shuffle=True)\n", + "train_loaders = []\n", + "test_loaders = []\n", + "for i, (train_index, test_index) in enumerate(kf.split(dataset)):\n", + " train_ = torch.utils.data.Subset(dataset, train_index)\n", + " test_ = torch.utils.data.Subset(dataset, test_index)\n", + " train_loaders.append(torch.utils.data.DataLoader(train_, batch_size=batch_size, shuffle=True))\n", + " test_loaders.append(torch.utils.data.DataLoader(test_, batch_size=batch_size, shuffle=False))\n", + "\n", + "torch.manual_seed(torch.initial_seed())\n", + "torch.save(test_loaders, 'test_loaders.pth')\n", + "assert(len(train_loaders) == len(test_loaders))\n", + "\n", + "# Determine the baseline F1 score\n", + "df = pd.DataFrame(columns=['indentifier', 'fold', 'f1_score'])\n", + "for indentifier in range(100):\n", + " test_loaders = torch.load('test_loaders.pth')\n", + " for fold in range(len(test_loaders)):\n", + " net = EEGNet()\n", + " if torch.cuda.is_available():\n", + " net = torch.nn.DataParallel(net)\n", + "\n", + " f1_score = test(net, test_loaders[fold])\n", + " df = df.append({'indentifier': indentifier, 'fold': fold, 'f1_score': f1_score}, ignore_index=True)\n", + "\n", + " df.to_csv('baseline.csv', index=False)\n", + "\n", + "# Determine the F1 score\n", + "for fold in range(len(train_loaders)):\n", + " net = EEGNet().to(device)\n", + " criterion = torch.nn.CrossEntropyLoss()\n", + " optimizer = torch.optim.Adam(net.parameters(), lr=init_lr)\n", + " train(net, train_loaders[fold], test_loaders[fold], epochs=50, fold=fold)\n", + "\n", + "fold_f1_scores = []\n", + "for fold in range(len(train_loaders)):\n", + " net = EEGNet().to(device)\n", + " net.load_state_dict(torch.load('trained_net_fold_%d.pt' % fold), strict=True)\n", + " fold_f1_scores.append(test(net, test_loaders[fold]))\n", + " print('f1_score of fold %d: %0.4f' % (fold, fold_f1_scores[fold]))\n", + "\n", + "print('baseline -> mean: %0.4f\\tstddev: %0.4f' % (np.mean(df['f1_score'].values), np.std(df['f1_score'].values)))\n", + "print('trained -> mean: %0.4f\\tstddev: %0.4f' % (np.mean(fold_f1_scores), np.std(fold_f1_scores)))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. Network conversion" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import memtorch\n", + "from memtorch.mn.Module import patch_model\n", + "from memtorch.map.Parameter import naive_map\n", + "from memtorch.bh.crossbar.Program import naive_program\n", + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "import copy\n", + "\n", + "\n", + "test_loaders = torch.load('test_loaders.pth')\n", + "\n", + "# Determine the first baseline F1 score\n", + "df = pd.DataFrame(columns=['indentifier', 'fold', 'f1_score'])\n", + "for indentifier in range(100):\n", + " for fold in range(len(test_loaders)):\n", + " net = EEGNet()\n", + " net.load_state_dict(torch.load('trained_net_fold_%d.pt' % fold), strict=True)\n", + " if torch.cuda.is_available():\n", + " net = torch.nn.DataParallel(net)\n", + "\n", + " patched_net = patch_model(copy.deepcopy(net),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None,\n", + " scheme=memtorch.bh.Scheme.DoubleColumn)\n", + "\n", + " for i, (name, m) in enumerate(list(patched_net.named_modules())):\n", + " if isinstance(m, memtorch.mn.Linear):\n", + " m.crossbars[0].conductance_matrix = m.crossbars[0].conductance_matrix.uniform_(1 / 2.5e3, 1 / 100)\n", + " m.crossbars[1].conductance_matrix = m.crossbars[1].conductance_matrix.uniform_(1 / 2.5e3, 1 / 100)\n", + "\n", + " patched_net.tune_()\n", + " f1_score = test(patched_net, test_loaders[fold])\n", + " df = df.append({'indentifier': indentifier, 'fold': fold, 'f1_score': f1_score}, ignore_index=True)\n", + "\n", + " df.to_csv('baseline_variability.csv', index=False)\n", + "\n", + "# Determine the second baseline F1 score\n", + "df_2 = pd.DataFrame(columns=['indentifier', 'fold', 'f1_score'])\n", + "for indentifier in range(100):\n", + " for fold in range(len(test_loaders)):\n", + " net = EEGNet()\n", + " if torch.cuda.is_available():\n", + " net = torch.nn.DataParallel(net)\n", + "\n", + " patched_net = patch_model(copy.deepcopy(net),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None,\n", + " scheme=memtorch.bh.Scheme.DoubleColumn)\n", + "\n", + " for i, (name, m) in enumerate(list(patched_net.named_modules())):\n", + " if isinstance(m, memtorch.mn.Linear):\n", + " m.crossbars[0].conductance_matrix = m.crossbars[0].conductance_matrix.uniform_(1 / 2.5e3, 1 / 100)\n", + " m.crossbars[1].conductance_matrix = m.crossbars[1].conductance_matrix.uniform_(1 / 2.5e3, 1 / 100)\n", + "\n", + " f1_score = test(patched_net, test_loaders[fold])\n", + " df_2 = df_2.append({'indentifier': indentifier, 'fold': fold, 'f1_score': f1_score}, ignore_index=True)\n", + "\n", + " df_2.to_csv('baseline_variability_no_tune.csv', index=False)\n", + "\n", + "# Determine the F1 score\n", + "fold_f1_scores = []\n", + "for fold in range(len(test_loaders)):\n", + " net = EEGNet()\n", + " net.load_state_dict(torch.load('trained_net_fold_%d.pt' % fold), strict=False)\n", + " if torch.cuda.is_available():\n", + " net = torch.nn.DataParallel(net)\n", + "\n", + " reference_memristor = memtorch.bh.memristor.VTEAM\n", + " reference_memristor_params = {'time_series_resolution': 1e-6,\n", + " 'alpha_off': 1,\n", + " 'alpha_on': 3,\n", + " 'v_off': 0.5,\n", + " 'v_on': -0.53,\n", + " 'r_off': 2.5e3,\n", + " 'r_on': 100,\n", + " 'k_off': 4.03e-8,\n", + " 'k_on': -80,\n", + " 'd': 10e-9,\n", + " 'x_on': 0,\n", + " 'x_off': 10e-9}\n", + "\n", + " patched_net = patch_model(net,\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None,\n", + " scheme=memtorch.bh.Scheme.DoubleColumn)\n", + "\n", + " patched_net.tune_()\n", + " f1_score = test(patched_net, test_loaders[fold])\n", + " fold_f1_scores.append(f1_score)\n", + "\n", + "tuned_baseline = np.mean(df['f1_score'].values)\n", + "print('baseline -> mean: %0.4f\\tstddev: %0.4f' % (np.mean(df_2['f1_score'].values), np.std(df_2['f1_score'].values))) \n", + "print('tuned baseline -> mean: %0.4f\\tstddev: %0.4f' % (np.mean(df['f1_score'].values), np.std(df['f1_score'].values)))\n", + "print('trained and tuned -> mean: %0.4f\\tstddev: %0.4f' % (np.mean(fold_f1_scores), np.std(fold_f1_scores)))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "# Plot the hysteresis loop\n", + "palette = [\"#DA4453\", \"#8CC152\", \"#4A89DC\", \"#F6BB42\", \"#B600B0\", \"#535353\"]\n", + "f = plt.figure(figsize=(16/3, 4))\n", + "plt.title('Hysteresis Loop')\n", + "plt.xlabel('Voltage (V)')\n", + "plt.ylabel('Current (A)')\n", + "j = 0\n", + "for i in range(10):\n", + " j = j + 1\n", + " if j == 6:\n", + " j = 0\n", + "\n", + " memristor = reference_memristor(**reference_memristor_params)\n", + " voltage_signal, current_signal = memristor.plot_hysteresis_loop(duration=2, voltage_signal_amplitude=1, voltage_signal_frequency = 0.5, return_result=True)\n", + " plt.plot(voltage_signal, current_signal, color=palette[j])\n", + "\n", + "plt.grid()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 5. Device-to-device variability investigation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Determine the F1 score\n", + "df = pd.DataFrame(columns=['sigma', 'mean', 'std'])\n", + "sigma_values = np.linspace(0, 500, 21)\n", + "for sigma in sigma_values:\n", + " f1_scores = []\n", + " for fold in range(len(test_loaders)):\n", + " net = EEGNet()\n", + " net.load_state_dict(torch.load('trained_net_fold_%d.pt' % fold), strict=True)\n", + " if torch.cuda.is_available():\n", + " net = torch.nn.DataParallel(net)\n", + "\n", + " non_linear_reference_memristor_params = {'time_series_resolution': 1e-6,\n", + " 'alpha_off': 1,\n", + " 'alpha_on': 3,\n", + " 'v_off': 0.5,\n", + " 'v_on': -0.53,\n", + " 'r_off': memtorch.bh.StochasticParameter(2.5e3, std=sigma*2, min=1),\n", + " 'r_on': memtorch.bh.StochasticParameter(100, std=sigma, min=1),\n", + " 'k_off': 4.03e-8,\n", + " 'k_on': -80,\n", + " 'd': 10e-9,\n", + " 'x_on': 0,\n", + " 'x_off': 10e-9}\n", + " \n", + " patched_net = patch_model(copy.deepcopy(net),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=non_linear_reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None,\n", + " scheme=memtorch.bh.Scheme.DoubleColumn)\n", + "\n", + " patched_net.tune_()\n", + " f1_score = test(patched_net, test_loaders[fold])\n", + " f1_scores.append(f1_score)\n", + "\n", + " df = df.append({'sigma': sigma, 'mean': np.mean(f1_scores), 'std': np.std(f1_scores)}, ignore_index=True)\n", + "\n", + "df.to_csv('variability.csv', index=False)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "f = plt.figure(figsize=(16/3, 4))\n", + "plt.axhline(y=tuned_baseline, color='k', linestyle='--', zorder=1)\n", + "b = plt.bar(df['sigma'], df['mean'], width=12.5, zorder=2)\n", + "plt.xlabel('$\\sigma$')\n", + "plt.ylabel('F1 Score')\n", + "for bar in b:\n", + " bar.set_edgecolor('black')\n", + " bar.set_facecolor(palette[0])\n", + " bar.set_linewidth(1)\n", + "\n", + "f.tight_layout()\n", + "plt.grid()\n", + "plt.ylim([0.9, 1.0])\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 6. Non-linear IV characteristics investigation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Determine the F1 score\n", + "df = pd.DataFrame(columns=['sigma', 'mean', 'std'])\n", + "sigma_values = np.linspace(0, 500, 11)\n", + "f1_scores = []\n", + "for fold in range(len(test_loaders)):\n", + " net = EEGNet()\n", + " net.load_state_dict(torch.load('trained_net_fold_%d.pt' % fold), strict=False)\n", + " if torch.cuda.is_available():\n", + " net = torch.nn.DataParallel(net)\n", + "\n", + " patched_net = patch_model(net,\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None,\n", + " scheme=memtorch.bh.Scheme.DoubleColumn)\n", + "\n", + " patched_net = apply_nonidealities(patched_net,\n", + " non_idealities=[memtorch.bh.nonideality.NonIdeality.NonLinear],\n", + " sweep_duration=2,\n", + " sweep_voltage_signal_amplitude=1,\n", + " sweep_voltage_signal_frequency=0.5)\n", + "\n", + " patched_net.tune_()\n", + " f1_score = test(patched_net, test_loaders[fold])\n", + " f1_scores.append(f1_score)\n", + "\n", + "print('mean: %0.4f\\tstddev: %0.4f' % (np.mean(f1_scores), np.std(f1_scores))) " + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/memtorch/examples/NovelSimulations.ipynb b/memtorch/examples/NovelSimulations.ipynb new file mode 100644 index 00000000..1d9f7e58 --- /dev/null +++ b/memtorch/examples/NovelSimulations.ipynb @@ -0,0 +1,687 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Novel Simulations" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 1. Define and train a VGG Convolutional Neural Network (CNN) using CIFAR-10" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch.optim as optim\n", + "from torch.autograd import Variable\n", + "import memtorch\n", + "from memtorch.utils import LoadCIFAR10\n", + "\n", + "\n", + "class Net(nn.Module):\n", + " def __init__(self, inflation_ratio=1):\n", + " super(Net, self).__init__()\n", + " self.conv0 = nn.Conv2d(in_channels=3, out_channels=128*inflation_ratio, kernel_size=3, stride=1, padding=1)\n", + " self.bn0 = nn.BatchNorm2d(num_features=128*inflation_ratio)\n", + " self.act0 = nn.ReLU()\n", + " self.conv1 = nn.Conv2d(in_channels=128*inflation_ratio, out_channels=128*inflation_ratio, kernel_size=3, padding=1)\n", + " self.bn1 = nn.BatchNorm2d(num_features=128*inflation_ratio)\n", + " self.act1 = nn.ReLU()\n", + " self.conv2 = nn.Conv2d(in_channels=128*inflation_ratio, out_channels=256*inflation_ratio, kernel_size=3, padding=1)\n", + " self.bn2 = nn.BatchNorm2d(num_features=256*inflation_ratio)\n", + " self.act2 = nn.ReLU()\n", + " self.conv3 = nn.Conv2d(in_channels=256*inflation_ratio, out_channels=256*inflation_ratio, kernel_size=3, padding=1)\n", + " self.bn3 = nn.BatchNorm2d(num_features=256*inflation_ratio)\n", + " self.act3 = nn.ReLU()\n", + " self.conv4 = nn.Conv2d(in_channels=256*inflation_ratio, out_channels=512*inflation_ratio, kernel_size=3, padding=1)\n", + " self.bn4 = nn.BatchNorm2d(num_features=512*inflation_ratio)\n", + " self.act4 = nn.ReLU()\n", + " self.conv5 = nn.Conv2d(in_channels=512*inflation_ratio, out_channels=512, kernel_size=3, padding=1)\n", + " self.bn5 = nn.BatchNorm2d(num_features=512)\n", + " self.act5 = nn.ReLU()\n", + " self.fc6 = nn.Linear(in_features=512*4*4, out_features=1024)\n", + " self.bn6 = nn.BatchNorm1d(num_features=1024)\n", + " self.act6 = nn.ReLU()\n", + " self.fc7 = nn.Linear(in_features=1024, out_features=1024)\n", + " self.bn7 = nn.BatchNorm1d(num_features=1024)\n", + " self.act7 = nn.ReLU()\n", + " self.fc8 = nn.Linear(in_features=1024, out_features=10)\n", + "\n", + " def forward(self, input):\n", + " x = self.act0(self.bn0(self.conv0(input)))\n", + " x = self.act1(self.bn1(F.max_pool2d(self.conv1(x), 2)))\n", + " x = self.act2(self.bn2(self.conv2(x)))\n", + " x = self.act3(self.bn3(F.max_pool2d(self.conv3(x), 2)))\n", + " x = self.act4(self.bn4(self.conv4(x)))\n", + " x = self.act5(self.bn5(F.max_pool2d(self.conv5(x), 2)))\n", + " x = x.view(x.size(0), -1)\n", + " x = self.act6(self.bn6(self.fc6(x)))\n", + " x = self.act7(self.bn7(self.fc7(x)))\n", + " return self.fc8(x)\n", + " \n", + " \n", + "def test(model, test_loader):\n", + " correct = 0\n", + " for batch_idx, (data, target) in enumerate(test_loader): \n", + " output = model(data.to(device))\n", + " pred = output.data.max(1)[1]\n", + " correct += pred.eq(target.to(device).data.view_as(pred)).cpu().sum()\n", + "\n", + " return 100. * float(correct) / float(len(test_loader.dataset))\n", + "\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "epochs = 50\n", + "train_loader, validation_loader, test_loader = LoadCIFAR10(batch_size=256, validation=False)\n", + "model = Net().to(device)\n", + "if device == 'cuda':\n", + " model = torch.nn.DataParallel(model)\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "learning_rate = 1e-2\n", + "optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n", + "best_accuracy = 0\n", + "for epoch in range(0, epochs):\n", + " print('Epoch: [%d]\\t\\t' % (epoch + 1), end='')\n", + " if epoch % 20 == 0:\n", + " learning_rate = learning_rate * 0.1\n", + " for param_group in optimizer.param_groups:\n", + " param_group['lr'] = learning_rate\n", + "\n", + " model.train()\n", + " for batch_idx, (data, target) in enumerate(train_loader):\n", + " optimizer.zero_grad()\n", + " output = model(data.to(device))\n", + " loss = criterion(output, target.to(device))\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " accuracy = test(model, test_loader)\n", + " print('%2.2f%%' % accuracy)\n", + " if accuracy > best_accuracy:\n", + " torch.save(model.state_dict(), 'trained_model.pt')\n", + " best_accuracy = accuracy" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Load and test the network" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import copy\n", + "import pandas as pd\n", + "import matplotlib\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "\n", + "model = Net().to(device)\n", + "try:\n", + " model.load_state_dict(torch.load('trained_model.pt'), strict=False)\n", + "except:\n", + " raise Exception('trained_model.pt has not been found.')\n", + " \n", + "print('Test Set Accuracy: \\t%2.2f%%' % test(model, test_loader))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Import seaborn and define an appropriate color-palette" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "\n", + "\n", + "palette = [\"#DA4453\", \"#8CC152\", \"#4A89DC\", \"#F6BB42\", \"#B600B0\", \"#535353\"]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. Device-device variability investigation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from memtorch.mn.Module import patch_model\n", + "from memtorch.map.Parameter import naive_map\n", + "from memtorch.bh.crossbar.Program import naive_program\n", + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "\n", + "\n", + "def trial(r_on, r_off, sigma):\n", + " model_ = copy.deepcopy(model)\n", + " reference_memristor = memtorch.bh.memristor.VTEAM\n", + " reference_memristor_params = {'time_series_resolution': 1e-10,\n", + " 'r_off': memtorch.bh.StochasticParameter(r_off, std=sigma*2, min=1),\n", + " 'r_on': memtorch.bh.StochasticParameter(r_on, std=sigma, min=1)}\n", + "\n", + " patched_model = patch_model(copy.deepcopy(model_),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear, torch.nn.Conv2d],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None)\n", + " \n", + " patched_model.tune_()\n", + " return test(patched_model, test_loader)\n", + "\n", + "df = pd.DataFrame(columns=['sigma', 'test_set_accuracy'])\n", + "r_on = 200\n", + "r_off = 500\n", + "sigma_values = np.linspace(0, 100, 21)\n", + "for sigma in sigma_values:\n", + " df = df.append({'sigma': sigma, 'test_set_accuracy': trial(r_on, r_off, sigma)}, ignore_index=True)\n", + " \n", + "df.to_csv('variability.csv', index=False)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "df = pd.read_csv('variability.csv')\n", + "f = plt.figure()\n", + "plt.axhline(y=10, color='k', linestyle='--', zorder=1)\n", + "b = plt.bar(df['sigma'], df['test_set_accuracy'], width=2.5, zorder=2)\n", + "plt.xlabel('$\\sigma$')\n", + "plt.ylabel('CIFAR-10 Test-set Accuracy (%)')\n", + "for bar in b:\n", + " bar.set_edgecolor('black')\n", + " bar.set_facecolor(palette[0])\n", + " bar.set_linewidth(1)\n", + " \n", + "f.tight_layout()\n", + "plt.grid()\n", + "plt.savefig(\"P1.svg\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 5. Finite conductance states investigation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from memtorch.mn.Module import patch_model\n", + "from memtorch.map.Parameter import naive_map\n", + "from memtorch.bh.crossbar.Program import naive_program\n", + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "\n", + "\n", + "def trial(r_on, r_off, finite_states):\n", + " model_ = copy.deepcopy(model)\n", + " reference_memristor = memtorch.bh.memristor.VTEAM\n", + " reference_memristor_params = {'time_series_resolution': 1e-10,\n", + " 'r_off': r_off,\n", + " 'r_on': r_on}\n", + "\n", + " patched_model = patch_model(copy.deepcopy(model_),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear, torch.nn.Conv2d],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None)\n", + " \n", + " patched_model = apply_nonidealities(patched_model,\n", + " non_idealities=[memtorch.bh.nonideality.NonIdeality.FiniteConductanceStates],\n", + " conductance_states = int(finite_states))\n", + " \n", + " patched_model.tune_()\n", + " return test(patched_model, test_loader)\n", + "\n", + "df = pd.DataFrame(columns=['finite_states', 'test_set_accuracy'])\n", + "r_on = 200\n", + "r_off = 500\n", + "finite_state_values = np.linspace(1, 10, 10)\n", + "for finite_states in finite_state_values:\n", + " df = df.append({'finite_states': finite_states, 'test_set_accuracy': trial(r_on, r_off, finite_states)}, ignore_index=True)\n", + " \n", + "df.to_csv('finite_states.csv', index=False)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "df = pd.read_csv('finite_states.csv')\n", + "f = plt.figure()\n", + "plt.axhline(y=10, color='k', linestyle='--', zorder=1)\n", + "b = plt.bar(df['finite_states'], df['test_set_accuracy'], width=0.5, zorder=2)\n", + "plt.xlabel('Number of Finite States')\n", + "plt.ylabel('CIFAR-10 Test-set Accuracy (%)')\n", + "plt.xticks(df['finite_states'])\n", + "for bar in b:\n", + " bar.set_edgecolor('black')\n", + " bar.set_facecolor(palette[0])\n", + " bar.set_linewidth(1)\n", + " \n", + "f.tight_layout()\n", + "plt.grid()\n", + "plt.savefig(\"P2.svg\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 6. Device failure investigation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from memtorch.mn.Module import patch_model\n", + "from memtorch.map.Parameter import naive_map\n", + "from memtorch.bh.crossbar.Program import naive_program\n", + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "\n", + "\n", + "def trial(r_on, r_off, lrs_proportion, hrs_proportion):\n", + " model_ = copy.deepcopy(model)\n", + " reference_memristor = memtorch.bh.memristor.VTEAM\n", + " reference_memristor_params = {'time_series_resolution': 1e-10,\n", + " 'r_off': r_off,\n", + " 'r_on': r_on}\n", + "\n", + " patched_model = patch_model(copy.deepcopy(model_),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear, torch.nn.Conv2d],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None)\n", + " \n", + " patched_model = apply_nonidealities(patched_model,\n", + " non_idealities=[memtorch.bh.nonideality.NonIdeality.DeviceFaults],\n", + " lrs_proportion=lrs_proportion,\n", + " hrs_proportion=hrs_proportion,\n", + " electroform_proportion=0)\n", + " \n", + " patched_model.tune_()\n", + " return test(patched_model, test_loader)\n", + "\n", + "df_lrs_hrs = pd.DataFrame(columns=['failure_percentage', 'test_set_accuracy'])\n", + "df_lrs = pd.DataFrame(columns=['failure_percentage', 'test_set_accuracy'])\n", + "df_hrs = pd.DataFrame(columns=['failure_percentage', 'test_set_accuracy'])\n", + "r_on = 200\n", + "r_off = 500\n", + "failures = np.linspace(0, 0.25, 11)\n", + "\n", + "for failure in failures:\n", + " df_lrs_hrs = df_lrs_hrs.append({'failure_percentage': failure, 'test_set_accuracy': trial(r_on, r_off, failure, failure)}, ignore_index=True)\n", + " df_lrs = df_lrs.append({'failure_percentage': failure, 'test_set_accuracy': trial(r_on, r_off, failure, 0)}, ignore_index=True) \n", + " df_hrs = df_hrs.append({'failure_percentage': failure, 'test_set_accuracy': trial(r_on, r_off, 0, failure)}, ignore_index=True) \n", + " \n", + "df_lrs_hrs.to_csv('failure_lrs_hrs.csv', index=False)\n", + "df_lrs.to_csv('failure_lrs.csv', index=False)\n", + "df_hrs.to_csv('failure_hrs.csv', index=False)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "from matplotlib.ticker import FormatStrFormatter\n", + "\n", + "\n", + "df_lrs_hrs = pd.read_csv('failure_lrs_hrs.csv')\n", + "df_lrs = pd.read_csv('failure_lrs.csv')\n", + "df_hrs = pd.read_csv('failure_hrs.csv')\n", + "f = plt.figure()\n", + "plt.axhline(y=10, color='k', linestyle='--', zorder=1)\n", + "concat = pd.concat([df_lrs_hrs['failure_percentage'], \n", + " df_lrs_hrs['test_set_accuracy'], \n", + " df_lrs['test_set_accuracy'], \n", + " df_hrs['test_set_accuracy']], \n", + " axis=1)\n", + "concat.columns = ['failure_percentage', 'lrs_hrs', 'lrs', 'hrs']\n", + "data = pd.DataFrame(columns=['failure_percentage', 'state', 'test_set_accuracy'])\n", + "for index, row in concat.iterrows():\n", + " data = data.append({'failure_percentage': row['failure_percentage'] * 100, 'state': 'lrs_hrs', 'test_set_accuracy': row['lrs_hrs']}, ignore_index=True)\n", + " data = data.append({'failure_percentage': row['failure_percentage'] * 100, 'state': 'lrs', 'test_set_accuracy': row['lrs']}, ignore_index=True)\n", + " data = data.append({'failure_percentage': row['failure_percentage'] * 100, 'state': 'hrs', 'test_set_accuracy': row['hrs']}, ignore_index=True)\n", + " \n", + "data['state'] = data['state'].map({'lrs_hrs': '$R_{ON}$ and $R_{OFF}$', 'lrs': '$R_{ON}$', 'hrs': '$R_{OFF}$'})\n", + "h = sns.barplot(x=\"failure_percentage\", hue=\"state\", y=\"test_set_accuracy\", data=data, zorder=2, edgecolor='black', linewidth='1', palette=sns.color_palette(palette), saturation=1)\n", + "plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%1.1f'))\n", + "plt.xticks(np.arange(11), np.arange(0, 25 + 2.5, step=2.5))\n", + "h.legend(loc=1)\n", + "plt.xlabel('Device Failure (%)')\n", + "plt.ylabel('CIFAR-10 Test-set Accuracy (%)') \n", + "f.tight_layout()\n", + "plt.grid()\n", + "plt.savefig(\"P3.svg\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 7. First novel simulation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from memtorch.mn.Module import patch_model\n", + "from memtorch.map.Parameter import naive_map\n", + "from memtorch.bh.crossbar.Program import naive_program\n", + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "\n", + "\n", + "def trial(num_conductance_states, g_ratio, sigma):\n", + " model_ = copy.deepcopy(model)\n", + " r_on = 200\n", + " reference_memristor = memtorch.bh.memristor.VTEAM\n", + " reference_memristor_params = {'time_series_resolution': 1e-10,\n", + " 'r_off': memtorch.bh.StochasticParameter(r_on * g_ratio, std=sigma*2, min=1),\n", + " 'r_on': memtorch.bh.StochasticParameter(r_on, std=sigma, min=1)}\n", + " patched_model = patch_model(copy.deepcopy(model_),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear, torch.nn.Conv2d],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None)\n", + " patched_model = apply_nonidealities(patched_model,\n", + " non_idealities=[memtorch.bh.nonideality.NonIdeality.FiniteConductanceStates],\n", + " conductance_states=int(num_conductance_states))\n", + " patched_model.tune_()\n", + " return test(patched_model, test_loader)\n", + "\n", + "std_devs = [0, 20, 100]\n", + "g_ratios = [2 ** n for n in range(6)]\n", + "conductance_states = np.linspace(2, 10, 9)\n", + "for std_dev in std_devs:\n", + " df = pd.DataFrame(columns=['conductance_states', 'g_ratio', 'test_set_accuracy'])\n", + " for g_ratio in g_ratios:\n", + " for num_conductance_states in conductance_states:\n", + " test_set_accuracy = trial(num_conductance_states, g_ratio, std_dev)\n", + " df = df.append({'conductance_states': num_conductance_states, \n", + " 'g_ratio': g_ratio, \n", + " 'test_set_accuracy': test_set_accuracy}, ignore_index=True)\n", + " \n", + " df.to_csv('S1_std_dev_%d.csv' % std_dev, index=False)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "scrolled": false + }, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "from matplotlib.ticker import FormatStrFormatter\n", + "\n", + "f = plt.figure(figsize=(16, 4))\n", + "plt.subplot(1, len(std_devs), 1)\n", + "for plot_index, std_dev in enumerate(std_devs):\n", + " plt.subplot(1, len(std_devs), plot_index + 1)\n", + " plt.axhline(y=10, color='k', linestyle='--', zorder=1)\n", + " data = pd.read_csv('S1_std_dev_%d.csv' % std_dev)\n", + " h = sns.barplot(x=\"conductance_states\", hue=\"g_ratio\", y=\"test_set_accuracy\", data=data, zorder=2, edgecolor='black', linewidth='1', palette=sns.color_palette(palette), saturation=1)\n", + " plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%1.0f'))\n", + " plt.xticks(np.arange(0, len(conductance_states)), map(lambda n: \"%d\" % n, conductance_states))\n", + " leg = h.axes.get_legend()\n", + " leg.set_title('RON/ROFF Ratio')\n", + " h.legend(loc=1)\n", + " plt.title('$\\sigma$ = %d' % std_dev)\n", + " if plot_index == 0:\n", + " plt.xlabel('Number of Finite States')\n", + " plt.ylabel('CIFAR-10 Test-set Accuracy (%)')\n", + " else:\n", + " plt.xlabel('')\n", + " plt.ylabel('')\n", + " \n", + " plt.grid()\n", + " \n", + "f.tight_layout()\n", + "plt.savefig(\"S1.svg\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 8. Second novel simulation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from memtorch.mn.Module import patch_model\n", + "from memtorch.map.Parameter import naive_map\n", + "from memtorch.bh.crossbar.Program import naive_program\n", + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "\n", + "\n", + "def trial(num_conductance_states, lrs_failure_rate, hrs_failure_rate, sigma):\n", + " model_ = copy.deepcopy(model)\n", + " r_on = 200\n", + " r_off = 500\n", + " reference_memristor = memtorch.bh.memristor.VTEAM\n", + " reference_memristor_params = {'time_series_resolution': 1e-10,\n", + " 'r_off': memtorch.bh.StochasticParameter(r_on * g_ratio, std=sigma*2, min=1),\n", + " 'r_on': memtorch.bh.StochasticParameter(r_off, std=sigma, min=1)}\n", + " patched_model = patch_model(copy.deepcopy(model_),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear, torch.nn.Conv2d],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None)\n", + " patched_model = apply_nonidealities(patched_model,\n", + " non_idealities=[memtorch.bh.nonideality.NonIdeality.FiniteConductanceStates,\n", + " memtorch.bh.nonideality.NonIdeality.DeviceFaults],\n", + " conductance_states=int(num_conductance_states),\n", + " lrs_proportion=lrs_failure_rate,\n", + " hrs_proportion=hrs_failure_rate,\n", + " electroform_proportion=0)\n", + " patched_model.tune_()\n", + " return test(patched_model, test_loader)\n", + "\n", + "std_devs = [0, 20, 100]\n", + "failure_rates = np.linspace(0, 0.25, 6)\n", + "conductance_states = np.linspace(2, 10, 9)\n", + "\n", + "# LRS\n", + "for std_dev in std_devs:\n", + " df = pd.DataFrame(columns=['conductance_states', 'failure_rate', 'test_set_accuracy'])\n", + " for failure_rate in failure_rates:\n", + " for num_conductance_states in conductance_states:\n", + " test_set_accuracy = trial(num_conductance_states, failure_rate, 0, std_dev)\n", + " df = df.append({'conductance_states': num_conductance_states, \n", + " 'failure_rate': failure_rate, \n", + " 'test_set_accuracy': test_set_accuracy}, ignore_index=True)\n", + " \n", + " df.to_csv('S2_LRS_std_dev_%d.csv' % std_dev, index=False)\n", + " \n", + "# HRS\n", + "for std_dev in std_devs:\n", + " df = pd.DataFrame(columns=['conductance_states', 'failure_rate', 'test_set_accuracy'])\n", + " for failure_rate in failure_rates:\n", + " for num_conductance_states in conductance_states:\n", + " test_set_accuracy = trial(num_conductance_states, 0, failure_rate, std_dev)\n", + " df = df.append({'conductance_states': num_conductance_states, \n", + " 'failure_rate': failure_rate, \n", + " 'test_set_accuracy': test_set_accuracy}, ignore_index=True)\n", + " \n", + " df.to_csv('S2_HRS_std_dev_%d.csv' % std_dev, index=False)\n", + " \n", + "# LRS and HRS\n", + "for std_dev in std_devs:\n", + " df = pd.DataFrame(columns=['conductance_states', 'failure_rate', 'test_set_accuracy'])\n", + " for failure_rate in failure_rates:\n", + " for num_conductance_states in conductance_states:\n", + " test_set_accuracy = trial(num_conductance_states, failure_rate, failure_rate, std_dev)\n", + " df = df.append({'conductance_states': num_conductance_states, \n", + " 'failure_rate': failure_rate, \n", + " 'test_set_accuracy': test_set_accuracy}, ignore_index=True)\n", + " \n", + " df.to_csv('S2_LRS_HRS_std_dev_%d.csv' % std_dev, index=False)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import seaborn as sns\n", + "from matplotlib.ticker import FormatStrFormatter\n", + "\n", + "f = plt.figure(figsize=(16, 12))\n", + "plt.subplot(3, len(std_devs), 1)\n", + "# LRS\n", + "for plot_index, std_dev in enumerate(std_devs):\n", + " plt.subplot(3, len(std_devs), plot_index + 1)\n", + " plt.axhline(y=10, color='k', linestyle='--', zorder=1)\n", + " data = pd.read_csv('S2_LRS_std_dev_%d.csv' % std_dev)\n", + " h = sns.barplot(x=\"conductance_states\", hue=\"failure_rate\", y=\"test_set_accuracy\", data=data, zorder=2, edgecolor='black', linewidth='1', palette=sns.color_palette(palette), saturation=1)\n", + " plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%1.0f'))\n", + " plt.xticks(np.arange(0, len(conductance_states)), map(lambda n: \"%d\" % n, conductance_states))\n", + " leg = h.axes.get_legend()\n", + " leg.set_title('Device Failure (%)')\n", + " h.legend(loc=1)\n", + " plt.title('$\\sigma$ = %d' % std_dev)\n", + " if plot_index == 0:\n", + " plt.xlabel('Number of Finite States')\n", + " plt.ylabel('[LRS] CIFAR-10 Test-set Accuracy (%)')\n", + " else:\n", + " plt.xlabel('')\n", + " plt.ylabel('')\n", + " \n", + " plt.grid()\n", + " \n", + "# HRS\n", + "for plot_index, std_dev in enumerate(std_devs):\n", + " plt.subplot(3, len(std_devs), plot_index + 1 + len(std_devs))\n", + " plt.axhline(y=10, color='k', linestyle='--', zorder=1)\n", + " data = pd.read_csv('S2_HRS_std_dev_%d.csv' % std_dev)\n", + " h = sns.barplot(x=\"conductance_states\", hue=\"failure_rate\", y=\"test_set_accuracy\", data=data, zorder=2, edgecolor='black', linewidth='1', palette=sns.color_palette(palette), saturation=1)\n", + " plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%1.0f'))\n", + " plt.xticks(np.arange(0, len(conductance_states)), map(lambda n: \"%d\" % n, conductance_states))\n", + " leg = h.axes.get_legend()\n", + " leg.set_title('Device Failure (%)')\n", + " h.legend(loc=1)\n", + " plt.title('$\\sigma$ = %d' % std_dev)\n", + " if plot_index == 0:\n", + " plt.xlabel('Number of Finite States')\n", + " plt.ylabel('[HRS] CIFAR-10 Test-set Accuracy (%)')\n", + " else:\n", + " plt.xlabel('')\n", + " plt.ylabel('')\n", + " \n", + " plt.grid()\n", + " \n", + "# LRS and HRS\n", + "for plot_index, std_dev in enumerate(std_devs):\n", + " plt.subplot(3, len(std_devs), plot_index + 1 + 2 * len(std_devs))\n", + " plt.axhline(y=10, color='k', linestyle='--', zorder=1)\n", + " data = pd.read_csv('S2_LRS_HRS_std_dev_%d.csv' % std_dev)\n", + " h = sns.barplot(x=\"conductance_states\", hue=\"failure_rate\", y=\"test_set_accuracy\", data=data, zorder=2, edgecolor='black', linewidth='1', palette=sns.color_palette(palette), saturation=1)\n", + " plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%1.0f'))\n", + " plt.xticks(np.arange(0, len(conductance_states)), map(lambda n: \"%d\" % n, conductance_states))\n", + " leg = h.axes.get_legend()\n", + " leg.set_title('Device Failure (%)')\n", + " h.legend(loc=1)\n", + " plt.title('$\\sigma$ = %d' % std_dev)\n", + " if plot_index == 0:\n", + " plt.xlabel('Number of Finite States')\n", + " plt.ylabel('[LRS and HRS] CIFAR-10 Test-set Accuracy (%)')\n", + " else:\n", + " plt.xlabel('')\n", + " plt.ylabel('')\n", + " \n", + " plt.grid()\n", + " \n", + "f.tight_layout()\n", + "plt.savefig(\"S2.svg\")\n", + "plt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/memtorch/examples/Tutorial.ipynb b/memtorch/examples/Tutorial.ipynb new file mode 100644 index 00000000..1d960ebc --- /dev/null +++ b/memtorch/examples/Tutorial.ipynb @@ -0,0 +1,562 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# MemTorch Tutorial" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "qBYEsnSav5E1" + }, + "source": [ + "## 1. Training and benchmarking a DNN using CIFAR-10" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "HCy9QqPHv5E3" + }, + "source": [ + "The VGG-16 DNN architecture is trained and tested using the CIFAR-10 data set. The CIFAR-10 data set consists of 60,000 32x32 color images in 10 classes, with 6,000 images per class. There are 50,000 training images and 10,000 test images. The network is trained for 50 epochs with a batch size, $\\Im=256$. The initial learning rate is $\\eta = 1e-2$, which is decayed by an order of magnitude every 20 training epochs. Adam is used to optimize network parameters and Cross Entropy (CE) is used to determine network losses. *memtorch.utils.LoadCIFAR10* is used to load the CIFAR-10 training and test sets. After each epoch the model is bench-marked using the CIFAR-10 test set. The model that achieves the highest test set accuracy is saved as *trained_model.pt*." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "jVH_tu3tv5E4" + }, + "outputs": [], + "source": [ + "import torch\n", + "from torch.autograd import Variable\n", + "import memtorch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch.optim as optim\n", + "from memtorch.utils import LoadCIFAR10\n", + "import numpy as np\n", + "\n", + "\n", + "class Net(nn.Module):\n", + " def __init__(self, inflation_ratio=1):\n", + " super(Net, self).__init__()\n", + " self.conv0 = nn.Conv2d(in_channels=3, out_channels=128*inflation_ratio, kernel_size=3, stride=1, padding=1)\n", + " self.bn0 = nn.BatchNorm2d(num_features=128*inflation_ratio)\n", + " self.act0 = nn.ReLU()\n", + " self.conv1 = nn.Conv2d(in_channels=128*inflation_ratio, out_channels=128*inflation_ratio, kernel_size=3, padding=1)\n", + " self.bn1 = nn.BatchNorm2d(num_features=128*inflation_ratio)\n", + " self.act1 = nn.ReLU()\n", + " self.conv2 = nn.Conv2d(in_channels=128*inflation_ratio, out_channels=256*inflation_ratio, kernel_size=3, padding=1)\n", + " self.bn2 = nn.BatchNorm2d(num_features=256*inflation_ratio)\n", + " self.act2 = nn.ReLU()\n", + " self.conv3 = nn.Conv2d(in_channels=256*inflation_ratio, out_channels=256*inflation_ratio, kernel_size=3, padding=1)\n", + " self.bn3 = nn.BatchNorm2d(num_features=256*inflation_ratio)\n", + " self.act3 = nn.ReLU()\n", + " self.conv4 = nn.Conv2d(in_channels=256*inflation_ratio, out_channels=512*inflation_ratio, kernel_size=3, padding=1)\n", + " self.bn4 = nn.BatchNorm2d(num_features=512*inflation_ratio)\n", + " self.act4 = nn.ReLU()\n", + " self.conv5 = nn.Conv2d(in_channels=512*inflation_ratio, out_channels=512, kernel_size=3, padding=1)\n", + " self.bn5 = nn.BatchNorm2d(num_features=512)\n", + " self.act5 = nn.ReLU()\n", + " self.fc6 = nn.Linear(in_features=512*4*4, out_features=1024)\n", + " self.bn6 = nn.BatchNorm1d(num_features=1024)\n", + " self.act6 = nn.ReLU()\n", + " self.fc7 = nn.Linear(in_features=1024, out_features=1024)\n", + " self.bn7 = nn.BatchNorm1d(num_features=1024)\n", + " self.act7 = nn.ReLU()\n", + " self.fc8 = nn.Linear(in_features=1024, out_features=10)\n", + "\n", + " def forward(self, input):\n", + " x = self.act0(self.bn0(self.conv0(input)))\n", + " x = self.act1(self.bn1(F.max_pool2d(self.conv1(x), 2)))\n", + " x = self.act2(self.bn2(self.conv2(x)))\n", + " x = self.act3(self.bn3(F.max_pool2d(self.conv3(x), 2)))\n", + " x = self.act4(self.bn4(self.conv4(x)))\n", + " x = self.act5(self.bn5(F.max_pool2d(self.conv5(x), 2)))\n", + " x = x.view(x.size(0), -1)\n", + " x = self.act6(self.bn6(self.fc6(x)))\n", + " x = self.act7(self.bn7(self.fc7(x)))\n", + " return self.fc8(x)\n", + "\n", + "def test(model, test_loader):\n", + " correct = 0\n", + " for batch_idx, (data, target) in enumerate(test_loader): \n", + " output = model(data.to(device))\n", + " pred = output.data.max(1)[1]\n", + " correct += pred.eq(target.to(device).data.view_as(pred)).cpu().sum()\n", + "\n", + " return 100. * float(correct) / float(len(test_loader.dataset))\n", + "\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "epochs = 50\n", + "train_loader, validation_loader, test_loader = LoadCIFAR10(batch_size=256, validation=False)\n", + "model = Net().to(device)\n", + "if device == 'cuda':\n", + " model = torch.nn.DataParallel(model)\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "learning_rate = 1e-2\n", + "optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n", + "best_accuracy = 0\n", + "for epoch in range(0, epochs):\n", + " print('Epoch: [%d]\\t\\t' % (epoch + 1), end='')\n", + " if epoch % 20 == 0:\n", + " learning_rate = learning_rate * 0.1\n", + " for param_group in optimizer.param_groups:\n", + " param_group['lr'] = learning_rate\n", + "\n", + " model.train()\n", + " for batch_idx, (data, target) in enumerate(train_loader):\n", + " optimizer.zero_grad()\n", + " output = model(data.to(device))\n", + " loss = criterion(output, target.to(device))\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " accuracy = test(model, test_loader)\n", + " print('%2.2f%%' % accuracy)\n", + " if accuracy > best_accuracy:\n", + " torch.save(model.state_dict(), 'trained_model.pt')\n", + " best_accuracy = accuracy" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "Ag8Z6Rn_v5E8" + }, + "source": [ + "## 2. Conversion of a DNN to a MDNN " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "lyt9qHvAv5E9" + }, + "source": [ + "We use MemTorch to demonstrate the conversion of a DNN to MDNN. A memristive device model is defined and characterized below, which is used to replace all *torch.nn.Linear* layers within the DNN, trained in Step 1, with equivalent crossbar architectures using *memtorch.mn.Module.patch_model*." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 295 + }, + "colab_type": "code", + "id": "dRMGKP-lv5E-", + "outputId": "f22a800e-3eae-4060-a874-23d7a218f3cf" + }, + "outputs": [], + "source": [ + "reference_memristor = memtorch.bh.memristor.VTEAM\n", + "reference_memristor_params = {'time_series_resolution': 1e-10}\n", + "memristor = reference_memristor(**reference_memristor_params)\n", + "memristor.plot_hysteresis_loop()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "b0kLErl0v5FC" + }, + "source": [ + "*memtorch.bh.map.Parameter.naive_map* is used to convert the weights within all *torch.nn.Linear* layers to equivalent conductance values, to be programmed to the two memristive devices used to represent each weight (positive and negative) using Eq. (13). \n", + "\n", + "*transistor* is *True*, so a 1T1R arrangement is simulated. *programming_routine* is set to *None* to skip device-level simulation of the programming routine. We note if *transistor* is *False* *programming_routine* must not be *None*. In which case, device-level simulation is performed for each device using *memtorch.bh.crossbar.gen_programming_signal* and *memtorch.bh.memristor.Memristor.simulate*, which uses finite differences to model internal device dynamics. As *scheme* is not defined, a double-column parameter representation scheme is adopted.\n", + "\n", + "All patched *torch.nn.Linear* layers are tuned using linear regression. A randomly generated tensor of size (8, *self.in_features*) is propagated through each memristive layer and each legacy layer (accessible using *layer.forward_legacy*). *sklearn.linear_model.LinearRegression* is used to determine the coefficient and intercept between the linear relationship of each set of outputs, which is used to define the *transform_output* lamdba function, that maps the output of each layer to their equivalent representations.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "oJWSTW5Qv5FD" + }, + "outputs": [], + "source": [ + "import copy\n", + "from memtorch.mn.Module import patch_model\n", + "from memtorch.map.Parameter import naive_map\n", + "from memtorch.bh.crossbar.Program import naive_program\n", + "\n", + "\n", + "model = Net()\n", + "if torch.cuda.is_available():\n", + " model = torch.nn.DataParallel(model)\n", + "\n", + "model.load_state_dict(torch.load('trained_model.pt'), strict=False)\n", + "patched_model = patch_model(copy.deepcopy(model),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "Mam3ggffv5FG" + }, + "outputs": [], + "source": [ + "patched_model.tune_()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": {}, + "colab_type": "code", + "id": "U5F0muXPv5FK" + }, + "outputs": [], + "source": [ + "print(test(patched_model, test_loader))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "eV8IJSH6v5FN" + }, + "source": [ + "## 3. Modeling non-ideal device characteristics" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "R4H9f4d248V7" + }, + "source": [ + "We use a simple prototype model to demonstrate modeling non-ideal device characteristics." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 50 + }, + "colab_type": "code", + "id": "x0mghWrdv5FO", + "outputId": "fb7d0542-7839-438e-94fb-029d05f0bbc1" + }, + "outputs": [], + "source": [ + "from memtorch.mn.Module import patch_model\n", + "import copy\n", + "from memtorch.map.Parameter import naive_map\n", + "\n", + "class Model(torch.nn.Module):\n", + "\n", + " def __init__(self):\n", + " super(Model, self).__init__()\n", + " self.convolutional_layer = torch.nn.Conv2d(in_channels=3, out_channels=1, kernel_size=5)\n", + " self.linear_layer = torch.nn.Linear(in_features=16, out_features=4)\n", + "\n", + " def forward(self, input):\n", + " x = self.convolutional_layer(input)\n", + " x = x.view(x.size(0), -1)\n", + " return self.linear_layer(x)\n", + " \n", + "torch.manual_seed(0)\n", + "model = Model()\n", + "if torch.cuda.is_available():\n", + " model = torch.nn.DataParallel(model)\n", + "\n", + "reference_memristor_params = {'time_series_resolution': 1e-10, 'r_off': 200, 'r_on': 100}\n", + "patched_model = patch_model(copy.deepcopy(model),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear, torch.nn.Conv2d],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "D2Vcpuuw5D_S" + }, + "source": [ + "Device-device variability is introduced to the VTEAM reference memristor model using *memtorch.bh.StochasticParameter*, by sampling $R_{\\text{OFF}}$ for each device from a normal distribution with $\\sigma = 20$ and $x = 200$, and $R_{\\text{ON}}$ for each device from a normal distribution with $\\sigma = 10$ and $x = 100$. Using *np.vectorize*, the $R_{\\text{OFF}}$ and $R_{\\text{ON}}$ values for each memristive device are compared." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 276 + }, + "colab_type": "code", + "id": "4thsaVDEv5FS", + "outputId": "e46021ed-b57f-4be7-f29e-15bd17ec2473" + }, + "outputs": [], + "source": [ + "from memtorch.mn.Module import patch_model\n", + "import copy\n", + "from memtorch.map.Parameter import naive_map\n", + "from memtorch.bh.crossbar.Program import naive_program\n", + "import matplotlib.pyplot as plt\n", + "from mpl_toolkits.axes_grid1 import make_axes_locatable\n", + "\n", + "reference_memristor_params = {'time_series_resolution': 1e-10, \n", + " 'r_off': memtorch.bh.StochasticParameter(200, std=20, min=2),\n", + " 'r_on': memtorch.bh.StochasticParameter(100, std=10, min=1)}\n", + "\n", + "patched_model_ = patch_model(copy.deepcopy(model),\n", + " memristor_model=reference_memristor,\n", + " memristor_model_params=reference_memristor_params,\n", + " module_parameters_to_patch=[torch.nn.Linear, torch.nn.Conv2d],\n", + " mapping_routine=naive_map,\n", + " transistor=True,\n", + " programming_routine=None)\n", + "\n", + "A = torch.Tensor(np.vectorize(lambda x: x.r_off)(patched_model_.linear_layer.crossbars[0].devices))\n", + "B = torch.Tensor(np.vectorize(lambda x: x.r_on)(patched_model_.linear_layer.crossbars[0].devices))\n", + "C = torch.cat((A, B), 0)\n", + "\n", + "\n", + "plt.subplot(2, 1, 1)\n", + "plt.imshow(A.transpose(0, 1), interpolation='nearest', aspect=1, vmin=C.min(), vmax=C.max(), cmap='seismic')\n", + "plt.xticks([])\n", + "plt.yticks([])\n", + "plt.xlabel('Dimension 1')\n", + "plt.ylabel('Dimension 0')\n", + "divider = make_axes_locatable(plt.gca())\n", + "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n", + "plt.colorbar(cax=cax)\n", + "\n", + "plt.subplot(2, 1, 2)\n", + "plt.imshow(B.transpose(0, 1), interpolation='nearest', aspect=1, vmin=C.min(), vmax=C.max(), cmap='seismic')\n", + "plt.xticks([])\n", + "plt.yticks([])\n", + "plt.xlabel('Dimension 1')\n", + "plt.ylabel('Dimension 0')\n", + "divider = make_axes_locatable(plt.gca())\n", + "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n", + "plt.colorbar(cax=cax)\n", + "plt.savefig('var.svg')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "3okdYrSZ7dJh" + }, + "source": [ + "We model a number (5) of finite discrete conductance states using $memtorch.bh.nonideality.NonIdeality.FiniteConductanceStates$. The conductance levels within the positive crossbar were compared before and after a finite discrete conductance states are modeled." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 246 + }, + "colab_type": "code", + "id": "bpIOctS5v5FV", + "outputId": "feefbf64-f8fe-4da2-8212-afa17dade373" + }, + "outputs": [], + "source": [ + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "\n", + "A = 1 / patched_model.linear_layer.crossbars[0].conductance_matrix\n", + "model = apply_nonidealities(copy.deepcopy(patched_model),\n", + " non_idealities=[memtorch.bh.nonideality.NonIdeality.FiniteConductanceStates],\n", + " conductance_states = 5)\n", + "B = 1 / model.linear_layer.crossbars[0].conductance_matrix\n", + "C = torch.cat((A, B), 0)\n", + "\n", + "plt.subplot(2, 1, 1)\n", + "plt.imshow(A.transpose(0, 1), interpolation='nearest', aspect=1, vmin=C.min(), vmax=C.max(), cmap='seismic')\n", + "plt.xticks([])\n", + "plt.yticks([])\n", + "plt.xlabel('Dimension 1')\n", + "plt.ylabel('Dimension 0')\n", + "divider = make_axes_locatable(plt.gca())\n", + "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n", + "plt.colorbar(cax=cax)\n", + "\n", + "plt.subplot(2, 1, 2)\n", + "plt.imshow(B.transpose(0, 1), interpolation='nearest', aspect=1, vmin=C.min(), vmax=C.max(), cmap='seismic')\n", + "plt.xticks([])\n", + "plt.yticks([])\n", + "plt.xlabel('Dimension 1')\n", + "plt.ylabel('Dimension 0')\n", + "divider = make_axes_locatable(plt.gca())\n", + "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n", + "plt.colorbar(cax=cax)\n", + "plt.savefig('finite.svg')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "rfyXHayL70HP" + }, + "source": [ + "We model device failure using $memtorch.bh.nonideality.NonIdeality.DeviceFaults$. The conductance levels within the positive crossbar are once again compared, before and after 50\\% of devices are stuck at $R_{\\text{LRS}}$ and 50\\% of devices are stuck at $R_{\\text{HRS}}$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 246 + }, + "colab_type": "code", + "id": "E6Xi7FUxv5FZ", + "outputId": "a074acc6-3e0b-4d39-89cf-90fb2ad05bdd" + }, + "outputs": [], + "source": [ + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "\n", + "A = 1 / patched_model.linear_layer.crossbars[0].conductance_matrix\n", + "model = apply_nonidealities(copy.deepcopy(patched_model),\n", + " non_idealities=[memtorch.bh.nonideality.NonIdeality.DeviceFaults],\n", + " lrs_proportion=0.5,\n", + " hrs_proportion=0.5,\n", + " electroform_proportion=0)\n", + "B = 1 / model.linear_layer.crossbars[0].conductance_matrix\n", + "C = torch.cat((A, B), 0)\n", + "\n", + "plt.subplot(2, 1, 1)\n", + "plt.imshow(A.transpose(0, 1), interpolation='nearest', aspect=1, vmin=C.min(), vmax=C.max(), cmap='seismic')\n", + "plt.xticks([])\n", + "plt.yticks([])\n", + "plt.xlabel('Dimension 1')\n", + "plt.ylabel('Dimension 0')\n", + "divider = make_axes_locatable(plt.gca())\n", + "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n", + "plt.colorbar(cax=cax)\n", + "\n", + "plt.subplot(2, 1, 2)\n", + "plt.imshow(B.transpose(0, 1), interpolation='nearest', aspect=1, vmin=C.min(), vmax=C.max(), cmap='seismic')\n", + "plt.xticks([])\n", + "plt.yticks([])\n", + "plt.xlabel('Dimension 1')\n", + "plt.ylabel('Dimension 0')\n", + "divider = make_axes_locatable(plt.gca())\n", + "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n", + "plt.colorbar(cax=cax)\n", + "plt.savefig('fault.svg')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "colab_type": "text", + "id": "WWX0f_Wz8U1L" + }, + "source": [ + "We model non-linear I/V characteristics using $memtorch.bh.nonideality.NonIdeality.NonLinear$ during inference. The output of the single *torch.nn.Linear* layer are compared when devices were simulated during inference with linear and non-linear I/V characteristics. Non-linear I/V characteristics were determined by applying a half-voltage sweep, using a sinusoidal cosine voltage signal with a duration of 5ns, amplitude of 1V, and a frequency of 50 MHz to each device. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 34 + }, + "colab_type": "code", + "id": "xIbVHttJv5Fb", + "outputId": "559d9c25-25f0-4f6c-fbeb-75defceb9048" + }, + "outputs": [], + "source": [ + "from memtorch.bh.nonideality.NonIdeality import apply_nonidealities\n", + "from sklearn.metrics.pairwise import cosine_similarity\n", + "\n", + "A = torch.tensor(np.zeros((100, 4)))\n", + "B = torch.tensor(np.zeros((100, 4)))\n", + "for i in range(100):\n", + " input = torch.zeros((1,3,8,8)).uniform_(-1, 1)\n", + " A[i, :] = patched_model(input)\n", + " model = apply_nonidealities(copy.deepcopy(patched_model),\n", + " non_idealities=[memtorch.bh.nonideality.NonIdeality.NonLinear],\n", + " sweep_duration=5e-9,\n", + " sweep_voltage_signal_amplitude=1,\n", + " sweep_voltage_signal_frequency=50e6)\n", + " B[i, :] = model(input)\n", + "\n", + "print(cosine_similarity([A.view(-1).numpy()], [B.view(-1).numpy()]))" + ] + } + ], + "metadata": { + "colab": { + "collapsed_sections": [], + "name": "Tutorial.ipynb", + "provenance": [] + }, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/memtorch/map/Module.py b/memtorch/map/Module.py new file mode 100644 index 00000000..4fc78f97 --- /dev/null +++ b/memtorch/map/Module.py @@ -0,0 +1,37 @@ +import memtorch +import torch +import torch.nn as nn +import torch.functional as F +import numpy as np +from sklearn import datasets, linear_model +from sklearn.metrics import r2_score + + +def naive_tune(module, input_shape): + """Method to determine a linear relationship between a memristive crossbar and the output for a given memristive module. + + Parameters + ---------- + module : torch.nn.Module + Memristive layer to tune. + input_shape : tuple + Shape of the randomly generated input used to tune a crossbar. + + Returns + ------- + function + Function which transforms the output of the crossbar to the expected output. + """ + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + tmp = module.bias + module.bias = None + input = torch.rand(input_shape).uniform_(-1, 1).to(device) + output = module.forward(input).detach().cpu().flatten() + legacy_output = module.forward_legacy(input).detach().cpu().flatten() + output = output.numpy().reshape(-1, 1) + legacy_output = legacy_output.numpy() + reg = linear_model.LinearRegression(fit_intercept=True).fit(output, legacy_output) + transform_output = lambda x: x * reg.coef_[0] + reg.intercept_ + module.bias = tmp + print('Tuned %s. Coefficient of determination: %f [%f, %f]' % (module, reg.score(output, legacy_output), reg.coef_[0], reg.intercept_)) + return transform_output diff --git a/memtorch/map/Parameter.py b/memtorch/map/Parameter.py new file mode 100644 index 00000000..7ed58035 --- /dev/null +++ b/memtorch/map/Parameter.py @@ -0,0 +1,43 @@ +import memtorch +from memtorch.utils import convert_range +import torch +import torch.nn as nn +import torch.functional as F +import numpy as np + + +def naive_map(weight, r_on, r_off, scheme): + """Method to naively map network parameters to memristive device conductances, using two crossbars to represent both positive and negative weights. + + Parameters + ---------- + weight : torch.Tensor + Weight tensor to map. + r_on : float + Low resistance state. + r_off : float + High resistance state. + scheme: memtorch.bh.crossbar.Scheme + Weight representation scheme. + + Returns + ------- + torch.Tensor, torch.Tensor + Positive and negative crossbar weights. + """ + if scheme == memtorch.bh.crossbar.Scheme.DoubleColumn: + range = weight.abs().max() + pos = weight.clone() + neg = weight.clone() * -1 + pos[pos < 0] = 0 + neg[neg < 0] = 0 + pos = convert_range(pos, 0, range, 1 / r_off, 1 / r_on) + neg = convert_range(neg, 0, range, 1 / r_off, 1 / r_on) + return pos, neg + elif scheme == memtorch.bh.crossbar.Scheme.SingleColumn: + range = weight.abs().max() + crossbar = weight.clone() + crossbar = convert_range(crossbar, crossbar.min(), crossbar.max(), 1 / r_off, 1 / r_on) + return crossbar + else: + raise('%s is not currently supported.' % scheme) diff --git a/memtorch/map/__init__.py b/memtorch/map/__init__.py new file mode 100644 index 00000000..1807e650 --- /dev/null +++ b/memtorch/map/__init__.py @@ -0,0 +1,2 @@ +from .Parameter import * +from .Module import * diff --git a/memtorch/mn/Conv2d.py b/memtorch/mn/Conv2d.py new file mode 100644 index 00000000..ec9f95d7 --- /dev/null +++ b/memtorch/mn/Conv2d.py @@ -0,0 +1,112 @@ +import torch +import torch.nn as nn +import memtorch +from memtorch.bh.crossbar.Crossbar import init_crossbar +from memtorch.bh.crossbar.Crossbar import simulate +from memtorch.utils import convert_range +from memtorch.map.Module import naive_tune +from memtorch.map.Parameter import naive_map +import numpy as np + + +class Conv2d(nn.Conv2d): + """nn.Conv2d equivalent. + + Parameters + ---------- + convolutional_layer : torch.nn.Conv2d + Linear layer to patch. + memristor_model : memtorch.bh.memristor.Memristor.Memristor + Memristor model. + memristor_model_params : **kwargs + Memristor model keyword arguments. + mapping_routine : function + Mapping routine to use. + transistor : bool + Used to determine if a 1T1R (True) or 1R arrangement (False) is simulated. + programming_routine : function + Programming routine to use. + scheme : memtorch.bh.Scheme + Weight representation scheme. + """ + + def __init__(self, convolutional_layer, memristor_model, memristor_model_params, mapping_routine=naive_map, transistor=False, programming_routine=None, scheme=memtorch.bh.Scheme.DoubleColumn, *args, **kwargs): + assert isinstance(convolutional_layer, nn.Conv2d), 'convolutional_layer is not an instance of nn.Conv2d.' + self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + super(Conv2d, self).__init__(convolutional_layer.in_channels, convolutional_layer.out_channels, convolutional_layer.kernel_size, **kwargs) + self.padding = convolutional_layer.padding + self.stride = convolutional_layer.stride + self.weight.data = convolutional_layer.weight.data + if convolutional_layer.bias is not None: + self.bias.data = convolutional_layer.bias.data + + self.zero_grad() + self.weight.requires_grad = False + if convolutional_layer.bias is not None: + self.bias.requires_grad = False + + self.crossbars, self.crossbar_operation = init_crossbar(weights=self.weight, + memristor_model=memristor_model, + memristor_model_params=memristor_model_params, + transistor=transistor, + mapping_routine=mapping_routine, + programming_routine=programming_routine, + scheme=scheme) + self.transform_output = lambda x: x + print('Patched %s -> %s' % (convolutional_layer, self)) + + def forward(self, input): + """Method to perform forward propagations. + + Parameters + ---------- + input : torch.Tensor + Input tensor. + + Returns + ------- + torch.Tensor + Output tensor. + """ + output_dim = int((input.shape[2] - self.kernel_size[0] + 2 * self.padding[0]) / self.stride[0]) + 1 + out = torch.zeros((input.shape[0], self.out_channels, output_dim, output_dim)).to(self.device) + for batch in range(input.shape[0]): + unfolded_batch_input = torch.nn.functional.unfold(input[batch, :, :, :].unsqueeze(0), kernel_size=self.kernel_size, padding=self.padding) + if hasattr(self, 'non_linear'): + unfolded_batch_input = convert_range(unfolded_batch_input, unfolded_batch_input.min(), unfolded_batch_input.max(), -1, 1).squeeze(0) + unfolded_batch_input = unfolded_batch_input.transpose(1, 0).cpu().detach().numpy() + if hasattr(self, 'simulate'): + out_ = torch.tensor(self.transform_output(self.crossbar_operation(self.crossbars, lambda crossbar, input: simulate(input, crossbar.devices.transpose(1, 0), nl=False), unfolded_batch_input))).to(self.device) + else: + out_ = torch.tensor(self.transform_output(self.crossbar_operation(self.crossbars, lambda crossbar, input: simulate(input, crossbar.devices.transpose(1, 0), nl=True), unfolded_batch_input))).to(self.device) + else: + out_ = self.transform_output(torch.matmul(self.crossbar_operation(self.crossbars, lambda crossbar: crossbar.conductance_matrix), unfolded_batch_input)) + + if not self.bias is None: + out_ += self.bias.view(-1, 1).expand_as(out_) + + out[batch] = out_.view(size=(1, self.out_channels, output_dim, output_dim)) + + return out + + def forward_legacy(self, input): + """Legacy method to perform forward propagations. + + Parameters + ---------- + input : torch.Tensor + Input tensor. + + Returns + ------- + torch.Tensor + Output tensor. + """ + return torch.nn.functional.conv2d(input.to(self.device), self.weight, bias=self.bias, stride=self.stride, padding=self.padding) + + def tune(self): + """Tuning method.""" + self.transform_output = naive_tune(self, (8, self.in_channels, 32, 32)) + + def __str__(self): + return "bh.Conv2d(in_channels=%d, out_channels=%d, kernel_size=(%d, %d), stride=(%d,%d), padding=(%d,%d))" % (self.in_channels, self.out_channels, self.kernel_size[0], self.kernel_size[1], self.stride[0], self.stride[1], self.padding[0], self.padding[1]) diff --git a/memtorch/mn/Linear.py b/memtorch/mn/Linear.py new file mode 100644 index 00000000..85e167f3 --- /dev/null +++ b/memtorch/mn/Linear.py @@ -0,0 +1,112 @@ +import torch +import torch.nn as nn +import memtorch +from memtorch.bh.crossbar.Crossbar import init_crossbar +from memtorch.bh.crossbar.Crossbar import simulate +from memtorch.utils import convert_range +from memtorch.map.Module import naive_tune +from memtorch.map.Parameter import naive_map +import numpy as np + + +class Linear(nn.Linear): + """nn.Linear equivalent. + + Parameters + ---------- + linear_layer : torch.nn.Linear + Linear layer to patch. + memristor_model : memtorch.bh.memristor.Memristor.Memristor + Memristor model. + memristor_model_params : **kwargs + Memristor model keyword arguments. + mapping_routine : function + Mapping routine to use. + transistor : bool + Used to determine if a 1T1R (True) or 1R arrangement (False) is simulated. + programming_routine : function + Programming routine to use. + scheme : memtorch.bh.Scheme + Weight representation scheme. + """ + + def __init__(self, linear_layer, memristor_model, memristor_model_params, mapping_routine=naive_map, transistor=True, programming_routine=None, scheme=memtorch.bh.Scheme.DoubleColumn, **kwargs): + assert isinstance(linear_layer, nn.Linear), 'linear_layer is not an instance of nn.Linear.' + self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + super(Linear, self).__init__(linear_layer.in_features, linear_layer.out_features, **kwargs) + self.weight.data = linear_layer.weight.data + if linear_layer.bias is not None: + self.bias.data = linear_layer.bias.data + else: + self.bias = None + + self.zero_grad() + self.weight.requires_grad = False + if linear_layer.bias is not None: + self.bias.requires_grad = False + + self.crossbars, self.crossbar_operation = init_crossbar(weights=self.weight, + memristor_model=memristor_model, + memristor_model_params=memristor_model_params, + transistor=transistor, + mapping_routine=mapping_routine, + programming_routine=programming_routine, + scheme=scheme) + self.transform_output = lambda x: x + print('Patched %s -> %s' % (linear_layer, self)) + + def forward(self, input): + """Method to perform forward propagations. + + Parameters + ---------- + input : torch.Tensor + Input tensor. + + Returns + ------- + torch.Tensor + Output tensor. + """ + if hasattr(self, 'non_linear'): + input = convert_range(input, input.min(), input.max(), -1, 1) + input = input.cpu().detach().numpy() + if hasattr(self, 'simulate'): + out = torch.tensor(self.transform_output(self.crossbar_operation(self.crossbars, lambda crossbar, input: simulate(input, crossbar.devices, nl=False), input))).to(self.device) + else: + out = torch.tensor(self.transform_output(self.crossbar_operation(self.crossbars, lambda crossbar, input: simulate(input, crossbar.devices, nl=True), input))).to(self.device) + else: + out = torch.matmul(input.to(self.device), self.crossbar_operation(self.crossbars, lambda crossbar: crossbar.conductance_matrix)) + + out = self.transform_output(out) + if not self.bias is None: + out += self.bias.view(1, -1).expand_as(out) + + return out + + + def forward_legacy(self, input): + """Legacy method to perform forward propagations. + + Parameters + ---------- + input : torch.Tensor + Input tensor. + + Returns + ------- + torch.Tensor + Output tensor. + """ + out = torch.matmul(input.to(self.device), self.weight.data.T.to(self.device)) + if not self.bias is None: + out += self.bias.view(1, -1).expand_as(out) + + return out + + def tune(self): + """Tuning method.""" + self.transform_output = naive_tune(self, (4098, self.in_features)) + + def __str__(self): + return "bh.Linear(in_features=%d, out_features=%d, bias=%s)" % (self.in_features, self.out_features, not self.bias is None) diff --git a/memtorch/mn/Module.py b/memtorch/mn/Module.py new file mode 100644 index 00000000..74aeeb00 --- /dev/null +++ b/memtorch/mn/Module.py @@ -0,0 +1,78 @@ +import memtorch +from memtorch.map.Parameter import naive_map +from .Linear import Linear +from .Conv2d import Conv2d +import torch +import torch.functional as F +import multiprocessing as mp +import itertools + + +supported_module_parameters = {'': Linear, + '': Conv2d + } + +def patch_model(model, memristor_model, memristor_model_params, module_parameters_to_patch={}, mapping_routine=naive_map, transistor=True, programming_routine=None, scheme=memtorch.bh.Scheme.DoubleColumn, **kwargs): + """Method to convert a torch.nn model to a memristive model. + + Parameters + ---------- + model : torch.nn.Module + torch.nn.Module to patch. + memristor_model : memtorch.bh.memristor.Memristor.Memristor + Memristor model. + memristor_model_params : **kwargs + Memristor model keyword arguments. + module_parameters_to_patch : module_paramter_patches + Model parameters to patch. + mapping_routine : function + Mapping routine to use. + transistor : bool + Used to determine if a 1T1R (True) or 1R arrangement (False) is simulated. + programming_routine : function + Programming routine to use. + scheme : memtorch.bh.Scheme + Weight representation scheme. + + Returns + ------- + torch.nn.Module + Patched torch.nn.Module. + """ + model.map = mapping_routine + for i, (name, m) in enumerate(list(model.named_modules())): + for parameter in module_parameters_to_patch: + if isinstance(m, parameter): + if torch.cuda.is_available() and len(name.split('.')) > 1: + name = name.split('.')[1] + + parameter_type = str(type(m)) + patch = supported_module_parameters.get(parameter_type) + assert parameter_type in supported_module_parameters, 'Patching of %s is not currently supported' % type(m) + if hasattr(model, 'module'): + setattr(model.module, name, patch(m, + memristor_model=memristor_model, + memristor_model_params=memristor_model_params, + mapping_routine=mapping_routine, + transistor=transistor, + programming_routine=programming_routine, + scheme=scheme, + **kwargs)) + else: + setattr(model, name, patch(m, + memristor_model=memristor_model, + memristor_model_params=memristor_model_params, + mapping_routine=mapping_routine, + transistor=transistor, + programming_routine=programming_routine, + scheme=scheme, + **kwargs)) + + def tune_(self): + """Method to tune a memristive layer.""" + for i, (name, m) in enumerate(list(self.named_modules())): + if hasattr(m, 'tune'): + m.tune() + + model.tune_ = tune_.__get__(model) + return model diff --git a/memtorch/mn/__init__.py b/memtorch/mn/__init__.py new file mode 100644 index 00000000..35a02772 --- /dev/null +++ b/memtorch/mn/__init__.py @@ -0,0 +1,3 @@ +from .Module import * +from .Conv2d import Conv2d +from .Linear import Linear diff --git a/memtorch/utils.py b/memtorch/utils.py new file mode 100644 index 00000000..70420ede --- /dev/null +++ b/memtorch/utils.py @@ -0,0 +1,93 @@ +import memtorch +import torch +import torchvision +from torchvision import datasets, transforms + + +def convert_range(old_value, old_min, old_max, new_min, new_max): + """Method to convert values between two ranges. + + Parameters + ---------- + old_value : object + Old value(s) to convert. May be a single number, vector or tensor. + old_min : float + Minimum old value. + old_max : float + Maximum old value. + new_min : float + Minimum new value. + new_max : float + Maximum new value. + + Returns + ------- + object + New value(s). + """ + return (((old_value - old_min) * (new_max - new_min)) / (old_max - old_min)) + new_min + +def LoadMNIST(batch_size=32, validation=True): + """Method to load the MNIST dataset. + + Parameters + ---------- + batch_size : int + Batch size. + validation : bool + Load the validation set (True). + + Returns + ------- + list of torch.utils.data + The train, validiation, and test loaders. + """ + root = 'data' + transform = transforms.Compose([transforms.ToTensor()]) + full_train_set = torchvision.datasets.MNIST(root=root, train=True, transform=transform, download=True) + test_set = torchvision.datasets.MNIST(root=root, train=False, transform=transform, download=True) + if validation: + train_size = int(0.8 * len(full_train_set)) + validation_size = len(full_train_set) - train_size + train_set, validation_set = torch.utils.data.random_split(full_train_set, [train_size, validation_size]) + train_loader = torch.utils.data.DataLoader(train_set, batch_size=batch_size, shuffle=True, num_workers=2) + validation_loader = torch.utils.data.DataLoader(validation_set, batch_size=batch_size, shuffle=True, num_workers=2) + else: + train_loader = torch.utils.data.DataLoader(full_train_set, batch_size=batch_size, shuffle=True, num_workers=2) + validation_loader = None + + test_loader = torch.utils.data.DataLoader(test_set, batch_size=int(batch_size/2), shuffle=False, num_workers=2) + return train_loader, validation_loader, test_loader + + +def LoadCIFAR10(batch_size=32, validation=True): + """Method to load the CIFAR-10 dataset. + + Parameters + ---------- + batch_size : int + Batch size. + validation : bool + Load the validation set (True). + + Returns + ------- + list of torch.utils.data + The train, validiation, and test loaders. + """ + root = 'data' + transform = transforms.Compose([transforms.ToTensor()]) + full_train_set = torchvision.datasets.CIFAR10(root=root, train=True, download=True, transform=transform) + test_set = torchvision.datasets.CIFAR10(root=root, train=False, download=True, transform=transform) + if validation: + train_size = int(0.8 * len(full_train_set)) + validation_size = len(full_train_set) - train_size + train_set, validation_set = torch.utils.data.random_split(full_train_set, [train_size, validation_size]) + train_loader = torch.utils.data.DataLoader(train_set, batch_size=batch_size, shuffle=True, num_workers=2) + validation_loader = torch.utils.data.DataLoader(validation_set, batch_size=batch_size, shuffle=True, num_workers=2) + else: + train_loader = torch.utils.data.DataLoader(full_train_set, batch_size=batch_size, shuffle=True, num_workers=2) + validation_loader = None + + test_loader = torch.utils.data.DataLoader(test_set, batch_size=int(batch_size/2), shuffle=False, num_workers=2) + return train_loader, validation_loader, test_loader diff --git a/setup.py b/setup.py new file mode 100644 index 00000000..ca293886 --- /dev/null +++ b/setup.py @@ -0,0 +1,47 @@ +from setuptools import setup, find_packages +import torch + + +CUDA = False +if CUDA: + from torch.utils.cpp_extension import BuildExtension, CUDAExtension, CppExtension + ext_modules = [ + CUDAExtension('cuda_quantization', [ + 'memtorch/cu/quantize/quant_cuda.cpp', + 'memtorch/cu/quantize/quant.cu' + ], extra_include_paths='memtorch/cu/quantize'), + CppExtension('quantization', [ + 'memtorch/cpp/quantize/quant.cpp' + ])] + name = 'memtorch' +else: + from torch.utils.cpp_extension import BuildExtension, CppExtension + ext_modules = [ + CppExtension('quantization', [ + 'memtorch/cpp/quantize/quant.cpp' + ])] + name = 'memtorch-cpu' + +setup(name=name, + version='1.0.1', + description='A Simulation Framework for Memristive Deep Learning Systems', + long_description='A Simulation Framework for Memristive Deep Learning Systems which integrates directly with the well-known PyTorch Machine Learning (ML) library', + url='https://github.com/coreylammie/MemTorch', + license='GPL-3.0', + author='Corey Lammie', + author_email='coreylammie@jcu.edu.au', + ext_modules=ext_modules, + cmdclass={ + 'build_ext': BuildExtension + }, + packages=find_packages(), + install_requires=[ + 'numpy', + 'pandas', + 'torch>=1.2.0', + 'matplotlib', + 'seaborn' + ], + python_requires='>=3.6', + include_package_data=True + )