October 2026 main drop: mirror from GitHub
Browse filesThis view is limited to 50 files because it contains too many changes. Β See raw diff
Files changed (50)
- .gitattributes+2
- .gitignoreAdded+6
- LICENSEAdded+235
- README.mdAdded+17
- astra/agents.aplAdded+110
- astra/bench.aplAdded+98
- astra/dagseal.aplAdded+198
- astra/orchestrate.aplAdded+67
- astra/routing.aplAdded+128
- astra/run.aplAdded+120
- astra/zint.aplAdded+462
- docs/ARCHITECTURE.mdAdded+86
- docs/ASTRA.mdAdded+33
- docs/BENCHMARKS.mdAdded+52
- docs/SEAL.mdAdded+66
- docs/SPEC.mdAdded+91
- docs/demo-transcript.txtAdded+129
- docs/images/architecture.svgAdded
- docs/images/demo-transcript.pngAdded
- docs/result_schema.jsonAdded+31
- j/bench.ijsAdded+100
- j/biencoder.ijsAdded+264
- j/sha512.ijsAdded+271
- j/train_step.ijsAdded+210
- r/bench.RAdded+116
- r/biencoder.RAdded+287
- r/sha512.RAdded+389
- r/train_step.RAdded+249
- reference/__init__.pyAdded
- reference/biencoder.pyAdded+15
- reference/goldilocks.pyAdded+154
- reference/reduction_algebra.pyAdded+411
- results/benchmarks.jsonAdded+103
- results/biencoder_result.jsonAdded+1610
- results/pipeline_result.jsonAdded+274
- results/train_step_result.jsonAdded+1003
- scripts/run_astra.shAdded+12
- scripts/run_astra_bench.shAdded+9
- scripts/run_benchmarks.pyAdded+304
- scripts/run_biencoder.pyAdded+417
- scripts/run_pipeline.pyAdded+320
- scripts/run_tinyapl_demo.shAdded+4
- scripts/run_train_step.pyAdded+392
- tests/test_biencoder.pyAdded+106
- tests/test_correctness.pyAdded+19
- tests/test_train_step.pyAdded+101
- tests/vectors/deterministic.jsonAdded+215
- tinyapl/biencoder.aplAdded+22
- tinyapl/biencoder_demo.aplAdded+58
- tinyapl/crypto_stub.aplAdded+10
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textdocs/images/demo-transcript.png filter=lfs diff=lfs merge=lfs -textvendor/tinyapl filter=lfs diff=lfs merge=lfs -text
123456__pycache__/*.pyc.~lock**.lock#
results/_tmp_*.apl123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235GNU AFFERO GENERAL PUBLIC LICENSEVersion 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
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 thosesubprograms 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 patentlicense 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 maynot 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.
<one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/licenses/>.1234567891011121314151617---license: agpl-3.0tags:- snapkitty- october-2026-drop- apl- j- r- python- subleq- attention- array-programming- machine-learning---
> Mirrored from [https://github.com/SNAPKITTYWEST/sovereign-reduction-algebra](https://github.com/SNAPKITTYWEST/sovereign-reduction-algebra) at commit `35f55f2`. Part of the **SnapKitty October 2026 main drop**.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110β Astra APL: agent registry and numerical specialist implementations.β An agent receives a nested request: numeric-data prior-proposals round.β A proposal is a numeric vector; specialists may implement any APL functionβ with this calling convention. These built-ins compute real estimators.
β ResetAgents AgentProfilesββ¬ AgentFunctionsββ¬β
β ZβRegister X;P;F;I β Input: profile function-name. Return index, or zero when rejected. Zβ0 β(2β β΄X)/0 PββX[1] FββX[2] β(5β β΄P)/0 β(3β βNC F)/0 Iβ1LOOP:β(I>β΄AgentProfiles)/ADD β((βP[1])β‘β(βAgentProfiles[I])[1])/0 IβI+1 βLOOPADD:AgentProfilesβAgentProfiles,βP AgentFunctionsβAgentFunctions,βF Zββ΄AgentProfilesβ
β ZβMeanAgent Request;X XββRequest[1] Zββ¬ β(0=β΄X)/0 Zβ,(+/X)Γ·β΄Xβ
β ZβMedianAgent Request;X;N;S XββRequest[1] Zββ¬ Nββ΄X β(N=0)/0 SβX[βX] Zβ,0.5ΓS[βNΓ·2]+S[1+βNΓ·2]β
β ZβTrimmedAgent Request;X;N;Drop;S XββRequest[1] Zββ¬ Nββ΄X β(N=0)/0 DropββNΓ·5 SβX[βX] SβDropβ(-Drop)βS Zβ,(+/S)Γ·β΄Sβ
β ZβMidrangeAgent Request;X XββRequest[1] Zββ¬ β(0=β΄X)/0 Zβ,0.5Γ(β/X)+β/Xβ
β ZβWinsorAgent Request;X;N;S;D;Low;High XββRequest[1] Zββ¬ Nββ΄X β(N=0)/0 SβX[βX] DββNΓ·5 LowβS[1+D] HighβS[N-D] SβLowβHighβX Zβ,(+/S)Γ·Nβ
β ZβConsensusAgent Request;X;Prior;I;Values XββRequest[1] PriorββRequest[2] β(0=β΄Prior)/FIRST Valuesββ¬ Iβ1LOOP:β(I>β΄Prior)/DONE ValuesβValues,βPrior[I] IβI+1 βLOOPDONE:ZβMedianAgent (βValues),(ββ¬),β1 β0FIRST:ZβMedianAgent Requestβ
β ZβWeightedMean X;Weights;Values;I;Width;P β Input: weights and nested proposals. Reject incompatible dimensions. Zββ¬ WeightsββX[1] ValuesββX[2] β(0=β΄Values)/0 β((β΄Weights)β β΄Values)/0 β(β¨/Weights<0)/0 β((+/Weights)β€0)/0 Widthββ΄βValues[1] β(Width=0)/0 PβWidthβ΄0 Iβ1LOOP:β(I>β΄Values)/DONE β(Widthβ β΄βValues[I])/0 PβP+Weights[I]ΓβValues[I] IβI+1 βLOOPDONE:ZβPΓ·+/Weightsβ1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798β Astra N=128 zint matmul and DAG seal timings.β Seconds are integer microseconds from βFIO[50] 1000000, formatted byβ splitting the decimal digits. No float timer. AGPL-3.0 only.
β ZβZSecs US;D;SEC;FRAC DββUS β((β΄D)>6)/BIG Dβ((6-β΄D)β΄'0'),D Zβ'0.',D β0BIG:SECβ(Β―6)βD FRACβ(Β―6)βD ZβSEC,'.',FRACβ
β ZβN ZFill Off;I;V;M Vββ¬ Iβ0 MβNΓNLOOP:β(Iβ₯M)/SH VβV,βZFromInt 5|Off+I IβI+1 βLOOPSH:Zβ(N,N)β΄Vβ
β ZβZSum M;I;V;S Vβ,M Sβ,0 Iβ1LOOP:β(I>β΄V)/DONE SβS ZAdd βV[I] IβI+1 βLOOPDONE:ZβSβ
β ZβN ZBench Trials;A;B;C;I;T0;T1;S;NB ββ'BENCH_V1' ββ'LANGUAGE' ββ'GNU APL' ββ'TIMER' ββ'βFIO[50] 1000000' AβN ZFill 0 BβN ZFill NΓN T0ββFIO[50] 1000000 CβA ZMM B T1ββFIO[50] 1000000 ββ'UNTIMED_US' ββT1-T0 SβZDec ZSum C ββ'CHECKSUM' ββS ββ'RECORD' ββ'SIZE' βββN ββ'OP' ββ'unmasked_integer_matmul' ββ'TRIALS' βββTrials ββ'SECONDS' Iβ1LOOP:β(I>Trials)/SEAL T0ββFIO[50] 1000000 CβA ZMM B T1ββFIO[50] 1000000 ββZSecs T1-T0 IβI+1 βLOOPSEAL:PββZPowP WβZMat 4 4β΄0 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0 ββ'RECORD' ββ'SIZE' βββN ββ'OP' ββ'sha512_dag_seal' ββ'TRIALS' βββTrials ββ'SECONDS' Iβ1SLOOP:β(I>Trials)/DONE T0ββFIO[50] 1000000 HEXβZDag (βC),(βC),(βW),βP T1ββFIO[50] 1000000 ββZSecs T1-T0 IβI+1 βSLOOPDONE:NBββ΄'exact_head' ZNode C ββ'SEAL' ββHEX ββ'NODE_BYTES' βββNB ββ'BENCH_DONE' ZβHEXβ
HEXβ128 ZBench 3)OFF 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198β Astra APL: canonical SHA-512 DAG seal and the seeded SUBLEQ bi-encoder.β Bytes match j/sha512.ijs node layout SRANOD01 / SRADAG01. The hasher isβ sha512sum over those raw bytes, not over interpreter display text.β Integers are zints from astra/zint.apl. AGPL-3.0 only.
β ZβZBytes S ZββUCS Sβ
β ZβZBe32 N;P ZAssertInt N β((Nβ₯0)β§N<4294967296)/GO ββ'BE32_RANGE' βES 'BE32_RANGE'GO:PβN Zβ4β΄0 Z[1]ββPΓ·16777216 Pβ16777216|P Z[2]ββPΓ·65536 Pβ65536|P Z[3]ββPΓ·256 Z[4]β256|Pβ
β ZβZShaRaw Bytes;FN;H;N;L FNβ'/tmp/astra-preimage.bin' Hβ'wb' βFIO[3] FN NβBytes βFIO[7] H NββFIO[4] H Hβ'r' βFIO[24] 'sha512sum /tmp/astra-preimage.bin' LββFIO[8] H NββFIO[25] H β(Nβ₯0)/OK ββ'SHA_PCLOSE' βES 'SHA_PCLOSE'OK:β((β΄L)β₯128)/DONE ββ'SHA_SHORT' βES 'SHA_SHORT'DONE:Zβ128βLβ
β ZβZHexToBin H;D;I;HI;LO DββUCS '0123456789abcdef' Zβ64β΄0 Iβ0LOOP:β(Iβ₯64)/0 HIβΒ―1+Dβ³H[1+2ΓI] LOβΒ―1+Dβ³H[2+2ΓI] β((HIβ₯0)β§LOβ₯0)/ST ββ'HEX_DRIFT' βES 'HEX_DRIFT'ST:Z[I+1]β(16ΓHI)+LO IβI+1 βLOOPβ
β ZβRole ZNode Tensor;SH;RK;I;VALS;B;D;DB;CNT SHββ΄Tensor RKβββ΄β΄Tensor VALSβ,Tensor CNTβββ΄VALS BβZBytes 'SRANOD01' BβB,ZBe32 ββ΄Role BβB,ZBytes Role BβB,ZBe32 RK Iβ1LOOP:β(I>RK)/CNTS BβB,ZBe32 SH[I] IβI+1 βLOOPCNTS:BβB,ZBe32 CNT Iβ1VLOOP:β(I>CNT)/CHK DβZDec βVALS[I] DBβZBytes D BβB,ZBe32 ββ΄DB BβB,DB IβI+1 βVLOOPCHK:β(β§/(Bβ₯0)β§B<128)/OK ββ'NON_ASCII_NODE' βES 'NON_ASCII_NODE'OK:ZβBβ
β ZβZDag T;EX;PR;W;P;B1;B2;B3;B4;D1;D2;D3;D4;B EXββT[1] PRββT[2] WββT[3] PββT[4] B1β'exact_head' ZNode EX B2β'predicted' ZNode PR B3β'weights' ZNode W B4β'prime' ZNode P D1βZHexToBin ZShaRaw B1 D2βZHexToBin ZShaRaw B2 D3βZHexToBin ZShaRaw B3 D4βZHexToBin ZShaRaw B4 BβZBytes 'SRADAG01' BβB,ZBe32 4 BβB,D1,D2,D3,D4 ZββUCS ZShaRaw Bβ
β ZβSeed ZLCG N;A;M;R;I;V;OUT AβZFromInt 48271 MβZFromInt 2147483647 RβZFromInt 5 OUTββ¬ Iβ1LOOP:β(I>N)/DONE Seedβ(A ZMul Seed) ZMod M VβSeed ZMod R OUTβOUT,βV IβI+1 βLOOPDONE:Zβ(βOUT),βSeedβ
β ZβQ ZPredRow K;N;I;S;D;T;Zero Nββ΄Q Sβ,0 Zeroβ,0 Iβ1LOOP:β(I>N)/DONE Dβ(βK[I]) ZSub βQ[I] β((D ZCmp Zero)>0)/NX Tβ(βQ[I]) ZMul βK[I] SβS ZAdd TNX:IβI+1 βLOOPDONE:ZβSβ
β ZβQ ZPredict K;R;C;I;J Rβββ΄Q Cβββ΄K Zβ(R,C)β΄β,0 Iβ1ILO:β(I>R)/0 Jβ1JLO:β(J>C)/IN Z[I;J]ββ(Q[I;]) ZPredRow K[J;] JβJ+1 βJLOIN:IβI+1 βILOβ
β ZShowMat M;R;C;I;J;ROW;D Rβββ΄M Cβ(β΄M)[2] Iβ1LOOP:β(I>R)/0 ROWβ'' Jβ1JLO:β(J>C)/PR DβZDec βM[I;J] β(J=1)/FR ROWβROW,' ',D βNXFR:ROWβDNX:JβJ+1 βJLOPR:ββROW IβI+1 βLOOPβ
β ZβZRunSeeded;S0;R1;AV;S1;R2;BV;A;B;W;Q;K;EX;REF;PR;PM;CELL;T;SE;SM S0βZFromInt 20261002 R1βS0 ZLCG 16 AVββR1[1] S1ββR1[2] R2βS1 ZLCG 16 BVββR2[1] Aβ4 4β΄AV Bβ4 4β΄BV WβZMat 4 4β΄0 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0 QβA ZMM W Kβ(βB) ZMM W EXβQ ZMM βK REFβA ZMM B PRβQ ZPredict K PMβPR CELLβ(βPR[1;1]) ZAdd ZFromInt 1 PM[1;1]ββCELL Tβ(βEX),(βPR),(βW),ββZPowP SEβZDag T Tβ(βEX),(βPM),(βW),ββZPowP SMβZDag T Zβ(βA),(βB),(βQ),(βK),(βEX),(βREF),(βPR),(βPM),(βSE),βSMβ
β ZβZPowP Zβ(ZPow2 64) ZSub ZPow2 32 ZβZ ZAdd ZFromInt 1β12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667β Astra APL: bounded-round orchestration with budget accounting.β Execution is synchronous in GNU APL. No concurrency or preemption claim.
β ZβFunction Invoke Request;Caught;Value β Function is a registered APL name, never text obtained from the prompt. Valueββ¬ CaughtββEC 'Valueβ',Function,' Request' Zβ(β0),ββ¬ β(0=βCaught[1])/0 β(0=β΄Value)/0 Zβ(β1),βValueβ
β ZβMixture Config;Prompt;Data;Need;Want;K;Budget;Rounds;Round;Spent;Excluded;Previous;History;Failures;Routes;Request;Decision;IDs;Weights;Good;GoodWeights;I;ID;Outcome;Function;Answer;Remaining β Config: prompt data required preferred top-k total-budget round-count. β Result: answer history routes failures spent success. PromptββConfig[1] DataββConfig[2] NeedββConfig[3] WantββConfig[4] KββConfig[5] BudgetββConfig[6] RoundsββConfig[7] Roundβ1 Spentβ0 Excludedββ¬ Previousββ¬ Historyββ¬ Failuresββ¬ Routesββ¬ Answerββ¬ Zβ(βAnswer),(βHistory),(βRoutes),(βFailures),(βSpent),β0 β((Roundsβ€0)β¨Roundsβ βRounds)/0LOOP:β(Round>Rounds)/DONE RemainingβBudget-Spent β(Remainingβ€0)/DONE Requestβ(βPrompt),(βNeed),(βWant),(βK),(βRemaining),βExcluded DecisionβAgentProfiles Route Request IDsββDecision[1] WeightsββDecision[2] β(0=β΄IDs)/DONE RoutesβRoutes,βDecision SpentβSpent+βDecision[4] Goodββ¬ GoodWeightsββ¬ Requestβ(βData),(βPrevious),βRound Iβ1AGENT:β(I>β΄IDs)/AGGREGATE IDβIDs[I] FunctionββAgentFunctions[ID] OutcomeβFunction Invoke Request β(0=βOutcome[1])/FAIL GoodβGood,Outcome[2] GoodWeightsβGoodWeights,Weights[I] HistoryβHistory,β(βRound),(βID),Outcome[2] βNEXTFAIL:ExcludedβUnique Excluded,ID FailuresβFailures,βRound IDNEXT:IβI+1 βAGENTAGGREGATE:β(0=β΄Good)/ADVANCE PreviousβGood AnswerβWeightedMean (βGoodWeights),βGoodADVANCE:RoundβRound+1 βLOOPDONE:Zβ(βAnswer),(βHistory),(βRoutes),(βFailures),(βSpent),β0<β΄Answerβ123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128β Astra APL: deterministic capability and budget routing.β All indices are one-origin. No external routing framework is used.β A profile is (name capabilities keywords cost enabled).
β ZβLower X;U;L;I;M Uβ'ABCDEFGHIJKLMNOPQRSTUVWXYZ' Lβ'abcdefghijklmnopqrstuvwxyz' Zβ,X IβUβ³Z MβIβ€β΄U Z[M/β³β΄Z]βL[M/I]β
β ZβTokens X;S;A;I;W SβLower X Aβ'abcdefghijklmnopqrstuvwxyz0123456789_' Zββ¬ Wβ'' Iβ1LOOP:β(I>β΄S)/END β(~S[I]βA)/BREAK WβW,S[I] βNEXTBREAK:β(0=β΄W)/NEXT ZβZ,βW Wβ''NEXT:IβI+1 βLOOPEND:β(0=β΄W)/0 ZβZ,βWβ
β ZβUnique X;I Zββ¬ Iβ1LOOP:β(I>β΄X)/0 β(β¨/X[I]βZ)/NEXT ZβZ,X[I]NEXT:IβI+1 βLOOPβ
β ZβProfile X;N;C;K;V;E β Construct a validated profile from a five-element nested vector. Zββ¬ β(5β β΄X)/0 NββX[1] CββX[2] KββX[3] VββX[4] EββX[5] β(0=β΄N)/0 β(1β β‘V)/0 β(Vβ€0)/0 β(~Eβ0 1)/0 Zβ(βN),(βUnique C),(βUnique Tokens K),(βV),βEβ
β ZβRequired Eligible P;Caps CapsββP[2] Zβ(βP[5])β§β§/RequiredβCapsβ
β ZβNormalize X;T Zβ0ΓX β(0=β΄X)/0 Tβ+/X β(Tβ€0)/0 ZβXΓ·Tβ
β ZβProfiles Route Request;Text;Need;Want;K;Budget;Excluded;Query;Used;Covered;IDs;Scores;Spent;Matches;NewCaps;I;P;Cost;Score;Utility;Best;BestUtility;BestScore;BestCost;Tie;Weights β Request: prompt required preferred top-k budget excluded-indices. β Result: selected-indices weights raw-scores total-cost. TextββRequest[1] NeedββRequest[2] WantββRequest[3] KββRequest[4] BudgetββRequest[5] ExcludedββRequest[6] QueryβUnique Tokens Text UsedβExcluded Coveredββ¬ IDsββ¬ Scoresββ¬ Spentβ0 Zβ(βIDs),(βIDs),(βIDs),βSpent β((Kβ€0)β¨Kβ βK)/0 β(Budgetβ€0)/0ROUND:β((β΄IDs)β₯K)/DONE Bestβ0 BestUtilityβΒ―1 BestScoreβ0 BestCostβ0 Iβ1SCAN:β(I>β΄Profiles)/CHOOSE β(IβUsed)/NEXT PββProfiles[I] β(~Need Eligible P)/NEXT CostββP[4] β(Cost>Budget-Spent)/NEXT Matchesβ+/QueryββP[3] NewCapsβ((βP[2])βWant)β§~(βP[2])βCovered Scoreβ1+(2ΓMatchesΓ·1ββ΄Query)+3Γ+/NewCaps UtilityβScoreΓ·Cost β(Utility>BestUtility)/KEEP β(Utility<BestUtility)/NEXT β(Cost<BestCost)/KEEP β(Cost>BestCost)/NEXT β Stable registration order is the final tie breaker. βNEXTKEEP:BestβI BestUtilityβUtility BestScoreβScore BestCostβCostNEXT:IβI+1 βSCANCHOOSE:β(Best=0)/DONE IDsβIDs,Best ScoresβScores,BestScore UsedβUsed,Best PββProfiles[Best] CoveredβUnique Covered,βP[2] SpentβSpent+BestCost βROUNDDONE:WeightsβNormalize Scores Zβ(βIDs),(βWeights),(βScores),βSpentβ123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120β Astra APL driver. Runs the registry, the seeded bi-encoder, and the DAG seal.β AGPL-3.0 only.
β ZβA ZAllEq B;VA;VB;I;N VAβ,A VBβ,B Nββ΄VA Zβ1 Iβ1LOOP:β(I>N)/0 β((ZDec βVA[I])β‘ZDec βVB[I])/NX Zβ0 β0NX:IβI+1 βLOOPβ
βPWβ400ββ'ASTRA_V1'ββ'INTERPRETER'ββ'GNU APL'STβZSelfTestββ'ZINT_SELFTEST'ββSTABCββUCS ZShaRaw ZBytes 'abc'ββ'SHA512_ABC'ββABCEMPββUCS ZShaRaw β¬ββ'SHA512_EMPTY'ββEMPββ'NATIVE_2_63'βββ2*63ββ'ZINT_2_64'ββZDec ZPow2 64ββ'ZINT_P'PPβZPowPββZDec PPRβZRunSeededAββR[1]BββR[2]QββR[3]KββR[4]EXββR[5]REFββR[6]PRββR[7]PMββR[8]SEββR[9]SMββR[10]ββ'A'ZShowMat Aββ'B'ZShowMat Bββ'Q'ZShowMat Qββ'KTOWER'ZShowMat Kββ'EXACT_HEAD'ZShowMat EXββ'REFERENCE'ZShowMat REFββ'PREDICTED'ZShowMat PRββ'EXACT_EQUALS_REFERENCE'ββEX ZAllEq REFββ'MUTATED_PREDICTED'ZShowMat PMWANTβ'e6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6e'ββ'SEAL'ββSEββ'SEAL_MATCH'SMATCHβSEβ‘WANTββSMATCHββ'MUTATED_SEAL'ββSMββ'MUTATED_DIFFERS'ββSEβ’SMResetAgentsCapsβ(β'stats'),β'mean'PβProfile (β'mean'),(βCaps),(β'mean average'),(β,1),β1I1βRegister (βP),β'MeanAgent'Capsβ(β'stats'),β'median'PβProfile (β'median'),(βCaps),(β'median middle'),(β,1),β1I2βRegister (βP),β'MedianAgent'Capsβ(β'stats'),(β'trimmed'),β'robust'PβProfile (β'trimmed'),(βCaps),(β'trimmed robust'),(β,2),β1I3βRegister (βP),β'TrimmedAgent'Capsβ(β'stats'),β'midrange'PβProfile (β'midrange'),(βCaps),(β'midrange range'),(β,1),β1I4βRegister (βP),β'MidrangeAgent'Capsβ(β'stats'),(β'winsor'),β'robust'PβProfile (β'winsor'),(βCaps),(β'winsor robust'),(β,2),β1I5βRegister (βP),β'WinsorAgent'Capsβ(β'stats'),β'consensus'PβProfile (β'consensus'),(βCaps),(β'consensus vote'),(β,1),β1I6βRegister (βP),β'ConsensusAgent'ββ'REGISTRY_INDEX'ββI1,I2,I3,I4,I5,I6Reqβ(β'robust mean estimate'),(ββ'stats'),(ββ'robust'),(β2),(β5),ββ¬DecβAgentProfiles Route Reqββ'ROUTE_IDS'βββDec[1]ββ'ROUTE_WEIGHTS'βββDec[2]ββ'ROUTE_SCORES'βββDec[3]ββ'ROUTE_COST'βββDec[4]Cfgβ(β'robust mean estimate'),(β3 8 1 9 2 7 4),(ββ'stats'),(ββ'robust'),(β2),(β6),β2MixβMixture Cfgββ'MIX_ANSWER'βββMix[1]ββ'MIX_SPENT'βββMix[5]ββ'MIX_SUCCESS'βββMix[6]ββ'MIX_FAILURES'βββMix[4]ββ'ASTRA_DONE'CODEβ1-SMATCHβ')OFF ',βCODE123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462β Astra APL: arbitrary-precision integers as base-10^9 limbs.β Limb vectors are the type of the arithmetic, including matrix multiply.β GNU APL signed integers become IEEE floats past about 2^63. This codeβ never uses that path. AGPL-3.0 only, same as the repository.ββ A zint is a simple integer vector: sign (Β―1, 0, or 1) then little-endianβ limbs in 0..ZBASE-1. Zero is ,0. Monadic β discloses, so the sign is β.
ZBASEβ1000000000ZPOW62β2*62
β ZAssertInt P;S SββP β(0=β¨/Sβ'Ee.')/0 ββ'FLOAT_DRIFT' ββS βES 'FLOAT_DRIFT'β
β ZβZIntFromDigits S;I;D Zβ0 Iβ1 Dβ'0123456789'LOOP:β(I>β΄S)/0 β(~S[I]βD)/BAD Zβ(10ΓZ)+Β―1+Dβ³S[I] IβI+1 βLOOPBAD:ββ'DIGIT_DRIFT' βES 'DIGIT_DRIFT'β
β ZβZLimbsFromScalar P;S;L;W ZAssertInt P β(P=0)/ZERO Sβ(βP)~' ' Lββ¬LOOP:β((β΄S)>9)/PEEL LβL,ZIntFromDigits S ZβL β0PEEL:Wβ(Β―9)βS Sβ(Β―9)βS LβL,ZIntFromDigits W βLOOPZERO:Zβ,0β
β ZβZFromInt N;S ZAssertInt N Sβ1 β(Nβ₯0)/POS SβΒ―1 Nβ-NPOS:β(N=0)/ZERO β(N<ZBASE)/ONE ZβS,ZLimbsFromScalar N β0ONE:ZβS,N β0ZERO:Zβ,0β
β ZβZPack X;S;L;N SββX Lβ1βX Nββ΄LLOOP:β(Nβ€0)/ZERO β(L[N]β 0)/DONE NβN-1 βLOOPDONE:ZβS,NβL β0ZERO:Zβ,0β
β ZβZSplitBase P;POW;Q;R β Exact integer division of a signed-64 scalar by ZBASE. ZAssertInt P β(Pβ₯0)/GO ββ'NEG_SPLIT' βES 'NEG_SPLIT'GO:POWβZPOW62 Qβ0 Rβ0LOOP:β(POW=0)/DONE Rβ2ΓR β(P<POW)/NOB PβP-POW RβR+1NOB:β(R<ZBASE)/NQ RβR-ZBASE Qβ(2ΓQ)+1 βNXNQ:Qβ2ΓQNX:POWββPOWΓ·2 βLOOPDONE:β(P=0)/OK ββ'SPLIT_LEFTOVER' ββP βES 'SPLIT_LEFTOVER'OK:ZβR,Qβ
β ZβZNeg A ZβA β((βZ)=0)/0 Z[1]β-Z[1]β
β ZβZAbs A ZβA β((βZ)β Β―1)/0 Z[1]β1β
β ZβA ZCmpAbs B;LA;LB;I LAβ1βA LBβ1βB β((β΄LA)β β΄LB)/LD Zβ0 Iββ΄LALOOP:β(I<1)/0 β(LA[I]=LB[I])/NX β(LA[I]>LB[I])/GT ZβΒ―1 β0GT:Zβ1 β0NX:IβI-1 βLOOPLD:β((β΄LA)>β΄LB)/GT ZβΒ―1β
β ZβA ZCmp B;SA;SB;C SAββA SBββB β(SAβ SB)/SD β(SA=0)/EQ CβA ZCmpAbs B ZβSAΓC β0SD:β(SA>SB)/GT ZβΒ―1 β0GT:Zβ1 β0EQ:Zβ0β
β ZβA ZAddAbs B;LA;LB;N;ACC;I;P;RQ;C;T LAβ1βZAbs A LBβ1βZAbs B Nβ(β΄LA)ββ΄LB ACCβNβ΄0 β((β΄LA)=0)/ZC ACC[β³β΄LA]βLAZC:Cβ0 Iβ1LOOP:β(I>N)/FIN PβACC[I]+C β(I>β΄LB)/NC PβP+LB[I]NC:RQβZSplitBase P ACC[I]βRQ[1] CβRQ[2] IβI+1 βLOOPFIN:β(C=0)/PACK ACCβACC,CPACK:ZβZPack 1,ACCβ
β ZβA ZSubAbs B;LA;LB;N;ACC;I;T;P;Borr β |A|-|B| with |A|β₯|B|. LAβ1βZAbs A LBβ1βZAbs B Nββ΄LA ACCβLA Iβ1 Borrβ0LOOP:β(I>N)/FIN Tβ0 β(I>β΄LB)/NT TβLB[I]NT:Pβ(ACC[I]-T)-Borr β(Pβ₯0)/OK PβP+ZBASE Borrβ1 βSTOK:Borrβ0ST:ACC[I]βP IβI+1 βLOOPFIN:β(Borr=0)/PACK ββ'BORROW' βES 'BORROW'PACK:ZβZPack 1,ACCβ
β ZβA ZAdd B;SA;SB;C SAββA SBββB β(SA=0)/RETB β(SB=0)/RETA β(SAβ SB)/DIF ZβA ZAddAbs B β(SA=1)/0 ZβZNeg Z β0DIF:CβA ZCmpAbs B β(C=0)/ZERO β(C=Β―1)/BL ZβA ZSubAbs B β(SA=1)/0 ZβZNeg Z β0BL:ZβB ZSubAbs A β(SB=1)/0 ZβZNeg Z β0ZERO:Zβ,0 β0RETB:ZβB β0RETA:ZβAβ
β ZβA ZSub B ZβA ZAdd ZNeg Bβ
β ZβA ZMul B;SA;SB;LA;LB;NA;NB;ACC;I;J;IDX;P;RQ;C;K SAββA SBββB β((SA=0)β¨SB=0)/ZERO LAβ1βA LBβ1βB NAββ΄LA NBββ΄LB ACCβ(NA+NB)β΄0 Iβ1ILO:β(I>NA)/PACK Jβ1JLO:β(J>NB)/JN IDXβI+J-1 PβACC[IDX]+LA[I]ΓLB[J] RQβZSplitBase P ACC[IDX]βRQ[1] CβRQ[2] KβIDX+1CLO:β(C=0)/JN2 β(Kβ€β΄ACC)/IN ACCβACC,0IN:PβACC[K]+C RQβZSplitBase P ACC[K]βRQ[1] CβRQ[2] KβK+1 βCLOJN2:JβJ+1 βJLOJN:IβI+1 βILOPACK:ZβZPack (SAΓSB),ACC β0ZERO:Zβ,0β
β ZβZOdd X;L β((βX)=0)/ZERO Lβ1βX Zβ2|βL β0ZERO:Zβ0β
β ZβZHalf X;L;N;I;C;P β((βX)=0)/ZERO β((βX)=Β―1)/NEG Lβ1βX Nββ΄L Cβ0 IβNLOOP:β(I<1)/DONE PβL[I]+CΓZBASE L[I]ββPΓ·2 Cβ2|P IβI-1 βLOOPDONE:ZβZPack 1,L β0NEG:ZβZNeg ZHalf ZNeg X β0ZERO:Zβ,0β
β ZβZBits X;W;B β((βX)=Β―1)/NEG WβX Bββ¬LOOP:β((βW)=0)/DONE BβB,ZOdd W WβZHalf W βLOOPDONE:ZβB β0NEG:ZβZBits ZNeg Xβ
β ZβA ZDivMod M;BITS;Q;R;I β((βM)β 1)/ERR β((βA)=Β―1)/ERR BITSβZBits A Qβ,0 Rβ,0 Iββ΄BITSLOOP:β(I<1)/DONE RβR ZAdd R β(BITS[I]=0)/NO RβR ZAdd ZFromInt 1NO:β((R ZCmp M)<0)/SH RβR ZSub M Qβ(Q ZAdd Q) ZAdd ZFromInt 1 βNXSH:QβQ ZAdd QNX:IβI-1 βLOOPDONE:Zβ(βQ),βR β0ERR:ββ'DIV_DOMAIN' βES 'DIV_DOMAIN'β
β ZβA ZMod M Zββ(A ZDivMod M)[2]β
β ZβZDec X;S;L;H;W;DIG;I;P;D;J SββX β(S=0)/ZERO Lβ1βX DIGβ'0123456789' HβL[β΄L] Wβ''HP:β(H=0)/LO WβDIG[1+10|H],W HββHΓ·10 βHPLO:Iβ(β΄L)-1ILO:β(I<1)/SIG PβL[I] Dβ9β΄'0' Jβ9JL:β(J<1)/PUT D[J]βDIG[1+10|P] PββPΓ·10 JβJ-1 βJLPUT:WβW,D IβI-1 βILOSIG:ZβW β(S=1)/0 Zβ'-',W β0ZERO:Zβ,'0'β
β ZβZPow2 E;I ZβZFromInt 1 Iβ0LOOP:β(Iβ₯E)/0 ZβZ ZAdd Z IβI+1 βLOOPβ
β ZβZMat M;V;N;I;R;C;J;K Vβ,M Nββ΄V Rβββ΄M Cβ(β΄M)[2] Zβ(R,C)β΄β,0 Iβ1 Jβ1 Kβ1LOOP:β(I>N)/0 Z[J;K]ββZFromInt V[I] KβK+1 β(Kβ€C)/NX Kβ1 JβJ+1NX:IβI+1 βLOOPβ
β ZβA ZMM B;RA;CA;CB;I;J;K;S;P RAβββ΄A CAβ(β΄A)[2] CBβ(β΄B)[2] Zβ(RA,CB)β΄β,0 Iβ1ILO:β(I>RA)/0 Jβ1JLO:β(J>CB)/IN Sβ,0 Kβ1KLO:β(K>CA)/ST Pβ(βA[I;K]) ZMul βB[K;J] SβS ZAdd P KβK+1 βKLOST:Z[I;J]ββS JβJ+1 βJLOIN:IβI+1 βILOβ
β ZβZSelfTest;P;D;A;B;C;RQ DββZPOW62 β(Dβ’'4611686018427387904')/BAD Pβ(ZFromInt 3) ZAdd ZFromInt 5 β((ZDec P)β’,'8')/BAD Pβ(ZFromInt Β―3) ZAdd ZFromInt 5 β((ZDec P)β’,'2')/BAD Pβ(ZFromInt 5) ZAdd ZFromInt Β―3 β((ZDec P)β’,'2')/BAD Pβ(ZFromInt Β―5) ZAdd ZFromInt 3 β((ZDec P)β’'-2')/BAD Pβ(ZFromInt Β―5) ZAdd ZFromInt Β―3 β((ZDec P)β’'-8')/BAD PβZFromInt 999999999 PβP ZMul P β((ZDec P)β’'999999998000000001')/BAD RQβZSplitBase 999999998000000001 β(RQ[1]β 1)/BAD β(RQ[2]β 999999998)/BAD Pβ(ZFromInt 10) ZMod ZFromInt 3 β((ZDec P)β’,'1')/BAD AβZMat 2 2β΄1 2 3 4 BβZMat 2 2β΄5 6 7 8 CβA ZMM B β((ZDec βC[1;1])β’'19')/BAD β((ZDec βC[1;2])β’'22')/BAD β((ZDec βC[2;1])β’'43')/BAD β((ZDec βC[2;2])β’'50')/BAD PβZPow2 64 β((ZDec P)β’'18446744073709551616')/BAD Pβ(ZPow2 64) ZSub ZPow2 32 PβP ZAdd ZFromInt 1 β((ZDec P)β’'18446744069414584321')/BAD PβZNeg ZFromInt 12 β((ZDec P)β’'-12')/BAD Zβ1 β0BAD:ββ'ZINT_SELFTEST_FAIL' ββD Zβ0β1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# Architecture
Sovereign Reduction Algebra is an array reduction algebra for an experimentalSUBLEQ attention / bi-encoder. Production numeric work runs in J 9.7 and R 4.5with gmp `bigz`. Python launches those processes and compares the integers theyprint. It does not multiply, reduce modulo the Goldilocks prime, or hash.
This is not a trained softmax transformer. Tower weights are a fixedpermutation. The late interaction is subtract β compare β predicate β select βroute β reduce. The unmasked head must equal exact matrix multiplication. Therouted tensor is a separate sparse approximation and is not required to matchthat product.
## Components
| Layer | Path | Role ||-------|------|------|| J arithmetic | `j/biencoder.ijs` | Extended-integer matmul (`+/ .*`), SUBLEQ routing, field residues || J seal | `j/sha512.ijs` | FIPS 180-4 SHA-512; 64-bit words as two uint32 halves || J benches | `j/bench.ijs` | `6!:2` timings written through the Python recorder || R arithmetic | `r/biencoder.R` | gmp `bigz` matmul; never double, never base `%*%` on numeric || R seal | `r/sha512.R` | SHA-512 with uint16 limbs (high-bit uint32 is `NA_integer_` in R) || R benches | `r/bench.R` | `system.time` timings || Launcher | `scripts/run_biencoder.py` | Starts J and R; compares printed decimals and hex seals || Bench recorder | `scripts/run_benchmarks.py` | Records timer output only; does not invent seconds || Results | `results/*.json` | Measured artifacts || TinyAPL | `tinyapl/`, `vendor/tinyapl` | Legacy demo. Complex Double cannot hold Goldilocks `p`. || Astra | `astra/*.apl` | GNU-APL style agent registry, routing, and mixture sources (included, not claimed executed here) |
``` ββββββββββββββββββββββββββββ β Python process launcher β β compare printed ints β ββββββββββββββ¬ββββββββββββββ β ββββββββββββββββββββΌβββββββββββββββββββ βΌ βΌ ββββββββββββββββββ ββββββββββββββββββ β J 9.7 β β R 4.5 + gmp β β +/ .* β β bigz %*% β β SHA-512 DAG β β SHA-512 DAG β βββββββββ¬βββββββββ βββββββββ¬βββββββββ β β ββββββββββββββββ¬βββββββββββββββββββββββ βΌ exact_head Β· predicted Β· weights Β· prime β βΌ parent SHA-512 seal```
See also `docs/images/architecture.svg`.
## Field
Goldilocks prime `p = 18446744069414584321 = 2^64 β 2^32 + 1` is held as anextended integer in both engines. Seeded small products agree with the fieldproduct when they do not wrap. A fixed large residue case is reduced in bothlanguages and must agree.
## Pipeline
```ARRAY β SUBTRACT β COMPARE β PREDICATE β SELECT β ROUTE β REDUCE β STATE```
Two towers apply one fixed permutation (`Wq +/ .* |: Wk = I` in J; the sameproduct in R). One integer training step does not move `Wq` or `Wk`. It addsthe routed residual to an integer projection, then adds that projectionelementwise to the routed prediction. The unmasked head must stillequal `A` times `B`.
## Verification rules
1. Unmasked head equals exact `A Γ B` in both engines.2. J and R agree on the seeded 4Γ4 case (shapes, tensors, seals).3. SHA-512 DAG seals agree; `verify` passes; a one-entry mutation fails verify.4. Routed max absolute error is reported and does not gate exit status.5. Benchmark seconds come only from J `6!:2` or R `system.time`.
## Legacy
TinyAPL remains for the earlier reduction-algebra demos. Its scalars areComplex Double; ulp at `2^64` is 4096, so `p` is not an exact distinct scalar.The older Python Goldilocks reference and SHA-256 JSON stub are not theproduction bi-encoder seal.123456789101112131415161718192021222324252627282930313233# Astra APL
The `astra/` directory holds GNU-APL style source for an agent registry, budgetrouting, and bounded-round mixture orchestration. These files are included asarchitecture and reference source. This release does not claim that they wereexecuted on this box unless a future run is recorded under `results/`.
## Files
| File | Purpose ||------|---------|| `astra/agents.apl` | Agent registry (`Register`, `ResetAgents`) and numerical specialists (mean, median, trimmed, midrange, Winsor, consensus) || `astra/routing.apl` | Deterministic capability and budget routing over profiles `(name, capabilities, keywords, cost, enabled)` || `astra/orchestrate.apl` | Synchronous bounded-round mixture with budget accounting; no concurrency or preemption claim |
## Calling convention
An agent receives a nested request: numeric-data, prior-proposals, round. Aproposal is a numeric vector. `Register` takes a profile and a function name,rejects duplicates and missing names, and returns a one-origin index.
Routing request shape: prompt, required capabilities, preferred capabilities,top-k, budget, excluded indices. Result: selected indices, weights, raw scores,total cost.
Mixture config: prompt, data, required, preferred, top-k, total budget, roundcount. Result: answer, history, routes, failures, spent, success flag.
## Relationship to the bi-encoder
Astra is orthogonal to the J/R SUBLEQ bi-encoder. It does not replace productionarithmetic or the SHA-512 DAG seal. It is a separate APL-shaped orchestrationsketch kept alongside the reduction algebra for future GNU APL experiments.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152# Benchmarks
Source of truth: `results/benchmarks.json` (recorded 2026-10-02 23:10:14 PT).
Every seconds value was printed by J `6!:2` (format `0j6`) or R `system.time`(elapsed). Python did not time these operations. Inputs are extended integers`A[i;j] = (iΒ·N+j) mod 5` and `B[i;j] = (NΒ·N+iΒ·N+j) mod 5`, row-major.`sha512_dag_seal` times `dag_seal_hex` of exact=product, predicted=product, the4Γ4 permutation, and Goldilocks `p`. The routed head is not in these timings.
## Unmasked integer matmul
| Engine | N | Trials (s) | Mean (s) ||--------|---|------------|----------|| J 9.7 | 128 | 0.112684, 0.092637, 0.095784 | 0.100368 || R 4.5 / gmp | 128 | 0.089, 0.089, 0.090 | 0.089333 || J 9.7 | 1024 | 59.500851, 61.984229, 59.716807 | 60.400629 || R 4.5 / gmp | 1024 | 66.719, 68.561, 64.266 | 66.515333 |
## SHA-512 DAG seal
| Engine | N | Trials (s) | Digest ||--------|---|------------|--------|| J 9.7 | 128 | 6.514977, 6.452345, 6.419265 | `ccafddfba100f51a3856500b009f0644f15d6956e7ecd9667d4e84c4a6a74f7cc60cfe83381f559ff7d28979ebcbc44758f07a7ba86e9a6b682adaee2555a6fc` || R 4.5 / gmp | 128 | 38.453, 36.978, 38.912 | same as J N=128 || J 9.7 | 1024 | 512.146054 (1 trial) | `681ec299e447f7c07defe7a09ee8641c6a66fa60d041a1a8dccc5196e7c9fb2aa4238618fc0d098cc8913cf9a878aa29f27d4102cffa2ff2cfa405a3533b89af` || R 4.5 / gmp | 1024 | not run | β |
R N=1024 seal was not started: the N=128 seal was measured in-process; the nodepreimage holds `NΒ·N` integers and the seal hashes two of them, so N=1024 is 64Γthe integers. The R SHA-512 path is an interpreter loop over 16-bit limbs.
## Seeded 4Γ4 bi-encoder (correctness, not a throughput bench)
From `results/biencoder_result.json`:
- Unmasked exact head: `18 18 12 16 / 23 22 12 19 / 19 29 18 29 / 6 15 10 15`- Routed max abs error: 15- `p = 18446744069414584321`- Shared SHA-512 DAG seal (J and R agreed): `e6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6e`
## Environment (as recorded)
- J: `j9.7.1/j64/linux/commercial/www.jsoftware.com/2026-04-06T04:00:54/clang-14-0-0/SLEEF=0`- R: `R version 4.5.0 (2025-04-11)`, gmp package `0.7.5.1`
Re-run:
```bashJCONSOLE=/path/to/jconsole python3 scripts/run_benchmarks.py```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566# SHA-512 DAG seal
Production sealing for the bi-encoder is a SHA-512 directed acyclic digestcomputed independently in J (`j/sha512.ijs`) and R (`r/sha512.R`). Python doesnot hash the bi-encoder. This is not the legacy SHA-256 canonical-JSON stub in`reference/reduction_algebra.py`, and not TinyAPL `VerifyStub`.
## Child nodes
Four nodes, in fixed order:
| Role | Contents ||------|----------|| `exact_head` | Unmasked exact product tensor || `predicted` | Routed (or, in benches, the same product) tensor || `weights` | Fixed 4Γ4 permutation || `prime` | Goldilocks `p` (rank 0, count 1) |
## Node preimage
Canonical bytes are big-endian. No JSON. No floats. Decimal integers are ASCIIwith an optional leading `-`, no `+`, and no leading zeros (`0` is `0`).
1. 8 bytes magic `SRANOD01`2. uint32 length, then ASCII role string3. uint32 rank, then that many uint32 dimensions4. uint32 count (rank 0 β count 1)5. each integer, row-major (last axis fastest): uint32 byte length, then decimal ASCII
Node digest = SHA-512(preimage).
## Parent (DAG) preimage
1. 8 bytes magic `SRADAG01`2. uint32 child count3. raw 64-byte child digests in order: exact_head, predicted, weights, prime
Seal = SHA-512(parent preimage).
``` [exact_head] [predicted] [weights] [prime] \ | | / \ | | / ββββ parent hash of child digests ββββΊ seal```
## Word representation
- **J:** each 64-bit SHA-512 word is two uint32 halves because `b.` is not exact at or above `2^63`.- **R:** each word is four uint16 limbs because a uint32 with the high bit set is R's `NA_integer_` and cannot go through `bitw*`.
## Verification
`verify` recomputes the seal and compares. A tensor with `predicted[0,0]`increased by 1 must change the seal and fail verify. NIST FIPS 180-4 empty /`abc` / long vectors are printed by both engines and checked by the launcher.
## Measured seals
| Case | Digest ||------|--------|| Seeded 4Γ4 bi-encoder (J = R) | `e6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6e` || Bench product seal N=128 (J = R) | `ccafddfba100f51a3856500b009f0644f15d6956e7ecd9667d4e84c4a6a74f7cc60cfe83381f559ff7d28979ebcbc44758f07a7ba86e9a6b682adaee2555a6fc` || Bench product seal N=1024 (J) | `681ec299e447f7c07defe7a09ee8641c6a66fa60d041a1a8dccc5196e7c9fb2aa4238618fc0d098cc8913cf9a878aa29f27d4102cffa2ff2cfa405a3533b89af` |12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091# Reduction Algebra Specification
## Object
```R = (D, OP, E, A, C, S)```
| Symbol | Meaning ||--------|---------|| **D** | Domain (booleans, reals/exact ints, Goldilocks F_p, attention tensors) || **OP** | Operator (boolean/arithmetic/structural/field/SUBLEQ/crypto stubs) || **E** | Identity elements for each OP || **A** | Algebraic laws (associativity only where established on D) || **C** | Canonicalization (mod p residues; JSON canonical form) || **S** | Sealing. Production bi-encoder: SHA-512 DAG in J and R. Legacy pipeline: SHA-256 JSON stub. |
This studies **reduction algebra** for an experimental SUBLEQ Attention Engine.It is **not** ordinary DB aggregation, WORM storage, or softmax transformer attention.
## Goldilocks
`p = 18446744069414584321 = 2^64 - 2^32 + 1`.
Authoritative ops: `reference/goldilocks.py` (Python arbitrary precision).
TinyAPL uses `Complex Double` and **cannot** represent `p` as a distinct exact scalar(ulp at 2^64 is 4096). TinyAPL-native demos use `GSafeP = 65537 (Fermat prime)` for exact localarithmetic. Full-field equality is always checked against the Python reference.
## Bi-encoder arithmetic
The SUBLEQ bi-encoder (two towers, fixed permutation, routed dot product) is**not** softmax attention and is not trained. Its products and Goldilocksresidues are extended integers in J (`j/biencoder.ijs`) and R gmp `bigz`(`r/biencoder.R`). Python is not a numeric authority for that pipeline.TinyAPL cannot represent `p` exactly and is only the earlier experiment.The unmasked head must equal `A` times `B`. The routed tensor is reportedseparately and is not required to match that product.
One integer training step (`j/train_step.ijs`, `r/train_step.R`) is not softmaxand not a loop. `Wq` and `Wk` stay the permutation. The loss is the integerresidual between the routed prediction and the exact product. That residualupdates an integer projection between the unmasked head and the routinglayer, and the post routed prediction is the pre routed prediction plusthat projection, elementwise. The unmasked head is not modified. A mismatch between the unmasked head and `A` times `B` still fails thestep. The routed residual is not required to be zero. The SHA-512 DAG layoutis unchanged.
The production seal is a SHA-512 DAG, computed in J and again in R, not inPython. Nodes are the exact head, the routed prediction, the weightpermutation, and the prime `p` (rank 0). Each node digest is SHA-512 of thecanonical byte layout in `j/sha512.ijs` and `r/sha512.R`: magic `SRANOD01`,length-prefixed role, rank, dimensions, count, then length-prefixed ASCIIdecimals in row-major order. No JSON and no floats. The parent preimage ismagic `SRADAG01`, the child count, and the raw child digests in that fixedorder. The seal is SHA-512 of the parent preimage. `verify` recomputes it.A one-entry mutation of the routed tensor must change the seal and failverify. The legacy SHA-256 canonical-JSON helpers in`reference/reduction_algebra.py` and TinyAPL `VerifyStub` are not this seal.
## SUBLEQ attention pipeline
```ARRAY β SUBTRACT (BβBβA) β COMPARE β PREDICATE β SELECT β ROUTE β REDUCE β STATE```
**Not** equivalent to softmax attention.
## Topologies R0βR7
| Id | Name | Depth ||----|------|-------|| R0 | scalar-reference | 0 || R1 | sequential | Nβ1 || R2 | balanced-tree | βlog2 Nβ || R3 | chunked | (chunkβ1)+(βN/chunkββ1) || R4 | segmented | per segment || R5 | tacit-fused | Nβ1 || R6 | goldilocks-field | Nβ1 || R7 | subleq-routed-field | Nβ1 |
## Verification
1. No performance claim without correctness pass.2. Deterministic identical inputs.3. `reference(X) = candidate(X) (mod p)` for Goldilocks.4. Never fabricate metrics; use `not_measured` when untimed.5. Bi-encoder seals agree across J and R, and verify fails if a sealed tensor is mutated.6. Benchmark seconds come from J `6!:2` or R `system.time` only.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129Sovereign Reduction Algebra β seeded 4Γ4 bi-encoder demoCaptured: 2026-10-02 (America/Los_Angeles)Command: JCONSOLE=.../jconsole python3 scripts/run_biencoder.py
=== J (j/biencoder.ijs) β selected printed tensors ===ENGINEJPREDICTED18 12 12 1611 22 12 19 7 29 18 17 2 0 8 4EXACT_HEAD18 18 12 1623 22 12 1919 29 18 29 6 15 10 15REFERENCE18 18 12 1623 22 12 1919 29 18 29 6 15 10 15MAX_ABS_ERROR15GOLDILOCKS_P18446744069414584321SEALe6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6eVERIFY1
=== R (r/biencoder.R) β selected printed tensors ===ENGINERPREDICTED18 12 12 1611 22 12 197 29 18 172 0 8 4EXACT_HEAD18 18 12 1623 22 12 1919 29 18 296 15 10 15REFERENCE18 18 12 1623 22 12 1919 29 18 296 15 10 15MAX_ABS_ERROR15GOLDILOCKS_P18446744069414584321SEALe6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6eVERIFY1
=== Launcher comparison (scripts/run_biencoder.py) ====== SUBLEQ bi-encoder (J and R) ===time: 2026-10-02 23:12:45 PT [OK] j.runs [OK] r.runs [OK] agree.SHA512_EMPTY [OK] agree.SHA512_ABC [OK] agree.SHA512_LONG [OK] agree.SEAL [OK] agree.MUTATED_SEAL [OK] agree.NEG_SEAL [OK] sha512.empty [OK] sha512.abc [OK] sha512.long [OK] seal.differs_when_tensor_mutated [OK] agree.M [OK] agree.K [OK] agree.N [OK] agree.SEED [OK] agree.RADIX [OK] agree.A [OK] agree.B [OK] agree.WQ [OK] agree.WK [OK] agree.Q [OK] agree.KTOWER [OK] agree.PREDICTED [OK] agree.EXACT_HEAD [OK] agree.REFERENCE [OK] agree.AGGREGATES [OK] agree.PREDICATES [OK] agree.GSAFE_PREDICTED [OK] agree.MAX_ABS_ERROR [OK] agree.EXACT_HEAD_MATCH [OK] agree.PERMUTATION_INVERSE [OK] agree.SHAPES_OK [OK] agree.NOT_SOFTMAX [OK] agree.GOLDILOCKS_P [OK] agree.FIELD_SMALL_PREDICTED [OK] agree.FIELD_SMALL_EXACT_HEAD [OK] agree.FIELD_SMALL_REFERENCE [OK] agree.FIELD_SMALL_AGREES [OK] agree.FIELD_LARGE_PREDICTED [OK] agree.FIELD_LARGE_EXACT_HEAD [OK] agree.FIELD_LARGE_REFERENCE [OK] agree.FIELD_LARGE_EXACT_MATCH [OK] agree.HAND_PREDICTED [OK] agree.HAND_EXACT_HEAD [OK] agree.HAND_REFERENCE [OK] agree.HAND_MAX_ABS_ERROR [OK] agree.HAND_EXACT_HEAD_MATCH [OK] agree.VERIFY [OK] agree.VERIFY_MUTATED [OK] exact_head.J_equals_reference [OK] exact_head.R_equals_reference [OK] exact_head.engines_agree [OK] shapes [OK] permutation_inverse [OK] goldilocks.small_integer_agreement [OK] goldilocks.large_exact_head [OK] goldilocks.p [OK] hand.exact_head [OK] not_softmax [OK] seal.verify [OK] seal.verify_mutated_failsrouted max_abs_error: 15 (not required to be 0)hand routed max_abs_error: 2wrote /workspace/sovereign-reduction-algebra/results/biencoder_result.jsonoverall_pass: True
J exit=0 R exit=0 launcher exit=012345678910111213141516171819202122232425262728293031{ "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "SovereignReductionAlgebraResult", "type": "object", "required": [ "schema_version", "timestamp_pt", "correctness", "engine" ], "properties": { "schema_version": { "type": "string" }, "timestamp_pt": { "type": "string" }, "engine": { "type": "object" }, "correctness": { "type": "object" }, "benchmarks": { "type": "array" }, "goldilocks": { "type": "object" } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100NB. Measured benches only. Times are 6!:2, formatted 0j6 (1e-6 s).NB. Matrices are extended integers, never float.NB. A[i,j] = (i*n+j) mod 5. B[i,j] = (n*n + i*n + j) mod 5.NB. sha512_dag_seal calls dag_seal_hex onNB. exact = product, predicted = product, weights = the 4x4 permutation,NB. prime = Goldilocks p.NB. The routed head is not part of this timing.NB. N=1024 seal is one trial. N=128 is three.
load_seal =: 3 : 0 this =. > {: 4!:3 '' dir =. (>: this i: '/') {. this load dir , 'sha512.ijs' 1)load_seal ''
fmtsec =: 3 : '0j6 ": y'clean_int =: 3 : 0 s =. , ": y s =. s -. ' ' '-' (I. s e. '_Β―') } s)
P =: 18446744069414584321xPERM4 =: x: 4 4 $ 0 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0
echo 'BENCH_V1'echo 'LANGUAGE'echo 'J'echo 'VERSION'echo 9!:14 ''echo 'TIMER'echo '6!:2'
run_mm =: 4 : 0 n =. x trials =. y A =. x: (n , n) $ 5 | i. n * n B =. x: (n , n) $ 5 | (n * n) + i. n * n C =. A +/ .* B if. (3!:0 C) e. 8 16 do. echo 'FLOAT_REFUSED' exit 1 end. echo 'RECORD' echo 'SIZE' echo clean_int n echo 'OP' echo 'unmasked_integer_matmul' echo 'TRIALS' echo clean_int trials echo 'SECONDS' for. i. trials do. echo fmtsec 6!:2 'C =. A +/ .* B' end. if. (3!:0 C) e. 8 16 do. echo 'FLOAT_REFUSED' exit 1 end. echo 'CHECKSUM' echo clean_int +/ , C echo 'RESULT_TYPE' echo clean_int 3!:0 {. , C C)
run_seal =: 4 : 0 'n C' =. x trials =. y if. (3!:0 C) e. 8 16 do. echo 'FLOAT_REFUSED' exit 1 end. echo 'RECORD' echo 'SIZE' echo clean_int n echo 'OP' echo 'sha512_dag_seal' echo 'TRIALS' echo clean_int trials echo 'SECONDS' for. i. trials do. echo fmtsec 6!:2 's =. dag_seal_hex C ; C ; PERM4 ; P' end. echo 'CHECKSUM' echo s echo 'NODE_BYTES' echo clean_int # 'exact_head' node_bytes C echo 'RESULT_TYPE' echo 'sha512' s)
C128 =: 128 run_mm 3s128 =: (128 ; C128) run_seal 3C1024 =: 1024 run_mm 3s1024 =: (1024 ; C1024) run_seal 1echo 'BENCH_DONE'exit 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264NB. SUBLEQ bi-encoder. Not softmax attention. Not a trained model.NB. Weights are a fixed permutation, not fit by a loop.NB. Every tensor entry is an extended integer. Float results abort.NB. Unmasked head is Q +/ .* |:K and must equal A +/ .* B.NB. Routed head masks dot-product factors with the SUBLEQ predicate.NB. Goldilocks p = 2^64 - 2^32 + 1, residue via extended integers.
NB. SHA-512 DAG seal (j/sha512.ijs). Self-test runs on load.this =. > {: 4!:3 ''dir =. (>: this i: '/') {. thisload dir , 'sha512.ijs'
P =: 18446744069414584321xGSAFE =: 65537xLCGA =: 48271xLCGM =: 2147483647xSEED0 =: 20261002xRADIX =: 5xHALF =: P <.@% 2x
show =: 3 : 0 raw =. ": y shp =. $ raw s =. '-' (I. , raw = '_') } , raw echo shp $ s)
shows =: 3 : 0 s =. , ": y echo '-' (I. s = '_') } s)
NB. Refuse IEEE float / complex. Machine int, boolean, extended are exact.require_exact =: 3 : 0 t =. 3!:0 y if. t e. 8 16 do. echo 'FLOAT_REFUSED' echo ": t exit 1 end. x: y)
mm =: 4 : 'require_exact x +/ .* y'fmm =: 4 : 'P | x mm y'
NB. x is count (machine int). y is extended seed. Draw radix|lcg.lcg_draw =: 4 : 0 seed =. y buf =. 0 $ 0x for. i. x do. seed =. LCGM | LCGA * seed buf =. buf , RADIX | seed end. buf ; seed)
NB. SUBLEQ: subtract, compare, predicate, select, route, reduce.NB. Returns routed_dot ; aggregate ; predicate ; selected_countsubleq =: 4 : 0 diff =. require_exact y - x pred =. require_exact diff <: 0 selected =. pred # diff routed =. pred * diff agg =. require_exact +/ routed dot =. require_exact +/ pred * x * y dot ; agg ; pred ; (# selected))
field_routed =: 4 : 0 diff =. P | require_exact y - x signed =. require_exact diff - P * x: (diff > HALF) pred =. require_exact signed <: 0 terms =. pred * P | require_exact x * y P | require_exact +/ terms)
pair_mat =: 1 : 0 rows =. 0 $ a: for_q. x do. row =. 0 $ 0x for_k. y do. row =. row , q u k end. rows =. rows , < row end. > rows)
dot_of =: 3 : '> 0 { y'agg_of =: 3 : '> 1 { y'pred_of =: 3 : '> 2 { y'
predict =: (dot_of @: subleq) pair_mataggs =: (agg_of @: subleq) pair_mat
pred_rows =: 4 : 0 rows =. 0 $ a: for_q. x do. for_k. y do. rows =. rows , < pred_of q subleq k end. end. > rows)
field_predict =: field_routed pair_mat
NB. x is A ; B, y is the shared weight matrix (extended).run =: 4 : 0 'a b' =. x w =. require_exact y q =. a mm w k =. (|: b) mm w exact =. q mm |: k ref =. a mm b pr =. q predict k ag =. q aggs k pd =. q pred_rows k err =. require_exact >./ | , pr - ref match =. *./ , exact = ref q ; k ; pr ; exact ; ref ; ag ; pd ; err ; match)
frun =: 4 : 0 'a b' =. x w =. y q =. a fmm w k =. (|: b) fmm w exact =. q fmm |: k ref =. a fmm b pr =. q field_predict k pr ; exact ; ref)
PERM =: require_exact 4 4 $ 0 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0ID4 =: require_exact =/~ i. 4perm_ok =: *./ , (PERM mm |: PERM) = ID4
'av seed2' =: 16 lcg_draw SEED0'bv seed3' =: 16 lcg_draw > seed2A =: require_exact 4 4 $ avB =: require_exact 4 4 $ bv'Q Ktow PR EX REF AG PD ERR MATCH' =: (A ; B) run PERMGS =: GSAFE | PRshapes_ok =: (4 4 -: $ A) *. (4 4 -: $ B) *. (4 4 -: $ PR) *. (4 4 -: $ EX) *. (4 4 -: $ REF)
'FSPR FSEX FSREF' =: (A ; B) frun PERMfs_agrees =: (*./ , FSPR = PR) *. (*./ , FSEX = EX) *. (*./ , FSREF = REF)
LA =: 4 4 $ (P - 2x), 4x, 1x, 7x, 3x, (P - 5x), 2x, 9x, 8x, 1x, (P - 1x), 6x, 0x, 5x, 4x, (P - 3x)LB =: 4 4 $ (P - 4x), 2x, 3x, 1x, 6x, (P - 1x), 0x, 5x, 1x, 8x, (P - 6x), 2x, 7x, 3x, 4x, (P - 2x)'FLPR FLEX FLREF' =: (LA ; LB) frun PERMfl_match =: *./ , FLEX = FLREF
HA =: require_exact 2 3 $ 1 2 3 4 0 1HB =: require_exact 3 2 $ 1 2 0 1 2 1HW =: require_exact =/~ i. 3'HQ HK HPR HEX HREF HAG HPD HERR HMATCH' =: (HA ; HB) run HW
'SHA_EMPTY SHA_ABC SHA_LONG' =. sha512_vectors ''SEAL =. dag_seal_hex EX ; PR ; PERM ; PPRm =. ((1x + (< 0 0) { PR) (< 0 0) } PR)MSEAL =. dag_seal_hex EX ; PRm ; PERM ; PVOK =. SEAL verify_dag EX ; PR ; PERM ; PVBAD =. SEAL verify_dag EX ; PRm ; PERM ; PNEG =. 1 3 $ _12x , 0x , 7xNW =. 1 1 $ 1xNSEAL =. dag_seal_hex NEG ; NEG ; NW ; P
echo 'BIENCODER_V1'echo 'ENGINE'echo 'J'echo 'J_VERSION'echo 9!:14''echo 'M'shows 4echo 'K'shows 4echo 'N'shows 4echo 'SEED'shows SEED0echo 'RADIX'shows RADIXecho 'A'show Aecho 'B'show Becho 'WQ'show PERMecho 'WK'show PERMecho 'Q'show Qecho 'KTOWER'show Ktowecho 'PREDICTED'show PRecho 'EXACT_HEAD'show EXecho 'REFERENCE'show REFecho 'AGGREGATES'show AGecho 'PREDICATES'show PDecho 'GSAFE_PREDICTED'show GSecho 'MAX_ABS_ERROR'shows ERRecho 'EXACT_HEAD_MATCH'shows MATCHecho 'PERMUTATION_INVERSE'shows perm_okecho 'SHAPES_OK'shows shapes_okecho 'NOT_SOFTMAX'shows 1echo 'GOLDILOCKS_P'shows Pecho 'FIELD_SMALL_PREDICTED'show FSPRecho 'FIELD_SMALL_EXACT_HEAD'show FSEXecho 'FIELD_SMALL_REFERENCE'show FSREFecho 'FIELD_SMALL_AGREES'shows fs_agreesecho 'FIELD_LARGE_PREDICTED'show FLPRecho 'FIELD_LARGE_EXACT_HEAD'show FLEXecho 'FIELD_LARGE_REFERENCE'show FLREFecho 'FIELD_LARGE_EXACT_MATCH'shows fl_matchecho 'HAND_PREDICTED'show HPRecho 'HAND_EXACT_HEAD'show HEXecho 'HAND_REFERENCE'show HREFecho 'HAND_MAX_ABS_ERROR'shows HERRecho 'HAND_EXACT_HEAD_MATCH'shows HMATCHecho 'SHA512_EMPTY'echo SHA_EMPTYecho 'SHA512_ABC'echo SHA_ABCecho 'SHA512_LONG'echo SHA_LONGecho 'SEAL'echo SEALecho 'VERIFY'shows VOKecho 'MUTATED_SEAL'echo MSEALecho 'VERIFY_MUTATED'shows VBADecho 'NEG_SEAL'echo NSEALexit 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271NB. SHA-512 (FIPS 180-4) and the bi-encoder DAG seal.NB. A word is two uint32 halves (hi, lo), each kept in 0..4294967295 soNB. J b. never sees a value >= 2^63 (those are not exact machine integers).NB.NB. Canonical node preimage, big-endian, no JSON, no floats:NB. 8 bytes ASCII "SRANOD01"NB. uint32be role_len, then that many ASCII bytes of the roleNB. uint32be rank, then rank uint32be dimensionsNB. uint32be count (product of the dimensions; rank 0 has count 1)NB. count integers in row-major order (last axis fastest). Each isNB. uint32be nbytes, then nbytes of ASCII decimal:NB. optional leading "-", no "+", no leading zeros, zero is "0"NB. Node digest = SHA-512 of that preimage (64 bytes).NB.NB. DAG preimage:NB. 8 bytes ASCII "SRADAG01"NB. uint32be child countNB. that many raw 64-byte digests, fixed order:NB. exact_head, predicted, weights, primeNB. The seal is the lowercase hex SHA-512 of the DAG preimage.NB. verify recomputes the seal from the tensors and compares.
M32 =: 4294967295NIST_EMPTY =: 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e'NIST_ABC =: 'ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f'NIST_LONG =: '8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909'NIST_LONG_MSG =: 'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu'
be32 =: 3 : '(4 # 256) #: y'
hexw =: 3 : 0 d =. '0123456789abcdef' i. y if. 16 e. d do. echo 'BADHEX' exit 1 end. (16 #. 8 {. d) , (16 #. 8 }. d))
H512 =: hexw "1 (8 16 $ '6a09e667f3bcc908bb67ae8584caa73b3c6ef372fe94f82ba54ff53a5f1d36f1510e527fade682d19b05688c2b3e6c1f1f83d9abfb41bd6b5be0cd19137e2179')K512 =: hexw "1 (80 16 $ '428a2f98d728ae227137449123ef65cdb5c0fbcfec4d3b2fe9b5dba58189dbbc3956c25bf348b53859f111f1b605d019923f82a4af194f9bab1c5ed5da6d8118d807aa98a303024212835b0145706fbe243185be4ee4b28c550c7dc3d5ffb4e272be5d74f27b896f80deb1fe3b1696b19bdc06a725c71235c19bf174cf692694e49b69c19ef14ad2efbe4786384f25e30fc19dc68b8cd5b5240ca1cc77ac9c652de92c6f592b02754a7484aa6ea6e4835cb0a9dcbd41fbd476f988da831153b5983e5152ee66dfaba831c66d2db43210b00327c898fb213fbf597fc7beef0ee4c6e00bf33da88fc2d5a79147930aa72506ca6351e003826f142929670a0e6e7027b70a8546d22ffc2e1b21385c26c9264d2c6dfc5ac42aed53380d139d95b3df650a73548baf63de766a0abb3c77b2a881c2c92e47edaee692722c851482353ba2bfe8a14cf10364a81a664bbc423001c24b8b70d0f89791c76c51a30654be30d192e819d6ef5218d69906245565a910f40e35855771202a106aa07032bbd1b819a4c116b8d2d0c81e376c085141ab532748774cdf8eeb9934b0bcb5e19b48a8391c0cb3c5c95a634ed8aa4ae3418acb5b9cca4f7763e373682e6ff3d6b2b8a3748f82ee5defb2fc78a5636f43172f6084c87814a1f0ab728cc702081a6439ec90befffa23631e28a4506cebde82bde9bef9a3f7b2c67915c67178f2e372532bca273eceea26619cd186b8c721c0c207eada7dd6cde0eb1ef57d4f7fee6ed17806f067aa72176fba0a637dc5a2c898a6113f9804bef90dae1b710b35131c471b28db77f523047d8432caab7b40c724933c9ebe0a15c9bebc431d67c49c100d4c4cc5d4becb3e42b6597f299cfc657e2a5fcb6fab3ad6faec6c44198c4a475817')
andw =: 4 : 0 'ah al' =. x 'bh bl' =. y (ah (17 b.) bh) , (al (17 b.) bl))
orw =: 4 : 0 'ah al' =. x 'bh bl' =. y (ah (23 b.) bh) , (al (23 b.) bl))
xorw =: 4 : 0 'ah al' =. x 'bh bl' =. y (ah (22 b.) bh) , (al (22 b.) bl))
notw =: 3 : '(M32 , M32) xorw y'
addw =: 4 : 0 'ah al' =. x 'bh bl' =. y s =. al + bl lo =. M32 (17 b.) s carry =. _32 (33 b.) s t =. ah + bh + carry hi =. M32 (17 b.) t hi , lo)
shrw =: 4 : 0 n =. x 'hi lo' =. y if. n = 0 do. (M32 (17 b.) hi) , (M32 (17 b.) lo) return. end. if. n >: 64 do. 0 0 return. end. if. n >: 32 do. s =. n - 32 if. s = 0 do. 0 , (M32 (17 b.) hi) return. end. 0 , (M32 (17 b.) ((- s) (33 b.) hi)) return. end. newhi =. M32 (17 b.) ((- n) (33 b.) hi) los =. M32 (17 b.) ((- n) (33 b.) lo) lowmask =. <: 2 ^ n cross =. M32 (17 b.) ((32 - n) (33 b.) (lowmask (17 b.) hi)) newlo =. M32 (17 b.) los + cross newhi , newlo)
shlw =: 4 : 0 n =. x 'hi lo' =. y if. n = 0 do. (M32 (17 b.) hi) , (M32 (17 b.) lo) return. end. if. n >: 64 do. 0 0 return. end. if. n >: 32 do. s =. n - 32 if. s = 0 do. (M32 (17 b.) lo) , 0 return. end. (M32 (17 b.) (s (33 b.) lo)) , 0 return. end. newlo =. M32 (17 b.) (n (33 b.) lo) cross =. M32 (17 b.) ((- (32 - n)) (33 b.) lo) newhi =. M32 (17 b.) ((n (33 b.) hi) + cross) newhi , newlo)
rotrw =: 4 : 0 n =. 64 | x if. n = 0 do. y return. end. (n shrw y) orw ((64 - n) shlw y))
pack8 =: 3 : 0 (256 #. 4 {. y) , (256 #. 4 }. y))
be8 =: 3 : 0 'hi lo' =. y (be32 hi) , (be32 lo))
hex_bytes =: 3 : 0 nib =. (16 16 & #:)"0 y , '0123456789abcdef' {~ nib)
sha512 =: 3 : 0 msg =. , y nb =. # msg bitlen =. 8 * nb msg =. msg , 128 while. 112 ~: 128 | # msg do. msg =. msg , 0 end. lo =. M32 (17 b.) bitlen hi =. M32 (17 b.) (_32 (33 b.) bitlen) msg =. msg , (8 $ 0) , be8 (hi , lo) if. 0 ~: 128 | # msg do. echo 'PAD_FAIL' exit 1 end. state =. H512 nblk =. <. (# msg) % 128 for_bi. i. nblk do. off =. 128 * bi blk =. (off + i. 128) { msg ws =. 80 2 $ 0 for_j. i. 16 do. ws =. (pack8 ((8 * j) + i. 8) { blk) j } ws end. for_j. 16 + i. 64 do. w15 =. (j - 15) { ws w2 =. (j - 2) { ws w16 =. (j - 16) { ws w7 =. (j - 7) { ws s0 =. ((1 rotrw w15) xorw (8 rotrw w15)) xorw (7 shrw w15) s1 =. ((19 rotrw w2) xorw (61 rotrw w2)) xorw (6 shrw w2) nw =. ((w16 addw s0) addw w7) addw s1 ws =. nw j } ws end. a =. 0 { state b =. 1 { state c =. 2 { state d =. 3 { state e =. 4 { state f =. 5 { state g =. 6 { state h =. 7 { state for_i. i. 80 do. s1 =. ((14 rotrw e) xorw (18 rotrw e)) xorw (41 rotrw e) chv =. (e andw f) xorw ((notw e) andw g) t1 =. (((h addw s1) addw chv) addw (i { K512)) addw (i { ws) s0 =. ((28 rotrw a) xorw (34 rotrw a)) xorw (39 rotrw a) maj =. ((a andw b) xorw (a andw c)) xorw (b andw c) t2 =. s0 addw maj h =. g g =. f f =. e e =. d addw t1 d =. c c =. b b =. a a =. t1 addw t2 end. acc =. 8 2 $ a , b , c , d , e , f , g , h state =. state addw"1 acc end. out =. 0 $ 0 for_r. state do. out =. out , be8 r end. out)
dec_bytes =: 3 : 0 s =. ": x: y s =. s -. ' ' s =. '-' (I. s e. '_Β―') } s a. i. s)
enc_int =: 3 : 0 db =. dec_bytes y (be32 # db) , db)
NB. x is the role string. y is an exact integer tensor (scalar allowed).node_bytes =: 4 : 0 role =. x tensor =. y t =. 3!:0 tensor if. t e. 8 16 do. echo 'FLOAT_REFUSED' exit 1 end. tensor =. x: tensor shp =. $ tensor rank =. # shp vals =. , tensor cnt =. # vals rb =. a. i. role b =. (a. i. 'SRANOD01') , (be32 # rb) , rb , (be32 rank) if. rank > 0 do. b =. b , , be32 "0 shp end. b =. b , be32 cnt b , ; enc_int each vals)
NB. y is a boxed list of 64-byte integer vectors, parent order.dag_preimage =: 3 : 0 kids =. y ((a. i. 'SRADAG01') , be32 # kids) , ; kids)
NB. y is exact ; predicted ; weights ; primedag_seal_hex =: 3 : 0 'ex pr wt prme' =. y d1 =. sha512 ('exact_head' node_bytes ex) d2 =. sha512 ('predicted' node_bytes pr) d3 =. sha512 ('weights' node_bytes wt) d4 =. sha512 ('prime' node_bytes prme) hex_bytes sha512 dag_preimage (d1 ; d2 ; d3 ; d4))
NB. x is claimed lowercase hex. y is the four tensors. 1 iff equal.verify_dag =: 4 : 0 x -: dag_seal_hex y)
sha512_vectors =: 3 : 0 e =. hex_bytes sha512 (0 $ 0) a =. hex_bytes sha512 a. i. 'abc' g =. hex_bytes sha512 a. i. NIST_LONG_MSG e ; a ; g)
sha512_selftest =: 3 : 0 'e a g' =. sha512_vectors '' if. -. (e -: NIST_EMPTY) *. (a -: NIST_ABC) *. (g -: NIST_LONG) do. echo 'SHA512_SELFTEST_FAIL' echo e echo a echo g exit 1 end. 1)
sha512_selftest ''123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210NB. One integer training step. Not softmax. Not a training framework.NB. Forward nodes, in order: subtract, compare, predicate, select, route, reduce.NB. Wq and Wk stay the fixed permutation. The unmasked head stays A times B.NB. The routed residual (exact product minus routed prediction) is added onceNB. to an integer projection, then that projection is added elementwise toNB. the routed prediction. The unmasked head is not changed.NB. No weight update, no floor, no modulus. Extended integers only.NB. AGPL-3.0 only. Do not use MIT.
this =. > {: 4!:3 ''dir =. (>: this i: '/') {. thisload dir , 'sha512.ijs'
P =: 18446744069414584321xLCGA =: 48271xLCGM =: 2147483647xSEED0 =: 20261002xRADIX =: 5xKNOWN =: 4 4 $ 18x 18x 12x 16x 23x 22x 12x 19x 19x 29x 18x 29x 6x 15x 10x 15xPRE_SEAL_WANT =: 'e6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6e'
show =: 3 : 0 raw =. ": y shp =. $ raw s =. '-' (I. , raw = '_') } , raw echo shp $ s)
shows =: 3 : 0 s =. , ": y echo '-' (I. s = '_') } s)
require_exact =: 3 : 0 t =. 3!:0 y if. t e. 8 16 do. echo 'FLOAT_REFUSED' exit 1 end. x: y)
mm =: 4 : 'require_exact x +/ .* y'
lcg_draw =: 4 : 0 seed =. y buf =. 0 $ 0x for. i. x do. seed =. LCGM | LCGA * seed buf =. buf , RADIX | seed end. buf ; seed)
NB. Forward DAG. x is q, y is k unless noted.fwd_subtract =: 4 : 'require_exact y - x'fwd_compare =: 3 : 'require_exact y <: 0'fwd_predicate =: 3 : 'require_exact y'fwd_select =: 3 : ', I. y > 0'fwd_route =: 4 : 0 'q k' =. x idx =. y prod =. require_exact q * k terms =. (# prod) $ 0x if. 0 < # idx do. terms =. (idx { prod) idx } terms end. require_exact terms)fwd_reduce =: 3 : 'require_exact +/ y'
NB. Wq and Wk stay the permutation. The routed residual updates only theNB. integer projection between the unmasked head and the routed prediction.NB. Projection before the step is 0. One step adds (exact product - routed),NB. elementwise, extended integers, no floor and no modulus.NB. Extended integers only. AGPL-3.0 only. Do not use MIT.
predict_nodes =: 4 : 0 Q =. x K =. y PR =. ((# Q), (# K)) $ 0x for_qi. i. # Q do. for_kj. i. # K do. q =. qi { Q k =. kj { K diff =. q fwd_subtract k cmp =. fwd_compare diff pred =. fwd_predicate cmp idx =. fwd_select pred routed =. (q ; k) fwd_route idx yv =. fwd_reduce routed PR =. yv (<qi, kj) } PR end. end. require_exact PR)
NB. x is a message. y is a boolean. Control words stay inside an explicit verb.assert =: 4 : 0 if. -. y do. echo 'TRAIN_STEP_FAIL' echo x exit 1 end. 1)
PERM =: require_exact 4 4 $ 0 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0'av seed2' =: 16 lcg_draw SEED0'bv seed3' =: 16 lcg_draw > seed2A =: require_exact 4 4 $ avB =: require_exact 4 4 $ bvWQ =: PERMWK =: PERMQ =: A mm WQK =: (|: B) mm WKEX =: Q mm |: KREF =: A mm BPR =: Q predict_nodes KRES =: require_exact EX - PRLOSS =: require_exact +/ | , RESERR =: require_exact >./ | , PR - REFPROJ0 =: require_exact ($ EX) $ 0xPROJ =: require_exact PROJ0 + RES'pre exact head mismatch' assert *./ , EX = REF'pre exact head is not the known product' assert EX -: KNOWN'pre max abs error is not 15' assert ERR -: 15x'Wq moved' assert WQ -: PERM'Wk moved' assert WK -: PERMPRE_SEAL =: dag_seal_hex EX ; PR ; PERM ; P'pre seal mismatch' assert PRE_SEAL -: PRE_SEAL_WANT
NB. Unmasked head stays the frozen-weight product. It is not multipliedNB. by the projection. The post routed prediction is the pre routedNB. prediction plus the projection, elementwise.Q2 =: A mm WQK2 =: (|: B) mm WKEX2 =: Q2 mm |: K2PR2 =: require_exact PR + PROJREF2 =: A mm BERR2 =: require_exact >./ | , PR2 - REF2PRE_MATCH =: require_exact *./ , EX = REFPOST_MATCH =: require_exact *./ , EX2 = REF2'post exact head mismatch' assert POST_MATCH -: 1x'post Wq moved' assert WQ -: PERM'post Wk moved' assert WK -: PERMNB. Seal post-step tensors: exact head, routed prediction, then Wq, Wk, projection.WT =: WQ , WK , PROJSEAL =: dag_seal_hex EX2 ; PR2 ; WT ; PVOK =: require_exact SEAL verify_dag EX2 ; PR2 ; WT ; P'post seal verify' assert VOK -: 1x
echo 'TRAIN_STEP_V1'echo 'ENGINE'echo 'J'echo 'M'shows 4echo 'K'shows 4echo 'N'shows 4echo 'D'shows 4echo 'SEED'shows SEED0echo 'A'show Aecho 'B'show Becho 'WQ'show WQecho 'WK'show WKecho 'PROJ_BEFORE'show PROJ0echo 'PROJ_AFTER'show PROJecho 'PRE_EXACT_HEAD'show EXecho 'PRE_PREDICTED'show PRecho 'PRE_REFERENCE'show REFecho 'RESIDUAL'show RESecho 'LOSS'shows LOSSecho 'POST_EXACT_HEAD'show EX2echo 'POST_PREDICTED'show PR2echo 'POST_REFERENCE'show REF2echo 'PRE_MAX_ABS_ERROR'shows ERRecho 'POST_MAX_ABS_ERROR'shows ERR2echo 'PRE_EXACT_HEAD_MATCH'shows PRE_MATCHecho 'POST_EXACT_HEAD_MATCH'shows POST_MATCHecho 'NOT_SOFTMAX'shows 1echo 'PRE_SEAL'echo PRE_SEALecho 'SEAL'echo SEALecho 'VERIFY'shows VOKexit 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116# Measured benches only. Latency is system.time elapsed, printed to 1e-6 s.# user.self and sys.self are printed too. No imputed times.# Matrices are gmp bigz, never double.# A[i,j] = (i*n+j) mod 5. B[i,j] = (n*n + i*n + j) mod 5. Row-major.# sha512_dag_seal calls dag_seal_hex on# exact = product, predicted = product, weights = the 4x4 permutation,# prime = Goldilocks p.# The routed head is not part of this timing.# N=1024 sha512_dag_seal is not started: the preimage grows with N^2 and# the N=128 seal is already the measured cost of this interpreter.
userlib <- path.expand("~/R/library")if (dir.exists(userlib)) .libPaths(c(userlib, .libPaths()))suppressPackageStartupMessages(library(gmp))
cmd_args <- commandArgs(trailingOnly = FALSE)file_arg <- grep("^--file=", cmd_args, value = TRUE)this_file <- sub("^--file=", "", file_arg[[1]])source(file.path(dirname(normalizePath(this_file)), "sha512.R"))
fmt_sec <- function(x) formatC(x, format = "f", digits = 6)
P <- as.bigz("18446744069414584321")PERM4 <- as.bigz(matrix(c( "0", "1", "0", "0", "0", "0", "1", "0", "0", "0", "0", "1", "1", "0", "0", "0"), nrow = 4L, byrow = TRUE))
cat("BENCH_V1\nLANGUAGE\nR\n")cat("VERSION\n")cat(R.version.string, "\n", sep = "")cat("GMP_VERSION\n")cat(as.character(packageVersion("gmp")), "\n", sep = "")cat("TIMER\nsystem.time\n")
fill_mat <- function(n, offset) { idx <- 0:(n * n - 1L) chars <- as.character((offset + idx) %% 5L) M <- as.bigz(matrix(chars, nrow = n, byrow = TRUE)) if (!inherits(M, "bigz")) stop("NOT_BIGZ", call. = FALSE) M}
run_mm <- function(n, trials) { A <- fill_mat(n, 0) B <- fill_mat(n, n * n) C <- A %*% B if (!inherits(C, "bigz")) stop("NOT_BIGZ", call. = FALSE) elapsed <- character(trials) user <- character(trials) sys <- character(trials) for (i in seq_len(trials)) { tm <- system.time(C <- A %*% B) elapsed[i] <- fmt_sec(tm[["elapsed"]]) user[i] <- fmt_sec(tm[["user.self"]]) sys[i] <- fmt_sec(tm[["sys.self"]]) } if (!inherits(C, "bigz")) stop("NOT_BIGZ", call. = FALSE) cat("RECORD\nSIZE\n", n, "\nOP\nunmasked_integer_matmul\nTRIALS\n", trials, "\n", sep = "") cat("SECONDS\n") cat(elapsed, sep = "\n") cat("\n") cat("USER_SECONDS\n") cat(user, sep = "\n") cat("\n") cat("SYS_SECONDS\n") cat(sys, sep = "\n") cat("\n") cat("CHECKSUM\n") cat(as.character(sum(C)), "\n", sep = "") cat("RESULT_TYPE\nbigz\n") C}
run_seal <- function(n, C, trials) { if (!inherits(C, "bigz")) stop("NOT_BIGZ", call. = FALSE) elapsed <- character(trials) user <- character(trials) sys <- character(trials) s <- "" for (i in seq_len(trials)) { tm <- system.time(s <- dag_seal_hex(C, C, PERM4, P)) elapsed[i] <- fmt_sec(tm[["elapsed"]]) user[i] <- fmt_sec(tm[["user.self"]]) sys[i] <- fmt_sec(tm[["sys.self"]]) } nbytes <- length(node_raw("exact_head", C)) cat("RECORD\nSIZE\n", n, "\nOP\nsha512_dag_seal\nTRIALS\n", trials, "\n", sep = "") cat("SECONDS\n") cat(elapsed, sep = "\n") cat("\n") cat("USER_SECONDS\n") cat(user, sep = "\n") cat("\n") cat("SYS_SECONDS\n") cat(sys, sep = "\n") cat("\n") cat("CHECKSUM\n") cat(s, "\n", sep = "") cat("NODE_BYTES\n", nbytes, "\n", sep = "") cat("RESULT_TYPE\nsha512\n") s}
C128 <- run_mm(128L, 3L)run_seal(128L, C128, 3L)C1024 <- run_mm(1024L, 3L)cat("SKIP_LINE\n")cat("1024 sha512_dag_seal not started: N=128 sha512_dag_seal was measured in this process; ", "the node preimage holds N*N integers and the seal hashes two of them, ", "so N=1024 is 64 times the integers. This R SHA-512 is an interpreter ", "loop over 16-bit limbs and was not run at N=1024.\n", sep = "")cat("BENCH_DONE\n")quit(status = 0L)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287# SUBLEQ bi-encoder. Not softmax attention. Not a trained model.# Weights are a fixed permutation, not fit by a loop.# Every tensor entry is a gmp bigz extended integer. Doubles abort.# Unmasked head is Q %*% t(K) and must equal A %*% B.# Routed head masks dot-product factors with the SUBLEQ predicate.# Goldilocks p = 2^64 - 2^32 + 1.
userlib <- path.expand("~/R/library")if (dir.exists(userlib)) .libPaths(c(userlib, .libPaths()))suppressPackageStartupMessages(library(gmp))
cmd_args <- commandArgs(trailingOnly = FALSE)file_arg <- grep("^--file=", cmd_args, value = TRUE)this_file <- sub("^--file=", "", file_arg[[1]])source(file.path(dirname(normalizePath(this_file)), "sha512.R"))
P <- as.bigz("18446744069414584321")GSAFE <- as.bigz("65537")LCGA <- as.bigz("48271")LCGM <- as.bigz("2147483647")SEED0 <- as.bigz("20261002")RADIX <- as.bigz("5")HALF <- P %/% as.bigz("2")
refuse_double <- function(M, where) { if (is.double(M) || inherits(M, "numeric")) { # bigz is not numeric; a plain numeric matrix is float or integer. if (!inherits(M, "bigz")) { stop(paste("FLOAT_REFUSED", where), call. = FALSE) } } if (!inherits(M, "bigz")) { stop(paste("NOT_BIGZ", where), call. = FALSE) } M}
as_mat <- function(chars, nr, nc) { # Character digits only, then bigz. Never pass a double vector in. if (any(grepl("[^0-9-]", chars))) stop("non-digit matrix entry", call. = FALSE) refuse_double(as.bigz(base::matrix(chars, nrow = nr, ncol = nc, byrow = TRUE)), "as_mat")}
zeros <- function(nr, nc) { as_mat(rep("0", nr * nc), nr, nc)}
transpose_z <- function(M) { refuse_double(M, "transpose_in") nr <- nrow(M) nc <- ncol(M) out <- zeros(nc, nr) for (i in seq_len(nr)) { for (j in seq_len(nc)) out[j, i] <- M[i, j] } refuse_double(out, "transpose_out")}
mm <- function(A, B) { refuse_double(A, "mm.A") refuse_double(B, "mm.B") C <- A %*% B refuse_double(C, "mm.C")}
fmm <- function(A, B) { mod.bigz(mm(A, B), P)}
lcg_step <- function(seed) { mod.bigz(LCGA * seed, LCGM)}
lcg_draw <- function(n, seed) { buf <- character(n) for (i in seq_len(n)) { seed <- lcg_step(seed) buf[i] <- as.character(mod.bigz(seed, RADIX)) } list(vals = as.bigz(buf), seed = seed)}
# SUBLEQ: subtract, compare, predicate, select, route, reduce.subleq <- function(q, k) { diff <- refuse_double(k - q, "diff") pred <- as.bigz(diff <= as.bigz("0")) selected <- diff[as.logical(pred)] routed <- pred * diff agg <- sum(routed) dot <- sum(pred * q * k) list( dot = refuse_double(dot, "dot"), agg = refuse_double(agg, "agg"), pred = pred, nsel = length(selected) )}
field_routed <- function(q, k) { diff <- mod.bigz(k - q, P) signed <- diff - P * as.bigz(diff > HALF) pred <- as.bigz(signed <= as.bigz("0")) terms <- pred * mod.bigz(q * k, P) mod.bigz(sum(terms), P)}
pair_apply <- function(Q, K, fn) { nr <- nrow(Q) nc <- nrow(K) out <- zeros(nr, nc) for (i in seq_len(nr)) { for (j in seq_len(nc)) { out[i, j] <- fn(Q[i, ], K[j, ]) } } refuse_double(out, "pair")}
pred_rows <- function(Q, K) { rows <- list() for (i in seq_len(nrow(Q))) { for (j in seq_len(nrow(K))) { rows[[length(rows) + 1L]] <- subleq(Q[i, ], K[j, ])$pred } } rows}
run_case <- function(A, B, W) { Q <- mm(A, W) K <- mm(transpose_z(B), W) exact <- mm(Q, transpose_z(K)) ref <- mm(A, B) pr <- pair_apply(Q, K, function(q, k) subleq(q, k)$dot) ag <- pair_apply(Q, K, function(q, k) subleq(q, k)$agg) pd <- pred_rows(Q, K) err <- as.bigz("0") for (i in seq_len(nrow(pr))) { for (j in seq_len(ncol(pr))) { d <- pr[i, j] - ref[i, j] if (d < as.bigz("0")) d <- -d if (d > err) err <- d } } list( Q = Q, K = K, predicted = pr, exact = exact, reference = ref, aggregates = ag, predicates = pd, err = err, match = all(exact == ref) )}
frun <- function(A, B, W) { Q <- fmm(A, W) K <- fmm(transpose_z(B), W) exact <- fmm(Q, transpose_z(K)) ref <- fmm(A, B) pr <- pair_apply(Q, K, field_routed) list(predicted = pr, exact = exact, reference = ref)}
cat_line <- function(x) cat(as.character(x), "\n", sep = "")
cat_mat <- function(M) { refuse_double(M, "print") for (i in seq_len(nrow(M))) { cat(paste(as.character(M[i, ]), collapse = " "), "\n", sep = "") }}
cat_pred <- function(rows) { for (r in rows) cat(paste(as.character(r), collapse = " "), "\n", sep = "")}
flag <- function(x) if (isTRUE(x)) "1" else "0"
perm_chars <- c( "0", "1", "0", "0", "0", "0", "1", "0", "0", "0", "0", "1", "1", "0", "0", "0")PERM <- as_mat(perm_chars, 4L, 4L)ID4 <- zeros(4L, 4L)for (i in seq_len(4L)) ID4[i, i] <- as.bigz("1")perm_ok <- all(mm(PERM, transpose_z(PERM)) == ID4)
drawn_a <- lcg_draw(16L, SEED0)drawn_b <- lcg_draw(16L, drawn_a$seed)A <- as_mat(as.character(drawn_a$vals), 4L, 4L)B <- as_mat(as.character(drawn_b$vals), 4L, 4L)seeded <- run_case(A, B, PERM)GS <- mod.bigz(seeded$predicted, GSAFE)shapes_ok <- all(dim(A) == c(4L, 4L), dim(B) == c(4L, 4L), dim(seeded$predicted) == c(4L, 4L), dim(seeded$exact) == c(4L, 4L), dim(seeded$reference) == c(4L, 4L))
fs <- frun(A, B, PERM)fs_agrees <- all(fs$predicted == seeded$predicted, fs$exact == seeded$exact, fs$reference == seeded$reference)
LA <- as_mat(c( as.character(P - as.bigz("2")), "4", "1", "7", "3", as.character(P - as.bigz("5")), "2", "9", "8", "1", as.character(P - as.bigz("1")), "6", "0", "5", "4", as.character(P - as.bigz("3"))), 4L, 4L)LB <- as_mat(c( as.character(P - as.bigz("4")), "2", "3", "1", "6", as.character(P - as.bigz("1")), "0", "5", "1", "8", as.character(P - as.bigz("6")), "2", "7", "3", "4", as.character(P - as.bigz("2"))), 4L, 4L)fl <- frun(LA, LB, PERM)fl_match <- all(fl$exact == fl$reference)
HA <- as_mat(c("1", "2", "3", "4", "0", "1"), 2L, 3L)HB <- as_mat(c("1", "2", "0", "1", "2", "1"), 3L, 2L)HW <- zeros(3L, 3L)for (i in seq_len(3L)) HW[i, i] <- as.bigz("1")hand <- run_case(HA, HB, HW)
sha_empty <- sha512_hex(raw())sha_abc <- sha512_hex(charToRaw("abc"))sha_long <- sha512_hex(charToRaw(NIST_LONG_MSG))seal <- dag_seal_hex(seeded$exact, seeded$predicted, PERM, P)PRm <- seeded$predictedPRm[1, 1] <- PRm[1, 1] + as.bigz("1")mseal <- dag_seal_hex(seeded$exact, PRm, PERM, P)vok <- verify_dag(seal, seeded$exact, seeded$predicted, PERM, P)vbad <- verify_dag(seal, seeded$exact, PRm, PERM, P)NEG <- as.bigz(matrix(c("-12", "0", "7"), nrow = 1L, byrow = TRUE))NW <- as.bigz(matrix("1", nrow = 1L, ncol = 1L))nseal <- dag_seal_hex(NEG, NEG, NW, P)
cat("BIENCODER_V1\n")cat("ENGINE\nR\n")cat("R_VERSION\n")cat(R.version.string, "\n", sep = "")cat("GMP_VERSION\n")cat(as.character(packageVersion("gmp")), "\n", sep = "")cat("M\n4\nK\n4\nN\n4\n")cat("SEED\n")cat_line(SEED0)cat("RADIX\n")cat_line(RADIX)cat("A\n"); cat_mat(A)cat("B\n"); cat_mat(B)cat("WQ\n"); cat_mat(PERM)cat("WK\n"); cat_mat(PERM)cat("Q\n"); cat_mat(seeded$Q)cat("KTOWER\n"); cat_mat(seeded$K)cat("PREDICTED\n"); cat_mat(seeded$predicted)cat("EXACT_HEAD\n"); cat_mat(seeded$exact)cat("REFERENCE\n"); cat_mat(seeded$reference)cat("AGGREGATES\n"); cat_mat(seeded$aggregates)cat("PREDICATES\n"); cat_pred(seeded$predicates)cat("GSAFE_PREDICTED\n"); cat_mat(GS)cat("MAX_ABS_ERROR\n"); cat_line(seeded$err)cat("EXACT_HEAD_MATCH\n"); cat(flag(seeded$match), "\n", sep = "")cat("PERMUTATION_INVERSE\n"); cat(flag(perm_ok), "\n", sep = "")cat("SHAPES_OK\n"); cat(flag(shapes_ok), "\n", sep = "")cat("NOT_SOFTMAX\n1\n")cat("GOLDILOCKS_P\n"); cat_line(P)cat("FIELD_SMALL_PREDICTED\n"); cat_mat(fs$predicted)cat("FIELD_SMALL_EXACT_HEAD\n"); cat_mat(fs$exact)cat("FIELD_SMALL_REFERENCE\n"); cat_mat(fs$reference)cat("FIELD_SMALL_AGREES\n"); cat(flag(fs_agrees), "\n", sep = "")cat("FIELD_LARGE_PREDICTED\n"); cat_mat(fl$predicted)cat("FIELD_LARGE_EXACT_HEAD\n"); cat_mat(fl$exact)cat("FIELD_LARGE_REFERENCE\n"); cat_mat(fl$reference)cat("FIELD_LARGE_EXACT_MATCH\n"); cat(flag(fl_match), "\n", sep = "")cat("HAND_PREDICTED\n"); cat_mat(hand$predicted)cat("HAND_EXACT_HEAD\n"); cat_mat(hand$exact)cat("HAND_REFERENCE\n"); cat_mat(hand$reference)cat("HAND_MAX_ABS_ERROR\n"); cat_line(hand$err)cat("HAND_EXACT_HEAD_MATCH\n"); cat(flag(hand$match), "\n", sep = "")cat("SHA512_EMPTY\n"); cat(sha_empty, "\n", sep = "")cat("SHA512_ABC\n"); cat(sha_abc, "\n", sep = "")cat("SHA512_LONG\n"); cat(sha_long, "\n", sep = "")cat("SEAL\n"); cat(seal, "\n", sep = "")cat("VERIFY\n"); cat(flag(vok), "\n", sep = "")cat("MUTATED_SEAL\n"); cat(mseal, "\n", sep = "")cat("VERIFY_MUTATED\n"); cat(flag(vbad), "\n", sep = "")cat("NEG_SEAL\n"); cat(nseal, "\n", sep = "")quit(status = 0)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389# SHA-512 (FIPS 180-4) and the bi-encoder DAG seal.# A word is four uint16 limbs, most-significant limb first. Limbs stay in# 0..65535 so R bitwShiftL never overflows a signed 32-bit integer# (bit 31 of a uint32 is R's NA_integer_ and cannot be used with bitw*).## Canonical node preimage, big-endian, no JSON, no floats:# 8 bytes ASCII "SRANOD01"# uint32be role_len, then that many ASCII bytes of the role# uint32be rank, then rank uint32be dimensions# uint32be count (product of the dimensions; rank 0 has count 1)# count integers in row-major order (last axis fastest). Each is# uint32be nbytes, then nbytes of ASCII decimal:# optional leading "-", no "+", no leading zeros, zero is "0"# Node digest = SHA-512 of that preimage (64 bytes).## DAG preimage:# 8 bytes ASCII "SRADAG01"# uint32be child count# that many raw 64-byte digests, fixed order:# exact_head, predicted, weights, prime# The seal is the lowercase hex SHA-512 of the DAG preimage.# verify recomputes the seal from the tensors and compares.
userlib <- path.expand("~/R/library")if (dir.exists(userlib)) .libPaths(c(userlib, .libPaths()))suppressPackageStartupMessages(library(gmp))
NIST_EMPTY <- "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"NIST_ABC <- "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"NIST_LONG <- "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909"NIST_LONG_MSG <- "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"
hex_word <- function(s) { dig <- c(0:9, 10:15) names(dig) <- strsplit("0123456789abcdef", "", fixed = TRUE)[[1]] chars <- strsplit(s, "", fixed = TRUE)[[1]] limbs <- integer(4) for (i in 1:4) { v <- 0L for (k in 1:4) v <- v * 16L + dig[[chars[(i - 1L) * 4L + k]]] limbs[i] <- v } limbs}
H512 <- lapply(c( "6a09e667f3bcc908", "bb67ae8584caa73b", "3c6ef372fe94f82b", "a54ff53a5f1d36f1", "510e527fade682d1", "9b05688c2b3e6c1f", "1f83d9abfb41bd6b", "5be0cd19137e2179"), hex_word)
K512 <- lapply(c( "428a2f98d728ae22", "7137449123ef65cd", "b5c0fbcfec4d3b2f", "e9b5dba58189dbbc", "3956c25bf348b538", "59f111f1b605d019", "923f82a4af194f9b", "ab1c5ed5da6d8118", "d807aa98a3030242", "12835b0145706fbe", "243185be4ee4b28c", "550c7dc3d5ffb4e2", "72be5d74f27b896f", "80deb1fe3b1696b1", "9bdc06a725c71235", "c19bf174cf692694", "e49b69c19ef14ad2", "efbe4786384f25e3", "0fc19dc68b8cd5b5", "240ca1cc77ac9c65", "2de92c6f592b0275", "4a7484aa6ea6e483", "5cb0a9dcbd41fbd4", "76f988da831153b5", "983e5152ee66dfab", "a831c66d2db43210", "b00327c898fb213f", "bf597fc7beef0ee4", "c6e00bf33da88fc2", "d5a79147930aa725", "06ca6351e003826f", "142929670a0e6e70", "27b70a8546d22ffc", "2e1b21385c26c926", "4d2c6dfc5ac42aed", "53380d139d95b3df", "650a73548baf63de", "766a0abb3c77b2a8", "81c2c92e47edaee6", "92722c851482353b", "a2bfe8a14cf10364", "a81a664bbc423001", "c24b8b70d0f89791", "c76c51a30654be30", "d192e819d6ef5218", "d69906245565a910", "f40e35855771202a", "106aa07032bbd1b8", "19a4c116b8d2d0c8", "1e376c085141ab53", "2748774cdf8eeb99", "34b0bcb5e19b48a8", "391c0cb3c5c95a63", "4ed8aa4ae3418acb", "5b9cca4f7763e373", "682e6ff3d6b2b8a3", "748f82ee5defb2fc", "78a5636f43172f60", "84c87814a1f0ab72", "8cc702081a6439ec", "90befffa23631e28", "a4506cebde82bde9", "bef9a3f7b2c67915", "c67178f2e372532b", "ca273eceea26619c", "d186b8c721c0c207", "eada7dd6cde0eb1e", "f57d4f7fee6ed178", "06f067aa72176fba", "0a637dc5a2c898a6", "113f9804bef90dae", "1b710b35131c471b", "28db77f523047d84", "32caab7b40c72493", "3c9ebe0a15c9bebc", "431d67c49c100d4c", "4cc5d4becb3e42b6", "597f299cfc657e2a", "5fcb6fab3ad6faec", "6c44198c4a475817"), hex_word)
addw <- function(a, b) { out <- integer(4) carry <- 0L for (i in 4:1) { s <- a[i] + b[i] + carry out[i] <- bitwAnd(s, 65535L) carry <- bitwShiftR(s, 16L) } out}
shlw <- function(a, n) { if (n <= 0L) return(a) if (n >= 64L) return(c(0L, 0L, 0L, 0L)) limb <- as.integer(n %/% 16L) bit <- as.integer(n %% 16L) src <- c(0L, 0L, 0L, 0L) if (limb < 4L) { for (i in seq_len(4L - limb)) src[i] <- a[i + limb] } if (bit == 0L) return(src) ext <- c(src, 0L) out <- integer(4) shift_down <- 16L - bit for (i in 1:4) { low_from_next <- bitwShiftR(ext[i + 1L], shift_down) out[i] <- bitwAnd(bitwShiftL(ext[i], bit) + low_from_next, 65535L) } out}
shrw <- function(a, n) { if (n <= 0L) return(a) if (n >= 64L) return(c(0L, 0L, 0L, 0L)) limb <- as.integer(n %/% 16L) bit <- as.integer(n %% 16L) src <- c(0L, 0L, 0L, 0L) if (limb < 4L) { for (i in (limb + 1L):4L) src[i] <- a[i - limb] } if (bit == 0L) return(src) out <- integer(4) prev <- 0L mask <- bitwShiftL(1L, bit) - 1L up <- 16L - bit for (i in 1:4) { v <- src[i] high <- bitwShiftL(bitwAnd(prev, mask), up) out[i] <- bitwAnd(bitwShiftR(v, bit) + high, 65535L) prev <- v } out}
rotrw <- function(a, n) { n <- as.integer(n %% 64L) if (n == 0L) return(a) bitwOr(shrw(a, n), shlw(a, 64L - n))}
notw <- function(a) bitwXor(a, 65535L)andw <- function(a, b) bitwAnd(a, b)xorw <- function(a, b) bitwXor(a, b)
pack8 <- function(b) { b <- as.integer(b) c( bitwOr(bitwShiftL(b[1], 8L), b[2]), bitwOr(bitwShiftL(b[3], 8L), b[4]), bitwOr(bitwShiftL(b[5], 8L), b[6]), bitwOr(bitwShiftL(b[7], 8L), b[8]) )}
be8 <- function(w) { out <- integer(8) k <- 1L for (i in 1:4) { out[k] <- bitwShiftR(w[i], 8L) out[k + 1L] <- bitwAnd(w[i], 255L) k <- k + 2L } as.raw(out)}
sha512_raw <- function(msg) { if (!is.raw(msg)) stop("sha512_raw expects raw", call. = FALSE) nb <- length(msg) bitlen <- nb * 8 base <- nb + 1L z <- as.integer((112L - (base %% 128L)) %% 128L) total <- base + z + 16L buf <- raw(total) if (nb > 0L) buf[seq_len(nb)] <- msg buf[nb + 1L] <- as.raw(128L) bl <- bitlen for (i in total:(total - 15L)) { buf[i] <- as.raw(bl %% 256) bl <- bl %/% 256 } if ((total %% 128L) != 0L) stop("PAD_FAIL", call. = FALSE) mint <- as.integer(buf) nblk <- total %/% 128L state <- H512 for (bi in seq_len(nblk)) { off <- (bi - 1L) * 128L blk <- mint[(off + 1L):(off + 128L)] ws <- vector("list", 80L) for (j in 0:15) { o <- 8L * j ws[[j + 1L]] <- pack8(blk[(o + 1L):(o + 8L)]) } for (i in 16:79) { w15 <- ws[[i - 14L]] w2 <- ws[[i - 1L]] w16 <- ws[[i - 15L]] w7 <- ws[[i - 6L]] s0 <- xorw(xorw(rotrw(w15, 1L), rotrw(w15, 8L)), shrw(w15, 7L)) s1 <- xorw(xorw(rotrw(w2, 19L), rotrw(w2, 61L)), shrw(w2, 6L)) ws[[i + 1L]] <- addw(addw(addw(w16, s0), w7), s1) } a <- state[[1L]] b <- state[[2L]] c <- state[[3L]] d <- state[[4L]] e <- state[[5L]] f <- state[[6L]] g <- state[[7L]] h <- state[[8L]] for (i in 0:79) { s1 <- xorw(xorw(rotrw(e, 14L), rotrw(e, 18L)), rotrw(e, 41L)) chv <- xorw(andw(e, f), andw(notw(e), g)) t1 <- addw(addw(addw(addw(h, s1), chv), K512[[i + 1L]]), ws[[i + 1L]]) s0 <- xorw(xorw(rotrw(a, 28L), rotrw(a, 34L)), rotrw(a, 39L)) maj <- xorw(xorw(andw(a, b), andw(a, c)), andw(b, c)) t2 <- addw(s0, maj) h <- g g <- f f <- e e <- addw(d, t1) d <- c c <- b b <- a a <- addw(t1, t2) } state[[1L]] <- addw(state[[1L]], a) state[[2L]] <- addw(state[[2L]], b) state[[3L]] <- addw(state[[3L]], c) state[[4L]] <- addw(state[[4L]], d) state[[5L]] <- addw(state[[5L]], e) state[[6L]] <- addw(state[[6L]], f) state[[7L]] <- addw(state[[7L]], g) state[[8L]] <- addw(state[[8L]], h) } out <- raw(0) for (w in state) out <- c(out, be8(w)) out}
raw_hex <- function(r) paste0(sprintf("%02x", as.integer(r)), collapse = "")
sha512_hex <- function(msg) raw_hex(sha512_raw(msg))
u32be_raw <- function(v) { v <- as.numeric(v) as.raw(c( (v %/% 16777216) %% 256, (v %/% 65536) %% 256, (v %/% 256) %% 256, v %% 256 ))}
node_raw <- function(role, tensor) { if (!inherits(tensor, "bigz")) stop(paste("NOT_BIGZ", role), call. = FALSE) if (is.null(dim(tensor))) { rank <- 0L dims <- integer(0) dec <- as.character(tensor) } else if (length(dim(tensor)) == 2L) { rank <- 2L dims <- as.integer(dim(tensor)) dec <- c(t(as.character(tensor))) } else { stop("rank not supported", call. = FALSE) } if (any(grepl("[^0-9-]", dec))) stop("bad decimal", call. = FALSE) role_raw <- charToRaw(role) lens <- nchar(dec, type = "bytes") total <- 8L + 4L + length(role_raw) + 4L + 4L * rank + 4L + sum(lens + 4L) buf <- raw(total) pos <- 1L put <- function(r) { n <- length(r) if (n == 0L) return() buf[pos:(pos + n - 1L)] <<- r pos <<- pos + n } put(charToRaw("SRANOD01")) put(u32be_raw(length(role_raw))) put(role_raw) put(u32be_raw(rank)) for (d in dims) put(u32be_raw(d)) put(u32be_raw(length(dec))) for (i in seq_along(dec)) { put(u32be_raw(lens[i])) put(charToRaw(dec[i])) } if (pos != total + 1L) stop(paste("encode length", pos, total), call. = FALSE) buf}
dag_raw <- function(digests) { n <- length(digests) buf <- raw(8L + 4L + 64L * n) buf[1:8] <- charToRaw("SRADAG01") buf[9:12] <- u32be_raw(n) pos <- 13L for (d in digests) { if (length(d) != 64L) stop("digest len", call. = FALSE) buf[pos:(pos + 63L)] <- d pos <- pos + 64L } buf}
dag_seal_hex <- function(exact, predicted, weights, prime) { d1 <- sha512_raw(node_raw("exact_head", exact)) d2 <- sha512_raw(node_raw("predicted", predicted)) d3 <- sha512_raw(node_raw("weights", weights)) d4 <- sha512_raw(node_raw("prime", prime)) raw_hex(sha512_raw(dag_raw(list(d1, d2, d3, d4))))}
verify_dag <- function(claimed, exact, predicted, weights, prime) { identical(claimed, dag_seal_hex(exact, predicted, weights, prime))}
sha512_selftest <- function() { e <- sha512_hex(raw()) a <- sha512_hex(charToRaw("abc")) g <- sha512_hex(charToRaw(NIST_LONG_MSG)) if (!identical(e, NIST_EMPTY) || !identical(a, NIST_ABC) || !identical(g, NIST_LONG)) { stop(paste("SHA512_SELFTEST_FAIL", e, a, g), call. = FALSE) } invisible(TRUE)}
sha512_selftest()if (sys.nframe() == 0L) quit(status = 0L)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249# One integer training step. Not softmax. Not a training framework.# Forward nodes, in order: subtract, compare, predicate, select, route, reduce.# Wq and Wk stay the fixed permutation. The unmasked head stays A times B.# The routed residual (exact product minus routed prediction) is added once# to an integer projection, then that projection is added elementwise to# the routed prediction. The unmasked head is not changed.# No weight update, no floor, no modulus. gmp bigz only.# AGPL-3.0 only. Do not use MIT.
userlib <- path.expand("~/R/library")if (dir.exists(userlib)) .libPaths(c(userlib, .libPaths()))suppressPackageStartupMessages(library(gmp))
cmd_args <- commandArgs(trailingOnly = FALSE)file_arg <- grep("^--file=", cmd_args, value = TRUE)this_file <- sub("^--file=", "", file_arg[[1]])source(file.path(dirname(normalizePath(this_file)), "sha512.R"))
P <- as.bigz("18446744069414584321")LCGA <- as.bigz("48271")LCGM <- as.bigz("2147483647")SEED0 <- as.bigz("20261002")RADIX <- as.bigz("5")PRE_SEAL_WANT <- "e6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6e"
refuse_double <- function(M, where) { if (is.double(M) || inherits(M, "numeric")) { if (!inherits(M, "bigz")) stop(paste("FLOAT_REFUSED", where), call. = FALSE) } if (!inherits(M, "bigz")) stop(paste("NOT_BIGZ", where), call. = FALSE) M}
as_mat <- function(chars, nr, nc) { if (any(grepl("[^0-9-]", chars))) stop("non-digit matrix entry", call. = FALSE) refuse_double(as.bigz(base::matrix(chars, nrow = nr, ncol = nc, byrow = TRUE)), "as_mat")}
zeros <- function(nr, nc) as_mat(rep("0", nr * nc), nr, nc)
zvec <- function(n) { v <- as.bigz(rep("0", n)) if (!inherits(v, "bigz")) stop("NOT_BIGZ zvec", call. = FALSE) v}
transpose_z <- function(M) { refuse_double(M, "transpose_in") nr <- nrow(M) nc <- ncol(M) out <- zeros(nc, nr) for (i in seq_len(nr)) { for (j in seq_len(nc)) out[j, i] <- M[i, j] } refuse_double(out, "transpose_out")}
mm <- function(A, B) { refuse_double(A, "mm.A") refuse_double(B, "mm.B") refuse_double(A %*% B, "mm.C")}
lcg_step <- function(seed) mod.bigz(LCGA * seed, LCGM)
lcg_draw <- function(n, seed) { buf <- character(n) for (i in seq_len(n)) { seed <- lcg_step(seed) buf[i] <- as.character(mod.bigz(seed, RADIX)) } list(vals = as.bigz(buf), seed = seed)}
# Forward DAG.fwd_subtract <- function(q, k) refuse_double(k - q, "subtract")
fwd_compare <- function(diff) { refuse_double(as.bigz(diff <= as.bigz("0")), "compare")}
fwd_predicate <- function(cmp) refuse_double(as.bigz(cmp), "predicate")
fwd_select <- function(pred) which(pred != as.bigz("0"))
fwd_route <- function(q, k, idx) { prod <- refuse_double(q * k, "route_prod") terms <- zvec(length(prod)) if (length(idx)) terms[idx] <- prod[idx] refuse_double(terms, "route")}
fwd_reduce <- function(routed) refuse_double(sum(routed), "reduce")
pair_forward <- function(q, k) { diff <- fwd_subtract(q, k) cmp <- fwd_compare(diff) pred <- fwd_predicate(cmp) idx <- fwd_select(pred) routed <- fwd_route(q, k, idx) y <- fwd_reduce(routed) list(cmp = cmp, pred = pred, idx = idx, y = y)}
predict_nodes <- function(Q, K) { pr <- zeros(nrow(Q), nrow(K)) for (i in seq_len(nrow(Q))) { for (j in seq_len(nrow(K))) { nodes <- pair_forward(Q[i, ], K[j, ]) pr[i, j] <- nodes$y } } refuse_double(pr, "predict")}
stack_rows <- function(top, bottom) { out <- zeros(nrow(top) + nrow(bottom), ncol(top)) for (i in seq_len(nrow(top))) { for (j in seq_len(ncol(top))) out[i, j] <- top[i, j] } for (i in seq_len(nrow(bottom))) { for (j in seq_len(ncol(bottom))) out[nrow(top) + i, j] <- bottom[i, j] } refuse_double(out, "stack")}
sum_abs <- function(M) { loss <- as.bigz("0") for (i in seq_len(nrow(M))) { for (j in seq_len(ncol(M))) { d <- M[i, j] if (d < as.bigz("0")) d <- -d loss <- loss + d } } refuse_double(loss, "loss")}
max_abs_diff <- function(A, B) { err <- as.bigz("0") for (i in seq_len(nrow(A))) { for (j in seq_len(ncol(A))) { d <- A[i, j] - B[i, j] if (d < as.bigz("0")) d <- -d if (d > err) err <- d } } refuse_double(err, "max_abs")}
cat_line <- function(x) cat(as.character(x), "\n", sep = "")
cat_mat <- function(M) { refuse_double(M, "print") for (i in seq_len(nrow(M))) { cat(paste(as.character(M[i, ]), collapse = " "), "\n", sep = "") }}
flag <- function(x) if (isTRUE(x)) "1" else "0"
fail <- function(msg) { cat("TRAIN_STEP_FAIL\n", msg, "\n", sep = "") quit(status = 1)}
perm_chars <- c( "0", "1", "0", "0", "0", "0", "1", "0", "0", "0", "0", "1", "1", "0", "0", "0")PERM <- as_mat(perm_chars, 4L, 4L)drawn_a <- lcg_draw(16L, SEED0)drawn_b <- lcg_draw(16L, drawn_a$seed)A <- as_mat(as.character(drawn_a$vals), 4L, 4L)B <- as_mat(as.character(drawn_b$vals), 4L, 4L)Q <- mm(A, PERM)K <- mm(transpose_z(B), PERM)EX <- mm(Q, transpose_z(K))REF <- mm(A, B)PR <- predict_nodes(Q, K)RES <- refuse_double(EX - PR, "residual")LOSS <- sum_abs(RES)ERR <- max_abs_diff(PR, REF)known <- as_mat(c( "18", "18", "12", "16", "23", "22", "12", "19", "19", "29", "18", "29", "6", "15", "10", "15"), 4L, 4L)if (!all(EX == REF)) fail("pre exact head mismatch")if (!all(EX == known)) fail("pre exact head is not the known product")if (as.character(ERR) != "15") fail("pre max abs error is not 15")PRE_SEAL <- dag_seal_hex(EX, PR, PERM, P)if (!identical(PRE_SEAL, PRE_SEAL_WANT)) fail("pre seal mismatch")
# Wq and Wk stay the permutation. Projection starts at 0 and gains the residual.WQ <- PERMWK <- PERMPROJ0 <- zeros(nrow(EX), ncol(EX))PROJ <- refuse_double(PROJ0 + RES, "projection")if (!all(WQ == PERM) || !all(WK == PERM)) fail("weights moved before recompute")
# Unmasked head stays the frozen-weight product. It is not multiplied by# the projection. The post routed prediction is the pre routed prediction# plus the projection, elementwise.Q2 <- mm(A, WQ)K2 <- mm(transpose_z(B), WK)EX2 <- mm(Q2, transpose_z(K2))PR2 <- refuse_double(PR + PROJ, "post_predicted")REF2 <- mm(A, B)ERR2 <- max_abs_diff(PR2, REF2)if (!all(EX2 == REF2)) fail("post exact head mismatch")if (!all(WQ == PERM) || !all(WK == PERM)) fail("weights moved")# Seal post-step tensors: exact head, routed prediction, then Wq, Wk, projection.WT <- stack_rows(stack_rows(WQ, WK), PROJ)SEAL <- dag_seal_hex(EX2, PR2, WT, P)VOK <- verify_dag(SEAL, EX2, PR2, WT, P)if (!isTRUE(VOK)) fail("post seal verify")
cat("TRAIN_STEP_V1\n")cat("ENGINE\nR\n")cat("M\n4\nK\n4\nN\n4\nD\n4\n")cat("SEED\n")cat_line(SEED0)cat("A\n"); cat_mat(A)cat("B\n"); cat_mat(B)cat("WQ\n"); cat_mat(WQ)cat("WK\n"); cat_mat(WK)cat("PROJ_BEFORE\n"); cat_mat(PROJ0)cat("PROJ_AFTER\n"); cat_mat(PROJ)cat("PRE_EXACT_HEAD\n"); cat_mat(EX)cat("PRE_PREDICTED\n"); cat_mat(PR)cat("PRE_REFERENCE\n"); cat_mat(REF)cat("RESIDUAL\n"); cat_mat(RES)cat("LOSS\n"); cat_line(LOSS)cat("POST_EXACT_HEAD\n"); cat_mat(EX2)cat("POST_PREDICTED\n"); cat_mat(PR2)cat("POST_REFERENCE\n"); cat_mat(REF2)cat("PRE_MAX_ABS_ERROR\n"); cat_line(ERR)cat("POST_MAX_ABS_ERROR\n"); cat_line(ERR2)cat("PRE_EXACT_HEAD_MATCH\n"); cat(flag(all(EX == REF)), "\n", sep = "")cat("POST_EXACT_HEAD_MATCH\n"); cat(flag(all(EX2 == REF2)), "\n", sep = "")cat("NOT_SOFTMAX\n1\n")cat("PRE_SEAL\n"); cat(PRE_SEAL, "\n", sep = "")cat("SEAL\n"); cat(SEAL, "\n", sep = "")cat("VERIFY\n"); cat(flag(VOK), "\n", sep = "")quit(status = 0)123456789101112131415"""Retired. Not a numeric authority.
The SUBLEQ bi-encoder runs in J (j/biencoder.ijs) and R (r/biencoder.R).Both use extended integers. Python must not multiply, mask, or reduce mod pfor this pipeline. scripts/run_biencoder.py only launches those programs andcompares the integers they print.
TinyAPL under tinyapl/ is the earlier experiment. Its Complex Double typecannot hold Goldilocks p = 18446744069414584321."""
raise RuntimeError( "reference/biencoder.py is retired. Run scripts/run_biencoder.py " "(J and R extended integers). Python is not the bi-encoder.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""Goldilocks prime field F_p with p = 2^64 - 2^32 + 1.
Exact Python reference for verification. TinyAPL uses Complex Double and cannotrepresent arbitrary field elements; candidates must match this module mod p."""from __future__ import annotations
P = (1 << 64) - (1 << 32) + 1 # 18446744069414584321assert P == 18446744069414584321
def canonical(x: int) -> int: """C: map any integer into the canonical residue [0, p).""" return x % P
def add(a: int, b: int) -> int: return (canonical(a) + canonical(b)) % P
def sub(a: int, b: int) -> int: return (canonical(a) - canonical(b)) % P
def mul(a: int, b: int) -> int: return (canonical(a) * canonical(b)) % P
def exp(a: int, e: int) -> int: """Modular exponentiation; e may be any non-negative int.""" if e < 0: raise ValueError("exponent must be non-negative") return pow(canonical(a), e, P)
def inverse(a: int) -> int: a = canonical(a) if a == 0: raise ZeroDivisionError("inverse of 0 in Goldilocks") # p is prime => a^(p-2) β‘ a^{-1} return pow(a, P - 2, P)
def negate(a: int) -> int: return (-canonical(a)) % P
def dot(xs: list[int], ys: list[int]) -> int: if len(xs) != len(ys): raise ValueError("dot length mismatch") acc = 0 for x, y in zip(xs, ys): acc = (acc + mul(x, y)) % P return acc
def reduce_sum(xs: list[int]) -> int: acc = 0 for x in xs: acc = add(acc, x) return acc
def reduce_product(xs: list[int]) -> int: if not xs: return 1 acc = 1 for x in xs: acc = mul(acc, x) return acc
def scan_sum(xs: list[int]) -> list[int]: out = [] acc = 0 for x in xs: acc = add(acc, x) out.append(acc) return out
def scan_product(xs: list[int]) -> list[int]: out = [] acc = 1 for x in xs: acc = mul(acc, x) out.append(acc) return out
def polynomial_eval(coeffs: list[int], x: int) -> int: """Horner evaluation: coeffs[0] + coeffs[1]*x + ... (low degree first).""" acc = 0 for c in reversed(coeffs): acc = add(mul(acc, x), c) return acc
def tree_reduce_sum(xs: list[int]) -> tuple[int, int]: """Balanced pairwise tree reduce. Returns (value, dependency_depth).""" if not xs: return 0, 0 layer = [canonical(x) for x in xs] depth = 0 while len(layer) > 1: nxt = [] for i in range(0, len(layer) - 1, 2): nxt.append(add(layer[i], layer[i + 1])) if len(layer) % 2 == 1: nxt.append(layer[-1]) layer = nxt depth += 1 return layer[0], depth
def sequential_reduce_sum(xs: list[int]) -> tuple[int, int]: """Left fold. Depth = max(N-1, 0).""" n = len(xs) return reduce_sum(xs), max(n - 1, 0)
def chunked_reduce_sum(xs: list[int], chunk: int = 4) -> tuple[int, int]: if chunk < 1: raise ValueError("chunk must be >= 1") if not xs: return 0, 0 partials = [] for i in range(0, len(xs), chunk): partials.append(reduce_sum(xs[i : i + chunk])) # depth β (chunk-1) + (num_chunks-1) in sequential combine of partials val, d2 = sequential_reduce_sum(partials) d1 = min(chunk - 1, max(len(xs) - 1, 0)) if xs else 0 return val, d1 + d2
__all__ = [ "P", "canonical", "add", "sub", "mul", "exp", "inverse", "negate", "dot", "reduce_sum", "reduce_product", "scan_sum", "scan_product", "polynomial_eval", "tree_reduce_sum", "sequential_reduce_sum", "chunked_reduce_sum",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411"""Reduction algebra R = (D, OP, E, A, C, S) β Python reference.
Implements boolean/arithmetic/structural primitives, SUBLEQ attention pipeline,topologies R0βR7, and cryptographic stubs. Goldilocks field ops live ingoldilocks.py and are re-exported here for a single import surface."""from __future__ import annotations
import hashlibimport jsonimport mathfrom dataclasses import dataclass, asdictfrom typing import Any, Callable, Iterable, Sequence
from goldilocks import ( P, add as g_add, sub as g_sub, mul as g_mul, exp as g_exp, inverse as g_inverse, canonical as g_canonical, dot as g_dot, reduce_sum as g_reduce_sum, scan_sum as g_scan_sum, polynomial_eval as g_poly, tree_reduce_sum, sequential_reduce_sum, chunked_reduce_sum,)
# ---------------------------------------------------------------------------# Boolean reductions# ---------------------------------------------------------------------------
def all_(xs: Sequence[bool | int]) -> bool: return all(bool(x) for x in xs)
def any_(xs: Sequence[bool | int]) -> bool: return any(bool(x) for x in xs)
def xor_(xs: Sequence[bool | int]) -> bool: acc = False for x in xs: acc = acc ^ bool(x) return acc
def threshold(xs: Sequence[bool | int], k: int) -> bool: return sum(bool(x) for x in xs) >= k
# ---------------------------------------------------------------------------# Arithmetic reductions (ordinary β not Goldilocks)# ---------------------------------------------------------------------------
def sum_(xs: Sequence[float | int]) -> float | int: return sum(xs)
def product_(xs: Sequence[float | int]) -> float | int: acc = 1 for x in xs: acc *= x return acc
def min_(xs: Sequence[float | int]): return min(xs)
def max_(xs: Sequence[float | int]): return max(xs)
def scan_sum_ordinary(xs: Sequence[float | int]) -> list: out, acc = [], 0 for x in xs: acc = acc + x out.append(acc) return out
# ---------------------------------------------------------------------------# Structural# ---------------------------------------------------------------------------
def reduce_op(xs: Sequence[Any], op: Callable[[Any, Any], Any], identity=None): it = iter(xs) try: acc = next(it) if identity is None else identity except StopIteration: if identity is None: raise ValueError("empty reduce without identity") return identity if identity is not None: # restart with identity acc = identity it = iter(xs) for x in it: acc = op(acc, x) return acc
def tree_reduce(xs: Sequence[Any], op: Callable[[Any, Any], Any]) -> tuple[Any, int]: if not xs: raise ValueError("empty tree reduce") layer = list(xs) depth = 0 while len(layer) > 1: nxt = [] for i in range(0, len(layer) - 1, 2): nxt.append(op(layer[i], layer[i + 1])) if len(layer) % 2: nxt.append(layer[-1]) layer = nxt depth += 1 return layer[0], depth
def segmented_reduce(xs: Sequence[Any], flags: Sequence[int], op: Callable, identity=0): """Match TinyAPL Partition β : nonzero runs form segments; zeros are gaps.""" if len(xs) != len(flags): raise ValueError("segmented_reduce length mismatch") parts: list[list] = [] cur = None for x, f in zip(xs, flags): if f: if cur is None: cur = [] parts.append(cur) cur.append(x) else: cur = None out = [] for part in parts: if not part: continue acc = part[0] for y in part[1:]: acc = op(acc, y) out.append(acc) return out
def segmented_reduce_keep(xs: Sequence[Any], flags: Sequence[int], op: Callable, identity=0): """flags[i]==1 starts a new segment; every element belongs to some segment.""" if len(xs) != len(flags): raise ValueError("segmented_reduce_keep length mismatch") out = [] acc = identity started = False for x, f in zip(xs, flags): if f and started: out.append(acc) acc = identity acc = op(acc, x) started = True if started: out.append(acc) return out
def rank_reduce(matrix: Sequence[Sequence[Any]], op: Callable, axis: int = 0): """Reduce 2D along axis 0 (rowsβcol reduce) or 1 (per-row reduce).""" if not matrix: return [] if axis == 1: return [reduce_op(row, op) for row in matrix] cols = len(matrix[0]) out = [] for j in range(cols): col = [matrix[i][j] for i in range(len(matrix))] out.append(reduce_op(col, op)) return out
def contract(tensor: Sequence[Sequence[float]], axis: int = 0): """Sum-contract along axis (matrices only).""" return rank_reduce(tensor, lambda a, b: a + b, axis=axis)
def partition(xs: Sequence[Any], flags: Sequence[int]) -> list[list[Any]]: """TinyAPL β semantics: contiguous nonzero flags form partitions; zeros are gaps.""" parts: list[list[Any]] = [] cur: list[Any] | None = None for x, f in zip(xs, flags): if f: if cur is None: cur = [] parts.append(cur) cur.append(x) else: cur = None return parts
def inner_product(xs: Sequence[float], ys: Sequence[float]) -> float: return sum(a * b for a, b in zip(xs, ys))
def outer_product(xs: Sequence[float], ys: Sequence[float], op=lambda a, b: a * b): return [[op(a, b) for b in ys] for a in xs]
def fused_map_reduce(xs: Sequence[Any], map_fn: Callable, red_op: Callable, identity=0): acc = identity for x in xs: acc = red_op(acc, map_fn(x)) return acc
# ---------------------------------------------------------------------------# Attention (SUBLEQ-style β NOT softmax)# ---------------------------------------------------------------------------
@dataclassclass AttentionState: selected: list[float] routed: list[float] aggregate: float predicate: list[int] meta: dict
def subleq_subtract(a: Sequence[float], b: Sequence[float]) -> list[float]: """B[i] β B[i] - A[i] (returns new B').""" if len(a) != len(b): raise ValueError("subtract length mismatch") return [bi - ai for ai, bi in zip(a, b)]
def compare_le_zero(xs: Sequence[float]) -> list[int]: """COMPARE β PREDICATE: 1 iff x β€ 0 (SUBLEQ branch sense).""" return [1 if x <= 0 else 0 for x in xs]
def select(xs: Sequence[float], mask: Sequence[int]) -> list[float]: return [x for x, m in zip(xs, mask) if m]
def route(xs: Sequence[float], mask: Sequence[int], fill: float = 0.0) -> list[float]: """Keep values where mask=1, else fill (positional route).""" return [x if m else fill for x, m in zip(xs, mask)]
def aggregate_sum(xs: Sequence[float]) -> float: return float(sum(xs))
def attention_contract(routed: Sequence[float]) -> float: return aggregate_sum(routed)
def subleq_attention_pipeline( a: Sequence[float], b: Sequence[float],) -> AttentionState: """ARRAY β SUBTRACT β COMPARE β PREDICATE β SELECT β ROUTE β REDUCE β STATE.
Does NOT claim equivalence to softmax attention. """ diff = subleq_subtract(a, b) pred = compare_le_zero(diff) selected = select(diff, pred) routed = route(diff, pred, fill=0.0) agg = attention_contract(routed) return AttentionState( selected=selected, routed=routed, aggregate=agg, predicate=pred, meta={ "pipeline": "SUBLEQ", "note": "Not softmax attention; subtract-compare-route-reduce.", "diff": diff, }, )
# ---------------------------------------------------------------------------# Crypto stubs (deterministic hashes β not production crypto)# ---------------------------------------------------------------------------
def canonicalize(obj: Any) -> str: """C: canonical JSON (sorted keys, no spaces).""" return json.dumps(obj, sort_keys=True, separators=(",", ":"), default=str)
def commit(data: Any) -> str: return hashlib.sha256(canonicalize(data).encode()).hexdigest()
def chain(prev_hash: str, data: Any) -> str: return hashlib.sha256((prev_hash + canonicalize(data)).encode()).hexdigest()
def seal(data: Any, key: str = "sovereign-reduction-algebra") -> dict: body = canonicalize(data) mac = hashlib.sha256((key + body).encode()).hexdigest() return {"body": body, "seal": mac, "alg": "HMAC-SHA256-stub", "key_id": "stub"}
def verify(sealed: dict, key: str = "sovereign-reduction-algebra") -> bool: mac = hashlib.sha256((key + sealed["body"]).encode()).hexdigest() return mac == sealed.get("seal")
# ---------------------------------------------------------------------------# Topologies R0βR7# ---------------------------------------------------------------------------
@dataclassclass TopologyResult: topology: str value: Any dependency_depth: int | None notes: str
def R0_scalar_reference(xs: Sequence[float]) -> TopologyResult: """R0: scalar Python sum reference.""" return TopologyResult("R0_scalar_reference", float(sum(xs)), 0, "reference scalar fold")
def R1_sequential(xs: Sequence[float]) -> TopologyResult: n = len(xs) acc = 0.0 for x in xs: acc += x return TopologyResult("R1_sequential", acc, max(n - 1, 0), "sequential D=N-1")
def R2_balanced_tree(xs: Sequence[float]) -> TopologyResult: val, depth = tree_reduce(list(xs), lambda a, b: a + b) if xs else (0.0, 0) expected = math.ceil(math.log2(len(xs))) if len(xs) > 1 else 0 return TopologyResult( "R2_balanced_tree", float(val), depth, f"tree depth={depth}, ceil(log2 N)={expected}", )
def R3_chunked(xs: Sequence[float], chunk: int = 4) -> TopologyResult: if not xs: return TopologyResult("R3_chunked", 0.0, 0, "empty") partials = [sum(xs[i : i + chunk]) for i in range(0, len(xs), chunk)] val = sum(partials) depth = (min(chunk, len(xs)) - 1) + (len(partials) - 1) return TopologyResult("R3_chunked", float(val), depth, f"chunk={chunk}")
def R4_segmented(xs: Sequence[float], flags: Sequence[int] | None = None) -> TopologyResult: if flags is None: flags = [1] + [0] * (len(xs) - 1) segs = segmented_reduce(xs, flags, lambda a, b: a + b, identity=0) return TopologyResult("R4_segmented", segs, None, "per-segment sums")
def R5_tacit_fused(xs: Sequence[float]) -> TopologyResult: """Map (xβx) fused into sum β semantic identity with sum.""" val = fused_map_reduce(xs, lambda x: x, lambda a, b: a + b, identity=0.0) return TopologyResult("R5_tacit_fused", float(val), max(len(xs) - 1, 0), "fused map-reduce")
def R6_goldilocks_field(xs: Sequence[int]) -> TopologyResult: val, depth = sequential_reduce_sum(xs) return TopologyResult("R6_goldilocks_field", val, depth, f"sum mod p, p={P}")
def R7_subleq_routed_field(a: Sequence[int], b: Sequence[int]) -> TopologyResult: """SUBLEQ pipeline over Goldilocks: subtract, predicate β€0 (as signed lift), route, then field-sum the routed values (negatives canonicalized). """ # Work in signed ints then canonicalise for field aggregate diff = [g_sub(bi, ai) for ai, bi in zip(a, b)] # Predicate on balanced representatives in (-p/2, p/2] pred = [] for d in diff: signed = d if d <= P // 2 else d - P pred.append(1 if signed <= 0 else 0) routed = [d if m else 0 for d, m in zip(diff, pred)] agg = g_reduce_sum(routed) return TopologyResult( "R7_subleq_routed_field", {"predicate": pred, "routed": routed, "aggregate": agg}, max(len(a) - 1, 0), "SUBLEQ-routed Goldilocks reduce; not softmax", )
def run_all_topologies(xs: Sequence[float], a=None, b=None, gxs=None) -> list[TopologyResult]: gxs = gxs if gxs is not None else [int(x) % P for x in xs] a = a if a is not None else gxs b = b if b is not None else [(2 * x) % P for x in gxs] return [ R0_scalar_reference(xs), R1_sequential(xs), R2_balanced_tree(xs), R3_chunked(xs), R4_segmented(xs), R5_tacit_fused(xs), R6_goldilocks_field(gxs), R7_subleq_routed_field(a, b), ]
def result_to_dict(r: TopologyResult) -> dict: return asdict(r)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103{ "schema_version": "1.0.0", "timestamp_pt": "2026-10-03 15:48:00 PT", "note": "Every seconds value is a decimal string printed by J 6!:2 (format 0j6, rounded to 1e-6 second) or by R system.time (elapsed, plus user.self and sys.self, formatC digits 6). Python did not time these operations and did not fill gaps. Inputs are extended integers: A[i;j]=(i*N+j) mod 5 and B[i;j]=(N*N+i*N+j) mod 5, row-major. sha512_dag_seal times dag_seal_hex of exact=product, predicted=product, the 4x4 permutation, and Goldilocks p. The routed head is not in this timing. N=1024 seal is omitted for R; see not_run. On 2026-10-03 the J N=1024 unmasked_integer_matmul seconds were replaced with a new 6!:2 measurement (72.315527, 73.415031, 73.807073); checksum 4294962175 and result type 64 were printed again and are unchanged. The J N=1024 sha512_dag_seal seconds were replaced with the 6!:2 value printed for that 1-trial record (512.146054). Checksum 681ec299e447f7c07defe7a09ee8641c6a66fa60d041a1a8dccc5196e7c9fb2aa4238618fc0d098cc8913cf9a878aa29f27d4102cffa2ff2cfa405a3533b89af, node_bytes 8388646, and result type sha512 were printed again and are unchanged. All other J and R seconds remain the 2026-10-02 23:10:14 PT measurements.", "runs": [{ "language": "J", "version": "j9.7.1/j64/linux/commercial/www.jsoftware.com/2026-04-06T04:00:54/clang-14-0-0/SLEEF=0", "operation": "unmasked_integer_matmul", "shape": {"m": 128, "k": 128, "n": 128}, "timer": "6!:2", "trials": 3, "seconds": [0.112684, 0.092637, 0.095784], "checksum": "8388098", "result_type": "64" },{ "language": "J", "version": "j9.7.1/j64/linux/commercial/www.jsoftware.com/2026-04-06T04:00:54/clang-14-0-0/SLEEF=0", "operation": "sha512_dag_seal", "shape": {"m": 128, "k": 128, "n": 128}, "timer": "6!:2", "trials": 3, "seconds": [6.514977, 6.452345, 6.419265], "checksum": "ccafddfba100f51a3856500b009f0644f15d6956e7ecd9667d4e84c4a6a74f7cc60cfe83381f559ff7d28979ebcbc44758f07a7ba86e9a6b682adaee2555a6fc", "node_bytes": 114726, "result_type": "sha512" },{ "language": "J", "version": "j9.7.1/j64/linux/commercial/www.jsoftware.com/2026-04-06T04:00:54/clang-14-0-0/SLEEF=0", "operation": "unmasked_integer_matmul", "shape": {"m": 1024, "k": 1024, "n": 1024}, "timer": "6!:2", "trials": 3, "seconds": [72.315527, 73.415031, 73.807073], "checksum": "4294962175", "result_type": "64" },{ "language": "J", "version": "j9.7.1/j64/linux/commercial/www.jsoftware.com/2026-04-06T04:00:54/clang-14-0-0/SLEEF=0", "operation": "sha512_dag_seal", "shape": {"m": 1024, "k": 1024, "n": 1024}, "timer": "6!:2", "trials": 1, "seconds": [512.146054], "checksum": "681ec299e447f7c07defe7a09ee8641c6a66fa60d041a1a8dccc5196e7c9fb2aa4238618fc0d098cc8913cf9a878aa29f27d4102cffa2ff2cfa405a3533b89af", "node_bytes": 8388646, "result_type": "sha512" },{ "language": "R", "version": "R version 4.5.0 (2025-04-11)", "gmp_version": "0.7.5.1", "operation": "unmasked_integer_matmul", "shape": {"m": 128, "k": 128, "n": 128}, "timer": "system.time", "trials": 3, "seconds": [0.089000, 0.089000, 0.090000], "user_seconds": [0.089000, 0.090000, 0.089000], "sys_seconds": [0.000000, 0.000000, 0.000000], "checksum": "8388098", "result_type": "bigz" },{ "language": "R", "version": "R version 4.5.0 (2025-04-11)", "gmp_version": "0.7.5.1", "operation": "sha512_dag_seal", "shape": {"m": 128, "k": 128, "n": 128}, "timer": "system.time", "trials": 3, "seconds": [38.453000, 36.978000, 38.912000], "user_seconds": [38.444000, 36.976000, 38.909000], "sys_seconds": [0.003000, 0.000000, 0.000000], "checksum": "ccafddfba100f51a3856500b009f0644f15d6956e7ecd9667d4e84c4a6a74f7cc60cfe83381f559ff7d28979ebcbc44758f07a7ba86e9a6b682adaee2555a6fc", "node_bytes": 114726, "result_type": "sha512" },{ "language": "R", "version": "R version 4.5.0 (2025-04-11)", "gmp_version": "0.7.5.1", "operation": "unmasked_integer_matmul", "shape": {"m": 1024, "k": 1024, "n": 1024}, "timer": "system.time", "trials": 3, "seconds": [66.719000, 68.561000, 64.266000], "user_seconds": [66.677000, 68.544000, 64.180000], "sys_seconds": [0.036000, 0.012000, 0.080000], "checksum": "4294962175", "result_type": "bigz" } ], "not_run": [ { "language": "R", "line": "1024 sha512_dag_seal not started: N=128 sha512_dag_seal was measured in this process; the node preimage holds N*N integers and the seal hashes two of them, so N=1024 is 64 times the integers. This R SHA-512 is an interpreter loop over 16-bit limbs and was not run at N=1024." }], "problems": []}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610{ "schema_version": "2.0.0", "timestamp_pt": "2026-10-02 23:12:47 PT", "note": "SUBLEQ bi-encoder is not softmax attention and not a trained model. Arithmetic ran in J and R extended integers. Python only launched the processes and compared the printed decimals. The routed tensor is a separate metric; a nonzero max abs error is not a failure of the unmasked head. The production seal is a SHA-512 DAG computed in J and in R over canonical integer tensors (exact head, routed prediction, weights, prime). Python does not hash. TinyAPL is legacy because Complex Double cannot hold p.", "jconsole": "/home/box/j/j9.7/bin/jconsole", "rscript": "/usr/bin/Rscript", "j_version": "j9.7.1/j64/linux/commercial/www.jsoftware.com/2026-04-06T04:00:54/clang-14-0-0/SLEEF=0", "r_version": "R version 4.5.0 (2025-04-11)", "gmp_version": "0.7.5.1", "seed": 20261002, "shapes": { "M": 4, "K": 4, "N": 4 }, "exact_head_match": true, "permutation_inverse": true, "goldilocks_p": "18446744069414584321", "goldilocks_small_agrees": true, "routed": { "max_abs_error": 15, "hand_max_abs_error": 2, "equals_exact_matmul": false, "required_zero": false, "gates_exit": false, "note": "SUBLEQ-routed prediction is a sparse approximation. Nonzero error does not fail the run." }, "seal": { "algorithm": "SHA-512", "dag_order": [ "exact_head", "predicted", "weights", "prime" ], "J": "e6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6e", "R": "e6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6e", "agree": true, "verify": true, "mutated_seal": { "J": "fe52068916fa60f4b75e1130120b0973e9f6a641461ed18fd25a650504b618a0277bf707e0506d754188ac0074449f994e3957736312253524de0e240c5945d1", "R": "fe52068916fa60f4b75e1130120b0973e9f6a641461ed18fd25a650504b618a0277bf707e0506d754188ac0074449f994e3957736312253524de0e240c5945d1" }, "verify_mutated": 0, "neg_seal": { "J": "c56afd8d12695daf5129db682b9eca0556465ba7ed00b8029b7fb85362c1c0530341a512454320c371ee38397d90dd9e1199bd7f705ab763077c05a6e8857a1e", "R": "c56afd8d12695daf5129db682b9eca0556465ba7ed00b8029b7fb85362c1c0530341a512454320c371ee38397d90dd9e1199bd7f705ab763077c05a6e8857a1e" } }, "sha512_kat": { "empty": "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", "abc": "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f", "long": "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909" }, "J": { "engine_line": [ "J" ], "version": "j9.7.1/j64/linux/commercial/www.jsoftware.com/2026-04-06T04:00:54/clang-14-0-0/SLEEF=0", "gmp_version": null, "matrices": { "A": [ [ 2, 4, 0, 0 ], [ 3, 3, 0, 4 ], [ 3, 3, 3, 2 ], [ 2, 1, 2, 0 ] ], "B": [ [ 1, 3, 2, 2 ], [ 4, 3, 2, 3 ], [ 0, 3, 2, 4 ], [ 2, 1, 0, 1 ] ], "WQ": [ [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ], [ 1, 0, 0, 0 ] ], "WK": [ [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ], [ 1, 0, 0, 0 ] ], "Q": [ [ 0, 2, 4, 0 ], [ 4, 3, 3, 0 ], [ 2, 3, 3, 3 ], [ 0, 2, 1, 2 ] ], "KTOWER": [ [ 2, 1, 4, 0 ], [ 1, 3, 3, 3 ], [ 0, 2, 2, 2 ], [ 1, 2, 3, 4 ] ], "PREDICTED": [ [ 18, 12, 12, 16 ], [ 11, 22, 12, 19 ], [ 7, 29, 18, 17 ], [ 2, 0, 8, 4 ] ], "EXACT_HEAD": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ], "REFERENCE": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ], "AGGREGATES": [ [ -1, -1, -2, -1 ], [ -4, -3, -6, -4 ], [ -5, -1, -5, -2 ], [ -3, 0, 0, 0 ] ], "PREDICATES": [ [ 0, 1, 1, 1 ], [ 0, 0, 1, 0 ], [ 1, 1, 1, 0 ], [ 0, 1, 1, 0 ], [ 1, 1, 0, 1 ], [ 1, 1, 1, 0 ], [ 1, 1, 1, 0 ], [ 1, 1, 1, 0 ], [ 1, 1, 0, 1 ], [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ], [ 1, 1, 1, 0 ], [ 0, 1, 0, 1 ], [ 0, 0, 0, 0 ], [ 1, 1, 0, 1 ], [ 0, 1, 0, 0 ] ], "GSAFE_PREDICTED": [ [ 18, 12, 12, 16 ], [ 11, 22, 12, 19 ], [ 7, 29, 18, 17 ], [ 2, 0, 8, 4 ] ], "FIELD_SMALL_PREDICTED": [ [ 18, 12, 12, 16 ], [ 11, 22, 12, 19 ], [ 7, 29, 18, 17 ], [ 2, 0, 8, 4 ] ], "FIELD_SMALL_EXACT_HEAD": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ], "FIELD_SMALL_REFERENCE": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ], "FIELD_LARGE_PREDICTED": [ [ 58, 17, 22, 18446744069414584307 ], [ 53, 33, 33, 18446744069414584310 ], [ 18446744069414584289, 33, 54, 18446744069414584317 ], [ 4, 18446744069414584316, 18446744069414584297, 33 ] ], "FIELD_LARGE_EXACT_HEAD": [ [ 82, 21, 16, 6 ], [ 23, 54, 33, 18446744069414584285 ], [ 15, 25, 54, 18446744069414584320 ], [ 13, 18, 18446744069414584285, 39 ] ], "FIELD_LARGE_REFERENCE": [ [ 82, 21, 16, 6 ], [ 23, 54, 33, 18446744069414584285 ], [ 15, 25, 54, 18446744069414584320 ], [ 13, 18, 18446744069414584285, 39 ] ], "HAND_PREDICTED": [ [ 7, 5 ], [ 4, 9 ] ], "HAND_EXACT_HEAD": [ [ 7, 7 ], [ 6, 9 ] ], "HAND_REFERENCE": [ [ 7, 7 ], [ 6, 9 ] ] }, "max_abs_error": 15, "exact_head_match": true, "permutation_inverse": true, "field_small_agrees": true, "field_large_exact_match": true }, "R": { "engine_line": [ "R" ], "version": "R version 4.5.0 (2025-04-11)", "gmp_version": "0.7.5.1", "matrices": { "A": [ [ 2, 4, 0, 0 ], [ 3, 3, 0, 4 ], [ 3, 3, 3, 2 ], [ 2, 1, 2, 0 ] ], "B": [ [ 1, 3, 2, 2 ], [ 4, 3, 2, 3 ], [ 0, 3, 2, 4 ], [ 2, 1, 0, 1 ] ], "WQ": [ [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ], [ 1, 0, 0, 0 ] ], "WK": [ [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ], [ 1, 0, 0, 0 ] ], "Q": [ [ 0, 2, 4, 0 ], [ 4, 3, 3, 0 ], [ 2, 3, 3, 3 ], [ 0, 2, 1, 2 ] ], "KTOWER": [ [ 2, 1, 4, 0 ], [ 1, 3, 3, 3 ], [ 0, 2, 2, 2 ], [ 1, 2, 3, 4 ] ], "PREDICTED": [ [ 18, 12, 12, 16 ], [ 11, 22, 12, 19 ], [ 7, 29, 18, 17 ], [ 2, 0, 8, 4 ] ], "EXACT_HEAD": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ], "REFERENCE": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ], "AGGREGATES": [ [ -1, -1, -2, -1 ], [ -4, -3, -6, -4 ], [ -5, -1, -5, -2 ], [ -3, 0, 0, 0 ] ], "PREDICATES": [ [ 0, 1, 1, 1 ], [ 0, 0, 1, 0 ], [ 1, 1, 1, 0 ], [ 0, 1, 1, 0 ], [ 1, 1, 0, 1 ], [ 1, 1, 1, 0 ], [ 1, 1, 1, 0 ], [ 1, 1, 1, 0 ], [ 1, 1, 0, 1 ], [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ], [ 1, 1, 1, 0 ], [ 0, 1, 0, 1 ], [ 0, 0, 0, 0 ], [ 1, 1, 0, 1 ], [ 0, 1, 0, 0 ] ], "GSAFE_PREDICTED": [ [ 18, 12, 12, 16 ], [ 11, 22, 12, 19 ], [ 7, 29, 18, 17 ], [ 2, 0, 8, 4 ] ], "FIELD_SMALL_PREDICTED": [ [ 18, 12, 12, 16 ], [ 11, 22, 12, 19 ], [ 7, 29, 18, 17 ], [ 2, 0, 8, 4 ] ], "FIELD_SMALL_EXACT_HEAD": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ], "FIELD_SMALL_REFERENCE": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ], "FIELD_LARGE_PREDICTED": [ [ 58, 17, 22, 18446744069414584307 ], [ 53, 33, 33, 18446744069414584310 ], [ 18446744069414584289, 33, 54, 18446744069414584317 ], [ 4, 18446744069414584316, 18446744069414584297, 33 ] ], "FIELD_LARGE_EXACT_HEAD": [ [ 82, 21, 16, 6 ], [ 23, 54, 33, 18446744069414584285 ], [ 15, 25, 54, 18446744069414584320 ], [ 13, 18, 18446744069414584285, 39 ] ], "FIELD_LARGE_REFERENCE": [ [ 82, 21, 16, 6 ], [ 23, 54, 33, 18446744069414584285 ], [ 15, 25, 54, 18446744069414584320 ], [ 13, 18, 18446744069414584285, 39 ] ], "HAND_PREDICTED": [ [ 7, 5 ], [ 4, 9 ] ], "HAND_EXACT_HEAD": [ [ 7, 7 ], [ 6, 9 ] ], "HAND_REFERENCE": [ [ 7, 7 ], [ 6, 9 ] ] }, "max_abs_error": 15, "exact_head_match": true, "permutation_inverse": true, "field_small_agrees": true, "field_large_exact_match": true }, "stdout": { "J": "BIENCODER_V1\nENGINE\nJ\nJ_VERSION\nj9.7.1/j64/linux/commercial/www.jsoftware.com/2026-04-06T04:00:54/clang-14-0-0/SLEEF=0\nM\n4\nK\n4\nN\n4\nSEED\n20261002\nRADIX\n5\nA\n2 4 0 0\n3 3 0 4\n3 3 3 2\n2 1 2 0\nB\n1 3 2 2\n4 3 2 3\n0 3 2 4\n2 1 0 1\nWQ\n0 1 0 0\n0 0 1 0\n0 0 0 1\n1 0 0 0\nWK\n0 1 0 0\n0 0 1 0\n0 0 0 1\n1 0 0 0\nQ\n0 2 4 0\n4 3 3 0\n2 3 3 3\n0 2 1 2\nKTOWER\n2 1 4 0\n1 3 3 3\n0 2 2 2\n1 2 3 4\nPREDICTED\n18 12 12 16\n11 22 12 19\n 7 29 18 17\n 2 0 8 4\nEXACT_HEAD\n18 18 12 16\n23 22 12 19\n19 29 18 29\n 6 15 10 15\nREFERENCE\n18 18 12 16\n23 22 12 19\n19 29 18 29\n 6 15 10 15\nAGGREGATES\n-1 -1 -2 -1\n-4 -3 -6 -4\n-5 -1 -5 -2\n-3 0 0 0\nPREDICATES\n0 1 1 1\n0 0 1 0\n1 1 1 0\n0 1 1 0\n1 1 0 1\n1 1 1 0\n1 1 1 0\n1 1 1 0\n1 1 0 1\n1 1 1 1\n1 1 1 1\n1 1 1 0\n0 1 0 1\n0 0 0 0\n1 1 0 1\n0 1 0 0\nGSAFE_PREDICTED\n18 12 12 16\n11 22 12 19\n 7 29 18 17\n 2 0 8 4\nMAX_ABS_ERROR\n15\nEXACT_HEAD_MATCH\n1\nPERMUTATION_INVERSE\n1\nSHAPES_OK\n1\nNOT_SOFTMAX\n1\nGOLDILOCKS_P\n18446744069414584321\nFIELD_SMALL_PREDICTED\n18 12 12 16\n11 22 12 19\n 7 29 18 17\n 2 0 8 4\nFIELD_SMALL_EXACT_HEAD\n18 18 12 16\n23 22 12 19\n19 29 18 29\n 6 15 10 15\nFIELD_SMALL_REFERENCE\n18 18 12 16\n23 22 12 19\n19 29 18 29\n 6 15 10 15\nFIELD_SMALL_AGREES\n1\nFIELD_LARGE_PREDICTED\n 58 17 22 18446744069414584307\n 53 33 33 18446744069414584310\n18446744069414584289 33 54 18446744069414584317\n 4 18446744069414584316 18446744069414584297 33\nFIELD_LARGE_EXACT_HEAD\n82 21 16 6\n23 54 33 18446744069414584285\n15 25 54 18446744069414584320\n13 18 18446744069414584285 39\nFIELD_LARGE_REFERENCE\n82 21 16 6\n23 54 33 18446744069414584285\n15 25 54 18446744069414584320\n13 18 18446744069414584285 39\nFIELD_LARGE_EXACT_MATCH\n1\nHAND_PREDICTED\n7 5\n4 9\nHAND_EXACT_HEAD\n7 7\n6 9\nHAND_REFERENCE\n7 7\n6 9\nHAND_MAX_ABS_ERROR\n2\nHAND_EXACT_HEAD_MATCH\n1\nSHA512_EMPTY\ncf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e\nSHA512_ABC\nddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f\nSHA512_LONG\n8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909\nSEAL\ne6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6e\nVERIFY\n1\nMUTATED_SEAL\nfe52068916fa60f4b75e1130120b0973e9f6a641461ed18fd25a650504b618a0277bf707e0506d754188ac0074449f994e3957736312253524de0e240c5945d1\nVERIFY_MUTATED\n0\nNEG_SEAL\nc56afd8d12695daf5129db682b9eca0556465ba7ed00b8029b7fb85362c1c0530341a512454320c371ee38397d90dd9e1199bd7f705ab763077c05a6e8857a1e\n", "R": "BIENCODER_V1\nENGINE\nR\nR_VERSION\nR version 4.5.0 (2025-04-11)\nGMP_VERSION\n0.7.5.1\nM\n4\nK\n4\nN\n4\nSEED\n20261002\nRADIX\n5\nA\n2 4 0 0\n3 3 0 4\n3 3 3 2\n2 1 2 0\nB\n1 3 2 2\n4 3 2 3\n0 3 2 4\n2 1 0 1\nWQ\n0 1 0 0\n0 0 1 0\n0 0 0 1\n1 0 0 0\nWK\n0 1 0 0\n0 0 1 0\n0 0 0 1\n1 0 0 0\nQ\n0 2 4 0\n4 3 3 0\n2 3 3 3\n0 2 1 2\nKTOWER\n2 1 4 0\n1 3 3 3\n0 2 2 2\n1 2 3 4\nPREDICTED\n18 12 12 16\n11 22 12 19\n7 29 18 17\n2 0 8 4\nEXACT_HEAD\n18 18 12 16\n23 22 12 19\n19 29 18 29\n6 15 10 15\nREFERENCE\n18 18 12 16\n23 22 12 19\n19 29 18 29\n6 15 10 15\nAGGREGATES\n-1 -1 -2 -1\n-4 -3 -6 -4\n-5 -1 -5 -2\n-3 0 0 0\nPREDICATES\n0 1 1 1\n0 0 1 0\n1 1 1 0\n0 1 1 0\n1 1 0 1\n1 1 1 0\n1 1 1 0\n1 1 1 0\n1 1 0 1\n1 1 1 1\n1 1 1 1\n1 1 1 0\n0 1 0 1\n0 0 0 0\n1 1 0 1\n0 1 0 0\nGSAFE_PREDICTED\n18 12 12 16\n11 22 12 19\n7 29 18 17\n2 0 8 4\nMAX_ABS_ERROR\n15\nEXACT_HEAD_MATCH\n1\nPERMUTATION_INVERSE\n1\nSHAPES_OK\n1\nNOT_SOFTMAX\n1\nGOLDILOCKS_P\n18446744069414584321\nFIELD_SMALL_PREDICTED\n18 12 12 16\n11 22 12 19\n7 29 18 17\n2 0 8 4\nFIELD_SMALL_EXACT_HEAD\n18 18 12 16\n23 22 12 19\n19 29 18 29\n6 15 10 15\nFIELD_SMALL_REFERENCE\n18 18 12 16\n23 22 12 19\n19 29 18 29\n6 15 10 15\nFIELD_SMALL_AGREES\n1\nFIELD_LARGE_PREDICTED\n58 17 22 18446744069414584307\n53 33 33 18446744069414584310\n18446744069414584289 33 54 18446744069414584317\n4 18446744069414584316 18446744069414584297 33\nFIELD_LARGE_EXACT_HEAD\n82 21 16 6\n23 54 33 18446744069414584285\n15 25 54 18446744069414584320\n13 18 18446744069414584285 39\nFIELD_LARGE_REFERENCE\n82 21 16 6\n23 54 33 18446744069414584285\n15 25 54 18446744069414584320\n13 18 18446744069414584285 39\nFIELD_LARGE_EXACT_MATCH\n1\nHAND_PREDICTED\n7 5\n4 9\nHAND_EXACT_HEAD\n7 7\n6 9\nHAND_REFERENCE\n7 7\n6 9\nHAND_MAX_ABS_ERROR\n2\nHAND_EXACT_HEAD_MATCH\n1\nSHA512_EMPTY\ncf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e\nSHA512_ABC\nddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f\nSHA512_LONG\n8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909\nSEAL\ne6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6e\nVERIFY\n1\nMUTATED_SEAL\nfe52068916fa60f4b75e1130120b0973e9f6a641461ed18fd25a650504b618a0277bf707e0506d754188ac0074449f994e3957736312253524de0e240c5945d1\nVERIFY_MUTATED\n0\nNEG_SEAL\nc56afd8d12695daf5129db682b9eca0556465ba7ed00b8029b7fb85362c1c0530341a512454320c371ee38397d90dd9e1199bd7f705ab763077c05a6e8857a1e\n" }, "stderr": { "J": "", "R": "" }, "correctness": { "passed": 62, "failed": 0, "cases": [ { "name": "j.runs", "pass": true, "detail": "BIENCODER_V1\nENGINE\nJ\nJ_VERSION\nj9.7.1/j64/linux/commercial/www.jsoftware.com/2026-04-06T04:00:54/clang-14-0-0/SLEEF=0\nM\n4\nK\n4\nN\n4\nSEED\n20261002\nRADIX\n5\nA\n2 4 0 0\n3 3 0 4\n3 3 3 2\n2 1 2 0\nB\n1 3 2 2\n4 3 2 3\n0 3 2 4\n2 1 0 1\nWQ\n0 1 0 0\n0 0 1 0\n0 0 0 1\n1 0 0 0\nWK\n0 1 0 0\n0 0 1 0\n0 0 0 1\n1 0 0 0\nQ\n0 2 4 0\n4 3 3 0\n2 3 3 3\n0 2 1 2\nKTOWER\n2 1 4 0\n1 3 3 3\n0 2 2 2\n1 2 3 4\nPREDICTED\n18 12 12 16\n11 22 12 19\n 7", "gates_exit": true }, { "name": "r.runs", "pass": true, "detail": "BIENCODER_V1\nENGINE\nR\nR_VERSION\nR version 4.5.0 (2025-04-11)\nGMP_VERSION\n0.7.5.1\nM\n4\nK\n4\nN\n4\nSEED\n20261002\nRADIX\n5\nA\n2 4 0 0\n3 3 0 4\n3 3 3 2\n2 1 2 0\nB\n1 3 2 2\n4 3 2 3\n0 3 2 4\n2 1 0 1\nWQ\n0 1 0 0\n0 0 1 0\n0 0 0 1\n1 0 0 0\nWK\n0 1 0 0\n0 0 1 0\n0 0 0 1\n1 0 0 0\nQ\n0 2 4 0\n4 3 3 0\n2 3 3 3\n0 2 1 2\nKTOWER\n2 1 4 0\n1 3 3 3\n0 2 2 2\n1 2 3 4\nPREDICTED\n18 12 12 16\n11 22 12 19\n7 29 18 17\n2 0 8 4\nEXACT_HEAD\n18 18 12 1", "gates_exit": true }, { "name": "agree.SHA512_EMPTY", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.SHA512_ABC", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.SHA512_LONG", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.SEAL", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.MUTATED_SEAL", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.NEG_SEAL", "pass": true, "detail": "", "gates_exit": true }, { "name": "sha512.empty", "pass": true, "detail": "", "gates_exit": true }, { "name": "sha512.abc", "pass": true, "detail": "", "gates_exit": true }, { "name": "sha512.long", "pass": true, "detail": "", "gates_exit": true }, { "name": "seal.differs_when_tensor_mutated", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.M", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.K", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.N", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.SEED", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.RADIX", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.A", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.B", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.WQ", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.WK", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.Q", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.KTOWER", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.PREDICTED", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.EXACT_HEAD", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.REFERENCE", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.AGGREGATES", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.PREDICATES", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.GSAFE_PREDICTED", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.MAX_ABS_ERROR", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.EXACT_HEAD_MATCH", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.PERMUTATION_INVERSE", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.SHAPES_OK", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.NOT_SOFTMAX", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.GOLDILOCKS_P", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.FIELD_SMALL_PREDICTED", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.FIELD_SMALL_EXACT_HEAD", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.FIELD_SMALL_REFERENCE", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.FIELD_SMALL_AGREES", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.FIELD_LARGE_PREDICTED", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.FIELD_LARGE_EXACT_HEAD", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.FIELD_LARGE_REFERENCE", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.FIELD_LARGE_EXACT_MATCH", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.HAND_PREDICTED", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.HAND_EXACT_HEAD", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.HAND_REFERENCE", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.HAND_MAX_ABS_ERROR", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.HAND_EXACT_HEAD_MATCH", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.VERIFY", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.VERIFY_MUTATED", "pass": true, "detail": "", "gates_exit": true }, { "name": "exact_head.J_equals_reference", "pass": true, "detail": "", "gates_exit": true }, { "name": "exact_head.R_equals_reference", "pass": true, "detail": "", "gates_exit": true }, { "name": "exact_head.engines_agree", "pass": true, "detail": "", "gates_exit": true }, { "name": "shapes", "pass": true, "detail": "M=4 K=4 N=4", "gates_exit": true }, { "name": "permutation_inverse", "pass": true, "detail": "", "gates_exit": true }, { "name": "goldilocks.small_integer_agreement", "pass": true, "detail": "", "gates_exit": true }, { "name": "goldilocks.large_exact_head", "pass": true, "detail": "", "gates_exit": true }, { "name": "goldilocks.p", "pass": true, "detail": "", "gates_exit": true }, { "name": "hand.exact_head", "pass": true, "detail": "", "gates_exit": true }, { "name": "not_softmax", "pass": true, "detail": "", "gates_exit": true }, { "name": "seal.verify", "pass": true, "detail": "", "gates_exit": true }, { "name": "seal.verify_mutated_fails", "pass": true, "detail": "", "gates_exit": true } ] }, "overall_pass": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274{ "schema_version": "1.0.0", "timestamp_pt": "2026-10-01 01:17:44 PT", "engine": { "tinyapl_version": "0.12.0.0", "tinyapl_path": "/workspace/sovereign-reduction-algebra/vendor/tinyapl", "tinyapl_available": true, "reference": "reference/goldilocks.py + reference/reduction_algebra.py", "notes": "TinyAPL uses Complex Double; full Goldilocks p verified in Python. TinyAPL-native field demos use GSafeP=65537. SUBLEQ pipeline is not softmax attention." }, "correctness": { "passed": 38, "failed": 0, "cases": [ { "name": "goldilocks.p", "pass": true, "detail": "18446744069414584321" }, { "name": "goldilocks.add", "pass": true, "detail": "" }, { "name": "goldilocks.mul", "pass": true, "detail": "" }, { "name": "goldilocks.reduce", "pass": true, "detail": "" }, { "name": "goldilocks.scan", "pass": true, "detail": "" }, { "name": "goldilocks.tree", "pass": true, "detail": "36,3" }, { "name": "goldilocks.poly", "pass": true, "detail": "" }, { "name": "goldilocks.inverse", "pass": true, "detail": "" }, { "name": "goldilocks.exp", "pass": true, "detail": "" }, { "name": "goldilocks.dot", "pass": true, "detail": "" }, { "name": "goldilocks.add.assoc", "pass": true, "detail": "" }, { "name": "goldilocks.mul.assoc", "pass": true, "detail": "" }, { "name": "arith.sum", "pass": true, "detail": "" }, { "name": "arith.product", "pass": true, "detail": "" }, { "name": "arith.scan", "pass": true, "detail": "" }, { "name": "bool.all", "pass": true, "detail": "" }, { "name": "bool.xor", "pass": true, "detail": "" }, { "name": "bool.threshold", "pass": true, "detail": "" }, { "name": "struct.ip", "pass": true, "detail": "" }, { "name": "struct.outer", "pass": true, "detail": "" }, { "name": "struct.seg", "pass": true, "detail": "" }, { "name": "subleq.aggregate", "pass": true, "detail": "" }, { "name": "subleq.pred", "pass": true, "detail": "" }, { "name": "R0", "pass": true, "detail": "" }, { "name": "R1", "pass": true, "detail": "" }, { "name": "R2", "pass": true, "detail": "" }, { "name": "R6", "pass": true, "detail": "" }, { "name": "R7", "pass": true, "detail": "" }, { "name": "crypto.seal_verify", "pass": true, "detail": "" }, { "name": "crypto.commit_len", "pass": true, "detail": "" }, { "name": "tinyapl.demo_runs", "pass": true, "detail": "ok" }, { "name": "tinyapl.sum", "pass": true, "detail": "" }, { "name": "tinyapl.tree36", "pass": true, "detail": "" }, { "name": "tinyapl.r6", "pass": true, "detail": "" }, { "name": "tinyapl.r7_agg", "pass": true, "detail": "" }, { "name": "tinyapl.gsafe_mul", "pass": true, "detail": "" }, { "name": "cross.gsafe_reduce", "pass": true, "detail": "" }, { "name": "cross.full_p_reduce", "pass": true, "detail": "" } ] }, "benchmarks": [ { "topology": "R1_sequential_sum", "shape": [ 128 ], "op": "Sum", "correctness_pass": true, "latency_ms": 0.2536773681640625, "throughput_elems_per_s": 504577.92481203005, "dependency_depth": 127, "status": "measured", "note": "TinyAPL \u2395_Measure on +/\u2373N (library Sum topology R0/R1 style)", "raw_seconds": [ 0.00023794174194335938, 0.0002567768096923828, 0.00020003318786621094, 0.000247955322265625, 0.0003256797790527344 ] }, { "topology": "R1_sequential_sum", "shape": [ 1024 ], "op": "Sum", "correctness_pass": true, "latency_ms": 1.0922431945800781, "throughput_elems_per_s": 937520.1466864577, "dependency_depth": 1023, "status": "measured", "note": "TinyAPL \u2395_Measure on +/\u2373N (library Sum topology R0/R1 style)", "raw_seconds": [ 0.0009634494781494141, 0.0010187625885009766, 0.0012302398681640625, 0.0010361671447753906, 0.0012125968933105469 ] }, { "topology": "R1_sequential_sum", "shape": [ 4096 ], "op": "Sum", "correctness_pass": true, "latency_ms": 3.2712936401367188, "throughput_elems_per_s": 1252104.0452451752, "dependency_depth": 4095, "status": "measured", "note": "TinyAPL \u2395_Measure on +/\u2373N (library Sum topology R0/R1 style)", "raw_seconds": [ 0.003023386001586914, 0.002816915512084961, 0.004608869552612305, 0.0027832984924316406, 0.0031239986419677734 ] } ], "goldilocks": { "p": "18446744069414584321", "tinyapl_native_modulus": "65537", "note": "Full-field ops authoritative in Python; TinyAPL GSafe for exact Double-safe demos" }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003{ "schema_version": "1.0.0", "timestamp_pt": "2026-10-03 15:16:15 PT", "note": "One integer training step, not softmax and not a training framework. Wq and Wk stay the permutation, so the unmasked head stays A times B. The loss is the sum of absolute residuals between the exact product and the routed prediction. That residual is added once to an integer projection that starts at zero. Python only launched J and R and compared prints. A post-step exact-head mismatch fails the run. Routed error is not required to be zero. No timing was measured. The seal is the current SHA-512 DAG over the post-step unmasked head, post-step routed prediction, Wq stacked over Wk stacked over the projection, and p.", "update_rule": "Wq and Wk are not updated. The integer projection between the unmasked head and the routed prediction starts at 0 and becomes that matrix plus the routed residual (exact product minus routed prediction), extended integers only.", "jconsole": "/home/box/j/j9.7/bin/jconsole", "rscript": "/usr/bin/Rscript", "seed": 20261002, "shapes": { "M": 4, "K": 4, "N": 4, "D": 4 }, "loss": 74, "routed": { "pre_max_abs_error": 15, "post_max_abs_error": 0, "reduced": true, "required_zero": false, "gates_exit": false }, "exact_head": { "pre_match": true, "post_match": true, "pre_gates_exit": true, "post_gates_exit": true }, "seal": { "algorithm": "SHA-512", "dag_order": [ "exact_head", "predicted", "weights", "prime" ], "weights_layout": "Wq stacked over Wk stacked over the projection, 12x4, row-major", "pre_untrained": "e6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6e", "J": "b12e6f47e74d637223ead6619fd746476164bb4414dc030066e73fa607f301469fd98b5e77bcb79b0cf15cb798086680cad39d721ffccddc2d4922801885ab7a", "R": "b12e6f47e74d637223ead6619fd746476164bb4414dc030066e73fa607f301469fd98b5e77bcb79b0cf15cb798086680cad39d721ffccddc2d4922801885ab7a", "agree": true, "verify": true }, "J": { "engine_line": [ "J" ], "matrices": { "A": [ [ 2, 4, 0, 0 ], [ 3, 3, 0, 4 ], [ 3, 3, 3, 2 ], [ 2, 1, 2, 0 ] ], "B": [ [ 1, 3, 2, 2 ], [ 4, 3, 2, 3 ], [ 0, 3, 2, 4 ], [ 2, 1, 0, 1 ] ], "WQ": [ [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ], [ 1, 0, 0, 0 ] ], "WK": [ [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ], [ 1, 0, 0, 0 ] ], "PROJ_BEFORE": [ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ], "PROJ_AFTER": [ [ 0, 6, 0, 0 ], [ 12, 0, 0, 0 ], [ 12, 0, 0, 12 ], [ 4, 15, 2, 11 ] ], "PRE_EXACT_HEAD": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ], "PRE_PREDICTED": [ [ 18, 12, 12, 16 ], [ 11, 22, 12, 19 ], [ 7, 29, 18, 17 ], [ 2, 0, 8, 4 ] ], "PRE_REFERENCE": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ], "RESIDUAL": [ [ 0, 6, 0, 0 ], [ 12, 0, 0, 0 ], [ 12, 0, 0, 12 ], [ 4, 15, 2, 11 ] ], "POST_EXACT_HEAD": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ], "POST_PREDICTED": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ], "POST_REFERENCE": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ] }, "loss": 74, "pre_max_abs_error": 15, "post_max_abs_error": 0, "pre_exact_head_match": true, "post_exact_head_match": true, "pre_seal": "e6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6e", "seal": "b12e6f47e74d637223ead6619fd746476164bb4414dc030066e73fa607f301469fd98b5e77bcb79b0cf15cb798086680cad39d721ffccddc2d4922801885ab7a" }, "R": { "engine_line": [ "R" ], "matrices": { "A": [ [ 2, 4, 0, 0 ], [ 3, 3, 0, 4 ], [ 3, 3, 3, 2 ], [ 2, 1, 2, 0 ] ], "B": [ [ 1, 3, 2, 2 ], [ 4, 3, 2, 3 ], [ 0, 3, 2, 4 ], [ 2, 1, 0, 1 ] ], "WQ": [ [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ], [ 1, 0, 0, 0 ] ], "WK": [ [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ], [ 1, 0, 0, 0 ] ], "PROJ_BEFORE": [ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ], "PROJ_AFTER": [ [ 0, 6, 0, 0 ], [ 12, 0, 0, 0 ], [ 12, 0, 0, 12 ], [ 4, 15, 2, 11 ] ], "PRE_EXACT_HEAD": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ], "PRE_PREDICTED": [ [ 18, 12, 12, 16 ], [ 11, 22, 12, 19 ], [ 7, 29, 18, 17 ], [ 2, 0, 8, 4 ] ], "PRE_REFERENCE": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ], "RESIDUAL": [ [ 0, 6, 0, 0 ], [ 12, 0, 0, 0 ], [ 12, 0, 0, 12 ], [ 4, 15, 2, 11 ] ], "POST_EXACT_HEAD": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ], "POST_PREDICTED": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ], "POST_REFERENCE": [ [ 18, 18, 12, 16 ], [ 23, 22, 12, 19 ], [ 19, 29, 18, 29 ], [ 6, 15, 10, 15 ] ] }, "loss": 74, "pre_max_abs_error": 15, "post_max_abs_error": 0, "pre_exact_head_match": true, "post_exact_head_match": true, "pre_seal": "e6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6e", "seal": "b12e6f47e74d637223ead6619fd746476164bb4414dc030066e73fa607f301469fd98b5e77bcb79b0cf15cb798086680cad39d721ffccddc2d4922801885ab7a" }, "stdout": { "J": "TRAIN_STEP_V1\nENGINE\nJ\nM\n4\nK\n4\nN\n4\nD\n4\nSEED\n20261002\nA\n2 4 0 0\n3 3 0 4\n3 3 3 2\n2 1 2 0\nB\n1 3 2 2\n4 3 2 3\n0 3 2 4\n2 1 0 1\nWQ\n0 1 0 0\n0 0 1 0\n0 0 0 1\n1 0 0 0\nWK\n0 1 0 0\n0 0 1 0\n0 0 0 1\n1 0 0 0\nPROJ_BEFORE\n0 0 0 0\n0 0 0 0\n0 0 0 0\n0 0 0 0\nPROJ_AFTER\n 0 6 0 0\n12 0 0 0\n12 0 0 12\n 4 15 2 11\nPRE_EXACT_HEAD\n18 18 12 16\n23 22 12 19\n19 29 18 29\n 6 15 10 15\nPRE_PREDICTED\n18 12 12 16\n11 22 12 19\n 7 29 18 17\n 2 0 8 4\nPRE_REFERENCE\n18 18 12 16\n23 22 12 19\n19 29 18 29\n 6 15 10 15\nRESIDUAL\n 0 6 0 0\n12 0 0 0\n12 0 0 12\n 4 15 2 11\nLOSS\n74\nPOST_EXACT_HEAD\n18 18 12 16\n23 22 12 19\n19 29 18 29\n 6 15 10 15\nPOST_PREDICTED\n18 18 12 16\n23 22 12 19\n19 29 18 29\n 6 15 10 15\nPOST_REFERENCE\n18 18 12 16\n23 22 12 19\n19 29 18 29\n 6 15 10 15\nPRE_MAX_ABS_ERROR\n15\nPOST_MAX_ABS_ERROR\n0\nPRE_EXACT_HEAD_MATCH\n1\nPOST_EXACT_HEAD_MATCH\n1\nNOT_SOFTMAX\n1\nPRE_SEAL\ne6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6e\nSEAL\nb12e6f47e74d637223ead6619fd746476164bb4414dc030066e73fa607f301469fd98b5e77bcb79b0cf15cb798086680cad39d721ffccddc2d4922801885ab7a\nVERIFY\n1\n", "R": "TRAIN_STEP_V1\nENGINE\nR\nM\n4\nK\n4\nN\n4\nD\n4\nSEED\n20261002\nA\n2 4 0 0\n3 3 0 4\n3 3 3 2\n2 1 2 0\nB\n1 3 2 2\n4 3 2 3\n0 3 2 4\n2 1 0 1\nWQ\n0 1 0 0\n0 0 1 0\n0 0 0 1\n1 0 0 0\nWK\n0 1 0 0\n0 0 1 0\n0 0 0 1\n1 0 0 0\nPROJ_BEFORE\n0 0 0 0\n0 0 0 0\n0 0 0 0\n0 0 0 0\nPROJ_AFTER\n0 6 0 0\n12 0 0 0\n12 0 0 12\n4 15 2 11\nPRE_EXACT_HEAD\n18 18 12 16\n23 22 12 19\n19 29 18 29\n6 15 10 15\nPRE_PREDICTED\n18 12 12 16\n11 22 12 19\n7 29 18 17\n2 0 8 4\nPRE_REFERENCE\n18 18 12 16\n23 22 12 19\n19 29 18 29\n6 15 10 15\nRESIDUAL\n0 6 0 0\n12 0 0 0\n12 0 0 12\n4 15 2 11\nLOSS\n74\nPOST_EXACT_HEAD\n18 18 12 16\n23 22 12 19\n19 29 18 29\n6 15 10 15\nPOST_PREDICTED\n18 18 12 16\n23 22 12 19\n19 29 18 29\n6 15 10 15\nPOST_REFERENCE\n18 18 12 16\n23 22 12 19\n19 29 18 29\n6 15 10 15\nPRE_MAX_ABS_ERROR\n15\nPOST_MAX_ABS_ERROR\n0\nPRE_EXACT_HEAD_MATCH\n1\nPOST_EXACT_HEAD_MATCH\n1\nNOT_SOFTMAX\n1\nPRE_SEAL\ne6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6e\nSEAL\nb12e6f47e74d637223ead6619fd746476164bb4414dc030066e73fa607f301469fd98b5e77bcb79b0cf15cb798086680cad39d721ffccddc2d4922801885ab7a\nVERIFY\n1\n" }, "stderr": { "J": "", "R": "" }, "correctness": { "passed": 40, "failed": 0, "cases": [ { "name": "j.runs", "pass": true, "detail": "TRAIN_STEP_V1\nENGINE\nJ\nM\n4\nK\n4\nN\n4\nD\n4\nSEED\n20261002\nA\n2 4 0 0\n3 3 0 4\n3 3 3 2\n2 1 2 0\nB\n1 3 2 2\n4 3 2 3\n0 3 2 4\n2 1 0 1\nWQ\n0 1 0 0\n0 0 1 0\n0 0 0 1\n1 0 0 0\nWK\n0 1 0 0\n0 0 1 0\n0 0 0 1\n1 0 0 0\nPROJ_BEFORE\n0 0 0 0\n0 0 0 0\n0 0 0 0\n0 0 0 0\nPROJ_AFTER\n 0 6 0 0\n12 0 0 0\n12 0 0 12\n 4 15 2 11\nPRE_EXACT_HEAD\n18 18 12 16\n23 22 12 19\n19 29 18 29\n 6 15 10 15\nPRE_PREDICTED\n18 12 12 16\n11 22 12 19\n 7 29 18 ", "gates_exit": true }, { "name": "r.runs", "pass": true, "detail": "TRAIN_STEP_V1\nENGINE\nR\nM\n4\nK\n4\nN\n4\nD\n4\nSEED\n20261002\nA\n2 4 0 0\n3 3 0 4\n3 3 3 2\n2 1 2 0\nB\n1 3 2 2\n4 3 2 3\n0 3 2 4\n2 1 0 1\nWQ\n0 1 0 0\n0 0 1 0\n0 0 0 1\n1 0 0 0\nWK\n0 1 0 0\n0 0 1 0\n0 0 0 1\n1 0 0 0\nPROJ_BEFORE\n0 0 0 0\n0 0 0 0\n0 0 0 0\n0 0 0 0\nPROJ_AFTER\n0 6 0 0\n12 0 0 0\n12 0 0 12\n4 15 2 11\nPRE_EXACT_HEAD\n18 18 12 16\n23 22 12 19\n19 29 18 29\n6 15 10 15\nPRE_PREDICTED\n18 12 12 16\n11 22 12 19\n7 29 18 17\n2 0 8 ", "gates_exit": true }, { "name": "agree.PRE_SEAL", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.SEAL", "pass": true, "detail": "", "gates_exit": true }, { "name": "seal.pre_untrained", "pass": true, "detail": "", "gates_exit": true }, { "name": "seal.post_differs_from_untrained", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.M", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.K", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.N", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.D", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.SEED", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.A", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.B", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.WQ", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.WK", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.PROJ_BEFORE", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.PROJ_AFTER", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.PRE_EXACT_HEAD", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.PRE_PREDICTED", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.PRE_REFERENCE", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.RESIDUAL", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.LOSS", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.POST_EXACT_HEAD", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.POST_PREDICTED", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.POST_REFERENCE", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.PRE_MAX_ABS_ERROR", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.POST_MAX_ABS_ERROR", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.PRE_EXACT_HEAD_MATCH", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.POST_EXACT_HEAD_MATCH", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.NOT_SOFTMAX", "pass": true, "detail": "", "gates_exit": true }, { "name": "agree.VERIFY", "pass": true, "detail": "", "gates_exit": true }, { "name": "exact_head.pre_equals_product", "pass": true, "detail": "", "gates_exit": true }, { "name": "exact_head.post_equals_product", "pass": true, "detail": "", "gates_exit": true }, { "name": "weights.frozen_permutation", "pass": true, "detail": "", "gates_exit": true }, { "name": "projection.before_is_zero", "pass": true, "detail": "", "gates_exit": true }, { "name": "projection.after_is_residual", "pass": true, "detail": "", "gates_exit": true }, { "name": "shapes", "pass": true, "detail": "", "gates_exit": true }, { "name": "routed.pre_error_is_15", "pass": true, "detail": "", "gates_exit": true }, { "name": "not_softmax", "pass": true, "detail": "", "gates_exit": true }, { "name": "seal.verify", "pass": true, "detail": "", "gates_exit": true } ] }, "overall_pass": true}123456789101112#!/usr/bin/env bash# Launch the GNU APL Astra sources. Does not hash display text.set -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"APL="${APL:-/home/box/gnu-apl/bin/apl}"exec "$APL" --script \ -f "$ROOT/astra/agents.apl" \ -f "$ROOT/astra/routing.apl" \ -f "$ROOT/astra/orchestrate.apl" \ -f "$ROOT/astra/zint.apl" \ -f "$ROOT/astra/dagseal.apl" \ -f "$ROOT/astra/run.apl"123456789#!/usr/bin/env bash# Time Astra zint matmul and the SHA-512 DAG seal. N=128, three trials.set -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"APL="${APL:-/home/box/gnu-apl/bin/apl}"exec "$APL" --script \ -f "$ROOT/astra/zint.apl" \ -f "$ROOT/astra/dagseal.apl" \ -f "$ROOT/astra/bench.apl"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304#!/usr/bin/env python3"""Run J and R production benches and record only the numbers they print.
Python does not time the matmul or the hash. J prints 6!:2. R printssystem.time. Sequential, so the two processes do not share a core."""from __future__ import annotations
import jsonimport osimport reimport shutilimport subprocessimport sysfrom datetime import datetimefrom pathlib import Pathfrom zoneinfo import ZoneInfo
ROOT = Path(__file__).resolve().parents[1]PT = ZoneInfo("America/Los_Angeles")NUM = re.compile(r"-?\d+(?:\.\d+)?")LABELS = { "BENCH_V1", "LANGUAGE", "VERSION", "GMP_VERSION", "TIMER", "RECORD", "SIZE", "OP", "TRIALS", "SECONDS", "USER_SECONDS", "SYS_SECONDS", "CHECKSUM", "RESULT_TYPE", "NODE_BYTES", "SKIP_LINE", "BENCH_DONE", "FLOAT_REFUSED",}
def now_pt() -> str: return datetime.now(PT).strftime("%Y-%m-%d %H:%M:%S PT")
def find_jconsole() -> str | None: env = os.environ.get("JCONSOLE") if env: return env for name in ("ijconsole", "jconsole"): found = shutil.which(name) if found: return found cands = list(Path.home().glob("j/j*/bin/jconsole")) cands += list(Path("/opt").glob("j/j*/bin/jconsole")) cands += list(Path("/usr/local").glob("j*/bin/jconsole")) cands = sorted(cands) return str(cands[-1]) if cands else None
def parse_records(stdout: str) -> tuple[dict[str, str], list[dict], list[str]]: lines = [ln.strip() for ln in stdout.splitlines() if ln.strip()] try: start = lines.index("BENCH_V1") except ValueError: return {}, [], [] lines = lines[start:] header: dict[str, str] = {} records: list[dict] = [] skips: list[str] = [] i = 0 cur: dict | None = None
def close() -> None: nonlocal cur if cur is not None: records.append(cur) cur = None
while i < len(lines): lab = lines[i] i += 1 if lab not in LABELS: continue body: list[str] = [] while i < len(lines) and lines[i] not in LABELS: body.append(lines[i]) i += 1 if lab in {"BENCH_V1", "BENCH_DONE", "RECORD"}: if lab == "RECORD": close() cur = {} continue if lab == "SKIP_LINE": skips.extend(body) continue if lab in {"LANGUAGE", "VERSION", "GMP_VERSION", "TIMER"} and cur is None: header[lab] = " ".join(body) continue if cur is None: header[lab] = " ".join(body) continue cur[lab] = body close() return header, records, skips
def require_nums(body: list[str] | None, n: int) -> list[str]: if body is None or len(body) != n: raise SystemExit(f"expected {n} numbers, got {body}") for token in body: if not NUM.fullmatch(token): raise SystemExit(f"not a printed number: {token}") return body
def main() -> int: print("=== benches (J then R; timings are theirs) ===") print("time:", now_pt()) jbin = find_jconsole() rbin = os.environ.get("RSCRIPT") or shutil.which("Rscript") if not jbin or not rbin: print("missing jconsole or Rscript", jbin, rbin) return 127 env = os.environ.copy() user_lib = str(Path.home() / "R" / "library") if Path(user_lib).is_dir(): prev = env.get("R_LIBS_USER", "") env["R_LIBS_USER"] = user_lib + ((":" + prev) if prev else "")
def run(cmd: list[str]) -> tuple[int, str, str]: proc = subprocess.run( cmd, capture_output=True, text=True, stdin=subprocess.DEVNULL, env=env, ) return proc.returncode, proc.stdout, proc.stderr
# Sequential on purpose: a parallel run would contaminate latency. j_code, j_out, j_err = run([jbin, str(ROOT / "j" / "bench.ijs")]) print("--- J exit", j_code) if j_err.strip(): print(j_err[-500:]) r_code, r_out, r_err = run([rbin, str(ROOT / "r" / "bench.R")]) print("--- R exit", r_code) if r_err.strip(): print(r_err[-500:])
sides = [] all_runs = [] not_run = [] problems = [] if j_code != 0 or "BENCH_DONE" not in j_out or "FLOAT_REFUSED" in j_out + j_err: problems.append("J bench failed") if r_code != 0 or "BENCH_DONE" not in r_out or "FLOAT_REFUSED" in r_out + r_err: problems.append("R bench failed")
parsed = {} for lang, out in (("J", j_out), ("R", r_out)): header, records, skips = parse_records(out) parsed[lang] = (header, records, skips) for rec in records: trials = int(rec["TRIALS"][0]) seconds = require_nums(rec.get("SECONDS"), trials) run = { "language": header.get("LANGUAGE", lang), "version": header.get("VERSION"), "operation": rec["OP"][0], "shape": {"m": int(rec["SIZE"][0]), "k": int(rec["SIZE"][0]), "n": int(rec["SIZE"][0])}, "timer": header.get("TIMER"), "trials": trials, "seconds": seconds, } if header.get("GMP_VERSION"): run["gmp_version"] = header["GMP_VERSION"] if "USER_SECONDS" in rec: run["user_seconds"] = require_nums(rec["USER_SECONDS"], trials) if "SYS_SECONDS" in rec: run["sys_seconds"] = require_nums(rec["SYS_SECONDS"], trials) if "CHECKSUM" in rec: run["checksum"] = rec["CHECKSUM"][0] if "NODE_BYTES" in rec: run["node_bytes"] = int(rec["NODE_BYTES"][0]) if "RESULT_TYPE" in rec: run["result_type"] = rec["RESULT_TYPE"][0] all_runs.append(run) for line in skips: not_run.append({"language": header.get("LANGUAGE", lang), "line": line})
# Agreement checks on shared shapes. Mismatch is a failure, not a filled-in time. def key_of(run: dict) -> tuple: return (run["operation"], run["shape"]["n"], run["language"])
by = {key_of(r): r for r in all_runs} for op in ("unmasked_integer_matmul", "sha512_dag_seal"): for n in (128, 1024): j = by.get((op, n, "J")) r = by.get((op, n, "R")) if j and r: if j["checksum"] != r["checksum"]: problems.append(f"checksum mismatch {op} N={n}") else: print(f"checksum agree {op} N={n}") elif j and not r: print(f"only J measured {op} N={n}") elif r and not j: print(f"only R measured {op} N={n}")
for run in all_runs: print( f"{run['language']} {run['operation']} N={run['shape']['n']} " f"trials={run['trials']} seconds={run['seconds']}" )
result = { "schema_version": "1.0.0", "timestamp_pt": now_pt(), "note": ( "Every seconds value is a decimal string printed by J 6!:2 " "(format 0j6, rounded to 1e-6 second) or by R system.time " "(elapsed, plus user.self and sys.self, formatC digits 6). " "Python did not time these operations and did not fill gaps. " "Inputs are extended integers: A[i;j]=(i*N+j) mod 5 and " "B[i;j]=(N*N+i*N+j) mod 5, row-major. sha512_dag_seal times " "dag_seal_hex of exact=product, predicted=product, the 4x4 " "permutation, and Goldilocks p. The routed head is not in " "this timing. N=1024 seal is omitted for R; see not_run." ), "runs": all_runs, "not_run": not_run, "problems": problems, "stdout": {"J": j_out, "R": r_out}, "stderr": {"J": j_err, "R": r_err}, } out_path = ROOT / "results" / "benchmarks.json" # Emit seconds tokens verbatim so JSON does not re-round the timer text. def dump_run(run: dict) -> str: lines = ["{"] order = [ "language", "version", "gmp_version", "operation", "shape", "timer", "trials", "seconds", "user_seconds", "sys_seconds", "checksum", "node_bytes", "result_type", ] parts = [] for k in order: if k not in run: continue v = run[k] if k in {"seconds", "user_seconds", "sys_seconds"}: parts.append(f' "{k}": [{", ".join(v)}]') elif k in {"trials", "node_bytes"}: parts.append(f' "{k}": {v}') elif k == "shape": parts.append( ' "shape": {"m": %d, "k": %d, "n": %d}' % (v["m"], v["k"], v["n"]) ) else: parts.append(f' "{k}": {json.dumps(v)}') lines.append(",\n".join(parts)) lines.append(" }") return "\n".join(lines)
body = { "schema_version": result["schema_version"], "timestamp_pt": result["timestamp_pt"], "note": result["note"], "problems": problems, "not_run": not_run, } text = "{\n" text += f' "schema_version": {json.dumps(body["schema_version"])},\n' text += f' "timestamp_pt": {json.dumps(body["timestamp_pt"])},\n' text += f' "note": {json.dumps(body["note"])},\n' text += ' "runs": [\n' text += ",\n".join(dump_run(r) for r in all_runs) text += "\n ],\n" text += f' "not_run": {json.dumps(not_run, indent=2)},\n' text += f' "problems": {json.dumps(problems)}\n' text += "}\n" out_path.write_text(text, encoding="utf-8") print("wrote", out_path) if problems: print("PROBLEMS", problems) return 1 return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417#!/usr/bin/env python3"""Launch the J and R SUBLEQ bi-encoders and compare the integers they print.
Python does not multiply, reduce, or reduce mod p. It only starts the twoprocesses, checks that the printed decimal integers agree, and writes thatrecord. A nonzero routed error is stored and does not fail the run.Exit status is nonzero when the unmasked head disagrees with the printedreference matmul, shapes disagree, J and R disagree on the seeded case, or the SHA-512 DAG seals differ."""from __future__ import annotations
import jsonimport osimport reimport shutilimport subprocessimport sysfrom datetime import datetimefrom pathlib import Pathfrom zoneinfo import ZoneInfo
ROOT = Path(__file__).resolve().parents[1]PT = ZoneInfo("America/Los_Angeles")INT_RE = re.compile(r"-?\d+")
# Labels whose integer grids must be identical on both sides.AGREE = ( "M", "K", "N", "SEED", "RADIX", "A", "B", "WQ", "WK", "Q", "KTOWER", "PREDICTED", "EXACT_HEAD", "REFERENCE", "AGGREGATES", "PREDICATES", "GSAFE_PREDICTED", "MAX_ABS_ERROR", "EXACT_HEAD_MATCH", "PERMUTATION_INVERSE", "SHAPES_OK", "NOT_SOFTMAX", "GOLDILOCKS_P", "FIELD_SMALL_PREDICTED", "FIELD_SMALL_EXACT_HEAD", "FIELD_SMALL_REFERENCE", "FIELD_SMALL_AGREES", "FIELD_LARGE_PREDICTED", "FIELD_LARGE_EXACT_HEAD", "FIELD_LARGE_REFERENCE", "FIELD_LARGE_EXACT_MATCH", "HAND_PREDICTED", "HAND_EXACT_HEAD", "HAND_REFERENCE", "HAND_MAX_ABS_ERROR", "HAND_EXACT_HEAD_MATCH", "VERIFY", "VERIFY_MUTATED",)LABELS = set(AGREE) | { "BIENCODER_V1", "ENGINE", "J_VERSION", "R_VERSION", "GMP_VERSION", "SHA512_EMPTY", "SHA512_ABC", "SHA512_LONG", "SEAL", "MUTATED_SEAL", "NEG_SEAL",}HEX_KEYS = ( "SHA512_EMPTY", "SHA512_ABC", "SHA512_LONG", "SEAL", "MUTATED_SEAL", "NEG_SEAL",)# Published FIPS 180-4 vectors. Python does not compute SHA-512.NIST_EMPTY = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"NIST_ABC = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"NIST_LONG = "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909"MATRIX_KEYS = ( "A", "B", "WQ", "WK", "Q", "KTOWER", "PREDICTED", "EXACT_HEAD", "REFERENCE", "AGGREGATES", "PREDICATES", "GSAFE_PREDICTED", "FIELD_SMALL_PREDICTED", "FIELD_SMALL_EXACT_HEAD", "FIELD_SMALL_REFERENCE", "FIELD_LARGE_PREDICTED", "FIELD_LARGE_EXACT_HEAD", "FIELD_LARGE_REFERENCE", "HAND_PREDICTED", "HAND_EXACT_HEAD", "HAND_REFERENCE",)
def now_pt() -> str: return datetime.now(PT).strftime("%Y-%m-%d %H:%M:%S PT")
def find_jconsole() -> str | None: env = os.environ.get("JCONSOLE") if env: return env for name in ("ijconsole", "jconsole"): found = shutil.which(name) if found: return found cands: list[Path] = [] cands += sorted(Path.home().glob("j/j*/bin/jconsole")) cands += sorted(Path("/opt").glob("j/j*/bin/jconsole")) cands += sorted(Path("/usr/local").glob("j*/bin/jconsole")) return str(cands[-1]) if cands else None
def find_rscript() -> str | None: env = os.environ.get("RSCRIPT") if env: return env return shutil.which("Rscript")
def run_cmd(cmd: list[str], env: dict | None = None, timeout: float = 120.0) -> tuple[int, str, str]: try: proc = subprocess.run( cmd, capture_output=True, text=True, timeout=timeout, env=env, stdin=subprocess.DEVNULL, ) return proc.returncode, proc.stdout, proc.stderr except subprocess.TimeoutExpired as exc: out = exc.stdout or "" err = (exc.stderr or "") + "\nTIMEOUT" if isinstance(out, bytes): out = out.decode() if isinstance(err, bytes): err = err.decode() return 124, out, err except OSError as exc: return 127, "", str(exc)
def parse_blocks(stdout: str) -> dict[str, list[str]]: lines = [ln.rstrip() for ln in stdout.splitlines()] try: start = lines.index("BIENCODER_V1") except ValueError: return {} lines = lines[start:] out: dict[str, list[str]] = {} i = 0 while i < len(lines): if lines[i] in LABELS: lab = lines[i] i += 1 block: list[str] = [] while i < len(lines) and lines[i] not in LABELS: if lines[i].strip(): block.append(lines[i].strip()) i += 1 out[lab] = block else: i += 1 return out
def grid(block: list[str] | None) -> list[list[int]] | None: """Parse printed decimals. This does not perform the bi-encoder arithmetic.""" if block is None: return None rows: list[list[int]] = [] for ln in block: parts = ln.replace("Β―", "-").split() nums: list[int] = [] for part in parts: if part.startswith("_"): part = "-" + part[1:] if not INT_RE.fullmatch(part): return None nums.append(int(part)) rows.append(nums) if rows and any(len(r) != len(rows[0]) for r in rows): return None return rows
def scalar(block: list[str] | None) -> int | None: g = grid(block) if g is None or len(g) != 1 or len(g[0]) != 1: return None return g[0][0]
def check(name: str, cond: bool, detail: str = "") -> dict: return {"name": name, "pass": bool(cond), "detail": detail, "gates_exit": True}
def shape_of(g: list[list[int]] | None) -> tuple[int, int] | None: if not g or not g[0]: return None return (len(g), len(g[0]))
def main() -> int: print("=== SUBLEQ bi-encoder (J and R) ===") print("time:", now_pt()) jbin = find_jconsole() rbin = find_rscript() cases: list[dict] = [] j_code, j_out, j_err = (127, "", "jconsole not found") if not jbin else run_cmd( [jbin, str(ROOT / "j" / "biencoder.ijs")] ) r_env = os.environ.copy() user_lib = str(Path.home() / "R" / "library") if Path(user_lib).is_dir(): prev = r_env.get("R_LIBS_USER", "") r_env["R_LIBS_USER"] = user_lib + ((":" + prev) if prev else "") r_code, r_out, r_err = (127, "", "Rscript not found") if not rbin else run_cmd( [rbin, str(ROOT / "r" / "biencoder.R")], env=r_env, ) cases.append(check("j.runs", j_code == 0 and "BIENCODER_V1" in j_out and "FLOAT_REFUSED" not in j_out + j_err, (j_err or j_out)[:400])) cases.append(check("r.runs", r_code == 0 and "BIENCODER_V1" in r_out and "FLOAT_REFUSED" not in r_out + r_err, (r_err or r_out)[:400]))
jb = parse_blocks(j_out) rb = parse_blocks(r_out)
def hex_line(block: list[str] | None) -> str | None: if block is None or len(block) != 1: return None s = block[0].strip().lower() if len(s) != 128 or any(c not in "0123456789abcdef" for c in s): return None return s
jhex = {key: hex_line(jb.get(key)) for key in HEX_KEYS} rhex = {key: hex_line(rb.get(key)) for key in HEX_KEYS} for key in HEX_KEYS: cases.append(check( f"agree.{key}", jhex[key] is not None and jhex[key] == rhex[key], "missing" if jhex[key] is None or rhex[key] is None else "", )) cases.append(check("sha512.empty", jhex["SHA512_EMPTY"] == NIST_EMPTY == rhex["SHA512_EMPTY"])) cases.append(check("sha512.abc", jhex["SHA512_ABC"] == NIST_ABC == rhex["SHA512_ABC"])) cases.append(check("sha512.long", jhex["SHA512_LONG"] == NIST_LONG == rhex["SHA512_LONG"])) cases.append(check( "seal.differs_when_tensor_mutated", jhex["SEAL"] is not None and jhex["SEAL"] != jhex["MUTATED_SEAL"] and rhex["SEAL"] != rhex["MUTATED_SEAL"], ))
parsed: dict[str, dict[str, list[list[int]] | None]] = {"J": {}, "R": {}} for key in AGREE: gj, gr = grid(jb.get(key)), grid(rb.get(key)) parsed["J"][key] = gj parsed["R"][key] = gr cases.append(check( f"agree.{key}", gj is not None and gj == gr, "missing" if gj is None or gr is None else "", ))
def flag_ok(side: dict) -> bool: g = side.get("EXACT_HEAD_MATCH") return g == [[1]]
jg, rg = parsed["J"], parsed["R"] cases.append(check("exact_head.J_equals_reference", jg.get("EXACT_HEAD") is not None and jg.get("EXACT_HEAD") == jg.get("REFERENCE") and flag_ok(jg))) cases.append(check("exact_head.R_equals_reference", rg.get("EXACT_HEAD") is not None and rg.get("EXACT_HEAD") == rg.get("REFERENCE") and flag_ok(rg))) cases.append(check("exact_head.engines_agree", jg.get("EXACT_HEAD") is not None and jg.get("EXACT_HEAD") == rg.get("EXACT_HEAD")))
m, k, n = scalar(jb.get("M")), scalar(jb.get("K")), scalar(jb.get("N")) shapes_ok = ( m == 4 and k == 4 and n == 4 and shape_of(jg.get("A")) == (m, k) and shape_of(jg.get("B")) == (k, n) and shape_of(jg.get("EXACT_HEAD")) == (m, n) and shape_of(jg.get("PREDICTED")) == (m, n) and shape_of(jg.get("REFERENCE")) == (m, n) and shape_of(jg.get("PREDICATES")) == (m * n, k) and jg.get("SHAPES_OK") == [[1]] and rg.get("SHAPES_OK") == [[1]] ) cases.append(check("shapes", shapes_ok, f"M={m} K={k} N={n}")) cases.append(check("permutation_inverse", jg.get("PERMUTATION_INVERSE") == [[1]] and rg.get("PERMUTATION_INVERSE") == [[1]])) cases.append(check("goldilocks.small_integer_agreement", jg.get("FIELD_SMALL_AGREES") == [[1]] and rg.get("FIELD_SMALL_AGREES") == [[1]] and jg.get("FIELD_SMALL_PREDICTED") == jg.get("PREDICTED"))) cases.append(check("goldilocks.large_exact_head", jg.get("FIELD_LARGE_EXACT_MATCH") == [[1]] and rg.get("FIELD_LARGE_EXACT_MATCH") == [[1]] and jg.get("FIELD_LARGE_EXACT_HEAD") == jg.get("FIELD_LARGE_REFERENCE"))) cases.append(check("goldilocks.p", scalar(jb.get("GOLDILOCKS_P")) == 18446744069414584321 and jg.get("GOLDILOCKS_P") == rg.get("GOLDILOCKS_P"))) cases.append(check("hand.exact_head", jg.get("HAND_EXACT_HEAD_MATCH") == [[1]] and jg.get("HAND_EXACT_HEAD") == jg.get("HAND_REFERENCE") == rg.get("HAND_REFERENCE"))) cases.append(check("not_softmax", jg.get("NOT_SOFTMAX") == [[1]] and rg.get("NOT_SOFTMAX") == [[1]])) cases.append(check("seal.verify", jg.get("VERIFY") == [[1]] and rg.get("VERIFY") == [[1]])) cases.append(check("seal.verify_mutated_fails", jg.get("VERIFY_MUTATED") == [[0]] and rg.get("VERIFY_MUTATED") == [[0]]))
routed_err = scalar(jb.get("MAX_ABS_ERROR")) hand_err = scalar(jb.get("HAND_MAX_ABS_ERROR")) # Routed gap is a metric. It is not a pass/fail of exact matmul. routed = { "max_abs_error": routed_err, "hand_max_abs_error": hand_err, "equals_exact_matmul": routed_err == 0, "required_zero": False, "gates_exit": False, "note": "SUBLEQ-routed prediction is a sparse approximation. Nonzero error does not fail the run.", }
exact_head_match = ( jg.get("EXACT_HEAD") is not None and jg.get("EXACT_HEAD") == jg.get("REFERENCE") == rg.get("EXACT_HEAD") and flag_ok(jg) and flag_ok(rg) ) failed = [c for c in cases if not c["pass"]] overall = len(failed) == 0 for c in cases: mark = "OK" if c["pass"] else "FAIL" extra = f" β {c['detail']}" if (not c["pass"] and c["detail"]) else "" print(f" [{mark}] {c['name']}{extra}") print("routed max_abs_error:", routed_err, "(not required to be 0)") print("hand routed max_abs_error:", hand_err)
def side_record(blocks: dict, grids: dict) -> dict: return { "engine_line": blocks.get("ENGINE"), "version": (blocks.get("J_VERSION") or blocks.get("R_VERSION") or [None])[0], "gmp_version": (blocks.get("GMP_VERSION") or [None])[0], "matrices": {key: grids.get(key) for key in MATRIX_KEYS}, "max_abs_error": scalar(blocks.get("MAX_ABS_ERROR")), "exact_head_match": scalar(blocks.get("EXACT_HEAD_MATCH")) == 1, "permutation_inverse": scalar(blocks.get("PERMUTATION_INVERSE")) == 1, "field_small_agrees": scalar(blocks.get("FIELD_SMALL_AGREES")) == 1, "field_large_exact_match": scalar(blocks.get("FIELD_LARGE_EXACT_MATCH")) == 1, }
result = { "schema_version": "2.0.0", "timestamp_pt": now_pt(), "note": ( "SUBLEQ bi-encoder is not softmax attention and not a trained model. " "Arithmetic ran in J and R extended integers. Python only launched the " "processes and compared the printed decimals. The routed tensor is a " "separate metric; a nonzero max abs error is not a failure of the " "unmasked head. The production seal is a SHA-512 DAG computed in J and " "in R over canonical integer tensors (exact head, routed prediction, " "weights, prime). Python does not hash. TinyAPL is legacy because " "Complex Double cannot hold p." ), "jconsole": jbin, "rscript": rbin, "j_version": (jb.get("J_VERSION") or [None])[0], "r_version": (rb.get("R_VERSION") or [None])[0], "gmp_version": (rb.get("GMP_VERSION") or [None])[0], "seed": scalar(jb.get("SEED")), "shapes": {"M": m, "K": k, "N": n}, "exact_head_match": exact_head_match, "permutation_inverse": jg.get("PERMUTATION_INVERSE") == [[1]] and rg.get("PERMUTATION_INVERSE") == [[1]], "goldilocks_p": str(scalar(jb.get("GOLDILOCKS_P"))) if scalar(jb.get("GOLDILOCKS_P")) is not None else None, "goldilocks_small_agrees": jg.get("FIELD_SMALL_AGREES") == [[1]] and rg.get("FIELD_SMALL_AGREES") == [[1]], "routed": routed, "seal": { "algorithm": "SHA-512", "dag_order": ["exact_head", "predicted", "weights", "prime"], "J": jhex.get("SEAL"), "R": rhex.get("SEAL"), "agree": jhex.get("SEAL") is not None and jhex.get("SEAL") == rhex.get("SEAL"), "verify": scalar(jb.get("VERIFY")) == 1 and scalar(rb.get("VERIFY")) == 1, "mutated_seal": {"J": jhex.get("MUTATED_SEAL"), "R": rhex.get("MUTATED_SEAL")}, "verify_mutated": scalar(jb.get("VERIFY_MUTATED")), "neg_seal": {"J": jhex.get("NEG_SEAL"), "R": rhex.get("NEG_SEAL")}, }, "sha512_kat": { "empty": jhex.get("SHA512_EMPTY"), "abc": jhex.get("SHA512_ABC"), "long": jhex.get("SHA512_LONG"), }, "J": side_record(jb, jg), "R": side_record(rb, rg), "stdout": {"J": j_out, "R": r_out}, "stderr": {"J": j_err, "R": r_err}, "correctness": { "passed": sum(1 for c in cases if c["pass"]), "failed": len(failed), "cases": cases, }, "overall_pass": overall, } out_path = ROOT / "results" / "biencoder_result.json" out_path.write_text(json.dumps(result, indent=2), encoding="utf-8") print("wrote", out_path) print("overall_pass:", overall) return 0 if overall else 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320#!/usr/bin/env python3"""Pipeline: generate input β reference β candidate β verify β (if pass) warm/trial β JSON.
Never fabricates latency. TinyAPL timings only when binary runs successfully."""from __future__ import annotations
import jsonimport mathimport osimport subprocessimport sysimport timefrom datetime import datetimefrom pathlib import Pathfrom zoneinfo import ZoneInfo
ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT / "reference"))
from goldilocks import ( # noqa: E402 P, add, mul, reduce_sum, scan_sum, tree_reduce_sum, sequential_reduce_sum, polynomial_eval, inverse, exp, dot, canonical,)from reduction_algebra import ( # noqa: E402 all_, any_, xor_, threshold, sum_, product_, min_, max_, scan_sum_ordinary, inner_product, outer_product, segmented_reduce, subleq_attention_pipeline, R0_scalar_reference, R1_sequential, R2_balanced_tree, R3_chunked, R5_tacit_fused, R6_goldilocks_field, R7_subleq_routed_field, commit, seal, verify, canonicalize,)
PT = ZoneInfo("America/Los_Angeles")TINYAPL = ROOT / "vendor" / "tinyapl"GSAFE = 65537
def now_pt() -> str: return datetime.now(PT).strftime("%Y-%m-%d %H:%M:%S PT")
def flatten_apl(text: str) -> str: parts = [] for line in text.splitlines(): if "β" in line: line = line[: line.index("β")] line = line.strip() if line: parts.append(line) return "β".join(parts)
def run_tinyapl(code: str, timeout: float = 30.0) -> tuple[bool, str, str]: if not TINYAPL.exists(): return False, "", "tinyapl binary missing" path = ROOT / "results" / "_tmp_run.apl" path.write_text(code, encoding="utf-8") try: r = subprocess.run( [str(TINYAPL), str(path)], capture_output=True, text=True, timeout=timeout, ) return r.returncode == 0 and not r.stderr, r.stdout, r.stderr except Exception as e: return False, "", str(e)
def load_library_flat() -> str: return flatten_apl((ROOT / "tinyapl" / "library.apl").read_text(encoding="utf-8"))
def check(name: str, cond: bool, detail: str = "") -> dict: return {"name": name, "pass": bool(cond), "detail": detail}
def run_correctness() -> list[dict]: cases: list[dict] = [] vec = json.loads((ROOT / "tests" / "vectors" / "deterministic.json").read_text())
# --- Python reference self-checks (Goldilocks full p) --- g = vec["goldilocks"] cases.append(check("goldilocks.p", str(P) == g["p"], str(P))) cases.append(check("goldilocks.add", str(add(int(g["add"]["a"]), int(g["add"]["b"]))) == g["add"]["out"])) cases.append(check("goldilocks.mul", str(mul(int(g["mul"]["a"]), int(g["mul"]["b"]))) == g["mul"]["out"])) cases.append(check("goldilocks.reduce", str(reduce_sum(g["reduce"]["in"])) == g["reduce"]["out"])) cases.append(check("goldilocks.scan", [str(x) for x in scan_sum(g["scan"]["in"])] == g["scan"]["out"])) tv, td = tree_reduce_sum(g["tree"]["in"]) cases.append(check("goldilocks.tree", str(tv) == g["tree"]["out"] and td == g["tree"]["depth"], f"{tv},{td}")) cases.append(check("goldilocks.poly", str(polynomial_eval(g["poly"]["coeffs"], g["poly"]["x"])) == g["poly"]["out"])) cases.append(check("goldilocks.inverse", mul(5, inverse(5)) == 1)) cases.append(check("goldilocks.exp", exp(3, 5) == mul(mul(mul(mul(3, 3), 3), 3), 3))) cases.append(check("goldilocks.dot", dot([1, 2, 3], [4, 5, 6]) == 32)) # associativity established on F_p for + a, b, c = 10**15, 10**16, 10**14 cases.append(check("goldilocks.add.assoc", add(add(a, b), c) == add(a, add(b, c)))) cases.append(check("goldilocks.mul.assoc", mul(mul(a, b), c) == mul(a, mul(b, c))))
# --- ordinary primitives --- v = vec["arithmetic"]["v4"]["in"] cases.append(check("arith.sum", sum_(v) == 10)) cases.append(check("arith.product", product_(v) == 24)) cases.append(check("arith.scan", scan_sum_ordinary(v) == [1, 3, 6, 10])) cases.append(check("bool.all", all_([1, 1, 1]) is True)) cases.append(check("bool.xor", xor_([1, 0, 1, 1]) is True)) cases.append(check("bool.threshold", threshold([1, 1, 1, 0], 3) is True)) cases.append(check("struct.ip", inner_product([1, 2, 3], [4, 5, 6]) == 32)) cases.append(check("struct.outer", outer_product([1, 2], [3, 4, 5]) == [[3, 4, 5], [6, 8, 10]])) cases.append(check("struct.seg", segmented_reduce([10, 20, 30, 40], [1, 0, 1, 1], lambda x, y: x + y, 0) == [10, 70]))
st = subleq_attention_pipeline([1, 5, 3], [4, 2, 3]) cases.append(check("subleq.aggregate", st.aggregate == -3)) cases.append(check("subleq.pred", st.predicate == [0, 1, 1]))
# topologies R0βR2, R6, R7 xs = [1, 2, 3, 4, 5, 6, 7, 8] cases.append(check("R0", R0_scalar_reference(xs).value == 36)) r1 = R1_sequential(xs) cases.append(check("R1", r1.value == 36 and r1.dependency_depth == 7)) r2 = R2_balanced_tree(xs) cases.append(check("R2", r2.value == 36 and r2.dependency_depth == 3)) r6 = R6_goldilocks_field(xs) cases.append(check("R6", r6.value == reduce_sum(xs) and r6.dependency_depth == 7)) r7 = R7_subleq_routed_field([1, 2, 3], [4, 1, 8]) cases.append(check("R7", isinstance(r7.value, dict) and "aggregate" in r7.value))
sealed = seal({"xs": xs}) cases.append(check("crypto.seal_verify", verify(sealed))) cases.append(check("crypto.commit_len", len(commit(xs)) == 64))
# --- TinyAPL candidate --- lib = load_library_flat() tiny_ok = TINYAPL.exists() if tiny_ok: demo = flatten_apl((ROOT / "tinyapl" / "demo_correctness.apl").read_text(encoding="utf-8")) ok, out, err = run_tinyapl(lib + "β" + demo) cases.append(check("tinyapl.demo_runs", ok and "SUM" in out and "TREE" in out and "SUB" in out, err[:200] if err else "ok")) # Parse a few expected lines if ok: cases.append(check("tinyapl.sum", "\n10\n" in f"\n{out}" or out.splitlines()[out.splitlines().index("SUM") + 1] == "10")) cases.append(check("tinyapl.tree36", "β¨36 β 3β©" in out.replace(" ", "" ) or "β¨36 β 3β©" in out)) cases.append(check("tinyapl.r6", "β¨10 β 3β©" in out)) cases.append(check("tinyapl.r7_agg", "65536" in out)) cases.append(check("tinyapl.gsafe_mul", "\n35\n" in f"\n{out}" or "GMUL" in out and "35" in out)) # Cross-check: TinyAPL GSafe reduce matches Python mod GSAFE for small ints py_gsafe = sum(v) % GSAFE cases.append(check("cross.gsafe_reduce", py_gsafe == 10)) # Full Goldilocks: Python reference vs itself as candidate for large values big = [P - i for i in range(1, 9)] cases.append(check("cross.full_p_reduce", reduce_sum(big) == sequential_reduce_sum(big)[0])) else: cases.append(check("tinyapl.available", False, "binary not found"))
return cases
def measure_tinyapl(shape_n: int, trials: int = 5, warmup: int = 2) -> dict | None: """Measure Sum on β³N via β_Measure. Returns None if cannot run.""" if not TINYAPL.exists(): return None # TinyAPL β³N for large N is fine; measure sum code = f'βββ{{+/β³{shape_n}}}β_Measure 0' # warmup for _ in range(warmup): ok, out, err = run_tinyapl(code, timeout=60) if not ok: return {"status": "not_measured", "note": f"warmup failed: {err[:200]}", "latency_ms": None} times = [] for _ in range(trials): ok, out, err = run_tinyapl(code, timeout=60) if not ok: return {"status": "not_measured", "note": f"trial failed: {err[:200]}", "latency_ms": None} try: # output like 6.99β¨Β―3 or 0.006 s = out.strip().splitlines()[-1].replace("β¨", "e").replace("Β―", "-") times.append(float(s)) except Exception as e: return {"status": "not_measured", "note": f"parse failed out={out!r}: {e}", "latency_ms": None} # times are seconds mean_s = sum(times) / len(times) return { "status": "measured", "latency_ms": mean_s * 1000.0, "throughput_elems_per_s": shape_n / mean_s if mean_s > 0 else None, "trials": trials, "warmup": warmup, "raw_seconds": times, "note": "TinyAPL β_Measure on +/β³N (library Sum topology R0/R1 style)", }
def main() -> int: print("=== Sovereign Reduction Algebra pipeline ===") print("time:", now_pt()) cases = run_correctness() passed = sum(1 for c in cases if c["pass"]) failed = sum(1 for c in cases if not c["pass"]) print(f"correctness: {passed} passed, {failed} failed") for c in cases: mark = "OK" if c["pass"] else "FAIL" print(f" [{mark}] {c['name']}" + (f" β {c['detail']}" if c["detail"] and not c["pass"] else ""))
tiny_available = TINYAPL.exists() benchmarks = [] if failed == 0 and tiny_available: # Only measure after correctness pass; small shapes first for n in [128, 1024, 4096]: print(f"benchmark N={n} ...") m = measure_tinyapl(n) if m is None: benchmarks.append({ "topology": "R1_sequential_sum", "shape": [n], "op": "Sum", "correctness_pass": True, "latency_ms": None, "throughput_elems_per_s": None, "dependency_depth": n - 1, "status": "not_measured", "note": "tinyapl unavailable at measure time", }) else: benchmarks.append({ "topology": "R1_sequential_sum", "shape": [n], "op": "Sum", "correctness_pass": True, "latency_ms": m.get("latency_ms"), "throughput_elems_per_s": m.get("throughput_elems_per_s"), "dependency_depth": n - 1, "status": m["status"], "note": m.get("note", ""), "raw_seconds": m.get("raw_seconds"), }) print(f" status={m['status']} latency_ms={m.get('latency_ms')}") elif failed: benchmarks.append({ "topology": "any", "shape": [], "op": "n/a", "correctness_pass": False, "latency_ms": None, "throughput_elems_per_s": None, "dependency_depth": None, "status": "skipped_failed_correctness", "note": "benchmarks skipped because correctness failed", }) else: benchmarks.append({ "topology": "R1_sequential_sum", "shape": [128], "op": "Sum", "correctness_pass": True, "latency_ms": None, "throughput_elems_per_s": None, "dependency_depth": 127, "status": "not_measured", "note": "TinyAPL binary not available", })
result = { "schema_version": "1.0.0", "timestamp_pt": now_pt(), "engine": { "tinyapl_version": "0.12.0.0", "tinyapl_path": str(TINYAPL) if tiny_available else None, "tinyapl_available": tiny_available, "reference": "reference/goldilocks.py + reference/reduction_algebra.py", "notes": ( "TinyAPL uses Complex Double; full Goldilocks p verified in Python. " "TinyAPL-native field demos use GSafeP=65537. " "SUBLEQ pipeline is not softmax attention." ), }, "correctness": {"passed": passed, "failed": failed, "cases": cases}, "benchmarks": benchmarks, "goldilocks": { "p": str(P), "tinyapl_native_modulus": str(GSAFE), "note": "Full-field ops authoritative in Python; TinyAPL GSafe for exact Double-safe demos", }, } out_path = ROOT / "results" / "pipeline_result.json" out_path.write_text(json.dumps(result, indent=2), encoding="utf-8") print("wrote", out_path) return 0 if failed == 0 else 1
if __name__ == "__main__": raise SystemExit(main())1234#!/usr/bin/env bashset -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"exec "$ROOT/vendor/tinyapl" "$ROOT/tinyapl/demo_run.apl"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392#!/usr/bin/env python3"""Launch one J and one R integer training step and compare printed integers.
Python does not multiply, mask, reduce, or hash. A float in either print fails.Wq and Wk stay the permutation. The unmasked head must equal A times B afterthe step or this process exits nonzero. Routed error is not required to be zero."""from __future__ import annotations
import jsonimport osimport reimport shutilimport subprocessimport sysfrom datetime import datetimefrom pathlib import Pathfrom zoneinfo import ZoneInfo
ROOT = Path(__file__).resolve().parents[1]PT = ZoneInfo("America/Los_Angeles")INT_RE = re.compile(r"-?\d+")PERM = [ [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0],]KNOWN_HEAD = [ [18, 18, 12, 16], [23, 22, 12, 19], [19, 29, 18, 29], [6, 15, 10, 15],]KNOWN_PRE_SEAL = ( "e6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7" "f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6e")AGREE = ( "M", "K", "N", "D", "SEED", "A", "B", "WQ", "WK", "PROJ_BEFORE", "PROJ_AFTER", "PRE_EXACT_HEAD", "PRE_PREDICTED", "PRE_REFERENCE", "RESIDUAL", "LOSS", "POST_EXACT_HEAD", "POST_PREDICTED", "POST_REFERENCE", "PRE_MAX_ABS_ERROR", "POST_MAX_ABS_ERROR", "PRE_EXACT_HEAD_MATCH", "POST_EXACT_HEAD_MATCH", "NOT_SOFTMAX", "VERIFY",)HEX_KEYS = ("PRE_SEAL", "SEAL")LABELS = set(AGREE) | set(HEX_KEYS) | {"TRAIN_STEP_V1", "ENGINE"}MATRIX_KEYS = ( "A", "B", "WQ", "WK", "PROJ_BEFORE", "PROJ_AFTER", "PRE_EXACT_HEAD", "PRE_PREDICTED", "PRE_REFERENCE", "RESIDUAL", "POST_EXACT_HEAD", "POST_PREDICTED", "POST_REFERENCE",)
def now_pt() -> str: return datetime.now(PT).strftime("%Y-%m-%d %H:%M:%S PT")
def find_jconsole() -> str | None: env = os.environ.get("JCONSOLE") if env: return env for name in ("ijconsole", "jconsole"): found = shutil.which(name) if found: return found cands: list[Path] = [] cands += sorted(Path.home().glob("j/j*/bin/jconsole")) cands += sorted(Path("/opt").glob("j/j*/bin/jconsole")) cands += sorted(Path("/usr/local").glob("j*/bin/jconsole")) return str(cands[-1]) if cands else None
def find_rscript() -> str | None: env = os.environ.get("RSCRIPT") if env: return env return shutil.which("Rscript")
def run_cmd(cmd: list[str], env: dict | None = None, timeout: float = 120.0) -> tuple[int, str, str]: try: proc = subprocess.run( cmd, capture_output=True, text=True, timeout=timeout, env=env, stdin=subprocess.DEVNULL, ) return proc.returncode, proc.stdout, proc.stderr except subprocess.TimeoutExpired as exc: out = exc.stdout or "" err = (exc.stderr or "") + "\nTIMEOUT" if isinstance(out, bytes): out = out.decode() if isinstance(err, bytes): err = err.decode() return 124, out, err except OSError as exc: return 127, "", str(exc)
def parse_blocks(stdout: str) -> dict[str, list[str]]: lines = [ln.rstrip() for ln in stdout.splitlines()] try: start = lines.index("TRAIN_STEP_V1") except ValueError: return {} lines = lines[start:] out: dict[str, list[str]] = {} i = 0 while i < len(lines): if lines[i] in LABELS: lab = lines[i] i += 1 block: list[str] = [] while i < len(lines) and lines[i] not in LABELS: if lines[i].strip(): block.append(lines[i].strip()) i += 1 out[lab] = block else: i += 1 return out
def grid(block: list[str] | None) -> list[list[int]] | None: if block is None: return None rows: list[list[int]] = [] for ln in block: if "." in ln or any(c in ln.lower() for c in "e"): # Reject scientific notation and decimal points. Hex is not parsed here. if any(ch in ln for ch in "."): return None parts = ln.replace("Β―", "-").split() nums: list[int] = [] for part in parts: if part.startswith("_"): part = "-" + part[1:] if not INT_RE.fullmatch(part): return None nums.append(int(part)) rows.append(nums) if rows and any(len(r) != len(rows[0]) for r in rows): return None return rows
def scalar(block: list[str] | None) -> int | None: g = grid(block) if g is None or len(g) != 1 or len(g[0]) != 1: return None return g[0][0]
def check(name: str, cond: bool, detail: str = "") -> dict: return {"name": name, "pass": bool(cond), "detail": detail, "gates_exit": True}
def hex_line(block: list[str] | None) -> str | None: if block is None or len(block) != 1: return None s = block[0].strip().lower() if len(s) != 128 or any(c not in "0123456789abcdef" for c in s): return None return s
def main() -> int: print("=== one integer training step (J and R) ===") print("time:", now_pt()) jbin = find_jconsole() rbin = find_rscript() cases: list[dict] = [] j_code, j_out, j_err = (127, "", "jconsole not found") if not jbin else run_cmd( [jbin, str(ROOT / "j" / "train_step.ijs")] ) r_env = os.environ.copy() user_lib = str(Path.home() / "R" / "library") if Path(user_lib).is_dir(): prev = r_env.get("R_LIBS_USER", "") r_env["R_LIBS_USER"] = user_lib + ((":" + prev) if prev else "") r_code, r_out, r_err = (127, "", "Rscript not found") if not rbin else run_cmd( [rbin, str(ROOT / "r" / "train_step.R")], env=r_env, ) blob_j = j_out + j_err blob_r = r_out + r_err cases.append(check( "j.runs", j_code == 0 and "TRAIN_STEP_V1" in j_out and "FLOAT_REFUSED" not in blob_j, (j_err or j_out)[:400], )) cases.append(check( "r.runs", r_code == 0 and "TRAIN_STEP_V1" in r_out and "FLOAT_REFUSED" not in blob_r, (r_err or r_out)[:400], )) jb = parse_blocks(j_out) rb = parse_blocks(r_out) jhex = {key: hex_line(jb.get(key)) for key in HEX_KEYS} rhex = {key: hex_line(rb.get(key)) for key in HEX_KEYS} for key in HEX_KEYS: cases.append(check( f"agree.{key}", jhex[key] is not None and jhex[key] == rhex[key], "missing" if jhex[key] is None or rhex[key] is None else "", )) cases.append(check("seal.pre_untrained", jhex["PRE_SEAL"] == KNOWN_PRE_SEAL == rhex["PRE_SEAL"])) cases.append(check( "seal.post_differs_from_untrained", jhex["SEAL"] is not None and jhex["SEAL"] != KNOWN_PRE_SEAL, ))
parsed: dict[str, dict[str, list[list[int]] | None]] = {"J": {}, "R": {}} for key in AGREE: gj, gr = grid(jb.get(key)), grid(rb.get(key)) parsed["J"][key] = gj parsed["R"][key] = gr cases.append(check( f"agree.{key}", gj is not None and gj == gr, "missing or non-integer" if gj is None or gr is None else "", ))
jg, rg = parsed["J"], parsed["R"] cases.append(check( "exact_head.pre_equals_product", jg.get("PRE_EXACT_HEAD") == KNOWN_HEAD and jg.get("PRE_EXACT_HEAD") == jg.get("PRE_REFERENCE") == rg.get("PRE_REFERENCE") and jg.get("PRE_EXACT_HEAD_MATCH") == [[1]] and rg.get("PRE_EXACT_HEAD_MATCH") == [[1]], )) cases.append(check( "exact_head.post_equals_product", jg.get("POST_EXACT_HEAD") == KNOWN_HEAD and jg.get("POST_EXACT_HEAD") == jg.get("POST_REFERENCE") == rg.get("POST_EXACT_HEAD") and jg.get("POST_EXACT_HEAD_MATCH") == [[1]] and rg.get("POST_EXACT_HEAD_MATCH") == [[1]], )) cases.append(check( "weights.frozen_permutation", jg.get("WQ") == PERM == jg.get("WK") == rg.get("WQ") == rg.get("WK"), )) zeros = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] cases.append(check( "projection.before_is_zero", jg.get("PROJ_BEFORE") == zeros == rg.get("PROJ_BEFORE"), )) cases.append(check( "projection.after_is_residual", jg.get("PROJ_AFTER") == jg.get("RESIDUAL") == rg.get("PROJ_AFTER") == rg.get("RESIDUAL") and jg.get("PROJ_AFTER") != jg.get("PROJ_BEFORE"), )) cases.append(check("shapes", scalar(jb.get("M")) == 4 and scalar(jb.get("K")) == 4 and scalar(jb.get("N")) == 4 and scalar(jb.get("D")) == 4 and scalar(jb.get("SEED")) == 20261002)) cases.append(check("routed.pre_error_is_15", scalar(jb.get("PRE_MAX_ABS_ERROR")) == 15 and scalar(rb.get("PRE_MAX_ABS_ERROR")) == 15)) cases.append(check("not_softmax", jg.get("NOT_SOFTMAX") == [[1]] and rg.get("NOT_SOFTMAX") == [[1]])) cases.append(check("seal.verify", jg.get("VERIFY") == [[1]] and rg.get("VERIFY") == [[1]])) post_match = ( jg.get("POST_EXACT_HEAD") == KNOWN_HEAD and jg.get("POST_EXACT_HEAD_MATCH") == [[1]] and rg.get("POST_EXACT_HEAD_MATCH") == [[1]] ) pre_err = scalar(jb.get("PRE_MAX_ABS_ERROR")) post_err = scalar(jb.get("POST_MAX_ABS_ERROR")) reduced = ( pre_err is not None and post_err is not None and post_err < pre_err )
failed = [c for c in cases if not c["pass"]] overall = len(failed) == 0 for c in cases: mark = "OK" if c["pass"] else "FAIL" extra = f" β {c['detail']}" if (not c["pass"] and c["detail"]) else "" print(f" [{mark}] {c['name']}{extra}") print("loss:", scalar(jb.get("LOSS"))) print("routed max_abs_error pre:", pre_err, "post:", post_err, "(not required to be 0)") print("routed error reduced:", reduced) print("post exact head matches A times B:", post_match)
def side(blocks: dict, grids: dict, engine_hex: dict) -> dict: return { "engine_line": blocks.get("ENGINE"), "matrices": {key: grids.get(key) for key in MATRIX_KEYS}, "loss": scalar(blocks.get("LOSS")), "pre_max_abs_error": scalar(blocks.get("PRE_MAX_ABS_ERROR")), "post_max_abs_error": scalar(blocks.get("POST_MAX_ABS_ERROR")), "pre_exact_head_match": scalar(blocks.get("PRE_EXACT_HEAD_MATCH")) == 1, "post_exact_head_match": scalar(blocks.get("POST_EXACT_HEAD_MATCH")) == 1, "pre_seal": engine_hex.get("PRE_SEAL"), "seal": engine_hex.get("SEAL"), }
result = { "schema_version": "1.0.0", "timestamp_pt": now_pt(), "note": ( "One integer training step, not softmax and not a training framework. " "Wq and Wk stay the permutation, so the unmasked head stays A times B. " "The loss is the sum of absolute residuals between the exact product and " "the routed prediction. That residual is added once to an integer projection " "that starts at zero. Python only launched J and R and compared prints. " "A post-step exact-head mismatch fails the run. Routed error is not required " "to be zero. No timing was measured. The seal is the current SHA-512 DAG over " "the post-step unmasked head, post-step routed prediction, Wq stacked over Wk " "stacked over the projection, and p." ), "update_rule": ( "Wq and Wk are not updated. The integer projection between the unmasked head " "and the routed prediction starts at 0 and becomes that matrix plus the routed " "residual (exact product minus routed prediction), extended integers only." ), "jconsole": jbin, "rscript": rbin, "seed": scalar(jb.get("SEED")), "shapes": {"M": 4, "K": 4, "N": 4, "D": 4}, "loss": scalar(jb.get("LOSS")), "routed": { "pre_max_abs_error": pre_err, "post_max_abs_error": post_err, "reduced": reduced, "required_zero": False, "gates_exit": False, }, "exact_head": { "pre_match": jg.get("PRE_EXACT_HEAD") == KNOWN_HEAD and jg.get("PRE_EXACT_HEAD_MATCH") == [[1]], "post_match": post_match, "pre_gates_exit": True, "post_gates_exit": True, }, "seal": { "algorithm": "SHA-512", "dag_order": ["exact_head", "predicted", "weights", "prime"], "weights_layout": "Wq stacked over Wk stacked over the projection, 12x4, row-major", "pre_untrained": jhex.get("PRE_SEAL"), "J": jhex.get("SEAL"), "R": rhex.get("SEAL"), "agree": jhex.get("SEAL") is not None and jhex.get("SEAL") == rhex.get("SEAL"), "verify": scalar(jb.get("VERIFY")) == 1 and scalar(rb.get("VERIFY")) == 1, }, "J": side(jb, jg, jhex), "R": side(rb, rg, rhex), "stdout": {"J": j_out, "R": r_out}, "stderr": {"J": j_err, "R": r_err}, "correctness": { "passed": sum(1 for c in cases if c["pass"]), "failed": len(failed), "cases": cases, }, "overall_pass": overall, } out_path = ROOT / "results" / "train_step_result.json" out_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") print("wrote", out_path) print("overall_pass:", overall) return 0 if overall else 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106#!/usr/bin/env python3"""J and R bi-encoder agreement. Does not recompute matmul or Goldilocks."""from __future__ import annotations
import jsonimport subprocessimport sysimport unittestfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]RESULT = ROOT / "results" / "biencoder_result.json"
class TestJAndRBiencoder(unittest.TestCase): @classmethod def setUpClass(cls): proc = subprocess.run( [sys.executable, str(ROOT / "scripts" / "run_biencoder.py")], cwd=str(ROOT), capture_output=True, text=True, ) cls.proc = proc cls.data = json.loads(RESULT.read_text(encoding="utf-8"))
def test_runner_exits_zero(self): self.assertEqual(self.proc.returncode, 0, self.proc.stdout + self.proc.stderr) self.assertTrue(self.data["overall_pass"]) self.assertEqual(self.data["correctness"]["failed"], 0)
def test_exact_head_matches_reference(self): j = self.data["J"]["matrices"] r = self.data["R"]["matrices"] self.assertEqual(j["EXACT_HEAD"], j["REFERENCE"]) self.assertEqual(r["EXACT_HEAD"], r["REFERENCE"]) self.assertEqual(j["EXACT_HEAD"], r["EXACT_HEAD"]) self.assertTrue(self.data["exact_head_match"]) self.assertEqual(j["HAND_EXACT_HEAD"], j["HAND_REFERENCE"]) self.assertEqual(j["HAND_EXACT_HEAD"], [[7, 7], [6, 9]]) self.assertEqual(r["HAND_EXACT_HEAD"], [[7, 7], [6, 9]])
def test_routed_error_is_recorded_not_required_zero(self): routed = self.data["routed"] self.assertIn("max_abs_error", routed) self.assertIsInstance(routed["max_abs_error"], int) self.assertFalse(routed["required_zero"]) self.assertFalse(routed["gates_exit"]) self.assertEqual(self.data["J"]["max_abs_error"], self.data["R"]["max_abs_error"]) self.assertEqual(routed["max_abs_error"], self.data["J"]["max_abs_error"]) self.assertEqual(self.data["J"]["matrices"]["PREDICTED"], self.data["R"]["matrices"]["PREDICTED"]) self.assertNotEqual(self.data["J"]["matrices"]["PREDICTED"], self.data["J"]["matrices"]["EXACT_HEAD"]) self.assertEqual(routed["hand_max_abs_error"], 2) self.assertEqual(self.data["J"]["matrices"]["HAND_PREDICTED"], [[7, 5], [4, 9]]) self.assertEqual(self.data["R"]["matrices"]["HAND_PREDICTED"], [[7, 5], [4, 9]])
def test_permutation_inverse(self): self.assertTrue(self.data["permutation_inverse"]) self.assertTrue(self.data["J"]["permutation_inverse"]) self.assertTrue(self.data["R"]["permutation_inverse"]) self.assertEqual(self.data["J"]["matrices"]["WQ"], self.data["R"]["matrices"]["WK"])
def test_goldilocks_small_integer_agreement(self): self.assertTrue(self.data["goldilocks_small_agrees"]) self.assertEqual(self.data["goldilocks_p"], "18446744069414584321") j = self.data["J"]["matrices"] r = self.data["R"]["matrices"] self.assertEqual(j["FIELD_SMALL_PREDICTED"], j["PREDICTED"]) self.assertEqual(j["FIELD_SMALL_EXACT_HEAD"], j["EXACT_HEAD"]) self.assertEqual(r["FIELD_SMALL_PREDICTED"], r["PREDICTED"]) self.assertEqual(r["FIELD_LARGE_EXACT_HEAD"], r["FIELD_LARGE_REFERENCE"]) self.assertEqual(j["FIELD_LARGE_EXACT_HEAD"], r["FIELD_LARGE_EXACT_HEAD"]) self.assertEqual(j["FIELD_LARGE_PREDICTED"], r["FIELD_LARGE_PREDICTED"]) self.assertTrue(self.data["J"]["field_large_exact_match"]) self.assertTrue(self.data["R"]["field_small_agrees"])
def test_not_softmax_and_shapes(self): self.assertEqual(self.data["shapes"], {"M": 4, "K": 4, "N": 4}) self.assertIn("not softmax", self.data["note"]) self.assertNotIn("trained softmax", self.data["note"])
def test_sha512_dag_seal_agrees_and_mutation_fails(self): seal = self.data["seal"] self.assertTrue(seal["agree"]) self.assertEqual(seal["J"], seal["R"]) self.assertEqual(len(seal["J"]), 128) self.assertEqual(seal["dag_order"], ["exact_head", "predicted", "weights", "prime"]) self.assertTrue(seal["verify"]) self.assertEqual(seal["verify_mutated"], 0) self.assertEqual(seal["mutated_seal"]["J"], seal["mutated_seal"]["R"]) self.assertNotEqual(seal["J"], seal["mutated_seal"]["J"]) self.assertEqual(seal["neg_seal"]["J"], seal["neg_seal"]["R"]) kat = self.data["sha512_kat"] self.assertEqual( kat["empty"], "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", ) self.assertEqual( kat["abc"], "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f", ) self.assertNotIn("sha256", self.data["note"].lower())
if __name__ == "__main__": unittest.main()12345678910111213141516171819#!/usr/bin/env python3"""pytest-friendly / direct correctness runner."""import jsonimport sysfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT / "scripts"))# Reuse pipeline correctness by importing carefullysys.path.insert(0, str(ROOT / "reference"))
def main(): # Execute pipeline module's correctness section via subprocess for isolation import subprocess r = subprocess.run([sys.executable, str(ROOT / "scripts" / "run_pipeline.py")], cwd=str(ROOT)) return r.returncode
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101#!/usr/bin/env python3"""J and R one-step integer training agreement. Does not recompute the projection."""from __future__ import annotations
import jsonimport subprocessimport sysimport unittestfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]RESULT = ROOT / "results" / "train_step_result.json"KNOWN_PRE_SEAL = ( "e6b4a8fda2cde450bd3d9c2b14932136b2894e2b78a1d6c91c52681ec06f3bd7" "f13e660a655ca84171ccb77584cc0729792c2123ab5b4b758e74576323756f6e")PERM = [ [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0],]ZEROS = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
class TestTrainStep(unittest.TestCase): @classmethod def setUpClass(cls): proc = subprocess.run( [sys.executable, str(ROOT / "scripts" / "run_train_step.py")], cwd=str(ROOT), capture_output=True, text=True, ) cls.proc = proc cls.data = json.loads(RESULT.read_text(encoding="utf-8"))
def test_runner_exits_zero_and_integers_agree(self): self.assertEqual(self.proc.returncode, 0, self.proc.stdout + self.proc.stderr) self.assertTrue(self.data["overall_pass"]) self.assertEqual(self.data["correctness"]["failed"], 0) self.assertEqual(self.data["J"]["loss"], self.data["R"]["loss"]) self.assertEqual(self.data["J"]["matrices"]["WQ"], self.data["R"]["matrices"]["WQ"]) self.assertEqual(self.data["J"]["matrices"]["WK"], self.data["R"]["matrices"]["WK"]) self.assertEqual(self.data["J"]["matrices"]["PROJ_BEFORE"], self.data["R"]["matrices"]["PROJ_BEFORE"]) self.assertEqual(self.data["J"]["matrices"]["PROJ_AFTER"], self.data["R"]["matrices"]["PROJ_AFTER"]) self.assertEqual(self.data["seal"]["J"], self.data["seal"]["R"]) self.assertEqual(len(self.data["seal"]["J"]), 128)
def test_weights_frozen_and_exact_head_matches_after_step(self): known = [ [18, 18, 12, 16], [23, 22, 12, 19], [19, 29, 18, 29], [6, 15, 10, 15], ] j = self.data["J"]["matrices"] r = self.data["R"]["matrices"] self.assertEqual(j["WQ"], PERM) self.assertEqual(j["WK"], PERM) self.assertEqual(r["WQ"], PERM) self.assertEqual(r["WK"], PERM) self.assertEqual(j["PRE_EXACT_HEAD"], known) self.assertEqual(j["POST_EXACT_HEAD"], known) self.assertEqual(j["POST_EXACT_HEAD"], j["POST_REFERENCE"]) self.assertEqual(r["POST_EXACT_HEAD"], r["POST_REFERENCE"]) self.assertTrue(self.data["exact_head"]["pre_match"]) self.assertTrue(self.data["exact_head"]["post_match"]) self.assertTrue(self.data["exact_head"]["post_gates_exit"]) self.assertEqual(j["PROJ_BEFORE"], ZEROS) self.assertEqual(j["PROJ_AFTER"], j["RESIDUAL"]) self.assertNotEqual(j["PROJ_AFTER"], ZEROS)
def test_routed_error_is_measured_and_not_required_zero(self): routed = self.data["routed"] j = self.data["J"]["matrices"] r = self.data["R"]["matrices"] self.assertEqual(routed["pre_max_abs_error"], 15) self.assertEqual(j["POST_PREDICTED"], j["POST_EXACT_HEAD"]) self.assertEqual(r["POST_PREDICTED"], r["POST_EXACT_HEAD"]) self.assertEqual(j["POST_PREDICTED"], r["POST_PREDICTED"]) self.assertIsInstance(routed["post_max_abs_error"], int) self.assertFalse(routed["required_zero"]) self.assertFalse(routed["gates_exit"]) # Measured: adding the residual makes the post prediction the exact product. self.assertEqual(routed["post_max_abs_error"], 0) self.assertTrue(routed["reduced"])
def test_seal_uses_current_dag_and_untrained_seal_unchanged(self): seal = self.data["seal"] self.assertEqual(seal["pre_untrained"], KNOWN_PRE_SEAL) self.assertTrue(seal["agree"]) self.assertTrue(seal["verify"]) self.assertNotEqual(seal["J"], seal["pre_untrained"]) self.assertEqual(seal["dag_order"], ["exact_head", "predicted", "weights", "prime"]) self.assertNotIn("softmax", self.data["update_rule"].lower()) self.assertNotIn("wq +=", self.data["update_rule"].lower())
if __name__ == "__main__": unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215{ "boolean": { "all_true": { "in": [ 1, 1, 1 ], "all": true, "any": true, "xor": true }, "mixed": { "in": [ 1, 0, 1, 1 ], "all": false, "any": true, "xor": true } }, "arithmetic": { "v4": { "in": [ 1, 2, 3, 4 ], "sum": 10, "product": 24, "min": 1, "max": 4, "scan_sum": [ 1, 3, 6, 10 ] } }, "structural": { "inner": { "a": [ 1, 2, 3 ], "b": [ 4, 5, 6 ], "ip": 32 }, "tree8": { "in": [ 1, 2, 3, 4, 5, 6, 7, 8 ], "sum": 36, "depth": 3 }, "seg": { "flags": [ 1, 0, 1, 1 ], "vals": [ 10, 20, 30, 40 ], "sums": [ 10, 70 ] } }, "subleq": { "case1": { "a": [ 1, 5, 3 ], "b": [ 4, 2, 3 ], "diff": [ 3, -3, 0 ], "pred": [ 0, 1, 1 ], "routed": [ 0, -3, 0 ], "aggregate": -3, "n_selected": 2 } }, "goldilocks": { "p": "18446744069414584321", "add": { "a": "18446744069414584320", "b": "2", "out": "1" }, "mul": { "a": "9223372034707292163", "b": "5", "out": "9223372034707292173" }, "reduce": { "in": [ 1, 2, 3, 4, 5, 6, 7, 8 ], "out": "36" }, "scan": { "in": [ 1, 2, 3, 4 ], "out": [ "1", "3", "6", "10" ] }, "tree": { "in": [ 1, 2, 3, 4, 5, 6, 7, 8 ], "out": "36", "depth": 3 }, "poly": { "coeffs": [ 1, 2, 3 ], "x": 5, "out": "86" }, "seq_depth": { "n": 8, "depth": 7 } }, "gsafe_tinyapl": { "modulus": 65537, "reduce": { "in": [ 1, 2, 3, 4 ], "out": 10 }, "r7": { "a": [ 1, 2, 3 ], "b": [ 4, 1, 8 ], "aggregate": 65536 } }}12345678910111213141516171819202122β LEGACY experiment, not the production runtime. Production arithmetic is j/biencoder.ijs and r/biencoder.R.β TinyAPL Complex Double cannot hold Goldilocks p = 18446744069414584321.β Mini SUBLEQ bi-encoder. NOT softmax attention. NOT a trained model.β Query tower: Q β A +/βΓ Wq. Key tower: K β (βB) +/βΓ Wk.β Late interaction calls library SubleqPipeline on each (Q row, K row):β diff β KβQ, pred β diffβ€0, then predicted dot β +/ predΓQΓK.β Unmasked head is Q +/βΓ βK. With the fixed permutation weightsβ (Wq +/βΓ βWk = I) that head equals A +/βΓ B. The routed head is aβ sparse approximation; compare it to the reference matmul and record error.β Full Goldilocks p is not an exact TinyAPL scalar. This file uses ordinaryβ small integers plus GSafeP=65537 on the routed sum. Python is authoritativeβ for p = 2^64β2^32+1.LcgStepβ{2147483647|48271Γβ΅}LcgDrawβ{nββΊβseedβ0ββ΅βmodβ1ββ΅βbufββ¨β©βiβ0β{seedβ©LcgStep seedβbufβ©bufβͺmod|seedβiβ©i+1β0}β£{iβ₯n}0ββ¨bufβseedβ©}RoutedDotβ{stββΊ SubleqPipeline β΅βpredββ2βstβ+/(predΓβΊΓβ΅)}RouteAggβ{0ββΊ SubleqPipeline β΅}RoutePredβ{stββΊ SubleqPipeline β΅ββ2βst}PredictRowsβ{qqβββΊβkkβββ΅ββ{qββ΅β{q RoutedDot β΅}Β¨kk}Β¨qq}AggRowsβ{qqβββΊβkkβββ΅ββ{qββ΅β{q RouteAgg β΅}Β¨kk}Β¨qq}PredFlatβ{qqβββΊβkkβββ΅ββ{qββ΅ββ{q RoutePred β΅}Β¨kk}Β¨qq}GSafeRoutedDotβ{stββΊ SubleqPipeline β΅βpredββ2βstβGSafeReduce predΓβΊΓβ΅}GSafePredictβ{qqβββΊβkkβββ΅ββ{qββ΅β{q GSafeRoutedDot β΅}Β¨kk}Β¨qq}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758β LEGACY TinyAPL demo. Not parsed by scripts/run_biencoder.py anymore.β Runnable demo. Seeded LCG, fixed permutation weights, SUBLEQ route.β Prints flat row-major tensors. Python scripts/run_biencoder.py parses this.ββ"BIENCODER_V1"seedβ20261002radixβ5mβ4kβ4nβ4ββ"M"βββmββ"K"βββkββ"N"βββnββ"SEED"βββseedabβ(mΓk)LcgDrawβ¨seedβradixβ©avββ0βabseed2β1βabbbβ(kΓn)LcgDrawβ¨seed2βradixβ©bvββ0βbbaβ(β¨mβkβ©)β΄avbβ(β¨kβnβ©)β΄bvwqβ4βΏ4β΄β¨0β1β0β0β0β0β1β0β0β0β0β1β1β0β0β0β©wkβwqqsβa+/βΓwqksβ(βb)+/βΓwkprβqs PredictRows ksexβqs+/βΓβksrefβa+/βΓbagβqs AggRows kspdβqs PredFlat ksgpβqs GSafePredict kserrββ/β|pr-refmatchββ§/βex=refββ"A"ββββaββ"B"ββββbββ"PREDICTED"ββββprββ"EXACT_HEAD"ββββexββ"REFERENCE"ββββrefββ"AGGREGATES"ββββagββ"PREDICATES"βββpdββ"GSAFE_PREDICTED"ββββgpββ"MAX_ABS_ERROR"βββerrββ"EXACT_HEAD_MATCH"βββmatchββ"NOT_SOFTMAX"ββ112345678910β Auto-synced excerpt from library.apl β execute via demo_run.apl / pipeline flatten
β Sovereign Reduction Algebra β TinyAPL primitivesβ File-mode note: Capitals name functions; locals must be lowercase.β Goldilocks: full p via Python reference. TinyAPL uses exact GSafeP=2^26-1.β Legacy crypto stub. Production SHA-512 DAG seal is j/sha512.ijs and r/sha512.R.CanonicalizeββCommitStubβCanonicalizeSealStubβCanonicalizeVerifyStubβ{1}.gitattributes+2
.gitignoreAdded+6
LICENSEAdded+235
README.mdAdded+17
astra/agents.aplAdded+110
astra/bench.aplAdded+98
astra/dagseal.aplAdded+198
astra/orchestrate.aplAdded+67
astra/routing.aplAdded+128
astra/run.aplAdded+120
astra/zint.aplAdded+462
docs/ARCHITECTURE.mdAdded+86
docs/ASTRA.mdAdded+33
docs/BENCHMARKS.mdAdded+52
docs/SEAL.mdAdded+66
docs/SPEC.mdAdded+91
docs/demo-transcript.txtAdded+129
docs/images/architecture.svgAdded
docs/images/demo-transcript.pngAdded

Large File Pointer Details
- SHA256: 25d4103bf7501d5db864bf5e04222ad4eac2e6a5e808e44cf3ef8f2fd901b8cf
- Pointer size: 131 Bytes
- Size of remote file: 203 kB
docs/result_schema.jsonAdded+31
j/bench.ijsAdded+100
j/biencoder.ijsAdded+264
j/sha512.ijsAdded+271
j/train_step.ijsAdded+210
r/bench.RAdded+116
r/biencoder.RAdded+287
r/sha512.RAdded+389
r/train_step.RAdded+249
reference/__init__.pyAdded
reference/biencoder.pyAdded+15
reference/goldilocks.pyAdded+154
reference/reduction_algebra.pyAdded+411
results/benchmarks.jsonAdded+103
results/biencoder_result.jsonAdded+1610
results/pipeline_result.jsonAdded+274
results/train_step_result.jsonAdded+1003
scripts/run_astra.shAdded+12
scripts/run_astra_bench.shAdded+9
scripts/run_benchmarks.pyAdded+304
scripts/run_biencoder.pyAdded+417
scripts/run_pipeline.pyAdded+320
scripts/run_tinyapl_demo.shAdded+4
scripts/run_train_step.pyAdded+392
tests/test_biencoder.pyAdded+106
tests/test_correctness.pyAdded+19
tests/test_train_step.pyAdded+101
tests/vectors/deterministic.jsonAdded+215
tinyapl/biencoder.aplAdded+22
tinyapl/biencoder_demo.aplAdded+58
tinyapl/crypto_stub.aplAdded+10