diff --git a/.gitignore b/.gitignore
new file mode 100644
index 000000000..5ca0973f8
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+.DS_Store
+
diff --git a/COPYING b/COPYING
new file mode 100644
index 000000000..be3f7b28e
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+.
diff --git a/IMPORTANT.txt b/IMPORTANT.txt
new file mode 100644
index 000000000..f98c882f4
--- /dev/null
+++ b/IMPORTANT.txt
@@ -0,0 +1,15 @@
+⢀⡴⠑⡄⠀⠀⠀⠀⠀⠀⠀⣀⣀⣤⣤⣤⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
+⠸⡇⠀⠿⡀⠀⠀⠀⣀⡴⢿⣿⣿⣿⣿⣿⣿⣿⣷⣦⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀
+⠀⠀⠀⠀⠑⢄⣠⠾⠁⣀⣄⡈⠙⣿⣿⣿⣿⣿⣿⣿⣿⣆⠀⠀⠀⠀⠀⠀⠀⠀
+⠀⠀⠀⠀⢀⡀⠁⠀⠀⠈⠙⠛⠂⠈⣿⣿⣿⣿⣿⠿⡿⢿⣆⠀⠀⠀⠀⠀⠀⠀
+⠀⠀⠀⢀⡾⣁⣀⠀⠴⠂⠙⣗⡀⠀⢻⣿⣿⠭⢤⣴⣦⣤⣹⠀⠀⠀⢀⢴⣶⣆
+⠀⠀⢀⣾⣿⣿⣿⣷⣮⣽⣾⣿⣥⣴⣿⣿⡿⢂⠔⢚⡿⢿⣿⣦⣴⣾⠁⠸⣼⡿
+⠀⢀⡞⠁⠙⠻⠿⠟⠉⠀⠛⢹⣿⣿⣿⣿⣿⣌⢤⣼⣿⣾⣿⡟⠉⠀⠀⠀⠀⠀
+⠀⣾⣷⣶⠇⠀⠀⣤⣄⣀⡀⠈⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀
+⠀⠉⠈⠉⠀⠀⢦⡈⢻⣿⣿⣿⣶⣶⣶⣶⣤⣽⡹⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀
+⠀⠀⠀⠀⠀⠀⠀⠉⠲⣽⡻⢿⣿⣿⣿⣿⣿⣿⣷⣜⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀
+⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣷⣶⣮⣭⣽⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀
+⠀⠀⠀⠀⠀⠀⣀⣀⣈⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⠀⠀⠀⠀⠀
+⠀⠀⠀⠀⠀⠀⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠀⠀⠀⠀⠀⠀⠀⠀
+⠀⠀⠀⠀⠀⠀⠀⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀
+⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠛⠻⠿⠿⠿⠿⠛⠉
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 000000000..056cc0770
--- /dev/null
+++ b/README.md
@@ -0,0 +1,39 @@
+# Twitter Recommendation Algorithm
+
+The Twitter Recommendation Algorithm is a set of services and jobs that are responsible for constructing and serving the
+Home Timeline. For an introduction to how the algorithm works, please refer to our [engineering blog](https://blog.twitter.com/engineering/en_us/topics/open-source/2023/twitter-recommendation-algorithm). The
+diagram below illustrates how major services and jobs interconnect.
+
+![](docs/system-diagram.png)
+
+These are the main components of the Recommendation Algorithm included in this repository:
+
+| Type | Component | Description |
+|------------|------------|------------|
+| Feature | [SimClusters](src/scala/com/twitter/simclusters_v2/README.md) | Community detection and sparse embeddings into those communities. |
+| | [TwHIN](https://github.com/twitter/the-algorithm-ml/blob/main/projects/twhin/README.md) | Dense knowledge graph embeddings for Users and Tweets. |
+| | [trust-and-safety-models](trust_and_safety_models/README.md) | Models for detecting NSFW or abusive content. |
+| | [real-graph](src/scala/com/twitter/interaction_graph/README.md) | Model to predict likelihood of a Twitter User interacting with another User. |
+| | [tweepcred](src/scala/com/twitter/graph/batch/job/tweepcred/README) | Page-Rank algorithm for calculating Twitter User reputation. |
+| | [recos-injector](recos-injector/README.md) | Streaming event processor for building input streams for [GraphJet](https://github.com/twitter/GraphJet) based services. |
+| | [graph-feature-service](graph-feature-service/README.md) | Serves graph features for a directed pair of Users (e.g. how many of User A's following liked Tweets from User B). |
+| Candidate Source | [search-index](src/java/com/twitter/search/README.md) | Find and rank In-Network Tweets. ~50% of Tweets come from this candidate source. |
+| | [cr-mixer](cr-mixer/README.md) | Coordination layer for fetching Out-of-Network tweet candidates from underlying compute services. |
+| | [user-tweet-entity-graph](src/scala/com/twitter/recos/user_tweet_entity_graph/README.md) (UTEG)| Maintains an in memory User to Tweet interaction graph, and finds candidates based on traversals of this graph. This is built on the [GraphJet](https://github.com/twitter/GraphJet) framework. Several other GraphJet based features and candidate sources are located [here](src/scala/com/twitter/recos) |
+| | [follow-recommendation-service](follow-recommendations-service/README.md) (FRS)| Provides Users with recommendations for accounts to follow, and Tweets from those accounts. |
+| Ranking | [light-ranker](src/python/twitter/deepbird/projects/timelines/scripts/models/earlybird/README.md) | Light ranker model used by search index (Earlybird) to rank Tweets. |
+| | [heavy-ranker](https://github.com/twitter/the-algorithm-ml/blob/main/projects/home/recap/README.md) | Neural network for ranking candidate tweets. One of the main signals used to select timeline Tweets post candidate sourcing. |
+| Tweet mixing & filtering | [home-mixer](home-mixer/README.md) | Main service used to construct and serve the Home Timeline. Built on [product-mixer](product-mixer/README.md) |
+| | [visibility-filters](visibilitylib/README.md) | Responsible for filtering Twitter content to support legal compliance, improve product quality, increase user trust, protect revenue through the use of hard-filtering, visible product treatments, and coarse-grained downranking. |
+| | [timelineranker](timelineranker/README.md) | Legacy service which provides relevance-scored tweets from the Earlybird Search Index and UTEG service. |
+| Software framework | [navi](navi/navi/README.md) | High performance, machine learning model serving written in Rust. |
+| | [product-mixer](product-mixer/README.md) | Software framework for building feeds of content. |
+| | [twml](twml/README.md) | Legacy machine learning framework built on TensorFlow v1. |
+
+We include Bazel BUILD files for most components, but not a top level BUILD or WORKSPACE file.
+
+## Contributing
+
+We invite the community to submit GitHub issues and pull requests for suggestions on improving the recommendation algorithm. We are working on tools to manage these suggestions and sync changes to our internal repository. Any security concerns or issues should be routed to our official [bug bounty program](https://hackerone.com/twitter) through HackerOne. We hope to benefit from the collective intelligence and expertise of the global community in helping us identify issues and suggest improvements, ultimately leading to a better Twitter.
+
+Read our blog on the open source initiative [here](https://blog.twitter.com/en_us/topics/company/2023/a-new-era-of-transparency-for-twitter).
diff --git a/twml/BUILD b/twml/BUILD
new file mode 100644
index 000000000..c339f6fae
--- /dev/null
+++ b/twml/BUILD
@@ -0,0 +1,186 @@
+twml_sources = [
+ "twml/**/*.py",
+]
+
+twml_deps = [
+ "3rdparty/python/cherrypy:default",
+ "3rdparty/python/pyyaml:default",
+ "3rdparty/python/absl-py:default",
+ "3rdparty/python/joblib:default",
+ "3rdparty/python/kazoo:default",
+ "3rdparty/python/python-dateutil:default",
+ "3rdparty/python/pytz:default",
+ "cortex/ml-metastore/src/main/python/com/twitter/mlmetastore/modelrepo/client",
+ "src/python/twitter/common/app",
+ "src/python/twitter/common/app/modules:vars",
+ "src/python/twitter/common/metrics",
+ "src/python/twitter/deepbird/compat/v1/optimizers",
+ "src/python/twitter/deepbird/compat/v1/rnn",
+ "src/python/twitter/deepbird/hparam",
+ "src/python/twitter/deepbird/io",
+ "src/python/twitter/deepbird/io/legacy",
+ "src/python/twitter/deepbird/logging",
+ "src/python/twitter/deepbird/sparse",
+ "src/python/twitter/deepbird/stats_server",
+ "src/python/twitter/deepbird/util:simple-data-record-handler",
+ "src/python/twitter/deepbird/util/hashing",
+ "src/python/twitter/ml/api/dal",
+ "src/python/twitter/ml/common:metrics",
+ "src/python/twitter/ml/common/kubernetes",
+ "src/python/twitter/ml/common:resources",
+ "src/python/twitter/ml/twml/kubernetes",
+ "src/python/twitter/ml/twml:status",
+ "src/thrift/com/twitter/dal:dal_no_constants-python",
+ "src/thrift/com/twitter/statebird:compiled-v2-python",
+]
+
+python3_library(
+ name = "twml-test-common-deps",
+ tags = ["no-mypy"],
+ dependencies = [
+ "src/python/twitter/deepbird/util:inference",
+ "src/python/twitter/deepbird/util/data",
+ "src/thrift/com/twitter/ml/api:data-python",
+ "twml/tests/data:resources",
+ ],
+)
+
+python3_library(
+ name = "twml_packer_deps_no_tf",
+ tags = [
+ "bazel-compatible",
+ "no-mypy",
+ ],
+ dependencies = [
+ "3rdparty/python/numpy:default",
+ "3rdparty/python/pandas:default",
+ "3rdparty/python/pyyaml:default",
+ "3rdparty/python/requests:default",
+ "3rdparty/python/scikit-learn:default",
+ "3rdparty/python/scipy:default",
+ "3rdparty/python/tensorflow-hub:default",
+ "3rdparty/python/thriftpy2:default",
+ ],
+)
+
+python3_library(
+ name = "twml_packer_deps_no_tf_py3",
+ tags = [
+ "known-to-fail-jira:CX-20246",
+ "no-mypy",
+ ],
+ dependencies = [
+ ":twml_packer_deps_no_tf",
+ "3rdparty/python/tensorflow-model-analysis",
+ ],
+)
+
+alias(
+ name = "twml-test-shared",
+ target = ":twml_common",
+)
+
+python3_library(
+ name = "twml_common",
+ sources = ["twml_common/**/*.py"],
+ tags = [
+ "bazel-compatible",
+ "no-mypy",
+ ],
+)
+
+# Alias twml-dev to twml to avoid breaking user targets.
+alias(
+ name = "twml-dev",
+ target = "twml",
+)
+
+python3_library(
+ name = "twml-test-dev-deps",
+ tags = [
+ "bazel-compatible",
+ "no-mypy",
+ ],
+ dependencies = [
+ ":twml",
+ ":twml-test-common-deps",
+ ":twml-test-shared",
+ "3rdparty/python/freezegun:default",
+ "src/python/twitter/deepbird/keras/layers",
+ "src/thrift/com/twitter/ml/api:data-python",
+ "src/thrift/com/twitter/ml/prediction_service:prediction_service-python",
+ ],
+)
+
+python3_library(
+ name = "twml-dev-python",
+ sources = twml_sources,
+ tags = [
+ "bazel-compatible",
+ "no-mypy",
+ ],
+ dependencies = twml_deps + [
+ ":twml_packer_deps_no_tf",
+ "3rdparty/python/tensorflow",
+ "3rdparty/python/twml:libtwml-universal",
+ "twml/libtwml:libtwml-python",
+ ],
+)
+
+# Build a smaller .pex file that models can depend on.
+# Tensorflow and other dependencies are downloaded from Packer on Aurora.
+# Note: This gets the C++ ops through 3rdparty artifacts.
+python3_library(
+ name = "twml-nodeps",
+ sources = twml_sources,
+ tags = [
+ "bazel-compatible",
+ "no-mypy",
+ ],
+ dependencies = twml_deps + [
+ "3rdparty/python/twml:libtwml-universal",
+ ],
+)
+
+python3_library(
+ name = "twml",
+ tags = [
+ "bazel-compatible",
+ "no-mypy",
+ ],
+ dependencies = [
+ ":twml-nodeps",
+ ":twml_packer_deps_no_tf",
+ "3rdparty/python/tensorflow",
+ ],
+)
+
+python37_binary(
+ name = "tensorboard",
+ source = "twml/tensorboard/__main__.py",
+ dependencies = [
+ "3rdparty/python/_closures/twml:tensorboard",
+ "3rdparty/python/tensorflow",
+ ],
+)
+
+python37_binary(
+ name = "saved_model_cli",
+ source = "twml/saved_model_cli/__main__.py",
+ dependencies = [
+ "3rdparty/python/_closures/twml:saved_model_cli",
+ "3rdparty/python/tensorflow",
+ ],
+)
+
+# This target is added so twml can be used regardless of the Tensorflow version:
+# This target does not pull in TensorFlow 1.x or the related libtwml compiled using TF 1.x.
+python3_library(
+ name = "twml-py-source-only",
+ sources = twml_sources,
+ tags = [
+ "known-to-fail-jira:CX-23416",
+ "no-mypy",
+ ],
+ dependencies = twml_deps,
+)
diff --git a/twml/README.md b/twml/README.md
new file mode 100644
index 000000000..df7a10328
--- /dev/null
+++ b/twml/README.md
@@ -0,0 +1,13 @@
+# TWML
+
+---
+Note: `twml` is no longer under development. Much of the code here is not out of date and unused.
+It is included here for completeness, because `twml` is still used to train the light ranker models
+(see `src/python/twitter/deepbird/projects/timelines/scripts/models/earlybird/README.md`)
+---
+
+TWML is one of Twitter's machine learning frameworks, which uses Tensorflow under the hood. While it is mostly
+deprecated,
+it is still currently used to train the Earlybird light ranking models (
+see `src/python/twitter/deepbird/projects/timelines/scripts/models/earlybird/train.py`).
+The most relevant part of this is the `DataRecordTrainer` class, which is where the core training logic resides.
\ No newline at end of file
diff --git a/twml/libtwml/BUILD b/twml/libtwml/BUILD
new file mode 100644
index 000000000..c80b64b3b
--- /dev/null
+++ b/twml/libtwml/BUILD
@@ -0,0 +1,8 @@
+python3_library(
+ name = "libtwml-python",
+ sources = ["libtwml/**/*.py"],
+ tags = [
+ "no-mypy",
+ "bazel-compatible",
+ ],
+)
diff --git a/twml/libtwml/include/twml.h b/twml/libtwml/include/twml.h
new file mode 100644
index 000000000..9d88cdc7b
--- /dev/null
+++ b/twml/libtwml/include/twml.h
@@ -0,0 +1,21 @@
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
diff --git a/twml/libtwml/include/twml/BatchPredictionRequest.h b/twml/libtwml/include/twml/BatchPredictionRequest.h
new file mode 100644
index 000000000..6070ec045
--- /dev/null
+++ b/twml/libtwml/include/twml/BatchPredictionRequest.h
@@ -0,0 +1,45 @@
+#pragma once
+
+#ifdef __cplusplus
+
+#include
+#include
+#include
+
+namespace twml {
+
+template
+class GenericBatchPredictionRequest {
+ static_assert(std::is_same::value ||
+ std::is_same::value,
+ "RecordType has to be HashedDatarecord or DataRecord");
+ public:
+ typedef typename RecordType::Reader Reader;
+ GenericBatchPredictionRequest(int numOfLabels=0, int numOfWeights=0):
+ m_common_features(), m_requests(),
+ num_labels(numOfLabels), num_weights(numOfWeights)
+ {}
+
+ void decode(Reader &reader);
+
+ std::vector& requests() {
+ return m_requests;
+ }
+
+ RecordType& common() {
+ return m_common_features;
+ }
+
+ private:
+ RecordType m_common_features;
+ std::vector m_requests;
+ int num_labels;
+ int num_weights;
+};
+
+using HashedBatchPredictionRequest = GenericBatchPredictionRequest;
+using BatchPredictionRequest = GenericBatchPredictionRequest;
+
+}
+
+#endif
diff --git a/twml/libtwml/include/twml/BatchPredictionResponse.h b/twml/libtwml/include/twml/BatchPredictionResponse.h
new file mode 100644
index 000000000..b7e709464
--- /dev/null
+++ b/twml/libtwml/include/twml/BatchPredictionResponse.h
@@ -0,0 +1,58 @@
+#pragma once
+
+#include
+#include
+#include
+
+namespace twml {
+
+ // Encodes a batch of model predictions as a list of Thrift DataRecord
+ // objects inside a Thrift BatchPredictionResponse object. Prediction
+ // values are continousFeatures inside each DataRecord.
+ //
+ // The BatchPredictionResponseWriter TensorFlow operator uses this class
+ // to determine the size of the output tensor to allocate. The operator
+ // then allocates memory for the output tensor and uses this class to
+ // write binary Thrift to the output tensor.
+ //
+ class BatchPredictionResponse {
+ private:
+ uint64_t batch_size_;
+ const Tensor &keys_;
+ const Tensor &values_; // prediction values (batch_size * num_keys)
+ const Tensor &dense_keys_;
+ const std::vector &dense_values_;
+
+ inline uint64_t getBatchSize() { return batch_size_; }
+ inline bool hasContinuous() { return keys_.getNumDims() > 0; }
+ inline bool hasDenseTensors() { return dense_keys_.getNumDims() > 0; }
+
+ inline uint64_t getPredictionSize() {
+ return values_.getNumDims() > 1 ? values_.getDim(1) : 1;
+ };
+
+ void encode(twml::ThriftWriter &thrift_writer);
+
+ template
+ void serializePredictions(twml::ThriftWriter &thrift_writer);
+
+ public:
+ // keys: 'continuousFeatures' prediction keys
+ // values: 'continuousFeatures' prediction values (batch_size * num_keys)
+ // dense_keys: 'tensors' prediction keys
+ // dense_values: 'tensors' prediction values (batch_size * num_keys)
+ BatchPredictionResponse(
+ const Tensor &keys, const Tensor &values,
+ const Tensor &dense_keys, const std::vector &dense_values);
+
+ // Calculate the size of the Thrift encoded output (but do not encode).
+ // The BatchPredictionResponseWriter TensorFlow operator uses this value
+ // to allocate the output tensor.
+ uint64_t encodedSize();
+
+ // Write the BatchPredictionResponse as binary Thrift. The
+ // BatchPredictionResponseWriter operator uses this method to populate
+ // the output tensor.
+ void write(Tensor &result);
+ };
+}
diff --git a/twml/libtwml/include/twml/BlockFormatReader.h b/twml/libtwml/include/twml/BlockFormatReader.h
new file mode 100644
index 000000000..4c68458ba
--- /dev/null
+++ b/twml/libtwml/include/twml/BlockFormatReader.h
@@ -0,0 +1,32 @@
+#pragma once
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace twml {
+class BlockFormatReader {
+ private:
+ int record_size_;
+ long block_pos_;
+ long block_end_;
+ char classname_[1024];
+
+ int read_one_record_size();
+ int read_int();
+ int consume_marker(int scan);
+ int unpack_varint_i32();
+ int unpack_tag_and_wiretype(uint32_t *tag, uint32_t *wiretype);
+ int unpack_string(char *out, uint64_t max_out_len);
+
+ public:
+ BlockFormatReader();
+ bool next();
+ uint64_t current_size() const { return record_size_; }
+
+ virtual uint64_t read_bytes(void *dest, int size, int count) = 0;
+};
+}
diff --git a/twml/libtwml/include/twml/BlockFormatWriter.h b/twml/libtwml/include/twml/BlockFormatWriter.h
new file mode 100644
index 000000000..b9c496f40
--- /dev/null
+++ b/twml/libtwml/include/twml/BlockFormatWriter.h
@@ -0,0 +1,61 @@
+#pragma once
+#include
+#include
+#include
+#include
+#include
+#include
+
+#ifndef PATH_MAX
+#define PATH_MAX (8096)
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ struct block_format_writer__;
+ typedef block_format_writer__ * block_format_writer;
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#ifdef __cplusplus
+namespace twml {
+ class BlockFormatWriter {
+ private:
+ const char *file_name_;
+ FILE *outputfile_;
+ char temp_file_name_[PATH_MAX];
+ int record_index_;
+ int records_per_block_;
+
+ int pack_tag_and_wiretype(FILE *file, uint32_t tag, uint32_t wiretype);
+ int pack_varint_i32(FILE *file, int value);
+ int pack_string(FILE *file, const char *in, size_t in_len);
+ int write_int(FILE *file, int value);
+
+ public:
+ BlockFormatWriter(const char *file_name, int record_per_block);
+ ~BlockFormatWriter();
+ int write(const char *class_name, const char *record, int record_len) ;
+ int flush();
+ block_format_writer getHandle();
+ };
+
+ BlockFormatWriter *getBlockFormatWriter(block_format_writer w);
+} //twml namespace
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+twml_err block_format_writer_create(block_format_writer *w, const char *file_name, int records_per_block);
+twml_err block_format_write(block_format_writer w, const char *class_name, const char *record, int record_len);
+twml_err block_format_flush(block_format_writer w);
+twml_err block_format_writer_delete(const block_format_writer w);
+#ifdef __cplusplus
+}
+#endif
diff --git a/twml/libtwml/include/twml/DataRecord.h b/twml/libtwml/include/twml/DataRecord.h
new file mode 100644
index 000000000..f39f1158b
--- /dev/null
+++ b/twml/libtwml/include/twml/DataRecord.h
@@ -0,0 +1,108 @@
+#pragma once
+#ifdef __cplusplus
+
+#include
+#include
+#include
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace twml {
+
+class DataRecordReader;
+
+class TWMLAPI DataRecord : public TensorRecord {
+public:
+ typedef std::vector> SparseContinuousValueType;
+ typedef std::vector SparseBinaryValueType;
+ typedef Set BinaryFeatures;
+ typedef Map ContinuousFeatures;
+ typedef Map DiscreteFeatures;
+ typedef Map StringFeatures;
+ typedef Map SparseBinaryFeatures;
+ typedef Map SparseContinuousFeatures;
+ typedef Map> BlobFeatures;
+
+private:
+ BinaryFeatures m_binary;
+ ContinuousFeatures m_continuous;
+ DiscreteFeatures m_discrete;
+ StringFeatures m_string;
+ SparseBinaryFeatures m_sparsebinary;
+ SparseContinuousFeatures m_sparsecontinuous;
+ BlobFeatures m_blob;
+
+
+ std::vector m_labels;
+ std::vector m_weights;
+
+ void addLabel(int64_t id, double label = 1);
+ void addWeight(int64_t id, double value);
+
+public:
+ typedef DataRecordReader Reader;
+
+ DataRecord(int num_labels=0, int num_weights=0):
+ m_binary(),
+ m_continuous(),
+ m_discrete(),
+ m_string(),
+ m_sparsebinary(),
+ m_sparsecontinuous(),
+ m_blob(),
+ m_labels(num_labels, std::nanf("")),
+ m_weights(num_weights) {
+#ifdef USE_DENSE_HASH
+ m_binary.set_empty_key(0);
+ m_continuous.set_empty_key(0);
+ m_discrete.set_empty_key(0);
+ m_string.set_empty_key(0);
+ m_sparsebinary.set_empty_key(0);
+ m_sparsecontinuous.set_empty_key(0);
+#endif
+ m_binary.max_load_factor(0.5);
+ m_continuous.max_load_factor(0.5);
+ m_discrete.max_load_factor(0.5);
+ m_string.max_load_factor(0.5);
+ m_sparsebinary.max_load_factor(0.5);
+ m_sparsecontinuous.max_load_factor(0.5);
+ }
+
+ const BinaryFeatures &getBinary() const { return m_binary; }
+ const ContinuousFeatures &getContinuous() const { return m_continuous; }
+ const DiscreteFeatures &getDiscrete() const { return m_discrete; }
+ const StringFeatures &getString() const { return m_string; }
+ const SparseBinaryFeatures &getSparseBinary() const { return m_sparsebinary; }
+ const SparseContinuousFeatures &getSparseContinuous() const { return m_sparsecontinuous; }
+ const BlobFeatures &getBlob() const { return m_blob; }
+
+ const std::vector &labels() const { return m_labels; }
+ const std::vector &weights() const { return m_weights; }
+
+ // used by DataRecordWriter
+ template
+ void addContinuous(std::vector feature_ids, std::vector values) {
+ for (size_t i = 0; i < feature_ids.size(); ++i){
+ m_continuous[feature_ids[i]] = values[i];
+ }
+ }
+
+ template
+ void addContinuous(const int64_t *keys, uint64_t num_keys, T *values) {
+ for (size_t i = 0; i < num_keys; ++i){
+ m_continuous[keys[i]] = values[i];
+ }
+ }
+
+ void decode(DataRecordReader &reader);
+ void clear();
+ friend class DataRecordReader;
+};
+
+}
+#endif
diff --git a/twml/libtwml/include/twml/DataRecordReader.h b/twml/libtwml/include/twml/DataRecordReader.h
new file mode 100644
index 000000000..0ef8e64ff
--- /dev/null
+++ b/twml/libtwml/include/twml/DataRecordReader.h
@@ -0,0 +1,61 @@
+#pragma once
+#ifdef __cplusplus
+
+#include
+#include
+#include
+#include
+
+#include
+
+#include
+#include
+#include
+
+namespace twml {
+
+class TWMLAPI DataRecordReader : public TensorRecordReader {
+
+private:
+ typedef Map KeyMap_t;
+ KeyMap_t *m_keep_map;
+ KeyMap_t *m_labels_map;
+ KeyMap_t *m_weights_map;
+
+public:
+ bool keepKey (const int64_t &key, int64_t &code);
+ bool isLabel (const int64_t &key, int64_t &code);
+ bool isWeight (const int64_t &key, int64_t &code);
+ void readBinary (const int feature_type , DataRecord *record);
+ void readContinuous (const int feature_type , DataRecord *record);
+ void readDiscrete (const int feature_type , DataRecord *record);
+ void readString (const int feature_type , DataRecord *record);
+ void readSparseBinary (const int feature_type , DataRecord *record);
+ void readSparseContinuous (const int feature_type , DataRecord *record);
+ void readBlob (const int feature_type , DataRecord *record);
+
+ DataRecordReader() :
+ TensorRecordReader(nullptr),
+ m_keep_map(nullptr),
+ m_labels_map(nullptr),
+ m_weights_map(nullptr)
+ {}
+
+ // Using a template instead of int64_t because tensorflow implements int64 based on compiler.
+ void setKeepMap(KeyMap_t *keep_map) {
+ m_keep_map = keep_map;
+ }
+
+ void setLabelsMap(KeyMap_t *labels_map) {
+ m_labels_map = labels_map;
+ }
+
+ void setWeightsMap(KeyMap_t *weights_map) {
+ m_weights_map = weights_map;
+ }
+
+ void setDecodeMode(int64_t mode) {}
+};
+
+}
+#endif
diff --git a/twml/libtwml/include/twml/DataRecordWriter.h b/twml/libtwml/include/twml/DataRecordWriter.h
new file mode 100644
index 000000000..6b330d323
--- /dev/null
+++ b/twml/libtwml/include/twml/DataRecordWriter.h
@@ -0,0 +1,39 @@
+#pragma once
+#ifdef __cplusplus
+
+#include
+#include
+#include
+
+namespace twml {
+
+// Encodes DataRecords as binary Thrift. BatchPredictionResponse
+// uses this class to encode prediction responses through our
+// TensorFlow response writer operator.
+class TWMLAPI DataRecordWriter {
+ private:
+ uint32_t m_records_written;
+ twml::ThriftWriter &m_thrift_writer;
+ twml::TensorRecordWriter m_tensor_writer;
+
+ void writeBinary(twml::DataRecord &record);
+ void writeContinuous(twml::DataRecord &record);
+ void writeDiscrete(twml::DataRecord &record);
+ void writeString(twml::DataRecord &record);
+ void writeSparseBinaryFeatures(twml::DataRecord &record);
+ void writeSparseContinuousFeatures(twml::DataRecord &record);
+ void writeBlobFeatures(twml::DataRecord &record);
+ void writeDenseTensors(twml::DataRecord &record);
+
+ public:
+ DataRecordWriter(twml::ThriftWriter &thrift_writer):
+ m_records_written(0),
+ m_thrift_writer(thrift_writer),
+ m_tensor_writer(twml::TensorRecordWriter(thrift_writer)) { }
+
+ uint32_t getRecordsWritten();
+ uint64_t write(twml::DataRecord &record);
+};
+
+}
+#endif
diff --git a/twml/libtwml/include/twml/Error.h b/twml/libtwml/include/twml/Error.h
new file mode 100644
index 000000000..89307d214
--- /dev/null
+++ b/twml/libtwml/include/twml/Error.h
@@ -0,0 +1,48 @@
+#pragma once
+#include
+
+#ifdef __cplusplus
+#include
+#include
+#include
+#include
+
+namespace twml {
+
+class Error : public std::runtime_error {
+ private:
+ twml_err m_err;
+ public:
+ Error(twml_err err, const std::string &msg) :
+ std::runtime_error(msg), m_err(err)
+ {
+ }
+
+ twml_err err() const
+ {
+ return m_err;
+ }
+};
+
+class ThriftInvalidField: public twml::Error {
+ public:
+ ThriftInvalidField(int16_t field_id, const std::string& func) :
+ Error(TWML_ERR_THRIFT,
+ "Found invalid field (" + std::to_string(field_id)
+ + ") while reading thrift [" + func + "]")
+ {
+ }
+};
+
+class ThriftInvalidType: public twml::Error {
+ public:
+ ThriftInvalidType(uint8_t type_id, const std::string& func, const std::string type) :
+ Error(TWML_ERR_THRIFT,
+ "Found invalid type (" + std::to_string(type_id) +
+ ") while reading thrift [" + func + "::" + type + "]")
+ {
+ }
+};
+
+}
+#endif
diff --git a/twml/libtwml/include/twml/HashedDataRecord.h b/twml/libtwml/include/twml/HashedDataRecord.h
new file mode 100644
index 000000000..de63c4dc7
--- /dev/null
+++ b/twml/libtwml/include/twml/HashedDataRecord.h
@@ -0,0 +1,70 @@
+#pragma once
+#ifdef __cplusplus
+
+#include
+#include
+
+#include
+#include
+#include
+
+namespace twml {
+
+class HashedDataRecordReader;
+
+class TWMLAPI HashedDataRecord : public TensorRecord {
+ public:
+ typedef HashedDataRecordReader Reader;
+
+ HashedDataRecord(int num_labels=0, int num_weights=0):
+ m_keys(),
+ m_transformed_keys(),
+ m_values(),
+ m_codes(),
+ m_types(),
+ m_labels(num_labels, std::nanf("")),
+ m_weights(num_weights) {}
+
+ void decode(HashedDataRecordReader &reader);
+
+ const std::vector &keys() const { return m_keys; }
+ const std::vector &transformed_keys() const { return m_transformed_keys; }
+ const std::vector &values() const { return m_values; }
+ const std::vector &codes() const { return m_codes; }
+ const std::vector &types() const { return m_types; }
+
+ const std::vector &labels() const { return m_labels; }
+ const std::vector &weights() const { return m_weights; }
+
+ void clear();
+
+ uint64_t totalSize() const { return m_keys.size(); }
+
+ void extendSize(int delta_size) {
+ int count = m_keys.size() + delta_size;
+ m_keys.reserve(count);
+ m_transformed_keys.reserve(count);
+ m_values.reserve(count);
+ m_codes.reserve(count);
+ m_types.reserve(count);
+ }
+
+ private:
+ std::vector m_keys;
+ std::vector m_transformed_keys;
+ std::vector m_values;
+ std::vector m_codes;
+ std::vector m_types;
+
+ std::vector m_labels;
+ std::vector m_weights;
+
+ void addKey(int64_t key, int64_t transformed_key, int64_t code, uint8_t type, double value=1);
+ void addLabel(int64_t id, double value = 1);
+ void addWeight(int64_t id, double value);
+
+ friend class HashedDataRecordReader;
+};
+
+}
+#endif
\ No newline at end of file
diff --git a/twml/libtwml/include/twml/HashedDataRecordReader.h b/twml/libtwml/include/twml/HashedDataRecordReader.h
new file mode 100644
index 000000000..5470eb5c8
--- /dev/null
+++ b/twml/libtwml/include/twml/HashedDataRecordReader.h
@@ -0,0 +1,70 @@
+#pragma once
+#ifdef __cplusplus
+
+#include
+#include
+#include
+#include
+
+#include
+
+#include
+#include
+#include
+
+namespace twml {
+
+enum class DecodeMode: int64_t
+{
+ hash_valname = 0,
+ hash_fname_and_valname = 1,
+};
+
+class TWMLAPI HashedDataRecordReader : public TensorRecordReader {
+private:
+ typedef Map KeyMap_t;
+ KeyMap_t *m_keep_map;
+ KeyMap_t *m_labels_map;
+ KeyMap_t *m_weights_map;
+ DecodeMode m_decode_mode;
+
+public:
+ bool keepId (const int64_t &key, int64_t &code);
+ bool isLabel (const int64_t &key, int64_t &code);
+ bool isWeight (const int64_t &key, int64_t &code);
+ void readBinary (const int feature_type , HashedDataRecord *record);
+ void readContinuous (const int feature_type , HashedDataRecord *record);
+ void readDiscrete (const int feature_type , HashedDataRecord *record);
+ void readString (const int feature_type , HashedDataRecord *record);
+ void readSparseBinary (const int feature_type , HashedDataRecord *record);
+ void readSparseContinuous (const int feature_type , HashedDataRecord *record);
+ void readBlob (const int feature_type , HashedDataRecord *record);
+
+ HashedDataRecordReader() :
+ TensorRecordReader(nullptr),
+ m_keep_map(nullptr),
+ m_labels_map(nullptr),
+ m_weights_map(nullptr),
+ m_decode_mode(DecodeMode::hash_valname)
+ {}
+
+ // Using a template instead of int64_t because tensorflow implements int64 based on compiler.
+ void setKeepMap(KeyMap_t *keep_map) {
+ m_keep_map = keep_map;
+ }
+
+ void setLabelsMap(KeyMap_t *labels_map) {
+ m_labels_map = labels_map;
+ }
+
+ void setWeightsMap(KeyMap_t *weights_map) {
+ m_weights_map = weights_map;
+ }
+
+ void setDecodeMode(int64_t mode) {
+ m_decode_mode = static_cast(mode);
+ }
+};
+
+}
+#endif
diff --git a/twml/libtwml/include/twml/Hashmap.h b/twml/libtwml/include/twml/Hashmap.h
new file mode 100644
index 000000000..59314236b
--- /dev/null
+++ b/twml/libtwml/include/twml/Hashmap.h
@@ -0,0 +1,110 @@
+#pragma once
+#include
+#include
+#include
+#include
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ typedef void * twml_hashmap;
+ typedef int64_t tw_hash_key_t;
+ typedef int64_t tw_hash_val_t;
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef __cplusplus
+namespace twml {
+
+ typedef tw_hash_key_t HashKey_t;
+ typedef tw_hash_val_t HashVal_t;
+
+ class HashMap {
+ private:
+ twml_hashmap m_hashmap;
+
+ public:
+ HashMap();
+ ~HashMap();
+
+ // Disable copy constructor and assignment
+ // TODO: Fix this after retain and release are added to twml_hashmap
+ HashMap(const HashMap &other) = delete;
+ HashMap& operator=(const HashMap &other) = delete;
+
+ void clear();
+ uint64_t size() const;
+ int8_t insert(const HashKey_t key);
+ int8_t insert(const HashKey_t key, const HashVal_t val);
+ void remove(const HashKey_t key);
+ int8_t get(HashVal_t &val, const HashKey_t key) const;
+
+ void insert(Tensor &mask, const Tensor keys);
+ void insert(Tensor &mask, const Tensor keys, const Tensor vals);
+ void remove(const Tensor keys);
+ void get(Tensor &mask, Tensor &vals, const Tensor keys) const;
+
+ void getInplace(Tensor &mask, Tensor &keys_vals) const;
+ void toTensors(Tensor &keys, Tensor &vals) const;
+ };
+}
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+ TWMLAPI twml_err twml_hashmap_create(twml_hashmap *hashmap);
+
+ TWMLAPI twml_err twml_hashmap_clear(const twml_hashmap hashmap);
+
+ TWMLAPI twml_err twml_hashmap_get_size(uint64_t *size, const twml_hashmap hashmap);
+
+ TWMLAPI twml_err twml_hashmap_delete(const twml_hashmap hashmap);
+
+ // insert, get, remove single key / value
+ TWMLAPI twml_err twml_hashmap_insert_key(int8_t *mask,
+ const twml_hashmap hashmap,
+ const tw_hash_key_t key);
+
+ TWMLAPI twml_err twml_hashmap_insert_key_and_value(int8_t *mask, twml_hashmap hashmap,
+ const tw_hash_key_t key,
+ const tw_hash_val_t val);
+
+ TWMLAPI twml_err twml_hashmap_remove_key(const twml_hashmap hashmap,
+ const tw_hash_key_t key);
+
+ TWMLAPI twml_err twml_hashmap_get_value(int8_t *mask, tw_hash_val_t *val,
+ const twml_hashmap hashmap,
+ const tw_hash_key_t key);
+
+ TWMLAPI twml_err twml_hashmap_insert_keys(twml_tensor masks,
+ const twml_hashmap hashmap,
+ const twml_tensor keys);
+
+ // insert, get, remove tensors of keys / values
+ TWMLAPI twml_err twml_hashmap_insert_keys_and_values(twml_tensor masks,
+ twml_hashmap hashmap,
+ const twml_tensor keys,
+ const twml_tensor vals);
+
+ TWMLAPI twml_err twml_hashmap_remove_keys(const twml_hashmap hashmap,
+ const twml_tensor keys);
+
+ TWMLAPI twml_err twml_hashmap_get_values(twml_tensor masks,
+ twml_tensor vals,
+ const twml_hashmap hashmap,
+ const twml_tensor keys);
+
+ TWMLAPI twml_err twml_hashmap_get_values_inplace(twml_tensor masks,
+ twml_tensor keys_vals,
+ const twml_hashmap hashmap);
+
+ TWMLAPI twml_err twml_hashmap_to_tensors(twml_tensor keys,
+ twml_tensor vals,
+ const twml_hashmap hashmap);
+#ifdef __cplusplus
+}
+#endif
diff --git a/twml/libtwml/include/twml/RawTensor.h b/twml/libtwml/include/twml/RawTensor.h
new file mode 100644
index 000000000..571966743
--- /dev/null
+++ b/twml/libtwml/include/twml/RawTensor.h
@@ -0,0 +1,92 @@
+#pragma once
+#include
+#include
+
+#ifdef __cplusplus
+namespace twml {
+
+// This class contains the raw pointers to tensors coming from thrift object.
+class TWMLAPI RawTensor : public Tensor
+{
+private:
+ bool m_is_big_endian;
+ uint64_t m_raw_length;
+public:
+
+ RawTensor() {}
+
+ RawTensor(void *data, const std::vector &dims,
+ const std::vector &strides, twml_type type, bool is_big_endian, uint64_t length)
+ : Tensor(data, dims, strides, type), m_is_big_endian(is_big_endian), m_raw_length(length) {}
+
+ bool is_big_endian() const {
+ return m_is_big_endian;
+ }
+
+ uint64_t getRawLength() const {
+ return m_raw_length;
+ }
+
+ // Extracts a slice from a tensor at idx0 along dimension 0
+ // Used in BatchPredictionResponse to write each slice in separate records
+ RawTensor getSlice(uint64_t idx0) const {
+ void *slice = nullptr;
+ uint64_t raw_length = 0;
+
+ if (getType() == TWML_TYPE_STRING) {
+ raw_length = getStride(0);
+ std::string *data = const_cast(static_cast(getData()));
+ slice = static_cast(data + raw_length * idx0);
+ } else {
+ raw_length = getStride(0) * getSizeOf(getType());
+ char *data = const_cast(static_cast(getData()));
+ slice = static_cast(data + raw_length * idx0);
+ }
+
+ std::vector dims, strides;
+ for (int i = 1; i < getNumDims(); i++) {
+ dims.push_back(getDim(i));
+ strides.push_back(getStride(i));
+ }
+
+ return RawTensor(slice, dims, strides, getType(), m_is_big_endian, raw_length);
+ }
+};
+
+// Wrapper class around RawTensor to hold sparse tensors.
+class TWMLAPI RawSparseTensor
+{
+private:
+ RawTensor m_indices;
+ RawTensor m_values;
+ std::vector m_dense_shape;
+
+public:
+
+ RawSparseTensor() {
+ }
+
+ RawSparseTensor(const RawTensor &indices_, const RawTensor &values_,
+ const std::vector &dense_shape_) :
+ m_indices(indices_), m_values(values_), m_dense_shape(dense_shape_)
+ {
+ if (m_indices.getType() != TWML_TYPE_INT64) {
+ throw twml::Error(TWML_ERR_TYPE, "Indices of Sparse Tensor must be of type int64");
+ }
+ }
+
+ const RawTensor &indices() const {
+ return m_indices;
+ }
+
+ const RawTensor &values() const {
+ return m_values;
+ }
+
+ const std::vector& denseShape() const {
+ return m_dense_shape;
+ }
+};
+
+}
+#endif
diff --git a/twml/libtwml/include/twml/Tensor.h b/twml/libtwml/include/twml/Tensor.h
new file mode 100644
index 000000000..774474403
--- /dev/null
+++ b/twml/libtwml/include/twml/Tensor.h
@@ -0,0 +1,82 @@
+#pragma once
+#include
+
+#include
+#include
+#include
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ struct twml_tensor__;
+ typedef twml_tensor__ * twml_tensor;
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef __cplusplus
+namespace twml {
+
+class TWMLAPI Tensor
+{
+private:
+ twml_type m_type;
+ void *m_data;
+ std::vector m_dims;
+ std::vector m_strides;
+
+public:
+ Tensor() {}
+ Tensor(void *data, int ndims, const uint64_t *dims, const uint64_t *strides, twml_type type);
+ Tensor(void *data, const std::vector &dims, const std::vector &strides, twml_type type);
+
+ const std::vector& getDims() const {
+ return m_dims;
+ }
+
+ int getNumDims() const;
+ uint64_t getDim(int dim) const;
+ uint64_t getStride(int dim) const;
+ uint64_t getNumElements() const;
+ twml_type getType() const;
+
+ twml_tensor getHandle();
+ const twml_tensor getHandle() const;
+
+ template T *getData();
+ template const T *getData() const;
+};
+
+TWMLAPI std::string getTypeName(twml_type type);
+TWMLAPI const Tensor *getConstTensor(const twml_tensor t);
+TWMLAPI Tensor *getTensor(twml_tensor t);
+TWMLAPI uint64_t getSizeOf(twml_type type);
+
+}
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ TWMLAPI twml_err twml_tensor_create(twml_tensor *tensor, void *data,
+ int ndims, uint64_t *dims,
+ uint64_t *strides, twml_type type);
+
+ TWMLAPI twml_err twml_tensor_delete(const twml_tensor tensor);
+
+ TWMLAPI twml_err twml_tensor_get_type(twml_type *type, const twml_tensor tensor);
+
+ TWMLAPI twml_err twml_tensor_get_data(void **data, const twml_tensor tensor);
+
+ TWMLAPI twml_err twml_tensor_get_dim(uint64_t *dim, const twml_tensor tensor, int id);
+
+ TWMLAPI twml_err twml_tensor_get_num_dims(int *ndims, const twml_tensor tensor);
+
+ TWMLAPI twml_err twml_tensor_get_num_elements(uint64_t *nelements, const twml_tensor tensor);
+
+ TWMLAPI twml_err twml_tensor_get_stride(uint64_t *stride, const twml_tensor tensor, int id);
+#ifdef __cplusplus
+}
+#endif
diff --git a/twml/libtwml/include/twml/TensorRecord.h b/twml/libtwml/include/twml/TensorRecord.h
new file mode 100644
index 000000000..d128cfdce
--- /dev/null
+++ b/twml/libtwml/include/twml/TensorRecord.h
@@ -0,0 +1,47 @@
+#pragma once
+#ifdef __cplusplus
+
+#include
+#include
+
+#include
+#include
+
+namespace twml {
+
+class TensorRecordReader;
+
+// A class containing the data from TensorRecord.
+// - This serves as the base class from which DataRecord and HashedDataRecord are inherited.
+class TWMLAPI TensorRecord {
+public:
+ typedef std::unordered_map RawTensors;
+ typedef std::unordered_map RawSparseTensors;
+
+private:
+ RawTensors m_tensors;
+ RawSparseTensors m_sparse_tensors;
+
+public:
+
+ const RawTensors &getRawTensors() {
+ return m_tensors;
+ }
+
+ const RawTensor& getRawTensor(int64_t id) const {
+ return m_tensors.at(id);
+ }
+
+ const RawSparseTensor& getRawSparseTensor(int64_t id) const {
+ return m_sparse_tensors.at(id);
+ }
+
+ void addRawTensor(int64_t id, const RawTensor &tensor) {
+ m_tensors.emplace(id, tensor);
+ }
+
+ friend class TensorRecordReader;
+};
+
+}
+#endif
diff --git a/twml/libtwml/include/twml/TensorRecordReader.h b/twml/libtwml/include/twml/TensorRecordReader.h
new file mode 100644
index 000000000..3a62bd885
--- /dev/null
+++ b/twml/libtwml/include/twml/TensorRecordReader.h
@@ -0,0 +1,34 @@
+#pragma once
+#ifdef __cplusplus
+
+#include
+#include
+#include
+
+#include
+
+#include
+#include
+#include
+
+namespace twml {
+
+// Class that parses the thrift objects as defined in tensor.thrift
+class TWMLAPI TensorRecordReader : public ThriftReader {
+
+ std::vector readShape();
+ template RawTensor readTypedTensor();
+ RawTensor readRawTypedTensor();
+ RawTensor readStringTensor();
+ RawTensor readGeneralTensor();
+ RawSparseTensor readCOOSparseTensor();
+
+public:
+ void readTensor(const int feature_type, TensorRecord *record);
+ void readSparseTensor(const int feature_type, TensorRecord *record);
+
+ TensorRecordReader(const uint8_t *buffer) : ThriftReader(buffer) {}
+};
+
+}
+#endif
diff --git a/twml/libtwml/include/twml/TensorRecordWriter.h b/twml/libtwml/include/twml/TensorRecordWriter.h
new file mode 100644
index 000000000..d8b7c3dbf
--- /dev/null
+++ b/twml/libtwml/include/twml/TensorRecordWriter.h
@@ -0,0 +1,35 @@
+#pragma once
+#ifdef __cplusplus
+
+#include
+#include
+
+namespace twml {
+
+// Encodes tensors as DataRecord/TensorRecord-compatible Thrift.
+// DataRecordWriter relies on this class to encode the tensor fields.
+class TWMLAPI TensorRecordWriter {
+
+private:
+ uint32_t m_records_written;
+ twml::ThriftWriter &m_thrift_writer;
+
+ void writeTensor(const RawTensor &tensor);
+ void writeRawTensor(const RawTensor &tensor);
+
+public:
+ TensorRecordWriter(twml::ThriftWriter &thrift_writer):
+ m_records_written(0),
+ m_thrift_writer(thrift_writer) { }
+
+ uint32_t getRecordsWritten();
+
+ // Caller (usually DataRecordWriter) must precede with struct header field
+ // like thrift_writer.writeStructFieldHeader(TTYPE_MAP, DR_GENERAL_TENSOR)
+ //
+ // All tensors written as RawTensors except for StringTensors
+ uint64_t write(twml::TensorRecord &record);
+};
+
+}
+#endif
diff --git a/twml/libtwml/include/twml/ThriftReader.h b/twml/libtwml/include/twml/ThriftReader.h
new file mode 100644
index 000000000..25c83ea29
--- /dev/null
+++ b/twml/libtwml/include/twml/ThriftReader.h
@@ -0,0 +1,56 @@
+#pragma once
+
+#ifdef __cplusplus
+
+#include
+#include
+#include
+#include
+
+namespace twml {
+
+class ThriftReader {
+ protected:
+ const uint8_t *m_buffer;
+
+ public:
+
+ ThriftReader(const uint8_t *buffer): m_buffer(buffer) {}
+
+ const uint8_t *getBuffer() { return m_buffer; }
+
+ void setBuffer(const uint8_t *buffer) { m_buffer = buffer; }
+
+ template T readDirect() {
+ T val;
+ memcpy(&val, m_buffer, sizeof(T));
+ m_buffer += sizeof(T);
+ return val;
+ }
+
+ template void skip() {
+ m_buffer += sizeof(T);
+ }
+
+ void skipLength(size_t length) {
+ m_buffer += length;
+ }
+
+ uint8_t readByte();
+ int16_t readInt16();
+ int32_t readInt32();
+ int64_t readInt64();
+ double readDouble();
+
+ template inline
+ int32_t getRawBuffer(const uint8_t **begin) {
+ int32_t length = readInt32();
+ *begin = m_buffer;
+ skipLength(length * sizeof(T));
+ return length;
+ }
+
+};
+
+}
+#endif
diff --git a/twml/libtwml/include/twml/ThriftWriter.h b/twml/libtwml/include/twml/ThriftWriter.h
new file mode 100644
index 000000000..1216415b0
--- /dev/null
+++ b/twml/libtwml/include/twml/ThriftWriter.h
@@ -0,0 +1,59 @@
+#pragma once
+
+#ifdef __cplusplus
+
+#include
+#include
+#include
+#include
+
+namespace twml {
+
+// A low-level binary Thrift writer that can also compute output size
+// in dry run mode without copying memory. See also https://git.io/vNPiv
+//
+// WARNING: Users of this class are responsible for generating valid Thrift
+// by following the Thrift binary protocol (https://git.io/vNPiv).
+class TWMLAPI ThriftWriter {
+ protected:
+ bool m_dry_run;
+ uint8_t *m_buffer;
+ size_t m_buffer_size;
+ size_t m_bytes_written;
+
+ template inline uint64_t write(T val);
+
+ public:
+ // buffer: Memory to write the binary Thrift to.
+ // buffer_size: Length of the buffer.
+ // dry_run: If true, just count bytes 'written' but do not copy memory.
+ // If false, write binary Thrift to the buffer normally.
+ // Useful to determine output size for TensorFlow allocations.
+ ThriftWriter(uint8_t *buffer, size_t buffer_size, bool dry_run = false) :
+ m_dry_run(dry_run),
+ m_buffer(buffer),
+ m_buffer_size(buffer_size),
+ m_bytes_written(0) {}
+
+ // total bytes written to the buffer since object creation
+ uint64_t getBytesWritten();
+
+ // encode headers and values into the buffer
+ uint64_t writeStructFieldHeader(int8_t field_type, int16_t field_id);
+ uint64_t writeStructStop();
+ uint64_t writeListHeader(int8_t element_type, int32_t num_elems);
+ uint64_t writeMapHeader(int8_t key_type, int8_t val_type, int32_t num_elems);
+ uint64_t writeDouble(double val);
+ uint64_t writeInt8(int8_t val);
+ uint64_t writeInt16(int16_t val);
+ uint64_t writeInt32(int32_t val);
+ uint64_t writeInt64(int64_t val);
+ uint64_t writeBinary(const uint8_t *bytes, int32_t num_bytes);
+ // clients expect UTF-8-encoded strings per the Thrift protocol
+ // (often this is just used to send bytes, not real strings though)
+ uint64_t writeString(std::string str);
+ uint64_t writeBool(bool val);
+};
+
+}
+#endif
diff --git a/twml/libtwml/include/twml/Type.h b/twml/libtwml/include/twml/Type.h
new file mode 100644
index 000000000..8b460c812
--- /dev/null
+++ b/twml/libtwml/include/twml/Type.h
@@ -0,0 +1,69 @@
+#pragma once
+#include
+#include
+#include
+
+#ifdef __cplusplus
+namespace twml {
+
+ template struct Type;
+
+ template<> struct Type
+ {
+ enum {
+ type = TWML_TYPE_FLOAT,
+ };
+ };
+
+ template<> struct Type
+ {
+ enum {
+ type = TWML_TYPE_STRING,
+ };
+ };
+
+ template<> struct Type
+ {
+ enum {
+ type = TWML_TYPE_DOUBLE,
+ };
+ };
+
+ template<> struct Type
+ {
+ enum {
+ type = TWML_TYPE_INT64,
+ };
+ };
+
+ template<> struct Type
+ {
+ enum {
+ type = TWML_TYPE_INT32,
+ };
+ };
+
+ template<> struct Type
+ {
+ enum {
+ type = TWML_TYPE_INT8,
+ };
+ };
+
+ template<> struct Type
+ {
+ enum {
+ type = TWML_TYPE_UINT8,
+ };
+ };
+
+
+ template<> struct Type
+ {
+ enum {
+ type = TWML_TYPE_BOOL,
+ };
+ };
+
+}
+#endif
diff --git a/twml/libtwml/include/twml/common.h b/twml/libtwml/include/twml/common.h
new file mode 100644
index 000000000..c3a2e9aee
--- /dev/null
+++ b/twml/libtwml/include/twml/common.h
@@ -0,0 +1,42 @@
+#ifndef TWML_LIBTWML_INCLUDE_TWML_COMMON_H_
+#define TWML_LIBTWML_INCLUDE_TWML_COMMON_H_
+
+#define USE_ABSEIL_HASH 1
+
+#if defined(USE_ABSEIL_HASH)
+#include "absl/container/flat_hash_map.h"
+#include "absl/container/flat_hash_set.h"
+#elif defined(USE_DENSE_HASH)
+#include
+#include
+#else
+#include
+#include
+#endif // USE_ABSEIL_HASH
+
+
+namespace twml {
+#if defined(USE_ABSEIL_HASH)
+ template
+ using Map = absl::flat_hash_map;
+
+ template
+ using Set = absl::flat_hash_set;
+#elif defined(USE_DENSE_HASH)
+// Do not use this unless an proper empty key can be found.
+ template
+ using Map = google::dense_hash_map;
+
+ template
+ using Set = google::dense_hash_set;
+#else
+ template
+ using Map = std::unordered_map;
+
+ template
+ using Set = std::unordered_set;
+#endif // USE_DENSE_HASH
+
+} // namespace twml
+
+#endif // TWML_LIBTWML_INCLUDE_TWML_COMMON_H_
\ No newline at end of file
diff --git a/twml/libtwml/include/twml/defines.h b/twml/libtwml/include/twml/defines.h
new file mode 100644
index 000000000..e7f7d138d
--- /dev/null
+++ b/twml/libtwml/include/twml/defines.h
@@ -0,0 +1,36 @@
+#pragma once
+#include
+#ifdef __cplusplus
+extern "C" {
+#endif
+ typedef enum {
+ TWML_TYPE_FLOAT32 = 1,
+ TWML_TYPE_FLOAT64 = 2,
+ TWML_TYPE_INT32 = 3,
+ TWML_TYPE_INT64 = 4,
+ TWML_TYPE_INT8 = 5,
+ TWML_TYPE_UINT8 = 6,
+ TWML_TYPE_BOOL = 7,
+ TWML_TYPE_STRING = 8,
+ TWML_TYPE_FLOAT = TWML_TYPE_FLOAT32,
+ TWML_TYPE_DOUBLE = TWML_TYPE_FLOAT64,
+ TWML_TYPE_UNKNOWN = -1,
+ } twml_type;
+
+ typedef enum {
+ TWML_ERR_NONE = 1000,
+ TWML_ERR_SIZE = 1001,
+ TWML_ERR_TYPE = 1002,
+ TWML_ERR_THRIFT = 1100,
+ TWML_ERR_IO = 1200,
+ TWML_ERR_UNKNOWN = 1999,
+ } twml_err;
+#ifdef __cplusplus
+}
+#endif
+
+#define TWMLAPI __attribute__((visibility("default")))
+
+#ifndef TWML_INDEX_BASE
+#define TWML_INDEX_BASE 0
+#endif
diff --git a/twml/libtwml/include/twml/discretizer_impl.h b/twml/libtwml/include/twml/discretizer_impl.h
new file mode 100644
index 000000000..587bde458
--- /dev/null
+++ b/twml/libtwml/include/twml/discretizer_impl.h
@@ -0,0 +1,22 @@
+#pragma once
+#include
+#include
+#include
+
+#ifdef __cplusplus
+namespace twml {
+ TWMLAPI void discretizerInfer(
+ Tensor &output_keys,
+ Tensor &output_vals,
+ const Tensor &input_ids,
+ const Tensor &input_vals,
+ const Tensor &bin_ids,
+ const Tensor &bin_vals,
+ const Tensor &feature_offsets,
+ int output_bits,
+ const Map &ID_to_index,
+ int start_compute,
+ int end_compute,
+ int output_start);
+} // namespace twml
+#endif
diff --git a/twml/libtwml/include/twml/functions.h b/twml/libtwml/include/twml/functions.h
new file mode 100644
index 000000000..c23680cac
--- /dev/null
+++ b/twml/libtwml/include/twml/functions.h
@@ -0,0 +1,26 @@
+#pragma once
+#include
+#include
+
+#ifdef __cplusplus
+namespace twml {
+
+ // Adding these as an easy way to test the wrappers
+ TWMLAPI void add1(Tensor &output, const Tensor input);
+ TWMLAPI void copy(Tensor &output, const Tensor input);
+ TWMLAPI int64_t featureId(const std::string &feature);
+}
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ // Adding these as an easy way to test the wrappers
+ TWMLAPI twml_err twml_add1(twml_tensor output, const twml_tensor input);
+ TWMLAPI twml_err twml_copy(twml_tensor output, const twml_tensor input);
+ TWMLAPI twml_err twml_get_feature_id(int64_t *result, const uint64_t len, const char *str);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/twml/libtwml/include/twml/hashing_discretizer_impl.h b/twml/libtwml/include/twml/hashing_discretizer_impl.h
new file mode 100644
index 000000000..a04efb7e0
--- /dev/null
+++ b/twml/libtwml/include/twml/hashing_discretizer_impl.h
@@ -0,0 +1,22 @@
+#pragma once
+#include
+#include
+#include
+#include
+
+#ifdef __cplusplus
+namespace twml {
+ TWMLAPI void hashDiscretizerInfer(
+ Tensor &output_keys,
+ Tensor &output_vals,
+ const Tensor &input_ids,
+ const Tensor &input_vals,
+ int n_bin,
+ const Tensor &bin_vals,
+ int output_bits,
+ const Map &ID_to_index,
+ int start_compute,
+ int end_compute,
+ int64_t options);
+} // namespace twml
+#endif
diff --git a/twml/libtwml/include/twml/io/IOError.h b/twml/libtwml/include/twml/io/IOError.h
new file mode 100644
index 000000000..867ab44df
--- /dev/null
+++ b/twml/libtwml/include/twml/io/IOError.h
@@ -0,0 +1,45 @@
+#pragma once
+
+#include
+
+namespace twml {
+namespace io {
+
+class IOError : public twml::Error {
+ public:
+ enum Status {
+ OUT_OF_RANGE = 1,
+ WRONG_MAGIC = 2,
+ WRONG_HEADER = 3,
+ ERROR_HEADER_CHECKSUM = 4,
+ INVALID_METHOD = 5,
+ USING_RESERVED = 6,
+ ERROR_HEADER_EXTRA_FIELD_CHECKSUM = 7,
+ CANT_FIT_OUTPUT = 8,
+ SPLIT_FILE = 9,
+ BLOCK_SIZE_TOO_LARGE = 10,
+ SOURCE_LARGER_THAN_DESTINATION = 11,
+ DESTINATION_LARGER_THAN_CAPACITY = 12,
+ HEADER_FLAG_MISMATCH = 13,
+ NOT_ENOUGH_INPUT = 14,
+ ERROR_SOURCE_BLOCK_CHECKSUM = 15,
+ COMPRESSED_DATA_VIOLATION = 16,
+ ERROR_DESTINATION_BLOCK_CHECKSUM = 17,
+ EMPTY_RECORD = 18,
+ MALFORMED_MEMORY_RECORD = 19,
+ UNSUPPORTED_OUTPUT_TYPE = 20,
+ OTHER_ERROR
+ };
+
+ IOError(Status status);
+
+ Status status() const {
+ return m_status;
+ }
+
+ private:
+ Status m_status;
+};
+
+}
+}
diff --git a/twml/libtwml/include/twml/optim.h b/twml/libtwml/include/twml/optim.h
new file mode 100644
index 000000000..d0a2df4ef
--- /dev/null
+++ b/twml/libtwml/include/twml/optim.h
@@ -0,0 +1,51 @@
+#pragma once
+#include
+#include
+
+#ifdef __cplusplus
+namespace twml {
+ TWMLAPI void linearInterpolation(
+ Tensor output,
+ const Tensor input,
+ const Tensor xs,
+ const Tensor ys);
+
+ TWMLAPI void nearestInterpolation(
+ Tensor output,
+ const Tensor input,
+ const Tensor xs,
+ const Tensor ys);
+
+ TWMLAPI void mdlInfer(
+ Tensor &output_keys,
+ Tensor &output_vals,
+ const Tensor &input_keys,
+ const Tensor &input_vals,
+ const Tensor &bin_ids,
+ const Tensor &bin_vals,
+ const Tensor &feature_offsets,
+ bool return_bin_indices = false);
+}
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ TWMLAPI twml_err twml_optim_nearest_interpolation(
+ twml_tensor output,
+ const twml_tensor input,
+ const twml_tensor xs,
+ const twml_tensor ys);
+
+ TWMLAPI twml_err twml_optim_mdl_infer(
+ twml_tensor output_keys,
+ twml_tensor output_vals,
+ const twml_tensor input_keys,
+ const twml_tensor input_vals,
+ const twml_tensor bin_ids,
+ const twml_tensor bin_vals,
+ const twml_tensor feature_offsets,
+ const bool return_bin_indices = false);
+#ifdef __cplusplus
+}
+#endif
diff --git a/twml/libtwml/include/twml/utilities.h b/twml/libtwml/include/twml/utilities.h
new file mode 100644
index 000000000..a30b44aff
--- /dev/null
+++ b/twml/libtwml/include/twml/utilities.h
@@ -0,0 +1,18 @@
+#pragma once
+#ifdef __cplusplus
+namespace twml {
+
+inline int64_t mixDiscreteIdAndValue(int64_t key, int64_t value) {
+ key ^= ((17LL + value) * 2654435761LL);
+ return key;
+}
+
+inline int64_t mixStringIdAndValue(int64_t key, int32_t str_len, const uint8_t *str) {
+ int32_t hash = 0;
+ for (int32_t i = 0; i < str_len; i++) {
+ hash = (31 * hash) + (int32_t)str[i];
+ }
+ return key ^ hash;
+}
+}
+#endif
\ No newline at end of file
diff --git a/twml/libtwml/setup.cfg b/twml/libtwml/setup.cfg
new file mode 100644
index 000000000..d5253c179
--- /dev/null
+++ b/twml/libtwml/setup.cfg
@@ -0,0 +1,9 @@
+[bdist_wheel]
+universal=1
+
+[build]
+build-lib=build_dir
+build-temp=build_dir
+
+[bdist]
+bdist-base=build_dir
diff --git a/twml/libtwml/setup.py b/twml/libtwml/setup.py
new file mode 100644
index 000000000..2dcfa105d
--- /dev/null
+++ b/twml/libtwml/setup.py
@@ -0,0 +1,12 @@
+"""
+libtwml setup.py module
+"""
+from setuptools import setup, find_packages
+
+setup(
+ name='libtwml',
+ version='2.0',
+ description="Tensorflow C++ ops for twml",
+ packages=find_packages(),
+ data_files=[('', ['libtwml_tf.so'])],
+)
diff --git a/twml/libtwml/src/lib/BatchPredictionRequest.cpp b/twml/libtwml/src/lib/BatchPredictionRequest.cpp
new file mode 100644
index 000000000..cca8d6545
--- /dev/null
+++ b/twml/libtwml/src/lib/BatchPredictionRequest.cpp
@@ -0,0 +1,52 @@
+#include "internal/thrift.h"
+#include "internal/error.h"
+
+#include
+#include
+#include
+#include
+
+#include
+#include
+#include
+
+namespace twml {
+
+template
+void GenericBatchPredictionRequest::decode(Reader &reader) {
+ uint8_t feature_type = reader.readByte();
+ while (feature_type != TTYPE_STOP) {
+ int16_t field_id = reader.readInt16();
+
+ switch (field_id) {
+ case 1: {
+ CHECK_THRIFT_TYPE(feature_type, TTYPE_LIST, "list");
+ CHECK_THRIFT_TYPE(reader.readByte(), TTYPE_STRUCT, "list_element");
+
+ int32_t length = reader.readInt32();
+ m_requests.resize(length, RecordType(this->num_labels, this->num_weights));
+ for (auto &request : m_requests) {
+ request.decode(reader);
+ }
+
+ break;
+ }
+ case 2: {
+ CHECK_THRIFT_TYPE(feature_type, TTYPE_STRUCT, "commonFeatures");
+ m_common_features.decode(reader);
+ break;
+ }
+ default: throw ThriftInvalidField(field_id, __func__);
+ }
+
+ feature_type = reader.readByte();
+ }
+ return;
+}
+
+
+// Instantiate decoders.
+template void GenericBatchPredictionRequest::decode(HashedDataRecordReader &reader);
+template void GenericBatchPredictionRequest::decode(DataRecordReader &reader);
+
+} // namespace twml
diff --git a/twml/libtwml/src/lib/BatchPredictionResponse.cpp b/twml/libtwml/src/lib/BatchPredictionResponse.cpp
new file mode 100644
index 000000000..2a17d3605
--- /dev/null
+++ b/twml/libtwml/src/lib/BatchPredictionResponse.cpp
@@ -0,0 +1,125 @@
+#include "internal/endianutils.h"
+#include "internal/error.h"
+#include "internal/thrift.h"
+
+#include
+#include
+#include
+#include
+#include
+
+#include
+#include
+#include
+#include
+
+#include
+
+// When the number of predictions is very high, as some cases that Ads wants, the generic thrift
+// encoder becomes super expensive because we have to deal with lua tables.
+// This function is a special operation to efficiently write a batch prediction responses based on
+// tensors.
+namespace twml {
+
+BatchPredictionResponse::BatchPredictionResponse(
+ const Tensor &keys, const Tensor &values,
+ const Tensor &dense_keys, const std::vector &dense_values
+) : keys_(keys), values_(values), dense_keys_(dense_keys), dense_values_(dense_values) {
+ // determine batch size
+ if (values_.getNumDims() > 0) {
+ batch_size_ = values_.getDim(0);
+ } else if (dense_keys_.getNumElements() < 1) {
+ throw twml::Error(TWML_ERR_TYPE, "Continuous values and dense tensors are both empty");
+ } else if (dense_keys_.getNumElements() != dense_values_.size()) {
+ throw twml::Error(TWML_ERR_TYPE, "Number of tensors not equal to number of keys");
+ } else {
+ // dim 0 for each tensor indexes batch elements
+ std::vector batch_sizes;
+ batch_sizes.reserve(dense_values_.size());
+
+ for (int i = 0; i < dense_values_.size(); i++)
+ batch_sizes.push_back(dense_values_.at(i).getDim(0));
+
+ if (std::adjacent_find(
+ batch_sizes.begin(),
+ batch_sizes.end(),
+ std::not_equal_to()) != batch_sizes.end())
+ throw twml::Error(TWML_ERR_TYPE, "Batch size (dim 0) for all tensors must be the same");
+
+ batch_size_ = dense_values.at(0).getDim(0);
+ }
+}
+
+void BatchPredictionResponse::encode(twml::ThriftWriter &thrift_writer) {
+ if (hasContinuous()) {
+ switch (values_.getType()) {
+ case TWML_TYPE_FLOAT:
+ serializePredictions(thrift_writer);
+ break;
+ case TWML_TYPE_DOUBLE:
+ serializePredictions(thrift_writer);
+ break;
+ default:
+ throw twml::Error(TWML_ERR_TYPE, "Predictions must be float or double.");
+ }
+ } else {
+ // dense tensor predictions
+ serializePredictions(thrift_writer);
+ }
+}
+
+template