diff --git a/.gitignore b/.gitignore new file mode 100755 index 0000000..ce82017 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/.idea/* +/build/* +/dist/* \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100755 index 0000000..1726667 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,11 @@ +FROM nvcr.io/nvidia/pytorch:22.10-py3 + +RUN apt-get update && apt-get install -y --no-install-recommends openssh-client openssh-server && \ + mkdir -p /var/run/sshd + +ENV MPI_HOME=/opt/hpcx/ompi/ +ENV NCCL_INCLUDE=/usr/include +ENV NCCL_LIB=/usr/lib/x86_64-linux-gnu/ + +RUN git clone https://github.com/IST-DASLab/torch_cgx /torch_cgx &&\ +cd /torch_cgx && python setup.py install \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100755 index 0000000..bbba84b --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,617 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100755 index 0000000..150d74b --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1 @@ +graft src \ No newline at end of file diff --git a/README.md b/README.md new file mode 100755 index 0000000..f525c81 --- /dev/null +++ b/README.md @@ -0,0 +1,90 @@ +# CGX + +CGX is a pytorch extension adding a backend for pytorch distributed supporting allreduce of quantized buffers. +It supports quantizations of float16, float32 to 1-8 bits. + +CGX is based on MPI torch.distributed backend. The extension essentially only replaces allreduce primitive. + +## Quick Start + +### Prerequisites +CGX, as a pytorch extension, requires `pytorch>=1.10.0`. + +For faster build we recommend to have `ninja` installed (`pip install ninja`). + +The compression is only supported for GPU-based buffers so either CUDA or ROCm is required. +If CUDA or ROCm are installed not in the standard paths, set `[CUDA|ROCM]_HOME` or `[CUDA|ROCM]_PATH` accordingly. + +As long as it is based on MPI, it requires OpenMPI with GPU support installed (other MPI implementations were not tested). +Also, the library supports NCCL based communications, so it requires NVIDIA NCCL library. + +### Build from source +Set `MPI_HOME` environment variable to mpi home. In case of AMD GPU, set `CGX_CUDA` to 0. +Set `NCCL_HOME` environment variable to NCCL home, or `NCCL_INCLUDE` and `NCCL_LIB`. +Set `QSGD_DETERMENISTIC=0` if you want to have stochastic version QSGD. + +```bash +git clone https://github.com/IST-DASLab/torch_cgx +export MPI_HOME=/path/to/mpi +export NCCL_HOME=/path/to/nccl +python setup.py install +``` + +### Usage +The only changes to the training script using pytorch distributed required + are importing the built extension and specifying `cgx` as `torch.distributed.init_process_group` backend parameter. + +Example: +``` python +import torch +import torch.distributed as dist +import torch_cgx + +dist.init_process_group('cgx', init_method='env://', rank=args.local_rank) +``` +Also, it order to perform layerwise compression and being able to filter small sensitive to gradient compression +layers (typically these are batch norm layers and biases) the `cgx` needs to have information about the model. +For that users need to register the communication hook. The minimal size of the layers can be +controlled with `layer_min_size` parameter. + +``` python +model = torch. +from cgx_utils import cgx_hook, CGXState +state = CGXState(torch.distributed.group.WORLD, layer_min_size=1024, + compression_params={"bits": args.quantization_bits, + "bucket_size": args.quantization_bucket_size}) +model.register_comm_hook(state, cgx_hook) +``` + +As long as the extension is based on MPI backend, it requires MPI-compliant launcher (`torch.distributed.launch` won't work): +`$ mpirun -np 2 python train.py` + +Also, if your training script was run previously with `torch.distributed.launch` utility, due to MPI launcher you need to set an environment variables (see cifar_train.py in examples) +``` +if "OMPI_COMM_WORLD_SIZE" in os.environ: + os.environ['MASTER_ADDR'] = '127.0.0.1' + os.environ['MASTER_PORT'] = '4040' + os.environ["WORLD_SIZE"] = os.environ["OMPI_COMM_WORLD_SIZE"] + os.environ["RANK"] = os.environ["OMPI_COMM_WORLD_RANK"] +``` + +## Tuning +CGX can be tuned with the following environment variables: + +- `CGX_COMPRESSION_QUANTIZATION_BITS` - number of bits each value of buffer is quantized to (from 1 to 8). Default is 32 which means no quantization is applied. This variable must be used if the `cgx_hook` communication hook is not registered. +- `CGX_COMPRESSION_BUCKET_SIZE` - size of subarray into which buffer is split before quantization. Default is 512. +- `CGX_COMPRESSION_SKIP_INCOMPLETE_BUCKETS` - boolean variable (0 or 1). After the splitting buffer into buckets, some values of buffer may remain. The variable tells quantization algorithm to compress or not to compress the remaining values. Default 0. +- `CGX_COMPRESSION_MINIMAL_SIZE` - minimal size of buffer (number of elements) to compress. Default is 0 but in fact minimal size is forced to be not less than 16. +- `CGX_FUSION_BUFFER_SIZE_MB`. CGX is leveraging [Tensor Fusion](https://github.com/horovod/horovod#tensor-fusion), a performance feature introduced in Horovod. This feature batches small allreduce operations. This decreases a latency in Data Parallel training. The environment variable controls the size of maximal buffer (in MB) that is communicated within one iteration of allreduce algorithm. Default is 64. The variable must be set **before** loading the module. +- `CGX_INNER_COMMUNICATOR_TYPE`. Specifies what library to use as communication backend for intra node communication (MPI, SHM, NCCL). +- `CGX_CROSS_COMMUNICATOR_TYPE`. Specifies what library to use as communication backend for inter node communication (MPI, NCCL). +- `CGX_INTRA_BROADCAST`. Parameter for multinode training. When enabled, inter-node communication is performed by only one gpu per node. + +## Examples + +Basic examples are provided under the [example](examples) folder. + +## Notes + - As Compression method, basic max-min uniform quantization function is used. In order to use max-min with random rounding like in QSGD, compile the library with QSGD_DETERMINISTIC=0 + - Reduction algorithm: Scatter-Reduce-AllGather. + - Part of the source code is based on [Horovod](https://github.com/horovod/horovod) and [NCCL](https://github.com/NVIDIA/nccl) sources. \ No newline at end of file diff --git a/cgx_utils/__init__.py b/cgx_utils/__init__.py new file mode 100755 index 0000000..f1f218a --- /dev/null +++ b/cgx_utils/__init__.py @@ -0,0 +1 @@ +from .allreduce_hooks import CGXState, cgx_hook \ No newline at end of file diff --git a/cgx_utils/allreduce_hooks.py b/cgx_utils/allreduce_hooks.py new file mode 100755 index 0000000..50e27e0 --- /dev/null +++ b/cgx_utils/allreduce_hooks.py @@ -0,0 +1,73 @@ +# pytorch-cgx +# +# Copyright (C) 2022 IST Austria +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . + +from typing import Dict +import torch +import torch.distributed as dist +import torch_cgx +import os + +COMPRESSION_QUANTIZATION_BITS = "CGX_COMPRESSION_QUANTIZATION_BITS" +COMPRESSION_BUCKET_SIZE = "CGX_COMPRESSION_BUCKET_SIZE" +COMPRESSION_MINIMAL_SIZE = "CGX_COMPRESSION_MINIMAL_SIZE" +VALUE_NO_COMPRESS=32 + + +class CGXState(object): + def __init__(self, process_group: dist.ProcessGroup, layer_min_size: int = 1024, + compression_params: Dict[str, int] = None): + self.process_group = process_group if process_group is not None else dist.group.WORLD + min_size_to_compress = int(os.getenv(COMPRESSION_MINIMAL_SIZE, "16")) + self.layer_min_size = max(layer_min_size, min_size_to_compress) + self.quantization_bits = int(os.getenv(COMPRESSION_QUANTIZATION_BITS, str(VALUE_NO_COMPRESS))) + self.quantization_bucket_size = int(os.getenv(COMPRESSION_BUCKET_SIZE, "1024")) + self.step = 0 + if compression_params is not None: + self.quantization_bits = compression_params.get("bits", self.quantization_bits) + self.quantization_bucket_size = compression_params.get("bucket_size", self.quantization_bucket_size) + + def should_compress_(self, tensor: torch.Tensor): + if tensor.dim() <= 1 or tensor.numel() < self.layer_min_size: + return False + return True + + +def _allreduce_fut( + process_group: dist.ProcessGroup, tensor: torch.Tensor +) -> torch.futures.Future[torch.Tensor]: + "Averages the input gradient tensor by allreduce and returns a future." + group_to_use = process_group if process_group is not None else dist.group.WORLD + # Apply the division first to avoid overflow, especially for FP16. + tensor.div_(group_to_use.size()) + return ( + dist.all_reduce(tensor, group=group_to_use, async_op=True) + .get_future() + .then(lambda fut: fut.value()[0]) + ) + + +def cgx_hook( + state: CGXState, bucket: dist.GradBucket +) -> torch.futures.Future[torch.Tensor]: + if state.step == 2: + for layer_idx, tensor in enumerate(bucket.gradients()): + bits = state.quantization_bits if state.should_compress_(tensor) else VALUE_NO_COMPRESS + torch_cgx.register_layer(bucket.index(), layer_idx, tensor.numel(), + bits, state.quantization_bucket_size) + if bucket.is_last(): + state.step += 1 + state.layer_idx = 0 + return _allreduce_fut(state.process_group, bucket.buffer()) diff --git a/examples/cifar_train.py b/examples/cifar_train.py new file mode 100755 index 0000000..81910b1 --- /dev/null +++ b/examples/cifar_train.py @@ -0,0 +1,239 @@ +import torch +import argparse +import torch.backends.cudnn as cudnn +import torch.optim as optim +import torch.utils.data.distributed +from torchvision import datasets, transforms, models +import os + +from tqdm import tqdm + +import torch.distributed as dist + +from torch.nn.parallel import DistributedDataParallel as DDP + +CIFAR100_TRAIN_MEAN = (0.5070751592371323, 0.48654887331495095, 0.4409178433670343) +CIFAR100_TRAIN_STD = (0.2673342858792401, 0.2564384629170883, 0.27615047132568404) + +CIFAR10_TRAIN_MEAN = (0.4914, 0.4822, 0.4465) +CIFAR10_TRAIN_STD = (0.2023, 0.1994, 0.2010) + +NCOLS_SCREEN = 85 + +# Training settings +parser = argparse.ArgumentParser(description='PyTorch CIFAR Example', + formatter_class=argparse.ArgumentDefaultsHelpFormatter) +parser.add_argument('--dataset-dir', default=os.path.expanduser('./cifar10'), + help='path to training data') +parser.add_argument('--log-dir', default='./logs', + help='tensorboard log directory') + +parser.add_argument('--batch-size', type=int, default=256, + help='input batch size for training') +parser.add_argument('--val-batch-size', type=int, default=256, + help='input batch size for validation') +parser.add_argument('--epochs', type=int, default=200, + help='number of epochs to train') +parser.add_argument('--base-lr', type=float, default=0.1, + help='learning rate for a single GPU') +parser.add_argument('--momentum', type=float, default=0.9, + help='SGD momentum') +parser.add_argument('--wd', type=float, default=1e-4, + help='weight decay') + +parser.add_argument('--no-cuda', action='store_true', default=False, + help='disables CUDA training') +parser.add_argument('--seed', type=int, default=42, + help='random seed') +parser.add_argument('--dist-backend', choices=['cgx', 'nccl', 'gloo'], default='nccl', + help='Backend for torch distributed') +parser.add_argument('--quantization-bits', type=int, default=32, + help='Quantization bits for maxmin quantization') +parser.add_argument('--quantization-bucket-size', type=int, default=1024, + help='Bucket size for quantization in maxmin quantization') +parser.add_argument('--local_rank', type=int, default=-1, + help='Local rank in distributed launch') + +args = parser.parse_args() +args.cuda = not args.no_cuda and torch.cuda.is_available() + + +if "OMPI_COMM_WORLD_SIZE" in os.environ: + args.local_rank = int(os.environ["OMPI_COMM_WORLD_RANK"]) + os.environ['MASTER_ADDR'] = '127.0.0.1' + os.environ['MASTER_PORT'] = '4040' + os.environ["WORLD_SIZE"] = os.environ["OMPI_COMM_WORLD_SIZE"] + os.environ["RANK"] = os.environ["OMPI_COMM_WORLD_RANK"] + +if "WORLD_SIZE" in os.environ: + import torch_cgx + args.distributed = int(os.environ["WORLD_SIZE"]) > 1 + local_rank = args.local_rank % torch.cuda.device_count() + dist.init_process_group(backend=args.dist_backend, init_method="env://") + args.world_size = torch.distributed.get_world_size() + rank = torch.distributed.get_rank() +else: + args.distributed = False + local_rank = 0 + args.world_size = 1 + rank = 0 +print(args) + +if args.cuda: + torch.cuda.set_device(local_rank) + torch.cuda.manual_seed(args.seed) + +cudnn.benchmark = True + +verbose = 1 if rank == 0 else 0 + +torch.set_num_threads(4) + +is_cifar100 = "cifar100" in args.dataset_dir +if is_cifar100: + transform_mean, transform_std = CIFAR100_TRAIN_MEAN, CIFAR100_TRAIN_STD +else: + transform_mean, transform_std = CIFAR10_TRAIN_MEAN, CIFAR10_TRAIN_STD + +kwargs = {'num_workers': 0, 'pin_memory': True} if args.cuda else {} +transform_train = transforms.Compose([ + transforms.RandomCrop(32, padding=4), + transforms.RandomHorizontalFlip(), + transforms.ToTensor(), + transforms.Normalize(transform_mean, transform_std), +]) + +if is_cifar100: + train_dataset = datasets.CIFAR100(root=args.dataset_dir, train=True, download=True, transform=transform_train) +else: + train_dataset = datasets.CIFAR10(root=args.dataset_dir, train=True, download=True, transform=transform_train) + +train_sampler = torch.utils.data.distributed.DistributedSampler( + train_dataset, num_replicas=args.world_size, rank=rank) +train_loader = torch.utils.data.DataLoader( + train_dataset, batch_size=args.batch_size, + sampler=train_sampler, **kwargs) + +transform_test = transforms.Compose([ + transforms.ToTensor(), + transforms.Normalize(transform_mean, transform_std), +]) + +if is_cifar100: + val_dataset = datasets.CIFAR100(root=args.dataset_dir, train=False, download=True, transform=transform_test) +else: + val_dataset = datasets.CIFAR10(root=args.dataset_dir, train=False, download=True, transform=transform_test) +val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=args.val_batch_size, + **kwargs) + +if is_cifar100: + num_classes = 100 +else: + num_classes = 10 +model = models.resnet18(num_classes=num_classes) + +if args.cuda: + # Move model to GPU. + model.cuda() + +optimizer = optim.SGD(model.parameters(), + lr=args.base_lr, + momentum=args.momentum, weight_decay=args.wd) +if args.distributed: + model = DDP(model, device_ids=[local_rank]) + if args.dist_backend == 'cgx': + assert "OMPI_COMM_WORLD_SIZE" in os.environ, "CGX only works with with mpirun launch" + from cgx_utils import cgx_hook, CGXState + state = CGXState(torch.distributed.group.WORLD, + compression_params={"bits": args.quantization_bits, + "bucket_size": args.quantization_bucket_size}) + model.register_comm_hook(state, cgx_hook) + + +def adjust_learning_rate(epoch, batch_idx): + if epoch < 60: + lr_adj = 1. + elif epoch < 120: + lr_adj = 2e-1 + elif epoch < 160: + lr_adj = 4e-2 + else: + lr_adj = 8e-3 + for param_group in optimizer.param_groups: + param_group['lr'] = args.base_lr * lr_adj + + +def train(epoch): + model.train() + criterion = torch.nn.CrossEntropyLoss() + train_loss = Metric('train_loss') + train_accuracy = Metric('train_accuracy') + + with tqdm(total=len(train_loader), + desc='TEpoch #{}'.format(epoch + 1), disable=not verbose, ncols=NCOLS_SCREEN) as t: + for batch_idx, (data, target) in enumerate(train_loader): + adjust_learning_rate(epoch, batch_idx) + if args.cuda: + data, target = data.cuda(), target.cuda() + optimizer.zero_grad() + output = model(data) + train_accuracy.update(accuracy(output, target)) + loss = criterion(output, target) + train_loss.update(loss) + t.set_postfix({'loss': train_loss.avg.item(), + 'accuracy': 100. * train_accuracy.avg.item()}) + loss.backward() + optimizer.step() + t.update(1) + + +def validate(epoch): + model.eval() + criterion = torch.nn.CrossEntropyLoss() + val_loss = Metric('val_loss') + val_accuracy = Metric('val_accuracy') + with tqdm(total=len(val_loader), + desc='Validate Epoch #{}'.format(epoch + 1), + disable=not verbose, ncols=NCOLS_SCREEN) as t: + with torch.no_grad(): + for data, target in val_loader: + if args.cuda: + data, target = data.cuda(), target.cuda() + output = model(data) + val_loss.update(criterion(output, target)) + + val_accuracy.update(accuracy(output, target)) + t.set_postfix({'loss': val_loss.avg.item(), + 'accuracy': 100. * val_accuracy.avg.item()}) + t.update(1) + + +def accuracy(output, target): + # get the index of the max log-probability + pred = output.max(1, keepdim=True)[1] + return pred.eq(target.view_as(pred)).cpu().float().mean() + + +class Metric(object): + def __init__(self, name): + self.name = name + self.sum = torch.tensor(0.) + self.n = torch.tensor(0.) + + def update(self, val): + self.sum += val.detach().cpu() + self.n += 1 + + @property + def avg(self): + return self.sum / self.n + + +num_images = len(train_loader) +for epoch in range(0, args.epochs): + if args.world_size > 0: + train_sampler.set_epoch(epoch) + train(epoch) + validate(epoch) + if args.distributed: + dist.barrier() diff --git a/examples/requirements.txt b/examples/requirements.txt new file mode 100755 index 0000000..fa9cf06 --- /dev/null +++ b/examples/requirements.txt @@ -0,0 +1 @@ +tqdm \ No newline at end of file diff --git a/examples/run_cifar.sh b/examples/run_cifar.sh new file mode 100755 index 0000000..416bbab --- /dev/null +++ b/examples/run_cifar.sh @@ -0,0 +1,6 @@ +NUM_NODES=${1:-2} +batch_size=$(( 512 / $NUM_NODES )) + +mpirun -np $NUM_NODES --tag-output --allow-run-as-root -bind-to none -map-by slot -mca pml ob1 -mca btl ^openib -mca coll ^hcoll \ +--mca btl_tcp_if_exclude lo,docker0 python cifar_train.py --epochs 10 --dataset-dir ./cifar10 \ +--quantization-bits 8 --quantization-bucket-size 1024 --dist-backend cgx --batch-size $batch_size \ No newline at end of file diff --git a/setup.cfg b/setup.cfg new file mode 100755 index 0000000..224a779 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,2 @@ +[metadata] +description-file = README.md \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100755 index 0000000..3b36366 --- /dev/null +++ b/setup.py @@ -0,0 +1,77 @@ +from setuptools import setup, Extension +from torch.utils import cpp_extension +import os +import subprocess + +src = ['src/mpi_allreduce_operations.cc', 'src/ProcessGroupCGX.cc', + 'src/common/reducer.cc', 'src/common/buffer.cc', 'src/common/mpi_context.cc', + 'src/common/mpi_communicator.cc', 'src/common/shm_communicator.cc', + 'src/common/scatter_reduce_allgather.cc', 'src/common/ring.cc', 'src/common/utils.cc', + 'src/common/compressor.cc', 'src/common/layer.cc', 'src/common/shm_utils.cc', + 'src/common/compression/gpu_compression_operations.cc', 'src/common/nccl_reduce.cc'] + +MPI_HOME=os.environ.get("MPI_HOME", "/usr/local/mpi") +NCCL_HOME=os.environ.get("NCCL_HOME", "/usr/local/nccl") +NCCL_INCLUDE=os.environ.get("NCCL_INCLUDE", "/usr/local/nccl/include") +NCCL_LIB=os.environ.get("NCCL_LIB", "/usr/local/nccl/lib") +IS_CUDA=int(os.environ.get("CGX_CUDA", "1")) != 0 +CUDA_VECTORIZED=int(os.environ.get("CUDA_VECTORIZED", "1")) != 0 +QSGD_DETERMENISTIC=int(os.environ.get("QSGD_DETERMENISTIC", "1")) != 0 +link_args = ['-L'+ os.path.join(MPI_HOME, 'lib'), '-lmpi'] +ompi_info_bin=os.path.join(MPI_HOME, 'bin', 'ompi_info') +env = os.environ +try: + ompi_info_out = subprocess.check_output([ompi_info_bin, '--parsable'], env=env) +except OSError as e: + raise RuntimeError('CMake failed: {}'.format(str(e))) + +if "bindings:cxx:yes" in str(ompi_info_out): + link_args.append('-lmpi_cxx') +if IS_CUDA: + src.extend(['src/common/compression/cuda_compression_operations.cu', 'src/common/cuda_operations.cc']) +else: + src.extend(['src/common/compression/hip_compression_operations.cc', 'src/common/hip_operations.cc']) +include_dirs = [os.path.join(MPI_HOME, "include")] +cxx_compile_args = ["-D_GLIBCXX_USE_CXX11_ABI=0"] +nvcc_compile_args = [] +if IS_CUDA: + cxx_compile_args.append("-DHAVE_CUDA=1") + nvcc_compile_args.append("-DHAVE_CUDA=1") + os.environ['TORCH_CUDA_ARCH_LIST'] = '7.0;7.5;8.6' +else: + cxx_compile_args.append("-DHAVE_ROCM=1") + nvcc_compile_args.append("-DHAVE_ROCM=1") + +if os.path.isdir(NCCL_HOME): + include_dirs.append(os.path.join(NCCL_HOME, "include")) + link_args.append('-L' + os.path.join(NCCL_HOME, 'lib')) + link_args.append('-lnccl') +elif os.path.isdir(NCCL_INCLUDE) and os.path.isdir(NCCL_LIB): + include_dirs.append(os.path.join(NCCL_INCLUDE)) + link_args.append('-L' + os.path.join(NCCL_LIB)) + link_args.append('-lnccl') +else: + raise ValueError("NCCL is not available") + +if CUDA_VECTORIZED: + nvcc_compile_args.append("-DCUDA_VECTORIZED=1") + cxx_compile_args.append("-DCUDA_VECTORIZED=1") +if QSGD_DETERMENISTIC: + nvcc_compile_args.append("-DQSGD_DETERMENISTIC=1") + cxx_compile_args.append("-DQSGD_DETERMENISTIC=1") + +setup(name='torch_cgx', + packages=['cgx_utils'], + version='0.1.0', + description='pytorch extension adding a backend ' + 'supporting allreduce of quantized buffers.', + author='Ilia Markov', + author_email='ilia.markov@ist.ac.at', + url='https://github.com/IST-DASLab/torch_cgx/', + download_url="https://github.com/IST-DASLab/torch_cgx/archive/refs/tags/v0.1.0.tar.gz", + ext_modules=[cpp_extension.CUDAExtension('torch_cgx', sources=src, + include_dirs=include_dirs, + extra_compile_args={'cxx': cxx_compile_args, 'nvcc': nvcc_compile_args}, + extra_link_args=link_args)], + cmdclass={'build_ext': cpp_extension.BuildExtension}, + ) diff --git a/src/ProcessGroupCGX.cc b/src/ProcessGroupCGX.cc new file mode 100755 index 0000000..8cffee1 --- /dev/null +++ b/src/ProcessGroupCGX.cc @@ -0,0 +1,859 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include "ProcessGroupCGX.h" + +#include +#include + +#include +#include +#include // Needed for CUDA-aware check + +namespace cgx { + +#define MPI_CHECK(cmd) \ + do { \ + int mpiStatus = cmd; \ + if (mpiStatus != MPI_SUCCESS) { \ + std::string err = "MPI error in: " + std::string(__FILE__) + ":" + \ + std::to_string(__LINE__) + \ + ", with error code: " + std::to_string(mpiStatus); \ + throw std::runtime_error(err); \ + } \ + } while (0) + +namespace { + +// Op mapping +std::map mpiOp = { + {c10d::ReduceOp::MIN, MPI_MIN}, + {c10d::ReduceOp::MAX, MPI_MAX}, + {c10d::ReduceOp::SUM, MPI_SUM}, + {c10d::ReduceOp::PRODUCT, MPI_PROD}, +}; +// Type mapping +std::map mpiDatatype = { + {at::kByte, MPI_UNSIGNED_CHAR}, + {at::kChar, MPI_CHAR}, + {at::kDouble, MPI_DOUBLE}, + {at::kFloat, MPI_FLOAT}, + {at::kInt, MPI_INT}, + {at::kLong, MPI_LONG}, + {at::kShort, MPI_SHORT}, +}; + +// Checking CUDA-aware MPI support, currently we only support CUDA aware +// MPI ops through Open MPI +bool cudaAwareMpiCheck() { +// Run time check +#if defined(MPIX_CUDA_AWARE_SUPPORT) + if (MPIX_Query_cuda_support() == 1) { + return true; + } else { + return false; + } +#else // !defined(MPIX_CUDA_AWARE_SUPPORT) + return false; +#endif // MPIX_CUDA_AWARE_SUPPORT +} + +// Checking the input tensor's validity +void checkSingleTensorHelper(const at::Tensor &tensor) { + if (!tensor.is_contiguous()) { + throw std::runtime_error("input tensor has to be contiguous"); + } + if (tensor.is_sparse()) { + throw std::runtime_error("input tensor has to be dense"); + } + if (tensor.is_cuda() && !cudaAwareMpiCheck()) { + throw std::runtime_error("CUDA tensor detected and the MPI used doesn't " + "have CUDA-aware MPI support"); + } +} + +void checkSingleTensor(const std::vector &tensors) { + if (tensors.size() != 1) { + throw std::runtime_error( + "MPI process group does not support multi-GPU collectives"); + } + checkSingleTensorHelper(tensors[0]); +} + +void checkSameSizeAndType(const at::Tensor &tensor, + const std::vector &tensors) { + for (size_t i = 0; i < tensors.size(); ++i) { + if ((tensors[i].numel() != tensor.numel()) || + (tensors[i].type() != tensor.type())) { + throw std::runtime_error("Tensors are not equal in size or data type"); + } + checkSingleTensorHelper(tensors[i]); + } +} + +} // namespace + +std::vector ProcessGroupCGX::WorkMPI::result() { + return outputTensors_; +} + +c10::intrusive_ptr ProcessGroupCGX::WorkMPI::getFuture() { + return future_; +} + +void ProcessGroupCGX::WorkMPI::finishWorkMPIError(std::exception_ptr eptr) { + future_->setError(eptr); + finish(eptr); +} + +void ProcessGroupCGX::WorkMPI::finishWorkMPI() { + if (compressed_) { + c10::cuda::CUDAStreamGuard streamGuard(*cgx_stream); + future_->markCompleted(at::IValue(outputTensors_)); + } else { + future_->markCompleted(at::IValue(outputTensors_)); + } + finish(); +} + +void ProcessGroupCGX::WorkMPI::synchronize() { + if (compressed_) { + auto data = outputTensors_[0]; + c10::DeviceGuard guard(data.device()); + std::unique_lock globalLock(pgGlobalMutex_); + endEvent_->block(at::cuda::getCurrentCUDAStream()); + } +} + +ProcessGroupCGX::AsyncWork::AsyncWork( + MPI_Request request, std::vector outputTensors, + const char *profilingTitle, + const c10::optional> &inputTensors) + : c10d::ProcessGroup::Work(-1, c10d::OpType::UNKNOWN, profilingTitle, + inputTensors), + outputTensors_(std::move(outputTensors)), request_(request) { + memset(&status_, 0, sizeof(status_)); +} + +ProcessGroupCGX::AsyncWork::~AsyncWork() { + if (request_ != MPI_REQUEST_NULL) { + std::cerr + << "Attempted destruction of AsyncWork before work has completed, " + << "terminating the program." << std::endl; + std::terminate(); + } +} + +bool ProcessGroupCGX::AsyncWork::isCompleted() { + if (request_ == MPI_REQUEST_NULL) { + return true; + } + + std::unique_lock globalLock(pgGlobalMutex_); + int flag = 0; + MPI_CHECK(MPI_Test(&request_, &flag, &status_)); + if (request_ != MPI_REQUEST_NULL) { + return false; + } + + // request_ == MPI_REQUEST_NULL; the work has completed + // Populate exception if request was not successful + if (status_.MPI_ERROR != MPI_SUCCESS) { + populateException(); + } + + return true; +} + +bool ProcessGroupCGX::AsyncWork::isSuccess() const { + if (request_ != MPI_REQUEST_NULL) { + throw std::runtime_error( + "Invalid call to AsyncWork::isSuccess before work has completed"); + } + + return status_.MPI_ERROR == MPI_SUCCESS; +} + +int ProcessGroupCGX::AsyncWork::sourceRank() const { + return status_.MPI_SOURCE; +} + +bool ProcessGroupCGX::AsyncWork::wait(std::chrono::milliseconds /* unused */) { + if (request_ == MPI_REQUEST_NULL) { + return true; + } + + std::unique_lock globalLock(pgGlobalMutex_); + MPI_CHECK(MPI_Wait(&request_, &status_)); + auto ok = (status_.MPI_ERROR == MPI_SUCCESS); + if (!ok) { + populateException(); + std::rethrow_exception(exception_); + } + // Always return true, because abort API is not implemented. + return true; +} + +void ProcessGroupCGX::AsyncWork::abort(){ + TORCH_CHECK(false, "ProcessGroupCGX::AsyncWork::abort not implemented.")} + +std::vector ProcessGroupCGX::AsyncWork::result() { + return outputTensors_; +} + +void ProcessGroupCGX::AsyncWork::populateException() { + std::array buf; + int len = buf.size(); + MPI_CHECK(MPI_Error_string(status_.MPI_ERROR, buf.data(), &len)); + exception_ = + std::make_exception_ptr(std::runtime_error(std::string(buf.data(), len))); +} + +// Static global states +int ProcessGroupCGX::mpiThreadSupport_ = 0; +std::mutex ProcessGroupCGX::pgGlobalMutex_; +// We only want to initialize once +std::once_flag ProcessGroupCGX::onceFlagInitMPI; + +void ProcessGroupCGX::mpiExit() { + std::unique_lock globalLock(pgGlobalMutex_); + if (mpiDatatype.find(at::kHalf) != mpiDatatype.end()) { + MPI_Type_free(&mpiDatatype[at::kHalf]); + } + MPI_CHECK(MPI_Finalize()); +} + +void ProcessGroupCGX::initMPIOnce() { + // Initialize MPI environment + std::call_once(onceFlagInitMPI, []() { + MPI_CHECK(MPI_Init_thread(nullptr, nullptr, MPI_THREAD_SERIALIZED, + &mpiThreadSupport_)); + if (mpiThreadSupport_ < MPI_THREAD_SERIALIZED) { + throw std::runtime_error("Used MPI implementation doesn't have the " + "minimum level of threading support: " + "MPI_THREAD_SERIALIZED. This is required by " + "c10d package"); + } + if (std::atexit(ProcessGroupCGX::mpiExit)) { + throw std::runtime_error("Fail to register the MPI exit handler"); + } + }); +} + +c10::intrusive_ptr ProcessGroupCGX::createProcessGroupCGX( + const c10::intrusive_ptr &store, int rank, int size, + const std::chrono::duration &timeout) { + // Once initialization + initMPIOnce(); + + MPI_Comm groupComm = MPI_COMM_WORLD; + return c10::make_intrusive(rank, size, groupComm); +} + +ProcessGroupCGX::ProcessGroupCGX(int rank, int size, MPI_Comm pgComm) + : ProcessGroup(rank, size), stop_(false), pgComm_(pgComm) { + if (pgComm_ == MPI_COMM_NULL) { + throw std::runtime_error("pgComm_ must not be MPI_COMM_NULL"); + } + allreduce_operator = std::make_unique(); + // Start the worker thread accepting MPI calls + workerThread_ = std::thread(&ProcessGroupCGX::runLoop, this); +} + +ProcessGroupCGX::~ProcessGroupCGX() { destroy(); } + +void ProcessGroupCGX::destroy() { + std::unique_lock lock(pgMutex_); + queueConsumeCV_.wait(lock, [&] { return queue_.empty(); }); + // Queue is empty, signal stop + stop_ = true; + + // Release lock to allow threads to terminate + lock.unlock(); + queueProduceCV_.notify_all(); + + // Join the single worker thread + workerThread_.join(); +} + +void ProcessGroupCGX::abort() { + destroy(); + MPI_Abort(pgComm_, EXIT_FAILURE); +} + +void ProcessGroupCGX::runLoop() { + std::unique_lock lock(pgMutex_); + while (!stop_) { + if (queue_.empty()) { + queueProduceCV_.wait(lock); + continue; + } + auto workTuple = std::move(queue_.front()); + queue_.pop(); + auto &workEntry = std::get<0>(workTuple); + auto &work = std::get<1>(workTuple); + queueConsumeCV_.notify_one(); + try { + workEntry->run(workEntry); + work->finishWorkMPI(); + } catch (std::exception &e) { + work->finishWorkMPIError(std::current_exception()); + } + } +} + +c10::intrusive_ptr ProcessGroupCGX::enqueue( + std::unique_ptr entry, const char *profilingTitle, + const c10::optional> &inputTensors, bool compressed, + const std::shared_ptr stream) { + auto work = + c10::make_intrusive(entry->dst, profilingTitle, inputTensors, + entry->endEvent_, compressed, stream); + if (compressed) { + c10::cuda::CUDAStreamGuard streamGuard(*(stream)); + work->future_ = c10::make_intrusive( + c10::ListType::create(c10::TensorType::get()), + std::vector({entry->dst[0].device()})); + } + std::unique_lock lock(pgMutex_); + queue_.push(std::make_tuple(std::move(entry), work)); + lock.unlock(); + queueProduceCV_.notify_one(); + return work; +} + +c10::intrusive_ptr +ProcessGroupCGX::broadcast(std::vector &tensors, + const c10d::BroadcastOptions &opts) { + checkSingleTensor(tensors); + std::function &)> runFunc = + [opts, this](std::unique_ptr &entry) { + auto data = (entry->src)[0]; + c10::DeviceGuard guard(data.device()); + std::unique_lock globalLock(pgGlobalMutex_); + MPI_Datatype dtype; + if (mpiDatatype.find(data.scalar_type()) != mpiDatatype.end()) + dtype = mpiDatatype.at(data.scalar_type()); + else { + assert(data.scalar_type() == at::kHalf); + MPI_CHECK(MPI_Type_contiguous(2, MPI_BYTE, &dtype)); + MPI_CHECK(MPI_Type_commit(&dtype)); + mpiDatatype[data.scalar_type()] = dtype; + } + MPI_CHECK(MPI_Bcast(data.data_ptr(), data.numel(), + mpiDatatype.at(data.scalar_type()), opts.rootRank, + pgComm_)); + }; + auto entry = std::unique_ptr( + new WorkEntry(&tensors, nullptr, std::move(runFunc))); + return enqueue(std::move(entry), "mpi:broadcast", + c10::optional>(tensors)); +} + +c10::intrusive_ptr +ProcessGroupCGX::allreduce(std::vector &tensors, + const c10d::AllreduceOptions &opts) { + checkSingleTensor(tensors); + auto &tensor = tensors[0]; + bool do_compress = (tensor.scalar_type() == at::kFloat or + tensor.scalar_type() == at::kHalf) and + opts.reduceOp == c10d::ReduceOp::SUM and + tensor.device().type() == at::kCUDA; + auto device_idx = tensor.device().index(); + if (streams_.find(device_idx) == streams_.end()) { + streams_.emplace(device_idx, std::make_shared( + std::move(at::cuda::getStreamFromPool()))); + } + if (cuda_start_events_.find(device_idx) == cuda_start_events_.end()) { + cuda_start_events_.emplace(device_idx, + std::make_shared()); + cuda_end_events_.emplace(device_idx, + std::make_shared()); + } + + std::function &)> runFunc = + [opts, this, do_compress, device_idx](std::unique_ptr &entry) { + auto &bucket = entry->src[0]; + c10::DeviceGuard guard(bucket.device()); + std::unique_lock globalLock(pgGlobalMutex_); + if (do_compress) { + (c10::cuda::CUDACachingAllocator::getFreeMutex())->lock(); + auto &cgx_event_start = *(cuda_start_events_.at(device_idx)); + auto &cgx_stream = *(streams_.at(device_idx)); + const auto ¤tStream = + at::cuda::getCurrentCUDAStream(device_idx); + cgx_event_start.record(currentStream); + cgx_event_start.block(cgx_stream); + c10::cuda::CUDACachingAllocator::recordStream( + bucket.storage().data_ptr(), cgx_stream); + allreduce_operator->PerformOperation(bucket, cgx_stream); + entry->endEvent_->record(cgx_stream); + (c10::cuda::CUDACachingAllocator::getFreeMutex())->unlock(); + } else { + MPI_CHECK(MPI_Allreduce(MPI_IN_PLACE, bucket.data_ptr(), + bucket.numel(), + mpiDatatype.at(bucket.scalar_type()), + mpiOp.at(opts.reduceOp), pgComm_)); + } + }; + auto entry = std::unique_ptr(new WorkEntry( + &tensors, &tensors, std::move(runFunc), cuda_end_events_.at(device_idx))); + return enqueue(std::move(entry), "mpi:allreduce", + c10::optional>(tensors), do_compress, + streams_.at(device_idx)); +} + +c10::intrusive_ptr +ProcessGroupCGX::allreduce_coalesced( + std::vector &tensors, + const c10d::AllreduceCoalescedOptions &opts) { + throw std::runtime_error( + "allreduce_coalesced is currently not supported with MPI"); +} + +c10::intrusive_ptr +ProcessGroupCGX::reduce(std::vector &tensors, + const c10d::ReduceOptions &opts) { + checkSingleTensor(tensors); + + std::function &)> runFunc = + [opts, this](std::unique_ptr &entry) { + auto data = (entry->src)[0]; + auto dataPtr = (entry->src)[0].data_ptr(); + void *sendbuf = (rank_ == opts.rootRank) ? MPI_IN_PLACE : dataPtr; + void *recvbuf = (rank_ == opts.rootRank) ? dataPtr : nullptr; + + c10::DeviceGuard guard(data.device()); + std::unique_lock globalLock(pgGlobalMutex_); + MPI_CHECK(MPI_Reduce(sendbuf, recvbuf, data.numel(), + mpiDatatype.at(data.scalar_type()), + mpiOp.at(opts.reduceOp), opts.rootRank, pgComm_)); + }; + auto entry = std::unique_ptr( + new WorkEntry(&tensors, &tensors, std::move(runFunc))); + return enqueue(std::move(entry), "mpi:reduce", + c10::optional>(tensors)); +} + +c10::intrusive_ptr +ProcessGroupCGX::allgather(std::vector> &outputTensors, + std::vector &inputTensors, + const c10d::AllgatherOptions &opts) { + checkSingleTensor(inputTensors); + if (outputTensors.size() != 1) { + throw std::runtime_error("MPI process group only supports a single " + "tensor op"); + } + if (static_cast(size_) != outputTensors[0].size()) { + throw std::runtime_error( + "All gather: number of output tensors should equal " + "to the world size"); + } + + checkSameSizeAndType(inputTensors[0], outputTensors[0]); + + std::function &)> runFunc = + [this](std::unique_ptr &entry) { + auto data = (entry->src)[0]; + std::vector outputDataVec = entry->dst; + auto flatOutputTensor = c10d::newLikeFlat(outputDataVec); + + c10::DeviceGuard guard(data.device()); + std::unique_lock globalLock(pgGlobalMutex_); + MPI_CHECK(MPI_Allgather(data.data_ptr(), data.numel(), + mpiDatatype.at(data.scalar_type()), + flatOutputTensor.data_ptr(), data.numel(), + mpiDatatype.at(data.scalar_type()), pgComm_)); + + for (size_t i = 0; i < outputDataVec.size(); ++i) { + outputDataVec[i].copy_(flatOutputTensor[i]); + } + }; + auto entry = std::unique_ptr( + new WorkEntry(&inputTensors, &outputTensors[0], std::move(runFunc))); + return enqueue(std::move(entry), "mpi:allgather", + c10::optional>(inputTensors)); +} + +c10::intrusive_ptr +ProcessGroupCGX::allgather_coalesced( + std::vector> & /* unused */, + std::vector & /* unused */, + const c10d::AllgatherOptions & /* unused */) { + throw std::runtime_error( + "ProcessGroupCGX does not support allgather_coalesced"); +} + +c10::intrusive_ptr +ProcessGroupCGX::gather(std::vector> &outputTensors, + std::vector &inputTensors, + const c10d::GatherOptions &opts) { + checkSingleTensor(inputTensors); + + if (rank_ != opts.rootRank) { + if (outputTensors.size() > 0) { + throw std::runtime_error("Gather: number of output tensors should be 0 " + "for non-root"); + } + } else { + if (outputTensors.size() != 1) { + throw std::runtime_error("Gather: multi-GPU collective is not supported"); + } + if (static_cast(size_) != outputTensors[0].size()) { + throw std::runtime_error("Gather: number of output tensors should equal " + "to the world size"); + } + checkSameSizeAndType(inputTensors[0], outputTensors[0]); + } + + std::function &)> runFunc = + [opts, this](std::unique_ptr &entry) { + auto data = (entry->src)[0]; + void *recvbuf = nullptr; + at::Tensor flatOutputTensor; + + std::vector dstdata = entry->dst; + if (rank_ == opts.rootRank) { + flatOutputTensor = c10d::newLikeFlat(dstdata); + recvbuf = flatOutputTensor.data_ptr(); + } + + c10::DeviceGuard guard(data.device()); + std::unique_lock globalLock(pgGlobalMutex_); + MPI_CHECK(MPI_Gather(data.data_ptr(), data.numel(), + mpiDatatype.at(data.scalar_type()), recvbuf, + data.numel(), mpiDatatype.at(data.scalar_type()), + opts.rootRank, pgComm_)); + + if (rank_ == opts.rootRank) { + const std::vector &outputDataVec = entry->dst; + // copy the flattened output tensors to the outputs + for (size_t i = 0; i < outputDataVec.size(); ++i) { + outputDataVec.at(i).copy_(flatOutputTensor[i]); + } + } + }; + + if (rank_ == opts.rootRank) { + auto entry = std::unique_ptr( + new WorkEntry(&inputTensors, &outputTensors[0], std::move(runFunc))); + return enqueue(std::move(entry), "mpi:gather", + c10::optional>(inputTensors)); + } else { + auto entry = std::unique_ptr( + new WorkEntry(&inputTensors, nullptr, std::move(runFunc))); + return enqueue(std::move(entry), "mpi:gather", + c10::optional>(inputTensors)); + } +} + +c10::intrusive_ptr +ProcessGroupCGX::scatter(std::vector &outputTensors, + std::vector> &inputTensors, + const c10d::ScatterOptions &opts) { + checkSingleTensor(outputTensors); + + if (rank_ != opts.rootRank) { + if (inputTensors.size() > 0) { + throw std::runtime_error("Scatter: number of input tensors should be 0 " + "for non-root"); + } + } else { + if (inputTensors.size() != 1) { + throw std::runtime_error( + "Scatter: multi-GPU collective is not supported"); + } + if (static_cast(size_) != inputTensors[0].size()) { + throw std::runtime_error("Scatter: number of input tensors should equal " + "to the world size"); + } + checkSameSizeAndType(outputTensors[0], inputTensors[0]); + } + + std::function &)> runFunc = + [opts, this](std::unique_ptr &entry) { + auto data = (entry->dst)[0]; + void *sendbuf = nullptr; + at::Tensor flatInputTensor; + + if (rank_ == opts.rootRank) { + std::vector &inputDataVec = entry->src; + flatInputTensor = c10d::newLikeFlat(inputDataVec); + sendbuf = flatInputTensor.data_ptr(); + + // copy the input tensors to the flatten large send buffer + for (size_t i = 0; i < inputDataVec.size(); ++i) { + flatInputTensor[i].copy_(inputDataVec.at(i)); + } + } + + c10::DeviceGuard guard(data.device()); + std::unique_lock globalLock(pgGlobalMutex_); + MPI_CHECK(MPI_Scatter( + sendbuf, data.numel(), mpiDatatype.at(data.scalar_type()), + data.data_ptr(), data.numel(), mpiDatatype.at(data.scalar_type()), + opts.rootRank, pgComm_)); + }; + + if (rank_ == opts.rootRank) { + auto entry = std::unique_ptr( + new WorkEntry(&inputTensors[0], &outputTensors, std::move(runFunc))); + return enqueue(std::move(entry), "mpi:scatter", + inputTensors.size() > 0 + ? c10::optional>(inputTensors[0]) + : c10::nullopt); + } else { + auto entry = std::unique_ptr( + new WorkEntry(nullptr, &outputTensors, std::move(runFunc))); + return enqueue(std::move(entry), "mpi:scatter", + inputTensors.size() > 0 + ? c10::optional>(inputTensors[0]) + : c10::nullopt); + } +} + +c10::intrusive_ptr ProcessGroupCGX::reduce_scatter( + std::vector &outputTensors, + std::vector> &inputTensors, + const c10d::ReduceScatterOptions &opts) { + throw std::runtime_error("ProcessGroupCGX does not support reduce_scatter"); +} + +c10::intrusive_ptr ProcessGroupCGX::alltoall_base( + at::Tensor &outputTensor, at::Tensor &inputTensor, + std::vector &outputSplitSizes, + std::vector &inputSplitSizes, const c10d::AllToAllOptions &opts) { + checkSingleTensorHelper(inputTensor); + checkSingleTensorHelper(outputTensor); + + if (outputSplitSizes.size() == 0 && inputSplitSizes.size() == 0) { + // We can use alltoall + TORCH_CHECK(outputTensor.numel() == inputTensor.numel() && + outputTensor.type() == inputTensor.type(), + "Tensors are not equal in size or data type"); + TORCH_CHECK(outputTensor.size(0) % size_ == 0, + "Tensor's dim 0 does not divide equally across group size"); + + std::function &)> runFunc = + [opts, this](std::unique_ptr &entry) { + auto srcdata = (entry->src)[0]; + auto dstdata = (entry->dst)[0]; + c10::DeviceGuard guard(srcdata.device()); + std::unique_lock globalLock(pgGlobalMutex_); + MPI_CHECK(MPI_Alltoall(srcdata.data_ptr(), srcdata.numel() / size_, + mpiDatatype.at(srcdata.scalar_type()), + dstdata.data_ptr(), dstdata.numel() / size_, + mpiDatatype.at(dstdata.scalar_type()), + pgComm_)); + }; + std::vector inputTensors = {inputTensor}; + std::vector outputTensors = {outputTensor}; + auto entry = std::unique_ptr( + new WorkEntry(&inputTensors, &outputTensors, std::move(runFunc))); + return enqueue(std::move(entry), "mpi:all_to_all", + c10::optional>(inputTensors)); + } else { + // Need alltoallv + c10d::checkSplitSizes(inputSplitSizes, inputTensor, size_); + c10d::checkSplitSizes(outputSplitSizes, outputTensor, size_); + std::function &)> runFunc = + [opts, this, inputSplitSizes, + outputSplitSizes](std::unique_ptr &entry) { + auto srcdata = (entry->src)[0]; + auto dstdata = (entry->dst)[0]; + std::vector send_lengths(size_); + std::vector recv_lengths(size_); + std::vector send_offsets(size_); + std::vector recv_offsets(size_); + c10d::computeLengthsAndOffsets(inputSplitSizes, srcdata, + &send_lengths, &send_offsets); + c10d::computeLengthsAndOffsets(outputSplitSizes, dstdata, + &recv_lengths, &recv_offsets); + c10::DeviceGuard guard(srcdata.device()); + std::unique_lock globalLock(pgGlobalMutex_); + MPI_CHECK(MPI_Alltoallv( + srcdata.data_ptr(), send_lengths.data(), send_offsets.data(), + mpiDatatype.at(srcdata.scalar_type()), dstdata.data_ptr(), + recv_lengths.data(), recv_offsets.data(), + mpiDatatype.at(dstdata.scalar_type()), pgComm_)); + }; + std::vector inputTensors = {inputTensor}; + std::vector outputTensors = {outputTensor}; + auto entry = std::unique_ptr( + new WorkEntry(&inputTensors, &outputTensors, std::move(runFunc))); + return enqueue(std::move(entry), "mpi:all_to_all", + c10::optional>(inputTensors)); + } +} +c10::intrusive_ptr +ProcessGroupCGX::alltoall(std::vector &outputTensors, + std::vector &inputTensors, + const c10d::AllToAllOptions &opts) { + TORCH_CHECK(inputTensors.size() == size_, + "Number of input tensors are not equal to group size"); + TORCH_CHECK(outputTensors.size() == size_, + "Number of output tensors are not equal to group size"); + std::function &)> runFunc = + [opts, this](std::unique_ptr &entry) { + std::vector send_lengths(size_); + std::vector recv_lengths(size_); + std::vector send_offsets(size_); + std::vector recv_offsets(size_); + auto srcdata = entry->src; + auto dstdata = entry->dst; + int64_t src_len = c10d::computeLengthsAndOffsets(srcdata, &send_lengths, + &send_offsets); + int64_t dst_len = c10d::computeLengthsAndOffsets(dstdata, &recv_lengths, + &recv_offsets); + std::vector send_lengthsL(send_lengths.begin(), + send_lengths.end()); + std::vector recv_lengthsL(recv_lengths.begin(), + recv_lengths.end()); + at::Tensor srcFlatData = at::empty({src_len}, srcdata[0].options()); + at::Tensor dstFlatData = at::empty({dst_len}, dstdata[0].options()); + auto srcFlatDataSplits = + srcFlatData.split_with_sizes(c10::IntArrayRef(send_lengthsL), 0); + for (int i = 0; i < size_; i++) { + srcFlatDataSplits[i].copy_(srcdata[i].view({-1})); + } + c10::DeviceGuard guard1(srcdata[0].device()); + std::unique_lock globalLock(pgGlobalMutex_); + MPI_CHECK(MPI_Alltoallv( + srcFlatData.data_ptr(), send_lengths.data(), send_offsets.data(), + mpiDatatype.at(srcdata[0].scalar_type()), dstFlatData.data_ptr(), + recv_lengths.data(), recv_offsets.data(), + mpiDatatype.at(dstdata[0].scalar_type()), pgComm_)); + + auto dstFlatDataSplits = + dstFlatData.split_with_sizes(c10::IntArrayRef(recv_lengthsL), 0); + for (int i = 0; i < size_; i++) { + dstdata[i].view({-1}).copy_(dstFlatDataSplits[i]); + } + }; + auto entry = std::unique_ptr( + new WorkEntry(&inputTensors, &outputTensors, std::move(runFunc))); + return enqueue(std::move(entry), "mpi:all_to_all", + c10::optional>(inputTensors)); +} + +c10::intrusive_ptr +ProcessGroupCGX::send(std::vector &tensors, int dstRank, int tag) { + checkSingleTensor(tensors); + + auto &tensor = tensors[0]; + MPI_Request request = MPI_REQUEST_NULL; + + { + c10::DeviceGuard guard(tensor.device()); + std::unique_lock globalLock(pgGlobalMutex_); + MPI_CHECK(MPI_Isend(tensor.data_ptr(), tensor.numel(), + mpiDatatype.at(tensor.scalar_type()), dstRank, tag, + pgComm_, &request)); + } + + return c10::make_intrusive( + request, std::vector(), "mpi:send", + c10::optional>(tensors)); +} + +c10::intrusive_ptr +ProcessGroupCGX::recv(std::vector &tensors, int srcRank, int tag) { + checkSingleTensor(tensors); + + auto &tensor = tensors[0]; + MPI_Request request = MPI_REQUEST_NULL; + + { + c10::DeviceGuard guard(tensor.device()); + std::unique_lock globalLock(pgGlobalMutex_); + MPI_CHECK(MPI_Irecv(tensor.data_ptr(), tensor.numel(), + mpiDatatype.at(tensor.scalar_type()), srcRank, tag, + pgComm_, &request)); + } + + return c10::make_intrusive( + request, tensors, "mpi:recv", + c10::optional>(tensors)); +} + +c10::intrusive_ptr +ProcessGroupCGX::recvAnysource(std::vector &tensors, int tag) { + checkSingleTensor(tensors); + + auto &tensor = tensors[0]; + MPI_Request request = MPI_REQUEST_NULL; + + { + c10::DeviceGuard guard(tensor.device()); + std::unique_lock globalLock(pgGlobalMutex_); + MPI_CHECK(MPI_Irecv(tensor.data_ptr(), tensor.numel(), + mpiDatatype.at(tensor.scalar_type()), MPI_ANY_SOURCE, + tag, pgComm_, &request)); + } + + return c10::make_intrusive( + request, tensors, "mpi:recvAnySource", + c10::optional>(tensors)); +} + +c10::intrusive_ptr +ProcessGroupCGX::barrier(const c10d::BarrierOptions &opts) { + std::function &)> runFunc = + [this](std::unique_ptr &entry) { + std::unique_lock globalLock(pgGlobalMutex_); + MPI_CHECK(MPI_Barrier(pgComm_)); + }; + auto entry = std::unique_ptr( + new WorkEntry(nullptr, nullptr, std::move(runFunc))); + return enqueue(std::move(entry), "mpi:barrier", c10::nullopt); +} + +c10::intrusive_ptr +ProcessGroupCGX::_allgather_base(at::Tensor & /*unused */, + at::Tensor & /*unused */, + const c10d::AllgatherOptions & /*unused */) { + throw std::runtime_error( + "no support for allgather_base in MPI process group"); +} + +MPI_Datatype ProcessGroupCGX::float16_type; + +void RegisterLayer(unsigned bucket_idx, unsigned layer_idx, + unsigned layer_numel, int bits, int bucket_size) { + MPIAllReduce_Operation::RegisterLayer(bucket_idx, layer_idx, layer_numel, + bits, bucket_size); +} + + +void SetQBits(unsigned bucket_idx, unsigned layer_idx, int bits) { + MPIAllReduce_Operation::SetQBits(bucket_idx, layer_idx, bits); +} + +void SetQBucketSize(unsigned bucket_idx, unsigned layer_idx, int bucket_size) { + MPIAllReduce_Operation::SetQBits(bucket_idx, layer_idx, bucket_size); +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("createProcessGroupCGX", &ProcessGroupCGX::createProcessGroupCGX); + m.def("register_layer", &RegisterLayer); + m.def("set_quantization_bits", &SetQBits); + m.def("set_quantization_bucket_size", &SetQBucketSize); +} + +} // namespace cgx diff --git a/src/ProcessGroupCGX.h b/src/ProcessGroupCGX.h new file mode 100755 index 0000000..522f837 --- /dev/null +++ b/src/ProcessGroupCGX.h @@ -0,0 +1,307 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "mpi_allreduce_operations.h" +#include + +#include +#include + +#include +#include + +namespace cgx { + +constexpr const char *CGX_BACKEND_NAME = "cgx"; + +// WorkEntry is the state associated with a single MPI run instance. +// It include the source Tensor list and destination Tensor list, as well as +// The actual run function that will operate either on src or dst or both. +struct WorkEntry { + explicit WorkEntry(std::vector *srcPtr, + std::vector *dstPtr, + std::function &)> run, + std::shared_ptr endEvent = nullptr) + : dst(dstPtr ? *dstPtr : std::vector()), run(std::move(run)), + endEvent_(endEvent) { + if (srcPtr) { + src = *srcPtr; + } + } + + // Not copyable + WorkEntry(const WorkEntry &) = delete; + // Not copy assignable + WorkEntry &operator=(const WorkEntry &) = delete; + + // For input and output tensors (in-place), we will always use src + std::vector src; + const std::vector dst; + std::shared_ptr endEvent_ = nullptr; + // src rank returned, for recv only + int *srcRank = nullptr; + std::function &)> run; +}; + +// ProcessGroupCGX implements MPI bindings with quantization for c10d. +// +// All functions on this class are expected to be called in the same +// order across processes in the group. This is the only way that we +// can guarantee to match up the same calls across processes. +// +// All MPI functions provided by this class is asynchronously scheduled on a +// Worker thread. Therefore, ProcessGroupCGX requires the MPI implementation +// that is used to have a minimum thread support value of MPI_THREAD_SERIALIZED. +// That is, The process may be multi-threaded, and multiple threads may make +// MPI calls, but only one at a time: MPI calls are not made concurrently from +// two distinct threads (all MPI calls are serialized). However, with +// MPI_THREAD_SERIALIZED, ProcessGroupCGX will only support a singe process +// group. In other words, no more than 1 process group can be created globally. +// +// If you would like to use multiple ProcessGroupCGX, it requres your MPI +// implemenation to have a thread support value of MPI_THREAD_MULTIPLE, that is, +// multiple threads may call MPI, with no restriction. +// +// Also note that ProcessGroupCGX only supports a single Tensor operation. In +// other words, the size of the input Tensor vector should always be 1. +// +// CUDA tensor can be supported if the MPI used is CUDA-aware MPI, and +// ProcessGroupCGX will automatically detect this support. +class ProcessGroupCGX : public c10d::ProcessGroup { +public: + class WorkMPI : public c10d::ProcessGroup::Work { + public: + explicit WorkMPI( + std::vector outputTensors, + const char *profilingTitle = nullptr, + const c10::optional> &inputTensors = + c10::nullopt, + std::shared_ptr endEvent = nullptr, + bool compressed = false, + const std::shared_ptr stream = nullptr) + : ProcessGroup::Work(-1, c10d::OpType::UNKNOWN, profilingTitle, + inputTensors), + outputTensors_(std::move(outputTensors)), + future_(c10::make_intrusive( + c10::ListType::create(c10::TensorType::get()))), + endEvent_(endEvent), compressed_(compressed), cgx_stream(stream) {} + + std::vector result() override; + c10::intrusive_ptr getFuture() override; + + void synchronize() override; + + protected: + friend class ProcessGroupCGX; + + private: + void finishWorkMPI(); + void finishWorkMPIError(std::exception_ptr eptr); + unsigned counter_; + std::shared_ptr endEvent_; + bool compressed_; + const std::shared_ptr cgx_stream; + std::vector outputTensors_; + c10::intrusive_ptr future_; + }; + + class AsyncWork : public c10d::ProcessGroup::Work { + public: + AsyncWork(MPI_Request request, std::vector outputTensors, + const char *profilingTitle, + const c10::optional> &inputTensors); + virtual ~AsyncWork(); + + bool isCompleted() override; + + bool isSuccess() const override; + + int sourceRank() const override; + + bool wait(std::chrono::milliseconds timeout = c10d::kUnsetTimeout) override; + + void abort() override; + std::vector result() override; + unsigned counter_; + + protected: + void populateException(); + + private: + const std::vector outputTensors_; + MPI_Request request_; + MPI_Status status_; + }; + + // Constructor will spawn up the worker thread loop + explicit ProcessGroupCGX(int rank, int size, MPI_Comm pgComm); + + virtual ~ProcessGroupCGX(); + + // Abort the MPI program, needs to be called when exception is detected + void abort(); + + const std::string getBackendName() const override { + return std::string(CGX_BACKEND_NAME); + } + + c10::intrusive_ptr broadcast( + std::vector &data, + const c10d::BroadcastOptions &opts = c10d::BroadcastOptions()) override; + + c10::intrusive_ptr allreduce( + std::vector &tensors, + const c10d::AllreduceOptions &opts = c10d::AllreduceOptions()) override; + + c10::intrusive_ptr + allreduce_coalesced(std::vector &tensors, + const c10d::AllreduceCoalescedOptions &opts = + c10d::AllreduceCoalescedOptions()) override; + + c10::intrusive_ptr + reduce(std::vector &tensors, + const c10d::ReduceOptions &opts = c10d::ReduceOptions()) override; + + c10::intrusive_ptr allgather( + std::vector> &outputTensors, + std::vector &inputTensors, + const c10d::AllgatherOptions &opts = c10d::AllgatherOptions()) override; + + c10::intrusive_ptr _allgather_base( + at::Tensor &outputbuffer, at::Tensor &inputbuffer, + const c10d::AllgatherOptions &opts = c10d::AllgatherOptions()) override; + + c10::intrusive_ptr allgather_coalesced( + std::vector> &outputTensorLists, + std::vector &inputTensors, + const c10d::AllgatherOptions &opts = c10d::AllgatherOptions()) override; + + c10::intrusive_ptr + gather(std::vector> &outputTensors, + std::vector &inputTensors, + const c10d::GatherOptions &opts = c10d::GatherOptions()) override; + + c10::intrusive_ptr + scatter(std::vector &outputTensors, + std::vector> &inputTensors, + const c10d::ScatterOptions &opts = c10d::ScatterOptions()) override; + + c10::intrusive_ptr + reduce_scatter(std::vector &outputTensors, + std::vector> &inputTensors, + const c10d::ReduceScatterOptions &opts = + c10d::ReduceScatterOptions()) override; + + c10::intrusive_ptr alltoall_base( + at::Tensor &outputTensor, at::Tensor &inputTensor, + std::vector &outputSplitSizes, + std::vector &inputSplitSizes, + const c10d::AllToAllOptions &opts = c10d::AllToAllOptions()) override; + + c10::intrusive_ptr alltoall( + std::vector &outputTensors, + std::vector &inputTensors, + const c10d::AllToAllOptions &opts = c10d::AllToAllOptions()) override; + + c10::intrusive_ptr + send(std::vector &tensors, int dstRank, int tag) override; + + c10::intrusive_ptr + recv(std::vector &tensors, int srcRank, int tag) override; + + c10::intrusive_ptr + recvAnysource(std::vector &tensor, int tag) override; + + c10::intrusive_ptr + barrier(const c10d::BarrierOptions &opts = c10d::BarrierOptions()) override; + + // Creating a new ProcessGroupCGX, will initiialize MPI if not initialized + static c10::intrusive_ptr + createProcessGroupCGX(const c10::intrusive_ptr &store, int rank, + int size, const std::chrono::duration &timeout); + + static void ProcessGroupCGXConstructor() __attribute__((constructor)) { + py::object module = py::module::import("torch.distributed"); + py::object register_backend = + module.attr("Backend").attr("register_backend"); + register_backend(CGX_BACKEND_NAME, py::cpp_function(createProcessGroupCGX)); + } + + // Support float16 in MPI + static MPI_Datatype float16_type; + +protected: + using WorkType = + std::tuple, c10::intrusive_ptr>; + // Worker thread loop + void runLoop(); + + // Helper function that is called by the destructor + void destroy(); + + c10::intrusive_ptr + enqueue(std::unique_ptr entry, const char *profilingTitle, + const c10::optional> &inputTensors, + bool compressed = false, + const std::shared_ptr stream = nullptr); + + bool stop_; + + std::mutex pgMutex_; + std::thread workerThread_; + + std::queue queue_; + std::condition_variable queueProduceCV_; + std::condition_variable queueConsumeCV_; + + // Global states + static void initMPIOnce(); + static void mpiExit(); + static std::once_flag onceFlagInitMPI; + + static std::mutex pgGlobalMutex_; + static int mpiThreadSupport_; + + MPI_Comm pgComm_; + std::unique_ptr allreduce_operator; + std::unordered_map> streams_; + std::unordered_map> cuda_start_events_; + std::unordered_map> + cuda_end_events_; + unsigned counter_; +}; + +} // namespace cgx diff --git a/src/common/buffer.cc b/src/common/buffer.cc new file mode 100755 index 0000000..32fc332 --- /dev/null +++ b/src/common/buffer.cc @@ -0,0 +1,36 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include "buffer.h" + +namespace cgx { +namespace common { +PersistentBuffer::PersistentBuffer(size_t size) { +// tensor_ = at::empty(size, at::device(at::kCUDA).dtype(at::kByte)); +// tensor_.zero_(); + tensor_ = at::zeros(size, at::device(at::kCUDA).dtype(at::kByte)); +} + +void * PersistentBuffer::RawPointer() const { + return tensor_.data_ptr(); +} + +} // namespace common +} // namespace cgx + diff --git a/src/common/buffer.h b/src/common/buffer.h new file mode 100755 index 0000000..a0ef812 --- /dev/null +++ b/src/common/buffer.h @@ -0,0 +1,35 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once +#include + +namespace cgx { +namespace common { + +struct PersistentBuffer { + PersistentBuffer(size_t size); + void* RawPointer() const; +private: + at::Tensor tensor_; +}; + + +} // namespace common +} // namespace cgx diff --git a/src/common/common.h b/src/common/common.h new file mode 100755 index 0000000..20e2f43 --- /dev/null +++ b/src/common/common.h @@ -0,0 +1,54 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once +#include +#include + +#define FUSION_BUFFER_SIZE_MB "CGX_FUSION_BUFFER_SIZE_MB" +#define COMPRESSION_MINIMAL_SIZE "CGX_COMPRESSION_MINIMAL_SIZE" +#define COMPRESSION_QUANTIZATION_BITS "CGX_COMPRESSION_QUANTIZATION_BITS" +#define COMPRESSION_BUCKET_SIZE "CGX_COMPRESSION_BUCKET_SIZE" +#define COMPRESSION_SKIP_INCOMPLETE_BUCKETS "CGX_COMPRESSION_SKIP_INCOMPLETE_BUCKETS" +#define COMPRESSION_FAKE_RATIO "CGX_COMPRESSION_FAKE_RATIO" +#define INNER_COMMUNICATOR_TYPE "CGX_INNER_COMMUNICATOR_TYPE" +#define INNER_REDUCTION_TYPE "CGX_INNER_REDUCTION_TYPE" +#define CROSS_COMMUNICATOR_TYPE "CGX_CROSS_COMMUNICATOR_TYPE" +#define CROSS_REDUCTION_TYPE "CGX_CROSS_REDUCTION_TYPE" +#define REMOTE_BUF_COMPRESSION "CGX_REMOTE_BUF_COMPRESSION" +#define DEBUG_ALL_TO_ALL_REDUCTION "CGX_DEBUG_ALL_TO_ALL_REDUCTION" +#define DEBUG_DUMMY_COMPRESSION "CGX_DEBUG_DUMMY_COMPRESSION" +#define INTRA_BROADCAST "CGX_INTRA_BROADCAST" +#define INTRA_COMPRESS "CGX_INTRA_COMPRESS" + +const unsigned int FUSION_SIZE_DEFAULT_MB = 64; +const unsigned int MIN_FUSION_SIZE = 2048; + +#define MPI_CHECK(condition) \ + do { \ + int op = condition; \ + if (op != MPI_SUCCESS) { \ + int len; \ + char estring[MPI_MAX_ERROR_STRING]; \ + MPI_Error_string(op, estring, &len); \ + printf("%s on line %i. MPI Error: %s\n", #condition, __LINE__, estring); \ + throw std::runtime_error(std::string(#condition) + " on line " + \ + std::to_string(__LINE__) + " failed: "); \ + } \ + } while (0) diff --git a/src/common/communicator.h b/src/common/communicator.h new file mode 100755 index 0000000..e667e0f --- /dev/null +++ b/src/common/communicator.h @@ -0,0 +1,66 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once +#include "common.h" +#include "gpu_context.h" +#include + +namespace cgx { +namespace common { + +struct Communicator { + enum CommunicatorType { MPI, SHM }; + Communicator(std::shared_ptr gpu_context) + : gpu_context_(gpu_context) {} + virtual void Init(int world_size, void *ctx) = 0; + virtual void ISend(void *buf, size_t buf_size, int peer_rank, + gpuStream_t stream) = 0; + virtual void IRecv(void *buf, size_t buf_size, int peer_rank, + gpuStream_t stream) = 0; + virtual void WaitSend(int rank) = 0; + virtual void WaitRecv(int rank) = 0; + virtual void WaitAllSend() = 0; + virtual void WaitAllRecv() = 0; + + virtual int TestRecv(int rank) = 0; + virtual void Barrier() { MPI_CHECK(MPI_Barrier(comm_)); } + CommunicatorType GetType() { return communicator_type_; } + +protected: + std::shared_ptr gpu_context_; + MPI_Comm comm_; + int rank_; + int world_size_; + CommunicatorType communicator_type_; +}; + +struct CommunicatorLocal : Communicator { + CommunicatorLocal(std::shared_ptr gpu_context) + : Communicator(gpu_context) {} + virtual void *GetRemoteBuftoSend(int peer_rank) = 0; + virtual void *GetRemoteBuftoRecv(int peer_rank) = 0; + virtual void *GetRemoteBroadcastBuftoSend() = 0; + virtual void *GetRemoteBroadcastBuftoRecv(int peer_rank) = 0; + virtual void CommitSend(int peer_rank, gpuStream_t stream) = 0; + virtual int TestRemote(int peer_rank, gpuStream_t stream) = 0; +}; + +} // namespace common +} // namespace cgx \ No newline at end of file diff --git a/src/common/compression/cuda_compression_operations.cu b/src/common/compression/cuda_compression_operations.cu new file mode 100755 index 0000000..00d19ae --- /dev/null +++ b/src/common/compression/cuda_compression_operations.cu @@ -0,0 +1,836 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include "cuda_compression_operations.h" +#include "gpu_common.h" +#include "gpu_fp16_util.h" +#include "gpu_rand.h" + +namespace cgx { +namespace common { +namespace gpu { +#if CUDA_VECTORIZED +const bool VECTORIZE_COMPRESS = true; +const bool VECTORIZE_DECOMPRESS = true; +#else +const bool VECTORIZE_COMPRESS = false; +const bool VECTORIZE_DECOMPRESS = false; +#endif + +const int MAXMIN_META_MULTIPLIER = 2; + +__global__ void _init_rand(unsigned int seed, RandState *states) { + unsigned int index = threadIdx.x + blockIdx.x * blockDim.x; + states[index] = xorshift128_init(seed * index); +} + +__global__ void _float2half(float *input, Half *output, int numel) { + int index = blockIdx.x * blockDim.x + threadIdx.x; + int stride = blockDim.x * gridDim.x; + for (int i = index; i < numel; i += stride) { + output[i] = __float2half(input[i]); + } +} + +__global__ void _half2float(Half *input, float *output, int numel) { + int index = blockIdx.x * blockDim.x + threadIdx.x; + int stride = blockDim.x * gridDim.x; + for (int i = index; i < numel; i += stride) { + output[i] = __half2float(input[i]); + } +} + +template +__global__ void _add(int64_t n, const T *x, const T *y, T *sum_result) { + int index = blockIdx.x * blockDim.x + threadIdx.x; + int stride = blockDim.x * gridDim.x; + for (int i = index; i < n; i += stride) { + sum_result[i] = sum(x[i], y[i]); + } +} + +// Single value quantization functions +template +inline __device__ unsigned char MaxMinEncodeValue(T input, T *feedback, + unsigned char *meta_info, + const float rand) { + T *maxmin = ((T *)meta_info); + const float unit_bucket = type2float(maxmin[0]); + if (unit_bucket < EPS) { + return 0; + } + const float min_bucket = type2float(maxmin[1]); + const float input_f = type2float(input); + const float d = ((input_f - min_bucket) / unit_bucket) + rand; + const unsigned char level = min(floor(d), (1 << BITS) - 1); + if (EF) + *feedback = float2type(input_f - (min_bucket + unit_bucket * level)); + return level; +} + +template +inline __device__ T MaxMinDecodeValue(const unsigned char input, + const unsigned char *meta_info, + const const unsigned int idx, + const int bucket_size) { + const unsigned int bucket_no = idx / bucket_size; + const T *maxmin = ((T *)meta_info) + MAXMIN_META_MULTIPLIER * bucket_no; + const T min = maxmin[1]; + const T unit = maxmin[0]; + return sum(min, mul_int(unit, (int)input)); +} + +template +__device__ void find_meta_parallel(const T *input, T *meta, + const int num_elems) { + unsigned int tid = threadIdx.x; + unsigned int block_size = blockDim.x; + const unsigned int divisor = (1 << BITS) - 1; + extern __shared__ __align__(sizeof(T)) unsigned char my_smem[]; + T *sdata = reinterpret_cast(my_smem); + meta[0] = input[0]; + meta[1] = input[0]; + unsigned int num_iters_per_bucket = (num_elems + block_size - 1) / block_size; + for (int i = 0; i < num_iters_per_bucket; i++) { + unsigned int idx = i * blockDim.x + tid; + if (idx < num_elems) { + sdata[tid] = input[idx]; + sdata[block_size + tid] = input[idx]; + } + __syncthreads(); + + for (unsigned int s = block_size / 2; s > 0; s >>= 1) { + if (tid < s && idx + s < num_elems) { + sdata[tid] = max(sdata[tid + s], sdata[tid]); + sdata[block_size + tid] = + min(sdata[block_size + tid + s], sdata[block_size + tid]); + } + __syncthreads(); + } + + if (tid == 0) { + meta[0] = max(meta[0], sdata[tid]); + meta[1] = min(meta[1], sdata[block_size + tid]); + } + } + if (tid == 0) { + float max = type2float(meta[0]); + float min = type2float(meta[1]); + meta[0] = float2type((max - min) / divisor); + } + __syncthreads(); +} + +template +__global__ void find_meta(const T *input, T *meta, const int num_elems, + const int bucket_size) { + unsigned num_blocks = gridDim.x; + unsigned int bid = blockIdx.x; + unsigned int num_buckets = (num_elems + bucket_size - 1) / bucket_size; + unsigned int cur_bucket_size; + for (unsigned int bucket_id = bid; bucket_id < num_buckets; + bucket_id += num_blocks) { + cur_bucket_size = umin(bucket_size, num_elems - bucket_id * bucket_size); + find_meta_parallel(input + bucket_size * bucket_id, + meta + MAXMIN_META_MULTIPLIER * bucket_id, + cur_bucket_size); + } +} + +template +inline __device__ void pack_value(const uint64_t value, unsigned char *output, + const unsigned int shift = 0) { +#pragma unroll BITS + for (unsigned int j = 0; j < BITS; j++) { + output[j] = value >> (PACK_SIZE * j) & 0xFF; + } +} + +template <> +inline __device__ void pack_value<2>(const uint64_t value, + unsigned char *output, + const unsigned int shift) { + U2 output2; +#pragma unroll 2 + for (unsigned int j = 0; j < 2; j++) { + output2.a[j] = value >> (PACK_SIZE * (j + shift)) & 0xFF; + } + uchar2 *output_p = reinterpret_cast(output); + output_p[0] = output2.vec; +} + +template <> +inline __device__ void pack_value<3>(const uint64_t value, + unsigned char *output, + const unsigned int shift) { + U3 output3; +#pragma unroll 3 + for (unsigned int j = 0; j < 3; j++) { + output3.a[j] = value >> (PACK_SIZE * (j + shift)) & 0xFF; + } + uchar3 *output_p = reinterpret_cast(output); + output_p[0] = output3.vec; +} + +template <> +inline __device__ void pack_value<4>(const uint64_t value, + unsigned char *output, + const unsigned int shift) { + U4 output4; +#pragma unroll 4 + for (unsigned int j = 0; j < 4; j++) { + output4.a[j] = value >> (PACK_SIZE * (j + shift)) & 0xFF; + } + uchar4 *output_p = reinterpret_cast(output); + output_p[0] = output4.vec; +} + +template <> +inline __device__ void pack_value<6>(const uint64_t value, + unsigned char *output, + const unsigned int shift) { + pack_value<3>(value, output, 0); + pack_value<3>(value, output + 3, 3); +} + +template <> +inline __device__ void pack_value<8>(const uint64_t value, + unsigned char *output, + const unsigned int shift) { + pack_value<4>(value, output, 0); + pack_value<4>(value, output + 4, 4); +} + +template +__device__ void CompressBucket(const T *input, unsigned char *output, + T *feedback_data, unsigned char *meta_info, + const int num_elems, RandState *state) { + typename TypeToVectorType::vector_union input_vector; + const unsigned int tid = threadIdx.x; + const unsigned int num_threads = blockDim.x; + float rand = 0.5; + int num_char = (BITS * num_elems + PACK_SIZE - 1) / PACK_SIZE; + T *feedback_ = nullptr; + for (unsigned int i = tid; i < (num_elems + PACK_SIZE - 1) / PACK_SIZE; + i += num_threads) { + uint64_t value = 0; + if (VECTORIZE) { + if (num_elems - i * PACK_SIZE >= PACK_SIZE) { +#pragma unroll + for (unsigned int j = 0; j < PACK_SIZE; + j += TypeToVectorType::num_values) { + int idx = i * PACK_SIZE + j; + input_vector.vec = + (reinterpret_cast::vector_type *>( + const_cast(input + idx)))[0]; +#pragma unroll + for (int k = 0; k < TypeToVectorType::num_values; k++) { + rand = GetRand(state); + if (EF) + feedback_ = feedback_data + idx + k; + uint64_t encoded = MaxMinEncodeValue( + input_vector.a[k], feedback_, meta_info, rand); + value |= (encoded << ((j + k) * BITS)); + } + } + } else { + for (unsigned int j = 0; j < num_elems - i * PACK_SIZE; j++) { + int idx = i * PACK_SIZE + j; + if (EF) + feedback_ = feedback_data + idx; + rand = GetRand(state); + uint64_t encoded = MaxMinEncodeValue( + input[idx], feedback_, meta_info, rand); + value |= (encoded << (j * BITS)); + } + } + if (num_char - i * BITS < BITS) { + for (unsigned int j = 0; j < num_char - i * BITS; j++) { + output[i * BITS + j] = value >> (PACK_SIZE * j) & 0xFF; + } + } else { + pack_value(value, output + i * BITS); + } + } else { + for (unsigned int j = 0; j < PACK_SIZE && i * PACK_SIZE + j < num_elems; + j++) { + int idx = i * PACK_SIZE + j; + if (EF) + feedback_ = feedback_data + idx; + rand = GetRand(state); + uint64_t encoded = MaxMinEncodeValue(input[idx], feedback_, + meta_info, rand); + value |= (encoded << (j * BITS)); + } + for (unsigned int j = 0; j < BITS && i * BITS + j < num_char; j++) { + output[i * BITS + j] = value >> (PACK_SIZE * j) & 0xFF; + } + } + } +} + +template +__global__ void pack_array(const T *input, unsigned char *output_data, + unsigned char *feedback_data, const int num_elems, + const unsigned int bucket_size, RandState *states) { + unsigned int tid = threadIdx.x + blockIdx.x * blockDim.x; + unsigned int num_buckets = (num_elems + bucket_size - 1) / bucket_size; + unsigned char *meta_info = output_data; + unsigned char *output; + output = output_data + MAXMIN_META_MULTIPLIER * sizeof(T) * num_buckets; + + const unsigned int stride = gridDim.x * blockDim.x; + float rand = 0.5; + int bucket_no; + int num_char = (BITS * num_elems + PACK_SIZE - 1) / PACK_SIZE; + T *feedback_; +#if !QSGD_DETERMENISTIC + RandState *state = &states[tid]; +#else + RandState *state = nullptr; +#endif + for (unsigned int i = tid; i < (num_elems + PACK_SIZE - 1) / PACK_SIZE; + i += stride) { + uint64_t value = 0; + if (VECTORIZE) { + typename TypeToVectorType::vector_union input_vector; + if (num_elems - i * PACK_SIZE >= PACK_SIZE) { +#pragma unroll + for (unsigned int j = 0; j < PACK_SIZE; + j += TypeToVectorType::num_values) { + int idx = i * PACK_SIZE + j; + input_vector.vec = + (reinterpret_cast::vector_type *>( + const_cast(input + idx)))[0]; +#pragma unroll + for (int k = 0; k < TypeToVectorType::num_values; k++) { + rand = GetRand(state); + if (EF) + feedback_ = ((T *)feedback_data) + idx + k; + bucket_no = (idx + k) / bucket_size; + uint64_t encoded = MaxMinEncodeValue( + input_vector.a[k], feedback_, + meta_info + MAXMIN_META_MULTIPLIER * sizeof(T) * bucket_no, + rand); + value |= (encoded << ((j + k) * BITS)); + } + } + } else { + for (unsigned int j = 0; j < num_elems - i * PACK_SIZE; j++) { + int idx = i * PACK_SIZE + j; + if (EF) + feedback_ = ((T *)feedback_data) + idx; + rand = GetRand(state); + bucket_no = idx / bucket_size; + uint64_t encoded = MaxMinEncodeValue( + input[idx], feedback_, + meta_info + MAXMIN_META_MULTIPLIER * sizeof(T) * bucket_no, rand); + value |= (encoded << (j * BITS)); + } + } + if (num_char - i * BITS < BITS) { + for (unsigned int j = 0; j < num_char - i * BITS; j++) { + output[i * BITS + j] = value >> (PACK_SIZE * j) & 0xFF; + } + } else { + pack_value(value, output + i * BITS); + } + } else { + for (unsigned int j = 0; j < PACK_SIZE && i * PACK_SIZE + j < num_elems; + j++) { + int idx = i * PACK_SIZE + j; + if (EF) + feedback_ = ((T *)feedback_data) + idx; + rand = GetRand(state); + bucket_no = idx / bucket_size; + uint64_t encoded = MaxMinEncodeValue( + input[idx], feedback_, + meta_info + MAXMIN_META_MULTIPLIER * sizeof(T) * bucket_no, rand); + value |= (encoded << (j * BITS)); + } + for (unsigned int j = 0; j < BITS && i * BITS + j < num_char; j++) { + output[i * BITS + j] = value >> (PACK_SIZE * j) & 0xFF; + } + } + } +} + +template +__global__ void quantize(const unsigned char *input_data, + unsigned char *output_data, + unsigned char *feedback_data, const int num_elems, + const unsigned int bucket_size, RandState *states) { + unsigned num_blocks = gridDim.x; + unsigned int tid = threadIdx.x + blockIdx.x * blockDim.x; + unsigned int bid = blockIdx.x; + unsigned int num_buckets = (num_elems + bucket_size - 1) / bucket_size; + unsigned int cur_bucket_size; + T *meta = (T *)output_data; + unsigned char *output; + output = output_data + MAXMIN_META_MULTIPLIER * sizeof(T) * num_buckets; + + unsigned int compressed_size = + (bucket_size * BITS + PACK_SIZE - 1) / PACK_SIZE; + + T *input = (T *)input_data; + for (unsigned int bucket_id = bid; bucket_id < num_buckets; + bucket_id += num_blocks) { + cur_bucket_size = umin(bucket_size, num_elems - bucket_id * bucket_size); + find_meta_parallel(input + bucket_size * bucket_id, + (meta + MAXMIN_META_MULTIPLIER * bucket_id), + cur_bucket_size); + } + RandState local_state = states[tid]; + for (unsigned int bucket_id = bid; bucket_id < num_buckets; + bucket_id += num_blocks) { + cur_bucket_size = umin(bucket_size, num_elems - bucket_id * bucket_size); + CompressBucket( + input + bucket_size * bucket_id, output + compressed_size * bucket_id, + (T *)feedback_data, + (unsigned char *)(meta + MAXMIN_META_MULTIPLIER * bucket_id), + cur_bucket_size, &local_state); + } + states[tid] = local_state; +} + +template +inline __device__ void unpack_value(const unsigned char *input, uint64_t &value, + const unsigned shift = 0) { + for (unsigned int j = 0; j < BITS; j++) { + value |= ((uint64_t)input[j]) << (j * PACK_SIZE); + } +} + +template <> +inline __device__ void unpack_value<2>(const unsigned char *input, + uint64_t &value, + const unsigned int shift) { + U2 input2; + input2.vec = + reinterpret_cast(const_cast(input))[0]; +#pragma unroll 2 + for (unsigned int j = 0; j < 2; j++) { + value |= ((uint64_t)input2.a[j]) << ((j + shift) * PACK_SIZE); + } +} + +template <> +inline __device__ void unpack_value<3>(const unsigned char *input, + uint64_t &value, + const unsigned int shift) { + U3 input3; + input3.vec = + reinterpret_cast(const_cast(input))[0]; +#pragma unroll 3 + for (unsigned int j = 0; j < 3; j++) { + value |= ((uint64_t)input3.a[j]) << ((j + shift) * PACK_SIZE); + } +} + +template <> +inline __device__ void unpack_value<4>(const unsigned char *input, + uint64_t &value, + const unsigned int shift) { + U4 input4; + input4.vec = + reinterpret_cast(const_cast(input))[0]; +#pragma unroll 4 + for (unsigned int j = 0; j < 4; j++) { + value |= ((uint64_t)input4.a[j]) << ((j + shift) * PACK_SIZE); + } +} + +template <> +inline __device__ void unpack_value<6>(const unsigned char *input, + uint64_t &value, + const unsigned int shift) { + unpack_value<3>(input, value, 0); + unpack_value<3>(input + 3, value, 3); +} + +template <> +inline __device__ void unpack_value<8>(const unsigned char *input, + uint64_t &value, + const unsigned int shift) { + unpack_value<4>(input, value, 0); + unpack_value<4>(input + 4, value, 4); +} + +template +__global__ void UnpackArray(const unsigned char *input, + const unsigned char *meta_info, T *output, + const int num_elems, const int bucket_size) { + unsigned int tid = threadIdx.x + blockIdx.x * blockDim.x; + unsigned int stride = gridDim.x * blockDim.x; + int num_char = (BITS * num_elems + PACK_SIZE - 1) / PACK_SIZE; + const unsigned int divisor = 1 << BITS; + for (unsigned int i = tid; i < (num_elems + PACK_SIZE - 1) / PACK_SIZE; + i += stride) { + uint64_t value = 0; + if (VECTORIZE) { + if ((i + 1) * BITS > num_char) { + for (unsigned int j = 0; j < num_char - i * BITS; j++) + value |= ((uint64_t)input[i * BITS + j]) << (j * PACK_SIZE); + } else { + unpack_value(input + i * BITS, value); + } + + if ((i + 1) * PACK_SIZE > num_elems) { + for (unsigned int j = 0; j < num_elems - i * PACK_SIZE; j++) { + unsigned char encoded_value = (value >> (j * BITS)) & (divisor - 1); + T d = MaxMinDecodeValue(encoded_value, meta_info, + i * PACK_SIZE + j, bucket_size); + if (ADD) { + output[i * PACK_SIZE + j] = sum(output[i * PACK_SIZE + j], d); + } else { + output[i * PACK_SIZE + j] = d; + } + } + } else { + typename TypeToVectorType::vector_union output_union; +#pragma unroll(PACK_SIZE / TypeToVectorType ::num_values) + for (int j = 0; j < PACK_SIZE; j += TypeToVectorType::num_values) { + typename TypeToVectorType::vector_type *output_p = + reinterpret_cast::vector_type *>( + &output[i * PACK_SIZE + j]); + if (ADD) + output_union.vec = *output_p; +#pragma unroll TypeToVectorType < T> ::num_values + for (int k = 0; k < TypeToVectorType::num_values; k++) { + unsigned char encoded_value = + (value >> ((j + k) * BITS)) & (divisor - 1); + T d = MaxMinDecodeValue(encoded_value, meta_info, + i * PACK_SIZE + j + k, bucket_size); + if (ADD) { + output_union.a[k] = sum((T)(output_union.a[k]), d); + } else { + output_union.a[k] = d; + } + } + *output_p = output_union.vec; + } + } + } else { + for (int j = 0; j < BITS && i * BITS + j < num_char; j++) { + value |= ((uint64_t)input[i * BITS + j]) << (j * PACK_SIZE); + } + for (int j = 0; j < PACK_SIZE && i * PACK_SIZE + j < num_elems; j++) { + unsigned char encoded_value = (value >> (j * BITS)) & (divisor - 1); + T d = MaxMinDecodeValue(encoded_value, meta_info, i * PACK_SIZE + j, + bucket_size); + if (ADD) { + output[i * PACK_SIZE + j] = sum(output[i * PACK_SIZE + j], d); + } else { + output[i * PACK_SIZE + j] = d; + } + } + } + } +} + +/*-------------------Host functions------------------------*/ +void CUDA_init_rand(RandState *states, size_t num_elems, unsigned int seed, + cudaStream_t stream) { + _init_rand<<>>(seed, states); +} + +template +void CUDA_add(int n, const T *x, T *y, T *sum, cudaStream_t stream) { + int num_threads = umin(n, MAX_THREADS_PER_BLOCK); + int blocks = BLOCKS_PER_GRID(n, num_threads); + _add<<>>(n, x, y, sum); + CUDA_CHECK(cudaGetLastError()); +} + +void CUDA_half2float(Half *input, float *output, int numel, + cudaStream_t stream) { + _half2float<<>>(input, output, numel); + CUDA_CHECK(cudaStreamSynchronize(stream)); +} + +void CUDA_float2half(float *input, half *output, int numel, + cudaStream_t stream) { + _float2half<<>>(input, output, numel); + CUDA_CHECK(cudaStreamSynchronize(stream)); +} + +// Difference between two alternatives QUANTIZE and QUANTIZE2 is that +// in QUANTIZE we only call 1 kernel in which we compute meta and pack values +// for each bucket. It means we use less blocks for packing than we could +// in QUANTIZE2 we first find all meta information in one kernel, +// then pack in the separate one. +template +inline void QUANTIZE2(const unsigned char *input_data, + unsigned char *output_data, unsigned char *feedback_data, + int num_elems, int bucket_size, RandState *states, + cudaStream_t stream) { + int num_blocks = + umin((num_elems + bucket_size - 1) / bucket_size, MAX_NUMBER_OF_BLOCKS); + int num_threads = umin(THREADS_PER_BLOCK_COMPRESS, bucket_size); + int shared_memory_block_size = + MAXMIN_META_MULTIPLIER * num_threads * sizeof(T); + unsigned int num_buckets = (num_elems + bucket_size - 1) / bucket_size; + const T *input = reinterpret_cast(input_data); + T *meta_info = reinterpret_cast(output_data); + find_meta + <<>>( + input, meta_info, num_elems, bucket_size); + + num_threads = THREADS_PER_BLOCK_COMPRESS; + num_blocks = BLOCKS_PER_GRID(num_elems / PACK_SIZE, num_threads); + pack_array<<>>( + input, output_data, feedback_data, num_elems, bucket_size, states); +} + +template +inline void QUANTIZE1(const unsigned char *input_data, + unsigned char *output_data, unsigned char *feedback_data, + int num_elems, int bits, int bucket_size, + RandState *states, cudaStream_t stream) { + switch (bits) { + case 1: + QUANTIZE2(input_data, output_data, feedback_data, + num_elems, bucket_size, states, stream); + break; + case 2: + QUANTIZE2(input_data, output_data, feedback_data, + num_elems, bucket_size, states, stream); + break; + case 3: + QUANTIZE2(input_data, output_data, feedback_data, + num_elems, bucket_size, states, stream); + break; + case 4: + QUANTIZE2(input_data, output_data, feedback_data, + num_elems, bucket_size, states, stream); + break; + case 5: + QUANTIZE2(input_data, output_data, feedback_data, + num_elems, bucket_size, states, stream); + break; + case 6: + QUANTIZE2(input_data, output_data, feedback_data, + num_elems, bucket_size, states, stream); + break; + case 7: + QUANTIZE2(input_data, output_data, feedback_data, + num_elems, bucket_size, states, stream); + break; + case 8: + QUANTIZE2(input_data, output_data, feedback_data, + num_elems, bucket_size, states, stream); + break; + default: + printf("Wrong number of bits %i!!!\n", bits); + } + CUDA_CHECK(cudaGetLastError()); +} + +template +inline void QUANTIZE(const unsigned char *input_data, + unsigned char *output_data, unsigned char *feedback_data, + int num_elems, int bits, int bucket_size, + RandState *states, cudaStream_t stream) { + int num_blocks = + umin((num_elems + bucket_size - 1) / bucket_size, MAX_NUMBER_OF_BLOCKS); + int num_threads = umin(THREADS_PER_BLOCK_COMPRESS, bucket_size); + int shared_memory_block_size = + MAXMIN_META_MULTIPLIER * MAX_THREADS_PER_BLOCK * sizeof(T); + switch (bits) { + case 1: + quantize + <<>>( + input_data, output_data, feedback_data, num_elems, bucket_size, + states); + break; + case 2: + quantize + <<>>( + input_data, output_data, feedback_data, num_elems, bucket_size, + states); + break; + case 3: + quantize + <<>>( + input_data, output_data, feedback_data, num_elems, bucket_size, + states); + break; + case 4: + quantize + <<>>( + input_data, output_data, feedback_data, num_elems, bucket_size, + states); + break; + case 5: + quantize + <<>>( + input_data, output_data, feedback_data, num_elems, bucket_size, + states); + break; + case 6: + quantize + <<>>( + input_data, output_data, feedback_data, num_elems, bucket_size, + states); + break; + case 7: + quantize + <<>>( + input_data, output_data, feedback_data, num_elems, bucket_size, + states); + break; + case 8: + quantize + <<>>( + input_data, output_data, feedback_data, num_elems, bucket_size, + states); + break; + default: + printf("Wrong number of bits %i!!!\n", bits); + } + CUDA_CHECK(cudaGetLastError()); +} + +// get_curand_array_size assumes that compressed will be done with maximum +// THREADS_PER_BLOCK_COMPRESS threads. +template +void CUDA_quantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + unsigned char *feedback_data, int num_elems, int bits, + int bucket_size, RandState *states, + cudaStream_t stream) { + // if the buffer is not aligned for vectorized, fallback to non-vectorized + if (VECTORIZE_COMPRESS and (((unsigned long)input_data & 15) == 0)) + QUANTIZE1(input_data, output_data, feedback_data, num_elems, + bits, bucket_size, states, stream); + else + QUANTIZE1(input_data, output_data, feedback_data, + num_elems, bits, bucket_size, states, stream); +} + +template +inline void DEQUANTIZE(const unsigned char *input, + const unsigned char *meta_info, T *output, int num_elems, + int bucket_size, int bits, cudaStream_t stream, + int num_blocks, int num_threads) { + switch (bits) { + case 1: + UnpackArray<<>>( + input, meta_info, output, num_elems, bucket_size); + break; + case 2: + UnpackArray<<>>( + input, meta_info, output, num_elems, bucket_size); + break; + case 3: + UnpackArray<<>>( + input, meta_info, output, num_elems, bucket_size); + break; + case 4: + UnpackArray<<>>( + input, meta_info, output, num_elems, bucket_size); + break; + case 5: + UnpackArray<<>>( + input, meta_info, output, num_elems, bucket_size); + break; + case 6: + UnpackArray<<>>( + input, meta_info, output, num_elems, bucket_size); + break; + case 7: + UnpackArray<<>>( + input, meta_info, output, num_elems, bucket_size); + break; + case 8: + UnpackArray<<>>( + input, meta_info, output, num_elems, bucket_size); + break; + default: + printf("Wrong number of bits %i!!!\n", bits); + } + CUDA_CHECK(cudaGetLastError()); +} + +template +void DEQUANTIZE1(const unsigned char *input, const unsigned char *meta_info, + T *output, int num_elems, int bucket_size, int bits, + cudaStream_t stream, int num_blocks, int num_threads) { + // if the buffer is not aligned for vectorized, fallback to non-vectorized + if (VECTORIZE_DECOMPRESS and (((unsigned long)output & 15) == 0)) + DEQUANTIZE(input, meta_info, output, num_elems, bucket_size, + bits, stream, num_blocks, num_threads); + else + DEQUANTIZE(input, meta_info, output, num_elems, bucket_size, + bits, stream, num_blocks, num_threads); +} + +template +void CUDA_dequantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, int num_elems, int bits, + int bucket_size, cudaStream_t stream) { + T *output = (T *)output_data; + const unsigned char *meta_info = input_data; + int num_buckets = (num_elems + bucket_size - 1) / bucket_size; + const unsigned char *input = + input_data + MAXMIN_META_MULTIPLIER * sizeof(T) * num_buckets; + int num_threads = THREADS_PER_BLOCK_DECOMPRESS; + int num_blocks = + BLOCKS_PER_GRID((num_elems + PACK_SIZE - 1) / PACK_SIZE, num_threads); +// DEQUANTIZE1(input, meta_info, output, num_elems, bucket_size, bits, +// stream, num_blocks, num_threads); +} + +/* Functions declarations */ +template void CUDA_add(int n, const float *x, float *y, float *sum, + cudaStream_t stream); +template void CUDA_add(int n, const Half *x, Half *y, Half *sum, + cudaStream_t stream); + +template void CUDA_quantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + unsigned char *feedback_data, + int num_elems, int bits, + int bucket_size, RandState *states, + cudaStream_t stream); +template void CUDA_quantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + unsigned char *feedback_data, + int num_elems, int bits, + int bucket_size, RandState *states, + cudaStream_t stream); + +template void CUDA_dequantize_maxmin( + const unsigned char *input_data, unsigned char *output_data, int num_elems, + int bits, int bucket_size, cudaStream_t stream); +template void CUDA_dequantize_maxmin( + const unsigned char *input_data, unsigned char *output_data, int num_elems, + int bits, int bucket_size, cudaStream_t stream); + +template void CUDA_dequantize_maxmin( + const unsigned char *input_data, unsigned char *output_data, int num_elems, + int bits, int bucket_size, cudaStream_t stream); +template void CUDA_dequantize_maxmin( + const unsigned char *input_data, unsigned char *output_data, int num_elems, + int bits, int bucket_size, cudaStream_t stream); + +} // namespace gpu +} // namespace common +} // namespace cgx diff --git a/src/common/compression/cuda_compression_operations.h b/src/common/compression/cuda_compression_operations.h new file mode 100755 index 0000000..aaab508 --- /dev/null +++ b/src/common/compression/cuda_compression_operations.h @@ -0,0 +1,56 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once +#include "gpu_compression_operations.h" + +namespace cgx { +namespace common { +namespace gpu { +template +void CUDA_quantize_maxmin(const unsigned char *input_data, unsigned char *output_data, + unsigned char *feedback_data, + int num_elems, int bits, int bucket_size, + RandState *states, cudaStream_t stream); + +template +void CUDA_dequantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + int num_elems, int bits, int bucket_size, + cudaStream_t stream); + +template +void CUDA_add(int n, const T *x, T *y, T *sum, cudaStream_t stream); + +void CUDA_init_rand(RandState *states, size_t num_elems, unsigned int seed, + cudaStream_t stream); + +void CUDA_half2float(Half *input, + float *output, + int numel, + cudaStream_t stream); + +void CUDA_float2half(float *input, + Half *output, + int numel, + cudaStream_t stream); + +} // namespace gpu +} // namespace common +} // namespace cgx \ No newline at end of file diff --git a/src/common/compression/gpu_common.h b/src/common/compression/gpu_common.h new file mode 100755 index 0000000..c09dc4c --- /dev/null +++ b/src/common/compression/gpu_common.h @@ -0,0 +1,51 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once +#include + +#if HAVE_CUDA +#define CUDA_CHECK(condition) \ +do { \ + cudaError_t cuda_result = condition; \ + if (cuda_result != cudaSuccess) { \ + printf("%s on line %i in %s returned: %s(code:%i)\n", #condition, \ + __LINE__, __FILE__, cudaGetErrorString(cuda_result), \ + cuda_result); \ + throw std::runtime_error( \ + std::string(#condition) + " in file " + __FILE__ \ + + " on line " + std::to_string(__LINE__) + \ + " returned: " + cudaGetErrorString(cuda_result)); \ + } \ +} while (0) +#elif HAVE_ROCM +#define HIP_CHECK(condition) \ +do { \ + hipError_t hip_result = condition; \ + if (hip_result != hipSuccess) { \ + printf("%s on line %i in %s returned: %s(code:%i)\n", #condition, \ + __LINE__, __FILE__, hipGetErrorString(hip_result), \ + hip_result); \ + throw std::runtime_error( \ + std::string(#condition) + " in file " + __FILE__ \ + + " on line " + std::to_string(__LINE__) + \ + " returned: " + hipGetErrorString(hip_result)); \ + } \ +} while (0) +#endif \ No newline at end of file diff --git a/src/common/compression/gpu_compression_operations.cc b/src/common/compression/gpu_compression_operations.cc new file mode 100755 index 0000000..f1fdc3b --- /dev/null +++ b/src/common/compression/gpu_compression_operations.cc @@ -0,0 +1,161 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include "gpu_compression_operations.h" + +#if HAVE_CUDA +#include "cuda_compression_operations.h" +#elif HAVE_ROCM +#include "hip_compression_operations.h" +#endif +namespace cgx { +namespace common { +namespace gpu { + +size_t get_curand_array_size(int num_elems) { + return BLOCKS_PER_GRID(num_elems, MAX_THREADS_PER_BLOCK) + * MAX_THREADS_PER_BLOCK * + sizeof(RandState); +} + +template +void quantize_maxmin(const unsigned char *input_data, unsigned char *output_data, + unsigned char *feedback_data, + int num_elems, int bits, + int bucket_size, RandState *states, + gpuStream_t stream) { +#if HAVE_CUDA + CUDA_quantize_maxmin(input_data, output_data, feedback_data, + num_elems, bits, bucket_size, states, stream); +#elif HAVE_ROCM + HIP_quantize_maxmin(input_data, output_data, feedback_data, num_elems, bits, + bucket_size, states, stream); +#endif +} + +template +void dequantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + int num_elems, int bits, + int bucket_size, gpuStream_t stream) { +#if HAVE_CUDA + CUDA_dequantize_maxmin(input_data, output_data, num_elems, + bits, bucket_size, stream); +#elif HAVE_ROCM + HIP_dequantize_maxmin(input_data, output_data, num_elems, bits, + bucket_size, stream); +#endif +} + +template +void add(int n, const T *x, T *y, T *sum, gpuStream_t stream) { +#if HAVE_CUDA + CUDA_add(n, x, y, sum, stream); +#elif HAVE_ROCM + HIP_add(n, x, y, sum, stream); +#endif +} + +void init_rand_states(RandState *states, size_t num_elems, unsigned int seed, + gpuStream_t stream) { +#if HAVE_CUDA + CUDA_init_rand(states, num_elems, seed, stream); +#elif HAVE_ROCM + HIP_init_rand(states, num_elems, seed, stream); +#endif +} + +void half2float(Half *input, float *output, int numel, gpuStream_t stream) { +#if HAVE_CUDA + CUDA_half2float(input, output, numel, stream); +#elif HAVE_ROCM +#endif +} + +void float2half(float *input, Half *output, int numel, gpuStream_t stream) { +#if HAVE_CUDA + CUDA_float2half(input, output, numel, stream); +#elif HAVE_ROCM +#endif +} + +/* Template declarations */ +template void quantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + unsigned char *feedback_data, + int num_elems, + int bits, + int bucket_size, + RandState *states, + gpuStream_t stream); + +template void quantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + unsigned char *feedback_data, + int num_elems, + int bits, + int bucket_size, + RandState *states, + gpuStream_t stream); + +template +void dequantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + int num_elems, + int bits, + int bucket_size, + gpuStream_t stream); + +template +void dequantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + int num_elems, + int bits, + int bucket_size, + gpuStream_t stream); + +template +void dequantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + int num_elems, + int bits, + int bucket_size, + gpuStream_t stream); + +template +void dequantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + int num_elems, + int bits, + int bucket_size, + gpuStream_t stream); + +template +void add(int n, + const float *x, + float *y, + float *sum, + gpuStream_t stream); + +template +void add(int n, const Half *x, Half *y, Half *sum, gpuStream_t stream); + +} // namespace gpu +} // namespace common +} // namespace cgx diff --git a/src/common/compression/gpu_compression_operations.h b/src/common/compression/gpu_compression_operations.h new file mode 100755 index 0000000..c4df33c --- /dev/null +++ b/src/common/compression/gpu_compression_operations.h @@ -0,0 +1,72 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once +#ifdef HAVE_CUDA +#include +#include +#include +#elif HAVE_ROCM +#include +#include +#endif + +#include "../gpu_context.h" +#include "gpu_def.h" + +namespace cgx { +namespace common { +namespace gpu { + +constexpr int MIN(int a, int b) { return (a > b) ? b : a; } + +constexpr int BLOCKS_PER_GRID(int num_elems, int threads_per_block) { + threads_per_block = (threads_per_block > 0) ? threads_per_block: 1; + return MIN((num_elems + (threads_per_block - 1)) / threads_per_block, + MAX_NUMBER_OF_BLOCKS); +} + +template +void quantize_maxmin(const unsigned char *input_data, unsigned char *output_data, + unsigned char *feedback_data, + int num_elems, int bits, + int bucket_size, RandState *states, + gpuStream_t stream); + +template +void dequantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + int num_elems, int bits, + int bucket_size, gpuStream_t stream); + +void init_rand_states(RandState* states, size_t num_elems, unsigned int seed, + gpuStream_t stream); +template +void add(int n, const T* x, T* y, T* sum, gpuStream_t stream); + +void half2float(Half* input, float* output, int numel, gpuStream_t stream); + +void float2half(float* input, Half* output, int numel, gpuStream_t stream); + + +size_t get_curand_array_size(int num_elems); + +} // namespace gpu +} // namespace common +} // namespace cgx \ No newline at end of file diff --git a/src/common/compression/gpu_def.h b/src/common/compression/gpu_def.h new file mode 100755 index 0000000..e2e0472 --- /dev/null +++ b/src/common/compression/gpu_def.h @@ -0,0 +1,92 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once +namespace cgx { +namespace common { +namespace gpu { +using uint64_t = unsigned long long int; + +struct xorshift128p_state { + uint64_t a, b; +}; + +using Half = __half; +using RandState = cgx::common::gpu::xorshift128p_state; + +const float EPS = 1e-10; +const int PACK_SIZE = 8; +const int MAX_THREADS_PER_BLOCK = 1024; +const int THREADS_PER_BLOCK_DECOMPRESS = MAX_THREADS_PER_BLOCK; +const int THREADS_PER_BLOCK_COMPRESS = 64; +const int MAX_NUMBER_OF_BLOCKS = 65535; +const int WARP_SIZE = 32; + +typedef union { + uchar2 vec; + unsigned char a[2]; +} U2; + +typedef union { + uchar3 vec; + unsigned char a[3]; +} U3; + +typedef union { + uchar4 vec; + unsigned char a[4]; +} U4; + +typedef struct __align__(16) { +half2 x; +half2 y; +half2 z; +half2 w; +} half8; + +typedef union { + half8 vec; + Half a[8]; +} H8; + +typedef union { + float4 vec; + float a[4]; +} F4; + +template +struct TypeToVectorType; + +template<> +struct TypeToVectorType { + typedef F4 vector_union; + typedef float4 vector_type; + static const int num_values = 4; +}; + +template<> +struct TypeToVectorType { + typedef H8 vector_union; + typedef half8 vector_type; + static const int num_values = 8; +}; + +} // namespace gpu +} // namespace common +} // namespace cgx \ No newline at end of file diff --git a/src/common/compression/gpu_fp16_util.h b/src/common/compression/gpu_fp16_util.h new file mode 100755 index 0000000..caed54c --- /dev/null +++ b/src/common/compression/gpu_fp16_util.h @@ -0,0 +1,231 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once + +#if HAVE_CUDA +#include +#elif HAVE_ROCM +#include +#endif + +namespace cgx { +namespace common { +namespace gpu { + + +__device__ __half hmax(__half a, __half b) { return __hge(a, b) ? a : b; } + +__device__ __half hmin(__half a, __half b) { return __hge(a, b) ? b : a; } + +__device__ __half habs(__half a) { + return hmax(a, __hneg(a)); +} + +template +__device__ inline T max(T a, T b) { + return fmaxf(a, b); +} + +template <> +__device__ inline __half max(__half a, __half b) { + return hmax(a, b); +} + +template +__device__ inline T min(T a, T b) { + return fminf(a, b); +} + +template <> +__device__ inline __half min(__half a, __half b) { + return hmin(a, b); +} + +template +__device__ inline T sum(T a, T b) { + return a + b; +} + +template <> +__device__ inline __half sum(__half a, __half b) { + return __hadd(a, b); +} + +template +__device__ inline T sub(T a, T b) { + return a - b; +} + +template <> +__device__ inline __half sub(__half a, __half b) { + return __hsub(a, b); +} + +template +__device__ inline T mul(T a, T b) { + return a * b; +} + +template <> +__device__ inline __half mul(__half a, __half b) { + return __hmul(a, b); +} + +template +__device__ inline T div(T a, T b) { + return a / b; +} + +template <> +__device__ inline __half div(__half a, __half b) { + return __hdiv(a, b); +} + +template +__device__ inline T mul_int(T a, int b) { + return a * b; +} + +template <> +__device__ inline __half mul_int(__half a, int b) { + return __hmul(a, __uint2half_rd(b)); +} + +template +__device__ inline T div_int(T a, unsigned int b) { + return a / b; +} + +template <> +__device__ inline __half div_int(__half a, unsigned int b) { + return __hdiv(a, __uint2half_rd(b)); +} + +template +__device__ inline T add_float(T a, float b) { + return a + b; +} + +template <> +__device__ inline __half add_float(__half a, float b) { + return __hadd(a, __float2half(b)); +} + +template +__device__ inline T mul_float(T a, float b) { + return a * b; +} + +template <> +__device__ inline __half mul_float(__half a, float b) { + return __hmul(a, __float2half(b)); +} + +template +__device__ inline T abs(T a) { + return fabsf(a); +} + +template <> +__device__ inline __half abs(__half a) { + return habs(a); +} + +template +__device__ inline T sqrt(T a) { + return ::sqrt(a); +} + +template <> +__device__ inline __half sqrt(__half a) { + return hsqrt(a); +} + +template +__device__ inline int floor(T a) { + return ::floor(a); +} + +template <> +__device__ inline int floor(__half a) { + return __half2uint_rd(hfloor(a)); +} + +template +__device__ inline bool lt(T a, T b) { + return a < b; +} + +template <> +__device__ inline bool lt(__half a, __half b) { + return __hlt(a, b); +} + +template +__device__ inline bool le(T a, T b) { + return a <= b; +} + +template <> +__device__ inline bool le(__half a, __half b) { + return __hle(a, b); +} + +template +__device__ inline T float2type(float a) { + return (T) a; +} + +template <> +__device__ inline __half float2type(float a) { + return __float2half(a); +} + +template +__device__ inline float type2float(T a) { + return (float) a; +} + +template <> +__device__ inline float type2float(__half a) { + return __half2float(a); +} + +template +__device__ inline bool isnan(T a) { + return ::isnan(a); +} + +template <> +__device__ inline bool isnan(__half a) { + return __hisnan(a); +} + +__global__ void float2half(float* input, __half* output, int numel) { + int index = blockIdx.x * blockDim.x + threadIdx.x; + int stride = blockDim.x * gridDim.x; + for (int i = index; i < numel; i += stride) { + output[i] = __float2half(input[i]); + } +} + +} // namespace cuda +} // namespace common +} // namespace cgx diff --git a/src/common/compression/gpu_rand.h b/src/common/compression/gpu_rand.h new file mode 100755 index 0000000..bc2c77f --- /dev/null +++ b/src/common/compression/gpu_rand.h @@ -0,0 +1,65 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +namespace cgx { +namespace common { +namespace gpu { + +inline __device__ uint64_t splitmix64(uint64_t* seed) { + uint64_t result = *seed; + + *seed = result + 0x9E3779B97f4A7C15; + result = (result ^ (result >> 30)) * 0xBF58476D1CE4E5B9; + result = (result ^ (result >> 27)) * 0x94D049BB133111EB; + return result ^ (result >> 31); +} + +inline __device__ xorshift128p_state xorshift128_init(uint64_t seed) { + xorshift128p_state result; + uint64_t tmp = splitmix64(&seed); + result.a = tmp; + tmp = splitmix64(&seed); + result.b = tmp; + return result; +} + + +inline __device__ float xorshift128p(xorshift128p_state* state) { + uint64_t t = state->a; + uint64_t s = state->b; + state->a = s; + t ^= t << 23; // a + t ^= t >> 17; // b + t ^= s ^ (s >> 26); // c + state->b = t; + return (t + s) * 1.0; +} + +__device__ float GetRand(RandState* state_p) { +#if QSGD_DETERMENISTIC + return 0.5; +#else + return ((float)xorshift128p(state_p)) / UINT64_MAX; +#endif +} + + +} // namespace gpu +} // namespace common +} // namespace cgx \ No newline at end of file diff --git a/src/common/compression/hip_compression_operations.cc b/src/common/compression/hip_compression_operations.cc new file mode 100755 index 0000000..089bae6 --- /dev/null +++ b/src/common/compression/hip_compression_operations.cc @@ -0,0 +1,625 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include "hip_compression_operations.h" +#include "gpu_fp16_util.h" +#include "gpu_rand.h" +#include "hip/hip_runtime.h" + +#define HIP_CHECK(cmd) \ + do { \ + hipError_t error = cmd; \ + if (error != hipSuccess) { \ + fprintf(stderr, "error: '%s'(%d) at %s:%d\n", hipGetErrorString(error), \ + error, __FILE__, __LINE__); \ + throw std::runtime_error(std::string(#cmd) + " on line " + \ + std::to_string(__LINE__) + \ + " returned: " + hipGetErrorString(error)); \ + } \ + } while (0) + +namespace cgx { +namespace common { +namespace gpu { +const bool VECTORIZE_COMPRESS = false; +const bool VECTORIZE_DECOMPRESS = false; + +__global__ void _init_rand(unsigned int seed, RandState *states) { + unsigned int index = hipThreadIdx_x + hipBlockIdx_x * hipBlockDim_x; + states[index] = xorshift128_init(seed * index); +} + +template +__global__ void _add(int64_t n, const T *x, const T *y, T *sum_result) { + int index = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; + int stride = hipBlockDim_x * gridDim.x; + for (int i = index; i < n; i += stride) { + sum_result[i] = sum(x[i], y[i]); + } +} + +// Single value quantization functions +template +inline __device__ unsigned char +MaxMinEncodeValue(const T input, T *feedback, unsigned char *meta_info, float rand) { + T *maxmin = ((T *)meta_info); + float min = type2float(maxmin[1]); + float unit = type2float(maxmin[0]); + if (unit < EPS) { + return 0; + } + float input_f = type2float(input); + float d = ((input_f - min) / unit) + rand; + unsigned char level = floor(d); + if (EF) + *feedback = float2type(input_f - (min + unit * level)); + return level; +} + +template +inline __device__ T MaxMinDecodeValue(const unsigned char input, + const unsigned char *meta_info, + const unsigned int idx, + const int bucket_size) { + const unsigned int bucket_no = idx / bucket_size; + const T *maxmin = ((T *)meta_info) + 2 * bucket_no; + T min = maxmin[1]; + T unit = maxmin[0]; + return sum(min, mul_int(unit, (int)input)); +} + +template +__device__ void find_meta_parallel(const T *input, unsigned char *meta, + int num_elems) { + unsigned int tid = hipThreadIdx_x; + unsigned int block_size = hipBlockDim_x; + T *meta_buf = (T *)meta; + const unsigned int divisor = (1 << BITS) - 1; + extern __shared__ __align__(sizeof(T)) unsigned char my_smem[]; + T *sdata = reinterpret_cast(my_smem); + meta_buf[0] = input[0]; + meta_buf[1] = input[0]; + unsigned int num_iters_per_bucket = (num_elems + block_size - 1) / block_size; + for (int i = 0; i < num_iters_per_bucket; i++) { + unsigned int idx = i * hipBlockDim_x + tid; + if (idx < num_elems) { + sdata[tid] = input[idx]; + sdata[block_size + tid] = input[idx]; + } + __syncthreads(); + + for (unsigned int s = block_size / 2; s > 0; s >>= 1) { + if (tid < s && idx + s < num_elems) { + sdata[tid] = max(sdata[tid + s], sdata[tid]); + sdata[block_size + tid] = + min(sdata[block_size + tid + s], sdata[block_size + tid]); + } + __syncthreads(); + } + + if (tid == 0) { + meta_buf[0] = max(meta_buf[0], sdata[tid]); + meta_buf[1] = min(meta_buf[1], sdata[block_size + tid]); + } + } + if (tid == 0) { + float max = type2float(meta_buf[0]); + float min = type2float(meta_buf[1]); + meta_buf[0] = float2type((max - min) / divisor); + } + __syncthreads(); +} + +template +inline __device__ void pack_value(const uint64_t value, unsigned char *output, + unsigned int shift = 0) { +#pragma unroll BITS + for (unsigned int j = 0; j < BITS; j++) { + output[j] = value >> (PACK_SIZE * j) & 0xFF; + } +} + +template <> +inline __device__ void +pack_value<2>(const uint64_t value, unsigned char *output, unsigned int shift) { + U2 output2; +#pragma unroll 2 + for (unsigned int j = 0; j < 2; j++) { + output2.a[j] = value >> (PACK_SIZE * (j + shift)) & 0xFF; + } + uchar2 *output_p = reinterpret_cast(output); + output_p[0] = output2.vec; +} + +template <> +inline __device__ void +pack_value<3>(const uint64_t value, unsigned char *output, unsigned int shift) { + U3 output3; +#pragma unroll 3 + for (unsigned int j = 0; j < 3; j++) { + output3.a[j] = value >> (PACK_SIZE * (j + shift)) & 0xFF; + } + uchar3 *output_p = reinterpret_cast(output); + output_p[0] = output3.vec; +} + +template <> +inline __device__ void +pack_value<4>(const uint64_t value, unsigned char *output, unsigned int shift) { + U4 output4; +#pragma unroll 4 + for (unsigned int j = 0; j < 4; j++) { + output4.a[j] = value >> (PACK_SIZE * (j + shift)) & 0xFF; + } + uchar4 *output_p = reinterpret_cast(output); + output_p[0] = output4.vec; +} + +template <> +inline __device__ void +pack_value<6>(const uint64_t value, unsigned char *output, unsigned int shift) { + pack_value<3>(value, output, 0); + pack_value<3>(value, output + 3, 3); +} + +template <> +inline __device__ void +pack_value<8>(const uint64_t value, unsigned char *output, unsigned int shift) { + pack_value<4>(value, output, 0); + pack_value<4>(value, output + 4, 4); +} + +template +__device__ void CompressBucket(const T *input, unsigned char *output, + T *feedback_data, unsigned char *meta_info, + int num_elems, RandState *state) { + unsigned int tid = hipThreadIdx_x; + unsigned int num_threads = hipBlockDim_x; + float rand; + int num_char = (BITS * num_elems + PACK_SIZE - 1) / PACK_SIZE; + T *feedback_ = nullptr; + for (unsigned int i = tid; i < (num_elems + PACK_SIZE - 1) / PACK_SIZE; + i += num_threads) { + uint64_t value = 0; + if (VECTORIZE_COMPRESS) { + typename TypeToVectorType::vector_union input_vector; + if (num_elems - i * PACK_SIZE >= PACK_SIZE) { +#pragma unroll + for (unsigned int j = 0; j < PACK_SIZE; + j += TypeToVectorType::num_values) { + int idx = i * PACK_SIZE + j; + input_vector.vec = + (reinterpret_cast::vector_type *>( + const_cast(input + idx)))[0]; +#pragma unroll + for (int k = 0; k < TypeToVectorType::num_values; k++) { + rand = GetRand(state); + if (EF) + feedback_ = feedback_data + idx + k; + uint64_t encoded = MaxMinEncodeValue( + input_vector.a[k], feedback_, meta_info, rand); + value += (encoded << ((j + k) * BITS)); + } + } + } else { + for (unsigned int j = 0; j < num_elems - i * PACK_SIZE; j++) { + int idx = i * PACK_SIZE + j; + if (EF) + feedback_ = feedback_data + idx; + rand = GetRand(state); + unsigned encoded = + MaxMinEncodeValue(input[idx], feedback_, meta_info, rand); + value += (encoded << (j * BITS)); + } + } + if (num_char - i * BITS < BITS) { + for (unsigned int j = 0; j < num_char - i * BITS; j++) { + output[i * BITS + j] = value >> (PACK_SIZE * j) & 0xFF; + } + } else { + pack_value(value, output + i * BITS); + } + } else { + for (unsigned int j = 0; j < PACK_SIZE && i * PACK_SIZE + j < num_elems; + j++) { + int idx = i * PACK_SIZE + j; + if (EF) + feedback_ = feedback_data + idx; + rand = GetRand(state); + uint64_t encoded = + MaxMinEncodeValue(input[idx], feedback_, meta_info, rand); + value += (encoded << (j * BITS)); + } + for (unsigned int j = 0; j < BITS && i * BITS + j < num_char; j++) { + output[i * BITS + j] = value >> (PACK_SIZE * j) & 0xFF; + } + } + } +} + +template +__global__ void quantize(const unsigned char *input_data, + unsigned char *output_data, + unsigned char *feedback_data, int num_elems, + int bucket_size, RandState *states) { + unsigned num_blocks = gridDim.x; + unsigned int tid = hipThreadIdx_x + hipBlockIdx_x * hipBlockDim_x; + unsigned int bid = hipBlockIdx_x; + unsigned int num_buckets = (num_elems + bucket_size - 1) / bucket_size; + unsigned int cur_bucket_size; + T *meta = (T *)output_data; + unsigned char *output; + const int META_MULTIPLIER = 2; + output = output_data + META_MULTIPLIER * sizeof(T) * num_buckets; + + unsigned int compressed_size = + (bucket_size * BITS + PACK_SIZE - 1) / PACK_SIZE; + + T *input = (T *)input_data; + for (int bucket_id = bid; bucket_id < num_buckets; bucket_id += num_blocks) { + cur_bucket_size = umin(bucket_size, num_elems - bucket_id * bucket_size); + find_meta_parallel( + input + bucket_size * bucket_id, + (unsigned char *)(meta + META_MULTIPLIER * bucket_id), cur_bucket_size); + } + RandState local_state = states[tid]; + for (int bucket_id = bid; bucket_id < num_buckets; bucket_id += num_blocks) { + cur_bucket_size = umin(bucket_size, num_elems - bucket_id * bucket_size); + CompressBucket( + input + bucket_size * bucket_id, output + compressed_size * bucket_id, + (T *)feedback_data, + (unsigned char *)(meta + META_MULTIPLIER * bucket_id), cur_bucket_size, + &local_state); + } + states[tid] = local_state; +} + +template +inline __device__ void unpack_value(const unsigned char *input, uint64_t &value, + const unsigned shift = 0) { + for (unsigned int j = 0; j < BITS; j++) { + value |= ((uint64_t)input[j]) << (j * PACK_SIZE); + } +} + +template <> +inline __device__ void unpack_value<2>(const unsigned char *input, uint64_t &value, + const unsigned int shift) { + U2 input2; + input2.vec = reinterpret_cast(const_cast(input))[0]; +#pragma unroll 3 + for (unsigned int j = 0; j < 2; j++) { + value |= ((uint64_t)input2.a[j]) << ((j + shift) * PACK_SIZE); + } +} + +template <> +inline __device__ void unpack_value<3>(cosnt unsigned char *input, uint64_t &value, + const unsigned int shift) { + U3 input3; + input3.vec = reinterpret_cast(const_cast(input))[0]; +#pragma unroll 3 + for (unsigned int j = 0; j < 3; j++) { + value |= ((uint64_t)input3.a[j]) << ((j + shift) * PACK_SIZE); + } +} + +template <> +inline __device__ void unpack_value<4>(const unsigned char *input, uint64_t &value, + const unsigned int shift) { + U4 input4; + input4.vec = reinterpret_cast(const_cast(input))[0]; +#pragma unroll 4 + for (unsigned int j = 0; j < 4; j++) { + value |= ((uint64_t)input4.a[j]) << ((j + shift) * PACK_SIZE); + } +} + +template <> +inline __device__ void unpack_value<6>(const unsigned char *input, uint64_t &value, + const unsigned int shift) { + unpack_value<3>(input, value, 0); + unpack_value<3>(input + 3, value, 3); +} + +template <> +inline __device__ void unpack_value<8>(const unsigned char *input, uint64_t &value, + const unsigned int shift) { + unpack_value<4>(input, value, 0); + unpack_value<4>(input + 4, value, 4); +} + +template +__global__ void UnpackArray(const unsigned char *input, const unsigned char *meta_info, + T *output, int num_elems, int bucket_size) { + unsigned int tid = hipThreadIdx_x + hipBlockIdx_x * hipBlockDim_x; + unsigned int stride = gridDim.x * hipBlockDim_x; + int num_char = (BITS * num_elems + PACK_SIZE - 1) / PACK_SIZE; + const unsigned int divisor = 1 << BITS; + for (unsigned int i = tid; i < (num_elems + PACK_SIZE - 1) / PACK_SIZE; + i += stride) { + uint64_t value = 0; + if (VECTORIZE_DECOMPRESS) { + if ((i + 1) * BITS > num_char) { + for (unsigned int j = 0; j < num_char - i * BITS; j++) + value |= ((uint64_t)input[i * BITS + j]) << (j * PACK_SIZE); + } else { + unpack_value(input + i * BITS, value); + } + + if ((i + 1) * PACK_SIZE > num_elems) { + for (unsigned int j = 0; j < num_elems - i * PACK_SIZE; j++) { + unsigned char encoded_value = (value >> (j * BITS)) & (divisor - 1); + T d = MaxMinDecodeValue(encoded_value, meta_info, + i * PACK_SIZE + j, bucket_size); + if (ADD) { + output[i * PACK_SIZE + j] = sum(output[i * PACK_SIZE + j], d); + } else { + output[i * PACK_SIZE + j] = d; + } + } + } else { + typename TypeToVectorType::vector_union output_union; +#pragma unroll + for (int j = 0; j < PACK_SIZE; j += 4) { + typename TypeToVectorType::vector_type *output_p = + reinterpret_cast::vector_type *>( + &output[i * PACK_SIZE + j]); + if (ADD) + output_union.vec = *output_p; +#pragma unroll + for (int k = 0; k < TypeToVectorType::num_values; k++) { + unsigned char encoded_value = + (value >> ((j + k) * BITS)) & (divisor - 1); + T d = MaxMinDecodeValue(encoded_value, meta_info, + i * PACK_SIZE + j + k, bucket_size); + if (ADD) { + output_union.a[k] = sum((T)(output_union.a[k]), d); + } else { + output_union.a[k] = d; + } + *output_p = output_union.vec; + } + typename TypeToVectorType::vector_type *output_p = + reinterpret_cast::vector_type *>( + &output[i * PACK_SIZE + j]); + *output_p = output_union.vec; + } + } + } else { + for (int j = 0; j < BITS && i * BITS + j < num_char; j++) { + value |= ((uint64_t)input[i * BITS + j]) << (j * PACK_SIZE); + } + for (int j = 0; j < PACK_SIZE && i * PACK_SIZE + j < num_elems; j++) { + unsigned char encoded_value = (value >> (j * BITS)) & (divisor - 1); + T d = MaxMinDecodeValue(encoded_value, meta_info, i * PACK_SIZE + j, + bucket_size); + if (ADD) { + output[i * PACK_SIZE + j] = sum(output[i * PACK_SIZE + j], d); + } else { + output[i * PACK_SIZE + j] = d; + } + } + } + } +} + +/*-------------------Host functions------------------------*/ +void HIP_init_rand(RandState *states, size_t num_elems, unsigned int seed, + hipStream_t stream) { + hipLaunchKernelGGL( + (_init_rand), + dim3(BLOCKS_PER_GRID(num_elems, THREADS_PER_BLOCK_COMPRESS)), + dim3(THREADS_PER_BLOCK_COMPRESS), 0, stream, seed, states); +} + +template +void HIP_add(int n, const T *x, T *y, T *sum, hipStream_t stream) { + int num_threads = umin(n, MAX_THREADS_PER_BLOCK); + int blocks = BLOCKS_PER_GRID(n, num_threads); + hipLaunchKernelGGL((_add), dim3(blocks), dim3(num_threads), 0, stream, n, + x, y, sum); + HIP_CHECK(hipGetLastError()); +} + +template +inline void QUANTIZE(const unsigned char *input_data, + unsigned char *output_data, unsigned char *feedback_data, + int num_elems, int bits, int bucket_size, + RandState *states, hipStream_t stream, int num_blocks, + int num_threads, int shared_memory_block_size) { + switch (bits) { + case 1: + hipLaunchKernelGGL((quantize), dim3(num_blocks), + dim3(num_threads), shared_memory_block_size, stream, + input_data, output_data, feedback_data, num_elems, + bucket_size, states); + break; + case 2: + hipLaunchKernelGGL((quantize), dim3(num_blocks), + dim3(num_threads), shared_memory_block_size, stream, + input_data, output_data, feedback_data, num_elems, + bucket_size, states); + break; + case 3: + hipLaunchKernelGGL((quantize), dim3(num_blocks), + dim3(num_threads), shared_memory_block_size, stream, + input_data, output_data, feedback_data, num_elems, + bucket_size, states); + break; + case 4: + hipLaunchKernelGGL((quantize), dim3(num_blocks), + dim3(num_threads), shared_memory_block_size, stream, + input_data, output_data, feedback_data, num_elems, + bucket_size, states); + break; + case 5: + hipLaunchKernelGGL((quantize), dim3(num_blocks), + dim3(num_threads), shared_memory_block_size, stream, + input_data, output_data, feedback_data, num_elems, + bucket_size, states); + break; + case 6: + hipLaunchKernelGGL((quantize), dim3(num_blocks), + dim3(num_threads), shared_memory_block_size, stream, + input_data, output_data, feedback_data, num_elems, + bucket_size, states); + break; + case 7: + hipLaunchKernelGGL((quantize), dim3(num_blocks), + dim3(num_threads), shared_memory_block_size, stream, + input_data, output_data, feedback_data, num_elems, + bucket_size, states); + break; + case 8: + hipLaunchKernelGGL((quantize), dim3(num_blocks), + dim3(num_threads), shared_memory_block_size, stream, + input_data, output_data, feedback_data, num_elems, + bucket_size, states); + break; + default: + printf("Wrong number of bits %i!!!\n", bits); + } + HIP_CHECK(hipGetLastError()); +} + +template +void HIP_quantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + unsigned char *feedback_data, int num_elems, int bits, + int bucket_size, RandState *states, + hipStream_t stream) { + int num_blocks = + umin((num_elems + bucket_size - 1) / bucket_size, MAX_NUMBER_OF_BLOCKS); + int num_threads = umin(THREADS_PER_BLOCK_COMPRESS, bucket_size); + int shared_memory_block_size = 2 * MAX_THREADS_PER_BLOCK * sizeof(T); + QUANTIZE(input_data, output_data, feedback_data, num_elems, bits, + bucket_size, states, stream, num_blocks, num_threads, + shared_memory_block_size); +} + +template +inline void DEQUANTIZE(const unsigned char *input, const unsigned char *meta_info, + T *output, int num_elems, int bucket_size, int bits, + hipStream_t stream, int num_blocks, int num_threads) { + switch (bits) { + case 1: + hipLaunchKernelGGL((UnpackArray), dim3(num_blocks), + dim3(num_threads), 0, stream, input, meta_info, output, + num_elems, bucket_size); + break; + case 2: + hipLaunchKernelGGL((UnpackArray), dim3(num_blocks), + dim3(num_threads), 0, stream, input, meta_info, output, + num_elems, bucket_size); + break; + case 3: + hipLaunchKernelGGL((UnpackArray), dim3(num_blocks), + dim3(num_threads), 0, stream, input, meta_info, output, + num_elems, bucket_size); + break; + case 4: + hipLaunchKernelGGL((UnpackArray), dim3(num_blocks), + dim3(num_threads), 0, stream, input, meta_info, output, + num_elems, bucket_size); + break; + case 5: + hipLaunchKernelGGL((UnpackArray), dim3(num_blocks), + dim3(num_threads), 0, stream, input, meta_info, output, + num_elems, bucket_size); + break; + case 6: + hipLaunchKernelGGL((UnpackArray), dim3(num_blocks), + dim3(num_threads), 0, stream, input, meta_info, output, + num_elems, bucket_size); + break; + case 7: + hipLaunchKernelGGL((UnpackArray), dim3(num_blocks), + dim3(num_threads), 0, stream, input, meta_info, output, + num_elems, bucket_size); + break; + case 8: + hipLaunchKernelGGL((UnpackArray), dim3(num_blocks), + dim3(num_threads), 0, stream, input, meta_info, output, + num_elems, bucket_size); + break; + default: + printf("Wrong number of bits %i!!!\n", bits); + } + HIP_CHECK(hipGetLastError()); +} + +template +void HIP_dequantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, int num_elems, int bits, + int bucket_size, hipStream_t stream) { + T *output = (T *)output_data; + const unsigned char *meta_info = input_data; + int num_buckets = (num_elems + bucket_size - 1) / bucket_size; + unsigned char *input = input_data + 2 * sizeof(T) * num_buckets; + int num_threads = THREADS_PER_BLOCK_DECOMPRESS; + int num_blocks = BLOCKS_PER_GRID(num_elems / PACK_SIZE, num_threads); + DEQUANTIZE(input, meta_info, output, num_elems, bucket_size, bits, + stream, num_blocks, num_threads); +} + +/* Functions declarations */ +template void HIP_add(int n, const float *x, float *y, float *sum, + hipStream_t stream); +template void HIP_add(int n, const Half *x, Half *y, Half *sum, + hipStream_t stream); + +template void HIP_quantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + unsigned char *feedback_data, + int num_elems, int bits, + int bucket_size, RandState *states, + hipStream_t stream); +template void HIP_quantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + unsigned char *feedback_data, + int num_elems, int bits, + int bucket_size, RandState *states, + hipStream_t stream); + +template void HIP_dequantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + int num_elems, int bits, + int bucket_size, + hipStream_t stream); +template void HIP_dequantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + int num_elems, int bits, + int bucket_size, + hipStream_t stream); + +template void HIP_dequantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + int num_elems, int bits, + int bucket_size, + hipStream_t stream); +template void HIP_dequantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, + int num_elems, int bits, + int bucket_size, + hipStream_t stream); + +} // namespace gpu +} // namespace common +} // namespace cgx diff --git a/src/common/compression/hip_compression_operations.h b/src/common/compression/hip_compression_operations.h new file mode 100755 index 0000000..cf2cd46 --- /dev/null +++ b/src/common/compression/hip_compression_operations.h @@ -0,0 +1,44 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once +#include "gpu_compression_operations.h" + +namespace cgx { +namespace common { +namespace gpu { +template +void HIP_quantize_maxmin(const unsigned char *input_data, unsigned char *output_data, + unsigned char *feedback_data, int num_elems, int bits, + int bucket_size, RandState *states, + hipStream_t stream); + +template +void HIP_dequantize_maxmin(const unsigned char *input_data, + unsigned char *output_data, int num_elems, int bits, + int bucket_size, hipStream_t stream); + +template +void HIP_add(int n, const T *x, T *y, T *sum, hipStream_t stream); + +void HIP_init_rand(RandState *states, size_t num_elems, unsigned int seed, + hipStream_t stream); +} // namespace gpu +} // namespace common +} // namespace cgx \ No newline at end of file diff --git a/src/common/compressor.cc b/src/common/compressor.cc new file mode 100755 index 0000000..4073441 --- /dev/null +++ b/src/common/compressor.cc @@ -0,0 +1,446 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include "compressor.h" +#include "common.h" +#include "utils.h" + +namespace cgx { +namespace common { + +std::unordered_map + Compressor::layers_configs; +CompressionLayerConfig Compressor::default_config; + +Compressor::Compressor(std::shared_ptr gpu_context) + : gpu_context_(gpu_context) { + unsigned int fusion_size_mb = + utils::GetIntEnvOrDefault(FUSION_BUFFER_SIZE_MB, FUSION_SIZE_DEFAULT_MB); + tensor_fusion_size_ = std::max(fusion_size_mb * 1024 * 1024, MIN_FUSION_SIZE); + min_elems_to_compress_ = utils::GetIntEnvOrDefault(COMPRESSION_MINIMAL_SIZE, 16); +} + +void Compressor::ResetParamsFromEnv() { + default_config.bucket_size = utils::GetIntEnvOrDefault( + COMPRESSION_BUCKET_SIZE, COMPRESSION_DEFAULT_BUCKET_SIZE); + default_config.skip_incomplete_buckets = false; + utils::SetBoolFromEnv(COMPRESSION_SKIP_INCOMPLETE_BUCKETS, + default_config.skip_incomplete_buckets, true); +} + +CompressionLayerConfig &Compressor::GetLayerConfig(const LayerId &layer_id) { + auto it = layers_configs.find(layer_id); + if (it != layers_configs.end()) { + auto &config = it->second; + config.quantization_bits = (config.quantization_bits > 0) + ? config.quantization_bits + : default_config.quantization_bits; + config.bucket_size = (config.bucket_size > 0) ? config.bucket_size + : default_config.bucket_size; + config.skip_incomplete_buckets = default_config.skip_incomplete_buckets; + return config; + } + return default_config; +} + +size_t Compressor::BufferSize(int chunk_num_elems, + const std::vector &layers, + int fusion_offset) { + int offset_cumm = 0; + int nelem = 0; + size_t sum_result = 0; + for (auto &layer : layers) { + nelem = layer.numel(); + if (offset_cumm + nelem <= fusion_offset) { + offset_cumm += nelem; + continue; + } + + if (offset_cumm - fusion_offset >= chunk_num_elems) { + break; + } + + if (offset_cumm < fusion_offset) { + // If the first part of param group is placed in previous slice + // depending on reduction algorithm. + nelem = offset_cumm + nelem - fusion_offset; + } + + if (std::max(offset_cumm, fusion_offset) + nelem > + fusion_offset + chunk_num_elems) { + // if layer doesn't fit the rest of slice. + nelem = fusion_offset + chunk_num_elems - + std::max(offset_cumm, fusion_offset); + } + auto &config = GetLayerConfig(layer.layer_id()); + sum_result += BufferSize(nelem, layer.element_size(), config); + offset_cumm += layer.numel(); + } + return sum_result; +} + +size_t Compressor::Compress(unsigned char *output, + const std::vector &layers, int fusion_offset, + int chunk_num_elems, gpuStream_t stream) { + size_t total_compressed_size = 0; + + int offset_cumm = 0; + int nelem = 0; + int buffer_offset = 0; + size_t compressed_size; + for (auto &layer : layers) { + nelem = layer.numel(); + if (offset_cumm + nelem <= fusion_offset) { + offset_cumm += nelem; + continue; + } + + if (offset_cumm - fusion_offset >= chunk_num_elems) { + break; + } + buffer_offset = 0; + if (offset_cumm < fusion_offset) { + // If the first part of the entry is placed in the previous slice. + nelem = offset_cumm + nelem - fusion_offset; + buffer_offset = layer.numel() - nelem; + } + + if (std::max(offset_cumm, fusion_offset) + nelem > + fusion_offset + chunk_num_elems) { + // if entry doesn't fit the rest of slice. + nelem = fusion_offset + chunk_num_elems - + std::max(offset_cumm, fusion_offset); + } + auto offset = buffer_offset * layer.element_size(); + auto data = ((unsigned char *)layer.data_ptr()) + offset; + auto &config = GetLayerConfig(layer.layer_id()); + compressed_size = CompressBuffer(data, output, nullptr, nelem, + layer.scalar_type(), config, stream); + offset_cumm += layer.numel(); + output += compressed_size; + total_compressed_size += compressed_size; + } + return total_compressed_size; +} + +void Compressor::Decompress(unsigned char *input_data, + const std::vector &layers, int fusion_offset, + int chunk_num_elems, bool add, gpuStream_t stream) { + int offset_cumm = 0; + int nelem = 0; + int buffer_offset = 0; + size_t cumm_decompressed = 0; + + for (auto &layer : layers) { + nelem = layer.numel(); + if (offset_cumm + nelem <= fusion_offset) { + offset_cumm += nelem; + continue; + } + if (offset_cumm - fusion_offset >= chunk_num_elems) + break; + buffer_offset = 0; + if (offset_cumm < fusion_offset) { + // If the first part of param group is placed in previous slice + // depending on reduction algorithm. + nelem = offset_cumm + nelem - fusion_offset; + buffer_offset = layer.numel() - nelem; + } + if (std::max(offset_cumm, fusion_offset) + nelem > + fusion_offset + chunk_num_elems) { + // if layer doesn't fit the rest of slice. + nelem = fusion_offset + chunk_num_elems - + std::max(offset_cumm, fusion_offset); + } + auto output = ((unsigned char *)layer.data_ptr()) + + buffer_offset * layer.element_size(); + auto &config = GetLayerConfig(layer.layer_id()); + DecompressBuffer(input_data + cumm_decompressed, output, nelem, + layer.scalar_type(), add, config, stream); + cumm_decompressed += BufferSize(nelem, layer.element_size(), config); + offset_cumm += layer.numel(); + } +} + +void Compressor::GetSizesAndOffsets(int num_elements, int world_size, + int global_offset, + const std::vector &layers, + std::vector &offsets, + std::vector &sizes) { + int residue = num_elements % world_size; + int num_elems_per_node = num_elements / world_size; + int offset = global_offset; + for (int rank = 0; rank < world_size; rank++) { + sizes.push_back(num_elems_per_node + ((rank < residue) ? 1 : 0)); + offsets.push_back(offset); + offset += sizes.back(); + } +} + +void Compressor::Add(int num_elements, unsigned char *x, unsigned char *y, + unsigned char *sum, at::ScalarType dtype, + gpuStream_t stream) { + if (dtype == at::kHalf) { + gpu::add(num_elements, reinterpret_cast(x), + reinterpret_cast(y), + reinterpret_cast(sum), stream); + } else { + gpu::add(num_elements, reinterpret_cast(x), + reinterpret_cast(y), + reinterpret_cast(sum), stream); + } +} + +void Compressor::Float2Half(unsigned char *input, unsigned char *output, + int num_elements, gpuStream_t stream) { + gpu::float2half(reinterpret_cast(input), + reinterpret_cast(output), num_elements, stream); +} + +void Compressor::Half2Float(unsigned char *input, unsigned char *output, + int num_elements, gpuStream_t stream) { + gpu::half2float(reinterpret_cast(input), + reinterpret_cast(output), num_elements, stream); +} + +size_t DummyCompressor::CompressBuffer(unsigned char *input, + unsigned char *output, + unsigned char *feedback, int num_elems, + at::ScalarType dtype, + const CompressionLayerConfig &config, + gpuStream_t stream) { + gpu_context_->MemcpyAsyncD2D(output, input, + num_elems * utils::get_sizeof(dtype), stream); + return num_elems * utils::get_sizeof(dtype); +} + +void DummyCompressor::DecompressBuffer(unsigned char *input, + unsigned char *output, int num_elems, + at::ScalarType dtype, bool add, + const CompressionLayerConfig &config, + gpuStream_t stream) { + if (add) { + Compressor::Add(num_elems, input, output, output, dtype, stream); + } else { + gpu_context_->MemcpyAsyncD2D(output, input, + num_elems * utils::get_sizeof(dtype), stream); + } +} + +size_t DummyCompressor::BufferSize(int num_elems, size_t element_size, + const CompressionLayerConfig &config) { + return num_elems * element_size; +} + +bool DummyCompressor::isEnabled(const Layer &layer) { + return layer.numel() > min_elems_to_compress_; +} + +Quantizer::Quantizer(std::shared_ptr gpu_context) + : Compressor(gpu_context) {} + +void Quantizer::ResetParamsFromEnv() { + Compressor::ResetParamsFromEnv(); + auto quantization_bits = + common::utils::GetIntEnvOrDefault(COMPRESSION_QUANTIZATION_BITS, 32); + default_config.quantization_bits = quantization_bits; +} + +void Quantizer::GetSizesAndOffsets(int num_elements, int world_size, + int global_offset, + const std::vector &layers, + std::vector &offsets, + std::vector &sizes) { + int offset = global_offset; + int num_per_node; + auto it = layers.begin(); + int entry_offset = 0; + int n_elem = std::min((int)it->numel(), num_elements); + int cur_size = 0; + int align_unit = (layers[0].scalar_type() == at::kHalf) ? 8 : 4; + for (int rank = 0; rank < world_size; rank++) { + num_per_node = num_elements / (world_size - rank); + cur_size = 0; + while (cur_size < num_per_node) { + if (n_elem <= num_per_node - cur_size) { + cur_size += n_elem; + it++; + if (it == layers.end()) + break; + n_elem = std::min((int)it->numel(), num_elements); + } else { + int aligned = std::min( + (int)utils::round_to(num_per_node - cur_size, align_unit), n_elem); + cur_size += aligned; + n_elem -= aligned; + } + } + num_elements -= cur_size; + sizes.push_back(cur_size); + offsets.push_back(offset); + offset += cur_size; + } +} + +size_t MaxMinQuantizer::CompressBuffer(unsigned char *input, + unsigned char *output, + unsigned char *feedback, int num_elems, + at::ScalarType dtype, + const CompressionLayerConfig &config, + gpuStream_t stream) { + if (num_elems == 0) + return 0; + const int bits = config.quantization_bits; + const int bucket_size = config.bucket_size; + const bool skip_incomplete = config.skip_incomplete_buckets; + int num_elems_to_compress = num_elems; + int residual_elems = 0; + int compressed_size = 0; + if (skip_incomplete) { + num_elems_to_compress = (num_elems / bucket_size) * bucket_size; + residual_elems = num_elems % bucket_size; + } + if (num_elems_to_compress > 0) { + if (dtype != at::kHalf) { + gpu::quantize_maxmin(input, output, feedback, + num_elems_to_compress, bits, bucket_size, + rand_states_, stream); + } else { + gpu::quantize_maxmin(input, output, feedback, + num_elems_to_compress, bits, bucket_size, + rand_states_, stream); + } + compressed_size = + BufferSize(num_elems_to_compress, utils::get_sizeof(dtype), config); + } + if (skip_incomplete and residual_elems > 0) { + input += num_elems_to_compress * utils::get_sizeof(dtype); + output += compressed_size; + gpu_context_->MemcpyAsyncD2D((void *)output, (void *)input, + residual_elems * utils::get_sizeof(dtype), + stream); + compressed_size += utils::get_sizeof(dtype) * residual_elems; + } + return compressed_size; +} + +void MaxMinQuantizer::DecompressBuffer(unsigned char *input, + unsigned char *output, int num_elems, + at::ScalarType dtype, bool add, + const CompressionLayerConfig &config, + gpuStream_t stream) { + if (num_elems == 0) + return; + const int bits = config.quantization_bits; + const int bucket_size = config.bucket_size; + const bool skip_incomplete = config.skip_incomplete_buckets; + int num_elems_to_decompress = num_elems; + int residual_elems = 0; + if (skip_incomplete) { + num_elems_to_decompress = (num_elems / bucket_size) * bucket_size; + residual_elems = num_elems % bucket_size; + } + if (num_elems_to_decompress > 0) { + if (add) { + if (dtype != at::kHalf) { + gpu::dequantize_maxmin( + input, output, num_elems_to_decompress, bits, bucket_size, stream); + } else { + gpu::dequantize_maxmin( + input, output, num_elems_to_decompress, bits, bucket_size, stream); + } + } else { + if (dtype != at::kHalf) { + gpu::dequantize_maxmin(input, output, + num_elems_to_decompress, bits, + bucket_size, stream); + } else { + gpu::dequantize_maxmin(input, output, + num_elems_to_decompress, bits, + bucket_size, stream); + } + } + } + + if (skip_incomplete and residual_elems > 0) { + int compressed_size = + BufferSize(num_elems_to_decompress, utils::get_sizeof(dtype), config); + input += compressed_size; + output += num_elems_to_decompress * utils::get_sizeof(dtype); + if (add) { + if (dtype != at::kHalf) + gpu::add(residual_elems, (float *)input, (float *)output, + (float *)output, stream); + else + gpu::add(residual_elems, (gpu::Half *)input, + (gpu::Half *)output, (gpu::Half *)output, stream); + } else { + gpu_context_->MemcpyAsyncD2D((void *)output, (void *)input, + residual_elems * utils::get_sizeof(dtype), + stream); + } + } +} + +size_t MaxMinQuantizer::BufferSize(int num_elems, size_t element_size, + const CompressionLayerConfig &config) { + if (num_elems == 0) + return 0; + const int bits = config.quantization_bits; + const int bucket_size = config.bucket_size; + const bool skip_incomplete = config.skip_incomplete_buckets; + int num_buckets = (num_elems + bucket_size - 1) / bucket_size; + int residuals = 0; + if (skip_incomplete) { + num_buckets = num_elems / bucket_size; + residuals = num_elems % bucket_size; + num_elems = num_buckets * bucket_size; + } + size_t meta_buffer_size = 2 * num_buckets * element_size; + size_t compressed_values_buffer_size = (num_elems * bits + 7) / 8; + return meta_buffer_size + utils::aligned_size(compressed_values_buffer_size) + + residuals * element_size; +} + +bool MaxMinQuantizer::isEnabled(const Layer &layer) { + auto &config = GetLayerConfig(layer.layer_id()); + return layer.numel() > min_elems_to_compress_ and + config.quantization_bits <= 8; +} + +void MaxMinQuantizer::Init(int element_size, gpuStream_t stream) { + size_t max_num_elems = tensor_fusion_size_ / element_size; + size_t randstates_sizes = gpu::get_curand_array_size(max_num_elems); + size_t metainfo_buf_size = (max_num_elems + default_config.bucket_size - 1) / + default_config.bucket_size; +#if !QSGD_DETERMENISTIC + randstates_sizes = 0; +#endif + if (!aux_buffer_) { + aux_buffer_ = std::make_unique(randstates_sizes + + metainfo_buf_size); +#if !QSGD_DETERMENISTIC + rand_states_ = static_cast(aux_buffer_->RawPointer()); + gpu::init_rand_states(rand_states_, max_num_elems, time(NULL), stream); +#endif + } +} + +} // namespace common +} // namespace cgx \ No newline at end of file diff --git a/src/common/compressor.h b/src/common/compressor.h new file mode 100755 index 0000000..1b5a95e --- /dev/null +++ b/src/common/compressor.h @@ -0,0 +1,185 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once +#include +#include +#include + +#include "buffer.h" +#include "compression/gpu_compression_operations.h" +#include "gpu_context.h" +#include "layer.h" + +namespace cgx { +namespace common { +const int COMPRESSION_DEFAULT_BUCKET_SIZE = 512; + +struct CompressionLayerConfig { + int quantization_bits; + int bucket_size; + bool skip_incomplete_buckets; + bool operator==(const CompressionLayerConfig &b) { + return quantization_bits == b.quantization_bits and + bucket_size == b.bucket_size and + skip_incomplete_buckets == b.skip_incomplete_buckets; + } +}; + +class Compressor { +public: + Compressor(std::shared_ptr gpu_context); + virtual ~Compressor() = default; + // Returns size of buffer to allocate for usage in compress (in bytes). We + // assume that no compression will be done in-place. + virtual size_t BufferSize(int num_elems, size_t element_size, + const CompressionLayerConfig &config) = 0; + size_t BufferSize(int num_elems, const std::vector &layers, + int fusion_offset); + + size_t Compress(unsigned char *output, const std::vector &tensors, + int fusion_offset, int chunk_num_elems, gpuStream_t stream); + + void Decompress(unsigned char *input_data, const std::vector &entries, + int fusion_offset, int chunk_num_elems, bool add, + gpuStream_t stream); + + // Returns size of compressed size (in bytes). And update error_feedback. + // If error_feedback is nullptr, it's not updated. + virtual size_t CompressBuffer(unsigned char *input_data, + unsigned char *output, + unsigned char *feedback_data, int num_elems, + at::ScalarType dtype, + const CompressionLayerConfig &config, + gpuStream_t stream) = 0; + // Decompress data from input to output. + // If add is True sum decompressed data with output. + virtual void DecompressBuffer(unsigned char *input, unsigned char *output, + int num_elems, at::ScalarType dtype, bool add, + const CompressionLayerConfig &config, + gpuStream_t stream) = 0; + static void GetSizesAndOffsets(int num_elements, int world_size, + int global_offset, + const std::vector &entries, + std::vector &offsets, + std::vector &sizes); + static void Add(int num_elements, unsigned char *x, unsigned char *y, + unsigned char *sum, at::ScalarType dtype, gpuStream_t stream); + void Float2Half(unsigned char *input, unsigned char *output, int num_elements, + gpuStream_t stream); + void Half2Float(unsigned char *input, unsigned char *output, int num_elements, + gpuStream_t stream); + + virtual bool isEnabled(const Layer &tensor) = 0; + virtual void ResetParamsFromEnv(); + virtual void Init(int elem_size, gpuStream_t stream) {} + CompressionLayerConfig &GetLayerConfig(const LayerId &name); + static void SetQBits(const LayerId &layer_id, int bits) { + auto &config = layers_configs[layer_id]; + config.quantization_bits = bits; + config.bucket_size = (config.bucket_size > 0) ? config.bucket_size + : default_config.bucket_size; + } + + static void SetQBucketSize(const LayerId &layer_id, int bucket_size) { + auto &config = layers_configs[layer_id]; + config.quantization_bits = (config.quantization_bits > 0) + ? config.quantization_bits + : default_config.quantization_bits; + ; + config.bucket_size = bucket_size; + } + +protected: + struct hash_laierid { + size_t operator()(const LayerId &id) const { + auto hash1 = std::hash{}(id.first); + auto hash2 = std::hash{}(id.second); + + if (hash1 != hash2) { + return hash1 ^ hash2; + } + return hash1; + } + }; + + std::shared_ptr gpu_context_; + static CompressionLayerConfig default_config; + static std::unordered_map + layers_configs; + size_t tensor_fusion_size_; + int min_elems_to_compress_; +}; + +class Quantizer : public Compressor { +public: + explicit Quantizer(std::shared_ptr gpu_context); + static void GetSizesAndOffsets(int num_elements, int world_size, + int global_offset, + const std::vector &tensors, + std::vector &offsets, + std::vector &sizes); + void ResetParamsFromEnv() override; + +protected: + gpu::RandState *rand_states_; + std::unique_ptr aux_buffer_; +}; + +class DummyCompressor : public Compressor { +public: + DummyCompressor(std::shared_ptr gpu_context) + : Compressor(gpu_context) {} + + size_t CompressBuffer(unsigned char *input, unsigned char *output, + unsigned char *feedback, int num_elems, + at::ScalarType dtype, + const CompressionLayerConfig &config, + gpuStream_t stream) override; + void DecompressBuffer(unsigned char *input, unsigned char *output, + int num_elems, at::ScalarType dtype, bool add, + const CompressionLayerConfig &config, + gpuStream_t stream) override; + size_t BufferSize(int num_elems, size_t element_size, + const CompressionLayerConfig &config) final; + bool isEnabled(const Layer &tensor) override; +}; + +class MaxMinQuantizer : public Quantizer { +public: + MaxMinQuantizer(std::shared_ptr gpu_context) + : Quantizer(gpu_context) {} + + size_t CompressBuffer(unsigned char *input, unsigned char *output, + unsigned char *feedback, int num_elems, + at::ScalarType dtype, + const CompressionLayerConfig &config, + gpuStream_t stream) override; + void DecompressBuffer(unsigned char *input, unsigned char *output, + int num_elems, at::ScalarType dtype, bool add, + const CompressionLayerConfig &config, + gpuStream_t stream) override; + size_t BufferSize(int num_elems, size_t element_size, + const CompressionLayerConfig &config) final; + bool isEnabled(const Layer &tensor) override; + virtual void Init(int elem_size, gpuStream_t stream); +}; + +} // namespace common +} // namespace cgx diff --git a/src/common/cuda_operations.cc b/src/common/cuda_operations.cc new file mode 100755 index 0000000..39e64da --- /dev/null +++ b/src/common/cuda_operations.cc @@ -0,0 +1,143 @@ +// Copyright 2016 The TensorFlow Authors. All Rights Reserved. +// Modifications copyright (C) 2019 Uber Technologies, Inc. +// Modifications copyright (C) 2022 IST Austria. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================= + +#include "gpu_context.h" + +#include + +namespace cgx { +namespace common { + +class GPUContext::impl { +public: + void ErrorCheck(std::string op_name, cudaError_t cuda_result) { + if (cuda_result != cudaSuccess) { + throw std::logic_error( + std::string(op_name) + " failed: " + cudaGetErrorString(cuda_result)); + } + } + + void EventCreate(cudaEvent_t *event) { + ErrorCheck("cudaEventCreateWithFlags", + cudaEventCreateWithFlags(event, + cudaEventDisableTiming + | cudaEventInterprocess)); + } + + void EventDestroy(cudaEvent_t &event) { + ErrorCheck("cudaEventDestroy", cudaEventDestroy(event)); + } + + void IpcGetEventHandle(cudaIpcEventHandle_t *eventHandle, cudaEvent_t &event) { + ErrorCheck("cudaIpcGetEventHandle", + cudaIpcGetEventHandle(eventHandle, event)); + } + + void IpcOpenEventHandle(cudaEvent_t *event, cudaIpcEventHandle_t &eventHandle) { + ErrorCheck("cudaIpcOpenEventHandle", + cudaIpcOpenEventHandle(event, eventHandle)); + } + + void EventRecord(cudaEvent_t &event, + cudaStream_t &stream) { + ErrorCheck("cudaEventRecord", cudaEventRecord(event, stream)); + } + + void StreamCreate(cudaStream_t *stream) { +// int greatest_priority; +// ErrorCheck("cudaDeviceGetStreamPriorityRange", +// cudaDeviceGetStreamPriorityRange(NULL, &greatest_priority)); +// ErrorCheck("cudaStreamCreateWithPriority", +// cudaStreamCreateWithPriority(stream, +// cudaStreamNonBlocking, +// greatest_priority)); + ErrorCheck("cudaStreamCreateWithFlags", + cudaStreamCreateWithFlags(stream, cudaStreamNonBlocking)); + } + + void StreamSynchronize(cudaStream_t stream) { + ErrorCheck("cudaStreamSynchronize", cudaStreamSynchronize(stream)); + } + + void StreamWaitEvent(cudaStream_t stream, cudaEvent_t &event) { + ErrorCheck("cudaStreamWaitEvent", cudaStreamWaitEvent(stream, event, 0)); + } + + int GetDevice() { + int device; + ErrorCheck("cudaGetDevice", cudaGetDevice(&device)); + return device; + } + + void SetDevice(int device) { + ErrorCheck("cudaSetDevice", cudaSetDevice(device)); + } + + void MemcpyAsyncD2D(void *dst, + const void *src, + size_t count, + cudaStream_t stream) { + ErrorCheck("cudaMemcpyAsync", + cudaMemcpyAsync(dst, + src, + count, + cudaMemcpyDeviceToDevice, + stream)); + } + + void MemcpyAsyncH2D(void *dst, + const void *src, + size_t count, + cudaStream_t stream) { + ErrorCheck("cudaMemcpyAsync", + cudaMemcpyAsync(dst, + src, + count, + cudaMemcpyHostToDevice, + stream)); + } + + void MemcpyAsyncD2H(void *dst, + const void *src, + size_t count, + cudaStream_t stream) { + ErrorCheck("cudaMemcpyAsync", + cudaMemcpyAsync(dst, + src, + count, + cudaMemcpyDeviceToHost, + stream)); + } + + void DeviceSynchronize() { + ErrorCheck("cudaDeviceSynchronize", cudaDeviceSynchronize()); + } + + void MemcpyD2D(void *dst, const void *src, size_t count) { + ErrorCheck("cudaMemcpy", + cudaMemcpy(dst, src, count, cudaMemcpyDeviceToDevice)); + } + +private: + // We reuse CUDA events as it appears that their creation carries non-zero cost. + std::unordered_map> cuda_events; +}; + +#include "gpu_context_impl.cc" + +} // namespace common +} // namespace cgx diff --git a/src/common/gpu_context.h b/src/common/gpu_context.h new file mode 100755 index 0000000..bb8a322 --- /dev/null +++ b/src/common/gpu_context.h @@ -0,0 +1,103 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once +// Copyright 2016 The TensorFlow Authors. All Rights Reserved. +// Modifications copyright (C) 2019 Uber Technologies, Inc. +// Modifications copyright (C) 2020, NVIDIA CORPORATION. All rights reserved. +// Modifications copyright (C) 2022, IST Austria. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================= +#if HAVE_CUDA +#include +#include +using gpuError_t = cudaError_t; +using gpuEvent_t = cudaEvent_t; +using gpuStream_t = cudaStream_t; +using gpuIpcEventHandle_t = cudaIpcEventHandle_t; +#elif HAVE_ROCM +#include +using gpuError_t = hipError_t; +using gpuEvent_t = hipEvent_t; +using gpuStream_t = hipStream_t; +using gpuIpcEventHandle_t = hipIpcEventHandle_t; +#endif +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef TEST +#include +#endif + +namespace cgx { +namespace common { + +class GPUContext { +public: + GPUContext(); + ~GPUContext(); + + void ErrorCheck(std::string op_name, gpuError_t gpu_result); + + void EventCreate(gpuEvent_t* event); + void EventDestroy(gpuEvent_t& event); + void EventRecord(gpuEvent_t& event, gpuStream_t &stream); + + void IpcGetEventHandle(gpuIpcEventHandle_t *eventHandle, gpuEvent_t &event); + void IpcOpenEventHandle(gpuEvent_t *event, gpuIpcEventHandle_t &eventHandle); + + void StreamCreate(gpuStream_t *stream); + void StreamSynchronize(gpuStream_t stream); + void StreamWaitEvent(gpuStream_t& stream, gpuEvent_t& event); + + void DeviceSynchronize(); + + int GetDevice(); + + void SetDevice(int device); + + void MemcpyAsyncD2D(void *dst, const void *src, size_t count, gpuStream_t stream); + void MemcpyAsyncH2D(void *dst, const void *src, size_t count, gpuStream_t stream); + void MemcpyAsyncD2H(void *dst, const void *src, size_t count, gpuStream_t stream); + + void MemcpyD2D(void *dst, const void* srt, size_t count); + +private: + class impl; + std::unique_ptr pimpl; +}; +} // namespace common +}// namespace cgx \ No newline at end of file diff --git a/src/common/gpu_context_impl.cc b/src/common/gpu_context_impl.cc new file mode 100755 index 0000000..d39a2d3 --- /dev/null +++ b/src/common/gpu_context_impl.cc @@ -0,0 +1,99 @@ + +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +GPUContext::GPUContext() : pimpl{new impl} {} +GPUContext::~GPUContext() = default; + +void GPUContext::ErrorCheck(std::string op_name, gpuError_t gpu_result) { + pimpl->ErrorCheck(op_name, gpu_result); +} + +void GPUContext::EventCreate(gpuEvent_t *event) { + pimpl->EventCreate(event); +} + +void GPUContext::EventDestroy(gpuEvent_t &event) { + pimpl->EventDestroy(event); +} + +void GPUContext::EventRecord(gpuEvent_t &event, + gpuStream_t &stream) { + pimpl->EventRecord(event, stream); +} + +void GPUContext::IpcGetEventHandle(gpuIpcEventHandle_t *eventHandle, gpuEvent_t &event) { + pimpl->IpcGetEventHandle(eventHandle, event); +} + +void GPUContext::IpcOpenEventHandle(gpuEvent_t *event, + gpuIpcEventHandle_t &eventHandle) { + pimpl->IpcOpenEventHandle(event, eventHandle); +} + +void GPUContext::StreamCreate(gpuStream_t *stream) { + pimpl->StreamCreate(stream); +} + +void GPUContext::StreamSynchronize(gpuStream_t stream) { + pimpl->StreamSynchronize(stream); +} + +int GPUContext::GetDevice() { + return pimpl->GetDevice(); +} + +void GPUContext::SetDevice(int device) { + pimpl->SetDevice(device); +} + +void GPUContext::MemcpyAsyncD2D(void *dst, + const void *src, + size_t count, + gpuStream_t stream) { + pimpl->MemcpyAsyncD2D(dst, src, count, stream); +} + +void GPUContext::MemcpyAsyncH2D(void *dst, + const void *src, + size_t count, + gpuStream_t stream) { + pimpl->MemcpyAsyncH2D(dst, src, count, stream); +} + +void GPUContext::MemcpyAsyncD2H(void *dst, + const void *src, + size_t count, + gpuStream_t stream) { + pimpl->MemcpyAsyncD2H(dst, src, count, stream); +} + +void GPUContext::MemcpyD2D(void *dst, + const void *src, + size_t count) { + pimpl->MemcpyD2D(dst, src, count); +} + +void GPUContext::DeviceSynchronize() { + pimpl->DeviceSynchronize(); +} + +void GPUContext::StreamWaitEvent(gpuStream_t &stream, gpuEvent_t &event) { + pimpl->StreamWaitEvent(stream, event); +} diff --git a/src/common/hip_operations.cc b/src/common/hip_operations.cc new file mode 100755 index 0000000..2d958fe --- /dev/null +++ b/src/common/hip_operations.cc @@ -0,0 +1,133 @@ +// Copyright 2016 The TensorFlow Authors. All Rights Reserved. +// Modifications copyright (C) 2019 Uber Technologies, Inc. +// Modifications copyright (C) 2022 IST Austria. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ============================================================================= + +#include "gpu_context.h" + +#include +namespace cgx { +namespace common { + +class GPUContext::impl { +public: + void ErrorCheck(std::string op_name, hipError_t hip_result) { + if (hip_result != hipSuccess) { + throw std::logic_error( + std::string(op_name) + " failed: " + hipGetErrorString(hip_result)); + } + } + + void EventCreate(hipEvent_t *event) { + ErrorCheck("hipEventCreateWithFlags", + hipEventCreateWithFlags(event, + hipEventDisableTiming + | hipEventInterprocess)); + } + + void EventRecord(hipEvent_t &event, hipStream_t &stream) { + ErrorCheck("hipEventRecord", hipEventRecord(event, stream)); + } + + void EventDestroy(hipEvent_t &event) { + ErrorCheck("hipEventDestroy", hipEventDestroy(event)); + } + + void IpcGetEventHandle(hipIpcEventHandle_t *eventHandle, hipEvent_t &event) { + ErrorCheck("hipIpcGetEventHandle", + hipIpcGetEventHandle(eventHandle, event)); + } + + void IpcOpenEventHandle(hipEvent_t *event, hipIpcEventHandle_t &eventHandle) { + ErrorCheck("hipIpcOpenEventHandle", + hipIpcOpenEventHandle(event, eventHandle)); + } + + void StreamCreate(hipStream_t *stream) { + int greatest_priority; + ErrorCheck("hipDeviceGetStreamPriorityRange", + hipDeviceGetStreamPriorityRange(NULL, &greatest_priority)); + ErrorCheck("hipStreamCreateWithPriority", + hipStreamCreateWithPriority(stream, + hipStreamNonBlocking, + greatest_priority)); + } + + void StreamSynchronize(hipStream_t stream) { + ErrorCheck("hipStreamSynchronize", hipStreamSynchronize(stream)); + } + + int GetDevice() { + int device; + ErrorCheck("hipGetDevice", hipGetDevice(&device)); + return device; + } + + void SetDevice(int device) { + ErrorCheck("hipSetDevice", hipSetDevice(device)); + } + + void MemcpyAsyncD2D(void *dst, + const void *src, + size_t count, + hipStream_t stream) { + ErrorCheck("hipMemcpyAsync", + hipMemcpyAsync(dst, + src, + count, + hipMemcpyDeviceToDevice, + stream)); + } + + void MemcpyAsyncH2D(void *dst, + const void *src, + size_t count, + hipStream_t stream) { + ErrorCheck("hipMemcpyAsync", + hipMemcpyAsync(dst, src, count, hipMemcpyHostToDevice, stream)); + } + + void MemcpyAsyncD2H(void *dst, + const void *src, + size_t count, + hipStream_t stream) { + ErrorCheck("hipMemcpyAsync", + hipMemcpyAsync(dst, src, count, hipMemcpyDeviceToHost, stream)); + } + + void MemcpyD2D(void *dst, const void *src, size_t count) { + ErrorCheck("hipMemcpyAsync", + hipMemcpy(dst, src, count, hipMemcpyDeviceToDevice)); + } + + void DeviceSynchronize() { + ErrorCheck("hipDeviceSynchronize", hipDeviceSynchronize()); + } + + void StreamWaitEvent(hipStream_t stream, hipEvent_t &event) { + ErrorCheck("hipStreamWaitEvent", hipStreamWaitEvent(stream, event, 0)); + } + +private: + // We reuse HIP events as it appears that their creation carries non-zero cost. + std::unordered_map> hip_events; + std::mutex hip_events_mutex; +}; + +#include "gpu_context_impl.cc" + +} // namespace common +} // namespace cgx + diff --git a/src/common/layer.cc b/src/common/layer.cc new file mode 100755 index 0000000..f0015b8 --- /dev/null +++ b/src/common/layer.cc @@ -0,0 +1,45 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include "layer.h" + +namespace cgx { +namespace common { + +Layer::Layer(const at::Tensor &tensor) { + data_ = tensor.data_ptr(); + element_size_ = tensor.element_size(); + numel_ = tensor.numel(); + scalar_type_ = tensor.scalar_type(); + device_index_ = tensor.get_device(); + layer_id_ = std::make_pair(0, 0); +} + +Layer::Layer(const at::Tensor &tensor, const LayerId &layer_id, + void *ptr, int numel) { + layer_id_ = layer_id; + data_ = ptr; + numel_ = numel; + element_size_ = tensor.element_size(); + scalar_type_ = tensor.scalar_type(); + device_index_ = tensor.get_device(); +} + +} // namespace common +} // namespace cgx \ No newline at end of file diff --git a/src/common/layer.h b/src/common/layer.h new file mode 100755 index 0000000..696d09e --- /dev/null +++ b/src/common/layer.h @@ -0,0 +1,49 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include +#include + +namespace cgx { +namespace common { +using LayerId = std::pair; + +struct Layer { + Layer(const at::Tensor& tensor); + Layer(const at::Tensor& tensor, const LayerId& layer_id, + void* ptr, int numel); + const LayerId& layer_id() const {return layer_id_;} + void* data_ptr() const {return data_;} + int numel() const { return numel_; } + size_t element_size() const {return element_size_;}; + at::ScalarType scalar_type() const { return scalar_type_;} + const int64_t& device_index() const { return device_index_; } +private: + LayerId layer_id_; + void* data_; + int numel_; + size_t element_size_; + at::ScalarType scalar_type_; + int64_t device_index_; +}; + +} // namespace common +} // namespace cgx diff --git a/src/common/mpi_communicator.cc b/src/common/mpi_communicator.cc new file mode 100755 index 0000000..8d40fa0 --- /dev/null +++ b/src/common/mpi_communicator.cc @@ -0,0 +1,88 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include "mpi_communicator.h" + +namespace cgx { +namespace common { + +void MPICommunicator::Init(int world_size, void *ctx) { + if (recv_requests.size() == 0) { + for (int i = 0; i < world_size; i++) { + recv_requests.push_back(MPI_REQUEST_NULL); + send_requests.push_back(MPI_REQUEST_NULL); + } + } + comm_ = *(static_cast(ctx)); + MPI_CHECK(MPI_Comm_rank(comm_, &rank_)); + world_size_ = world_size; + MPI_Barrier(comm_); +} + +void MPICommunicator::IRecv(void *buf, + size_t buf_size, + int peer_rank, + gpuStream_t stream) { + gpu_context_->StreamSynchronize(stream); + MPI_CHECK(MPI_Irecv(buf, buf_size, MPI_UNSIGNED_CHAR, + peer_rank, 0, comm_, &recv_requests.at(peer_rank))); +} + +void MPICommunicator::ISend(void *buf, + size_t buf_size, + int peer_rank, + gpuStream_t stream) { + gpu_context_->StreamSynchronize(stream); + MPI_CHECK(MPI_Wait(&send_requests.at(peer_rank), MPI_STATUSES_IGNORE)); + MPI_CHECK(MPI_Isend(buf, buf_size, MPI_UNSIGNED_CHAR, + peer_rank, 0, comm_, &send_requests.at(peer_rank))); +} + +void MPICommunicator::WaitAllSend() { + for (int peer_rank = 0; peer_rank < world_size_; peer_rank++) { + if (send_requests.at(peer_rank) == MPI_REQUEST_NULL) + continue; + MPI_CHECK(MPI_Wait(&send_requests.at(peer_rank), MPI_STATUSES_IGNORE)); + } +} + +int MPICommunicator::TestRecv(int peer_rank) { + int flag = 0; + MPI_CHECK(MPI_Test(&recv_requests.at(peer_rank), &flag, MPI_STATUSES_IGNORE)); + return flag; +} + +void MPICommunicator::WaitRecv(int peer_rank) { + MPI_CHECK(MPI_Wait(&recv_requests.at(peer_rank), MPI_STATUSES_IGNORE)); +} + +void MPICommunicator::WaitSend(int peer_rank) { + MPI_CHECK(MPI_Wait(&send_requests.at(peer_rank), MPI_STATUSES_IGNORE)); +} + +void MPICommunicator::WaitAllRecv() { + for (int peer_rank = 0; peer_rank < world_size_; peer_rank++) { + if (send_requests.at(peer_rank) == MPI_REQUEST_NULL) + continue; + MPI_CHECK(MPI_Wait(&recv_requests.at(peer_rank), MPI_STATUSES_IGNORE)); + } +} + +} // namespace common +} // namespace cgx diff --git a/src/common/mpi_communicator.h b/src/common/mpi_communicator.h new file mode 100755 index 0000000..e4c013e --- /dev/null +++ b/src/common/mpi_communicator.h @@ -0,0 +1,46 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once +#include "communicator.h" + +namespace cgx { +namespace common { + +struct MPICommunicator : public Communicator { + MPICommunicator(std::shared_ptrgpu_context) : Communicator(gpu_context){ + communicator_type_ = CommunicatorType::MPI; + } + virtual void Init(int world_size, void *ctx) override; + virtual void ISend(void *buf, size_t buf_size, int peer_rank, + gpuStream_t stream) override; + virtual void IRecv(void *buf, size_t buf_size, int peer_rank, + gpuStream_t stream) override; + virtual void WaitSend(int peer_rank) override; + virtual void WaitRecv(int peer_rank) override; + virtual void WaitAllSend() override; + virtual void WaitAllRecv() override; + virtual int TestRecv(int rank) override; +protected: + std::vector send_requests; + std::vector recv_requests; +}; + +} // namespace common +} // namespace cgx \ No newline at end of file diff --git a/src/common/mpi_context.cc b/src/common/mpi_context.cc new file mode 100755 index 0000000..d18a664 --- /dev/null +++ b/src/common/mpi_context.cc @@ -0,0 +1,55 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include "mpi_context.h" +#include "common.h" + +namespace cgx { +namespace common { + +MPIContext::MPIContext() { + MPI_CHECK(MPI_Comm_dup(MPI_COMM_WORLD, &global_comm_)); + MPI_CHECK(MPI_Comm_split_type(global_comm_, MPI_COMM_TYPE_SHARED, 0, MPI_INFO_NULL, + &local_comm_)); + int local_rank, world_rank; + MPI_CHECK(MPI_Comm_rank(global_comm_, &world_rank)); + MPI_CHECK(MPI_Comm_rank(local_comm_, &local_rank)); + + // Create cross node communicator. + MPI_CHECK(MPI_Comm_split(global_comm_, local_rank, world_rank, &cross_comm_)); +} + +int MPIContext::GetSize(MPI_Comm comm) const { + int size; + MPI_CHECK(MPI_Comm_size(comm, &size)); + return size; +} + +int MPIContext::GetRank(MPI_Comm comm) const { + int rank; + MPI_CHECK(MPI_Comm_rank(comm, &rank)); + return rank; +} + +void MPIContext::Barrier(MPI_Comm comm) const { + MPI_CHECK(MPI_Barrier(comm)); +} + +} // namespace common +} // namespace cgx diff --git a/src/common/mpi_context.h b/src/common/mpi_context.h new file mode 100755 index 0000000..229af5e --- /dev/null +++ b/src/common/mpi_context.h @@ -0,0 +1,43 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once +#include + +namespace cgx { +namespace common { + +struct MPIContext { + MPIContext(); + MPI_Comm GetGlobalComm() const {return global_comm_;} + MPI_Comm GetLocalComm() const {return local_comm_;} + MPI_Comm GetCrossComm() {return cross_comm_;} + int GetRank(MPI_Comm comm) const; + int GetSize(MPI_Comm comm) const; + void Barrier(MPI_Comm comm) const; +private: + MPI_Comm global_comm_; + MPI_Comm local_comm_; + MPI_Comm cross_comm_; +}; + +} // namespace common +} // namespace cgx + + diff --git a/src/common/nccl_reduce.cc b/src/common/nccl_reduce.cc new file mode 100755 index 0000000..8e2061a --- /dev/null +++ b/src/common/nccl_reduce.cc @@ -0,0 +1,248 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include "nccl_reduce.h" +#include + +namespace cgx { +namespace common { + +std::map ncclDatatype = { + {at::kByte, ncclInt8}, {at::kChar, ncclChar}, {at::kDouble, ncclFloat64}, + {at::kFloat, ncclFloat}, {at::kInt, ncclInt}, {at::kLong, ncclInt64}, + {at::kShort, ncclUint8}, {at::kHalf, ncclHalf}}; + +NCCL_Reduce::NCCL_Reduce(std::shared_ptr gpu_context, + std::shared_ptr compressor, int world_size) + : Reducer(gpu_context, compressor) { + nccl_comm_ = nullptr; + int64_t chunk_size = tensor_fusion_size_; + chunk_size = utils::aligned_size((chunk_size + world_size - 1) / world_size); + int64_t buffer_size = chunk_size * world_size + chunk_size * (world_size - 1); + buffer_ = std::make_unique(buffer_size); + void *buffer_data = buffer_->RawPointer(); + gradients_send_ = static_cast(buffer_data); + gradients_recv_ = gradients_send_ + chunk_size * world_size; +} + +void NCCL_Reduce::ErrorCheck(std::string op_name, ncclResult_t nccl_result) { + if (nccl_result != ncclSuccess) { + ncclCommAbort(nccl_comm_); + throw std::runtime_error(std::string(op_name) + + " failed: " + ncclGetErrorString(nccl_result)); + } +} + +void NCCL_Reduce::Init(void *comm_p) { + if (nccl_comm_ != nullptr) + return; + MPI_Comm comm = *(static_cast(comm_p)); + int world_size, rank; + MPI_CHECK(MPI_Comm_size(comm, &world_size)); + MPI_CHECK(MPI_Comm_rank(comm, &rank)); + ncclUniqueId nccl_id; + if (rank == 0) { + ErrorCheck("ncclGetUniqueId", ncclGetUniqueId(&nccl_id)); + } + MPI_CHECK(MPI_Bcast(&nccl_id, sizeof(nccl_id), MPI_BYTE, 0, comm)); + auto nccl_result = ncclCommInitRank(&nccl_comm_, world_size, nccl_id, rank); + ErrorCheck("ncclCommInitRank", nccl_result); + MPI_CHECK(MPI_Barrier(comm)); +} + +int NCCL_Reduce::AllreduceDivision(int num_elements, int global_offset, + std::vector &layers, void *comm_p, + gpuStream_t gpu_stream, + bool do_compression) { + if (do_compression) { + return AllreduceCompressed(num_elements, global_offset, layers, comm_p, + gpu_stream); + } else { + return AllreduceUncompressed(num_elements, global_offset, layers, comm_p, + gpu_stream); + } +} + +int NCCL_Reduce::AllReduceAlltoAll(int num_elements, int global_offset, + std::vector &layers, void *comm, + gpuStream_t gpu_stream) { + return AllreduceUncompressed(num_elements, global_offset, layers, comm, + gpu_stream); +} + +int NCCL_Reduce::AllreduceUncompressed(int num_elements, int global_offset, + std::vector &layers, void *comm_p, + gpuStream_t gpu_stream) { + Init(comm_p); + unsigned char *layers_data = gradients_send_; + FuseLayerData(&layers_data, layers, num_elements, global_offset, gpu_stream); + auto nccl_result = ncclAllReduce(layers_data, layers_data, num_elements, + ncclDatatype.at(layers[0].scalar_type()), + ncclSum, nccl_comm_, gpu_stream); + ErrorCheck("ncclAllReduce", nccl_result); + UnfuseLayerData(layers_data, layers, num_elements, gpu_stream); + return 0; +} + +int NCCL_Reduce::AllreduceCompressed(int num_elements, int global_offset, + std::vector &layers, void *comm_p, + gpuStream_t gpu_stream) { + Init(comm_p); + MPI_Comm mpi_comm = *(static_cast(comm_p)); + int world_size, rank; + MPI_CHECK(MPI_Comm_size(mpi_comm, &world_size)); + MPI_CHECK(MPI_Comm_rank(mpi_comm, &rank)); + std::vector chunk_sizes, offsets; + Quantizer::GetSizesAndOffsets(num_elements, world_size, global_offset, layers, + offsets, chunk_sizes); + compressor_->Init(layers[0].element_size(), gpu_stream); + unsigned char *send_buf = gradients_send_; + unsigned char *recv_buf = gradients_recv_; + std::vector nodes; + std::vector compressed_sizes(world_size, 0); + int send_num_elems = 0; + int send_compressed_size = 0; + int start_elem = offsets[rank]; + int recv_num_elems = chunk_sizes[rank]; + int recv_compressed_size = utils::aligned_size( + compressor_->BufferSize(recv_num_elems, layers, start_elem)); + for (int node_rank = 0; node_rank < world_size; node_rank++) { + if (node_rank == rank) { + continue; + } + int start_offset = offsets[node_rank]; + send_num_elems = chunk_sizes[node_rank]; + + send_compressed_size = utils::aligned_size(compressor_->Compress( + send_buf, layers, start_offset, send_num_elems, gpu_stream)); + compressed_sizes[node_rank] = send_compressed_size; + send_buf += send_compressed_size; + } + send_buf = gradients_send_; + + ErrorCheck("ncclGroupStart", ncclGroupStart()); + for (int node_rank = 0; node_rank < world_size; node_rank++) { + if (node_rank == rank) { + continue; + } + send_compressed_size = compressed_sizes[node_rank]; + ErrorCheck("ncclRecv", ncclRecv(recv_buf, recv_compressed_size, ncclChar, + node_rank, nccl_comm_, gpu_stream)); + ErrorCheck("ncclSend", ncclSend(send_buf, send_compressed_size, ncclChar, + node_rank, nccl_comm_, gpu_stream)); + recv_buf += recv_compressed_size; + send_buf += send_compressed_size; + } + ErrorCheck("ncclGroupEnd", ncclGroupEnd()); + + recv_buf = gradients_recv_; + for (int i = 0; i < world_size - 1; i++) { + compressor_->Decompress(recv_buf, layers, start_elem, recv_num_elems, true, + gpu_stream); + recv_buf += recv_compressed_size; + } + // End of the first round. + + compressor_->Compress(gradients_send_, layers, start_elem, recv_num_elems, + gpu_stream); + compressor_->Decompress(gradients_send_, layers, start_elem, recv_num_elems, + false, gpu_stream); + recv_buf = gradients_recv_; + send_compressed_size = recv_compressed_size; + ErrorCheck("ncclGroupStart", ncclGroupStart()); + for (int node_rank = 0; node_rank < world_size; node_rank++) { + if (node_rank == rank) { + continue; + } + int their_start_offset = offsets[node_rank]; + recv_compressed_size = compressed_sizes[node_rank]; + ErrorCheck("ncclRecv", ncclRecv(recv_buf, recv_compressed_size, ncclChar, + node_rank, nccl_comm_, gpu_stream)); + ErrorCheck("ncclSend", + ncclSend(gradients_send_, send_compressed_size, ncclChar, + node_rank, nccl_comm_, gpu_stream)); + recv_buf += recv_compressed_size; + } + ErrorCheck("ncclGroupEnd", ncclGroupEnd()); + + recv_buf = gradients_recv_; + for (int node_rank = 0; node_rank < world_size; node_rank++) { + if (node_rank == rank) { + continue; + } + // Offset of the received chunk + int their_start_offset = offsets[node_rank]; + recv_num_elems = chunk_sizes[node_rank]; + recv_compressed_size = compressed_sizes[node_rank]; + compressor_->Decompress(recv_buf, layers, their_start_offset, + recv_num_elems, false, gpu_stream); + recv_buf += recv_compressed_size; + } + return 0; +} + +int NCCL_Reduce::Broadcast(int num_elements, int global_offset, + std::vector &layers, void *comm_p, + gpuStream_t gpu_stream, bool do_compression) { + Init(comm_p); + unsigned char *layers_data = gradients_send_; + FuseLayerData(&layers_data, layers, num_elements, global_offset, gpu_stream); + + auto nccl_result = ncclBcast(layers_data, num_elements, + ncclDatatype.at(layers[0].scalar_type()), 0, + nccl_comm_, gpu_stream); + ErrorCheck("ncclBcast", nccl_result); + UnfuseLayerData(layers_data, layers, num_elements, gpu_stream); + return 0; +} + +void NCCL_Reduce::FuseLayerData(unsigned char **layers_data, + std::vector &layers, int num_elements, + int global_offset, gpuStream_t stream) { + auto element_size = utils::get_sizeof(layers[0].scalar_type()); + + if (layers.size() > 1) { + auto data_tmp = *layers_data; + for (auto &layer : layers) { + gpu_context_->MemcpyAsyncD2D(data_tmp, layer.data_ptr(), + layer.numel() * element_size, stream); + data_tmp += layer.numel() * element_size; + } + } else { + *layers_data = static_cast(layers[0].data_ptr()) + + global_offset * element_size; + } +} + +void NCCL_Reduce::UnfuseLayerData(unsigned char *layers_data, + std::vector &layers, int num_elements, + gpuStream_t stream) { + auto element_size = utils::get_sizeof(layers[0].scalar_type()); + + if (layers.size() > 1) { + for (auto &layer : layers) { + gpu_context_->MemcpyAsyncD2D(layer.data_ptr(), layers_data, + layer.numel() * element_size, stream); + layers_data += layer.numel() * element_size; + } + } +} + +} // namespace common +} // namespace cgx diff --git a/src/common/nccl_reduce.h b/src/common/nccl_reduce.h new file mode 100755 index 0000000..f09d9a8 --- /dev/null +++ b/src/common/nccl_reduce.h @@ -0,0 +1,61 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once +#include "reducer.h" +#include + +namespace cgx { +namespace common { + +class NCCL_Reduce : public Reducer { +public: + NCCL_Reduce(std::shared_ptr gpu_context, + std::shared_ptr compressor, int world_size); + int AllReduceAlltoAll(int num_elements, int global_offset, + std::vector &layers, void *comm_p, + gpuStream_t gpu_stream) override; + int AllreduceDivision(int num_elements, int global_offset, + std::vector &tensors, void *comm, + gpuStream_t gpu_stream, bool do_compression) override; + int Broadcast(int num_elements, int global_offset, std::vector &layers, + void *comm, gpuStream_t gpu_stream, + bool do_compression) override; + +private: + void Init(void *comm); + void ErrorCheck(std::string op_name, ncclResult_t nccl_result); + void FuseLayerData(unsigned char **layers_data, std::vector &layers, + int num_elements, int global_offset, gpuStream_t stream); + void UnfuseLayerData(unsigned char *layers_data, std::vector &layers, + int num_elements, gpuStream_t stream); + + int AllreduceUncompressed(int num_elements, int global_offset, + std::vector &tensors, void *comm, + gpuStream_t gpu_stream); + + int AllreduceCompressed(int num_elements, int global_offset, + std::vector &tensors, void *comm, + gpuStream_t gpu_stream); + + ncclComm_t nccl_comm_; +}; + +} // namespace common +} // namespace cgx diff --git a/src/common/reducer.cc b/src/common/reducer.cc new file mode 100755 index 0000000..ea9cbd3 --- /dev/null +++ b/src/common/reducer.cc @@ -0,0 +1,162 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include "reducer.h" +namespace cgx { +namespace common { + +Reducer::Reducer(std::shared_ptr gpu_context, + std::shared_ptr compressor, + std::shared_ptr communicator) + : compressor_(compressor), gpu_context_(gpu_context), + communicator_(communicator) { + unsigned int fusion_size_mb = + utils::GetIntEnvOrDefault(FUSION_BUFFER_SIZE_MB, FUSION_SIZE_DEFAULT_MB); + tensor_fusion_size_ = std::max(fusion_size_mb * 1024 * 1024, MIN_FUSION_SIZE); +} + +int Reducer::AllReduceAlltoAll(int num_elements, int global_offset, + std::vector &layers, void *comm_p, + gpuStream_t gpu_stream) { + MPI_Comm comm = *(static_cast(comm_p)); + int world_size, rank; + MPI_CHECK(MPI_Comm_size(comm, &world_size)); + MPI_CHECK(MPI_Comm_rank(comm, &rank)); + unsigned char *send_buf = gradients_send_; + unsigned char *recv_buf = gradients_recv_; + size_t element_size = layers[0].element_size(); + size_t buf_size = num_elements * element_size; + + communicator_->Init(world_size, comm_p); + if (layers.size() > 1) { + for (auto &layer: layers) { + gpu_context_->MemcpyAsyncD2D(send_buf, + layer.data_ptr(), + layer.numel() * element_size, + gpu_stream); + send_buf += layer.numel() * element_size; + } + send_buf = gradients_send_; + } else { + send_buf = static_cast(layers[0].data_ptr()) + global_offset * element_size; + } + + std::vector nodes; + for (int node_rank = 0; node_rank < world_size; node_rank++) { + if (node_rank == rank) + continue; + communicator_->ISend(send_buf, buf_size, node_rank, + gpu_stream); + communicator_->IRecv(recv_buf, buf_size, node_rank, gpu_stream); + nodes.push_back(node_rank); + recv_buf += buf_size; + } + communicator_->WaitAllSend(); + + while (nodes.size() > 0) { + for (int i = 0; i < nodes.size(); i++) { + auto &node_rank = nodes.at(i); + if (communicator_->TestRecv(node_rank) > 0) { + auto idx = node_rank - ((node_rank > rank) ? 1 : 0); + Compressor::Add(num_elements, gradients_recv_ + idx * buf_size, + send_buf, send_buf, layers[0].scalar_type(), gpu_stream); + nodes.erase(nodes.begin() + i); + } + } + } + if (layers.size() > 1) { + for (auto &layer: layers) { + gpu_context_->MemcpyAsyncD2D(layer.data_ptr(), + send_buf, + layer.numel() * element_size, + gpu_stream); + send_buf += layer.numel() * element_size; + } + } + return 0; +} + +int Reducer::Broadcast(int num_elements, int global_offset, + std::vector &layers, void *comm_p, + gpuStream_t gpu_stream, bool do_compression) { + MPI_Comm comm = *(static_cast(comm_p)); + int world_size, rank; + MPI_CHECK(MPI_Comm_size(comm, &world_size)); + MPI_CHECK(MPI_Comm_rank(comm, &rank)); + int element_size = layers[0].element_size(); + + communicator_->Init(world_size, comm_p); + if (do_compression) + compressor_->Init(layers[0].element_size(), gpu_stream); + if (rank == 0) { + unsigned char *send_buf = gradients_send_; + size_t send_size; + if (do_compression) { + send_size = utils::aligned_size(compressor_->Compress( + gradients_send_, layers, global_offset, num_elements, gpu_stream)); + compressor_->Decompress(gradients_send_, layers, num_elements, + global_offset, false, gpu_stream); + send_buf = gradients_send_; + } else { + if (layers.size() > 1) { + for (auto &layer : layers) { + gpu_context_->MemcpyAsyncD2D(send_buf, layer.data_ptr(), + layer.numel() * element_size, + gpu_stream); + send_buf += layer.numel() * element_size; + } + send_buf = gradients_send_; + } else { + send_buf = static_cast(layers[0].data_ptr()); + } + send_size = num_elements * element_size; + } + for (int node_rank = 1; node_rank < world_size; node_rank++) { + communicator_->ISend(send_buf, send_size, node_rank, gpu_stream); + } + communicator_->WaitAllSend(); + } else { + size_t recv_size = 0; + unsigned char *recv_buf = gradients_send_; + if (do_compression) { + recv_size = utils::aligned_size( + compressor_->BufferSize(num_elements, layers, global_offset)); + } else { + recv_size = num_elements * element_size; + if (layers.size() == 1) + recv_buf = static_cast(layers[0].data_ptr()); + } + communicator_->IRecv(recv_buf, recv_size, 0, gpu_stream); + communicator_->WaitRecv(0); + if (do_compression) { + compressor_->Decompress(recv_buf, layers, global_offset, num_elements, + false, gpu_stream); + } else if (layers.size() > 1) { + for (auto &layer : layers) { + gpu_context_->MemcpyAsyncD2D(layer.data_ptr(), recv_buf, + layer.numel() * element_size, gpu_stream); + recv_buf += layer.numel() * element_size; + } + } + } + return 0; +} + +} // namespace common +} // namespace cgx diff --git a/src/common/reducer.h b/src/common/reducer.h new file mode 100755 index 0000000..80f39e0 --- /dev/null +++ b/src/common/reducer.h @@ -0,0 +1,77 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "common.h" +#include "compressor.h" +#include "gpu_context.h" +#include "utils.h" +#include + +#include "mpi_communicator.h" +#if HAVE_CUDA +#include "shm_communicator.h" +#endif + +namespace cgx { +namespace common { + +class Reducer { +public: + Reducer(std::shared_ptr gpu_context, + std::shared_ptr compressor, + std::shared_ptr communicator= nullptr); + + virtual ~Reducer() = default; + virtual int AllreduceDivision(int num_elements, int global_offset, + std::vector &layers, + void *comm, gpuStream_t gpu_stream, + bool do_compression) = 0; + virtual int AllReduceAlltoAll(int num_elements, int global_offset, + std::vector &layers, + void *comm, gpuStream_t gpu_stream); + virtual int Broadcast(int num_elements, int global_offset, + std::vector &layers, + void *comm, gpuStream_t gpu_stream, bool do_compression); +protected: + std::shared_ptr compressor_; + std::shared_ptr communicator_; + std::shared_ptr gpu_context_; + + // We only need some framework agnostic Buffer Manager so we reuse + // FussionBufferManager. Our usage of it is not related to tensor fusion + // buffer. + std::unique_ptr buffer_; + unsigned char *gradients_send_ = nullptr; + unsigned char *gradients_recv_ = nullptr; + size_t tensor_fusion_size_; +}; + +class MPIReducer : public Reducer { +public: + MPIReducer(std::shared_ptr gpu_context, + std::shared_ptr compressor, + std::shared_ptr communicator) + : Reducer(gpu_context, compressor, communicator) {} +}; + +void printDebug(unsigned char *buf, int numel); +} // namespace common +} // namespace cgx diff --git a/src/common/ring.cc b/src/common/ring.cc new file mode 100755 index 0000000..0897f7a --- /dev/null +++ b/src/common/ring.cc @@ -0,0 +1,229 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include "ring.h" + +namespace cgx { +namespace common { + +MPI_Allreduce_Ring::MPI_Allreduce_Ring( + std::shared_ptr gpu_context, + std::shared_ptr compressor, + std::shared_ptr communicator, int world_size) + : MPIReducer(gpu_context, compressor, communicator) { + int64_t chunk_size = tensor_fusion_size_; + chunk_size = utils::aligned_size((chunk_size + world_size - 1) / world_size); + int64_t buffer_size = chunk_size * world_size + chunk_size * (world_size - 1); + + buffer_ = std::make_unique(buffer_size); + void *buffer_data = buffer_->RawPointer(); + gradients_send_ = static_cast(buffer_data); + gradients_recv_ = gradients_send_ + chunk_size * world_size; +} + +int MPI_Allreduce_Ring::AllreduceDivision(int num_elements, int global_offset, + std::vector &tensors, + void *comm_p, gpuStream_t gpu_stream, + bool do_compression) { + int status; + if (do_compression) { + status = AllreduceDivisionCompressed(num_elements, global_offset, tensors, + comm_p, gpu_stream); + } else { + status = AllreduceDivisionUncompressed(num_elements, global_offset, tensors, + comm_p, gpu_stream); + } + MPI_Comm comm = *(static_cast(comm_p)); + MPI_CHECK(MPI_Barrier(comm)); + return status; +} + +int MPI_Allreduce_Ring::AllreduceDivisionUncompressed( + int num_elements, int global_offset, std::vector &layers, + void *comm_p, gpuStream_t gpu_stream) { + MPI_Comm comm = *(static_cast(comm_p)); + int world_size, rank; + std::vector chunk_sizes, offsets; + unsigned char *send_buf = gradients_send_; + unsigned char *send_buf_base = send_buf; + unsigned char *recv_buf = gradients_recv_; + int element_size = layers[0].element_size(); + + MPI_CHECK(MPI_Comm_size(comm, &world_size)); + MPI_CHECK(MPI_Comm_rank(comm, &rank)); + Compressor::GetSizesAndOffsets(num_elements, world_size, global_offset, layers, + offsets, chunk_sizes); + communicator_->Init(world_size, comm_p); + if (layers.size() > 1) { + for (auto &layer : layers) { + gpu_context_->MemcpyAsyncD2D(send_buf, layer.data_ptr(), + layer.numel() * element_size, gpu_stream); + send_buf += layer.numel() * element_size; + } + send_buf = send_buf_base; + } else { + send_buf = static_cast(layers[0].data_ptr()) + + element_size * global_offset; + send_buf_base = send_buf; + } + + // Receive from your left neighbor with wrap-around. + const size_t recv_from = (rank - 1 + world_size) % world_size; + // Send to your right neighbor with wrap-around. + const size_t send_to = (rank + 1) % world_size; + + int recv_segment_idx, send_segment_idx; + int buf_send_idx, buf_recv_idx; + int send_size, recv_size; + for (int i = 0; i < world_size - 1; i++) { + recv_segment_idx = (rank - i - 1 + world_size) % world_size; + send_segment_idx = (rank - i + world_size) % world_size; + buf_send_idx = offsets[send_segment_idx]; + buf_recv_idx = offsets[recv_segment_idx]; + communicator_->ISend(send_buf_base + buf_send_idx * element_size, + chunk_sizes[send_segment_idx] * element_size, send_to, + gpu_stream); + communicator_->IRecv(recv_buf, chunk_sizes[recv_segment_idx] * element_size, + recv_from, gpu_stream); + communicator_->WaitSend(send_to); + communicator_->WaitRecv(recv_from); + Compressor::Add(chunk_sizes[recv_segment_idx], + send_buf_base + buf_recv_idx * element_size, recv_buf, + send_buf_base + buf_recv_idx * element_size, + layers[0].scalar_type(), gpu_stream); + } + for (int i = 0; i < world_size - 1; i++) { + send_segment_idx = (rank - i + world_size + 1) % world_size; + buf_send_idx = offsets[send_segment_idx]; + send_buf = send_buf_base + buf_send_idx * element_size; + send_size = chunk_sizes[send_segment_idx] * element_size; + + recv_segment_idx = (rank - i + world_size) % world_size; + buf_recv_idx = offsets[recv_segment_idx]; + recv_size = chunk_sizes[recv_segment_idx] * element_size; + recv_buf = send_buf_base + buf_recv_idx * element_size; + + communicator_->ISend(send_buf, send_size, send_to, gpu_stream); + communicator_->IRecv(recv_buf, recv_size, recv_from, gpu_stream); + communicator_->WaitSend(send_to); + communicator_->WaitRecv(recv_from); + send_buf += send_size; + } + send_buf = send_buf_base; + if (layers.size() > 1) { + for (auto &layer : layers) { + gpu_context_->MemcpyAsyncD2D(layer.data_ptr(), send_buf, + layer.numel() * element_size, gpu_stream); + send_buf += layer.numel() * element_size; + } + } + return 0; +} + +int MPI_Allreduce_Ring::AllreduceDivisionCompressed(int num_elements, + int global_offset, + std::vector &layers, + void *comm_p, + gpuStream_t gpu_stream) { + MPI_Comm comm = *(static_cast(comm_p)); + int world_size, rank; + MPI_CHECK(MPI_Comm_size(comm, &world_size)); + MPI_CHECK(MPI_Comm_rank(comm, &rank)); + std::vector chunk_sizes, offsets; + Quantizer::GetSizesAndOffsets(num_elements, world_size, global_offset, layers, + offsets, chunk_sizes); + communicator_->Init(world_size, comm_p); + compressor_->Init(layers[0].element_size(), gpu_stream); + int start_elem = offsets[rank] + global_offset; + int recv_num_elems = chunk_sizes[rank]; + int recv_compressed_size = utils::aligned_size( + compressor_->BufferSize(recv_num_elems, layers, start_elem)); + int send_num_elems = 0; + int send_compressed_size = 0; + unsigned char *send_buf = gradients_send_; + unsigned char *recv_buf = gradients_recv_; + int element_size = layers[0].element_size(); + // Receive from your left neighbor with wrap-around. + const size_t recv_from = (rank - 1 + world_size) % world_size; + // Send to your right neighbor with wrap-around. + const size_t send_to = (rank + 1) % world_size; + int recv_segment_idx, send_segment_idx; + int buf_send_idx, buf_recv_idx; + int send_size, recv_size; + + for (int i = 0; i < world_size - 1; i++) { + recv_segment_idx = (rank - i - 1 + world_size) % world_size; + send_segment_idx = (rank - i + world_size) % world_size; + buf_send_idx = offsets[send_segment_idx]; + buf_recv_idx = offsets[recv_segment_idx]; + + recv_size = utils::aligned_size(compressor_->BufferSize( + chunk_sizes[recv_segment_idx], layers, buf_recv_idx)); + communicator_->IRecv(gradients_recv_, recv_size, recv_from, gpu_stream); + + send_size = utils::aligned_size( + compressor_->Compress(gradients_send_, layers, buf_send_idx, + chunk_sizes[send_segment_idx], gpu_stream)); + communicator_->ISend(gradients_send_, send_size, send_to, gpu_stream); + communicator_->WaitRecv(recv_from); + communicator_->WaitSend(send_to); + compressor_->Decompress(gradients_recv_, layers, buf_recv_idx, + chunk_sizes[recv_segment_idx], true, gpu_stream); + } + + send_segment_idx = (rank + world_size + 1) % world_size; + buf_send_idx = offsets[send_segment_idx]; + send_buf = gradients_send_; + send_size = utils::aligned_size(compressor_->Compress( + send_buf, layers, buf_send_idx, chunk_sizes[send_segment_idx], gpu_stream)); + compressor_->Decompress(send_buf, layers, buf_send_idx, + chunk_sizes[send_segment_idx], false, gpu_stream); + recv_buf = send_buf + send_size; + unsigned char *compressed_buf = recv_buf; + + for (int i = 0; i < world_size - 1; i++) { + recv_segment_idx = (rank - i + world_size) % world_size; + buf_recv_idx = offsets[recv_segment_idx]; + recv_size = utils::aligned_size(compressor_->BufferSize( + chunk_sizes[recv_segment_idx], layers, buf_recv_idx)); + communicator_->ISend(send_buf, send_size, send_to, gpu_stream); + communicator_->IRecv(recv_buf, recv_size, recv_from, gpu_stream); + communicator_->WaitSend(send_to); + communicator_->WaitRecv(recv_from); + send_buf += send_size; + recv_buf += recv_size; + send_size = recv_size; + } + + // Decompress all chunks we received. + for (int i = 0; i < world_size - 1; i++) { + recv_segment_idx = (rank - i + world_size) % world_size; + buf_recv_idx = offsets[recv_segment_idx]; + + compressor_->Decompress(compressed_buf, layers, buf_recv_idx, + chunk_sizes[recv_segment_idx], false, gpu_stream); + recv_size = utils::aligned_size(compressor_->BufferSize( + chunk_sizes[recv_segment_idx], layers, buf_recv_idx)); + compressed_buf += recv_size; + } + return 0; +} + +} // namespace common +} // namespace cgx diff --git a/src/common/ring.h b/src/common/ring.h new file mode 100755 index 0000000..a24ad33 --- /dev/null +++ b/src/common/ring.h @@ -0,0 +1,48 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "reducer.h" + +namespace cgx { +namespace common { + +class MPI_Allreduce_Ring : public MPIReducer { +public: + MPI_Allreduce_Ring(std::shared_ptr gpu_context, + std::shared_ptr compressor, + std::shared_ptr communicator, + int world_size); + + int AllreduceDivision(int num_elements, int global_offset, + std::vector &tensors, void *comm, + gpuStream_t gpu_stream, bool do_compression) override; + +private: + int AllreduceDivisionCompressed(int num_elements, int global_offset, + std::vector &layers, void *comm, + gpuStream_t gpu_stream); + int AllreduceDivisionUncompressed(int num_elements, int global_offset, + std::vector &layers, void *comm, + gpuStream_t gpu_stream); +}; + +} // namespace common +} // namespace cgx diff --git a/src/common/scatter_reduce_allgather.cc b/src/common/scatter_reduce_allgather.cc new file mode 100755 index 0000000..5da8283 --- /dev/null +++ b/src/common/scatter_reduce_allgather.cc @@ -0,0 +1,416 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include "scatter_reduce_allgather.h" + +#include "assert.h" +#include "compression/gpu_common.h" + +namespace cgx { +namespace common { + +void printDebug(void *buf, int numel, gpuStream_t gpu_stream) { + float *host_buf = new float[numel]; + cudaStreamSynchronize(gpu_stream); + cudaMemcpy(host_buf, buf, numel * sizeof(float), cudaMemcpyDeviceToHost); + for (int i = 0; i < numel; i++) { + std::cout << host_buf[i] << " "; + } + std::cout << std::endl; + CUDA_CHECK(cudaGetLastError()); + delete[] host_buf; +} + +MPI_Allreduce_ScatterReduceAllgather::MPI_Allreduce_ScatterReduceAllgather( + std::shared_ptr gpu_context, + std::shared_ptr compressor, + std::shared_ptr communicator, int world_size) + : MPIReducer(gpu_context, compressor, communicator) { + int64_t chunk_size = tensor_fusion_size_; + all_to_all_reduction_ = + utils::GetIntEnvOrDefault(DEBUG_ALL_TO_ALL_REDUCTION, 0); + int64_t buffer_size = 0; + if (!all_to_all_reduction_) { + chunk_size = + utils::aligned_size((chunk_size + world_size - 1) / world_size); + buffer_size = chunk_size * world_size + chunk_size * (world_size - 1); + } else { + buffer_size = chunk_size * world_size; + } + + buffer_ = std::make_unique(buffer_size); + void *buffer_data = buffer_->RawPointer(); + if (!all_to_all_reduction_) { + gradients_send_ = static_cast(buffer_data); + gradients_recv_ = gradients_send_ + chunk_size * world_size; + } else { + gradients_send_ = static_cast(buffer_data); + gradients_recv_ = gradients_send_ + chunk_size; + } + remote_buf_compression_enabled_ = + utils::GetIntEnvOrDefault(REMOTE_BUF_COMPRESSION, 0); + assert(!(remote_buf_compression_enabled_ and all_to_all_reduction_)); +} + +int MPI_Allreduce_ScatterReduceAllgather::AllreduceDivision( + int num_elements, int global_offset, std::vector &layers, + void *comm_p, gpuStream_t gpu_stream, bool do_compression) { + MPI_Comm comm = *(static_cast(comm_p)); + int status; + if (do_compression) { + if (all_to_all_reduction_) { + status = AllReduceAlltoAllCompressed(num_elements, global_offset, layers, + comm_p, gpu_stream); + } else if (remote_buf_compression_enabled_ and + communicator_->GetType() != Communicator::MPI) { + status = AllreduceCompressedRemoteBuf(num_elements, global_offset, layers, + comm_p, gpu_stream); + } else { + status = AllreduceCompressed(num_elements, global_offset, layers, comm_p, gpu_stream); + } + } else { + status = AllreduceUncompressed(num_elements, global_offset, layers, comm_p, gpu_stream); + } + return status; +} + +// Perform Scatter-Reduce-AllGather (SRA) +int MPI_Allreduce_ScatterReduceAllgather::AllreduceCompressed( + int num_elements, int global_offset, std::vector &layers, + void *comm_p, gpuStream_t gpu_stream) { + MPI_Comm comm = *(static_cast(comm_p)); + int world_size, rank; + MPI_CHECK(MPI_Comm_size(comm, &world_size)); + MPI_CHECK(MPI_Comm_rank(comm, &rank)); + std::vector chunk_sizes, offsets; + Quantizer::GetSizesAndOffsets(num_elements, world_size, global_offset, layers, + offsets, chunk_sizes); + communicator_->Init(world_size, comm_p); + compressor_->Init(layers[0].element_size(), gpu_stream); + int start_elem = offsets[rank]; + int recv_num_elems = chunk_sizes[rank]; + int recv_compressed_size = utils::aligned_size( + compressor_->BufferSize(recv_num_elems, layers, start_elem)); + int send_num_elems = 0; + int send_compressed_size = 0; + unsigned char *send_buf = gradients_send_; + unsigned char *recv_buf = gradients_recv_; + std::queue send_sizes; + std::vector nodes; + for (int node_rank = 0; node_rank < world_size; node_rank++) { + if (node_rank == rank) { + continue; + } + int start_offset = offsets[node_rank]; + send_num_elems = chunk_sizes[node_rank]; + + send_compressed_size = utils::aligned_size(compressor_->Compress( + send_buf, layers, start_offset, send_num_elems, gpu_stream)); + send_buf += send_compressed_size; + send_sizes.push(send_compressed_size); + } + send_buf = gradients_send_; + for (int node_rank = 0; node_rank < world_size; node_rank++) { + if (node_rank == rank) { + continue; + } + communicator_->IRecv(recv_buf, recv_compressed_size, node_rank, + gpu_stream); + send_compressed_size = send_sizes.front(); + communicator_->ISend(send_buf, send_compressed_size, node_rank, + gpu_stream); + recv_buf += recv_compressed_size; + send_buf += send_compressed_size; + send_sizes.pop(); + nodes.push_back(node_rank); + } + while (nodes.size() > 0) { + for (int i = 0; i < nodes.size(); i++) { + auto &node_rank = nodes.at(i); + if (communicator_->TestRecv(node_rank) > 0) { + auto idx = node_rank - ((node_rank > rank) ? 1 : 0); + compressor_->Decompress(gradients_recv_ + recv_compressed_size * idx, + layers, start_elem, recv_num_elems, true, + gpu_stream); + nodes.erase(nodes.begin() + i); + } + } + } + communicator_->WaitAllSend(); + // End of the first round. + compressor_->Compress(gradients_send_, layers, start_elem, recv_num_elems, + gpu_stream); + compressor_->Decompress(gradients_send_, layers, start_elem, recv_num_elems, + false, gpu_stream); + recv_buf = gradients_recv_; + // second round of SRA. receive the sums from other nodes. Perform + send_compressed_size = recv_compressed_size; + std::vector> recv_offsets; + int64_t recv_acc_size = 0; + for (int node_rank = 0; node_rank < world_size; node_rank++) { + if (node_rank == rank) { + continue; + } + int their_start_offset = offsets[node_rank]; + recv_num_elems = chunk_sizes[node_rank]; + recv_compressed_size = utils::aligned_size( + compressor_->BufferSize(recv_num_elems, layers, their_start_offset)); + communicator_->IRecv(recv_buf, recv_compressed_size, node_rank, + gpu_stream); + communicator_->ISend(gradients_send_, send_compressed_size, node_rank, + gpu_stream); + + recv_buf += recv_compressed_size; + recv_offsets.emplace_back(recv_acc_size, their_start_offset, + recv_num_elems); + recv_acc_size += recv_compressed_size; + nodes.push_back(node_rank); + } + int their_start_offset; + while (nodes.size() > 0) { + for (int i = 0; i < nodes.size(); i++) { + auto &node_rank = nodes.at(i); + if (communicator_->TestRecv(node_rank) > 0) { + auto idx = node_rank - ((node_rank > rank) ? 1 : 0); + std::tie(recv_acc_size, their_start_offset, recv_num_elems) = + recv_offsets[idx]; + compressor_->Decompress(gradients_recv_ + recv_acc_size, layers, + their_start_offset, recv_num_elems, false, + gpu_stream); + nodes.erase(nodes.begin() + i); + } + } + } + communicator_->WaitAllSend(); + return 0; +} + +int MPI_Allreduce_ScatterReduceAllgather::AllreduceCompressedRemoteBuf( + int num_elements, int global_offset, std::vector &layers, + void *comm_p, gpuStream_t gpu_stream) { + MPI_Comm comm = *(static_cast(comm_p)); + int world_size, rank; + MPI_CHECK(MPI_Comm_size(comm, &world_size)); + MPI_CHECK(MPI_Comm_rank(comm, &rank)); + std::vector chunk_sizes, offsets; + Quantizer::GetSizesAndOffsets(num_elements, world_size, global_offset, layers, + offsets, chunk_sizes); + CommunicatorLocal *communicator_local_ = + reinterpret_cast(communicator_.get()); + communicator_local_->Init(world_size, comm_p); + compressor_->Init(layers[0].element_size(), gpu_stream); + int start_elem, num_elems; + int send_compressed_size = 0; + unsigned char *send_buf = gradients_send_; + + unsigned char *remote_buf; + for (int node_rank = 0; node_rank < world_size; node_rank++) { + if (node_rank == rank) { + continue; + } + + start_elem = offsets[node_rank]; + num_elems = chunk_sizes[node_rank]; + remote_buf = static_cast( + communicator_local_->GetRemoteBuftoSend(node_rank)); + send_compressed_size = utils::aligned_size(compressor_->Compress( + remote_buf, layers, start_elem, num_elems, gpu_stream)); + } + start_elem = offsets[rank]; + num_elems = chunk_sizes[rank]; + int recv_compressed_size = utils::aligned_size( + compressor_->BufferSize(chunk_sizes[rank], layers, offsets[rank])); + for (int node_rank = 0; node_rank < world_size; node_rank++) { + if (node_rank == rank) { + continue; + } + remote_buf = static_cast( + communicator_local_->GetRemoteBuftoRecv(node_rank)); + + compressor_->Decompress(remote_buf, layers, start_elem, num_elems, true, + gpu_stream); + } + // End of the first round. + remote_buf = static_cast( + communicator_local_->GetRemoteBroadcastBuftoSend()); + send_compressed_size = utils::aligned_size(compressor_->Compress( + remote_buf, layers, start_elem, num_elems, gpu_stream)); + compressor_->Decompress(remote_buf, layers, start_elem, num_elems, false, + gpu_stream); + for (int node_rank = 0; node_rank < world_size; node_rank++) { + if (node_rank == rank) + continue; + remote_buf = static_cast( + communicator_local_->GetRemoteBroadcastBuftoRecv(node_rank)); + start_elem = offsets[node_rank]; + num_elems = chunk_sizes[node_rank]; + compressor_->Decompress(remote_buf, layers, start_elem, num_elems, false, + gpu_stream); + } + return 0; +} + +int MPI_Allreduce_ScatterReduceAllgather::AllReduceAlltoAllCompressed( + int num_elements, int global_offset, std::vector &layers, + void *comm_p, gpuStream_t gpu_stream) { + MPI_Comm comm = *(static_cast(comm_p)); + int world_size, rank; + MPI_CHECK(MPI_Comm_size(comm, &world_size)); + MPI_CHECK(MPI_Comm_rank(comm, &rank)); + communicator_->Init(world_size, comm_p); + compressor_->Init(layers[0].element_size(), gpu_stream); + int compressed_size = compressor_->Compress( + gradients_send_, layers, global_offset, num_elements, gpu_stream); + unsigned char *recv_buf = gradients_recv_; + std::vector nodes; + for (int node_rank = 0; node_rank < world_size; node_rank++) { + if (node_rank == rank) + continue; + communicator_->ISend(gradients_send_, compressed_size, node_rank, + gpu_stream); + communicator_->IRecv(recv_buf, compressed_size, node_rank, gpu_stream); + nodes.push_back(node_rank); + recv_buf += compressed_size; + } + communicator_->WaitAllSend(); + compressor_->Decompress(gradients_send_, layers, global_offset, num_elements, + false, gpu_stream); + while (nodes.size() > 0) { + for (int i = 0; i < nodes.size(); i++) { + auto &node_rank = nodes.at(i); + if (communicator_->TestRecv(node_rank) > 0) { + auto idx = node_rank - ((node_rank > rank) ? 1 : 0); + compressor_->Decompress(gradients_recv_ + idx * compressed_size, layers, + global_offset, num_elements, true, gpu_stream); + nodes.erase(nodes.begin() + i); + } + } + } + return 0; +} + +int MPI_Allreduce_ScatterReduceAllgather::AllreduceUncompressed( + int num_elements, int global_offset, std::vector &layers, + void *comm_p, gpuStream_t gpu_stream) { + MPI_Comm comm = *(static_cast(comm_p)); + int world_size, rank; + MPI_CHECK(MPI_Comm_size(comm, &world_size)); + MPI_CHECK(MPI_Comm_rank(comm, &rank)); + int element_size = layers[0].element_size(); + std::vector chunk_sizes, offsets; + Compressor::GetSizesAndOffsets(num_elements, world_size, global_offset, + layers, offsets, chunk_sizes); + int send_size; + int recv_num_elems = chunk_sizes[rank]; + int recv_size = recv_num_elems * element_size; + unsigned char *send_buf = gradients_send_; + unsigned char *send_buf_base = send_buf; + unsigned char *recv_buf = gradients_recv_; + + communicator_->Init(world_size, comm_p); + if (layers.size() > 1) { + for (auto &layer : layers) { + gpu_context_->MemcpyAsyncD2D(send_buf, layer.data_ptr(), + layer.numel() * element_size, gpu_stream); + send_buf += layer.numel() * element_size; + } + send_buf = send_buf_base; + } else { + send_buf = static_cast(layers[0].data_ptr()); + send_buf_base = send_buf; + } + + if (num_elements > world_size) { + std::vector nodes; + nodes.reserve(world_size - 1); + for (int node_rank = 0; node_rank < world_size; node_rank++) { + if (node_rank == rank) { + send_buf += recv_size; + continue; + } + send_size = chunk_sizes[node_rank] * element_size; + communicator_->IRecv(recv_buf, recv_size, node_rank, gpu_stream); + communicator_->ISend(send_buf, send_size, node_rank, gpu_stream); + recv_buf += recv_size; + send_buf += send_size; + nodes.push_back(node_rank); + } + send_buf = send_buf_base + offsets[rank] * element_size; + recv_buf = gradients_recv_; + while (nodes.size() > 0) { + for (int i = 0; i < nodes.size(); i++) { + auto &node_rank = nodes[i]; + if (communicator_->TestRecv(node_rank) > 0) { + auto idx = node_rank - ((node_rank > rank) ? 1 : 0); + recv_buf = gradients_recv_ + recv_size * idx; + + Compressor::Add(recv_num_elems, send_buf, recv_buf, send_buf, + layers[0].scalar_type(), gpu_stream); + nodes.erase(nodes.begin() + i); + } + } + } + communicator_->WaitAllSend(); + send_size = recv_size; + recv_buf = send_buf_base; + for (int node_rank = 0; node_rank < world_size; node_rank++) { + if (node_rank == rank) { + recv_buf += send_size; + continue; + } + recv_size = chunk_sizes[node_rank] * element_size; + communicator_->IRecv(recv_buf, recv_size, node_rank, gpu_stream); + communicator_->ISend(send_buf, send_size, node_rank, gpu_stream); + recv_buf += recv_size; + } + communicator_->WaitAllRecv(); + communicator_->WaitAllSend(); + send_buf = send_buf_base; + } else { + send_size = num_elements * element_size; + for (int node_rank = 0; node_rank < world_size; node_rank++) { + if (node_rank == rank) + continue; + communicator_->ISend(send_buf, send_size, node_rank, gpu_stream); + communicator_->IRecv(recv_buf, send_size, node_rank, gpu_stream); + recv_buf += send_size; + } + communicator_->WaitAllRecv(); + communicator_->WaitAllSend(); + recv_buf = gradients_recv_; + for (int node_rank = 0; node_rank < world_size; node_rank++) { + if (node_rank == rank) + continue; + compressor_->Add(num_elements, send_buf, recv_buf, send_buf, + layers[0].scalar_type(), gpu_stream); + recv_buf += send_size; + } + } + if (layers.size() > 1) { + for (auto &layer : layers) { + gpu_context_->MemcpyAsyncD2D(layer.data_ptr(), send_buf, + layer.numel() * element_size, gpu_stream); + send_buf += layer.numel() * element_size; + } + } + return 0; +} + +} // namespace common +} // namespace cgx diff --git a/src/common/scatter_reduce_allgather.h b/src/common/scatter_reduce_allgather.h new file mode 100755 index 0000000..b607462 --- /dev/null +++ b/src/common/scatter_reduce_allgather.h @@ -0,0 +1,59 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once +#include "reducer.h" +#include "communicator.h" + +namespace cgx { +namespace common { + +class MPI_Allreduce_ScatterReduceAllgather : public MPIReducer { +public: + MPI_Allreduce_ScatterReduceAllgather(std::shared_ptr gpu_context, + std::shared_ptr compressor, + std::shared_ptr communicator, + int world_size); + + int AllreduceDivision(int num_elements, int global_offset, + std::vector &tensors, + void *comm, gpuStream_t gpu_stream, bool do_compression) override; +private: + int AllreduceCompressed(int num_elements, int global_offset, + std::vector &layers, + void *comm, gpuStream_t gpu_stream); + int AllreduceUncompressed(int num_elements, int global_offset, + std::vector &layers, + void *comm, gpuStream_t gpu_stream); + int AllreduceCompressedRemoteBuf(int num_elements, + int global_offset, + std::vector< + Layer> &layers, + void *comm_p, gpuStream_t gpu_stream); + int AllReduceAlltoAllCompressed(int num_elements, int global_offset, + std::vector &layers, + void *comm, gpuStream_t gpu_stream); +private: + bool remote_buf_compression_enabled_; + bool all_to_all_reduction_; + unsigned counter_ = 0; +}; + +} // namespace common +} // namespace cgx diff --git a/src/common/shm_communicator.cc b/src/common/shm_communicator.cc new file mode 100755 index 0000000..9038cae --- /dev/null +++ b/src/common/shm_communicator.cc @@ -0,0 +1,357 @@ +/************************************************************************* +* Copyright (c) 2016-2022, NVIDIA CORPORATION. All rights reserved. +* +* Modifications copyright (C) 2022, IST Austria. +************************************************************************/ + +#include "shm_communicator.h" +#include "compression/gpu_common.h" +#include "shm_utils.h" +#include "utils.h" +#include +#include +#include + +#define TRIV_CHECK(cmd) \ + do { \ + int e = cmd; \ + if (e != 0) { \ + printf("Failed: %s:%d: %s\n", __FILE__, __LINE__, strerror(errno)); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) + +namespace cgx { +namespace common { + +const char *sendSemFmt = "/cgx-sem-send-%d-%d"; +const char *recvSemFmt = "/cgx-sem-recv-%d-%d"; + +SHMCommunicator::~SHMCommunicator() { + // Can't deallocate buffers here, because at this point destuctor is called + // CUDA driver is in the middle of deinitialization. + if (!initialized_) + return; + for (auto &resource : send_resources) { + if (resource.first == rank_) + continue; + freeEventSync(&resource.second.second, true); + // freeBuffer(&resource.second.first); + } + for (auto &resource : recv_resources) { + if (resource.first == rank_) + continue; + freeEventSync(&resource.second.second, false); + // freeBuffer(&resource.second.first); + } + MPI_Barrier(comm_); + for (auto &resource : send_resources) { + if (resource.first == rank_) + continue; + unlinkSem(resource.first); + } +} + +void SHMCommunicator::Init(int world_size, void *ctx) { + if (initialized_) { + for (auto &resource : send_resources) { + resource.second.first.shmOffset = 0; + } + for (auto &resource : recv_resources) { + resource.second.first.shmOffset = 0; + } + return; + } + comm_ = *(static_cast(ctx)); + MPI_CHECK(MPI_Comm_rank(comm_, &rank_)); + world_size_ = world_size; + unsigned int fusion_size_mb = + utils::GetIntEnvOrDefault(FUSION_BUFFER_SIZE_MB, FUSION_SIZE_DEFAULT_MB); + unsigned int buf_size = + std::max(fusion_size_mb * 1024 * 1024, MIN_FUSION_SIZE); + // Initialize shared memory buffers. + for (int peer_rank = 0; peer_rank < world_size; peer_rank++) { + auto &send_resource = send_resources[peer_rank]; + sendInit(&send_resource.first, peer_rank, buf_size); + } + MPI_Barrier(comm_); + for (int peer_rank = 0; peer_rank < world_size; peer_rank++) { + if (peer_rank == rank_) + continue; + auto &recv_resource = recv_resources[peer_rank]; + recvInit(&recv_resource.first, peer_rank, buf_size, false); + auto &broadcast_recv_resource = broadcast_recv_resources[peer_rank]; + recvInit(&broadcast_recv_resource.first, peer_rank, buf_size, true); + } + MPI_Barrier(comm_); + cleanupBroadcast(); + // Initialize IPC primitives. + std::vector send_requests; + int count = 0; + for (int peer_rank = 0; peer_rank < world_size; peer_rank++) { + if (peer_rank == rank_) + continue; + auto &send_resource = send_resources[peer_rank]; + auto &recv_resource = recv_resources[peer_rank]; + initEventSend(send_resource.second, recv_resource.second, peer_rank, + send_requests); + } + for (int peer_rank = 0; peer_rank < world_size; peer_rank++) { + if (peer_rank == rank_) + continue; + auto &send_resource = send_resources[peer_rank]; + auto &recv_resource = recv_resources[peer_rank]; + initEventRecv(send_resource.second, recv_resource.second, peer_rank); + } + MPI_Waitall(send_requests.size(), send_requests.data(), MPI_STATUSES_IGNORE); + MPI_Barrier(comm_); + initialized_ = true; +} +static int counter = 0; +void SHMCommunicator::ISend(void *buf, size_t buf_size, int peer_rank, + gpuStream_t stream) { + auto &send_resource = send_resources[peer_rank]; + auto &shm_buf = send_resource.first; + auto &eventSync = send_resource.second; + eventSync.stream = stream; + // Performance optimization for SRA. + // We can postpone waiting for recv ACK of the previous send in allreduce and + // send new data into a piece of shared memory (shifted by shm_buf.shmOffset). + if (shm_buf.shmOffset == 0) { + TRIV_CHECK(sem_wait(eventSync.recvSem)); + gpu_context_->StreamWaitEvent(eventSync.stream, eventSync.recvEvent); + } + + assert(shm_buf.shmOffset + buf_size < shm_buf.shmSize); + gpu_context_->MemcpyAsyncD2D(static_cast(shm_buf.devHostMem) + + shm_buf.shmOffset, + buf, buf_size, stream); + gpu_context_->EventRecord(eventSync.sentEvent, stream); + + if (shm_buf.shmOffset > 0) { + // Postponed wait for the previous recv ACK. + TRIV_CHECK(sem_wait(eventSync.recvSem)); + } + // Notify peer that send event has been recorded. + sem_post(eventSync.sentSem); + shm_buf.shmOffset += buf_size; +} + +void SHMCommunicator::IRecv(void *buf, size_t buf_size, int peer_rank, + gpuStream_t stream) { + auto &recv_resource = recv_resources[peer_rank]; + auto &shm_buf = recv_resource.first; + assert(shm_buf.shmOffset + buf_size < shm_buf.shmSize); + auto &eventSync = recv_resource.second; + eventSync.stream = stream; + auto &recv_request = recv_requests[peer_rank]; + recv_request.recv_size = buf_size; + recv_request.dest = buf; +} + +int SHMCommunicator::TestRecv(int peer_rank) { + auto &recv_resource = recv_resources[peer_rank]; + auto &shm_buf = recv_resource.first; + auto &eventSync = recv_resource.second; + // Wait notification of sent data. + // Need to wait till the send event from peer is recorded. + int ret = sem_trywait(eventSync.sentSem); + if (ret < 0) { + if (errno == EAGAIN) { + return 0; + } else { + TRIV_CHECK(ret); + } + } + // Wait on stream till data transfer is finished. + gpu_context_->StreamWaitEvent(eventSync.stream, eventSync.sentEvent); + auto &recv_request = recv_requests[peer_rank]; + gpu_context_->MemcpyAsyncD2D(recv_request.dest, + static_cast(shm_buf.devHostMem) + + shm_buf.shmOffset, + recv_request.recv_size, eventSync.stream); + gpu_context_->EventRecord(eventSync.recvEvent, eventSync.stream); + TRIV_CHECK(sem_post(eventSync.recvSem)); + shm_buf.shmOffset += recv_request.recv_size; + counter++; + return 1; +} + +void SHMCommunicator::WaitAllSend() {} + +void SHMCommunicator::WaitSend(int rank) { + send_resources.at(rank).first.shmOffset = 0; +} + +void SHMCommunicator::WaitAllRecv() { + std::vector nodes; + for (int peer_rank = 0; peer_rank < world_size_; peer_rank++) { + if (peer_rank == rank_) + continue; + nodes.push_back(peer_rank); + } + while (nodes.size() > 0) { + for (int i = 0; i < nodes.size(); i++) { + if (TestRecv(nodes[i])) { + nodes.erase(nodes.begin() + i); + } + } + } +} + +void SHMCommunicator::WaitRecv(int rank) { + while (!TestRecv(rank)) { + } + recv_resources.at(rank).first.shmOffset = 0; +} + +void *SHMCommunicator::GetRemoteBuftoSend(int peer_rank) { + auto &send_resource = send_resources.at(peer_rank); + auto &shm_buf = send_resource.first; + return shm_buf.devHostMem; +} + +void *SHMCommunicator::GetRemoteBuftoRecv(int peer_rank) { + auto &recv_resource = recv_resources.at(peer_rank); + auto &shm_buf = recv_resource.first; + return shm_buf.devHostMem; +} + +void *SHMCommunicator::GetRemoteBroadcastBuftoSend() { + auto &send_resource = send_resources.at(rank_); + auto &shm_buf = send_resource.first; + return shm_buf.devHostMem; +} + +void *SHMCommunicator::GetRemoteBroadcastBuftoRecv(int peer_rank) { + auto &recv_resource = broadcast_recv_resources.at(peer_rank); + auto &shm_buf = recv_resource.first; + return shm_buf.devHostMem; +} + +void SHMCommunicator::CommitSend(int peer_rank, gpuStream_t stream) { + auto &send_resource = send_resources.at(rank_); + auto &eventSync = send_resource.second; + gpu_context_->EventRecord(eventSync.sentEvent, stream); + TRIV_CHECK(sem_post(eventSync.sentSem)); +} + +int SHMCommunicator::TestRemote(int peer_rank, gpuStream_t stream) { return 0; } + +void SHMCommunicator::sendInit(shmBuffer *buffer, int peer_rank, + size_t shm_size) { + char shmName[utils::MAX_SHM_NAME_LEN]; + buffer->shmSize = shm_size; + buffer->shmOffset = 0; + sprintf(shmName, "cgx-shm-send-%d-%d", rank_, peer_rank); + TRIV_CHECK(utils::shmOpen(shmName, buffer->shmSize, (void **)&buffer->hostMem, + (void **)&buffer->devHostMem, 1)); +} + +void SHMCommunicator::recvInit(shmBuffer *buffer, int peer_rank, + size_t shm_size, bool broadcast) { + char shmName[utils::MAX_SHM_NAME_LEN]; + buffer->shmSize = shm_size; + buffer->shmOffset = 0; + sprintf(shmName, "cgx-shm-send-%d-%d", peer_rank, + broadcast ? peer_rank : rank_); + TRIV_CHECK(utils::shmOpen(shmName, buffer->shmSize, (void **)&buffer->hostMem, + (void **)&buffer->devHostMem, 0)); + // in case of broadcast we cleanup later. + if (!broadcast) + TRIV_CHECK(utils::shmUnlink(shmName);); +} + +void SHMCommunicator::cleanupBroadcast() { + char shmName[utils::MAX_SHM_NAME_LEN]; + sprintf(shmName, "cgx-shm-send-%d-%d", rank_, rank_); + TRIV_CHECK(utils::shmUnlink(shmName);); +} + +void SHMCommunicator::initEventSend(gpuEventSync &sendEventSync, + gpuEventSync &recvEventSync, int peer_rank, + std::vector &send_requests) { + char semName[utils::MAX_SHM_NAME_LEN]; + sprintf(semName, sendSemFmt, rank_, peer_rank); + int ret = sem_unlink(semName); + if (ret < 0 and errno != ENOENT) { + TRIV_CHECK(ret); + } + sendEventSync.sentSem = sem_open(semName, O_CREAT | O_EXCL, 0644, 0); + TRIV_CHECK(!sendEventSync.sentSem); + + sprintf(semName, recvSemFmt, peer_rank, rank_); + ret = sem_unlink(semName); + if (ret < 0 and errno != ENOENT) { + TRIV_CHECK(ret); + } + recvEventSync.recvSem = sem_open(semName, O_CREAT | O_EXCL, 0644, 1); + TRIV_CHECK(!recvEventSync.recvSem); + + gpu_context_->EventCreate(&sendEventSync.sentEvent); + gpu_context_->IpcGetEventHandle(&sendEventSync.sendEventHandle, + sendEventSync.sentEvent); + send_requests.push_back(MPI_Request()); + MPI_CHECK(MPI_Isend((void *)(&sendEventSync.sendEventHandle), + sizeof(sendEventSync.sendEventHandle), MPI_UNSIGNED_CHAR, + peer_rank, 0, comm_, &send_requests.back())); + + gpu_context_->EventCreate(&recvEventSync.recvEvent); + gpu_context_->IpcGetEventHandle(&recvEventSync.recvEventHandle, + recvEventSync.recvEvent); + send_requests.push_back(MPI_Request()); + MPI_CHECK(MPI_Isend((void *)(&recvEventSync.recvEventHandle), + sizeof(recvEventSync.recvEventHandle), MPI_UNSIGNED_CHAR, + peer_rank, 0, comm_, &send_requests.back())); +} + +void SHMCommunicator::initEventRecv(gpuEventSync &sendEventSync, + gpuEventSync &recvEventSync, + int peer_rank) { + MPI_CHECK(MPI_Recv((void *)(&recvEventSync.sendEventHandle), + sizeof(recvEventSync.sendEventHandle), MPI_UNSIGNED_CHAR, + peer_rank, 0, comm_, MPI_STATUSES_IGNORE)); + gpu_context_->IpcOpenEventHandle(&recvEventSync.sentEvent, + recvEventSync.sendEventHandle); + + MPI_CHECK(MPI_Recv((void *)(&sendEventSync.recvEventHandle), + sizeof(sendEventSync.recvEventHandle), MPI_UNSIGNED_CHAR, + peer_rank, 0, comm_, MPI_STATUSES_IGNORE)); + gpu_context_->IpcOpenEventHandle(&sendEventSync.recvEvent, + sendEventSync.recvEventHandle); + + char semName[utils::MAX_SHM_NAME_LEN]; + sprintf(semName, sendSemFmt, peer_rank, rank_); + recvEventSync.sentSem = sem_open(semName, O_RDWR); + TRIV_CHECK(!recvEventSync.sentSem); + + sprintf(semName, recvSemFmt, rank_, peer_rank); + sendEventSync.recvSem = sem_open(semName, O_RDWR); + TRIV_CHECK(!sendEventSync.recvSem); +} + +void SHMCommunicator::freeBuffer(shmBuffer *buffer) { + TRIV_CHECK( + utils::shmClose(buffer->hostMem, buffer->devHostMem, buffer->shmSize)); +} + +void SHMCommunicator::freeEventSync(gpuEventSync *eventSync, bool send) { + if (send) + gpu_context_->EventDestroy(eventSync->sentEvent); + else + gpu_context_->EventDestroy(eventSync->recvEvent); + + TRIV_CHECK(sem_close(eventSync->sentSem)); + TRIV_CHECK(sem_close(eventSync->recvSem)); +} + +void SHMCommunicator::unlinkSem(int peer_rank) { + char semName[utils::MAX_SHM_NAME_LEN]; + sprintf(semName, sendSemFmt, rank_, peer_rank); + TRIV_CHECK(sem_unlink(semName)); + sprintf(semName, recvSemFmt, rank_, peer_rank); + TRIV_CHECK(sem_unlink(semName)); +} + +} // namespace common +} // namespace cgx diff --git a/src/common/shm_communicator.h b/src/common/shm_communicator.h new file mode 100755 index 0000000..fa2e5e5 --- /dev/null +++ b/src/common/shm_communicator.h @@ -0,0 +1,104 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include "communicator.h" +#include +#include +#include + +namespace cgx { +namespace common { +struct SHMCommunicator : public CommunicatorLocal { + SHMCommunicator(std::shared_ptr gpu_context) + : CommunicatorLocal(gpu_context) { + communicator_type_ = CommunicatorType::SHM; + } + + ~SHMCommunicator(); + + virtual void Init(int world_size, void *ctx) override; + virtual void ISend(void *buf, size_t buf_size, int peer_rank, + gpuStream_t stream) override; + virtual void IRecv(void *buf, size_t buf_size, int peer_rank, + gpuStream_t stream) override; + virtual void WaitSend(int rank) override; + virtual void WaitRecv(int rank) override; + virtual void WaitAllSend() override; + virtual void WaitAllRecv() override; + virtual int TestRecv(int rank) override; + virtual void *GetRemoteBuftoSend(int peer_rank) override; + virtual void *GetRemoteBuftoRecv(int peer_rank) override; + virtual void *GetRemoteBroadcastBuftoSend() override; + virtual void *GetRemoteBroadcastBuftoRecv(int peer_rank) override; + virtual void CommitSend(int peer_rank, gpuStream_t stream) override; + virtual int TestRemote(int peer_rank, gpuStream_t stream) override; + +private: + struct gpuEventSync { + sem_t *sentSem; + gpuEvent_t sentEvent; + gpuIpcEventHandle_t sendEventHandle; + + sem_t *recvSem; + gpuEvent_t recvEvent; + gpuIpcEventHandle_t recvEventHandle; + + gpuStream_t stream; + }; + + struct shmBuffer { + int shmSize; + int shmOffset; + void *hostMem; + void *devHostMem; + }; + + struct RecvRequest { + int recv_size; + void *dest; + }; + + // Initialize send and receive resources. + // Calls to sendInit and recvInit + // must be separated with MPI_Barrier. + void sendInit(shmBuffer *resource, int peer_rank, size_t shm_size); + void recvInit(shmBuffer *resource, int peer_rank, size_t shm_size, + bool broadcast); + void cleanupBroadcast(); + // Initialize IPC primitives. + void initEventSend(gpuEventSync &sendEventSync, gpuEventSync &recvEventSync, + int peer_rank, std::vector &send_requests); + void initEventRecv(gpuEventSync &sendEventSync, gpuEventSync &recvEventSync,int peer_rank); + + static void freeBuffer(shmBuffer *buffer); + void freeEventSync(gpuEventSync *eventSend, bool send); + void unlinkSem(int peer_rank); + + std::unordered_map> send_resources; + std::unordered_map> recv_resources; + std::unordered_map> + broadcast_recv_resources; + std::unordered_map recv_requests; + bool initialized_ = false; +}; + +} // namespace common +} // namespace cgx diff --git a/src/common/shm_utils.cc b/src/common/shm_utils.cc new file mode 100755 index 0000000..8e93265 --- /dev/null +++ b/src/common/shm_utils.cc @@ -0,0 +1,142 @@ +/************************************************************************* +* Copyright (c) 2016-2022, NVIDIA CORPORATION. All rights reserved. +* +* Modifications copyright (C) 2022, IST Austria. +************************************************************************/ + +#include "shm_utils.h" +#include +#include +#include +#include +#include +#include +#include +#include +#if HAVE_CUDA +#include +#include +#elif HAVE_ROCM +#include +#endif +#include "compression/gpu_common.h" + +#define SYS_CHECK(call, name) \ + do { \ + int retval; \ + SYS_CHECKVAL(call, name, retval); \ + } while (false) + +#define SYS_CHECKSYNC(call, name, retval) \ + do { \ + retval = call; \ + if (retval == -1 && \ + (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)) { \ + printf("Call to " name " returned %s, retrying", strerror(errno)); \ + } else { \ + break; \ + } \ + } while (true) + +#define SYS_CHECKVAL(call, name, retval) \ + do { \ + SYS_CHECKSYNC(call, name, retval); \ + if (retval == -1) { \ + printf("Call to " name " failed : %s", strerror(errno)); \ + return 1; \ + } \ + } while (false) + + +namespace cgx { +namespace common { +namespace utils { + + +int shm_allocate(int fd, const int shmsize) { + int err = posix_fallocate(fd, 0, shmsize); + if (err) { + errno = err; + return -1; + } + return 0; +} + +int shm_map(int fd, const int shmsize, void **ptr) { + *ptr = mmap(NULL, shmsize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + return (*ptr == MAP_FAILED) ? -1 : 0; +} + +static int shm_setup(const char *shmname, const int shmsize, int *fd, void **ptr, + int create) { + SYS_CHECKVAL(shm_open(shmname, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR), + "shm_open", *fd); + if (create) + SYS_CHECK(shm_allocate(*fd, shmsize), "posix_fallocate"); + SYS_CHECK(shm_map(*fd, shmsize, ptr), "mmap"); + close(*fd); + *fd = -1; + if (create) + memset(*ptr, 0, shmsize); + return 0; +} + +int shmOpen(const char *shmname, const int shmsize, void **shmPtr, + void **devShmPtr, int create) { + int fd = -1; + void *ptr = MAP_FAILED; + int res = 0; + + res = shm_setup(shmname, shmsize, &fd, &ptr, create); + if (res > 0) + goto sysError; +#if HAVE_CUDA + if ((res = cudaHostRegister(ptr, shmsize, cudaHostRegisterMapped)) != + cudaSuccess || + (res = cudaHostGetDevicePointer(devShmPtr, ptr, 0)) != cudaSuccess) + goto gpuError; +#elif HAVE_ROCM + if ((res = hipHostRegister(ptr, shmsize, hipHostRegisterMapped)) != + hipSuccess || + (res = hipHostGetDevicePointer(devShmPtr, ptr, 0)) != hipSuccess) + goto gpuError; +#endif + *shmPtr = ptr; + return 0; +sysError: + printf("Error while %s shared memory segment %s (size %d)\n", + create ? "creating" : "attaching to", shmname, shmsize); +gpuError: + if (fd != -1) + close(fd); + if (create) + shm_unlink(shmname); + if (ptr != MAP_FAILED) + munmap(ptr, shmsize); + *shmPtr = NULL; + return res; +} + +int shmUnlink(const char *shmname) { + if (shmname != NULL) + SYS_CHECK(shm_unlink(shmname), "shm_unlink"); + return 0; +} + +int shmClose(void *shmPtr, void *devShmPtr, const int shmsize) { +#if HAVE_CUDA + CUDA_CHECK(cudaHostUnregister(shmPtr)); +#elif HAVE_ROCM + HIP_CHECK(hipHostUnregister(shmPtr)); +#endif + if (munmap(shmPtr, shmsize) != 0) { + printf("munmap of shared memory failed\n"); + return 1; + } + return 0; +} + +} // namespace utils +} // namespace common +} // namespace cgx + diff --git a/src/common/shm_utils.h b/src/common/shm_utils.h new file mode 100755 index 0000000..6c37271 --- /dev/null +++ b/src/common/shm_utils.h @@ -0,0 +1,36 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once + +namespace cgx { +namespace common { +namespace utils { +const int MAX_SHM_NAME_LEN = 1024; + +int shmOpen(const char *shmname, const int shmsize, void **shmPtr, + void **devShmPtr, int create); + +int shmUnlink(const char *shmname); + +int shmClose(void *shmPtr, void *devShmPtr, const int shmsize); + +} // namespace utils +} // namespace common +} // namespace cgx diff --git a/src/common/utils.cc b/src/common/utils.cc new file mode 100755 index 0000000..435ef46 --- /dev/null +++ b/src/common/utils.cc @@ -0,0 +1,97 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include "utils.h" +#include + +namespace cgx { +namespace common { +namespace utils { + +int GetIntEnvOrDefault(const char *env_variable, int default_value) { + auto env_value = std::getenv(env_variable); + return env_value != nullptr ? std::strtol(env_value, nullptr, 10) + : default_value; +} + +float GetFloatEnvOrDefault(const char *env_variable, float default_value) { + auto env_value = std::getenv(env_variable); + return env_value != nullptr ? std::stof(std::string(env_value)) + : default_value; +} + +void SetBoolFromEnv(const char *env, bool &val, bool value_if_set) { + auto env_value = std::getenv(env); + if (env_value != nullptr && std::strtol(env_value, nullptr, 10) > 0) { + val = value_if_set; + } +} + +CommunicatorType GetCommTypeFromEnv(const char* env, CommunicatorType default_value) { + auto env_value = std::getenv(env); + if (env_value == nullptr) + return default_value; + auto env_value_str = std::string(env_value); + if (env_value_str == "MPI") + return CommunicatorType::MPI; + else if (env_value_str == "SHM") + return CommunicatorType::SHM; + else if (env_value_str == "NCCL") + return CommunicatorType::NCCL; + else + throw std::runtime_error("Unknown type of communicator"); +} + +ReductionType GetRedTypeFromEnv(const char* env, ReductionType default_value) { + auto env_value = std::getenv(env); + if (env_value == nullptr) + return default_value; + auto env_value_str = std::string(env_value); + if (env_value_str == "SRA") + return ReductionType::SRA; + else if (env_value_str == "Ring") + return ReductionType::Ring; + else + throw std::runtime_error("Unknown type of reduction"); +} + +#ifndef TEST +size_t get_sizeof(at::ScalarType dtype) { + if (dtype == at::kHalf) { + return sizeof(float) / 2; + + } else if (dtype == at::kFloat) { + return sizeof(float); + } else { + throw std::runtime_error("Unknown type at get_sizeof"); + } +} +#endif + +size_t round_to(size_t x, size_t m) { + return x + ((m - x % m) % m); +} + +size_t aligned_size(size_t size) { + return round_to(size, ALIGNMENT_UNIT); +} + +} // namespace utils +} // namespace common +} // namespace cgx \ No newline at end of file diff --git a/src/common/utils.h b/src/common/utils.h new file mode 100755 index 0000000..12660fd --- /dev/null +++ b/src/common/utils.h @@ -0,0 +1,63 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once +#include +#include + +#ifndef TEST +#include +#endif + +namespace cgx { +namespace common { +namespace utils { + +enum CommunicatorType { + MPI, + SHM, + NCCL +}; + +enum ReductionType { + SRA, + Ring +}; + +const size_t ALIGNMENT_UNIT = 2 * sizeof(float); + +int GetIntEnvOrDefault(const char *env_variable, int default_value); +float GetFloatEnvOrDefault(const char *env_variable, float default_value); + +void SetBoolFromEnv(const char* env, bool& val, bool value_if_set); + +#ifndef TEST +size_t get_sizeof(at::ScalarType dtype); +#endif + +size_t round_to(size_t x, size_t m); + +size_t aligned_size(size_t size); + +CommunicatorType GetCommTypeFromEnv(const char* env, CommunicatorType default_value); +ReductionType GetRedTypeFromEnv(const char* env, ReductionType default_value); + +} // namespace utils +} // namespace common +} // namespace cgx \ No newline at end of file diff --git a/src/mpi_allreduce_operations.cc b/src/mpi_allreduce_operations.cc new file mode 100755 index 0000000..bc56036 --- /dev/null +++ b/src/mpi_allreduce_operations.cc @@ -0,0 +1,287 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include "mpi_allreduce_operations.h" +#include "common/common.h" +#include "common/compressor.h" +#include "common/mpi_communicator.h" +#include "common/ring.h" +#include "common/scatter_reduce_allgather.h" +#include "common/utils.h" + +#if HAVE_CUDA +#include "common/nccl_reduce.h" +#include "common/shm_communicator.h" +#endif + +namespace cgx { + +std::vector> + MPIAllReduce_Operation::layers_sizes_; + +int NumElements(std::vector &layers) { + int sum = 0; + for (auto &layer : layers) { + sum += layer.numel(); + } + return sum; +} + +std::shared_ptr +CreateCompressor(std::shared_ptr gpu_context) { + bool dummy = false; + common::utils::SetBoolFromEnv(DEBUG_DUMMY_COMPRESSION, dummy, true); + if (dummy) + return std::make_shared(gpu_context); + else + return std::make_shared(gpu_context); +} + +std::shared_ptr +CreateReducer(std::shared_ptr gpu_context, + std::shared_ptr compressor, + std::shared_ptr communicator, + common::utils::ReductionType red_type, int world_size) { + if (red_type == common::utils::ReductionType::SRA) { + return std::make_shared( + gpu_context, compressor, communicator, world_size); + } else { + return std::make_shared( + gpu_context, compressor, communicator, world_size); + } +} + +std::shared_ptr +CreateInnerReducer(std::shared_ptr gpu_context, + std::shared_ptr compressor, + std::shared_ptr mpi_context) { + auto comm_type = common::utils::GetCommTypeFromEnv( + INNER_COMMUNICATOR_TYPE, common::utils::CommunicatorType::SHM); + unsigned world_size = mpi_context->GetSize(mpi_context->GetLocalComm()); + std::shared_ptr communicator; +#if HAVE_CUDA + if (comm_type == common::utils::CommunicatorType::NCCL) { + return std::make_shared(gpu_context, compressor, + world_size); + } + if (comm_type == common::utils::CommunicatorType::SHM) + communicator.reset(new common::SHMCommunicator(gpu_context)); +#endif + if (comm_type == common::utils::CommunicatorType::MPI) + communicator.reset(new common::MPICommunicator(gpu_context)); + if (!communicator) + throw std::runtime_error("Communicator type is not supported"); + auto red_type = common::utils::GetRedTypeFromEnv( + INNER_REDUCTION_TYPE, common::utils::ReductionType::SRA); + return CreateReducer(gpu_context, compressor, communicator, red_type, + world_size); +} + +std::shared_ptr +CreateCrossReducer(std::shared_ptr gpu_context, + std::shared_ptr compressor, + std::shared_ptr mpi_context) { + auto red_type = common::utils::GetRedTypeFromEnv( + CROSS_REDUCTION_TYPE, common::utils::ReductionType::Ring); + unsigned world_size = mpi_context->GetSize(mpi_context->GetCrossComm()); +#if HAVE_CUDA + auto comm_type = common::utils::GetCommTypeFromEnv( + CROSS_COMMUNICATOR_TYPE, common::utils::CommunicatorType::MPI); + if (comm_type == common::utils::CommunicatorType::NCCL) { + return std::make_shared(gpu_context, compressor, world_size); + } +#endif + + return CreateReducer(gpu_context, compressor, + std::make_shared(gpu_context), + red_type, + world_size); +} + +MPIAllReduce_Operation::MPIAllReduce_Operation() { + gpu_context_ = std::make_shared(); + mpi_context_ = std::make_shared(); + gpu_context_->SetDevice(mpi_context_->GetRank(mpi_context_->GetLocalComm())); + compressor_ = CreateCompressor(gpu_context_); + if (mpi_context_->GetSize(mpi_context_->GetLocalComm()) > 1) + intra_reducer_ = + CreateInnerReducer(gpu_context_, compressor_, mpi_context_); + if (mpi_context_->GetSize(mpi_context_->GetCrossComm()) > 1) + cross_reducer_ = + CreateCrossReducer(gpu_context_, compressor_, mpi_context_); + unsigned int fusion_size_mb = common::utils::GetIntEnvOrDefault( + FUSION_BUFFER_SIZE_MB, FUSION_SIZE_DEFAULT_MB); + fake_compression_ratio_ = + common::utils::GetFloatEnvOrDefault(COMPRESSION_FAKE_RATIO, 1.0); + tensor_fusion_threshold_ = + std::max(fusion_size_mb * 1024 * 1024, MIN_FUSION_SIZE); + intra_broadcast_ = common::utils::GetIntEnvOrDefault(INTRA_BROADCAST, 1); + intra_compress_ = common::utils::GetIntEnvOrDefault(INTRA_COMPRESS, 1); + bucket_idx_ = 0; +} + +int MPIAllReduce_Operation::allReduce(int num_elements, int offset, + std::vector &layers, + at::cuda::CUDAStream& stream, + bool do_compression) { + if (num_elements > 1000 and fake_compression_ratio_ < 1.0) + num_elements = (int)(num_elements * fake_compression_ratio_); + auto local_comm = mpi_context_->GetLocalComm(); + int status; + if (mpi_context_->GetSize(local_comm) > 1) { + if (num_elements < 16) { + status = intra_reducer_->AllReduceAlltoAll(num_elements, offset, layers, + (void *)&local_comm, stream); + } else { + status = intra_reducer_->AllreduceDivision( + num_elements, offset, layers, (void *)&local_comm, stream, + do_compression and intra_compress_); + } + } + if (status < 0) + return status; + auto cross_comm = mpi_context_->GetCrossComm(); + if (mpi_context_->GetSize(cross_comm) > 1) { + if (num_elements < 16) { + status = cross_reducer_->AllReduceAlltoAll(num_elements, offset, layers, + (void *)&cross_comm, stream); + } else { + if (intra_broadcast_) { + if (mpi_context_->GetRank(local_comm) == 0) + status = cross_reducer_->AllreduceDivision( + num_elements, offset, layers, (void *)&cross_comm, stream, + do_compression); + if (mpi_context_->GetSize(local_comm) > 1) { + mpi_context_->Barrier(local_comm); + status = + intra_reducer_->Broadcast(num_elements, offset, layers, + (void *)&local_comm, stream, + do_compression); + } + } else { + status = cross_reducer_->AllreduceDivision( + num_elements, offset, layers, (void *)&cross_comm, stream, + do_compression); + } + } + } + return status; +} + +int MPIAllReduce_Operation::performOperationSingle(common::Layer &layer, + at::cuda::CUDAStream& stream, + bool do_compression) { + int max_buffer_size = tensor_fusion_threshold_ / layer.element_size(); + int num_elements = layer.numel(); + std::vector layers = {layer}; + int status; + for (int offset = 0; offset < num_elements; offset += max_buffer_size) { + status = allReduce(std::min(max_buffer_size, num_elements - offset), offset, + layers, stream, do_compression); + } + return status; +} + +int MPIAllReduce_Operation::performOperation(std::vector &layers, + at::cuda::CUDAStream& stream, + bool do_compression) { + unsigned max_buffer_size = tensor_fusion_threshold_ / layers[0].element_size(); + int num_elements = NumElements(layers); + int status; + + if (num_elements < max_buffer_size) { + return allReduce(num_elements, 0, layers, stream, do_compression); + } + std::vector tmp_layers; + int cur_size = 0; + for (auto &layer : layers) { + if (layer.numel() > max_buffer_size) { + status = performOperationSingle(layer, stream, do_compression); + break; + } + if (cur_size + layer.numel() > max_buffer_size) { + status = allReduce(cur_size, 0, tmp_layers, stream, do_compression); + cur_size = 0; + tmp_layers.clear(); + } + tmp_layers.push_back(layer); + cur_size += layer.numel(); + } + return status; +} + +int MPIAllReduce_Operation::PerformOperation(at::Tensor &bucket, + at::cuda::CUDAStream& stream) { + std::vector layers; + int status; + if (bucket.numel() < MIN_LAYER_SIZE) { + layers.emplace_back(bucket); + status = performOperation(layers, stream, false); + return status; + } + compressor_->ResetParamsFromEnv(); + extractLayers(bucket, layers); + std::vector layers_compress; + std::vector layers_nocompress; + for (auto &layer : layers) { + if (compressor_->isEnabled(layer)) + layers_compress.push_back(layer); + else + layers_nocompress.push_back(layer); + } + if (!layers_compress.empty()) { + status = performOperation(layers_compress, stream, true); + } + if (!layers_nocompress.empty()) { + status = performOperation(layers_nocompress, stream, false); + } + return status; +} + +void MPIAllReduce_Operation::extractLayers(const at::Tensor &bucket, + std::vector &layers) { + if (layers_sizes_.empty()) { + layers.emplace_back(bucket); + return; + } + if (bucket_idx_ > 0 and bucket_idx_ % layers_sizes_.size() == 0) { + training_step_++; + } + bucket_idx_ %= layers_sizes_.size(); + const auto& sizes = layers_sizes_.at(bucket_idx_); + unsigned cur_numel = 0; + unsigned layer_idx = 0; + char *ptr = static_cast(bucket.data_ptr()); + for (auto& layer_size: sizes) { + layers.emplace_back(bucket, std::make_pair(bucket_idx_, layer_idx), ptr, + layer_size); + cur_numel += layer_size; + ptr += layer_size * bucket.element_size(); + layer_idx++; + } + if (cur_numel != bucket.numel()) { + throw std::runtime_error("Error at extracting the layers from bucket. " + "Number of elements in bucket is not equal to " + "number in the layers expected to be in " + "the bucket."); + } + bucket_idx_++; +} + +} // namespace cgx diff --git a/src/mpi_allreduce_operations.h b/src/mpi_allreduce_operations.h new file mode 100755 index 0000000..966d1f2 --- /dev/null +++ b/src/mpi_allreduce_operations.h @@ -0,0 +1,86 @@ +/* + * pytorch-cgx + * + * Copyright (C) 2022 Institute of Science and Technology Austria (ISTA). + * All Rights Reserved. + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#pragma once +#include +#include + +#include + +#include "common/gpu_context.h" +#include "common/layer.h" +#include "common/mpi_context.h" +#include "common/reducer.h" + +namespace cgx { +const int MIN_LAYER_SIZE = 16; + +struct MPIAllReduce_Operation { + MPIAllReduce_Operation(); + int PerformOperation(at::Tensor &bucket, at::cuda::CUDAStream &stream); + static void RegisterLayer(unsigned bucket_idx, unsigned layer_idx, + unsigned layer_numel, + int quantization_bits, int bucket_size) { + assert(layers_sizes_.size() >= bucket_idx && "Registering bucket out of order is not supported"); + if (layers_sizes_.size() == bucket_idx) { + layers_sizes_.emplace_back(std::vector()); + } + assert(layers_sizes_[bucket_idx].size() >= layer_idx && "Registering layer out of order is not supported"); + layers_sizes_[bucket_idx].push_back(layer_numel); + + SetQBits(bucket_idx, layer_idx, quantization_bits); + SetQBucketSize(bucket_idx, layer_idx, bucket_size); + } + + static void SetQBits(unsigned bucket_idx, unsigned layer_idx, + int quantization_bits) { + common::Compressor::SetQBits(std::make_pair(bucket_idx, layer_idx), quantization_bits); + } + + static void SetQBucketSize(unsigned bucket_idx, unsigned layer_idx, + int bucket_size) { + common::Compressor::SetQBucketSize(std::make_pair(bucket_idx, layer_idx), bucket_size); + } + +protected: + std::shared_ptr gpu_context_; + std::shared_ptr mpi_context_; + std::shared_ptr intra_reducer_; + std::shared_ptr cross_reducer_; + std::shared_ptr compressor_; + int64_t tensor_fusion_threshold_; + float fake_compression_ratio_; + +private: + void extractLayers(const at::Tensor &bucket, + std::vector &layers); + int performOperationSingle(common::Layer &layer, at::cuda::CUDAStream &stream, + bool do_compression); + int allReduce(int num_elements, int offset, + std::vector &tensors, + at::cuda::CUDAStream &stream, bool do_compression); + int performOperation(std::vector &tensors, + at::cuda::CUDAStream &stream, bool do_compression); + static std::vector> layers_sizes_; + unsigned bucket_idx_; + unsigned training_step_; + bool intra_broadcast_; + bool intra_compress_; +}; +} // namespace cgx \ No newline at end of file diff --git a/test/test_qmpi.py b/test/test_qmpi.py new file mode 100755 index 0000000..12963da --- /dev/null +++ b/test/test_qmpi.py @@ -0,0 +1,105 @@ +import torch.distributed as dist +import torch +import os +import unittest +import warnings +import torch_cgx +import numpy as np + +def reduce_equal_tests(rank, world_size, device="cuda"): + sizes = [1, 2, 8, 128, 1024, 1000000] + tests = [] + for dtype in [torch.float16, torch.float32, torch.int32]: + for size in sizes: + tests.append(( + torch.tensor([rank + 1] * size, dtype=dtype, device=device), + torch.tensor([(world_size * (world_size + 1)) // 2] * size, dtype=dtype, device=device) + ) + ) + return tests + + +def reduce_nonequal_tests(rank, world_size, device="cuda"): + sizes = [128, 1024, 1025, 16384, 1000000] + tests = [] + bits = [2, 3, 4, 6, 8] + for bit in bits: + for dtype in [torch.float16, torch.float32]: + for size in sizes: + arange = np.arange(-size / 2, size / 2, 1.0) + if dtype == torch.float16: + arange *= 1e-3 + tests.append(( + torch.tensor((rank + 1) * arange, dtype=dtype, device=device), + torch.tensor(((world_size * (world_size + 1)) / 2) * arange, dtype=dtype, device=device), + bit + ) + ) + return tests + + +class CGXTests(unittest.TestCase): + + def __init__(self, *args, **kwargs): + super(CGXTests, self).__init__(*args, **kwargs) + warnings.simplefilter('module') + + def assertTensorEqual(self, t1, t2, msg=None): + self.assertIsInstance(t1, torch.Tensor, 'First argument is not a Tensor') + self.assertIsInstance(t2, torch.Tensor, 'Second argument is not a Tensor') + if not torch.equal(t1, t2): + self.fail("Tensors are not equal: {} != {}. {}".format(t1, t2, msg)) + + def setUp(self) -> None: + super().setUp() + self.addTypeEqualityFunc(torch.Tensor, "assertTensorEqual") + assert "OMPI_COMM_WORLD_SIZE" in os.environ, "Launch with mpirun" + self.rank = int(os.environ["OMPI_COMM_WORLD_RANK"]) + self.world_size = int(os.environ["OMPI_COMM_WORLD_SIZE"]) + os.environ['MASTER_ADDR'] = '127.0.0.1' + os.environ['MASTER_PORT'] = '4040' + os.environ["WORLD_SIZE"] = os.environ["OMPI_COMM_WORLD_SIZE"] + dist.init_process_group(backend="cgx", init_method="env://", rank=self.rank) + torch.cuda.set_device(self.rank % torch.cuda.device_count()) + + def tearDown(self) -> None: + dist.barrier() + dist.destroy_process_group() + + def test_compressed_exact(self): + quantization_bits = [2, 4, 8] + tests = reduce_equal_tests(self.rank, self.world_size, device="cuda") + for q in quantization_bits: + os.environ["CGX_COMPRESSION_QUANTIZATION_BITS"] = str(q) + for (input, expected) in tests: + for i in range(10): + t = input.clone() + dist.all_reduce(t, op=dist.ReduceOp.SUM) + self.assertEqual(t, expected, "Parameters. bits {},buffer size: {}".format(q, t.numel())) + + def test_compressed_non_exact(self): + tests = reduce_nonequal_tests(self.rank, self.world_size, device="cuda") + bucket_sizes = [64, 512, 2048] + for (input, expected, q) in tests: + os.environ["CGX_COMPRESSION_QUANTIZATION_BITS"] = str(q) + for bucket_size in bucket_sizes: + os.environ["CGX_COMPRESSION_BUCKET_SIZE"] = str(bucket_size) + for i in range(10): + t = input.clone() + dist.all_reduce(t, op=dist.ReduceOp.SUM) + size = t.numel() + coef = self.world_size * (self.world_size + 1) + self.assertLess(torch.norm(t - expected, p=float("inf")).item(), 2 * min(bucket_size, size) / ((1 << q) - 1) * coef, + "Parameters. bits {}, bucket_size: {}, buffer size: {}".format(q, bucket_size, size)) + + def test_uncompressed(self): + os.environ["CGX_COMPRESSION_QUANTIZATION_BITS"] = str(32) + tests = reduce_equal_tests(self.rank, self.world_size) + for (input, expected) in tests: + t = input.clone() + dist.all_reduce(t, op=dist.ReduceOp.SUM) + self.assertEqual(t, expected) + + +if __name__ == "__main__": + unittest.main() \ No newline at end of file